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.
@@ -490,12 +490,84 @@ var require_cross_spawn = __commonJS(function(exports, module) {
490
490
  module.exports._enoent = enoent;
491
491
  });
492
492
 
493
+ // ../protocol/src/node/bridge-launch-environment.ts
494
+ import { closeSync, fstatSync, openSync, readSync, rmSync, constants } from "node:fs";
495
+ var BRIDGE_LAUNCH_ENVIRONMENT_ENV = "ORKESTRATOR_BRIDGE_LAUNCH_ENVIRONMENT";
496
+ var BRIDGE_LAUNCH_KEYS_ENV = "ORKESTRATOR_BRIDGE_LAUNCH_KEYS";
497
+ var BRIDGE_LAUNCH_WORKDIR_ENV = "ORKESTRATOR_BRIDGE_LAUNCH_WORKDIR";
498
+ var MAX_SNAPSHOT_BYTES = 1024 * 1024;
499
+ var MAX_SNAPSHOT_ENTRIES = 4096;
500
+ var NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_%.-]*$/;
501
+ var LAUNCH_ONLY = /(?:_BRIDGE_TOKEN|_TOKEN_SHA256|_AUTHORITY_KEY)$|^ORKESTRATOR_BRIDGE_(?:LAUNCH_|EXECUTION_POLICY$)|^ORKESTRATOR_COORDINATOR_/;
502
+ var NOT_APPLIED = new Set(["PWD", "OLDPWD", "SHLVL", "_", "NODE_PATH"]);
503
+ function readSnapshot(file) {
504
+ let fd;
505
+ try {
506
+ fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
507
+ } catch {
508
+ return null;
509
+ }
510
+ try {
511
+ const stat = fstatSync(fd);
512
+ if (!stat.isFile() || stat.size > MAX_SNAPSHOT_BYTES)
513
+ return null;
514
+ const buffer = Buffer.alloc(stat.size);
515
+ let offset = 0;
516
+ while (offset < buffer.length) {
517
+ const read = readSync(fd, buffer, offset, buffer.length - offset, offset);
518
+ if (read === 0)
519
+ break;
520
+ offset += read;
521
+ }
522
+ return buffer.subarray(0, offset);
523
+ } finally {
524
+ closeSync(fd);
525
+ }
526
+ }
527
+ function applyBridgeLaunchEnvironment(env = process.env, chdir = (directory) => process.chdir(directory)) {
528
+ const file = env[BRIDGE_LAUNCH_ENVIRONMENT_ENV];
529
+ if (!file)
530
+ return null;
531
+ const trusted = new Set((env[BRIDGE_LAUNCH_KEYS_ENV] ?? "").split(",").map((name) => name.trim()).filter(Boolean));
532
+ const workdir = env[BRIDGE_LAUNCH_WORKDIR_ENV];
533
+ delete env[BRIDGE_LAUNCH_ENVIRONMENT_ENV];
534
+ delete env[BRIDGE_LAUNCH_KEYS_ENV];
535
+ delete env[BRIDGE_LAUNCH_WORKDIR_ENV];
536
+ const result = { applied: 0, refused: 0 };
537
+ const snapshot = readSnapshot(file);
538
+ rmSync(file, { force: true });
539
+ if (snapshot) {
540
+ const entries = snapshot.toString("utf8").split("\x00").slice(0, MAX_SNAPSHOT_ENTRIES);
541
+ for (const entry of entries) {
542
+ const separator = entry.indexOf("=");
543
+ if (separator <= 0)
544
+ continue;
545
+ const name = entry.slice(0, separator);
546
+ if (!NAME_PATTERN.test(name) || NOT_APPLIED.has(name))
547
+ continue;
548
+ if (trusted.has(name) || LAUNCH_ONLY.test(name)) {
549
+ result.refused += 1;
550
+ continue;
551
+ }
552
+ env[name] = entry.slice(separator + 1);
553
+ result.applied += 1;
554
+ }
555
+ }
556
+ if (workdir) {
557
+ try {
558
+ chdir(workdir);
559
+ } catch {}
560
+ }
561
+ return result;
562
+ }
563
+ applyBridgeLaunchEnvironment();
564
+
493
565
  // ../../bridges/pi-bridge/src/config.ts
494
- import { randomBytes as randomBytes2 } from "node:crypto";
566
+ import { randomBytes as randomBytes3 } from "node:crypto";
495
567
  import { resolve } from "node:path";
496
568
 
497
569
  // ../protocol/src/node/bridge-credential.ts
498
- import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
570
+ import { createHash as createHash2, randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
499
571
  import { createRequire as createRequire2 } from "node:module";
500
572
 
501
573
  // ../protocol/src/secret-redaction.ts
@@ -541,7 +613,7 @@ var MAX_FRAME_CHARS = 240;
541
613
  var MAX_RAW_FRAME_CHARS = 1024;
542
614
  var MAX_CAUSE_DEPTH = 2;
543
615
  var TRUNCATED_MARKER = "...[truncated]";
544
- var NAME_PATTERN = /^[A-Za-z_$][\w$.-]{0,63}$/;
616
+ var NAME_PATTERN2 = /^[A-Za-z_$][\w$.-]{0,63}$/;
545
617
  var CODE_PATTERN = /^[\w.:-]{1,64}$/;
546
618
  var SYSCALL_PATTERN = /^[\w./ -]{1,128}$/;
547
619
  var COMMAND_OUTPUT_FIELDS = ["stdout", "stderr", "cmd", "spawnargs"];
@@ -619,7 +691,7 @@ function describe(error, includeStack, includeMessage, depth) {
619
691
  if (!(error instanceof Error) && typeof rawMessage !== "string") {
620
692
  return { name: "NonError", message: "[object]" };
621
693
  }
622
- const name = matching(read(error, "name"), NAME_PATTERN) ?? "Error";
694
+ const name = matching(read(error, "name"), NAME_PATTERN2) ?? "Error";
623
695
  const message = typeof rawMessage === "string" ? rawMessage : undefined;
624
696
  const commandFailure = isCommandFailure(error, name, message);
625
697
  const stackHoldsMessage = message !== undefined && String(read(error, "stack") ?? "").includes(message);
@@ -674,7 +746,7 @@ function logErrorKind(error) {
674
746
  const safeCode = finite(code) ?? matching(code, CODE_PATTERN);
675
747
  if (safeCode !== undefined)
676
748
  return String(safeCode);
677
- return matching(read(error, "name"), NAME_PATTERN) ?? "Error";
749
+ return matching(read(error, "name"), NAME_PATTERN2) ?? "Error";
678
750
  }
679
751
 
680
752
  // ../protocol/src/log-vocabulary/define.ts
@@ -1095,6 +1167,7 @@ var DESKTOP_LOG_AREAS = defineLogAreas({
1095
1167
  events: {
1096
1168
  "attention-failed": "A dialog could not ask for the user's attention.",
1097
1169
  closed: "A native dialog closed.",
1170
+ "hidden-cancelled": "A hidden profile cancelled a dialog without opening native UI.",
1098
1171
  "open-failed": "A dialog could not open; it was answered as cancelled.",
1099
1172
  opening: "A native dialog is opening.",
1100
1173
  "preview-beforeunload-ignored": "A browser preview's beforeunload handler was ignored.",
@@ -1180,6 +1253,7 @@ var ENVIRONMENT_LOG_AREAS = defineLogAreas({
1180
1253
  "orphan-session.reaped": "A native session no tab references was torn down.",
1181
1254
  "handoff-sweep.failed": "Sweeping transferred transcripts no tab references failed.",
1182
1255
  "delete.terminals-survived": "Terminal process trees outlived termination, so the deletion stops.",
1256
+ "delete.step-deadline": "A deletion step that runs child processes passed its deadline; they are stopped and the deletion fails once they have.",
1183
1257
  "delete.artifacts-left": "Graph run artifact directories were not removed.",
1184
1258
  "delete.worktrees-kept": "Graph runs kept branch worktrees.",
1185
1259
  "delete.step-failed": "One best-effort part of deleting an environment failed; `step` says which, and the rest goes on.",
@@ -1214,6 +1288,7 @@ var GATEWAY_LOG_AREAS = defineLogAreas({
1214
1288
  "host.refused": "A request named a host this gateway does not answer to. Logged once per name, up to a limit.",
1215
1289
  "port.fallback": "The preferred port was taken, so a nearby one is used.",
1216
1290
  "port.fallback-distant": "The preferred port and those nearby were taken, so another is used.",
1291
+ "request-auth.fallback": "A desktop request-auth hook failed closed. Phase only; no request or error content.",
1217
1292
  "request.failed": "A gateway request failed. Throttled: repeats are counted, not written.",
1218
1293
  "websocket.upgrade-failed": "A WebSocket upgrade failed.",
1219
1294
  "events.client-dropped": "An event-stream client buffered too much and was dropped; it reconnects and refetches.",
@@ -1272,6 +1347,11 @@ var LOCAL_SERVER_LOG_AREAS = defineLogAreas({
1272
1347
  requested: "boolean"
1273
1348
  }
1274
1349
  },
1350
+ "bridge.orphans-reaped": {
1351
+ 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.",
1352
+ essential: true,
1353
+ fields: { key: "label", pid: "number", result: "label" }
1354
+ },
1275
1355
  "reaper.tmux-list-failed": "Orphaned claude-tmux sessions could not be listed.",
1276
1356
  "reaper.tmux-kill-failed": "An orphaned tmux session could not be killed.",
1277
1357
  "reaper.tmux-reaped": "Orphaned claude-tmux sessions of a deleted environment were killed.",
@@ -1322,6 +1402,8 @@ var LOGGING_LOG_AREAS = defineLogAreas({
1322
1402
  },
1323
1403
  "essential.write-failed": "Writing the essential log failed. Its entries are counted, and a marker reports them at the next write that works.",
1324
1404
  "policy.changed": "The logging settings changed: saving, retention and levels, with no content.",
1405
+ "policy.detail-expired": "Raised log detail reached its expiry, so the backend set its raised levels back to info. Saving is unchanged.",
1406
+ "policy.expiry-failed": "Checking or applying the log detail expiry failed; the next check, a minute later, tries again.",
1325
1407
  "policy.bridge-predates-route": "A running bridge has no logging settings route; it applies them at its next start.",
1326
1408
  "policy.push-failed": "A running bridge did not take the logging settings after retries; its next start resends them.",
1327
1409
  "prune.failed": "Removing expired log files failed; the next sweep retries.",
@@ -1329,6 +1411,23 @@ var LOGGING_LOG_AREAS = defineLogAreas({
1329
1411
  "unknown-area": "Code outside the type checker asked for an area that is not listed.",
1330
1412
  ...THROTTLE_LOG_EVENTS
1331
1413
  }
1414
+ },
1415
+ "renderer-errors": {
1416
+ description: "Renderer failures a desktop window reported from its error ring: class, boundary, surface, count and fingerprint, never a message or stack.",
1417
+ events: {
1418
+ "error.recorded": {
1419
+ description: "A renderer reported `count` new occurrences of one failure since its last report.",
1420
+ essential: true,
1421
+ fields: {
1422
+ errorClass: "label",
1423
+ boundary: "label",
1424
+ route: "label",
1425
+ fingerprint: "label",
1426
+ count: "number"
1427
+ }
1428
+ },
1429
+ "report.rate-limited": "Renderer error entries arrived faster than the backend records them, so `dropped` were counted and not written."
1430
+ }
1332
1431
  }
1333
1432
  });
1334
1433
 
@@ -1386,6 +1485,8 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
1386
1485
  "usage-limit.notice-failed": "A usage-limit stop's outcome could not be read for its notice.",
1387
1486
  "usage-limit.resend-failed": "Resending after a usage limit failed. An unknown send stays in the journal.",
1388
1487
  "title.strategy-failed": "A session title strategy failed, so the next is tried. Content-free: the error can quote the prompt.",
1488
+ "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.",
1489
+ "steer.capability-cleared": "A projection cleared `actions.steer` because its bridge did not qualify. Identifiers and turn status only.",
1389
1490
  ...THROTTLE_LOG_EVENTS
1390
1491
  }
1391
1492
  },
@@ -1486,6 +1587,9 @@ var RUNTIME_LOG_AREAS = defineLogAreas({
1486
1587
  essential: true,
1487
1588
  fields: { origin: "label", ...ESSENTIAL_ERROR_FIELDS }
1488
1589
  },
1590
+ "child.reaped": "A macOS child whose exit Bun lost was reaped after its command settled, so it no longer waits as a zombie.",
1591
+ "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.",
1592
+ "child.reap-unavailable": "waitpid could not be loaded, so children whose exit Bun lost stay zombies until this process exits.",
1489
1593
  ...THROTTLE_LOG_EVENTS
1490
1594
  }
1491
1595
  }
@@ -1892,6 +1996,13 @@ var COORDINATOR_LOG_AREAS = defineLogAreas({
1892
1996
  "store.workflows-cleared": "The workflow store was full, so a batch of its oldest finished records was removed.",
1893
1997
  "store.workflows-in-use": "The workflow store was full and every record was still in use, so new work was refused.",
1894
1998
  "remote-worker.settle-failed": "A remote worker could not be settled.",
1999
+ "node-release.failed": "Work on a node that was forgotten or handed over could not be closed; the sweep's registry check retries.",
2000
+ "node-release.reconcile-failed": "The sweep could not check records against the node registry; the next sweep retries.",
2001
+ "node-release.unregistered": "Records named a node the registry no longer holds, so their work was closed here.",
2002
+ "node-release.notice-failed": "The notice for work closed on a released node could not be sent; it stays owed and the sweep retries.",
2003
+ "node-release.no-coordinator": "Work closed on a released node belonged to a coordinator that no longer exists, so nobody was told.",
2004
+ "node-offline.notice-failed": "The notice that a node has been unreachable for a day could not be sent; the next failed read retries.",
2005
+ "node-offline.check-failed": "Whether a long-unreachable node's coordinators were told could not be checked; the next read retries.",
1895
2006
  "checkout.merge-followed": "After an environment's PR merged, the project checkout was fast-forwarded, or `outcome` says why not.",
1896
2007
  "checkout.merge-follow-failed": "Fast-forwarding the project checkout failed, after an environment's PR merged or before mail woke the main coordinator.",
1897
2008
  "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`).",
@@ -1988,6 +2099,7 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1988
2099
  events: {
1989
2100
  "portable-inputs.relay-missing": "Docker is rootless and the image predates the staged-input relay, so the container cannot read them until rebuilt.",
1990
2101
  "git-mirror.mount-unavailable": "A new container gets no project Git mirror, so its clone goes to the remote.",
2102
+ "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.",
1991
2103
  "git-mirror.refreshed": "A project's Git mirror was built or updated.",
1992
2104
  "git-mirror.seeded": "A project's Git mirror was built from its host checkout and only what the remote added to it.",
1993
2105
  "git-mirror.seed-skipped": "A project's host checkout could not seed its Git mirror, so the build downloads everything.",
@@ -2073,7 +2185,11 @@ var DOCKER_LOG_AREAS = defineLogAreas({
2073
2185
  "network.list-failed": "Docker networks could not be listed.",
2074
2186
  "network.inspect-failed": "A Docker network could not be inspected.",
2075
2187
  "stale-containers.removing": "Stale probe containers are being removed.",
2076
- "stale-networks.removing": "Stale probe networks are being removed."
2188
+ "stale-networks.removing": "Stale probe networks are being removed.",
2189
+ "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).",
2190
+ "peers.subnets-loaded": "The Docker subnets the agent tools server admits were reloaded.",
2191
+ "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.",
2192
+ "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."
2077
2193
  }
2078
2194
  }
2079
2195
  });
@@ -2164,6 +2280,7 @@ var NODES_LOG_AREAS = defineLogAreas({
2164
2280
  "verification.record-failed": "A node verification could not be recorded.",
2165
2281
  "profile.record-failed": "A node profile could not be recorded.",
2166
2282
  "detach.unconfirmed": "A forgotten node has not confirmed the detach yet.",
2283
+ "grant.revocation-listener-failed": "A connection could not be told its client grant was removed; the grant is still gone.",
2167
2284
  "handover.recovery-pending": "Command handover recovery is still pending.",
2168
2285
  "ticket-sync.work-record-failed": "A remote build started but its ticket work location could not be saved.",
2169
2286
  "ticket-sync.failed": "A Kanban sync with a node failed; it is retried.",
@@ -2216,7 +2333,9 @@ var HOST_LOG_AREAS = defineLogAreas({
2216
2333
  "tool.missing": "A host tool was not found.",
2217
2334
  "maintenance.listener-failed": "A host maintenance listener threw; the others still run.",
2218
2335
  "suspend.reconcile-failed": "Reconciling due work after a host suspension failed.",
2219
- "load.sample-failed": "Sampling machine load failed; the next sample retries."
2336
+ "load.sample-failed": "Sampling machine load failed; the next sample retries.",
2337
+ "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.",
2338
+ ...THROTTLE_LOG_EVENTS
2220
2339
  }
2221
2340
  }
2222
2341
  });
@@ -3314,33 +3433,198 @@ function createLogger(area) {
3314
3433
  };
3315
3434
  }
3316
3435
 
3436
+ // ../protocol/src/node/bridge-authority.ts
3437
+ import {
3438
+ createHash,
3439
+ createPrivateKey,
3440
+ createPublicKey,
3441
+ generateKeyPairSync,
3442
+ randomBytes,
3443
+ sign,
3444
+ verify
3445
+ } from "node:crypto";
3446
+ var BRIDGE_AUTHORITY_HEADER = "x-orkestrator-authority";
3447
+ var BRIDGE_AUTHORITY_REFUSED_CODE = "authority-signature-required";
3448
+ var BRIDGE_AUTHORITY_WINDOW_MS = 5 * 60000;
3449
+ var BRIDGE_AUTHORITY_MAX_NONCES = 8192;
3450
+ var BRIDGE_AUTHORITY_MAX_BODY_BYTES = 64 * 1024 * 1024;
3451
+ var SCHEME = "orkestrator-bridge-authority-v1";
3452
+ var KEY_PATTERN = /^[A-Za-z0-9_-]{40,200}$/;
3453
+ var HEADER_PATTERN = /^v1 t=(\d{1,16}) n=([A-Za-z0-9_-]{22}) s=([A-Za-z0-9_-]{86})$/;
3454
+ var READ_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
3455
+ var UNSIGNED_ROUTES = [
3456
+ /^\/session\/[^/]+\/close$/,
3457
+ /^\/sessions\/activity$/,
3458
+ /^\/debug\/log-policy$/
3459
+ ];
3460
+ function bridgeAuthorityKeyEnv(tokenEnv) {
3461
+ return `${tokenEnv}_AUTHORITY_KEY`;
3462
+ }
3463
+ function isBridgeAuthorityKey(value) {
3464
+ return typeof value === "string" && KEY_PATTERN.test(value);
3465
+ }
3466
+ function publicKeyFrom(encoded) {
3467
+ if (!isBridgeAuthorityKey(encoded))
3468
+ return null;
3469
+ try {
3470
+ const key = createPublicKey({
3471
+ key: Buffer.from(encoded, "base64url"),
3472
+ format: "der",
3473
+ type: "spki"
3474
+ });
3475
+ return key.asymmetricKeyType === "ed25519" ? key : null;
3476
+ } catch {
3477
+ return null;
3478
+ }
3479
+ }
3480
+ function bridgeAuthorityTarget(url) {
3481
+ const parsed = new URL(url, "http://bridge.invalid");
3482
+ return `${parsed.pathname}${parsed.search}`;
3483
+ }
3484
+ function bridgeRequestNeedsAuthority(method, target) {
3485
+ if (READ_METHODS.has(method.toUpperCase()))
3486
+ return false;
3487
+ const pathname = bridgeAuthorityTarget(target).split("?", 1)[0];
3488
+ return !UNSIGNED_ROUTES.some((pattern) => pattern.test(pathname));
3489
+ }
3490
+ function bodyDigest(body) {
3491
+ return createHash("sha256").update(body ?? "").digest("hex");
3492
+ }
3493
+ function signedMessage(method, target, issuedAt, nonce, digest) {
3494
+ return Buffer.from([SCHEME, method.toUpperCase(), target, String(issuedAt), nonce, digest].join(`
3495
+ `));
3496
+ }
3497
+ var UNENFORCED = {
3498
+ enforced: false,
3499
+ requires: () => false,
3500
+ check: () => ({ ok: true })
3501
+ };
3502
+ function bridgeAuthorityFromPublicKey(publicKey, options = {}) {
3503
+ if (publicKey === undefined)
3504
+ return UNENFORCED;
3505
+ const key = publicKeyFrom(publicKey);
3506
+ const now = options.now ?? Date.now;
3507
+ const maxNonces = options.maxNonces ?? BRIDGE_AUTHORITY_MAX_NONCES;
3508
+ const seen = new Map;
3509
+ let floor = -Infinity;
3510
+ const remember = (nonce, issuedAt, current) => {
3511
+ for (const [oldNonce, oldIssuedAt] of seen) {
3512
+ if (seen.size < maxNonces && oldIssuedAt >= current - BRIDGE_AUTHORITY_WINDOW_MS)
3513
+ break;
3514
+ seen.delete(oldNonce);
3515
+ floor = Math.max(floor, oldIssuedAt);
3516
+ }
3517
+ seen.set(nonce, issuedAt);
3518
+ };
3519
+ return {
3520
+ enforced: true,
3521
+ requires: bridgeRequestNeedsAuthority,
3522
+ check(request) {
3523
+ if (!request.header)
3524
+ return { ok: false, reason: "missing" };
3525
+ const match = HEADER_PATTERN.exec(request.header.trim());
3526
+ if (!match)
3527
+ return { ok: false, reason: "malformed" };
3528
+ const issuedAt = Number(match[1]);
3529
+ const nonce = match[2];
3530
+ const current = now();
3531
+ if (Math.abs(current - issuedAt) > BRIDGE_AUTHORITY_WINDOW_MS || issuedAt <= floor) {
3532
+ return { ok: false, reason: "stale" };
3533
+ }
3534
+ if (!key)
3535
+ return { ok: false, reason: "invalid" };
3536
+ const valid = verify(null, signedMessage(request.method, bridgeAuthorityTarget(request.url), issuedAt, nonce, bodyDigest(request.body)), key, Buffer.from(match[3], "base64url"));
3537
+ if (!valid)
3538
+ return { ok: false, reason: "invalid" };
3539
+ if (seen.has(nonce))
3540
+ return { ok: false, reason: "replayed" };
3541
+ remember(nonce, issuedAt, current);
3542
+ return { ok: true };
3543
+ }
3544
+ };
3545
+ }
3546
+ function loadBridgeAuthority(tokenEnv, options = {}) {
3547
+ const env = options.env ?? process.env;
3548
+ const name = bridgeAuthorityKeyEnv(tokenEnv);
3549
+ const value = env[name]?.trim();
3550
+ delete env[name];
3551
+ return bridgeAuthorityFromPublicKey(value || undefined, { now: options.now });
3552
+ }
3553
+ function refusal(reason) {
3554
+ return {
3555
+ status: 403,
3556
+ body: {
3557
+ error: "This request changes an agent's authority and needs the backend's signature",
3558
+ code: BRIDGE_AUTHORITY_REFUSED_CODE,
3559
+ reason
3560
+ }
3561
+ };
3562
+ }
3563
+ var TOO_LARGE = {
3564
+ status: 413,
3565
+ body: { error: "Request body is too large" }
3566
+ };
3567
+ var admittedBodies = new WeakMap;
3568
+ async function admitNodeBridgeRequest(authority, request, maxBodyBytes) {
3569
+ const method = request.method ?? "GET";
3570
+ const url = request.url ?? "/";
3571
+ if (!authority.requires(method, url))
3572
+ return null;
3573
+ const header = request.headers[BRIDGE_AUTHORITY_HEADER];
3574
+ const value = Array.isArray(header) ? header[0] : header;
3575
+ if (!value)
3576
+ return refusal("missing");
3577
+ const chunks = [];
3578
+ let total = 0;
3579
+ for await (const chunk of request) {
3580
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
3581
+ total += buffer.length;
3582
+ if (total > maxBodyBytes)
3583
+ return TOO_LARGE;
3584
+ chunks.push(buffer);
3585
+ }
3586
+ const body = Buffer.concat(chunks);
3587
+ const result = authority.check({ method, url, header: value, body });
3588
+ if (!result.ok)
3589
+ return refusal(result.reason);
3590
+ admittedBodies.set(request, body);
3591
+ return null;
3592
+ }
3593
+ function takeAdmittedBody(request) {
3594
+ const body = admittedBodies.get(request);
3595
+ admittedBodies.delete(request);
3596
+ return body;
3597
+ }
3598
+
3317
3599
  // ../protocol/src/node/bridge-credential.ts
3318
3600
  var BRIDGE_TOKEN_PREFIX = "okb_";
3319
3601
  var PR_SET_DUMPABLE = 4;
3320
3602
  var VERIFIER_PATTERN = /^[0-9a-f]{64}$/;
3321
3603
  var log = createLogger("bridge.lifecycle");
3322
3604
  function mintBridgeToken() {
3323
- return `${BRIDGE_TOKEN_PREFIX}${randomBytes(32).toString("base64url")}`;
3605
+ return `${BRIDGE_TOKEN_PREFIX}${randomBytes2(32).toString("base64url")}`;
3324
3606
  }
3325
3607
  function bridgeTokenVerifier(token) {
3326
- return createHash("sha256").update(token).digest("hex");
3608
+ return createHash2("sha256").update(token).digest("hex");
3327
3609
  }
3328
3610
  function bridgeTokenVerifierEnv(tokenEnv) {
3329
3611
  return `${tokenEnv}_SHA256`;
3330
3612
  }
3331
- function credentialFromVerifier(verifier, plainToken) {
3613
+ function credentialFromVerifier(verifier, plainToken, authority = UNENFORCED_AUTHORITY) {
3332
3614
  const expected = Buffer.from(verifier, "hex");
3333
3615
  return {
3334
3616
  plainToken,
3617
+ authority,
3335
3618
  matches(candidate) {
3336
3619
  if (!candidate)
3337
3620
  return false;
3338
- return timingSafeEqual(expected, createHash("sha256").update(candidate).digest());
3621
+ return timingSafeEqual(expected, createHash2("sha256").update(candidate).digest());
3339
3622
  }
3340
3623
  };
3341
3624
  }
3342
- function bridgeCredentialFromToken(token) {
3343
- return credentialFromVerifier(bridgeTokenVerifier(token), token);
3625
+ var UNENFORCED_AUTHORITY = loadBridgeAuthority("", { env: {} });
3626
+ function bridgeCredentialFromToken(token, authority = UNENFORCED_AUTHORITY) {
3627
+ return credentialFromVerifier(bridgeTokenVerifier(token), token, authority);
3344
3628
  }
3345
3629
  function markProcessNonDumpable(loadFfi = () => createRequire2(import.meta.url)("bun:ffi")) {
3346
3630
  if (process.platform !== "linux" || !process.versions.bun)
@@ -3372,21 +3656,23 @@ function loadBridgeCredential(tokenEnv, options = {}) {
3372
3656
  const token = env[tokenEnv]?.trim();
3373
3657
  delete env[verifierEnv];
3374
3658
  delete env[tokenEnv];
3659
+ const authority = loadBridgeAuthority(tokenEnv, { env });
3375
3660
  if (verifier) {
3376
3661
  (options.harden ?? markProcessNonDumpable)();
3377
- return VERIFIER_PATTERN.test(verifier) ? credentialFromVerifier(verifier, undefined) : bridgeCredentialFromToken(mintBridgeToken());
3662
+ return VERIFIER_PATTERN.test(verifier) ? credentialFromVerifier(verifier, undefined, authority) : bridgeCredentialFromToken(mintBridgeToken(), authority);
3378
3663
  }
3379
- return bridgeCredentialFromToken(token || mintBridgeToken());
3664
+ return bridgeCredentialFromToken(token || mintBridgeToken(), authority);
3380
3665
  }
3381
3666
 
3382
3667
  // ../../bridges/pi-bridge/src/config.ts
3383
3668
  var PROVIDER = "pi";
3384
- var bridgeGeneration = randomBytes2(16).toString("hex");
3669
+ var bridgeGeneration = randomBytes3(16).toString("hex");
3385
3670
  var port = parsePort(process.env.PORT);
3386
3671
  var hostname = process.env.HOSTNAME?.trim() || "127.0.0.1";
3387
3672
  var workingDirectory = resolve(process.env.CWD?.trim() || process.cwd());
3388
3673
  var bridgeCredential = loadBridgeCredential("PI_BRIDGE_TOKEN");
3389
3674
  var authToken = bridgeCredential.plainToken ?? "";
3675
+ var bridgeAuthority = bridgeCredential.authority;
3390
3676
  function stateFilePath() {
3391
3677
  const directory = process.env.PI_BRIDGE_STATE_DIR?.trim();
3392
3678
  return directory ? resolve(directory, "state.json") : null;
@@ -3525,7 +3811,7 @@ function promptClaimReleased(state) {
3525
3811
  return claimReleases.get(state)?.promise ?? Promise.resolve();
3526
3812
  }
3527
3813
  function publicTurnStatus(state) {
3528
- return state.promptClaim !== undefined ? "running" : state.status;
3814
+ return state.promptClaim !== undefined || state.compacting ? "running" : state.status;
3529
3815
  }
3530
3816
  function cancelRequestedFor(state, claim) {
3531
3817
  return claim !== undefined && state.cancelRequestedClaim === claim;
@@ -3925,7 +4211,7 @@ function boundId(value) {
3925
4211
  return Buffer.byteLength(trimmed) > MAX_MODEL_ID_BYTES ? "" : trimmed;
3926
4212
  }
3927
4213
  // ../protocol/src/node/revised-rows.ts
3928
- import { createHash as createHash2 } from "node:crypto";
4214
+ import { createHash as createHash3 } from "node:crypto";
3929
4215
  var RECENTLY_REVISED_ROWS_MAX = 128;
3930
4216
 
3931
4217
  class RecentlyRevisedRows {
@@ -3963,7 +4249,7 @@ class RecentlyRevisedRows {
3963
4249
  function revisedRowsReconciliationToken(overflowVersion, omitted) {
3964
4250
  if (overflowVersion === 0 && omitted.length === 0)
3965
4251
  return;
3966
- const digest = createHash2("sha256").update(String(overflowVersion));
4252
+ const digest = createHash3("sha256").update(String(overflowVersion));
3967
4253
  for (const row of omitted)
3968
4254
  digest.update(JSON.stringify(row) ?? "null");
3969
4255
  return digest.digest("hex");
@@ -4589,7 +4875,7 @@ function firstLine(value) {
4589
4875
  return line.trim() || value.trim();
4590
4876
  }
4591
4877
  // ../../bridges/pi-bridge/src/translate.ts
4592
- import { randomBytes as randomBytes4 } from "node:crypto";
4878
+ import { randomBytes as randomBytes5 } from "node:crypto";
4593
4879
 
4594
4880
  // ../protocol/src/transcript-part-ids.ts
4595
4881
  var TOOL_RESULT_IMAGE_PREFIX = "image:";
@@ -4624,7 +4910,7 @@ function nextPartOrdinal(message) {
4624
4910
  }
4625
4911
 
4626
4912
  // ../../bridges/pi-bridge/src/commands.ts
4627
- import { randomBytes as randomBytes3 } from "node:crypto";
4913
+ import { randomBytes as randomBytes4 } from "node:crypto";
4628
4914
 
4629
4915
  // ../protocol/src/agent-platforms.ts
4630
4916
  var AGENT_PLATFORMS = Object.freeze([
@@ -6114,7 +6400,7 @@ function settleCommandRun(state, run, requestId) {
6114
6400
  return;
6115
6401
  }
6116
6402
  function appendCommandOutcome(state, requestId, part) {
6117
- const messageId = requestId ? `command-outcome:${requestId}` : `command-outcome:${randomBytes3(12).toString("hex")}`;
6403
+ const messageId = requestId ? `command-outcome:${requestId}` : `command-outcome:${randomBytes4(12).toString("hex")}`;
6118
6404
  if (state.messages.some((message) => message.id === messageId))
6119
6405
  return;
6120
6406
  const message = {
@@ -6276,7 +6562,7 @@ function applySteerDelivery(state, value) {
6276
6562
  setSteerJournal(state, { ...entry, state: "delivered" });
6277
6563
  state.currentAssistantMessageId = undefined;
6278
6564
  state.openTextParts.clear();
6279
- const messageId = randomBytes4(12).toString("hex");
6565
+ const messageId = randomBytes5(12).toString("hex");
6280
6566
  const message = {
6281
6567
  id: messageId,
6282
6568
  role: "user",
@@ -6566,7 +6852,7 @@ var RESUME_FELL_BACK_NOTICE = "Could not resume the previous Pi conversation, so
6566
6852
  function appendResumeFallbackNotice(state) {
6567
6853
  closeTextParts(state);
6568
6854
  state.currentAssistantMessageId = undefined;
6569
- const messageId = randomBytes4(12).toString("hex");
6855
+ const messageId = randomBytes5(12).toString("hex");
6570
6856
  const createdAt = new Date().toISOString();
6571
6857
  const part = {
6572
6858
  type: "status",
@@ -6674,7 +6960,7 @@ function currentAssistantMessage(state) {
6674
6960
  if (last?.role === "assistant" && last.id === state.currentAssistantMessageId)
6675
6961
  return last;
6676
6962
  const message = {
6677
- id: randomBytes4(12).toString("hex"),
6963
+ id: randomBytes5(12).toString("hex"),
6678
6964
  role: "assistant",
6679
6965
  content: "",
6680
6966
  parts: [],
@@ -6812,7 +7098,7 @@ function readStringList(value) {
6812
7098
  return value.filter((entry) => typeof entry === "string");
6813
7099
  }
6814
7100
  // ../../bridges/pi-bridge/src/interactions.ts
6815
- import { randomBytes as randomBytes6 } from "node:crypto";
7101
+ import { randomBytes as randomBytes7 } from "node:crypto";
6816
7102
 
6817
7103
  // ../protocol/src/agent-interaction-deadline.ts
6818
7104
  var SYSTEM_CLOCK = {
@@ -6926,6 +7212,9 @@ class InteractionDeadline {
6926
7212
  }
6927
7213
 
6928
7214
  // ../protocol/src/coordinator.ts
7215
+ var COORDINATOR_PROTECTED_DATA_DIR_ENV = "ORKESTRATOR_COORDINATOR_PROTECTED_DATA_DIR";
7216
+ var COORDINATOR_OTHER_ENVIRONMENTS_SETTING_LABEL = "Let the coordinator use environments it did not create";
7217
+ var COORDINATOR_ENVIRONMENT_ORIGIN_REFUSAL = `Not done: this coordinator did not create that environment, so it may not send it work. Do not retry. Use an environment this coordinator launched, or start a new one. If the user wants this coordinator to work in environments it did not create, tell them to turn on "${COORDINATOR_OTHER_ENVIRONMENTS_SETTING_LABEL}" in this project's settings, under Coordinator.`;
6929
7218
  var COORDINATOR_CONTROL_TOOL_NAMES = Object.freeze([
6930
7219
  "ack_message",
6931
7220
  "add_ticket_comment",
@@ -7301,7 +7590,7 @@ var DEFAULT_WORKFLOW_RESULT_TOOLS_SETTINGS = {
7301
7590
  };
7302
7591
 
7303
7592
  // ../../bridges/pi-bridge/src/mcp.ts
7304
- import { createHash as createHash3 } from "node:crypto";
7593
+ import { createHash as createHash4 } from "node:crypto";
7305
7594
  import { readFile } from "node:fs/promises";
7306
7595
  import { join as join3, resolve as resolvePath } from "node:path";
7307
7596
 
@@ -31150,7 +31439,7 @@ function mcpConnectionNeedsRefresh(state) {
31150
31439
  }
31151
31440
  async function fileDigest(file) {
31152
31441
  try {
31153
- return `sha256:${createHash3("sha256").update(await readFile(file)).digest("base64url")}`;
31442
+ return `sha256:${createHash4("sha256").update(await readFile(file)).digest("base64url")}`;
31154
31443
  } catch {
31155
31444
  return "absent";
31156
31445
  }
@@ -31162,7 +31451,7 @@ async function piMcpConfigRevision(state, options = {}) {
31162
31451
  state.policy?.projectResources === true ? fileDigest(join3(options.cwd ?? workingDirectory, ".pi", "mcp.json")) : Promise.resolve("excluded")
31163
31452
  ]);
31164
31453
  return {
31165
- fingerprint: createHash3("sha256").update(`user=${user}\x00project=${project}`).digest("base64url"),
31454
+ fingerprint: createHash4("sha256").update(`user=${user}\x00project=${project}`).digest("base64url"),
31166
31455
  sources: { user, project }
31167
31456
  };
31168
31457
  }
@@ -31535,7 +31824,7 @@ import { mkdir, readFile as readFile2, rename, writeFile } from "node:fs/promise
31535
31824
  import { dirname } from "node:path";
31536
31825
 
31537
31826
  // ../../bridges/pi-bridge/src/session-factory.ts
31538
- import { randomBytes as randomBytes5 } from "node:crypto";
31827
+ import { randomBytes as randomBytes6 } from "node:crypto";
31539
31828
 
31540
31829
  // ../protocol/src/runtime-health.ts
31541
31830
  var MAX_RUNTIME_NOTICE_MESSAGE_LENGTH = 1000;
@@ -31625,7 +31914,7 @@ function emptyRuntimeHealth() {
31625
31914
  // ../../bridges/pi-bridge/src/session-factory.ts
31626
31915
  function newSessionState(clientSessionKey, policy) {
31627
31916
  return {
31628
- id: randomBytes5(16).toString("hex"),
31917
+ id: randomBytes6(16).toString("hex"),
31629
31918
  ...policy ? { policy } : {},
31630
31919
  ...clientSessionKey ? { clientSessionKey } : {},
31631
31920
  status: "idle",
@@ -31776,6 +32065,7 @@ function toPersisted(state) {
31776
32065
  ...state.promptJournalComplete ? { promptJournalComplete: true } : {},
31777
32066
  steerJournal: Array.from(state.steerJournal.values()).map((entry) => entry.state === "prepared" || entry.state === "queued" ? { ...entry, state: "ambiguous" } : entry),
31778
32067
  composer: state.composer,
32068
+ ...state.autoCompaction === undefined ? {} : { autoCompaction: state.autoCompaction },
31779
32069
  ...state.usage ? { usage: state.usage } : {},
31780
32070
  ...state.slashCommands.length > 0 ? { commands: state.slashCommands } : {},
31781
32071
  ...state.commandCatalogue.truncated ? { commandsTruncated: true } : {},
@@ -31840,6 +32130,8 @@ function restoreSession(entry) {
31840
32130
  state.transcriptTruncated = entry.transcriptTruncated === true;
31841
32131
  state.revision = readCount(entry.revision);
31842
32132
  state.composer = restoreComposer(entry.composer);
32133
+ if (typeof entry.autoCompaction === "boolean")
32134
+ state.autoCompaction = entry.autoCompaction;
31843
32135
  const usage = restoreUsage(entry.usage);
31844
32136
  if (usage)
31845
32137
  state.usage = usage;
@@ -31994,6 +32286,365 @@ function readJournalState(value) {
31994
32286
  return "ambiguous";
31995
32287
  }
31996
32288
 
32289
+ // ../../bridges/pi-bridge/src/read-boundary.ts
32290
+ import { homedir as homedir3 } from "node:os";
32291
+ import { resolve as resolve4 } from "node:path";
32292
+ import { fileURLToPath } from "node:url";
32293
+
32294
+ // ../protocol/src/node/coordinator-read-boundary.ts
32295
+ import { realpathSync } from "node:fs";
32296
+ import { homedir as homedir2 } from "node:os";
32297
+ import { dirname as dirname2, isAbsolute, join as join4, parse as parse4, resolve as resolve2, sep } from "node:path";
32298
+ function canonicalPath(path) {
32299
+ let existing = path;
32300
+ const tail = [];
32301
+ for (;; ) {
32302
+ try {
32303
+ return join4(realpathSync.native(existing), ...tail.reverse());
32304
+ } catch {
32305
+ const parent = dirname2(existing);
32306
+ if (parent === existing)
32307
+ return path;
32308
+ tail.push(existing.slice(parent.length).replace(/^[/\\]+/, ""));
32309
+ existing = parent;
32310
+ }
32311
+ }
32312
+ }
32313
+ function namedAndCanonicalPaths(paths) {
32314
+ const named = paths.flatMap((path) => path?.trim() && isAbsolute(path) ? [path] : []);
32315
+ return [...new Set(named.flatMap((path) => [resolve2(path), canonicalPath(path)]))];
32316
+ }
32317
+ function isWithin(root, path) {
32318
+ if (path === root)
32319
+ return true;
32320
+ const prefix = root === parse4(root).root ? root : `${root}${sep}`;
32321
+ return path.startsWith(prefix);
32322
+ }
32323
+ function protectedDataDirBoundary(dataDir, allowances) {
32324
+ const trimmed = dataDir?.trim();
32325
+ if (!trimmed || !isAbsolute(trimmed))
32326
+ return null;
32327
+ const deny = namedAndCanonicalPaths([trimmed]);
32328
+ return {
32329
+ deny,
32330
+ allow: namedAndCanonicalPaths(allowances).filter((path) => !deny.includes(path) && deny.some((root) => isWithin(root, path)))
32331
+ };
32332
+ }
32333
+ function deniedForm(boundary, path) {
32334
+ return boundary.deny.some((root) => isWithin(root, path)) && !boundary.allow.some((root) => isWithin(root, path));
32335
+ }
32336
+ function expandedHome(path) {
32337
+ if (path === "~")
32338
+ return homedir2();
32339
+ return path.startsWith("~/") ? `${homedir2()}${sep}${path.slice(2)}` : path;
32340
+ }
32341
+ function readBoundaryRefuses(boundary, path, cwd, options = {}) {
32342
+ const expanded = expandedHome(path);
32343
+ const raw = isAbsolute(expanded) ? expanded : `${cwd}${sep}${expanded}`;
32344
+ const lexical = resolve2(raw);
32345
+ const real = canonicalPath(raw);
32346
+ if (deniedForm(boundary, lexical) || deniedForm(boundary, real))
32347
+ return true;
32348
+ return options.traversal === true && boundary.deny.some((root) => isWithin(lexical, root) || isWithin(real, root));
32349
+ }
32350
+
32351
+ // ../../bridges/pi-bridge/src/prompt-attachments.ts
32352
+ import { constants as constants2 } from "node:fs";
32353
+ import { lstat, open as open2, realpath } from "node:fs/promises";
32354
+ import { isAbsolute as isAbsolute2, join as join5, relative, resolve as resolve3, sep as sep2 } from "node:path";
32355
+ class PromptAttachmentError extends Error {
32356
+ code;
32357
+ name = "PromptAttachmentError";
32358
+ constructor(code, message) {
32359
+ super(message);
32360
+ this.code = code;
32361
+ }
32362
+ }
32363
+ var MAX_IMAGE_ATTACHMENT_BYTES = 8 * 1024 * 1024;
32364
+ var MAX_PROMPT_ATTACHMENTS = 20;
32365
+ var MAX_TOTAL_IMAGE_ATTACHMENT_BYTES = 32 * 1024 * 1024;
32366
+ var MAX_ATTACHMENT_PATH_BYTES = 4 * 1024;
32367
+ var MAX_ATTACHMENT_FILENAME_BYTES = 1 * 1024;
32368
+ var READ_CHUNK_BYTES = 64 * 1024;
32369
+ function parsePromptAttachments(value) {
32370
+ if (value === undefined || value === null)
32371
+ return [];
32372
+ if (!Array.isArray(value)) {
32373
+ throw new PromptAttachmentError("attachment_invalid", "attachments must be an array");
32374
+ }
32375
+ if (value.length > MAX_PROMPT_ATTACHMENTS) {
32376
+ throw new PromptAttachmentError("attachment_invalid", `A prompt can carry at most ${MAX_PROMPT_ATTACHMENTS} attachments`);
32377
+ }
32378
+ return value.map((candidate) => {
32379
+ if (candidate === null || typeof candidate !== "object" || Array.isArray(candidate)) {
32380
+ throw new PromptAttachmentError("attachment_invalid", "Each attachment must be an object");
32381
+ }
32382
+ const record = candidate;
32383
+ if (record.type !== "image" && record.type !== "file") {
32384
+ throw new PromptAttachmentError("attachment_invalid", "An attachment must be an image or a file");
32385
+ }
32386
+ const path = typeof record.path === "string" ? record.path.trim() : "";
32387
+ if (!path || Buffer.byteLength(path) > MAX_ATTACHMENT_PATH_BYTES) {
32388
+ throw new PromptAttachmentError("attachment_invalid", "Each attachment needs a workspace path");
32389
+ }
32390
+ if (path.includes("\x00")) {
32391
+ throw new PromptAttachmentError("attachment_invalid", "An attachment path must not contain null bytes");
32392
+ }
32393
+ const filename = typeof record.filename === "string" && record.filename.trim() && Buffer.byteLength(record.filename) <= MAX_ATTACHMENT_FILENAME_BYTES ? record.filename : undefined;
32394
+ return { type: record.type, path, ...filename ? { filename } : {} };
32395
+ });
32396
+ }
32397
+ async function readPromptImages(attachments, workspaceRoot, modelResize) {
32398
+ const images = [];
32399
+ let totalBytes = 0;
32400
+ for (const attachment of attachments) {
32401
+ if (attachment.type !== "image")
32402
+ continue;
32403
+ const { bytes, absolutePath, mimeType } = await readWorkspaceImage(attachment.path, workspaceRoot);
32404
+ totalBytes += bytes.length;
32405
+ if (totalBytes > MAX_TOTAL_IMAGE_ATTACHMENT_BYTES) {
32406
+ throw new PromptAttachmentError("attachment_too_large", "Image attachments exceed the 32MB total limit");
32407
+ }
32408
+ const normalized = await normalizeImageForPi(bytes, mimeType, modelResize);
32409
+ images.push({
32410
+ data: normalized.data,
32411
+ mimeType: normalized.mimeType,
32412
+ path: attachment.path,
32413
+ absolutePath,
32414
+ ...attachment.filename ? { filename: attachment.filename } : {}
32415
+ });
32416
+ }
32417
+ return images;
32418
+ }
32419
+ async function normalizeImageForPi(bytes, mimeType, modelResize) {
32420
+ const resized = await resizeImage(bytes, mimeType, {
32421
+ ...modelResize,
32422
+ maxBytes: Math.min(modelResize?.maxBytes ?? Infinity, MAX_IMAGE_ATTACHMENT_BYTES)
32423
+ }).catch(() => null);
32424
+ let normalized = resized ?? { data: bytes.toString("base64"), mimeType };
32425
+ if (normalized.mimeType === "image/gif" || normalized.mimeType === "image/webp") {
32426
+ normalized = await convertToPng(normalized.data, normalized.mimeType).catch(() => null) ?? normalized;
32427
+ }
32428
+ return { data: normalized.data, mimeType: normalized.mimeType };
32429
+ }
32430
+ function attachmentErrorForFsFailure(error) {
32431
+ const code = error?.code;
32432
+ if (code === "ELOOP") {
32433
+ return new PromptAttachmentError("attachment_symlink_not_allowed", "Image attachments must be regular workspace files, not symbolic links");
32434
+ }
32435
+ return new PromptAttachmentError("attachment_read_failed", "Image attachment could not be read from the workspace");
32436
+ }
32437
+ var BRIDGE_ATTACHMENT_ROOT_ENV = "ORKESTRATOR_BRIDGE_ATTACHMENT_ROOT";
32438
+ function configuredAttachmentRoot(env = process.env) {
32439
+ const value = env[BRIDGE_ATTACHMENT_ROOT_ENV]?.trim();
32440
+ return value && isAbsolute2(value) ? resolve3(value) : undefined;
32441
+ }
32442
+ function attachmentContainmentRoot(filePath, workspaceRoot, extraRoot = configuredAttachmentRoot()) {
32443
+ if (extraRoot && isAbsolute2(filePath) && isPathWithin(extraRoot, resolve3(filePath))) {
32444
+ return extraRoot;
32445
+ }
32446
+ return resolve3(workspaceRoot);
32447
+ }
32448
+ function isPathWithin(root, candidate) {
32449
+ if (candidate === root)
32450
+ return true;
32451
+ const childPath = relative(root, candidate);
32452
+ return Boolean(childPath) && childPath !== ".." && !childPath.startsWith(`..${sep2}`) && !isAbsolute2(childPath);
32453
+ }
32454
+ async function assertNoSymlinkComponents(root, targetPath) {
32455
+ let currentPath = root;
32456
+ for (const segment of relative(root, targetPath).split(sep2).filter(Boolean)) {
32457
+ currentPath = join5(currentPath, segment);
32458
+ const stats = await lstat(currentPath).catch((error) => {
32459
+ throw attachmentErrorForFsFailure(error);
32460
+ });
32461
+ if (stats.isSymbolicLink()) {
32462
+ throw new PromptAttachmentError("attachment_symlink_not_allowed", "Image attachments must be regular workspace files, not symbolic links");
32463
+ }
32464
+ }
32465
+ }
32466
+ async function assertOpenedWorkspaceFile(targetPath, canonicalRoot, openedStats) {
32467
+ const [pathStats, canonicalTarget] = await Promise.all([
32468
+ lstat(targetPath),
32469
+ realpath(targetPath)
32470
+ ]).catch((error) => {
32471
+ throw attachmentErrorForFsFailure(error);
32472
+ });
32473
+ if (pathStats.isSymbolicLink()) {
32474
+ throw new PromptAttachmentError("attachment_symlink_not_allowed", "Image attachments must be regular workspace files, not symbolic links");
32475
+ }
32476
+ if (!pathStats.isFile() || !openedStats.isFile() || pathStats.dev !== openedStats.dev || pathStats.ino !== openedStats.ino) {
32477
+ throw new PromptAttachmentError("attachment_not_regular_file", "Image attachment is not a stable regular workspace file");
32478
+ }
32479
+ if (!isPathWithin(canonicalRoot, canonicalTarget)) {
32480
+ throw new PromptAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace");
32481
+ }
32482
+ }
32483
+ function assertStableRead(initial, final, bytesRead) {
32484
+ if (final.dev !== initial.dev || final.ino !== initial.ino || final.size !== initial.size || final.size !== bytesRead || final.mtimeMs !== initial.mtimeMs || final.ctimeMs !== initial.ctimeMs) {
32485
+ throw new PromptAttachmentError("attachment_changed", "Image attachment changed while it was being read; attach it again");
32486
+ }
32487
+ }
32488
+ async function readWorkspaceImage(filePath, workspaceRoot) {
32489
+ const lexicalRoot = attachmentContainmentRoot(filePath, workspaceRoot);
32490
+ const targetPath = isAbsolute2(filePath) ? resolve3(filePath) : resolve3(lexicalRoot, filePath);
32491
+ if (!isPathWithin(lexicalRoot, targetPath)) {
32492
+ throw new PromptAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace");
32493
+ }
32494
+ const canonicalRoot = await realpath(lexicalRoot).catch((error) => {
32495
+ throw attachmentErrorForFsFailure(error);
32496
+ });
32497
+ await assertNoSymlinkComponents(lexicalRoot, targetPath);
32498
+ const canonicalTarget = await realpath(targetPath).catch((error) => {
32499
+ throw attachmentErrorForFsFailure(error);
32500
+ });
32501
+ if (!isPathWithin(canonicalRoot, canonicalTarget)) {
32502
+ throw new PromptAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace");
32503
+ }
32504
+ const noFollow = constants2.O_NOFOLLOW ?? 0;
32505
+ const handle = await open2(targetPath, constants2.O_RDONLY | noFollow).catch((error) => {
32506
+ throw attachmentErrorForFsFailure(error);
32507
+ });
32508
+ try {
32509
+ const initialStats = await handle.stat();
32510
+ await assertOpenedWorkspaceFile(targetPath, canonicalRoot, initialStats);
32511
+ if (initialStats.size > MAX_IMAGE_ATTACHMENT_BYTES) {
32512
+ throw new PromptAttachmentError("attachment_too_large", "Image attachment exceeds the 8MB limit");
32513
+ }
32514
+ const mimeType = await detectSupportedImageMimeTypeFromFile(targetPath).catch(() => null);
32515
+ if (!mimeType) {
32516
+ throw new PromptAttachmentError("attachment_unsupported_format", "Image attachments must be PNG, JPEG, GIF, or WebP");
32517
+ }
32518
+ const chunks = [];
32519
+ let totalBytes = 0;
32520
+ while (totalBytes <= MAX_IMAGE_ATTACHMENT_BYTES) {
32521
+ const remaining = MAX_IMAGE_ATTACHMENT_BYTES + 1 - totalBytes;
32522
+ const chunk = Buffer.allocUnsafe(Math.min(READ_CHUNK_BYTES, remaining));
32523
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
32524
+ if (bytesRead === 0)
32525
+ break;
32526
+ chunks.push(chunk.subarray(0, bytesRead));
32527
+ totalBytes += bytesRead;
32528
+ }
32529
+ if (totalBytes > MAX_IMAGE_ATTACHMENT_BYTES) {
32530
+ throw new PromptAttachmentError("attachment_too_large", "Image attachment exceeds the 8MB limit");
32531
+ }
32532
+ if (totalBytes === 0) {
32533
+ throw new PromptAttachmentError("attachment_empty", "Image attachment file is empty");
32534
+ }
32535
+ const finalStats = await handle.stat();
32536
+ await assertOpenedWorkspaceFile(targetPath, canonicalRoot, finalStats);
32537
+ assertStableRead(initialStats, finalStats, totalBytes);
32538
+ return { bytes: Buffer.concat(chunks, totalBytes), absolutePath: targetPath, mimeType };
32539
+ } catch (error) {
32540
+ if (error instanceof PromptAttachmentError)
32541
+ throw error;
32542
+ throw attachmentErrorForFsFailure(error);
32543
+ } finally {
32544
+ await handle.close();
32545
+ }
32546
+ }
32547
+ async function resolvePromptFiles(attachments, workspaceRoot) {
32548
+ const files = [];
32549
+ for (const attachment of attachments) {
32550
+ if (attachment.type !== "file")
32551
+ continue;
32552
+ const absolutePath = await resolveWorkspaceFile(attachment.path, workspaceRoot);
32553
+ files.push({
32554
+ path: attachment.path,
32555
+ absolutePath,
32556
+ ...attachment.filename ? { filename: attachment.filename } : {}
32557
+ });
32558
+ }
32559
+ return files;
32560
+ }
32561
+ async function resolveWorkspaceFile(filePath, workspaceRoot) {
32562
+ const lexicalRoot = attachmentContainmentRoot(filePath, workspaceRoot);
32563
+ const targetPath = isAbsolute2(filePath) ? resolve3(filePath) : resolve3(lexicalRoot, filePath);
32564
+ if (!isPathWithin(lexicalRoot, targetPath)) {
32565
+ throw new PromptAttachmentError("attachment_outside_workspace", "A file attachment must be contained in the current workspace");
32566
+ }
32567
+ const canonicalRoot = await realpath(lexicalRoot).catch((error) => {
32568
+ throw attachmentErrorForFsFailure(error);
32569
+ });
32570
+ await assertNoSymlinkComponents(lexicalRoot, targetPath);
32571
+ const canonicalTarget = await realpath(targetPath).catch((error) => {
32572
+ throw attachmentErrorForFsFailure(error);
32573
+ });
32574
+ if (!isPathWithin(canonicalRoot, canonicalTarget)) {
32575
+ throw new PromptAttachmentError("attachment_outside_workspace", "A file attachment must be contained in the current workspace");
32576
+ }
32577
+ const stats = await lstat(targetPath).catch((error) => {
32578
+ throw attachmentErrorForFsFailure(error);
32579
+ });
32580
+ if (!stats.isFile()) {
32581
+ throw new PromptAttachmentError("attachment_not_regular_file", "A file attachment must name a regular workspace file");
32582
+ }
32583
+ return targetPath;
32584
+ }
32585
+ function promptFileReferences(files) {
32586
+ if (files.length === 0)
32587
+ return "";
32588
+ const lines = files.map((file) => file.filename && file.filename !== file.path ? `- ${file.absolutePath} (${file.filename})` : `- ${file.absolutePath}`);
32589
+ return `
32590
+
32591
+ Attached files:
32592
+ ${lines.join(`
32593
+ `)}`;
32594
+ }
32595
+
32596
+ // ../../bridges/pi-bridge/src/read-boundary.ts
32597
+ var PI_READ_BOUNDARY_REFUSAL = "Coordinators cannot read Orkestrator's data directory, which holds credentials with wider authority than this conversation. This conversation's own attachments stay readable.";
32598
+ function piCoordinatorReadBoundary(cwd, env = process.env) {
32599
+ return protectedDataDirBoundary(env[COORDINATOR_PROTECTED_DATA_DIR_ENV], [
32600
+ cwd,
32601
+ canonicalPath(cwd),
32602
+ configuredAttachmentRoot(env)
32603
+ ]);
32604
+ }
32605
+ var UNICODE_SPACES = /[  -    ]/g;
32606
+ function piPath(value) {
32607
+ let path = value.replace(UNICODE_SPACES, " ");
32608
+ if (path.startsWith("@"))
32609
+ path = path.slice(1);
32610
+ if (path.startsWith("file://")) {
32611
+ try {
32612
+ path = fileURLToPath(path);
32613
+ } catch {
32614
+ return;
32615
+ }
32616
+ }
32617
+ return path;
32618
+ }
32619
+ var SEARCHES = new Set(["grep", "find"]);
32620
+ var READERS = new Set(["read", "ls", ...SEARCHES]);
32621
+ function piReadToolRefused(boundary, toolName, input, cwd) {
32622
+ if (!READERS.has(toolName))
32623
+ return false;
32624
+ const raw = input && typeof input === "object" ? input.path : undefined;
32625
+ const named = typeof raw === "string" && raw.trim() ? raw : toolName === "read" ? undefined : ".";
32626
+ if (named === undefined)
32627
+ return false;
32628
+ const path = piPath(named);
32629
+ if (path === undefined)
32630
+ return true;
32631
+ if (readBoundaryRefuses(boundary, path, cwd, { traversal: SEARCHES.has(toolName) })) {
32632
+ return true;
32633
+ }
32634
+ if (toolName !== "read")
32635
+ return false;
32636
+ const expanded = path === "~" ? homedir3() : path.startsWith("~/") ? resolve4(homedir3(), path.slice(2)) : path;
32637
+ const resolved = resolve4(cwd, expanded);
32638
+ const nfd = resolved.normalize("NFD");
32639
+ return [
32640
+ resolved,
32641
+ resolved.replace(/ (AM|PM)\./gi, " $1."),
32642
+ nfd,
32643
+ resolved.replace(/'/g, "’"),
32644
+ nfd.replace(/'/g, "’")
32645
+ ].some((candidate) => readBoundaryRefuses(boundary, candidate, cwd));
32646
+ }
32647
+
31997
32648
  // ../../bridges/pi-bridge/src/interactions.ts
31998
32649
  var READ_ONLY_TOOLS = new Set(["read", "grep", "find", "ls"]);
31999
32650
  async function requestToolApproval(state, toolCallId, toolName, input) {
@@ -32006,6 +32657,12 @@ async function requestToolApproval(state, toolCallId, toolName, input) {
32006
32657
  reason: "This review session is read-only. Read the supplied package; commands, edits, and extension tools are disabled."
32007
32658
  };
32008
32659
  }
32660
+ if (READ_ONLY_TOOLS.has(toolName)) {
32661
+ const boundary = piCoordinatorReadBoundary(workingDirectory);
32662
+ if (boundary && piReadToolRefused(boundary, toolName, input, workingDirectory)) {
32663
+ return { block: true, reason: PI_READ_BOUNDARY_REFUSAL };
32664
+ }
32665
+ }
32009
32666
  if (turnCancellationRequested(state)) {
32010
32667
  return { block: true, reason: "The turn was cancelled before this tool call was approved." };
32011
32668
  }
@@ -32024,7 +32681,7 @@ async function requestToolApproval(state, toolCallId, toolName, input) {
32024
32681
  if (state.approvals.size >= MAX_PENDING_APPROVALS) {
32025
32682
  return { block: true, reason: "Too many tool calls are already awaiting approval." };
32026
32683
  }
32027
- const id = randomBytes6(12).toString("hex");
32684
+ const id = randomBytes7(12).toString("hex");
32028
32685
  return new Promise((resolve) => {
32029
32686
  let settled = false;
32030
32687
  const settle = (decision, reason) => {
@@ -32137,7 +32794,7 @@ function readString2(value) {
32137
32794
  return nonBlank(value) ? value.trim() : "";
32138
32795
  }
32139
32796
  // ../../bridges/pi-bridge/src/agent-session.ts
32140
- import { randomBytes as randomBytes7 } from "node:crypto";
32797
+ import { randomBytes as randomBytes8 } from "node:crypto";
32141
32798
  import { existsSync as existsSync2, statSync } from "node:fs";
32142
32799
 
32143
32800
  // ../protocol/src/rich-content-policy.ts
@@ -32413,12 +33070,12 @@ function assertExecutionPolicyNotWidened(current, next) {
32413
33070
  }
32414
33071
 
32415
33072
  // ../../bridges/pi-bridge/src/agent-session.ts
32416
- import { realpath, stat as stat3 } from "node:fs/promises";
32417
- import { join as join7, resolve as resolve3, sep } from "node:path";
33073
+ import { realpath as realpath2, stat as stat3 } from "node:fs/promises";
33074
+ import { join as join9, resolve as resolve6, sep as sep3 } from "node:path";
32418
33075
 
32419
33076
  // ../protocol/src/node/command-change-journal.ts
32420
33077
  import { appendFile, mkdir as mkdir2, readFile as readFile3, rename as rename2, rm, stat, writeFile as writeFile2 } from "node:fs/promises";
32421
- import { dirname as dirname2 } from "node:path";
33078
+ import { dirname as dirname3 } from "node:path";
32422
33079
  var MAX_JOURNAL_ENTRIES = 1000;
32423
33080
  var MAX_JOURNAL_FILES_PER_ENTRY = 20;
32424
33081
  var MAX_JOURNAL_PATH_LENGTH = 1024;
@@ -32491,7 +33148,7 @@ class CommandChangeJournal {
32491
33148
  const line = `${JSON.stringify({ id, change: bounded })}
32492
33149
  `;
32493
33150
  this.writes = this.writes.then(async () => {
32494
- await mkdir2(dirname2(this.path), { recursive: true, mode: 448 });
33151
+ await mkdir2(dirname3(this.path), { recursive: true, mode: 448 });
32495
33152
  if (!this.sizeChecked) {
32496
33153
  this.sizeChecked = true;
32497
33154
  const existing = await stat(this.path).catch(() => {
@@ -32584,12 +33241,850 @@ function isFileEditToolName(toolName) {
32584
33241
  }
32585
33242
 
32586
33243
  // ../protocol/src/node/workspace-change-probe.ts
32587
- import { execFile, spawn as spawn2 } from "node:child_process";
32588
- import { randomUUID } from "node:crypto";
32589
- import { rmSync } from "node:fs";
32590
- import { copyFile, lstat, mkdtemp as mkdtemp2, rm as rm2 } from "node:fs/promises";
33244
+ import { randomUUID as randomUUID2 } from "node:crypto";
33245
+ import { rmSync as rmSync2 } from "node:fs";
33246
+ import { copyFile, lstat as lstat2, mkdtemp as mkdtemp2, rm as rm2 } from "node:fs/promises";
32591
33247
  import { tmpdir as tmpdir2 } from "node:os";
32592
- import { delimiter, isAbsolute, join as join4, resolve as resolve2 } from "node:path";
33248
+ import { delimiter, isAbsolute as isAbsolute3, join as join6, resolve as resolve5 } from "node:path";
33249
+
33250
+ // ../protocol/src/node/command-capture.ts
33251
+ import { spawn as spawn2 } from "node:child_process";
33252
+ import { randomUUID } from "node:crypto";
33253
+ import { constants as fsConstants } from "node:fs";
33254
+ import * as captureFs from "node:fs";
33255
+ import os from "node:os";
33256
+ import path from "node:path";
33257
+ import { inspect } from "node:util";
33258
+
33259
+ // ../protocol/src/node/command-failure-reason.ts
33260
+ var MAX_MATCHED_CHARS = 16 * 1024;
33261
+ var SIGNAL_PATTERN = /^SIG[A-Z0-9]{1,16}$/;
33262
+ var TOOL_RULES = {
33263
+ git: [
33264
+ ["branch-exists", /a branch named .* already exists/i],
33265
+ ["ref-conflict", /exists; cannot create|cannot lock ref .* is at .* but expected/i],
33266
+ ["lock-held", /could not lock config file [^\n]*: File exists/i],
33267
+ ["lock-held", /(?:unable to create '[^\n]*\.lock'|cannot lock ref)[^\n]*: File exists/i],
33268
+ ["lock-held", /another git process/i],
33269
+ ["worktree-conflict", /already (?:checked out|used by worktree)|used by worktree at/i],
33270
+ ["invalid-ref", /not a valid (?:branch name|object name)|bad (?:revision|object)/i],
33271
+ ["invalid-ref", /unknown revision|ambiguous argument|invalid reference/i],
33272
+ ["branch-not-found", /no branch named|refname .* not found|branch '.*' not found/i],
33273
+ ["branch-not-found", /did not match any file\(s\) known to git/i],
33274
+ ["dubious-ownership", /detected dubious ownership/i],
33275
+ ["no-remote", /does not appear to be a git repository|no such remote/i],
33276
+ ["no-remote", /repository (?:.* )?not found/i],
33277
+ ["not-a-repository", /not a git repository/i],
33278
+ ["remote-ref-missing", /could(?:n't| not) find remote ref|not our ref/i],
33279
+ ["merge-conflict", /\bCONFLICT \(|merge conflict|could not apply|unmerged files/i],
33280
+ ["dirty-worktree", /local changes .* would be overwritten|commit your changes or stash/i],
33281
+ ["nothing-to-commit", /nothing to commit|no changes added to commit/i],
33282
+ ["push-rejected", /\[(?:remote )?rejected\]|non-fast-forward/i],
33283
+ ["identity-unknown", /please tell me who you are|unable to auto-detect email/i],
33284
+ [
33285
+ "worktree-has-changes",
33286
+ /^fatal: [^\n]*['"] contains modified or untracked files(?:, use --force to delete it)?\.?\s*$/im
33287
+ ],
33288
+ ["not-a-worktree", /^fatal: [^\n]*['"] is not a working tree\.?\s*$/im],
33289
+ ["branch-not-merged", /^(?:error|fatal): [^\n]*['"] is not fully merged\.?\s*$/im]
33290
+ ],
33291
+ gh: [
33292
+ ["pull-request-exists", /a pull request for branch .* already exists/i],
33293
+ ["no-pull-request", /no (?:pull requests? (?:found|match)|open pull requests?\b)/i],
33294
+ ["rate-limited", /rate limit|http 429/i],
33295
+ ["forbidden", /http 403|resource not accessible/i],
33296
+ ["resource-not-found", /http 404|could not resolve to a/i],
33297
+ ["server-error", /http 5\d\d/i]
33298
+ ],
33299
+ docker: [
33300
+ ["daemon-unavailable", /cannot connect to the docker daemon|error during connect/i],
33301
+ [
33302
+ "daemon-unavailable",
33303
+ /is the docker daemon running|docker desktop is (?:not running|unable)/i
33304
+ ],
33305
+ ["container-not-found", /no such container/i],
33306
+ ["container-not-running", /container .* is (?:not running|paused|restarting)/i],
33307
+ ["container-name-conflict", /name .* is already in use/i],
33308
+ ["image-not-found", /no such image|pull access denied|manifest .* not found/i],
33309
+ ["image-not-found", /manifest unknown|repository does not exist/i],
33310
+ ["removal-in-progress", /removal of container .* is already in progress/i],
33311
+ [
33312
+ "image-in-use",
33313
+ /image is (?:being used|referenced)|unable to (?:remove|delete) .*must be forced/i
33314
+ ],
33315
+ ["volume-in-use", /volume is in use/i],
33316
+ ["volume-not-found", /no such volume/i],
33317
+ ["network-in-use", /has active endpoints/i],
33318
+ ["network-not-found", /network .* not found/i]
33319
+ ],
33320
+ tmux: [
33321
+ ["session-exists", /duplicate session/i],
33322
+ [
33323
+ "server-not-running",
33324
+ /no server running|failed to connect to server|no sessions|server exited|lost server/i
33325
+ ],
33326
+ [
33327
+ "server-not-running",
33328
+ /error connecting to \/[^\n]* \((?:No such file or directory|Connection refused)\)/i
33329
+ ],
33330
+ ["session-not-found", /can't find (?:session|window|pane)|session not found/i]
33331
+ ]
33332
+ };
33333
+ var ALL_TOOLS = Object.keys(TOOL_RULES);
33334
+ var SHARED_RULES = [
33335
+ ["disk-full", /no space left|enospc|disk quota exceeded/i],
33336
+ ["auth-failed", /authentication (?:failed|required)|could not read (?:username|password)/i],
33337
+ ["auth-failed", /terminal prompts disabled|invalid username or password|bad credentials/i],
33338
+ ["auth-failed", /permission denied \(|permission to \S+ denied|host key verification failed/i],
33339
+ ["auth-failed", /gh auth login|not logged in|unauthorized|http 401|returned error: 40[13]/i],
33340
+ ["network-failed", /could not resolve host|connection (?:timed out|refused|reset)/i],
33341
+ ["network-failed", /network is unreachable|no route to host|temporary failure in name/i],
33342
+ ["network-failed", /early eof|failed to connect|remote end hung up/i],
33343
+ ["network-failed", /unable to access ['"]?https?:\/\//i],
33344
+ ["network-failed", /tls handshake|i\/o timeout/i],
33345
+ [
33346
+ "network-failed",
33347
+ /error connecting to (?:https?:\/\/)?[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?::\d+)?(?:[\s/:]|$)/i
33348
+ ],
33349
+ ["port-in-use", /port is already allocated|address already in use/i],
33350
+ ["permission-denied", /permission denied|operation not permitted|read-only file system/i],
33351
+ ["command-not-found", /command not found/i],
33352
+ ["path-not-found", /no such file or directory/i],
33353
+ ["invalid-usage", /^usage: |unknown (?:option|flag|command|shorthand flag)|invalid option/im]
33354
+ ];
33355
+ var TOOL_EXIT_CODES = {
33356
+ git: { 129: "invalid-usage" },
33357
+ gh: { 2: "aborted", 4: "auth-failed" },
33358
+ docker: { 125: "daemon-error" },
33359
+ tmux: {}
33360
+ };
33361
+ var SHARED_EXIT_CODES = {
33362
+ 124: "timed-out",
33363
+ 126: "not-executable",
33364
+ 127: "command-not-found",
33365
+ 137: "killed",
33366
+ 143: "killed"
33367
+ };
33368
+ function read2(target, key) {
33369
+ return target[key];
33370
+ }
33371
+ function boundedForMatching(text) {
33372
+ if (text.length <= MAX_MATCHED_CHARS)
33373
+ return text;
33374
+ const half = MAX_MATCHED_CHARS / 2;
33375
+ return `${text.slice(0, half)}
33376
+ ${text.slice(-half)}`;
33377
+ }
33378
+ function failureText(error) {
33379
+ const stderr = read2(error, "stderr");
33380
+ if (Buffer.isBuffer(stderr) && stderr.length > 0) {
33381
+ return boundedForMatching(stderr.subarray(-MAX_MATCHED_CHARS).toString());
33382
+ }
33383
+ if (typeof stderr === "string" && stderr.length > 0)
33384
+ return boundedForMatching(stderr);
33385
+ const message = read2(error, "message");
33386
+ if (typeof message !== "string")
33387
+ return "";
33388
+ return message.startsWith("Command failed") ? "" : boundedForMatching(message);
33389
+ }
33390
+ function isRawSpawnEnoent(error) {
33391
+ const syscall = read2(error, "syscall");
33392
+ return read2(error, "code") === "ENOENT" && typeof syscall === "string" && /^(?:spawn(?:Sync)?(?:\s|$)|posix_spawnp?$)/.test(syscall);
33393
+ }
33394
+ function classifiedReason(error, exitCode, signal, options) {
33395
+ if (read2(error, "aborted") === true)
33396
+ return "aborted";
33397
+ if (read2(error, "outputLimitExceeded") === true)
33398
+ return "output-too-large";
33399
+ if (read2(error, "timedOut") === true)
33400
+ return "timed-out";
33401
+ if (read2(error, "executableMissing") === true || isRawSpawnEnoent(error)) {
33402
+ return "executable-missing";
33403
+ }
33404
+ const named = exitCode === null ? undefined : options.exitCodes?.[exitCode];
33405
+ if (named)
33406
+ return named;
33407
+ if (signal)
33408
+ return "killed";
33409
+ const text = failureText(error);
33410
+ for (const tool of options.tools ?? ALL_TOOLS) {
33411
+ for (const [reason, pattern] of TOOL_RULES[tool]) {
33412
+ if (pattern.test(text))
33413
+ return reason;
33414
+ }
33415
+ }
33416
+ for (const [reason, pattern] of SHARED_RULES) {
33417
+ if (pattern.test(text))
33418
+ return reason;
33419
+ }
33420
+ if (exitCode !== null) {
33421
+ for (const tool of options.tools ?? []) {
33422
+ const reason = TOOL_EXIT_CODES[tool][exitCode];
33423
+ if (reason)
33424
+ return reason;
33425
+ }
33426
+ const reason = SHARED_EXIT_CODES[exitCode];
33427
+ if (reason)
33428
+ return reason;
33429
+ }
33430
+ return "unclassified";
33431
+ }
33432
+ function numericExitCode(error) {
33433
+ for (const key of ["exitCode", "code"]) {
33434
+ const value = read2(error, key);
33435
+ if (typeof value === "number" && Number.isFinite(value))
33436
+ return value;
33437
+ }
33438
+ return null;
33439
+ }
33440
+ function classifyCommandFailure(error, options = {}) {
33441
+ if (typeof error !== "object" || error === null) {
33442
+ return { reason: "unclassified", exitCode: null, signal: null };
33443
+ }
33444
+ try {
33445
+ const exitCode = numericExitCode(error);
33446
+ const rawSignal = read2(error, "signal");
33447
+ const signal = typeof rawSignal === "string" && SIGNAL_PATTERN.test(rawSignal) ? rawSignal : null;
33448
+ return { reason: classifiedReason(error, exitCode, signal, options), exitCode, signal };
33449
+ } catch {
33450
+ return { reason: "unclassified", exitCode: null, signal: null };
33451
+ }
33452
+ }
33453
+
33454
+ // ../protocol/src/node/lost-exit-reaper.ts
33455
+ import { createRequire as createRequire3 } from "node:module";
33456
+
33457
+ // ../protocol/src/node/shell-process-state.ts
33458
+ import { spawnSync } from "node:child_process";
33459
+ import { readdirSync, readFileSync } from "node:fs";
33460
+ import { constants as osConstants } from "node:os";
33461
+ var PROCESS_INSPECTION_OPTIONS = {
33462
+ timeout: 100,
33463
+ killSignal: "SIGKILL",
33464
+ maxBuffer: 1024 * 1024
33465
+ };
33466
+ function bunRuntime() {
33467
+ return globalThis.Bun;
33468
+ }
33469
+ function decodeWaitStatus(status) {
33470
+ const signalNumber = status & 127;
33471
+ if (signalNumber === 0)
33472
+ return { code: status >> 8 & 255, signal: null };
33473
+ const name = Object.entries(osConstants.signals).find(([, value]) => value === signalNumber)?.[0];
33474
+ return { code: null, signal: name ?? "SIGKILL" };
33475
+ }
33476
+ function readZombieExit(pid) {
33477
+ try {
33478
+ const result = bunRuntime()?.spawnSync(["/bin/ps", "-o", "stat=,xstat=", "-p", String(pid)], PROCESS_INSPECTION_OPTIONS);
33479
+ if (!result?.success)
33480
+ return;
33481
+ const { stdout } = result;
33482
+ const match = /^Z\S*\s+([0-9a-f]+)\s*$/i.exec(stdout.toString().trim());
33483
+ return match ? decodeWaitStatus(Number.parseInt(match[1], 16)) : undefined;
33484
+ } catch {
33485
+ return;
33486
+ }
33487
+ }
33488
+ var EXIT_WATCH_MS = 1000;
33489
+ var EXIT_WATCH_MAX_MS = 16000;
33490
+ function watchForLostExit(pid, onExit) {
33491
+ if (process.platform !== "darwin" || pid === undefined || !bunRuntime())
33492
+ return () => {
33493
+ return;
33494
+ };
33495
+ let timer;
33496
+ const watch = (delayMs) => {
33497
+ timer = setTimeout(() => {
33498
+ const exit = readZombieExit(pid);
33499
+ if (exit)
33500
+ onExit(exit);
33501
+ else
33502
+ watch(Math.min(delayMs * 2, EXIT_WATCH_MAX_MS));
33503
+ }, delayMs);
33504
+ };
33505
+ watch(EXIT_WATCH_MS);
33506
+ return () => clearTimeout(timer);
33507
+ }
33508
+ function isLiveMember(state, groupId, pgid) {
33509
+ return Number(groupId) === pgid && state !== undefined && !/^[ZX]/.test(state);
33510
+ }
33511
+ function linuxGroupHasLiveMember(pgid) {
33512
+ for (const entry of readdirSync("/proc")) {
33513
+ if (!/^\d+$/.test(entry))
33514
+ continue;
33515
+ let stat;
33516
+ try {
33517
+ stat = readFileSync(`/proc/${entry}/stat`, "latin1");
33518
+ } catch {
33519
+ continue;
33520
+ }
33521
+ const [state, , groupId] = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
33522
+ if (isLiveMember(state, groupId, pgid))
33523
+ return true;
33524
+ }
33525
+ return false;
33526
+ }
33527
+ function psGroupHasLiveMember(pgid) {
33528
+ const argv = ["-A", "-o", "pgid=,stat="];
33529
+ const bun = bunRuntime();
33530
+ const result = bun ? bun.spawnSync(["/bin/ps", ...argv], PROCESS_INSPECTION_OPTIONS) : spawnSync("/bin/ps", argv, PROCESS_INSPECTION_OPTIONS);
33531
+ const succeeded = "success" in result ? result.success : result.status === 0 && !result.error;
33532
+ if (!succeeded)
33533
+ return true;
33534
+ return result.stdout.toString().split(`
33535
+ `).some((line) => {
33536
+ const [groupId, state] = line.trim().split(/\s+/);
33537
+ return isLiveMember(state, groupId, pgid);
33538
+ });
33539
+ }
33540
+ function groupHasLiveMember(pgid) {
33541
+ try {
33542
+ return process.platform === "linux" ? linuxGroupHasLiveMember(pgid) : psGroupHasLiveMember(pgid);
33543
+ } catch {
33544
+ return true;
33545
+ }
33546
+ }
33547
+
33548
+ // ../protocol/src/node/lost-exit-reaper.ts
33549
+ var log3 = createLogger("process");
33550
+ var REAP_GRACE_MS = 2000;
33551
+ var REAP_MAX_CHECK_MS = 30000;
33552
+ var REAP_MAX_CHECKS = 12;
33553
+ var REAP_MAX_PENDING = 256;
33554
+ function createLostExitReaper(options) {
33555
+ const { system } = options;
33556
+ const graceMs = options.graceMs ?? REAP_GRACE_MS;
33557
+ const maxCheckMs = options.maxCheckMs ?? REAP_MAX_CHECK_MS;
33558
+ const maxChecks = options.maxChecks ?? REAP_MAX_CHECKS;
33559
+ const maxPending = options.maxPending ?? REAP_MAX_PENDING;
33560
+ const pending = new Map;
33561
+ let reaped = 0;
33562
+ let abandoned = 0;
33563
+ const abandon = (pid, reason) => {
33564
+ abandoned += 1;
33565
+ log3.warn("child.reap-abandoned", { pid, reason });
33566
+ };
33567
+ const check = (pid, reported, startedAt) => {
33568
+ if (reported())
33569
+ return false;
33570
+ const found = system.inspect(pid);
33571
+ if (found === undefined)
33572
+ return true;
33573
+ if (found === "gone" || found.ppid !== system.selfPid)
33574
+ return false;
33575
+ if (!found.state.startsWith("Z"))
33576
+ return true;
33577
+ const result = system.waitNoHang(pid);
33578
+ if (result === pid) {
33579
+ reaped += 1;
33580
+ log3.info("child.reaped", { pid, waitedMs: Date.now() - startedAt });
33581
+ return false;
33582
+ }
33583
+ if (result === 0)
33584
+ return true;
33585
+ abandon(pid, "waitpid-failed");
33586
+ return false;
33587
+ };
33588
+ const schedule = (pid, reported, startedAt, delayMs, checks) => {
33589
+ const timer = setTimeout(() => {
33590
+ pending.delete(pid);
33591
+ let again;
33592
+ try {
33593
+ again = check(pid, reported, startedAt);
33594
+ } catch {
33595
+ again = true;
33596
+ }
33597
+ if (!again)
33598
+ return;
33599
+ if (checks + 1 >= maxChecks) {
33600
+ abandon(pid, "not-a-zombie");
33601
+ return;
33602
+ }
33603
+ schedule(pid, reported, startedAt, Math.min(delayMs * 2, maxCheckMs), checks + 1);
33604
+ }, delayMs);
33605
+ timer.unref?.();
33606
+ pending.set(pid, timer);
33607
+ };
33608
+ return {
33609
+ reap(pid, reported) {
33610
+ if (!Number.isSafeInteger(pid) || pid <= 1 || pid === system.selfPid)
33611
+ return;
33612
+ if (pending.has(pid) || reported())
33613
+ return;
33614
+ if (pending.size >= maxPending) {
33615
+ abandon(pid, "capacity");
33616
+ return;
33617
+ }
33618
+ schedule(pid, reported, Date.now(), graceMs, 0);
33619
+ },
33620
+ stats: () => ({ pending: pending.size, reaped, abandoned }),
33621
+ stop() {
33622
+ for (const timer of pending.values())
33623
+ clearTimeout(timer);
33624
+ pending.clear();
33625
+ }
33626
+ };
33627
+ }
33628
+ var WNOHANG = 1;
33629
+ function loadDarwinWaitpid(loadFfi = () => createRequire3(import.meta.url)("bun:ffi")) {
33630
+ try {
33631
+ const { dlopen, FFIType } = loadFfi();
33632
+ const libSystem = dlopen("/usr/lib/libSystem.B.dylib", {
33633
+ waitpid: { args: [FFIType.i32, FFIType.ptr, FFIType.i32], returns: FFIType.i32 }
33634
+ });
33635
+ const status = new Int32Array(1);
33636
+ return (pid) => libSystem.symbols.waitpid(pid, status, WNOHANG);
33637
+ } catch {
33638
+ return;
33639
+ }
33640
+ }
33641
+ function darwinReaperSystem(loadFfi) {
33642
+ const waitNoHang = loadDarwinWaitpid(loadFfi);
33643
+ if (!waitNoHang)
33644
+ return;
33645
+ return {
33646
+ selfPid: process.pid,
33647
+ inspect(pid) {
33648
+ const result = bunRuntime()?.spawnSync(["/bin/ps", "-o", "ppid=,stat=", "-p", String(pid)], PROCESS_INSPECTION_OPTIONS);
33649
+ if (!result)
33650
+ return;
33651
+ const output = result.stdout.toString().trim();
33652
+ if (!result.success)
33653
+ return result.exitCode === 1 && output === "" ? "gone" : undefined;
33654
+ const match = /^(\d+)\s+(\S+)$/.exec(output);
33655
+ return match ? { ppid: Number(match[1]), state: match[2] } : undefined;
33656
+ },
33657
+ waitNoHang
33658
+ };
33659
+ }
33660
+ var defaultReaper;
33661
+ function createDarwinLostExitReaper(loadFfi) {
33662
+ const system = darwinReaperSystem(loadFfi);
33663
+ if (!system)
33664
+ log3.warn("child.reap-unavailable");
33665
+ return system ? createLostExitReaper({ system }) : null;
33666
+ }
33667
+ function sharedReaper() {
33668
+ if (defaultReaper === undefined) {
33669
+ defaultReaper = createDarwinLostExitReaper();
33670
+ }
33671
+ return defaultReaper ?? undefined;
33672
+ }
33673
+ function reapAfterLostExit(pid, reported) {
33674
+ if (process.platform !== "darwin" || pid === undefined || !bunRuntime())
33675
+ return;
33676
+ sharedReaper()?.reap(pid, reported);
33677
+ }
33678
+
33679
+ // ../protocol/src/node/command-capture.ts
33680
+ class CommandFailedError extends Error {
33681
+ stdout;
33682
+ stdoutBytes;
33683
+ stderr;
33684
+ timedOut;
33685
+ outputCloseTimedOut;
33686
+ executableMissing;
33687
+ aborted;
33688
+ outputLimitExceeded;
33689
+ exitCode;
33690
+ signal;
33691
+ constructor(message, details = {}) {
33692
+ super(message);
33693
+ this.name = "CommandFailedError";
33694
+ this.stdout = details.stdout ?? "";
33695
+ this.stdoutBytes = details.stdoutBytes ?? Buffer.alloc(0);
33696
+ this.stderr = details.stderr ?? "";
33697
+ this.timedOut = details.timedOut ?? false;
33698
+ this.outputCloseTimedOut = details.outputCloseTimedOut ?? false;
33699
+ this.executableMissing = details.executableMissing ?? false;
33700
+ this.aborted = details.aborted ?? false;
33701
+ this.outputLimitExceeded = details.outputLimitExceeded ?? false;
33702
+ this.exitCode = details.exitCode ?? null;
33703
+ this.signal = details.signal ?? null;
33704
+ }
33705
+ toJSON() {
33706
+ return { ...formatLogError(this), ...classifyCommandFailure(this) };
33707
+ }
33708
+ [inspect.custom]() {
33709
+ const { name, reason, exitCode, signal, stack } = this.toJSON();
33710
+ const frames = stack?.length ? ` | ${stack.join(" | ")}` : "";
33711
+ return `${name} reason=${reason} exitCode=${exitCode} signal=${signal} outputOmitted=true${frames}`;
33712
+ }
33713
+ }
33714
+ function redactCommandValues(value, redactValues) {
33715
+ const secrets = Array.from(new Set((redactValues ?? []).filter((secret) => typeof secret === "string" && secret.length > 0))).sort((left, right) => right.length - left.length);
33716
+ return secrets.reduce((redacted, secret) => redacted.split(secret).join("[REDACTED]"), value);
33717
+ }
33718
+ var COMMAND_ABORTED_MESSAGE = "Command aborted";
33719
+ var OUTPUT_LIMIT_MESSAGE = "maxBuffer length exceeded";
33720
+ function commandFailureOutcome(error) {
33721
+ const details = error ?? {};
33722
+ const message = typeof details.message === "string" ? details.message : "";
33723
+ return {
33724
+ timedOut: details.killed === true,
33725
+ executableMissing: details.code === "ENOENT",
33726
+ aborted: message === COMMAND_ABORTED_MESSAGE,
33727
+ outputLimitExceeded: details.outputLimitExceeded === true,
33728
+ exitCode: typeof details.code === "number" ? details.code : null,
33729
+ signal: details.signal ?? null
33730
+ };
33731
+ }
33732
+ var commandInvocations = new Map;
33733
+ var commandCaptureMetrics;
33734
+ var commandObservers = new Map;
33735
+ function nonInteractiveGitEnv(env) {
33736
+ const merged = { ...env ?? process.env };
33737
+ merged.GIT_TERMINAL_PROMPT ??= "0";
33738
+ if (process.platform !== "win32") {
33739
+ merged.SSH_ASKPASS ??= "/usr/bin/false";
33740
+ merged.SSH_ASKPASS_REQUIRE ??= "force";
33741
+ }
33742
+ return merged;
33743
+ }
33744
+ var MAX_COMMAND_OUTPUT_BYTES2 = 50 * 1024 * 1024;
33745
+ var COMMAND_KILL_GRACE_MS = 100;
33746
+ var COMMAND_OUTPUT_CHECK_MS = 100;
33747
+ var COMMAND_GROUP_POLL_MS = 5;
33748
+ var COMMAND_GROUP_POLL_MAX_MS = 200;
33749
+ function openCaptureFile() {
33750
+ const filePath = path.join(os.tmpdir(), `orkestrator-capture-${randomUUID()}`);
33751
+ const fd = captureFs.openSync(filePath, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_RDWR | fsConstants.O_APPEND, 384);
33752
+ try {
33753
+ captureFs.unlinkSync(filePath);
33754
+ return fd;
33755
+ } catch (error) {
33756
+ captureFs.closeSync(fd);
33757
+ throw error;
33758
+ }
33759
+ }
33760
+ function readCaptureFile(fd, limit) {
33761
+ const size = Math.min(captureFs.fstatSync(fd).size, limit);
33762
+ const buffer = Buffer.allocUnsafe(size);
33763
+ let offset = 0;
33764
+ while (offset < size) {
33765
+ const bytesRead = captureFs.readSync(fd, buffer, offset, size - offset, offset);
33766
+ if (bytesRead === 0)
33767
+ break;
33768
+ offset += bytesRead;
33769
+ }
33770
+ return buffer.subarray(0, offset);
33771
+ }
33772
+ function spawnCaptured(command, args, options, stdoutFd, stderrFd) {
33773
+ const payload = options.stdin?.length ? Buffer.from(options.stdin) : undefined;
33774
+ const env = command === "git" ? nonInteractiveGitEnv(options.env) : options.env ?? process.env;
33775
+ const detached = process.platform !== "win32";
33776
+ const bun = bunRuntime();
33777
+ if (bun) {
33778
+ const child = bun.spawn([command, ...args], {
33779
+ cwd: options.cwd,
33780
+ env,
33781
+ detached,
33782
+ windowsHide: true,
33783
+ stdin: payload ?? "pipe",
33784
+ stdout: stdoutFd,
33785
+ stderr: stderrFd
33786
+ });
33787
+ if (!payload)
33788
+ closeStdin(child.stdin);
33789
+ const current = () => ({ code: child.exitCode, signal: child.signalCode });
33790
+ return {
33791
+ pid: child.pid,
33792
+ exited: child.exited.then(current),
33793
+ current,
33794
+ kill: (signal) => child.kill(signal)
33795
+ };
33796
+ }
33797
+ const child = spawn2(command, args, {
33798
+ cwd: options.cwd,
33799
+ env,
33800
+ detached,
33801
+ windowsHide: true,
33802
+ stdio: [payload ? "pipe" : "ignore", stdoutFd, stderrFd]
33803
+ });
33804
+ if (payload) {
33805
+ child.stdin?.on("error", () => {
33806
+ return;
33807
+ });
33808
+ child.stdin?.end(payload);
33809
+ }
33810
+ return {
33811
+ pid: child.pid,
33812
+ exited: new Promise((resolve, reject) => {
33813
+ child.once("exit", (code, signal) => resolve({ code, signal }));
33814
+ child.once("error", reject);
33815
+ }),
33816
+ current: () => ({ code: child.exitCode, signal: child.signalCode }),
33817
+ kill: (signal) => {
33818
+ child.kill(signal);
33819
+ }
33820
+ };
33821
+ }
33822
+ function closeStdin(stdin) {
33823
+ try {
33824
+ Promise.resolve(stdin.end()).catch(() => {
33825
+ return;
33826
+ });
33827
+ } catch {}
33828
+ }
33829
+ function exitReported(child) {
33830
+ const { code, signal } = child.current();
33831
+ return code !== null || signal !== null;
33832
+ }
33833
+ function signalCommand(child, signal) {
33834
+ if (child.pid === undefined)
33835
+ return;
33836
+ try {
33837
+ if (process.platform !== "win32") {
33838
+ process.kill(-child.pid, signal);
33839
+ } else {
33840
+ child.kill(signal);
33841
+ }
33842
+ } catch {}
33843
+ }
33844
+ function commandGroupAlive(child) {
33845
+ if (process.platform === "win32" || child.pid === undefined)
33846
+ return false;
33847
+ try {
33848
+ process.kill(-child.pid, 0);
33849
+ } catch (error) {
33850
+ if (error.code === "ESRCH")
33851
+ return false;
33852
+ }
33853
+ return groupHasLiveMember(child.pid);
33854
+ }
33855
+ function executeCommandBytes(command, args, options, timeoutMs, outputLimit, stderrLimit) {
33856
+ return new Promise((resolve, reject) => {
33857
+ if (options.signal?.aborted) {
33858
+ reject(Object.assign(new Error(COMMAND_ABORTED_MESSAGE), { killed: true }));
33859
+ return;
33860
+ }
33861
+ const captureFds = [];
33862
+ const releaseCaptureFds = () => {
33863
+ for (const fd of captureFds.splice(0)) {
33864
+ try {
33865
+ captureFs.closeSync(fd);
33866
+ } catch {}
33867
+ }
33868
+ };
33869
+ try {
33870
+ captureFds.push(openCaptureFile());
33871
+ captureFds.push(openCaptureFile());
33872
+ } catch (error) {
33873
+ releaseCaptureFds();
33874
+ const code = error.code ?? "unknown";
33875
+ reject(new Error(`Could not open a command output file in the temporary directory: ${code}`));
33876
+ return;
33877
+ }
33878
+ const [stdoutFd, stderrFd] = captureFds;
33879
+ let child;
33880
+ try {
33881
+ child = spawnCaptured(command, args, options, stdoutFd, stderrFd);
33882
+ } catch (error) {
33883
+ releaseCaptureFds();
33884
+ reject(error);
33885
+ return;
33886
+ }
33887
+ let settled = false;
33888
+ let timedOut = false;
33889
+ let timeoutTimer;
33890
+ let groupTimer;
33891
+ let limitTimer;
33892
+ let stopExitWatch = () => {};
33893
+ let commandExit;
33894
+ let pendingFailure;
33895
+ const finishCapture = () => {
33896
+ settled = true;
33897
+ clearTimeout(timeoutTimer);
33898
+ clearTimeout(groupTimer);
33899
+ clearInterval(limitTimer);
33900
+ stopExitWatch();
33901
+ options.signal?.removeEventListener("abort", abort);
33902
+ if (!exitReported(child))
33903
+ reapAfterLostExit(child.pid, () => exitReported(child));
33904
+ try {
33905
+ return {
33906
+ stdout: readCaptureFile(stdoutFd, outputLimit),
33907
+ stderr: readCaptureFile(stderrFd, stderrLimit)
33908
+ };
33909
+ } catch (error) {
33910
+ reject(error);
33911
+ return;
33912
+ } finally {
33913
+ releaseCaptureFds();
33914
+ }
33915
+ };
33916
+ const rejectFailure = (error) => {
33917
+ const output = finishCapture();
33918
+ if (output)
33919
+ reject(Object.assign(error, { ...output, killed: timedOut }));
33920
+ };
33921
+ const awaitTermination = (delayMs) => {
33922
+ clearTimeout(groupTimer);
33923
+ if (settled)
33924
+ return;
33925
+ if ((commandExit || exitReported(child)) && !commandGroupAlive(child)) {
33926
+ rejectFailure(pendingFailure);
33927
+ return;
33928
+ }
33929
+ groupTimer = setTimeout(awaitTermination, delayMs, Math.min(delayMs * 2, COMMAND_GROUP_POLL_MAX_MS));
33930
+ };
33931
+ const fail = (error) => {
33932
+ if (settled || pendingFailure)
33933
+ return;
33934
+ if (options.waitForTermination && child.pid !== undefined) {
33935
+ pendingFailure = error;
33936
+ signalCommand(child, "SIGKILL");
33937
+ clearTimeout(timeoutTimer);
33938
+ clearInterval(limitTimer);
33939
+ awaitTermination(COMMAND_GROUP_POLL_MS);
33940
+ } else
33941
+ rejectFailure(error);
33942
+ };
33943
+ const abort = () => {
33944
+ timedOut = true;
33945
+ signalCommand(child, "SIGKILL");
33946
+ fail(new Error(COMMAND_ABORTED_MESSAGE));
33947
+ };
33948
+ options.signal?.addEventListener("abort", abort, { once: true });
33949
+ const checkOutputLimit = () => {
33950
+ const stream = captureFs.fstatSync(stdoutFd).size > outputLimit ? "stdout" : captureFs.fstatSync(stderrFd).size > stderrLimit ? "stderr" : undefined;
33951
+ if (stream === undefined)
33952
+ return false;
33953
+ signalCommand(child, "SIGKILL");
33954
+ fail(Object.assign(new Error(`${stream} ${OUTPUT_LIMIT_MESSAGE}`), {
33955
+ outputLimitExceeded: true
33956
+ }));
33957
+ return true;
33958
+ };
33959
+ const failIfOverLimit = () => {
33960
+ try {
33961
+ return checkOutputLimit();
33962
+ } catch (error) {
33963
+ signalCommand(child, "SIGKILL");
33964
+ fail(error instanceof Error ? error : new Error(String(error)));
33965
+ return true;
33966
+ }
33967
+ };
33968
+ limitTimer = setInterval(() => {
33969
+ if (!settled && !timedOut && !pendingFailure)
33970
+ failIfOverLimit();
33971
+ }, COMMAND_OUTPUT_CHECK_MS);
33972
+ const settleOnExit = () => {
33973
+ if (settled || timedOut || pendingFailure || failIfOverLimit())
33974
+ return;
33975
+ if (commandExit?.code !== 0 || commandExit.signal !== null) {
33976
+ fail(Object.assign(new Error(`Command failed: ${[command, ...args].join(" ")}`), {
33977
+ code: commandExit?.code,
33978
+ signal: commandExit?.signal
33979
+ }));
33980
+ return;
33981
+ }
33982
+ const output = finishCapture();
33983
+ if (output)
33984
+ resolve(output);
33985
+ };
33986
+ const awaitGroupExit = (delayMs) => {
33987
+ if (settled || timedOut || pendingFailure)
33988
+ return;
33989
+ if (commandGroupAlive(child)) {
33990
+ groupTimer = setTimeout(awaitGroupExit, delayMs, Math.min(delayMs * 2, COMMAND_GROUP_POLL_MAX_MS));
33991
+ return;
33992
+ }
33993
+ settleOnExit();
33994
+ };
33995
+ const onCommandExit = (exit) => {
33996
+ if (commandExit)
33997
+ return;
33998
+ commandExit = exit;
33999
+ stopExitWatch();
34000
+ if (pendingFailure)
34001
+ awaitTermination(COMMAND_GROUP_POLL_MS);
34002
+ else if (options.waitForDescendants)
34003
+ awaitGroupExit(COMMAND_GROUP_POLL_MS);
34004
+ else
34005
+ settleOnExit();
34006
+ };
34007
+ child.exited.then(onCommandExit, (error) => fail(error instanceof Error ? error : new Error(String(error))));
34008
+ stopExitWatch = watchForLostExit(child.pid, (exit) => {
34009
+ if (!settled)
34010
+ onCommandExit(exit);
34011
+ });
34012
+ if (timeoutMs > 0) {
34013
+ timeoutTimer = setTimeout(() => {
34014
+ timedOut = true;
34015
+ signalCommand(child, "SIGTERM");
34016
+ timeoutTimer = setTimeout(() => {
34017
+ signalCommand(child, "SIGKILL");
34018
+ fail(Object.assign(new Error(`Command timed out after ${timeoutMs} ms`), {
34019
+ code: child.current().code,
34020
+ signal: child.current().signal
34021
+ }));
34022
+ }, COMMAND_KILL_GRACE_MS);
34023
+ }, timeoutMs);
34024
+ }
34025
+ });
34026
+ }
34027
+ async function runCommandBytes(command, args = [], options = {}) {
34028
+ const timeoutMs = options.timeoutMs ?? 60000;
34029
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > 2147483647) {
34030
+ throw new RangeError("timeoutMs must be an integer between 0 and 2147483647");
34031
+ }
34032
+ const outputLimit = options.maxOutputBytes ?? MAX_COMMAND_OUTPUT_BYTES2;
34033
+ if (!Number.isSafeInteger(outputLimit) || outputLimit <= 0) {
34034
+ throw new RangeError("maxOutputBytes must be a positive integer");
34035
+ }
34036
+ const stderrLimit = options.maxStderrBytes ?? outputLimit;
34037
+ if (!Number.isSafeInteger(stderrLimit) || stderrLimit <= 0) {
34038
+ throw new RangeError("maxStderrBytes must be a positive integer");
34039
+ }
34040
+ if (commandInvocations.size < 64 || commandInvocations.has(command)) {
34041
+ commandInvocations.set(command, (commandInvocations.get(command) ?? 0) + 1);
34042
+ }
34043
+ for (const observer of commandObservers.get(command) ?? [])
34044
+ observer(args);
34045
+ commandCaptureMetrics?.started(command, args);
34046
+ try {
34047
+ const { stdout, stderr } = await executeCommandBytes(command, args, options, timeoutMs, outputLimit, stderrLimit);
34048
+ commandCaptureMetrics?.capturedBytes(stdout.length);
34049
+ return {
34050
+ stdout: Buffer.isBuffer(stdout) ? stdout : Buffer.from(stdout),
34051
+ stderr: Buffer.isBuffer(stderr) ? stderr : Buffer.from(stderr)
34052
+ };
34053
+ } catch (error) {
34054
+ const outcome = commandFailureOutcome(error);
34055
+ const redacting = options.redactValues?.some((value) => typeof value === "string" && value.length > 0);
34056
+ if (error && typeof error === "object" && "stdout" in error && "stderr" in error) {
34057
+ const withOutput = error;
34058
+ const stderr = withOutput.stderr?.toString() ?? "";
34059
+ const stdout = withOutput.stdout?.toString() ?? "";
34060
+ const message = (stderr || stdout || withOutput.message || "Command failed").trim();
34061
+ throw new CommandFailedError(redactCommandValues(message, options.redactValues), {
34062
+ ...outcome,
34063
+ stdout: redactCommandValues(stdout, options.redactValues),
34064
+ stderr: redactCommandValues(stderr, options.redactValues),
34065
+ ...!redacting && Buffer.isBuffer(withOutput.stdout) ? { stdoutBytes: withOutput.stdout } : {}
34066
+ });
34067
+ }
34068
+ if (redacting) {
34069
+ const message = error instanceof Error ? error.message : String(error);
34070
+ throw new CommandFailedError(redactCommandValues(message || "Command failed", options.redactValues), outcome);
34071
+ }
34072
+ if (outcome.timedOut || outcome.executableMissing) {
34073
+ const message = error instanceof Error ? error.message : String(error);
34074
+ throw new CommandFailedError(message || "Command failed", outcome);
34075
+ }
34076
+ throw error;
34077
+ }
34078
+ }
34079
+ async function runCommand(command, args = [], options = {}) {
34080
+ const { stdout, stderr } = await runCommandBytes(command, args, options);
34081
+ return {
34082
+ stdout: redactCommandValues(stdout.toString(), options.redactValues),
34083
+ stderr: redactCommandValues(stderr.toString(), options.redactValues)
34084
+ };
34085
+ }
34086
+
34087
+ // ../protocol/src/node/workspace-change-probe.ts
32593
34088
  var DEFAULT_MAX_UNTRACKED_FILE_BYTES = 2 * 1024 * 1024;
32594
34089
  var DEFAULT_MAX_UNTRACKED_FILES = 5000;
32595
34090
  var DEFAULT_SLOW_SNAPSHOT_MS = 500;
@@ -32603,31 +34098,20 @@ var temporaryObjectDirectories = new Set;
32603
34098
  process.once("exit", () => {
32604
34099
  for (const directory of temporaryObjectDirectories) {
32605
34100
  try {
32606
- rmSync(directory, { recursive: true, force: true });
34101
+ rmSync2(directory, { recursive: true, force: true });
32607
34102
  } catch {}
32608
34103
  }
32609
34104
  });
32610
- var runGit = (args, options) => new Promise((resolvePromise, reject) => {
32611
- const env = { ...process.env, ...options.env, GIT_OPTIONAL_LOCKS: "0" };
32612
- if (options.stdin === undefined) {
32613
- execFile("git", args, { cwd: options.cwd, env, timeout: GIT_TIMEOUT_MS, maxBuffer: GIT_MAX_BUFFER }, (error, stdout) => error ? reject(error) : resolvePromise({ stdout: String(stdout) }));
32614
- return;
32615
- }
32616
- const child = spawn2("git", args, { cwd: options.cwd, env, timeout: GIT_TIMEOUT_MS });
32617
- let stdout = "";
32618
- let stdoutBytes = 0;
32619
- child.stdout.setEncoding("utf8");
32620
- child.stdout.on("data", (chunk) => {
32621
- stdoutBytes += chunk.length;
32622
- if (stdoutBytes <= GIT_MAX_BUFFER)
32623
- stdout += chunk;
34105
+ var runGit = async (args, options) => {
34106
+ const { stdout } = await runCommand("git", args, {
34107
+ cwd: options.cwd,
34108
+ env: { ...process.env, ...options.env, GIT_OPTIONAL_LOCKS: "0" },
34109
+ timeoutMs: GIT_TIMEOUT_MS,
34110
+ maxOutputBytes: GIT_MAX_BUFFER,
34111
+ ...options.stdin === undefined ? {} : { stdin: options.stdin }
32624
34112
  });
32625
- child.stderr.resume();
32626
- child.on("error", reject);
32627
- child.on("close", (code) => code === 0 ? resolvePromise({ stdout }) : reject(new Error(`git exited with ${code}`)));
32628
- child.stdin.on("error", () => {});
32629
- child.stdin.end(options.stdin);
32630
- });
34113
+ return { stdout };
34114
+ };
32631
34115
 
32632
34116
  class WorkspaceChangeProbe {
32633
34117
  git;
@@ -32871,8 +34355,8 @@ class WorkspaceChangeProbe {
32871
34355
  return;
32872
34356
  return {
32873
34357
  root,
32874
- indexPath: isAbsolute(index) ? index : resolve2(cwd, index),
32875
- objectsPath: isAbsolute(objects) ? objects : resolve2(cwd, objects)
34358
+ indexPath: isAbsolute3(index) ? index : resolve5(cwd, index),
34359
+ objectsPath: isAbsolute3(objects) ? objects : resolve5(cwd, objects)
32876
34360
  };
32877
34361
  }).catch(() => {
32878
34362
  return;
@@ -32915,8 +34399,8 @@ class WorkspaceChangeProbe {
32915
34399
  return;
32916
34400
  const { root, indexPath } = repo.location;
32917
34401
  const started = this.now();
32918
- const tempIndex = join4(this.tempDir, `orkestrator-probe-${randomUUID()}.index`);
32919
- const objectDirectory = await mkdtemp2(join4(this.tempDir, "orkestrator-probe-objects-"));
34402
+ const tempIndex = join6(this.tempDir, `orkestrator-probe-${randomUUID2()}.index`);
34403
+ const objectDirectory = await mkdtemp2(join6(this.tempDir, "orkestrator-probe-objects-"));
32920
34404
  temporaryObjectDirectories.add(objectDirectory);
32921
34405
  let retained = false;
32922
34406
  try {
@@ -32933,7 +34417,7 @@ class WorkspaceChangeProbe {
32933
34417
  const included = [];
32934
34418
  const skipped = new Map;
32935
34419
  for (const path of untracked) {
32936
- const stats = await lstat(join4(root, path)).catch(() => {
34420
+ const stats = await lstat2(join6(root, path)).catch(() => {
32937
34421
  return;
32938
34422
  });
32939
34423
  if (!stats)
@@ -33080,7 +34564,7 @@ function parseNumstatZ(output) {
33080
34564
 
33081
34565
  // ../../bridges/pi-bridge/src/change-evidence.ts
33082
34566
  import { existsSync } from "node:fs";
33083
- import { isAbsolute as isAbsolute2, relative } from "node:path";
34567
+ import { isAbsolute as isAbsolute4, relative as relative2 } from "node:path";
33084
34568
 
33085
34569
  // ../protocol/src/field-validation.ts
33086
34570
  function isPlainRecord(value) {
@@ -33483,10 +34967,10 @@ function workspaceObservationReportIssues(value) {
33483
34967
  }
33484
34968
 
33485
34969
  // ../protocol/src/node/change-tracking/evidence-spool.ts
33486
- import { createHash as createHash4, randomUUID as randomUUID2 } from "node:crypto";
33487
- import { readdirSync, readFileSync } from "node:fs";
34970
+ import { createHash as createHash5, randomUUID as randomUUID3 } from "node:crypto";
34971
+ import { readdirSync as readdirSync2, readFileSync as readFileSync2 } from "node:fs";
33488
34972
  import { appendFile as appendFile2, mkdir as mkdir3, rename as rename3, rm as rm3, writeFile as writeFile3 } from "node:fs/promises";
33489
- import { join as join5 } from "node:path";
34973
+ import { join as join7 } from "node:path";
33490
34974
  var DEFAULT_EVIDENCE_SPOOL_LIMITS = {
33491
34975
  maxEntries: 2048,
33492
34976
  maxEntryBytes: 256 * 1024,
@@ -33499,10 +34983,10 @@ var DEFAULT_EVIDENCE_SPOOL_LIMITS = {
33499
34983
  var ENTRIES_FILE = "entries.jsonl";
33500
34984
  var BODY_DIRECTORY = "bodies";
33501
34985
  function evidenceBodyId(bytes) {
33502
- return `sha256:${createHash4("sha256").update(bytes).digest("hex")}`;
34986
+ return `sha256:${createHash5("sha256").update(bytes).digest("hex")}`;
33503
34987
  }
33504
34988
  function stableEvidenceId(...parts) {
33505
- const hash = createHash4("sha256");
34989
+ const hash = createHash5("sha256");
33506
34990
  for (const part of parts)
33507
34991
  hash.update(`${part ?? ""}\x00`);
33508
34992
  return hash.digest("hex").slice(0, 40);
@@ -33529,7 +35013,7 @@ class ChangeEvidenceSpool {
33529
35013
  restoring = false;
33530
35014
  constructor(options = {}) {
33531
35015
  this.limits = { ...DEFAULT_EVIDENCE_SPOOL_LIMITS, ...options.limits };
33532
- this.runtimeEpoch = options.runtimeEpoch ?? randomUUID2();
35016
+ this.runtimeEpoch = options.runtimeEpoch ?? randomUUID3();
33533
35017
  this.directory = options.directory;
33534
35018
  if (this.directory) {
33535
35019
  this.restoring = true;
@@ -33632,7 +35116,7 @@ class ChangeEvidenceSpool {
33632
35116
  return;
33633
35117
  if (this.entries.length >= this.limits.maxEntries - 1)
33634
35118
  return;
33635
- const gapId = randomUUID2();
35119
+ const gapId = randomUUID3();
33636
35120
  const coverage = this.droppedUnknown ? {
33637
35121
  kind: "unknown-range",
33638
35122
  bindingId: this.gapBindingId || "unknown",
@@ -33749,7 +35233,7 @@ class ChangeEvidenceSpool {
33749
35233
  const lines = this.pendingLines.splice(0).join("");
33750
35234
  this.enqueueIo(async () => {
33751
35235
  await mkdir3(directory, { recursive: true, mode: 448 });
33752
- await appendFile2(join5(directory, ENTRIES_FILE), lines, { mode: 384 });
35236
+ await appendFile2(join7(directory, ENTRIES_FILE), lines, { mode: 384 });
33753
35237
  });
33754
35238
  }
33755
35239
  persistBody(id, bytes) {
@@ -33757,9 +35241,9 @@ class ChangeEvidenceSpool {
33757
35241
  if (!directory || this.restoring)
33758
35242
  return;
33759
35243
  this.enqueueIo(async () => {
33760
- const bodies = join5(directory, BODY_DIRECTORY);
35244
+ const bodies = join7(directory, BODY_DIRECTORY);
33761
35245
  await mkdir3(bodies, { recursive: true, mode: 448 });
33762
- await writeFile3(join5(bodies, bodyFileName(id)), bytes, { mode: 384, flag: "wx" }).catch((error) => {
35246
+ await writeFile3(join7(bodies, bodyFileName(id)), bytes, { mode: 384, flag: "wx" }).catch((error) => {
33763
35247
  if (error.code !== "EEXIST")
33764
35248
  throw error;
33765
35249
  });
@@ -33769,7 +35253,7 @@ class ChangeEvidenceSpool {
33769
35253
  const directory = this.directory;
33770
35254
  if (!directory)
33771
35255
  return;
33772
- this.enqueueIo(() => rm3(join5(directory, BODY_DIRECTORY, bodyFileName(id)), { force: true }));
35256
+ this.enqueueIo(() => rm3(join7(directory, BODY_DIRECTORY, bodyFileName(id)), { force: true }));
33773
35257
  }
33774
35258
  compactPersisted() {
33775
35259
  const directory = this.directory;
@@ -33780,7 +35264,7 @@ class ChangeEvidenceSpool {
33780
35264
  `);
33781
35265
  this.enqueueIo(async () => {
33782
35266
  await mkdir3(directory, { recursive: true, mode: 448 });
33783
- const file = join5(directory, ENTRIES_FILE);
35267
+ const file = join7(directory, ENTRIES_FILE);
33784
35268
  const temp = `${file}.${process.pid}.tmp`;
33785
35269
  await writeFile3(temp, body ? `${body}
33786
35270
  ` : "", { mode: 384 });
@@ -33792,10 +35276,10 @@ class ChangeEvidenceSpool {
33792
35276
  await this.io;
33793
35277
  }
33794
35278
  restore(directory) {
33795
- const bodyDirectory = join5(directory, BODY_DIRECTORY);
35279
+ const bodyDirectory = join7(directory, BODY_DIRECTORY);
33796
35280
  try {
33797
- for (const name of readdirSync(bodyDirectory)) {
33798
- const bytes = new Uint8Array(readFileSync(join5(bodyDirectory, name)));
35281
+ for (const name of readdirSync2(bodyDirectory)) {
35282
+ const bytes = new Uint8Array(readFileSync2(join7(bodyDirectory, name)));
33799
35283
  const id = evidenceBodyId(bytes);
33800
35284
  if (bodyFileName(id) !== name)
33801
35285
  continue;
@@ -33807,7 +35291,7 @@ class ChangeEvidenceSpool {
33807
35291
  } catch {}
33808
35292
  let text = "";
33809
35293
  try {
33810
- text = readFileSync(join5(directory, ENTRIES_FILE), "utf8");
35294
+ text = readFileSync2(join7(directory, ENTRIES_FILE), "utf8");
33811
35295
  } catch {
33812
35296
  return;
33813
35297
  }
@@ -34225,10 +35709,10 @@ function stringField(value, key) {
34225
35709
  function evidencePath(path) {
34226
35710
  if (!path)
34227
35711
  return;
34228
- if (!isAbsolute2(path))
35712
+ if (!isAbsolute4(path))
34229
35713
  return path;
34230
- const inside = relative(workingDirectory, path);
34231
- return inside && !inside.startsWith("..") && !isAbsolute2(inside) ? inside : path;
35714
+ const inside = relative2(workingDirectory, path);
35715
+ return inside && !inside.startsWith("..") && !isAbsolute4(inside) ? inside : path;
34232
35716
  }
34233
35717
  function writeReplacement(input, claim) {
34234
35718
  const path = evidencePath(stringField(input, "path"));
@@ -34496,9 +35980,9 @@ async function overlayCommandChanges(state, options = {}) {
34496
35980
  }
34497
35981
 
34498
35982
  // ../../bridges/pi-bridge/src/session-list-cache.ts
34499
- import { createHash as createHash5 } from "node:crypto";
35983
+ import { createHash as createHash6 } from "node:crypto";
34500
35984
  import { readdir, stat as stat2 } from "node:fs/promises";
34501
- import { join as join6 } from "node:path";
35985
+ import { join as join8 } from "node:path";
34502
35986
  var SESSION_LIST_CACHE_TTL_MS = 30000;
34503
35987
  var MAX_CACHED_SESSION_LIST_BYTES = 2 * 1024 * 1024;
34504
35988
  var cached2;
@@ -34509,10 +35993,10 @@ async function sessionFilesStamp(directory) {
34509
35993
  } catch {
34510
35994
  return;
34511
35995
  }
34512
- const stats = await Promise.all(names.map((name) => stat2(join6(directory, name)).catch(() => {
35996
+ const stats = await Promise.all(names.map((name) => stat2(join8(directory, name)).catch(() => {
34513
35997
  return;
34514
35998
  })));
34515
- const hash = createHash5("sha256");
35999
+ const hash = createHash6("sha256");
34516
36000
  for (const [index, name] of names.entries()) {
34517
36001
  const file = stats[index];
34518
36002
  hash.update(file ? `${name}\x00${file.size}\x00${file.mtimeMs}\x00${file.ctimeMs}\x00${file.ino}
@@ -34531,8 +36015,73 @@ function rememberSessionList(directory, stamp, entries) {
34531
36015
  cached2 = stamp !== undefined && encodedJsonBytes(entries) <= MAX_CACHED_SESSION_LIST_BYTES ? { directory, stamp, entries, expiresAt: performance.now() + SESSION_LIST_CACHE_TTL_MS } : undefined;
34532
36016
  }
34533
36017
 
36018
+ // ../../bridges/pi-bridge/src/compaction-controls.ts
36019
+ var AUTO_COMPACTION_PARAMETER_ID = "autoCompaction";
36020
+ var PI_AUTO_COMPACTION_DEFAULT = true;
36021
+ var COMPACTION_CANCELLED_MESSAGE = "Compaction was stopped before it finished; the conversation was not compacted.";
36022
+ function autoCompactionEnabled(state) {
36023
+ return state.autoCompaction ?? state.autoCompactionSetting ?? PI_AUTO_COMPACTION_DEFAULT;
36024
+ }
36025
+ function publicComposer(state) {
36026
+ const composer = state.composer;
36027
+ const parameter = {
36028
+ id: AUTO_COMPACTION_PARAMETER_ID,
36029
+ label: "Auto-compact",
36030
+ kind: "toggle",
36031
+ defaultValue: state.autoCompactionSetting ?? PI_AUTO_COMPACTION_DEFAULT,
36032
+ scope: "session"
36033
+ };
36034
+ return {
36035
+ ...composer,
36036
+ models: composer.models.map((model) => ({
36037
+ ...model,
36038
+ parameters: [
36039
+ ...(model.parameters ?? []).filter((entry) => entry.id !== AUTO_COMPACTION_PARAMETER_ID),
36040
+ parameter
36041
+ ]
36042
+ })),
36043
+ parameterValues: {
36044
+ ...composer.parameterValues,
36045
+ [AUTO_COMPACTION_PARAMETER_ID]: autoCompactionEnabled(state)
36046
+ }
36047
+ };
36048
+ }
36049
+ function parseAutoCompaction(parameterValues) {
36050
+ if (!parameterValues || typeof parameterValues !== "object" || Array.isArray(parameterValues)) {
36051
+ return;
36052
+ }
36053
+ const value = parameterValues[AUTO_COMPACTION_PARAMETER_ID];
36054
+ return typeof value === "boolean" ? value : undefined;
36055
+ }
36056
+ function installAutoCompactionOverride(settingsManager, choice) {
36057
+ const own = settingsManager.getCompactionEnabled.bind(settingsManager);
36058
+ const setting = own();
36059
+ settingsManager.getCompactionEnabled = () => choice() ?? own();
36060
+ return setting;
36061
+ }
36062
+ function readAutoCompactionSetting(read) {
36063
+ try {
36064
+ return read().getCompactionEnabled();
36065
+ } catch {
36066
+ return;
36067
+ }
36068
+ }
36069
+ function requestCompactionCancellation(state) {
36070
+ const compaction = state.manualCompaction;
36071
+ if (!compaction)
36072
+ return;
36073
+ compaction.cancelRequested = true;
36074
+ state.session?.abortCompaction();
36075
+ return compaction.settled;
36076
+ }
36077
+ function abortCancelledCompactionOnStart(state, event, session) {
36078
+ if (event.type === "compaction_start" && state.manualCompaction?.cancelRequested) {
36079
+ session.abortCompaction();
36080
+ }
36081
+ }
36082
+
34534
36083
  // ../../bridges/pi-bridge/src/agent-session.ts
34535
- var log3 = createLogger("bridge.pi");
36084
+ var log4 = createLogger("bridge.pi");
34536
36085
  var closingSessions = new WeakSet;
34537
36086
 
34538
36087
  class SessionClosingError extends Error {
@@ -34586,6 +36135,15 @@ function defaultModelIds(state, cwd = workingDirectory, agentDir = agentDirector
34586
36135
  ids.push(fallback);
34587
36136
  return ids;
34588
36137
  }
36138
+ function refreshAutoCompactionSetting(state) {
36139
+ const setting = readAutoCompactionSetting(() => SettingsManager.create(workingDirectory, agentDirectory() ?? getAgentDir(), {
36140
+ projectTrusted: piResourceLoaderPolicy(state).projectTrusted
36141
+ }));
36142
+ if (setting !== undefined && setting !== state.autoCompactionSetting) {
36143
+ state.autoCompactionSetting = setting;
36144
+ state.revision += 1;
36145
+ }
36146
+ }
34589
36147
  function adoptHydratedComposer(state, hydrated) {
34590
36148
  const current = state.composer;
34591
36149
  const selectedModelId = current.selectedModelId ?? hydrated.selectedModelId;
@@ -34613,6 +36171,7 @@ async function hydrateSessionComposer(state, options = {}) {
34613
36171
  const operation = (async () => {
34614
36172
  if (settled)
34615
36173
  await settled;
36174
+ refreshAutoCompactionSetting(state);
34616
36175
  const hydrated = await hydrateComposerForSession(state.composer, undefined, defaultModelIds(state));
34617
36176
  if (hydrated.models.length === 0) {
34618
36177
  composerHydrationRetryAfter.set(state, Date.now() + CATALOG_TIMEOUT_MS);
@@ -34681,6 +36240,7 @@ async function createSession(clientSessionKey, patch, policy) {
34681
36240
  if (resolved.id === "coordinator-read-only")
34682
36241
  state.readOnly = true;
34683
36242
  applyComposerPatch(state, patch);
36243
+ refreshAutoCompactionSetting(state);
34684
36244
  state.composer = await hydrateComposerForSession(state.composer, undefined, defaultModelIds(state));
34685
36245
  sessions.set(state.id, state);
34686
36246
  if (clientSessionKey)
@@ -34773,7 +36333,10 @@ async function createPiAgentSession(state) {
34773
36333
  sessionManager,
34774
36334
  sessionStartEvent
34775
36335
  }) => {
34776
- const settingsManager = SettingsManager.create(cwd, runtimeAgentDir);
36336
+ const settingsManager = SettingsManager.create(cwd, runtimeAgentDir, {
36337
+ projectTrusted: piResourceLoaderPolicy(state, cwd).projectTrusted
36338
+ });
36339
+ state.autoCompactionSetting = installAutoCompactionOverride(settingsManager, () => state.autoCompaction);
34777
36340
  const services = await createPiSessionServices(state, {
34778
36341
  cwd,
34779
36342
  agentDir: runtimeAgentDir,
@@ -34868,6 +36431,7 @@ function publishAttachedSession(state, session) {
34868
36431
  state.sessionFile = session.sessionFile;
34869
36432
  state.unsubscribe = session.subscribe((event) => {
34870
36433
  applySessionEvent(state, event);
36434
+ abortCancelledCompactionOnStart(state, event, session);
34871
36435
  if (event.type === "tool_execution_end") {
34872
36436
  discardToolCall(state, event.toolCallId, event.result);
34873
36437
  }
@@ -34967,9 +36531,9 @@ function projectResourceDiscoveryOptions(enabled = false, readOnly = false) {
34967
36531
  }
34968
36532
  function coordinatorProjectSkillPaths(cwd = workingDirectory) {
34969
36533
  return [
34970
- join7(cwd, ".pi", "skills"),
34971
- join7(cwd, ".agents", "skills"),
34972
- join7(cwd, ".claude", "skills")
36534
+ join9(cwd, ".pi", "skills"),
36535
+ join9(cwd, ".agents", "skills"),
36536
+ join9(cwd, ".claude", "skills")
34973
36537
  ].filter((path) => existsSync2(path));
34974
36538
  }
34975
36539
  function piResourceLoaderPolicy(state, cwd = workingDirectory) {
@@ -35066,12 +36630,12 @@ function sessionManagerFor(state) {
35066
36630
  state.resumeFallbackFile = undefined;
35067
36631
  if (!hasHistory && state.resumeFallbackFile !== state.sessionFile && (state.messages.length > 0 || state.promptSequence > 0)) {
35068
36632
  state.resumeFallbackFile = state.sessionFile;
35069
- log3.warn("session.resume-fell-back", { sessionId: state.id });
36633
+ log4.warn("session.resume-fell-back", { sessionId: state.id });
35070
36634
  appendResumeFallbackNotice(state);
35071
36635
  }
35072
36636
  return manager;
35073
36637
  } catch (error) {
35074
- log3.warn("session.resume-fell-back", {
36638
+ log4.warn("session.resume-fell-back", {
35075
36639
  sessionId: state.id,
35076
36640
  error: formatLogError(error, { message: false })
35077
36641
  });
@@ -35133,6 +36697,9 @@ function parseComposerPatch(body) {
35133
36697
  patch.reasoningId ??= body.effort.trim();
35134
36698
  if (typeof body.persistDefaults === "boolean")
35135
36699
  patch.persistDefaults = body.persistDefaults;
36700
+ const autoCompaction = parseAutoCompaction(body.parameterValues);
36701
+ if (autoCompaction !== undefined)
36702
+ patch.autoCompaction = autoCompaction;
35136
36703
  return Object.keys(patch).length > 0 ? patch : undefined;
35137
36704
  }
35138
36705
  function applyComposerPatch(state, patch) {
@@ -35152,6 +36719,10 @@ function applyComposerPatch(state, patch) {
35152
36719
  state.composer = { ...state.composer, selectedReasoningId: patch.reasoningId };
35153
36720
  changed = true;
35154
36721
  }
36722
+ if (patch.autoCompaction !== undefined && patch.autoCompaction !== state.autoCompaction) {
36723
+ state.autoCompaction = patch.autoCompaction;
36724
+ changed = true;
36725
+ }
35155
36726
  if (changed)
35156
36727
  state.revision += 1;
35157
36728
  return changed;
@@ -35201,7 +36772,7 @@ async function listResumableSessions() {
35201
36772
  read.abort();
35202
36773
  if (error instanceof TimeoutError)
35203
36774
  throw error;
35204
- log3.warn("session-list.failed", { error: formatLogError(error, { message: false }) });
36775
+ log4.warn("session-list.failed", { error: formatLogError(error, { message: false }) });
35205
36776
  return [];
35206
36777
  }
35207
36778
  }
@@ -35228,20 +36799,20 @@ async function readResumableSessions(signal) {
35228
36799
  return entries;
35229
36800
  }
35230
36801
  function resumableSessionRoot() {
35231
- return sessionDirectory() ?? join7(agentDirectory() ?? getAgentDir(), "sessions");
36802
+ return sessionDirectory() ?? join9(agentDirectory() ?? getAgentDir(), "sessions");
35232
36803
  }
35233
36804
  async function assertResumableSessionFile(sessionFile) {
35234
36805
  const root = resumableSessionRoot();
35235
- const requested = resolve3(root, sessionFile);
36806
+ const requested = resolve6(root, sessionFile);
35236
36807
  let real;
35237
36808
  let rootReal;
35238
36809
  try {
35239
- rootReal = await realpath(root);
35240
- real = await realpath(requested);
36810
+ rootReal = await realpath2(root);
36811
+ real = await realpath2(requested);
35241
36812
  } catch {
35242
36813
  throw new Error("That Pi session file does not exist");
35243
36814
  }
35244
- if (real !== rootReal && !real.startsWith(rootReal.endsWith(sep) ? rootReal : rootReal + sep)) {
36815
+ if (real !== rootReal && !real.startsWith(rootReal.endsWith(sep3) ? rootReal : rootReal + sep3)) {
35245
36816
  throw new Error("That Pi session file is outside this environment's session directory");
35246
36817
  }
35247
36818
  const info = await stat3(real).catch(() => {
@@ -35257,7 +36828,7 @@ async function resumeSession(sessionFile, patch, policy) {
35257
36828
  const ownedFile = existing.sessionFile;
35258
36829
  if (!ownedFile)
35259
36830
  continue;
35260
- const sameFile = ownedFile === resolved || ownedFile === sessionFile || await realpath(ownedFile).catch(() => {
36831
+ const sameFile = ownedFile === resolved || ownedFile === sessionFile || await realpath2(ownedFile).catch(() => {
35261
36832
  return;
35262
36833
  }) === resolved;
35263
36834
  if (sameFile) {
@@ -35286,6 +36857,7 @@ async function resumeSession(sessionFile, patch, policy) {
35286
36857
  state.policyPending = !policy;
35287
36858
  state.sessionFile = resolved;
35288
36859
  applyComposerPatch(state, patch);
36860
+ refreshAutoCompactionSetting(state);
35289
36861
  state.composer = await hydrateComposerForSession(state.composer, undefined, defaultModelIds(state));
35290
36862
  hydrateHistory(state);
35291
36863
  await overlayCommandChanges(state);
@@ -35413,7 +36985,7 @@ function hydrateHistory(state) {
35413
36985
  state.revision += 1;
35414
36986
  }
35415
36987
  function appendHistoricNotice(state, entry, part) {
35416
- const messageId = randomBytes7(12).toString("hex");
36988
+ const messageId = randomBytes8(12).toString("hex");
35417
36989
  pushMessage(state, "assistant", part.content, [{ ...part, sourcePartId: `${messageId}:0`, sourceMessageId: messageId }], entryCreatedAt(entry), messageId);
35418
36990
  }
35419
36991
  function entryCreatedAt(entry) {
@@ -35565,7 +37137,7 @@ function readContentText(content) {
35565
37137
  return chunks.join(`
35566
37138
  `);
35567
37139
  }
35568
- function pushMessage(state, role, content, parts, createdAt, messageId = randomBytes7(12).toString("hex")) {
37140
+ function pushMessage(state, role, content, parts, createdAt, messageId = randomBytes8(12).toString("hex")) {
35569
37141
  const message = {
35570
37142
  id: messageId,
35571
37143
  role,
@@ -35584,14 +37156,14 @@ function pushMessage(state, role, content, parts, createdAt, messageId = randomB
35584
37156
  chargeTranscript(state, Buffer.byteLength(JSON.stringify(message)));
35585
37157
  }
35586
37158
  // ../protocol/src/node/bridge-diagnostics.ts
35587
- import { createHash as createHash6 } from "node:crypto";
37159
+ import { createHash as createHash7 } from "node:crypto";
35588
37160
 
35589
37161
  // ../protocol/src/event-loop-stall-monitor.ts
35590
- var log4 = createLogger("event-loop");
37162
+ var log5 = createLogger("event-loop");
35591
37163
  var EVENT_LOOP_STALL_ALWAYS_LOG_MS = 1e4;
35592
37164
 
35593
37165
  // ../protocol/src/node/bridge-diagnostics.ts
35594
- var log5 = createLogger("bridge.diagnostics");
37166
+ var log6 = createLogger("bridge.diagnostics");
35595
37167
  var BRIDGE_DIAGNOSTICS_INTERVAL_MS = 60000;
35596
37168
  var INTERVAL_MS = BRIDGE_DIAGNOSTICS_INTERVAL_MS;
35597
37169
  var STALL_NO_DELTA_MS = 2 * INTERVAL_MS;
@@ -35683,7 +37255,7 @@ function sameSet(a, b) {
35683
37255
  function identity(value) {
35684
37256
  if (typeof value !== "string" || !value || value.length > MAX_ID_LENGTH)
35685
37257
  return;
35686
- return createHash6("sha256").update(value).digest("hex").slice(0, 16);
37258
+ return createHash7("sha256").update(value).digest("hex").slice(0, 16);
35687
37259
  }
35688
37260
  function readBridgeDebugFlag(value) {
35689
37261
  return value?.trim() === "1";
@@ -35756,16 +37328,16 @@ function safeDiagnosticMetrics(value) {
35756
37328
  return result;
35757
37329
  }
35758
37330
  function bridgeDiagnosticsChangesEnabled() {
35759
- return log5.isEnabled("trace");
37331
+ return log6.isEnabled("trace");
35760
37332
  }
35761
37333
  function writeBridgeDiagnostic({ bridge, event, payload }) {
35762
37334
  return tryWriteLog("info", "bridge.diagnostics", event, { bridge, payload });
35763
37335
  }
35764
37336
  function bridgeDiagnosticsActive() {
35765
- return log5.isEnabled("info");
37337
+ return log6.isEnabled("info");
35766
37338
  }
35767
37339
  function bridgeDiagnosticsStreamEnabled(bridge) {
35768
- return bridgeDebugEnabled(bridge) || log5.isEnabled("debug");
37340
+ return bridgeDebugEnabled(bridge) || log6.isEnabled("debug");
35769
37341
  }
35770
37342
  function writeDiagnostic(bridge, event, payload, write) {
35771
37343
  try {
@@ -36261,7 +37833,7 @@ var STRUCTURED_OUTPUT_FAILURE_CODES = new Set([
36261
37833
  ]);
36262
37834
 
36263
37835
  // ../../bridges/pi-bridge/src/prompt.ts
36264
- var log6 = createLogger("bridge.pi");
37836
+ var log7 = createLogger("bridge.pi");
36265
37837
  var STRUCTURED_PROMPT_INSTRUCTION_PREFIX = "End your turn with exactly one JSON value";
36266
37838
  function structuredPromptInstruction(schema) {
36267
37839
  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.
@@ -36472,7 +38044,7 @@ async function withinStartupDeadline(accepted, deadlineMs) {
36472
38044
  }
36473
38045
  }
36474
38046
  function abandonStartup(state, session, claim, accepted, settled, input, diagnostics, error, evidenceTurnId) {
36475
- log6.warn("turn.startup-timed-out", { sessionId: state.id });
38047
+ log7.warn("turn.startup-timed-out", { sessionId: state.id });
36476
38048
  state.status = "error";
36477
38049
  state.error = error.message;
36478
38050
  state.revision += 1;
@@ -36629,7 +38201,7 @@ function recordInterruptedOutput(state, input, message) {
36629
38201
  }
36630
38202
  function failTurn(state, session, error, input, abortedBeforeCleanup = state.turnAborted === true) {
36631
38203
  if (!abortedBeforeCleanup && state.turnCancelRequested !== true) {
36632
- log6.warn("turn.failed", {
38204
+ log7.warn("turn.failed", {
36633
38205
  sessionId: state.id,
36634
38206
  error: formatLogError(error, { message: false })
36635
38207
  });
@@ -36840,250 +38412,6 @@ function errorText(error) {
36840
38412
  function toImageContent(image) {
36841
38413
  return { type: "image", data: image.data, mimeType: image.mimeType };
36842
38414
  }
36843
- // ../../bridges/pi-bridge/src/prompt-attachments.ts
36844
- import { constants } from "node:fs";
36845
- import { lstat as lstat2, open as open2, realpath as realpath2 } from "node:fs/promises";
36846
- import { isAbsolute as isAbsolute3, join as join8, relative as relative2, resolve as resolve4, sep as sep2 } from "node:path";
36847
- class PromptAttachmentError extends Error {
36848
- code;
36849
- name = "PromptAttachmentError";
36850
- constructor(code, message) {
36851
- super(message);
36852
- this.code = code;
36853
- }
36854
- }
36855
- var MAX_IMAGE_ATTACHMENT_BYTES = 8 * 1024 * 1024;
36856
- var MAX_PROMPT_ATTACHMENTS = 20;
36857
- var MAX_TOTAL_IMAGE_ATTACHMENT_BYTES = 32 * 1024 * 1024;
36858
- var MAX_ATTACHMENT_PATH_BYTES = 4 * 1024;
36859
- var MAX_ATTACHMENT_FILENAME_BYTES = 1 * 1024;
36860
- var READ_CHUNK_BYTES = 64 * 1024;
36861
- function parsePromptAttachments(value) {
36862
- if (value === undefined || value === null)
36863
- return [];
36864
- if (!Array.isArray(value)) {
36865
- throw new PromptAttachmentError("attachment_invalid", "attachments must be an array");
36866
- }
36867
- if (value.length > MAX_PROMPT_ATTACHMENTS) {
36868
- throw new PromptAttachmentError("attachment_invalid", `A prompt can carry at most ${MAX_PROMPT_ATTACHMENTS} attachments`);
36869
- }
36870
- return value.map((candidate) => {
36871
- if (candidate === null || typeof candidate !== "object" || Array.isArray(candidate)) {
36872
- throw new PromptAttachmentError("attachment_invalid", "Each attachment must be an object");
36873
- }
36874
- const record = candidate;
36875
- if (record.type !== "image" && record.type !== "file") {
36876
- throw new PromptAttachmentError("attachment_invalid", "An attachment must be an image or a file");
36877
- }
36878
- const path = typeof record.path === "string" ? record.path.trim() : "";
36879
- if (!path || Buffer.byteLength(path) > MAX_ATTACHMENT_PATH_BYTES) {
36880
- throw new PromptAttachmentError("attachment_invalid", "Each attachment needs a workspace path");
36881
- }
36882
- if (path.includes("\x00")) {
36883
- throw new PromptAttachmentError("attachment_invalid", "An attachment path must not contain null bytes");
36884
- }
36885
- const filename = typeof record.filename === "string" && record.filename.trim() && Buffer.byteLength(record.filename) <= MAX_ATTACHMENT_FILENAME_BYTES ? record.filename : undefined;
36886
- return { type: record.type, path, ...filename ? { filename } : {} };
36887
- });
36888
- }
36889
- async function readPromptImages(attachments, workspaceRoot, modelResize) {
36890
- const images = [];
36891
- let totalBytes = 0;
36892
- for (const attachment of attachments) {
36893
- if (attachment.type !== "image")
36894
- continue;
36895
- const { bytes, absolutePath, mimeType } = await readWorkspaceImage(attachment.path, workspaceRoot);
36896
- totalBytes += bytes.length;
36897
- if (totalBytes > MAX_TOTAL_IMAGE_ATTACHMENT_BYTES) {
36898
- throw new PromptAttachmentError("attachment_too_large", "Image attachments exceed the 32MB total limit");
36899
- }
36900
- const normalized = await normalizeImageForPi(bytes, mimeType, modelResize);
36901
- images.push({
36902
- data: normalized.data,
36903
- mimeType: normalized.mimeType,
36904
- path: attachment.path,
36905
- absolutePath,
36906
- ...attachment.filename ? { filename: attachment.filename } : {}
36907
- });
36908
- }
36909
- return images;
36910
- }
36911
- async function normalizeImageForPi(bytes, mimeType, modelResize) {
36912
- const resized = await resizeImage(bytes, mimeType, {
36913
- ...modelResize,
36914
- maxBytes: Math.min(modelResize?.maxBytes ?? Infinity, MAX_IMAGE_ATTACHMENT_BYTES)
36915
- }).catch(() => null);
36916
- let normalized = resized ?? { data: bytes.toString("base64"), mimeType };
36917
- if (normalized.mimeType === "image/gif" || normalized.mimeType === "image/webp") {
36918
- normalized = await convertToPng(normalized.data, normalized.mimeType).catch(() => null) ?? normalized;
36919
- }
36920
- return { data: normalized.data, mimeType: normalized.mimeType };
36921
- }
36922
- function attachmentErrorForFsFailure(error) {
36923
- const code = error?.code;
36924
- if (code === "ELOOP") {
36925
- return new PromptAttachmentError("attachment_symlink_not_allowed", "Image attachments must be regular workspace files, not symbolic links");
36926
- }
36927
- return new PromptAttachmentError("attachment_read_failed", "Image attachment could not be read from the workspace");
36928
- }
36929
- var BRIDGE_ATTACHMENT_ROOT_ENV = "ORKESTRATOR_BRIDGE_ATTACHMENT_ROOT";
36930
- function configuredAttachmentRoot(env = process.env) {
36931
- const value = env[BRIDGE_ATTACHMENT_ROOT_ENV]?.trim();
36932
- return value && isAbsolute3(value) ? resolve4(value) : undefined;
36933
- }
36934
- function attachmentContainmentRoot(filePath, workspaceRoot, extraRoot = configuredAttachmentRoot()) {
36935
- if (extraRoot && isAbsolute3(filePath) && isPathWithin(extraRoot, resolve4(filePath))) {
36936
- return extraRoot;
36937
- }
36938
- return resolve4(workspaceRoot);
36939
- }
36940
- function isPathWithin(root, candidate) {
36941
- if (candidate === root)
36942
- return true;
36943
- const childPath = relative2(root, candidate);
36944
- return Boolean(childPath) && childPath !== ".." && !childPath.startsWith(`..${sep2}`) && !isAbsolute3(childPath);
36945
- }
36946
- async function assertNoSymlinkComponents(root, targetPath) {
36947
- let currentPath = root;
36948
- for (const segment of relative2(root, targetPath).split(sep2).filter(Boolean)) {
36949
- currentPath = join8(currentPath, segment);
36950
- const stats = await lstat2(currentPath).catch((error) => {
36951
- throw attachmentErrorForFsFailure(error);
36952
- });
36953
- if (stats.isSymbolicLink()) {
36954
- throw new PromptAttachmentError("attachment_symlink_not_allowed", "Image attachments must be regular workspace files, not symbolic links");
36955
- }
36956
- }
36957
- }
36958
- async function assertOpenedWorkspaceFile(targetPath, canonicalRoot, openedStats) {
36959
- const [pathStats, canonicalTarget] = await Promise.all([
36960
- lstat2(targetPath),
36961
- realpath2(targetPath)
36962
- ]).catch((error) => {
36963
- throw attachmentErrorForFsFailure(error);
36964
- });
36965
- if (pathStats.isSymbolicLink()) {
36966
- throw new PromptAttachmentError("attachment_symlink_not_allowed", "Image attachments must be regular workspace files, not symbolic links");
36967
- }
36968
- if (!pathStats.isFile() || !openedStats.isFile() || pathStats.dev !== openedStats.dev || pathStats.ino !== openedStats.ino) {
36969
- throw new PromptAttachmentError("attachment_not_regular_file", "Image attachment is not a stable regular workspace file");
36970
- }
36971
- if (!isPathWithin(canonicalRoot, canonicalTarget)) {
36972
- throw new PromptAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace");
36973
- }
36974
- }
36975
- function assertStableRead(initial, final, bytesRead) {
36976
- if (final.dev !== initial.dev || final.ino !== initial.ino || final.size !== initial.size || final.size !== bytesRead || final.mtimeMs !== initial.mtimeMs || final.ctimeMs !== initial.ctimeMs) {
36977
- throw new PromptAttachmentError("attachment_changed", "Image attachment changed while it was being read; attach it again");
36978
- }
36979
- }
36980
- async function readWorkspaceImage(filePath, workspaceRoot) {
36981
- const lexicalRoot = attachmentContainmentRoot(filePath, workspaceRoot);
36982
- const targetPath = isAbsolute3(filePath) ? resolve4(filePath) : resolve4(lexicalRoot, filePath);
36983
- if (!isPathWithin(lexicalRoot, targetPath)) {
36984
- throw new PromptAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace");
36985
- }
36986
- const canonicalRoot = await realpath2(lexicalRoot).catch((error) => {
36987
- throw attachmentErrorForFsFailure(error);
36988
- });
36989
- await assertNoSymlinkComponents(lexicalRoot, targetPath);
36990
- const canonicalTarget = await realpath2(targetPath).catch((error) => {
36991
- throw attachmentErrorForFsFailure(error);
36992
- });
36993
- if (!isPathWithin(canonicalRoot, canonicalTarget)) {
36994
- throw new PromptAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace");
36995
- }
36996
- const noFollow = constants.O_NOFOLLOW ?? 0;
36997
- const handle = await open2(targetPath, constants.O_RDONLY | noFollow).catch((error) => {
36998
- throw attachmentErrorForFsFailure(error);
36999
- });
37000
- try {
37001
- const initialStats = await handle.stat();
37002
- await assertOpenedWorkspaceFile(targetPath, canonicalRoot, initialStats);
37003
- if (initialStats.size > MAX_IMAGE_ATTACHMENT_BYTES) {
37004
- throw new PromptAttachmentError("attachment_too_large", "Image attachment exceeds the 8MB limit");
37005
- }
37006
- const mimeType = await detectSupportedImageMimeTypeFromFile(targetPath).catch(() => null);
37007
- if (!mimeType) {
37008
- throw new PromptAttachmentError("attachment_unsupported_format", "Image attachments must be PNG, JPEG, GIF, or WebP");
37009
- }
37010
- const chunks = [];
37011
- let totalBytes = 0;
37012
- while (totalBytes <= MAX_IMAGE_ATTACHMENT_BYTES) {
37013
- const remaining = MAX_IMAGE_ATTACHMENT_BYTES + 1 - totalBytes;
37014
- const chunk = Buffer.allocUnsafe(Math.min(READ_CHUNK_BYTES, remaining));
37015
- const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
37016
- if (bytesRead === 0)
37017
- break;
37018
- chunks.push(chunk.subarray(0, bytesRead));
37019
- totalBytes += bytesRead;
37020
- }
37021
- if (totalBytes > MAX_IMAGE_ATTACHMENT_BYTES) {
37022
- throw new PromptAttachmentError("attachment_too_large", "Image attachment exceeds the 8MB limit");
37023
- }
37024
- if (totalBytes === 0) {
37025
- throw new PromptAttachmentError("attachment_empty", "Image attachment file is empty");
37026
- }
37027
- const finalStats = await handle.stat();
37028
- await assertOpenedWorkspaceFile(targetPath, canonicalRoot, finalStats);
37029
- assertStableRead(initialStats, finalStats, totalBytes);
37030
- return { bytes: Buffer.concat(chunks, totalBytes), absolutePath: targetPath, mimeType };
37031
- } catch (error) {
37032
- if (error instanceof PromptAttachmentError)
37033
- throw error;
37034
- throw attachmentErrorForFsFailure(error);
37035
- } finally {
37036
- await handle.close();
37037
- }
37038
- }
37039
- async function resolvePromptFiles(attachments, workspaceRoot) {
37040
- const files = [];
37041
- for (const attachment of attachments) {
37042
- if (attachment.type !== "file")
37043
- continue;
37044
- const absolutePath = await resolveWorkspaceFile(attachment.path, workspaceRoot);
37045
- files.push({
37046
- path: attachment.path,
37047
- absolutePath,
37048
- ...attachment.filename ? { filename: attachment.filename } : {}
37049
- });
37050
- }
37051
- return files;
37052
- }
37053
- async function resolveWorkspaceFile(filePath, workspaceRoot) {
37054
- const lexicalRoot = attachmentContainmentRoot(filePath, workspaceRoot);
37055
- const targetPath = isAbsolute3(filePath) ? resolve4(filePath) : resolve4(lexicalRoot, filePath);
37056
- if (!isPathWithin(lexicalRoot, targetPath)) {
37057
- throw new PromptAttachmentError("attachment_outside_workspace", "A file attachment must be contained in the current workspace");
37058
- }
37059
- const canonicalRoot = await realpath2(lexicalRoot).catch((error) => {
37060
- throw attachmentErrorForFsFailure(error);
37061
- });
37062
- await assertNoSymlinkComponents(lexicalRoot, targetPath);
37063
- const canonicalTarget = await realpath2(targetPath).catch((error) => {
37064
- throw attachmentErrorForFsFailure(error);
37065
- });
37066
- if (!isPathWithin(canonicalRoot, canonicalTarget)) {
37067
- throw new PromptAttachmentError("attachment_outside_workspace", "A file attachment must be contained in the current workspace");
37068
- }
37069
- const stats = await lstat2(targetPath).catch((error) => {
37070
- throw attachmentErrorForFsFailure(error);
37071
- });
37072
- if (!stats.isFile()) {
37073
- throw new PromptAttachmentError("attachment_not_regular_file", "A file attachment must name a regular workspace file");
37074
- }
37075
- return targetPath;
37076
- }
37077
- function promptFileReferences(files) {
37078
- if (files.length === 0)
37079
- return "";
37080
- const lines = files.map((file) => file.filename && file.filename !== file.path ? `- ${file.absolutePath} (${file.filename})` : `- ${file.absolutePath}`);
37081
- return `
37082
-
37083
- Attached files:
37084
- ${lines.join(`
37085
- `)}`;
37086
- }
37087
38415
  // ../protocol/src/node/transcript-window.ts
37088
38416
  import { Buffer as Buffer4 } from "node:buffer";
37089
38417
  var DEFAULT_ENVELOPE_RESERVE_BYTES = 256;
@@ -37192,7 +38520,8 @@ function publicSession(state) {
37192
38520
  revision: state.revision,
37193
38521
  ...publicCommandRevision(state),
37194
38522
  sessionId: state.id,
37195
- composer: state.composer,
38523
+ composer: publicComposer(state),
38524
+ ...publicTurnActivity(state),
37196
38525
  ...state.policy ? { policy: piReportedPolicy(state.policy, state.readOnly) } : {},
37197
38526
  ...contextUsage ? { contextUsage } : {},
37198
38527
  runtime: publicRuntime(state)
@@ -37217,7 +38546,8 @@ function publicStatus(state, readiness) {
37217
38546
  ...publicCommandRevision(state),
37218
38547
  ...state.sessionFile ? { resumableSessionId: state.sessionFile } : {},
37219
38548
  ...state.title ? { title: state.title } : {},
37220
- composer: state.composer,
38549
+ composer: publicComposer(state),
38550
+ ...publicTurnActivity(state),
37221
38551
  ...state.policy ? { policy: piReportedPolicy(state.policy, state.readOnly) } : {},
37222
38552
  ...contextUsage ? { contextUsage } : {},
37223
38553
  runtime: publicRuntime(state),
@@ -37244,7 +38574,10 @@ function messageWindow(state, fromIndex, tailMessages = null) {
37244
38574
  };
37245
38575
  }
37246
38576
  function publicTurnError(state) {
37247
- return state.promptClaim !== undefined ? undefined : state.error;
38577
+ return state.promptClaim !== undefined || state.compacting ? undefined : state.error;
38578
+ }
38579
+ function publicTurnActivity(state) {
38580
+ return state.compacting ? { activity: "compacting" } : {};
37248
38581
  }
37249
38582
  function publicActivity(state) {
37250
38583
  if (sessionIsBlocked(state))
@@ -37373,6 +38706,7 @@ function effectiveLogLevel(detail, area) {
37373
38706
  return detail.level;
37374
38707
  }
37375
38708
  }
38709
+ var LOG_DETAIL_EXPIRY_MS = 24 * 60 * 60 * 1000;
37376
38710
  function logDetailEnablesBridgeDiagnostics(detail) {
37377
38711
  return LEVEL_DETAIL[effectiveLogLevel(detail, BRIDGE_DIAGNOSTICS_LOG_AREA)] >= LEVEL_DETAIL.debug;
37378
38712
  }
@@ -37543,7 +38877,7 @@ function humanPromptObservation(messages, tasks) {
37543
38877
  }
37544
38878
 
37545
38879
  // ../../bridges/pi-bridge/src/http.ts
37546
- import { createHash as createHash8, randomBytes as randomBytes8 } from "node:crypto";
38880
+ import { createHash as createHash9, randomBytes as randomBytes9 } from "node:crypto";
37547
38881
  import { pathToFileURL } from "node:url";
37548
38882
  import { gzip } from "node:zlib";
37549
38883
 
@@ -37600,7 +38934,7 @@ var DEFAULT_MCP_MANAGEMENT_ROLLOUT = Object.freeze({
37600
38934
 
37601
38935
  // ../protocol/src/node/bridge-transcript-summary.ts
37602
38936
  import { Buffer as Buffer5 } from "node:buffer";
37603
- import { createHash as createHash7 } from "node:crypto";
38937
+ import { createHash as createHash8 } from "node:crypto";
37604
38938
 
37605
38939
  // ../protocol/src/node/progressive-transcript.ts
37606
38940
  var BRIDGE_TRANSCRIPT_MAX_MESSAGES = 100;
@@ -37766,7 +39100,7 @@ function digestPayload(payload) {
37766
39100
  const serialized = JSON.stringify(payload);
37767
39101
  return {
37768
39102
  bytes: Buffer5.byteLength(serialized),
37769
- digest: createHash7("sha256").update(serialized).digest("base64url").slice(0, 32)
39103
+ digest: createHash8("sha256").update(serialized).digest("base64url").slice(0, 32)
37770
39104
  };
37771
39105
  }
37772
39106
  function topLevelKey(part, index) {
@@ -38487,7 +39821,7 @@ async function answerSessionActivityBatch(body, read, options = {}) {
38487
39821
  }
38488
39822
 
38489
39823
  // ../../bridges/pi-bridge/src/http.ts
38490
- var log7 = createLogger("bridge.pi");
39824
+ var log8 = createLogger("bridge.pi");
38491
39825
 
38492
39826
  class HttpError extends Error {
38493
39827
  status;
@@ -38518,7 +39852,7 @@ function assertSessionOpen(state) {
38518
39852
  var GLOBAL_REFRESH_CONCURRENCY = 4;
38519
39853
  var DEFAULT_DELETE_CANCEL_TIMEOUT_MS = 5000;
38520
39854
  var DEFAULT_CANCEL_ACK_TIMEOUT_MS = 5000;
38521
- var TRANSCRIPT_GENERATION = randomBytes8(16).toString("hex");
39855
+ var TRANSCRIPT_GENERATION = randomBytes9(16).toString("hex");
38522
39856
  var deleteCancelTimeoutMs = DEFAULT_DELETE_CANCEL_TIMEOUT_MS;
38523
39857
  var cancelAckTimeoutMs = DEFAULT_CANCEL_ACK_TIMEOUT_MS;
38524
39858
  function setDeleteCancelTimeoutForTests(timeoutMs) {
@@ -38541,6 +39875,9 @@ async function route(request, response, clientSignal) {
38541
39875
  })) {
38542
39876
  return json(response, 401, { error: "Unauthorized" });
38543
39877
  }
39878
+ const refused = await admitNodeBridgeRequest(bridgeAuthority, request, MAX_BODY_BYTES);
39879
+ if (refused)
39880
+ return json(response, refused.status, refused.body);
38544
39881
  try {
38545
39882
  if (url.pathname === SESSION_ACTIVITY_BATCH_PATH && request.method === "POST") {
38546
39883
  const answer = await answerSessionActivityBatch(request, sessionActivityObservation, {
@@ -38560,7 +39897,7 @@ async function route(request, response, clientSignal) {
38560
39897
  if (error instanceof HttpError)
38561
39898
  return json(response, error.status, { error: error.message });
38562
39899
  if (error instanceof PolicyWideningRefusedError) {
38563
- log7.warn("session.policy-widening-refused", { widened: error.widened.join(",") });
39900
+ log8.warn("session.policy-widening-refused", { widened: error.widened.join(",") });
38564
39901
  return json(response, 403, error.refusal());
38565
39902
  }
38566
39903
  if (error instanceof SessionBusyError)
@@ -38577,7 +39914,7 @@ async function route(request, response, clientSignal) {
38577
39914
  if (error instanceof PromptAttachmentError) {
38578
39915
  return json(response, 400, { error: error.message });
38579
39916
  }
38580
- log7.error("http.route-failed");
39917
+ log8.error("http.route-failed");
38581
39918
  return json(response, 500, { error: "Internal bridge error" });
38582
39919
  }
38583
39920
  }
@@ -38802,7 +40139,7 @@ async function routeSession(request, response, url, clientSignal) {
38802
40139
  return json(response, 200, { servers: publicPiMcpServers(state) });
38803
40140
  }
38804
40141
  if (action === "config" && request.method === "GET") {
38805
- return json(response, 200, { ...state.composer, commands: state.slashCommands });
40142
+ return json(response, 200, { ...publicComposer(state), commands: state.slashCommands });
38806
40143
  }
38807
40144
  if (action === "config" && request.method === "POST") {
38808
40145
  return await handleConfig(request, response, state);
@@ -38911,7 +40248,7 @@ async function handleConfig(request, response, state) {
38911
40248
  }
38912
40249
  const patch = parseComposerPatch(body);
38913
40250
  if (!patch)
38914
- return json(response, 200, { ...state.composer, commands: state.slashCommands });
40251
+ return json(response, 200, { ...publicComposer(state), commands: state.slashCommands });
38915
40252
  state.dispatching = true;
38916
40253
  try {
38917
40254
  if (applyComposerPatch(state, patch)) {
@@ -38921,7 +40258,7 @@ async function handleConfig(request, response, state) {
38921
40258
  } finally {
38922
40259
  state.dispatching = false;
38923
40260
  }
38924
- return json(response, 200, { ...state.composer, commands: state.slashCommands });
40261
+ return json(response, 200, { ...publicComposer(state), commands: state.slashCommands });
38925
40262
  }
38926
40263
  async function handleCancel(response, state) {
38927
40264
  const { claim, cancel } = requestTurnCancellation(state, "The turn was cancelled before this tool call was approved.");
@@ -38932,6 +40269,13 @@ async function handleCancel(response, state) {
38932
40269
  if (claim !== undefined) {
38933
40270
  return json(response, 202, { cancelled: false, pending: true });
38934
40271
  }
40272
+ const compaction = requestCompactionCancellation(state);
40273
+ if (compaction) {
40274
+ const outcome = await withTimeout(compaction.then((stopped) => stopped ? "stopped" : "finished"), cancelAckTimeoutMs, "Pi compaction cancellation is still in flight").catch(() => "pending");
40275
+ if (outcome === "pending")
40276
+ return json(response, 202, { cancelled: false, pending: true });
40277
+ return json(response, 200, { cancelled: outcome === "stopped" });
40278
+ }
38935
40279
  return json(response, 200, { cancelled: false });
38936
40280
  }
38937
40281
  async function handleCompact(request, response, state) {
@@ -38942,6 +40286,17 @@ async function handleCompact(request, response, state) {
38942
40286
  state.dispatching = true;
38943
40287
  state.compacting = true;
38944
40288
  state.revision += 1;
40289
+ let settle = () => {
40290
+ return;
40291
+ };
40292
+ const compaction = {
40293
+ cancelRequested: false,
40294
+ settled: new Promise((resolve) => {
40295
+ settle = resolve;
40296
+ })
40297
+ };
40298
+ state.manualCompaction = compaction;
40299
+ let stopped = false;
38945
40300
  let instructions;
38946
40301
  try {
38947
40302
  const parsed = parseCompactInstructionsBody(await readJsonValue(request));
@@ -38949,8 +40304,21 @@ async function handleCompact(request, response, state) {
38949
40304
  throw new HttpError(400, parsed.error);
38950
40305
  instructions = parsed.instructions;
38951
40306
  const session = await ensureSession(state);
38952
- await session.compact(instructions);
40307
+ if (compaction.cancelRequested)
40308
+ stopped = true;
40309
+ else {
40310
+ try {
40311
+ await session.compact(instructions);
40312
+ } catch (error) {
40313
+ if (!compaction.cancelRequested)
40314
+ throw error;
40315
+ stopped = true;
40316
+ }
40317
+ }
38953
40318
  } finally {
40319
+ if (state.manualCompaction === compaction)
40320
+ state.manualCompaction = undefined;
40321
+ settle(stopped);
38954
40322
  state.compacting = false;
38955
40323
  state.dispatching = false;
38956
40324
  state.revision += 1;
@@ -38959,6 +40327,9 @@ async function handleCompact(request, response, state) {
38959
40327
  return;
38960
40328
  });
38961
40329
  }
40330
+ if (stopped) {
40331
+ return json(response, 409, { error: COMPACTION_CANCELLED_MESSAGE, cancelled: true });
40332
+ }
38962
40333
  return json(response, 200, instructions ? { compacted: true, instructions: "applied" } : { compacted: true });
38963
40334
  }
38964
40335
  async function handleSteer(request, response, state) {
@@ -38978,7 +40349,7 @@ async function handleSteer(request, response, state) {
38978
40349
  throw new HttpError(400, "requestId is required");
38979
40350
  if (!expectedRunId)
38980
40351
  throw new HttpError(400, "expectedRunId is required");
38981
- const inputDigest = createHash8("sha256").update(text).digest("hex");
40352
+ const inputDigest = createHash9("sha256").update(text).digest("hex");
38982
40353
  const previous = state.steerJournal.get(requestId);
38983
40354
  if (previous) {
38984
40355
  if (previous.inputDigest !== inputDigest || previous.expectedRunId !== expectedRunId) {
@@ -39344,7 +40715,7 @@ async function handleAdmittedPrompt(request, response, state, clientSignal, admi
39344
40715
  });
39345
40716
  }
39346
40717
  if (error instanceof PromptRefusedError && !cancelRequestedFor(state, claim)) {
39347
- log7.warn("turn.refused", {
40718
+ log8.warn("turn.refused", {
39348
40719
  sessionId: state.id,
39349
40720
  error: formatLogError(error, { message: false })
39350
40721
  });
@@ -39411,7 +40782,7 @@ function appendLocalExchange(state, prompt, reply, requestId, kind) {
39411
40782
  if (userId && state.messages.some((message) => message.id === userId))
39412
40783
  return;
39413
40784
  appendUserMessage(state, prompt, [], [], userId);
39414
- const messageId = requestId ? `${kind}-reply:${requestId}` : randomBytes8(12).toString("hex");
40785
+ const messageId = requestId ? `${kind}-reply:${requestId}` : randomBytes9(12).toString("hex");
39415
40786
  state.messages.push({
39416
40787
  id: messageId,
39417
40788
  role: "assistant",
@@ -39428,7 +40799,7 @@ function appendLocalExchange(state, prompt, reply, requestId, kind) {
39428
40799
  });
39429
40800
  chargeTranscript(state, Buffer.byteLength(reply));
39430
40801
  }
39431
- function appendUserMessage(state, prompt, images, files, messageId = randomBytes8(12).toString("hex")) {
40802
+ function appendUserMessage(state, prompt, images, files, messageId = randomBytes9(12).toString("hex")) {
39432
40803
  const attachments = [...images, ...files];
39433
40804
  state.messages.push({
39434
40805
  id: messageId,
@@ -39484,9 +40855,10 @@ async function readJson(request) {
39484
40855
  return isObject(parsed) ? parsed : {};
39485
40856
  }
39486
40857
  async function readJsonValue(request) {
39487
- const chunks = [];
39488
- let total = 0;
39489
- for await (const chunk of request) {
40858
+ const admitted = takeAdmittedBody(request);
40859
+ const chunks = admitted ? [admitted] : [];
40860
+ let total = admitted?.length ?? 0;
40861
+ for await (const chunk of admitted ? [] : request) {
39490
40862
  const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
39491
40863
  total += buffer.length;
39492
40864
  if (total > MAX_BODY_BYTES)
@@ -39604,7 +40976,7 @@ function startParentWatchdog(options) {
39604
40976
  }
39605
40977
 
39606
40978
  // ../protocol/src/bridge-lifecycle.ts
39607
- var log8 = createLogger("bridge.lifecycle");
40979
+ var log9 = createLogger("bridge.lifecycle");
39608
40980
  var TERMINATION_SIGNALS = ["SIGTERM", "SIGINT"];
39609
40981
  function errorKind(error) {
39610
40982
  if (error instanceof Error)
@@ -39658,7 +41030,7 @@ class BridgeLifecycle {
39658
41030
  }
39659
41031
  requestExit() {
39660
41032
  this.#exit ??= this.shutdown().then(() => this.#options.exit(0), (error) => {
39661
- log8.error("shutdown.failed", {
41033
+ log9.error("shutdown.failed", {
39662
41034
  bridge: this.#options.label,
39663
41035
  errorClass: errorKind(error)
39664
41036
  });
@@ -39675,7 +41047,7 @@ class BridgeLifecycle {
39675
41047
  try {
39676
41048
  idleSweep.run();
39677
41049
  } catch (error) {
39678
- log8.warn("idle-sweep.failed", {
41050
+ log9.warn("idle-sweep.failed", {
39679
41051
  bridge: this.#options.label,
39680
41052
  errorClass: errorKind(error)
39681
41053
  });
@@ -39946,9 +41318,9 @@ function installFatalRejectionGuard(options) {
39946
41318
  }
39947
41319
 
39948
41320
  // ../protocol/src/node/process-failure-log.ts
39949
- var log9 = createLogger("process");
41321
+ var log10 = createLogger("process");
39950
41322
  function logUnhandledRejection(reason) {
39951
- log9.throttled("error", "rejection.unhandled", {
41323
+ log10.throttled("error", "rejection.unhandled", {
39952
41324
  error: reason,
39953
41325
  fields: () => ({ error: formatLogError(reason, { message: false }) })
39954
41326
  });
@@ -40030,6 +41402,7 @@ export {
40030
41402
  boundTranscript,
40031
41403
  boundTranscriptDuringStreaming,
40032
41404
  boundTranscriptForRead,
41405
+ bridgeAuthority,
40033
41406
  bridgeGeneration,
40034
41407
  cancelRequestedFor,
40035
41408
  catalogReadFailed,