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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +661 -0
  2. package/dist/build-skills-Cfj0OGnW.mjs +293 -0
  3. package/dist/build-skills-Cfj0OGnW.mjs.map +1 -0
  4. package/dist/dist-CUltriBW.mjs +1628 -0
  5. package/dist/dist-CUltriBW.mjs.map +1 -0
  6. package/dist/drive-BEshRPDR.mjs +84 -0
  7. package/dist/drive-BEshRPDR.mjs.map +1 -0
  8. package/dist/esm-C1DOsF1a.mjs +13140 -0
  9. package/dist/esm-C1DOsF1a.mjs.map +1 -0
  10. package/dist/events-BnwGFTjv.mjs +237 -0
  11. package/dist/events-BnwGFTjv.mjs.map +1 -0
  12. package/dist/folders-C-pFsTXT.mjs +256 -0
  13. package/dist/folders-C-pFsTXT.mjs.map +1 -0
  14. package/dist/index.d.mts +1005 -0
  15. package/dist/index.d.mts.map +1 -0
  16. package/dist/index.mjs +8 -0
  17. package/dist/local-signer-EFzJV3bn.mjs +128 -0
  18. package/dist/local-signer-EFzJV3bn.mjs.map +1 -0
  19. package/dist/markdown-D-sP2zw_.mjs +275 -0
  20. package/dist/markdown-D-sP2zw_.mjs.map +1 -0
  21. package/dist/proxy-BFR8GScT.mjs +302 -0
  22. package/dist/proxy-BFR8GScT.mjs.map +1 -0
  23. package/dist/proxy-routes-DP3ztsnS.mjs +215 -0
  24. package/dist/proxy-routes-DP3ztsnS.mjs.map +1 -0
  25. package/dist/reactor-C9VIUX1H.mjs +51 -0
  26. package/dist/reactor-C9VIUX1H.mjs.map +1 -0
  27. package/dist/rolldown-runtime-8H4AJuhK.mjs +14 -0
  28. package/dist/runners/clint-runner.d.mts +398 -0
  29. package/dist/runners/clint-runner.d.mts.map +1 -0
  30. package/dist/runners/clint-runner.mjs +522 -0
  31. package/dist/runners/clint-runner.mjs.map +1 -0
  32. package/dist/runners/mastra-runner.d.mts +300 -0
  33. package/dist/runners/mastra-runner.d.mts.map +1 -0
  34. package/dist/runners/mastra-runner.mjs +516 -0
  35. package/dist/runners/mastra-runner.mjs.map +1 -0
  36. package/dist/services-9E-r0nWl.mjs +999 -0
  37. package/dist/services-9E-r0nWl.mjs.map +1 -0
  38. package/dist/src-DD8PWpD5.mjs +4767 -0
  39. package/dist/src-DD8PWpD5.mjs.map +1 -0
  40. package/dist/start-b7Mn2cxB.mjs +1526 -0
  41. package/dist/start-b7Mn2cxB.mjs.map +1 -0
  42. package/dist/stdin-BjAO9gPK.mjs +17 -0
  43. package/dist/stdin-BjAO9gPK.mjs.map +1 -0
  44. package/dist/stream-DVuufwIj.mjs +148 -0
  45. package/dist/stream-DVuufwIj.mjs.map +1 -0
  46. package/dist/subscriptions-CfiflAsI.mjs +38 -0
  47. package/dist/subscriptions-CfiflAsI.mjs.map +1 -0
  48. package/dist/switchboard-CyvOavqL.mjs +57 -0
  49. package/dist/switchboard-CyvOavqL.mjs.map +1 -0
  50. package/dist/types-CRkoD-Mm.d.mts +1770 -0
  51. package/dist/types-CRkoD-Mm.d.mts.map +1 -0
  52. package/package.json +102 -3
  53. package/README.md +0 -3
@@ -0,0 +1,522 @@
1
+ import { d as isPortFree, n as defineService, t as createServiceManager } from "../services-9E-r0nWl.mjs";
2
+ import { r as formatStatus, t as createEventBus } from "../events-BnwGFTjv.mjs";
3
+ import { createRequire } from "node:module";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { pathToFileURL } from "node:url";
7
+ import { z } from "zod";
8
+ import { createInterface } from "node:readline";
9
+ import { compoundOutputSource, defaultUserDataDir, loadHost, loadProducers, outputRefsOf, outputSitesOf, planCompound, probeRun, processResolveEnv, refineStartOrder, resolveHostOutputs, resolveHostPlugins, runObserveHook, runObserveHookSequential, runRecordOutputSource } from "@powerhousedao/host-core";
10
+ import { defineHostSchemas, ref } from "@powerhousedao/host-core/schema";
11
+ //#region src/runners/removed-forms.ts
12
+ /**
13
+ * Output tokens (typed-host-configs T3) replaced the sibling-host reference
14
+ * forms the clint runners used to resolve themselves. A removed key is not
15
+ * just "unrecognized": its error names the token form that replaces it.
16
+ * Pass the result as a strict object's `error` option.
17
+ */
18
+ function removedKeyError(key, hint) {
19
+ return (issue) => {
20
+ if (issue.code !== "unrecognized_keys" || !issue.keys.includes(key)) return;
21
+ return `\`${key}\` was removed; ${hint(typeof issue.input === "object" && issue.input !== null ? issue.input : {})}`;
22
+ };
23
+ }
24
+ /** A quoted host name from a removed reference, or a placeholder. */
25
+ function quotedHost(value, placeholder) {
26
+ return typeof value === "string" && value.length > 0 ? JSON.stringify(value) : placeholder;
27
+ }
28
+ //#endregion
29
+ //#region src/runners/proxy-plugin.ts
30
+ /**
31
+ * R5 — the clint proxy as a COMPOUND plugin (rewire plan: appliesTo
32
+ * "compound", the member-set branch of the hierarchy). One front port routes
33
+ * to upstream URLs, WebSocket-aware. A route to a member names that member
34
+ * host's own output (e.g. `{ $output: { host: "assistant", path: ["origin"] } }`),
35
+ * resolved before the runner sees the config — the proxy never derives an
36
+ * address from a declared port. Declarative veneer over the clint package's
37
+ * createProxyServer; the route table assembly is pure
38
+ * (buildProxyRouteTable) and unit-tested without sockets.
39
+ */
40
+ /** The token form that replaced a route's `member` reference. */
41
+ function memberHint(input) {
42
+ return `point \`upstream\` at the member host's output: upstream: <host>.origin from ../<host>/outputs.js, or { $output: { host: "<member's host>"${typeof input.member === "string" && input.member.length > 0 ? `, member: ${JSON.stringify(input.member)}` : ""}, path: ["origin"] } }.`;
43
+ }
44
+ /** The proxy config, built once per form: `url` is the upstream field —
45
+ * `ref(z.url())` when declared, `z.url()` when resolved. */
46
+ function buildProxyPluginConfigSchema(url) {
47
+ /** One route: an upstream URL (literal or output token) plus optional
48
+ * path + ws. */
49
+ const proxyRouteSchema = z.strictObject({
50
+ upstream: url,
51
+ path: z.string().optional(),
52
+ ws: z.boolean().optional()
53
+ }, { error: removedKeyError("member", memberHint) });
54
+ return z.strictObject({
55
+ /** Front port (0 = any free port). */
56
+ port: z.number().int().min(0),
57
+ /** Bind address (default "0.0.0.0"). */
58
+ host: z.string().min(1).optional(),
59
+ publicUrl: z.url().optional(),
60
+ /** Route prefix -> target. */
61
+ routes: z.record(z.string(), proxyRouteSchema)
62
+ });
63
+ }
64
+ /** `runner.proxy` on a clint-runner host, resolved (what the runner reads). */
65
+ const proxyPluginConfigSchema = buildProxyPluginConfigSchema(z.url());
66
+ /** `runner.proxy` as declared: upstreams may be output tokens. */
67
+ const declaredProxyPluginConfigSchema = buildProxyPluginConfigSchema(ref(z.url()));
68
+ /** Pure route-table assembly: each upstream (+ optional path). */
69
+ function buildProxyRouteTable(config) {
70
+ return Object.entries(config.routes).map(([prefix, route]) => ({
71
+ prefix,
72
+ upstream: `${route.upstream.replace(/\/+$/, "")}${route.path ?? ""}`,
73
+ ws: route.ws ?? false,
74
+ source: `upstream:${route.upstream}`
75
+ }));
76
+ }
77
+ function createProxyPlugin(config) {
78
+ return {
79
+ name: "clint-proxy",
80
+ appliesTo: "compound",
81
+ hooks: {
82
+ onMembersReady: async (ctx) => {
83
+ const table = buildProxyRouteTable(config);
84
+ ctx.proxyRoutes = table;
85
+ const { createProxyServer } = await import("../proxy-BFR8GScT.mjs").then((n) => n.n);
86
+ const instance = await createProxyServer({
87
+ port: config.port,
88
+ host: config.host ?? "0.0.0.0",
89
+ publicUrl: config.publicUrl,
90
+ logger: ctx.logger ?? console
91
+ });
92
+ for (const route of table) instance.addRoute({
93
+ prefix: route.prefix,
94
+ upstream: new URL(route.upstream),
95
+ ws: route.ws,
96
+ source: route.source
97
+ });
98
+ ctx.proxyUrl = instance.url;
99
+ ctx.proxyStop = () => instance.stop();
100
+ ctx.logger?.info(`[clint-proxy] listening on ${instance.url} — ${table.length} route(s)`);
101
+ },
102
+ onShutdown: async (ctx) => {
103
+ await ctx.proxyStop?.();
104
+ }
105
+ }
106
+ };
107
+ }
108
+ //#endregion
109
+ //#region src/runners/member-records.ts
110
+ /** How often {@link awaitRunRecord} re-reads a member's run record. */
111
+ const RECORD_POLL_MS = 100;
112
+ /**
113
+ * Waits for a started member's LIVE run record. A member counts as up when
114
+ * its stdout matches the readiness pattern, but `ph run` writes the member's
115
+ * run record only after the runner's `ready` resolves, so a reader that
116
+ * looks right after the readiness line can find none. Polls until the
117
+ * record is live, the member's service fails or stops, or `timeout` passes;
118
+ * then throws naming the member, its record, the timeout and its readers.
119
+ * An earlier run's stale record does not count: it is waited past.
120
+ */
121
+ async function awaitRunRecord(projectRoot, projectName, consumer, wait, pollMs = RECORD_POLL_MS) {
122
+ const deadline = Date.now() + wait.timeout;
123
+ for (;;) {
124
+ if (probeRun(projectRoot, wait.host, projectName).status === "live") return;
125
+ const status = wait.status?.();
126
+ const gone = status === "failed" || status === "stopped";
127
+ if (gone || Date.now() >= deadline) {
128
+ const why = gone ? `${status} before publishing its live run record` : `published no live run record within ${wait.timeout} ms (children.${wait.id}.config.readiness.timeout)`;
129
+ throw new Error(`hosts/${consumer}/host.js: member "${wait.id}" is up (its readiness line matched) but ${why} (.ph/run/${wait.host}.json); ${wait.readers.join(", ")} read its outputs.`);
130
+ }
131
+ await new Promise((resolve) => setTimeout(resolve, Math.min(pollMs, Math.max(0, deadline - Date.now()))));
132
+ }
133
+ }
134
+ //#endregion
135
+ //#region src/runners/clint-runner.ts
136
+ /**
137
+ * clint-runner (P5.4): the clint shell as a compound runner. Each member
138
+ * runs as `ph-cli run <member>` in its own process, scheduled by the ported
139
+ * services manager; `lifecycle: "detached"` (default) leaves members running
140
+ * and re-attaches next run, `"attached"` tears them down. `config.agents`
141
+ * maps names to OpenAI-compatible endpoints (a literal, or a member's
142
+ * `endpoints.openai` token resolved once it is up). `dev` adds a line chat
143
+ * loop against the first agent; the ink REPL stays the library path.
144
+ */
145
+ const kind = "compound";
146
+ /** The token form that replaced an agent's sibling `host` reference. */
147
+ function agentHostHint(input) {
148
+ return `use url: <host>.endpoints.openai from ../<host>/outputs.js, or { url: { $output: { host: ${quotedHost(input.host, "\"<agent host>\"")}, path: ["endpoints", "openai"] } } }.`;
149
+ }
150
+ /** An agent the shell can chat with: the OpenAI-compatible base URL of an
151
+ * agent API (an agent host's `endpoints.openai` output, or external). */
152
+ function agentRefSchema(url) {
153
+ return z.strictObject({ url }, { error: removedKeyError("host", agentHostHint) });
154
+ }
155
+ /**
156
+ * The clint compound host, from one definition in two forms: DECLARED (what
157
+ * host.js authors write) and RESOLVED (what `validateHost` checks).
158
+ *
159
+ * `config.agents.*.url` and `runner.proxy.routes.*.upstream` are DEFERRED
160
+ * self fields: they typically name outputs of this compound's own members,
161
+ * which exist only once clint has started them inside the verb. They take
162
+ * tokens in BOTH forms (`ref`, not `s.tokenable`), and the runner resolves
163
+ * them after its members are up, then parses them with `ownFieldsSchema`.
164
+ */
165
+ const schemas = defineHostSchemas((base) => {
166
+ /** clint-runner's own `runner` options, on top of the common base. */
167
+ const clintRunnerOptionsSchema = base.runnerBaseSchema.extend({
168
+ /** "detached" (default): children outlive the shell and are
169
+ * re-attached on the next run. "attached": the shell tears them down
170
+ * on exit. */
171
+ lifecycle: z.enum(["attached", "detached"]).optional(),
172
+ /** One front port routing to upstreams (the clint proxy plugin). */
173
+ proxy: declaredProxyPluginConfigSchema.optional()
174
+ }).strict();
175
+ /** A member's scheduling knobs. Members run as their own `ph-cli run
176
+ * <host>` process, so the wrapper's `config` is read by clint (not passed
177
+ * to the member) and holds only these. */
178
+ const clintMemberConfigSchema = z.strictObject({
179
+ /** When the member counts as up: a stdout pattern (regex source, case
180
+ * insensitive) and a timeout in ms. */
181
+ readiness: z.strictObject({
182
+ pattern: z.string().min(1).optional(),
183
+ timeout: z.number().int().positive().optional()
184
+ }).optional() });
185
+ const cliHostConfigSchema = z.strictObject({
186
+ agents: z.record(z.string(), agentRefSchema(ref(z.url()))).optional(),
187
+ /** Member start order; must name declared children. Unnamed members
188
+ * start after the named ones, in declaration order. */
189
+ startOrder: z.array(z.string().min(1)).optional()
190
+ });
191
+ return base.compoundHostSchema.extend({
192
+ runner: clintRunnerOptionsSchema,
193
+ children: z.record(z.string(), base.childWrapperSchema.extend({ config: clintMemberConfigSchema.optional() })),
194
+ config: cliHostConfigSchema.optional()
195
+ }).superRefine(refineStartOrder);
196
+ });
197
+ /** Declared form: what a host file may contain before resolution. */
198
+ const declaredHostSchema = schemas.declaredHostSchema;
199
+ /** Resolved form: what `validateHost` checks and the verbs receive (the
200
+ * deferred self fields may still carry tokens; see above). */
201
+ const hostSchema = schemas.hostSchema;
202
+ /** The deferred self fields once resolved (after member start). */
203
+ const ownFieldsSchema = z.strictObject({
204
+ agents: z.record(z.string(), agentRefSchema(z.url())).optional(),
205
+ proxy: proxyPluginConfigSchema.optional()
206
+ });
207
+ /** The verbs this runner exports (the rest of its exports are not verbs). */
208
+ const verbs = [
209
+ "run",
210
+ "serve",
211
+ "dev",
212
+ "build"
213
+ ];
214
+ /**
215
+ * Resolve the shell's own tokens before any member starts: `$env`, the
216
+ * built-ins and other hosts' outputs now (an unset variable or a producer
217
+ * that is not running fails with nothing started); tokens naming its own
218
+ * members' outputs are deferred until those members are up (`finish`).
219
+ * `children` stay as declared: each member resolves its own.
220
+ */
221
+ async function resolveOwnTokens(host, ctx, projectName) {
222
+ const members = Object.entries(host.children).map(([key, wrapper]) => ({
223
+ key,
224
+ host: wrapper.host
225
+ }));
226
+ const foreign = outputRefsOf({
227
+ ...host,
228
+ children: {}
229
+ }).filter((ref) => !members.some((member) => member.host === ref.host));
230
+ return resolveHostOutputs(host, {
231
+ outputs: runRecordOutputSource(ctx.projectRoot, {
232
+ consumer: host.name,
233
+ producers: await loadProducers(ctx.projectRoot, foreign),
234
+ projectName
235
+ }),
236
+ ...processResolveEnv(ctx.projectRoot, ctx.env),
237
+ where: `hosts/${host.name}/host.js`
238
+ }, { deferSelf: { members } });
239
+ }
240
+ /** Finish the deferred self tokens from the members' live run records. */
241
+ function finishOwnTokens(pending, live, name) {
242
+ const started = /* @__PURE__ */ new Map();
243
+ for (const [key, member] of Object.entries(live)) if (member.outputs !== void 0) started.set(key, member.outputs);
244
+ const silent = pending.needs.filter((key) => !started.has(key));
245
+ if (silent.length > 0) {
246
+ const paths = pending.deferred.filter((d) => d.members.some((key) => silent.includes(key))).map((d) => d.path);
247
+ throw new Error(`hosts/${name}/host.js: ${paths.join(", ")} read the outputs of member ${silent.map((key) => `"${key}"`).join(", ")}, which is up but published no live run record (.ph/run/<host>.json) to read them from.`);
248
+ }
249
+ const members = Object.entries(pending.host.children).map(([key, wrapper]) => ({
250
+ key,
251
+ host: wrapper.host
252
+ }));
253
+ return pending.finish(compoundOutputSource(members, started, name));
254
+ }
255
+ /** Started members' outputs, read from their own run records (members run
256
+ * as separate `ph-cli run` processes, which publish their outputs there). */
257
+ function liveMemberOutputs(projectRoot, projectName, memberHosts) {
258
+ const members = {};
259
+ for (const [id, hostName] of Object.entries(memberHosts)) {
260
+ const probe = probeRun(projectRoot, hostName, projectName);
261
+ members[id] = {
262
+ host: hostName,
263
+ outputs: probe.status === "live" ? probe.record.outputs : void 0
264
+ };
265
+ }
266
+ return members;
267
+ }
268
+ /** What starting the shell produces: the resolved agent endpoints and, when
269
+ * `runner.proxy` is set, the proxy's URL. Member outputs belong to the
270
+ * members. */
271
+ const outputsSchema = z.strictObject({
272
+ agents: z.record(z.string(), z.url()),
273
+ proxy: z.strictObject({ url: z.url() }).optional()
274
+ });
275
+ const DEFAULT_READINESS = "https?://|listening|ready";
276
+ /** How long a member may take to print its readiness line, in ms; also how
277
+ * long clint then waits for its run record when something reads it. */
278
+ const READINESS_TIMEOUT = 18e4;
279
+ /** Resolve the project's ph-cli entry the same way host-core resolves runner
280
+ * modules: from the PROJECT's dependency tree. */
281
+ function resolvePhCliEntry(projectRoot) {
282
+ const pkgPath = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href).resolve("@powerhousedao/ph-cli/package.json");
283
+ return path.join(path.dirname(pkgPath), "dist", "cli.mjs");
284
+ }
285
+ function childServices(host, ctx, phCliEntry) {
286
+ return Object.entries(host.children).map(([name, wrapper]) => defineService({
287
+ id: name,
288
+ name,
289
+ command: () => `node "${phCliEntry}" run ${wrapper.host}`,
290
+ env: () => ({
291
+ FEATURE_UNIFORM_RUNNERS_ENABLED: "1",
292
+ PH_USER_DATA_DIR: defaultUserDataDir(ctx.projectRoot, ctx.env)
293
+ }),
294
+ readiness: {
295
+ patterns: [{
296
+ name: "up",
297
+ pattern: new RegExp(wrapper.config?.readiness?.pattern ?? DEFAULT_READINESS, "i")
298
+ }],
299
+ timeout: wrapper.config?.readiness?.timeout ?? READINESS_TIMEOUT
300
+ }
301
+ }));
302
+ }
303
+ function readProjectName(projectRoot, fallback) {
304
+ try {
305
+ return JSON.parse(fs.readFileSync(path.join(projectRoot, "package.json"), "utf8")).name ?? fallback;
306
+ } catch {
307
+ return fallback;
308
+ }
309
+ }
310
+ async function stopAll(services, names) {
311
+ for (const id of names) try {
312
+ await services.stop(id);
313
+ } catch {}
314
+ }
315
+ async function startShell(host, ctx) {
316
+ const projectName = readProjectName(ctx.projectRoot, host.name);
317
+ const pending = await resolveOwnTokens(host, ctx, projectName);
318
+ const resolved = pending.host;
319
+ const config = resolved.config ?? {};
320
+ const lifecycle = resolved.runner.lifecycle ?? "detached";
321
+ const phCliEntry = resolvePhCliEntry(ctx.projectRoot);
322
+ const children = resolved.children;
323
+ const definitions = childServices(resolved, ctx, phCliEntry);
324
+ const eventBus = createEventBus();
325
+ const servicesDir = path.join(ctx.projectRoot, ".ph", "services");
326
+ const services = createServiceManager(definitions, {
327
+ config: {},
328
+ servicesDir,
329
+ eventBus
330
+ });
331
+ const names = definitions.map((d) => d.id);
332
+ const loaded = /* @__PURE__ */ new Map();
333
+ for (const id of names) loaded.set(id, await loadHost(ctx.projectRoot, children[id].host));
334
+ const memberRefs = names.map((key) => ({
335
+ key,
336
+ host: children[key].host
337
+ }));
338
+ const plan = planCompound(names.map((key) => ({
339
+ key,
340
+ host: children[key].host,
341
+ refs: outputSitesOf(loaded.get(key)?.host).filter(({ ref }) => memberRefs.some((m) => m.host === ref.host)).map(({ ref, path }) => ({
342
+ ref,
343
+ path
344
+ }))
345
+ })), config.startOrder);
346
+ const ordered = plan.order;
347
+ const readers = /* @__PURE__ */ new Map();
348
+ const addReader = (id, reader) => readers.set(id, [...readers.get(id) ?? [], reader]);
349
+ for (const deferred of pending.deferred) for (const id of deferred.members) addReader(id, deferred.path);
350
+ for (const edge of plan.edges) addReader(edge.producer, `member "${edge.consumer}"`);
351
+ /** Wait for a member's live run record when something reads it. With
352
+ * `managed` (clint's own service state describes it), a failed or stopped
353
+ * service ends the wait early; a member found serving on its port is not
354
+ * clint's to watch, so it gets the full timeout. */
355
+ const waitForRecord = async (id, memberHost, managed = true) => {
356
+ const read = readers.get(id);
357
+ if (!read) return;
358
+ try {
359
+ await awaitRunRecord(ctx.projectRoot, projectName, host.name, {
360
+ id,
361
+ host: memberHost,
362
+ timeout: children[id].config?.readiness?.timeout ?? READINESS_TIMEOUT,
363
+ readers: read,
364
+ ...managed ? { status: () => services.list(id).find((s) => s.serviceId === id)?.status } : {}
365
+ });
366
+ } catch (error) {
367
+ if (lifecycle === "attached") await stopAll(services, names);
368
+ throw error;
369
+ }
370
+ };
371
+ const memberHosts = {};
372
+ for (const id of ordered) {
373
+ const wrapper = children[id];
374
+ const member = loaded.get(id) ?? await loadHost(ctx.projectRoot, wrapper.host);
375
+ memberHosts[id] = member.host.name;
376
+ const record = probeRun(ctx.projectRoot, member.host.name, projectName);
377
+ if (record.status === "live") {
378
+ console.log(`[${resolved.name}] ${id}: already running (pid ${record.record.pid}) — re-attached`);
379
+ continue;
380
+ }
381
+ const memberPort = typeof wrapper.runner?.port === "number" ? wrapper.runner.port : typeof member.host.runner.port === "number" ? member.host.runner.port : void 0;
382
+ if (memberPort !== void 0 && !await isPortFree(memberPort)) {
383
+ console.log(`[${resolved.name}] ${id}: port ${memberPort} already serving — re-attached`);
384
+ await waitForRecord(id, member.host.name, false);
385
+ continue;
386
+ }
387
+ if (services.list(id).some((s) => s.status === "ready" || s.status === "starting")) {
388
+ console.log(`[${resolved.name}] ${id}: already running — re-attached`);
389
+ await waitForRecord(id, member.host.name);
390
+ continue;
391
+ }
392
+ console.log(`[${resolved.name}] starting ${id}…`);
393
+ await services.start(id, {
394
+ workdir: ctx.projectRoot,
395
+ cwd: ctx.projectRoot
396
+ });
397
+ const status = services.list(id).find((s) => s.serviceId === id);
398
+ if (status) console.log(` ${formatStatus(status)}`);
399
+ await waitForRecord(id, member.host.name);
400
+ }
401
+ let own;
402
+ try {
403
+ const finished = finishOwnTokens(pending, liveMemberOutputs(ctx.projectRoot, projectName, memberHosts), host.name);
404
+ const parsedOwn = ownFieldsSchema.safeParse({
405
+ agents: finished.config?.agents,
406
+ proxy: finished.runner.proxy
407
+ });
408
+ if (!parsedOwn.success) throw new Error(`hosts/${host.name}: agents/proxy resolved to invalid values:\n${z.prettifyError(parsedOwn.error)}`);
409
+ own = parsedOwn.data;
410
+ } catch (error) {
411
+ if (lifecycle === "attached") await stopAll(services, names);
412
+ throw error;
413
+ }
414
+ const pluginEntries = resolved.runner.plugins;
415
+ const resolvedPlugins = pluginEntries ? (await resolveHostPlugins(ctx.projectRoot, "compound", ctx.verb, pluginEntries, `hosts/${host.name}/host.js`)).map((r) => r.plugin) : [];
416
+ const proxyBlock = own.proxy;
417
+ if (proxyBlock) resolvedPlugins.push(createProxyPlugin(proxyBlock));
418
+ const compoundCtx = { logger: { info: (m) => console.log(m) } };
419
+ if (resolvedPlugins.length > 0) await runObserveHook("onMembersReady", resolvedPlugins, compoundCtx);
420
+ const agents = {};
421
+ for (const [name, agent] of Object.entries(own.agents ?? {})) agents[name] = agent.url.replace(/\/$/, "");
422
+ if (Object.keys(agents).length > 0) console.log(`[${resolved.name}] agents: ${Object.entries(agents).map(([n, u]) => `${n} → ${u}`).join(", ")}`);
423
+ const shutdown = async () => {
424
+ if (resolvedPlugins.length > 0) await runObserveHookSequential("onShutdown", resolvedPlugins, compoundCtx);
425
+ if (lifecycle === "attached") await stopAll(services, names);
426
+ else console.log(`[${resolved.name}] detached lifecycle: children keep running (stop them with the ${resolved.name} service commands or taskkill).`);
427
+ };
428
+ const parsedOutputs = outputsSchema.safeParse({
429
+ agents,
430
+ ...compoundCtx.proxyUrl ? { proxy: { url: compoundCtx.proxyUrl } } : {}
431
+ });
432
+ if (!parsedOutputs.success) {
433
+ await shutdown();
434
+ throw new Error(`hosts/${host.name}: the shell produced invalid outputs:\n${z.prettifyError(parsedOutputs.error)}`);
435
+ }
436
+ const outputs = parsedOutputs.data;
437
+ if (lifecycle === "attached") {
438
+ const onSignal = () => {
439
+ shutdown().finally(() => process.exit(130));
440
+ };
441
+ process.once("SIGINT", onSignal);
442
+ process.once("SIGTERM", onSignal);
443
+ }
444
+ return {
445
+ outputs,
446
+ ready: Promise.resolve(),
447
+ services,
448
+ shutdown
449
+ };
450
+ }
451
+ /** Minimal line chat against an agent's OpenAI-compatible endpoint. */
452
+ async function chatLoop(agents) {
453
+ const [agentName, endpoint] = Object.entries(agents)[0] ?? [];
454
+ if (!agentName || !endpoint) {
455
+ console.log("No agents configured (config.agents) — chat unavailable.");
456
+ return;
457
+ }
458
+ console.log(`Chatting with ${agentName} (${endpoint}). /exit to quit.`);
459
+ const rl = createInterface({
460
+ input: process.stdin,
461
+ output: process.stdout
462
+ });
463
+ const ask = (q) => new Promise((resolve) => rl.question(q, resolve));
464
+ for (;;) {
465
+ const line = (await ask("> ")).trim();
466
+ if (line === "/exit" || line === "exit") break;
467
+ if (!line) continue;
468
+ try {
469
+ const res = await fetch(`${endpoint}/chat/completions`, {
470
+ method: "POST",
471
+ headers: { "content-type": "application/json" },
472
+ body: JSON.stringify({ messages: [{
473
+ role: "user",
474
+ content: line
475
+ }] })
476
+ });
477
+ const body = await res.json();
478
+ console.log(body.choices?.[0]?.message?.content ?? `[error] ${body.error?.message ?? res.status}`);
479
+ } catch (error) {
480
+ console.log(`[transport error] ${String(error)}`);
481
+ }
482
+ }
483
+ rl.close();
484
+ }
485
+ async function run(host, ctx) {
486
+ const handle = await startShell(host, ctx);
487
+ console.log(`[${host.name}] services up. (ph run ${host.name} dev for the chat shell; Ctrl+C ${host.runner.lifecycle === "attached" ? "stops the children" : "leaves children running"}.)`);
488
+ return handle;
489
+ }
490
+ const serve = run;
491
+ /** dev = services up + the line chat shell (blocks until /exit). */
492
+ async function dev(host, ctx) {
493
+ const handle = await startShell(host, ctx);
494
+ await chatLoop(handle.outputs.agents);
495
+ await handle.shutdown();
496
+ }
497
+ /** build = forward build to each member host that exports it (fail loud on
498
+ * members that do not — a silent skip would report success on an unbuilt
499
+ * set), same posture as the generic compound. */
500
+ async function build(host, ctx) {
501
+ const { getVerb, resolveRunnerModule, validateHost } = await import("@powerhousedao/host-core");
502
+ for (const [name, wrapper] of Object.entries(host.children)) {
503
+ const member = await loadHost(ctx.projectRoot, wrapper.host);
504
+ const specifier = member.host.runner.module;
505
+ const runner = await resolveRunnerModule(ctx.projectRoot, specifier);
506
+ const validated = validateHost(runner, specifier, member.host, `hosts/${wrapper.host}/host.js`);
507
+ const fn = getVerb(runner, specifier, "build");
508
+ console.log(`[${host.name}] build → ${name} (${wrapper.host})`);
509
+ await fn(validated, {
510
+ ...ctx,
511
+ verb: "build",
512
+ parent: {
513
+ host: host.name,
514
+ verb: ctx.verb
515
+ }
516
+ });
517
+ }
518
+ }
519
+ //#endregion
520
+ export { build, declaredHostSchema, dev, hostSchema, kind, outputsSchema, run, serve, verbs };
521
+
522
+ //# sourceMappingURL=clint-runner.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clint-runner.mjs","names":[],"sources":["../../src/runners/removed-forms.ts","../../src/runners/proxy-plugin.ts","../../src/runners/member-records.ts","../../src/runners/clint-runner.ts"],"sourcesContent":["import type { z } from \"zod\";\n\n/**\n * Output tokens (typed-host-configs T3) replaced the sibling-host reference\n * forms the clint runners used to resolve themselves. A removed key is not\n * just \"unrecognized\": its error names the token form that replaces it.\n * Pass the result as a strict object's `error` option.\n */\nexport function removedKeyError(\n key: string,\n hint: (input: Record<string, unknown>) => string,\n): z.core.$ZodErrorMap {\n return (issue) => {\n if (issue.code !== \"unrecognized_keys\" || !issue.keys.includes(key)) {\n return undefined;\n }\n const input =\n typeof issue.input === \"object\" && issue.input !== null\n ? (issue.input as Record<string, unknown>)\n : {};\n return `\\`${key}\\` was removed; ${hint(input)}`;\n };\n}\n\n/** A quoted host name from a removed reference, or a placeholder. */\nexport function quotedHost(value: unknown, placeholder: string): string {\n return typeof value === \"string\" && value.length > 0\n ? JSON.stringify(value)\n : placeholder;\n}\n","import type { HostPlugin } from \"@powerhousedao/host-core\";\nimport { ref } from \"@powerhousedao/host-core/schema\";\nimport { z } from \"zod\";\nimport { removedKeyError } from \"./removed-forms.js\";\n\n/**\n * R5 — the clint proxy as a COMPOUND plugin (rewire plan: appliesTo\n * \"compound\", the member-set branch of the hierarchy). One front port routes\n * to upstream URLs, WebSocket-aware. A route to a member names that member\n * host's own output (e.g. `{ $output: { host: \"assistant\", path: [\"origin\"] } }`),\n * resolved before the runner sees the config — the proxy never derives an\n * address from a declared port. Declarative veneer over the clint package's\n * createProxyServer; the route table assembly is pure\n * (buildProxyRouteTable) and unit-tested without sockets.\n */\n\n/** The token form that replaced a route's `member` reference. */\nfunction memberHint(input: Record<string, unknown>): string {\n const member =\n typeof input.member === \"string\" && input.member.length > 0\n ? `, member: ${JSON.stringify(input.member)}`\n : \"\";\n return `point \\`upstream\\` at the member host's output: upstream: <host>.origin from ../<host>/outputs.js, or { $output: { host: \"<member's host>\"${member}, path: [\"origin\"] } }.`;\n}\n\n/** The proxy config, built once per form: `url` is the upstream field —\n * `ref(z.url())` when declared, `z.url()` when resolved. */\nfunction buildProxyPluginConfigSchema<U extends z.ZodType>(url: U) {\n /** One route: an upstream URL (literal or output token) plus optional\n * path + ws. */\n const proxyRouteSchema = z.strictObject(\n {\n upstream: url,\n path: z.string().optional(),\n ws: z.boolean().optional(),\n },\n { error: removedKeyError(\"member\", memberHint) },\n );\n return z.strictObject({\n /** Front port (0 = any free port). */\n port: z.number().int().min(0),\n /** Bind address (default \"0.0.0.0\"). */\n host: z.string().min(1).optional(),\n publicUrl: z.url().optional(),\n /** Route prefix -> target. */\n routes: z.record(z.string(), proxyRouteSchema),\n });\n}\n\n/** `runner.proxy` on a clint-runner host, resolved (what the runner reads). */\nexport const proxyPluginConfigSchema = buildProxyPluginConfigSchema(z.url());\n\n/** `runner.proxy` as declared: upstreams may be output tokens. */\nexport const declaredProxyPluginConfigSchema = buildProxyPluginConfigSchema(\n ref(z.url()),\n);\n\nexport type ProxyPluginConfig = z.output<typeof proxyPluginConfigSchema>;\nexport type ProxyPluginConfigInput = z.input<\n typeof declaredProxyPluginConfigSchema\n>;\n\nexport interface ResolvedProxyRoute {\n prefix: string;\n upstream: string;\n ws: boolean;\n source: string;\n}\n\n/** Pure route-table assembly: each upstream (+ optional path). */\nexport function buildProxyRouteTable(\n config: ProxyPluginConfig,\n): ResolvedProxyRoute[] {\n return Object.entries(config.routes).map(([prefix, route]) => ({\n prefix,\n upstream: `${route.upstream.replace(/\\/+$/, \"\")}${route.path ?? \"\"}`,\n ws: route.ws ?? false,\n source: `upstream:${route.upstream}`,\n }));\n}\n\nexport interface ClintCompoundContext {\n proxyRoutes?: ResolvedProxyRoute[];\n /** The proxy's listening URL, set at onMembersReady. */\n proxyUrl?: string;\n proxyStop?: () => Promise<void>;\n logger?: { info: (m: string) => void };\n}\n\nexport function createProxyPlugin(config: ProxyPluginConfig): HostPlugin<{\n onMembersReady: (ctx: ClintCompoundContext) => Promise<void>;\n onShutdown: (ctx: ClintCompoundContext) => Promise<void>;\n}> {\n return {\n name: \"clint-proxy\",\n appliesTo: \"compound\",\n hooks: {\n onMembersReady: async (ctx) => {\n const table = buildProxyRouteTable(config);\n ctx.proxyRoutes = table;\n const { createProxyServer } = await import(\"../core/proxy.js\");\n const instance = await createProxyServer({\n port: config.port,\n host: config.host ?? \"0.0.0.0\",\n publicUrl: config.publicUrl,\n logger: (ctx.logger ?? console) as never,\n });\n for (const route of table) {\n instance.addRoute({\n prefix: route.prefix,\n upstream: new URL(route.upstream),\n ws: route.ws,\n source: route.source,\n });\n }\n ctx.proxyUrl = instance.url;\n ctx.proxyStop = () => instance.stop();\n ctx.logger?.info(\n `[clint-proxy] listening on ${instance.url} — ${table.length} route(s)`,\n );\n },\n onShutdown: async (ctx) => {\n await ctx.proxyStop?.();\n },\n },\n };\n}\n\nexport default createProxyPlugin;\n","import { probeRun } from \"@powerhousedao/host-core\";\n\n/* Kept out of clint-runner.ts: a runner module exports only its verb\n * functions (plus schemas and constants). */\n\n/** How often {@link awaitRunRecord} re-reads a member's run record. */\nconst RECORD_POLL_MS = 100;\n\n/** A member whose outputs something reads, and what it waits for. */\nexport interface RecordWait {\n /** The child key (`children.<id>`). */\n id: string;\n /** The member host's `name` (its record is `.ph/run/<host>.json`). */\n host: string;\n /** How long to wait, in ms (the member's readiness timeout). */\n timeout: number;\n /** Who reads the member's outputs, for the error. */\n readers: string[];\n /** The member's service state, when clint started it: a `failed` or\n * `stopped` member will never publish, so the wait ends early. */\n status?: () => string | undefined;\n}\n\n/**\n * Waits for a started member's LIVE run record. A member counts as up when\n * its stdout matches the readiness pattern, but `ph run` writes the member's\n * run record only after the runner's `ready` resolves, so a reader that\n * looks right after the readiness line can find none. Polls until the\n * record is live, the member's service fails or stops, or `timeout` passes;\n * then throws naming the member, its record, the timeout and its readers.\n * An earlier run's stale record does not count: it is waited past.\n */\nexport async function awaitRunRecord(\n projectRoot: string,\n projectName: string,\n consumer: string,\n wait: RecordWait,\n pollMs = RECORD_POLL_MS,\n): Promise<void> {\n const deadline = Date.now() + wait.timeout;\n for (;;) {\n if (probeRun(projectRoot, wait.host, projectName).status === \"live\") {\n return;\n }\n const status = wait.status?.();\n const gone = status === \"failed\" || status === \"stopped\";\n if (gone || Date.now() >= deadline) {\n const why = gone\n ? `${status} before publishing its live run record`\n : `published no live run record within ${wait.timeout} ms (children.${wait.id}.config.readiness.timeout)`;\n throw new Error(\n `hosts/${consumer}/host.js: member \"${wait.id}\" is up (its readiness line matched) but ${why} (.ph/run/${wait.host}.json); ${wait.readers.join(\", \")} read its outputs.`,\n );\n }\n await new Promise((resolve) =>\n setTimeout(resolve, Math.min(pollMs, Math.max(0, deadline - Date.now()))),\n );\n }\n}\n","import { createInterface } from \"node:readline\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n compoundOutputSource,\n defaultUserDataDir,\n loadHost,\n loadProducers,\n outputRefsOf,\n outputSitesOf,\n planCompound,\n probeRun,\n processResolveEnv,\n refineStartOrder,\n resolveHostOutputs,\n runObserveHook,\n runObserveHookSequential,\n resolveHostPlugins,\n runRecordOutputSource,\n type DeferredResolution,\n type LoadedHost,\n type RunnerContext,\n type RunnerHandle,\n} from \"@powerhousedao/host-core\";\nimport { defineHostSchemas, ref } from \"@powerhousedao/host-core/schema\";\nimport { z } from \"zod\";\nimport {\n createProxyPlugin,\n declaredProxyPluginConfigSchema,\n proxyPluginConfigSchema,\n type ClintCompoundContext,\n} from \"./proxy-plugin.js\";\nimport { awaitRunRecord } from \"./member-records.js\";\nimport { quotedHost, removedKeyError } from \"./removed-forms.js\";\nimport fs from \"node:fs\";\nimport { createEventBus } from \"../core/events.js\";\nimport { isPortFree } from \"../core/preflight.js\";\nimport { createServiceManager, defineService } from \"../core/services.js\";\nimport { formatStatus } from \"../core/service-command.js\";\nimport type { ServiceDefinition, ServiceManager } from \"../core/types.js\";\n\n/**\n * clint-runner (P5.4): the clint shell as a compound runner. Each member\n * runs as `ph-cli run <member>` in its own process, scheduled by the ported\n * services manager; `lifecycle: \"detached\"` (default) leaves members running\n * and re-attaches next run, `\"attached\"` tears them down. `config.agents`\n * maps names to OpenAI-compatible endpoints (a literal, or a member's\n * `endpoints.openai` token resolved once it is up). `dev` adds a line chat\n * loop against the first agent; the ink REPL stays the library path.\n */\n\nexport const kind = \"compound\";\n\n/** The token form that replaced an agent's sibling `host` reference. */\nfunction agentHostHint(input: Record<string, unknown>): string {\n const host = quotedHost(input.host, '\"<agent host>\"');\n return `use url: <host>.endpoints.openai from ../<host>/outputs.js, or { url: { $output: { host: ${host}, path: [\"endpoints\", \"openai\"] } } }.`;\n}\n\n/** An agent the shell can chat with: the OpenAI-compatible base URL of an\n * agent API (an agent host's `endpoints.openai` output, or external). */\nfunction agentRefSchema<U extends z.ZodType>(url: U) {\n return z.strictObject(\n { url },\n { error: removedKeyError(\"host\", agentHostHint) },\n );\n}\n\n/**\n * The clint compound host, from one definition in two forms: DECLARED (what\n * host.js authors write) and RESOLVED (what `validateHost` checks).\n *\n * `config.agents.*.url` and `runner.proxy.routes.*.upstream` are DEFERRED\n * self fields: they typically name outputs of this compound's own members,\n * which exist only once clint has started them inside the verb. They take\n * tokens in BOTH forms (`ref`, not `s.tokenable`), and the runner resolves\n * them after its members are up, then parses them with `ownFieldsSchema`.\n */\nconst schemas = defineHostSchemas((base) => {\n /** clint-runner's own `runner` options, on top of the common base. */\n const clintRunnerOptionsSchema = base.runnerBaseSchema\n .extend({\n /** \"detached\" (default): children outlive the shell and are\n * re-attached on the next run. \"attached\": the shell tears them down\n * on exit. */\n lifecycle: z.enum([\"attached\", \"detached\"]).optional(),\n /** One front port routing to upstreams (the clint proxy plugin). */\n proxy: declaredProxyPluginConfigSchema.optional(),\n })\n .strict();\n\n /** A member's scheduling knobs. Members run as their own `ph-cli run\n * <host>` process, so the wrapper's `config` is read by clint (not passed\n * to the member) and holds only these. */\n const clintMemberConfigSchema = z.strictObject({\n /** When the member counts as up: a stdout pattern (regex source, case\n * insensitive) and a timeout in ms. */\n readiness: z\n .strictObject({\n pattern: z.string().min(1).optional(),\n timeout: z.number().int().positive().optional(),\n })\n .optional(),\n });\n\n const cliHostConfigSchema = z.strictObject({\n agents: z.record(z.string(), agentRefSchema(ref(z.url()))).optional(),\n /** Member start order; must name declared children. Unnamed members\n * start after the named ones, in declaration order. */\n startOrder: z.array(z.string().min(1)).optional(),\n });\n\n // Extend the unrefined base, refine last (zod refuses to extend a refined\n // object).\n return base.compoundHostSchema\n .extend({\n runner: clintRunnerOptionsSchema,\n children: z.record(\n z.string(),\n base.childWrapperSchema.extend({\n config: clintMemberConfigSchema.optional(),\n }),\n ),\n config: cliHostConfigSchema.optional(),\n })\n .superRefine(refineStartOrder);\n});\n\n/** Declared form: what a host file may contain before resolution. */\nexport const declaredHostSchema = schemas.declaredHostSchema;\n/** Resolved form: what `validateHost` checks and the verbs receive (the\n * deferred self fields may still carry tokens; see above). */\nexport const hostSchema = schemas.hostSchema;\n\n/** The deferred self fields once resolved (after member start). */\nconst ownFieldsSchema = z.strictObject({\n agents: z.record(z.string(), agentRefSchema(z.url())).optional(),\n proxy: proxyPluginConfigSchema.optional(),\n});\n\n/** What a clint host.js author writes. */\nexport type ClintHostInput = z.input<typeof declaredHostSchema>;\n/** What the verbs receive. */\nexport type ClintHost = z.output<typeof hostSchema>;\ntype OwnFields = z.output<typeof ownFieldsSchema>;\n\n/** The verbs this runner exports (the rest of its exports are not verbs). */\nexport const verbs = [\"run\", \"serve\", \"dev\", \"build\"] as const;\n\n/** Live outputs of the compound's members, keyed by child name\n * (`outputs` undefined when the member published no live run record). */\nexport type LiveMemberOutputs = Record<\n string,\n { host: string; outputs: unknown }\n>;\n\n/**\n * Resolve the shell's own tokens before any member starts: `$env`, the\n * built-ins and other hosts' outputs now (an unset variable or a producer\n * that is not running fails with nothing started); tokens naming its own\n * members' outputs are deferred until those members are up (`finish`).\n * `children` stay as declared: each member resolves its own.\n */\nasync function resolveOwnTokens(\n host: ClintHost,\n ctx: RunnerContext,\n projectName: string,\n): Promise<DeferredResolution<ClintHost>> {\n const members = Object.entries(host.children).map(([key, wrapper]) => ({\n key,\n host: wrapper.host,\n }));\n const foreign = outputRefsOf({ ...host, children: {} }).filter(\n (ref) => !members.some((member) => member.host === ref.host),\n );\n return resolveHostOutputs(\n host,\n {\n outputs: runRecordOutputSource(ctx.projectRoot, {\n consumer: host.name,\n producers: await loadProducers(ctx.projectRoot, foreign),\n projectName,\n }),\n ...processResolveEnv(ctx.projectRoot, ctx.env),\n where: `hosts/${host.name}/host.js`,\n },\n { deferSelf: { members } },\n );\n}\n\n/** Finish the deferred self tokens from the members' live run records. */\nfunction finishOwnTokens(\n pending: DeferredResolution<ClintHost>,\n live: LiveMemberOutputs,\n name: string,\n): ClintHost {\n const started = new Map<string, unknown>();\n for (const [key, member] of Object.entries(live)) {\n if (member.outputs !== undefined) started.set(key, member.outputs);\n }\n const silent = pending.needs.filter((key) => !started.has(key));\n if (silent.length > 0) {\n const paths = pending.deferred\n .filter((d) => d.members.some((key) => silent.includes(key)))\n .map((d) => d.path);\n throw new Error(\n `hosts/${name}/host.js: ${paths.join(\", \")} read the outputs of member ${silent.map((key) => `\"${key}\"`).join(\", \")}, which is up but published no live run record (.ph/run/<host>.json) to read them from.`,\n );\n }\n const members = Object.entries(pending.host.children).map(\n ([key, wrapper]) => ({ key, host: wrapper.host }),\n );\n return pending.finish(compoundOutputSource(members, started, name));\n}\n\n/** Started members' outputs, read from their own run records (members run\n * as separate `ph-cli run` processes, which publish their outputs there). */\nfunction liveMemberOutputs(\n projectRoot: string,\n projectName: string,\n memberHosts: Record<string, string>,\n): LiveMemberOutputs {\n const members: LiveMemberOutputs = {};\n for (const [id, hostName] of Object.entries(memberHosts)) {\n const probe = probeRun(projectRoot, hostName, projectName);\n members[id] = {\n host: hostName,\n outputs: probe.status === \"live\" ? probe.record.outputs : undefined,\n };\n }\n return members;\n}\n\n/** What starting the shell produces: the resolved agent endpoints and, when\n * `runner.proxy` is set, the proxy's URL. Member outputs belong to the\n * members. */\nexport const outputsSchema = z.strictObject({\n agents: z.record(z.string(), z.url()),\n proxy: z.strictObject({ url: z.url() }).optional(),\n});\n\nexport type ClintOutputs = z.infer<typeof outputsSchema>;\n\ndeclare global {\n interface PHHostRunners {\n \"@powerhousedao/clint/clint-runner\": {\n host: ClintHostInput;\n outputs: ClintOutputs;\n };\n }\n}\n\n// A URL in stdout is the universal \"I am serving\" signal across member kinds\n// (switchboard prints \"MCP server available at http://…\", preview \"Local:\",\n// the agent \"agent API … http://…\").\nconst DEFAULT_READINESS = \"https?://|listening|ready\";\n/** How long a member may take to print its readiness line, in ms; also how\n * long clint then waits for its run record when something reads it. */\nconst READINESS_TIMEOUT = 180_000;\n\n/** Resolve the project's ph-cli entry the same way host-core resolves runner\n * modules: from the PROJECT's dependency tree. */\nfunction resolvePhCliEntry(projectRoot: string): string {\n const require_ = createRequire(\n pathToFileURL(path.join(projectRoot, \"package.json\")).href,\n );\n const pkgPath = require_.resolve(\"@powerhousedao/ph-cli/package.json\");\n return path.join(path.dirname(pkgPath), \"dist\", \"cli.mjs\");\n}\n\nfunction childServices(\n host: ClintHost,\n ctx: RunnerContext,\n phCliEntry: string,\n): ServiceDefinition<Record<string, unknown>>[] {\n return Object.entries(host.children).map(([name, wrapper]) =>\n defineService({\n id: name,\n name,\n command: () => `node \"${phCliEntry}\" run ${wrapper.host}`,\n env: () => ({\n FEATURE_UNIFORM_RUNNERS_ENABLED: \"1\",\n PH_USER_DATA_DIR: defaultUserDataDir(ctx.projectRoot, ctx.env),\n }),\n readiness: {\n patterns: [\n {\n name: \"up\",\n pattern: new RegExp(\n wrapper.config?.readiness?.pattern ?? DEFAULT_READINESS,\n \"i\",\n ),\n },\n ],\n timeout: wrapper.config?.readiness?.timeout ?? READINESS_TIMEOUT,\n },\n }),\n );\n}\n\nfunction readProjectName(projectRoot: string, fallback: string): string {\n try {\n return (\n (\n JSON.parse(\n fs.readFileSync(path.join(projectRoot, \"package.json\"), \"utf8\"),\n ) as { name?: string }\n ).name ?? fallback\n );\n } catch {\n return fallback;\n }\n}\n\nasync function stopAll(\n services: ServiceManager,\n names: string[],\n): Promise<void> {\n for (const id of names) {\n try {\n await services.stop(id);\n } catch {\n // already stopped\n }\n }\n}\n\n/** The shell's handle: the runner contract plus the services manager. */\nexport interface CliRunHandle extends RunnerHandle<ClintOutputs> {\n services: ServiceManager;\n}\n\nasync function startShell(\n host: ClintHost,\n ctx: RunnerContext,\n): Promise<CliRunHandle> {\n const projectName = readProjectName(ctx.projectRoot, host.name);\n // resolveOwnTokens also substitutes the \"${userData}\"/\"${projectRoot}\"\n // sugar (processResolveEnv's built-ins); member wrappers stay as declared.\n const pending = await resolveOwnTokens(host, ctx, projectName);\n const resolved = pending.host;\n const config = resolved.config ?? {};\n const lifecycle = resolved.runner.lifecycle ?? \"detached\";\n\n const phCliEntry = resolvePhCliEntry(ctx.projectRoot);\n const children = resolved.children;\n const definitions = childServices(resolved, ctx, phCliEntry);\n const eventBus = createEventBus();\n // R5: compound plugins (appliesTo \"compound\" — e.g. the proxy) run over the\n // member set. Built-ins resolve from a declared `runner.plugins`; the proxy\n // is registered when a `runner.proxy` block is present (ergonomic alias).\n const servicesDir = path.join(ctx.projectRoot, \".ph\", \"services\");\n const services = createServiceManager(definitions, {\n config: {},\n servicesDir,\n eventBus,\n });\n\n // Each member's own host.js: its `$output` tokens on sibling members\n // decide the start order (each member resolves them from its producers'\n // run records as it starts).\n const names = definitions.map((d) => d.id);\n const loaded = new Map<string, LoadedHost>();\n for (const id of names) {\n loaded.set(id, await loadHost(ctx.projectRoot, children[id].host));\n }\n // Start order: the same dependency plan the generic compound uses —\n // producers before consumers (ties keep declaration order); a\n // config.startOrder must agree with the tokens. Tokens on hosts outside\n // the compound read standalone producers and do not order members.\n const memberRefs = names.map((key) => ({ key, host: children[key].host }));\n const plan = planCompound(\n names.map((key) => ({\n key,\n host: children[key].host,\n refs: outputSitesOf(loaded.get(key)?.host)\n .filter(({ ref }) => memberRefs.some((m) => m.host === ref.host))\n .map(({ ref, path }) => ({ ref, path })),\n })),\n config.startOrder,\n );\n const ordered = plan.order;\n // Whose outputs are read, and by whom: the shell's deferred self fields,\n // and the members that consume a sibling.\n const readers = new Map<string, string[]>();\n const addReader = (id: string, reader: string) =>\n readers.set(id, [...(readers.get(id) ?? []), reader]);\n for (const deferred of pending.deferred) {\n for (const id of deferred.members) addReader(id, deferred.path);\n }\n for (const edge of plan.edges) {\n addReader(edge.producer, `member \"${edge.consumer}\"`);\n }\n /** Wait for a member's live run record when something reads it. With\n * `managed` (clint's own service state describes it), a failed or stopped\n * service ends the wait early; a member found serving on its port is not\n * clint's to watch, so it gets the full timeout. */\n const waitForRecord = async (\n id: string,\n memberHost: string,\n managed = true,\n ) => {\n const read = readers.get(id);\n if (!read) return;\n try {\n await awaitRunRecord(ctx.projectRoot, projectName, host.name, {\n id,\n host: memberHost,\n timeout: children[id].config?.readiness?.timeout ?? READINESS_TIMEOUT,\n readers: read,\n ...(managed\n ? {\n status: () =>\n services.list(id).find((s) => s.serviceId === id)?.status,\n }\n : {}),\n });\n } catch (error) {\n if (lifecycle === \"attached\") await stopAll(services, names);\n throw error;\n }\n };\n\n const memberHosts: Record<string, string> = {};\n for (const id of ordered) {\n // Re-attach checks, strongest first. (1) The member's OWN run record —\n // written with the member process's real pid (mastra-runner, the generic\n // compound). (2) Port occupancy for record-less bridge members. (3) The\n // service state file — weakest on Windows, where it records the cmd shim\n // pid, which dies on console teardown while the node grandchild survives.\n const wrapper = children[id];\n const member =\n loaded.get(id) ?? (await loadHost(ctx.projectRoot, wrapper.host));\n memberHosts[id] = member.host.name;\n const record = probeRun(ctx.projectRoot, member.host.name, projectName);\n if (record.status === \"live\") {\n console.log(\n `[${resolved.name}] ${id}: already running (pid ${record.record.pid}) — re-attached`,\n );\n continue;\n }\n const memberPort =\n typeof wrapper.runner?.port === \"number\"\n ? wrapper.runner.port\n : typeof member.host.runner.port === \"number\"\n ? member.host.runner.port\n : undefined;\n if (memberPort !== undefined && !(await isPortFree(memberPort))) {\n console.log(\n `[${resolved.name}] ${id}: port ${memberPort} already serving — re-attached`,\n );\n // It may still be booting (an earlier detached run, or started by\n // hand): its readers need its record, as after a fresh start.\n await waitForRecord(id, member.host.name, false);\n continue;\n }\n const already = services\n .list(id)\n .some((s) => s.status === \"ready\" || s.status === \"starting\");\n if (already) {\n console.log(`[${resolved.name}] ${id}: already running — re-attached`);\n await waitForRecord(id, member.host.name);\n continue;\n }\n console.log(`[${resolved.name}] starting ${id}…`);\n await services.start(id, {\n workdir: ctx.projectRoot,\n cwd: ctx.projectRoot,\n });\n const status = services.list(id).find((s) => s.serviceId === id);\n if (status) console.log(` ${formatStatus(status)}`);\n // Before anything reads its outputs (the next member, or the shell's\n // own deferred fields below).\n await waitForRecord(id, member.host.name);\n }\n\n // The deferred self fields (agent urls, proxy upstreams) name the\n // members' outputs, which exist now.\n let own: OwnFields;\n try {\n const finished = finishOwnTokens(\n pending,\n liveMemberOutputs(ctx.projectRoot, projectName, memberHosts),\n host.name,\n );\n const parsedOwn = ownFieldsSchema.safeParse({\n agents: finished.config?.agents,\n proxy: finished.runner.proxy,\n });\n if (!parsedOwn.success) {\n throw new Error(\n `hosts/${host.name}: agents/proxy resolved to invalid values:\\n${z.prettifyError(parsedOwn.error)}`,\n );\n }\n own = parsedOwn.data;\n } catch (error) {\n if (lifecycle === \"attached\") await stopAll(services, names);\n throw error;\n }\n\n // Compound-plugin pipeline (CompoundCore): resolve entries + the proxy\n // ergonomic alias, then fire onMembersReady now that endpoints are known.\n const pluginEntries = resolved.runner.plugins;\n const resolvedPlugins = pluginEntries\n ? (\n await resolveHostPlugins(\n ctx.projectRoot,\n \"compound\",\n ctx.verb,\n pluginEntries,\n `hosts/${host.name}/host.js`,\n )\n ).map((r) => r.plugin)\n : [];\n const proxyBlock = own.proxy;\n if (proxyBlock) {\n resolvedPlugins.push(createProxyPlugin(proxyBlock));\n }\n const compoundCtx: ClintCompoundContext = {\n logger: { info: (m: string) => console.log(m) },\n };\n if (resolvedPlugins.length > 0) {\n await runObserveHook(\"onMembersReady\", resolvedPlugins, compoundCtx);\n }\n\n const agents: Record<string, string> = {};\n for (const [name, agent] of Object.entries(own.agents ?? {})) {\n agents[name] = agent.url.replace(/\\/$/, \"\");\n }\n if (Object.keys(agents).length > 0) {\n console.log(\n `[${resolved.name}] agents: ${Object.entries(agents)\n .map(([n, u]) => `${n} → ${u}`)\n .join(\", \")}`,\n );\n }\n\n const shutdown = async () => {\n if (resolvedPlugins.length > 0) {\n await runObserveHookSequential(\n \"onShutdown\",\n resolvedPlugins,\n compoundCtx,\n );\n }\n if (lifecycle === \"attached\") {\n await stopAll(services, names);\n } else {\n console.log(\n `[${resolved.name}] detached lifecycle: children keep running ` +\n `(stop them with the ${resolved.name} service commands or taskkill).`,\n );\n }\n };\n\n // Validated before the stack is handed out: an invalid output (e.g. a proxy\n // bound to a bare IPv6 host, which does not form a URL) tears down what\n // was started instead of leaving it half-up.\n const parsedOutputs = outputsSchema.safeParse({\n agents,\n ...(compoundCtx.proxyUrl ? { proxy: { url: compoundCtx.proxyUrl } } : {}),\n });\n if (!parsedOutputs.success) {\n await shutdown();\n throw new Error(\n `hosts/${host.name}: the shell produced invalid outputs:\\n${z.prettifyError(parsedOutputs.error)}`,\n );\n }\n const outputs = parsedOutputs.data;\n\n if (lifecycle === \"attached\") {\n const onSignal = () => {\n void shutdown().finally(() => process.exit(130));\n };\n process.once(\"SIGINT\", onSignal);\n process.once(\"SIGTERM\", onSignal);\n }\n\n // Members were started (and awaited to readiness) above.\n return { outputs, ready: Promise.resolve(), services, shutdown };\n}\n\n/** Minimal line chat against an agent's OpenAI-compatible endpoint. */\nasync function chatLoop(agents: Record<string, string>): Promise<void> {\n const [agentName, endpoint] = Object.entries(agents)[0] ?? [];\n if (!agentName || !endpoint) {\n console.log(\"No agents configured (config.agents) — chat unavailable.\");\n return;\n }\n console.log(`Chatting with ${agentName} (${endpoint}). /exit to quit.`);\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n const ask = (q: string) =>\n new Promise<string>((resolve) => rl.question(q, resolve));\n for (;;) {\n const line = (await ask(\"> \")).trim();\n if (line === \"/exit\" || line === \"exit\") break;\n if (!line) continue;\n try {\n const res = await fetch(`${endpoint}/chat/completions`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n messages: [{ role: \"user\", content: line }],\n }),\n });\n const body = (await res.json()) as {\n choices?: { message?: { content?: string } }[];\n error?: { message?: string };\n };\n console.log(\n body.choices?.[0]?.message?.content ??\n `[error] ${body.error?.message ?? res.status}`,\n );\n } catch (error) {\n console.log(`[transport error] ${String(error)}`);\n }\n }\n rl.close();\n}\n\nexport async function run(\n host: ClintHost,\n ctx: RunnerContext,\n): Promise<CliRunHandle> {\n const handle = await startShell(host, ctx);\n console.log(\n `[${host.name}] services up. ` +\n `(ph run ${host.name} dev for the chat shell; Ctrl+C ${\n host.runner.lifecycle === \"attached\"\n ? \"stops the children\"\n : \"leaves children running\"\n }.)`,\n );\n return handle;\n}\n\nexport const serve = run;\n\n/** dev = services up + the line chat shell (blocks until /exit). */\nexport async function dev(host: ClintHost, ctx: RunnerContext): Promise<void> {\n const handle = await startShell(host, ctx);\n await chatLoop(handle.outputs.agents);\n await handle.shutdown();\n}\n\n/** build = forward build to each member host that exports it (fail loud on\n * members that do not — a silent skip would report success on an unbuilt\n * set), same posture as the generic compound. */\nexport async function build(\n host: ClintHost,\n ctx: RunnerContext,\n): Promise<void> {\n const { getVerb, resolveRunnerModule, validateHost } =\n await import(\"@powerhousedao/host-core\");\n for (const [name, wrapper] of Object.entries(host.children)) {\n const member = await loadHost(ctx.projectRoot, wrapper.host);\n const specifier = member.host.runner.module;\n const runner = await resolveRunnerModule(ctx.projectRoot, specifier);\n const validated = validateHost(\n runner,\n specifier,\n member.host,\n `hosts/${wrapper.host}/host.js`,\n );\n const fn = getVerb(runner, specifier, \"build\");\n console.log(`[${host.name}] build → ${name} (${wrapper.host})`);\n await fn(validated, {\n ...ctx,\n verb: \"build\",\n parent: { host: host.name, verb: ctx.verb },\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAQA,SAAgB,gBACd,KACA,MACqB;CACrB,QAAQ,UAAU;EAChB,IAAI,MAAM,SAAS,uBAAuB,CAAC,MAAM,KAAK,SAAS,GAAG,GAChE;EAMF,OAAO,KAAK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