@alexkroman1/aai-cli 0.14.4 → 0.15.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.
@@ -551,7 +551,10 @@ function fileServedByVite(base, rawUrl) {
551
551
  * the {@link fileServedByVite} `bypass`, because a prefix key also claims a
552
552
  * same-named source directory (`workflows/` is where the SDK tells authors to
553
553
  * put bodies, and `api/` is as plausible);
554
- * - an EXACT HTTP route → a bare target string;
554
+ * - an EXACT HTTP route → a bare target string, unless a `ws` row already owns
555
+ * the path: `/phone` is both the carrier's media stream and its webhook, and
556
+ * a `ws: true` entry proxies plain HTTP too, so overwriting it would drop the
557
+ * upgrade;
555
558
  * - `root` is skipped: a `/` key would prefix-match every request, and the
556
559
  * page there is Vite's to serve.
557
560
  */
@@ -567,7 +570,7 @@ function devProxyTable(target, viteRoot) {
567
570
  target,
568
571
  bypass: (req) => fileServedByVite(viteRoot, req.url)
569
572
  };
570
- else table[route.path] = target;
573
+ else table[route.path] ??= target;
571
574
  }
572
575
  return table;
573
576
  }
package/dist/cli.mjs CHANGED
@@ -425,7 +425,7 @@ const dirArg = {
425
425
  */
426
426
  const REAL_EXECUTORS = {
427
427
  secret: () => import("./secret-DPdPEet2.mjs"),
428
- logs: () => import("./logs-CnPK-Prw.mjs")
428
+ logs: () => import("./logs-BeLJUZBn.mjs")
429
429
  };
430
430
  /**
431
431
  * Build `aai secret` and `aai logs` over `load`. The seam a spec hands fake
@@ -892,7 +892,7 @@ const dev = defineExec({
892
892
  },
893
893
  cwd: "agent",
894
894
  async run({ args, cwd, ui }) {
895
- const { executeDev } = await import("./dev-CsdCGy8U.mjs");
895
+ const { executeDev } = await import("./dev-Ci6tvUSa.mjs");
896
896
  return executeDev({
897
897
  cwd,
898
898
  port: args.port,
@@ -913,7 +913,7 @@ const consoleCommand = defineExec({
913
913
  } },
914
914
  cwd: "agent",
915
915
  async run({ args, cwd, mode, ui }) {
916
- const { executeConsole } = await import("./console-tRZbtiDe.mjs");
916
+ const { executeConsole } = await import("./console-JZnt9Ak6.mjs");
917
917
  return executeConsole({
918
918
  cwd,
919
919
  verbose: args.verbose,
@@ -3,7 +3,7 @@ import { a as ok, n as fail } from "./_output-DBP9Op_d.mjs";
3
3
  import { t as defaultUi } from "./_ui-Coe0zwmm.mjs";
4
4
  import { o as errorDetail, s as errorMessage } from "./_utils-BVLdBvdT.mjs";
5
5
  import { n as createWorkerEvaluator } from "./_bundler-B6v31ROV.mjs";
6
- import { loadWorker, t as resolveAgentEnv } from "./_dev-server-BVADkK1M.mjs";
6
+ import { loadWorker, t as resolveAgentEnv } from "./_dev-server-mHw_an61.mjs";
7
7
  import { styleText } from "node:util";
8
8
  import { spawn } from "node:child_process";
9
9
  import { connectSession, createRuntime, ensureSessionStateSchema, ensureWorkflowJournalSchema } from "@alexkroman1/aai-runtime";
@@ -164,7 +164,7 @@ async function resolveDevDeps(deps) {
164
164
  ui: deps.ui ?? defaultUi,
165
165
  startQuickTunnel: deps.startQuickTunnel ?? startQuickTunnel,
166
166
  runPublicUrlHook: deps.runPublicUrlHook ?? runPublicUrlHook,
167
- startDevServer: deps.startDevServer ?? (await import("./_dev-server-BVADkK1M.mjs")).startDevServer
167
+ startDevServer: deps.startDevServer ?? (await import("./_dev-server-mHw_an61.mjs")).startDevServer
168
168
  };
169
169
  }
170
170
  /**
@@ -9,7 +9,7 @@ import { sleep } from "@alexkroman1/aai/internal";
9
9
  /**
10
10
  * `aai logs` — what the deployed agent has printed.
11
11
  *
12
- * The terminal half of the same read the studio's Logs pane makes
12
+ * The terminal half of the same read the studio's coding agent makes
13
13
  * (`GET /:slug/logs`, aai-server/agent-logs.ts): a bounded ring the GUEST holds,
14
14
  * paged by cursor. Two things follow from that and are what this command has to
15
15
  * be honest about, because neither is visible in a wall of lines:
package/dist/logs.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * `aai logs` — what the deployed agent has printed.
3
3
  *
4
- * The terminal half of the same read the studio's Logs pane makes
4
+ * The terminal half of the same read the studio's coding agent makes
5
5
  * (`GET /:slug/logs`, aai-server/agent-logs.ts): a bounded ring the GUEST holds,
6
6
  * paged by cursor. Two things follow from that and are what this command has to
7
7
  * be honest about, because neither is visible in a wall of lines:
@@ -26,24 +26,29 @@ ASSEMBLYAI_API_KEY=
26
26
  # (free key: https://brave.com/search/api/):
27
27
  # BRAVE_API_KEY=
28
28
 
29
- # --- Durable workflows and uploads -----------------------------------------
29
+ # --- Saving data (optional) ------------------------------------------------
30
30
  #
31
- # A DEPLOYED agent's runs are durable with no setup — the platform keeps them
32
- # on its own database. `api.upload(file)` is the exception: an upload's record
33
- # needs a database YOU supply, so without a DATABASE_URL the bytes live only as
34
- # long as the sandbox even though the runs reading them do not.
31
+ # Just trying out a proof of concept? Skip this section: you need no database.
35
32
  #
36
- # These four are the LOCAL equivalents, and none is needed by an agent that has
37
- # no workflow.
33
+ # What persists with no setup: everything a call needs DURING the call (a tool's
34
+ # session state survives a reconnect), and, once deployed, durable workflow
35
+ # runs — the platform stores those for you.
38
36
  #
39
- # All three storage keys or none: two of three resolves to nothing and refuses
40
- # by name rather than half-working. Nothing creates the bucket for you — a
41
- # bucket is dashboard state, not a migration.
37
+ # What does NOT persist: anything you want to keep AFTER a call — a booking, a
38
+ # lead, a call summary. For that, bring your own database (Supabase, Neon, any
39
+ # Postgres) and write to it from a tool: put its connection string in this file
40
+ # for `aai dev`, `aai secret put` it for production, and read it with
41
+ # `ctx.env.YOUR_KEY`. See "Persisting data" in agent-guide/TOOLS.md.
42
42
  #
43
- # From the Supabase CLI: `supabase start`, then `supabase status -o env` for
44
- # API_URL and SERVICE_ROLE_KEY. The local stack declares one bucket, `blobs`,
45
- # and uploads land under an `uploads/` prefix inside it — the same layout
46
- # production uses beside its `blobs/<sha256>` deploy artifacts.
43
+ # The variables below are only for an agent that runs a workflow LOCALLY under
44
+ # `aai dev`, or accepts file uploads (`api.upload(file)`) — an upload's record
45
+ # needs a database you supply, even deployed. Otherwise leave them commented.
46
+ #
47
+ # Set all three AAI_UPLOAD_STORAGE_* keys or none (two of three is refused by
48
+ # name). Nothing creates the bucket for you. With the Supabase CLI:
49
+ # `supabase start`, then `supabase status -o env` for API_URL and
50
+ # SERVICE_ROLE_KEY; the local stack declares one bucket, `blobs`, and uploads
51
+ # land under its `uploads/` prefix.
47
52
  #
48
53
  # DATABASE_URL=postgresql://postgres:postgres@127.0.0.1:54322/postgres
49
54
  # AAI_UPLOAD_STORAGE_URL=http://127.0.0.1:54321
@@ -185,6 +185,14 @@ env var a tool or step reads; **publishing checks it**, so a missing key fails
185
185
  at `aai publish` instead of mid-call). `agent-guide/AGENT-API.md` lists every
186
186
  field.
187
187
 
188
+ **To change the model, set `llm` in `agent.ts`** — templates usually omit it, so
189
+ there is no line to find. The default is `gpt-5.6-luna` on the AssemblyAI LLM
190
+ Gateway, which is **not part of AssemblyAI's free credits**: an account with no
191
+ payment method is refused ("does not have access to this LLM Gateway model").
192
+ Add a card in the dashboard, or bring another provider's key
193
+ (`agent-guide/PROVIDERS.md`). A model must support tool calling if the agent has
194
+ tools — `qwen3.5-4b-32k-fast` does not.
195
+
188
196
  **Four modes, one field: `mode`.** Omit it for PIPELINE — the default, and the
189
197
  mode this guide assumes. `mode: "s2s"` beside an `s2s: assemblyAIS2s()`
190
198
  descriptor selects speech-to-speech; `mode: "text"` a text-only agent;
@@ -167,8 +167,11 @@ been spoken (`{ afterReply: false }` cuts it); a spec reads
167
167
 
168
168
  ### Placing a call
169
169
 
170
- `stepPlaceCall` (`/step`) dials through Twilio from a step; the answered call
171
- streams to `<agentUrl>/phone?carrier=twilio` (an agent with `telephony`):
170
+ `stepPlaceCall` (`/step`) dials through Twilio from a step; once answered,
171
+ Twilio fetches `<agentUrl>/phone?carrier=twilio` and streams to that agent
172
+ (which needs `telephony`). `agentUrl` defaults to THIS agent's public URL —
173
+ deployed, or the tunnel of `aai dev --tunnel` — so pass it only to have another
174
+ agent answer:
172
175
 
173
176
  ```ts
174
177
  import { requireStepEnv, stepPlaceCall } from "@alexkroman1/aai/step";
@@ -178,7 +181,6 @@ export async function dial(to: string, callRef: string): Promise<string> {
178
181
  carrier: "twilio",
179
182
  to,
180
183
  from: requireStepEnv("TWILIO_FROM_NUMBER"),
181
- agentUrl: requireStepEnv("CALLER_AGENT_URL"), // its public base URL
182
184
  parameters: { call: callRef }, // → `call.parameters`
183
185
  });
184
186
  return callId;
@@ -189,9 +191,10 @@ Credentials: env `TWILIO_ACCOUNT_SID`/`TWILIO_AUTH_TOKEN`, or `credentials`.
189
191
  Poll `stepCallStatus({ carrier, callId })` between `ctx.sleep`s until
190
192
  `completed`/`busy`/`no-answer`/`failed`/`canceled`. Failures are
191
193
  `PlaceCallError` (`retryable` only on 429/5xx/no answer; advice for common
192
- Twilio codes; never the token). A lost answer can ring twice: keep the dial
193
- step's `maxAttempts` small. `timeLimitS` (default 600) caps the call. Specs:
194
- `stubPlaceCall()` (`/testing`). Twilio only.
194
+ Twilio codes; never the token; a loopback `agentUrl` is refused). A lost answer
195
+ can ring twice: keep the dial step's `maxAttempts` small. `timeLimitS`
196
+ (default 600) caps the call. Specs: `stubPlaceCall({ publicUrl })` (`/testing`).
197
+ Twilio only.
195
198
 
196
199
  ### Saying something from outside a turn — `ctx.speech`
197
200
 
@@ -148,7 +148,40 @@ prompt, the session's own event stream. Before trusting a green run:
148
148
  `clientId`, `phone` and `call` are what `sessionClientId`, `sessionClientPhone`,
149
149
  `sessionCall` and `sessionContext` see; a refused call reads as
150
150
  `session.refused`. A tool's `endSession(ctx)` really hangs up
151
- (`turn.endedSession`, `session.ended`); that turn awaits `onSessionEnd`.
151
+ (`turn.endedSession`, `session.ended`); that turn awaits `onSessionEnd`. A
152
+ tool's `sendDtmf(ctx, keys)` presses really reach the session: `turn.dtmf` lists
153
+ the keys pressed that turn, whatever the tool is called. To test an agent that
154
+ places calls against an automated phone menu, declare the menu as data and walk
155
+ it — `walkPhoneTree(session, tree)` plays each prompt, follows the keys the
156
+ agent actually pressed (a wrong key replays the menu, as a real one does) and
157
+ answers `{ reached, path, turns, stopped }`:
158
+
159
+ ```ts
160
+ import { agent } from "@alexkroman1/aai";
161
+ import { describeEval, walkPhoneTree } from "@alexkroman1/aai-runtime/testing/vitest";
162
+ import { expect } from "vitest";
163
+
164
+ // In an eval this is `import agentDef from "virtual:aai/agent"`.
165
+ const agentDef = agent({ name: "Caller", greeting: "" });
166
+
167
+ describeEval(agentDef, (test) => {
168
+ test("presses through the menu to the pharmacist", async ({ session }) => {
169
+ const walk = await walkPhoneTree(session, {
170
+ name: "main",
171
+ prompt: "For billing, press 1. For the pharmacy, press 2.",
172
+ options: {
173
+ "1": { name: "billing", prompt: "Billing, this is Sam." },
174
+ "2": { name: "pharmacist", prompt: "Pharmacy, this is Dana. How can I help?" },
175
+ },
176
+ });
177
+ expect(walk.reached).toBe("pharmacist");
178
+ // A menu is not listening for words.
179
+ for (const turn of walk.turns.slice(0, -1)) expect(turn.text).toBe("");
180
+ });
181
+ });
182
+ ```
183
+
184
+ The `outbound-call-agent` template walks a three-level tree this way.
152
185
  `network: evalNetwork({ state, routes })` answers every tool, builtin and step
153
186
  `fetch`, refusing the rest: `ctx.network`. `workflows` takes a client or
154
187
  per-case factory: `ctx.workflowClient`. A failure prints the conversation.
@@ -213,7 +213,7 @@ Available from `@alexkroman1/aai-ui`:
213
213
  | `ChatView` | `icon?, title?` | Chat interface (header + messages + controls) |
214
214
  | `SidebarLayout` | `sidebar, children, sidebarWidth?, sidebarPosition?` | Two-column layout |
215
215
  | `MessageList` | — | Messages with auto-scroll, tool calls, transcript |
216
- | `Controls` | — | Stop/Resume + New Conversation buttons |
216
+ | `Controls` | — | Stop/Resume, New Conversation and End Call buttons |
217
217
  | `Button` | — | Styled button |
218
218
  | `UploadProgressBar` | `upload, onPause?, onResume?` | Bytes in flight, with pause/resume |
219
219
 
@@ -15,10 +15,10 @@
15
15
  "publish:agent": "aai publish"
16
16
  },
17
17
  "dependencies": {
18
- "@alexkroman1/aai": "^0.14.4",
19
- "@alexkroman1/aai-cli": "^0.14.4",
20
- "@alexkroman1/aai-runtime": "^0.14.4",
21
- "@alexkroman1/aai-ui": "^0.14.4",
18
+ "@alexkroman1/aai": "^0.15.1",
19
+ "@alexkroman1/aai-cli": "^0.15.1",
20
+ "@alexkroman1/aai-runtime": "^0.15.1",
21
+ "@alexkroman1/aai-ui": "^0.15.1",
22
22
  "react": "^19.3.0",
23
23
  "react-dom": "^19.3.0",
24
24
  "tailwindcss": "^4.0.0",
@@ -22,9 +22,15 @@
22
22
  * `system-prompt.md` declare — `./agent.ts` alone has no `end_call`.
23
23
  */
24
24
  import agentDef from "virtual:aai/agent";
25
- import { describeEval, toolArgsIn, toolNames } from "@alexkroman1/aai-runtime/testing/vitest";
25
+ import {
26
+ describeEval,
27
+ toolArgsIn,
28
+ toolNames,
29
+ walkPhoneTree,
30
+ } from "@alexkroman1/aai-runtime/testing/vitest";
26
31
  import { expect } from "vitest";
27
32
  import { signCall } from "./call-params.ts";
33
+ import { NO_FIT_CALL, PHARMACY_CALL } from "./phone-trees.ts";
28
34
 
29
35
  const SECRET = "eval-calls-key";
30
36
  const PROMPT =
@@ -34,6 +40,29 @@ const PROMPT =
34
40
 
35
41
  const parameters = await signCall({ id: "call_eval", prompt: PROMPT }, SECRET);
36
42
 
43
+ const DIGIT_WORDS = [
44
+ "zero",
45
+ "one",
46
+ "two",
47
+ "three",
48
+ "four",
49
+ "five",
50
+ "six",
51
+ "seven",
52
+ "eight",
53
+ "nine",
54
+ ];
55
+
56
+ /** The digits in `text`, number words included ("oh" as zero) — a number as it is spoken. */
57
+ function spokenDigits(text: string): string {
58
+ return text
59
+ .toLowerCase()
60
+ .replace(/\b(zero|oh|one|two|three|four|five|six|seven|eight|nine)\b/g, (word) =>
61
+ String(word === "oh" ? 0 : DIGIT_WORDS.indexOf(word)),
62
+ )
63
+ .replace(/\D/g, "");
64
+ }
65
+
37
66
  describeEval(
38
67
  agentDef,
39
68
  (test) => {
@@ -85,6 +114,9 @@ describeEval(
85
114
  "Thanks for calling. To leave a message for Maria, press 1. For all other calls, press 0.",
86
115
  );
87
116
  expect(toolArgsIn(turn.toolCalls, "press_keys")[0]).toMatchObject({ keys: "1" });
117
+ // What the line heard, and what the tool told the model back.
118
+ expect(turn.dtmf).toEqual(["1"]);
119
+ expect(turn.toolCalls[0]?.result).toContain('"pressed":"1"');
88
120
  expect(turn.endedSession).toBe(false);
89
121
  },
90
122
  {
@@ -98,7 +130,8 @@ describeEval(
98
130
  const turn = await session.say(
99
131
  "Hi, you've reached Maria. I can't come to the phone right now, please leave a message after the beep.",
100
132
  );
101
- expect(turn.text).toMatch(/415.?555.?0100|four one five/i);
133
+ // However it is read out: "415-555-0100", "4-1-5…", "four-one-five…".
134
+ expect(spokenDigits(turn.text), turn.text).toContain("4155550100");
102
135
  expect(toolArgsIn(turn.toolCalls, "end_call")[0]).toMatchObject({ reached: "voicemail" });
103
136
  expect(turn.endedSession).toBe(true);
104
137
  },
@@ -116,6 +149,66 @@ describeEval(
116
149
  },
117
150
  );
118
151
 
152
+ // Phone trees, walked by the keys the agent actually pressed (`turn.dtmf`): a
153
+ // wrong key replays the menu rather than advancing a script written for the
154
+ // right one. `phone-trees.ts` holds the trees, which a real call can play too.
155
+ describeEval(
156
+ agentDef,
157
+ (test) => {
158
+ test(
159
+ "walks three menus to the pharmacist without a word to any of them, then says why it called",
160
+ async ({ session }) => {
161
+ const walk = await walkPhoneTree(session, PHARMACY_CALL.tree);
162
+
163
+ expect(walk.reached, JSON.stringify(walk.path)).toBe(PHARMACY_CALL.goal);
164
+ // A menu is not listening for words.
165
+ const menus = walk.turns.slice(0, -1);
166
+ for (const turn of menus) expect(turn.text).toBe("");
167
+ const greeting = walk.turns.at(-1);
168
+ expect(greeting?.dtmf).toEqual([]);
169
+ expect(greeting?.text).toMatch(/jordan/i);
170
+ expect(greeting?.text).toMatch(/prescription/i);
171
+ },
172
+ {
173
+ stubReply: [
174
+ { tool: "press_keys", args: { keys: "1" } },
175
+ "",
176
+ { tool: "press_keys", args: { keys: "3" } },
177
+ "",
178
+ { tool: "press_keys", args: { keys: "2" } },
179
+ "",
180
+ "Hi Dana, I'm an AI assistant calling for Jordan Lee to check whether a prescription is ready for pickup.",
181
+ ],
182
+ },
183
+ );
184
+
185
+ test(
186
+ "takes the catch-all option when no option fits the task, then asks to be put through",
187
+ async ({ session }) => {
188
+ const walk = await walkPhoneTree(session, NO_FIT_CALL.tree);
189
+
190
+ expect(walk.reached, JSON.stringify(walk.path)).toBe(NO_FIT_CALL.goal);
191
+ expect(walk.turns.at(-1)?.text).toMatch(/pharmacy|prescription/i);
192
+ },
193
+ {
194
+ stubReply: [
195
+ { tool: "press_keys", args: { keys: "0" } },
196
+ "",
197
+ "Hi, I'm an AI assistant calling about a prescription for Jordan Lee. Could you put me through to the pharmacy?",
198
+ ],
199
+ },
200
+ );
201
+ },
202
+ {
203
+ env: { CALLS_API_KEY: SECRET },
204
+ call: {
205
+ carrier: "twilio",
206
+ callId: "CA_tree",
207
+ parameters: await signCall({ id: "call_tree", prompt: PHARMACY_CALL.task }, SECRET),
208
+ },
209
+ },
210
+ );
211
+
119
212
  describeEval(
120
213
  agentDef,
121
214
  (test) => {
@@ -36,7 +36,12 @@ import type { CallRecord } from "./api-types.ts";
36
36
  import { CHUNK_CHARS, readCall, signCall } from "./call-params.ts";
37
37
  import { closeCall, liveCall, openCall, recordTurn } from "./live-calls.ts";
38
38
  import { call } from "./shared.ts";
39
- import { type CallEnded, type CallInput, MAX_RING_POLLS } from "./workflows/call.ts";
39
+ import {
40
+ type CallEnded,
41
+ type CallInput,
42
+ MAX_RING_POLLS,
43
+ transcriptText,
44
+ } from "./workflows/call.ts";
40
45
  import { callEndedToken } from "./workflows/tokens.ts";
41
46
 
42
47
  const SECRET = "test-calls-key";
@@ -319,6 +324,75 @@ describe("the session", () => {
319
324
  expect(sentDtmfCalls(ctx)).toEqual([]);
320
325
  });
321
326
 
327
+ test("a phone tree walked key by key lands in the transcript the summary reads", async () => {
328
+ openCall("s_1", "call_tree", 0);
329
+ const ctx = createToolContext({ sessionId: "s_1" });
330
+ recordTurn("s_1", "callee", "For appointments, press 2. For billing, press 3.");
331
+ await run("press_keys", { keys: "2" }, ctx);
332
+ recordTurn("s_1", "callee", "Enter your party's extension, then pound.");
333
+ await run("press_keys", { keys: "204#" }, ctx);
334
+ recordTurn("s_1", "callee", "Front desk, this is Dana.");
335
+
336
+ expect(sentDtmfCalls(ctx)).toEqual(["2", "204#"]);
337
+ const transcript = liveCall("call_tree")?.transcript ?? [];
338
+ expect(transcriptText(transcript)).toBe(
339
+ [
340
+ "Callee: For appointments, press 2. For billing, press 3.",
341
+ "Agent: [pressed 2]",
342
+ "Callee: Enter your party's extension, then pound.",
343
+ "Agent: [pressed 204#]",
344
+ "Callee: Front desk, this is Dana.",
345
+ ].join("\n"),
346
+ );
347
+ });
348
+
349
+ test("press_keys sends the keys a model spells with spaces, commas or pauses", async () => {
350
+ const ctx = createToolContext({ sessionId: "s_1" });
351
+ await run("press_keys", { keys: "2 0 4 #" }, ctx);
352
+ await run("press_keys", { keys: "0w2" }, ctx);
353
+ expect(sentDtmfCalls(ctx)).toEqual(["204#", "0w2"]);
354
+ });
355
+
356
+ test("press_keys on a call that has ended says so, and writes no press", async () => {
357
+ openCall("s_gone", "call_gone", 0);
358
+ // A context whose session has no audio to play into — what `sendDtmf` sees
359
+ // once the line has dropped.
360
+ const ctx = { ...createToolContext({ sessionId: "s_1" }), sessionId: "s_gone" };
361
+ const result = await run("press_keys", { keys: "1" }, ctx);
362
+
363
+ expect(result).toEqual({ pressed: null, error: "The call has ended." });
364
+ expect(liveCall("call_gone")?.transcript).toEqual([]);
365
+ closeCall("s_gone");
366
+ });
367
+
368
+ test("records both sides as they are committed, but not the runtime's recovery line", () => {
369
+ openCall("s_1", "call_lines", 0);
370
+ const ctx = createToolContext({ sessionId: "s_1" });
371
+ const meta = { id: "evt_1", at: 0 };
372
+ agentDef.events?.["userTranscript.committed"]?.(
373
+ { type: "userTranscript.committed", text: "Hello?", meta },
374
+ ctx,
375
+ );
376
+ agentDef.events?.["agentTranscript.committed"]?.(
377
+ { type: "agentTranscript.committed", text: "Hi, is this Maria?", meta },
378
+ ctx,
379
+ );
380
+ agentDef.events?.["agentTranscript.committed"]?.(
381
+ {
382
+ type: "agentTranscript.committed",
383
+ text: "Sorry, something went wrong.",
384
+ recovery: "turn-failed",
385
+ meta,
386
+ },
387
+ ctx,
388
+ );
389
+
390
+ expect(liveCall("call_lines")?.transcript).toEqual([
391
+ { role: "callee", text: "Hello?" },
392
+ { role: "agent", text: "Hi, is this Maria?" },
393
+ ]);
394
+ });
395
+
322
396
  test("hands the transcript to the call's run as the session ends", async () => {
323
397
  const signal = vi.fn(async () => true);
324
398
  const workflows = { ...installStubWorkflows(), signal };
@@ -376,7 +450,6 @@ describe("the run is DURABLE", () => {
376
450
  vi.stubEnv("TWILIO_ACCOUNT_SID", "AC123");
377
451
  vi.stubEnv("TWILIO_AUTH_TOKEN", "token");
378
452
  vi.stubEnv("TWILIO_FROM_NUMBER", "+14155550100");
379
- vi.stubEnv("CALLER_AGENT_URL", "https://caller.example.com");
380
453
  vi.stubEnv("CALLS_API_KEY", SECRET);
381
454
  vi.stubEnv("ASSEMBLYAI_API_KEY", "sk-test");
382
455
  });
@@ -387,6 +460,7 @@ describe("the run is DURABLE", () => {
387
460
  const webhook = vi.fn((_body: unknown) => ({ status: 204, body: "" }));
388
461
  const twilio = stubPlaceCall({
389
462
  status: (placed) => (placed.polls === 1 ? "ringing" : "in-progress"),
463
+ publicUrl: "https://caller.example.com",
390
464
  ...options,
391
465
  otherwise: (req) =>
392
466
  model.route(req) ??
@@ -411,7 +485,7 @@ describe("the run is DURABLE", () => {
411
485
  expect(world.twilio.calls).toHaveLength(1);
412
486
  const placed = world.twilio.calls[0];
413
487
  expect(placed?.to).toBe(INPUT.phone_number);
414
- expect(placed?.streamUrl).toBe("wss://caller.example.com/phone?carrier=twilio");
488
+ expect(placed?.webhookUrl).toBe("https://caller.example.com/phone?carrier=twilio");
415
489
  // The answering session can verify the brief it was handed.
416
490
  expect(await readCall(placed?.parameters ?? {}, SECRET)).toEqual({
417
491
  id: INPUT.id,
@@ -28,10 +28,10 @@
28
28
  * | `CALLS_API_KEY` | The `Authorization` the API requires, and the key the call brief is signed with |
29
29
  * | `TWILIO_ACCOUNT_SID`, `TWILIO_AUTH_TOKEN` | The Twilio account that dials |
30
30
  * | `TWILIO_FROM_NUMBER` | A number on that account, in E.164 — the caller id |
31
- * | `CALLER_AGENT_URL` | This agent's PUBLIC base URL; Twilio streams the answered call to `<it>/phone` |
32
31
  *
33
- * Under `aai dev`, run `aai dev --tunnel` and set `CALLER_AGENT_URL` to the
34
- * tunnel URL it prints — Twilio cannot reach `localhost`.
32
+ * Twilio is pointed back at THIS agent's public URL, which the host knows: the
33
+ * deployed agent's own URL, or under `aai dev` the tunnel `aai dev --tunnel`
34
+ * opens — Twilio cannot reach `localhost`.
35
35
  *
36
36
  * ## The session is a stranger until it proves otherwise
37
37
  *
@@ -82,13 +82,7 @@ export default agent({
82
82
  greeting: "",
83
83
  // The run waits on these; the API starts them. A session never does.
84
84
  workflows: { call },
85
- requiredEnv: [
86
- "CALLS_API_KEY",
87
- "TWILIO_ACCOUNT_SID",
88
- "TWILIO_AUTH_TOKEN",
89
- "TWILIO_FROM_NUMBER",
90
- "CALLER_AGENT_URL",
91
- ],
85
+ requiredEnv: ["CALLS_API_KEY", "TWILIO_ACCOUNT_SID", "TWILIO_AUTH_TOKEN", "TWILIO_FROM_NUMBER"],
92
86
  // Phone audio: give a callee a beat longer to finish a thought.
93
87
  turnTaking: { minSilenceMs: 1200 },
94
88
 
@@ -102,7 +96,11 @@ export default agent({
102
96
 
103
97
  events: {
104
98
  "userTranscript.committed": (event, ctx) => recordTurn(ctx.sessionId, "callee", event.text),
105
- "agentTranscript.committed": (event, ctx) => recordTurn(ctx.sessionId, "agent", event.text),
99
+ // A `recovery` line is the runtime apologizing for a failed turn, not the
100
+ // agent's words: kept out, or the summary reports it as something said.
101
+ "agentTranscript.committed": (event, ctx) => {
102
+ if (event.recovery === undefined) recordTurn(ctx.sessionId, "agent", event.text);
103
+ },
106
104
  },
107
105
 
108
106
  async onSessionEnd({ sessionId, workflows }) {
@@ -0,0 +1,90 @@
1
+ // Copyright 2026 the AAI authors. MIT license.
2
+ /**
3
+ * Phone trees to test the caller against — each a task and the automated menu
4
+ * that answers it, declared as data so two harnesses play the same one:
5
+ *
6
+ * - `agent.eval.test.ts` walks it with `walkPhoneTree` — the model's choices,
7
+ * one text turn per menu, no phone involved.
8
+ * - `scripts/phone-tree-call.mjs` (in the aai repo) serves it as a REAL
9
+ * Twilio menu and has the deployed agent dial it — the keys as tones on a
10
+ * phone line, decoded by the carrier.
11
+ *
12
+ * Nothing in the agent imports this; it is test data.
13
+ */
14
+
15
+ import type { PhoneTree } from "@alexkroman1/aai-runtime/testing/vitest";
16
+
17
+ /** A task the caller is handed, the menu that answers when it dials, and the leaf it should reach. */
18
+ export type PhoneTreeCall = { task: string; tree: PhoneTree; goal: string };
19
+
20
+ const PHARMACIST = {
21
+ name: "pharmacist",
22
+ prompt: "Bayview pharmacy, this is Dana speaking. How can I help you?",
23
+ };
24
+
25
+ const PHARMACY_TASK =
26
+ "Call Bayview Medical's pharmacy to check whether Jordan Lee's prescription is ready " +
27
+ "for pickup. Jordan's date of birth is March 3rd, 1985. Ask what time the pharmacy " +
28
+ "closes today.";
29
+
30
+ /**
31
+ * Three menus deep, with an extension shortcut and a wrong turn at each level:
32
+ * a language menu, the main menu, then the pharmacy's own.
33
+ */
34
+ export const PHARMACY_CALL: PhoneTreeCall = {
35
+ task: PHARMACY_TASK,
36
+ goal: "pharmacist",
37
+ tree: {
38
+ name: "language",
39
+ prompt: "Para español, oprima el dos. For English, press one.",
40
+ options: {
41
+ "2": {
42
+ name: "spanish",
43
+ prompt: "Gracias por llamar a Bayview Medical. ¿En qué le puedo ayudar?",
44
+ },
45
+ "1": {
46
+ name: "main",
47
+ prompt:
48
+ "Thank you for calling Bayview Medical. If this is a medical emergency, hang up " +
49
+ "and dial 911. For appointments, press 1. For billing, press 2. For the pharmacy, " +
50
+ "press 3. If you know your party's extension, you may dial it at any time.",
51
+ options: {
52
+ "1": { name: "appointments", prompt: "Appointments, this is Sam. How can I help?" },
53
+ "2": { name: "billing", prompt: "Billing department, this is Lee." },
54
+ "3": {
55
+ name: "pharmacy",
56
+ prompt:
57
+ "Pharmacy. To refill a prescription, press 1. To check on a prescription or " +
58
+ "speak with a pharmacist, press 2.",
59
+ options: {
60
+ "1": {
61
+ name: "refill line",
62
+ prompt: "Automated refills. Please enter your prescription number.",
63
+ },
64
+ "2": PHARMACIST,
65
+ "204": PHARMACIST,
66
+ },
67
+ },
68
+ "204": PHARMACIST,
69
+ },
70
+ },
71
+ },
72
+ },
73
+ };
74
+
75
+ /** One menu where no option names the task — the caller should take the catch-all. */
76
+ export const NO_FIT_CALL: PhoneTreeCall = {
77
+ task: PHARMACY_TASK,
78
+ goal: "operator",
79
+ tree: {
80
+ name: "main",
81
+ prompt:
82
+ "Thank you for calling Bayview Medical. For lab results, press 1. For new patient " +
83
+ "registration, press 2. For all other questions, press 0.",
84
+ options: {
85
+ "1": { name: "lab results", prompt: "Lab results line. Please enter your patient ID." },
86
+ "2": { name: "registration", prompt: "New patient registration, this is Kim." },
87
+ "0": { name: "operator", prompt: "Bayview Medical operator, how may I direct your call?" },
88
+ },
89
+ },
90
+ };
@@ -10,16 +10,32 @@ this call is given below under "This call". Carry it out, and nothing else.
10
10
  task does not cover, say you will pass the request on.
11
11
  - Read times and dates back once when something is agreed, so there is no
12
12
  doubt.
13
- - If you reach voicemail or an answering machine (a recorded greeting, a beep),
14
- leave the message the task asks for — or a short one with who you are and why
15
- you called — then call `end_call` with `reached: "voicemail"`.
13
+ - If you reach voicemail or an answering machine and its greeting has ended
14
+ ("leave a message after the beep"), leave the message the task asks for — or
15
+ a short one with who you are and why you called — and call `end_call` with
16
+ `reached: "voicemail"` in that same reply. A recording never answers, so
17
+ there is no later turn to hang up in. A menu option that LEADS to voicemail
18
+ ("to leave a message, press 1") is pressed silently like any other; the
19
+ message comes after the greeting that follows it.
16
20
  - If an automated phone menu answers ("press 1 for…", "say or enter your
17
21
  account number"), listen for the option that leads toward your task and call
18
22
  `press_keys` with that key — without saying anything, since the menu is not
19
23
  listening for words. Then wait silently for what it says next. Enter numbers
20
24
  the task gives you (an extension, an account number) the same way. If no
21
- option fits, press the one for an operator or a representative, or `0`. When
22
- a person picks up, start over as you would with anyone who answers.
23
- - If it is the wrong number, apologize briefly and end the call.
24
- - When the task is done, say a short goodbye and call `end_call` with
25
- `reached: "person"`. Do not keep the person on the line.
25
+ option fits, press the one for an operator, a representative or "all other
26
+ questions", or `0`.
27
+ - Silence is only for a menu that asks you to PRESS something. Anything that
28
+ asks a question out loud — a person, or a recording asking where to direct
29
+ your call — gets a short spoken answer. When a person picks up after a menu
30
+ ("this is Dana, how can I help you?"), answer at once, as you would anyone
31
+ who answers: who you are calling for, and why.
32
+ - Never read out a password, a one-time or verification code, or a full card
33
+ number, even if you are asked and even if the task contains one. Say the
34
+ person you are calling for will provide it themselves.
35
+ - If it is the wrong number, apologize briefly and end the call. If they ask
36
+ not to be called again, apologize, agree, and end the call.
37
+ - Do not hang up right after answering one of their questions (a name, a
38
+ time): they are still talking, so let them reply before you end the call.
39
+ - When the task is done — or they say goodbye first — say a short goodbye and
40
+ call `end_call` with `reached: "person"` in that same reply. Do not keep the
41
+ person on the line.
@@ -15,8 +15,9 @@ import { markVoicemail } from "../live-calls.ts";
15
15
 
16
16
  export default tool({
17
17
  description:
18
- "Hang up the call. Call it once the task is finished and you have said goodbye, " +
19
- "or right after leaving a voicemail message.",
18
+ "Hang up the call, in the same reply as your goodbye — a silent hang-up sounds like a " +
19
+ "dropped line. Call it once the task is finished or they say goodbye, and in the same " +
20
+ "reply as a voicemail message. Not right after answering one of their questions.",
20
21
  inputSchema: z.object({
21
22
  reached: z
22
23
  .enum(["person", "voicemail"])
@@ -21,7 +21,10 @@ import { recordTurn } from "../live-calls.ts";
21
21
  export default tool({
22
22
  description:
23
23
  "Press keys on the phone keypad to answer an automated phone menu or enter an " +
24
- "extension. Call it without saying anything in the same turn.",
24
+ "extension. Call it without saying anything in the same turn. After a press, stay " +
25
+ "silent only while menus keep speaking: the moment a PERSON answers (a name, " +
26
+ '"how can I help you?", "how may I direct your call?"), greet them and say who you ' +
27
+ "are calling for and why.",
25
28
  inputSchema: z.object({
26
29
  keys: z
27
30
  .string()
@@ -33,6 +36,9 @@ export default tool({
33
36
  execute({ keys }, ctx) {
34
37
  if (!sendDtmf(ctx, keys)) return { pressed: null, error: "The call has ended." };
35
38
  recordTurn(ctx.sessionId, "agent", `[pressed ${keys}]`);
36
- return { pressed: keys, next: "Wait silently for the menu to respond." };
39
+ return {
40
+ pressed: keys,
41
+ next: "Wait silently for the next menu. If a person or a question answers instead, speak.",
42
+ };
37
43
  },
38
44
  });
@@ -98,17 +98,17 @@ export const CALL_WINDOW_MS = (CALL_TIME_LIMIT_S + 120) * 1000;
98
98
  export type Dialled = { callId: string } | { refused: string };
99
99
 
100
100
  /** The env keys the dial needs, read one at a time so a missing one is named. */
101
- function dialEnv(): { from: string; agentUrl: string; secret: string } {
101
+ function dialEnv(): { from: string; secret: string } {
102
102
  return {
103
103
  from: requireStepEnv("TWILIO_FROM_NUMBER"),
104
- agentUrl: requireStepEnv("CALLER_AGENT_URL"),
105
104
  secret: requireStepEnv("CALLS_API_KEY"),
106
105
  };
107
106
  }
108
107
 
109
108
  /**
110
109
  * Ask Twilio to ring `phone_number` and stream the answered call to this
111
- * agent. A refusal nobody can retry past — a missing env key, a bad number —
110
+ * agent — `stepPlaceCall` points it at the agent's own public URL. A refusal
111
+ * nobody can retry past — a missing env key, a bad number, no public URL —
112
112
  * comes back as `{ refused }`; anything retryable is thrown.
113
113
  */
114
114
  export async function dial(input: CallInput): Promise<Dialled> {
@@ -119,7 +119,6 @@ export async function dial(input: CallInput): Promise<Dialled> {
119
119
  carrier: "twilio",
120
120
  to: input.phone_number,
121
121
  from: env.from,
122
- agentUrl: env.agentUrl,
123
122
  parameters,
124
123
  timeLimitS: CALL_TIME_LIMIT_S,
125
124
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexkroman1/aai-cli",
3
- "version": "0.14.4",
3
+ "version": "0.15.1",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -58,9 +58,9 @@
58
58
  "vite": "^8.3.1",
59
59
  "xstate": "^5.33.2",
60
60
  "zod": "^4.6.5",
61
- "@alexkroman1/aai": "0.14.4",
62
- "@alexkroman1/aai-runtime": "0.14.4",
63
- "@alexkroman1/aai-ui": "0.14.4"
61
+ "@alexkroman1/aai": "0.15.1",
62
+ "@alexkroman1/aai-runtime": "0.15.1",
63
+ "@alexkroman1/aai-ui": "0.15.1"
64
64
  },
65
65
  "devDependencies": {
66
66
  "playwright": "^1.63.0",