@buildanagent/sdk 0.1.0-alpha.10 → 0.1.0-alpha.12
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 +45 -1
- package/dist/errors.d.ts +6 -3
- package/dist/errors.js +3 -0
- package/dist/errors.js.map +1 -1
- package/dist/testing/auto-responder.d.ts +35 -0
- package/dist/testing/auto-responder.js +142 -0
- package/dist/testing/auto-responder.js.map +1 -0
- package/dist/testing/index.d.ts +11 -4
- package/dist/testing/index.js +10 -3
- package/dist/testing/index.js.map +1 -1
- package/dist/testing/recording.d.ts +92 -0
- package/dist/testing/recording.js +130 -0
- package/dist/testing/recording.js.map +1 -0
- package/dist/testing/replay.d.ts +41 -0
- package/dist/testing/replay.js +134 -0
- package/dist/testing/replay.js.map +1 -0
- package/dist/testing/scripted-approvals.d.ts +32 -0
- package/dist/testing/scripted-approvals.js +31 -0
- package/dist/testing/scripted-approvals.js.map +1 -0
- package/dist/testing/scripted-mcp.d.ts +43 -0
- package/dist/testing/scripted-mcp.js +67 -0
- package/dist/testing/scripted-mcp.js.map +1 -0
- package/dist/testing/scripted-model.d.ts +11 -2
- package/dist/testing/scripted-model.js +33 -2
- package/dist/testing/scripted-model.js.map +1 -1
- package/dist/vendor/agent-safety/errors.d.ts +2 -1
- package/dist/vendor/agent-safety/errors.js.map +1 -1
- package/dist/vendor/agent-safety/test-signer.d.ts +13 -0
- package/dist/vendor/agent-safety/test-signer.js +18 -0
- package/dist/vendor/agent-safety/test-signer.js.map +1 -0
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scripted-model.js","sourceRoot":"","sources":["../../src/testing/scripted-model.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAGL,UAAU,EAQV,eAAe,GAChB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAwCxC,MAAM,YAAY,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AAK,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC;gBACzF,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,SAAS,CAAC,GAAG,EAAE,SAAS,CAAC,EAAE,CAAC;gBAC5D,OAAO,KAAK,CAAC;YACf,CAAC;YACD,OAAO,IAAI,KAAK,CAAC;YACjB,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,QAAQ,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;QAChD,CAAC;QACD,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACxB,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;QAC5C,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["/**\n * `ScriptedModel`: the strict scripted test model every loop, tool, hook and pause test drives\n * (SDK plan §3.3, §5.1; SDK decision 14; agent-SDK guide §8).\n *\n * - **Strict.** A call past the last step throws `UnexpectedModelCallError`; `assertComplete()` throws if steps remain.\n * - **Frozen snapshots.** Each request is cloned and deeply frozen when the call is made, so later mutation of the\n * caller's context never changes `calls`.\n * - **Realistic streams.** Text, reasoning and tool-input JSON arrive in chunks of `chunkSize` characters, and the\n * abort signal is checked between chunks.\n * - **Deterministic.** Chunk sizes and generated ids come only from the options, never `Math.random()` or `Date.now()`.\n *\n * It implements the gateway's `ModelAdapter` and imports nothing from the loop, so gateway tests can use it too.\n */\nimport {\n type AssistantMessage,\n type ContentBlock,\n emptyUsage,\n type ModelAdapter,\n type ModelCaps,\n type ModelContext,\n type ModelEvent,\n type ModelRef,\n type StreamOptions,\n type Usage,\n unreportedUsage,\n} from \"@buildanagent/gateway\";\nimport { SdkError } from \"../errors.js\";\n\n/** One scripted model response. */\nexport interface AssistantScript {\n content: ContentBlock[];\n /** Defaults to `\"tool_calls\"` when `content` has a tool call, else `\"stop\"`. Ignored when `error` is set. */\n stopReason?: \"stop\" | \"length\" | \"tool_calls\";\n /** Ends the stream with an `error` terminal (`stopReason: \"error\"`) after streaming `content`. */\n error?: NonNullable<AssistantMessage[\"error\"]>;\n /**\n * The token counts the response reports; counts left out are zero. Leave `usage` itself out to script a provider\n * that reports none: the message's usage is then `unreported`, and `createModel()` prices it as unknown. Pass\n * `usage: {}` for a response that reports zero tokens.\n */\n usage?: Partial<Omit<Usage, \"raw\">>;\n}\n\n/** A frozen, detached snapshot of one call: the model, the context and the serialisable options. */\nexport interface RecordedRequest {\n readonly model: ModelRef;\n readonly context: ModelContext;\n readonly options: Readonly<\n Pick<StreamOptions, \"maxOutputTokens\" | \"temperature\" | \"cacheRetention\" | \"providerOptions\">\n >;\n}\n\n/** A fixed response, or a responder that builds one from the recorded request. */\nexport type ScriptStep = AssistantScript | ((request: RecordedRequest) => AssistantScript | Promise<AssistantScript>);\n\nexport interface ScriptedModelOptions {\n /** Characters per delta. Default 4. */\n chunkSize?: number;\n /** Overrides the adapter's `api` and `provider` (`\"scripted\"` by default). */\n ref?: Partial<ModelRef>;\n /** Fills in missing tool-call ids. Default `call-1`, `call-2`, … */\n idGenerator?: () => string;\n /** The caps `createModel()` gives this model. Default: 200,000-token window, 32,000 output tokens, images, reasoning. */\n caps?: ModelCaps;\n}\n\nconst DEFAULT_CAPS: ModelCaps = { contextWindow: 200_000, maxOutputTokens: 32_000, images: true, reasoning: true };\n\n/**\n * Thrown when a `ScriptedModel` is called after its last scripted step. It is an `SdkError` with code\n * `unexpected_model_call`, so `isSdkError()` recognises it too.\n */\nexport class UnexpectedModelCallError extends SdkError {\n override readonly name = \"UnexpectedModelCallError\";\n\n constructor(message: string) {\n super(\"unexpected_model_call\", message);\n }\n}\n\nfunction deepFreeze<T>(value: T): T {\n if (value && typeof value === \"object\" && !Object.isFrozen(value)) {\n Object.freeze(value);\n for (const key of Reflect.ownKeys(value)) deepFreeze((value as Record<PropertyKey, unknown>)[key]);\n }\n return value;\n}\n\nfunction chunks(text: string, size: number): string[] {\n if (text.length === 0) return [];\n const out: string[] = [];\n for (let i = 0; i < text.length; i += size) out.push(text.slice(i, i + size));\n return out;\n}\n\n/** What one stream has built so far. */\ninterface RunState {\n readonly model: ModelRef;\n readonly content: ContentBlock[];\n readonly usage: Usage;\n}\n\n/** The serialisable stream options, with omitted ones left out rather than set to `undefined`. */\nfunction recordedOptions(options: StreamOptions): RecordedRequest[\"options\"] {\n const recorded: { -readonly [K in keyof RecordedRequest[\"options\"]]: RecordedRequest[\"options\"][K] } = {};\n if (options.maxOutputTokens !== undefined) recorded.maxOutputTokens = options.maxOutputTokens;\n if (options.temperature !== undefined) recorded.temperature = options.temperature;\n if (options.cacheRetention !== undefined) recorded.cacheRetention = options.cacheRetention;\n if (options.providerOptions !== undefined) recorded.providerOptions = options.providerOptions;\n return recorded;\n}\n\nfunction messageOf(\n run: RunState,\n stopReason: AssistantMessage[\"stopReason\"],\n error?: NonNullable<AssistantMessage[\"error\"]>,\n): AssistantMessage {\n return {\n role: \"assistant\",\n content: [...run.content],\n model: run.model,\n stopReason,\n ...(error === undefined ? {} : { error }),\n usage: run.usage,\n cost: { total: null, basis: \"unknown\", currency: \"USD\" },\n };\n}\n\n/** The terminal event once every block has streamed: an error if the script set one, else done. */\nfunction terminal(run: RunState, script: AssistantScript): ModelEvent {\n if (script.error) return { type: \"error\", message: messageOf(run, \"error\", script.error) };\n const stopReason = script.stopReason ?? (run.content.some((b) => b.type === \"tool_call\") ? \"tool_calls\" : \"stop\");\n return { type: \"done\", message: messageOf(run, stopReason) };\n}\n\nexport class ScriptedModel implements ModelAdapter {\n readonly specificationVersion = \"v1\" as const;\n readonly api: string;\n readonly provider: string;\n readonly defaultCaps: ModelCaps;\n readonly #steps: ScriptStep[];\n readonly #calls: RecordedRequest[] = [];\n readonly #chunkSize: number;\n readonly #nextId: () => string;\n #used = 0;\n #overRuns = 0;\n\n constructor(steps: ScriptStep[], options: ScriptedModelOptions = {}) {\n const chunkSize = options.chunkSize ?? 4;\n if (!Number.isInteger(chunkSize) || chunkSize < 1) throw new RangeError(\"chunkSize must be a positive integer\");\n this.#steps = [...steps];\n this.#chunkSize = chunkSize;\n this.api = options.ref?.api ?? \"scripted\";\n this.provider = options.ref?.provider ?? \"scripted\";\n this.defaultCaps = { ...(options.caps ?? DEFAULT_CAPS) };\n let n = 0;\n this.#nextId = options.idGenerator ?? (() => `call-${++n}`);\n }\n\n /** Every call so far, as frozen, detached snapshots. */\n get calls(): readonly RecordedRequest[] {\n return this.#calls;\n }\n\n /**\n * Throws if any scripted step was never used, or if the model was called after its last step. Call it in test\n * teardown: `createModel()` turns an over-run's `UnexpectedModelCallError` into a failed call, so a run reports it\n * as an `error` result, and only this check makes the test fail.\n */\n assertComplete(): void {\n if (this.#overRuns > 0) {\n throw new UnexpectedModelCallError(\n `ScriptedModel: called ${this.#overRuns} more time(s) than its ${this.#steps.length} scripted steps allow`,\n );\n }\n const remaining = this.#steps.length - this.#used;\n if (remaining > 0) {\n throw new Error(`ScriptedModel: ${remaining} of ${this.#steps.length} scripted steps were never called`);\n }\n }\n\n stream(model: ModelRef, context: ModelContext, options: StreamOptions): AsyncIterable<ModelEvent> {\n const callNumber = this.#used + 1;\n const step = this.#steps[this.#used];\n if (step === undefined) return this.#overRun(callNumber);\n const request: RecordedRequest = deepFreeze(structuredClone({ model, context, options: recordedOptions(options) }));\n this.#calls.push(request);\n this.#used += 1;\n return this.#run(step, request, options.signal);\n }\n\n // The error surfaces when the caller reads the stream, like any other stream failure, not when it calls stream().\n #overRun(callNumber: number): AsyncIterable<ModelEvent> {\n this.#overRuns += 1;\n const error = new UnexpectedModelCallError(\n `ScriptedModel: call ${callNumber} has no scripted step (the script has ${this.#steps.length})`,\n );\n return { [Symbol.asyncIterator]: () => ({ next: () => Promise.reject(error) }) };\n }\n\n async *#run(step: ScriptStep, request: RecordedRequest, signal: AbortSignal | undefined): AsyncGenerator<ModelEvent> {\n const script = typeof step === \"function\" ? await step(request) : step;\n const usage = script.usage === undefined ? unreportedUsage() : { ...emptyUsage(), ...script.usage, raw: null };\n const run: RunState = { model: request.model, content: [], usage };\n yield { type: \"start\" };\n let index = 0;\n for (const scripted of script.content) {\n // Checked before the call id is drawn, so an abort leaves the id sequence and the image blocks untouched.\n if (signal?.aborted) {\n yield { type: \"error\", message: messageOf(run, \"aborted\") };\n return;\n }\n const block = this.#withCallId(scripted);\n if (block.type === \"image\") {\n run.content.push(block);\n continue;\n }\n const completed = yield* this.#streamBlock(block, index, run, signal);\n if (!completed) return;\n index += 1;\n }\n yield terminal(run, script);\n }\n\n #withCallId(scripted: ContentBlock): ContentBlock {\n if (scripted.type === \"tool_call\" && !scripted.callId) return { ...scripted, callId: this.#nextId() };\n return structuredClone(scripted);\n }\n\n /** Streams one text, reasoning or tool-call block in chunks; returns false after an abort ends the stream. */\n async *#streamBlock(\n block: Exclude<ContentBlock, { type: \"image\" }>,\n index: number,\n run: RunState,\n signal: AbortSignal | undefined,\n ): AsyncGenerator<ModelEvent, boolean> {\n const kind = block.type === \"tool_call\" ? \"tool_input\" : block.type;\n const text = block.type === \"tool_call\" ? JSON.stringify(block.input ?? {}) : block.text;\n yield { type: `${kind}_start`, index };\n let partial = \"\";\n for (const delta of chunks(text, this.#chunkSize)) {\n if (signal?.aborted) {\n // An aborted stream keeps the text streamed so far, but never a partial tool call.\n if (block.type !== \"tool_call\" && partial) run.content.push({ ...block, text: partial });\n yield { type: \"error\", message: messageOf(run, \"aborted\") };\n return false;\n }\n partial += delta;\n yield { type: `${kind}_delta`, index, delta };\n }\n run.content.push(block);\n yield { type: `${kind}_end`, index, block };\n return true;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"scripted-model.js","sourceRoot":"","sources":["../../src/testing/scripted-model.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAGL,UAAU,EAQV,eAAe,GAChB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAmDxC,MAAM,YAAY,GAAc,EAA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AAI,OAAO,GAAG,EAAE,CAAC;QACjB,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;YAClD,IAAI,MAAM,EAAE,OAAO,EAAE,CAAC;gBACpB,mFAAmF;gBACnF,IAAI,KAAK,CAAC,IAAI,KAAK,WAAW,IAAI,OAAO;oBAAE,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC;gBACzF,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,SAAS,CAAC,GAAG,EAAE,SAAS,CAAC,EAAE,CAAC;gBAC5D,OAAO,KAAK,CAAC;YACf,CAAC;YACD,OAAO,IAAI,KAAK,CAAC;YACjB,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,QAAQ,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;QAChD,CAAC;QACD,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACxB,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;QAC5C,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["/**\n * `ScriptedModel`: the strict scripted test model every loop, tool, hook and pause test drives\n * (SDK plan §3.3, §5.1; SDK decision 14; agent-SDK guide §8).\n *\n * - **Strict.** A call past the last step throws `UnexpectedModelCallError`; `assertComplete()` throws if steps remain.\n * - **Frozen snapshots.** Each request is cloned and deeply frozen when the call is made, so later mutation of the\n * caller's context never changes `calls`.\n * - **Realistic streams.** Text, reasoning and tool-input JSON arrive in chunks of `chunkSize` characters, and the\n * abort signal is checked between chunks. A `StreamScript` instead plays back recorded events exactly as they came.\n * - **Deterministic.** Chunk sizes and generated ids come only from the options, never `Math.random()` or `Date.now()`.\n *\n * It implements the gateway's `ModelAdapter` and imports nothing from the loop, so gateway tests can use it too.\n */\nimport {\n type AssistantMessage,\n type ContentBlock,\n emptyUsage,\n type ModelAdapter,\n type ModelCaps,\n type ModelContext,\n type ModelEvent,\n type ModelRef,\n type StreamOptions,\n type Usage,\n unreportedUsage,\n} from \"@buildanagent/gateway\";\nimport { SdkError } from \"../errors.js\";\n\n/** One scripted model response. */\nexport interface AssistantScript {\n content: ContentBlock[];\n /** Defaults to `\"tool_calls\"` when `content` has a tool call, else `\"stop\"`. Ignored when `error` is set. */\n stopReason?: \"stop\" | \"length\" | \"tool_calls\";\n /** Ends the stream with an `error` terminal (`stopReason: \"error\"`) after streaming `content`. */\n error?: NonNullable<AssistantMessage[\"error\"]>;\n /**\n * The token counts the response reports; counts left out are zero. Leave `usage` itself out to script a provider\n * that reports none: the message's usage is then `unreported`, and `createModel()` prices it as unknown. Pass\n * `usage: {}` for a response that reports zero tokens.\n */\n usage?: Partial<Omit<Usage, \"raw\">>;\n}\n\n/** A frozen, detached snapshot of one call: the model, the context and the serialisable options. */\nexport interface RecordedRequest {\n readonly model: ModelRef;\n readonly context: ModelContext;\n readonly options: Readonly<\n Pick<StreamOptions, \"maxOutputTokens\" | \"temperature\" | \"cacheRetention\" | \"providerOptions\">\n >;\n}\n\n/**\n * A response played back event for event, such as one `recordPairs()` captured from a real model. `events` must start\n * with `start` and end with its only terminal, `done` or `error`; the abort signal is checked between events.\n */\nexport interface StreamScript {\n readonly events: readonly ModelEvent[];\n}\n\n/** A fixed response, or a responder that builds one from the recorded request. */\nexport type ScriptStep =\n | AssistantScript\n | StreamScript\n | ((request: RecordedRequest) => AssistantScript | StreamScript | Promise<AssistantScript | StreamScript>);\n\nexport interface ScriptedModelOptions {\n /** Characters per delta. Default 4. */\n chunkSize?: number;\n /** Overrides the adapter's `api` and `provider` (`\"scripted\"` by default). */\n ref?: Partial<ModelRef>;\n /** Fills in missing tool-call ids. Default `call-1`, `call-2`, … */\n idGenerator?: () => string;\n /** The caps `createModel()` gives this model. Default: 200,000-token window, 32,000 output tokens, images, reasoning. */\n caps?: ModelCaps;\n}\n\nconst DEFAULT_CAPS: ModelCaps = { contextWindow: 200_000, maxOutputTokens: 32_000, images: true, reasoning: true };\n\n/**\n * Thrown when a `ScriptedModel` is called after its last scripted step. It is an `SdkError` with code\n * `unexpected_model_call`, so `isSdkError()` recognises it too.\n */\nexport class UnexpectedModelCallError extends SdkError {\n override readonly name = \"UnexpectedModelCallError\";\n\n constructor(message: string) {\n super(\"unexpected_model_call\", message);\n }\n}\n\nfunction deepFreeze<T>(value: T): T {\n if (value && typeof value === \"object\" && !Object.isFrozen(value)) {\n Object.freeze(value);\n for (const key of Reflect.ownKeys(value)) deepFreeze((value as Record<PropertyKey, unknown>)[key]);\n }\n return value;\n}\n\nfunction chunks(text: string, size: number): string[] {\n if (text.length === 0) return [];\n const out: string[] = [];\n for (let i = 0; i < text.length; i += size) out.push(text.slice(i, i + size));\n return out;\n}\n\n/** What one stream has built so far. */\ninterface RunState {\n readonly model: ModelRef;\n readonly content: ContentBlock[];\n readonly usage: Usage;\n}\n\n/** The serialisable stream options, with omitted ones left out rather than set to `undefined`. */\nexport function recordedOptions(options: StreamOptions): RecordedRequest[\"options\"] {\n const recorded: { -readonly [K in keyof RecordedRequest[\"options\"]]: RecordedRequest[\"options\"][K] } = {};\n if (options.maxOutputTokens !== undefined) recorded.maxOutputTokens = options.maxOutputTokens;\n if (options.temperature !== undefined) recorded.temperature = options.temperature;\n if (options.cacheRetention !== undefined) recorded.cacheRetention = options.cacheRetention;\n if (options.providerOptions !== undefined) recorded.providerOptions = options.providerOptions;\n return recorded;\n}\n\nfunction messageOf(\n run: RunState,\n stopReason: AssistantMessage[\"stopReason\"],\n error?: NonNullable<AssistantMessage[\"error\"]>,\n): AssistantMessage {\n return {\n role: \"assistant\",\n content: [...run.content],\n model: run.model,\n stopReason,\n ...(error === undefined ? {} : { error }),\n usage: run.usage,\n cost: { total: null, basis: \"unknown\", currency: \"USD\" },\n };\n}\n\n/** The terminal event once every block has streamed: an error if the script set one, else done. */\nfunction terminal(run: RunState, script: AssistantScript): ModelEvent {\n if (script.error) return { type: \"error\", message: messageOf(run, \"error\", script.error) };\n const stopReason = script.stopReason ?? (run.content.some((b) => b.type === \"tool_call\") ? \"tool_calls\" : \"stop\");\n return { type: \"done\", message: messageOf(run, stopReason) };\n}\n\nfunction isTerminal(event: ModelEvent): boolean {\n return event.type === \"done\" || event.type === \"error\";\n}\n\nfunction checkStreamScript(script: StreamScript): void {\n const { events } = script;\n const terminals = events.filter(isTerminal).length;\n if (events[0]?.type !== \"start\" || terminals !== 1 || !isTerminal(events[events.length - 1] as ModelEvent)) {\n throw new RangeError(\"a StreamScript's events must start with start and end with its only done or error event\");\n }\n}\n\n/** Plays a stream script's events as copies; an abort ends it with the blocks that had ended so far. */\nasync function* playEvents(script: StreamScript, model: ModelRef, signal: AbortSignal | undefined) {\n checkStreamScript(script);\n const ended: ContentBlock[] = [];\n for (const event of script.events) {\n if (signal?.aborted && event.type !== \"start\") {\n const run: RunState = { model, content: ended, usage: unreportedUsage() };\n yield { type: \"error\", message: messageOf(run, \"aborted\") } satisfies ModelEvent;\n return;\n }\n const copy = structuredClone(event);\n if (copy.type === \"text_end\" || copy.type === \"reasoning_end\" || copy.type === \"tool_input_end\") {\n ended.push(copy.block);\n }\n yield copy;\n }\n}\n\nexport class ScriptedModel implements ModelAdapter {\n readonly specificationVersion = \"v1\" as const;\n readonly api: string;\n readonly provider: string;\n readonly defaultCaps: ModelCaps;\n readonly #steps: ScriptStep[];\n readonly #calls: RecordedRequest[] = [];\n readonly #chunkSize: number;\n readonly #nextId: () => string;\n #used = 0;\n #overRuns = 0;\n\n constructor(steps: ScriptStep[], options: ScriptedModelOptions = {}) {\n const chunkSize = options.chunkSize ?? 4;\n if (!Number.isInteger(chunkSize) || chunkSize < 1) throw new RangeError(\"chunkSize must be a positive integer\");\n this.#steps = [...steps];\n this.#chunkSize = chunkSize;\n this.api = options.ref?.api ?? \"scripted\";\n this.provider = options.ref?.provider ?? \"scripted\";\n this.defaultCaps = { ...(options.caps ?? DEFAULT_CAPS) };\n let n = 0;\n this.#nextId = options.idGenerator ?? (() => `call-${++n}`);\n }\n\n /** Every call so far, as frozen, detached snapshots. */\n get calls(): readonly RecordedRequest[] {\n return this.#calls;\n }\n\n /**\n * Throws if any scripted step was never used, or if the model was called after its last step. Call it in test\n * teardown: `createModel()` turns an over-run's `UnexpectedModelCallError` into a failed call, so a run reports it\n * as an `error` result, and only this check makes the test fail.\n */\n assertComplete(): void {\n if (this.#overRuns > 0) {\n throw new UnexpectedModelCallError(\n `ScriptedModel: called ${this.#overRuns} more time(s) than its ${this.#steps.length} scripted steps allow`,\n );\n }\n const remaining = this.#steps.length - this.#used;\n if (remaining > 0) {\n throw new Error(`ScriptedModel: ${remaining} of ${this.#steps.length} scripted steps were never called`);\n }\n }\n\n stream(model: ModelRef, context: ModelContext, options: StreamOptions): AsyncIterable<ModelEvent> {\n const callNumber = this.#used + 1;\n const step = this.#steps[this.#used];\n if (step === undefined) return this.#overRun(callNumber);\n const request: RecordedRequest = deepFreeze(structuredClone({ model, context, options: recordedOptions(options) }));\n this.#calls.push(request);\n this.#used += 1;\n return this.#run(step, request, options.signal);\n }\n\n // The error surfaces when the caller reads the stream, like any other stream failure, not when it calls stream().\n #overRun(callNumber: number): AsyncIterable<ModelEvent> {\n this.#overRuns += 1;\n const error = new UnexpectedModelCallError(\n `ScriptedModel: call ${callNumber} has no scripted step (the script has ${this.#steps.length})`,\n );\n return { [Symbol.asyncIterator]: () => ({ next: () => Promise.reject(error) }) };\n }\n\n async *#run(step: ScriptStep, request: RecordedRequest, signal: AbortSignal | undefined): AsyncGenerator<ModelEvent> {\n const script = typeof step === \"function\" ? await step(request) : step;\n if (\"events\" in script) {\n yield* playEvents(script, request.model, signal);\n return;\n }\n const usage = script.usage === undefined ? unreportedUsage() : { ...emptyUsage(), ...script.usage, raw: null };\n const run: RunState = { model: request.model, content: [], usage };\n yield { type: \"start\" };\n let index = 0;\n for (const scripted of script.content) {\n // Checked before the call id is drawn, so an abort leaves the id sequence and the image blocks untouched.\n if (signal?.aborted) {\n yield { type: \"error\", message: messageOf(run, \"aborted\") };\n return;\n }\n const block = this.#withCallId(scripted);\n if (block.type === \"image\") {\n run.content.push(block);\n continue;\n }\n const completed = yield* this.#streamBlock(block, index, run, signal);\n if (!completed) return;\n index += 1;\n }\n yield terminal(run, script);\n }\n\n #withCallId(scripted: ContentBlock): ContentBlock {\n if (scripted.type === \"tool_call\" && !scripted.callId) return { ...scripted, callId: this.#nextId() };\n return structuredClone(scripted);\n }\n\n /** Streams one text, reasoning or tool-call block in chunks; returns false after an abort ends the stream. */\n async *#streamBlock(\n block: Exclude<ContentBlock, { type: \"image\" }>,\n index: number,\n run: RunState,\n signal: AbortSignal | undefined,\n ): AsyncGenerator<ModelEvent, boolean> {\n const kind = block.type === \"tool_call\" ? \"tool_input\" : block.type;\n const text = block.type === \"tool_call\" ? JSON.stringify(block.input ?? {}) : block.text;\n yield { type: `${kind}_start`, index };\n let partial = \"\";\n for (const delta of chunks(text, this.#chunkSize)) {\n if (signal?.aborted) {\n // An aborted stream keeps the text streamed so far, but never a partial tool call.\n if (block.type !== \"tool_call\" && partial) run.content.push({ ...block, text: partial });\n yield { type: \"error\", message: messageOf(run, \"aborted\") };\n return false;\n }\n partial += delta;\n yield { type: `${kind}_delta`, index, delta };\n }\n run.content.push(block);\n yield { type: `${kind}_end`, index, block };\n return true;\n }\n}\n"]}
|
|
@@ -10,8 +10,9 @@
|
|
|
10
10
|
* model provider's key or base URL is empty, malformed or points at a gateway that may bill another credential.
|
|
11
11
|
* `egress_refused`: a model request would leave for another host or carry another credential. `default_provider`: code
|
|
12
12
|
* resolved a string model id, or another default provider is set, so a call could reach a gateway nobody configured.
|
|
13
|
+
* `invalid_effect`: a guarded write's scope, business key or options break a rule.
|
|
13
14
|
*/
|
|
14
|
-
export type SafetyErrorCode = "invalid_outcome" | "invalid_input" | "invalid_key_ring" | "invalid_pending" | "invalid_byok_config" | "egress_refused" | "default_provider";
|
|
15
|
+
export type SafetyErrorCode = "invalid_outcome" | "invalid_input" | "invalid_key_ring" | "invalid_pending" | "invalid_byok_config" | "egress_refused" | "default_provider" | "invalid_effect";
|
|
15
16
|
/** Thrown for a mistake in how the safety package is called. A write that fails is an outcome, never this error. */
|
|
16
17
|
export declare class SafetyError extends Error {
|
|
17
18
|
readonly name = "SafetyError";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/vendor/agent-safety/errors.ts"],"names":[],"mappings":"AAAA;;;;GAIG;
|
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/vendor/agent-safety/errors.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAqBH,4FAA4F;AAC5F,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,uCAAuC,CAAC,CAAC;AAEzE,oHAAoH;AACpH,MAAM,OAAO,WAAY,SAAQ,KAAK;IAClB,IAAI,GAAG,aAAa,CAAC;IAC9B,IAAI,CAAkB;IAE/B,YAAY,IAAqB,EAAE,OAAe,EAAE,OAAsB;QACxE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,CAAC;CACF;AAED,gFAAgF;AAChF,MAAM,UAAU,aAAa,CAAC,KAAc;IAC1C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,YAAY,CAAC,KAAK,IAAI,CAAC;AAClH,CAAC","sourcesContent":["/**\n * `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason, an\n * input that has no canonical JSON form, a key ring that can't sign, or a model request that would use a credential\n * nobody configured.\n */\n\n/**\n * Why a `SafetyError` was thrown. `invalid_outcome`: a write outcome breaks a rule. `invalid_input`: a tool input has\n * no canonical JSON form, or a tool's context fails its `contextSchema`. `invalid_key_ring`: a signer's keys or key\n * ids can't be used. `invalid_pending`: the fields of a pending request can't be signed. `invalid_byok_config`: a\n * model provider's key or base URL is empty, malformed or points at a gateway that may bill another credential.\n * `egress_refused`: a model request would leave for another host or carry another credential. `default_provider`: code\n * resolved a string model id, or another default provider is set, so a call could reach a gateway nobody configured.\n * `invalid_effect`: a guarded write's scope, business key or options break a rule.\n */\nexport type SafetyErrorCode =\n | \"invalid_outcome\"\n | \"invalid_input\"\n | \"invalid_key_ring\"\n | \"invalid_pending\"\n | \"invalid_byok_config\"\n | \"egress_refused\"\n | \"default_provider\"\n | \"invalid_effect\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst SAFETY_ERROR = Symbol.for(\"buildanagent.agent-safety.SafetyError\");\n\n/** Thrown for a mistake in how the safety package is called. A write that fails is an outcome, never this error. */\nexport class SafetyError extends Error {\n override readonly name = \"SafetyError\";\n readonly code: SafetyErrorCode;\n\n constructor(code: SafetyErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, SAFETY_ERROR, { value: true });\n }\n}\n\n/** True for a `SafetyError`, including one from another copy of the package. */\nexport function isSafetyError(error: unknown): error is SafetyError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[SAFETY_ERROR] === true;\n}\n"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The fixed-key test signer, which `@buildanagent/agent-safety/testing` exports. It sits in its own file so the SDK
|
|
3
|
+
* can carry a copy of it without the `EffectStore` conformance cases.
|
|
4
|
+
*/
|
|
5
|
+
import { type ApprovalSigner } from "./signer.js";
|
|
6
|
+
/** The key id of `testSigner()`. */
|
|
7
|
+
export declare const TEST_KEY_ID = "test-fixed-key";
|
|
8
|
+
/**
|
|
9
|
+
* A signer with a fixed, published key, for tests and fixtures: every process produces the same signatures, so a
|
|
10
|
+
* signed pause can be checked into a test. Anyone can forge its signatures. Never use it outside tests, and never add
|
|
11
|
+
* its key id, `test-fixed-key`, to a real key ring.
|
|
12
|
+
*/
|
|
13
|
+
export declare function testSigner(): ApprovalSigner;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The fixed-key test signer, which `@buildanagent/agent-safety/testing` exports. It sits in its own file so the SDK
|
|
3
|
+
* can carry a copy of it without the `EffectStore` conformance cases.
|
|
4
|
+
*/
|
|
5
|
+
import { hmacSigner } from "./signer.js";
|
|
6
|
+
/** The key id of `testSigner()`. */
|
|
7
|
+
export const TEST_KEY_ID = "test-fixed-key";
|
|
8
|
+
// Public on purpose: tests in any process, and fixtures checked into the repo, must produce the same signatures.
|
|
9
|
+
const TEST_KEY = new TextEncoder().encode("buildanagent testSigner fixed key, never for production");
|
|
10
|
+
/**
|
|
11
|
+
* A signer with a fixed, published key, for tests and fixtures: every process produces the same signatures, so a
|
|
12
|
+
* signed pause can be checked into a test. Anyone can forge its signatures. Never use it outside tests, and never add
|
|
13
|
+
* its key id, `test-fixed-key`, to a real key ring.
|
|
14
|
+
*/
|
|
15
|
+
export function testSigner() {
|
|
16
|
+
return hmacSigner({ keys: { [TEST_KEY_ID]: TEST_KEY }, current: TEST_KEY_ID });
|
|
17
|
+
}
|
|
18
|
+
//# sourceMappingURL=test-signer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"test-signer.js","sourceRoot":"","sources":["../../../src/vendor/agent-safety/test-signer.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAuB,UAAU,EAAE,MAAM,aAAa,CAAC;AAE9D,oCAAoC;AACpC,MAAM,CAAC,MAAM,WAAW,GAAG,gBAAgB,CAAC;AAC5C,iHAAiH;AACjH,MAAM,QAAQ,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,yDAAyD,CAAC,CAAC;AAErG;;;;GAIG;AACH,MAAM,UAAU,UAAU;IACxB,OAAO,UAAU,CAAC,EAAE,IAAI,EAAE,EAAE,CAAC,WAAW,CAAC,EAAE,QAAQ,EAAE,EAAE,OAAO,EAAE,WAAW,EAAE,CAAC,CAAC;AACjF,CAAC","sourcesContent":["/**\n * The fixed-key test signer, which `@buildanagent/agent-safety/testing` exports. It sits in its own file so the SDK\n * can carry a copy of it without the `EffectStore` conformance cases.\n */\nimport { type ApprovalSigner, hmacSigner } from \"./signer.js\";\n\n/** The key id of `testSigner()`. */\nexport const TEST_KEY_ID = \"test-fixed-key\";\n// Public on purpose: tests in any process, and fixtures checked into the repo, must produce the same signatures.\nconst TEST_KEY = new TextEncoder().encode(\"buildanagent testSigner fixed key, never for production\");\n\n/**\n * A signer with a fixed, published key, for tests and fixtures: every process produces the same signatures, so a\n * signed pause can be checked into a test. Anyone can forge its signatures. Never use it outside tests, and never add\n * its key id, `test-fixed-key`, to a real key ring.\n */\nexport function testSigner(): ApprovalSigner {\n return hmacSigner({ keys: { [TEST_KEY_ID]: TEST_KEY }, current: TEST_KEY_ID });\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@buildanagent/sdk",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.12",
|
|
4
4
|
"description": "The buildanagent SDK: the agent loop, tools, hooks, signed pauses and budgets over the gateway.",
|
|
5
5
|
"license": "Apache-2.0 OR MIT",
|
|
6
6
|
"repository": {
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"dependencies": {
|
|
38
38
|
"@earendil-works/pi-schema": "1.5.2",
|
|
39
39
|
"@standard-schema/spec": "1.1.0",
|
|
40
|
-
"@buildanagent/gateway": "0.1.0-alpha.
|
|
40
|
+
"@buildanagent/gateway": "0.1.0-alpha.12"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
43
|
"@cfworker/json-schema": "4.1.6",
|