@buildanagent/sdk 0.1.0-alpha.0 → 0.1.0-alpha.1
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
CHANGED
|
@@ -37,7 +37,7 @@ const model = new ScriptedModel(
|
|
|
37
37
|
);
|
|
38
38
|
```
|
|
39
39
|
|
|
40
|
-
A step is either a fixed response or a function that builds one from the request. A response stops with `"tool_calls"` when it contains a tool call and with `"stop"` otherwise. Setting `error` ends the stream with an error instead.
|
|
40
|
+
A step is either a fixed response or a function that builds one from the request. A response stops with `"tool_calls"` when it contains a tool call and with `"stop"` otherwise. Setting `error` ends the stream with an error instead. Set `usage` to the token counts the response reports; counts you leave out are zero. A response without `usage` acts like a provider that reported none: its usage is marked `unreported`, so `createModel()` prices it as unknown rather than free. Pass `usage: {}` to report zero tokens.
|
|
41
41
|
|
|
42
42
|
## Tests give the same result every run
|
|
43
43
|
|
|
@@ -19,6 +19,11 @@ export interface AssistantScript {
|
|
|
19
19
|
stopReason?: "stop" | "length" | "tool_calls";
|
|
20
20
|
/** Ends the stream with an `error` terminal (`stopReason: "error"`) after streaming `content`. */
|
|
21
21
|
error?: NonNullable<AssistantMessage["error"]>;
|
|
22
|
+
/**
|
|
23
|
+
* The token counts the response reports; counts left out are zero. Leave `usage` itself out to script a provider
|
|
24
|
+
* that reports none: the message's usage is then `unreported`, and `createModel()` prices it as unknown. Pass
|
|
25
|
+
* `usage: {}` for a response that reports zero tokens.
|
|
26
|
+
*/
|
|
22
27
|
usage?: Partial<Omit<Usage, "raw">>;
|
|
23
28
|
}
|
|
24
29
|
/** A frozen, detached snapshot of one call: the model, the context and the serialisable options. */
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
*
|
|
12
12
|
* It implements the gateway's `ModelAdapter` and imports nothing from the loop, so gateway tests can use it too.
|
|
13
13
|
*/
|
|
14
|
-
import { emptyUsage, } from "@buildanagent/gateway";
|
|
14
|
+
import { emptyUsage, unreportedUsage, } from "@buildanagent/gateway";
|
|
15
15
|
const DEFAULT_CAPS = { contextWindow: 200_000, maxOutputTokens: 32_000, images: true, reasoning: true };
|
|
16
16
|
export class UnexpectedModelCallError extends Error {
|
|
17
17
|
name = "UnexpectedModelCallError";
|
|
@@ -113,7 +113,8 @@ export class ScriptedModel {
|
|
|
113
113
|
}
|
|
114
114
|
async *#run(step, request, signal) {
|
|
115
115
|
const script = typeof step === "function" ? await step(request) : step;
|
|
116
|
-
const
|
|
116
|
+
const usage = script.usage === undefined ? unreportedUsage() : { ...emptyUsage(), ...script.usage, raw: null };
|
|
117
|
+
const run = { model: request.model, content: [], usage };
|
|
117
118
|
yield { type: "start" };
|
|
118
119
|
let index = 0;
|
|
119
120
|
for (const scripted of script.content) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scripted-model.js","sourceRoot":"","sources":["../../src/testing/scripted-model.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAGL,UAAU,GAQX,MAAM,uBAAuB,CAAC;AAmC/B,MAAM,YAAY,GAAc,EAAE,aAAa,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AAEnH,MAAM,OAAO,wBAAyB,SAAQ,KAAK;IAC/B,IAAI,GAAG,0BAA0B,CAAC;CACrD;AAED,SAAS,UAAU,CAAI,KAAQ;IAC7B,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QAClE,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACrB,KAAK,MAAM,GAAG,IAAI,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC;YAAE,UAAU,CAAE,KAAsC,CAAC,GAAG,CAAC,CAAC,CAAC;IACrG,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAA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,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.\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} from \"@buildanagent/gateway\";\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 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\nexport class UnexpectedModelCallError extends Error {\n override readonly name = \"UnexpectedModelCallError\";\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\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 /** Throws if any scripted step was never used. Call it in test teardown. */\n assertComplete(): void {\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 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 run: RunState = { model: request.model, content: [], usage: { ...emptyUsage(), ...script.usage, raw: null } };\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;AAwC/B,MAAM,YAAY,GAAc,EAAE,aAAa,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AAEnH,MAAM,OAAO,wBAAyB,SAAQ,KAAK;IAC/B,IAAI,GAAG,0BAA0B,CAAC;CACrD;AAED,SAAS,UAAU,CAAI,KAAQ;IAC7B,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QAClE,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACrB,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W,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC;QACzF,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,QAAQ,EAAE,KAAK,EAAE,CAAC;QACvC,IAAI,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.\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\";\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\nexport class UnexpectedModelCallError extends Error {\n override readonly name = \"UnexpectedModelCallError\";\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\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 /** Throws if any scripted step was never used. Call it in test teardown. */\n assertComplete(): void {\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 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"]}
|
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.1",
|
|
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": {
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
}
|
|
36
36
|
},
|
|
37
37
|
"dependencies": {
|
|
38
|
-
"@buildanagent/gateway": "0.1.0-alpha.
|
|
38
|
+
"@buildanagent/gateway": "0.1.0-alpha.1"
|
|
39
39
|
},
|
|
40
40
|
"scripts": {
|
|
41
41
|
"build": "node ../../scripts/clean-dist.mjs && tsc -p tsconfig.build.json",
|