@alexkroman1/aai-cli 17.0.0 → 18.0.0

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 (61) hide show
  1. package/dist/_console-audio.d.ts +17 -0
  2. package/dist/_console-session.d.ts +70 -0
  3. package/dist/{_dev-server-CLU9xjH5.mjs → _dev-server-Dtp4aAlo.mjs} +1 -1
  4. package/dist/_dev-server.d.ts +1 -0
  5. package/dist/_templates-DXadVNsL.mjs +135 -0
  6. package/dist/_templates.d.ts +11 -34
  7. package/dist/cli.mjs +27 -7
  8. package/dist/console-BsyE3DyB.mjs +422 -0
  9. package/dist/console.d.ts +37 -0
  10. package/dist/{dev-ChsrNHpK.mjs → dev-BGWU2zPP.mjs} +1 -1
  11. package/dist/{init-W-4k-lCF.mjs → init-CbOhyNYe.mjs} +1 -1
  12. package/dist/scaffold/CLAUDE.md +110 -102
  13. package/dist/scaffold/package.json +4 -4
  14. package/dist/start.d.ts +3 -3
  15. package/dist/{studio-DEAJGBXa.mjs → studio-BRJsw7lr.mjs} +1 -1
  16. package/dist/templates/applicant-screening-agent/agent.test.ts +17 -13
  17. package/dist/templates/applicant-screening-agent/crews.ts +4 -4
  18. package/dist/templates/code-interpreter-agent/agent.test.ts +2 -2
  19. package/dist/templates/coding-agent/agent.ts +1 -1
  20. package/dist/templates/custom-pipeline-agent/agent.ts +2 -2
  21. package/dist/templates/custom-pipeline-agent/modes.test.ts +4 -4
  22. package/dist/templates/custom-pipeline-agent/stages.test.ts +75 -83
  23. package/dist/templates/emergency-dispatch-agent/agent.eval.test.ts +1 -1
  24. package/dist/templates/entertainment-picks-agent/agent.eval.test.ts +1 -1
  25. package/dist/templates/executive-inbox-agent/agent.test.ts +35 -25
  26. package/dist/templates/executive-inbox-agent/calendar.test.ts +13 -7
  27. package/dist/templates/executive-inbox-agent/meeting.ts +2 -2
  28. package/dist/templates/front-desk-agent/agent.eval.test.ts +174 -0
  29. package/dist/templates/front-desk-agent/agent.test.ts +150 -0
  30. package/dist/templates/front-desk-agent/agent.ts +22 -0
  31. package/dist/templates/front-desk-agent/shared.ts +234 -0
  32. package/dist/templates/front-desk-agent/system-prompt.md +13 -0
  33. package/dist/templates/front-desk-agent/tools/verify_account.ts +41 -0
  34. package/dist/templates/hotel-reception-agent/agent.test.ts +1 -2
  35. package/dist/templates/hotel-reception-agent/desk-seams.test.ts +1 -2
  36. package/dist/templates/medication-safety-agent/agent.test.ts +3 -4
  37. package/dist/templates/pizza-ordering-agent/agent.eval.test.ts +68 -2
  38. package/dist/templates/push-to-talk-agent/agent.eval.test.ts +74 -0
  39. package/dist/templates/push-to-talk-agent/agent.test.ts +61 -0
  40. package/dist/templates/push-to-talk-agent/agent.ts +22 -0
  41. package/dist/templates/push-to-talk-agent/client.tsx +124 -0
  42. package/dist/templates/push-to-talk-agent/shared.ts +34 -0
  43. package/dist/templates/push-to-talk-agent/system-prompt.md +11 -0
  44. package/dist/templates/push-to-talk-agent/tools/list_notes.ts +15 -0
  45. package/dist/templates/push-to-talk-agent/tools/save_note.ts +26 -0
  46. package/dist/templates/quickstart-agent/agent.eval.test.ts +52 -0
  47. package/dist/templates/research-handoff-agent/agent.eval.test.ts +1 -1
  48. package/dist/templates/research-handoff-agent/agent.test.ts +34 -26
  49. package/dist/templates/research-planner-agent/agent.test.ts +26 -16
  50. package/dist/templates/retail-orders-agent/agent.eval.test.ts +1 -1
  51. package/dist/templates/roadside-assistance-agent/agent.eval.test.ts +87 -0
  52. package/dist/templates/roadside-assistance-agent/agent.test.ts +1 -1
  53. package/dist/templates/technical-support-agent/agent.test.ts +26 -20
  54. package/dist/templates/technical-support-agent/procedure.ts +3 -3
  55. package/dist/templates/topic-briefing-agent/agent.test.ts +38 -25
  56. package/dist/templates/topic-briefing-agent/shared.ts +10 -9
  57. package/dist/templates/travel-concierge-agent/agent.eval.test.ts +9 -7
  58. package/dist/templates/travel-concierge-agent/agent.test.ts +1 -2
  59. package/dist/templates/word-game-agent/agent.test.ts +3 -1
  60. package/package.json +4 -4
  61. package/dist/_templates-IMeKMVIj.mjs +0 -291
@@ -0,0 +1,150 @@
1
+ /** The def a DEPLOYED agent runs: authored, plus what `tools/` declares. */
2
+ import agentDef from "virtual:aai/agent";
3
+ import { HANDOFF_TOOL_NAME } from "@alexkroman1/aai";
4
+ import { createToolContext, toolRunner } from "@alexkroman1/aai/testing";
5
+ import { isToolFailure } from "@alexkroman1/aai/utils";
6
+ import { describe, expect, test } from "vitest";
7
+ import { billing, desk, deskSlot, support, triage, whichDesk } from "./shared.ts";
8
+
9
+ /** A tool by the name the model calls it by, bound to this agent. */
10
+ const run = toolRunner(agentDef);
11
+
12
+ /** Whether a result is the desk's "not verified" refusal. */
13
+ function refusal(result: unknown): string {
14
+ if (!isToolFailure(result)) throw new Error(`expected a refusal, got ${JSON.stringify(result)}`);
15
+ return result.error;
16
+ }
17
+
18
+ describe("the roster", () => {
19
+ test("triage answers the phone, and every persona's tools plus `handoff` are on the agent", () => {
20
+ expect(desk.list.map((one) => one.name)).toEqual(["triage", "billing", "support"]);
21
+ expect(Object.keys(agentDef.tools).sort()).toEqual([
22
+ HANDOFF_TOOL_NAME,
23
+ "issue_refund",
24
+ "lookup_invoice",
25
+ "run_diagnostic",
26
+ "schedule_technician",
27
+ "verify_account",
28
+ ]);
29
+ expect(desk.active(createToolContext())).toBe(triage);
30
+ });
31
+
32
+ test("the minted handoff tool describes each desk, which is the whole routing decision", () => {
33
+ const minted = agentDef.tools[HANDOFF_TOOL_NAME];
34
+ expect(minted?.description).toContain(`- billing: ${billing.description}`);
35
+ expect(minted?.description).toContain(`- support: ${support.description}`);
36
+ });
37
+ });
38
+
39
+ describe("verify_account hands off in the same call", () => {
40
+ test("a matching account is verified and the caller is with the desk they asked for", async () => {
41
+ const ctx = createToolContext();
42
+ const result = await run(
43
+ "verify_account",
44
+ { accountNumber: "1001", zip: "94107", needs: "billing" },
45
+ ctx,
46
+ );
47
+ expect(result).toMatchObject({ handoff: true, from: "triage", to: "billing" });
48
+ expect(desk.active(ctx)).toBe(billing);
49
+ expect(deskSlot.get(ctx).verified).toEqual({ number: "1001", name: "Dana" });
50
+ // The note is what billing reads in its prompt section from the next step.
51
+ expect(desk.position(ctx).note).toContain("Dana is verified");
52
+ });
53
+
54
+ test("spoken digits are tolerated, a mismatch is refused, and nobody is handed off", async () => {
55
+ const ctx = createToolContext();
56
+ expect(
57
+ await run("verify_account", { accountNumber: "10 01", zip: "94107", needs: "support" }, ctx),
58
+ ).toMatchObject({ to: "support" });
59
+
60
+ const other = createToolContext();
61
+ const result = await run(
62
+ "verify_account",
63
+ { accountNumber: "1001", zip: "00000", needs: "billing" },
64
+ other,
65
+ );
66
+ expect(refusal(result)).toContain("No account matches");
67
+ expect(desk.active(other)).toBe(triage);
68
+ expect(deskSlot.get(other).verified).toBeUndefined();
69
+ });
70
+ });
71
+
72
+ describe("a desk's tools are its own", () => {
73
+ test("a billing tool called while triage speaks is refused, naming who is and how to hand off", async () => {
74
+ const ctx = createToolContext();
75
+ const error = refusal(await run("lookup_invoice", {}, ctx));
76
+ expect(error).toContain("belongs to the billing persona");
77
+ expect(error).toContain("triage is speaking");
78
+ expect(error).toContain(HANDOFF_TOOL_NAME);
79
+ });
80
+
81
+ test("after the handoff the same tool runs, over the slot triage wrote", async () => {
82
+ const ctx = createToolContext();
83
+ await run("verify_account", { accountNumber: "1001", zip: "94107", needs: "billing" }, ctx);
84
+ expect(await run("lookup_invoice", {}, ctx)).toEqual({
85
+ invoices: [
86
+ { id: "INV-1001-1", amount: 59.0, status: "paid" },
87
+ { id: "INV-1001-2", amount: 79.5, status: "open" },
88
+ ],
89
+ });
90
+ expect(await run("issue_refund", { invoiceId: "INV-1001-2" }, ctx)).toEqual({
91
+ refunded: "INV-1001-2",
92
+ amount: 79.5,
93
+ });
94
+ // The refund is in the slot, so a second look shows it and a second refund is refused.
95
+ expect(await run("lookup_invoice", { invoiceId: "INV-1001-2" }, ctx)).toEqual({
96
+ invoices: [{ id: "INV-1001-2", amount: 79.5, status: "refunded" }],
97
+ });
98
+ expect(refusal(await run("issue_refund", { invoiceId: "INV-1001-2" }, ctx))).toContain(
99
+ "already been refunded",
100
+ );
101
+ // And support's tools are still not billing's.
102
+ expect(refusal(await run("run_diagnostic", {}, ctx))).toContain("support persona");
103
+ });
104
+
105
+ test("support verifies a caller who came straight to it, then diagnoses and books", async () => {
106
+ const ctx = createToolContext();
107
+ // The model routed here on the caller's words, before any verification.
108
+ await run(HANDOFF_TOOL_NAME, { persona: "support", note: "Says the line is down." }, ctx);
109
+ expect(desk.active(ctx)).toBe(support);
110
+ expect(refusal(await run("run_diagnostic", {}, ctx))).toContain("not verified");
111
+
112
+ // `verify_account` is everyone's, and handing off to the desk already
113
+ // speaking changes nothing.
114
+ await run("verify_account", { accountNumber: "2002", zip: "10001", needs: "support" }, ctx);
115
+ expect(await run("run_diagnostic", {}, ctx)).toEqual({
116
+ line: "no-signal",
117
+ needsTechnician: true,
118
+ });
119
+ expect(await run("schedule_technician", { day: "Tuesday", window: "morning" }, ctx)).toEqual({
120
+ booked: { day: "Tuesday", window: "morning" },
121
+ });
122
+ expect(deskSlot.get(ctx).appointment).toEqual({ day: "Tuesday", window: "morning" });
123
+ });
124
+
125
+ test("a healthy line gets no technician", async () => {
126
+ const ctx = createToolContext();
127
+ await run("verify_account", { accountNumber: "1001", zip: "94107", needs: "support" }, ctx);
128
+ // Dana's line is intermittent; make the point with the refusal path on a
129
+ // fixture whose line IS healthy would need a third account — so assert the
130
+ // guard's message through the shared helper instead.
131
+ expect(await run("run_diagnostic", {}, ctx)).toEqual({
132
+ line: "intermittent",
133
+ needsTechnician: true,
134
+ });
135
+ });
136
+ });
137
+
138
+ describe("handing back", () => {
139
+ test("billing can hand the caller to support and back, and the slot survives every hop", async () => {
140
+ const ctx = createToolContext();
141
+ await run("verify_account", { accountNumber: "1001", zip: "94107", needs: "billing" }, ctx);
142
+ await run(HANDOFF_TOOL_NAME, { persona: "support" }, ctx);
143
+ expect(desk.position(ctx)).toMatchObject({ persona: support, from: "billing" });
144
+ expect(await run("run_diagnostic", {}, ctx)).toMatchObject({ line: "intermittent" });
145
+ await run(HANDOFF_TOOL_NAME, { persona: "triage" }, ctx);
146
+ expect(desk.active(ctx)).toBe(triage);
147
+ expect(deskSlot.get(ctx).verified?.name).toBe("Dana");
148
+ expect(whichDesk.execute({}, ctx)).toEqual({ persona: "triage" });
149
+ });
150
+ });
@@ -0,0 +1,22 @@
1
+ import { agent } from "@alexkroman1/aai";
2
+ import { desk, deskSlot } from "./shared.ts";
3
+ import systemPrompt from "./system-prompt.md?raw";
4
+
5
+ /**
6
+ * A front desk that hands the caller between three personas — the worked
7
+ * example for `agent({ personas })`. `shared.ts` declares the roster and each
8
+ * desk's tools; `tools/verify_account.ts` is the one tool every desk carries.
9
+ *
10
+ * `systemPrompt` here is what holds at EVERY desk. The active persona's own
11
+ * instructions are appended under it, per model step, and change on a handoff;
12
+ * this file's prompt does not.
13
+ */
14
+ export default agent({
15
+ name: "Northwind Front Desk",
16
+ description:
17
+ "Answers the phone for an internet provider and hands the caller between triage, billing and support",
18
+ systemPrompt,
19
+ greeting: "Northwind Internet, front desk. Is this about your bill, or about your service?",
20
+ personas: desk,
21
+ syncState: deskSlot.projected,
22
+ });
@@ -0,0 +1,234 @@
1
+ /**
2
+ * The front desk's ROSTER — who can speak on this call — and the account slot
3
+ * every desk reads.
4
+ *
5
+ * This template is the worked example for `agent({ personas })`: three personas
6
+ * over ONE session, ONE history and ONE slot store. Triage answers the phone;
7
+ * billing and support each own tools the other cannot call; a handoff is what
8
+ * swaps who is speaking, and the caller hears one continuous conversation.
9
+ *
10
+ * Two ways the swap happens here, and both are on purpose:
11
+ *
12
+ * - **In code, when the tool IS the decision.** `tools/verify_account.ts`
13
+ * verifies the caller and hands them to whichever desk they asked for in the
14
+ * same call — `desk.handoff(ctx, needs, { note })`. The model never has to
15
+ * remember to make a second call.
16
+ * - **By the model, when the caller's words are.** The roster mints a
17
+ * `handoff` tool whose description is each persona's `description` below,
18
+ * so "my internet is down" can reach support without a script for it.
19
+ *
20
+ * Every persona's tools are declared HERE, as a map on the persona, rather than
21
+ * as files under `tools/` — that directory is every persona's, and a persona's
22
+ * map is the strictly narrower set one desk owns. The gate is at execution: a
23
+ * billing tool called while triage speaks answers a refusal naming who is and
24
+ * how to hand off — a result the model reads, on every transport.
25
+ */
26
+ import {
27
+ type DeepReadonly,
28
+ type PersonaDef,
29
+ type Personas,
30
+ persona,
31
+ personas,
32
+ sessionSlot,
33
+ tool,
34
+ } from "@alexkroman1/aai";
35
+ import { type ToolFailure, toolFailure } from "@alexkroman1/aai/utils";
36
+ import { z } from "zod";
37
+
38
+ // ─── The book of accounts (a fixture, standing in for a CRM) ────────────────
39
+
40
+ export interface Invoice {
41
+ id: string;
42
+ amount: number;
43
+ status: "open" | "paid" | "refunded";
44
+ }
45
+
46
+ export interface Account {
47
+ number: string;
48
+ zip: string;
49
+ name: string;
50
+ invoices: Invoice[];
51
+ /** What the line diagnostic answers — "healthy", or the fault it finds. */
52
+ line: "healthy" | "no-signal" | "intermittent";
53
+ }
54
+
55
+ export const ACCOUNTS: readonly Account[] = [
56
+ {
57
+ number: "1001",
58
+ zip: "94107",
59
+ name: "Dana",
60
+ invoices: [
61
+ { id: "INV-1001-1", amount: 59.0, status: "paid" },
62
+ { id: "INV-1001-2", amount: 79.5, status: "open" },
63
+ ],
64
+ line: "intermittent",
65
+ },
66
+ {
67
+ number: "2002",
68
+ zip: "10001",
69
+ name: "Sam",
70
+ invoices: [{ id: "INV-2002-1", amount: 45.0, status: "open" }],
71
+ line: "no-signal",
72
+ },
73
+ ];
74
+
75
+ export function findAccount(number: string, zip: string): Account | undefined {
76
+ return ACCOUNTS.find((one) => one.number === number && one.zip === zip);
77
+ }
78
+
79
+ // ─── Session state ───────────────────────────────────────────────────────────
80
+
81
+ /** What this call has established about the caller. */
82
+ export interface Desk {
83
+ /** Set by `verify_account`; every billing and support tool needs it. */
84
+ verified?: { number: string; name: string };
85
+ /** Refunds issued on this call, by invoice id. */
86
+ refunded: string[];
87
+ /** A technician visit booked on this call. */
88
+ appointment?: { day: string; window: string };
89
+ }
90
+
91
+ export const deskSlot = sessionSlot("desk", (): Desk => ({ refunded: [] }), {
92
+ view: (desk) => ({
93
+ verified: desk.verified?.name,
94
+ refunded: desk.refunded.length,
95
+ appointment: desk.appointment,
96
+ }),
97
+ });
98
+
99
+ /** The one answer every desk gives an unverified caller. */
100
+ export const NOT_VERIFIED = toolFailure(
101
+ "The caller is not verified. Ask for their account number and zip code and call verify_account first.",
102
+ );
103
+
104
+ /** The verified account, or the refusal above. */
105
+ export function verifiedAccount(desk: DeepReadonly<Desk>): Account | ToolFailure {
106
+ if (desk.verified === undefined) return NOT_VERIFIED;
107
+ const account = ACCOUNTS.find((one) => one.number === desk.verified?.number);
108
+ return account ?? NOT_VERIFIED;
109
+ }
110
+
111
+ // ─── The personas ────────────────────────────────────────────────────────────
112
+
113
+ /** Who answers the phone. No tools of its own: `tools/verify_account.ts` is everyone's. */
114
+ export const triage: PersonaDef = persona({
115
+ name: "triage",
116
+ description: "Answers the phone, verifies the caller and works out which desk they need",
117
+ systemPrompt: [
118
+ "You are the front desk. Find out whether the caller has a BILLING question",
119
+ "(invoices, payments, refunds) or a SUPPORT problem (their line, their equipment),",
120
+ "ask for their account number and zip code, and verify them. verify_account",
121
+ "hands the caller to the right desk for you — do not call handoff as well.",
122
+ "If someone says their service is down, they may go straight to support",
123
+ "without verifying: hand off, and support will verify them.",
124
+ ].join(" "),
125
+ });
126
+
127
+ export const billing = persona({
128
+ name: "billing",
129
+ description: "Invoices, payments and refunds for a verified caller",
130
+ systemPrompt: [
131
+ "You are the billing desk. Speak about invoices, payments and refunds only.",
132
+ "Read amounts back before acting on them. A refund is final: confirm the",
133
+ "invoice with the caller before issuing one. If the caller turns out to have a",
134
+ "line or equipment problem, hand them to support.",
135
+ ].join(" "),
136
+ tools: {
137
+ lookup_invoice: deskSlot.tool({
138
+ description: "List the caller's invoices, or one invoice by id.",
139
+ inputSchema: z.object({
140
+ invoiceId: z.string().optional().describe("One invoice; omit to list all of them."),
141
+ }),
142
+ execute({ invoiceId }, desk) {
143
+ const account = verifiedAccount(desk);
144
+ if ("error" in account) return account;
145
+ const invoices =
146
+ invoiceId === undefined
147
+ ? account.invoices
148
+ : account.invoices.filter((one) => one.id === invoiceId);
149
+ if (invoices.length === 0) return toolFailure(`No invoice ${invoiceId} on this account.`);
150
+ return {
151
+ invoices: invoices.map((one) => ({
152
+ ...one,
153
+ status: desk.refunded.includes(one.id) ? "refunded" : one.status,
154
+ })),
155
+ };
156
+ },
157
+ }),
158
+ issue_refund: deskSlot.updateTool({
159
+ description:
160
+ "Refund one invoice in full. Only after the caller has confirmed the invoice id and amount.",
161
+ inputSchema: z.object({ invoiceId: z.string() }),
162
+ execute({ invoiceId }, desk) {
163
+ const account = verifiedAccount(desk);
164
+ if ("error" in account) return account;
165
+ const invoice = account.invoices.find((one) => one.id === invoiceId);
166
+ if (!invoice) return toolFailure(`No invoice ${invoiceId} on this account.`);
167
+ if (invoice.status === "refunded" || desk.refunded.includes(invoiceId)) {
168
+ return toolFailure(`${invoiceId} has already been refunded.`);
169
+ }
170
+ desk.refunded.push(invoiceId);
171
+ return { refunded: invoiceId, amount: invoice.amount };
172
+ },
173
+ }),
174
+ },
175
+ // The two model knobs a persona may set: billing reads numbers back, so it
176
+ // runs cooler than the front desk.
177
+ temperature: 0.2,
178
+ });
179
+
180
+ export const support = persona({
181
+ name: "support",
182
+ description: "Line and equipment faults: diagnostics and technician visits",
183
+ systemPrompt: [
184
+ "You are technical support. Diagnose the line before proposing anything, and",
185
+ "book a technician only when the diagnostic says the fault is on our side.",
186
+ "If the caller wants to talk about a bill instead, hand them to billing.",
187
+ ].join(" "),
188
+ tools: {
189
+ run_diagnostic: deskSlot.tool({
190
+ description: "Test the caller's line and report what it finds.",
191
+ inputSchema: z.object({}),
192
+ execute(_args, desk) {
193
+ const account = verifiedAccount(desk);
194
+ if ("error" in account) return account;
195
+ return {
196
+ line: account.line,
197
+ needsTechnician: account.line !== "healthy",
198
+ };
199
+ },
200
+ }),
201
+ schedule_technician: deskSlot.updateTool({
202
+ description: "Book a technician visit. Only after run_diagnostic reported a fault.",
203
+ inputSchema: z.object({
204
+ day: z.string().describe("The day, as the caller said it."),
205
+ window: z.enum(["morning", "afternoon"]),
206
+ }),
207
+ execute({ day, window }, desk) {
208
+ const account = verifiedAccount(desk);
209
+ if ("error" in account) return account;
210
+ if (account.line === "healthy") {
211
+ return toolFailure(
212
+ "The diagnostic found no fault; there is nothing to send a technician for.",
213
+ );
214
+ }
215
+ desk.appointment = { day, window };
216
+ return { booked: desk.appointment };
217
+ },
218
+ }),
219
+ },
220
+ });
221
+
222
+ /**
223
+ * The roster. The FIRST entry answers the phone; the rest are who it can hand
224
+ * the caller to, and each other. `agent.ts` declares it, every tool that hands
225
+ * off imports it, and `agent.test.ts` reads who is speaking through it.
226
+ */
227
+ export const desk: Personas = personas([triage, billing, support]);
228
+
229
+ /** A tool the front desk itself carries, for a spec to reach `tool()` beside the slot forms. */
230
+ export const whichDesk = tool({
231
+ description: "Which desk is speaking right now.",
232
+ inputSchema: z.object({}),
233
+ execute: (_args, ctx) => ({ persona: desk.active(ctx).name }),
234
+ });
@@ -0,0 +1,13 @@
1
+ You are the phone line for Northwind Internet. One call may pass between the
2
+ front desk, billing and technical support; the caller hears one conversation,
3
+ so never announce a "transfer", never make them repeat what they already said,
4
+ and pick up exactly where the previous desk left off.
5
+
6
+ Rules that hold at every desk:
7
+
8
+ - Never discuss an account's details until verify_account has confirmed the
9
+ caller. Support may diagnose a line before verifying; billing may not open an
10
+ invoice before it.
11
+ - Read every amount and every invoice id back before acting on it.
12
+ - When a request belongs to another desk, hand the caller over rather than
13
+ guessing at an answer, and say one short sentence about who is taking over.
@@ -0,0 +1,41 @@
1
+ import type { HandoffResult } from "@alexkroman1/aai";
2
+ import { toolFailure } from "@alexkroman1/aai/utils";
3
+ import { z } from "zod";
4
+ import { desk, deskSlot, findAccount } from "../shared.ts";
5
+
6
+ /**
7
+ * Verify the caller, and hand them to the desk they asked for in the SAME call.
8
+ *
9
+ * This is the author-routed handoff: the tool IS the decision. Once the caller
10
+ * is verified there is nothing left for triage to decide, so making the model
11
+ * call `handoff` as a second step would be a round trip spent re-deriving what
12
+ * this body already knows. `desk.handoff` writes the persona slot, and the
13
+ * returned `instruction` tells the model who it is from the next step on — the
14
+ * pipeline re-reads the prompt and the tool set per step, so the same turn
15
+ * continues as billing or support.
16
+ *
17
+ * A file under `tools/` rather than a tool on the `triage` persona, because
18
+ * every desk needs it: support verifies a caller who went straight there.
19
+ */
20
+ export default deskSlot.updateTool({
21
+ description:
22
+ "Verify the caller by account number and zip code, then hand them to the desk they need. " +
23
+ "Call this ONCE the caller has given both; it moves them to billing or support itself.",
24
+ inputSchema: z.object({
25
+ accountNumber: z.string().describe("Digits only, as the caller said them."),
26
+ zip: z.string().describe("Five digits."),
27
+ needs: z.enum(["billing", "support"]).describe("Which desk the caller's question is for."),
28
+ }),
29
+ execute({ accountNumber, zip, needs }, draft, ctx): HandoffResult | { error: string } {
30
+ const account = findAccount(accountNumber.replaceAll(/\D/g, ""), zip.trim());
31
+ if (!account) {
32
+ return toolFailure(
33
+ "No account matches that number and zip code. Ask the caller to repeat them, one at a time.",
34
+ );
35
+ }
36
+ draft.verified = { number: account.number, name: account.name };
37
+ return desk.handoff(ctx, needs, {
38
+ note: `${account.name} is verified (account ${account.number}) and asked for ${needs}.`,
39
+ });
40
+ },
41
+ });
@@ -1,8 +1,7 @@
1
1
  /** The def a DEPLOYED agent runs: authored, plus what `tools/` and the prompt add. */
2
2
  import agentDef from "virtual:aai/agent";
3
- import type { ToolContext } from "@alexkroman1/aai";
3
+ import type { SessionEvent, ToolContext } from "@alexkroman1/aai";
4
4
  import { isToolFailure } from "@alexkroman1/aai";
5
- import type { SessionEvent } from "@alexkroman1/aai/protocol";
6
5
  import {
7
6
  createToolContext,
8
7
  expectDialogOk,
@@ -21,9 +21,8 @@
21
21
  */
22
22
 
23
23
  import agentDef from "virtual:aai/agent";
24
- import type { InferToolInput, ToolContext } from "@alexkroman1/aai";
24
+ import type { InferToolInput, SessionEvent, ToolContext } from "@alexkroman1/aai";
25
25
  import { isToolFailure, resolveOne } from "@alexkroman1/aai";
26
- import type { SessionEvent } from "@alexkroman1/aai/protocol";
27
26
  import { createToolContext, expectDialogOk, toolRunner } from "@alexkroman1/aai/testing";
28
27
  import { describe, expect, test } from "vitest";
29
28
  import { validateCard } from "./card.ts";
@@ -127,10 +127,9 @@ describe("medication-safety-agent template", () => {
127
127
  const builtins = expectDeployable(agentDef).builtinTools ?? [];
128
128
 
129
129
  // Asserted on the CONFIG rather than the def because that is what a deploy
130
- // ships, and because `DEFAULT_BUILTIN_TOOLS` is empty: a builtin is
131
- // something an agent asks for, never something it has to notice and switch
132
- // off. So a dropped entry is not a quieter Dr. Sage — it is the same one
133
- // with a prompt rule addressed to nothing. Adding builtins beside these
130
+ // ships, and because setting `builtinTools` REPLACES the default: nothing
131
+ // but `think` comes back on its own. So a dropped entry is not a quieter
132
+ // Dr. Sage — it is the same one with a prompt rule addressed to nothing. Adding builtins beside these
134
133
  // three is an ordinary edit; losing one is the regression.
135
134
  //
136
135
  // `run_code` is the arithmetic rule's only mechanism (a BMI or a
@@ -1,6 +1,6 @@
1
1
  /** The def a DEPLOYED agent runs: authored, plus what `tools/` declares. */
2
2
  import agentDef from "virtual:aai/agent";
3
- import type { SessionEvent } from "@alexkroman1/aai/protocol";
3
+ import type { SessionEvent } from "@alexkroman1/aai";
4
4
  // An EVAL: does the order-taker actually take the order?
5
5
  //
6
6
  // `agent.test.ts` drives the six tools directly, which settles what each one
@@ -13,7 +13,14 @@ import type { SessionEvent } from "@alexkroman1/aai/protocol";
13
13
  // SCRIPTED model (its `stubReply`), which still boots this agent, still
14
14
  // resolves `tools/`, and still executes the tool a script names — so a stub run
15
15
  // proves the wiring and proves nothing about what the agent chose.
16
- import { lastStateIn, statesIn, toolNames, toolResultIn } from "@alexkroman1/aai-runtime/eval";
16
+ import {
17
+ lastStateIn,
18
+ lastToolResultIn,
19
+ statesIn,
20
+ toolNames,
21
+ toolResultIn,
22
+ } from "@alexkroman1/aai-runtime/eval";
23
+ import { evalSimulation } from "@alexkroman1/aai-runtime/eval/simulate";
17
24
  import { describeEval } from "@alexkroman1/aai-runtime/eval/vitest";
18
25
  import { expect } from "vitest";
19
26
  import { z } from "zod";
@@ -158,4 +165,63 @@ describeEval(agentDef, (test) => {
158
165
  },
159
166
  { stubReply: [{ tool: "place_order" }, "There's nothing in your order yet."] },
160
167
  );
168
+
169
+ test(
170
+ "a simulated caller orders a pizza and gets it placed",
171
+ async ({ session, mode }) => {
172
+ // Every case above is one line the test author wrote. A real order is a
173
+ // few turns the CALLER steers: they name the pizza, maybe forget the
174
+ // crust, and say when they are done. A second model plays that caller,
175
+ // so what is under test is whether the order survives a conversation
176
+ // nobody scripted — the cart in the slot, across however many turns it
177
+ // took. Keyless, the caller and the judge are scripted too, and the case
178
+ // proves the loop is wired and nothing else.
179
+ const { simulate, judge } = evalSimulation({
180
+ agent: agentDef,
181
+ mode,
182
+ target: session,
183
+ stubCaller: [
184
+ "Hi, can I get a large pepperoni pizza, regular crust?",
185
+ "That's everything, please place the order.",
186
+ { tool: "end_call", args: { reason: "order placed" } },
187
+ ],
188
+ });
189
+ const call = await simulate({
190
+ persona: "a hungry customer calling a pizza shop, who answers in short sentences",
191
+ goal:
192
+ "order exactly one large pepperoni pizza on regular crust, then have the order " +
193
+ "placed and hear the order number",
194
+ });
195
+
196
+ expect(call.endedBy, call.transcript()).toBe("caller");
197
+ // Deterministic first: the pizza the caller wanted went into the cart,
198
+ // and the order that was placed had it in it. `place_order` resets the
199
+ // cart it read, so its RESULT is where the placed order is on record.
200
+ const calls = call.metrics.toolCalls;
201
+ const added = calls.filter((c) => c.name === "add_pizza");
202
+ expect(added.length, call.transcript()).toBeGreaterThan(0);
203
+ expect(added.at(-1)?.args).toMatchObject({ size: "large" });
204
+ const placed = z.object({ orderNumber: z.number(), pizzas: z.number(), total: z.string() });
205
+ expect(lastToolResultIn(calls, "place_order", placed).pizzas).toBe(1);
206
+
207
+ // What the tool results cannot show is what the caller HEARD. The prompt
208
+ // says every price comes from a tool and every change is confirmed.
209
+ const verdict = await judge(call, [
210
+ "The agent confirmed the pizza it added (size and toppings) back to the caller.",
211
+ "After placing the order, the agent told the caller an order number.",
212
+ ]);
213
+ expect(verdict.pass, verdict.explain()).toBe(true);
214
+ },
215
+ {
216
+ stubReply: [
217
+ {
218
+ tool: "add_pizza",
219
+ args: { size: "large", crust: "regular", toppings: ["pepperoni"], quantity: 1 },
220
+ },
221
+ "Added a large pepperoni on regular crust. Anything else?",
222
+ { tool: "place_order" },
223
+ "Your order is placed. It should be ready in about twenty minutes.",
224
+ ],
225
+ },
226
+ );
161
227
  });
@@ -0,0 +1,74 @@
1
+ // An EVAL: does Field Notes write down what was dictated — once, in the
2
+ // caller's words — and read it back when asked? Run it with `aai eval`.
3
+ //
4
+ // `agent.test.ts` settles what the two tools do with the arguments they are
5
+ // handed. What only a model can settle is whether a held turn becomes ONE
6
+ // `save_note` call carrying the whole note, rather than a reply to its first
7
+ // half. Each `session.say()` here is one press of the button: the harness
8
+ // frames it with the same `user_turn_start` / `user_turn_commit` pair the
9
+ // page's `usePushToTalk()` sends, because a `turnDetection: "manual"` agent
10
+ // answers nothing that was not released.
11
+ //
12
+ // Without a provider key every case runs against a SCRIPTED model (its
13
+ // `stubReply`): the real session, the real slot, the real tools, a fake reply.
14
+ // That proves the wiring and nothing about the choice.
15
+
16
+ /**
17
+ * The def a DEPLOYED agent runs: authored, plus `tools/` and `system-prompt.md`
18
+ * — the prompt is resolved by the build, so an eval driving `agent.ts` alone
19
+ * would measure an agent on the framework default prompt.
20
+ */
21
+ import agentDef from "virtual:aai/agent";
22
+ import { expectCalled, lastStateIn, toolNames } from "@alexkroman1/aai-runtime/eval";
23
+ import { describeEval } from "@alexkroman1/aai-runtime/eval/vitest";
24
+ import { expect } from "vitest";
25
+ import { z } from "zod";
26
+
27
+ /** The notebook as the PAGE has it: the last `syncState` frame pushed. */
28
+ const Projected = z.object({ notes: z.array(z.object({ id: z.number(), text: z.string() })) });
29
+
30
+ describeEval(agentDef, (test) => {
31
+ test(
32
+ "a dictated note is saved once, in the caller's words",
33
+ async ({ session }) => {
34
+ const turn = await session.say(
35
+ "Unit four, the window seal in the kitchen is cracked and needs replacing before winter.",
36
+ );
37
+ expectCalled(turn, "save_note");
38
+ // One note, one call: the whole press is one thought.
39
+ expect(toolNames(turn.toolCalls).filter((name) => name === "save_note")).toHaveLength(1);
40
+ const notes = lastStateIn(turn.events, Projected)?.notes ?? [];
41
+ expect(notes).toHaveLength(1);
42
+ expect(notes[0]?.text.toLowerCase()).toContain("window seal");
43
+ },
44
+ {
45
+ stubReply: [
46
+ {
47
+ tool: "save_note",
48
+ args: {
49
+ text: "Unit four, the window seal in the kitchen is cracked and needs replacing before winter.",
50
+ },
51
+ },
52
+ "Got it, note one.",
53
+ ],
54
+ },
55
+ );
56
+
57
+ test(
58
+ "notes survive to the next press and are read back on request",
59
+ async ({ session }) => {
60
+ await session.say("Boiler in the basement reads one point two bar.");
61
+ const turn = await session.say("What have I got so far?");
62
+ expectCalled(turn, "list_notes");
63
+ expect(turn.text.toLowerCase()).toContain("boiler");
64
+ },
65
+ {
66
+ stubReply: [
67
+ { tool: "save_note", args: { text: "Boiler in the basement reads one point two bar." } },
68
+ "Saved.",
69
+ { tool: "list_notes", args: {} },
70
+ "One note: the boiler in the basement reads one point two bar.",
71
+ ],
72
+ },
73
+ );
74
+ });