The best way to control Claude Code, Codex and more from any computer or phone

main
ts 93 lines 3.75 KB
Raw
1 import { parseGoalCommand } from "@t3tools/contracts";
2 import * as Effect from "effect/Effect";
3 import * as JsonSchema from "effect/JsonSchema";
4 import * as Result from "effect/Result";
5 import * as Schema from "effect/Schema";
6 import * as SchemaRepresentation from "effect/SchemaRepresentation";
7
8 type OutputSchema = Readonly<Record<string, Schema.Json>>;
9
10 // A schema built from JSON Schema needs no services, which its `Schema.Top` type cannot say.
11 const compile = (schema: OutputSchema) =>
12 Result.try(
13 () =>
14 SchemaRepresentation.fromJsonSchemaDocument(
15 JsonSchema.fromSchemaDraft2020_12(schema),
16 ) as Schema.Codec<unknown>,
17 );
18
19 // The schema travels with the run to every client, and into the prompt of every turn that owes it.
20 const MAX_SCHEMA_CHARS = 32_000;
21
22 /** Why a declared output schema cannot be used, or null when it can. */
23 const outputSchemaProblem = (schema: OutputSchema): string | null =>
24 JSON.stringify(schema).length > MAX_SCHEMA_CHARS
25 ? `The output schema is larger than ${MAX_SCHEMA_CHARS} characters.`
26 : Result.isFailure(compile(schema))
27 ? "The output schema is not a usable JSON Schema."
28 : null;
29
30 /** Whether a message is a command its provider runs itself, which takes no appended instructions. */
31 export const isProviderCommand = (message: {
32 readonly text: string;
33 readonly attachments?: ReadonlyArray<unknown> | undefined;
34 }): boolean =>
35 (message.attachments?.length ?? 0) === 0 &&
36 (["/compact", "/logout"].includes(message.text.trim().toLowerCase()) ||
37 parseGoalCommand(message) !== null);
38
39 /** Why a message cannot be asked for a result under this schema, or null when it can. */
40 export const outputRequestProblem = (
41 schema: OutputSchema,
42 message: { readonly text: string; readonly attachments?: ReadonlyArray<unknown> | undefined },
43 ): string | null =>
44 isProviderCommand(message)
45 ? "A command cannot be asked for a result. Ask for it in a message."
46 : outputSchemaProblem(schema);
47
48 /** Appended to the turn's prompt: the agent learns the shape and how to hand the result back. */
49 export const outputInstructions = (schema: OutputSchema): string =>
50 [
51 "A program reads the result of this turn, not a person.",
52 "When the work is done, call the `t3_submit_output` tool once with `json` set to JSON text matching this JSON Schema:",
53 JSON.stringify(schema),
54 "If you could not finish, still submit, with the fields that say so. A rejected submission names what did not fit: correct it and submit again.",
55 ].join("\n");
56
57 /** Why a submission was turned down. What did not fit is in `cause`, never in the problem. */
58 export interface OutputRejection {
59 readonly problem: string;
60 readonly cause?: unknown;
61 }
62
63 /**
64 * Checks what an agent submitted against the schema its run declared. The value is kept as
65 * submitted. A schema that closes its object turns down keys it does not name; an open one keeps
66 * them.
67 */
68 export const checkOutput = Effect.fn("runOutput.checkOutput")(function* (
69 schema: OutputSchema,
70 json: string,
71 ) {
72 const parsed = Result.try(() => JSON.parse(json) as Schema.Json);
73 if (Result.isFailure(parsed)) {
74 return Result.fail<OutputRejection>({ problem: "`json` is not valid JSON text." });
75 }
76 const compiled = compile(schema);
77 if (Result.isFailure(compiled)) {
78 return Result.fail<OutputRejection>({
79 problem: "The output schema is not a usable JSON Schema.",
80 });
81 }
82 const outputSchema = compiled.success;
83 const decoded = yield* Schema.decodeEffect(outputSchema)(parsed.success, {
84 errors: "all",
85 onExcessProperty: "error",
86 }).pipe(Effect.result);
87 return Result.isFailure(decoded)
88 ? Result.fail<OutputRejection>({
89 problem: "The result does not match the schema.",
90 cause: decoded.failure,
91 })
92 : Result.succeed(parsed.success);
93 });