@alexkroman1/aai-cli 0.14.2 → 0.14.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{_dev-server-Cy-Mmetk.mjs → _dev-server-BVADkK1M.mjs} +12 -2
- package/dist/_dev-vite-config.d.ts +7 -1
- package/dist/cli.mjs +2 -2
- package/dist/{console-B318NbnN.mjs → console-tRZbtiDe.mjs} +1 -1
- package/dist/{dev-CWCsHFBX.mjs → dev-CsdCGy8U.mjs} +1 -1
- package/dist/scaffold/package.json +4 -4
- package/dist/templates/outbound-call-agent/agent.eval.test.ts +136 -0
- package/dist/templates/outbound-call-agent/agent.test.ts +508 -0
- package/dist/templates/outbound-call-agent/agent.ts +130 -0
- package/dist/templates/outbound-call-agent/api-types.ts +48 -0
- package/dist/templates/outbound-call-agent/api.ts +122 -0
- package/dist/templates/outbound-call-agent/call-params.ts +109 -0
- package/dist/templates/outbound-call-agent/client.tsx +407 -0
- package/dist/templates/outbound-call-agent/live-calls.ts +80 -0
- package/dist/templates/outbound-call-agent/shared.ts +44 -0
- package/dist/templates/outbound-call-agent/system-prompt.md +25 -0
- package/dist/templates/outbound-call-agent/tools/end_call.ts +30 -0
- package/dist/templates/outbound-call-agent/tools/press_keys.ts +38 -0
- package/dist/templates/outbound-call-agent/workflows/call.ts +290 -0
- package/dist/templates/outbound-call-agent/workflows/tokens.ts +16 -0
- package/package.json +4 -4
|
@@ -0,0 +1,508 @@
|
|
|
1
|
+
// Copyright 2026 the AAI authors. MIT license.
|
|
2
|
+
/// <reference types="vite/client" />
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Specs for the outbound caller, in the order a call travels:
|
|
6
|
+
*
|
|
7
|
+
* - **The API** — auth, validation, and that a call is one run keyed by its
|
|
8
|
+
* id, against a stubbed `ctx.workflows`.
|
|
9
|
+
* - **The brief** — that a call's parameters round-trip, and that a session
|
|
10
|
+
* whose parameters were not signed by this app is refused before it starts.
|
|
11
|
+
* - **The session** — the live transcript, `press_keys`, `end_call`, and the hand-over of
|
|
12
|
+
* the transcript to the run as the session ends.
|
|
13
|
+
* - **The run, durably** — `callFlow` on the real replay engine
|
|
14
|
+
* (`runWorkflow`) against a stubbed Twilio and model: it suspends while the
|
|
15
|
+
* phone rings and while the call is talked, resumes on the session's signal
|
|
16
|
+
* without dialling twice, and turns every way a call can go into a record.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import agentDef from "virtual:aai/agent";
|
|
20
|
+
import type { RouteContext, RouteRequest } from "@alexkroman1/aai";
|
|
21
|
+
import { sentDtmfCalls } from "@alexkroman1/aai/experimental";
|
|
22
|
+
import {
|
|
23
|
+
createRunSnapshot,
|
|
24
|
+
createToolContext,
|
|
25
|
+
endSessionCalls,
|
|
26
|
+
type RunWorkflowOptions,
|
|
27
|
+
runWorkflow,
|
|
28
|
+
stubGatewayRoute,
|
|
29
|
+
stubPlaceCall,
|
|
30
|
+
toolRunner,
|
|
31
|
+
} from "@alexkroman1/aai-runtime/testing";
|
|
32
|
+
import { installStubWorkflows } from "@alexkroman1/aai-runtime/testing/vitest";
|
|
33
|
+
import { afterEach, beforeEach, describe, expect, onTestFinished, test, vi } from "vitest";
|
|
34
|
+
import { createCall, getCall, listCalls, newCallId } from "./api.ts";
|
|
35
|
+
import type { CallRecord } from "./api-types.ts";
|
|
36
|
+
import { CHUNK_CHARS, readCall, signCall } from "./call-params.ts";
|
|
37
|
+
import { closeCall, liveCall, openCall, recordTurn } from "./live-calls.ts";
|
|
38
|
+
import { call } from "./shared.ts";
|
|
39
|
+
import { type CallEnded, type CallInput, MAX_RING_POLLS } from "./workflows/call.ts";
|
|
40
|
+
import { callEndedToken } from "./workflows/tokens.ts";
|
|
41
|
+
|
|
42
|
+
const SECRET = "test-calls-key";
|
|
43
|
+
const PROMPT =
|
|
44
|
+
"Call Maria for Mission Dental to confirm her cleaning tomorrow at 2:30pm. " +
|
|
45
|
+
"If she needs to reschedule, offer Thursday at 10am or Friday at 4pm.";
|
|
46
|
+
|
|
47
|
+
const run = toolRunner(agentDef);
|
|
48
|
+
|
|
49
|
+
/** A request to one of the routes, authorized unless the case says otherwise. */
|
|
50
|
+
function request(over: Partial<RouteRequest> = {}): RouteRequest {
|
|
51
|
+
return {
|
|
52
|
+
method: "GET",
|
|
53
|
+
path: "/v1/calls",
|
|
54
|
+
params: {},
|
|
55
|
+
query: {},
|
|
56
|
+
headers: { authorization: SECRET },
|
|
57
|
+
body: undefined,
|
|
58
|
+
...over,
|
|
59
|
+
} as RouteRequest;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** A route context over a stubbed workflow client. */
|
|
63
|
+
function routeContext(
|
|
64
|
+
workflows = installStubWorkflows({ names: ["call"] }),
|
|
65
|
+
env: Record<string, string> = { CALLS_API_KEY: SECRET },
|
|
66
|
+
): RouteContext {
|
|
67
|
+
return {
|
|
68
|
+
env,
|
|
69
|
+
workflows,
|
|
70
|
+
clientTranscript: vi.fn(),
|
|
71
|
+
speech: () => undefined,
|
|
72
|
+
signal: new AbortController().signal,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** What a thrown `routeError` carries, without naming its class. */
|
|
77
|
+
async function refusal(promise: unknown): Promise<{ status: number; message: string }> {
|
|
78
|
+
try {
|
|
79
|
+
await promise;
|
|
80
|
+
} catch (err: unknown) {
|
|
81
|
+
return err as { status: number; message: string };
|
|
82
|
+
}
|
|
83
|
+
throw new Error("expected the route to refuse");
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
describe("the agent", () => {
|
|
87
|
+
test("answers Twilio calls and declares the call workflow and its routes", () => {
|
|
88
|
+
expect(agentDef.telephony).toEqual(["twilio"]);
|
|
89
|
+
expect(Object.keys(agentDef.workflows ?? {})).toContain("call");
|
|
90
|
+
expect(Object.keys(agentDef.routes ?? {})).toEqual(
|
|
91
|
+
expect.arrayContaining(["POST /v1/calls", "GET /v1/calls", "GET /v1/calls/:id"]),
|
|
92
|
+
);
|
|
93
|
+
// An outbound call: the person who answers speaks first.
|
|
94
|
+
expect(agentDef.greeting).toBe("");
|
|
95
|
+
});
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
describe("POST /v1/calls", () => {
|
|
99
|
+
const body = {
|
|
100
|
+
phone_number: "+14155550132",
|
|
101
|
+
prompt: PROMPT,
|
|
102
|
+
webhook_url: "https://example.com/hooks/calls",
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
test("starts one run, keyed by the call id it answers with", async () => {
|
|
106
|
+
const workflows = installStubWorkflows({ names: ["call"] });
|
|
107
|
+
const answer = (await createCall(
|
|
108
|
+
request({ method: "POST", body }),
|
|
109
|
+
routeContext(workflows),
|
|
110
|
+
)) as {
|
|
111
|
+
status: number;
|
|
112
|
+
body: CallRecord;
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
expect(answer.status).toBe(201);
|
|
116
|
+
expect(answer.body).toMatchObject({
|
|
117
|
+
status: "queued",
|
|
118
|
+
phone_number: body.phone_number,
|
|
119
|
+
transcript: [],
|
|
120
|
+
});
|
|
121
|
+
expect(answer.body.id).toMatch(/^call_[0-9a-f]{16}$/);
|
|
122
|
+
expect(workflows.start).toHaveBeenCalledWith(
|
|
123
|
+
call,
|
|
124
|
+
expect.objectContaining({ ...body, id: answer.body.id }),
|
|
125
|
+
{ key: answer.body.id, label: body.phone_number },
|
|
126
|
+
);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
test("accepts `Bearer <key>` as well as the bare key", async () => {
|
|
130
|
+
const ctx = routeContext();
|
|
131
|
+
await createCall(
|
|
132
|
+
request({ method: "POST", body, headers: { authorization: `Bearer ${SECRET}` } }),
|
|
133
|
+
ctx,
|
|
134
|
+
);
|
|
135
|
+
expect(ctx.workflows.start).toHaveBeenCalledOnce();
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
test("refuses a wrong key, and is off entirely without CALLS_API_KEY", async () => {
|
|
139
|
+
const ctx = routeContext();
|
|
140
|
+
expect(
|
|
141
|
+
await refusal(
|
|
142
|
+
createCall(request({ method: "POST", body, headers: { authorization: "nope" } }), ctx),
|
|
143
|
+
),
|
|
144
|
+
).toMatchObject({ status: 401 });
|
|
145
|
+
expect(
|
|
146
|
+
await refusal(createCall(request({ method: "POST", body }), routeContext(undefined, {}))),
|
|
147
|
+
).toMatchObject({ status: 503, message: expect.stringMatching(/CALLS_API_KEY/) });
|
|
148
|
+
expect(ctx.workflows.start).not.toHaveBeenCalled();
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
test("refuses a number that is not E.164 and a missing prompt, saying which", async () => {
|
|
152
|
+
const ctx = routeContext();
|
|
153
|
+
const refused = await refusal(
|
|
154
|
+
createCall(
|
|
155
|
+
request({ method: "POST", body: { phone_number: "415-555-0132", prompt: " " } }),
|
|
156
|
+
ctx,
|
|
157
|
+
),
|
|
158
|
+
);
|
|
159
|
+
expect(refused.status).toBe(400);
|
|
160
|
+
expect(refused.message).toMatch(/E\.164/);
|
|
161
|
+
expect(refused.message).toMatch(/prompt is required/);
|
|
162
|
+
expect(ctx.workflows.start).not.toHaveBeenCalled();
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
test("mints a distinct id per call", () => {
|
|
166
|
+
expect(new Set(Array.from({ length: 50 }, newCallId)).size).toBe(50);
|
|
167
|
+
});
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
describe("GET /v1/calls/:id and GET /v1/calls", () => {
|
|
171
|
+
afterEach(() => {
|
|
172
|
+
closeCall("s_live");
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
test("a finished call is the run's output", async () => {
|
|
176
|
+
const record: CallRecord = {
|
|
177
|
+
id: "call_done",
|
|
178
|
+
status: "completed",
|
|
179
|
+
outcome: "answered",
|
|
180
|
+
phone_number: "+14155550132",
|
|
181
|
+
created_at: 1,
|
|
182
|
+
duration_seconds: 74,
|
|
183
|
+
summary: "Maria rebooked for Thursday at 10am.",
|
|
184
|
+
transcript: [{ role: "agent", text: "Hi, is this Maria?" }],
|
|
185
|
+
};
|
|
186
|
+
const workflows = installStubWorkflows({
|
|
187
|
+
runs: [
|
|
188
|
+
createRunSnapshot({
|
|
189
|
+
workflow: "call",
|
|
190
|
+
key: "call_done",
|
|
191
|
+
status: "completed",
|
|
192
|
+
output: record,
|
|
193
|
+
}),
|
|
194
|
+
],
|
|
195
|
+
});
|
|
196
|
+
const ctx = routeContext(workflows);
|
|
197
|
+
expect(await getCall(request({ params: { id: "call_done" } }), ctx)).toEqual(record);
|
|
198
|
+
expect(workflows.find).toHaveBeenCalledWith(call, "call_done", { limit: 1 });
|
|
199
|
+
expect(await listCalls(request(), ctx)).toEqual({ calls: [record] });
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
test("a call being talked shows its lines so far", async () => {
|
|
203
|
+
const workflows = installStubWorkflows({
|
|
204
|
+
runs: [createRunSnapshot({ workflow: "call", key: "call_live", status: "running" })],
|
|
205
|
+
});
|
|
206
|
+
openCall("s_live", "call_live", 0);
|
|
207
|
+
recordTurn("s_live", "callee", "Hello?");
|
|
208
|
+
recordTurn("s_live", "agent", "Hi, is this Maria?");
|
|
209
|
+
|
|
210
|
+
expect(
|
|
211
|
+
await getCall(request({ params: { id: "call_live" } }), routeContext(workflows)),
|
|
212
|
+
).toMatchObject({
|
|
213
|
+
id: "call_live",
|
|
214
|
+
status: "in-progress",
|
|
215
|
+
transcript: [
|
|
216
|
+
{ role: "callee", text: "Hello?" },
|
|
217
|
+
{ role: "agent", text: "Hi, is this Maria?" },
|
|
218
|
+
],
|
|
219
|
+
});
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
test("a run that failed says why; an unknown id is a 404", async () => {
|
|
223
|
+
const failed = installStubWorkflows({
|
|
224
|
+
runs: [
|
|
225
|
+
createRunSnapshot({ workflow: "call", key: "call_bad", status: "failed", error: "boom" }),
|
|
226
|
+
],
|
|
227
|
+
});
|
|
228
|
+
expect(
|
|
229
|
+
await getCall(request({ params: { id: "call_bad" } }), routeContext(failed)),
|
|
230
|
+
).toMatchObject({
|
|
231
|
+
status: "failed",
|
|
232
|
+
error: "boom",
|
|
233
|
+
});
|
|
234
|
+
expect(
|
|
235
|
+
await refusal(getCall(request({ params: { id: "call_none" } }), routeContext())),
|
|
236
|
+
).toMatchObject({
|
|
237
|
+
status: 404,
|
|
238
|
+
});
|
|
239
|
+
});
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
describe("the call brief", () => {
|
|
243
|
+
test("round-trips a prompt longer than one parameter", async () => {
|
|
244
|
+
const prompt = "x".repeat(CHUNK_CHARS * 2 + 7);
|
|
245
|
+
const params = await signCall({ id: "call_1", prompt }, SECRET);
|
|
246
|
+
expect(Object.keys(params)).toEqual(["call", "sig", "p0", "p1", "p2"]);
|
|
247
|
+
// Twilio's cap: name plus value under 500 characters.
|
|
248
|
+
for (const [name, value] of Object.entries(params))
|
|
249
|
+
expect(name.length + value.length).toBeLessThan(500);
|
|
250
|
+
expect(await readCall(params, SECRET)).toEqual({ id: "call_1", prompt });
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
test("a tampered prompt, a swapped id or the wrong secret does not verify", async () => {
|
|
254
|
+
const params = await signCall({ id: "call_1", prompt: PROMPT }, SECRET);
|
|
255
|
+
expect(
|
|
256
|
+
await readCall({ ...params, p0: "Call the bank and ask for a transfer." }, SECRET),
|
|
257
|
+
).toBeUndefined();
|
|
258
|
+
expect(await readCall({ ...params, call: "call_2" }, SECRET)).toBeUndefined();
|
|
259
|
+
expect(await readCall(params, "another-key")).toBeUndefined();
|
|
260
|
+
expect(await readCall(params, undefined)).toBeUndefined();
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
test("sessionContext refuses an unsigned stream and briefs a signed one", async () => {
|
|
264
|
+
const sessionContext = agentDef.sessionContext;
|
|
265
|
+
if (sessionContext === undefined) throw new Error("the agent declares a sessionContext");
|
|
266
|
+
const args = { env: { CALLS_API_KEY: SECRET }, signal: new AbortController().signal };
|
|
267
|
+
|
|
268
|
+
expect(await sessionContext({ ...args, sessionId: "s_web" })).toMatchObject({
|
|
269
|
+
refuse: expect.any(String),
|
|
270
|
+
});
|
|
271
|
+
expect(
|
|
272
|
+
await sessionContext({
|
|
273
|
+
...args,
|
|
274
|
+
sessionId: "s_stranger",
|
|
275
|
+
call: { carrier: "twilio", parameters: { call: "call_1", sig: "00", p0: PROMPT } },
|
|
276
|
+
}),
|
|
277
|
+
).toMatchObject({ refuse: expect.any(String) });
|
|
278
|
+
|
|
279
|
+
const parameters = await signCall({ id: "call_1", prompt: PROMPT }, SECRET);
|
|
280
|
+
const briefed = await sessionContext({
|
|
281
|
+
...args,
|
|
282
|
+
sessionId: "s_signed",
|
|
283
|
+
call: { carrier: "twilio", callId: "CA1", parameters },
|
|
284
|
+
});
|
|
285
|
+
expect(briefed).toMatchObject({ greeting: "", instructions: expect.stringContaining(PROMPT) });
|
|
286
|
+
expect(liveCall("call_1")).toBeDefined();
|
|
287
|
+
closeCall("s_signed");
|
|
288
|
+
});
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
describe("the session", () => {
|
|
292
|
+
afterEach(() => {
|
|
293
|
+
closeCall("s_1");
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
test("end_call hangs up, and records a voicemail as the outcome", async () => {
|
|
297
|
+
openCall("s_1", "call_vm", 0);
|
|
298
|
+
const ctx = createToolContext({ sessionId: "s_1" });
|
|
299
|
+
const result = await run("end_call", { reached: "voicemail" }, ctx);
|
|
300
|
+
|
|
301
|
+
expect(result).toMatchObject({ ended: expect.any(Boolean) });
|
|
302
|
+
expect(endSessionCalls(ctx)).toHaveLength(1);
|
|
303
|
+
expect(liveCall("call_vm")?.voicemail).toBe(true);
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
test("press_keys plays the keys into the call and writes them into its transcript", async () => {
|
|
307
|
+
openCall("s_1", "call_menu", 0);
|
|
308
|
+
const ctx = createToolContext({ sessionId: "s_1" });
|
|
309
|
+
const result = await run("press_keys", { keys: "2#" }, ctx);
|
|
310
|
+
|
|
311
|
+
expect(result).toMatchObject({ pressed: "2#" });
|
|
312
|
+
expect(sentDtmfCalls(ctx)).toEqual(["2#"]);
|
|
313
|
+
expect(liveCall("call_menu")?.transcript).toEqual([{ role: "agent", text: "[pressed 2#]" }]);
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
test("press_keys refuses a key no phone has, so the model can retry", async () => {
|
|
317
|
+
const ctx = createToolContext({ sessionId: "s_1" });
|
|
318
|
+
await expect(run("press_keys", { keys: "one" }, ctx)).rejects.toThrow(/not a phone key/);
|
|
319
|
+
expect(sentDtmfCalls(ctx)).toEqual([]);
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
test("hands the transcript to the call's run as the session ends", async () => {
|
|
323
|
+
const signal = vi.fn(async () => true);
|
|
324
|
+
const workflows = { ...installStubWorkflows(), signal };
|
|
325
|
+
openCall("s_1", "call_42", Date.now() - 74_000);
|
|
326
|
+
recordTurn("s_1", "callee", "Hello?");
|
|
327
|
+
recordTurn("s_1", "agent", "Hi, is this Maria?");
|
|
328
|
+
|
|
329
|
+
await agentDef.onSessionEnd?.({ sessionId: "s_1", env: {}, workflows, lastEventIndex: 1 });
|
|
330
|
+
|
|
331
|
+
expect(signal).toHaveBeenCalledWith(callEndedToken("call_42"), {
|
|
332
|
+
transcript: [
|
|
333
|
+
{ role: "callee", text: "Hello?" },
|
|
334
|
+
{ role: "agent", text: "Hi, is this Maria?" },
|
|
335
|
+
],
|
|
336
|
+
voicemail: false,
|
|
337
|
+
duration_seconds: 74,
|
|
338
|
+
});
|
|
339
|
+
// Handed over once, and then forgotten.
|
|
340
|
+
expect(liveCall("call_42")).toBeUndefined();
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
test("a session that was never a placed call hands nothing over", async () => {
|
|
344
|
+
const signal = vi.fn(async () => true);
|
|
345
|
+
await agentDef.onSessionEnd?.({
|
|
346
|
+
sessionId: "s_none",
|
|
347
|
+
env: {},
|
|
348
|
+
workflows: { ...installStubWorkflows(), signal },
|
|
349
|
+
lastEventIndex: -1,
|
|
350
|
+
});
|
|
351
|
+
expect(signal).not.toHaveBeenCalled();
|
|
352
|
+
});
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
describe("the run is DURABLE", () => {
|
|
356
|
+
const INPUT: CallInput = {
|
|
357
|
+
id: "call_7Hq2xK9mPz",
|
|
358
|
+
phone_number: "+14155550132",
|
|
359
|
+
prompt: PROMPT,
|
|
360
|
+
webhook_url: "https://example.com/hooks/calls",
|
|
361
|
+
created_at: 1_700_000_000_000,
|
|
362
|
+
};
|
|
363
|
+
const ENDED: CallEnded = {
|
|
364
|
+
transcript: [
|
|
365
|
+
{ role: "agent", text: "Hi, is this Maria? I'm calling from Mission Dental." },
|
|
366
|
+
{ role: "callee", text: "Something came up at work. Anything later this week?" },
|
|
367
|
+
{ role: "agent", text: "I have Thursday at 10am or Friday at 4pm." },
|
|
368
|
+
{ role: "callee", text: "Thursday at 10 works." },
|
|
369
|
+
],
|
|
370
|
+
voicemail: false,
|
|
371
|
+
duration_seconds: 74,
|
|
372
|
+
};
|
|
373
|
+
const SUMMARY = "Maria rebooked for Thursday at 10am.";
|
|
374
|
+
|
|
375
|
+
beforeEach(() => {
|
|
376
|
+
vi.stubEnv("TWILIO_ACCOUNT_SID", "AC123");
|
|
377
|
+
vi.stubEnv("TWILIO_AUTH_TOKEN", "token");
|
|
378
|
+
vi.stubEnv("TWILIO_FROM_NUMBER", "+14155550100");
|
|
379
|
+
vi.stubEnv("CALLER_AGENT_URL", "https://caller.example.com");
|
|
380
|
+
vi.stubEnv("CALLS_API_KEY", SECRET);
|
|
381
|
+
vi.stubEnv("ASSEMBLYAI_API_KEY", "sk-test");
|
|
382
|
+
});
|
|
383
|
+
|
|
384
|
+
/** Twilio, the model and the webhook behind the one published `stepFetch`. */
|
|
385
|
+
function stubWorld(options: Parameters<typeof stubPlaceCall>[0] = {}) {
|
|
386
|
+
const model = stubGatewayRoute(JSON.stringify({ summary: SUMMARY }));
|
|
387
|
+
const webhook = vi.fn((_body: unknown) => ({ status: 204, body: "" }));
|
|
388
|
+
const twilio = stubPlaceCall({
|
|
389
|
+
status: (placed) => (placed.polls === 1 ? "ringing" : "in-progress"),
|
|
390
|
+
...options,
|
|
391
|
+
otherwise: (req) =>
|
|
392
|
+
model.route(req) ??
|
|
393
|
+
webhook(
|
|
394
|
+
JSON.parse(typeof req.body === "string" ? req.body : new TextDecoder().decode(req.body)),
|
|
395
|
+
),
|
|
396
|
+
});
|
|
397
|
+
onTestFinished(() => twilio.restore());
|
|
398
|
+
return { twilio, model: model.calls, webhook };
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function start(options?: RunWorkflowOptions) {
|
|
402
|
+
return runWorkflow(call, INPUT, { name: "call", ...options });
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
test("rings, parks on the call, and resumes on the session's signal into the finished record", async () => {
|
|
406
|
+
const world = stubWorld();
|
|
407
|
+
const handle = await start();
|
|
408
|
+
|
|
409
|
+
// Suspended on the first ring poll, with the dial already journaled.
|
|
410
|
+
expect(handle.status).toBe("running");
|
|
411
|
+
expect(world.twilio.calls).toHaveLength(1);
|
|
412
|
+
const placed = world.twilio.calls[0];
|
|
413
|
+
expect(placed?.to).toBe(INPUT.phone_number);
|
|
414
|
+
expect(placed?.streamUrl).toBe("wss://caller.example.com/phone?carrier=twilio");
|
|
415
|
+
// The answering session can verify the brief it was handed.
|
|
416
|
+
expect(await readCall(placed?.parameters ?? {}, SECRET)).toEqual({
|
|
417
|
+
id: INPUT.id,
|
|
418
|
+
prompt: PROMPT,
|
|
419
|
+
});
|
|
420
|
+
|
|
421
|
+
await handle.advanceSleep(); // ringing
|
|
422
|
+
await handle.advanceSleep(); // answered — now parked on the call
|
|
423
|
+
expect(handle.status).toBe("running");
|
|
424
|
+
|
|
425
|
+
await handle.signal(callEndedToken(INPUT.id), ENDED);
|
|
426
|
+
expect(handle.signalled).toBe(true);
|
|
427
|
+
expect(handle.status).toBe("completed");
|
|
428
|
+
|
|
429
|
+
const expected: CallRecord = {
|
|
430
|
+
id: INPUT.id,
|
|
431
|
+
status: "completed",
|
|
432
|
+
phone_number: INPUT.phone_number,
|
|
433
|
+
created_at: INPUT.created_at,
|
|
434
|
+
outcome: "answered",
|
|
435
|
+
duration_seconds: 74,
|
|
436
|
+
summary: SUMMARY,
|
|
437
|
+
transcript: ENDED.transcript,
|
|
438
|
+
};
|
|
439
|
+
expect(handle.output).toEqual(expected);
|
|
440
|
+
expect(world.webhook).toHaveBeenCalledWith(expected);
|
|
441
|
+
// One dial, one model call, across every suspension.
|
|
442
|
+
expect(world.twilio.calls).toHaveLength(1);
|
|
443
|
+
expect(world.model).toHaveLength(1);
|
|
444
|
+
});
|
|
445
|
+
|
|
446
|
+
test("a worker that dies after dialling resumes without ringing the phone again", async () => {
|
|
447
|
+
const world = stubWorld();
|
|
448
|
+
const handle = await start({ crashAt: "ring-status" });
|
|
449
|
+
await handle.advanceSleep(); // the first ring poll is delivered, and the worker dies in it
|
|
450
|
+
await handle.restart(); // a new worker: the dial is journaled, the poll runs again
|
|
451
|
+
await handle.advanceSleep();
|
|
452
|
+
await handle.signal(callEndedToken(INPUT.id), ENDED);
|
|
453
|
+
|
|
454
|
+
expect(handle.status).toBe("completed");
|
|
455
|
+
expect(world.twilio.calls).toHaveLength(1);
|
|
456
|
+
});
|
|
457
|
+
|
|
458
|
+
test("voicemail is the outcome when the agent said so", async () => {
|
|
459
|
+
stubWorld();
|
|
460
|
+
const handle = await start();
|
|
461
|
+
await handle.advanceSleep();
|
|
462
|
+
await handle.advanceSleep();
|
|
463
|
+
await handle.signal(callEndedToken(INPUT.id), { ...ENDED, voicemail: true });
|
|
464
|
+
expect(handle.output).toMatchObject({ outcome: "voicemail" });
|
|
465
|
+
});
|
|
466
|
+
|
|
467
|
+
test("nobody answering completes as no-answer, with no model call", async () => {
|
|
468
|
+
const world = stubWorld({ status: "no-answer" });
|
|
469
|
+
const handle = await start();
|
|
470
|
+
await handle.advanceSleep();
|
|
471
|
+
|
|
472
|
+
expect(handle.status).toBe("completed");
|
|
473
|
+
expect(handle.output).toMatchObject({ outcome: "no-answer", transcript: [] });
|
|
474
|
+
expect(world.model).toHaveLength(0);
|
|
475
|
+
expect(world.webhook).toHaveBeenCalledOnce();
|
|
476
|
+
});
|
|
477
|
+
|
|
478
|
+
test("a phone that only ever rings gives up after the last poll", async () => {
|
|
479
|
+
stubWorld({ status: "ringing" });
|
|
480
|
+
const handle = await start();
|
|
481
|
+
for (let i = 0; i < MAX_RING_POLLS; i++) await handle.advanceSleep();
|
|
482
|
+
expect(handle.output).toMatchObject({ outcome: "no-answer" });
|
|
483
|
+
});
|
|
484
|
+
|
|
485
|
+
test("a dial Twilio refuses completes as failed, with Twilio's reason", async () => {
|
|
486
|
+
const world = stubWorld({ dial: { status: 400, code: 21_219, message: "unverified" } });
|
|
487
|
+
const handle = await start();
|
|
488
|
+
|
|
489
|
+
expect(handle.status).toBe("completed");
|
|
490
|
+
expect(handle.output).toMatchObject({ outcome: "failed", error: expect.any(String) });
|
|
491
|
+
// Not retried: a refusal asks the same way next time.
|
|
492
|
+
expect(world.twilio.calls).toHaveLength(1);
|
|
493
|
+
});
|
|
494
|
+
|
|
495
|
+
test("a transcript that never arrives closes the window instead of hanging", async () => {
|
|
496
|
+
stubWorld();
|
|
497
|
+
const handle = await start();
|
|
498
|
+
await handle.advanceSleep();
|
|
499
|
+
await handle.advanceSleep();
|
|
500
|
+
await handle.expireWaits();
|
|
501
|
+
|
|
502
|
+
expect(handle.status).toBe("completed");
|
|
503
|
+
expect(handle.output).toMatchObject({
|
|
504
|
+
outcome: "answered",
|
|
505
|
+
error: expect.stringMatching(/transcript/),
|
|
506
|
+
});
|
|
507
|
+
});
|
|
508
|
+
});
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// Copyright 2026 the AAI authors. MIT license.
|
|
2
|
+
/**
|
|
3
|
+
* An agent that MAKES phone calls — behind an HTTP API, with a page to drive
|
|
4
|
+
* it and watch the transcript come back.
|
|
5
|
+
*
|
|
6
|
+
* ```text
|
|
7
|
+
* POST /api/v1/calls ─► run `call` ─► stepPlaceCall ─► Twilio rings the number
|
|
8
|
+
* │ │ answered
|
|
9
|
+
* │ ▼
|
|
10
|
+
* │ WS /phone ─► this agent, in a session:
|
|
11
|
+
* │ sessionContext — verify, read the brief
|
|
12
|
+
* │ events — record each line live
|
|
13
|
+
* │ press_keys — answer a phone menu
|
|
14
|
+
* │ end_call — hang up (voicemail?)
|
|
15
|
+
* ◄──── signal ────── onSessionEnd — hand over the transcript
|
|
16
|
+
* ▼
|
|
17
|
+
* summarize ─► webhook ─► output = the CallRecord GET /api/v1/calls/:id reads
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* One file per concern: `api.ts` (the routes), `shared.ts` + `workflows/call.ts`
|
|
21
|
+
* (the run), `call-params.ts` (what the call carries, signed), `live-calls.ts`
|
|
22
|
+
* (the lines of calls in progress), `client.tsx` (the page).
|
|
23
|
+
*
|
|
24
|
+
* ## Setup
|
|
25
|
+
*
|
|
26
|
+
* | Env | What it is |
|
|
27
|
+
* | --- | --- |
|
|
28
|
+
* | `CALLS_API_KEY` | The `Authorization` the API requires, and the key the call brief is signed with |
|
|
29
|
+
* | `TWILIO_ACCOUNT_SID`, `TWILIO_AUTH_TOKEN` | The Twilio account that dials |
|
|
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
|
+
*
|
|
33
|
+
* Under `aai dev`, run `aai dev --tunnel` and set `CALLER_AGENT_URL` to the
|
|
34
|
+
* tunnel URL it prints — Twilio cannot reach `localhost`.
|
|
35
|
+
*
|
|
36
|
+
* ## The session is a stranger until it proves otherwise
|
|
37
|
+
*
|
|
38
|
+
* `WS /phone` is served to anyone who finds the URL. `sessionContext` reads the
|
|
39
|
+
* signed brief off the call's parameters and REFUSES any stream whose
|
|
40
|
+
* signature does not verify, which hangs up before the greeting or a single
|
|
41
|
+
* model call. A verified call gets its task as `instructions` — appended to
|
|
42
|
+
* `system-prompt.md` for the whole session — and an empty greeting: on an
|
|
43
|
+
* outbound call the person who answers speaks first.
|
|
44
|
+
*/
|
|
45
|
+
|
|
46
|
+
import { agent } from "@alexkroman1/aai";
|
|
47
|
+
import { createCall, getCall, listCalls } from "./api.ts";
|
|
48
|
+
import { readCall } from "./call-params.ts";
|
|
49
|
+
import { closeCall, openCall, recordTurn } from "./live-calls.ts";
|
|
50
|
+
import { call } from "./shared.ts";
|
|
51
|
+
import { callEndedToken } from "./workflows/tokens.ts";
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* How many times `onSessionEnd` offers the transcript before giving up, and how
|
|
55
|
+
* long it waits between offers. A call shorter than one ring poll can end
|
|
56
|
+
* before its run has reached the wait, and `signal()` answers `false` until it
|
|
57
|
+
* has — so the hand-over retries across a little more than one poll.
|
|
58
|
+
*/
|
|
59
|
+
export const HANDOVER_ATTEMPTS = 8;
|
|
60
|
+
export const HANDOVER_RETRY_MS = 2500;
|
|
61
|
+
|
|
62
|
+
/** Make `offer` again after `ms` — a deferral: the timer runs the offer itself. */
|
|
63
|
+
function offerLater(offer: () => Promise<boolean>, ms: number): Promise<boolean> {
|
|
64
|
+
return new Promise((resolve, reject) => {
|
|
65
|
+
setTimeout(() => {
|
|
66
|
+
offer().then(resolve, reject);
|
|
67
|
+
}, ms);
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The task, framed as instructions for this one session. */
|
|
72
|
+
export function briefInstructions(prompt: string): string {
|
|
73
|
+
return `## This call\n\nYou placed this call. Your task, exactly as you were given it:\n\n${prompt}`;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export default agent({
|
|
77
|
+
name: "Outbound Caller",
|
|
78
|
+
description:
|
|
79
|
+
"Places phone calls from an HTTP API, carries out a task on each, and reports the transcript",
|
|
80
|
+
telephony: ["twilio"],
|
|
81
|
+
// The callee says "Hello?" first; the model answers it, with the task in hand.
|
|
82
|
+
greeting: "",
|
|
83
|
+
// The run waits on these; the API starts them. A session never does.
|
|
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
|
+
],
|
|
92
|
+
// Phone audio: give a callee a beat longer to finish a thought.
|
|
93
|
+
turnTaking: { minSilenceMs: 1200 },
|
|
94
|
+
|
|
95
|
+
async sessionContext({ sessionId, call: placed, env }) {
|
|
96
|
+
if (placed === undefined) return { refuse: "this agent only talks on calls it placed" };
|
|
97
|
+
const brief = await readCall(placed.parameters, env.CALLS_API_KEY);
|
|
98
|
+
if (brief === undefined) return { refuse: "unsigned or forged call parameters" };
|
|
99
|
+
openCall(sessionId, brief.id, Date.now());
|
|
100
|
+
return { instructions: briefInstructions(brief.prompt), greeting: "" };
|
|
101
|
+
},
|
|
102
|
+
|
|
103
|
+
events: {
|
|
104
|
+
"userTranscript.committed": (event, ctx) => recordTurn(ctx.sessionId, "callee", event.text),
|
|
105
|
+
"agentTranscript.committed": (event, ctx) => recordTurn(ctx.sessionId, "agent", event.text),
|
|
106
|
+
},
|
|
107
|
+
|
|
108
|
+
async onSessionEnd({ sessionId, workflows }) {
|
|
109
|
+
const ended = closeCall(sessionId);
|
|
110
|
+
if (ended === undefined) return;
|
|
111
|
+
const { id } = ended;
|
|
112
|
+
const payload = {
|
|
113
|
+
transcript: ended.transcript,
|
|
114
|
+
voicemail: ended.voicemail,
|
|
115
|
+
duration_seconds: Math.round((Date.now() - ended.startedAt) / 1000),
|
|
116
|
+
};
|
|
117
|
+
const offer = () => workflows.signal(callEndedToken(id), payload);
|
|
118
|
+
if (await offer()) return;
|
|
119
|
+
for (let attempt = 2; attempt <= HANDOVER_ATTEMPTS; attempt++) {
|
|
120
|
+
if (await offerLater(offer, HANDOVER_RETRY_MS)) return;
|
|
121
|
+
}
|
|
122
|
+
console.warn(`call ${id}: nobody took the transcript; the run will report it missing`);
|
|
123
|
+
},
|
|
124
|
+
|
|
125
|
+
routes: {
|
|
126
|
+
"POST /v1/calls": createCall,
|
|
127
|
+
"GET /v1/calls": listCalls,
|
|
128
|
+
"GET /v1/calls/:id": getCall,
|
|
129
|
+
},
|
|
130
|
+
});
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Copyright 2026 the AAI authors. MIT license.
|
|
2
|
+
/**
|
|
3
|
+
* The shapes `/api/v1/calls` speaks — the one contract the run, the routes,
|
|
4
|
+
* the webhook and the page all agree on.
|
|
5
|
+
*
|
|
6
|
+
* Plain types and nothing else, so `client.tsx` can import them without
|
|
7
|
+
* pulling a line of server code into the browser bundle.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** One line of the conversation. `agent` is this app; `callee` is who picked up. */
|
|
11
|
+
export type TranscriptTurn = { role: "agent" | "callee"; text: string };
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Where a call is.
|
|
15
|
+
*
|
|
16
|
+
* `queued` until the carrier rings, `in-progress` once a session is talking,
|
|
17
|
+
* `completed` when the run has written its result (whatever the outcome), and
|
|
18
|
+
* `failed` when the run itself failed — never for a call nobody answered,
|
|
19
|
+
* which is a `completed` call with `outcome: "no-answer"`.
|
|
20
|
+
*/
|
|
21
|
+
export type CallStatus = "queued" | "ringing" | "in-progress" | "completed" | "failed";
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* How it went, once it is over.
|
|
25
|
+
*
|
|
26
|
+
* `answered` and `voicemail` both reached a session; the agent decides which
|
|
27
|
+
* with `end_call`. The rest are the carrier's word for a call that never
|
|
28
|
+
* connected.
|
|
29
|
+
*/
|
|
30
|
+
export type CallOutcome = "answered" | "voicemail" | "no-answer" | "busy" | "failed" | "canceled";
|
|
31
|
+
|
|
32
|
+
/** What `GET /api/v1/calls/:id` answers, and what the webhook is sent. */
|
|
33
|
+
export type CallRecord = {
|
|
34
|
+
id: string;
|
|
35
|
+
status: CallStatus;
|
|
36
|
+
phone_number: string;
|
|
37
|
+
/** Epoch ms the call was requested. */
|
|
38
|
+
created_at: number;
|
|
39
|
+
outcome?: CallOutcome;
|
|
40
|
+
duration_seconds?: number;
|
|
41
|
+
summary?: string;
|
|
42
|
+
transcript: TranscriptTurn[];
|
|
43
|
+
/** Why a call failed or a dial was refused, in a sentence a person can act on. */
|
|
44
|
+
error?: string;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/** What `GET /api/v1/calls` answers: newest first. */
|
|
48
|
+
export type CallList = { calls: CallRecord[] };
|