@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.
@@ -0,0 +1,122 @@
1
+ // Copyright 2026 the AAI authors. MIT license.
2
+ /**
3
+ * `/api/v1/calls` — the HTTP API that places calls and reads them back.
4
+ *
5
+ * ```sh
6
+ * curl "$AGENT_URL/api/v1/calls" \
7
+ * -H "Authorization: $CALLS_API_KEY" \
8
+ * -H "Content-Type: application/json" \
9
+ * -d '{"phone_number": "+14155550132", "prompt": "Call Maria for Mission Dental…",
10
+ * "webhook_url": "https://example.com/hooks/calls"}'
11
+ * ```
12
+ *
13
+ * | Route | Answers |
14
+ * | --- | --- |
15
+ * | `POST /v1/calls` | `201` and the queued {@link CallRecord} — the call is dialled in the background |
16
+ * | `GET /v1/calls/:id` | the call as it stands: live lines while it is talking, the full record once done |
17
+ * | `GET /v1/calls` | the most recent calls, newest first |
18
+ *
19
+ * Every route checks `Authorization` against `CALLS_API_KEY` (a bare key or
20
+ * `Bearer <key>`): `agent({ routes })` is as open as the server, and a route
21
+ * that dials a phone is not one to leave open.
22
+ *
23
+ * Each call is one run of the `call` workflow, started with `key` = the call
24
+ * id, so the API stores nothing of its own: a read is `find(call, id)`.
25
+ */
26
+
27
+ import {
28
+ type RouteContext,
29
+ type RouteHandler,
30
+ type RouteRequest,
31
+ routeError,
32
+ routeResponse,
33
+ } from "@alexkroman1/aai";
34
+ import type { WorkflowRunSnapshot } from "@alexkroman1/aai/workflow-api";
35
+ import type { CallList, CallRecord } from "./api-types.ts";
36
+ import { safeEqual } from "./call-params.ts";
37
+ import { liveCall } from "./live-calls.ts";
38
+ import { call, callRequest } from "./shared.ts";
39
+
40
+ /** Most calls `GET /v1/calls` lists. */
41
+ export const LIST_LIMIT = 50;
42
+
43
+ /** Refuse a request that does not carry `CALLS_API_KEY`. */
44
+ export function authorize(req: RouteRequest, env: RouteContext["env"]): void {
45
+ const key = env.CALLS_API_KEY;
46
+ if (!key)
47
+ throw routeError(503, "The calls API is off: set the CALLS_API_KEY secret to turn it on.");
48
+ const given = (req.headers.authorization ?? "").replace(/^Bearer\s+/i, "").trim();
49
+ if (!safeEqual(given, key)) throw routeError(401, "Missing or wrong Authorization header.");
50
+ }
51
+
52
+ /** A fresh call id: `call_` and sixteen random hex characters. */
53
+ export function newCallId(): string {
54
+ return `call_${crypto.randomUUID().replaceAll("-", "").slice(0, 16)}`;
55
+ }
56
+
57
+ /**
58
+ * What a run says about its call. A finished run's output IS the record; an
59
+ * unfinished one is filled in from the live transcript when this process is
60
+ * the one on the call.
61
+ */
62
+ export function toRecord(run: WorkflowRunSnapshot<CallRecord>): CallRecord {
63
+ const id = run.key ?? run.runId;
64
+ const base = { id, phone_number: run.label ?? "", created_at: run.createdAt, transcript: [] };
65
+ switch (run.status) {
66
+ case "completed":
67
+ return run.output;
68
+ case "failed":
69
+ return { ...base, status: "failed", error: run.error };
70
+ case "cancelled":
71
+ return { ...base, status: "completed", outcome: "canceled" };
72
+ default: {
73
+ const live = liveCall(id);
74
+ return live === undefined
75
+ ? { ...base, status: "queued" }
76
+ : { ...base, status: "in-progress", transcript: [...live.transcript] };
77
+ }
78
+ }
79
+ }
80
+
81
+ /** `POST /v1/calls` — validate, start the run, answer at once. */
82
+ export const createCall: RouteHandler = async (req, ctx) => {
83
+ authorize(req, ctx.env);
84
+ const parsed = callRequest.safeParse(req.body);
85
+ if (!parsed.success) {
86
+ throw routeError(400, parsed.error.issues.map((issue) => issue.message).join("; "));
87
+ }
88
+ const id = newCallId();
89
+ const createdAt = Date.now();
90
+ await ctx.workflows.start(
91
+ call,
92
+ { ...parsed.data, id, created_at: createdAt },
93
+ // `key` is how every later read finds the run; `label` carries the number
94
+ // so an unfinished run can still say who it is calling.
95
+ { key: id, label: parsed.data.phone_number },
96
+ );
97
+ const record: CallRecord = {
98
+ id,
99
+ status: "queued",
100
+ phone_number: parsed.data.phone_number,
101
+ created_at: createdAt,
102
+ transcript: [],
103
+ };
104
+ return routeResponse(201, record);
105
+ };
106
+
107
+ /** `GET /v1/calls/:id` — the call as it stands. */
108
+ export const getCall: RouteHandler = async (req, ctx) => {
109
+ authorize(req, ctx.env);
110
+ const id = req.params.id ?? "";
111
+ const [run] = await ctx.workflows.find(call, id, { limit: 1 });
112
+ if (run === undefined) throw routeError(404, `No call ${id}.`);
113
+ return toRecord(run);
114
+ };
115
+
116
+ /** `GET /v1/calls` — the most recent calls, newest first. */
117
+ export const listCalls: RouteHandler = async (req, ctx) => {
118
+ authorize(req, ctx.env);
119
+ const runs = await ctx.workflows.recent(call, { limit: LIST_LIMIT });
120
+ const list: CallList = { calls: runs.map(toRecord) };
121
+ return list;
122
+ };
@@ -0,0 +1,109 @@
1
+ // Copyright 2026 the AAI authors. MIT license.
2
+ /**
3
+ * What a placed call carries to the session that answers it, and the
4
+ * signature that proves this app placed it.
5
+ *
6
+ * `stepPlaceCall` hands Twilio a set of `<Parameter>`s, and the answering
7
+ * session reads them back as `call.parameters` in `sessionContext` — before the
8
+ * first model call. That is the ONLY channel between the run that dialled and
9
+ * the session that talks, so the call's whole brief travels on it: the call id,
10
+ * the task prompt, and a signature over both.
11
+ *
12
+ * ## Why the prompt rides on the call instead of being looked up
13
+ *
14
+ * `sessionContext` is handed `env` and the call, and nothing that reads a
15
+ * workflow run — and it has 1.5 seconds. Carrying the prompt on the call means
16
+ * the session needs no store, no lookup and no network: the brief arrives with
17
+ * the audio. Twilio caps each parameter at 500 characters (name plus value) and
18
+ * a stream at 32 of them, so the prompt is cut into {@link CHUNK_CHARS} pieces
19
+ * named `p0`, `p1`, … — {@link MAX_PROMPT_CHARS} fits with room to spare.
20
+ *
21
+ * ## Why it is signed
22
+ *
23
+ * `WS /phone` is unauthenticated — anyone who learns the agent's URL can open
24
+ * a stream and claim any parameters they like, and spend the agent's model on
25
+ * a conversation of their choosing. So {@link signCall} computes an HMAC over
26
+ * the id and the prompt with `CALLS_API_KEY`, and {@link readCall} answers
27
+ * `undefined` for a stream whose signature does not verify; `agent.ts` turns
28
+ * that into `{ refuse }`, which hangs up before the greeting or any model call.
29
+ *
30
+ * Web Crypto rather than `node:crypto`: it is a global in Node, in the guest
31
+ * and in a browser alike, so this module imports nothing.
32
+ */
33
+
34
+ /** Characters of prompt per `<Parameter>` — under Twilio's 500 with the name. */
35
+ export const CHUNK_CHARS = 450;
36
+
37
+ /** The longest task prompt a call accepts — nine chunks, well inside 32 parameters. */
38
+ export const MAX_PROMPT_CHARS = 4000;
39
+
40
+ /** What a verified call told its session. */
41
+ export type CallBrief = {
42
+ /** This app's call id — `call_…`, the id the API answers with. */
43
+ id: string;
44
+ /** The task, as the API caller wrote it. */
45
+ prompt: string;
46
+ };
47
+
48
+ /** Constant-time comparison, so a forged secret learns nothing from timing. */
49
+ export function safeEqual(a: string, b: string): boolean {
50
+ if (a.length !== b.length) return false;
51
+ let diff = 0;
52
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
53
+ return diff === 0;
54
+ }
55
+
56
+ async function hmac(secret: string, text: string): Promise<string> {
57
+ const encoder = new TextEncoder();
58
+ const key = await crypto.subtle.importKey(
59
+ "raw",
60
+ encoder.encode(secret),
61
+ { name: "HMAC", hash: "SHA-256" },
62
+ false,
63
+ ["sign"],
64
+ );
65
+ const mac = await crypto.subtle.sign("HMAC", key, encoder.encode(text));
66
+ return Array.from(new Uint8Array(mac), (byte) => byte.toString(16).padStart(2, "0")).join("");
67
+ }
68
+
69
+ /** The signed text: the id, a separator no id contains, and the prompt. */
70
+ function signedText(brief: CallBrief): string {
71
+ return `${brief.id}\n${brief.prompt}`;
72
+ }
73
+
74
+ /**
75
+ * The `<Parameter>`s for one call: `call`, `sig`, and the prompt as `p0…pN`.
76
+ *
77
+ * @throws {RangeError} When the prompt is over {@link MAX_PROMPT_CHARS} — the
78
+ * API's schema refuses that first, so reaching it is a bug.
79
+ */
80
+ export async function signCall(brief: CallBrief, secret: string): Promise<Record<string, string>> {
81
+ if (brief.prompt.length > MAX_PROMPT_CHARS) {
82
+ throw new RangeError(`A call prompt is at most ${MAX_PROMPT_CHARS} characters.`);
83
+ }
84
+ const params: Record<string, string> = {
85
+ call: brief.id,
86
+ sig: await hmac(secret, signedText(brief)),
87
+ };
88
+ for (let i = 0; i * CHUNK_CHARS < brief.prompt.length; i++) {
89
+ params[`p${i}`] = brief.prompt.slice(i * CHUNK_CHARS, (i + 1) * CHUNK_CHARS);
90
+ }
91
+ return params;
92
+ }
93
+
94
+ /**
95
+ * The brief a stream's parameters carry, or `undefined` when they were not
96
+ * signed by this app — a stranger, a stale secret, or a truncated stream.
97
+ */
98
+ export async function readCall(
99
+ params: Readonly<Record<string, string>>,
100
+ secret: string | undefined,
101
+ ): Promise<CallBrief | undefined> {
102
+ const id = params.call;
103
+ const sig = params.sig;
104
+ if (!(secret && id && sig)) return undefined;
105
+ let prompt = "";
106
+ for (let i = 0; params[`p${i}`] !== undefined; i++) prompt += params[`p${i}`];
107
+ const brief = { id, prompt };
108
+ return safeEqual(sig, await hmac(secret, signedText(brief))) ? brief : undefined;
109
+ }
@@ -0,0 +1,407 @@
1
+ // Copyright 2026 the AAI authors. MIT license.
2
+ /**
3
+ * The console for the calls API: write a task, place the call, and watch the
4
+ * transcript come back.
5
+ *
6
+ * Mounted with `mountPage()`: nobody talks to this agent from the browser —
7
+ * it talks on the phone — so the page opens no session and asks for no
8
+ * microphone. It is one more caller of `/api/v1/calls`, written against the
9
+ * same contract (`api-types.ts`) the curl example is.
10
+ *
11
+ * ## Why it fetches by hand
12
+ *
13
+ * Every route checks `Authorization` (see `api.ts`), and `routeFetch` /
14
+ * `useRoute` send no headers. So {@link callsApi} is the same few lines with
15
+ * the header added: resolve `api/…` against the page's DIRECTORY (an agent
16
+ * served below `/:slug/` reaches its own `/:slug/api`), send JSON, and turn a
17
+ * failure into the route's own `{ error }` sentence.
18
+ *
19
+ * The key is kept in `localStorage` so a reload does not ask again; a browser
20
+ * that refuses storage just asks each time.
21
+ */
22
+
23
+ import { isRecord, omitUndefined } from "@alexkroman1/aai/utils";
24
+ import { mountPage } from "@alexkroman1/aai-ui";
25
+ import "@alexkroman1/aai-ui/styles.css";
26
+ import { type ReactNode, type SyntheticEvent, useCallback, useEffect, useState } from "react";
27
+ import type { CallList, CallRecord } from "./api-types.ts";
28
+
29
+ const KEY_STORAGE = "outbound-caller.api-key";
30
+
31
+ /** How often the open call is re-read while it is still going. */
32
+ const LIVE_POLL_MS = 1500;
33
+
34
+ /** How often the list is re-read. */
35
+ const LIST_POLL_MS = 5000;
36
+
37
+ const EXAMPLE_PROMPT =
38
+ "Call Maria for Mission Dental to confirm her cleaning tomorrow at 2:30pm. " +
39
+ "If she needs to reschedule, offer Thursday at 10am or Friday at 4pm. " +
40
+ "If you get voicemail, ask her to call 415-555-0100.";
41
+
42
+ function readStoredKey(): string {
43
+ try {
44
+ return localStorage.getItem(KEY_STORAGE) ?? "";
45
+ } catch {
46
+ return "";
47
+ }
48
+ }
49
+
50
+ function storeKey(key: string): void {
51
+ try {
52
+ localStorage.setItem(KEY_STORAGE, key);
53
+ } catch {
54
+ // Storage refused (a private window): the key lives for this page only.
55
+ }
56
+ }
57
+
58
+ /** One call to the agent's own `/api` routes, with the API key attached. */
59
+ async function callsApi<T>(
60
+ method: "GET" | "POST",
61
+ path: string,
62
+ key: string,
63
+ body?: unknown,
64
+ ): Promise<T> {
65
+ const url = new URL(`api${path}`, new URL(".", window.location.href));
66
+ // Every request carries a content type, so a GET and a POST build one way.
67
+ const res = await fetch(url, {
68
+ method,
69
+ headers: { authorization: key, "content-type": "application/json" },
70
+ ...omitUndefined({ body: body === undefined ? undefined : JSON.stringify(body) }),
71
+ });
72
+ const json: unknown = await res.json().catch(() => ({}));
73
+ if (!res.ok) {
74
+ const said = isRecord(json) && typeof json.error === "string" ? json.error : undefined;
75
+ throw new Error(said ?? `${method} ${path}: ${res.status}`);
76
+ }
77
+ return json as T;
78
+ }
79
+
80
+ function isFinished(call: CallRecord | undefined): boolean {
81
+ return call?.status === "completed" || call?.status === "failed";
82
+ }
83
+
84
+ /** A pill for where a call is, or how it went once it is over. */
85
+ function StatusPill({ call }: { call: CallRecord }): ReactNode {
86
+ const label = call.status === "completed" ? (call.outcome ?? "completed") : call.status;
87
+ const live = call.status === "in-progress";
88
+ const bad = call.status === "failed" || call.outcome === "failed";
89
+ return (
90
+ <span
91
+ className={`rounded-full border px-2 py-0.5 text-xs ${
92
+ live
93
+ ? "border-aai-primary text-aai-primary"
94
+ : bad
95
+ ? "border-red-500 text-red-500"
96
+ : "border-aai-border text-aai-text opacity-80"
97
+ }`}
98
+ >
99
+ {live ? "live" : label}
100
+ </span>
101
+ );
102
+ }
103
+
104
+ function Transcript({ call }: { call: CallRecord }): ReactNode {
105
+ if (call.transcript.length === 0) {
106
+ return (
107
+ <p className="text-sm opacity-60">
108
+ {isFinished(call) ? "Nothing was said on this call." : "Waiting for the call to connect…"}
109
+ </p>
110
+ );
111
+ }
112
+ return (
113
+ <ol className="flex flex-col gap-2">
114
+ {call.transcript.map((turn, i) => (
115
+ // Lines only ever append, so the index is a stable key.
116
+ <li key={i} className={`flex ${turn.role === "agent" ? "justify-start" : "justify-end"}`}>
117
+ <div
118
+ className={`max-w-[80%] rounded-lg px-3 py-2 text-sm leading-relaxed ${
119
+ turn.role === "agent" ? "bg-aai-surface text-aai-text" : "bg-aai-primary text-aai-bg"
120
+ }`}
121
+ >
122
+ <span className="block text-xs opacity-70">
123
+ {turn.role === "agent" ? "Agent" : "Callee"}
124
+ </span>
125
+ {turn.text}
126
+ </div>
127
+ </li>
128
+ ))}
129
+ </ol>
130
+ );
131
+ }
132
+
133
+ function CallDetail({ id, apiKey }: { id: string; apiKey: string }): ReactNode {
134
+ const [call, setCall] = useState<CallRecord | undefined>(undefined);
135
+ const [error, setError] = useState<string | undefined>(undefined);
136
+ const finished = isFinished(call);
137
+
138
+ useEffect(() => {
139
+ setCall(undefined);
140
+ setError(undefined);
141
+ }, [id]);
142
+
143
+ useEffect(() => {
144
+ if (finished) return;
145
+ let stopped = false;
146
+ const read = () =>
147
+ callsApi<CallRecord>("GET", `/v1/calls/${encodeURIComponent(id)}`, apiKey)
148
+ .then((answer) => {
149
+ if (!stopped) setCall(answer);
150
+ })
151
+ .catch((err: unknown) => {
152
+ if (!stopped) setError(err instanceof Error ? err.message : String(err));
153
+ });
154
+ void read();
155
+ const timer = setInterval(() => void read(), LIVE_POLL_MS);
156
+ return () => {
157
+ stopped = true;
158
+ clearInterval(timer);
159
+ };
160
+ }, [id, apiKey, finished]);
161
+
162
+ if (error !== undefined) return <p className="text-sm text-red-500">{error}</p>;
163
+ if (call === undefined) return <p className="text-sm opacity-60">Loading…</p>;
164
+ return (
165
+ <article className="flex flex-col gap-4">
166
+ <header className="flex flex-wrap items-center gap-3">
167
+ <h2 className="font-mono text-lg">{call.phone_number}</h2>
168
+ <StatusPill call={call} />
169
+ {call.duration_seconds !== undefined && (
170
+ <span className="text-sm opacity-70">{call.duration_seconds}s</span>
171
+ )}
172
+ <span className="ml-auto font-mono text-xs opacity-60">{call.id}</span>
173
+ </header>
174
+ {call.error !== undefined && <p className="text-sm text-red-500">{call.error}</p>}
175
+ {call.summary !== undefined && (
176
+ <section className="rounded-lg border border-aai-border p-3">
177
+ <h3 className="mb-1 text-xs uppercase opacity-60">Summary</h3>
178
+ <p className="text-pretty text-sm leading-relaxed">{call.summary}</p>
179
+ </section>
180
+ )}
181
+ <Transcript call={call} />
182
+ {finished && (
183
+ <details className="text-xs">
184
+ <summary className="cursor-pointer opacity-70">Raw JSON</summary>
185
+ <pre className="aai-scroll mt-2 overflow-x-auto rounded-md bg-aai-surface p-3">
186
+ {JSON.stringify(call, null, 2)}
187
+ </pre>
188
+ </details>
189
+ )}
190
+ </article>
191
+ );
192
+ }
193
+
194
+ function NewCall({
195
+ apiKey,
196
+ onPlaced,
197
+ }: {
198
+ apiKey: string;
199
+ onPlaced: (call: CallRecord) => void;
200
+ }): ReactNode {
201
+ const [phone, setPhone] = useState("");
202
+ const [prompt, setPrompt] = useState(EXAMPLE_PROMPT);
203
+ const [webhook, setWebhook] = useState("");
204
+ const [busy, setBusy] = useState(false);
205
+ const [error, setError] = useState<string | undefined>(undefined);
206
+
207
+ async function submit(event: SyntheticEvent<HTMLFormElement>): Promise<void> {
208
+ event.preventDefault();
209
+ setBusy(true);
210
+ setError(undefined);
211
+ try {
212
+ const placed = await callsApi<CallRecord>("POST", "/v1/calls", apiKey, {
213
+ phone_number: phone.trim(),
214
+ prompt,
215
+ ...(webhook.trim() === "" ? {} : { webhook_url: webhook.trim() }),
216
+ });
217
+ onPlaced(placed);
218
+ } catch (err: unknown) {
219
+ setError(err instanceof Error ? err.message : String(err));
220
+ } finally {
221
+ setBusy(false);
222
+ }
223
+ }
224
+
225
+ const input = "rounded-md border border-aai-border bg-aai-bg px-3 py-2 text-sm text-aai-text";
226
+ return (
227
+ <form onSubmit={(event) => void submit(event)} className="flex flex-col gap-3">
228
+ <label className="flex flex-col gap-1 text-sm">
229
+ Phone number
230
+ <input
231
+ className={`${input} font-mono`}
232
+ type="tel"
233
+ required
234
+ placeholder="+14155550132"
235
+ pattern="\+[1-9][0-9]{6,14}"
236
+ value={phone}
237
+ onChange={(event) => setPhone(event.target.value)}
238
+ />
239
+ </label>
240
+ <label className="flex flex-col gap-1 text-sm">
241
+ What should the agent do on this call?
242
+ <textarea
243
+ className={`${input} min-h-32 leading-relaxed`}
244
+ required
245
+ maxLength={4000}
246
+ value={prompt}
247
+ onChange={(event) => setPrompt(event.target.value)}
248
+ />
249
+ </label>
250
+ <label className="flex flex-col gap-1 text-sm">
251
+ Webhook URL (optional)
252
+ <input
253
+ className={input}
254
+ type="url"
255
+ placeholder="https://example.com/hooks/calls"
256
+ value={webhook}
257
+ onChange={(event) => setWebhook(event.target.value)}
258
+ />
259
+ </label>
260
+ {error !== undefined && (
261
+ <p role="alert" className="text-sm text-red-500">
262
+ {error}
263
+ </p>
264
+ )}
265
+ <button
266
+ type="submit"
267
+ disabled={busy || apiKey === ""}
268
+ className="self-start rounded-md bg-aai-primary px-4 py-2 text-sm text-aai-bg disabled:opacity-50"
269
+ >
270
+ {busy ? "Placing…" : "Place call"}
271
+ </button>
272
+ </form>
273
+ );
274
+ }
275
+
276
+ function CallsList({
277
+ apiKey,
278
+ selected,
279
+ onSelect,
280
+ refresh,
281
+ }: {
282
+ apiKey: string;
283
+ selected: string | undefined;
284
+ onSelect: (id: string) => void;
285
+ refresh: number;
286
+ }): ReactNode {
287
+ const [calls, setCalls] = useState<CallRecord[]>([]);
288
+ const [error, setError] = useState<string | undefined>(undefined);
289
+
290
+ // `refresh` is a dependency on purpose: placing a call bumps it, so the new
291
+ // call shows without waiting for the next poll.
292
+ useEffect(() => {
293
+ if (apiKey === "") return;
294
+ let stopped = false;
295
+ const read = () =>
296
+ callsApi<CallList>("GET", "/v1/calls", apiKey)
297
+ .then((answer) => {
298
+ if (stopped) return;
299
+ setCalls(answer.calls);
300
+ setError(undefined);
301
+ })
302
+ .catch((err: unknown) => {
303
+ if (!stopped) setError(err instanceof Error ? err.message : String(err));
304
+ });
305
+ void read();
306
+ const timer = setInterval(() => void read(), LIST_POLL_MS);
307
+ return () => {
308
+ stopped = true;
309
+ clearInterval(timer);
310
+ };
311
+ }, [apiKey, refresh]);
312
+
313
+ if (error !== undefined) return <p className="text-sm text-red-500">{error}</p>;
314
+ if (calls.length === 0) return <p className="text-sm opacity-60">No calls yet.</p>;
315
+ return (
316
+ <ul className="flex flex-col gap-1">
317
+ {calls.map((call) => (
318
+ <li key={call.id}>
319
+ <button
320
+ type="button"
321
+ onClick={() => onSelect(call.id)}
322
+ className={`flex w-full items-center gap-2 rounded-md border px-3 py-2 text-left text-sm ${
323
+ call.id === selected ? "border-aai-primary" : "border-aai-border"
324
+ }`}
325
+ >
326
+ <span className="font-mono">{call.phone_number}</span>
327
+ <StatusPill call={call} />
328
+ <span className="ml-auto text-xs opacity-60">
329
+ {new Date(call.created_at).toLocaleTimeString()}
330
+ </span>
331
+ </button>
332
+ </li>
333
+ ))}
334
+ </ul>
335
+ );
336
+ }
337
+
338
+ export function App(): ReactNode {
339
+ const [apiKey, setApiKey] = useState(readStoredKey);
340
+ const [selected, setSelected] = useState<string | undefined>(undefined);
341
+ const [refresh, setRefresh] = useState(0);
342
+
343
+ const saveKey = useCallback((key: string) => {
344
+ setApiKey(key);
345
+ storeKey(key);
346
+ }, []);
347
+
348
+ return (
349
+ <main className="mx-auto flex max-w-6xl flex-col gap-6 bg-aai-bg p-4 text-aai-text md:p-8">
350
+ <header className="flex flex-col gap-1">
351
+ <h1 className="text-balance text-2xl">Outbound Caller</h1>
352
+ <p className="text-pretty text-sm opacity-70">
353
+ Give the agent a number and a task. It places the call, carries out the task, and the
354
+ transcript appears here as the conversation happens.
355
+ </p>
356
+ </header>
357
+
358
+ <label className="flex flex-col gap-1 text-sm md:max-w-md">
359
+ API key (the agent's <code>CALLS_API_KEY</code>)
360
+ <input
361
+ className="rounded-md border border-aai-border bg-aai-bg px-3 py-2 font-mono text-sm text-aai-text"
362
+ type="password"
363
+ autoComplete="off"
364
+ value={apiKey}
365
+ onChange={(event) => saveKey(event.target.value)}
366
+ />
367
+ </label>
368
+
369
+ <div className="grid gap-6 md:grid-cols-[minmax(0,2fr)_minmax(0,3fr)]">
370
+ <section className="flex flex-col gap-6">
371
+ <div className="rounded-lg border border-aai-border bg-aai-surface p-4">
372
+ <h2 className="mb-3 text-lg">New call</h2>
373
+ <NewCall
374
+ apiKey={apiKey}
375
+ onPlaced={(call) => {
376
+ setSelected(call.id);
377
+ setRefresh((n) => n + 1);
378
+ }}
379
+ />
380
+ </div>
381
+ <div className="flex flex-col gap-2">
382
+ <h2 className="text-lg">Recent calls</h2>
383
+ {apiKey === "" ? (
384
+ <p className="text-sm opacity-60">Enter the API key to see calls.</p>
385
+ ) : (
386
+ <CallsList
387
+ apiKey={apiKey}
388
+ selected={selected}
389
+ onSelect={setSelected}
390
+ refresh={refresh}
391
+ />
392
+ )}
393
+ </div>
394
+ </section>
395
+ <section className="rounded-lg border border-aai-border p-4">
396
+ {selected === undefined ? (
397
+ <p className="text-sm opacity-60">Place a call or pick one to see its transcript.</p>
398
+ ) : (
399
+ <CallDetail id={selected} apiKey={apiKey} />
400
+ )}
401
+ </section>
402
+ </div>
403
+ </main>
404
+ );
405
+ }
406
+
407
+ mountPage({ name: "Outbound Caller", component: App });