@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
@@ -96,6 +96,68 @@ export const NOT_PROVIDER_ACTIVITY_EVENTS = Object.freeze([
96
96
  'thinking_level_changed',
97
97
  ])
98
98
 
99
+ // #9241: classifying a session event as "assistant output" for the stop-before-reply
100
+ // marker. A turn the user Stops before ANY output gets a replayable marker; a Stop
101
+ // after output stays quiet (#8461). The classification is FAIL-SAFE: only the names
102
+ // in TURN_QUIET_EVENTS are known not to be output, so a new or unclassified event
103
+ // counts as output, which suppresses the marker -- today's behaviour -- rather than
104
+ // minting a wrong "stopped before a reply" over a turn that had begun. The two lists
105
+ // below must between them cover every forwarded session event
106
+ // (PROVIDER_ACTIVITY_EVENTS + NOT_PROVIDER_ACTIVITY_EVENTS) and name nothing that is
107
+ // not emitted; tests/stop-before-reply-roster.test.js checks both directions.
108
+ // Conditional on payload: `stream_delta` (empty text) and `message` (system type or
109
+ // empty content) are quiet; see `eventCountsAsTurnOutput`.
110
+ export const TURN_QUIET_EVENTS = Object.freeze([
111
+ // `stream_start` opens an EMPTY slot (claude-tui emits it at turn start, #4010);
112
+ // its `stream_end` closes it
113
+ 'stream_start', 'stream_end',
114
+ // turn bookkeeping
115
+ 'turn_state', 'result', 'stopped', 'ready', 'busy_cleared', 'declaration_turn',
116
+ 'tool_input_recorded', 'models_updated',
117
+ // permission and queue bookkeeping (a prompt still open at Stop counts through
118
+ // getPendingPermissionCount, and `permission_request` itself is output)
119
+ 'permission_resolved', 'permission_expired', 'message_queued', 'message_dequeued',
120
+ // derived or recomputed state
121
+ 'activity_delta', 'activity_snapshot', 'background_work_changed', 'background_tasks_changed',
122
+ // configuration, environment and daemon housekeeping
123
+ 'mcp_servers', 'skill_changed', 'skill_trust_request', 'skill_trust_granted',
124
+ 'inactivity_warning', 'stdin_dropped_totals', 'setup_log', 'respawn_exhausted',
125
+ 'thinking_level_changed',
126
+ // claude-tui's raw PTY mirror (prompt echo, redraws, a resize) is the SCREEN, not the
127
+ // reply: see ClaudeTuiSession's hook drain for the signal that is (#9241)
128
+ 'terminal_output', 'terminal_resize',
129
+ // the embedded user shell is not the model
130
+ 'shell_spawned', 'shell_exited',
131
+ ])
132
+ const TURN_QUIET_EVENT_SET = new Set(TURN_QUIET_EVENTS)
133
+
134
+ // #9241: events that ARE output, declared so the roster test forces a decision for
135
+ // each new event. Not read at runtime: everything outside TURN_QUIET_EVENTS counts.
136
+ export const TURN_OUTPUT_EVENTS = Object.freeze([
137
+ 'stream_delta', 'message', 'tool_start', 'tool_input_delta', 'tool_result',
138
+ 'user_question', 'multi_question_intervention', 'permission_request', 'error',
139
+ 'agent_spawned', 'agent_event', 'agent_completed', 'plan_started', 'plan_ready',
140
+ 'assistant_response',
141
+ ])
142
+
143
+ /**
144
+ * #9241: does this session event show the model began answering? Fail-safe (see
145
+ * TURN_QUIET_EVENTS): unknown names and unrecognised payload shapes count.
146
+ *
147
+ * @param {string} event
148
+ * @param {*} data
149
+ * @returns {boolean}
150
+ */
151
+ export function eventCountsAsTurnOutput(event, data) {
152
+ if (TURN_QUIET_EVENT_SET.has(event)) return false
153
+ if (event === 'stream_delta') return !(typeof data?.delta === 'string' && data.delta === '')
154
+ if (event === 'message') {
155
+ if (data?.type === 'system') return false
156
+ return !(typeof data?.content === 'string' && data.content === '')
157
+ }
158
+ return true
159
+ }
160
+
99
161
  // #5936 (epic #5935): explicit overflow cap for the shared outgoing-message
100
162
  // queue (`_outgoingQueue`). Replaces the SDK's hard-coded mid-turn cap of 3
101
163
  // (#5711) with one bounded, surfaced limit shared by SDK + CLI. A send-while-
@@ -104,11 +166,23 @@ export const NOT_PROVIDER_ACTIVITY_EVENTS = Object.freeze([
104
166
  // burst of owner follow-ups while still bounding memory if a client wedges.
105
167
  export const OUTGOING_QUEUE_MAX = 10
106
168
 
169
+ /**
170
+ * #8281: handoff-blocker codes that are reported but advisory. A caller decides
171
+ * whether they block; every other code is hard.
172
+ */
173
+ export const SOFT_HANDOFF_BLOCKER_CODES = Object.freeze(new Set(['background_shells']))
174
+
107
175
  /**
108
176
  * Report the provider's input-admission boundary without waiting for the turn.
109
177
  * Async sendMessage implementations call this before their first await when
110
178
  * possible, or later when an async transport handshake proves admission.
111
179
  */
180
+ /** #9242: the admission shape for a send refused by its own predicate after provider preparation. */
181
+ export const NOT_ADMITTED_ADMISSION = Object.freeze({
182
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
183
+ reason: 'not_admitted', message: 'The input was no longer admitted after preparation; it was not dispatched.',
184
+ })
185
+
112
186
  export function reportInputAdmission(sendOptions, admission) {
113
187
  const callback = sendOptions?.onInputAdmission
114
188
  if (typeof callback === 'function') callback(admission)
@@ -340,6 +414,14 @@ export class BaseSession extends EventEmitter {
340
414
  return 'unknown'
341
415
  }
342
416
 
417
+ /**
418
+ * Whether the RUNNING process was launched with project settings loaded (claude-cli
419
+ * and claude-tui set this at each launch). `undefined` for a provider that does not
420
+ * record it.
421
+ * @returns {boolean|undefined}
422
+ */
423
+ get launchedWithProject() { return this._launchedWithProject }
424
+
343
425
  /** Runtime-negotiated capability states; static UI capabilities are separate. */
344
426
  get providerRuntimeCapabilities() {
345
427
  return {}
@@ -593,6 +675,17 @@ export class BaseSession extends EventEmitter {
593
675
  // CLI child's exit, a late abort rejection) must not repeat.
594
676
  this._stoppedSinceStopRequest = false
595
677
  this._stopAckedByResult = false
678
+ // #9241: per TURN (reset on the busy false->true edge, NOT in `_clearMessageState`,
679
+ // which claude-cli runs BEFORE its terminal `result`/`stopped`): a Stop came in
680
+ // through the `interrupt` message (`markStopRequested`; `_stopRequestedThisTurn`
681
+ // also covers the scheduler and orchestration, which never arm this), the model
682
+ // produced output (set by the emit() override and `_noteTurnOutput`), the marker
683
+ // went out (`_stopMarkerEmitted`), or the turn's terminal event settled the
684
+ // question (`_stopMarkerMinted`).
685
+ this._stopMarkerArmed = false
686
+ this._turnOutputSeen = false
687
+ this._stopMarkerMinted = false
688
+ this._stopMarkerEmitted = false
596
689
  // #4307/#5177/#5247/#5265: pending background-shell tracking + the reaping
597
690
  // sweep live in BackgroundShellTracker (#5376). BaseSession composes one and
598
691
  // delegates the public surface (trackBackgroundShell / clearBackgroundShell /
@@ -700,6 +793,10 @@ export class BaseSession extends EventEmitter {
700
793
  // input_conflict gate) — by the time a send reaches the queue it is the
701
794
  // owner's own follow-up, never a way around primary-client arbitration.
702
795
  this._outgoingQueue = []
796
+ // #8281: prompts `dequeueNextOutgoing()` has shifted off the queue whose
797
+ // deferred send (process.nextTick) has not begun yet. A counter, not a
798
+ // boolean, so two shifts landing before the tick cannot clear each other.
799
+ this._dequeuesInFlight = 0
703
800
  this._activeAgents = new Map()
704
801
  this._resultTimeout = null
705
802
  // #3899: parallel hard-cap setTimeout handle. Armed alongside
@@ -979,6 +1076,13 @@ export class BaseSession extends EventEmitter {
979
1076
  const next = !!value
980
1077
  if (this._busyFlag === next) return
981
1078
  this._busyFlag = next
1079
+ if (next) {
1080
+ // #9241: a new turn starts with a clean slate for the stop-before-reply marker.
1081
+ this._stopMarkerArmed = false
1082
+ this._turnOutputSeen = false
1083
+ this._stopMarkerMinted = false
1084
+ this._stopMarkerEmitted = false
1085
+ }
982
1086
  this.emit('turn_state', { active: next })
983
1087
  }
984
1088
 
@@ -1029,6 +1133,101 @@ export class BaseSession extends EventEmitter {
1029
1133
  return this._backgroundShellTracker.size
1030
1134
  }
1031
1135
 
1136
+ /**
1137
+ * #8281: a prompt has left `_outgoingQueue` (see `dequeueNextOutgoing`) but its
1138
+ * deferred send has not begun. For that one tick the session is not busy AND
1139
+ * the queue is empty, yet a turn is about to start.
1140
+ * @returns {boolean}
1141
+ */
1142
+ get hasDequeueInFlight() {
1143
+ return this._dequeuesInFlight > 0
1144
+ }
1145
+
1146
+ /**
1147
+ * #8281: is a turn in flight from the point of view of a handoff? Defaults to
1148
+ * `turnActive`. A provider whose turn exists before `_isBusy` is set (or
1149
+ * before its backend id is known) overrides this rather than the base class
1150
+ * learning provider internals.
1151
+ * @returns {boolean}
1152
+ */
1153
+ _hasTurnInFlight() {
1154
+ return this.turnActive
1155
+ }
1156
+
1157
+ /**
1158
+ * #8281: ids of every permission prompt waiting on a human for this session,
1159
+ * deduped across the same sources `getPendingPermissionCount()` counts:
1160
+ * the hook-routed ids (`_pendingPermissionIds`, CLI / TUI, registered by
1161
+ * ws-permissions through `notifyPermissionPending`), the in-process map
1162
+ * installed as `_pendingPermissions` when it is a Map, and the
1163
+ * PermissionManager's own ids. EMPTY when none of them holds anything.
1164
+ * @returns {string[]}
1165
+ */
1166
+ getPendingPermissionIds() {
1167
+ const ids = new Set(this._pendingPermissionIds)
1168
+ if (this._pendingPermissions instanceof Map) {
1169
+ for (const id of this._pendingPermissions.keys()) ids.add(id)
1170
+ }
1171
+ for (const id of this._permissions?.getPendingPermissionIds?.() ?? []) ids.add(id)
1172
+ return Array.from(ids)
1173
+ }
1174
+
1175
+ /**
1176
+ * #8281: prompts accepted by the provider that wait in a queue other than
1177
+ * `_outgoingQueue` (or have left one with the send deferred). Default 0; a
1178
+ * provider with a second queue overrides it. Counted as `queued_prompts`.
1179
+ * @returns {number}
1180
+ */
1181
+ _extraQueuedPromptCount() {
1182
+ return 0
1183
+ }
1184
+
1185
+ /**
1186
+ * #8281: why a handoff must not start from this session right now. An empty
1187
+ * array means nothing in THIS session can still act. Each entry is
1188
+ * `{ code, detail? }`; codes:
1189
+ *
1190
+ * - `turn_active` a turn is in flight (`_hasTurnInFlight`)
1191
+ * - `queued_prompts` prompts wait in the outgoing queue, or one has left
1192
+ * it and its send has not begun (`hasDequeueInFlight`)
1193
+ * - `pending_permission` an approval is waiting (`getPendingPermissionIds`)
1194
+ * - `pending_question` an AskUserQuestion is waiting (`getPendingQuestions`)
1195
+ * - `active_agents` subagents are running (`getActiveAgents`)
1196
+ * - `not_ready` the provider process is not ready
1197
+ * - `destroying` the session is being torn down
1198
+ * - `background_shells` SOFT: tracked background shells exist; the entry's
1199
+ * detail carries `soft: true` (see
1200
+ * `SOFT_HANDOFF_BLOCKER_CODES`). It is reported, and the
1201
+ * caller decides whether it blocks.
1202
+ *
1203
+ * Does NOT see what lives outside the session: the prompt evaluator and
1204
+ * scheduler/orchestration ownership. `SessionManager.
1205
+ * getHandoffBlockers` adds those. `isRunning` is unchanged and unrelated.
1206
+ *
1207
+ * @returns {{ code: string, detail?: object }[]}
1208
+ */
1209
+ getHandoffBlockers() {
1210
+ const blockers = []
1211
+ if (this._destroying) blockers.push({ code: 'destroying' })
1212
+ if (!this._processReady) blockers.push({ code: 'not_ready' })
1213
+ if (this._hasTurnInFlight()) blockers.push({ code: 'turn_active' })
1214
+ const queued = this._outgoingQueue.length + this._dequeuesInFlight + this._extraQueuedPromptCount()
1215
+ if (queued > 0) blockers.push({ code: 'queued_prompts', detail: { count: queued } })
1216
+ const permissionIds = this.getPendingPermissionIds()
1217
+ if (permissionIds.length > 0) {
1218
+ blockers.push({ code: 'pending_permission', detail: { requestIds: permissionIds } })
1219
+ }
1220
+ const questions = this.getPendingQuestions()
1221
+ if (questions.length > 0) {
1222
+ blockers.push({ code: 'pending_question', detail: { count: questions.length } })
1223
+ }
1224
+ const agents = this._activeAgents.size
1225
+ if (agents > 0) blockers.push({ code: 'active_agents', detail: { count: agents } })
1226
+ const shells = this.backgroundShellCount
1227
+ if (shells > 0) blockers.push({ code: 'background_shells', detail: { count: shells, soft: true } })
1228
+ return blockers
1229
+ }
1230
+
1032
1231
  /**
1033
1232
  * #8302: why `isRunning` is true — `'turn'`, `'background-shells'` (idle model,
1034
1233
  * tracked shells only), or `null` when the session is not busy. Derived from
@@ -1135,6 +1334,8 @@ export class BaseSession extends EventEmitter {
1135
1334
  dequeueNextOutgoing() {
1136
1335
  if (this._destroying || this._outgoingQueue.length === 0) return null
1137
1336
  const item = this._outgoingQueue.shift()
1337
+ // #8281: the item is off the queue but not yet sent; see `hasDequeueInFlight`.
1338
+ this._dequeuesInFlight++
1138
1339
  const clientMessageId = typeof item.sendOptions?.clientMessageId === 'string'
1139
1340
  ? item.sendOptions.clientMessageId
1140
1341
  : undefined
@@ -1149,6 +1350,9 @@ export class BaseSession extends EventEmitter {
1149
1350
  // dequeue ahead of the result that triggered it.
1150
1351
  const remaining = this._outgoingQueue.length
1151
1352
  process.nextTick(() => {
1353
+ // #8281: the deferred send begins here. Cleared FIRST so every exit below
1354
+ // (destroyed, admission refused, sent) leaves the counter balanced.
1355
+ this._dequeuesInFlight = Math.max(0, this._dequeuesInFlight - 1)
1152
1356
  if (this._destroying) return
1153
1357
  // #8301: an item that carries `sendOptions.admitAtFlush` is re-checked HERE,
1154
1358
  // at the moment it would be dispatched — after the preceding turn's
@@ -1194,12 +1398,30 @@ export class BaseSession extends EventEmitter {
1194
1398
  // The connection that queued this follow-up may have ended while it waited:
1195
1399
  // a revoked or expired credential must not get its queued input dispatched.
1196
1400
  if (!stillAuthorized(item?.sendOptions?.isAuthorized)) return false
1197
- const predicate = item?.sendOptions?.admitAtFlush
1401
+ return this._admitPreparedSend(item?.sendOptions)
1402
+ }
1403
+
1404
+ /**
1405
+ * #9242: re-ask a send's admission predicate (`sendOptions.admitAtFlush`) at a
1406
+ * provider's POST-PREPARATION point — after any await between `sendMessage` entry
1407
+ * and the irreversible step (history mutation, query/stream dispatch). The flush
1408
+ * check covers a send that was queued; this covers one that was never queued but
1409
+ * waited inside the provider (project-settings scan, MCP prompt expansion). No
1410
+ * predicate means admitted, so every caller that passes none is unchanged. Anything
1411
+ * but `true`, or a throw, is a refusal; the CALLER must then release busy, report
1412
+ * the refusal and continue the queue. (TurnDriver's predicate wrapper ends its own
1413
+ * turn NOT_ADMITTED on a refusal.)
1414
+ *
1415
+ * @param {{ admitAtFlush?: () => boolean }} [sendOptions]
1416
+ * @returns {boolean}
1417
+ */
1418
+ _admitPreparedSend(sendOptions) {
1419
+ const predicate = sendOptions?.admitAtFlush
1198
1420
  if (typeof predicate !== 'function') return true
1199
1421
  try {
1200
1422
  return predicate() === true
1201
1423
  } catch (err) {
1202
- ;(this._log || log).warn(`Queued follow-up admission check threw; dropping it: ${err?.message || err}`)
1424
+ ;(this._log || log).warn(`Send admission check threw; refusing the send: ${err?.message || err}`)
1203
1425
  return false
1204
1426
  }
1205
1427
  }
@@ -1669,6 +1891,44 @@ export class BaseSession extends EventEmitter {
1669
1891
  this._permissions?.markUserStopInFlight?.()
1670
1892
  }
1671
1893
 
1894
+ /**
1895
+ * #9241: a Stop came in through the `interrupt` message (the dashboard, the app, or
1896
+ * an agent-control client: the marker's wording is neutral, so who pressed it does
1897
+ * not matter). Separate from `markUserStopInFlight` (permission labelling) and
1898
+ * `_noteTurnStopRequested` (anyone's `interrupt()`, including the scheduler's and
1899
+ * orchestration's, which must never leave a marker). Called by the `interrupt`
1900
+ * message handler only. A no-op when idle, so a Stop between turns cannot leak into
1901
+ * the next one; idempotent for a double Stop. A prompt still open counts as output
1902
+ * too (hook-routed ones are also latched when they are registered).
1903
+ */
1904
+ markStopRequested() {
1905
+ if (!this._isBusy) return
1906
+ this._stopMarkerArmed = true
1907
+ if (this.getPendingPermissionCount() > 0) this._turnOutputSeen = true
1908
+ }
1909
+
1910
+ /**
1911
+ * #9241: a provider's own evidence that the model began answering, for output that
1912
+ * does not reach `emit` as a classified event (claude-tui's structured events lag
1913
+ * its screen, see ClaudeTuiSession's hook drain).
1914
+ */
1915
+ _noteTurnOutput() {
1916
+ this._turnOutputSeen = true
1917
+ }
1918
+
1919
+ /**
1920
+ * #9241: should the terminal event now being emitted for this turn carry the
1921
+ * stop-before-reply marker? True once per turn, only for a Stop that came in
1922
+ * through `interrupt` before any output, never while the session is being torn
1923
+ * down. The CALLER also needs the provider's explicit word that the turn ended
1924
+ * BECAUSE of the requested stop (`stopRequested` on its stop-path event, or its own
1925
+ * `turnOutcome: 'stopped'`): a stall watchdog, a timeout or an error after the Stop
1926
+ * ends the turn too, and is not a Stop.
1927
+ */
1928
+ _shouldMintStopBeforeReply() {
1929
+ return this._stopMarkerArmed && !this._turnOutputSeen && !this._stopMarkerMinted && !this._destroying
1930
+ }
1931
+
1672
1932
  /**
1673
1933
  * #7376: record that a Stop was requested during the turn that is running
1674
1934
  * now. A no-op when idle, so a Stop pressed between turns cannot leak into the
@@ -2302,12 +2562,29 @@ export class BaseSession extends EventEmitter {
2302
2562
  */
2303
2563
  emit(event, ...args) {
2304
2564
  if (PROVIDER_ACTIVITY_EVENT_SET.has(event)) this.noteProviderActivity()
2565
+ if (eventCountsAsTurnOutput(event, args[0])) this._turnOutputSeen = true
2305
2566
  if (event === 'stopped') {
2306
2567
  // #8461: this Stop was already confirmed in place of the chip; not twice.
2307
2568
  if (this._stopAckedByResult) {
2308
2569
  this._stopAckedByResult = false
2309
2570
  return false
2310
2571
  }
2572
+ // #9241: a Stop that ends the turn with no `result` (SDK abort, claude-cli child
2573
+ // exit, ACP, jsonl subprocess) leaves nothing in history. When the provider says
2574
+ // this `stopped` IS the requested stop (`stopRequested`, set on its stop path
2575
+ // only: not on a watchdog, a timeout or an error that was converted to
2576
+ // `stopped`), mint the marker first, so the client idles on it and `stopped`
2577
+ // follows.
2578
+ // Read through a local alias on purpose: the features-gate scanner
2579
+ // (config-supported-keys-docs.test.js) flags `X[0].stopRequested === true` as a
2580
+ // gate shape, a false positive for this internal signal.
2581
+ const stoppedPayload = args[0]
2582
+ const explicit = !!stoppedPayload && typeof stoppedPayload === 'object' && stoppedPayload.stopRequested === true
2583
+ if (stoppedPayload && typeof stoppedPayload === 'object' && 'stopRequested' in stoppedPayload) {
2584
+ const { stopRequested: _signal, ...rest } = stoppedPayload
2585
+ args[0] = rest // internal: never on the wire
2586
+ }
2587
+ if (explicit && this._shouldMintStopBeforeReply()) this._emitStopBeforeReplyResult()
2311
2588
  this._stoppedSinceStopRequest = true
2312
2589
  }
2313
2590
  let ackStop = false
@@ -2350,7 +2627,31 @@ export class BaseSession extends EventEmitter {
2350
2627
  const { turnOutcome: _userStop, ...rest } = payload
2351
2628
  payload = rest
2352
2629
  ackStop = !this._stoppedSinceStopRequest
2630
+ // #9241: the chip is dropped for a Stop that was asked for, but a Stop
2631
+ // before any output gets the quiet marker in its place, and ONLY when the
2632
+ // provider says by `stopRequested` that this result IS the Stop's end (a
2633
+ // BYOK upstream error that raced the abort also arrives as `stopped`).
2634
+ if (payload.stopRequested === true && this._shouldMintStopBeforeReply()) {
2635
+ payload = { ...payload, turnOutcome: 'stopped_before_output' }
2636
+ }
2637
+ } else if (payload && typeof payload === 'object' && payload.stopRequested === true
2638
+ && payload.turnOutcome === undefined && this._shouldMintStopBeforeReply()) {
2639
+ // claude-cli's synthetic result for a Stop (child exit / 5 s safety timer): it
2640
+ // clears message state first and carries `interrupted` with no outcome, and
2641
+ // says by `stopRequested` that the Stop is why (its stall watchdogs use the
2642
+ // same shape and do not).
2643
+ payload = { ...payload, turnOutcome: 'stopped_before_output' }
2644
+ }
2645
+ if (payload && typeof payload === 'object' && 'stopRequested' in payload) {
2646
+ const { stopRequested: _signal, ...rest } = payload
2647
+ payload = rest // internal: never on the wire
2353
2648
  }
2649
+ if (payload && typeof payload === 'object' && payload.turnOutcome === 'stopped_before_output') {
2650
+ this._stopMarkerEmitted = true
2651
+ }
2652
+ // #9241: the turn's terminal `result` settles the marker, minted or not, so a
2653
+ // `stopped` that follows it never mints a second one.
2654
+ if (this._stopMarkerArmed) this._stopMarkerMinted = true
2354
2655
  // #7326: a marked outcome (anything but `completed`) becomes a chip in the
2355
2656
  // transcript, and the chip needs an identity that the live `result` frame
2356
2657
  // and the history entry replayed later AGREE on -- a `result` has no id, and
@@ -2372,6 +2673,19 @@ export class BaseSession extends EventEmitter {
2372
2673
  return delivered
2373
2674
  }
2374
2675
 
2676
+ /**
2677
+ * #9241: emit the stop-before-reply marker as the turn's own `result`. Not billed
2678
+ * (`cost: null`), and internal-only `interrupted` as on every synthetic terminal
2679
+ * result (#7072). Goes through emit() so it is stamped, normalised, recorded in
2680
+ * history and idles the client like any other result.
2681
+ */
2682
+ _emitStopBeforeReplyResult() {
2683
+ this.emit('result', {
2684
+ cost: null, duration: null, usage: null, sessionId: this._sessionId,
2685
+ turnOutcome: 'stopped_before_output', interrupted: true,
2686
+ })
2687
+ }
2688
+
2375
2689
  /**
2376
2690
  * How many permission requests are waiting on a human for this session,
2377
2691
  * across both routes: the hook-routed ids (CLI / TUI, #2831) and the
@@ -2452,6 +2766,9 @@ export class BaseSession extends EventEmitter {
2452
2766
  notifyPermissionPending(requestId) {
2453
2767
  if (!requestId || this._pendingPermissionIds.has(requestId)) return
2454
2768
  this._pendingPermissionIds.add(requestId)
2769
+ // #9241: a prompt the model raised is output, and a hook-routed one never passes
2770
+ // through emit(): latch it here, so one answered before the Stop still counts.
2771
+ this._turnOutputSeen = true
2455
2772
  if (this._pendingPermissionIds.size === 1) this._onFirstPermissionPending()
2456
2773
  }
2457
2774
 
@@ -129,6 +129,8 @@ export const BOUND_DENIED_MESSAGE_TYPES = Object.freeze({
129
129
  set_prompt_evaluator_skip_pattern: 'a pattern the daemon runs on its own event loop for every input',
130
130
  add_mcp_server: 'host-wide server configuration',
131
131
  remove_mcp_server: 'host-wide server configuration',
132
+ trust_folder: 'lets a folder\'s project settings run on this machine',
133
+ untrust_folder: 'changes which folders run project settings on this machine',
132
134
  submit_mcp_auth_code: 'stores a credential shared by every session using the server',
133
135
  list_providers: 'host-wide configuration status',
134
136
  byok_get_credentials_status: 'host-wide credential status',
@@ -151,6 +153,16 @@ export const BOUND_DENIED_MESSAGE_TYPES = Object.freeze({
151
153
  session_preset_revoke: 'host-wide presets',
152
154
  daemon_update_action: 'host lifecycle',
153
155
  revoke_token: 'credential management',
156
+ principal_admin_grant: 'credential management',
157
+ principal_admin_list: 'credential management',
158
+ principal_admin_revoke: 'credential management',
159
+ principal_admin_disable: 'credential management',
160
+ principal_admin_enable: 'credential management',
161
+ principal_subscribe: 'agent-principal journal read path, never a bound client\'s',
162
+ principal_unsubscribe: 'agent-principal journal read path, never a bound client\'s',
163
+ principal_events_read: 'agent-principal journal read path, never a bound client\'s',
164
+ principal_pending_permissions: 'agent-principal pending-permission snapshot, never a bound client\'s',
165
+ principal_sessions_snapshot: 'agent-principal session roster snapshot, never a bound client\'s',
154
166
  pair_approve: 'credential management',
155
167
  pair_deny: 'credential management',
156
168
 
@@ -722,7 +722,7 @@ export function mcpSourceToWriteScope(source) {
722
722
  * @param {string} configPath — resolved `~/.claude.json` path (or override)
723
723
  * @returns {{ sources: Array<{ mcpServers: unknown, source: string }>, warnings: string[] }}
724
724
  */
725
- function readMcpSourcesInPrecedenceOrder(cwd, configPath) {
725
+ function readMcpSourcesInPrecedenceOrder(cwd, configPath, { includeProjectFile = true } = {}) {
726
726
  const warnings = []
727
727
  const sources = []
728
728
 
@@ -784,7 +784,7 @@ function readMcpSourcesInPrecedenceOrder(cwd, configPath) {
784
784
  // 2 — "Project" scope: <cwd>/.mcp.json, checked into the repo. cwd may not
785
785
  // exist (removed tmp dir, stale worktree) — join+existsSync just reports
786
786
  // false rather than throwing.
787
- if (cwd) {
787
+ if (cwd && includeProjectFile) {
788
788
  const mcpJsonPath = join(cwd, '.mcp.json')
789
789
  if (existsSync(mcpJsonPath)) {
790
790
  const raw = readJson(mcpJsonPath, 'project .mcp.json')
@@ -829,12 +829,16 @@ function readMcpSourcesInPrecedenceOrder(cwd, configPath) {
829
829
  * Never throws: each read is guarded and failures accumulate as warnings, so a
830
830
  * corrupt config can't take down session start.
831
831
  *
832
+ * `includeProjectFile: false` leaves out `<cwd>/.mcp.json`, for a session
833
+ * that does not load project-scope settings (claude-setting-sources.js), so
834
+ * the list shows only servers that session can actually load.
835
+ *
832
836
  * @param {string} cwd — the session's working directory
833
- * @param {{ configPath?: string }} [opts]
837
+ * @param {{ configPath?: string, includeProjectFile?: boolean }} [opts]
834
838
  * @returns {{ servers: Array<{ name: string }>, warnings: string[] }}
835
839
  */
836
- export function discoverConfiguredMcpServers(cwd, { configPath = defaultClaudeConfigPath() } = {}) {
837
- const { sources, warnings } = readMcpSourcesInPrecedenceOrder(cwd, configPath)
840
+ export function discoverConfiguredMcpServers(cwd, { configPath = defaultClaudeConfigPath(), includeProjectFile = true } = {}) {
841
+ const { sources, warnings } = readMcpSourcesInPrecedenceOrder(cwd, configPath, { includeProjectFile })
838
842
  const byName = new Map()
839
843
  for (const { mcpServers, source } of sources) {
840
844
  for (const name of collectConfiguredNames(mcpServers, { warnings, source })) {
@@ -71,7 +71,7 @@
71
71
  * iteration can add expiry timestamps without breaking the file format.
72
72
  */
73
73
 
74
- import { createHash } from 'node:crypto'
74
+ import { createHash, randomBytes } from 'node:crypto'
75
75
  import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync, chmodSync, unlinkSync } from 'node:fs'
76
76
  import { dirname } from 'node:path'
77
77
  import { configPath } from './config-dir.js'
@@ -160,7 +160,7 @@ function sanitizeTrustUrl(url) {
160
160
  }
161
161
  }
162
162
 
163
- function sha256Hex(input) {
163
+ export function sha256Hex(input) {
164
164
  return createHash('sha256').update(input, 'utf8').digest('hex')
165
165
  }
166
166
 
@@ -172,7 +172,7 @@ function sha256Hex(input) {
172
172
  * component value containing a separator, quote, NUL or newline cannot be made to
173
173
  * straddle a field boundary and collide with a different component split.
174
174
  */
175
- function canonicalJson(value) {
175
+ export function canonicalJson(value) {
176
176
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`
177
177
  if (value !== null && typeof value === 'object') {
178
178
  return `{${Object.keys(value)
@@ -351,6 +351,36 @@ export function loadTrustStore(filePath = defaultTrustStorePath(), { log } = {})
351
351
  }
352
352
  }
353
353
 
354
+ /**
355
+ * Write `content` to `filePath` with mode 0600 via temp + rename, so a crash
356
+ * mid-write cannot leave a half-written trust file. Creates the parent dir
357
+ * (0700) when missing.
358
+ *
359
+ * #4463: when renameSync throws (cross-device link, FS quota, ACL) the temp file
360
+ * would otherwise be left behind. Unlink it on the failure path and re-throw the
361
+ * ORIGINAL rename error so the caller sees the real failure rather than a
362
+ * cleanup-side ENOENT. The cleanup unlink swallows its own errors (the temp may
363
+ * already be gone if the rename partially succeeded or the FS removed it).
364
+ */
365
+ export function writeFileAtomic0600(filePath, content, beforeRename) {
366
+ const dir = dirname(filePath)
367
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 })
368
+ // A unique temp name (pid + random) opened O_EXCL: a concurrent writer in another
369
+ // process cannot share or clobber it, and a planted file or symlink at the name is
370
+ // refused rather than followed.
371
+ const tmp = `${filePath}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`
372
+ try {
373
+ writeFileSync(tmp, content, { mode: 0o600, flag: 'wx' })
374
+ try { chmodSync(tmp, 0o600) } catch {}
375
+ // Last check before the file replaces the target; throwing abandons the write.
376
+ if (beforeRename) beforeRename()
377
+ renameSync(tmp, filePath)
378
+ } catch (err) {
379
+ try { unlinkSync(tmp) } catch {}
380
+ throw err
381
+ }
382
+ }
383
+
354
384
  /**
355
385
  * Append a trust decision. Idempotent — re-recording an already-trusted
356
386
  * tuple is a no-op (no duplicate entries). Writes via temp + rename so a
@@ -366,23 +396,7 @@ export function recordTrust(server, filePath = defaultTrustStorePath()) {
366
396
  // and of the raw url are written — no argv element, env value, header value or
367
397
  // url credential ever reaches disk.
368
398
  entries.push({ ...trustKeyComponents(server), key, trustedAt: new Date().toISOString() })
369
- const dir = dirname(filePath)
370
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 })
371
- const tmp = `${filePath}.tmp`
372
- writeFileSync(tmp, JSON.stringify({ trustedTuples: entries }, null, 2), { mode: 0o600 })
373
- try { chmodSync(tmp, 0o600) } catch {}
374
- // #4463: when renameSync throws (cross-device link, FS quota, ACL) the
375
- // temp file would otherwise be left behind. Unlink it on the failure
376
- // path and re-throw the ORIGINAL rename error so the caller sees the
377
- // real failure rather than a cleanup-side ENOENT. The cleanup unlink
378
- // swallows its own errors (the temp may already be gone if the rename
379
- // partially succeeded or the FS removed it).
380
- try {
381
- renameSync(tmp, filePath)
382
- } catch (err) {
383
- try { unlinkSync(tmp) } catch {}
384
- throw err
385
- }
399
+ writeFileAtomic0600(filePath, JSON.stringify({ trustedTuples: entries }, null, 2))
386
400
  return loadTrustStore(filePath)
387
401
  }
388
402