orkestrator 2.37.3-beta → 2.37.4-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.
@@ -691,12 +691,22 @@ var DESKTOP_LOG_AREAS = defineLogAreas({
691
691
  denied: "A renderer asked for a permission the policy does not grant."
692
692
  }
693
693
  },
694
+ "desktop.webrequest": {
695
+ description: "Main-process webRequest listeners on Electron sessions. Listener names only; never a URL, header or error message.",
696
+ events: {
697
+ "listener.failed-closed": "A listener's decision threw or rejected, so it answered with its fail-closed response.",
698
+ "observer.failed": "A listener with no callback (a redirect observer) threw; its fallback ran.",
699
+ "callback.failed": "Electron's webRequest callback threw while a listener answered.",
700
+ ...THROTTLE_LOG_EVENTS
701
+ }
702
+ },
694
703
  "desktop.dialog": {
695
704
  description: "Native dialogs, whose modal loops hold the main thread while they are open.",
696
705
  events: {
697
706
  "attention-failed": "A dialog could not ask for the user's attention.",
698
707
  closed: "A native dialog closed.",
699
708
  "hidden-cancelled": "A hidden profile cancelled a dialog without opening native UI.",
709
+ "no-display-cancelled": "A headless Electron with no display cancelled a dialog instead of opening native UI.",
700
710
  "open-failed": "A dialog could not open; it was answered as cancelled.",
701
711
  opening: "A native dialog is opening.",
702
712
  "preview-beforeunload-ignored": "A browser preview's beforeunload handler was ignored.",
@@ -1052,6 +1062,7 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
1052
1062
  "agent-tools.unavailable": "OpenCode agent tools remain unavailable for a session.",
1053
1063
  "coordinator-servers.unavailable": "OpenCode coordinator research servers are unavailable.",
1054
1064
  "monitor.reconnecting": "The request monitor lost its stream and is reconnecting. Error class only.",
1065
+ "monitor.silent": "The request monitor's stream stopped heartbeating, so it is replaced. `silenceMs` only.",
1055
1066
  "worker-limit.reached": "The bounded request workers are full, so the stream restarts and a snapshot reconciles.",
1056
1067
  "request.failed": "Handling a request event failed, so the stream restarts. Error class only.",
1057
1068
  "credential-plugin.skipped": "A host OpenCode server started without the credential plugin, so its tools inherit its password; `reason` says why.",
@@ -1074,6 +1085,7 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
1074
1085
  "host-server.terminate-failed": "A 2.x server that did not become ready could not be stopped; its process entry is kept for shutdown. Error class only.",
1075
1086
  "container-server.launched": "The start script of a container environment's 2.x server was run. Container port only.",
1076
1087
  "container-server.ready": "A container environment's 2.x server this backend started answered `/api/info` as 2.x. Environment id only.",
1088
+ "container-server.cleanup-failed": "Cleanup after OpenCode startup failed; step names only, while the original startup error is preserved.",
1077
1089
  "container-server.warm-incomplete": "The first workspace request to a container's new 2.x server failed, so its plugins load on the next one. Error class only.",
1078
1090
  "resume-list.unavailable": "The 2.x sessions could not be listed for the resume picker, so it shows the 1.x list alone. Error class only.",
1079
1091
  "credential.mirrored": "A provider sign-in change was copied into the 2.x database. `outcome` (written, removed, unchanged, skipped) only; never a provider id or value.",
@@ -1308,6 +1320,7 @@ var TMUX_LOG_AREAS = defineLogAreas({
1308
1320
  "cleanup.skipped": "Environment tmux cleanup was skipped because tmux could not be reached and nothing required it.",
1309
1321
  "cleanup.environments-load-failed": "Environments could not be loaded during tmux cleanup, so it stays incomplete.",
1310
1322
  "cleanup.kill-failed": "An environment's tmux sessions could not be killed.",
1323
+ "cleanup.kill-incomplete": "An environment's tmux sessions could not all be shown gone (a session survived, or the socket was unreachable while another tmux process might own it), so cleanup stays incomplete.",
1311
1324
  "hooks.uninstall-failed": "Workspace hooks could not be uninstalled.",
1312
1325
  "hooks.git-exclude-failed": "The git exclude for Claude's local settings could not be set.",
1313
1326
  "naming.prepare-failed": "First-prompt naming could not be prepared; the prompt still goes ahead.",
@@ -1437,6 +1450,7 @@ var STORAGE_LOG_AREAS = defineLogAreas({
1437
1450
  "config.restrict-mode-failed": "A config file holding provider secrets could not be set to owner-only; the backend carries on.",
1438
1451
  "legacy-json.moved": "JSON store files written after the SQLite migration were archived, not imported.",
1439
1452
  "legacy-json.archive-failed": "Imported JSON store files could not be archived.",
1453
+ "native-session-owners.backfill-failed": "Native-session rows could not be given their environment as owner at open; an environment delete then parses those rows instead, and the next open retries.",
1440
1454
  "lease.timed-out": "A waiter gave up on a lease; `lease` and `family` name it, `holderAgeMs` is the time since its holder's last heartbeat (null when the holder had just gone), `waitedMs` how long the waiter waited.",
1441
1455
  "lease.heartbeat-failed": "A held lease's heartbeat failed, which shortens the lease; the next one retries.",
1442
1456
  "scrub.vacuum-failed": "Deleted-content page reclamation failed; the checkpoint is attempted independently.",
@@ -1486,6 +1500,7 @@ var BUILD_PIPELINE_LOG_AREAS = defineLogAreas({
1486
1500
  "transcripts.maintenance-failed": "Migrating or sweeping stage transcripts failed; the next start retries.",
1487
1501
  "restore.skipped": "A pipeline could not be restored at startup and was skipped.",
1488
1502
  "criteria.record-failed": "Acceptance criteria results could not be recorded on the ticket.",
1503
+ "completion-notes.publish-failed": "A finished pipeline's notes tab could not be added to the layout; the run stays complete.",
1489
1504
  "workspace.waiting": "A pipeline is waiting for its workspace; written once per reason.",
1490
1505
  "rewind.pending": "A pipeline's code rewind has not finished; written once per reason.",
1491
1506
  "kanban.status-failed": "A restarted pipeline's Kanban status could not be set; it retries shortly.",
@@ -1527,6 +1542,8 @@ var CHANGE_TRACKING_LOG_AREAS = defineLogAreas({
1527
1542
  "dispatch.record-failed": "Recording a turn's dispatch outcome failed.",
1528
1543
  "turn.finalize-failed": "Finalizing a turn failed.",
1529
1544
  "turn.settle-failed": "Settling a late interrupted turn failed.",
1545
+ "turn.end-recovery": "A background retry of a turn end capture that timed out finished: recovered, done (no longer eligible) or exhausted.",
1546
+ "turn.end-recovery-failed": "A background retry of a turn end capture threw; it counts as a failed attempt.",
1530
1547
  "evidence.pull-failed": "Pulling change evidence from a bridge failed; a later pull retries.",
1531
1548
  "measurement.failed": "Recomputing a tool's measurement failed."
1532
1549
  }
@@ -1595,6 +1612,7 @@ var COORDINATOR_LOG_AREAS = defineLogAreas({
1595
1612
  "node-release.no-coordinator": "Work closed on a released node belonged to a coordinator that no longer exists, so nobody was told.",
1596
1613
  "node-offline.notice-failed": "The notice that a node has been unreachable for a day could not be sent; the next failed read retries.",
1597
1614
  "node-offline.check-failed": "Whether a long-unreachable node's coordinators were told could not be checked; the next read retries.",
1615
+ "node-reconnect.notice-failed": "The message that a node a coordinator tried while it was disconnected is back could not be sent; it is not retried, since the coordinator already holds the refusal.",
1598
1616
  "checkout.merge-followed": "After an environment's PR merged, the project checkout was fast-forwarded, or `outcome` says why not.",
1599
1617
  "checkout.merge-follow-failed": "Fast-forwarding the project checkout failed, after an environment's PR merged or before mail woke the main coordinator.",
1600
1618
  "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`).",
@@ -1647,7 +1665,8 @@ var REVIEW_LOG_AREAS = defineLogAreas({
1647
1665
  "monitor.task-store-failed": "A pull request could not be recorded on its Kanban task.",
1648
1666
  "monitor.merged-tickets-closed": "The startup sweep moved Kanban tickets whose pull request had merged to done (`count`).",
1649
1667
  "monitor.merged-tickets-close-failed": "The startup sweep closing Kanban tickets whose pull request merged failed; the next backend start retries.",
1650
- "monitor.emit-failed": "A pull request monitor event could not be emitted to its sink."
1668
+ "monitor.emit-failed": "A pull request monitor event could not be emitted to its sink.",
1669
+ "branch-cleanup.kept": "A merge or cleanup kept a pull request's head branch because it is not the branch created for the environment (`reason`)."
1651
1670
  }
1652
1671
  }
1653
1672
  });
@@ -1679,6 +1698,8 @@ var AGENT_ACCOUNTS_LOG_AREAS = defineLogAreas({
1679
1698
  "kept-note.failed": "Recording why a limit stop found no account to move to failed; the stop stands.",
1680
1699
  "container-sync.failed": "Handing a login or account to a container failed; `step` says which part.",
1681
1700
  "last-usage.save-failed": "The last plan usage reading could not be saved; the next save retries.",
1701
+ "shared-usage.save-failed": "The shared usage readings could not be saved; they stay in memory and the next reading saves them.",
1702
+ "shared-usage.record-failed": "A fresh usage reading could not be kept for sharing with other machines; the account's own reading stands.",
1682
1703
  "login-cleanup.failed": "A temporary login could not be cleaned up.",
1683
1704
  "login-renewal.failed": "Renewing an idle account's sign-in to read its usage failed; it is retried after a backoff.",
1684
1705
  "login-renewal.not-extended": "Claude Code ran to renew an idle account's sign-in, but its token is still lapsed.",
@@ -1696,6 +1717,7 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1696
1717
  "git-mirror.mount-unavailable": "A new container gets no project Git mirror, so its clone goes to the remote.",
1697
1718
  "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.",
1698
1719
  "git-mirror.refreshed": "A project's Git mirror was built or updated.",
1720
+ "git-mirror.access-changed": "A project's Git mirror was withdrawn because containers are now given a different credential (another access kind, or a token acting as another or an unreadable account), so no reader keeps what it could not fetch itself.",
1699
1721
  "git-mirror.seeded": "A project's Git mirror was built from its host checkout and only what the remote added to it.",
1700
1722
  "git-mirror.seed-skipped": "A project's host checkout could not seed its Git mirror, so the build downloads everything.",
1701
1723
  "git-mirror.refresh-failed": "A project's Git mirror could not be updated. New clones still work, from the mirror as it was or from the remote.",
@@ -1709,6 +1731,9 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1709
1731
  "git-mirror.clone-fallback": "A new environment could not clone from its project's Git mirror and cloned from the remote.",
1710
1732
  "project-seed.refused": "A project .env, .env.local or opencode.json was not copied into a new container: a link, not a regular file, outside the project, too large or unreadable.",
1711
1733
  "opencode.warm-incomplete": "OpenCode did not finish loading /workspace in a container.",
1734
+ "opencode.listener-replaced": "The process on a container's OpenCode port (`provider`: `opencode` or `opencode2`) is not the server the backend launched and recorded, so its password was withheld and the next start replaces it. `stage` is `request` when the re-check after a refused connection or an unexpected answer found it (to-do 7550); that connection then sends nothing more.",
1735
+ "opencode.project-config-too-large": "A checkout's opencode.json or opencode.jsonc was larger than the limit, so a launched OpenCode server does not read it. File name only.",
1736
+ "opencode.project-config-filtered": "Values were left out of a checkout's OpenCode configuration before a launched server reads it (to-do 7550): counts of plugin keys, `{env:}` and `{file:}` references and dropped instructions (including separate instructionGlob and instructionUrl counts), and the names of files that were not a JSONC object. Never values.",
1712
1737
  "log-driver.unbounded": "The Docker daemon offers neither the local nor the json-file log driver, so new containers keep its default driver, whose log may be uncapped. Written once per backend.",
1713
1738
  "lifecycle-event.reconcile-failed": "Reconciling an environment after a container start or stop event failed; the next status read retries.",
1714
1739
  "login-keeper.pass-failed": "A Claude login keeper pass failed; the next interval retries.",
@@ -1743,6 +1768,17 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1743
1768
  description: "A bridge process was launched in a container, for the first time there or as a relaunch; `provider` names it. A relaunch keeps the run before it in the previous log.",
1744
1769
  essential: true,
1745
1770
  fields: { provider: "label", containerPort: "number" }
1771
+ },
1772
+ "bridge.listener-refused": {
1773
+ description: "The socket listening on a container bridge's port is not the one the bridge the backend started opened (to-do 7250), so its token is not handed out and the next start replaces it. `reason` is a fixed label: `different-socket`, `several-sockets`, `pending` (a start has not recorded its bridge yet, or failed before it did) or `scan-incomplete`.",
1774
+ essential: true,
1775
+ fields: { provider: "label", reason: "label" }
1776
+ },
1777
+ "bridge.listener-adopted": "A running container bridge had no listener record, because a backend from before the record started it, so the socket on its port was recorded as the bridge's; `provider` names it.",
1778
+ "bridge.listener-unrecorded": {
1779
+ description: "A bridge the backend just launched could not be recorded as its port's listener, for the fixed `reason` given (`no-listener`, `several-sockets`, `launch-exited` or `scan-incomplete`); what listens on the port is stopped and the start fails.",
1780
+ essential: true,
1781
+ fields: { provider: "label", reason: "label" }
1746
1782
  }
1747
1783
  }
1748
1784
  },
@@ -1797,7 +1833,8 @@ var MCP_LOG_AREAS = defineLogAreas({
1797
1833
  "listener.port-free": "The Control MCP's fixed port is free again, so it is listening.",
1798
1834
  "state-listener.failed": "A Control MCP state listener threw; the others still run.",
1799
1835
  "delegation.remote-open-failed": "A delegation could not be opened on another node.",
1800
- "delegation.open-failed": "A coordinator delegation could not be opened."
1836
+ "delegation.open-failed": "A coordinator delegation could not be opened.",
1837
+ "delegation.turn-origin-unreadable": "A coordinator's last turn origin could not be read, so its delegated prompt is marked as arising from agent mail."
1801
1838
  }
1802
1839
  },
1803
1840
  "mcp-management": {
@@ -1882,6 +1919,7 @@ var NODES_LOG_AREAS = defineLogAreas({
1882
1919
  "ticket-sync.failed": "A Kanban sync with a node failed; it is retried.",
1883
1920
  "ticket-sync.unknown-project": "A node sent ticket changes for a project that no longer exists here.",
1884
1921
  "ticket-sync.forget-failed": "A detached command node's ticket copies could not be released.",
1922
+ "usage-sync.failed": "Sharing usage readings with a node failed; the next reading or reconnect retries.",
1885
1923
  "fleet-update.requested": "The update policy asked an older leaf to install the command node's version.",
1886
1924
  "fleet-update.failed": "The update policy could not read or update a leaf; it retries later.",
1887
1925
  "fleet-update.policy-load-failed": "The stored update policy could not be read; it is off."
@@ -1973,6 +2011,20 @@ var SCHEDULER_LOG_AREAS = defineLogAreas({
1973
2011
  }
1974
2012
  });
1975
2013
 
2014
+ // ../protocol/src/log-vocabulary/self-improvement.ts
2015
+ var SELF_IMPROVEMENT_LOG_AREAS = defineLogAreas({
2016
+ "self-improvement": {
2017
+ description: "Self-improvement runs: diagnostics and conversation review turned into tickets. Counts and steps only, never conversation text.",
2018
+ events: {
2019
+ "run.started": "A run started; `trigger` is manual, daily or dry-run.",
2020
+ "run.finished": "A run finished; `created`, `verified`, `fixFailed` and `parts` count its tickets, confirmed fixes, failed fixes and conversation parts read.",
2021
+ "run.failed": "A run stopped before it finished; `reason` is a fixed label.",
2022
+ "review.call-failed": "One conversation review call failed; the run carries on and the part is read again next run.",
2023
+ "daily.check-failed": "The daily run check failed; the next check retries."
2024
+ }
2025
+ }
2026
+ });
2027
+
1976
2028
  // ../protocol/src/log-vocabulary/web-app.ts
1977
2029
  var WEB_APP_LOG_AREAS = defineLogAreas({
1978
2030
  "web.app": {
@@ -2308,6 +2360,10 @@ var WEB_SETTINGS_LOG_AREAS = defineLogAreas({
2308
2360
  "web.settings": {
2309
2361
  description: "The settings screens.",
2310
2362
  events: {
2363
+ "self-improvement.status-failed": "Settings → Self-improvement could not read the status.",
2364
+ "self-improvement.projects-failed": "Settings → Self-improvement could not list the projects.",
2365
+ "self-improvement.save-failed": "Settings → Self-improvement could not save a setting.",
2366
+ "self-improvement.run-failed": "Settings → Self-improvement could not start a run.",
2311
2367
  "config.save-failed": "Global settings could not be saved.",
2312
2368
  "config.load-failed": "The settings page could not load the config.",
2313
2369
  "config.reload-failed": "Re-reading the workspace config after a save failed.",
@@ -2477,6 +2533,7 @@ var LOG_VOCABULARY = {
2477
2533
  ...HOST_LOG_AREAS,
2478
2534
  ...TRANSCRIPT_ARTIFACTS_LOG_AREAS,
2479
2535
  ...SCHEDULER_LOG_AREAS,
2536
+ ...SELF_IMPROVEMENT_LOG_AREAS,
2480
2537
  ...WEB_APP_LOG_AREAS,
2481
2538
  ...WEB_BUILD_PIPELINE_LOG_AREAS,
2482
2539
  ...WEB_CHAT_LOG_AREAS,
@@ -2598,6 +2655,14 @@ var SIGNALS = new Set([
2598
2655
  "SIGXFSZ"
2599
2656
  ]);
2600
2657
  var PROVIDERS = new Set(["claude", "codex", "opencode", "cursor", "grok", "acp", "pi"]);
2658
+ var BRIDGE_LISTENER_REASONS = new Set([
2659
+ "different-socket",
2660
+ "several-sockets",
2661
+ "pending",
2662
+ "scan-incomplete",
2663
+ "no-listener",
2664
+ "launch-exited"
2665
+ ]);
2601
2666
  var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
2602
2667
  var SOURCE = new RegExp(`^(?:claude|codex|opencode|cursor|grok|acp|pi):${UUID}$`, "i");
2603
2668
  var STORAGE_DATABASES = new Set(["main", "ledger", "other"]);
@@ -3459,6 +3524,56 @@ function turnTokenTotal(usage) {
3459
3524
  }
3460
3525
  // ../../bridges/cursor-bridge/src/credentials.ts
3461
3526
  import { Cursor, FileCredentialStore } from "@cursor/sdk";
3527
+
3528
+ // ../protocol/src/node/bounded-wait.ts
3529
+ function boundedWait(work, timeoutMs, options = {}) {
3530
+ return new Promise((resolve, reject) => {
3531
+ let timedOut = false;
3532
+ const timer = setTimeout(() => {
3533
+ timedOut = true;
3534
+ resolve({ settled: false });
3535
+ }, timeoutMs);
3536
+ unrefTimer(timer);
3537
+ Promise.resolve(work).then((value) => {
3538
+ if (!timedOut) {
3539
+ clearTimeout(timer);
3540
+ resolve({ settled: true, value });
3541
+ return;
3542
+ }
3543
+ disposeLate(options.onLate, value);
3544
+ }, (error) => {
3545
+ if (!timedOut) {
3546
+ clearTimeout(timer);
3547
+ reject(error);
3548
+ }
3549
+ });
3550
+ });
3551
+ }
3552
+ async function boundedWaitOrThrow(work, timeoutMs, timeoutError, options = {}) {
3553
+ const result = await boundedWait(work, timeoutMs, options);
3554
+ if (!result.settled)
3555
+ throw timeoutError();
3556
+ return result.value;
3557
+ }
3558
+ function unrefTimer(timer) {
3559
+ const handle = timer;
3560
+ if (typeof handle === "object" && typeof handle.unref === "function")
3561
+ handle.unref();
3562
+ }
3563
+ function disposeLate(onLate, value) {
3564
+ if (!onLate)
3565
+ return;
3566
+ try {
3567
+ const disposal = onLate(value);
3568
+ if (disposal && typeof disposal.then === "function") {
3569
+ Promise.resolve(disposal).catch(() => {
3570
+ return;
3571
+ });
3572
+ }
3573
+ } catch {}
3574
+ }
3575
+
3576
+ // ../../bridges/cursor-bridge/src/credentials.ts
3462
3577
  var CURSOR_AUTHENTICATION_REQUIRED_MESSAGE = "Cursor is not signed in. Sign in from Settings › Cursor, or set a Cursor API key.";
3463
3578
  var AUTH_CACHE_TTL_MS = 15000;
3464
3579
  var authCache;
@@ -3579,23 +3694,11 @@ async function lookUpAccount(credential) {
3579
3694
  if (entry.timedOut)
3580
3695
  return { settled: false, account: undefined };
3581
3696
  const active = entry;
3582
- const { result } = entry;
3583
- let timer;
3584
- try {
3585
- return await Promise.race([
3586
- result.then((account) => ({ settled: true, account })),
3587
- new Promise((resolve) => {
3588
- timer = setTimeout(() => {
3589
- active.timedOut = true;
3590
- resolve({ settled: false, account: undefined });
3591
- }, accountLookupTimeoutMs);
3592
- timer.unref();
3593
- })
3594
- ]);
3595
- } finally {
3596
- if (timer)
3597
- clearTimeout(timer);
3598
- }
3697
+ const outcome = await boundedWait(entry.result, accountLookupTimeoutMs);
3698
+ if (outcome.settled)
3699
+ return { settled: true, account: outcome.value };
3700
+ active.timedOut = true;
3701
+ return { settled: false, account: undefined };
3599
3702
  }
3600
3703
  function beginLogin(options = {}) {
3601
3704
  const controller = new AbortController;
@@ -3858,20 +3961,8 @@ function boundId(value) {
3858
3961
  const trimmed = value?.trim() ?? "";
3859
3962
  return Buffer.byteLength(trimmed) > MAX_MODEL_ID_BYTES ? "" : trimmed;
3860
3963
  }
3861
- async function withTimeout(work, timeoutMs) {
3862
- let timer;
3863
- try {
3864
- return await Promise.race([
3865
- work,
3866
- new Promise((_, reject) => {
3867
- timer = setTimeout(() => reject(new Error("Cursor catalogue read timed out")), timeoutMs);
3868
- timer.unref();
3869
- })
3870
- ]);
3871
- } finally {
3872
- if (timer)
3873
- clearTimeout(timer);
3874
- }
3964
+ function withTimeout(work, timeoutMs) {
3965
+ return boundedWaitOrThrow(work, timeoutMs, () => new Error("Cursor catalogue read timed out"));
3875
3966
  }
3876
3967
  // ../../bridges/cursor-bridge/src/mcp.ts
3877
3968
  import { promises as fs } from "node:fs";
@@ -27266,6 +27357,58 @@ var PROTECTED_SEGMENTS = new Set([
27266
27357
  ".mcp.json"
27267
27358
  ]);
27268
27359
 
27360
+ // ../protocol/src/agent-mail.ts
27361
+ var AGENT_MAIL_MAX_BODY_BYTES = 32 * 1024;
27362
+ var AGENT_MAIL_MAX_STORE_BYTES = 32 * 1024 * 1024;
27363
+ var AGENT_MAIL_DEFAULT_RETENTION_DAYS = 14;
27364
+ var AGENT_MAIL_MAX_ATTACHMENT_BYTES = 8 * 1024 * 1024;
27365
+ var AGENT_MAIL_MAX_TOTAL_ATTACHMENT_BYTES = 32 * 1024 * 1024;
27366
+ var AGENT_MAIL_DEFAULT_AUTONOMOUS_WAKE_BUDGET = 16;
27367
+ var AGENT_MAIL_DEFAULT_HOURLY_WAKE_LIMIT = 40;
27368
+ var AGENT_MAIL_TOOL_NAMES = Object.freeze([
27369
+ "list_mailboxes",
27370
+ "send_message",
27371
+ "check_inbox",
27372
+ "read_message",
27373
+ "ack_message",
27374
+ "reply_message",
27375
+ "get_message_status"
27376
+ ]);
27377
+ var DEFAULT_AGENT_MESSAGING_SETTINGS = Object.freeze({
27378
+ enabled: true,
27379
+ allowCrossProject: false,
27380
+ defaultInjectPolicy: "off",
27381
+ wakePeers: false,
27382
+ autonomousWakeBudget: AGENT_MAIL_DEFAULT_AUTONOMOUS_WAKE_BUDGET,
27383
+ hourlyWakeLimit: AGENT_MAIL_DEFAULT_HOURLY_WAKE_LIMIT,
27384
+ coordinatorStatusWakes: "settled",
27385
+ retentionDays: AGENT_MAIL_DEFAULT_RETENTION_DAYS,
27386
+ paused: false
27387
+ });
27388
+ function agentMailCapabilities(tabType, agent, locked = true) {
27389
+ if (tabType === "agent-native") {
27390
+ if (!locked || !agent)
27391
+ return { canPull: false, canSend: false, canInject: false };
27392
+ if (agent === "claude" || agent === "codex" || agent === "opencode" || agent === "pi" || agent === "cursor" || agent === "grok") {
27393
+ return { canPull: true, canSend: true, canInject: true };
27394
+ }
27395
+ return { canPull: false, canSend: false, canInject: false };
27396
+ }
27397
+ if (tabType === "claude-tmux")
27398
+ return { canPull: true, canSend: true, canInject: true };
27399
+ if (tabType === "pipeline-worker") {
27400
+ return agent ? { canPull: true, canSend: true, canInject: true } : { canPull: false, canSend: false, canInject: false };
27401
+ }
27402
+ if (["claude", "codex", "opencode"].includes(tabType)) {
27403
+ return { canPull: true, canSend: true, canInject: false };
27404
+ }
27405
+ if (["cursor", "grok", "pi"].includes(tabType)) {
27406
+ return { canPull: false, canSend: false, canInject: false };
27407
+ }
27408
+ return { canPull: false, canSend: false, canInject: false };
27409
+ }
27410
+ var NATIVE_AGENT_MAIL_CAPABILITIES = Object.freeze(Object.fromEntries(AGENT_PLATFORMS.map((agent) => [agent, agentMailCapabilities("agent-native", agent)])));
27411
+
27269
27412
  // ../protocol/src/review-evidence-frames.ts
27270
27413
  var SYSTEM_INSTRUCTIONS_FRAME_OPEN = "<orkestrator-system-instructions>";
27271
27414
  var SYSTEM_INSTRUCTIONS_FRAME_CLOSE = "</orkestrator-system-instructions>";
@@ -27850,6 +27993,11 @@ var BACKGROUND_CAPABLE_SHELL_TOOL_NAMES = new Set([
27850
27993
  "run_terminal_cmd",
27851
27994
  "execute_command"
27852
27995
  ]);
27996
+ var NATIVE_AGENT_BRANCH_LIST_LIMITS = Object.freeze({
27997
+ branches: 50,
27998
+ promptChars: 280,
27999
+ entryIdChars: 512
28000
+ });
27853
28001
  var NATIVE_AGENT_COMMAND_EXECUTION_KINDS = [
27854
28002
  "provider-prompt",
27855
28003
  "provider-command",
@@ -28975,58 +29123,6 @@ function transcriptBoundSummary(state) {
28975
29123
  };
28976
29124
  }
28977
29125
 
28978
- // ../protocol/src/agent-mail.ts
28979
- var AGENT_MAIL_MAX_BODY_BYTES = 32 * 1024;
28980
- var AGENT_MAIL_MAX_STORE_BYTES = 32 * 1024 * 1024;
28981
- var AGENT_MAIL_DEFAULT_RETENTION_DAYS = 14;
28982
- var AGENT_MAIL_MAX_ATTACHMENT_BYTES = 8 * 1024 * 1024;
28983
- var AGENT_MAIL_MAX_TOTAL_ATTACHMENT_BYTES = 32 * 1024 * 1024;
28984
- var AGENT_MAIL_DEFAULT_AUTONOMOUS_WAKE_BUDGET = 16;
28985
- var AGENT_MAIL_DEFAULT_HOURLY_WAKE_LIMIT = 40;
28986
- var AGENT_MAIL_TOOL_NAMES = Object.freeze([
28987
- "list_mailboxes",
28988
- "send_message",
28989
- "check_inbox",
28990
- "read_message",
28991
- "ack_message",
28992
- "reply_message",
28993
- "get_message_status"
28994
- ]);
28995
- var DEFAULT_AGENT_MESSAGING_SETTINGS = Object.freeze({
28996
- enabled: true,
28997
- allowCrossProject: false,
28998
- defaultInjectPolicy: "off",
28999
- wakePeers: false,
29000
- autonomousWakeBudget: AGENT_MAIL_DEFAULT_AUTONOMOUS_WAKE_BUDGET,
29001
- hourlyWakeLimit: AGENT_MAIL_DEFAULT_HOURLY_WAKE_LIMIT,
29002
- coordinatorStatusWakes: "settled",
29003
- retentionDays: AGENT_MAIL_DEFAULT_RETENTION_DAYS,
29004
- paused: false
29005
- });
29006
- function agentMailCapabilities(tabType, agent, locked = true) {
29007
- if (tabType === "agent-native") {
29008
- if (!locked || !agent)
29009
- return { canPull: false, canSend: false, canInject: false };
29010
- if (agent === "claude" || agent === "codex" || agent === "opencode" || agent === "pi" || agent === "cursor" || agent === "grok") {
29011
- return { canPull: true, canSend: true, canInject: true };
29012
- }
29013
- return { canPull: false, canSend: false, canInject: false };
29014
- }
29015
- if (tabType === "claude-tmux")
29016
- return { canPull: true, canSend: true, canInject: true };
29017
- if (tabType === "pipeline-worker") {
29018
- return agent ? { canPull: true, canSend: true, canInject: true } : { canPull: false, canSend: false, canInject: false };
29019
- }
29020
- if (["claude", "codex", "opencode"].includes(tabType)) {
29021
- return { canPull: true, canSend: true, canInject: false };
29022
- }
29023
- if (["cursor", "grok", "pi"].includes(tabType)) {
29024
- return { canPull: false, canSend: false, canInject: false };
29025
- }
29026
- return { canPull: false, canSend: false, canInject: false };
29027
- }
29028
- var NATIVE_AGENT_MAIL_CAPABILITIES = Object.freeze(Object.fromEntries(AGENT_PLATFORMS.map((agent) => [agent, agentMailCapabilities("agent-native", agent)])));
29029
-
29030
29126
  // ../protocol/src/transcript-artifacts.ts
29031
29127
  var ARTIFACT_TOOL_NAMES = Object.freeze([
29032
29128
  "create_artifact",
@@ -29445,33 +29541,12 @@ async function hostServerTools(input) {
29445
29541
  }
29446
29542
  async function connectWithTimeout(transport, url, token) {
29447
29543
  const controller = new AbortController;
29448
- const attempt = transport.connect(url, token, controller.signal);
29449
- let timedOut = false;
29450
- let timer;
29451
- const deadline = new Promise((_resolve, reject) => {
29452
- timer = setTimeout(() => {
29453
- timedOut = true;
29454
- controller.abort();
29455
- reject(new Error("Orkestrator MCP timed out"));
29456
- }, connectTimeoutMs);
29457
- timer.unref();
29458
- });
29459
29544
  try {
29460
- return await Promise.race([attempt, deadline]);
29545
+ return await boundedWaitOrThrow(transport.connect(url, token, controller.signal), connectTimeoutMs, () => new Error("Orkestrator MCP timed out"), { onLate: (late) => late.close() });
29461
29546
  } catch (error) {
29462
29547
  if (!controller.signal.aborted)
29463
29548
  controller.abort();
29464
- if (timedOut) {
29465
- attempt.then((late) => late.close().catch(() => {
29466
- return;
29467
- }), () => {
29468
- return;
29469
- });
29470
- }
29471
29549
  throw error;
29472
- } finally {
29473
- if (timer)
29474
- clearTimeout(timer);
29475
29550
  }
29476
29551
  }
29477
29552
  var defaultTransport = {
@@ -31232,8 +31307,8 @@ function cursorAppliedPolicy(state) {
31232
31307
  // ../../bridges/cursor-bridge/src/agent-session.ts
31233
31308
  import { createHash as createHash7, randomBytes as randomBytes6 } from "node:crypto";
31234
31309
  import { readFile as readFile2 } from "node:fs/promises";
31235
- import { homedir as homedir3 } from "node:os";
31236
- import { join as join6 } from "node:path";
31310
+ import { homedir as homedir5 } from "node:os";
31311
+ import { join as join9 } from "node:path";
31237
31312
 
31238
31313
  // ../../bridges/cursor-bridge/src/persistence.ts
31239
31314
  import { randomBytes as randomBytes5 } from "node:crypto";
@@ -32317,20 +32392,8 @@ async function cancelSurvivingRuns(agentId, cancelTimeoutMs) {
32317
32392
  const stopped = await Promise.all(running.map((run) => withTimeout2(Promise.resolve().then(() => run.cancel()), cancelTimeoutMs).then(() => true, () => false)));
32318
32393
  return stopped.every(Boolean) ? "cancelled" : "running";
32319
32394
  }
32320
- async function withTimeout2(work, timeoutMs) {
32321
- let timer;
32322
- try {
32323
- return await Promise.race([
32324
- work,
32325
- new Promise((_, reject) => {
32326
- timer = setTimeout(() => reject(new Error("Cursor history read timed out")), timeoutMs);
32327
- timer.unref();
32328
- })
32329
- ]);
32330
- } finally {
32331
- if (timer)
32332
- clearTimeout(timer);
32333
- }
32395
+ function withTimeout2(work, timeoutMs) {
32396
+ return boundedWaitOrThrow(work, timeoutMs, () => new Error("Cursor history read timed out"));
32334
32397
  }
32335
32398
 
32336
32399
  // ../../bridges/cursor-bridge/src/session-tombstones.ts
@@ -32338,8 +32401,8 @@ var log3 = createLogger("bridge.cursor");
32338
32401
  async function closeRestoredTombstone(id, ackTimeoutMs = CLOSE_ACK_TIMEOUT_MS) {
32339
32402
  if (!closingTombstones.has(id) && !tombstoneCloses.has(id))
32340
32403
  return "closed";
32341
- const outcome = await withBudget(finishTombstone(id), ackTimeoutMs);
32342
- return outcome === "timeout" ? "pending" : outcome;
32404
+ const outcome = await boundedWait(finishTombstone(id), ackTimeoutMs);
32405
+ return outcome.settled ? outcome.value : "pending";
32343
32406
  }
32344
32407
  var tombstoneCloses = new Map;
32345
32408
  var publishingTombstones = new Map;
@@ -32422,21 +32485,6 @@ async function finishRestoredTombstones() {
32422
32485
  }
32423
32486
  return result;
32424
32487
  }
32425
- async function withBudget(work, timeoutMs) {
32426
- let timer;
32427
- try {
32428
- return await Promise.race([
32429
- work,
32430
- new Promise((resolve) => {
32431
- timer = setTimeout(() => resolve("timeout"), timeoutMs);
32432
- timer.unref?.();
32433
- })
32434
- ]);
32435
- } finally {
32436
- if (timer)
32437
- clearTimeout(timer);
32438
- }
32439
- }
32440
32488
 
32441
32489
  // ../protocol/src/node/cursor-plan-usage.ts
32442
32490
  import { Buffer as Buffer4 } from "node:buffer";
@@ -32651,6 +32699,1092 @@ function schedulePlanAccountRefresh(timeoutMs = CATALOG_TIMEOUT_MS) {
32651
32699
  });
32652
32700
  }
32653
32701
 
32702
+ // ../../bridges/cursor-bridge/src/read-boundary.ts
32703
+ import { homedir as homedir4 } from "node:os";
32704
+ import { isAbsolute as isAbsolute5, resolve as resolve6, sep as sep5 } from "node:path";
32705
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
32706
+ // ../protocol/src/coordinator.ts
32707
+ var COORDINATOR_PROTECTED_DATA_DIR_ENV = "ORKESTRATOR_COORDINATOR_PROTECTED_DATA_DIR";
32708
+ var COORDINATOR_OTHER_ENVIRONMENTS_SETTING_LABEL = "Let the coordinator use environments it did not create";
32709
+ 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.`;
32710
+ var COORDINATOR_CONTROL_TOOL_NAMES = Object.freeze([
32711
+ "mark_topic",
32712
+ "mark_question",
32713
+ "ack_message",
32714
+ "add_ticket_comment",
32715
+ "address_multi_review",
32716
+ "adopt_workflow",
32717
+ "answer_worker_question",
32718
+ "ask_agents",
32719
+ "cancel_build_pipeline",
32720
+ "cancel_graph_run",
32721
+ "cancel_multi_review",
32722
+ "cancel_schedule",
32723
+ "clear_worker_goal",
32724
+ "compare_project_files",
32725
+ "create_pr",
32726
+ "create_schedule",
32727
+ "create_ticket",
32728
+ "create_ticket_label",
32729
+ "custom_fix_multi_review",
32730
+ "edit_worker_tab",
32731
+ "fork_worker",
32732
+ "get_build_pipeline",
32733
+ "get_environment",
32734
+ "get_feature_plan",
32735
+ "get_graph_run",
32736
+ "get_launch_options",
32737
+ "get_message",
32738
+ "get_message_status",
32739
+ "get_multi_review",
32740
+ "get_repository_context",
32741
+ "get_tab_state",
32742
+ "get_tab_transcript",
32743
+ "get_ticket",
32744
+ "get_usage_limits",
32745
+ "get_worker_changes",
32746
+ "get_worker_goal",
32747
+ "launch_environment",
32748
+ "launch_feature_plan",
32749
+ "launch_graph",
32750
+ "launch_job",
32751
+ "launch_multi_review",
32752
+ "launch_terminal",
32753
+ "list_agents",
32754
+ "list_environments",
32755
+ "list_graph_templates",
32756
+ "list_mailboxes",
32757
+ "list_nodes",
32758
+ "list_projects",
32759
+ "list_provider_accounts",
32760
+ "list_schedules",
32761
+ "list_tabs",
32762
+ "list_ticket_labels",
32763
+ "list_tickets",
32764
+ "list_worker_commands",
32765
+ "list_workflows",
32766
+ "open_multi_review",
32767
+ "open_multi_review_fix",
32768
+ "open_worker_browser",
32769
+ "pause_build_pipeline",
32770
+ "pause_schedule",
32771
+ "pause_worker_goal",
32772
+ "propose_agents_md_update",
32773
+ "read_messages",
32774
+ "read_node_environment",
32775
+ "request_env_value_reveal",
32776
+ "request_environment_deletion",
32777
+ "request_project_file_update",
32778
+ "request_project_on_node",
32779
+ "request_root_changes",
32780
+ "resolve_conflicts",
32781
+ "restart_build_pipeline_step",
32782
+ "resume_build_pipeline",
32783
+ "resume_schedule",
32784
+ "run_worker_command",
32785
+ "send_message",
32786
+ "send_prompt_to_tab",
32787
+ "set_ticket_label",
32788
+ "set_worker_goal",
32789
+ "start_build_pipeline",
32790
+ "start_environment",
32791
+ "stop_environment",
32792
+ "stop_worker_turn",
32793
+ "switch_provider_account",
32794
+ "set_account_auto_switch",
32795
+ "transfer_files",
32796
+ "update_schedule",
32797
+ "update_ticket"
32798
+ ]);
32799
+ var COORDINATOR_PROJECT_HOME_MESSAGE_WINDOW_MS = 3 * 60 * 60000;
32800
+
32801
+ // ../protocol/src/node/coordinator-read-boundary.ts
32802
+ import { realpathSync as realpathSync2 } from "node:fs";
32803
+ import { homedir as homedir3 } from "node:os";
32804
+ import { dirname as dirname2, isAbsolute as isAbsolute2, join as join4, parse as parse4, resolve as resolve3, sep as sep2 } from "node:path";
32805
+ function canonicalPath(path) {
32806
+ let existing = path;
32807
+ const tail = [];
32808
+ for (;; ) {
32809
+ try {
32810
+ return join4(realpathSync2.native(existing), ...tail.reverse());
32811
+ } catch {
32812
+ const parent = dirname2(existing);
32813
+ if (parent === existing)
32814
+ return path;
32815
+ tail.push(existing.slice(parent.length).replace(/^[/\\]+/, ""));
32816
+ existing = parent;
32817
+ }
32818
+ }
32819
+ }
32820
+ function namedAndCanonicalPaths(paths) {
32821
+ const named = paths.flatMap((path) => path?.trim() && isAbsolute2(path) ? [path] : []);
32822
+ return [...new Set(named.flatMap((path) => [resolve3(path), canonicalPath(path)]))];
32823
+ }
32824
+ function isWithin2(root, path) {
32825
+ if (path === root)
32826
+ return true;
32827
+ const prefix = root === parse4(root).root ? root : `${root}${sep2}`;
32828
+ return path.startsWith(prefix);
32829
+ }
32830
+ function protectedDataDirBoundary(dataDir, allowances) {
32831
+ const trimmed = dataDir?.trim();
32832
+ if (!trimmed || !isAbsolute2(trimmed))
32833
+ return null;
32834
+ const deny = namedAndCanonicalPaths([trimmed]);
32835
+ return {
32836
+ deny,
32837
+ allow: namedAndCanonicalPaths(allowances).filter((path) => !deny.includes(path) && deny.some((root) => isWithin2(root, path)))
32838
+ };
32839
+ }
32840
+ function deniedForm(boundary, path) {
32841
+ return boundary.deny.some((root) => isWithin2(root, path)) && !boundary.allow.some((root) => isWithin2(root, path));
32842
+ }
32843
+ function expandedHome(path) {
32844
+ if (path === "~")
32845
+ return homedir3();
32846
+ return path.startsWith("~/") ? `${homedir3()}${sep2}${path.slice(2)}` : path;
32847
+ }
32848
+ function readBoundaryRefuses(boundary, path, cwd, options = {}) {
32849
+ const expanded = expandedHome(path);
32850
+ const raw = isAbsolute2(expanded) ? expanded : `${cwd}${sep2}${expanded}`;
32851
+ const lexical = resolve3(raw);
32852
+ const real = canonicalPath(raw);
32853
+ if (deniedForm(boundary, lexical) || deniedForm(boundary, real))
32854
+ return true;
32855
+ return options.traversal === true && boundary.deny.some((root) => isWithin2(lexical, root) || isWithin2(real, root));
32856
+ }
32857
+
32858
+ // ../../bridges/cursor-bridge/src/prompt-attachments.ts
32859
+ import { constants as constants2 } from "node:fs";
32860
+ import { lstat, open as open3, realpath } from "node:fs/promises";
32861
+ import { isAbsolute as isAbsolute3, join as join5, relative as relative2, resolve as resolve4, sep as sep3 } from "node:path";
32862
+
32863
+ class PromptAttachmentError extends Error {
32864
+ code;
32865
+ name = "PromptAttachmentError";
32866
+ constructor(code, message) {
32867
+ super(message);
32868
+ this.code = code;
32869
+ }
32870
+ }
32871
+ var MAX_IMAGE_ATTACHMENT_BYTES = 8 * 1024 * 1024;
32872
+ var MAX_PROMPT_ATTACHMENTS = 20;
32873
+ var MAX_TOTAL_IMAGE_ATTACHMENT_BYTES = 32 * 1024 * 1024;
32874
+ var MAX_ATTACHMENT_PATH_BYTES = 4 * 1024;
32875
+ var MAX_ATTACHMENT_FILENAME_BYTES = 1 * 1024;
32876
+ var READ_CHUNK_BYTES = 64 * 1024;
32877
+ function parsePromptAttachments(value) {
32878
+ if (value === undefined || value === null)
32879
+ return [];
32880
+ if (!Array.isArray(value)) {
32881
+ throw new PromptAttachmentError("attachment_invalid", "attachments must be an array");
32882
+ }
32883
+ if (value.length > MAX_PROMPT_ATTACHMENTS) {
32884
+ throw new PromptAttachmentError("attachment_invalid", `A prompt can carry at most ${MAX_PROMPT_ATTACHMENTS} attachments`);
32885
+ }
32886
+ return value.map((candidate) => {
32887
+ if (candidate === null || typeof candidate !== "object" || Array.isArray(candidate)) {
32888
+ throw new PromptAttachmentError("attachment_invalid", "Each attachment must be an object");
32889
+ }
32890
+ const record = candidate;
32891
+ if (record.type !== "image") {
32892
+ throw new PromptAttachmentError("attachment_invalid", "Cursor accepts image attachments only");
32893
+ }
32894
+ const path = typeof record.path === "string" ? record.path.trim() : "";
32895
+ if (!path || Buffer.byteLength(path) > MAX_ATTACHMENT_PATH_BYTES) {
32896
+ throw new PromptAttachmentError("attachment_invalid", "Each attachment needs a workspace path");
32897
+ }
32898
+ if (path.includes("\x00")) {
32899
+ throw new PromptAttachmentError("attachment_invalid", "An attachment path must not contain null bytes");
32900
+ }
32901
+ const filename = typeof record.filename === "string" && record.filename.trim() && Buffer.byteLength(record.filename) <= MAX_ATTACHMENT_FILENAME_BYTES ? record.filename : undefined;
32902
+ return { type: "image", path, ...filename ? { filename } : {} };
32903
+ });
32904
+ }
32905
+ async function readPromptImages(attachments, workspaceRoot) {
32906
+ const images = [];
32907
+ let totalBytes = 0;
32908
+ for (const attachment of attachments) {
32909
+ const { bytes, absolutePath } = await readWorkspaceImage(attachment.path, workspaceRoot);
32910
+ totalBytes += bytes.length;
32911
+ if (totalBytes > MAX_TOTAL_IMAGE_ATTACHMENT_BYTES) {
32912
+ throw new PromptAttachmentError("attachment_too_large", "Image attachments exceed the 32MB total limit");
32913
+ }
32914
+ images.push({
32915
+ data: bytes.toString("base64"),
32916
+ mimeType: imageMimeType(bytes),
32917
+ path: attachment.path,
32918
+ absolutePath,
32919
+ ...attachment.filename ? { filename: attachment.filename } : {}
32920
+ });
32921
+ }
32922
+ return images;
32923
+ }
32924
+ function imageMimeType(bytes) {
32925
+ if (bytes.length >= 8 && bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
32926
+ return "image/png";
32927
+ if (bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) {
32928
+ return "image/jpeg";
32929
+ }
32930
+ if (bytes.length >= 6 && (bytes.subarray(0, 6).toString("latin1") === "GIF87a" || bytes.subarray(0, 6).toString("latin1") === "GIF89a"))
32931
+ return "image/gif";
32932
+ if (bytes.length >= 12 && bytes.subarray(0, 4).toString("latin1") === "RIFF" && bytes.subarray(8, 12).toString("latin1") === "WEBP")
32933
+ return "image/webp";
32934
+ throw new PromptAttachmentError("attachment_unsupported_format", "Image attachments must be PNG, JPEG, GIF, or WebP");
32935
+ }
32936
+ function attachmentErrorForFsFailure(error) {
32937
+ const code = error?.code;
32938
+ if (code === "ELOOP") {
32939
+ return new PromptAttachmentError("attachment_symlink_not_allowed", "Image attachments must be regular workspace files, not symbolic links");
32940
+ }
32941
+ return new PromptAttachmentError("attachment_read_failed", "Image attachment could not be read from the workspace");
32942
+ }
32943
+ var BRIDGE_ATTACHMENT_ROOT_ENV = "ORKESTRATOR_BRIDGE_ATTACHMENT_ROOT";
32944
+ function configuredAttachmentRoot(env = process.env) {
32945
+ const value = env[BRIDGE_ATTACHMENT_ROOT_ENV]?.trim();
32946
+ return value && isAbsolute3(value) ? resolve4(value) : undefined;
32947
+ }
32948
+ function attachmentContainmentRoot(filePath, workspaceRoot, extraRoot = configuredAttachmentRoot()) {
32949
+ if (extraRoot && isAbsolute3(filePath) && isPathWithin(extraRoot, resolve4(filePath))) {
32950
+ return extraRoot;
32951
+ }
32952
+ return resolve4(workspaceRoot);
32953
+ }
32954
+ function isPathWithin(root, candidate) {
32955
+ if (candidate === root)
32956
+ return true;
32957
+ const childPath = relative2(root, candidate);
32958
+ return Boolean(childPath) && childPath !== ".." && !childPath.startsWith(`..${sep3}`) && !isAbsolute3(childPath);
32959
+ }
32960
+ async function assertNoSymlinkComponents(root, targetPath) {
32961
+ let currentPath = root;
32962
+ for (const segment of relative2(root, targetPath).split(sep3).filter(Boolean)) {
32963
+ currentPath = join5(currentPath, segment);
32964
+ const stats = await lstat(currentPath).catch((error) => {
32965
+ throw attachmentErrorForFsFailure(error);
32966
+ });
32967
+ if (stats.isSymbolicLink()) {
32968
+ throw new PromptAttachmentError("attachment_symlink_not_allowed", "Image attachments must be regular workspace files, not symbolic links");
32969
+ }
32970
+ }
32971
+ }
32972
+ async function assertOpenedWorkspaceFile(targetPath, canonicalRoot, openedStats) {
32973
+ const [pathStats, canonicalTarget] = await Promise.all([
32974
+ lstat(targetPath),
32975
+ realpath(targetPath)
32976
+ ]).catch((error) => {
32977
+ throw attachmentErrorForFsFailure(error);
32978
+ });
32979
+ if (pathStats.isSymbolicLink()) {
32980
+ throw new PromptAttachmentError("attachment_symlink_not_allowed", "Image attachments must be regular workspace files, not symbolic links");
32981
+ }
32982
+ if (!pathStats.isFile() || !openedStats.isFile() || pathStats.dev !== openedStats.dev || pathStats.ino !== openedStats.ino) {
32983
+ throw new PromptAttachmentError("attachment_not_regular_file", "Image attachment is not a stable regular workspace file");
32984
+ }
32985
+ if (!isPathWithin(canonicalRoot, canonicalTarget)) {
32986
+ throw new PromptAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace");
32987
+ }
32988
+ }
32989
+ function assertStableRead(initial, final, bytesRead) {
32990
+ if (final.dev !== initial.dev || final.ino !== initial.ino || final.size !== initial.size || final.size !== bytesRead || final.mtimeMs !== initial.mtimeMs || final.ctimeMs !== initial.ctimeMs) {
32991
+ throw new PromptAttachmentError("attachment_changed", "Image attachment changed while it was being read; attach it again");
32992
+ }
32993
+ }
32994
+ async function readWorkspaceImage(filePath, workspaceRoot) {
32995
+ const lexicalRoot = attachmentContainmentRoot(filePath, workspaceRoot);
32996
+ const targetPath = isAbsolute3(filePath) ? resolve4(filePath) : resolve4(lexicalRoot, filePath);
32997
+ if (!isPathWithin(lexicalRoot, targetPath)) {
32998
+ throw new PromptAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace");
32999
+ }
33000
+ const canonicalRoot = await realpath(lexicalRoot).catch((error) => {
33001
+ throw attachmentErrorForFsFailure(error);
33002
+ });
33003
+ await assertNoSymlinkComponents(lexicalRoot, targetPath);
33004
+ const canonicalTarget = await realpath(targetPath).catch((error) => {
33005
+ throw attachmentErrorForFsFailure(error);
33006
+ });
33007
+ if (!isPathWithin(canonicalRoot, canonicalTarget)) {
33008
+ throw new PromptAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace");
33009
+ }
33010
+ const noFollow = constants2.O_NOFOLLOW ?? 0;
33011
+ const handle = await open3(targetPath, constants2.O_RDONLY | noFollow).catch((error) => {
33012
+ throw attachmentErrorForFsFailure(error);
33013
+ });
33014
+ try {
33015
+ const initialStats = await handle.stat();
33016
+ await assertOpenedWorkspaceFile(targetPath, canonicalRoot, initialStats);
33017
+ if (initialStats.size > MAX_IMAGE_ATTACHMENT_BYTES) {
33018
+ throw new PromptAttachmentError("attachment_too_large", "Image attachment exceeds the 8MB limit");
33019
+ }
33020
+ const chunks = [];
33021
+ let totalBytes = 0;
33022
+ while (totalBytes <= MAX_IMAGE_ATTACHMENT_BYTES) {
33023
+ const remaining = MAX_IMAGE_ATTACHMENT_BYTES + 1 - totalBytes;
33024
+ const chunk = Buffer.allocUnsafe(Math.min(READ_CHUNK_BYTES, remaining));
33025
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
33026
+ if (bytesRead === 0)
33027
+ break;
33028
+ chunks.push(chunk.subarray(0, bytesRead));
33029
+ totalBytes += bytesRead;
33030
+ }
33031
+ if (totalBytes > MAX_IMAGE_ATTACHMENT_BYTES) {
33032
+ throw new PromptAttachmentError("attachment_too_large", "Image attachment exceeds the 8MB limit");
33033
+ }
33034
+ if (totalBytes === 0) {
33035
+ throw new PromptAttachmentError("attachment_empty", "Image attachment file is empty");
33036
+ }
33037
+ const finalStats = await handle.stat();
33038
+ await assertOpenedWorkspaceFile(targetPath, canonicalRoot, finalStats);
33039
+ assertStableRead(initialStats, finalStats, totalBytes);
33040
+ return { bytes: Buffer.concat(chunks, totalBytes), absolutePath: targetPath };
33041
+ } catch (error) {
33042
+ if (error instanceof PromptAttachmentError)
33043
+ throw error;
33044
+ throw attachmentErrorForFsFailure(error);
33045
+ } finally {
33046
+ await handle.close();
33047
+ }
33048
+ }
33049
+
33050
+ // ../../bridges/cursor-bridge/src/read-tools.ts
33051
+ import { isUtf8 } from "node:buffer";
33052
+ import { spawn } from "node:child_process";
33053
+ import { existsSync as existsSync2, realpathSync as realpathSync3 } from "node:fs";
33054
+ import { open as open4, stat as stat2 } from "node:fs/promises";
33055
+ import { basename as basename2, dirname as dirname3, extname, isAbsolute as isAbsolute4, join as join6, relative as relative3, resolve as resolve5, sep as sep4 } from "node:path";
33056
+ import { fileURLToPath } from "node:url";
33057
+ var MAX_READ_BYTES = 8 * 1024 * 1024;
33058
+ var MAX_SEARCH_ENTRIES = 2000;
33059
+ var MAX_MATCH_LINE_CHARS = 1000;
33060
+ var MAX_RIPGREP_OUTPUT_BYTES = 16 * 1024 * 1024;
33061
+ var MAX_RIPGREP_STDERR_BYTES = 4096;
33062
+ var SEARCH_TIMEOUT_MS = 25000;
33063
+ var LS_TIMEOUT_MS = 5000;
33064
+ var LS_CHARACTER_BUDGET = 2500;
33065
+ var IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp"]);
33066
+ function withClone(value) {
33067
+ Object.defineProperty(value, "clone", {
33068
+ value: () => withClone(structuredClone(value)),
33069
+ enumerable: false
33070
+ });
33071
+ return value;
33072
+ }
33073
+ function errorCode(error) {
33074
+ return error && typeof error === "object" && "code" in error ? String(error.code) : undefined;
33075
+ }
33076
+ function errorMessage2(error) {
33077
+ return error instanceof Error ? error.message : "Unknown error occurred";
33078
+ }
33079
+ function countLines(text) {
33080
+ let lines = 1;
33081
+ for (let index = text.indexOf(`
33082
+ `);index !== -1; index = text.indexOf(`
33083
+ `, index + 1)) {
33084
+ lines += 1;
33085
+ }
33086
+ return lines;
33087
+ }
33088
+ function clampLine(value, total) {
33089
+ if (Number.isNaN(value) || value === 0)
33090
+ return 0;
33091
+ if (value === Number.POSITIVE_INFINITY)
33092
+ return total;
33093
+ if (value === Number.NEGATIVE_INFINITY)
33094
+ return 0;
33095
+ const whole = Math.trunc(value);
33096
+ return whole < 0 ? Math.max(total + whole, 0) : Math.min(whole, total);
33097
+ }
33098
+ function readLineRange(totalLines, empty, args) {
33099
+ if (args.offset === undefined && args.limit === undefined)
33100
+ return { applied: false };
33101
+ if (empty)
33102
+ return { applied: false };
33103
+ const offset = args.offset ?? 1;
33104
+ const limit = args.limit ?? (offset < 0 ? Math.abs(offset) : totalLines);
33105
+ const first = offset < 0 ? Math.max(0, totalLines + offset) : Math.max(0, offset - 1);
33106
+ if (first >= totalLines)
33107
+ return { applied: false };
33108
+ const last = Math.min(totalLines, first + limit);
33109
+ const start = clampLine(first, totalLines);
33110
+ return { applied: true, start, end: Math.max(start, clampLine(last, totalLines)) };
33111
+ }
33112
+ function sliceLines(text, start, end) {
33113
+ if (start >= end)
33114
+ return "";
33115
+ let from = 0;
33116
+ for (let line = 0;line < start; line += 1) {
33117
+ const next = text.indexOf(`
33118
+ `, from);
33119
+ if (next === -1)
33120
+ return "";
33121
+ from = next + 1;
33122
+ }
33123
+ let to = from;
33124
+ for (let line = start;line < end; line += 1) {
33125
+ const next = text.indexOf(`
33126
+ `, to);
33127
+ if (next === -1)
33128
+ return text.slice(from);
33129
+ to = next + 1;
33130
+ }
33131
+ return text.slice(from, to);
33132
+ }
33133
+ function readCharacterLimit(args) {
33134
+ if (args.maxChars === undefined || args.offset !== undefined || args.limit !== undefined) {
33135
+ return MAX_READ_BYTES;
33136
+ }
33137
+ return Math.min(MAX_READ_BYTES, args.maxChars + 2);
33138
+ }
33139
+ function trimSurrogate(text) {
33140
+ const last = text.charCodeAt(text.length - 1);
33141
+ return last >= 55296 && last <= 56319 ? text.slice(0, -1) : text;
33142
+ }
33143
+ var BINARY_SIGNATURES = [
33144
+ Buffer.from("%PDF-", "ascii"),
33145
+ Buffer.from([80, 75, 3, 4]),
33146
+ Buffer.from([127, 69, 76, 70]),
33147
+ Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
33148
+ Buffer.from([255, 216, 255]),
33149
+ Buffer.from("GIF87a", "ascii"),
33150
+ Buffer.from("GIF89a", "ascii"),
33151
+ Buffer.from("SQLite format 3\x00", "ascii"),
33152
+ Buffer.from([31, 139])
33153
+ ];
33154
+ function looksBinary(head) {
33155
+ if (BINARY_SIGNATURES.some((signature) => head.subarray(0, signature.length).equals(signature))) {
33156
+ return true;
33157
+ }
33158
+ return head.includes(0);
33159
+ }
33160
+ async function readHead(path, bytes) {
33161
+ const handle = await open4(path, "r");
33162
+ try {
33163
+ const buffer = Buffer.alloc(bytes);
33164
+ const { bytesRead } = await handle.read(buffer, 0, bytes, 0);
33165
+ return buffer.subarray(0, bytesRead);
33166
+ } finally {
33167
+ await handle.close();
33168
+ }
33169
+ }
33170
+ function success(path, value) {
33171
+ return { result: { case: "success", value: withClone({ path, ...value }) } };
33172
+ }
33173
+ async function readFileTool(path, args) {
33174
+ try {
33175
+ const stats = await stat2(path);
33176
+ if (stats.isDirectory()) {
33177
+ return {
33178
+ result: {
33179
+ case: "invalidFile",
33180
+ value: { path, reason: "Path is a directory, not a file" }
33181
+ }
33182
+ };
33183
+ }
33184
+ if (!stats.isFile()) {
33185
+ return {
33186
+ result: {
33187
+ case: "invalidFile",
33188
+ value: { path, reason: "Path is neither a file nor a directory" }
33189
+ }
33190
+ };
33191
+ }
33192
+ const fileSize = BigInt(stats.size);
33193
+ const extension = extname(path).toLowerCase();
33194
+ const head = await readHead(path, Math.min(stats.size, 8192));
33195
+ if (IMAGE_EXTENSIONS.has(extension) || extension === ".pdf" || looksBinary(head)) {
33196
+ if (!(IMAGE_EXTENSIONS.has(extension) || extension === ".pdf")) {
33197
+ return {
33198
+ result: {
33199
+ case: "invalidFile",
33200
+ value: { path, reason: "File content is binary data, not text" }
33201
+ }
33202
+ };
33203
+ }
33204
+ if (stats.size > MAX_READ_BYTES) {
33205
+ return {
33206
+ result: {
33207
+ case: "invalidFile",
33208
+ value: { path, reason: `File is larger than ${MAX_READ_BYTES} bytes` }
33209
+ }
33210
+ };
33211
+ }
33212
+ const data = await readHead(path, stats.size);
33213
+ return success(path, {
33214
+ output: { case: "data", value: new Uint8Array(data) },
33215
+ totalLines: 0,
33216
+ fileSize,
33217
+ truncated: false
33218
+ });
33219
+ }
33220
+ const capped = stats.size > MAX_READ_BYTES;
33221
+ const bytes = await readHead(path, Math.min(stats.size, MAX_READ_BYTES));
33222
+ let text = bytes.toString("utf8");
33223
+ if (text.charCodeAt(0) === 65279)
33224
+ text = text.slice(1);
33225
+ const totalLines = countLines(text);
33226
+ const range = readLineRange(totalLines, text === "", args);
33227
+ let content = range.applied ? sliceLines(text, range.start, range.end) : text;
33228
+ let truncated = capped;
33229
+ const limit = readCharacterLimit(args);
33230
+ if (content.length > limit) {
33231
+ content = trimSurrogate(content.substring(0, limit));
33232
+ truncated = true;
33233
+ }
33234
+ return success(path, {
33235
+ output: { case: "content", value: content },
33236
+ totalLines,
33237
+ fileSize,
33238
+ truncated,
33239
+ rangeApplied: range.applied
33240
+ });
33241
+ } catch (error) {
33242
+ const code = errorCode(error);
33243
+ if (code === "ENOENT")
33244
+ return { result: { case: "fileNotFound", value: { path } } };
33245
+ if (code === "EACCES" || code === "EPERM") {
33246
+ return { result: { case: "permissionDenied", value: { path } } };
33247
+ }
33248
+ return { result: { case: "error", value: { path, error: errorMessage2(error) } } };
33249
+ }
33250
+ }
33251
+ function sdkDirectory() {
33252
+ try {
33253
+ return realpathSync3(dirname3(fileURLToPath(import.meta.resolve("@cursor/sdk"))));
33254
+ } catch {
33255
+ return;
33256
+ }
33257
+ }
33258
+ function resolveRipgrep(workspace, env = process.env, from = [sdkDirectory(), dirname3(fileURLToPath(import.meta.url))]) {
33259
+ const binary = process.platform === "win32" ? "rg.exe" : "rg";
33260
+ const configured = env.CURSOR_RIPGREP_PATH?.trim();
33261
+ if (configured && isAbsolute4(configured) && existsSync2(configured))
33262
+ return configured;
33263
+ const workspaceRoot = resolve5(workspace);
33264
+ const insideWorkspace = (path) => {
33265
+ const inside = relative3(workspaceRoot, path);
33266
+ return inside === "" || !inside.startsWith("..") && !isAbsolute4(inside);
33267
+ };
33268
+ const relativeBinary = join6("node_modules", "@cursor", `sdk-${process.platform}-${process.arch}`, "bin", binary);
33269
+ for (const start of from) {
33270
+ if (!start)
33271
+ continue;
33272
+ let directory = resolve5(start);
33273
+ for (;; ) {
33274
+ const candidate = join6(directory, relativeBinary);
33275
+ if (!insideWorkspace(candidate) && existsSync2(candidate))
33276
+ return candidate;
33277
+ const parent = dirname3(directory);
33278
+ if (parent === directory)
33279
+ break;
33280
+ directory = parent;
33281
+ }
33282
+ }
33283
+ return binary;
33284
+ }
33285
+ function runRipgrep(ripgrep, args, cwd, timeoutMs) {
33286
+ return new Promise((resolvePromise, reject) => {
33287
+ const child = spawn(ripgrep, args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
33288
+ const chunks = [];
33289
+ let bytes = 0;
33290
+ let stderr = "";
33291
+ let timedOut = false;
33292
+ let outputCapped = false;
33293
+ const timer = setTimeout(() => {
33294
+ timedOut = true;
33295
+ child.kill("SIGKILL");
33296
+ }, timeoutMs);
33297
+ child.stdout.on("data", (chunk) => {
33298
+ if (outputCapped)
33299
+ return;
33300
+ const room = MAX_RIPGREP_OUTPUT_BYTES - bytes;
33301
+ if (chunk.length >= room) {
33302
+ chunks.push(chunk.subarray(0, room));
33303
+ bytes += room;
33304
+ outputCapped = true;
33305
+ child.kill("SIGKILL");
33306
+ return;
33307
+ }
33308
+ chunks.push(chunk);
33309
+ bytes += chunk.length;
33310
+ });
33311
+ child.stderr.on("data", (chunk) => {
33312
+ if (stderr.length < MAX_RIPGREP_STDERR_BYTES) {
33313
+ stderr = (stderr + chunk.toString("utf8")).slice(0, MAX_RIPGREP_STDERR_BYTES);
33314
+ }
33315
+ });
33316
+ child.once("error", (error) => {
33317
+ clearTimeout(timer);
33318
+ reject(error);
33319
+ });
33320
+ child.once("close", (exitCode) => {
33321
+ clearTimeout(timer);
33322
+ resolvePromise({
33323
+ stdout: Buffer.concat(chunks),
33324
+ stderr,
33325
+ exitCode,
33326
+ timedOut,
33327
+ outputCapped
33328
+ });
33329
+ });
33330
+ });
33331
+ }
33332
+ function ripgrepFailed(run) {
33333
+ return !run.timedOut && !run.outputCapped && run.exitCode === 2 && run.stdout.length === 0;
33334
+ }
33335
+ function ripgrepError(run) {
33336
+ return run.stderr.trim().split(/\r?\n/)[0] || `ripgrep exited with code ${run.exitCode}`;
33337
+ }
33338
+ function outputModeOf(value) {
33339
+ const mode = value ?? "content";
33340
+ return mode === "content" || mode === "files_with_matches" || mode === "count" ? mode : undefined;
33341
+ }
33342
+ function listsFiles(args, mode) {
33343
+ return mode === "files_with_matches" && (args.pattern ?? "") === "" && Boolean(args.glob);
33344
+ }
33345
+ function page(entries, args) {
33346
+ const offset = args.offset !== undefined && args.offset > 0 ? Math.trunc(args.offset) : 0;
33347
+ let kept = entries.slice(offset);
33348
+ let headLimitApplied;
33349
+ if (args.headLimit !== undefined && args.headLimit > 0 && kept.length > args.headLimit) {
33350
+ headLimitApplied = Math.trunc(args.headLimit);
33351
+ kept = kept.slice(0, headLimitApplied);
33352
+ }
33353
+ const clientTruncated = kept.length > MAX_SEARCH_ENTRIES;
33354
+ if (clientTruncated)
33355
+ kept = kept.slice(0, MAX_SEARCH_ENTRIES);
33356
+ return {
33357
+ kept,
33358
+ ...headLimitApplied !== undefined ? { headLimitApplied } : {},
33359
+ ...offset > 0 ? { offsetApplied: offset } : {},
33360
+ clientTruncated
33361
+ };
33362
+ }
33363
+ function grepArguments(args, mode, target) {
33364
+ const files = listsFiles(args, mode);
33365
+ const rg = [];
33366
+ if (mode === "content") {
33367
+ rg.push("--json");
33368
+ if (args.contextBefore !== undefined)
33369
+ rg.push("--before-context", String(args.contextBefore));
33370
+ if (args.contextAfter !== undefined)
33371
+ rg.push("--after-context", String(args.contextAfter));
33372
+ if (args.context !== undefined && args.contextBefore === undefined && args.contextAfter === undefined) {
33373
+ rg.push("--context", String(args.context));
33374
+ }
33375
+ } else if (mode === "files_with_matches") {
33376
+ rg.push(files ? "--files" : "--files-with-matches", "--null");
33377
+ } else {
33378
+ rg.push("--count", "--with-filename", "--null");
33379
+ }
33380
+ rg.push(args.caseInsensitive === true ? "--ignore-case" : "--case-sensitive");
33381
+ if (args.type)
33382
+ rg.push("--type", args.type);
33383
+ if (args.glob) {
33384
+ rg.push("--iglob", args.glob);
33385
+ if (files)
33386
+ rg.push("--iglob", "!**/.git");
33387
+ }
33388
+ if (args.multiline)
33389
+ rg.push("--multiline", "--multiline-dotall");
33390
+ const sort = args.sort ?? "modified";
33391
+ if (sort !== "none")
33392
+ rg.push(args.sortAscending === true ? "--sort" : "--sortr", sort);
33393
+ rg.push("--no-config", "--color=never", "--hidden", "--follow");
33394
+ if (!files)
33395
+ rg.push("--regexp", args.pattern ?? "");
33396
+ rg.push("--", target);
33397
+ return rg;
33398
+ }
33399
+ function withoutDotSlash(path) {
33400
+ return path.startsWith(`.${sep4}`) ? path.slice(2) : path;
33401
+ }
33402
+ function pathText(bytes) {
33403
+ return isUtf8(bytes) ? bytes.toString("utf8") : undefined;
33404
+ }
33405
+ function splitNull(output) {
33406
+ const paths = [];
33407
+ let start = 0;
33408
+ for (let end = output.indexOf(0);end !== -1; end = output.indexOf(0, start)) {
33409
+ const path = pathText(output.subarray(start, end));
33410
+ if (path)
33411
+ paths.push(path);
33412
+ start = end + 1;
33413
+ }
33414
+ return paths;
33415
+ }
33416
+ function jsonText(value) {
33417
+ if (!value)
33418
+ return "";
33419
+ if (typeof value.text === "string")
33420
+ return value.text;
33421
+ return typeof value.bytes === "string" ? Buffer.from(value.bytes, "base64").toString("utf8") : "";
33422
+ }
33423
+ function contentLines(output) {
33424
+ const lines = [];
33425
+ for (const raw of output.toString("utf8").split(`
33426
+ `)) {
33427
+ if (!raw.trim())
33428
+ continue;
33429
+ let event;
33430
+ try {
33431
+ event = JSON.parse(raw);
33432
+ } catch {
33433
+ continue;
33434
+ }
33435
+ if (event.type !== "match" && event.type !== "context")
33436
+ continue;
33437
+ const data = event.data ?? {};
33438
+ const reportedPath = data.path;
33439
+ const file = reportedPath?.bytes !== undefined ? pathText(Buffer.from(reportedPath.bytes, "base64")) : reportedPath?.text;
33440
+ if (!file)
33441
+ continue;
33442
+ const text = jsonText(data.lines).replace(/\r?\n$/, "");
33443
+ const lineNumber = typeof data.line_number === "number" ? data.line_number : 0;
33444
+ text.split(`
33445
+ `).forEach((line, index) => {
33446
+ const truncated = line.length > MAX_MATCH_LINE_CHARS;
33447
+ lines.push({
33448
+ file: withoutDotSlash(file),
33449
+ lineNumber: lineNumber + index,
33450
+ content: truncated ? line.slice(0, MAX_MATCH_LINE_CHARS) : line,
33451
+ contentTruncated: truncated,
33452
+ isContextLine: event.type === "context"
33453
+ });
33454
+ });
33455
+ }
33456
+ return lines;
33457
+ }
33458
+ async function grepTool(args, options) {
33459
+ const mode = outputModeOf(args.outputMode);
33460
+ if (!mode) {
33461
+ return {
33462
+ result: { case: "error", value: { error: `Unknown output mode: ${args.outputMode}` } }
33463
+ };
33464
+ }
33465
+ const { cwd, refused } = options;
33466
+ try {
33467
+ const targetStats = await stat2(options.target).catch((error) => {
33468
+ if (errorCode(error) === "ENOENT")
33469
+ return;
33470
+ throw error;
33471
+ });
33472
+ if (!targetStats) {
33473
+ return {
33474
+ result: { case: "error", value: { error: `Path does not exist: ${options.target}` } }
33475
+ };
33476
+ }
33477
+ const inside = relative3(cwd, options.target);
33478
+ const target = inside === "" ? "." : !inside.startsWith("..") && !isAbsolute4(inside) ? inside : options.target;
33479
+ const rgArgs = grepArguments(args, mode, target);
33480
+ const cursorIgnore = join6(cwd, ".cursorignore");
33481
+ if (existsSync2(cursorIgnore))
33482
+ rgArgs.unshift("--ignore-file", cursorIgnore);
33483
+ const run = await runRipgrep(options.ripgrep, rgArgs, cwd, SEARCH_TIMEOUT_MS);
33484
+ if (ripgrepFailed(run)) {
33485
+ return { result: { case: "error", value: { error: ripgrepError(run) } } };
33486
+ }
33487
+ const ripgrepTruncated = run.timedOut || run.outputCapped;
33488
+ const admitted = (file) => !refused(resolve5(cwd, file));
33489
+ let union;
33490
+ if (mode === "content") {
33491
+ const lines = contentLines(run.stdout).filter((line) => admitted(line.file));
33492
+ const paged = page(lines, args);
33493
+ const byFile = new Map;
33494
+ for (const { file, ...line } of paged.kept) {
33495
+ const matches = byFile.get(file) ?? [];
33496
+ matches.push(line);
33497
+ byFile.set(file, matches);
33498
+ }
33499
+ union = {
33500
+ case: "content",
33501
+ value: {
33502
+ matches: Array.from(byFile, ([file, matches]) => ({ file, matches })),
33503
+ totalLines: lines.length,
33504
+ totalMatchedLines: lines.filter((line) => !line.isContextLine).length,
33505
+ clientTruncated: paged.clientTruncated,
33506
+ ripgrepTruncated,
33507
+ headLimitApplied: paged.headLimitApplied,
33508
+ offsetApplied: paged.offsetApplied
33509
+ }
33510
+ };
33511
+ } else if (mode === "files_with_matches") {
33512
+ const files = splitNull(run.stdout).map(withoutDotSlash).filter(admitted);
33513
+ const paged = page(files, args);
33514
+ union = {
33515
+ case: "files",
33516
+ value: {
33517
+ files: paged.kept,
33518
+ totalFiles: files.length,
33519
+ clientTruncated: paged.clientTruncated,
33520
+ ripgrepTruncated,
33521
+ headLimitApplied: paged.headLimitApplied,
33522
+ offsetApplied: paged.offsetApplied
33523
+ }
33524
+ };
33525
+ } else {
33526
+ const counts = [];
33527
+ let start = 0;
33528
+ while (start < run.stdout.length) {
33529
+ const separator = run.stdout.indexOf(0, start);
33530
+ if (separator === -1)
33531
+ break;
33532
+ const end = run.stdout.indexOf(10, separator + 1);
33533
+ if (end === -1)
33534
+ break;
33535
+ const path = pathText(run.stdout.subarray(start, separator));
33536
+ const count = Number.parseInt(run.stdout.subarray(separator + 1, end).toString("ascii"), 10);
33537
+ if (path !== undefined) {
33538
+ const file = withoutDotSlash(path);
33539
+ if (Number.isFinite(count) && admitted(file))
33540
+ counts.push({ file, count });
33541
+ }
33542
+ start = end + 1;
33543
+ }
33544
+ const paged = page(counts, args);
33545
+ union = {
33546
+ case: "count",
33547
+ value: {
33548
+ counts: paged.kept,
33549
+ totalFiles: counts.length,
33550
+ totalMatches: counts.reduce((sum, entry) => sum + entry.count, 0),
33551
+ clientTruncated: paged.clientTruncated,
33552
+ ripgrepTruncated,
33553
+ headLimitApplied: paged.headLimitApplied,
33554
+ offsetApplied: paged.offsetApplied
33555
+ }
33556
+ };
33557
+ }
33558
+ return {
33559
+ result: {
33560
+ case: "success",
33561
+ value: {
33562
+ pattern: args.pattern ?? "",
33563
+ path: args.path ?? "",
33564
+ outputMode: mode,
33565
+ workspaceResults: { [cwd]: { result: union } }
33566
+ }
33567
+ }
33568
+ };
33569
+ } catch (error) {
33570
+ return { result: { case: "error", value: { error: errorMessage2(error) } } };
33571
+ }
33572
+ }
33573
+ function treeNode(absPath, processed) {
33574
+ return {
33575
+ absPath,
33576
+ childrenDirs: [],
33577
+ childrenFiles: [],
33578
+ childrenWereProcessed: processed,
33579
+ fullSubtreeExtensionCounts: {}
33580
+ };
33581
+ }
33582
+
33583
+ class TreeBuilder {
33584
+ rootPath;
33585
+ root;
33586
+ nodes = new Map;
33587
+ charactersUsed;
33588
+ budgetExceeded = false;
33589
+ constructor(rootPath) {
33590
+ this.rootPath = rootPath;
33591
+ this.root = treeNode(rootPath, true);
33592
+ this.nodes.set(rootPath, this.root);
33593
+ this.charactersUsed = rootPath.length;
33594
+ }
33595
+ ancestors(directory) {
33596
+ const chain = [];
33597
+ let current = directory;
33598
+ for (;; ) {
33599
+ const node = this.nodes.get(current);
33600
+ if (node)
33601
+ chain.push(node);
33602
+ if (current === this.rootPath)
33603
+ break;
33604
+ const parent = dirname3(current);
33605
+ if (parent === current || !parent.startsWith(this.rootPath))
33606
+ break;
33607
+ current = parent;
33608
+ }
33609
+ return chain;
33610
+ }
33611
+ ensureDirectory(directory) {
33612
+ const existing = this.nodes.get(directory);
33613
+ if (existing)
33614
+ return existing;
33615
+ const inside = relative3(this.rootPath, directory);
33616
+ if (inside === ".." || inside.startsWith(`..${sep4}`) || isAbsolute4(inside))
33617
+ return;
33618
+ const parent = this.ensureDirectory(dirname3(directory));
33619
+ const node = treeNode(directory, !this.budgetExceeded);
33620
+ this.nodes.set(directory, node);
33621
+ parent?.childrenDirs.push(node);
33622
+ return node;
33623
+ }
33624
+ add(file) {
33625
+ const name = basename2(file);
33626
+ const directory = dirname3(file);
33627
+ const node = this.ensureDirectory(directory);
33628
+ if (!node)
33629
+ return;
33630
+ if (!this.budgetExceeded && this.charactersUsed + name.length <= LS_CHARACTER_BUDGET) {
33631
+ node.childrenFiles.push({ name });
33632
+ this.charactersUsed += name.length;
33633
+ return;
33634
+ }
33635
+ const chain = this.ancestors(directory);
33636
+ if (!this.budgetExceeded) {
33637
+ this.budgetExceeded = true;
33638
+ for (const ancestor of chain)
33639
+ ancestor.childrenWereProcessed = false;
33640
+ }
33641
+ const extension = extname(name).replace(/^\./, "") || name;
33642
+ for (const ancestor of chain) {
33643
+ ancestor.fullSubtreeExtensionCounts[extension] = (ancestor.fullSubtreeExtensionCounts[extension] ?? 0) + 1;
33644
+ ancestor.numFiles = (ancestor.numFiles ?? 0) + 1;
33645
+ }
33646
+ }
33647
+ sorted() {
33648
+ const sort = (node) => {
33649
+ node.childrenDirs.sort((a, b) => basename2(a.absPath).localeCompare(basename2(b.absPath)));
33650
+ node.childrenFiles.sort((a, b) => a.name.localeCompare(b.name));
33651
+ node.childrenDirs.forEach(sort);
33652
+ };
33653
+ sort(this.root);
33654
+ return this.root;
33655
+ }
33656
+ }
33657
+ async function lsTool(path, args, options) {
33658
+ try {
33659
+ let stats;
33660
+ try {
33661
+ stats = await stat2(path);
33662
+ } catch (error) {
33663
+ if (errorCode(error) === "ENOENT") {
33664
+ return {
33665
+ result: { case: "error", value: { path, error: `Path does not exist: ${path}` } }
33666
+ };
33667
+ }
33668
+ return { result: { case: "error", value: { path, error: errorMessage2(error) } } };
33669
+ }
33670
+ if (!stats.isDirectory()) {
33671
+ return {
33672
+ result: { case: "error", value: { path, error: `Path is not a directory: ${path}` } }
33673
+ };
33674
+ }
33675
+ const rgArgs = [
33676
+ "--files",
33677
+ "--null",
33678
+ "--hidden",
33679
+ "--no-require-git",
33680
+ "--no-config",
33681
+ "--color=never"
33682
+ ];
33683
+ for (const ignore of args.ignore ?? [])
33684
+ rgArgs.push("--iglob", `!${ignore}`);
33685
+ const cursorIgnore = join6(path, ".cursorignore");
33686
+ if (existsSync2(cursorIgnore))
33687
+ rgArgs.push("--ignore-file", cursorIgnore);
33688
+ const run = await runRipgrep(options.ripgrep, rgArgs, path, args.timeoutMs ?? LS_TIMEOUT_MS);
33689
+ if (ripgrepFailed(run)) {
33690
+ return { result: { case: "error", value: { path, error: ripgrepError(run) } } };
33691
+ }
33692
+ const tree = new TreeBuilder(path);
33693
+ for (const line of splitNull(run.stdout)) {
33694
+ if (!line)
33695
+ continue;
33696
+ const file = resolve5(path, line);
33697
+ if (options.refused(file))
33698
+ continue;
33699
+ tree.add(file);
33700
+ }
33701
+ const directoryTreeRoot = tree.sorted();
33702
+ return run.timedOut ? { result: { case: "timeout", value: { directoryTreeRoot } } } : { result: { case: "success", value: { directoryTreeRoot } } };
33703
+ } catch (error) {
33704
+ return { result: { case: "error", value: { path, error: errorMessage2(error) } } };
33705
+ }
33706
+ }
33707
+
33708
+ // ../../bridges/cursor-bridge/src/read-boundary.ts
33709
+ var CURSOR_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.";
33710
+ function cursorCoordinatorReadBoundary(cwd, env = process.env) {
33711
+ return protectedDataDirBoundary(env[COORDINATOR_PROTECTED_DATA_DIR_ENV], [
33712
+ cwd,
33713
+ canonicalPath(cwd),
33714
+ configuredAttachmentRoot(env)
33715
+ ]);
33716
+ }
33717
+ function cursorToolPath(value, cwd) {
33718
+ let path = value.trim();
33719
+ if (path.startsWith("file://")) {
33720
+ try {
33721
+ path = fileURLToPath2(path);
33722
+ } catch {
33723
+ return;
33724
+ }
33725
+ }
33726
+ if (path === "~")
33727
+ path = homedir4();
33728
+ else if (path.startsWith("~/"))
33729
+ path = `${homedir4()}${sep5}${path.slice(2)}`;
33730
+ return isAbsolute5(path) ? resolve6(path) : resolve6(cwd, path);
33731
+ }
33732
+ function cursorReadBoundaryExecutors(boundary, cwd, options = {}) {
33733
+ const refused = (path) => readBoundaryRefuses(boundary, path, cwd);
33734
+ let ripgrep = options.ripgrep;
33735
+ const rg = () => ripgrep ??= resolveRipgrep(cwd);
33736
+ return {
33737
+ overrideReadExecutor: {
33738
+ async execute(_context, args) {
33739
+ const raw = args?.path ?? "";
33740
+ if (raw.trim() === "") {
33741
+ return {
33742
+ result: {
33743
+ case: "error",
33744
+ value: { path: raw, error: "path is empty or only whitespace" }
33745
+ }
33746
+ };
33747
+ }
33748
+ const path = cursorToolPath(raw, cwd);
33749
+ if (path === undefined || refused(path)) {
33750
+ return {
33751
+ result: {
33752
+ case: "rejected",
33753
+ value: { path: path ?? raw, reason: CURSOR_READ_BOUNDARY_REFUSAL }
33754
+ }
33755
+ };
33756
+ }
33757
+ return readFileTool(path, args);
33758
+ }
33759
+ },
33760
+ overrideGrepExecutor: {
33761
+ async execute(_context, args) {
33762
+ const named = args?.path?.trim() ? args.path : ".";
33763
+ const target = cursorToolPath(named, cwd);
33764
+ if (target === undefined || refused(target)) {
33765
+ return { result: { case: "error", value: { error: CURSOR_READ_BOUNDARY_REFUSAL } } };
33766
+ }
33767
+ return grepTool(args ?? {}, { cwd, target, refused, ripgrep: rg() });
33768
+ }
33769
+ },
33770
+ overrideLsExecutor: {
33771
+ async execute(_context, args) {
33772
+ const named = args?.path?.trim() ? args.path : ".";
33773
+ const path = cursorToolPath(named, cwd);
33774
+ if (path === undefined || refused(path)) {
33775
+ return {
33776
+ result: {
33777
+ case: "rejected",
33778
+ value: { path: path ?? named, reason: CURSOR_READ_BOUNDARY_REFUSAL }
33779
+ }
33780
+ };
33781
+ }
33782
+ return lsTool(path, args ?? {}, { refused, ripgrep: rg() });
33783
+ }
33784
+ }
33785
+ };
33786
+ }
33787
+
32654
33788
  // ../../bridges/cursor-bridge/src/sdk-runtime.ts
32655
33789
  import {
32656
33790
  Cursor as Cursor3,
@@ -33735,7 +34869,7 @@ async function prewarmCursorWorkspace(options, sandboxBoundary) {
33735
34869
  }
33736
34870
 
33737
34871
  // ../../bridges/cursor-bridge/src/change-evidence.ts
33738
- import { basename as basename2, dirname as dirname2, isAbsolute as isAbsolute2, join as join5, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
34872
+ import { basename as basename3, dirname as dirname4, isAbsolute as isAbsolute6, join as join8, relative as relative4, resolve as resolve7, sep as sep6 } from "node:path";
33739
34873
 
33740
34874
  // ../protocol/src/field-validation.ts
33741
34875
  function isPlainRecord(value) {
@@ -34141,7 +35275,7 @@ function workspaceObservationReportIssues(value) {
34141
35275
  import { createHash as createHash6, randomUUID } from "node:crypto";
34142
35276
  import { readdirSync as readdirSync2, readFileSync as readFileSync2 } from "node:fs";
34143
35277
  import { appendFile, mkdir as mkdir2, rename as rename2, rm, writeFile as writeFile2 } from "node:fs/promises";
34144
- import { join as join4 } from "node:path";
35278
+ import { join as join7 } from "node:path";
34145
35279
  var DEFAULT_EVIDENCE_SPOOL_LIMITS = {
34146
35280
  maxEntries: 2048,
34147
35281
  maxEntryBytes: 256 * 1024,
@@ -34404,7 +35538,7 @@ class ChangeEvidenceSpool {
34404
35538
  const lines = this.pendingLines.splice(0).join("");
34405
35539
  this.enqueueIo(async () => {
34406
35540
  await mkdir2(directory, { recursive: true, mode: 448 });
34407
- await appendFile(join4(directory, ENTRIES_FILE), lines, { mode: 384 });
35541
+ await appendFile(join7(directory, ENTRIES_FILE), lines, { mode: 384 });
34408
35542
  });
34409
35543
  }
34410
35544
  persistBody(id, bytes) {
@@ -34412,9 +35546,9 @@ class ChangeEvidenceSpool {
34412
35546
  if (!directory || this.restoring)
34413
35547
  return;
34414
35548
  this.enqueueIo(async () => {
34415
- const bodies = join4(directory, BODY_DIRECTORY);
35549
+ const bodies = join7(directory, BODY_DIRECTORY);
34416
35550
  await mkdir2(bodies, { recursive: true, mode: 448 });
34417
- await writeFile2(join4(bodies, bodyFileName(id)), bytes, { mode: 384, flag: "wx" }).catch((error) => {
35551
+ await writeFile2(join7(bodies, bodyFileName(id)), bytes, { mode: 384, flag: "wx" }).catch((error) => {
34418
35552
  if (error.code !== "EEXIST")
34419
35553
  throw error;
34420
35554
  });
@@ -34424,7 +35558,7 @@ class ChangeEvidenceSpool {
34424
35558
  const directory = this.directory;
34425
35559
  if (!directory)
34426
35560
  return;
34427
- this.enqueueIo(() => rm(join4(directory, BODY_DIRECTORY, bodyFileName(id)), { force: true }));
35561
+ this.enqueueIo(() => rm(join7(directory, BODY_DIRECTORY, bodyFileName(id)), { force: true }));
34428
35562
  }
34429
35563
  compactPersisted() {
34430
35564
  const directory = this.directory;
@@ -34435,7 +35569,7 @@ class ChangeEvidenceSpool {
34435
35569
  `);
34436
35570
  this.enqueueIo(async () => {
34437
35571
  await mkdir2(directory, { recursive: true, mode: 448 });
34438
- const file = join4(directory, ENTRIES_FILE);
35572
+ const file = join7(directory, ENTRIES_FILE);
34439
35573
  const temp = `${file}.${process.pid}.tmp`;
34440
35574
  await writeFile2(temp, body ? `${body}
34441
35575
  ` : "", { mode: 384 });
@@ -34447,10 +35581,10 @@ class ChangeEvidenceSpool {
34447
35581
  await this.io;
34448
35582
  }
34449
35583
  restore(directory) {
34450
- const bodyDirectory = join4(directory, BODY_DIRECTORY);
35584
+ const bodyDirectory = join7(directory, BODY_DIRECTORY);
34451
35585
  try {
34452
35586
  for (const name of readdirSync2(bodyDirectory)) {
34453
- const bytes = new Uint8Array(readFileSync2(join4(bodyDirectory, name)));
35587
+ const bytes = new Uint8Array(readFileSync2(join7(bodyDirectory, name)));
34454
35588
  const id = evidenceBodyId(bytes);
34455
35589
  if (bodyFileName(id) !== name)
34456
35590
  continue;
@@ -34462,7 +35596,7 @@ class ChangeEvidenceSpool {
34462
35596
  } catch {}
34463
35597
  let text = "";
34464
35598
  try {
34465
- text = readFileSync2(join4(directory, ENTRIES_FILE), "utf8");
35599
+ text = readFileSync2(join7(directory, ENTRIES_FILE), "utf8");
34466
35600
  } catch {
34467
35601
  return;
34468
35602
  }
@@ -35147,7 +36281,7 @@ function resolveCaptureExecutor(stateDirectory = stateDirectoryPath()) {
35147
36281
  return "unknown";
35148
36282
  if (stateDirectory === CONTAINER_STATE_DIRECTORY)
35149
36283
  return "container-worker";
35150
- if (basename2(dirname2(stateDirectory)) === HOST_STATE_ROOT)
36284
+ if (basename3(dirname4(stateDirectory)) === HOST_STATE_ROOT)
35151
36285
  return "host-worker";
35152
36286
  return "unknown";
35153
36287
  }
@@ -35179,7 +36313,7 @@ var runtime;
35179
36313
  function currentRuntime() {
35180
36314
  if (!runtime) {
35181
36315
  const directory = stateDirectoryPath();
35182
- const spool = new ChangeEvidenceSpool(directory ? { directory: join5(directory, "change-evidence") } : {});
36316
+ const spool = new ChangeEvidenceSpool(directory ? { directory: join8(directory, "change-evidence") } : {});
35183
36317
  runtime = createRuntime(spool, resolveCaptureExecutor());
35184
36318
  }
35185
36319
  return runtime;
@@ -35203,11 +36337,11 @@ function evidencePath(value) {
35203
36337
  if (!nonBlank(value))
35204
36338
  return;
35205
36339
  const raw = value.trim();
35206
- const absolute = isAbsolute2(raw) ? raw : resolve3(workingDirectory, raw);
35207
- const inside = relative2(workingDirectory, absolute);
35208
- if (!inside || inside.startsWith("..") || isAbsolute2(inside))
36340
+ const absolute = isAbsolute6(raw) ? raw : resolve7(workingDirectory, raw);
36341
+ const inside = relative4(workingDirectory, absolute);
36342
+ if (!inside || inside.startsWith("..") || isAbsolute6(inside))
35209
36343
  return raw;
35210
- return inside.split(sep2).join("/");
36344
+ return inside.split(sep6).join("/");
35211
36345
  }
35212
36346
  function cursorPatchFormat(text) {
35213
36347
  if (!text.startsWith("diff --git ") && !text.startsWith("--- "))
@@ -35637,8 +36771,8 @@ async function cursorMcpConfigRevision(state) {
35637
36771
  return { fingerprint: "read-only", sources: { user: "excluded", project: "excluded" } };
35638
36772
  }
35639
36773
  const [user, project] = await Promise.all([
35640
- fileDigest(join6(configHomeForTests ?? homedir3(), ".cursor", "mcp.json")),
35641
- policy.projectResources ? fileDigest(join6(workingDirectory, ".cursor", "mcp.json")) : Promise.resolve("excluded")
36774
+ fileDigest(join9(configHomeForTests ?? homedir5(), ".cursor", "mcp.json")),
36775
+ policy.projectResources ? fileDigest(join9(workingDirectory, ".cursor", "mcp.json")) : Promise.resolve("excluded")
35642
36776
  ]);
35643
36777
  return {
35644
36778
  fingerprint: createHash7("sha256").update(`user=${user}\x00project=${project}`).digest("base64url"),
@@ -35683,7 +36817,7 @@ async function attach(state) {
35683
36817
  const mcpServers = await cursorMcpServers(state.agentMcp, {
35684
36818
  readOnly,
35685
36819
  projectResources: policy.projectResources,
35686
- ...selectServers ? { userServers: selectServers, configHome: configHomeForTests ?? homedir3() } : {}
36820
+ ...selectServers ? { userServers: selectServers, configHome: configHomeForTests ?? homedir5() } : {}
35687
36821
  });
35688
36822
  const allowHttpMcp = !readOnly || policy.sandbox === "container";
35689
36823
  const [hosted, research] = readOnly ? await Promise.all([
@@ -35717,6 +36851,7 @@ async function attach(state) {
35717
36851
  selectsServers: selectServers !== undefined
35718
36852
  });
35719
36853
  state.loadsProjectRules = settingSources.includes("project");
36854
+ const readBoundary = readOnly ? cursorCoordinatorReadBoundary(workingDirectory) : null;
35720
36855
  const options = {
35721
36856
  apiKey,
35722
36857
  model: modelSelection(state.composer),
@@ -35726,7 +36861,8 @@ async function attach(state) {
35726
36861
  settingSources,
35727
36862
  sandboxOptions: { enabled: policy.sandbox === "provider" },
35728
36863
  autoReview: policy.sandbox === "provider" && policy.approvals === "auto-approve",
35729
- ...customTools ? { customTools } : {}
36864
+ ...customTools ? { customTools } : {},
36865
+ ...readBoundary ? { resourceProviderOptions: cursorReadBoundaryExecutors(readBoundary, workingDirectory) } : {}
35730
36866
  },
35731
36867
  ...readOnly ? {
35732
36868
  tools: [
@@ -36608,17 +37744,17 @@ function repositoryInstructionsBlock(path, content, truncated) {
36608
37744
  }
36609
37745
 
36610
37746
  // ../protocol/src/node/repository-instructions.ts
36611
- import { open as open3, realpath } from "node:fs/promises";
36612
- import { join as join7, relative as relative3, isAbsolute as isAbsolute3 } from "node:path";
37747
+ import { open as open5, realpath as realpath2 } from "node:fs/promises";
37748
+ import { join as join10, relative as relative5, isAbsolute as isAbsolute7 } from "node:path";
36613
37749
  var MAX_REPOSITORY_INSTRUCTIONS_BYTES = 256 * 1024;
36614
37750
  async function readRepositoryInstructions(cwd, maxBytes = MAX_REPOSITORY_INSTRUCTIONS_BYTES) {
36615
- const path = join7(cwd, REPOSITORY_INSTRUCTIONS_FILE);
37751
+ const path = join10(cwd, REPOSITORY_INSTRUCTIONS_FILE);
36616
37752
  try {
36617
- const [root, target] = await Promise.all([realpath(cwd), realpath(path)]);
36618
- const inside = relative3(root, target);
36619
- if (!inside || inside.startsWith("..") || isAbsolute3(inside))
37753
+ const [root, target] = await Promise.all([realpath2(cwd), realpath2(path)]);
37754
+ const inside = relative5(root, target);
37755
+ if (!inside || inside.startsWith("..") || isAbsolute7(inside))
36620
37756
  return;
36621
- const handle = await open3(target, "r");
37757
+ const handle = await open5(target, "r");
36622
37758
  try {
36623
37759
  const buffer = Buffer.alloc(maxBytes + 1);
36624
37760
  const { bytesRead } = await handle.read(buffer, 0, maxBytes + 1, 0);
@@ -36813,7 +37949,7 @@ var STRUCTURED_OUTPUT_FAILURE_CODES = new Set([
36813
37949
  import { randomUUID as randomUUID4 } from "node:crypto";
36814
37950
 
36815
37951
  // ../../bridges/cursor-bridge/src/command-changes.ts
36816
- import { resolve as resolve5 } from "node:path";
37952
+ import { resolve as resolve9 } from "node:path";
36817
37953
 
36818
37954
  // ../protocol/src/node/command-change-journal.ts
36819
37955
  var MAX_JOURNAL_BYTES = 8 * 1024 * 1024;
@@ -36842,12 +37978,12 @@ function isFileEditToolName(toolName) {
36842
37978
  // ../protocol/src/node/workspace-change-probe.ts
36843
37979
  import { randomUUID as randomUUID3 } from "node:crypto";
36844
37980
  import { rmSync as rmSync2 } from "node:fs";
36845
- import { copyFile, lstat, mkdtemp, rm as rm2 } from "node:fs/promises";
37981
+ import { copyFile, lstat as lstat2, mkdtemp, rm as rm2 } from "node:fs/promises";
36846
37982
  import { tmpdir } from "node:os";
36847
- import { delimiter, isAbsolute as isAbsolute4, join as join8, resolve as resolve4 } from "node:path";
37983
+ import { delimiter, isAbsolute as isAbsolute8, join as join11, resolve as resolve8 } from "node:path";
36848
37984
 
36849
37985
  // ../protocol/src/node/command-capture.ts
36850
- import { spawn } from "node:child_process";
37986
+ import { spawn as spawn2 } from "node:child_process";
36851
37987
  import { randomUUID as randomUUID2 } from "node:crypto";
36852
37988
  import { constants as fsConstants } from "node:fs";
36853
37989
  import * as captureFs from "node:fs";
@@ -37394,7 +38530,7 @@ function spawnCaptured(command, args, options, stdoutFd, stderrFd) {
37394
38530
  kill: (signal) => child.kill(signal)
37395
38531
  };
37396
38532
  }
37397
- const child = spawn(command, args, {
38533
+ const child = spawn2(command, args, {
37398
38534
  cwd: options.cwd,
37399
38535
  env,
37400
38536
  detached,
@@ -37955,8 +39091,8 @@ class WorkspaceChangeProbe {
37955
39091
  return;
37956
39092
  return {
37957
39093
  root,
37958
- indexPath: isAbsolute4(index) ? index : resolve4(cwd, index),
37959
- objectsPath: isAbsolute4(objects) ? objects : resolve4(cwd, objects)
39094
+ indexPath: isAbsolute8(index) ? index : resolve8(cwd, index),
39095
+ objectsPath: isAbsolute8(objects) ? objects : resolve8(cwd, objects)
37960
39096
  };
37961
39097
  }).catch(() => {
37962
39098
  return;
@@ -37999,8 +39135,8 @@ class WorkspaceChangeProbe {
37999
39135
  return;
38000
39136
  const { root, indexPath } = repo.location;
38001
39137
  const started = this.now();
38002
- const tempIndex = join8(this.tempDir, `orkestrator-probe-${randomUUID3()}.index`);
38003
- const objectDirectory = await mkdtemp(join8(this.tempDir, "orkestrator-probe-objects-"));
39138
+ const tempIndex = join11(this.tempDir, `orkestrator-probe-${randomUUID3()}.index`);
39139
+ const objectDirectory = await mkdtemp(join11(this.tempDir, "orkestrator-probe-objects-"));
38004
39140
  temporaryObjectDirectories.add(objectDirectory);
38005
39141
  let retained = false;
38006
39142
  try {
@@ -38017,7 +39153,7 @@ class WorkspaceChangeProbe {
38017
39153
  const included = [];
38018
39154
  const skipped = new Map;
38019
39155
  for (const path of untracked) {
38020
- const stats = await lstat(join8(root, path)).catch(() => {
39156
+ const stats = await lstat2(join11(root, path)).catch(() => {
38021
39157
  return;
38022
39158
  });
38023
39159
  if (!stats)
@@ -38253,7 +39389,7 @@ function classify(toolCall) {
38253
39389
  if (toolCall.type === "shell") {
38254
39390
  if (args.isBackground === true || args.runInBackground === true)
38255
39391
  return;
38256
- const cwd = nonBlank(args.workingDirectory) ? resolve5(workingDirectory, args.workingDirectory.trim()) : workingDirectory;
39392
+ const cwd = nonBlank(args.workingDirectory) ? resolve9(workingDirectory, args.workingDirectory.trim()) : workingDirectory;
38257
39393
  return { measure: true, cwd };
38258
39394
  }
38259
39395
  if (isFileEditToolName(toolCall.type) || CURSOR_FILE_EDIT_TOOLS.has(toolCall.type)) {
@@ -38880,211 +40016,8 @@ function errorText(error) {
38880
40016
  return error.trim();
38881
40017
  return "The Cursor turn failed";
38882
40018
  }
38883
- async function withTimeout3(work, timeoutMs) {
38884
- let timer;
38885
- try {
38886
- return await Promise.race([
38887
- work,
38888
- new Promise((_, reject) => {
38889
- timer = setTimeout(() => reject(new TurnTimeoutError), timeoutMs);
38890
- timer.unref();
38891
- })
38892
- ]);
38893
- } finally {
38894
- if (timer)
38895
- clearTimeout(timer);
38896
- }
38897
- }
38898
- // ../../bridges/cursor-bridge/src/prompt-attachments.ts
38899
- import { constants as constants2 } from "node:fs";
38900
- import { lstat as lstat2, open as open4, realpath as realpath2 } from "node:fs/promises";
38901
- import { isAbsolute as isAbsolute5, join as join9, relative as relative4, resolve as resolve6, sep as sep3 } from "node:path";
38902
-
38903
- class PromptAttachmentError extends Error {
38904
- code;
38905
- name = "PromptAttachmentError";
38906
- constructor(code, message) {
38907
- super(message);
38908
- this.code = code;
38909
- }
38910
- }
38911
- var MAX_IMAGE_ATTACHMENT_BYTES = 8 * 1024 * 1024;
38912
- var MAX_PROMPT_ATTACHMENTS = 20;
38913
- var MAX_TOTAL_IMAGE_ATTACHMENT_BYTES = 32 * 1024 * 1024;
38914
- var MAX_ATTACHMENT_PATH_BYTES = 4 * 1024;
38915
- var MAX_ATTACHMENT_FILENAME_BYTES = 1 * 1024;
38916
- var READ_CHUNK_BYTES = 64 * 1024;
38917
- function parsePromptAttachments(value) {
38918
- if (value === undefined || value === null)
38919
- return [];
38920
- if (!Array.isArray(value)) {
38921
- throw new PromptAttachmentError("attachment_invalid", "attachments must be an array");
38922
- }
38923
- if (value.length > MAX_PROMPT_ATTACHMENTS) {
38924
- throw new PromptAttachmentError("attachment_invalid", `A prompt can carry at most ${MAX_PROMPT_ATTACHMENTS} attachments`);
38925
- }
38926
- return value.map((candidate) => {
38927
- if (candidate === null || typeof candidate !== "object" || Array.isArray(candidate)) {
38928
- throw new PromptAttachmentError("attachment_invalid", "Each attachment must be an object");
38929
- }
38930
- const record = candidate;
38931
- if (record.type !== "image") {
38932
- throw new PromptAttachmentError("attachment_invalid", "Cursor accepts image attachments only");
38933
- }
38934
- const path = typeof record.path === "string" ? record.path.trim() : "";
38935
- if (!path || Buffer.byteLength(path) > MAX_ATTACHMENT_PATH_BYTES) {
38936
- throw new PromptAttachmentError("attachment_invalid", "Each attachment needs a workspace path");
38937
- }
38938
- if (path.includes("\x00")) {
38939
- throw new PromptAttachmentError("attachment_invalid", "An attachment path must not contain null bytes");
38940
- }
38941
- const filename = typeof record.filename === "string" && record.filename.trim() && Buffer.byteLength(record.filename) <= MAX_ATTACHMENT_FILENAME_BYTES ? record.filename : undefined;
38942
- return { type: "image", path, ...filename ? { filename } : {} };
38943
- });
38944
- }
38945
- async function readPromptImages(attachments, workspaceRoot) {
38946
- const images = [];
38947
- let totalBytes = 0;
38948
- for (const attachment of attachments) {
38949
- const { bytes, absolutePath } = await readWorkspaceImage(attachment.path, workspaceRoot);
38950
- totalBytes += bytes.length;
38951
- if (totalBytes > MAX_TOTAL_IMAGE_ATTACHMENT_BYTES) {
38952
- throw new PromptAttachmentError("attachment_too_large", "Image attachments exceed the 32MB total limit");
38953
- }
38954
- images.push({
38955
- data: bytes.toString("base64"),
38956
- mimeType: imageMimeType(bytes),
38957
- path: attachment.path,
38958
- absolutePath,
38959
- ...attachment.filename ? { filename: attachment.filename } : {}
38960
- });
38961
- }
38962
- return images;
38963
- }
38964
- function imageMimeType(bytes) {
38965
- if (bytes.length >= 8 && bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
38966
- return "image/png";
38967
- if (bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) {
38968
- return "image/jpeg";
38969
- }
38970
- if (bytes.length >= 6 && (bytes.subarray(0, 6).toString("latin1") === "GIF87a" || bytes.subarray(0, 6).toString("latin1") === "GIF89a"))
38971
- return "image/gif";
38972
- if (bytes.length >= 12 && bytes.subarray(0, 4).toString("latin1") === "RIFF" && bytes.subarray(8, 12).toString("latin1") === "WEBP")
38973
- return "image/webp";
38974
- throw new PromptAttachmentError("attachment_unsupported_format", "Image attachments must be PNG, JPEG, GIF, or WebP");
38975
- }
38976
- function attachmentErrorForFsFailure(error) {
38977
- const code = error?.code;
38978
- if (code === "ELOOP") {
38979
- return new PromptAttachmentError("attachment_symlink_not_allowed", "Image attachments must be regular workspace files, not symbolic links");
38980
- }
38981
- return new PromptAttachmentError("attachment_read_failed", "Image attachment could not be read from the workspace");
38982
- }
38983
- var BRIDGE_ATTACHMENT_ROOT_ENV = "ORKESTRATOR_BRIDGE_ATTACHMENT_ROOT";
38984
- function configuredAttachmentRoot(env = process.env) {
38985
- const value = env[BRIDGE_ATTACHMENT_ROOT_ENV]?.trim();
38986
- return value && isAbsolute5(value) ? resolve6(value) : undefined;
38987
- }
38988
- function attachmentContainmentRoot(filePath, workspaceRoot, extraRoot = configuredAttachmentRoot()) {
38989
- if (extraRoot && isAbsolute5(filePath) && isPathWithin(extraRoot, resolve6(filePath))) {
38990
- return extraRoot;
38991
- }
38992
- return resolve6(workspaceRoot);
38993
- }
38994
- function isPathWithin(root, candidate) {
38995
- if (candidate === root)
38996
- return true;
38997
- const childPath = relative4(root, candidate);
38998
- return Boolean(childPath) && childPath !== ".." && !childPath.startsWith(`..${sep3}`) && !isAbsolute5(childPath);
38999
- }
39000
- async function assertNoSymlinkComponents(root, targetPath) {
39001
- let currentPath = root;
39002
- for (const segment of relative4(root, targetPath).split(sep3).filter(Boolean)) {
39003
- currentPath = join9(currentPath, segment);
39004
- const stats = await lstat2(currentPath).catch((error) => {
39005
- throw attachmentErrorForFsFailure(error);
39006
- });
39007
- if (stats.isSymbolicLink()) {
39008
- throw new PromptAttachmentError("attachment_symlink_not_allowed", "Image attachments must be regular workspace files, not symbolic links");
39009
- }
39010
- }
39011
- }
39012
- async function assertOpenedWorkspaceFile(targetPath, canonicalRoot, openedStats) {
39013
- const [pathStats, canonicalTarget] = await Promise.all([
39014
- lstat2(targetPath),
39015
- realpath2(targetPath)
39016
- ]).catch((error) => {
39017
- throw attachmentErrorForFsFailure(error);
39018
- });
39019
- if (pathStats.isSymbolicLink()) {
39020
- throw new PromptAttachmentError("attachment_symlink_not_allowed", "Image attachments must be regular workspace files, not symbolic links");
39021
- }
39022
- if (!pathStats.isFile() || !openedStats.isFile() || pathStats.dev !== openedStats.dev || pathStats.ino !== openedStats.ino) {
39023
- throw new PromptAttachmentError("attachment_not_regular_file", "Image attachment is not a stable regular workspace file");
39024
- }
39025
- if (!isPathWithin(canonicalRoot, canonicalTarget)) {
39026
- throw new PromptAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace");
39027
- }
39028
- }
39029
- function assertStableRead(initial, final, bytesRead) {
39030
- if (final.dev !== initial.dev || final.ino !== initial.ino || final.size !== initial.size || final.size !== bytesRead || final.mtimeMs !== initial.mtimeMs || final.ctimeMs !== initial.ctimeMs) {
39031
- throw new PromptAttachmentError("attachment_changed", "Image attachment changed while it was being read; attach it again");
39032
- }
39033
- }
39034
- async function readWorkspaceImage(filePath, workspaceRoot) {
39035
- const lexicalRoot = attachmentContainmentRoot(filePath, workspaceRoot);
39036
- const targetPath = isAbsolute5(filePath) ? resolve6(filePath) : resolve6(lexicalRoot, filePath);
39037
- if (!isPathWithin(lexicalRoot, targetPath)) {
39038
- throw new PromptAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace");
39039
- }
39040
- const canonicalRoot = await realpath2(lexicalRoot).catch((error) => {
39041
- throw attachmentErrorForFsFailure(error);
39042
- });
39043
- await assertNoSymlinkComponents(lexicalRoot, targetPath);
39044
- const canonicalTarget = await realpath2(targetPath).catch((error) => {
39045
- throw attachmentErrorForFsFailure(error);
39046
- });
39047
- if (!isPathWithin(canonicalRoot, canonicalTarget)) {
39048
- throw new PromptAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace");
39049
- }
39050
- const noFollow = constants2.O_NOFOLLOW ?? 0;
39051
- const handle = await open4(targetPath, constants2.O_RDONLY | noFollow).catch((error) => {
39052
- throw attachmentErrorForFsFailure(error);
39053
- });
39054
- try {
39055
- const initialStats = await handle.stat();
39056
- await assertOpenedWorkspaceFile(targetPath, canonicalRoot, initialStats);
39057
- if (initialStats.size > MAX_IMAGE_ATTACHMENT_BYTES) {
39058
- throw new PromptAttachmentError("attachment_too_large", "Image attachment exceeds the 8MB limit");
39059
- }
39060
- const chunks = [];
39061
- let totalBytes = 0;
39062
- while (totalBytes <= MAX_IMAGE_ATTACHMENT_BYTES) {
39063
- const remaining = MAX_IMAGE_ATTACHMENT_BYTES + 1 - totalBytes;
39064
- const chunk = Buffer.allocUnsafe(Math.min(READ_CHUNK_BYTES, remaining));
39065
- const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
39066
- if (bytesRead === 0)
39067
- break;
39068
- chunks.push(chunk.subarray(0, bytesRead));
39069
- totalBytes += bytesRead;
39070
- }
39071
- if (totalBytes > MAX_IMAGE_ATTACHMENT_BYTES) {
39072
- throw new PromptAttachmentError("attachment_too_large", "Image attachment exceeds the 8MB limit");
39073
- }
39074
- if (totalBytes === 0) {
39075
- throw new PromptAttachmentError("attachment_empty", "Image attachment file is empty");
39076
- }
39077
- const finalStats = await handle.stat();
39078
- await assertOpenedWorkspaceFile(targetPath, canonicalRoot, finalStats);
39079
- assertStableRead(initialStats, finalStats, totalBytes);
39080
- return { bytes: Buffer.concat(chunks, totalBytes), absolutePath: targetPath };
39081
- } catch (error) {
39082
- if (error instanceof PromptAttachmentError)
39083
- throw error;
39084
- throw attachmentErrorForFsFailure(error);
39085
- } finally {
39086
- await handle.close();
39087
- }
40019
+ function withTimeout3(work, timeoutMs) {
40020
+ return boundedWaitOrThrow(work, timeoutMs, () => new TurnTimeoutError);
39088
40021
  }
39089
40022
  // ../protocol/src/node/transcript-window.ts
39090
40023
  import { Buffer as Buffer5 } from "node:buffer";
@@ -39460,6 +40393,11 @@ function applyBridgeLogPolicy(value, env = process.env) {
39460
40393
  return { status: 200, body: { applied: true, seq: policy.seq, diagnostics } };
39461
40394
  }
39462
40395
 
40396
+ // ../protocol/src/terminal-text.ts
40397
+ var MAX_STRING_LENGTH = 8 * 1024;
40398
+ var BUDGET_FLOOR = 4 * 1024;
40399
+ var MAX_MOVE = 4 * 1024;
40400
+
39463
40401
  // ../protocol/src/human-prompts.ts
39464
40402
  var HUMAN_PROMPT_SCAN_BYTES = 16 * 1024;
39465
40403
  var HUMAN_PROMPT_KINDS = new Set([
@@ -39542,18 +40480,8 @@ async function closeSessionPermanently(state, ackTimeoutMs = CLOSE_ACK_TIMEOUT_M
39542
40480
  state.closing = undefined;
39543
40481
  });
39544
40482
  }
39545
- const operation = state.closing;
39546
- let timer;
39547
- const timedOut = new Promise((resolve) => {
39548
- timer = setTimeout(() => resolve("pending"), ackTimeoutMs);
39549
- timer.unref?.();
39550
- });
39551
- try {
39552
- return await Promise.race([operation.then(() => "closed"), timedOut]);
39553
- } finally {
39554
- if (timer)
39555
- clearTimeout(timer);
39556
- }
40483
+ const outcome = await boundedWait(state.closing, ackTimeoutMs);
40484
+ return outcome.settled ? "closed" : "pending";
39557
40485
  }
39558
40486
  async function runClose(state) {
39559
40487
  if (!state.closeFenced) {
@@ -39602,6 +40530,27 @@ function requestStop(state) {
39602
40530
  }
39603
40531
  }
39604
40532
 
40533
+ // ../protocol/src/contract/ipc-error.ts
40534
+ var REGISTERED_ERROR_CODES = {
40535
+ "unknown-command": { domain: "text", command: "text" },
40536
+ "unsupported-version": { domain: "text", range: "range", command: "text" },
40537
+ "unsupported-field": { domain: "text", field: "text", command: "text" },
40538
+ "kanban-request-id-conflict": { record: "text" },
40539
+ "native-job-receipt-capacity": { limit: "count" },
40540
+ "native-agent-provider-session-missing": {},
40541
+ "container-lifecycle": { reason: "text" },
40542
+ "mcp-management": { reason: "text" },
40543
+ "pane-layout-revision-conflict": {},
40544
+ "design-revision-conflict": {},
40545
+ "prompt-queue-message-conflict": {},
40546
+ "unknown-node": {},
40547
+ "node-admin-refused": {},
40548
+ "node-scope-closed": {},
40549
+ "node-unavailable": {}
40550
+ };
40551
+ var REGISTERED_ERROR_CODE_LIST = Object.keys(REGISTERED_ERROR_CODES);
40552
+ var MAX_COUNT = 2 ** 31 - 1;
40553
+
39605
40554
  // ../protocol/src/mcp-management.ts
39606
40555
  var MCP_CONFIG_REPORTING_VERSION = 1;
39607
40556
  var MCP_MANAGEMENT_LIMITS = {