@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 @@
|
|
|
1
|
+
{"version":3,"file":"hook-runner.js","sourceRoot":"","sources":["../src/hook-runner.ts"],"names":[],"mappings":"AAiBA,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;AAE1B,OAAO,EAAwB,iBAAiB,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAEjF,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,EAAkC,aAAa,EAAwB,MAAM,qBAAqB,CAAC;AAE1G,OAAO,EAAE,aAAa,EAAwB,MAAM,iCAAiC,CAAC;AACtF,OAAO,EAIL,gBAAgB,GACjB,MAAM,kCAAkC,CAAC;AAG1C,uHAAuH;AACvH,MAAM,OAAO,WAAY,SAAQ,QAAQ;IACrB,IAAI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C;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. Under `blockingApprovals()` the runner instead emits the request, waits for\n * the handler's answer, checks it against the request, and allows or denies the call. A tool's clarification question\n * is signed through the same path. A pause that can't be signed never pauses unsigned: the call is blocked instead,\n * 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 { type ApprovalHandler, blockingHandlerOf, 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 {\n type PendingFields,\n type Resolution,\n type SignedPendingRequest,\n verifyResolution,\n} 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/**\n * A resolution's optional `reason` or `by`, kept only when it is a string. A resolution comes unchecked from the\n * host's store or handler, so any other value is dropped rather than shown to the model as `null` or `[object Object]`.\n */\nexport function textOf(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n\n/** The error result of a call a person denied, with their reason when they gave one. */\nexport function denied(\n tool: string,\n reason: string | undefined,\n requestId: string,\n by: string | undefined,\n): ToolResult {\n const text =\n reason === undefined || reason === \"\"\n ? `Tool call \"${tool}\" was denied by the approver.`\n : `Tool call \"${tool}\" was denied: ${reason}`;\n return blocked(text, { decision: \"deny\", requestId, ...(by === undefined ? {} : { by }) });\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/** The reason a request carries when `continueRun()` asks again for a call whose earlier request failed its check. */\nconst REISSUED_REASON = \"The earlier request for this call could not be verified, so it needs a new answer.\";\n\n/** Resolves to `ABORTED` once `signal` fires, or to what `promise` resolves to if that comes first. */\nconst ABORTED = Symbol(\"aborted\");\nasync function unlessAborted<T>(promise: Promise<T>, signal: AbortSignal): Promise<T | typeof ABORTED> {\n let stop: (() => void) | undefined;\n const aborted = new Promise<typeof ABORTED>((resolve) => {\n stop = () => resolve(ABORTED);\n if (signal.aborted) stop();\n else signal.addEventListener(\"abort\", stop, { once: true });\n });\n try {\n return await Promise.race([promise, aborted]);\n } finally {\n if (stop !== undefined) signal.removeEventListener(\"abort\", stop);\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 readonly #requestIds = new Set<string>();\n readonly #blocking: ApprovalHandler | undefined;\n\n constructor(setup: HookRunnerSetup) {\n this.#setup = setup;\n this.#hooks = setup.interceptors;\n this.#continues = setup.interceptors.onFailure === \"continue\";\n this.#blocking = blockingHandlerOf(setup.interceptors);\n }\n\n /**\n * Marks request ids that already wait in the context a `continueRun()` started from, so a request this run signs\n * never takes one of them.\n */\n reserveRequestIds(ids: Iterable<string>): void {\n for (const id of ids) this.#requestIds.add(id);\n }\n\n /**\n * The gate `continueRun()` puts in front of a call whose stored request failed its check: the run's own gate is\n * asked as for a new call, but the call never runs. A deny still blocks it and an `ask` pauses it as usual, and an\n * `allow`, or no gate at all, pauses it too, with a new request over the input the gate allowed.\n */\n reissueGate(): NonNullable<PipelineContext[\"gate\"]> {\n return async (e) => {\n // A call asked again never blocks on a handler: its new request is returned with the context.\n const outcome = this.#hooks.beforeToolCall === undefined ? undefined : await this.#gate(e, false);\n if (outcome !== undefined && (\"blocked\" in outcome || \"paused\" in outcome)) return outcome;\n const input = outcome === undefined ? e.input : outcome.input;\n return this.#sign(\n e.tool.name,\n { kind: \"approval\", callId: e.call.callId, tool: e.tool.name, input, reason: REISSUED_REASON },\n input,\n );\n };\n }\n\n /**\n * Signs the clarification request of a call whose tool asked the user `question`, over the input the tool ran\n * with. A question that can't be signed blocks the call, as an approval does.\n */\n clarify(call: ToolCall, input: unknown, question: string): Promise<GateOutcome> {\n return this.#sign(\n call.name,\n { kind: \"clarification\", callId: call.callId, tool: call.name, input, question },\n input,\n );\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(\n input: { call: ToolCall; tool: AnyTool; input: unknown },\n block = true,\n ): 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, block)\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. Under `blockingApprovals()`, the request is emitted and answered here instead.\n */\n async #pause(\n call: ToolCall,\n tool: AnyTool,\n seen: unknown,\n decision: AskDecision,\n block: boolean,\n ): Promise<GateOutcome | undefined> {\n const { reason, policyVersion } = decision;\n const input = thawedCopy(decision.input === undefined ? seen : await this.#replacement(tool, decision.input));\n const fields: PendingFields = {\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 const outcome = await this.#sign(tool.name, fields, input);\n if (!block || this.#blocking === undefined || !(\"paused\" in outcome)) return outcome;\n return this.#waitFor(this.#blocking, call, tool.name, outcome.paused, input, decision.input === undefined);\n }\n\n /** Signs one pending request through the one signing path, or blocks the call when it can't be signed. */\n async #sign(tool: string, fields: PendingFields, input: unknown): Promise<GateOutcome> {\n const { signer, clock } = this.#setup;\n let request: SignedPendingRequest;\n try {\n request = await signPause(fields, signer, {\n generateId: () => this.#requestId(),\n now: () => new Date(clock.now()),\n });\n } catch (error) {\n return this.#unsigned(tool, 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, \"duplicate_request_id\");\n this.#requestIds.add(request.id);\n return { paused: request, input };\n }\n\n /**\n * The blocking form of a pause: emit the signed request, wait for the handler, and check its answer against the\n * request before the call may run. Every failure denies the call; nothing here lets it run unanswered.\n */\n async #waitFor(\n handler: ApprovalHandler,\n call: ToolCall,\n tool: string,\n request: SignedPendingRequest,\n input: unknown,\n unchanged: boolean,\n ): Promise<GateOutcome | undefined> {\n const { signal, signer } = this.#setup;\n this.#setup.send({ type: \"approval_request\", request, input });\n const refuse = (why: string, error: string): GateOutcome => {\n this.#setup.send({ type: \"hook_error\", hook: \"blockingApprovals\", error });\n return {\n blocked: blocked(`Tool call \"${tool}\" was not run, because ${why}.`, {\n decision: \"ask\",\n requestId: request.id,\n }),\n };\n };\n let answer: unknown;\n try {\n answer = await unlessAborted(Promise.resolve(handler(request, Object.freeze({ input, signal }))), signal);\n } catch (error) {\n return refuse(\"its approval handler failed\", messageOf(error));\n }\n if (answer === ABORTED) {\n const text = `Tool call \"${tool}\" was not run, because the run was aborted while it waited for approval.`;\n return { blocked: blocked(text, { decision: \"ask\", requestId: request.id }) };\n }\n let check: Awaited<ReturnType<typeof verifyResolution>>;\n try {\n check = await verifyResolution(request, answer as Resolution, {\n signer,\n call: { callId: call.callId, tool, input },\n });\n } catch {\n // A custom signer whose verify() throws fails the check; its message may hold anything, so it isn't passed on.\n return refuse(\"its approval could not be verified\", \"the approval was refused (error)\");\n }\n if (!check.ok) return refuse(\"its approval could not be verified\", `the approval was refused (${check.cause})`);\n const resolution = check.resolution;\n // An unchanged input is the checked one the gate saw, which the pipeline runs as it is; a replacement is passed on.\n if (\"decision\" in resolution && resolution.decision === \"allow\") return unchanged ? undefined : { input };\n const reason = \"reason\" in resolution ? textOf(resolution.reason) : undefined;\n return { blocked: denied(tool, reason, request.id, textOf(resolution.by)) };\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
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The hook types: six interceptors that can change a run, and the observer that only watches it. Each interceptor
|
|
3
|
+
* takes one event object and returns a replacement, never mutating its input, because the event's data is frozen.
|
|
4
|
+
*/
|
|
5
|
+
import type { AssistantMessage, ContentBlock, Message, Model, ModelCallOptions, ModelContext, ModelRef, Usage } from "@buildanagent/gateway";
|
|
6
|
+
import type { AgentEvent } from "./events.js";
|
|
7
|
+
import type { ToolResult } from "./tools/types.js";
|
|
8
|
+
/** A value or a promise of one: a hook may be a plain function or an `async` one. */
|
|
9
|
+
export type MaybePromise<T> = T | Promise<T>;
|
|
10
|
+
/**
|
|
11
|
+
* A value, or nothing: what a hook that may change something returns. `void` lets an `async` hook that has nothing
|
|
12
|
+
* to change simply end, where `undefined` would force it to return explicitly.
|
|
13
|
+
*/
|
|
14
|
+
export type OrNothing<T> = T | void;
|
|
15
|
+
/** The options of one model call, without the abort signal, which the run supplies. */
|
|
16
|
+
export type CallOptions = Omit<ModelCallOptions, "signal">;
|
|
17
|
+
/** The fields every hook event carries. */
|
|
18
|
+
export interface HookEventBase {
|
|
19
|
+
/** The run's id. */
|
|
20
|
+
readonly runId: string;
|
|
21
|
+
/** The index of the model call the hook belongs to, counted from 0. */
|
|
22
|
+
readonly stepIndex: number;
|
|
23
|
+
/** The tool call's id, for the two tool hooks; absent for the others. */
|
|
24
|
+
readonly callId?: string;
|
|
25
|
+
/** The run's abort signal. Pass it on to any I/O the hook does. */
|
|
26
|
+
readonly signal: AbortSignal;
|
|
27
|
+
/** When the hook was called, from the run's clock, in ISO 8601. */
|
|
28
|
+
readonly timestamp: string;
|
|
29
|
+
}
|
|
30
|
+
/** What `transformContext` receives: the conversation as it stands before the model call. */
|
|
31
|
+
export interface ContextEvent extends HookEventBase {
|
|
32
|
+
/** The system prompt. */
|
|
33
|
+
readonly system: string;
|
|
34
|
+
/** The whole conversation so far, never a view an earlier call's transform returned. */
|
|
35
|
+
readonly messages: readonly Message[];
|
|
36
|
+
/** The model the run was started with. */
|
|
37
|
+
readonly model: ModelRef;
|
|
38
|
+
/** The previous model call's usage. Absent on the first call. */
|
|
39
|
+
readonly lastUsage?: Usage;
|
|
40
|
+
}
|
|
41
|
+
/** What `beforeModelCall` receives: the request about to be sent. */
|
|
42
|
+
export interface ModelCallEvent extends HookEventBase {
|
|
43
|
+
/** The request: the system prompt, the messages `transformContext` returned and the tools this call sends. */
|
|
44
|
+
readonly context: ModelContext;
|
|
45
|
+
/** The options of this call, without the abort signal. */
|
|
46
|
+
readonly options: CallOptions;
|
|
47
|
+
}
|
|
48
|
+
/** What `afterModelCall` receives: the model's finished response. */
|
|
49
|
+
export interface ModelResultEvent extends HookEventBase {
|
|
50
|
+
/** The response, including a failed one, whose `stopReason` is `"error"`. */
|
|
51
|
+
readonly message: AssistantMessage;
|
|
52
|
+
}
|
|
53
|
+
/** What `beforeToolCall` receives: a call whose input has passed the tool's schema. */
|
|
54
|
+
export interface ToolCallEvent extends HookEventBase {
|
|
55
|
+
readonly callId: string;
|
|
56
|
+
/** The tool's name. */
|
|
57
|
+
readonly tool: string;
|
|
58
|
+
/** The validated input. */
|
|
59
|
+
readonly input: unknown;
|
|
60
|
+
}
|
|
61
|
+
/** What `afterToolCall` receives: the result of a call that executed, before the model reads it. */
|
|
62
|
+
export interface ToolResultEvent extends ToolCallEvent {
|
|
63
|
+
readonly result: ToolResult;
|
|
64
|
+
}
|
|
65
|
+
/** What `shouldStop` receives, after a step's tool calls have their results. */
|
|
66
|
+
export interface StepEvent extends HookEventBase {
|
|
67
|
+
/** The whole conversation so far, including this step's response and tool results. */
|
|
68
|
+
readonly messages: readonly Message[];
|
|
69
|
+
/** This step's model response. */
|
|
70
|
+
readonly lastMessage: AssistantMessage;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Changes to one model call's request. Every field is optional, and a change applies to that call only; the next
|
|
74
|
+
* call starts again from the run's own settings.
|
|
75
|
+
*/
|
|
76
|
+
export interface ModelCallPatch {
|
|
77
|
+
/** Replaces the system prompt for this call. */
|
|
78
|
+
readonly system?: string;
|
|
79
|
+
/** Replaces the messages sent for this call. The run's own transcript keeps its messages. */
|
|
80
|
+
readonly messages?: readonly Message[];
|
|
81
|
+
/**
|
|
82
|
+
* The names of the tools to send, as the complete list: a tool left out is not sent, and a tool whose `exposure`
|
|
83
|
+
* is `deferred` or `hidden` is sent when named. Tools always go out in definition order, whatever order this list
|
|
84
|
+
* is in. A name that matches no tool throws an `SdkError` with code `invalid_hook_result`. A call to a tool that
|
|
85
|
+
* was not sent gets the unknown-tool error.
|
|
86
|
+
*/
|
|
87
|
+
readonly activeTools?: readonly string[];
|
|
88
|
+
/** Makes this call with another model. */
|
|
89
|
+
readonly model?: Model;
|
|
90
|
+
/** Replaces the options of this call. */
|
|
91
|
+
readonly options?: CallOptions;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
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` 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, or, under `blockingApprovals()`, waits for the
|
|
98
|
+
* handler's answer. `reason` is shown to the approver and isn't
|
|
99
|
+
* signed; `policyVersion` is signed. An `ask` may carry an `input`, which must pass the tool's schema like an
|
|
100
|
+
* `allow`'s: the request is then signed over it, because it is the input the call would run with once approved.
|
|
101
|
+
* `composeInterceptors()` passes an earlier gate's replacement on this way when a later gate asks.
|
|
102
|
+
*/
|
|
103
|
+
export type GateDecision = {
|
|
104
|
+
readonly decision: "allow";
|
|
105
|
+
readonly input?: unknown;
|
|
106
|
+
readonly reason?: string;
|
|
107
|
+
} | {
|
|
108
|
+
readonly decision: "deny";
|
|
109
|
+
readonly reason: string;
|
|
110
|
+
} | {
|
|
111
|
+
readonly decision: "ask";
|
|
112
|
+
readonly input?: unknown;
|
|
113
|
+
readonly reason?: string;
|
|
114
|
+
readonly policyVersion?: string;
|
|
115
|
+
};
|
|
116
|
+
/**
|
|
117
|
+
* Changes to a tool's result. Each field present replaces the result's own. A replaced `outcome` is not available
|
|
118
|
+
* here: a write's outcome is rendered into `content` once, so replace `content` instead.
|
|
119
|
+
*/
|
|
120
|
+
export type ToolResultPatch = Partial<Omit<ToolResult, "outcome">>;
|
|
121
|
+
/**
|
|
122
|
+
* What `shouldStop` decides. `true` or `{ stop: "hook" }` ends the run `stopped`, with the reason as `stoppedBy`
|
|
123
|
+
* (`"hook"` for `true`). `{ stop: "no_progress" }` ends it `no_progress`. `{ continue }` keeps a run going that the
|
|
124
|
+
* 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
|
|
125
|
+
* not added, so a hook that must reach the model should return it after a text answer. `false` leaves the decision to the run.
|
|
126
|
+
*/
|
|
127
|
+
export type StopDecision = boolean | {
|
|
128
|
+
readonly continue: string | readonly ContentBlock[];
|
|
129
|
+
} | {
|
|
130
|
+
readonly stop: "no_progress" | "hook";
|
|
131
|
+
readonly reason: string;
|
|
132
|
+
};
|
|
133
|
+
/**
|
|
134
|
+
* The six interceptors, in the order a step calls them: `transformContext`, `beforeModelCall`, the model call,
|
|
135
|
+
* `afterModelCall`, then for each tool call `beforeToolCall` and `afterToolCall`, and last `shouldStop`. A run takes
|
|
136
|
+
* one object; `composeInterceptors()` joins several. Each hook may be `async`.
|
|
137
|
+
*/
|
|
138
|
+
export interface Interceptors {
|
|
139
|
+
/**
|
|
140
|
+
* Returns the messages to send for this model call, such as a masked or summarised view of a long conversation.
|
|
141
|
+
* The view reaches that call's request only: the next call's event, `result.messages` and `result.context` hold
|
|
142
|
+
* the full history. Each call emits a `context_transformed` event with the message counts.
|
|
143
|
+
*/
|
|
144
|
+
readonly transformContext?: (e: ContextEvent) => MaybePromise<readonly Message[]>;
|
|
145
|
+
/** Changes the request about to be sent. Return nothing to leave it as it is. */
|
|
146
|
+
readonly beforeModelCall?: (e: ModelCallEvent) => MaybePromise<OrNothing<ModelCallPatch>>;
|
|
147
|
+
/**
|
|
148
|
+
* Replaces the model's response. The transcript and the `model_call_end` event hold the replacement, and its tool
|
|
149
|
+
* calls are the ones that run. The call's usage and cost stay those of the model's own response. If it throws
|
|
150
|
+
* while the run fails closed, both hold an empty stand-in with `stopReason: "error"` and that usage and cost.
|
|
151
|
+
*/
|
|
152
|
+
readonly afterModelCall?: (e: ModelResultEvent) => MaybePromise<OrNothing<{
|
|
153
|
+
readonly message?: AssistantMessage;
|
|
154
|
+
}>>;
|
|
155
|
+
/**
|
|
156
|
+
* The gate: decides whether a tool call runs, once for each call that passed validation, one call at a time in
|
|
157
|
+
* model order, and before any call of the step executes. With no `beforeToolCall`, no gate stands in the way and
|
|
158
|
+
* every registered tool is allowed. A gate that returns `ask` pauses the call, and the run ends `awaiting_approval`
|
|
159
|
+
* with a signed pending request for it. A gate that throws denies the call unless `onFailure` is `"continue"`. A gate must return a
|
|
160
|
+
* decision: returning nothing throws an `SdkError` with code `invalid_hook_result`.
|
|
161
|
+
*/
|
|
162
|
+
readonly beforeToolCall?: (e: ToolCallEvent) => MaybePromise<GateDecision>;
|
|
163
|
+
/**
|
|
164
|
+
* Replaces fields of a result before the model reads it, and before `tool_call_end` reports it. It runs for calls
|
|
165
|
+
* that executed, including ones whose `execute` threw, and not for calls that never ran, such as an unknown tool,
|
|
166
|
+
* invalid input or a denied call. Return nothing to keep the result.
|
|
167
|
+
*/
|
|
168
|
+
readonly afterToolCall?: (e: ToolResultEvent) => MaybePromise<OrNothing<ToolResultPatch>>;
|
|
169
|
+
/** Ends the run, or keeps it going, after a step. It is not asked once the run has a stop reason of its own. */
|
|
170
|
+
readonly shouldStop?: (e: StepEvent) => MaybePromise<StopDecision>;
|
|
171
|
+
/**
|
|
172
|
+
* What a hook that throws does. `"fail_closed"` (the default) stops the unsafe thing: a failed `beforeToolCall`
|
|
173
|
+
* denies the call, a failed `afterToolCall` withholds the result, and a failed model-moment hook or `shouldStop`
|
|
174
|
+
* ends the run with `stopReason: "error"` and `error.kind: "hook"`. `"continue"` skips the failed hook and goes on
|
|
175
|
+
* as if it had returned nothing. Either way the run emits a `hook_error` event.
|
|
176
|
+
*/
|
|
177
|
+
readonly onFailure?: "fail_closed" | "continue";
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Watches a run: called with each event, in order, and never able to change the run. A promise it returns is waited
|
|
181
|
+
* for before the next event is delivered to it. A throw or a rejection becomes a `hook_error` event.
|
|
182
|
+
*/
|
|
183
|
+
export type Observer = (event: AgentEvent) => MaybePromise<void>;
|
package/dist/hooks.js
ADDED
|
@@ -0,0 +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` 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, or, under `blockingApprovals()`, waits for the\n * handler's answer. `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
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`.
|
|
3
|
-
*
|
|
4
|
-
*
|
|
2
|
+
* `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the loop (`run()`,
|
|
3
|
+
* `continueRun()`, `runOrThrow()`), its events and results, the tools (their definitions, schemas, results and write
|
|
4
|
+
* outcomes) and the hooks: six interceptors that can change a run and observers that only watch it. The loop also
|
|
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. A gate that asks for a person, or a
|
|
7
|
+
* tool that asks the user a question, ends the run with a signed pending request, which `continueRun()` resumes with
|
|
8
|
+
* resolutions, in this process or another; `blockingApprovals()` answers approvals inside the run instead. The
|
|
9
|
+
* signers, the input hash and the pending record are the safety package's, re-exported unchanged.
|
|
5
10
|
*/
|
|
11
|
+
export { projectCallCost } from "@buildanagent/gateway";
|
|
12
|
+
export { composeInterceptors } from "./compose.js";
|
|
13
|
+
export { isSdkError, RunStoppedError, SdkError, type SdkErrorCode } from "./errors.js";
|
|
14
|
+
export { AGENT_EVENT_TYPES, type AgentEvent, type AgentEventBody, type EventBase, type ModelCallRequest, type ResolutionRejectionCause, type WarningCode, } from "./events.js";
|
|
15
|
+
export type { CallOptions, ContextEvent, GateDecision, HookEventBase, Interceptors, MaybePromise, ModelCallEvent, ModelCallPatch, ModelResultEvent, Observer, OrNothing, StepEvent, StopDecision, ToolCallEvent, ToolResultEvent, ToolResultPatch, } from "./hooks.js";
|
|
16
|
+
export { type ApprovalDetails, type ApprovalHandler, blockingApprovals, createPendingRequest, type PendingRequestFields, } from "./pauses.js";
|
|
17
|
+
export { DEFAULT_PROGRESS, type ProgressPolicy } from "./progress.js";
|
|
18
|
+
export type { AwaitingApprovalResult, BudgetResult, ClarificationRequestedResult, Context, DoneResult, EndedResult, ErrorResult, NoProgressResult, ResultBase, RunError, RunResult, StoppedResult, UnfinishedResult, } from "./result.js";
|
|
19
|
+
export { type ContinueOptions, continueRun, nestedRunDepth, type Run, type RunInput, type RunOptions, run, runOrThrow, } from "./run.js";
|
|
20
|
+
export type { DeliveryKind, DeliveryReceipt } from "./steering.js";
|
|
21
|
+
export { type ClarificationToolOptions, clarificationTool, defineTool, type OutputToolOptions, outputTool, } from "./tools/define.js";
|
|
22
|
+
export type { JsonSchema, SchemaIssue, ToolAnnotations, ToolContext, ToolDefinition, ToolEffect, ToolExecutionMode, ToolExposure, ToolFailure, ToolResult, ToolSchema, } from "./tools/types.js";
|
|
23
|
+
export { isSafetyError, SafetyError, type SafetyErrorCode } from "./vendor/agent-safety/errors.js";
|
|
24
|
+
export { canonicalInputHash } from "./vendor/agent-safety/hash.js";
|
|
25
|
+
export type { WriteOutcome } from "./vendor/agent-safety/outcome.js";
|
|
26
|
+
export type { Recheck, RejectionCause, Resolution, SignedPendingRequest, SignPendingOptions, } from "./vendor/agent-safety/pending.js";
|
|
27
|
+
export { type ApprovalSigner, ephemeralSigner, type HmacSignerOptions, hmacSigner, } from "./vendor/agent-safety/signer.js";
|
|
28
|
+
/** The package's name, `@buildanagent/sdk`. */
|
|
6
29
|
export declare const SDK_PACKAGE = "@buildanagent/sdk";
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,25 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`.
|
|
3
|
-
*
|
|
4
|
-
*
|
|
2
|
+
* `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the loop (`run()`,
|
|
3
|
+
* `continueRun()`, `runOrThrow()`), its events and results, the tools (their definitions, schemas, results and write
|
|
4
|
+
* outcomes) and the hooks: six interceptors that can change a run and observers that only watch it. The loop also
|
|
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. A gate that asks for a person, or a
|
|
7
|
+
* tool that asks the user a question, ends the run with a signed pending request, which `continueRun()` resumes with
|
|
8
|
+
* resolutions, in this process or another; `blockingApprovals()` answers approvals inside the run instead. The
|
|
9
|
+
* signers, the input hash and the pending record are the safety package's, re-exported unchanged.
|
|
5
10
|
*/
|
|
11
|
+
// Re-exported so a caller that calls `Model.complete()` outside the loop projects a cost with the loop's own formula.
|
|
12
|
+
export { projectCallCost } from "@buildanagent/gateway";
|
|
13
|
+
export { composeInterceptors } from "./compose.js";
|
|
14
|
+
export { isSdkError, RunStoppedError, SdkError } from "./errors.js";
|
|
15
|
+
export { AGENT_EVENT_TYPES, } from "./events.js";
|
|
16
|
+
export { blockingApprovals, createPendingRequest, } from "./pauses.js";
|
|
17
|
+
export { DEFAULT_PROGRESS } from "./progress.js";
|
|
18
|
+
export { continueRun, nestedRunDepth, run, runOrThrow, } from "./run.js";
|
|
19
|
+
export { clarificationTool, defineTool, outputTool, } from "./tools/define.js";
|
|
20
|
+
export { isSafetyError, SafetyError } from "./vendor/agent-safety/errors.js";
|
|
21
|
+
export { canonicalInputHash } from "./vendor/agent-safety/hash.js";
|
|
22
|
+
export { ephemeralSigner, hmacSigner, } from "./vendor/agent-safety/signer.js";
|
|
23
|
+
/** The package's name, `@buildanagent/sdk`. */
|
|
6
24
|
export const SDK_PACKAGE = "@buildanagent/sdk";
|
|
7
25
|
//# 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;;;;;;;;;GASG;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,GAOlB,MAAM,aAAa,CAAC;AAmBrB,OAAO,EAGL,iBAAiB,EACjB,oBAAoB,GAErB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,gBAAgB,EAAuB,MAAM,eAAe,CAAC;AAgBtE,OAAO,EAEL,WAAW,EACX,cAAc,EAId,GAAG,EACH,UAAU,GACX,MAAM,UAAU,CAAC;AAElB,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;AASnE,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, or a\n * tool that asks the user a question, ends the run with a signed pending request, which `continueRun()` resumes with\n * resolutions, in this process or another; `blockingApprovals()` answers approvals inside the run instead. The\n * signers, the input hash and the pending record are the safety package's, 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 ResolutionRejectionCause,\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 {\n type ApprovalDetails,\n type ApprovalHandler,\n blockingApprovals,\n createPendingRequest,\n type PendingRequestFields,\n} from \"./pauses.js\";\nexport { DEFAULT_PROGRESS, type ProgressPolicy } from \"./progress.js\";\nexport type {\n AwaitingApprovalResult,\n BudgetResult,\n ClarificationRequestedResult,\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 {\n type ContinueOptions,\n continueRun,\n nestedRunDepth,\n type Run,\n type RunInput,\n type RunOptions,\n run,\n runOrThrow,\n} 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 {\n Recheck,\n RejectionCause,\n Resolution,\n SignedPendingRequest,\n SignPendingOptions,\n} 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
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The step loop: one model call, then the tool calls it asked for, then the stop check, until a stop reason holds
|
|
3
|
+
* (agent-SDK guide §3). The non-streaming result is built from the same run, so there is one loop for both modes.
|
|
4
|
+
*
|
|
5
|
+
* Each step runs transform → before → stream → after → tools → stop. Those moments are where the interceptors
|
|
6
|
+
* plug in (D6); a run without interceptors sends the transcript as it stands and keeps each response unchanged.
|
|
7
|
+
* Every outcome is a stop reason, never an exception: only a programmer error, such as a malformed tool result,
|
|
8
|
+
* throws.
|
|
9
|
+
*/
|
|
10
|
+
import { type Message, type Model } from "@buildanagent/gateway";
|
|
11
|
+
import type { AgentEventBody } from "./events.js";
|
|
12
|
+
import type { CallOptions, Interceptors } from "./hooks.js";
|
|
13
|
+
import type { ProgressCheck } from "./progress.js";
|
|
14
|
+
import type { RunResult } from "./result.js";
|
|
15
|
+
import { type ResumeSetup } from "./resume.js";
|
|
16
|
+
import type { SteeringQueue } from "./steering.js";
|
|
17
|
+
import type { Clock } from "./testing/determinism.js";
|
|
18
|
+
import { type AnyTool } from "./tools/pipeline.js";
|
|
19
|
+
import type { ApprovalSigner } from "./vendor/agent-safety/signer.js";
|
|
20
|
+
/** Everything one run needs, fixed when it starts. */
|
|
21
|
+
export interface LoopSetup {
|
|
22
|
+
readonly runId: string;
|
|
23
|
+
readonly model: Model;
|
|
24
|
+
readonly system: string;
|
|
25
|
+
/** The conversation before this run's own messages. */
|
|
26
|
+
readonly history: readonly Message[];
|
|
27
|
+
/** The messages the run starts by adding, such as the user's input. */
|
|
28
|
+
readonly input: readonly Message[];
|
|
29
|
+
/**
|
|
30
|
+
* Every tool the run knows, in definition order. A request sends the ones whose exposure is `direct`, or the ones
|
|
31
|
+
* `activeTools` names, and only the tools a request sent can run.
|
|
32
|
+
*/
|
|
33
|
+
readonly tools: readonly AnyTool[];
|
|
34
|
+
readonly output: AnyTool | undefined;
|
|
35
|
+
readonly maxSteps: number;
|
|
36
|
+
/** The most the run's model calls may cost, in USD, or `undefined` for no cap (D9). */
|
|
37
|
+
readonly budgetUsd?: number;
|
|
38
|
+
/** How deeply this run is nested inside other agents' tool calls, and the deepest nesting allowed (D11). */
|
|
39
|
+
readonly depth: number;
|
|
40
|
+
readonly maxDepth: number;
|
|
41
|
+
readonly modelOptions: CallOptions;
|
|
42
|
+
readonly interceptors: Interceptors;
|
|
43
|
+
/** The default progress policy, run after the caller's `shouldStop`, or `undefined` when it is off (D11). */
|
|
44
|
+
readonly progress?: ProgressCheck;
|
|
45
|
+
/** The messages a caller queued with `steer()` and `followUp()`, applied only at step boundaries. */
|
|
46
|
+
readonly steering: SteeringQueue;
|
|
47
|
+
readonly signal: AbortSignal;
|
|
48
|
+
readonly clock: Clock;
|
|
49
|
+
/** Signs the pending request of each call a gate asks about (D5). */
|
|
50
|
+
readonly signer: ApprovalSigner;
|
|
51
|
+
/** Makes each pending request's id. */
|
|
52
|
+
readonly nextId: () => string;
|
|
53
|
+
/** The waiting calls of the context a `continueRun()` resumes, and their resolutions. */
|
|
54
|
+
readonly resume?: ResumeSetup;
|
|
55
|
+
}
|
|
56
|
+
/** Sends one event; the run adds the `EventBase` fields. */
|
|
57
|
+
export type Emit = (body: AgentEventBody, stepIndex: number) => void;
|
|
58
|
+
/**
|
|
59
|
+
* Resolves once every observer has handled the events sent so far. The loop calls it only once it has its outcome,
|
|
60
|
+
* and the run treats the first call as the point after which an abort no longer counts.
|
|
61
|
+
*/
|
|
62
|
+
export type Drain = () => Promise<void>;
|
|
63
|
+
/**
|
|
64
|
+
* Runs the loop to a stop reason and returns the result. It throws only for a programmer error, after the results
|
|
65
|
+
* already received are in the transcript.
|
|
66
|
+
*/
|
|
67
|
+
export declare function runLoop(setup: LoopSetup, emit: Emit, drain: Drain): Promise<RunResult>;
|