@agent-device/proxy 0.21.37-nightly.20261111.157 → 0.21.37

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
@@ -65,8 +65,12 @@ export default { fetch: proxy.handle };
65
65
  For a WebSocket or other message transport, turn each incoming message into a `Request` and send
66
66
  the `Response` back. Three things the proxy relies on:
67
67
 
68
- - `request.url` is the URL the client used. Upload tickets point clients at its origin. An
69
- `x-forwarded-proto` header overrides the scheme.
68
+ - `request.url` is the URL the client used. Upload tickets point clients at its origin. The first
69
+ comma-separated `x-forwarded-proto` value overrides the scheme when it is `http` or `https`
70
+ (case-insensitive). This value is client-controlled unless your ingress replaces it. Configure
71
+ your ingress to replace client-supplied values with the public scheme rather than append to them.
72
+ When you construct `Request` objects, use the public URL and remove untrusted forwarding
73
+ headers before calling `handle`.
70
74
  - `request.signal` aborts when the client goes away. The proxy then cancels the daemon request, so
71
75
  work the client stopped waiting for does not keep running.
72
76
  - Response bodies stream. Artifact downloads can be large, so forward the body as it arrives.
@@ -139,8 +143,20 @@ authenticate: async (request) => {
139
143
  | `clientToken` | required without `authenticate` | Token clients must send as their daemon auth token. |
140
144
  | `authenticate` | none | Authenticates each client and names its tenant; replaces `clientToken`. |
141
145
  | `upstreamFetch` | global `fetch` | Sends one request to the daemon. |
142
- | `maxRpcBodyBytes` | 1 MiB | Larger `/rpc` bodies get a 400 response. |
143
- | `upstreamTimeoutMs` | 5 minutes | Longest time one daemon request may take, including its body. |
146
+ | `maxRpcBodyBytes` | 64 MiB, the daemon's own request limit | Larger `/rpc` bodies get a 400 response. |
147
+ | `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. |
148
+
149
+ `maxRpcBodyBytes` limits the bytes of one `/rpc` body. The proxy reads the whole body before it
150
+ authenticates the client, then decodes and parses it. One unauthenticated request can therefore
151
+ hold more memory than the limit: the raw bytes plus the decoded string and the parsed request. For
152
+ a proxy that faces the internet, set `maxRpcBodyBytes` lower than the 64 MiB default, to the largest
153
+ request your clients send.
154
+
155
+ After the limit check, the proxy rewrites the body: it adds the daemon token and, with
156
+ `authenticate`, the tenant fields. The rewritten body can be a few hundred bytes larger than the
157
+ client's. The daemon applies its own 64 MiB limit, so a client body within that margin of 64 MiB
158
+ passes the proxy and the daemon refuses it. Clients refuse requests over 64 MiB before sending them,
159
+ so only a body in that narrow margin is affected.
144
160
 
145
161
  ## Health and restarts
146
162
 
package/dist/errors.mjs CHANGED
@@ -7,7 +7,11 @@ const REDACTED_STRING_MAX_LENGTH = 400;
7
7
  const REDACTED_STDERR_MAX_LENGTH = 8192;
8
8
  const TRUNCATION_SUFFIX = "...<truncated>";
9
9
  function redactDiagnosticData(input) {
10
- return redactValue(input, /* @__PURE__ */ new WeakSet());
10
+ return redactValue(input, {
11
+ ancestors: /* @__PURE__ */ new WeakSet(),
12
+ clones: /* @__PURE__ */ new WeakMap(),
13
+ circularMarks: 0
14
+ });
11
15
  }
12
16
  /** Sanitizes an untrusted structured cause before it crosses a process or client boundary. */
13
17
  function sanitizeErrorCause(cause) {
@@ -19,21 +23,29 @@ function sanitizeErrorCause(cause) {
19
23
  ...typeof candidate.code === "string" && candidate.code.length > 0 ? { code: candidate.code } : {}
20
24
  });
21
25
  }
22
- function redactValue(value, seen, keyHint) {
26
+ function redactValue(value, traversal, keyHint) {
23
27
  if (value === null || value === void 0) return value;
24
28
  if (typeof value === "string") return redactString(value, keyHint);
25
29
  if (typeof value !== "object") return value;
26
- if (seen.has(value)) return "[Circular]";
27
- seen.add(value);
28
- if (Array.isArray(value)) return value.map((entry) => redactValue(entry, seen));
29
- const output = {};
30
- for (const [key, entry] of Object.entries(value)) {
31
- if (SENSITIVE_KEY_RE.test(key)) {
32
- output[key] = "[REDACTED]";
33
- continue;
34
- }
35
- output[key] = redactValue(entry, seen, key);
30
+ if (traversal.clones.has(value)) return traversal.clones.get(value);
31
+ if (traversal.ancestors.has(value)) {
32
+ traversal.circularMarks += 1;
33
+ return "[Circular]";
36
34
  }
35
+ const marksBefore = traversal.circularMarks;
36
+ traversal.ancestors.add(value);
37
+ try {
38
+ const clone = redactObject(value, traversal);
39
+ if (traversal.circularMarks === marksBefore) traversal.clones.set(value, clone);
40
+ return clone;
41
+ } finally {
42
+ traversal.ancestors.delete(value);
43
+ }
44
+ }
45
+ function redactObject(value, traversal) {
46
+ if (Array.isArray(value)) return value.map((entry) => redactValue(entry, traversal));
47
+ const output = {};
48
+ for (const [key, entry] of Object.entries(value)) output[key] = SENSITIVE_KEY_RE.test(key) ? "[REDACTED]" : redactValue(entry, traversal, key);
37
49
  return output;
38
50
  }
39
51
  function redactString(value, keyHint) {
@@ -306,7 +318,7 @@ function codeRecoveryHint(code) {
306
318
  case "UNSUPPORTED_PLATFORM": return "This platform is not supported for the requested operation; run devices to inspect available targets.";
307
319
  case "AMBIGUOUS_MATCH": return "Multiple candidates matched. Narrow the query or pass an exact identifier.";
308
320
  case "DEVICE_IN_USE": return "The device is busy with another agent-device request; retry once it frees up.";
309
- case "REPLAY_DIVERGENCE": return "Read the divergence report (details.divergence) for the screen and selector suggestions to repair the step.";
321
+ case "REPLAY_DIVERGENCE": return "Repair the step from the divergence report: its screen and selector suggestions.";
310
322
  case "REPAIR_SESSION_EXPIRED": return "The --save-script repair session was reaped before it was finalized; re-run replay <script> --save-script from the start.";
311
323
  case "REPAIR_COMMIT_FAILED": return "The repair transaction completed, but committing its healed script failed at teardown (no-clobber refusal or a filesystem error); inspect the target path/permissions, then re-run replay <script> --save-script to retry.";
312
324
  case "NOT_IMPLEMENTED": return "This command is part of the planned API but is not implemented yet.";
package/dist/index.d.mts CHANGED
@@ -28,6 +28,10 @@ type DaemonProxyOptions = {
28
28
  /** Auth token of the upstream daemon. Never leaves the proxy. */
29
29
  upstreamToken: string;
30
30
  maxRpcBodyBytes?: number;
31
+ /**
32
+ * Longest time one daemon request may take, including its body. Unset, an exchange lasts as long
33
+ * as its client request: the client's command envelope bounds it.
34
+ */
31
35
  upstreamTimeoutMs?: number;
32
36
  upstreamFetch?: DaemonProxyUpstreamFetch;
33
37
  } & ({
@@ -47,7 +51,10 @@ type DaemonProxy = {
47
51
  readonly instanceId: string;
48
52
  /**
49
53
  * Answers one client request. `request.url` must be the URL the client used, because upload
50
- * tickets are rewritten to its origin; an `x-forwarded-proto` header overrides its scheme.
54
+ * tickets are rewritten to its origin. The first comma-separated `x-forwarded-proto` value
55
+ * overrides its scheme when it is `http` or `https` (case-insensitive). This value is
56
+ * client-controlled unless ingress replaces it with the public scheme. Replace rather than
57
+ * append forwarding metadata, or remove untrusted headers and construct the public request URL.
51
58
  * Abort `request.signal` when the client goes away so in-flight daemon work is cancelled.
52
59
  * Resolves with an error response rather than rejecting.
53
60
  */
package/dist/index.mjs CHANGED
@@ -43,6 +43,14 @@ function normalizeTenantId(raw) {
43
43
  function isTenantOwnedSessionName(tenant, sessionName) {
44
44
  return sessionName.startsWith(`${tenant}:`);
45
45
  }
46
+ /**
47
+ * The largest serialized daemon request, in UTF-8 bytes, that any transport reads: the socket
48
+ * line, the HTTP `/rpc` body, and the proxy's `/rpc` body. Clients refuse a larger request before
49
+ * sending it. It sits well above what a client builds: `test` inlines one replay bundle per flow,
50
+ * each up to 2 MiB before JSON escaping, so 64 MiB fits a suite of several maximum-size flows with
51
+ * worst-case escaping. It also bounds the memory one unauthenticated connection can hold.
52
+ */
53
+ const DAEMON_REQUEST_MAX_BYTES = 67108864;
46
54
  const DAEMON_HTTP_INSTANCE_HEADER = "x-agent-device-instance";
47
55
  const DAEMON_HTTP_UPSTREAM_INSTANCE_HEADER = "x-agent-device-upstream-instance";
48
56
  const DAEMON_HTTP_INSTANCE_MISMATCH_HEADER = "x-agent-device-instance-mismatch";
@@ -112,8 +120,9 @@ function readRecord(value) {
112
120
  //#region src/daemon-proxy.ts
113
121
  /** The client request headers an upload ticket repeats when `authenticate` names none. */
114
122
  const DEFAULT_UPLOAD_CREDENTIAL_HEADERS = Object.keys(buildDaemonHttpAuthHeaders("client"));
115
- const DEFAULT_MAX_RPC_BODY_BYTES = 1048576;
116
- const DEFAULT_UPSTREAM_TIMEOUT_MS = 3e5;
123
+ const DEFAULT_MAX_RPC_BODY_BYTES = DAEMON_REQUEST_MAX_BYTES;
124
+ /** `/health` answers quickly or not at all; its probe never waits on `upstreamTimeoutMs`. */
125
+ const UPSTREAM_HEALTH_TIMEOUT_MS = 5e3;
117
126
  const DAEMON_PROXY_PREFIX = `${DAEMON_HTTP_BASE_PATH}/`;
118
127
  const FORWARDED_REQUEST_HEADERS = [
119
128
  "content-type",
@@ -161,8 +170,22 @@ async function handleProxyRequest(request, options, instanceId) {
161
170
  const route = resolveProxyRoute(request.url);
162
171
  if (request.method === "GET" && route === "/health") return await proxyHealthResponse(request, options, instanceId);
163
172
  if (!isSupportedDaemonRoute(route, request.method)) return new Response(new TextEncoder().encode("Not found"), { status: 404 });
173
+ if (route !== "/rpc") return await handleDaemonRoute(request, route, options, instanceId);
164
174
  let rpcBody;
165
- if (route === "/rpc") rpcBody = await readRequestText(request, options.maxRpcBodyBytes, "Proxy request body is too large.");
175
+ try {
176
+ rpcBody = await readRequestText(request, options.maxRpcBodyBytes, "Proxy request body is too large.");
177
+ } catch (error) {
178
+ return rpcErrorResponse(null, error);
179
+ }
180
+ const envelopeRefusal = refuseInvalidRpcEnvelope(rpcBody);
181
+ if (envelopeRefusal) return envelopeRefusal;
182
+ try {
183
+ return await handleDaemonRoute(request, route, options, instanceId, rpcBody);
184
+ } catch (error) {
185
+ return rpcErrorResponse(readJsonRpcId(rpcBody), error);
186
+ }
187
+ }
188
+ async function handleDaemonRoute(request, route, options, instanceId, rpcBody) {
166
189
  const caller = await authenticateCaller(request, options, rpcBody);
167
190
  if (!caller) return unauthorizedResponse(route, readJsonRpcId(rpcBody));
168
191
  if (caller.tenantId && !isRouteWithinTenant(route, caller.tenantId)) return Response.json({
@@ -249,7 +272,7 @@ async function readUpstreamHealth(request, options) {
249
272
  const response = await options.upstreamFetch(new Request(buildDaemonHttpUrl(options.upstreamBaseUrl, "health"), {
250
273
  method: "GET",
251
274
  headers: buildUpstreamHeaders(new Headers(), options.upstreamToken, "/health"),
252
- signal: upstreamSignal(request, options)
275
+ signal: AbortSignal.any([request.signal, AbortSignal.timeout(UPSTREAM_HEALTH_TIMEOUT_MS)])
253
276
  }));
254
277
  const text = await response.text();
255
278
  try {
@@ -293,6 +316,7 @@ async function forwardProxyRequest(params) {
293
316
  * turns a dropped upstream request into cancellation of in-flight runner work.
294
317
  */
295
318
  function upstreamSignal(request, options) {
319
+ if (options.upstreamTimeoutMs === void 0) return request.signal;
296
320
  return AbortSignal.any([request.signal, AbortSignal.timeout(options.upstreamTimeoutMs)]);
297
321
  }
298
322
  function copyProxyResponseHeaders(upstreamResponse, request, route) {
@@ -359,8 +383,9 @@ function rewriteUploadDirectUrl(upstreamUrl, request) {
359
383
  const requestUrl = new URL(request.url);
360
384
  const uploadIndex = requestUrl.pathname.lastIndexOf("/upload/preflight");
361
385
  const uploadPrefix = uploadIndex >= 0 ? requestUrl.pathname.slice(0, uploadIndex) : "";
362
- const forwardedProto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
363
- const rewritten = new URL(`${forwardedProto || requestUrl.protocol.replace(/:$/, "")}://${requestUrl.host}`);
386
+ const forwardedProto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase();
387
+ const rewritten = new URL(requestUrl.origin);
388
+ if (forwardedProto === "http" || forwardedProto === "https") rewritten.protocol = forwardedProto;
364
389
  rewritten.pathname = `${uploadPrefix}${parsed.pathname}`;
365
390
  rewritten.search = parsed.search;
366
391
  return rewritten.toString();
@@ -372,7 +397,7 @@ function normalizeProxyOptions(options) {
372
397
  clientToken: options.authenticate ? void 0 : normalizeToken(options.clientToken ?? "", "clientToken"),
373
398
  authenticate: options.authenticate,
374
399
  maxRpcBodyBytes: options.maxRpcBodyBytes ?? DEFAULT_MAX_RPC_BODY_BYTES,
375
- upstreamTimeoutMs: options.upstreamTimeoutMs ?? DEFAULT_UPSTREAM_TIMEOUT_MS,
400
+ upstreamTimeoutMs: options.upstreamTimeoutMs,
376
401
  upstreamFetch: options.upstreamFetch ?? ((request) => fetch(request))
377
402
  };
378
403
  }
@@ -581,6 +606,44 @@ function tenantRpcMethodRefusedResponse(rpcId) {
581
606
  }
582
607
  }, { status: 401 });
583
608
  }
609
+ const JSON_RPC_PARSE_ERROR = -32700;
610
+ const JSON_RPC_INVALID_REQUEST = -32600;
611
+ /** Refuses an `/rpc` body that is not JSON, or not one object, as the daemon itself does. */
612
+ function refuseInvalidRpcEnvelope(body) {
613
+ let parsed;
614
+ try {
615
+ parsed = JSON.parse(body);
616
+ } catch {
617
+ return rpcRefusalResponse(JSON_RPC_PARSE_ERROR, "Parse error");
618
+ }
619
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return null;
620
+ return rpcRefusalResponse(JSON_RPC_INVALID_REQUEST, "Invalid Request");
621
+ }
622
+ function rpcRefusalResponse(code, message) {
623
+ return Response.json({
624
+ jsonrpc: "2.0",
625
+ id: null,
626
+ error: {
627
+ code,
628
+ message,
629
+ data: normalizeError(new AppError("INVALID_ARGS", message))
630
+ }
631
+ }, { status: 400 });
632
+ }
633
+ /** An `/rpc` failure in the JSON-RPC envelope the client reads its error code and message from. */
634
+ function rpcErrorResponse(rpcId, error) {
635
+ const normalized = normalizeError(error);
636
+ const invalidArgs = normalized.code === "INVALID_ARGS";
637
+ return Response.json({
638
+ jsonrpc: "2.0",
639
+ id: rpcId,
640
+ error: {
641
+ code: invalidArgs ? -32602 : -32e3,
642
+ message: normalized.message,
643
+ data: normalized
644
+ }
645
+ }, { status: invalidArgs ? 400 : 500 });
646
+ }
584
647
  function proxyErrorResponse(error) {
585
648
  const normalized = normalizeError(error);
586
649
  return Response.json({
package/dist/process.mjs CHANGED
@@ -662,24 +662,83 @@ function isProcessGroupAlive(pid) {
662
662
  }
663
663
  }
664
664
  /**
665
- * Reads who owns a pid, off the event loop, with a budget the caller names. The three fields
666
- * are read concurrently so a loaded host pays one budget for the set rather than one per
667
- * field; on Windows one CIM query answers the whole set. Use this rather than the synchronous
668
- * probes when the answer decides whether a process is signaled: waiting is reversible and
669
- * signaling the wrong process is not.
665
+ * Reads who owns a pid, off the event loop, with a budget the caller names. Use this rather than
666
+ * the synchronous probes when the answer decides whether a process is signaled: waiting is
667
+ * reversible and signaling the wrong process is not. See {@link readProcessIdentities}.
670
668
  */
671
669
  async function readProcessIdentityFacts(pid, timeoutMs = PS_TIMEOUT_MS) {
672
- if (isWindowsHostPlatform()) return await readWindowsProcessIdentityFacts(pid, timeoutMs);
673
- const [startTime, command, state] = await Promise.all([
674
- readProcessFieldAsync(pid, "lstart=", timeoutMs),
675
- readProcessFieldAsync(pid, "command=", timeoutMs),
676
- readProcessFieldAsync(pid, "state=", timeoutMs)
677
- ]);
678
- return {
679
- startTime,
680
- command,
681
- zombie: state === null ? null : state.startsWith("Z")
682
- };
670
+ return (await readProcessIdentities([pid], timeoutMs)).get(pid) ?? UNANSWERED_IDENTITY;
671
+ }
672
+ const UNANSWERED_IDENTITY = Object.freeze({
673
+ startTime: null,
674
+ command: null,
675
+ zombie: null
676
+ });
677
+ /**
678
+ * What the host says about each pid named, off the event loop. Every pid shares the same process
679
+ * table reads: on POSIX one `ps` for state and start time and one for the command, run
680
+ * concurrently so a loaded host pays one budget for the set; on Windows one CIM query. A pid the
681
+ * host did not answer for maps to all-`null` facts, which is unknown evidence, never absence.
682
+ *
683
+ * Nothing about another process is cached: its identity is the fact a caller is about to act on,
684
+ * and a pid can change hands between two reads. Only this process's own identity is reused, by
685
+ * `readCurrentOwnerIdentity`, because a process's own start time never changes.
686
+ */
687
+ async function readProcessIdentities(pids, timeoutMs = PS_TIMEOUT_MS) {
688
+ const selected = uniquePositivePids(pids);
689
+ const facts = /* @__PURE__ */ new Map();
690
+ if (selected.length === 0) return facts;
691
+ const rows = await withoutCommandExecutorOverride(() => readProcessIdentityRows(selected, timeoutMs));
692
+ for (const pid of selected) facts.set(pid, rows.get(pid) ?? UNANSWERED_IDENTITY);
693
+ return facts;
694
+ }
695
+ async function readProcessIdentityRows(pids, timeoutMs) {
696
+ if (isWindowsHostPlatform()) {
697
+ const rows = await readWindowsProcessRowsAsync(pids, windowsBudgetMs(timeoutMs));
698
+ return new Map(rows.map((row) => [row.pid, {
699
+ startTime: row.startTime,
700
+ command: row.command,
701
+ zombie: false
702
+ }]));
703
+ }
704
+ const [identityRows, commandRows] = await Promise.all([runHostPsAsync(HOST_PROCESS_IDENTITY_PS_ARGS(pids), timeoutMs, parseHostProcessIdentityRows), runHostPsAsync(HOST_PROCESS_COMMAND_PS_ARGS(pids), timeoutMs, parseHostProcessCommandRows)]);
705
+ const identities = new Map(identityRows.map((row) => [row.pid, row]));
706
+ const commands = new Map(commandRows.map((row) => [row.pid, row.command]));
707
+ const facts = /* @__PURE__ */ new Map();
708
+ for (const pid of pids) {
709
+ const identity = identities.get(pid);
710
+ const command = commands.get(pid) ?? null;
711
+ if (!identity && command === null) continue;
712
+ facts.set(pid, {
713
+ startTime: identity?.startTime ?? null,
714
+ command,
715
+ zombie: identity ? identity.state.startsWith("Z") : null
716
+ });
717
+ }
718
+ return facts;
719
+ }
720
+ async function runHostPsAsync(args, timeoutMs, parse) {
721
+ try {
722
+ const result = await runCmd(hostPsCommand(), args, {
723
+ allowFailure: true,
724
+ timeoutMs
725
+ });
726
+ return result.exitCode !== 0 ? [] : parse(result.stdout);
727
+ } catch {
728
+ return [];
729
+ }
730
+ }
731
+ const HOST_PROCESS_COMMAND_PS_ARGS = (pids) => [
732
+ "-p",
733
+ pids.join(","),
734
+ "-o",
735
+ "pid=,command="
736
+ ];
737
+ function parseHostProcessCommandRows(stdout) {
738
+ return parseProcessTableRows(stdout, /^\s*(\d+)()\s+(.+?)\s*$/, (match, pid) => ({
739
+ pid,
740
+ command: match[3]
741
+ }));
683
742
  }
684
743
  function readProcessStartTime(pid) {
685
744
  return readProcessField(pid, "lstart=");
@@ -746,18 +805,8 @@ function readHostProcessIdentityRowsSync(pids) {
746
805
  }
747
806
  }
748
807
  async function readHostProcessIdentityRowsAsync(pids) {
749
- const selected = uniquePositivePids(pids);
750
- if (selected.length === 0) return [];
751
- if (isWindowsHostPlatform()) return windowsProcessIdentityRows(await readWindowsProcessRowsAsync(selected, WINDOWS_PS_TIMEOUT_MS));
752
- try {
753
- const result = await runCmd(hostPsCommand(), HOST_PROCESS_IDENTITY_PS_ARGS(selected), {
754
- allowFailure: true,
755
- timeoutMs: PS_TIMEOUT_MS
756
- });
757
- return result.exitCode !== 0 ? [] : parseHostProcessIdentityRows(result.stdout);
758
- } catch {
759
- return [];
760
- }
808
+ if (isWindowsHostPlatform()) return windowsProcessIdentityRows(await readWindowsProcessRowsAsync(pids, WINDOWS_PS_TIMEOUT_MS));
809
+ return await runHostPsAsync(HOST_PROCESS_IDENTITY_PS_ARGS(pids), PS_TIMEOUT_MS, parseHostProcessIdentityRows);
761
810
  }
762
811
  function parseHostProcessIdentityRows(stdout) {
763
812
  const rows = [];
@@ -798,22 +847,6 @@ function readProcessField(pid, field) {
798
847
  return null;
799
848
  }
800
849
  }
801
- async function readProcessFieldAsync(pid, field, timeoutMs) {
802
- if (!Number.isInteger(pid) || pid <= 0) return null;
803
- try {
804
- return processFieldValue(await runCmd(hostPsCommand(), [
805
- "-p",
806
- String(pid),
807
- "-o",
808
- field
809
- ], {
810
- allowFailure: true,
811
- timeoutMs
812
- }));
813
- } catch {
814
- return null;
815
- }
816
- }
817
850
  function processFieldValue(result) {
818
851
  if (result.exitCode !== 0) return null;
819
852
  const value = result.stdout.trim();
@@ -898,41 +931,6 @@ function readWindowsProcessField(pid, field) {
898
931
  function windowsBudgetMs(timeoutMs) {
899
932
  return Math.max(timeoutMs, WINDOWS_PS_TIMEOUT_MS);
900
933
  }
901
- async function readWindowsProcessIdentityFacts(pid, timeoutMs) {
902
- if (!Number.isInteger(pid) || pid <= 0) return {
903
- startTime: null,
904
- command: null,
905
- zombie: null
906
- };
907
- try {
908
- const result = await runCmd(WINDOWS_PROCESS_TOOL, windowsProcessQueryArgs([pid]), {
909
- allowFailure: true,
910
- timeoutMs: windowsBudgetMs(timeoutMs)
911
- });
912
- if (result.exitCode !== 0) return {
913
- startTime: null,
914
- command: null,
915
- zombie: null
916
- };
917
- const row = parseWindowsProcessRows(result.stdout).find((candidate) => candidate.pid === pid);
918
- if (!row) return {
919
- startTime: null,
920
- command: null,
921
- zombie: null
922
- };
923
- return {
924
- startTime: row.startTime,
925
- command: row.command,
926
- zombie: false
927
- };
928
- } catch {
929
- return {
930
- startTime: null,
931
- command: null,
932
- zombie: null
933
- };
934
- }
935
- }
936
934
  async function listWindowsHostProcesses(options) {
937
935
  const result = await (options.runCommand ?? runCmd)(WINDOWS_PROCESS_TOOL, windowsProcessQueryArgs([]), {
938
936
  allowFailure: true,
@@ -1033,52 +1031,74 @@ function readConfirmedProcessStopDetails(details) {
1033
1031
  const errno = details?.errno;
1034
1032
  return {
1035
1033
  reason,
1036
- signal: signal === "SIGTERM" || signal === "SIGKILL" ? signal : void 0,
1034
+ signal: signal === "SIGTERM" || signal === "SIGINT" || signal === "SIGKILL" ? signal : void 0,
1037
1035
  errno: reason === "signal-failed" && typeof errno === "string" ? errno : void 0,
1038
1036
  pid
1039
1037
  };
1040
1038
  }
1039
+ function judgeProcessIdentity(expected, facts) {
1040
+ if (facts.zombie) return "exited";
1041
+ const { startTime, matches } = expected;
1042
+ if (startTime && facts.startTime && facts.startTime !== startTime) return "reassigned";
1043
+ const commandMatches = facts.command === null || !matches ? void 0 : matches(facts.command);
1044
+ if (!startTime && commandMatches === false) return "reassigned";
1045
+ if (!startTime && !matches) return "unverified";
1046
+ return (!startTime || facts.startTime === startTime) && (!matches || commandMatches === true) ? "ours" : "unverified";
1047
+ }
1041
1048
  /**
1042
- * Signals one process TERM then KILL and proves which way the recorded process ended, so a caller
1043
- * only forgets one it watched leave. Identity settles it both ways: unreadable identity retains
1044
- * rather than signaling a process this caller cannot name, while a released pid, a zombie, or a
1045
- * start time the host contradicts proves it gone. A refusal is not absence, so each stage waits.
1049
+ * The one TERM-then-KILL escalation in host-kit. Signals one process gracefully, waits the grace
1050
+ * period, re-proves identity, then sends SIGKILL, and proves which way the recorded process ended
1051
+ * so a caller only forgets one it watched leave. Every signal needs a host-confirmed identity
1052
+ * ({@link judgeProcessIdentity}): an unreadable identity before either signal retains rather than
1053
+ * signaling a process this caller cannot name. A refusal is not absence, so each stage waits.
1046
1054
  */
1047
1055
  async function stopProcessAndConfirmExit(target, budget) {
1048
1056
  if (target.pid === process.pid) throw new RangeError("Cannot stop the current process");
1049
1057
  const identity = await proveStopTargetIdentity(target);
1050
- if (identity === "gone") return { status: "stopped" };
1058
+ if (identity === "released" || identity === "exited") return { status: "stopped" };
1059
+ if (identity === "reassigned") return {
1060
+ status: "stopped",
1061
+ reassigned: true
1062
+ };
1051
1063
  if (identity === "unverified") return {
1052
1064
  status: "retained",
1053
1065
  reason: "identity-unverified"
1054
1066
  };
1055
- const term = await proveSignalStage(target, "SIGTERM", budget.termTimeoutMs);
1056
- if (term.proof === "exited") return { status: "stopped" };
1057
- if (term.proof === "refused") return retainedSignalFailure("SIGTERM", term.errno);
1067
+ const graceful = budget.gracefulSignal ?? "SIGTERM";
1068
+ const term = await proveSignalStage(target, graceful, budget.termTimeoutMs);
1069
+ if (term.proof !== "survived") return stageVerdict(term, graceful);
1058
1070
  const kill = await proveSignalStage(target, "SIGKILL", budget.killTimeoutMs);
1059
- if (kill.proof === "exited") return { status: "stopped" };
1060
- if (kill.proof === "refused") return retainedSignalFailure("SIGKILL", kill.errno);
1071
+ if (kill.proof !== "survived" && kill.proof !== "unverified") return stageVerdict(kill, "SIGKILL");
1061
1072
  return {
1062
1073
  status: "retained",
1063
1074
  reason: "exit-timeout",
1064
1075
  signal: "SIGKILL"
1065
1076
  };
1066
1077
  }
1078
+ /** The verdict a signal stage settles on its own, before any further signal. */
1079
+ function stageVerdict(stage, signal) {
1080
+ if (stage.proof === "exited") return {
1081
+ status: "stopped",
1082
+ signal
1083
+ };
1084
+ if (stage.proof === "reassigned") return {
1085
+ status: "stopped",
1086
+ signal,
1087
+ reassigned: true
1088
+ };
1089
+ if (stage.proof === "refused") return retainedSignalFailure(signal, stage.errno);
1090
+ return {
1091
+ status: "retained",
1092
+ reason: "identity-unverified"
1093
+ };
1094
+ }
1067
1095
  /**
1068
1096
  * Whether the live pid still names the process the caller recorded, read once before anything is
1069
- * signaled. `ours` needs a claim the host confirmed: two recorded facts that no readable fact
1070
- * contradicts only prove the host is silent, and silence about a pid this caller may not own is
1071
- * exactly what must not become permission to signal it.
1097
+ * signaled. `released` is a pid `kill(pid, 0)` no longer finds; the rest is {@link judgeProcessIdentity}.
1072
1098
  */
1073
1099
  async function proveStopTargetIdentity(target) {
1074
- if (!isStopPidLive(target.pid)) return "gone";
1075
- const facts = await readProcessIdentityFacts(target.pid);
1076
- if (facts.zombie) return "gone";
1077
- if (target.identity.startTime && facts.startTime && facts.startTime !== target.identity.startTime) return "gone";
1078
- if (target.identity.matches && facts.command && !target.identity.matches(facts.command)) return "gone";
1079
- const confirmedStartTime = Boolean(target.identity.startTime && facts.startTime);
1080
- const confirmedCommand = Boolean(target.identity.matches && facts.command);
1081
- return confirmedStartTime || confirmedCommand ? "ours" : "unverified";
1100
+ if (!isStopPidLive(target.pid)) return "released";
1101
+ return judgeProcessIdentity(target.identity, await readProcessIdentityFacts(target.pid));
1082
1102
  }
1083
1103
  function retainedSignalFailure(signal, errno) {
1084
1104
  return {
@@ -1088,15 +1108,24 @@ function retainedSignalFailure(signal, errno) {
1088
1108
  errno
1089
1109
  };
1090
1110
  }
1111
+ /**
1112
+ * Sends one signal and waits its budget. A pid that outlives the budget is judged again, which is
1113
+ * also the identity proof the next signal needs: `kill(pid, 0)` cannot tell, because `EPERM` also
1114
+ * comes back for a zombie awaiting its parent, and on Windows for a process that exited while its
1115
+ * object still had handles.
1116
+ */
1091
1117
  async function proveSignalStage(target, signal, timeoutMs) {
1092
1118
  const errno = signalProcessForStop(target.pid, signal);
1093
1119
  if (errno === "ESRCH") return { proof: "exited" };
1094
1120
  if (await waitForStopPidRelease(target.pid, timeoutMs)) return { proof: "exited" };
1095
- if (await proveRecordedProcessGone(target)) return { proof: "exited" };
1096
- return errno === void 0 ? { proof: "survived" } : {
1121
+ const verdict = await proveStopTargetIdentity(target);
1122
+ if (verdict === "released" || verdict === "exited") return { proof: "exited" };
1123
+ if (verdict === "reassigned") return { proof: "reassigned" };
1124
+ if (errno !== void 0) return {
1097
1125
  proof: "refused",
1098
1126
  errno
1099
1127
  };
1128
+ return { proof: verdict === "unverified" ? "unverified" : "survived" };
1100
1129
  }
1101
1130
  const STOP_LIVENESS_POLL_MS = 50;
1102
1131
  /**
@@ -1124,19 +1153,6 @@ async function waitForStopPidRelease(pid, timeoutMs) {
1124
1153
  await sleep(Math.min(STOP_LIVENESS_POLL_MS, Math.max(0, deadline - Date.now())));
1125
1154
  }
1126
1155
  }
1127
- /**
1128
- * Whether the pid outliving its budget still proves the recorded process is gone, which the answer to
1129
- * `kill(pid, 0)` cannot: `EPERM` also comes back for a zombie awaiting its parent, and on Windows for
1130
- * a process that exited while its object still had handles. A start time the host contradicts proves
1131
- * the pid changed hands; the process table holding no row does not, because a hidden or unreadable
1132
- * process is missing from it too.
1133
- */
1134
- async function proveRecordedProcessGone(target) {
1135
- const facts = await readProcessIdentityFacts(target.pid);
1136
- if (facts.zombie) return true;
1137
- const startTime = target.identity.startTime;
1138
- return Boolean(startTime && facts.startTime && facts.startTime !== startTime);
1139
- }
1140
1156
  /** The errno that refused the signal, or `undefined` when the host accepted it. */
1141
1157
  function signalProcessForStop(pid, signal) {
1142
1158
  if (!Number.isInteger(pid) || pid <= 0) return "ESRCH";
@@ -1150,14 +1166,6 @@ function signalProcessForStop(pid, signal) {
1150
1166
  }
1151
1167
  }
1152
1168
  const ERRNO_CODE = /^E[A-Z0-9]+$/;
1153
- async function stopPidsWithEscalation(options) {
1154
- const pids = uniquePositivePids(options.pids, { excludePid: process.pid });
1155
- if (pids.length === 0) return;
1156
- signalPidsBestEffort(pids, "SIGTERM");
1157
- await Promise.all(pids.map(async (pid) => await waitForProcessExit(pid, options.termTimeoutMs)));
1158
- signalPidsBestEffort(pids.filter((pid) => isProcessAlive(pid)), "SIGKILL");
1159
- await Promise.all(pids.map(async (pid) => await waitForProcessExit(pid, options.killTimeoutMs)));
1160
- }
1161
1169
  const SYSCTL_TIMEOUT_MS = 1e3;
1162
1170
  const APPLE_SILICON_SYSCTL = ["-n", "hw.optional.arm64"];
1163
1171
  let pendingHostCpuArch;
@@ -1238,8 +1246,10 @@ function createReapSummary() {
1238
1246
  terminatedPids: [],
1239
1247
  missing: 0,
1240
1248
  missingPids: [],
1241
- ownershipLost: 0,
1242
- ownershipLostPids: [],
1249
+ unconfirmed: 0,
1250
+ unconfirmedPids: [],
1251
+ survived: 0,
1252
+ survivedPids: [],
1243
1253
  skippedForOpenWebSession: false
1244
1254
  };
1245
1255
  }
@@ -1275,56 +1285,35 @@ function isOpenWebSessionSkip(scope, record, policy) {
1275
1285
  return scope === "daemon" && record.purpose === "managed-web-browser" && policy.openWebSession;
1276
1286
  }
1277
1287
  function appendReapOutcome(summary, record, outcome, retained) {
1278
- if (outcome === "terminated") {
1279
- summary.terminated += 1;
1280
- summary.terminatedPids.push(record.pid);
1281
- return;
1282
- }
1283
- if (outcome === "missing") {
1284
- summary.missing += 1;
1285
- summary.missingPids.push(record.pid);
1286
- return;
1287
- }
1288
- summary.ownershipLost += 1;
1289
- summary.ownershipLostPids.push(record.pid);
1290
- retained.push(record);
1288
+ summary[outcome] += 1;
1289
+ summary[`${outcome}Pids`].push(record.pid);
1290
+ if (outcome === "unconfirmed" || outcome === "survived") retained.push(record);
1291
1291
  }
1292
+ /**
1293
+ * Stops one recorded process through the shared escalation. The record names the process by start
1294
+ * time and exact command, and both must be read and match before any signal. A pid the host shows
1295
+ * in another lifetime is proven gone and never signaled; one the host will not fully describe, or
1296
+ * that shows the recorded lifetime running another command, is kept rather than guessed at.
1297
+ */
1292
1298
  async function reapOwnedProcess(record, policy) {
1293
- const initial = await inspectOwnedProcess(record);
1294
- if (initial !== void 0) return initial;
1295
- signalBestEffort(record.pid, initialSignalFor(record));
1296
- return await escalateOwnedProcess(record, policy);
1297
- }
1298
- async function inspectOwnedProcess(record) {
1299
- if (record.pid === process.pid || !isProcessAlive(record.pid)) return "missing";
1300
- const facts = await readProcessIdentityFacts(record.pid);
1301
- if (facts.zombie) return "missing";
1302
- return matchesFacts(record, facts) ? void 0 : "ownership-lost";
1303
- }
1304
- function initialSignalFor(record) {
1305
- return record.purpose === "simctl-screen-recording" ? "SIGINT" : "SIGTERM";
1306
- }
1307
- async function escalateOwnedProcess(record, policy) {
1308
- const termOutcome = await waitForOwnedProcessExit(record, policy.termTimeoutMs);
1309
- if (termOutcome === "exited") return "terminated";
1310
- if (termOutcome === "ownership-lost") return "ownership-lost";
1311
- signalBestEffort(record.pid, "SIGKILL");
1312
- return await waitForOwnedProcessExit(record, policy.killTimeoutMs) === "exited" ? "terminated" : "ownership-lost";
1313
- }
1314
- async function waitForOwnedProcessExit(record, timeoutMs) {
1315
- await waitForProcessExit(record.pid, timeoutMs);
1316
- if (!isProcessAlive(record.pid)) return "exited";
1317
- const facts = await readProcessIdentityFacts(record.pid);
1318
- if (facts.zombie) return "exited";
1319
- return matchesFacts(record, facts) ? "owned-alive" : "ownership-lost";
1299
+ if (record.pid === process.pid) return "missing";
1300
+ return reapOutcomeOf(await stopProcessAndConfirmExit({
1301
+ pid: record.pid,
1302
+ identity: {
1303
+ startTime: record.startTime,
1304
+ matches: (command) => command === record.command
1305
+ }
1306
+ }, {
1307
+ ...policy,
1308
+ gracefulSignal: gracefulSignalFor(record)
1309
+ }));
1320
1310
  }
1321
- function matchesFacts(record, facts) {
1322
- return facts.startTime === record.startTime && facts.command === record.command;
1311
+ function reapOutcomeOf(stop) {
1312
+ if (stop.status === "stopped") return stop.signal && !stop.reassigned ? "terminated" : "missing";
1313
+ return stop.reason === "identity-unverified" ? "unconfirmed" : "survived";
1323
1314
  }
1324
- function signalBestEffort(pid, signal) {
1325
- try {
1326
- process.kill(pid, signal);
1327
- } catch {}
1315
+ function gracefulSignalFor(record) {
1316
+ return record.purpose === "simctl-screen-recording" ? "SIGINT" : "SIGTERM";
1328
1317
  }
1329
1318
  //#endregion
1330
1319
  //#region ../host-kit/src/internal/atomic-file.ts
@@ -1513,11 +1502,25 @@ function errorMessage(error) {
1513
1502
  function isProcessPid(value) {
1514
1503
  return typeof value === "number" && Number.isInteger(value) && value > 0 && value <= 2147483647;
1515
1504
  }
1505
+ let currentOwnerIdentity;
1506
+ /**
1507
+ * This process's identity. A process's own start time never changes, so the first readable answer
1508
+ * is kept for the life of the process and every later call is free. An unreadable start time is
1509
+ * not kept: the next call asks the host again rather than recording an owner without one.
1510
+ */
1516
1511
  function readCurrentOwnerIdentity() {
1517
- return {
1512
+ return rememberedOwnerIdentity() ?? rememberOwnerIdentity(readProcessStartTime(process.pid));
1513
+ }
1514
+ function rememberedOwnerIdentity() {
1515
+ return currentOwnerIdentity?.pid === process.pid ? { ...currentOwnerIdentity } : void 0;
1516
+ }
1517
+ function rememberOwnerIdentity(startTime) {
1518
+ const identity = {
1518
1519
  pid: process.pid,
1519
- startTime: readProcessStartTime(process.pid)
1520
+ startTime
1520
1521
  };
1522
+ if (startTime !== null) currentOwnerIdentity = Object.freeze({ ...identity });
1523
+ return identity;
1521
1524
  }
1522
1525
  function ownerIdentityMatches(left, right) {
1523
1526
  return left.pid === right.pid && left.startTime === right.startTime;
@@ -1554,6 +1557,15 @@ function classifyOwnerLiveness(params) {
1554
1557
  if (guarded) return guarded;
1555
1558
  return classifyLiveOwnerFromObservation(params, readHostProcessIdentityObservations([params.owner.pid]).get(params.owner.pid) ?? null);
1556
1559
  }
1560
+ /**
1561
+ * {@link classifyOwnerLiveness} off the event loop, for a caller that is already waiting. A pid
1562
+ * that `kill(pid, 0)` already proves dead is judged without running the process tool at all.
1563
+ */
1564
+ async function classifyOwnerLivenessAsync(params) {
1565
+ const guarded = guardOwnerPid(params.owner);
1566
+ if (guarded) return guarded;
1567
+ return classifyOwnerLivenessFromObservation(params, (await readHostProcessIdentityObservationsAsync([params.owner.pid])).get(params.owner.pid) ?? null);
1568
+ }
1557
1569
  function classifyOwnerLivenessFromObservation(params, observation) {
1558
1570
  const guarded = guardOwnerPid(params.owner);
1559
1571
  if (guarded) return guarded;
@@ -1602,4 +1614,4 @@ function classifyOwnerStateDirectory(stateDir) {
1602
1614
  }
1603
1615
  }
1604
1616
  //#endregion
1605
- export { captureHostEnvironment, classifyOwnerLiveness, classifyOwnerLivenessFromObservation, confirmedProcessStopDetails, createOwnedProcessRecordStore, describeUnconfirmedProcessStop, expandProcessTree, hostNodeExecutablePath, hostNodeVersion, hostPlatform, hostProcessId, isProcessAlive, isProcessGroupAlive, isProcessPid, isProcessZombie, listHostProcesses, ownerIdentityDiffers, ownerIdentityMatches, readConfirmedProcessStopDetails, readCurrentOwnerIdentity, readHostCpuArch, readHostCpuArchSync, readHostProcessIdentityObservations, readHostProcessIdentityObservationsAsync, readOwnedProcessRecordFile, readProcessCommand, readProcessIdentityFacts, readProcessStartTime, reapOwnedProcessRecordsAtStartup, signalPidsBestEffort, signalProcessGroupBestEffort, stopPidsWithEscalation, stopProcessAndConfirmExit, uniquePositivePids, waitForProcessExit, writeHostStderr };
1617
+ export { captureHostEnvironment, classifyOwnerLiveness, classifyOwnerLivenessAsync, classifyOwnerLivenessFromObservation, confirmedProcessStopDetails, createOwnedProcessRecordStore, describeUnconfirmedProcessStop, expandProcessTree, hostNodeExecutablePath, hostNodeVersion, hostPlatform, hostProcessId, isProcessAlive, isProcessGroupAlive, isProcessPid, isProcessZombie, judgeProcessIdentity, listHostProcesses, ownerIdentityDiffers, ownerIdentityMatches, readConfirmedProcessStopDetails, readCurrentOwnerIdentity, readHostCpuArch, readHostCpuArchSync, readHostProcessIdentityObservations, readHostProcessIdentityObservationsAsync, readOwnedProcessRecordFile, readProcessCommand, readProcessIdentities, readProcessIdentityFacts, readProcessStartTime, reapOwnedProcessRecordsAtStartup, signalPidsBestEffort, signalProcessGroupBestEffort, stopProcessAndConfirmExit, uniquePositivePids, waitForProcessExit, writeHostStderr };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-device/proxy",
3
- "version": "0.21.37-nightly.20261111.157",
3
+ "version": "0.21.37",
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/contracts": "0.0.0",
29
28
  "@agent-device/host-kit": "0.0.0",
29
+ "@agent-device/contracts": "0.0.0",
30
30
  "@agent-device/kernel": "0.0.0"
31
31
  },
32
32
  "scripts": {