@powerhousedao/clint 6.4.0-next.0 → 6.4.0-next.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{build-skills-BNEOn-cl.mjs → build-skills-Bpbbnin0.mjs} +2 -2
- package/dist/{build-skills-BNEOn-cl.mjs.map → build-skills-Bpbbnin0.mjs.map} +1 -1
- package/dist/{dist--xzirmg-.mjs → dist-Bd6hUl0J.mjs} +2 -2
- package/dist/{dist--xzirmg-.mjs.map → dist-Bd6hUl0J.mjs.map} +1 -1
- package/dist/{index-C3-HSfKb.d.mts → index-CfHcet4v.d.mts} +2 -2
- package/dist/{index-C3-HSfKb.d.mts.map → index-CfHcet4v.d.mts.map} +1 -1
- package/dist/index.d.mts +33 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +3 -3
- package/dist/integrations/mastra/index.d.mts +1 -1
- package/dist/integrations/mastra/index.mjs.map +1 -1
- package/dist/integrations/powerhouse/index.d.mts +2 -2
- package/dist/integrations/powerhouse/index.mjs +2 -2
- package/dist/{powerhouse-BDnj7kqd.mjs → powerhouse-3XZmdY3_.mjs} +4 -4
- package/dist/{powerhouse-BDnj7kqd.mjs.map → powerhouse-3XZmdY3_.mjs.map} +1 -1
- package/dist/{remote-reactor-BQzq4yfO.mjs → remote-reactor-oBsHphPT.mjs} +2 -2
- package/dist/{remote-reactor-BQzq4yfO.mjs.map → remote-reactor-oBsHphPT.mjs.map} +1 -1
- package/dist/runners/cli-runner.d.mts +5 -1
- package/dist/runners/cli-runner.d.mts.map +1 -1
- package/dist/runners/cli-runner.mjs +24 -10
- package/dist/runners/cli-runner.mjs.map +1 -1
- package/dist/runners/mastra-runner.mjs +2 -2
- package/dist/{src-BehwgLP6.mjs → src-BmMd0Wl4.mjs} +161 -23
- package/dist/src-BmMd0Wl4.mjs.map +1 -0
- package/dist/testing/index.d.mts +2 -2
- package/dist/{types-CbHJ-ZnH.d.mts → types-3TnDjQ1w.d.mts} +2 -2
- package/dist/{types-CbHJ-ZnH.d.mts.map → types-3TnDjQ1w.d.mts.map} +1 -1
- package/dist/{types-CF6GuPJd.d.mts → types-DbQKfvWc.d.mts} +20 -1
- package/dist/types-DbQKfvWc.d.mts.map +1 -0
- package/package.json +13 -13
- package/dist/src-BehwgLP6.mjs.map +0 -1
- package/dist/types-CF6GuPJd.d.mts.map +0 -1
|
@@ -21,7 +21,7 @@ async function probeEndpoint(endpoint, timeoutMs) {
|
|
|
21
21
|
signal: AbortSignal.timeout(timeoutMs)
|
|
22
22
|
});
|
|
23
23
|
} catch (cause) {
|
|
24
|
-
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
|
|
24
|
+
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 dev\`, or the compound that members both) and retry.`, { cause });
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
27
|
/** Read the inspection subgraph's info when it answers (dev switchboards
|
|
@@ -66,4 +66,4 @@ async function attachRemoteReactor(options) {
|
|
|
66
66
|
//#endregion
|
|
67
67
|
export { remote_reactor_exports as n, attachRemoteReactor as t };
|
|
68
68
|
|
|
69
|
-
//# sourceMappingURL=remote-reactor-
|
|
69
|
+
//# sourceMappingURL=remote-reactor-oBsHphPT.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote-reactor-
|
|
1
|
+
{"version":3,"file":"remote-reactor-oBsHphPT.mjs","names":[],"sources":["../src/integrations/powerhouse/remote-reactor.ts"],"sourcesContent":["import type {\n DocumentModelModule,\n ISigner,\n} from \"@powerhousedao/shared/document-model\";\nimport type { ReactorProtocol } from \"@powerhousedao/host-core\";\nimport type {\n BearerTokenProvider,\n GraphQLReactorClientOptions,\n} from \"@powerhousedao/reactor-browser/graphql-client\";\n\n/**\n * P5.5 — the agent host's reactor is a REMOTE attach: a running switchboard,\n * reached over GraphQL, with nothing of it glued to the CLI's lifetime. N\n * agents attach to ONE reactor as clients; the switchboard\n * outlives agent sessions. The agent DEPENDS on the switchboard — an\n * unreachable remote fails the attach loudly with the start hint, it never\n * auto-starts one.\n */\n\nexport interface AttachRemoteReactorOptions {\n /**\n * Where the switchboard lives: its GraphQL endpoint\n * (`http://localhost:4001/graphql`), a drive url (`…/d/<drive>`), or a bare\n * origin — the endpoint is derived.\n */\n url: string;\n /** Document models the client signs/reduces with. */\n documentModels: readonly DocumentModelModule<any>[];\n /**\n * What this agent expects of the fleet it joins (the host file's\n * reactor.protocol). Reachability and inspection facts are checked at\n * attach; flag-level comparison engages once the inspection subgraph\n * exposes the enforcement flags (upstream note in the phase-5 WBS) — until\n * then the expectation is carried for the error message and future use.\n */\n expectedProtocol?: ReactorProtocol;\n /** Bearer for authenticated switchboards; omitted = unauthenticated. */\n token?: string;\n /**\n * Resolves the bearer per request, for a token that expires (a Renown\n * token). Takes precedence over `token`. Returning undefined sends the\n * request unauthenticated.\n */\n tokenProvider?: BearerTokenProvider;\n /**\n * Signs the actions the client pushes. A function is called per push (see\n * `createReactorWrites`, whose `signer` refuses while the identity has no\n * user). Omitted, the client falls back to the ambient Renown signer, which\n * does not exist in Node: actions then go out unsigned.\n */\n signer?: ISigner | (() => ISigner | undefined);\n /** Reachability probe budget. */\n timeoutMs?: number;\n}\n\nexport interface RemoteReactorAttachment {\n /** The derived GraphQL endpoint actually dialed. */\n endpoint: string;\n /** IReactorClient-compatible GraphQL client (reactor-browser). */\n client: unknown;\n /** Remote facts from the inspection subgraph, when it answers. */\n remoteInfo?: Record<string, unknown>;\n}\n\n/** Derive the GraphQL endpoint from the accepted url spellings. */\nexport function deriveGraphqlEndpoint(url: string): string {\n const parsed = new URL(url);\n if (parsed.pathname.includes(\"/d/\")) {\n return `${parsed.origin}/graphql`;\n }\n if (parsed.pathname.replace(/\\/$/, \"\").endsWith(\"/graphql\")) {\n return `${parsed.origin}${parsed.pathname.replace(/\\/$/, \"\")}`;\n }\n const base = parsed.pathname.replace(/\\/$/, \"\");\n return `${parsed.origin}${base}/graphql`;\n}\n\nasync function probeEndpoint(\n endpoint: string,\n timeoutMs: number,\n): Promise<void> {\n try {\n // A GraphQL endpoint answers POST; any HTTP response (even 400) proves\n // the server is listening. Only transport failure means unreachable.\n await fetch(endpoint, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ query: \"{ __typename }\" }),\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (cause) {\n throw new Error(\n `Cannot attach to the reactor at ${endpoint}: the switchboard is not ` +\n `answering. The agent depends on a RUNNING switchboard and never ` +\n `starts one — start it first (e.g. \\`ph run switchboard\\`, ` +\n `\\`ph dev\\`, or the compound that members both) and retry.`,\n { cause },\n );\n }\n}\n\n/** Read the inspection subgraph's info when it answers (dev switchboards\n * under the OPEN policy serve it); absence is not an attach failure. */\nasync function readRemoteInfo(\n endpoint: string,\n tokenProvider: BearerTokenProvider | undefined,\n timeoutMs: number,\n): Promise<Record<string, unknown> | undefined> {\n try {\n const token = await tokenProvider?.();\n const res = await fetch(`${endpoint}/inspection`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(token ? { authorization: `Bearer ${token}` } : {}),\n },\n body: JSON.stringify({\n query: \"query ReactorInspectionInfo { inspection { info } }\",\n }),\n signal: AbortSignal.timeout(timeoutMs),\n });\n if (!res.ok) return undefined;\n const body = (await res.json()) as {\n data?: { inspection?: { info?: Record<string, unknown> } };\n };\n return body.data?.inspection?.info;\n } catch {\n return undefined;\n }\n}\n\nexport async function attachRemoteReactor(\n options: AttachRemoteReactorOptions,\n): Promise<RemoteReactorAttachment> {\n const timeoutMs = options.timeoutMs ?? 10_000;\n const endpoint = deriveGraphqlEndpoint(options.url);\n\n const token = options.token;\n const tokenProvider =\n options.tokenProvider ??\n (token ? () => Promise.resolve<string | undefined>(token) : undefined);\n\n await probeEndpoint(endpoint, timeoutMs);\n const remoteInfo = await readRemoteInfo(endpoint, tokenProvider, timeoutMs);\n\n const { GraphQLReactorClient } =\n await import(\"@powerhousedao/reactor-browser/graphql-client\");\n const clientOptions: GraphQLReactorClientOptions = {\n url: endpoint,\n documentModels: options.documentModels,\n ...(tokenProvider ? { tokenProvider } : {}),\n ...(options.signer ? { signer: options.signer } : {}),\n };\n const client = new GraphQLReactorClient(clientOptions);\n\n return { endpoint, client, remoteInfo };\n}\n"],"mappings":";;;;;;;AAiEA,SAAgB,sBAAsB,KAAqB;CACzD,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,IAAI,OAAO,SAAS,SAAS,KAAK,GAChC,OAAO,GAAG,OAAO,OAAO;CAE1B,IAAI,OAAO,SAAS,QAAQ,OAAO,EAAE,CAAC,CAAC,SAAS,UAAU,GACxD,OAAO,GAAG,OAAO,SAAS,OAAO,SAAS,QAAQ,OAAO,EAAE;CAE7D,MAAM,OAAO,OAAO,SAAS,QAAQ,OAAO,EAAE;CAC9C,OAAO,GAAG,OAAO,SAAS,KAAK;AACjC;AAEA,eAAe,cACb,UACA,WACe;CACf,IAAI;EAGF,MAAM,MAAM,UAAU;GACpB,QAAQ;GACR,SAAS,EAAE,gBAAgB,mBAAmB;GAC9C,MAAM,KAAK,UAAU,EAAE,OAAO,iBAAiB,CAAC;GAChD,QAAQ,YAAY,QAAQ,SAAS;EACvC,CAAC;CACH,SAAS,OAAO;EACd,MAAM,IAAI,MACR,mCAAmC,SAAS,+MAI5C,EAAE,MAAM,CACV;CACF;AACF;;;AAIA,eAAe,eACb,UACA,eACA,WAC8C;CAC9C,IAAI;EACF,MAAM,QAAQ,MAAM,gBAAgB;EACpC,MAAM,MAAM,MAAM,MAAM,GAAG,SAAS,cAAc;GAChD,QAAQ;GACR,SAAS;IACP,gBAAgB;IAChB,GAAI,QAAQ,EAAE,eAAe,UAAU,QAAQ,IAAI,CAAC;GACtD;GACA,MAAM,KAAK,UAAU,EACnB,OAAO,sDACT,CAAC;GACD,QAAQ,YAAY,QAAQ,SAAS;EACvC,CAAC;EACD,IAAI,CAAC,IAAI,IAAI,OAAO,KAAA;EAIpB,QAAO,MAHa,IAAI,KAAK,EAAA,CAGjB,MAAM,YAAY;CAChC,QAAQ;EACN;CACF;AACF;AAEA,eAAsB,oBACpB,SACkC;CAClC,MAAM,YAAY,QAAQ,aAAa;CACvC,MAAM,WAAW,sBAAsB,QAAQ,GAAG;CAElD,MAAM,QAAQ,QAAQ;CACtB,MAAM,gBACJ,QAAQ,kBACP,cAAc,QAAQ,QAA4B,KAAK,IAAI,KAAA;CAE9D,MAAM,cAAc,UAAU,SAAS;CACvC,MAAM,aAAa,MAAM,eAAe,UAAU,eAAe,SAAS;CAE1E,MAAM,EAAE,yBACN,MAAM,OAAO;CASf,OAAO;EAAE;EAAU,QAAA,IAFA,qBAAqB;GALtC,KAAK;GACL,gBAAgB,QAAQ;GACxB,GAAI,gBAAgB,EAAE,cAAc,IAAI,CAAC;GACzC,GAAI,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;EAED,CAE5B;EAAG;CAAW;AACxC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { F as Cli, bt as RunOptions } from "../types-
|
|
1
|
+
import { F as Cli, bt as RunOptions } from "../types-DbQKfvWc.mjs";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { RunnerArgsSchema, RunnerContext } from "@powerhousedao/host-core";
|
|
4
4
|
//#region src/runners/cli-runner.d.ts
|
|
@@ -299,6 +299,10 @@ export interface RunCliOptions {
|
|
|
299
299
|
signal?: AbortSignal;
|
|
300
300
|
/** The compound's other members (see `RunOptions.members`). */
|
|
301
301
|
members?: RunOptions["members"];
|
|
302
|
+
/** A running instance's control channel (see `RunOptions.remoteServices`). */
|
|
303
|
+
remoteServices?: RunOptions["remoteServices"];
|
|
304
|
+
/** How the Cli is started to keep running (see `RunOptions.serveCommand`). */
|
|
305
|
+
serveCommand?: string;
|
|
302
306
|
}
|
|
303
307
|
/**
|
|
304
308
|
* Runs `cli` in this process's terminal: its stdin, stdout and stderr, and
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli-runner.d.mts","names":[],"sources":["../../src/runners/cli-runner.ts"],"mappings":";;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"cli-runner.d.mts","names":[],"sources":["../../src/runners/cli-runner.ts"],"mappings":";;;;;;;;;;;;;;;;;;;qBA4Ca;;;qBAIA;;;qBAIA;;qBAGA,YAAY;;qBA8BZ,oBAAkB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAA6B,EAAA,KAAA;;qBAE/C,YAAU,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAAqB,EAAA,KAAA;;YAGhC,eAAe,EAAE,aAAa;;YAE9B,UAAU,EAAE,cAAc;QAE9B;YACI;IACR;MACE,MAAM;MACN,SAAS;;;;;;;;;wBAkEO,QACpB,qBACA,uBACC,QAAQ;;;;;;wBAkCW,WACpB,sBACC,QAAQ;iBAuCM;;EAEf;;;;EAIA;;EAEA;;;EAGA,aAAa,OAAO;;;EAGpB;;EAEA,uBAAuB;;EAEvB,SAAS;;EAET,UAAU;;EAEV,iBAAiB;;EAEjB;;;;;;;;;wBAUoB,OACpB,KAAK,KACL,SAAS,gBACR;;iBA+Hc;EACf,SAAS;EACT,OAAO;;EAEP,QAAQ;;;EAGR,YAAY;;;;;;;;wBA6EQ,IACpB,MAAM,SACN,KAAK,gBACJ,QAAQ;;;;;;;;;wBAuDW,MAAM,MAAM,SAAS,KAAK,gBAAgB"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { n as resolveRemoteReactorConfig, t as attachDefaultReactor } from "../powerhouse-
|
|
1
|
+
import { n as resolveRemoteReactorConfig, t as attachDefaultReactor } from "../powerhouse-3XZmdY3_.mjs";
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { pathToFileURL } from "node:url";
|
|
6
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";
|
|
7
|
+
import { STOP_ON_STDIN_ENV, STOP_STREAM_LIMIT_MS, clearRunRecord, controlRecordOf, ensureProcessControlChannel, probeRun, readProjectName, readRunRecord, runRecordKey, stopStreamOf, writeRunRecord } from "@powerhousedao/host-core";
|
|
8
8
|
import { defineHostSchemas } from "@powerhousedao/host-core/schema";
|
|
9
9
|
//#region src/runners/cli-runner.ts
|
|
10
10
|
/**
|
|
@@ -185,7 +185,9 @@ async function runCli(cli, options) {
|
|
|
185
185
|
...reactor ? { reactor } : {},
|
|
186
186
|
...options.onServe ? { onServe: options.onServe } : {},
|
|
187
187
|
...options.signal ? { signal: options.signal } : {},
|
|
188
|
-
...options.members ? { members: options.members } : {}
|
|
188
|
+
...options.members ? { members: options.members } : {},
|
|
189
|
+
...options.remoteServices ? { remoteServices: options.remoteServices } : {},
|
|
190
|
+
...options.serveCommand ? { serveCommand: options.serveCommand } : {}
|
|
189
191
|
});
|
|
190
192
|
} catch (error) {
|
|
191
193
|
console.error(error instanceof Error ? error.message : String(error));
|
|
@@ -198,14 +200,16 @@ async function runCli(cli, options) {
|
|
|
198
200
|
/**
|
|
199
201
|
* The record of a Cli that keeps running: what `ph run <host> --stop` reads.
|
|
200
202
|
* A one-shot writes none and takes no lock, so it runs beside a serving
|
|
201
|
-
* instance; a second serving instance is refused.
|
|
203
|
+
* instance; a second serving instance is refused. The record names the
|
|
204
|
+
* process's control channel, which the Cli answers service requests on.
|
|
202
205
|
*/
|
|
203
|
-
function recordServing(projectRoot, hostName, verb, hostPackage) {
|
|
206
|
+
async function recordServing(projectRoot, hostName, verb, hostPackage) {
|
|
204
207
|
const projectName = readProjectName(projectRoot);
|
|
205
208
|
const key = runRecordKey(hostName, hostPackage);
|
|
206
209
|
const probe = probeRun(projectRoot, key, projectName);
|
|
207
210
|
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
211
|
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.`);
|
|
212
|
+
const control = (await ensureProcessControlChannel())?.record;
|
|
209
213
|
writeRunRecord(projectRoot, {
|
|
210
214
|
version: 2,
|
|
211
215
|
host: hostName,
|
|
@@ -215,7 +219,8 @@ function recordServing(projectRoot, hostName, verb, hostPackage) {
|
|
|
215
219
|
verb,
|
|
216
220
|
pid: process.pid,
|
|
217
221
|
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
218
|
-
outputs: {}
|
|
222
|
+
outputs: {},
|
|
223
|
+
...control ? { extra: { control } } : {}
|
|
219
224
|
});
|
|
220
225
|
process.on("exit", () => {
|
|
221
226
|
if (readRunRecord(projectRoot, key)?.pid === process.pid) clearRunRecord(projectRoot, key);
|
|
@@ -257,9 +262,13 @@ function inStack(cli, host, ctx, url) {
|
|
|
257
262
|
workdir: ctx.projectRoot,
|
|
258
263
|
signal: stop.signal,
|
|
259
264
|
members: ctx.foreground.members,
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
265
|
+
serveCommand: `ph run ${ctx.foreground.stack ?? stack}`,
|
|
266
|
+
...ctx.foreground.beside ? {
|
|
267
|
+
...ctx.foreground.control ? { remoteServices: ctx.foreground.control } : {},
|
|
268
|
+
onServe: () => {
|
|
269
|
+
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.`);
|
|
270
|
+
}
|
|
271
|
+
} : {}
|
|
263
272
|
}).then(async (code) => {
|
|
264
273
|
await Promise.all([drained(process.stdout), drained(process.stderr)]);
|
|
265
274
|
return code;
|
|
@@ -291,11 +300,16 @@ async function run(host, ctx) {
|
|
|
291
300
|
foreground: ctx.foreground
|
|
292
301
|
}, url);
|
|
293
302
|
const stopStream = stopStreamOf(ctx.env, () => process.stdin);
|
|
303
|
+
const key = runRecordKey(host.name, ctx.hostPackage?.name);
|
|
304
|
+
const probe = probeRun(ctx.projectRoot, key, readProjectName(ctx.projectRoot));
|
|
305
|
+
const remoteServices = probe.status === "live" && probe.record.pid !== process.pid ? controlRecordOf(probe.record) : void 0;
|
|
294
306
|
const code = await runCli(cli, {
|
|
295
307
|
argv: ctx.argv ?? [],
|
|
296
308
|
...url ? { url } : {},
|
|
297
309
|
workdir: ctx.projectRoot,
|
|
298
310
|
...stopStream ? { stopStream } : {},
|
|
311
|
+
...remoteServices ? { remoteServices } : {},
|
|
312
|
+
serveCommand: `ph run ${key}`,
|
|
299
313
|
onServe: () => recordServing(ctx.projectRoot, host.name, ctx.verb, ctx.hostPackage?.name)
|
|
300
314
|
});
|
|
301
315
|
await Promise.all([drained(process.stdout), drained(process.stderr)]);
|
|
@@ -311,7 +325,7 @@ async function run(host, ctx) {
|
|
|
311
325
|
*/
|
|
312
326
|
async function build(host, ctx) {
|
|
313
327
|
const cli = await loadCli(ctx.projectRoot, host.config?.package);
|
|
314
|
-
const { buildSkills } = await import("../build-skills-
|
|
328
|
+
const { buildSkills } = await import("../build-skills-Bpbbnin0.mjs");
|
|
315
329
|
const result = await buildSkills({
|
|
316
330
|
rootDir: ctx.projectRoot,
|
|
317
331
|
cli
|
|
@@ -1 +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,MAA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MACR,SAAS,KAAK,KAAK,cAAc,IAAI,OAAO,KAAK,sIAAsI,KAAK,KAAK,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"}
|
|
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 controlRecordOf,\n ensureProcessControlChannel,\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 /** A running instance's control channel (see `RunOptions.remoteServices`). */\n remoteServices?: RunOptions[\"remoteServices\"];\n /** How the Cli is started to keep running (see `RunOptions.serveCommand`). */\n serveCommand?: string;\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 ...(options.remoteServices\n ? { remoteServices: options.remoteServices }\n : {}),\n ...(options.serveCommand ? { serveCommand: options.serveCommand } : {}),\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. The record names the\n * process's control channel, which the Cli answers service requests on.\n */\nasync function recordServing(\n projectRoot: string,\n hostName: string,\n verb: string,\n hostPackage?: string,\n): Promise<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 const control = (await ensureProcessControlChannel())?.record;\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 ...(control ? { extra: { control } } : {}),\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 serveCommand: `ph run ${ctx.foreground.stack ?? stack}`,\n ...(ctx.foreground.beside\n ? {\n ...(ctx.foreground.control\n ? { remoteServices: ctx.foreground.control }\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 // A command beside a serving instance of this host reaches its services.\n const key = runRecordKey(host.name, ctx.hostPackage?.name);\n const probe = probeRun(\n ctx.projectRoot,\n key,\n readProjectName(ctx.projectRoot),\n );\n const remoteServices =\n probe.status === \"live\" && probe.record.pid !== process.pid\n ? controlRecordOf(probe.record)\n : undefined;\n const code = await runCli(cli, {\n argv: ctx.argv ?? [],\n ...(url ? { url } : {}),\n workdir: ctx.projectRoot,\n ...(stopStream ? { stopStream } : {}),\n ...(remoteServices ? { remoteServices } : {}),\n serveCommand: `ph run ${key}`,\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":";;;;;;;;;;;;;;;;;;;;;;;;AA4CA,MAAa,OAAO;;;AAIpB,MAAa,aAAa;;;AAI1B,MAAa,QAAQ,CAAC,OAAO,OAAO;;AAGpC,MAAa,aAA+B;CAC1C,SAAS,CAAC;CACV,OAAO,CAAC;CACR,aAAa;AACf;;AAGA,MAAM,kBACJ;;;;;;AAOF,MAAM,UAAU,mBAAmB,MACjC,EAAE,kBAAkB,OAAO;CACzB,QAAQ,EAAE,iBAAiB,OAAO;CAClC,QAAQ,EACL,aAAa;;;;;AAKZ,SAAS,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,EACtC,CAAC,CAAC,CACD,SAAS;AACd,CAAC,CACH;;AAEA,MAAa,qBAAqB,QAAQ;;AAE1C,MAAa,aAAa,QAAQ;;;AAkBlC,SAAS,YAAY,MAAmC;CACtD,MAAM,WAAW,OAAO,QAAQ,KAAK,SAAS,YAAY,CAAC,CAAC;CAC5D,IAAI,SAAS,WAAW,GAAG,OAAO,KAAA;CAClC,MAAM,QAAQ,SAAS,MAAM,GAAG,aAAa,QAAQ,SAAS,QAAQ;CACtE,IAAI,OACF,MAAM,IAAI,MACR,SAAS,KAAK,KAAK,+DAA+D,MAAM,GAAG,QAAQ,MAAM,EAAE,CAAC,KAAK,iFAChC,gBAAgB,EACnG;CAEF,IAAI,SAAS,SAAS,GACpB,MA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KACA,gBAAgB,IAAI,WAAW,CACjC;CACA,MAAM,iBACJ,MAAM,WAAW,UAAU,MAAM,OAAO,QAAQ,QAAQ,MACpD,gBAAgB,MAAM,MAAM,IAC5B,KAAA;CACN,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,GAAI,iBAAiB,EAAE,eAAe,IAAI,CAAC;EAC3C,cAAc,UAAU;EACxB,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"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as attachRemoteReactor } from "../remote-reactor-
|
|
1
|
+
import { t as attachRemoteReactor } from "../remote-reactor-oBsHphPT.mjs";
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
import { randomUUID } from "node:crypto";
|
|
@@ -449,7 +449,7 @@ const serve = run;
|
|
|
449
449
|
*/
|
|
450
450
|
async function build(host, ctx) {
|
|
451
451
|
const config = host.config ?? {};
|
|
452
|
-
const { buildSkills } = await import("../build-skills-
|
|
452
|
+
const { buildSkills } = await import("../build-skills-Bpbbnin0.mjs");
|
|
453
453
|
const { loadOwnCli } = await import("./cli-runner.mjs");
|
|
454
454
|
const result = await buildSkills({
|
|
455
455
|
rootDir: ctx.projectRoot,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as slugToTitle, t as getSchemaFields } from "./schema-BEKAZGyT.mjs";
|
|
2
|
-
import { M as createDocumentChangeTrigger, N as defineCommand } from "./powerhouse-
|
|
2
|
+
import { M as createDocumentChangeTrigger, N as defineCommand } from "./powerhouse-3XZmdY3_.mjs";
|
|
3
3
|
import { a as getGhostSuggestion, b as supervisedSpawnOptions, d as watchLogFile, i as getCompletions, l as resolveServiceName, o as createServiceManager, p as scanProjects, r as getCompletionSuffix, s as defineService, t as renderMarkdown, u as sanitizeLogText, v as killTree, x as formatStreamChunk, y as superviseChild } from "./markdown-BUeGwhbR.mjs";
|
|
4
4
|
import { n as createWorkdirStore, t as createMemoryWorkdirStore } from "./store-CxqB-OrX.mjs";
|
|
5
5
|
import "./proxy-ji3EHzLn.mjs";
|
|
@@ -10,6 +10,7 @@ import { z } from "zod";
|
|
|
10
10
|
import { Command } from "commander";
|
|
11
11
|
import { randomBytes, randomUUID } from "node:crypto";
|
|
12
12
|
import { homedir } from "node:os";
|
|
13
|
+
import { ControlError, callControl, processControlChannel } from "@powerhousedao/host-core/control-channel";
|
|
13
14
|
import { spawn } from "node:child_process";
|
|
14
15
|
import Handlebars from "handlebars";
|
|
15
16
|
import { EventEmitter } from "node:events";
|
|
@@ -539,6 +540,145 @@ function generateConfigCommandHelp(cliName, configSchema, workdir, sensitiveKeys
|
|
|
539
540
|
return lines.join("\n");
|
|
540
541
|
}
|
|
541
542
|
//#endregion
|
|
543
|
+
//#region src/core/service-control.ts
|
|
544
|
+
/**
|
|
545
|
+
* A CLI's services over the control channel of the process that runs them.
|
|
546
|
+
* The process that keeps running answers `list`, `start`, `stop`, `restart`
|
|
547
|
+
* and `logs` ({@link serveServices}); a command typed in a second terminal
|
|
548
|
+
* reaches them through a manager that forwards ({@link connectRemoteServices}).
|
|
549
|
+
* A command with nothing to forward to cannot start a service at all
|
|
550
|
+
* ({@link refuseServiceStarts}): the service would end with the command.
|
|
551
|
+
*/
|
|
552
|
+
const startParamsSchema = z.object({
|
|
553
|
+
id: z.string().min(1),
|
|
554
|
+
options: z.object({
|
|
555
|
+
workdir: z.string().optional(),
|
|
556
|
+
cwd: z.string().optional(),
|
|
557
|
+
params: z.record(z.string(), z.unknown()).optional(),
|
|
558
|
+
name: z.string().optional()
|
|
559
|
+
}).optional()
|
|
560
|
+
});
|
|
561
|
+
const instanceParamsSchema = z.object({
|
|
562
|
+
id: z.string().min(1),
|
|
563
|
+
instanceId: z.string().optional()
|
|
564
|
+
});
|
|
565
|
+
const listParamsSchema = z.object({ serviceId: z.string().optional() });
|
|
566
|
+
const logsParamsSchema = instanceParamsSchema.extend({ lines: z.number().int().positive().optional() });
|
|
567
|
+
function parse(schema, params) {
|
|
568
|
+
const parsed = schema.safeParse(params ?? {});
|
|
569
|
+
if (!parsed.success) throw new Error(`Bad parameters: ${parsed.error.issues.map((i) => `${i.path.join(".") || "<root>"}: ${i.message}`).join("; ")}`);
|
|
570
|
+
return parsed.data;
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* Stops the service's running instance, if any, and starts it again where
|
|
574
|
+
* and as it ran. Resolves with the new instance's id.
|
|
575
|
+
*/
|
|
576
|
+
async function restartService(services, id, instanceId, workdir) {
|
|
577
|
+
const [instance] = services.list(id).filter((s) => s.status === "ready" || s.status === "starting");
|
|
578
|
+
let name;
|
|
579
|
+
if (instance) {
|
|
580
|
+
if (instance.instanceId?.includes(":")) name = instance.instanceId.split(":")[1];
|
|
581
|
+
await services.stop(id, instanceId);
|
|
582
|
+
}
|
|
583
|
+
const cwd = instance?.workdir ?? workdir;
|
|
584
|
+
return services.start(id, {
|
|
585
|
+
workdir: cwd,
|
|
586
|
+
cwd,
|
|
587
|
+
params: instance?.params,
|
|
588
|
+
name
|
|
589
|
+
});
|
|
590
|
+
}
|
|
591
|
+
/** Answers service requests on `channel` from `services`. */
|
|
592
|
+
function serveServices(channel, services, cli) {
|
|
593
|
+
channel.describe({
|
|
594
|
+
cli: cli.name,
|
|
595
|
+
version: cli.version
|
|
596
|
+
});
|
|
597
|
+
channel.handle("list", (params) => ({ instances: services.list(parse(listParamsSchema, params).serviceId) }));
|
|
598
|
+
channel.handle("start", async (params) => {
|
|
599
|
+
const { id, options } = parse(startParamsSchema, params);
|
|
600
|
+
return {
|
|
601
|
+
instanceId: await services.start(id, options),
|
|
602
|
+
instances: services.list()
|
|
603
|
+
};
|
|
604
|
+
});
|
|
605
|
+
channel.handle("stop", async (params) => {
|
|
606
|
+
const { id, instanceId } = parse(instanceParamsSchema, params);
|
|
607
|
+
await services.stop(id, instanceId);
|
|
608
|
+
return { instances: services.list() };
|
|
609
|
+
});
|
|
610
|
+
channel.handle("restart", async (params) => {
|
|
611
|
+
const { id, instanceId } = parse(instanceParamsSchema, params);
|
|
612
|
+
return {
|
|
613
|
+
instanceId: await restartService(services, id, instanceId, cli.workdir),
|
|
614
|
+
instances: services.list()
|
|
615
|
+
};
|
|
616
|
+
});
|
|
617
|
+
channel.handle("logs", (params) => {
|
|
618
|
+
const { id, instanceId, lines } = parse(logsParamsSchema, params);
|
|
619
|
+
return { text: services.logs(id, instanceId, lines) };
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
const instancesOf = (result) => result?.instances ?? [];
|
|
623
|
+
/**
|
|
624
|
+
* A manager whose instances live in the process behind `control`: start,
|
|
625
|
+
* stop and list act there; logs, definitions and scans are read here (the
|
|
626
|
+
* files are the same). Undefined when that process does not answer service
|
|
627
|
+
* requests.
|
|
628
|
+
*/
|
|
629
|
+
async function connectRemoteServices(local, control) {
|
|
630
|
+
let instances;
|
|
631
|
+
try {
|
|
632
|
+
const hello = await callControl(control, "hello", void 0, { timeoutMs: 5e3 });
|
|
633
|
+
const methods = Array.isArray(hello?.methods) ? hello.methods : [];
|
|
634
|
+
if (![
|
|
635
|
+
"list",
|
|
636
|
+
"start",
|
|
637
|
+
"stop"
|
|
638
|
+
].every((m) => methods.includes(m))) return;
|
|
639
|
+
instances = instancesOf(await callControl(control, "list"));
|
|
640
|
+
} catch (error) {
|
|
641
|
+
if (error instanceof ControlError) return void 0;
|
|
642
|
+
throw error;
|
|
643
|
+
}
|
|
644
|
+
return {
|
|
645
|
+
...local,
|
|
646
|
+
async start(id, opts) {
|
|
647
|
+
const result = await callControl(control, "start", {
|
|
648
|
+
id,
|
|
649
|
+
...opts ? { options: opts } : {}
|
|
650
|
+
});
|
|
651
|
+
instances = instancesOf(result);
|
|
652
|
+
return result.instanceId;
|
|
653
|
+
},
|
|
654
|
+
async stop(id, instanceId) {
|
|
655
|
+
instances = instancesOf(await callControl(control, "stop", {
|
|
656
|
+
id,
|
|
657
|
+
...instanceId ? { instanceId } : {}
|
|
658
|
+
}));
|
|
659
|
+
},
|
|
660
|
+
stopAll: () => local.stopAll(),
|
|
661
|
+
list: (serviceId) => serviceId ? instances.filter((s) => s.serviceId === serviceId) : [...instances]
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
/** Thrown by a start that cannot outlive its command. */
|
|
665
|
+
var ServiceStartRefused = class extends Error {
|
|
666
|
+
constructor(id, serveCommand) {
|
|
667
|
+
super(`${id} was not started: a service runs as long as the process that started it, and this command ends. Start it where it keeps running: ${serveCommand ? `\`${serveCommand}\`` : "`ph run <host>`"}, then run this command from a second terminal.`);
|
|
668
|
+
this.name = "ServiceStartRefused";
|
|
669
|
+
}
|
|
670
|
+
};
|
|
671
|
+
/**
|
|
672
|
+
* The manager of a command that ends with nothing running to forward to:
|
|
673
|
+
* everything but `start`, which is refused with where to run instead.
|
|
674
|
+
*/
|
|
675
|
+
function refuseServiceStarts(local, serveCommand) {
|
|
676
|
+
return {
|
|
677
|
+
...local,
|
|
678
|
+
start: (id) => Promise.reject(new ServiceStartRefused(id, serveCommand))
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
//#endregion
|
|
542
682
|
//#region src/core/service-command.ts
|
|
543
683
|
/**
|
|
544
684
|
* Format a service instance status line for display.
|
|
@@ -609,6 +749,7 @@ function createServiceCommands(def) {
|
|
|
609
749
|
});
|
|
610
750
|
return { text: formatStatus(services.list(id).find((s) => s.instanceId === instanceId)) };
|
|
611
751
|
} catch (err) {
|
|
752
|
+
if (err instanceof ServiceStartRefused) throw err;
|
|
612
753
|
const msg = err instanceof Error ? err.message : String(err);
|
|
613
754
|
return { text: `✗ ${id}: ${msg}` };
|
|
614
755
|
}
|
|
@@ -640,26 +781,10 @@ function createServiceCommands(def) {
|
|
|
640
781
|
const services = context.services;
|
|
641
782
|
if (!services) throw new Error("No services configured");
|
|
642
783
|
try {
|
|
643
|
-
const
|
|
644
|
-
let prevWorkdir;
|
|
645
|
-
let prevParams;
|
|
646
|
-
let prevName;
|
|
647
|
-
if (running.length > 0) {
|
|
648
|
-
const instance = running[0];
|
|
649
|
-
prevWorkdir = instance.workdir;
|
|
650
|
-
prevParams = instance.params;
|
|
651
|
-
if (instance.instanceId?.includes(":")) prevName = instance.instanceId.split(":")[1];
|
|
652
|
-
await services.stop(id, input.instance);
|
|
653
|
-
}
|
|
654
|
-
const cwd = prevWorkdir ?? context.workdir;
|
|
655
|
-
const instanceId = await services.start(id, {
|
|
656
|
-
workdir: cwd,
|
|
657
|
-
cwd,
|
|
658
|
-
params: prevParams,
|
|
659
|
-
name: prevName
|
|
660
|
-
});
|
|
784
|
+
const instanceId = await restartService(services, id, input.instance, context.workdir);
|
|
661
785
|
return { text: formatStatus(services.list(id).find((s) => s.instanceId === instanceId)) };
|
|
662
786
|
} catch (err) {
|
|
787
|
+
if (err instanceof ServiceStartRefused) throw err;
|
|
663
788
|
const msg = err instanceof Error ? err.message : String(err);
|
|
664
789
|
return { text: `✗ ${id}: ${msg}` };
|
|
665
790
|
}
|
|
@@ -2322,7 +2447,7 @@ function createCliRuntime(deps) {
|
|
|
2322
2447
|
await getReactor();
|
|
2323
2448
|
output(`Reactor ready (drive: ${cachedReactor.driveId})`);
|
|
2324
2449
|
if (cachedReactor.personalDriveId) {
|
|
2325
|
-
const { createFolderOperations, createFolderCommands } = await import("./powerhouse-
|
|
2450
|
+
const { createFolderOperations, createFolderCommands } = await import("./powerhouse-3XZmdY3_.mjs").then((n) => n.S);
|
|
2326
2451
|
const folderOps = createFolderOperations(cachedReactor.client, cachedReactor.personalDriveId, log);
|
|
2327
2452
|
context.folders = folderOps;
|
|
2328
2453
|
const folderCmds = createFolderCommands(folderOps);
|
|
@@ -3037,7 +3162,9 @@ function defineCli(options) {
|
|
|
3037
3162
|
reactor: runOptions?.reactor,
|
|
3038
3163
|
onServe: runOptions?.onServe,
|
|
3039
3164
|
signal: runOptions?.signal,
|
|
3040
|
-
members: runOptions?.members
|
|
3165
|
+
members: runOptions?.members,
|
|
3166
|
+
remoteServices: runOptions?.remoteServices,
|
|
3167
|
+
serveCommand: runOptions?.serveCommand
|
|
3041
3168
|
});
|
|
3042
3169
|
}
|
|
3043
3170
|
/**
|
|
@@ -3228,6 +3355,11 @@ function defineCli(options) {
|
|
|
3228
3355
|
const mode = !interactiveFlag ? "headless" : isTTY ? "interactive-terminal" : "interactive-streaming";
|
|
3229
3356
|
const hasKeepAlive = !!effectiveRoutine;
|
|
3230
3357
|
if (isBuiltinFlag || !interactiveFlag && (isSubcommand || hasPrompt)) {
|
|
3358
|
+
if (context.services && isSubcommand && !isBuiltinFlag) {
|
|
3359
|
+
const local = context.services;
|
|
3360
|
+
context.services = (opts.remoteServices ? await connectRemoteServices(local, opts.remoteServices) : void 0) ?? refuseServiceStarts(local, opts.serveCommand);
|
|
3361
|
+
}
|
|
3362
|
+
if (opts.remoteServices && !isBuiltinFlag) context.serving = opts.remoteServices;
|
|
3231
3363
|
if (hasPrompt) {
|
|
3232
3364
|
const agentProvider = await runtime.getAgent();
|
|
3233
3365
|
if (agentProvider) {
|
|
@@ -3269,6 +3401,12 @@ function defineCli(options) {
|
|
|
3269
3401
|
exit(1);
|
|
3270
3402
|
return;
|
|
3271
3403
|
}
|
|
3404
|
+
const control = processControlChannel();
|
|
3405
|
+
if (control && context.services) serveServices(control, context.services, {
|
|
3406
|
+
name: options.name,
|
|
3407
|
+
version: options.version,
|
|
3408
|
+
workdir
|
|
3409
|
+
});
|
|
3272
3410
|
let session;
|
|
3273
3411
|
if (interactiveFlag) {
|
|
3274
3412
|
if (!options.interactive) {
|
|
@@ -3676,6 +3814,6 @@ async function getProjectMapping(scanResults, folders) {
|
|
|
3676
3814
|
return mappings;
|
|
3677
3815
|
}
|
|
3678
3816
|
//#endregion
|
|
3679
|
-
export {
|
|
3817
|
+
export { restartService as A, userConfigPath as B, installSkills as C, ServiceStartRefused as D, formatStatus as E, configKeyToEnvVar as F, createLogger as H, getMissingRequiredFields as I, localConfigPath as L, createConfigCommand as M, generateConfigCommandHelp as N, connectRemoteServices as O, resolveWorkdir as P, resolveConfig as R, readSkills as S, createServiceCommands as T, formatZodError as U, userStoreFolder as V, readPackageInfo as W, createSkillCommands as _, initLifecycle as a, registerDefaultHelpers as b, tokenizeArgs as c, createRoutine as d, IDENTITY_WRAPS as f, DEFAULT_SKILL_INSTRUCTION as g, createEventBus as h, defineCli as i, serveServices as j, refuseServiceStarts as k, createCompositeServiceManager as l, createProcessManager as m, createTypes as n, createReplSession as o, composeWraps as p, defineTrigger as r, parseReplInput as s, getProjectMapping as t, createRoutineServiceAdapter as u, isSkillInvocation as v, createHelpCommand as w, renderSkillTemplate as x, extractTemplateVars as y, toUpperSnake as z };
|
|
3680
3818
|
|
|
3681
|
-
//# sourceMappingURL=src-
|
|
3819
|
+
//# sourceMappingURL=src-BmMd0Wl4.mjs.map
|