@powerhousedao/clint 6.3.0-dev.9 → 6.4.0-next.0
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-DZIv63eB.mjs +77 -0
- package/dist/build-DZIv63eB.mjs.map +1 -0
- package/dist/{build-skills-BnqGyuCH.mjs → build-skills-BNEOn-cl.mjs} +15 -6
- package/dist/build-skills-BNEOn-cl.mjs.map +1 -0
- package/dist/dist--xzirmg-.mjs +655 -0
- package/dist/dist--xzirmg-.mjs.map +1 -0
- package/dist/glob-CGjvhxgW.mjs +48 -0
- package/dist/glob-CGjvhxgW.mjs.map +1 -0
- package/dist/index-C3-HSfKb.d.mts +389 -0
- package/dist/index-C3-HSfKb.d.mts.map +1 -0
- package/dist/index.d.mts +55 -303
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +7 -8
- package/dist/integrations/mastra/index.d.mts +248 -0
- package/dist/integrations/mastra/index.d.mts.map +1 -0
- package/dist/integrations/mastra/index.mjs +509 -0
- package/dist/integrations/mastra/index.mjs.map +1 -0
- package/dist/integrations/powerhouse/index.d.mts +4 -0
- package/dist/integrations/powerhouse/index.mjs +3 -0
- package/dist/markdown-BUeGwhbR.mjs +1588 -0
- package/dist/markdown-BUeGwhbR.mjs.map +1 -0
- package/dist/powerhouse-BDnj7kqd.mjs +1922 -0
- package/dist/powerhouse-BDnj7kqd.mjs.map +1 -0
- package/dist/{proxy-BFR8GScT.mjs → proxy-ji3EHzLn.mjs} +128 -28
- package/dist/proxy-ji3EHzLn.mjs.map +1 -0
- package/dist/remote-reactor-BQzq4yfO.mjs +69 -0
- package/dist/remote-reactor-BQzq4yfO.mjs.map +1 -0
- package/dist/{start-b7Mn2cxB.mjs → repl-Czb7u0x_.mjs} +6 -29
- package/dist/repl-Czb7u0x_.mjs.map +1 -0
- package/dist/runners/cli-runner.d.mts +339 -0
- package/dist/runners/cli-runner.d.mts.map +1 -0
- package/dist/runners/cli-runner.mjs +324 -0
- package/dist/runners/cli-runner.mjs.map +1 -0
- package/dist/runners/mastra-runner.d.mts +5 -3
- package/dist/runners/mastra-runner.d.mts.map +1 -1
- package/dist/runners/mastra-runner.mjs +10 -60
- package/dist/runners/mastra-runner.mjs.map +1 -1
- package/dist/runners/proxy-runner.d.mts +281 -0
- package/dist/runners/proxy-runner.d.mts.map +1 -0
- package/dist/runners/proxy-runner.mjs +91 -0
- package/dist/runners/proxy-runner.mjs.map +1 -0
- package/dist/schema-BEKAZGyT.mjs +47 -0
- package/dist/schema-BEKAZGyT.mjs.map +1 -0
- package/dist/{src-BebNN3xc.mjs → src-BehwgLP6.mjs} +395 -1481
- package/dist/src-BehwgLP6.mjs.map +1 -0
- package/dist/start-BHn9LIyX.mjs +37 -0
- package/dist/start-BHn9LIyX.mjs.map +1 -0
- package/dist/store-CxqB-OrX.mjs +101 -0
- package/dist/store-CxqB-OrX.mjs.map +1 -0
- package/dist/{stream-DVuufwIj.mjs → stream-BguHx7vC.mjs} +4 -2
- package/dist/{stream-DVuufwIj.mjs.map → stream-BguHx7vC.mjs.map} +1 -1
- package/dist/testing/index.d.mts +81 -0
- package/dist/testing/index.d.mts.map +1 -0
- package/dist/testing/index.mjs +131 -0
- package/dist/testing/index.mjs.map +1 -0
- package/dist/{types-CRkoD-Mm.d.mts → types-CF6GuPJd.d.mts} +241 -261
- package/dist/types-CF6GuPJd.d.mts.map +1 -0
- package/dist/types-CbHJ-ZnH.d.mts +60 -0
- package/dist/types-CbHJ-ZnH.d.mts.map +1 -0
- package/package.json +44 -25
- package/dist/build-skills-BnqGyuCH.mjs.map +0 -1
- package/dist/dist-CUltriBW.mjs +0 -1628
- package/dist/dist-CUltriBW.mjs.map +0 -1
- package/dist/drive-Bu9zoFrO.mjs +0 -85
- package/dist/drive-Bu9zoFrO.mjs.map +0 -1
- package/dist/esm-C1DOsF1a.mjs +0 -13140
- package/dist/esm-C1DOsF1a.mjs.map +0 -1
- package/dist/events-BnwGFTjv.mjs +0 -237
- package/dist/events-BnwGFTjv.mjs.map +0 -1
- package/dist/folders-BYO1Wqqb.mjs +0 -256
- package/dist/folders-BYO1Wqqb.mjs.map +0 -1
- package/dist/local-signer-EFzJV3bn.mjs +0 -128
- package/dist/local-signer-EFzJV3bn.mjs.map +0 -1
- package/dist/markdown-D-sP2zw_.mjs +0 -275
- package/dist/markdown-D-sP2zw_.mjs.map +0 -1
- package/dist/proxy-BFR8GScT.mjs.map +0 -1
- package/dist/proxy-routes-DP3ztsnS.mjs +0 -215
- package/dist/proxy-routes-DP3ztsnS.mjs.map +0 -1
- package/dist/reactor-C9VIUX1H.mjs +0 -51
- package/dist/reactor-C9VIUX1H.mjs.map +0 -1
- package/dist/runners/clint-runner.d.mts +0 -398
- package/dist/runners/clint-runner.d.mts.map +0 -1
- package/dist/runners/clint-runner.mjs +0 -519
- package/dist/runners/clint-runner.mjs.map +0 -1
- package/dist/services-9E-r0nWl.mjs +0 -999
- package/dist/services-9E-r0nWl.mjs.map +0 -1
- package/dist/src-BebNN3xc.mjs.map +0 -1
- package/dist/start-b7Mn2cxB.mjs.map +0 -1
- package/dist/subscriptions-CfiflAsI.mjs +0 -38
- package/dist/subscriptions-CfiflAsI.mjs.map +0 -1
- package/dist/switchboard-CyvOavqL.mjs +0 -57
- package/dist/switchboard-CyvOavqL.mjs.map +0 -1
- package/dist/types-CRkoD-Mm.d.mts.map +0 -1
|
@@ -1,13 +1,60 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
|
|
2
|
-
import { c as normalizeLoopbackHost, l as prefixMatches, o as deriveBasePath } from "./proxy-routes-DP3ztsnS.mjs";
|
|
3
2
|
import http from "node:http";
|
|
4
3
|
import httpProxy from "http-proxy";
|
|
4
|
+
//#region src/core/proxy-routes.ts
|
|
5
|
+
/**
|
|
6
|
+
* Match a route prefix against a request pathname on path-segment boundaries:
|
|
7
|
+
* the prefix matches only when the pathname equals it or continues with a `/`.
|
|
8
|
+
* A bare `startsWith` would let `/foobar` match a `/foo` route. The root prefix
|
|
9
|
+
* `/` matches everything. A prefix already carrying a trailing `/`
|
|
10
|
+
* (e.g. `/switchboard/attachments/`) matches `<prefix>` and `<prefix><rest>`
|
|
11
|
+
* without doubling the separator.
|
|
12
|
+
*/
|
|
13
|
+
function prefixMatches(prefix, pathname) {
|
|
14
|
+
if (prefix === "/") return true;
|
|
15
|
+
if (prefix.endsWith("/")) return pathname === prefix.slice(0, -1) || pathname.startsWith(prefix);
|
|
16
|
+
return pathname === prefix || pathname.startsWith(prefix + "/");
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Derive the mount base path from publicUrl's pathname. Returns '' for an
|
|
20
|
+
* absent/invalid/root pathname, otherwise a leading-slash, no-trailing-slash
|
|
21
|
+
* form ('/myagent'). Mirrors the trailing-slash stripping the proxy's
|
|
22
|
+
* advertised `url` applies, so the base path and `url` stay aligned.
|
|
23
|
+
*/
|
|
24
|
+
function deriveBasePath(publicUrl) {
|
|
25
|
+
const trimmed = publicUrl?.trim();
|
|
26
|
+
if (!trimmed) return "";
|
|
27
|
+
try {
|
|
28
|
+
const url = new URL(trimmed);
|
|
29
|
+
if (!/^https?:$/.test(url.protocol)) return "";
|
|
30
|
+
return url.pathname.replace(/\/+$/, "");
|
|
31
|
+
} catch {
|
|
32
|
+
return "";
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Rewrite a loopback `localhost` host to `127.0.0.1` so a pinned-family agent
|
|
37
|
+
* (autoSelectFamily:false) connects deterministically over IPv4 instead of
|
|
38
|
+
* racing `::1`/`127.0.0.1` (Happy-Eyeballs). Preserves any `:port`. Non-loopback
|
|
39
|
+
* hosts are returned unchanged.
|
|
40
|
+
*/
|
|
41
|
+
function normalizeLoopbackHost(host) {
|
|
42
|
+
const [hostname, ...rest] = host.split(":");
|
|
43
|
+
if (hostname.toLowerCase() === "localhost") return ["127.0.0.1", ...rest].join(":");
|
|
44
|
+
return host;
|
|
45
|
+
}
|
|
46
|
+
//#endregion
|
|
5
47
|
//#region src/core/proxy.ts
|
|
6
48
|
/**
|
|
7
|
-
*
|
|
49
|
+
* Reverse proxy — one front port routing path prefixes to upstreams (the
|
|
50
|
+
* server behind `@powerhousedao/clint/proxy-runner`).
|
|
8
51
|
* Uses http-proxy for HTTP + WebSocket forwarding.
|
|
9
52
|
*/
|
|
10
|
-
var proxy_exports = /* @__PURE__ */ __exportAll({
|
|
53
|
+
var proxy_exports = /* @__PURE__ */ __exportAll({
|
|
54
|
+
createProxyServer: () => createProxyServer,
|
|
55
|
+
safeEnd: () => safeEnd,
|
|
56
|
+
stripClientForwardedHost: () => stripClientForwardedHost
|
|
57
|
+
});
|
|
11
58
|
/**
|
|
12
59
|
* Compute the X-Forwarded-Prefix value to send upstream. `base` is the
|
|
13
60
|
* mount base path ('' | '/x') prepended so upstreams emitting absolute
|
|
@@ -34,7 +81,42 @@ function splitUrl(url) {
|
|
|
34
81
|
}
|
|
35
82
|
const DEFAULT_DRAIN_TIMEOUT_MS = 1e4;
|
|
36
83
|
/**
|
|
37
|
-
*
|
|
84
|
+
* Finish a client response without ever writing to one that has ended.
|
|
85
|
+
* - Nothing sent yet and still writable: write head + body.
|
|
86
|
+
* - Head already sent but not ended: end it (no second head, no body).
|
|
87
|
+
* - Already ended, or the client socket is gone: do nothing.
|
|
88
|
+
* Never throws: a client that went away is not an error for the proxy.
|
|
89
|
+
*/
|
|
90
|
+
function safeEnd(res, status, body, headers = { "Content-Type": "application/json" }) {
|
|
91
|
+
try {
|
|
92
|
+
if (res.writableEnded || res.destroyed) return;
|
|
93
|
+
if (!res.headersSent && res.writable) {
|
|
94
|
+
for (const name of res.getHeaderNames()) res.removeHeader(name);
|
|
95
|
+
res.writeHead(status, {
|
|
96
|
+
...headers,
|
|
97
|
+
"Content-Length": Buffer.byteLength(body)
|
|
98
|
+
});
|
|
99
|
+
res.end(body);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (res.headersSent) res.end();
|
|
103
|
+
} catch {}
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Drop a client-sent `x-forwarded-host` so http-proxy's xfwd sets it from the
|
|
107
|
+
* real incoming `Host` (it keeps an existing value: `xfh = xfh || host`).
|
|
108
|
+
* `changeOrigin` rewrites `Host` to the upstream, so `x-forwarded-host` is the
|
|
109
|
+
* only place upstreams see the browser's host — a client-chosen value there
|
|
110
|
+
* would defeat their Host checks (e.g. DNS-rebinding guards). An ingress in
|
|
111
|
+
* front preserves `Host`, so its public host still arrives.
|
|
112
|
+
* (`x-forwarded-for`/`-port`/`-proto` are appended to, never replaced, so the
|
|
113
|
+
* real hop is always present in them.)
|
|
114
|
+
*/
|
|
115
|
+
function stripClientForwardedHost(req) {
|
|
116
|
+
delete req.headers["x-forwarded-host"];
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Create and start a reverse proxy server.
|
|
38
120
|
*/
|
|
39
121
|
async function createProxyServer(options) {
|
|
40
122
|
const { host, logger } = options;
|
|
@@ -69,6 +151,14 @@ async function createProxyServer(options) {
|
|
|
69
151
|
});
|
|
70
152
|
proxy.on("proxyRes", (proxyRes, _req, res) => {
|
|
71
153
|
const serverRes = res;
|
|
154
|
+
const stopFeeding = () => {
|
|
155
|
+
proxyRes.unpipe(serverRes);
|
|
156
|
+
if (!proxyRes.destroyed && !proxyRes.readableEnded) proxyRes.destroy();
|
|
157
|
+
};
|
|
158
|
+
serverRes.once("close", stopFeeding);
|
|
159
|
+
serverRes.once("finish", () => {
|
|
160
|
+
if (!proxyRes.readableEnded) stopFeeding();
|
|
161
|
+
});
|
|
72
162
|
proxyRes.on("close", () => {
|
|
73
163
|
if (!proxyRes.readableEnded && !serverRes.writableEnded) serverRes.destroy();
|
|
74
164
|
});
|
|
@@ -85,16 +175,11 @@ async function createProxyServer(options) {
|
|
|
85
175
|
const code = err.code;
|
|
86
176
|
const status = code === "ETIMEDOUT" || code === "ECONNRESET" ? 504 : 502;
|
|
87
177
|
const message = status === 504 ? "Gateway Timeout" : "Bad Gateway";
|
|
88
|
-
if (res && "writeHead" in res) {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
error: message,
|
|
94
|
-
message: err.message
|
|
95
|
-
}));
|
|
96
|
-
} else if (!serverRes.writableEnded) serverRes.end();
|
|
97
|
-
} else if (res && "destroy" in res) res.destroy();
|
|
178
|
+
if (res && "writeHead" in res) safeEnd(res, status, JSON.stringify({
|
|
179
|
+
error: message,
|
|
180
|
+
message: err.message
|
|
181
|
+
}));
|
|
182
|
+
else if (res && "destroy" in res) res.destroy();
|
|
98
183
|
});
|
|
99
184
|
function matchRoute(pathname) {
|
|
100
185
|
for (const route of routes) if (route.exact && pathname === route.prefix) return route;
|
|
@@ -114,11 +199,17 @@ async function createProxyServer(options) {
|
|
|
114
199
|
return upstreamPath + suffix;
|
|
115
200
|
}
|
|
116
201
|
const server = http.createServer((req, res) => {
|
|
202
|
+
const logClientError = (what) => (err) => {
|
|
203
|
+
const code = err.code;
|
|
204
|
+
if (code === "ERR_STREAM_WRITE_AFTER_END" || code === "ERR_HTTP_HEADERS_SENT") logger.warn(`Proxy client ${what} error for ${req.url}: ${err.message}`);
|
|
205
|
+
else logger.debug(`Proxy client ${what} error for ${req.url}: ${err.message}`);
|
|
206
|
+
};
|
|
207
|
+
res.on("error", logClientError("response"));
|
|
208
|
+
req.on("error", logClientError("request"));
|
|
117
209
|
const [rawPath, query] = splitUrl(req.url ?? "/");
|
|
118
210
|
const stripped = stripBase(rawPath);
|
|
119
211
|
if (stripped === void 0) {
|
|
120
|
-
res
|
|
121
|
-
res.end(JSON.stringify({
|
|
212
|
+
safeEnd(res, 404, JSON.stringify({
|
|
122
213
|
error: "Not Found",
|
|
123
214
|
path: rawPath
|
|
124
215
|
}));
|
|
@@ -126,42 +217,49 @@ async function createProxyServer(options) {
|
|
|
126
217
|
}
|
|
127
218
|
const pathname = stripped;
|
|
128
219
|
if (pathname === "/_proxy/health") {
|
|
129
|
-
res
|
|
130
|
-
res.end(JSON.stringify({
|
|
220
|
+
safeEnd(res, 200, JSON.stringify({
|
|
131
221
|
ok: true,
|
|
132
222
|
routes: routes.length
|
|
133
223
|
}));
|
|
134
224
|
return;
|
|
135
225
|
}
|
|
136
226
|
if (pathname === "/_proxy/routes") {
|
|
137
|
-
res
|
|
138
|
-
res.end(JSON.stringify(routes.map((r) => ({
|
|
227
|
+
safeEnd(res, 200, JSON.stringify(routes.map((r) => ({
|
|
139
228
|
prefix: r.prefix,
|
|
140
229
|
upstream: r.upstream?.toString(),
|
|
141
230
|
ws: r.ws,
|
|
142
231
|
source: r.source,
|
|
143
232
|
...r.redirectTo ? { redirectTo: r.redirectTo } : {},
|
|
144
|
-
...r.exact ? { exact: true } : {}
|
|
233
|
+
...r.exact ? { exact: true } : {},
|
|
234
|
+
...r.unavailable ? { unavailable: true } : {}
|
|
145
235
|
}))));
|
|
146
236
|
return;
|
|
147
237
|
}
|
|
148
238
|
const route = matchRoute(pathname);
|
|
149
239
|
if (!route) {
|
|
150
|
-
res
|
|
151
|
-
res.end(JSON.stringify({
|
|
240
|
+
safeEnd(res, 404, JSON.stringify({
|
|
152
241
|
error: "Not Found",
|
|
153
242
|
path: pathname
|
|
154
243
|
}));
|
|
155
244
|
return;
|
|
156
245
|
}
|
|
157
246
|
if (route.redirectTo) {
|
|
158
|
-
res
|
|
159
|
-
|
|
247
|
+
safeEnd(res, 302, "", { Location: prefixRedirect(route.redirectTo) + query });
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
if (route.unavailable) {
|
|
251
|
+
safeEnd(res, 503, JSON.stringify({
|
|
252
|
+
error: "Service Unavailable",
|
|
253
|
+
message: "starting",
|
|
254
|
+
path: pathname
|
|
255
|
+
}), {
|
|
256
|
+
"Content-Type": "application/json",
|
|
257
|
+
"Retry-After": "2"
|
|
258
|
+
});
|
|
160
259
|
return;
|
|
161
260
|
}
|
|
162
261
|
if (!route.upstream) {
|
|
163
|
-
res
|
|
164
|
-
res.end(JSON.stringify({
|
|
262
|
+
safeEnd(res, 502, JSON.stringify({
|
|
165
263
|
error: "Bad Gateway",
|
|
166
264
|
message: "route has no upstream"
|
|
167
265
|
}));
|
|
@@ -173,6 +271,7 @@ async function createProxyServer(options) {
|
|
|
173
271
|
const forwardedPrefix = computeForwardedPrefix(route, basePath);
|
|
174
272
|
if (forwardedPrefix) req.headers["x-forwarded-prefix"] = forwardedPrefix;
|
|
175
273
|
else delete req.headers["x-forwarded-prefix"];
|
|
274
|
+
stripClientForwardedHost(req);
|
|
176
275
|
req.url = (targetPath || "/") + query;
|
|
177
276
|
proxy.web(req, res, {
|
|
178
277
|
target,
|
|
@@ -219,6 +318,7 @@ async function createProxyServer(options) {
|
|
|
219
318
|
const forwardedPrefix = computeForwardedPrefix(route, basePath);
|
|
220
319
|
if (forwardedPrefix) req.headers["x-forwarded-prefix"] = forwardedPrefix;
|
|
221
320
|
else delete req.headers["x-forwarded-prefix"];
|
|
321
|
+
stripClientForwardedHost(req);
|
|
222
322
|
req.url = (targetPath || "/") + query;
|
|
223
323
|
proxy.ws(req, socket, head, {
|
|
224
324
|
target,
|
|
@@ -299,4 +399,4 @@ async function createProxyServer(options) {
|
|
|
299
399
|
//#endregion
|
|
300
400
|
export { proxy_exports as n, createProxyServer as t };
|
|
301
401
|
|
|
302
|
-
//# sourceMappingURL=proxy-
|
|
402
|
+
//# sourceMappingURL=proxy-ji3EHzLn.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"proxy-ji3EHzLn.mjs","names":[],"sources":["../src/core/proxy-routes.ts","../src/core/proxy.ts"],"sourcesContent":["/**\n * The proxy server's route type and its pure path helpers. No side effects —\n * easily unit-testable.\n */\n\nexport interface ProxyRoute {\n /** URL path prefix matched against incoming requests (e.g. '/switchboard/graphql'). */\n prefix: string;\n /**\n * Upstream target URL (e.g. new URL('http://localhost:4001/graphql')).\n * Optional only for pure redirect routes (`redirectTo` set).\n */\n upstream?: URL;\n /** Whether WebSocket upgrade should be forwarded on this route. */\n ws: boolean;\n /** Origin label for route management (e.g. 'switchboard', 'service:my-svc'). */\n source: string;\n /**\n * When set, matching requests get a 302 to this location instead of being\n * proxied. No upstream connection is made.\n */\n redirectTo?: string;\n /**\n * Match the prefix exactly rather than as a `startsWith` prefix. Exact\n * routes are matched before prefix routes so a `'/'` redirect can coexist\n * with a `'/'` catch-all without shadowing longer prefixes.\n */\n exact?: boolean;\n /**\n * The upstream behind this prefix is still starting: matching requests get\n * 503 + Retry-After instead of being proxied. A 404 would tell clients the\n * endpoint does not exist, which some treat as permanent.\n */\n unavailable?: boolean;\n}\n\n/**\n * Match a route prefix against a request pathname on path-segment boundaries:\n * the prefix matches only when the pathname equals it or continues with a `/`.\n * A bare `startsWith` would let `/foobar` match a `/foo` route. The root prefix\n * `/` matches everything. A prefix already carrying a trailing `/`\n * (e.g. `/switchboard/attachments/`) matches `<prefix>` and `<prefix><rest>`\n * without doubling the separator.\n */\nexport function prefixMatches(prefix: string, pathname: string): boolean {\n if (prefix === \"/\") return true;\n if (prefix.endsWith(\"/\")) {\n return pathname === prefix.slice(0, -1) || pathname.startsWith(prefix);\n }\n return pathname === prefix || pathname.startsWith(prefix + \"/\");\n}\n\n/**\n * Derive the mount base path from publicUrl's pathname. Returns '' for an\n * absent/invalid/root pathname, otherwise a leading-slash, no-trailing-slash\n * form ('/myagent'). Mirrors the trailing-slash stripping the proxy's\n * advertised `url` applies, so the base path and `url` stay aligned.\n */\nexport function deriveBasePath(publicUrl: string | undefined): string {\n const trimmed = publicUrl?.trim();\n if (!trimmed) return \"\";\n try {\n const url = new URL(trimmed);\n // `new URL('localhost:8090')` parses with protocol 'localhost:' —\n // anything but http(s) is treated as invalid.\n if (!/^https?:$/.test(url.protocol)) return \"\";\n return url.pathname.replace(/\\/+$/, \"\");\n } catch {\n return \"\";\n }\n}\n\n/**\n * Rewrite a loopback `localhost` host to `127.0.0.1` so a pinned-family agent\n * (autoSelectFamily:false) connects deterministically over IPv4 instead of\n * racing `::1`/`127.0.0.1` (Happy-Eyeballs). Preserves any `:port`. Non-loopback\n * hosts are returned unchanged.\n */\nexport function normalizeLoopbackHost(host: string): string {\n const [hostname, ...rest] = host.split(\":\");\n if (hostname.toLowerCase() === \"localhost\") {\n return [\"127.0.0.1\", ...rest].join(\":\");\n }\n return host;\n}\n","/**\n * Reverse proxy — one front port routing path prefixes to upstreams (the\n * server behind `@powerhousedao/clint/proxy-runner`).\n * Uses http-proxy for HTTP + WebSocket forwarding.\n */\nimport http from \"node:http\";\nimport httpProxy from \"http-proxy\";\nimport type { Logger } from \"./types.js\";\nimport type { ProxyRoute } from \"./proxy-routes.js\";\nimport {\n deriveBasePath,\n normalizeLoopbackHost,\n prefixMatches,\n} from \"./proxy-routes.js\";\n\nexport interface ProxyServerOptions {\n /** Port to listen on (0 = auto-assign). */\n port: number;\n /** Bind address (default '0.0.0.0'). */\n host: string;\n /**\n * Browser-facing base URL when the proxy sits behind an ingress /\n * reverse proxy (e.g. `https://vetra-agent.<tenant>.vetra.io`). When\n * set, `url` returns this instead of the local listen address, so\n * everything composed from it is reachable from outside the pod.\n *\n * A non-root pathname mounts the whole proxy surface under that base\n * path (e.g. `https://host/myagent` → base path `/myagent`): incoming\n * requests carry the prefix, it is stripped before route matching, and\n * redirect Locations are re-prefixed with it.\n */\n publicUrl?: string;\n logger: Logger;\n}\n\nexport interface ProxyServerInstance {\n readonly port: number;\n readonly host: string;\n readonly url: string;\n addRoute(route: ProxyRoute): void;\n removeRoutesBySource(source: string): void;\n getRoutes(): ReadonlyArray<Readonly<ProxyRoute>>;\n stop(): Promise<void>;\n}\n\n/**\n * Compute the X-Forwarded-Prefix value to send upstream. `base` is the\n * mount base path ('' | '/x') prepended so upstreams emitting absolute\n * paths reconstruct the externally-visible prefix.\n */\nfunction computeForwardedPrefix(\n route: ProxyRoute,\n base: string,\n): string | undefined {\n if (!route.upstream) return undefined;\n const strip = (s: string) => s.replace(/\\/$/, \"\");\n const prefix = strip(route.prefix);\n const upstreamPath = strip(route.upstream.pathname);\n const routePrefix =\n upstreamPath && prefix.endsWith(upstreamPath)\n ? prefix.slice(0, -upstreamPath.length)\n : prefix;\n const result = base + routePrefix;\n return result || undefined;\n}\n\n// Upstream/incoming socket timeouts (ms), overridable via env. The proxy\n// fronts only loopback dev services that should answer in well under a second;\n// 30s upstream is generous headroom for a cold start yet fails fast on a dead\n// or silent upstream instead of hanging the client. Incoming client timeout is\n// looser (60s) to reap stuck/half-open clients without cutting slow uploads.\n// WS routes are not bound by proxyTimeout here (long-lived upgrades).\nfunction envMs(name: string, fallback: number): number {\n const raw = process.env[name];\n if (!raw) return fallback;\n const n = Number(raw);\n return Number.isFinite(n) && n >= 0 ? n : fallback;\n}\nconst DEFAULT_UPSTREAM_TIMEOUT_MS = 30_000;\nconst DEFAULT_INCOMING_TIMEOUT_MS = 60_000;\n\n// Split a request URL into pathname and query tail ('' or leading-'?').\n// Route matching and base stripping operate on the pathname only; the tail\n// is re-appended to the path forwarded upstream (and to redirect Locations).\nfunction splitUrl(url: string): [pathname: string, query: string] {\n const qIdx = url.indexOf(\"?\");\n return qIdx === -1 ? [url, \"\"] : [url.slice(0, qIdx), url.slice(qIdx)];\n}\n\n// Max time to wait for in-flight requests to finish on shutdown before\n// force-closing remaining sockets. Overridable via PH_PROXY_DRAIN_TIMEOUT_MS.\nconst DEFAULT_DRAIN_TIMEOUT_MS = 10_000;\n\n/**\n * Finish a client response without ever writing to one that has ended.\n * - Nothing sent yet and still writable: write head + body.\n * - Head already sent but not ended: end it (no second head, no body).\n * - Already ended, or the client socket is gone: do nothing.\n * Never throws: a client that went away is not an error for the proxy.\n */\nexport function safeEnd(\n res: http.ServerResponse,\n status: number,\n body: string,\n headers: http.OutgoingHttpHeaders = { \"Content-Type\": \"application/json\" },\n): void {\n try {\n if (res.writableEnded || res.destroyed) return;\n if (!res.headersSent && res.writable) {\n // Drop headers a half-processed upstream response may already have set\n // (e.g. its Content-Length), which would truncate or mislabel our body.\n for (const name of res.getHeaderNames()) res.removeHeader(name);\n res.writeHead(status, {\n ...headers,\n \"Content-Length\": Buffer.byteLength(body),\n });\n res.end(body);\n return;\n }\n // Head already sent: close the body. Nothing sent but not writable: leave\n // it alone (an end() here would emit an implicit 200).\n if (res.headersSent) res.end();\n } catch {\n // The response went away between the check and the write.\n }\n}\n\n/**\n * Drop a client-sent `x-forwarded-host` so http-proxy's xfwd sets it from the\n * real incoming `Host` (it keeps an existing value: `xfh = xfh || host`).\n * `changeOrigin` rewrites `Host` to the upstream, so `x-forwarded-host` is the\n * only place upstreams see the browser's host — a client-chosen value there\n * would defeat their Host checks (e.g. DNS-rebinding guards). An ingress in\n * front preserves `Host`, so its public host still arrives.\n * (`x-forwarded-for`/`-port`/`-proto` are appended to, never replaced, so the\n * real hop is always present in them.)\n */\nexport function stripClientForwardedHost(req: {\n headers: http.IncomingHttpHeaders;\n}): void {\n delete req.headers[\"x-forwarded-host\"];\n}\n\n/**\n * Create and start a reverse proxy server.\n */\nexport async function createProxyServer(\n options: ProxyServerOptions,\n): Promise<ProxyServerInstance> {\n const { host, logger } = options;\n let routes: ProxyRoute[] = [];\n // Idempotent stop: a duplicate signal during teardown must not re-drain.\n let stopped = false;\n\n // Base path the whole proxy surface is mounted under, derived from a\n // non-root pathname on publicUrl. Empty when serving from the origin\n // root. Normalized to a leading-slash, no-trailing-slash form ('' | '/x').\n const basePath = deriveBasePath(options.publicUrl);\n\n // Strip the base path from an incoming request path before route\n // matching. Requests that don't carry the prefix yield undefined so the\n // caller can 404 rather than mismatch a root route.\n function stripBase(pathname: string): string | undefined {\n if (!basePath) return pathname;\n if (!prefixMatches(basePath, pathname)) return undefined;\n return pathname === basePath ? \"/\" : pathname.slice(basePath.length);\n }\n\n // Re-prefix a root-relative redirect Location with the base path so the\n // browser stays under the mount. Absolute URLs and other-prefixed paths\n // pass through untouched.\n function prefixRedirect(location: string): string {\n if (!basePath) return location;\n if (!location.startsWith(\"/\") || location.startsWith(\"//\")) return location;\n if (prefixMatches(basePath, location)) return location;\n return basePath + location;\n }\n\n // Shared keep-alive agent for all upstreams (every target is loopback HTTP).\n // autoSelectFamily:false pins Node to the first resolved address; paired with\n // localhost→127.0.0.1 normalization on the target host so the pinned family\n // is deterministically IPv4 (avoids the Happy-Eyeballs dual-stack stall).\n const upstreamAgent = new http.Agent({\n keepAlive: true,\n autoSelectFamily: false,\n });\n\n const proxy = httpProxy.createProxyServer({\n xfwd: true,\n agent: upstreamAgent,\n proxyTimeout: envMs(\n \"PH_PROXY_UPSTREAM_TIMEOUT_MS\",\n DEFAULT_UPSTREAM_TIMEOUT_MS,\n ),\n timeout: envMs(\"PH_PROXY_INCOMING_TIMEOUT_MS\", DEFAULT_INCOMING_TIMEOUT_MS),\n });\n\n // Event streams legitimately go quiet between events; the fail-fast idle\n // timeouts (proxyTimeout/timeout) must not reap them. Clear both the\n // upstream and client socket idle timers for text/event-stream responses.\n proxy.on(\"proxyRes\", (proxyRes, _req, res) => {\n const contentType = String(\n proxyRes.headers[\"content-type\"] ?? \"\",\n ).toLowerCase();\n if (!contentType.includes(\"text/event-stream\")) return;\n proxyRes.socket?.setTimeout(0);\n (res as http.ServerResponse).socket?.setTimeout(0);\n });\n\n // proxyTimeout fires mid-response as proxyReq.abort(); Node suppresses the\n // request 'error' after an explicit abort, so http-proxy's error handler\n // never runs and the client would hang on a truncated body. If the upstream\n // body closes without ending, tear down the client response (destroy, not\n // end — a clean end would mis-signal a complete chunked body).\n proxy.on(\"proxyRes\", (proxyRes, _req, res) => {\n const serverRes = res as http.ServerResponse;\n // Once the client response is done (ended by an error answer, or the\n // client went away) stop feeding it, so a late chunk is never written\n // to an ended response.\n const stopFeeding = () => {\n proxyRes.unpipe(serverRes);\n if (!proxyRes.destroyed && !proxyRes.readableEnded) proxyRes.destroy();\n };\n serverRes.once(\"close\", stopFeeding);\n serverRes.once(\"finish\", () => {\n if (!proxyRes.readableEnded) stopFeeding();\n });\n proxyRes.on(\"close\", () => {\n if (!proxyRes.readableEnded && !serverRes.writableEnded) {\n serverRes.destroy();\n }\n });\n });\n\n // Upstream 3xx responses pass through verbatim; under a base-path mount a\n // root-relative Location would escape the mount. Re-prefix it the same way\n // built-in redirect routes are (prefixRedirect: no-op at root mount, for\n // absolute/protocol-relative URLs, and for already-prefixed paths).\n // http-proxy emits 'proxyRes' before writing headers in default mode, so\n // mutating proxyRes.headers takes effect.\n proxy.on(\"proxyRes\", (proxyRes) => {\n const status = proxyRes.statusCode ?? 0;\n if (status < 300 || status >= 400) return;\n const location = proxyRes.headers.location;\n if (typeof location !== \"string\") return;\n proxyRes.headers.location = prefixRedirect(location);\n });\n\n proxy.on(\"error\", (err, req, res) => {\n logger.warn(`Proxy error for ${req.url}: ${err.message}`);\n // 504 on an upstream that accepted/connected but stalled past proxyTimeout\n // (http-proxy surfaces this as ECONNRESET/ETIMEDOUT); 502 on a refused or\n // unreachable connect. Default to 502 for anything else.\n const code = (err as NodeJS.ErrnoException).code;\n const status = code === \"ETIMEDOUT\" || code === \"ECONNRESET\" ? 504 : 502;\n const message = status === 504 ? \"Gateway Timeout\" : \"Bad Gateway\";\n // Guard against double-send: the response may be a WS socket, or headers\n // may already be in flight from a partially-streamed response.\n if (res && \"writeHead\" in res) {\n safeEnd(\n res as http.ServerResponse,\n status,\n JSON.stringify({ error: message, message: err.message }),\n );\n } else if (res && \"destroy\" in res) {\n (res as import(\"node:net\").Socket).destroy();\n }\n });\n\n function matchRoute(pathname: string): ProxyRoute | undefined {\n // Exact routes win first, so a `'/'` exact redirect fires only on the bare\n // root while `/assets/*`, `/d/<id>`, etc. fall through to prefix routes\n // (including a `'/'` catch-all).\n for (const route of routes) {\n if (route.exact && pathname === route.prefix) {\n return route;\n }\n }\n // Routes are kept sorted longest-prefix-first.\n for (const route of routes) {\n if (route.exact) continue;\n if (prefixMatches(route.prefix, pathname)) {\n return route;\n }\n }\n return undefined;\n }\n\n function sortRoutes(): void {\n routes.sort((a, b) => b.prefix.length - a.prefix.length);\n }\n\n function rewriteTarget(\n route: ProxyRoute,\n upstream: URL,\n requestPath: string,\n ): string {\n const suffix = requestPath.slice(route.prefix.length);\n const upstreamPath = upstream.pathname;\n // Avoid double slashes when both upstream ends with / and suffix starts with /\n if (upstreamPath.endsWith(\"/\") && suffix.startsWith(\"/\")) {\n return upstreamPath + suffix.slice(1);\n }\n // Ensure a separator when upstream doesn't end with / and suffix doesn't start with /\n if (\n !upstreamPath.endsWith(\"/\") &&\n suffix.length > 0 &&\n !suffix.startsWith(\"/\")\n ) {\n return upstreamPath + \"/\" + suffix;\n }\n return upstreamPath + suffix;\n }\n\n const server = http.createServer((req, res) => {\n // A write that lands on a response after it ended (or after the client\n // left) is reported as an 'error' event on the response; without a\n // listener that would be an uncaught exception.\n const logClientError = (what: string) => (err: Error) => {\n const code = (err as NodeJS.ErrnoException).code;\n // These two mean the proxy itself wrote at the wrong time; client\n // resets (ECONNRESET etc.) are routine.\n if (\n code === \"ERR_STREAM_WRITE_AFTER_END\" ||\n code === \"ERR_HTTP_HEADERS_SENT\"\n ) {\n logger.warn(\n `Proxy client ${what} error for ${req.url}: ${err.message}`,\n );\n } else {\n logger.debug(\n `Proxy client ${what} error for ${req.url}: ${err.message}`,\n );\n }\n };\n res.on(\"error\", logClientError(\"response\"));\n req.on(\"error\", logClientError(\"request\"));\n const [rawPath, query] = splitUrl(req.url ?? \"/\");\n const stripped = stripBase(rawPath);\n if (stripped === undefined) {\n safeEnd(res, 404, JSON.stringify({ error: \"Not Found\", path: rawPath }));\n return;\n }\n const pathname = stripped;\n\n // Built-in health endpoint\n if (pathname === \"/_proxy/health\") {\n safeEnd(res, 200, JSON.stringify({ ok: true, routes: routes.length }));\n return;\n }\n\n // Built-in debug endpoint\n if (pathname === \"/_proxy/routes\") {\n safeEnd(\n res,\n 200,\n JSON.stringify(\n routes.map((r) => ({\n prefix: r.prefix,\n upstream: r.upstream?.toString(),\n ws: r.ws,\n source: r.source,\n ...(r.redirectTo ? { redirectTo: r.redirectTo } : {}),\n ...(r.exact ? { exact: true } : {}),\n ...(r.unavailable ? { unavailable: true } : {}),\n })),\n ),\n );\n return;\n }\n\n const route = matchRoute(pathname);\n if (!route) {\n safeEnd(res, 404, JSON.stringify({ error: \"Not Found\", path: pathname }));\n return;\n }\n\n if (route.redirectTo) {\n safeEnd(res, 302, \"\", {\n Location: prefixRedirect(route.redirectTo) + query,\n });\n return;\n }\n\n if (route.unavailable) {\n safeEnd(\n res,\n 503,\n JSON.stringify({\n error: \"Service Unavailable\",\n message: \"starting\",\n path: pathname,\n }),\n { \"Content-Type\": \"application/json\", \"Retry-After\": \"2\" },\n );\n return;\n }\n\n if (!route.upstream) {\n safeEnd(\n res,\n 502,\n JSON.stringify({\n error: \"Bad Gateway\",\n message: \"route has no upstream\",\n }),\n );\n return;\n }\n\n const upstream = route.upstream;\n const targetPath = rewriteTarget(route, upstream, pathname);\n const target = `${upstream.protocol}//${normalizeLoopbackHost(upstream.host)}`;\n\n const forwardedPrefix = computeForwardedPrefix(route, basePath);\n if (forwardedPrefix) {\n req.headers[\"x-forwarded-prefix\"] = forwardedPrefix;\n } else {\n delete req.headers[\"x-forwarded-prefix\"];\n }\n stripClientForwardedHost(req);\n req.url = (targetPath || \"/\") + query;\n proxy.web(req, res, { target, changeOrigin: true });\n });\n\n // Errors on accepted client sockets (resets, aborts) must surface on the\n // socket, never as an uncaught exception: destroy and move on.\n server.on(\"connection\", (socket) => {\n socket.on(\"error\", (err) => {\n logger.debug(`Proxy client socket error: ${err.message}`);\n socket.destroy();\n });\n });\n\n // Malformed or aborted requests before a response object exists: answer 400\n // when the socket is still usable, otherwise just drop it.\n server.on(\"clientError\", (err, socket) => {\n logger.debug(`Proxy client error: ${err.message}`);\n if (\n (err as NodeJS.ErrnoException).code !== \"ECONNRESET\" &&\n socket.writable\n ) {\n socket.end(\"HTTP/1.1 400 Bad Request\\r\\n\\r\\n\");\n return;\n }\n socket.destroy();\n });\n\n // Tracked upgrade/WS client sockets, closed on drain so a long-lived socket\n // can't block shutdown indefinitely.\n const upgradeSockets = new Set<import(\"node:stream\").Duplex>();\n\n // WebSocket upgrade handling\n server.on(\"upgrade\", (req, socket, head) => {\n upgradeSockets.add(socket);\n socket.on(\"close\", () => upgradeSockets.delete(socket));\n // http-proxy only attaches its client-socket error handler after the\n // upstream upgrade succeeds; a client reset during the handshake would\n // otherwise surface as an unhandled 'error' and crash the process. Attach\n // ours first, before any validation or proxy.ws().\n socket.on(\"error\", (err) => {\n logger.warn(\n `Proxy WS client socket error for ${req.url}: ${err.message}`,\n );\n socket.destroy();\n });\n\n const [rawPath, query] = splitUrl(req.url ?? \"/\");\n const stripped = stripBase(rawPath);\n if (stripped === undefined) {\n socket.destroy();\n return;\n }\n const pathname = stripped;\n const route = matchRoute(pathname);\n\n if (!route || !route.ws || !route.upstream) {\n socket.destroy();\n return;\n }\n\n const upstream = route.upstream;\n const targetPath = rewriteTarget(route, upstream, pathname);\n const target = `${upstream.protocol}//${normalizeLoopbackHost(upstream.host)}`;\n\n const forwardedPrefix = computeForwardedPrefix(route, basePath);\n if (forwardedPrefix) {\n req.headers[\"x-forwarded-prefix\"] = forwardedPrefix;\n } else {\n delete req.headers[\"x-forwarded-prefix\"];\n }\n stripClientForwardedHost(req);\n req.url = (targetPath || \"/\") + query;\n proxy.ws(req, socket, head, { target, changeOrigin: true });\n });\n\n // Start listening\n const assignedPort = await new Promise<number>((resolve, reject) => {\n server.on(\"error\", reject);\n server.listen(options.port, host, () => {\n const addr = server.address();\n const p = typeof addr === \"object\" && addr ? addr.port : options.port;\n resolve(p);\n });\n });\n\n // `url` advertises the browser-facing base, including any base path on\n // publicUrl. `xfwd` relies on the fronting ingress to set\n // X-Forwarded-Proto/Host; the base path is folded into X-Forwarded-Prefix\n // here so upstreams emitting absolute paths reconstruct the full prefix.\n // `|| fallback` (not `??`) so an empty/whitespace-only publicUrl is treated\n // as unset rather than producing an empty `url`. The CLI also validates this\n // as a URL, but createProxyServer is callable directly so we guard here too.\n const url =\n options.publicUrl?.trim().replace(/\\/+$/, \"\") ||\n `http://${host === \"0.0.0.0\" ? \"localhost\" : host}:${assignedPort}`;\n\n const instance: ProxyServerInstance = {\n get port() {\n return assignedPort;\n },\n get host() {\n return host;\n },\n get url() {\n return url;\n },\n\n addRoute(route: ProxyRoute): void {\n // Same prefix only conflicts when both match the same way: an exact\n // route and a prefix route on the same prefix (e.g. a `'/'` redirect vs\n // Connect's `'/'` catch-all) coexist — matchRoute dispatches exact first.\n // Re-adding from the same source replaces the existing route, so\n // repeated registration (e.g. a second service:ready) is idempotent.\n const sameMatch = (r: ProxyRoute) =>\n r.prefix === route.prefix && !!r.exact === !!route.exact;\n const ownIdx = routes.findIndex(\n (r) => sameMatch(r) && r.source === route.source,\n );\n if (ownIdx !== -1) {\n // Replace in place: equal prefix length means the sorted position is\n // unchanged, and re-sorting must not let a previously-shadowed\n // same-prefix route from another source jump ahead.\n const prev = routes[ownIdx];\n routes[ownIdx] = route;\n const prevDest =\n prev.redirectTo ?? prev.upstream?.toString() ?? \"(no upstream)\";\n const newDest =\n route.redirectTo ?? route.upstream?.toString() ?? \"(no upstream)\";\n if (prevDest !== newDest) {\n logger.warn(\n `Proxy route replaced: '${route.prefix}' (${route.source}) upstream ${prevDest} → ${newDest}`,\n );\n }\n } else {\n const existing = routes.find(sameMatch);\n if (existing) {\n logger.warn(\n `Proxy route conflict: '${route.prefix}'${route.exact ? \" (exact)\" : \"\"} already registered by ${existing.source}; ` +\n `route from ${route.source} will be shadowed`,\n );\n }\n routes.push(route);\n sortRoutes();\n }\n const dest = route.redirectTo\n ? `redirect → ${route.redirectTo}`\n : (route.upstream?.toString() ?? \"(no upstream)\");\n logger.debug(\n `Proxy route added: ${route.prefix} → ${dest} (${route.source})`,\n );\n },\n\n removeRoutesBySource(source: string): void {\n const before = routes.length;\n routes = routes.filter((r) => r.source !== source);\n const removed = before - routes.length;\n if (removed > 0) {\n logger.debug(\n `Proxy: removed ${removed} route(s) for source '${source}'`,\n );\n }\n },\n\n getRoutes(): ReadonlyArray<Readonly<ProxyRoute>> {\n return routes;\n },\n\n async stop(): Promise<void> {\n if (stopped) return;\n stopped = true;\n\n const drainTimeout = envMs(\n \"PH_PROXY_DRAIN_TIMEOUT_MS\",\n DEFAULT_DRAIN_TIMEOUT_MS,\n );\n\n // Stop accepting new connections; server.close resolves once all\n // in-flight HTTP requests finish.\n const drained = new Promise<void>((resolve) => {\n server.close(() => resolve());\n });\n\n // Close tracked WS/upgrade sockets so they don't hold the drain open.\n for (const socket of upgradeSockets) socket.destroy();\n upgradeSockets.clear();\n\n // Bound the drain: after the timeout, force-close any sockets still\n // serving in-flight HTTP requests and resolve.\n let timer: NodeJS.Timeout | undefined;\n const deadline = new Promise<void>((resolve) => {\n timer = setTimeout(() => {\n logger.warn(\n `Proxy drain timed out after ${drainTimeout}ms; force-closing connections`,\n );\n server.closeAllConnections?.();\n resolve();\n }, drainTimeout);\n timer.unref?.();\n });\n\n await Promise.race([drained, deadline]);\n if (timer) clearTimeout(timer);\n proxy.close();\n upstreamAgent.destroy();\n logger.debug(\"Proxy server stopped\");\n },\n };\n\n return instance;\n}\n"],"mappings":";;;;;;;;;;;;AA4CA,SAAgB,cAAc,QAAgB,UAA2B;CACvE,IAAI,WAAW,KAAK,OAAO;CAC3B,IAAI,OAAO,SAAS,GAAG,GACrB,OAAO,aAAa,OAAO,MAAM,GAAG,EAAE,KAAK,SAAS,WAAW,MAAM;CAEvE,OAAO,aAAa,UAAU,SAAS,WAAW,SAAS,GAAG;AAChE;;;;;;;AAQA,SAAgB,eAAe,WAAuC;CACpE,MAAM,UAAU,WAAW,KAAK;CAChC,IAAI,CAAC,SAAS,OAAO;CACrB,IAAI;EACF,MAAM,MAAM,IAAI,IAAI,OAAO;EAG3B,IAAI,CAAC,YAAY,KAAK,IAAI,QAAQ,GAAG,OAAO;EAC5C,OAAO,IAAI,SAAS,QAAQ,QAAQ,EAAE;CACxC,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;AAQA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I,UAAU,GACZ,OAAO,MACL,kBAAkB,QAAQ,wBAAwB,OAAO,EAC3D;EAEJ;EAEA,YAAiD;GAC/C,OAAO;EACT;EAEA,MAAM,OAAsB;GAC1B,IAAI,SAAS;GACb,UAAU;GAEV,MAAM,eAAe,MACnB,6BACA,wBACF;GAIA,MAAM,UAAU,IAAI,SAAe,YAAY;IAC7C,OAAO,YAAY,QAAQ,CAAC;GAC9B,CAAC;GAGD,KAAK,MAAM,UAAU,gBAAgB,OAAO,QAAQ;GACpD,eAAe,MAAM;GAIrB,IAAI;GACJ,MAAM,WAAW,IAAI,SAAe,YAAY;IAC9C,QAAQ,iBAAiB;KACvB,OAAO,KACL,+BAA+B,aAAa,8BAC9C;KACA,OAAO,sBAAsB;KAC7B,QAAQ;IACV,GAAG,YAAY;IACf,MAAM,QAAQ;GAChB,CAAC;GAED,MAAM,QAAQ,KAAK,CAAC,SAAS,QAAQ,CAAC;GACtC,IAAI,OAAO,aAAa,KAAK;GAC7B,MAAM,MAAM;GACZ,cAAc,QAAQ;GACtB,OAAO,MAAM,sBAAsB;EACrC;CAGY;AAChB"}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
|
|
2
|
+
//#region src/integrations/powerhouse/remote-reactor.ts
|
|
3
|
+
var remote_reactor_exports = /* @__PURE__ */ __exportAll({
|
|
4
|
+
attachRemoteReactor: () => attachRemoteReactor,
|
|
5
|
+
deriveGraphqlEndpoint: () => deriveGraphqlEndpoint
|
|
6
|
+
});
|
|
7
|
+
/** Derive the GraphQL endpoint from the accepted url spellings. */
|
|
8
|
+
function deriveGraphqlEndpoint(url) {
|
|
9
|
+
const parsed = new URL(url);
|
|
10
|
+
if (parsed.pathname.includes("/d/")) return `${parsed.origin}/graphql`;
|
|
11
|
+
if (parsed.pathname.replace(/\/$/, "").endsWith("/graphql")) return `${parsed.origin}${parsed.pathname.replace(/\/$/, "")}`;
|
|
12
|
+
const base = parsed.pathname.replace(/\/$/, "");
|
|
13
|
+
return `${parsed.origin}${base}/graphql`;
|
|
14
|
+
}
|
|
15
|
+
async function probeEndpoint(endpoint, timeoutMs) {
|
|
16
|
+
try {
|
|
17
|
+
await fetch(endpoint, {
|
|
18
|
+
method: "POST",
|
|
19
|
+
headers: { "content-type": "application/json" },
|
|
20
|
+
body: JSON.stringify({ query: "{ __typename }" }),
|
|
21
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
22
|
+
});
|
|
23
|
+
} catch (cause) {
|
|
24
|
+
throw new Error(`Cannot attach to the reactor at ${endpoint}: the switchboard is not answering. The agent depends on a RUNNING switchboard and never starts one — start it first (e.g. \`ph run switchboard\`, \`ph vetra\`, or the compound that members both) and retry.`, { cause });
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** Read the inspection subgraph's info when it answers (dev switchboards
|
|
28
|
+
* under the OPEN policy serve it); absence is not an attach failure. */
|
|
29
|
+
async function readRemoteInfo(endpoint, tokenProvider, timeoutMs) {
|
|
30
|
+
try {
|
|
31
|
+
const token = await tokenProvider?.();
|
|
32
|
+
const res = await fetch(`${endpoint}/inspection`, {
|
|
33
|
+
method: "POST",
|
|
34
|
+
headers: {
|
|
35
|
+
"content-type": "application/json",
|
|
36
|
+
...token ? { authorization: `Bearer ${token}` } : {}
|
|
37
|
+
},
|
|
38
|
+
body: JSON.stringify({ query: "query ReactorInspectionInfo { inspection { info } }" }),
|
|
39
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
40
|
+
});
|
|
41
|
+
if (!res.ok) return void 0;
|
|
42
|
+
return (await res.json()).data?.inspection?.info;
|
|
43
|
+
} catch {
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
async function attachRemoteReactor(options) {
|
|
48
|
+
const timeoutMs = options.timeoutMs ?? 1e4;
|
|
49
|
+
const endpoint = deriveGraphqlEndpoint(options.url);
|
|
50
|
+
const token = options.token;
|
|
51
|
+
const tokenProvider = options.tokenProvider ?? (token ? () => Promise.resolve(token) : void 0);
|
|
52
|
+
await probeEndpoint(endpoint, timeoutMs);
|
|
53
|
+
const remoteInfo = await readRemoteInfo(endpoint, tokenProvider, timeoutMs);
|
|
54
|
+
const { GraphQLReactorClient } = await import("@powerhousedao/reactor-browser/graphql-client");
|
|
55
|
+
return {
|
|
56
|
+
endpoint,
|
|
57
|
+
client: new GraphQLReactorClient({
|
|
58
|
+
url: endpoint,
|
|
59
|
+
documentModels: options.documentModels,
|
|
60
|
+
...tokenProvider ? { tokenProvider } : {},
|
|
61
|
+
...options.signer ? { signer: options.signer } : {}
|
|
62
|
+
}),
|
|
63
|
+
remoteInfo
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
//#endregion
|
|
67
|
+
export { remote_reactor_exports as n, attachRemoteReactor as t };
|
|
68
|
+
|
|
69
|
+
//# sourceMappingURL=remote-reactor-BQzq4yfO.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"remote-reactor-BQzq4yfO.mjs","names":[],"sources":["../src/integrations/powerhouse/remote-reactor.ts"],"sourcesContent":["import type {\n DocumentModelModule,\n ISigner,\n} from \"@powerhousedao/shared/document-model\";\nimport type { ReactorProtocol } from \"@powerhousedao/host-core\";\nimport type {\n BearerTokenProvider,\n GraphQLReactorClientOptions,\n} from \"@powerhousedao/reactor-browser/graphql-client\";\n\n/**\n * P5.5 — the agent host's reactor is a REMOTE attach: a running switchboard,\n * reached over GraphQL, with nothing of it glued to the CLI's lifetime. N\n * agents attach to ONE reactor as clients; the switchboard\n * outlives agent sessions. The agent DEPENDS on the switchboard — an\n * unreachable remote fails the attach loudly with the start hint, it never\n * auto-starts one.\n */\n\nexport interface AttachRemoteReactorOptions {\n /**\n * Where the switchboard lives: its GraphQL endpoint\n * (`http://localhost:4001/graphql`), a drive url (`…/d/<drive>`), or a bare\n * origin — the endpoint is derived.\n */\n url: string;\n /** Document models the client signs/reduces with. */\n documentModels: readonly DocumentModelModule<any>[];\n /**\n * What this agent expects of the fleet it joins (the host file's\n * reactor.protocol). Reachability and inspection facts are checked at\n * attach; flag-level comparison engages once the inspection subgraph\n * exposes the enforcement flags (upstream note in the phase-5 WBS) — until\n * then the expectation is carried for the error message and future use.\n */\n expectedProtocol?: ReactorProtocol;\n /** Bearer for authenticated switchboards; omitted = unauthenticated. */\n token?: string;\n /**\n * Resolves the bearer per request, for a token that expires (a Renown\n * token). Takes precedence over `token`. Returning undefined sends the\n * request unauthenticated.\n */\n tokenProvider?: BearerTokenProvider;\n /**\n * Signs the actions the client pushes. A function is called per push (see\n * `createReactorWrites`, whose `signer` refuses while the identity has no\n * user). Omitted, the client falls back to the ambient Renown signer, which\n * does not exist in Node: actions then go out unsigned.\n */\n signer?: ISigner | (() => ISigner | undefined);\n /** Reachability probe budget. */\n timeoutMs?: number;\n}\n\nexport interface RemoteReactorAttachment {\n /** The derived GraphQL endpoint actually dialed. */\n endpoint: string;\n /** IReactorClient-compatible GraphQL client (reactor-browser). */\n client: unknown;\n /** Remote facts from the inspection subgraph, when it answers. */\n remoteInfo?: Record<string, unknown>;\n}\n\n/** Derive the GraphQL endpoint from the accepted url spellings. */\nexport function deriveGraphqlEndpoint(url: string): string {\n const parsed = new URL(url);\n if (parsed.pathname.includes(\"/d/\")) {\n return `${parsed.origin}/graphql`;\n }\n if (parsed.pathname.replace(/\\/$/, \"\").endsWith(\"/graphql\")) {\n return `${parsed.origin}${parsed.pathname.replace(/\\/$/, \"\")}`;\n }\n const base = parsed.pathname.replace(/\\/$/, \"\");\n return `${parsed.origin}${base}/graphql`;\n}\n\nasync function probeEndpoint(\n endpoint: string,\n timeoutMs: number,\n): Promise<void> {\n try {\n // A GraphQL endpoint answers POST; any HTTP response (even 400) proves\n // the server is listening. Only transport failure means unreachable.\n await fetch(endpoint, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ query: \"{ __typename }\" }),\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (cause) {\n throw new Error(\n `Cannot attach to the reactor at ${endpoint}: the switchboard is not ` +\n `answering. The agent depends on a RUNNING switchboard and never ` +\n `starts one — start it first (e.g. \\`ph run switchboard\\`, ` +\n `\\`ph 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 tokenProvider: BearerTokenProvider | undefined,\n timeoutMs: number,\n): Promise<Record<string, unknown> | undefined> {\n try {\n const token = await tokenProvider?.();\n const res = await fetch(`${endpoint}/inspection`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(token ? { authorization: `Bearer ${token}` } : {}),\n },\n body: JSON.stringify({\n query: \"query ReactorInspectionInfo { inspection { info } }\",\n }),\n signal: AbortSignal.timeout(timeoutMs),\n });\n if (!res.ok) return undefined;\n const body = (await res.json()) as {\n data?: { inspection?: { info?: Record<string, unknown> } };\n };\n return body.data?.inspection?.info;\n } catch {\n return undefined;\n }\n}\n\nexport async function attachRemoteReactor(\n options: AttachRemoteReactorOptions,\n): Promise<RemoteReactorAttachment> {\n const timeoutMs = options.timeoutMs ?? 10_000;\n const endpoint = deriveGraphqlEndpoint(options.url);\n\n const token = options.token;\n const tokenProvider =\n options.tokenProvider ??\n (token ? () => Promise.resolve<string | undefined>(token) : undefined);\n\n await probeEndpoint(endpoint, timeoutMs);\n const remoteInfo = await readRemoteInfo(endpoint, tokenProvider, timeoutMs);\n\n const { GraphQLReactorClient } =\n await import(\"@powerhousedao/reactor-browser/graphql-client\");\n const clientOptions: GraphQLReactorClientOptions = {\n url: endpoint,\n documentModels: options.documentModels,\n ...(tokenProvider ? { tokenProvider } : {}),\n ...(options.signer ? { signer: options.signer } : {}),\n };\n const client = new GraphQLReactorClient(clientOptions);\n\n return { endpoint, client, remoteInfo };\n}\n"],"mappings":";;;;;;;AAiEA,SAAgB,sBAAsB,KAAqB;CACzD,MA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,KAAK,IAAI,KAAA;CAE9D,MAAM,cAAc,UAAU,SAAS;CACvC,MAAM,aAAa,MAAM,eAAe,UAAU,eAAe,SAAS;CAE1E,MAAM,EAAE,yBACN,MAAM,OAAO;CASf,OAAO;EAAE;EAAU,QAAA,IAFA,qBAAqB;GALtC,KAAK;GACL,gBAAgB,QAAQ;GACxB,GAAI,gBAAgB,EAAE,cAAc,IAAI,CAAC;GACzC,GAAI,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;EAED,CAE5B;EAAG;CAAW;AACxC"}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as applyCompletion, o as formatStreamChunk, t as renderMarkdown } from "./markdown-D-sP2zw_.mjs";
|
|
1
|
+
import { c as hostCommandLine, l as resolveServiceName, n as applyCompletion, t as renderMarkdown, x as formatStreamChunk } from "./markdown-BUeGwhbR.mjs";
|
|
3
2
|
import path from "node:path";
|
|
3
|
+
import { Box, Static, Text, useApp, useInput, useStdin, useStdout } from "ink";
|
|
4
4
|
import { useCallback, useEffect, useRef, useState } from "react";
|
|
5
|
-
import { Box, Static, Text, render, useApp, useInput, useStdin, useStdout } from "ink";
|
|
6
5
|
import Spinner from "ink-spinner";
|
|
7
6
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
8
7
|
//#region src/interactive/text-input.tsx
|
|
@@ -471,11 +470,11 @@ function ServicePanel({ services, onExit, serviceId, workdir }) {
|
|
|
471
470
|
/* @__PURE__ */ jsxs(Text, { children: [/* @__PURE__ */ jsx(Text, {
|
|
472
471
|
bold: true,
|
|
473
472
|
children: "Command: "
|
|
474
|
-
}), typeof def?.command === "function" ? "(dynamic)" : def?.command ?? "—"] }),
|
|
473
|
+
}), def?.run ? hostCommandLine(def.run) : typeof def?.command === "function" ? "(dynamic)" : def?.command ?? "—"] }),
|
|
475
474
|
def?.shutdown && /* @__PURE__ */ jsxs(Text, { children: [/* @__PURE__ */ jsx(Text, {
|
|
476
475
|
bold: true,
|
|
477
476
|
children: "Shutdown:"
|
|
478
|
-
}), ` ${def.shutdown.signal} (timeout ${def.shutdown.timeout}ms)`] }),
|
|
477
|
+
}), ` ${def.shutdown.signal ?? "stdin"} (timeout ${def.shutdown.timeout}ms)`] }),
|
|
479
478
|
def?.restart?.enabled && /* @__PURE__ */ jsxs(Text, { children: [/* @__PURE__ */ jsx(Text, {
|
|
480
479
|
bold: true,
|
|
481
480
|
children: "Restart: "
|
|
@@ -1499,28 +1498,6 @@ function Repl({ session, services, workdir, onStart }) {
|
|
|
1499
1498
|
});
|
|
1500
1499
|
}
|
|
1501
1500
|
//#endregion
|
|
1502
|
-
|
|
1503
|
-
/**
|
|
1504
|
-
* Start the Ink-based interactive REPL.
|
|
1505
|
-
* This function renders the Repl component and waits until the user exits.
|
|
1506
|
-
*/
|
|
1507
|
-
async function startInkRepl(session, opts) {
|
|
1508
|
-
const origError = console.error;
|
|
1509
|
-
console.error = (...args) => {
|
|
1510
|
-
if (typeof args[0] === "string" && args[0].includes("SYNCHRONOUS TERMINATION NOTICE")) return;
|
|
1511
|
-
origError.apply(console, args);
|
|
1512
|
-
};
|
|
1513
|
-
await render(/* @__PURE__ */ jsx(Repl, {
|
|
1514
|
-
session,
|
|
1515
|
-
services: opts?.services,
|
|
1516
|
-
workdir: opts?.workdir,
|
|
1517
|
-
onStart: opts?.onStart
|
|
1518
|
-
}), {
|
|
1519
|
-
exitOnCtrlC: false,
|
|
1520
|
-
kittyKeyboard: { mode: "auto" }
|
|
1521
|
-
}).waitUntilExit();
|
|
1522
|
-
}
|
|
1523
|
-
//#endregion
|
|
1524
|
-
export { startInkRepl };
|
|
1501
|
+
export { Repl };
|
|
1525
1502
|
|
|
1526
|
-
//# sourceMappingURL=
|
|
1503
|
+
//# sourceMappingURL=repl-Czb7u0x_.mjs.map
|