@alexkroman1/aai-cli 0.13.0 → 0.14.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.
Files changed (66) hide show
  1. package/README.md +15 -15
  2. package/dist/{_bundler-CgBw5Bcu.mjs → _bundler-B6v31ROV.mjs} +1 -1
  3. package/dist/_console-audio.d.ts +18 -0
  4. package/dist/{_dev-server-BNq5OnUJ.mjs → _dev-server-GoEXEVpA.mjs} +2 -2
  5. package/dist/_resource-commands.d.ts +34 -2
  6. package/dist/{_slug-api-DJuwYZ6T.mjs → _slug-api-BnmTHtjd.mjs} +1 -1
  7. package/dist/{_studio-BH05zugt.mjs → _studio-B5m4jBTD.mjs} +14 -9
  8. package/dist/_studio.d.ts +16 -4
  9. package/dist/_target-bundle.d.ts +2 -0
  10. package/dist/{_templates-Bv-rd0SO.mjs → _templates-BVMVsQh0.mjs} +10 -6
  11. package/dist/_templates.d.ts +9 -2
  12. package/dist/{build-B37oBfEv.mjs → build-CKhanHVv.mjs} +28 -32
  13. package/dist/cli-workflow.d.ts +7 -0
  14. package/dist/cli.mjs +213 -181
  15. package/dist/{client-bundler-D4SeZJ8E.mjs → client-bundler-DZ_Zoznn.mjs} +2 -1
  16. package/dist/client-bundler.d.ts +7 -1
  17. package/dist/client-bundler.mjs +1 -1
  18. package/dist/{console-D6OOjjeJ.mjs → console-Dxq26Adz.mjs} +14 -10
  19. package/dist/{delete-Br0EOH0g.mjs → delete-DwXCHzTl.mjs} +8 -8
  20. package/dist/delete.d.ts +4 -3
  21. package/dist/{deploy-CLUH5cv2.mjs → deploy-CbA8Ibiu.mjs} +2 -2
  22. package/dist/{dev-ZVuyPLUk.mjs → dev-BWBDbUEb.mjs} +1 -1
  23. package/dist/{init-x3FsKl2q.mjs → init-CidslZZz.mjs} +1 -1
  24. package/dist/{logs-BfRq1HX9.mjs → logs-CnPK-Prw.mjs} +25 -3
  25. package/dist/scaffold/CLAUDE.md +52 -52
  26. package/dist/scaffold/agent-guide/AGENT-API.md +20 -20
  27. package/dist/scaffold/agent-guide/HOSTING.md +32 -33
  28. package/dist/scaffold/agent-guide/PIPELINE-TUNING.md +44 -47
  29. package/dist/scaffold/agent-guide/PROVIDERS.md +54 -57
  30. package/dist/scaffold/agent-guide/TESTING-EVALS.md +31 -31
  31. package/dist/scaffold/agent-guide/TOOLS.md +86 -87
  32. package/dist/scaffold/agent-guide/UI.md +59 -58
  33. package/dist/scaffold/agent-guide/WORKFLOWS.md +129 -127
  34. package/dist/scaffold/package.json +4 -4
  35. package/dist/scaffold/vitest.config.ts +3 -3
  36. package/dist/{secret-Db1UWLSZ.mjs → secret-DPdPEet2.mjs} +2 -2
  37. package/dist/{studio-DAoJApzD.mjs → studio-COjK25Rl.mjs} +23 -24
  38. package/dist/studio.d.ts +5 -4
  39. package/dist/templates/call-audit-workflow/agent.eval.test.ts +6 -6
  40. package/dist/templates/call-audit-workflow/agent.test.ts +2 -2
  41. package/dist/templates/document-redline-workflow/agent.eval.test.ts +14 -17
  42. package/dist/templates/home-assistant-agent/agent.test.ts +0 -1
  43. package/dist/templates/link-digest-workflow/agent.eval.test.ts +2 -2
  44. package/dist/templates/link-digest-workflow/agent.test.ts +24 -25
  45. package/dist/templates/medication-safety-agent/agent.test.ts +15 -18
  46. package/dist/templates/medication-safety-agent/fda.test.ts +16 -17
  47. package/dist/templates/medication-safety-agent/fda.ts +7 -0
  48. package/dist/templates/medication-safety-agent/tools/check_drug_interaction.ts +61 -53
  49. package/dist/templates/medication-safety-agent/tools/medication_lookup.ts +42 -32
  50. package/dist/templates/meeting-recap-agent/agent.eval.test.ts +29 -16
  51. package/dist/templates/podcast-digest-workflow/agent.eval.test.ts +3 -3
  52. package/dist/templates/podcast-digest-workflow/agent.test.ts +17 -17
  53. package/dist/templates/research-handoff-agent/agent.eval.test.ts +22 -15
  54. package/dist/templates/research-handoff-agent/agent.test.ts +2 -15
  55. package/dist/templates/research-planner-agent/agent.test.ts +22 -17
  56. package/dist/templates/research-planner-agent/shared.ts +122 -93
  57. package/dist/templates/retail-orders-agent/shared.ts +2 -2
  58. package/dist/templates/retail-orders-agent/tools/get_order_details.ts +1 -1
  59. package/dist/templates/spoken-summary-workflow/agent.eval.test.ts +6 -6
  60. package/dist/templates/spoken-summary-workflow/agent.test.ts +2 -2
  61. package/dist/templates/transcription-workflow/agent.eval.test.ts +3 -3
  62. package/dist/templates/transcription-workflow/agent.test.ts +2 -1
  63. package/dist/templates/transcription-workflow/recover.test.ts +4 -7
  64. package/dist/templates/web-research-agent/agent.test.ts +4 -3
  65. package/dist/templates/word-game-agent/agent.test.ts +11 -5
  66. package/package.json +6 -6
@@ -6,8 +6,8 @@ Choosing between pipeline and S2S is `PIPELINE-TUNING.md`.
6
6
 
7
7
  ## Providers
8
8
 
9
- Provider SDKs are **optional peer dependencies**. Install only the SDKs
10
- for the providers you actually use.
9
+ Provider SDKs are **optional peer dependencies**. Install only the SDKs for the
10
+ providers you actually use.
11
11
 
12
12
  ### STT — `@alexkroman1/aai/stt`
13
13
 
@@ -18,19 +18,18 @@ for the providers you actually use.
18
18
  | `elevenLabsStt` | `"scribe_v2_realtime"` | `ELEVENLABS_API_KEY` |
19
19
  | `sonioxStt` | `"stt-rt-v3"` | `SONIOX_API_KEY` |
20
20
 
21
- All STT factories accept `{ model?: string, ... }`. Bare calls
22
- (`deepgramStt()`, `sonioxStt()`, etc.) use the default model. Language is spelled
23
- `language` where the vendor takes one code (`deepgramStt`, `elevenLabsStt`) and
24
- `languages` where it takes a list (`assemblyAIStt`, `sonioxStt`) — and only
25
- `deepgramStt`'s unset value means English; the other three auto-detect.
21
+ All STT factories accept `{ model?: string, ... }`. Bare calls (`deepgramStt()`,
22
+ `sonioxStt()`, etc.) use the default model. Language is spelled `language` where
23
+ the vendor takes one code (`deepgramStt`, `elevenLabsStt`) and `languages` where
24
+ it takes a list (`assemblyAIStt`, `sonioxStt`) — and only `deepgramStt`'s unset
25
+ value means English; the other three auto-detect.
26
26
 
27
- `elevenLabsStt` carries the stage in its name because ElevenLabs is
28
- better known for TTS: when that stage arrives, `elevenLabs` is the name it
29
- should get.
27
+ `elevenLabsStt` carries the stage in its name because ElevenLabs is better known
28
+ for TTS: when that stage arrives, `elevenLabs` is the name it should get.
30
29
 
31
- `assemblyAIStt` accepts an optional `region: "eu"` for EU data residency —
32
- it routes streaming transcription to AssemblyAI's EU endpoints. EU-region
33
- API keys require it; the US endpoints reject them. Example:
30
+ `assemblyAIStt` accepts an optional `region: "eu"` for EU data residency — it
31
+ routes streaming transcription to AssemblyAI's EU endpoints. EU-region API keys
32
+ require it; the US endpoints reject them. Example:
34
33
  `assemblyAIStt({ model: "universal-3-5-pro", region: "eu" })`.
35
34
 
36
35
  ### LLM — `@alexkroman1/aai/llm`
@@ -52,24 +51,24 @@ The provider is a string, not a function name:
52
51
  | `"assemblyai"` | `@ai-sdk/openai` | `ASSEMBLYAI_API_KEY` |
53
52
 
54
53
  `model` is required. Example:
55
- `llm({ provider: "anthropic", model: "claude-haiku-4-5" })`.
56
- `"openrouter"` and `"gateway"` (the [Vercel AI
57
- Gateway](https://vercel.com/docs/ai-gateway)) address a model as
58
- `"creator/model"`; every other provider takes its own bare id.
54
+ `llm({ provider: "anthropic", model: "claude-haiku-4-5" })`. `"openrouter"` and
55
+ `"gateway"` (the [Vercel AI Gateway](https://vercel.com/docs/ai-gateway))
56
+ address a model as `"creator/model"`; every other provider takes its own bare
57
+ id.
59
58
 
60
- `provider` is OPEN: any other string compiles. A provider with no built-in
61
- entry is reached as an OpenAI-compatible endpoint by naming its `baseUrl` (and
59
+ `provider` is OPEN: any other string compiles. A provider with no built-in entry
60
+ is reached as an OpenAI-compatible endpoint by naming its `baseUrl` (and
62
61
  `apiKeyEnv`, the variable its key is in); `aai build` warns about an unknown
63
- provider that has neither. `providerOptions` carries provider-specific
64
- settings: a native client's AI SDK `providerOptions`; on `openrouter`,
65
- `cerebras` or a `baseUrl` provider, raw request-body fields (`top_k`).
62
+ provider that has neither. `providerOptions` carries provider-specific settings:
63
+ a native client's AI SDK `providerOptions`; on `openrouter`, `cerebras` or a
64
+ `baseUrl` provider, raw request-body fields (`top_k`).
66
65
 
67
- `"assemblyai"` routes through the [AssemblyAI LLM
68
- Gateway](https://www.assemblyai.com/docs/llm-gateway) — an
69
- OpenAI-compatible endpoint fronting 25+ models (Claude, GPT, Gemini,
70
- etc.) with the same API key as AssemblyAI STT. A bare model-id string on
71
- `llm` is shorthand for it (and a `"creator/model"` string for `"gateway"`), and
72
- unset stages keep the AssemblyAI default:
66
+ `"assemblyai"` routes through the
67
+ [AssemblyAI LLM Gateway](https://www.assemblyai.com/docs/llm-gateway) — an
68
+ OpenAI-compatible endpoint fronting 25+ models (Claude, GPT, Gemini, etc.) with
69
+ the same API key as AssemblyAI STT. A bare model-id string on `llm` is shorthand
70
+ for it (and a `"creator/model"` string for `"gateway"`), and unset stages keep
71
+ the AssemblyAI default:
73
72
 
74
73
  ```ts
75
74
  import { agent } from "@alexkroman1/aai";
@@ -108,36 +107,34 @@ export default agent({
108
107
  Bare calls (`assemblyAITts()`, `cartesiaTts()`, `rimeTts()`) use the defaults.
109
108
  Override with `{ voice, model, language }`.
110
109
 
111
- **AssemblyAI TTS** shares `ASSEMBLYAI_API_KEY` with AssemblyAI STT and the
112
- LLM Gateway, so an all-AssemblyAI pipeline needs exactly one secret. On the
113
- default pipeline, `tts: assemblyAITts({ voice: "michael" })` changes the voice
114
- and leaves the other two stages on the default. Each
115
- voice speaks one language, and this is the whole catalog — **a voice not on
116
- this list is rejected after the socket opens, which leaves the agent
117
- connected, "ready", and permanently silent**, so pick one from here rather
118
- than guessing a plausible name:
119
-
120
- - **English, US accent**: `alba`, `anna`, `charles`, `eve`, `george`,
121
- `jane` (the default), `jean`, `mary`, `michael`
110
+ **AssemblyAI TTS** shares `ASSEMBLYAI_API_KEY` with AssemblyAI STT and the LLM
111
+ Gateway, so an all-AssemblyAI pipeline needs exactly one secret. On the default
112
+ pipeline, `tts: assemblyAITts({ voice: "michael" })` changes the voice and
113
+ leaves the other two stages on the default. Each voice speaks one language, and
114
+ this is the whole catalog — **a voice not on this list is rejected after the
115
+ socket opens, which leaves the agent connected, "ready", and permanently
116
+ silent**, so pick one from here rather than guessing a plausible name:
117
+
118
+ - **English, US accent**: `alba`, `anna`, `charles`, `eve`, `george`, `jane`
119
+ (the default), `jean`, `mary`, `michael`
122
120
  - **English, UK accent**: `paul`, `vera`
123
- - **Native accent, code-switches with English**: `estelle` (fr),
124
- `giovanni` (it), `juergen` (de), `lola` (es), `rafael` (pt)
125
-
126
- There is no separate age/gender/style axis — match the persona by picking a
127
- name and accent, and put the delivery in the system prompt instead.
128
-
129
- Set
130
- `language` only alongside a voice that speaks it, as an ISO 639-1 code —
131
- `"en"`, `"fr"`, `"de"`, `"it"`, `"pt"`, `"es"` are the six the catalog
132
- covers, and the SDK translates each to the full name the service wants.
133
- An unsupported code, and a code the declared voice does not speak, are both
134
- build errors naming the voices that do speak it — including the one you get by
135
- setting `language` alone, since the descriptor then fills in the default
136
- English voice. (A voice this release's catalog does not list is passed through:
137
- the catalog is the service's, so a voice it ships later still works.)
138
-
139
- **Rime quirk:** language uses ISO 639-3 three-letter codes (e.g. `"eng"`
140
- not `"en"`).
121
+ - **Native accent, code-switches with English**: `estelle` (fr), `giovanni`
122
+ (it), `juergen` (de), `lola` (es), `rafael` (pt)
123
+
124
+ There is no separate age/gender/style axis — match the persona by picking a name
125
+ and accent, and put the delivery in the system prompt instead.
126
+
127
+ Set `language` only alongside a voice that speaks it, as an ISO 639-1 code —
128
+ `"en"`, `"fr"`, `"de"`, `"it"`, `"pt"`, `"es"` are the six the catalog covers,
129
+ and the SDK translates each to the full name the service wants. An unsupported
130
+ code, and a code the declared voice does not speak, are both build errors naming
131
+ the voices that do speak it — including the one you get by setting `language`
132
+ alone, since the descriptor then fills in the default English voice. (A voice
133
+ this release's catalog does not list is passed through: the catalog is the
134
+ service's, so a voice it ships later still works.)
135
+
136
+ **Rime quirk:** language uses ISO 639-3 three-letter codes (e.g. `"eng"` not
137
+ `"en"`).
141
138
 
142
139
  Set provider keys the same way as any secret: `.env` for local dev,
143
140
  `aai secret put` for production.
@@ -1,9 +1,9 @@
1
1
  # Testing and evals
2
2
 
3
- Part of the aai authoring guide (start with the core guide). A TEST asserts
4
- the agent's shape and its tools' logic (`pnpm test`); an EVAL drives a real
5
- session and asserts what the agent did (`pnpm eval`). Testing a workflow BODY
6
- — the replay engine, crashes, signals — is "Testing a workflow body" in
3
+ Part of the aai authoring guide (start with the core guide). A TEST asserts the
4
+ agent's shape and its tools' logic (`pnpm test`); an EVAL drives a real session
5
+ and asserts what the agent did (`pnpm eval`). Testing a workflow BODY — the
6
+ replay engine, crashes, signals — is "Testing a workflow body" in
7
7
  `WORKFLOWS.md`.
8
8
 
9
9
  **A test file imports testing names from two doors, and only those two:**
@@ -13,8 +13,8 @@ session and asserts what the agent did (`pnpm eval`). Testing a workflow BODY
13
13
  | `@alexkroman1/aai-runtime/testing` | everything that installs nothing — `runTool`, `createToolContext`, `expectToolOk`, the stubs, `runWorkflow` |
14
14
  | `@alexkroman1/aai-runtime/testing/vitest` | everything that installs or restores (`installStubGateway`, `installStubStepFetch`, …) and the eval suites |
15
15
 
16
- `vitest.config.ts` is the one exception: it imports `defineAgentTestConfig`
17
- from `@alexkroman1/aai/testing/vite`. (The helpers are declared in
16
+ `vitest.config.ts` is the one exception: it imports `defineAgentTestConfig` from
17
+ `@alexkroman1/aai/testing/vite`. (The helpers are declared in
18
18
  `@alexkroman1/aai/testing` and `/testing/vitest`, which still work; the two
19
19
  runtime doors re-export them as the same declarations beside the runtime's own.)
20
20
 
@@ -22,11 +22,11 @@ runtime doors re-export them as the same declarations beside the runtime's own.)
22
22
 
23
23
  Co-locate tests as `agent.test.ts` (the `custom-pipeline-agent` template is a
24
24
  reference). **When the project has one, it is yours to maintain**: it asserts
25
- the agent's shape — name, providers, tool names — so rewriting the agent
26
- without updating it leaves a test asserting an agent that no longer exists.
27
- When a test fails after your change, decide which side is stale: updating the
28
- test to match the new agent is a normal fix, not a workaround. Do not delete a
29
- test to make it pass.
25
+ the agent's shape — name, providers, tool names — so rewriting the agent without
26
+ updating it leaves a test asserting an agent that no longer exists. When a test
27
+ fails after your change, decide which side is stale: updating the test to match
28
+ the new agent is a normal fix, not a workaround. Do not delete a test to make it
29
+ pass.
30
30
 
31
31
  **A spec that needs the agent as DEPLOYED imports one module:**
32
32
 
@@ -38,17 +38,17 @@ That is `agent.ts` with its `tools/` directory discovered and its
38
38
  `system-prompt.md` applied — the same lowering `aai build` does, so a spec
39
39
  measures the agent that ships rather than the raw default export (which has no
40
40
  tools and the framework's default prompt). `vitest.config.ts` registers the
41
- plugin that serves it; a scaffolded project already has it. For a runner that
42
- is not vitest, `deployedAgent` on `@alexkroman1/aai-runtime/testing` is the
43
- same thing written out.
41
+ plugin that serves it; a scaffolded project already has it. For a runner that is
42
+ not vitest, `deployedAgent` on `@alexkroman1/aai-runtime/testing` is the same
43
+ thing written out.
44
44
 
45
45
  **Call a tool with `runTool(tool, args, ctx)`**: passed the tool itself, the
46
46
  result is typed by its `execute` — no `as` cast (the `runTool(agent, "name", …)`
47
- form answers `unknown`). **Unwrap it with `expectToolOk(result)`**, which
48
- INFERS the type: it subtracts the `ToolFailure` arm of a plain `tool()`'s
49
- result (and unwraps a gated dialog tool's envelope), throwing with the refusal
50
- quoted when the tool refused. Do not copy an `ok<T>()` helper into a spec; pass
51
- a type argument only for a result that arrives as `unknown`.
47
+ form answers `unknown`). **Unwrap it with `expectToolOk(result)`**, which INFERS
48
+ the type: it subtracts the `ToolFailure` arm of a plain `tool()`'s result (and
49
+ unwraps a gated dialog tool's envelope), throwing with the refusal quoted when
50
+ the tool refused. Do not copy an `ok<T>()` helper into a spec; pass a type
51
+ argument only for a result that arrives as `unknown`.
52
52
 
53
53
  ```ts
54
54
  import { tool, toolFailure } from "@alexkroman1/aai";
@@ -75,9 +75,9 @@ on.
75
75
 
76
76
  **A hand-built `ctx` is `createToolContext()`** — every field inert, `send`
77
77
  recorded on `ctx.sent`, a real slot store, a fresh `sessionId` per call. Its
78
- `generate` and `delegate` take a SCRIPT (`{ reply }` for every call, `{ routes }`
79
- keyed by system prompt or subagent name) and hand the fake back on `ctx.model`
80
- and `ctx.desk`, whose `calls` a spec asserts on.
78
+ `generate` and `delegate` take a SCRIPT (`{ reply }` for every call,
79
+ `{ routes }` keyed by system prompt or subagent name) and hand the fake back on
80
+ `ctx.model` and `ctx.desk`, whose `calls` a spec asserts on.
81
81
 
82
82
  ```ts
83
83
  import { createToolContext } from "@alexkroman1/aai-runtime/testing";
@@ -94,21 +94,21 @@ test("the tool asks the model once", async () => {
94
94
  });
95
95
  ```
96
96
 
97
- The other doubles a tool body needs are on the same door — `stubDelegate` for
98
- a subagent, `endSessionCalls(ctx)` for a hang-up, `stubStepFetch`/`stubSpeech`/
97
+ The other doubles a tool body needs are on the same door — `stubDelegate` for a
98
+ subagent, `endSessionCalls(ctx)` for a hang-up, `stubStepFetch`/`stubSpeech`/
99
99
  `stubUploads`/`stubPlaceCall` for step I/O — and each topic file names the one
100
100
  its feature needs. **A fake that fills a process-wide slot is INSTALLED** from
101
101
  `@alexkroman1/aai-runtime/testing/vitest`, which arms it for one test and
102
102
  restores it afterwards: `installStubGateway(replies)` answers a step's model
103
103
  calls (`stepGenerate`, `stepGenerateJson`) and returns the calls it saw. Call it
104
- by its own name — do not alias it to `stubGateway`, which is the
105
- non-installing builder it wraps.
104
+ by its own name — do not alias it to `stubGateway`, which is the non-installing
105
+ builder it wraps.
106
106
 
107
107
  ## Evals: `agent.eval.test.ts`
108
108
 
109
109
  Run `pnpm eval` when you change what the agent DOES. Cases live in
110
- `agent.eval.test.ts` (the `quickstart-agent` template ships one), and
111
- everything an eval's harness needs — `describeEval`, the readers and claims,
110
+ `agent.eval.test.ts` (the `quickstart-agent` template ships one), and everything
111
+ an eval's harness needs — `describeEval`, the readers and claims,
112
112
  `evalSimulation`, and stubs like `stubGatewayRoute` — is on
113
113
  `@alexkroman1/aai-runtime/testing/vitest`:
114
114
 
@@ -145,9 +145,9 @@ prompt, the session's own event stream. Before trusting a green run:
145
145
  the model has to choose for itself, a refusal, a judgement).
146
146
 
147
147
  **Who is calling** is a suite or case option (a case's `null` clears it):
148
- `clientId`, `phone` and `call` are what `sessionClientId`,
149
- `sessionClientPhone`, `sessionCall` and `sessionContext` see; a refused call
150
- reads as `session.refused`. A tool's `endSession(ctx)` really hangs up
148
+ `clientId`, `phone` and `call` are what `sessionClientId`, `sessionClientPhone`,
149
+ `sessionCall` and `sessionContext` see; a refused call reads as
150
+ `session.refused`. A tool's `endSession(ctx)` really hangs up
151
151
  (`turn.endedSession`, `session.ended`); that turn awaits `onSessionEnd`.
152
152
  `network: evalNetwork({ state, routes })` answers every tool, builtin and step
153
153
  `fetch`, refusing the rest: `ctx.network`. `workflows` takes a client or
@@ -19,8 +19,8 @@ const myTool = tool({
19
19
  });
20
20
  ```
21
21
 
22
- `execute` may call `fetch` directly — tool code reaches external APIs the
23
- same way in `aai dev` and deployed.
22
+ `execute` may call `fetch` directly — tool code reaches external APIs the same
23
+ way in `aai dev` and deployed.
24
24
 
25
25
  ### `ctx` (ToolContext)
26
26
 
@@ -55,9 +55,9 @@ declare module "@alexkroman1/aai" {
55
55
  }
56
56
  ```
57
57
 
58
- **Pass `ctx.signal` to anything slow.** It is always present — no `?.`
59
- needed — and forwarding it is what makes a tool stop work the caller has
60
- already interrupted:
58
+ **Pass `ctx.signal` to anything slow.** It is always present — no `?.` needed —
59
+ and forwarding it is what makes a tool stop work the caller has already
60
+ interrupted:
61
61
 
62
62
  ```ts
63
63
  import { tool } from "@alexkroman1/aai";
@@ -80,9 +80,9 @@ so a variable declared empty and filled in the same scope widens from what you
80
80
  put in it — `const items = []` followed by `items.push(pick)` infers `Pick[]`
81
81
  with no annotation. Do NOT add type annotations defensively.
82
82
 
83
- **Annotate the DECLARATION when the first write is somewhere the compiler
84
- cannot follow** — inside a callback, or after the value has already been read.
85
- The widening only tracks straight-line code in one scope, so in those cases the
83
+ **Annotate the DECLARATION when the first write is somewhere the compiler cannot
84
+ follow** — inside a callback, or after the value has already been read. The
85
+ widening only tracks straight-line code in one scope, so in those cases the
86
86
  declaration keeps its starting type:
87
87
 
88
88
  ```ts no-check
@@ -95,8 +95,8 @@ let best: Pick | null = null; // ✅
95
95
  const [picks, set] = useState<Pick[]>([]); // ✅
96
96
  ```
97
97
 
98
- Annotating the _use_ instead does not help — the declaration is still wrong,
99
- so the next push just reports the next line.
98
+ Annotating the _use_ instead does not help — the declaration is still wrong, so
99
+ the next push just reports the next line.
100
100
 
101
101
  ### Session state
102
102
 
@@ -142,9 +142,9 @@ Four rules, and each is an error rather than advice if you get it wrong:
142
142
 
143
143
  - **`tool` reads, `updateTool` writes.** What a read is handed is FROZEN, so
144
144
  mutating it throws instead of quietly going nowhere.
145
- - **A write is SYNCHRONOUS.** The value you mutate is stored the moment your body
146
- returns, so an `updateTool` body may not `await`. When you need a model call or
147
- a fetch first, do it in an ordinary `tool()` and then mutate:
145
+ - **A write is SYNCHRONOUS.** The value you mutate is stored the moment your
146
+ body returns, so an `updateTool` body may not `await`. When you need a model
147
+ call or a fetch first, do it in an ordinary `tool()` and then mutate:
148
148
 
149
149
  ```ts no-check
150
150
  execute: async (args, ctx) => {
@@ -166,22 +166,22 @@ Four rules, and each is an error rather than advice if you get it wrong:
166
166
  either way; that is the reason for the rules above.
167
167
 
168
168
  There is nothing to declare on `agent()` — the slot owns its own default. Use
169
- `syncState: slot.projected` (or a list of them) to show state to a custom client.
170
- `slot.snapshot(ctx)` returns a mutable deep copy of the value — what a spec
171
- hands `slot.set`, instead of `structuredClone(slot.get(ctx))` and a cast.
169
+ `syncState: slot.projected` (or a list of them) to show state to a custom
170
+ client. `slot.snapshot(ctx)` returns a mutable deep copy of the value — what a
171
+ spec hands `slot.set`, instead of `structuredClone(slot.get(ctx))` and a cast.
172
172
 
173
173
  **`verbatimModuleSyntax` applies to every type you import** — `ToolContext`,
174
- `ToolDef`, `Message`, provider types. A plain
175
- `import { ToolContext }` fails; use `import type { ToolContext }`, or
176
- `import { agent, type ToolContext }` to combine with value imports.
174
+ `ToolDef`, `Message`, provider types. A plain `import { ToolContext }` fails;
175
+ use `import type { ToolContext }`, or `import { agent, type ToolContext }` to
176
+ combine with value imports.
177
177
 
178
178
  `ctx.generate({ prompt, system?, llm?, schema?, temperature?, maxOutputTokens? })`
179
- runs one LLM generation on the host. It defaults to the agent's pipeline
180
- `llm`; pass an `llm` descriptor (from `@alexkroman1/aai/llm`) or a model-id
181
- string to use another provider whose API key is in the agent's secrets —
182
- that's also how S2S agents use it. Pass a Zod schema as `schema` for typed
183
- structured output (`generateObject`-style): the result's `object` carries
184
- the parsed, typed value. A plain JSON Schema object also works.
179
+ runs one LLM generation on the host. It defaults to the agent's pipeline `llm`;
180
+ pass an `llm` descriptor (from `@alexkroman1/aai/llm`) or a model-id string to
181
+ use another provider whose API key is in the agent's secrets — that's also how
182
+ S2S agents use it. Pass a Zod schema as `schema` for typed structured output
183
+ (`generateObject`-style): the result's `object` carries the parsed, typed value.
184
+ A plain JSON Schema object also works.
185
185
 
186
186
  The option bag is `GenerateOptions` and the answer is `GenerateResult`
187
187
  (`GenerateObjectResult<T>` with a `schema`), both exported from
@@ -247,9 +247,9 @@ an SDK dependency. `technical-support-agent` is the worked example.
247
247
  ### Speakers (`speaker()`, `ctx.delegate`, `roster()`)
248
248
 
249
249
  `ctx.generate` is ONE prompt. When answering takes an unknown number of tool
250
- calls the conversation has no reason to carry, delegate to a **speaker** off
251
- the line: a second tool loop with its own prompt, model, tools and — the whole
252
- point — its own context window.
250
+ calls the conversation has no reason to carry, delegate to a **speaker** off the
251
+ line: a second tool loop with its own prompt, model, tools and — the whole point
252
+ — its own context window.
253
253
 
254
254
  ```ts
255
255
  import { speaker, tool } from "@alexkroman1/aai";
@@ -278,12 +278,12 @@ FINAL message, so declare `expectedOutput`; its context is isolated, so `task`
278
278
  must be a complete brief; `maxSteps` bounds the loop, and a capped run is asked
279
279
  for its answer with tools withheld; and say you are looking it up before you
280
280
  call. It may name its own `llm` and `tools` map; **delegation is one level
281
- deep**. In tests, `stubDelegate` (`@alexkroman1/aai-runtime/testing`) fakes
282
- it by name.
281
+ deep**. In tests, `stubDelegate` (`@alexkroman1/aai-runtime/testing`) fakes it
282
+ by name.
283
283
 
284
284
  When the SPEAKER has to change — triage verifies the caller, billing takes over
285
- with its own instructions and tools, one history — mark them `speaks: true` on
286
- a `roster()`; the first speaking entry answers the call.
285
+ with its own instructions and tools, one history — mark them `speaks: true` on a
286
+ `roster()`; the first speaking entry answers the call.
287
287
 
288
288
  ```ts
289
289
  import { agent, speaker, roster } from "@alexkroman1/aai";
@@ -339,9 +339,8 @@ Nothing else. `agent.ts` does not import it, does not list it, and takes no
339
339
  `tools` field at all — see "A file in `tools/` IS a tool" in the core guide.
340
340
 
341
341
  **Calling the network builtins from your own tool code.** `web_search`,
342
- `visit_webpage` and `fetch_json` are declared to the MODEL — the LLM calls
343
- them, and they are not on `ctx`. When your own `execute` needs one, import
344
- it:
342
+ `visit_webpage` and `fetch_json` are declared to the MODEL — the LLM calls them,
343
+ and they are not on `ctx`. When your own `execute` needs one, import it:
345
344
 
346
345
  ```ts no-check
347
346
  import { fetchJson, visitWebpage, webSearch } from "@alexkroman1/aai/tools";
@@ -353,28 +352,27 @@ execute: async ({ city }) => await fetchJson(`https://api.example.com/${city}`),
353
352
 
354
353
  Same implementations the builtins use, so you get URL screening, credential-
355
354
  header stripping, size caps and timeouts rather than a bare `fetch`. Plain
356
- `fetch` still works when you want none of that. There is no callable
357
- `run_code`: it exists to run code the model wrote, and tool code that wants
358
- to compute something can just compute it.
355
+ `fetch` still works when you want none of that. There is no callable `run_code`:
356
+ it exists to run code the model wrote, and tool code that wants to compute
357
+ something can just compute it.
359
358
 
360
359
  **But prefer the BUILTIN when the model should decide.** These two are not
361
360
  interchangeable:
362
361
 
363
362
  - If the agent's job is to search or browse — a research assistant, anything
364
363
  that follows a link the user mentions — declare
365
- `builtinTools: ["web_search", "visit_webpage"]` and let the model call
366
- them. It can then search several times with different queries, or read one
367
- specific page, as the conversation needs.
368
- - Import from `/tools` when YOUR tool's own logic needs a fetch: a currency
369
- tool hitting one known API, a price checker with a fixed endpoint.
364
+ `builtinTools: ["web_search", "visit_webpage"]` and let the model call them.
365
+ It can then search several times with different queries, or read one specific
366
+ page, as the conversation needs.
367
+ - Import from `/tools` when YOUR tool's own logic needs a fetch: a currency tool
368
+ hitting one known API, a price checker with a fixed endpoint.
370
369
 
371
370
  Wrapping `webSearch` in a single custom tool is the mistake to avoid — it
372
371
  replaces "the model searches as needed" with one fixed query-and-summarize
373
372
  pipeline, and no amount of prompting gets the flexibility back.
374
373
 
375
- **`inputSchema` is a Zod object, or absent.** The field itself is
376
- optional, but its VALUE must be a plain `z.object(...)` — so all of these
377
- are type errors:
374
+ **`inputSchema` is a Zod object, or absent.** The field itself is optional, but
375
+ its VALUE must be a plain `z.object(...)` — so all of these are type errors:
378
376
 
379
377
  ```ts no-check
380
378
  inputSchema: z.undefined(), // ✗ ZodUndefined
@@ -387,11 +385,11 @@ For a tool with no arguments write `tool({ description, execute })`, or
387
385
  argument optional, put `.optional()` on the FIELD, never on the object:
388
386
  `z.object({ notes: z.string().optional() })`.
389
387
 
390
- **Do not annotate `execute`'s return type.** Nothing needs it — the result
391
- is serialized to the model either way — and it reliably breaks the moment
392
- the tool also returns an error, because `Promise<DrugInfo>` does not accept
393
- `{ error: "not found" }`. Every such annotation eventually costs a build
394
- round to widen into a union. Let it infer.
388
+ **Do not annotate `execute`'s return type.** Nothing needs it — the result is
389
+ serialized to the model either way — and it reliably breaks the moment the tool
390
+ also returns an error, because `Promise<DrugInfo>` does not accept
391
+ `{ error: "not found" }`. Every such annotation eventually costs a build round
392
+ to widen into a union. Let it infer.
395
393
 
396
394
  ### A tool the BROWSER runs — `clientTool()`
397
395
 
@@ -434,19 +432,19 @@ export function LocationTool() {
434
432
  }
435
433
  ```
436
434
 
437
- - **Only a browser session can answer it.** On a phone call, in a text agent
438
- or a subagent the call fails naming why — give such an agent a server path.
435
+ - **Only a browser session can answer it.** On a phone call, in a text agent or
436
+ a subagent the call fails naming why — give such an agent a server path.
439
437
  - **No page answer within `timeoutMs` fails the call**, as does a barge-in.
440
- - **Never send a secret the model should not see through one** — the result
441
- goes into the conversation like any other tool result. Return the token, the
442
- last four digits, the decision — not the card number.
438
+ - **Never send a secret the model should not see through one** — the result goes
439
+ into the conversation like any other tool result. Return the token, the last
440
+ four digits, the decision — not the card number.
443
441
 
444
442
  ### A tool built by a factory still gets its own file
445
443
 
446
- The `tools/` rules (file name = tool name, default export, flat directory)
447
- are in the core guide. A tool that closes over module-local state, or one
448
- built by your own wrapper, still gets its own file — the file names the
449
- instance and the factory lives beside it:
444
+ The `tools/` rules (file name = tool name, default export, flat directory) are
445
+ in the core guide. A tool that closes over module-local state, or one built by
446
+ your own wrapper, still gets its own file — the file names the instance and the
447
+ factory lives beside it:
450
448
 
451
449
  ```ts no-check
452
450
  // tools/to_hotel_assistant.ts
@@ -484,13 +482,13 @@ it, `[]` for none.
484
482
 
485
483
  A keyed builtin reads its key from the agent env; list it in `requiredEnv`.
486
484
 
487
- **Every builtin here is a tool the MODEL calls, not a function your code
488
- can call** — there is no `fetch_json()` for a tool's `execute`. So:
485
+ **Every builtin here is a tool the MODEL calls, not a function your code can
486
+ call** — there is no `fetch_json()` for a tool's `execute`. So:
489
487
 
490
- - **Declare the builtin** (`builtinTools: ["fetch_json"]`) when the MODEL
491
- should decide the URL and read the JSON — lookups you cannot enumerate.
492
- - **Write your own tool** whose `execute` calls `fetch` when YOU own the
493
- URL and the shape — a specific endpoint, auth, or a reshaped response.
488
+ - **Declare the builtin** (`builtinTools: ["fetch_json"]`) when the MODEL should
489
+ decide the URL and read the JSON — lookups you cannot enumerate.
490
+ - **Write your own tool** whose `execute` calls `fetch` when YOU own the URL and
491
+ the shape — a specific endpoint, auth, or a reshaped response.
494
492
 
495
493
  Network builtins are SSRF-screened outside a container (private/loopback
496
494
  blocked). Your own tool code has open egress either way.
@@ -549,13 +547,13 @@ const feed = parseFeed(xml);
549
547
  const episodes = feed?.items.filter((item) => item.enclosureUrl !== undefined) ?? [];
550
548
  ```
551
549
 
552
- **Reach for this rather than writing the patterns.** Both are cheap to get
553
- wrong in ways that only show up on real pages: `<[^>]+>` cuts a tag whose
554
- attribute contains a `>`, `<script[^>]*>[\s\S]*?<\/script>` leaves the whole
555
- script in your prompt when the page was truncated mid-tag, and
556
- `indexOf("<title>")` finds an entry's title rather than a channel's. The
557
- `link-digest-workflow` and `podcast-digest-workflow` templates each shipped one
558
- before this subpath existed.
550
+ **Reach for this rather than writing the patterns.** Both are cheap to get wrong
551
+ in ways that only show up on real pages: `<[^>]+>` cuts a tag whose attribute
552
+ contains a `>`, `<script[^>]*>[\s\S]*?<\/script>` leaves the whole script in
553
+ your prompt when the page was truncated mid-tag, and `indexOf("<title>")` finds
554
+ an entry's title rather than a channel's. The `link-digest-workflow` and
555
+ `podcast-digest-workflow` templates each shipped one before this subpath
556
+ existed.
559
557
 
560
558
  ## Persisting data — bring your own client
561
559
 
@@ -583,9 +581,9 @@ export default tool({
583
581
  });
584
582
  ```
585
583
 
586
- Add the driver to your project's `package.json` and the URL with `aai secret put
587
- DATABASE_URL …` (or in `.env` under `aai dev`). Nothing here is privileged — an
588
- HTTP API, a provider SDK or a hosted KV works the same way.
584
+ Add the driver to your project's `package.json` and the URL with
585
+ `aai secret put DATABASE_URL …` (or in `.env` under `aai dev`). Nothing here is
586
+ privileged — an HTTP API, a provider SDK or a hosted KV works the same way.
589
587
 
590
588
  **What the platform DOES persist for you**, with no setup:
591
589
 
@@ -604,23 +602,24 @@ saves.
604
602
  ## Speech goes both ways — `spokenMoney`, `resolveOne`, `isoDate`
605
603
 
606
604
  **Speech goes both ways, and `@alexkroman1/aai` publishes both conversions.**
607
- Inbound: `spokenDigits("four one five")` is `"415"`, `spokenOrdinal("the third
608
- one")` is `3`, and `resolveOne(candidates, spoken, opts)` picks the one item a
609
- phrase meant — answering a `ToolFailure` when nothing matches or several do, the
610
- case a hand-written `.find()` gets wrong.
605
+ Inbound: `spokenDigits("four one five")` is `"415"`,
606
+ `spokenOrdinal("the third one")` is `3`, and
607
+ `resolveOne(candidates, spoken, opts)` picks the one item a phrase meant —
608
+ answering a `ToolFailure` when nothing matches or several do, the case a
609
+ hand-written `.find()` gets wrong.
611
610
 
612
611
  Outbound: an engine handed `$240.50` may read "dollar sign two hundred forty
613
- point five zero" — right text, wrong call.
614
- Render the words first: `spokenMoney(240.5)` is `"240 dollars and 50 cents"`,
615
- `spokenDate("2026-06-08")` is `"Monday, June 8"`, `spokenTime("18:30")` is
616
- `"6:30 PM"`. `mintCode("HTL")` mints a reference with no `0`/`O`, `1`/`I` or
617
- `L` in it — what comes back wrong read aloud.
612
+ point five zero" — right text, wrong call. Render the words first:
613
+ `spokenMoney(240.5)` is `"240 dollars and 50 cents"`, `spokenDate("2026-06-08")`
614
+ is `"Monday, June 8"`, `spokenTime("18:30")` is `"6:30 PM"`. `mintCode("HTL")`
615
+ mints a reference with no `0`/`O`, `1`/`I` or `L` in it — what comes back wrong
616
+ read aloud.
618
617
 
619
618
  **Declare a date or a time on the SCHEMA.** `isoDate("the arrival date")` and
620
619
  `clockTime("the pickup time")` are zod fields, so the rule reaches the model
621
620
  before it calls rather than as a refusal after. `isIsoDate` refuses
622
- `2026-02-30`; `addDays`/`daysBetween` compute in UTC — never turn a
623
- `YYYY-MM-DD` into a `Date` in local time.
621
+ `2026-02-30`; `addDays`/`daysBetween` compute in UTC — never turn a `YYYY-MM-DD`
622
+ into a `Date` in local time.
624
623
 
625
624
  **Never call `Math.random()` in a tool** — use `ctx.random`, which a test can
626
625
  substitute, so a dice roll or a minted code is something a spec can assert.