orkestrator 2.37.5-beta → 2.38.0-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.
@@ -263,6 +263,7 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
263
263
  "question.answers-received": "A parked question received its answers.",
264
264
  "question.stale": "An answer arrived for a question no longer pending; the route answered stale.",
265
265
  "question.wait-failed": "A parked question ended without an answer: cancelled, timed out or closed.",
266
+ "read-only-connection.bedrock-withheld": "A read-only turn did not take the user settings' Bedrock connection: it names no bearer token or static key pair, so the CLI would resolve AWS profiles, whose credential_process runs outside the read-only boundary.",
266
267
  "runtime.ended-under-resumed-turn": "The Claude runtime ended while a resumed root turn was still open.",
267
268
  "server.listening": "The HTTP server is listening.",
268
269
  "server.starting": "The HTTP server is about to bind.",
@@ -885,28 +886,28 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
885
886
  "credential-plugin.skipped": "A host OpenCode server started without the credential plugin, so its tools inherit its password; `reason` says why.",
886
887
  "host-database.separated": "Host OpenCode uses Orkestrator's own database because the shared one has no `session` table (an OpenCode 2 database); `reason` says why.",
887
888
  "host-database.unreadable": "The shared OpenCode database could not be inspected, so host OpenCode opens it as usual. Error class only.",
888
- "login.opencode2-mirror-failed": "A provider sign-in change reached OpenCode 1 but could not be copied into the OpenCode 2 database; the user is told to retry. Error class only."
889
+ "login.export-failed": "A provider sign-in change was saved in the host OpenCode database, but the `auth.json` copy containers are handed could not be updated; the user is told to retry. Error class only."
889
890
  }
890
891
  },
891
892
  "native-agent.opencode2": {
892
- description: "The OpenCode 2.x provider: its event monitor, steering, routing, host and container servers.",
893
+ description: "The OpenCode provider (OpenCode 2.x): its event monitor, steering, session instructions, host and container servers.",
893
894
  events: {
894
895
  "events.dropped": "The 2.x event stream ended or failed, so reads go to the server until it reconnects. Error class only.",
896
+ "monitor.silent": "The 2.x event stream sent a heartbeat and then went quiet, so it is replaced. `silenceMs` only.",
895
897
  "steer.unconfirmed": "A 2.x steer got no definite answer, so its delivery is reconciled from history. Error class only.",
896
898
  "provider.dispose-failed": "Disposing the 2.x provider of a replaced server failed. Error class only.",
899
+ "location.reload-unconfirmed": "After a 2.x location reload, the read that waits for the rebuilt location failed; catalogues are re-read anyway. Error class only.",
900
+ "credential.legacy-reconciled": "A host 2.x database from before OpenCode 1.x was retired was reconciled with auth.json once. Counts of credentials written and removed only.",
901
+ "credential.legacy-reconcile-failed": "The one-time reconcile of a host 2.x database with auth.json failed; the next host start retries it. Error class only.",
897
902
  "transcript.unknown-row": "A 2.x history row of a kind the transcript does not know was dropped (a newer server). Its kind name only, once per kind.",
898
903
  "mcp.remove-failed": "Removing a closed session's Orkestrator MCP server from the 2.x server failed. Error class only.",
899
- "protocol.select-failed": "A workflow could not read the OpenCode line setting, so its new session takes 1.x. Error class only.",
900
- "host-server.ready": "A local environment's (or a coordinator conversation's) 2.x server answered `/api/info` as 2.x. Environment id, pid and whether it is a coordinator's only.",
901
904
  "coordinator-research.unavailable": "A coordinator's 2.x server could not register its research servers, so the conversation runs without them until the server restarts. Error class only.",
902
- "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.",
903
905
  "container-server.launched": "The start script of a container environment's 2.x server was run. Container port only.",
904
906
  "container-server.ready": "A container environment's 2.x server this backend started answered `/api/info` as 2.x. Environment id only.",
905
907
  "container-server.cleanup-failed": "Cleanup after OpenCode startup failed; step names only, while the original startup error is preserved.",
906
908
  "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.",
907
- "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.",
908
- "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.",
909
- "credential.server-exit-unclean": "The private 2.x server started to copy a sign-in did not stop cleanly. Error class only.",
909
+ "instructions.unavailable": "The 2.x server refused Orkestrator's shared instructions entry for a session, which runs without them. Error class only.",
910
+ "host-database-server.exit-unclean": "A private 2.x server started on the host database (provider sign-in, the host model catalogue) did not stop cleanly. Error class only.",
910
911
  "user-config.mirror-failed": "The user's global OpenCode configuration could not be mirrored for a host 2.x server, which starts without it. Error class only.",
911
912
  "user-config.unreadable": "A file of the user's OpenCode configuration could not be read for the 2.x mirror. `source`, the file's name and the error code only.",
912
913
  "user-config.rejected": "Files of the user's OpenCode configuration are not a JSONC object, so the 2.x mirror leaves them out. `source` and file names only, never contents.",
@@ -957,7 +958,7 @@ var RUNTIME_LOG_AREAS = defineLogAreas({
957
958
  description: "This process's event loop. A stall of 10 seconds or more is written at error, so no level hides it.",
958
959
  events: {
959
960
  stalled: {
960
- description: "A timer fired late, so every request in that window waited. In the backend the line also names what ran: `storageMs` and the `storage*` fields describe the slow SQLite calls in the window (`operation.slow` in `storage`), `commandsInFlight` and `commands` the commands running, `blockingCommand` one whose synchronous part overlapped it, and `jobsInWindow` and `jobs` the recurring jobs that ran around it. `cpuMs` is the CPU time the process used in the window: near `lagMs` its own thread was busy, far below it the thread waited.",
961
+ description: "A timer fired late, so every request in that window waited. In the backend the line also names what ran: `storageMs` and the `storage*` fields describe the slow SQLite calls in the window (`operation.slow` in `storage`), `storageCalls` and `storageCallMs` every SQLite call that ended in it, slow or not (`storageMainCallMs` and `storageLedgerCallMs` per database), `commandsInFlight` and `commands` the commands running, `blockingCommand` one whose synchronous part overlapped it, and `jobsInWindow` and `jobs` the recurring jobs that ran around it. `cpuMs` is the CPU time the process used in the window: near `lagMs` its own thread was busy, far below it the thread waited.",
961
962
  essential: true,
962
963
  minLevel: "error",
963
964
  fields: {
@@ -970,6 +971,10 @@ var RUNTIME_LOG_AREAS = defineLogAreas({
970
971
  storageTable: "label",
971
972
  storageLongestMs: "number",
972
973
  storageBusy: "boolean",
974
+ storageCalls: "number",
975
+ storageCallMs: "number",
976
+ storageMainCallMs: "number",
977
+ storageLedgerCallMs: "number",
973
978
  commandsInFlight: "number",
974
979
  blockingCommandMs: "number",
975
980
  jobsInWindow: "number"
@@ -1152,6 +1157,7 @@ var TMUX_LOG_AREAS = defineLogAreas({
1152
1157
  "cli.fast-mode-unsupported": "The claude CLI lacks --settings, so it launches without fast mode.",
1153
1158
  "cli.effort-unsupported": "The claude CLI lacks --effort, so it launches without it.",
1154
1159
  "interactive.snapshot-failed": "An interactive snapshot failed; expected while a pane is closing.",
1160
+ "interactive.lease-lapsed": "No client renewed an interactive terminal for 45 seconds, so its capture loop stopped.",
1155
1161
  "signal.arm-failed": "The Claude state signal could not be armed.",
1156
1162
  "signal.degraded": "The Claude state signal missed a change or rang too often, so polling stays at one second until it is re-armed.",
1157
1163
  "hook-signal.arm-failed": "The tmux hook doorbell could not be armed.",
@@ -1274,7 +1280,6 @@ var STORAGE_LOG_AREAS = defineLogAreas({
1274
1280
  "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.",
1275
1281
  "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.",
1276
1282
  "lease.heartbeat-failed": "A held lease's heartbeat failed, which shortens the lease; the next one retries.",
1277
- "scrub.vacuum-failed": "Deleted-content page reclamation failed; the checkpoint is attempted independently.",
1278
1283
  "scrub.checkpoint-failed": "Deleted content could not be scrubbed from the WAL yet because the truncating checkpoint failed or a reader held an older snapshot; it is retried without waiting until it succeeds.",
1279
1284
  "upkeep.vacuum-failed": "Periodic page reclamation failed; the next upkeep pass retries.",
1280
1285
  "upkeep.finished": "One periodic upkeep pass ended: `optimizeMs` is how long refreshing planner statistics held the event loop, `released` and `left` the free pages returned and still free, `releaseMs` the release child's run and `stop` why it ended (`done`, `budget`, `busy`, `no-progress`, `slow-step`, `not-incremental`, `no-free-pages`, `failed`).",
@@ -1462,7 +1467,17 @@ var REVIEW_LOG_AREAS = defineLogAreas({
1462
1467
  "fix-outcome.read-failed": "Reading an interactive fix's outcome failed; it stays pending.",
1463
1468
  "fix-usage.read-failed": "Reading an Address Findings session's token usage failed.",
1464
1469
  "result.consume-deferred": "Consuming a workflow result failed; it stays staged and is retried.",
1465
- "failure-triage.failed": "Classifying a review package's failing tests failed; the package is sealed without the triage and says so."
1470
+ "failure-triage.failed": "Classifying a review package's failing tests failed; the package is sealed without the triage and says so.",
1471
+ "consolidation.budget-exceeded": {
1472
+ description: "A panel's reports did not fit one consolidation turn even after optional prose was removed, so consolidation failed before dispatch. Counts only.",
1473
+ essential: true,
1474
+ fields: {
1475
+ reviewers: "number",
1476
+ sourceFindings: "number",
1477
+ compactBytes: "number",
1478
+ maxBytes: "number"
1479
+ }
1480
+ }
1466
1481
  }
1467
1482
  },
1468
1483
  "pull-request": {
@@ -1558,6 +1573,7 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1558
1573
  "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; that connection then sends nothing more.",
1559
1574
  "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.",
1560
1575
  "opencode.project-config-filtered": "Values were left out of a checkout's OpenCode configuration before a launched server reads it: 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.",
1576
+ "daemon.rootless-live-restore": "The Docker daemon is rootless and has live-restore on, which a rootless restart cannot honour: the new daemon reports every container exited while the old containers' processes keep running with no network, so turn live-restore off in its daemon.json. Written once per backend.",
1561
1577
  "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.",
1562
1578
  "lifecycle-event.reconcile-failed": "Reconciling an environment after a container start or stop event failed; the next status read retries.",
1563
1579
  "login-keeper.pass-failed": "A Claude login keeper pass failed; the next interval retries.",
@@ -1565,13 +1581,15 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1565
1581
  "login-keeper.refresh-not-extended": "Refreshing the host Claude login did not extend its expiry.",
1566
1582
  "login-keeper.refresh-check-failed": "Checking the host Claude login after a refresh failed.",
1567
1583
  "login-watcher.pass-failed": "A container login file watcher pass failed; the next one retries.",
1584
+ "login-watcher.opencode-renewal-failed": "OAuth logins a host OpenCode server refreshed could not be copied into the `auth.json` containers are handed; the files are still delivered and the next pass retries. Error class only.",
1568
1585
  "lifecycle.record-failure-failed": "A failed container operation could not be recorded.",
1569
1586
  "lifecycle.reconcile-failed": "Reconciling one environment's container operation failed; the next pass retries.",
1570
1587
  "replacement.clear-terminals-failed": "Terminal sessions could not be cleared after a container replacement.",
1571
1588
  "recovery.clear-terminals-failed": "Terminal sessions could not be cleared after a recovery restore.",
1572
1589
  "github-ranges.seed-not-copied": "The GitHub ranges seed could not be copied into a container, so its firewall fetches them.",
1573
1590
  "availability.probe-failed": "Docker is not available; written when the diagnostic changes. Fixed-shape metadata only: messages can hold daemon endpoints.",
1574
- "start.port-collision-retrying": "An automatic host port collided on start, so it is retried once with fresh ports.",
1591
+ "start.port-collision-retrying": "An automatic host port collided on start, so it is retried (up to three times): with fresh ports, or, when `backendChosen`, on the same backend-chosen port after a pause.",
1592
+ "host-ports.owned-list-failed": "Docker could not list the host ports the backend chose for this owner's other containers, so a new rootless container's ports were chosen avoiding only this process's recent choices.",
1575
1593
  "writer-lease.lost": {
1576
1594
  description: "This backend lost the registry writer lease, for the fixed `reason` given. Schedules stop and container changes are refused until it restarts.",
1577
1595
  essential: true,
@@ -1685,7 +1703,8 @@ var DESIGN_LOG_AREAS = defineLogAreas({
1685
1703
  "startup.step-failed": "One part of design startup failed; `step` says which.",
1686
1704
  "legacy.retire-failed": "A migrated legacy design could not be retired.",
1687
1705
  "profiles.swept": "Design startup removed stale browser profiles.",
1688
- "session-link.record-failed": "A closing conversation could not be recorded on a design link."
1706
+ "session-link.record-failed": "A closing conversation could not be recorded on a design link.",
1707
+ "session-link.archived-read-failed": "Whether design links' conversations are archived could not be read; they read as not archived."
1689
1708
  }
1690
1709
  }
1691
1710
  });
@@ -1754,9 +1773,14 @@ var NODES_LOG_AREAS = defineLogAreas({
1754
1773
  // ../protocol/src/log-vocabulary/linear.ts
1755
1774
  var LINEAR_LOG_AREAS = defineLogAreas({
1756
1775
  linear: {
1757
- description: "Linear issues read for build actions.",
1776
+ description: "Linear issues read for build actions, project board links and the Linear connection across machines.",
1758
1777
  events: {
1759
- "comments.load-failed": "An issue's comments could not be loaded; the issue still renders without them."
1778
+ "board-link.conflict": "Two of this machine's projects were linked to one Linear board on different machines; the link changed last kept it and the other was cleared.",
1779
+ "comments.load-failed": "An issue's comments could not be loaded; the issue still renders without them.",
1780
+ "connection.revoked-by-sync": "A disconnect made on another machine named this machine's Linear key, so it was cleared here.",
1781
+ "connection.exported-to-command-node": "An attached command node copied this machine's Linear key at the user's request (the key is not logged).",
1782
+ "sync.failed": "A Linear board-link sync with a node failed; it is retried on the next pass.",
1783
+ "sync.older-node": "A node does not sync Linear board links yet; it keeps its own links."
1760
1784
  }
1761
1785
  }
1762
1786
  });
@@ -1767,7 +1791,9 @@ var USAGE_HISTORY_LOG_AREAS = defineLogAreas({
1767
1791
  description: "Recorded agent token usage.",
1768
1792
  events: {
1769
1793
  "record.failed": "Agent usage could not be recorded; a later read counts it.",
1770
- "prune.failed": "Pruning recorded usage failed; the next prune retries."
1794
+ "prune.failed": "Pruning recorded usage failed; the next prune retries.",
1795
+ "settled-read.failed": "Reading a settled turn's usage failed; the session's next outcome or state read retries it.",
1796
+ "settled-read.abandoned": "A settled turn's usage was given up after repeated failed reads or a full retry queue; only a later projection can still count it."
1771
1797
  }
1772
1798
  }
1773
1799
  });
@@ -1966,7 +1992,9 @@ var WEB_CLAUDE_TMUX_LOG_AREAS = defineLogAreas({
1966
1992
  "files.load-failed": "The file list for @mentions could not be loaded.",
1967
1993
  "clipboard.image-failed": "An image pasted into the interactive terminal could not be saved.",
1968
1994
  "terminal.resize-failed": "Resizing the interactive terminal's session failed.",
1969
- "terminal.recover-failed": "The interactive terminal could not reattach to its session."
1995
+ "terminal.recover-failed": "The interactive terminal could not reattach to its session.",
1996
+ "terminal.lease-lapsed": "The backend had dropped the interactive terminal after missed renewals; a new one is attached (once the page is visible).",
1997
+ "terminal.renew-failed": "Renewing the interactive terminal's lease failed; the next renewal retries."
1970
1998
  }
1971
1999
  }
1972
2000
  });
@@ -8760,20 +8788,177 @@ function withReadOnlyGitConfig(turnPolicy, environment) {
8760
8788
  return next;
8761
8789
  }
8762
8790
 
8763
- // ../../bridges/claude-bridge/src/services/coordinator-skills.ts
8764
- import { createHash as createHash4, randomBytes } from "node:crypto";
8765
- import {
8766
- mkdir as mkdir2,
8767
- readdir as readdir2,
8768
- readFile as readFile3,
8769
- realpath,
8770
- rename as rename2,
8771
- rm as rm2,
8772
- stat as stat2,
8773
- symlink,
8774
- writeFile as writeFile2
8775
- } from "node:fs/promises";
8776
- import { isAbsolute, join as join3 } from "node:path";
8791
+ // ../../bridges/claude-bridge/src/services/json-file-cache.ts
8792
+ import { createHash as createHash4 } from "node:crypto";
8793
+ import { readFile as readFile3, stat as stat2 } from "node:fs/promises";
8794
+ var SEPARATOR = "\x00";
8795
+ var slices = new Map;
8796
+ var readCohorts = new Map;
8797
+ var parseCounts = new Map;
8798
+ var beforeStatForTesting = null;
8799
+ function fingerprintOf(stats) {
8800
+ return `${stats.dev}:${stats.ino}:${stats.size}:${stats.mtimeMs}`;
8801
+ }
8802
+ function forgetFile(filePath) {
8803
+ const prefix = `${filePath}${SEPARATOR}`;
8804
+ for (const key of slices.keys()) {
8805
+ if (key.startsWith(prefix))
8806
+ slices.delete(key);
8807
+ }
8808
+ }
8809
+ function joinReadCohort(filePath) {
8810
+ const existing = readCohorts.get(filePath);
8811
+ if (existing) {
8812
+ existing.readers += 1;
8813
+ return existing;
8814
+ }
8815
+ const cohort = { readers: 1, parses: new Map };
8816
+ readCohorts.set(filePath, cohort);
8817
+ return cohort;
8818
+ }
8819
+ function leaveReadCohort(filePath, cohort) {
8820
+ cohort.readers -= 1;
8821
+ if (cohort.readers === 0 && readCohorts.get(filePath) === cohort) {
8822
+ readCohorts.delete(filePath);
8823
+ }
8824
+ }
8825
+ function parseOnce(filePath, fingerprint, cohort) {
8826
+ const existing = cohort.parses.get(fingerprint);
8827
+ if (existing)
8828
+ return existing;
8829
+ const parse = (async () => {
8830
+ parseCounts.set(filePath, (parseCounts.get(filePath) ?? 0) + 1);
8831
+ let bytes;
8832
+ try {
8833
+ bytes = await readFile3(filePath);
8834
+ } catch {
8835
+ return { parsed: null, digest: null };
8836
+ }
8837
+ const digest = createHash4("sha256").update(bytes).digest("base64url");
8838
+ try {
8839
+ return { parsed: JSON.parse(bytes.toString("utf-8")), digest };
8840
+ } catch {
8841
+ return { parsed: null, digest };
8842
+ }
8843
+ })();
8844
+ cohort.parses.set(fingerprint, parse);
8845
+ return parse;
8846
+ }
8847
+ async function readJsonSliceCached(filePath, sliceKey, select) {
8848
+ return (await readJsonSliceCachedWithDigest(filePath, sliceKey, select)).value;
8849
+ }
8850
+ async function readJsonSliceCachedWithDigest(filePath, sliceKey, select) {
8851
+ const cohort = joinReadCohort(filePath);
8852
+ try {
8853
+ await beforeStatForTesting?.(filePath);
8854
+ let fingerprint;
8855
+ try {
8856
+ fingerprint = fingerprintOf(await stat2(filePath));
8857
+ } catch {
8858
+ forgetFile(filePath);
8859
+ return { value: null, digest: null };
8860
+ }
8861
+ const key = `${filePath}${SEPARATOR}${sliceKey}`;
8862
+ const cached = slices.get(key);
8863
+ if (cached && cached.fingerprint === fingerprint) {
8864
+ return { value: cached.value, digest: cached.digest };
8865
+ }
8866
+ const { parsed, digest } = await parseOnce(filePath, fingerprint, cohort);
8867
+ let value = null;
8868
+ if (parsed !== null && parsed !== undefined) {
8869
+ try {
8870
+ value = select(parsed) ?? null;
8871
+ } catch {
8872
+ value = null;
8873
+ }
8874
+ }
8875
+ slices.set(key, { fingerprint, value, digest });
8876
+ return { value, digest };
8877
+ } finally {
8878
+ leaveReadCohort(filePath, cohort);
8879
+ }
8880
+ }
8881
+
8882
+ // ../protocol/src/coordinator-web-research.ts
8883
+ var COORDINATOR_WEB_RESEARCH_MODES = ["off", "search", "search-and-mcp"];
8884
+ var DEFAULT_COORDINATOR_RESEARCH_MCP_SERVERS = Object.freeze([{ name: "context7", url: "https://mcp.context7.com/mcp" }]);
8885
+ var MAX_COORDINATOR_RESEARCH_MCP_SERVERS = 8;
8886
+ var COORDINATOR_WEB_RESEARCH_ENV = "ORKESTRATOR_COORDINATOR_WEB_RESEARCH";
8887
+ var COORDINATOR_RESEARCH_MCP_ENV = "ORKESTRATOR_COORDINATOR_RESEARCH_MCP";
8888
+ var RESERVED_SERVER_NAME = /^orkestrator/;
8889
+ var SERVER_NAME = /^[a-z0-9][a-z0-9-]{0,31}$/;
8890
+ function isCoordinatorWebResearch(value) {
8891
+ return typeof value === "string" && COORDINATOR_WEB_RESEARCH_MODES.includes(value);
8892
+ }
8893
+ function coordinatorResearchMcpServerProblem(server) {
8894
+ if (!SERVER_NAME.test(server.name)) {
8895
+ return "Use 1 to 32 lowercase letters, digits or hyphens for the name.";
8896
+ }
8897
+ if (RESERVED_SERVER_NAME.test(server.name))
8898
+ return "Names starting with orkestrator are reserved.";
8899
+ let url;
8900
+ try {
8901
+ url = new URL(server.url);
8902
+ } catch {
8903
+ return "The URL is not valid.";
8904
+ }
8905
+ if (url.protocol !== "https:")
8906
+ return "Only https:// research servers are allowed.";
8907
+ if (url.username || url.password)
8908
+ return "Credentials in the URL are not allowed.";
8909
+ return;
8910
+ }
8911
+ function normalizeCoordinatorResearchMcpServers(value) {
8912
+ if (value === undefined)
8913
+ return DEFAULT_COORDINATOR_RESEARCH_MCP_SERVERS.map((s) => ({ ...s }));
8914
+ if (!Array.isArray(value))
8915
+ return [];
8916
+ const servers = [];
8917
+ const names = new Set;
8918
+ for (const entry of value) {
8919
+ if (servers.length >= MAX_COORDINATOR_RESEARCH_MCP_SERVERS)
8920
+ break;
8921
+ if (!entry || typeof entry !== "object")
8922
+ continue;
8923
+ const { name, url } = entry;
8924
+ if (typeof name !== "string" || typeof url !== "string")
8925
+ continue;
8926
+ const server = { name: name.trim(), url: url.trim() };
8927
+ if (coordinatorResearchMcpServerProblem(server) || names.has(server.name))
8928
+ continue;
8929
+ names.add(server.name);
8930
+ servers.push(server);
8931
+ }
8932
+ return servers;
8933
+ }
8934
+ function coordinatorWebResearchFromEnv(env) {
8935
+ const value = env[COORDINATOR_WEB_RESEARCH_ENV];
8936
+ return isCoordinatorWebResearch(value) ? value : "off";
8937
+ }
8938
+ function coordinatorResearchMcpServersFromEnv(env) {
8939
+ if (coordinatorWebResearchFromEnv(env) !== "search-and-mcp")
8940
+ return [];
8941
+ const raw = env[COORDINATOR_RESEARCH_MCP_ENV];
8942
+ if (!raw)
8943
+ return [];
8944
+ try {
8945
+ return normalizeCoordinatorResearchMcpServers(JSON.parse(raw));
8946
+ } catch {
8947
+ return [];
8948
+ }
8949
+ }
8950
+ var COORDINATOR_DENIED = Object.freeze([
8951
+ "file.write",
8952
+ "file.patch",
8953
+ "shell.mutate",
8954
+ "network"
8955
+ ]);
8956
+ function coordinatorCapabilityPolicy(mode) {
8957
+ return {
8958
+ deny: [...COORDINATOR_DENIED],
8959
+ ...mode === "off" ? {} : { allow: ["web.search"] }
8960
+ };
8961
+ }
8777
8962
  // ../protocol/src/coordinator.ts
8778
8963
  var COORDINATOR_COMMAND_SANDBOX_ENV = "ORKESTRATOR_COORDINATOR_COMMAND_SANDBOX";
8779
8964
  var COORDINATOR_PROTECTED_DATA_DIR_ENV = "ORKESTRATOR_COORDINATOR_PROTECTED_DATA_DIR";
@@ -8787,6 +8972,7 @@ var COORDINATOR_CONTROL_TOOL_NAMES = Object.freeze([
8787
8972
  "mark_topic",
8788
8973
  "mark_question",
8789
8974
  "ack_message",
8975
+ "add_linear_comment",
8790
8976
  "add_ticket_comment",
8791
8977
  "address_multi_review",
8792
8978
  "adopt_workflow",
@@ -8798,6 +8984,7 @@ var COORDINATOR_CONTROL_TOOL_NAMES = Object.freeze([
8798
8984
  "cancel_schedule",
8799
8985
  "clear_worker_goal",
8800
8986
  "compare_project_files",
8987
+ "create_linear_issue",
8801
8988
  "create_pr",
8802
8989
  "create_schedule",
8803
8990
  "create_ticket",
@@ -8810,6 +8997,7 @@ var COORDINATOR_CONTROL_TOOL_NAMES = Object.freeze([
8810
8997
  "get_feature_plan",
8811
8998
  "get_graph_run",
8812
8999
  "get_launch_options",
9000
+ "get_linear_issue",
8813
9001
  "get_message",
8814
9002
  "get_message_status",
8815
9003
  "get_multi_review",
@@ -8829,6 +9017,8 @@ var COORDINATOR_CONTROL_TOOL_NAMES = Object.freeze([
8829
9017
  "list_agents",
8830
9018
  "list_environments",
8831
9019
  "list_graph_templates",
9020
+ "list_linear_board_options",
9021
+ "list_linear_issues",
8832
9022
  "list_mailboxes",
8833
9023
  "list_nodes",
8834
9024
  "list_projects",
@@ -8869,1290 +9059,1262 @@ var COORDINATOR_CONTROL_TOOL_NAMES = Object.freeze([
8869
9059
  "switch_provider_account",
8870
9060
  "set_account_auto_switch",
8871
9061
  "transfer_files",
9062
+ "update_linear_issue",
8872
9063
  "update_schedule",
8873
9064
  "update_ticket"
8874
9065
  ]);
8875
9066
  var COORDINATOR_PROJECT_HOME_MESSAGE_WINDOW_MS = 3 * 60 * 60000;
8876
9067
 
8877
- // ../../bridges/claude-bridge/src/services/coordinator-skills.ts
8878
- var KEPT_FRONTMATTER_KEYS = Object.freeze([
8879
- "name",
8880
- "description",
8881
- "when_to_use",
8882
- "argument-hint",
8883
- "arguments",
8884
- "disable-model-invocation",
8885
- "user-invocable",
8886
- "version"
8887
- ]);
8888
- var MIRROR_FORMAT = 1;
8889
- var MAX_SKILLS_PER_SOURCE = 256;
8890
- var MAX_SKILL_FILE_BYTES = 1024 * 1024;
8891
- var MAX_ENTRIES_PER_SKILL = 256;
8892
- var KEPT_OLD_MIRRORS = 4;
8893
- var SKILL_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
8894
- var FRONTMATTER = /^?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;
8895
- function coordinatorSkillSources(cwd, env = process.env) {
8896
- const userDir = env[COORDINATOR_CLAUDE_USER_SKILLS_DIR_ENV]?.trim();
8897
- return [
8898
- ...userDir && isAbsolute(userDir) ? [{ plugin: "user-skills", dir: userDir }] : [],
8899
- { plugin: "project-skills", dir: join3(cwd, ".claude", "skills") }
8900
- ];
9068
+ // ../../bridges/claude-bridge/src/services/mcp-tool-prefix.ts
9069
+ function claudeMcpToolPrefix(name) {
9070
+ let normalized = name.replace(/[^a-zA-Z0-9_-]/g, "_");
9071
+ if (name.startsWith("claude.ai ")) {
9072
+ normalized = normalized.replace(/_+/g, "_").replace(/^_|_$/g, "");
9073
+ }
9074
+ return `mcp__${normalized}__`;
8901
9075
  }
8902
- async function coordinatorSkillPlugins(sources, root = claudeCoordinatorSkillPluginsDir()) {
8903
- const plugins = [];
8904
- const skills = [];
8905
- for (const source of sources) {
9076
+
9077
+ // ../../bridges/claude-bridge/src/services/read-only-path-boundary.ts
9078
+ import { join as join4 } from "node:path";
9079
+
9080
+ // ../protocol/src/node/coordinator-read-boundary.ts
9081
+ import { realpathSync } from "node:fs";
9082
+ import { homedir as homedir2 } from "node:os";
9083
+ import { dirname as dirname2, isAbsolute, join as join3, parse, resolve as resolve2, sep } from "node:path";
9084
+ function canonicalPath(path) {
9085
+ let existing = path;
9086
+ const tail = [];
9087
+ for (;; ) {
8906
9088
  try {
8907
- const mirror = await mirrorSkillSource(source, root);
8908
- if (!mirror)
8909
- continue;
8910
- plugins.push({ type: "local", path: mirror.path });
8911
- skills.push(...mirror.names.map((name) => `${source.plugin}:${name}`));
8912
- } catch (error) {
8913
- debugLog("[coordinator-skills] Skipping skills source", {
8914
- plugin: source.plugin,
8915
- error: error instanceof Error ? error.message : String(error)
8916
- });
9089
+ return join3(realpathSync.native(existing), ...tail.reverse());
9090
+ } catch {
9091
+ const parent = dirname2(existing);
9092
+ if (parent === existing)
9093
+ return path;
9094
+ tail.push(existing.slice(parent.length).replace(/^[/\\]+/, ""));
9095
+ existing = parent;
8917
9096
  }
8918
9097
  }
8919
- return { plugins, skills };
8920
9098
  }
8921
- async function mirrorSkillSource(source, root) {
8922
- const dir = await realpath(source.dir).catch(() => {
8923
- return;
8924
- });
8925
- if (!dir)
8926
- return;
8927
- const skills = await readSkills(dir);
8928
- if (skills.length === 0)
8929
- return;
8930
- const digest = createHash4("sha256").update(JSON.stringify([MIRROR_FORMAT, source.plugin, dir, skills])).digest("hex").slice(0, 24);
8931
- const path = join3(root, `${source.plugin}-${digest}`);
8932
- if (!await isMirror(path))
8933
- await writeMirror(root, path, source.plugin, skills);
8934
- await pruneOldMirrors(root, source.plugin, path);
8935
- return { path, names: skills.map((skill) => skill.name) };
9099
+ function namedAndCanonicalPaths(paths) {
9100
+ const named = paths.flatMap((path) => path?.trim() && isAbsolute(path) ? [path] : []);
9101
+ return [...new Set(named.flatMap((path) => [resolve2(path), canonicalPath(path)]))];
8936
9102
  }
8937
- async function readSkills(dir) {
8938
- const entries = (await readdir2(dir)).filter((name) => !name.startsWith(".")).sort();
8939
- const skills = [];
8940
- const names = new Set;
8941
- for (const entry of entries) {
8942
- if (skills.length >= MAX_SKILLS_PER_SOURCE)
8943
- break;
8944
- const skillDir = await realpath(join3(dir, entry)).catch(() => {
8945
- return;
8946
- });
8947
- if (!skillDir || !(await stat2(skillDir).catch(() => {
8948
- return;
8949
- }))?.isDirectory())
8950
- continue;
8951
- const skill = await readSkill(skillDir, entry);
8952
- if (!skill || names.has(skill.name))
8953
- continue;
8954
- names.add(skill.name);
8955
- skills.push(skill);
8956
- }
8957
- return skills;
8958
- }
8959
- async function readSkill(skillDir, dirName) {
8960
- const entries = await readdir2(skillDir);
8961
- const skillFile = entries.find((entry) => entry === "SKILL.md");
8962
- if (!skillFile)
8963
- return;
8964
- const file = join3(skillDir, skillFile);
8965
- const info = await stat2(file).catch(() => {
8966
- return;
8967
- });
8968
- if (!info?.isFile() || info.size > MAX_SKILL_FILE_BYTES)
8969
- return;
8970
- const sanitized = sanitizeSkillFile(await readFile3(file, "utf8"), dirName);
8971
- if (!sanitized) {
8972
- debugLog("[coordinator-skills] Skipping skill with unreadable frontmatter", { dirName });
8973
- return;
8974
- }
8975
- const links = entries.filter((entry) => entry.toLowerCase() !== "skill.md").sort().slice(0, MAX_ENTRIES_PER_SKILL).map((entry) => [entry, join3(skillDir, entry)]);
8976
- return { name: sanitized.name, text: sanitized.text, links };
8977
- }
8978
- function yamlParser() {
8979
- const parse = globalThis.Bun?.YAML?.parse;
8980
- return typeof parse === "function" ? parse : null;
8981
- }
8982
- function sanitizeSkillFile(text, dirName, parse = yamlParser()) {
8983
- const match = FRONTMATTER.exec(text);
8984
- let fields = {};
8985
- if (match) {
8986
- if (!parse)
8987
- return;
8988
- let parsed;
8989
- try {
8990
- parsed = parse(match[1]);
8991
- } catch {
8992
- return;
8993
- }
8994
- if (parsed !== null && parsed !== undefined) {
8995
- if (typeof parsed !== "object" || Array.isArray(parsed))
8996
- return;
8997
- fields = parsed;
8998
- }
8999
- }
9000
- const declared = typeof fields.name === "string" ? fields.name.trim() : "";
9001
- const name = SKILL_NAME.test(declared) ? declared : dirName;
9002
- if (!SKILL_NAME.test(name))
9003
- return;
9004
- const lines = [`name: ${JSON.stringify(name)}`];
9005
- for (const key of KEPT_FRONTMATTER_KEYS) {
9006
- if (key === "name" || !Object.hasOwn(fields, key))
9007
- continue;
9008
- const value = frontmatterValue(fields[key]);
9009
- if (value !== undefined)
9010
- lines.push(`${key}: ${value}`);
9011
- }
9012
- const body = match ? text.slice(match[0].length) : text.replace(/^/, "");
9013
- return { name, text: `---
9014
- ${lines.join(`
9015
- `)}
9016
- ---
9017
- ${body}` };
9103
+ function isWithin(root, path) {
9104
+ if (path === root)
9105
+ return true;
9106
+ const prefix = root === parse(root).root ? root : `${root}${sep}`;
9107
+ return path.startsWith(prefix);
9018
9108
  }
9019
- function frontmatterValue(value) {
9020
- if (typeof value === "string" || typeof value === "boolean")
9021
- return JSON.stringify(value);
9022
- if (typeof value === "number" && Number.isFinite(value))
9023
- return JSON.stringify(String(value));
9024
- if (Array.isArray(value) && value.every((item) => typeof item === "string"))
9025
- return JSON.stringify(value);
9026
- return;
9109
+ function protectedDataDirBoundary(dataDir, allowances) {
9110
+ const trimmed = dataDir?.trim();
9111
+ if (!trimmed || !isAbsolute(trimmed))
9112
+ return null;
9113
+ const deny = namedAndCanonicalPaths([trimmed]);
9114
+ return {
9115
+ deny,
9116
+ allow: namedAndCanonicalPaths(allowances).filter((path) => !deny.includes(path) && deny.some((root) => isWithin(root, path)))
9117
+ };
9027
9118
  }
9028
- async function isMirror(path) {
9029
- return (await stat2(join3(path, ".claude-plugin", "plugin.json")).catch(() => {
9030
- return;
9031
- }))?.isFile() ? true : false;
9119
+ function deniedForm(boundary, path) {
9120
+ return boundary.deny.some((root) => isWithin(root, path)) && !boundary.allow.some((root) => isWithin(root, path));
9032
9121
  }
9033
- async function writeMirror(root, path, plugin, skills) {
9034
- await mkdir2(root, { recursive: true, mode: 448 });
9035
- const staging = join3(root, `.staging-${randomBytes(8).toString("hex")}`);
9036
- try {
9037
- await mkdir2(join3(staging, ".claude-plugin"), { recursive: true });
9038
- await writeFile2(join3(staging, ".claude-plugin", "plugin.json"), JSON.stringify({
9039
- name: plugin,
9040
- description: plugin === "user-skills" ? "The user's own Claude skills, mirrored by Orkestrator without hooks or tool grants." : "This project's .claude/skills, mirrored by Orkestrator without hooks or tool grants."
9041
- }));
9042
- for (const skill of skills) {
9043
- const skillDir = join3(staging, "skills", skill.name);
9044
- await mkdir2(skillDir, { recursive: true });
9045
- await writeFile2(join3(skillDir, "SKILL.md"), skill.text);
9046
- for (const [name, target] of skill.links)
9047
- await symlink(target, join3(skillDir, name));
9048
- }
9049
- try {
9050
- await rename2(staging, path);
9051
- } catch (error) {
9052
- if (!await isMirror(path))
9053
- throw error;
9054
- }
9055
- } finally {
9056
- await rm2(staging, { recursive: true, force: true });
9057
- }
9122
+ function expandedHome(path) {
9123
+ if (path === "~")
9124
+ return homedir2();
9125
+ return path.startsWith("~/") ? `${homedir2()}${sep}${path.slice(2)}` : path;
9058
9126
  }
9059
- async function pruneOldMirrors(root, plugin, current) {
9060
- try {
9061
- const old = await Promise.all((await readdir2(root)).filter((name) => name.startsWith(`${plugin}-`) && join3(root, name) !== current).map(async (name) => ({
9062
- path: join3(root, name),
9063
- mtimeMs: (await stat2(join3(root, name)).catch(() => {
9064
- return;
9065
- }))?.mtimeMs ?? 0
9066
- })));
9067
- old.sort((a, b) => b.mtimeMs - a.mtimeMs);
9068
- for (const { path } of old.slice(KEPT_OLD_MIRRORS)) {
9069
- await rm2(path, { recursive: true, force: true });
9070
- }
9071
- } catch {}
9127
+ function readBoundaryRefuses(boundary, path, cwd, options = {}) {
9128
+ const expanded = expandedHome(path);
9129
+ const raw = isAbsolute(expanded) ? expanded : `${cwd}${sep}${expanded}`;
9130
+ const lexical = resolve2(raw);
9131
+ const real = canonicalPath(raw);
9132
+ if (deniedForm(boundary, lexical) || deniedForm(boundary, real))
9133
+ return true;
9134
+ return options.traversal === true && boundary.deny.some((root) => isWithin(lexical, root) || isWithin(real, root));
9072
9135
  }
9073
9136
 
9074
- // ../../bridges/claude-bridge/src/services/plugin-config.ts
9075
- import { readdir as readdir3, access } from "node:fs/promises";
9076
- import { join as join4 } from "node:path";
9077
-
9078
- // ../protocol/src/node/claude-plugin-set.ts
9079
- import path2 from "node:path";
9080
- var CLAUDE_PLUGINS_MARKER = "/.claude/plugins/";
9081
- function isRecord(value) {
9082
- return typeof value === "object" && value !== null && !Array.isArray(value);
9137
+ // ../../bridges/claude-bridge/src/services/read-only-path-boundary.ts
9138
+ function claudeReadOnlyWorkspacePaths(cwd) {
9139
+ return [...new Set([cwd, canonicalPath(cwd)])];
9083
9140
  }
9084
- function claudePluginConfigList(value) {
9085
- if (!Array.isArray(value))
9086
- return [];
9087
- const plugins = [];
9088
- for (const item of value) {
9089
- if (isRecord(item) && typeof item.path === "string" && item.path) {
9090
- plugins.push({ type: "local", path: item.path });
9091
- }
9141
+ function coordinatorReadBoundary(workspaces, env = process.env) {
9142
+ const dataDir = env[COORDINATOR_PROTECTED_DATA_DIR_ENV]?.trim();
9143
+ return protectedDataDirBoundary(dataDir, [
9144
+ env.CLAUDE_CONFIG_DIR,
9145
+ env.ORKESTRATOR_BRIDGE_ATTACHMENT_ROOT,
9146
+ env[COORDINATOR_CLAUDE_USER_SKILLS_DIR_ENV],
9147
+ dataDir ? join4(dataDir, "toolchains") : undefined,
9148
+ ...workspaces
9149
+ ]);
9150
+ }
9151
+ function globRoot(pattern) {
9152
+ if (!pattern.startsWith("/") && !pattern.startsWith("~") && !pattern.startsWith("..")) {
9153
+ return;
9092
9154
  }
9093
- return plugins;
9155
+ const wildcard = pattern.search(/[*?[{]/);
9156
+ return wildcard < 0 ? pattern : pattern.slice(0, wildcard);
9094
9157
  }
9095
- function isPathWithin(parentDir, candidatePath) {
9096
- const relativePath = path2.relative(parentDir, candidatePath);
9097
- return relativePath === "" || !relativePath.startsWith("..") && !path2.isAbsolute(relativePath);
9158
+ function readToolRefused(boundary, tool, input, cwd) {
9159
+ const text = (key) => {
9160
+ const value = input[key];
9161
+ return typeof value === "string" && value.trim() ? value : undefined;
9162
+ };
9163
+ if (tool === "Read") {
9164
+ const path = text("file_path");
9165
+ return path !== undefined && readBoundaryRefuses(boundary, path, cwd);
9166
+ }
9167
+ if (tool !== "Grep" && tool !== "Glob")
9168
+ return false;
9169
+ const roots = [text("path") ?? cwd];
9170
+ const pattern = tool === "Glob" ? text("pattern") : undefined;
9171
+ const root = pattern ? globRoot(pattern) : undefined;
9172
+ if (root)
9173
+ roots.push(root);
9174
+ return roots.some((path) => readBoundaryRefuses(boundary, path, cwd, { traversal: true }));
9098
9175
  }
9099
- function remapInstalledPlugins(pluginsDir, installedPlugins, onUnsafe) {
9100
- const plugins = [];
9101
- const pluginsRoot = path2.resolve(pluginsDir);
9102
- if (!isRecord(installedPlugins.plugins))
9103
- return plugins;
9104
- for (const [installedId, entries] of Object.entries(installedPlugins.plugins)) {
9105
- if (!Array.isArray(entries))
9106
- continue;
9107
- for (const entry of entries) {
9108
- if (!isRecord(entry) || typeof entry.installPath !== "string")
9109
- continue;
9110
- const installPath = entry.installPath;
9111
- const markerIdx = installPath.indexOf(CLAUDE_PLUGINS_MARKER);
9112
- let resolvedPath;
9113
- if (markerIdx !== -1) {
9114
- const relativePath = installPath.substring(markerIdx + CLAUDE_PLUGINS_MARKER.length);
9115
- const remappedPath = path2.resolve(pluginsDir, relativePath);
9116
- if (!isPathWithin(pluginsRoot, remappedPath)) {
9117
- onUnsafe?.(installPath);
9118
- continue;
9119
- }
9120
- resolvedPath = remappedPath;
9121
- } else {
9122
- resolvedPath = installPath;
9176
+ function shellCommandRefused(boundary, command, cwd, options) {
9177
+ const [program, ...tokens] = command.trim().split(/\s+/);
9178
+ if (options.traversal) {
9179
+ const indirectOption = program === "sort" || program === "wc" ? "--files0-from" : program === "file" ? "--files-from" : ["cksum", "md5sum", "sha1sum", "sha256sum"].includes(program ?? "") ? "--check" : undefined;
9180
+ if (indirectOption && tokens.some((token) => {
9181
+ const option = token.split("=", 1)[0];
9182
+ return option.startsWith("--") && indirectOption.startsWith(option) || program === "file" && /^-[^-]*f/.test(token) || indirectOption === "--check" && /^-[^-]*c/.test(token);
9183
+ }))
9184
+ return true;
9185
+ if (program === "grep" && tokens.some((token) => /^-[^-]*[RS]/.test(token) || token.startsWith("--") && "--dereference-recursive".startsWith(token)) || program === "diff" && tokens.some((token) => /^-[^-]*r/.test(token) || token.startsWith("--") && "--recursive".startsWith(token)) || (program === "rg" || program === "ag" || program === "find" || program === "fd" || program === "du" || program === "ls") && tokens.some((token) => token === "--follow" || token === "--dereference" || /^-[^-]*L/.test(token)))
9186
+ return true;
9187
+ const searches = program === "rg" || program === "ag" || program === "find" || program === "fd" || program === "du" || program === "ls" || program === "tree" || program === "grep";
9188
+ if (searches && readBoundaryRefuses(boundary, cwd, cwd, options))
9189
+ return true;
9190
+ }
9191
+ return tokens.some((token) => {
9192
+ const attached = [];
9193
+ if (token.startsWith("--")) {
9194
+ const equals = token.indexOf("=");
9195
+ if (equals >= 0)
9196
+ attached.push(token.slice(equals + 1));
9197
+ } else if (token.startsWith("-")) {
9198
+ for (let index = 1;index < token.length && /[a-zA-Z0-9]/.test(token[index]); index++) {
9199
+ attached.push(token.slice(index + 1));
9123
9200
  }
9124
- plugins.push({ type: "local", path: resolvedPath, installedId });
9125
9201
  }
9126
- }
9127
- return plugins;
9128
- }
9129
- function resolveClaudePluginPath(pluginPath, cwd, home) {
9130
- if (pluginPath.startsWith("~"))
9131
- return path2.join(home, pluginPath.slice(1));
9132
- if (pluginPath.startsWith("/"))
9133
- return pluginPath;
9134
- return path2.join(cwd, pluginPath);
9135
- }
9136
- function mergeClaudePluginLayers(layers, options) {
9137
- const ordered = [
9138
- claudePluginConfigList(layers.global),
9139
- layers.cliInstalled,
9140
- ...options.includeProjectSources ? [claudePluginConfigList(layers.projectGlobal), claudePluginConfigList(layers.projectLocal)] : []
9141
- ];
9142
- const seen = new Set;
9143
- const paths = [];
9144
- for (const layer of ordered) {
9145
- for (const plugin of layer) {
9146
- const resolved = resolveClaudePluginPath(plugin.path, options.cwd, options.home);
9147
- if (seen.has(resolved))
9148
- continue;
9149
- seen.add(resolved);
9150
- paths.push(resolved);
9151
- }
9152
- }
9153
- return paths;
9154
- }
9155
- var INVALID_PLUGIN_NAME = new RegExp("[@:\\s/\\\\\\u0000-\\u001f\\u007f\\u200b-\\u200f\\u2028-\\u202e\\u2060-\\u2064\\ufeff]");
9156
- var CLAUDE_PLUGIN_SETTING_SOURCES = ["local", "project", "user"];
9157
- function claudeInstalledPluginIdEnablement(id, settings, loadedSources) {
9158
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9159
- for (const source of ["local", "project", "user"]) {
9160
- if (!loadedSources.includes(source))
9161
- continue;
9162
- const document = settings[source];
9163
- const enabledPlugins = isRecord(document) ? document.enabledPlugins : undefined;
9164
- if (!isRecord(enabledPlugins) || !Object.hasOwn(enabledPlugins, id))
9165
- continue;
9166
- return { enabled: enabledPlugins[id] === true, decidedBy: { source, key: id } };
9167
- }
9168
- return { enabled: false };
9169
- }
9170
- function enabledInstalledPlugins(plugins, settings, loadedSources) {
9171
- return plugins.filter((plugin) => plugin.installedId === undefined || claudeInstalledPluginIdEnablement(plugin.installedId, settings, loadedSources).enabled);
9172
- }
9173
- function claudePluginSettingSources(settingSources) {
9174
- return CLAUDE_PLUGIN_SETTING_SOURCES.filter((source) => settingSources.includes(source));
9202
+ return [token, ...attached].some((candidate) => candidate && readBoundaryRefuses(boundary, candidate, cwd, options));
9203
+ });
9175
9204
  }
9176
9205
 
9177
- // ../../bridges/claude-bridge/src/services/json-file-cache.ts
9178
- import { createHash as createHash5 } from "node:crypto";
9179
- import { readFile as readFile4, stat as stat3 } from "node:fs/promises";
9180
- var SEPARATOR = "\x00";
9181
- var slices = new Map;
9182
- var readCohorts = new Map;
9183
- var parseCounts = new Map;
9184
- var beforeStatForTesting = null;
9185
- function fingerprintOf(stats) {
9186
- return `${stats.dev}:${stats.ino}:${stats.size}:${stats.mtimeMs}`;
9187
- }
9188
- function forgetFile(filePath) {
9189
- const prefix = `${filePath}${SEPARATOR}`;
9190
- for (const key of slices.keys()) {
9191
- if (key.startsWith(prefix))
9192
- slices.delete(key);
9193
- }
9194
- }
9195
- function joinReadCohort(filePath) {
9196
- const existing = readCohorts.get(filePath);
9197
- if (existing) {
9198
- existing.readers += 1;
9199
- return existing;
9200
- }
9201
- const cohort = { readers: 1, parses: new Map };
9202
- readCohorts.set(filePath, cohort);
9203
- return cohort;
9204
- }
9205
- function leaveReadCohort(filePath, cohort) {
9206
- cohort.readers -= 1;
9207
- if (cohort.readers === 0 && readCohorts.get(filePath) === cohort) {
9208
- readCohorts.delete(filePath);
9209
- }
9210
- }
9211
- function parseOnce(filePath, fingerprint, cohort) {
9212
- const existing = cohort.parses.get(fingerprint);
9213
- if (existing)
9214
- return existing;
9215
- const parse = (async () => {
9216
- parseCounts.set(filePath, (parseCounts.get(filePath) ?? 0) + 1);
9217
- let bytes;
9218
- try {
9219
- bytes = await readFile4(filePath);
9220
- } catch {
9221
- return { parsed: null, digest: null };
9222
- }
9223
- const digest = createHash5("sha256").update(bytes).digest("base64url");
9224
- try {
9225
- return { parsed: JSON.parse(bytes.toString("utf-8")), digest };
9226
- } catch {
9227
- return { parsed: null, digest };
9228
- }
9229
- })();
9230
- cohort.parses.set(fingerprint, parse);
9231
- return parse;
9232
- }
9233
- async function readJsonSliceCached(filePath, sliceKey, select) {
9234
- return (await readJsonSliceCachedWithDigest(filePath, sliceKey, select)).value;
9235
- }
9236
- async function readJsonSliceCachedWithDigest(filePath, sliceKey, select) {
9237
- const cohort = joinReadCohort(filePath);
9238
- try {
9239
- await beforeStatForTesting?.(filePath);
9240
- let fingerprint;
9241
- try {
9242
- fingerprint = fingerprintOf(await stat3(filePath));
9243
- } catch {
9244
- forgetFile(filePath);
9245
- return { value: null, digest: null };
9246
- }
9247
- const key = `${filePath}${SEPARATOR}${sliceKey}`;
9248
- const cached = slices.get(key);
9249
- if (cached && cached.fingerprint === fingerprint) {
9250
- return { value: cached.value, digest: cached.digest };
9251
- }
9252
- const { parsed, digest } = await parseOnce(filePath, fingerprint, cohort);
9253
- let value = null;
9254
- if (parsed !== null && parsed !== undefined) {
9255
- try {
9256
- value = select(parsed) ?? null;
9257
- } catch {
9258
- value = null;
9259
- }
9260
- }
9261
- slices.set(key, { fingerprint, value, digest });
9262
- return { value, digest };
9263
- } finally {
9264
- leaveReadCohort(filePath, cohort);
9265
- }
9266
- }
9267
-
9268
- // ../../bridges/claude-bridge/src/services/plugin-config.ts
9269
- var log4 = createLogger("bridge.claude");
9270
- async function pathExists(path) {
9271
- try {
9272
- await access(path);
9273
- return true;
9274
- } catch {
9275
- return false;
9276
- }
9277
- }
9278
- async function scanCliPluginsDirectory(pluginsDir) {
9279
- if (!await pathExists(pluginsDir)) {
9280
- return [];
9281
- }
9282
- try {
9283
- const entries = await readdir3(pluginsDir, { withFileTypes: true });
9284
- const plugins = [];
9285
- for (const entry of entries) {
9286
- if (!entry.isDirectory()) {
9287
- continue;
9288
- }
9289
- const pluginPath = join4(pluginsDir, entry.name);
9290
- const manifestPath = join4(pluginPath, ".claude-plugin", "plugin.json");
9291
- if (await pathExists(manifestPath)) {
9292
- plugins.push({
9293
- type: "local",
9294
- path: pluginPath
9295
- });
9296
- }
9297
- }
9298
- return plugins;
9299
- } catch {
9300
- return [];
9301
- }
9302
- }
9303
- async function loadGlobalPlugins() {
9304
- const plugins = await readJsonSliceCached(claudeJsonPath(), "plugins", (config) => claudePluginConfigList(config?.plugins));
9305
- return plugins ?? [];
9306
- }
9307
- async function loadProjectPlugins(cwd) {
9308
- const plugins = await readJsonSliceCached(join4(cwd, ".claude", "plugins.json"), "plugins", (config) => claudePluginConfigList(config?.plugins));
9309
- return plugins ?? [];
9310
- }
9311
- async function loadCliInstalledPlugins() {
9312
- const pluginsDir = claudePluginsDir();
9313
- const installedPluginsPath = join4(pluginsDir, "installed_plugins.json");
9314
- const plugins = await readJsonSliceCached(installedPluginsPath, "plugins", (config) => config?.plugins);
9315
- if (!plugins) {
9316
- return scanCliPluginsDirectory(pluginsDir);
9317
- }
9318
- return remapInstalledPlugins2(pluginsDir, { plugins });
9319
- }
9320
- function pluginSettingsPath(source, cwd) {
9321
- switch (source) {
9322
- case "user":
9323
- return claudeUserSettingsPath();
9324
- case "project":
9325
- return join4(cwd, ".claude", "settings.json");
9326
- case "local":
9327
- return join4(cwd, ".claude", "settings.local.json");
9328
- }
9329
- }
9330
- async function loadPluginSettings(cwd, sources) {
9331
- const entries = await Promise.all(sources.map(async (source) => {
9332
- const enabledPlugins = await readJsonSliceCached(pluginSettingsPath(source, cwd), "enabledPlugins", (config) => config?.enabledPlugins ?? null);
9333
- return [source, enabledPlugins === null ? undefined : { enabledPlugins }];
9334
- }));
9335
- return Object.fromEntries(entries);
9336
- }
9337
- function remapInstalledPlugins2(pluginsDir, installedPlugins) {
9338
- return remapInstalledPlugins(pluginsDir, installedPlugins, (installPath) => log4.warn("plugin.unsafe-path", { path: installPath }));
9339
- }
9340
- async function loadProjectOverridesFromGlobal(cwd) {
9341
- const plugins = await readJsonSliceCached(claudeJsonPath(), `projects:${cwd}:plugins`, (config) => claudePluginConfigList(config?.projects?.[cwd]?.plugins));
9342
- return plugins ?? [];
9343
- }
9344
- async function readPluginManifest(pluginPath) {
9345
- const manifestPath = join4(pluginPath, ".claude-plugin", "plugin.json");
9346
- const manifest = await readJsonSliceCached(manifestPath, "manifest", (config) => config ? { name: config.name, description: config.description } : null);
9347
- if (!manifest) {
9348
- return null;
9349
- }
9350
- const name = manifest.name || pluginPath.split("/").pop() || "unknown";
9351
- return {
9352
- name,
9353
- description: manifest.description
9354
- };
9355
- }
9356
- function resolvePath(pluginPath, cwd) {
9357
- return resolveClaudePluginPath(pluginPath, cwd, claudeHome());
9358
- }
9359
- function defaultSettingSources(includeProjectSources) {
9360
- return includeProjectSources ? ["user", "project"] : ["user"];
9361
- }
9362
- async function getMergedPlugins(cwd, includeProjectSources = true, settingSources = defaultSettingSources(includeProjectSources)) {
9363
- const sources = claudePluginSettingSources(settingSources);
9364
- const [global2, cliInstalled, projectGlobal, projectLocal, settings] = await Promise.all([
9365
- loadGlobalPlugins(),
9366
- loadCliInstalledPlugins(),
9367
- includeProjectSources ? loadProjectOverridesFromGlobal(cwd) : [],
9368
- includeProjectSources ? loadProjectPlugins(cwd) : [],
9369
- loadPluginSettings(cwd, sources)
9370
- ]);
9371
- return mergeClaudePluginLayers({
9372
- global: global2,
9373
- cliInstalled: enabledInstalledPlugins(cliInstalled, settings, sources),
9374
- projectGlobal,
9375
- projectLocal
9376
- }, { cwd, home: claudeHome(), includeProjectSources }).map((path) => ({ type: "local", path }));
9377
- }
9378
- async function getPluginsForSdk(cwd, includeProjectSources = true, settingSources = defaultSettingSources(includeProjectSources)) {
9379
- const configs = await getMergedPlugins(cwd, includeProjectSources, settingSources);
9380
- const validPlugins = [];
9381
- for (const config of configs) {
9382
- if (await pathExists(config.path)) {
9383
- validPlugins.push({
9384
- type: "local",
9385
- path: config.path
9386
- });
9387
- } else {
9388
- const pluginName = config.path.split("/").pop() || "unknown";
9389
- log4.warn("plugin.path-missing", { pluginName, path: config.path });
9390
- }
9391
- }
9392
- return validPlugins;
9393
- }
9394
- async function getPluginInfo(cwd) {
9395
- const [global2, cliInstalled, projectGlobal, projectLocal] = await Promise.all([
9396
- loadGlobalPlugins(),
9397
- loadCliInstalledPlugins(),
9398
- loadProjectOverridesFromGlobal(cwd),
9399
- loadProjectPlugins(cwd)
9400
- ]);
9401
- const globalPaths = new Set(global2.map((p) => resolvePath(p.path, cwd)));
9402
- const cliPaths = new Set(cliInstalled.map((p) => resolvePath(p.path, cwd)));
9403
- const projectGlobalPaths = new Set(projectGlobal.map((p) => resolvePath(p.path, cwd)));
9404
- const projectLocalPaths = new Set(projectLocal.map((p) => resolvePath(p.path, cwd)));
9405
- const merged = await getMergedPlugins(cwd);
9406
- const result = [];
9407
- for (const config of merged) {
9408
- const manifest = await readPluginManifest(config.path);
9409
- const exists = await pathExists(config.path);
9410
- let source = "global";
9411
- if (projectLocalPaths.has(config.path) || projectGlobalPaths.has(config.path)) {
9412
- source = "project";
9413
- } else if (cliPaths.has(config.path)) {
9414
- source = "cli";
9415
- } else if (globalPaths.has(config.path)) {
9416
- source = "global";
9206
+ // ../../bridges/claude-bridge/src/services/read-only-policy.ts
9207
+ var CAPABILITY_TOOLS = new Map([
9208
+ ["file.write", ["Write", "NotebookEdit", "EnterWorktree", "ExitWorktree"]],
9209
+ ["file.patch", ["Edit", "MultiEdit", "ApplyPatch"]],
9210
+ ["shell", ["Bash", "BashOutput", "KillShell", "PowerShell"]],
9211
+ ["shell.mutate", ["PowerShell"]],
9212
+ ["network", ["WebFetch", "WebSearch", "RemoteTrigger"]],
9213
+ ["web.search", ["WebSearch"]],
9214
+ ["subagents", ["Task", "Agent"]],
9215
+ ["git.commit", ["Bash(git commit)", "Bash(git commit *)"]],
9216
+ ["git.push", ["Bash(git push)", "Bash(git push *)"]],
9217
+ ["github.write", ["Bash(gh)", "Bash(gh *)"]]
9218
+ ]);
9219
+ var READ_ONLY_TOOLS = Object.freeze([
9220
+ "Read",
9221
+ "Glob",
9222
+ "Grep",
9223
+ "Bash",
9224
+ "Task",
9225
+ "Agent",
9226
+ "TodoWrite",
9227
+ "AskUserQuestion"
9228
+ ]);
9229
+ var WAITING_TOOLS = new Set([
9230
+ "Monitor",
9231
+ "ScheduleWakeup",
9232
+ "CronCreate",
9233
+ "CronList",
9234
+ "CronDelete",
9235
+ "SendMessage"
9236
+ ]);
9237
+ var READ_ONLY_COMMANDS = Object.freeze(new Set([
9238
+ "awk",
9239
+ "basename",
9240
+ "cat",
9241
+ "cksum",
9242
+ "column",
9243
+ "comm",
9244
+ "cut",
9245
+ "date",
9246
+ "diff",
9247
+ "dirname",
9248
+ "du",
9249
+ "echo",
9250
+ "file",
9251
+ "find",
9252
+ "fd",
9253
+ "grep",
9254
+ "head",
9255
+ "hostname",
9256
+ "jq",
9257
+ "ls",
9258
+ "md5sum",
9259
+ "nl",
9260
+ "od",
9261
+ "printf",
9262
+ "pwd",
9263
+ "readlink",
9264
+ "realpath",
9265
+ "rg",
9266
+ "sha1sum",
9267
+ "sha256sum",
9268
+ "sort",
9269
+ "stat",
9270
+ "tail",
9271
+ "tr",
9272
+ "true",
9273
+ "uniq",
9274
+ "wc",
9275
+ "which",
9276
+ "whoami",
9277
+ "xxd",
9278
+ "yq"
9279
+ ]));
9280
+ var MUTATING_ARGUMENTS = new Map([
9281
+ ["date", new Set(["-s", "--set"])],
9282
+ ["fd", new Set(["-x", "-X", "--exec", "--exec-batch"])],
9283
+ ["file", new Set(["-C", "--compile"])],
9284
+ [
9285
+ "find",
9286
+ new Set([
9287
+ "-delete",
9288
+ "-exec",
9289
+ "-execdir",
9290
+ "-fls",
9291
+ "-fprint",
9292
+ "-fprint0",
9293
+ "-fprintf",
9294
+ "-ok",
9295
+ "-okdir"
9296
+ ])
9297
+ ],
9298
+ ["hostname", new Set(["-F", "--file", "-b", "--boot"])],
9299
+ ["rg", new Set(["--hostname-bin", "--pre"])],
9300
+ ["sort", new Set(["-o", "--output", "-T", "--temporary-directory", "--compress-program"])],
9301
+ ["yq", new Set(["-i", "--in-place", "--inplace", "-s", "--split-exp"])]
9302
+ ]);
9303
+ var POSITIONAL_LIMITS = new Map([
9304
+ ["hostname", { max: 0, valueOptions: new Set }],
9305
+ ["uniq", { max: 1, valueOptions: new Set(["-f", "-s", "-w"]) }],
9306
+ [
9307
+ "xxd",
9308
+ {
9309
+ max: 1,
9310
+ stopAtFirstOperand: true,
9311
+ valueOptions: new Set([
9312
+ "-c",
9313
+ "-cols",
9314
+ "-g",
9315
+ "-groupsize",
9316
+ "-l",
9317
+ "-len",
9318
+ "-n",
9319
+ "-name",
9320
+ "-o",
9321
+ "-offset",
9322
+ "-s",
9323
+ "-seek"
9324
+ ])
9417
9325
  }
9418
- result.push({
9419
- name: manifest?.name || config.path.split("/").pop() || "unknown",
9420
- path: config.path,
9421
- description: manifest?.description,
9422
- source,
9423
- enabled: exists
9424
- });
9425
- }
9426
- return result;
9427
- }
9428
-
9429
- // ../protocol/src/coordinator-web-research.ts
9430
- var COORDINATOR_WEB_RESEARCH_MODES = ["off", "search", "search-and-mcp"];
9431
- var DEFAULT_COORDINATOR_RESEARCH_MCP_SERVERS = Object.freeze([{ name: "context7", url: "https://mcp.context7.com/mcp" }]);
9432
- var MAX_COORDINATOR_RESEARCH_MCP_SERVERS = 8;
9433
- var COORDINATOR_WEB_RESEARCH_ENV = "ORKESTRATOR_COORDINATOR_WEB_RESEARCH";
9434
- var COORDINATOR_RESEARCH_MCP_ENV = "ORKESTRATOR_COORDINATOR_RESEARCH_MCP";
9435
- var RESERVED_SERVER_NAME = /^orkestrator/;
9436
- var SERVER_NAME = /^[a-z0-9][a-z0-9-]{0,31}$/;
9437
- function isCoordinatorWebResearch(value) {
9438
- return typeof value === "string" && COORDINATOR_WEB_RESEARCH_MODES.includes(value);
9439
- }
9440
- function coordinatorResearchMcpServerProblem(server) {
9441
- if (!SERVER_NAME.test(server.name)) {
9442
- return "Use 1 to 32 lowercase letters, digits or hyphens for the name.";
9443
- }
9444
- if (RESERVED_SERVER_NAME.test(server.name))
9445
- return "Names starting with orkestrator are reserved.";
9446
- let url;
9447
- try {
9448
- url = new URL(server.url);
9449
- } catch {
9450
- return "The URL is not valid.";
9451
- }
9452
- if (url.protocol !== "https:")
9453
- return "Only https:// research servers are allowed.";
9454
- if (url.username || url.password)
9455
- return "Credentials in the URL are not allowed.";
9456
- return;
9457
- }
9458
- function normalizeCoordinatorResearchMcpServers(value) {
9459
- if (value === undefined)
9460
- return DEFAULT_COORDINATOR_RESEARCH_MCP_SERVERS.map((s) => ({ ...s }));
9461
- if (!Array.isArray(value))
9462
- return [];
9463
- const servers = [];
9464
- const names = new Set;
9465
- for (const entry of value) {
9466
- if (servers.length >= MAX_COORDINATOR_RESEARCH_MCP_SERVERS)
9467
- break;
9468
- if (!entry || typeof entry !== "object")
9469
- continue;
9470
- const { name, url } = entry;
9471
- if (typeof name !== "string" || typeof url !== "string")
9472
- continue;
9473
- const server = { name: name.trim(), url: url.trim() };
9474
- if (coordinatorResearchMcpServerProblem(server) || names.has(server.name))
9475
- continue;
9476
- names.add(server.name);
9477
- servers.push(server);
9478
- }
9479
- return servers;
9326
+ ]
9327
+ ]);
9328
+ var OPTION_ALLOWLISTS = new Map([
9329
+ ["awk", new Set(["-F", "-v", "--field-separator", "--assign"])]
9330
+ ]);
9331
+ var GIT_GLOBAL_OPTIONS = new Set([
9332
+ "-P",
9333
+ "--literal-pathspecs",
9334
+ "--no-optional-locks",
9335
+ "--no-pager"
9336
+ ]);
9337
+ var GIT_MUTATING_ARGUMENTS = new Set([
9338
+ "--config-env",
9339
+ "--exec-path",
9340
+ "--ext-diff",
9341
+ "--filters",
9342
+ "--output",
9343
+ "--textconv"
9344
+ ]);
9345
+ var GIT_SUBCOMMAND_MUTATING_ARGUMENTS = new Map([
9346
+ ["grep", new Set(["-O", "--open-files-in-pager"])]
9347
+ ]);
9348
+ var READ_ONLY_GIT_SUBCOMMANDS = Object.freeze(new Set([
9349
+ "blame",
9350
+ "cat-file",
9351
+ "describe",
9352
+ "diff",
9353
+ "grep",
9354
+ "log",
9355
+ "ls-files",
9356
+ "ls-tree",
9357
+ "merge-base",
9358
+ "name-rev",
9359
+ "rev-list",
9360
+ "rev-parse",
9361
+ "shortlog",
9362
+ "show",
9363
+ "show-ref",
9364
+ "status",
9365
+ "whatchanged"
9366
+ ]));
9367
+ var GIT_REF_WRITE_FLAGS = Object.freeze(new Set([
9368
+ "-C",
9369
+ "-D",
9370
+ "-M",
9371
+ "-c",
9372
+ "-d",
9373
+ "-f",
9374
+ "-m",
9375
+ "-u",
9376
+ "--copy",
9377
+ "--delete",
9378
+ "--edit-description",
9379
+ "--force",
9380
+ "--move",
9381
+ "--set-upstream-to",
9382
+ "--unset-upstream"
9383
+ ]));
9384
+ var GIT_REF_LIST_FLAGS = Object.freeze(new Set([
9385
+ "-l",
9386
+ "--list",
9387
+ "--contains",
9388
+ "--no-contains",
9389
+ "--merged",
9390
+ "--no-merged",
9391
+ "--points-at",
9392
+ "--show-current"
9393
+ ]));
9394
+ var GIT_CONFIG_READ_FLAGS = Object.freeze(new Set(["-l", "--get", "--get-all", "--get-regexp", "--get-urlmatch", "--list"]));
9395
+ var GIT_CONFIG_WRITE_FLAGS = Object.freeze(new Set([
9396
+ "-e",
9397
+ "--add",
9398
+ "--edit",
9399
+ "--remove-section",
9400
+ "--rename-section",
9401
+ "--replace-all",
9402
+ "--set",
9403
+ "--set-all",
9404
+ "--unset",
9405
+ "--unset-all"
9406
+ ]));
9407
+ var GIT_CONFIG_READ_SUBCOMMANDS = Object.freeze(new Set(["get", "list"]));
9408
+ var GIT_CONFIG_WRITE_SUBCOMMANDS = Object.freeze(new Set(["edit", "remove-section", "rename-section", "set", "unset"]));
9409
+ var GIT_REMOTE_READ_SUBCOMMANDS = Object.freeze(new Set(["get-url"]));
9410
+ function hasFlag(args, flags) {
9411
+ const letters = [...flags].flatMap((flag) => /^-[A-Za-z0-9]$/.test(flag) ? [flag[1]] : []);
9412
+ return args.some((arg) => flags.has(arg) || flags.has(arg.split("=", 1)[0] ?? arg) || arg.startsWith("--") && [...flags].some((flag) => flag.startsWith("--") && flag.startsWith(arg.split("=", 1)[0])) || /^-[^-]/.test(arg) && letters.some((letter) => arg.slice(1).includes(letter)));
9480
9413
  }
9481
- function coordinatorWebResearchFromEnv(env) {
9482
- const value = env[COORDINATOR_WEB_RESEARCH_ENV];
9483
- return isCoordinatorWebResearch(value) ? value : "off";
9414
+ function listsRefsOnly(args) {
9415
+ if (hasFlag(args, GIT_REF_WRITE_FLAGS))
9416
+ return false;
9417
+ const positionals = args.filter((arg) => !arg.startsWith("-"));
9418
+ return positionals.length === 0 || hasFlag(args, GIT_REF_LIST_FLAGS);
9484
9419
  }
9485
- function coordinatorResearchMcpServersFromEnv(env) {
9486
- if (coordinatorWebResearchFromEnv(env) !== "search-and-mcp")
9487
- return [];
9488
- const raw = env[COORDINATOR_RESEARCH_MCP_ENV];
9489
- if (!raw)
9490
- return [];
9491
- try {
9492
- return normalizeCoordinatorResearchMcpServers(JSON.parse(raw));
9493
- } catch {
9494
- return [];
9495
- }
9420
+ function readsConfigOnly(args) {
9421
+ if (hasFlag(args, GIT_CONFIG_WRITE_FLAGS))
9422
+ return false;
9423
+ const positionals = args.filter((arg) => !arg.startsWith("-"));
9424
+ const first = positionals[0];
9425
+ if (first && GIT_CONFIG_WRITE_SUBCOMMANDS.has(first))
9426
+ return false;
9427
+ if (hasFlag(args, GIT_CONFIG_READ_FLAGS))
9428
+ return true;
9429
+ if (first && GIT_CONFIG_READ_SUBCOMMANDS.has(first))
9430
+ return true;
9431
+ return positionals.length <= 1;
9496
9432
  }
9497
- var COORDINATOR_DENIED = Object.freeze([
9498
- "file.write",
9499
- "file.patch",
9500
- "shell.mutate",
9501
- "network"
9433
+ var CONDITIONAL_GIT_SUBCOMMANDS = new Map([
9434
+ ["branch", listsRefsOnly],
9435
+ ["config", readsConfigOnly],
9436
+ [
9437
+ "remote",
9438
+ (args) => {
9439
+ const first = args.find((arg) => !arg.startsWith("-"));
9440
+ return first === undefined || GIT_REMOTE_READ_SUBCOMMANDS.has(first);
9441
+ }
9442
+ ],
9443
+ ["tag", listsRefsOnly]
9502
9444
  ]);
9503
- function coordinatorCapabilityPolicy(mode) {
9504
- return {
9505
- deny: [...COORDINATOR_DENIED],
9506
- ...mode === "off" ? {} : { allow: ["web.search"] }
9507
- };
9508
- }
9509
-
9510
- // ../../bridges/claude-bridge/src/services/mcp-tool-prefix.ts
9511
- function claudeMcpToolPrefix(name) {
9512
- let normalized = name.replace(/[^a-zA-Z0-9_-]/g, "_");
9513
- if (name.startsWith("claude.ai ")) {
9514
- normalized = normalized.replace(/_+/g, "_").replace(/^_|_$/g, "");
9515
- }
9516
- return `mcp__${normalized}__`;
9445
+ var NETWORK_COMMANDS = new Set(["curl", "gh", "wget"]);
9446
+ var NETWORK_GIT_SUBCOMMANDS = new Set(["fetch", "ls-remote", "pull"]);
9447
+ var COMPOSITION_PATTERN = /[;&|><`$(){}\n\r'"\\*?[\]]|\bsudo\b|\bexec\b/;
9448
+ function isCoordinatorReadOnlyPolicy(policy) {
9449
+ return policy?.id === "coordinator-read-only";
9517
9450
  }
9518
-
9519
- // ../../bridges/claude-bridge/src/services/read-only-path-boundary.ts
9520
- import { join as join6 } from "node:path";
9521
-
9522
- // ../protocol/src/node/coordinator-read-boundary.ts
9523
- import { realpathSync } from "node:fs";
9524
- import { homedir as homedir2 } from "node:os";
9525
- import { dirname as dirname2, isAbsolute as isAbsolute2, join as join5, parse, resolve as resolve2, sep } from "node:path";
9526
- function canonicalPath(path) {
9527
- let existing = path;
9528
- const tail = [];
9529
- for (;; ) {
9530
- try {
9531
- return join5(realpathSync.native(existing), ...tail.reverse());
9532
- } catch {
9533
- const parent = dirname2(existing);
9534
- if (parent === existing)
9535
- return path;
9536
- tail.push(existing.slice(parent.length).replace(/^[/\\]+/, ""));
9537
- existing = parent;
9451
+ function claudeDeniedTools(policy) {
9452
+ const tools = new Set;
9453
+ for (const capability of nativeAgentDeniedCapabilities(policy)) {
9454
+ const server = nativeAgentMcpServer(capability);
9455
+ if (server) {
9456
+ tools.add(`${claudeMcpToolPrefix(server)}*`);
9457
+ continue;
9538
9458
  }
9459
+ for (const tool of CAPABILITY_TOOLS.get(capability) ?? [])
9460
+ tools.add(tool);
9539
9461
  }
9462
+ if (!nativeAgentPolicyDeniesWebSearch(policy))
9463
+ tools.delete("WebSearch");
9464
+ return [...tools];
9540
9465
  }
9541
- function namedAndCanonicalPaths(paths) {
9542
- const named = paths.flatMap((path) => path?.trim() && isAbsolute2(path) ? [path] : []);
9543
- return [...new Set(named.flatMap((path) => [resolve2(path), canonicalPath(path)]))];
9466
+ function claudeDisallowedTools(policy) {
9467
+ const denied = claudeDeniedTools(policy);
9468
+ if (denied.length === 0)
9469
+ return policy?.toolPolicy?.deny;
9470
+ return [...new Set([...policy?.toolPolicy?.deny ?? [], ...denied])];
9544
9471
  }
9545
- function isWithin(root, path) {
9546
- if (path === root)
9547
- return true;
9548
- const prefix = root === parse(root).root ? root : `${root}${sep}`;
9549
- return path.startsWith(prefix);
9472
+ function claudeReadOnlyAllowedTools(options) {
9473
+ return [
9474
+ ...READ_ONLY_TOOLS,
9475
+ ...(options.skillNames ?? []).map((name) => `Skill(${name})`),
9476
+ ...options.policy && !nativeAgentPolicyDeniesWebSearch(options.policy) ? ["WebSearch"] : [],
9477
+ ...(options.agentMcpServerNames ?? []).map((name) => `${claudeMcpToolPrefix(name)}*`),
9478
+ ...(options.researchMcpServerNames ?? []).map((name) => `${claudeMcpToolPrefix(name)}*`),
9479
+ ...(options.grantedMcpServerNames ?? []).map((name) => `${claudeMcpToolPrefix(name)}*`)
9480
+ ];
9550
9481
  }
9551
- function protectedDataDirBoundary(dataDir, allowances) {
9552
- const trimmed = dataDir?.trim();
9553
- if (!trimmed || !isAbsolute2(trimmed))
9554
- return null;
9555
- const deny = namedAndCanonicalPaths([trimmed]);
9482
+ function claudeReadOnlySandbox(policy, options = {}) {
9556
9483
  return {
9557
- deny,
9558
- allow: namedAndCanonicalPaths(allowances).filter((path) => !deny.includes(path) && deny.some((root) => isWithin(root, path)))
9484
+ enabled: options.commandSandbox !== "unavailable",
9485
+ failIfUnavailable: options.commandSandbox !== "unavailable",
9486
+ autoAllowBashIfSandboxed: true,
9487
+ allowUnsandboxedCommands: false,
9488
+ excludedCommands: [],
9489
+ filesystem: {
9490
+ denyWrite: [...new Set(options.workspaces ?? [])],
9491
+ ...options.readBoundary ? { denyRead: options.readBoundary.deny, allowRead: options.readBoundary.allow } : {}
9492
+ },
9493
+ network: {
9494
+ allowLocalBinding: policy.networkAccess === "full",
9495
+ strictAllowlist: true,
9496
+ allowedDomains: []
9497
+ }
9559
9498
  };
9560
9499
  }
9561
- function deniedForm(boundary, path) {
9562
- return boundary.deny.some((root) => isWithin(root, path)) && !boundary.allow.some((root) => isWithin(root, path));
9563
- }
9564
- function expandedHome(path) {
9565
- if (path === "~")
9566
- return homedir2();
9567
- return path.startsWith("~/") ? `${homedir2()}${sep}${path.slice(2)}` : path;
9568
- }
9569
- function readBoundaryRefuses(boundary, path, cwd, options = {}) {
9570
- const expanded = expandedHome(path);
9571
- const raw = isAbsolute2(expanded) ? expanded : `${cwd}${sep}${expanded}`;
9572
- const lexical = resolve2(raw);
9573
- const real = canonicalPath(raw);
9574
- if (deniedForm(boundary, lexical) || deniedForm(boundary, real))
9575
- return true;
9576
- return options.traversal === true && boundary.deny.some((root) => isWithin(lexical, root) || isWithin(real, root));
9500
+ function readOnlyRefusalRole(sessionPolicy, readOnlyTurn, env = process.env) {
9501
+ if (processExecutionPolicyIsCoordinator(env))
9502
+ return "coordinator";
9503
+ return !readOnlyTurn && isCoordinatorReadOnlyPolicy(sessionPolicy) ? "coordinator" : "read-only";
9577
9504
  }
9578
-
9579
- // ../../bridges/claude-bridge/src/services/read-only-path-boundary.ts
9580
- function claudeReadOnlyWorkspacePaths(cwd) {
9581
- return [...new Set([cwd, canonicalPath(cwd)])];
9505
+ var REFUSALS = {
9506
+ coordinator: {
9507
+ composition: "Coordinator shells cannot use quotes, escapes, globs, pipes, redirection, substitution or command chaining, because the command that runs would not be the one checked.",
9508
+ byPath: (program) => `Coordinator shells run reading programs by name only, so \`${program}\` is not available here. Use the program name, or delegate it to a worker environment.`,
9509
+ gitSandbox: "Coordinator Git commands require the command sandbox because Git configuration can run helpers. Use reading tools or delegate to a worker environment.",
9510
+ unavailable: (described) => `Coordinator is read-only, so \`${described}\` is not available here. Delegate it to a worker environment.`,
9511
+ gitArgument: (described) => `Coordinator is read-only, so \`${described}\` cannot be used with an argument that writes a file or runs another program. Delegate it to a worker environment.`,
9512
+ gitGlobalOption: (option) => `Coordinator Git commands run against this checkout only, so the Git option \`${option}\` is not available before the subcommand. Delegate it to a worker environment.`,
9513
+ argument: (program) => `Coordinator is read-only, so \`${program}\` cannot be used with an argument that writes or runs another program. Delegate it to a worker environment.`,
9514
+ program: (program) => `Coordinator is read-only, so \`${program}\` is not available here. Delegate commands that change the checkout to a worker environment.`,
9515
+ network: (described) => `Coordinator commands have no network access, so \`${described}\` is not available here. Delegate it to a worker environment.`,
9516
+ tool: (tool) => `Coordinator is read-only, so ${tool} is not available. Delegate file changes to a worker environment.`,
9517
+ waiting: (tool) => `Coordinator turns do not wait, so ${tool} is not available. Delegated work reports back by waking this conversation with a message when it finishes; end your turn instead.`,
9518
+ mcp: (tool) => `Coordinator sessions may only use Orkestrator's own tools, so ${tool} is not available.`,
9519
+ unsandboxed: "Coordinator commands may not run outside the sandbox.",
9520
+ dataDirectory: "Coordinators cannot read Orkestrator's data directory, which holds credentials with wider authority than this conversation. This conversation's own tool results, memory and attachments stay readable."
9521
+ },
9522
+ "read-only": {
9523
+ composition: "Shell commands in this session cannot use quotes, escapes, globs, pipes, redirection, substitution or command chaining, because the command that runs would not be the one checked.",
9524
+ byPath: (program) => `This session runs reading programs by name only, so \`${program}\` is not available here. Use the program name.`,
9525
+ gitSandbox: "Git commands in this session require the command sandbox because Git configuration can run helpers. Use reading tools instead.",
9526
+ unavailable: (described) => `This session is read-only, so \`${described}\` is not available here.`,
9527
+ gitArgument: (described) => `This session is read-only, so \`${described}\` cannot be used with an argument that writes a file or runs another program.`,
9528
+ gitGlobalOption: (option) => `Git commands in this session run against this checkout only, so the Git option \`${option}\` is not available before the subcommand.`,
9529
+ argument: (program) => `This session is read-only, so \`${program}\` cannot be used with an argument that writes or runs another program.`,
9530
+ program: (program) => `This session is read-only, so \`${program}\` is not available here. It may read the checkout but not change it.`,
9531
+ network: (described) => `Commands in this session have no network access, so \`${described}\` is not available here.`,
9532
+ tool: (tool) => `This session is read-only, so ${tool} is not available.`,
9533
+ waiting: (tool) => `This session's turns do not wait, so ${tool} is not available. End your turn instead.`,
9534
+ mcp: (tool) => `This session may only use Orkestrator's own tools and the MCP servers granted to it, so ${tool} is not available.`,
9535
+ unsandboxed: "Commands in this session may not run outside the sandbox.",
9536
+ dataDirectory: "This session cannot read Orkestrator's data directory, which holds credentials with wider authority than this session. Its own tool results, memory and attachments stay readable."
9537
+ }
9538
+ };
9539
+ function isReadOnlyShellCommand(command, options = {}) {
9540
+ const refusals = REFUSALS[options.role ?? "coordinator"];
9541
+ const trimmed = command.trim();
9542
+ if (!trimmed)
9543
+ return { allowed: true };
9544
+ if (COMPOSITION_PATTERN.test(trimmed) || /(?:^|\s)~/.test(trimmed)) {
9545
+ return { allowed: false, reason: refusals.composition };
9546
+ }
9547
+ const tokens = trimmed.split(/\s+/).filter(Boolean);
9548
+ const first = tokens[0] ?? "";
9549
+ if (!first)
9550
+ return { allowed: true };
9551
+ if (first.includes("/") || first.includes("\\")) {
9552
+ return { allowed: false, reason: refusals.byPath(first) };
9553
+ }
9554
+ const program = first;
9555
+ if (NETWORK_COMMANDS.has(program))
9556
+ return { allowed: false, reason: refusals.network(program) };
9557
+ if (program === "git") {
9558
+ if (options.commandSandbox !== "required") {
9559
+ return { allowed: false, reason: refusals.gitSandbox };
9560
+ }
9561
+ const subcommandIndex = tokens.findIndex((token, index) => index > 0 && !token.startsWith("-"));
9562
+ const subcommand = subcommandIndex > 0 ? tokens[subcommandIndex] : undefined;
9563
+ const args = subcommandIndex > 0 ? tokens.slice(subcommandIndex + 1) : [];
9564
+ const globalOptions = tokens.slice(1, subcommandIndex > 0 ? subcommandIndex : undefined);
9565
+ const unlisted = globalOptions.find((option) => !GIT_GLOBAL_OPTIONS.has(option));
9566
+ if (unlisted)
9567
+ return { allowed: false, reason: refusals.gitGlobalOption(unlisted) };
9568
+ if (subcommand && (NETWORK_GIT_SUBCOMMANDS.has(subcommand) || subcommand === "remote" && args.some((arg) => arg === "show"))) {
9569
+ return { allowed: false, reason: refusals.network(`git ${subcommand}`) };
9570
+ }
9571
+ const permitted = subcommand !== undefined && (READ_ONLY_GIT_SUBCOMMANDS.has(subcommand) || (CONDITIONAL_GIT_SUBCOMMANDS.get(subcommand)?.(args) ?? false));
9572
+ const described = ["git", subcommand].filter(Boolean).join(" ");
9573
+ if (!permitted) {
9574
+ return { allowed: false, reason: refusals.unavailable(described) };
9575
+ }
9576
+ if (hasFlag(tokens.slice(1), GIT_MUTATING_ARGUMENTS) || hasFlag(args, GIT_SUBCOMMAND_MUTATING_ARGUMENTS.get(subcommand) ?? new Set)) {
9577
+ return { allowed: false, reason: refusals.gitArgument(described) };
9578
+ }
9579
+ return { allowed: true };
9580
+ }
9581
+ if (READ_ONLY_COMMANDS.has(program)) {
9582
+ const args = tokens.slice(1);
9583
+ const mutating = MUTATING_ARGUMENTS.get(program);
9584
+ const allowedOptions = OPTION_ALLOWLISTS.get(program);
9585
+ const limit = POSITIONAL_LIMITS.get(program);
9586
+ if (mutating && hasFlag(args, mutating) || allowedOptions && !optionsAllowed(args, allowedOptions) || limit && positionalCount(args, limit.valueOptions, limit.stopAtFirstOperand) > limit.max) {
9587
+ return { allowed: false, reason: refusals.argument(program) };
9588
+ }
9589
+ return { allowed: true };
9590
+ }
9591
+ return { allowed: false, reason: refusals.program(program) };
9582
9592
  }
9583
- function coordinatorReadBoundary(workspaces, env = process.env) {
9584
- const dataDir = env[COORDINATOR_PROTECTED_DATA_DIR_ENV]?.trim();
9585
- return protectedDataDirBoundary(dataDir, [
9586
- env.CLAUDE_CONFIG_DIR,
9587
- env.ORKESTRATOR_BRIDGE_ATTACHMENT_ROOT,
9588
- env[COORDINATOR_CLAUDE_USER_SKILLS_DIR_ENV],
9589
- dataDir ? join6(dataDir, "toolchains") : undefined,
9590
- ...workspaces
9591
- ]);
9593
+ function optionsAllowed(args, allowed) {
9594
+ for (let index = 0;index < args.length; index += 1) {
9595
+ const arg = args[index];
9596
+ if (arg === "--")
9597
+ return true;
9598
+ if (!arg.startsWith("-") || arg === "-")
9599
+ continue;
9600
+ if (allowed.has(arg)) {
9601
+ index += 1;
9602
+ continue;
9603
+ }
9604
+ const long = arg.startsWith("--") ? arg.split("=", 1)[0] : undefined;
9605
+ const attached = long ?? arg.slice(0, 2);
9606
+ if (!allowed.has(attached))
9607
+ return false;
9608
+ }
9609
+ return true;
9592
9610
  }
9593
- function globRoot(pattern) {
9594
- if (!pattern.startsWith("/") && !pattern.startsWith("~") && !pattern.startsWith("..")) {
9595
- return;
9611
+ function positionalCount(args, valueOptions, stopAtFirstOperand = false) {
9612
+ let count = 0;
9613
+ let optionsEnded = false;
9614
+ for (let index = 0;index < args.length; index += 1) {
9615
+ const arg = args[index];
9616
+ if (!optionsEnded && arg === "--") {
9617
+ optionsEnded = true;
9618
+ continue;
9619
+ }
9620
+ if (!optionsEnded && arg.startsWith("-") && arg !== "-") {
9621
+ if (valueOptions.has(arg))
9622
+ index += 1;
9623
+ continue;
9624
+ }
9625
+ count += 1;
9626
+ if (stopAtFirstOperand)
9627
+ optionsEnded = true;
9596
9628
  }
9597
- const wildcard = pattern.search(/[*?[{]/);
9598
- return wildcard < 0 ? pattern : pattern.slice(0, wildcard);
9629
+ return count;
9599
9630
  }
9600
- function readToolRefused(boundary, tool, input, cwd) {
9601
- const text = (key) => {
9602
- const value = input[key];
9603
- return typeof value === "string" && value.trim() ? value : undefined;
9631
+ function deny(reason) {
9632
+ return {
9633
+ hookSpecificOutput: {
9634
+ hookEventName: "PreToolUse",
9635
+ permissionDecision: "deny",
9636
+ permissionDecisionReason: reason
9637
+ }
9604
9638
  };
9605
- if (tool === "Read") {
9606
- const path = text("file_path");
9607
- return path !== undefined && readBoundaryRefuses(boundary, path, cwd);
9608
- }
9609
- if (tool !== "Grep" && tool !== "Glob")
9610
- return false;
9611
- const roots = [text("path") ?? cwd];
9612
- const pattern = tool === "Glob" ? text("pattern") : undefined;
9613
- const root = pattern ? globRoot(pattern) : undefined;
9614
- if (root)
9615
- roots.push(root);
9616
- return roots.some((path) => readBoundaryRefuses(boundary, path, cwd, { traversal: true }));
9617
9639
  }
9618
- function shellCommandRefused(boundary, command, cwd, options) {
9619
- const [program, ...tokens] = command.trim().split(/\s+/);
9620
- if (options.traversal) {
9621
- const indirectOption = program === "sort" || program === "wc" ? "--files0-from" : program === "file" ? "--files-from" : ["cksum", "md5sum", "sha1sum", "sha256sum"].includes(program ?? "") ? "--check" : undefined;
9622
- if (indirectOption && tokens.some((token) => {
9623
- const option = token.split("=", 1)[0];
9624
- return option.startsWith("--") && indirectOption.startsWith(option) || program === "file" && /^-[^-]*f/.test(token) || indirectOption === "--check" && /^-[^-]*c/.test(token);
9625
- }))
9626
- return true;
9627
- if (program === "grep" && tokens.some((token) => /^-[^-]*[RS]/.test(token) || token.startsWith("--") && "--dereference-recursive".startsWith(token)) || program === "diff" && tokens.some((token) => /^-[^-]*r/.test(token) || token.startsWith("--") && "--recursive".startsWith(token)) || (program === "rg" || program === "ag" || program === "find" || program === "fd" || program === "du" || program === "ls") && tokens.some((token) => token === "--follow" || token === "--dereference" || /^-[^-]*L/.test(token)))
9628
- return true;
9629
- const searches = program === "rg" || program === "ag" || program === "find" || program === "fd" || program === "du" || program === "ls" || program === "tree" || program === "grep";
9630
- if (searches && readBoundaryRefuses(boundary, cwd, cwd, options))
9631
- return true;
9632
- }
9633
- return tokens.some((token) => {
9634
- const attached = [];
9635
- if (token.startsWith("--")) {
9636
- const equals = token.indexOf("=");
9637
- if (equals >= 0)
9638
- attached.push(token.slice(equals + 1));
9639
- } else if (token.startsWith("-")) {
9640
- for (let index = 1;index < token.length && /[a-zA-Z0-9]/.test(token[index]); index++) {
9641
- attached.push(token.slice(index + 1));
9640
+ function createCoordinatorReadOnlyHook(policy, researchMcpServerNames = coordinatorResearchMcpServersFromEnv(process.env).map((server) => server.name), options = {}) {
9641
+ const refusals = REFUSALS[options.role ?? "coordinator"];
9642
+ const deniedTools = new Set(claudeDeniedTools(policy));
9643
+ const deniedMcpPrefixes = [...deniedTools].filter((tool) => tool.startsWith("mcp__") && tool.endsWith("__*")).map((tool) => tool.slice(0, -1));
9644
+ const allowedMcpPrefixes = [
9645
+ claudeMcpToolPrefix("orkestrator"),
9646
+ ...researchMcpServerNames.map(claudeMcpToolPrefix),
9647
+ ...(nativeAgentUserMcpGrant(policy) ?? []).map(claudeMcpToolPrefix)
9648
+ ];
9649
+ const readBoundary = (cwd) => options.readBoundary !== undefined ? options.readBoundary : process.env[COORDINATOR_PROTECTED_DATA_DIR_ENV] ? coordinatorReadBoundary(claudeReadOnlyWorkspacePaths(cwd)) : null;
9650
+ return async (input) => {
9651
+ if (input.hook_event_name !== "PreToolUse")
9652
+ return {};
9653
+ const toolName = input.tool_name;
9654
+ if (deniedTools.has(toolName)) {
9655
+ return deny(refusals.tool(toolName));
9656
+ }
9657
+ if (WAITING_TOOLS.has(toolName)) {
9658
+ return deny(refusals.waiting(toolName));
9659
+ }
9660
+ if (deniedMcpPrefixes.some((prefix) => toolName.startsWith(prefix))) {
9661
+ return deny(`This session's policy denies the MCP server behind ${toolName}.`);
9662
+ }
9663
+ if (toolName.startsWith("mcp__")) {
9664
+ if (!allowedMcpPrefixes.some((prefix) => toolName.startsWith(prefix))) {
9665
+ return deny(refusals.mcp(toolName));
9642
9666
  }
9667
+ return {};
9643
9668
  }
9644
- return [token, ...attached].some((candidate) => candidate && readBoundaryRefuses(boundary, candidate, cwd, options));
9645
- });
9646
- }
9647
-
9648
- // ../../bridges/claude-bridge/src/services/read-only-policy.ts
9649
- var CAPABILITY_TOOLS = new Map([
9650
- ["file.write", ["Write", "NotebookEdit", "EnterWorktree", "ExitWorktree"]],
9651
- ["file.patch", ["Edit", "MultiEdit", "ApplyPatch"]],
9652
- ["shell", ["Bash", "BashOutput", "KillShell", "PowerShell"]],
9653
- ["shell.mutate", ["PowerShell"]],
9654
- ["network", ["WebFetch", "WebSearch", "RemoteTrigger"]],
9655
- ["web.search", ["WebSearch"]],
9656
- ["subagents", ["Task", "Agent"]],
9657
- ["git.commit", ["Bash(git commit)", "Bash(git commit *)"]],
9658
- ["git.push", ["Bash(git push)", "Bash(git push *)"]],
9659
- ["github.write", ["Bash(gh)", "Bash(gh *)"]]
9660
- ]);
9661
- var READ_ONLY_TOOLS = Object.freeze([
9662
- "Read",
9663
- "Glob",
9664
- "Grep",
9665
- "Bash",
9666
- "Task",
9667
- "Agent",
9668
- "TodoWrite",
9669
- "AskUserQuestion"
9670
- ]);
9671
- var WAITING_TOOLS = new Set([
9672
- "Monitor",
9673
- "ScheduleWakeup",
9674
- "CronCreate",
9675
- "CronList",
9676
- "CronDelete",
9677
- "SendMessage"
9678
- ]);
9679
- var READ_ONLY_COMMANDS = Object.freeze(new Set([
9680
- "awk",
9681
- "basename",
9682
- "cat",
9683
- "cksum",
9684
- "column",
9685
- "comm",
9686
- "cut",
9687
- "date",
9688
- "diff",
9689
- "dirname",
9690
- "du",
9691
- "echo",
9692
- "file",
9693
- "find",
9694
- "fd",
9695
- "grep",
9696
- "head",
9697
- "hostname",
9698
- "jq",
9699
- "ls",
9700
- "md5sum",
9701
- "nl",
9702
- "od",
9703
- "printf",
9704
- "pwd",
9705
- "readlink",
9706
- "realpath",
9707
- "rg",
9708
- "sha1sum",
9709
- "sha256sum",
9710
- "sort",
9711
- "stat",
9712
- "tail",
9713
- "tr",
9714
- "true",
9715
- "uniq",
9716
- "wc",
9717
- "which",
9718
- "whoami",
9719
- "xxd",
9720
- "yq"
9721
- ]));
9722
- var MUTATING_ARGUMENTS = new Map([
9723
- ["date", new Set(["-s", "--set"])],
9724
- ["fd", new Set(["-x", "-X", "--exec", "--exec-batch"])],
9725
- ["file", new Set(["-C", "--compile"])],
9726
- [
9727
- "find",
9728
- new Set([
9729
- "-delete",
9730
- "-exec",
9731
- "-execdir",
9732
- "-fls",
9733
- "-fprint",
9734
- "-fprint0",
9735
- "-fprintf",
9736
- "-ok",
9737
- "-okdir"
9738
- ])
9739
- ],
9740
- ["hostname", new Set(["-F", "--file", "-b", "--boot"])],
9741
- ["rg", new Set(["--hostname-bin", "--pre"])],
9742
- ["sort", new Set(["-o", "--output", "-T", "--temporary-directory", "--compress-program"])],
9743
- ["yq", new Set(["-i", "--in-place", "--inplace", "-s", "--split-exp"])]
9744
- ]);
9745
- var POSITIONAL_LIMITS = new Map([
9746
- ["hostname", { max: 0, valueOptions: new Set }],
9747
- ["uniq", { max: 1, valueOptions: new Set(["-f", "-s", "-w"]) }],
9748
- [
9749
- "xxd",
9750
- {
9751
- max: 1,
9752
- stopAtFirstOperand: true,
9753
- valueOptions: new Set([
9754
- "-c",
9755
- "-cols",
9756
- "-g",
9757
- "-groupsize",
9758
- "-l",
9759
- "-len",
9760
- "-n",
9761
- "-name",
9762
- "-o",
9763
- "-offset",
9764
- "-s",
9765
- "-seek"
9766
- ])
9669
+ if (toolName === "Bash") {
9670
+ const toolInput = input.tool_input;
9671
+ if (toolInput?.dangerouslyDisableSandbox === true) {
9672
+ return deny(refusals.unsandboxed);
9673
+ }
9674
+ const command = typeof toolInput?.command === "string" ? toolInput.command : "";
9675
+ const verdict = isReadOnlyShellCommand(command, options);
9676
+ if (!verdict.allowed)
9677
+ return deny(verdict.reason);
9678
+ const boundary = readBoundary(input.cwd);
9679
+ if (boundary && shellCommandRefused(boundary, command, input.cwd, {
9680
+ traversal: options.commandSandbox === "unavailable"
9681
+ })) {
9682
+ return deny(refusals.dataDirectory);
9683
+ }
9684
+ return {};
9767
9685
  }
9768
- ]
9769
- ]);
9770
- var OPTION_ALLOWLISTS = new Map([
9771
- ["awk", new Set(["-F", "-v", "--field-separator", "--assign"])]
9772
- ]);
9773
- var GIT_GLOBAL_OPTIONS = new Set([
9774
- "-P",
9775
- "--literal-pathspecs",
9776
- "--no-optional-locks",
9777
- "--no-pager"
9778
- ]);
9779
- var GIT_MUTATING_ARGUMENTS = new Set([
9780
- "--config-env",
9781
- "--exec-path",
9782
- "--ext-diff",
9783
- "--filters",
9784
- "--output",
9785
- "--textconv"
9786
- ]);
9787
- var GIT_SUBCOMMAND_MUTATING_ARGUMENTS = new Map([
9788
- ["grep", new Set(["-O", "--open-files-in-pager"])]
9789
- ]);
9790
- var READ_ONLY_GIT_SUBCOMMANDS = Object.freeze(new Set([
9791
- "blame",
9792
- "cat-file",
9793
- "describe",
9794
- "diff",
9795
- "grep",
9796
- "log",
9797
- "ls-files",
9798
- "ls-tree",
9799
- "merge-base",
9800
- "name-rev",
9801
- "rev-list",
9802
- "rev-parse",
9803
- "shortlog",
9804
- "show",
9805
- "show-ref",
9806
- "status",
9807
- "whatchanged"
9808
- ]));
9809
- var GIT_REF_WRITE_FLAGS = Object.freeze(new Set([
9810
- "-C",
9811
- "-D",
9812
- "-M",
9813
- "-c",
9814
- "-d",
9815
- "-f",
9816
- "-m",
9817
- "-u",
9818
- "--copy",
9819
- "--delete",
9820
- "--edit-description",
9821
- "--force",
9822
- "--move",
9823
- "--set-upstream-to",
9824
- "--unset-upstream"
9825
- ]));
9826
- var GIT_REF_LIST_FLAGS = Object.freeze(new Set([
9827
- "-l",
9828
- "--list",
9829
- "--contains",
9830
- "--no-contains",
9831
- "--merged",
9832
- "--no-merged",
9833
- "--points-at",
9834
- "--show-current"
9835
- ]));
9836
- var GIT_CONFIG_READ_FLAGS = Object.freeze(new Set(["-l", "--get", "--get-all", "--get-regexp", "--get-urlmatch", "--list"]));
9837
- var GIT_CONFIG_WRITE_FLAGS = Object.freeze(new Set([
9838
- "-e",
9839
- "--add",
9840
- "--edit",
9841
- "--remove-section",
9842
- "--rename-section",
9843
- "--replace-all",
9844
- "--set",
9845
- "--set-all",
9846
- "--unset",
9847
- "--unset-all"
9848
- ]));
9849
- var GIT_CONFIG_READ_SUBCOMMANDS = Object.freeze(new Set(["get", "list"]));
9850
- var GIT_CONFIG_WRITE_SUBCOMMANDS = Object.freeze(new Set(["edit", "remove-section", "rename-section", "set", "unset"]));
9851
- var GIT_REMOTE_READ_SUBCOMMANDS = Object.freeze(new Set(["get-url"]));
9852
- function hasFlag(args, flags) {
9853
- const letters = [...flags].flatMap((flag) => /^-[A-Za-z0-9]$/.test(flag) ? [flag[1]] : []);
9854
- return args.some((arg) => flags.has(arg) || flags.has(arg.split("=", 1)[0] ?? arg) || arg.startsWith("--") && [...flags].some((flag) => flag.startsWith("--") && flag.startsWith(arg.split("=", 1)[0])) || /^-[^-]/.test(arg) && letters.some((letter) => arg.slice(1).includes(letter)));
9686
+ if (toolName === "Read" || toolName === "Grep" || toolName === "Glob") {
9687
+ const boundary = readBoundary(input.cwd);
9688
+ const toolInput = input.tool_input ?? {};
9689
+ if (boundary && readToolRefused(boundary, toolName, toolInput, input.cwd)) {
9690
+ return deny(refusals.dataDirectory);
9691
+ }
9692
+ }
9693
+ return {};
9694
+ };
9855
9695
  }
9856
- function listsRefsOnly(args) {
9857
- if (hasFlag(args, GIT_REF_WRITE_FLAGS))
9858
- return false;
9859
- const positionals = args.filter((arg) => !arg.startsWith("-"));
9860
- return positionals.length === 0 || hasFlag(args, GIT_REF_LIST_FLAGS);
9696
+ var BRIDGE_EXECUTION_POLICY_ENV = "ORKESTRATOR_BRIDGE_EXECUTION_POLICY";
9697
+ function processExecutionPolicyIsCoordinator(env = process.env) {
9698
+ return env[BRIDGE_EXECUTION_POLICY_ENV] === "coordinator-read-only";
9861
9699
  }
9862
- function readsConfigOnly(args) {
9863
- if (hasFlag(args, GIT_CONFIG_WRITE_FLAGS))
9700
+ function coordinatorProcessPolicy(env = process.env) {
9701
+ return {
9702
+ id: "coordinator-read-only",
9703
+ sandbox: "provider",
9704
+ approvals: "deny",
9705
+ projectResources: false,
9706
+ capabilityPolicy: coordinatorCapabilityPolicy(coordinatorWebResearchFromEnv(env)),
9707
+ networkAccess: "restricted"
9708
+ };
9709
+ }
9710
+ function effectiveExecutionPolicy(requested, env = process.env) {
9711
+ if (!processExecutionPolicyIsCoordinator(env))
9712
+ return requested;
9713
+ return coordinatorProcessPolicy();
9714
+ }
9715
+
9716
+ // ../../bridges/claude-bridge/src/services/read-only-connection-env.ts
9717
+ var log4 = createLogger("bridge.claude");
9718
+ var READ_ONLY_CONNECTION_ENV_NAMES = new Set([
9719
+ "ANTHROPIC_API_KEY",
9720
+ "ANTHROPIC_AUTH_TOKEN",
9721
+ "ANTHROPIC_BASE_URL",
9722
+ "ANTHROPIC_CUSTOM_HEADERS",
9723
+ "CLAUDE_CODE_OAUTH_TOKEN",
9724
+ "ANTHROPIC_MODEL",
9725
+ "ANTHROPIC_SMALL_FAST_MODEL",
9726
+ "ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION",
9727
+ "CLAUDE_CODE_USE_BEDROCK",
9728
+ "CLAUDE_CODE_SKIP_BEDROCK_AUTH",
9729
+ "ANTHROPIC_BEDROCK_BASE_URL",
9730
+ "AWS_REGION",
9731
+ "AWS_DEFAULT_REGION",
9732
+ "AWS_ACCESS_KEY_ID",
9733
+ "AWS_SECRET_ACCESS_KEY",
9734
+ "AWS_SESSION_TOKEN",
9735
+ "AWS_BEARER_TOKEN_BEDROCK",
9736
+ "CLAUDE_CODE_USE_VERTEX",
9737
+ "CLAUDE_CODE_SKIP_VERTEX_AUTH",
9738
+ "ANTHROPIC_VERTEX_PROJECT_ID",
9739
+ "ANTHROPIC_VERTEX_BASE_URL",
9740
+ "CLOUD_ML_REGION",
9741
+ "GOOGLE_CLOUD_PROJECT",
9742
+ "GOOGLE_APPLICATION_CREDENTIALS",
9743
+ "CLAUDE_CODE_USE_FOUNDRY",
9744
+ "CLAUDE_CODE_SKIP_FOUNDRY_AUTH",
9745
+ "ANTHROPIC_FOUNDRY_API_KEY",
9746
+ "ANTHROPIC_FOUNDRY_BASE_URL",
9747
+ "ANTHROPIC_FOUNDRY_RESOURCE",
9748
+ "HTTPS_PROXY",
9749
+ "https_proxy",
9750
+ "HTTP_PROXY",
9751
+ "http_proxy",
9752
+ "NO_PROXY",
9753
+ "no_proxy",
9754
+ "NODE_EXTRA_CA_CERTS",
9755
+ "CLAUDE_CODE_CLIENT_CERT",
9756
+ "CLAUDE_CODE_CLIENT_KEY",
9757
+ "CLAUDE_CODE_CLIENT_KEY_PASSPHRASE"
9758
+ ]);
9759
+ var READ_ONLY_CONNECTION_ENV_PATTERNS = [
9760
+ /^ANTHROPIC_DEFAULT_[A-Z0-9]+_MODEL$/,
9761
+ /^VERTEX_REGION_CLAUDE_[A-Z0-9_]+$/
9762
+ ];
9763
+ var MAX_CONNECTION_ENV_ENTRIES = 64;
9764
+ var MAX_CONNECTION_ENV_VALUE_BYTES = 16 * 1024;
9765
+ function isReadOnlyConnectionEnvName(name) {
9766
+ return READ_ONLY_CONNECTION_ENV_NAMES.has(name) || READ_ONLY_CONNECTION_ENV_PATTERNS.some((pattern) => pattern.test(name));
9767
+ }
9768
+ function selectReadOnlyConnectionEnv(settings) {
9769
+ if (!settings || typeof settings !== "object" || Array.isArray(settings))
9770
+ return {};
9771
+ const env = settings.env;
9772
+ if (!env || typeof env !== "object" || Array.isArray(env))
9773
+ return {};
9774
+ const selected = {};
9775
+ let count = 0;
9776
+ for (const [name, raw] of Object.entries(env)) {
9777
+ if (!isReadOnlyConnectionEnvName(name))
9778
+ continue;
9779
+ const value = typeof raw === "string" ? raw : typeof raw === "number" || typeof raw === "boolean" ? String(raw) : undefined;
9780
+ if (value === undefined || value.includes("\x00"))
9781
+ continue;
9782
+ if (Buffer.byteLength(value, "utf8") > MAX_CONNECTION_ENV_VALUE_BYTES)
9783
+ continue;
9784
+ if (++count > MAX_CONNECTION_ENV_ENTRIES)
9785
+ break;
9786
+ selected[name] = value;
9787
+ }
9788
+ return selected;
9789
+ }
9790
+ async function readUserSettingsConnectionEnv(settingsPath = claudeUserSettingsPath()) {
9791
+ const selected = await readJsonSliceCached(settingsPath, "read-only-connection-env", selectReadOnlyConnectionEnv);
9792
+ return selected ?? {};
9793
+ }
9794
+ var BEDROCK_AUTH_ENV_NAMES = [
9795
+ "CLAUDE_CODE_USE_BEDROCK",
9796
+ "CLAUDE_CODE_SKIP_BEDROCK_AUTH",
9797
+ "AWS_BEARER_TOKEN_BEDROCK",
9798
+ "AWS_ACCESS_KEY_ID",
9799
+ "AWS_SECRET_ACCESS_KEY",
9800
+ "AWS_SESSION_TOKEN"
9801
+ ];
9802
+ var FALSE_FLAG_VALUES = new Set(["", "0", "false", "no", "off"]);
9803
+ var TRUE_FLAG_VALUES = new Set(["1", "true", "yes", "on"]);
9804
+ function flagMayBeOn(value) {
9805
+ return value !== undefined && !FALSE_FLAG_VALUES.has(value.trim().toLowerCase());
9806
+ }
9807
+ function flagIsOn(value) {
9808
+ return value !== undefined && TRUE_FLAG_VALUES.has(value.trim().toLowerCase());
9809
+ }
9810
+ function bedrockResolvesAwsProfiles(environment) {
9811
+ if (!flagMayBeOn(environment.CLAUDE_CODE_USE_BEDROCK))
9864
9812
  return false;
9865
- const positionals = args.filter((arg) => !arg.startsWith("-"));
9866
- const first = positionals[0];
9867
- if (first && GIT_CONFIG_WRITE_SUBCOMMANDS.has(first))
9813
+ if (flagIsOn(environment.CLAUDE_CODE_SKIP_BEDROCK_AUTH))
9868
9814
  return false;
9869
- if (hasFlag(args, GIT_CONFIG_READ_FLAGS))
9870
- return true;
9871
- if (first && GIT_CONFIG_READ_SUBCOMMANDS.has(first))
9872
- return true;
9873
- return positionals.length <= 1;
9815
+ if (environment.AWS_BEARER_TOKEN_BEDROCK?.trim())
9816
+ return false;
9817
+ return !(environment.AWS_ACCESS_KEY_ID?.trim() && environment.AWS_SECRET_ACCESS_KEY?.trim());
9874
9818
  }
9875
- var CONDITIONAL_GIT_SUBCOMMANDS = new Map([
9876
- ["branch", listsRefsOnly],
9877
- ["config", readsConfigOnly],
9878
- [
9879
- "remote",
9880
- (args) => {
9881
- const first = args.find((arg) => !arg.startsWith("-"));
9882
- return first === undefined || GIT_REMOTE_READ_SUBCOMMANDS.has(first);
9883
- }
9884
- ],
9885
- ["tag", listsRefsOnly]
9819
+ function readOnlyConnectionOverlay(environment, connection) {
9820
+ if (!bedrockResolvesAwsProfiles({ ...environment, ...connection }) || bedrockResolvesAwsProfiles(environment)) {
9821
+ return { overlay: connection, withheldBedrock: false };
9822
+ }
9823
+ const overlay = { ...connection };
9824
+ for (const name of BEDROCK_AUTH_ENV_NAMES)
9825
+ delete overlay[name];
9826
+ return { overlay, withheldBedrock: true };
9827
+ }
9828
+ async function withReadOnlyConnectionEnv(turnPolicy, environment, readConnectionEnv = () => readUserSettingsConnectionEnv()) {
9829
+ if (!isCoordinatorReadOnlyPolicy(turnPolicy))
9830
+ return environment;
9831
+ const connection = await readConnectionEnv();
9832
+ if (Object.keys(connection).length === 0)
9833
+ return environment;
9834
+ const { overlay, withheldBedrock } = readOnlyConnectionOverlay(environment, connection);
9835
+ if (withheldBedrock) {
9836
+ log4.warn("read-only-connection.bedrock-withheld");
9837
+ }
9838
+ if (Object.keys(overlay).length === 0)
9839
+ return environment;
9840
+ return { ...environment, ...overlay };
9841
+ }
9842
+ function connectionEnvFingerprint(environment) {
9843
+ return Object.entries(environment).filter((entry) => typeof entry[1] === "string" && isReadOnlyConnectionEnvName(entry[0])).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
9844
+ }
9845
+
9846
+ // ../../bridges/claude-bridge/src/services/coordinator-skills.ts
9847
+ import { createHash as createHash5, randomBytes } from "node:crypto";
9848
+ import {
9849
+ mkdir as mkdir2,
9850
+ readdir as readdir2,
9851
+ readFile as readFile4,
9852
+ realpath,
9853
+ rename as rename2,
9854
+ rm as rm2,
9855
+ stat as stat3,
9856
+ symlink,
9857
+ writeFile as writeFile2
9858
+ } from "node:fs/promises";
9859
+ import { isAbsolute as isAbsolute2, join as join5 } from "node:path";
9860
+ var KEPT_FRONTMATTER_KEYS = Object.freeze([
9861
+ "name",
9862
+ "description",
9863
+ "when_to_use",
9864
+ "argument-hint",
9865
+ "arguments",
9866
+ "disable-model-invocation",
9867
+ "user-invocable",
9868
+ "version"
9886
9869
  ]);
9887
- var NETWORK_COMMANDS = new Set(["curl", "gh", "wget"]);
9888
- var NETWORK_GIT_SUBCOMMANDS = new Set(["fetch", "ls-remote", "pull"]);
9889
- var COMPOSITION_PATTERN = /[;&|><`$(){}\n\r'"\\*?[\]]|\bsudo\b|\bexec\b/;
9890
- function isCoordinatorReadOnlyPolicy(policy) {
9891
- return policy?.id === "coordinator-read-only";
9870
+ var MIRROR_FORMAT = 1;
9871
+ var MAX_SKILLS_PER_SOURCE = 256;
9872
+ var MAX_SKILL_FILE_BYTES = 1024 * 1024;
9873
+ var MAX_ENTRIES_PER_SKILL = 256;
9874
+ var KEPT_OLD_MIRRORS = 4;
9875
+ var SKILL_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
9876
+ var FRONTMATTER = /^?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;
9877
+ function coordinatorSkillSources(cwd, env = process.env) {
9878
+ const userDir = env[COORDINATOR_CLAUDE_USER_SKILLS_DIR_ENV]?.trim();
9879
+ return [
9880
+ ...userDir && isAbsolute2(userDir) ? [{ plugin: "user-skills", dir: userDir }] : [],
9881
+ { plugin: "project-skills", dir: join5(cwd, ".claude", "skills") }
9882
+ ];
9892
9883
  }
9893
- function claudeDeniedTools(policy) {
9894
- const tools = new Set;
9895
- for (const capability of nativeAgentDeniedCapabilities(policy)) {
9896
- const server = nativeAgentMcpServer(capability);
9897
- if (server) {
9898
- tools.add(`${claudeMcpToolPrefix(server)}*`);
9884
+ async function coordinatorSkillPlugins(sources, root = claudeCoordinatorSkillPluginsDir()) {
9885
+ const plugins = [];
9886
+ const skills = [];
9887
+ for (const source of sources) {
9888
+ try {
9889
+ const mirror = await mirrorSkillSource(source, root);
9890
+ if (!mirror)
9891
+ continue;
9892
+ plugins.push({ type: "local", path: mirror.path });
9893
+ skills.push(...mirror.names.map((name) => `${source.plugin}:${name}`));
9894
+ } catch (error) {
9895
+ debugLog("[coordinator-skills] Skipping skills source", {
9896
+ plugin: source.plugin,
9897
+ error: error instanceof Error ? error.message : String(error)
9898
+ });
9899
+ }
9900
+ }
9901
+ return { plugins, skills };
9902
+ }
9903
+ async function mirrorSkillSource(source, root) {
9904
+ const dir = await realpath(source.dir).catch(() => {
9905
+ return;
9906
+ });
9907
+ if (!dir)
9908
+ return;
9909
+ const skills = await readSkills(dir);
9910
+ if (skills.length === 0)
9911
+ return;
9912
+ const digest = createHash5("sha256").update(JSON.stringify([MIRROR_FORMAT, source.plugin, dir, skills])).digest("hex").slice(0, 24);
9913
+ const path = join5(root, `${source.plugin}-${digest}`);
9914
+ if (!await isMirror(path))
9915
+ await writeMirror(root, path, source.plugin, skills);
9916
+ await pruneOldMirrors(root, source.plugin, path);
9917
+ return { path, names: skills.map((skill) => skill.name) };
9918
+ }
9919
+ async function readSkills(dir) {
9920
+ const entries = (await readdir2(dir)).filter((name) => !name.startsWith(".")).sort();
9921
+ const skills = [];
9922
+ const names = new Set;
9923
+ for (const entry of entries) {
9924
+ if (skills.length >= MAX_SKILLS_PER_SOURCE)
9925
+ break;
9926
+ const skillDir = await realpath(join5(dir, entry)).catch(() => {
9927
+ return;
9928
+ });
9929
+ if (!skillDir || !(await stat3(skillDir).catch(() => {
9930
+ return;
9931
+ }))?.isDirectory())
9932
+ continue;
9933
+ const skill = await readSkill(skillDir, entry);
9934
+ if (!skill || names.has(skill.name))
9899
9935
  continue;
9936
+ names.add(skill.name);
9937
+ skills.push(skill);
9938
+ }
9939
+ return skills;
9940
+ }
9941
+ async function readSkill(skillDir, dirName) {
9942
+ const entries = await readdir2(skillDir);
9943
+ const skillFile = entries.find((entry) => entry === "SKILL.md");
9944
+ if (!skillFile)
9945
+ return;
9946
+ const file = join5(skillDir, skillFile);
9947
+ const info = await stat3(file).catch(() => {
9948
+ return;
9949
+ });
9950
+ if (!info?.isFile() || info.size > MAX_SKILL_FILE_BYTES)
9951
+ return;
9952
+ const sanitized = sanitizeSkillFile(await readFile4(file, "utf8"), dirName);
9953
+ if (!sanitized) {
9954
+ debugLog("[coordinator-skills] Skipping skill with unreadable frontmatter", { dirName });
9955
+ return;
9956
+ }
9957
+ const links = entries.filter((entry) => entry.toLowerCase() !== "skill.md").sort().slice(0, MAX_ENTRIES_PER_SKILL).map((entry) => [entry, join5(skillDir, entry)]);
9958
+ return { name: sanitized.name, text: sanitized.text, links };
9959
+ }
9960
+ function yamlParser() {
9961
+ const parse = globalThis.Bun?.YAML?.parse;
9962
+ return typeof parse === "function" ? parse : null;
9963
+ }
9964
+ function sanitizeSkillFile(text, dirName, parse = yamlParser()) {
9965
+ const match = FRONTMATTER.exec(text);
9966
+ let fields = {};
9967
+ if (match) {
9968
+ if (!parse)
9969
+ return;
9970
+ let parsed;
9971
+ try {
9972
+ parsed = parse(match[1]);
9973
+ } catch {
9974
+ return;
9975
+ }
9976
+ if (parsed !== null && parsed !== undefined) {
9977
+ if (typeof parsed !== "object" || Array.isArray(parsed))
9978
+ return;
9979
+ fields = parsed;
9900
9980
  }
9901
- for (const tool of CAPABILITY_TOOLS.get(capability) ?? [])
9902
- tools.add(tool);
9903
9981
  }
9904
- if (!nativeAgentPolicyDeniesWebSearch(policy))
9905
- tools.delete("WebSearch");
9906
- return [...tools];
9982
+ const declared = typeof fields.name === "string" ? fields.name.trim() : "";
9983
+ const name = SKILL_NAME.test(declared) ? declared : dirName;
9984
+ if (!SKILL_NAME.test(name))
9985
+ return;
9986
+ const lines = [`name: ${JSON.stringify(name)}`];
9987
+ for (const key of KEPT_FRONTMATTER_KEYS) {
9988
+ if (key === "name" || !Object.hasOwn(fields, key))
9989
+ continue;
9990
+ const value = frontmatterValue(fields[key]);
9991
+ if (value !== undefined)
9992
+ lines.push(`${key}: ${value}`);
9993
+ }
9994
+ const body = match ? text.slice(match[0].length) : text.replace(/^/, "");
9995
+ return { name, text: `---
9996
+ ${lines.join(`
9997
+ `)}
9998
+ ---
9999
+ ${body}` };
10000
+ }
10001
+ function frontmatterValue(value) {
10002
+ if (typeof value === "string" || typeof value === "boolean")
10003
+ return JSON.stringify(value);
10004
+ if (typeof value === "number" && Number.isFinite(value))
10005
+ return JSON.stringify(String(value));
10006
+ if (Array.isArray(value) && value.every((item) => typeof item === "string"))
10007
+ return JSON.stringify(value);
10008
+ return;
10009
+ }
10010
+ async function isMirror(path) {
10011
+ return (await stat3(join5(path, ".claude-plugin", "plugin.json")).catch(() => {
10012
+ return;
10013
+ }))?.isFile() ? true : false;
10014
+ }
10015
+ async function writeMirror(root, path, plugin, skills) {
10016
+ await mkdir2(root, { recursive: true, mode: 448 });
10017
+ const staging = join5(root, `.staging-${randomBytes(8).toString("hex")}`);
10018
+ try {
10019
+ await mkdir2(join5(staging, ".claude-plugin"), { recursive: true });
10020
+ await writeFile2(join5(staging, ".claude-plugin", "plugin.json"), JSON.stringify({
10021
+ name: plugin,
10022
+ description: plugin === "user-skills" ? "The user's own Claude skills, mirrored by Orkestrator without hooks or tool grants." : "This project's .claude/skills, mirrored by Orkestrator without hooks or tool grants."
10023
+ }));
10024
+ for (const skill of skills) {
10025
+ const skillDir = join5(staging, "skills", skill.name);
10026
+ await mkdir2(skillDir, { recursive: true });
10027
+ await writeFile2(join5(skillDir, "SKILL.md"), skill.text);
10028
+ for (const [name, target] of skill.links)
10029
+ await symlink(target, join5(skillDir, name));
10030
+ }
10031
+ try {
10032
+ await rename2(staging, path);
10033
+ } catch (error) {
10034
+ if (!await isMirror(path))
10035
+ throw error;
10036
+ }
10037
+ } finally {
10038
+ await rm2(staging, { recursive: true, force: true });
10039
+ }
9907
10040
  }
9908
- function claudeDisallowedTools(policy) {
9909
- const denied = claudeDeniedTools(policy);
9910
- if (denied.length === 0)
9911
- return policy?.toolPolicy?.deny;
9912
- return [...new Set([...policy?.toolPolicy?.deny ?? [], ...denied])];
10041
+ async function pruneOldMirrors(root, plugin, current) {
10042
+ try {
10043
+ const old = await Promise.all((await readdir2(root)).filter((name) => name.startsWith(`${plugin}-`) && join5(root, name) !== current).map(async (name) => ({
10044
+ path: join5(root, name),
10045
+ mtimeMs: (await stat3(join5(root, name)).catch(() => {
10046
+ return;
10047
+ }))?.mtimeMs ?? 0
10048
+ })));
10049
+ old.sort((a, b) => b.mtimeMs - a.mtimeMs);
10050
+ for (const { path } of old.slice(KEPT_OLD_MIRRORS)) {
10051
+ await rm2(path, { recursive: true, force: true });
10052
+ }
10053
+ } catch {}
9913
10054
  }
9914
- function claudeReadOnlyAllowedTools(options) {
9915
- return [
9916
- ...READ_ONLY_TOOLS,
9917
- ...(options.skillNames ?? []).map((name) => `Skill(${name})`),
9918
- ...options.policy && !nativeAgentPolicyDeniesWebSearch(options.policy) ? ["WebSearch"] : [],
9919
- ...(options.agentMcpServerNames ?? []).map((name) => `${claudeMcpToolPrefix(name)}*`),
9920
- ...(options.researchMcpServerNames ?? []).map((name) => `${claudeMcpToolPrefix(name)}*`),
9921
- ...(options.grantedMcpServerNames ?? []).map((name) => `${claudeMcpToolPrefix(name)}*`)
9922
- ];
10055
+
10056
+ // ../../bridges/claude-bridge/src/services/plugin-config.ts
10057
+ import { readdir as readdir3, access } from "node:fs/promises";
10058
+ import { join as join6 } from "node:path";
10059
+
10060
+ // ../protocol/src/node/claude-plugin-set.ts
10061
+ import path2 from "node:path";
10062
+ var CLAUDE_PLUGINS_MARKER = "/.claude/plugins/";
10063
+ function isRecord(value) {
10064
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9923
10065
  }
9924
- function claudeReadOnlySandbox(policy, options = {}) {
9925
- return {
9926
- enabled: options.commandSandbox !== "unavailable",
9927
- failIfUnavailable: options.commandSandbox !== "unavailable",
9928
- autoAllowBashIfSandboxed: true,
9929
- allowUnsandboxedCommands: false,
9930
- excludedCommands: [],
9931
- filesystem: {
9932
- denyWrite: [...new Set(options.workspaces ?? [])],
9933
- ...options.readBoundary ? { denyRead: options.readBoundary.deny, allowRead: options.readBoundary.allow } : {}
9934
- },
9935
- network: {
9936
- allowLocalBinding: policy.networkAccess === "full",
9937
- strictAllowlist: true,
9938
- allowedDomains: []
10066
+ function claudePluginConfigList(value) {
10067
+ if (!Array.isArray(value))
10068
+ return [];
10069
+ const plugins = [];
10070
+ for (const item of value) {
10071
+ if (isRecord(item) && typeof item.path === "string" && item.path) {
10072
+ plugins.push({ type: "local", path: item.path });
9939
10073
  }
9940
- };
10074
+ }
10075
+ return plugins;
9941
10076
  }
9942
- function readOnlyRefusalRole(sessionPolicy, readOnlyTurn, env = process.env) {
9943
- if (processExecutionPolicyIsCoordinator(env))
9944
- return "coordinator";
9945
- return !readOnlyTurn && isCoordinatorReadOnlyPolicy(sessionPolicy) ? "coordinator" : "read-only";
10077
+ function isPathWithin(parentDir, candidatePath) {
10078
+ const relativePath = path2.relative(parentDir, candidatePath);
10079
+ return relativePath === "" || !relativePath.startsWith("..") && !path2.isAbsolute(relativePath);
9946
10080
  }
9947
- var REFUSALS = {
9948
- coordinator: {
9949
- composition: "Coordinator shells cannot use quotes, escapes, globs, pipes, redirection, substitution or command chaining, because the command that runs would not be the one checked.",
9950
- byPath: (program) => `Coordinator shells run reading programs by name only, so \`${program}\` is not available here. Use the program name, or delegate it to a worker environment.`,
9951
- gitSandbox: "Coordinator Git commands require the command sandbox because Git configuration can run helpers. Use reading tools or delegate to a worker environment.",
9952
- unavailable: (described) => `Coordinator is read-only, so \`${described}\` is not available here. Delegate it to a worker environment.`,
9953
- gitArgument: (described) => `Coordinator is read-only, so \`${described}\` cannot be used with an argument that writes a file or runs another program. Delegate it to a worker environment.`,
9954
- gitGlobalOption: (option) => `Coordinator Git commands run against this checkout only, so the Git option \`${option}\` is not available before the subcommand. Delegate it to a worker environment.`,
9955
- argument: (program) => `Coordinator is read-only, so \`${program}\` cannot be used with an argument that writes or runs another program. Delegate it to a worker environment.`,
9956
- program: (program) => `Coordinator is read-only, so \`${program}\` is not available here. Delegate commands that change the checkout to a worker environment.`,
9957
- network: (described) => `Coordinator commands have no network access, so \`${described}\` is not available here. Delegate it to a worker environment.`,
9958
- tool: (tool) => `Coordinator is read-only, so ${tool} is not available. Delegate file changes to a worker environment.`,
9959
- waiting: (tool) => `Coordinator turns do not wait, so ${tool} is not available. Delegated work reports back by waking this conversation with a message when it finishes; end your turn instead.`,
9960
- mcp: (tool) => `Coordinator sessions may only use Orkestrator's own tools, so ${tool} is not available.`,
9961
- unsandboxed: "Coordinator commands may not run outside the sandbox.",
9962
- dataDirectory: "Coordinators cannot read Orkestrator's data directory, which holds credentials with wider authority than this conversation. This conversation's own tool results, memory and attachments stay readable."
9963
- },
9964
- "read-only": {
9965
- composition: "Shell commands in this session cannot use quotes, escapes, globs, pipes, redirection, substitution or command chaining, because the command that runs would not be the one checked.",
9966
- byPath: (program) => `This session runs reading programs by name only, so \`${program}\` is not available here. Use the program name.`,
9967
- gitSandbox: "Git commands in this session require the command sandbox because Git configuration can run helpers. Use reading tools instead.",
9968
- unavailable: (described) => `This session is read-only, so \`${described}\` is not available here.`,
9969
- gitArgument: (described) => `This session is read-only, so \`${described}\` cannot be used with an argument that writes a file or runs another program.`,
9970
- gitGlobalOption: (option) => `Git commands in this session run against this checkout only, so the Git option \`${option}\` is not available before the subcommand.`,
9971
- argument: (program) => `This session is read-only, so \`${program}\` cannot be used with an argument that writes or runs another program.`,
9972
- program: (program) => `This session is read-only, so \`${program}\` is not available here. It may read the checkout but not change it.`,
9973
- network: (described) => `Commands in this session have no network access, so \`${described}\` is not available here.`,
9974
- tool: (tool) => `This session is read-only, so ${tool} is not available.`,
9975
- waiting: (tool) => `This session's turns do not wait, so ${tool} is not available. End your turn instead.`,
9976
- mcp: (tool) => `This session may only use Orkestrator's own tools and the MCP servers granted to it, so ${tool} is not available.`,
9977
- unsandboxed: "Commands in this session may not run outside the sandbox.",
9978
- dataDirectory: "This session cannot read Orkestrator's data directory, which holds credentials with wider authority than this session. Its own tool results, memory and attachments stay readable."
9979
- }
9980
- };
9981
- function isReadOnlyShellCommand(command, options = {}) {
9982
- const refusals = REFUSALS[options.role ?? "coordinator"];
9983
- const trimmed = command.trim();
9984
- if (!trimmed)
9985
- return { allowed: true };
9986
- if (COMPOSITION_PATTERN.test(trimmed) || /(?:^|\s)~/.test(trimmed)) {
9987
- return { allowed: false, reason: refusals.composition };
9988
- }
9989
- const tokens = trimmed.split(/\s+/).filter(Boolean);
9990
- const first = tokens[0] ?? "";
9991
- if (!first)
9992
- return { allowed: true };
9993
- if (first.includes("/") || first.includes("\\")) {
9994
- return { allowed: false, reason: refusals.byPath(first) };
9995
- }
9996
- const program = first;
9997
- if (NETWORK_COMMANDS.has(program))
9998
- return { allowed: false, reason: refusals.network(program) };
9999
- if (program === "git") {
10000
- if (options.commandSandbox !== "required") {
10001
- return { allowed: false, reason: refusals.gitSandbox };
10002
- }
10003
- const subcommandIndex = tokens.findIndex((token, index) => index > 0 && !token.startsWith("-"));
10004
- const subcommand = subcommandIndex > 0 ? tokens[subcommandIndex] : undefined;
10005
- const args = subcommandIndex > 0 ? tokens.slice(subcommandIndex + 1) : [];
10006
- const globalOptions = tokens.slice(1, subcommandIndex > 0 ? subcommandIndex : undefined);
10007
- const unlisted = globalOptions.find((option) => !GIT_GLOBAL_OPTIONS.has(option));
10008
- if (unlisted)
10009
- return { allowed: false, reason: refusals.gitGlobalOption(unlisted) };
10010
- if (subcommand && (NETWORK_GIT_SUBCOMMANDS.has(subcommand) || subcommand === "remote" && args.some((arg) => arg === "show"))) {
10011
- return { allowed: false, reason: refusals.network(`git ${subcommand}`) };
10012
- }
10013
- const permitted = subcommand !== undefined && (READ_ONLY_GIT_SUBCOMMANDS.has(subcommand) || (CONDITIONAL_GIT_SUBCOMMANDS.get(subcommand)?.(args) ?? false));
10014
- const described = ["git", subcommand].filter(Boolean).join(" ");
10015
- if (!permitted) {
10016
- return { allowed: false, reason: refusals.unavailable(described) };
10017
- }
10018
- if (hasFlag(tokens.slice(1), GIT_MUTATING_ARGUMENTS) || hasFlag(args, GIT_SUBCOMMAND_MUTATING_ARGUMENTS.get(subcommand) ?? new Set)) {
10019
- return { allowed: false, reason: refusals.gitArgument(described) };
10081
+ function remapInstalledPlugins(pluginsDir, installedPlugins, onUnsafe) {
10082
+ const plugins = [];
10083
+ const pluginsRoot = path2.resolve(pluginsDir);
10084
+ if (!isRecord(installedPlugins.plugins))
10085
+ return plugins;
10086
+ for (const [installedId, entries] of Object.entries(installedPlugins.plugins)) {
10087
+ if (!Array.isArray(entries))
10088
+ continue;
10089
+ for (const entry of entries) {
10090
+ if (!isRecord(entry) || typeof entry.installPath !== "string")
10091
+ continue;
10092
+ const installPath = entry.installPath;
10093
+ const markerIdx = installPath.indexOf(CLAUDE_PLUGINS_MARKER);
10094
+ let resolvedPath;
10095
+ if (markerIdx !== -1) {
10096
+ const relativePath = installPath.substring(markerIdx + CLAUDE_PLUGINS_MARKER.length);
10097
+ const remappedPath = path2.resolve(pluginsDir, relativePath);
10098
+ if (!isPathWithin(pluginsRoot, remappedPath)) {
10099
+ onUnsafe?.(installPath);
10100
+ continue;
10101
+ }
10102
+ resolvedPath = remappedPath;
10103
+ } else {
10104
+ resolvedPath = installPath;
10105
+ }
10106
+ plugins.push({ type: "local", path: resolvedPath, installedId });
10020
10107
  }
10021
- return { allowed: true };
10022
10108
  }
10023
- if (READ_ONLY_COMMANDS.has(program)) {
10024
- const args = tokens.slice(1);
10025
- const mutating = MUTATING_ARGUMENTS.get(program);
10026
- const allowedOptions = OPTION_ALLOWLISTS.get(program);
10027
- const limit = POSITIONAL_LIMITS.get(program);
10028
- if (mutating && hasFlag(args, mutating) || allowedOptions && !optionsAllowed(args, allowedOptions) || limit && positionalCount(args, limit.valueOptions, limit.stopAtFirstOperand) > limit.max) {
10029
- return { allowed: false, reason: refusals.argument(program) };
10109
+ return plugins;
10110
+ }
10111
+ function resolveClaudePluginPath(pluginPath, cwd, home) {
10112
+ if (pluginPath.startsWith("~"))
10113
+ return path2.join(home, pluginPath.slice(1));
10114
+ if (pluginPath.startsWith("/"))
10115
+ return pluginPath;
10116
+ return path2.join(cwd, pluginPath);
10117
+ }
10118
+ function mergeClaudePluginLayers(layers, options) {
10119
+ const ordered = [
10120
+ claudePluginConfigList(layers.global),
10121
+ layers.cliInstalled,
10122
+ ...options.includeProjectSources ? [claudePluginConfigList(layers.projectGlobal), claudePluginConfigList(layers.projectLocal)] : []
10123
+ ];
10124
+ const seen = new Set;
10125
+ const paths = [];
10126
+ for (const layer of ordered) {
10127
+ for (const plugin of layer) {
10128
+ const resolved = resolveClaudePluginPath(plugin.path, options.cwd, options.home);
10129
+ if (seen.has(resolved))
10130
+ continue;
10131
+ seen.add(resolved);
10132
+ paths.push(resolved);
10030
10133
  }
10031
- return { allowed: true };
10032
10134
  }
10033
- return { allowed: false, reason: refusals.program(program) };
10135
+ return paths;
10034
10136
  }
10035
- function optionsAllowed(args, allowed) {
10036
- for (let index = 0;index < args.length; index += 1) {
10037
- const arg = args[index];
10038
- if (arg === "--")
10039
- return true;
10040
- if (!arg.startsWith("-") || arg === "-")
10137
+ var INVALID_PLUGIN_NAME = new RegExp("[@:\\s/\\\\\\u0000-\\u001f\\u007f\\u200b-\\u200f\\u2028-\\u202e\\u2060-\\u2064\\ufeff]");
10138
+ var CLAUDE_PLUGIN_SETTING_SOURCES = ["local", "project", "user"];
10139
+ function claudeInstalledPluginIdEnablement(id, settings, loadedSources) {
10140
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10141
+ for (const source of ["local", "project", "user"]) {
10142
+ if (!loadedSources.includes(source))
10041
10143
  continue;
10042
- if (allowed.has(arg)) {
10043
- index += 1;
10144
+ const document = settings[source];
10145
+ const enabledPlugins = isRecord(document) ? document.enabledPlugins : undefined;
10146
+ if (!isRecord(enabledPlugins) || !Object.hasOwn(enabledPlugins, id))
10044
10147
  continue;
10148
+ return { enabled: enabledPlugins[id] === true, decidedBy: { source, key: id } };
10149
+ }
10150
+ return { enabled: false };
10151
+ }
10152
+ function enabledInstalledPlugins(plugins, settings, loadedSources) {
10153
+ return plugins.filter((plugin) => plugin.installedId === undefined || claudeInstalledPluginIdEnablement(plugin.installedId, settings, loadedSources).enabled);
10154
+ }
10155
+ function claudePluginSettingSources(settingSources) {
10156
+ return CLAUDE_PLUGIN_SETTING_SOURCES.filter((source) => settingSources.includes(source));
10157
+ }
10158
+
10159
+ // ../../bridges/claude-bridge/src/services/plugin-config.ts
10160
+ var log5 = createLogger("bridge.claude");
10161
+ async function pathExists(path) {
10162
+ try {
10163
+ await access(path);
10164
+ return true;
10165
+ } catch {
10166
+ return false;
10167
+ }
10168
+ }
10169
+ async function scanCliPluginsDirectory(pluginsDir) {
10170
+ if (!await pathExists(pluginsDir)) {
10171
+ return [];
10172
+ }
10173
+ try {
10174
+ const entries = await readdir3(pluginsDir, { withFileTypes: true });
10175
+ const plugins = [];
10176
+ for (const entry of entries) {
10177
+ if (!entry.isDirectory()) {
10178
+ continue;
10179
+ }
10180
+ const pluginPath = join6(pluginsDir, entry.name);
10181
+ const manifestPath = join6(pluginPath, ".claude-plugin", "plugin.json");
10182
+ if (await pathExists(manifestPath)) {
10183
+ plugins.push({
10184
+ type: "local",
10185
+ path: pluginPath
10186
+ });
10187
+ }
10045
10188
  }
10046
- const long = arg.startsWith("--") ? arg.split("=", 1)[0] : undefined;
10047
- const attached = long ?? arg.slice(0, 2);
10048
- if (!allowed.has(attached))
10049
- return false;
10189
+ return plugins;
10190
+ } catch {
10191
+ return [];
10050
10192
  }
10051
- return true;
10052
10193
  }
10053
- function positionalCount(args, valueOptions, stopAtFirstOperand = false) {
10054
- let count = 0;
10055
- let optionsEnded = false;
10056
- for (let index = 0;index < args.length; index += 1) {
10057
- const arg = args[index];
10058
- if (!optionsEnded && arg === "--") {
10059
- optionsEnded = true;
10060
- continue;
10061
- }
10062
- if (!optionsEnded && arg.startsWith("-") && arg !== "-") {
10063
- if (valueOptions.has(arg))
10064
- index += 1;
10065
- continue;
10066
- }
10067
- count += 1;
10068
- if (stopAtFirstOperand)
10069
- optionsEnded = true;
10194
+ async function loadGlobalPlugins() {
10195
+ const plugins = await readJsonSliceCached(claudeJsonPath(), "plugins", (config) => claudePluginConfigList(config?.plugins));
10196
+ return plugins ?? [];
10197
+ }
10198
+ async function loadProjectPlugins(cwd) {
10199
+ const plugins = await readJsonSliceCached(join6(cwd, ".claude", "plugins.json"), "plugins", (config) => claudePluginConfigList(config?.plugins));
10200
+ return plugins ?? [];
10201
+ }
10202
+ async function loadCliInstalledPlugins() {
10203
+ const pluginsDir = claudePluginsDir();
10204
+ const installedPluginsPath = join6(pluginsDir, "installed_plugins.json");
10205
+ const plugins = await readJsonSliceCached(installedPluginsPath, "plugins", (config) => config?.plugins);
10206
+ if (!plugins) {
10207
+ return scanCliPluginsDirectory(pluginsDir);
10070
10208
  }
10071
- return count;
10209
+ return remapInstalledPlugins2(pluginsDir, { plugins });
10072
10210
  }
10073
- function deny(reason) {
10074
- return {
10075
- hookSpecificOutput: {
10076
- hookEventName: "PreToolUse",
10077
- permissionDecision: "deny",
10078
- permissionDecisionReason: reason
10079
- }
10080
- };
10211
+ function pluginSettingsPath(source, cwd) {
10212
+ switch (source) {
10213
+ case "user":
10214
+ return claudeUserSettingsPath();
10215
+ case "project":
10216
+ return join6(cwd, ".claude", "settings.json");
10217
+ case "local":
10218
+ return join6(cwd, ".claude", "settings.local.json");
10219
+ }
10081
10220
  }
10082
- function createCoordinatorReadOnlyHook(policy, researchMcpServerNames = coordinatorResearchMcpServersFromEnv(process.env).map((server) => server.name), options = {}) {
10083
- const refusals = REFUSALS[options.role ?? "coordinator"];
10084
- const deniedTools = new Set(claudeDeniedTools(policy));
10085
- const deniedMcpPrefixes = [...deniedTools].filter((tool) => tool.startsWith("mcp__") && tool.endsWith("__*")).map((tool) => tool.slice(0, -1));
10086
- const allowedMcpPrefixes = [
10087
- claudeMcpToolPrefix("orkestrator"),
10088
- ...researchMcpServerNames.map(claudeMcpToolPrefix),
10089
- ...(nativeAgentUserMcpGrant(policy) ?? []).map(claudeMcpToolPrefix)
10090
- ];
10091
- const readBoundary = (cwd) => options.readBoundary !== undefined ? options.readBoundary : process.env[COORDINATOR_PROTECTED_DATA_DIR_ENV] ? coordinatorReadBoundary(claudeReadOnlyWorkspacePaths(cwd)) : null;
10092
- return async (input) => {
10093
- if (input.hook_event_name !== "PreToolUse")
10094
- return {};
10095
- const toolName = input.tool_name;
10096
- if (deniedTools.has(toolName)) {
10097
- return deny(refusals.tool(toolName));
10098
- }
10099
- if (WAITING_TOOLS.has(toolName)) {
10100
- return deny(refusals.waiting(toolName));
10101
- }
10102
- if (deniedMcpPrefixes.some((prefix) => toolName.startsWith(prefix))) {
10103
- return deny(`This session's policy denies the MCP server behind ${toolName}.`);
10104
- }
10105
- if (toolName.startsWith("mcp__")) {
10106
- if (!allowedMcpPrefixes.some((prefix) => toolName.startsWith(prefix))) {
10107
- return deny(refusals.mcp(toolName));
10108
- }
10109
- return {};
10110
- }
10111
- if (toolName === "Bash") {
10112
- const toolInput = input.tool_input;
10113
- if (toolInput?.dangerouslyDisableSandbox === true) {
10114
- return deny(refusals.unsandboxed);
10115
- }
10116
- const command = typeof toolInput?.command === "string" ? toolInput.command : "";
10117
- const verdict = isReadOnlyShellCommand(command, options);
10118
- if (!verdict.allowed)
10119
- return deny(verdict.reason);
10120
- const boundary = readBoundary(input.cwd);
10121
- if (boundary && shellCommandRefused(boundary, command, input.cwd, {
10122
- traversal: options.commandSandbox === "unavailable"
10123
- })) {
10124
- return deny(refusals.dataDirectory);
10125
- }
10126
- return {};
10127
- }
10128
- if (toolName === "Read" || toolName === "Grep" || toolName === "Glob") {
10129
- const boundary = readBoundary(input.cwd);
10130
- const toolInput = input.tool_input ?? {};
10131
- if (boundary && readToolRefused(boundary, toolName, toolInput, input.cwd)) {
10132
- return deny(refusals.dataDirectory);
10133
- }
10134
- }
10135
- return {};
10136
- };
10221
+ async function loadPluginSettings(cwd, sources) {
10222
+ const entries = await Promise.all(sources.map(async (source) => {
10223
+ const enabledPlugins = await readJsonSliceCached(pluginSettingsPath(source, cwd), "enabledPlugins", (config) => config?.enabledPlugins ?? null);
10224
+ return [source, enabledPlugins === null ? undefined : { enabledPlugins }];
10225
+ }));
10226
+ return Object.fromEntries(entries);
10137
10227
  }
10138
- var BRIDGE_EXECUTION_POLICY_ENV = "ORKESTRATOR_BRIDGE_EXECUTION_POLICY";
10139
- function processExecutionPolicyIsCoordinator(env = process.env) {
10140
- return env[BRIDGE_EXECUTION_POLICY_ENV] === "coordinator-read-only";
10228
+ function remapInstalledPlugins2(pluginsDir, installedPlugins) {
10229
+ return remapInstalledPlugins(pluginsDir, installedPlugins, (installPath) => log5.warn("plugin.unsafe-path", { path: installPath }));
10141
10230
  }
10142
- function coordinatorProcessPolicy(env = process.env) {
10231
+ async function loadProjectOverridesFromGlobal(cwd) {
10232
+ const plugins = await readJsonSliceCached(claudeJsonPath(), `projects:${cwd}:plugins`, (config) => claudePluginConfigList(config?.projects?.[cwd]?.plugins));
10233
+ return plugins ?? [];
10234
+ }
10235
+ async function readPluginManifest(pluginPath) {
10236
+ const manifestPath = join6(pluginPath, ".claude-plugin", "plugin.json");
10237
+ const manifest = await readJsonSliceCached(manifestPath, "manifest", (config) => config ? { name: config.name, description: config.description } : null);
10238
+ if (!manifest) {
10239
+ return null;
10240
+ }
10241
+ const name = manifest.name || pluginPath.split("/").pop() || "unknown";
10143
10242
  return {
10144
- id: "coordinator-read-only",
10145
- sandbox: "provider",
10146
- approvals: "deny",
10147
- projectResources: false,
10148
- capabilityPolicy: coordinatorCapabilityPolicy(coordinatorWebResearchFromEnv(env)),
10149
- networkAccess: "restricted"
10243
+ name,
10244
+ description: manifest.description
10150
10245
  };
10151
10246
  }
10152
- function effectiveExecutionPolicy(requested, env = process.env) {
10153
- if (!processExecutionPolicyIsCoordinator(env))
10154
- return requested;
10155
- return coordinatorProcessPolicy();
10247
+ function resolvePath(pluginPath, cwd) {
10248
+ return resolveClaudePluginPath(pluginPath, cwd, claudeHome());
10249
+ }
10250
+ function defaultSettingSources(includeProjectSources) {
10251
+ return includeProjectSources ? ["user", "project"] : ["user"];
10252
+ }
10253
+ async function getMergedPlugins(cwd, includeProjectSources = true, settingSources = defaultSettingSources(includeProjectSources)) {
10254
+ const sources = claudePluginSettingSources(settingSources);
10255
+ const [global2, cliInstalled, projectGlobal, projectLocal, settings] = await Promise.all([
10256
+ loadGlobalPlugins(),
10257
+ loadCliInstalledPlugins(),
10258
+ includeProjectSources ? loadProjectOverridesFromGlobal(cwd) : [],
10259
+ includeProjectSources ? loadProjectPlugins(cwd) : [],
10260
+ loadPluginSettings(cwd, sources)
10261
+ ]);
10262
+ return mergeClaudePluginLayers({
10263
+ global: global2,
10264
+ cliInstalled: enabledInstalledPlugins(cliInstalled, settings, sources),
10265
+ projectGlobal,
10266
+ projectLocal
10267
+ }, { cwd, home: claudeHome(), includeProjectSources }).map((path) => ({ type: "local", path }));
10268
+ }
10269
+ async function getPluginsForSdk(cwd, includeProjectSources = true, settingSources = defaultSettingSources(includeProjectSources)) {
10270
+ const configs = await getMergedPlugins(cwd, includeProjectSources, settingSources);
10271
+ const validPlugins = [];
10272
+ for (const config of configs) {
10273
+ if (await pathExists(config.path)) {
10274
+ validPlugins.push({
10275
+ type: "local",
10276
+ path: config.path
10277
+ });
10278
+ } else {
10279
+ const pluginName = config.path.split("/").pop() || "unknown";
10280
+ log5.warn("plugin.path-missing", { pluginName, path: config.path });
10281
+ }
10282
+ }
10283
+ return validPlugins;
10284
+ }
10285
+ async function getPluginInfo(cwd) {
10286
+ const [global2, cliInstalled, projectGlobal, projectLocal] = await Promise.all([
10287
+ loadGlobalPlugins(),
10288
+ loadCliInstalledPlugins(),
10289
+ loadProjectOverridesFromGlobal(cwd),
10290
+ loadProjectPlugins(cwd)
10291
+ ]);
10292
+ const globalPaths = new Set(global2.map((p) => resolvePath(p.path, cwd)));
10293
+ const cliPaths = new Set(cliInstalled.map((p) => resolvePath(p.path, cwd)));
10294
+ const projectGlobalPaths = new Set(projectGlobal.map((p) => resolvePath(p.path, cwd)));
10295
+ const projectLocalPaths = new Set(projectLocal.map((p) => resolvePath(p.path, cwd)));
10296
+ const merged = await getMergedPlugins(cwd);
10297
+ const result = [];
10298
+ for (const config of merged) {
10299
+ const manifest = await readPluginManifest(config.path);
10300
+ const exists = await pathExists(config.path);
10301
+ let source = "global";
10302
+ if (projectLocalPaths.has(config.path) || projectGlobalPaths.has(config.path)) {
10303
+ source = "project";
10304
+ } else if (cliPaths.has(config.path)) {
10305
+ source = "cli";
10306
+ } else if (globalPaths.has(config.path)) {
10307
+ source = "global";
10308
+ }
10309
+ result.push({
10310
+ name: manifest?.name || config.path.split("/").pop() || "unknown",
10311
+ path: config.path,
10312
+ description: manifest?.description,
10313
+ source,
10314
+ enabled: exists
10315
+ });
10316
+ }
10317
+ return result;
10156
10318
  }
10157
10319
 
10158
10320
  // ../../bridges/claude-bridge/src/services/claude-query-config.ts
@@ -10185,14 +10347,23 @@ function readOnlyTurnPolicy(sessionPolicy) {
10185
10347
  }
10186
10348
  }, "claude");
10187
10349
  }
10188
- function claudeReportedPolicy(session) {
10350
+ var CLAUDE_LINUX_SANDBOX_LOOPBACK_NOTE = "On Linux, Claude's command sandbox gives each command its own network namespace: commands reach other hosts through the sandbox's proxy, but cannot connect directly to services on this machine's loopback (localhost), such as a dev server or local database.";
10351
+ function claudeReportedPolicy(session, platform = process.platform) {
10189
10352
  if (session.status === "running" && session.commandDiscoveryInputs?.readOnly === true) {
10190
10353
  const turnPolicy = claudeTurnPolicy(session.executionPolicy, true);
10191
10354
  if (turnPolicy) {
10192
10355
  return readOnlyTurnReportedPolicy(turnPolicy, session.readOnlyCommandSandboxOff === undefined ? {} : { commandSandboxOff: session.readOnlyCommandSandboxOff });
10193
10356
  }
10194
10357
  }
10195
- return session.executionPolicy;
10358
+ return session.executionPolicy && withLinuxLoopbackNote(session.executionPolicy, platform);
10359
+ }
10360
+ function withLinuxLoopbackNote(policy, platform) {
10361
+ if (platform !== "linux" || policy.sandbox !== "provider" || policy.networkAccess !== "full") {
10362
+ return policy;
10363
+ }
10364
+ if (policy.note?.includes(CLAUDE_LINUX_SANDBOX_LOOPBACK_NOTE))
10365
+ return policy;
10366
+ return appendNativeAgentPolicyNote(policy, CLAUDE_LINUX_SANDBOX_LOOPBACK_NOTE);
10196
10367
  }
10197
10368
  function claudePolicyPermissionMode(policy) {
10198
10369
  return isRestrictivePolicy(policy) ? "default" : "bypassPermissions";
@@ -10465,7 +10636,7 @@ function claudeSandboxRefusal(policy, options = {}) {
10465
10636
  }
10466
10637
 
10467
10638
  // ../../bridges/claude-bridge/src/services/session-manager-background-tasks.ts
10468
- var log5 = createLogger("bridge.claude");
10639
+ var log6 = createLogger("bridge.claude");
10469
10640
  var PROVISIONAL_BACKGROUND_TASK_PREFIX = "pending-bash:";
10470
10641
  var MAX_BACKGROUND_TASK_CANDIDATES = 128;
10471
10642
  function provisionalBackgroundTaskId(toolUseId) {
@@ -10500,7 +10671,7 @@ function registerBackgroundTaskCandidate(runtime, toolUseId) {
10500
10671
  return;
10501
10672
  const { candidates } = runtime.tasks;
10502
10673
  if (!candidates.has(toolUseId) && candidates.size >= MAX_BACKGROUND_TASK_CANDIDATES) {
10503
- log5.warn("task.candidate-bound-reached", {
10674
+ log6.warn("task.candidate-bound-reached", {
10504
10675
  sessionId: runtime.session.id,
10505
10676
  bound: MAX_BACKGROUND_TASK_CANDIDATES
10506
10677
  });
@@ -10614,7 +10785,7 @@ async function persistShellTaskFields(session, toolUseId, fields) {
10614
10785
  ]
10615
10786
  });
10616
10787
  } catch {
10617
- log5.warn("task.details-persist-failed");
10788
+ log6.warn("task.details-persist-failed");
10618
10789
  }
10619
10790
  }
10620
10791
  function cacheShellTaskFields(session, toolUseId, fields) {
@@ -10736,7 +10907,7 @@ function parkSettlingBackgroundTask(owner, task) {
10736
10907
  return;
10737
10908
  const { settling } = owner.tasks;
10738
10909
  if (!settling.has(task.id) && settling.size >= MAX_SETTLING_BACKGROUND_TASKS) {
10739
- log5.warn("task.settling-bound-reached", {
10910
+ log6.warn("task.settling-bound-reached", {
10740
10911
  sessionId: owner.session.id,
10741
10912
  bound: MAX_SETTLING_BACKGROUND_TASKS
10742
10913
  });
@@ -10811,7 +10982,7 @@ async function stopBackgroundTask(sessionId, taskId) {
10811
10982
  if (latest && !LIVE_BACKGROUND_TASK_STATUSES.has(latest.status)) {
10812
10983
  return { ok: true };
10813
10984
  }
10814
- log5.warn("task.stop-failed", { error: formatLogError(error, { stack: false }) });
10985
+ log6.warn("task.stop-failed", { error: formatLogError(error, { stack: false }) });
10815
10986
  if (settleBackgroundTask(session, taskId, "killed", "The Claude control channel for this task is no longer available")) {
10816
10987
  emitBackgroundTaskSnapshot(session);
10817
10988
  }
@@ -12438,7 +12609,7 @@ function restoredTurnInterruption(preferences) {
12438
12609
  }
12439
12610
 
12440
12611
  // ../../bridges/claude-bridge/src/services/session-manager-lifecycle.ts
12441
- var log6 = createLogger("bridge.claude");
12612
+ var log7 = createLogger("bridge.claude");
12442
12613
  async function getSessionActivity(sessionId) {
12443
12614
  const session = sessions.get(sessionId);
12444
12615
  if (session) {
@@ -12618,7 +12789,7 @@ async function claimPromptDispatch(sessionId, requestId, startDispatch, testHook
12618
12789
  try {
12619
12790
  await updateSessionPreferences(sdkSessionId, journalUpdate([...retainedRequestIds].slice(-MAX_DISPATCHED_REQUEST_IDS)));
12620
12791
  } catch (rollbackError) {
12621
- log6.error("dispatch.rollback-failed", {
12792
+ log7.error("dispatch.rollback-failed", {
12622
12793
  error: formatLogError(rollbackError, { stack: false })
12623
12794
  });
12624
12795
  }
@@ -12872,7 +13043,8 @@ function claudeLaunchResourceProfile(plugins, environment) {
12872
13043
  credentials: digest([
12873
13044
  environment.GH_TOKEN ?? null,
12874
13045
  environment.GITHUB_TOKEN ?? null,
12875
- environment.GITHUB_PERSONAL_ACCESS_TOKEN ?? null
13046
+ environment.GITHUB_PERSONAL_ACCESS_TOKEN ?? null,
13047
+ connectionEnvFingerprint(environment)
12876
13048
  ])
12877
13049
  };
12878
13050
  }
@@ -12912,7 +13084,7 @@ async function assertClaudeRuntimeAccepts(session, options, resources, readOnlyC
12912
13084
  const policy = claudeTurnPolicy(session.executionPolicy, options?.readOnly);
12913
13085
  const [{ plugins }, environment] = await Promise.all([
12914
13086
  resolveClaudeTurnPlugins(request.cwd, policy, claudeTurnSettingSources(session, options)),
12915
- runtimeEnvironmentForSessionQuery(policy)
13087
+ runtimeEnvironmentForSessionQuery(policy).then((environment) => withReadOnlyConnectionEnv(policy, environment))
12916
13088
  ]);
12917
13089
  resources = claudeLaunchResourceProfile(plugins, environment);
12918
13090
  }
@@ -13566,7 +13738,7 @@ function groupHasLiveMember(pgid) {
13566
13738
  }
13567
13739
 
13568
13740
  // ../protocol/src/node/lost-exit-reaper.ts
13569
- var log7 = createLogger("process");
13741
+ var log8 = createLogger("process");
13570
13742
  var REAP_GRACE_MS = 2000;
13571
13743
  var REAP_MAX_CHECK_MS = 30000;
13572
13744
  var REAP_MAX_CHECKS = 12;
@@ -13582,7 +13754,7 @@ function createLostExitReaper(options) {
13582
13754
  let abandoned = 0;
13583
13755
  const abandon = (pid, reason) => {
13584
13756
  abandoned += 1;
13585
- log7.warn("child.reap-abandoned", { pid, reason });
13757
+ log8.warn("child.reap-abandoned", { pid, reason });
13586
13758
  };
13587
13759
  const check = (pid, reported, startedAt) => {
13588
13760
  if (reported())
@@ -13597,7 +13769,7 @@ function createLostExitReaper(options) {
13597
13769
  const result = system.waitNoHang(pid);
13598
13770
  if (result === pid) {
13599
13771
  reaped += 1;
13600
- log7.info("child.reaped", { pid, waitedMs: Date.now() - startedAt });
13772
+ log8.info("child.reaped", { pid, waitedMs: Date.now() - startedAt });
13601
13773
  return false;
13602
13774
  }
13603
13775
  if (result === 0)
@@ -13681,7 +13853,7 @@ var defaultReaper;
13681
13853
  function createDarwinLostExitReaper(loadFfi) {
13682
13854
  const system = darwinReaperSystem(loadFfi);
13683
13855
  if (!system)
13684
- log7.warn("child.reap-unavailable");
13856
+ log8.warn("child.reap-unavailable");
13685
13857
  return system ? createLostExitReaper({ system }) : null;
13686
13858
  }
13687
13859
  function sharedReaper() {
@@ -17892,7 +18064,7 @@ function reconcileClaudeUsage(terminal, streamed) {
17892
18064
  }
17893
18065
 
17894
18066
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-turn-lifecycle.ts
17895
- var log8 = createLogger("bridge.claude");
18067
+ var log9 = createLogger("bridge.claude");
17896
18068
  function diagnosticErrorClass(error) {
17897
18069
  try {
17898
18070
  if (!(error instanceof Error))
@@ -17982,7 +18154,7 @@ async function reconcilePlanModeFromStatus(turn, reported) {
17982
18154
  try {
17983
18155
  await applySessionPlanMode(session, false);
17984
18156
  } catch (error) {
17985
- log8.warn("plan-mode.record-failed", { sessionId, errorClass: diagnosticErrorClass(error) });
18157
+ log9.warn("plan-mode.record-failed", { sessionId, errorClass: diagnosticErrorClass(error) });
17986
18158
  }
17987
18159
  }
17988
18160
  function setCompletionBlockedByBackgroundTasks(turn, blocked) {
@@ -18227,7 +18399,7 @@ function createTurnState(session, sessionId, init) {
18227
18399
  }
18228
18400
 
18229
18401
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-admission.ts
18230
- var log9 = createLogger("bridge.claude");
18402
+ var log10 = createLogger("bridge.claude");
18231
18403
  var STREAM_EVENT_COALESCE_MS = 100;
18232
18404
  function admitPrompt(sessionId, options) {
18233
18405
  const session = sessions.get(sessionId);
@@ -18362,7 +18534,7 @@ async function readTranscriptForPrompt(session) {
18362
18534
  try {
18363
18535
  return await readPersistedSessionMessagesOnce(session);
18364
18536
  } catch (error) {
18365
- log9.warn("transcript.hydrate-failed", { error: formatLogError(error, { stack: false }) });
18537
+ log10.warn("transcript.hydrate-failed", { error: formatLogError(error, { stack: false }) });
18366
18538
  return TRANSCRIPT_READ_FAILED;
18367
18539
  }
18368
18540
  }
@@ -18466,7 +18638,7 @@ var ORKESTRATOR_ARTIFACT_MCP_SERVER_NAME = "orkestrator-artifacts";
18466
18638
  var ORKESTRATOR_ARTIFACT_MCP_PATH = "/artifact-mcp";
18467
18639
 
18468
18640
  // ../../bridges/claude-bridge/src/services/mcp-config.ts
18469
- var log10 = createLogger("bridge.claude");
18641
+ var log11 = createLogger("bridge.claude");
18470
18642
  var AGENT_MCP_SERVER_NAME = "orkestrator";
18471
18643
  var AGENT_MCP_URL_ENV = "ORKESTRATOR_AGENT_MCP_URL";
18472
18644
  var AGENT_MCP_TOKEN_ENV = "ORKESTRATOR_AGENT_MCP_TOKEN";
@@ -18551,7 +18723,7 @@ function toSdkServers(configs) {
18551
18723
  if (sdkConfig) {
18552
18724
  servers[name] = sdkConfig;
18553
18725
  } else {
18554
- log10.warn("mcp.config-ignored");
18726
+ log11.warn("mcp.config-ignored");
18555
18727
  }
18556
18728
  }
18557
18729
  return servers;
@@ -18938,7 +19110,7 @@ function claudeReadiness() {
18938
19110
  }
18939
19111
 
18940
19112
  // ../../bridges/claude-bridge/src/services/claude-model-catalog.ts
18941
- var log11 = createLogger("bridge.claude");
19113
+ var log12 = createLogger("bridge.claude");
18942
19114
  var CLAUDE_MODEL_CACHE_TTL_MS = 60 * 60000;
18943
19115
  var CLAUDE_MODEL_PROBE_TIMEOUT_MS = 25000;
18944
19116
  var remembered;
@@ -19073,7 +19245,7 @@ async function probeModels(at) {
19073
19245
  await rememberModels(models, account, at);
19074
19246
  return { source: "sdk", models: catalogModels(models) };
19075
19247
  } catch (error) {
19076
- log11.warn("models.fetch-failed", { error: formatLogError(error) });
19248
+ log12.warn("models.fetch-failed", { error: formatLogError(error) });
19077
19249
  return fallbackCatalog();
19078
19250
  } finally {
19079
19251
  if (q?.return) {
@@ -20578,6 +20750,10 @@ var SUBORK_LIMITS = Object.freeze({
20578
20750
  deadlineMs: 45 * 60000
20579
20751
  });
20580
20752
 
20753
+ // ../protocol/src/auto-pipeline-tool.ts
20754
+ var AUTO_PIPELINE_TOOL_NAME = "convert_to_pipeline";
20755
+ var AGENT_AUTO_PIPELINE_TOOL_NAMES = Object.freeze([AUTO_PIPELINE_TOOL_NAME]);
20756
+
20581
20757
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-query.ts
20582
20758
  import { createHash as createHash11 } from "node:crypto";
20583
20759
 
@@ -21330,14 +21506,14 @@ function isValidMcpFormContent(schema, content) {
21330
21506
  }
21331
21507
 
21332
21508
  // ../../bridges/claude-bridge/src/services/session-manager-interactions.ts
21333
- var log12 = createLogger("bridge.claude");
21509
+ var log13 = createLogger("bridge.claude");
21334
21510
  function answerQuestion(requestId, answers) {
21335
21511
  const question = pendingQuestions.get(requestId);
21336
21512
  if (!question) {
21337
21513
  debugLog("[session-manager] Question not found for requestId:", requestId);
21338
21514
  return false;
21339
21515
  }
21340
- log12.info("question.answering", { requestId, answerCount: Object.keys(answers).length });
21516
+ log13.info("question.answering", { requestId, answerCount: Object.keys(answers).length });
21341
21517
  const resolver = questionResolvers.get(requestId);
21342
21518
  if (resolver) {
21343
21519
  debugLog("[session-manager] Resolving promise for question:", requestId);
@@ -21389,7 +21565,7 @@ function respondToPlanApproval(requestId, approved, feedback) {
21389
21565
  debugLog("[session-manager] Refusing incomplete plan approval", { requestId });
21390
21566
  return false;
21391
21567
  }
21392
- log12.info("plan-approval.responding", {
21568
+ log13.info("plan-approval.responding", {
21393
21569
  requestId,
21394
21570
  approved,
21395
21571
  hasFeedback: typeof feedback === "string" && feedback.length > 0
@@ -21746,7 +21922,7 @@ async function requestClaudeToolApproval(sessionId, toolName, input, permissionC
21746
21922
  }
21747
21923
 
21748
21924
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-hooks.ts
21749
- var log13 = createLogger("bridge.claude");
21925
+ var log14 = createLogger("bridge.claude");
21750
21926
  async function recordPreCompact(turn, hookInput) {
21751
21927
  const { session } = turn;
21752
21928
  if (hookInput.hook_event_name !== "PreCompact" || session.latestTurnGeneration !== turn.turnGeneration) {
@@ -21860,7 +22036,7 @@ function recordingHookDenials(hook, conversationId) {
21860
22036
  } catch (error) {
21861
22037
  if (input.hook_event_name !== "PreToolUse")
21862
22038
  throw error;
21863
- log13.warn("hook.boundary-failed-closed", { tool: input.tool_name });
22039
+ log14.warn("hook.boundary-failed-closed", { tool: input.tool_name });
21864
22040
  output = {
21865
22041
  hookSpecificOutput: {
21866
22042
  hookEventName: "PreToolUse",
@@ -21947,7 +22123,8 @@ async function resolveQueryPlan(turn, sdkTextPrompt, testHooks) {
21947
22123
  ...AGENT_MAIL_TOOL_NAMES,
21948
22124
  ...ARTIFACT_TOOL_NAMES,
21949
22125
  ...AGENT_GOAL_TOOL_NAMES,
21950
- ...AGENT_SUBORK_TOOL_NAMES
22126
+ ...AGENT_SUBORK_TOOL_NAMES,
22127
+ ...AGENT_AUTO_PIPELINE_TOOL_NAMES
21951
22128
  ].map((name) => `mcp__${AGENT_MCP_SERVER_NAME}__${name}`) : [];
21952
22129
  const allowedTools = coordinatorReadOnly ? claudeReadOnlyAllowedTools({
21953
22130
  agentMcpServerNames: mcpServerNames.has(AGENT_MCP_SERVER_NAME) ? [AGENT_MCP_SERVER_NAME] : [],
@@ -21984,7 +22161,7 @@ async function resolveQueryPlan(turn, sdkTextPrompt, testHooks) {
21984
22161
  const envPath = process.env.PATH;
21985
22162
  debugLog("[session-manager] SDK env PATH", { path: envPath });
21986
22163
  const sdkPrompt = await buildSdkPrompt(sdkTextPrompt, options?.attachments, cwd, testHooks?.afterAttachmentSymlinkValidation, testHooks?.afterAttachmentCanonicalValidation, testHooks?.afterAttachmentInitialValidation);
21987
- const queryEnvironment = withReadOnlyGitConfig(policy, withUnattendedOverloadRetry(session.executionPolicy, await runtimeEnvironmentForSessionQuery(policy)));
22164
+ const queryEnvironment = withReadOnlyGitConfig(policy, withUnattendedOverloadRetry(session.executionPolicy, await withReadOnlyConnectionEnv(policy, await runtimeEnvironmentForSessionQuery(policy))));
21988
22165
  const liveSettings = claudeLiveSettings({
21989
22166
  model: options?.model,
21990
22167
  permissionMode,
@@ -22635,7 +22812,7 @@ var LEAF_MESSAGE_HANDLERS = {
22635
22812
  };
22636
22813
 
22637
22814
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-handlers/result.ts
22638
- var log14 = createLogger("bridge.claude");
22815
+ var log15 = createLogger("bridge.claude");
22639
22816
  function claudeStartupFailureMessage(reason) {
22640
22817
  switch (reason) {
22641
22818
  case "org_pin_api_key_conflict":
@@ -22843,9 +23020,9 @@ async function handleResultMessage(turn, message) {
22843
23020
  const startupFailure = resultMsg.startup_failure_reason ? withStartupFailureDetail(claudeStartupFailureMessage(resultMsg.startup_failure_reason), resultMsg.errors) : undefined;
22844
23021
  const usageLimit = resultMsg.subtype === "success" && classifyUsageLimitError(resultMsg.result) ? resultMsg.result.trim().slice(0, MAX_USAGE_LIMIT_ERROR_CHARS) : undefined;
22845
23022
  if (!startupFailure && (usageLimit || turn.rateLimitRejected)) {
22846
- log14.warn("query.usage-limited", { subtype: resultMsg.subtype, sessionId });
23023
+ log15.warn("query.usage-limited", { subtype: resultMsg.subtype, sessionId });
22847
23024
  } else {
22848
- log14.error("query.failed", { subtype: resultMsg.subtype, sessionId, isError: resultIsError });
23025
+ log15.error("query.failed", { subtype: resultMsg.subtype, sessionId, isError: resultIsError });
22849
23026
  }
22850
23027
  const resultError = startupFailure || resultMsg.errors?.filter(Boolean).join(`
22851
23028
  `) || usageLimit || (resultMsg.subtype === "success" ? "Claude ended the turn on an API error." : `Claude query failed: ${resultMsg.subtype}`);
@@ -23279,7 +23456,7 @@ async function handleSystemMessage(turn, message) {
23279
23456
  }
23280
23457
 
23281
23458
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-handlers/user.ts
23282
- var log15 = createLogger("bridge.claude");
23459
+ var log16 = createLogger("bridge.claude");
23283
23460
  function handleUserMessage(turn, message) {
23284
23461
  const { session, sessionId, stream } = turn;
23285
23462
  const { toolTracker, taskRegistry, activeTaskIds } = stream;
@@ -23329,7 +23506,7 @@ function handleUserMessage(turn, message) {
23329
23506
  if (turn.planApprovedThisTurn) {
23330
23507
  for (const tool of toolTracker.getTools()) {
23331
23508
  if (tool.toolName === "ExitPlanMode" && tool.toolState === "failure" && tool.toolUseId) {
23332
- log15.warn("plan-exit.failure-overridden", { sessionId, toolUseId: tool.toolUseId });
23509
+ log16.warn("plan-exit.failure-overridden", { sessionId, toolUseId: tool.toolUseId });
23333
23510
  toolTracker.updateToolResult(tool.toolUseId, {
23334
23511
  state: "success",
23335
23512
  output: "Plan approved by the user. Proceeding with implementation.",
@@ -23441,7 +23618,7 @@ async function readClaudeMcpToolHints(control, serverName, toolName, timeoutMs =
23441
23618
  }
23442
23619
 
23443
23620
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-can-use-tool.ts
23444
- var log16 = createLogger("bridge.claude");
23621
+ var log17 = createLogger("bridge.claude");
23445
23622
  function boundedPlan(content) {
23446
23623
  if (typeof content !== "string" || content.trim().length === 0)
23447
23624
  return {};
@@ -23500,7 +23677,7 @@ async function askUserQuestion(turn, input, permissionContext) {
23500
23677
  });
23501
23678
  try {
23502
23679
  const answers = await Promise.race([answerPromise, timeoutPromise]);
23503
- log16.info("question.answers-received", { questionId, answerCount: Object.keys(answers).length });
23680
+ log17.info("question.answers-received", { questionId, answerCount: Object.keys(answers).length });
23504
23681
  return {
23505
23682
  behavior: "allow",
23506
23683
  updatedInput: {
@@ -23509,7 +23686,7 @@ async function askUserQuestion(turn, input, permissionContext) {
23509
23686
  }
23510
23687
  };
23511
23688
  } catch (error) {
23512
- log16.warn("question.wait-failed", { error: formatLogError(error) });
23689
+ log17.warn("question.wait-failed", { error: formatLogError(error) });
23513
23690
  const message = error instanceof Error ? error.message : "Question was cancelled";
23514
23691
  if (pendingQuestions.has(questionId)) {
23515
23692
  eventEmitter.emit({
@@ -23590,7 +23767,7 @@ async function requestPlanApproval(turn, input, permissionContext) {
23590
23767
  });
23591
23768
  try {
23592
23769
  const response = await Promise.race([approvalPromise, timeoutPromise]);
23593
- log16.info("plan-approval.result", {
23770
+ log17.info("plan-approval.result", {
23594
23771
  approvalId,
23595
23772
  approved: response.approved,
23596
23773
  hasFeedback: typeof response.feedback === "string" && response.feedback.length > 0
@@ -23639,7 +23816,7 @@ Please revise the plan based on this feedback.` : `I've reviewed the plan and I
23639
23816
  };
23640
23817
  }
23641
23818
  } catch (error) {
23642
- log16.warn("plan-approval.wait-failed", { error: formatLogError(error) });
23819
+ log17.warn("plan-approval.wait-failed", { error: formatLogError(error) });
23643
23820
  const errorMessage = error instanceof Error ? error.message : "Plan approval was cancelled";
23644
23821
  if (pendingPlanApprovals.has(approvalId)) {
23645
23822
  eventEmitter.emit({
@@ -23730,7 +23907,7 @@ function createClaudeRuntimeTurn(turn) {
23730
23907
  }
23731
23908
 
23732
23909
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-launch.ts
23733
- var log17 = createLogger("bridge.claude");
23910
+ var log18 = createLogger("bridge.claude");
23734
23911
  async function consumeClaudeRuntime(runtime, frames, markEnded) {
23735
23912
  let failure;
23736
23913
  try {
@@ -23807,7 +23984,7 @@ function releaseOrphanedForeground(runtime, error) {
23807
23984
  eventEmitter.emit({ type: "session.idle", sessionId, data: { success: true } });
23808
23985
  return;
23809
23986
  }
23810
- log17.error("runtime.ended-under-resumed-turn", { sessionId });
23987
+ log18.error("runtime.ended-under-resumed-turn", { sessionId });
23811
23988
  session.status = "error";
23812
23989
  session.error = error instanceof Error ? error.message : String(error);
23813
23990
  session.errorCode = undefined;
@@ -23972,7 +24149,7 @@ async function runTurnOnRuntime(turn, plan, testHooks) {
23972
24149
  }
23973
24150
 
23974
24151
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-settle.ts
23975
- var log18 = createLogger("bridge.claude");
24152
+ var log19 = createLogger("bridge.claude");
23976
24153
  function settleTurnEnd(turn) {
23977
24154
  const { session, sessionId, options, structuredRequestId, abortController, stream, diagnostics } = turn;
23978
24155
  diagnostics?.streamSettled("resolved");
@@ -24097,10 +24274,10 @@ function settleFailedTurn(turn, error) {
24097
24274
  const killedBy = killedClaudeProcessSignal(error);
24098
24275
  const usageLimited = !killedBy && (turn.rateLimitRejected || isUsageLimitError(error));
24099
24276
  if (usageLimited) {
24100
- log18.warn("prompt.usage-limited", { errorClass: diagnosticErrorClass(error) });
24277
+ log19.warn("prompt.usage-limited", { errorClass: diagnosticErrorClass(error) });
24101
24278
  markUsageLimitError(error);
24102
24279
  } else {
24103
- log18.error("prompt.failed", { errorClass: diagnosticErrorClass(error) });
24280
+ log19.error("prompt.failed", { errorClass: diagnosticErrorClass(error) });
24104
24281
  }
24105
24282
  if (session.abortController === abortController) {
24106
24283
  const failure = killedBy ? claudeProcessKilledMessage(killedBy) : error instanceof Error ? error.message : String(error);
@@ -24210,7 +24387,7 @@ function finalizeTurn(turn) {
24210
24387
  }
24211
24388
 
24212
24389
  // ../../bridges/claude-bridge/src/services/session-manager-prompt.ts
24213
- var log19 = createLogger("bridge.claude");
24390
+ var log20 = createLogger("bridge.claude");
24214
24391
  function turnWriterLiveness(turn) {
24215
24392
  const tasks = Object.values(turn.session.backgroundTasks ?? {});
24216
24393
  if (tasks.some((task) => LIVE_BACKGROUND_TASK_STATUSES.has(task.status)))
@@ -24253,7 +24430,7 @@ async function sendPrompt(sessionId, prompt, options, testHooks) {
24253
24430
  try {
24254
24431
  await sendPrompt(sessionId, followUp.prompt, followUp.options);
24255
24432
  } catch (repromptError) {
24256
- log19.error(followUp.failureEvent, { error: formatLogError(repromptError) });
24433
+ log20.error(followUp.failureEvent, { error: formatLogError(repromptError) });
24257
24434
  return Promise.reject(repromptError);
24258
24435
  }
24259
24436
  } catch (error) {
@@ -24265,7 +24442,7 @@ async function sendPrompt(sessionId, prompt, options, testHooks) {
24265
24442
  }
24266
24443
  }
24267
24444
  // ../../bridges/claude-bridge/src/services/session-manager-close.ts
24268
- var log20 = createLogger("bridge.claude");
24445
+ var log21 = createLogger("bridge.claude");
24269
24446
  var CLOSE_CONFIRMATION_BUDGET_MS = 1e4;
24270
24447
 
24271
24448
  class SessionCloseNotConfirmedError extends Error {
@@ -24328,7 +24505,7 @@ async function closeQueryControls(controls, deadline) {
24328
24505
  if (await settlesBy(Promise.resolve(control.close()), deadline))
24329
24506
  return;
24330
24507
  } catch (error) {
24331
- log20.error("query.close-failed", {
24508
+ log21.error("query.close-failed", {
24332
24509
  errorClass: error instanceof Error ? error.name : typeof error
24333
24510
  });
24334
24511
  }
@@ -24340,18 +24517,18 @@ async function settlesBy(work, deadline) {
24340
24517
  return (await boundedWait(work, Math.max(0, deadline - Date.now()))).settled;
24341
24518
  }
24342
24519
  // ../../bridges/claude-bridge/src/routes/config.ts
24343
- var log21 = createLogger("bridge.claude");
24520
+ var log22 = createLogger("bridge.claude");
24344
24521
  var config2 = new Hono2;
24345
24522
  config2.get("/models", async (c) => {
24346
24523
  if (c.req.query("forceRefresh") === "true")
24347
24524
  invalidateClaudeModelCatalog();
24348
24525
  const startedAt = Date.now();
24349
- log21.debug("models.requested");
24526
+ log22.debug("models.requested");
24350
24527
  const [{ models, source }, versions] = await Promise.all([
24351
24528
  getAvailableModelCatalog(),
24352
24529
  getClaudeRuntimeVersions()
24353
24530
  ]);
24354
- log21.debug("models.responded", { count: models.length, durationMs: Date.now() - startedAt });
24531
+ log22.debug("models.responded", { count: models.length, durationMs: Date.now() - startedAt });
24355
24532
  const response = {
24356
24533
  models,
24357
24534
  source,
@@ -25375,7 +25552,7 @@ function bridgeTranscriptPageRouteBody(source, query) {
25375
25552
  }
25376
25553
 
25377
25554
  // ../../bridges/claude-bridge/src/routes/session-transcript.ts
25378
- var log22 = createLogger("bridge.claude");
25555
+ var log23 = createLogger("bridge.claude");
25379
25556
  function claudeTranscriptSource(id, generation) {
25380
25557
  const sessionData = peekSession(id);
25381
25558
  if (!sessionData)
@@ -25428,7 +25605,7 @@ function registerSessionTranscriptRoutes(app, generation, materialize) {
25428
25605
  const response = c.json(bridgeTranscriptRouteBody(read.source, query3(c)));
25429
25606
  if (read.needsHydration) {
25430
25607
  hydratePersistedSessionMessages(id).catch((error) => {
25431
- log22.warn("transcript.background-hydrate-failed", {
25608
+ log23.warn("transcript.background-hydrate-failed", {
25432
25609
  error: formatLogError(error, { stack: false })
25433
25610
  });
25434
25611
  });
@@ -25440,7 +25617,7 @@ function registerSessionTranscriptRoutes(app, generation, materialize) {
25440
25617
  }
25441
25618
 
25442
25619
  // ../../bridges/claude-bridge/src/routes/session.ts
25443
- var log23 = createLogger("bridge.claude");
25620
+ var log24 = createLogger("bridge.claude");
25444
25621
  var session = new Hono2;
25445
25622
  var TRANSCRIPT_GENERATION = randomUUID6();
25446
25623
  var MAX_QUESTION_ANSWER_REQUEST_BYTES = AGENT_INTERACTION_LIMITS.maxSerializedPayloadBytes + 1024;
@@ -25497,10 +25674,10 @@ function isUsageLimitedRejection(error) {
25497
25674
  }
25498
25675
  function logPromptProcessingFailure(error) {
25499
25676
  if (isUsageLimitedRejection(error)) {
25500
- log23.debug("prompt.processing-usage-limited");
25677
+ log24.debug("prompt.processing-usage-limited");
25501
25678
  return;
25502
25679
  }
25503
- log23.error("prompt.processing-failed", { error: formatLogError(error) });
25680
+ log24.error("prompt.processing-failed", { error: formatLogError(error) });
25504
25681
  }
25505
25682
  var STALE_PROMPT_STATUS = 409;
25506
25683
  function stalePrompt(message) {
@@ -25536,7 +25713,7 @@ session.post("/create", async (c) => {
25536
25713
  const clientSessionKey = body.clientSessionKey;
25537
25714
  const policy = effectiveExecutionPolicy(isNativeAgentExecutionPolicy(body.policy) ? body.policy : undefined);
25538
25715
  const newSession = policy ? await createOrRecoverSession(title, clientSessionKey, policy) : await createOrRecoverSession(title, clientSessionKey);
25539
- log23.info("session.created", { sessionId: newSession.id });
25716
+ log24.info("session.created", { sessionId: newSession.id });
25540
25717
  const response = {
25541
25718
  sessionId: newSession.id,
25542
25719
  title: newSession.title
@@ -25544,10 +25721,10 @@ session.post("/create", async (c) => {
25544
25721
  return c.json(response, 201);
25545
25722
  } catch (error) {
25546
25723
  if (error instanceof PolicyWideningRefusedError) {
25547
- log23.warn("session.policy-widening-refused", { widened: error.widened.join(",") });
25724
+ log24.warn("session.policy-widening-refused", { widened: error.widened.join(",") });
25548
25725
  return c.json(error.refusal(), 403);
25549
25726
  }
25550
- log23.error("session.create-failed", { error: formatLogError(error) });
25727
+ log24.error("session.create-failed", { error: formatLogError(error) });
25551
25728
  return c.json({ error: error instanceof Error ? error.message : "Failed to create session" }, 500);
25552
25729
  }
25553
25730
  });
@@ -25555,7 +25732,7 @@ session.get("/list", async (c) => {
25555
25732
  try {
25556
25733
  await reconcilePersistedSessions();
25557
25734
  } catch (error) {
25558
- log23.warn("sessions.reconcile-failed", { error: formatLogError(error) });
25735
+ log24.warn("sessions.reconcile-failed", { error: formatLogError(error) });
25559
25736
  }
25560
25737
  const sessions = listSessions();
25561
25738
  const response = {
@@ -25574,7 +25751,7 @@ async function resolveSession(id, failureMessage) {
25574
25751
  try {
25575
25752
  return { ok: true, session: getSession(id) ?? await ensurePersistedSession(id) };
25576
25753
  } catch (error) {
25577
- log23.error("session.resolve-failed", { action: failureMessage, error: formatLogError(error) });
25754
+ log24.error("session.resolve-failed", { action: failureMessage, error: formatLogError(error) });
25578
25755
  return {
25579
25756
  ok: false,
25580
25757
  body: { error: errorMessage(error, failureMessage) },
@@ -25595,7 +25772,7 @@ session.get("/:id", async (c) => {
25595
25772
  try {
25596
25773
  await hydratePersistedSessionMessages(id);
25597
25774
  } catch (error) {
25598
- log23.error("session.task-state-hydrate-failed", { error: formatLogError(error) });
25775
+ log24.error("session.task-state-hydrate-failed", { error: formatLogError(error) });
25599
25776
  return c.json({ error: errorMessage(error, "Failed to hydrate session task state") }, sessionErrorStatus(error));
25600
25777
  }
25601
25778
  }
@@ -25647,7 +25824,7 @@ session.get("/:id/usage", async (c) => {
25647
25824
  const contextUsage = await refreshClaudeContextUsage(resolved.session);
25648
25825
  return c.json({ contextUsage });
25649
25826
  } catch (error) {
25650
- log23.warn("context-usage.read-failed", { error: formatLogError(error, { stack: false }) });
25827
+ log24.warn("context-usage.read-failed", { error: formatLogError(error, { stack: false }) });
25651
25828
  return c.json({ error: "Context usage is temporarily unavailable" }, 503);
25652
25829
  }
25653
25830
  });
@@ -25668,7 +25845,7 @@ session.post("/:id/config", async (c) => {
25668
25845
  const refusePolicyWidening = () => {
25669
25846
  const widened = nextPolicy ? executionPolicyWidenings(sessionData.executionPolicy, nextPolicy) : [];
25670
25847
  if (widened.length > 0) {
25671
- log23.warn("session.policy-widening-refused", {
25848
+ log24.warn("session.policy-widening-refused", {
25672
25849
  sessionId: sessionData.id,
25673
25850
  widened: widened.join(",")
25674
25851
  });
@@ -25709,7 +25886,7 @@ session.get("/:id/commands", async (c) => {
25709
25886
  try {
25710
25887
  return c.json(await readClaudeCommandCatalogue(c.req.param("id")));
25711
25888
  } catch (error) {
25712
- log23.warn("commands.read-failed", { error: formatLogError(error, { stack: false }) });
25889
+ log24.warn("commands.read-failed", { error: formatLogError(error, { stack: false }) });
25713
25890
  return c.json({ error: errorMessage(error, "Claude command discovery failed") }, 503);
25714
25891
  }
25715
25892
  });
@@ -25957,7 +26134,7 @@ session.post("/:id/prompt", async (c) => {
25957
26134
  duplicate: true
25958
26135
  });
25959
26136
  }
25960
- log23.debug("prompt.accepted", { sessionId: id });
26137
+ log24.debug("prompt.accepted", { sessionId: id });
25961
26138
  return c.json({
25962
26139
  status: "processing",
25963
26140
  requestId,
@@ -25970,7 +26147,7 @@ session.post("/:id/prompt", async (c) => {
25970
26147
  if (sessionData.rewindInProgress === true) {
25971
26148
  return c.json({ error: "Session is restoring files from a checkpoint" }, 409);
25972
26149
  }
25973
- log23.info("prompt.received", {
26150
+ log24.info("prompt.received", {
25974
26151
  sessionId: id,
25975
26152
  promptLength: prompt.length,
25976
26153
  model,
@@ -26000,14 +26177,14 @@ session.post("/:id/prompt", async (c) => {
26000
26177
  }).catch((error) => {
26001
26178
  logPromptProcessingFailure(error);
26002
26179
  });
26003
- log23.debug("prompt.accepted", { sessionId: id });
26180
+ log24.debug("prompt.accepted", { sessionId: id });
26004
26181
  return c.json({
26005
26182
  status: "processing",
26006
26183
  requestId,
26007
26184
  turnStartedAt: sessionData.turnStartedAt
26008
26185
  }, 202);
26009
26186
  } catch (error) {
26010
- log23.error("prompt.send-failed", { error: formatLogError(error) });
26187
+ log24.error("prompt.send-failed", { error: formatLogError(error) });
26011
26188
  return c.json({ error: errorMessage(error, "Failed to send prompt") }, sessionErrorStatus(error));
26012
26189
  }
26013
26190
  });
@@ -26068,7 +26245,7 @@ session.post("/:id/fork", async (c) => {
26068
26245
  title: forked.title
26069
26246
  }, 201);
26070
26247
  } catch (error) {
26071
- log23.error("session.fork-failed", { error: formatLogError(error) });
26248
+ log24.error("session.fork-failed", { error: formatLogError(error) });
26072
26249
  return c.json({ error: errorMessage(error, "Failed to fork session") }, sessionErrorStatus(error));
26073
26250
  }
26074
26251
  });
@@ -26100,7 +26277,7 @@ session.post("/:id/compact", compactBodyLimit, async (c) => {
26100
26277
  }
26101
26278
  const { instructions } = parsed;
26102
26279
  sendPrompt(id, instructions ? `/compact ${instructions}` : "/compact").catch((error) => {
26103
- log23.error("session.compact-failed", { error: formatLogError(error) });
26280
+ log24.error("session.compact-failed", { error: formatLogError(error) });
26104
26281
  });
26105
26282
  return c.json(instructions ? { status: "processing", instructions: "applied" } : { status: "processing" }, 202);
26106
26283
  });
@@ -26118,7 +26295,7 @@ session.post("/:id/rewind", async (c) => {
26118
26295
  const result = await rewindSessionFiles(id, messageId, dryRun);
26119
26296
  return c.json({ status: dryRun ? "previewed" : "rewound", result });
26120
26297
  } catch (error) {
26121
- log23.error("session.rewind-failed", { error: formatLogError(error) });
26298
+ log24.error("session.rewind-failed", { error: formatLogError(error) });
26122
26299
  return c.json({ error: errorMessage(error, "Failed to rewind session files") }, sessionErrorStatus(error));
26123
26300
  }
26124
26301
  });
@@ -26129,7 +26306,7 @@ session.post("/:id/tasks/:taskId/stop", async (c) => {
26129
26306
  return c.json({ status: "stopped" });
26130
26307
  return c.json({ error: stopped.message }, stopped.reason === "no_control_channel" ? 409 : 404);
26131
26308
  } catch (error) {
26132
- log23.error("task.stop-route-failed", { error: formatLogError(error) });
26309
+ log24.error("task.stop-route-failed", { error: formatLogError(error) });
26133
26310
  return c.json({ error: errorMessage(error, "Failed to stop background task") }, sessionErrorStatus(error));
26134
26311
  }
26135
26312
  });
@@ -26200,7 +26377,7 @@ session.post("/:id/questions/:questionId/answer", questionAnswerBodyLimit, async
26200
26377
  const pendingQuestions = getPendingQuestions(sessionId);
26201
26378
  const pendingQuestion = pendingQuestions.find((q) => q.id === questionId);
26202
26379
  if (!pendingQuestion) {
26203
- log23.info("question.stale", { questionId });
26380
+ log24.info("question.stale", { questionId });
26204
26381
  return c.json(stalePrompt("Question is no longer pending"), STALE_PROMPT_STATUS);
26205
26382
  }
26206
26383
  if (!isBoundedClaudeQuestionAnswers(answersArray, pendingQuestion.questions.length)) {
@@ -26211,7 +26388,7 @@ session.post("/:id/questions/:questionId/answer", questionAnswerBodyLimit, async
26211
26388
  const questionAnswers = answersArray[index] || [];
26212
26389
  answersRecord[q.question] = serializeClaudeQuestionAnswer(questionAnswers, q.multiSelect === true);
26213
26390
  });
26214
- log23.debug("question.answers-prepared", {
26391
+ log24.debug("question.answers-prepared", {
26215
26392
  questionId,
26216
26393
  questionCount: pendingQuestion.questions.length,
26217
26394
  answerCount: answersArray.reduce((count, answers) => count + answers.length, 0)
@@ -26223,7 +26400,7 @@ session.post("/:id/questions/:questionId/answer", questionAnswerBodyLimit, async
26223
26400
  return c.json(stalePrompt("Question is no longer pending"), STALE_PROMPT_STATUS);
26224
26401
  }
26225
26402
  } catch (error) {
26226
- log23.error("question.answer-failed", { error: formatLogError(error) });
26403
+ log24.error("question.answer-failed", { error: formatLogError(error) });
26227
26404
  return c.json({ error: error instanceof Error ? error.message : "Failed to answer question" }, 500);
26228
26405
  }
26229
26406
  });
@@ -26263,7 +26440,7 @@ session.post("/:id/plan-approvals/:approvalId/respond", planApprovalBodyLimit, a
26263
26440
  if (approved && (typeof pendingApproval.plan !== "string" || pendingApproval.plan.trim().length === 0 || pendingApproval.planTruncated === true)) {
26264
26441
  return c.json({ error: "A complete plan is required before approval", status: "rejected" }, 409);
26265
26442
  }
26266
- log23.info("plan-approval.response-received", {
26443
+ log24.info("plan-approval.response-received", {
26267
26444
  sessionId,
26268
26445
  approvalId,
26269
26446
  approved,
@@ -26276,7 +26453,7 @@ session.post("/:id/plan-approvals/:approvalId/respond", planApprovalBodyLimit, a
26276
26453
  return c.json(stalePrompt("Plan approval is no longer pending"), STALE_PROMPT_STATUS);
26277
26454
  }
26278
26455
  } catch (error) {
26279
- log23.error("plan-approval.response-failed", { error: formatLogError(error) });
26456
+ log24.error("plan-approval.response-failed", { error: formatLogError(error) });
26280
26457
  return c.json({ error: error instanceof Error ? error.message : "Failed to respond to plan approval" }, 500);
26281
26458
  }
26282
26459
  });
@@ -26675,7 +26852,7 @@ class EventRing {
26675
26852
  }
26676
26853
 
26677
26854
  // ../../bridges/claude-bridge/src/routes/events.ts
26678
- var log24 = createLogger("bridge.claude");
26855
+ var log25 = createLogger("bridge.claude");
26679
26856
  var serializedEvents = new WeakMap;
26680
26857
  function serializeEvent(event) {
26681
26858
  let serialized = serializedEvents.get(event);
@@ -26926,14 +27103,14 @@ function createEventsRouter(limits = {}) {
26926
27103
  events.get("/subscribe", (c) => {
26927
27104
  const origin = c.req.header("origin");
26928
27105
  const userAgent = c.req.header("user-agent");
26929
- log24.debug("sse.subscribe-requested", { origin, userAgent });
27106
+ log25.debug("sse.subscribe-requested", { origin, userAgent });
26930
27107
  return streamSSE(c, async (stream) => {
26931
27108
  const connectedAt = new Date().toISOString();
26932
- log24.debug("sse.opened", { connectedAt });
27109
+ log25.debug("sse.opened", { connectedAt });
26933
27110
  let isOpen = true;
26934
27111
  const closure = createSseConnectionClosure();
26935
27112
  const onRequestAbort = () => {
26936
- log24.debug("sse.aborted");
27113
+ log25.debug("sse.aborted");
26937
27114
  isOpen = false;
26938
27115
  closure.close();
26939
27116
  };
@@ -26947,7 +27124,7 @@ function createEventsRouter(limits = {}) {
26947
27124
  if (!isOpen)
26948
27125
  return;
26949
27126
  isOpen = false;
26950
- log24.info("sse.closed", { reason });
27127
+ log25.info("sse.closed", { reason });
26951
27128
  closure.close();
26952
27129
  };
26953
27130
  const writeFrame = createBoundedSseWriter(async (frame) => {
@@ -26998,7 +27175,7 @@ function createEventsRouter(limits = {}) {
26998
27175
  }
26999
27176
  writeFrame(frame).catch((error) => {
27000
27177
  if (!c.req.raw.signal.aborted) {
27001
- log24.warn("sse.write-failed", { error: formatLogError(error) });
27178
+ log25.warn("sse.write-failed", { error: formatLogError(error) });
27002
27179
  closeConnection("write failed");
27003
27180
  }
27004
27181
  });
@@ -27060,7 +27237,7 @@ function createEventsRouter(limits = {}) {
27060
27237
  data: JSON.stringify({ timestamp: new Date().toISOString() })
27061
27238
  }).catch((error) => {
27062
27239
  if (!c.req.raw.signal.aborted) {
27063
- log24.warn("sse.keepalive-failed", { error: formatLogError(error, { stack: false }) });
27240
+ log25.warn("sse.keepalive-failed", { error: formatLogError(error, { stack: false }) });
27064
27241
  closeConnection("keepalive failed");
27065
27242
  }
27066
27243
  });
@@ -27068,10 +27245,10 @@ function createEventsRouter(limits = {}) {
27068
27245
  await closure.closed;
27069
27246
  } catch (error) {
27070
27247
  if (!c.req.raw.signal.aborted) {
27071
- log24.warn("sse.handshake-failed", { error: formatLogError(error) });
27248
+ log25.warn("sse.handshake-failed", { error: formatLogError(error) });
27072
27249
  }
27073
27250
  } finally {
27074
- log24.debug("sse.cleanup");
27251
+ log25.debug("sse.cleanup");
27075
27252
  isOpen = false;
27076
27253
  c.req.raw.signal.removeEventListener("abort", onRequestAbort);
27077
27254
  if (keepaliveInterval)
@@ -27087,7 +27264,7 @@ var events = createEventsRouter();
27087
27264
  var events_default = events;
27088
27265
 
27089
27266
  // ../../bridges/claude-bridge/src/routes/mcp.ts
27090
- var log25 = createLogger("bridge.claude");
27267
+ var log26 = createLogger("bridge.claude");
27091
27268
  var mcp = new Hono2;
27092
27269
  mcp.get("/servers", async (c) => {
27093
27270
  try {
@@ -27098,14 +27275,14 @@ mcp.get("/servers", async (c) => {
27098
27275
  cwd
27099
27276
  });
27100
27277
  } catch (error) {
27101
- log25.error("mcp.read-failed", { error: formatLogError(error) });
27278
+ log26.error("mcp.read-failed", { error: formatLogError(error) });
27102
27279
  return c.json({ error: error instanceof Error ? error.message : "Failed to get MCP servers" }, 500);
27103
27280
  }
27104
27281
  });
27105
27282
  var mcp_default = mcp;
27106
27283
 
27107
27284
  // ../../bridges/claude-bridge/src/routes/plugins.ts
27108
- var log26 = createLogger("bridge.claude");
27285
+ var log27 = createLogger("bridge.claude");
27109
27286
  var plugins = new Hono2;
27110
27287
  plugins.get("/", async (c) => {
27111
27288
  try {
@@ -27116,7 +27293,7 @@ plugins.get("/", async (c) => {
27116
27293
  cwd
27117
27294
  });
27118
27295
  } catch (error) {
27119
- log26.error("plugins.read-failed", { error: formatLogError(error) });
27296
+ log27.error("plugins.read-failed", { error: formatLogError(error) });
27120
27297
  return c.json({ error: error instanceof Error ? error.message : "Failed to get plugins" }, 500);
27121
27298
  }
27122
27299
  });
@@ -27309,9 +27486,9 @@ function installFatalRejectionGuard(options) {
27309
27486
  }
27310
27487
 
27311
27488
  // ../protocol/src/node/process-failure-log.ts
27312
- var log27 = createLogger("process");
27489
+ var log28 = createLogger("process");
27313
27490
  function logUnhandledRejection(reason) {
27314
- log27.throttled("error", "rejection.unhandled", {
27491
+ log28.throttled("error", "rejection.unhandled", {
27315
27492
  error: reason,
27316
27493
  fields: () => ({ error: formatLogError(reason, { message: false }) })
27317
27494
  });
@@ -28990,7 +29167,7 @@ async function admitFetchBridgeRequest(authority, original, maxBodyBytes = BRIDG
28990
29167
  var BRIDGE_TOKEN_PREFIX = "okb_";
28991
29168
  var PR_SET_DUMPABLE = 4;
28992
29169
  var VERIFIER_PATTERN = /^[0-9a-f]{64}$/;
28993
- var log28 = createLogger("bridge.lifecycle");
29170
+ var log29 = createLogger("bridge.lifecycle");
28994
29171
  function mintBridgeToken() {
28995
29172
  return `${BRIDGE_TOKEN_PREFIX}${randomBytes3(32).toString("base64url")}`;
28996
29173
  }
@@ -29033,9 +29210,9 @@ function markProcessNonDumpable(loadFfi = () => createRequire2(import.meta.url)(
29033
29210
  } finally {
29034
29211
  libc.close();
29035
29212
  }
29036
- log28.warn("credential.not-hardened", { reason: "prctl-refused" });
29213
+ log29.warn("credential.not-hardened", { reason: "prctl-refused" });
29037
29214
  } catch {
29038
- log28.warn("credential.not-hardened", { reason: "ffi-unavailable" });
29215
+ log29.warn("credential.not-hardened", { reason: "ffi-unavailable" });
29039
29216
  }
29040
29217
  return false;
29041
29218
  }
@@ -29055,11 +29232,11 @@ function loadBridgeCredential(tokenEnv, options = {}) {
29055
29232
  }
29056
29233
 
29057
29234
  // ../../bridges/claude-bridge/src/index.ts
29058
- var log29 = createLogger("bridge.claude");
29235
+ var log30 = createLogger("bridge.claude");
29059
29236
  configureBridgeLogger();
29060
29237
  var app = new Hono2;
29061
29238
  app.onError((error, c) => {
29062
- log29.error("http.request-failed", {
29239
+ log30.error("http.request-failed", {
29063
29240
  method: c.req.method,
29064
29241
  path: c.req.path,
29065
29242
  error: formatLogError(error)
@@ -29170,7 +29347,7 @@ if (parentPid !== null) {
29170
29347
  startParentWatchdog({
29171
29348
  parentPid,
29172
29349
  onParentExit: () => {
29173
- log29.warn("parent.gone", { parentPid });
29350
+ log30.warn("parent.gone", { parentPid });
29174
29351
  process.exit(0);
29175
29352
  }
29176
29353
  });
@@ -29181,13 +29358,13 @@ function startBridgeServer(env = process.env, start = serve) {
29181
29358
  }
29182
29359
  const port = parseInt(env.PORT || "4097", 10);
29183
29360
  const hostname = env.HOSTNAME || "0.0.0.0";
29184
- log29.debug("server.starting", { hostname, port });
29361
+ log30.debug("server.starting", { hostname, port });
29185
29362
  const server = start({
29186
29363
  fetch: app.fetch,
29187
29364
  port,
29188
29365
  hostname
29189
29366
  });
29190
- log29.info("server.listening", { hostname, port });
29367
+ log30.info("server.listening", { hostname, port });
29191
29368
  return server;
29192
29369
  }
29193
29370
  var __testing = {