@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.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Restart supervision for `aai dev`.
2
+ * Restart supervision for `aai dev`, as a statechart.
3
3
  *
4
4
  * The dev server's subtlest logic is not the wiring (chokidar, Vite, the
5
5
  * bundler) but the small state machine that decides WHEN to rebuild and in
@@ -14,6 +14,42 @@
14
14
  *
15
15
  * The supervised server is opaque (`S`): the supervisor never touches it
16
16
  * except through `ops`, so a test can use a plain label.
17
+ *
18
+ * ## Teardown is LEAVING `rebuilding`, which is what deletes the `closed` checks
19
+ *
20
+ * This was a `booting`/`queuedDuringBoot`/`closed` latch set plus a
21
+ * `createCoalescingRunner` over an async `restartOnce`, which re-read `closed`
22
+ * after every `await` — after the build, after the listen, between listen
23
+ * attempts — because a teardown could land at any of them. Each step is now an
24
+ * invoked actor of its own state, so `CLOSE` exits the step and stops it, and
25
+ * its outcome is never delivered: the re-check is the machine.
26
+ *
27
+ * Stopping an actor does not cancel the operation under it, though, and the
28
+ * step that was in flight is holding a server nobody else knows about — the
29
+ * one just built, or the one half-way through binding. So every step that
30
+ * holds the REPLACEMENT disposes of it when its signal aborts, after its own
31
+ * operation settles: closing a server whose `listen` is still in flight would
32
+ * let the bind complete afterwards and leak the port. That disposal is
33
+ * fire-and-forget, as the old early returns were — `close()` awaits teardown
34
+ * and the CURRENT server, never an in-flight rebuild.
35
+ *
36
+ * ## Coalescing is a flag in context, not a runner
37
+ *
38
+ * At most one rebuild runs; every `REQUEST` landing during one (or during
39
+ * boot) sets `queued`, and the rebuild's end — success, failed build, failed
40
+ * listen — re-enters `rebuilding` once if it is set. That is the
41
+ * `createCoalescingRunner` contract restated as a transition, and the policy
42
+ * is the same: a rebuild reads the files as they are WHEN IT RUNS, so N queued
43
+ * rebuilds would do the trailing one's work N times, while dropping the
44
+ * trigger would leave the newest save unserved.
45
+ *
46
+ * ## Actions never throw
47
+ *
48
+ * A throwing action ERRORS an XState actor for good, which would wedge
49
+ * watching — the old runner's "a rejection never wedges" property. The one
50
+ * effect that can throw on an ordinary path is `notify` (stderr closed by
51
+ * `aai dev | head`), so it goes through {@link report}, which falls back to
52
+ * reporting the throw itself and then swallows.
17
53
  */
18
54
  export type NotifyLevel = "error" | "warn" | "info" | "success";
19
55
  export type RestartOps<S> = {
@@ -20,6 +20,7 @@ import { defaultClientDir } from "@alexkroman1/aai-ui/client-dir";
20
20
  import { watch } from "chokidar";
21
21
  import getPort, { portNumbers } from "get-port";
22
22
  import { agentConfigWarnings } from "@alexkroman1/aai/manifest";
23
+ import { assign, createActor, fromPromise, setup, waitFor } from "xstate";
23
24
  import { isBlankSecret } from "@alexkroman1/aai/host-internal";
24
25
  import { CLIENT_CONFIG_PATH, buildClientConfig } from "@alexkroman1/aai/protocol";
25
26
  import { SESSION_SECRET_ENV, createSessionAuth, createSessionToken, verifySessionToken } from "@alexkroman1/aai-runtime/auth";
@@ -61,7 +62,7 @@ async function resolveAgentEnv(root, agentDef, ui = defaultUi, deps = { ensureAp
61
62
  //#endregion
62
63
  //#region src/_dev-restart.ts
63
64
  /**
64
- * Restart supervision for `aai dev`.
65
+ * Restart supervision for `aai dev`, as a statechart.
65
66
  *
66
67
  * The dev server's subtlest logic is not the wiring (chokidar, Vite, the
67
68
  * bundler) but the small state machine that decides WHEN to rebuild and in
@@ -76,11 +77,264 @@ async function resolveAgentEnv(root, agentDef, ui = defaultUi, deps = { ensureAp
76
77
  *
77
78
  * The supervised server is opaque (`S`): the supervisor never touches it
78
79
  * except through `ops`, so a test can use a plain label.
80
+ *
81
+ * ## Teardown is LEAVING `rebuilding`, which is what deletes the `closed` checks
82
+ *
83
+ * This was a `booting`/`queuedDuringBoot`/`closed` latch set plus a
84
+ * `createCoalescingRunner` over an async `restartOnce`, which re-read `closed`
85
+ * after every `await` — after the build, after the listen, between listen
86
+ * attempts — because a teardown could land at any of them. Each step is now an
87
+ * invoked actor of its own state, so `CLOSE` exits the step and stops it, and
88
+ * its outcome is never delivered: the re-check is the machine.
89
+ *
90
+ * Stopping an actor does not cancel the operation under it, though, and the
91
+ * step that was in flight is holding a server nobody else knows about — the
92
+ * one just built, or the one half-way through binding. So every step that
93
+ * holds the REPLACEMENT disposes of it when its signal aborts, after its own
94
+ * operation settles: closing a server whose `listen` is still in flight would
95
+ * let the bind complete afterwards and leak the port. That disposal is
96
+ * fire-and-forget, as the old early returns were — `close()` awaits teardown
97
+ * and the CURRENT server, never an in-flight rebuild.
98
+ *
99
+ * ## Coalescing is a flag in context, not a runner
100
+ *
101
+ * At most one rebuild runs; every `REQUEST` landing during one (or during
102
+ * boot) sets `queued`, and the rebuild's end — success, failed build, failed
103
+ * listen — re-enters `rebuilding` once if it is set. That is the
104
+ * `createCoalescingRunner` contract restated as a transition, and the policy
105
+ * is the same: a rebuild reads the files as they are WHEN IT RUNS, so N queued
106
+ * rebuilds would do the trailing one's work N times, while dropping the
107
+ * trigger would leave the newest save unserved.
108
+ *
109
+ * ## Actions never throw
110
+ *
111
+ * A throwing action ERRORS an XState actor for good, which would wedge
112
+ * watching — the old runner's "a rejection never wedges" property. The one
113
+ * effect that can throw on an ordinary path is `notify` (stderr closed by
114
+ * `aai dev | head`), so it goes through {@link report}, which falls back to
115
+ * reporting the throw itself and then swallows.
79
116
  */
80
117
  /** Attempts to bind the port during the close→listen swap. */
81
118
  const LISTEN_ATTEMPTS = 3;
82
119
  /** Backoff between those attempts. */
83
120
  const LISTEN_RETRY_DELAY_MS = 250;
121
+ /** Best-effort close: a synchronous throw is swallowed alongside a rejection. */
122
+ async function closeQuietly(ops, server) {
123
+ try {
124
+ await ops.close(server);
125
+ } catch {}
126
+ }
127
+ /**
128
+ * Notify without ever throwing. A failing notifier is reported as a failed
129
+ * restart (what reached the old `request()` catch), and a second failure is
130
+ * dropped — there is nowhere left to say it.
131
+ */
132
+ function report(ops, level, message) {
133
+ try {
134
+ ops.notify(level, message);
135
+ } catch (err) {
136
+ try {
137
+ ops.notify("error", `Restart failed: ${errorMessage$1(err)}`);
138
+ } catch {}
139
+ }
140
+ }
141
+ /**
142
+ * Run `step`, then — if the owning state was left meanwhile — close `server`,
143
+ * which nothing else will. Waiting for `step` first is the point: see the
144
+ * module comment on closing a server mid-`listen`.
145
+ */
146
+ async function disposingOnAbort(signal, ops, server, step) {
147
+ try {
148
+ return await step();
149
+ } finally {
150
+ if (signal.aborted) await closeQuietly(ops, server);
151
+ }
152
+ }
153
+ function restartMachine() {
154
+ return setup({
155
+ types: {},
156
+ actors: {
157
+ /** A server built after its state was left is closed rather than orphaned. */
158
+ build: fromPromise(async ({ input, signal }) => {
159
+ const server = await input.build();
160
+ if (signal.aborted) await closeQuietly(input, server);
161
+ return server;
162
+ }),
163
+ /** Close the OLD server so the replacement can bind its port. */
164
+ swap: fromPromise(({ input, signal }) => disposingOnAbort(signal, input.ops, input.server, () => closeQuietly(input.ops, input.old))),
165
+ listen: fromPromise(({ input, signal }) => disposingOnAbort(signal, input.ops, input.server, () => input.ops.listen(input.server))),
166
+ backoff: fromPromise(({ input, signal }) => disposingOnAbort(signal, input.ops, input.server, () => (input.ops.sleep ?? sleep)(LISTEN_RETRY_DELAY_MS))),
167
+ /** Close a replacement that never bound. Not interruptible: it IS the cleanup. */
168
+ discard: fromPromise(({ input }) => closeQuietly(input.ops, input.server)),
169
+ /** Teardown first, then the serving server; each best-effort. */
170
+ shutdown: fromPromise(async ({ input }) => {
171
+ try {
172
+ await input.ops.teardown?.();
173
+ } catch {}
174
+ if (input.current !== void 0) await closeQuietly(input.ops, input.current);
175
+ })
176
+ },
177
+ guards: {
178
+ queued: ({ context }) => context.queued,
179
+ hasCurrent: ({ context }) => context.current !== void 0,
180
+ canRetry: ({ context }) => context.attempt < LISTEN_ATTEMPTS
181
+ },
182
+ actions: {
183
+ queue: assign({ queued: true }),
184
+ /**
185
+ * Refused after a teardown, rather than orphaning the server the caller
186
+ * just built: `CLOSE` during boot found no current server and closed
187
+ * nothing, so without this the freshly listening server would keep its
188
+ * port bound for the life of the process.
189
+ */
190
+ refuseAdopt: ({ context, event }) => {
191
+ if (event.type === "ADOPT") closeQuietly(context.ops, event.server);
192
+ }
193
+ }
194
+ }).createMachine({
195
+ id: "devRestart",
196
+ context: ({ input }) => ({
197
+ ops: input,
198
+ current: void 0,
199
+ next: void 0,
200
+ old: void 0,
201
+ queued: false,
202
+ attempt: 1
203
+ }),
204
+ initial: "booting",
205
+ on: { CLOSE: { target: ".closed" } },
206
+ states: {
207
+ booting: { on: {
208
+ REQUEST: { actions: "queue" },
209
+ ADOPT: [{
210
+ guard: "queued",
211
+ target: "rebuilding",
212
+ actions: assign({ current: ({ event }) => event.server })
213
+ }, {
214
+ target: "idle",
215
+ actions: assign({ current: ({ event }) => event.server })
216
+ }]
217
+ } },
218
+ idle: { on: { REQUEST: { target: "rebuilding" } } },
219
+ rebuilding: {
220
+ entry: assign({
221
+ queued: false,
222
+ attempt: 1,
223
+ next: void 0
224
+ }),
225
+ on: { REQUEST: { actions: "queue" } },
226
+ onDone: [{
227
+ guard: "queued",
228
+ target: "rebuilding",
229
+ reenter: true
230
+ }, { target: "idle" }],
231
+ initial: "building",
232
+ states: {
233
+ building: { invoke: {
234
+ src: "build",
235
+ input: ({ context }) => context.ops,
236
+ onDone: [{
237
+ guard: "hasCurrent",
238
+ target: "swapping",
239
+ actions: assign({
240
+ next: ({ event }) => event.output,
241
+ old: ({ context }) => context.current,
242
+ current: void 0
243
+ })
244
+ }, {
245
+ target: "listening",
246
+ actions: assign({ next: ({ event }) => event.output })
247
+ }],
248
+ onError: {
249
+ target: "done",
250
+ actions: ({ context, event }) => report(context.ops, "error", `Restart failed: ${errorMessage$1(event.error)} (previous server still running)`)
251
+ }
252
+ } },
253
+ swapping: { invoke: {
254
+ src: "swap",
255
+ input: ({ context }) => ({
256
+ ops: context.ops,
257
+ server: context.next,
258
+ old: context.old
259
+ }),
260
+ onDone: {
261
+ target: "listening",
262
+ actions: assign({ old: void 0 })
263
+ }
264
+ } },
265
+ listening: { invoke: {
266
+ src: "listen",
267
+ input: ({ context }) => ({
268
+ ops: context.ops,
269
+ server: context.next
270
+ }),
271
+ onDone: {
272
+ target: "done",
273
+ actions: [assign({
274
+ current: ({ context }) => context.next,
275
+ next: void 0
276
+ }), ({ context }) => report(context.ops, "success", "Restarted")]
277
+ },
278
+ onError: [{
279
+ guard: "canRetry",
280
+ target: "backoff",
281
+ actions: assign({ attempt: ({ context }) => context.attempt + 1 })
282
+ }, {
283
+ target: "discarding",
284
+ actions: ({ context, event }) => report(context.ops, "error", `Restart failed: ${errorMessage$1(event.error)} — dev server is down; save a file to retry.`)
285
+ }]
286
+ } },
287
+ backoff: { invoke: {
288
+ src: "backoff",
289
+ input: ({ context }) => ({
290
+ ops: context.ops,
291
+ server: context.next
292
+ }),
293
+ onDone: { target: "listening" }
294
+ } },
295
+ discarding: { invoke: {
296
+ src: "discard",
297
+ input: ({ context }) => ({
298
+ ops: context.ops,
299
+ server: context.next
300
+ }),
301
+ onDone: {
302
+ target: "done",
303
+ actions: assign({ next: void 0 })
304
+ }
305
+ } },
306
+ done: { type: "final" }
307
+ }
308
+ },
309
+ /**
310
+ * Torn down. Deliberately NOT `type: "final"`: a final actor stops, and
311
+ * this one still has a job — an `ADOPT` from a boot that finished after
312
+ * Ctrl-C must close that server — and xstate warns on a send to a
313
+ * stopped actor, which `request()` after teardown would trigger.
314
+ * `REQUEST` and a second `CLOSE` are simply unhandled here.
315
+ */
316
+ closed: {
317
+ initial: "shuttingDown",
318
+ on: {
319
+ ADOPT: { actions: "refuseAdopt" },
320
+ CLOSE: {}
321
+ },
322
+ states: {
323
+ shuttingDown: { invoke: {
324
+ src: "shutdown",
325
+ input: ({ context }) => ({
326
+ ops: context.ops,
327
+ current: context.current
328
+ }),
329
+ onDone: { target: "down" },
330
+ onError: { target: "down" }
331
+ } },
332
+ down: {}
333
+ }
334
+ }
335
+ }
336
+ });
337
+ }
84
338
  /**
85
339
  * Create a {@link RestartSupervisor}. It starts in the "restarting" state:
86
340
  * callers install their watcher and call {@link RestartSupervisor.request}
@@ -88,105 +342,20 @@ const LISTEN_RETRY_DELAY_MS = 250;
88
342
  * the built server (or {@link RestartSupervisor.close} on startup failure).
89
343
  */
90
344
  function createRestartSupervisor(ops) {
91
- const wait = ops.sleep ?? sleep;
92
- let booting = true;
93
- let queuedDuringBoot = false;
94
- let closed = false;
95
- let current;
345
+ const actor = createActor(restartMachine(), { input: ops }).start();
96
346
  let cleanupPromise;
97
- /**
98
- * At most one rebuild in flight; every change landing during one collapses
99
- * into a SINGLE trailing rebuild started after it settles.
100
- *
101
- * That is exactly the repo's `createCoalescingRunner` contract, and this
102
- * module used to re-derive it with a `restarting` flag, a `pendingRestart`
103
- * flag and a `do/while` loop. Coalescing is the right policy for the same
104
- * reason it is there: a rebuild reads the files as they are WHEN IT RUNS, so
105
- * N queued rebuilds would do the trailing one's work N times, while dropping
106
- * the trigger outright would leave the newest save unserved (or, when the
107
- * in-flight rebuild died on a mid-edit syntax error, leave the server down).
108
- */
109
- const rebuilds = createCoalescingRunner(() => restartOnce());
110
- function request() {
111
- if (booting) {
112
- queuedDuringBoot = true;
113
- return;
114
- }
115
- rebuilds.trigger().catch((err) => {
116
- ops.notify("error", `Restart failed: ${errorMessage$1(err)}`);
117
- });
118
- }
119
- async function restartOnce() {
120
- if (closed) return;
121
- let newServer;
122
- try {
123
- newServer = await ops.build();
124
- } catch (err) {
125
- ops.notify("error", `Restart failed: ${errorMessage$1(err)} (previous server still running)`);
126
- return;
127
- }
128
- if (closed) {
129
- await closeQuietly(newServer);
130
- return;
131
- }
132
- if (current !== void 0) {
133
- const old = current;
134
- current = void 0;
135
- await closeQuietly(old);
136
- }
137
- try {
138
- await listenWithRetry(newServer);
139
- } catch (err) {
140
- ops.notify("error", `Restart failed: ${errorMessage$1(err)} — dev server is down; save a file to retry.`);
141
- await closeQuietly(newServer);
142
- return;
143
- }
144
- current = newServer;
145
- if (closed) {
146
- await closeQuietly(newServer);
147
- return;
148
- }
149
- ops.notify("success", "Restarted");
150
- }
151
- /**
152
- * Listen with a few short-backoff retries. During the close→listen swap the
153
- * port is momentarily free, so another process can snatch it (or the OS can
154
- * hold it in TIME_WAIT); one blind attempt would leave the dev server down
155
- * until the next file change.
156
- */
157
- async function listenWithRetry(server) {
158
- for (let attempt = 1;; attempt++) try {
159
- await ops.listen(server);
160
- return;
161
- } catch (err) {
162
- if (attempt >= LISTEN_ATTEMPTS || closed) throw err;
163
- await wait(LISTEN_RETRY_DELAY_MS);
164
- }
165
- }
166
- /** Best-effort close: a synchronous throw is swallowed alongside a rejection. */
167
- async function closeQuietly(server) {
168
- try {
169
- await ops.close(server);
170
- } catch {}
171
- }
172
347
  return {
173
- request,
174
- adopt(server) {
175
- if (closed) {
176
- closeQuietly(server);
177
- return;
178
- }
179
- current = server;
180
- booting = false;
181
- if (queuedDuringBoot) request();
182
- },
183
- current: () => current,
348
+ request: () => actor.send({ type: "REQUEST" }),
349
+ adopt: (server) => actor.send({
350
+ type: "ADOPT",
351
+ server
352
+ }),
353
+ current: () => actor.getSnapshot().context.current,
184
354
  close() {
185
- cleanupPromise ??= (async () => {
186
- closed = true;
187
- await ops.teardown?.().catch(() => void 0);
188
- if (current !== void 0) await closeQuietly(current);
189
- })();
355
+ if (cleanupPromise === void 0) {
356
+ actor.send({ type: "CLOSE" });
357
+ cleanupPromise = waitFor(actor, (s) => s.matches({ closed: "down" })).then(() => void 0);
358
+ }
190
359
  return cleanupPromise;
191
360
  }
192
361
  };
@@ -488,7 +657,7 @@ function devProxyTable(target, viteRoot) {
488
657
  * to ONE non-loopback interface was unreachable through the proxy before this and
489
658
  * still is.
490
659
  */
491
- function viteDevConfig(cwd, vitePort, backendPort, clientPlugins = []) {
660
+ function viteDevConfig(cwd, vitePort, backendPort, clientPlugins = [], publicUrl) {
492
661
  const target = `http://127.0.0.1:${backendPort}`;
493
662
  const viteRoot = path.resolve(cwd);
494
663
  const devSource = devSourceViteConfig();
@@ -504,10 +673,20 @@ function viteDevConfig(cwd, vitePort, backendPort, clientPlugins = []) {
504
673
  port: vitePort,
505
674
  strictPort: true,
506
675
  host: devBindHost() ?? DEFAULT_LISTEN_HOST,
676
+ ...omitUndefined({ allowedHosts: publicHost(publicUrl) }),
507
677
  proxy: devProxyTable(target, viteRoot)
508
678
  }
509
679
  };
510
680
  }
681
+ /** The hostname of a public URL as Vite's `allowedHosts`, or nothing to add. */
682
+ function publicHost(publicUrl) {
683
+ if (!publicUrl) return void 0;
684
+ try {
685
+ return [new URL(publicUrl).hostname];
686
+ } catch {
687
+ return;
688
+ }
689
+ }
511
690
  //#endregion
512
691
  //#region src/_dev-watch.ts
513
692
  /**
@@ -719,7 +898,7 @@ async function startDevServer(opts, seams = {}) {
719
898
  boundServer = initialServer;
720
899
  if (hasClient) {
721
900
  const clientPlugins = await defaultClientPlugins(cwd) ?? [];
722
- viteServer = await io.createViteServer(viteDevConfig(cwd, vitePort, backendPort, clientPlugins));
901
+ viteServer = await io.createViteServer(viteDevConfig(cwd, vitePort, backendPort, clientPlugins, process.env.PUBLIC_URL?.trim()));
723
902
  await viteServer.listen();
724
903
  viteServer.httpServer?.on("error", (err) => {
725
904
  ui.notify("error", `Vite dev server error: ${errorMessage$1(err)}`);
@@ -97,4 +97,10 @@ export declare function viteDevConfig(cwd: string, vitePort: number, backendPort
97
97
  * The client plugins when the project has no `vite.config.*` of its own
98
98
  * (`defaultClientPlugins`); empty when Vite loads the project's config.
99
99
  */
100
- clientPlugins?: import("vite").PluginOption[]): import("vite").InlineConfig;
100
+ clientPlugins?: import("vite").PluginOption[],
101
+ /**
102
+ * `PUBLIC_URL` (set by `--tunnel`): its host is the one non-loopback name
103
+ * Vite must answer. Vite 403s any other `Host` header, so without it a tunnel
104
+ * — and every webhook through it — is blocked before reaching the proxy.
105
+ */
106
+ publicUrl?: string): import("vite").InlineConfig;
package/dist/cli.mjs CHANGED
@@ -892,7 +892,7 @@ const dev = defineExec({
892
892
  },
893
893
  cwd: "agent",
894
894
  async run({ args, cwd, ui }) {
895
- const { executeDev } = await import("./dev-BWBDbUEb.mjs");
895
+ const { executeDev } = await import("./dev-CsdCGy8U.mjs");
896
896
  return executeDev({
897
897
  cwd,
898
898
  port: args.port,
@@ -913,7 +913,7 @@ const consoleCommand = defineExec({
913
913
  } },
914
914
  cwd: "agent",
915
915
  async run({ args, cwd, mode, ui }) {
916
- const { executeConsole } = await import("./console-Dxq26Adz.mjs");
916
+ const { executeConsole } = await import("./console-tRZbtiDe.mjs");
917
917
  return executeConsole({
918
918
  cwd,
919
919
  verbose: args.verbose,
@@ -3,7 +3,7 @@ import { a as ok, n as fail } from "./_output-DBP9Op_d.mjs";
3
3
  import { t as defaultUi } from "./_ui-Coe0zwmm.mjs";
4
4
  import { o as errorDetail, s as errorMessage } from "./_utils-BVLdBvdT.mjs";
5
5
  import { n as createWorkerEvaluator } from "./_bundler-B6v31ROV.mjs";
6
- import { loadWorker, t as resolveAgentEnv } from "./_dev-server-GoEXEVpA.mjs";
6
+ import { loadWorker, t as resolveAgentEnv } from "./_dev-server-BVADkK1M.mjs";
7
7
  import { styleText } from "node:util";
8
8
  import { spawn } from "node:child_process";
9
9
  import { connectSession, createRuntime, ensureSessionStateSchema, ensureWorkflowJournalSchema } from "@alexkroman1/aai-runtime";
@@ -164,7 +164,7 @@ async function resolveDevDeps(deps) {
164
164
  ui: deps.ui ?? defaultUi,
165
165
  startQuickTunnel: deps.startQuickTunnel ?? startQuickTunnel,
166
166
  runPublicUrlHook: deps.runPublicUrlHook ?? runPublicUrlHook,
167
- startDevServer: deps.startDevServer ?? (await import("./_dev-server-GoEXEVpA.mjs")).startDevServer
167
+ startDevServer: deps.startDevServer ?? (await import("./_dev-server-BVADkK1M.mjs")).startDevServer
168
168
  };
169
169
  }
170
170
  /**
@@ -15,10 +15,10 @@
15
15
  "publish:agent": "aai publish"
16
16
  },
17
17
  "dependencies": {
18
- "@alexkroman1/aai": "^0.14.1",
19
- "@alexkroman1/aai-cli": "^0.14.1",
20
- "@alexkroman1/aai-runtime": "^0.14.1",
21
- "@alexkroman1/aai-ui": "^0.14.1",
18
+ "@alexkroman1/aai": "^0.14.3",
19
+ "@alexkroman1/aai-cli": "^0.14.3",
20
+ "@alexkroman1/aai-runtime": "^0.14.3",
21
+ "@alexkroman1/aai-ui": "^0.14.3",
22
22
  "react": "^19.3.0",
23
23
  "react-dom": "^19.3.0",
24
24
  "tailwindcss": "^4.0.0",
@@ -0,0 +1,136 @@
1
+ // Copyright 2026 the AAI authors. MIT license.
2
+ // An EVAL: does the caller actually behave on a call? Run it with `aai eval`.
3
+ //
4
+ // `agent.test.ts` drives the API, the brief, the hand-over and the run. What
5
+ // none of that can say is whether the AGENT — a model reading
6
+ // `system-prompt.md` plus the task the call carried — opens the way an
7
+ // outbound caller should, stays inside the options it was given, and hangs up
8
+ // when it is done. Each case here is a placed call: `describeEval`'s `call` is
9
+ // the record a carrier's `start` frame produces, put through the runtime's own
10
+ // `sessionContext` step, so the brief is VERIFIED and handed to the session
11
+ // exactly as on a real call.
12
+ //
13
+ // Keyless, the model is SCRIPTED (each case's `stubReply`): that proves the
14
+ // wiring — the brief verifies, `end_call` is a tool the session can reach and
15
+ // it really hangs up — and nothing about what the agent says.
16
+ //
17
+ // What no eval here can see: anything below the audio boundary, the carrier,
18
+ // or the run that dialled. Those are the specs' and a real call's.
19
+
20
+ /**
21
+ * The def a DEPLOYED agent runs: authored, plus what `tools/` and
22
+ * `system-prompt.md` declare — `./agent.ts` alone has no `end_call`.
23
+ */
24
+ import agentDef from "virtual:aai/agent";
25
+ import { describeEval, toolArgsIn, toolNames } from "@alexkroman1/aai-runtime/testing/vitest";
26
+ import { expect } from "vitest";
27
+ import { signCall } from "./call-params.ts";
28
+
29
+ const SECRET = "eval-calls-key";
30
+ const PROMPT =
31
+ "Call Maria for Mission Dental to confirm her cleaning tomorrow at 2:30pm. " +
32
+ "If she needs to reschedule, offer Thursday at 10am or Friday at 4pm. " +
33
+ "If you get voicemail, ask her to call 415-555-0100.";
34
+
35
+ const parameters = await signCall({ id: "call_eval", prompt: PROMPT }, SECRET);
36
+
37
+ describeEval(
38
+ agentDef,
39
+ (test) => {
40
+ test(
41
+ "answers the callee's hello with who it is calling for, and why",
42
+ async ({ session }) => {
43
+ expect(session.refused).toBeUndefined();
44
+ const turn = await session.say("Hello?");
45
+
46
+ expect(turn.completed).toBe(true);
47
+ expect(turn.text).toMatch(/mission dental/i);
48
+ expect(turn.toolCalls).toEqual([]);
49
+ },
50
+ {
51
+ stubReply:
52
+ "Hi, is this Maria? I'm calling from Mission Dental about your cleaning tomorrow at 2:30.",
53
+ },
54
+ );
55
+
56
+ test(
57
+ "offers only the times it was given, and hangs up once it is settled",
58
+ async ({ session }) => {
59
+ await session.say("Hello?");
60
+ const offer = await session.say(
61
+ "Yes, this is Maria. Something came up at work — anything later this week?",
62
+ );
63
+ expect(offer.text).toMatch(/thursday/i);
64
+ expect(offer.text).toMatch(/friday/i);
65
+
66
+ const done = await session.say("Thursday at 10 works. Thanks, bye!");
67
+ expect(toolNames(done.toolCalls)).toContain("end_call");
68
+ expect(toolArgsIn(done.toolCalls, "end_call")[0]).toMatchObject({ reached: "person" });
69
+ expect(done.endedSession).toBe(true);
70
+ },
71
+ {
72
+ stubReply: [
73
+ "Hi, is this Maria? I'm calling from Mission Dental about your cleaning tomorrow at 2:30.",
74
+ "No problem. I have Thursday at 10am or Friday at 4pm.",
75
+ { tool: "end_call", args: { reached: "person" } },
76
+ "You're booked for Thursday at 10am. Goodbye!",
77
+ ],
78
+ },
79
+ );
80
+
81
+ test(
82
+ "answers a phone menu by pressing the key toward the callee, saying nothing",
83
+ async ({ session }) => {
84
+ const turn = await session.say(
85
+ "Thanks for calling. To leave a message for Maria, press 1. For all other calls, press 0.",
86
+ );
87
+ expect(toolArgsIn(turn.toolCalls, "press_keys")[0]).toMatchObject({ keys: "1" });
88
+ expect(turn.endedSession).toBe(false);
89
+ },
90
+ {
91
+ stubReply: [{ tool: "press_keys", args: { keys: "1" } }, ""],
92
+ },
93
+ );
94
+
95
+ test(
96
+ "leaves the voicemail the task asks for, then hangs up",
97
+ async ({ session }) => {
98
+ const turn = await session.say(
99
+ "Hi, you've reached Maria. I can't come to the phone right now, please leave a message after the beep.",
100
+ );
101
+ expect(turn.text).toMatch(/415.?555.?0100|four one five/i);
102
+ expect(toolArgsIn(turn.toolCalls, "end_call")[0]).toMatchObject({ reached: "voicemail" });
103
+ expect(turn.endedSession).toBe(true);
104
+ },
105
+ {
106
+ stubReply: [
107
+ { tool: "end_call", args: { reached: "voicemail" } },
108
+ "Hi Maria, this is Mission Dental about your cleaning tomorrow at 2:30. Please call us at 415-555-0100.",
109
+ ],
110
+ },
111
+ );
112
+ },
113
+ {
114
+ env: { CALLS_API_KEY: SECRET },
115
+ call: { carrier: "twilio", callId: "CA_eval", parameters },
116
+ },
117
+ );
118
+
119
+ describeEval(
120
+ agentDef,
121
+ (test) => {
122
+ test("a stream whose brief this app did not sign is refused before a word", async ({
123
+ session,
124
+ }) => {
125
+ expect(session.refused).toMatch(/unsigned|forged/);
126
+ });
127
+ },
128
+ {
129
+ env: { CALLS_API_KEY: SECRET },
130
+ call: {
131
+ carrier: "twilio",
132
+ callId: "CA_stranger",
133
+ parameters: { ...parameters, p0: "Call the bank." },
134
+ },
135
+ },
136
+ );