orkestrator 2.37.4-beta → 2.37.6-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -250,16 +250,20 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
250
250
  "prompt.accepted": "The route accepted a prompt and answered 202.",
251
251
  "prompt.failed": "A prompt turn failed; the session reports the error.",
252
252
  "prompt.processing-failed": "A prompt accepted by the route failed while processing.",
253
+ "prompt.processing-usage-limited": "A prompt accepted by the route ended on a usage limit; the turn already logged prompt.usage-limited.",
253
254
  "prompt.received": "A prompt reached the bridge; only its length is logged.",
254
255
  "prompt.send-failed": "A prompt request failed; the route answered with an error.",
256
+ "prompt.usage-limited": "A prompt turn ended because the account's plan allowance is used up; the session reports the limit.",
255
257
  "query.close-failed": "Stopping the Claude query failed while closing a tab; the close stays pending.",
256
258
  "query.failed": "A Claude query ended with an error result.",
259
+ "query.usage-limited": "Claude refused a query because the account's plan allowance is used up; the turn reports the limit.",
257
260
  "question.answer-failed": "The answer-question route failed.",
258
261
  "question.answering": "Answering a parked question.",
259
262
  "question.answers-prepared": "The route prepared a question answer for the session.",
260
263
  "question.answers-received": "A parked question received its answers.",
261
264
  "question.stale": "An answer arrived for a question no longer pending; the route answered stale.",
262
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.",
263
267
  "runtime.ended-under-resumed-turn": "The Claude runtime ended while a resumed root turn was still open.",
264
268
  "server.listening": "The HTTP server is listening.",
265
269
  "server.starting": "The HTTP server is about to bind.",
@@ -452,10 +456,10 @@ var DESKTOP_LOG_AREAS = defineLogAreas({
452
456
  "dev-mode.ignored-packaged": "A packaged app was launched with ELECTRON_DEV=1 and ignored it; it loads its bundled renderer.",
453
457
  "instance.already-running": "Another instance holds this data directory; this one will quit.",
454
458
  "main-thread.stalled": {
455
- description: "A timer fired late, so windows, IPC and the stdout reader waited.",
459
+ description: "A timer fired late, so windows, IPC and the stdout reader waited. `cpuMs` is the CPU time the process used in the window: near `lagMs` the main thread was busy, far below it the thread waited.",
456
460
  essential: true,
457
461
  minLevel: "error",
458
- fields: { lagMs: "number", intervalMs: "number" }
462
+ fields: { lagMs: "number", intervalMs: "number", cpuMs: "number" }
459
463
  },
460
464
  "process-memory": "Development only: working set per Electron process type, sampled on an interval.",
461
465
  "process-memory.failed": "Development only: one process memory sample could not be read.",
@@ -889,6 +893,7 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
889
893
  description: "The OpenCode 2.x provider: its event monitor, steering, routing, host and container servers.",
890
894
  events: {
891
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.",
892
897
  "steer.unconfirmed": "A 2.x steer got no definite answer, so its delivery is reconciled from history. Error class only.",
893
898
  "provider.dispose-failed": "Disposing the 2.x provider of a replaced server failed. Error class only.",
894
899
  "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.",
@@ -954,20 +959,26 @@ var RUNTIME_LOG_AREAS = defineLogAreas({
954
959
  description: "This process's event loop. A stall of 10 seconds or more is written at error, so no level hides it.",
955
960
  events: {
956
961
  stalled: {
957
- 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, and `blockingCommand` one whose synchronous part overlapped it.",
962
+ 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.",
958
963
  essential: true,
959
964
  minLevel: "error",
960
965
  fields: {
961
966
  lagMs: "number",
962
967
  intervalMs: "number",
968
+ cpuMs: "number",
963
969
  storageMs: "number",
964
970
  storageDatabase: "label",
965
971
  storageOp: "label",
966
972
  storageTable: "label",
967
973
  storageLongestMs: "number",
968
974
  storageBusy: "boolean",
975
+ storageCalls: "number",
976
+ storageCallMs: "number",
977
+ storageMainCallMs: "number",
978
+ storageLedgerCallMs: "number",
969
979
  commandsInFlight: "number",
970
- blockingCommandMs: "number"
980
+ blockingCommandMs: "number",
981
+ jobsInWindow: "number"
971
982
  }
972
983
  }
973
984
  }
@@ -1007,6 +1018,8 @@ var TERMINAL_LOG_AREAS = defineLogAreas({
1007
1018
  "pty.exit-notify-failed": "Notifying a terminal's exit failed.",
1008
1019
  "pty.late-exit-listener-failed": "A listener added after a terminal exited threw.",
1009
1020
  "setup.pty-reused": "A setup terminal reused its existing PTY.",
1021
+ "setup.pty-retired": "A setup retry ended the terminal the previous run left open, so the new run gets its own.",
1022
+ "setup.pty-retire-failed": "A setup retry could not end the previous run's process tree, so it kept that terminal and started nothing.",
1010
1023
  "setup.pty-spawning": "A setup terminal is spawning its PTY. The argument count only, never the arguments.",
1011
1024
  "setup.pty-spawned": "A setup terminal's PTY started.",
1012
1025
  "setup.pty-exited": "A setup terminal's PTY exited.",
@@ -1267,7 +1280,6 @@ var STORAGE_LOG_AREAS = defineLogAreas({
1267
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.",
1268
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.",
1269
1282
  "lease.heartbeat-failed": "A held lease's heartbeat failed, which shortens the lease; the next one retries.",
1270
- "scrub.vacuum-failed": "Deleted-content page reclamation failed; the checkpoint is attempted independently.",
1271
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.",
1272
1284
  "upkeep.vacuum-failed": "Periodic page reclamation failed; the next upkeep pass retries.",
1273
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`).",
@@ -1318,6 +1330,8 @@ var BUILD_PIPELINE_LOG_AREAS = defineLogAreas({
1318
1330
  "workspace.waiting": "A pipeline is waiting for its workspace; written once per reason.",
1319
1331
  "rewind.pending": "A pipeline's code rewind has not finished; written once per reason.",
1320
1332
  "kanban.status-failed": "A restarted pipeline's Kanban status could not be set; it retries shortly.",
1333
+ "kanban.environment-deleted-read-failed": "The pipelines of an environment being deleted could not be read, so their tickets keep their columns.",
1334
+ "kanban.environment-deleted-update-failed": "The ticket of a pipeline whose environment was deleted could not be moved; the deletion goes on.",
1321
1335
  "usage.read-failed": "Reading a stage session's token usage failed.",
1322
1336
  "checkpoint.deferred": "A stage transcript checkpoint could not be written yet; the provider's history stands.",
1323
1337
  "checkpoint.not-committed": "A stage transcript checkpoint was reverted in the commit that should have kept it.",
@@ -1368,6 +1382,7 @@ var CHANGE_TRACKING_LOG_AREAS = defineLogAreas({
1368
1382
  "baseline.update-failed": "An environment's diff baseline could not be updated.",
1369
1383
  "scan.watcher-failed": "An environment's diff watcher failed; its scans fall back to polling.",
1370
1384
  "scan.failed": "A diff scan failed; the last results stay, marked stale, and the scan is retried.",
1385
+ "scan.target-missing": "A local environment's worktree folder is missing (deleted, moved or on an unmounted drive); no scan runs, the last results stay, marked stale, and the folder is checked again on the failure backoff.",
1371
1386
  "scan.freshness-read-failed": "Reading whether an environment's remote is fresh failed.",
1372
1387
  "scan.listener-failed": "A change-tracking scan listener threw; the scan itself stands.",
1373
1388
  "emit.diff-stats-failed": "A diff stats change could not be emitted to its sink.",
@@ -1452,7 +1467,17 @@ var REVIEW_LOG_AREAS = defineLogAreas({
1452
1467
  "fix-outcome.read-failed": "Reading an interactive fix's outcome failed; it stays pending.",
1453
1468
  "fix-usage.read-failed": "Reading an Address Findings session's token usage failed.",
1454
1469
  "result.consume-deferred": "Consuming a workflow result failed; it stays staged and is retried.",
1455
- "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
+ }
1456
1481
  }
1457
1482
  },
1458
1483
  "pull-request": {
@@ -1545,9 +1570,10 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1545
1570
  "git-mirror.clone-fallback": "A new environment could not clone from its project's Git mirror and cloned from the remote.",
1546
1571
  "project-seed.refused": "A project .env, .env.local or opencode.json was not copied into a new container: a link, not a regular file, outside the project, too large or unreadable.",
1547
1572
  "opencode.warm-incomplete": "OpenCode did not finish loading /workspace in a container.",
1548
- "opencode.listener-replaced": "The process on a container's OpenCode port (`provider`: `opencode` or `opencode2`) is not the server the backend launched and recorded, so its password was withheld and the next start replaces it. `stage` is `request` when the re-check after a refused connection or an unexpected answer found it (to-do 7550); that connection then sends nothing more.",
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.",
1549
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.",
1550
- "opencode.project-config-filtered": "Values were left out of a checkout's OpenCode configuration before a launched server reads it (to-do 7550): counts of plugin keys, `{env:}` and `{file:}` references and dropped instructions (including separate instructionGlob and instructionUrl counts), and the names of files that were not a JSONC object. Never values.",
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.",
1551
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.",
1552
1578
  "lifecycle-event.reconcile-failed": "Reconciling an environment after a container start or stop event failed; the next status read retries.",
1553
1579
  "login-keeper.pass-failed": "A Claude login keeper pass failed; the next interval retries.",
@@ -1561,7 +1587,8 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1561
1587
  "recovery.clear-terminals-failed": "Terminal sessions could not be cleared after a recovery restore.",
1562
1588
  "github-ranges.seed-not-copied": "The GitHub ranges seed could not be copied into a container, so its firewall fetches them.",
1563
1589
  "availability.probe-failed": "Docker is not available; written when the diagnostic changes. Fixed-shape metadata only: messages can hold daemon endpoints.",
1564
- "start.port-collision-retrying": "An automatic host port collided on start, so it is retried once with fresh ports.",
1590
+ "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.",
1591
+ "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.",
1565
1592
  "writer-lease.lost": {
1566
1593
  description: "This backend lost the registry writer lease, for the fixed `reason` given. Schedules stop and container changes are refused until it restarts.",
1567
1594
  essential: true,
@@ -1584,7 +1611,7 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1584
1611
  fields: { provider: "label", containerPort: "number" }
1585
1612
  },
1586
1613
  "bridge.listener-refused": {
1587
- description: "The socket listening on a container bridge's port is not the one the bridge the backend started opened (to-do 7250), so its token is not handed out and the next start replaces it. `reason` is a fixed label: `different-socket`, `several-sockets`, `pending` (a start has not recorded its bridge yet, or failed before it did) or `scan-incomplete`.",
1614
+ description: "The socket listening on a container bridge's port is not the one the bridge the backend started opened, so its token is not handed out and the next start replaces it. `reason` is a fixed label: `different-socket`, `several-sockets`, `pending` (a start has not recorded its bridge yet, or failed before it did) or `scan-incomplete`.",
1588
1615
  essential: true,
1589
1616
  fields: { provider: "label", reason: "label" }
1590
1617
  },
@@ -2106,6 +2133,7 @@ var WEB_KANBAN_LOG_AREAS = defineLogAreas({
2106
2133
  "task.move-failed": "A task move failed and its status was rolled back.",
2107
2134
  "comment.add-failed": "A comment could not be added to a task.",
2108
2135
  "comment.delete-failed": "A comment could not be deleted from a task.",
2136
+ "pr.merge-failed": "Merging a ticket's pull request from its Notes tab failed; the error was shown to the user.",
2109
2137
  "image.add-failed": "An image could not be added to a task.",
2110
2138
  "image.delete-failed": "An image could not be deleted from a task.",
2111
2139
  "notes.load-failed": "Project notes could not be loaded; the editor stays disabled.",
@@ -3402,11 +3430,10 @@ function setLiveBridgeDiagnostics(enabled) {
3402
3430
  for (const scope of Array.from(liveScopes))
3403
3431
  scope.syncActive();
3404
3432
  }
3405
- function bridgeDebugEnabled(bridge, env = process.env) {
3433
+ function bridgeDebugEnabled(_bridge, env = process.env) {
3406
3434
  if (liveDiagnostics !== undefined && env === process.env)
3407
3435
  return liveDiagnostics;
3408
- const value = env.ORKESTRATOR_BRIDGE_DEBUG ?? env[`${bridge.toUpperCase()}_BRIDGE_DEBUG`];
3409
- return readBridgeDebugFlag(value);
3436
+ return readBridgeDebugFlag(env.ORKESTRATOR_BRIDGE_DEBUG);
3410
3437
  }
3411
3438
  function safeDiagnosticMetrics(value) {
3412
3439
  const result = {};
@@ -6871,26 +6898,6 @@ function claudePlanWindowFromKind(kind, modelName) {
6871
6898
  }
6872
6899
  return;
6873
6900
  }
6874
- var LEGACY_CLAUDE_WINDOW_LABELS = {
6875
- "five hour": "five_hour",
6876
- session: "five_hour",
6877
- weekly: "seven_day",
6878
- "weekly all": "seven_day",
6879
- "weekly (oauth apps)": "seven_day_oauth_apps"
6880
- };
6881
- function claudePlanWindowFromLabel(label) {
6882
- const normalized = label.trim().toLowerCase();
6883
- const legacyId = LEGACY_CLAUDE_WINDOW_LABELS[normalized];
6884
- for (const [id, meta] of Object.entries(CLAUDE_PLAN_WINDOW_LABELS)) {
6885
- if (id === legacyId || meta.label.toLowerCase() === normalized)
6886
- return { id, ...meta };
6887
- }
6888
- const model = label.trim().match(/^weekly \((.+)\)$/i)?.[1] ?? label.trim().match(/^weekly (.+) limit$/i)?.[1];
6889
- if (!model)
6890
- return;
6891
- const known = Object.entries(CLAUDE_PLAN_WINDOW_LABELS).find(([id]) => id === `seven_day_${model.trim().toLowerCase()}`);
6892
- return known ? { id: known[0], ...known[1] } : claudeModelWeeklyWindow(model);
6893
- }
6894
6901
 
6895
6902
  // ../../bridges/claude-bridge/src/services/event-message-id.ts
6896
6903
  function eventMessageId(event) {
@@ -7708,21 +7715,6 @@ async function updateSessionPreferences(sdkSessionId, update) {
7708
7715
  }).catch(() => {});
7709
7716
  return write;
7710
7717
  }
7711
- async function deleteSessionPreferences(sdkSessionId) {
7712
- const writeKey = normalizedSessionId(sdkSessionId);
7713
- const path = preferencesPath(sdkSessionId);
7714
- if (!writeKey || !path)
7715
- return;
7716
- const previous = pendingWrites.get(writeKey) ?? Promise.resolve();
7717
- const deletion = previous.catch(() => {}).then(() => withPreferenceFileLock(path, () => rm(path, { force: true })));
7718
- pendingWrites.set(writeKey, deletion);
7719
- deletion.finally(() => {
7720
- if (pendingWrites.get(writeKey) === deletion) {
7721
- pendingWrites.delete(writeKey);
7722
- }
7723
- }).catch(() => {});
7724
- return deletion;
7725
- }
7726
7718
 
7727
7719
  // ../../bridges/claude-bridge/src/services/session-manager-core.ts
7728
7720
  import { execFile } from "node:child_process";
@@ -7743,7 +7735,6 @@ var pendingPromptDispatchClaims = new Map;
7743
7735
  var IDLE_TRANSCRIPT_EVICTION_MS = 30 * 60 * 1000;
7744
7736
  var IDLE_TRANSCRIPT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
7745
7737
  var STRUCTURED_USAGE_REQUEST_TIMEOUT_MS = 1000;
7746
- var PLAN_USAGE_PROBE_TIMEOUT_MS = 1e4;
7747
7738
 
7748
7739
  class StructuredUsageRequestTimeoutError extends Error {
7749
7740
  constructor(timeoutMs = STRUCTURED_USAGE_REQUEST_TIMEOUT_MS) {
@@ -8502,8 +8493,6 @@ async function persistedSessionExistsOnDisk(sdkSessionId) {
8502
8493
  return true;
8503
8494
  try {
8504
8495
  const sdk = await claudeSdk();
8505
- if (typeof sdk.getSessionInfo !== "function")
8506
- return true;
8507
8496
  const info = await sdk.getSessionInfo(sdkSessionId, {
8508
8497
  dir: currentWorkingDirectory()
8509
8498
  });
@@ -8537,8 +8526,6 @@ async function persistSessionTitle(session, title) {
8537
8526
  if (!session.sdkSessionId)
8538
8527
  return;
8539
8528
  const sdk = await claudeSdk();
8540
- if (typeof sdk.renameSession !== "function")
8541
- return;
8542
8529
  await sdk.renameSession(session.sdkSessionId, title, {
8543
8530
  dir: currentWorkingDirectory()
8544
8531
  });
@@ -8790,20 +8777,177 @@ function withReadOnlyGitConfig(turnPolicy, environment) {
8790
8777
  return next;
8791
8778
  }
8792
8779
 
8793
- // ../../bridges/claude-bridge/src/services/coordinator-skills.ts
8794
- import { createHash as createHash4, randomBytes } from "node:crypto";
8795
- import {
8796
- mkdir as mkdir2,
8797
- readdir as readdir2,
8798
- readFile as readFile3,
8799
- realpath,
8800
- rename as rename2,
8801
- rm as rm2,
8802
- stat as stat2,
8803
- symlink,
8804
- writeFile as writeFile2
8805
- } from "node:fs/promises";
8806
- import { isAbsolute, join as join3 } from "node:path";
8780
+ // ../../bridges/claude-bridge/src/services/json-file-cache.ts
8781
+ import { createHash as createHash4 } from "node:crypto";
8782
+ import { readFile as readFile3, stat as stat2 } from "node:fs/promises";
8783
+ var SEPARATOR = "\x00";
8784
+ var slices = new Map;
8785
+ var readCohorts = new Map;
8786
+ var parseCounts = new Map;
8787
+ var beforeStatForTesting = null;
8788
+ function fingerprintOf(stats) {
8789
+ return `${stats.dev}:${stats.ino}:${stats.size}:${stats.mtimeMs}`;
8790
+ }
8791
+ function forgetFile(filePath) {
8792
+ const prefix = `${filePath}${SEPARATOR}`;
8793
+ for (const key of slices.keys()) {
8794
+ if (key.startsWith(prefix))
8795
+ slices.delete(key);
8796
+ }
8797
+ }
8798
+ function joinReadCohort(filePath) {
8799
+ const existing = readCohorts.get(filePath);
8800
+ if (existing) {
8801
+ existing.readers += 1;
8802
+ return existing;
8803
+ }
8804
+ const cohort = { readers: 1, parses: new Map };
8805
+ readCohorts.set(filePath, cohort);
8806
+ return cohort;
8807
+ }
8808
+ function leaveReadCohort(filePath, cohort) {
8809
+ cohort.readers -= 1;
8810
+ if (cohort.readers === 0 && readCohorts.get(filePath) === cohort) {
8811
+ readCohorts.delete(filePath);
8812
+ }
8813
+ }
8814
+ function parseOnce(filePath, fingerprint, cohort) {
8815
+ const existing = cohort.parses.get(fingerprint);
8816
+ if (existing)
8817
+ return existing;
8818
+ const parse = (async () => {
8819
+ parseCounts.set(filePath, (parseCounts.get(filePath) ?? 0) + 1);
8820
+ let bytes;
8821
+ try {
8822
+ bytes = await readFile3(filePath);
8823
+ } catch {
8824
+ return { parsed: null, digest: null };
8825
+ }
8826
+ const digest = createHash4("sha256").update(bytes).digest("base64url");
8827
+ try {
8828
+ return { parsed: JSON.parse(bytes.toString("utf-8")), digest };
8829
+ } catch {
8830
+ return { parsed: null, digest };
8831
+ }
8832
+ })();
8833
+ cohort.parses.set(fingerprint, parse);
8834
+ return parse;
8835
+ }
8836
+ async function readJsonSliceCached(filePath, sliceKey, select) {
8837
+ return (await readJsonSliceCachedWithDigest(filePath, sliceKey, select)).value;
8838
+ }
8839
+ async function readJsonSliceCachedWithDigest(filePath, sliceKey, select) {
8840
+ const cohort = joinReadCohort(filePath);
8841
+ try {
8842
+ await beforeStatForTesting?.(filePath);
8843
+ let fingerprint;
8844
+ try {
8845
+ fingerprint = fingerprintOf(await stat2(filePath));
8846
+ } catch {
8847
+ forgetFile(filePath);
8848
+ return { value: null, digest: null };
8849
+ }
8850
+ const key = `${filePath}${SEPARATOR}${sliceKey}`;
8851
+ const cached = slices.get(key);
8852
+ if (cached && cached.fingerprint === fingerprint) {
8853
+ return { value: cached.value, digest: cached.digest };
8854
+ }
8855
+ const { parsed, digest } = await parseOnce(filePath, fingerprint, cohort);
8856
+ let value = null;
8857
+ if (parsed !== null && parsed !== undefined) {
8858
+ try {
8859
+ value = select(parsed) ?? null;
8860
+ } catch {
8861
+ value = null;
8862
+ }
8863
+ }
8864
+ slices.set(key, { fingerprint, value, digest });
8865
+ return { value, digest };
8866
+ } finally {
8867
+ leaveReadCohort(filePath, cohort);
8868
+ }
8869
+ }
8870
+
8871
+ // ../protocol/src/coordinator-web-research.ts
8872
+ var COORDINATOR_WEB_RESEARCH_MODES = ["off", "search", "search-and-mcp"];
8873
+ var DEFAULT_COORDINATOR_RESEARCH_MCP_SERVERS = Object.freeze([{ name: "context7", url: "https://mcp.context7.com/mcp" }]);
8874
+ var MAX_COORDINATOR_RESEARCH_MCP_SERVERS = 8;
8875
+ var COORDINATOR_WEB_RESEARCH_ENV = "ORKESTRATOR_COORDINATOR_WEB_RESEARCH";
8876
+ var COORDINATOR_RESEARCH_MCP_ENV = "ORKESTRATOR_COORDINATOR_RESEARCH_MCP";
8877
+ var RESERVED_SERVER_NAME = /^orkestrator/;
8878
+ var SERVER_NAME = /^[a-z0-9][a-z0-9-]{0,31}$/;
8879
+ function isCoordinatorWebResearch(value) {
8880
+ return typeof value === "string" && COORDINATOR_WEB_RESEARCH_MODES.includes(value);
8881
+ }
8882
+ function coordinatorResearchMcpServerProblem(server) {
8883
+ if (!SERVER_NAME.test(server.name)) {
8884
+ return "Use 1 to 32 lowercase letters, digits or hyphens for the name.";
8885
+ }
8886
+ if (RESERVED_SERVER_NAME.test(server.name))
8887
+ return "Names starting with orkestrator are reserved.";
8888
+ let url;
8889
+ try {
8890
+ url = new URL(server.url);
8891
+ } catch {
8892
+ return "The URL is not valid.";
8893
+ }
8894
+ if (url.protocol !== "https:")
8895
+ return "Only https:// research servers are allowed.";
8896
+ if (url.username || url.password)
8897
+ return "Credentials in the URL are not allowed.";
8898
+ return;
8899
+ }
8900
+ function normalizeCoordinatorResearchMcpServers(value) {
8901
+ if (value === undefined)
8902
+ return DEFAULT_COORDINATOR_RESEARCH_MCP_SERVERS.map((s) => ({ ...s }));
8903
+ if (!Array.isArray(value))
8904
+ return [];
8905
+ const servers = [];
8906
+ const names = new Set;
8907
+ for (const entry of value) {
8908
+ if (servers.length >= MAX_COORDINATOR_RESEARCH_MCP_SERVERS)
8909
+ break;
8910
+ if (!entry || typeof entry !== "object")
8911
+ continue;
8912
+ const { name, url } = entry;
8913
+ if (typeof name !== "string" || typeof url !== "string")
8914
+ continue;
8915
+ const server = { name: name.trim(), url: url.trim() };
8916
+ if (coordinatorResearchMcpServerProblem(server) || names.has(server.name))
8917
+ continue;
8918
+ names.add(server.name);
8919
+ servers.push(server);
8920
+ }
8921
+ return servers;
8922
+ }
8923
+ function coordinatorWebResearchFromEnv(env) {
8924
+ const value = env[COORDINATOR_WEB_RESEARCH_ENV];
8925
+ return isCoordinatorWebResearch(value) ? value : "off";
8926
+ }
8927
+ function coordinatorResearchMcpServersFromEnv(env) {
8928
+ if (coordinatorWebResearchFromEnv(env) !== "search-and-mcp")
8929
+ return [];
8930
+ const raw = env[COORDINATOR_RESEARCH_MCP_ENV];
8931
+ if (!raw)
8932
+ return [];
8933
+ try {
8934
+ return normalizeCoordinatorResearchMcpServers(JSON.parse(raw));
8935
+ } catch {
8936
+ return [];
8937
+ }
8938
+ }
8939
+ var COORDINATOR_DENIED = Object.freeze([
8940
+ "file.write",
8941
+ "file.patch",
8942
+ "shell.mutate",
8943
+ "network"
8944
+ ]);
8945
+ function coordinatorCapabilityPolicy(mode) {
8946
+ return {
8947
+ deny: [...COORDINATOR_DENIED],
8948
+ ...mode === "off" ? {} : { allow: ["web.search"] }
8949
+ };
8950
+ }
8807
8951
  // ../protocol/src/coordinator.ts
8808
8952
  var COORDINATOR_COMMAND_SANDBOX_ENV = "ORKESTRATOR_COORDINATOR_COMMAND_SANDBOX";
8809
8953
  var COORDINATOR_PROTECTED_DATA_DIR_ENV = "ORKESTRATOR_COORDINATOR_PROTECTED_DATA_DIR";
@@ -8904,1285 +9048,1256 @@ var COORDINATOR_CONTROL_TOOL_NAMES = Object.freeze([
8904
9048
  ]);
8905
9049
  var COORDINATOR_PROJECT_HOME_MESSAGE_WINDOW_MS = 3 * 60 * 60000;
8906
9050
 
8907
- // ../../bridges/claude-bridge/src/services/coordinator-skills.ts
8908
- var KEPT_FRONTMATTER_KEYS = Object.freeze([
8909
- "name",
8910
- "description",
8911
- "when_to_use",
8912
- "argument-hint",
8913
- "arguments",
8914
- "disable-model-invocation",
8915
- "user-invocable",
8916
- "version"
8917
- ]);
8918
- var MIRROR_FORMAT = 1;
8919
- var MAX_SKILLS_PER_SOURCE = 256;
8920
- var MAX_SKILL_FILE_BYTES = 1024 * 1024;
8921
- var MAX_ENTRIES_PER_SKILL = 256;
8922
- var KEPT_OLD_MIRRORS = 4;
8923
- var SKILL_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
8924
- var FRONTMATTER = /^?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;
8925
- function coordinatorSkillSources(cwd, env = process.env) {
8926
- const userDir = env[COORDINATOR_CLAUDE_USER_SKILLS_DIR_ENV]?.trim();
8927
- return [
8928
- ...userDir && isAbsolute(userDir) ? [{ plugin: "user-skills", dir: userDir }] : [],
8929
- { plugin: "project-skills", dir: join3(cwd, ".claude", "skills") }
8930
- ];
9051
+ // ../../bridges/claude-bridge/src/services/mcp-tool-prefix.ts
9052
+ function claudeMcpToolPrefix(name) {
9053
+ let normalized = name.replace(/[^a-zA-Z0-9_-]/g, "_");
9054
+ if (name.startsWith("claude.ai ")) {
9055
+ normalized = normalized.replace(/_+/g, "_").replace(/^_|_$/g, "");
9056
+ }
9057
+ return `mcp__${normalized}__`;
8931
9058
  }
8932
- async function coordinatorSkillPlugins(sources, root = claudeCoordinatorSkillPluginsDir()) {
8933
- const plugins = [];
8934
- const skills = [];
8935
- for (const source of sources) {
9059
+
9060
+ // ../../bridges/claude-bridge/src/services/read-only-path-boundary.ts
9061
+ import { join as join4 } from "node:path";
9062
+
9063
+ // ../protocol/src/node/coordinator-read-boundary.ts
9064
+ import { realpathSync } from "node:fs";
9065
+ import { homedir as homedir2 } from "node:os";
9066
+ import { dirname as dirname2, isAbsolute, join as join3, parse, resolve as resolve2, sep } from "node:path";
9067
+ function canonicalPath(path) {
9068
+ let existing = path;
9069
+ const tail = [];
9070
+ for (;; ) {
8936
9071
  try {
8937
- const mirror = await mirrorSkillSource(source, root);
8938
- if (!mirror)
8939
- continue;
8940
- plugins.push({ type: "local", path: mirror.path });
8941
- skills.push(...mirror.names.map((name) => `${source.plugin}:${name}`));
8942
- } catch (error) {
8943
- debugLog("[coordinator-skills] Skipping skills source", {
8944
- plugin: source.plugin,
8945
- error: error instanceof Error ? error.message : String(error)
8946
- });
9072
+ return join3(realpathSync.native(existing), ...tail.reverse());
9073
+ } catch {
9074
+ const parent = dirname2(existing);
9075
+ if (parent === existing)
9076
+ return path;
9077
+ tail.push(existing.slice(parent.length).replace(/^[/\\]+/, ""));
9078
+ existing = parent;
8947
9079
  }
8948
9080
  }
8949
- return { plugins, skills };
8950
9081
  }
8951
- async function mirrorSkillSource(source, root) {
8952
- const dir = await realpath(source.dir).catch(() => {
8953
- return;
8954
- });
8955
- if (!dir)
8956
- return;
8957
- const skills = await readSkills(dir);
8958
- if (skills.length === 0)
8959
- return;
8960
- const digest = createHash4("sha256").update(JSON.stringify([MIRROR_FORMAT, source.plugin, dir, skills])).digest("hex").slice(0, 24);
8961
- const path = join3(root, `${source.plugin}-${digest}`);
8962
- if (!await isMirror(path))
8963
- await writeMirror(root, path, source.plugin, skills);
8964
- await pruneOldMirrors(root, source.plugin, path);
8965
- return { path, names: skills.map((skill) => skill.name) };
9082
+ function namedAndCanonicalPaths(paths) {
9083
+ const named = paths.flatMap((path) => path?.trim() && isAbsolute(path) ? [path] : []);
9084
+ return [...new Set(named.flatMap((path) => [resolve2(path), canonicalPath(path)]))];
8966
9085
  }
8967
- async function readSkills(dir) {
8968
- const entries = (await readdir2(dir)).filter((name) => !name.startsWith(".")).sort();
8969
- const skills = [];
8970
- const names = new Set;
8971
- for (const entry of entries) {
8972
- if (skills.length >= MAX_SKILLS_PER_SOURCE)
8973
- break;
8974
- const skillDir = await realpath(join3(dir, entry)).catch(() => {
8975
- return;
8976
- });
8977
- if (!skillDir || !(await stat2(skillDir).catch(() => {
8978
- return;
8979
- }))?.isDirectory())
8980
- continue;
8981
- const skill = await readSkill(skillDir, entry);
8982
- if (!skill || names.has(skill.name))
8983
- continue;
8984
- names.add(skill.name);
8985
- skills.push(skill);
8986
- }
8987
- return skills;
9086
+ function isWithin(root, path) {
9087
+ if (path === root)
9088
+ return true;
9089
+ const prefix = root === parse(root).root ? root : `${root}${sep}`;
9090
+ return path.startsWith(prefix);
8988
9091
  }
8989
- async function readSkill(skillDir, dirName) {
8990
- const entries = await readdir2(skillDir);
8991
- const skillFile = entries.find((entry) => entry === "SKILL.md");
8992
- if (!skillFile)
8993
- return;
8994
- const file = join3(skillDir, skillFile);
8995
- const info = await stat2(file).catch(() => {
8996
- return;
8997
- });
8998
- if (!info?.isFile() || info.size > MAX_SKILL_FILE_BYTES)
8999
- return;
9000
- const sanitized = sanitizeSkillFile(await readFile3(file, "utf8"), dirName);
9001
- if (!sanitized) {
9002
- debugLog("[coordinator-skills] Skipping skill with unreadable frontmatter", { dirName });
9003
- return;
9004
- }
9005
- const links = entries.filter((entry) => entry.toLowerCase() !== "skill.md").sort().slice(0, MAX_ENTRIES_PER_SKILL).map((entry) => [entry, join3(skillDir, entry)]);
9006
- return { name: sanitized.name, text: sanitized.text, links };
9092
+ function protectedDataDirBoundary(dataDir, allowances) {
9093
+ const trimmed = dataDir?.trim();
9094
+ if (!trimmed || !isAbsolute(trimmed))
9095
+ return null;
9096
+ const deny = namedAndCanonicalPaths([trimmed]);
9097
+ return {
9098
+ deny,
9099
+ allow: namedAndCanonicalPaths(allowances).filter((path) => !deny.includes(path) && deny.some((root) => isWithin(root, path)))
9100
+ };
9007
9101
  }
9008
- function yamlParser() {
9009
- const parse = globalThis.Bun?.YAML?.parse;
9010
- return typeof parse === "function" ? parse : null;
9102
+ function deniedForm(boundary, path) {
9103
+ return boundary.deny.some((root) => isWithin(root, path)) && !boundary.allow.some((root) => isWithin(root, path));
9011
9104
  }
9012
- function sanitizeSkillFile(text, dirName, parse = yamlParser()) {
9013
- const match = FRONTMATTER.exec(text);
9014
- let fields = {};
9015
- if (match) {
9016
- if (!parse)
9017
- return;
9018
- let parsed;
9019
- try {
9020
- parsed = parse(match[1]);
9021
- } catch {
9022
- return;
9023
- }
9024
- if (parsed !== null && parsed !== undefined) {
9025
- if (typeof parsed !== "object" || Array.isArray(parsed))
9026
- return;
9027
- fields = parsed;
9028
- }
9029
- }
9030
- const declared = typeof fields.name === "string" ? fields.name.trim() : "";
9031
- const name = SKILL_NAME.test(declared) ? declared : dirName;
9032
- if (!SKILL_NAME.test(name))
9033
- return;
9034
- const lines = [`name: ${JSON.stringify(name)}`];
9035
- for (const key of KEPT_FRONTMATTER_KEYS) {
9036
- if (key === "name" || !Object.hasOwn(fields, key))
9037
- continue;
9038
- const value = frontmatterValue(fields[key]);
9039
- if (value !== undefined)
9040
- lines.push(`${key}: ${value}`);
9041
- }
9042
- const body = match ? text.slice(match[0].length) : text.replace(/^/, "");
9043
- return { name, text: `---
9044
- ${lines.join(`
9045
- `)}
9046
- ---
9047
- ${body}` };
9105
+ function expandedHome(path) {
9106
+ if (path === "~")
9107
+ return homedir2();
9108
+ return path.startsWith("~/") ? `${homedir2()}${sep}${path.slice(2)}` : path;
9048
9109
  }
9049
- function frontmatterValue(value) {
9050
- if (typeof value === "string" || typeof value === "boolean")
9051
- return JSON.stringify(value);
9052
- if (typeof value === "number" && Number.isFinite(value))
9053
- return JSON.stringify(String(value));
9054
- if (Array.isArray(value) && value.every((item) => typeof item === "string"))
9055
- return JSON.stringify(value);
9056
- return;
9110
+ function readBoundaryRefuses(boundary, path, cwd, options = {}) {
9111
+ const expanded = expandedHome(path);
9112
+ const raw = isAbsolute(expanded) ? expanded : `${cwd}${sep}${expanded}`;
9113
+ const lexical = resolve2(raw);
9114
+ const real = canonicalPath(raw);
9115
+ if (deniedForm(boundary, lexical) || deniedForm(boundary, real))
9116
+ return true;
9117
+ return options.traversal === true && boundary.deny.some((root) => isWithin(lexical, root) || isWithin(real, root));
9057
9118
  }
9058
- async function isMirror(path) {
9059
- return (await stat2(join3(path, ".claude-plugin", "plugin.json")).catch(() => {
9119
+
9120
+ // ../../bridges/claude-bridge/src/services/read-only-path-boundary.ts
9121
+ function claudeReadOnlyWorkspacePaths(cwd) {
9122
+ return [...new Set([cwd, canonicalPath(cwd)])];
9123
+ }
9124
+ function coordinatorReadBoundary(workspaces, env = process.env) {
9125
+ const dataDir = env[COORDINATOR_PROTECTED_DATA_DIR_ENV]?.trim();
9126
+ return protectedDataDirBoundary(dataDir, [
9127
+ env.CLAUDE_CONFIG_DIR,
9128
+ env.ORKESTRATOR_BRIDGE_ATTACHMENT_ROOT,
9129
+ env[COORDINATOR_CLAUDE_USER_SKILLS_DIR_ENV],
9130
+ dataDir ? join4(dataDir, "toolchains") : undefined,
9131
+ ...workspaces
9132
+ ]);
9133
+ }
9134
+ function globRoot(pattern) {
9135
+ if (!pattern.startsWith("/") && !pattern.startsWith("~") && !pattern.startsWith("..")) {
9060
9136
  return;
9061
- }))?.isFile() ? true : false;
9137
+ }
9138
+ const wildcard = pattern.search(/[*?[{]/);
9139
+ return wildcard < 0 ? pattern : pattern.slice(0, wildcard);
9062
9140
  }
9063
- async function writeMirror(root, path, plugin, skills) {
9064
- await mkdir2(root, { recursive: true, mode: 448 });
9065
- const staging = join3(root, `.staging-${randomBytes(8).toString("hex")}`);
9066
- try {
9067
- await mkdir2(join3(staging, ".claude-plugin"), { recursive: true });
9068
- await writeFile2(join3(staging, ".claude-plugin", "plugin.json"), JSON.stringify({
9069
- name: plugin,
9070
- 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."
9071
- }));
9072
- for (const skill of skills) {
9073
- const skillDir = join3(staging, "skills", skill.name);
9074
- await mkdir2(skillDir, { recursive: true });
9075
- await writeFile2(join3(skillDir, "SKILL.md"), skill.text);
9076
- for (const [name, target] of skill.links)
9077
- await symlink(target, join3(skillDir, name));
9078
- }
9079
- try {
9080
- await rename2(staging, path);
9081
- } catch (error) {
9082
- if (!await isMirror(path))
9083
- throw error;
9084
- }
9085
- } finally {
9086
- await rm2(staging, { recursive: true, force: true });
9141
+ function readToolRefused(boundary, tool, input, cwd) {
9142
+ const text = (key) => {
9143
+ const value = input[key];
9144
+ return typeof value === "string" && value.trim() ? value : undefined;
9145
+ };
9146
+ if (tool === "Read") {
9147
+ const path = text("file_path");
9148
+ return path !== undefined && readBoundaryRefuses(boundary, path, cwd);
9087
9149
  }
9150
+ if (tool !== "Grep" && tool !== "Glob")
9151
+ return false;
9152
+ const roots = [text("path") ?? cwd];
9153
+ const pattern = tool === "Glob" ? text("pattern") : undefined;
9154
+ const root = pattern ? globRoot(pattern) : undefined;
9155
+ if (root)
9156
+ roots.push(root);
9157
+ return roots.some((path) => readBoundaryRefuses(boundary, path, cwd, { traversal: true }));
9088
9158
  }
9089
- async function pruneOldMirrors(root, plugin, current) {
9090
- try {
9091
- const old = await Promise.all((await readdir2(root)).filter((name) => name.startsWith(`${plugin}-`) && join3(root, name) !== current).map(async (name) => ({
9092
- path: join3(root, name),
9093
- mtimeMs: (await stat2(join3(root, name)).catch(() => {
9094
- return;
9095
- }))?.mtimeMs ?? 0
9096
- })));
9097
- old.sort((a, b) => b.mtimeMs - a.mtimeMs);
9098
- for (const { path } of old.slice(KEPT_OLD_MIRRORS)) {
9099
- await rm2(path, { recursive: true, force: true });
9159
+ function shellCommandRefused(boundary, command, cwd, options) {
9160
+ const [program, ...tokens] = command.trim().split(/\s+/);
9161
+ if (options.traversal) {
9162
+ const indirectOption = program === "sort" || program === "wc" ? "--files0-from" : program === "file" ? "--files-from" : ["cksum", "md5sum", "sha1sum", "sha256sum"].includes(program ?? "") ? "--check" : undefined;
9163
+ if (indirectOption && tokens.some((token) => {
9164
+ const option = token.split("=", 1)[0];
9165
+ return option.startsWith("--") && indirectOption.startsWith(option) || program === "file" && /^-[^-]*f/.test(token) || indirectOption === "--check" && /^-[^-]*c/.test(token);
9166
+ }))
9167
+ return true;
9168
+ 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)))
9169
+ return true;
9170
+ const searches = program === "rg" || program === "ag" || program === "find" || program === "fd" || program === "du" || program === "ls" || program === "tree" || program === "grep";
9171
+ if (searches && readBoundaryRefuses(boundary, cwd, cwd, options))
9172
+ return true;
9173
+ }
9174
+ return tokens.some((token) => {
9175
+ const attached = [];
9176
+ if (token.startsWith("--")) {
9177
+ const equals = token.indexOf("=");
9178
+ if (equals >= 0)
9179
+ attached.push(token.slice(equals + 1));
9180
+ } else if (token.startsWith("-")) {
9181
+ for (let index = 1;index < token.length && /[a-zA-Z0-9]/.test(token[index]); index++) {
9182
+ attached.push(token.slice(index + 1));
9183
+ }
9100
9184
  }
9101
- } catch {}
9185
+ return [token, ...attached].some((candidate) => candidate && readBoundaryRefuses(boundary, candidate, cwd, options));
9186
+ });
9102
9187
  }
9103
9188
 
9104
- // ../../bridges/claude-bridge/src/services/plugin-config.ts
9105
- import { readdir as readdir3, access } from "node:fs/promises";
9106
- import { join as join4 } from "node:path";
9107
-
9108
- // ../protocol/src/node/claude-plugin-set.ts
9109
- import path2 from "node:path";
9110
- var CLAUDE_PLUGINS_MARKER = "/.claude/plugins/";
9111
- function isRecord(value) {
9112
- return typeof value === "object" && value !== null && !Array.isArray(value);
9113
- }
9114
- function claudePluginConfigList(value) {
9115
- if (!Array.isArray(value))
9116
- return [];
9117
- const plugins = [];
9118
- for (const item of value) {
9119
- if (isRecord(item) && typeof item.path === "string" && item.path) {
9120
- plugins.push({ type: "local", path: item.path });
9121
- }
9122
- }
9123
- return plugins;
9124
- }
9125
- function isPathWithin(parentDir, candidatePath) {
9126
- const relativePath = path2.relative(parentDir, candidatePath);
9127
- return relativePath === "" || !relativePath.startsWith("..") && !path2.isAbsolute(relativePath);
9128
- }
9129
- function remapInstalledPlugins(pluginsDir, installedPlugins, onUnsafe) {
9130
- const plugins = [];
9131
- const pluginsRoot = path2.resolve(pluginsDir);
9132
- if (!isRecord(installedPlugins.plugins))
9133
- return plugins;
9134
- for (const [installedId, entries] of Object.entries(installedPlugins.plugins)) {
9135
- if (!Array.isArray(entries))
9136
- continue;
9137
- for (const entry of entries) {
9138
- if (!isRecord(entry) || typeof entry.installPath !== "string")
9139
- continue;
9140
- const installPath = entry.installPath;
9141
- const markerIdx = installPath.indexOf(CLAUDE_PLUGINS_MARKER);
9142
- let resolvedPath;
9143
- if (markerIdx !== -1) {
9144
- const relativePath = installPath.substring(markerIdx + CLAUDE_PLUGINS_MARKER.length);
9145
- const remappedPath = path2.resolve(pluginsDir, relativePath);
9146
- if (!isPathWithin(pluginsRoot, remappedPath)) {
9147
- onUnsafe?.(installPath);
9148
- continue;
9149
- }
9150
- resolvedPath = remappedPath;
9151
- } else {
9152
- resolvedPath = installPath;
9153
- }
9154
- plugins.push({ type: "local", path: resolvedPath, installedId });
9155
- }
9156
- }
9157
- return plugins;
9158
- }
9159
- function resolveClaudePluginPath(pluginPath, cwd, home) {
9160
- if (pluginPath.startsWith("~"))
9161
- return path2.join(home, pluginPath.slice(1));
9162
- if (pluginPath.startsWith("/"))
9163
- return pluginPath;
9164
- return path2.join(cwd, pluginPath);
9165
- }
9166
- function mergeClaudePluginLayers(layers, options) {
9167
- const ordered = [
9168
- claudePluginConfigList(layers.global),
9169
- layers.cliInstalled,
9170
- ...options.includeProjectSources ? [claudePluginConfigList(layers.projectGlobal), claudePluginConfigList(layers.projectLocal)] : []
9171
- ];
9172
- const seen = new Set;
9173
- const paths = [];
9174
- for (const layer of ordered) {
9175
- for (const plugin of layer) {
9176
- const resolved = resolveClaudePluginPath(plugin.path, options.cwd, options.home);
9177
- if (seen.has(resolved))
9178
- continue;
9179
- seen.add(resolved);
9180
- paths.push(resolved);
9181
- }
9182
- }
9183
- return paths;
9184
- }
9185
- var INVALID_PLUGIN_NAME = new RegExp("[@:\\s/\\\\\\u0000-\\u001f\\u007f\\u200b-\\u200f\\u2028-\\u202e\\u2060-\\u2064\\ufeff]");
9186
- var CLAUDE_PLUGIN_SETTING_SOURCES = ["local", "project", "user"];
9187
- function claudeInstalledPluginIdEnablement(id, settings, loadedSources) {
9188
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9189
- for (const source of ["local", "project", "user"]) {
9190
- if (!loadedSources.includes(source))
9191
- continue;
9192
- const document = settings[source];
9193
- const enabledPlugins = isRecord(document) ? document.enabledPlugins : undefined;
9194
- if (!isRecord(enabledPlugins) || !Object.hasOwn(enabledPlugins, id))
9195
- continue;
9196
- return { enabled: enabledPlugins[id] === true, decidedBy: { source, key: id } };
9197
- }
9198
- return { enabled: false };
9199
- }
9200
- function enabledInstalledPlugins(plugins, settings, loadedSources) {
9201
- return plugins.filter((plugin) => plugin.installedId === undefined || claudeInstalledPluginIdEnablement(plugin.installedId, settings, loadedSources).enabled);
9202
- }
9203
- function claudePluginSettingSources(settingSources) {
9204
- return CLAUDE_PLUGIN_SETTING_SOURCES.filter((source) => settingSources.includes(source));
9205
- }
9206
-
9207
- // ../../bridges/claude-bridge/src/services/json-file-cache.ts
9208
- import { createHash as createHash5 } from "node:crypto";
9209
- import { readFile as readFile4, stat as stat3 } from "node:fs/promises";
9210
- var SEPARATOR = "\x00";
9211
- var slices = new Map;
9212
- var readCohorts = new Map;
9213
- var parseCounts = new Map;
9214
- var beforeStatForTesting = null;
9215
- function fingerprintOf(stats) {
9216
- return `${stats.dev}:${stats.ino}:${stats.size}:${stats.mtimeMs}`;
9217
- }
9218
- function forgetFile(filePath) {
9219
- const prefix = `${filePath}${SEPARATOR}`;
9220
- for (const key of slices.keys()) {
9221
- if (key.startsWith(prefix))
9222
- slices.delete(key);
9223
- }
9224
- }
9225
- function joinReadCohort(filePath) {
9226
- const existing = readCohorts.get(filePath);
9227
- if (existing) {
9228
- existing.readers += 1;
9229
- return existing;
9230
- }
9231
- const cohort = { readers: 1, parses: new Map };
9232
- readCohorts.set(filePath, cohort);
9233
- return cohort;
9234
- }
9235
- function leaveReadCohort(filePath, cohort) {
9236
- cohort.readers -= 1;
9237
- if (cohort.readers === 0 && readCohorts.get(filePath) === cohort) {
9238
- readCohorts.delete(filePath);
9239
- }
9240
- }
9241
- function parseOnce(filePath, fingerprint, cohort) {
9242
- const existing = cohort.parses.get(fingerprint);
9243
- if (existing)
9244
- return existing;
9245
- const parse = (async () => {
9246
- parseCounts.set(filePath, (parseCounts.get(filePath) ?? 0) + 1);
9247
- let bytes;
9248
- try {
9249
- bytes = await readFile4(filePath);
9250
- } catch {
9251
- return { parsed: null, digest: null };
9252
- }
9253
- const digest = createHash5("sha256").update(bytes).digest("base64url");
9254
- try {
9255
- return { parsed: JSON.parse(bytes.toString("utf-8")), digest };
9256
- } catch {
9257
- return { parsed: null, digest };
9258
- }
9259
- })();
9260
- cohort.parses.set(fingerprint, parse);
9261
- return parse;
9262
- }
9263
- async function readJsonSliceCached(filePath, sliceKey, select) {
9264
- return (await readJsonSliceCachedWithDigest(filePath, sliceKey, select)).value;
9265
- }
9266
- async function readJsonSliceCachedWithDigest(filePath, sliceKey, select) {
9267
- const cohort = joinReadCohort(filePath);
9268
- try {
9269
- await beforeStatForTesting?.(filePath);
9270
- let fingerprint;
9271
- try {
9272
- fingerprint = fingerprintOf(await stat3(filePath));
9273
- } catch {
9274
- forgetFile(filePath);
9275
- return { value: null, digest: null };
9276
- }
9277
- const key = `${filePath}${SEPARATOR}${sliceKey}`;
9278
- const cached = slices.get(key);
9279
- if (cached && cached.fingerprint === fingerprint) {
9280
- return { value: cached.value, digest: cached.digest };
9281
- }
9282
- const { parsed, digest } = await parseOnce(filePath, fingerprint, cohort);
9283
- let value = null;
9284
- if (parsed !== null && parsed !== undefined) {
9285
- try {
9286
- value = select(parsed) ?? null;
9287
- } catch {
9288
- value = null;
9289
- }
9290
- }
9291
- slices.set(key, { fingerprint, value, digest });
9292
- return { value, digest };
9293
- } finally {
9294
- leaveReadCohort(filePath, cohort);
9295
- }
9296
- }
9297
-
9298
- // ../../bridges/claude-bridge/src/services/plugin-config.ts
9299
- var log4 = createLogger("bridge.claude");
9300
- async function pathExists(path) {
9301
- try {
9302
- await access(path);
9303
- return true;
9304
- } catch {
9305
- return false;
9306
- }
9307
- }
9308
- async function scanCliPluginsDirectory(pluginsDir) {
9309
- if (!await pathExists(pluginsDir)) {
9310
- return [];
9311
- }
9312
- try {
9313
- const entries = await readdir3(pluginsDir, { withFileTypes: true });
9314
- const plugins = [];
9315
- for (const entry of entries) {
9316
- if (!entry.isDirectory()) {
9317
- continue;
9318
- }
9319
- const pluginPath = join4(pluginsDir, entry.name);
9320
- const manifestPath = join4(pluginPath, ".claude-plugin", "plugin.json");
9321
- if (await pathExists(manifestPath)) {
9322
- plugins.push({
9323
- type: "local",
9324
- path: pluginPath
9325
- });
9326
- }
9327
- }
9328
- return plugins;
9329
- } catch {
9330
- return [];
9331
- }
9332
- }
9333
- async function loadGlobalPlugins() {
9334
- const plugins = await readJsonSliceCached(claudeJsonPath(), "plugins", (config) => claudePluginConfigList(config?.plugins));
9335
- return plugins ?? [];
9336
- }
9337
- async function loadProjectPlugins(cwd) {
9338
- const plugins = await readJsonSliceCached(join4(cwd, ".claude", "plugins.json"), "plugins", (config) => claudePluginConfigList(config?.plugins));
9339
- return plugins ?? [];
9340
- }
9341
- async function loadCliInstalledPlugins() {
9342
- const pluginsDir = claudePluginsDir();
9343
- const installedPluginsPath = join4(pluginsDir, "installed_plugins.json");
9344
- const plugins = await readJsonSliceCached(installedPluginsPath, "plugins", (config) => config?.plugins);
9345
- if (!plugins) {
9346
- return scanCliPluginsDirectory(pluginsDir);
9347
- }
9348
- return remapInstalledPlugins2(pluginsDir, { plugins });
9349
- }
9350
- function pluginSettingsPath(source, cwd) {
9351
- switch (source) {
9352
- case "user":
9353
- return claudeUserSettingsPath();
9354
- case "project":
9355
- return join4(cwd, ".claude", "settings.json");
9356
- case "local":
9357
- return join4(cwd, ".claude", "settings.local.json");
9358
- }
9359
- }
9360
- async function loadPluginSettings(cwd, sources) {
9361
- const entries = await Promise.all(sources.map(async (source) => {
9362
- const enabledPlugins = await readJsonSliceCached(pluginSettingsPath(source, cwd), "enabledPlugins", (config) => config?.enabledPlugins ?? null);
9363
- return [source, enabledPlugins === null ? undefined : { enabledPlugins }];
9364
- }));
9365
- return Object.fromEntries(entries);
9366
- }
9367
- function remapInstalledPlugins2(pluginsDir, installedPlugins) {
9368
- return remapInstalledPlugins(pluginsDir, installedPlugins, (installPath) => log4.warn("plugin.unsafe-path", { path: installPath }));
9369
- }
9370
- async function loadProjectOverridesFromGlobal(cwd) {
9371
- const plugins = await readJsonSliceCached(claudeJsonPath(), `projects:${cwd}:plugins`, (config) => claudePluginConfigList(config?.projects?.[cwd]?.plugins));
9372
- return plugins ?? [];
9373
- }
9374
- async function readPluginManifest(pluginPath) {
9375
- const manifestPath = join4(pluginPath, ".claude-plugin", "plugin.json");
9376
- const manifest = await readJsonSliceCached(manifestPath, "manifest", (config) => config ? { name: config.name, description: config.description } : null);
9377
- if (!manifest) {
9378
- return null;
9379
- }
9380
- const name = manifest.name || pluginPath.split("/").pop() || "unknown";
9381
- return {
9382
- name,
9383
- description: manifest.description
9384
- };
9385
- }
9386
- function resolvePath(pluginPath, cwd) {
9387
- return resolveClaudePluginPath(pluginPath, cwd, claudeHome());
9388
- }
9389
- function defaultSettingSources(includeProjectSources) {
9390
- return includeProjectSources ? ["user", "project"] : ["user"];
9391
- }
9392
- async function getMergedPlugins(cwd, includeProjectSources = true, settingSources = defaultSettingSources(includeProjectSources)) {
9393
- const sources = claudePluginSettingSources(settingSources);
9394
- const [global2, cliInstalled, projectGlobal, projectLocal, settings] = await Promise.all([
9395
- loadGlobalPlugins(),
9396
- loadCliInstalledPlugins(),
9397
- includeProjectSources ? loadProjectOverridesFromGlobal(cwd) : [],
9398
- includeProjectSources ? loadProjectPlugins(cwd) : [],
9399
- loadPluginSettings(cwd, sources)
9400
- ]);
9401
- return mergeClaudePluginLayers({
9402
- global: global2,
9403
- cliInstalled: enabledInstalledPlugins(cliInstalled, settings, sources),
9404
- projectGlobal,
9405
- projectLocal
9406
- }, { cwd, home: claudeHome(), includeProjectSources }).map((path) => ({ type: "local", path }));
9407
- }
9408
- async function getPluginsForSdk(cwd, includeProjectSources = true, settingSources = defaultSettingSources(includeProjectSources)) {
9409
- const configs = await getMergedPlugins(cwd, includeProjectSources, settingSources);
9410
- const validPlugins = [];
9411
- for (const config of configs) {
9412
- if (await pathExists(config.path)) {
9413
- validPlugins.push({
9414
- type: "local",
9415
- path: config.path
9416
- });
9417
- } else {
9418
- const pluginName = config.path.split("/").pop() || "unknown";
9419
- log4.warn("plugin.path-missing", { pluginName, path: config.path });
9420
- }
9421
- }
9422
- return validPlugins;
9423
- }
9424
- async function getPluginInfo(cwd) {
9425
- const [global2, cliInstalled, projectGlobal, projectLocal] = await Promise.all([
9426
- loadGlobalPlugins(),
9427
- loadCliInstalledPlugins(),
9428
- loadProjectOverridesFromGlobal(cwd),
9429
- loadProjectPlugins(cwd)
9430
- ]);
9431
- const globalPaths = new Set(global2.map((p) => resolvePath(p.path, cwd)));
9432
- const cliPaths = new Set(cliInstalled.map((p) => resolvePath(p.path, cwd)));
9433
- const projectGlobalPaths = new Set(projectGlobal.map((p) => resolvePath(p.path, cwd)));
9434
- const projectLocalPaths = new Set(projectLocal.map((p) => resolvePath(p.path, cwd)));
9435
- const merged = await getMergedPlugins(cwd);
9436
- const result = [];
9437
- for (const config of merged) {
9438
- const manifest = await readPluginManifest(config.path);
9439
- const exists = await pathExists(config.path);
9440
- let source = "global";
9441
- if (projectLocalPaths.has(config.path) || projectGlobalPaths.has(config.path)) {
9442
- source = "project";
9443
- } else if (cliPaths.has(config.path)) {
9444
- source = "cli";
9445
- } else if (globalPaths.has(config.path)) {
9446
- source = "global";
9189
+ // ../../bridges/claude-bridge/src/services/read-only-policy.ts
9190
+ var CAPABILITY_TOOLS = new Map([
9191
+ ["file.write", ["Write", "NotebookEdit", "EnterWorktree", "ExitWorktree"]],
9192
+ ["file.patch", ["Edit", "MultiEdit", "ApplyPatch"]],
9193
+ ["shell", ["Bash", "BashOutput", "KillShell", "PowerShell"]],
9194
+ ["shell.mutate", ["PowerShell"]],
9195
+ ["network", ["WebFetch", "WebSearch", "RemoteTrigger"]],
9196
+ ["web.search", ["WebSearch"]],
9197
+ ["subagents", ["Task", "Agent"]],
9198
+ ["git.commit", ["Bash(git commit)", "Bash(git commit *)"]],
9199
+ ["git.push", ["Bash(git push)", "Bash(git push *)"]],
9200
+ ["github.write", ["Bash(gh)", "Bash(gh *)"]]
9201
+ ]);
9202
+ var READ_ONLY_TOOLS = Object.freeze([
9203
+ "Read",
9204
+ "Glob",
9205
+ "Grep",
9206
+ "Bash",
9207
+ "Task",
9208
+ "Agent",
9209
+ "TodoWrite",
9210
+ "AskUserQuestion"
9211
+ ]);
9212
+ var WAITING_TOOLS = new Set([
9213
+ "Monitor",
9214
+ "ScheduleWakeup",
9215
+ "CronCreate",
9216
+ "CronList",
9217
+ "CronDelete",
9218
+ "SendMessage"
9219
+ ]);
9220
+ var READ_ONLY_COMMANDS = Object.freeze(new Set([
9221
+ "awk",
9222
+ "basename",
9223
+ "cat",
9224
+ "cksum",
9225
+ "column",
9226
+ "comm",
9227
+ "cut",
9228
+ "date",
9229
+ "diff",
9230
+ "dirname",
9231
+ "du",
9232
+ "echo",
9233
+ "file",
9234
+ "find",
9235
+ "fd",
9236
+ "grep",
9237
+ "head",
9238
+ "hostname",
9239
+ "jq",
9240
+ "ls",
9241
+ "md5sum",
9242
+ "nl",
9243
+ "od",
9244
+ "printf",
9245
+ "pwd",
9246
+ "readlink",
9247
+ "realpath",
9248
+ "rg",
9249
+ "sha1sum",
9250
+ "sha256sum",
9251
+ "sort",
9252
+ "stat",
9253
+ "tail",
9254
+ "tr",
9255
+ "true",
9256
+ "uniq",
9257
+ "wc",
9258
+ "which",
9259
+ "whoami",
9260
+ "xxd",
9261
+ "yq"
9262
+ ]));
9263
+ var MUTATING_ARGUMENTS = new Map([
9264
+ ["date", new Set(["-s", "--set"])],
9265
+ ["fd", new Set(["-x", "-X", "--exec", "--exec-batch"])],
9266
+ ["file", new Set(["-C", "--compile"])],
9267
+ [
9268
+ "find",
9269
+ new Set([
9270
+ "-delete",
9271
+ "-exec",
9272
+ "-execdir",
9273
+ "-fls",
9274
+ "-fprint",
9275
+ "-fprint0",
9276
+ "-fprintf",
9277
+ "-ok",
9278
+ "-okdir"
9279
+ ])
9280
+ ],
9281
+ ["hostname", new Set(["-F", "--file", "-b", "--boot"])],
9282
+ ["rg", new Set(["--hostname-bin", "--pre"])],
9283
+ ["sort", new Set(["-o", "--output", "-T", "--temporary-directory", "--compress-program"])],
9284
+ ["yq", new Set(["-i", "--in-place", "--inplace", "-s", "--split-exp"])]
9285
+ ]);
9286
+ var POSITIONAL_LIMITS = new Map([
9287
+ ["hostname", { max: 0, valueOptions: new Set }],
9288
+ ["uniq", { max: 1, valueOptions: new Set(["-f", "-s", "-w"]) }],
9289
+ [
9290
+ "xxd",
9291
+ {
9292
+ max: 1,
9293
+ stopAtFirstOperand: true,
9294
+ valueOptions: new Set([
9295
+ "-c",
9296
+ "-cols",
9297
+ "-g",
9298
+ "-groupsize",
9299
+ "-l",
9300
+ "-len",
9301
+ "-n",
9302
+ "-name",
9303
+ "-o",
9304
+ "-offset",
9305
+ "-s",
9306
+ "-seek"
9307
+ ])
9447
9308
  }
9448
- result.push({
9449
- name: manifest?.name || config.path.split("/").pop() || "unknown",
9450
- path: config.path,
9451
- description: manifest?.description,
9452
- source,
9453
- enabled: exists
9454
- });
9455
- }
9456
- return result;
9457
- }
9458
-
9459
- // ../protocol/src/coordinator-web-research.ts
9460
- var COORDINATOR_WEB_RESEARCH_MODES = ["off", "search", "search-and-mcp"];
9461
- var DEFAULT_COORDINATOR_RESEARCH_MCP_SERVERS = Object.freeze([{ name: "context7", url: "https://mcp.context7.com/mcp" }]);
9462
- var MAX_COORDINATOR_RESEARCH_MCP_SERVERS = 8;
9463
- var COORDINATOR_WEB_RESEARCH_ENV = "ORKESTRATOR_COORDINATOR_WEB_RESEARCH";
9464
- var COORDINATOR_RESEARCH_MCP_ENV = "ORKESTRATOR_COORDINATOR_RESEARCH_MCP";
9465
- var RESERVED_SERVER_NAME = /^orkestrator/;
9466
- var SERVER_NAME = /^[a-z0-9][a-z0-9-]{0,31}$/;
9467
- function isCoordinatorWebResearch(value) {
9468
- return typeof value === "string" && COORDINATOR_WEB_RESEARCH_MODES.includes(value);
9469
- }
9470
- function coordinatorResearchMcpServerProblem(server) {
9471
- if (!SERVER_NAME.test(server.name)) {
9472
- return "Use 1 to 32 lowercase letters, digits or hyphens for the name.";
9473
- }
9474
- if (RESERVED_SERVER_NAME.test(server.name))
9475
- return "Names starting with orkestrator are reserved.";
9476
- let url;
9477
- try {
9478
- url = new URL(server.url);
9479
- } catch {
9480
- return "The URL is not valid.";
9481
- }
9482
- if (url.protocol !== "https:")
9483
- return "Only https:// research servers are allowed.";
9484
- if (url.username || url.password)
9485
- return "Credentials in the URL are not allowed.";
9486
- return;
9487
- }
9488
- function normalizeCoordinatorResearchMcpServers(value) {
9489
- if (value === undefined)
9490
- return DEFAULT_COORDINATOR_RESEARCH_MCP_SERVERS.map((s) => ({ ...s }));
9491
- if (!Array.isArray(value))
9492
- return [];
9493
- const servers = [];
9494
- const names = new Set;
9495
- for (const entry of value) {
9496
- if (servers.length >= MAX_COORDINATOR_RESEARCH_MCP_SERVERS)
9497
- break;
9498
- if (!entry || typeof entry !== "object")
9499
- continue;
9500
- const { name, url } = entry;
9501
- if (typeof name !== "string" || typeof url !== "string")
9502
- continue;
9503
- const server = { name: name.trim(), url: url.trim() };
9504
- if (coordinatorResearchMcpServerProblem(server) || names.has(server.name))
9505
- continue;
9506
- names.add(server.name);
9507
- servers.push(server);
9508
- }
9509
- return servers;
9309
+ ]
9310
+ ]);
9311
+ var OPTION_ALLOWLISTS = new Map([
9312
+ ["awk", new Set(["-F", "-v", "--field-separator", "--assign"])]
9313
+ ]);
9314
+ var GIT_GLOBAL_OPTIONS = new Set([
9315
+ "-P",
9316
+ "--literal-pathspecs",
9317
+ "--no-optional-locks",
9318
+ "--no-pager"
9319
+ ]);
9320
+ var GIT_MUTATING_ARGUMENTS = new Set([
9321
+ "--config-env",
9322
+ "--exec-path",
9323
+ "--ext-diff",
9324
+ "--filters",
9325
+ "--output",
9326
+ "--textconv"
9327
+ ]);
9328
+ var GIT_SUBCOMMAND_MUTATING_ARGUMENTS = new Map([
9329
+ ["grep", new Set(["-O", "--open-files-in-pager"])]
9330
+ ]);
9331
+ var READ_ONLY_GIT_SUBCOMMANDS = Object.freeze(new Set([
9332
+ "blame",
9333
+ "cat-file",
9334
+ "describe",
9335
+ "diff",
9336
+ "grep",
9337
+ "log",
9338
+ "ls-files",
9339
+ "ls-tree",
9340
+ "merge-base",
9341
+ "name-rev",
9342
+ "rev-list",
9343
+ "rev-parse",
9344
+ "shortlog",
9345
+ "show",
9346
+ "show-ref",
9347
+ "status",
9348
+ "whatchanged"
9349
+ ]));
9350
+ var GIT_REF_WRITE_FLAGS = Object.freeze(new Set([
9351
+ "-C",
9352
+ "-D",
9353
+ "-M",
9354
+ "-c",
9355
+ "-d",
9356
+ "-f",
9357
+ "-m",
9358
+ "-u",
9359
+ "--copy",
9360
+ "--delete",
9361
+ "--edit-description",
9362
+ "--force",
9363
+ "--move",
9364
+ "--set-upstream-to",
9365
+ "--unset-upstream"
9366
+ ]));
9367
+ var GIT_REF_LIST_FLAGS = Object.freeze(new Set([
9368
+ "-l",
9369
+ "--list",
9370
+ "--contains",
9371
+ "--no-contains",
9372
+ "--merged",
9373
+ "--no-merged",
9374
+ "--points-at",
9375
+ "--show-current"
9376
+ ]));
9377
+ var GIT_CONFIG_READ_FLAGS = Object.freeze(new Set(["-l", "--get", "--get-all", "--get-regexp", "--get-urlmatch", "--list"]));
9378
+ var GIT_CONFIG_WRITE_FLAGS = Object.freeze(new Set([
9379
+ "-e",
9380
+ "--add",
9381
+ "--edit",
9382
+ "--remove-section",
9383
+ "--rename-section",
9384
+ "--replace-all",
9385
+ "--set",
9386
+ "--set-all",
9387
+ "--unset",
9388
+ "--unset-all"
9389
+ ]));
9390
+ var GIT_CONFIG_READ_SUBCOMMANDS = Object.freeze(new Set(["get", "list"]));
9391
+ var GIT_CONFIG_WRITE_SUBCOMMANDS = Object.freeze(new Set(["edit", "remove-section", "rename-section", "set", "unset"]));
9392
+ var GIT_REMOTE_READ_SUBCOMMANDS = Object.freeze(new Set(["get-url"]));
9393
+ function hasFlag(args, flags) {
9394
+ const letters = [...flags].flatMap((flag) => /^-[A-Za-z0-9]$/.test(flag) ? [flag[1]] : []);
9395
+ 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)));
9510
9396
  }
9511
- function coordinatorWebResearchFromEnv(env) {
9512
- const value = env[COORDINATOR_WEB_RESEARCH_ENV];
9513
- return isCoordinatorWebResearch(value) ? value : "off";
9397
+ function listsRefsOnly(args) {
9398
+ if (hasFlag(args, GIT_REF_WRITE_FLAGS))
9399
+ return false;
9400
+ const positionals = args.filter((arg) => !arg.startsWith("-"));
9401
+ return positionals.length === 0 || hasFlag(args, GIT_REF_LIST_FLAGS);
9514
9402
  }
9515
- function coordinatorResearchMcpServersFromEnv(env) {
9516
- if (coordinatorWebResearchFromEnv(env) !== "search-and-mcp")
9517
- return [];
9518
- const raw = env[COORDINATOR_RESEARCH_MCP_ENV];
9519
- if (!raw)
9520
- return [];
9521
- try {
9522
- return normalizeCoordinatorResearchMcpServers(JSON.parse(raw));
9523
- } catch {
9524
- return [];
9525
- }
9403
+ function readsConfigOnly(args) {
9404
+ if (hasFlag(args, GIT_CONFIG_WRITE_FLAGS))
9405
+ return false;
9406
+ const positionals = args.filter((arg) => !arg.startsWith("-"));
9407
+ const first = positionals[0];
9408
+ if (first && GIT_CONFIG_WRITE_SUBCOMMANDS.has(first))
9409
+ return false;
9410
+ if (hasFlag(args, GIT_CONFIG_READ_FLAGS))
9411
+ return true;
9412
+ if (first && GIT_CONFIG_READ_SUBCOMMANDS.has(first))
9413
+ return true;
9414
+ return positionals.length <= 1;
9526
9415
  }
9527
- var COORDINATOR_DENIED = Object.freeze([
9528
- "file.write",
9529
- "file.patch",
9530
- "shell.mutate",
9531
- "network"
9416
+ var CONDITIONAL_GIT_SUBCOMMANDS = new Map([
9417
+ ["branch", listsRefsOnly],
9418
+ ["config", readsConfigOnly],
9419
+ [
9420
+ "remote",
9421
+ (args) => {
9422
+ const first = args.find((arg) => !arg.startsWith("-"));
9423
+ return first === undefined || GIT_REMOTE_READ_SUBCOMMANDS.has(first);
9424
+ }
9425
+ ],
9426
+ ["tag", listsRefsOnly]
9532
9427
  ]);
9533
- function coordinatorCapabilityPolicy(mode) {
9534
- return {
9535
- deny: [...COORDINATOR_DENIED],
9536
- ...mode === "off" ? {} : { allow: ["web.search"] }
9537
- };
9538
- }
9539
-
9540
- // ../../bridges/claude-bridge/src/services/mcp-tool-prefix.ts
9541
- function claudeMcpToolPrefix(name) {
9542
- let normalized = name.replace(/[^a-zA-Z0-9_-]/g, "_");
9543
- if (name.startsWith("claude.ai ")) {
9544
- normalized = normalized.replace(/_+/g, "_").replace(/^_|_$/g, "");
9545
- }
9546
- return `mcp__${normalized}__`;
9428
+ var NETWORK_COMMANDS = new Set(["curl", "gh", "wget"]);
9429
+ var NETWORK_GIT_SUBCOMMANDS = new Set(["fetch", "ls-remote", "pull"]);
9430
+ var COMPOSITION_PATTERN = /[;&|><`$(){}\n\r'"\\*?[\]]|\bsudo\b|\bexec\b/;
9431
+ function isCoordinatorReadOnlyPolicy(policy) {
9432
+ return policy?.id === "coordinator-read-only";
9547
9433
  }
9548
-
9549
- // ../../bridges/claude-bridge/src/services/read-only-path-boundary.ts
9550
- import { join as join6 } from "node:path";
9551
-
9552
- // ../protocol/src/node/coordinator-read-boundary.ts
9553
- import { realpathSync } from "node:fs";
9554
- import { homedir as homedir2 } from "node:os";
9555
- import { dirname as dirname2, isAbsolute as isAbsolute2, join as join5, parse, resolve as resolve2, sep } from "node:path";
9556
- function canonicalPath(path) {
9557
- let existing = path;
9558
- const tail = [];
9559
- for (;; ) {
9560
- try {
9561
- return join5(realpathSync.native(existing), ...tail.reverse());
9562
- } catch {
9563
- const parent = dirname2(existing);
9564
- if (parent === existing)
9565
- return path;
9566
- tail.push(existing.slice(parent.length).replace(/^[/\\]+/, ""));
9567
- existing = parent;
9434
+ function claudeDeniedTools(policy) {
9435
+ const tools = new Set;
9436
+ for (const capability of nativeAgentDeniedCapabilities(policy)) {
9437
+ const server = nativeAgentMcpServer(capability);
9438
+ if (server) {
9439
+ tools.add(`${claudeMcpToolPrefix(server)}*`);
9440
+ continue;
9568
9441
  }
9442
+ for (const tool of CAPABILITY_TOOLS.get(capability) ?? [])
9443
+ tools.add(tool);
9569
9444
  }
9445
+ if (!nativeAgentPolicyDeniesWebSearch(policy))
9446
+ tools.delete("WebSearch");
9447
+ return [...tools];
9570
9448
  }
9571
- function namedAndCanonicalPaths(paths) {
9572
- const named = paths.flatMap((path) => path?.trim() && isAbsolute2(path) ? [path] : []);
9573
- return [...new Set(named.flatMap((path) => [resolve2(path), canonicalPath(path)]))];
9449
+ function claudeDisallowedTools(policy) {
9450
+ const denied = claudeDeniedTools(policy);
9451
+ if (denied.length === 0)
9452
+ return policy?.toolPolicy?.deny;
9453
+ return [...new Set([...policy?.toolPolicy?.deny ?? [], ...denied])];
9574
9454
  }
9575
- function isWithin(root, path) {
9576
- if (path === root)
9577
- return true;
9578
- const prefix = root === parse(root).root ? root : `${root}${sep}`;
9579
- return path.startsWith(prefix);
9455
+ function claudeReadOnlyAllowedTools(options) {
9456
+ return [
9457
+ ...READ_ONLY_TOOLS,
9458
+ ...(options.skillNames ?? []).map((name) => `Skill(${name})`),
9459
+ ...options.policy && !nativeAgentPolicyDeniesWebSearch(options.policy) ? ["WebSearch"] : [],
9460
+ ...(options.agentMcpServerNames ?? []).map((name) => `${claudeMcpToolPrefix(name)}*`),
9461
+ ...(options.researchMcpServerNames ?? []).map((name) => `${claudeMcpToolPrefix(name)}*`),
9462
+ ...(options.grantedMcpServerNames ?? []).map((name) => `${claudeMcpToolPrefix(name)}*`)
9463
+ ];
9580
9464
  }
9581
- function protectedDataDirBoundary(dataDir, allowances) {
9582
- const trimmed = dataDir?.trim();
9583
- if (!trimmed || !isAbsolute2(trimmed))
9584
- return null;
9585
- const deny = namedAndCanonicalPaths([trimmed]);
9465
+ function claudeReadOnlySandbox(policy, options = {}) {
9586
9466
  return {
9587
- deny,
9588
- allow: namedAndCanonicalPaths(allowances).filter((path) => !deny.includes(path) && deny.some((root) => isWithin(root, path)))
9467
+ enabled: options.commandSandbox !== "unavailable",
9468
+ failIfUnavailable: options.commandSandbox !== "unavailable",
9469
+ autoAllowBashIfSandboxed: true,
9470
+ allowUnsandboxedCommands: false,
9471
+ excludedCommands: [],
9472
+ filesystem: {
9473
+ denyWrite: [...new Set(options.workspaces ?? [])],
9474
+ ...options.readBoundary ? { denyRead: options.readBoundary.deny, allowRead: options.readBoundary.allow } : {}
9475
+ },
9476
+ network: {
9477
+ allowLocalBinding: policy.networkAccess === "full",
9478
+ strictAllowlist: true,
9479
+ allowedDomains: []
9480
+ }
9589
9481
  };
9590
9482
  }
9591
- function deniedForm(boundary, path) {
9592
- return boundary.deny.some((root) => isWithin(root, path)) && !boundary.allow.some((root) => isWithin(root, path));
9593
- }
9594
- function expandedHome(path) {
9595
- if (path === "~")
9596
- return homedir2();
9597
- return path.startsWith("~/") ? `${homedir2()}${sep}${path.slice(2)}` : path;
9598
- }
9599
- function readBoundaryRefuses(boundary, path, cwd, options = {}) {
9600
- const expanded = expandedHome(path);
9601
- const raw = isAbsolute2(expanded) ? expanded : `${cwd}${sep}${expanded}`;
9602
- const lexical = resolve2(raw);
9603
- const real = canonicalPath(raw);
9604
- if (deniedForm(boundary, lexical) || deniedForm(boundary, real))
9605
- return true;
9606
- return options.traversal === true && boundary.deny.some((root) => isWithin(lexical, root) || isWithin(real, root));
9483
+ function readOnlyRefusalRole(sessionPolicy, readOnlyTurn, env = process.env) {
9484
+ if (processExecutionPolicyIsCoordinator(env))
9485
+ return "coordinator";
9486
+ return !readOnlyTurn && isCoordinatorReadOnlyPolicy(sessionPolicy) ? "coordinator" : "read-only";
9607
9487
  }
9608
-
9609
- // ../../bridges/claude-bridge/src/services/read-only-path-boundary.ts
9610
- function claudeReadOnlyWorkspacePaths(cwd) {
9611
- return [...new Set([cwd, canonicalPath(cwd)])];
9488
+ var REFUSALS = {
9489
+ coordinator: {
9490
+ 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.",
9491
+ 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.`,
9492
+ gitSandbox: "Coordinator Git commands require the command sandbox because Git configuration can run helpers. Use reading tools or delegate to a worker environment.",
9493
+ unavailable: (described) => `Coordinator is read-only, so \`${described}\` is not available here. Delegate it to a worker environment.`,
9494
+ 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.`,
9495
+ 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.`,
9496
+ 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.`,
9497
+ program: (program) => `Coordinator is read-only, so \`${program}\` is not available here. Delegate commands that change the checkout to a worker environment.`,
9498
+ network: (described) => `Coordinator commands have no network access, so \`${described}\` is not available here. Delegate it to a worker environment.`,
9499
+ tool: (tool) => `Coordinator is read-only, so ${tool} is not available. Delegate file changes to a worker environment.`,
9500
+ 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.`,
9501
+ mcp: (tool) => `Coordinator sessions may only use Orkestrator's own tools, so ${tool} is not available.`,
9502
+ unsandboxed: "Coordinator commands may not run outside the sandbox.",
9503
+ 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."
9504
+ },
9505
+ "read-only": {
9506
+ 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.",
9507
+ byPath: (program) => `This session runs reading programs by name only, so \`${program}\` is not available here. Use the program name.`,
9508
+ gitSandbox: "Git commands in this session require the command sandbox because Git configuration can run helpers. Use reading tools instead.",
9509
+ unavailable: (described) => `This session is read-only, so \`${described}\` is not available here.`,
9510
+ gitArgument: (described) => `This session is read-only, so \`${described}\` cannot be used with an argument that writes a file or runs another program.`,
9511
+ gitGlobalOption: (option) => `Git commands in this session run against this checkout only, so the Git option \`${option}\` is not available before the subcommand.`,
9512
+ argument: (program) => `This session is read-only, so \`${program}\` cannot be used with an argument that writes or runs another program.`,
9513
+ program: (program) => `This session is read-only, so \`${program}\` is not available here. It may read the checkout but not change it.`,
9514
+ network: (described) => `Commands in this session have no network access, so \`${described}\` is not available here.`,
9515
+ tool: (tool) => `This session is read-only, so ${tool} is not available.`,
9516
+ waiting: (tool) => `This session's turns do not wait, so ${tool} is not available. End your turn instead.`,
9517
+ mcp: (tool) => `This session may only use Orkestrator's own tools and the MCP servers granted to it, so ${tool} is not available.`,
9518
+ unsandboxed: "Commands in this session may not run outside the sandbox.",
9519
+ 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."
9520
+ }
9521
+ };
9522
+ function isReadOnlyShellCommand(command, options = {}) {
9523
+ const refusals = REFUSALS[options.role ?? "coordinator"];
9524
+ const trimmed = command.trim();
9525
+ if (!trimmed)
9526
+ return { allowed: true };
9527
+ if (COMPOSITION_PATTERN.test(trimmed) || /(?:^|\s)~/.test(trimmed)) {
9528
+ return { allowed: false, reason: refusals.composition };
9529
+ }
9530
+ const tokens = trimmed.split(/\s+/).filter(Boolean);
9531
+ const first = tokens[0] ?? "";
9532
+ if (!first)
9533
+ return { allowed: true };
9534
+ if (first.includes("/") || first.includes("\\")) {
9535
+ return { allowed: false, reason: refusals.byPath(first) };
9536
+ }
9537
+ const program = first;
9538
+ if (NETWORK_COMMANDS.has(program))
9539
+ return { allowed: false, reason: refusals.network(program) };
9540
+ if (program === "git") {
9541
+ if (options.commandSandbox !== "required") {
9542
+ return { allowed: false, reason: refusals.gitSandbox };
9543
+ }
9544
+ const subcommandIndex = tokens.findIndex((token, index) => index > 0 && !token.startsWith("-"));
9545
+ const subcommand = subcommandIndex > 0 ? tokens[subcommandIndex] : undefined;
9546
+ const args = subcommandIndex > 0 ? tokens.slice(subcommandIndex + 1) : [];
9547
+ const globalOptions = tokens.slice(1, subcommandIndex > 0 ? subcommandIndex : undefined);
9548
+ const unlisted = globalOptions.find((option) => !GIT_GLOBAL_OPTIONS.has(option));
9549
+ if (unlisted)
9550
+ return { allowed: false, reason: refusals.gitGlobalOption(unlisted) };
9551
+ if (subcommand && (NETWORK_GIT_SUBCOMMANDS.has(subcommand) || subcommand === "remote" && args.some((arg) => arg === "show"))) {
9552
+ return { allowed: false, reason: refusals.network(`git ${subcommand}`) };
9553
+ }
9554
+ const permitted = subcommand !== undefined && (READ_ONLY_GIT_SUBCOMMANDS.has(subcommand) || (CONDITIONAL_GIT_SUBCOMMANDS.get(subcommand)?.(args) ?? false));
9555
+ const described = ["git", subcommand].filter(Boolean).join(" ");
9556
+ if (!permitted) {
9557
+ return { allowed: false, reason: refusals.unavailable(described) };
9558
+ }
9559
+ if (hasFlag(tokens.slice(1), GIT_MUTATING_ARGUMENTS) || hasFlag(args, GIT_SUBCOMMAND_MUTATING_ARGUMENTS.get(subcommand) ?? new Set)) {
9560
+ return { allowed: false, reason: refusals.gitArgument(described) };
9561
+ }
9562
+ return { allowed: true };
9563
+ }
9564
+ if (READ_ONLY_COMMANDS.has(program)) {
9565
+ const args = tokens.slice(1);
9566
+ const mutating = MUTATING_ARGUMENTS.get(program);
9567
+ const allowedOptions = OPTION_ALLOWLISTS.get(program);
9568
+ const limit = POSITIONAL_LIMITS.get(program);
9569
+ if (mutating && hasFlag(args, mutating) || allowedOptions && !optionsAllowed(args, allowedOptions) || limit && positionalCount(args, limit.valueOptions, limit.stopAtFirstOperand) > limit.max) {
9570
+ return { allowed: false, reason: refusals.argument(program) };
9571
+ }
9572
+ return { allowed: true };
9573
+ }
9574
+ return { allowed: false, reason: refusals.program(program) };
9612
9575
  }
9613
- function coordinatorReadBoundary(workspaces, env = process.env) {
9614
- const dataDir = env[COORDINATOR_PROTECTED_DATA_DIR_ENV]?.trim();
9615
- return protectedDataDirBoundary(dataDir, [
9616
- env.CLAUDE_CONFIG_DIR,
9617
- env.ORKESTRATOR_BRIDGE_ATTACHMENT_ROOT,
9618
- env[COORDINATOR_CLAUDE_USER_SKILLS_DIR_ENV],
9619
- dataDir ? join6(dataDir, "toolchains") : undefined,
9620
- ...workspaces
9621
- ]);
9576
+ function optionsAllowed(args, allowed) {
9577
+ for (let index = 0;index < args.length; index += 1) {
9578
+ const arg = args[index];
9579
+ if (arg === "--")
9580
+ return true;
9581
+ if (!arg.startsWith("-") || arg === "-")
9582
+ continue;
9583
+ if (allowed.has(arg)) {
9584
+ index += 1;
9585
+ continue;
9586
+ }
9587
+ const long = arg.startsWith("--") ? arg.split("=", 1)[0] : undefined;
9588
+ const attached = long ?? arg.slice(0, 2);
9589
+ if (!allowed.has(attached))
9590
+ return false;
9591
+ }
9592
+ return true;
9622
9593
  }
9623
- function globRoot(pattern) {
9624
- if (!pattern.startsWith("/") && !pattern.startsWith("~") && !pattern.startsWith("..")) {
9625
- return;
9594
+ function positionalCount(args, valueOptions, stopAtFirstOperand = false) {
9595
+ let count = 0;
9596
+ let optionsEnded = false;
9597
+ for (let index = 0;index < args.length; index += 1) {
9598
+ const arg = args[index];
9599
+ if (!optionsEnded && arg === "--") {
9600
+ optionsEnded = true;
9601
+ continue;
9602
+ }
9603
+ if (!optionsEnded && arg.startsWith("-") && arg !== "-") {
9604
+ if (valueOptions.has(arg))
9605
+ index += 1;
9606
+ continue;
9607
+ }
9608
+ count += 1;
9609
+ if (stopAtFirstOperand)
9610
+ optionsEnded = true;
9626
9611
  }
9627
- const wildcard = pattern.search(/[*?[{]/);
9628
- return wildcard < 0 ? pattern : pattern.slice(0, wildcard);
9612
+ return count;
9629
9613
  }
9630
- function readToolRefused(boundary, tool, input, cwd) {
9631
- const text = (key) => {
9632
- const value = input[key];
9633
- return typeof value === "string" && value.trim() ? value : undefined;
9614
+ function deny(reason) {
9615
+ return {
9616
+ hookSpecificOutput: {
9617
+ hookEventName: "PreToolUse",
9618
+ permissionDecision: "deny",
9619
+ permissionDecisionReason: reason
9620
+ }
9634
9621
  };
9635
- if (tool === "Read") {
9636
- const path = text("file_path");
9637
- return path !== undefined && readBoundaryRefuses(boundary, path, cwd);
9638
- }
9639
- if (tool !== "Grep" && tool !== "Glob")
9640
- return false;
9641
- const roots = [text("path") ?? cwd];
9642
- const pattern = tool === "Glob" ? text("pattern") : undefined;
9643
- const root = pattern ? globRoot(pattern) : undefined;
9644
- if (root)
9645
- roots.push(root);
9646
- return roots.some((path) => readBoundaryRefuses(boundary, path, cwd, { traversal: true }));
9647
9622
  }
9648
- function shellCommandRefused(boundary, command, cwd, options) {
9649
- const [program, ...tokens] = command.trim().split(/\s+/);
9650
- if (options.traversal) {
9651
- const indirectOption = program === "sort" || program === "wc" ? "--files0-from" : program === "file" ? "--files-from" : ["cksum", "md5sum", "sha1sum", "sha256sum"].includes(program ?? "") ? "--check" : undefined;
9652
- if (indirectOption && tokens.some((token) => {
9653
- const option = token.split("=", 1)[0];
9654
- return option.startsWith("--") && indirectOption.startsWith(option) || program === "file" && /^-[^-]*f/.test(token) || indirectOption === "--check" && /^-[^-]*c/.test(token);
9655
- }))
9656
- return true;
9657
- 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)))
9658
- return true;
9659
- const searches = program === "rg" || program === "ag" || program === "find" || program === "fd" || program === "du" || program === "ls" || program === "tree" || program === "grep";
9660
- if (searches && readBoundaryRefuses(boundary, cwd, cwd, options))
9661
- return true;
9662
- }
9663
- return tokens.some((token) => {
9664
- const attached = [];
9665
- if (token.startsWith("--")) {
9666
- const equals = token.indexOf("=");
9667
- if (equals >= 0)
9668
- attached.push(token.slice(equals + 1));
9669
- } else if (token.startsWith("-")) {
9670
- for (let index = 1;index < token.length && /[a-zA-Z0-9]/.test(token[index]); index++) {
9671
- attached.push(token.slice(index + 1));
9623
+ function createCoordinatorReadOnlyHook(policy, researchMcpServerNames = coordinatorResearchMcpServersFromEnv(process.env).map((server) => server.name), options = {}) {
9624
+ const refusals = REFUSALS[options.role ?? "coordinator"];
9625
+ const deniedTools = new Set(claudeDeniedTools(policy));
9626
+ const deniedMcpPrefixes = [...deniedTools].filter((tool) => tool.startsWith("mcp__") && tool.endsWith("__*")).map((tool) => tool.slice(0, -1));
9627
+ const allowedMcpPrefixes = [
9628
+ claudeMcpToolPrefix("orkestrator"),
9629
+ ...researchMcpServerNames.map(claudeMcpToolPrefix),
9630
+ ...(nativeAgentUserMcpGrant(policy) ?? []).map(claudeMcpToolPrefix)
9631
+ ];
9632
+ const readBoundary = (cwd) => options.readBoundary !== undefined ? options.readBoundary : process.env[COORDINATOR_PROTECTED_DATA_DIR_ENV] ? coordinatorReadBoundary(claudeReadOnlyWorkspacePaths(cwd)) : null;
9633
+ return async (input) => {
9634
+ if (input.hook_event_name !== "PreToolUse")
9635
+ return {};
9636
+ const toolName = input.tool_name;
9637
+ if (deniedTools.has(toolName)) {
9638
+ return deny(refusals.tool(toolName));
9639
+ }
9640
+ if (WAITING_TOOLS.has(toolName)) {
9641
+ return deny(refusals.waiting(toolName));
9642
+ }
9643
+ if (deniedMcpPrefixes.some((prefix) => toolName.startsWith(prefix))) {
9644
+ return deny(`This session's policy denies the MCP server behind ${toolName}.`);
9645
+ }
9646
+ if (toolName.startsWith("mcp__")) {
9647
+ if (!allowedMcpPrefixes.some((prefix) => toolName.startsWith(prefix))) {
9648
+ return deny(refusals.mcp(toolName));
9672
9649
  }
9650
+ return {};
9673
9651
  }
9674
- return [token, ...attached].some((candidate) => candidate && readBoundaryRefuses(boundary, candidate, cwd, options));
9675
- });
9676
- }
9677
-
9678
- // ../../bridges/claude-bridge/src/services/read-only-policy.ts
9679
- var CAPABILITY_TOOLS = new Map([
9680
- ["file.write", ["Write", "NotebookEdit", "EnterWorktree", "ExitWorktree"]],
9681
- ["file.patch", ["Edit", "MultiEdit", "ApplyPatch"]],
9682
- ["shell", ["Bash", "BashOutput", "KillShell", "PowerShell"]],
9683
- ["shell.mutate", ["PowerShell"]],
9684
- ["network", ["WebFetch", "WebSearch", "RemoteTrigger"]],
9685
- ["web.search", ["WebSearch"]],
9686
- ["subagents", ["Task", "Agent"]],
9687
- ["git.commit", ["Bash(git commit)", "Bash(git commit *)"]],
9688
- ["git.push", ["Bash(git push)", "Bash(git push *)"]],
9689
- ["github.write", ["Bash(gh)", "Bash(gh *)"]]
9690
- ]);
9691
- var READ_ONLY_TOOLS = Object.freeze([
9692
- "Read",
9693
- "Glob",
9694
- "Grep",
9695
- "Bash",
9696
- "Task",
9697
- "Agent",
9698
- "TodoWrite",
9699
- "AskUserQuestion"
9700
- ]);
9701
- var WAITING_TOOLS = new Set([
9702
- "Monitor",
9703
- "ScheduleWakeup",
9704
- "CronCreate",
9705
- "CronList",
9706
- "CronDelete",
9707
- "SendMessage"
9708
- ]);
9709
- var READ_ONLY_COMMANDS = Object.freeze(new Set([
9710
- "awk",
9711
- "basename",
9712
- "cat",
9713
- "cksum",
9714
- "column",
9715
- "comm",
9716
- "cut",
9717
- "date",
9718
- "diff",
9719
- "dirname",
9720
- "du",
9721
- "echo",
9722
- "file",
9723
- "find",
9724
- "fd",
9725
- "grep",
9726
- "head",
9727
- "hostname",
9728
- "jq",
9729
- "ls",
9730
- "md5sum",
9731
- "nl",
9732
- "od",
9733
- "printf",
9734
- "pwd",
9735
- "readlink",
9736
- "realpath",
9737
- "rg",
9738
- "sha1sum",
9739
- "sha256sum",
9740
- "sort",
9741
- "stat",
9742
- "tail",
9743
- "tr",
9744
- "true",
9745
- "uniq",
9746
- "wc",
9747
- "which",
9748
- "whoami",
9749
- "xxd",
9750
- "yq"
9751
- ]));
9752
- var MUTATING_ARGUMENTS = new Map([
9753
- ["date", new Set(["-s", "--set"])],
9754
- ["fd", new Set(["-x", "-X", "--exec", "--exec-batch"])],
9755
- ["file", new Set(["-C", "--compile"])],
9756
- [
9757
- "find",
9758
- new Set([
9759
- "-delete",
9760
- "-exec",
9761
- "-execdir",
9762
- "-fls",
9763
- "-fprint",
9764
- "-fprint0",
9765
- "-fprintf",
9766
- "-ok",
9767
- "-okdir"
9768
- ])
9769
- ],
9770
- ["hostname", new Set(["-F", "--file", "-b", "--boot"])],
9771
- ["rg", new Set(["--hostname-bin", "--pre"])],
9772
- ["sort", new Set(["-o", "--output", "-T", "--temporary-directory", "--compress-program"])],
9773
- ["yq", new Set(["-i", "--in-place", "--inplace", "-s", "--split-exp"])]
9774
- ]);
9775
- var POSITIONAL_LIMITS = new Map([
9776
- ["hostname", { max: 0, valueOptions: new Set }],
9777
- ["uniq", { max: 1, valueOptions: new Set(["-f", "-s", "-w"]) }],
9778
- [
9779
- "xxd",
9780
- {
9781
- max: 1,
9782
- stopAtFirstOperand: true,
9783
- valueOptions: new Set([
9784
- "-c",
9785
- "-cols",
9786
- "-g",
9787
- "-groupsize",
9788
- "-l",
9789
- "-len",
9790
- "-n",
9791
- "-name",
9792
- "-o",
9793
- "-offset",
9794
- "-s",
9795
- "-seek"
9796
- ])
9652
+ if (toolName === "Bash") {
9653
+ const toolInput = input.tool_input;
9654
+ if (toolInput?.dangerouslyDisableSandbox === true) {
9655
+ return deny(refusals.unsandboxed);
9656
+ }
9657
+ const command = typeof toolInput?.command === "string" ? toolInput.command : "";
9658
+ const verdict = isReadOnlyShellCommand(command, options);
9659
+ if (!verdict.allowed)
9660
+ return deny(verdict.reason);
9661
+ const boundary = readBoundary(input.cwd);
9662
+ if (boundary && shellCommandRefused(boundary, command, input.cwd, {
9663
+ traversal: options.commandSandbox === "unavailable"
9664
+ })) {
9665
+ return deny(refusals.dataDirectory);
9666
+ }
9667
+ return {};
9797
9668
  }
9798
- ]
9799
- ]);
9800
- var OPTION_ALLOWLISTS = new Map([
9801
- ["awk", new Set(["-F", "-v", "--field-separator", "--assign"])]
9802
- ]);
9803
- var GIT_GLOBAL_OPTIONS = new Set([
9804
- "-P",
9805
- "--literal-pathspecs",
9806
- "--no-optional-locks",
9807
- "--no-pager"
9808
- ]);
9809
- var GIT_MUTATING_ARGUMENTS = new Set([
9810
- "--config-env",
9811
- "--exec-path",
9812
- "--ext-diff",
9813
- "--filters",
9814
- "--output",
9815
- "--textconv"
9816
- ]);
9817
- var GIT_SUBCOMMAND_MUTATING_ARGUMENTS = new Map([
9818
- ["grep", new Set(["-O", "--open-files-in-pager"])]
9669
+ if (toolName === "Read" || toolName === "Grep" || toolName === "Glob") {
9670
+ const boundary = readBoundary(input.cwd);
9671
+ const toolInput = input.tool_input ?? {};
9672
+ if (boundary && readToolRefused(boundary, toolName, toolInput, input.cwd)) {
9673
+ return deny(refusals.dataDirectory);
9674
+ }
9675
+ }
9676
+ return {};
9677
+ };
9678
+ }
9679
+ var BRIDGE_EXECUTION_POLICY_ENV = "ORKESTRATOR_BRIDGE_EXECUTION_POLICY";
9680
+ function processExecutionPolicyIsCoordinator(env = process.env) {
9681
+ return env[BRIDGE_EXECUTION_POLICY_ENV] === "coordinator-read-only";
9682
+ }
9683
+ function coordinatorProcessPolicy(env = process.env) {
9684
+ return {
9685
+ id: "coordinator-read-only",
9686
+ sandbox: "provider",
9687
+ approvals: "deny",
9688
+ projectResources: false,
9689
+ capabilityPolicy: coordinatorCapabilityPolicy(coordinatorWebResearchFromEnv(env)),
9690
+ networkAccess: "restricted"
9691
+ };
9692
+ }
9693
+ function effectiveExecutionPolicy(requested, env = process.env) {
9694
+ if (!processExecutionPolicyIsCoordinator(env))
9695
+ return requested;
9696
+ return coordinatorProcessPolicy();
9697
+ }
9698
+
9699
+ // ../../bridges/claude-bridge/src/services/read-only-connection-env.ts
9700
+ var log4 = createLogger("bridge.claude");
9701
+ var READ_ONLY_CONNECTION_ENV_NAMES = new Set([
9702
+ "ANTHROPIC_API_KEY",
9703
+ "ANTHROPIC_AUTH_TOKEN",
9704
+ "ANTHROPIC_BASE_URL",
9705
+ "ANTHROPIC_CUSTOM_HEADERS",
9706
+ "CLAUDE_CODE_OAUTH_TOKEN",
9707
+ "ANTHROPIC_MODEL",
9708
+ "ANTHROPIC_SMALL_FAST_MODEL",
9709
+ "ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION",
9710
+ "CLAUDE_CODE_USE_BEDROCK",
9711
+ "CLAUDE_CODE_SKIP_BEDROCK_AUTH",
9712
+ "ANTHROPIC_BEDROCK_BASE_URL",
9713
+ "AWS_REGION",
9714
+ "AWS_DEFAULT_REGION",
9715
+ "AWS_ACCESS_KEY_ID",
9716
+ "AWS_SECRET_ACCESS_KEY",
9717
+ "AWS_SESSION_TOKEN",
9718
+ "AWS_BEARER_TOKEN_BEDROCK",
9719
+ "CLAUDE_CODE_USE_VERTEX",
9720
+ "CLAUDE_CODE_SKIP_VERTEX_AUTH",
9721
+ "ANTHROPIC_VERTEX_PROJECT_ID",
9722
+ "ANTHROPIC_VERTEX_BASE_URL",
9723
+ "CLOUD_ML_REGION",
9724
+ "GOOGLE_CLOUD_PROJECT",
9725
+ "GOOGLE_APPLICATION_CREDENTIALS",
9726
+ "CLAUDE_CODE_USE_FOUNDRY",
9727
+ "CLAUDE_CODE_SKIP_FOUNDRY_AUTH",
9728
+ "ANTHROPIC_FOUNDRY_API_KEY",
9729
+ "ANTHROPIC_FOUNDRY_BASE_URL",
9730
+ "ANTHROPIC_FOUNDRY_RESOURCE",
9731
+ "HTTPS_PROXY",
9732
+ "https_proxy",
9733
+ "HTTP_PROXY",
9734
+ "http_proxy",
9735
+ "NO_PROXY",
9736
+ "no_proxy",
9737
+ "NODE_EXTRA_CA_CERTS",
9738
+ "CLAUDE_CODE_CLIENT_CERT",
9739
+ "CLAUDE_CODE_CLIENT_KEY",
9740
+ "CLAUDE_CODE_CLIENT_KEY_PASSPHRASE"
9819
9741
  ]);
9820
- var READ_ONLY_GIT_SUBCOMMANDS = Object.freeze(new Set([
9821
- "blame",
9822
- "cat-file",
9823
- "describe",
9824
- "diff",
9825
- "grep",
9826
- "log",
9827
- "ls-files",
9828
- "ls-tree",
9829
- "merge-base",
9830
- "name-rev",
9831
- "rev-list",
9832
- "rev-parse",
9833
- "shortlog",
9834
- "show",
9835
- "show-ref",
9836
- "status",
9837
- "whatchanged"
9838
- ]));
9839
- var GIT_REF_WRITE_FLAGS = Object.freeze(new Set([
9840
- "-C",
9841
- "-D",
9842
- "-M",
9843
- "-c",
9844
- "-d",
9845
- "-f",
9846
- "-m",
9847
- "-u",
9848
- "--copy",
9849
- "--delete",
9850
- "--edit-description",
9851
- "--force",
9852
- "--move",
9853
- "--set-upstream-to",
9854
- "--unset-upstream"
9855
- ]));
9856
- var GIT_REF_LIST_FLAGS = Object.freeze(new Set([
9857
- "-l",
9858
- "--list",
9859
- "--contains",
9860
- "--no-contains",
9861
- "--merged",
9862
- "--no-merged",
9863
- "--points-at",
9864
- "--show-current"
9865
- ]));
9866
- var GIT_CONFIG_READ_FLAGS = Object.freeze(new Set(["-l", "--get", "--get-all", "--get-regexp", "--get-urlmatch", "--list"]));
9867
- var GIT_CONFIG_WRITE_FLAGS = Object.freeze(new Set([
9868
- "-e",
9869
- "--add",
9870
- "--edit",
9871
- "--remove-section",
9872
- "--rename-section",
9873
- "--replace-all",
9874
- "--set",
9875
- "--set-all",
9876
- "--unset",
9877
- "--unset-all"
9878
- ]));
9879
- var GIT_CONFIG_READ_SUBCOMMANDS = Object.freeze(new Set(["get", "list"]));
9880
- var GIT_CONFIG_WRITE_SUBCOMMANDS = Object.freeze(new Set(["edit", "remove-section", "rename-section", "set", "unset"]));
9881
- var GIT_REMOTE_READ_SUBCOMMANDS = Object.freeze(new Set(["get-url"]));
9882
- function hasFlag(args, flags) {
9883
- const letters = [...flags].flatMap((flag) => /^-[A-Za-z0-9]$/.test(flag) ? [flag[1]] : []);
9884
- 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)));
9742
+ var READ_ONLY_CONNECTION_ENV_PATTERNS = [
9743
+ /^ANTHROPIC_DEFAULT_[A-Z0-9]+_MODEL$/,
9744
+ /^VERTEX_REGION_CLAUDE_[A-Z0-9_]+$/
9745
+ ];
9746
+ var MAX_CONNECTION_ENV_ENTRIES = 64;
9747
+ var MAX_CONNECTION_ENV_VALUE_BYTES = 16 * 1024;
9748
+ function isReadOnlyConnectionEnvName(name) {
9749
+ return READ_ONLY_CONNECTION_ENV_NAMES.has(name) || READ_ONLY_CONNECTION_ENV_PATTERNS.some((pattern) => pattern.test(name));
9885
9750
  }
9886
- function listsRefsOnly(args) {
9887
- if (hasFlag(args, GIT_REF_WRITE_FLAGS))
9888
- return false;
9889
- const positionals = args.filter((arg) => !arg.startsWith("-"));
9890
- return positionals.length === 0 || hasFlag(args, GIT_REF_LIST_FLAGS);
9751
+ function selectReadOnlyConnectionEnv(settings) {
9752
+ if (!settings || typeof settings !== "object" || Array.isArray(settings))
9753
+ return {};
9754
+ const env = settings.env;
9755
+ if (!env || typeof env !== "object" || Array.isArray(env))
9756
+ return {};
9757
+ const selected = {};
9758
+ let count = 0;
9759
+ for (const [name, raw] of Object.entries(env)) {
9760
+ if (!isReadOnlyConnectionEnvName(name))
9761
+ continue;
9762
+ const value = typeof raw === "string" ? raw : typeof raw === "number" || typeof raw === "boolean" ? String(raw) : undefined;
9763
+ if (value === undefined || value.includes("\x00"))
9764
+ continue;
9765
+ if (Buffer.byteLength(value, "utf8") > MAX_CONNECTION_ENV_VALUE_BYTES)
9766
+ continue;
9767
+ if (++count > MAX_CONNECTION_ENV_ENTRIES)
9768
+ break;
9769
+ selected[name] = value;
9770
+ }
9771
+ return selected;
9891
9772
  }
9892
- function readsConfigOnly(args) {
9893
- if (hasFlag(args, GIT_CONFIG_WRITE_FLAGS))
9773
+ async function readUserSettingsConnectionEnv(settingsPath = claudeUserSettingsPath()) {
9774
+ const selected = await readJsonSliceCached(settingsPath, "read-only-connection-env", selectReadOnlyConnectionEnv);
9775
+ return selected ?? {};
9776
+ }
9777
+ var BEDROCK_AUTH_ENV_NAMES = [
9778
+ "CLAUDE_CODE_USE_BEDROCK",
9779
+ "CLAUDE_CODE_SKIP_BEDROCK_AUTH",
9780
+ "AWS_BEARER_TOKEN_BEDROCK",
9781
+ "AWS_ACCESS_KEY_ID",
9782
+ "AWS_SECRET_ACCESS_KEY",
9783
+ "AWS_SESSION_TOKEN"
9784
+ ];
9785
+ var FALSE_FLAG_VALUES = new Set(["", "0", "false", "no", "off"]);
9786
+ var TRUE_FLAG_VALUES = new Set(["1", "true", "yes", "on"]);
9787
+ function flagMayBeOn(value) {
9788
+ return value !== undefined && !FALSE_FLAG_VALUES.has(value.trim().toLowerCase());
9789
+ }
9790
+ function flagIsOn(value) {
9791
+ return value !== undefined && TRUE_FLAG_VALUES.has(value.trim().toLowerCase());
9792
+ }
9793
+ function bedrockResolvesAwsProfiles(environment) {
9794
+ if (!flagMayBeOn(environment.CLAUDE_CODE_USE_BEDROCK))
9894
9795
  return false;
9895
- const positionals = args.filter((arg) => !arg.startsWith("-"));
9896
- const first = positionals[0];
9897
- if (first && GIT_CONFIG_WRITE_SUBCOMMANDS.has(first))
9796
+ if (flagIsOn(environment.CLAUDE_CODE_SKIP_BEDROCK_AUTH))
9898
9797
  return false;
9899
- if (hasFlag(args, GIT_CONFIG_READ_FLAGS))
9900
- return true;
9901
- if (first && GIT_CONFIG_READ_SUBCOMMANDS.has(first))
9902
- return true;
9903
- return positionals.length <= 1;
9798
+ if (environment.AWS_BEARER_TOKEN_BEDROCK?.trim())
9799
+ return false;
9800
+ return !(environment.AWS_ACCESS_KEY_ID?.trim() && environment.AWS_SECRET_ACCESS_KEY?.trim());
9904
9801
  }
9905
- var CONDITIONAL_GIT_SUBCOMMANDS = new Map([
9906
- ["branch", listsRefsOnly],
9907
- ["config", readsConfigOnly],
9908
- [
9909
- "remote",
9910
- (args) => {
9911
- const first = args.find((arg) => !arg.startsWith("-"));
9912
- return first === undefined || GIT_REMOTE_READ_SUBCOMMANDS.has(first);
9913
- }
9914
- ],
9915
- ["tag", listsRefsOnly]
9802
+ function readOnlyConnectionOverlay(environment, connection) {
9803
+ if (!bedrockResolvesAwsProfiles({ ...environment, ...connection }) || bedrockResolvesAwsProfiles(environment)) {
9804
+ return { overlay: connection, withheldBedrock: false };
9805
+ }
9806
+ const overlay = { ...connection };
9807
+ for (const name of BEDROCK_AUTH_ENV_NAMES)
9808
+ delete overlay[name];
9809
+ return { overlay, withheldBedrock: true };
9810
+ }
9811
+ async function withReadOnlyConnectionEnv(turnPolicy, environment, readConnectionEnv = () => readUserSettingsConnectionEnv()) {
9812
+ if (!isCoordinatorReadOnlyPolicy(turnPolicy))
9813
+ return environment;
9814
+ const connection = await readConnectionEnv();
9815
+ if (Object.keys(connection).length === 0)
9816
+ return environment;
9817
+ const { overlay, withheldBedrock } = readOnlyConnectionOverlay(environment, connection);
9818
+ if (withheldBedrock) {
9819
+ log4.warn("read-only-connection.bedrock-withheld");
9820
+ }
9821
+ if (Object.keys(overlay).length === 0)
9822
+ return environment;
9823
+ return { ...environment, ...overlay };
9824
+ }
9825
+ function connectionEnvFingerprint(environment) {
9826
+ return Object.entries(environment).filter((entry) => typeof entry[1] === "string" && isReadOnlyConnectionEnvName(entry[0])).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
9827
+ }
9828
+
9829
+ // ../../bridges/claude-bridge/src/services/coordinator-skills.ts
9830
+ import { createHash as createHash5, randomBytes } from "node:crypto";
9831
+ import {
9832
+ mkdir as mkdir2,
9833
+ readdir as readdir2,
9834
+ readFile as readFile4,
9835
+ realpath,
9836
+ rename as rename2,
9837
+ rm as rm2,
9838
+ stat as stat3,
9839
+ symlink,
9840
+ writeFile as writeFile2
9841
+ } from "node:fs/promises";
9842
+ import { isAbsolute as isAbsolute2, join as join5 } from "node:path";
9843
+ var KEPT_FRONTMATTER_KEYS = Object.freeze([
9844
+ "name",
9845
+ "description",
9846
+ "when_to_use",
9847
+ "argument-hint",
9848
+ "arguments",
9849
+ "disable-model-invocation",
9850
+ "user-invocable",
9851
+ "version"
9916
9852
  ]);
9917
- var NETWORK_COMMANDS = new Set(["curl", "gh", "wget"]);
9918
- var NETWORK_GIT_SUBCOMMANDS = new Set(["fetch", "ls-remote", "pull"]);
9919
- var COMPOSITION_PATTERN = /[;&|><`$(){}\n\r'"\\*?[\]]|\bsudo\b|\bexec\b/;
9920
- function isCoordinatorReadOnlyPolicy(policy) {
9921
- return policy?.id === "coordinator-read-only";
9853
+ var MIRROR_FORMAT = 1;
9854
+ var MAX_SKILLS_PER_SOURCE = 256;
9855
+ var MAX_SKILL_FILE_BYTES = 1024 * 1024;
9856
+ var MAX_ENTRIES_PER_SKILL = 256;
9857
+ var KEPT_OLD_MIRRORS = 4;
9858
+ var SKILL_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
9859
+ var FRONTMATTER = /^?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;
9860
+ function coordinatorSkillSources(cwd, env = process.env) {
9861
+ const userDir = env[COORDINATOR_CLAUDE_USER_SKILLS_DIR_ENV]?.trim();
9862
+ return [
9863
+ ...userDir && isAbsolute2(userDir) ? [{ plugin: "user-skills", dir: userDir }] : [],
9864
+ { plugin: "project-skills", dir: join5(cwd, ".claude", "skills") }
9865
+ ];
9922
9866
  }
9923
- function claudeDeniedTools(policy) {
9924
- const tools = new Set;
9925
- for (const capability of nativeAgentDeniedCapabilities(policy)) {
9926
- const server = nativeAgentMcpServer(capability);
9927
- if (server) {
9928
- tools.add(`${claudeMcpToolPrefix(server)}*`);
9867
+ async function coordinatorSkillPlugins(sources, root = claudeCoordinatorSkillPluginsDir()) {
9868
+ const plugins = [];
9869
+ const skills = [];
9870
+ for (const source of sources) {
9871
+ try {
9872
+ const mirror = await mirrorSkillSource(source, root);
9873
+ if (!mirror)
9874
+ continue;
9875
+ plugins.push({ type: "local", path: mirror.path });
9876
+ skills.push(...mirror.names.map((name) => `${source.plugin}:${name}`));
9877
+ } catch (error) {
9878
+ debugLog("[coordinator-skills] Skipping skills source", {
9879
+ plugin: source.plugin,
9880
+ error: error instanceof Error ? error.message : String(error)
9881
+ });
9882
+ }
9883
+ }
9884
+ return { plugins, skills };
9885
+ }
9886
+ async function mirrorSkillSource(source, root) {
9887
+ const dir = await realpath(source.dir).catch(() => {
9888
+ return;
9889
+ });
9890
+ if (!dir)
9891
+ return;
9892
+ const skills = await readSkills(dir);
9893
+ if (skills.length === 0)
9894
+ return;
9895
+ const digest = createHash5("sha256").update(JSON.stringify([MIRROR_FORMAT, source.plugin, dir, skills])).digest("hex").slice(0, 24);
9896
+ const path = join5(root, `${source.plugin}-${digest}`);
9897
+ if (!await isMirror(path))
9898
+ await writeMirror(root, path, source.plugin, skills);
9899
+ await pruneOldMirrors(root, source.plugin, path);
9900
+ return { path, names: skills.map((skill) => skill.name) };
9901
+ }
9902
+ async function readSkills(dir) {
9903
+ const entries = (await readdir2(dir)).filter((name) => !name.startsWith(".")).sort();
9904
+ const skills = [];
9905
+ const names = new Set;
9906
+ for (const entry of entries) {
9907
+ if (skills.length >= MAX_SKILLS_PER_SOURCE)
9908
+ break;
9909
+ const skillDir = await realpath(join5(dir, entry)).catch(() => {
9910
+ return;
9911
+ });
9912
+ if (!skillDir || !(await stat3(skillDir).catch(() => {
9913
+ return;
9914
+ }))?.isDirectory())
9929
9915
  continue;
9930
- }
9931
- for (const tool of CAPABILITY_TOOLS.get(capability) ?? [])
9932
- tools.add(tool);
9916
+ const skill = await readSkill(skillDir, entry);
9917
+ if (!skill || names.has(skill.name))
9918
+ continue;
9919
+ names.add(skill.name);
9920
+ skills.push(skill);
9933
9921
  }
9934
- if (!nativeAgentPolicyDeniesWebSearch(policy))
9935
- tools.delete("WebSearch");
9936
- return [...tools];
9922
+ return skills;
9937
9923
  }
9938
- function claudeDisallowedTools(policy) {
9939
- const denied = claudeDeniedTools(policy);
9940
- if (denied.length === 0)
9941
- return policy?.toolPolicy?.deny;
9942
- return [...new Set([...policy?.toolPolicy?.deny ?? [], ...denied])];
9924
+ async function readSkill(skillDir, dirName) {
9925
+ const entries = await readdir2(skillDir);
9926
+ const skillFile = entries.find((entry) => entry === "SKILL.md");
9927
+ if (!skillFile)
9928
+ return;
9929
+ const file = join5(skillDir, skillFile);
9930
+ const info = await stat3(file).catch(() => {
9931
+ return;
9932
+ });
9933
+ if (!info?.isFile() || info.size > MAX_SKILL_FILE_BYTES)
9934
+ return;
9935
+ const sanitized = sanitizeSkillFile(await readFile4(file, "utf8"), dirName);
9936
+ if (!sanitized) {
9937
+ debugLog("[coordinator-skills] Skipping skill with unreadable frontmatter", { dirName });
9938
+ return;
9939
+ }
9940
+ const links = entries.filter((entry) => entry.toLowerCase() !== "skill.md").sort().slice(0, MAX_ENTRIES_PER_SKILL).map((entry) => [entry, join5(skillDir, entry)]);
9941
+ return { name: sanitized.name, text: sanitized.text, links };
9943
9942
  }
9944
- function claudeReadOnlyAllowedTools(options) {
9945
- return [
9946
- ...READ_ONLY_TOOLS,
9947
- ...(options.skillNames ?? []).map((name) => `Skill(${name})`),
9948
- ...options.policy && !nativeAgentPolicyDeniesWebSearch(options.policy) ? ["WebSearch"] : [],
9949
- ...(options.agentMcpServerNames ?? []).map((name) => `${claudeMcpToolPrefix(name)}*`),
9950
- ...(options.researchMcpServerNames ?? []).map((name) => `${claudeMcpToolPrefix(name)}*`),
9951
- ...(options.grantedMcpServerNames ?? []).map((name) => `${claudeMcpToolPrefix(name)}*`)
9952
- ];
9943
+ function yamlParser() {
9944
+ const parse = globalThis.Bun?.YAML?.parse;
9945
+ return typeof parse === "function" ? parse : null;
9953
9946
  }
9954
- function claudeReadOnlySandbox(policy, options = {}) {
9955
- return {
9956
- enabled: options.commandSandbox !== "unavailable",
9957
- failIfUnavailable: options.commandSandbox !== "unavailable",
9958
- autoAllowBashIfSandboxed: true,
9959
- allowUnsandboxedCommands: false,
9960
- excludedCommands: [],
9961
- filesystem: {
9962
- denyWrite: [...new Set(options.workspaces ?? [])],
9963
- ...options.readBoundary ? { denyRead: options.readBoundary.deny, allowRead: options.readBoundary.allow } : {}
9964
- },
9965
- network: {
9966
- allowLocalBinding: policy.networkAccess === "full",
9967
- strictAllowlist: true,
9968
- allowedDomains: []
9947
+ function sanitizeSkillFile(text, dirName, parse = yamlParser()) {
9948
+ const match = FRONTMATTER.exec(text);
9949
+ let fields = {};
9950
+ if (match) {
9951
+ if (!parse)
9952
+ return;
9953
+ let parsed;
9954
+ try {
9955
+ parsed = parse(match[1]);
9956
+ } catch {
9957
+ return;
9958
+ }
9959
+ if (parsed !== null && parsed !== undefined) {
9960
+ if (typeof parsed !== "object" || Array.isArray(parsed))
9961
+ return;
9962
+ fields = parsed;
9969
9963
  }
9970
- };
9971
- }
9972
- function readOnlyRefusalRole(sessionPolicy, readOnlyTurn, env = process.env) {
9973
- if (processExecutionPolicyIsCoordinator(env))
9974
- return "coordinator";
9975
- return !readOnlyTurn && isCoordinatorReadOnlyPolicy(sessionPolicy) ? "coordinator" : "read-only";
9976
- }
9977
- var REFUSALS = {
9978
- coordinator: {
9979
- 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.",
9980
- 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.`,
9981
- gitSandbox: "Coordinator Git commands require the command sandbox because Git configuration can run helpers. Use reading tools or delegate to a worker environment.",
9982
- unavailable: (described) => `Coordinator is read-only, so \`${described}\` is not available here. Delegate it to a worker environment.`,
9983
- 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.`,
9984
- 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.`,
9985
- 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.`,
9986
- program: (program) => `Coordinator is read-only, so \`${program}\` is not available here. Delegate commands that change the checkout to a worker environment.`,
9987
- network: (described) => `Coordinator commands have no network access, so \`${described}\` is not available here. Delegate it to a worker environment.`,
9988
- tool: (tool) => `Coordinator is read-only, so ${tool} is not available. Delegate file changes to a worker environment.`,
9989
- 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.`,
9990
- mcp: (tool) => `Coordinator sessions may only use Orkestrator's own tools, so ${tool} is not available.`,
9991
- unsandboxed: "Coordinator commands may not run outside the sandbox.",
9992
- 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."
9993
- },
9994
- "read-only": {
9995
- 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.",
9996
- byPath: (program) => `This session runs reading programs by name only, so \`${program}\` is not available here. Use the program name.`,
9997
- gitSandbox: "Git commands in this session require the command sandbox because Git configuration can run helpers. Use reading tools instead.",
9998
- unavailable: (described) => `This session is read-only, so \`${described}\` is not available here.`,
9999
- gitArgument: (described) => `This session is read-only, so \`${described}\` cannot be used with an argument that writes a file or runs another program.`,
10000
- gitGlobalOption: (option) => `Git commands in this session run against this checkout only, so the Git option \`${option}\` is not available before the subcommand.`,
10001
- argument: (program) => `This session is read-only, so \`${program}\` cannot be used with an argument that writes or runs another program.`,
10002
- program: (program) => `This session is read-only, so \`${program}\` is not available here. It may read the checkout but not change it.`,
10003
- network: (described) => `Commands in this session have no network access, so \`${described}\` is not available here.`,
10004
- tool: (tool) => `This session is read-only, so ${tool} is not available.`,
10005
- waiting: (tool) => `This session's turns do not wait, so ${tool} is not available. End your turn instead.`,
10006
- mcp: (tool) => `This session may only use Orkestrator's own tools and the MCP servers granted to it, so ${tool} is not available.`,
10007
- unsandboxed: "Commands in this session may not run outside the sandbox.",
10008
- 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."
10009
- }
10010
- };
10011
- function isReadOnlyShellCommand(command, options = {}) {
10012
- const refusals = REFUSALS[options.role ?? "coordinator"];
10013
- const trimmed = command.trim();
10014
- if (!trimmed)
10015
- return { allowed: true };
10016
- if (COMPOSITION_PATTERN.test(trimmed) || /(?:^|\s)~/.test(trimmed)) {
10017
- return { allowed: false, reason: refusals.composition };
10018
9964
  }
10019
- const tokens = trimmed.split(/\s+/).filter(Boolean);
10020
- const first = tokens[0] ?? "";
10021
- if (!first)
10022
- return { allowed: true };
10023
- if (first.includes("/") || first.includes("\\")) {
10024
- return { allowed: false, reason: refusals.byPath(first) };
9965
+ const declared = typeof fields.name === "string" ? fields.name.trim() : "";
9966
+ const name = SKILL_NAME.test(declared) ? declared : dirName;
9967
+ if (!SKILL_NAME.test(name))
9968
+ return;
9969
+ const lines = [`name: ${JSON.stringify(name)}`];
9970
+ for (const key of KEPT_FRONTMATTER_KEYS) {
9971
+ if (key === "name" || !Object.hasOwn(fields, key))
9972
+ continue;
9973
+ const value = frontmatterValue(fields[key]);
9974
+ if (value !== undefined)
9975
+ lines.push(`${key}: ${value}`);
10025
9976
  }
10026
- const program = first;
10027
- if (NETWORK_COMMANDS.has(program))
10028
- return { allowed: false, reason: refusals.network(program) };
10029
- if (program === "git") {
10030
- if (options.commandSandbox !== "required") {
10031
- return { allowed: false, reason: refusals.gitSandbox };
9977
+ const body = match ? text.slice(match[0].length) : text.replace(/^/, "");
9978
+ return { name, text: `---
9979
+ ${lines.join(`
9980
+ `)}
9981
+ ---
9982
+ ${body}` };
9983
+ }
9984
+ function frontmatterValue(value) {
9985
+ if (typeof value === "string" || typeof value === "boolean")
9986
+ return JSON.stringify(value);
9987
+ if (typeof value === "number" && Number.isFinite(value))
9988
+ return JSON.stringify(String(value));
9989
+ if (Array.isArray(value) && value.every((item) => typeof item === "string"))
9990
+ return JSON.stringify(value);
9991
+ return;
9992
+ }
9993
+ async function isMirror(path) {
9994
+ return (await stat3(join5(path, ".claude-plugin", "plugin.json")).catch(() => {
9995
+ return;
9996
+ }))?.isFile() ? true : false;
9997
+ }
9998
+ async function writeMirror(root, path, plugin, skills) {
9999
+ await mkdir2(root, { recursive: true, mode: 448 });
10000
+ const staging = join5(root, `.staging-${randomBytes(8).toString("hex")}`);
10001
+ try {
10002
+ await mkdir2(join5(staging, ".claude-plugin"), { recursive: true });
10003
+ await writeFile2(join5(staging, ".claude-plugin", "plugin.json"), JSON.stringify({
10004
+ name: plugin,
10005
+ 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."
10006
+ }));
10007
+ for (const skill of skills) {
10008
+ const skillDir = join5(staging, "skills", skill.name);
10009
+ await mkdir2(skillDir, { recursive: true });
10010
+ await writeFile2(join5(skillDir, "SKILL.md"), skill.text);
10011
+ for (const [name, target] of skill.links)
10012
+ await symlink(target, join5(skillDir, name));
10032
10013
  }
10033
- const subcommandIndex = tokens.findIndex((token, index) => index > 0 && !token.startsWith("-"));
10034
- const subcommand = subcommandIndex > 0 ? tokens[subcommandIndex] : undefined;
10035
- const args = subcommandIndex > 0 ? tokens.slice(subcommandIndex + 1) : [];
10036
- const globalOptions = tokens.slice(1, subcommandIndex > 0 ? subcommandIndex : undefined);
10037
- const unlisted = globalOptions.find((option) => !GIT_GLOBAL_OPTIONS.has(option));
10038
- if (unlisted)
10039
- return { allowed: false, reason: refusals.gitGlobalOption(unlisted) };
10040
- if (subcommand && (NETWORK_GIT_SUBCOMMANDS.has(subcommand) || subcommand === "remote" && args.some((arg) => arg === "show"))) {
10041
- return { allowed: false, reason: refusals.network(`git ${subcommand}`) };
10014
+ try {
10015
+ await rename2(staging, path);
10016
+ } catch (error) {
10017
+ if (!await isMirror(path))
10018
+ throw error;
10042
10019
  }
10043
- const permitted = subcommand !== undefined && (READ_ONLY_GIT_SUBCOMMANDS.has(subcommand) || (CONDITIONAL_GIT_SUBCOMMANDS.get(subcommand)?.(args) ?? false));
10044
- const described = ["git", subcommand].filter(Boolean).join(" ");
10045
- if (!permitted) {
10046
- return { allowed: false, reason: refusals.unavailable(described) };
10020
+ } finally {
10021
+ await rm2(staging, { recursive: true, force: true });
10022
+ }
10023
+ }
10024
+ async function pruneOldMirrors(root, plugin, current) {
10025
+ try {
10026
+ const old = await Promise.all((await readdir2(root)).filter((name) => name.startsWith(`${plugin}-`) && join5(root, name) !== current).map(async (name) => ({
10027
+ path: join5(root, name),
10028
+ mtimeMs: (await stat3(join5(root, name)).catch(() => {
10029
+ return;
10030
+ }))?.mtimeMs ?? 0
10031
+ })));
10032
+ old.sort((a, b) => b.mtimeMs - a.mtimeMs);
10033
+ for (const { path } of old.slice(KEPT_OLD_MIRRORS)) {
10034
+ await rm2(path, { recursive: true, force: true });
10047
10035
  }
10048
- if (hasFlag(tokens.slice(1), GIT_MUTATING_ARGUMENTS) || hasFlag(args, GIT_SUBCOMMAND_MUTATING_ARGUMENTS.get(subcommand) ?? new Set)) {
10049
- return { allowed: false, reason: refusals.gitArgument(described) };
10036
+ } catch {}
10037
+ }
10038
+
10039
+ // ../../bridges/claude-bridge/src/services/plugin-config.ts
10040
+ import { readdir as readdir3, access } from "node:fs/promises";
10041
+ import { join as join6 } from "node:path";
10042
+
10043
+ // ../protocol/src/node/claude-plugin-set.ts
10044
+ import path2 from "node:path";
10045
+ var CLAUDE_PLUGINS_MARKER = "/.claude/plugins/";
10046
+ function isRecord(value) {
10047
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10048
+ }
10049
+ function claudePluginConfigList(value) {
10050
+ if (!Array.isArray(value))
10051
+ return [];
10052
+ const plugins = [];
10053
+ for (const item of value) {
10054
+ if (isRecord(item) && typeof item.path === "string" && item.path) {
10055
+ plugins.push({ type: "local", path: item.path });
10050
10056
  }
10051
- return { allowed: true };
10052
10057
  }
10053
- if (READ_ONLY_COMMANDS.has(program)) {
10054
- const args = tokens.slice(1);
10055
- const mutating = MUTATING_ARGUMENTS.get(program);
10056
- const allowedOptions = OPTION_ALLOWLISTS.get(program);
10057
- const limit = POSITIONAL_LIMITS.get(program);
10058
- if (mutating && hasFlag(args, mutating) || allowedOptions && !optionsAllowed(args, allowedOptions) || limit && positionalCount(args, limit.valueOptions, limit.stopAtFirstOperand) > limit.max) {
10059
- return { allowed: false, reason: refusals.argument(program) };
10058
+ return plugins;
10059
+ }
10060
+ function isPathWithin(parentDir, candidatePath) {
10061
+ const relativePath = path2.relative(parentDir, candidatePath);
10062
+ return relativePath === "" || !relativePath.startsWith("..") && !path2.isAbsolute(relativePath);
10063
+ }
10064
+ function remapInstalledPlugins(pluginsDir, installedPlugins, onUnsafe) {
10065
+ const plugins = [];
10066
+ const pluginsRoot = path2.resolve(pluginsDir);
10067
+ if (!isRecord(installedPlugins.plugins))
10068
+ return plugins;
10069
+ for (const [installedId, entries] of Object.entries(installedPlugins.plugins)) {
10070
+ if (!Array.isArray(entries))
10071
+ continue;
10072
+ for (const entry of entries) {
10073
+ if (!isRecord(entry) || typeof entry.installPath !== "string")
10074
+ continue;
10075
+ const installPath = entry.installPath;
10076
+ const markerIdx = installPath.indexOf(CLAUDE_PLUGINS_MARKER);
10077
+ let resolvedPath;
10078
+ if (markerIdx !== -1) {
10079
+ const relativePath = installPath.substring(markerIdx + CLAUDE_PLUGINS_MARKER.length);
10080
+ const remappedPath = path2.resolve(pluginsDir, relativePath);
10081
+ if (!isPathWithin(pluginsRoot, remappedPath)) {
10082
+ onUnsafe?.(installPath);
10083
+ continue;
10084
+ }
10085
+ resolvedPath = remappedPath;
10086
+ } else {
10087
+ resolvedPath = installPath;
10088
+ }
10089
+ plugins.push({ type: "local", path: resolvedPath, installedId });
10060
10090
  }
10061
- return { allowed: true };
10062
10091
  }
10063
- return { allowed: false, reason: refusals.program(program) };
10092
+ return plugins;
10064
10093
  }
10065
- function optionsAllowed(args, allowed) {
10066
- for (let index = 0;index < args.length; index += 1) {
10067
- const arg = args[index];
10068
- if (arg === "--")
10069
- return true;
10070
- if (!arg.startsWith("-") || arg === "-")
10071
- continue;
10072
- if (allowed.has(arg)) {
10073
- index += 1;
10074
- continue;
10094
+ function resolveClaudePluginPath(pluginPath, cwd, home) {
10095
+ if (pluginPath.startsWith("~"))
10096
+ return path2.join(home, pluginPath.slice(1));
10097
+ if (pluginPath.startsWith("/"))
10098
+ return pluginPath;
10099
+ return path2.join(cwd, pluginPath);
10100
+ }
10101
+ function mergeClaudePluginLayers(layers, options) {
10102
+ const ordered = [
10103
+ claudePluginConfigList(layers.global),
10104
+ layers.cliInstalled,
10105
+ ...options.includeProjectSources ? [claudePluginConfigList(layers.projectGlobal), claudePluginConfigList(layers.projectLocal)] : []
10106
+ ];
10107
+ const seen = new Set;
10108
+ const paths = [];
10109
+ for (const layer of ordered) {
10110
+ for (const plugin of layer) {
10111
+ const resolved = resolveClaudePluginPath(plugin.path, options.cwd, options.home);
10112
+ if (seen.has(resolved))
10113
+ continue;
10114
+ seen.add(resolved);
10115
+ paths.push(resolved);
10075
10116
  }
10076
- const long = arg.startsWith("--") ? arg.split("=", 1)[0] : undefined;
10077
- const attached = long ?? arg.slice(0, 2);
10078
- if (!allowed.has(attached))
10079
- return false;
10080
10117
  }
10081
- return true;
10118
+ return paths;
10082
10119
  }
10083
- function positionalCount(args, valueOptions, stopAtFirstOperand = false) {
10084
- let count = 0;
10085
- let optionsEnded = false;
10086
- for (let index = 0;index < args.length; index += 1) {
10087
- const arg = args[index];
10088
- if (!optionsEnded && arg === "--") {
10089
- optionsEnded = true;
10120
+ var INVALID_PLUGIN_NAME = new RegExp("[@:\\s/\\\\\\u0000-\\u001f\\u007f\\u200b-\\u200f\\u2028-\\u202e\\u2060-\\u2064\\ufeff]");
10121
+ var CLAUDE_PLUGIN_SETTING_SOURCES = ["local", "project", "user"];
10122
+ function claudeInstalledPluginIdEnablement(id, settings, loadedSources) {
10123
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10124
+ for (const source of ["local", "project", "user"]) {
10125
+ if (!loadedSources.includes(source))
10090
10126
  continue;
10091
- }
10092
- if (!optionsEnded && arg.startsWith("-") && arg !== "-") {
10093
- if (valueOptions.has(arg))
10094
- index += 1;
10127
+ const document = settings[source];
10128
+ const enabledPlugins = isRecord(document) ? document.enabledPlugins : undefined;
10129
+ if (!isRecord(enabledPlugins) || !Object.hasOwn(enabledPlugins, id))
10095
10130
  continue;
10096
- }
10097
- count += 1;
10098
- if (stopAtFirstOperand)
10099
- optionsEnded = true;
10131
+ return { enabled: enabledPlugins[id] === true, decidedBy: { source, key: id } };
10100
10132
  }
10101
- return count;
10133
+ return { enabled: false };
10102
10134
  }
10103
- function deny(reason) {
10104
- return {
10105
- hookSpecificOutput: {
10106
- hookEventName: "PreToolUse",
10107
- permissionDecision: "deny",
10108
- permissionDecisionReason: reason
10109
- }
10110
- };
10135
+ function enabledInstalledPlugins(plugins, settings, loadedSources) {
10136
+ return plugins.filter((plugin) => plugin.installedId === undefined || claudeInstalledPluginIdEnablement(plugin.installedId, settings, loadedSources).enabled);
10111
10137
  }
10112
- function createCoordinatorReadOnlyHook(policy, researchMcpServerNames = coordinatorResearchMcpServersFromEnv(process.env).map((server) => server.name), options = {}) {
10113
- const refusals = REFUSALS[options.role ?? "coordinator"];
10114
- const deniedTools = new Set(claudeDeniedTools(policy));
10115
- const deniedMcpPrefixes = [...deniedTools].filter((tool) => tool.startsWith("mcp__") && tool.endsWith("__*")).map((tool) => tool.slice(0, -1));
10116
- const allowedMcpPrefixes = [
10117
- claudeMcpToolPrefix("orkestrator"),
10118
- ...researchMcpServerNames.map(claudeMcpToolPrefix),
10119
- ...(nativeAgentUserMcpGrant(policy) ?? []).map(claudeMcpToolPrefix)
10120
- ];
10121
- const readBoundary = (cwd) => options.readBoundary !== undefined ? options.readBoundary : process.env[COORDINATOR_PROTECTED_DATA_DIR_ENV] ? coordinatorReadBoundary(claudeReadOnlyWorkspacePaths(cwd)) : null;
10122
- return async (input) => {
10123
- if (input.hook_event_name !== "PreToolUse")
10124
- return {};
10125
- const toolName = input.tool_name;
10126
- if (deniedTools.has(toolName)) {
10127
- return deny(refusals.tool(toolName));
10128
- }
10129
- if (WAITING_TOOLS.has(toolName)) {
10130
- return deny(refusals.waiting(toolName));
10131
- }
10132
- if (deniedMcpPrefixes.some((prefix) => toolName.startsWith(prefix))) {
10133
- return deny(`This session's policy denies the MCP server behind ${toolName}.`);
10134
- }
10135
- if (toolName.startsWith("mcp__")) {
10136
- if (!allowedMcpPrefixes.some((prefix) => toolName.startsWith(prefix))) {
10137
- return deny(refusals.mcp(toolName));
10138
- }
10139
- return {};
10140
- }
10141
- if (toolName === "Bash") {
10142
- const toolInput = input.tool_input;
10143
- if (toolInput?.dangerouslyDisableSandbox === true) {
10144
- return deny(refusals.unsandboxed);
10145
- }
10146
- const command = typeof toolInput?.command === "string" ? toolInput.command : "";
10147
- const verdict = isReadOnlyShellCommand(command, options);
10148
- if (!verdict.allowed)
10149
- return deny(verdict.reason);
10150
- const boundary = readBoundary(input.cwd);
10151
- if (boundary && shellCommandRefused(boundary, command, input.cwd, {
10152
- traversal: options.commandSandbox === "unavailable"
10153
- })) {
10154
- return deny(refusals.dataDirectory);
10138
+ function claudePluginSettingSources(settingSources) {
10139
+ return CLAUDE_PLUGIN_SETTING_SOURCES.filter((source) => settingSources.includes(source));
10140
+ }
10141
+
10142
+ // ../../bridges/claude-bridge/src/services/plugin-config.ts
10143
+ var log5 = createLogger("bridge.claude");
10144
+ async function pathExists(path) {
10145
+ try {
10146
+ await access(path);
10147
+ return true;
10148
+ } catch {
10149
+ return false;
10150
+ }
10151
+ }
10152
+ async function scanCliPluginsDirectory(pluginsDir) {
10153
+ if (!await pathExists(pluginsDir)) {
10154
+ return [];
10155
+ }
10156
+ try {
10157
+ const entries = await readdir3(pluginsDir, { withFileTypes: true });
10158
+ const plugins = [];
10159
+ for (const entry of entries) {
10160
+ if (!entry.isDirectory()) {
10161
+ continue;
10155
10162
  }
10156
- return {};
10157
- }
10158
- if (toolName === "Read" || toolName === "Grep" || toolName === "Glob") {
10159
- const boundary = readBoundary(input.cwd);
10160
- const toolInput = input.tool_input ?? {};
10161
- if (boundary && readToolRefused(boundary, toolName, toolInput, input.cwd)) {
10162
- return deny(refusals.dataDirectory);
10163
+ const pluginPath = join6(pluginsDir, entry.name);
10164
+ const manifestPath = join6(pluginPath, ".claude-plugin", "plugin.json");
10165
+ if (await pathExists(manifestPath)) {
10166
+ plugins.push({
10167
+ type: "local",
10168
+ path: pluginPath
10169
+ });
10163
10170
  }
10164
10171
  }
10165
- return {};
10166
- };
10172
+ return plugins;
10173
+ } catch {
10174
+ return [];
10175
+ }
10167
10176
  }
10168
- var BRIDGE_EXECUTION_POLICY_ENV = "ORKESTRATOR_BRIDGE_EXECUTION_POLICY";
10169
- function processExecutionPolicyIsCoordinator(env = process.env) {
10170
- return env[BRIDGE_EXECUTION_POLICY_ENV] === "coordinator-read-only";
10177
+ async function loadGlobalPlugins() {
10178
+ const plugins = await readJsonSliceCached(claudeJsonPath(), "plugins", (config) => claudePluginConfigList(config?.plugins));
10179
+ return plugins ?? [];
10171
10180
  }
10172
- function coordinatorProcessPolicy(env = process.env) {
10181
+ async function loadProjectPlugins(cwd) {
10182
+ const plugins = await readJsonSliceCached(join6(cwd, ".claude", "plugins.json"), "plugins", (config) => claudePluginConfigList(config?.plugins));
10183
+ return plugins ?? [];
10184
+ }
10185
+ async function loadCliInstalledPlugins() {
10186
+ const pluginsDir = claudePluginsDir();
10187
+ const installedPluginsPath = join6(pluginsDir, "installed_plugins.json");
10188
+ const plugins = await readJsonSliceCached(installedPluginsPath, "plugins", (config) => config?.plugins);
10189
+ if (!plugins) {
10190
+ return scanCliPluginsDirectory(pluginsDir);
10191
+ }
10192
+ return remapInstalledPlugins2(pluginsDir, { plugins });
10193
+ }
10194
+ function pluginSettingsPath(source, cwd) {
10195
+ switch (source) {
10196
+ case "user":
10197
+ return claudeUserSettingsPath();
10198
+ case "project":
10199
+ return join6(cwd, ".claude", "settings.json");
10200
+ case "local":
10201
+ return join6(cwd, ".claude", "settings.local.json");
10202
+ }
10203
+ }
10204
+ async function loadPluginSettings(cwd, sources) {
10205
+ const entries = await Promise.all(sources.map(async (source) => {
10206
+ const enabledPlugins = await readJsonSliceCached(pluginSettingsPath(source, cwd), "enabledPlugins", (config) => config?.enabledPlugins ?? null);
10207
+ return [source, enabledPlugins === null ? undefined : { enabledPlugins }];
10208
+ }));
10209
+ return Object.fromEntries(entries);
10210
+ }
10211
+ function remapInstalledPlugins2(pluginsDir, installedPlugins) {
10212
+ return remapInstalledPlugins(pluginsDir, installedPlugins, (installPath) => log5.warn("plugin.unsafe-path", { path: installPath }));
10213
+ }
10214
+ async function loadProjectOverridesFromGlobal(cwd) {
10215
+ const plugins = await readJsonSliceCached(claudeJsonPath(), `projects:${cwd}:plugins`, (config) => claudePluginConfigList(config?.projects?.[cwd]?.plugins));
10216
+ return plugins ?? [];
10217
+ }
10218
+ async function readPluginManifest(pluginPath) {
10219
+ const manifestPath = join6(pluginPath, ".claude-plugin", "plugin.json");
10220
+ const manifest = await readJsonSliceCached(manifestPath, "manifest", (config) => config ? { name: config.name, description: config.description } : null);
10221
+ if (!manifest) {
10222
+ return null;
10223
+ }
10224
+ const name = manifest.name || pluginPath.split("/").pop() || "unknown";
10173
10225
  return {
10174
- id: "coordinator-read-only",
10175
- sandbox: "provider",
10176
- approvals: "deny",
10177
- projectResources: false,
10178
- capabilityPolicy: coordinatorCapabilityPolicy(coordinatorWebResearchFromEnv(env)),
10179
- networkAccess: "restricted"
10226
+ name,
10227
+ description: manifest.description
10180
10228
  };
10181
10229
  }
10182
- function effectiveExecutionPolicy(requested, env = process.env) {
10183
- if (!processExecutionPolicyIsCoordinator(env))
10184
- return requested;
10185
- return coordinatorProcessPolicy();
10230
+ function resolvePath(pluginPath, cwd) {
10231
+ return resolveClaudePluginPath(pluginPath, cwd, claudeHome());
10232
+ }
10233
+ function defaultSettingSources(includeProjectSources) {
10234
+ return includeProjectSources ? ["user", "project"] : ["user"];
10235
+ }
10236
+ async function getMergedPlugins(cwd, includeProjectSources = true, settingSources = defaultSettingSources(includeProjectSources)) {
10237
+ const sources = claudePluginSettingSources(settingSources);
10238
+ const [global2, cliInstalled, projectGlobal, projectLocal, settings] = await Promise.all([
10239
+ loadGlobalPlugins(),
10240
+ loadCliInstalledPlugins(),
10241
+ includeProjectSources ? loadProjectOverridesFromGlobal(cwd) : [],
10242
+ includeProjectSources ? loadProjectPlugins(cwd) : [],
10243
+ loadPluginSettings(cwd, sources)
10244
+ ]);
10245
+ return mergeClaudePluginLayers({
10246
+ global: global2,
10247
+ cliInstalled: enabledInstalledPlugins(cliInstalled, settings, sources),
10248
+ projectGlobal,
10249
+ projectLocal
10250
+ }, { cwd, home: claudeHome(), includeProjectSources }).map((path) => ({ type: "local", path }));
10251
+ }
10252
+ async function getPluginsForSdk(cwd, includeProjectSources = true, settingSources = defaultSettingSources(includeProjectSources)) {
10253
+ const configs = await getMergedPlugins(cwd, includeProjectSources, settingSources);
10254
+ const validPlugins = [];
10255
+ for (const config of configs) {
10256
+ if (await pathExists(config.path)) {
10257
+ validPlugins.push({
10258
+ type: "local",
10259
+ path: config.path
10260
+ });
10261
+ } else {
10262
+ const pluginName = config.path.split("/").pop() || "unknown";
10263
+ log5.warn("plugin.path-missing", { pluginName, path: config.path });
10264
+ }
10265
+ }
10266
+ return validPlugins;
10267
+ }
10268
+ async function getPluginInfo(cwd) {
10269
+ const [global2, cliInstalled, projectGlobal, projectLocal] = await Promise.all([
10270
+ loadGlobalPlugins(),
10271
+ loadCliInstalledPlugins(),
10272
+ loadProjectOverridesFromGlobal(cwd),
10273
+ loadProjectPlugins(cwd)
10274
+ ]);
10275
+ const globalPaths = new Set(global2.map((p) => resolvePath(p.path, cwd)));
10276
+ const cliPaths = new Set(cliInstalled.map((p) => resolvePath(p.path, cwd)));
10277
+ const projectGlobalPaths = new Set(projectGlobal.map((p) => resolvePath(p.path, cwd)));
10278
+ const projectLocalPaths = new Set(projectLocal.map((p) => resolvePath(p.path, cwd)));
10279
+ const merged = await getMergedPlugins(cwd);
10280
+ const result = [];
10281
+ for (const config of merged) {
10282
+ const manifest = await readPluginManifest(config.path);
10283
+ const exists = await pathExists(config.path);
10284
+ let source = "global";
10285
+ if (projectLocalPaths.has(config.path) || projectGlobalPaths.has(config.path)) {
10286
+ source = "project";
10287
+ } else if (cliPaths.has(config.path)) {
10288
+ source = "cli";
10289
+ } else if (globalPaths.has(config.path)) {
10290
+ source = "global";
10291
+ }
10292
+ result.push({
10293
+ name: manifest?.name || config.path.split("/").pop() || "unknown",
10294
+ path: config.path,
10295
+ description: manifest?.description,
10296
+ source,
10297
+ enabled: exists
10298
+ });
10299
+ }
10300
+ return result;
10186
10301
  }
10187
10302
 
10188
10303
  // ../../bridges/claude-bridge/src/services/claude-query-config.ts
@@ -10215,14 +10330,23 @@ function readOnlyTurnPolicy(sessionPolicy) {
10215
10330
  }
10216
10331
  }, "claude");
10217
10332
  }
10218
- function claudeReportedPolicy(session) {
10333
+ 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.";
10334
+ function claudeReportedPolicy(session, platform = process.platform) {
10219
10335
  if (session.status === "running" && session.commandDiscoveryInputs?.readOnly === true) {
10220
10336
  const turnPolicy = claudeTurnPolicy(session.executionPolicy, true);
10221
10337
  if (turnPolicy) {
10222
10338
  return readOnlyTurnReportedPolicy(turnPolicy, session.readOnlyCommandSandboxOff === undefined ? {} : { commandSandboxOff: session.readOnlyCommandSandboxOff });
10223
10339
  }
10224
10340
  }
10225
- return session.executionPolicy;
10341
+ return session.executionPolicy && withLinuxLoopbackNote(session.executionPolicy, platform);
10342
+ }
10343
+ function withLinuxLoopbackNote(policy, platform) {
10344
+ if (platform !== "linux" || policy.sandbox !== "provider" || policy.networkAccess !== "full") {
10345
+ return policy;
10346
+ }
10347
+ if (policy.note?.includes(CLAUDE_LINUX_SANDBOX_LOOPBACK_NOTE))
10348
+ return policy;
10349
+ return appendNativeAgentPolicyNote(policy, CLAUDE_LINUX_SANDBOX_LOOPBACK_NOTE);
10226
10350
  }
10227
10351
  function claudePolicyPermissionMode(policy) {
10228
10352
  return isRestrictivePolicy(policy) ? "default" : "bypassPermissions";
@@ -10495,7 +10619,7 @@ function claudeSandboxRefusal(policy, options = {}) {
10495
10619
  }
10496
10620
 
10497
10621
  // ../../bridges/claude-bridge/src/services/session-manager-background-tasks.ts
10498
- var log5 = createLogger("bridge.claude");
10622
+ var log6 = createLogger("bridge.claude");
10499
10623
  var PROVISIONAL_BACKGROUND_TASK_PREFIX = "pending-bash:";
10500
10624
  var MAX_BACKGROUND_TASK_CANDIDATES = 128;
10501
10625
  function provisionalBackgroundTaskId(toolUseId) {
@@ -10530,7 +10654,7 @@ function registerBackgroundTaskCandidate(runtime, toolUseId) {
10530
10654
  return;
10531
10655
  const { candidates } = runtime.tasks;
10532
10656
  if (!candidates.has(toolUseId) && candidates.size >= MAX_BACKGROUND_TASK_CANDIDATES) {
10533
- log5.warn("task.candidate-bound-reached", {
10657
+ log6.warn("task.candidate-bound-reached", {
10534
10658
  sessionId: runtime.session.id,
10535
10659
  bound: MAX_BACKGROUND_TASK_CANDIDATES
10536
10660
  });
@@ -10644,7 +10768,7 @@ async function persistShellTaskFields(session, toolUseId, fields) {
10644
10768
  ]
10645
10769
  });
10646
10770
  } catch {
10647
- log5.warn("task.details-persist-failed");
10771
+ log6.warn("task.details-persist-failed");
10648
10772
  }
10649
10773
  }
10650
10774
  function cacheShellTaskFields(session, toolUseId, fields) {
@@ -10766,7 +10890,7 @@ function parkSettlingBackgroundTask(owner, task) {
10766
10890
  return;
10767
10891
  const { settling } = owner.tasks;
10768
10892
  if (!settling.has(task.id) && settling.size >= MAX_SETTLING_BACKGROUND_TASKS) {
10769
- log5.warn("task.settling-bound-reached", {
10893
+ log6.warn("task.settling-bound-reached", {
10770
10894
  sessionId: owner.session.id,
10771
10895
  bound: MAX_SETTLING_BACKGROUND_TASKS
10772
10896
  });
@@ -10841,7 +10965,7 @@ async function stopBackgroundTask(sessionId, taskId) {
10841
10965
  if (latest && !LIVE_BACKGROUND_TASK_STATUSES.has(latest.status)) {
10842
10966
  return { ok: true };
10843
10967
  }
10844
- log5.warn("task.stop-failed", { error: formatLogError(error, { stack: false }) });
10968
+ log6.warn("task.stop-failed", { error: formatLogError(error, { stack: false }) });
10845
10969
  if (settleBackgroundTask(session, taskId, "killed", "The Claude control channel for this task is no longer available")) {
10846
10970
  emitBackgroundTaskSnapshot(session);
10847
10971
  }
@@ -12468,7 +12592,7 @@ function restoredTurnInterruption(preferences) {
12468
12592
  }
12469
12593
 
12470
12594
  // ../../bridges/claude-bridge/src/services/session-manager-lifecycle.ts
12471
- var log6 = createLogger("bridge.claude");
12595
+ var log7 = createLogger("bridge.claude");
12472
12596
  async function getSessionActivity(sessionId) {
12473
12597
  const session = sessions.get(sessionId);
12474
12598
  if (session) {
@@ -12648,7 +12772,7 @@ async function claimPromptDispatch(sessionId, requestId, startDispatch, testHook
12648
12772
  try {
12649
12773
  await updateSessionPreferences(sdkSessionId, journalUpdate([...retainedRequestIds].slice(-MAX_DISPATCHED_REQUEST_IDS)));
12650
12774
  } catch (rollbackError) {
12651
- log6.error("dispatch.rollback-failed", {
12775
+ log7.error("dispatch.rollback-failed", {
12652
12776
  error: formatLogError(rollbackError, { stack: false })
12653
12777
  });
12654
12778
  }
@@ -12902,7 +13026,8 @@ function claudeLaunchResourceProfile(plugins, environment) {
12902
13026
  credentials: digest([
12903
13027
  environment.GH_TOKEN ?? null,
12904
13028
  environment.GITHUB_TOKEN ?? null,
12905
- environment.GITHUB_PERSONAL_ACCESS_TOKEN ?? null
13029
+ environment.GITHUB_PERSONAL_ACCESS_TOKEN ?? null,
13030
+ connectionEnvFingerprint(environment)
12906
13031
  ])
12907
13032
  };
12908
13033
  }
@@ -12942,7 +13067,7 @@ async function assertClaudeRuntimeAccepts(session, options, resources, readOnlyC
12942
13067
  const policy = claudeTurnPolicy(session.executionPolicy, options?.readOnly);
12943
13068
  const [{ plugins }, environment] = await Promise.all([
12944
13069
  resolveClaudeTurnPlugins(request.cwd, policy, claudeTurnSettingSources(session, options)),
12945
- runtimeEnvironmentForSessionQuery(policy)
13070
+ runtimeEnvironmentForSessionQuery(policy).then((environment) => withReadOnlyConnectionEnv(policy, environment))
12946
13071
  ]);
12947
13072
  resources = claudeLaunchResourceProfile(plugins, environment);
12948
13073
  }
@@ -13596,7 +13721,7 @@ function groupHasLiveMember(pgid) {
13596
13721
  }
13597
13722
 
13598
13723
  // ../protocol/src/node/lost-exit-reaper.ts
13599
- var log7 = createLogger("process");
13724
+ var log8 = createLogger("process");
13600
13725
  var REAP_GRACE_MS = 2000;
13601
13726
  var REAP_MAX_CHECK_MS = 30000;
13602
13727
  var REAP_MAX_CHECKS = 12;
@@ -13612,7 +13737,7 @@ function createLostExitReaper(options) {
13612
13737
  let abandoned = 0;
13613
13738
  const abandon = (pid, reason) => {
13614
13739
  abandoned += 1;
13615
- log7.warn("child.reap-abandoned", { pid, reason });
13740
+ log8.warn("child.reap-abandoned", { pid, reason });
13616
13741
  };
13617
13742
  const check = (pid, reported, startedAt) => {
13618
13743
  if (reported())
@@ -13627,7 +13752,7 @@ function createLostExitReaper(options) {
13627
13752
  const result = system.waitNoHang(pid);
13628
13753
  if (result === pid) {
13629
13754
  reaped += 1;
13630
- log7.info("child.reaped", { pid, waitedMs: Date.now() - startedAt });
13755
+ log8.info("child.reaped", { pid, waitedMs: Date.now() - startedAt });
13631
13756
  return false;
13632
13757
  }
13633
13758
  if (result === 0)
@@ -13711,7 +13836,7 @@ var defaultReaper;
13711
13836
  function createDarwinLostExitReaper(loadFfi) {
13712
13837
  const system = darwinReaperSystem(loadFfi);
13713
13838
  if (!system)
13714
- log7.warn("child.reap-unavailable");
13839
+ log8.warn("child.reap-unavailable");
13715
13840
  return system ? createLostExitReaper({ system }) : null;
13716
13841
  }
13717
13842
  function sharedReaper() {
@@ -16075,11 +16200,6 @@ function commandChangeJournal(sdkSessionId) {
16075
16200
  }
16076
16201
  return journal;
16077
16202
  }
16078
- async function deleteCommandChangeJournal(sdkSessionId) {
16079
- const journal = commandChangeJournal(sdkSessionId);
16080
- journals.delete(sdkSessionId);
16081
- await journal?.remove();
16082
- }
16083
16203
  function isMeasuredCommand(toolName, toolInput) {
16084
16204
  if (toolName !== "Bash")
16085
16205
  return false;
@@ -16259,9 +16379,6 @@ function labelSubagentModel(row, parent, records) {
16259
16379
  }
16260
16380
  }
16261
16381
  async function rehydrateSubagentParts(sdk, sdkSessionId, dir, messages) {
16262
- if (typeof sdk.listSubagents !== "function" || typeof sdk.getSubagentMessages !== "function") {
16263
- return;
16264
- }
16265
16382
  const agentIds = (await sdk.listSubagents(sdkSessionId, { dir }).catch(() => [])).slice(0, MAX_REHYDRATED_SUBAGENTS);
16266
16383
  if (agentIds.length === 0)
16267
16384
  return;
@@ -16324,19 +16441,7 @@ function applyLocalTranscriptOverlay(session) {
16324
16441
  markTranscriptChanged(session);
16325
16442
  }
16326
16443
  var sessionDeletionTick = 0;
16327
- var DELETE_TOMBSTONE_LIMIT = 128;
16328
16444
  var deletedSdkSessionTicks = new Map;
16329
- function recordDeletedSdkSession(sdkSessionId) {
16330
- sessionDeletionTick += 1;
16331
- deletedSdkSessionTicks.delete(sdkSessionId);
16332
- deletedSdkSessionTicks.set(sdkSessionId, sessionDeletionTick);
16333
- while (deletedSdkSessionTicks.size > DELETE_TOMBSTONE_LIMIT) {
16334
- const oldest = deletedSdkSessionTicks.keys().next();
16335
- if (oldest.done)
16336
- break;
16337
- deletedSdkSessionTicks.delete(oldest.value);
16338
- }
16339
- }
16340
16445
  function deletedSinceTick(sdkSessionId, readTick) {
16341
16446
  const deletedAt = deletedSdkSessionTicks.get(sdkSessionId);
16342
16447
  return deletedAt !== undefined && deletedAt > readTick;
@@ -16350,8 +16455,6 @@ function isDefaultSessionTitle(title, bridgeId, sdkId) {
16350
16455
  }
16351
16456
  async function reconcilePersistedSessions() {
16352
16457
  const sdk = await claudeSdk();
16353
- if (typeof sdk.listSessions !== "function")
16354
- return;
16355
16458
  const cwd = currentWorkingDirectory();
16356
16459
  const listStartedAtTick = sessionDeletionTick;
16357
16460
  const infos = await sdk.listSessions({
@@ -16415,8 +16518,6 @@ async function materializePersistedSessionState(sessionId, sdkId) {
16415
16518
  const racedDuringImport = sessions.get(sessionId);
16416
16519
  if (racedDuringImport)
16417
16520
  return racedDuringImport;
16418
- if (typeof sdk.getSessionInfo !== "function")
16419
- return;
16420
16521
  const [info, preferences] = await Promise.all([
16421
16522
  sdk.getSessionInfo(sdkId, {
16422
16523
  dir: currentWorkingDirectory()
@@ -16479,8 +16580,6 @@ async function readPersistedSessionMessages(session) {
16479
16580
  if (!session.sdkSessionId)
16480
16581
  return;
16481
16582
  const sdk = await claudeSdk();
16482
- if (typeof sdk.getSessionMessages !== "function")
16483
- return;
16484
16583
  const [persisted, commandChanges, preferences] = await Promise.all([
16485
16584
  sdk.getSessionMessages(session.sdkSessionId, {
16486
16585
  dir: currentWorkingDirectory(),
@@ -16630,60 +16729,6 @@ function startIdleTranscriptSweep(intervalMs = IDLE_TRANSCRIPT_SWEEP_INTERVAL_MS
16630
16729
  return timer;
16631
16730
  }
16632
16731
  startIdleTranscriptSweep();
16633
- async function deleteSessionDurably(sessionId) {
16634
- const session = sessions.get(sessionId) ?? await ensurePersistedSession(sessionId);
16635
- if (!session) {
16636
- const sdkSessionId = sdkSessionIdFromBridgeId(sessionId);
16637
- if (sdkSessionId) {
16638
- await deleteSessionPreferences(sdkSessionId);
16639
- await deleteCommandChangeJournal(sdkSessionId);
16640
- }
16641
- return false;
16642
- }
16643
- if (session.deleting) {
16644
- throw sessionOperationError("conflict", "Session deletion is already in progress");
16645
- }
16646
- session.deleting = true;
16647
- session.status = "running";
16648
- claimedPromptDispatches.delete(sessionId);
16649
- session.abortController?.abort();
16650
- session.abortController = undefined;
16651
- cleanupPendingInteractions(sessionId);
16652
- await releaseQueryControls(session);
16653
- await waitForPendingPromptDispatchClaim(sessionId);
16654
- let rolloutDeleted = false;
16655
- try {
16656
- const preferenceSessionId = session.sdkSessionId ?? sdkSessionIdFromBridgeId(session.id);
16657
- if (session.sdkSessionId) {
16658
- const sdk = await claudeSdk();
16659
- if (typeof sdk.deleteSession === "function") {
16660
- await sdk.deleteSession(session.sdkSessionId, {
16661
- dir: currentWorkingDirectory()
16662
- });
16663
- }
16664
- rolloutDeleted = true;
16665
- recordDeletedSdkSession(session.sdkSessionId);
16666
- }
16667
- forgetPromptDispatchesForSession(sessionId);
16668
- if (preferenceSessionId) {
16669
- await deleteSessionPreferences(preferenceSessionId);
16670
- await deleteCommandChangeJournal(preferenceSessionId);
16671
- }
16672
- sessions.delete(sessionId);
16673
- return true;
16674
- } catch (error) {
16675
- if (rolloutDeleted && session.sdkSessionId) {
16676
- recordDeletedSdkSession(session.sdkSessionId);
16677
- sessions.delete(sessionId);
16678
- throw error;
16679
- }
16680
- session.deleting = false;
16681
- session.status = "idle";
16682
- session.turnStartedAt = undefined;
16683
- session.completionBlockedByBackgroundTasks = false;
16684
- throw error;
16685
- }
16686
- }
16687
16732
  async function renameSessionDurably(sessionId, title) {
16688
16733
  const session = await ensurePersistedSession(sessionId);
16689
16734
  if (!session)
@@ -16707,9 +16752,6 @@ async function forkPersistedSession(sessionId, options = {}) {
16707
16752
  throw sessionOperationError("conflict", "Cannot fork a running session");
16708
16753
  }
16709
16754
  const sdk = await claudeSdk();
16710
- if (typeof sdk.forkSession !== "function") {
16711
- throw sessionOperationError("conflict", "Installed Claude Agent SDK does not support session forking");
16712
- }
16713
16755
  const boundaryId = options.upToMessageId ? await resolvePersistedMessageId(source, options.upToMessageId) : undefined;
16714
16756
  if (options.upToMessageId && !boundaryId) {
16715
16757
  throw sessionOperationError("invalid", "The selected Claude message is not a persisted fork boundary");
@@ -16744,8 +16786,6 @@ async function resolvePersistedMessageId(session, normalizedMessageId, allowedTy
16744
16786
  if (local && !allowedTypes.has(local.role))
16745
16787
  return;
16746
16788
  const sdk = await claudeSdk();
16747
- if (typeof sdk.getSessionMessages !== "function")
16748
- return candidate;
16749
16789
  const persisted = await sdk.getSessionMessages(session.sdkSessionId, {
16750
16790
  dir: currentWorkingDirectory(),
16751
16791
  includeSystemMessages: false
@@ -17685,6 +17725,29 @@ class PromptStream {
17685
17725
  }
17686
17726
  }
17687
17727
 
17728
+ // ../protocol/src/agent-usage-limits.ts
17729
+ var USAGE_LIMIT_PATTERNS = [
17730
+ /usage[\s_-]?limit/i,
17731
+ /hit your (?:usage |session |weekly )?limit/i,
17732
+ /\b(?:5|five)[\s-]?hour limit\b/i,
17733
+ /\bweekly limit\b/i,
17734
+ /\b(?:usage|quota|credits?|allowance) (?:is |has been )?(?:exhausted|exceeded|used up)\b/i,
17735
+ /\bquota exceeded\b|\binsufficient_quota\b|\bout of (?:credits|usage)\b/i,
17736
+ /\bUSAGE_EXHAUSTED\b|\bPAYMENT_REQUIRED\b/,
17737
+ /\b(?:usage|plan|session|daily|weekly|monthly|go) limit reached\b/i
17738
+ ];
17739
+ function classifyUsageLimitError(text) {
17740
+ if (typeof text !== "string" || !text.trim())
17741
+ return null;
17742
+ const bounded = text.slice(0, 2000);
17743
+ if (!USAGE_LIMIT_PATTERNS.some((pattern) => pattern.test(bounded)))
17744
+ return null;
17745
+ const reset = bounded.match(/\b(?:resets?|try again)(?:\s+(?:at|in|after))?\s+([^.\n·]{1,60})/i);
17746
+ const hint = reset?.[1]?.trim();
17747
+ return hint ? { resetHint: hint } : {};
17748
+ }
17749
+ var USAGE_LIMIT_ERROR_CODE = "usage-limit";
17750
+
17688
17751
  // ../protocol/src/structured-output-text.ts
17689
17752
  var STRUCTURED_OUTPUT_RECOVERY_CHARS = 1024 * 1024;
17690
17753
  var THINKING_TAGS = "thinking|thought|reasoning|think";
@@ -17984,7 +18047,7 @@ function reconcileClaudeUsage(terminal, streamed) {
17984
18047
  }
17985
18048
 
17986
18049
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-turn-lifecycle.ts
17987
- var log8 = createLogger("bridge.claude");
18050
+ var log9 = createLogger("bridge.claude");
17988
18051
  function diagnosticErrorClass(error) {
17989
18052
  try {
17990
18053
  if (!(error instanceof Error))
@@ -17995,6 +18058,27 @@ function diagnosticErrorClass(error) {
17995
18058
  return "Error";
17996
18059
  }
17997
18060
  }
18061
+ function isUsageLimitError(error) {
18062
+ try {
18063
+ const text = error instanceof Error ? error.message : error;
18064
+ return classifyUsageLimitError(text) !== null;
18065
+ } catch {
18066
+ return false;
18067
+ }
18068
+ }
18069
+ var USAGE_LIMITED_ERROR_PROPERTY = "usageLimited";
18070
+ function markUsageLimitError(error) {
18071
+ if (typeof error !== "object" && typeof error !== "function" || error === null)
18072
+ return;
18073
+ try {
18074
+ Object.defineProperty(error, USAGE_LIMITED_ERROR_PROPERTY, {
18075
+ value: true,
18076
+ configurable: true,
18077
+ enumerable: false,
18078
+ writable: false
18079
+ });
18080
+ } catch {}
18081
+ }
17998
18082
  function ownsActiveTurn(turn) {
17999
18083
  const { session, sessionId } = turn;
18000
18084
  return !turn.abortController.signal.aborted && sessions.get(sessionId) === session && session.abortController === turn.abortController;
@@ -18053,7 +18137,7 @@ async function reconcilePlanModeFromStatus(turn, reported) {
18053
18137
  try {
18054
18138
  await applySessionPlanMode(session, false);
18055
18139
  } catch (error) {
18056
- log8.warn("plan-mode.record-failed", { sessionId, errorClass: diagnosticErrorClass(error) });
18140
+ log9.warn("plan-mode.record-failed", { sessionId, errorClass: diagnosticErrorClass(error) });
18057
18141
  }
18058
18142
  }
18059
18143
  function setCompletionBlockedByBackgroundTasks(turn, blocked) {
@@ -18298,7 +18382,7 @@ function createTurnState(session, sessionId, init) {
18298
18382
  }
18299
18383
 
18300
18384
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-admission.ts
18301
- var log9 = createLogger("bridge.claude");
18385
+ var log10 = createLogger("bridge.claude");
18302
18386
  var STREAM_EVENT_COALESCE_MS = 100;
18303
18387
  function admitPrompt(sessionId, options) {
18304
18388
  const session = sessions.get(sessionId);
@@ -18433,7 +18517,7 @@ async function readTranscriptForPrompt(session) {
18433
18517
  try {
18434
18518
  return await readPersistedSessionMessagesOnce(session);
18435
18519
  } catch (error) {
18436
- log9.warn("transcript.hydrate-failed", { error: formatLogError(error, { stack: false }) });
18520
+ log10.warn("transcript.hydrate-failed", { error: formatLogError(error, { stack: false }) });
18437
18521
  return TRANSCRIPT_READ_FAILED;
18438
18522
  }
18439
18523
  }
@@ -18537,7 +18621,7 @@ var ORKESTRATOR_ARTIFACT_MCP_SERVER_NAME = "orkestrator-artifacts";
18537
18621
  var ORKESTRATOR_ARTIFACT_MCP_PATH = "/artifact-mcp";
18538
18622
 
18539
18623
  // ../../bridges/claude-bridge/src/services/mcp-config.ts
18540
- var log10 = createLogger("bridge.claude");
18624
+ var log11 = createLogger("bridge.claude");
18541
18625
  var AGENT_MCP_SERVER_NAME = "orkestrator";
18542
18626
  var AGENT_MCP_URL_ENV = "ORKESTRATOR_AGENT_MCP_URL";
18543
18627
  var AGENT_MCP_TOKEN_ENV = "ORKESTRATOR_AGENT_MCP_TOKEN";
@@ -18622,7 +18706,7 @@ function toSdkServers(configs) {
18622
18706
  if (sdkConfig) {
18623
18707
  servers[name] = sdkConfig;
18624
18708
  } else {
18625
- log10.warn("mcp.config-ignored");
18709
+ log11.warn("mcp.config-ignored");
18626
18710
  }
18627
18711
  }
18628
18712
  return servers;
@@ -18665,13 +18749,6 @@ async function getMcpServerInfo(cwd) {
18665
18749
  function sourceDigest(digest) {
18666
18750
  return digest === null ? "absent" : `sha256:${digest}`;
18667
18751
  }
18668
- function normalizeScope(scope) {
18669
- if (scope === true)
18670
- return "all";
18671
- if (scope === false)
18672
- return "user";
18673
- return scope;
18674
- }
18675
18752
  function mcpSourceScopeForPolicy(policy) {
18676
18753
  if (isCoordinatorReadOnlyPolicy(policy)) {
18677
18754
  return (nativeAgentUserMcpGrant(policy)?.length ?? 0) > 0 ? "user" : "none";
@@ -18743,7 +18820,7 @@ function revisionFingerprint(sources) {
18743
18820
  return createHash9("sha256").update(`user=${sources.user}\x00project=${sources.project}`).digest("base64url");
18744
18821
  }
18745
18822
  async function getMcpRuntimeConfig(cwd, env = process.env, connection, sources = "all", allowConfigured) {
18746
- const scoped = await loadScopedMcpServers(cwd, normalizeScope(sources));
18823
+ const scoped = await loadScopedMcpServers(cwd, sources);
18747
18824
  const { revision } = scoped;
18748
18825
  const configs = allowConfigured ? Object.fromEntries(Object.entries(scoped.configs).filter(([name]) => allowConfigured(name))) : scoped.configs;
18749
18826
  const servers = toSdkServers(configs);
@@ -18768,7 +18845,7 @@ async function getMcpRuntimeConfig(cwd, env = process.env, connection, sources =
18768
18845
  delete servers[ORKESTRATOR_ARTIFACT_MCP_SERVER_NAME];
18769
18846
  layers.delete(ORKESTRATOR_ARTIFACT_MCP_SERVER_NAME);
18770
18847
  }
18771
- const research = normalizeScope(sources) === "none" ? coordinatorResearchMcpServersFromEnv(env) : [];
18848
+ const research = sources === "none" ? coordinatorResearchMcpServersFromEnv(env) : [];
18772
18849
  for (const server of research)
18773
18850
  servers[server.name] = { type: "http", url: server.url };
18774
18851
  return {
@@ -19016,7 +19093,7 @@ function claudeReadiness() {
19016
19093
  }
19017
19094
 
19018
19095
  // ../../bridges/claude-bridge/src/services/claude-model-catalog.ts
19019
- var log11 = createLogger("bridge.claude");
19096
+ var log12 = createLogger("bridge.claude");
19020
19097
  var CLAUDE_MODEL_CACHE_TTL_MS = 60 * 60000;
19021
19098
  var CLAUDE_MODEL_PROBE_TIMEOUT_MS = 25000;
19022
19099
  var remembered;
@@ -19151,7 +19228,7 @@ async function probeModels(at) {
19151
19228
  await rememberModels(models, account, at);
19152
19229
  return { source: "sdk", models: catalogModels(models) };
19153
19230
  } catch (error) {
19154
- log11.warn("models.fetch-failed", { error: formatLogError(error) });
19231
+ log12.warn("models.fetch-failed", { error: formatLogError(error) });
19155
19232
  return fallbackCatalog();
19156
19233
  } finally {
19157
19234
  if (q?.return) {
@@ -19862,44 +19939,6 @@ async function performSessionMcpAction(sessionId, serverId, action) {
19862
19939
  });
19863
19940
  }
19864
19941
  }
19865
- function claudeWindowId(label) {
19866
- const known = claudePlanWindowFromLabel(label);
19867
- if (known)
19868
- return known.id;
19869
- const slug = label.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
19870
- return slug || "window";
19871
- }
19872
- async function planUsageFrom(control) {
19873
- const getStructuredUsage = control.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET;
19874
- if (!getStructuredUsage) {
19875
- throw new Error("Claude's plan usage API is unavailable in this CLI version");
19876
- }
19877
- const structuredUsage = await getStructuredUsageWithTimeout(getStructuredUsage, control, PLAN_USAGE_PROBE_TIMEOUT_MS);
19878
- return rateLimitsFromStructuredUsage(structuredUsage);
19879
- }
19880
- async function readClaudePlanUsage() {
19881
- let rateLimits = await readFromLiveClaude((control) => control.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET ? planUsageFrom(control) : undefined, PLAN_USAGE_PROBE_TIMEOUT_MS);
19882
- let probe;
19883
- try {
19884
- if (rateLimits === undefined) {
19885
- probe = createProbe();
19886
- rateLimits = await planUsageFrom(probe);
19887
- }
19888
- if (rateLimits === undefined) {
19889
- throw new Error("Claude did not report plan usage");
19890
- }
19891
- return rateLimits.map((window) => ({
19892
- window: claudeWindowId(window.label),
19893
- label: window.label,
19894
- ...window.usedPercent !== undefined ? { usedPercent: window.usedPercent } : {},
19895
- ...window.resetsAt !== undefined ? { resetsAt: window.resetsAt } : {}
19896
- }));
19897
- } finally {
19898
- await Promise.resolve(probe?.close()).catch(() => {
19899
- return;
19900
- });
19901
- }
19902
- }
19903
19942
  async function steerClaudeSession(sessionId, text, requestId, expectedRunId) {
19904
19943
  const capacityRefusal = {
19905
19944
  outcome: "rejected",
@@ -21446,14 +21485,14 @@ function isValidMcpFormContent(schema, content) {
21446
21485
  }
21447
21486
 
21448
21487
  // ../../bridges/claude-bridge/src/services/session-manager-interactions.ts
21449
- var log12 = createLogger("bridge.claude");
21488
+ var log13 = createLogger("bridge.claude");
21450
21489
  function answerQuestion(requestId, answers) {
21451
21490
  const question = pendingQuestions.get(requestId);
21452
21491
  if (!question) {
21453
21492
  debugLog("[session-manager] Question not found for requestId:", requestId);
21454
21493
  return false;
21455
21494
  }
21456
- log12.info("question.answering", { requestId, answerCount: Object.keys(answers).length });
21495
+ log13.info("question.answering", { requestId, answerCount: Object.keys(answers).length });
21457
21496
  const resolver = questionResolvers.get(requestId);
21458
21497
  if (resolver) {
21459
21498
  debugLog("[session-manager] Resolving promise for question:", requestId);
@@ -21505,7 +21544,7 @@ function respondToPlanApproval(requestId, approved, feedback) {
21505
21544
  debugLog("[session-manager] Refusing incomplete plan approval", { requestId });
21506
21545
  return false;
21507
21546
  }
21508
- log12.info("plan-approval.responding", {
21547
+ log13.info("plan-approval.responding", {
21509
21548
  requestId,
21510
21549
  approved,
21511
21550
  hasFeedback: typeof feedback === "string" && feedback.length > 0
@@ -21862,7 +21901,7 @@ async function requestClaudeToolApproval(sessionId, toolName, input, permissionC
21862
21901
  }
21863
21902
 
21864
21903
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-hooks.ts
21865
- var log13 = createLogger("bridge.claude");
21904
+ var log14 = createLogger("bridge.claude");
21866
21905
  async function recordPreCompact(turn, hookInput) {
21867
21906
  const { session } = turn;
21868
21907
  if (hookInput.hook_event_name !== "PreCompact" || session.latestTurnGeneration !== turn.turnGeneration) {
@@ -21976,7 +22015,7 @@ function recordingHookDenials(hook, conversationId) {
21976
22015
  } catch (error) {
21977
22016
  if (input.hook_event_name !== "PreToolUse")
21978
22017
  throw error;
21979
- log13.warn("hook.boundary-failed-closed", { tool: input.tool_name });
22018
+ log14.warn("hook.boundary-failed-closed", { tool: input.tool_name });
21980
22019
  output = {
21981
22020
  hookSpecificOutput: {
21982
22021
  hookEventName: "PreToolUse",
@@ -22100,7 +22139,7 @@ async function resolveQueryPlan(turn, sdkTextPrompt, testHooks) {
22100
22139
  const envPath = process.env.PATH;
22101
22140
  debugLog("[session-manager] SDK env PATH", { path: envPath });
22102
22141
  const sdkPrompt = await buildSdkPrompt(sdkTextPrompt, options?.attachments, cwd, testHooks?.afterAttachmentSymlinkValidation, testHooks?.afterAttachmentCanonicalValidation, testHooks?.afterAttachmentInitialValidation);
22103
- const queryEnvironment = withReadOnlyGitConfig(policy, withUnattendedOverloadRetry(session.executionPolicy, await runtimeEnvironmentForSessionQuery(policy)));
22142
+ const queryEnvironment = withReadOnlyGitConfig(policy, withUnattendedOverloadRetry(session.executionPolicy, await withReadOnlyConnectionEnv(policy, await runtimeEnvironmentForSessionQuery(policy))));
22104
22143
  const liveSettings = claudeLiveSettings({
22105
22144
  model: options?.model,
22106
22145
  permissionMode,
@@ -22750,31 +22789,8 @@ var LEAF_MESSAGE_HANDLERS = {
22750
22789
  conversation_reset: handleConversationReset
22751
22790
  };
22752
22791
 
22753
- // ../protocol/src/agent-usage-limits.ts
22754
- var USAGE_LIMIT_PATTERNS = [
22755
- /usage[\s_-]?limit/i,
22756
- /hit your (?:usage |session |weekly )?limit/i,
22757
- /\b(?:5|five)[\s-]?hour limit\b/i,
22758
- /\bweekly limit\b/i,
22759
- /\b(?:usage|quota|credits?|allowance) (?:is |has been )?(?:exhausted|exceeded|used up)\b/i,
22760
- /\bquota exceeded\b|\binsufficient_quota\b|\bout of (?:credits|usage)\b/i,
22761
- /\bUSAGE_EXHAUSTED\b|\bPAYMENT_REQUIRED\b/,
22762
- /\b(?:usage|plan|session|daily|weekly|monthly|go) limit reached\b/i
22763
- ];
22764
- function classifyUsageLimitError(text) {
22765
- if (typeof text !== "string" || !text.trim())
22766
- return null;
22767
- const bounded = text.slice(0, 2000);
22768
- if (!USAGE_LIMIT_PATTERNS.some((pattern) => pattern.test(bounded)))
22769
- return null;
22770
- const reset = bounded.match(/\b(?:resets?|try again)(?:\s+(?:at|in|after))?\s+([^.\n·]{1,60})/i);
22771
- const hint = reset?.[1]?.trim();
22772
- return hint ? { resetHint: hint } : {};
22773
- }
22774
- var USAGE_LIMIT_ERROR_CODE = "usage-limit";
22775
-
22776
22792
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-handlers/result.ts
22777
- var log14 = createLogger("bridge.claude");
22793
+ var log15 = createLogger("bridge.claude");
22778
22794
  function claudeStartupFailureMessage(reason) {
22779
22795
  switch (reason) {
22780
22796
  case "org_pin_api_key_conflict":
@@ -22979,9 +22995,13 @@ async function handleResultMessage(turn, message) {
22979
22995
  debugLog("[session-manager] Query stopped by the user", { sessionId });
22980
22996
  finishTurnInputIfSettled(turn);
22981
22997
  } else {
22982
- log14.error("query.failed", { subtype: resultMsg.subtype, sessionId, isError: resultIsError });
22983
22998
  const startupFailure = resultMsg.startup_failure_reason ? withStartupFailureDetail(claudeStartupFailureMessage(resultMsg.startup_failure_reason), resultMsg.errors) : undefined;
22984
22999
  const usageLimit = resultMsg.subtype === "success" && classifyUsageLimitError(resultMsg.result) ? resultMsg.result.trim().slice(0, MAX_USAGE_LIMIT_ERROR_CHARS) : undefined;
23000
+ if (!startupFailure && (usageLimit || turn.rateLimitRejected)) {
23001
+ log15.warn("query.usage-limited", { subtype: resultMsg.subtype, sessionId });
23002
+ } else {
23003
+ log15.error("query.failed", { subtype: resultMsg.subtype, sessionId, isError: resultIsError });
23004
+ }
22985
23005
  const resultError = startupFailure || resultMsg.errors?.filter(Boolean).join(`
22986
23006
  `) || usageLimit || (resultMsg.subtype === "success" ? "Claude ended the turn on an API error." : `Claude query failed: ${resultMsg.subtype}`);
22987
23007
  if (startupFailure) {
@@ -23414,7 +23434,7 @@ async function handleSystemMessage(turn, message) {
23414
23434
  }
23415
23435
 
23416
23436
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-handlers/user.ts
23417
- var log15 = createLogger("bridge.claude");
23437
+ var log16 = createLogger("bridge.claude");
23418
23438
  function handleUserMessage(turn, message) {
23419
23439
  const { session, sessionId, stream } = turn;
23420
23440
  const { toolTracker, taskRegistry, activeTaskIds } = stream;
@@ -23464,7 +23484,7 @@ function handleUserMessage(turn, message) {
23464
23484
  if (turn.planApprovedThisTurn) {
23465
23485
  for (const tool of toolTracker.getTools()) {
23466
23486
  if (tool.toolName === "ExitPlanMode" && tool.toolState === "failure" && tool.toolUseId) {
23467
- log15.warn("plan-exit.failure-overridden", { sessionId, toolUseId: tool.toolUseId });
23487
+ log16.warn("plan-exit.failure-overridden", { sessionId, toolUseId: tool.toolUseId });
23468
23488
  toolTracker.updateToolResult(tool.toolUseId, {
23469
23489
  state: "success",
23470
23490
  output: "Plan approved by the user. Proceeding with implementation.",
@@ -23576,7 +23596,7 @@ async function readClaudeMcpToolHints(control, serverName, toolName, timeoutMs =
23576
23596
  }
23577
23597
 
23578
23598
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-can-use-tool.ts
23579
- var log16 = createLogger("bridge.claude");
23599
+ var log17 = createLogger("bridge.claude");
23580
23600
  function boundedPlan(content) {
23581
23601
  if (typeof content !== "string" || content.trim().length === 0)
23582
23602
  return {};
@@ -23635,7 +23655,7 @@ async function askUserQuestion(turn, input, permissionContext) {
23635
23655
  });
23636
23656
  try {
23637
23657
  const answers = await Promise.race([answerPromise, timeoutPromise]);
23638
- log16.info("question.answers-received", { questionId, answerCount: Object.keys(answers).length });
23658
+ log17.info("question.answers-received", { questionId, answerCount: Object.keys(answers).length });
23639
23659
  return {
23640
23660
  behavior: "allow",
23641
23661
  updatedInput: {
@@ -23644,7 +23664,7 @@ async function askUserQuestion(turn, input, permissionContext) {
23644
23664
  }
23645
23665
  };
23646
23666
  } catch (error) {
23647
- log16.warn("question.wait-failed", { error: formatLogError(error) });
23667
+ log17.warn("question.wait-failed", { error: formatLogError(error) });
23648
23668
  const message = error instanceof Error ? error.message : "Question was cancelled";
23649
23669
  if (pendingQuestions.has(questionId)) {
23650
23670
  eventEmitter.emit({
@@ -23725,7 +23745,7 @@ async function requestPlanApproval(turn, input, permissionContext) {
23725
23745
  });
23726
23746
  try {
23727
23747
  const response = await Promise.race([approvalPromise, timeoutPromise]);
23728
- log16.info("plan-approval.result", {
23748
+ log17.info("plan-approval.result", {
23729
23749
  approvalId,
23730
23750
  approved: response.approved,
23731
23751
  hasFeedback: typeof response.feedback === "string" && response.feedback.length > 0
@@ -23774,7 +23794,7 @@ Please revise the plan based on this feedback.` : `I've reviewed the plan and I
23774
23794
  };
23775
23795
  }
23776
23796
  } catch (error) {
23777
- log16.warn("plan-approval.wait-failed", { error: formatLogError(error) });
23797
+ log17.warn("plan-approval.wait-failed", { error: formatLogError(error) });
23778
23798
  const errorMessage = error instanceof Error ? error.message : "Plan approval was cancelled";
23779
23799
  if (pendingPlanApprovals.has(approvalId)) {
23780
23800
  eventEmitter.emit({
@@ -23865,7 +23885,7 @@ function createClaudeRuntimeTurn(turn) {
23865
23885
  }
23866
23886
 
23867
23887
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-launch.ts
23868
- var log17 = createLogger("bridge.claude");
23888
+ var log18 = createLogger("bridge.claude");
23869
23889
  async function consumeClaudeRuntime(runtime, frames, markEnded) {
23870
23890
  let failure;
23871
23891
  try {
@@ -23942,7 +23962,7 @@ function releaseOrphanedForeground(runtime, error) {
23942
23962
  eventEmitter.emit({ type: "session.idle", sessionId, data: { success: true } });
23943
23963
  return;
23944
23964
  }
23945
- log17.error("runtime.ended-under-resumed-turn", { sessionId });
23965
+ log18.error("runtime.ended-under-resumed-turn", { sessionId });
23946
23966
  session.status = "error";
23947
23967
  session.error = error instanceof Error ? error.message : String(error);
23948
23968
  session.errorCode = undefined;
@@ -24107,7 +24127,7 @@ async function runTurnOnRuntime(turn, plan, testHooks) {
24107
24127
  }
24108
24128
 
24109
24129
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-settle.ts
24110
- var log18 = createLogger("bridge.claude");
24130
+ var log19 = createLogger("bridge.claude");
24111
24131
  function settleTurnEnd(turn) {
24112
24132
  const { session, sessionId, options, structuredRequestId, abortController, stream, diagnostics } = turn;
24113
24133
  diagnostics?.streamSettled("resolved");
@@ -24229,9 +24249,15 @@ function settleFailedTurn(turn, error) {
24229
24249
  recordInterruptedStructuredOutputIfCurrent(turn);
24230
24250
  return;
24231
24251
  }
24232
- log18.error("prompt.failed", { errorClass: diagnosticErrorClass(error) });
24252
+ const killedBy = killedClaudeProcessSignal(error);
24253
+ const usageLimited = !killedBy && (turn.rateLimitRejected || isUsageLimitError(error));
24254
+ if (usageLimited) {
24255
+ log19.warn("prompt.usage-limited", { errorClass: diagnosticErrorClass(error) });
24256
+ markUsageLimitError(error);
24257
+ } else {
24258
+ log19.error("prompt.failed", { errorClass: diagnosticErrorClass(error) });
24259
+ }
24233
24260
  if (session.abortController === abortController) {
24234
- const killedBy = killedClaudeProcessSignal(error);
24235
24261
  const failure = killedBy ? claudeProcessKilledMessage(killedBy) : error instanceof Error ? error.message : String(error);
24236
24262
  if (options?.outputSchema && structuredRequestId && !session.structuredOutput) {
24237
24263
  recordStructuredOutput(session, structuredOutputFailure("claude", "provider_error", failure, {
@@ -24339,7 +24365,7 @@ function finalizeTurn(turn) {
24339
24365
  }
24340
24366
 
24341
24367
  // ../../bridges/claude-bridge/src/services/session-manager-prompt.ts
24342
- var log19 = createLogger("bridge.claude");
24368
+ var log20 = createLogger("bridge.claude");
24343
24369
  function turnWriterLiveness(turn) {
24344
24370
  const tasks = Object.values(turn.session.backgroundTasks ?? {});
24345
24371
  if (tasks.some((task) => LIVE_BACKGROUND_TASK_STATUSES.has(task.status)))
@@ -24382,7 +24408,7 @@ async function sendPrompt(sessionId, prompt, options, testHooks) {
24382
24408
  try {
24383
24409
  await sendPrompt(sessionId, followUp.prompt, followUp.options);
24384
24410
  } catch (repromptError) {
24385
- log19.error(followUp.failureEvent, { error: formatLogError(repromptError) });
24411
+ log20.error(followUp.failureEvent, { error: formatLogError(repromptError) });
24386
24412
  return Promise.reject(repromptError);
24387
24413
  }
24388
24414
  } catch (error) {
@@ -24394,7 +24420,7 @@ async function sendPrompt(sessionId, prompt, options, testHooks) {
24394
24420
  }
24395
24421
  }
24396
24422
  // ../../bridges/claude-bridge/src/services/session-manager-close.ts
24397
- var log20 = createLogger("bridge.claude");
24423
+ var log21 = createLogger("bridge.claude");
24398
24424
  var CLOSE_CONFIRMATION_BUDGET_MS = 1e4;
24399
24425
 
24400
24426
  class SessionCloseNotConfirmedError extends Error {
@@ -24457,7 +24483,7 @@ async function closeQueryControls(controls, deadline) {
24457
24483
  if (await settlesBy(Promise.resolve(control.close()), deadline))
24458
24484
  return;
24459
24485
  } catch (error) {
24460
- log20.error("query.close-failed", {
24486
+ log21.error("query.close-failed", {
24461
24487
  errorClass: error instanceof Error ? error.name : typeof error
24462
24488
  });
24463
24489
  }
@@ -24469,18 +24495,18 @@ async function settlesBy(work, deadline) {
24469
24495
  return (await boundedWait(work, Math.max(0, deadline - Date.now()))).settled;
24470
24496
  }
24471
24497
  // ../../bridges/claude-bridge/src/routes/config.ts
24472
- var log21 = createLogger("bridge.claude");
24498
+ var log22 = createLogger("bridge.claude");
24473
24499
  var config2 = new Hono2;
24474
24500
  config2.get("/models", async (c) => {
24475
24501
  if (c.req.query("forceRefresh") === "true")
24476
24502
  invalidateClaudeModelCatalog();
24477
24503
  const startedAt = Date.now();
24478
- log21.debug("models.requested");
24504
+ log22.debug("models.requested");
24479
24505
  const [{ models, source }, versions] = await Promise.all([
24480
24506
  getAvailableModelCatalog(),
24481
24507
  getClaudeRuntimeVersions()
24482
24508
  ]);
24483
- log21.debug("models.responded", { count: models.length, durationMs: Date.now() - startedAt });
24509
+ log22.debug("models.responded", { count: models.length, durationMs: Date.now() - startedAt });
24484
24510
  const response = {
24485
24511
  models,
24486
24512
  source,
@@ -25504,7 +25530,7 @@ function bridgeTranscriptPageRouteBody(source, query) {
25504
25530
  }
25505
25531
 
25506
25532
  // ../../bridges/claude-bridge/src/routes/session-transcript.ts
25507
- var log22 = createLogger("bridge.claude");
25533
+ var log23 = createLogger("bridge.claude");
25508
25534
  function claudeTranscriptSource(id, generation) {
25509
25535
  const sessionData = peekSession(id);
25510
25536
  if (!sessionData)
@@ -25557,7 +25583,7 @@ function registerSessionTranscriptRoutes(app, generation, materialize) {
25557
25583
  const response = c.json(bridgeTranscriptRouteBody(read.source, query3(c)));
25558
25584
  if (read.needsHydration) {
25559
25585
  hydratePersistedSessionMessages(id).catch((error) => {
25560
- log22.warn("transcript.background-hydrate-failed", {
25586
+ log23.warn("transcript.background-hydrate-failed", {
25561
25587
  error: formatLogError(error, { stack: false })
25562
25588
  });
25563
25589
  });
@@ -25569,7 +25595,7 @@ function registerSessionTranscriptRoutes(app, generation, materialize) {
25569
25595
  }
25570
25596
 
25571
25597
  // ../../bridges/claude-bridge/src/routes/session.ts
25572
- var log23 = createLogger("bridge.claude");
25598
+ var log24 = createLogger("bridge.claude");
25573
25599
  var session = new Hono2;
25574
25600
  var TRANSCRIPT_GENERATION = randomUUID6();
25575
25601
  var MAX_QUESTION_ANSWER_REQUEST_BYTES = AGENT_INTERACTION_LIMITS.maxSerializedPayloadBytes + 1024;
@@ -25615,6 +25641,22 @@ function sessionErrorStatus(error) {
25615
25641
  return 503;
25616
25642
  return 500;
25617
25643
  }
25644
+ function isUsageLimitedRejection(error) {
25645
+ try {
25646
+ if (error?.usageLimited === true)
25647
+ return true;
25648
+ return classifyUsageLimitError(error instanceof Error ? error.message : error) !== null;
25649
+ } catch {
25650
+ return false;
25651
+ }
25652
+ }
25653
+ function logPromptProcessingFailure(error) {
25654
+ if (isUsageLimitedRejection(error)) {
25655
+ log24.debug("prompt.processing-usage-limited");
25656
+ return;
25657
+ }
25658
+ log24.error("prompt.processing-failed", { error: formatLogError(error) });
25659
+ }
25618
25660
  var STALE_PROMPT_STATUS = 409;
25619
25661
  function stalePrompt(message) {
25620
25662
  return { error: message, status: "stale" };
@@ -25649,7 +25691,7 @@ session.post("/create", async (c) => {
25649
25691
  const clientSessionKey = body.clientSessionKey;
25650
25692
  const policy = effectiveExecutionPolicy(isNativeAgentExecutionPolicy(body.policy) ? body.policy : undefined);
25651
25693
  const newSession = policy ? await createOrRecoverSession(title, clientSessionKey, policy) : await createOrRecoverSession(title, clientSessionKey);
25652
- log23.info("session.created", { sessionId: newSession.id });
25694
+ log24.info("session.created", { sessionId: newSession.id });
25653
25695
  const response = {
25654
25696
  sessionId: newSession.id,
25655
25697
  title: newSession.title
@@ -25657,10 +25699,10 @@ session.post("/create", async (c) => {
25657
25699
  return c.json(response, 201);
25658
25700
  } catch (error) {
25659
25701
  if (error instanceof PolicyWideningRefusedError) {
25660
- log23.warn("session.policy-widening-refused", { widened: error.widened.join(",") });
25702
+ log24.warn("session.policy-widening-refused", { widened: error.widened.join(",") });
25661
25703
  return c.json(error.refusal(), 403);
25662
25704
  }
25663
- log23.error("session.create-failed", { error: formatLogError(error) });
25705
+ log24.error("session.create-failed", { error: formatLogError(error) });
25664
25706
  return c.json({ error: error instanceof Error ? error.message : "Failed to create session" }, 500);
25665
25707
  }
25666
25708
  });
@@ -25668,7 +25710,7 @@ session.get("/list", async (c) => {
25668
25710
  try {
25669
25711
  await reconcilePersistedSessions();
25670
25712
  } catch (error) {
25671
- log23.warn("sessions.reconcile-failed", { error: formatLogError(error) });
25713
+ log24.warn("sessions.reconcile-failed", { error: formatLogError(error) });
25672
25714
  }
25673
25715
  const sessions = listSessions();
25674
25716
  const response = {
@@ -25687,7 +25729,7 @@ async function resolveSession(id, failureMessage) {
25687
25729
  try {
25688
25730
  return { ok: true, session: getSession(id) ?? await ensurePersistedSession(id) };
25689
25731
  } catch (error) {
25690
- log23.error("session.resolve-failed", { action: failureMessage, error: formatLogError(error) });
25732
+ log24.error("session.resolve-failed", { action: failureMessage, error: formatLogError(error) });
25691
25733
  return {
25692
25734
  ok: false,
25693
25735
  body: { error: errorMessage(error, failureMessage) },
@@ -25708,7 +25750,7 @@ session.get("/:id", async (c) => {
25708
25750
  try {
25709
25751
  await hydratePersistedSessionMessages(id);
25710
25752
  } catch (error) {
25711
- log23.error("session.task-state-hydrate-failed", { error: formatLogError(error) });
25753
+ log24.error("session.task-state-hydrate-failed", { error: formatLogError(error) });
25712
25754
  return c.json({ error: errorMessage(error, "Failed to hydrate session task state") }, sessionErrorStatus(error));
25713
25755
  }
25714
25756
  }
@@ -25760,39 +25802,10 @@ session.get("/:id/usage", async (c) => {
25760
25802
  const contextUsage = await refreshClaudeContextUsage(resolved.session);
25761
25803
  return c.json({ contextUsage });
25762
25804
  } catch (error) {
25763
- log23.warn("context-usage.read-failed", { error: formatLogError(error, { stack: false }) });
25805
+ log24.warn("context-usage.read-failed", { error: formatLogError(error, { stack: false }) });
25764
25806
  return c.json({ error: "Context usage is temporarily unavailable" }, 503);
25765
25807
  }
25766
25808
  });
25767
- session.put("/:id/preferences", async (c) => {
25768
- const id = c.req.param("id");
25769
- try {
25770
- let body;
25771
- try {
25772
- body = await c.req.json();
25773
- } catch {
25774
- return c.json({ error: "Request body must be valid JSON" }, 400);
25775
- }
25776
- if (body === null || typeof body !== "object" || Array.isArray(body) || Object.getPrototypeOf(body) !== Object.prototype) {
25777
- return c.json({ error: "Request body must be a JSON object" }, 400);
25778
- }
25779
- const record = body;
25780
- const unexpectedField = Object.keys(record).find((key) => key !== "planMode");
25781
- if (unexpectedField) {
25782
- return c.json({ error: `Unexpected session preference field: ${unexpectedField}` }, 400);
25783
- }
25784
- if (!Object.hasOwn(record, "planMode")) {
25785
- return c.json({ error: "planMode is required" }, 400);
25786
- }
25787
- if (Object.hasOwn(record, "planMode") && typeof record.planMode !== "boolean") {
25788
- return c.json({ error: "planMode must be a boolean" }, 400);
25789
- }
25790
- const updated = await setSessionPreferences(id, typeof record.planMode === "boolean" ? { planMode: record.planMode } : {});
25791
- return c.json({ planMode: updated.planMode ?? false });
25792
- } catch (error) {
25793
- return c.json({ error: errorMessage(error, "Failed to update session preferences") }, sessionErrorStatus(error));
25794
- }
25795
- });
25796
25809
  function claudeApprovalMode(value) {
25797
25810
  return value === "default" || value === "acceptEdits" || value === "auto" || value === "bypassPermissions" ? value : undefined;
25798
25811
  }
@@ -25810,7 +25823,7 @@ session.post("/:id/config", async (c) => {
25810
25823
  const refusePolicyWidening = () => {
25811
25824
  const widened = nextPolicy ? executionPolicyWidenings(sessionData.executionPolicy, nextPolicy) : [];
25812
25825
  if (widened.length > 0) {
25813
- log23.warn("session.policy-widening-refused", {
25826
+ log24.warn("session.policy-widening-refused", {
25814
25827
  sessionId: sessionData.id,
25815
25828
  widened: widened.join(",")
25816
25829
  });
@@ -25851,7 +25864,7 @@ session.get("/:id/commands", async (c) => {
25851
25864
  try {
25852
25865
  return c.json(await readClaudeCommandCatalogue(c.req.param("id")));
25853
25866
  } catch (error) {
25854
- log23.warn("commands.read-failed", { error: formatLogError(error, { stack: false }) });
25867
+ log24.warn("commands.read-failed", { error: formatLogError(error, { stack: false }) });
25855
25868
  return c.json({ error: errorMessage(error, "Claude command discovery failed") }, 503);
25856
25869
  }
25857
25870
  });
@@ -25913,17 +25926,6 @@ session.get("/:id/structured-output", (c) => {
25913
25926
  requestId: sessionData.structuredOutputRequestId
25914
25927
  });
25915
25928
  });
25916
- session.get("/:id/tasks", async (c) => {
25917
- const id = c.req.param("id");
25918
- const sessionData = getSession(id) ?? await ensurePersistedSession(id);
25919
- if (!sessionData) {
25920
- return c.json({ error: "Session not found" }, 404);
25921
- }
25922
- if (sessionData.persistedMessagesLoaded === false) {
25923
- await hydratePersistedSessionMessages(id);
25924
- }
25925
- return c.json(sessionData.taskRegistry?.snapshot() ?? { items: [], complete: true });
25926
- });
25927
25929
  session.get("/:id/messages", async (c) => {
25928
25930
  const id = c.req.param("id");
25929
25931
  const resolved = await resolveSession(id, "Failed to load session messages");
@@ -26096,7 +26098,7 @@ session.post("/:id/prompt", async (c) => {
26096
26098
  rejectStarted?.(sessionOperationError("conflict", "Prompt stopped before launch"));
26097
26099
  }, (error) => {
26098
26100
  rejectStarted?.(error);
26099
- log23.error("prompt.processing-failed", { error: formatLogError(error) });
26101
+ logPromptProcessingFailure(error);
26100
26102
  });
26101
26103
  return { started, completion };
26102
26104
  });
@@ -26110,7 +26112,7 @@ session.post("/:id/prompt", async (c) => {
26110
26112
  duplicate: true
26111
26113
  });
26112
26114
  }
26113
- log23.debug("prompt.accepted", { sessionId: id });
26115
+ log24.debug("prompt.accepted", { sessionId: id });
26114
26116
  return c.json({
26115
26117
  status: "processing",
26116
26118
  requestId,
@@ -26123,7 +26125,7 @@ session.post("/:id/prompt", async (c) => {
26123
26125
  if (sessionData.rewindInProgress === true) {
26124
26126
  return c.json({ error: "Session is restoring files from a checkpoint" }, 409);
26125
26127
  }
26126
- log23.info("prompt.received", {
26128
+ log24.info("prompt.received", {
26127
26129
  sessionId: id,
26128
26130
  promptLength: prompt.length,
26129
26131
  model,
@@ -26151,16 +26153,16 @@ session.post("/:id/prompt", async (c) => {
26151
26153
  ...workflowResultTurn ? { workflowResultTurn } : {},
26152
26154
  ...providerPrompt !== undefined ? { providerPrompt } : {}
26153
26155
  }).catch((error) => {
26154
- log23.error("prompt.processing-failed", { error: formatLogError(error) });
26156
+ logPromptProcessingFailure(error);
26155
26157
  });
26156
- log23.debug("prompt.accepted", { sessionId: id });
26158
+ log24.debug("prompt.accepted", { sessionId: id });
26157
26159
  return c.json({
26158
26160
  status: "processing",
26159
26161
  requestId,
26160
26162
  turnStartedAt: sessionData.turnStartedAt
26161
26163
  }, 202);
26162
26164
  } catch (error) {
26163
- log23.error("prompt.send-failed", { error: formatLogError(error) });
26165
+ log24.error("prompt.send-failed", { error: formatLogError(error) });
26164
26166
  return c.json({ error: errorMessage(error, "Failed to send prompt") }, sessionErrorStatus(error));
26165
26167
  }
26166
26168
  });
@@ -26195,34 +26197,7 @@ session.post("/:id/hard-abort", (c) => {
26195
26197
  return c.json({ error: "Session not found" }, 404);
26196
26198
  return c.json({ status: abortSession(id) ? "aborted" : "not_running" });
26197
26199
  });
26198
- session.delete("/:id", async (c) => {
26199
- const id = c.req.param("id");
26200
- try {
26201
- const deleted = await deleteSessionDurably(id);
26202
- if (deleted) {
26203
- return c.json({ status: "deleted" });
26204
- }
26205
- return c.json({ error: "Session not found" }, 404);
26206
- } catch (error) {
26207
- log23.error("session.delete-failed", { error: formatLogError(error) });
26208
- return c.json({ error: errorMessage(error, "Failed to delete session") }, sessionErrorStatus(error));
26209
- }
26210
- });
26211
26200
  registerSessionCloseRoute(session);
26212
- session.post("/:id/rename", async (c) => {
26213
- const id = c.req.param("id");
26214
- const body = await c.req.json().catch(() => ({}));
26215
- const title = typeof body.title === "string" ? body.title.trim() : "";
26216
- if (!title)
26217
- return c.json({ error: "Title is required" }, 400);
26218
- try {
26219
- const renamed = await renameSessionDurably(id, title);
26220
- return renamed ? c.json({ status: "renamed", title }) : c.json({ error: "Session not found" }, 404);
26221
- } catch (error) {
26222
- log23.error("session.rename-failed", { error: formatLogError(error) });
26223
- return c.json({ error: errorMessage(error, "Failed to rename session") }, sessionErrorStatus(error));
26224
- }
26225
- });
26226
26201
  session.post("/:id/title", async (c) => {
26227
26202
  const title = String((await c.req.json().catch(() => ({}))).title ?? "").trim();
26228
26203
  if (!title)
@@ -26248,7 +26223,7 @@ session.post("/:id/fork", async (c) => {
26248
26223
  title: forked.title
26249
26224
  }, 201);
26250
26225
  } catch (error) {
26251
- log23.error("session.fork-failed", { error: formatLogError(error) });
26226
+ log24.error("session.fork-failed", { error: formatLogError(error) });
26252
26227
  return c.json({ error: errorMessage(error, "Failed to fork session") }, sessionErrorStatus(error));
26253
26228
  }
26254
26229
  });
@@ -26280,7 +26255,7 @@ session.post("/:id/compact", compactBodyLimit, async (c) => {
26280
26255
  }
26281
26256
  const { instructions } = parsed;
26282
26257
  sendPrompt(id, instructions ? `/compact ${instructions}` : "/compact").catch((error) => {
26283
- log23.error("session.compact-failed", { error: formatLogError(error) });
26258
+ log24.error("session.compact-failed", { error: formatLogError(error) });
26284
26259
  });
26285
26260
  return c.json(instructions ? { status: "processing", instructions: "applied" } : { status: "processing" }, 202);
26286
26261
  });
@@ -26298,7 +26273,7 @@ session.post("/:id/rewind", async (c) => {
26298
26273
  const result = await rewindSessionFiles(id, messageId, dryRun);
26299
26274
  return c.json({ status: dryRun ? "previewed" : "rewound", result });
26300
26275
  } catch (error) {
26301
- log23.error("session.rewind-failed", { error: formatLogError(error) });
26276
+ log24.error("session.rewind-failed", { error: formatLogError(error) });
26302
26277
  return c.json({ error: errorMessage(error, "Failed to rewind session files") }, sessionErrorStatus(error));
26303
26278
  }
26304
26279
  });
@@ -26309,7 +26284,7 @@ session.post("/:id/tasks/:taskId/stop", async (c) => {
26309
26284
  return c.json({ status: "stopped" });
26310
26285
  return c.json({ error: stopped.message }, stopped.reason === "no_control_channel" ? 409 : 404);
26311
26286
  } catch (error) {
26312
- log23.error("task.stop-route-failed", { error: formatLogError(error) });
26287
+ log24.error("task.stop-route-failed", { error: formatLogError(error) });
26313
26288
  return c.json({ error: errorMessage(error, "Failed to stop background task") }, sessionErrorStatus(error));
26314
26289
  }
26315
26290
  });
@@ -26380,7 +26355,7 @@ session.post("/:id/questions/:questionId/answer", questionAnswerBodyLimit, async
26380
26355
  const pendingQuestions = getPendingQuestions(sessionId);
26381
26356
  const pendingQuestion = pendingQuestions.find((q) => q.id === questionId);
26382
26357
  if (!pendingQuestion) {
26383
- log23.info("question.stale", { questionId });
26358
+ log24.info("question.stale", { questionId });
26384
26359
  return c.json(stalePrompt("Question is no longer pending"), STALE_PROMPT_STATUS);
26385
26360
  }
26386
26361
  if (!isBoundedClaudeQuestionAnswers(answersArray, pendingQuestion.questions.length)) {
@@ -26391,7 +26366,7 @@ session.post("/:id/questions/:questionId/answer", questionAnswerBodyLimit, async
26391
26366
  const questionAnswers = answersArray[index] || [];
26392
26367
  answersRecord[q.question] = serializeClaudeQuestionAnswer(questionAnswers, q.multiSelect === true);
26393
26368
  });
26394
- log23.debug("question.answers-prepared", {
26369
+ log24.debug("question.answers-prepared", {
26395
26370
  questionId,
26396
26371
  questionCount: pendingQuestion.questions.length,
26397
26372
  answerCount: answersArray.reduce((count, answers) => count + answers.length, 0)
@@ -26403,7 +26378,7 @@ session.post("/:id/questions/:questionId/answer", questionAnswerBodyLimit, async
26403
26378
  return c.json(stalePrompt("Question is no longer pending"), STALE_PROMPT_STATUS);
26404
26379
  }
26405
26380
  } catch (error) {
26406
- log23.error("question.answer-failed", { error: formatLogError(error) });
26381
+ log24.error("question.answer-failed", { error: formatLogError(error) });
26407
26382
  return c.json({ error: error instanceof Error ? error.message : "Failed to answer question" }, 500);
26408
26383
  }
26409
26384
  });
@@ -26443,7 +26418,7 @@ session.post("/:id/plan-approvals/:approvalId/respond", planApprovalBodyLimit, a
26443
26418
  if (approved && (typeof pendingApproval.plan !== "string" || pendingApproval.plan.trim().length === 0 || pendingApproval.planTruncated === true)) {
26444
26419
  return c.json({ error: "A complete plan is required before approval", status: "rejected" }, 409);
26445
26420
  }
26446
- log23.info("plan-approval.response-received", {
26421
+ log24.info("plan-approval.response-received", {
26447
26422
  sessionId,
26448
26423
  approvalId,
26449
26424
  approved,
@@ -26456,7 +26431,7 @@ session.post("/:id/plan-approvals/:approvalId/respond", planApprovalBodyLimit, a
26456
26431
  return c.json(stalePrompt("Plan approval is no longer pending"), STALE_PROMPT_STATUS);
26457
26432
  }
26458
26433
  } catch (error) {
26459
- log23.error("plan-approval.response-failed", { error: formatLogError(error) });
26434
+ log24.error("plan-approval.response-failed", { error: formatLogError(error) });
26460
26435
  return c.json({ error: error instanceof Error ? error.message : "Failed to respond to plan approval" }, 500);
26461
26436
  }
26462
26437
  });
@@ -26855,7 +26830,7 @@ class EventRing {
26855
26830
  }
26856
26831
 
26857
26832
  // ../../bridges/claude-bridge/src/routes/events.ts
26858
- var log24 = createLogger("bridge.claude");
26833
+ var log25 = createLogger("bridge.claude");
26859
26834
  var serializedEvents = new WeakMap;
26860
26835
  function serializeEvent(event) {
26861
26836
  let serialized = serializedEvents.get(event);
@@ -27106,14 +27081,14 @@ function createEventsRouter(limits = {}) {
27106
27081
  events.get("/subscribe", (c) => {
27107
27082
  const origin = c.req.header("origin");
27108
27083
  const userAgent = c.req.header("user-agent");
27109
- log24.debug("sse.subscribe-requested", { origin, userAgent });
27084
+ log25.debug("sse.subscribe-requested", { origin, userAgent });
27110
27085
  return streamSSE(c, async (stream) => {
27111
27086
  const connectedAt = new Date().toISOString();
27112
- log24.debug("sse.opened", { connectedAt });
27087
+ log25.debug("sse.opened", { connectedAt });
27113
27088
  let isOpen = true;
27114
27089
  const closure = createSseConnectionClosure();
27115
27090
  const onRequestAbort = () => {
27116
- log24.debug("sse.aborted");
27091
+ log25.debug("sse.aborted");
27117
27092
  isOpen = false;
27118
27093
  closure.close();
27119
27094
  };
@@ -27127,7 +27102,7 @@ function createEventsRouter(limits = {}) {
27127
27102
  if (!isOpen)
27128
27103
  return;
27129
27104
  isOpen = false;
27130
- log24.info("sse.closed", { reason });
27105
+ log25.info("sse.closed", { reason });
27131
27106
  closure.close();
27132
27107
  };
27133
27108
  const writeFrame = createBoundedSseWriter(async (frame) => {
@@ -27178,7 +27153,7 @@ function createEventsRouter(limits = {}) {
27178
27153
  }
27179
27154
  writeFrame(frame).catch((error) => {
27180
27155
  if (!c.req.raw.signal.aborted) {
27181
- log24.warn("sse.write-failed", { error: formatLogError(error) });
27156
+ log25.warn("sse.write-failed", { error: formatLogError(error) });
27182
27157
  closeConnection("write failed");
27183
27158
  }
27184
27159
  });
@@ -27240,7 +27215,7 @@ function createEventsRouter(limits = {}) {
27240
27215
  data: JSON.stringify({ timestamp: new Date().toISOString() })
27241
27216
  }).catch((error) => {
27242
27217
  if (!c.req.raw.signal.aborted) {
27243
- log24.warn("sse.keepalive-failed", { error: formatLogError(error, { stack: false }) });
27218
+ log25.warn("sse.keepalive-failed", { error: formatLogError(error, { stack: false }) });
27244
27219
  closeConnection("keepalive failed");
27245
27220
  }
27246
27221
  });
@@ -27248,10 +27223,10 @@ function createEventsRouter(limits = {}) {
27248
27223
  await closure.closed;
27249
27224
  } catch (error) {
27250
27225
  if (!c.req.raw.signal.aborted) {
27251
- log24.warn("sse.handshake-failed", { error: formatLogError(error) });
27226
+ log25.warn("sse.handshake-failed", { error: formatLogError(error) });
27252
27227
  }
27253
27228
  } finally {
27254
- log24.debug("sse.cleanup");
27229
+ log25.debug("sse.cleanup");
27255
27230
  isOpen = false;
27256
27231
  c.req.raw.signal.removeEventListener("abort", onRequestAbort);
27257
27232
  if (keepaliveInterval)
@@ -27267,7 +27242,7 @@ var events = createEventsRouter();
27267
27242
  var events_default = events;
27268
27243
 
27269
27244
  // ../../bridges/claude-bridge/src/routes/mcp.ts
27270
- var log25 = createLogger("bridge.claude");
27245
+ var log26 = createLogger("bridge.claude");
27271
27246
  var mcp = new Hono2;
27272
27247
  mcp.get("/servers", async (c) => {
27273
27248
  try {
@@ -27278,14 +27253,14 @@ mcp.get("/servers", async (c) => {
27278
27253
  cwd
27279
27254
  });
27280
27255
  } catch (error) {
27281
- log25.error("mcp.read-failed", { error: formatLogError(error) });
27256
+ log26.error("mcp.read-failed", { error: formatLogError(error) });
27282
27257
  return c.json({ error: error instanceof Error ? error.message : "Failed to get MCP servers" }, 500);
27283
27258
  }
27284
27259
  });
27285
27260
  var mcp_default = mcp;
27286
27261
 
27287
27262
  // ../../bridges/claude-bridge/src/routes/plugins.ts
27288
- var log26 = createLogger("bridge.claude");
27263
+ var log27 = createLogger("bridge.claude");
27289
27264
  var plugins = new Hono2;
27290
27265
  plugins.get("/", async (c) => {
27291
27266
  try {
@@ -27296,7 +27271,7 @@ plugins.get("/", async (c) => {
27296
27271
  cwd
27297
27272
  });
27298
27273
  } catch (error) {
27299
- log26.error("plugins.read-failed", { error: formatLogError(error) });
27274
+ log27.error("plugins.read-failed", { error: formatLogError(error) });
27300
27275
  return c.json({ error: error instanceof Error ? error.message : "Failed to get plugins" }, 500);
27301
27276
  }
27302
27277
  });
@@ -27489,9 +27464,9 @@ function installFatalRejectionGuard(options) {
27489
27464
  }
27490
27465
 
27491
27466
  // ../protocol/src/node/process-failure-log.ts
27492
- var log27 = createLogger("process");
27467
+ var log28 = createLogger("process");
27493
27468
  function logUnhandledRejection(reason) {
27494
- log27.throttled("error", "rejection.unhandled", {
27469
+ log28.throttled("error", "rejection.unhandled", {
27495
27470
  error: reason,
27496
27471
  fields: () => ({ error: formatLogError(reason, { message: false }) })
27497
27472
  });
@@ -29170,7 +29145,7 @@ async function admitFetchBridgeRequest(authority, original, maxBodyBytes = BRIDG
29170
29145
  var BRIDGE_TOKEN_PREFIX = "okb_";
29171
29146
  var PR_SET_DUMPABLE = 4;
29172
29147
  var VERIFIER_PATTERN = /^[0-9a-f]{64}$/;
29173
- var log28 = createLogger("bridge.lifecycle");
29148
+ var log29 = createLogger("bridge.lifecycle");
29174
29149
  function mintBridgeToken() {
29175
29150
  return `${BRIDGE_TOKEN_PREFIX}${randomBytes3(32).toString("base64url")}`;
29176
29151
  }
@@ -29213,9 +29188,9 @@ function markProcessNonDumpable(loadFfi = () => createRequire2(import.meta.url)(
29213
29188
  } finally {
29214
29189
  libc.close();
29215
29190
  }
29216
- log28.warn("credential.not-hardened", { reason: "prctl-refused" });
29191
+ log29.warn("credential.not-hardened", { reason: "prctl-refused" });
29217
29192
  } catch {
29218
- log28.warn("credential.not-hardened", { reason: "ffi-unavailable" });
29193
+ log29.warn("credential.not-hardened", { reason: "ffi-unavailable" });
29219
29194
  }
29220
29195
  return false;
29221
29196
  }
@@ -29235,11 +29210,11 @@ function loadBridgeCredential(tokenEnv, options = {}) {
29235
29210
  }
29236
29211
 
29237
29212
  // ../../bridges/claude-bridge/src/index.ts
29238
- var log29 = createLogger("bridge.claude");
29213
+ var log30 = createLogger("bridge.claude");
29239
29214
  configureBridgeLogger();
29240
29215
  var app = new Hono2;
29241
29216
  app.onError((error, c) => {
29242
- log29.error("http.request-failed", {
29217
+ log30.error("http.request-failed", {
29243
29218
  method: c.req.method,
29244
29219
  path: c.req.path,
29245
29220
  error: formatLogError(error)
@@ -29247,7 +29222,6 @@ app.onError((error, c) => {
29247
29222
  return c.json({ error: "Internal Server Error" }, 500);
29248
29223
  });
29249
29224
  var BRIDGE_TOKEN_ENV = "CLAUDE_BRIDGE_TOKEN";
29250
- var BRIDGE_ALLOWED_ORIGINS_ENV = "CLAUDE_BRIDGE_ALLOWED_ORIGINS";
29251
29225
  var bridgeCredential = loadBridgeCredential(BRIDGE_TOKEN_ENV);
29252
29226
  process.env.ORKESTRATOR_NATIVE_AGENT_BRIDGE = "claude";
29253
29227
  var bridgeAuthEnabledOverrideForTesting = null;
@@ -29269,11 +29243,6 @@ function bearerToken(header) {
29269
29243
  function isTrustedBridgeOrigin(origin) {
29270
29244
  if (!origin)
29271
29245
  return true;
29272
- if (origin === "null" || origin === "file://")
29273
- return true;
29274
- const configured = (process.env[BRIDGE_ALLOWED_ORIGINS_ENV] ?? "").split(",").map((entry) => entry.trim().replace(/\/$/, "")).filter(Boolean);
29275
- if (configured.includes(origin.replace(/\/$/, "")))
29276
- return true;
29277
29246
  try {
29278
29247
  const parsed = new URL(origin);
29279
29248
  return (parsed.protocol === "http:" || parsed.protocol === "https:") && (parsed.hostname === "127.0.0.1" || parsed.hostname === "localhost" || parsed.hostname === "::1" || parsed.hostname === "[::1]");
@@ -29289,21 +29258,10 @@ app.use("*", async (c, next) => {
29289
29258
  if (!isTrustedBridgeOrigin(origin)) {
29290
29259
  return c.json({ error: "Origin is not allowed" }, 403);
29291
29260
  }
29292
- if (origin) {
29293
- c.header("Access-Control-Allow-Origin", origin);
29294
- c.header("Vary", "Origin");
29295
- }
29296
- if (c.req.method === "OPTIONS") {
29297
- c.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
29298
- c.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Orkestrator-Claude-Token");
29299
- c.header("Access-Control-Allow-Private-Network", "true");
29300
- return c.body(null, 204);
29301
- }
29302
29261
  if (isBridgeAuthEnabled() && !isPublicHealthRequest(c.req.method, c.req.path)) {
29303
29262
  const dedicatedHeaderToken = c.req.raw.headers.get("x-orkestrator-claude-token")?.trim();
29304
29263
  const headerToken = bearerToken(c.req.raw.headers.get("authorization") ?? undefined);
29305
- const eventToken = c.req.path === "/event/subscribe" ? c.req.query("token")?.trim() : undefined;
29306
- if (!tokenMatches(dedicatedHeaderToken) && !tokenMatches(headerToken) && !tokenMatches(eventToken)) {
29264
+ if (!tokenMatches(dedicatedHeaderToken) && !tokenMatches(headerToken)) {
29307
29265
  return c.json({ error: "Unauthorized" }, 401);
29308
29266
  }
29309
29267
  const admission = await admitFetchBridgeRequest(bridgeCredential.authority, c.req.raw);
@@ -29329,7 +29287,6 @@ app.use("/session/:id/transcript", compress({ encoding: "gzip" }));
29329
29287
  compressTranscriptReads(app);
29330
29288
  app.get("/global/auth-check", (c) => c.json({ status: "ok" }));
29331
29289
  app.get("/global/auth", async (c) => c.json(await readClaudeAuthStatus()));
29332
- app.get("/global/usage", async (c) => c.json({ account: await readClaudePlanUsage() }));
29333
29290
  app.post("/global/auth/login", (c) => c.json({ error: "Claude signs in from the sign-in card in its tab or from Settings → Claude." }, 405));
29334
29291
  app.post("/global/auth/logout", (c) => c.json({ error: "Claude sign-out is available from a terminal tab." }, 405));
29335
29292
  app.post("/global/refresh-catalog", async (c) => {
@@ -29368,7 +29325,7 @@ if (parentPid !== null) {
29368
29325
  startParentWatchdog({
29369
29326
  parentPid,
29370
29327
  onParentExit: () => {
29371
- log29.warn("parent.gone", { parentPid });
29328
+ log30.warn("parent.gone", { parentPid });
29372
29329
  process.exit(0);
29373
29330
  }
29374
29331
  });
@@ -29379,13 +29336,13 @@ function startBridgeServer(env = process.env, start = serve) {
29379
29336
  }
29380
29337
  const port = parseInt(env.PORT || "4097", 10);
29381
29338
  const hostname = env.HOSTNAME || "0.0.0.0";
29382
- log29.debug("server.starting", { hostname, port });
29339
+ log30.debug("server.starting", { hostname, port });
29383
29340
  const server = start({
29384
29341
  fetch: app.fetch,
29385
29342
  port,
29386
29343
  hostname
29387
29344
  });
29388
- log29.info("server.listening", { hostname, port });
29345
+ log30.info("server.listening", { hostname, port });
29389
29346
  return server;
29390
29347
  }
29391
29348
  var __testing = {