@alexkroman1/aai-cli 0.14.1 → 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-restart.d.ts +37 -1
- package/dist/{_dev-server-GoEXEVpA.mjs → _dev-server-BVADkK1M.mjs} +278 -99
- package/dist/_dev-vite-config.d.ts +7 -1
- package/dist/cli.mjs +2 -2
- package/dist/{console-Dxq26Adz.mjs → console-tRZbtiDe.mjs} +1 -1
- package/dist/{dev-BWBDbUEb.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 +5 -4
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// Copyright 2026 the AAI authors. MIT license.
|
|
2
|
+
/**
|
|
3
|
+
* The calls being talked RIGHT NOW, and what has been said on each so far.
|
|
4
|
+
*
|
|
5
|
+
* Two readers need a call's words before the call is over, and neither can
|
|
6
|
+
* reach the session that is speaking them:
|
|
7
|
+
*
|
|
8
|
+
* - `onSessionEnd` hands the transcript to the call's run, and is handed no
|
|
9
|
+
* slots — only the session id.
|
|
10
|
+
* - `GET /api/v1/calls/:id` shows the conversation LIVE, and a route has no
|
|
11
|
+
* session at all.
|
|
12
|
+
*
|
|
13
|
+
* So the session's event handlers write each committed line here, keyed by
|
|
14
|
+
* session id, and both readers look it up. It is per-process memory, which is
|
|
15
|
+
* exactly as long as it needs to live: a call's session, its event handlers
|
|
16
|
+
* and its `onSessionEnd` run in one runtime, and the entry is dropped the
|
|
17
|
+
* moment the transcript has been handed over. A live view served by a
|
|
18
|
+
* DIFFERENT process than the one on the call sees no live lines and shows the
|
|
19
|
+
* run's status instead; the finished transcript is the run's output either
|
|
20
|
+
* way.
|
|
21
|
+
*
|
|
22
|
+
* Bounded twice — lines per call and calls in flight — because it is fed by
|
|
23
|
+
* strangers' speech.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import type { TranscriptTurn } from "./api-types.ts";
|
|
27
|
+
|
|
28
|
+
/** One call in progress. */
|
|
29
|
+
export type LiveCall = {
|
|
30
|
+
id: string;
|
|
31
|
+
startedAt: number;
|
|
32
|
+
transcript: TranscriptTurn[];
|
|
33
|
+
voicemail: boolean;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/** Most lines kept for one call — a ten-minute call is well under this. */
|
|
37
|
+
export const MAX_LIVE_TURNS = 500;
|
|
38
|
+
|
|
39
|
+
/** Most calls held at once; the oldest is dropped past it. */
|
|
40
|
+
export const MAX_LIVE_CALLS = 200;
|
|
41
|
+
|
|
42
|
+
const bySession = new Map<string, LiveCall>();
|
|
43
|
+
|
|
44
|
+
/** Start following the call `sessionId` is talking on. */
|
|
45
|
+
export function openCall(sessionId: string, id: string, now: number): void {
|
|
46
|
+
if (bySession.size >= MAX_LIVE_CALLS) {
|
|
47
|
+
const oldest = bySession.keys().next().value;
|
|
48
|
+
if (oldest !== undefined) bySession.delete(oldest);
|
|
49
|
+
}
|
|
50
|
+
bySession.set(sessionId, { id, startedAt: now, transcript: [], voicemail: false });
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Add one committed line to the session's call. A session with no call is ignored. */
|
|
54
|
+
export function recordTurn(sessionId: string, role: TranscriptTurn["role"], text: string): void {
|
|
55
|
+
const call = bySession.get(sessionId);
|
|
56
|
+
const said = text.trim();
|
|
57
|
+
if (call === undefined || said === "" || call.transcript.length >= MAX_LIVE_TURNS) return;
|
|
58
|
+
call.transcript.push({ role, text: said });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The agent decided it reached an answering machine. */
|
|
62
|
+
export function markVoicemail(sessionId: string): boolean {
|
|
63
|
+
const call = bySession.get(sessionId);
|
|
64
|
+
if (call === undefined) return false;
|
|
65
|
+
call.voicemail = true;
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Stop following the session's call, and hand back what it held. */
|
|
70
|
+
export function closeCall(sessionId: string): LiveCall | undefined {
|
|
71
|
+
const call = bySession.get(sessionId);
|
|
72
|
+
bySession.delete(sessionId);
|
|
73
|
+
return call;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The call `id`, while a session on this process is still talking on it. */
|
|
77
|
+
export function liveCall(id: string): Readonly<LiveCall> | undefined {
|
|
78
|
+
for (const call of bySession.values()) if (call.id === id) return call;
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Copyright 2026 the AAI authors. MIT license.
|
|
2
|
+
/**
|
|
3
|
+
* The call workflow's DECLARATION and the request schema `POST /api/v1/calls`
|
|
4
|
+
* validates against — in a module `agent.ts`, the routes and the specs can all
|
|
5
|
+
* import. The body is `workflows/call.ts`.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { type WorkflowDef, workflow } from "@alexkroman1/aai";
|
|
9
|
+
import { z } from "zod";
|
|
10
|
+
import type { CallRecord } from "./api-types.ts";
|
|
11
|
+
import { MAX_PROMPT_CHARS } from "./call-params.ts";
|
|
12
|
+
import { callFlow } from "./workflows/call.ts";
|
|
13
|
+
|
|
14
|
+
/** An E.164 number: a `+`, a country code, and up to fifteen digits in all. */
|
|
15
|
+
const E164 = /^\+[1-9]\d{6,14}$/;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* What `POST /api/v1/calls` accepts. Field names are snake_case because they
|
|
19
|
+
* are the public API's, exactly as the curl example writes them.
|
|
20
|
+
*/
|
|
21
|
+
export const callRequest = z.object({
|
|
22
|
+
phone_number: z.string().regex(E164, "phone_number must be E.164, like +14155550132"),
|
|
23
|
+
prompt: z
|
|
24
|
+
.string()
|
|
25
|
+
.trim()
|
|
26
|
+
.min(1, "prompt is required")
|
|
27
|
+
.max(MAX_PROMPT_CHARS, `prompt is at most ${MAX_PROMPT_CHARS} characters`),
|
|
28
|
+
webhook_url: z.url({ protocol: /^https?$/ }).optional(),
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
const callInput = callRequest.extend({
|
|
32
|
+
id: z.string().describe("This app's call id — the run is keyed by it"),
|
|
33
|
+
created_at: z.number().describe("Epoch ms the call was requested"),
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* One phone call, start to finish. Annotated so `typeof call` does not depend
|
|
38
|
+
* on the body's own signature (see "ANNOTATE the def" in the workflows guide).
|
|
39
|
+
*/
|
|
40
|
+
export const call: WorkflowDef<typeof callInput, CallRecord> = workflow({
|
|
41
|
+
description: "Place one phone call, follow it to the end, and write up what was said",
|
|
42
|
+
input: callInput,
|
|
43
|
+
run: callFlow,
|
|
44
|
+
});
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
You are an AI assistant placing a phone call on someone's behalf. The task for
|
|
2
|
+
this call is given below under "This call". Carry it out, and nothing else.
|
|
3
|
+
|
|
4
|
+
- The person who answers speaks first. Reply by greeting them, confirming you
|
|
5
|
+
have the right person when the task names one, and saying who you are calling
|
|
6
|
+
for and why — in one or two sentences.
|
|
7
|
+
- If you are asked, say plainly that you are an AI assistant.
|
|
8
|
+
- Offer only the options, times and details the task gives you. Never invent an
|
|
9
|
+
appointment, a price, a policy or a promise. If they ask for something the
|
|
10
|
+
task does not cover, say you will pass the request on.
|
|
11
|
+
- Read times and dates back once when something is agreed, so there is no
|
|
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"`.
|
|
16
|
+
- If an automated phone menu answers ("press 1 for…", "say or enter your
|
|
17
|
+
account number"), listen for the option that leads toward your task and call
|
|
18
|
+
`press_keys` with that key — without saying anything, since the menu is not
|
|
19
|
+
listening for words. Then wait silently for what it says next. Enter numbers
|
|
20
|
+
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.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// Copyright 2026 the AAI authors. MIT license.
|
|
2
|
+
/**
|
|
3
|
+
* Hang up — once the task is done, the callee has said goodbye, or a voicemail
|
|
4
|
+
* message has been left.
|
|
5
|
+
*
|
|
6
|
+
* `endSession` lets the current reply finish speaking first, so the goodbye the
|
|
7
|
+
* model writes alongside this call is heard before the line drops. Saying
|
|
8
|
+
* whether it was VOICEMAIL is the one fact about the call only the agent can
|
|
9
|
+
* judge, so it is recorded here and reported as the call's `outcome`.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { endSession, tool } from "@alexkroman1/aai";
|
|
13
|
+
import { z } from "zod";
|
|
14
|
+
import { markVoicemail } from "../live-calls.ts";
|
|
15
|
+
|
|
16
|
+
export default tool({
|
|
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.",
|
|
20
|
+
inputSchema: z.object({
|
|
21
|
+
reached: z
|
|
22
|
+
.enum(["person", "voicemail"])
|
|
23
|
+
.describe("Who you ended up talking to: a person, or an answering machine / voicemail"),
|
|
24
|
+
}),
|
|
25
|
+
execute({ reached }, ctx) {
|
|
26
|
+
if (reached === "voicemail") markVoicemail(ctx.sessionId);
|
|
27
|
+
const ending = endSession(ctx);
|
|
28
|
+
return { ended: ending, say: "Finish your last sentence; the line closes after it." };
|
|
29
|
+
},
|
|
30
|
+
});
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// Copyright 2026 the AAI authors. MIT license.
|
|
2
|
+
/**
|
|
3
|
+
* Press keys on the phone keypad — how the caller gets through an automated
|
|
4
|
+
* menu ("press 1 for appointments") or types an extension.
|
|
5
|
+
*
|
|
6
|
+
* `sendDtmf` plays each key's tone pair into the call's audio, behind anything
|
|
7
|
+
* the agent is still saying, and the carrier carries it to the menu like the
|
|
8
|
+
* agent's voice. Each press is also written into the call's transcript, so the
|
|
9
|
+
* record shows how the menu was navigated and the summary can say so.
|
|
10
|
+
*
|
|
11
|
+
* A barge-in drops tones not yet played, as it does speech — and a menu talks
|
|
12
|
+
* over everything — so the prompt has the model press keys in a turn that
|
|
13
|
+
* says nothing.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { tool } from "@alexkroman1/aai";
|
|
17
|
+
import { sendDtmf } from "@alexkroman1/aai/experimental";
|
|
18
|
+
import { z } from "zod";
|
|
19
|
+
import { recordTurn } from "../live-calls.ts";
|
|
20
|
+
|
|
21
|
+
export default tool({
|
|
22
|
+
description:
|
|
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.",
|
|
25
|
+
inputSchema: z.object({
|
|
26
|
+
keys: z
|
|
27
|
+
.string()
|
|
28
|
+
.describe(
|
|
29
|
+
"The keys to press, in order: 0-9, * and #. Use w for a half-second pause " +
|
|
30
|
+
"(e.g. '1', '3#', '1234#', '0w2').",
|
|
31
|
+
),
|
|
32
|
+
}),
|
|
33
|
+
execute({ keys }, ctx) {
|
|
34
|
+
if (!sendDtmf(ctx, keys)) return { pressed: null, error: "The call has ended." };
|
|
35
|
+
recordTurn(ctx.sessionId, "agent", `[pressed ${keys}]`);
|
|
36
|
+
return { pressed: keys, next: "Wait silently for the menu to respond." };
|
|
37
|
+
},
|
|
38
|
+
});
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
// Copyright 2026 the AAI authors. MIT license.
|
|
2
|
+
/**
|
|
3
|
+
* The durable half of one phone call: dial, follow it, collect what was said,
|
|
4
|
+
* write it up, and tell whoever asked.
|
|
5
|
+
*
|
|
6
|
+
* Every call the API places is ONE run of this body, keyed by the call id, so
|
|
7
|
+
* `GET /api/v1/calls/:id` is a read of the run and the finished
|
|
8
|
+
* {@link CallRecord} is the run's output. Nothing else stores a call.
|
|
9
|
+
*
|
|
10
|
+
* ## The shape of a call, as waits
|
|
11
|
+
*
|
|
12
|
+
* 1. **`dial`** — `stepPlaceCall` asks Twilio to ring the number and, once it is
|
|
13
|
+
* answered, stream the audio to this agent's `WS /phone`, carrying the
|
|
14
|
+
* signed brief (`call-params.ts`). Two attempts at most: Twilio takes no
|
|
15
|
+
* idempotency key, so a retried dial whose first answer was lost rings the
|
|
16
|
+
* phone twice.
|
|
17
|
+
* 2. **`ring`** — a short durable sleep and a status read, until the call is
|
|
18
|
+
* answered or over. Polled, because a call nobody picks up never reaches a
|
|
19
|
+
* session, so nothing else would ever say "no answer".
|
|
20
|
+
* 3. **The call itself** — once it is answered the run PARKS on
|
|
21
|
+
* {@link callEndedToken} until the session's `onSessionEnd` signals the
|
|
22
|
+
* transcript (`agent.ts`). Suspended, not blocked: a ten-minute call costs
|
|
23
|
+
* nothing while it runs. The window is the call's own time limit plus
|
|
24
|
+
* slack, and closing unanswered is an outcome, not a failure.
|
|
25
|
+
* 4. **`summarize`** and **`webhook`** — one model call over the transcript,
|
|
26
|
+
* then one POST of the finished record to the caller's `webhook_url`.
|
|
27
|
+
*
|
|
28
|
+
* ## A dial the carrier REFUSES is a result, not a failed run
|
|
29
|
+
*
|
|
30
|
+
* A wrong number, a caller id not on the account, a trial account calling an
|
|
31
|
+
* unverified phone — `PlaceCallError` says which, in a sentence, with
|
|
32
|
+
* `retryable: false`. The run catches exactly that case and completes with
|
|
33
|
+
* `outcome: "failed"` and the sentence as `error`, so the API caller and the
|
|
34
|
+
* webhook get the reason rather than a run that died. A retryable refusal (a
|
|
35
|
+
* 429, a 5xx) is still thrown, so the engine's retry gets its turn.
|
|
36
|
+
*
|
|
37
|
+
* ## Why the transcript arrives by signal and not by a read
|
|
38
|
+
*
|
|
39
|
+
* The session's words live in the session, and the platform keeps no log a
|
|
40
|
+
* step could read them back from afterwards. So the session hands them over
|
|
41
|
+
* as it ends — the one moment it has them all and is done changing them.
|
|
42
|
+
*/
|
|
43
|
+
|
|
44
|
+
import type { WorkflowContext } from "@alexkroman1/aai";
|
|
45
|
+
import {
|
|
46
|
+
isCallOver,
|
|
47
|
+
PlaceCallError,
|
|
48
|
+
type PlacedCallStatus,
|
|
49
|
+
requireStepEnv,
|
|
50
|
+
stepCallStatus,
|
|
51
|
+
stepFetch,
|
|
52
|
+
stepGenerateJson,
|
|
53
|
+
stepPlaceCall,
|
|
54
|
+
} from "@alexkroman1/aai/step";
|
|
55
|
+
import { orFail } from "@alexkroman1/aai/step-errors";
|
|
56
|
+
import { errorMessage, omitUndefined } from "@alexkroman1/aai/utils";
|
|
57
|
+
import { z } from "zod";
|
|
58
|
+
import type { CallOutcome, CallRecord, TranscriptTurn } from "../api-types.ts";
|
|
59
|
+
import { signCall } from "../call-params.ts";
|
|
60
|
+
import { callEndedToken } from "./tokens.ts";
|
|
61
|
+
|
|
62
|
+
/** What the API hands the run. */
|
|
63
|
+
export type CallInput = {
|
|
64
|
+
id: string;
|
|
65
|
+
phone_number: string;
|
|
66
|
+
prompt: string;
|
|
67
|
+
webhook_url?: string | undefined;
|
|
68
|
+
created_at: number;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
/** What the answering session signals as it ends. */
|
|
72
|
+
export type CallEnded = {
|
|
73
|
+
transcript: TranscriptTurn[];
|
|
74
|
+
/** The agent judged it was talking to an answering machine (`end_call`). */
|
|
75
|
+
voicemail: boolean;
|
|
76
|
+
duration_seconds: number;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
/** The longest a call may last, in seconds — Twilio hangs up at this. */
|
|
80
|
+
export const CALL_TIME_LIMIT_S = 600;
|
|
81
|
+
|
|
82
|
+
/** How often the run asks whether the phone has been answered. */
|
|
83
|
+
export const RING_POLL_MS = 5000;
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* How many ring polls before the run gives up on an answer — past Twilio's own
|
|
87
|
+
* 30-second ring timeout, so the carrier normally says `no-answer` first.
|
|
88
|
+
*/
|
|
89
|
+
export const MAX_RING_POLLS = 12;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* How long the run waits for the session to hand over its transcript: the
|
|
93
|
+
* call's whole time limit, plus slack for the session to wind down.
|
|
94
|
+
*/
|
|
95
|
+
export const CALL_WINDOW_MS = (CALL_TIME_LIMIT_S + 120) * 1000;
|
|
96
|
+
|
|
97
|
+
/** A dial the carrier accepted, or the sentence it refused with. */
|
|
98
|
+
export type Dialled = { callId: string } | { refused: string };
|
|
99
|
+
|
|
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 } {
|
|
102
|
+
return {
|
|
103
|
+
from: requireStepEnv("TWILIO_FROM_NUMBER"),
|
|
104
|
+
agentUrl: requireStepEnv("CALLER_AGENT_URL"),
|
|
105
|
+
secret: requireStepEnv("CALLS_API_KEY"),
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 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 —
|
|
112
|
+
* comes back as `{ refused }`; anything retryable is thrown.
|
|
113
|
+
*/
|
|
114
|
+
export async function dial(input: CallInput): Promise<Dialled> {
|
|
115
|
+
try {
|
|
116
|
+
const env = dialEnv();
|
|
117
|
+
const parameters = await signCall({ id: input.id, prompt: input.prompt }, env.secret);
|
|
118
|
+
const { callId } = await stepPlaceCall({
|
|
119
|
+
carrier: "twilio",
|
|
120
|
+
to: input.phone_number,
|
|
121
|
+
from: env.from,
|
|
122
|
+
agentUrl: env.agentUrl,
|
|
123
|
+
parameters,
|
|
124
|
+
timeLimitS: CALL_TIME_LIMIT_S,
|
|
125
|
+
});
|
|
126
|
+
return { callId };
|
|
127
|
+
} catch (err: unknown) {
|
|
128
|
+
if (err instanceof PlaceCallError && err.retryable) throw err;
|
|
129
|
+
return { refused: errorMessage(err) };
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Where the carrier says the call is. */
|
|
134
|
+
export async function readStatus(callId: string): Promise<PlacedCallStatus> {
|
|
135
|
+
return await stepCallStatus({ carrier: "twilio", callId });
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Answered (or answered and already over) — the run should wait for the transcript. */
|
|
139
|
+
function connected(status: PlacedCallStatus): boolean {
|
|
140
|
+
return status === "in-progress" || status === "completed";
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The carrier's word for a call that never reached a session. */
|
|
144
|
+
function unansweredOutcome(status: PlacedCallStatus): CallOutcome {
|
|
145
|
+
switch (status) {
|
|
146
|
+
case "busy":
|
|
147
|
+
case "failed":
|
|
148
|
+
case "canceled":
|
|
149
|
+
return status;
|
|
150
|
+
default:
|
|
151
|
+
// Still `queued`/`ringing` after every poll reads as nobody picking up.
|
|
152
|
+
return "no-answer";
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const Summary = z.object({
|
|
157
|
+
summary: z
|
|
158
|
+
.string()
|
|
159
|
+
.describe("Two or three sentences: what happened on the call and anything agreed"),
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
/** The transcript as plain lines, which is what a model reads best. */
|
|
163
|
+
export function transcriptText(transcript: readonly TranscriptTurn[]): string {
|
|
164
|
+
return transcript
|
|
165
|
+
.map((turn) => `${turn.role === "agent" ? "Agent" : "Callee"}: ${turn.text}`)
|
|
166
|
+
.join("\n");
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Write the call up in two or three sentences, against the task it was given. */
|
|
170
|
+
export async function summarize(
|
|
171
|
+
prompt: string,
|
|
172
|
+
transcript: readonly TranscriptTurn[],
|
|
173
|
+
): Promise<string> {
|
|
174
|
+
const { summary } = await orFail(stepGenerateJson)(
|
|
175
|
+
`The task the caller was given:\n${prompt}\n\nThe call:\n${transcriptText(transcript)}`,
|
|
176
|
+
{
|
|
177
|
+
schema: Summary,
|
|
178
|
+
system:
|
|
179
|
+
"You write up phone calls an AI agent placed. Say plainly what the person on the line said and decided, " +
|
|
180
|
+
"and anything they asked for. Never invent details the call does not contain.",
|
|
181
|
+
},
|
|
182
|
+
);
|
|
183
|
+
return summary;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** POST the finished record to the caller's webhook. A non-2xx is retried by the engine. */
|
|
187
|
+
export async function deliver(webhookUrl: string, record: CallRecord): Promise<number> {
|
|
188
|
+
const response = await orFail(stepFetch)(webhookUrl, {
|
|
189
|
+
method: "POST",
|
|
190
|
+
headers: { "content-type": "application/json" },
|
|
191
|
+
body: JSON.stringify(record),
|
|
192
|
+
});
|
|
193
|
+
return response.status;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** The record the run returns, before the webhook has had its say. */
|
|
197
|
+
function callRecord(
|
|
198
|
+
input: CallInput,
|
|
199
|
+
outcome: CallOutcome,
|
|
200
|
+
fields: {
|
|
201
|
+
transcript?: TranscriptTurn[];
|
|
202
|
+
duration_seconds?: number;
|
|
203
|
+
summary?: string;
|
|
204
|
+
error?: string;
|
|
205
|
+
},
|
|
206
|
+
): CallRecord {
|
|
207
|
+
return {
|
|
208
|
+
id: input.id,
|
|
209
|
+
status: "completed",
|
|
210
|
+
phone_number: input.phone_number,
|
|
211
|
+
created_at: input.created_at,
|
|
212
|
+
outcome,
|
|
213
|
+
transcript: fields.transcript ?? [],
|
|
214
|
+
...omitUndefined({
|
|
215
|
+
duration_seconds: fields.duration_seconds,
|
|
216
|
+
summary: fields.summary,
|
|
217
|
+
error: fields.error,
|
|
218
|
+
}),
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** The body — see this module's doc for the four stages. */
|
|
223
|
+
export async function callFlow(input: CallInput, ctx: WorkflowContext): Promise<CallRecord> {
|
|
224
|
+
const dialled = await ctx.step("dial", () => dial(input), { maxAttempts: 2 });
|
|
225
|
+
if ("refused" in dialled) {
|
|
226
|
+
return await finish(input, callRecord(input, "failed", { error: dialled.refused }), ctx);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
let status: PlacedCallStatus = "queued";
|
|
230
|
+
for (let i = 0; i < MAX_RING_POLLS && !connected(status) && !isCallOver(status); i++) {
|
|
231
|
+
await ctx.sleep("ring", RING_POLL_MS);
|
|
232
|
+
status = await ctx.step("ring-status", () => readStatus(dialled.callId));
|
|
233
|
+
}
|
|
234
|
+
if (!connected(status)) {
|
|
235
|
+
return await finish(input, callRecord(input, unansweredOutcome(status), {}), ctx);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const ended = await ctx.waitFor<CallEnded>(callEndedToken(input.id), {
|
|
239
|
+
timeoutMs: CALL_WINDOW_MS,
|
|
240
|
+
});
|
|
241
|
+
if (ended === undefined) {
|
|
242
|
+
return await finish(
|
|
243
|
+
input,
|
|
244
|
+
callRecord(input, "answered", {
|
|
245
|
+
error: "The call was answered, but its transcript never reached this run.",
|
|
246
|
+
}),
|
|
247
|
+
ctx,
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const outcome: CallOutcome = ended.voicemail ? "voicemail" : "answered";
|
|
252
|
+
const summary =
|
|
253
|
+
ended.transcript.length === 0
|
|
254
|
+
? undefined
|
|
255
|
+
: await ctx.step("summarize", () => summarize(input.prompt, ended.transcript));
|
|
256
|
+
return await finish(
|
|
257
|
+
input,
|
|
258
|
+
callRecord(input, outcome, {
|
|
259
|
+
transcript: ended.transcript,
|
|
260
|
+
duration_seconds: ended.duration_seconds,
|
|
261
|
+
...omitUndefined({ summary }),
|
|
262
|
+
}),
|
|
263
|
+
ctx,
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Deliver the record to the webhook, when one was given, and return it.
|
|
269
|
+
*
|
|
270
|
+
* A webhook that keeps failing does not fail the CALL — the call happened, and
|
|
271
|
+
* the record is still readable from the API — so its failure is written onto
|
|
272
|
+
* the record as `error` instead.
|
|
273
|
+
*/
|
|
274
|
+
async function finish(
|
|
275
|
+
input: CallInput,
|
|
276
|
+
record: CallRecord,
|
|
277
|
+
ctx: WorkflowContext,
|
|
278
|
+
): Promise<CallRecord> {
|
|
279
|
+
const url = input.webhook_url;
|
|
280
|
+
if (url === undefined) return record;
|
|
281
|
+
try {
|
|
282
|
+
await ctx.step("webhook", () => deliver(url, record), { maxAttempts: 3 });
|
|
283
|
+
return record;
|
|
284
|
+
} catch (err: unknown) {
|
|
285
|
+
return {
|
|
286
|
+
...record,
|
|
287
|
+
error: record.error ?? `The webhook was not delivered: ${errorMessage(err)}`,
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Copyright 2026 the AAI authors. MIT license.
|
|
2
|
+
/**
|
|
3
|
+
* The hook token the call's run parks on and the session's end signals.
|
|
4
|
+
*
|
|
5
|
+
* Two files have to derive it identically — `workflows/call.ts` waits on it,
|
|
6
|
+
* `agent.ts`'s `onSessionEnd` answers it — and a template literal written
|
|
7
|
+
* twice drifts once, silently: the only symptom is `signal()` answering
|
|
8
|
+
* `false`, which is also what "nobody is waiting yet" looks like. Hence one
|
|
9
|
+
* function, imported by both.
|
|
10
|
+
*
|
|
11
|
+
* Derived from the CALL id, which is the run's own input and unique per run,
|
|
12
|
+
* so two runs can never claim one token.
|
|
13
|
+
*/
|
|
14
|
+
export function callEndedToken(callId: string): string {
|
|
15
|
+
return `call-ended:${callId}`;
|
|
16
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alexkroman1/aai-cli",
|
|
3
|
-
"version": "0.14.
|
|
3
|
+
"version": "0.14.3",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -56,10 +56,11 @@
|
|
|
56
56
|
"p-debounce": "^5.1.1",
|
|
57
57
|
"p-timeout": "^7.0.2",
|
|
58
58
|
"vite": "^8.3.1",
|
|
59
|
+
"xstate": "^5.33.2",
|
|
59
60
|
"zod": "^4.6.5",
|
|
60
|
-
"@alexkroman1/aai": "0.14.
|
|
61
|
-
"@alexkroman1/aai-runtime": "0.14.
|
|
62
|
-
"@alexkroman1/aai-ui": "0.14.
|
|
61
|
+
"@alexkroman1/aai": "0.14.3",
|
|
62
|
+
"@alexkroman1/aai-runtime": "0.14.3",
|
|
63
|
+
"@alexkroman1/aai-ui": "0.14.3"
|
|
63
64
|
},
|
|
64
65
|
"devDependencies": {
|
|
65
66
|
"playwright": "^1.63.0",
|