@powerhousedao/clint 6.2.3-dev.57 → 6.2.3-dev.59
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-C1Vr_kQh.mjs → build-skills-C8MlDvTC.mjs} +3 -3
- package/dist/{build-skills-C1Vr_kQh.mjs.map → build-skills-C8MlDvTC.mjs.map} +1 -1
- package/dist/{events-DkzJFZeW.mjs → events-BnwGFTjv.mjs} +2 -2
- package/dist/{events-DkzJFZeW.mjs.map → events-BnwGFTjv.mjs.map} +1 -1
- package/dist/index.mjs +6 -4
- package/dist/{markdown-C1TFXoB6.mjs → markdown-D-sP2zw_.mjs} +2 -2
- package/dist/{markdown-C1TFXoB6.mjs.map → markdown-D-sP2zw_.mjs.map} +1 -1
- package/dist/proxy-BFR8GScT.mjs +302 -0
- package/dist/proxy-BFR8GScT.mjs.map +1 -0
- package/dist/proxy-routes-DP3ztsnS.mjs +215 -0
- package/dist/proxy-routes-DP3ztsnS.mjs.map +1 -0
- package/dist/runners/clint-runner.d.mts +46 -2
- package/dist/runners/clint-runner.d.mts.map +1 -1
- package/dist/runners/clint-runner.mjs +81 -3
- package/dist/runners/clint-runner.mjs.map +1 -1
- package/dist/runners/mastra-runner.d.mts +46 -1
- package/dist/runners/mastra-runner.d.mts.map +1 -1
- package/dist/runners/mastra-runner.mjs +6 -2
- package/dist/runners/mastra-runner.mjs.map +1 -1
- package/dist/{services-BvLvP5Qh.mjs → services-9E-r0nWl.mjs} +3 -214
- package/dist/services-9E-r0nWl.mjs.map +1 -0
- package/dist/{src-DRDGtXYJ.mjs → src-v5f_WnlY.mjs} +8 -302
- package/dist/src-v5f_WnlY.mjs.map +1 -0
- package/dist/{start-CKRhuB1Y.mjs → start-b7Mn2cxB.mjs} +3 -3
- package/dist/{start-CKRhuB1Y.mjs.map → start-b7Mn2cxB.mjs.map} +1 -1
- package/package.json +15 -15
- package/dist/services-BvLvP5Qh.mjs.map +0 -1
- package/dist/src-DRDGtXYJ.mjs.map +0 -1
|
@@ -24,10 +24,16 @@ export declare const hostSchema: import("zod").ZodObject<{
|
|
|
24
24
|
module: import("zod").ZodString;
|
|
25
25
|
defaultVerb: import("zod").ZodOptional<import("zod").ZodString>;
|
|
26
26
|
port: import("zod").ZodOptional<import("zod").ZodNumber>;
|
|
27
|
+
host: import("zod").ZodOptional<import("zod").ZodString>;
|
|
28
|
+
plugins: import("zod").ZodOptional<import("zod").ZodArray<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodObject<{
|
|
29
|
+
module: import("zod").ZodString;
|
|
30
|
+
enabled: import("zod").ZodOptional<import("zod").ZodBoolean>;
|
|
31
|
+
verbs: import("zod").ZodOptional<import("zod").ZodUnion<readonly [import("zod").ZodLiteral<"*">, import("zod").ZodArray<import("zod").ZodString>]>>;
|
|
32
|
+
config: import("zod").ZodOptional<import("zod").ZodRecord<import("zod").ZodString, import("zod").ZodUnknown>>;
|
|
33
|
+
}, import("zod/v4/core").$strict>]>>>;
|
|
27
34
|
}, import("zod/v4/core").$loose>;
|
|
28
35
|
children: import("zod").ZodRecord<import("zod").ZodString, import("zod").ZodObject<{
|
|
29
36
|
host: import("zod").ZodString;
|
|
30
|
-
plugins: import("zod").ZodOptional<import("zod").ZodArray<import("zod").ZodString>>;
|
|
31
37
|
runner: import("zod").ZodOptional<import("zod").ZodObject<{}, import("zod/v4/core").$loose>>;
|
|
32
38
|
config: import("zod").ZodOptional<import("zod").ZodObject<{}, import("zod/v4/core").$loose>>;
|
|
33
39
|
reactor: import("zod").ZodOptional<import("zod").ZodObject<{
|
|
@@ -59,12 +65,18 @@ export declare const hostSchema: import("zod").ZodObject<{
|
|
|
59
65
|
host: import("zod").ZodOptional<import("zod").ZodString>;
|
|
60
66
|
url: import("zod").ZodOptional<import("zod").ZodString>;
|
|
61
67
|
}, import("zod/v4/core").$strict>>;
|
|
68
|
+
projection: import("zod").ZodOptional<import("zod").ZodObject<{
|
|
69
|
+
enabled: import("zod").ZodOptional<import("zod").ZodBoolean>;
|
|
70
|
+
dbPoolSize: import("zod").ZodOptional<import("zod").ZodNumber>;
|
|
71
|
+
}, import("zod/v4/core").$strict>>;
|
|
72
|
+
executors: import("zod").ZodOptional<import("zod").ZodObject<{
|
|
73
|
+
numWorkers: import("zod").ZodOptional<import("zod").ZodUnion<readonly [import("zod").ZodNumber, import("zod").ZodLiteral<"auto">]>>;
|
|
74
|
+
}, import("zod/v4/core").$strict>>;
|
|
62
75
|
}, import("zod/v4/core").$strict>>>;
|
|
63
76
|
placement: import("zod").ZodOptional<import("zod").ZodObject<{
|
|
64
77
|
primary: import("zod").ZodOptional<import("zod").ZodString>;
|
|
65
78
|
default: import("zod").ZodOptional<import("zod").ZodObject<{}, import("zod/v4/core").$loose>>;
|
|
66
79
|
}, import("zod/v4/core").$strict>>;
|
|
67
|
-
workflows: import("zod").ZodOptional<import("zod").ZodBoolean>;
|
|
68
80
|
protocol: import("zod").ZodOptional<import("zod").ZodObject<{
|
|
69
81
|
featureFlags: import("zod").ZodOptional<import("zod").ZodObject<{
|
|
70
82
|
documentDecisions: import("zod").ZodOptional<import("zod").ZodBoolean>;
|
|
@@ -81,6 +93,38 @@ export declare const hostSchema: import("zod").ZodObject<{
|
|
|
81
93
|
refuse: "refuse";
|
|
82
94
|
}>>;
|
|
83
95
|
}, import("zod/v4/core").$strict>>;
|
|
96
|
+
workflows: import("zod").ZodOptional<import("zod").ZodBoolean>;
|
|
97
|
+
renown: import("zod").ZodOptional<import("zod").ZodObject<{
|
|
98
|
+
url: import("zod").ZodOptional<import("zod").ZodString>;
|
|
99
|
+
networkId: import("zod").ZodOptional<import("zod").ZodString>;
|
|
100
|
+
chainId: import("zod").ZodOptional<import("zod").ZodNumber>;
|
|
101
|
+
}, import("zod/v4/core").$strict>>;
|
|
102
|
+
packages: import("zod").ZodOptional<import("zod").ZodObject<{
|
|
103
|
+
registryUrl: import("zod").ZodOptional<import("zod").ZodString>;
|
|
104
|
+
}, import("zod/v4/core").$strict>>;
|
|
105
|
+
namespace: import("zod").ZodOptional<import("zod").ZodString>;
|
|
106
|
+
auth: import("zod").ZodOptional<import("zod").ZodObject<{
|
|
107
|
+
enabled: import("zod").ZodOptional<import("zod").ZodBoolean>;
|
|
108
|
+
admins: import("zod").ZodOptional<import("zod").ZodArray<import("zod").ZodString>>;
|
|
109
|
+
renown: import("zod").ZodOptional<import("zod").ZodObject<{}, import("zod/v4/core").$loose>>;
|
|
110
|
+
}, import("zod/v4/core").$strict>>;
|
|
111
|
+
drives: import("zod").ZodOptional<import("zod").ZodArray<import("zod").ZodObject<{
|
|
112
|
+
slug: import("zod").ZodString;
|
|
113
|
+
id: import("zod").ZodOptional<import("zod").ZodString>;
|
|
114
|
+
projectHash: import("zod").ZodOptional<import("zod").ZodBoolean>;
|
|
115
|
+
name: import("zod").ZodOptional<import("zod").ZodString>;
|
|
116
|
+
icon: import("zod").ZodOptional<import("zod").ZodString>;
|
|
117
|
+
preferredEditor: import("zod").ZodOptional<import("zod").ZodString>;
|
|
118
|
+
sharingType: import("zod").ZodOptional<import("zod").ZodEnum<{
|
|
119
|
+
private: "private";
|
|
120
|
+
public: "public";
|
|
121
|
+
shared: "shared";
|
|
122
|
+
}>>;
|
|
123
|
+
availableOffline: import("zod").ZodOptional<import("zod").ZodBoolean>;
|
|
124
|
+
remote: import("zod").ZodOptional<import("zod").ZodObject<{
|
|
125
|
+
url: import("zod").ZodString;
|
|
126
|
+
}, import("zod/v4/core").$strict>>;
|
|
127
|
+
}, import("zod/v4/core").$strict>>>;
|
|
84
128
|
}, import("zod/v4/core").$strict>>;
|
|
85
129
|
}, import("zod/v4/core").$strict>>;
|
|
86
130
|
config: import("zod").ZodOptional<import("zod").ZodObject<{}, import("zod/v4/core").$loose>>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clint-runner.d.mts","names":[],"sources":["../../src/runners/clint-runner.ts"],"mappings":";;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"clint-runner.d.mts","names":[],"sources":["../../src/runners/clint-runner.ts"],"mappings":";;;;;;;;;;;;;;;;;;;qBAiDa;qBAEA,0BAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;yBAAqB;iBA8F3B;EACf,UAAU;EACV,QAAQ;EACR,gBAAgB;;wBAuMI,IACpB,MAAM,gBACN,KAAK,gBACJ,QAAQ;qBAaE,cAAK;;wBAGI,IACpB,MAAM,gBACN,KAAK,gBACJ;;;;wBASmB,MACpB,MAAM,gBACN,KAAK,gBACJ"}
|
|
@@ -1,11 +1,74 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { r as formatStatus, t as createEventBus } from "../events-
|
|
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
3
|
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
7
|
import { createInterface } from "node:readline";
|
|
8
|
-
import { compoundHostSchema, defaultUserDataDir, loadHost, probeRun, resolveUserDataPlaceholders } from "@powerhousedao/host-core";
|
|
8
|
+
import { compoundHostSchema, defaultUserDataDir, loadHost, probeRun, resolveHostPlugins, resolveUserDataPlaceholders, runObserveHook, runObserveHookSequential } from "@powerhousedao/host-core";
|
|
9
|
+
//#region src/runners/proxy-plugin.ts
|
|
10
|
+
/**
|
|
11
|
+
* Pure route-table assembly: member refs become loopback upstreams via the
|
|
12
|
+
* member's host:port (+ optional path); explicit upstreams pass through.
|
|
13
|
+
* A member ref with no known endpoint throws naming the member — a routing
|
|
14
|
+
* declaration that cannot resolve must fail loudly, not silently drop.
|
|
15
|
+
*/
|
|
16
|
+
function buildProxyRouteTable(config, members) {
|
|
17
|
+
const table = [];
|
|
18
|
+
for (const [prefix, route] of Object.entries(config.routes)) {
|
|
19
|
+
if (route.upstream) {
|
|
20
|
+
table.push({
|
|
21
|
+
prefix,
|
|
22
|
+
upstream: `${route.upstream.replace(/\/+$/, "")}${route.path ?? ""}`,
|
|
23
|
+
ws: route.ws ?? false,
|
|
24
|
+
source: `upstream:${route.upstream}`
|
|
25
|
+
});
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
if (!route.member) throw new Error(`proxy route "${prefix}" names neither a member nor an upstream.`);
|
|
29
|
+
const endpoint = members[route.member];
|
|
30
|
+
if (!endpoint) throw new Error(`proxy route "${prefix}" references member "${route.member}", which has no resolved endpoint (known: ${Object.keys(members).join(", ") || "none"}).`);
|
|
31
|
+
const host = endpoint.host === "0.0.0.0" ? "127.0.0.1" : endpoint.host;
|
|
32
|
+
table.push({
|
|
33
|
+
prefix,
|
|
34
|
+
upstream: `http://${host}:${endpoint.port}${route.path ?? ""}`,
|
|
35
|
+
ws: route.ws ?? false,
|
|
36
|
+
source: `member:${route.member}`
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
return table;
|
|
40
|
+
}
|
|
41
|
+
function createProxyPlugin(config) {
|
|
42
|
+
return {
|
|
43
|
+
name: "clint-proxy",
|
|
44
|
+
appliesTo: "compound",
|
|
45
|
+
hooks: {
|
|
46
|
+
onMembersReady: async (ctx) => {
|
|
47
|
+
const table = buildProxyRouteTable(config, ctx.memberEndpoints);
|
|
48
|
+
ctx.proxyRoutes = table;
|
|
49
|
+
const { createProxyServer } = await import("../proxy-BFR8GScT.mjs").then((n) => n.n);
|
|
50
|
+
const instance = await createProxyServer({
|
|
51
|
+
port: config.port,
|
|
52
|
+
host: config.host ?? "0.0.0.0",
|
|
53
|
+
publicUrl: config.publicUrl,
|
|
54
|
+
logger: ctx.logger ?? console
|
|
55
|
+
});
|
|
56
|
+
for (const route of table) instance.addRoute({
|
|
57
|
+
prefix: route.prefix,
|
|
58
|
+
upstream: new URL(route.upstream),
|
|
59
|
+
ws: route.ws,
|
|
60
|
+
source: route.source
|
|
61
|
+
});
|
|
62
|
+
ctx.proxyStop = () => instance.stop();
|
|
63
|
+
ctx.logger?.info(`[clint-proxy] listening on ${instance.url} — ${table.length} route(s)`);
|
|
64
|
+
},
|
|
65
|
+
onShutdown: async (ctx) => {
|
|
66
|
+
await ctx.proxyStop?.();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
//#endregion
|
|
9
72
|
//#region src/runners/clint-runner.ts
|
|
10
73
|
/**
|
|
11
74
|
* clint-runner (P5.4): the clint framework shell as a compound-kind runner.
|
|
@@ -76,6 +139,7 @@ async function startShell(host, ctx) {
|
|
|
76
139
|
const projectName = readProjectName(ctx.projectRoot, resolved.name);
|
|
77
140
|
const definitions = childServices(resolved, ctx, phCliEntry);
|
|
78
141
|
const eventBus = createEventBus();
|
|
142
|
+
const memberEndpoints = {};
|
|
79
143
|
const servicesDir = path.join(ctx.projectRoot, ".ph", "services");
|
|
80
144
|
const services = createServiceManager(definitions, {
|
|
81
145
|
config: {},
|
|
@@ -93,6 +157,10 @@ async function startShell(host, ctx) {
|
|
|
93
157
|
continue;
|
|
94
158
|
}
|
|
95
159
|
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
|
+
};
|
|
96
164
|
if (memberPort !== void 0 && !await isPortFree(memberPort)) {
|
|
97
165
|
console.log(`[${resolved.name}] ${id}: port ${memberPort} already serving — re-attached`);
|
|
98
166
|
continue;
|
|
@@ -109,10 +177,20 @@ async function startShell(host, ctx) {
|
|
|
109
177
|
const status = services.list(id).find((s) => s.serviceId === id);
|
|
110
178
|
if (status) console.log(` ${formatStatus(status)}`);
|
|
111
179
|
}
|
|
180
|
+
const pluginEntries = resolved.runner.plugins;
|
|
181
|
+
const resolvedPlugins = pluginEntries ? (await resolveHostPlugins(ctx.projectRoot, "compound", ctx.verb ?? "run", pluginEntries, `hosts/${host.name}/host.js`)).map((r) => r.plugin) : [];
|
|
182
|
+
const proxyBlock = resolved.runner.proxy;
|
|
183
|
+
if (proxyBlock && typeof proxyBlock === "object") resolvedPlugins.push(createProxyPlugin(proxyBlock));
|
|
184
|
+
const compoundCtx = {
|
|
185
|
+
memberEndpoints,
|
|
186
|
+
logger: { info: (m) => console.log(m) }
|
|
187
|
+
};
|
|
188
|
+
if (resolvedPlugins.length > 0) await runObserveHook("onMembersReady", resolvedPlugins, compoundCtx);
|
|
112
189
|
const agents = {};
|
|
113
190
|
for (const [name, ref] of Object.entries(config.agents ?? {})) agents[name] = await resolveAgentEndpoint(ref, ctx);
|
|
114
191
|
if (Object.keys(agents).length > 0) console.log(`[${resolved.name}] agents: ${Object.entries(agents).map(([n, u]) => `${n} → ${u}`).join(", ")}`);
|
|
115
192
|
const shutdown = async () => {
|
|
193
|
+
if (resolvedPlugins.length > 0) await runObserveHookSequential("onShutdown", resolvedPlugins, compoundCtx);
|
|
116
194
|
if (lifecycle === "attached") for (const id of names) try {
|
|
117
195
|
await services.stop(id);
|
|
118
196
|
} catch {}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clint-runner.mjs","names":[],"sources":["../../src/runners/clint-runner.ts"],"sourcesContent":["import { createInterface } from \"node:readline\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n compoundHostSchema,\n defaultUserDataDir,\n loadHost,\n probeRun,\n resolveUserDataPlaceholders,\n type HostDefinition,\n type RunnerContext,\n} from \"@powerhousedao/host-core\";\nimport fs from \"node:fs\";\nimport { createEventBus } from \"../core/events.js\";\nimport { isPortFree } from \"../core/preflight.js\";\nimport {\n createServiceManager,\n defineService,\n resolveServiceName,\n} 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 framework shell as a compound-kind runner.\n * Children declared in hosts/cli/host.js are SCHEDULED as clint services —\n * each member runs as `ph-cli run <member>` in its own (hidden) process with\n * state files, logs, readiness patterns and restart policies from the ported\n * services manager; `lifecycle: \"detached\"` (the default, clint's own\n * posture) leaves children running when the shell exits and re-attaches on\n * the next run, `\"attached\"` tears them down vetra-style.\n *\n * The agents manager (config.agents) maps names to OpenAI-compatible\n * endpoints — a sibling host reference resolves through that host's\n * runner.port (the mastra-runner serves /v1 there). `dev` adds a line chat\n * loop against the first agent; the full ink REPL remains the library path\n * (defineCli) for implementation projects, as scaffolded clint CLIs use it\n * natively — noted in the phase-5 WBS.\n */\n\nexport const kind = \"compound\";\n\nexport const hostSchema = compoundHostSchema;\n\ninterface ChildWrapper {\n host: string;\n runner?: { port?: number } & Record<string, unknown>;\n config?: { readiness?: { pattern?: string; timeout?: number } } & Record<\n string,\n unknown\n >;\n}\n\ninterface AgentRef {\n host?: string;\n url?: string;\n}\n\ninterface CliHostConfig {\n agents?: Record<string, AgentRef>;\n startOrder?: string[];\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\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: HostDefinition,\n ctx: RunnerContext,\n phCliEntry: string,\n): ServiceDefinition<Record<string, unknown>>[] {\n const children = (host.children ?? {}) as Record<string, ChildWrapper>;\n return Object.entries(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 ?? 180_000,\n },\n }),\n );\n}\n\nasync function resolveAgentEndpoint(\n ref: AgentRef,\n ctx: RunnerContext,\n): Promise<string> {\n if (ref.url) return ref.url.replace(/\\/$/, \"\");\n if (ref.host) {\n const sibling = await loadHost(ctx.projectRoot, ref.host);\n const port = sibling.host.runner.port ?? 4910;\n return `http://127.0.0.1:${String(port)}/v1`;\n }\n throw new Error(\"agents entries need { host } or { url }\");\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\nexport interface CliRunHandle {\n services: ServiceManager;\n agents: Record<string, string>;\n shutdown: () => Promise<void>;\n}\n\nasync function startShell(\n host: HostDefinition,\n ctx: RunnerContext,\n): Promise<CliRunHandle> {\n const userData = defaultUserDataDir(ctx.projectRoot, ctx.env);\n const resolved = resolveUserDataPlaceholders(host, userData);\n const config = (resolved.config ?? {}) as CliHostConfig;\n const lifecycle =\n (resolved.runner.lifecycle as string | undefined) ?? \"detached\";\n\n const phCliEntry = resolvePhCliEntry(ctx.projectRoot);\n const children = (resolved.children ?? {}) as Record<string, ChildWrapper>;\n const projectName = readProjectName(ctx.projectRoot, resolved.name);\n const definitions = childServices(resolved, ctx, phCliEntry);\n const eventBus = createEventBus();\n const servicesDir = path.join(ctx.projectRoot, \".ph\", \"services\");\n const services = createServiceManager(definitions, {\n config: {},\n servicesDir,\n eventBus,\n });\n\n // Start order: config.startOrder first, then declaration order.\n const names = definitions.map((d) => d.id);\n const ordered = [\n ...(config.startOrder ?? []).filter((n) => names.includes(n)),\n ...names.filter((n) => !(config.startOrder ?? []).includes(n)),\n ];\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 = await loadHost(ctx.projectRoot, wrapper.host);\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 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 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 }\n\n const agents: Record<string, string> = {};\n for (const [name, ref] of Object.entries(config.agents ?? {})) {\n agents[name] = await resolveAgentEndpoint(ref, ctx);\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 (lifecycle === \"attached\") {\n for (const id of names) {\n try {\n await services.stop(id);\n } catch {\n // already stopped\n }\n }\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 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 return { services, agents, 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: HostDefinition,\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 as string | undefined) === \"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(\n host: HostDefinition,\n ctx: RunnerContext,\n): Promise<void> {\n const handle = await startShell(host, ctx);\n await chatLoop(handle.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: HostDefinition,\n ctx: RunnerContext,\n): Promise<void> {\n const { getVerb, resolveRunnerModule, validateHost } =\n await import(\"@powerhousedao/host-core\");\n const children = (host.children ?? {}) as Record<string, ChildWrapper>;\n for (const [name, wrapper] of Object.entries(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 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(member.host, { ...ctx, verb: \"build\" });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAa,OAAO;AAEpB,MAAa,aAAa;AAwB1B,MAAM,oBAAoB;;;AAI1B,SAAS,kBAAkB,aAA6B;CAItD,MAAM,UAHW,cACf,cAAc,KAAK,KAAK,aAAa,cAAc,CAAC,CAAC,CAAC,IAEjC,CAAC,CAAC,QAAQ,oCAAoC;CACrE,OAAO,KAAK,KAAK,KAAK,QAAQ,OAAO,GAAG,QAAQ,SAAS;AAC3D;AAEA,SAAS,cACP,MACA,KACA,YAC8C;CAC9C,MAAM,WAAY,KAAK,YAAY,CAAC;CACpC,OAAO,OAAO,QAAQ,QAAQ,CAAC,CAAC,KAAK,CAAC,MAAM,aAC1C,cAAc;EACZ,IAAI;EACJ;EACA,eAAe,SAAS,WAAW,QAAQ,QAAQ;EACnD,YAAY;GACV,iCAAiC;GACjC,kBAAkB,mBAAmB,IAAI,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AAY,KAAK,IAAI,QAAQ,KAAK,EAAE;EAC9D,MAAM,GAAG,OAAO,MAAM;GAAE,GAAG;GAAK,MAAM;EAAQ,CAAC;CACjD;AACF"}
|
|
1
|
+
{"version":3,"file":"clint-runner.mjs","names":[],"sources":["../../src/runners/proxy-plugin.ts","../../src/runners/clint-runner.ts"],"sourcesContent":["import type { HostPlugin } from \"@powerhousedao/host-core\";\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 the scheduled members, WebSocket-aware; member references resolve\n * through each child's runner.{host,port} (the agents-manager convention).\n * Declarative veneer over the clint package's createProxyServer; the route\n * table assembly is pure (buildProxyRouteTable) and unit-tested without\n * sockets.\n */\n\nexport interface ProxyPluginConfig {\n port: number;\n host?: string;\n publicUrl?: string;\n /** Route prefix -> target: a member reference (resolved to the child's\n * host:port) or an explicit upstream URL; optional path + ws. */\n routes: Record<\n string,\n {\n member?: string;\n upstream?: string;\n path?: string;\n ws?: boolean;\n }\n >;\n}\n\nexport interface ResolvedProxyRoute {\n prefix: string;\n upstream: string;\n ws: boolean;\n source: string;\n}\n\n/** Member endpoints the compound runner knows at onMemberReady: name ->\n * { host, port }. */\nexport type MemberEndpoints = Record<string, { host: string; port: number }>;\n\n/**\n * Pure route-table assembly: member refs become loopback upstreams via the\n * member's host:port (+ optional path); explicit upstreams pass through.\n * A member ref with no known endpoint throws naming the member — a routing\n * declaration that cannot resolve must fail loudly, not silently drop.\n */\nexport function buildProxyRouteTable(\n config: ProxyPluginConfig,\n members: MemberEndpoints,\n): ResolvedProxyRoute[] {\n const table: ResolvedProxyRoute[] = [];\n for (const [prefix, route] of Object.entries(config.routes)) {\n if (route.upstream) {\n table.push({\n prefix,\n upstream: `${route.upstream.replace(/\\/+$/, \"\")}${route.path ?? \"\"}`,\n ws: route.ws ?? false,\n source: `upstream:${route.upstream}`,\n });\n continue;\n }\n if (!route.member) {\n throw new Error(\n `proxy route \"${prefix}\" names neither a member nor an upstream.`,\n );\n }\n const endpoint = members[route.member];\n if (!endpoint) {\n throw new Error(\n `proxy route \"${prefix}\" references member \"${route.member}\", which has no resolved endpoint (known: ${Object.keys(members).join(\", \") || \"none\"}).`,\n );\n }\n const host = endpoint.host === \"0.0.0.0\" ? \"127.0.0.1\" : endpoint.host;\n table.push({\n prefix,\n upstream: `http://${host}:${endpoint.port}${route.path ?? \"\"}`,\n ws: route.ws ?? false,\n source: `member:${route.member}`,\n });\n }\n return table;\n}\n\nexport interface ClintCompoundContext {\n memberEndpoints: MemberEndpoints;\n proxyRoutes?: ResolvedProxyRoute[];\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, ctx.memberEndpoints);\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 } as never);\n }\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 { createInterface } from \"node:readline\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n compoundHostSchema,\n defaultUserDataDir,\n loadHost,\n probeRun,\n resolveUserDataPlaceholders,\n runObserveHook,\n runObserveHookSequential,\n resolveHostPlugins,\n type HostDefinition,\n type RunnerContext,\n} from \"@powerhousedao/host-core\";\nimport {\n createProxyPlugin,\n type ClintCompoundContext,\n type MemberEndpoints,\n} from \"./proxy-plugin.js\";\nimport fs from \"node:fs\";\nimport { createEventBus } from \"../core/events.js\";\nimport { isPortFree } from \"../core/preflight.js\";\nimport {\n createServiceManager,\n defineService,\n resolveServiceName,\n} 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 framework shell as a compound-kind runner.\n * Children declared in hosts/cli/host.js are SCHEDULED as clint services —\n * each member runs as `ph-cli run <member>` in its own (hidden) process with\n * state files, logs, readiness patterns and restart policies from the ported\n * services manager; `lifecycle: \"detached\"` (the default, clint's own\n * posture) leaves children running when the shell exits and re-attaches on\n * the next run, `\"attached\"` tears them down vetra-style.\n *\n * The agents manager (config.agents) maps names to OpenAI-compatible\n * endpoints — a sibling host reference resolves through that host's\n * runner.port (the mastra-runner serves /v1 there). `dev` adds a line chat\n * loop against the first agent; the full ink REPL remains the library path\n * (defineCli) for implementation projects, as scaffolded clint CLIs use it\n * natively — noted in the phase-5 WBS.\n */\n\nexport const kind = \"compound\";\n\nexport const hostSchema = compoundHostSchema;\n\ninterface ChildWrapper {\n host: string;\n runner?: { port?: number } & Record<string, unknown>;\n config?: { readiness?: { pattern?: string; timeout?: number } } & Record<\n string,\n unknown\n >;\n}\n\ninterface AgentRef {\n host?: string;\n url?: string;\n}\n\ninterface CliHostConfig {\n agents?: Record<string, AgentRef>;\n startOrder?: string[];\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\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: HostDefinition,\n ctx: RunnerContext,\n phCliEntry: string,\n): ServiceDefinition<Record<string, unknown>>[] {\n const children = (host.children ?? {}) as Record<string, ChildWrapper>;\n return Object.entries(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 ?? 180_000,\n },\n }),\n );\n}\n\nasync function resolveAgentEndpoint(\n ref: AgentRef,\n ctx: RunnerContext,\n): Promise<string> {\n if (ref.url) return ref.url.replace(/\\/$/, \"\");\n if (ref.host) {\n const sibling = await loadHost(ctx.projectRoot, ref.host);\n const port = sibling.host.runner.port ?? 4910;\n return `http://127.0.0.1:${String(port)}/v1`;\n }\n throw new Error(\"agents entries need { host } or { url }\");\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\nexport interface CliRunHandle {\n services: ServiceManager;\n agents: Record<string, string>;\n shutdown: () => Promise<void>;\n}\n\nasync function startShell(\n host: HostDefinition,\n ctx: RunnerContext,\n): Promise<CliRunHandle> {\n const userData = defaultUserDataDir(ctx.projectRoot, ctx.env);\n const resolved = resolveUserDataPlaceholders(host, userData);\n const config = (resolved.config ?? {}) as CliHostConfig;\n const lifecycle =\n (resolved.runner.lifecycle as string | undefined) ?? \"detached\";\n\n const phCliEntry = resolvePhCliEntry(ctx.projectRoot);\n const children = (resolved.children ?? {}) as Record<string, ChildWrapper>;\n const projectName = readProjectName(ctx.projectRoot, resolved.name);\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 memberEndpoints: MemberEndpoints = {};\n const servicesDir = path.join(ctx.projectRoot, \".ph\", \"services\");\n const services = createServiceManager(definitions, {\n config: {},\n servicesDir,\n eventBus,\n });\n\n // Start order: config.startOrder first, then declaration order.\n const names = definitions.map((d) => d.id);\n const ordered = [\n ...(config.startOrder ?? []).filter((n) => names.includes(n)),\n ...names.filter((n) => !(config.startOrder ?? []).includes(n)),\n ];\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 = await loadHost(ctx.projectRoot, wrapper.host);\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) {\n const memberHost =\n (typeof wrapper.runner?.host === \"string\" && wrapper.runner.host) ||\n (typeof member.host.runner.host === \"string\" &&\n member.host.runner.host) ||\n \"127.0.0.1\";\n memberEndpoints[id] = { host: memberHost, port: memberPort };\n }\n if (memberPort !== undefined && !(await isPortFree(memberPort))) {\n console.log(\n `[${resolved.name}] ${id}: port ${memberPort} already serving — re-attached`,\n );\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 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 }\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 as { plugins?: unknown }).plugins as\n | Parameters<typeof resolveHostPlugins>[3]\n | undefined;\n const resolvedPlugins = pluginEntries\n ? (\n await resolveHostPlugins(\n ctx.projectRoot,\n \"compound\",\n ctx.verb ?? \"run\",\n pluginEntries,\n `hosts/${host.name}/host.js`,\n )\n ).map((r) => r.plugin)\n : [];\n const proxyBlock = (resolved.runner as { proxy?: unknown }).proxy;\n if (proxyBlock && typeof proxyBlock === \"object\") {\n resolvedPlugins.push(createProxyPlugin(proxyBlock as never) as never);\n }\n const compoundCtx: ClintCompoundContext = {\n memberEndpoints,\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, ref] of Object.entries(config.agents ?? {})) {\n agents[name] = await resolveAgentEndpoint(ref, ctx);\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 for (const id of names) {\n try {\n await services.stop(id);\n } catch {\n // already stopped\n }\n }\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 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 return { services, agents, 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: HostDefinition,\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 as string | undefined) === \"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(\n host: HostDefinition,\n ctx: RunnerContext,\n): Promise<void> {\n const handle = await startShell(host, ctx);\n await chatLoop(handle.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: HostDefinition,\n ctx: RunnerContext,\n): Promise<void> {\n const { getVerb, resolveRunnerModule, validateHost } =\n await import(\"@powerhousedao/host-core\");\n const children = (host.children ?? {}) as Record<string, ChildWrapper>;\n for (const [name, wrapper] of Object.entries(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 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(member.host, { ...ctx, verb: \"build\" });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA8CA,SAAgB,qBACd,QACA,SACsB;CACtB,MAAM,QAA8B,CAAC;CACrC,KAAK,MAAM,CAAC,QAAQ,UAAU,OAAO,QAAQ,OAAO,MAAM,GAAG;EAC3D,IAAI,MAAM,UAAU;GAClB,MAAM,KAAK;IACT;IACA,UAAU,GAAG,MAAM,SAAS,QAAQ,QAAQ,EAAE,IAAI,MAAM,QAAQ;IAChE,IAAI,MAAM,MAAM;IAChB,QAAQ,YAAY,MAAM;GAC5B,CAAC;GACD;EACF;EACA,IAAI,CAAC,MAAM,QACT,MAAM,IAAI,MACR,gBAAgB,OAAO,0CACzB;EAEF,MAAM,WAAW,QAAQ,MAAM;EAC/B,IAAI,CAAC,UACH,MAAM,IAAI,MACR,gBAAgB,OAAO,uBAAuB,MAAM,OAAO,4CAA4C,OAAO,KAAK,OAAO,CAAC,CAAC,KAAK,IAAI,KAAK,OAAO,GACnJ;EAEF,MAAM,OAAO,SAAS,SAAS,YAAY,cAAc,SAAS;EAClE,MAAM,KAAK;GACT;GACA,UAAU,UAAU,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OAAO,KAAK,GAAG;EAClD;CACF;CACA,GAAG,MAAM;AACX;AAEA,eAAsB,IACpB,MACA,KACuB;CACvB,MAAM,SAAS,MAAM,WAAW,MAAM,GAAG;CACzC,QAAQ,IACN,IAAI,KAAK,KAAK,yBACD,KAAK,KAAK,kCAClB,KAAK,OAAO,cAAqC,aAC9C,uBACA,0BACL,GACL;CACA,OAAO;AACT;AAEA,MAAa,QAAQ;;AAGrB,eAAsB,IACpB,MACA,KACe;CACf,MAAM,SAAS,MAAM,WAAW,MAAM,GAAG;CACzC,MAAM,SAAS,OAAO,MAAM;CAC5B,MAAM,OAAO,SAAS;AACxB;;;;AAKA,eAAsB,MACpB,MACA,KACe;CACf,MAAM,EAAE,SAAS,qBAAqB,iBACpC,MAAM,OAAO;CACf,MAAM,WAAY,KAAK,YAAY,CAAC;CACpC,KAAK,MAAM,CAAC,MAAM,YAAY,OAAO,QAAQ,QAAQ,GAAG;EACtD,MAAM,SAAS,MAAM,SAAS,IAAI,aAAa,QAAQ,IAAI;EAC3D,MAAM,YAAY,OAAO,KAAK,OAAO;EACrC,MAAM,SAAS,MAAM,oBAAoB,IAAI,aAAa,SAAS;EACnE,aACE,QACA,WACA,OAAO,MACP,SAAS,QAAQ,KAAK,SACxB;EACA,MAAM,KAAK,QAAQ,QAAQ,WAAW,OAAO;EAC7C,QAAQ,IAAI,IAAI,KAAK,KAAK,YAAY,KAAK,IAAI,QAAQ,KAAK,EAAE;EAC9D,MAAM,GAAG,OAAO,MAAM;GAAE,GAAG;GAAK,MAAM;EAAQ,CAAC;CACjD;AACF"}
|
|
@@ -17,6 +17,13 @@ export declare const hostSchema: import("zod").ZodObject<{
|
|
|
17
17
|
module: import("zod").ZodString;
|
|
18
18
|
defaultVerb: import("zod").ZodOptional<import("zod").ZodString>;
|
|
19
19
|
port: import("zod").ZodOptional<import("zod").ZodNumber>;
|
|
20
|
+
host: import("zod").ZodOptional<import("zod").ZodString>;
|
|
21
|
+
plugins: import("zod").ZodOptional<import("zod").ZodArray<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodObject<{
|
|
22
|
+
module: import("zod").ZodString;
|
|
23
|
+
enabled: import("zod").ZodOptional<import("zod").ZodBoolean>;
|
|
24
|
+
verbs: import("zod").ZodOptional<import("zod").ZodUnion<readonly [import("zod").ZodLiteral<"*">, import("zod").ZodArray<import("zod").ZodString>]>>;
|
|
25
|
+
config: import("zod").ZodOptional<import("zod").ZodRecord<import("zod").ZodString, import("zod").ZodUnknown>>;
|
|
26
|
+
}, import("zod/v4/core").$strict>]>>>;
|
|
20
27
|
}, import("zod/v4/core").$loose>;
|
|
21
28
|
config: import("zod").ZodOptional<import("zod").ZodObject<{}, import("zod/v4/core").$loose>>;
|
|
22
29
|
profile: import("zod").ZodOptional<import("zod").ZodObject<{
|
|
@@ -54,12 +61,18 @@ export declare const hostSchema: import("zod").ZodObject<{
|
|
|
54
61
|
host: import("zod").ZodOptional<import("zod").ZodString>;
|
|
55
62
|
url: import("zod").ZodOptional<import("zod").ZodString>;
|
|
56
63
|
}, import("zod/v4/core").$strict>>;
|
|
64
|
+
projection: import("zod").ZodOptional<import("zod").ZodObject<{
|
|
65
|
+
enabled: import("zod").ZodOptional<import("zod").ZodBoolean>;
|
|
66
|
+
dbPoolSize: import("zod").ZodOptional<import("zod").ZodNumber>;
|
|
67
|
+
}, import("zod/v4/core").$strict>>;
|
|
68
|
+
executors: import("zod").ZodOptional<import("zod").ZodObject<{
|
|
69
|
+
numWorkers: import("zod").ZodOptional<import("zod").ZodUnion<readonly [import("zod").ZodNumber, import("zod").ZodLiteral<"auto">]>>;
|
|
70
|
+
}, import("zod/v4/core").$strict>>;
|
|
57
71
|
}, import("zod/v4/core").$strict>>>;
|
|
58
72
|
placement: import("zod").ZodOptional<import("zod").ZodObject<{
|
|
59
73
|
primary: import("zod").ZodOptional<import("zod").ZodString>;
|
|
60
74
|
default: import("zod").ZodOptional<import("zod").ZodObject<{}, import("zod/v4/core").$loose>>;
|
|
61
75
|
}, import("zod/v4/core").$strict>>;
|
|
62
|
-
workflows: import("zod").ZodOptional<import("zod").ZodBoolean>;
|
|
63
76
|
protocol: import("zod").ZodOptional<import("zod").ZodObject<{
|
|
64
77
|
featureFlags: import("zod").ZodOptional<import("zod").ZodObject<{
|
|
65
78
|
documentDecisions: import("zod").ZodOptional<import("zod").ZodBoolean>;
|
|
@@ -76,6 +89,38 @@ export declare const hostSchema: import("zod").ZodObject<{
|
|
|
76
89
|
refuse: "refuse";
|
|
77
90
|
}>>;
|
|
78
91
|
}, import("zod/v4/core").$strict>>;
|
|
92
|
+
workflows: import("zod").ZodOptional<import("zod").ZodBoolean>;
|
|
93
|
+
renown: import("zod").ZodOptional<import("zod").ZodObject<{
|
|
94
|
+
url: import("zod").ZodOptional<import("zod").ZodString>;
|
|
95
|
+
networkId: import("zod").ZodOptional<import("zod").ZodString>;
|
|
96
|
+
chainId: import("zod").ZodOptional<import("zod").ZodNumber>;
|
|
97
|
+
}, import("zod/v4/core").$strict>>;
|
|
98
|
+
packages: import("zod").ZodOptional<import("zod").ZodObject<{
|
|
99
|
+
registryUrl: import("zod").ZodOptional<import("zod").ZodString>;
|
|
100
|
+
}, import("zod/v4/core").$strict>>;
|
|
101
|
+
namespace: import("zod").ZodOptional<import("zod").ZodString>;
|
|
102
|
+
auth: import("zod").ZodOptional<import("zod").ZodObject<{
|
|
103
|
+
enabled: import("zod").ZodOptional<import("zod").ZodBoolean>;
|
|
104
|
+
admins: import("zod").ZodOptional<import("zod").ZodArray<import("zod").ZodString>>;
|
|
105
|
+
renown: import("zod").ZodOptional<import("zod").ZodObject<{}, import("zod/v4/core").$loose>>;
|
|
106
|
+
}, import("zod/v4/core").$strict>>;
|
|
107
|
+
drives: import("zod").ZodOptional<import("zod").ZodArray<import("zod").ZodObject<{
|
|
108
|
+
slug: import("zod").ZodString;
|
|
109
|
+
id: import("zod").ZodOptional<import("zod").ZodString>;
|
|
110
|
+
projectHash: import("zod").ZodOptional<import("zod").ZodBoolean>;
|
|
111
|
+
name: import("zod").ZodOptional<import("zod").ZodString>;
|
|
112
|
+
icon: import("zod").ZodOptional<import("zod").ZodString>;
|
|
113
|
+
preferredEditor: import("zod").ZodOptional<import("zod").ZodString>;
|
|
114
|
+
sharingType: import("zod").ZodOptional<import("zod").ZodEnum<{
|
|
115
|
+
private: "private";
|
|
116
|
+
public: "public";
|
|
117
|
+
shared: "shared";
|
|
118
|
+
}>>;
|
|
119
|
+
availableOffline: import("zod").ZodOptional<import("zod").ZodBoolean>;
|
|
120
|
+
remote: import("zod").ZodOptional<import("zod").ZodObject<{
|
|
121
|
+
url: import("zod").ZodString;
|
|
122
|
+
}, import("zod/v4/core").$strict>>;
|
|
123
|
+
}, import("zod/v4/core").$strict>>>;
|
|
79
124
|
}, import("zod/v4/core").$strict>>;
|
|
80
125
|
}, import("zod/v4/core").$loose>;
|
|
81
126
|
type ChatMessage = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mastra-runner.d.mts","names":[],"sources":["../../src/runners/mastra-runner.ts"],"mappings":";;;;;;;;;;;;qBAoCa;qBAEA,0BAAU
|
|
1
|
+
{"version":3,"file":"mastra-runner.d.mts","names":[],"sources":["../../src/runners/mastra-runner.ts"],"mappings":";;;;;;;;;;;;qBAoCa;qBAEA,0BAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;yBAAoB;KAyDtC;EAAgB;EAAc;;;;wBAInB,mBAAmB,UAAU;iBAqC5B;EACf;EACA,WAAW;EACX,OAAO;EACP,gBAAgB;;wBA2NI,IACpB,MAAM,gBACN,KAAK,gBACJ,QAAQ;qBAIE,cAAK;;wBAGI,MACpB,MAAM,gBACN,KAAK,gBACJ"}
|
|
@@ -185,13 +185,17 @@ async function serveAgent(host, ctx) {
|
|
|
185
185
|
return;
|
|
186
186
|
}
|
|
187
187
|
if (req.method === "GET" && url === "/v1/models") {
|
|
188
|
+
const profile = resolved.profile ?? {};
|
|
188
189
|
res.writeHead(200, { "content-type": "application/json" });
|
|
189
190
|
res.end(JSON.stringify({
|
|
190
191
|
object: "list",
|
|
191
192
|
data: [{
|
|
192
193
|
id: provider.modelId,
|
|
193
194
|
object: "model",
|
|
194
|
-
owned_by: "clint"
|
|
195
|
+
owned_by: "clint",
|
|
196
|
+
name: profile.name ?? resolved.name,
|
|
197
|
+
...profile.description ? { description: profile.description } : {},
|
|
198
|
+
...profile.icon ? { image: profile.icon } : {}
|
|
195
199
|
}]
|
|
196
200
|
}));
|
|
197
201
|
return;
|
|
@@ -294,7 +298,7 @@ const serve = run;
|
|
|
294
298
|
/** `build` — skill + agent-profile compilation (ph-clint-dev's pipeline). */
|
|
295
299
|
async function build(host, ctx) {
|
|
296
300
|
const config = host.config ?? {};
|
|
297
|
-
const { buildSkills } = await import("../build-skills-
|
|
301
|
+
const { buildSkills } = await import("../build-skills-C8MlDvTC.mjs");
|
|
298
302
|
const result = await buildSkills({
|
|
299
303
|
rootDir: ctx.projectRoot,
|
|
300
304
|
skillsDir: config.prompts?.skillsDir,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mastra-runner.mjs","names":[],"sources":["../../src/integrations/powerhouse/remote-reactor.ts","../../src/runners/agent-provider.ts","../../src/runners/mastra-runner.ts"],"sourcesContent":["import type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport type { ReactorProtocol } from \"@powerhousedao/host-core\";\n\n/**\n * P5.5 — the agent host's reactor is a REMOTE attach: a running switchboard,\n * reached over GraphQL, instead of the embedded PGlite reactor glued to the\n * CLI's lifetime. 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: DocumentModelModule[];\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 /** 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 vetra\\`, 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 token: string | undefined,\n timeoutMs: number,\n): Promise<Record<string, unknown> | undefined> {\n try {\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 await probeEndpoint(endpoint, timeoutMs);\n const remoteInfo = await readRemoteInfo(endpoint, options.token, timeoutMs);\n\n const { GraphQLReactorClient } =\n await import(\"@powerhousedao/reactor-browser/graphql-client\");\n const client = new GraphQLReactorClient({\n url: endpoint,\n documentModels: options.documentModels,\n ...(options.token\n ? { tokenProvider: () => Promise.resolve(options.token) }\n : {}),\n } as never);\n\n return { endpoint, client, remoteInfo };\n}\n","import type { StreamChunk } from \"../core/types.js\";\n\n/**\n * The mastra-runner's provider seam: a real Mastra agent when a model is\n * configured, and a DEMO provider otherwise — same posture as the ph-rupert\n * example: the host answers without an API key, loudly saying it is the demo.\n */\nexport interface AgentStreamProvider {\n readonly modelId: string;\n stream(\n prompt: string,\n options: { threadId: string },\n ): AsyncIterable<StreamChunk>;\n}\n\nexport function createDemoProvider(agentName: string): AgentStreamProvider {\n return {\n modelId: \"demo\",\n // eslint-disable-next-line require-yield -- single-chunk generator below\n async *stream(prompt: string) {\n const text =\n `You said: ${JSON.stringify(prompt.slice(0, 2000))}. ` +\n `I'm the ${agentName} demo agent — configure a model (host config ` +\n `\\`model\\`, provider API key in the environment) for real responses.`;\n yield { type: \"text-delta\", text } as StreamChunk;\n },\n };\n}\n\nexport interface MastraProviderOptions {\n agentName: string;\n instructions: string;\n /** Mastra model-router string, e.g. `anthropic/claude-sonnet-4-5`. */\n model: string;\n}\n\nexport async function createMastraProvider(\n options: MastraProviderOptions,\n): Promise<AgentStreamProvider> {\n const { Agent } = await import(\"@mastra/core/agent\");\n const { mapMastraStream } = await import(\"../integrations/mastra/stream.js\");\n const agent = new Agent({\n id: options.agentName,\n name: options.agentName,\n instructions: options.instructions,\n // Mastra's model router resolves provider/key from the environment.\n model: options.model as never,\n });\n return {\n modelId: options.model,\n async *stream(prompt: string, streamOptions: { threadId: string }) {\n const result = await agent.stream(prompt, {\n memory: undefined,\n threadId: streamOptions.threadId,\n } as never);\n yield* mapMastraStream(\n (result as { fullStream: AsyncIterable<unknown> }).fullStream as never,\n );\n },\n };\n}\n","import { randomUUID } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport { createServer, type Server } from \"node:http\";\nimport {\n defaultUserDataDir,\n loadHost,\n probeRun,\n reactorHostSchema,\n resolveUserDataPlaceholders,\n writeRunRecord,\n clearRunRecord,\n type HostDefinition,\n type ReactorConfig,\n type RunnerContext,\n} from \"@powerhousedao/host-core\";\nimport {\n attachRemoteReactor,\n type RemoteReactorAttachment,\n} from \"../integrations/powerhouse/remote-reactor.js\";\nimport {\n createDemoProvider,\n createMastraProvider,\n type AgentStreamProvider,\n} from \"./agent-provider.js\";\n\n/**\n * mastra-runner (P5.6): the headless agent host. Its reactor is a REMOTE\n * attach — a lone `remote` backend naming a running switchboard (by sibling\n * host reference or URL); it depends on that switchboard and never starts\n * one. `run`/`serve` expose an OpenAI-compatible chat-completions endpoint\n * (streaming SSE + non-streaming, stateless baseline — the caller owns\n * session state); without a configured model it answers as the DEMO agent.\n * `build` compiles skills and agent profiles (ph-clint-dev's pipeline,\n * ported).\n */\n\nexport const kind = \"reactor\";\n\nexport const hostSchema = reactorHostSchema;\n\ninterface AgentHostConfig {\n model?: string;\n instructions?: string;\n prompts?: {\n skillsDir?: string;\n agentsDir?: string;\n outDir?: string;\n };\n}\n\nconst DEFAULT_AGENT_PORT = 4910;\n\n/** Resolve the remote backend's switchboard url: `remote.url` as given, or a\n * sibling host reference (`remote.host`) whose runner.port names the port. */\nasync function resolveRemoteUrl(\n host: HostDefinition,\n ctx: RunnerContext,\n): Promise<string> {\n const reactor = host.reactor as ReactorConfig | undefined;\n const backends = Object.entries(reactor?.backends ?? {});\n const remote = backends.find(([, b]) => b.kind === \"remote\")?.[1];\n if (!remote) {\n throw new Error(\n `hosts/${host.name}: an agent host attaches to a RUNNING switchboard — ` +\n `declare a remote backend, e.g. reactor.backends.switchboard = ` +\n `{ kind: \"remote\", remote: { host: \"switchboard\" } }.`,\n );\n }\n const ref = remote.remote as { url?: string; host?: string } | undefined;\n if (ref?.url) return ref.url;\n if (ref?.host) {\n const sibling = await loadHost(ctx.projectRoot, ref.host);\n const port = sibling.host.runner.port;\n if (typeof port !== \"number\") {\n throw new Error(\n `hosts/${host.name}: sibling host \"${ref.host}\" declares no ` +\n `runner.port to derive the switchboard endpoint from — set one, or ` +\n `use remote.url.`,\n );\n }\n return `http://localhost:${port}/graphql`;\n }\n throw new Error(\n `hosts/${host.name}: the remote backend needs remote.url or a sibling ` +\n `remote.host reference.`,\n );\n}\n\ntype ChatMessage = { role: string; content: unknown };\n\n/** Baseline stateless mapping: the last user message is the prompt (string\n * or OpenAI content-part arrays flattened to their text parts). */\nexport function promptFromMessages(messages: ChatMessage[]): string {\n const lastUser = [...messages].reverse().find((m) => m.role === \"user\");\n const content = lastUser?.content;\n if (typeof content === \"string\") return content;\n if (Array.isArray(content)) {\n return content\n .map((part: { type?: string; text?: string }) =>\n part.type === \"text\" ? (part.text ?? \"\") : \"\",\n )\n .join(\"\");\n }\n return \"\";\n}\n\nasync function readBody(\n req: import(\"node:http\").IncomingMessage,\n): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of req) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nfunction completionChunk(\n id: string,\n model: string,\n delta: Record<string, unknown>,\n finish: string | null,\n): string {\n return `data: ${JSON.stringify({\n id,\n object: \"chat.completion.chunk\",\n created: Math.floor(Date.now() / 1000),\n model,\n choices: [{ index: 0, delta, finish_reason: finish }],\n })}\\n\\n`;\n}\n\nexport interface AgentServeHandle {\n port: number;\n endpoints: Record<string, string>;\n ready: Promise<void>;\n shutdown: () => Promise<void>;\n}\n\nasync function serveAgent(\n host: HostDefinition,\n ctx: RunnerContext,\n): Promise<AgentServeHandle> {\n const userData = defaultUserDataDir(ctx.projectRoot, ctx.env);\n const resolved = resolveUserDataPlaceholders(host, userData);\n const config = (resolved.config ?? {}) as AgentHostConfig;\n const port =\n typeof resolved.runner.port === \"number\"\n ? resolved.runner.port\n : DEFAULT_AGENT_PORT;\n\n // Single-instance lock, standalone-run parity with the compound.\n const projectName = (() => {\n try {\n return (\n (\n JSON.parse(\n fs.readFileSync(`${ctx.projectRoot}/package.json`, \"utf8\"),\n ) as { name?: string }\n ).name ?? host.name\n );\n } catch {\n return host.name;\n }\n })();\n const probe = probeRun(ctx.projectRoot, resolved.name, projectName);\n if (probe.status === \"live\") {\n throw new Error(\n `${resolved.name} is already running (pid ${probe.record.pid}).`,\n );\n }\n\n // The reactor: attach, loudly, before serving anything.\n const remoteUrl = await resolveRemoteUrl(resolved, ctx);\n const attachment: RemoteReactorAttachment = await attachRemoteReactor({\n url: remoteUrl,\n documentModels: [],\n });\n console.log(`[${resolved.name}] reactor attached: ${attachment.endpoint}`);\n\n // The agent: real Mastra when a model is configured, demo otherwise.\n let provider: AgentStreamProvider;\n if (config.model) {\n provider = await createMastraProvider({\n agentName: resolved.name,\n instructions:\n config.instructions ??\n `You are ${resolved.name}, a Powerhouse project agent.`,\n model: config.model,\n });\n } else {\n provider = createDemoProvider(resolved.name);\n }\n\n const server: Server = createServer((req, res) => {\n void (async () => {\n const url = (req.url ?? \"/\").split(\"?\")[0];\n if (req.method === \"GET\" && url === \"/ready\") {\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify({ ok: true, agent: resolved.name }));\n return;\n }\n if (req.method === \"GET\" && url === \"/v1/models\") {\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(\n JSON.stringify({\n object: \"list\",\n data: [\n { id: provider.modelId, object: \"model\", owned_by: \"clint\" },\n ],\n }),\n );\n return;\n }\n if (req.method === \"POST\" && url === \"/v1/chat/completions\") {\n let body: { messages?: ChatMessage[]; stream?: boolean };\n try {\n body = JSON.parse(await readBody(req)) as typeof body;\n } catch {\n res.writeHead(400, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify({ error: { message: \"invalid JSON body\" } }));\n return;\n }\n const prompt = promptFromMessages(body.messages ?? []);\n const id = `chatcmpl-${randomUUID()}`;\n const threadId = randomUUID(); // stateless baseline: the caller owns sessions\n\n if (body.stream) {\n res.writeHead(200, {\n \"content-type\": \"text/event-stream\",\n \"cache-control\": \"no-store\",\n connection: \"keep-alive\",\n });\n res.write(\n completionChunk(id, provider.modelId, { role: \"assistant\" }, null),\n );\n try {\n for await (const chunk of provider.stream(prompt, { threadId })) {\n if (chunk.type === \"text-delta\" && chunk.text) {\n res.write(\n completionChunk(\n id,\n provider.modelId,\n { content: chunk.text },\n null,\n ),\n );\n } else if (chunk.type === \"error\") {\n res.write(\n completionChunk(\n id,\n provider.modelId,\n {\n content: `\\n[agent error] ${String((chunk as { message?: unknown }).message ?? \"unknown\")}`,\n },\n null,\n ),\n );\n }\n }\n res.write(completionChunk(id, provider.modelId, {}, \"stop\"));\n res.write(\"data: [DONE]\\n\\n\");\n } finally {\n res.end();\n }\n return;\n }\n\n let text = \"\";\n for await (const chunk of provider.stream(prompt, { threadId })) {\n if (chunk.type === \"text-delta\" && chunk.text) text += chunk.text;\n }\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(\n JSON.stringify({\n id,\n object: \"chat.completion\",\n created: Math.floor(Date.now() / 1000),\n model: provider.modelId,\n choices: [\n {\n index: 0,\n message: { role: \"assistant\", content: text },\n finish_reason: \"stop\",\n },\n ],\n }),\n );\n return;\n }\n res.writeHead(404, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify({ error: { message: `no route: ${url}` } }));\n })().catch((error: unknown) => {\n if (!res.headersSent) res.writeHead(500);\n res.end(JSON.stringify({ error: { message: String(error) } }));\n });\n });\n\n const ready = new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(port, \"127.0.0.1\", () => resolve());\n });\n await ready;\n // The actual bound port (a requested 0 means \"any free port\").\n const boundPort = (server.address() as { port: number }).port;\n console.log(\n `[${resolved.name}] agent API (OpenAI-compatible): http://127.0.0.1:${boundPort}/v1 (model: ${provider.modelId})`,\n );\n\n writeRunRecord(ctx.projectRoot, {\n pid: process.pid,\n hostName: resolved.name,\n projectName,\n startedAt: new Date().toISOString(),\n members: {\n [resolved.name]: {\n port: boundPort,\n url: `http://127.0.0.1:${boundPort}/v1`,\n },\n },\n extra: { reactor: attachment.endpoint, model: provider.modelId },\n });\n const cleanup = () => clearRunRecord(ctx.projectRoot, resolved.name);\n process.once(\"exit\", cleanup);\n\n return {\n port: boundPort,\n endpoints: {\n openai: `http://127.0.0.1:${boundPort}/v1`,\n ready: `http://127.0.0.1:${boundPort}/ready`,\n },\n ready,\n shutdown: async () => {\n cleanup();\n await new Promise((resolve) => server.close(resolve));\n },\n };\n}\n\nexport async function run(\n host: HostDefinition,\n ctx: RunnerContext,\n): Promise<AgentServeHandle> {\n return serveAgent(host, ctx);\n}\n\nexport const serve = run;\n\n/** `build` — skill + agent-profile compilation (ph-clint-dev's pipeline). */\nexport async function build(\n host: HostDefinition,\n ctx: RunnerContext,\n): Promise<void> {\n const config = (host.config ?? {}) as AgentHostConfig;\n const { buildSkills } = await import(\"../dev/build-skills.js\");\n const result = await buildSkills({\n rootDir: ctx.projectRoot,\n skillsDir: config.prompts?.skillsDir,\n agentsDir: config.prompts?.agentsDir,\n outDir: config.prompts?.outDir,\n });\n console.log(\n `[${host.name}] compiled ${result.skills} skill(s), ${result.profiles} profile(s) → ${result.outDir}`,\n );\n}\n"],"mappings":";;;;;;AA6CA,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,iNAI5C,EAAE,MAAM,CACV;CACF;AACF;;;AAIA,eAAe,eACb,UACA,OACA,WAC8C;CAC9C,IAAI;EACF,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;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B,eAAe,IAAI,aAAa,SAAS,IAAI;CACnE,QAAQ,KAAK,QAAQ,OAAO;CAE5B,OAAO;EACL,MAAM;EACN,WAAW;GACT,QAAQ,oBAAoB,UAAU;GACtC,OAAO,oBAAoB,UAAU;EACvC;EACA;EACA,UAAU,YAAY;GACpB,QAAQ;GACR,MAAM,IAAI,SAAS,YAAY,OAAO,MAAM,OAAO,CAAC;EACtD;CACF;AACF;AAEA,eAAsB,IACpB,MACA,KAC2B;CAC3B,OAAO,WAAW,MAAM,GAAG;AAC7B;AAEA,MAAa,QAAQ;;AAGrB,eAAsB,MACpB,MACA,KACe;CACf,MAAM,SAAU,KAAK,UAAU,CAAC;CAChC,MAAM,EAAE,gBAAgB,MAAM,OAAO;CACrC,MAAM,SAAS,MAAM,YAAY;EAC/B,SAAS,IAAI;EACb,WAAW,OAAO,SAAS;EAC3B,WAAW,OAAO,SAAS;EAC3B,QAAQ,OAAO,SAAS;CAC1B,CAAC;CACD,QAAQ,IACN,IAAI,KAAK,KAAK,aAAa,OAAO,OAAO,aAAa,OAAO,SAAS,gBAAgB,OAAO,QAC/F;AACF"}
|
|
1
|
+
{"version":3,"file":"mastra-runner.mjs","names":[],"sources":["../../src/integrations/powerhouse/remote-reactor.ts","../../src/runners/agent-provider.ts","../../src/runners/mastra-runner.ts"],"sourcesContent":["import type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport type { ReactorProtocol } from \"@powerhousedao/host-core\";\n\n/**\n * P5.5 — the agent host's reactor is a REMOTE attach: a running switchboard,\n * reached over GraphQL, instead of the embedded PGlite reactor glued to the\n * CLI's lifetime. 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: DocumentModelModule[];\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 /** 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 vetra\\`, 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 token: string | undefined,\n timeoutMs: number,\n): Promise<Record<string, unknown> | undefined> {\n try {\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 await probeEndpoint(endpoint, timeoutMs);\n const remoteInfo = await readRemoteInfo(endpoint, options.token, timeoutMs);\n\n const { GraphQLReactorClient } =\n await import(\"@powerhousedao/reactor-browser/graphql-client\");\n const client = new GraphQLReactorClient({\n url: endpoint,\n documentModels: options.documentModels,\n ...(options.token\n ? { tokenProvider: () => Promise.resolve(options.token) }\n : {}),\n } as never);\n\n return { endpoint, client, remoteInfo };\n}\n","import type { StreamChunk } from \"../core/types.js\";\n\n/**\n * The mastra-runner's provider seam: a real Mastra agent when a model is\n * configured, and a DEMO provider otherwise — same posture as the ph-rupert\n * example: the host answers without an API key, loudly saying it is the demo.\n */\nexport interface AgentStreamProvider {\n readonly modelId: string;\n stream(\n prompt: string,\n options: { threadId: string },\n ): AsyncIterable<StreamChunk>;\n}\n\nexport function createDemoProvider(agentName: string): AgentStreamProvider {\n return {\n modelId: \"demo\",\n // eslint-disable-next-line require-yield -- single-chunk generator below\n async *stream(prompt: string) {\n const text =\n `You said: ${JSON.stringify(prompt.slice(0, 2000))}. ` +\n `I'm the ${agentName} demo agent — configure a model (host config ` +\n `\\`model\\`, provider API key in the environment) for real responses.`;\n yield { type: \"text-delta\", text } as StreamChunk;\n },\n };\n}\n\nexport interface MastraProviderOptions {\n agentName: string;\n instructions: string;\n /** Mastra model-router string, e.g. `anthropic/claude-sonnet-4-5`. */\n model: string;\n}\n\nexport async function createMastraProvider(\n options: MastraProviderOptions,\n): Promise<AgentStreamProvider> {\n const { Agent } = await import(\"@mastra/core/agent\");\n const { mapMastraStream } = await import(\"../integrations/mastra/stream.js\");\n const agent = new Agent({\n id: options.agentName,\n name: options.agentName,\n instructions: options.instructions,\n // Mastra's model router resolves provider/key from the environment.\n model: options.model as never,\n });\n return {\n modelId: options.model,\n async *stream(prompt: string, streamOptions: { threadId: string }) {\n const result = await agent.stream(prompt, {\n memory: undefined,\n threadId: streamOptions.threadId,\n } as never);\n yield* mapMastraStream(\n (result as { fullStream: AsyncIterable<unknown> }).fullStream as never,\n );\n },\n };\n}\n","import { randomUUID } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport { createServer, type Server } from \"node:http\";\nimport {\n defaultUserDataDir,\n loadHost,\n probeRun,\n reactorHostSchema,\n resolveUserDataPlaceholders,\n writeRunRecord,\n clearRunRecord,\n type HostDefinition,\n type ReactorConfig,\n type RunnerContext,\n} from \"@powerhousedao/host-core\";\nimport {\n attachRemoteReactor,\n type RemoteReactorAttachment,\n} from \"../integrations/powerhouse/remote-reactor.js\";\nimport {\n createDemoProvider,\n createMastraProvider,\n type AgentStreamProvider,\n} from \"./agent-provider.js\";\n\n/**\n * mastra-runner (P5.6): the headless agent host. Its reactor is a REMOTE\n * attach — a lone `remote` backend naming a running switchboard (by sibling\n * host reference or URL); it depends on that switchboard and never starts\n * one. `run`/`serve` expose an OpenAI-compatible chat-completions endpoint\n * (streaming SSE + non-streaming, stateless baseline — the caller owns\n * session state); without a configured model it answers as the DEMO agent.\n * `build` compiles skills and agent profiles (ph-clint-dev's pipeline,\n * ported).\n */\n\nexport const kind = \"reactor\";\n\nexport const hostSchema = reactorHostSchema;\n\n/**\n * host.js config for the agent host — OPERATOR SETTINGS only (rewire R5):\n * `model` selects the LLM; `instructions`/`prompts` shape the agent. Framework\n * KNOBS (maxSteps, cacheControl, memory tuning, untilIdle, tool allowlists)\n * stay in code, and the agent CARD (description/image) comes from the host's\n * `profile`, not here. An LLM API key is a SECRET — env only, never config.\n */\ninterface AgentHostConfig {\n model?: string;\n instructions?: string;\n prompts?: {\n skillsDir?: string;\n agentsDir?: string;\n outDir?: string;\n };\n}\n\nconst DEFAULT_AGENT_PORT = 4910;\n\n/** Resolve the remote backend's switchboard url: `remote.url` as given, or a\n * sibling host reference (`remote.host`) whose runner.port names the port. */\nasync function resolveRemoteUrl(\n host: HostDefinition,\n ctx: RunnerContext,\n): Promise<string> {\n const reactor = host.reactor as ReactorConfig | undefined;\n const backends = Object.entries(reactor?.backends ?? {});\n const remote = backends.find(([, b]) => b.kind === \"remote\")?.[1];\n if (!remote) {\n throw new Error(\n `hosts/${host.name}: an agent host attaches to a RUNNING switchboard — ` +\n `declare a remote backend, e.g. reactor.backends.switchboard = ` +\n `{ kind: \"remote\", remote: { host: \"switchboard\" } }.`,\n );\n }\n const ref = remote.remote as { url?: string; host?: string } | undefined;\n if (ref?.url) return ref.url;\n if (ref?.host) {\n const sibling = await loadHost(ctx.projectRoot, ref.host);\n const port = sibling.host.runner.port;\n if (typeof port !== \"number\") {\n throw new Error(\n `hosts/${host.name}: sibling host \"${ref.host}\" declares no ` +\n `runner.port to derive the switchboard endpoint from — set one, or ` +\n `use remote.url.`,\n );\n }\n return `http://localhost:${port}/graphql`;\n }\n throw new Error(\n `hosts/${host.name}: the remote backend needs remote.url or a sibling ` +\n `remote.host reference.`,\n );\n}\n\ntype ChatMessage = { role: string; content: unknown };\n\n/** Baseline stateless mapping: the last user message is the prompt (string\n * or OpenAI content-part arrays flattened to their text parts). */\nexport function promptFromMessages(messages: ChatMessage[]): string {\n const lastUser = [...messages].reverse().find((m) => m.role === \"user\");\n const content = lastUser?.content;\n if (typeof content === \"string\") return content;\n if (Array.isArray(content)) {\n return content\n .map((part: { type?: string; text?: string }) =>\n part.type === \"text\" ? (part.text ?? \"\") : \"\",\n )\n .join(\"\");\n }\n return \"\";\n}\n\nasync function readBody(\n req: import(\"node:http\").IncomingMessage,\n): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of req) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nfunction completionChunk(\n id: string,\n model: string,\n delta: Record<string, unknown>,\n finish: string | null,\n): string {\n return `data: ${JSON.stringify({\n id,\n object: \"chat.completion.chunk\",\n created: Math.floor(Date.now() / 1000),\n model,\n choices: [{ index: 0, delta, finish_reason: finish }],\n })}\\n\\n`;\n}\n\nexport interface AgentServeHandle {\n port: number;\n endpoints: Record<string, string>;\n ready: Promise<void>;\n shutdown: () => Promise<void>;\n}\n\nasync function serveAgent(\n host: HostDefinition,\n ctx: RunnerContext,\n): Promise<AgentServeHandle> {\n const userData = defaultUserDataDir(ctx.projectRoot, ctx.env);\n const resolved = resolveUserDataPlaceholders(host, userData);\n const config = (resolved.config ?? {}) as AgentHostConfig;\n const port =\n typeof resolved.runner.port === \"number\"\n ? resolved.runner.port\n : DEFAULT_AGENT_PORT;\n\n // Single-instance lock, standalone-run parity with the compound.\n const projectName = (() => {\n try {\n return (\n (\n JSON.parse(\n fs.readFileSync(`${ctx.projectRoot}/package.json`, \"utf8\"),\n ) as { name?: string }\n ).name ?? host.name\n );\n } catch {\n return host.name;\n }\n })();\n const probe = probeRun(ctx.projectRoot, resolved.name, projectName);\n if (probe.status === \"live\") {\n throw new Error(\n `${resolved.name} is already running (pid ${probe.record.pid}).`,\n );\n }\n\n // The reactor: attach, loudly, before serving anything.\n const remoteUrl = await resolveRemoteUrl(resolved, ctx);\n const attachment: RemoteReactorAttachment = await attachRemoteReactor({\n url: remoteUrl,\n documentModels: [],\n });\n console.log(`[${resolved.name}] reactor attached: ${attachment.endpoint}`);\n\n // The agent: real Mastra when a model is configured, demo otherwise.\n let provider: AgentStreamProvider;\n if (config.model) {\n provider = await createMastraProvider({\n agentName: resolved.name,\n instructions:\n config.instructions ??\n `You are ${resolved.name}, a Powerhouse project agent.`,\n model: config.model,\n });\n } else {\n provider = createDemoProvider(resolved.name);\n }\n\n const server: Server = createServer((req, res) => {\n void (async () => {\n const url = (req.url ?? \"/\").split(\"?\")[0];\n if (req.method === \"GET\" && url === \"/ready\") {\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify({ ok: true, agent: resolved.name }));\n return;\n }\n if (req.method === \"GET\" && url === \"/v1/models\") {\n // The agent card: id + model, plus description/image from the host's\n // profile (rewire R5 — identity lives in profile, not config).\n const profile = (resolved.profile ?? {}) as {\n description?: string;\n icon?: string;\n name?: string;\n };\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(\n JSON.stringify({\n object: \"list\",\n data: [\n {\n id: provider.modelId,\n object: \"model\",\n owned_by: \"clint\",\n name: profile.name ?? resolved.name,\n ...(profile.description\n ? { description: profile.description }\n : {}),\n ...(profile.icon ? { image: profile.icon } : {}),\n },\n ],\n }),\n );\n return;\n }\n if (req.method === \"POST\" && url === \"/v1/chat/completions\") {\n let body: { messages?: ChatMessage[]; stream?: boolean };\n try {\n body = JSON.parse(await readBody(req)) as typeof body;\n } catch {\n res.writeHead(400, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify({ error: { message: \"invalid JSON body\" } }));\n return;\n }\n const prompt = promptFromMessages(body.messages ?? []);\n const id = `chatcmpl-${randomUUID()}`;\n const threadId = randomUUID(); // stateless baseline: the caller owns sessions\n\n if (body.stream) {\n res.writeHead(200, {\n \"content-type\": \"text/event-stream\",\n \"cache-control\": \"no-store\",\n connection: \"keep-alive\",\n });\n res.write(\n completionChunk(id, provider.modelId, { role: \"assistant\" }, null),\n );\n try {\n for await (const chunk of provider.stream(prompt, { threadId })) {\n if (chunk.type === \"text-delta\" && chunk.text) {\n res.write(\n completionChunk(\n id,\n provider.modelId,\n { content: chunk.text },\n null,\n ),\n );\n } else if (chunk.type === \"error\") {\n res.write(\n completionChunk(\n id,\n provider.modelId,\n {\n content: `\\n[agent error] ${String((chunk as { message?: unknown }).message ?? \"unknown\")}`,\n },\n null,\n ),\n );\n }\n }\n res.write(completionChunk(id, provider.modelId, {}, \"stop\"));\n res.write(\"data: [DONE]\\n\\n\");\n } finally {\n res.end();\n }\n return;\n }\n\n let text = \"\";\n for await (const chunk of provider.stream(prompt, { threadId })) {\n if (chunk.type === \"text-delta\" && chunk.text) text += chunk.text;\n }\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(\n JSON.stringify({\n id,\n object: \"chat.completion\",\n created: Math.floor(Date.now() / 1000),\n model: provider.modelId,\n choices: [\n {\n index: 0,\n message: { role: \"assistant\", content: text },\n finish_reason: \"stop\",\n },\n ],\n }),\n );\n return;\n }\n res.writeHead(404, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify({ error: { message: `no route: ${url}` } }));\n })().catch((error: unknown) => {\n if (!res.headersSent) res.writeHead(500);\n res.end(JSON.stringify({ error: { message: String(error) } }));\n });\n });\n\n const ready = new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(port, \"127.0.0.1\", () => resolve());\n });\n await ready;\n // The actual bound port (a requested 0 means \"any free port\").\n const boundPort = (server.address() as { port: number }).port;\n console.log(\n `[${resolved.name}] agent API (OpenAI-compatible): http://127.0.0.1:${boundPort}/v1 (model: ${provider.modelId})`,\n );\n\n writeRunRecord(ctx.projectRoot, {\n pid: process.pid,\n hostName: resolved.name,\n projectName,\n startedAt: new Date().toISOString(),\n members: {\n [resolved.name]: {\n port: boundPort,\n url: `http://127.0.0.1:${boundPort}/v1`,\n },\n },\n extra: { reactor: attachment.endpoint, model: provider.modelId },\n });\n const cleanup = () => clearRunRecord(ctx.projectRoot, resolved.name);\n process.once(\"exit\", cleanup);\n\n return {\n port: boundPort,\n endpoints: {\n openai: `http://127.0.0.1:${boundPort}/v1`,\n ready: `http://127.0.0.1:${boundPort}/ready`,\n },\n ready,\n shutdown: async () => {\n cleanup();\n await new Promise((resolve) => server.close(resolve));\n },\n };\n}\n\nexport async function run(\n host: HostDefinition,\n ctx: RunnerContext,\n): Promise<AgentServeHandle> {\n return serveAgent(host, ctx);\n}\n\nexport const serve = run;\n\n/** `build` — skill + agent-profile compilation (ph-clint-dev's pipeline). */\nexport async function build(\n host: HostDefinition,\n ctx: RunnerContext,\n): Promise<void> {\n const config = (host.config ?? {}) as AgentHostConfig;\n const { buildSkills } = await import(\"../dev/build-skills.js\");\n const result = await buildSkills({\n rootDir: ctx.projectRoot,\n skillsDir: config.prompts?.skillsDir,\n agentsDir: config.prompts?.agentsDir,\n outDir: config.prompts?.outDir,\n });\n console.log(\n `[${host.name}] compiled ${result.skills} skill(s), ${result.profiles} profile(s) → ${result.outDir}`,\n );\n}\n"],"mappings":";;;;;;AA6CA,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,iNAI5C,EAAE,MAAM,CACV;CACF;AACF;;;AAIA,eAAe,eACb,UACA,OACA,WAC8C;CAC9C,IAAI;EAC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