@buildanagent/sdk 0.1.0-alpha.0 → 0.1.0-alpha.2

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 (41) hide show
  1. package/README.md +89 -3
  2. package/dist/errors.d.ts +19 -0
  3. package/dist/errors.js +26 -0
  4. package/dist/errors.js.map +1 -0
  5. package/dist/index.d.ts +7 -3
  6. package/dist/index.js +5 -3
  7. package/dist/index.js.map +1 -1
  8. package/dist/testing/scripted-model.d.ts +5 -0
  9. package/dist/testing/scripted-model.js +3 -2
  10. package/dist/testing/scripted-model.js.map +1 -1
  11. package/dist/tools/coerce.d.ts +15 -0
  12. package/dist/tools/coerce.js +93 -0
  13. package/dist/tools/coerce.js.map +1 -0
  14. package/dist/tools/define.d.ts +42 -0
  15. package/dist/tools/define.js +96 -0
  16. package/dist/tools/define.js.map +1 -0
  17. package/dist/tools/format-error.d.ts +13 -0
  18. package/dist/tools/format-error.js +65 -0
  19. package/dist/tools/format-error.js.map +1 -0
  20. package/dist/tools/outcome.d.ts +7 -0
  21. package/dist/tools/outcome.js +30 -0
  22. package/dist/tools/outcome.js.map +1 -0
  23. package/dist/tools/pipeline.d.ts +52 -0
  24. package/dist/tools/pipeline.js +184 -0
  25. package/dist/tools/pipeline.js.map +1 -0
  26. package/dist/tools/schema.d.ts +20 -0
  27. package/dist/tools/schema.js +100 -0
  28. package/dist/tools/schema.js.map +1 -0
  29. package/dist/tools/types.d.ts +144 -0
  30. package/dist/tools/types.js +2 -0
  31. package/dist/tools/types.js.map +1 -0
  32. package/dist/vendor/agent-safety/errors.d.ts +14 -0
  33. package/dist/vendor/agent-safety/errors.js +21 -0
  34. package/dist/vendor/agent-safety/errors.js.map +1 -0
  35. package/dist/vendor/agent-safety/outcome.d.ts +88 -0
  36. package/dist/vendor/agent-safety/outcome.js +140 -0
  37. package/dist/vendor/agent-safety/outcome.js.map +1 -0
  38. package/dist/vendor/agent-safety/render.d.ts +40 -0
  39. package/dist/vendor/agent-safety/render.js +92 -0
  40. package/dist/vendor/agent-safety/render.js.map +1 -0
  41. package/package.json +11 -3
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  The SDK runs your agent's loop over [`@buildanagent/gateway`](../gateway/README.md): it calls the model, runs the tools the model asks for, and stops when the work is done. Its testing export lets you test that agent offline against a scripted model, with no API key.
4
4
 
5
- As of November 2026 the package holds only the testing export. The loop, tools, hooks, approvals and budgets are next.
5
+ As of November 2026 the package holds tool definitions and the testing export. You can define your tools and their rules now; the loop that calls the model and runs them comes next, with hooks, approvals and budgets.
6
6
 
7
7
  ## Install the alpha with `pnpm add @buildanagent/sdk@alpha`
8
8
 
@@ -12,7 +12,93 @@ Every release is an alpha until the first stable one, and npm serves the alphas
12
12
  pnpm add @buildanagent/sdk@alpha @buildanagent/gateway@alpha
13
13
  ```
14
14
 
15
- Both packages always share one version, and the SDK depends on that exact version of the gateway. Name the tag: a plain `pnpm add @buildanagent/sdk` installs `0.0.0-bootstrap.0`, a deprecated placeholder, because `latest` stays on it until the first stable release. The package needs Node 22 or later.
15
+ Both packages always share one version, and the SDK depends on that exact version of the gateway. Name the tag: a plain `pnpm add @buildanagent/sdk` installs `0.0.0-bootstrap.0`, a deprecated placeholder, because `latest` stays on it until the first stable release. The package needs Node 22.19 or later, the oldest Node its validator, pi-schema 1.5.2, supports.
16
+
17
+ Don't start Node with `--conditions=source` in a project that installs the SDK. Its validator, pi-schema 1.5.2, maps that condition to a source file its package doesn't ship, so the SDK's root entry fails to load under it ([validator check](docs/validator-check.md)).
18
+
19
+ ## Define a tool with `defineTool()`
20
+
21
+ A tool is a name, a description the model reads, an input schema and an `execute` function. This tool looks up an order in your own store:
22
+
23
+ ```ts
24
+ export function lookupOrderTool(findOrder: FindOrder) {
25
+ return defineTool({
26
+ name: "lookup_order",
27
+ description: "Look up an order by its number and return its status.",
28
+ inputSchema: z.object({ order: z.number().int().positive() }),
29
+ async execute({ order }) {
30
+ const found = await findOrder(order);
31
+ if (found === undefined) return { content: [{ type: "text", text: `No order ${order} exists.` }], isError: true };
32
+ return { content: [{ type: "text", text: `Order ${order} is ${found.status}.` }], structured: found };
33
+ },
34
+ });
35
+ }
36
+ ```
37
+
38
+ The input schema is either a Standard Schema or a raw JSON Schema object. A Standard Schema is a schema from a library that can also describe itself as JSON Schema: Zod 4.2 or later, ArkType, or Valibot through `toStandardJsonSchema()` from `@valibot/to-json-schema`. A raw schema follows draft 2020-12, or draft 7 when its `$schema` names draft 7. Raw schemas check `format` keywords such as `email` and `date`.
39
+
40
+ `execute` receives the validated input and returns a tool result with three channels:
41
+
42
+ - **`content`** is the text and images the model reads.
43
+ - **`details`** is for your logs and user interface; the model never sees it.
44
+ - **`structured`** is typed data for your code, such as the order above.
45
+
46
+ `defineTool()` checks the tool once, when you call it. A name outside the tool-name rule, 1 to 64 characters from `A-Z`, `a-z`, `0-9`, `_` and `-`, throws an `SdkError`. So does a schema that does not compile.
47
+
48
+ ## A failed call becomes an error the model can fix
49
+
50
+ Every tool call runs the same steps in order: find the tool by name, coerce the arguments, validate them, give `repair` one chance, then run `execute`. A failure the model caused, at any step, returns an error result to the model and throws nothing. When the model sends `"forty-two"` as the order number, it reads this:
51
+
52
+ ```text
53
+ The arguments for tool "lookup_order" are invalid:
54
+ - /order: Invalid input: expected number, received string
55
+ Received arguments: {"order":"forty-two"}
56
+ Do not substitute a mock, a placeholder or invented data for this tool's result. Fix the call, try another approach, or tell the user what failed.
57
+ ```
58
+
59
+ Each failing field appears as its JSON Pointer path, so the model knows exactly what to fix. The last line is there because agents have been seen to answer a failed tool by inventing a result. Three options on the tool and one flag on your own result change what happens:
60
+
61
+ - **`repair`** receives invalid input and its issues, and returns fixed input to validate again, or `undefined` to report the failure.
62
+ - **`formatError`** builds the model's content for a failed call in place of the default text.
63
+ - **`redactErrors: true`** shows the model a fixed line when `execute` throws, and keeps the thrown message in the result's `details`. Use it when error messages may hold secrets, such as connection strings.
64
+ - **`isError: true`** on your own result marks a failure you report yourself, such as an order that doesn't exist.
65
+
66
+ The model also sees an error for a tool name that doesn't exist, with the list of real ones. A response that stopped at its output limit runs none of its tool calls, because their arguments may be cut short; the model is asked to send each call again. A response that ended in an error or was aborted runs none of its calls either, and once the run is cancelled no further call starts.
67
+
68
+ ## Arguments are coerced by three rules
69
+
70
+ Models sometimes send a number as a string. Before validation, the SDK converts these values, and nothing else:
71
+
72
+ 1. A string holding JSON becomes the object or array it encodes, where the schema expects an object or an array.
73
+ 2. A string holding a decimal number becomes that number, where the schema expects a number, or an integer when the number is whole. A whole number beyond 2^53 stays a string, because JavaScript would round it to a different number.
74
+ 3. The string `"true"` or `"false"` becomes a boolean, where the schema expects a boolean.
75
+
76
+ The rules reach nested values through `properties` and `items`, and only where the schema names a single type. A value that already has the expected type is never changed.
77
+
78
+ ## Report what a write did with an outcome
79
+
80
+ A tool that changes the world, such as a refund, declares `effect: { kind: "write" }`. A tool without it counts as read-only, so it is safe to run again after a crash. The optional `businessKey` names the real-world operation, such as `refund:42`, so a retry is recognised as the same refund.
81
+
82
+ Such a tool returns an `outcome` beside its content. An outcome says which of five things happened: `applied`, `not_applied`, `compensated`, `partial` or `unknown`. It also says what the model should do next and whether a retry is safe. This refund tool reports a declined refund:
83
+
84
+ ```ts
85
+ return { ...base, kind: "not_applied", retry: "never", applied: [], reason: reply.code, next };
86
+ ```
87
+
88
+ The model reads the outcome first, as a sentence and as JSON, and then your content. For the declined refund the sentence begins "The refund_create call did not take effect, and nothing changed." Every kind except `applied` marks the result as an error. An outcome that breaks a rule, such as a retry its kind doesn't allow, throws an `SdkError`.
89
+
90
+ ## End the run with `outputTool()`, or ask with `clarificationTool()`
91
+
92
+ `outputTool({ name, schema })` turns the run's final answer into a tool call. A call whose input passes the schema ends the run, and the validated answer is the result's `structured` value. A call that fails the schema returns the issues to the model, which can correct its answer and call again.
93
+
94
+ `clarificationTool()` gives the model a tool named `ask_user` that takes one `question`. Its result carries the question as a pause, so the run can wait for the user's answer. Pass `{ name }` to call it something else.
95
+
96
+ ## `SdkError` marks a mistake in your code
97
+
98
+ The SDK throws only for programmer errors, never for a failure the model caused. `isSdkError(error)` recognises the error, and its `code` says why:
99
+
100
+ - **`invalid_tool_definition`**: a tool's name, description or schema is unusable, or two tools share a name.
101
+ - **`invalid_tool_result`**: `execute` returned something other than a tool result, or an invalid outcome. A text block needs a string `text`, and an image block a string `mediaType` and `data`.
16
102
 
17
103
  ## Test against a strict scripted model
18
104
 
@@ -37,7 +123,7 @@ const model = new ScriptedModel(
37
123
  );
38
124
  ```
39
125
 
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.
126
+ 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
127
 
42
128
  ## Tests give the same result every run
43
129
 
@@ -0,0 +1,19 @@
1
+ /**
2
+ * `SdkError`: the SDK's error for programmer errors, such as a tool definition that breaks the name rule or a tool
3
+ * that returns something other than a tool result. A failure the model caused, such as invalid tool input, is never
4
+ * thrown: the tool pipeline returns it to the model as an error result.
5
+ */
6
+ /** Why an `SdkError` was thrown. */
7
+ export type SdkErrorCode = "invalid_tool_definition" | "invalid_tool_result";
8
+ /**
9
+ * Thrown for a mistake in how the SDK is called. `invalid_tool_definition`: a tool's name, description or schema
10
+ * is unusable, or two tools share a name. `invalid_tool_result`: a tool's `execute` returned a malformed result or
11
+ * write outcome.
12
+ */
13
+ export declare class SdkError extends Error {
14
+ readonly name = "SdkError";
15
+ readonly code: SdkErrorCode;
16
+ constructor(code: SdkErrorCode, message: string, options?: ErrorOptions);
17
+ }
18
+ /** True for an `SdkError`, including one from another copy of the package. */
19
+ export declare function isSdkError(error: unknown): error is SdkError;
package/dist/errors.js ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * `SdkError`: the SDK's error for programmer errors, such as a tool definition that breaks the name rule or a tool
3
+ * that returns something other than a tool result. A failure the model caused, such as invalid tool input, is never
4
+ * thrown: the tool pipeline returns it to the model as an error result.
5
+ */
6
+ // A registered symbol, so the guard still works when two copies of the package are bundled.
7
+ const SDK_ERROR = Symbol.for("buildanagent.sdk.SdkError");
8
+ /**
9
+ * Thrown for a mistake in how the SDK is called. `invalid_tool_definition`: a tool's name, description or schema
10
+ * is unusable, or two tools share a name. `invalid_tool_result`: a tool's `execute` returned a malformed result or
11
+ * write outcome.
12
+ */
13
+ export class SdkError extends Error {
14
+ name = "SdkError";
15
+ code;
16
+ constructor(code, message, options) {
17
+ super(message, options);
18
+ this.code = code;
19
+ Object.defineProperty(this, SDK_ERROR, { value: true });
20
+ }
21
+ }
22
+ /** True for an `SdkError`, including one from another copy of the package. */
23
+ export function isSdkError(error) {
24
+ return typeof error === "object" && error !== null && error[SDK_ERROR] === true;
25
+ }
26
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAKH,4FAA4F;AAC5F,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;AAE1D;;;;GAIG;AACH,MAAM,OAAO,QAAS,SAAQ,KAAK;IACf,IAAI,GAAG,UAAU,CAAC;IAC3B,IAAI,CAAe;IAE5B,YAAY,IAAkB,EAAE,OAAe,EAAE,OAAsB;QACrE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,SAAS,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC1D,CAAC;CACF;AAED,8EAA8E;AAC9E,MAAM,UAAU,UAAU,CAAC,KAAc;IACvC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC;AAC/G,CAAC","sourcesContent":["/**\n * `SdkError`: the SDK's error for programmer errors, such as a tool definition that breaks the name rule or a tool\n * that returns something other than a tool result. A failure the model caused, such as invalid tool input, is never\n * thrown: the tool pipeline returns it to the model as an error result.\n */\n\n/** Why an `SdkError` was thrown. */\nexport type SdkErrorCode = \"invalid_tool_definition\" | \"invalid_tool_result\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst SDK_ERROR = Symbol.for(\"buildanagent.sdk.SdkError\");\n\n/**\n * Thrown for a mistake in how the SDK is called. `invalid_tool_definition`: a tool's name, description or schema\n * is unusable, or two tools share a name. `invalid_tool_result`: a tool's `execute` returned a malformed result or\n * write outcome.\n */\nexport class SdkError extends Error {\n override readonly name = \"SdkError\";\n readonly code: SdkErrorCode;\n\n constructor(code: SdkErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, SDK_ERROR, { value: true });\n }\n}\n\n/** True for an `SdkError`, including one from another copy of the package. */\nexport function isSdkError(error: unknown): error is SdkError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[SDK_ERROR] === true;\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  /**
2
- * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`.
3
- *
4
- * The loop, tools, hooks, signed pauses and budgets are planned in the SDK plan §3.3.
2
+ * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the tools: their definitions,
3
+ * schemas, results and write outcomes. The loop, hooks, signed pauses and budgets are planned in the SDK plan §3.3.
5
4
  */
5
+ export { isSdkError, SdkError, type SdkErrorCode } from "./errors.js";
6
+ export { type ClarificationToolOptions, clarificationTool, defineTool, type OutputToolOptions, outputTool, } from "./tools/define.js";
7
+ export type { JsonSchema, SchemaIssue, ToolContext, ToolDefinition, ToolEffect, ToolFailure, ToolResult, ToolSchema, } from "./tools/types.js";
8
+ export type { WriteOutcome } from "./vendor/agent-safety/outcome.js";
9
+ /** The package's name, `@buildanagent/sdk`. */
6
10
  export declare const SDK_PACKAGE = "@buildanagent/sdk";
package/dist/index.js CHANGED
@@ -1,7 +1,9 @@
1
1
  /**
2
- * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`.
3
- *
4
- * The loop, tools, hooks, signed pauses and budgets are planned in the SDK plan §3.3.
2
+ * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the tools: their definitions,
3
+ * schemas, results and write outcomes. The loop, hooks, signed pauses and budgets are planned in the SDK plan §3.3.
5
4
  */
5
+ export { isSdkError, SdkError } from "./errors.js";
6
+ export { clarificationTool, defineTool, outputTool, } from "./tools/define.js";
7
+ /** The package's name, `@buildanagent/sdk`. */
6
8
  export const SDK_PACKAGE = "@buildanagent/sdk";
7
9
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,mBAAmB,CAAC","sourcesContent":["/**\n * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`.\n *\n * The loop, tools, hooks, signed pauses and budgets are planned in the SDK plan §3.3.\n */\nexport const SDK_PACKAGE = \"@buildanagent/sdk\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAqB,MAAM,aAAa,CAAC;AACtE,OAAO,EAEL,iBAAiB,EACjB,UAAU,EAEV,UAAU,GACX,MAAM,mBAAmB,CAAC;AAa3B,+CAA+C;AAC/C,MAAM,CAAC,MAAM,WAAW,GAAG,mBAAmB,CAAC","sourcesContent":["/**\n * `@buildanagent/sdk`: the agent loop over `@buildanagent/gateway`. This entry holds the tools: their definitions,\n * schemas, results and write outcomes. The loop, hooks, signed pauses and budgets are planned in the SDK plan §3.3.\n */\nexport { isSdkError, SdkError, type SdkErrorCode } from \"./errors.js\";\nexport {\n type ClarificationToolOptions,\n clarificationTool,\n defineTool,\n type OutputToolOptions,\n outputTool,\n} from \"./tools/define.js\";\nexport type {\n JsonSchema,\n SchemaIssue,\n ToolContext,\n ToolDefinition,\n ToolEffect,\n ToolFailure,\n ToolResult,\n ToolSchema,\n} from \"./tools/types.js\";\nexport type { WriteOutcome } from \"./vendor/agent-safety/outcome.js\";\n\n/** The package's name, `@buildanagent/sdk`. */\nexport const SDK_PACKAGE = \"@buildanagent/sdk\";\n"]}
@@ -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 run = { model: request.model, content: [], usage: { ...emptyUsage(), ...script.usage, raw: null } };
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,SAAS,MAAM,CAAC,IAAY,EAAE,IAAY;IACxC,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IACjC,MAAM,GAAG,GAAa,EAAE,CAAC;IACzB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,IAAI,IAAI;QAAE,GAAG,CAAC,IAAI,CAAC,I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AC;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,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,SAAS,MAAM,CAAC,IAAY,EAAE,IAAY;IACxC,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;I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AAC,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"]}
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Coercion: the few conversions the pipeline makes to a model's tool arguments before validation (D7 keeps coercion
3
+ * our own step, not the validator's). The rules stay minimal and the SDK README lists them:
4
+ *
5
+ * 1. A string that holds JSON becomes the object or array it encodes, where the schema's `type` is `object` or
6
+ * `array`.
7
+ * 2. A string that holds a decimal number becomes that number, where the `type` is `number`, or `integer` when the
8
+ * number is whole. A whole number outside the safe integer range (beyond 2^53) stays a string.
9
+ * 3. The string `"true"` or `"false"` becomes a boolean, where the `type` is `boolean`.
10
+ *
11
+ * The rules reach nested values through `properties` and `items` only, and only where `type` is a single string.
12
+ * They never change a value that already has the schema's type, and they never modify the input.
13
+ */
14
+ /** Applies the coercion rules to `value` under `schema`, returning `value` itself when no rule applies. */
15
+ export declare function coerceValue(value: unknown, schema: unknown): unknown;
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Coercion: the few conversions the pipeline makes to a model's tool arguments before validation (D7 keeps coercion
3
+ * our own step, not the validator's). The rules stay minimal and the SDK README lists them:
4
+ *
5
+ * 1. A string that holds JSON becomes the object or array it encodes, where the schema's `type` is `object` or
6
+ * `array`.
7
+ * 2. A string that holds a decimal number becomes that number, where the `type` is `number`, or `integer` when the
8
+ * number is whole. A whole number outside the safe integer range (beyond 2^53) stays a string.
9
+ * 3. The string `"true"` or `"false"` becomes a boolean, where the `type` is `boolean`.
10
+ *
11
+ * The rules reach nested values through `properties` and `items` only, and only where `type` is a single string.
12
+ * They never change a value that already has the schema's type, and they never modify the input.
13
+ */
14
+ const DECIMAL = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
15
+ function isRecord(value) {
16
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17
+ }
18
+ function parseJson(text) {
19
+ try {
20
+ return JSON.parse(text);
21
+ }
22
+ catch {
23
+ // Not JSON: the value stays a string, and validation reports it.
24
+ return undefined;
25
+ }
26
+ }
27
+ function coerceObject(value, schema) {
28
+ const parsed = typeof value === "string" ? parseJson(value) : value;
29
+ const object = isRecord(parsed) ? parsed : undefined;
30
+ if (object === undefined)
31
+ return value;
32
+ const properties = isRecord(schema.properties) ? schema.properties : {};
33
+ let copy;
34
+ for (const [key, child] of Object.entries(properties)) {
35
+ if (!Object.hasOwn(object, key))
36
+ continue;
37
+ const coerced = coerceValue(object[key], child);
38
+ if (coerced === object[key])
39
+ continue;
40
+ copy ??= { ...object };
41
+ copy[key] = coerced;
42
+ }
43
+ return copy ?? object;
44
+ }
45
+ function coerceArray(value, schema) {
46
+ const parsed = typeof value === "string" ? parseJson(value) : value;
47
+ if (!Array.isArray(parsed))
48
+ return value;
49
+ if (!isRecord(schema.items))
50
+ return parsed;
51
+ const items = schema.items;
52
+ const coerced = parsed.map((item) => coerceValue(item, items));
53
+ return coerced.some((item, index) => item !== parsed[index]) ? coerced : parsed;
54
+ }
55
+ function coerceNumber(value, integer) {
56
+ if (typeof value !== "string" || !DECIMAL.test(value))
57
+ return value;
58
+ const number = Number(value);
59
+ if (!Number.isFinite(number) || (integer && !Number.isInteger(number)))
60
+ return value;
61
+ // A whole number past 2^53 would come out as a different number, such as another order's id, so it stays a string
62
+ // and validation reports it.
63
+ if (Number.isInteger(number) && !Number.isSafeInteger(number))
64
+ return value;
65
+ return number;
66
+ }
67
+ function coerceBoolean(value) {
68
+ if (value === "true")
69
+ return true;
70
+ if (value === "false")
71
+ return false;
72
+ return value;
73
+ }
74
+ /** Applies the coercion rules to `value` under `schema`, returning `value` itself when no rule applies. */
75
+ export function coerceValue(value, schema) {
76
+ if (!isRecord(schema) || typeof schema.type !== "string")
77
+ return value;
78
+ switch (schema.type) {
79
+ case "object":
80
+ return coerceObject(value, schema);
81
+ case "array":
82
+ return coerceArray(value, schema);
83
+ case "number":
84
+ return coerceNumber(value, false);
85
+ case "integer":
86
+ return coerceNumber(value, true);
87
+ case "boolean":
88
+ return coerceBoolean(value);
89
+ default:
90
+ return value;
91
+ }
92
+ }
93
+ //# sourceMappingURL=coerce.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"coerce.js","sourceRoot":"","sources":["../../src/tools/coerce.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH,MAAM,OAAO,GAAG,+CAA+C,CAAC;AAEhE,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAED,SAAS,SAAS,CAAC,IAAY;IAC7B,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC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A2G;AAC3G,MAAM,UAAU,WAAW,CAAC,KAAc,EAAE,MAAe;IACzD,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,OAAO,MAAM,CAAC,IAAI,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACvE,QAAQ,MAAM,CAAC,IAAI,EAAE,CAAC;QACpB,KAAK,QAAQ;YACX,OAAO,YAAY,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACrC,KAAK,OAAO;YACV,OAAO,WAAW,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACpC,KAAK,QAAQ;YACX,OAAO,YAAY,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;QACpC,KAAK,SAAS;YACZ,OAAO,YAAY,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QACnC,KAAK,SAAS;YACZ,OAAO,aAAa,CAAC,KAAK,CAAC,CAAC;QAC9B;YACE,OAAO,KAAK,CAAC;IACjB,CAAC;AACH,CAAC","sourcesContent":["/**\n * Coercion: the few conversions the pipeline makes to a model's tool arguments before validation (D7 keeps coercion\n * our own step, not the validator's). The rules stay minimal and the SDK README lists them:\n *\n * 1. A string that holds JSON becomes the object or array it encodes, where the schema's `type` is `object` or\n * `array`.\n * 2. A string that holds a decimal number becomes that number, where the `type` is `number`, or `integer` when the\n * number is whole. A whole number outside the safe integer range (beyond 2^53) stays a string.\n * 3. The string `\"true\"` or `\"false\"` becomes a boolean, where the `type` is `boolean`.\n *\n * The rules reach nested values through `properties` and `items` only, and only where `type` is a single string.\n * They never change a value that already has the schema's type, and they never modify the input.\n */\n\ntype Schema = Readonly<Record<string, unknown>>;\n\nconst DECIMAL = /^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n // Not JSON: the value stays a string, and validation reports it.\n return undefined;\n }\n}\n\nfunction coerceObject(value: unknown, schema: Schema): unknown {\n const parsed = typeof value === \"string\" ? parseJson(value) : value;\n const object = isRecord(parsed) ? parsed : undefined;\n if (object === undefined) return value;\n const properties = isRecord(schema.properties) ? schema.properties : {};\n let copy: Record<string, unknown> | undefined;\n for (const [key, child] of Object.entries(properties)) {\n if (!Object.hasOwn(object, key)) continue;\n const coerced = coerceValue(object[key], child);\n if (coerced === object[key]) continue;\n copy ??= { ...object };\n copy[key] = coerced;\n }\n return copy ?? object;\n}\n\nfunction coerceArray(value: unknown, schema: Schema): unknown {\n const parsed = typeof value === \"string\" ? parseJson(value) : value;\n if (!Array.isArray(parsed)) return value;\n if (!isRecord(schema.items)) return parsed;\n const items = schema.items;\n const coerced = parsed.map((item: unknown) => coerceValue(item, items));\n return coerced.some((item, index) => item !== parsed[index]) ? coerced : parsed;\n}\n\nfunction coerceNumber(value: unknown, integer: boolean): unknown {\n if (typeof value !== \"string\" || !DECIMAL.test(value)) return value;\n const number = Number(value);\n if (!Number.isFinite(number) || (integer && !Number.isInteger(number))) return value;\n // A whole number past 2^53 would come out as a different number, such as another order's id, so it stays a string\n // and validation reports it.\n if (Number.isInteger(number) && !Number.isSafeInteger(number)) return value;\n return number;\n}\n\nfunction coerceBoolean(value: unknown): unknown {\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n return value;\n}\n\n/** Applies the coercion rules to `value` under `schema`, returning `value` itself when no rule applies. */\nexport function coerceValue(value: unknown, schema: unknown): unknown {\n if (!isRecord(schema) || typeof schema.type !== \"string\") return value;\n switch (schema.type) {\n case \"object\":\n return coerceObject(value, schema);\n case \"array\":\n return coerceArray(value, schema);\n case \"number\":\n return coerceNumber(value, false);\n case \"integer\":\n return coerceNumber(value, true);\n case \"boolean\":\n return coerceBoolean(value);\n default:\n return value;\n }\n}\n"]}
@@ -0,0 +1,42 @@
1
+ import type { StandardJSONSchemaV1, StandardSchemaV1 } from "@standard-schema/spec";
2
+ import { type PreparedSchema } from "./schema.js";
3
+ import type { ToolDefinition } from "./types.js";
4
+ /**
5
+ * Checks a tool and returns its prepared schema, preparing it on first use. Throws an `SdkError`, code
6
+ * `invalid_tool_definition`, for a bad name, a missing description or `execute`, or an unusable schema.
7
+ */
8
+ export declare function preparedSchemaOf(tool: ToolDefinition<unknown, unknown>): PreparedSchema;
9
+ /**
10
+ * Defines a tool. The returned copy is frozen, and its schema is compiled now, so a mistake surfaces here.
11
+ *
12
+ * Throws an `SdkError`, code `invalid_tool_definition`, when the name breaks the tool-name rule (1 to 64 characters
13
+ * from `A-Z`, `a-z`, `0-9`, `_` and `-`), the description or `execute` is missing, a raw JSON Schema does not
14
+ * compile or names a draft other than 2020-12 or 7, or a Standard Schema cannot describe itself as JSON Schema.
15
+ */
16
+ export declare function defineTool<I, S = unknown>(definition: ToolDefinition<I, S>): ToolDefinition<I, S>;
17
+ /** The options of `outputTool()`. */
18
+ export interface OutputToolOptions<S> {
19
+ readonly name: string;
20
+ /** The schema of the final answer. A Standard Schema that can describe itself as JSON Schema, such as Zod 4.2's. */
21
+ readonly schema: StandardSchemaV1<unknown, S> & StandardJSONSchemaV1<unknown, S>;
22
+ /** Defaults to a line asking the model to call the tool once, with its final answer. */
23
+ readonly description?: string;
24
+ }
25
+ /**
26
+ * Defines a tool whose input is the run's final answer. A call whose input passes `schema` ends the run, with the
27
+ * validated value as the result's `structured` field. A call that fails it returns the schema's issues to the model
28
+ * as an error result, so the model can correct the answer and call again.
29
+ */
30
+ export declare function outputTool<S>(options: OutputToolOptions<S>): ToolDefinition<S, S>;
31
+ /** The options of `clarificationTool()`. */
32
+ export interface ClarificationToolOptions {
33
+ /** Defaults to `ask_user`. */
34
+ readonly name?: string;
35
+ }
36
+ /**
37
+ * Defines a tool the model calls to ask the user a question. Its result carries the question as a `pause` of kind
38
+ * `clarification`, which the run turns into a request for the user's answer.
39
+ */
40
+ export declare function clarificationTool(options?: ClarificationToolOptions): ToolDefinition<{
41
+ question: string;
42
+ }, never>;
@@ -0,0 +1,96 @@
1
+ /**
2
+ * `defineTool()`, `outputTool()` and `clarificationTool()`: each checks a definition once and prepares its schema,
3
+ * so a broken tool throws when it is defined rather than when the model first calls it.
4
+ */
5
+ import { assertCanonicalName } from "@buildanagent/gateway";
6
+ import { SdkError } from "../errors.js";
7
+ import { prepareSchema } from "./schema.js";
8
+ // Keyed by the frozen definition, so a schema is compiled once however many runs use the tool.
9
+ const prepared = new WeakMap();
10
+ function invalid(message, cause) {
11
+ return new SdkError("invalid_tool_definition", message, cause === undefined ? {} : { cause });
12
+ }
13
+ function checkName(name) {
14
+ if (typeof name !== "string")
15
+ throw invalid("a tool's name must be a string");
16
+ try {
17
+ assertCanonicalName(name);
18
+ }
19
+ catch (cause) {
20
+ throw invalid(cause instanceof Error ? cause.message : String(cause), cause);
21
+ }
22
+ return name;
23
+ }
24
+ /**
25
+ * Checks a tool and returns its prepared schema, preparing it on first use. Throws an `SdkError`, code
26
+ * `invalid_tool_definition`, for a bad name, a missing description or `execute`, or an unusable schema.
27
+ */
28
+ export function preparedSchemaOf(tool) {
29
+ const known = prepared.get(tool);
30
+ if (known !== undefined)
31
+ return known;
32
+ const name = checkName(tool.name);
33
+ if (typeof tool.description !== "string")
34
+ throw invalid(`tool "${name}": description must be a string`);
35
+ if (typeof tool.execute !== "function")
36
+ throw invalid(`tool "${name}": execute must be a function`);
37
+ const schema = prepareSchema(name, tool.inputSchema);
38
+ prepared.set(tool, schema);
39
+ return schema;
40
+ }
41
+ /**
42
+ * Defines a tool. The returned copy is frozen, and its schema is compiled now, so a mistake surfaces here.
43
+ *
44
+ * Throws an `SdkError`, code `invalid_tool_definition`, when the name breaks the tool-name rule (1 to 64 characters
45
+ * from `A-Z`, `a-z`, `0-9`, `_` and `-`), the description or `execute` is missing, a raw JSON Schema does not
46
+ * compile or names a draft other than 2020-12 or 7, or a Standard Schema cannot describe itself as JSON Schema.
47
+ */
48
+ export function defineTool(definition) {
49
+ const tool = Object.freeze({ ...definition });
50
+ // Method parameters are bivariant, so a tool of any input type is a ToolDefinition<unknown, unknown>.
51
+ preparedSchemaOf(tool);
52
+ return tool;
53
+ }
54
+ const OUTPUT_DESCRIPTION = "Submit your final answer as this tool's input. Call it once, when the task is done.";
55
+ const OUTPUT_ACCEPTED = "The final answer was accepted.";
56
+ /**
57
+ * Defines a tool whose input is the run's final answer. A call whose input passes `schema` ends the run, with the
58
+ * validated value as the result's `structured` field. A call that fails it returns the schema's issues to the model
59
+ * as an error result, so the model can correct the answer and call again.
60
+ */
61
+ export function outputTool(options) {
62
+ return defineTool({
63
+ name: options.name,
64
+ description: options.description ?? OUTPUT_DESCRIPTION,
65
+ inputSchema: options.schema,
66
+ async execute(input) {
67
+ return { content: [{ type: "text", text: OUTPUT_ACCEPTED }], structured: input, terminate: true };
68
+ },
69
+ });
70
+ }
71
+ const CLARIFICATION_SCHEMA = Object.freeze({
72
+ type: "object",
73
+ properties: Object.freeze({
74
+ question: Object.freeze({ type: "string", minLength: 1, description: "The question to ask the user." }),
75
+ }),
76
+ required: Object.freeze(["question"]),
77
+ additionalProperties: false,
78
+ });
79
+ /**
80
+ * Defines a tool the model calls to ask the user a question. Its result carries the question as a `pause` of kind
81
+ * `clarification`, which the run turns into a request for the user's answer.
82
+ */
83
+ export function clarificationTool(options = {}) {
84
+ return defineTool({
85
+ name: options.name ?? "ask_user",
86
+ description: "Ask the user a question when you cannot continue without their answer.",
87
+ inputSchema: CLARIFICATION_SCHEMA,
88
+ async execute({ question }) {
89
+ return {
90
+ content: [{ type: "text", text: "The question was sent to the user." }],
91
+ pause: { kind: "clarification", question },
92
+ };
93
+ },
94
+ });
95
+ }
96
+ //# sourceMappingURL=define.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"define.js","sourceRoot":"","sources":["../../src/tools/define.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE5D,OAAO,EAAE,QAAQ,EAAE,MA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5B,CAAC,CAAC;AAEH;;;GAGG;AACH,MAAM,UAAU,iBAAiB,CAAC,OAAO,GAA6B,EAAE;IACtE,OAAO,UAAU,CAA8B;QAC7C,IAAI,EAAE,OAAO,CAAC,IAAI,IAAI,UAAU;QAChC,WAAW,EAAE,wEAAwE;QACrF,WAAW,EAAE,oBAAoB;QACjC,KAAK,CAAC,OAAO,CAAC,EAAE,QAAQ,EAAE;YACxB,OAAO;gBACL,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,oCAAoC,EAAE,CAAC;gBACvE,KAAK,EAAE,EAAE,IAAI,EAAE,eAAe,EAAE,QAAQ,EAAE;aAC3C,CAAC;QACJ,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * `defineTool()`, `outputTool()` and `clarificationTool()`: each checks a definition once and prepares its schema,\n * so a broken tool throws when it is defined rather than when the model first calls it.\n */\nimport { assertCanonicalName } from \"@buildanagent/gateway\";\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { SdkError } from \"../errors.js\";\nimport { type PreparedSchema, prepareSchema } from \"./schema.js\";\nimport type { ToolDefinition, ToolResult } from \"./types.js\";\n\n// Keyed by the frozen definition, so a schema is compiled once however many runs use the tool.\nconst prepared = new WeakMap<object, PreparedSchema>();\n\nfunction invalid(message: string, cause?: unknown): SdkError {\n return new SdkError(\"invalid_tool_definition\", message, cause === undefined ? {} : { cause });\n}\n\nfunction checkName(name: unknown): string {\n if (typeof name !== \"string\") throw invalid(\"a tool's name must be a string\");\n try {\n assertCanonicalName(name);\n } catch (cause) {\n throw invalid(cause instanceof Error ? cause.message : String(cause), cause);\n }\n return name;\n}\n\n/**\n * Checks a tool and returns its prepared schema, preparing it on first use. Throws an `SdkError`, code\n * `invalid_tool_definition`, for a bad name, a missing description or `execute`, or an unusable schema.\n */\nexport function preparedSchemaOf(tool: ToolDefinition<unknown, unknown>): PreparedSchema {\n const known = prepared.get(tool);\n if (known !== undefined) return known;\n const name = checkName(tool.name);\n if (typeof tool.description !== \"string\") throw invalid(`tool \"${name}\": description must be a string`);\n if (typeof tool.execute !== \"function\") throw invalid(`tool \"${name}\": execute must be a function`);\n const schema = prepareSchema(name, tool.inputSchema);\n prepared.set(tool, schema);\n return schema;\n}\n\n/**\n * Defines a tool. The returned copy is frozen, and its schema is compiled now, so a mistake surfaces here.\n *\n * Throws an `SdkError`, code `invalid_tool_definition`, when the name breaks the tool-name rule (1 to 64 characters\n * from `A-Z`, `a-z`, `0-9`, `_` and `-`), the description or `execute` is missing, a raw JSON Schema does not\n * compile or names a draft other than 2020-12 or 7, or a Standard Schema cannot describe itself as JSON Schema.\n */\nexport function defineTool<I, S = unknown>(definition: ToolDefinition<I, S>): ToolDefinition<I, S> {\n const tool = Object.freeze({ ...definition });\n // Method parameters are bivariant, so a tool of any input type is a ToolDefinition<unknown, unknown>.\n preparedSchemaOf(tool as ToolDefinition<unknown, unknown>);\n return tool;\n}\n\n/** The options of `outputTool()`. */\nexport interface OutputToolOptions<S> {\n readonly name: string;\n /** The schema of the final answer. A Standard Schema that can describe itself as JSON Schema, such as Zod 4.2's. */\n readonly schema: StandardSchemaV1<unknown, S> & StandardJSONSchemaV1<unknown, S>;\n /** Defaults to a line asking the model to call the tool once, with its final answer. */\n readonly description?: string;\n}\n\nconst OUTPUT_DESCRIPTION = \"Submit your final answer as this tool's input. Call it once, when the task is done.\";\nconst OUTPUT_ACCEPTED = \"The final answer was accepted.\";\n\n/**\n * Defines a tool whose input is the run's final answer. A call whose input passes `schema` ends the run, with the\n * validated value as the result's `structured` field. A call that fails it returns the schema's issues to the model\n * as an error result, so the model can correct the answer and call again.\n */\nexport function outputTool<S>(options: OutputToolOptions<S>): ToolDefinition<S, S> {\n return defineTool<S, S>({\n name: options.name,\n description: options.description ?? OUTPUT_DESCRIPTION,\n inputSchema: options.schema,\n async execute(input): Promise<ToolResult<S>> {\n return { content: [{ type: \"text\", text: OUTPUT_ACCEPTED }], structured: input, terminate: true };\n },\n });\n}\n\n/** The options of `clarificationTool()`. */\nexport interface ClarificationToolOptions {\n /** Defaults to `ask_user`. */\n readonly name?: string;\n}\n\nconst CLARIFICATION_SCHEMA = Object.freeze({\n type: \"object\",\n properties: Object.freeze({\n question: Object.freeze({ type: \"string\", minLength: 1, description: \"The question to ask the user.\" }),\n }),\n required: Object.freeze([\"question\"]),\n additionalProperties: false,\n});\n\n/**\n * Defines a tool the model calls to ask the user a question. Its result carries the question as a `pause` of kind\n * `clarification`, which the run turns into a request for the user's answer.\n */\nexport function clarificationTool(options: ClarificationToolOptions = {}): ToolDefinition<{ question: string }, never> {\n return defineTool<{ question: string }, never>({\n name: options.name ?? \"ask_user\",\n description: \"Ask the user a question when you cannot continue without their answer.\",\n inputSchema: CLARIFICATION_SCHEMA,\n async execute({ question }) {\n return {\n content: [{ type: \"text\", text: \"The question was sent to the user.\" }],\n pause: { kind: \"clarification\", question },\n };\n },\n });\n}\n"]}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The default error text the model reads for a failed tool call. Every message says what failed, shows the
3
+ * arguments the model sent, and tells the model not to answer the failure with invented data, because agents have
4
+ * been seen to "make a mock implementation" when a tool fails (agent-SDK guide §4).
5
+ */
6
+ import type { ModelContent } from "@buildanagent/gateway";
7
+ import type { ToolFailure } from "./types.js";
8
+ /** The line every default error message ends with. */
9
+ export declare const DO_NOT_SUBSTITUTE: string;
10
+ /** The fixed line a redacted error shows the model in place of the thrown message. */
11
+ export declare const REDACTED_MESSAGE = "its error message is hidden.";
12
+ /** The default content for a failed tool call: what failed, the received arguments, and the do-not-substitute line. */
13
+ export declare function formatToolError(failure: ToolFailure): ModelContent[];