@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
@@ -37,6 +37,7 @@ import {
37
37
  } from './role-prompts.js'
38
38
  import { createGitOps } from './git-ops.js'
39
39
  import { TurnError } from './turn-driver.js'
40
+ import { hasSpend } from './run-record.js'
40
41
  import { recordToRunSummary, recordToRunDetail, gateToWire } from './to-wire.js'
41
42
  import { buildRunReport, renderReportMarkdown } from './run-report.js'
42
43
 
@@ -87,12 +88,11 @@ const AUDIT_ELIGIBLE_PROVIDERS = new Set(['claude-sdk', 'claude-byok', 'codex'])
87
88
  // names the failure; a Stop the SDK answers with an `aborted_*` result is
88
89
  // marked by BaseSession.emit for every result whose turnOutcome is `stopped`.
89
90
  //
90
- // NOT CLOSED — codex app-server. It ends an interrupted turn with
91
- // `turn/completed`, which `_finishTurn` reports as a normal result without
92
- // reading `turn.status` (the protocol's TurnStatus has an `interrupted` value).
93
- // Whether the real binary answers `turn/interrupt` that way is unverified
94
- // against a live process (#7072 follow-up), so an operator Stop on a codex
95
- // architect session may still settle as a completed turn.
91
+ // codex app-server (#9241): `_finishTurn` now reads `turn.status` and reports an
92
+ // `interrupted` turn as a `stopped` result, which closes this the same way. The
93
+ // `turn/completed {status: 'interrupted'}` answer is documented by OpenAI but not
94
+ // pinned against a live binary here (#7072 follow-up), so an operator Stop on a
95
+ // codex architect session could still settle as a completed turn if it differs.
96
96
  //
97
97
  // So this set means "vetted to not kill the NEXT turn", and — for claude-sdk and
98
98
  // claude-byok — "cannot report an interrupted turn as complete". Anything outside
@@ -812,16 +812,45 @@ export class OrchestrationManager extends EventEmitter {
812
812
  let attempt = 0
813
813
  let currentPrompt = prompt
814
814
  let lastError = null
815
- while (attempt <= this._cfg.maxParseRetries) {
816
- const { text, result } = await this._driver.driveTurn(sessionId, currentPrompt, { label: turnLabel, timeoutMs: this._cfg.turnTimeoutMs })
815
+ const recordUsageUnsafe = (result, terminalEvent = 'result') => {
817
816
  const roleClass = run.ownedSessions.get(sessionId)?.role ?? null
818
817
  // dotted ledger role: architect plan/synthesis vs architect.review, worker.audit
819
818
  const ledgerRole = roleClass === 'architect'
820
819
  ? (turnLabel === 'poa_review' || turnLabel === 'result_review' ? 'architect.review' : 'architect')
821
820
  : `worker.${roleClass}`
822
821
  this._ledger.recordTurnUsage(run.runId, {
823
- subtaskId, sessionId, role: ledgerRole, turnLabel, terminalEvent: 'result', data: result,
822
+ subtaskId, sessionId, role: ledgerRole, turnLabel, terminalEvent, data: result,
824
823
  })
824
+ }
825
+ // #9147 — the ledger is bookkeeping about the turn, never the turn's outcome: a
826
+ // failed write is logged and swallowed so the TurnError being rethrown (and so
827
+ // the TURN_STOPPED -> `interrupted` subtask mapping) or the resolved result
828
+ // propagates unchanged.
829
+ const recordUsage = (result, terminalEvent = 'result') => {
830
+ try { recordUsageUnsafe(result, terminalEvent) } catch (err) {
831
+ this._log?.warn?.(`orchestration: recording ${turnLabel} usage failed: ${err?.stack || err?.message || err}`)
832
+ }
833
+ }
834
+ // Skip null/empty synthetic stalls using the same token normalization as the
835
+ // ledger reducer.
836
+ while (attempt <= this._cfg.maxParseRetries) {
837
+ let turn
838
+ try {
839
+ turn = await this._driver.driveTurn(sessionId, currentPrompt, { label: turnLabel, timeoutMs: this._cfg.turnTimeoutMs,
840
+ // #9147: spend that arrives while a TURN_TIMEOUT drains (a bare `stopped`
841
+ // carries none, see TurnDriver.driveTurn). TurnDriver delivers it at most once and never to the next turn.
842
+ onLateUsage: (result, terminalEvent) => { if (hasSpend(result)) recordUsage(result, terminalEvent) },
843
+ })
844
+ } catch (err) {
845
+ // A rejected terminal result OR error can still have spent money/tokens
846
+ // (#8554). Require TurnDriver's explicit event provenance; thrown send
847
+ // failures are not accounting evidence.
848
+ const result = err instanceof TurnError && (err.terminalEvent === 'result' || err.terminalEvent === 'error') ? err.result : null
849
+ if (hasSpend(result)) recordUsage(result, err.terminalEvent)
850
+ throw err // an interrupted decision must never enter the parse/repair path
851
+ }
852
+ const { text, result } = turn
853
+ recordUsage(result)
825
854
  try {
826
855
  return { decision: extractDecision(text, kind).decision }
827
856
  } catch (err) {
@@ -30,6 +30,8 @@
30
30
  // deleted with no observable change today. That makes the branch a guard
31
31
  // against a FUTURE allow path being added above it, and the invariant worth
32
32
  // testing is its POSITION, not its effect (see the test).
33
+ import { RESOLVED_BY } from '../permission-resolved-by.js'
34
+
33
35
  export const ALWAYS_DENY = new Set(['Task', 'Agent', 'WebFetch', 'WebSearch'])
34
36
 
35
37
  export class OrchestrationPermissionGate {
@@ -113,7 +115,8 @@ export class OrchestrationPermissionGate {
113
115
  return
114
116
  }
115
117
  try {
116
- session.respondToPermission(requestId, decision === 'allow' ? 'allow' : 'deny')
118
+ // #9119: a policy decision (the allowlist), never a person.
119
+ session.respondToPermission(requestId, decision === 'allow' ? 'allow' : 'deny', undefined, undefined, undefined, RESOLVED_BY.rule)
117
120
  } catch (err) {
118
121
  this._log?.warn?.(`permission-gate: respond failed for ${sessionId}: ${err?.message || err}`)
119
122
  }
@@ -68,6 +68,17 @@ export function normalizeUsage(usage) {
68
68
  }
69
69
  }
70
70
 
71
+ /**
72
+ * Whether a projected terminal payload reports any spend: a finite cost (zero and
73
+ * negative included) or any token count the ledger would fold (via normalizeUsage).
74
+ * The ONE spend predicate: the turn driver (which decides whether a terminal event
75
+ * uses up the single late-usage delivery) and the manager (which decides whether to
76
+ * record) must agree, or spend is dropped or never delivered (#9147).
77
+ */
78
+ export function hasSpend(result) {
79
+ return !!result && (Number.isFinite(result.cost) || Object.values(normalizeUsage(result.usage)).some((n) => n > 0))
80
+ }
81
+
71
82
  // Fold one turn's numbers into a cell in place. `cost` is the provider-reported
72
83
  // signed cost (null/undefined = unknown); `pricedCostUsd` is the server-derived
73
84
  // fallback used ONLY when cost is unknown.
@@ -63,20 +63,22 @@
63
63
  * completion, and this driver rejects it (TURN_STOPPED, or TURN_ERROR when the
64
64
  * payload also carries `failureMessage`). The flag is set by BaseSession.emit for
65
65
  * every result whose `turnOutcome` is `stopped` (the SDK's aborted_* results, an
66
- * ACP `cancelled`), by claude-byok when an interrupt lands in the tool phase, by
67
- * claude-sdk's stream-stall result and by claude-cli's synthetic interrupted
66
+ * ACP `cancelled`, and the Codex app-server's `turn/completed {status:
67
+ * 'interrupted'}`, #9241), by claude-byok when an interrupt lands in the tool phase,
68
+ * by claude-sdk's stream-stall result and by claude-cli's synthetic interrupted
68
69
  * result. It is internal: event-normalizer whitelists the result fields it puts
69
70
  * on the wire, so clients never see it.
70
71
  *
71
- * NOT covered: the Codex app-server. It ends an interrupted turn with
72
- * `turn/completed` and `_finishTurn` reports it as a normal result without
73
- * reading `turn.status` (see the comment there). Whether the real binary does
74
- * that is tracked separately; until it is pinned, an operator Stop on a codex
75
- * session can still settle as a success.
72
+ * Codex app-server: `_finishTurn` now reads `turn.status` and reports `interrupted`
73
+ * as a `stopped` result. That shape is documented by OpenAI but has not been pinned
74
+ * against a live binary in this repo's tests, so an operator Stop on a codex session
75
+ * settling as a success remains possible if the binary answers differently.
76
76
  * - Watchdog: on timeout, interrupt() the session and reject TURN_TIMEOUT.
77
77
  * - `session_destroyed` mid-turn → SESSION_GONE.
78
78
  */
79
79
 
80
+ import { hasSpend } from './run-record.js'
81
+
80
82
  export const MAX_ACCUM_BYTES = 2 * 1024 * 1024
81
83
  export const DEFAULT_TURN_TIMEOUT_MS = 30 * 60 * 1000
82
84
  // After a timeout+interrupt the mutex is held in a "draining" state until the
@@ -86,12 +88,29 @@ export const DEFAULT_TURN_TIMEOUT_MS = 30 * 60 * 1000
86
88
  export const DEFAULT_DRAIN_TIMEOUT_MS = 10 * 1000
87
89
  const TRUNCATION_MARKER = '\n…[chroxy-orch: output truncated at 2MB]…\n'
88
90
 
91
+ // Both result and error events can carry a turn's sole accounting payload.
92
+ // Preserve the same projection for either terminal event; never copy nested
93
+ // exception properties, error codes or unrelated provider metadata.
94
+ function projectTerminalUsage(data) {
95
+ return {
96
+ cost: data?.cost ?? null,
97
+ duration: data?.duration ?? null,
98
+ usage: data?.usage ?? null,
99
+ modelUsage: data?.modelUsage ?? null,
100
+ model: data?.model ?? null,
101
+ numTurns: Number.isFinite(data?.numTurns) ? data.numTurns : null,
102
+ apiDurationMs: Number.isFinite(data?.apiDurationMs) ? data.apiDurationMs : null,
103
+ }
104
+ }
105
+
89
106
  export class TurnError extends Error {
90
- constructor(code, message, { partialText = '' } = {}) {
107
+ constructor(code, message, { partialText = '', result = null, terminalEvent = null } = {}) {
91
108
  super(message || code)
92
109
  this.name = 'TurnError'
93
- this.code = code // TURN_ERROR | TURN_TIMEOUT | TURN_STOPPED | SESSION_GONE | SEND_FAILED
110
+ this.code = code // TURN_ERROR | TURN_TIMEOUT | TURN_STOPPED | SESSION_GONE | SEND_FAILED | NOT_ADMITTED
94
111
  this.partialText = partialText
112
+ this.result = result // projected terminal accounting, never thrown error metadata
113
+ this.terminalEvent = terminalEvent // result | error; null without a terminal payload
95
114
  }
96
115
  }
97
116
 
@@ -104,6 +123,15 @@ export class TurnDriver {
104
123
  if (!sessionManager || typeof sessionManager.on !== 'function') {
105
124
  throw new Error('TurnDriver requires a sessionManager EventEmitter')
106
125
  }
126
+ // #9184: the turn-driven registry is what keeps a daemon wake out of a driven
127
+ // session (#8327). A manager without it must fail HERE, not silently run
128
+ // unguarded ("cannot check" reading as "nothing to check"). There is no
129
+ // guard-free mode: every construction site passes a real SessionManager.
130
+ for (const method of ['markTurnDriven', 'releaseTurnDriven']) {
131
+ if (typeof sessionManager[method] !== 'function') {
132
+ throw new Error(`TurnDriver requires a sessionManager with ${method}() (the turn-driven registry, #8327)`)
133
+ }
134
+ }
107
135
  this._sm = sessionManager
108
136
  this._log = log
109
137
  this._defaultTimeoutMs = defaultTimeoutMs
@@ -112,6 +140,7 @@ export class TurnDriver {
112
140
  this._occupied = new Set() // sessionId -> has a turn running or reserved
113
141
  this._waiters = new Map() // sessionId -> FIFO array of { start, reject }
114
142
  this._handoff = new Set() // sessionId -> a deferred _startNext is already queued
143
+ this._late = new Map() // sessionId -> timed-out ctx still owed this frame's terminal usage (#9147)
115
144
  this._onSessionEvent = this._handleSessionEvent.bind(this)
116
145
  this._onSessionDestroyed = this._handleSessionDestroyed.bind(this)
117
146
  this._sm.on('session_event', this._onSessionEvent)
@@ -129,8 +158,9 @@ export class TurnDriver {
129
158
  const active = [...this._active.values()]
130
159
  this._waiters.clear()
131
160
  this._active.clear()
132
- this._occupied.clear()
161
+ for (const id of [...this._occupied]) this._vacate(id)
133
162
  this._handoff.clear()
163
+ this._late.clear()
134
164
  for (const w of waiters) {
135
165
  try { w.reject(new TurnError('SESSION_GONE', 'TurnDriver disposed')) } catch { /* ignore */ }
136
166
  }
@@ -151,17 +181,36 @@ export class TurnDriver {
151
181
  * tick after the prior turn releases — never inside the frame that released it
152
182
  * (_scheduleNext).
153
183
  * @returns {Promise<{ text: string, result: { cost, duration, usage, modelUsage, model, numTurns, apiDurationMs } }>}
184
+ *
185
+ * `admit` (optional, #9242): a predicate re-asked at the moment the prompt would
186
+ * actually reach the provider — when this turn starts after waiting on the
187
+ * per-session mutex, and (through the provider's flush-time admission hook,
188
+ * BaseSession `admitAtFlush`) when a provider that queued the send dispatches it.
189
+ * Anything but `true`, or a throw, means NOT admitted: the prompt is never sent
190
+ * and the turn rejects `NOT_ADMITTED`. Callers that pass none are unchanged.
191
+ *
192
+ * `onLateUsage(result, terminalEvent)` (optional, #9147): called AT MOST ONCE with the
193
+ * projected accounting of a `result`/`error` that arrives AFTER the turn already
194
+ * rejected without one — while a TURN_TIMEOUT drains (the interrupted session's
195
+ * trailing `result` is swallowed there). Without it that spend never reached the
196
+ * caller's ledger. A bare `stopped` is deliberately NOT covered: every provider
197
+ * reports an interrupted turn's accounting in a `result` BEFORE `stopped` (which
198
+ * the result path already carries), `stopped`'s own payload is never accounting,
199
+ * and a result after it in the same frame cannot be attributed. The event is
200
+ * consumed here (swallowed by the drain / dropped by the epoch guard) so it can never
201
+ * ALSO reach the next turn: the caller records it exactly once. A throw is logged.
202
+ * Callers that pass none are unchanged.
154
203
  * @throws {TurnError}
155
204
  */
156
- driveTurn(sessionId, prompt, { label = null, timeoutMs = null } = {}) {
205
+ driveTurn(sessionId, prompt, { label = null, timeoutMs = null, admit = null, onLateUsage = null } = {}) {
157
206
  if (this._disposed) return Promise.reject(new TurnError('SESSION_GONE', 'TurnDriver disposed'))
158
207
  const entry = this._sm.getSession?.(sessionId)
159
208
  if (!entry || !entry.session) return Promise.reject(new TurnError('SESSION_GONE', `session ${sessionId} not found`))
160
209
 
161
210
  return new Promise((resolve, reject) => {
162
- const start = () => this._beginTurn(sessionId, prompt, { label, timeoutMs }, resolve, reject)
211
+ const start = () => this._beginTurn(sessionId, prompt, { label, timeoutMs, admit, onLateUsage }, resolve, reject)
163
212
  if (!this._occupied.has(sessionId)) {
164
- this._occupied.add(sessionId)
213
+ this._occupy(sessionId)
165
214
  start()
166
215
  } else {
167
216
  const q = this._waiters.get(sessionId) || []
@@ -171,7 +220,12 @@ export class TurnDriver {
171
220
  })
172
221
  }
173
222
 
174
- _beginTurn(sessionId, prompt, { label, timeoutMs }, resolve, reject) {
223
+ _admitted(admit) {
224
+ if (typeof admit !== 'function') return true
225
+ try { return admit() === true } catch { return false }
226
+ }
227
+
228
+ _beginTurn(sessionId, prompt, { label, timeoutMs, admit = null, onLateUsage = null }, resolve, reject) {
175
229
  // Re-fetch the session at START time, not at driveTurn() time: a queued turn
176
230
  // may have waited behind the mutex while its session was destroyed/replaced.
177
231
  const entry = this._sm.getSession?.(sessionId)
@@ -180,6 +234,11 @@ export class TurnDriver {
180
234
  this._scheduleNext(sessionId)
181
235
  return
182
236
  }
237
+ if (!this._admitted(admit)) {
238
+ reject(new TurnError('NOT_ADMITTED', `turn for session ${sessionId} was not admitted at dispatch`))
239
+ this._scheduleNext(sessionId)
240
+ return
241
+ }
183
242
  const ctx = {
184
243
  sessionId,
185
244
  label,
@@ -189,6 +248,7 @@ export class TurnDriver {
189
248
  truncated: false,
190
249
  settled: false,
191
250
  timer: null,
251
+ onLateUsage: typeof onLateUsage === 'function' ? onLateUsage : null,
192
252
  resolve,
193
253
  reject,
194
254
  }
@@ -210,7 +270,20 @@ export class TurnDriver {
210
270
  // Fire-and-forget send; a rejection (closing socket, etc.) is SEND_FAILED —
211
271
  // NEVER leave it unhandled (an unhandled rejection crashes the daemon).
212
272
  try {
213
- const ret = entry.session.sendMessage(prompt, [], { clientMessageId: `orch-${label || 'turn'}` })
273
+ const ret = entry.session.sendMessage(prompt, [], {
274
+ clientMessageId: `orch-${label || 'turn'}`,
275
+ // #9242: a provider that QUEUES this send re-asks at flush; a refusal drops the
276
+ // prompt (never sent) and ends this turn instead of leaving it to time out.
277
+ ...(typeof admit === 'function'
278
+ ? {
279
+ admitAtFlush: () => {
280
+ const ok = this._admitted(admit)
281
+ if (!ok) this._finishTurn(ctx, () => ctx.reject(new TurnError('NOT_ADMITTED', `queued turn for session ${sessionId} was not admitted at flush`, { partialText: ctx.text() })))
282
+ return ok
283
+ },
284
+ }
285
+ : {}),
286
+ })
214
287
  if (ret && typeof ret.then === 'function') {
215
288
  ret.catch((err) => {
216
289
  this._finishTurn(ctx, () => ctx.reject(new TurnError('SEND_FAILED', (err && err.message) || 'sendMessage rejected', { partialText: ctx.text() })))
@@ -252,17 +325,43 @@ export class TurnDriver {
252
325
  const next = q.shift() // stays occupied — hand the slot to the next turn
253
326
  next.start()
254
327
  } else {
255
- this._occupied.delete(sessionId)
328
+ this._vacate(sessionId)
256
329
  this._waiters.delete(sessionId)
257
330
  }
258
331
  }
259
332
 
333
+ // #8327: `_occupied` is mirrored into the SessionManager's ONE registry, so a
334
+ // daemon wake (daemonTurnRefusal -> 'orchestrated') can see every driver's
335
+ // sessions. These two are the ONLY places that touch `_occupied` — a new
336
+ // construction site gets the registration for free, through its sessionManager.
337
+ _occupy(sessionId) {
338
+ this._occupied.add(sessionId)
339
+ try { this._sm.markTurnDriven(sessionId, this) } catch (err) { this._log?.warn?.(`TurnDriver: markTurnDriven failed: ${err?.message || err}`) }
340
+ }
341
+
342
+ _vacate(sessionId) {
343
+ this._occupied.delete(sessionId)
344
+ try { this._sm.releaseTurnDriven(sessionId, this) } catch (err) { this._log?.warn?.(`TurnDriver: releaseTurnDriven failed: ${err?.message || err}`) }
345
+ }
346
+
260
347
  _handleSessionEvent({ sessionId, event, data } = {}) {
261
348
  const ctx = this._active.get(sessionId)
262
- if (!ctx) return // epoch guard: no active/draining turn for this session → drop
349
+ if (!ctx) {
350
+ // epoch guard: no active/draining turn for this session → drop. The one
351
+ // exception is the same-frame slot of a turn that just rejected without its
352
+ // accounting (#9147): its own trailing result/error is owed to that turn.
353
+ const late = this._late.get(sessionId)
354
+ if (late && (event === 'result' || event === 'error')) this._reportLateUsage(late, event, data)
355
+ return
356
+ }
263
357
  if (ctx.draining) {
264
358
  // A settled-but-draining turn (post-timeout). Swallow its trailing output;
265
359
  // a terminal event confirms the session stopped → release the mutex.
360
+ if (event === 'result' || event === 'error') this._reportLateUsage(ctx, event, data)
361
+ // `stream_end` (or a terminal event with no spend, e.g. a BYOK non-fatal
362
+ // `error`) ends the drain BEFORE the interrupted turn's spend-bearing `result`
363
+ // in the same frame: keep that frame's slot open so the spend is not dropped.
364
+ if (event === 'stream_end') this._armLate(ctx)
266
365
  if (event === 'result' || event === 'error' || event === 'stopped' || event === 'stream_end') {
267
366
  this._endDrain(ctx)
268
367
  }
@@ -286,6 +385,7 @@ export class TurnDriver {
286
385
  break
287
386
  }
288
387
  case 'result': {
388
+ const result = projectTerminalUsage(data)
289
389
  // #7072 — a terminal-looking `result` the provider marked `interrupted:
290
390
  // true` is terminal but NOT a success: the turn was cut short (a Stop that
291
391
  // the provider answered with a normal result, a BYOK interrupt in the tool
@@ -300,29 +400,21 @@ export class TurnDriver {
300
400
  const partialText = this._assembleText(ctx)
301
401
  const failure = typeof data.failureMessage === 'string' && data.failureMessage ? data.failureMessage : null
302
402
  this._finishTurn(ctx, () => ctx.reject(failure
303
- ? new TurnError('TURN_ERROR', failure, { partialText })
304
- : new TurnError('TURN_STOPPED', 'turn interrupted before completing', { partialText })))
403
+ ? new TurnError('TURN_ERROR', failure, { partialText, result, terminalEvent: 'result' })
404
+ : new TurnError('TURN_STOPPED', 'turn interrupted before completing', { partialText, result, terminalEvent: 'result' })))
305
405
  break
306
406
  }
307
- // Forward the FULL terminal usage payload, not just cost/duration/usage:
308
- // the ledger's recordTurnUsage keys off modelUsage/model/numTurns/
309
- // apiDurationMs for per-model attribution (#6692). Dropping them here
310
- // would silently collapse every metered run to a single unknown model.
311
- const result = {
312
- cost: data?.cost ?? null,
313
- duration: data?.duration ?? null,
314
- usage: data?.usage ?? null,
315
- modelUsage: data?.modelUsage ?? null,
316
- model: data?.model ?? null,
317
- numTurns: Number.isFinite(data?.numTurns) ? data.numTurns : null,
318
- apiDurationMs: Number.isFinite(data?.apiDurationMs) ? data.apiDurationMs : null,
319
- }
320
407
  const text = this._assembleText(ctx)
321
408
  this._finishTurn(ctx, () => ctx.resolve({ text, result }))
322
409
  break
323
410
  }
324
411
  case 'error': {
325
- this._finishTurn(ctx, () => ctx.reject(new TurnError('TURN_ERROR', (data && data.message) || 'session error', { partialText: this._assembleText(ctx) })))
412
+ // BYOK can emit error instead of result after completed rounds. Its
413
+ // top-level partial spend is genuine terminal accounting (#8554), unlike
414
+ // arbitrary properties on a thrown/rejected sendMessage exception.
415
+ this._finishTurn(ctx, () => ctx.reject(new TurnError('TURN_ERROR', (data && data.message) || 'session error', {
416
+ partialText: this._assembleText(ctx), result: projectTerminalUsage(data), terminalEvent: 'error',
417
+ })))
326
418
  break
327
419
  }
328
420
  case 'stopped': {
@@ -351,6 +443,32 @@ export class TurnDriver {
351
443
  }
352
444
  }
353
445
 
446
+ // #9147 — a turn that rejected WITHOUT a terminal accounting payload (a TURN_TIMEOUT
447
+ // draining) may still be owed its session's trailing result/error. Hold a slot for
448
+ // the rest of the current synchronous frame only — cleared on the same tick the mutex
449
+ // hand-off happens, so it can never see the next turn's events.
450
+ _armLate(ctx) {
451
+ if (!ctx.onLateUsage) return
452
+ // Already armed this frame: its one nextTick clear is queued; do not queue another.
453
+ if (this._late.get(ctx.sessionId) === ctx) return
454
+ this._late.set(ctx.sessionId, ctx)
455
+ process.nextTick(() => { if (this._late.get(ctx.sessionId) === ctx) this._late.delete(ctx.sessionId) })
456
+ }
457
+
458
+ _reportLateUsage(ctx, event, data) {
459
+ if (!ctx.onLateUsage) return
460
+ const projected = projectTerminalUsage(data)
461
+ // A terminal event with no spend does not use up the single delivery: a
462
+ // spend-bearing result in the same frame is still owed to this turn.
463
+ if (!hasSpend(projected)) { this._armLate(ctx); return }
464
+ // Exactly once: delivery closes the same-frame slot and the drain-ending event
465
+ // removed the ctx from _active, so no later event can reach this ctx again.
466
+ if (this._late.get(ctx.sessionId) === ctx) this._late.delete(ctx.sessionId)
467
+ try { ctx.onLateUsage(projected, event) } catch (err) {
468
+ this._log?.warn?.(`TurnDriver: onLateUsage failed: ${err?.message || err}`)
469
+ }
470
+ }
471
+
354
472
  _handleSessionDestroyed({ sessionId } = {}) {
355
473
  const ctx = this._active.get(sessionId)
356
474
  if (!ctx || ctx.settled) return
@@ -232,13 +232,13 @@ function isUnder(path, base) {
232
232
  * re-verify before signalling), cwdOf, kill, uid, selfPid, platform, realpath,
233
233
  * plus (when `cwdOf` is not overridden) `exists`/`resolveBinary`/`execFileSync`/
234
234
  * `readlink` consumed by the default lsof/procfs resolution (#8083)
235
- * @returns {{ scanned: number, candidates: number, unresolved: number, reaped: object[], skipped: object[], error: string|null, errorCode: string|null }}
235
+ * @returns {{ scanned: number, candidates: number, unresolved: number, reaped: object[], skipped: object[], error: string|null, errorCode: string|null, errorStage: 'list'|'cwd'|null }}
236
236
  */
237
237
  export function sweepOrphans({ worktreeBase, minAgeMs = DEFAULT_MIN_AGE_MS, deps = {} } = {}) {
238
- const report = { scanned: 0, candidates: 0, unresolved: 0, reaped: [], skipped: [], error: null, errorCode: null }
238
+ const report = { scanned: 0, candidates: 0, unresolved: 0, reaped: [], skipped: [], error: null, errorCode: null, errorStage: null }
239
239
  const platform = deps.platform || process.platform
240
240
  if (platform === 'win32') return report
241
- if (!worktreeBase) { report.error = 'no worktree base'; return report }
241
+ if (!worktreeBase) { report.error = 'no worktree base'; report.errorStage = 'list'; return report }
242
242
 
243
243
  const listProcesses = deps.listProcesses || defaultListProcesses
244
244
  const cwdOf = deps.cwdOf || defaultCwdOf
@@ -248,7 +248,18 @@ export function sweepOrphans({ worktreeBase, minAgeMs = DEFAULT_MIN_AGE_MS, deps
248
248
  // As root the uid predicate matches EVERY process, and inside a container
249
249
  // pid 1 is a live entrypoint whose children are owned, not orphaned — the
250
250
  // remaining cwd check would be the only guard. Refuse rather than widen.
251
- if (uid === 0) { report.error = 'running as root: the uid predicate cannot distinguish orphans'; return report }
251
+ if (uid === 0) { report.error = 'running as root: the uid predicate cannot distinguish orphans'; report.errorStage = 'list'; return report }
252
+ // As pid 1 (a container run without `--init`, e.g. `CHROXY_TUNNEL=none`
253
+ // makes the daemon its own entrypoint) every direct child of the daemon has
254
+ // ppid 1, so a LIVE session child satisfies the whole orphan predicate and
255
+ // the re-verification (still ppid 1) would pass it. Refuse rather than kill
256
+ // live children (#9248).
257
+ if (selfPid === 1) {
258
+ report.error = 'running as pid 1: every direct child has ppid 1, so orphans cannot be told apart from live children (run the container with --init, or compose `init: true`)'
259
+ report.errorCode = 'PID_ONE'
260
+ report.errorStage = 'list'
261
+ return report
262
+ }
252
263
  // lsof and /proc report REAL paths; compare against the real base, or a
253
264
  // symlink anywhere in the chain (/tmp → /private/tmp, a linked $HOME) makes
254
265
  // every comparison fail and the sweep a permanent silent no-op.
@@ -259,6 +270,7 @@ export function sweepOrphans({ worktreeBase, minAgeMs = DEFAULT_MIN_AGE_MS, deps
259
270
  let rows
260
271
  try { rows = parseProcessTable(listProcesses()) } catch (err) {
261
272
  report.error = `process listing failed: ${(err && err.message) || err}`
273
+ report.errorStage = 'list'
262
274
  return report
263
275
  }
264
276
  report.scanned = rows.length
@@ -281,6 +293,7 @@ export function sweepOrphans({ worktreeBase, minAgeMs = DEFAULT_MIN_AGE_MS, deps
281
293
  // nothing this tick.
282
294
  report.error = `cwd lookup unavailable: ${(err && err.message) || err}`
283
295
  report.errorCode = (err && err.code) || null
296
+ report.errorStage = 'cwd'
284
297
  return report
285
298
  }
286
299
 
@@ -301,6 +314,7 @@ export function sweepOrphans({ worktreeBase, minAgeMs = DEFAULT_MIN_AGE_MS, deps
301
314
  let recheck
302
315
  try { recheck = new Map(parseProcessTable(listProcesses()).map((r) => [r.pid, r])) } catch (err) {
303
316
  report.error = `re-verification listing failed: ${(err && err.message) || err}`
317
+ report.errorStage = 'cwd'
304
318
  return report
305
319
  }
306
320
 
@@ -327,6 +341,9 @@ function isEnabled(config) {
327
341
  return config.orphanReap.enabled !== false
328
342
  }
329
343
 
344
+ /** At most one ok-sweep summary per this interval (#8232). */
345
+ const OK_SUMMARY_INTERVAL_MS = 60 * 60 * 1000
346
+
330
347
  /**
331
348
  * Run one sweep against the configured worktree root and log a manifest.
332
349
  * Returns null when disabled by config or on Windows.
@@ -334,12 +351,14 @@ function isEnabled(config) {
334
351
  * @param {object} config - merged server config
335
352
  * @param {{ info: Function, warn: Function }} log
336
353
  * @param {object} [deps] - sweepOrphans seams plus `worktreeBase`. Also the
337
- * log-dedup carrier for the LSOF_NOT_FOUND case (#8083) below: `deps` is the
338
- * SAME object across every tick of `startPeriodicOrphanReap`'s interval (its
339
- * closure captures it once), so a flag set here on first sight persists for
340
- * the rest of the daemon's life without any new module/closure-level state.
341
- * A one-off caller that doesn't pass its own `deps` gets a fresh `{}` each
342
- * call, so it always logs — exactly like today, for every OTHER error kind.
354
+ * carrier for the cannot-check de-duplication and the hourly ok-sweep
355
+ * heartbeat (#8083, #8232): `deps` is the SAME object across every tick of
356
+ * `startPeriodicOrphanReap`'s interval (its closure captures it once), so
357
+ * state set here persists for the daemon's life without any new
358
+ * module/closure-level state. `deps.now` is an injectable clock. A one-off
359
+ * caller that doesn't pass its own `deps` gets a fresh `{}` each call, so it
360
+ * always logs. A sweep that THROWS is not de-duplicated here: the catch in
361
+ * `startPeriodicOrphanReap` warns on every occurrence (loud by design).
343
362
  */
344
363
  export function maybeReapOrphans(config, log, deps = {}) {
345
364
  if (!isEnabled(config)) return null
@@ -349,20 +368,58 @@ export function maybeReapOrphans(config, log, deps = {}) {
349
368
  const worktreeBase = deps.worktreeBase || configPath('worktrees')
350
369
  const report = sweepOrphans({ worktreeBase, minAgeMs, deps })
351
370
  if (report.error) {
352
- // Genuinely-missing lsof is a durable host fact, not a transient hiccup —
353
- // warning every 5 minutes forever is pure log spam once it's been said
354
- // once. Every OTHER "cannot check" reason still warns on every sweep,
355
- // unchanged (a real, possibly-transient problem must stay loud).
356
- if (report.errorCode === 'LSOF_NOT_FOUND') {
357
- if (!deps.lsofUnavailableWarned) {
358
- log.warn(`orphan-reaper: sweep skipped — ${report.error} (further occurrences suppressed until restart)`)
359
- deps.lsofUnavailableWarned = true
360
- }
371
+ // De-duplicate EVERY cannot-check reason per daemon (#8083, #8232): a
372
+ // host fact (no lsof, no `ps` in a slim image) is identical on every
373
+ // 5-minute sweep, so repeating the warning forever is pure spam. A reason
374
+ // still surfaces on every NEW occurrence — the first sighting, a
375
+ // different reason, or the same one returning after a successful sweep —
376
+ // and recovery is announced once below.
377
+ // Key on code AND message so two distinct failures sharing an err.code
378
+ // never collapse into one silenced warning; varying message data can only
379
+ // cause an extra warning, never silence.
380
+ const key = `${report.errorCode || ''}:${report.error}`
381
+ if (deps.skipWarnedKey !== key) {
382
+ log.warn(`orphan-reaper: sweep skipped — ${report.error} (repeats suppressed until the reason changes or a sweep succeeds)`)
383
+ deps.skipWarnedKey = key
384
+ deps.skipLabel = report.error
385
+ deps.skipStage = report.errorStage
386
+ deps.skipSuppressed = 0
361
387
  } else {
362
- log.warn(`orphan-reaper: sweep skipped — ${report.error}`)
388
+ deps.skipSuppressed = (deps.skipSuppressed || 0) + 1
363
389
  }
364
390
  return report
365
391
  }
392
+ // An error-free sweep only proves a stage that actually ran: the process
393
+ // listing runs every sweep, but the cwd lookup (lsof) runs only when there
394
+ // are candidates. A zero-candidate sweep must not clear a cwd-stage reason.
395
+ if (deps.skipWarnedKey !== undefined && (deps.skipStage !== 'cwd' || report.candidates > 0)) {
396
+ const n = (deps.skipSuppressed || 0) + 1
397
+ log.info(`orphan-reaper: sweeps resumed after ${n} skipped (${deps.skipLabel})`)
398
+ deps.skipWarnedKey = undefined
399
+ deps.skipLabel = undefined
400
+ deps.skipStage = undefined
401
+ deps.skipSuppressed = 0
402
+ }
403
+ // Positive signal (#8232): without it a healthy reaper and a dead one look
404
+ // the same in the log. First ok sweep says so; then at most one summary/hour.
405
+ // While a reason is still outstanding the line names it instead of "ok".
406
+ const nowMs = (deps.now || Date.now)()
407
+ deps.okSweepsSinceSummary = (deps.okSweepsSinceSummary || 0) + 1
408
+ const counts = `${report.scanned} scanned, ${report.candidates} candidate(s), ${report.reaped.length} reaped`
409
+ const outstanding = deps.skipWarnedKey !== undefined ? ` (${deps.skipStage} check still unavailable: ${deps.skipLabel})` : ''
410
+ if (deps.lastOkSummaryAt === undefined) {
411
+ log.info(outstanding
412
+ ? `orphan-reaper: sweep NOT fully ok${outstanding} — ${counts}`
413
+ : `orphan-reaper: sweep ok — ${counts}`)
414
+ deps.lastOkSummaryAt = nowMs
415
+ deps.okSweepsSinceSummary = 0
416
+ } else if (nowMs - deps.lastOkSummaryAt >= OK_SUMMARY_INTERVAL_MS) {
417
+ log.info(outstanding
418
+ ? `orphan-reaper: ${deps.okSweepsSinceSummary} sweep(s) since last summary, NOT fully ok${outstanding} (last: ${counts})`
419
+ : `orphan-reaper: ${deps.okSweepsSinceSummary} sweep(s) ok since last summary (last: ${counts})`)
420
+ deps.lastOkSummaryAt = nowMs
421
+ deps.okSweepsSinceSummary = 0
422
+ }
366
423
  for (const r of report.reaped) {
367
424
  log.warn(`orphan-reaper: killed pid ${r.pid} (ppid 1, ${Math.round(r.ageMs / 60000)} min, cwd ${r.cwd}): ${r.args}`)
368
425
  }
@@ -30,13 +30,13 @@ export const BOUND_OUTGOING_DENIED = Object.freeze([
30
30
  'daemon_update_status', 'delete_archived_session_result', 'directory_listing',
31
31
  'emulator_action_ack', 'emulator_status_snapshot', 'environment_created',
32
32
  'environment_destroyed', 'environment_error', 'environment_info', 'environment_list',
33
- 'external_sessions_snapshot', 'failed_restore_history', 'failed_restores_list',
33
+ 'external_sessions_snapshot', 'failed_restore_history', 'failed_restores_list', 'folder_trust_result',
34
34
  'git_commit_result', 'git_create_pr_result', 'git_repo_check_result', 'github_webhook_config',
35
35
  'host_prune_action_ack', 'host_prune_status_snapshot', 'host_status_snapshot',
36
36
  'integration_action_ack', 'integration_status_snapshot', 'mailbox_status_snapshot',
37
37
  'monthly_budget', 'notification_prefs', 'orchestration_action_ack', 'orchestration_run_delta',
38
38
  'orchestration_run_snapshot', 'orchestration_runs_snapshot', 'pair_pending',
39
- 'pair_request_pending', 'pair_resolved', 'repo_events_delta', 'repo_events_snapshot',
39
+ 'pair_request_pending', 'pair_resolved', 'principal_admin_result', 'principal_event', 'principal_events_page', 'principal_gap', 'principal_live_fence', 'principal_pending_permissions_result', 'principal_sessions_snapshot_result', 'principal_subscribed', 'repo_events_delta', 'repo_events_snapshot',
40
40
  'repo_runtime_config_snapshot', 'restore_archived_session_result', 'retry_failed_restore_result',
41
41
  'runner_status_snapshot', 'scheduled_tasks', 'session_archive_policy_result',
42
42
  'session_preset_snapshot', 'shell_pending_approval', 'simulator_action_ack',
@@ -47,7 +47,7 @@ export const BOUND_OUTGOING_DENIED = Object.freeze([
47
47
  ])
48
48
 
49
49
  /** @type {readonly string[]} */
50
- export const BOUND_OUTGOING_REDACTED = Object.freeze(['auth_bootstrap', 'auth_ok', 'cost_update', 'mcp_servers'])
50
+ export const BOUND_OUTGOING_REDACTED = Object.freeze(['auth_bootstrap', 'auth_ok', 'cost_update', 'folder_trust_state', 'mcp_servers'])
51
51
 
52
52
  /** @type {readonly string[]} */
53
53
  export const BOUND_OUTGOING_ALLOWED = Object.freeze([
@@ -72,7 +72,7 @@ export const BOUND_OUTGOING_ALLOWED = Object.freeze([
72
72
  'session_updated', 'session_usage', 'session_warning', 'skill_activated', 'skill_changed',
73
73
  'skill_deactivated', 'skills_list', 'stdin_dropped_totals', 'stream_delta', 'stream_end',
74
74
  'stream_start', 'summarize_session_result', 'symbol_location', 'symbols_snapshot',
75
- 'terminal_output', 'terminal_size', 'thinking_level_changed', 'tool_input_delta', 'tool_result',
75
+ 'terminal_output', 'terminal_size', 'thinking_level_changed', 'tool_input_backfill', 'tool_input_delta', 'tool_result',
76
76
  'tool_start', 'tunnel_url_changed', 'user_question', 'write_file_result',
77
77
  ])
78
78
 
@@ -155,6 +155,12 @@ export function frameForBoundClient(message) {
155
155
  }),
156
156
  }
157
157
  }
158
+ if (type === 'folder_trust_state') {
159
+ // The summary lists the commands a folder's settings would run: the
160
+ // owner's to review, not this connection's. The status alone passes.
161
+ const { summary: _s, digest: _d, ...rest } = message
162
+ return rest
163
+ }
158
164
  if (type === 'cost_update') {
159
165
  // The host-wide running total is not this session's cost.
160
166
  const { totalCost: _t, ...rest } = message