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