@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.
Files changed (116) hide show
  1. package/README.md +424 -5
  2. package/dist/budget.d.ts +33 -0
  3. package/dist/budget.js +55 -0
  4. package/dist/budget.js.map +1 -0
  5. package/dist/compose.d.ts +26 -0
  6. package/dist/compose.js +157 -0
  7. package/dist/compose.js.map +1 -0
  8. package/dist/errors.d.ts +49 -0
  9. package/dist/errors.js +57 -0
  10. package/dist/errors.js.map +1 -0
  11. package/dist/events.d.ts +168 -0
  12. package/dist/events.js +32 -0
  13. package/dist/events.js.map +1 -0
  14. package/dist/freeze.d.ts +11 -0
  15. package/dist/freeze.js +42 -0
  16. package/dist/freeze.js.map +1 -0
  17. package/dist/hook-checks.d.ts +31 -0
  18. package/dist/hook-checks.js +130 -0
  19. package/dist/hook-checks.js.map +1 -0
  20. package/dist/hook-runner.d.ts +96 -0
  21. package/dist/hook-runner.js +372 -0
  22. package/dist/hook-runner.js.map +1 -0
  23. package/dist/hooks.d.ts +183 -0
  24. package/dist/hooks.js +2 -0
  25. package/dist/hooks.js.map +1 -0
  26. package/dist/index.d.ts +26 -3
  27. package/dist/index.js +21 -3
  28. package/dist/index.js.map +1 -1
  29. package/dist/loop.d.ts +67 -0
  30. package/dist/loop.js +644 -0
  31. package/dist/loop.js.map +1 -0
  32. package/dist/observers.d.ts +31 -0
  33. package/dist/observers.js +98 -0
  34. package/dist/observers.js.map +1 -0
  35. package/dist/otel/attributes.d.ts +43 -0
  36. package/dist/otel/attributes.js +50 -0
  37. package/dist/otel/attributes.js.map +1 -0
  38. package/dist/otel/content.d.ts +17 -0
  39. package/dist/otel/content.js +48 -0
  40. package/dist/otel/content.js.map +1 -0
  41. package/dist/otel/index.d.ts +6 -2
  42. package/dist/otel/index.js +6 -2
  43. package/dist/otel/index.js.map +1 -1
  44. package/dist/otel/observer.d.ts +82 -0
  45. package/dist/otel/observer.js +300 -0
  46. package/dist/otel/observer.js.map +1 -0
  47. package/dist/pauses.d.ts +61 -0
  48. package/dist/pauses.js +83 -0
  49. package/dist/pauses.js.map +1 -0
  50. package/dist/progress.d.ts +34 -0
  51. package/dist/progress.js +139 -0
  52. package/dist/progress.js.map +1 -0
  53. package/dist/result.d.ts +134 -0
  54. package/dist/result.js +2 -0
  55. package/dist/result.js.map +1 -0
  56. package/dist/resume.d.ts +76 -0
  57. package/dist/resume.js +237 -0
  58. package/dist/resume.js.map +1 -0
  59. package/dist/run.d.ts +214 -0
  60. package/dist/run.js +327 -0
  61. package/dist/run.js.map +1 -0
  62. package/dist/steering.d.ts +52 -0
  63. package/dist/steering.js +104 -0
  64. package/dist/steering.js.map +1 -0
  65. package/dist/testing/scripted-model.d.ts +12 -2
  66. package/dist/testing/scripted-model.js +19 -2
  67. package/dist/testing/scripted-model.js.map +1 -1
  68. package/dist/tools/coerce.d.ts +15 -0
  69. package/dist/tools/coerce.js +93 -0
  70. package/dist/tools/coerce.js.map +1 -0
  71. package/dist/tools/define.d.ts +54 -0
  72. package/dist/tools/define.js +121 -0
  73. package/dist/tools/define.js.map +1 -0
  74. package/dist/tools/format-error.d.ts +13 -0
  75. package/dist/tools/format-error.js +66 -0
  76. package/dist/tools/format-error.js.map +1 -0
  77. package/dist/tools/outcome.d.ts +7 -0
  78. package/dist/tools/outcome.js +30 -0
  79. package/dist/tools/outcome.js.map +1 -0
  80. package/dist/tools/pipeline.d.ts +111 -0
  81. package/dist/tools/pipeline.js +382 -0
  82. package/dist/tools/pipeline.js.map +1 -0
  83. package/dist/tools/scheduler.d.ts +33 -0
  84. package/dist/tools/scheduler.js +51 -0
  85. package/dist/tools/scheduler.js.map +1 -0
  86. package/dist/tools/schema.d.ts +20 -0
  87. package/dist/tools/schema.js +100 -0
  88. package/dist/tools/schema.js.map +1 -0
  89. package/dist/tools/types.d.ts +196 -0
  90. package/dist/tools/types.js +2 -0
  91. package/dist/tools/types.js.map +1 -0
  92. package/dist/vendor/agent-safety/bytes.d.ts +17 -0
  93. package/dist/vendor/agent-safety/bytes.js +59 -0
  94. package/dist/vendor/agent-safety/bytes.js.map +1 -0
  95. package/dist/vendor/agent-safety/errors.d.ts +23 -0
  96. package/dist/vendor/agent-safety/errors.js +22 -0
  97. package/dist/vendor/agent-safety/errors.js.map +1 -0
  98. package/dist/vendor/agent-safety/hash.d.ts +16 -0
  99. package/dist/vendor/agent-safety/hash.js +110 -0
  100. package/dist/vendor/agent-safety/hash.js.map +1 -0
  101. package/dist/vendor/agent-safety/outcome.d.ts +88 -0
  102. package/dist/vendor/agent-safety/outcome.js +140 -0
  103. package/dist/vendor/agent-safety/outcome.js.map +1 -0
  104. package/dist/vendor/agent-safety/pending.d.ts +119 -0
  105. package/dist/vendor/agent-safety/pending.js +122 -0
  106. package/dist/vendor/agent-safety/pending.js.map +1 -0
  107. package/dist/vendor/agent-safety/render.d.ts +40 -0
  108. package/dist/vendor/agent-safety/render.js +92 -0
  109. package/dist/vendor/agent-safety/render.js.map +1 -0
  110. package/dist/vendor/agent-safety/signer.d.ts +42 -0
  111. package/dist/vendor/agent-safety/signer.js +128 -0
  112. package/dist/vendor/agent-safety/signer.js.map +1 -0
  113. package/dist/version.d.ts +2 -0
  114. package/dist/version.js +8 -0
  115. package/dist/version.js.map +1 -0
  116. package/package.json +13 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resume.js","sourceRoot":"","sources":["../src/resume.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAGlD,OAAO,EAIL,gBAAgB,GACjB,MAAM,kCAAkC,CAAC;AAuC1C,SAAS,OAAO,CAAC,OAAe;IAC9B,MAAM,IAAI,QAAQ,CAAC,qBAAqB,EAAE,iBAAiB,OAAO,EAAE,CAAC,CAAC;AACxE,CAAC;AAED,SAAS,QAAQ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,CAAC,CAAC;QACjH,OAAO,yBAAyB,CAAC;IACnC,CAAC;IACD,IAAI,MAAM,KAAK,OAAO;QAAE,OAAO,SAAS,CAAC;IACzC,IAAI,QAAQ,CAAC,MAAM,CAAC,IAAI,OAAO,MAAM,CAAC,IAAI,KAAK,QAAQ,IAAI,MAAM,CAAC,IAAI,KAAK,EAAE;QAAE,OAAO,MAAM,CAAC,IAAI,CAAC;IAClG,OAAO,mCAAmC,CAAC;AAC7C,CAAC","sourcesContent":["/**\n * Resuming a paused context (D5; SDK plan §3.3). `continueRun()` first checks the context's shape and refuses one it\n * can't resume safely, then, inside the run, checks every waiting call's stored request and its resolution before\n * anything runs. The checks fail closed: a request or resolution that doesn't verify never runs its call, and the\n * call asks again with a new request.\n */\nimport type { AssistantMessage, Message } from \"@buildanagent/gateway\";\nimport { SdkError } from \"./errors.js\";\nimport type { AgentEventBody, ResolutionRejectionCause } from \"./events.js\";\nimport { denied, textOf } from \"./hook-runner.js\";\nimport type { Context } from \"./result.js\";\nimport type { ToolCall, ToolResult } from \"./tools/types.js\";\nimport {\n type Recheck,\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/** A call of the context's last assistant message that has no result, and the stored request it waits on. */\nexport interface OpenCall {\n readonly call: ToolCall;\n /** The stored request, untrusted until its signature verifies. Only `id` and `callId` are known to be strings. */\n readonly request: SignedPendingRequest;\n}\n\n/** What a run that resumes a paused context starts with, checked for shape when `continueRun()` is called. */\nexport interface ResumeSetup {\n /** The assistant message whose calls wait, absent when none does. */\n readonly message?: AssistantMessage;\n /** The calls that wait, in model order. */\n readonly open: readonly OpenCall[];\n /** Each resolution, by the request id it names. */\n readonly resolutions: ReadonlyMap<string, Resolution>;\n /** The request ids that more than one resolution names. */\n readonly replayed: ReadonlySet<string>;\n /** The request ids of resolutions that name no request in the context. */\n readonly unmatched: readonly string[];\n /** The input each stored request signs, by request id. */\n readonly inputs: Readonly<Record<string, unknown>>;\n /** Runs current policy before an approved call runs. */\n readonly recheck?: Recheck;\n}\n\n/** What the checks decided for one waiting call. */\nexport type Verdict =\n /** A verified approval: the call runs with `call.input`, the input its request signs. */\n | { readonly kind: \"run\"; readonly call: ToolCall }\n /** A verified denial or answer, or an approval current policy now denies: the model reads `result`. */\n | { readonly kind: \"result\"; readonly call: ToolCall; readonly result: ToolResult }\n /** No resolution names the request, which verified: it still waits. */\n | { readonly kind: \"wait\"; readonly call: ToolCall; readonly request: SignedPendingRequest; readonly input: unknown }\n /** The request or its resolution failed a check: the call asks again. */\n | { readonly kind: \"reissue\"; readonly call: ToolCall };\n\nfunction invalid(message: string): never {\n throw new SdkError(\"invalid_run_options\", `continueRun() ${message}`);\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isFailedTurn(message: Message): boolean {\n return message.role === \"assistant\" && (message.stopReason === \"error\" || message.stopReason === \"aborted\");\n}\n\n/**\n * The calls of the last assistant message that no later tool message answers. A message that ended in an error or\n * an abort has none: the gateway's replay pass drops it, and the run asks the model again.\n */\nfunction openCallsOf(messages: readonly Message[]): { message: AssistantMessage; calls: ToolCall[] } | undefined {\n const index = messages.findLastIndex((message) => message.role === \"assistant\");\n const message = messages[index];\n if (message?.role !== \"assistant\" || isFailedTurn(message)) return undefined;\n const answered = new Set<string>();\n for (const later of messages.slice(index + 1)) if (later.role === \"tool\") answered.add(later.callId);\n const calls = message.content.filter(\n (block): block is ToolCall => block.type === \"tool_call\" && !answered.has(block.callId),\n );\n return { message, calls };\n}\n\n/** Checks the context's shape, the minimum `continueRun()` needs to read it. */\nfunction checkContext(context: unknown): asserts context is Context {\n if (!isObject(context)) invalid(\"needs a context object with system and messages\");\n if (typeof context.system !== \"string\") invalid(\"needs a context whose system is a string\");\n if (!Array.isArray(context.messages) || !context.messages.every((m) => isObject(m) && typeof m.role === \"string\")) {\n invalid(\"needs a context whose messages are a list of messages\");\n }\n if (context.pending !== undefined && !Array.isArray(context.pending)) invalid(\"needs pending to be a list\");\n if (context.pendingInputs !== undefined && !isObject(context.pendingInputs)) {\n invalid(\"needs pendingInputs to be an object of inputs by request id\");\n }\n}\n\n/** The stored requests by call id, after checking that each one is an object with a string `id` and `callId`. */\nfunction requestsByCall(pending: readonly unknown[]): Map<string, SignedPendingRequest> {\n const byCall = new Map<string, SignedPendingRequest>();\n const ids = new Set<string>();\n for (const request of pending) {\n if (!isObject(request) || typeof request.id !== \"string\" || typeof request.callId !== \"string\") {\n invalid(\"needs each pending request to be an object with a string id and callId\");\n }\n if (ids.has(request.id)) invalid(`got two pending requests with the id ${JSON.stringify(request.id)}`);\n if (byCall.has(request.callId)) invalid(`got two pending requests for the call ${JSON.stringify(request.callId)}`);\n ids.add(request.id);\n byCall.set(request.callId, request as unknown as SignedPendingRequest);\n }\n return byCall;\n}\n\n/** The resolutions by request id, with the ids more than one of them names. */\nfunction resolutionsOf(resolutions: unknown): { byId: Map<string, Resolution>; replayed: Set<string> } {\n if (resolutions !== undefined && !Array.isArray(resolutions)) invalid(\"needs resolutions to be a list\");\n const byId = new Map<string, Resolution>();\n const replayed = new Set<string>();\n for (const resolution of (resolutions ?? []) as unknown[]) {\n if (!isObject(resolution) || typeof resolution.requestId !== \"string\") {\n invalid(\"needs each resolution to be an object with a string requestId\");\n }\n if (byId.has(resolution.requestId)) replayed.add(resolution.requestId);\n byId.set(resolution.requestId, resolution as unknown as Resolution);\n }\n return { byId, replayed };\n}\n\n/**\n * Pairs each waiting call with its stored request, and refuses a call with none, two calls with one id, and a\n * request whose call doesn't wait.\n */\nfunction matchOpenCalls(calls: readonly ToolCall[], byCall: ReadonlyMap<string, SignedPendingRequest>): OpenCall[] {\n const open: OpenCall[] = [];\n for (const call of calls) {\n const request = byCall.get(call.callId);\n // The owner's rule (2026-11-19): a waiting call with no record is a lost pause, so it fails loudly here rather\n // than reaching the model as \"No result was recorded\".\n if (request === undefined) {\n invalid(\n `can't resume the call ${JSON.stringify(call.callId)} to \"${call.name}\": it has no result and no pending ` +\n \"request, so its pause record was lost. Restore the context's pending and pendingInputs, or add a result\",\n );\n }\n if (open.some((entry) => entry.call.callId === call.callId)) {\n invalid(`got two waiting calls with the id ${JSON.stringify(call.callId)}`);\n }\n open.push({ call, request });\n }\n for (const [callId, request] of byCall) {\n if (!calls.some((call) => call.callId === callId)) {\n invalid(\n `got the pending request ${JSON.stringify(request.id)}, whose call doesn't wait in this context. ` +\n \"Remove the request from pending and its input from pendingInputs, or restore the call without its result\",\n );\n }\n }\n return open;\n}\n\n/**\n * Checks a context and its resolutions before a run starts, and returns what the run needs to resume its waiting\n * calls, or `undefined` when no call waits. Throws an `SdkError` with code `invalid_run_options` for a context it\n * can't read, for a call of the last assistant message that has no result and no stored request, for a stored\n * request whose call doesn't wait in the context, and for malformed resolutions or `recheck`.\n */\nexport function resumeSetupOf(context: unknown, resolutions: unknown, recheck: unknown): ResumeSetup | undefined {\n checkContext(context);\n if (recheck !== undefined && typeof recheck !== \"function\") invalid(\"needs recheck to be a function\");\n const byCall = requestsByCall(context.pending ?? []);\n const { byId, replayed } = resolutionsOf(resolutions);\n const found = openCallsOf(context.messages);\n const open = matchOpenCalls(found?.calls ?? [], byCall);\n const known = new Set(open.map((entry) => entry.request.id));\n const unmatched = [...byId.keys()].filter((id) => !known.has(id));\n if (found === undefined || open.length === 0) {\n // Resolutions that name no request are still reported, and nothing runs for them.\n if (unmatched.length === 0) return undefined;\n return { open: [], resolutions: byId, replayed, unmatched, inputs: {} };\n }\n return {\n message: found.message,\n open,\n resolutions: byId,\n replayed,\n unmatched,\n inputs: (context.pendingInputs ?? {}) as Readonly<Record<string, unknown>>,\n ...(recheck === undefined ? {} : { recheck: recheck as Recheck }),\n };\n}\n\n/** A resolution of the request's own kind, to check a stored request that no resolution names. */\nfunction probeOf(request: SignedPendingRequest): Resolution {\n return request.kind === \"clarification\"\n ? { requestId: request.id, answer: \"\" }\n : { requestId: request.id, decision: \"deny\" };\n}\n\nfunction inputOf(inputs: Readonly<Record<string, unknown>>, id: string): unknown {\n return Object.hasOwn(inputs, id) ? inputs[id] : undefined;\n}\n\n/** What the checks need from the run. */\nexport interface JudgeContext {\n readonly signer: ApprovalSigner;\n send(body: AgentEventBody): void;\n}\n\n/**\n * Checks each waiting call's stored request and resolution, in model order, and decides what happens to the call.\n * Nothing runs here: the run acts on the verdicts afterwards.\n */\nexport async function judgeOpenCalls(resume: ResumeSetup, ctx: JudgeContext): Promise<Verdict[]> {\n const reject = (requestId: string, callId: string | undefined, cause: ResolutionRejectionCause) =>\n ctx.send({ type: \"resolution_rejected\", requestId, ...(callId === undefined ? {} : { callId }), cause });\n for (const id of resume.unmatched) reject(id, undefined, \"unknown_request\");\n const verdicts: Verdict[] = [];\n for (const { call, request } of resume.open) {\n if (resume.replayed.has(request.id)) {\n reject(request.id, call.callId, \"replayed\");\n verdicts.push({ kind: \"reissue\", call });\n continue;\n }\n const input = inputOf(resume.inputs, request.id);\n const resolution = resume.resolutions.get(request.id);\n const cause = await failedCheck(request, resolution ?? probeOf(request), call, input, ctx.signer);\n if (cause !== undefined) {\n reject(request.id, call.callId, cause);\n verdicts.push({ kind: \"reissue\", call });\n } else if (resolution === undefined) {\n verdicts.push({ kind: \"wait\", call, request, input });\n } else {\n verdicts.push(await verdictOf(call, request, resolution, input, resume.recheck, ctx));\n }\n }\n return verdicts;\n}\n\n/** Why the request or its resolution failed `verifyResolution()`, or `undefined` when both passed. */\nasync function failedCheck(\n request: SignedPendingRequest,\n resolution: Resolution,\n call: ToolCall,\n input: unknown,\n signer: ApprovalSigner,\n): Promise<ResolutionRejectionCause | undefined> {\n try {\n const check = await verifyResolution(request, resolution, {\n signer,\n call: { callId: call.callId, tool: call.name, input },\n });\n return check.ok ? undefined : check.cause;\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 \"error\";\n }\n}\n\n/** The verdict for a verified resolution. */\nasync function verdictOf(\n call: ToolCall,\n request: SignedPendingRequest,\n resolution: Resolution,\n input: unknown,\n recheck: Recheck | undefined,\n ctx: JudgeContext,\n): Promise<Verdict> {\n const by = textOf(resolution.by);\n // The verified request's kind decides, never the resolution's fields: a resolution that carries both an `answer`\n // and a `decision` passes the check for either kind, and an approval must never take a host's text as its result.\n if (request.kind === \"clarification\") {\n const result: ToolResult = {\n content: [{ type: \"text\", text: (resolution as { answer: string }).answer }],\n details: { requestId: request.id, ...(by === undefined ? {} : { by }) },\n };\n return { kind: \"result\", call, result };\n }\n const decision = resolution as Extract<Resolution, { decision: unknown }>;\n if (decision.decision === \"deny\") {\n return { kind: \"result\", call, result: denied(call.name, textOf(decision.reason), request.id, by) };\n }\n const blocked = recheck === undefined ? undefined : await policyBlock(recheck, request, input, ctx);\n if (blocked !== undefined) {\n const text = `Tool call \"${call.name}\" was approved, but current policy now denies it: ${blocked}`;\n const result: ToolResult = {\n content: [{ type: \"text\", text }],\n isError: true,\n details: { decision: \"deny\", requestId: request.id, policy: true },\n };\n return { kind: \"result\", call, result };\n }\n // The approved call runs with the input its request signs, never the transcript's arguments.\n return { kind: \"run\", call: { ...call, input } };\n}\n\n/** Why current policy blocks an approved call, or `undefined` when `recheck` allows it. Fails closed. */\nasync function policyBlock(\n recheck: Recheck,\n request: SignedPendingRequest,\n input: unknown,\n ctx: JudgeContext,\n): Promise<string | undefined> {\n let answer: unknown;\n try {\n // Copies, so a callback that edits what it is handed can't change the input the run executes after the check. A\n // request or input that can't be copied fails the check closed.\n answer = await recheck(structuredClone(request), structuredClone(input));\n } catch (error) {\n ctx.send({ type: \"hook_error\", hook: \"recheck\", error: error instanceof Error ? error.message : String(error) });\n return \"the policy check failed\";\n }\n if (answer === \"allow\") return undefined;\n if (isObject(answer) && typeof answer.deny === \"string\" && answer.deny !== \"\") return answer.deny;\n return \"the policy check did not allow it\";\n}\n"]}
package/dist/run.d.ts ADDED
@@ -0,0 +1,214 @@
1
+ /**
2
+ * `run()`, `continueRun()` and `runOrThrow()`, and the `Run` object they share (SDK plan §3.3; D10). A run streams
3
+ * its events to anyone who iterates it and settles `result` with the same run's outcome, so the streaming and the
4
+ * non-streaming caller drive one loop.
5
+ */
6
+ import type { ContentBlock, Message, Model } from "@buildanagent/gateway";
7
+ import type { AgentEvent } from "./events.js";
8
+ import type { CallOptions, Interceptors, Observer } from "./hooks.js";
9
+ import { type ProgressPolicy } from "./progress.js";
10
+ import type { Context, DoneResult, RunResult } from "./result.js";
11
+ import { type DeliveryReceipt } from "./steering.js";
12
+ import type { Clock } from "./testing/determinism.js";
13
+ import type { ToolContext, ToolDefinition } from "./tools/types.js";
14
+ import type { Recheck, Resolution } from "./vendor/agent-safety/pending.js";
15
+ import { type ApprovalSigner } from "./vendor/agent-safety/signer.js";
16
+ /** The options `run()` and `continueRun()` share. */
17
+ export interface RunOptions<S = unknown> {
18
+ /** The model, from `createModel()`. */
19
+ readonly model: Model;
20
+ /**
21
+ * The tools the model may call. Tools whose `exposure` is `deferred` or `hidden` are not sent unless a
22
+ * `beforeModelCall` interceptor names them in `activeTools`.
23
+ */
24
+ readonly tools?: readonly ToolDefinition<unknown, unknown>[];
25
+ /**
26
+ * A tool from `outputTool()` whose input is the final answer. It is sent with the other tools; once the model calls
27
+ * it with input that passes its schema, the run ends `done`, and `result.output` holds the validated answer.
28
+ */
29
+ readonly output?: ToolDefinition<S, S>;
30
+ /**
31
+ * The most model calls the run may make. Default 20. A run that reaches it while the model still wants to go on
32
+ * ends with `stopReason: "max_steps"` and emits a `warning` event with `code: "max_steps"`.
33
+ */
34
+ readonly maxSteps?: number;
35
+ /**
36
+ * The most the run's model calls may cost, in USD. Before each call the run projects its cost with
37
+ * `projectCallCost()` and, if the spend so far plus that projection would pass the cap, ends with
38
+ * `stopReason: "budget"` without making the call. The cap counts the calls this run makes, not the cost of the
39
+ * history a `continueRun()` starts from. A budgeted run on a model whose price is unknown ends `error` with
40
+ * `error.kind: "unknown_price"` before its first call, because it could not tell what it spent. Without it, a run
41
+ * has no cap.
42
+ */
43
+ readonly budgetUsd?: number;
44
+ /**
45
+ * The default progress policy: the run ends `no_progress` after 3 identical failing tool calls in a row, or after 5
46
+ * calls to a tool with one `progressKey` and no success between them. It runs after your own `shouldStop`, whose
47
+ * `{ continue }` can't keep a stuck run going. Pass numbers to change either threshold, or `false` to turn the
48
+ * policy off.
49
+ */
50
+ readonly progress?: ProgressPolicy | false;
51
+ /**
52
+ * How deeply this run is nested inside other agents' tool calls. Default 0. A tool that starts a run of its own
53
+ * passes `depth: ctx.depth + 1` and `maxDepth: ctx.maxDepth`; `run()` throws an `SdkError` with code
54
+ * `max_depth_exceeded` when `depth` is above `maxDepth`, which the tool's caller reads as an error result.
55
+ */
56
+ readonly depth?: number;
57
+ /** The deepest nesting allowed, which tools read as `ctx.maxDepth`. Default 2. */
58
+ readonly maxDepth?: number;
59
+ /** Aborts the run, like `run.abort()`. */
60
+ readonly signal?: AbortSignal;
61
+ /** Options for every model call, such as `maxOutputTokens`. The run passes its own abort signal. */
62
+ readonly modelOptions?: CallOptions;
63
+ /**
64
+ * The interceptors: hooks that can change the run at six moments. A run takes one object; join several with
65
+ * `composeInterceptors()`. See `Interceptors` for the order and for what a failing hook does.
66
+ */
67
+ readonly interceptors?: Interceptors;
68
+ /**
69
+ * Observers, which receive every event from `run_start` on and can't change the run. Each observer sees the events in
70
+ * order and waits for its own promises, but observers don't wait for each other. An observer that throws becomes a
71
+ * `hook_error` event. The run waits for every observer to handle the last event before it settles, for at most
72
+ * `observerTimeoutMs` each time it waits; an observer that hasn't caught up by then is removed and reported as a
73
+ * `hook_error`.
74
+ */
75
+ readonly observers?: readonly Observer[];
76
+ /**
77
+ * The longest the run waits for its observers each time it waits for them: before `agent_settled`, before
78
+ * `run_end` and before it settles. A number from 1 to 2147483647; the default is 10000. It bounds an observer whose promise never settles.
79
+ */
80
+ readonly observerTimeoutMs?: number;
81
+ /** Stamps each event's `timestamp`, and is passed to tools. Defaults to the system clock. */
82
+ readonly clock?: Clock;
83
+ /**
84
+ * Makes the run's id, then the id of each pending request the run signs. A request id that repeats the run's id or
85
+ * an earlier request's id is replaced by `crypto.randomUUID()`, so a generator that always returns one id still
86
+ * pauses every call; return a fresh id on every call to keep request ids deterministic. Defaults to
87
+ * `crypto.randomUUID()`.
88
+ */
89
+ readonly idGenerator?: () => string;
90
+ /**
91
+ * Signs the pending request a run writes when a `beforeToolCall` gate returns `ask`. The default,
92
+ * `ephemeralSigner()`, holds a random key that lives only in this process, so only this process can verify its
93
+ * pauses: on a serverless host, or anywhere a pause may resume in another process, pass `hmacSigner()` over a key
94
+ * ring you keep. A pause that can't be signed is never written unsigned; its call is blocked instead.
95
+ */
96
+ readonly signer?: ApprovalSigner;
97
+ }
98
+ /** What `continueRun()` takes besides the shared options: the answers to a paused context's requests. */
99
+ export interface ContinueOptions<S = unknown> extends RunOptions<S> {
100
+ /**
101
+ * A person's answer to each pending request of the context: `{ requestId, decision: "allow" | "deny" }` for an
102
+ * approval, `{ requestId, answer }` for a question. Each is checked against its request and the input
103
+ * `context.pendingInputs` holds for it, with the run's `signer`, before anything runs. A request no resolution
104
+ * names still waits, and the run ends paused again without a model call.
105
+ */
106
+ readonly resolutions?: readonly Resolution[];
107
+ /**
108
+ * Runs current policy for each verified approval just before its call runs. It gets copies of the request and
109
+ * input. Resolve to `"allow"` to run the call, or to `{ deny: reason }` to give the model an error result with that
110
+ * reason instead. A `recheck` that throws or returns anything else denies the call. Without it, a verified approval
111
+ * runs, so check policy before you resolve.
112
+ */
113
+ readonly recheck?: Recheck;
114
+ }
115
+ /** What `run()` takes besides the shared options. */
116
+ export interface RunInput {
117
+ /** The system prompt. */
118
+ readonly system: string;
119
+ /** The user's message that starts the run. */
120
+ readonly input: string | readonly ContentBlock[];
121
+ /** Earlier messages to send before `input`, such as a previous conversation. */
122
+ readonly history?: readonly Message[];
123
+ }
124
+ /**
125
+ * A run in progress. Iterate it to stream its events: each iteration starts from the run's first event, so you can
126
+ * start iterating at any time. Await `result` for the outcome; it rejects only for a programmer error, such as a
127
+ * tool that returns a malformed result, and iteration then throws the same error after the last event.
128
+ */
129
+ export interface Run<S = unknown> extends AsyncIterable<AgentEvent> {
130
+ /** The run's id, which every event carries. */
131
+ readonly id: string;
132
+ /** The outcome, once the run has stopped. */
133
+ readonly result: Promise<RunResult<S>>;
134
+ /**
135
+ * Stops the run. A model call in flight ends, a running tool sees its `signal` fire, and calls that haven't started
136
+ * get an error result instead. The run then ends with `stopReason: "aborted"`, unless a gate already paused a call
137
+ * in the step, which ends it `awaiting_approval`, because that call's signed request still waits. Does nothing once
138
+ * the run has its outcome and is ending, which is before `agent_settled`.
139
+ */
140
+ abort(reason?: string): void;
141
+ /**
142
+ * Adds an observer that receives the events from now on, in order, and returns the function that removes it. An
143
+ * event that was queued for it but not yet handled is dropped when you remove it. Add it right after `run()` to
144
+ * see every event but `run_start`, which `run()` emits before it returns; to see that one too, pass the observer
145
+ * in the `observers` option.
146
+ */
147
+ on(observer: Observer): () => void;
148
+ /**
149
+ * Queues a user message that redirects the run. The run applies it at the next step boundary: after the model call
150
+ * or tool batch in flight, never inside it, and before the next model call. The promise resolves with a
151
+ * `DeliveryReceipt` once the message is in the transcript, and the run emits a `steer_applied` event for it. It
152
+ * rejects with an `SdkError` whose code is `undelivered_message` when the run ends first, and with
153
+ * `invalid_run_options` for a blank message or a block that isn't text or an image. Steers are applied in the
154
+ * order they were sent.
155
+ */
156
+ steer(message: string | readonly ContentBlock[]): Promise<DeliveryReceipt>;
157
+ /**
158
+ * Queues a user message that waits until the run would otherwise end. When the model has answered and no tool call
159
+ * is left, the run applies every waiting follow-up as user messages and makes one more model call, so a follow-up
160
+ * sent before the run ends extends it by one step. A steer that is waiting goes first. The run still ends, and the
161
+ * follow-up rejects with `undelivered_message`, when another stop reason ends it: a `shouldStop` hook or progress
162
+ * policy that stops it, its output tool, an abort or `maxSteps`. The receipt works as for `steer()`.
163
+ */
164
+ followUp(message: string | readonly ContentBlock[]): Promise<DeliveryReceipt>;
165
+ }
166
+ /**
167
+ * The `depth` and `maxDepth` options for a run that a tool starts: one level deeper than the tool's own run, under
168
+ * the same cap. Spread it into the nested `run()`; the nested run throws `max_depth_exceeded` when the tool was
169
+ * already at `maxDepth`.
170
+ */
171
+ export declare function nestedRunDepth(ctx: Pick<ToolContext, "depth" | "maxDepth">): {
172
+ depth: number;
173
+ maxDepth: number;
174
+ };
175
+ /**
176
+ * Starts a run: the model answers `input`, runs the tools it asks for, and goes on until it answers without a tool
177
+ * call, an output tool accepts its answer, or a stop reason ends the run early. Throws an `SdkError` at once for an
178
+ * unusable option: a model that isn't from `createModel()`, a `maxSteps` that isn't a positive integer, an output tool
179
+ * that isn't sent to the model, or two tools with one name.
180
+ */
181
+ export declare function run<S = unknown>(options: RunOptions<S> & RunInput): Run<S>;
182
+ /**
183
+ * Goes on with a conversation from a result's `context`, or one you rebuilt from your own store. It runs like
184
+ * `run()`, from the last message in the context, and `result.messages` holds only the messages it adds. The context
185
+ * is sent as it stands, so add a user message to one that ends with the model's answer, such as a `done` result's.
186
+ * A context whose last response ended in an error asks the model again.
187
+ *
188
+ * A paused context resumes with `resolutions`. Before the first model call, each waiting call's stored request is
189
+ * verified with the run's `signer` against its call and its input in `context.pendingInputs`, then:
190
+ *
191
+ * - a verified `allow` runs the call once, with the input its request signs and without `beforeToolCall`, after
192
+ * `recheck` allows it;
193
+ * - a verified `deny` gives the model an error result with the reason, and a verified `answer` reaches the model as
194
+ * the call's result;
195
+ * - a request no resolution names still waits;
196
+ * - a request or resolution that fails its check runs nothing, emits `resolution_rejected`, and the call asks again
197
+ * with a new approval request: the gate is asked as for a new call, and the call pauses even when the gate allows
198
+ * it. A call to a tool the model isn't sent by default gets the unknown-tool error result instead.
199
+ *
200
+ * Settling the requests is not a step. When a call still waits, the run ends paused again without a model call, and
201
+ * when none does and an approved call's result sets `terminate`, the run ends `done` without one.
202
+ * Each request answers once per context, but the SDK can't see other processes: mark a request used in your store
203
+ * before you resume it, so a second resume of the same stored context is refused there.
204
+ *
205
+ * Throws an `SdkError` with code `invalid_run_options` for a context it can't read, for a context whose last
206
+ * assistant message has a call with no result and no pending request, for a pending request whose call doesn't wait
207
+ * in the context, and for malformed `resolutions` or `recheck`, besides the options `run()` refuses.
208
+ */
209
+ export declare function continueRun<S = unknown>(context: Context, options: ContinueOptions<S>): Run<S>;
210
+ /**
211
+ * Awaits a run and returns its result if it ended `done`. Any other stop reason throws a `RunStoppedError` that
212
+ * carries the result and the context to continue from.
213
+ */
214
+ export declare function runOrThrow<S>(started: Run<S>): Promise<DoneResult<S>>;
package/dist/run.js ADDED
@@ -0,0 +1,327 @@
1
+ import { checkBudgetOption } from "./budget.js";
2
+ import { RunStoppedError, SdkError } from "./errors.js";
3
+ import { runLoop } from "./loop.js";
4
+ import { ObserverBus } from "./observers.js";
5
+ import { blockingHandlerOf, isSigner } from "./pauses.js";
6
+ import { progressCheck, resolveProgress } from "./progress.js";
7
+ import { resumeSetupOf } from "./resume.js";
8
+ import { SteeringQueue } from "./steering.js";
9
+ import { preparedSchemaOf } from "./tools/define.js";
10
+ import { ephemeralSigner } from "./vendor/agent-safety/signer.js";
11
+ import { SDK_VERSION } from "./version.js";
12
+ /** The step cap's default, counted in model calls. */
13
+ const DEFAULT_MAX_STEPS = 20;
14
+ /** The depth cap's default (D11): a top-level run, its subagents and their subagents may run, and no deeper. */
15
+ const DEFAULT_MAX_DEPTH = 2;
16
+ /** How long the run waits, by default, for an observer to catch up before it drops it. */
17
+ const DEFAULT_OBSERVER_TIMEOUT_MS = 10_000;
18
+ /** The longest delay `setTimeout` accepts; a larger one fires at once on Node and workerd alike. */
19
+ const MAX_TIMER_MS = 2_147_483_647;
20
+ const systemClock = { now: () => new Date().toISOString() };
21
+ const randomIds = () => globalThis.crypto.randomUUID();
22
+ function messageOf(error) {
23
+ return error instanceof Error ? error.message : String(error);
24
+ }
25
+ function checkObserver(observer) {
26
+ if (typeof observer !== "function") {
27
+ throw new SdkError("invalid_run_options", `an observer must be a function, got ${typeof observer}`);
28
+ }
29
+ }
30
+ const HOOK_NAMES = [
31
+ "transformContext",
32
+ "beforeModelCall",
33
+ "afterModelCall",
34
+ "beforeToolCall",
35
+ "afterToolCall",
36
+ "shouldStop",
37
+ ];
38
+ /** Checks the interceptors option once, so a misspelt or mistyped hook fails at `run()` and not mid-run. */
39
+ function checkInterceptors(interceptors) {
40
+ if (typeof interceptors !== "object" || interceptors === null) {
41
+ throw new SdkError("invalid_run_options", "interceptors must be an object of hooks");
42
+ }
43
+ for (const name of HOOK_NAMES) {
44
+ const hook = interceptors[name];
45
+ if (hook !== undefined && typeof hook !== "function") {
46
+ throw new SdkError("invalid_run_options", `interceptors.${name} must be a function, got ${typeof hook}`);
47
+ }
48
+ }
49
+ blockingHandlerOf(interceptors);
50
+ const { onFailure } = interceptors;
51
+ if (onFailure !== undefined && onFailure !== "fail_closed" && onFailure !== "continue") {
52
+ throw new SdkError("invalid_run_options", `interceptors.onFailure must be "fail_closed" or "continue"`);
53
+ }
54
+ return interceptors;
55
+ }
56
+ function reasonOf(reason) {
57
+ if (typeof reason === "string")
58
+ return reason;
59
+ return reason instanceof Error ? reason.message : undefined;
60
+ }
61
+ class RunHandle {
62
+ id;
63
+ result;
64
+ #events = [];
65
+ #controller = new AbortController();
66
+ #clock;
67
+ #bus;
68
+ #waiters = [];
69
+ #ended = false;
70
+ /** Set once the loop has its outcome and starts to end the run, so `abort()` no longer does anything. */
71
+ #settled = false;
72
+ /** Set by `run_end`: nothing may follow it, so a late observer report is dropped. */
73
+ #closed = false;
74
+ #steering;
75
+ #failure;
76
+ #stepIndex = 0;
77
+ constructor(setup, signal, watch) {
78
+ this.id = setup.runId;
79
+ this.#clock = setup.clock;
80
+ this.#steering = new SteeringQueue(setup.runId);
81
+ this.#bus = new ObserverBus((hook, error) => {
82
+ if (!this.#closed)
83
+ this.#push({ type: "hook_error", hook, error: messageOf(error) }, this.#stepIndex);
84
+ }, watch.timeoutMs);
85
+ const { observers } = watch;
86
+ for (const observer of observers)
87
+ this.#bus.add(observer);
88
+ const emit = (body, stepIndex) => this.#push(body, stepIndex);
89
+ const { model } = setup;
90
+ const versions = { sdkVersion: SDK_VERSION, specVersion: "v1", defaultsHash: "", capabilities: [] };
91
+ emit({ type: "run_start", ...versions, model: model.ref }, 0);
92
+ const forwardAbort = () => this.abort(reasonOf(signal?.reason));
93
+ if (signal?.aborted)
94
+ forwardAbort();
95
+ else
96
+ signal?.addEventListener("abort", forwardAbort, { once: true });
97
+ // The loop starts after this turn, so an observer added with `run.on()` straight after `run()` sees every event
98
+ // after `run_start`, and a `run.abort()` straight after it stops the run before its first model call.
99
+ // The loop drains the observers only once it has its outcome (`finish()`), so the first drain is also where an
100
+ // abort stops mattering: it could no longer change the outcome, only add an `abort` event after it.
101
+ const drain = () => {
102
+ this.#settled = true;
103
+ return this.#bus.flush();
104
+ };
105
+ const loop = Promise.resolve().then(() => runLoop({ ...setup, signal: this.#controller.signal, steering: this.#steering }, emit, drain));
106
+ // The loop's result type is `RunResult<unknown>`; only the output tool, whose type is `S`, fills `output`.
107
+ this.result = loop;
108
+ // Handling the rejection here also keeps a caller who only iterates from an unhandled rejection: iteration
109
+ // throws the same error.
110
+ loop.then(() => this.#end(signal, forwardAbort, undefined), (error) => this.#end(signal, forwardAbort, { error }));
111
+ }
112
+ abort(reason) {
113
+ if (this.#settled || this.#ended || this.#controller.signal.aborted)
114
+ return;
115
+ this.#push(reason === undefined ? { type: "abort" } : { type: "abort", reason }, this.#stepIndex);
116
+ this.#controller.abort(reason);
117
+ }
118
+ on(observer) {
119
+ checkObserver(observer);
120
+ return this.#bus.add(observer);
121
+ }
122
+ steer(message) {
123
+ return this.#steering.add("steer", message);
124
+ }
125
+ followUp(message) {
126
+ return this.#steering.add("follow_up", message);
127
+ }
128
+ [Symbol.asyncIterator]() {
129
+ let cursor = 0;
130
+ return {
131
+ next: async () => {
132
+ while (cursor >= this.#events.length && !this.#ended) {
133
+ await new Promise((resolve) => this.#waiters.push(resolve));
134
+ }
135
+ const event = this.#events[cursor];
136
+ if (event !== undefined) {
137
+ cursor += 1;
138
+ return { value: event, done: false };
139
+ }
140
+ if (this.#failure !== undefined)
141
+ throw this.#failure.error;
142
+ return { value: undefined, done: true };
143
+ },
144
+ };
145
+ }
146
+ #push(body, stepIndex) {
147
+ this.#stepIndex = stepIndex;
148
+ if (body.type === "run_end")
149
+ this.#closed = true;
150
+ const base = { runId: this.id, seq: this.#events.length, stepIndex, timestamp: this.#clock.now() };
151
+ const event = { ...base, ...body };
152
+ this.#events.push(event);
153
+ this.#bus.deliver(event);
154
+ this.#wake();
155
+ }
156
+ #end(signal, forwardAbort, failure) {
157
+ signal?.removeEventListener("abort", forwardAbort);
158
+ this.#failure = failure;
159
+ this.#ended = true;
160
+ this.#wake();
161
+ }
162
+ #wake() {
163
+ const waiters = this.#waiters;
164
+ this.#waiters = [];
165
+ for (const wake of waiters)
166
+ wake();
167
+ }
168
+ }
169
+ function isModel(model) {
170
+ const candidate = model;
171
+ return (typeof candidate === "object" &&
172
+ candidate !== null &&
173
+ typeof candidate.stream === "function" &&
174
+ typeof candidate.price === "function" &&
175
+ typeof candidate.ref === "object");
176
+ }
177
+ /** Every tool the run may send, the output tool last unless `tools` already holds it, after checking each one. */
178
+ function toolsOf(options) {
179
+ const tools = [...(options.tools ?? [])];
180
+ const output = options.output;
181
+ if (output !== undefined && !tools.includes(output))
182
+ tools.push(output);
183
+ const names = new Set();
184
+ for (const tool of tools) {
185
+ preparedSchemaOf(tool);
186
+ if (names.has(tool.name)) {
187
+ throw new SdkError("invalid_tool_definition", `two tools are named "${tool.name}"; tool names must be unique`);
188
+ }
189
+ names.add(tool.name);
190
+ }
191
+ return tools;
192
+ }
193
+ function isCount(value) {
194
+ return typeof value === "number" && Number.isInteger(value) && value >= 0;
195
+ }
196
+ /**
197
+ * The `depth` and `maxDepth` options for a run that a tool starts: one level deeper than the tool's own run, under
198
+ * the same cap. Spread it into the nested `run()`; the nested run throws `max_depth_exceeded` when the tool was
199
+ * already at `maxDepth`.
200
+ */
201
+ export function nestedRunDepth(ctx) {
202
+ return { depth: ctx.depth + 1, maxDepth: ctx.maxDepth };
203
+ }
204
+ /** Checks `depth` and `maxDepth`, and refuses a run nested deeper than the cap allows (D11). */
205
+ function depthsOf(options) {
206
+ const { depth = 0, maxDepth = DEFAULT_MAX_DEPTH } = options;
207
+ if (!isCount(depth) || !isCount(maxDepth)) {
208
+ throw new SdkError("invalid_run_options", `depth and maxDepth must be whole numbers, 0 or more, got ${String(depth)} and ${String(maxDepth)}`);
209
+ }
210
+ if (depth > maxDepth) {
211
+ throw new SdkError("max_depth_exceeded", `a run at depth ${depth} is deeper than maxDepth ${maxDepth} allows`);
212
+ }
213
+ return { depth, maxDepth };
214
+ }
215
+ /**
216
+ * The default progress policy for this run, or `undefined` when `progress: false` turns it off. `skip` is the number
217
+ * of messages before the run's own.
218
+ */
219
+ function progressOf(options, tools, skip) {
220
+ const policy = resolveProgress(options.progress);
221
+ return policy === undefined ? undefined : progressCheck(tools, policy, skip);
222
+ }
223
+ function setupOf(options, context, input) {
224
+ if (!isModel(options.model)) {
225
+ throw new SdkError("invalid_run_options", "the model must come from createModel(), such as createModel({ adapter, id })");
226
+ }
227
+ const maxSteps = options.maxSteps ?? DEFAULT_MAX_STEPS;
228
+ if (!Number.isInteger(maxSteps) || maxSteps < 1) {
229
+ throw new SdkError("invalid_run_options", `maxSteps must be a positive integer, got ${maxSteps}`);
230
+ }
231
+ const signer = options.signer ?? ephemeralSigner();
232
+ if (!isSigner(signer)) {
233
+ throw new SdkError("invalid_run_options", "signer must be an ApprovalSigner, such as hmacSigner() or ephemeralSigner()");
234
+ }
235
+ const budgetUsd = checkBudgetOption(options.budgetUsd);
236
+ const tools = toolsOf(options);
237
+ const { depth, maxDepth } = depthsOf(options);
238
+ const progress = progressOf(options, tools, context.messages.length + input.length);
239
+ if (options.output !== undefined && (options.output.exposure ?? "direct") !== "direct") {
240
+ throw new SdkError("invalid_run_options", `the output tool "${options.output.name}" must be sent to the model, so its exposure must be "direct"`);
241
+ }
242
+ const nextId = options.idGenerator ?? randomIds;
243
+ return {
244
+ runId: nextId(),
245
+ nextId,
246
+ signer,
247
+ model: options.model,
248
+ system: context.system,
249
+ history: context.messages,
250
+ input,
251
+ tools,
252
+ output: options.output,
253
+ maxSteps,
254
+ ...(budgetUsd === undefined ? {} : { budgetUsd }),
255
+ depth,
256
+ maxDepth,
257
+ modelOptions: options.modelOptions ?? {},
258
+ interceptors: checkInterceptors(options.interceptors ?? {}),
259
+ ...(progress === undefined ? {} : { progress }),
260
+ clock: options.clock ?? systemClock,
261
+ };
262
+ }
263
+ function observersOf(options) {
264
+ const observers = options.observers ?? [];
265
+ for (const observer of observers)
266
+ checkObserver(observer);
267
+ const timeoutMs = options.observerTimeoutMs ?? DEFAULT_OBSERVER_TIMEOUT_MS;
268
+ if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMER_MS) {
269
+ throw new SdkError("invalid_run_options", `observerTimeoutMs must be a number from 1 to ${MAX_TIMER_MS}, got ${timeoutMs}`);
270
+ }
271
+ return { observers, timeoutMs };
272
+ }
273
+ /**
274
+ * Starts a run: the model answers `input`, runs the tools it asks for, and goes on until it answers without a tool
275
+ * call, an output tool accepts its answer, or a stop reason ends the run early. Throws an `SdkError` at once for an
276
+ * unusable option: a model that isn't from `createModel()`, a `maxSteps` that isn't a positive integer, an output tool
277
+ * that isn't sent to the model, or two tools with one name.
278
+ */
279
+ export function run(options) {
280
+ const content = typeof options.input === "string" ? [{ type: "text", text: options.input }] : options.input;
281
+ const input = { role: "user", content: [...content] };
282
+ const setup = setupOf(options, { system: options.system, messages: options.history ?? [] }, [input]);
283
+ return new RunHandle(setup, options.signal, observersOf(options));
284
+ }
285
+ /**
286
+ * Goes on with a conversation from a result's `context`, or one you rebuilt from your own store. It runs like
287
+ * `run()`, from the last message in the context, and `result.messages` holds only the messages it adds. The context
288
+ * is sent as it stands, so add a user message to one that ends with the model's answer, such as a `done` result's.
289
+ * A context whose last response ended in an error asks the model again.
290
+ *
291
+ * A paused context resumes with `resolutions`. Before the first model call, each waiting call's stored request is
292
+ * verified with the run's `signer` against its call and its input in `context.pendingInputs`, then:
293
+ *
294
+ * - a verified `allow` runs the call once, with the input its request signs and without `beforeToolCall`, after
295
+ * `recheck` allows it;
296
+ * - a verified `deny` gives the model an error result with the reason, and a verified `answer` reaches the model as
297
+ * the call's result;
298
+ * - a request no resolution names still waits;
299
+ * - a request or resolution that fails its check runs nothing, emits `resolution_rejected`, and the call asks again
300
+ * with a new approval request: the gate is asked as for a new call, and the call pauses even when the gate allows
301
+ * it. A call to a tool the model isn't sent by default gets the unknown-tool error result instead.
302
+ *
303
+ * Settling the requests is not a step. When a call still waits, the run ends paused again without a model call, and
304
+ * when none does and an approved call's result sets `terminate`, the run ends `done` without one.
305
+ * Each request answers once per context, but the SDK can't see other processes: mark a request used in your store
306
+ * before you resume it, so a second resume of the same stored context is refused there.
307
+ *
308
+ * Throws an `SdkError` with code `invalid_run_options` for a context it can't read, for a context whose last
309
+ * assistant message has a call with no result and no pending request, for a pending request whose call doesn't wait
310
+ * in the context, and for malformed `resolutions` or `recheck`, besides the options `run()` refuses.
311
+ */
312
+ export function continueRun(context, options) {
313
+ const resume = resumeSetupOf(context, options?.resolutions, options?.recheck);
314
+ const setup = setupOf(options, context, []);
315
+ return new RunHandle(resume === undefined ? setup : { ...setup, resume }, options.signal, observersOf(options));
316
+ }
317
+ /**
318
+ * Awaits a run and returns its result if it ended `done`. Any other stop reason throws a `RunStoppedError` that
319
+ * carries the result and the context to continue from.
320
+ */
321
+ export async function runOrThrow(started) {
322
+ const result = await started.result;
323
+ if (result.stopReason === "done")
324
+ return result;
325
+ throw new RunStoppedError(result);
326
+ }
327
+ //# sourceMappingURL=run.js.map