@powerhousedao/clint 6.2.3-dev.69 → 6.2.3-dev.71
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/runners/clint-runner.d.mts +362 -119
- package/dist/runners/clint-runner.d.mts.map +1 -1
- package/dist/runners/clint-runner.mjs +328 -86
- package/dist/runners/clint-runner.mjs.map +1 -1
- package/dist/runners/mastra-runner.d.mts +261 -109
- package/dist/runners/mastra-runner.d.mts.map +1 -1
- package/dist/runners/mastra-runner.mjs +110 -50
- package/dist/runners/mastra-runner.mjs.map +1 -1
- package/package.json +16 -15
|
@@ -4,39 +4,75 @@ import { createRequire } from "node:module";
|
|
|
4
4
|
import fs from "node:fs";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import { pathToFileURL } from "node:url";
|
|
7
|
+
import { z } from "zod";
|
|
7
8
|
import { createInterface } from "node:readline";
|
|
8
|
-
import {
|
|
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
|
|
9
29
|
//#region src/runners/proxy-plugin.ts
|
|
10
30
|
/**
|
|
11
|
-
*
|
|
12
|
-
* member
|
|
13
|
-
*
|
|
14
|
-
*
|
|
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.
|
|
15
39
|
*/
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
}
|
|
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
|
+
}));
|
|
40
76
|
}
|
|
41
77
|
function createProxyPlugin(config) {
|
|
42
78
|
return {
|
|
@@ -44,7 +80,7 @@ function createProxyPlugin(config) {
|
|
|
44
80
|
appliesTo: "compound",
|
|
45
81
|
hooks: {
|
|
46
82
|
onMembersReady: async (ctx) => {
|
|
47
|
-
const table = buildProxyRouteTable(config
|
|
83
|
+
const table = buildProxyRouteTable(config);
|
|
48
84
|
ctx.proxyRoutes = table;
|
|
49
85
|
const { createProxyServer } = await import("../proxy-BFR8GScT.mjs").then((n) => n.n);
|
|
50
86
|
const instance = await createProxyServer({
|
|
@@ -59,6 +95,7 @@ function createProxyPlugin(config) {
|
|
|
59
95
|
ws: route.ws,
|
|
60
96
|
source: route.source
|
|
61
97
|
});
|
|
98
|
+
ctx.proxyUrl = instance.url;
|
|
62
99
|
ctx.proxyStop = () => instance.stop();
|
|
63
100
|
ctx.logger?.info(`[clint-proxy] listening on ${instance.url} — ${table.length} route(s)`);
|
|
64
101
|
},
|
|
@@ -69,26 +106,176 @@ function createProxyPlugin(config) {
|
|
|
69
106
|
};
|
|
70
107
|
}
|
|
71
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
|
|
72
135
|
//#region src/runners/clint-runner.ts
|
|
73
136
|
/**
|
|
74
|
-
* clint-runner (P5.4): the clint
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
* the
|
|
81
|
-
*
|
|
82
|
-
* The agents manager (config.agents) maps names to OpenAI-compatible
|
|
83
|
-
* endpoints — a sibling host reference resolves through that host's
|
|
84
|
-
* runner.port (the mastra-runner serves /v1 there). `dev` adds a line chat
|
|
85
|
-
* loop against the first agent; the full ink REPL remains the library path
|
|
86
|
-
* (defineCli) for implementation projects, as scaffolded clint CLIs use it
|
|
87
|
-
* natively — noted in the phase-5 WBS.
|
|
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.
|
|
88
144
|
*/
|
|
89
145
|
const kind = "compound";
|
|
90
|
-
|
|
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
|
+
});
|
|
91
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;
|
|
92
279
|
/** Resolve the project's ph-cli entry the same way host-core resolves runner
|
|
93
280
|
* modules: from the PROJECT's dependency tree. */
|
|
94
281
|
function resolvePhCliEntry(projectRoot) {
|
|
@@ -96,8 +283,7 @@ function resolvePhCliEntry(projectRoot) {
|
|
|
96
283
|
return path.join(path.dirname(pkgPath), "dist", "cli.mjs");
|
|
97
284
|
}
|
|
98
285
|
function childServices(host, ctx, phCliEntry) {
|
|
99
|
-
|
|
100
|
-
return Object.entries(children).map(([name, wrapper]) => defineService({
|
|
286
|
+
return Object.entries(host.children).map(([name, wrapper]) => defineService({
|
|
101
287
|
id: name,
|
|
102
288
|
name,
|
|
103
289
|
command: () => `node "${phCliEntry}" run ${wrapper.host}`,
|
|
@@ -110,18 +296,10 @@ function childServices(host, ctx, phCliEntry) {
|
|
|
110
296
|
name: "up",
|
|
111
297
|
pattern: new RegExp(wrapper.config?.readiness?.pattern ?? DEFAULT_READINESS, "i")
|
|
112
298
|
}],
|
|
113
|
-
timeout: wrapper.config?.readiness?.timeout ??
|
|
299
|
+
timeout: wrapper.config?.readiness?.timeout ?? READINESS_TIMEOUT
|
|
114
300
|
}
|
|
115
301
|
}));
|
|
116
302
|
}
|
|
117
|
-
async function resolveAgentEndpoint(ref, ctx) {
|
|
118
|
-
if (ref.url) return ref.url.replace(/\/$/, "");
|
|
119
|
-
if (ref.host) {
|
|
120
|
-
const port = (await loadHost(ctx.projectRoot, ref.host)).host.runner.port ?? 4910;
|
|
121
|
-
return `http://127.0.0.1:${String(port)}/v1`;
|
|
122
|
-
}
|
|
123
|
-
throw new Error("agents entries need { host } or { url }");
|
|
124
|
-
}
|
|
125
303
|
function readProjectName(projectRoot, fallback) {
|
|
126
304
|
try {
|
|
127
305
|
return JSON.parse(fs.readFileSync(path.join(projectRoot, "package.json"), "utf8")).name ?? fallback;
|
|
@@ -129,17 +307,21 @@ function readProjectName(projectRoot, fallback) {
|
|
|
129
307
|
return fallback;
|
|
130
308
|
}
|
|
131
309
|
}
|
|
310
|
+
async function stopAll(services, names) {
|
|
311
|
+
for (const id of names) try {
|
|
312
|
+
await services.stop(id);
|
|
313
|
+
} catch {}
|
|
314
|
+
}
|
|
132
315
|
async function startShell(host, ctx) {
|
|
133
|
-
const
|
|
134
|
-
const
|
|
316
|
+
const projectName = readProjectName(ctx.projectRoot, host.name);
|
|
317
|
+
const pending = await resolveOwnTokens(host, ctx, projectName);
|
|
318
|
+
const resolved = pending.host;
|
|
135
319
|
const config = resolved.config ?? {};
|
|
136
320
|
const lifecycle = resolved.runner.lifecycle ?? "detached";
|
|
137
321
|
const phCliEntry = resolvePhCliEntry(ctx.projectRoot);
|
|
138
|
-
const children = resolved.children
|
|
139
|
-
const projectName = readProjectName(ctx.projectRoot, resolved.name);
|
|
322
|
+
const children = resolved.children;
|
|
140
323
|
const definitions = childServices(resolved, ctx, phCliEntry);
|
|
141
324
|
const eventBus = createEventBus();
|
|
142
|
-
const memberEndpoints = {};
|
|
143
325
|
const servicesDir = path.join(ctx.projectRoot, ".ph", "services");
|
|
144
326
|
const services = createServiceManager(definitions, {
|
|
145
327
|
config: {},
|
|
@@ -147,26 +329,64 @@ async function startShell(host, ctx) {
|
|
|
147
329
|
eventBus
|
|
148
330
|
});
|
|
149
331
|
const names = definitions.map((d) => d.id);
|
|
150
|
-
const
|
|
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 = {};
|
|
151
372
|
for (const id of ordered) {
|
|
152
373
|
const wrapper = children[id];
|
|
153
|
-
const member = await loadHost(ctx.projectRoot, wrapper.host);
|
|
374
|
+
const member = loaded.get(id) ?? await loadHost(ctx.projectRoot, wrapper.host);
|
|
375
|
+
memberHosts[id] = member.host.name;
|
|
154
376
|
const record = probeRun(ctx.projectRoot, member.host.name, projectName);
|
|
155
377
|
if (record.status === "live") {
|
|
156
378
|
console.log(`[${resolved.name}] ${id}: already running (pid ${record.record.pid}) — re-attached`);
|
|
157
379
|
continue;
|
|
158
380
|
}
|
|
159
381
|
const memberPort = typeof wrapper.runner?.port === "number" ? wrapper.runner.port : typeof member.host.runner.port === "number" ? member.host.runner.port : void 0;
|
|
160
|
-
if (memberPort !== void 0) memberEndpoints[id] = {
|
|
161
|
-
host: typeof wrapper.runner?.host === "string" && wrapper.runner.host || typeof member.host.runner.host === "string" && member.host.runner.host || "127.0.0.1",
|
|
162
|
-
port: memberPort
|
|
163
|
-
};
|
|
164
382
|
if (memberPort !== void 0 && !await isPortFree(memberPort)) {
|
|
165
383
|
console.log(`[${resolved.name}] ${id}: port ${memberPort} already serving — re-attached`);
|
|
384
|
+
await waitForRecord(id, member.host.name, false);
|
|
166
385
|
continue;
|
|
167
386
|
}
|
|
168
387
|
if (services.list(id).some((s) => s.status === "ready" || s.status === "starting")) {
|
|
169
388
|
console.log(`[${resolved.name}] ${id}: already running — re-attached`);
|
|
389
|
+
await waitForRecord(id, member.host.name);
|
|
170
390
|
continue;
|
|
171
391
|
}
|
|
172
392
|
console.log(`[${resolved.name}] starting ${id}…`);
|
|
@@ -176,26 +396,44 @@ async function startShell(host, ctx) {
|
|
|
176
396
|
});
|
|
177
397
|
const status = services.list(id).find((s) => s.serviceId === id);
|
|
178
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;
|
|
179
413
|
}
|
|
180
414
|
const pluginEntries = resolved.runner.plugins;
|
|
181
|
-
const resolvedPlugins = pluginEntries ? (await resolveHostPlugins(ctx.projectRoot, "compound", ctx.verb
|
|
182
|
-
const proxyBlock =
|
|
183
|
-
if (proxyBlock
|
|
184
|
-
const compoundCtx = {
|
|
185
|
-
memberEndpoints,
|
|
186
|
-
logger: { info: (m) => console.log(m) }
|
|
187
|
-
};
|
|
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) } };
|
|
188
419
|
if (resolvedPlugins.length > 0) await runObserveHook("onMembersReady", resolvedPlugins, compoundCtx);
|
|
189
420
|
const agents = {};
|
|
190
|
-
for (const [name,
|
|
421
|
+
for (const [name, agent] of Object.entries(own.agents ?? {})) agents[name] = agent.url.replace(/\/$/, "");
|
|
191
422
|
if (Object.keys(agents).length > 0) console.log(`[${resolved.name}] agents: ${Object.entries(agents).map(([n, u]) => `${n} → ${u}`).join(", ")}`);
|
|
192
423
|
const shutdown = async () => {
|
|
193
424
|
if (resolvedPlugins.length > 0) await runObserveHookSequential("onShutdown", resolvedPlugins, compoundCtx);
|
|
194
|
-
if (lifecycle === "attached")
|
|
195
|
-
await services.stop(id);
|
|
196
|
-
} catch {}
|
|
425
|
+
if (lifecycle === "attached") await stopAll(services, names);
|
|
197
426
|
else console.log(`[${resolved.name}] detached lifecycle: children keep running (stop them with the ${resolved.name} service commands or taskkill).`);
|
|
198
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;
|
|
199
437
|
if (lifecycle === "attached") {
|
|
200
438
|
const onSignal = () => {
|
|
201
439
|
shutdown().finally(() => process.exit(130));
|
|
@@ -204,8 +442,9 @@ async function startShell(host, ctx) {
|
|
|
204
442
|
process.once("SIGTERM", onSignal);
|
|
205
443
|
}
|
|
206
444
|
return {
|
|
445
|
+
outputs,
|
|
446
|
+
ready: Promise.resolve(),
|
|
207
447
|
services,
|
|
208
|
-
agents,
|
|
209
448
|
shutdown
|
|
210
449
|
};
|
|
211
450
|
}
|
|
@@ -252,7 +491,7 @@ const serve = run;
|
|
|
252
491
|
/** dev = services up + the line chat shell (blocks until /exit). */
|
|
253
492
|
async function dev(host, ctx) {
|
|
254
493
|
const handle = await startShell(host, ctx);
|
|
255
|
-
await chatLoop(handle.agents);
|
|
494
|
+
await chatLoop(handle.outputs.agents);
|
|
256
495
|
await handle.shutdown();
|
|
257
496
|
}
|
|
258
497
|
/** build = forward build to each member host that exports it (fail loud on
|
|
@@ -260,21 +499,24 @@ async function dev(host, ctx) {
|
|
|
260
499
|
* set), same posture as the generic compound. */
|
|
261
500
|
async function build(host, ctx) {
|
|
262
501
|
const { getVerb, resolveRunnerModule, validateHost } = await import("@powerhousedao/host-core");
|
|
263
|
-
const
|
|
264
|
-
for (const [name, wrapper] of Object.entries(children)) {
|
|
502
|
+
for (const [name, wrapper] of Object.entries(host.children)) {
|
|
265
503
|
const member = await loadHost(ctx.projectRoot, wrapper.host);
|
|
266
504
|
const specifier = member.host.runner.module;
|
|
267
505
|
const runner = await resolveRunnerModule(ctx.projectRoot, specifier);
|
|
268
|
-
validateHost(runner, specifier, member.host, `hosts/${wrapper.host}/host.js`);
|
|
506
|
+
const validated = validateHost(runner, specifier, member.host, `hosts/${wrapper.host}/host.js`);
|
|
269
507
|
const fn = getVerb(runner, specifier, "build");
|
|
270
508
|
console.log(`[${host.name}] build → ${name} (${wrapper.host})`);
|
|
271
|
-
await fn(
|
|
509
|
+
await fn(validated, {
|
|
272
510
|
...ctx,
|
|
273
|
-
verb: "build"
|
|
511
|
+
verb: "build",
|
|
512
|
+
parent: {
|
|
513
|
+
host: host.name,
|
|
514
|
+
verb: ctx.verb
|
|
515
|
+
}
|
|
274
516
|
});
|
|
275
517
|
}
|
|
276
518
|
}
|
|
277
519
|
//#endregion
|
|
278
|
-
export { build, dev, hostSchema, kind, run, serve };
|
|
520
|
+
export { build, declaredHostSchema, dev, hostSchema, kind, outputsSchema, run, serve, verbs };
|
|
279
521
|
|
|
280
522
|
//# sourceMappingURL=clint-runner.mjs.map
|