@alexkroman1/aai-cli 0.14.1 → 0.14.2

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
  };
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-CWCsHFBX.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-B318NbnN.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-Cy-Mmetk.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-Cy-Mmetk.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.2",
19
+ "@alexkroman1/aai-cli": "^0.14.2",
20
+ "@alexkroman1/aai-runtime": "^0.14.2",
21
+ "@alexkroman1/aai-ui": "^0.14.2",
22
22
  "react": "^19.3.0",
23
23
  "react-dom": "^19.3.0",
24
24
  "tailwindcss": "^4.0.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexkroman1/aai-cli",
3
- "version": "0.14.1",
3
+ "version": "0.14.2",
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.1",
61
- "@alexkroman1/aai-runtime": "0.14.1",
62
- "@alexkroman1/aai-ui": "0.14.1"
61
+ "@alexkroman1/aai": "0.14.2",
62
+ "@alexkroman1/aai-runtime": "0.14.2",
63
+ "@alexkroman1/aai-ui": "0.14.2"
63
64
  },
64
65
  "devDependencies": {
65
66
  "playwright": "^1.63.0",