@powerhousedao/clint 0.0.0-stage → 6.2.3-dev.101

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 (53) hide show
  1. package/LICENSE +661 -0
  2. package/dist/build-skills-Cfj0OGnW.mjs +293 -0
  3. package/dist/build-skills-Cfj0OGnW.mjs.map +1 -0
  4. package/dist/dist-CUltriBW.mjs +1628 -0
  5. package/dist/dist-CUltriBW.mjs.map +1 -0
  6. package/dist/drive-BEshRPDR.mjs +84 -0
  7. package/dist/drive-BEshRPDR.mjs.map +1 -0
  8. package/dist/esm-C1DOsF1a.mjs +13140 -0
  9. package/dist/esm-C1DOsF1a.mjs.map +1 -0
  10. package/dist/events-BnwGFTjv.mjs +237 -0
  11. package/dist/events-BnwGFTjv.mjs.map +1 -0
  12. package/dist/folders-C-pFsTXT.mjs +256 -0
  13. package/dist/folders-C-pFsTXT.mjs.map +1 -0
  14. package/dist/index.d.mts +1005 -0
  15. package/dist/index.d.mts.map +1 -0
  16. package/dist/index.mjs +8 -0
  17. package/dist/local-signer-EFzJV3bn.mjs +128 -0
  18. package/dist/local-signer-EFzJV3bn.mjs.map +1 -0
  19. package/dist/markdown-D-sP2zw_.mjs +275 -0
  20. package/dist/markdown-D-sP2zw_.mjs.map +1 -0
  21. package/dist/proxy-BFR8GScT.mjs +302 -0
  22. package/dist/proxy-BFR8GScT.mjs.map +1 -0
  23. package/dist/proxy-routes-DP3ztsnS.mjs +215 -0
  24. package/dist/proxy-routes-DP3ztsnS.mjs.map +1 -0
  25. package/dist/reactor-C9VIUX1H.mjs +51 -0
  26. package/dist/reactor-C9VIUX1H.mjs.map +1 -0
  27. package/dist/rolldown-runtime-8H4AJuhK.mjs +14 -0
  28. package/dist/runners/clint-runner.d.mts +398 -0
  29. package/dist/runners/clint-runner.d.mts.map +1 -0
  30. package/dist/runners/clint-runner.mjs +522 -0
  31. package/dist/runners/clint-runner.mjs.map +1 -0
  32. package/dist/runners/mastra-runner.d.mts +300 -0
  33. package/dist/runners/mastra-runner.d.mts.map +1 -0
  34. package/dist/runners/mastra-runner.mjs +516 -0
  35. package/dist/runners/mastra-runner.mjs.map +1 -0
  36. package/dist/services-9E-r0nWl.mjs +999 -0
  37. package/dist/services-9E-r0nWl.mjs.map +1 -0
  38. package/dist/src-DD8PWpD5.mjs +4767 -0
  39. package/dist/src-DD8PWpD5.mjs.map +1 -0
  40. package/dist/start-b7Mn2cxB.mjs +1526 -0
  41. package/dist/start-b7Mn2cxB.mjs.map +1 -0
  42. package/dist/stdin-BjAO9gPK.mjs +17 -0
  43. package/dist/stdin-BjAO9gPK.mjs.map +1 -0
  44. package/dist/stream-DVuufwIj.mjs +148 -0
  45. package/dist/stream-DVuufwIj.mjs.map +1 -0
  46. package/dist/subscriptions-CfiflAsI.mjs +38 -0
  47. package/dist/subscriptions-CfiflAsI.mjs.map +1 -0
  48. package/dist/switchboard-CyvOavqL.mjs +57 -0
  49. package/dist/switchboard-CyvOavqL.mjs.map +1 -0
  50. package/dist/types-CRkoD-Mm.d.mts +1770 -0
  51. package/dist/types-CRkoD-Mm.d.mts.map +1 -0
  52. package/package.json +102 -3
  53. package/README.md +0 -3
@@ -0,0 +1,4767 @@
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-C-pFsTXT.mjs";
9
+ import { createRequire } from "node:module";
10
+ import fs, { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
11
+ import path, { basename, dirname, join, resolve } from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+ import { z } from "zod";
14
+ 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";
18
+ import { homedir } from "node:os";
19
+ import Handlebars from "handlebars";
20
+ //#region src/core/pkg.ts
21
+ /**
22
+ * Read CLI identity from the implementation project's package.json.
23
+ *
24
+ * ```ts
25
+ * import { readPackageInfo } from '@powerhousedao/ph-clint';
26
+ *
27
+ * const pkg = readPackageInfo(import.meta.url);
28
+ * export const CLI_ROOT = pkg.root;
29
+ * export const CLI_NAME = pkg.name.replace(/-cli$/, '');
30
+ * export const CLI_VERSION = pkg.version;
31
+ * ```
32
+ */
33
+ /**
34
+ * 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 `..`).
38
+ */
39
+ function readPackageInfo(importMetaUrl) {
40
+ const root = path.resolve(path.dirname(fileURLToPath(importMetaUrl)), "..");
41
+ const raw = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8"));
42
+ const name = raw.name?.replace(/^@[^/]+\//, "");
43
+ if (!name) throw new Error(`No "name" in ${root}/package.json`);
44
+ if (!raw.version) throw new Error(`No "version" in ${root}/package.json`);
45
+ return {
46
+ root,
47
+ name,
48
+ version: raw.version
49
+ };
50
+ }
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
+ }
72
+ }
73
+ return options;
74
+ }
75
+ //#endregion
76
+ //#region src/core/errors.ts
77
+ function formatZodError(err, commandId) {
78
+ if (!(err instanceof z.ZodError)) return err instanceof Error ? err.message : String(err);
79
+ return [commandId ? `Invalid arguments for '${commandId}'` : "Validation error", ...err.issues.map((issue) => {
80
+ return ` ${issue.path.length > 0 ? `--${issue.path.join(".")}` : "(input)"}: ${issue.message}`;
81
+ })].join("\n");
82
+ }
83
+ //#endregion
84
+ //#region src/core/logger.ts
85
+ const LEVELS = {
86
+ debug: 0,
87
+ info: 1,
88
+ warn: 2,
89
+ error: 3
90
+ };
91
+ const PREFIXES = {
92
+ debug: "[DEBUG] ",
93
+ info: "",
94
+ warn: "[WARN] ",
95
+ error: "[ERROR] "
96
+ };
97
+ function createLogger(level = "info", sink = (msg) => process.stderr.write(msg + "\n")) {
98
+ const threshold = LEVELS[level];
99
+ function write(lvl, msg, args) {
100
+ if (LEVELS[lvl] < threshold) return;
101
+ sink(args.length > 0 ? `${PREFIXES[lvl]}${msg} ${args.map(String).join(" ")}` : `${PREFIXES[lvl]}${msg}`);
102
+ }
103
+ return {
104
+ level,
105
+ debug: (msg, ...args) => write("debug", msg, args),
106
+ info: (msg, ...args) => write("info", msg, args),
107
+ warn: (msg, ...args) => write("warn", msg, args),
108
+ error: (msg, ...args) => write("error", msg, args)
109
+ };
110
+ }
111
+ //#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
+ //#region src/core/config.ts
314
+ /**
315
+ * Convert a camelCase string to UPPER_SNAKE_CASE.
316
+ */
317
+ function toUpperSnake(str) {
318
+ return str.replace(/-/g, "_").replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toUpperCase();
319
+ }
320
+ /**
321
+ * Derive the environment variable name for a config field.
322
+ * E.g., configKeyToEnvVar('tasks', 'defaultPriority') → 'TASKS_DEFAULT_PRIORITY'
323
+ */
324
+ function configKeyToEnvVar(cliName, field) {
325
+ return `${toUpperSnake(cliName)}_${toUpperSnake(field)}`;
326
+ }
327
+ /**
328
+ * List all config fields and their corresponding env var names.
329
+ */
330
+ function getConfigEnvVars(cliName, configSchema) {
331
+ return getSchemaFields(configSchema).map((f) => ({
332
+ name: configKeyToEnvVar(cliName, f.key),
333
+ field: f.key,
334
+ description: f.description ?? ""
335
+ }));
336
+ }
337
+ /**
338
+ * Load a JSON config/settings file.
339
+ * Returns empty object if the file doesn't exist or is invalid.
340
+ */
341
+ function loadJsonFile$1(path) {
342
+ try {
343
+ return JSON.parse(readFileSync(path, "utf-8"));
344
+ } catch {
345
+ return {};
346
+ }
347
+ }
348
+ /**
349
+ * Pick values from an env-like Record, mapping env var names back to config field names.
350
+ */
351
+ function pickEnvValues(env, cliName, configSchema) {
352
+ const fields = getSchemaFields(configSchema);
353
+ const result = {};
354
+ for (const field of fields) {
355
+ const value = env[configKeyToEnvVar(cliName, field.key)];
356
+ if (value !== void 0) result[field.key] = value;
357
+ }
358
+ return result;
359
+ }
360
+ /**
361
+ * Return the path to the local config file for a CLI.
362
+ * Located at {workdir}/.ph/{cli-name}.config.local.json.
363
+ */
364
+ function localConfigPath(workdir, cliName) {
365
+ return join(workdir, ".ph", `${cliName}.config.local.json`);
366
+ }
367
+ /**
368
+ * Return the path to the user-wide config file for a CLI.
369
+ * Located at ~/.ph/{cli-name}.config.user.json.
370
+ */
371
+ function userConfigPath(cliName) {
372
+ return join(homedir(), ".ph", `${cliName}.config.user.json`);
373
+ }
374
+ /**
375
+ * Return the path to a user-scope store folder for a CLI.
376
+ * Located at ~/.ph/{cli-name}/{subpath...}.
377
+ * When called with no subpath, returns the store root ~/.ph/{cli-name}/.
378
+ */
379
+ function userStoreFolder(cliName, ...subpath) {
380
+ return join(homedir(), ".ph", cliName, ...subpath);
381
+ }
382
+ /**
383
+ * Resolve config through 6 layers (highest priority first):
384
+ *
385
+ * 1. Config file (--config flag, path relative to cwd)
386
+ * 2. Environment variables ({CLINAME}_{FIELD_NAME})
387
+ * 3. Local config ({workdir}/.ph/{cli-name}.config.local.json)
388
+ * 4. User config (~/.ph/{cli-name}.config.user.json)
389
+ * 5. Implementation defaults (passed from project code)
390
+ * 6. Hardcoded defaults (from Zod schema .default() calls)
391
+ *
392
+ * Returns the validated, merged config object.
393
+ */
394
+ function resolveConfig(opts) {
395
+ const { configSchema, cliName, workdir, configFile, cwd, implementationDefaults } = opts;
396
+ const implDefaults = implementationDefaults ?? {};
397
+ const userConfig = loadJsonFile$1(userConfigPath(cliName));
398
+ const localConfig = loadJsonFile$1(localConfigPath(workdir, cliName));
399
+ const envValues = pickEnvValues(process.env, cliName, configSchema);
400
+ let configFileValues = {};
401
+ if (configFile) {
402
+ const baseCwd = cwd ?? process.cwd();
403
+ configFileValues = loadJsonFile$1(resolve(baseCwd, configFile));
404
+ }
405
+ const merged = {
406
+ ...implDefaults,
407
+ ...userConfig,
408
+ ...localConfig,
409
+ ...envValues,
410
+ ...configFileValues
411
+ };
412
+ return configSchema.parse(merged);
413
+ }
414
+ /**
415
+ * Identify config fields that are mandatory (no default, not optional)
416
+ * and have no value in the merged config.
417
+ */
418
+ function getMissingRequiredFields(configSchema, resolvedConfig) {
419
+ const fields = getSchemaFields(configSchema);
420
+ const missing = [];
421
+ for (const field of fields) if (!field.isOptional && !field.hasDefault && resolvedConfig[field.key] === void 0) missing.push({
422
+ key: field.key,
423
+ description: field.description ?? ""
424
+ });
425
+ return missing;
426
+ }
427
+ //#endregion
428
+ //#region src/core/workdir.ts
429
+ /**
430
+ * Resolve the working directory through a 3-level precedence:
431
+ * 1. Fallback: cwd (always available)
432
+ * 2. CLI flag: --workdir value (user override)
433
+ * 3. Implementation override (project code sets it)
434
+ *
435
+ * Higher numbers override lower. Returns an absolute path.
436
+ */
437
+ function resolveWorkdir(opts = {}) {
438
+ const base = opts.fallback ?? process.cwd();
439
+ const raw = opts.implementationOverride ?? opts.cliFlag ?? base;
440
+ return resolve(base, raw);
441
+ }
442
+ //#endregion
443
+ //#region src/core/config-command.ts
444
+ /**
445
+ * Load a JSON config file, returning empty object if missing or invalid.
446
+ */
447
+ function loadJsonFile(path) {
448
+ try {
449
+ return JSON.parse(readFileSync(path, "utf-8"));
450
+ } catch {
451
+ return {};
452
+ }
453
+ }
454
+ /** Restrictive permissions for config files holding secrets. */
455
+ const SENSITIVE_FILE_MODE = 384;
456
+ function writeJsonFile(path, data, mode) {
457
+ const dir = dirname(path);
458
+ mkdirSync(dir, { recursive: true });
459
+ const tmp = join(dir, `.${basename(path)}.tmp-${randomBytes(6).toString("hex")}`);
460
+ const contents = JSON.stringify(data, null, 2) + "\n";
461
+ try {
462
+ writeFileSync(tmp, contents, mode !== void 0 ? {
463
+ encoding: "utf-8",
464
+ mode
465
+ } : "utf-8");
466
+ try {
467
+ renameSync(tmp, path);
468
+ } catch (err) {
469
+ const code = err.code;
470
+ if (code !== "EEXIST" && code !== "EPERM") throw err;
471
+ unlinkSync(path);
472
+ renameSync(tmp, path);
473
+ }
474
+ } catch (err) {
475
+ try {
476
+ unlinkSync(tmp);
477
+ } catch {}
478
+ throw err;
479
+ }
480
+ }
481
+ /** 0600 when the object holds any sensitive key, else undefined (default perms). */
482
+ function fileModeFor(data, sensitiveKeys) {
483
+ if (!sensitiveKeys) return void 0;
484
+ for (const key of Object.keys(data)) if (sensitiveKeys.has(key)) return SENSITIVE_FILE_MODE;
485
+ }
486
+ /**
487
+ * Coerce a string value to the appropriate type based on schema field info.
488
+ */
489
+ function coerceValue(value, field) {
490
+ switch (field.baseType) {
491
+ case "number": return Number(value);
492
+ case "boolean": return value === "true" || value === "1" || value === "yes";
493
+ default: return value;
494
+ }
495
+ }
496
+ /**
497
+ * Resolve where a config value is actually coming from in the 6-layer chain.
498
+ */
499
+ function resolveSource(key, cliName, workdir, configFile) {
500
+ if (configFile) {
501
+ if (key in loadJsonFile(configFile)) return "--config file";
502
+ }
503
+ const envName = configKeyToEnvVar(cliName, key);
504
+ if (process.env[envName] !== void 0) return `env ${envName}`;
505
+ if (key in loadJsonFile(localConfigPath(workdir, cliName))) return "local";
506
+ if (key in loadJsonFile(userConfigPath(cliName))) return "user";
507
+ return "default";
508
+ }
509
+ /**
510
+ * All scope values accepted by the config command.
511
+ * Write mode only accepts 'local' and 'user'.
512
+ */
513
+ const ALL_SCOPES = [
514
+ "args",
515
+ "env",
516
+ "local",
517
+ "user",
518
+ "sys"
519
+ ];
520
+ const WRITABLE_SCOPES = /* @__PURE__ */ new Set(["local", "user"]);
521
+ /**
522
+ * Create the built-in `config` command for a CLI.
523
+ */
524
+ function createConfigCommand(opts) {
525
+ const { cliName, configSchema, sensitiveKeys, implementationDefaults } = opts;
526
+ const fields = getSchemaFields(configSchema, sensitiveKeys);
527
+ fields.map((f) => f.key);
528
+ const fieldMap = new Map(fields.map((f) => [f.key, f]));
529
+ const envToField = /* @__PURE__ */ new Map();
530
+ for (const f of fields) envToField.set(configKeyToEnvVar(cliName, f.key), f.key);
531
+ return {
532
+ id: "config",
533
+ description: "View or modify configuration settings",
534
+ inputSchema: z.object({
535
+ name: z.string().optional().describe("Setting name (camelCase) or env variable (UPPER_SNAKE)"),
536
+ write: z.string().optional().describe("Value to write"),
537
+ remove: z.boolean().optional().describe("Remove the setting from the scope"),
538
+ list: z.boolean().optional().describe("List all settings"),
539
+ scope: z.enum(ALL_SCOPES).optional().describe("Scope to read from or write to"),
540
+ revealSecrets: z.boolean().optional().describe("Show sensitive values instead of censoring them")
541
+ }),
542
+ execute: async (input, context) => {
543
+ const { name: rawName, write: newValue, remove, list, scope, revealSecrets } = input;
544
+ const reveal = !!revealSecrets;
545
+ const workdir = context.workdir;
546
+ if ([
547
+ newValue !== void 0,
548
+ !!remove,
549
+ !!list
550
+ ].filter(Boolean).length > 1) throw new Error("Options --write, --remove, and --list are mutually exclusive.");
551
+ if (list) {
552
+ if (rawName) throw new Error("--list does not accept --name.");
553
+ return listSettings(fields, cliName, workdir, scope, configSchema, opts.configFile, implementationDefaults, reveal);
554
+ }
555
+ if (!rawName) throw new Error("--name is required (use --list to show all settings).");
556
+ let settingName = rawName;
557
+ if (!fieldMap.has(settingName)) {
558
+ const upper = settingName.toUpperCase();
559
+ const fromEnv = envToField.get(settingName) ?? envToField.get(upper);
560
+ if (fromEnv) settingName = fromEnv;
561
+ else {
562
+ const validNames = [...fieldMap.keys(), ...envToField.keys()];
563
+ throw new Error(`Unknown setting "${rawName}". Valid names:\n${validNames.map((n) => ` ${n}`).join("\n")}`);
564
+ }
565
+ }
566
+ const field = fieldMap.get(settingName);
567
+ if (remove) {
568
+ const removeScope = scope ?? "local";
569
+ if (!WRITABLE_SCOPES.has(removeScope)) throw new Error(`Cannot remove from scope "${removeScope}". Only local and user are writable.`);
570
+ const filePath = removeScope === "user" ? userConfigPath(cliName) : localConfigPath(workdir, cliName);
571
+ const existing = loadJsonFile(filePath);
572
+ if (!(settingName in existing)) return { text: `${settingName} is not set in ${removeScope} config` };
573
+ delete existing[settingName];
574
+ writeJsonFile(filePath, existing, fileModeFor(existing, sensitiveKeys));
575
+ return { text: `Removed ${settingName} from ${removeScope} config` };
576
+ }
577
+ if (newValue !== void 0) {
578
+ const writeScope = scope ?? "local";
579
+ if (!WRITABLE_SCOPES.has(writeScope)) throw new Error(`Cannot write to scope "${writeScope}". Only local and user are writable.`);
580
+ const filePath = writeScope === "user" ? userConfigPath(cliName) : localConfigPath(workdir, cliName);
581
+ const coerced = coerceValue(newValue, field);
582
+ try {
583
+ const testObj = {};
584
+ testObj[settingName] = coerced;
585
+ configSchema.parse(testObj);
586
+ } catch (err) {
587
+ const msg = err instanceof Error ? err.message : String(err);
588
+ throw new Error(`Invalid value for ${settingName}: ${msg}`);
589
+ }
590
+ const existing = loadJsonFile(filePath);
591
+ existing[settingName] = coerced;
592
+ writeJsonFile(filePath, existing, fileModeFor(existing, sensitiveKeys));
593
+ return { text: `Set ${settingName} = ${JSON.stringify(coerced)} in ${writeScope} config` };
594
+ }
595
+ if (scope) return readFromScope(settingName, scope, cliName, workdir, field, configSchema, implementationDefaults, reveal);
596
+ const value = resolveConfig({
597
+ configSchema,
598
+ cliName,
599
+ workdir,
600
+ configFile: opts.configFile,
601
+ implementationDefaults
602
+ })[settingName];
603
+ const source = resolveSource(settingName, cliName, workdir, opts.configFile);
604
+ const displayValue = !reveal && field.sensitive && value !== void 0 && value !== null ? "\"***\"" : JSON.stringify(value);
605
+ return { text: `${settingName} = ${displayValue} (source: ${source})` };
606
+ }
607
+ };
608
+ }
609
+ /**
610
+ * Censor a value if the field is sensitive and reveal is not enabled.
611
+ */
612
+ function censorValue(value, field, reveal) {
613
+ if (!reveal && field.sensitive && value !== void 0 && value !== null) return "\"***\"";
614
+ return JSON.stringify(value);
615
+ }
616
+ /**
617
+ * List all settings as a formatted table.
618
+ */
619
+ function listSettings(fields, cliName, workdir, scope, configSchema, configFile, implementationDefaults, reveal = false) {
620
+ const lines = [];
621
+ const maxKeyLen = Math.max(...fields.map((f) => f.key.length));
622
+ for (const field of fields) {
623
+ const paddedKey = field.key.padEnd(maxKeyLen);
624
+ if (scope) {
625
+ const match = readFromScope(field.key, scope, cliName, workdir, field, configSchema, implementationDefaults, reveal).text.match(/= (.+?) {2}\(/);
626
+ if (match) lines.push(`${paddedKey} ${match[1]}`);
627
+ else lines.push(`${paddedKey} (not set)`);
628
+ } else try {
629
+ const value = resolveConfig({
630
+ configSchema,
631
+ cliName,
632
+ workdir,
633
+ configFile,
634
+ implementationDefaults
635
+ })[field.key];
636
+ const source = resolveSource(field.key, cliName, workdir, configFile);
637
+ lines.push(`${paddedKey} ${censorValue(value, field, reveal)} (${source})`);
638
+ } catch {
639
+ lines.push(`${paddedKey} <error>`);
640
+ }
641
+ }
642
+ return { text: lines.join("\n") };
643
+ }
644
+ /**
645
+ * Read a setting from a specific scope layer.
646
+ */
647
+ function readFromScope(key, scope, cliName, workdir, field, configSchema, implementationDefaults, reveal = false) {
648
+ switch (scope) {
649
+ case "args": return { text: `${key}: the args scope reflects the --config file, which is not accessible from this context` };
650
+ case "env": {
651
+ const envName = configKeyToEnvVar(cliName, key);
652
+ const value = process.env[envName];
653
+ if (value === void 0) return { text: `${key} is not set in environment (${envName})` };
654
+ return { text: `${key} = ${censorValue(value, field, reveal)} (env: ${envName})` };
655
+ }
656
+ case "local": {
657
+ const value = loadJsonFile(localConfigPath(workdir, cliName))[key];
658
+ if (value === void 0) return { text: `${key} is not set in local config` };
659
+ return { text: `${key} = ${censorValue(value, field, reveal)} (local)` };
660
+ }
661
+ case "user": {
662
+ const value = loadJsonFile(userConfigPath(cliName))[key];
663
+ if (value === void 0) return { text: `${key} is not set in user config` };
664
+ return { text: `${key} = ${censorValue(value, field, reveal)} (user)` };
665
+ }
666
+ case "sys": {
667
+ const defaults = implementationDefaults ?? {};
668
+ if (key in defaults) return { text: `${key} = ${censorValue(defaults[key], field, reveal)} (system default)` };
669
+ if (field.hasDefault) return { text: `${key} = ${censorValue(field.defaultValue, field, reveal)} (system default)` };
670
+ return { text: `${key} has no system default` };
671
+ }
672
+ }
673
+ }
674
+ /**
675
+ * Generate a detailed help page for the config command.
676
+ */
677
+ function generateConfigCommandHelp(cliName, configSchema, workdir, sensitiveKeys) {
678
+ const fields = getSchemaFields(configSchema, sensitiveKeys);
679
+ const lines = [];
680
+ const cliPrefix = toUpperSnake(cliName);
681
+ lines.push(`${cliName} config — View and modify configuration`);
682
+ lines.push("");
683
+ lines.push(`Usage: ${cliName} config [options]`);
684
+ lines.push("");
685
+ lines.push("Options:");
686
+ lines.push(" -n, --name <setting> Setting name");
687
+ lines.push(" -w, --write <value> Write a new value");
688
+ lines.push(" -r, --remove Remove a setting from the scope");
689
+ lines.push(" -l, --list List all settings");
690
+ lines.push(" -s, --scope <scope> Scope to read from or write to");
691
+ lines.push(" Read: args | env | local | user | sys");
692
+ lines.push(" Write/Remove: local | user (default: local)");
693
+ lines.push("");
694
+ lines.push("Examples:");
695
+ lines.push(` ${cliName} config --list Show all settings`);
696
+ lines.push(` ${cliName} config --list --scope env Show environment overrides`);
697
+ lines.push(` ${cliName} config --name watchDir Show resolved value`);
698
+ lines.push(` ${cliName} config --name watchDir --scope local Show local config value`);
699
+ lines.push(` ${cliName} config --name watchDir --write ./lib Write to local config`);
700
+ lines.push(` ${cliName} config --name watchDir --write ./lib --scope user`);
701
+ lines.push(` ${"".padEnd(cliName.length)} Write to user config`);
702
+ lines.push(` ${cliName} config --name watchDir --remove Remove from local config`);
703
+ lines.push("");
704
+ lines.push("Settings:");
705
+ lines.push("");
706
+ for (const field of fields) {
707
+ const envVar = configKeyToEnvVar(cliName, field.key);
708
+ const typeParts = [field.baseType];
709
+ if (field.isOptional) typeParts.push("optional");
710
+ if (!field.isOptional && !field.hasDefault) typeParts.push("required");
711
+ const nameLine = field.description ? ` ${field.key} — ${field.description}` : ` ${field.key}`;
712
+ lines.push(nameLine);
713
+ lines.push("");
714
+ lines.push(` Type: ${typeParts.join(", ")}`);
715
+ lines.push(` Env: ${envVar}`);
716
+ try {
717
+ const value = resolveConfig({
718
+ configSchema,
719
+ cliName,
720
+ workdir
721
+ })[field.key];
722
+ const source = resolveSource(field.key, cliName, workdir);
723
+ if (field.hasDefault || field.isOptional) lines.push(` Default: ${censorValue(field.hasDefault ? field.defaultValue : void 0, field, false)}`);
724
+ lines.push(` Value: ${censorValue(value, field, false)} (${source})`);
725
+ } catch {
726
+ lines.push(" Value: <error resolving>");
727
+ }
728
+ lines.push("");
729
+ }
730
+ lines.push("Workdir:");
731
+ lines.push("");
732
+ lines.push(" The working directory (--workdir) is resolved before configuration");
733
+ lines.push(" and determines where local config files are found. It is NOT a config");
734
+ lines.push(" parameter — it is a prerequisite for config resolution.");
735
+ lines.push("");
736
+ lines.push(" Resolution order:");
737
+ lines.push(" 1. process.cwd() Fallback (always available)");
738
+ lines.push(" 2. --workdir <path> User override via CLI flag");
739
+ lines.push(" 3. Implementation override Set by the application code");
740
+ lines.push("");
741
+ lines.push(" Higher numbers take precedence. If the application sets a workdir");
742
+ lines.push(" override, the --workdir flag is hidden from --help.");
743
+ lines.push("");
744
+ lines.push(` Current: ${workdir}`);
745
+ lines.push("");
746
+ lines.push("Location and Resolution:");
747
+ lines.push("");
748
+ lines.push(" Configuration is resolved through 5 layers (highest priority first):");
749
+ lines.push("");
750
+ lines.push(" 1. --config <file> Config file flag (path relative to cwd)");
751
+ lines.push(` 2. Environment vars ${cliPrefix}_{FIELD_NAME} format`);
752
+ lines.push(` 3. Local config ${localConfigPath(workdir, cliName)}`);
753
+ lines.push(` 4. User config ${userConfigPath(cliName)}`);
754
+ lines.push(" 5. System defaults Built-in defaults for this application");
755
+ lines.push("");
756
+ lines.push(" The --write and --remove flags target layer 3 (local) by default,");
757
+ lines.push(" or layer 4 (user) with --scope user. Layers 1, 2, and 5 are read-only.");
758
+ lines.push("");
759
+ return lines.join("\n");
760
+ }
761
+ //#endregion
762
+ //#region src/core/help-command.ts
763
+ 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
+ /**
765
+ * Create the built-in `cli-docs` command for a CLI.
766
+ *
767
+ * Captures Commander's own help output so the agent sees exactly the same
768
+ * text the user gets from `mycli help` / `mycli help <command>`, with
769
+ * headings reworded for agent context.
770
+ */
771
+ function createHelpCommand(opts) {
772
+ return {
773
+ id: "cli-docs",
774
+ description: "Show CLI help or help for a specific command",
775
+ inputSchema: z.object({ command: z.string().optional().describe("Command name to get help for (omit for general help)") }),
776
+ execute: async (input, _context) => {
777
+ const { command: commandId } = input;
778
+ const cli = opts.getCli();
779
+ const argv = ["node", cli.name];
780
+ if (commandId) argv.push(commandId, "--help");
781
+ else argv.push("--help");
782
+ const chunks = [];
783
+ await cli.run(argv, {
784
+ stdout: (msg) => chunks.push(msg),
785
+ stderr: (msg) => chunks.push(msg),
786
+ exit: () => {}
787
+ });
788
+ const helpText = chunks.join("\n").replace(/^Usage: /m, "CLI Usage: ").replace(/^Options:/m, "CLI Options:").replace(/^Commands:/m, "Commands / Agent Tools:");
789
+ return { text: `${PREAMBLE}\n\n${helpText}` };
790
+ }
791
+ };
792
+ }
793
+ //#endregion
794
+ //#region src/core/init.ts
795
+ /**
796
+ * Recursively copy a directory tree, returning the number of files copied.
797
+ */
798
+ function copyDirRecursive(src, dest) {
799
+ fs.mkdirSync(dest, { recursive: true });
800
+ let count = 0;
801
+ for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
802
+ const srcPath = path.join(src, entry.name);
803
+ const destPath = path.join(dest, entry.name);
804
+ if (entry.isDirectory()) count += copyDirRecursive(srcPath, destPath);
805
+ else {
806
+ fs.copyFileSync(srcPath, destPath);
807
+ count++;
808
+ }
809
+ }
810
+ return count;
811
+ }
812
+ /**
813
+ * Copy pre-packaged skill folders into the store's `.mastra/skills/` directory.
814
+ *
815
+ * Iterates `skillArtifacts` and uses the first directory that exists.
816
+ * Clears the target before copying to avoid stale skills.
817
+ * Each skill folder is expected to contain at least a `SKILL.md` file.
818
+ *
819
+ * @returns The number of skill folders copied, or 0 if no source was found.
820
+ */
821
+ function installSkills(options) {
822
+ const { store, skillArtifacts, stdout = console.log } = options;
823
+ const targetDir = store.getStoreFolder(".mastra/skills");
824
+ const source = skillArtifacts.find((s) => fs.existsSync(s));
825
+ if (!source) {
826
+ stdout("[init] No skill source directory found — skipping skill installation");
827
+ return 0;
828
+ }
829
+ stdout(`[init] Installing skills from ${source}`);
830
+ const skillDirs = fs.readdirSync(source, { withFileTypes: true }).filter((d) => d.isDirectory() && !d.name.startsWith(".")).map((d) => d.name);
831
+ if (skillDirs.length === 0) {
832
+ stdout("[init] No skill folders found in source — skipping");
833
+ return 0;
834
+ }
835
+ if (fs.existsSync(targetDir)) fs.rmSync(targetDir, { recursive: true });
836
+ fs.mkdirSync(targetDir, { recursive: true });
837
+ let totalFiles = 0;
838
+ for (const skillName of skillDirs) {
839
+ const src = path.join(source, skillName);
840
+ const dest = path.join(targetDir, skillName);
841
+ totalFiles += copyDirRecursive(src, dest);
842
+ }
843
+ stdout(`[init] Installed ${skillDirs.length} skills (${totalFiles} files)`);
844
+ return skillDirs.length;
845
+ }
846
+ //#endregion
847
+ //#region src/core/skills.ts
848
+ /**
849
+ * Parse YAML-ish frontmatter from a SKILL.md file.
850
+ * Only extracts `name` and `description` — no YAML parser dependency needed.
851
+ */
852
+ function parseFrontmatter(content) {
853
+ const match = content.match(/^---\n([\s\S]*?)\n---/);
854
+ if (!match) return null;
855
+ const block = match[1];
856
+ const nameMatch = block.match(/^name:\s*(.+)$/m);
857
+ const descMatch = block.match(/^description:\s*"?([^"\n]+)"?$/m);
858
+ if (!nameMatch) return null;
859
+ return {
860
+ name: nameMatch[1].trim(),
861
+ description: descMatch ? descMatch[1].trim() : ""
862
+ };
863
+ }
864
+ /**
865
+ * Read skill metadata from artifact directories.
866
+ *
867
+ * Scans each artifact directory for `{skillName}/SKILL.md` files, parses
868
+ * frontmatter, and returns a deduplicated sorted list. First directory wins
869
+ * on name collisions. When a name appears in more than one root, `onWarn` is
870
+ * invoked once per collision so the caller can surface the conflict.
871
+ *
872
+ * Convention: codegen orders artifacts as `[skills-tpl/, skills-ext/]`, so
873
+ * tpl always wins over ext. The warning message names both roots verbatim.
874
+ */
875
+ function readSkills(artifacts, onWarn) {
876
+ const seenAt = /* @__PURE__ */ new Map();
877
+ const skills = [];
878
+ for (const source of artifacts) {
879
+ if (!fs.existsSync(source)) continue;
880
+ let entries;
881
+ try {
882
+ entries = fs.readdirSync(source, { withFileTypes: true });
883
+ } catch {
884
+ continue;
885
+ }
886
+ for (const entry of entries) {
887
+ if (!entry.isDirectory()) continue;
888
+ const skillMdPath = path.join(source, entry.name, "SKILL.md");
889
+ if (!fs.existsSync(skillMdPath)) continue;
890
+ const existing = seenAt.get(entry.name);
891
+ if (existing !== void 0) {
892
+ onWarn?.(`Skill "${entry.name}" exists in both ${existing} and ${source} — using ${existing}`);
893
+ continue;
894
+ }
895
+ try {
896
+ const info = parseFrontmatter(fs.readFileSync(skillMdPath, "utf-8"));
897
+ if (info) {
898
+ seenAt.set(entry.name, source);
899
+ const cliDocsPath = path.join(source, entry.name, ".cli-docs.md");
900
+ const hasDocs = fs.existsSync(cliDocsPath);
901
+ skills.push({
902
+ ...info,
903
+ skillMdPath,
904
+ ...hasDocs && { cliDocsPath }
905
+ });
906
+ }
907
+ } catch {}
908
+ }
909
+ }
910
+ return skills.sort((a, b) => a.name.localeCompare(b.name));
911
+ }
912
+ //#endregion
913
+ //#region src/core/templates.ts
914
+ /**
915
+ * Known helper names — both custom defaults and Handlebars built-ins.
916
+ * Used by extractTemplateVars to filter out helper references.
917
+ */
918
+ const KNOWN_HELPERS = /* @__PURE__ */ new Set([
919
+ "formatDate",
920
+ "join",
921
+ "exists",
922
+ "eq",
923
+ "uppercase",
924
+ "lowercase",
925
+ "hasItems",
926
+ "default",
927
+ "if",
928
+ "unless",
929
+ "each",
930
+ "with",
931
+ "lookup",
932
+ "log"
933
+ ]);
934
+ /**
935
+ * Register the 8 standard Handlebars helpers on a Handlebars instance.
936
+ */
937
+ function registerDefaultHelpers(hbs) {
938
+ hbs.registerHelper("formatDate", (date, format) => {
939
+ if (!date) return "";
940
+ const d = new Date(date);
941
+ if (format === "time") return d.toLocaleTimeString();
942
+ if (format === "date") return d.toLocaleDateString();
943
+ return d.toISOString();
944
+ });
945
+ hbs.registerHelper("join", (arr, sep) => Array.isArray(arr) ? arr.join(typeof sep === "string" ? sep : ", ") : "");
946
+ hbs.registerHelper("exists", (value) => value !== void 0 && value !== null && value !== "");
947
+ hbs.registerHelper("eq", (a, b) => a === b);
948
+ hbs.registerHelper("uppercase", (s) => typeof s === "string" ? s.toUpperCase() : "");
949
+ hbs.registerHelper("lowercase", (s) => typeof s === "string" ? s.toLowerCase() : "");
950
+ hbs.registerHelper("hasItems", (arr) => Array.isArray(arr) && arr.length > 0);
951
+ hbs.registerHelper("default", (value, defaultValue) => value !== void 0 && value !== null && value !== "" ? value : defaultValue);
952
+ }
953
+ /**
954
+ * Walk a Handlebars AST and return all top-level variable names referenced.
955
+ * Filters out known helpers and built-in block helpers.
956
+ */
957
+ function extractTemplateVars(template) {
958
+ const ast = Handlebars.parse(template);
959
+ const vars = /* @__PURE__ */ new Set();
960
+ const visitor = new Handlebars.Visitor();
961
+ function collectParams(params) {
962
+ if (!params) return;
963
+ for (const p of params) if (p.type === "PathExpression") {
964
+ const expr = p;
965
+ const root = expr.parts[0];
966
+ if (root && !KNOWN_HELPERS.has(expr.original) && !expr.data && expr.depth === 0) vars.add(root);
967
+ }
968
+ }
969
+ visitor.MustacheStatement = function(stmt) {
970
+ const p = stmt.path;
971
+ if (p.type === "PathExpression") {
972
+ const expr = p;
973
+ const root = expr.parts[0];
974
+ if (root && !KNOWN_HELPERS.has(expr.original) && !expr.data && expr.depth === 0) vars.add(root);
975
+ }
976
+ collectParams(stmt.params);
977
+ Handlebars.Visitor.prototype.MustacheStatement.call(this, stmt);
978
+ };
979
+ visitor.SubExpression = function(sexpr) {
980
+ collectParams(sexpr.params);
981
+ Handlebars.Visitor.prototype.SubExpression.call(this, sexpr);
982
+ };
983
+ visitor.BlockStatement = function(block) {
984
+ collectParams(block.params);
985
+ Handlebars.Visitor.prototype.BlockStatement.call(this, block);
986
+ };
987
+ visitor.accept(ast);
988
+ return vars;
989
+ }
990
+ /**
991
+ * Render a Handlebars template with default helpers and missing-variable detection.
992
+ * Uses Handlebars.create() for isolation — no global state pollution.
993
+ */
994
+ function renderSkillTemplate(template, context, options) {
995
+ const hbs = Handlebars.create();
996
+ registerDefaultHelpers(hbs);
997
+ if (options?.helpers) for (const [name, fn] of Object.entries(options.helpers)) hbs.registerHelper(name, fn);
998
+ const vars = extractTemplateVars(template);
999
+ const contextKeys = new Set(Object.keys(context));
1000
+ const extraKnown = options?.knownHelpers ? new Set(options.knownHelpers) : /* @__PURE__ */ new Set();
1001
+ const customHelperNames = options?.helpers ? new Set(Object.keys(options.helpers)) : /* @__PURE__ */ new Set();
1002
+ const warnings = [];
1003
+ for (const v of [...vars].sort()) if (!contextKeys.has(v) && !extraKnown.has(v) && !customHelperNames.has(v)) warnings.push(`Template references "{{${v}}}" but context has no value for it`);
1004
+ return {
1005
+ rendered: hbs.compile(template, { noEscape: true })(context),
1006
+ warnings
1007
+ };
1008
+ }
1009
+ //#endregion
1010
+ //#region src/core/skill-commands.ts
1011
+ /**
1012
+ * Default Handlebars template for skill instructions.
1013
+ */
1014
+ const DEFAULT_SKILL_INSTRUCTION = "Use your {{skillId}} skill for the following instructions: {{prompt}}";
1015
+ /**
1016
+ * Type guard for SkillInvocation.
1017
+ */
1018
+ function isSkillInvocation(v) {
1019
+ return typeof v === "object" && v !== null && v.type === "skill-invocation";
1020
+ }
1021
+ /**
1022
+ * Normalize a SkillConfig value — accepts plain string shorthand.
1023
+ */
1024
+ function normalizeSkillConfig(value) {
1025
+ return typeof value === "string" ? { description: value } : value;
1026
+ }
1027
+ /**
1028
+ * Input schema for skill commands — a single optional --prompt flag.
1029
+ */
1030
+ const skillInputSchema = z.object({ prompt: z.string().optional().describe("Instructions for the skill") });
1031
+ /**
1032
+ * Validate that an instructionTemplate includes the {{prompt}} variable.
1033
+ * Returns a warning string if missing, or undefined if ok.
1034
+ */
1035
+ function validateInstructionTemplate(skillName, template) {
1036
+ if (!extractTemplateVars(template).has("prompt")) return `Skill "${skillName}": instructionTemplate does not include {{prompt}} — the user's message will not be forwarded to the agent`;
1037
+ }
1038
+ /**
1039
+ * Create CLI commands from skill metadata and optional skill configs.
1040
+ * Each skill becomes a thin command with a --prompt flag that returns a SkillInvocation.
1041
+ *
1042
+ * Emits warnings to stderr when a custom instructionTemplate omits {{prompt}}.
1043
+ */
1044
+ function createSkillCommands(skills, skillConfigs) {
1045
+ return skills.map((skill) => {
1046
+ const rawConfig = skillConfigs?.[skill.name];
1047
+ const config = rawConfig ? normalizeSkillConfig(rawConfig) : void 0;
1048
+ const description = config?.description || skill.description || `Use the ${skill.name} skill`;
1049
+ if (config?.instructionTemplate) {
1050
+ const warning = validateInstructionTemplate(skill.name, config.instructionTemplate);
1051
+ if (warning) console.warn(`[ph-clint] ${warning}`);
1052
+ }
1053
+ let inputSchema = skillInputSchema;
1054
+ if (config?.inputSchema && config.inputSchema instanceof z.ZodObject) {
1055
+ const extraFields = config.inputSchema.shape;
1056
+ const baseShape = skillInputSchema.shape;
1057
+ inputSchema = z.object({
1058
+ ...baseShape,
1059
+ ...extraFields
1060
+ });
1061
+ }
1062
+ return {
1063
+ id: skill.name,
1064
+ description,
1065
+ inputSchema,
1066
+ execute: async (input) => ({
1067
+ type: "skill-invocation",
1068
+ skillName: skill.name,
1069
+ userMessage: input.prompt,
1070
+ ...config?.instructionTemplate && { instructionTemplate: config.instructionTemplate },
1071
+ inputValues: input
1072
+ })
1073
+ };
1074
+ });
1075
+ }
1076
+ //#endregion
1077
+ //#region src/core/processes.ts
1078
+ /**
1079
+ * Create a process manager for running bounded shell commands.
1080
+ * Inspired by the agent prototype's CLIExecutor.
1081
+ */
1082
+ function createProcessManager() {
1083
+ const handles = [];
1084
+ async function run(command, opts) {
1085
+ const label = opts?.label ?? command;
1086
+ const timeout = opts?.timeout ?? 3e4;
1087
+ return new Promise((resolve) => {
1088
+ const chunks = [];
1089
+ let resolved = false;
1090
+ let lineBuffer = "";
1091
+ const child = spawn(command, {
1092
+ shell: true,
1093
+ stdio: [
1094
+ "ignore",
1095
+ "pipe",
1096
+ "pipe"
1097
+ ],
1098
+ ...supervisedSpawnOptions(),
1099
+ cwd: opts?.cwd,
1100
+ env: opts?.env ? {
1101
+ ...process.env,
1102
+ ...opts.env
1103
+ } : void 0
1104
+ });
1105
+ function killProcess() {
1106
+ try {
1107
+ if (child.pid) killTree(child.pid, "SIGTERM");
1108
+ } catch {}
1109
+ }
1110
+ const handle = {
1111
+ label,
1112
+ status: "running",
1113
+ kill() {
1114
+ if (handle.status === "running") killProcess();
1115
+ }
1116
+ };
1117
+ handles.push(handle);
1118
+ function handleData(data) {
1119
+ const text = data.toString();
1120
+ chunks.push(text);
1121
+ if (opts?.onOutput) {
1122
+ lineBuffer += text;
1123
+ let nlIdx;
1124
+ while ((nlIdx = lineBuffer.indexOf("\n")) !== -1) {
1125
+ opts.onOutput(lineBuffer.slice(0, nlIdx));
1126
+ lineBuffer = lineBuffer.slice(nlIdx + 1);
1127
+ }
1128
+ }
1129
+ }
1130
+ child.stdout?.on("data", handleData);
1131
+ child.stderr?.on("data", handleData);
1132
+ child.unref();
1133
+ function finish(success, output) {
1134
+ if (resolved) return;
1135
+ resolved = true;
1136
+ clearTimeout(timer);
1137
+ if (opts?.onOutput && lineBuffer.length > 0) {
1138
+ opts.onOutput(lineBuffer);
1139
+ lineBuffer = "";
1140
+ }
1141
+ handle.status = success ? "succeeded" : "failed";
1142
+ resolve({
1143
+ success,
1144
+ output
1145
+ });
1146
+ }
1147
+ const timer = setTimeout(() => {
1148
+ killProcess();
1149
+ finish(false, chunks.join(""));
1150
+ }, timeout);
1151
+ child.on("close", (code) => {
1152
+ finish(code === 0, chunks.join(""));
1153
+ });
1154
+ /* istanbul ignore next -- with shell: true, failures come via exit code, not error event */
1155
+ child.on("error", (err) => {
1156
+ finish(false, err.message);
1157
+ });
1158
+ });
1159
+ }
1160
+ function list() {
1161
+ return [...handles];
1162
+ }
1163
+ return {
1164
+ run,
1165
+ list
1166
+ };
1167
+ }
1168
+ //#endregion
1169
+ //#region src/core/wraps.ts
1170
+ /**
1171
+ * The identity registry — every wrap is a passthrough.
1172
+ *
1173
+ * `agentStream` returns `inner` directly (not a wrapping async generator) so
1174
+ * the no-instrumentation path adds zero generator frames per yield. The
1175
+ * other wraps reduce to immediate `inner()` calls which V8 inlines.
1176
+ */
1177
+ const IDENTITY_WRAPS = {
1178
+ command: (_id, inner) => inner(),
1179
+ agentStream: (inner) => inner,
1180
+ tool: (_name, tool) => tool,
1181
+ routineIteration: (_attrs, inner) => inner()
1182
+ };
1183
+ /**
1184
+ * Compose two registries left-to-right: the result invokes `a`'s wrap first
1185
+ * (outer), then `b`'s wrap (inner). For the identity element, this is a
1186
+ * no-op.
1187
+ *
1188
+ * Composition semantics by wrap shape:
1189
+ * - `command` / `routineIteration` (invoke-around): `b` runs inside `a`'s body.
1190
+ * - `agentStream` / `tool` (decorate-and-return): `b` decorates the result of `a`.
1191
+ */
1192
+ function mergeWraps(a, b) {
1193
+ return {
1194
+ command: b.command ? (id, inner) => a.command(id, () => b.command(id, inner)) : a.command,
1195
+ agentStream: b.agentStream ? (inner, attrs) => b.agentStream(a.agentStream(inner, attrs), attrs) : a.agentStream,
1196
+ tool: b.tool ? (name, tool) => b.tool(name, a.tool(name, tool)) : a.tool,
1197
+ routineIteration: b.routineIteration ? (attrs, inner) => a.routineIteration(attrs, () => b.routineIteration(attrs, inner)) : a.routineIteration
1198
+ };
1199
+ }
1200
+ /**
1201
+ * Fold a list of LifecycleHandle contributions into a single WrapRegistry,
1202
+ * starting from IDENTITY_WRAPS.
1203
+ *
1204
+ * Empty input (no lifecycle hooks registered, or every hook returned no
1205
+ * contributions) yields IDENTITY_WRAPS — core's call sites are unconditional.
1206
+ */
1207
+ function composeWraps(handles) {
1208
+ return handles.map((h) => h.contribute ?? {}).reduce(mergeWraps, IDENTITY_WRAPS);
1209
+ }
1210
+ //#endregion
1211
+ //#region src/core/routine.ts
1212
+ /**
1213
+ * Create a routine — a tick-based execution loop with pluggable triggers.
1214
+ * Inspired by the agent prototype's AgentRoutine.
1215
+ *
1216
+ * State machine: init → ready → running ↔ stopping
1217
+ */
1218
+ function createRoutine(options) {
1219
+ const tickInterval = options.tickInterval ?? 2e3;
1220
+ const idleInterval = options.idleInterval ?? 500;
1221
+ const bus = options.eventBus ?? createEventBus();
1222
+ const pm = options.processManager ?? createProcessManager();
1223
+ let ctx = options.context ?? {
1224
+ workspace: createMemoryWorkdirStore(),
1225
+ config: {},
1226
+ workdir: "",
1227
+ stdout: console.log,
1228
+ runProcess: (cmd, opts) => pm.run(cmd, {
1229
+ ...opts,
1230
+ onOutput: (line) => ctx.stdout(line + "\n")
1231
+ })
1232
+ };
1233
+ if (!ctx.emit) ctx.emit = (event, data) => bus.emit(event, data);
1234
+ if (!ctx.on) ctx.on = (event, handler) => bus.on(event, handler);
1235
+ let status = "init";
1236
+ let loopPromise = null;
1237
+ let stopRequested = false;
1238
+ const queue = [];
1239
+ let getReactor = options.getReactor;
1240
+ let getAgent = options.getAgent;
1241
+ let wraps = IDENTITY_WRAPS;
1242
+ function makeTriggerContext(trigger) {
1243
+ const state = trigger.state ? trigger.state() : {};
1244
+ const reactorAccessor = () => getReactor?.() ?? Promise.resolve(void 0);
1245
+ const agentAccessor = () => getAgent?.() ?? Promise.resolve(void 0);
1246
+ return {
1247
+ get context() {
1248
+ return ctx;
1249
+ },
1250
+ get commandContext() {
1251
+ return {
1252
+ ...ctx,
1253
+ reactor: reactorAccessor,
1254
+ agent: agentAccessor
1255
+ };
1256
+ },
1257
+ state,
1258
+ reactor: reactorAccessor,
1259
+ agent: agentAccessor
1260
+ };
1261
+ }
1262
+ const triggerContexts = /* @__PURE__ */ new Map();
1263
+ for (const trigger of options.triggers) triggerContexts.set(trigger.id, makeTriggerContext(trigger));
1264
+ async function executeWorkItem(item) {
1265
+ switch (item.type) {
1266
+ case "function": {
1267
+ const fn = item.params.fn;
1268
+ return fn();
1269
+ }
1270
+ case "command": {
1271
+ const commandId = item.params.commandId;
1272
+ const args = item.params.args ?? {};
1273
+ const cmd = options.commands.get(commandId);
1274
+ if (!cmd) throw new Error(`Unknown command: ${commandId}`);
1275
+ const parsed = cmd.inputSchema.parse(args);
1276
+ const extCtx = {
1277
+ ...ctx,
1278
+ routine,
1279
+ processes: pm,
1280
+ emit: (event, data) => bus.emit(event, data)
1281
+ };
1282
+ return cmd.execute(parsed, extCtx);
1283
+ }
1284
+ default: {
1285
+ const _exhaustive = item.type;
1286
+ throw new Error(`Unknown work item type: ${_exhaustive}`);
1287
+ }
1288
+ }
1289
+ }
1290
+ async function loop() {
1291
+ for (const trigger of options.triggers) if (trigger.setup) {
1292
+ const tCtx = triggerContexts.get(trigger.id);
1293
+ await trigger.setup(tCtx);
1294
+ }
1295
+ status = "running";
1296
+ let iterationIndex = 0;
1297
+ while (!stopRequested) {
1298
+ const iterationStart = Date.now();
1299
+ await wraps.routineIteration({ index: iterationIndex }, async () => {
1300
+ for (const trigger of options.triggers) {
1301
+ const tCtx = triggerContexts.get(trigger.id);
1302
+ try {
1303
+ const item = await trigger.poll(tCtx);
1304
+ if (item) queue.push(item);
1305
+ } catch (err) {
1306
+ ctx.log?.warn?.(`[routine] trigger ${trigger.id} poll error: ${err instanceof Error ? err.message : String(err)}`);
1307
+ ctx.log?.debug?.(`[routine] trigger ${trigger.id} stack: ${err instanceof Error ? err.stack : ""}`);
1308
+ }
1309
+ }
1310
+ if (queue.length > 0) {
1311
+ const item = queue.shift();
1312
+ try {
1313
+ const result = await executeWorkItem(item);
1314
+ if (routine.onOutput && result !== void 0 && result !== null) {
1315
+ const text = typeof result === "object" && result !== null && "text" in result ? result.text : String(result);
1316
+ if (text) routine.onOutput(text);
1317
+ }
1318
+ await item.callbacks?.onSuccess?.(result);
1319
+ } catch (error) {
1320
+ await item.callbacks?.onFailure?.(error instanceof Error ? error : new Error(String(error)));
1321
+ }
1322
+ }
1323
+ });
1324
+ iterationIndex++;
1325
+ const elapsed = Date.now() - iterationStart;
1326
+ const idle = Math.max(idleInterval, tickInterval - elapsed);
1327
+ await new Promise((r) => setTimeout(r, idle));
1328
+ }
1329
+ for (const trigger of options.triggers) if (trigger.teardown) try {
1330
+ await trigger.teardown(triggerContexts.get(trigger.id));
1331
+ } catch {}
1332
+ status = "ready";
1333
+ stopRequested = false;
1334
+ }
1335
+ const routine = {
1336
+ onOutput: void 0,
1337
+ onChunk: void 0,
1338
+ get status() {
1339
+ return status;
1340
+ },
1341
+ get triggerIds() {
1342
+ return options.triggers.map((t) => t.id);
1343
+ },
1344
+ get queueLength() {
1345
+ return queue.length;
1346
+ },
1347
+ start() {
1348
+ if (status === "running") return;
1349
+ if (status === "init" || status === "ready") {
1350
+ stopRequested = false;
1351
+ if (status === "init") status = "ready";
1352
+ loopPromise = loop();
1353
+ }
1354
+ },
1355
+ async stop() {
1356
+ if (status !== "running") return;
1357
+ status = "stopping";
1358
+ stopRequested = true;
1359
+ if (loopPromise) {
1360
+ await loopPromise;
1361
+ loopPromise = null;
1362
+ }
1363
+ },
1364
+ setContext(newCtx) {
1365
+ ctx = newCtx;
1366
+ if (!routine.onOutput) {
1367
+ const buf = [];
1368
+ routine.onOutput = (text) => {
1369
+ buf.push(text);
1370
+ while (buf.length > 500) buf.shift();
1371
+ };
1372
+ }
1373
+ ctx.stdout = (text) => {
1374
+ routine.onOutput(text);
1375
+ };
1376
+ ctx.runProcess = (cmd, opts) => {
1377
+ const toolName = cmd;
1378
+ let segmentOpened = false;
1379
+ return pm.run(cmd, {
1380
+ ...opts,
1381
+ onOutput: (line) => {
1382
+ if (!segmentOpened) {
1383
+ segmentOpened = true;
1384
+ routine.onChunk?.({
1385
+ type: "tool-call",
1386
+ toolName,
1387
+ args: {}
1388
+ });
1389
+ }
1390
+ routine.onChunk?.({
1391
+ type: "tool-output",
1392
+ toolName,
1393
+ text: line
1394
+ });
1395
+ routine.onOutput?.(line);
1396
+ }
1397
+ }).then((result) => {
1398
+ if (segmentOpened) {
1399
+ const chunk = {
1400
+ type: "tool-result",
1401
+ toolName,
1402
+ result: { text: `exit ${result.success ? 0 : 1}` },
1403
+ isError: !result.success
1404
+ };
1405
+ routine.onChunk?.(chunk);
1406
+ }
1407
+ return result;
1408
+ });
1409
+ };
1410
+ },
1411
+ setCapabilities(caps) {
1412
+ if (caps.getReactor) getReactor = caps.getReactor;
1413
+ if (caps.getAgent) getAgent = caps.getAgent;
1414
+ if (caps.wraps) wraps = caps.wraps;
1415
+ }
1416
+ };
1417
+ return routine;
1418
+ }
1419
+ //#endregion
1420
+ //#region src/core/routine-service.ts
1421
+ const DEFAULT_LOG_BUFFER_SIZE = 500;
1422
+ /**
1423
+ * Create a ServiceManager adapter that wraps a Routine,
1424
+ * giving it the same command surface as a process-based service.
1425
+ */
1426
+ function createRoutineServiceAdapter(routine, config, eventBus) {
1427
+ const id = config.id;
1428
+ const name = config.name ?? slugToTitle(id);
1429
+ const logBuffer = [];
1430
+ let instanceWorkdir;
1431
+ const originalOnOutput = routine.onOutput;
1432
+ routine.onOutput = (text) => {
1433
+ logBuffer.push(text);
1434
+ while (logBuffer.length > DEFAULT_LOG_BUFFER_SIZE) logBuffer.shift();
1435
+ originalOnOutput?.(text);
1436
+ };
1437
+ function mapStatus() {
1438
+ switch (routine.status) {
1439
+ case "init":
1440
+ case "ready": return "idle";
1441
+ case "running": return "ready";
1442
+ case "stopping": return "stopping";
1443
+ }
1444
+ }
1445
+ function getInstanceStatus() {
1446
+ return {
1447
+ serviceId: id,
1448
+ instanceId: id,
1449
+ name,
1450
+ status: mapStatus(),
1451
+ ...instanceWorkdir && { workdir: instanceWorkdir }
1452
+ };
1453
+ }
1454
+ const syntheticDef = {
1455
+ id,
1456
+ name,
1457
+ command: "",
1458
+ maxInstances: 1,
1459
+ ...config.projectScanner && { projectScanner: config.projectScanner }
1460
+ };
1461
+ async function start(_id, opts) {
1462
+ if (_id !== id) throw new Error(`Unknown service: ${_id}`);
1463
+ if (routine.status === "running") throw new Error(`Service ${id} is already running`);
1464
+ if (opts?.workdir) instanceWorkdir = opts.workdir;
1465
+ routine.start();
1466
+ eventBus?.emit("service:ready", {
1467
+ id,
1468
+ instanceId: id,
1469
+ name
1470
+ });
1471
+ return id;
1472
+ }
1473
+ async function stop(_id) {
1474
+ if (_id !== id) throw new Error(`Unknown service: ${_id}`);
1475
+ if (routine.status !== "running") throw new Error(`Service ${id} is not running`);
1476
+ await routine.stop();
1477
+ eventBus?.emit("service:stopped", {
1478
+ id,
1479
+ instanceId: id,
1480
+ name
1481
+ });
1482
+ }
1483
+ function list(serviceId) {
1484
+ if (serviceId && serviceId !== id) return [];
1485
+ return [getInstanceStatus()];
1486
+ }
1487
+ function getDefinition(_id) {
1488
+ return _id === id ? syntheticDef : void 0;
1489
+ }
1490
+ function logs(_id, _instanceId, lines = 50) {
1491
+ if (_id !== id) throw new Error(`Unknown service: ${_id}`);
1492
+ return logBuffer.slice(-lines).join("\n");
1493
+ }
1494
+ function watchLogs(_id, _instanceId, onLine) {
1495
+ if (_id !== id) throw new Error(`Unknown service: ${_id}`);
1496
+ const prevOnOutput = routine.onOutput;
1497
+ routine.onOutput = (text) => {
1498
+ prevOnOutput?.(text);
1499
+ onLine(text);
1500
+ };
1501
+ return () => {
1502
+ routine.onOutput = prevOnOutput ?? void 0;
1503
+ };
1504
+ }
1505
+ function watchChunks(_id, _instanceId, onChunk) {
1506
+ if (_id !== id) throw new Error(`Unknown service: ${_id}`);
1507
+ const prevOnChunk = routine.onChunk;
1508
+ routine.onChunk = (chunk) => {
1509
+ prevOnChunk?.(chunk);
1510
+ onChunk(chunk);
1511
+ };
1512
+ return () => {
1513
+ routine.onChunk = prevOnChunk ?? void 0;
1514
+ };
1515
+ }
1516
+ function scanProjects$1(_id, rootDir) {
1517
+ if (_id !== id) throw new Error(`Unknown service: ${_id}`);
1518
+ if (!config.projectScanner) return [];
1519
+ return scanProjects(rootDir, config.projectScanner);
1520
+ }
1521
+ function purgeStoppedInstances(_id) {
1522
+ if (_id !== id) throw new Error(`Unknown service: ${_id}`);
1523
+ logBuffer.length = 0;
1524
+ }
1525
+ return {
1526
+ start,
1527
+ stop,
1528
+ list,
1529
+ getDefinition,
1530
+ logs,
1531
+ watchLogs,
1532
+ watchChunks,
1533
+ scanProjects: scanProjects$1,
1534
+ purgeStoppedInstances
1535
+ };
1536
+ }
1537
+ /**
1538
+ * Create a composite ServiceManager that routes calls to the correct
1539
+ * underlying manager based on service ID.
1540
+ */
1541
+ function createCompositeServiceManager(managers, routeMap) {
1542
+ function getManager(id) {
1543
+ const mgr = routeMap.get(id);
1544
+ if (!mgr) throw new Error(`Unknown service: ${id}`);
1545
+ return mgr;
1546
+ }
1547
+ async function start(id, opts) {
1548
+ return getManager(id).start(id, opts);
1549
+ }
1550
+ async function stop(id, instanceId) {
1551
+ return getManager(id).stop(id, instanceId);
1552
+ }
1553
+ function list(serviceId) {
1554
+ if (serviceId) return getManager(serviceId).list(serviceId);
1555
+ const results = [];
1556
+ for (const mgr of managers) results.push(...mgr.list());
1557
+ return results;
1558
+ }
1559
+ function getDefinition(id) {
1560
+ return routeMap.get(id)?.getDefinition(id);
1561
+ }
1562
+ function logs(id, instanceId, lines) {
1563
+ return getManager(id).logs(id, instanceId, lines);
1564
+ }
1565
+ function watchLogs(id, instanceId, onLine) {
1566
+ return getManager(id).watchLogs(id, instanceId, onLine);
1567
+ }
1568
+ function watchChunks(id, instanceId, onChunk) {
1569
+ return getManager(id).watchChunks(id, instanceId, onChunk);
1570
+ }
1571
+ function scanProjects(id, rootDir) {
1572
+ return getManager(id).scanProjects(id, rootDir);
1573
+ }
1574
+ function purgeStoppedInstances(id) {
1575
+ return getManager(id).purgeStoppedInstances(id);
1576
+ }
1577
+ return {
1578
+ start,
1579
+ stop,
1580
+ list,
1581
+ getDefinition,
1582
+ logs,
1583
+ watchLogs,
1584
+ watchChunks,
1585
+ scanProjects,
1586
+ purgeStoppedInstances
1587
+ };
1588
+ }
1589
+ //#endregion
1590
+ //#region src/interactive/router.ts
1591
+ /**
1592
+ * Parse a REPL input line.
1593
+ *
1594
+ * - Empty/whitespace → { type: 'empty' }
1595
+ * - /exit or /quit → { type: 'exit' }
1596
+ * - /cmd --arg val → { type: 'command', commandId: 'cmd', args: ['--arg', 'val'] }
1597
+ * - Anything else → { type: 'unknown' }
1598
+ */
1599
+ function parseReplInput(input, commandIds, hasDefaultCommand) {
1600
+ const trimmed = input.trim();
1601
+ if (!trimmed) return {
1602
+ type: "empty",
1603
+ raw: trimmed
1604
+ };
1605
+ if (!trimmed.startsWith("/")) {
1606
+ if (hasDefaultCommand) return {
1607
+ type: "text",
1608
+ raw: trimmed
1609
+ };
1610
+ return {
1611
+ type: "unknown",
1612
+ raw: trimmed
1613
+ };
1614
+ }
1615
+ const match = trimmed.match(/^\/(\S+)\s*(.*)/);
1616
+ if (!match) return {
1617
+ type: "unknown",
1618
+ raw: trimmed
1619
+ };
1620
+ const [, name, rest] = match;
1621
+ const cmdName = name.toLowerCase();
1622
+ if (cmdName === "exit" || cmdName === "quit") return {
1623
+ type: "exit",
1624
+ raw: trimmed
1625
+ };
1626
+ if (commandIds.includes(cmdName)) return {
1627
+ type: "command",
1628
+ commandId: cmdName,
1629
+ args: tokenizeArgs(rest),
1630
+ raw: trimmed
1631
+ };
1632
+ return {
1633
+ type: "unknown",
1634
+ commandId: cmdName,
1635
+ raw: trimmed
1636
+ };
1637
+ }
1638
+ /**
1639
+ * Tokenize an argument string, respecting quoted values.
1640
+ *
1641
+ * Examples:
1642
+ * `--name Alice` → ['--name', 'Alice']
1643
+ * `--title "Hello World"` → ['--title', 'Hello World']
1644
+ * `--title 'Hello World'` → ['--title', 'Hello World']
1645
+ */
1646
+ function tokenizeArgs(argsStr) {
1647
+ const tokens = [];
1648
+ let current = "";
1649
+ let inQuote = false;
1650
+ let quoteChar = "";
1651
+ for (const ch of argsStr) if (inQuote) {
1652
+ if (ch === quoteChar) inQuote = false;
1653
+ else current += ch;
1654
+ } else if (ch === "\"" || ch === "'") {
1655
+ inQuote = true;
1656
+ quoteChar = ch;
1657
+ } else if (ch === " " || ch === " ") {
1658
+ if (current) {
1659
+ tokens.push(current);
1660
+ current = "";
1661
+ }
1662
+ } else current += ch;
1663
+ if (current) tokens.push(current);
1664
+ return tokens;
1665
+ }
1666
+ //#endregion
1667
+ //#region src/interactive/session.ts
1668
+ /**
1669
+ * Format a command result for display.
1670
+ * If the result has a `.text` string property, use that.
1671
+ * Otherwise, convert to string.
1672
+ */
1673
+ function formatResult$1(result) {
1674
+ if (result === void 0 || result === null) return "";
1675
+ if (typeof result === "object" && result !== null && "text" in result && typeof result.text === "string") return result.text;
1676
+ return String(result);
1677
+ }
1678
+ /**
1679
+ * Determine which fields need interactive prompting for a command.
1680
+ *
1681
+ * @param explicitKeys - keys explicitly provided by the user (from argv flags)
1682
+ *
1683
+ * Prompting only triggers when required fields are missing. If all required
1684
+ * fields are satisfied, the command executes immediately — even if there are
1685
+ * optional fields listed in `promptOptional`.
1686
+ *
1687
+ * When prompting IS triggered (because required fields are missing):
1688
+ * - Missing required fields → prompt
1689
+ * - Fields in `promptOptional` not explicitly provided → also prompt
1690
+ * - Fields with defaults when `promptForDefaults` is true → also prompt
1691
+ *
1692
+ * This means `promptOptional` = "if you're already prompting, ask for these too".
1693
+ */
1694
+ function getFieldsToPrompt(commandId, explicitKeys, cli) {
1695
+ const cmd = cli.getCommand(commandId);
1696
+ if (!cmd) return [];
1697
+ const fields = getSchemaFields(cmd.inputSchema);
1698
+ const prompt = cmd.prompt;
1699
+ if (fields.filter((f) => !explicitKeys.has(f.key) && !f.isOptional && !f.hasDefault).length === 0) return [];
1700
+ return fields.filter((f) => {
1701
+ if (explicitKeys.has(f.key)) return false;
1702
+ if (!f.isOptional && !f.hasDefault) return true;
1703
+ if (prompt?.promptForDefaults && f.hasDefault) return true;
1704
+ if (prompt?.promptOptional?.includes(f.key)) return true;
1705
+ return false;
1706
+ });
1707
+ }
1708
+ /**
1709
+ * Extract which keys the user explicitly provided from raw argv tokens.
1710
+ * Counts both --flag tokens and leading positional tokens (mapped to
1711
+ * positional field keys in declared order).
1712
+ */
1713
+ function getExplicitKeys(argv, positional) {
1714
+ const keys = /* @__PURE__ */ new Set();
1715
+ const positionalKeys = positional ?? [];
1716
+ let positionalIdx = 0;
1717
+ let sawFlag = false;
1718
+ for (const arg of argv) if (arg.startsWith("--")) {
1719
+ sawFlag = true;
1720
+ keys.add(arg.slice(2));
1721
+ } else if (!sawFlag && positionalIdx < positionalKeys.length) {
1722
+ keys.add(positionalKeys[positionalIdx]);
1723
+ positionalIdx++;
1724
+ }
1725
+ return keys;
1726
+ }
1727
+ /**
1728
+ * Build the prompt text for a field, including type hint and default.
1729
+ */
1730
+ function buildPromptText(field) {
1731
+ const parts = [];
1732
+ if (field.baseType === "enum") parts.push(field.description ?? field.key);
1733
+ else if (field.baseType === "boolean") parts.push(`${field.description ?? field.key} (true/false)`);
1734
+ else parts.push(field.description ?? field.key);
1735
+ if (field.hasDefault) parts.push(`[${field.defaultValue}]`);
1736
+ return parts.join(" ");
1737
+ }
1738
+ /**
1739
+ * Create a REPL session — the testable logic layer for interactive mode.
1740
+ *
1741
+ * The session processes input lines (e.g. `/greet --name Alice`),
1742
+ * dispatches them to commands, and returns formatted output.
1743
+ * It is independent of Ink rendering.
1744
+ */
1745
+ function createReplSession(opts) {
1746
+ const { cli, context, agentProvider } = opts;
1747
+ const threadId = opts.threadId ?? (agentProvider ? randomUUID() : void 0);
1748
+ const commands = cli.listCommands();
1749
+ const commandIds = commands.map((c) => c.id);
1750
+ const hasDefaultCommand = cli.hasAgent;
1751
+ let prompting = null;
1752
+ let sessionRef = null;
1753
+ let currentAbortController = null;
1754
+ /** Render an agent prompt from a SkillInvocation using its template. */
1755
+ function renderSkillPromptFromInvocation(invocation) {
1756
+ const { rendered, warnings } = renderSkillTemplate(invocation.instructionTemplate ?? "Use your {{skillId}} skill for the following instructions: {{prompt}}", {
1757
+ skillId: invocation.skillName,
1758
+ prompt: invocation.userMessage ?? "",
1759
+ ...invocation.inputValues ?? {}
1760
+ });
1761
+ for (const w of warnings) console.warn(`[ph-clint] Skill "${invocation.skillName}": ${w}`);
1762
+ return rendered.trim();
1763
+ }
1764
+ function buildExitMessage() {
1765
+ const parts = [];
1766
+ if (context.services) {
1767
+ const dim = "\x1B[2m";
1768
+ const reset = "\x1B[0m";
1769
+ const active = context.services.list().filter((s) => s.status === "ready" || s.status === "starting");
1770
+ for (const svc of active) {
1771
+ 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`);
1773
+ }
1774
+ }
1775
+ if (threadId) parts.push(`Goodbye! \x1b[2mTo resume, run: ${cli.name} -i --resume ${threadId}\x1b[0m`);
1776
+ else parts.push("Goodbye!");
1777
+ return parts.join("\n");
1778
+ }
1779
+ /**
1780
+ * Execute a command while capturing ctx.stdout() calls.
1781
+ * When the command produces progressive output (calls ctx.stdout),
1782
+ * emits tool-call / tool-output / tool-result chunks so the REPL
1783
+ * renders it in a rolling window. Commands without progressive output
1784
+ * stream as text-delta (no segment overhead).
1785
+ */
1786
+ async function executeCommandWithCapture(commandId, args) {
1787
+ const captured = [];
1788
+ const streamParts = [];
1789
+ let segmentOpened = false;
1790
+ const origStdout = context.stdout;
1791
+ context.stdout = (text) => {
1792
+ captured.push(text);
1793
+ if (!segmentOpened) {
1794
+ segmentOpened = true;
1795
+ const callChunk = {
1796
+ type: "tool-call",
1797
+ toolName: commandId,
1798
+ args
1799
+ };
1800
+ streamParts.push(formatStreamChunk(callChunk));
1801
+ sessionRef?.onStreamChunk?.(callChunk, streamParts.join(""));
1802
+ }
1803
+ const chunk = {
1804
+ type: "tool-output",
1805
+ toolName: commandId,
1806
+ text
1807
+ };
1808
+ streamParts.push(formatStreamChunk(chunk));
1809
+ sessionRef?.onStreamChunk?.(chunk, streamParts.join(""));
1810
+ };
1811
+ try {
1812
+ const result = await cli.execute(commandId, args, context);
1813
+ context.stdout = origStdout;
1814
+ if (isSkillInvocation(result)) return handleAgentPrompt(renderSkillPromptFromInvocation(result));
1815
+ const text = formatResult$1(result);
1816
+ if (segmentOpened) {
1817
+ const resultChunk = {
1818
+ type: "tool-result",
1819
+ toolName: commandId,
1820
+ result: { text },
1821
+ isError: false
1822
+ };
1823
+ streamParts.push(formatStreamChunk(resultChunk));
1824
+ sessionRef?.onStreamChunk?.(resultChunk, streamParts.join(""));
1825
+ }
1826
+ const rendered = renderMarkdown(text);
1827
+ const prefix = captured.length > 0 ? captured.join("") : "";
1828
+ return {
1829
+ text: prefix && rendered ? prefix + rendered : prefix + rendered,
1830
+ type: "result"
1831
+ };
1832
+ } catch (err) {
1833
+ context.stdout = origStdout;
1834
+ throw err;
1835
+ }
1836
+ }
1837
+ /**
1838
+ * Return the next prompt output for the current prompting state,
1839
+ * or execute the command if all fields are collected.
1840
+ */
1841
+ async function advancePrompt() {
1842
+ const state = prompting;
1843
+ if (state.remainingFields.length === 0) {
1844
+ const { commandId, collectedArgs } = state;
1845
+ prompting = null;
1846
+ try {
1847
+ const cmd = cli.getCommand(commandId);
1848
+ return await executeCommandWithCapture(commandId, cli.parseArgs(commandId, argsToArgv(collectedArgs, cmd?.positional)));
1849
+ } catch (err) {
1850
+ return {
1851
+ text: formatZodError(err, commandId),
1852
+ type: "error"
1853
+ };
1854
+ }
1855
+ }
1856
+ const field = state.remainingFields[0];
1857
+ return {
1858
+ text: buildPromptText(field),
1859
+ type: "prompt",
1860
+ promptLabel: field.key
1861
+ };
1862
+ }
1863
+ /**
1864
+ * Convert a collected args map back to argv-style tokens for parseArgs.
1865
+ * Positional fields are emitted first, in declared order, then flags.
1866
+ */
1867
+ function argsToArgv(args, positional) {
1868
+ const argv = [];
1869
+ const positionalKeys = positional ?? [];
1870
+ const positionalSet = new Set(positionalKeys);
1871
+ for (const key of positionalKeys) {
1872
+ const value = args[key];
1873
+ if (value === void 0 || value === null || value === "") break;
1874
+ argv.push(String(value));
1875
+ }
1876
+ for (const [key, value] of Object.entries(args)) {
1877
+ if (positionalSet.has(key)) continue;
1878
+ if (typeof value === "boolean") {
1879
+ if (value) argv.push(`--${key}`);
1880
+ } else if (value !== void 0 && value !== null && value !== "") argv.push(`--${key}`, String(value));
1881
+ }
1882
+ return argv;
1883
+ }
1884
+ async function handlePromptAnswer(input) {
1885
+ if (!prompting) return {
1886
+ text: "",
1887
+ type: "empty"
1888
+ };
1889
+ const field = prompting.remainingFields[0];
1890
+ const trimmed = input.trim();
1891
+ if (trimmed === "" && field.hasDefault) {} else if (trimmed === "" && (field.isOptional || field.hasDefault)) {} else if (trimmed === "") return {
1892
+ text: `${field.key} is required`,
1893
+ type: "prompt",
1894
+ promptLabel: field.key
1895
+ };
1896
+ else if (field.baseType === "boolean") prompting.collectedArgs[field.key] = trimmed === "true" || trimmed === "1" || trimmed === "yes";
1897
+ else prompting.collectedArgs[field.key] = trimmed;
1898
+ prompting.remainingFields = prompting.remainingFields.slice(1);
1899
+ return advancePrompt();
1900
+ }
1901
+ async function processInput(input) {
1902
+ if (prompting) return handlePromptAnswer(input);
1903
+ const parsed = parseReplInput(input, commandIds, hasDefaultCommand);
1904
+ switch (parsed.type) {
1905
+ case "empty": return {
1906
+ text: "",
1907
+ type: "empty"
1908
+ };
1909
+ case "exit": return {
1910
+ text: buildExitMessage(),
1911
+ type: "exit"
1912
+ };
1913
+ case "text": return handleAgentPrompt(parsed.raw);
1914
+ case "unknown":
1915
+ if (parsed.commandId) return {
1916
+ text: `Unknown command: /${parsed.commandId}. Type /cli-docs for available commands.`,
1917
+ type: "error"
1918
+ };
1919
+ return {
1920
+ text: "Commands start with /. Type /cli-docs for available commands.",
1921
+ type: "error"
1922
+ };
1923
+ case "command": {
1924
+ if (parsed.commandId?.endsWith("-manage")) {
1925
+ const serviceId = parsed.commandId.slice(0, -7);
1926
+ if (!context.services?.getDefinition(serviceId)) return {
1927
+ text: `Unknown service: ${serviceId}`,
1928
+ type: "error"
1929
+ };
1930
+ return {
1931
+ text: "",
1932
+ type: "panel",
1933
+ panelId: `services:${serviceId}`
1934
+ };
1935
+ }
1936
+ const cmdForKeys = cli.getCommand(parsed.commandId);
1937
+ const explicitKeys = getExplicitKeys(parsed.args, cmdForKeys?.positional);
1938
+ try {
1939
+ const args = cli.parseArgs(parsed.commandId, parsed.args);
1940
+ const fieldsToPrompt = getFieldsToPrompt(parsed.commandId, explicitKeys, cli);
1941
+ if (fieldsToPrompt.length > 0) {
1942
+ prompting = {
1943
+ commandId: parsed.commandId,
1944
+ collectedArgs: { ...args },
1945
+ remainingFields: fieldsToPrompt
1946
+ };
1947
+ return advancePrompt();
1948
+ }
1949
+ return await executeCommandWithCapture(parsed.commandId, args);
1950
+ } catch (err) {
1951
+ const msg = formatZodError(err, parsed.commandId);
1952
+ const cmd = cli.getCommand(parsed.commandId);
1953
+ if (cmd?.prompt && (msg.includes("Missing required option") || msg.includes("Missing required argument"))) {
1954
+ const partialArgs = parseArgsPartial(parsed.args, cmd);
1955
+ const fieldsToPrompt = getFieldsToPrompt(parsed.commandId, explicitKeys, cli);
1956
+ if (fieldsToPrompt.length > 0) {
1957
+ prompting = {
1958
+ commandId: parsed.commandId,
1959
+ collectedArgs: partialArgs,
1960
+ remainingFields: fieldsToPrompt
1961
+ };
1962
+ return advancePrompt();
1963
+ }
1964
+ }
1965
+ return {
1966
+ text: msg,
1967
+ type: "error"
1968
+ };
1969
+ }
1970
+ }
1971
+ }
1972
+ }
1973
+ /**
1974
+ * Parse args without throwing on missing required fields.
1975
+ * Used to collect whatever args were provided before entering prompting.
1976
+ */
1977
+ function parseArgsPartial(argv, cmd) {
1978
+ if (!cmd) return {};
1979
+ const fields = getSchemaFields(cmd.inputSchema);
1980
+ const positionalKeys = cmd.positional ?? [];
1981
+ const result = {};
1982
+ let positionalIdx = 0;
1983
+ for (let i = 0; i < argv.length; i++) {
1984
+ const arg = argv[i];
1985
+ if (!arg.startsWith("--")) {
1986
+ if (positionalIdx < positionalKeys.length) {
1987
+ result[positionalKeys[positionalIdx]] = arg;
1988
+ positionalIdx++;
1989
+ }
1990
+ continue;
1991
+ }
1992
+ const flagName = arg.slice(2);
1993
+ const field = fields.find((f) => f.key === flagName);
1994
+ if (!field) continue;
1995
+ if (field.baseType === "boolean") result[field.key] = true;
1996
+ else {
1997
+ const nextArg = argv[i + 1];
1998
+ if (nextArg !== void 0 && !nextArg.startsWith("--")) {
1999
+ result[field.key] = nextArg;
2000
+ i++;
2001
+ }
2002
+ }
2003
+ }
2004
+ for (const field of fields) {
2005
+ if (field.key in result) continue;
2006
+ if (field.hasDefault && !cmd.prompt?.promptOptional?.includes(field.key) && !cmd.prompt?.promptForDefaults) result[field.key] = field.defaultValue;
2007
+ }
2008
+ return result;
2009
+ }
2010
+ /**
2011
+ * Head-crop a tool-result body: keep at most `windowSize` lines,
2012
+ * append truncation indicator if exceeded.
2013
+ */
2014
+ function cropToolBody(body, windowSize) {
2015
+ const lines = body.split("\n");
2016
+ if (lines.length <= windowSize) return body;
2017
+ const kept = lines.slice(0, windowSize);
2018
+ const omitted = lines.length - windowSize;
2019
+ kept.push(`\x1b[2m... (${omitted} more lines)\x1b[0m`);
2020
+ return kept.join("\n");
2021
+ }
2022
+ /**
2023
+ * Format a tool-result chunk for the history result.
2024
+ * Status line + cropped body, as pre-formatted (non-markdown) text.
2025
+ */
2026
+ function formatToolResult(chunk, windowSize) {
2027
+ const formatted = formatStreamChunk(chunk).trim();
2028
+ const nlIdx = formatted.indexOf("\n");
2029
+ if (nlIdx === -1) return formatted;
2030
+ const statusLine = formatted.slice(0, nlIdx);
2031
+ const body = formatted.slice(nlIdx + 1);
2032
+ return statusLine + "\n" + cropToolBody(body, windowSize);
2033
+ }
2034
+ async function handleAgentPrompt(text) {
2035
+ if (!agentProvider) return {
2036
+ text: "Agent not available",
2037
+ type: "error"
2038
+ };
2039
+ try {
2040
+ const segments = [];
2041
+ const commandMap = new Map(commands.map((c) => [c.id, c]));
2042
+ currentAbortController = new AbortController();
2043
+ const stream = agentProvider.stream(text, {
2044
+ threadId,
2045
+ tools: commandMap,
2046
+ abortSignal: currentAbortController.signal
2047
+ });
2048
+ const windowSize = sessionRef?.outputWindow ?? 6;
2049
+ const streamParts = [];
2050
+ const toolSegs = [];
2051
+ context._onToolOutput = (toolName, outputText) => {
2052
+ const toolOutputChunk = {
2053
+ type: "tool-output",
2054
+ toolName,
2055
+ text: outputText
2056
+ };
2057
+ const display = formatStreamChunk(toolOutputChunk);
2058
+ const match = toolSegs.find((t) => !t.complete && t.toolName === toolName) ?? toolSegs.find((t) => !t.complete);
2059
+ if (match) segments[match.index].content += display;
2060
+ streamParts.push(display);
2061
+ sessionRef?.onStreamChunk?.(toolOutputChunk, streamParts.join(""));
2062
+ };
2063
+ for await (const chunk of stream) {
2064
+ const isText = chunk.type === "text-delta";
2065
+ let display;
2066
+ if (chunk.type === "tool-result") display = formatToolResult(chunk, windowSize);
2067
+ else display = formatStreamChunk(chunk);
2068
+ if (chunk.type === "tool-call") {
2069
+ segments.push({
2070
+ content: display,
2071
+ isText: false
2072
+ });
2073
+ toolSegs.push({
2074
+ index: segments.length - 1,
2075
+ toolCallId: chunk.toolCallId,
2076
+ toolName: chunk.toolName,
2077
+ complete: false
2078
+ });
2079
+ } else if (chunk.type === "tool-result") {
2080
+ const match = (chunk.toolCallId ? toolSegs.find((t) => !t.complete && t.toolCallId === chunk.toolCallId) : void 0) ?? toolSegs.find((t) => !t.complete && t.toolName === chunk.toolName) ?? toolSegs.find((t) => !t.complete);
2081
+ if (match) {
2082
+ segments[match.index].content += display;
2083
+ match.complete = true;
2084
+ } else segments.push({
2085
+ content: display,
2086
+ isText: false
2087
+ });
2088
+ } else if (isText) {
2089
+ const last = segments[segments.length - 1];
2090
+ if (last && last.isText) last.content += display;
2091
+ else segments.push({
2092
+ content: display,
2093
+ isText: true
2094
+ });
2095
+ } else {
2096
+ const last = segments[segments.length - 1];
2097
+ if (last && !last.isText) last.content += display;
2098
+ else segments.push({
2099
+ content: display,
2100
+ isText: false
2101
+ });
2102
+ }
2103
+ streamParts.push(display);
2104
+ sessionRef?.onStreamChunk?.(chunk, streamParts.join(""));
2105
+ }
2106
+ context._onToolOutput = void 0;
2107
+ currentAbortController = null;
2108
+ return {
2109
+ text: segments.map((seg) => {
2110
+ const trimmed = seg.content.trim();
2111
+ if (seg.isText) return renderMarkdown(trimmed);
2112
+ return trimmed.split("\n").map((line, j) => {
2113
+ if (j === 0) return line;
2114
+ if (j === 1) return " ⎿ " + line;
2115
+ return " " + line;
2116
+ }).join("\n");
2117
+ }).filter((s) => s !== "").join("\n\n"),
2118
+ type: "result"
2119
+ };
2120
+ } catch (err) {
2121
+ currentAbortController = null;
2122
+ if (err instanceof Error && err.name === "AbortError") return {
2123
+ text: "(interrupted)",
2124
+ type: "result"
2125
+ };
2126
+ return {
2127
+ text: err instanceof Error ? err.message : String(err),
2128
+ type: "error"
2129
+ };
2130
+ }
2131
+ }
2132
+ const session = {
2133
+ processInput,
2134
+ getCompletions: (partial) => prompting ? [] : getCompletions(partial, commands),
2135
+ getGhostSuggestion: (input) => prompting ? null : getGhostSuggestion(input, commands),
2136
+ getCompletionSuffix: (completion, input) => getCompletionSuffix(completion, input, commands),
2137
+ get isPrompting() {
2138
+ return prompting !== null;
2139
+ },
2140
+ welcome: typeof cli.interactive?.welcome === "function" ? void 0 : cli.interactive?.welcome,
2141
+ get exitMessage() {
2142
+ return buildExitMessage();
2143
+ },
2144
+ outputWindow: (cli.interactive && "outputWindow" in cli.interactive ? cli.interactive.outputWindow : void 0) ?? 6,
2145
+ abortCurrentStream() {
2146
+ if (currentAbortController) {
2147
+ const origError = console.error;
2148
+ console.error = (...args) => {
2149
+ const first = args[0];
2150
+ if (typeof first === "string" && first.includes("Error in LLM execution")) return;
2151
+ origError.apply(console, args);
2152
+ };
2153
+ currentAbortController.abort();
2154
+ currentAbortController = null;
2155
+ setTimeout(() => {
2156
+ console.error = origError;
2157
+ }, 100);
2158
+ }
2159
+ }
2160
+ };
2161
+ sessionRef = session;
2162
+ return session;
2163
+ }
2164
+ //#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
+ //#region src/core/runtime.ts
2937
+ 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;
2941
+ const skipRoutineStart = deps.skipRoutineStart ?? false;
2942
+ const wraps = deps.wraps ?? IDENTITY_WRAPS;
2943
+ const lifecycleShutdown = deps.lifecycleShutdown;
2944
+ let cachedReactor;
2945
+ let switchboardInstance;
2946
+ let cachedProvider;
2947
+ async function getReactor() {
2948
+ if (cachedReactor) return cachedReactor;
2949
+ if (!reactorConfig) return void 0;
2950
+ cachedReactor = await reactorConfig.create({
2951
+ workdir,
2952
+ config,
2953
+ workspace,
2954
+ emit: context.emit,
2955
+ on: context.on,
2956
+ switchboard: reactorConfig.switchboard,
2957
+ attachments: deps.attachments
2958
+ });
2959
+ return cachedReactor;
2960
+ }
2961
+ async function getAgent() {
2962
+ if (cachedProvider) return cachedProvider;
2963
+ if (!agentLoader) return void 0;
2964
+ await getReactor();
2965
+ const agentCtx = {
2966
+ workdir,
2967
+ config,
2968
+ cliName,
2969
+ cliVersion,
2970
+ context,
2971
+ commands: [...commandMap.values()].filter((c) => !skillIds.has(c.id)),
2972
+ skills: resolvedSkills,
2973
+ prompts,
2974
+ wraps
2975
+ };
2976
+ cachedProvider = await agentLoader(agentCtx);
2977
+ return cachedProvider;
2978
+ }
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
+ async function teardown() {
3020
+ if (routine && routine.status === "running") {
3021
+ log.debug("Stopping routine...");
3022
+ await routine.stop();
3023
+ }
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();
3031
+ }
3032
+ if (cachedReactor) {
3033
+ log.debug("Stopping Reactor...");
3034
+ await cachedReactor.shutdown();
3035
+ }
3036
+ if (lifecycleShutdown) {
3037
+ log.debug("Stopping lifecycle hooks...");
3038
+ await lifecycleShutdown();
3039
+ }
3040
+ }
3041
+ function reportActiveServices(output) {
3042
+ if (!context.services) return;
3043
+ const dim = "\x1B[2m";
3044
+ const reset = "\x1B[0m";
3045
+ const active = context.services.list().filter((s) => s.status === "ready" || s.status === "starting");
3046
+ for (let i = 0; i < active.length; i++) {
3047
+ const svc = active[i];
3048
+ 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}`);
3050
+ }
3051
+ }
3052
+ async function startupSequence(output) {
3053
+ try {
3054
+ if (proxyInstance) output(`Proxy listening on ${proxyInstance.url}`);
3055
+ if (reactorConfig) {
3056
+ log.debug("Starting Reactor...");
3057
+ await getReactor();
3058
+ log.debug(`Reactor storage: ${workspace.getStoreFolder("reactor-storage")}`);
3059
+ output(`Reactor ready (drive: ${cachedReactor.driveId})`);
3060
+ if (cachedReactor.personalDriveId) {
3061
+ const { createFolderOperations, createFolderCommands } = await import("./folders-C-pFsTXT.mjs").then((n) => n.t);
3062
+ const folderOps = createFolderOperations(cachedReactor.client, cachedReactor.personalDriveId, log);
3063
+ context.folders = folderOps;
3064
+ const folderCmds = createFolderCommands(folderOps);
3065
+ for (const cmd of folderCmds) commandMap.set(cmd.id, cmd);
3066
+ }
3067
+ }
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
+ if (routine && !skipRoutineStart) {
3107
+ routine.setContext(context);
3108
+ routine.start();
3109
+ output("Routine running");
3110
+ }
3111
+ } catch (err) {
3112
+ await teardown();
3113
+ throw err;
3114
+ }
3115
+ }
3116
+ if (routine) routine.setCapabilities({
3117
+ getReactor,
3118
+ getAgent,
3119
+ wraps
3120
+ });
3121
+ return {
3122
+ getReactor,
3123
+ getAgent,
3124
+ startupSequence,
3125
+ teardown,
3126
+ reportActiveServices
3127
+ };
3128
+ }
3129
+ //#endregion
3130
+ //#region src/core/lifecycle.ts
3131
+ /**
3132
+ * Run each registered lifecycle hook's `onInit` in declaration order with the
3133
+ * given context, then compose their contributions into a single wrap registry.
3134
+ *
3135
+ * Empty input → IDENTITY_WRAPS, no-op shutdown.
3136
+ *
3137
+ * Errors from a hook's onInit propagate — a failing plugin halts CLI startup
3138
+ * (a partial-init state is worse than failure).
3139
+ */
3140
+ async function initLifecycle(hooks, ctx) {
3141
+ if (hooks.length === 0) return {
3142
+ wraps: IDENTITY_WRAPS,
3143
+ shutdown: async () => {},
3144
+ handles: []
3145
+ };
3146
+ const handles = [];
3147
+ for (const hook of hooks) {
3148
+ const handle = await hook.onInit(ctx);
3149
+ handles.push(handle);
3150
+ }
3151
+ return {
3152
+ wraps: composeWraps(handles),
3153
+ shutdown: async () => {
3154
+ for (let i = handles.length - 1; i >= 0; i--) {
3155
+ const handle = handles[i];
3156
+ if (handle.shutdown) try {
3157
+ await handle.shutdown();
3158
+ } catch (err) {
3159
+ process.stderr.write(`[lifecycle] shutdown error in ${hooks[i]?.name ?? "unknown"}: ${err instanceof Error ? err.message : String(err)}\n`);
3160
+ }
3161
+ }
3162
+ },
3163
+ handles
3164
+ };
3165
+ }
3166
+ //#endregion
3167
+ //#region src/core/cli.ts
3168
+ /* istanbul ignore next -- fallback stdout used only when running without RunOptions (real terminal) */
3169
+ const defaultStdout = (text) => {
3170
+ process.stdout.write(text);
3171
+ };
3172
+ /**
3173
+ * Format a command result for output.
3174
+ * If the result has a `.text` string property, use that.
3175
+ * Otherwise, convert to string.
3176
+ */
3177
+ function formatResult(result) {
3178
+ if (result === void 0 || result === null) return void 0;
3179
+ if (typeof result === "object" && result !== null && "text" in result && typeof result.text === "string") return result.text;
3180
+ return String(result);
3181
+ }
3182
+ /**
3183
+ * Resolve a Resolvable<T> value — call it if it's a function, return it otherwise.
3184
+ */
3185
+ function resolveValue(value, ctx) {
3186
+ return typeof value === "function" ? value(ctx) : value;
3187
+ }
3188
+ /**
3189
+ * Define a CLI — the top-level entry point.
3190
+ *
3191
+ * When a `configSchema` is provided, TSchema is inferred automatically,
3192
+ * giving typed `config` in agent factories, `Resolvable` callbacks, and
3193
+ * interactive config.
3194
+ */
3195
+ function defineCli(options) {
3196
+ const sensitiveKeys = /* @__PURE__ */ new Set();
3197
+ if (options.secretsSchema && options.configSchema) {
3198
+ const secretsObj = options.secretsSchema;
3199
+ for (const key of Object.keys(secretsObj.shape)) sensitiveKeys.add(key);
3200
+ const configObj = options.configSchema;
3201
+ options = {
3202
+ ...options,
3203
+ configSchema: configObj.merge(secretsObj)
3204
+ };
3205
+ }
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
+ if (options.lifecycle && options.lifecycle.length > 0 && options.configSchema) {
3219
+ let merged = options.configSchema;
3220
+ for (const hook of options.lifecycle) if (hook.configSchema) merged = merged.merge(hook.configSchema);
3221
+ if (merged !== options.configSchema) options = {
3222
+ ...options,
3223
+ configSchema: merged
3224
+ };
3225
+ }
3226
+ const commandMap = /* @__PURE__ */ new Map();
3227
+ for (const cmd of options.commands) commandMap.set(cmd.id, cmd);
3228
+ let activeConfigFile;
3229
+ let activeWorkdir = process.cwd();
3230
+ const configFieldCount = options.configSchema ? getSchemaFields(options.configSchema).length : 0;
3231
+ if (configFieldCount > 0 && !commandMap.has("config")) {
3232
+ const configCmd = createConfigCommand({
3233
+ cliName: options.name,
3234
+ configSchema: options.configSchema,
3235
+ sensitiveKeys,
3236
+ implementationDefaults: options.configDefaults,
3237
+ get configFile() {
3238
+ return activeConfigFile;
3239
+ }
3240
+ });
3241
+ commandMap.set("config", configCmd);
3242
+ }
3243
+ const hasTriggers = options.triggers && options.triggers.length > 0;
3244
+ const hasServices = options.services && options.services.length > 0;
3245
+ const serviceGroups = /* @__PURE__ */ new Map();
3246
+ if (hasServices) for (const svcDef of options.services) {
3247
+ const cmds = createServiceCommands(svcDef);
3248
+ const svcGroup = {
3249
+ name: resolveServiceName(svcDef),
3250
+ description: svcDef.description
3251
+ };
3252
+ for (const cmd of cmds) {
3253
+ if (!commandMap.has(cmd.id)) commandMap.set(cmd.id, cmd);
3254
+ serviceGroups.set(cmd.id, svcGroup);
3255
+ }
3256
+ }
3257
+ let cliRef;
3258
+ if (!commandMap.has("cli-docs")) commandMap.set("cli-docs", createHelpCommand({ getCli: () => cliRef }));
3259
+ let resolvedSkills = [];
3260
+ if (options.prompts && options.prompts.artifacts.length > 0) {
3261
+ resolvedSkills = readSkills(options.prompts.artifacts);
3262
+ const skillCmds = createSkillCommands(resolvedSkills, options.prompts.skills);
3263
+ for (const cmd of skillCmds) if (!commandMap.has(cmd.id)) commandMap.set(cmd.id, cmd);
3264
+ }
3265
+ const skillIds = new Set(resolvedSkills.map((s) => s.name));
3266
+ let _eventBus;
3267
+ function getEventBus() {
3268
+ if (!_eventBus) _eventBus = createEventBus();
3269
+ return _eventBus;
3270
+ }
3271
+ const eventBus = hasTriggers || hasServices ? getEventBus() : void 0;
3272
+ const processManager = createProcessManager();
3273
+ let routine;
3274
+ let routineServiceAdapter;
3275
+ if (hasTriggers) {
3276
+ routine = createRoutine({
3277
+ triggers: options.triggers,
3278
+ commands: commandMap,
3279
+ tickInterval: options.routine?.tickInterval,
3280
+ idleInterval: options.routine?.idleInterval,
3281
+ eventBus,
3282
+ processManager
3283
+ });
3284
+ if (options.routine?.id) {
3285
+ const routineConfig = options.routine;
3286
+ const routineName = routineConfig.name ?? slugToTitle(routineConfig.id);
3287
+ const syntheticDef = {
3288
+ id: routineConfig.id,
3289
+ name: routineName,
3290
+ command: "",
3291
+ maxInstances: 1,
3292
+ ...routineConfig.projectScanner && { projectScanner: routineConfig.projectScanner }
3293
+ };
3294
+ const cmds = createServiceCommands(syntheticDef);
3295
+ const svcGroup = { name: routineName };
3296
+ for (const cmd of cmds) {
3297
+ if (!commandMap.has(cmd.id)) commandMap.set(cmd.id, cmd);
3298
+ serviceGroups.set(cmd.id, svcGroup);
3299
+ }
3300
+ routineServiceAdapter = createRoutineServiceAdapter(routine, routineConfig, eventBus);
3301
+ }
3302
+ }
3303
+ let agentLoader;
3304
+ function configureAgent(loader) {
3305
+ agentLoader = loader;
3306
+ }
3307
+ let reactorConfig;
3308
+ 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
+ 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
+ }
3338
+ function getCommand(id) {
3339
+ return commandMap.get(id);
3340
+ }
3341
+ function listCommands() {
3342
+ return [...commandMap.values()];
3343
+ }
3344
+ function buildContext(base) {
3345
+ const noop = () => Promise.resolve({
3346
+ success: true,
3347
+ output: ""
3348
+ });
3349
+ const ctx = {
3350
+ workdir: process.cwd(),
3351
+ workspace: createMemoryWorkdirStore(),
3352
+ config: options.configSchema ? options.configSchema.parse({}) : {},
3353
+ stdout: defaultStdout,
3354
+ runProcess: noop,
3355
+ ...base
3356
+ };
3357
+ if (routine) ctx.routine = routine;
3358
+ ctx.processes = processManager;
3359
+ ctx.runProcess = (cmd, opts) => processManager.run(cmd, {
3360
+ ...opts,
3361
+ onOutput: (line) => ctx.stdout(line + "\n")
3362
+ });
3363
+ ctx.emit = (event, data) => getEventBus().emit(event, data);
3364
+ ctx.on = (event, handler) => getEventBus().on(event, handler);
3365
+ return ctx;
3366
+ }
3367
+ async function execute(commandId, args, context) {
3368
+ const cmd = commandMap.get(commandId);
3369
+ if (!cmd) throw new Error(`Unknown command: ${commandId}`);
3370
+ let parsed;
3371
+ try {
3372
+ parsed = cmd.inputSchema.parse(args);
3373
+ } catch (err) {
3374
+ throw new Error(formatZodError(err, commandId));
3375
+ }
3376
+ const ctx = buildContext(context);
3377
+ return cmd.execute(parsed, ctx);
3378
+ }
3379
+ function parseArgs(commandId, argv) {
3380
+ const cmd = commandMap.get(commandId);
3381
+ if (!cmd) throw new Error(`Unknown command: ${commandId}`);
3382
+ const fields = getSchemaFields(cmd.inputSchema);
3383
+ const positionalKeys = cmd.positional ?? [];
3384
+ const positionalSet = new Set(positionalKeys);
3385
+ const result = {};
3386
+ let positionalIdx = 0;
3387
+ for (let i = 0; i < argv.length; i++) {
3388
+ const arg = argv[i];
3389
+ if (!arg.startsWith("--")) {
3390
+ if (positionalIdx >= positionalKeys.length) throw new Error(`Unexpected argument: ${arg}`);
3391
+ const key = positionalKeys[positionalIdx];
3392
+ result[key] = arg;
3393
+ positionalIdx++;
3394
+ continue;
3395
+ }
3396
+ const flagName = arg.slice(2);
3397
+ const field = fields.find((f) => f.key === flagName);
3398
+ if (!field) throw new Error(`Unknown option: ${arg}`);
3399
+ if (positionalSet.has(flagName)) throw new Error(`Option --${flagName} is positional; pass it by position instead`);
3400
+ if (field.baseType === "boolean") result[field.key] = true;
3401
+ else {
3402
+ const nextArg = argv[i + 1];
3403
+ if (nextArg === void 0 || nextArg.startsWith("--")) throw new Error(`Missing value for ${arg}`);
3404
+ result[field.key] = nextArg;
3405
+ i++;
3406
+ }
3407
+ }
3408
+ for (const field of fields) {
3409
+ if (field.key in result) continue;
3410
+ if (field.hasDefault) result[field.key] = field.defaultValue;
3411
+ else if (!field.isOptional) {
3412
+ if (positionalSet.has(field.key)) throw new Error(`Missing required argument: <${field.key}>`);
3413
+ throw new Error(`Missing required option: --${field.key}`);
3414
+ }
3415
+ }
3416
+ return result;
3417
+ }
3418
+ function generateHelp() {
3419
+ const desc = resolveValue(options.description, {
3420
+ workdir: activeWorkdir,
3421
+ config: {}
3422
+ });
3423
+ const lines = [];
3424
+ lines.push(`${options.name} v${options.version}`);
3425
+ lines.push("");
3426
+ lines.push(desc);
3427
+ lines.push("");
3428
+ if (options.interactive) {
3429
+ lines.push("Options:");
3430
+ lines.push(" -i, --interactive Start interactive REPL mode");
3431
+ lines.push("");
3432
+ }
3433
+ const allCmds = [...commandMap.values()];
3434
+ const regularCmds = allCmds.filter((c) => !skillIds.has(c.id) && !serviceGroups.has(c.id));
3435
+ const skillCmds = allCmds.filter((c) => skillIds.has(c.id));
3436
+ const svcNameOrder = [];
3437
+ const svcCmdsByName = /* @__PURE__ */ new Map();
3438
+ for (const cmd of allCmds) {
3439
+ const group = serviceGroups.get(cmd.id);
3440
+ if (!group) continue;
3441
+ if (!svcCmdsByName.has(group.name)) {
3442
+ svcNameOrder.push(group.name);
3443
+ svcCmdsByName.set(group.name, {
3444
+ group,
3445
+ cmds: []
3446
+ });
3447
+ }
3448
+ svcCmdsByName.get(group.name).cmds.push(cmd);
3449
+ }
3450
+ lines.push("Commands:");
3451
+ for (const cmd of regularCmds) lines.push(` ${cmd.id.padEnd(36)} ${cmd.description}`);
3452
+ for (const name of svcNameOrder) {
3453
+ const entry = svcCmdsByName.get(name);
3454
+ lines.push("");
3455
+ lines.push(`${entry.group.name}:`);
3456
+ if (entry.group.description) {
3457
+ lines.push(` ${entry.group.description}`);
3458
+ lines.push("");
3459
+ }
3460
+ for (const cmd of entry.cmds) lines.push(` ${cmd.id.padEnd(36)} ${cmd.description}`);
3461
+ }
3462
+ if (skillCmds.length > 0) {
3463
+ lines.push("");
3464
+ lines.push(`Skills (run "${options.name} help <skill>" for details):`);
3465
+ for (const cmd of skillCmds) lines.push(` ${cmd.id.padEnd(36)} ${cmd.description}`);
3466
+ }
3467
+ lines.push("");
3468
+ const configHelp = generateConfigHelp();
3469
+ if (configHelp) lines.push(configHelp);
3470
+ return lines.join("\n");
3471
+ }
3472
+ function generateConfigHelp() {
3473
+ if (!options.configSchema) return void 0;
3474
+ const envVars = configEnvVars();
3475
+ /* istanbul ignore next -- configSchema always has at least one field when present */
3476
+ if (envVars.length === 0) return void 0;
3477
+ const fields = getSchemaFields(options.configSchema, sensitiveKeys);
3478
+ const lines = [];
3479
+ lines.push("Configuration:");
3480
+ for (let i = 0; i < envVars.length; i++) {
3481
+ const ev = envVars[i];
3482
+ const field = fields[i];
3483
+ const parts = [` ${ev.name}`];
3484
+ if (ev.description) parts.push(` ${ev.description}`);
3485
+ if (field?.hasDefault) parts.push(`(default: ${JSON.stringify(field.defaultValue)})`);
3486
+ if (field && !field.isOptional && !field.hasDefault) parts.push("(required)");
3487
+ lines.push(parts.join(" "));
3488
+ }
3489
+ lines.push("");
3490
+ return lines.join("\n");
3491
+ }
3492
+ function generateCommandHelp(commandId) {
3493
+ const cmd = commandMap.get(commandId);
3494
+ if (!cmd) throw new Error(`Unknown command: ${commandId}`);
3495
+ if (commandId === "config" && options.configSchema) return generateConfigCommandHelp(options.name, options.configSchema, activeWorkdir, sensitiveKeys);
3496
+ if (skillIds.has(commandId)) {
3497
+ const skill = resolvedSkills.find((s) => s.name === commandId);
3498
+ const lines = [];
3499
+ lines.push(`Skill: ${commandId}`);
3500
+ lines.push("");
3501
+ lines.push(cmd.description);
3502
+ lines.push("");
3503
+ const fields = getSchemaFields(cmd.inputSchema);
3504
+ const positionalSet = new Set(cmd.positional ?? []);
3505
+ if (fields.length > 0) {
3506
+ lines.push("Parameters:");
3507
+ for (const field of fields) {
3508
+ const parts = [` ${positionalSet.has(field.key) ? field.isOptional || field.hasDefault ? `[${field.key}]` : `<${field.key}>` : `--${field.key}`}`];
3509
+ parts.push(field.description ?? "");
3510
+ if (field.hasDefault) parts.push(`(default: ${JSON.stringify(field.defaultValue)})`);
3511
+ if (!field.isOptional) parts.push("(required)");
3512
+ lines.push(parts.join(" "));
3513
+ }
3514
+ lines.push("");
3515
+ }
3516
+ if (skill?.cliDocsPath) try {
3517
+ const docsContent = fs.readFileSync(skill.cliDocsPath, "utf-8").trim();
3518
+ if (docsContent) {
3519
+ lines.push(docsContent);
3520
+ lines.push("");
3521
+ }
3522
+ } catch {}
3523
+ return lines.join("\n");
3524
+ }
3525
+ const fields = getSchemaFields(cmd.inputSchema);
3526
+ const positionalKeys = cmd.positional ?? [];
3527
+ const positionalSet = new Set(positionalKeys);
3528
+ const lines = [];
3529
+ const usageParts = [`${options.name}`, cmd.id];
3530
+ for (const key of positionalKeys) {
3531
+ const field = fields.find((f) => f.key === key);
3532
+ if (!field) continue;
3533
+ const isOptional = field.isOptional || field.hasDefault;
3534
+ usageParts.push(isOptional ? `[${key}]` : `<${key}>`);
3535
+ }
3536
+ const flagFields = fields.filter((f) => !positionalSet.has(f.key));
3537
+ if (flagFields.length > 0) usageParts.push("[options]");
3538
+ lines.push(`Usage: ${usageParts.join(" ")}`);
3539
+ lines.push("");
3540
+ lines.push(cmd.description);
3541
+ lines.push("");
3542
+ if (positionalKeys.length > 0) {
3543
+ lines.push("Arguments:");
3544
+ for (const key of positionalKeys) {
3545
+ const field = fields.find((f) => f.key === key);
3546
+ if (!field) continue;
3547
+ const parts = [` ${field.isOptional || field.hasDefault ? `[${field.key}]` : `<${field.key}>`}`];
3548
+ parts.push(field.description ?? "");
3549
+ if (field.hasDefault) parts.push(`(default: ${JSON.stringify(field.defaultValue)})`);
3550
+ lines.push(parts.join(" "));
3551
+ }
3552
+ lines.push("");
3553
+ }
3554
+ if (flagFields.length > 0) {
3555
+ lines.push("Options:");
3556
+ for (const field of flagFields) {
3557
+ const parts = [` --${field.key}`];
3558
+ parts.push(field.description ?? "");
3559
+ if (field.hasDefault) parts.push(`(default: ${JSON.stringify(field.defaultValue)})`);
3560
+ if (!field.isOptional) parts.push("(required)");
3561
+ lines.push(parts.join(" "));
3562
+ }
3563
+ }
3564
+ lines.push("");
3565
+ return lines.join("\n");
3566
+ }
3567
+ function generateCompletion(shell) {
3568
+ const commandNames = [...commandMap.keys()].join(" ");
3569
+ if (shell === "bash") return [
3570
+ `# bash completion for ${options.name}`,
3571
+ `_${options.name}_completions() {`,
3572
+ ` local commands="${commandNames}"`,
3573
+ ` COMPREPLY=($(compgen -W "$commands" -- "\${COMP_WORDS[COMP_CWORD]}")`,
3574
+ `}`,
3575
+ `complete -F _${options.name}_completions ${options.name}`
3576
+ ].join("\n");
3577
+ if (shell === "zsh") return [
3578
+ `#compdef ${options.name}`,
3579
+ `_${options.name}() {`,
3580
+ ` local commands=(${commandNames})`,
3581
+ ` _describe 'command' commands`,
3582
+ `}`,
3583
+ `compdef _${options.name} ${options.name}`
3584
+ ].join("\n");
3585
+ if (shell === "fish") {
3586
+ const lines = [`# fish completion for ${options.name}`];
3587
+ for (const name of commandMap.keys()) lines.push(`complete -c ${options.name} -n '__fish_use_subcommand' -a '${name}'`);
3588
+ return lines.join("\n");
3589
+ }
3590
+ throw new Error(`Unsupported shell: ${shell}`);
3591
+ }
3592
+ function configEnvVars() {
3593
+ if (!options.configSchema) return [];
3594
+ return getConfigEnvVars(options.name, options.configSchema);
3595
+ }
3596
+ function buildProgram(stdout, context, resolvedDescription, onSkillInvocation, wraps) {
3597
+ const program = new Command();
3598
+ program.name(options.name).version(options.version).description(resolvedDescription).enablePositionalOptions().exitOverride().configureOutput({
3599
+ writeOut: (str) => stdout(str.trimEnd()),
3600
+ writeErr: (str) => stdout(str.trimEnd())
3601
+ });
3602
+ if (options.interactive) program.option("-i, --interactive", "Start interactive REPL mode");
3603
+ 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
+ program.option("--verbose", "Enable debug-level logging");
3607
+ program.option("--meta", "Output CLI metadata as JSON");
3608
+ if (agentLoader) program.option("--resume <thread-id>", "Resume a previous conversation");
3609
+ if (!options.workdir) program.option("-w, --workdir <path>", "Set the workspace directory");
3610
+ if (configFieldCount > 0) program.option("-c, --config <path>", "Load config from a JSON file (relative to cwd)");
3611
+ const configShorthands = {
3612
+ name: "-n",
3613
+ write: "-w",
3614
+ remove: "-r",
3615
+ list: "-l",
3616
+ scope: "-s"
3617
+ };
3618
+ for (const cmd of commandMap.values()) {
3619
+ if (cmd.id === "cli-docs") continue;
3620
+ const isSkill = skillIds.has(cmd.id);
3621
+ const isHidden = isSkill || serviceGroups.has(cmd.id);
3622
+ const sub = program.command(cmd.id, { hidden: isHidden }).description(cmd.description);
3623
+ const isBuiltinConfig = cmd.id === "config" && options.configSchema;
3624
+ const fields = getSchemaFields(cmd.inputSchema);
3625
+ const positionalKeys = cmd.positional ?? [];
3626
+ const positionalSet = new Set(positionalKeys);
3627
+ for (const key of positionalKeys) {
3628
+ const field = fields.find((f) => f.key === key);
3629
+ if (!field) continue;
3630
+ const spec = field.isOptional || field.hasDefault ? `[${field.key}]` : `<${field.key}>`;
3631
+ sub.argument(spec, field.description ?? "");
3632
+ }
3633
+ for (const field of fields) {
3634
+ if (positionalSet.has(field.key)) continue;
3635
+ const desc = field.description ?? "";
3636
+ const shorthand = isBuiltinConfig ? configShorthands[field.key] : void 0;
3637
+ const longFlag = `--${field.key}`;
3638
+ const flag = shorthand ? `${shorthand}, ${longFlag}` : longFlag;
3639
+ if (field.baseType === "boolean") sub.option(flag, desc, field.hasDefault ? field.defaultValue : false);
3640
+ else if (field.isOptional) sub.option(`${flag} <value>`, desc, field.hasDefault ? String(field.defaultValue) : void 0);
3641
+ else sub.requiredOption(`${flag} <value>`, desc);
3642
+ }
3643
+ if (isBuiltinConfig) sub.helpInformation = () => generateConfigCommandHelp(options.name, options.configSchema, activeWorkdir, sensitiveKeys) + "\n";
3644
+ if (isSkill) sub.helpInformation = () => generateCommandHelp(cmd.id) + "\n";
3645
+ sub.action(async (...actionArgs) => {
3646
+ const trailing = actionArgs.slice(0, -1);
3647
+ const merged = { ...trailing[positionalKeys.length] ?? {} };
3648
+ for (let i = 0; i < positionalKeys.length; i++) {
3649
+ const key = positionalKeys[i];
3650
+ const value = trailing[i];
3651
+ if (value !== void 0) merged[key] = value;
3652
+ }
3653
+ let parsed;
3654
+ try {
3655
+ parsed = cmd.inputSchema.parse(merged);
3656
+ } catch (err) {
3657
+ throw new Error(formatZodError(err, cmd.id));
3658
+ }
3659
+ const result = wraps ? await wraps.command(cmd.id, () => cmd.execute(parsed, context)) : await cmd.execute(parsed, context);
3660
+ if (isSkillInvocation(result)) {
3661
+ if (onSkillInvocation) await onSkillInvocation(result);
3662
+ else stdout(`Skill: ${result.skillName}` + (result.userMessage ? ` — ${result.userMessage}` : ""));
3663
+ return;
3664
+ }
3665
+ const output = formatResult(result);
3666
+ if (output !== void 0) stdout(output);
3667
+ });
3668
+ }
3669
+ const groupedLines = [];
3670
+ const allCmds = [...commandMap.values()];
3671
+ const svcNameOrder = [];
3672
+ const svcCmdsByName = /* @__PURE__ */ new Map();
3673
+ for (const cmd of allCmds) {
3674
+ const group = serviceGroups.get(cmd.id);
3675
+ if (!group) continue;
3676
+ if (!svcCmdsByName.has(group.name)) {
3677
+ svcNameOrder.push(group.name);
3678
+ svcCmdsByName.set(group.name, {
3679
+ group,
3680
+ cmds: []
3681
+ });
3682
+ }
3683
+ svcCmdsByName.get(group.name).cmds.push(cmd);
3684
+ }
3685
+ for (const name of svcNameOrder) {
3686
+ const entry = svcCmdsByName.get(name);
3687
+ groupedLines.push("");
3688
+ groupedLines.push(`${entry.group.name}:`);
3689
+ if (entry.group.description) {
3690
+ groupedLines.push(` ${entry.group.description}`);
3691
+ groupedLines.push("");
3692
+ }
3693
+ for (const cmd of entry.cmds) groupedLines.push(` ${cmd.id.padEnd(36)} ${cmd.description}`);
3694
+ }
3695
+ const skillCmds = allCmds.filter((c) => skillIds.has(c.id));
3696
+ if (skillCmds.length > 0) {
3697
+ groupedLines.push("");
3698
+ groupedLines.push(`Skills (run "${options.name} help <skill>" for details):`);
3699
+ for (const cmd of skillCmds) groupedLines.push(` ${cmd.id.padEnd(36)} ${cmd.description}`);
3700
+ }
3701
+ if (groupedLines.length > 0) program.addHelpText("after", groupedLines.join("\n"));
3702
+ const configHelp = generateConfigHelp();
3703
+ if (configHelp) program.addHelpText("after", "\n" + configHelp);
3704
+ return program;
3705
+ }
3706
+ /**
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().
3710
+ */
3711
+ function wireServices(context, config, log, proxyInstance) {
3712
+ const servicesNow = options.services && options.services.length > 0;
3713
+ let processServiceManager;
3714
+ if (servicesNow && options.services) {
3715
+ const svcDir = userStoreFolder(options.name, "services");
3716
+ processServiceManager = createServiceManager(options.services, {
3717
+ config,
3718
+ servicesDir: svcDir,
3719
+ eventBus: getEventBus()
3720
+ });
3721
+ }
3722
+ if (processServiceManager && routineServiceAdapter) {
3723
+ const routeMap = /* @__PURE__ */ new Map();
3724
+ for (const svc of options.services) routeMap.set(svc.id, processServiceManager);
3725
+ routeMap.set(options.routine.id, routineServiceAdapter);
3726
+ context.services = createCompositeServiceManager([processServiceManager, routineServiceAdapter], routeMap);
3727
+ } else if (processServiceManager) context.services = processServiceManager;
3728
+ 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);
3755
+ }
3756
+ }
3757
+ }
3758
+ /**
3759
+ * Initialize the CLI runtime without entering the dispatch loop.
3760
+ * Returns resolved workdir, config, context, and lazy agent accessor.
3761
+ */
3762
+ async function bootstrap(opts) {
3763
+ const bootTimings = {
3764
+ bootStartedAt: Date.now(),
3765
+ configResolvedAt: 0,
3766
+ lifecycleInitStartedAt: 0
3767
+ };
3768
+ const stdoutFn = opts?.stdout ?? ((msg) => {
3769
+ console.log(msg);
3770
+ });
3771
+ const stderrFn = opts?.stderr ?? ((msg) => {
3772
+ console.error(msg);
3773
+ });
3774
+ const cwd = process.cwd();
3775
+ const workdir = opts?.workdir ? resolveWorkdir({ implementationOverride: opts.workdir }) : resolveWorkdir({
3776
+ implementationOverride: options.workdir,
3777
+ fallback: cwd
3778
+ });
3779
+ activeWorkdir = workdir;
3780
+ const workspace = createWorkdirStore(workdir, options.name);
3781
+ if (options.prompts && options.prompts.artifacts.length > 0) {
3782
+ const storeRoot = workspace.getStoreFolder();
3783
+ if (!fs.existsSync(storeRoot)) {
3784
+ fs.mkdirSync(storeRoot, { recursive: true });
3785
+ const dbFolder = workspace.getStoreFolder(".mastra/db");
3786
+ fs.mkdirSync(dbFolder, { recursive: true });
3787
+ installSkills({
3788
+ store: workspace,
3789
+ skillArtifacts: options.prompts.artifacts,
3790
+ stdout: () => {}
3791
+ });
3792
+ }
3793
+ }
3794
+ const config = options.configSchema ? resolveConfig({
3795
+ configSchema: options.configSchema,
3796
+ cliName: options.name,
3797
+ workdir,
3798
+ configFile: opts?.configFile,
3799
+ cwd,
3800
+ implementationDefaults: options.configDefaults
3801
+ }) : {};
3802
+ bootTimings.configResolvedAt = Date.now();
3803
+ const log = createLogger(opts?.logLevel ?? "info", stderrFn);
3804
+ const context = buildContext({
3805
+ workdir,
3806
+ workspace,
3807
+ config,
3808
+ stdout: stdoutFn,
3809
+ log
3810
+ });
3811
+ wireServices(context, config, log);
3812
+ bootTimings.lifecycleInitStartedAt = Date.now();
3813
+ const lifecycleCtx = {
3814
+ config,
3815
+ cliName: options.name,
3816
+ cliVersion: options.version,
3817
+ log,
3818
+ eventBus: getEventBus(),
3819
+ userStoreFolder: userStoreFolder(options.name),
3820
+ isInteractive: process.stdin.isTTY === true,
3821
+ bootTimings
3822
+ };
3823
+ const lifecycle = await initLifecycle(options.lifecycle ?? [], lifecycleCtx);
3824
+ const runtime = createCliRuntime({
3825
+ cliName: options.name,
3826
+ cliVersion: options.version,
3827
+ workdir,
3828
+ workspace,
3829
+ config,
3830
+ context,
3831
+ log,
3832
+ commandMap,
3833
+ agentLoader,
3834
+ skillIds,
3835
+ resolvedSkills,
3836
+ prompts: options.prompts,
3837
+ wraps: lifecycle.wraps,
3838
+ lifecycleShutdown: lifecycle.shutdown
3839
+ });
3840
+ context.agent = runtime.getAgent;
3841
+ return {
3842
+ workdir,
3843
+ config,
3844
+ context,
3845
+ getAgent: runtime.getAgent,
3846
+ get mastraAgent() {
3847
+ return runtime.getAgent().then((p) => p?.mastraAgent);
3848
+ }
3849
+ };
3850
+ }
3851
+ /**
3852
+ * Public entry point — fills in process defaults, then delegates to runImpl.
3853
+ */
3854
+ async function run(argv, runOptions) {
3855
+ return runImpl(argv, {
3856
+ exit: runOptions?.exit ?? ((code) => process.exit(code)),
3857
+ stdout: runOptions?.stdout ?? ((msg) => {
3858
+ console.log(msg);
3859
+ }),
3860
+ stderr: runOptions?.stderr ?? ((msg) => {
3861
+ console.error(msg);
3862
+ }),
3863
+ cwd: runOptions?.workdir ?? process.cwd(),
3864
+ writeRaw: runOptions?.stdout ?? defaultStdout,
3865
+ configFile: runOptions?.configFile,
3866
+ resume: runOptions?.resume,
3867
+ interactiveInput: runOptions?.interactiveInput,
3868
+ logLevel: runOptions?.logLevel
3869
+ });
3870
+ }
3871
+ /**
3872
+ * Internal run with fully-resolved options — no process globals, fully testable.
3873
+ */
3874
+ async function runImpl(argv, opts) {
3875
+ const bootTimings = {
3876
+ bootStartedAt: Date.now(),
3877
+ configResolvedAt: 0,
3878
+ lifecycleInitStartedAt: 0
3879
+ };
3880
+ const { exit, stdout, stderr, cwd, writeRaw } = opts;
3881
+ const userArgs = argv.slice(2);
3882
+ const subcommandNames = /* @__PURE__ */ new Set([...commandMap.keys(), "help"]);
3883
+ let subcommandIdx = userArgs.findIndex((a) => subcommandNames.has(a));
3884
+ if (subcommandIdx === -1) subcommandIdx = userArgs.length;
3885
+ const preCommandArgs = userArgs.slice(0, subcommandIdx);
3886
+ let workdirFlag;
3887
+ let configFileFlag = opts.configFile;
3888
+ let resumeId = opts.resume;
3889
+ let interactiveFlag = false;
3890
+ let verboseFlag = false;
3891
+ let metaFlag = false;
3892
+ let noRoutineFlag = false;
3893
+ let noApiFlag = false;
3894
+ let noStudioFlag = false;
3895
+ const frameworkFlags = /* @__PURE__ */ new Set([
3896
+ "--resume",
3897
+ "--workdir",
3898
+ "-w",
3899
+ "--config",
3900
+ "-c"
3901
+ ]);
3902
+ for (let i = 0; i < preCommandArgs.length; i++) {
3903
+ const arg = preCommandArgs[i];
3904
+ if (arg === "-i" || arg === "--interactive") interactiveFlag = true;
3905
+ else if (arg === "--verbose") verboseFlag = true;
3906
+ else if (arg === "--meta") metaFlag = true;
3907
+ 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
+ else if (frameworkFlags.has(arg) && i + 1 < preCommandArgs.length) {
3911
+ const value = preCommandArgs[i + 1];
3912
+ if (arg === "--workdir" || arg === "-w") workdirFlag = value;
3913
+ else if (arg === "--config" || arg === "-c") configFileFlag = value;
3914
+ else if (arg === "--resume") resumeId = value;
3915
+ i++;
3916
+ }
3917
+ }
3918
+ const workdir = resolveWorkdir({
3919
+ implementationOverride: options.workdir,
3920
+ cliFlag: workdirFlag,
3921
+ fallback: cwd
3922
+ });
3923
+ activeWorkdir = workdir;
3924
+ activeConfigFile = configFileFlag;
3925
+ const workspace = createWorkdirStore(workdir, options.name);
3926
+ if (options.prompts && options.prompts.artifacts.length > 0) {
3927
+ const storeRoot = workspace.getStoreFolder();
3928
+ if (!fs.existsSync(storeRoot)) {
3929
+ fs.mkdirSync(storeRoot, { recursive: true });
3930
+ const dbFolder = workspace.getStoreFolder(".mastra/db");
3931
+ fs.mkdirSync(dbFolder, { recursive: true });
3932
+ installSkills({
3933
+ store: workspace,
3934
+ skillArtifacts: options.prompts.artifacts,
3935
+ stdout: verboseFlag ? stderr : () => {}
3936
+ });
3937
+ }
3938
+ }
3939
+ const config = options.configSchema ? resolveConfig({
3940
+ configSchema: options.configSchema,
3941
+ cliName: options.name,
3942
+ workdir,
3943
+ configFile: configFileFlag,
3944
+ cwd,
3945
+ implementationDefaults: options.configDefaults
3946
+ }) : {};
3947
+ bootTimings.configResolvedAt = Date.now();
3948
+ const log = createLogger(opts.logLevel ?? (verboseFlag ? "debug" : "info"), stderr);
3949
+ const context = buildContext({
3950
+ workdir,
3951
+ workspace,
3952
+ config,
3953
+ stdout: writeRaw,
3954
+ log
3955
+ });
3956
+ const firstSubcmd = userArgs.slice(subcommandIdx)[0];
3957
+ const isSubcommand = firstSubcmd && (commandMap.has(firstSubcmd) || firstSubcmd === "help");
3958
+ 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);
3997
+ bootTimings.lifecycleInitStartedAt = Date.now();
3998
+ const lifecycleCtx = {
3999
+ config,
4000
+ cliName: options.name,
4001
+ cliVersion: options.version,
4002
+ log,
4003
+ eventBus: getEventBus(),
4004
+ userStoreFolder: userStoreFolder(options.name),
4005
+ isInteractive: process.stdin.isTTY === true,
4006
+ bootTimings
4007
+ };
4008
+ const lifecycle = await initLifecycle(options.lifecycle ?? [], lifecycleCtx);
4009
+ const typedConfig = config;
4010
+ const resolvableCtx = {
4011
+ workdir,
4012
+ config: typedConfig
4013
+ };
4014
+ const resolvedDescription = resolveValue(options.description, resolvableCtx);
4015
+ const resolvedWelcome = options.interactive ? resolveValue(options.interactive.welcome, resolvableCtx) : void 0;
4016
+ const runtime = createCliRuntime({
4017
+ cliName: options.name,
4018
+ cliVersion: options.version,
4019
+ workdir,
4020
+ workspace,
4021
+ config,
4022
+ context,
4023
+ log,
4024
+ commandMap,
4025
+ reactorConfig,
4026
+ agentLoader,
4027
+ routine,
4028
+ skipRoutineStart: noRoutineFlag,
4029
+ proxyInstance,
4030
+ enableSwitchboard: !noApiFlag,
4031
+ enableConnect: !noStudioFlag,
4032
+ attachmentJwtHandler: options.attachmentJwtHandler?.({
4033
+ workdir,
4034
+ config: typedConfig
4035
+ }),
4036
+ skillIds,
4037
+ resolvedSkills,
4038
+ prompts: options.prompts,
4039
+ wraps: lifecycle.wraps,
4040
+ lifecycleShutdown: lifecycle.shutdown
4041
+ });
4042
+ if (reactorConfig) context.reactor = runtime.getReactor;
4043
+ context.agent = runtime.getAgent;
4044
+ if (metaFlag) {
4045
+ stdout(JSON.stringify(getMetadata(), null, 2));
4046
+ exit(0);
4047
+ return;
4048
+ }
4049
+ const promptArgs = [];
4050
+ {
4051
+ let skipNext = false;
4052
+ for (const arg of preCommandArgs) {
4053
+ if (skipNext) {
4054
+ skipNext = false;
4055
+ continue;
4056
+ }
4057
+ if (frameworkFlags.has(arg)) {
4058
+ skipNext = true;
4059
+ continue;
4060
+ }
4061
+ if (arg.startsWith("-")) continue;
4062
+ promptArgs.push(arg);
4063
+ }
4064
+ }
4065
+ const hasPrompt = !isSubcommand && agentLoader && promptArgs.length > 0;
4066
+ /**
4067
+ * Render an agent prompt from a SkillInvocation using its template.
4068
+ */
4069
+ function renderSkillPrompt(invocation) {
4070
+ const template = invocation.instructionTemplate ?? "Use your {{skillId}} skill for the following instructions: {{prompt}}";
4071
+ const skill = resolvedSkills.find((s) => s.name === invocation.skillName);
4072
+ return renderSkillTemplate(template, {
4073
+ skillId: invocation.skillName,
4074
+ description: skill?.description ?? "",
4075
+ prompt: invocation.userMessage ?? "",
4076
+ ...invocation.inputValues ?? {}
4077
+ }).rendered.trim();
4078
+ }
4079
+ async function handleSkillInvocation(invocation) {
4080
+ const agentProvider = await runtime.getAgent();
4081
+ if (!agentProvider) {
4082
+ stderr("Agent not available — cannot invoke skill");
4083
+ exit(1);
4084
+ return;
4085
+ }
4086
+ const prompt = renderSkillPrompt(invocation);
4087
+ const threadId = resumeId ?? randomUUID();
4088
+ for await (const chunk of agentProvider.stream(prompt, {
4089
+ threadId,
4090
+ tools: commandMap
4091
+ })) writeRaw(formatStreamChunk(chunk));
4092
+ stdout("");
4093
+ stdout(`\x1b[2mThread: ${threadId} (continue with: ${options.name} --resume ${threadId} "your message")\x1b[0m`);
4094
+ }
4095
+ const effectiveRoutine = noRoutineFlag ? void 0 : routine;
4096
+ const effectiveApi = !noApiFlag && reactorConfig?.switchboard?.enabled;
4097
+ const isTTY = interactiveFlag && !opts.interactiveInput && process.stdin.isTTY;
4098
+ const mode = !interactiveFlag ? "headless" : isTTY ? "interactive-terminal" : "interactive-streaming";
4099
+ const hasKeepAlive = !!effectiveRoutine || !!effectiveApi || !!proxyInstance;
4100
+ if (isBuiltinFlag || !interactiveFlag && (isSubcommand || hasPrompt)) {
4101
+ if (hasPrompt) {
4102
+ const agentProvider = await runtime.getAgent();
4103
+ if (agentProvider) {
4104
+ const prompt = promptArgs.join(" ");
4105
+ const threadId = resumeId ?? randomUUID();
4106
+ for await (const chunk of agentProvider.stream(prompt, {
4107
+ threadId,
4108
+ tools: commandMap
4109
+ })) writeRaw(formatStreamChunk(chunk));
4110
+ stdout("");
4111
+ stdout(`\x1b[2mThread: ${threadId} (continue with: ${options.name} --resume ${threadId} "your message")\x1b[0m`);
4112
+ await runtime.teardown();
4113
+ return;
4114
+ }
4115
+ }
4116
+ const program = buildProgram(stdout, context, resolvedDescription, agentLoader ? handleSkillInvocation : void 0, lifecycle.wraps);
4117
+ try {
4118
+ await program.parseAsync(argv);
4119
+ } catch (err) {
4120
+ if (err.exitCode === 0) {
4121
+ exit(0);
4122
+ return;
4123
+ }
4124
+ const msg = err instanceof Error ? err.message : String(err);
4125
+ if (msg !== "(outputHelp)" && msg !== "(version)") stderr(msg);
4126
+ exit(err.exitCode ?? 1);
4127
+ return;
4128
+ }
4129
+ await runtime.teardown();
4130
+ } else if (interactiveFlag || hasKeepAlive) {
4131
+ let session;
4132
+ if (interactiveFlag) {
4133
+ if (!options.interactive) {
4134
+ stderr("Interactive mode is not configured for this CLI");
4135
+ exit(1);
4136
+ return;
4137
+ }
4138
+ const resolvedInteractive = {
4139
+ welcome: resolvedWelcome,
4140
+ outputWindow: options.interactive?.outputWindow ?? 6
4141
+ };
4142
+ session = createReplSession({
4143
+ cli: {
4144
+ name: options.name,
4145
+ version: options.version,
4146
+ description: resolvedDescription,
4147
+ configSchema: options.configSchema,
4148
+ interactive: resolvedInteractive,
4149
+ get hasAgent() {
4150
+ return !!agentLoader;
4151
+ },
4152
+ get hasReactor() {
4153
+ return !!reactorConfig;
4154
+ },
4155
+ configureAgent,
4156
+ configureReactor,
4157
+ getCommand,
4158
+ listCommands,
4159
+ execute,
4160
+ parseArgs,
4161
+ generateHelp,
4162
+ generateCommandHelp,
4163
+ generateCompletion,
4164
+ configEnvVars,
4165
+ getMetadata,
4166
+ bootstrap,
4167
+ run,
4168
+ stopRoutine
4169
+ },
4170
+ context,
4171
+ agentProvider: await runtime.getAgent(),
4172
+ threadId: resumeId
4173
+ });
4174
+ }
4175
+ if (session?.welcome && mode !== "interactive-terminal") stdout(session.welcome);
4176
+ switch (mode) {
4177
+ case "interactive-terminal": {
4178
+ /* istanbul ignore next -- Ink REPL requires a real terminal */
4179
+ const { startInkRepl } = await import("./start-b7Mn2cxB.mjs");
4180
+ /* istanbul ignore next */
4181
+ await startInkRepl(session, {
4182
+ services: context.services,
4183
+ workdir: context.workdir,
4184
+ onStart: async (append) => {
4185
+ await runtime.startupSequence(append);
4186
+ }
4187
+ });
4188
+ /* istanbul ignore next */
4189
+ await runtime.teardown();
4190
+ /* istanbul ignore next */
4191
+ exit(0);
4192
+ break;
4193
+ }
4194
+ case "interactive-streaming": {
4195
+ try {
4196
+ await runtime.startupSequence(stdout);
4197
+ } catch (err) {
4198
+ const msg = err instanceof Error ? err.message : String(err);
4199
+ log.error(msg);
4200
+ exit(1);
4201
+ return;
4202
+ }
4203
+ const { createStdinLineReader } = await import("./stdin-BjAO9gPK.mjs");
4204
+ const source = opts.interactiveInput ?? createStdinLineReader();
4205
+ let exitedViaCommand = false;
4206
+ for await (const line of source) {
4207
+ const result = await session.processInput(line);
4208
+ if (result.type === "exit") {
4209
+ if (result.text) stdout(result.text);
4210
+ exitedViaCommand = true;
4211
+ break;
4212
+ }
4213
+ if (result.text) stdout(result.text);
4214
+ }
4215
+ if (!exitedViaCommand) stdout(session.exitMessage);
4216
+ if (hasKeepAlive) {
4217
+ stdout("Stdin closed — still serving. Press Ctrl+C to stop.");
4218
+ await new Promise((resolve) => {
4219
+ const onSignal = async () => {
4220
+ const suppress = () => {};
4221
+ process.removeListener("SIGINT", onSignal);
4222
+ process.removeListener("SIGTERM", onSignal);
4223
+ process.on("SIGINT", suppress);
4224
+ process.on("SIGTERM", suppress);
4225
+ await runtime.teardown();
4226
+ process.removeListener("SIGINT", suppress);
4227
+ process.removeListener("SIGTERM", suppress);
4228
+ resolve();
4229
+ };
4230
+ process.on("SIGINT", onSignal);
4231
+ process.on("SIGTERM", onSignal);
4232
+ });
4233
+ return;
4234
+ }
4235
+ await runtime.teardown();
4236
+ exit(0);
4237
+ break;
4238
+ }
4239
+ case "headless":
4240
+ try {
4241
+ await runtime.startupSequence(stdout);
4242
+ } catch (err) {
4243
+ stderr(err instanceof Error ? err.message : String(err));
4244
+ exit(1);
4245
+ return;
4246
+ }
4247
+ stdout("Serving — press Ctrl+C to stop.");
4248
+ await new Promise((resolve) => {
4249
+ const onSignal = async () => {
4250
+ const suppress = () => {};
4251
+ process.removeListener("SIGINT", onSignal);
4252
+ process.removeListener("SIGTERM", onSignal);
4253
+ process.on("SIGINT", suppress);
4254
+ process.on("SIGTERM", suppress);
4255
+ runtime.reportActiveServices(stdout);
4256
+ await runtime.teardown();
4257
+ process.removeListener("SIGINT", suppress);
4258
+ process.removeListener("SIGTERM", suppress);
4259
+ resolve();
4260
+ };
4261
+ process.on("SIGINT", onSignal);
4262
+ process.on("SIGTERM", onSignal);
4263
+ });
4264
+ return;
4265
+ }
4266
+ } else {
4267
+ buildProgram(stdout, context, resolvedDescription, agentLoader ? handleSkillInvocation : void 0, lifecycle.wraps).outputHelp();
4268
+ await runtime.teardown();
4269
+ }
4270
+ }
4271
+ async function stopRoutine() {
4272
+ if (routine) await routine.stop();
4273
+ }
4274
+ function fieldsToMap(fields) {
4275
+ const map = {};
4276
+ for (const f of fields) {
4277
+ const entry = {
4278
+ id: f.key,
4279
+ description: f.description,
4280
+ optional: f.isOptional,
4281
+ type: f.baseType,
4282
+ sensitive: f.sensitive
4283
+ };
4284
+ if (f.hasDefault) entry.default = f.defaultValue;
4285
+ map[f.key] = entry;
4286
+ }
4287
+ return map;
4288
+ }
4289
+ function getMetadata() {
4290
+ const desc = resolveValue(options.description, {
4291
+ workdir: activeWorkdir,
4292
+ config: {}
4293
+ });
4294
+ let configMeta = null;
4295
+ if (options.configSchema) {
4296
+ const fields = getSchemaFields(options.configSchema, sensitiveKeys);
4297
+ const envVarsByField = /* @__PURE__ */ new Map();
4298
+ for (const ev of configEnvVars()) envVarsByField.set(ev.field, ev.name);
4299
+ configMeta = {};
4300
+ for (const f of fields) {
4301
+ const entry = {
4302
+ id: f.key,
4303
+ description: f.description,
4304
+ optional: f.isOptional,
4305
+ type: f.baseType,
4306
+ sensitive: f.sensitive,
4307
+ env: envVarsByField.get(f.key) ?? ""
4308
+ };
4309
+ if (f.hasDefault) entry.default = f.defaultValue;
4310
+ configMeta[f.key] = entry;
4311
+ }
4312
+ }
4313
+ const commandsMeta = {};
4314
+ for (const cmd of commandMap.values()) {
4315
+ if (skillIds.has(cmd.id)) continue;
4316
+ commandsMeta[cmd.id] = {
4317
+ id: cmd.id,
4318
+ description: cmd.description,
4319
+ params: fieldsToMap(getSchemaFields(cmd.inputSchema))
4320
+ };
4321
+ }
4322
+ let servicesMeta = null;
4323
+ if (options.services && options.services.length > 0) {
4324
+ servicesMeta = {};
4325
+ for (const svc of options.services) {
4326
+ const mcpCaptures = [];
4327
+ if (svc.readiness) {
4328
+ if (svc.readiness.patterns) {
4329
+ for (const pat of svc.readiness.patterns) if (pat.captures) {
4330
+ for (const [capName, def] of Object.entries(pat.captures)) if (typeof def === "object" && def.type === "api-mcp") mcpCaptures.push(capName);
4331
+ }
4332
+ } else if (svc.readiness.captures) {
4333
+ for (const [capName, def] of Object.entries(svc.readiness.captures)) if (typeof def === "object" && def.type === "api-mcp") mcpCaptures.push(capName);
4334
+ }
4335
+ }
4336
+ let mcpPrefix;
4337
+ if (mcpCaptures.length === 1) mcpPrefix = `${svc.id}-mcp__`;
4338
+ else if (mcpCaptures.length > 1) {
4339
+ mcpPrefix = {};
4340
+ for (const capName of mcpCaptures) mcpPrefix[capName] = `${svc.id}-${capName}-mcp__`;
4341
+ }
4342
+ servicesMeta[svc.id] = {
4343
+ id: svc.id,
4344
+ name: resolveServiceName(svc),
4345
+ ...svc.description && { description: svc.description },
4346
+ ...svc.maxInstances !== void 0 && { maxInstances: svc.maxInstances },
4347
+ params: svc.paramsSchema ? fieldsToMap(getSchemaFields(svc.paramsSchema)) : {},
4348
+ ...svc.shutdown && { shutdown: {
4349
+ signal: String(svc.shutdown.signal),
4350
+ timeout: svc.shutdown.timeout
4351
+ } },
4352
+ ...svc.restart && { restart: {
4353
+ enabled: svc.restart.enabled,
4354
+ maxRetries: svc.restart.maxRetries,
4355
+ delay: svc.restart.delay
4356
+ } },
4357
+ ...svc.readiness?.timeout !== void 0 && { readinessTimeout: svc.readiness.timeout },
4358
+ ...mcpPrefix !== void 0 && { mcpPrefix }
4359
+ };
4360
+ }
4361
+ }
4362
+ let promptsMeta = null;
4363
+ if (options.prompts) {
4364
+ const resolvedMap = {};
4365
+ for (const s of resolvedSkills) resolvedMap[s.name] = {
4366
+ id: s.name,
4367
+ description: s.description
4368
+ };
4369
+ promptsMeta = {
4370
+ artifacts: options.prompts.artifacts,
4371
+ agents: options.prompts.agents ?? {},
4372
+ skills: options.prompts.skills ?? {},
4373
+ resolved: resolvedMap
4374
+ };
4375
+ }
4376
+ return {
4377
+ name: options.name,
4378
+ version: options.version,
4379
+ description: desc,
4380
+ hasInteractive: !!options.interactive,
4381
+ hasAgent: !!agentLoader,
4382
+ hasReactor: !!reactorConfig,
4383
+ config: configMeta,
4384
+ commands: commandsMeta,
4385
+ services: servicesMeta,
4386
+ prompts: promptsMeta
4387
+ };
4388
+ }
4389
+ const staticDescription = typeof options.description === "string" ? options.description : options.description({
4390
+ workdir: activeWorkdir,
4391
+ config: {}
4392
+ });
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
+ cliRef = {
4415
+ name: options.name,
4416
+ version: options.version,
4417
+ description: staticDescription,
4418
+ configSchema: options.configSchema,
4419
+ interactive: options.interactive,
4420
+ get hasAgent() {
4421
+ return !!agentLoader;
4422
+ },
4423
+ get hasReactor() {
4424
+ return !!reactorConfig;
4425
+ },
4426
+ configureAgent,
4427
+ configureReactor,
4428
+ getCommand,
4429
+ listCommands,
4430
+ execute,
4431
+ parseArgs,
4432
+ generateHelp,
4433
+ generateCommandHelp,
4434
+ generateCompletion,
4435
+ configEnvVars,
4436
+ getMetadata,
4437
+ bootstrap,
4438
+ run,
4439
+ stopRoutine
4440
+ };
4441
+ return cliRef;
4442
+ }
4443
+ //#endregion
4444
+ //#region src/core/trigger.ts
4445
+ /**
4446
+ * Define a trigger — a pluggable object that produces work items for the routine loop.
4447
+ *
4448
+ * Generics:
4449
+ * - `TState` — shape of `ctx.state`. Combine with `state: () => TState` to initialize.
4450
+ * - `TConfig` — shape of `ctx.context.config`. Use the binding from `createTypes()` to avoid repeating.
4451
+ * - `R` — DocumentRegistry, narrows `ctx.reactor()` and event payloads.
4452
+ */
4453
+ function defineTrigger(options) {
4454
+ return options;
4455
+ }
4456
+ //#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
+ //#region src/core/types-binding.ts
4539
+ /**
4540
+ * Bind a CLI's config schema and optional registry once; reuse the returned
4541
+ * typed factories across every command/trigger/service in the impl.
4542
+ *
4543
+ * ```ts
4544
+ * // impl/src/framework.ts
4545
+ * import { z } from 'zod';
4546
+ * import { createTypes, defineRegistry } from '@powerhousedao/ph-clint';
4547
+ * import { PhClintProject } from '@powerhousedao/ph-clint-app/document-models/ph-clint-project';
4548
+ *
4549
+ * const configSchema = z.object({ projectDocumentId: z.string().optional() });
4550
+ * const registry = defineRegistry([PhClintProject] as const);
4551
+ *
4552
+ * export const {
4553
+ * defineCommand,
4554
+ * defineTrigger,
4555
+ * defineService,
4556
+ * createDocumentChangeTrigger,
4557
+ * } = createTypes({ configSchema, registry });
4558
+ * ```
4559
+ */
4560
+ function createTypes(_opts) {
4561
+ return {
4562
+ defineCommand,
4563
+ defineTrigger,
4564
+ defineService,
4565
+ createDocumentChangeTrigger
4566
+ };
4567
+ }
4568
+ //#endregion
4569
+ //#region src/core/project-mapping.ts
4570
+ /**
4571
+ * Walk the drive folder tree recursively, collecting all document entries.
4572
+ * Uses a visited set to break cycles (e.g. self-referencing folder nodes).
4573
+ */
4574
+ async function walkFolders(folders, folderPath, visited) {
4575
+ const seen = visited ?? /* @__PURE__ */ new Set();
4576
+ const key = folderPath ?? "";
4577
+ if (seen.has(key)) return [];
4578
+ seen.add(key);
4579
+ const entries = await folders.listFolder(folderPath || void 0);
4580
+ const results = [];
4581
+ for (const entry of entries) if (entry.type === "document") results.push(entry);
4582
+ else if (entry.type === "folder") results.push(...await walkFolders(folders, entry.path, seen));
4583
+ return results;
4584
+ }
4585
+ /**
4586
+ * Merge on-disk scan results with personal drive folder entries
4587
+ * to produce a unified project mapping.
4588
+ *
4589
+ * Links are matched by documentId. Projects without a documentId
4590
+ * are still included (path-only). Drive documents without a matching
4591
+ * on-disk project are also included (document-only).
4592
+ */
4593
+ async function getProjectMapping(scanResults, folders) {
4594
+ const mappings = [];
4595
+ const seenDocIds = /* @__PURE__ */ new Set();
4596
+ for (const scan of scanResults) {
4597
+ const mapping = {
4598
+ name: scan.name,
4599
+ path: scan.path,
4600
+ documentId: scan.documentId,
4601
+ documentType: scan.documentType,
4602
+ folderPath: void 0
4603
+ };
4604
+ if (scan.documentId) seenDocIds.add(scan.documentId);
4605
+ mappings.push(mapping);
4606
+ }
4607
+ if (folders) {
4608
+ const driveEntries = await walkFolders(folders);
4609
+ for (const entry of driveEntries) {
4610
+ const existing = mappings.find((m) => m.documentId && m.documentId === entry.id);
4611
+ if (existing) existing.folderPath = entry.path;
4612
+ else if (!seenDocIds.has(entry.id)) {
4613
+ seenDocIds.add(entry.id);
4614
+ mappings.push({
4615
+ name: entry.name,
4616
+ path: void 0,
4617
+ documentId: entry.id,
4618
+ documentType: entry.documentType,
4619
+ folderPath: entry.path
4620
+ });
4621
+ }
4622
+ }
4623
+ }
4624
+ return mappings;
4625
+ }
4626
+ //#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-BEshRPDR.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 };
4766
+
4767
+ //# sourceMappingURL=src-DD8PWpD5.mjs.map