@agent-device/proxy 0.21.39 → 0.22.0-nightly-0-22.20261117.184

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/README.md CHANGED
@@ -94,49 +94,10 @@ Your Node HTTP client must send exactly one valid `Host` header on every request
94
94
  configured. Configure raw-socket and HTTP/1.0 health probes to send `Host: localhost` (or your
95
95
  deployment's host and port).
96
96
 
97
- ### How the proxy reaches the daemon
98
-
99
- On artifact transfer routes — `POST /upload`, `/upload/preflight` and `/upload/finalize`,
100
- `PUT /upload/direct/*` and `GET /artifacts*` — the proxy forwards with `node:http` / `node:https`.
101
- Each transfer has a connect limit of 30 seconds, a response-header wait of 30 seconds that
102
- starts only once its own outgoing body has finished and the connection is established, and a
103
- 120-second limit on body inactivity. For downloads, that limit counts time spent waiting for
104
- upstream bytes while you read the response; it pauses when you stop reading. Every forwarded
105
- exchange also ends at 600 seconds regardless of how steadily its bytes move. Your `upstreamTimeoutMs`
106
- is an additional cap. The earliest caller cancellation, operator cap, phase limit or aggregate expiry
107
- ends the exchange. A transfer does not retry or restart its aggregate.
108
-
109
- Transfer phase and aggregate timeout error responses use HTTP 500 and include `reason`,
110
- `transferPhase` and `timeoutMs`. These fields appear only for `COMMAND_FAILED` with
111
- `reason: transfer_phase_timeout` and the matching connect/header (30000ms) or body (120000ms)
112
- phase budget, or `reason: transfer_forwarding_deadline_exceeded` with
113
- `transferPhase: forwarding` and `timeoutMs: 600000`. Other errors omit these fields.
114
- After the proxy returns a response, a timeout while you consume it fails the body read instead of
115
- replacing its status. Preflight bodies are consumed before ticket rewriting; a timeout there returns
116
- HTTP 500.
117
-
118
- On these routes:
119
-
120
- - Redirects are returned without being followed. The daemon's `308` resume response keeps its
121
- `Range` and `x-upload-offset` headers.
122
- - Default request headers added by `fetch`, such as `accept` and `user-agent`, are not sent.
123
- - A patched global `fetch` or an `undici` global dispatcher no longer intercepts the request.
124
-
125
- Supply `upstreamFetch` if you need those Fetch behaviors or your own routing.
126
-
127
- Environment-proxy routing depends on your runtime. In loopback checks, Node 22.12 ignores
128
- `HTTP_PROXY` and `HTTPS_PROXY` for both transports. Node 26.11.1 uses them when
129
- `NODE_USE_ENV_PROXY=1`. Bun 1.4.2 Fetch uses them without that opt-in, while the default transfer
130
- transport requires it. On Node 26.11.1 and Bun 1.4.2, `NO_PROXY=127.0.0.1` bypasses the proxy.
131
- If your Bun deployment needs proxy routing for transfers, set `NODE_USE_ENV_PROXY=1` or supply
132
- `upstreamFetch`.
133
-
134
- By default, `/rpc`, `/health` and request diagnostics use global `fetch`.
135
-
136
97
  ### Reach the daemon over your own transport
137
98
 
138
- Pass `upstreamFetch` when the daemon is only reachable some other way, such as a tunnel the device
139
- host opened to your gateway:
99
+ By default the proxy calls the daemon with the global `fetch`. Pass `upstreamFetch` when the daemon
100
+ is only reachable some other way, such as a tunnel the device host opened to your gateway:
140
101
 
141
102
  ```ts
142
103
  const proxy = createDaemonProxy({
@@ -150,16 +111,6 @@ const proxy = createDaemonProxy({
150
111
  `upstreamFetch` receives a `Request` addressed to `upstreamBaseUrl` and must resolve with the
151
112
  daemon's `Response`. Abort the exchange when `request.signal` aborts.
152
113
 
153
- On transfer routes, the proxy bounds its wait for your transport and response body. It settles on
154
- your abort, your `upstreamTimeoutMs`, its 600-second aggregate and its demand-aware response-body
155
- inactivity limit. Work your transport starts can keep running if it ignores `request.signal`. The
156
- proxy does not wait for that work or for a cancellation callback that never settles. It cannot
157
- measure a connect or a header wait it does not own, so on transfer routes your transport keeps those
158
- obligations. Bound connection establishment to 30 seconds and the response-header wait to 30 seconds
159
- once the connection is established and the outgoing body has finished. Stream `request.body` with
160
- 120-second body inactivity limits. Stop your request and response sources on cancellation. A body
161
- pull alone does not confirm that an outgoing byte was sent.
162
-
163
114
  ### Authenticate each client yourself
164
115
 
165
116
  One `clientToken` is shared by every client. To give each client its own credential, pass
@@ -207,9 +158,9 @@ authenticate: async (request) => {
207
158
  | `upstreamToken` | required | The daemon's auth token. |
208
159
  | `clientToken` | required without `authenticate` | Token clients must send as their daemon auth token. |
209
160
  | `authenticate` | none | Authenticates each client and names its tenant; replaces `clientToken`. |
210
- | `upstreamFetch` | none | Sends one request to the daemon. Without it, transfer routes use `node:http(s)` and every other route uses the global `fetch`. |
161
+ | `upstreamFetch` | global `fetch` | Sends one request to the daemon. |
211
162
  | `maxRpcBodyBytes` | 64 MiB, the daemon's own request limit | Larger `/rpc` bodies get a 400 response. |
212
- | `upstreamTimeoutMs` | none | Independent cap on one daemon request, including its body. `/health` keeps its separate five-second limit. Without this option, other requests last as long as the client waits, bounded by the client's command timeout and, on transfer routes, the 600-second forwarding aggregate. |
163
+ | `upstreamTimeoutMs` | none | Longest time one daemon request may take, including its body. Without it, a request lasts as long as the client waits, and the client's command timeout bounds it. |
213
164
 
214
165
  `maxRpcBodyBytes` limits the bytes of one `/rpc` body. The proxy reads the whole body before it
215
166
  authenticates the client, then decodes and parses it. One unauthenticated request can therefore
package/dist/index.d.mts CHANGED
@@ -1,14 +1,9 @@
1
1
  import http from "node:http";
2
2
  //#region src/daemon-proxy.d.ts
3
3
  /**
4
- * Carries one request to the upstream daemon and resolves with its response. Without `upstreamFetch`
5
- * the proxy reaches the daemon over `node:http(s)` on artifact transfer routes and over the global
6
- * `fetch` on `/rpc`, health and diagnostics. Supply your own to reach the daemon over another
7
- * transport, such as a WebSocket tunnel. Abort the exchange when `request.signal` aborts.
8
- *
9
- * A custom transport owns its phase guarantees and must observe `request.signal` on every route.
10
- * On transfer routes, the proxy bounds its own response and body waits, even if the transport
11
- * ignores cancellation. It cannot forcibly join work started by that transport.
4
+ * Carries one request to the upstream daemon and resolves with its response. The default is the
5
+ * global `fetch`; supply your own to reach the daemon over another transport, such as a
6
+ * WebSocket tunnel. Abort the exchange when `request.signal` aborts.
12
7
  */
13
8
  type DaemonProxyUpstreamFetch = (request: Request) => Promise<Response>;
14
9
  /** The client an `authenticate` call admitted. */
@@ -36,12 +31,10 @@ type DaemonProxyOptions = {
36
31
  publicOrigin?: string;
37
32
  maxRpcBodyBytes?: number;
38
33
  /**
39
- * Independent cap on one upstream request, including its response body. Transfers also observe
40
- * their phase limits and 600-second aggregate. When unset, other requests use the client's
41
- * command envelope. The health probe keeps its separate five-second limit.
34
+ * Longest time one daemon request may take, including its body. Unset, an exchange lasts as long
35
+ * as its client request: the client's command envelope bounds it.
42
36
  */
43
37
  upstreamTimeoutMs?: number;
44
- /** Overrides the transport for every upstream route. See `DaemonProxyUpstreamFetch`. */
45
38
  upstreamFetch?: DaemonProxyUpstreamFetch;
46
39
  } & ({
47
40
  /** Token proxy clients must present as their daemon auth token. */
package/dist/index.mjs CHANGED
@@ -1,8 +1,19 @@
1
1
  import { r as normalizeError, t as AppError } from "./errors.mjs";
2
- import { l as timingSafeStringEqual } from "./transport.mjs";
3
2
  import { a as DAEMON_HTTP_PUBLIC_NETWORK_ACCESS, c as DAEMON_REQUEST_MAX_BYTES, d as buildDaemonHttpUrl, f as buildDaemonInstanceMismatchRpcResponse, g as normalizeTenantId, h as normalizeDaemonPublicOrigin, i as DAEMON_HTTP_NETWORK_ACCESS_HEADER, l as buildDaemonHealthPayload, n as DAEMON_HTTP_INSTANCE_HEADER, o as DAEMON_HTTP_TENANT_HEADER, p as isTenantOwnedSessionName, r as DAEMON_HTTP_INSTANCE_MISMATCH_HEADER, s as DAEMON_HTTP_UPSTREAM_INSTANCE_HEADER, t as DAEMON_HTTP_BASE_PATH, u as buildDaemonHttpAuthHeaders } from "./daemon-http.mjs";
4
- import { randomUUID } from "node:crypto";
3
+ import crypto, { randomUUID } from "node:crypto";
5
4
  import http from "node:http";
5
+ //#region ../host-kit/src/internal/transport.ts
6
+ /**
7
+ * Compares two secret strings in constant time. Hashing both inputs first
8
+ * keeps the comparison length-independent, so unequal-length tokens neither
9
+ * throw nor leak length via timing.
10
+ */
11
+ function timingSafeStringEqual(a, b) {
12
+ const hashA = crypto.createHash("sha256").update(a).digest();
13
+ const hashB = crypto.createHash("sha256").update(b).digest();
14
+ return crypto.timingSafeEqual(hashA, hashB);
15
+ }
16
+ //#endregion
6
17
  //#region src/install-source-admission.ts
7
18
  function carriesUnbackedHostPathInstallSource(rpcBody) {
8
19
  const params = readRpcParams(rpcBody);
@@ -75,7 +86,7 @@ function createDaemonProxy(options) {
75
86
  try {
76
87
  return await handleProxyRequest(request, normalized, instanceId);
77
88
  } catch (error) {
78
- return proxyErrorResponse(error, request);
89
+ return proxyErrorResponse(error);
79
90
  }
80
91
  }
81
92
  };
@@ -215,7 +226,7 @@ async function readUpstreamHealth(request, options) {
215
226
  async function forwardProxyRequest(params) {
216
227
  const { request, route, options, rpcBody, caller } = params;
217
228
  const body = resolveUpstreamBody(request, route, rpcBody, options.upstreamToken, caller.tenantId);
218
- const upstreamResponse = await options.upstreamTransport(route, new Request(buildUpstreamUrl(options.upstreamBaseUrl, route, request.url), {
229
+ const upstreamResponse = await options.upstreamFetch(new Request(buildUpstreamUrl(options.upstreamBaseUrl, route, request.url), {
219
230
  method: request.method,
220
231
  headers: buildUpstreamHeaders(request.headers, options.upstreamToken, route, caller.tenantId),
221
232
  signal: upstreamSignal(request, options),
@@ -237,6 +248,10 @@ async function forwardProxyRequest(params) {
237
248
  headers
238
249
  });
239
250
  }
251
+ /**
252
+ * An upstream exchange lives exactly as long as the client keeps waiting for it: the daemon
253
+ * turns a dropped upstream request into cancellation of in-flight runner work.
254
+ */
240
255
  function upstreamSignal(request, options) {
241
256
  if (options.upstreamTimeoutMs === void 0) return request.signal;
242
257
  return AbortSignal.any([request.signal, AbortSignal.timeout(options.upstreamTimeoutMs)]);
@@ -317,8 +332,6 @@ function normalizeProxyOptions(options) {
317
332
  const upstreamBaseUrl = normalizeBaseUrl(options.upstreamBaseUrl, "upstreamBaseUrl");
318
333
  const upstreamToken = normalizeToken(options.upstreamToken, "upstreamToken");
319
334
  const clientToken = options.authenticate ? void 0 : normalizeToken(options.clientToken ?? "", "clientToken");
320
- const upstreamFetch = options.upstreamFetch ?? ((request) => fetch(request));
321
- const customUpstreamFetch = options.upstreamFetch;
322
335
  return {
323
336
  upstreamBaseUrl,
324
337
  publicOrigin: options.publicOrigin === void 0 ? void 0 : normalizeDaemonPublicOrigin(options.publicOrigin),
@@ -327,12 +340,7 @@ function normalizeProxyOptions(options) {
327
340
  authenticate: options.authenticate,
328
341
  maxRpcBodyBytes: options.maxRpcBodyBytes ?? DEFAULT_MAX_RPC_BODY_BYTES,
329
342
  upstreamTimeoutMs: options.upstreamTimeoutMs,
330
- upstreamFetch,
331
- upstreamTransport: async (route, request) => {
332
- if (!isTransferRoute(route, request.method)) return upstreamFetch(request);
333
- const { createNodeTransferFetch, settleUpstreamFetch } = await import("./transfer-transport.mjs");
334
- return customUpstreamFetch ? settleUpstreamFetch(customUpstreamFetch, request) : createNodeTransferFetch()(request);
335
- }
343
+ upstreamFetch: options.upstreamFetch ?? ((request) => fetch(request))
336
344
  };
337
345
  }
338
346
  function normalizeBaseUrl(value, label) {
@@ -357,7 +365,9 @@ function resolveProxyRoute(requestUrl) {
357
365
  }
358
366
  function isSupportedDaemonRoute(route, method) {
359
367
  if (route === "/rpc") return method === "POST";
360
- if (isTransferRoute(route, method)) return true;
368
+ if (isSupportedUploadRoute(route, method)) return true;
369
+ if (route === "/artifacts" || route === "/artifacts/") return method === "GET";
370
+ if (route.startsWith("/artifacts/")) return method === "GET";
361
371
  if (isRequestDiagnosticsRoute(route)) return method === "GET";
362
372
  return false;
363
373
  }
@@ -370,9 +380,6 @@ function isRequestDiagnosticsRoute(route) {
370
380
  const segments = route.split("/");
371
381
  return segments.length === 6 && segments[1] === "sessions" && segments[3] === "requests" && segments[5] === "diagnostics" && segments[2] !== "" && segments[4] !== "";
372
382
  }
373
- function isTransferRoute(route, method) {
374
- return isSupportedUploadRoute(route, method) || method === "GET" && (route === "/artifacts" || route.startsWith("/artifacts/"));
375
- }
376
383
  function isSupportedUploadRoute(route, method) {
377
384
  if (route === "/upload") return method === "POST";
378
385
  if (isUploadPreflightRoute(route)) return method === "POST";
@@ -579,14 +586,12 @@ function rpcErrorResponse(rpcId, error) {
579
586
  }
580
587
  }, { status: invalidArgs ? 400 : 500 });
581
588
  }
582
- async function proxyErrorResponse(error, request) {
583
- const details = isTransferRoute(resolveProxyRoute(request.url), request.method) ? (await import("./transfer-transport.mjs")).transferWireDetails(error) : {};
589
+ function proxyErrorResponse(error) {
584
590
  const normalized = normalizeError(error);
585
591
  return Response.json({
586
592
  ok: false,
587
593
  error: normalized.message,
588
- code: normalized.code,
589
- ...details
594
+ code: normalized.code
590
595
  }, { status: normalized.code === "INVALID_ARGS" ? 400 : 500 });
591
596
  }
592
597
  //#endregion
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-device/proxy",
3
- "version": "0.21.39",
3
+ "version": "0.22.0-nightly-0-22.20261117.184",
4
4
  "type": "module",
5
5
  "description": "Transport-neutral authenticating proxy in front of an agent-device daemon.",
6
6
  "license": "MIT",
@@ -25,8 +25,8 @@
25
25
  "dist"
26
26
  ],
27
27
  "devDependencies": {
28
- "@agent-device/host-kit": "0.0.0",
29
28
  "@agent-device/contracts": "0.0.0",
29
+ "@agent-device/host-kit": "0.0.0",
30
30
  "@agent-device/kernel": "0.0.0"
31
31
  },
32
32
  "scripts": {
@@ -1,393 +0,0 @@
1
- import { t as AppError } from "./errors.mjs";
2
- import { a as isTransferPhaseTimeoutError, c as observeCompletedRequestWrites, i as createTransferPhaseWatchdog, n as TRANSFER_CONNECT_TIMEOUT_MS, o as loadNodeHttpRequester, r as TRANSFER_RESPONSE_HEADER_TIMEOUT_MS, s as observeClientRequestPhases, t as TRANSFER_BODY_INACTIVITY_TIMEOUT_MS } from "./transport.mjs";
3
- //#region src/transfer-transport.ts
4
- const PROXY_TRANSFER_AGGREGATE_MS = 6e5;
5
- const TRANSFER_FORWARDING_DEADLINE_REASON = "transfer_forwarding_deadline_exceeded";
6
- const NULL_BODY_STATUSES = /* @__PURE__ */ new Set([
7
- 204,
8
- 205,
9
- 304
10
- ]);
11
- /** Forwards one exchange over the runtime's default global Node agent, without redirects or retries. */
12
- function createNodeTransferFetch() {
13
- return async (request) => {
14
- const exchange = openExchange(request.signal);
15
- try {
16
- return await exchangeOverNodeHttp(request, exchange);
17
- } catch (error) {
18
- exchange.dispose();
19
- throw error;
20
- }
21
- };
22
- }
23
- /** Bounds proxy-owned waits; opaque transport work and cancellation callbacks are never joined. */
24
- async function settleUpstreamFetch(upstreamFetch, request) {
25
- const exchange = openExchange(request.signal);
26
- let response;
27
- try {
28
- response = await untilAborted(exchange.signal, () => upstreamFetch(new Request(request, { signal: exchange.signal })), (late) => cancelForeignBody(late.body));
29
- if (!response.body) {
30
- exchange.dispose();
31
- return response;
32
- }
33
- return new Response(demandAwareStream(foreignBodySource(response.body), exchange, () => {
34
- exchange.dispose();
35
- }), {
36
- status: response.status,
37
- statusText: response.statusText,
38
- headers: response.headers
39
- });
40
- } catch (error) {
41
- const failure = exchange.classify(error);
42
- cancelForeignBody(response?.body ?? null);
43
- exchange.dispose();
44
- throw failure;
45
- }
46
- }
47
- function transferWireDetails(error) {
48
- if (!(error instanceof AppError) || error.code !== "COMMAND_FAILED") return {};
49
- const { reason, transferPhase, timeoutMs } = error.details ?? {};
50
- if (reason === TRANSFER_FORWARDING_DEADLINE_REASON) return transferPhase === "forwarding" && timeoutMs === PROXY_TRANSFER_AGGREGATE_MS ? {
51
- reason,
52
- transferPhase,
53
- timeoutMs
54
- } : {};
55
- if (!isTransferPhaseTimeoutError(error)) return {};
56
- let phaseBudgetMs;
57
- switch (transferPhase) {
58
- case "connect":
59
- phaseBudgetMs = TRANSFER_CONNECT_TIMEOUT_MS;
60
- break;
61
- case "response-headers":
62
- phaseBudgetMs = TRANSFER_RESPONSE_HEADER_TIMEOUT_MS;
63
- break;
64
- case "request-body":
65
- case "response-body":
66
- phaseBudgetMs = TRANSFER_BODY_INACTIVITY_TIMEOUT_MS;
67
- break;
68
- default: return {};
69
- }
70
- return timeoutMs === phaseBudgetMs ? {
71
- reason,
72
- transferPhase,
73
- timeoutMs
74
- } : {};
75
- }
76
- function openExchange(caller) {
77
- const forwarding = new AbortController();
78
- const timer = setTimeout(() => forwarding.abort(new AppError("COMMAND_FAILED", "Proxy transfer forwarding deadline exceeded", {
79
- reason: TRANSFER_FORWARDING_DEADLINE_REASON,
80
- transferPhase: "forwarding",
81
- timeoutMs: PROXY_TRANSFER_AGGREGATE_MS
82
- })), PROXY_TRANSFER_AGGREGATE_MS);
83
- timer.unref();
84
- const watchdog = createTransferPhaseWatchdog(AbortSignal.any([caller, forwarding.signal]));
85
- return {
86
- signal: watchdog.signal,
87
- watchdog,
88
- classify: (error) => watchdog.signal.aborted ? watchdog.signal.reason : error,
89
- cancel: (reason) => forwarding.abort(reason),
90
- dispose: () => {
91
- clearTimeout(timer);
92
- watchdog.dispose();
93
- }
94
- };
95
- }
96
- async function exchangeOverNodeHttp(request, exchange) {
97
- const url = new URL(request.url);
98
- const [transport, { urlToHttpOptions }] = await untilAborted(exchange.signal, () => Promise.all([loadNodeHttpRequester(url.protocol), import("node:url")]));
99
- exchange.signal.throwIfAborted();
100
- const { auth: _auth, ...target } = urlToHttpOptions(url);
101
- const options = {
102
- ...target,
103
- method: request.method,
104
- path: `${url.pathname}${url.search}`,
105
- headers: Object.fromEntries(request.headers),
106
- signal: exchange.signal
107
- };
108
- exchange.watchdog.arm("connect", TRANSFER_CONNECT_TIMEOUT_MS);
109
- return await new Promise((resolve, reject) => {
110
- const outgoingStopped = new AbortController();
111
- const requestClosed = new AbortController();
112
- let answered = false;
113
- let response;
114
- let responseClosed = Promise.resolve();
115
- let finishing;
116
- const finish = () => {
117
- if (finishing) return finishing;
118
- outgoingStopped.abort();
119
- if (!req.writableFinished && !req.closed) req.destroy();
120
- finishing = Promise.all([
121
- pump,
122
- reqClosed,
123
- responseClosed
124
- ]).then(() => {
125
- phases.dispose();
126
- stopObservingWrites();
127
- req.off("error", fail);
128
- response?.off("error", fail);
129
- exchange.signal.removeEventListener("abort", onAbort);
130
- exchange.dispose();
131
- });
132
- return finishing;
133
- };
134
- const fail = (error) => {
135
- if (answered) return;
136
- answered = true;
137
- const failure = exchange.classify(error);
138
- response?.destroy();
139
- req.destroy();
140
- finish().then(() => reject(failure));
141
- };
142
- const req = transport.request(options, (res) => {
143
- response = res;
144
- responseClosed = new Promise((closed) => res.once("close", closed));
145
- res.on("error", fail);
146
- if (answered || exchange.signal.aborted) {
147
- res.destroy();
148
- fail(exchange.signal.reason);
149
- return;
150
- }
151
- const status = res.statusCode ?? 500;
152
- if (status < 200 || status > 599) {
153
- fail(new AppError("COMMAND_FAILED", "Upstream daemon returned an unusable HTTP status", {
154
- reason: "transfer_gateway_status",
155
- status
156
- }));
157
- return;
158
- }
159
- answered = true;
160
- outgoingStopped.abort();
161
- exchange.watchdog.suspend();
162
- const headers = new Headers();
163
- for (const [name, value] of Object.entries(res.headers)) {
164
- if (value === void 0) continue;
165
- for (const item of Array.isArray(value) ? value : [value]) headers.append(name, item);
166
- }
167
- if (request.method === "HEAD" || NULL_BODY_STATUSES.has(status)) {
168
- res.resume();
169
- responseClosed.then(finish);
170
- resolve(new Response(null, {
171
- status,
172
- headers
173
- }));
174
- return;
175
- }
176
- resolve(new Response(demandAwareStream(nodeBodySource(res), exchange, finish), {
177
- status,
178
- headers
179
- }));
180
- });
181
- const reqClosed = new Promise((closed) => {
182
- req.once("close", () => {
183
- requestClosed.abort();
184
- closed();
185
- if (!answered) fail(new AppError("COMMAND_FAILED", "Upstream daemon closed before responding", { reason: "transfer_upstream_closed" }));
186
- });
187
- });
188
- req.on("error", fail);
189
- const phases = observeClientRequestPhases(req, exchange.watchdog);
190
- const stopObservingWrites = observeCompletedRequestWrites(req, exchange.signal, () => {
191
- exchange.watchdog.touchBody();
192
- });
193
- const onAbort = () => {
194
- response?.destroy();
195
- fail(exchange.signal.reason);
196
- };
197
- exchange.signal.addEventListener("abort", onAbort, { once: true });
198
- const pump = pumpOutgoing(request, req, exchange.signal, AbortSignal.any([
199
- exchange.signal,
200
- outgoingStopped.signal,
201
- requestClosed.signal
202
- ])).catch(fail);
203
- if (exchange.signal.aborted) onAbort();
204
- });
205
- }
206
- async function pumpOutgoing(request, req, lifetime, stopped) {
207
- if (stopped.aborted) return;
208
- if (!request.body) {
209
- req.end();
210
- return;
211
- }
212
- const reader = request.body.getReader();
213
- try {
214
- for (;;) {
215
- const { done, value } = await untilAborted(stopped, () => reader.read());
216
- if (stopped.aborted) return;
217
- if (done) {
218
- req.end();
219
- return;
220
- }
221
- if (value.byteLength === 0) {
222
- await yieldTransferEvents(stopped);
223
- continue;
224
- }
225
- if (!req.write(value)) await waitUntilDrained(req, stopped);
226
- }
227
- } catch (error) {
228
- if (!stopped.aborted) throw error;
229
- } finally {
230
- if (lifetime.aborted) reader.cancel(lifetime.reason).catch(() => void 0);
231
- reader.releaseLock();
232
- }
233
- }
234
- function waitUntilDrained(req, signal) {
235
- return new Promise((resolve, reject) => {
236
- const cleanup = () => {
237
- req.off("drain", drained);
238
- signal.removeEventListener("abort", aborted);
239
- };
240
- const drained = () => {
241
- cleanup();
242
- resolve();
243
- };
244
- const aborted = () => {
245
- cleanup();
246
- reject(signal.reason);
247
- };
248
- req.once("drain", drained);
249
- signal.addEventListener("abort", aborted, { once: true });
250
- if (signal.aborted) aborted();
251
- else if (req.destroyed || req.closed) {
252
- cleanup();
253
- reject(new AppError("COMMAND_FAILED", "Upstream daemon closed during a write", { reason: "transfer_upstream_closed" }));
254
- } else if (!req.writableNeedDrain) drained();
255
- });
256
- }
257
- function foreignBodySource(body) {
258
- const reader = body.getReader();
259
- return {
260
- next: async () => {
261
- const { done, value } = await reader.read();
262
- return done ? null : value;
263
- },
264
- stop: (reason) => {
265
- reader.cancel(reason).catch(() => void 0);
266
- reader.releaseLock();
267
- }
268
- };
269
- }
270
- function cancelForeignBody(body) {
271
- if (body) body.cancel().catch(() => void 0);
272
- }
273
- function nodeBodySource(res) {
274
- const iterator = res[Symbol.asyncIterator]();
275
- return {
276
- next: async () => {
277
- const { done, value } = await iterator.next();
278
- return done ? null : value;
279
- },
280
- stop: async () => {
281
- if (!res.destroyed) res.destroy();
282
- await iterator.return?.();
283
- }
284
- };
285
- }
286
- function demandAwareStream(source, exchange, cleanup) {
287
- let ended = false;
288
- let finishing;
289
- const finish = (reason) => {
290
- if (finishing) return finishing;
291
- ended = true;
292
- exchange.signal.removeEventListener("abort", onAbort);
293
- exchange.watchdog.suspend();
294
- finishing = Promise.resolve(source.stop(reason)).catch(() => void 0).then(cleanup);
295
- return finishing;
296
- };
297
- let downstream;
298
- const onAbort = () => {
299
- if (ended) return;
300
- downstream.error(exchange.signal.reason);
301
- finish(exchange.signal.reason);
302
- };
303
- return new ReadableStream({
304
- start(controller) {
305
- downstream = controller;
306
- exchange.signal.addEventListener("abort", onAbort, { once: true });
307
- if (exchange.signal.aborted) onAbort();
308
- },
309
- async pull(controller) {
310
- if (ended) return;
311
- exchange.watchdog.arm("response-body", TRANSFER_BODY_INACTIVITY_TIMEOUT_MS);
312
- try {
313
- for (;;) {
314
- const chunk = await untilAborted(exchange.signal, () => source.next());
315
- if (ended) return;
316
- if (chunk === null) {
317
- await finish();
318
- controller.close();
319
- return;
320
- }
321
- if (chunk.byteLength === 0) {
322
- await yieldTransferEvents(exchange.signal);
323
- continue;
324
- }
325
- exchange.watchdog.suspend();
326
- controller.enqueue(chunk);
327
- return;
328
- }
329
- } catch (error) {
330
- if (ended) return;
331
- const failure = exchange.classify(error);
332
- controller.error(failure);
333
- await finish(failure);
334
- }
335
- },
336
- cancel(reason) {
337
- exchange.cancel(reason);
338
- return finish(reason);
339
- }
340
- }, { highWaterMark: 0 });
341
- }
342
- function yieldTransferEvents(signal) {
343
- return new Promise((resolve, reject) => {
344
- const timer = setTimeout(() => {
345
- signal.removeEventListener("abort", aborted);
346
- resolve();
347
- }, 0);
348
- const aborted = () => {
349
- clearTimeout(timer);
350
- signal.removeEventListener("abort", aborted);
351
- reject(signal.reason);
352
- };
353
- signal.addEventListener("abort", aborted, { once: true });
354
- if (signal.aborted) aborted();
355
- });
356
- }
357
- function untilAborted(signal, run, discardLate) {
358
- return new Promise((resolve, reject) => {
359
- let settled = false;
360
- const stop = () => {
361
- settled = true;
362
- signal.removeEventListener("abort", aborted);
363
- };
364
- const aborted = () => {
365
- stop();
366
- reject(signal.reason);
367
- };
368
- if (signal.aborted) {
369
- aborted();
370
- return;
371
- }
372
- signal.addEventListener("abort", aborted, { once: true });
373
- try {
374
- run().then((value) => {
375
- if (settled) {
376
- discardLate?.(value);
377
- return;
378
- }
379
- stop();
380
- resolve(value);
381
- }, (error) => {
382
- if (settled) return;
383
- stop();
384
- reject(error);
385
- });
386
- } catch (error) {
387
- stop();
388
- reject(error);
389
- }
390
- });
391
- }
392
- //#endregion
393
- export { createNodeTransferFetch, settleUpstreamFetch, transferWireDetails };
@@ -1,182 +0,0 @@
1
- import { t as AppError } from "./errors.mjs";
2
- import crypto from "node:crypto";
3
- import { types } from "node:util";
4
- //#region ../host-kit/src/internal/transport.ts
5
- /**
6
- * Loads `node:http` / `node:https` on demand, at the call site that actually
7
- * issues a request.
8
- *
9
- * Importing either for a VALUE initializes undici and, under
10
- * `NODE_USE_SYSTEM_CA=1`, the platform trust store -- ~79ms per process. Several
11
- * modules that only *might* speak HTTP (the daemon transport, remote artifact
12
- * upload/download) sit in the CLI's eager import closure, where the default
13
- * daemon transport is a plain `node:net` socket and no HTTP request is ever
14
- * made. `src/__tests__/cli-startup-import-closure.test.ts` fails the build if a
15
- * static import of either module reappears in that closure.
16
- *
17
- * Resolves `.default`, not the namespace, so callers get the very same module
18
- * object a static `import http from 'node:http'` yields -- its `request`
19
- * property is mutable, which the transport tests rely on to stub requests.
20
- */
21
- async function loadNodeHttpRequester(protocol) {
22
- return protocol === "https:" ? (await import("node:https")).default : (await import("node:http")).default;
23
- }
24
- /**
25
- * Compares two secret strings in constant time. Hashing both inputs first
26
- * keeps the comparison length-independent, so unequal-length tokens neither
27
- * throw nor leak length via timing.
28
- */
29
- function timingSafeStringEqual(a, b) {
30
- const hashA = crypto.createHash("sha256").update(a).digest();
31
- const hashB = crypto.createHash("sha256").update(b).digest();
32
- return crypto.timingSafeEqual(hashA, hashB);
33
- }
34
- /**
35
- * Reports successful nonempty write completions as local-kernel acceptance, never peer receipt.
36
- * Attach at construction. Late response/abort/destroy/dispose completions do not count.
37
- * Disposal restores this wrapper only; caller arguments, callback and backpressure are preserved.
38
- */
39
- function observeCompletedRequestWrites(req, signal, onCompleted) {
40
- const ownWrite = Object.getOwnPropertyDescriptor(req, "write");
41
- const write = req.write;
42
- let observing = true;
43
- const onResponse = () => {
44
- observing = false;
45
- };
46
- const observedWrite = function(...args) {
47
- const [chunk, encoding] = args;
48
- const callbackIndex = typeof encoding === "function" ? 1 : 2;
49
- const callback = args[callbackIndex];
50
- const encodingName = typeof encoding === "string" ? encoding.toLowerCase() : void 0;
51
- const hasBytes = typeof chunk === "string" ? encodingName === "hex" || encodingName === "base64" || encodingName === "base64url" ? Buffer.from(chunk, encodingName).byteLength > 0 : chunk.length > 0 : types.isUint8Array(chunk) && chunk.byteLength > 0;
52
- if (observing && hasBytes) args[callbackIndex] = (error) => {
53
- if (!error && observing && !req.destroyed && !signal.aborted) onCompleted();
54
- if (typeof callback === "function") callback(error);
55
- };
56
- return Reflect.apply(write, this, args);
57
- };
58
- req.write = observedWrite;
59
- req.prependListener("response", onResponse);
60
- return () => {
61
- observing = false;
62
- req.off("response", onResponse);
63
- if (req.write !== observedWrite) return;
64
- if (ownWrite) Object.defineProperty(req, "write", ownWrite);
65
- else Reflect.deleteProperty(req, "write");
66
- };
67
- }
68
- const TRANSFER_CONNECT_TIMEOUT_MS = 3e4;
69
- /** Header wait begins after connection and outgoing flush. */
70
- const TRANSFER_RESPONSE_HEADER_TIMEOUT_MS = 3e4;
71
- const TRANSFER_BODY_INACTIVITY_TIMEOUT_MS = 12e4;
72
- const BODY_PHASES = /* @__PURE__ */ new Set(["request-body", "response-body"]);
73
- const TRANSFER_PHASE_TIMEOUT_REASON = "transfer_phase_timeout";
74
- function createTransferPhaseWatchdog(callerSignal) {
75
- const phase = new AbortController();
76
- const signal = callerSignal ? AbortSignal.any([callerSignal, phase.signal]) : phase.signal;
77
- let armed;
78
- let timer;
79
- let suspended = false;
80
- const rearm = () => {
81
- if (timer !== void 0) clearTimeout(timer);
82
- timer = void 0;
83
- const current = armed;
84
- if (!current || suspended) return;
85
- timer = setTimeout(() => {
86
- timer = void 0;
87
- phase.abort(createTransferPhaseTimeoutError(current.phase, current.timeoutMs));
88
- }, current.timeoutMs);
89
- timer.unref();
90
- };
91
- return {
92
- signal,
93
- arm(nextPhase, timeoutMs) {
94
- if (signal.aborted) return;
95
- suspended = false;
96
- armed = {
97
- phase: nextPhase,
98
- timeoutMs
99
- };
100
- rearm();
101
- },
102
- touchBody() {
103
- if (!armed || !BODY_PHASES.has(armed.phase)) return;
104
- rearm();
105
- },
106
- suspend() {
107
- suspended = true;
108
- if (timer !== void 0) clearTimeout(timer);
109
- timer = void 0;
110
- },
111
- dispose() {
112
- armed = void 0;
113
- if (timer !== void 0) clearTimeout(timer);
114
- timer = void 0;
115
- }
116
- };
117
- }
118
- function createTransferPhaseTimeoutError(phase, timeoutMs) {
119
- return new AppError("COMMAND_FAILED", `Artifact transfer ${phase} timed out`, {
120
- reason: TRANSFER_PHASE_TIMEOUT_REASON,
121
- transferPhase: phase,
122
- timeoutMs
123
- });
124
- }
125
- function isTransferPhaseTimeoutError(error) {
126
- return error instanceof AppError && error.details?.reason === TRANSFER_PHASE_TIMEOUT_REASON;
127
- }
128
- /**
129
- * Attach at construction after arming connect. Headers need connection and request finish.
130
- * TLS needs secureConnect; pooled sockets are connected. Buffered bytes are not progress.
131
- * The caller reports body bytes; response start retires request events. Dispose at settlement.
132
- */
133
- function observeClientRequestPhases(req, watchdog) {
134
- let established = false;
135
- let flushed = false;
136
- let responseStarted = false;
137
- let socket;
138
- let connectEvent;
139
- const advance = () => {
140
- if (responseStarted || watchdog.signal.aborted || !established) return;
141
- if (flushed) watchdog.arm("response-headers", TRANSFER_RESPONSE_HEADER_TIMEOUT_MS);
142
- else watchdog.arm("request-body", TRANSFER_BODY_INACTIVITY_TIMEOUT_MS);
143
- };
144
- const onConnected = () => {
145
- established = true;
146
- advance();
147
- };
148
- const onSocket = (next) => {
149
- if (!next.connecting) {
150
- established = true;
151
- advance();
152
- return;
153
- }
154
- socket = next;
155
- connectEvent = next.encrypted === true ? "secureConnect" : "connect";
156
- next.once(connectEvent, onConnected);
157
- };
158
- const onFinish = () => {
159
- flushed = true;
160
- advance();
161
- };
162
- const onResponse = () => {
163
- responseStarted = true;
164
- watchdog.arm("response-body", TRANSFER_BODY_INACTIVITY_TIMEOUT_MS);
165
- };
166
- req.on("socket", onSocket);
167
- req.on("finish", onFinish);
168
- req.prependListener("response", onResponse);
169
- return {
170
- get responseStarted() {
171
- return responseStarted;
172
- },
173
- dispose() {
174
- req.off("socket", onSocket);
175
- req.off("finish", onFinish);
176
- req.off("response", onResponse);
177
- if (socket && connectEvent) socket.off(connectEvent, onConnected);
178
- }
179
- };
180
- }
181
- //#endregion
182
- export { isTransferPhaseTimeoutError as a, observeCompletedRequestWrites as c, createTransferPhaseWatchdog as i, timingSafeStringEqual as l, TRANSFER_CONNECT_TIMEOUT_MS as n, loadNodeHttpRequester as o, TRANSFER_RESPONSE_HEADER_TIMEOUT_MS as r, observeClientRequestPhases as s, TRANSFER_BODY_INACTIVITY_TIMEOUT_MS as t };