orkestrator 2.36.4-beta → 2.36.6-beta

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.
@@ -1,8 +1,80 @@
1
+ // ../protocol/src/node/bridge-launch-environment.ts
2
+ import { closeSync, fstatSync, openSync, readSync, rmSync, constants } from "node:fs";
3
+ var BRIDGE_LAUNCH_ENVIRONMENT_ENV = "ORKESTRATOR_BRIDGE_LAUNCH_ENVIRONMENT";
4
+ var BRIDGE_LAUNCH_KEYS_ENV = "ORKESTRATOR_BRIDGE_LAUNCH_KEYS";
5
+ var BRIDGE_LAUNCH_WORKDIR_ENV = "ORKESTRATOR_BRIDGE_LAUNCH_WORKDIR";
6
+ var MAX_SNAPSHOT_BYTES = 1024 * 1024;
7
+ var MAX_SNAPSHOT_ENTRIES = 4096;
8
+ var NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_%.-]*$/;
9
+ var LAUNCH_ONLY = /(?:_BRIDGE_TOKEN|_TOKEN_SHA256|_AUTHORITY_KEY)$|^ORKESTRATOR_BRIDGE_(?:LAUNCH_|EXECUTION_POLICY$)|^ORKESTRATOR_COORDINATOR_/;
10
+ var NOT_APPLIED = new Set(["PWD", "OLDPWD", "SHLVL", "_", "NODE_PATH"]);
11
+ function readSnapshot(file) {
12
+ let fd;
13
+ try {
14
+ fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
15
+ } catch {
16
+ return null;
17
+ }
18
+ try {
19
+ const stat = fstatSync(fd);
20
+ if (!stat.isFile() || stat.size > MAX_SNAPSHOT_BYTES)
21
+ return null;
22
+ const buffer = Buffer.alloc(stat.size);
23
+ let offset = 0;
24
+ while (offset < buffer.length) {
25
+ const read = readSync(fd, buffer, offset, buffer.length - offset, offset);
26
+ if (read === 0)
27
+ break;
28
+ offset += read;
29
+ }
30
+ return buffer.subarray(0, offset);
31
+ } finally {
32
+ closeSync(fd);
33
+ }
34
+ }
35
+ function applyBridgeLaunchEnvironment(env = process.env, chdir = (directory) => process.chdir(directory)) {
36
+ const file = env[BRIDGE_LAUNCH_ENVIRONMENT_ENV];
37
+ if (!file)
38
+ return null;
39
+ const trusted = new Set((env[BRIDGE_LAUNCH_KEYS_ENV] ?? "").split(",").map((name) => name.trim()).filter(Boolean));
40
+ const workdir = env[BRIDGE_LAUNCH_WORKDIR_ENV];
41
+ delete env[BRIDGE_LAUNCH_ENVIRONMENT_ENV];
42
+ delete env[BRIDGE_LAUNCH_KEYS_ENV];
43
+ delete env[BRIDGE_LAUNCH_WORKDIR_ENV];
44
+ const result = { applied: 0, refused: 0 };
45
+ const snapshot = readSnapshot(file);
46
+ rmSync(file, { force: true });
47
+ if (snapshot) {
48
+ const entries = snapshot.toString("utf8").split("\x00").slice(0, MAX_SNAPSHOT_ENTRIES);
49
+ for (const entry of entries) {
50
+ const separator = entry.indexOf("=");
51
+ if (separator <= 0)
52
+ continue;
53
+ const name = entry.slice(0, separator);
54
+ if (!NAME_PATTERN.test(name) || NOT_APPLIED.has(name))
55
+ continue;
56
+ if (trusted.has(name) || LAUNCH_ONLY.test(name)) {
57
+ result.refused += 1;
58
+ continue;
59
+ }
60
+ env[name] = entry.slice(separator + 1);
61
+ result.applied += 1;
62
+ }
63
+ }
64
+ if (workdir) {
65
+ try {
66
+ chdir(workdir);
67
+ } catch {}
68
+ }
69
+ return result;
70
+ }
71
+ applyBridgeLaunchEnvironment();
72
+
1
73
  // ../../bridges/cursor-bridge/src/config.ts
2
74
  import { resolve } from "node:path";
3
75
 
4
76
  // ../protocol/src/node/bridge-credential.ts
5
- import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
77
+ import { createHash as createHash2, randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
6
78
  import { createRequire } from "node:module";
7
79
 
8
80
  // ../protocol/src/secret-redaction.ts
@@ -48,7 +120,7 @@ var MAX_FRAME_CHARS = 240;
48
120
  var MAX_RAW_FRAME_CHARS = 1024;
49
121
  var MAX_CAUSE_DEPTH = 2;
50
122
  var TRUNCATED_MARKER = "...[truncated]";
51
- var NAME_PATTERN = /^[A-Za-z_$][\w$.-]{0,63}$/;
123
+ var NAME_PATTERN2 = /^[A-Za-z_$][\w$.-]{0,63}$/;
52
124
  var CODE_PATTERN = /^[\w.:-]{1,64}$/;
53
125
  var SYSCALL_PATTERN = /^[\w./ -]{1,128}$/;
54
126
  var COMMAND_OUTPUT_FIELDS = ["stdout", "stderr", "cmd", "spawnargs"];
@@ -126,7 +198,7 @@ function describe(error, includeStack, includeMessage, depth) {
126
198
  if (!(error instanceof Error) && typeof rawMessage !== "string") {
127
199
  return { name: "NonError", message: "[object]" };
128
200
  }
129
- const name = matching(read(error, "name"), NAME_PATTERN) ?? "Error";
201
+ const name = matching(read(error, "name"), NAME_PATTERN2) ?? "Error";
130
202
  const message = typeof rawMessage === "string" ? rawMessage : undefined;
131
203
  const commandFailure = isCommandFailure(error, name, message);
132
204
  const stackHoldsMessage = message !== undefined && String(read(error, "stack") ?? "").includes(message);
@@ -181,7 +253,7 @@ function logErrorKind(error) {
181
253
  const safeCode = finite(code) ?? matching(code, CODE_PATTERN);
182
254
  if (safeCode !== undefined)
183
255
  return String(safeCode);
184
- return matching(read(error, "name"), NAME_PATTERN) ?? "Error";
256
+ return matching(read(error, "name"), NAME_PATTERN2) ?? "Error";
185
257
  }
186
258
 
187
259
  // ../protocol/src/log-vocabulary/define.ts
@@ -602,6 +674,7 @@ var DESKTOP_LOG_AREAS = defineLogAreas({
602
674
  events: {
603
675
  "attention-failed": "A dialog could not ask for the user's attention.",
604
676
  closed: "A native dialog closed.",
677
+ "hidden-cancelled": "A hidden profile cancelled a dialog without opening native UI.",
605
678
  "open-failed": "A dialog could not open; it was answered as cancelled.",
606
679
  opening: "A native dialog is opening.",
607
680
  "preview-beforeunload-ignored": "A browser preview's beforeunload handler was ignored.",
@@ -687,6 +760,7 @@ var ENVIRONMENT_LOG_AREAS = defineLogAreas({
687
760
  "orphan-session.reaped": "A native session no tab references was torn down.",
688
761
  "handoff-sweep.failed": "Sweeping transferred transcripts no tab references failed.",
689
762
  "delete.terminals-survived": "Terminal process trees outlived termination, so the deletion stops.",
763
+ "delete.step-deadline": "A deletion step that runs child processes passed its deadline; they are stopped and the deletion fails once they have.",
690
764
  "delete.artifacts-left": "Graph run artifact directories were not removed.",
691
765
  "delete.worktrees-kept": "Graph runs kept branch worktrees.",
692
766
  "delete.step-failed": "One best-effort part of deleting an environment failed; `step` says which, and the rest goes on.",
@@ -721,6 +795,7 @@ var GATEWAY_LOG_AREAS = defineLogAreas({
721
795
  "host.refused": "A request named a host this gateway does not answer to. Logged once per name, up to a limit.",
722
796
  "port.fallback": "The preferred port was taken, so a nearby one is used.",
723
797
  "port.fallback-distant": "The preferred port and those nearby were taken, so another is used.",
798
+ "request-auth.fallback": "A desktop request-auth hook failed closed. Phase only; no request or error content.",
724
799
  "request.failed": "A gateway request failed. Throttled: repeats are counted, not written.",
725
800
  "websocket.upgrade-failed": "A WebSocket upgrade failed.",
726
801
  "events.client-dropped": "An event-stream client buffered too much and was dropped; it reconnects and refetches.",
@@ -779,6 +854,11 @@ var LOCAL_SERVER_LOG_AREAS = defineLogAreas({
779
854
  requested: "boolean"
780
855
  }
781
856
  },
857
+ "bridge.orphans-reaped": {
858
+ description: "Processes a bridge left in its process group after exiting on its own (its agent CLI, mid-turn) were stopped. `warn` when they left; `error` when one survived SIGKILL.",
859
+ essential: true,
860
+ fields: { key: "label", pid: "number", result: "label" }
861
+ },
782
862
  "reaper.tmux-list-failed": "Orphaned claude-tmux sessions could not be listed.",
783
863
  "reaper.tmux-kill-failed": "An orphaned tmux session could not be killed.",
784
864
  "reaper.tmux-reaped": "Orphaned claude-tmux sessions of a deleted environment were killed.",
@@ -829,6 +909,8 @@ var LOGGING_LOG_AREAS = defineLogAreas({
829
909
  },
830
910
  "essential.write-failed": "Writing the essential log failed. Its entries are counted, and a marker reports them at the next write that works.",
831
911
  "policy.changed": "The logging settings changed: saving, retention and levels, with no content.",
912
+ "policy.detail-expired": "Raised log detail reached its expiry, so the backend set its raised levels back to info. Saving is unchanged.",
913
+ "policy.expiry-failed": "Checking or applying the log detail expiry failed; the next check, a minute later, tries again.",
832
914
  "policy.bridge-predates-route": "A running bridge has no logging settings route; it applies them at its next start.",
833
915
  "policy.push-failed": "A running bridge did not take the logging settings after retries; its next start resends them.",
834
916
  "prune.failed": "Removing expired log files failed; the next sweep retries.",
@@ -836,6 +918,23 @@ var LOGGING_LOG_AREAS = defineLogAreas({
836
918
  "unknown-area": "Code outside the type checker asked for an area that is not listed.",
837
919
  ...THROTTLE_LOG_EVENTS
838
920
  }
921
+ },
922
+ "renderer-errors": {
923
+ description: "Renderer failures a desktop window reported from its error ring: class, boundary, surface, count and fingerprint, never a message or stack.",
924
+ events: {
925
+ "error.recorded": {
926
+ description: "A renderer reported `count` new occurrences of one failure since its last report.",
927
+ essential: true,
928
+ fields: {
929
+ errorClass: "label",
930
+ boundary: "label",
931
+ route: "label",
932
+ fingerprint: "label",
933
+ count: "number"
934
+ }
935
+ },
936
+ "report.rate-limited": "Renderer error entries arrived faster than the backend records them, so `dropped` were counted and not written."
937
+ }
839
938
  }
840
939
  });
841
940
 
@@ -893,6 +992,8 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
893
992
  "usage-limit.notice-failed": "A usage-limit stop's outcome could not be read for its notice.",
894
993
  "usage-limit.resend-failed": "Resending after a usage limit failed. An unknown send stays in the journal.",
895
994
  "title.strategy-failed": "A session title strategy failed, so the next is tried. Content-free: the error can quote the prompt.",
995
+ "steer.qualification-failed": "A bridge's steer qualification failed or answered non-OK, so steering is not offered. Agent and status code or error class only.",
996
+ "steer.capability-cleared": "A projection cleared `actions.steer` because its bridge did not qualify. Identifiers and turn status only.",
896
997
  ...THROTTLE_LOG_EVENTS
897
998
  }
898
999
  },
@@ -993,6 +1094,9 @@ var RUNTIME_LOG_AREAS = defineLogAreas({
993
1094
  essential: true,
994
1095
  fields: { origin: "label", ...ESSENTIAL_ERROR_FIELDS }
995
1096
  },
1097
+ "child.reaped": "A macOS child whose exit Bun lost was reaped after its command settled, so it no longer waits as a zombie.",
1098
+ "child.reap-abandoned": "A child whose exit Bun lost was left unreaped: `reason` says whether it was never seen as a zombie (`not-a-zombie`), too many were pending (`capacity`), or `waitpid` failed.",
1099
+ "child.reap-unavailable": "waitpid could not be loaded, so children whose exit Bun lost stay zombies until this process exits.",
996
1100
  ...THROTTLE_LOG_EVENTS
997
1101
  }
998
1102
  }
@@ -1399,6 +1503,13 @@ var COORDINATOR_LOG_AREAS = defineLogAreas({
1399
1503
  "store.workflows-cleared": "The workflow store was full, so a batch of its oldest finished records was removed.",
1400
1504
  "store.workflows-in-use": "The workflow store was full and every record was still in use, so new work was refused.",
1401
1505
  "remote-worker.settle-failed": "A remote worker could not be settled.",
1506
+ "node-release.failed": "Work on a node that was forgotten or handed over could not be closed; the sweep's registry check retries.",
1507
+ "node-release.reconcile-failed": "The sweep could not check records against the node registry; the next sweep retries.",
1508
+ "node-release.unregistered": "Records named a node the registry no longer holds, so their work was closed here.",
1509
+ "node-release.notice-failed": "The notice for work closed on a released node could not be sent; it stays owed and the sweep retries.",
1510
+ "node-release.no-coordinator": "Work closed on a released node belonged to a coordinator that no longer exists, so nobody was told.",
1511
+ "node-offline.notice-failed": "The notice that a node has been unreachable for a day could not be sent; the next failed read retries.",
1512
+ "node-offline.check-failed": "Whether a long-unreachable node's coordinators were told could not be checked; the next read retries.",
1402
1513
  "checkout.merge-followed": "After an environment's PR merged, the project checkout was fast-forwarded, or `outcome` says why not.",
1403
1514
  "checkout.merge-follow-failed": "Fast-forwarding the project checkout failed, after an environment's PR merged or before mail woke the main coordinator.",
1404
1515
  "checkout.mail-follow": "Before mail woke the main coordinator, the project checkout was fast-forwarded (`fast-forwarded-fetched` when the fetch was slow or failed and the upstream commit already fetched was merged), or `outcome` says why not (`timed-out`, `failed`).",
@@ -1495,6 +1606,7 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1495
1606
  events: {
1496
1607
  "portable-inputs.relay-missing": "Docker is rootless and the image predates the staged-input relay, so the container cannot read them until rebuilt.",
1497
1608
  "git-mirror.mount-unavailable": "A new container gets no project Git mirror, so its clone goes to the remote.",
1609
+ "git-mirror.mount-withheld": "A new restricted container gets no project Git mirror because its firewall would not let it reach the project's remote, so it cannot read what the remote serves through the mirror either.",
1498
1610
  "git-mirror.refreshed": "A project's Git mirror was built or updated.",
1499
1611
  "git-mirror.seeded": "A project's Git mirror was built from its host checkout and only what the remote added to it.",
1500
1612
  "git-mirror.seed-skipped": "A project's host checkout could not seed its Git mirror, so the build downloads everything.",
@@ -1580,7 +1692,11 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1580
1692
  "network.list-failed": "Docker networks could not be listed.",
1581
1693
  "network.inspect-failed": "A Docker network could not be inspected.",
1582
1694
  "stale-containers.removing": "Stale probe containers are being removed.",
1583
- "stale-networks.removing": "Stale probe networks are being removed."
1695
+ "stale-networks.removing": "Stale probe networks are being removed.",
1696
+ "peers.refused": "The agent tools server closed connections from addresses outside loopback and this backend's Docker networks (at most one entry a minute, with a count).",
1697
+ "peers.subnets-loaded": "The Docker subnets the agent tools server admits were reloaded.",
1698
+ "port.loopback-taken": "The agent tools server gave up a port because another process holds it on 127.0.0.1, where host agents call; it moves to a free port.",
1699
+ "peers.subnets-load-failed": "The Docker subnets the agent tools server admits could not be read; cached permissions are cleared and only loopback is admitted until a successful retry."
1584
1700
  }
1585
1701
  }
1586
1702
  });
@@ -1671,6 +1787,7 @@ var NODES_LOG_AREAS = defineLogAreas({
1671
1787
  "verification.record-failed": "A node verification could not be recorded.",
1672
1788
  "profile.record-failed": "A node profile could not be recorded.",
1673
1789
  "detach.unconfirmed": "A forgotten node has not confirmed the detach yet.",
1790
+ "grant.revocation-listener-failed": "A connection could not be told its client grant was removed; the grant is still gone.",
1674
1791
  "handover.recovery-pending": "Command handover recovery is still pending.",
1675
1792
  "ticket-sync.work-record-failed": "A remote build started but its ticket work location could not be saved.",
1676
1793
  "ticket-sync.failed": "A Kanban sync with a node failed; it is retried.",
@@ -1723,7 +1840,9 @@ var HOST_LOG_AREAS = defineLogAreas({
1723
1840
  "tool.missing": "A host tool was not found.",
1724
1841
  "maintenance.listener-failed": "A host maintenance listener threw; the others still run.",
1725
1842
  "suspend.reconcile-failed": "Reconciling due work after a host suspension failed.",
1726
- "load.sample-failed": "Sampling machine load failed; the next sample retries."
1843
+ "load.sample-failed": "Sampling machine load failed; the next sample retries.",
1844
+ "usage.source-stalled": "A usage source (scope: disk or gpu-sysfs) did not answer in time; its figure is missing from the sample until it does.",
1845
+ ...THROTTLE_LOG_EVENTS
1727
1846
  }
1728
1847
  }
1729
1848
  });
@@ -2821,33 +2940,198 @@ function createLogger(area) {
2821
2940
  };
2822
2941
  }
2823
2942
 
2943
+ // ../protocol/src/node/bridge-authority.ts
2944
+ import {
2945
+ createHash,
2946
+ createPrivateKey,
2947
+ createPublicKey,
2948
+ generateKeyPairSync,
2949
+ randomBytes,
2950
+ sign,
2951
+ verify
2952
+ } from "node:crypto";
2953
+ var BRIDGE_AUTHORITY_HEADER = "x-orkestrator-authority";
2954
+ var BRIDGE_AUTHORITY_REFUSED_CODE = "authority-signature-required";
2955
+ var BRIDGE_AUTHORITY_WINDOW_MS = 5 * 60000;
2956
+ var BRIDGE_AUTHORITY_MAX_NONCES = 8192;
2957
+ var BRIDGE_AUTHORITY_MAX_BODY_BYTES = 64 * 1024 * 1024;
2958
+ var SCHEME = "orkestrator-bridge-authority-v1";
2959
+ var KEY_PATTERN = /^[A-Za-z0-9_-]{40,200}$/;
2960
+ var HEADER_PATTERN = /^v1 t=(\d{1,16}) n=([A-Za-z0-9_-]{22}) s=([A-Za-z0-9_-]{86})$/;
2961
+ var READ_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
2962
+ var UNSIGNED_ROUTES = [
2963
+ /^\/session\/[^/]+\/close$/,
2964
+ /^\/sessions\/activity$/,
2965
+ /^\/debug\/log-policy$/
2966
+ ];
2967
+ function bridgeAuthorityKeyEnv(tokenEnv) {
2968
+ return `${tokenEnv}_AUTHORITY_KEY`;
2969
+ }
2970
+ function isBridgeAuthorityKey(value) {
2971
+ return typeof value === "string" && KEY_PATTERN.test(value);
2972
+ }
2973
+ function publicKeyFrom(encoded) {
2974
+ if (!isBridgeAuthorityKey(encoded))
2975
+ return null;
2976
+ try {
2977
+ const key = createPublicKey({
2978
+ key: Buffer.from(encoded, "base64url"),
2979
+ format: "der",
2980
+ type: "spki"
2981
+ });
2982
+ return key.asymmetricKeyType === "ed25519" ? key : null;
2983
+ } catch {
2984
+ return null;
2985
+ }
2986
+ }
2987
+ function bridgeAuthorityTarget(url) {
2988
+ const parsed = new URL(url, "http://bridge.invalid");
2989
+ return `${parsed.pathname}${parsed.search}`;
2990
+ }
2991
+ function bridgeRequestNeedsAuthority(method, target) {
2992
+ if (READ_METHODS.has(method.toUpperCase()))
2993
+ return false;
2994
+ const pathname = bridgeAuthorityTarget(target).split("?", 1)[0];
2995
+ return !UNSIGNED_ROUTES.some((pattern) => pattern.test(pathname));
2996
+ }
2997
+ function bodyDigest(body) {
2998
+ return createHash("sha256").update(body ?? "").digest("hex");
2999
+ }
3000
+ function signedMessage(method, target, issuedAt, nonce, digest) {
3001
+ return Buffer.from([SCHEME, method.toUpperCase(), target, String(issuedAt), nonce, digest].join(`
3002
+ `));
3003
+ }
3004
+ var UNENFORCED = {
3005
+ enforced: false,
3006
+ requires: () => false,
3007
+ check: () => ({ ok: true })
3008
+ };
3009
+ function bridgeAuthorityFromPublicKey(publicKey, options = {}) {
3010
+ if (publicKey === undefined)
3011
+ return UNENFORCED;
3012
+ const key = publicKeyFrom(publicKey);
3013
+ const now = options.now ?? Date.now;
3014
+ const maxNonces = options.maxNonces ?? BRIDGE_AUTHORITY_MAX_NONCES;
3015
+ const seen = new Map;
3016
+ let floor = -Infinity;
3017
+ const remember = (nonce, issuedAt, current) => {
3018
+ for (const [oldNonce, oldIssuedAt] of seen) {
3019
+ if (seen.size < maxNonces && oldIssuedAt >= current - BRIDGE_AUTHORITY_WINDOW_MS)
3020
+ break;
3021
+ seen.delete(oldNonce);
3022
+ floor = Math.max(floor, oldIssuedAt);
3023
+ }
3024
+ seen.set(nonce, issuedAt);
3025
+ };
3026
+ return {
3027
+ enforced: true,
3028
+ requires: bridgeRequestNeedsAuthority,
3029
+ check(request) {
3030
+ if (!request.header)
3031
+ return { ok: false, reason: "missing" };
3032
+ const match = HEADER_PATTERN.exec(request.header.trim());
3033
+ if (!match)
3034
+ return { ok: false, reason: "malformed" };
3035
+ const issuedAt = Number(match[1]);
3036
+ const nonce = match[2];
3037
+ const current = now();
3038
+ if (Math.abs(current - issuedAt) > BRIDGE_AUTHORITY_WINDOW_MS || issuedAt <= floor) {
3039
+ return { ok: false, reason: "stale" };
3040
+ }
3041
+ if (!key)
3042
+ return { ok: false, reason: "invalid" };
3043
+ const valid = verify(null, signedMessage(request.method, bridgeAuthorityTarget(request.url), issuedAt, nonce, bodyDigest(request.body)), key, Buffer.from(match[3], "base64url"));
3044
+ if (!valid)
3045
+ return { ok: false, reason: "invalid" };
3046
+ if (seen.has(nonce))
3047
+ return { ok: false, reason: "replayed" };
3048
+ remember(nonce, issuedAt, current);
3049
+ return { ok: true };
3050
+ }
3051
+ };
3052
+ }
3053
+ function loadBridgeAuthority(tokenEnv, options = {}) {
3054
+ const env = options.env ?? process.env;
3055
+ const name = bridgeAuthorityKeyEnv(tokenEnv);
3056
+ const value = env[name]?.trim();
3057
+ delete env[name];
3058
+ return bridgeAuthorityFromPublicKey(value || undefined, { now: options.now });
3059
+ }
3060
+ function refusal(reason) {
3061
+ return {
3062
+ status: 403,
3063
+ body: {
3064
+ error: "This request changes an agent's authority and needs the backend's signature",
3065
+ code: BRIDGE_AUTHORITY_REFUSED_CODE,
3066
+ reason
3067
+ }
3068
+ };
3069
+ }
3070
+ var TOO_LARGE = {
3071
+ status: 413,
3072
+ body: { error: "Request body is too large" }
3073
+ };
3074
+ var admittedBodies = new WeakMap;
3075
+ async function admitNodeBridgeRequest(authority, request, maxBodyBytes) {
3076
+ const method = request.method ?? "GET";
3077
+ const url = request.url ?? "/";
3078
+ if (!authority.requires(method, url))
3079
+ return null;
3080
+ const header = request.headers[BRIDGE_AUTHORITY_HEADER];
3081
+ const value = Array.isArray(header) ? header[0] : header;
3082
+ if (!value)
3083
+ return refusal("missing");
3084
+ const chunks = [];
3085
+ let total = 0;
3086
+ for await (const chunk of request) {
3087
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
3088
+ total += buffer.length;
3089
+ if (total > maxBodyBytes)
3090
+ return TOO_LARGE;
3091
+ chunks.push(buffer);
3092
+ }
3093
+ const body = Buffer.concat(chunks);
3094
+ const result = authority.check({ method, url, header: value, body });
3095
+ if (!result.ok)
3096
+ return refusal(result.reason);
3097
+ admittedBodies.set(request, body);
3098
+ return null;
3099
+ }
3100
+ function takeAdmittedBody(request) {
3101
+ const body = admittedBodies.get(request);
3102
+ admittedBodies.delete(request);
3103
+ return body;
3104
+ }
3105
+
2824
3106
  // ../protocol/src/node/bridge-credential.ts
2825
3107
  var BRIDGE_TOKEN_PREFIX = "okb_";
2826
3108
  var PR_SET_DUMPABLE = 4;
2827
3109
  var VERIFIER_PATTERN = /^[0-9a-f]{64}$/;
2828
3110
  var log = createLogger("bridge.lifecycle");
2829
3111
  function mintBridgeToken() {
2830
- return `${BRIDGE_TOKEN_PREFIX}${randomBytes(32).toString("base64url")}`;
3112
+ return `${BRIDGE_TOKEN_PREFIX}${randomBytes2(32).toString("base64url")}`;
2831
3113
  }
2832
3114
  function bridgeTokenVerifier(token) {
2833
- return createHash("sha256").update(token).digest("hex");
3115
+ return createHash2("sha256").update(token).digest("hex");
2834
3116
  }
2835
3117
  function bridgeTokenVerifierEnv(tokenEnv) {
2836
3118
  return `${tokenEnv}_SHA256`;
2837
3119
  }
2838
- function credentialFromVerifier(verifier, plainToken) {
3120
+ function credentialFromVerifier(verifier, plainToken, authority = UNENFORCED_AUTHORITY) {
2839
3121
  const expected = Buffer.from(verifier, "hex");
2840
3122
  return {
2841
3123
  plainToken,
3124
+ authority,
2842
3125
  matches(candidate) {
2843
3126
  if (!candidate)
2844
3127
  return false;
2845
- return timingSafeEqual(expected, createHash("sha256").update(candidate).digest());
3128
+ return timingSafeEqual(expected, createHash2("sha256").update(candidate).digest());
2846
3129
  }
2847
3130
  };
2848
3131
  }
2849
- function bridgeCredentialFromToken(token) {
2850
- return credentialFromVerifier(bridgeTokenVerifier(token), token);
3132
+ var UNENFORCED_AUTHORITY = loadBridgeAuthority("", { env: {} });
3133
+ function bridgeCredentialFromToken(token, authority = UNENFORCED_AUTHORITY) {
3134
+ return credentialFromVerifier(bridgeTokenVerifier(token), token, authority);
2851
3135
  }
2852
3136
  function markProcessNonDumpable(loadFfi = () => createRequire(import.meta.url)("bun:ffi")) {
2853
3137
  if (process.platform !== "linux" || !process.versions.bun)
@@ -2879,11 +3163,12 @@ function loadBridgeCredential(tokenEnv, options = {}) {
2879
3163
  const token = env[tokenEnv]?.trim();
2880
3164
  delete env[verifierEnv];
2881
3165
  delete env[tokenEnv];
3166
+ const authority = loadBridgeAuthority(tokenEnv, { env });
2882
3167
  if (verifier) {
2883
3168
  (options.harden ?? markProcessNonDumpable)();
2884
- return VERIFIER_PATTERN.test(verifier) ? credentialFromVerifier(verifier, undefined) : bridgeCredentialFromToken(mintBridgeToken());
3169
+ return VERIFIER_PATTERN.test(verifier) ? credentialFromVerifier(verifier, undefined, authority) : bridgeCredentialFromToken(mintBridgeToken(), authority);
2885
3170
  }
2886
- return bridgeCredentialFromToken(token || mintBridgeToken());
3171
+ return bridgeCredentialFromToken(token || mintBridgeToken(), authority);
2887
3172
  }
2888
3173
 
2889
3174
  // ../../bridges/cursor-bridge/src/config.ts
@@ -2893,6 +3178,7 @@ var hostname = process.env.HOSTNAME?.trim() || "127.0.0.1";
2893
3178
  var workingDirectory = resolve(process.env.CWD?.trim() || process.cwd());
2894
3179
  var bridgeCredential = loadBridgeCredential("CURSOR_BRIDGE_TOKEN");
2895
3180
  var authToken = bridgeCredential.plainToken ?? "";
3181
+ var bridgeAuthority = bridgeCredential.authority;
2896
3182
  function applyWorkingDirectory(directory = workingDirectory) {
2897
3183
  const target = resolve(directory);
2898
3184
  if (process.cwd() === target)
@@ -27687,7 +27973,7 @@ ${read.text}` : read.text);
27687
27973
  }
27688
27974
 
27689
27975
  // ../protocol/src/node/revised-rows.ts
27690
- import { createHash as createHash2 } from "node:crypto";
27976
+ import { createHash as createHash3 } from "node:crypto";
27691
27977
  var RECENTLY_REVISED_ROWS_MAX = 128;
27692
27978
 
27693
27979
  class RecentlyRevisedRows {
@@ -27725,7 +28011,7 @@ class RecentlyRevisedRows {
27725
28011
  function revisedRowsReconciliationToken(overflowVersion, omitted) {
27726
28012
  if (overflowVersion === 0 && omitted.length === 0)
27727
28013
  return;
27728
- const digest = createHash2("sha256").update(String(overflowVersion));
28014
+ const digest = createHash3("sha256").update(String(overflowVersion));
27729
28015
  for (const row of omitted)
27730
28016
  digest.update(JSON.stringify(row) ?? "null");
27731
28017
  return digest.digest("hex");
@@ -29786,7 +30072,7 @@ function stringify(value) {
29786
30072
  }
29787
30073
  }
29788
30074
  // ../../bridges/cursor-bridge/src/translate.ts
29789
- import { randomBytes as randomBytes2 } from "node:crypto";
30075
+ import { randomBytes as randomBytes3 } from "node:crypto";
29790
30076
 
29791
30077
  // ../protocol/src/transcript-part-ids.ts
29792
30078
  var MAX_ORDINAL_DIGITS = 15;
@@ -30288,7 +30574,7 @@ function applyAppendedUserMessage(state, update) {
30288
30574
  const text = update.userMessage.text;
30289
30575
  if (!text)
30290
30576
  return;
30291
- const messageId = `appended-${randomBytes2(8).toString("hex")}`;
30577
+ const messageId = `appended-${randomBytes3(8).toString("hex")}`;
30292
30578
  const part = {
30293
30579
  type: "text",
30294
30580
  content: boundText(text, MAX_MESSAGE_TEXT_BYTES),
@@ -30399,7 +30685,7 @@ function currentAssistantMessage(state) {
30399
30685
  if (last?.role === "assistant" && last.id === state.currentAssistantMessageId)
30400
30686
  return last;
30401
30687
  const message = {
30402
- id: randomBytes2(12).toString("hex"),
30688
+ id: randomBytes3(12).toString("hex"),
30403
30689
  role: "assistant",
30404
30690
  content: "",
30405
30691
  parts: [],
@@ -30424,7 +30710,7 @@ var RESUME_FELL_BACK_NOTICE = "Could not resume the previous Cursor conversation
30424
30710
  function appendResumeFallbackNotice(state) {
30425
30711
  closeTextParts(state, undefined);
30426
30712
  state.currentAssistantMessageId = undefined;
30427
- const messageId = randomBytes2(12).toString("hex");
30713
+ const messageId = randomBytes3(12).toString("hex");
30428
30714
  const createdAt = new Date().toISOString();
30429
30715
  const part = {
30430
30716
  type: "status",
@@ -30769,13 +31055,13 @@ function cursorAppliedPolicy(state) {
30769
31055
  }
30770
31056
 
30771
31057
  // ../../bridges/cursor-bridge/src/agent-session.ts
30772
- import { createHash as createHash6, randomBytes as randomBytes5 } from "node:crypto";
31058
+ import { createHash as createHash7, randomBytes as randomBytes6 } from "node:crypto";
30773
31059
  import { readFile as readFile2 } from "node:fs/promises";
30774
31060
  import { homedir as homedir3 } from "node:os";
30775
31061
  import { join as join6 } from "node:path";
30776
31062
 
30777
31063
  // ../../bridges/cursor-bridge/src/persistence.ts
30778
- import { randomBytes as randomBytes4 } from "node:crypto";
31064
+ import { randomBytes as randomBytes5 } from "node:crypto";
30779
31065
  import { mkdir, open as open2, readdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
30780
31066
  import { basename, dirname, join as join3 } from "node:path";
30781
31067
 
@@ -31181,7 +31467,7 @@ function encodedBytes(requestId, value) {
31181
31467
  }
31182
31468
 
31183
31469
  // ../../bridges/cursor-bridge/src/session-factory.ts
31184
- import { randomBytes as randomBytes3 } from "node:crypto";
31470
+ import { randomBytes as randomBytes4 } from "node:crypto";
31185
31471
 
31186
31472
  // ../protocol/src/runtime-health.ts
31187
31473
  var MAX_RUNTIME_NOTICE_MESSAGE_LENGTH = 1000;
@@ -31271,7 +31557,7 @@ function emptyRuntimeHealth() {
31271
31557
  // ../../bridges/cursor-bridge/src/session-factory.ts
31272
31558
  function newSessionState(clientSessionKey, policy) {
31273
31559
  return {
31274
- id: randomBytes3(16).toString("hex"),
31560
+ id: randomBytes4(16).toString("hex"),
31275
31561
  ...policy ? { policy } : {},
31276
31562
  ...clientSessionKey ? { clientSessionKey } : {},
31277
31563
  status: "idle",
@@ -31343,7 +31629,7 @@ var UNSUPPORTED_DIRECTORY_SYNC = new Set(["EISDIR", "EPERM", "EINVAL", "ENOTSUP"
31343
31629
  var temporarySequence = 0;
31344
31630
  function temporaryPath(stateFile) {
31345
31631
  temporarySequence += 1;
31346
- return `${stateFile}.${process.pid}.${temporarySequence}.${randomBytes4(4).toString("hex")}.tmp`;
31632
+ return `${stateFile}.${process.pid}.${temporarySequence}.${randomBytes5(4).toString("hex")}.tmp`;
31347
31633
  }
31348
31634
  var TEMPORARY_NAME = /^(\d+)\.\d+\.[0-9a-f]+$/;
31349
31635
  var TEMPORARY_SWEEP_INTERVAL_MS = 10 * 60 * 1000;
@@ -32199,7 +32485,7 @@ import {
32199
32485
  } from "@cursor/sdk";
32200
32486
 
32201
32487
  // ../protocol/src/node/bridge-diagnostics.ts
32202
- import { createHash as createHash3 } from "node:crypto";
32488
+ import { createHash as createHash4 } from "node:crypto";
32203
32489
 
32204
32490
  // ../protocol/src/event-loop-stall-monitor.ts
32205
32491
  var log4 = createLogger("event-loop");
@@ -32298,7 +32584,7 @@ function sameSet(a, b) {
32298
32584
  function identity(value) {
32299
32585
  if (typeof value !== "string" || !value || value.length > MAX_ID_LENGTH)
32300
32586
  return;
32301
- return createHash3("sha256").update(value).digest("hex").slice(0, 16);
32587
+ return createHash4("sha256").update(value).digest("hex").slice(0, 16);
32302
32588
  }
32303
32589
  function readBridgeDebugFlag(value) {
32304
32590
  return value?.trim() === "1";
@@ -32698,7 +32984,7 @@ var bufferedFlushes = new Set;
32698
32984
 
32699
32985
  // ../../bridges/cursor-bridge/src/sdk-diagnostics.ts
32700
32986
  import { AsyncLocalStorage } from "node:async_hooks";
32701
- import { createHash as createHash4 } from "node:crypto";
32987
+ import { createHash as createHash5 } from "node:crypto";
32702
32988
  import * as sdk from "@cursor/sdk";
32703
32989
  var MAX_TRANSPORTS = 16;
32704
32990
  var MAX_EXECUTIONS = 128;
@@ -32796,7 +33082,7 @@ function object2(value) {
32796
33082
  function hash(value) {
32797
33083
  if (typeof value !== "string" || !value || value.length > 1024)
32798
33084
  return;
32799
- return createHash4("sha256").update(value).digest("hex").slice(0, 16);
33085
+ return createHash5("sha256").update(value).digest("hex").slice(0, 16);
32800
33086
  }
32801
33087
  function age(now, value) {
32802
33088
  return typeof value === "number" && Number.isFinite(value) ? Math.max(0, now - value) : null;
@@ -33676,7 +33962,7 @@ function workspaceObservationReportIssues(value) {
33676
33962
  }
33677
33963
 
33678
33964
  // ../protocol/src/node/change-tracking/evidence-spool.ts
33679
- import { createHash as createHash5, randomUUID } from "node:crypto";
33965
+ import { createHash as createHash6, randomUUID } from "node:crypto";
33680
33966
  import { readdirSync as readdirSync2, readFileSync as readFileSync2 } from "node:fs";
33681
33967
  import { appendFile, mkdir as mkdir2, rename as rename2, rm, writeFile as writeFile2 } from "node:fs/promises";
33682
33968
  import { join as join4 } from "node:path";
@@ -33692,10 +33978,10 @@ var DEFAULT_EVIDENCE_SPOOL_LIMITS = {
33692
33978
  var ENTRIES_FILE = "entries.jsonl";
33693
33979
  var BODY_DIRECTORY = "bodies";
33694
33980
  function evidenceBodyId(bytes) {
33695
- return `sha256:${createHash5("sha256").update(bytes).digest("hex")}`;
33981
+ return `sha256:${createHash6("sha256").update(bytes).digest("hex")}`;
33696
33982
  }
33697
33983
  function stableEvidenceId(...parts) {
33698
- const hash = createHash5("sha256");
33984
+ const hash = createHash6("sha256");
33699
33985
  for (const part of parts)
33700
33986
  hash.update(`${part ?? ""}\x00`);
33701
33987
  return hash.digest("hex").slice(0, 40);
@@ -35164,7 +35450,7 @@ function markConfigResumePending(state, pending) {
35164
35450
  }
35165
35451
  async function fileDigest(file) {
35166
35452
  try {
35167
- return `sha256:${createHash6("sha256").update(await readFile2(file)).digest("base64url")}`;
35453
+ return `sha256:${createHash7("sha256").update(await readFile2(file)).digest("base64url")}`;
35168
35454
  } catch {
35169
35455
  return "absent";
35170
35456
  }
@@ -35179,7 +35465,7 @@ async function cursorMcpConfigRevision(state) {
35179
35465
  policy.projectResources ? fileDigest(join6(workingDirectory, ".cursor", "mcp.json")) : Promise.resolve("excluded")
35180
35466
  ]);
35181
35467
  return {
35182
- fingerprint: createHash6("sha256").update(`user=${user}\x00project=${project}`).digest("base64url"),
35468
+ fingerprint: createHash7("sha256").update(`user=${user}\x00project=${project}`).digest("base64url"),
35183
35469
  sources: { user, project }
35184
35470
  };
35185
35471
  }
@@ -35849,7 +36135,7 @@ function appendHistoricTurn(state, turn, runId) {
35849
36135
  pushHistoricRow(state, row, planned);
35850
36136
  }
35851
36137
  function newHistoricRow() {
35852
- return { messageId: randomBytes5(12).toString("hex"), parts: [], content: "" };
36138
+ return { messageId: randomBytes6(12).toString("hex"), parts: [], content: "" };
35853
36139
  }
35854
36140
  function pushHistoricRow(state, row, planned) {
35855
36141
  if (row.parts.length === 0)
@@ -35914,7 +36200,7 @@ function appendHistoricShellTurn(state, body) {
35914
36200
  args: body.shellCommand,
35915
36201
  ...isObject(body.shellOutput) ? { result: { status: "success", value: body.shellOutput } } : {}
35916
36202
  });
35917
- const messageId = randomBytes5(12).toString("hex");
36203
+ const messageId = randomBytes6(12).toString("hex");
35918
36204
  pushMessage(state, "assistant", "", [
35919
36205
  {
35920
36206
  type: "tool-invocation",
@@ -35931,7 +36217,7 @@ function appendHistoricShellTurn(state, body) {
35931
36217
  }
35932
36218
  ], messageId);
35933
36219
  }
35934
- function pushMessage(state, role, content, parts, messageId = randomBytes5(12).toString("hex"), extras) {
36220
+ function pushMessage(state, role, content, parts, messageId = randomBytes6(12).toString("hex"), extras) {
35935
36221
  const message = {
35936
36222
  id: messageId,
35937
36223
  role,
@@ -36348,7 +36634,7 @@ var STRUCTURED_OUTPUT_FAILURE_CODES = new Set([
36348
36634
  ]);
36349
36635
 
36350
36636
  // ../../bridges/cursor-bridge/src/prompt.ts
36351
- import { randomUUID as randomUUID3 } from "node:crypto";
36637
+ import { randomUUID as randomUUID4 } from "node:crypto";
36352
36638
 
36353
36639
  // ../../bridges/cursor-bridge/src/command-changes.ts
36354
36640
  import { resolve as resolve5 } from "node:path";
@@ -36378,12 +36664,850 @@ function isFileEditToolName(toolName) {
36378
36664
  }
36379
36665
 
36380
36666
  // ../protocol/src/node/workspace-change-probe.ts
36381
- import { execFile, spawn } from "node:child_process";
36382
- import { randomUUID as randomUUID2 } from "node:crypto";
36383
- import { rmSync } from "node:fs";
36667
+ import { randomUUID as randomUUID3 } from "node:crypto";
36668
+ import { rmSync as rmSync2 } from "node:fs";
36384
36669
  import { copyFile, lstat, mkdtemp, rm as rm2 } from "node:fs/promises";
36385
36670
  import { tmpdir } from "node:os";
36386
36671
  import { delimiter, isAbsolute as isAbsolute4, join as join8, resolve as resolve4 } from "node:path";
36672
+
36673
+ // ../protocol/src/node/command-capture.ts
36674
+ import { spawn } from "node:child_process";
36675
+ import { randomUUID as randomUUID2 } from "node:crypto";
36676
+ import { constants as fsConstants } from "node:fs";
36677
+ import * as captureFs from "node:fs";
36678
+ import os from "node:os";
36679
+ import path from "node:path";
36680
+ import { inspect } from "node:util";
36681
+
36682
+ // ../protocol/src/node/command-failure-reason.ts
36683
+ var MAX_MATCHED_CHARS = 16 * 1024;
36684
+ var SIGNAL_PATTERN = /^SIG[A-Z0-9]{1,16}$/;
36685
+ var TOOL_RULES = {
36686
+ git: [
36687
+ ["branch-exists", /a branch named .* already exists/i],
36688
+ ["ref-conflict", /exists; cannot create|cannot lock ref .* is at .* but expected/i],
36689
+ ["lock-held", /could not lock config file [^\n]*: File exists/i],
36690
+ ["lock-held", /(?:unable to create '[^\n]*\.lock'|cannot lock ref)[^\n]*: File exists/i],
36691
+ ["lock-held", /another git process/i],
36692
+ ["worktree-conflict", /already (?:checked out|used by worktree)|used by worktree at/i],
36693
+ ["invalid-ref", /not a valid (?:branch name|object name)|bad (?:revision|object)/i],
36694
+ ["invalid-ref", /unknown revision|ambiguous argument|invalid reference/i],
36695
+ ["branch-not-found", /no branch named|refname .* not found|branch '.*' not found/i],
36696
+ ["branch-not-found", /did not match any file\(s\) known to git/i],
36697
+ ["dubious-ownership", /detected dubious ownership/i],
36698
+ ["no-remote", /does not appear to be a git repository|no such remote/i],
36699
+ ["no-remote", /repository (?:.* )?not found/i],
36700
+ ["not-a-repository", /not a git repository/i],
36701
+ ["remote-ref-missing", /could(?:n't| not) find remote ref|not our ref/i],
36702
+ ["merge-conflict", /\bCONFLICT \(|merge conflict|could not apply|unmerged files/i],
36703
+ ["dirty-worktree", /local changes .* would be overwritten|commit your changes or stash/i],
36704
+ ["nothing-to-commit", /nothing to commit|no changes added to commit/i],
36705
+ ["push-rejected", /\[(?:remote )?rejected\]|non-fast-forward/i],
36706
+ ["identity-unknown", /please tell me who you are|unable to auto-detect email/i],
36707
+ [
36708
+ "worktree-has-changes",
36709
+ /^fatal: [^\n]*['"] contains modified or untracked files(?:, use --force to delete it)?\.?\s*$/im
36710
+ ],
36711
+ ["not-a-worktree", /^fatal: [^\n]*['"] is not a working tree\.?\s*$/im],
36712
+ ["branch-not-merged", /^(?:error|fatal): [^\n]*['"] is not fully merged\.?\s*$/im]
36713
+ ],
36714
+ gh: [
36715
+ ["pull-request-exists", /a pull request for branch .* already exists/i],
36716
+ ["no-pull-request", /no (?:pull requests? (?:found|match)|open pull requests?\b)/i],
36717
+ ["rate-limited", /rate limit|http 429/i],
36718
+ ["forbidden", /http 403|resource not accessible/i],
36719
+ ["resource-not-found", /http 404|could not resolve to a/i],
36720
+ ["server-error", /http 5\d\d/i]
36721
+ ],
36722
+ docker: [
36723
+ ["daemon-unavailable", /cannot connect to the docker daemon|error during connect/i],
36724
+ [
36725
+ "daemon-unavailable",
36726
+ /is the docker daemon running|docker desktop is (?:not running|unable)/i
36727
+ ],
36728
+ ["container-not-found", /no such container/i],
36729
+ ["container-not-running", /container .* is (?:not running|paused|restarting)/i],
36730
+ ["container-name-conflict", /name .* is already in use/i],
36731
+ ["image-not-found", /no such image|pull access denied|manifest .* not found/i],
36732
+ ["image-not-found", /manifest unknown|repository does not exist/i],
36733
+ ["removal-in-progress", /removal of container .* is already in progress/i],
36734
+ [
36735
+ "image-in-use",
36736
+ /image is (?:being used|referenced)|unable to (?:remove|delete) .*must be forced/i
36737
+ ],
36738
+ ["volume-in-use", /volume is in use/i],
36739
+ ["volume-not-found", /no such volume/i],
36740
+ ["network-in-use", /has active endpoints/i],
36741
+ ["network-not-found", /network .* not found/i]
36742
+ ],
36743
+ tmux: [
36744
+ ["session-exists", /duplicate session/i],
36745
+ [
36746
+ "server-not-running",
36747
+ /no server running|failed to connect to server|no sessions|server exited|lost server/i
36748
+ ],
36749
+ [
36750
+ "server-not-running",
36751
+ /error connecting to \/[^\n]* \((?:No such file or directory|Connection refused)\)/i
36752
+ ],
36753
+ ["session-not-found", /can't find (?:session|window|pane)|session not found/i]
36754
+ ]
36755
+ };
36756
+ var ALL_TOOLS = Object.keys(TOOL_RULES);
36757
+ var SHARED_RULES = [
36758
+ ["disk-full", /no space left|enospc|disk quota exceeded/i],
36759
+ ["auth-failed", /authentication (?:failed|required)|could not read (?:username|password)/i],
36760
+ ["auth-failed", /terminal prompts disabled|invalid username or password|bad credentials/i],
36761
+ ["auth-failed", /permission denied \(|permission to \S+ denied|host key verification failed/i],
36762
+ ["auth-failed", /gh auth login|not logged in|unauthorized|http 401|returned error: 40[13]/i],
36763
+ ["network-failed", /could not resolve host|connection (?:timed out|refused|reset)/i],
36764
+ ["network-failed", /network is unreachable|no route to host|temporary failure in name/i],
36765
+ ["network-failed", /early eof|failed to connect|remote end hung up/i],
36766
+ ["network-failed", /unable to access ['"]?https?:\/\//i],
36767
+ ["network-failed", /tls handshake|i\/o timeout/i],
36768
+ [
36769
+ "network-failed",
36770
+ /error connecting to (?:https?:\/\/)?[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?::\d+)?(?:[\s/:]|$)/i
36771
+ ],
36772
+ ["port-in-use", /port is already allocated|address already in use/i],
36773
+ ["permission-denied", /permission denied|operation not permitted|read-only file system/i],
36774
+ ["command-not-found", /command not found/i],
36775
+ ["path-not-found", /no such file or directory/i],
36776
+ ["invalid-usage", /^usage: |unknown (?:option|flag|command|shorthand flag)|invalid option/im]
36777
+ ];
36778
+ var TOOL_EXIT_CODES = {
36779
+ git: { 129: "invalid-usage" },
36780
+ gh: { 2: "aborted", 4: "auth-failed" },
36781
+ docker: { 125: "daemon-error" },
36782
+ tmux: {}
36783
+ };
36784
+ var SHARED_EXIT_CODES = {
36785
+ 124: "timed-out",
36786
+ 126: "not-executable",
36787
+ 127: "command-not-found",
36788
+ 137: "killed",
36789
+ 143: "killed"
36790
+ };
36791
+ function read2(target, key) {
36792
+ return target[key];
36793
+ }
36794
+ function boundedForMatching(text) {
36795
+ if (text.length <= MAX_MATCHED_CHARS)
36796
+ return text;
36797
+ const half = MAX_MATCHED_CHARS / 2;
36798
+ return `${text.slice(0, half)}
36799
+ ${text.slice(-half)}`;
36800
+ }
36801
+ function failureText(error) {
36802
+ const stderr = read2(error, "stderr");
36803
+ if (Buffer.isBuffer(stderr) && stderr.length > 0) {
36804
+ return boundedForMatching(stderr.subarray(-MAX_MATCHED_CHARS).toString());
36805
+ }
36806
+ if (typeof stderr === "string" && stderr.length > 0)
36807
+ return boundedForMatching(stderr);
36808
+ const message = read2(error, "message");
36809
+ if (typeof message !== "string")
36810
+ return "";
36811
+ return message.startsWith("Command failed") ? "" : boundedForMatching(message);
36812
+ }
36813
+ function isRawSpawnEnoent(error) {
36814
+ const syscall = read2(error, "syscall");
36815
+ return read2(error, "code") === "ENOENT" && typeof syscall === "string" && /^(?:spawn(?:Sync)?(?:\s|$)|posix_spawnp?$)/.test(syscall);
36816
+ }
36817
+ function classifiedReason(error, exitCode, signal, options) {
36818
+ if (read2(error, "aborted") === true)
36819
+ return "aborted";
36820
+ if (read2(error, "outputLimitExceeded") === true)
36821
+ return "output-too-large";
36822
+ if (read2(error, "timedOut") === true)
36823
+ return "timed-out";
36824
+ if (read2(error, "executableMissing") === true || isRawSpawnEnoent(error)) {
36825
+ return "executable-missing";
36826
+ }
36827
+ const named = exitCode === null ? undefined : options.exitCodes?.[exitCode];
36828
+ if (named)
36829
+ return named;
36830
+ if (signal)
36831
+ return "killed";
36832
+ const text = failureText(error);
36833
+ for (const tool of options.tools ?? ALL_TOOLS) {
36834
+ for (const [reason, pattern] of TOOL_RULES[tool]) {
36835
+ if (pattern.test(text))
36836
+ return reason;
36837
+ }
36838
+ }
36839
+ for (const [reason, pattern] of SHARED_RULES) {
36840
+ if (pattern.test(text))
36841
+ return reason;
36842
+ }
36843
+ if (exitCode !== null) {
36844
+ for (const tool of options.tools ?? []) {
36845
+ const reason = TOOL_EXIT_CODES[tool][exitCode];
36846
+ if (reason)
36847
+ return reason;
36848
+ }
36849
+ const reason = SHARED_EXIT_CODES[exitCode];
36850
+ if (reason)
36851
+ return reason;
36852
+ }
36853
+ return "unclassified";
36854
+ }
36855
+ function numericExitCode(error) {
36856
+ for (const key of ["exitCode", "code"]) {
36857
+ const value = read2(error, key);
36858
+ if (typeof value === "number" && Number.isFinite(value))
36859
+ return value;
36860
+ }
36861
+ return null;
36862
+ }
36863
+ function classifyCommandFailure(error, options = {}) {
36864
+ if (typeof error !== "object" || error === null) {
36865
+ return { reason: "unclassified", exitCode: null, signal: null };
36866
+ }
36867
+ try {
36868
+ const exitCode = numericExitCode(error);
36869
+ const rawSignal = read2(error, "signal");
36870
+ const signal = typeof rawSignal === "string" && SIGNAL_PATTERN.test(rawSignal) ? rawSignal : null;
36871
+ return { reason: classifiedReason(error, exitCode, signal, options), exitCode, signal };
36872
+ } catch {
36873
+ return { reason: "unclassified", exitCode: null, signal: null };
36874
+ }
36875
+ }
36876
+
36877
+ // ../protocol/src/node/lost-exit-reaper.ts
36878
+ import { createRequire as createRequire2 } from "node:module";
36879
+
36880
+ // ../protocol/src/node/shell-process-state.ts
36881
+ import { spawnSync } from "node:child_process";
36882
+ import { readdirSync as readdirSync3, readFileSync as readFileSync3 } from "node:fs";
36883
+ import { constants as osConstants } from "node:os";
36884
+ var PROCESS_INSPECTION_OPTIONS = {
36885
+ timeout: 100,
36886
+ killSignal: "SIGKILL",
36887
+ maxBuffer: 1024 * 1024
36888
+ };
36889
+ function bunRuntime() {
36890
+ return globalThis.Bun;
36891
+ }
36892
+ function decodeWaitStatus(status) {
36893
+ const signalNumber = status & 127;
36894
+ if (signalNumber === 0)
36895
+ return { code: status >> 8 & 255, signal: null };
36896
+ const name = Object.entries(osConstants.signals).find(([, value]) => value === signalNumber)?.[0];
36897
+ return { code: null, signal: name ?? "SIGKILL" };
36898
+ }
36899
+ function readZombieExit(pid) {
36900
+ try {
36901
+ const result = bunRuntime()?.spawnSync(["/bin/ps", "-o", "stat=,xstat=", "-p", String(pid)], PROCESS_INSPECTION_OPTIONS);
36902
+ if (!result?.success)
36903
+ return;
36904
+ const { stdout } = result;
36905
+ const match = /^Z\S*\s+([0-9a-f]+)\s*$/i.exec(stdout.toString().trim());
36906
+ return match ? decodeWaitStatus(Number.parseInt(match[1], 16)) : undefined;
36907
+ } catch {
36908
+ return;
36909
+ }
36910
+ }
36911
+ var EXIT_WATCH_MS = 1000;
36912
+ var EXIT_WATCH_MAX_MS = 16000;
36913
+ function watchForLostExit(pid, onExit) {
36914
+ if (process.platform !== "darwin" || pid === undefined || !bunRuntime())
36915
+ return () => {
36916
+ return;
36917
+ };
36918
+ let timer;
36919
+ const watch = (delayMs) => {
36920
+ timer = setTimeout(() => {
36921
+ const exit = readZombieExit(pid);
36922
+ if (exit)
36923
+ onExit(exit);
36924
+ else
36925
+ watch(Math.min(delayMs * 2, EXIT_WATCH_MAX_MS));
36926
+ }, delayMs);
36927
+ };
36928
+ watch(EXIT_WATCH_MS);
36929
+ return () => clearTimeout(timer);
36930
+ }
36931
+ function isLiveMember(state, groupId, pgid) {
36932
+ return Number(groupId) === pgid && state !== undefined && !/^[ZX]/.test(state);
36933
+ }
36934
+ function linuxGroupHasLiveMember(pgid) {
36935
+ for (const entry of readdirSync3("/proc")) {
36936
+ if (!/^\d+$/.test(entry))
36937
+ continue;
36938
+ let stat;
36939
+ try {
36940
+ stat = readFileSync3(`/proc/${entry}/stat`, "latin1");
36941
+ } catch {
36942
+ continue;
36943
+ }
36944
+ const [state, , groupId] = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
36945
+ if (isLiveMember(state, groupId, pgid))
36946
+ return true;
36947
+ }
36948
+ return false;
36949
+ }
36950
+ function psGroupHasLiveMember(pgid) {
36951
+ const argv = ["-A", "-o", "pgid=,stat="];
36952
+ const bun = bunRuntime();
36953
+ const result = bun ? bun.spawnSync(["/bin/ps", ...argv], PROCESS_INSPECTION_OPTIONS) : spawnSync("/bin/ps", argv, PROCESS_INSPECTION_OPTIONS);
36954
+ const succeeded = "success" in result ? result.success : result.status === 0 && !result.error;
36955
+ if (!succeeded)
36956
+ return true;
36957
+ return result.stdout.toString().split(`
36958
+ `).some((line) => {
36959
+ const [groupId, state] = line.trim().split(/\s+/);
36960
+ return isLiveMember(state, groupId, pgid);
36961
+ });
36962
+ }
36963
+ function groupHasLiveMember(pgid) {
36964
+ try {
36965
+ return process.platform === "linux" ? linuxGroupHasLiveMember(pgid) : psGroupHasLiveMember(pgid);
36966
+ } catch {
36967
+ return true;
36968
+ }
36969
+ }
36970
+
36971
+ // ../protocol/src/node/lost-exit-reaper.ts
36972
+ var log7 = createLogger("process");
36973
+ var REAP_GRACE_MS = 2000;
36974
+ var REAP_MAX_CHECK_MS = 30000;
36975
+ var REAP_MAX_CHECKS = 12;
36976
+ var REAP_MAX_PENDING = 256;
36977
+ function createLostExitReaper(options) {
36978
+ const { system } = options;
36979
+ const graceMs = options.graceMs ?? REAP_GRACE_MS;
36980
+ const maxCheckMs = options.maxCheckMs ?? REAP_MAX_CHECK_MS;
36981
+ const maxChecks = options.maxChecks ?? REAP_MAX_CHECKS;
36982
+ const maxPending = options.maxPending ?? REAP_MAX_PENDING;
36983
+ const pending = new Map;
36984
+ let reaped = 0;
36985
+ let abandoned = 0;
36986
+ const abandon = (pid, reason) => {
36987
+ abandoned += 1;
36988
+ log7.warn("child.reap-abandoned", { pid, reason });
36989
+ };
36990
+ const check = (pid, reported, startedAt) => {
36991
+ if (reported())
36992
+ return false;
36993
+ const found = system.inspect(pid);
36994
+ if (found === undefined)
36995
+ return true;
36996
+ if (found === "gone" || found.ppid !== system.selfPid)
36997
+ return false;
36998
+ if (!found.state.startsWith("Z"))
36999
+ return true;
37000
+ const result = system.waitNoHang(pid);
37001
+ if (result === pid) {
37002
+ reaped += 1;
37003
+ log7.info("child.reaped", { pid, waitedMs: Date.now() - startedAt });
37004
+ return false;
37005
+ }
37006
+ if (result === 0)
37007
+ return true;
37008
+ abandon(pid, "waitpid-failed");
37009
+ return false;
37010
+ };
37011
+ const schedule = (pid, reported, startedAt, delayMs, checks) => {
37012
+ const timer = setTimeout(() => {
37013
+ pending.delete(pid);
37014
+ let again;
37015
+ try {
37016
+ again = check(pid, reported, startedAt);
37017
+ } catch {
37018
+ again = true;
37019
+ }
37020
+ if (!again)
37021
+ return;
37022
+ if (checks + 1 >= maxChecks) {
37023
+ abandon(pid, "not-a-zombie");
37024
+ return;
37025
+ }
37026
+ schedule(pid, reported, startedAt, Math.min(delayMs * 2, maxCheckMs), checks + 1);
37027
+ }, delayMs);
37028
+ timer.unref?.();
37029
+ pending.set(pid, timer);
37030
+ };
37031
+ return {
37032
+ reap(pid, reported) {
37033
+ if (!Number.isSafeInteger(pid) || pid <= 1 || pid === system.selfPid)
37034
+ return;
37035
+ if (pending.has(pid) || reported())
37036
+ return;
37037
+ if (pending.size >= maxPending) {
37038
+ abandon(pid, "capacity");
37039
+ return;
37040
+ }
37041
+ schedule(pid, reported, Date.now(), graceMs, 0);
37042
+ },
37043
+ stats: () => ({ pending: pending.size, reaped, abandoned }),
37044
+ stop() {
37045
+ for (const timer of pending.values())
37046
+ clearTimeout(timer);
37047
+ pending.clear();
37048
+ }
37049
+ };
37050
+ }
37051
+ var WNOHANG = 1;
37052
+ function loadDarwinWaitpid(loadFfi = () => createRequire2(import.meta.url)("bun:ffi")) {
37053
+ try {
37054
+ const { dlopen, FFIType } = loadFfi();
37055
+ const libSystem = dlopen("/usr/lib/libSystem.B.dylib", {
37056
+ waitpid: { args: [FFIType.i32, FFIType.ptr, FFIType.i32], returns: FFIType.i32 }
37057
+ });
37058
+ const status = new Int32Array(1);
37059
+ return (pid) => libSystem.symbols.waitpid(pid, status, WNOHANG);
37060
+ } catch {
37061
+ return;
37062
+ }
37063
+ }
37064
+ function darwinReaperSystem(loadFfi) {
37065
+ const waitNoHang = loadDarwinWaitpid(loadFfi);
37066
+ if (!waitNoHang)
37067
+ return;
37068
+ return {
37069
+ selfPid: process.pid,
37070
+ inspect(pid) {
37071
+ const result = bunRuntime()?.spawnSync(["/bin/ps", "-o", "ppid=,stat=", "-p", String(pid)], PROCESS_INSPECTION_OPTIONS);
37072
+ if (!result)
37073
+ return;
37074
+ const output = result.stdout.toString().trim();
37075
+ if (!result.success)
37076
+ return result.exitCode === 1 && output === "" ? "gone" : undefined;
37077
+ const match = /^(\d+)\s+(\S+)$/.exec(output);
37078
+ return match ? { ppid: Number(match[1]), state: match[2] } : undefined;
37079
+ },
37080
+ waitNoHang
37081
+ };
37082
+ }
37083
+ var defaultReaper;
37084
+ function createDarwinLostExitReaper(loadFfi) {
37085
+ const system = darwinReaperSystem(loadFfi);
37086
+ if (!system)
37087
+ log7.warn("child.reap-unavailable");
37088
+ return system ? createLostExitReaper({ system }) : null;
37089
+ }
37090
+ function sharedReaper() {
37091
+ if (defaultReaper === undefined) {
37092
+ defaultReaper = createDarwinLostExitReaper();
37093
+ }
37094
+ return defaultReaper ?? undefined;
37095
+ }
37096
+ function reapAfterLostExit(pid, reported) {
37097
+ if (process.platform !== "darwin" || pid === undefined || !bunRuntime())
37098
+ return;
37099
+ sharedReaper()?.reap(pid, reported);
37100
+ }
37101
+
37102
+ // ../protocol/src/node/command-capture.ts
37103
+ class CommandFailedError extends Error {
37104
+ stdout;
37105
+ stdoutBytes;
37106
+ stderr;
37107
+ timedOut;
37108
+ outputCloseTimedOut;
37109
+ executableMissing;
37110
+ aborted;
37111
+ outputLimitExceeded;
37112
+ exitCode;
37113
+ signal;
37114
+ constructor(message, details = {}) {
37115
+ super(message);
37116
+ this.name = "CommandFailedError";
37117
+ this.stdout = details.stdout ?? "";
37118
+ this.stdoutBytes = details.stdoutBytes ?? Buffer.alloc(0);
37119
+ this.stderr = details.stderr ?? "";
37120
+ this.timedOut = details.timedOut ?? false;
37121
+ this.outputCloseTimedOut = details.outputCloseTimedOut ?? false;
37122
+ this.executableMissing = details.executableMissing ?? false;
37123
+ this.aborted = details.aborted ?? false;
37124
+ this.outputLimitExceeded = details.outputLimitExceeded ?? false;
37125
+ this.exitCode = details.exitCode ?? null;
37126
+ this.signal = details.signal ?? null;
37127
+ }
37128
+ toJSON() {
37129
+ return { ...formatLogError(this), ...classifyCommandFailure(this) };
37130
+ }
37131
+ [inspect.custom]() {
37132
+ const { name, reason, exitCode, signal, stack } = this.toJSON();
37133
+ const frames = stack?.length ? ` | ${stack.join(" | ")}` : "";
37134
+ return `${name} reason=${reason} exitCode=${exitCode} signal=${signal} outputOmitted=true${frames}`;
37135
+ }
37136
+ }
37137
+ function redactCommandValues(value, redactValues) {
37138
+ const secrets = Array.from(new Set((redactValues ?? []).filter((secret) => typeof secret === "string" && secret.length > 0))).sort((left, right) => right.length - left.length);
37139
+ return secrets.reduce((redacted, secret) => redacted.split(secret).join("[REDACTED]"), value);
37140
+ }
37141
+ var COMMAND_ABORTED_MESSAGE = "Command aborted";
37142
+ var OUTPUT_LIMIT_MESSAGE = "maxBuffer length exceeded";
37143
+ function commandFailureOutcome(error) {
37144
+ const details = error ?? {};
37145
+ const message = typeof details.message === "string" ? details.message : "";
37146
+ return {
37147
+ timedOut: details.killed === true,
37148
+ executableMissing: details.code === "ENOENT",
37149
+ aborted: message === COMMAND_ABORTED_MESSAGE,
37150
+ outputLimitExceeded: details.outputLimitExceeded === true,
37151
+ exitCode: typeof details.code === "number" ? details.code : null,
37152
+ signal: details.signal ?? null
37153
+ };
37154
+ }
37155
+ var commandInvocations = new Map;
37156
+ var commandCaptureMetrics;
37157
+ var commandObservers = new Map;
37158
+ function nonInteractiveGitEnv(env) {
37159
+ const merged = { ...env ?? process.env };
37160
+ merged.GIT_TERMINAL_PROMPT ??= "0";
37161
+ if (process.platform !== "win32") {
37162
+ merged.SSH_ASKPASS ??= "/usr/bin/false";
37163
+ merged.SSH_ASKPASS_REQUIRE ??= "force";
37164
+ }
37165
+ return merged;
37166
+ }
37167
+ var MAX_COMMAND_OUTPUT_BYTES = 50 * 1024 * 1024;
37168
+ var COMMAND_KILL_GRACE_MS = 100;
37169
+ var COMMAND_OUTPUT_CHECK_MS = 100;
37170
+ var COMMAND_GROUP_POLL_MS = 5;
37171
+ var COMMAND_GROUP_POLL_MAX_MS = 200;
37172
+ function openCaptureFile() {
37173
+ const filePath = path.join(os.tmpdir(), `orkestrator-capture-${randomUUID2()}`);
37174
+ const fd = captureFs.openSync(filePath, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_RDWR | fsConstants.O_APPEND, 384);
37175
+ try {
37176
+ captureFs.unlinkSync(filePath);
37177
+ return fd;
37178
+ } catch (error) {
37179
+ captureFs.closeSync(fd);
37180
+ throw error;
37181
+ }
37182
+ }
37183
+ function readCaptureFile(fd, limit) {
37184
+ const size = Math.min(captureFs.fstatSync(fd).size, limit);
37185
+ const buffer = Buffer.allocUnsafe(size);
37186
+ let offset = 0;
37187
+ while (offset < size) {
37188
+ const bytesRead = captureFs.readSync(fd, buffer, offset, size - offset, offset);
37189
+ if (bytesRead === 0)
37190
+ break;
37191
+ offset += bytesRead;
37192
+ }
37193
+ return buffer.subarray(0, offset);
37194
+ }
37195
+ function spawnCaptured(command, args, options, stdoutFd, stderrFd) {
37196
+ const payload = options.stdin?.length ? Buffer.from(options.stdin) : undefined;
37197
+ const env = command === "git" ? nonInteractiveGitEnv(options.env) : options.env ?? process.env;
37198
+ const detached = process.platform !== "win32";
37199
+ const bun = bunRuntime();
37200
+ if (bun) {
37201
+ const child = bun.spawn([command, ...args], {
37202
+ cwd: options.cwd,
37203
+ env,
37204
+ detached,
37205
+ windowsHide: true,
37206
+ stdin: payload ?? "pipe",
37207
+ stdout: stdoutFd,
37208
+ stderr: stderrFd
37209
+ });
37210
+ if (!payload)
37211
+ closeStdin(child.stdin);
37212
+ const current = () => ({ code: child.exitCode, signal: child.signalCode });
37213
+ return {
37214
+ pid: child.pid,
37215
+ exited: child.exited.then(current),
37216
+ current,
37217
+ kill: (signal) => child.kill(signal)
37218
+ };
37219
+ }
37220
+ const child = spawn(command, args, {
37221
+ cwd: options.cwd,
37222
+ env,
37223
+ detached,
37224
+ windowsHide: true,
37225
+ stdio: [payload ? "pipe" : "ignore", stdoutFd, stderrFd]
37226
+ });
37227
+ if (payload) {
37228
+ child.stdin?.on("error", () => {
37229
+ return;
37230
+ });
37231
+ child.stdin?.end(payload);
37232
+ }
37233
+ return {
37234
+ pid: child.pid,
37235
+ exited: new Promise((resolve, reject) => {
37236
+ child.once("exit", (code, signal) => resolve({ code, signal }));
37237
+ child.once("error", reject);
37238
+ }),
37239
+ current: () => ({ code: child.exitCode, signal: child.signalCode }),
37240
+ kill: (signal) => {
37241
+ child.kill(signal);
37242
+ }
37243
+ };
37244
+ }
37245
+ function closeStdin(stdin) {
37246
+ try {
37247
+ Promise.resolve(stdin.end()).catch(() => {
37248
+ return;
37249
+ });
37250
+ } catch {}
37251
+ }
37252
+ function exitReported(child) {
37253
+ const { code, signal } = child.current();
37254
+ return code !== null || signal !== null;
37255
+ }
37256
+ function signalCommand(child, signal) {
37257
+ if (child.pid === undefined)
37258
+ return;
37259
+ try {
37260
+ if (process.platform !== "win32") {
37261
+ process.kill(-child.pid, signal);
37262
+ } else {
37263
+ child.kill(signal);
37264
+ }
37265
+ } catch {}
37266
+ }
37267
+ function commandGroupAlive(child) {
37268
+ if (process.platform === "win32" || child.pid === undefined)
37269
+ return false;
37270
+ try {
37271
+ process.kill(-child.pid, 0);
37272
+ } catch (error) {
37273
+ if (error.code === "ESRCH")
37274
+ return false;
37275
+ }
37276
+ return groupHasLiveMember(child.pid);
37277
+ }
37278
+ function executeCommandBytes(command, args, options, timeoutMs, outputLimit, stderrLimit) {
37279
+ return new Promise((resolve, reject) => {
37280
+ if (options.signal?.aborted) {
37281
+ reject(Object.assign(new Error(COMMAND_ABORTED_MESSAGE), { killed: true }));
37282
+ return;
37283
+ }
37284
+ const captureFds = [];
37285
+ const releaseCaptureFds = () => {
37286
+ for (const fd of captureFds.splice(0)) {
37287
+ try {
37288
+ captureFs.closeSync(fd);
37289
+ } catch {}
37290
+ }
37291
+ };
37292
+ try {
37293
+ captureFds.push(openCaptureFile());
37294
+ captureFds.push(openCaptureFile());
37295
+ } catch (error) {
37296
+ releaseCaptureFds();
37297
+ const code = error.code ?? "unknown";
37298
+ reject(new Error(`Could not open a command output file in the temporary directory: ${code}`));
37299
+ return;
37300
+ }
37301
+ const [stdoutFd, stderrFd] = captureFds;
37302
+ let child;
37303
+ try {
37304
+ child = spawnCaptured(command, args, options, stdoutFd, stderrFd);
37305
+ } catch (error) {
37306
+ releaseCaptureFds();
37307
+ reject(error);
37308
+ return;
37309
+ }
37310
+ let settled = false;
37311
+ let timedOut = false;
37312
+ let timeoutTimer;
37313
+ let groupTimer;
37314
+ let limitTimer;
37315
+ let stopExitWatch = () => {};
37316
+ let commandExit;
37317
+ let pendingFailure;
37318
+ const finishCapture = () => {
37319
+ settled = true;
37320
+ clearTimeout(timeoutTimer);
37321
+ clearTimeout(groupTimer);
37322
+ clearInterval(limitTimer);
37323
+ stopExitWatch();
37324
+ options.signal?.removeEventListener("abort", abort);
37325
+ if (!exitReported(child))
37326
+ reapAfterLostExit(child.pid, () => exitReported(child));
37327
+ try {
37328
+ return {
37329
+ stdout: readCaptureFile(stdoutFd, outputLimit),
37330
+ stderr: readCaptureFile(stderrFd, stderrLimit)
37331
+ };
37332
+ } catch (error) {
37333
+ reject(error);
37334
+ return;
37335
+ } finally {
37336
+ releaseCaptureFds();
37337
+ }
37338
+ };
37339
+ const rejectFailure = (error) => {
37340
+ const output = finishCapture();
37341
+ if (output)
37342
+ reject(Object.assign(error, { ...output, killed: timedOut }));
37343
+ };
37344
+ const awaitTermination = (delayMs) => {
37345
+ clearTimeout(groupTimer);
37346
+ if (settled)
37347
+ return;
37348
+ if ((commandExit || exitReported(child)) && !commandGroupAlive(child)) {
37349
+ rejectFailure(pendingFailure);
37350
+ return;
37351
+ }
37352
+ groupTimer = setTimeout(awaitTermination, delayMs, Math.min(delayMs * 2, COMMAND_GROUP_POLL_MAX_MS));
37353
+ };
37354
+ const fail = (error) => {
37355
+ if (settled || pendingFailure)
37356
+ return;
37357
+ if (options.waitForTermination && child.pid !== undefined) {
37358
+ pendingFailure = error;
37359
+ signalCommand(child, "SIGKILL");
37360
+ clearTimeout(timeoutTimer);
37361
+ clearInterval(limitTimer);
37362
+ awaitTermination(COMMAND_GROUP_POLL_MS);
37363
+ } else
37364
+ rejectFailure(error);
37365
+ };
37366
+ const abort = () => {
37367
+ timedOut = true;
37368
+ signalCommand(child, "SIGKILL");
37369
+ fail(new Error(COMMAND_ABORTED_MESSAGE));
37370
+ };
37371
+ options.signal?.addEventListener("abort", abort, { once: true });
37372
+ const checkOutputLimit = () => {
37373
+ const stream = captureFs.fstatSync(stdoutFd).size > outputLimit ? "stdout" : captureFs.fstatSync(stderrFd).size > stderrLimit ? "stderr" : undefined;
37374
+ if (stream === undefined)
37375
+ return false;
37376
+ signalCommand(child, "SIGKILL");
37377
+ fail(Object.assign(new Error(`${stream} ${OUTPUT_LIMIT_MESSAGE}`), {
37378
+ outputLimitExceeded: true
37379
+ }));
37380
+ return true;
37381
+ };
37382
+ const failIfOverLimit = () => {
37383
+ try {
37384
+ return checkOutputLimit();
37385
+ } catch (error) {
37386
+ signalCommand(child, "SIGKILL");
37387
+ fail(error instanceof Error ? error : new Error(String(error)));
37388
+ return true;
37389
+ }
37390
+ };
37391
+ limitTimer = setInterval(() => {
37392
+ if (!settled && !timedOut && !pendingFailure)
37393
+ failIfOverLimit();
37394
+ }, COMMAND_OUTPUT_CHECK_MS);
37395
+ const settleOnExit = () => {
37396
+ if (settled || timedOut || pendingFailure || failIfOverLimit())
37397
+ return;
37398
+ if (commandExit?.code !== 0 || commandExit.signal !== null) {
37399
+ fail(Object.assign(new Error(`Command failed: ${[command, ...args].join(" ")}`), {
37400
+ code: commandExit?.code,
37401
+ signal: commandExit?.signal
37402
+ }));
37403
+ return;
37404
+ }
37405
+ const output = finishCapture();
37406
+ if (output)
37407
+ resolve(output);
37408
+ };
37409
+ const awaitGroupExit = (delayMs) => {
37410
+ if (settled || timedOut || pendingFailure)
37411
+ return;
37412
+ if (commandGroupAlive(child)) {
37413
+ groupTimer = setTimeout(awaitGroupExit, delayMs, Math.min(delayMs * 2, COMMAND_GROUP_POLL_MAX_MS));
37414
+ return;
37415
+ }
37416
+ settleOnExit();
37417
+ };
37418
+ const onCommandExit = (exit) => {
37419
+ if (commandExit)
37420
+ return;
37421
+ commandExit = exit;
37422
+ stopExitWatch();
37423
+ if (pendingFailure)
37424
+ awaitTermination(COMMAND_GROUP_POLL_MS);
37425
+ else if (options.waitForDescendants)
37426
+ awaitGroupExit(COMMAND_GROUP_POLL_MS);
37427
+ else
37428
+ settleOnExit();
37429
+ };
37430
+ child.exited.then(onCommandExit, (error) => fail(error instanceof Error ? error : new Error(String(error))));
37431
+ stopExitWatch = watchForLostExit(child.pid, (exit) => {
37432
+ if (!settled)
37433
+ onCommandExit(exit);
37434
+ });
37435
+ if (timeoutMs > 0) {
37436
+ timeoutTimer = setTimeout(() => {
37437
+ timedOut = true;
37438
+ signalCommand(child, "SIGTERM");
37439
+ timeoutTimer = setTimeout(() => {
37440
+ signalCommand(child, "SIGKILL");
37441
+ fail(Object.assign(new Error(`Command timed out after ${timeoutMs} ms`), {
37442
+ code: child.current().code,
37443
+ signal: child.current().signal
37444
+ }));
37445
+ }, COMMAND_KILL_GRACE_MS);
37446
+ }, timeoutMs);
37447
+ }
37448
+ });
37449
+ }
37450
+ async function runCommandBytes(command, args = [], options = {}) {
37451
+ const timeoutMs = options.timeoutMs ?? 60000;
37452
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > 2147483647) {
37453
+ throw new RangeError("timeoutMs must be an integer between 0 and 2147483647");
37454
+ }
37455
+ const outputLimit = options.maxOutputBytes ?? MAX_COMMAND_OUTPUT_BYTES;
37456
+ if (!Number.isSafeInteger(outputLimit) || outputLimit <= 0) {
37457
+ throw new RangeError("maxOutputBytes must be a positive integer");
37458
+ }
37459
+ const stderrLimit = options.maxStderrBytes ?? outputLimit;
37460
+ if (!Number.isSafeInteger(stderrLimit) || stderrLimit <= 0) {
37461
+ throw new RangeError("maxStderrBytes must be a positive integer");
37462
+ }
37463
+ if (commandInvocations.size < 64 || commandInvocations.has(command)) {
37464
+ commandInvocations.set(command, (commandInvocations.get(command) ?? 0) + 1);
37465
+ }
37466
+ for (const observer of commandObservers.get(command) ?? [])
37467
+ observer(args);
37468
+ commandCaptureMetrics?.started(command, args);
37469
+ try {
37470
+ const { stdout, stderr } = await executeCommandBytes(command, args, options, timeoutMs, outputLimit, stderrLimit);
37471
+ commandCaptureMetrics?.capturedBytes(stdout.length);
37472
+ return {
37473
+ stdout: Buffer.isBuffer(stdout) ? stdout : Buffer.from(stdout),
37474
+ stderr: Buffer.isBuffer(stderr) ? stderr : Buffer.from(stderr)
37475
+ };
37476
+ } catch (error) {
37477
+ const outcome = commandFailureOutcome(error);
37478
+ const redacting = options.redactValues?.some((value) => typeof value === "string" && value.length > 0);
37479
+ if (error && typeof error === "object" && "stdout" in error && "stderr" in error) {
37480
+ const withOutput = error;
37481
+ const stderr = withOutput.stderr?.toString() ?? "";
37482
+ const stdout = withOutput.stdout?.toString() ?? "";
37483
+ const message = (stderr || stdout || withOutput.message || "Command failed").trim();
37484
+ throw new CommandFailedError(redactCommandValues(message, options.redactValues), {
37485
+ ...outcome,
37486
+ stdout: redactCommandValues(stdout, options.redactValues),
37487
+ stderr: redactCommandValues(stderr, options.redactValues),
37488
+ ...!redacting && Buffer.isBuffer(withOutput.stdout) ? { stdoutBytes: withOutput.stdout } : {}
37489
+ });
37490
+ }
37491
+ if (redacting) {
37492
+ const message = error instanceof Error ? error.message : String(error);
37493
+ throw new CommandFailedError(redactCommandValues(message || "Command failed", options.redactValues), outcome);
37494
+ }
37495
+ if (outcome.timedOut || outcome.executableMissing) {
37496
+ const message = error instanceof Error ? error.message : String(error);
37497
+ throw new CommandFailedError(message || "Command failed", outcome);
37498
+ }
37499
+ throw error;
37500
+ }
37501
+ }
37502
+ async function runCommand(command, args = [], options = {}) {
37503
+ const { stdout, stderr } = await runCommandBytes(command, args, options);
37504
+ return {
37505
+ stdout: redactCommandValues(stdout.toString(), options.redactValues),
37506
+ stderr: redactCommandValues(stderr.toString(), options.redactValues)
37507
+ };
37508
+ }
37509
+
37510
+ // ../protocol/src/node/workspace-change-probe.ts
36387
37511
  var DEFAULT_MAX_UNTRACKED_FILE_BYTES = 2 * 1024 * 1024;
36388
37512
  var DEFAULT_MAX_UNTRACKED_FILES = 5000;
36389
37513
  var DEFAULT_SLOW_SNAPSHOT_MS = 500;
@@ -36397,31 +37521,20 @@ var temporaryObjectDirectories = new Set;
36397
37521
  process.once("exit", () => {
36398
37522
  for (const directory of temporaryObjectDirectories) {
36399
37523
  try {
36400
- rmSync(directory, { recursive: true, force: true });
37524
+ rmSync2(directory, { recursive: true, force: true });
36401
37525
  } catch {}
36402
37526
  }
36403
37527
  });
36404
- var runGit = (args, options) => new Promise((resolvePromise, reject) => {
36405
- const env = { ...process.env, ...options.env, GIT_OPTIONAL_LOCKS: "0" };
36406
- if (options.stdin === undefined) {
36407
- execFile("git", args, { cwd: options.cwd, env, timeout: GIT_TIMEOUT_MS, maxBuffer: GIT_MAX_BUFFER }, (error, stdout) => error ? reject(error) : resolvePromise({ stdout: String(stdout) }));
36408
- return;
36409
- }
36410
- const child = spawn("git", args, { cwd: options.cwd, env, timeout: GIT_TIMEOUT_MS });
36411
- let stdout = "";
36412
- let stdoutBytes = 0;
36413
- child.stdout.setEncoding("utf8");
36414
- child.stdout.on("data", (chunk) => {
36415
- stdoutBytes += chunk.length;
36416
- if (stdoutBytes <= GIT_MAX_BUFFER)
36417
- stdout += chunk;
37528
+ var runGit = async (args, options) => {
37529
+ const { stdout } = await runCommand("git", args, {
37530
+ cwd: options.cwd,
37531
+ env: { ...process.env, ...options.env, GIT_OPTIONAL_LOCKS: "0" },
37532
+ timeoutMs: GIT_TIMEOUT_MS,
37533
+ maxOutputBytes: GIT_MAX_BUFFER,
37534
+ ...options.stdin === undefined ? {} : { stdin: options.stdin }
36418
37535
  });
36419
- child.stderr.resume();
36420
- child.on("error", reject);
36421
- child.on("close", (code) => code === 0 ? resolvePromise({ stdout }) : reject(new Error(`git exited with ${code}`)));
36422
- child.stdin.on("error", () => {});
36423
- child.stdin.end(options.stdin);
36424
- });
37536
+ return { stdout };
37537
+ };
36425
37538
 
36426
37539
  class WorkspaceChangeProbe {
36427
37540
  git;
@@ -36709,7 +37822,7 @@ class WorkspaceChangeProbe {
36709
37822
  return;
36710
37823
  const { root, indexPath } = repo.location;
36711
37824
  const started = this.now();
36712
- const tempIndex = join8(this.tempDir, `orkestrator-probe-${randomUUID2()}.index`);
37825
+ const tempIndex = join8(this.tempDir, `orkestrator-probe-${randomUUID3()}.index`);
36713
37826
  const objectDirectory = await mkdtemp(join8(this.tempDir, "orkestrator-probe-objects-"));
36714
37827
  temporaryObjectDirectories.add(objectDirectory);
36715
37828
  let retained = false;
@@ -36972,7 +38085,7 @@ function classify(toolCall) {
36972
38085
  return;
36973
38086
  }
36974
38087
  // ../../bridges/cursor-bridge/src/prompt.ts
36975
- var log7 = createLogger("bridge.cursor");
38088
+ var log8 = createLogger("bridge.cursor");
36976
38089
  var STRUCTURED_PROMPT_INSTRUCTION_PREFIX = "End your turn with exactly one JSON value";
36977
38090
  function structuredPromptInstruction(schema) {
36978
38091
  return `${STRUCTURED_PROMPT_INSTRUCTION_PREFIX} matching this JSON Schema. That final message must be the JSON value alone, with no Markdown fence and no commentary around it.
@@ -37010,7 +38123,7 @@ async function dispatchPrompt(state, agent, input) {
37010
38123
  const promptSequence = state.promptSequence;
37011
38124
  const diagnostics = createRunDiagnostics(state);
37012
38125
  const evidence = trackTurnEvidence(state.id, {
37013
- turnId: input.requestId ?? `cursor-turn:${randomUUID3()}`,
38126
+ turnId: input.requestId ?? `cursor-turn:${randomUUID4()}`,
37014
38127
  mode: "live"
37015
38128
  });
37016
38129
  const commandChanges = trackCommandChanges(state, evidence);
@@ -37174,7 +38287,7 @@ async function followRun(state, run, promptSequence, input, timeoutMs = PROMPT_T
37174
38287
  }) : undefined;
37175
38288
  if (!turnStillOwned(state, promptSequence))
37176
38289
  return await closedTurnStopped();
37177
- log7.warn("turn.timed-out", { sessionId: state.id });
38290
+ log8.warn("turn.timed-out", { sessionId: state.id });
37178
38291
  state.error = error.message;
37179
38292
  state.revision += 1;
37180
38293
  schedulePersist();
@@ -37243,7 +38356,7 @@ function finishTurn(state, result, input, streamed) {
37243
38356
  }
37244
38357
  function failTurn(state, error, input, result, streamed = {}) {
37245
38358
  if (state.turnCancelRequested !== true) {
37246
- log7.warn("turn.failed", {
38359
+ log8.warn("turn.failed", {
37247
38360
  sessionId: state.id,
37248
38361
  error: formatLogError(error, { message: false })
37249
38362
  });
@@ -37606,7 +38719,7 @@ async function withTimeout3(work, timeoutMs) {
37606
38719
  }
37607
38720
  }
37608
38721
  // ../../bridges/cursor-bridge/src/prompt-attachments.ts
37609
- import { constants } from "node:fs";
38722
+ import { constants as constants2 } from "node:fs";
37610
38723
  import { lstat as lstat2, open as open4, realpath as realpath2 } from "node:fs/promises";
37611
38724
  import { isAbsolute as isAbsolute5, join as join9, relative as relative4, resolve as resolve6, sep as sep3 } from "node:path";
37612
38725
 
@@ -37757,8 +38870,8 @@ async function readWorkspaceImage(filePath, workspaceRoot) {
37757
38870
  if (!isPathWithin(canonicalRoot, canonicalTarget)) {
37758
38871
  throw new PromptAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace");
37759
38872
  }
37760
- const noFollow = constants.O_NOFOLLOW ?? 0;
37761
- const handle = await open4(targetPath, constants.O_RDONLY | noFollow).catch((error) => {
38873
+ const noFollow = constants2.O_NOFOLLOW ?? 0;
38874
+ const handle = await open4(targetPath, constants2.O_RDONLY | noFollow).catch((error) => {
37762
38875
  throw attachmentErrorForFsFailure(error);
37763
38876
  });
37764
38877
  try {
@@ -38065,6 +39178,7 @@ function effectiveLogLevel(detail, area) {
38065
39178
  return detail.level;
38066
39179
  }
38067
39180
  }
39181
+ var LOG_DETAIL_EXPIRY_MS = 24 * 60 * 60 * 1000;
38068
39182
  function logDetailEnablesBridgeDiagnostics(detail) {
38069
39183
  return LEVEL_DETAIL[effectiveLogLevel(detail, BRIDGE_DIAGNOSTICS_LOG_AREA)] >= LEVEL_DETAIL.debug;
38070
39184
  }
@@ -38235,7 +39349,7 @@ function humanPromptObservation(messages, tasks) {
38235
39349
  }
38236
39350
 
38237
39351
  // ../../bridges/cursor-bridge/src/http.ts
38238
- import { createHash as createHash8, randomBytes as randomBytes6 } from "node:crypto";
39352
+ import { createHash as createHash9, randomBytes as randomBytes7 } from "node:crypto";
38239
39353
  import { pathToFileURL } from "node:url";
38240
39354
  import { gzip } from "node:zlib";
38241
39355
 
@@ -38364,7 +39478,7 @@ var DEFAULT_MCP_MANAGEMENT_ROLLOUT = Object.freeze({
38364
39478
 
38365
39479
  // ../protocol/src/node/bridge-transcript-summary.ts
38366
39480
  import { Buffer as Buffer6 } from "node:buffer";
38367
- import { createHash as createHash7 } from "node:crypto";
39481
+ import { createHash as createHash8 } from "node:crypto";
38368
39482
 
38369
39483
  // ../protocol/src/node/progressive-transcript.ts
38370
39484
  var BRIDGE_TRANSCRIPT_MAX_MESSAGES = 100;
@@ -38530,7 +39644,7 @@ function digestPayload(payload) {
38530
39644
  const serialized = JSON.stringify(payload);
38531
39645
  return {
38532
39646
  bytes: Buffer6.byteLength(serialized),
38533
- digest: createHash7("sha256").update(serialized).digest("base64url").slice(0, 32)
39647
+ digest: createHash8("sha256").update(serialized).digest("base64url").slice(0, 32)
38534
39648
  };
38535
39649
  }
38536
39650
  function topLevelKey(part, index) {
@@ -39252,7 +40366,7 @@ async function answerSessionActivityBatch(body, read, options = {}) {
39252
40366
  }
39253
40367
 
39254
40368
  // ../../bridges/cursor-bridge/src/http.ts
39255
- var log8 = createLogger("bridge.cursor");
40369
+ var log9 = createLogger("bridge.cursor");
39256
40370
 
39257
40371
  class HttpError extends Error {
39258
40372
  status;
@@ -39275,6 +40389,9 @@ async function route(request, response, clientSignal) {
39275
40389
  })) {
39276
40390
  return json(response, 401, { error: "Unauthorized" });
39277
40391
  }
40392
+ const refused = await admitNodeBridgeRequest(bridgeAuthority, request, MAX_BODY_BYTES);
40393
+ if (refused)
40394
+ return json(response, refused.status, refused.body);
39278
40395
  try {
39279
40396
  if (url.pathname === SESSION_ACTIVITY_BATCH_PATH && request.method === "POST") {
39280
40397
  const answer = await answerSessionActivityBatch(request, sessionActivityObservation, {
@@ -39296,7 +40413,7 @@ async function route(request, response, clientSignal) {
39296
40413
  if (error instanceof HttpError)
39297
40414
  return json(response, error.status, { error: error.message });
39298
40415
  if (error instanceof PolicyWideningRefusedError) {
39299
- log8.warn("session.policy-widening-refused", { widened: error.widened.join(",") });
40416
+ log9.warn("session.policy-widening-refused", { widened: error.widened.join(",") });
39300
40417
  return json(response, 403, error.refusal());
39301
40418
  }
39302
40419
  if (error instanceof CredentialError) {
@@ -39321,7 +40438,7 @@ async function route(request, response, clientSignal) {
39321
40438
  if (error instanceof PromptAttachmentError) {
39322
40439
  return json(response, 400, { error: error.message });
39323
40440
  }
39324
- log8.error("http.route-failed");
40441
+ log9.error("http.route-failed");
39325
40442
  return json(response, 500, { error: "Internal bridge error" });
39326
40443
  }
39327
40444
  }
@@ -39461,7 +40578,7 @@ async function startLogin(response) {
39461
40578
  });
39462
40579
  json(response, 200, { url: loginUrl, loginUrl });
39463
40580
  }
39464
- var TRANSCRIPT_GENERATION = randomBytes6(16).toString("hex");
40581
+ var TRANSCRIPT_GENERATION = randomBytes7(16).toString("hex");
39465
40582
  var SESSION_ROUTE = /^\/session\/([^/]+)(?:\/(messages|transcript|status|usage|activity|human-prompts|prompt|attach|dispatch|cancel|abort|hard-abort|steer|structured-output|interactions|config|approvals|runtime-health|commands|mcp|rewind-messages|compact|close))?(?:\/([^/]+))?$/;
39466
40583
  async function routeSession(request, response, url, clientSignal) {
39467
40584
  const match = SESSION_ROUTE.exec(url.pathname);
@@ -39667,7 +40784,7 @@ async function handleSteer(request, response, state) {
39667
40784
  const expectedRunId = readBoundedString(body.expectedRunId, MAX_STEER_ID_BYTES, "expectedRunId");
39668
40785
  if (!text)
39669
40786
  throw new HttpError(400, "input is required");
39670
- const inputDigest = createHash8("sha256").update(text).digest("hex");
40787
+ const inputDigest = createHash9("sha256").update(text).digest("hex");
39671
40788
  if (requestId && expectedRunId) {
39672
40789
  const previous = state.steerJournal.get(requestId);
39673
40790
  if (previous) {
@@ -40023,7 +41140,7 @@ async function dispatchClaimedPrompt(response, state, input) {
40023
41140
  userMessageId
40024
41141
  });
40025
41142
  } catch (error) {
40026
- log8.warn("turn.send-failed", {
41143
+ log9.warn("turn.send-failed", {
40027
41144
  sessionId: state.id,
40028
41145
  error: formatLogError(error, { message: false })
40029
41146
  });
@@ -40146,7 +41263,7 @@ function appendLocalExchange(state, prompt, reply, requestId) {
40146
41263
  if (userId && state.messages.some((message) => message.id === userId))
40147
41264
  return;
40148
41265
  const userMessageId = appendUserMessage(state, prompt, [], userId);
40149
- const messageId = requestId ? `idle-steer-reply:${requestId}` : randomBytes6(12).toString("hex");
41266
+ const messageId = requestId ? `idle-steer-reply:${requestId}` : randomBytes7(12).toString("hex");
40150
41267
  state.messages.push({
40151
41268
  id: messageId,
40152
41269
  role: "assistant",
@@ -40163,7 +41280,7 @@ function appendLocalExchange(state, prompt, reply, requestId) {
40163
41280
  });
40164
41281
  chargeTranscript(state, Buffer.byteLength(reply));
40165
41282
  }
40166
- function appendUserMessage(state, prompt, images, messageId = randomBytes6(12).toString("hex")) {
41283
+ function appendUserMessage(state, prompt, images, messageId = randomBytes7(12).toString("hex")) {
40167
41284
  state.messages.push({
40168
41285
  id: messageId,
40169
41286
  role: "user",
@@ -40199,9 +41316,10 @@ function readBoundedString(value, limit, field) {
40199
41316
  return trimmed;
40200
41317
  }
40201
41318
  async function readJson(request) {
40202
- const chunks = [];
40203
- let total = 0;
40204
- for await (const chunk of request) {
41319
+ const admitted = takeAdmittedBody(request);
41320
+ const chunks = admitted ? [admitted] : [];
41321
+ let total = admitted?.length ?? 0;
41322
+ for await (const chunk of admitted ? [] : request) {
40205
41323
  const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
40206
41324
  total += buffer.length;
40207
41325
  if (total > MAX_BODY_BYTES)
@@ -40317,7 +41435,7 @@ function startParentWatchdog(options) {
40317
41435
  }
40318
41436
 
40319
41437
  // ../protocol/src/bridge-lifecycle.ts
40320
- var log9 = createLogger("bridge.lifecycle");
41438
+ var log10 = createLogger("bridge.lifecycle");
40321
41439
  var TERMINATION_SIGNALS = ["SIGTERM", "SIGINT"];
40322
41440
  function errorKind(error) {
40323
41441
  if (error instanceof Error)
@@ -40371,7 +41489,7 @@ class BridgeLifecycle {
40371
41489
  }
40372
41490
  requestExit() {
40373
41491
  this.#exit ??= this.shutdown().then(() => this.#options.exit(0), (error) => {
40374
- log9.error("shutdown.failed", {
41492
+ log10.error("shutdown.failed", {
40375
41493
  bridge: this.#options.label,
40376
41494
  errorClass: errorKind(error)
40377
41495
  });
@@ -40388,7 +41506,7 @@ class BridgeLifecycle {
40388
41506
  try {
40389
41507
  idleSweep.run();
40390
41508
  } catch (error) {
40391
- log9.warn("idle-sweep.failed", {
41509
+ log10.warn("idle-sweep.failed", {
40392
41510
  bridge: this.#options.label,
40393
41511
  errorClass: errorKind(error)
40394
41512
  });
@@ -40460,7 +41578,7 @@ async function settleIdleDetaches() {
40460
41578
  }
40461
41579
 
40462
41580
  // ../../bridges/cursor-bridge/src/server.ts
40463
- var log10 = createLogger("bridge.cursor");
41581
+ var log11 = createLogger("bridge.cursor");
40464
41582
  var IDLE_SWEEP_MS = 60 * 1000;
40465
41583
  var lifecycle;
40466
41584
  var server = createServer((request, response) => {
@@ -40495,7 +41613,7 @@ function lifecycleFor(listenPort, options) {
40495
41613
  applyWorkingDirectory();
40496
41614
  await loadPersistedState();
40497
41615
  finishRestoredTombstones().catch(() => {
40498
- log10.warn("startup.closes-failed");
41616
+ log11.warn("startup.closes-failed");
40499
41617
  });
40500
41618
  await new Promise((resolve) => server.listen(listenPort, hostname, resolve));
40501
41619
  },
@@ -40661,9 +41779,9 @@ function installFatalRejectionGuard(options) {
40661
41779
  }
40662
41780
 
40663
41781
  // ../protocol/src/node/process-failure-log.ts
40664
- var log11 = createLogger("process");
41782
+ var log12 = createLogger("process");
40665
41783
  function logUnhandledRejection(reason) {
40666
- log11.throttled("error", "rejection.unhandled", {
41784
+ log12.throttled("error", "rejection.unhandled", {
40667
41785
  error: reason,
40668
41786
  fields: () => ({ error: formatLogError(reason, { message: false }) })
40669
41787
  });
@@ -40794,6 +41912,7 @@ export {
40794
41912
  boundTranscript,
40795
41913
  boundTranscriptDuringStreaming,
40796
41914
  boundTranscriptForRead,
41915
+ bridgeAuthority,
40797
41916
  cancelSurvivingRuns,
40798
41917
  chargeTranscript,
40799
41918
  childTrimNoticePartId,