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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/dist/build-DZIv63eB.mjs +77 -0
  2. package/dist/build-DZIv63eB.mjs.map +1 -0
  3. package/dist/{build-skills-BnqGyuCH.mjs → build-skills-XkfkDhWl.mjs} +15 -6
  4. package/dist/build-skills-XkfkDhWl.mjs.map +1 -0
  5. package/dist/dist-Bd6hUl0J.mjs +655 -0
  6. package/dist/dist-Bd6hUl0J.mjs.map +1 -0
  7. package/dist/glob-CGjvhxgW.mjs +48 -0
  8. package/dist/glob-CGjvhxgW.mjs.map +1 -0
  9. package/dist/index-C3-HSfKb.d.mts +389 -0
  10. package/dist/index-C3-HSfKb.d.mts.map +1 -0
  11. package/dist/index.d.mts +55 -303
  12. package/dist/index.d.mts.map +1 -1
  13. package/dist/index.mjs +7 -8
  14. package/dist/integrations/mastra/index.d.mts +248 -0
  15. package/dist/integrations/mastra/index.d.mts.map +1 -0
  16. package/dist/integrations/mastra/index.mjs +509 -0
  17. package/dist/integrations/mastra/index.mjs.map +1 -0
  18. package/dist/integrations/powerhouse/index.d.mts +4 -0
  19. package/dist/integrations/powerhouse/index.mjs +3 -0
  20. package/dist/markdown-BUeGwhbR.mjs +1588 -0
  21. package/dist/markdown-BUeGwhbR.mjs.map +1 -0
  22. package/dist/powerhouse-3XZmdY3_.mjs +1922 -0
  23. package/dist/powerhouse-3XZmdY3_.mjs.map +1 -0
  24. package/dist/{proxy-BFR8GScT.mjs → proxy-ji3EHzLn.mjs} +128 -28
  25. package/dist/proxy-ji3EHzLn.mjs.map +1 -0
  26. package/dist/remote-reactor-oBsHphPT.mjs +69 -0
  27. package/dist/remote-reactor-oBsHphPT.mjs.map +1 -0
  28. package/dist/{start-b7Mn2cxB.mjs → repl-Czb7u0x_.mjs} +6 -29
  29. package/dist/repl-Czb7u0x_.mjs.map +1 -0
  30. package/dist/runners/cli-runner.d.mts +339 -0
  31. package/dist/runners/cli-runner.d.mts.map +1 -0
  32. package/dist/runners/cli-runner.mjs +324 -0
  33. package/dist/runners/cli-runner.mjs.map +1 -0
  34. package/dist/runners/mastra-runner.d.mts +5 -3
  35. package/dist/runners/mastra-runner.d.mts.map +1 -1
  36. package/dist/runners/mastra-runner.mjs +10 -60
  37. package/dist/runners/mastra-runner.mjs.map +1 -1
  38. package/dist/runners/proxy-runner.d.mts +281 -0
  39. package/dist/runners/proxy-runner.d.mts.map +1 -0
  40. package/dist/runners/proxy-runner.mjs +91 -0
  41. package/dist/runners/proxy-runner.mjs.map +1 -0
  42. package/dist/schema-BEKAZGyT.mjs +47 -0
  43. package/dist/schema-BEKAZGyT.mjs.map +1 -0
  44. package/dist/{src-BebNN3xc.mjs → src-055YwI8s.mjs} +395 -1481
  45. package/dist/src-055YwI8s.mjs.map +1 -0
  46. package/dist/start-BHn9LIyX.mjs +37 -0
  47. package/dist/start-BHn9LIyX.mjs.map +1 -0
  48. package/dist/store-CxqB-OrX.mjs +101 -0
  49. package/dist/store-CxqB-OrX.mjs.map +1 -0
  50. package/dist/{stream-DVuufwIj.mjs → stream-BguHx7vC.mjs} +4 -2
  51. package/dist/{stream-DVuufwIj.mjs.map → stream-BguHx7vC.mjs.map} +1 -1
  52. package/dist/testing/index.d.mts +81 -0
  53. package/dist/testing/index.d.mts.map +1 -0
  54. package/dist/testing/index.mjs +131 -0
  55. package/dist/testing/index.mjs.map +1 -0
  56. package/dist/{types-CRkoD-Mm.d.mts → types-CF6GuPJd.d.mts} +241 -261
  57. package/dist/types-CF6GuPJd.d.mts.map +1 -0
  58. package/dist/types-CbHJ-ZnH.d.mts +60 -0
  59. package/dist/types-CbHJ-ZnH.d.mts.map +1 -0
  60. package/package.json +44 -25
  61. package/dist/build-skills-BnqGyuCH.mjs.map +0 -1
  62. package/dist/dist-CUltriBW.mjs +0 -1628
  63. package/dist/dist-CUltriBW.mjs.map +0 -1
  64. package/dist/drive-Bu9zoFrO.mjs +0 -85
  65. package/dist/drive-Bu9zoFrO.mjs.map +0 -1
  66. package/dist/esm-C1DOsF1a.mjs +0 -13140
  67. package/dist/esm-C1DOsF1a.mjs.map +0 -1
  68. package/dist/events-BnwGFTjv.mjs +0 -237
  69. package/dist/events-BnwGFTjv.mjs.map +0 -1
  70. package/dist/folders-BYO1Wqqb.mjs +0 -256
  71. package/dist/folders-BYO1Wqqb.mjs.map +0 -1
  72. package/dist/local-signer-EFzJV3bn.mjs +0 -128
  73. package/dist/local-signer-EFzJV3bn.mjs.map +0 -1
  74. package/dist/markdown-D-sP2zw_.mjs +0 -275
  75. package/dist/markdown-D-sP2zw_.mjs.map +0 -1
  76. package/dist/proxy-BFR8GScT.mjs.map +0 -1
  77. package/dist/proxy-routes-DP3ztsnS.mjs +0 -215
  78. package/dist/proxy-routes-DP3ztsnS.mjs.map +0 -1
  79. package/dist/reactor-C9VIUX1H.mjs +0 -51
  80. package/dist/reactor-C9VIUX1H.mjs.map +0 -1
  81. package/dist/runners/clint-runner.d.mts +0 -398
  82. package/dist/runners/clint-runner.d.mts.map +0 -1
  83. package/dist/runners/clint-runner.mjs +0 -519
  84. package/dist/runners/clint-runner.mjs.map +0 -1
  85. package/dist/services-9E-r0nWl.mjs +0 -999
  86. package/dist/services-9E-r0nWl.mjs.map +0 -1
  87. package/dist/src-BebNN3xc.mjs.map +0 -1
  88. package/dist/start-b7Mn2cxB.mjs.map +0 -1
  89. package/dist/subscriptions-CfiflAsI.mjs +0 -38
  90. package/dist/subscriptions-CfiflAsI.mjs.map +0 -1
  91. package/dist/switchboard-CyvOavqL.mjs +0 -57
  92. package/dist/switchboard-CyvOavqL.mjs.map +0 -1
  93. package/dist/types-CRkoD-Mm.d.mts.map +0 -1
@@ -0,0 +1,324 @@
1
+ import { n as resolveRemoteReactorConfig, t as attachDefaultReactor } from "../powerhouse-3XZmdY3_.mjs";
2
+ import { createRequire } from "node:module";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+ import { z } from "zod";
7
+ import { STOP_ON_STDIN_ENV, STOP_STREAM_LIMIT_MS, clearRunRecord, probeRun, readProjectName, readRunRecord, runRecordKey, stopStreamOf, writeRunRecord } from "@powerhousedao/host-core";
8
+ import { defineHostSchemas } from "@powerhousedao/host-core/schema";
9
+ //#region src/runners/cli-runner.ts
10
+ /**
11
+ * cli-runner (A5): runs a package's `Cli` — its `./cli` export, the
12
+ * `defineCli` result — in the terminal `ph run` was started from. The host's
13
+ * reactor is a REMOTE attach, as mastra-runner's: a lone `remote` backend
14
+ * whose `remote.url` is a drive address on a running switchboard (typically
15
+ * the output token `switchboard.drives.<slug>.url`). The runner hands that
16
+ * reactor to the Cli for the run (`RunOptions.reactor`), in place of the
17
+ * `create` the Cli configured. Everything after `ph run <host> --` (or `ph run <host> run`, or a first word
18
+ * that is no verb: `ph run <host> hello`) is the Cli's argv: a one-shot
19
+ * command, `-i` for its shell, or nothing.
20
+ *
21
+ * In a compound it is the foreground member (A6): it runs in the compound's
22
+ * process with the terminal, after the members next to it, which it sees as
23
+ * service instances; its end ends the stack with its exit code.
24
+ */
25
+ const kind = "reactor";
26
+ /** The Cli owns the terminal: it reads stdin itself, and in a compound it is
27
+ * the foreground member. */
28
+ const foreground = true;
29
+ /** The verbs this runner exports (`runCli`, `loadCli` and `loadOwnCli` are
30
+ * helpers). */
31
+ const verbs = ["run", "build"];
32
+ /** The Cli parses its own arguments: `ph run` hands them over unchecked. */
33
+ const argsSchema = {
34
+ options: [],
35
+ flags: [],
36
+ passthrough: true
37
+ };
38
+ /** The token a host writes for the switchboard's drive address (error hints). */
39
+ const REMOTE_URL_HINT = "remote: { url: switchboard.drives.<slug>.url } (from ../switchboard/outputs.js), or literally { url: { $output: { host: \"switchboard\", path: [\"drives\", \"<slug>\", \"url\"] } } }";
40
+ /**
41
+ * The cli host, from one definition in two forms: DECLARED (`remote.url` may
42
+ * be an output token; what host.js authors write) and RESOLVED (what the verb
43
+ * receives). `config` names the Cli; the reactor block names its switchboard.
44
+ */
45
+ const schemas = defineHostSchemas((s) => s.reactorHostSchema.extend({
46
+ runner: s.runnerBaseSchema.strict(),
47
+ config: z.strictObject({
48
+ /** The package whose `./cli` export the host runs (`<package>/cli`,
49
+ * resolved from the project). Absent: the project's own `./cli`. In a
50
+ * host an installed package supplies, both resolve from that package:
51
+ * absent is the package's own `./cli`. */
52
+ package: z.string().min(1).optional() }).optional()
53
+ }));
54
+ /** Declared form: what a host file may contain before resolution. */
55
+ const declaredHostSchema = schemas.declaredHostSchema;
56
+ /** Resolved form: what the verb receives (and `validateHost` checks). */
57
+ const hostSchema = schemas.hostSchema;
58
+ /** The drive address the host's reactor attaches to; undefined without a
59
+ * reactor block (the Cli then keeps the reactor it configured, if any). */
60
+ function remoteUrlOf(host) {
61
+ const backends = Object.entries(host.reactor?.backends ?? {});
62
+ if (backends.length === 0) return void 0;
63
+ const local = backends.find(([, backend]) => backend.kind !== "remote");
64
+ if (local) throw new Error(`hosts/${host.name}: a cli host attaches to a RUNNING switchboard, but backend "${local[0]}" is "${local[1].kind}". Run the reactor as its own switchboard host and declare one remote backend: ${REMOTE_URL_HINT}.`);
65
+ if (backends.length > 1) throw new Error(`hosts/${host.name}: a cli host attaches to one switchboard; declare one remote backend, not ${backends.length}.`);
66
+ const url = backends[0][1].remote?.url;
67
+ if (typeof url !== "string") throw new Error(`hosts/${host.name}: the remote backend needs a drive address on the switchboard (<switchboard>/d/<slug>): ${REMOTE_URL_HINT}.`);
68
+ return url;
69
+ }
70
+ function isCli(value) {
71
+ if (typeof value !== "object" || value === null) return false;
72
+ const cli = value;
73
+ return typeof cli.name === "string" && typeof cli.run === "function" && typeof cli.listCommands === "function";
74
+ }
75
+ /** The project's own package name, which its `./cli` is reached by. */
76
+ function ownPackageName(projectRoot) {
77
+ let name;
78
+ try {
79
+ name = JSON.parse(fs.readFileSync(path.join(projectRoot, "package.json"), "utf8")).name;
80
+ } catch {}
81
+ if (typeof name !== "string" || !name) throw new Error(`${projectRoot}/package.json has no name, so its ./cli export cannot be resolved; set config.package to the package that exports the Cli.`);
82
+ return name;
83
+ }
84
+ /**
85
+ * The `Cli` a package exports as `./cli` (named `cli`, or the default
86
+ * export), resolved from the project's dependency tree. Without `packageName`
87
+ * it is the project's own export, by its package.json name.
88
+ */
89
+ async function loadCli(projectRoot, packageName) {
90
+ const specifier = `${packageName ?? ownPackageName(projectRoot)}/cli`;
91
+ const projectRequire = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href);
92
+ let file;
93
+ try {
94
+ file = projectRequire.resolve(specifier);
95
+ } catch (cause) {
96
+ throw new Error(packageName ? `Cannot resolve ${specifier} from ${projectRoot}: the package must be a dependency of the project and export ./cli.` : `Cannot resolve ${specifier} from ${projectRoot}: its package.json needs the ./cli export, and \`ph build\` must have built cli/index.ts.`, { cause });
97
+ }
98
+ const module = await import(pathToFileURL(file).href);
99
+ const cli = module.cli ?? module.default;
100
+ if (!isCli(cli)) throw new Error(`${specifier} exports no Cli: export the defineCli result as \`cli\` (or as the default export).`);
101
+ return cli;
102
+ }
103
+ /**
104
+ * The project's own `./cli` export, or undefined when its package.json has
105
+ * none (a package without a Cli). An export that is declared but cannot be
106
+ * loaded throws, as `loadCli` does.
107
+ */
108
+ async function loadOwnCli(projectRoot) {
109
+ let exported;
110
+ try {
111
+ exported = JSON.parse(fs.readFileSync(path.join(projectRoot, "package.json"), "utf8")).exports?.["./cli"];
112
+ } catch {
113
+ return;
114
+ }
115
+ return exported ? loadCli(projectRoot) : void 0;
116
+ }
117
+ /** Whether `argv` opens the Cli's shell: `-i` before the command name, as the
118
+ * Cli itself reads its framework flags. */
119
+ function asksInteractive(cli, argv) {
120
+ const commands = /* @__PURE__ */ new Set([...cli.listCommands().map(({ id }) => id), "help"]);
121
+ for (const arg of argv) {
122
+ if (commands.has(arg)) return false;
123
+ if (arg === "-i" || arg === "--interactive") return true;
124
+ }
125
+ return false;
126
+ }
127
+ /** Calls `stop` once, when `stream` delivers anything or ends. */
128
+ function whenStreamStops(stream, stop) {
129
+ let stopped = false;
130
+ const once = () => {
131
+ if (stopped) return;
132
+ stopped = true;
133
+ stop();
134
+ };
135
+ for (const event of [
136
+ "data",
137
+ "end",
138
+ "close",
139
+ "error"
140
+ ]) stream.once(event, once);
141
+ stream.resume();
142
+ }
143
+ /**
144
+ * Runs `cli` in this process's terminal: its stdin, stdout and stderr, and
145
+ * the reactor `url` names. Resolves with the exit code once the Cli is done
146
+ * and its reactor released; it never exits the process itself, except when a
147
+ * stop through `stopStream` outlives its limit. A product bin is this call:
148
+ * `process.exit(await runCli(cli, { url, argv: process.argv.slice(2) }))`.
149
+ */
150
+ async function runCli(cli, options) {
151
+ const { stopStream } = options;
152
+ if (stopStream && asksInteractive(cli, options.argv)) {
153
+ console.error(`${cli.name}: -i reads stdin, and the process that started this one holds stdin to ask it to stop (${STOP_ON_STDIN_ENV}=1). Run the shell from a terminal, or run a command without -i.`);
154
+ return 1;
155
+ }
156
+ let attached;
157
+ const { url } = options;
158
+ const reactor = url ? async (setup, configured) => attached = await attachDefaultReactor(setup, {
159
+ ...await resolveRemoteReactorConfig(configured?.remote, setup),
160
+ url
161
+ }) : void 0;
162
+ if (stopStream) {
163
+ whenStreamStops(stopStream, () => {
164
+ const limit = options.stopStreamLimitMs ?? STOP_STREAM_LIMIT_MS;
165
+ setTimeout(() => process.exit(143), limit).unref();
166
+ if (process.emit("SIGTERM", "SIGTERM")) return;
167
+ const retry = setInterval(() => {
168
+ if (process.emit("SIGTERM", "SIGTERM")) clearInterval(retry);
169
+ }, 100);
170
+ retry.unref();
171
+ });
172
+ for (const output of [process.stdout, process.stderr]) output.on("error", () => void 0);
173
+ }
174
+ let exitCode = 0;
175
+ try {
176
+ await cli.run([
177
+ "node",
178
+ cli.name,
179
+ ...options.argv
180
+ ], {
181
+ exit: (code) => {
182
+ exitCode = code;
183
+ },
184
+ ...options.workdir ? { workdir: options.workdir } : {},
185
+ ...reactor ? { reactor } : {},
186
+ ...options.onServe ? { onServe: options.onServe } : {},
187
+ ...options.signal ? { signal: options.signal } : {},
188
+ ...options.members ? { members: options.members } : {}
189
+ });
190
+ } catch (error) {
191
+ console.error(error instanceof Error ? error.message : String(error));
192
+ if (exitCode === 0) exitCode = 1;
193
+ } finally {
194
+ await attached?.shutdown();
195
+ }
196
+ return exitCode;
197
+ }
198
+ /**
199
+ * The record of a Cli that keeps running: what `ph run <host> --stop` reads.
200
+ * A one-shot writes none and takes no lock, so it runs beside a serving
201
+ * instance; a second serving instance is refused.
202
+ */
203
+ function recordServing(projectRoot, hostName, verb, hostPackage) {
204
+ const projectName = readProjectName(projectRoot);
205
+ const key = runRecordKey(hostName, hostPackage);
206
+ const probe = probeRun(projectRoot, key, projectName);
207
+ if (probe.status === "live" && probe.record.pid !== process.pid) throw new Error(`${key} is already running for this project (pid ${probe.record.pid}). Stop it with \`ph run ${key} --stop\`, or run a command beside it: \`ph run ${key} -- <command>\`.`);
208
+ if (probe.status === "foreign") throw new Error(`.ph/run/${key}.json describes a live "${probe.record.projectName}", but this project is "${projectName}". Refusing to start a second instance.`);
209
+ writeRunRecord(projectRoot, {
210
+ version: 2,
211
+ host: hostName,
212
+ ...hostPackage === void 0 ? {} : { package: hostPackage },
213
+ projectName,
214
+ kind: "reactor",
215
+ verb,
216
+ pid: process.pid,
217
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
218
+ outputs: {}
219
+ });
220
+ process.on("exit", () => {
221
+ if (readRunRecord(projectRoot, key)?.pid === process.pid) clearRunRecord(projectRoot, key);
222
+ });
223
+ }
224
+ /** Resolves once what was written to `stream` before has been handed on
225
+ * (process.exit drops what a pipe has not taken yet). */
226
+ function drained(stream) {
227
+ return new Promise((resolve) => stream.write("", () => resolve()));
228
+ }
229
+ /** How long a stop from the compound waits for the Cli before the compound
230
+ * stops the rest: a command in flight or the line-based shell does not
231
+ * listen for it. */
232
+ const FOREGROUND_STOP_MS = 1e4;
233
+ /**
234
+ * The Cli as a compound's foreground member: in the compound's process, on
235
+ * the terminal, after the other members. Returns at once; the compound reads
236
+ * the Cli's end from `exited`. A supervised compound holds stdin (its stop
237
+ * stream), so the Cli neither reads it nor opens its shell then. Beside a
238
+ * running stack it may only run a command that ends.
239
+ */
240
+ function inStack(cli, host, ctx, url) {
241
+ const argv = ctx.argv ?? [];
242
+ const stack = ctx.parent?.host ?? host.name;
243
+ const done = (exited) => ({
244
+ outputs: {},
245
+ ready: Promise.resolve(),
246
+ exited,
247
+ shutdown: () => Promise.resolve()
248
+ });
249
+ if (ctx.env[STOP_ON_STDIN_ENV] === "1" && asksInteractive(cli, argv)) {
250
+ console.error(`${cli.name}: -i reads stdin, and the process that started "${stack}" holds its stdin to ask it to stop (${STOP_ON_STDIN_ENV}=1). Run the shell from a terminal, or run a command without -i.`);
251
+ return done(Promise.resolve(1));
252
+ }
253
+ const stop = new AbortController();
254
+ const exited = runCli(cli, {
255
+ argv,
256
+ ...url ? { url } : {},
257
+ workdir: ctx.projectRoot,
258
+ signal: stop.signal,
259
+ members: ctx.foreground.members,
260
+ ...ctx.foreground.beside ? { onServe: () => {
261
+ throw new Error(`${stack} is already running: beside it, \`ph run ${stack} -- <command>\` runs a command that ends. The shell and a serving Cli run in the stack itself.`);
262
+ } } : {}
263
+ }).then(async (code) => {
264
+ await Promise.all([drained(process.stdout), drained(process.stderr)]);
265
+ return code;
266
+ });
267
+ return {
268
+ ...done(exited),
269
+ shutdown: async () => {
270
+ stop.abort();
271
+ let timer;
272
+ await Promise.race([exited, new Promise((resolve) => {
273
+ timer = setTimeout(resolve, FOREGROUND_STOP_MS);
274
+ })]);
275
+ clearTimeout(timer);
276
+ }
277
+ };
278
+ }
279
+ /**
280
+ * `run`: the Cli in the foreground, with the host's reactor. On its own the
281
+ * process ends with the Cli's exit code. As a compound's foreground member
282
+ * it returns a handle whose `exited` the compound ends the stack on; it is
283
+ * never a compound's other, in-process kind of member.
284
+ */
285
+ async function run(host, ctx) {
286
+ if (ctx.parent && !ctx.foreground) throw new Error(`hosts/${host.name}: compound "${ctx.parent.host}" runs the cli runner as an ordinary member, but the Cli owns the terminal and its end is the stack's: it runs on its own (\`ph run ${host.name}\`) or as a compound's foreground member.`);
287
+ const url = remoteUrlOf(host);
288
+ const cli = await loadCli(ctx.hostPackage?.root ?? ctx.projectRoot, host.config?.package);
289
+ if (ctx.foreground) return inStack(cli, host, {
290
+ ...ctx,
291
+ foreground: ctx.foreground
292
+ }, url);
293
+ const stopStream = stopStreamOf(ctx.env, () => process.stdin);
294
+ const code = await runCli(cli, {
295
+ argv: ctx.argv ?? [],
296
+ ...url ? { url } : {},
297
+ workdir: ctx.projectRoot,
298
+ ...stopStream ? { stopStream } : {},
299
+ onServe: () => recordServing(ctx.projectRoot, host.name, ctx.verb, ctx.hostPackage?.name)
300
+ });
301
+ await Promise.all([drained(process.stdout), drained(process.stderr)]);
302
+ process.exit(code);
303
+ }
304
+ /**
305
+ * `build`: the package's skill and agent-profile compilation with the Cli's
306
+ * metadata in the template context. Loading the Cli starts nothing (no
307
+ * reactor, no services). Source and output are the conventional paths
308
+ * (`prompts/` or `agents/`, `dist/skills`). Shadows a Cli command named
309
+ * `build` as the first word after the host; `ph run <host> run build` still
310
+ * reaches it.
311
+ */
312
+ async function build(host, ctx) {
313
+ const cli = await loadCli(ctx.projectRoot, host.config?.package);
314
+ const { buildSkills } = await import("../build-skills-XkfkDhWl.mjs");
315
+ const result = await buildSkills({
316
+ rootDir: ctx.projectRoot,
317
+ cli
318
+ });
319
+ console.log(`[${host.name}] compiled ${result.skills} skill(s), ${result.profiles} profile(s) → ${result.outDir}`);
320
+ }
321
+ //#endregion
322
+ export { argsSchema, build, declaredHostSchema, foreground, hostSchema, kind, loadCli, loadOwnCli, run, runCli, verbs };
323
+
324
+ //# sourceMappingURL=cli-runner.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli-runner.mjs","names":[],"sources":["../../src/runners/cli-runner.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n clearRunRecord,\n probeRun,\n readProjectName,\n readRunRecord,\n runRecordKey,\n STOP_ON_STDIN_ENV,\n STOP_STREAM_LIMIT_MS,\n stopStreamOf,\n writeRunRecord,\n type RunnerArgsSchema,\n type RunnerContext,\n} from \"@powerhousedao/host-core\";\nimport { defineHostSchemas } from \"@powerhousedao/host-core/schema\";\nimport { z } from \"zod\";\nimport type { Cli, RunOptions, RunReactor } from \"../core/types.js\";\nimport {\n attachDefaultReactor,\n resolveRemoteReactorConfig,\n} from \"../integrations/powerhouse/index.js\";\nimport type { ReactorContext } from \"../integrations/powerhouse/types.js\";\n\n/**\n * cli-runner (A5): runs a package's `Cli` — its `./cli` export, the\n * `defineCli` result — in the terminal `ph run` was started from. The host's\n * reactor is a REMOTE attach, as mastra-runner's: a lone `remote` backend\n * whose `remote.url` is a drive address on a running switchboard (typically\n * the output token `switchboard.drives.<slug>.url`). The runner hands that\n * reactor to the Cli for the run (`RunOptions.reactor`), in place of the\n * `create` the Cli configured. Everything after `ph run <host> --` (or `ph run <host> run`, or a first word\n * that is no verb: `ph run <host> hello`) is the Cli's argv: a one-shot\n * command, `-i` for its shell, or nothing.\n *\n * In a compound it is the foreground member (A6): it runs in the compound's\n * process with the terminal, after the members next to it, which it sees as\n * service instances; its end ends the stack with its exit code.\n */\n\nexport const kind = \"reactor\";\n\n/** The Cli owns the terminal: it reads stdin itself, and in a compound it is\n * the foreground member. */\nexport const foreground = true;\n\n/** The verbs this runner exports (`runCli`, `loadCli` and `loadOwnCli` are\n * helpers). */\nexport const verbs = [\"run\", \"build\"] as const;\n\n/** The Cli parses its own arguments: `ph run` hands them over unchecked. */\nexport const argsSchema: RunnerArgsSchema = {\n options: [],\n flags: [],\n passthrough: true,\n};\n\n/** The token a host writes for the switchboard's drive address (error hints). */\nconst REMOTE_URL_HINT =\n 'remote: { url: switchboard.drives.<slug>.url } (from ../switchboard/outputs.js), or literally { url: { $output: { host: \"switchboard\", path: [\"drives\", \"<slug>\", \"url\"] } } }';\n\n/**\n * The cli host, from one definition in two forms: DECLARED (`remote.url` may\n * be an output token; what host.js authors write) and RESOLVED (what the verb\n * receives). `config` names the Cli; the reactor block names its switchboard.\n */\nconst schemas = defineHostSchemas((s) =>\n s.reactorHostSchema.extend({\n runner: s.runnerBaseSchema.strict(),\n config: z\n .strictObject({\n /** The package whose `./cli` export the host runs (`<package>/cli`,\n * resolved from the project). Absent: the project's own `./cli`. In a\n * host an installed package supplies, both resolve from that package:\n * absent is the package's own `./cli`. */\n package: z.string().min(1).optional(),\n })\n .optional(),\n }),\n);\n/** Declared form: what a host file may contain before resolution. */\nexport const declaredHostSchema = schemas.declaredHostSchema;\n/** Resolved form: what the verb receives (and `validateHost` checks). */\nexport const hostSchema = schemas.hostSchema;\n\n/** What a cli host.js author writes. */\nexport type CliHostInput = z.input<typeof declaredHostSchema>;\n/** What the verb receives. */\nexport type CliHost = z.output<typeof hostSchema>;\n\ndeclare global {\n interface PHHostRunners {\n \"@powerhousedao/clint/cli-runner\": {\n host: CliHostInput;\n outputs: Record<string, never>;\n };\n }\n}\n\n/** The drive address the host's reactor attaches to; undefined without a\n * reactor block (the Cli then keeps the reactor it configured, if any). */\nfunction remoteUrlOf(host: CliHost): string | undefined {\n const backends = Object.entries(host.reactor?.backends ?? {});\n if (backends.length === 0) return undefined;\n const local = backends.find(([, backend]) => backend.kind !== \"remote\");\n if (local) {\n throw new Error(\n `hosts/${host.name}: a cli host attaches to a RUNNING switchboard, but backend \"${local[0]}\" is \"${local[1].kind}\". ` +\n `Run the reactor as its own switchboard host and declare one remote backend: ${REMOTE_URL_HINT}.`,\n );\n }\n if (backends.length > 1) {\n throw new Error(\n `hosts/${host.name}: a cli host attaches to one switchboard; declare one remote backend, not ${backends.length}.`,\n );\n }\n const url = backends[0][1].remote?.url;\n if (typeof url !== \"string\") {\n throw new Error(\n `hosts/${host.name}: the remote backend needs a drive address on the switchboard (<switchboard>/d/<slug>): ${REMOTE_URL_HINT}.`,\n );\n }\n return url;\n}\n\nfunction isCli(value: unknown): value is Cli {\n if (typeof value !== \"object\" || value === null) return false;\n const cli = value as Partial<Record<keyof Cli, unknown>>;\n return (\n typeof cli.name === \"string\" &&\n typeof cli.run === \"function\" &&\n typeof cli.listCommands === \"function\"\n );\n}\n\n/** The project's own package name, which its `./cli` is reached by. */\nfunction ownPackageName(projectRoot: string): string {\n let name: unknown;\n try {\n name = (\n JSON.parse(\n fs.readFileSync(path.join(projectRoot, \"package.json\"), \"utf8\"),\n ) as { name?: unknown }\n ).name;\n } catch {\n // reported below\n }\n if (typeof name !== \"string\" || !name) {\n throw new Error(\n `${projectRoot}/package.json has no name, so its ./cli export cannot be resolved; set config.package to the package that exports the Cli.`,\n );\n }\n return name;\n}\n\n/**\n * The `Cli` a package exports as `./cli` (named `cli`, or the default\n * export), resolved from the project's dependency tree. Without `packageName`\n * it is the project's own export, by its package.json name.\n */\nexport async function loadCli(\n projectRoot: string,\n packageName?: string,\n): Promise<Cli> {\n const specifier = `${packageName ?? ownPackageName(projectRoot)}/cli`;\n const projectRequire = createRequire(\n pathToFileURL(path.join(projectRoot, \"package.json\")).href,\n );\n let file: string;\n try {\n file = projectRequire.resolve(specifier);\n } catch (cause) {\n throw new Error(\n packageName\n ? `Cannot resolve ${specifier} from ${projectRoot}: the package must be a dependency of the project and export ./cli.`\n : `Cannot resolve ${specifier} from ${projectRoot}: its package.json needs the ./cli export, and \\`ph build\\` must have built cli/index.ts.`,\n { cause },\n );\n }\n const module = (await import(pathToFileURL(file).href)) as Record<\n string,\n unknown\n >;\n const cli = module.cli ?? module.default;\n if (!isCli(cli)) {\n throw new Error(\n `${specifier} exports no Cli: export the defineCli result as \\`cli\\` (or as the default export).`,\n );\n }\n return cli;\n}\n\n/**\n * The project's own `./cli` export, or undefined when its package.json has\n * none (a package without a Cli). An export that is declared but cannot be\n * loaded throws, as `loadCli` does.\n */\nexport async function loadOwnCli(\n projectRoot: string,\n): Promise<Cli | undefined> {\n let exported: unknown;\n try {\n exported = (\n JSON.parse(\n fs.readFileSync(path.join(projectRoot, \"package.json\"), \"utf8\"),\n ) as { exports?: Record<string, unknown> }\n ).exports?.[\"./cli\"];\n } catch {\n return undefined;\n }\n return exported ? loadCli(projectRoot) : undefined;\n}\n\n/** Whether `argv` opens the Cli's shell: `-i` before the command name, as the\n * Cli itself reads its framework flags. */\nfunction asksInteractive(cli: Cli, argv: readonly string[]): boolean {\n const commands = new Set([...cli.listCommands().map(({ id }) => id), \"help\"]);\n for (const arg of argv) {\n if (commands.has(arg)) return false;\n if (arg === \"-i\" || arg === \"--interactive\") return true;\n }\n return false;\n}\n\n/** Calls `stop` once, when `stream` delivers anything or ends. */\nfunction whenStreamStops(stream: NodeJS.ReadableStream, stop: () => void) {\n let stopped = false;\n const once = () => {\n if (stopped) return;\n stopped = true;\n stop();\n };\n for (const event of [\"data\", \"end\", \"close\", \"error\"]) {\n stream.once(event, once);\n }\n stream.resume();\n}\n\nexport interface RunCliOptions {\n /** The Cli's arguments, as typed after its name. */\n argv: readonly string[];\n /** A switchboard drive address (`<switchboard>/d/<slug>`) the Cli's\n * reactor attaches to, in place of the one it configured. Absent: the Cli\n * keeps its own. */\n url?: string;\n /** Where the Cli works when no `--workdir` says otherwise. Default: cwd. */\n workdir?: string;\n /** A supervisor's stop request: anything on it, or its end, stops the Cli\n * as SIGTERM would. It is stdin, so the Cli's shell (`-i`) is refused. */\n stopStream?: NodeJS.ReadableStream;\n /** How long a stop may take before the process exits regardless (default\n * {@link STOP_STREAM_LIMIT_MS}). */\n stopStreamLimitMs?: number;\n /** Called when the Cli keeps running (see `RunOptions.onServe`). */\n onServe?: () => void | Promise<void>;\n /** Stops a Cli that keeps running (see `RunOptions.signal`). */\n signal?: AbortSignal;\n /** The compound's other members (see `RunOptions.members`). */\n members?: RunOptions[\"members\"];\n}\n\n/**\n * Runs `cli` in this process's terminal: its stdin, stdout and stderr, and\n * the reactor `url` names. Resolves with the exit code once the Cli is done\n * and its reactor released; it never exits the process itself, except when a\n * stop through `stopStream` outlives its limit. A product bin is this call:\n * `process.exit(await runCli(cli, { url, argv: process.argv.slice(2) }))`.\n */\nexport async function runCli(\n cli: Cli,\n options: RunCliOptions,\n): Promise<number> {\n const { stopStream } = options;\n if (stopStream && asksInteractive(cli, options.argv)) {\n console.error(\n `${cli.name}: -i reads stdin, and the process that started this one holds stdin to ask it to stop (${STOP_ON_STDIN_ENV}=1). ` +\n \"Run the shell from a terminal, or run a command without -i.\",\n );\n return 1;\n }\n\n // Released here as well as by the Cli's teardown, which not every exit\n // path of the Cli runs; it releases once.\n let attached: ReactorContext | undefined;\n const { url } = options;\n const reactor: RunReactor | undefined = url\n ? async (setup, configured) =>\n (attached = await attachDefaultReactor(setup, {\n ...(await resolveRemoteReactorConfig(configured?.remote, setup)),\n url,\n }))\n : undefined;\n\n if (stopStream) {\n whenStreamStops(stopStream, () => {\n // No supervisor may be left to end a stop that hangs.\n const limit = options.stopStreamLimitMs ?? STOP_STREAM_LIMIT_MS;\n setTimeout(() => process.exit(143), limit).unref();\n // As the stop channel does: a serving Cli's handler tears it down. A\n // stop during its start waits for the handler; a command in flight\n // finishes within the limit.\n if (process.emit(\"SIGTERM\", \"SIGTERM\")) return;\n const retry = setInterval(() => {\n if (process.emit(\"SIGTERM\", \"SIGTERM\")) clearInterval(retry);\n }, 100);\n retry.unref();\n });\n // These go when the supervisor does, and with no listener the next line\n // would be a fatal error in the middle of the shutdown it asked for.\n for (const output of [process.stdout, process.stderr]) {\n output.on(\"error\", () => undefined);\n }\n }\n\n let exitCode = 0;\n try {\n await cli.run([\"node\", cli.name, ...options.argv], {\n exit: (code) => {\n exitCode = code;\n },\n ...(options.workdir ? { workdir: options.workdir } : {}),\n ...(reactor ? { reactor } : {}),\n ...(options.onServe ? { onServe: options.onServe } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n ...(options.members ? { members: options.members } : {}),\n });\n } catch (error) {\n console.error(error instanceof Error ? error.message : String(error));\n if (exitCode === 0) exitCode = 1;\n } finally {\n await attached?.shutdown();\n }\n return exitCode;\n}\n\n/**\n * The record of a Cli that keeps running: what `ph run <host> --stop` reads.\n * A one-shot writes none and takes no lock, so it runs beside a serving\n * instance; a second serving instance is refused.\n */\nfunction recordServing(\n projectRoot: string,\n hostName: string,\n verb: string,\n hostPackage?: string,\n): void {\n const projectName = readProjectName(projectRoot);\n // A package's host is filed, and addressed, behind its package.\n const key = runRecordKey(hostName, hostPackage);\n const probe = probeRun(projectRoot, key, projectName);\n if (probe.status === \"live\" && probe.record.pid !== process.pid) {\n throw new Error(\n `${key} is already running for this project (pid ${probe.record.pid}). ` +\n `Stop it with \\`ph run ${key} --stop\\`, or run a command beside it: \\`ph run ${key} -- <command>\\`.`,\n );\n }\n if (probe.status === \"foreign\") {\n throw new Error(\n `.ph/run/${key}.json describes a live \"${probe.record.projectName}\", but this project is \"${projectName}\". Refusing to start a second instance.`,\n );\n }\n writeRunRecord(projectRoot, {\n version: 2,\n host: hostName,\n ...(hostPackage === undefined ? {} : { package: hostPackage }),\n projectName,\n kind: \"reactor\",\n verb,\n pid: process.pid,\n startedAt: new Date().toISOString(),\n outputs: {},\n });\n process.on(\"exit\", () => {\n if (readRunRecord(projectRoot, key)?.pid === process.pid) {\n clearRunRecord(projectRoot, key);\n }\n });\n}\n\n/** Resolves once what was written to `stream` before has been handed on\n * (process.exit drops what a pipe has not taken yet). */\nfunction drained(stream: NodeJS.WriteStream): Promise<void> {\n return new Promise((resolve) => stream.write(\"\", () => resolve()));\n}\n\n/** How long a stop from the compound waits for the Cli before the compound\n * stops the rest: a command in flight or the line-based shell does not\n * listen for it. */\nconst FOREGROUND_STOP_MS = 10_000;\n\n/** The handle the compound gets from its foreground member. */\nexport interface ForegroundHandle {\n outputs: Record<string, never>;\n ready: Promise<void>;\n /** The Cli's end, with its exit code: the stack's. */\n exited: Promise<number>;\n /** Asks the Cli to stop (its `RunOptions.signal`) and waits for it, up to\n * a limit. */\n shutdown(): Promise<void>;\n}\n\n/**\n * The Cli as a compound's foreground member: in the compound's process, on\n * the terminal, after the other members. Returns at once; the compound reads\n * the Cli's end from `exited`. A supervised compound holds stdin (its stop\n * stream), so the Cli neither reads it nor opens its shell then. Beside a\n * running stack it may only run a command that ends.\n */\nfunction inStack(\n cli: Cli,\n host: CliHost,\n ctx: RunnerContext & { foreground: NonNullable<RunnerContext[\"foreground\"]> },\n url: string | undefined,\n): ForegroundHandle {\n const argv = ctx.argv ?? [];\n const stack = ctx.parent?.host ?? host.name;\n const done = (exited: Promise<number>): ForegroundHandle => ({\n outputs: {},\n ready: Promise.resolve(),\n exited,\n shutdown: () => Promise.resolve(),\n });\n if (ctx.env[STOP_ON_STDIN_ENV] === \"1\" && asksInteractive(cli, argv)) {\n console.error(\n `${cli.name}: -i reads stdin, and the process that started \"${stack}\" holds its stdin to ask it to stop (${STOP_ON_STDIN_ENV}=1). ` +\n `Run the shell from a terminal, or run a command without -i.`,\n );\n return done(Promise.resolve(1));\n }\n const stop = new AbortController();\n const exited = runCli(cli, {\n argv,\n ...(url ? { url } : {}),\n workdir: ctx.projectRoot,\n signal: stop.signal,\n members: ctx.foreground.members,\n ...(ctx.foreground.beside\n ? {\n onServe: () => {\n throw new Error(\n `${stack} is already running: beside it, \\`ph run ${stack} -- <command>\\` runs a command that ends. The shell and a serving Cli run in the stack itself.`,\n );\n },\n }\n : {}),\n }).then(async (code) => {\n await Promise.all([drained(process.stdout), drained(process.stderr)]);\n return code;\n });\n return {\n ...done(exited),\n shutdown: async () => {\n stop.abort();\n let timer: NodeJS.Timeout | undefined;\n await Promise.race([\n exited,\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, FOREGROUND_STOP_MS);\n }),\n ]);\n clearTimeout(timer);\n },\n };\n}\n\n/**\n * `run`: the Cli in the foreground, with the host's reactor. On its own the\n * process ends with the Cli's exit code. As a compound's foreground member\n * it returns a handle whose `exited` the compound ends the stack on; it is\n * never a compound's other, in-process kind of member.\n */\nexport async function run(\n host: CliHost,\n ctx: RunnerContext,\n): Promise<ForegroundHandle | undefined> {\n if (ctx.parent && !ctx.foreground) {\n throw new Error(\n `hosts/${host.name}: compound \"${ctx.parent.host}\" runs the cli runner as an ordinary member, but the Cli owns the terminal and its end is the stack's: it runs on its own (\\`ph run ${host.name}\\`) or as a compound's foreground member.`,\n );\n }\n const url = remoteUrlOf(host);\n // From the package that supplies the host, if one does: its own `./cli`.\n // The Cli still works in the project.\n const cli = await loadCli(\n ctx.hostPackage?.root ?? ctx.projectRoot,\n host.config?.package,\n );\n if (ctx.foreground) {\n return inStack(cli, host, { ...ctx, foreground: ctx.foreground }, url);\n }\n const stopStream = stopStreamOf(ctx.env, () => process.stdin);\n const code = await runCli(cli, {\n argv: ctx.argv ?? [],\n ...(url ? { url } : {}),\n workdir: ctx.projectRoot,\n ...(stopStream ? { stopStream } : {}),\n onServe: () =>\n recordServing(\n ctx.projectRoot,\n host.name,\n ctx.verb,\n ctx.hostPackage?.name,\n ),\n });\n await Promise.all([drained(process.stdout), drained(process.stderr)]);\n process.exit(code);\n}\n\n/**\n * `build`: the package's skill and agent-profile compilation with the Cli's\n * metadata in the template context. Loading the Cli starts nothing (no\n * reactor, no services). Source and output are the conventional paths\n * (`prompts/` or `agents/`, `dist/skills`). Shadows a Cli command named\n * `build` as the first word after the host; `ph run <host> run build` still\n * reaches it.\n */\nexport async function build(host: CliHost, ctx: RunnerContext): Promise<void> {\n const cli = await loadCli(ctx.projectRoot, host.config?.package);\n const { buildSkills } = await import(\"../dev/build-skills.js\");\n const result = await buildSkills({ rootDir: ctx.projectRoot, cli });\n console.log(\n `[${host.name}] compiled ${result.skills} skill(s), ${result.profiles} profile(s) → ${result.outDir}`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0CA,MAAa,OAAO;;;AAIpB,MAAa,aAAa;;;AAI1B,MAAa,QAAQ,CAAC,OAAO,OAAO;;AAGpC,MAAa,aAA+B;CAC1C,SAAS,CA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K,0CACnM;CAEF,MAAM,MAAM,YAAY,IAAI;CAG5B,MAAM,MAAM,MAAM,QAChB,IAAI,aAAa,QAAQ,IAAI,aAC7B,KAAK,QAAQ,OACf;CACA,IAAI,IAAI,YACN,OAAO,QAAQ,KAAK,MAAM;EAAE,GAAG;EAAK,YAAY,IAAI;CAAW,GAAG,GAAG;CAEvE,MAAM,aAAa,aAAa,IAAI,WAAW,QAAQ,KAAK;CAC5D,MAAM,OAAO,MAAM,OAAO,KAAK;EAC7B,MAAM,IAAI,QAAQ,CAAC;EACnB,GAAI,MAAM,EAAE,IAAI,IAAI,CAAC;EACrB,SAAS,IAAI;EACb,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;EACnC,eACE,cACE,IAAI,aACJ,KAAK,MACL,IAAI,MACJ,IAAI,aAAa,IACnB;CACJ,CAAC;CACD,MAAM,QAAQ,IAAI,CAAC,QAAQ,QAAQ,MAAM,GAAG,QAAQ,QAAQ,MAAM,CAAC,CAAC;CACpE,QAAQ,KAAK,IAAI;AACnB;;;;;;;;;AAUA,eAAsB,MAAM,MAAe,KAAmC;CAC5E,MAAM,MAAM,MAAM,QAAQ,IAAI,aAAa,KAAK,QAAQ,OAAO;CAC/D,MAAM,EAAE,gBAAgB,MAAM,OAAO;CACrC,MAAM,SAAS,MAAM,YAAY;EAAE,SAAS,IAAI;EAAa;CAAI,CAAC;CAClE,QAAQ,IACN,IAAI,KAAK,KAAK,aAAa,OAAO,OAAO,aAAa,OAAO,SAAS,gBAAgB,OAAO,QAC/F;AACF"}
@@ -86,7 +86,6 @@ export declare const declaredHostSchema: z.ZodObject<{
86
86
  refuse: "refuse";
87
87
  }>>;
88
88
  }, z.core.$strict>>;
89
- workflows: z.ZodOptional<z.ZodBoolean>;
90
89
  renown: z.ZodOptional<z.ZodObject<{
91
90
  url: z.ZodOptional<z.ZodString>;
92
91
  networkId: z.ZodOptional<z.ZodString>;
@@ -208,7 +207,6 @@ export declare const hostSchema: z.ZodObject<{
208
207
  refuse: "refuse";
209
208
  }>>;
210
209
  }, z.core.$strict>>;
211
- workflows: z.ZodOptional<z.ZodBoolean>;
212
210
  renown: z.ZodOptional<z.ZodObject<{
213
211
  url: z.ZodOptional<z.ZodString>;
214
212
  networkId: z.ZodOptional<z.ZodString>;
@@ -293,7 +291,11 @@ export declare function promptFromMessages(messages: ChatMessage[]): string;
293
291
  export type AgentServeHandle = RunnerHandle<MastraOutputs>;
294
292
  export declare function run(host: MastraHost, ctx: RunnerContext): Promise<AgentServeHandle>;
295
293
  export declare const serve: typeof run;
296
- /** `build` — skill + agent-profile compilation (ph-clint-dev's pipeline). */
294
+ /**
295
+ * `build` — skill + agent-profile compilation (ph-clint-dev's pipeline).
296
+ * When the package also exports a `Cli` (`./cli`), its metadata joins the
297
+ * template context; without that export the build is path-driven only.
298
+ */
297
299
  export declare function build(host: MastraHost, ctx: RunnerContext): Promise<void>;
298
300
  //#endregion
299
301
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"mastra-runner.d.mts","names":[],"sources":["../../src/runners/mastra-runner.ts"],"mappings":";;;;;;;;;;;;;;;qBA0Ca;;qBAGA;;qBA8CA,oBAAkB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAA6B,EAAA,KAAA;;qBAE/C,YAAU,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAAqB,EAAA,KAAA;;YAGhC,kBAAkB,EAAE,aAAa;;YAEjC,aAAa,EAAE,cAAc;YAC7B,kBAAkB,YAAY;;;qBAI7B,eAAa,EAAA;;;;;;GASxB,EAAA,KAAA;YAEU,gBAAgB,EAAE,aAAa;QAEnC;YACI;IACR;MACE,MAAM;MACN,SAAS;;;;KA+BV;EAAgB;EAAc;;;;wBAInB,mBAAmB,UAAU;YAqCjC,mBAAmB,aAAa;wBAmNtB,IACpB,MAAM,YACN,KAAK,gBACJ,QAAQ;qBAIE,cAAK;;wBAGI,MACpB,MAAM,YACN,KAAK,gBACJ"}
1
+ {"version":3,"file":"mastra-runner.d.mts","names":[],"sources":["../../src/runners/mastra-runner.ts"],"mappings":";;;;;;;;;;;;;;;qBA0Ca;;qBAGA;;qBA8CA,oBAAkB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAA6B,EAAA,KAAA;;qBAE/C,YAAU,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAAqB,EAAA,KAAA;;YAGhC,kBAAkB,EAAE,aAAa;;YAEjC,aAAa,EAAE,cAAc;YAC7B,kBAAkB,YAAY;;;qBAI7B,eAAa,EAAA;;;;;;GASxB,EAAA,KAAA;YAEU,gBAAgB,EAAE,aAAa;QAEnC;YACI;IACR;MACE,MAAM;MACN,SAAS;;;;KA+BV;EAAgB;EAAc;;;;wBAInB,mBAAmB,UAAU;YAqCjC,mBAAmB,aAAa;wBAmNtB,IACpB,MAAM,YACN,KAAK,gBACJ,QAAQ;qBAIE,cAAK;;;;;;wBAOI,MACpB,MAAM,YACN,KAAK,gBACJ"}
@@ -1,66 +1,10 @@
1
+ import { t as attachRemoteReactor } from "../remote-reactor-oBsHphPT.mjs";
1
2
  import fs from "node:fs";
2
3
  import { z } from "zod";
3
4
  import { randomUUID } from "node:crypto";
4
5
  import { createServer } from "node:http";
5
6
  import { defaultUserDataDir, probeRun, resolveUserDataPlaceholders } from "@powerhousedao/host-core";
6
7
  import { defineHostSchemas, switchboardOfDrive } from "@powerhousedao/host-core/schema";
7
- //#region src/integrations/powerhouse/remote-reactor.ts
8
- /** Derive the GraphQL endpoint from the accepted url spellings. */
9
- function deriveGraphqlEndpoint(url) {
10
- const parsed = new URL(url);
11
- if (parsed.pathname.includes("/d/")) return `${parsed.origin}/graphql`;
12
- if (parsed.pathname.replace(/\/$/, "").endsWith("/graphql")) return `${parsed.origin}${parsed.pathname.replace(/\/$/, "")}`;
13
- const base = parsed.pathname.replace(/\/$/, "");
14
- return `${parsed.origin}${base}/graphql`;
15
- }
16
- async function probeEndpoint(endpoint, timeoutMs) {
17
- try {
18
- await fetch(endpoint, {
19
- method: "POST",
20
- headers: { "content-type": "application/json" },
21
- body: JSON.stringify({ query: "{ __typename }" }),
22
- signal: AbortSignal.timeout(timeoutMs)
23
- });
24
- } catch (cause) {
25
- throw new Error(`Cannot attach to the reactor at ${endpoint}: the switchboard is not answering. The agent depends on a RUNNING switchboard and never starts one — start it first (e.g. \`ph run switchboard\`, \`ph vetra\`, or the compound that members both) and retry.`, { cause });
26
- }
27
- }
28
- /** Read the inspection subgraph's info when it answers (dev switchboards
29
- * under the OPEN policy serve it); absence is not an attach failure. */
30
- async function readRemoteInfo(endpoint, token, timeoutMs) {
31
- try {
32
- const res = await fetch(`${endpoint}/inspection`, {
33
- method: "POST",
34
- headers: {
35
- "content-type": "application/json",
36
- ...token ? { authorization: `Bearer ${token}` } : {}
37
- },
38
- body: JSON.stringify({ query: "query ReactorInspectionInfo { inspection { info } }" }),
39
- signal: AbortSignal.timeout(timeoutMs)
40
- });
41
- if (!res.ok) return void 0;
42
- return (await res.json()).data?.inspection?.info;
43
- } catch {
44
- return;
45
- }
46
- }
47
- async function attachRemoteReactor(options) {
48
- const timeoutMs = options.timeoutMs ?? 1e4;
49
- const endpoint = deriveGraphqlEndpoint(options.url);
50
- await probeEndpoint(endpoint, timeoutMs);
51
- const remoteInfo = await readRemoteInfo(endpoint, options.token, timeoutMs);
52
- const { GraphQLReactorClient } = await import("@powerhousedao/reactor-browser/graphql-client");
53
- return {
54
- endpoint,
55
- client: new GraphQLReactorClient({
56
- url: endpoint,
57
- documentModels: options.documentModels,
58
- ...options.token ? { tokenProvider: () => Promise.resolve(options.token) } : {}
59
- }),
60
- remoteInfo
61
- };
62
- }
63
- //#endregion
64
8
  //#region src/integrations/powerhouse/reactor-tools.ts
65
9
  const DRIVE_TYPE = "powerhouse/document-drive";
66
10
  function isRecord(v) {
@@ -226,7 +170,7 @@ function mastraModelConfig(model, apiKey) {
226
170
  }
227
171
  async function createMastraProvider(options) {
228
172
  const { Agent } = await import("@mastra/core/agent");
229
- const { mapMastraStream } = await import("../stream-DVuufwIj.mjs");
173
+ const { mapMastraStream } = await import("../stream-BguHx7vC.mjs").then((n) => n.n);
230
174
  const agent = new Agent({
231
175
  id: options.agentName,
232
176
  name: options.agentName,
@@ -498,12 +442,18 @@ async function run(host, ctx) {
498
442
  return serveAgent(host, ctx);
499
443
  }
500
444
  const serve = run;
501
- /** `build` — skill + agent-profile compilation (ph-clint-dev's pipeline). */
445
+ /**
446
+ * `build` — skill + agent-profile compilation (ph-clint-dev's pipeline).
447
+ * When the package also exports a `Cli` (`./cli`), its metadata joins the
448
+ * template context; without that export the build is path-driven only.
449
+ */
502
450
  async function build(host, ctx) {
503
451
  const config = host.config ?? {};
504
- const { buildSkills } = await import("../build-skills-BnqGyuCH.mjs");
452
+ const { buildSkills } = await import("../build-skills-XkfkDhWl.mjs");
453
+ const { loadOwnCli } = await import("./cli-runner.mjs");
505
454
  const result = await buildSkills({
506
455
  rootDir: ctx.projectRoot,
456
+ cli: await loadOwnCli(ctx.projectRoot),
507
457
  skillsDir: config.prompts?.skillsDir,
508
458
  agentsDir: config.prompts?.agentsDir,
509
459
  outDir: config.prompts?.outDir