@buildanagent/sdk 0.1.0-alpha.1 → 0.1.0-alpha.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +424 -5
- package/dist/budget.d.ts +33 -0
- package/dist/budget.js +55 -0
- package/dist/budget.js.map +1 -0
- package/dist/compose.d.ts +26 -0
- package/dist/compose.js +157 -0
- package/dist/compose.js.map +1 -0
- package/dist/errors.d.ts +49 -0
- package/dist/errors.js +57 -0
- package/dist/errors.js.map +1 -0
- package/dist/events.d.ts +168 -0
- package/dist/events.js +32 -0
- package/dist/events.js.map +1 -0
- package/dist/freeze.d.ts +11 -0
- package/dist/freeze.js +42 -0
- package/dist/freeze.js.map +1 -0
- package/dist/hook-checks.d.ts +31 -0
- package/dist/hook-checks.js +130 -0
- package/dist/hook-checks.js.map +1 -0
- package/dist/hook-runner.d.ts +96 -0
- package/dist/hook-runner.js +372 -0
- package/dist/hook-runner.js.map +1 -0
- package/dist/hooks.d.ts +183 -0
- package/dist/hooks.js +2 -0
- package/dist/hooks.js.map +1 -0
- package/dist/index.d.ts +26 -3
- package/dist/index.js +21 -3
- package/dist/index.js.map +1 -1
- package/dist/loop.d.ts +67 -0
- package/dist/loop.js +644 -0
- package/dist/loop.js.map +1 -0
- package/dist/observers.d.ts +31 -0
- package/dist/observers.js +98 -0
- package/dist/observers.js.map +1 -0
- package/dist/otel/attributes.d.ts +43 -0
- package/dist/otel/attributes.js +50 -0
- package/dist/otel/attributes.js.map +1 -0
- package/dist/otel/content.d.ts +17 -0
- package/dist/otel/content.js +48 -0
- package/dist/otel/content.js.map +1 -0
- package/dist/otel/index.d.ts +6 -2
- package/dist/otel/index.js +6 -2
- package/dist/otel/index.js.map +1 -1
- package/dist/otel/observer.d.ts +82 -0
- package/dist/otel/observer.js +300 -0
- package/dist/otel/observer.js.map +1 -0
- package/dist/pauses.d.ts +61 -0
- package/dist/pauses.js +83 -0
- package/dist/pauses.js.map +1 -0
- package/dist/progress.d.ts +34 -0
- package/dist/progress.js +139 -0
- package/dist/progress.js.map +1 -0
- package/dist/result.d.ts +134 -0
- package/dist/result.js +2 -0
- package/dist/result.js.map +1 -0
- package/dist/resume.d.ts +76 -0
- package/dist/resume.js +237 -0
- package/dist/resume.js.map +1 -0
- package/dist/run.d.ts +214 -0
- package/dist/run.js +327 -0
- package/dist/run.js.map +1 -0
- package/dist/steering.d.ts +52 -0
- package/dist/steering.js +104 -0
- package/dist/steering.js.map +1 -0
- package/dist/testing/scripted-model.d.ts +12 -2
- package/dist/testing/scripted-model.js +19 -2
- package/dist/testing/scripted-model.js.map +1 -1
- package/dist/tools/coerce.d.ts +15 -0
- package/dist/tools/coerce.js +93 -0
- package/dist/tools/coerce.js.map +1 -0
- package/dist/tools/define.d.ts +54 -0
- package/dist/tools/define.js +121 -0
- package/dist/tools/define.js.map +1 -0
- package/dist/tools/format-error.d.ts +13 -0
- package/dist/tools/format-error.js +66 -0
- package/dist/tools/format-error.js.map +1 -0
- package/dist/tools/outcome.d.ts +7 -0
- package/dist/tools/outcome.js +30 -0
- package/dist/tools/outcome.js.map +1 -0
- package/dist/tools/pipeline.d.ts +111 -0
- package/dist/tools/pipeline.js +382 -0
- package/dist/tools/pipeline.js.map +1 -0
- package/dist/tools/scheduler.d.ts +33 -0
- package/dist/tools/scheduler.js +51 -0
- package/dist/tools/scheduler.js.map +1 -0
- package/dist/tools/schema.d.ts +20 -0
- package/dist/tools/schema.js +100 -0
- package/dist/tools/schema.js.map +1 -0
- package/dist/tools/types.d.ts +196 -0
- package/dist/tools/types.js +2 -0
- package/dist/tools/types.js.map +1 -0
- package/dist/vendor/agent-safety/bytes.d.ts +17 -0
- package/dist/vendor/agent-safety/bytes.js +59 -0
- package/dist/vendor/agent-safety/bytes.js.map +1 -0
- package/dist/vendor/agent-safety/errors.d.ts +23 -0
- package/dist/vendor/agent-safety/errors.js +22 -0
- package/dist/vendor/agent-safety/errors.js.map +1 -0
- package/dist/vendor/agent-safety/hash.d.ts +16 -0
- package/dist/vendor/agent-safety/hash.js +110 -0
- package/dist/vendor/agent-safety/hash.js.map +1 -0
- package/dist/vendor/agent-safety/outcome.d.ts +88 -0
- package/dist/vendor/agent-safety/outcome.js +140 -0
- package/dist/vendor/agent-safety/outcome.js.map +1 -0
- package/dist/vendor/agent-safety/pending.d.ts +119 -0
- package/dist/vendor/agent-safety/pending.js +122 -0
- package/dist/vendor/agent-safety/pending.js.map +1 -0
- package/dist/vendor/agent-safety/render.d.ts +40 -0
- package/dist/vendor/agent-safety/render.js +92 -0
- package/dist/vendor/agent-safety/render.js.map +1 -0
- package/dist/vendor/agent-safety/signer.d.ts +42 -0
- package/dist/vendor/agent-safety/signer.js +128 -0
- package/dist/vendor/agent-safety/signer.js.map +1 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +8 -0
- package/dist/version.js.map +1 -0
- package/package.json +13 -3
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Schema handling: turns a tool's `inputSchema` into the JSON Schema the model is sent and a validator the pipeline
|
|
3
|
+
* runs. A Standard Schema validates itself and describes itself as JSON Schema; a raw JSON Schema is compiled once
|
|
4
|
+
* with pi-schema, drafts 2020-12 and 7, with format checks on (D7).
|
|
5
|
+
*/
|
|
6
|
+
import { compile } from "@earendil-works/pi-schema";
|
|
7
|
+
import { formats } from "@earendil-works/pi-schema/formats";
|
|
8
|
+
import { SdkError } from "../errors.js";
|
|
9
|
+
const DRAFT_7 = /^https?:\/\/json-schema\.org\/draft-07\/schema#?$/;
|
|
10
|
+
const DRAFT_2020_12 = /^https?:\/\/json-schema\.org\/draft\/2020-12\/schema#?$/;
|
|
11
|
+
function isStandardSchema(schema) {
|
|
12
|
+
return "~standard" in schema;
|
|
13
|
+
}
|
|
14
|
+
// An ArkType schema is a callable function that carries `~standard`, so a function counts when it has that property.
|
|
15
|
+
function isSchemaShaped(schema) {
|
|
16
|
+
if (typeof schema === "object")
|
|
17
|
+
return schema !== null;
|
|
18
|
+
return typeof schema === "function" && "~standard" in schema;
|
|
19
|
+
}
|
|
20
|
+
function invalid(tool, message, cause) {
|
|
21
|
+
return new SdkError("invalid_tool_definition", `tool "${tool}": ${message}`, cause === undefined ? {} : { cause });
|
|
22
|
+
}
|
|
23
|
+
function draftOf(tool, schema) {
|
|
24
|
+
const declared = schema.$schema;
|
|
25
|
+
if (declared === undefined || (typeof declared === "string" && DRAFT_2020_12.test(declared)))
|
|
26
|
+
return "2020-12";
|
|
27
|
+
if (typeof declared === "string" && DRAFT_7.test(declared))
|
|
28
|
+
return "7";
|
|
29
|
+
throw invalid(tool, `$schema ${JSON.stringify(declared)} is not draft 2020-12 or draft 7`);
|
|
30
|
+
}
|
|
31
|
+
function prepareJsonSchema(tool, schema) {
|
|
32
|
+
let validator;
|
|
33
|
+
try {
|
|
34
|
+
validator = compile(schema, { draft: draftOf(tool, schema), formats });
|
|
35
|
+
}
|
|
36
|
+
catch (cause) {
|
|
37
|
+
if (cause instanceof SdkError)
|
|
38
|
+
throw cause;
|
|
39
|
+
throw invalid(tool, "its input schema does not compile", cause);
|
|
40
|
+
}
|
|
41
|
+
return {
|
|
42
|
+
jsonSchema: schema,
|
|
43
|
+
async validate(value) {
|
|
44
|
+
if (validator.check(value))
|
|
45
|
+
return { ok: true, value };
|
|
46
|
+
const issues = validator.errors(value).map(({ path, keyword, message }) => ({ path, keyword, message }));
|
|
47
|
+
return { ok: false, issues };
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
// RFC 6901: "~" and "/" in a key are escaped as "~0" and "~1".
|
|
52
|
+
function pointer(path) {
|
|
53
|
+
return (path ?? [])
|
|
54
|
+
.map((segment) => {
|
|
55
|
+
const key = typeof segment === "object" ? segment.key : segment;
|
|
56
|
+
const text = typeof key === "symbol" ? (key.description ?? "") : String(key);
|
|
57
|
+
return `/${text.replaceAll("~", "~0").replaceAll("/", "~1")}`;
|
|
58
|
+
})
|
|
59
|
+
.join("");
|
|
60
|
+
}
|
|
61
|
+
function prepareStandardSchema(tool, schema) {
|
|
62
|
+
let jsonSchema;
|
|
63
|
+
try {
|
|
64
|
+
jsonSchema = schema["~standard"].jsonSchema.input({ target: "draft-2020-12" });
|
|
65
|
+
}
|
|
66
|
+
catch (cause) {
|
|
67
|
+
throw invalid(tool, "its Standard Schema cannot describe its input as draft 2020-12 JSON Schema", cause);
|
|
68
|
+
}
|
|
69
|
+
return {
|
|
70
|
+
jsonSchema,
|
|
71
|
+
async validate(value) {
|
|
72
|
+
let result;
|
|
73
|
+
try {
|
|
74
|
+
result = await schema["~standard"].validate(value);
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
// A validator that throws is the schema library's failure, not the model's, but the model still needs an
|
|
78
|
+
// error result, so the throw becomes one issue at the root.
|
|
79
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
80
|
+
return { ok: false, issues: [{ path: "", message: `the schema's validator threw: ${message}` }] };
|
|
81
|
+
}
|
|
82
|
+
if (result.issues === undefined)
|
|
83
|
+
return { ok: true, value: result.value };
|
|
84
|
+
return {
|
|
85
|
+
ok: false,
|
|
86
|
+
issues: result.issues.map((issue) => ({ path: pointer(issue.path), message: issue.message })),
|
|
87
|
+
};
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Prepares a tool's input schema. Throws an `SdkError`, code `invalid_tool_definition`, when a raw schema does not
|
|
93
|
+
* compile or names a draft other than 2020-12 or 7, or when a Standard Schema cannot produce JSON Schema.
|
|
94
|
+
*/
|
|
95
|
+
export function prepareSchema(tool, schema) {
|
|
96
|
+
if (!isSchemaShaped(schema))
|
|
97
|
+
throw invalid(tool, "inputSchema must be a JSON Schema object or a Standard Schema");
|
|
98
|
+
return isStandardSchema(schema) ? prepareStandardSchema(tool, schema) : prepareJsonSchema(tool, schema);
|
|
99
|
+
}
|
|
100
|
+
//# sourceMappingURL=schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC;YAC1E,OAAO;gBACL,EAAE,EAAE,KAAK;gBACT,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;aAC9F,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,IAAY,EAAE,MAA2B;IACrE,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC;QAAE,MAAM,OAAO,CAAC,IAAI,EAAE,+DAA+D,CAAC,CAAC;IAClH,OAAO,gBAAgB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,qBAAqB,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,iBAAiB,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAC1G,CAAC","sourcesContent":["/**\n * Schema handling: turns a tool's `inputSchema` into the JSON Schema the model is sent and a validator the pipeline\n * runs. A Standard Schema validates itself and describes itself as JSON Schema; a raw JSON Schema is compiled once\n * with pi-schema, drafts 2020-12 and 7, with format checks on (D7).\n */\nimport { compile, type Validator } from \"@earendil-works/pi-schema\";\nimport { formats } from \"@earendil-works/pi-schema/formats\";\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { SdkError } from \"../errors.js\";\nimport type { JsonSchema, SchemaIssue, ToolSchema } from \"./types.js\";\n\n/** The outcome of validating one input: the value `execute` receives, or the issues. */\nexport type Validation =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly issues: readonly SchemaIssue[] };\n\n/** A tool's schema, ready for the pipeline. */\nexport interface PreparedSchema {\n /** The JSON Schema the model is sent, and the one coercion reads. */\n readonly jsonSchema: JsonSchema;\n validate(value: unknown): Promise<Validation>;\n}\n\ntype StandardToolSchema = StandardSchemaV1<unknown, unknown> & StandardJSONSchemaV1<unknown, unknown>;\n\nconst DRAFT_7 = /^https?:\\/\\/json-schema\\.org\\/draft-07\\/schema#?$/;\nconst DRAFT_2020_12 = /^https?:\\/\\/json-schema\\.org\\/draft\\/2020-12\\/schema#?$/;\n\nfunction isStandardSchema(schema: ToolSchema<unknown>): schema is StandardToolSchema {\n return \"~standard\" in schema;\n}\n\n// An ArkType schema is a callable function that carries `~standard`, so a function counts when it has that property.\nfunction isSchemaShaped(schema: unknown): schema is ToolSchema<unknown> {\n if (typeof schema === \"object\") return schema !== null;\n return typeof schema === \"function\" && \"~standard\" in schema;\n}\n\nfunction invalid(tool: string, message: string, cause?: unknown): SdkError {\n return new SdkError(\"invalid_tool_definition\", `tool \"${tool}\": ${message}`, cause === undefined ? {} : { cause });\n}\n\nfunction draftOf(tool: string, schema: JsonSchema): \"7\" | \"2020-12\" {\n const declared = schema.$schema;\n if (declared === undefined || (typeof declared === \"string\" && DRAFT_2020_12.test(declared))) return \"2020-12\";\n if (typeof declared === \"string\" && DRAFT_7.test(declared)) return \"7\";\n throw invalid(tool, `$schema ${JSON.stringify(declared)} is not draft 2020-12 or draft 7`);\n}\n\nfunction prepareJsonSchema(tool: string, schema: JsonSchema): PreparedSchema {\n let validator: Validator<unknown>;\n try {\n validator = compile(schema, { draft: draftOf(tool, schema), formats });\n } catch (cause) {\n if (cause instanceof SdkError) throw cause;\n throw invalid(tool, \"its input schema does not compile\", cause);\n }\n return {\n jsonSchema: schema,\n async validate(value) {\n if (validator.check(value)) return { ok: true, value };\n const issues = validator.errors(value).map(({ path, keyword, message }) => ({ path, keyword, message }));\n return { ok: false, issues };\n },\n };\n}\n\n// RFC 6901: \"~\" and \"/\" in a key are escaped as \"~0\" and \"~1\".\nfunction pointer(path: StandardSchemaV1.Issue[\"path\"]): string {\n return (path ?? [])\n .map((segment) => {\n const key = typeof segment === \"object\" ? segment.key : segment;\n const text = typeof key === \"symbol\" ? (key.description ?? \"\") : String(key);\n return `/${text.replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\")}`;\n })\n .join(\"\");\n}\n\nfunction prepareStandardSchema(tool: string, schema: StandardToolSchema): PreparedSchema {\n let jsonSchema: JsonSchema;\n try {\n jsonSchema = schema[\"~standard\"].jsonSchema.input({ target: \"draft-2020-12\" });\n } catch (cause) {\n throw invalid(tool, \"its Standard Schema cannot describe its input as draft 2020-12 JSON Schema\", cause);\n }\n return {\n jsonSchema,\n async validate(value) {\n let result: StandardSchemaV1.Result<unknown>;\n try {\n result = await schema[\"~standard\"].validate(value);\n } catch (error) {\n // A validator that throws is the schema library's failure, not the model's, but the model still needs an\n // error result, so the throw becomes one issue at the root.\n const message = error instanceof Error ? error.message : String(error);\n return { ok: false, issues: [{ path: \"\", message: `the schema's validator threw: ${message}` }] };\n }\n if (result.issues === undefined) return { ok: true, value: result.value };\n return {\n ok: false,\n issues: result.issues.map((issue) => ({ path: pointer(issue.path), message: issue.message })),\n };\n },\n };\n}\n\n/**\n * Prepares a tool's input schema. Throws an `SdkError`, code `invalid_tool_definition`, when a raw schema does not\n * compile or names a draft other than 2020-12 or 7, or when a Standard Schema cannot produce JSON Schema.\n */\nexport function prepareSchema(tool: string, schema: ToolSchema<unknown>): PreparedSchema {\n if (!isSchemaShaped(schema)) throw invalid(tool, \"inputSchema must be a JSON Schema object or a Standard Schema\");\n return isStandardSchema(schema) ? prepareStandardSchema(tool, schema) : prepareJsonSchema(tool, schema);\n}\n"]}
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The tool types: what a tool declares, what its `execute` receives and returns, and the failures the pipeline
|
|
3
|
+
* reports to the model (SDK plan §3.3; agent-SDK guide §4).
|
|
4
|
+
*/
|
|
5
|
+
import type { ContentBlock, ModelContent } from "@buildanagent/gateway";
|
|
6
|
+
import type { StandardJSONSchemaV1, StandardSchemaV1 } from "@standard-schema/spec";
|
|
7
|
+
import type { Clock } from "../testing/determinism.js";
|
|
8
|
+
import type { WriteOutcome } from "../vendor/agent-safety/outcome.js";
|
|
9
|
+
/** A JSON Schema object, draft 2020-12 or draft 7, such as `{ type: "object", properties: { … } }`. */
|
|
10
|
+
export type JsonSchema = Readonly<Record<string, unknown>>;
|
|
11
|
+
/**
|
|
12
|
+
* A tool's input schema: a Standard Schema that can also describe itself as JSON Schema (Zod 4.2 or later, ArkType,
|
|
13
|
+
* or Valibot through `toStandardJsonSchema()` from `@valibot/to-json-schema`), or a raw JSON Schema object. A raw schema whose `$schema` names draft 7 is checked as draft 7, and
|
|
14
|
+
* any other as draft 2020-12.
|
|
15
|
+
*/
|
|
16
|
+
export type ToolSchema<I> = (StandardSchemaV1<unknown, I> & StandardJSONSchemaV1<unknown, I>) | JsonSchema;
|
|
17
|
+
/**
|
|
18
|
+
* One reason a tool input failed its schema. `path` is a JSON Pointer, such as `/items/0/sku`, or `""` for the whole
|
|
19
|
+
* input.
|
|
20
|
+
*/
|
|
21
|
+
export interface SchemaIssue {
|
|
22
|
+
readonly path: string;
|
|
23
|
+
readonly message: string;
|
|
24
|
+
/** The JSON Schema keyword that failed, such as `required`, when the validator reports one. */
|
|
25
|
+
readonly keyword?: string;
|
|
26
|
+
}
|
|
27
|
+
/** The fields every tool failure carries. `input` is the arguments the model sent. */
|
|
28
|
+
interface FailureBase {
|
|
29
|
+
readonly tool: string;
|
|
30
|
+
readonly callId: string;
|
|
31
|
+
readonly input: unknown;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* A failed tool call, as the error formatter receives it. `unknown_tool`: the model named a tool that doesn't exist.
|
|
35
|
+
* `invalid_input`: the arguments failed the schema, even after repair. `execution_error`: `execute` threw; with
|
|
36
|
+
* `redactErrors`, `message` is a fixed line and the thrown message is only in the result's `details`. `truncated`:
|
|
37
|
+
* the response was cut off at the output limit, so the call was not run. `not_run`: the call was not run because the
|
|
38
|
+
* response ended in an error (`response_error`) or was aborted (`response_aborted`), or the run was cancelled before
|
|
39
|
+
* the call started (`run_aborted`), or a sibling call in the same step threw a programmer error (`sibling_failed`).
|
|
40
|
+
*/
|
|
41
|
+
export type ToolFailure = (FailureBase & {
|
|
42
|
+
readonly kind: "unknown_tool";
|
|
43
|
+
readonly availableTools: readonly string[];
|
|
44
|
+
}) | (FailureBase & {
|
|
45
|
+
readonly kind: "invalid_input";
|
|
46
|
+
readonly issues: readonly SchemaIssue[];
|
|
47
|
+
}) | (FailureBase & {
|
|
48
|
+
readonly kind: "execution_error";
|
|
49
|
+
readonly message: string;
|
|
50
|
+
readonly redacted: boolean;
|
|
51
|
+
}) | (FailureBase & {
|
|
52
|
+
readonly kind: "truncated";
|
|
53
|
+
}) | (FailureBase & {
|
|
54
|
+
readonly kind: "not_run";
|
|
55
|
+
readonly reason: "response_error" | "response_aborted" | "run_aborted" | "sibling_failed";
|
|
56
|
+
});
|
|
57
|
+
/**
|
|
58
|
+
* Declares that a tool changes the world, such as sending an email. A tool without `effect` counts as read-only, so
|
|
59
|
+
* a run that crashes mid-call may safely run it again. `businessKey` names the real-world operation, such as
|
|
60
|
+
* `refund:<order id>`, so the same write is recognised across retries and sessions.
|
|
61
|
+
*/
|
|
62
|
+
export interface ToolEffect<I> {
|
|
63
|
+
readonly kind: "write";
|
|
64
|
+
businessKey?(input: I): string;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* What a tool says about itself, using the names of the Model Context Protocol's tool annotations. A hint comes from
|
|
68
|
+
* whoever wrote the tool, so the scheduler trusts it only for a tool marked `firstParty`.
|
|
69
|
+
*/
|
|
70
|
+
export interface ToolAnnotations {
|
|
71
|
+
/**
|
|
72
|
+
* The tool changes nothing. With `firstParty`, its calls that share a `resourceKey` run together, unless the tool
|
|
73
|
+
* also declares an `effect`, which wins.
|
|
74
|
+
*/
|
|
75
|
+
readonly readOnlyHint?: boolean;
|
|
76
|
+
}
|
|
77
|
+
/** How a tool's calls are scheduled within one step: `parallel` (the default) or `sequential`. */
|
|
78
|
+
export type ToolExecutionMode = "parallel" | "sequential";
|
|
79
|
+
/** Whether a tool is sent to the model: `direct`, `deferred` or `hidden`. */
|
|
80
|
+
export type ToolExposure = "direct" | "deferred" | "hidden";
|
|
81
|
+
/** What a tool's `execute` receives besides its input. */
|
|
82
|
+
export interface ToolContext {
|
|
83
|
+
readonly runId: string;
|
|
84
|
+
readonly callId: string;
|
|
85
|
+
/**
|
|
86
|
+
* Fires when the run is aborted, and when a sibling call in the same step throws a programmer error, because the
|
|
87
|
+
* step is then abandoned. A sibling's error result, which the model reads and answers, never fires it.
|
|
88
|
+
*/
|
|
89
|
+
readonly signal: AbortSignal;
|
|
90
|
+
/** How deeply this run is nested inside other agents' tool calls; 0 for a top-level run. */
|
|
91
|
+
readonly depth: number;
|
|
92
|
+
/** The deepest nesting allowed; a tool that starts another agent refuses at this depth. */
|
|
93
|
+
readonly maxDepth: number;
|
|
94
|
+
readonly clock: Clock;
|
|
95
|
+
/** Reports progress for a user interface, such as rows processed so far. The model never sees it. */
|
|
96
|
+
update(details: unknown): void;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* What a tool returns. `content` is what the model reads, `details` is for logs and user interfaces, and
|
|
100
|
+
* `structured` is typed data for your code; only `content` reaches the model. `isError` marks a failure for the model.
|
|
101
|
+
* `terminate` asks the run to end after this step. `pause` asks the user a question: the call then waits for the
|
|
102
|
+
* answer, which reaches the model as its result. `outcome` reports what a write did: any kind except `applied` sets
|
|
103
|
+
* `isError`, and the model reads the outcome's sentence and fields before `content`.
|
|
104
|
+
*/
|
|
105
|
+
export interface ToolResult<S = unknown> {
|
|
106
|
+
readonly content: readonly ModelContent[];
|
|
107
|
+
readonly details?: unknown;
|
|
108
|
+
readonly structured?: S;
|
|
109
|
+
readonly isError?: boolean;
|
|
110
|
+
readonly terminate?: boolean;
|
|
111
|
+
readonly pause?: {
|
|
112
|
+
readonly kind: "clarification";
|
|
113
|
+
readonly question: string;
|
|
114
|
+
};
|
|
115
|
+
readonly outcome?: WriteOutcome;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* A tool the model can call. `I` is the input `execute` receives after validation, and `S` the type of `structured`.
|
|
119
|
+
*
|
|
120
|
+
* Every call runs the same steps: the name is resolved, the input is coerced and validated, `repair` gets one chance
|
|
121
|
+
* to fix invalid input, then `execute` runs. A failure the model caused, such as an unknown tool, invalid input or
|
|
122
|
+
* a throwing `execute`, returns an error result to the model. A result that isn't a list of text and image blocks,
|
|
123
|
+
* or that carries an invalid write outcome, throws an `SdkError` with code `invalid_tool_result`.
|
|
124
|
+
*/
|
|
125
|
+
export interface ToolDefinition<I = unknown, S = unknown> {
|
|
126
|
+
/** 1 to 64 characters from `A-Z`, `a-z`, `0-9`, `_` and `-`. */
|
|
127
|
+
readonly name: string;
|
|
128
|
+
readonly description: string;
|
|
129
|
+
/**
|
|
130
|
+
* `function` (the default) runs in your process. The other kinds are for tools that a provider defines or runs:
|
|
131
|
+
* `dynamic` tools have a schema known only at run time, such as one from an MCP server.
|
|
132
|
+
*/
|
|
133
|
+
readonly kind?: "function" | "dynamic" | "provider-local" | "provider-executed";
|
|
134
|
+
readonly inputSchema: ToolSchema<I>;
|
|
135
|
+
/**
|
|
136
|
+
* Whether the model is sent this tool. `direct` (the default) sends it with every model call. A `deferred` or
|
|
137
|
+
* `hidden` tool is left out of every request unless a `beforeModelCall` interceptor names it in `activeTools`, and
|
|
138
|
+
* a call the model makes to a tool that request didn't send gets the unknown-tool error result.
|
|
139
|
+
*/
|
|
140
|
+
readonly exposure?: ToolExposure;
|
|
141
|
+
/** Marks a tool that changes the world. A tool without it counts as read-only. */
|
|
142
|
+
readonly effect?: ToolEffect<I>;
|
|
143
|
+
/**
|
|
144
|
+
* How this tool's calls are scheduled. A step's calls start together by default. A tool that sets `sequential`
|
|
145
|
+
* makes every call of its step run one at a time, in the order the model sent them, because it may depend on the
|
|
146
|
+
* calls around it.
|
|
147
|
+
*/
|
|
148
|
+
readonly executionMode?: ToolExecutionMode;
|
|
149
|
+
/**
|
|
150
|
+
* Names the resource a call touches, such as a file path. Calls in one step that return the same key never run at
|
|
151
|
+
* the same time, in any tool, and run in model order; calls with different keys run together. It must be
|
|
152
|
+
* deterministic and return a string, and it receives the validated input.
|
|
153
|
+
*/
|
|
154
|
+
resourceKey?(input: I): string;
|
|
155
|
+
/**
|
|
156
|
+
* Names what a call works on, such as a file path and a line range, so the run can tell that the model keeps
|
|
157
|
+
* retrying the same thing. By default, five calls to this tool with one key, none of them successful, end the run
|
|
158
|
+
* `no_progress`; a successful call with that key starts the count again. It receives the model's input as sent,
|
|
159
|
+
* before validation, so it must cope with any shape, and its parameter is `unknown` for that reason. A key that throws or
|
|
160
|
+
* isn't a string leaves the call unkeyed.
|
|
161
|
+
*/
|
|
162
|
+
progressKey?(input: unknown): string;
|
|
163
|
+
/** Hints about the tool, such as `readOnlyHint`. They affect scheduling only when `firstParty` is true. */
|
|
164
|
+
readonly annotations?: ToolAnnotations;
|
|
165
|
+
/**
|
|
166
|
+
* True for a tool you wrote, false (the default) for one that came from a server you don't control, such as an MCP
|
|
167
|
+
* tool. Only a first-party tool's `readOnlyHint` changes how its calls are scheduled: read-only calls that share a
|
|
168
|
+
* `resourceKey` run together, and wait only for the writers before them. A tool with an `effect` is never read-only.
|
|
169
|
+
*/
|
|
170
|
+
readonly firstParty?: boolean;
|
|
171
|
+
/**
|
|
172
|
+
* Called once when the input fails its schema, with the coerced input and the issues. Return fixed input to
|
|
173
|
+
* validate again, or `undefined` to report the failure to the model.
|
|
174
|
+
*/
|
|
175
|
+
repair?(e: {
|
|
176
|
+
readonly input: unknown;
|
|
177
|
+
readonly issues: readonly SchemaIssue[];
|
|
178
|
+
}): Promise<unknown>;
|
|
179
|
+
/**
|
|
180
|
+
* Builds the content the model reads for a failed call, in place of the default text, which lists the issues and
|
|
181
|
+
* the received arguments and tells the model not to substitute invented data. It runs synchronously; if it throws
|
|
182
|
+
* or returns anything but a list of text and image blocks, the model reads the default text instead.
|
|
183
|
+
*/
|
|
184
|
+
formatError?(failure: ToolFailure): readonly ModelContent[];
|
|
185
|
+
/**
|
|
186
|
+
* When true, an error thrown by `execute` reaches the model as a fixed line, and its message goes only to the
|
|
187
|
+
* result's `details`. Default false.
|
|
188
|
+
*/
|
|
189
|
+
readonly redactErrors?: boolean;
|
|
190
|
+
execute(input: I, ctx: ToolContext): Promise<ToolResult<S>>;
|
|
191
|
+
}
|
|
192
|
+
/** A tool call block from an assistant message. */
|
|
193
|
+
export type ToolCall = Extract<ContentBlock, {
|
|
194
|
+
type: "tool_call";
|
|
195
|
+
}>;
|
|
196
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/tools/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The tool types: what a tool declares, what its `execute` receives and returns, and the failures the pipeline\n * reports to the model (SDK plan §3.3; agent-SDK guide §4).\n */\nimport type { ContentBlock, ModelContent } from \"@buildanagent/gateway\";\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { Clock } from \"../testing/determinism.js\";\nimport type { WriteOutcome } from \"../vendor/agent-safety/outcome.js\";\n\n/** A JSON Schema object, draft 2020-12 or draft 7, such as `{ type: \"object\", properties: { … } }`. */\nexport type JsonSchema = Readonly<Record<string, unknown>>;\n\n/**\n * A tool's input schema: a Standard Schema that can also describe itself as JSON Schema (Zod 4.2 or later, ArkType,\n * or Valibot through `toStandardJsonSchema()` from `@valibot/to-json-schema`), or a raw JSON Schema object. A raw schema whose `$schema` names draft 7 is checked as draft 7, and\n * any other as draft 2020-12.\n */\nexport type ToolSchema<I> = (StandardSchemaV1<unknown, I> & StandardJSONSchemaV1<unknown, I>) | JsonSchema;\n\n/**\n * One reason a tool input failed its schema. `path` is a JSON Pointer, such as `/items/0/sku`, or `\"\"` for the whole\n * input.\n */\nexport interface SchemaIssue {\n readonly path: string;\n readonly message: string;\n /** The JSON Schema keyword that failed, such as `required`, when the validator reports one. */\n readonly keyword?: string;\n}\n\n/** The fields every tool failure carries. `input` is the arguments the model sent. */\ninterface FailureBase {\n readonly tool: string;\n readonly callId: string;\n readonly input: unknown;\n}\n\n/**\n * A failed tool call, as the error formatter receives it. `unknown_tool`: the model named a tool that doesn't exist.\n * `invalid_input`: the arguments failed the schema, even after repair. `execution_error`: `execute` threw; with\n * `redactErrors`, `message` is a fixed line and the thrown message is only in the result's `details`. `truncated`:\n * the response was cut off at the output limit, so the call was not run. `not_run`: the call was not run because the\n * response ended in an error (`response_error`) or was aborted (`response_aborted`), or the run was cancelled before\n * the call started (`run_aborted`), or a sibling call in the same step threw a programmer error (`sibling_failed`).\n */\nexport type ToolFailure =\n | (FailureBase & { readonly kind: \"unknown_tool\"; readonly availableTools: readonly string[] })\n | (FailureBase & { readonly kind: \"invalid_input\"; readonly issues: readonly SchemaIssue[] })\n | (FailureBase & { readonly kind: \"execution_error\"; readonly message: string; readonly redacted: boolean })\n | (FailureBase & { readonly kind: \"truncated\" })\n | (FailureBase & {\n readonly kind: \"not_run\";\n readonly reason: \"response_error\" | \"response_aborted\" | \"run_aborted\" | \"sibling_failed\";\n });\n\n/**\n * Declares that a tool changes the world, such as sending an email. A tool without `effect` counts as read-only, so\n * a run that crashes mid-call may safely run it again. `businessKey` names the real-world operation, such as\n * `refund:<order id>`, so the same write is recognised across retries and sessions.\n */\nexport interface ToolEffect<I> {\n readonly kind: \"write\";\n businessKey?(input: I): string;\n}\n\n/**\n * What a tool says about itself, using the names of the Model Context Protocol's tool annotations. A hint comes from\n * whoever wrote the tool, so the scheduler trusts it only for a tool marked `firstParty`.\n */\nexport interface ToolAnnotations {\n /**\n * The tool changes nothing. With `firstParty`, its calls that share a `resourceKey` run together, unless the tool\n * also declares an `effect`, which wins.\n */\n readonly readOnlyHint?: boolean;\n}\n\n/** How a tool's calls are scheduled within one step: `parallel` (the default) or `sequential`. */\nexport type ToolExecutionMode = \"parallel\" | \"sequential\";\n\n/** Whether a tool is sent to the model: `direct`, `deferred` or `hidden`. */\nexport type ToolExposure = \"direct\" | \"deferred\" | \"hidden\";\n\n/** What a tool's `execute` receives besides its input. */\nexport interface ToolContext {\n readonly runId: string;\n readonly callId: string;\n /**\n * Fires when the run is aborted, and when a sibling call in the same step throws a programmer error, because the\n * step is then abandoned. A sibling's error result, which the model reads and answers, never fires it.\n */\n readonly signal: AbortSignal;\n /** How deeply this run is nested inside other agents' tool calls; 0 for a top-level run. */\n readonly depth: number;\n /** The deepest nesting allowed; a tool that starts another agent refuses at this depth. */\n readonly maxDepth: number;\n readonly clock: Clock;\n /** Reports progress for a user interface, such as rows processed so far. The model never sees it. */\n update(details: unknown): void;\n}\n\n/**\n * What a tool returns. `content` is what the model reads, `details` is for logs and user interfaces, and\n * `structured` is typed data for your code; only `content` reaches the model. `isError` marks a failure for the model.\n * `terminate` asks the run to end after this step. `pause` asks the user a question: the call then waits for the\n * answer, which reaches the model as its result. `outcome` reports what a write did: any kind except `applied` sets\n * `isError`, and the model reads the outcome's sentence and fields before `content`.\n */\nexport interface ToolResult<S = unknown> {\n readonly content: readonly ModelContent[];\n readonly details?: unknown;\n readonly structured?: S;\n readonly isError?: boolean;\n readonly terminate?: boolean;\n readonly pause?: { readonly kind: \"clarification\"; readonly question: string };\n readonly outcome?: WriteOutcome;\n}\n\n/**\n * A tool the model can call. `I` is the input `execute` receives after validation, and `S` the type of `structured`.\n *\n * Every call runs the same steps: the name is resolved, the input is coerced and validated, `repair` gets one chance\n * to fix invalid input, then `execute` runs. A failure the model caused, such as an unknown tool, invalid input or\n * a throwing `execute`, returns an error result to the model. A result that isn't a list of text and image blocks,\n * or that carries an invalid write outcome, throws an `SdkError` with code `invalid_tool_result`.\n */\nexport interface ToolDefinition<I = unknown, S = unknown> {\n /** 1 to 64 characters from `A-Z`, `a-z`, `0-9`, `_` and `-`. */\n readonly name: string;\n readonly description: string;\n /**\n * `function` (the default) runs in your process. The other kinds are for tools that a provider defines or runs:\n * `dynamic` tools have a schema known only at run time, such as one from an MCP server.\n */\n readonly kind?: \"function\" | \"dynamic\" | \"provider-local\" | \"provider-executed\";\n readonly inputSchema: ToolSchema<I>;\n /**\n * Whether the model is sent this tool. `direct` (the default) sends it with every model call. A `deferred` or\n * `hidden` tool is left out of every request unless a `beforeModelCall` interceptor names it in `activeTools`, and\n * a call the model makes to a tool that request didn't send gets the unknown-tool error result.\n */\n readonly exposure?: ToolExposure;\n /** Marks a tool that changes the world. A tool without it counts as read-only. */\n readonly effect?: ToolEffect<I>;\n /**\n * How this tool's calls are scheduled. A step's calls start together by default. A tool that sets `sequential`\n * makes every call of its step run one at a time, in the order the model sent them, because it may depend on the\n * calls around it.\n */\n readonly executionMode?: ToolExecutionMode;\n /**\n * Names the resource a call touches, such as a file path. Calls in one step that return the same key never run at\n * the same time, in any tool, and run in model order; calls with different keys run together. It must be\n * deterministic and return a string, and it receives the validated input.\n */\n resourceKey?(input: I): string;\n /**\n * Names what a call works on, such as a file path and a line range, so the run can tell that the model keeps\n * retrying the same thing. By default, five calls to this tool with one key, none of them successful, end the run\n * `no_progress`; a successful call with that key starts the count again. It receives the model's input as sent,\n * before validation, so it must cope with any shape, and its parameter is `unknown` for that reason. A key that throws or\n * isn't a string leaves the call unkeyed.\n */\n progressKey?(input: unknown): string;\n /** Hints about the tool, such as `readOnlyHint`. They affect scheduling only when `firstParty` is true. */\n readonly annotations?: ToolAnnotations;\n /**\n * True for a tool you wrote, false (the default) for one that came from a server you don't control, such as an MCP\n * tool. Only a first-party tool's `readOnlyHint` changes how its calls are scheduled: read-only calls that share a\n * `resourceKey` run together, and wait only for the writers before them. A tool with an `effect` is never read-only.\n */\n readonly firstParty?: boolean;\n /**\n * Called once when the input fails its schema, with the coerced input and the issues. Return fixed input to\n * validate again, or `undefined` to report the failure to the model.\n */\n repair?(e: { readonly input: unknown; readonly issues: readonly SchemaIssue[] }): Promise<unknown>;\n /**\n * Builds the content the model reads for a failed call, in place of the default text, which lists the issues and\n * the received arguments and tells the model not to substitute invented data. It runs synchronously; if it throws\n * or returns anything but a list of text and image blocks, the model reads the default text instead.\n */\n formatError?(failure: ToolFailure): readonly ModelContent[];\n /**\n * When true, an error thrown by `execute` reaches the model as a fixed line, and its message goes only to the\n * result's `details`. Default false.\n */\n readonly redactErrors?: boolean;\n execute(input: I, ctx: ToolContext): Promise<ToolResult<S>>;\n}\n\n/** A tool call block from an assistant message. */\nexport type ToolCall = Extract<ContentBlock, { type: \"tool_call\" }>;\n"]}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Byte helpers for the signers: base64url without padding (RFC 4648 §5), and a comparison whose running time doesn't
|
|
3
|
+
* depend on where two byte strings first differ. Web-standard APIs only, so they run on every target.
|
|
4
|
+
*/
|
|
5
|
+
/** Encodes bytes as base64url with no padding. */
|
|
6
|
+
export declare function toBase64Url(bytes: Uint8Array): string;
|
|
7
|
+
/**
|
|
8
|
+
* Decodes unpadded base64url. Returns `undefined` for any text that isn't the canonical encoding of some bytes: a
|
|
9
|
+
* character outside the alphabet, padding, a length no encoding has, or unused low bits that aren't zero. Refusing a
|
|
10
|
+
* non-canonical form keeps one signature from having two spellings.
|
|
11
|
+
*/
|
|
12
|
+
export declare function fromBase64Url(text: string): Uint8Array | undefined;
|
|
13
|
+
/**
|
|
14
|
+
* True when two byte strings are equal. It compares every byte, whatever the first difference, so the time it takes
|
|
15
|
+
* reveals only the lengths, which are public for a MAC.
|
|
16
|
+
*/
|
|
17
|
+
export declare function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Byte helpers for the signers: base64url without padding (RFC 4648 §5), and a comparison whose running time doesn't
|
|
3
|
+
* depend on where two byte strings first differ. Web-standard APIs only, so they run on every target.
|
|
4
|
+
*/
|
|
5
|
+
const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
6
|
+
const VALUE = new Map([...ALPHABET].map((char, index) => [char, index]));
|
|
7
|
+
/** Encodes bytes as base64url with no padding. */
|
|
8
|
+
export function toBase64Url(bytes) {
|
|
9
|
+
let out = "";
|
|
10
|
+
for (let index = 0; index < bytes.length; index += 3) {
|
|
11
|
+
// Missing bytes of the last group count as zero; the characters they would fill are left off below.
|
|
12
|
+
const chunk = ((bytes[index] ?? 0) << 16) | ((bytes[index + 1] ?? 0) << 8) | (bytes[index + 2] ?? 0);
|
|
13
|
+
const chars = Math.min(4, Math.ceil(((bytes.length - index) * 8) / 6));
|
|
14
|
+
for (let shift = 0; shift < chars; shift++)
|
|
15
|
+
out += ALPHABET[(chunk >> (18 - 6 * shift)) & 63];
|
|
16
|
+
}
|
|
17
|
+
return out;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Decodes unpadded base64url. Returns `undefined` for any text that isn't the canonical encoding of some bytes: a
|
|
21
|
+
* character outside the alphabet, padding, a length no encoding has, or unused low bits that aren't zero. Refusing a
|
|
22
|
+
* non-canonical form keeps one signature from having two spellings.
|
|
23
|
+
*/
|
|
24
|
+
export function fromBase64Url(text) {
|
|
25
|
+
if (text.length % 4 === 1)
|
|
26
|
+
return undefined;
|
|
27
|
+
const bytes = new Uint8Array(Math.floor((text.length * 6) / 8));
|
|
28
|
+
let buffer = 0;
|
|
29
|
+
let bits = 0;
|
|
30
|
+
let out = 0;
|
|
31
|
+
for (const char of text) {
|
|
32
|
+
const value = VALUE.get(char);
|
|
33
|
+
if (value === undefined)
|
|
34
|
+
return undefined;
|
|
35
|
+
buffer = ((buffer << 6) | value) & 0xffffff;
|
|
36
|
+
bits += 6;
|
|
37
|
+
if (bits >= 8) {
|
|
38
|
+
bits -= 8;
|
|
39
|
+
bytes[out++] = (buffer >> bits) & 0xff;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
// The bits left over after the last whole byte must be zero, or two texts would decode to the same bytes.
|
|
43
|
+
if ((buffer & ((1 << bits) - 1)) !== 0)
|
|
44
|
+
return undefined;
|
|
45
|
+
return bytes;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* True when two byte strings are equal. It compares every byte, whatever the first difference, so the time it takes
|
|
49
|
+
* reveals only the lengths, which are public for a MAC.
|
|
50
|
+
*/
|
|
51
|
+
export function constantTimeEqual(a, b) {
|
|
52
|
+
if (a.length !== b.length)
|
|
53
|
+
return false;
|
|
54
|
+
let difference = 0;
|
|
55
|
+
for (let index = 0; index < a.length; index++)
|
|
56
|
+
difference |= (a[index] ?? 0) ^ (b[index] ?? 0);
|
|
57
|
+
return difference === 0;
|
|
58
|
+
}
|
|
59
|
+
//# sourceMappingURL=bytes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bytes.js","sourceRoot":"","sources":["../../../src/vendor/agent-safety/bytes.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,QAAQ,GAAG,kEAAkE,CAAC;AACpF,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;AAEzE,kDAAkD;AAClD,MAAM,UAAU,WAAW,CAAC,KAAiB;IAC3C,IAAI,GAAG,GAAG,EAAE,CAAC;IACb,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,KAAK,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC,EAAE,CAAC;QACrD,oGAAoG;QACpG,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,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,IAAI,IAAI,CAAC,GAAG,IAAI,CAAC;QACzC,CAAC;IACH,CAAC;IACD,0GAA0G;IAC1G,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IACzD,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,iBAAiB,CAAC,CAAa,EAAE,CAAa;IAC5D,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IACxC,IAAI,UAAU,GAAG,CAAC,CAAC;IACnB,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,MAAM,EAAE,KAAK,EAAE;QAAE,UAAU,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;IAC/F,OAAO,UAAU,KAAK,CAAC,CAAC;AAC1B,CAAC","sourcesContent":["/**\n * Byte helpers for the signers: base64url without padding (RFC 4648 §5), and a comparison whose running time doesn't\n * depend on where two byte strings first differ. Web-standard APIs only, so they run on every target.\n */\n\nconst ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\nconst VALUE = new Map([...ALPHABET].map((char, index) => [char, index]));\n\n/** Encodes bytes as base64url with no padding. */\nexport function toBase64Url(bytes: Uint8Array): string {\n let out = \"\";\n for (let index = 0; index < bytes.length; index += 3) {\n // Missing bytes of the last group count as zero; the characters they would fill are left off below.\n const chunk = ((bytes[index] ?? 0) << 16) | ((bytes[index + 1] ?? 0) << 8) | (bytes[index + 2] ?? 0);\n const chars = Math.min(4, Math.ceil(((bytes.length - index) * 8) / 6));\n for (let shift = 0; shift < chars; shift++) out += ALPHABET[(chunk >> (18 - 6 * shift)) & 63];\n }\n return out;\n}\n\n/**\n * Decodes unpadded base64url. Returns `undefined` for any text that isn't the canonical encoding of some bytes: a\n * character outside the alphabet, padding, a length no encoding has, or unused low bits that aren't zero. Refusing a\n * non-canonical form keeps one signature from having two spellings.\n */\nexport function fromBase64Url(text: string): Uint8Array | undefined {\n if (text.length % 4 === 1) return undefined;\n const bytes = new Uint8Array(Math.floor((text.length * 6) / 8));\n let buffer = 0;\n let bits = 0;\n let out = 0;\n for (const char of text) {\n const value = VALUE.get(char);\n if (value === undefined) return undefined;\n buffer = ((buffer << 6) | value) & 0xffffff;\n bits += 6;\n if (bits >= 8) {\n bits -= 8;\n bytes[out++] = (buffer >> bits) & 0xff;\n }\n }\n // The bits left over after the last whole byte must be zero, or two texts would decode to the same bytes.\n if ((buffer & ((1 << bits) - 1)) !== 0) return undefined;\n return bytes;\n}\n\n/**\n * True when two byte strings are equal. It compares every byte, whatever the first difference, so the time it takes\n * reveals only the lengths, which are public for a MAC.\n */\nexport function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let difference = 0;\n for (let index = 0; index < a.length; index++) difference |= (a[index] ?? 0) ^ (b[index] ?? 0);\n return difference === 0;\n}\n"]}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason, an
|
|
3
|
+
* input that has no canonical JSON form, a key ring that can't sign, or a model request that would use a credential
|
|
4
|
+
* nobody configured.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Why a `SafetyError` was thrown. `invalid_outcome`: a write outcome breaks a rule. `invalid_input`: a tool input has
|
|
8
|
+
* no canonical JSON form, or a tool's context fails its `contextSchema`. `invalid_key_ring`: a signer's keys or key
|
|
9
|
+
* ids can't be used. `invalid_pending`: the fields of a pending request can't be signed. `invalid_byok_config`: a
|
|
10
|
+
* model provider's key or base URL is empty, malformed or points at a gateway that may bill another credential.
|
|
11
|
+
* `egress_refused`: a model request would leave for another host or carry another credential. `default_provider`: code
|
|
12
|
+
* resolved a string model id, or another default provider is set, so a call could reach a gateway nobody configured.
|
|
13
|
+
* `invalid_effect`: a guarded write's scope, business key or options break a rule.
|
|
14
|
+
*/
|
|
15
|
+
export type SafetyErrorCode = "invalid_outcome" | "invalid_input" | "invalid_key_ring" | "invalid_pending" | "invalid_byok_config" | "egress_refused" | "default_provider" | "invalid_effect";
|
|
16
|
+
/** Thrown for a mistake in how the safety package is called. A write that fails is an outcome, never this error. */
|
|
17
|
+
export declare class SafetyError extends Error {
|
|
18
|
+
readonly name = "SafetyError";
|
|
19
|
+
readonly code: SafetyErrorCode;
|
|
20
|
+
constructor(code: SafetyErrorCode, message: string, options?: ErrorOptions);
|
|
21
|
+
}
|
|
22
|
+
/** True for a `SafetyError`, including one from another copy of the package. */
|
|
23
|
+
export declare function isSafetyError(error: unknown): error is SafetyError;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason, an
|
|
3
|
+
* input that has no canonical JSON form, a key ring that can't sign, or a model request that would use a credential
|
|
4
|
+
* nobody configured.
|
|
5
|
+
*/
|
|
6
|
+
// A registered symbol, so the guard still works when two copies of the package are bundled.
|
|
7
|
+
const SAFETY_ERROR = Symbol.for("buildanagent.agent-safety.SafetyError");
|
|
8
|
+
/** Thrown for a mistake in how the safety package is called. A write that fails is an outcome, never this error. */
|
|
9
|
+
export class SafetyError extends Error {
|
|
10
|
+
name = "SafetyError";
|
|
11
|
+
code;
|
|
12
|
+
constructor(code, message, options) {
|
|
13
|
+
super(message, options);
|
|
14
|
+
this.code = code;
|
|
15
|
+
Object.defineProperty(this, SAFETY_ERROR, { value: true });
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
/** True for a `SafetyError`, including one from another copy of the package. */
|
|
19
|
+
export function isSafetyError(error) {
|
|
20
|
+
return typeof error === "object" && error !== null && error[SAFETY_ERROR] === true;
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/vendor/agent-safety/errors.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAqBH,4FAA4F;AAC5F,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,uCAAuC,CAAC,CAAC;AAEzE,oHAAoH;AACpH,MAAM,OAAO,WAAY,SAAQ,KAAK;IAClB,IAAI,GAAG,aAAa,CAAC;IAC9B,IAAI,CAAkB;IAE/B,YAAY,IAAqB,EAAE,OAAe,EAAE,OAAsB;QACxE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,CAAC;CACF;AAED,gFAAgF;AAChF,MAAM,UAAU,aAAa,CAAC,KAAc;IAC1C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,YAAY,CAAC,KAAK,IAAI,CAAC;AAClH,CAAC","sourcesContent":["/**\n * `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason, an\n * input that has no canonical JSON form, a key ring that can't sign, or a model request that would use a credential\n * nobody configured.\n */\n\n/**\n * Why a `SafetyError` was thrown. `invalid_outcome`: a write outcome breaks a rule. `invalid_input`: a tool input has\n * no canonical JSON form, or a tool's context fails its `contextSchema`. `invalid_key_ring`: a signer's keys or key\n * ids can't be used. `invalid_pending`: the fields of a pending request can't be signed. `invalid_byok_config`: a\n * model provider's key or base URL is empty, malformed or points at a gateway that may bill another credential.\n * `egress_refused`: a model request would leave for another host or carry another credential. `default_provider`: code\n * resolved a string model id, or another default provider is set, so a call could reach a gateway nobody configured.\n * `invalid_effect`: a guarded write's scope, business key or options break a rule.\n */\nexport type SafetyErrorCode =\n | \"invalid_outcome\"\n | \"invalid_input\"\n | \"invalid_key_ring\"\n | \"invalid_pending\"\n | \"invalid_byok_config\"\n | \"egress_refused\"\n | \"default_provider\"\n | \"invalid_effect\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst SAFETY_ERROR = Symbol.for(\"buildanagent.agent-safety.SafetyError\");\n\n/** Thrown for a mistake in how the safety package is called. A write that fails is an outcome, never this error. */\nexport class SafetyError extends Error {\n override readonly name = \"SafetyError\";\n readonly code: SafetyErrorCode;\n\n constructor(code: SafetyErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, SAFETY_ERROR, { value: true });\n }\n}\n\n/** True for a `SafetyError`, including one from another copy of the package. */\nexport function isSafetyError(error: unknown): error is SafetyError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[SAFETY_ERROR] === true;\n}\n"]}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hashes a tool input: the SHA-256 of its canonical JSON (RFC 8785), as 64 lowercase hex digits. Two inputs whose
|
|
3
|
+
* object keys differ only in order get the same hash, and any changed value gives a different one. Object properties
|
|
4
|
+
* set to `undefined` are left out, as `JSON.stringify` leaves them out. The hash is async, because Web Crypto's
|
|
5
|
+
* digest is.
|
|
6
|
+
*
|
|
7
|
+
* It rejects with a `SafetyError`, code `invalid_input`, for a value that has no single JSON form:
|
|
8
|
+
* - `undefined`, or a hole, in an array;
|
|
9
|
+
* - a number that isn't finite;
|
|
10
|
+
* - a string with a lone surrogate;
|
|
11
|
+
* - a bigint, symbol or function;
|
|
12
|
+
* - an object that isn't plain, such as a `Date` (a plain object's prototype is `null` or any realm's
|
|
13
|
+
* `Object.prototype`);
|
|
14
|
+
* - an object or array that contains itself.
|
|
15
|
+
*/
|
|
16
|
+
export declare function canonicalInputHash(input: unknown): Promise<string>;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `canonicalInputHash()`: one hash per tool input, whatever order its keys arrive in. Approvals sign it and effect
|
|
3
|
+
* records store it, so both must compute it the same way on every runtime: canonical JSON as RFC 8785 (JCS) defines
|
|
4
|
+
* it, hashed with Web Crypto's SHA-256. Web Crypto is read as the bare `crypto` global, the same object as
|
|
5
|
+
* `globalThis.crypto`, because the Workers types declare it as a `const`, which `typeof globalThis` lacks.
|
|
6
|
+
*/
|
|
7
|
+
import { SafetyError } from "./errors.js";
|
|
8
|
+
const ENCODER = new TextEncoder();
|
|
9
|
+
function invalid(path, why) {
|
|
10
|
+
return new SafetyError("invalid_input", `the input at ${path} ${why}, so it has no canonical JSON form`);
|
|
11
|
+
}
|
|
12
|
+
function canonicalString(value, path) {
|
|
13
|
+
// JCS refuses lone surrogates, which JSON.stringify would escape instead.
|
|
14
|
+
if (!value.isWellFormed())
|
|
15
|
+
throw invalid(path, "holds a lone surrogate");
|
|
16
|
+
return JSON.stringify(value);
|
|
17
|
+
}
|
|
18
|
+
function canonicalNumber(value, path) {
|
|
19
|
+
if (!Number.isFinite(value))
|
|
20
|
+
throw invalid(path, `is ${value}`);
|
|
21
|
+
// JCS serializes numbers as ECMAScript does, which JSON.stringify follows, including -0 as 0.
|
|
22
|
+
return JSON.stringify(value);
|
|
23
|
+
}
|
|
24
|
+
// Plain means a null prototype or any realm's `Object.prototype`, whose own prototype is null: an object made in a
|
|
25
|
+
// `vm` context or an iframe is as plain as one made here, while a `Date` or class instance is not.
|
|
26
|
+
function isPlainObject(value) {
|
|
27
|
+
const prototype = Object.getPrototypeOf(value);
|
|
28
|
+
return prototype === null || Object.getPrototypeOf(prototype) === null;
|
|
29
|
+
}
|
|
30
|
+
function byKey([a], [b]) {
|
|
31
|
+
// JCS sorts property names by UTF-16 code units, which is what `<` compares.
|
|
32
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
33
|
+
}
|
|
34
|
+
// `ancestors` holds the objects and arrays that enclose the current value, so a cycle throws instead of recursing
|
|
35
|
+
// until the stack runs out. A value shared by two siblings is no cycle, so it is removed again on the way out.
|
|
36
|
+
function canonicalObject(value, path, ancestors) {
|
|
37
|
+
// Each property is read once, so a getter or a Proxy can't be counted as present and then read as undefined.
|
|
38
|
+
const entries = Object.entries(value)
|
|
39
|
+
.filter(([, item]) => item !== undefined)
|
|
40
|
+
.sort(byKey);
|
|
41
|
+
const members = entries.map(([key, item]) => `${canonicalString(key, `${path}'s property name`)}:${canonical(item, `${path}.${key}`, ancestors)}`);
|
|
42
|
+
return `{${members.join(",")}}`;
|
|
43
|
+
}
|
|
44
|
+
function canonicalArray(value, path, ancestors) {
|
|
45
|
+
// An index loop, because `map` skips the holes of a sparse array and `join` would then write `[1,,3]`.
|
|
46
|
+
const items = [];
|
|
47
|
+
for (let index = 0; index < value.length; index++) {
|
|
48
|
+
const itemPath = `${path}[${index}]`;
|
|
49
|
+
if (!(index in value))
|
|
50
|
+
throw invalid(itemPath, "is a hole in a sparse array");
|
|
51
|
+
const item = value[index];
|
|
52
|
+
if (item === undefined)
|
|
53
|
+
throw invalid(itemPath, "is undefined");
|
|
54
|
+
items.push(canonical(item, itemPath, ancestors));
|
|
55
|
+
}
|
|
56
|
+
return `[${items.join(",")}]`;
|
|
57
|
+
}
|
|
58
|
+
function nested(value, path, ancestors, write) {
|
|
59
|
+
if (ancestors.has(value))
|
|
60
|
+
throw invalid(path, "refers back to an object that contains it");
|
|
61
|
+
ancestors.add(value);
|
|
62
|
+
try {
|
|
63
|
+
return write();
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
ancestors.delete(value);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function describeType(value) {
|
|
70
|
+
if (value === undefined)
|
|
71
|
+
return "undefined";
|
|
72
|
+
return typeof value === "object" ? "an object that isn't plain" : `a ${typeof value}`;
|
|
73
|
+
}
|
|
74
|
+
function canonical(value, path, ancestors) {
|
|
75
|
+
if (value === null || typeof value === "boolean")
|
|
76
|
+
return JSON.stringify(value);
|
|
77
|
+
if (typeof value === "string")
|
|
78
|
+
return canonicalString(value, path);
|
|
79
|
+
if (typeof value === "number")
|
|
80
|
+
return canonicalNumber(value, path);
|
|
81
|
+
if (Array.isArray(value))
|
|
82
|
+
return nested(value, path, ancestors, () => canonicalArray(value, path, ancestors));
|
|
83
|
+
if (typeof value === "object" && isPlainObject(value)) {
|
|
84
|
+
return nested(value, path, ancestors, () => canonicalObject(value, path, ancestors));
|
|
85
|
+
}
|
|
86
|
+
throw invalid(path, `is ${describeType(value)}`);
|
|
87
|
+
}
|
|
88
|
+
function hex(bytes) {
|
|
89
|
+
return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Hashes a tool input: the SHA-256 of its canonical JSON (RFC 8785), as 64 lowercase hex digits. Two inputs whose
|
|
93
|
+
* object keys differ only in order get the same hash, and any changed value gives a different one. Object properties
|
|
94
|
+
* set to `undefined` are left out, as `JSON.stringify` leaves them out. The hash is async, because Web Crypto's
|
|
95
|
+
* digest is.
|
|
96
|
+
*
|
|
97
|
+
* It rejects with a `SafetyError`, code `invalid_input`, for a value that has no single JSON form:
|
|
98
|
+
* - `undefined`, or a hole, in an array;
|
|
99
|
+
* - a number that isn't finite;
|
|
100
|
+
* - a string with a lone surrogate;
|
|
101
|
+
* - a bigint, symbol or function;
|
|
102
|
+
* - an object that isn't plain, such as a `Date` (a plain object's prototype is `null` or any realm's
|
|
103
|
+
* `Object.prototype`);
|
|
104
|
+
* - an object or array that contains itself.
|
|
105
|
+
*/
|
|
106
|
+
export async function canonicalInputHash(input) {
|
|
107
|
+
const text = canonical(input, "$", new Set());
|
|
108
|
+
return hex(await crypto.subtle.digest("SHA-256", ENCODER.encode(text)));
|
|
109
|
+
}
|
|
110
|
+
//# sourceMappingURL=hash.js.map
|