@powerhousedao/clint 6.3.0-dev.9 → 6.4.0-next.1

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.
Files changed (93) hide show
  1. package/dist/build-DZIv63eB.mjs +77 -0
  2. package/dist/build-DZIv63eB.mjs.map +1 -0
  3. package/dist/{build-skills-BnqGyuCH.mjs → build-skills-XkfkDhWl.mjs} +15 -6
  4. package/dist/build-skills-XkfkDhWl.mjs.map +1 -0
  5. package/dist/dist-Bd6hUl0J.mjs +655 -0
  6. package/dist/dist-Bd6hUl0J.mjs.map +1 -0
  7. package/dist/glob-CGjvhxgW.mjs +48 -0
  8. package/dist/glob-CGjvhxgW.mjs.map +1 -0
  9. package/dist/index-C3-HSfKb.d.mts +389 -0
  10. package/dist/index-C3-HSfKb.d.mts.map +1 -0
  11. package/dist/index.d.mts +55 -303
  12. package/dist/index.d.mts.map +1 -1
  13. package/dist/index.mjs +7 -8
  14. package/dist/integrations/mastra/index.d.mts +248 -0
  15. package/dist/integrations/mastra/index.d.mts.map +1 -0
  16. package/dist/integrations/mastra/index.mjs +509 -0
  17. package/dist/integrations/mastra/index.mjs.map +1 -0
  18. package/dist/integrations/powerhouse/index.d.mts +4 -0
  19. package/dist/integrations/powerhouse/index.mjs +3 -0
  20. package/dist/markdown-BUeGwhbR.mjs +1588 -0
  21. package/dist/markdown-BUeGwhbR.mjs.map +1 -0
  22. package/dist/powerhouse-3XZmdY3_.mjs +1922 -0
  23. package/dist/powerhouse-3XZmdY3_.mjs.map +1 -0
  24. package/dist/{proxy-BFR8GScT.mjs → proxy-ji3EHzLn.mjs} +128 -28
  25. package/dist/proxy-ji3EHzLn.mjs.map +1 -0
  26. package/dist/remote-reactor-oBsHphPT.mjs +69 -0
  27. package/dist/remote-reactor-oBsHphPT.mjs.map +1 -0
  28. package/dist/{start-b7Mn2cxB.mjs → repl-Czb7u0x_.mjs} +6 -29
  29. package/dist/repl-Czb7u0x_.mjs.map +1 -0
  30. package/dist/runners/cli-runner.d.mts +339 -0
  31. package/dist/runners/cli-runner.d.mts.map +1 -0
  32. package/dist/runners/cli-runner.mjs +324 -0
  33. package/dist/runners/cli-runner.mjs.map +1 -0
  34. package/dist/runners/mastra-runner.d.mts +5 -3
  35. package/dist/runners/mastra-runner.d.mts.map +1 -1
  36. package/dist/runners/mastra-runner.mjs +10 -60
  37. package/dist/runners/mastra-runner.mjs.map +1 -1
  38. package/dist/runners/proxy-runner.d.mts +281 -0
  39. package/dist/runners/proxy-runner.d.mts.map +1 -0
  40. package/dist/runners/proxy-runner.mjs +91 -0
  41. package/dist/runners/proxy-runner.mjs.map +1 -0
  42. package/dist/schema-BEKAZGyT.mjs +47 -0
  43. package/dist/schema-BEKAZGyT.mjs.map +1 -0
  44. package/dist/{src-BebNN3xc.mjs → src-055YwI8s.mjs} +395 -1481
  45. package/dist/src-055YwI8s.mjs.map +1 -0
  46. package/dist/start-BHn9LIyX.mjs +37 -0
  47. package/dist/start-BHn9LIyX.mjs.map +1 -0
  48. package/dist/store-CxqB-OrX.mjs +101 -0
  49. package/dist/store-CxqB-OrX.mjs.map +1 -0
  50. package/dist/{stream-DVuufwIj.mjs → stream-BguHx7vC.mjs} +4 -2
  51. package/dist/{stream-DVuufwIj.mjs.map → stream-BguHx7vC.mjs.map} +1 -1
  52. package/dist/testing/index.d.mts +81 -0
  53. package/dist/testing/index.d.mts.map +1 -0
  54. package/dist/testing/index.mjs +131 -0
  55. package/dist/testing/index.mjs.map +1 -0
  56. package/dist/{types-CRkoD-Mm.d.mts → types-CF6GuPJd.d.mts} +241 -261
  57. package/dist/types-CF6GuPJd.d.mts.map +1 -0
  58. package/dist/types-CbHJ-ZnH.d.mts +60 -0
  59. package/dist/types-CbHJ-ZnH.d.mts.map +1 -0
  60. package/package.json +44 -25
  61. package/dist/build-skills-BnqGyuCH.mjs.map +0 -1
  62. package/dist/dist-CUltriBW.mjs +0 -1628
  63. package/dist/dist-CUltriBW.mjs.map +0 -1
  64. package/dist/drive-Bu9zoFrO.mjs +0 -85
  65. package/dist/drive-Bu9zoFrO.mjs.map +0 -1
  66. package/dist/esm-C1DOsF1a.mjs +0 -13140
  67. package/dist/esm-C1DOsF1a.mjs.map +0 -1
  68. package/dist/events-BnwGFTjv.mjs +0 -237
  69. package/dist/events-BnwGFTjv.mjs.map +0 -1
  70. package/dist/folders-BYO1Wqqb.mjs +0 -256
  71. package/dist/folders-BYO1Wqqb.mjs.map +0 -1
  72. package/dist/local-signer-EFzJV3bn.mjs +0 -128
  73. package/dist/local-signer-EFzJV3bn.mjs.map +0 -1
  74. package/dist/markdown-D-sP2zw_.mjs +0 -275
  75. package/dist/markdown-D-sP2zw_.mjs.map +0 -1
  76. package/dist/proxy-BFR8GScT.mjs.map +0 -1
  77. package/dist/proxy-routes-DP3ztsnS.mjs +0 -215
  78. package/dist/proxy-routes-DP3ztsnS.mjs.map +0 -1
  79. package/dist/reactor-C9VIUX1H.mjs +0 -51
  80. package/dist/reactor-C9VIUX1H.mjs.map +0 -1
  81. package/dist/runners/clint-runner.d.mts +0 -398
  82. package/dist/runners/clint-runner.d.mts.map +0 -1
  83. package/dist/runners/clint-runner.mjs +0 -519
  84. package/dist/runners/clint-runner.mjs.map +0 -1
  85. package/dist/services-9E-r0nWl.mjs +0 -999
  86. package/dist/services-9E-r0nWl.mjs.map +0 -1
  87. package/dist/src-BebNN3xc.mjs.map +0 -1
  88. package/dist/start-b7Mn2cxB.mjs.map +0 -1
  89. package/dist/subscriptions-CfiflAsI.mjs +0 -38
  90. package/dist/subscriptions-CfiflAsI.mjs.map +0 -1
  91. package/dist/switchboard-CyvOavqL.mjs +0 -57
  92. package/dist/switchboard-CyvOavqL.mjs.map +0 -1
  93. package/dist/types-CRkoD-Mm.d.mts.map +0 -1
@@ -1,28 +1,24 @@
1
- import { a as scanProjects, c as checkCommand, d as isPortFree, f as getSchemaFields, l as checkPort, n as defineService, o as killTree, p as slugToTitle, r as resolveServiceName, s as supervisedSpawnOptions, t as createServiceManager } from "./services-9E-r0nWl.mjs";
2
- import { a as getGhostSuggestion, i as getCompletions, o as formatStreamChunk, r as getCompletionSuffix, t as renderMarkdown } from "./markdown-D-sP2zw_.mjs";
3
- import { i as buildSwitchboardRoutes, n as buildSwitchboardProxyUrls, o as deriveBasePath, t as buildServiceRoutes, u as resolveImplicitProxyRoot } from "./proxy-routes-DP3ztsnS.mjs";
4
- import { n as createServiceCommands, t as createEventBus } from "./events-BnwGFTjv.mjs";
5
- import { t as createProxyServer } from "./proxy-BFR8GScT.mjs";
6
- import "./reactor-C9VIUX1H.mjs";
7
- import "./switchboard-CyvOavqL.mjs";
8
- import "./folders-BYO1Wqqb.mjs";
9
- import { createRequire } from "node:module";
10
- import fs, { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
1
+ import { n as slugToTitle, t as getSchemaFields } from "./schema-BEKAZGyT.mjs";
2
+ import { M as createDocumentChangeTrigger, N as defineCommand } from "./powerhouse-3XZmdY3_.mjs";
3
+ import { a as getGhostSuggestion, b as supervisedSpawnOptions, d as watchLogFile, i as getCompletions, l as resolveServiceName, o as createServiceManager, p as scanProjects, r as getCompletionSuffix, s as defineService, t as renderMarkdown, u as sanitizeLogText, v as killTree, x as formatStreamChunk, y as superviseChild } from "./markdown-BUeGwhbR.mjs";
4
+ import { n as createWorkdirStore, t as createMemoryWorkdirStore } from "./store-CxqB-OrX.mjs";
5
+ import "./proxy-ji3EHzLn.mjs";
6
+ import fs, { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
11
7
  import path, { basename, dirname, join, resolve } from "node:path";
12
8
  import { fileURLToPath } from "node:url";
13
9
  import { z } from "zod";
14
10
  import { Command } from "commander";
15
- import { spawn } from "node:child_process";
16
- import crypto, { randomBytes, randomUUID } from "node:crypto";
17
- import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
11
+ import { randomBytes, randomUUID } from "node:crypto";
18
12
  import { homedir } from "node:os";
13
+ import { spawn } from "node:child_process";
19
14
  import Handlebars from "handlebars";
15
+ import { EventEmitter } from "node:events";
20
16
  //#region src/core/pkg.ts
21
17
  /**
22
18
  * Read CLI identity from the implementation project's package.json.
23
19
  *
24
20
  * ```ts
25
- * import { readPackageInfo } from '@powerhousedao/ph-clint';
21
+ * import { readPackageInfo } from '@powerhousedao/clint';
26
22
  *
27
23
  * const pkg = readPackageInfo(import.meta.url);
28
24
  * export const CLI_ROOT = pkg.root;
@@ -32,12 +28,14 @@ import Handlebars from "handlebars";
32
28
  */
33
29
  /**
34
30
  * Read package identity from the nearest `package.json` above the calling
35
- * source file. Pass `import.meta.url` — the function resolves the project
36
- * root as the parent directory of the file's directory (i.e. `src/config.ts`
37
- * → project root is `..`).
31
+ * source file. Pass `import.meta.url`: the search starts in that file's
32
+ * directory and walks up to the filesystem root, so a source file at any
33
+ * depth (`src/config.ts`, `cli/src/config.ts`) and a bundle
34
+ * (`node_modules/<pkg>/dist/node/cli/index.mjs`) both read their own
35
+ * package's. That package.json must carry a `name` and a `version`.
38
36
  */
39
37
  function readPackageInfo(importMetaUrl) {
40
- const root = path.resolve(path.dirname(fileURLToPath(importMetaUrl)), "..");
38
+ const root = nearestPackageRoot(path.dirname(fileURLToPath(importMetaUrl)));
41
39
  const raw = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8"));
42
40
  const name = raw.name?.replace(/^@[^/]+\//, "");
43
41
  if (!name) throw new Error(`No "name" in ${root}/package.json`);
@@ -48,29 +46,12 @@ function readPackageInfo(importMetaUrl) {
48
46
  version: raw.version
49
47
  };
50
48
  }
51
- //#endregion
52
- //#region src/core/command.ts
53
- /**
54
- * Define a command — the atomic unit of ph-clint.
55
- * Compatible with Mastra createTool() shape.
56
- */
57
- function defineCommand(options) {
58
- if (options.positional && options.positional.length > 0) {
59
- const fields = getSchemaFields(options.inputSchema);
60
- const fieldMap = new Map(fields.map((f) => [f.key, f]));
61
- const seen = /* @__PURE__ */ new Set();
62
- let sawOptional = false;
63
- for (const key of options.positional) {
64
- const field = fieldMap.get(key);
65
- if (!field) throw new Error(`Command '${options.id}': positional field '${key}' is not in inputSchema`);
66
- if (seen.has(key)) throw new Error(`Command '${options.id}': positional field '${key}' listed more than once`);
67
- seen.add(key);
68
- const isOptional = field.isOptional || field.hasDefault;
69
- if (sawOptional && !isOptional) throw new Error(`Command '${options.id}': required positional '${key}' may not follow an optional positional`);
70
- if (isOptional) sawOptional = true;
71
- }
49
+ /** The first directory from `start` up that holds a package.json. */
50
+ function nearestPackageRoot(start) {
51
+ for (let dir = start;; dir = path.dirname(dir)) {
52
+ if (existsSync(path.join(dir, "package.json"))) return dir;
53
+ if (path.dirname(dir) === dir) throw new Error(`No package.json in ${start} or any directory above it`);
72
54
  }
73
- return options;
74
55
  }
75
56
  //#endregion
76
57
  //#region src/core/errors.ts
@@ -109,207 +90,6 @@ function createLogger(level = "info", sink = (msg) => process.stderr.write(msg +
109
90
  };
110
91
  }
111
92
  //#endregion
112
- //#region src/integrations/powerhouse/connect.ts
113
- /**
114
- * Create a ServiceDefinition for Connect.
115
- *
116
- * Connect runs as a managed child process via ServiceManager, persisting
117
- * beyond CLI exit. It serves the Powerhouse Connect web UI pointing at
118
- * the Switchboard's drive URL.
119
- */
120
- function connectServiceDefinition(connectConfig) {
121
- const serviceName = connectConfig.name ?? "connect";
122
- const servicePort = connectConfig.port;
123
- const isStaticMode = !!connectConfig.assetsDir;
124
- return {
125
- id: serviceName,
126
- name: serviceName,
127
- description: "Powerhouse Connect web interface",
128
- command: ({ params }) => {
129
- const p = params?.port ?? servicePort;
130
- if (isStaticMode) return `npx --no-install ph-cli connect preview --outDir ${JSON.stringify(connectConfig.assetsDir)} --port ${p}`;
131
- return `ph connect --port ${p}`;
132
- },
133
- env: ({ params }) => ({
134
- PH_CONNECT_DEFAULT_DRIVES_URL: params?.driveUrl ?? "",
135
- PH_CONNECT_DRIVES_PRESERVE_STRATEGY: "preserve-all",
136
- ...connectConfig.registryUrl ? { PH_CONNECT_PACKAGES_REGISTRY: connectConfig.registryUrl } : {}
137
- }),
138
- preflight: [...isStaticMode ? [] : [checkCommand("ph", { hint: "Install the Powerhouse CLI: npm install -g ph-cli" })], checkPort((ctx) => ctx.params?.port ?? servicePort, serviceName)],
139
- readiness: {
140
- patterns: [{
141
- name: "connect",
142
- pattern: /Local:\s*(https?:\/\/[^\s]+)/,
143
- captures: { "connect-studio": {
144
- group: 1,
145
- type: "website",
146
- proxyRoot: true
147
- } }
148
- }],
149
- timeout: 3e4
150
- },
151
- shutdown: {
152
- signal: "SIGTERM",
153
- timeout: 5e3
154
- },
155
- restart: {
156
- enabled: false,
157
- maxRetries: 0,
158
- delay: 0
159
- }
160
- };
161
- }
162
- //#endregion
163
- //#region src/integrations/powerhouse/ports.ts
164
- /**
165
- * Port derivation and resolution for per-CLI namespacing.
166
- *
167
- * When multiple ph-clint CLIs run simultaneously, they need different default
168
- * ports and service names. This module provides deterministic hash-based port
169
- * defaults and async port scanning.
170
- */
171
- /**
172
- * DJB2 hash seeded with a salt → port in range 10000–59900.
173
- *
174
- * Deterministic: same (cliName, salt) always produces the same port.
175
- */
176
- function defaultPort(cliName, salt) {
177
- const input = `${cliName}:${salt}`;
178
- let hash = 5381;
179
- for (let i = 0; i < input.length; i++) hash = (hash << 5) + hash + input.charCodeAt(i) >>> 0;
180
- const raw = 1e4 + hash % 49901;
181
- return Math.round(raw / 10) * 10;
182
- }
183
- /**
184
- * Scan [port, port+range-1] for the first free port.
185
- * Throws with a clear error if no port in the range is available.
186
- *
187
- * @param port Base port to start scanning from.
188
- * @param range Number of ports to scan (default 1).
189
- * @param label Human-readable label for error messages.
190
- */
191
- async function resolvePort(port, range, label) {
192
- for (let p = port; p < port + range; p++) if (await isPortFree(p)) return p;
193
- if (range === 1) throw new Error(`${label} port ${port} is already in use\n Hint: Stop the process using port ${port}, or use a different port`);
194
- throw new Error(`${label}: no free port in range ${port}–${port + range - 1}\n Hint: Free a port in this range, or configure a different port`);
195
- }
196
- /**
197
- * Stamp port and name defaults onto switchboard/connect sub-configs.
198
- *
199
- * Called synchronously in configureReactor() — no port scanning here,
200
- * just default derivation. The actual port scan (resolvePort) happens
201
- * later in startSwitchboardLayer() / connect preflight.
202
- */
203
- function resolveReactorDefaults(cliName, config) {
204
- const result = {};
205
- if (config.switchboard) result.switchboard = {
206
- ...config.switchboard,
207
- port: config.switchboard.port ?? defaultPort(cliName, "switchboard"),
208
- name: config.switchboard.name ?? `${cliName}-api`
209
- };
210
- if (config.connect) result.connect = {
211
- ...config.connect,
212
- port: config.connect.port ?? defaultPort(cliName, "connect"),
213
- name: config.connect.name ?? `${cliName}-studio`
214
- };
215
- return result;
216
- }
217
- //#endregion
218
- //#region src/core/store.ts
219
- /**
220
- * Read a JSON file, returning `fallback` on ENOENT.
221
- */
222
- async function readJson(filePath, fallback) {
223
- try {
224
- const raw = await readFile(filePath, "utf8");
225
- return JSON.parse(raw);
226
- } catch (err) {
227
- if (err.code === "ENOENT") return fallback;
228
- throw err;
229
- }
230
- }
231
- /**
232
- * Atomic JSON write: write to temp file, then rename.
233
- */
234
- async function writeJson(filePath, value) {
235
- const dir = dirname(filePath);
236
- await mkdir(dir, { recursive: true });
237
- const tmp = join(dir, `.tmp-${randomBytes(6).toString("hex")}`);
238
- try {
239
- await writeFile(tmp, JSON.stringify(value, null, 2) + "\n", "utf8");
240
- await rename(tmp, filePath);
241
- } catch (err) {
242
- try {
243
- await unlink(tmp);
244
- } catch {}
245
- throw err;
246
- }
247
- }
248
- function assertJsonFilename(filename) {
249
- if (!filename.endsWith(".json")) throw new Error(`Filename must end with .json: ${filename}`);
250
- }
251
- /**
252
- * Create a file-based WorkdirStore.
253
- *
254
- * @param cliWorkdir Working directory (resolved to absolute via `path.resolve(cwd, cliWorkdir)`).
255
- * @param cliName CLI name, used to namespace under `.ph/`.
256
- */
257
- function createWorkdirStore(cliWorkdir, cliName) {
258
- const workdir = resolve(process.cwd(), cliWorkdir);
259
- const storeRoot = join(workdir, ".ph", cliName);
260
- const localConfigPath = join(workdir, ".ph", `${cliName}.config.local.json`);
261
- return {
262
- getWorkdir: () => workdir,
263
- getLocalConfigPath: () => localConfigPath,
264
- getStoreFolder: (path) => path ? join(storeRoot, path) : storeRoot,
265
- async loadJsonObject(filename, fallback) {
266
- assertJsonFilename(filename);
267
- return readJson(join(storeRoot, filename), fallback);
268
- },
269
- async storeJsonObject(filename, value) {
270
- assertJsonFilename(filename);
271
- return writeJson(join(storeRoot, filename), value);
272
- },
273
- async loadLocalConfig(fallback) {
274
- return readJson(localConfigPath, fallback);
275
- },
276
- async storeLocalConfig(value) {
277
- return writeJson(localConfigPath, value);
278
- }
279
- };
280
- }
281
- /**
282
- * Create an in-memory WorkdirStore for testing or when no persistence is needed.
283
- *
284
- * @param cliWorkdir Working directory (defaults to `'.'`, resolved to absolute).
285
- * @param cliName CLI name (defaults to `'test'`).
286
- */
287
- function createMemoryWorkdirStore(cliWorkdir = ".", cliName = "test") {
288
- const workdir = resolve(process.cwd(), cliWorkdir);
289
- const storeRoot = join(workdir, ".ph", cliName);
290
- const localConfigPath = join(workdir, ".ph", `${cliName}.config.local.json`);
291
- const data = /* @__PURE__ */ new Map();
292
- return {
293
- getWorkdir: () => workdir,
294
- getLocalConfigPath: () => localConfigPath,
295
- getStoreFolder: (path) => path ? join(storeRoot, path) : storeRoot,
296
- async loadJsonObject(filename, fallback) {
297
- assertJsonFilename(filename);
298
- return data.has(filename) ? data.get(filename) : fallback;
299
- },
300
- async storeJsonObject(filename, value) {
301
- assertJsonFilename(filename);
302
- data.set(filename, value);
303
- },
304
- async loadLocalConfig(fallback) {
305
- return data.has("__local_config__") ? data.get("__local_config__") : fallback;
306
- },
307
- async storeLocalConfig(value) {
308
- data.set("__local_config__", value);
309
- }
310
- };
311
- }
312
- //#endregion
313
93
  //#region src/core/config.ts
314
94
  /**
315
95
  * Convert a camelCase string to UPPER_SNAKE_CASE.
@@ -759,6 +539,214 @@ function generateConfigCommandHelp(cliName, configSchema, workdir, sensitiveKeys
759
539
  return lines.join("\n");
760
540
  }
761
541
  //#endregion
542
+ //#region src/core/service-command.ts
543
+ /**
544
+ * Format a service instance status line for display.
545
+ */
546
+ function formatStatus(s) {
547
+ const parts = [`${s.status === "ready" ? "●" : s.status === "starting" ? "◐" : s.status === "failed" ? "✗" : s.status === "stopping" ? "◑" : s.status === "stopped" ? "■" : "○"} ${s.name} [${s.status}]`];
548
+ if (s.instanceId && s.instanceId !== s.serviceId) parts.push(`(${s.instanceId})`);
549
+ if (s.workdir) parts.push(path.basename(s.workdir));
550
+ if (s.pid) parts.push(`pid ${s.pid}`);
551
+ if (s.endpoints) {
552
+ const ep = Object.entries(s.endpoints).map(([k, v]) => `${k}=${v}`);
553
+ if (ep.length) parts.push(ep.join(" "));
554
+ }
555
+ if (s.workdir) parts.push(s.workdir);
556
+ if (s.error) parts.push(`error: ${s.error}`);
557
+ if (s.restartAttempt) parts.push(`restart #${s.restartAttempt}`);
558
+ return parts.join(" ");
559
+ }
560
+ /**
561
+ * Create per-service commands for a service definition.
562
+ *
563
+ * For service `id: 'vetra'`, generates:
564
+ * - vetra-start: Start the service
565
+ * - vetra-stop: Stop the service
566
+ * - vetra-restart: Restart the service
567
+ * - vetra-ps: Show service status
568
+ * - vetra-logs: Tail service logs
569
+ * - vetra-manage: Open interactive panel (REPL only)
570
+ */
571
+ function createServiceCommands(def) {
572
+ const { id } = def;
573
+ const isMultiInstance = (def.maxInstances ?? 1) > 1;
574
+ const startFields = {};
575
+ if (isMultiInstance) startFields.name = z.string().optional().describe("Instance name (for multi-instance services)");
576
+ startFields.workdir = z.string().optional().describe("Working directory for the service");
577
+ if (def.paramsSchema) {
578
+ const paramFields = getSchemaFields(def.paramsSchema);
579
+ for (const field of paramFields) if (def.paramsSchema instanceof z.ZodObject) {
580
+ const shape = def.paramsSchema.shape;
581
+ if (shape[field.key]) startFields[field.key] = shape[field.key];
582
+ }
583
+ }
584
+ const startSchema = z.object(startFields);
585
+ const instanceFields = {};
586
+ if (isMultiInstance) instanceFields.instance = z.string().optional().describe("Instance ID (omit for all)");
587
+ const commands = [];
588
+ commands.push({
589
+ id: `${id}-start`,
590
+ description: `Start ${resolveServiceName(def)}`,
591
+ inputSchema: startSchema,
592
+ execute: async (rawInput, context) => {
593
+ const input = rawInput;
594
+ const services = context.services;
595
+ if (!services) throw new Error("No services configured");
596
+ try {
597
+ const params = {};
598
+ if (def.paramsSchema) {
599
+ const paramFields = getSchemaFields(def.paramsSchema);
600
+ for (const field of paramFields) if (input[field.key] !== void 0) params[field.key] = input[field.key];
601
+ }
602
+ const rawWorkdir = input.workdir;
603
+ const cwd = (rawWorkdir ? path.resolve(context.workdir, rawWorkdir) : void 0) ?? context.workdir;
604
+ const instanceId = await services.start(id, {
605
+ name: input.name,
606
+ workdir: cwd,
607
+ cwd,
608
+ params: Object.keys(params).length > 0 ? params : void 0
609
+ });
610
+ return { text: formatStatus(services.list(id).find((s) => s.instanceId === instanceId)) };
611
+ } catch (err) {
612
+ const msg = err instanceof Error ? err.message : String(err);
613
+ return { text: `✗ ${id}: ${msg}` };
614
+ }
615
+ }
616
+ });
617
+ commands.push({
618
+ id: `${id}-stop`,
619
+ description: `Stop ${resolveServiceName(def)}`,
620
+ inputSchema: z.object(instanceFields),
621
+ execute: async (rawInput, context) => {
622
+ const input = rawInput;
623
+ const services = context.services;
624
+ if (!services) throw new Error("No services configured");
625
+ try {
626
+ await services.stop(id, input.instance);
627
+ return { text: "" };
628
+ } catch (err) {
629
+ const msg = err instanceof Error ? err.message : String(err);
630
+ return { text: `✗ ${id}: ${msg}` };
631
+ }
632
+ }
633
+ });
634
+ commands.push({
635
+ id: `${id}-restart`,
636
+ description: `Restart ${resolveServiceName(def)}`,
637
+ inputSchema: z.object(instanceFields),
638
+ execute: async (rawInput, context) => {
639
+ const input = rawInput;
640
+ const services = context.services;
641
+ if (!services) throw new Error("No services configured");
642
+ try {
643
+ const running = services.list(id).filter((s) => s.status === "ready" || s.status === "starting");
644
+ let prevWorkdir;
645
+ let prevParams;
646
+ let prevName;
647
+ if (running.length > 0) {
648
+ const instance = running[0];
649
+ prevWorkdir = instance.workdir;
650
+ prevParams = instance.params;
651
+ if (instance.instanceId?.includes(":")) prevName = instance.instanceId.split(":")[1];
652
+ await services.stop(id, input.instance);
653
+ }
654
+ const cwd = prevWorkdir ?? context.workdir;
655
+ const instanceId = await services.start(id, {
656
+ workdir: cwd,
657
+ cwd,
658
+ params: prevParams,
659
+ name: prevName
660
+ });
661
+ return { text: formatStatus(services.list(id).find((s) => s.instanceId === instanceId)) };
662
+ } catch (err) {
663
+ const msg = err instanceof Error ? err.message : String(err);
664
+ return { text: `✗ ${id}: ${msg}` };
665
+ }
666
+ }
667
+ });
668
+ commands.push({
669
+ id: `${id}-ps`,
670
+ description: `Show ${resolveServiceName(def)} status`,
671
+ inputSchema: z.object({}),
672
+ execute: async (_input, context) => {
673
+ const services = context.services;
674
+ if (!services) throw new Error("No services configured");
675
+ const all = services.list(id);
676
+ if (all.length === 0) return { text: `No instances of ${id}` };
677
+ return {
678
+ text: all.map(formatStatus).join("\n"),
679
+ data: all
680
+ };
681
+ }
682
+ });
683
+ const logsFields = {
684
+ lines: z.coerce.number().default(50).describe("Number of log lines to show"),
685
+ instance: z.string().optional().describe("Instance ID (use -ps to find it)")
686
+ };
687
+ commands.push({
688
+ id: `${id}-logs`,
689
+ description: `Show ${resolveServiceName(def)} logs`,
690
+ inputSchema: z.object(logsFields),
691
+ execute: async (rawInput, context) => {
692
+ const input = rawInput;
693
+ const services = context.services;
694
+ if (!services) throw new Error("No services configured");
695
+ return { text: services.logs(id, input.instance, input.lines) || "No logs available" };
696
+ }
697
+ });
698
+ commands.push({
699
+ id: `${id}-manage`,
700
+ description: `Open ${resolveServiceName(def)} management panel (REPL only)`,
701
+ inputSchema: z.object({}),
702
+ execute: async (_input, context) => {
703
+ const services = context.services;
704
+ if (!services) throw new Error("No services configured");
705
+ return { text: services.list(id).map(formatStatus).join("\n") };
706
+ }
707
+ });
708
+ if (def.projectScanner) commands.push({
709
+ id: `${id}-ls`,
710
+ description: `List ${resolveServiceName(def)} projects in the working directory`,
711
+ inputSchema: z.object({}),
712
+ execute: async (_input, context) => {
713
+ const services = context.services;
714
+ if (!services) throw new Error("No services configured");
715
+ const projects = services.scanProjects(id, context.workdir);
716
+ if (projects.length === 0) return {
717
+ text: `No ${resolveServiceName(def)} projects found`,
718
+ data: []
719
+ };
720
+ if (projects.some((p) => p.documentId)) {
721
+ const header = " Name Location Document ID Type";
722
+ const sep = " " + "-".repeat(83);
723
+ const lines = projects.map((p) => {
724
+ const rel = path.relative(context.workdir, p.path);
725
+ const display = rel ? "./" + rel : ".";
726
+ const docId = p.documentId ? p.documentId.slice(0, 36) : "(none)";
727
+ const docType = p.documentType ?? "-";
728
+ return ` ${p.name.padEnd(20)}${display.padEnd(22)}${docId.padEnd(37)}${docType}`;
729
+ });
730
+ return {
731
+ text: `Found ${projects.length} project(s):\n${header}\n${sep}\n${lines.join("\n")}`,
732
+ data: projects
733
+ };
734
+ } else {
735
+ const lines = projects.map((p) => {
736
+ const rel = path.relative(context.workdir, p.path);
737
+ const display = rel ? "./" + rel : ".";
738
+ return ` ${p.name} ${display}`;
739
+ });
740
+ return {
741
+ text: `Found ${projects.length} project(s):\n${lines.join("\n")}`,
742
+ data: projects
743
+ };
744
+ }
745
+ }
746
+ });
747
+ return commands;
748
+ }
749
+ //#endregion
762
750
  //#region src/core/help-command.ts
763
751
  const PREAMBLE = "As a CLI-first agent, your tools map directly onto CLI commands that the user can invoke through the command line directly, in interactive mode, or through you. Use the /cli-docs tool to learn more about the CLI capabilities and your own tools.";
764
752
  /**
@@ -1074,6 +1062,28 @@ function createSkillCommands(skills, skillConfigs) {
1074
1062
  });
1075
1063
  }
1076
1064
  //#endregion
1065
+ //#region src/core/events.ts
1066
+ /**
1067
+ * Create an event bus — a central EventEmitter-based bus for decoupled communication.
1068
+ *
1069
+ * The runtime is untyped (plain EventEmitter under the hood). The `R` generic
1070
+ * only shapes the static typing of `emit` / `on` / `off` for framework events.
1071
+ */
1072
+ function createEventBus() {
1073
+ const emitter = new EventEmitter();
1074
+ return {
1075
+ emit: ((event, data) => {
1076
+ emitter.emit(event, data);
1077
+ }),
1078
+ on: ((event, handler) => {
1079
+ emitter.on(event, handler);
1080
+ }),
1081
+ off: ((event, handler) => {
1082
+ emitter.off(event, handler);
1083
+ })
1084
+ };
1085
+ }
1086
+ //#endregion
1077
1087
  //#region src/core/processes.ts
1078
1088
  /**
1079
1089
  * Create a process manager for running bounded shell commands.
@@ -1102,10 +1112,9 @@ function createProcessManager() {
1102
1112
  ...opts.env
1103
1113
  } : void 0
1104
1114
  });
1115
+ superviseChild(child);
1105
1116
  function killProcess() {
1106
- try {
1107
- if (child.pid) killTree(child.pid, "SIGTERM");
1108
- } catch {}
1117
+ if (child.pid) killTree(child.pid, "SIGTERM");
1109
1118
  }
1110
1119
  const handle = {
1111
1120
  label,
@@ -1417,6 +1426,70 @@ function createRoutine(options) {
1417
1426
  return routine;
1418
1427
  }
1419
1428
  //#endregion
1429
+ //#region src/core/member-services.ts
1430
+ /**
1431
+ * The members of the compound a CLI is the foreground member of, as a
1432
+ * ServiceManager, so the panel and the log calls show them next to the
1433
+ * CLI's own services (plan section 2a). A member is one instance: its
1434
+ * service id and instance id are its name. The compound owns their life:
1435
+ * start and stop refuse, and stopAll leaves them to it.
1436
+ */
1437
+ function createMemberServiceManager(members) {
1438
+ const memberOf = (id) => {
1439
+ const member = members().find((m) => m.name === id);
1440
+ if (!member) throw new Error(`Unknown service: ${id}`);
1441
+ return member;
1442
+ };
1443
+ const instanceOf = (member) => ({
1444
+ serviceId: member.name,
1445
+ instanceId: member.name,
1446
+ name: member.name,
1447
+ status: member.status,
1448
+ ...member.pid !== void 0 ? { pid: member.pid } : {},
1449
+ endpoints: { ...member.endpoints },
1450
+ ...member.error !== void 0 ? { error: member.error } : {}
1451
+ });
1452
+ const owned = (id) => /* @__PURE__ */ new Error(`${id} is a member of the stack this CLI runs in: it starts and stops with the stack.`);
1453
+ return {
1454
+ start(id) {
1455
+ memberOf(id);
1456
+ return Promise.reject(owned(id));
1457
+ },
1458
+ stop(id) {
1459
+ memberOf(id);
1460
+ return Promise.reject(owned(id));
1461
+ },
1462
+ stopAll: () => Promise.resolve(),
1463
+ list(serviceId) {
1464
+ return members().filter((m) => serviceId === void 0 || m.name === serviceId).map(instanceOf);
1465
+ },
1466
+ getDefinition: () => void 0,
1467
+ logs(id, _instanceId, lines = 50) {
1468
+ const member = memberOf(id);
1469
+ const footer = `\n— ${member.name} [${member.status}] log`;
1470
+ if (!member.logFile) return `${member.name} runs in this process: its output is this process's.${footer}`;
1471
+ try {
1472
+ const content = fs.readFileSync(member.logFile, "utf-8");
1473
+ const all = sanitizeLogText(content).split("\n");
1474
+ return sanitizeLogText(all.slice(-lines).join("\n")) + footer;
1475
+ } catch {
1476
+ return "";
1477
+ }
1478
+ },
1479
+ watchLogs(id, _instanceId, onLine) {
1480
+ const member = memberOf(id);
1481
+ if (!member.logFile) return () => {};
1482
+ return watchLogFile(member.logFile, onLine);
1483
+ },
1484
+ watchChunks(id, _instanceId, _onChunk) {
1485
+ memberOf(id);
1486
+ return () => {};
1487
+ },
1488
+ scanProjects: () => [],
1489
+ purgeStoppedInstances: () => void 0
1490
+ };
1491
+ }
1492
+ //#endregion
1420
1493
  //#region src/core/routine-service.ts
1421
1494
  const DEFAULT_LOG_BUFFER_SIZE = 500;
1422
1495
  /**
@@ -1480,6 +1553,9 @@ function createRoutineServiceAdapter(routine, config, eventBus) {
1480
1553
  name
1481
1554
  });
1482
1555
  }
1556
+ async function stopAll() {
1557
+ if (routine.status === "running") await stop(id);
1558
+ }
1483
1559
  function list(serviceId) {
1484
1560
  if (serviceId && serviceId !== id) return [];
1485
1561
  return [getInstanceStatus()];
@@ -1525,6 +1601,7 @@ function createRoutineServiceAdapter(routine, config, eventBus) {
1525
1601
  return {
1526
1602
  start,
1527
1603
  stop,
1604
+ stopAll,
1528
1605
  list,
1529
1606
  getDefinition,
1530
1607
  logs,
@@ -1550,6 +1627,11 @@ function createCompositeServiceManager(managers, routeMap) {
1550
1627
  async function stop(id, instanceId) {
1551
1628
  return getManager(id).stop(id, instanceId);
1552
1629
  }
1630
+ async function stopAll() {
1631
+ const errors = [];
1632
+ for (const mgr of managers) await mgr.stopAll().catch((error) => errors.push(error));
1633
+ if (errors.length > 0) throw errors[0];
1634
+ }
1553
1635
  function list(serviceId) {
1554
1636
  if (serviceId) return getManager(serviceId).list(serviceId);
1555
1637
  const results = [];
@@ -1577,6 +1659,7 @@ function createCompositeServiceManager(managers, routeMap) {
1577
1659
  return {
1578
1660
  start,
1579
1661
  stop,
1662
+ stopAll,
1580
1663
  list,
1581
1664
  getDefinition,
1582
1665
  logs,
@@ -1769,7 +1852,7 @@ function createReplSession(opts) {
1769
1852
  const active = context.services.list().filter((s) => s.status === "ready" || s.status === "starting");
1770
1853
  for (const svc of active) {
1771
1854
  const where = svc.workdir ? ` ${dim}\`${svc.workdir}\`${reset}` : "";
1772
- parts.push(`${svc.name} still active${where}\n ${dim}Run \`${cli.name} ${svc.serviceId}-stop\` to shut it down${reset}\n`);
1855
+ parts.push(`Stopping ${svc.name}${where}\n`);
1773
1856
  }
1774
1857
  }
1775
1858
  if (threadId) parts.push(`Goodbye! \x1b[2mTo resume, run: ${cli.name} -i --resume ${threadId}\x1b[0m`);
@@ -2162,787 +2245,13 @@ function createReplSession(opts) {
2162
2245
  return session;
2163
2246
  }
2164
2247
  //#endregion
2165
- //#region ../reactor-attachments/dist/switchboard-attachment-transport-BH3ZAmxE.js
2166
- /**
2167
- * Thrown when an attachment ref or hash is not known to the store.
2168
- */
2169
- var AttachmentNotFound = class extends Error {
2170
- constructor(identifier) {
2171
- super(`Attachment not found: ${identifier}`);
2172
- this.name = "AttachmentNotFound";
2173
- }
2174
- };
2175
- /**
2176
- * Thrown when a reservation ID is not found in the reservation store.
2177
- */
2178
- var ReservationNotFound = class extends Error {
2179
- constructor(reservationId) {
2180
- super(`Reservation not found: ${reservationId}`);
2181
- this.name = "ReservationNotFound";
2182
- }
2183
- };
2184
- /**
2185
- * Thrown when an attachment ref string does not match the expected format.
2186
- */
2187
- var InvalidAttachmentRef = class extends Error {
2188
- constructor(ref) {
2189
- super(`Invalid attachment ref: ${ref}`);
2190
- this.name = "InvalidAttachmentRef";
2191
- }
2192
- };
2193
- /**
2194
- * Thrown by reserve() when the claimed hash is already available in the store.
2195
- * The caller should use err.ref directly and upload nothing -- this is the
2196
- * dedup fast path: duplicate content never leaves the client.
2197
- */
2198
- var AttachmentAlreadyExists = class extends Error {
2199
- hash;
2200
- ref;
2201
- constructor(hash, ref) {
2202
- super(`Attachment already exists for hash: ${hash}`);
2203
- this.name = "AttachmentAlreadyExists";
2204
- this.hash = hash;
2205
- this.ref = ref;
2206
- }
2207
- };
2208
- /**
2209
- * Thrown by send() when the server-computed hash of the uploaded bytes
2210
- * does not match the hash claimed at reservation time. Nothing is committed;
2211
- * the reservation is retained so the client can retry with correct bytes.
2212
- */
2213
- var HashMismatch = class extends Error {
2214
- claimed;
2215
- actual;
2216
- constructor(claimed, actual) {
2217
- super(`Hash mismatch: claimed ${claimed} but computed ${actual}`);
2218
- this.name = "HashMismatch";
2219
- this.claimed = claimed;
2220
- this.actual = actual;
2221
- }
2222
- };
2223
- /**
2224
- * Thrown by send() when the uploaded byte count does not equal the
2225
- * sizeBytes declared at reservation time. The handle may reject
2226
- * mid-stream as soon as the count exceeds the declaration.
2227
- * Nothing is committed; the reservation is retained for retry.
2228
- *
2229
- * "actual" is the byte count received from the stream before aborting --
2230
- * it includes the chunk that crossed the declaration and can exceed bytes
2231
- * persisted. On mid-stream aborts the true total is unknown; at least
2232
- * "actual" bytes were sent.
2233
- */
2234
- var SizeMismatch = class extends Error {
2235
- declared;
2236
- actual;
2237
- constructor(declared, actual) {
2238
- super(`Size mismatch: declared ${declared} bytes but received ${actual}`);
2239
- this.name = "SizeMismatch";
2240
- this.declared = declared;
2241
- this.actual = actual;
2242
- }
2243
- };
2244
- /**
2245
- * Thrown when a remote transfer step fails. Identifies the stage only; it
2246
- * intentionally carries no URL, signature query, bucket key, or bearer
2247
- * material so it is always safe to log or surface.
2248
- */
2249
- var AttachmentTransferError = class extends Error {
2250
- stage;
2251
- status;
2252
- constructor(stage, status) {
2253
- super(status === void 0 ? `Attachment ${stage} request failed` : `Attachment ${stage} request failed with status ${status}`);
2254
- this.name = "AttachmentTransferError";
2255
- this.stage = stage;
2256
- this.status = status;
2257
- }
2258
- };
2259
- var AttachmentPending = class extends Error {
2260
- hash;
2261
- expiresAtUtc;
2262
- metadata;
2263
- constructor(hash, expiresAtUtc, meta) {
2264
- super(`Attachment pending upload for hash: ${hash}, expires: ${expiresAtUtc}`);
2265
- this.name = "AttachmentPending";
2266
- this.hash = hash;
2267
- this.expiresAtUtc = expiresAtUtc;
2268
- this.metadata = meta;
2269
- }
2270
- };
2271
- const REF_PATTERN = /^attachment:\/\/v(\d+):(.+)$/;
2272
- const DEFAULT_VERSION = 1;
2273
- function parseRef(ref) {
2274
- const match = REF_PATTERN.exec(ref);
2275
- if (!match) throw new InvalidAttachmentRef(ref);
2276
- return {
2277
- version: Number(match[1]),
2278
- hash: match[2]
2279
- };
2280
- }
2281
- function createRef(hash, version = DEFAULT_VERSION) {
2282
- return `attachment://v${version}:${hash}`;
2283
- }
2284
- async function buildAuthHeaders(url, jwtHandler) {
2285
- const headers = {};
2286
- if (jwtHandler) {
2287
- const token = await jwtHandler(url);
2288
- if (token) headers["Authorization"] = `Bearer ${token}`;
2289
- }
2290
- return headers;
2291
- }
2292
- //#endregion
2293
- //#region ../reactor-attachments/dist/routing-attachment-service-C88ryRgj.js
2294
- function isRecord$3(value) {
2295
- return typeof value === "object" && value !== null && !Array.isArray(value);
2296
- }
2297
- function parseUrl(value) {
2298
- if (typeof value !== "string" || value.length === 0) throw new Error("Attachment target URL must be a non-empty string");
2299
- if (value.trim() !== value || hasForbiddenUrlWhitespace(value)) throw new Error("Attachment target URL must not contain raw whitespace");
2300
- let parsed;
2301
- try {
2302
- parsed = new URL(value);
2303
- } catch {
2304
- throw new Error("Attachment target URL is invalid");
2305
- }
2306
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:" || parsed.username !== "" || parsed.password !== "") throw new Error("Attachment target URL must be HTTP(S) and must not contain credentials");
2307
- return value;
2308
- }
2309
- function parseHeaders(value) {
2310
- if (!isRecord$3(value)) throw new Error("Attachment target headers must be an object");
2311
- const headers = Object.create(null);
2312
- const headerName = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
2313
- for (const [name, headerValue] of Object.entries(value)) {
2314
- if (!headerName.test(name)) throw new Error(`Attachment target header name is invalid: ${name}`);
2315
- if (typeof headerValue !== "string" || hasForbiddenHeaderCharacter(headerValue)) throw new Error(`Attachment target header value is invalid: ${name}`);
2316
- headers[name] = headerValue;
2317
- }
2318
- return headers;
2319
- }
2320
- function hasForbiddenHeaderCharacter(value) {
2321
- for (let index = 0; index < value.length; index++) {
2322
- const code = value.charCodeAt(index);
2323
- if (code <= 8 || code >= 10 && code <= 31 || code === 127 || code > 255) return true;
2324
- }
2325
- return false;
2326
- }
2327
- function hasForbiddenUrlWhitespace(value) {
2328
- for (let index = 0; index < value.length; index++) {
2329
- const code = value.charCodeAt(index);
2330
- if (code <= 32 || code === 127) return true;
2331
- }
2332
- return false;
2333
- }
2334
- function parseExpiry(value, required) {
2335
- if (value === void 0 && !required) return void 0;
2336
- if (typeof value !== "string") throw new Error("Attachment target expiry must be an ISO 8601 UTC string");
2337
- const parsed = new Date(value);
2338
- if (Number.isNaN(parsed.getTime()) || parsed.toISOString() !== value) throw new Error("Attachment target expiry must be an ISO 8601 UTC string");
2339
- return value;
2340
- }
2341
- function parseAttachmentUploadTarget(value) {
2342
- if (!isRecord$3(value)) throw new Error("Attachment upload target must be an object");
2343
- const url = parseUrl(value.url);
2344
- const headers = parseHeaders(value.headers);
2345
- switch (value.kind) {
2346
- case "switchboard":
2347
- if (value.method !== "PUT") throw new Error("Switchboard upload target method must be PUT");
2348
- return {
2349
- kind: "switchboard",
2350
- method: "PUT",
2351
- url,
2352
- headers,
2353
- ...value.expiresAtUtc === void 0 ? {} : { expiresAtUtc: parseExpiry(value.expiresAtUtc, false) }
2354
- };
2355
- case "presigned-put":
2356
- if (value.method !== "PUT") throw new Error("Presigned upload target method must be PUT");
2357
- return {
2358
- kind: "presigned-put",
2359
- method: "PUT",
2360
- url,
2361
- headers,
2362
- expiresAtUtc: parseExpiry(value.expiresAtUtc, true)
2363
- };
2364
- default: throw new Error("Attachment upload target kind is unknown");
2365
- }
2366
- }
2367
- function parseAttachmentDownloadTarget(value) {
2368
- if (!isRecord$3(value)) throw new Error("Attachment download target must be an object");
2369
- const url = parseUrl(value.url);
2370
- const headers = parseHeaders(value.headers);
2371
- switch (value.kind) {
2372
- case "switchboard":
2373
- if (value.method !== "GET") throw new Error("Switchboard download target method must be GET");
2374
- return {
2375
- kind: "switchboard",
2376
- method: "GET",
2377
- url,
2378
- headers,
2379
- ...value.expiresAtUtc === void 0 ? {} : { expiresAtUtc: parseExpiry(value.expiresAtUtc, false) }
2380
- };
2381
- case "presigned-get":
2382
- if (value.method !== "GET") throw new Error("Presigned download target method must be GET");
2383
- return {
2384
- kind: "presigned-get",
2385
- method: "GET",
2386
- url,
2387
- headers,
2388
- expiresAtUtc: parseExpiry(value.expiresAtUtc, true)
2389
- };
2390
- default: throw new Error("Attachment download target kind is unknown");
2391
- }
2392
- }
2393
- const CLIENT_HASH_PATTERN = /^[a-f0-9]{64}$/;
2394
- var AttachmentService = class {
2395
- store;
2396
- reservations;
2397
- uploadFactory;
2398
- backend;
2399
- constructor(store, reservations, uploadFactory, backend) {
2400
- this.store = store;
2401
- this.reservations = reservations;
2402
- this.uploadFactory = uploadFactory;
2403
- this.backend = backend;
2404
- }
2405
- async reserve(options) {
2406
- if (options.clientHash !== void 0) return this.reserveHashFirst(options);
2407
- if (this.backend?.kind === "s3") throw new Error("S3 attachment reservations require a client hash");
2408
- const reservation = await this.reservations.create(options);
2409
- return this.uploadFactory.createUpload(reservation);
2410
- }
2411
- async stat(ref, options) {
2412
- const { hash } = parseRef(ref);
2413
- return options?.documentId === void 0 ? this.store.stat(hash) : this.store.stat(hash, options.documentId);
2414
- }
2415
- async get(ref, options) {
2416
- const { hash } = parseRef(ref);
2417
- const normalized = options === void 0 || options instanceof AbortSignal ? { signal: options } : options;
2418
- return normalized.documentId === void 0 ? this.store.get(hash, normalized.signal) : this.store.get(hash, normalized.signal, normalized.documentId);
2419
- }
2420
- getDownloadTarget(ref, options) {
2421
- const { hash } = parseRef(ref);
2422
- const getTarget = this.store.getDownloadTarget?.bind(this.store);
2423
- if (getTarget === void 0) return Promise.reject(/* @__PURE__ */ new Error("Download targets are not supported by this attachment store: only remote stores negotiate direct URLs"));
2424
- return getTarget(hash, options);
2425
- }
2426
- async reserveHashFirst(options) {
2427
- const normalized = options.clientHash.toLowerCase();
2428
- if (!CLIENT_HASH_PATTERN.test(normalized)) throw new Error(`clientHash must be a 64-character lowercase hex string, got: ${options.clientHash}`);
2429
- if (options.sizeBytes === void 0 || !Number.isSafeInteger(options.sizeBytes) || options.sizeBytes < 0) throw new Error("sizeBytes must be a non-negative safe integer when clientHash is provided");
2430
- const normalizedOptions = {
2431
- ...options,
2432
- clientHash: normalized
2433
- };
2434
- let existingHeader = null;
2435
- try {
2436
- existingHeader = await this.store.stat(normalized);
2437
- } catch (err) {
2438
- if (!(err instanceof AttachmentNotFound) && !(err instanceof AttachmentPending)) throw err;
2439
- }
2440
- if (existingHeader !== null) {
2441
- if (this.backend?.kind === "s3") {
2442
- if (await this.backend.exists(normalized)) throw new AttachmentAlreadyExists(normalized, createRef(normalized));
2443
- } else if (existingHeader.status === "available") throw new AttachmentAlreadyExists(normalized, createRef(normalized));
2444
- }
2445
- const reservation = await this.reservations.create(normalizedOptions);
2446
- if (this.backend?.kind !== "s3") return this.uploadFactory.createUpload(reservation);
2447
- const uploadTarget = await this.backend.prepareUploadTarget(reservation);
2448
- return this.uploadFactory.createUpload({
2449
- ...reservation,
2450
- uploadTarget
2451
- });
2452
- }
2453
- };
2454
- /** Tells a Blob from a stream by shape: `instanceof Blob` misses other realms and polyfills. */
2455
- function isBlob(data) {
2456
- return !("getReader" in data);
2457
- }
2458
- /**
2459
- * The default transport. Ignores `onProgress` — fetch has no upload-side
2460
- * progress event, and silence is how a transport reports that bytes are
2461
- * unobservable.
2462
- */
2463
- function createFetchUploadTransport(fetchFn) {
2464
- return (request) => fetchFn(request.url, {
2465
- method: request.method,
2466
- headers: request.headers,
2467
- body: request.body,
2468
- ...request.signal ? { signal: request.signal } : {}
2469
- });
2470
- }
2471
- function isRecord$2(value) {
2472
- return typeof value === "object" && value !== null && !Array.isArray(value);
2473
- }
2474
- function deriveExtension(fileName) {
2475
- const idx = fileName.lastIndexOf(".");
2476
- if (idx <= 0 || idx === fileName.length - 1) return null;
2477
- return fileName.slice(idx + 1).toLowerCase();
2478
- }
2479
- function isReservationBase(value) {
2480
- if (!isRecord$2(value)) return false;
2481
- if (typeof value.reservationId !== "string") return false;
2482
- if (typeof value.mimeType !== "string") return false;
2483
- if (typeof value.fileName !== "string") return false;
2484
- if (value.extension !== null && typeof value.extension !== "string") return false;
2485
- if (typeof value.createdAtUtc !== "string") return false;
2486
- if (typeof value.expiresAtUtc !== "string") return false;
2487
- return true;
2488
- }
2489
- function isReservation(value) {
2490
- if (!isReservationBase(value)) return false;
2491
- if (value.clientHash !== void 0 && value.clientHash !== null && typeof value.clientHash !== "string") return false;
2492
- if (value.sizeBytes !== void 0 && value.sizeBytes !== null && typeof value.sizeBytes !== "number") return false;
2493
- return true;
2494
- }
2495
- var RemoteReservationStore = class {
2496
- remoteUrl;
2497
- jwtHandler;
2498
- fetchFn;
2499
- constructor(config) {
2500
- this.remoteUrl = config.remoteUrl;
2501
- this.jwtHandler = config.jwtHandler;
2502
- this.fetchFn = (config.fetchFn ?? globalThis.fetch).bind(globalThis);
2503
- }
2504
- async create(options) {
2505
- const url = `${this.remoteUrl}/attachments/reservations`;
2506
- const authHeaders = await buildAuthHeaders(url, this.jwtHandler);
2507
- const extension = options.extension ?? deriveExtension(options.fileName);
2508
- const bodyObj = {
2509
- mimeType: options.mimeType,
2510
- fileName: options.fileName,
2511
- extension
2512
- };
2513
- if (options.clientHash !== void 0) bodyObj.clientHash = options.clientHash;
2514
- if (options.sizeBytes !== void 0) bodyObj.sizeBytes = options.sizeBytes;
2515
- const response = await this.fetchFn(url, {
2516
- method: "POST",
2517
- headers: {
2518
- ...authHeaders,
2519
- "Content-Type": "application/json"
2520
- },
2521
- body: JSON.stringify(bodyObj)
2522
- });
2523
- if (response.status === 409) {
2524
- let body;
2525
- try {
2526
- body = await response.json();
2527
- } catch {
2528
- throw new Error(`Reservation create failed: ${response.status} ${response.statusText}`);
2529
- }
2530
- if (isRecord$2(body) && body.error === "already_exists" && options.clientHash !== void 0) {
2531
- let ref;
2532
- if (typeof body.ref === "string") try {
2533
- parseRef(body.ref);
2534
- ref = body.ref;
2535
- } catch {
2536
- ref = createRef(options.clientHash);
2537
- }
2538
- else ref = createRef(options.clientHash);
2539
- throw new AttachmentAlreadyExists(options.clientHash, ref);
2540
- }
2541
- throw new Error(`Reservation create failed: ${response.status} ${response.statusText}`);
2542
- }
2543
- if (!response.ok) throw new Error(`Reservation create failed: ${response.status} ${response.statusText}`);
2544
- let json;
2545
- try {
2546
- json = await response.json();
2547
- } catch {
2548
- throw new Error("Reservation create returned non-JSON response");
2549
- }
2550
- if (typeof json !== "object" || json === null || typeof json.reservationId !== "string" || json.reservationId.length === 0) throw new Error("Reservation create returned a payload missing a non-empty reservationId string");
2551
- const body = json;
2552
- const now = /* @__PURE__ */ new Date();
2553
- return {
2554
- reservationId: body.reservationId,
2555
- mimeType: options.mimeType,
2556
- fileName: options.fileName,
2557
- extension,
2558
- createdAtUtc: body.createdAtUtc ?? now.toISOString(),
2559
- expiresAtUtc: body.expiresAtUtc ?? new Date(now.getTime() + 864e5).toISOString(),
2560
- clientHash: options.clientHash ?? null,
2561
- sizeBytes: options.sizeBytes ?? null,
2562
- ...body.uploadTarget === void 0 ? {} : { uploadTarget: parseAttachmentUploadTarget(body.uploadTarget) }
2563
- };
2564
- }
2565
- async get(reservationId) {
2566
- const url = `${this.remoteUrl}/attachments/reservations/${encodeURIComponent(reservationId)}`;
2567
- const authHeaders = await buildAuthHeaders(url, this.jwtHandler);
2568
- const response = await this.fetchFn(url, { headers: authHeaders });
2569
- if (response.status === 404) throw new ReservationNotFound(reservationId);
2570
- if (!response.ok) throw new Error(`Reservation get failed: ${response.status} ${response.statusText}`);
2571
- let parsed;
2572
- try {
2573
- parsed = await response.json();
2574
- } catch {
2575
- throw new Error("Reservation get returned non-JSON response");
2576
- }
2577
- if (!isReservation(parsed)) throw new Error("Reservation get returned a payload that does not match the Reservation shape");
2578
- return {
2579
- reservationId: parsed.reservationId,
2580
- mimeType: parsed.mimeType,
2581
- fileName: parsed.fileName,
2582
- extension: parsed.extension,
2583
- createdAtUtc: parsed.createdAtUtc,
2584
- expiresAtUtc: parsed.expiresAtUtc,
2585
- clientHash: parsed.clientHash ?? null,
2586
- sizeBytes: parsed.sizeBytes ?? null,
2587
- ...parsed.uploadTarget === void 0 ? {} : { uploadTarget: parseAttachmentUploadTarget(parsed.uploadTarget) }
2588
- };
2589
- }
2590
- async delete(reservationId) {
2591
- const url = `${this.remoteUrl}/attachments/reservations/${encodeURIComponent(reservationId)}`;
2592
- const authHeaders = await buildAuthHeaders(url, this.jwtHandler);
2593
- const response = await this.fetchFn(url, {
2594
- method: "DELETE",
2595
- headers: authHeaders
2596
- });
2597
- if (!response.ok && response.status !== 404 && response.status !== 410) throw new Error(`Reservation delete failed: ${response.status} ${response.statusText}`);
2598
- }
2599
- deleteExpired() {
2600
- return Promise.reject(/* @__PURE__ */ new Error("RemoteReservationStore.deleteExpired is not supported"));
2601
- }
2602
- };
2603
- function isRecord$1(value) {
2604
- return typeof value === "object" && value !== null && !Array.isArray(value);
2605
- }
2606
- /**
2607
- * A Blob goes out untouched, so a File streams from disk. A stream is
2608
- * buffered: browsers don't portably accept a ReadableStream request body.
2609
- */
2610
- async function toBody(data) {
2611
- return isBlob(data) ? data : new Response(data).blob();
2612
- }
2613
- var RemoteAttachmentUpload = class {
2614
- reservationId;
2615
- ref;
2616
- expiresAtUtc;
2617
- uploadTarget;
2618
- reservation;
2619
- remoteUrl;
2620
- jwtHandler;
2621
- uploadTransport;
2622
- constructor(reservation, config) {
2623
- this.reservationId = reservation.reservationId;
2624
- this.ref = reservation.clientHash !== null ? createRef(reservation.clientHash) : null;
2625
- this.expiresAtUtc = reservation.expiresAtUtc;
2626
- if (reservation.uploadTarget) this.uploadTarget = reservation.uploadTarget;
2627
- this.reservation = reservation;
2628
- this.remoteUrl = config.remoteUrl;
2629
- this.jwtHandler = config.jwtHandler;
2630
- this.uploadTransport = config.fetchFn ? createFetchUploadTransport(config.fetchFn.bind(globalThis)) : config.uploadTransport ?? createFetchUploadTransport(globalThis.fetch.bind(globalThis));
2631
- }
2632
- async send(data, options) {
2633
- if (this.uploadTarget?.kind === "presigned-put") return this.sendPresigned(this.uploadTarget, data, options);
2634
- const url = `${this.remoteUrl}/attachments/reservations/${this.reservationId}`;
2635
- const authHeaders = await buildAuthHeaders(url, this.jwtHandler);
2636
- const body = await toBody(data);
2637
- const response = await this.uploadTransport({
2638
- url,
2639
- method: "PUT",
2640
- headers: {
2641
- ...authHeaders,
2642
- "Content-Type": "application/octet-stream"
2643
- },
2644
- body,
2645
- ...options?.onProgress ? { onProgress: (loaded, total) => options.onProgress?.(loaded, total) } : {},
2646
- ...options?.signal ? { signal: options.signal } : {}
2647
- });
2648
- if (response.status === 422) {
2649
- let errorBody;
2650
- try {
2651
- errorBody = await response.json();
2652
- } catch {
2653
- throw new Error(`Attachment upload failed: ${response.status} ${response.statusText}`);
2654
- }
2655
- if (isRecord$1(errorBody)) {
2656
- if (errorBody.error === "hash_mismatch" && typeof errorBody.claimed === "string" && typeof errorBody.actual === "string") throw new HashMismatch(errorBody.claimed, errorBody.actual);
2657
- if (errorBody.error === "size_mismatch" && typeof errorBody.declared === "number" && typeof errorBody.actual === "number") throw new SizeMismatch(errorBody.declared, errorBody.actual);
2658
- }
2659
- throw new Error(`Attachment upload failed: ${response.status} ${response.statusText}`);
2660
- }
2661
- if (!response.ok) throw new Error(`Attachment upload failed: ${response.status} ${response.statusText}`);
2662
- return await response.json();
2663
- }
2664
- /**
2665
- * Direct provider upload: PUT the bytes to the presigned URL with exactly
2666
- * the returned headers — never the Switchboard JWT — and treat any 2xx as
2667
- * final success with no follow-up control request. The result is
2668
- * synthesized from the hash-first reservation, which is the only path that
2669
- * can produce a presigned target.
2670
- */
2671
- async sendPresigned(target, data, options) {
2672
- if (this.reservation.clientHash === null || this.ref === null) throw new Error("Presigned upload targets require a hash-first reservation");
2673
- const body = await toBody(data);
2674
- const response = await this.uploadTransport({
2675
- url: target.url,
2676
- method: target.method,
2677
- headers: { ...target.headers },
2678
- body,
2679
- ...options?.onProgress ? { onProgress: (loaded, total) => options.onProgress?.(loaded, total) } : {},
2680
- ...options?.signal ? { signal: options.signal } : {}
2681
- });
2682
- if (!response.ok) throw new AttachmentTransferError("presigned-put", response.status);
2683
- const hash = this.reservation.clientHash;
2684
- const now = (/* @__PURE__ */ new Date()).toISOString();
2685
- return {
2686
- hash,
2687
- ref: this.ref,
2688
- header: {
2689
- hash,
2690
- mimeType: this.reservation.mimeType,
2691
- fileName: this.reservation.fileName,
2692
- sizeBytes: this.reservation.sizeBytes ?? body.size,
2693
- extension: this.reservation.extension,
2694
- status: "available",
2695
- source: "local",
2696
- createdAtUtc: this.reservation.createdAtUtc || now,
2697
- lastAccessedAtUtc: now,
2698
- expiresAtUtc: null
2699
- }
2700
- };
2701
- }
2702
- };
2703
- var RemoteAttachmentUploadFactory = class {
2704
- config;
2705
- constructor(config) {
2706
- this.config = config;
2707
- }
2708
- createUpload(reservation) {
2709
- return new RemoteAttachmentUpload(reservation, this.config);
2710
- }
2711
- };
2712
- const MISSING_DOCUMENT_ID = "Remote attachment reads require the documentId whose operations reference the attachment";
2713
- function isRecord(value) {
2714
- return typeof value === "object" && value !== null && !Array.isArray(value);
2715
- }
2716
- function isAttachmentMetadata(value) {
2717
- if (!isRecord(value)) return false;
2718
- if (typeof value.mimeType !== "string") return false;
2719
- if (typeof value.fileName !== "string") return false;
2720
- if (typeof value.sizeBytes !== "number" || !Number.isFinite(value.sizeBytes) || value.sizeBytes < 0) return false;
2721
- if (value.extension !== null && typeof value.extension !== "string") return false;
2722
- if (typeof value.createdAtUtc !== "string") return false;
2723
- if (value.lastAccessedAtUtc !== void 0 && typeof value.lastAccessedAtUtc !== "string") return false;
2724
- return true;
2725
- }
2726
- function contentTypeFallback(response) {
2727
- const contentLength = response.headers.get("Content-Length");
2728
- if (contentLength === null) throw new Error("Switchboard response missing both Attachment-Metadata and Content-Length headers");
2729
- const sizeBytes = Number(contentLength);
2730
- if (!Number.isInteger(sizeBytes) || sizeBytes < 0) throw new Error(`Switchboard response has invalid Content-Length header: ${JSON.stringify(contentLength)}`);
2731
- const lastModified = response.headers.get("Last-Modified");
2732
- const dateHeader = response.headers.get("Date");
2733
- const createdAtUtc = lastModified ? new Date(lastModified).toISOString() : dateHeader ? new Date(dateHeader).toISOString() : (/* @__PURE__ */ new Date()).toISOString();
2734
- return {
2735
- mimeType: response.headers.get("Content-Type") ?? "application/octet-stream",
2736
- fileName: "unknown",
2737
- sizeBytes,
2738
- extension: null,
2739
- createdAtUtc,
2740
- lastAccessedAtUtc: createdAtUtc
2741
- };
2742
- }
2743
- function parseMetadata(response) {
2744
- let fallbackCache;
2745
- const fallback = () => {
2746
- if (fallbackCache === void 0) fallbackCache = contentTypeFallback(response);
2747
- return fallbackCache;
2748
- };
2749
- const metaHeader = response.headers.get("Attachment-Metadata");
2750
- if (metaHeader) try {
2751
- const parsed = JSON.parse(metaHeader);
2752
- if (isRecord(parsed)) {
2753
- if (parsed.extension === void 0) parsed.extension = null;
2754
- if (parsed.createdAtUtc === void 0) parsed.createdAtUtc = fallback().createdAtUtc;
2755
- if (parsed.lastAccessedAtUtc === void 0) parsed.lastAccessedAtUtc = fallback().lastAccessedAtUtc;
2756
- }
2757
- if (isAttachmentMetadata(parsed)) return parsed;
2758
- } catch {}
2759
- return fallback();
2760
- }
2761
- function parsePendingExpiry(response) {
2762
- const header = response.headers.get("Attachment-Pending");
2763
- if (!header) return null;
2764
- try {
2765
- const parsed = JSON.parse(header);
2766
- if (!isRecord(parsed)) return null;
2767
- if (typeof parsed.expiresAtUtc !== "string") return null;
2768
- const result = { expiresAtUtc: parsed.expiresAtUtc };
2769
- if (typeof parsed.mimeType === "string") result.mimeType = parsed.mimeType;
2770
- if (typeof parsed.fileName === "string") result.fileName = parsed.fileName;
2771
- if (typeof parsed.sizeBytes === "number" && Number.isFinite(parsed.sizeBytes) && parsed.sizeBytes >= 0) result.sizeBytes = parsed.sizeBytes;
2772
- return result;
2773
- } catch {
2774
- return null;
2775
- }
2776
- }
2777
- function parsePendingHeader(response) {
2778
- const partial = parsePendingExpiry(response);
2779
- if (!partial) return null;
2780
- if (typeof partial.mimeType !== "string" || typeof partial.fileName !== "string" || partial.sizeBytes === void 0) return null;
2781
- return {
2782
- expiresAtUtc: partial.expiresAtUtc,
2783
- mimeType: partial.mimeType,
2784
- fileName: partial.fileName,
2785
- sizeBytes: partial.sizeBytes
2786
- };
2787
- }
2788
- var RemoteAttachmentStore = class {
2789
- remoteUrl;
2790
- jwtHandler;
2791
- fetchFn;
2792
- constructor(config) {
2793
- this.remoteUrl = config.remoteUrl;
2794
- this.jwtHandler = config.jwtHandler;
2795
- this.fetchFn = (config.fetchFn ?? globalThis.fetch).bind(globalThis);
2796
- }
2797
- /**
2798
- * Get attachment metadata. Normally returns a pending AttachmentHeader
2799
- * (status: 'pending') when the server responds 202 with a full
2800
- * Attachment-Pending header. When only expiresAtUtc is present in the
2801
- * header (degraded wire), throws AttachmentPending instead -- the
2802
- * AttachmentPending throw is the degraded-wire case.
2803
- */
2804
- async stat(hash, documentId) {
2805
- if (documentId === void 0) throw new AttachmentNotFound(hash);
2806
- const url = `${this.remoteUrl}/attachments/${hash}?documentId=${encodeURIComponent(documentId)}`;
2807
- const authHeaders = await buildAuthHeaders(url, this.jwtHandler);
2808
- const response = await this.fetchFn(url, {
2809
- method: "HEAD",
2810
- headers: authHeaders
2811
- });
2812
- if (response.status === 202) {
2813
- const fullPending = parsePendingHeader(response);
2814
- if (fullPending) return buildPendingHeader(hash, fullPending);
2815
- const partial = parsePendingExpiry(response);
2816
- if (partial) throw new AttachmentPending(hash, partial.expiresAtUtc);
2817
- throw new Error("Attachment stat returned 202 with missing or malformed Attachment-Pending header");
2818
- }
2819
- if (response.status === 404) throw new AttachmentNotFound(hash);
2820
- if (!response.ok) throw new Error(`Attachment stat failed: ${response.status} ${response.statusText}`);
2821
- return buildHeader(hash, parseMetadata(response));
2822
- }
2823
- async get(hash, signal, documentId) {
2824
- if (documentId === void 0) throw new Error(MISSING_DOCUMENT_ID);
2825
- const target = await this.getDownloadTarget(hash, {
2826
- documentId,
2827
- signal
2828
- });
2829
- if (target.kind === "presigned-get") return this.fetchPresigned(hash, target, signal);
2830
- return this.fetchAttachment(hash, target, signal);
2831
- }
2832
- /**
2833
- * Asks Switchboard for an authorized download target. The request carries
2834
- * the JWT; the response is runtime-validated before any byte transfer.
2835
- * Public so callers can mint direct URLs (previews, share links) without
2836
- * transferring bytes; `expiresIn` requests a caller-chosen lifetime.
2837
- */
2838
- async getDownloadTarget(hash, options) {
2839
- const { documentId, expiresIn, signal } = options;
2840
- const expiry = expiresIn === void 0 ? "" : `&expiresIn=${encodeURIComponent(String(expiresIn))}`;
2841
- const url = `${this.remoteUrl}/attachments/${hash}/download-target?documentId=${encodeURIComponent(documentId)}${expiry}`;
2842
- const headers = await buildAuthHeaders(url, this.jwtHandler);
2843
- const response = await this.fetchFn(url, {
2844
- signal,
2845
- headers
2846
- });
2847
- if (response.status === 404) throw new AttachmentNotFound(hash);
2848
- if (!response.ok) throw new AttachmentTransferError("download-target", response.status);
2849
- let body;
2850
- try {
2851
- body = await response.json();
2852
- } catch {
2853
- throw new AttachmentTransferError("download-target");
2854
- }
2855
- return parseAttachmentDownloadTarget(body);
2856
- }
2857
- /**
2858
- * Executes a presigned GET with exactly the returned headers and no JWT.
2859
- * A provider 404 means the object is missing despite available metadata
2860
- * (the accepted abandoned-upload trade-off) and surfaces as the same typed
2861
- * not-found error callers already handle.
2862
- */
2863
- async fetchPresigned(hash, target, signal) {
2864
- const response = await this.fetchFn(target.url, {
2865
- signal,
2866
- headers: { ...target.headers }
2867
- });
2868
- if (response.status === 404) throw new AttachmentNotFound(hash);
2869
- if (!response.ok) throw new AttachmentTransferError("presigned-get", response.status);
2870
- if (!response.body) throw new Error("Response body is null");
2871
- return {
2872
- header: buildHeader(hash, parseMetadata(response)),
2873
- body: response.body
2874
- };
2875
- }
2876
- async fetchAttachment(hash, target, signal) {
2877
- const url = target.url;
2878
- const authHeaders = await buildAuthHeaders(url, this.jwtHandler);
2879
- const headers = {
2880
- ...target.headers,
2881
- ...authHeaders
2882
- };
2883
- const response = await this.fetchFn(url, {
2884
- signal,
2885
- headers
2886
- });
2887
- if (response.status === 202) {
2888
- const pending = parsePendingExpiry(response);
2889
- if (!pending) throw new Error("Attachment fetch returned 202 with missing or malformed Attachment-Pending header");
2890
- throw new AttachmentPending(hash, pending.expiresAtUtc);
2891
- }
2892
- if (response.status === 404) throw new AttachmentNotFound(hash);
2893
- if (!response.ok) throw new Error(`Attachment fetch failed: ${response.status} ${response.statusText}`);
2894
- if (!response.body) throw new Error("Response body is null");
2895
- return {
2896
- header: buildHeader(hash, parseMetadata(response)),
2897
- body: response.body
2898
- };
2899
- }
2900
- };
2901
- function buildHeader(hash, metadata) {
2902
- return {
2903
- hash,
2904
- mimeType: metadata.mimeType,
2905
- fileName: metadata.fileName,
2906
- sizeBytes: metadata.sizeBytes,
2907
- extension: metadata.extension,
2908
- status: "available",
2909
- source: "sync",
2910
- createdAtUtc: metadata.createdAtUtc,
2911
- lastAccessedAtUtc: metadata.lastAccessedAtUtc ?? metadata.createdAtUtc,
2912
- expiresAtUtc: null
2913
- };
2914
- }
2915
- function buildPendingHeader(hash, pending) {
2916
- const now = (/* @__PURE__ */ new Date()).toISOString();
2917
- return {
2918
- hash,
2919
- mimeType: pending.mimeType,
2920
- fileName: pending.fileName,
2921
- sizeBytes: pending.sizeBytes,
2922
- extension: null,
2923
- status: "pending",
2924
- source: "sync",
2925
- createdAtUtc: now,
2926
- lastAccessedAtUtc: now,
2927
- expiresAtUtc: pending.expiresAtUtc
2928
- };
2929
- }
2930
- function createRemoteAttachmentService(config) {
2931
- const reservations = new RemoteReservationStore(config);
2932
- const uploadFactory = new RemoteAttachmentUploadFactory(config);
2933
- return new AttachmentService(new RemoteAttachmentStore(config), reservations, uploadFactory);
2934
- }
2935
- //#endregion
2936
2248
  //#region src/core/runtime.ts
2937
2249
  function createCliRuntime(deps) {
2938
- const { cliName, cliVersion, workdir, workspace, config, context, log, commandMap, reactorConfig, agentLoader, routine, proxyInstance, skillIds, resolvedSkills, prompts } = deps;
2939
- const enableSwitchboard = deps.enableSwitchboard ?? true;
2940
- const enableConnect = deps.enableConnect ?? true;
2250
+ const { cliName, cliVersion, workdir, workspace, config, context, log, commandMap, reactorConfig, agentLoader, routine, skillIds, resolvedSkills, prompts } = deps;
2941
2251
  const skipRoutineStart = deps.skipRoutineStart ?? false;
2942
2252
  const wraps = deps.wraps ?? IDENTITY_WRAPS;
2943
2253
  const lifecycleShutdown = deps.lifecycleShutdown;
2944
2254
  let cachedReactor;
2945
- let switchboardInstance;
2946
2255
  let cachedProvider;
2947
2256
  async function getReactor() {
2948
2257
  if (cachedReactor) return cachedReactor;
@@ -2953,8 +2262,8 @@ function createCliRuntime(deps) {
2953
2262
  workspace,
2954
2263
  emit: context.emit,
2955
2264
  on: context.on,
2956
- switchboard: reactorConfig.switchboard,
2957
- attachments: deps.attachments
2265
+ attachments: deps.attachments,
2266
+ attachmentJwtHandler: deps.attachmentJwtHandler
2958
2267
  });
2959
2268
  return cachedReactor;
2960
2269
  }
@@ -2976,58 +2285,14 @@ function createCliRuntime(deps) {
2976
2285
  cachedProvider = await agentLoader(agentCtx);
2977
2286
  return cachedProvider;
2978
2287
  }
2979
- async function startSwitchboardLayer() {
2980
- if (!reactorConfig?.switchboard?.enabled || !cachedReactor?._module) return;
2981
- const switchboardHost = reactorConfig.switchboard.host ?? "localhost";
2982
- const switchboardLabel = reactorConfig.switchboard.name ?? "switchboard";
2983
- const switchboardPort = await resolvePort(reactorConfig.switchboard.port, reactorConfig.switchboard.portRange ?? 1, switchboardLabel);
2984
- const dbPath = workspace.getStoreFolder("read-model.db");
2985
- log.debug(`Starting Switchboard on ${switchboardHost}:${switchboardPort}, dbPath: ${dbPath}`);
2986
- const { startSwitchboard } = await import("./switchboard-CyvOavqL.mjs").then((n) => n.n);
2987
- switchboardInstance = await startSwitchboard({
2988
- reactorModule: cachedReactor._module,
2989
- host: switchboardHost,
2990
- port: switchboardPort,
2991
- dbPath,
2992
- driveId: cachedReactor.driveId,
2993
- registryUrl: reactorConfig.switchboard.registryUrl
2994
- });
2995
- cachedReactor.switchboardUrl = switchboardInstance.switchboardUrl;
2996
- cachedReactor.driveUrl = switchboardInstance.driveUrl;
2997
- cachedReactor.mcpUrl = switchboardInstance.mcpUrl;
2998
- if (!cachedReactor.attachments) cachedReactor.attachments = createRemoteAttachmentService({
2999
- remoteUrl: new URL(switchboardInstance.switchboardUrl).origin,
3000
- jwtHandler: deps.attachmentJwtHandler
3001
- });
3002
- if (proxyInstance) {
3003
- const sbRoutes = buildSwitchboardRoutes(switchboardInstance.switchboardUrl, switchboardInstance.mcpUrl);
3004
- for (const route of sbRoutes) {
3005
- proxyInstance.addRoute(route);
3006
- log.debug(` proxy: ${route.prefix} → ${route.upstream?.toString() ?? route.redirectTo ?? ""}`);
3007
- }
3008
- }
3009
- context.emit?.("powerhouse:switchboard:ready", {
3010
- switchboardUrl: switchboardInstance.switchboardUrl,
3011
- driveUrl: switchboardInstance.driveUrl,
3012
- mcpUrl: switchboardInstance.mcpUrl,
3013
- proxy: proxyInstance ? {
3014
- url: proxyInstance.url,
3015
- ...buildSwitchboardProxyUrls(proxyInstance.url, switchboardInstance)
3016
- } : void 0
3017
- });
3018
- }
3019
2288
  async function teardown() {
3020
2289
  if (routine && routine.status === "running") {
3021
2290
  log.debug("Stopping routine...");
3022
2291
  await routine.stop();
3023
2292
  }
3024
- if (switchboardInstance) {
3025
- log.debug("Stopping Switchboard...");
3026
- await switchboardInstance.shutdown();
3027
- }
3028
- if (proxyInstance) {
3029
- log.debug("Stopping proxy...");
3030
- await proxyInstance.stop();
2293
+ if (context.services) {
2294
+ log.debug("Stopping services...");
2295
+ await context.services.stopAll();
3031
2296
  }
3032
2297
  if (cachedReactor) {
3033
2298
  log.debug("Stopping Reactor...");
@@ -3038,6 +2303,7 @@ function createCliRuntime(deps) {
3038
2303
  await lifecycleShutdown();
3039
2304
  }
3040
2305
  }
2306
+ /** Name the running services teardown is about to stop. */
3041
2307
  function reportActiveServices(output) {
3042
2308
  if (!context.services) return;
3043
2309
  const dim = "\x1B[2m";
@@ -3046,63 +2312,23 @@ function createCliRuntime(deps) {
3046
2312
  for (let i = 0; i < active.length; i++) {
3047
2313
  const svc = active[i];
3048
2314
  const where = svc.workdir ? ` ${dim}\`${svc.workdir}\`${reset}` : "";
3049
- output(`${i === 0 ? "\n\n" : ""}${svc.name} still active${where}\n ${dim}Run \`${cliName} ${svc.serviceId}-stop\` to shut it down${reset}`);
2315
+ output(`${i === 0 ? "\n\n" : ""}Stopping ${svc.name}${where}`);
3050
2316
  }
3051
2317
  }
3052
2318
  async function startupSequence(output) {
3053
2319
  try {
3054
- if (proxyInstance) output(`Proxy listening on ${proxyInstance.url}`);
3055
2320
  if (reactorConfig) {
3056
2321
  log.debug("Starting Reactor...");
3057
2322
  await getReactor();
3058
- log.debug(`Reactor storage: ${workspace.getStoreFolder("reactor-storage")}`);
3059
2323
  output(`Reactor ready (drive: ${cachedReactor.driveId})`);
3060
2324
  if (cachedReactor.personalDriveId) {
3061
- const { createFolderOperations, createFolderCommands } = await import("./folders-BYO1Wqqb.mjs").then((n) => n.t);
2325
+ const { createFolderOperations, createFolderCommands } = await import("./powerhouse-3XZmdY3_.mjs").then((n) => n.S);
3062
2326
  const folderOps = createFolderOperations(cachedReactor.client, cachedReactor.personalDriveId, log);
3063
2327
  context.folders = folderOps;
3064
2328
  const folderCmds = createFolderCommands(folderOps);
3065
2329
  for (const cmd of folderCmds) commandMap.set(cmd.id, cmd);
3066
2330
  }
3067
2331
  }
3068
- if (reactorConfig?.switchboard?.enabled && enableSwitchboard && cachedReactor?._module) {
3069
- log.debug("Starting Switchboard...");
3070
- await startSwitchboardLayer();
3071
- const sb = switchboardInstance;
3072
- output(`Switchboard '${reactorConfig.switchboard.name}' ready at ${sb.switchboardUrl}`);
3073
- log.debug(` drive: ${sb.driveUrl}`);
3074
- log.debug(` mcp: ${sb.mcpUrl}`);
3075
- }
3076
- if (reactorConfig?.connect?.enabled && enableConnect && context.services) {
3077
- const connectName = reactorConfig.connect.name;
3078
- const connectWorkdir = reactorConfig.connect.workdir ?? workdir;
3079
- const running = context.services.list(connectName).find((i) => i.status === "ready" || i.status === "starting");
3080
- if (running && running.workdir === connectWorkdir) output(`Connect '${connectName}' already running at ${running.endpoints?.["connect-studio"] ?? "unknown URL"}`);
3081
- else {
3082
- if (running) {
3083
- log.info(`Stopping Connect (wrong workdir: ${running.workdir})`);
3084
- await context.services.stop(connectName);
3085
- }
3086
- log.debug(`Starting Connect in ${connectWorkdir}`);
3087
- const connectParams = {};
3088
- if (reactorConfig.connect.port) connectParams.port = reactorConfig.connect.port;
3089
- if (cachedReactor?.driveUrl) connectParams.driveUrl = cachedReactor.driveUrl;
3090
- connectParams.base = `${deriveBasePath(config.proxyPublicUrl)}/`;
3091
- const instanceId = await context.services.start(connectName, {
3092
- workdir: connectWorkdir,
3093
- cwd: connectWorkdir,
3094
- params: Object.keys(connectParams).length > 0 ? connectParams : void 0
3095
- });
3096
- output(`Connect '${connectName}' ready at ${context.services.list(connectName).find((i) => i.instanceId === instanceId)?.endpoints?.["connect-studio"] ?? `http://localhost:${reactorConfig.connect.port}`}`);
3097
- }
3098
- const drives = cachedReactor?.drives;
3099
- const baseDriveUrl = cachedReactor?.driveUrl;
3100
- const baseDriveId = cachedReactor?.driveId;
3101
- if (drives?.length) output(` Drives:\n${drives.map((d) => {
3102
- const url = baseDriveUrl && baseDriveId ? baseDriveUrl.replace(baseDriveId, d.id) : `(drive: ${d.id})`;
3103
- return ` ${d.name} (${d.role}): ${url}`;
3104
- }).join("\n")}`);
3105
- }
3106
2332
  if (routine && !skipRoutineStart) {
3107
2333
  routine.setContext(context);
3108
2334
  routine.start();
@@ -3203,18 +2429,6 @@ function defineCli(options) {
3203
2429
  configSchema: configObj.merge(secretsObj)
3204
2430
  };
3205
2431
  }
3206
- if (options.proxyEnabled && options.configSchema) {
3207
- const proxySchema = z.object({
3208
- proxyPort: z.coerce.number().default(0),
3209
- proxyHost: z.string().default("0.0.0.0"),
3210
- proxyPublicUrl: z.string().url().optional()
3211
- });
3212
- const configObj = options.configSchema;
3213
- options = {
3214
- ...options,
3215
- configSchema: configObj.merge(proxySchema)
3216
- };
3217
- }
3218
2432
  if (options.lifecycle && options.lifecycle.length > 0 && options.configSchema) {
3219
2433
  let merged = options.configSchema;
3220
2434
  for (const hook of options.lifecycle) if (hook.configSchema) merged = merged.merge(hook.configSchema);
@@ -3284,14 +2498,13 @@ function defineCli(options) {
3284
2498
  if (options.routine?.id) {
3285
2499
  const routineConfig = options.routine;
3286
2500
  const routineName = routineConfig.name ?? slugToTitle(routineConfig.id);
3287
- const syntheticDef = {
2501
+ const cmds = createServiceCommands({
3288
2502
  id: routineConfig.id,
3289
2503
  name: routineName,
3290
2504
  command: "",
3291
2505
  maxInstances: 1,
3292
2506
  ...routineConfig.projectScanner && { projectScanner: routineConfig.projectScanner }
3293
- };
3294
- const cmds = createServiceCommands(syntheticDef);
2507
+ });
3295
2508
  const svcGroup = { name: routineName };
3296
2509
  for (const cmd of cmds) {
3297
2510
  if (!commandMap.has(cmd.id)) commandMap.set(cmd.id, cmd);
@@ -3306,34 +2519,7 @@ function defineCli(options) {
3306
2519
  }
3307
2520
  let reactorConfig;
3308
2521
  function configureReactor(config) {
3309
- const resolved = resolveReactorDefaults(options.name, config);
3310
- if (resolved.switchboard) config = {
3311
- ...config,
3312
- switchboard: resolved.switchboard
3313
- };
3314
- if (resolved.connect) config = {
3315
- ...config,
3316
- connect: resolved.connect
3317
- };
3318
- if (config.connect?.enabled && options.root) {
3319
- const connect = { ...config.connect };
3320
- if (!connect.workdir) connect.workdir = resolveAppPackageDir(options.root, options.name);
3321
- if (connect.assetsDir === void 0 && connect.workdir) {
3322
- const candidateDir = path.join(connect.workdir, "dist", "connect");
3323
- if (fs.existsSync(path.join(candidateDir, "index.html"))) connect.assetsDir = candidateDir;
3324
- }
3325
- config = {
3326
- ...config,
3327
- connect
3328
- };
3329
- }
3330
2522
  reactorConfig = config;
3331
- if (config.connect?.enabled) {
3332
- const def = connectServiceDefinition(config.connect);
3333
- for (const cmd of createServiceCommands(def)) if (!commandMap.has(cmd.id)) commandMap.set(cmd.id, cmd);
3334
- if (!options.services) options.services = [];
3335
- options.services.push(def);
3336
- }
3337
2523
  }
3338
2524
  function getCommand(id) {
3339
2525
  return commandMap.get(id);
@@ -3601,8 +2787,6 @@ function defineCli(options) {
3601
2787
  });
3602
2788
  if (options.interactive) program.option("-i, --interactive", "Start interactive REPL mode");
3603
2789
  if (hasTriggers) program.option("-R, --no-routine", "Skip routine activation");
3604
- if (reactorConfig?.switchboard?.enabled) program.option("-A, --no-api", "Skip API (switchboard) activation");
3605
- if (reactorConfig?.connect?.enabled) program.option("-S, --no-studio", "Skip Studio (connect) activation");
3606
2790
  program.option("--verbose", "Enable debug-level logging");
3607
2791
  program.option("--meta", "Output CLI metadata as JSON");
3608
2792
  if (agentLoader) program.option("--resume <thread-id>", "Resume a previous conversation");
@@ -3704,11 +2888,11 @@ function defineCli(options) {
3704
2888
  return program;
3705
2889
  }
3706
2890
  /**
3707
- * Wire up ServiceManager (process + routine), event handlers, and proxy
3708
- * event wiring onto a freshly-built context. Shared by bootstrap() and
3709
- * the interactive-mode startup in runImpl().
2891
+ * Wire up ServiceManager (process + routine + compound members) and event
2892
+ * handlers onto a freshly-built context. Shared by bootstrap() and the
2893
+ * interactive-mode startup in runImpl().
3710
2894
  */
3711
- function wireServices(context, config, log, proxyInstance) {
2895
+ function wireServices(context, config, log, members) {
3712
2896
  const servicesNow = options.services && options.services.length > 0;
3713
2897
  let processServiceManager;
3714
2898
  if (servicesNow && options.services) {
@@ -3726,34 +2910,18 @@ function defineCli(options) {
3726
2910
  context.services = createCompositeServiceManager([processServiceManager, routineServiceAdapter], routeMap);
3727
2911
  } else if (processServiceManager) context.services = processServiceManager;
3728
2912
  else if (routineServiceAdapter) context.services = routineServiceAdapter;
3729
- if (_eventBus && options.events) for (const [event, handler] of Object.entries(options.events)) _eventBus.on(event, (data) => handler(data, log));
3730
- if (proxyInstance) {
3731
- const implicitRoot = resolveImplicitProxyRoot(options.services ?? []);
3732
- if (implicitRoot) log.debug(`Proxy: '${implicitRoot.serviceId}/${implicitRoot.captureName}' is the only website capture — serving it at '/' (set proxyRoot to make this explicit)`);
3733
- const bus = getEventBus();
3734
- bus.on("service:ready", (data) => {
3735
- if (!data?.id || !context.services) return;
3736
- const def = context.services.getDefinition(data.id);
3737
- if (!def) return;
3738
- const inst = context.services.list(data.id).find((i) => i.instanceId === data.instanceId);
3739
- if (!inst) return;
3740
- const routes = buildServiceRoutes(def, inst, implicitRoot, log);
3741
- for (const route of routes) proxyInstance.addRoute(route);
3742
- });
3743
- bus.on("service:stopped", (data) => {
3744
- if (data?.id) proxyInstance.removeRoutesBySource(`service:${data.id}`);
3745
- });
3746
- bus.on("service:failed", (data) => {
3747
- if (data?.id) proxyInstance.removeRoutesBySource(`service:${data.id}`);
3748
- });
3749
- if (context.services) for (const inst of context.services.list()) {
3750
- if (inst.status !== "ready" || !inst.endpoints) continue;
3751
- const def = context.services.getDefinition(inst.serviceId);
3752
- if (!def) continue;
3753
- const routes = buildServiceRoutes(def, inst, implicitRoot, log);
3754
- for (const route of routes) proxyInstance.addRoute(route);
2913
+ if (members) {
2914
+ const memberManager = createMemberServiceManager(members);
2915
+ const own = context.services;
2916
+ const routeMap = /* @__PURE__ */ new Map();
2917
+ if (own) {
2918
+ for (const svc of options.services ?? []) routeMap.set(svc.id, own);
2919
+ if (routineServiceAdapter) routeMap.set(options.routine.id, own);
3755
2920
  }
2921
+ for (const member of members()) if (!routeMap.has(member.name)) routeMap.set(member.name, memberManager);
2922
+ context.services = createCompositeServiceManager(own ? [own, memberManager] : [memberManager], routeMap);
3756
2923
  }
2924
+ if (_eventBus && options.events) for (const [event, handler] of Object.entries(options.events)) _eventBus.on(event, (data) => handler(data, log));
3757
2925
  }
3758
2926
  /**
3759
2927
  * Initialize the CLI runtime without entering the dispatch loop.
@@ -3865,7 +3033,11 @@ function defineCli(options) {
3865
3033
  configFile: runOptions?.configFile,
3866
3034
  resume: runOptions?.resume,
3867
3035
  interactiveInput: runOptions?.interactiveInput,
3868
- logLevel: runOptions?.logLevel
3036
+ logLevel: runOptions?.logLevel,
3037
+ reactor: runOptions?.reactor,
3038
+ onServe: runOptions?.onServe,
3039
+ signal: runOptions?.signal,
3040
+ members: runOptions?.members
3869
3041
  });
3870
3042
  }
3871
3043
  /**
@@ -3890,8 +3062,6 @@ function defineCli(options) {
3890
3062
  let verboseFlag = false;
3891
3063
  let metaFlag = false;
3892
3064
  let noRoutineFlag = false;
3893
- let noApiFlag = false;
3894
- let noStudioFlag = false;
3895
3065
  const frameworkFlags = /* @__PURE__ */ new Set([
3896
3066
  "--resume",
3897
3067
  "--workdir",
@@ -3905,8 +3075,6 @@ function defineCli(options) {
3905
3075
  else if (arg === "--verbose") verboseFlag = true;
3906
3076
  else if (arg === "--meta") metaFlag = true;
3907
3077
  else if (arg === "-R" || arg === "--no-routine") noRoutineFlag = true;
3908
- else if (arg === "-A" || arg === "--no-api") noApiFlag = true;
3909
- else if (arg === "-S" || arg === "--no-studio") noStudioFlag = true;
3910
3078
  else if (frameworkFlags.has(arg) && i + 1 < preCommandArgs.length) {
3911
3079
  const value = preCommandArgs[i + 1];
3912
3080
  if (arg === "--workdir" || arg === "-w") workdirFlag = value;
@@ -3956,44 +3124,7 @@ function defineCli(options) {
3956
3124
  const firstSubcmd = userArgs.slice(subcommandIdx)[0];
3957
3125
  const isSubcommand = firstSubcmd && (commandMap.has(firstSubcmd) || firstSubcmd === "help");
3958
3126
  const isBuiltinFlag = preCommandArgs.some((a) => a === "--help" || a === "-h" || a === "--version" || a === "-V");
3959
- const willRunOneShot = !interactiveFlag && (isSubcommand || isBuiltinFlag || metaFlag);
3960
- let proxyInstance;
3961
- if (options.proxyEnabled && !willRunOneShot) {
3962
- const proxyPort = config.proxyPort ?? 0;
3963
- const proxyHost = config.proxyHost ?? "0.0.0.0";
3964
- const proxyPublicUrl = config.proxyPublicUrl;
3965
- proxyInstance = await createProxyServer({
3966
- port: proxyPort,
3967
- host: proxyHost,
3968
- publicUrl: proxyPublicUrl,
3969
- logger: log
3970
- });
3971
- for (const route of options.proxyRoutes ?? []) try {
3972
- proxyInstance.addRoute({
3973
- prefix: route.prefix.startsWith("/") ? route.prefix : `/${route.prefix}`,
3974
- upstream: new URL(route.upstream),
3975
- ws: route.ws ?? false,
3976
- source: "static"
3977
- });
3978
- } catch (err) {
3979
- log.warn(`Invalid proxyRoutes entry '${route.prefix}': ${err instanceof Error ? err.message : String(err)}`);
3980
- }
3981
- const proxy = proxyInstance;
3982
- context.proxy = {
3983
- url: proxy.url,
3984
- port: proxy.port,
3985
- routes: () => proxy.getRoutes().map((r) => ({
3986
- prefix: r.prefix,
3987
- upstream: r.upstream?.toString(),
3988
- ws: r.ws,
3989
- source: r.source,
3990
- redirectTo: r.redirectTo,
3991
- exact: r.exact
3992
- })),
3993
- addRoute: (route) => proxy.addRoute(route)
3994
- };
3995
- }
3996
- wireServices(context, config, log, proxyInstance);
3127
+ wireServices(context, config, log, opts.members);
3997
3128
  bootTimings.lifecycleInitStartedAt = Date.now();
3998
3129
  const lifecycleCtx = {
3999
3130
  config,
@@ -4013,6 +3144,8 @@ function defineCli(options) {
4013
3144
  };
4014
3145
  const resolvedDescription = resolveValue(options.description, resolvableCtx);
4015
3146
  const resolvedWelcome = options.interactive ? resolveValue(options.interactive.welcome, resolvableCtx) : void 0;
3147
+ const supplyReactor = opts.reactor;
3148
+ const runReactor = supplyReactor ? { create: (setup) => supplyReactor(setup, reactorConfig) } : reactorConfig;
4016
3149
  const runtime = createCliRuntime({
4017
3150
  cliName: options.name,
4018
3151
  cliVersion: options.version,
@@ -4022,13 +3155,10 @@ function defineCli(options) {
4022
3155
  context,
4023
3156
  log,
4024
3157
  commandMap,
4025
- reactorConfig,
3158
+ reactorConfig: runReactor,
4026
3159
  agentLoader,
4027
3160
  routine,
4028
3161
  skipRoutineStart: noRoutineFlag,
4029
- proxyInstance,
4030
- enableSwitchboard: !noApiFlag,
4031
- enableConnect: !noStudioFlag,
4032
3162
  attachmentJwtHandler: options.attachmentJwtHandler?.({
4033
3163
  workdir,
4034
3164
  config: typedConfig
@@ -4039,7 +3169,8 @@ function defineCli(options) {
4039
3169
  wraps: lifecycle.wraps,
4040
3170
  lifecycleShutdown: lifecycle.shutdown
4041
3171
  });
4042
- if (reactorConfig) context.reactor = runtime.getReactor;
3172
+ if (runReactor) context.reactor = runtime.getReactor;
3173
+ if (supplyReactor) context.reactorAttached = true;
4043
3174
  context.agent = runtime.getAgent;
4044
3175
  if (metaFlag) {
4045
3176
  stdout(JSON.stringify(getMetadata(), null, 2));
@@ -4093,10 +3224,9 @@ function defineCli(options) {
4093
3224
  stdout(`\x1b[2mThread: ${threadId} (continue with: ${options.name} --resume ${threadId} "your message")\x1b[0m`);
4094
3225
  }
4095
3226
  const effectiveRoutine = noRoutineFlag ? void 0 : routine;
4096
- const effectiveApi = !noApiFlag && reactorConfig?.switchboard?.enabled;
4097
3227
  const isTTY = interactiveFlag && !opts.interactiveInput && process.stdin.isTTY;
4098
3228
  const mode = !interactiveFlag ? "headless" : isTTY ? "interactive-terminal" : "interactive-streaming";
4099
- const hasKeepAlive = !!effectiveRoutine || !!effectiveApi || !!proxyInstance;
3229
+ const hasKeepAlive = !!effectiveRoutine;
4100
3230
  if (isBuiltinFlag || !interactiveFlag && (isSubcommand || hasPrompt)) {
4101
3231
  if (hasPrompt) {
4102
3232
  const agentProvider = await runtime.getAgent();
@@ -4117,6 +3247,9 @@ function defineCli(options) {
4117
3247
  try {
4118
3248
  await program.parseAsync(argv);
4119
3249
  } catch (err) {
3250
+ try {
3251
+ await runtime.teardown();
3252
+ } catch {}
4120
3253
  if (err.exitCode === 0) {
4121
3254
  exit(0);
4122
3255
  return;
@@ -4128,6 +3261,14 @@ function defineCli(options) {
4128
3261
  }
4129
3262
  await runtime.teardown();
4130
3263
  } else if (interactiveFlag || hasKeepAlive) {
3264
+ if (opts.onServe) try {
3265
+ await opts.onServe();
3266
+ } catch (err) {
3267
+ await runtime.teardown();
3268
+ stderr(err instanceof Error ? err.message : String(err));
3269
+ exit(1);
3270
+ return;
3271
+ }
4131
3272
  let session;
4132
3273
  if (interactiveFlag) {
4133
3274
  if (!options.interactive) {
@@ -4150,7 +3291,7 @@ function defineCli(options) {
4150
3291
  return !!agentLoader;
4151
3292
  },
4152
3293
  get hasReactor() {
4153
- return !!reactorConfig;
3294
+ return !!runReactor;
4154
3295
  },
4155
3296
  configureAgent,
4156
3297
  configureReactor,
@@ -4176,14 +3317,15 @@ function defineCli(options) {
4176
3317
  switch (mode) {
4177
3318
  case "interactive-terminal": {
4178
3319
  /* istanbul ignore next -- Ink REPL requires a real terminal */
4179
- const { startInkRepl } = await import("./start-b7Mn2cxB.mjs");
3320
+ const { startInkRepl } = await import("./start-BHn9LIyX.mjs");
4180
3321
  /* istanbul ignore next */
4181
3322
  await startInkRepl(session, {
4182
3323
  services: context.services,
4183
3324
  workdir: context.workdir,
4184
3325
  onStart: async (append) => {
4185
3326
  await runtime.startupSequence(append);
4186
- }
3327
+ },
3328
+ ...opts.signal ? { signal: opts.signal } : {}
4187
3329
  });
4188
3330
  /* istanbul ignore next */
4189
3331
  await runtime.teardown();
@@ -4216,7 +3358,11 @@ function defineCli(options) {
4216
3358
  if (hasKeepAlive) {
4217
3359
  stdout("Stdin closed — still serving. Press Ctrl+C to stop.");
4218
3360
  await new Promise((resolve) => {
3361
+ let stopped = false;
4219
3362
  const onSignal = async () => {
3363
+ if (stopped) return;
3364
+ stopped = true;
3365
+ opts.signal?.removeEventListener("abort", onSignal);
4220
3366
  const suppress = () => {};
4221
3367
  process.removeListener("SIGINT", onSignal);
4222
3368
  process.removeListener("SIGTERM", onSignal);
@@ -4229,6 +3375,8 @@ function defineCli(options) {
4229
3375
  };
4230
3376
  process.on("SIGINT", onSignal);
4231
3377
  process.on("SIGTERM", onSignal);
3378
+ opts.signal?.addEventListener("abort", onSignal, { once: true });
3379
+ if (opts.signal?.aborted) onSignal();
4232
3380
  });
4233
3381
  return;
4234
3382
  }
@@ -4246,7 +3394,11 @@ function defineCli(options) {
4246
3394
  }
4247
3395
  stdout("Serving — press Ctrl+C to stop.");
4248
3396
  await new Promise((resolve) => {
3397
+ let stopped = false;
4249
3398
  const onSignal = async () => {
3399
+ if (stopped) return;
3400
+ stopped = true;
3401
+ opts.signal?.removeEventListener("abort", onSignal);
4250
3402
  const suppress = () => {};
4251
3403
  process.removeListener("SIGINT", onSignal);
4252
3404
  process.removeListener("SIGTERM", onSignal);
@@ -4260,6 +3412,8 @@ function defineCli(options) {
4260
3412
  };
4261
3413
  process.on("SIGINT", onSignal);
4262
3414
  process.on("SIGTERM", onSignal);
3415
+ opts.signal?.addEventListener("abort", onSignal, { once: true });
3416
+ if (opts.signal?.aborted) onSignal();
4263
3417
  });
4264
3418
  return;
4265
3419
  }
@@ -4346,7 +3500,7 @@ function defineCli(options) {
4346
3500
  ...svc.maxInstances !== void 0 && { maxInstances: svc.maxInstances },
4347
3501
  params: svc.paramsSchema ? fieldsToMap(getSchemaFields(svc.paramsSchema)) : {},
4348
3502
  ...svc.shutdown && { shutdown: {
4349
- signal: String(svc.shutdown.signal),
3503
+ signal: svc.run ? "stdin" : String(svc.shutdown.signal),
4350
3504
  timeout: svc.shutdown.timeout
4351
3505
  } },
4352
3506
  ...svc.restart && { restart: {
@@ -4390,27 +3544,6 @@ function defineCli(options) {
4390
3544
  workdir: activeWorkdir,
4391
3545
  config: {}
4392
3546
  });
4393
- /**
4394
- * Resolve the -app companion package directory using Node module resolution.
4395
- * Falls back to the sibling directory convention for workspace layouts.
4396
- */
4397
- function resolveAppPackageDir(cliRoot, cliName) {
4398
- try {
4399
- const cliPkgPath = path.join(cliRoot, "package.json");
4400
- const appPkgName = JSON.parse(fs.readFileSync(cliPkgPath, "utf8")).name.replace(/-cli$/, "-app");
4401
- const entry = createRequire(cliPkgPath).resolve(appPkgName);
4402
- let dir = path.dirname(entry);
4403
- while (dir !== path.dirname(dir)) {
4404
- const candidate = path.join(dir, "package.json");
4405
- if (fs.existsSync(candidate)) {
4406
- if (JSON.parse(fs.readFileSync(candidate, "utf8")).name === appPkgName) return dir;
4407
- }
4408
- dir = path.dirname(dir);
4409
- }
4410
- } catch {}
4411
- const bareName = cliName.replace(/^@[^/]+\//, "");
4412
- return path.resolve(cliRoot, `../${bareName}-app`);
4413
- }
4414
3547
  cliRef = {
4415
3548
  name: options.name,
4416
3549
  version: options.version,
@@ -4454,87 +3587,6 @@ function defineTrigger(options) {
4454
3587
  return options;
4455
3588
  }
4456
3589
  //#endregion
4457
- //#region src/integrations/powerhouse/change-trigger.ts
4458
- /**
4459
- * Build a Trigger that listens for document change events on the event bus,
4460
- * coalesces them, loads matching documents, narrows to the registered type,
4461
- * and hands them to the user's onChange handler.
4462
- *
4463
- * Runtime behavior:
4464
- * 1. `setup()` subscribes to `powerhouse:document:changed`. For each event,
4465
- * if any documentType matches (and, when `documentId` is a literal
4466
- * string, the id also matches), bump the pending counter.
4467
- * 2. If `initialReconcile !== false`, `setup()` bumps pending once on
4468
- * startup so the first poll reconciles without waiting for an event.
4469
- * 3. `poll()` returns null unless pending > 0. When pending > 0:
4470
- * - If `documentId` is set: load single doc, wrap in `[doc]`
4471
- * - If `documentId` is omitted: `find()` all docs of matching type(s)
4472
- * Applies `filter` per-doc, then calls `onChange(docs, ctx)`.
4473
- * 4. pending is reset to 0 at the start of each poll drain — multiple
4474
- * events within a tick coalesce to one `onChange` call.
4475
- */
4476
- function createDocumentChangeTrigger(options) {
4477
- const initialReconcile = options.initialReconcile !== false;
4478
- const types = Array.isArray(options.documentType) ? options.documentType : [options.documentType];
4479
- return {
4480
- id: options.id,
4481
- type: "condition",
4482
- state: options.state ?? (() => ({ pending: 0 })),
4483
- async setup(ctx) {
4484
- const log = ctx.context.log;
4485
- const on = ctx.context.on;
4486
- if (!on) {
4487
- log?.debug(`[${options.id}] no event bus on CoreContext — poll-only mode`);
4488
- if (initialReconcile) ctx.state.pending = 1;
4489
- return;
4490
- }
4491
- on("powerhouse:document:changed", (payload) => {
4492
- const documents = payload.documents ?? [];
4493
- if (!documents.some((d) => types.includes(d.header?.documentType))) return;
4494
- if (typeof options.documentId === "string") {
4495
- if (!documents.map((d) => d.header?.id).includes(options.documentId)) return;
4496
- }
4497
- ctx.state.pending += 1;
4498
- log?.debug(`[${options.id}] queued change (pending=${ctx.state.pending})`);
4499
- });
4500
- if (initialReconcile) ctx.state.pending = 1;
4501
- },
4502
- async poll(ctx) {
4503
- if (!ctx.state.pending) return null;
4504
- ctx.state.pending = 0;
4505
- const reactor = await ctx.reactor();
4506
- if (!reactor) {
4507
- ctx.context.log?.debug(`[${options.id}] no reactor available, skipping`);
4508
- return null;
4509
- }
4510
- let docs;
4511
- if (options.documentId) {
4512
- const docId = typeof options.documentId === "function" ? await options.documentId(ctx) : options.documentId;
4513
- if (!docId) {
4514
- ctx.context.log?.debug(`[${options.id}] no target document id resolved, skipping`);
4515
- return null;
4516
- }
4517
- docs = [await reactor.client.get(docId)];
4518
- } else {
4519
- const allDocs = [];
4520
- for (const t of types) {
4521
- const found = (await reactor.client.find({ type: t }))?.results ?? [];
4522
- allDocs.push(...found);
4523
- }
4524
- docs = allDocs;
4525
- if (docs.length === 0 && !options.callOnEmpty) return null;
4526
- }
4527
- if (options.filter) {
4528
- const filtered = [];
4529
- for (const doc of docs) if (await options.filter(doc, ctx)) filtered.push(doc);
4530
- if (filtered.length === 0) return null;
4531
- docs = filtered;
4532
- }
4533
- return options.onChange(docs, ctx);
4534
- }
4535
- };
4536
- }
4537
- //#endregion
4538
3590
  //#region src/core/types-binding.ts
4539
3591
  /**
4540
3592
  * Bind a CLI's config schema and optional registry once; reuse the returned
@@ -4624,144 +3676,6 @@ async function getProjectMapping(scanResults, folders) {
4624
3676
  return mappings;
4625
3677
  }
4626
3678
  //#endregion
4627
- //#region src/integrations/powerhouse/registry.ts
4628
- /**
4629
- * Build a DocumentRegistry from a tuple of DocumentModelModules.
4630
- *
4631
- * ```ts
4632
- * const registry = defineRegistry([PhClintProject, DocumentDrive] as const);
4633
- * // typeof registry:
4634
- * // {
4635
- * // 'powerhouse/ph-clint-project': RegistryEntry<PhClintProjectPHState, PhClintProjectAction>;
4636
- * // 'powerhouse/document-drive': RegistryEntry<DocumentDrivePHState, DocumentDriveAction>;
4637
- * // }
4638
- * ```
4639
- *
4640
- * Runtime value is a plain object keyed by `documentModel.id`. Consumers can
4641
- * introspect it to list registered types; Phase 3's
4642
- * `createDocumentChangeTrigger` also uses it for runtime lookup.
4643
- */
4644
- function defineRegistry(modules) {
4645
- const out = {};
4646
- for (const mod of modules) out[mod.documentModel.global.id] = mod;
4647
- return out;
4648
- }
4649
- //#endregion
4650
- //#region src/integrations/powerhouse/identity.ts
4651
- /**
4652
- * Deterministic identity derivation for per-CLI namespacing.
4653
- *
4654
- * Produces stable, reproducible identifiers from (cliName, salt) pairs.
4655
- * Used for drive IDs and other resources that must be consistent across
4656
- * sessions and systems.
4657
- *
4658
- * Placeholder implementation — will be replaced with Ed25519 public key
4659
- * derivation when document authorization is added.
4660
- */
4661
- /**
4662
- * Deterministic UUID-shaped identifier from (cliName, salt).
4663
- *
4664
- * Uses SHA-256 of `${cliName}:${salt}`, truncated to 128 bits and formatted
4665
- * as a UUID v4 string (version nibble = 4, variant = 10xx). Deterministic:
4666
- * same (cliName, salt) always produces the same ID across systems.
4667
- */
4668
- function deterministicId(cliName, salt) {
4669
- const input = `${cliName}:${salt}`;
4670
- const hash = crypto.createHash("sha256").update(input).digest();
4671
- const bytes = new Uint8Array(hash.buffer, hash.byteOffset, 16);
4672
- bytes[6] = bytes[6] & 15 | 64;
4673
- bytes[8] = bytes[8] & 63 | 128;
4674
- const hex = Buffer.from(bytes).toString("hex");
4675
- return [
4676
- hex.slice(0, 8),
4677
- hex.slice(8, 12),
4678
- hex.slice(12, 16),
4679
- hex.slice(16, 20),
4680
- hex.slice(20, 32)
4681
- ].join("-");
4682
- }
4683
- //#endregion
4684
- //#region src/integrations/powerhouse/type-guard.ts
4685
- /**
4686
- * Type guard for discriminated narrowing in multi-type onChange handlers.
4687
- *
4688
- * Usage:
4689
- * onChange(docs, ctx) {
4690
- * for (const doc of docs) {
4691
- * if (isDocType(doc, 'powerhouse/ph-clint-project')) {
4692
- * // doc is narrowed to R['powerhouse/ph-clint-project']['document']
4693
- * }
4694
- * }
4695
- * }
4696
- */
4697
- function isDocType(doc, type) {
4698
- return doc.header?.documentType === type;
4699
- }
4700
- //#endregion
4701
- //#region src/integrations/powerhouse/index.ts
4702
- /**
4703
- * Build a ReactorContext using the standard composition:
4704
- * buildReactor() + ensureDrive() + bridgeSubscriptions() + startSwitchboard().
4705
- *
4706
- * This is the common-case helper for configureReactor().create.
4707
- * Advanced users can write their own factory.
4708
- */
4709
- async function buildDefaultReactor(ctx, options) {
4710
- const { buildReactor } = await import("./reactor-C9VIUX1H.mjs").then((n) => n.t);
4711
- const { ensureDrive, ensureRemoteDrive } = await import("./drive-Bu9zoFrO.mjs").then((n) => n.t);
4712
- const reactorModule = await buildReactor({
4713
- documentModels: options.documentModels,
4714
- storagePath: ctx.workspace.getStoreFolder("reactor-storage"),
4715
- enableSync: !!ctx.switchboard?.enabled
4716
- });
4717
- const driveConfigs = options.drives ?? (options.drive ? [{
4718
- ...options.drive,
4719
- role: "personal"
4720
- }] : [{
4721
- name: "default",
4722
- role: "personal"
4723
- }]);
4724
- const drives = [];
4725
- for (const cfg of driveConfigs) if (cfg.remoteUrl) {
4726
- const drive = await ensureRemoteDrive(reactorModule, cfg.remoteUrl, cfg.name);
4727
- drives.push({
4728
- ...drive,
4729
- role: cfg.role,
4730
- remoteUrl: cfg.remoteUrl
4731
- });
4732
- } else {
4733
- const drive = await ensureDrive(reactorModule, cfg);
4734
- drives.push({
4735
- ...drive,
4736
- role: cfg.role
4737
- });
4738
- }
4739
- const personalDriveId = drives.find((d) => d.role === "personal")?.id ?? drives[0]?.id ?? "";
4740
- const driveId = personalDriveId;
4741
- let unsubscribe;
4742
- if (options.subscriptions && ctx.emit) {
4743
- const { bridgeSubscriptions } = await import("./subscriptions-CfiflAsI.mjs").then((n) => n.t);
4744
- unsubscribe = bridgeSubscriptions(reactorModule.client, options.subscriptions, ctx.emit);
4745
- }
4746
- const result = {
4747
- client: reactorModule.client,
4748
- driveId,
4749
- personalDriveId,
4750
- drives,
4751
- attachments: ctx.attachments,
4752
- _module: reactorModule,
4753
- async shutdown() {
4754
- unsubscribe?.();
4755
- try {
4756
- const status = reactorModule.reactor.kill();
4757
- await Promise.race([status.completed, new Promise((resolve) => setTimeout(resolve, 3e3))]);
4758
- } catch {}
4759
- }
4760
- };
4761
- ctx.emit?.("powerhouse:ready", { driveId });
4762
- return result;
4763
- }
4764
- //#endregion
4765
- export { generateConfigCommandHelp as A, createWorkdirStore as B, extractTemplateVars as C, installSkills as D, readSkills as E, resolveConfig as F, formatZodError as G, resolvePort as H, toUpperSnake as I, defineCommand as K, userConfigPath as L, configKeyToEnvVar as M, getMissingRequiredFields as N, createHelpCommand as O, localConfigPath as P, userStoreFolder as R, isSkillInvocation as S, renderSkillTemplate as T, resolveReactorDefaults as U, defaultPort as V, createLogger as W, IDENTITY_WRAPS as _, getProjectMapping as a, DEFAULT_SKILL_INSTRUCTION as b, defineTrigger as c, createReplSession as d, parseReplInput as f, createRoutine as g, createRoutineServiceAdapter as h, defineRegistry as i, resolveWorkdir as j, createConfigCommand as k, defineCli as l, createCompositeServiceManager as m, isDocType as n, createTypes as o, tokenizeArgs as p, readPackageInfo as q, deterministicId as r, createDocumentChangeTrigger as s, buildDefaultReactor as t, initLifecycle as u, composeWraps as v, registerDefaultHelpers as w, createSkillCommands as x, createProcessManager as y, createMemoryWorkdirStore as z };
3679
+ export { configKeyToEnvVar as A, installSkills as C, createConfigCommand as D, formatStatus as E, userConfigPath as F, userStoreFolder as I, createLogger as L, localConfigPath as M, resolveConfig as N, generateConfigCommandHelp as O, toUpperSnake as P, formatZodError as R, readSkills as S, createServiceCommands as T, createSkillCommands as _, initLifecycle as a, registerDefaultHelpers as b, tokenizeArgs as c, createRoutine as d, IDENTITY_WRAPS as f, DEFAULT_SKILL_INSTRUCTION as g, createEventBus as h, defineCli as i, getMissingRequiredFields as j, resolveWorkdir as k, createCompositeServiceManager as l, createProcessManager as m, createTypes as n, createReplSession as o, composeWraps as p, defineTrigger as r, parseReplInput as s, getProjectMapping as t, createRoutineServiceAdapter as u, isSkillInvocation as v, createHelpCommand as w, renderSkillTemplate as x, extractTemplateVars as y, readPackageInfo as z };
4766
3680
 
4767
- //# sourceMappingURL=src-BebNN3xc.mjs.map
3681
+ //# sourceMappingURL=src-055YwI8s.mjs.map