@chroxy/server 0.11.10 → 0.11.11

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.
Files changed (153) hide show
  1. package/CONFIG.md +4 -2
  2. package/package.json +3 -3
  3. package/src/acp-session.js +5 -1
  4. package/src/agent-connections.js +12 -1
  5. package/src/agent-control/client.js +29 -0
  6. package/src/agent-control/events.js +8 -4
  7. package/src/agent-control/local-connection.js +34 -16
  8. package/src/agent-control/mcp-server.js +2 -0
  9. package/src/anthropic-compatible-config.js +1 -0
  10. package/src/anthropic-gemini-shim.js +444 -0
  11. package/src/anthropic-gemini-translate.js +1030 -0
  12. package/src/base-session.js +319 -2
  13. package/src/bound-client-policy.js +12 -0
  14. package/src/byok-mcp-config.js +9 -5
  15. package/src/byok-mcp-trust.js +34 -20
  16. package/src/byok-session.js +62 -9
  17. package/src/byok-tool-executor.js +81 -1
  18. package/src/claude-setting-sources.js +74 -0
  19. package/src/claude-tui/pty-driver.js +5 -1
  20. package/src/claude-tui/usage-limit.js +2 -2
  21. package/src/claude-tui-session.js +57 -4
  22. package/src/cli/agent-cmd.js +236 -0
  23. package/src/cli/connection-state.js +54 -0
  24. package/src/cli/freshness-cmd.js +53 -0
  25. package/src/cli/pages-cmd.js +6 -4
  26. package/src/cli/pair-code-cmd.js +7 -6
  27. package/src/cli/pair-discord-cmd.js +7 -6
  28. package/src/cli/schedule-cmd.js +25 -3
  29. package/src/cli/server-cmd.js +6 -0
  30. package/src/cli/shell-cmd.js +7 -4
  31. package/src/cli/status-cmd.js +19 -5
  32. package/src/cli-session.js +190 -11
  33. package/src/cli.js +4 -0
  34. package/src/codex-app-server-session.js +78 -17
  35. package/src/codex-error-text.js +114 -0
  36. package/src/config-dir-migration.js +11 -6
  37. package/src/config.js +23 -3
  38. package/src/connection-info.js +73 -14
  39. package/src/continuations.js +153 -40
  40. package/src/conversation-scanner.js +2 -21
  41. package/src/conversation-search.js +4 -17
  42. package/src/dev-preview.js +2 -1
  43. package/src/docker-session.js +10 -1
  44. package/src/doctor.js +14 -3
  45. package/src/durable-write.js +35 -0
  46. package/src/environments/authority.js +7 -1
  47. package/src/event-normalizer.js +35 -2
  48. package/src/folder-trust-wire.js +137 -0
  49. package/src/folder-trust-worker.js +17 -0
  50. package/src/folder-trust.js +1572 -0
  51. package/src/freshness/activity-meter.js +101 -0
  52. package/src/freshness/adapter.js +199 -0
  53. package/src/freshness/checks.js +239 -0
  54. package/src/freshness/config.js +98 -0
  55. package/src/freshness/core.js +185 -0
  56. package/src/freshness/derive.js +680 -0
  57. package/src/freshness/exchange.js +305 -0
  58. package/src/freshness/file-ledger.js +400 -0
  59. package/src/freshness/grade.js +81 -0
  60. package/src/freshness/hash.js +45 -0
  61. package/src/freshness/inbox.js +163 -0
  62. package/src/freshness/index.js +20 -0
  63. package/src/freshness/investigation.js +474 -0
  64. package/src/freshness/keys.js +177 -0
  65. package/src/freshness/ledger.js +122 -0
  66. package/src/freshness/outbox.js +131 -0
  67. package/src/freshness/policy.js +599 -0
  68. package/src/freshness/queue.js +843 -0
  69. package/src/freshness/read-errors.js +23 -0
  70. package/src/freshness/render.js +153 -0
  71. package/src/freshness/runtime.js +113 -0
  72. package/src/freshness/session-registry-adapter.js +161 -0
  73. package/src/freshness/state-file-adapter.js +167 -0
  74. package/src/freshness-runner/build-info.js +139 -0
  75. package/src/freshness-runner/cli.js +105 -0
  76. package/src/freshness-runner/run-tick.js +109 -0
  77. package/src/freshness-runner/stamp.js +57 -0
  78. package/src/freshness-sources/claude-transcript-adapter.js +211 -0
  79. package/src/freshness-sources/codex-transcript-adapter.js +33 -0
  80. package/src/freshness-sources/index.js +8 -0
  81. package/src/gemini-byok-session.js +292 -0
  82. package/src/gemini-credentials.js +67 -0
  83. package/src/gemini-key-safety.js +246 -0
  84. package/src/gemini-models.js +386 -0
  85. package/src/handler-utils.js +6 -13
  86. package/src/handlers/checkpoint-handlers.js +8 -0
  87. package/src/handlers/folder-trust-handlers.js +90 -0
  88. package/src/handlers/input-handlers.js +40 -11
  89. package/src/handlers/principal-admin-handlers.js +229 -0
  90. package/src/handlers/principal-handlers.js +262 -0
  91. package/src/handlers/scheduler-handlers.js +4 -4
  92. package/src/handlers/session-handlers.js +10 -1
  93. package/src/handlers/settings-handlers.js +42 -8
  94. package/src/handlers/skills-handlers.js +7 -0
  95. package/src/history-page.js +8 -0
  96. package/src/jsonl-reader.js +90 -10
  97. package/src/jsonl-subprocess-session.js +4 -1
  98. package/src/logger.js +105 -15
  99. package/src/mailbox-route.js +102 -0
  100. package/src/notification-prefs.js +15 -0
  101. package/src/orchestration/orchestration-manager.js +38 -9
  102. package/src/orchestration/permission-gate.js +4 -1
  103. package/src/orchestration/run-record.js +11 -0
  104. package/src/orchestration/turn-driver.js +151 -33
  105. package/src/orphan-reaper.js +77 -20
  106. package/src/outgoing-policy.js +10 -4
  107. package/src/permission-floor.js +54 -2
  108. package/src/permission-manager.js +32 -13
  109. package/src/permission-resolved-by.js +89 -0
  110. package/src/permission-resolver.js +7 -3
  111. package/src/platform.js +156 -4
  112. package/src/principal-audit.js +189 -0
  113. package/src/principal-binding.js +25 -0
  114. package/src/principal-brakes.js +21 -0
  115. package/src/principal-effect.js +101 -0
  116. package/src/principal-journal.js +905 -0
  117. package/src/principal-kill-switch.js +183 -0
  118. package/src/principal-label.js +5 -0
  119. package/src/principal-pending-permissions.js +177 -0
  120. package/src/principal-policy.js +1094 -0
  121. package/src/principal-sessions-snapshot.js +208 -0
  122. package/src/principal-store.js +488 -0
  123. package/src/principal-subscriptions.js +283 -0
  124. package/src/providers.js +2 -0
  125. package/src/redaction.js +181 -22
  126. package/src/scheduled-task-store.js +12 -0
  127. package/src/scheduler.js +304 -17
  128. package/src/sdk-session.js +60 -7
  129. package/src/server-cli/push-notification-handler.js +6 -1
  130. package/src/server-cli.js +30 -1
  131. package/src/session-ci-watcher.js +210 -37
  132. package/src/session-manager.js +590 -19
  133. package/src/session-message-history.js +121 -2
  134. package/src/session-name-allocator.js +685 -0
  135. package/src/statusline.js +78 -19
  136. package/src/summarize-session.js +2 -0
  137. package/src/turn-outcome.js +5 -2
  138. package/src/utils/argv-safety.js +29 -0
  139. package/src/utils/binary-package-manifest.js +57 -15
  140. package/src/utils/bounded-regex-worker.js +4 -0
  141. package/src/utils/bounded-regex.js +16 -7
  142. package/src/utils/pid-liveness.js +47 -0
  143. package/src/web-task-manager.js +45 -4
  144. package/src/worktree-gc.js +195 -4
  145. package/src/ws-auth.js +103 -19
  146. package/src/ws-broadcaster.js +39 -7
  147. package/src/ws-client-manager.js +8 -0
  148. package/src/ws-file-ops/browser.js +35 -3
  149. package/src/ws-forwarding.js +23 -3
  150. package/src/ws-handler-context.js +18 -0
  151. package/src/ws-history.js +79 -12
  152. package/src/ws-message-handlers.js +10 -2
  153. package/src/ws-server.js +253 -13
@@ -17,7 +17,7 @@
17
17
  import Anthropic, { APIUserAbortError } from '@anthropic-ai/sdk'
18
18
  import { assertAuthorized, stillAuthorized } from './connection-authority.js'
19
19
  import { performance } from 'node:perf_hooks'
20
- import { BaseSession, buildBaseSessionOpts, reportInputAdmission } from './base-session.js'
20
+ import { BaseSession, buildBaseSessionOpts, reportInputAdmission, NOT_ADMITTED_ADMISSION } from './base-session.js'
21
21
  import { BYOK_CUSTOMIZATION } from './provider-customization.js'
22
22
  import { loadByokInstructionPolicy } from './instruction-policy.js'
23
23
  import { synthesizeModelUsage } from './usage-normalize.js'
@@ -619,6 +619,10 @@ export class ClaudeByokSession extends BaseSession {
619
619
  return getModelPricing(model)
620
620
  }
621
621
 
622
+ _buildStreamParams(params) {
623
+ return params
624
+ }
625
+
622
626
  /**
623
627
  * #7012: lazily construct + start the MCP fleet from whatever is currently in
624
628
  * `_mcpServerConfigs`, exactly once. Extracted out of `start()` (which was the
@@ -1161,6 +1165,14 @@ export class ClaudeByokSession extends BaseSession {
1161
1165
  })
1162
1166
  return
1163
1167
  }
1168
+ // #9242: the expansion is an await; re-ask admission before the marker, the
1169
+ // history entry and the stream. Refused: no dispatch, queued follow-ups go on.
1170
+ if (!this._admitPreparedSend(sendOptions)) {
1171
+ this._isBusy = false
1172
+ this._permissions.clearUserStopInFlight()
1173
+ reportInputAdmission(sendOptions, NOT_ADMITTED_ADMISSION)
1174
+ return
1175
+ }
1164
1176
  } catch (err) {
1165
1177
  this._isBusy = false
1166
1178
  this._permissions.clearUserStopInFlight() // #8430: this turn ends here, off the _finishTurn path
@@ -1297,7 +1309,7 @@ export class ClaudeByokSession extends BaseSession {
1297
1309
  let stream
1298
1310
  try {
1299
1311
  stream = this._client.messages.stream(
1300
- {
1312
+ this._buildStreamParams({
1301
1313
  model: this.model || this._defaultModel,
1302
1314
  max_tokens: DEFAULT_MAX_TOKENS,
1303
1315
  ...(systemPrompt ? { system: systemPrompt } : {}),
@@ -1307,7 +1319,7 @@ export class ClaudeByokSession extends BaseSession {
1307
1319
  // turn without anything to invalidate.
1308
1320
  tools: this._buildTools(),
1309
1321
  messages: this._history,
1310
- },
1322
+ }),
1311
1323
  { signal: this._abortController.signal },
1312
1324
  )
1313
1325
  } catch (err) {
@@ -1646,7 +1658,7 @@ export class ClaudeByokSession extends BaseSession {
1646
1658
  let summaryStream
1647
1659
  try {
1648
1660
  summaryStream = this._client.messages.stream(
1649
- {
1661
+ this._buildStreamParams({
1650
1662
  model: this.model || this._defaultModel,
1651
1663
  max_tokens: DEFAULT_MAX_TOKENS,
1652
1664
  ...(systemPrompt ? { system: systemPrompt } : {}),
@@ -1654,7 +1666,7 @@ export class ClaudeByokSession extends BaseSession {
1654
1666
  // tried to tool_use, the API would reject (no tools to
1655
1667
  // dispatch to). Cleaner to just omit.
1656
1668
  messages: this._history,
1657
- },
1669
+ }),
1658
1670
  { signal: this._abortController.signal },
1659
1671
  )
1660
1672
  } catch (err) {
@@ -1742,6 +1754,7 @@ export class ClaudeByokSession extends BaseSession {
1742
1754
  lastStopReason,
1743
1755
  toolRoundCapReached,
1744
1756
  interrupted: stoppedInToolPhase,
1757
+ stopRequested: stoppedInToolPhase, // #9241: the tool-phase abort IS the Stop
1745
1758
  turnStartedAt,
1746
1759
  turnUsage,
1747
1760
  turnCost,
@@ -1804,6 +1817,8 @@ export class ClaudeByokSession extends BaseSession {
1804
1817
  lastStopReason,
1805
1818
  toolRoundCapReached,
1806
1819
  interrupted: true,
1820
+ // #9241: only an abort is the Stop; any other error that raced it is not
1821
+ stopRequested: ClaudeByokSession._isGenuineAbort(err),
1807
1822
  turnStartedAt,
1808
1823
  turnUsage,
1809
1824
  turnCost,
@@ -2787,7 +2802,7 @@ export class ClaudeByokSession extends BaseSession {
2787
2802
  * PermissionManager which resolves the pending Promise in
2788
2803
  * handlePermission() above.
2789
2804
  */
2790
- respondToPermission(requestId, decision, editedInput, reason, scope) {
2805
+ respondToPermission(requestId, decision, editedInput, reason, scope, resolvedBy) {
2791
2806
  // #5056: if this requestId belongs to a Task subagent (its pending
2792
2807
  // entry lives in the CHILD's PermissionManager, not ours), forward
2793
2808
  // the decision to that child. ws-permissions only ever calls the
@@ -2801,7 +2816,7 @@ export class ClaudeByokSession extends BaseSession {
2801
2816
  // #6543: forward the operator's per-hunk editedInput to the child too.
2802
2817
  // #6773: the deny `reason` forwards to the child as well.
2803
2818
  // #8517: so does the session-scope label.
2804
- const resolved = child.respondToPermission(requestId, decision, editedInput, reason, scope)
2819
+ const resolved = child.respondToPermission(requestId, decision, editedInput, reason, scope, resolvedBy)
2805
2820
  // Drop the routing entry once the child has taken the response, so a
2806
2821
  // duplicate/late response can't re-resolve a stale id. The child also emits
2807
2822
  // permission_resolved which our relay listener uses to clear the same entry
@@ -2813,7 +2828,7 @@ export class ClaudeByokSession extends BaseSession {
2813
2828
  this._subagentPermissionRouting.delete(requestId)
2814
2829
  return resolved
2815
2830
  }
2816
- return this._permissions.respondToPermission(requestId, decision, editedInput, reason, scope)
2831
+ return this._permissions.respondToPermission(requestId, decision, editedInput, reason, scope, resolvedBy)
2817
2832
  }
2818
2833
 
2819
2834
  /**
@@ -2870,7 +2885,7 @@ export class ClaudeByokSession extends BaseSession {
2870
2885
  * `stopped` when the Stop was requested. Emits `stream_end` first.
2871
2886
  */
2872
2887
  _emitTurnResult({
2873
- messageId, lastStopReason, toolRoundCapReached, interrupted,
2888
+ messageId, lastStopReason, toolRoundCapReached, interrupted, stopRequested = false,
2874
2889
  turnStartedAt, turnUsage, turnCost, turnCostKnown, finalRoundOccupancy,
2875
2890
  }) {
2876
2891
  this.emit('stream_end', { messageId })
@@ -2883,6 +2898,7 @@ export class ClaudeByokSession extends BaseSession {
2883
2898
  ...turnOutcomeField(outcomeFromByokTurn({ stopReason: lastStopReason, toolRoundCapReached, interrupted })),
2884
2899
  // #7072: terminal but not successful (internal; not on the wire).
2885
2900
  ...(interrupted ? { interrupted: true } : {}),
2901
+ ...(stopRequested ? { stopRequested: true } : {}), // #9241 (internal; stripped by BaseSession.emit)
2886
2902
  duration: Date.now() - turnStartedAt,
2887
2903
  usage: turnUsage,
2888
2904
  ...(finalRoundOccupancy ? { contextOccupancy: finalRoundOccupancy } : {}),
@@ -2904,11 +2920,48 @@ export class ClaudeByokSession extends BaseSession {
2904
2920
 
2905
2921
  /** True when `err` is the abort of an in-flight stream (see _emitTurnError). */
2906
2922
  _isAbortError(err) {
2923
+ // #9266: an aborted controller used to make ANY error an abort, so an
2924
+ // upstream HTTP 500 that raced a Stop ended as a quiet stopped turn and the
2925
+ // error was never shown. Now an error carrying evidence that it came from
2926
+ // upstream (an SDK APIError with an HTTP status, or an SSE `error` body) is
2927
+ // surfaced even after the Stop. Once the signal IS aborted, every other
2928
+ // error is treated as the Stop's own fallout: the shapes the SDK/undici throw
2929
+ // BECAUSE of the abort (an abort on the `cause` chain, or a bare `terminated`/
2930
+ // connection error with no status, incl. APIConnectionTimeoutError) are
2931
+ // deliberately quiet, so a real Stop never shows a spurious error. With no
2932
+ // Stop, only the error's own top-level abort shape counts (pre-#9266).
2933
+ if (ClaudeByokSession._isUpstreamError(err)) return false
2907
2934
  return err instanceof APIUserAbortError ||
2908
2935
  err?.name === 'AbortError' ||
2909
2936
  !!this._abortController?.signal?.aborted
2910
2937
  }
2911
2938
 
2939
+ /**
2940
+ * #9266: the error itself says it is an abort: the SDK's APIUserAbortError, a
2941
+ * fetch/DOMException `AbortError`, or either of those anywhere on its `cause`
2942
+ * chain (undici's `terminated` and the SDK's AnthropicError/APIConnectionError
2943
+ * wrappers carry the abort as `cause`). No signal state is consulted.
2944
+ */
2945
+ static _isGenuineAbort(err) {
2946
+ for (let e = err, depth = 0; e && depth < 5; e = e.cause, depth++) {
2947
+ if (e instanceof APIUserAbortError || e.name === 'AbortError') return true
2948
+ }
2949
+ return false
2950
+ }
2951
+
2952
+ /**
2953
+ * #9266: evidence that `err` is a real upstream response, independent of any
2954
+ * abort: an HTTP status, or the body of an SSE `error` event (the SDK keeps it
2955
+ * as the parsed object, or as the raw string when it is not JSON).
2956
+ */
2957
+ static _isUpstreamError(err) {
2958
+ if (ClaudeByokSession._isGenuineAbort(err)) return false
2959
+ if (Number.isInteger(err?.status)) return true
2960
+ const body = err?.error
2961
+ return (body != null && typeof body === 'object') ||
2962
+ (typeof body === 'string' && body.length > 0)
2963
+ }
2964
+
2912
2965
  /**
2913
2966
  * #8553: did somebody ASK for the abort `err` reports? True only for an abort
2914
2967
  * that came through interrupt() (the user, the scheduler, the orchestration
@@ -21,6 +21,7 @@
21
21
  import { join, resolve } from 'node:path'
22
22
  import { opendir, lstat, realpath, readlink } from 'node:fs/promises'
23
23
  import { constants as fsConstants } from 'node:fs'
24
+ import { createLogger } from './logger.js'
24
25
  import { isIP } from 'node:net'
25
26
  import { lookup as dnsLookup } from 'node:dns/promises'
26
27
  import { validateRawPathWithinCwd, resolveSessionCwd } from './ws-file-ops/common.js'
@@ -126,6 +127,8 @@ function globTimeoutMs() {
126
127
  return n > 0 ? n : GLOB_TIMEOUT_DEFAULT_MS
127
128
  }
128
129
 
130
+ const log = createLogger('byok-tool-executor')
131
+
129
132
  /**
130
133
  * #7356 — a cap on how many Glob walks run at once, DAEMON-WIDE.
131
134
  *
@@ -152,7 +155,58 @@ function globMaxConcurrent() {
152
155
  const n = Number(raw)
153
156
  return n > 0 ? n : GLOB_MAX_CONCURRENT_DEFAULT
154
157
  }
155
- const globWalkSlots = { active: 0, queue: [] }
158
+ const globWalkSlots = { active: 0, queue: [], capSince: null, lastWarnAt: null, lastLimit: Infinity }
159
+
160
+ // Test-only: awaited inside a walk right after it starts, so a test can park a
161
+ // started walk deterministically (no timing race against a real directory walk).
162
+ let globWalkStartHook = null
163
+ function __setGlobWalkStartHookForTest(fn) {
164
+ globWalkStartHook = fn || null
165
+ }
166
+
167
+ // #8349 — the limiter's clock, injectable so the stuck-at-cap check is proven
168
+ // without waiting real deadlines. null restores Date.now.
169
+ let globLimiterNow = Date.now
170
+ function __setGlobLimiterClockForTest(fn) {
171
+ globLimiterNow = fn || Date.now
172
+ }
173
+
174
+ // Track how long the limiter has sat at its cap with no slot handed back. A
175
+ // release is progress, so it clears the clock; the pump (or a grant) that
176
+ // refills the cap restarts it.
177
+ function noteGlobCapState(limit) {
178
+ if (globWalkSlots.active >= limit) {
179
+ if (globWalkSlots.capSince === null) globWalkSlots.capSince = globLimiterNow()
180
+ } else {
181
+ globWalkSlots.capSince = null
182
+ }
183
+ }
184
+
185
+ /**
186
+ * #8349 — a walk stuck inside an awaited opendir/readdir (hung mount, FUSE)
187
+ * never sees `state.stop`, so its slot is never returned and the cap turns one
188
+ * hung call into a daemon-wide Glob outage. Log one warning when the limiter
189
+ * has been full, with no slot released, for more than a few deadlines, and at
190
+ * most once per that interval. Returns whether it warned. It is only evaluated
191
+ * when a queued Glob times out, so a stuck cap with no further Glob calls is
192
+ * silent (no timer polls it). The slot is NOT
193
+ * force-released: the hung walk still holds a directory handle and a libuv
194
+ * pool thread, so freeing its slot would let new walks oversubscribe exactly
195
+ * the resource the cap protects.
196
+ */
197
+ const GLOB_STUCK_DEADLINE_MULTIPLE = 3
198
+ function warnIfGlobWalksStuck(deadlineMs, warn = (m) => log.warn(m)) {
199
+ const { capSince, active } = globWalkSlots
200
+ if (capSince === null) return false
201
+ const now = globLimiterNow()
202
+ const threshold = GLOB_STUCK_DEADLINE_MULTIPLE * deadlineMs
203
+ if (now - capSince <= threshold) return false
204
+ if (globWalkSlots.lastWarnAt !== null && now - globWalkSlots.lastWarnAt <= threshold) return false
205
+ globWalkSlots.lastWarnAt = now
206
+ warn(`${active} Glob walks have held every walk slot for ${Math.round((now - capSince) / 1000)}s without returning; ` +
207
+ 'later Globs will time out waiting for a slot until one returns (a hung mount or blocked device?)')
208
+ return true
209
+ }
156
210
 
157
211
  function pumpGlobWalkSlots() {
158
212
  while (globWalkSlots.queue.length > 0 && globWalkSlots.active < globWalkSlots.queue[0].limit) {
@@ -160,6 +214,9 @@ function pumpGlobWalkSlots() {
160
214
  globWalkSlots.active++
161
215
  waiter.resolve(makeGlobSlotRelease())
162
216
  }
217
+ // Unconditional: a release followed by a grant that refills the cap with an
218
+ // empty queue must restart the stuck clock too.
219
+ noteGlobCapState(globWalkSlots.lastLimit)
163
220
  }
164
221
 
165
222
  function makeGlobSlotRelease() {
@@ -168,6 +225,8 @@ function makeGlobSlotRelease() {
168
225
  if (released) return
169
226
  released = true
170
227
  globWalkSlots.active--
228
+ globWalkSlots.capSince = null // a slot came back: progress, and the next stuck episode warns afresh
229
+ globWalkSlots.lastWarnAt = null
171
230
  pumpGlobWalkSlots()
172
231
  }
173
232
  }
@@ -179,13 +238,16 @@ function makeGlobSlotRelease() {
179
238
  * observes `state.stop` itself and releases in its own `finally`).
180
239
  */
181
240
  function acquireGlobWalkSlot(limit) {
241
+ globWalkSlots.lastLimit = limit
182
242
  let waiter = null
183
243
  const granted = new Promise((resolve) => {
184
244
  if (globWalkSlots.active < limit) {
185
245
  globWalkSlots.active++
246
+ noteGlobCapState(limit)
186
247
  resolve(makeGlobSlotRelease())
187
248
  return
188
249
  }
250
+ noteGlobCapState(limit)
189
251
  waiter = { limit, resolve }
190
252
  globWalkSlots.queue.push(waiter)
191
253
  })
@@ -665,9 +727,17 @@ async function runGlob({ input, cwd, cwdRealCache, cwdCacheTtl, signal }) {
665
727
  // against this call's budget; a call that times out or is aborted while
666
728
  // still queued is dequeued below and never starts a walk.
667
729
  const slot = acquireGlobWalkSlot(globMaxConcurrent())
730
+ // #8349 — whether this call's walk ever got a slot. A timeout with no slot
731
+ // was spent queued behind other walks, which is not the same as a slow walk.
732
+ let walkStarted = false
668
733
  async function collectAll() {
669
734
  const release = await slot.granted
670
735
  if (release === null) return
736
+ // Known, unreachable-in-practice edge: a slot granted after the deadline
737
+ // already fired is not "started" (the loop below returns at once and the
738
+ // late grant releases in `finally`), so such a call keeps the queued message.
739
+ if (state.stop === null) walkStarted = true
740
+ if (walkStarted && globWalkStartHook) await globWalkStartHook()
671
741
  try {
672
742
  for (const p of patterns) {
673
743
  if (state.stop !== null || files.length >= GLOB_COLLECT_CEILING) return
@@ -696,6 +766,13 @@ async function runGlob({ input, cwd, cwdRealCache, cwdCacheTtl, signal }) {
696
766
  return { content: `Glob failed: ${walkError?.message || String(walkError)}`, isError: true }
697
767
  }
698
768
  if (state.stop === 'timed out') {
769
+ if (!walkStarted) {
770
+ warnIfGlobWalksStuck(timeoutMs)
771
+ return {
772
+ content: `Glob timed out after ${timeoutMs}ms (waited ${timeoutMs}ms for a free walk slot; ${globWalkSlots.active} ${globWalkSlots.active === 1 ? 'walk was' : 'walks were'} busy)`,
773
+ isError: true,
774
+ }
775
+ }
699
776
  return { content: `Glob timed out after ${timeoutMs}ms`, isError: true }
700
777
  }
701
778
  if (state.stop === 'interrupted') return { content: 'Glob interrupted', isError: true }
@@ -3447,6 +3524,9 @@ export {
3447
3524
  walkGlob,
3448
3525
  acquireGlobWalkSlot,
3449
3526
  globWalkSlotStats,
3527
+ warnIfGlobWalksStuck,
3528
+ __setGlobLimiterClockForTest,
3529
+ __setGlobWalkStartHookForTest,
3450
3530
  expandBraces,
3451
3531
  GLOB_BRACE_EXPANSION_CAP,
3452
3532
  parseRangeGroup,
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Which Claude settings scopes a chroxy-launched Claude process may load.
3
+ *
4
+ * This is the one place that decision is made. Every launch path (SDK, CLI,
5
+ * claude-tui, web tasks) and the status-line reader go through it.
6
+ *
7
+ * The user's own settings (`~/.claude`, or `CLAUDE_CONFIG_DIR`) are always used.
8
+ * Settings that live in the session's working directory (`.mcp.json`,
9
+ * `.claude/settings.json`, project `CLAUDE.md`, skills, agents, commands) are
10
+ * loaded only after the owner trusted the folder (folder-trust.js); every folder
11
+ * starts untrusted. Any change to the listed files makes the folder untrusted
12
+ * again until it is re-approved. The `local` scope
13
+ * (`.claude/settings.local.json`) is never included, whatever the folder's state.
14
+ *
15
+ * With no `cwd` the answer is "not allowed".
16
+ */
17
+
18
+ import { getFolderTrustStateForLaunch, loadFolderTrustRecords, resolveRealPath } from './folder-trust.js'
19
+
20
+ /**
21
+ * Setting-source names for a project-settings decision already taken.
22
+ * @param {boolean} allowed
23
+ * @returns {string[]}
24
+ */
25
+ export function claudeSettingSourcesFor(allowed) {
26
+ return allowed ? ['user', 'project'] : ['user']
27
+ }
28
+
29
+ /**
30
+ * The same, as the value of the CLI's `--setting-sources` flag.
31
+ * @param {boolean} allowed
32
+ * @returns {string}
33
+ */
34
+ export function claudeSettingSourcesValueFor(allowed) {
35
+ return claudeSettingSourcesFor(allowed).join(',')
36
+ }
37
+
38
+ /**
39
+ * Decide, without any scan, a folder that cannot be trusted: no folder, one that
40
+ * cannot be resolved, or one with no trust record (whatever a scan would find, it is
41
+ * untrusted, so the common case answers without walking the folder).
42
+ * @param {string} [cwd] - session working directory
43
+ * @returns {false|null} `false` when decided untrusted, `null` when a scan must decide
44
+ */
45
+ export function projectSettingsDecidedWithoutScan(cwd) {
46
+ if (typeof cwd !== 'string' || cwd === '') return false
47
+ const real = resolveRealPath(cwd)
48
+ if (real.error) return false
49
+ if (!loadFolderTrustRecords().some((r) => r.path === real.path)) return false
50
+ return null
51
+ }
52
+
53
+ /**
54
+ * May settings files in `cwd` (project scope) be read or executed? True ONLY when
55
+ * the owner trusted the folder and its files are still the ones they approved.
56
+ * There is no implicit rule: a folder with nothing command-bearing is untrusted
57
+ * until it is trusted too.
58
+ *
59
+ * This is the launch decision. A folder with no record is decided at once. For a
60
+ * recorded folder the files are scanned as they are NOW, in a worker thread, by a
61
+ * scan started for this call: never the display cache, never a scan another caller
62
+ * started. Any error, timeout or incomplete scan is "not allowed".
63
+ * @param {string} [cwd] - session working directory
64
+ * @returns {Promise<boolean>}
65
+ */
66
+ export async function projectSettingsAllowedAsync(cwd) {
67
+ const decided = projectSettingsDecidedWithoutScan(cwd)
68
+ if (decided !== null) return decided
69
+ try {
70
+ return (await getFolderTrustStateForLaunch(cwd)).status === 'trusted'
71
+ } catch {
72
+ return false
73
+ }
74
+ }
@@ -330,7 +330,7 @@ export function ensureCwdTrusted(cwd, env = process.env) {
330
330
  // Legacy sessions write this once at start. Explicit native connections rewrite
331
331
  // it before every spawn/respawn so the SessionStart route marker carries a fresh
332
332
  // nonce. The file remains stable across turns within one PTY process.
333
- export function writeHookSettings(sinkDir, { permissionsEnabled, nativeRouteNonce = null, permissionHookScript = PERMISSION_HOOK_SCRIPT, thinkingSummaries = false }) {
333
+ export function writeHookSettings(sinkDir, { permissionsEnabled, nativeRouteNonce = null, permissionHookScript = PERMISSION_HOOK_SCRIPT, thinkingSummaries = false, enableAllProjectMcpServers = false }) {
334
334
  const settingsPath = join(sinkDir, 'settings.json')
335
335
  const sinkDirEsc = JSON.stringify(sinkDir)
336
336
  // Portable unique-id source for hook filenames — see the UUID note above.
@@ -369,6 +369,10 @@ export function writeHookSettings(sinkDir, { permissionsEnabled, nativeRouteNonc
369
369
  // is for, and the --settings file outranks the user's own settings.json, so
370
370
  // chroxy's choice is the one that applies to a chroxy-owned TUI.
371
371
  ...(thinkingSummaries ? { showThinkingSummaries: true } : {}),
372
+ // Interactive claude asks for approval of each `.mcp.json` server and blocks
373
+ // the PTY on that dialog. The owner's folder-trust decision replaces it, so
374
+ // this is written ONLY when project settings are allowed for the folder.
375
+ ...(enableAllProjectMcpServers ? { enableAllProjectMcpServers: true } : {}),
372
376
  hooks: {
373
377
  ...(nativeRouteNonce ? {
374
378
  SessionStart: [
@@ -188,8 +188,8 @@ export function classifyUsageLimit(text, { structured = false } = {}) {
188
188
  kind: 'credits',
189
189
  code: USAGE_LIMIT_CODE,
190
190
  resetsAt: null,
191
- message: 'Claude cannot run this model without usage credits. Switch to another model, or add usage credits, then send your message again.',
192
- repeatMessage: 'Still no usage credits for this model \u2014 switch to another model or add usage credits.',
191
+ message: 'Usage limit: Claude cannot run this model without usage credits. Switch to another model, or add usage credits, then send your message again.',
192
+ repeatMessage: 'Usage limit: Still no usage credits for this model \u2014 switch to another model or add usage credits.',
193
193
  episodeKey: 'credits|',
194
194
  }
195
195
  }
@@ -71,6 +71,7 @@ import {
71
71
  } from './background-shells.js'
72
72
  import { normalizeClaudeTuiToolResponse } from './claude-tui-tool-response.js'
73
73
  import { scrubTerminalText } from './claude-tui/diagnostic-tail.js'
74
+ import { claudeSettingSourcesValueFor, projectSettingsAllowedAsync } from './claude-setting-sources.js'
74
75
  // #5559 — PTY-write / paste-throttle layer + interactive-form driver carved out
75
76
  // into focused modules. The empirically-pinned helpers, constants and methods
76
77
  // are moved byte-identically; the *Mixin classes carry the write/form methods,
@@ -201,6 +202,8 @@ const PTY_EXITED_BEFORE_PROMPT_MESSAGE = 'Claude exited before your message coul
201
202
  const PTY_EXITED_MID_TURN_MESSAGE = 'Claude exited mid-turn — restarting.'
202
203
  const PROMPT_EMPTY_MESSAGE = 'Your message was empty after removing control characters, so nothing was sent.'
203
204
  const PTY_RESPAWN_EXHAUSTED_MESSAGE = 'Claude kept exiting; stopped restarting it.'
205
+ // #9241: Claude Code's reply-line glyph, U+23FA on macOS and U+25CF elsewhere (see _appendToOutputTail).
206
+ const REPLY_GLYPH_RE = /[\u23FA\u25CF]/
204
207
 
205
208
  /**
206
209
  * ClaudeTuiSession — drives the interactive `claude` TUI under a PTY so the
@@ -619,6 +622,8 @@ export class ClaudeTuiSession extends BaseSession {
619
622
  this._sinkBaseCompromiseWarnLoggedMs = 0 // throttle the compromised-base error log
620
623
  this._term = null // persistent PTY for the session's lifetime
621
624
  this._settingsPath = null
625
+ // What the settings file at `_settingsPath` was written under (project settings allowed or not).
626
+ this._settingsProjectAllowed = false
622
627
  // #4013: sidecar file containing the current permission mode. The
623
628
  // hook script re-reads it on every tool call so setPermissionMode()
624
629
  // can take effect without restarting the PTY (which would lose the
@@ -2886,7 +2891,11 @@ export class ClaudeTuiSession extends BaseSession {
2886
2891
  */
2887
2892
  _emitConfiguredMcpServers() {
2888
2893
  try {
2889
- const { servers, warnings } = discoverConfiguredMcpServers(this.cwd)
2894
+ const { servers, warnings } = discoverConfiguredMcpServers(this.cwd, {
2895
+ // What the RUNNING process was launched with (the decision its spawn took), so this
2896
+ // listing matches what it loaded and never scans the folder again.
2897
+ includeProjectFile: this._launchedWithProject === true,
2898
+ })
2890
2899
  for (const warning of warnings) {
2891
2900
  ;(this._log || log).warn(`MCP config: ${warning}`)
2892
2901
  }
@@ -3729,6 +3738,13 @@ export class ClaudeTuiSession extends BaseSession {
3729
3738
  this._beginNativeRouteVerification()
3730
3739
  }
3731
3740
  const cwdReal = realpathSync(this.cwd)
3741
+ // The ONE project-settings decision for this spawn: it picks `--setting-sources`
3742
+ // and whether the per-session settings file enables `.mcp.json` servers.
3743
+ // A folder with no trust record is decided without a scan; a trusted one is verified by a
3744
+ // fresh scan off the main thread.
3745
+ const projectAllowed = await projectSettingsAllowedAsync(cwdReal)
3746
+ if (this._destroying) return
3747
+ this._launchedWithProject = projectAllowed
3732
3748
  const env = this._buildPtyEnv(permissionsEnabled)
3733
3749
  let attemptedBinary
3734
3750
  // #8038: the binary-gate step gets its OWN try, split out from the nonce /
@@ -3757,12 +3773,17 @@ export class ClaudeTuiSession extends BaseSession {
3757
3773
  try {
3758
3774
  nativeRouteNonce = this._connectionAuthRoute === 'native' ? randomBytes(16).toString('hex') : null
3759
3775
  if (nativeRouteNonce) {
3760
- this._settingsPath = this._writeHookSettings({ permissionsEnabled, nativeRouteNonce })
3776
+ this._settingsPath = this._writeHookSettings({ permissionsEnabled, nativeRouteNonce, projectAllowed })
3761
3777
  }
3762
3778
  } catch (err) {
3763
3779
  this._blockNativeRouteVerification(err)
3764
3780
  throw err
3765
3781
  }
3782
+ // The settings file written at start (or by a previous spawn) carries the
3783
+ // decision it was written under; rewrite it when this spawn decided otherwise.
3784
+ if (this._settingsProjectAllowed !== projectAllowed && this._sinkDir && !nativeRouteNonce) {
3785
+ this._settingsPath = this._writeHookSettings({ permissionsEnabled, projectAllowed })
3786
+ }
3766
3787
  try {
3767
3788
  await this._verifyNativeConnectionRoute({ binary: attemptedBinary, cwd: cwdReal, env })
3768
3789
  } catch (err) {
@@ -3911,6 +3932,7 @@ export class ClaudeTuiSession extends BaseSession {
3911
3932
  : ['--session-id', this._sessionId]
3912
3933
  args.push(
3913
3934
  '--settings', this._settingsPath,
3935
+ '--setting-sources', claudeSettingSourcesValueFor(projectAllowed),
3914
3936
  // Claude Code 2.1.186 added a "Claude in Chrome extension detected"
3915
3937
  // first-run prompt that interactively blocks the TUI (1/2/Enter/Esc) when
3916
3938
  // the browser extension is installed. chroxy's PTY driver can't dismiss
@@ -4351,6 +4373,22 @@ export class ClaudeTuiSession extends BaseSession {
4351
4373
  else this._declareReadyAfterSilentStart()
4352
4374
  }
4353
4375
  const rawStr = String(data)
4376
+ // #9241: the first assistant line on the screen is the earliest sign claude began
4377
+ // answering, and for a text-only reply it is the ONLY one until the Stop hook (no
4378
+ // PreToolUse fires, and the text reaches `emit` as a stream_delta at the end).
4379
+ // Claude Code prefixes assistant text and tool lines with a platform-dependent glyph:
4380
+ // its own `macos ? '\u23FA' : '\u25CF'` (U+23FA on macOS, U+25CF on every other
4381
+ // platform), so BOTH are accepted. U+25CF also appears elsewhere in its UI, but an
4382
+ // over-match only suppresses the marker, never mints it over visible text (fail-safe).
4383
+ // DEPENDENCY: if a Claude Code release changes either glyph, a Stop over visible text
4384
+ // can again be marked "stopped before a reply" (the marker errs toward showing).
4385
+ // Armed only once this turn's prompt has been written (`_markPromptWritten`), so the
4386
+ // echo of the prompt and the previous turn's screen do not count; a redraw that
4387
+ // re-prints an older glyph line after that only suppresses the marker (fail-safe).
4388
+ if (this._replyGlyphWatch && this._isBusy && REPLY_GLYPH_RE.test(rawStr)) {
4389
+ this._replyGlyphWatch = false
4390
+ this._noteTurnOutput()
4391
+ }
4354
4392
  const chunk = Buffer.from(rawStr, 'utf8')
4355
4393
  // #5794/#5809: monotonic total — never capped, so the nudge's progress check
4356
4394
  // works even when _outputTail is pinned at PTY_TAIL_BYTES.
@@ -4696,6 +4734,7 @@ export class ClaudeTuiSession extends BaseSession {
4696
4734
  this._turnStartedOnThisPty = true // #8441
4697
4735
  this._limitScanFromBytes = this._totalOutputBytes // #8454
4698
4736
  this._lastTurnStopped = false
4737
+ this._replyGlyphWatch = false // #9241: armed again by _markPromptWritten
4699
4738
  }
4700
4739
 
4701
4740
  /**
@@ -4707,6 +4746,7 @@ export class ClaudeTuiSession extends BaseSession {
4707
4746
  */
4708
4747
  _markPromptWritten() {
4709
4748
  this._limitScanFromBytes = this._totalOutputBytes
4749
+ this._replyGlyphWatch = true // #9241: see _appendToOutputTail
4710
4750
  }
4711
4751
 
4712
4752
  /**
@@ -5326,6 +5366,15 @@ export class ClaudeTuiSession extends BaseSession {
5326
5366
  // `_consumedFiles.size` (which no longer grows — files are unlinked +
5327
5367
  // pruned), otherwise the disarm/re-arm would stop firing on progress.
5328
5368
  if (drainedThisPass > 0 && this._isBusy) {
5369
+ // #9241: a consumed hook file is the earliest structured proof that claude
5370
+ // began working on this turn (the PreToolUse / Stop hook fires as it happens),
5371
+ // so it is what a Stop is judged against. The PTY mirror (`terminal_output`,
5372
+ // `terminal_resize`: prompt echo, redraws) is the screen and does not count,
5373
+ // and claude's transcript lags both (see the KNOWN LIMIT above). KNOWN LIMIT:
5374
+ // a Stop that lands before this poller drains a hook file that was already
5375
+ // written (the loop checks `aborted` first) sees no output yet, so a tool the
5376
+ // user watched start can still be marked "stopped before a reply".
5377
+ this._noteTurnOutput()
5329
5378
  // #4732: a consumed hook file = first output observed for this
5330
5379
  // turn. Disarm the pre-first-output watchdog BEFORE the
5331
5380
  // re-arm below — `_armResultTimeout` would otherwise re-arm
@@ -5993,7 +6042,7 @@ export class ClaudeTuiSession extends BaseSession {
5993
6042
  if (messageId) this.emit('stream_end', { messageId })
5994
6043
  // The tools the Stop cut off were cut off, not failed (#7376).
5995
6044
  this._emitResult(
5996
- { cost: null, duration, usage: null, sessionId: this._sessionId, turnOutcome: 'stopped', interrupted: true },
6045
+ { cost: null, duration, usage: null, sessionId: this._sessionId, turnOutcome: 'stopped', interrupted: true, stopRequested: true }, // #9241: the Stop's own end
5997
6046
  'user_stop',
5998
6047
  )
5999
6048
  this._clearTurnEndState()
@@ -6552,11 +6601,15 @@ export class ClaudeTuiSession extends BaseSession {
6552
6601
  * summaries from the API, which is what puts readable text in the transcript's
6553
6602
  * `thinking` blocks (without it the block carries only its signature).
6554
6603
  */
6555
- _writeHookSettings({ permissionsEnabled, nativeRouteNonce = null }) {
6604
+ _writeHookSettings({ permissionsEnabled, nativeRouteNonce = null, projectAllowed = false }) {
6605
+ // The spawn's ONE project-settings decision is passed in (see _spawnPty), so the
6606
+ // settings file and `--setting-sources` can never disagree.
6607
+ this._settingsProjectAllowed = projectAllowed
6556
6608
  return writeHookSettings(this._sinkDir, {
6557
6609
  permissionsEnabled,
6558
6610
  ...(nativeRouteNonce ? { nativeRouteNonce } : {}),
6559
6611
  thinkingSummaries: this._thinkingEnabled,
6612
+ enableAllProjectMcpServers: projectAllowed,
6560
6613
  })
6561
6614
  }
6562
6615