@buildanagent/sdk 0.1.0-alpha.7 → 0.1.0-alpha.9
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 +91 -4
- package/dist/compose.d.ts +2 -1
- package/dist/compose.js +10 -4
- package/dist/compose.js.map +1 -1
- package/dist/errors.d.ts +2 -1
- package/dist/errors.js +2 -1
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +18 -4
- package/dist/events.js +1 -0
- package/dist/events.js.map +1 -1
- package/dist/hook-checks.js +17 -0
- package/dist/hook-checks.js.map +1 -1
- package/dist/hook-runner.d.ts +10 -0
- package/dist/hook-runner.js +86 -9
- package/dist/hook-runner.js.map +1 -1
- package/dist/hooks.d.ts +9 -4
- package/dist/hooks.js.map +1 -1
- package/dist/index.d.ts +9 -3
- package/dist/index.js +7 -2
- package/dist/index.js.map +1 -1
- package/dist/loop.d.ts +5 -0
- package/dist/loop.js +26 -3
- package/dist/loop.js.map +1 -1
- 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 +32 -0
- package/dist/pauses.js +46 -0
- package/dist/pauses.js.map +1 -0
- package/dist/result.d.ts +27 -3
- package/dist/result.js.map +1 -1
- package/dist/run.d.ts +19 -3
- package/dist/run.js +17 -1
- package/dist/run.js.map +1 -1
- package/dist/tools/pipeline.d.ts +19 -3
- package/dist/tools/pipeline.js +24 -5
- package/dist/tools/pipeline.js.map +1 -1
- 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 +8 -4
- package/dist/vendor/agent-safety/errors.js +2 -2
- package/dist/vendor/agent-safety/errors.js.map +1 -1
- package/dist/vendor/agent-safety/hash.js +3 -2
- package/dist/vendor/agent-safety/hash.js.map +1 -1
- 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/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/package.json +4 -2
package/dist/hook-runner.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { isSdkError, SdkError } from "./errors.js";
|
|
2
2
|
import { frozenCopy, thawedCopy } from "./freeze.js";
|
|
3
3
|
import { checkDecision, checkMessages, checkModelPatch, checkReplacement, checkResultPatch, checkStopDecision, } from "./hook-checks.js";
|
|
4
|
+
import { signPause } from "./pauses.js";
|
|
5
|
+
import { preparedSchemaOf } from "./tools/define.js";
|
|
4
6
|
import { isContentList } from "./tools/pipeline.js";
|
|
7
|
+
import { isSafetyError } from "./vendor/agent-safety/errors.js";
|
|
5
8
|
/** Thrown inside a run when a hook failed while the run fails closed; the loop ends the run with an `error` result. */
|
|
6
9
|
export class HookFailure extends SdkError {
|
|
7
10
|
name = "HookFailure";
|
|
@@ -30,20 +33,28 @@ function blocked(text, details) {
|
|
|
30
33
|
function gateOutcome(tool, decision) {
|
|
31
34
|
if (decision.decision === "allow")
|
|
32
35
|
return decision.input === undefined ? undefined : { input: thawedCopy(decision.input) };
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
36
|
+
return { blocked: blocked(`Tool call "${tool}" was denied: ${decision.reason}`, { decision: "deny" }) };
|
|
37
|
+
}
|
|
38
|
+
const SAFETY_CODES = [
|
|
39
|
+
"invalid_outcome",
|
|
40
|
+
"invalid_input",
|
|
41
|
+
"invalid_key_ring",
|
|
42
|
+
"invalid_pending",
|
|
43
|
+
];
|
|
44
|
+
/**
|
|
45
|
+
* Why a pause could not be signed, as reports may show it: one of the safety package's error codes, or a fixed word.
|
|
46
|
+
* A custom signer's own text is never passed on, because nothing stops it from quoting key material, and that holds
|
|
47
|
+
* for a `code` too: any object can carry the safety error's marker, so only a known code is trusted.
|
|
48
|
+
*/
|
|
49
|
+
function unsignedCause(error) {
|
|
50
|
+
return isSafetyError(error) && SAFETY_CODES.includes(error.code) ? error.code : "signer_failed";
|
|
41
51
|
}
|
|
42
52
|
/** Runs one run's interceptors. */
|
|
43
53
|
export class HookRunner {
|
|
44
54
|
#setup;
|
|
45
55
|
#hooks;
|
|
46
56
|
#continues;
|
|
57
|
+
#requestIds = new Set();
|
|
47
58
|
constructor(setup) {
|
|
48
59
|
this.#setup = setup;
|
|
49
60
|
this.#hooks = setup.interceptors;
|
|
@@ -112,7 +123,73 @@ export class HookRunner {
|
|
|
112
123
|
const guarded = await this.#guard("beforeToolCall", () => hook(event), failed);
|
|
113
124
|
if (guarded.status === "skipped")
|
|
114
125
|
return undefined;
|
|
115
|
-
|
|
126
|
+
if (guarded.status === "closed")
|
|
127
|
+
return guarded.value;
|
|
128
|
+
const decision = checkDecision(guarded.value);
|
|
129
|
+
return decision.decision === "ask"
|
|
130
|
+
? this.#pause(call, tool, input.input, decision)
|
|
131
|
+
: gateOutcome(tool.name, decision);
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Signs the pending request for a call a gate asked about and returns it with the input it signs. That input is the
|
|
135
|
+
* one the call would run with: the checked input the gate saw, or the `ask`'s own replacement, which must pass the
|
|
136
|
+
* tool's schema like an `allow`'s. If signing fails, the call is blocked: a pause that no signature covers is never
|
|
137
|
+
* written.
|
|
138
|
+
*/
|
|
139
|
+
async #pause(call, tool, seen, decision) {
|
|
140
|
+
const { signer, clock } = this.#setup;
|
|
141
|
+
const { reason, policyVersion } = decision;
|
|
142
|
+
const input = thawedCopy(decision.input === undefined ? seen : await this.#replacement(tool, decision.input));
|
|
143
|
+
let request;
|
|
144
|
+
try {
|
|
145
|
+
request = await signPause({
|
|
146
|
+
kind: "approval",
|
|
147
|
+
callId: call.callId,
|
|
148
|
+
tool: tool.name,
|
|
149
|
+
input,
|
|
150
|
+
...(policyVersion === undefined ? {} : { policyVersion }),
|
|
151
|
+
// Display text only, so a blank reason is left out rather than failing the signature.
|
|
152
|
+
...(reason === undefined || reason === "" ? {} : { reason }),
|
|
153
|
+
}, signer, { generateId: () => this.#requestId(), now: () => new Date(clock.now()) });
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
return this.#unsigned(tool.name, unsignedCause(error));
|
|
157
|
+
}
|
|
158
|
+
// A resolution names its request by id, so two pending requests of one run must never share one.
|
|
159
|
+
if (this.#requestIds.has(request.id))
|
|
160
|
+
return this.#unsigned(tool.name, "duplicate_request_id");
|
|
161
|
+
this.#requestIds.add(request.id);
|
|
162
|
+
return { paused: request, input };
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* The next request id from the run's `idGenerator`. A generator that repeats an id, such as one that always returns
|
|
166
|
+
* a session id, was enough for a run id alone, so a repeat of the run id or of an earlier request's id falls back to
|
|
167
|
+
* a random UUID instead of blocking the call.
|
|
168
|
+
*/
|
|
169
|
+
#requestId() {
|
|
170
|
+
const id = this.#setup.nextId();
|
|
171
|
+
return id === this.#setup.runId || this.#requestIds.has(id) ? globalThis.crypto.randomUUID() : id;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* An `ask`'s replacement input, checked against the tool's schema, because a call must never run with input its own
|
|
175
|
+
* tool would reject.
|
|
176
|
+
*/
|
|
177
|
+
async #replacement(tool, input) {
|
|
178
|
+
const checked = await preparedSchemaOf(tool).validate(input);
|
|
179
|
+
if (checked.ok)
|
|
180
|
+
return checked.value;
|
|
181
|
+
const issues = checked.issues.map((issue) => `${issue.path} ${issue.message}`.trim()).join("; ");
|
|
182
|
+
throw new SdkError("invalid_hook_result", `beforeToolCall asked about tool "${tool.name}" with an input its schema rejects: ${issues}`);
|
|
183
|
+
}
|
|
184
|
+
/** Blocks a call whose pause could not be signed, and reports why without the signer's own message. */
|
|
185
|
+
#unsigned(tool, cause) {
|
|
186
|
+
this.#setup.send({
|
|
187
|
+
type: "hook_error",
|
|
188
|
+
hook: "signer",
|
|
189
|
+
error: `the approval request could not be signed (${cause})`,
|
|
190
|
+
});
|
|
191
|
+
const text = `Tool call "${tool}" needs approval, but its approval request could not be signed, so it was not run.`;
|
|
192
|
+
return { blocked: blocked(text, { decision: "ask", error: cause }) };
|
|
116
193
|
}
|
|
117
194
|
async #afterTool(input) {
|
|
118
195
|
const hook = this.#hooks.afterToolCall;
|
package/dist/hook-runner.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hook-runner.js","sourceRoot":"","sources":["../src/hook-runner.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEnD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EACL,aAAa,EACb,aAAa,EACb,eAAe,EACf,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,GAElB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EAAkC,aAAa,EAAwB,MAAM,qBAAqB,CAAC;AAG1G,uHAAuH;AACvH,MAAM,OAAO,WAAY,SAAQ,QAAQ;IACrB,IAAI,GAAG,aAAa,CAAC;IAC9B,IAAI,CAAS;IAEtB,YAAY,IAAY,EAAE,KAAc;QACtC,KAAK,CAAC,aAAa,EAAE,OAAO,IAAI,iBAAiB,SAAS,CAAC,KAAK,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAChF,IAAI,CAAC,IAAI,GAAG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AAS,EAAE;YAClC,GAAG,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC;YAC3C,MAAM;YACN,SAAS,EAAE,KAAK,CAAC,GAAG,EAAE;YACtB,GAAG,UAAU,CAAC,OAAO,CAAC;SACvB,CAAgC,CAAC;IACpC,CAAC;IAED,qHAAqH;IACrH,KAAK,CAAC,MAAM,CACV,IAAY,EACZ,IAA0B,EAC1B,MAA8B;QAE9B,IAAI,CAAC;YACH,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,IAAI,EAAE,EAAE,CAAC;QAC/C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,0GAA0G;YAC1G,+FAA+F;YAC/F,IAAI,UAAU,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,qBAAqB;gBAAE,MAAM,KAAK,CAAC;YAC3E,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YACxE,IAAI,IAAI,CAAC,UAAU;gBAAE,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;YAClD,IAAI,MAAM,KAAK,SAAS;gBAAE,MAAM,IAAI,WAAW,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;YAC7D,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;QACpD,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * Runs the interceptors for one run: builds each hook's frozen event, applies the failure policy, checks what the\n * hook returned and emits `hook_error` and `context_transformed`. The loop and the tool pipeline call it at each\n * moment and never look at the hooks themselves.\n *\n * Failure policy (D6): a hook that throws is reported as a `hook_error` event. Under `fail_closed`, the default, a\n * failed gate denies its call, a failed `afterToolCall` withholds the result, and any other failed hook throws a\n * `HookFailure`, which the loop turns into an `error` result. Under `continue` the failed hook is skipped.\n */\nimport type { AssistantMessage, Message, ModelContext, ModelRef, Usage } from \"@buildanagent/gateway\";\nimport { isSdkError, SdkError } from \"./errors.js\";\nimport type { AgentEventBody } from \"./events.js\";\nimport { frozenCopy, thawedCopy } from \"./freeze.js\";\nimport {\n checkDecision,\n checkMessages,\n checkModelPatch,\n checkReplacement,\n checkResultPatch,\n checkStopDecision,\n type StopVerdict,\n} from \"./hook-checks.js\";\nimport type { CallOptions, GateDecision, HookEventBase, Interceptors, ModelCallPatch } from \"./hooks.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { type AnyTool, type GateOutcome, isContentList, type PipelineContext } from \"./tools/pipeline.js\";\nimport type { ToolCall, ToolResult } from \"./tools/types.js\";\n\n/** Thrown inside a run when a hook failed while the run fails closed; the loop ends the run with an `error` result. */\nexport class HookFailure extends SdkError {\n override readonly name = \"HookFailure\";\n readonly hook: string;\n\n constructor(hook: string, cause: unknown) {\n super(\"hook_failed\", `the ${hook} hook failed: ${messageOf(cause)}`, { cause });\n this.hook = hook;\n }\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** How a guarded hook call ended: it returned, it failed and the run skips it, or it failed and a result stands in. */\ntype Guarded<T, R> =\n | { readonly status: \"ok\"; readonly value: T }\n | { readonly status: \"skipped\" }\n | { readonly status: \"closed\"; readonly value: R };\n\n/** The result of a call after `afterToolCall` returned `patch`, checked to still be one the model can read. */\nfunction mergeResult(tool: string, result: ToolResult, patch: Record<string, unknown> | undefined): ToolResult {\n if (patch === undefined) return result;\n const merged = { ...result, ...patch } as ToolResult;\n if (!isContentList(merged.content)) {\n throw new SdkError(\n \"invalid_hook_result\",\n `afterToolCall for \"${tool}\" returned content that is not a list of text and image blocks`,\n );\n }\n return merged;\n}\n\n/** What a run gives its hook runner. */\nexport interface HookRunnerSetup {\n readonly interceptors: Interceptors;\n readonly runId: string;\n readonly signal: AbortSignal;\n readonly clock: Clock;\n /** The index of the model call in progress. */\n stepIndex(): number;\n send(body: AgentEventBody): void;\n}\n\nfunction blocked(text: string, details: Record<string, unknown>): ToolResult {\n return { content: [{ type: \"text\", text }], isError: true, details };\n}\n\n/** The pipeline hooks that the interceptors fill, left out when no interceptor needs them. */\nexport type PipelineHooks = Pick<PipelineContext, \"gate\" | \"after\">;\n\nfunction gateOutcome(tool: string, decision: GateDecision): GateOutcome | undefined {\n if (decision.decision === \"allow\")\n return decision.input === undefined ? undefined : { input: thawedCopy(decision.input) };\n if (decision.decision === \"deny\") {\n return { blocked: blocked(`Tool call \"${tool}\" was denied: ${decision.reason}`, { decision: \"deny\" }) };\n }\n const why = decision.reason === undefined ? \"\" : ` (${decision.reason})`;\n const text = `Tool call \"${tool}\" needs approval${why}, and this run can't ask for it, so it was not run.`;\n return {\n blocked: blocked(text, { decision: \"ask\", ...(decision.reason === undefined ? {} : { reason: decision.reason }) }),\n };\n}\n\n/** Runs one run's interceptors. */\nexport class HookRunner {\n readonly #setup: HookRunnerSetup;\n readonly #hooks: Interceptors;\n readonly #continues: boolean;\n\n constructor(setup: HookRunnerSetup) {\n this.#setup = setup;\n this.#hooks = setup.interceptors;\n this.#continues = setup.interceptors.onFailure === \"continue\";\n }\n\n /** The gate and the after-hook, for the tool pipeline. */\n pipelineHooks(): PipelineHooks {\n return {\n ...(this.#hooks.beforeToolCall === undefined ? {} : { gate: (e) => this.#gate(e) }),\n ...(this.#hooks.afterToolCall === undefined ? {} : { after: (e) => this.#afterTool(e) }),\n };\n }\n\n /** The messages `transformContext` chose for this call, or undefined to send the transcript as it is. */\n async transformContext(input: {\n system: string;\n messages: readonly Message[];\n model: ModelRef;\n lastUsage: Usage | undefined;\n }): Promise<Message[] | undefined> {\n const hook = this.#hooks.transformContext;\n if (hook === undefined) return undefined;\n const { lastUsage, ...rest } = input;\n const event = this.#event({ ...rest, ...(lastUsage === undefined ? {} : { lastUsage }) });\n const guarded = await this.#guard(\"transformContext\", () => hook(event));\n if (guarded.status !== \"ok\") return undefined;\n const messages = checkMessages(\"transformContext\", guarded.value);\n this.#setup.send({ type: \"context_transformed\", before: input.messages.length, after: messages.length });\n return messages;\n }\n\n /** What `beforeModelCall` changed, if anything. */\n async beforeModelCall(input: { context: ModelContext; options: CallOptions }): Promise<ModelCallPatch | undefined> {\n const hook = this.#hooks.beforeModelCall;\n if (hook === undefined) return undefined;\n const event = this.#event(input);\n const guarded = await this.#guard(\"beforeModelCall\", () => hook(event));\n return guarded.status === \"ok\" ? checkModelPatch(guarded.value) : undefined;\n }\n\n /** The response the run goes on with: `afterModelCall`'s replacement, or `message` itself. */\n async afterModelCall(message: AssistantMessage): Promise<AssistantMessage> {\n const hook = this.#hooks.afterModelCall;\n if (hook === undefined) return message;\n const event = this.#event({ message });\n const guarded = await this.#guard(\"afterModelCall\", () => hook(event));\n return (guarded.status === \"ok\" ? checkReplacement(guarded.value) : undefined) ?? message;\n }\n\n /** What `shouldStop` decided. */\n async shouldStop(input: { messages: readonly Message[]; lastMessage: AssistantMessage }): Promise<StopVerdict> {\n const hook = this.#hooks.shouldStop;\n if (hook === undefined) return { kind: \"none\" };\n const event = this.#event(input);\n const guarded = await this.#guard(\"shouldStop\", () => hook(event));\n return guarded.status === \"ok\" ? checkStopDecision(guarded.value) : { kind: \"none\" };\n }\n\n async #gate(input: { call: ToolCall; tool: AnyTool; input: unknown }): Promise<GateOutcome | undefined> {\n const hook = this.#hooks.beforeToolCall;\n if (hook === undefined) return undefined;\n const { call, tool } = input;\n const event = this.#event({ callId: call.callId, tool: tool.name, input: input.input }, call.callId);\n const failed = (error: unknown): GateOutcome => ({\n blocked: blocked(`Tool call \"${tool.name}\" was not run, because its permission check failed.`, {\n hook: \"beforeToolCall\",\n error: messageOf(error),\n }),\n });\n const guarded = await this.#guard(\"beforeToolCall\", () => hook(event), failed);\n if (guarded.status === \"skipped\") return undefined;\n return guarded.status === \"closed\" ? guarded.value : gateOutcome(tool.name, checkDecision(guarded.value));\n }\n\n async #afterTool(input: { call: ToolCall; tool: AnyTool; input: unknown; result: ToolResult }): Promise<ToolResult> {\n const hook = this.#hooks.afterToolCall;\n const { call, tool, result } = input;\n if (hook === undefined) return result;\n const event = this.#event({ callId: call.callId, tool: tool.name, input: input.input, result }, call.callId);\n // The tool already ran, so the stand-in says so and keeps the write outcome: a model told only \"withheld\" would\n // retry a write that was applied.\n const withheld = (error: unknown): ToolResult => ({\n ...blocked(`Tool call \"${tool.name}\" ran, but its result was withheld, because its result check failed.`, {\n hook: \"afterToolCall\",\n error: messageOf(error),\n }),\n ...(result.outcome === undefined ? {} : { outcome: result.outcome }),\n });\n const guarded = await this.#guard(\"afterToolCall\", () => hook(event), withheld);\n if (guarded.status === \"skipped\") return result;\n return guarded.status === \"closed\"\n ? guarded.value\n : mergeResult(tool.name, result, checkResultPatch(guarded.value));\n }\n\n #event<P extends object>(payload: P, callId?: string): Readonly<HookEventBase & P> {\n const { runId, signal, clock } = this.#setup;\n return Object.freeze({\n runId,\n stepIndex: this.#setup.stepIndex(),\n ...(callId === undefined ? {} : { callId }),\n signal,\n timestamp: clock.now(),\n ...frozenCopy(payload),\n }) as Readonly<HookEventBase & P>;\n }\n\n /** Calls a hook under the failure policy. Without `closed`, a failure under `fail_closed` throws a `HookFailure`. */\n async #guard<T, R = never>(\n hook: string,\n call: () => T | Promise<T>,\n closed?: (error: unknown) => R,\n ): Promise<Guarded<Awaited<T>, R>> {\n try {\n return { status: \"ok\", value: await call() };\n } catch (error) {\n // A wrong return shape is a programmer error whatever the policy, even when a joined hook found it inside\n // `composeInterceptors()`: skipping or closing on it would let a typo in a gate pass silently.\n if (isSdkError(error) && error.code === \"invalid_hook_result\") throw error;\n this.#setup.send({ type: \"hook_error\", hook, error: messageOf(error) });\n if (this.#continues) return { status: \"skipped\" };\n if (closed === undefined) throw new HookFailure(hook, error);\n return { status: \"closed\", value: closed(error) };\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"hook-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G,UAAU,CAAC,OAAO,CAAC;SACvB,CAAgC,CAAC;IACpC,CAAC;IAED,qHAAqH;IACrH,KAAK,CAAC,MAAM,CACV,IAAY,EACZ,IAA0B,EAC1B,MAA8B;QAE9B,IAAI,CAAC;YACH,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,IAAI,EAAE,EAAE,CAAC;QAC/C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,0GAA0G;YAC1G,+FAA+F;YAC/F,IAAI,UAAU,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,qBAAqB;gBAAE,MAAM,KAAK,CAAC;YAC3E,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YACxE,IAAI,IAAI,CAAC,UAAU;gBAAE,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;YAClD,IAAI,MAAM,KAAK,SAAS;gBAAE,MAAM,IAAI,WAAW,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;YAC7D,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;QACpD,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * Runs the interceptors for one run: builds each hook's frozen event, applies the failure policy, checks what the\n * hook returned and emits `hook_error` and `context_transformed`. The loop and the tool pipeline call it at each\n * moment and never look at the hooks themselves.\n *\n * Failure policy (D6): a hook that throws is reported as a `hook_error` event. Under `fail_closed`, the default, a\n * failed gate denies its call, a failed `afterToolCall` withholds the result, and any other failed hook throws a\n * `HookFailure`, which the loop turns into an `error` result. Under `continue` the failed hook is skipped.\n *\n * A gate's `ask` pauses its call (D5): the runner signs a pending request through the one signing path, over the\n * input the call would run with, and hands the request and that input to the pipeline, which reports the pause once\n * every call of the step has been gated. A pause that can't be signed never pauses unsigned: the call is blocked\n * instead, whatever `onFailure` says.\n */\nimport type { AssistantMessage, Message, ModelContext, ModelRef, Usage } from \"@buildanagent/gateway\";\nimport { isSdkError, SdkError } from \"./errors.js\";\nimport type { AgentEventBody } from \"./events.js\";\nimport { frozenCopy, thawedCopy } from \"./freeze.js\";\nimport {\n checkDecision,\n checkMessages,\n checkModelPatch,\n checkReplacement,\n checkResultPatch,\n checkStopDecision,\n type StopVerdict,\n} from \"./hook-checks.js\";\nimport type { CallOptions, GateDecision, HookEventBase, Interceptors, ModelCallPatch } from \"./hooks.js\";\nimport { signPause } from \"./pauses.js\";\nimport type { Clock } from \"./testing/determinism.js\";\nimport { preparedSchemaOf } from \"./tools/define.js\";\nimport { type AnyTool, type GateOutcome, isContentList, type PipelineContext } from \"./tools/pipeline.js\";\nimport type { ToolCall, ToolResult } from \"./tools/types.js\";\nimport { isSafetyError, type SafetyErrorCode } from \"./vendor/agent-safety/errors.js\";\nimport type { SignedPendingRequest } from \"./vendor/agent-safety/pending.js\";\nimport type { ApprovalSigner } from \"./vendor/agent-safety/signer.js\";\n\n/** Thrown inside a run when a hook failed while the run fails closed; the loop ends the run with an `error` result. */\nexport class HookFailure extends SdkError {\n override readonly name = \"HookFailure\";\n readonly hook: string;\n\n constructor(hook: string, cause: unknown) {\n super(\"hook_failed\", `the ${hook} hook failed: ${messageOf(cause)}`, { cause });\n this.hook = hook;\n }\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** How a guarded hook call ended: it returned, it failed and the run skips it, or it failed and a result stands in. */\ntype Guarded<T, R> =\n | { readonly status: \"ok\"; readonly value: T }\n | { readonly status: \"skipped\" }\n | { readonly status: \"closed\"; readonly value: R };\n\n/** The result of a call after `afterToolCall` returned `patch`, checked to still be one the model can read. */\nfunction mergeResult(tool: string, result: ToolResult, patch: Record<string, unknown> | undefined): ToolResult {\n if (patch === undefined) return result;\n const merged = { ...result, ...patch } as ToolResult;\n if (!isContentList(merged.content)) {\n throw new SdkError(\n \"invalid_hook_result\",\n `afterToolCall for \"${tool}\" returned content that is not a list of text and image blocks`,\n );\n }\n return merged;\n}\n\n/** What a run gives its hook runner. */\nexport interface HookRunnerSetup {\n readonly interceptors: Interceptors;\n readonly runId: string;\n readonly signal: AbortSignal;\n readonly clock: Clock;\n /** The index of the model call in progress. */\n stepIndex(): number;\n send(body: AgentEventBody): void;\n /** Signs the pending request a gate's `ask` writes. */\n readonly signer: ApprovalSigner;\n /** Makes each pending request's id. */\n readonly nextId: () => string;\n}\n\n/** The decision of a gate that asks for a person. */\ntype AskDecision = Extract<GateDecision, { decision: \"ask\" }>;\n\nfunction blocked(text: string, details: Record<string, unknown>): ToolResult {\n return { content: [{ type: \"text\", text }], isError: true, details };\n}\n\n/** The pipeline hooks that the interceptors fill, left out when no interceptor needs them. */\nexport type PipelineHooks = Pick<PipelineContext, \"gate\" | \"after\">;\n\nfunction gateOutcome(tool: string, decision: Exclude<GateDecision, AskDecision>): GateOutcome | undefined {\n if (decision.decision === \"allow\")\n return decision.input === undefined ? undefined : { input: thawedCopy(decision.input) };\n return { blocked: blocked(`Tool call \"${tool}\" was denied: ${decision.reason}`, { decision: \"deny\" }) };\n}\n\nconst SAFETY_CODES: readonly string[] = [\n \"invalid_outcome\",\n \"invalid_input\",\n \"invalid_key_ring\",\n \"invalid_pending\",\n] satisfies readonly SafetyErrorCode[];\n\n/**\n * Why a pause could not be signed, as reports may show it: one of the safety package's error codes, or a fixed word.\n * A custom signer's own text is never passed on, because nothing stops it from quoting key material, and that holds\n * for a `code` too: any object can carry the safety error's marker, so only a known code is trusted.\n */\nfunction unsignedCause(error: unknown): string {\n return isSafetyError(error) && SAFETY_CODES.includes(error.code) ? error.code : \"signer_failed\";\n}\n\n/** Runs one run's interceptors. */\nexport class HookRunner {\n readonly #setup: HookRunnerSetup;\n readonly #hooks: Interceptors;\n readonly #continues: boolean;\n readonly #requestIds = new Set<string>();\n\n constructor(setup: HookRunnerSetup) {\n this.#setup = setup;\n this.#hooks = setup.interceptors;\n this.#continues = setup.interceptors.onFailure === \"continue\";\n }\n\n /** The gate and the after-hook, for the tool pipeline. */\n pipelineHooks(): PipelineHooks {\n return {\n ...(this.#hooks.beforeToolCall === undefined ? {} : { gate: (e) => this.#gate(e) }),\n ...(this.#hooks.afterToolCall === undefined ? {} : { after: (e) => this.#afterTool(e) }),\n };\n }\n\n /** The messages `transformContext` chose for this call, or undefined to send the transcript as it is. */\n async transformContext(input: {\n system: string;\n messages: readonly Message[];\n model: ModelRef;\n lastUsage: Usage | undefined;\n }): Promise<Message[] | undefined> {\n const hook = this.#hooks.transformContext;\n if (hook === undefined) return undefined;\n const { lastUsage, ...rest } = input;\n const event = this.#event({ ...rest, ...(lastUsage === undefined ? {} : { lastUsage }) });\n const guarded = await this.#guard(\"transformContext\", () => hook(event));\n if (guarded.status !== \"ok\") return undefined;\n const messages = checkMessages(\"transformContext\", guarded.value);\n this.#setup.send({ type: \"context_transformed\", before: input.messages.length, after: messages.length });\n return messages;\n }\n\n /** What `beforeModelCall` changed, if anything. */\n async beforeModelCall(input: { context: ModelContext; options: CallOptions }): Promise<ModelCallPatch | undefined> {\n const hook = this.#hooks.beforeModelCall;\n if (hook === undefined) return undefined;\n const event = this.#event(input);\n const guarded = await this.#guard(\"beforeModelCall\", () => hook(event));\n return guarded.status === \"ok\" ? checkModelPatch(guarded.value) : undefined;\n }\n\n /** The response the run goes on with: `afterModelCall`'s replacement, or `message` itself. */\n async afterModelCall(message: AssistantMessage): Promise<AssistantMessage> {\n const hook = this.#hooks.afterModelCall;\n if (hook === undefined) return message;\n const event = this.#event({ message });\n const guarded = await this.#guard(\"afterModelCall\", () => hook(event));\n return (guarded.status === \"ok\" ? checkReplacement(guarded.value) : undefined) ?? message;\n }\n\n /** What `shouldStop` decided. */\n async shouldStop(input: { messages: readonly Message[]; lastMessage: AssistantMessage }): Promise<StopVerdict> {\n const hook = this.#hooks.shouldStop;\n if (hook === undefined) return { kind: \"none\" };\n const event = this.#event(input);\n const guarded = await this.#guard(\"shouldStop\", () => hook(event));\n return guarded.status === \"ok\" ? checkStopDecision(guarded.value) : { kind: \"none\" };\n }\n\n async #gate(input: { call: ToolCall; tool: AnyTool; input: unknown }): Promise<GateOutcome | undefined> {\n const hook = this.#hooks.beforeToolCall;\n if (hook === undefined) return undefined;\n const { call, tool } = input;\n const event = this.#event({ callId: call.callId, tool: tool.name, input: input.input }, call.callId);\n const failed = (error: unknown): GateOutcome => ({\n blocked: blocked(`Tool call \"${tool.name}\" was not run, because its permission check failed.`, {\n hook: \"beforeToolCall\",\n error: messageOf(error),\n }),\n });\n const guarded = await this.#guard(\"beforeToolCall\", () => hook(event), failed);\n if (guarded.status === \"skipped\") return undefined;\n if (guarded.status === \"closed\") return guarded.value;\n const decision = checkDecision(guarded.value);\n return decision.decision === \"ask\"\n ? this.#pause(call, tool, input.input, decision)\n : gateOutcome(tool.name, decision);\n }\n\n /**\n * Signs the pending request for a call a gate asked about and returns it with the input it signs. That input is the\n * one the call would run with: the checked input the gate saw, or the `ask`'s own replacement, which must pass the\n * tool's schema like an `allow`'s. If signing fails, the call is blocked: a pause that no signature covers is never\n * written.\n */\n async #pause(call: ToolCall, tool: AnyTool, seen: unknown, decision: AskDecision): Promise<GateOutcome> {\n const { signer, clock } = this.#setup;\n const { reason, policyVersion } = decision;\n const input = thawedCopy(decision.input === undefined ? seen : await this.#replacement(tool, decision.input));\n let request: SignedPendingRequest;\n try {\n request = await signPause(\n {\n kind: \"approval\",\n callId: call.callId,\n tool: tool.name,\n input,\n ...(policyVersion === undefined ? {} : { policyVersion }),\n // Display text only, so a blank reason is left out rather than failing the signature.\n ...(reason === undefined || reason === \"\" ? {} : { reason }),\n },\n signer,\n { generateId: () => this.#requestId(), now: () => new Date(clock.now()) },\n );\n } catch (error) {\n return this.#unsigned(tool.name, unsignedCause(error));\n }\n // A resolution names its request by id, so two pending requests of one run must never share one.\n if (this.#requestIds.has(request.id)) return this.#unsigned(tool.name, \"duplicate_request_id\");\n this.#requestIds.add(request.id);\n return { paused: request, input };\n }\n\n /**\n * The next request id from the run's `idGenerator`. A generator that repeats an id, such as one that always returns\n * a session id, was enough for a run id alone, so a repeat of the run id or of an earlier request's id falls back to\n * a random UUID instead of blocking the call.\n */\n #requestId(): string {\n const id = this.#setup.nextId();\n return id === this.#setup.runId || this.#requestIds.has(id) ? globalThis.crypto.randomUUID() : id;\n }\n\n /**\n * An `ask`'s replacement input, checked against the tool's schema, because a call must never run with input its own\n * tool would reject.\n */\n async #replacement(tool: AnyTool, input: unknown): Promise<unknown> {\n const checked = await preparedSchemaOf(tool).validate(input);\n if (checked.ok) return checked.value;\n const issues = checked.issues.map((issue) => `${issue.path} ${issue.message}`.trim()).join(\"; \");\n throw new SdkError(\n \"invalid_hook_result\",\n `beforeToolCall asked about tool \"${tool.name}\" with an input its schema rejects: ${issues}`,\n );\n }\n\n /** Blocks a call whose pause could not be signed, and reports why without the signer's own message. */\n #unsigned(tool: string, cause: string): GateOutcome {\n this.#setup.send({\n type: \"hook_error\",\n hook: \"signer\",\n error: `the approval request could not be signed (${cause})`,\n });\n const text = `Tool call \"${tool}\" needs approval, but its approval request could not be signed, so it was not run.`;\n return { blocked: blocked(text, { decision: \"ask\", error: cause }) };\n }\n\n async #afterTool(input: { call: ToolCall; tool: AnyTool; input: unknown; result: ToolResult }): Promise<ToolResult> {\n const hook = this.#hooks.afterToolCall;\n const { call, tool, result } = input;\n if (hook === undefined) return result;\n const event = this.#event({ callId: call.callId, tool: tool.name, input: input.input, result }, call.callId);\n // The tool already ran, so the stand-in says so and keeps the write outcome: a model told only \"withheld\" would\n // retry a write that was applied.\n const withheld = (error: unknown): ToolResult => ({\n ...blocked(`Tool call \"${tool.name}\" ran, but its result was withheld, because its result check failed.`, {\n hook: \"afterToolCall\",\n error: messageOf(error),\n }),\n ...(result.outcome === undefined ? {} : { outcome: result.outcome }),\n });\n const guarded = await this.#guard(\"afterToolCall\", () => hook(event), withheld);\n if (guarded.status === \"skipped\") return result;\n return guarded.status === \"closed\"\n ? guarded.value\n : mergeResult(tool.name, result, checkResultPatch(guarded.value));\n }\n\n #event<P extends object>(payload: P, callId?: string): Readonly<HookEventBase & P> {\n const { runId, signal, clock } = this.#setup;\n return Object.freeze({\n runId,\n stepIndex: this.#setup.stepIndex(),\n ...(callId === undefined ? {} : { callId }),\n signal,\n timestamp: clock.now(),\n ...frozenCopy(payload),\n }) as Readonly<HookEventBase & P>;\n }\n\n /** Calls a hook under the failure policy. Without `closed`, a failure under `fail_closed` throws a `HookFailure`. */\n async #guard<T, R = never>(\n hook: string,\n call: () => T | Promise<T>,\n closed?: (error: unknown) => R,\n ): Promise<Guarded<Awaited<T>, R>> {\n try {\n return { status: \"ok\", value: await call() };\n } catch (error) {\n // A wrong return shape is a programmer error whatever the policy, even when a joined hook found it inside\n // `composeInterceptors()`: skipping or closing on it would let a typo in a gate pass silently.\n if (isSdkError(error) && error.code === \"invalid_hook_result\") throw error;\n this.#setup.send({ type: \"hook_error\", hook, error: messageOf(error) });\n if (this.#continues) return { status: \"skipped\" };\n if (closed === undefined) throw new HookFailure(hook, error);\n return { status: \"closed\", value: closed(error) };\n }\n }\n}\n"]}
|
package/dist/hooks.d.ts
CHANGED
|
@@ -92,8 +92,12 @@ export interface ModelCallPatch {
|
|
|
92
92
|
}
|
|
93
93
|
/**
|
|
94
94
|
* What `beforeToolCall` decides. `allow` runs the call, with `input` in place of the model's when given; the
|
|
95
|
-
* replacement must pass the tool's schema. `deny` blocks the call, and the model reads the `reason`. `ask`
|
|
96
|
-
*
|
|
95
|
+
* replacement must pass the tool's schema. `deny` blocks the call, and the model reads the `reason`. `ask` pauses
|
|
96
|
+
* the call for a person: the run signs a pending request for it with the run's `signer`, and ends
|
|
97
|
+
* `awaiting_approval` once the step's other calls have their results. `reason` is shown to the approver and isn't
|
|
98
|
+
* signed; `policyVersion` is signed. An `ask` may carry an `input`, which must pass the tool's schema like an
|
|
99
|
+
* `allow`'s: the request is then signed over it, because it is the input the call would run with once approved.
|
|
100
|
+
* `composeInterceptors()` passes an earlier gate's replacement on this way when a later gate asks.
|
|
97
101
|
*/
|
|
98
102
|
export type GateDecision = {
|
|
99
103
|
readonly decision: "allow";
|
|
@@ -104,6 +108,7 @@ export type GateDecision = {
|
|
|
104
108
|
readonly reason: string;
|
|
105
109
|
} | {
|
|
106
110
|
readonly decision: "ask";
|
|
111
|
+
readonly input?: unknown;
|
|
107
112
|
readonly reason?: string;
|
|
108
113
|
readonly policyVersion?: string;
|
|
109
114
|
};
|
|
@@ -149,8 +154,8 @@ export interface Interceptors {
|
|
|
149
154
|
/**
|
|
150
155
|
* The gate: decides whether a tool call runs, once for each call that passed validation, one call at a time in
|
|
151
156
|
* model order, and before any call of the step executes. With no `beforeToolCall`, no gate stands in the way and
|
|
152
|
-
* every registered tool is allowed. A gate that returns `ask` pauses the
|
|
153
|
-
*
|
|
157
|
+
* every registered tool is allowed. A gate that returns `ask` pauses the call, and the run ends `awaiting_approval`
|
|
158
|
+
* with a signed pending request for it. A gate that throws denies the call unless `onFailure` is `"continue"`. A gate must return a
|
|
154
159
|
* decision: returning nothing throws an `SdkError` with code `invalid_hook_result`.
|
|
155
160
|
*/
|
|
156
161
|
readonly beforeToolCall?: (e: ToolCallEvent) => MaybePromise<GateDecision>;
|
package/dist/hooks.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.js","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The hook types: six interceptors that can change a run, and the observer that only watches it. Each interceptor\n * takes one event object and returns a replacement, never mutating its input, because the event's data is frozen.\n */\nimport type {\n AssistantMessage,\n ContentBlock,\n Message,\n Model,\n ModelCallOptions,\n ModelContext,\n ModelRef,\n Usage,\n} from \"@buildanagent/gateway\";\nimport type { AgentEvent } from \"./events.js\";\nimport type { ToolResult } from \"./tools/types.js\";\n\n/** A value or a promise of one: a hook may be a plain function or an `async` one. */\nexport type MaybePromise<T> = T | Promise<T>;\n\n/**\n * A value, or nothing: what a hook that may change something returns. `void` lets an `async` hook that has nothing\n * to change simply end, where `undefined` would force it to return explicitly.\n */\n// biome-ignore lint/suspicious/noConfusingVoidType: a hook's return type, where void lets a function return nothing\nexport type OrNothing<T> = T | void;\n\n/** The options of one model call, without the abort signal, which the run supplies. */\nexport type CallOptions = Omit<ModelCallOptions, \"signal\">;\n\n/** The fields every hook event carries. */\nexport interface HookEventBase {\n /** The run's id. */\n readonly runId: string;\n /** The index of the model call the hook belongs to, counted from 0. */\n readonly stepIndex: number;\n /** The tool call's id, for the two tool hooks; absent for the others. */\n readonly callId?: string;\n /** The run's abort signal. Pass it on to any I/O the hook does. */\n readonly signal: AbortSignal;\n /** When the hook was called, from the run's clock, in ISO 8601. */\n readonly timestamp: string;\n}\n\n/** What `transformContext` receives: the conversation as it stands before the model call. */\nexport interface ContextEvent extends HookEventBase {\n /** The system prompt. */\n readonly system: string;\n /** The whole conversation so far, never a view an earlier call's transform returned. */\n readonly messages: readonly Message[];\n /** The model the run was started with. */\n readonly model: ModelRef;\n /** The previous model call's usage. Absent on the first call. */\n readonly lastUsage?: Usage;\n}\n\n/** What `beforeModelCall` receives: the request about to be sent. */\nexport interface ModelCallEvent extends HookEventBase {\n /** The request: the system prompt, the messages `transformContext` returned and the tools this call sends. */\n readonly context: ModelContext;\n /** The options of this call, without the abort signal. */\n readonly options: CallOptions;\n}\n\n/** What `afterModelCall` receives: the model's finished response. */\nexport interface ModelResultEvent extends HookEventBase {\n /** The response, including a failed one, whose `stopReason` is `\"error\"`. */\n readonly message: AssistantMessage;\n}\n\n/** What `beforeToolCall` receives: a call whose input has passed the tool's schema. */\nexport interface ToolCallEvent extends HookEventBase {\n readonly callId: string;\n /** The tool's name. */\n readonly tool: string;\n /** The validated input. */\n readonly input: unknown;\n}\n\n/** What `afterToolCall` receives: the result of a call that executed, before the model reads it. */\nexport interface ToolResultEvent extends ToolCallEvent {\n readonly result: ToolResult;\n}\n\n/** What `shouldStop` receives, after a step's tool calls have their results. */\nexport interface StepEvent extends HookEventBase {\n /** The whole conversation so far, including this step's response and tool results. */\n readonly messages: readonly Message[];\n /** This step's model response. */\n readonly lastMessage: AssistantMessage;\n}\n\n/**\n * Changes to one model call's request. Every field is optional, and a change applies to that call only; the next\n * call starts again from the run's own settings.\n */\nexport interface ModelCallPatch {\n /** Replaces the system prompt for this call. */\n readonly system?: string;\n /** Replaces the messages sent for this call. The run's own transcript keeps its messages. */\n readonly messages?: readonly Message[];\n /**\n * The names of the tools to send, as the complete list: a tool left out is not sent, and a tool whose `exposure`\n * is `deferred` or `hidden` is sent when named. Tools always go out in definition order, whatever order this list\n * is in. A name that matches no tool throws an `SdkError` with code `invalid_hook_result`. A call to a tool that\n * was not sent gets the unknown-tool error.\n */\n readonly activeTools?: readonly string[];\n /** Makes this call with another model. */\n readonly model?: Model;\n /** Replaces the options of this call. */\n readonly options?: CallOptions;\n}\n\n/**\n * What `beforeToolCall` decides. `allow` runs the call, with `input` in place of the model's when given; the\n * replacement must pass the tool's schema. `deny` blocks the call, and the model reads the `reason`. `ask` asks a\n * person; until runs can pause, it blocks the call like `deny` with a message that says approval isn't available.\n */\nexport type GateDecision =\n | { readonly decision: \"allow\"; readonly input?: unknown; readonly reason?: string }\n | { readonly decision: \"deny\"; readonly reason: string }\n | { readonly decision: \"ask\"; readonly reason?: string; readonly policyVersion?: string };\n\n/**\n * Changes to a tool's result. Each field present replaces the result's own. A replaced `outcome` is not available\n * here: a write's outcome is rendered into `content` once, so replace `content` instead.\n */\nexport type ToolResultPatch = Partial<Omit<ToolResult, \"outcome\">>;\n\n/**\n * What `shouldStop` decides. `true` or `{ stop: \"hook\" }` ends the run `stopped`, with the reason as `stoppedBy`\n * (`\"hook\"` for `true`). `{ stop: \"no_progress\" }` ends it `no_progress`. `{ continue }` keeps a run going that the\n * model ended by answering in text, adding the content as a user message. When the model's step called tools, the run goes on anyway and the content is\n * not added, so a hook that must reach the model should return it after a text answer. `false` leaves the decision to the run.\n */\nexport type StopDecision =\n | boolean\n | { readonly continue: string | readonly ContentBlock[] }\n | { readonly stop: \"no_progress\" | \"hook\"; readonly reason: string };\n\n/**\n * The six interceptors, in the order a step calls them: `transformContext`, `beforeModelCall`, the model call,\n * `afterModelCall`, then for each tool call `beforeToolCall` and `afterToolCall`, and last `shouldStop`. A run takes\n * one object; `composeInterceptors()` joins several. Each hook may be `async`.\n */\nexport interface Interceptors {\n /**\n * Returns the messages to send for this model call, such as a masked or summarised view of a long conversation.\n * The view reaches that call's request only: the next call's event, `result.messages` and `result.context` hold\n * the full history. Each call emits a `context_transformed` event with the message counts.\n */\n readonly transformContext?: (e: ContextEvent) => MaybePromise<readonly Message[]>;\n /** Changes the request about to be sent. Return nothing to leave it as it is. */\n readonly beforeModelCall?: (e: ModelCallEvent) => MaybePromise<OrNothing<ModelCallPatch>>;\n /**\n * Replaces the model's response. The transcript and the `model_call_end` event hold the replacement, and its tool\n * calls are the ones that run. The call's usage and cost stay those of the model's own response. If it throws\n * while the run fails closed, both hold an empty stand-in with `stopReason: \"error\"` and that usage and cost.\n */\n readonly afterModelCall?: (e: ModelResultEvent) => MaybePromise<OrNothing<{ readonly message?: AssistantMessage }>>;\n /**\n * The gate: decides whether a tool call runs, once for each call that passed validation, one call at a time in\n * model order, and before any call of the step executes. With no `beforeToolCall`, no gate stands in the way and\n * every registered tool is allowed. A gate that returns `ask` pauses the run once pauses exist; until then `ask`\n * blocks the call. A gate that throws denies the call unless `onFailure` is `\"continue\"`. A gate must return a\n * decision: returning nothing throws an `SdkError` with code `invalid_hook_result`.\n */\n readonly beforeToolCall?: (e: ToolCallEvent) => MaybePromise<GateDecision>;\n /**\n * Replaces fields of a result before the model reads it, and before `tool_call_end` reports it. It runs for calls\n * that executed, including ones whose `execute` threw, and not for calls that never ran, such as an unknown tool,\n * invalid input or a denied call. Return nothing to keep the result.\n */\n readonly afterToolCall?: (e: ToolResultEvent) => MaybePromise<OrNothing<ToolResultPatch>>;\n /** Ends the run, or keeps it going, after a step. It is not asked once the run has a stop reason of its own. */\n readonly shouldStop?: (e: StepEvent) => MaybePromise<StopDecision>;\n /**\n * What a hook that throws does. `\"fail_closed\"` (the default) stops the unsafe thing: a failed `beforeToolCall`\n * denies the call, a failed `afterToolCall` withholds the result, and a failed model-moment hook or `shouldStop`\n * ends the run with `stopReason: \"error\"` and `error.kind: \"hook\"`. `\"continue\"` skips the failed hook and goes on\n * as if it had returned nothing. Either way the run emits a `hook_error` event.\n */\n readonly onFailure?: \"fail_closed\" | \"continue\";\n}\n\n/**\n * Watches a run: called with each event, in order, and never able to change the run. A promise it returns is waited\n * for before the next event is delivered to it. A throw or a rejection becomes a `hook_error` event.\n */\nexport type Observer = (event: AgentEvent) => MaybePromise<void>;\n"]}
|
|
1
|
+
{"version":3,"file":"hooks.js","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The hook types: six interceptors that can change a run, and the observer that only watches it. Each interceptor\n * takes one event object and returns a replacement, never mutating its input, because the event's data is frozen.\n */\nimport type {\n AssistantMessage,\n ContentBlock,\n Message,\n Model,\n ModelCallOptions,\n ModelContext,\n ModelRef,\n Usage,\n} from \"@buildanagent/gateway\";\nimport type { AgentEvent } from \"./events.js\";\nimport type { ToolResult } from \"./tools/types.js\";\n\n/** A value or a promise of one: a hook may be a plain function or an `async` one. */\nexport type MaybePromise<T> = T | Promise<T>;\n\n/**\n * A value, or nothing: what a hook that may change something returns. `void` lets an `async` hook that has nothing\n * to change simply end, where `undefined` would force it to return explicitly.\n */\n// biome-ignore lint/suspicious/noConfusingVoidType: a hook's return type, where void lets a function return nothing\nexport type OrNothing<T> = T | void;\n\n/** The options of one model call, without the abort signal, which the run supplies. */\nexport type CallOptions = Omit<ModelCallOptions, \"signal\">;\n\n/** The fields every hook event carries. */\nexport interface HookEventBase {\n /** The run's id. */\n readonly runId: string;\n /** The index of the model call the hook belongs to, counted from 0. */\n readonly stepIndex: number;\n /** The tool call's id, for the two tool hooks; absent for the others. */\n readonly callId?: string;\n /** The run's abort signal. Pass it on to any I/O the hook does. */\n readonly signal: AbortSignal;\n /** When the hook was called, from the run's clock, in ISO 8601. */\n readonly timestamp: string;\n}\n\n/** What `transformContext` receives: the conversation as it stands before the model call. */\nexport interface ContextEvent extends HookEventBase {\n /** The system prompt. */\n readonly system: string;\n /** The whole conversation so far, never a view an earlier call's transform returned. */\n readonly messages: readonly Message[];\n /** The model the run was started with. */\n readonly model: ModelRef;\n /** The previous model call's usage. Absent on the first call. */\n readonly lastUsage?: Usage;\n}\n\n/** What `beforeModelCall` receives: the request about to be sent. */\nexport interface ModelCallEvent extends HookEventBase {\n /** The request: the system prompt, the messages `transformContext` returned and the tools this call sends. */\n readonly context: ModelContext;\n /** The options of this call, without the abort signal. */\n readonly options: CallOptions;\n}\n\n/** What `afterModelCall` receives: the model's finished response. */\nexport interface ModelResultEvent extends HookEventBase {\n /** The response, including a failed one, whose `stopReason` is `\"error\"`. */\n readonly message: AssistantMessage;\n}\n\n/** What `beforeToolCall` receives: a call whose input has passed the tool's schema. */\nexport interface ToolCallEvent extends HookEventBase {\n readonly callId: string;\n /** The tool's name. */\n readonly tool: string;\n /** The validated input. */\n readonly input: unknown;\n}\n\n/** What `afterToolCall` receives: the result of a call that executed, before the model reads it. */\nexport interface ToolResultEvent extends ToolCallEvent {\n readonly result: ToolResult;\n}\n\n/** What `shouldStop` receives, after a step's tool calls have their results. */\nexport interface StepEvent extends HookEventBase {\n /** The whole conversation so far, including this step's response and tool results. */\n readonly messages: readonly Message[];\n /** This step's model response. */\n readonly lastMessage: AssistantMessage;\n}\n\n/**\n * Changes to one model call's request. Every field is optional, and a change applies to that call only; the next\n * call starts again from the run's own settings.\n */\nexport interface ModelCallPatch {\n /** Replaces the system prompt for this call. */\n readonly system?: string;\n /** Replaces the messages sent for this call. The run's own transcript keeps its messages. */\n readonly messages?: readonly Message[];\n /**\n * The names of the tools to send, as the complete list: a tool left out is not sent, and a tool whose `exposure`\n * is `deferred` or `hidden` is sent when named. Tools always go out in definition order, whatever order this list\n * is in. A name that matches no tool throws an `SdkError` with code `invalid_hook_result`. A call to a tool that\n * was not sent gets the unknown-tool error.\n */\n readonly activeTools?: readonly string[];\n /** Makes this call with another model. */\n readonly model?: Model;\n /** Replaces the options of this call. */\n readonly options?: CallOptions;\n}\n\n/**\n * What `beforeToolCall` decides. `allow` runs the call, with `input` in place of the model's when given; the\n * replacement must pass the tool's schema. `deny` blocks the call, and the model reads the `reason`. `ask` pauses\n * the call for a person: the run signs a pending request for it with the run's `signer`, and ends\n * `awaiting_approval` once the step's other calls have their results. `reason` is shown to the approver and isn't\n * signed; `policyVersion` is signed. An `ask` may carry an `input`, which must pass the tool's schema like an\n * `allow`'s: the request is then signed over it, because it is the input the call would run with once approved.\n * `composeInterceptors()` passes an earlier gate's replacement on this way when a later gate asks.\n */\nexport type GateDecision =\n | { readonly decision: \"allow\"; readonly input?: unknown; readonly reason?: string }\n | { readonly decision: \"deny\"; readonly reason: string }\n | { readonly decision: \"ask\"; readonly input?: unknown; readonly reason?: string; readonly policyVersion?: string };\n\n/**\n * Changes to a tool's result. Each field present replaces the result's own. A replaced `outcome` is not available\n * here: a write's outcome is rendered into `content` once, so replace `content` instead.\n */\nexport type ToolResultPatch = Partial<Omit<ToolResult, \"outcome\">>;\n\n/**\n * What `shouldStop` decides. `true` or `{ stop: \"hook\" }` ends the run `stopped`, with the reason as `stoppedBy`\n * (`\"hook\"` for `true`). `{ stop: \"no_progress\" }` ends it `no_progress`. `{ continue }` keeps a run going that the\n * model ended by answering in text, adding the content as a user message. When the model's step called tools, the run goes on anyway and the content is\n * not added, so a hook that must reach the model should return it after a text answer. `false` leaves the decision to the run.\n */\nexport type StopDecision =\n | boolean\n | { readonly continue: string | readonly ContentBlock[] }\n | { readonly stop: \"no_progress\" | \"hook\"; readonly reason: string };\n\n/**\n * The six interceptors, in the order a step calls them: `transformContext`, `beforeModelCall`, the model call,\n * `afterModelCall`, then for each tool call `beforeToolCall` and `afterToolCall`, and last `shouldStop`. A run takes\n * one object; `composeInterceptors()` joins several. Each hook may be `async`.\n */\nexport interface Interceptors {\n /**\n * Returns the messages to send for this model call, such as a masked or summarised view of a long conversation.\n * The view reaches that call's request only: the next call's event, `result.messages` and `result.context` hold\n * the full history. Each call emits a `context_transformed` event with the message counts.\n */\n readonly transformContext?: (e: ContextEvent) => MaybePromise<readonly Message[]>;\n /** Changes the request about to be sent. Return nothing to leave it as it is. */\n readonly beforeModelCall?: (e: ModelCallEvent) => MaybePromise<OrNothing<ModelCallPatch>>;\n /**\n * Replaces the model's response. The transcript and the `model_call_end` event hold the replacement, and its tool\n * calls are the ones that run. The call's usage and cost stay those of the model's own response. If it throws\n * while the run fails closed, both hold an empty stand-in with `stopReason: \"error\"` and that usage and cost.\n */\n readonly afterModelCall?: (e: ModelResultEvent) => MaybePromise<OrNothing<{ readonly message?: AssistantMessage }>>;\n /**\n * The gate: decides whether a tool call runs, once for each call that passed validation, one call at a time in\n * model order, and before any call of the step executes. With no `beforeToolCall`, no gate stands in the way and\n * every registered tool is allowed. A gate that returns `ask` pauses the call, and the run ends `awaiting_approval`\n * with a signed pending request for it. A gate that throws denies the call unless `onFailure` is `\"continue\"`. A gate must return a\n * decision: returning nothing throws an `SdkError` with code `invalid_hook_result`.\n */\n readonly beforeToolCall?: (e: ToolCallEvent) => MaybePromise<GateDecision>;\n /**\n * Replaces fields of a result before the model reads it, and before `tool_call_end` reports it. It runs for calls\n * that executed, including ones whose `execute` threw, and not for calls that never ran, such as an unknown tool,\n * invalid input or a denied call. Return nothing to keep the result.\n */\n readonly afterToolCall?: (e: ToolResultEvent) => MaybePromise<OrNothing<ToolResultPatch>>;\n /** Ends the run, or keeps it going, after a step. It is not asked once the run has a stop reason of its own. */\n readonly shouldStop?: (e: StepEvent) => MaybePromise<StopDecision>;\n /**\n * What a hook that throws does. `\"fail_closed\"` (the default) stops the unsafe thing: a failed `beforeToolCall`\n * denies the call, a failed `afterToolCall` withholds the result, and a failed model-moment hook or `shouldStop`\n * ends the run with `stopReason: \"error\"` and `error.kind: \"hook\"`. `\"continue\"` skips the failed hook and goes on\n * as if it had returned nothing. Either way the run emits a `hook_error` event.\n */\n readonly onFailure?: \"fail_closed\" | \"continue\";\n}\n\n/**\n * Watches a run: called with each event, in order, and never able to change the run. A promise it returns is waited\n * for before the next event is delivered to it. A throw or a rejection becomes a `hook_error` event.\n */\nexport type Observer = (event: AgentEvent) => MaybePromise<void>;\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -3,20 +3,26 @@
|
|
|
3
3
|
* `continueRun()`, `runOrThrow()`), its events and results, the tools (their definitions, schemas, results and write
|
|
4
4
|
* outcomes) and the hooks: six interceptors that can change a run and observers that only watch it. The loop also
|
|
5
5
|
* holds the run's guards: a USD budget checked before each call, progress detection and a depth cap. A caller can
|
|
6
|
-
* steer a running agent or queue a follow-up, both applied at step boundaries.
|
|
7
|
-
*
|
|
6
|
+
* steer a running agent or queue a follow-up, both applied at step boundaries. A gate that asks for a person ends the
|
|
7
|
+
* run with a signed pending request; the signers, the input hash and the pending record are the safety package's,
|
|
8
|
+
* re-exported unchanged.
|
|
8
9
|
*/
|
|
9
10
|
export { projectCallCost } from "@buildanagent/gateway";
|
|
10
11
|
export { composeInterceptors } from "./compose.js";
|
|
11
12
|
export { isSdkError, RunStoppedError, SdkError, type SdkErrorCode } from "./errors.js";
|
|
12
13
|
export { AGENT_EVENT_TYPES, type AgentEvent, type AgentEventBody, type EventBase, type ModelCallRequest, type WarningCode, } from "./events.js";
|
|
13
14
|
export type { CallOptions, ContextEvent, GateDecision, HookEventBase, Interceptors, MaybePromise, ModelCallEvent, ModelCallPatch, ModelResultEvent, Observer, OrNothing, StepEvent, StopDecision, ToolCallEvent, ToolResultEvent, ToolResultPatch, } from "./hooks.js";
|
|
15
|
+
export { createPendingRequest, type PendingRequestFields } from "./pauses.js";
|
|
14
16
|
export { DEFAULT_PROGRESS, type ProgressPolicy } from "./progress.js";
|
|
15
|
-
export type { BudgetResult, Context, DoneResult, EndedResult, ErrorResult, NoProgressResult, ResultBase, RunError, RunResult, StoppedResult, UnfinishedResult, } from "./result.js";
|
|
17
|
+
export type { AwaitingApprovalResult, BudgetResult, Context, DoneResult, EndedResult, ErrorResult, NoProgressResult, ResultBase, RunError, RunResult, StoppedResult, UnfinishedResult, } from "./result.js";
|
|
16
18
|
export { continueRun, nestedRunDepth, type Run, type RunInput, type RunOptions, run, runOrThrow } from "./run.js";
|
|
17
19
|
export type { DeliveryKind, DeliveryReceipt } from "./steering.js";
|
|
18
20
|
export { type ClarificationToolOptions, clarificationTool, defineTool, type OutputToolOptions, outputTool, } from "./tools/define.js";
|
|
19
21
|
export type { JsonSchema, SchemaIssue, ToolAnnotations, ToolContext, ToolDefinition, ToolEffect, ToolExecutionMode, ToolExposure, ToolFailure, ToolResult, ToolSchema, } from "./tools/types.js";
|
|
22
|
+
export { isSafetyError, SafetyError, type SafetyErrorCode } from "./vendor/agent-safety/errors.js";
|
|
23
|
+
export { canonicalInputHash } from "./vendor/agent-safety/hash.js";
|
|
20
24
|
export type { WriteOutcome } from "./vendor/agent-safety/outcome.js";
|
|
25
|
+
export type { Resolution, SignedPendingRequest, SignPendingOptions } from "./vendor/agent-safety/pending.js";
|
|
26
|
+
export { type ApprovalSigner, ephemeralSigner, type HmacSignerOptions, hmacSigner, } from "./vendor/agent-safety/signer.js";
|
|
21
27
|
/** The package's name, `@buildanagent/sdk`. */
|
|
22
28
|
export declare const SDK_PACKAGE = "@buildanagent/sdk";
|
package/dist/index.js
CHANGED
|
@@ -3,17 +3,22 @@
|
|
|
3
3
|
* `continueRun()`, `runOrThrow()`), its events and results, the tools (their definitions, schemas, results and write
|
|
4
4
|
* outcomes) and the hooks: six interceptors that can change a run and observers that only watch it. The loop also
|
|
5
5
|
* holds the run's guards: a USD budget checked before each call, progress detection and a depth cap. A caller can
|
|
6
|
-
* steer a running agent or queue a follow-up, both applied at step boundaries.
|
|
7
|
-
*
|
|
6
|
+
* steer a running agent or queue a follow-up, both applied at step boundaries. A gate that asks for a person ends the
|
|
7
|
+
* run with a signed pending request; the signers, the input hash and the pending record are the safety package's,
|
|
8
|
+
* re-exported unchanged.
|
|
8
9
|
*/
|
|
9
10
|
// Re-exported so a caller that calls `Model.complete()` outside the loop projects a cost with the loop's own formula.
|
|
10
11
|
export { projectCallCost } from "@buildanagent/gateway";
|
|
11
12
|
export { composeInterceptors } from "./compose.js";
|
|
12
13
|
export { isSdkError, RunStoppedError, SdkError } from "./errors.js";
|
|
13
14
|
export { AGENT_EVENT_TYPES, } from "./events.js";
|
|
15
|
+
export { createPendingRequest } from "./pauses.js";
|
|
14
16
|
export { DEFAULT_PROGRESS } from "./progress.js";
|
|
15
17
|
export { continueRun, nestedRunDepth, run, runOrThrow } from "./run.js";
|
|
16
18
|
export { clarificationTool, defineTool, outputTool, } from "./tools/define.js";
|
|
19
|
+
export { isSafetyError, SafetyError } from "./vendor/agent-safety/errors.js";
|
|
20
|
+
export { canonicalInputHash } from "./vendor/agent-safety/hash.js";
|
|
21
|
+
export { ephemeralSigner, hmacSigner, } from "./vendor/agent-safety/signer.js";
|
|
17
22
|
/** The package's name, `@buildanagent/sdk`. */
|
|
18
23
|
export const SDK_PACKAGE = "@buildanagent/sdk";
|
|
19
24
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,sHAAsH;AACtH,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,QAAQ,EAAqB,MAAM,aAAa,CAAC;AACvF,OAAO,EACL,iBAAiB,GAMlB,MAAM,aAAa,CAAC;AAmBrB,OAAO,EAAE,oBAAoB,EAA6B,MAAM,aAAa,CAAC;AAC9E,OAAO,EAAE,gBAAgB,EAAuB,MAAM,eAAe,CAAC;AAetE,OAAO,EAAE,WAAW,EAAE,cAAc,EAA4C,GAAG,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAElH,OAAO,EAEL,iBAAiB,EACjB,UAAU,EAEV,UAAU,GACX,MAAM,mBAAmB,CAAC;AAc3B,OAAO,EAAE,aAAa,EAAE,WAAW,EAAwB,MAAM,iCAAiC,CAAC;AACnG,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAGnE,OAAO,EAEL,eAAe,EAEf,UAAU,GACX,MAAM,iCAAiC,CAAC;AAEzC,+CAA+C;AAC/C,MAAM,CAAC,MAAM,WAAW,GAAG,mBAAmB,CAAC","sourcesContent":["/**\n * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the loop (`run()`,\n * `continueRun()`, `runOrThrow()`), its events and results, the tools (their definitions, schemas, results and write\n * outcomes) and the hooks: six interceptors that can change a run and observers that only watch it. The loop also\n * holds the run's guards: a USD budget checked before each call, progress detection and a depth cap. A caller can\n * steer a running agent or queue a follow-up, both applied at step boundaries. A gate that asks for a person ends the\n * run with a signed pending request; the signers, the input hash and the pending record are the safety package's,\n * re-exported unchanged.\n */\n// Re-exported so a caller that calls `Model.complete()` outside the loop projects a cost with the loop's own formula.\nexport { projectCallCost } from \"@buildanagent/gateway\";\nexport { composeInterceptors } from \"./compose.js\";\nexport { isSdkError, RunStoppedError, SdkError, type SdkErrorCode } from \"./errors.js\";\nexport {\n AGENT_EVENT_TYPES,\n type AgentEvent,\n type AgentEventBody,\n type EventBase,\n type ModelCallRequest,\n type WarningCode,\n} from \"./events.js\";\nexport type {\n CallOptions,\n ContextEvent,\n GateDecision,\n HookEventBase,\n Interceptors,\n MaybePromise,\n ModelCallEvent,\n ModelCallPatch,\n ModelResultEvent,\n Observer,\n OrNothing,\n StepEvent,\n StopDecision,\n ToolCallEvent,\n ToolResultEvent,\n ToolResultPatch,\n} from \"./hooks.js\";\nexport { createPendingRequest, type PendingRequestFields } from \"./pauses.js\";\nexport { DEFAULT_PROGRESS, type ProgressPolicy } from \"./progress.js\";\nexport type {\n AwaitingApprovalResult,\n BudgetResult,\n Context,\n DoneResult,\n EndedResult,\n ErrorResult,\n NoProgressResult,\n ResultBase,\n RunError,\n RunResult,\n StoppedResult,\n UnfinishedResult,\n} from \"./result.js\";\nexport { continueRun, nestedRunDepth, type Run, type RunInput, type RunOptions, run, runOrThrow } from \"./run.js\";\nexport type { DeliveryKind, DeliveryReceipt } from \"./steering.js\";\nexport {\n type ClarificationToolOptions,\n clarificationTool,\n defineTool,\n type OutputToolOptions,\n outputTool,\n} from \"./tools/define.js\";\nexport type {\n JsonSchema,\n SchemaIssue,\n ToolAnnotations,\n ToolContext,\n ToolDefinition,\n ToolEffect,\n ToolExecutionMode,\n ToolExposure,\n ToolFailure,\n ToolResult,\n ToolSchema,\n} from \"./tools/types.js\";\nexport { isSafetyError, SafetyError, type SafetyErrorCode } from \"./vendor/agent-safety/errors.js\";\nexport { canonicalInputHash } from \"./vendor/agent-safety/hash.js\";\nexport type { WriteOutcome } from \"./vendor/agent-safety/outcome.js\";\nexport type { Resolution, SignedPendingRequest, SignPendingOptions } from \"./vendor/agent-safety/pending.js\";\nexport {\n type ApprovalSigner,\n ephemeralSigner,\n type HmacSignerOptions,\n hmacSigner,\n} from \"./vendor/agent-safety/signer.js\";\n\n/** The package's name, `@buildanagent/sdk`. */\nexport const SDK_PACKAGE = \"@buildanagent/sdk\";\n"]}
|
package/dist/loop.d.ts
CHANGED
|
@@ -15,6 +15,7 @@ import type { RunResult } from "./result.js";
|
|
|
15
15
|
import type { SteeringQueue } from "./steering.js";
|
|
16
16
|
import type { Clock } from "./testing/determinism.js";
|
|
17
17
|
import { type AnyTool } from "./tools/pipeline.js";
|
|
18
|
+
import type { ApprovalSigner } from "./vendor/agent-safety/signer.js";
|
|
18
19
|
/** Everything one run needs, fixed when it starts. */
|
|
19
20
|
export interface LoopSetup {
|
|
20
21
|
readonly runId: string;
|
|
@@ -44,6 +45,10 @@ export interface LoopSetup {
|
|
|
44
45
|
readonly steering: SteeringQueue;
|
|
45
46
|
readonly signal: AbortSignal;
|
|
46
47
|
readonly clock: Clock;
|
|
48
|
+
/** Signs the pending request of each call a gate asks about (D5). */
|
|
49
|
+
readonly signer: ApprovalSigner;
|
|
50
|
+
/** Makes each pending request's id. */
|
|
51
|
+
readonly nextId: () => string;
|
|
47
52
|
}
|
|
48
53
|
/** Sends one event; the run adds the `EventBase` fields. */
|
|
49
54
|
export type Emit = (body: AgentEventBody, stepIndex: number) => void;
|
package/dist/loop.js
CHANGED
|
@@ -39,6 +39,13 @@ class LoopState {
|
|
|
39
39
|
output;
|
|
40
40
|
/** Set when the run was kept going to deliver a follow-up, so the next step boundary applies the follow-ups too. */
|
|
41
41
|
releaseFollowUps = false;
|
|
42
|
+
/** The signed requests of the calls that gates paused, in model order. */
|
|
43
|
+
pending = [];
|
|
44
|
+
/**
|
|
45
|
+
* The input each pending request signs, by request id. It has no prototype, because an id comes from the host's
|
|
46
|
+
* `idGenerator` and `"__proto__"` must be stored as a key like any other.
|
|
47
|
+
*/
|
|
48
|
+
pendingInputs = Object.create(null);
|
|
42
49
|
constructor(setup, emit, drain) {
|
|
43
50
|
this.setup = setup;
|
|
44
51
|
this.emit = emit;
|
|
@@ -53,6 +60,8 @@ class LoopState {
|
|
|
53
60
|
clock: setup.clock,
|
|
54
61
|
stepIndex: () => this.stepIndex,
|
|
55
62
|
send: (body) => this.send(body),
|
|
63
|
+
signer: setup.signer,
|
|
64
|
+
nextId: setup.nextId,
|
|
56
65
|
});
|
|
57
66
|
}
|
|
58
67
|
/** The wire form of each of `tools`, as a request sends them. */
|
|
@@ -262,6 +271,11 @@ async function runTools(state, message) {
|
|
|
262
271
|
...state.hooks.pipelineHooks(),
|
|
263
272
|
onStart: (call) => state.send({ type: "tool_call_start", callId: call.callId, tool: call.name, input: call.input }),
|
|
264
273
|
onUpdate: (callId, details) => state.send({ type: "tool_call_update", callId, details }),
|
|
274
|
+
onPause: ({ request, input }) => {
|
|
275
|
+
state.pending.push(request);
|
|
276
|
+
state.pendingInputs[request.id] = input;
|
|
277
|
+
state.send({ type: "approval_request", request, input });
|
|
278
|
+
},
|
|
265
279
|
onResult: (entry) => {
|
|
266
280
|
state.append(toolMessage(entry));
|
|
267
281
|
if (output !== undefined && entry.call.name === output.name && entry.result.isError !== true) {
|
|
@@ -280,8 +294,9 @@ function runErrorOf(message) {
|
|
|
280
294
|
return { kind: error.kind, message: error.message, ...(error.status === undefined ? {} : { status: error.status }) };
|
|
281
295
|
}
|
|
282
296
|
/**
|
|
283
|
-
* The stop check after one step. A finished answer
|
|
284
|
-
* to change it; otherwise an abort stops the run before the step cap does. A
|
|
297
|
+
* The stop check after one step. A pause, a finished answer or a question for the user wins over an abort that came
|
|
298
|
+
* too late to change it; otherwise an abort stops the run before the step cap does. A pause wins over a finished
|
|
299
|
+
* answer too, because its call is still waiting. A text answer cut off at the output limit
|
|
285
300
|
* also counts as finished: its message keeps `stopReason: "length"`.
|
|
286
301
|
*/
|
|
287
302
|
function stopCheck(state, message, results) {
|
|
@@ -289,6 +304,11 @@ function stopCheck(state, message, results) {
|
|
|
289
304
|
return { stopReason: "error", error: runErrorOf(message) };
|
|
290
305
|
if (message.stopReason === "aborted")
|
|
291
306
|
return { stopReason: "aborted" };
|
|
307
|
+
// A paused call is still waiting, so the run can't count as finished, and the pause is signed and stored with the
|
|
308
|
+
// context, so it outlasts an abort that came while the step's other calls ran.
|
|
309
|
+
if (state.pending.length > 0) {
|
|
310
|
+
return { stopReason: "awaiting_approval", pending: [...state.pending], pendingInputs: { ...state.pendingInputs } };
|
|
311
|
+
}
|
|
292
312
|
const finished = results.length === 0 || results.some(({ result }) => result.terminate === true && !result.isError);
|
|
293
313
|
if (finished)
|
|
294
314
|
return { stopReason: "done", output: state.output };
|
|
@@ -427,9 +447,12 @@ function closeAborted(state) {
|
|
|
427
447
|
});
|
|
428
448
|
}
|
|
429
449
|
function resultOf(state, outcome) {
|
|
450
|
+
const pending = outcome.stopReason === "awaiting_approval"
|
|
451
|
+
? { pending: [...outcome.pending], pendingInputs: { ...outcome.pendingInputs } }
|
|
452
|
+
: {};
|
|
430
453
|
const base = {
|
|
431
454
|
messages: state.added,
|
|
432
|
-
context: { system: state.setup.system, messages: state.messages },
|
|
455
|
+
context: { system: state.setup.system, messages: state.messages, ...pending },
|
|
433
456
|
usage: state.usage,
|
|
434
457
|
cost: state.cost ?? { ...NO_COST },
|
|
435
458
|
steps: state.steps,
|