@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
@@ -29,12 +29,14 @@ import {
29
29
  import { listProviders, getProvider, resolveDaemonDefaultProvider } from '../providers.js'
30
30
  import { isProviderModelUnrestricted } from '../config.js'
31
31
  import { getProviderPermissionModeSupport } from '../permission-mode-support.js'
32
- import { createLogger, loggerForSession, sessionLogger } from '../logger.js'
32
+ import { createLogger, loggableValue, loggerForSession, sessionLogger } from '../logger.js'
33
33
  import { isBoundClient } from '../environments/authority.js'
34
+ import { isPrincipalClient, refusePrincipalHandler, sendPrincipalRefusal } from '../principal-policy.js'
34
35
  // Credential + skills handlers were split into sibling modules (audit P2-4);
35
36
  // their maps are composed into settingsHandlers below.
36
37
  import { credentialHandlers } from './credential-handlers.js'
37
38
  import { skillsHandlers } from './skills-handlers.js'
39
+ import { folderTrustHandlers } from './folder-trust-handlers.js'
38
40
  import {
39
41
  PER_SESSION_SETTINGS,
40
42
  buildPerSessionSettingHandler,
@@ -190,13 +192,34 @@ function handleSetModel(ws, client, msg, ctx) {
190
192
  return
191
193
  }
192
194
  if (providerAllowed) {
193
- if (!providerAllowed.includes(msg.model)) {
195
+ // #9139: the picker offers a models.json overlay row under its short id
196
+ // (`id`) while the allowlist holds TARGETS (`fullId`). Resolve an
197
+ // off-list id through this provider's roster and accept it only when the
198
+ // row's target is on the list; everything downstream (setModel, the
199
+ // broadcast) then speaks the target, which is also what the endpoint
200
+ // must receive — it would 404 an alias.
201
+ let requested = msg.model
202
+ if (!providerAllowed.includes(requested)) {
203
+ let row = null
204
+ try {
205
+ row = getRosterModelRow(entry.provider, requested)
206
+ } catch (err) {
207
+ // Roster unavailable: cannot resolve an alias, so refuse below —
208
+ // but leave a trace (#9153) so a broken lookup is not silent.
209
+ log.warn(`set_model roster lookup failed for provider '${entry.provider}' model ${loggableValue(msg.model)}: ${loggableValue(String(err?.message || err))}`)
210
+ }
211
+ // The re-check below is what refuses a target that is off the list.
212
+ if (row && typeof row.fullId === 'string') {
213
+ requested = row.fullId
214
+ }
215
+ }
216
+ if (!providerAllowed.includes(requested)) {
194
217
  // #4828: session-scoped — modelSessionId identifies the affected
195
218
  // session. Legacy single-session adapters may surface an empty
196
219
  // sessionId, so fall back to the module-level `log` rather than
197
220
  // throwing inside loggerForSession (matches the input-handlers
198
221
  // pattern from #4823).
199
- ;sessionLogger(modelSessionId).warn(`Rejected model '${msg.model}' on ${entry.provider} session ${modelSessionId} from ${client.id}`)
222
+ ;sessionLogger(modelSessionId).warn(`Rejected model ${loggableValue(msg.model)} on ${entry.provider} session ${modelSessionId} from ${client.id}`)
200
223
  sendError(
201
224
  ws,
202
225
  msg?.requestId,
@@ -208,18 +231,18 @@ function handleSetModel(ws, client, msg, ctx) {
208
231
  return
209
232
  }
210
233
  // #4828: session-scoped (single-session fallback as above).
211
- ;sessionLogger(modelSessionId).info(`Model change from ${client.id} on session ${modelSessionId}: ${msg.model}`)
234
+ ;sessionLogger(modelSessionId).info(`Model change from ${client.id} on session ${modelSessionId}: ${requested}`)
212
235
  // #5696: only broadcast when setModel() reports the change landed.
213
- if (!entry.session.setModel(msg.model)) {
214
- ;sessionLogger(modelSessionId).warn(`set_model rejected (session busy or no-op): requested ${msg.model}`)
215
- sendError(ws, msg?.requestId, 'MODEL_NOT_APPLIED', `Model change to '${msg.model}' was not applied (session busy or already on that model).`, undefined, ctx)
236
+ if (!entry.session.setModel(requested)) {
237
+ ;sessionLogger(modelSessionId).warn(`set_model rejected (session busy or no-op): requested ${requested}`)
238
+ sendError(ws, msg?.requestId, 'MODEL_NOT_APPLIED', `Model change to '${requested}' was not applied (session busy or already on that model).`, undefined, ctx)
216
239
  return
217
240
  }
218
241
  // Non-Claude providers use opaque model IDs (e.g. 'gemini-2.5-pro') —
219
242
  // broadcast them verbatim. toShortModelId() is a Claude-specific
220
243
  // alias collapse (claude-sonnet-4-6 → sonnet) and returns the input
221
244
  // unchanged for non-Claude IDs, so applying it uniformly is safe.
222
- ctx.transport.broadcastToSession(modelSessionId, { type: 'model_changed', model: toShortModelId(msg.model) })
245
+ ctx.transport.broadcastToSession(modelSessionId, { type: 'model_changed', model: toShortModelId(requested) })
223
246
  return
224
247
  }
225
248
  // Fall through to the legacy global allowlist when the provider hasn't
@@ -448,6 +471,9 @@ function handleSetPermissionMode(ws, client, msg, ctx) {
448
471
  }
449
472
 
450
473
  function handlePermissionResponse(ws, client, msg, ctx) {
474
+ // Principal branch, FIRST: a principal may answer only through principalMaySee
475
+ // (deny only, S15) and never reaches the dev-preview consent check or the host path.
476
+ if (isPrincipalClient(client)) return refusePrincipalHandler(ws, client, msg, ctx, 'answer')
451
477
  const { requestId, decision } = msg
452
478
  if (!requestId || !decision) return
453
479
  if (ctx.services?.devPreview?.respondToConsent(client, msg)) return
@@ -999,6 +1025,12 @@ function handleSetPromptEvaluatorSkipPattern(ws, client, msg, ctx) {
999
1025
  }
1000
1026
 
1001
1027
  function handleSetPermissionRules(ws, client, msg, ctx) {
1028
+ // Independent principal gate: permission rules are never delegated to an
1029
+ // agent principal, whatever its binding.
1030
+ if (isPrincipalClient(client)) {
1031
+ sendPrincipalRefusal(ws, client, msg, ctx, 'handler')
1032
+ return
1033
+ }
1002
1034
  // Bound (pairing-issued) session tokens are scoped to USE existing
1003
1035
  // permissions, never to escalate — the same principle that blocks them from
1004
1036
  // flipping to auto mode in handleSetPermissionMode. Permission rules can
@@ -1600,6 +1632,8 @@ export const settingsHandlers = {
1600
1632
  // Skills + credential handlers split into sibling modules (audit P2-4).
1601
1633
  ...skillsHandlers,
1602
1634
  ...credentialHandlers,
1635
+ // Per-folder trust for project settings (primary-only; see folder-trust-handlers.js).
1636
+ ...folderTrustHandlers,
1603
1637
  }
1604
1638
 
1605
1639
  export { ELIGIBLE_TOOLS, NEVER_AUTO_ALLOW }
@@ -22,6 +22,7 @@ import {
22
22
  import { realpathSync, readdirSync, statSync } from 'fs'
23
23
  import { loggerForSession } from '../logger.js'
24
24
  import { isBoundClient } from '../environments/authority.js'
25
+ import { isPrincipalClient, sendPrincipalRefusal } from '../principal-policy.js'
25
26
 
26
27
  // #3250: strict ISO-8601 datetime gate matching the shape z.string().datetime()
27
28
  // accepts. Used by handleListSkills to drop malformed timestamps from a
@@ -49,6 +50,12 @@ function _isIsoDatetime(s) {
49
50
  * early-return); false to proceed. See docs/security/bearer-token-authority.md.
50
51
  */
51
52
  function rejectSkillTrustIfBound(ws, client, msg, ctx) {
53
+ // Independent principal gate: skill trust is host-executable code and never
54
+ // delegated to an agent principal, whatever its binding.
55
+ if (isPrincipalClient(client)) {
56
+ sendPrincipalRefusal(ws, client, msg, ctx, 'handler')
57
+ return true
58
+ }
52
59
  if (!client?.boundSessionId) return false
53
60
  loggerForSession('ws', client.boundSessionId).warn(`Client ${client.id} (bound to ${client.boundSessionId}) attempted to modify skill trust (${msg?.type}) — rejected`)
54
61
  sendError(ws, msg?.requestId, 'SKILL_TRUST_FORBIDDEN_BOUND_CLIENT',
@@ -49,6 +49,14 @@ export function historyWireEntry(raw, history) {
49
49
  const value = entry[key]
50
50
  if (typeof value === 'string') {
51
51
  entry[key] = shorten(value)
52
+ // #9024: a reply's split points index its text. Past the clip they point at text the
53
+ // page no longer carries (or into the marker), and one such point makes a client drop
54
+ // the whole list: keep those inside what is kept, and none if none remain.
55
+ if (key === 'content' && value.length > max && Array.isArray(entry.splits)) {
56
+ const kept = entry.splits.filter((split) => split && typeof split.at === 'number' && split.at < max)
57
+ if (kept.length > 0) entry.splits = kept
58
+ else delete entry.splits
59
+ }
52
60
  } else if (value && typeof value === 'object') {
53
61
  let serialized
54
62
  try { serialized = JSON.stringify(value) } catch { serialized = '[unserializable]' }
@@ -210,6 +210,71 @@ export function getJsonlMtime(filePath) {
210
210
  }
211
211
  }
212
212
 
213
+ /**
214
+ * Harness-written `user` string entries that no person typed (#8951): background
215
+ * task results, CI monitor events, injected reminders, local-command wrappers and
216
+ * their output. Mirrors the runner's MACHINE_PROSE
217
+ * (docs/reports/harness-evals/runner/trialkit/extract.py). The scanner and search
218
+ * previews share it through `promptPreview`.
219
+ */
220
+ const MACHINE_PROSE_PREFIXES = [
221
+ '<task-notification>',
222
+ '<ci-monitor-event',
223
+ '<system-reminder>',
224
+ '<command-name>',
225
+ '<command-message>',
226
+ '<local-command-stdout>',
227
+ '<local-command-stderr>',
228
+ '<local-command-caveat>',
229
+ // Bash mode (`!cmd`): the command and its output are recorded as wrapped strings.
230
+ '<bash-input>',
231
+ '<bash-stdout>',
232
+ '<bash-stderr>',
233
+ '<command-args>',
234
+ ]
235
+
236
+ /**
237
+ * True when a string-content `user` entry is a prompt a person typed.
238
+ * `isMeta`, `isCompactSummary` and `isSidechain` entries are excluded by flag
239
+ * (a sidechain's string "prompt" is a subagent's Task prompt, written into the same
240
+ * file by older Claude Code versions, not something the person typed; the runner's
241
+ * extractor skips them too); the rest by the wrapper the harness puts at the start.
242
+ */
243
+ export function isTypedPromptString(entry, content) {
244
+ if (typeof content !== 'string') return false
245
+ if (entry.isMeta === true || entry.isCompactSummary === true || entry.isSidechain === true) return false
246
+ const text = content.trim()
247
+ if (!text) return false
248
+ return !MACHINE_PROSE_PREFIXES.some((p) => text.startsWith(p))
249
+ }
250
+
251
+ /**
252
+ * The first-prompt preview of one `user` entry, or null when it is not a typed
253
+ * prompt (#9363). The one rule behind the conversation list and search previews:
254
+ * string content must pass `isTypedPromptString`; array content is skipped when it
255
+ * carries a tool_result, otherwise its text blocks are joined with a newline.
256
+ * The result is cut to 200 characters.
257
+ *
258
+ * @param {object} entry - a parsed JSONL entry
259
+ * @returns {string|null}
260
+ */
261
+ export function promptPreview(entry) {
262
+ if (!entry || entry.type !== 'user') return null
263
+ const content = entry.message?.content
264
+ if (typeof content === 'string') {
265
+ return isTypedPromptString(entry, content) ? content.slice(0, 200) : null
266
+ }
267
+ if (Array.isArray(content)) {
268
+ if (content.some((b) => b.type === 'tool_result')) return null
269
+ const text = content
270
+ .filter((b) => b.type === 'text')
271
+ .map((b) => b.text)
272
+ .join('\n')
273
+ return text ? text.slice(0, 200) : null
274
+ }
275
+ return null
276
+ }
277
+
213
278
  /**
214
279
  * Parse raw JSONL text into Chroxy message format.
215
280
  * Shared parse core for the reader.
@@ -242,6 +307,13 @@ function parseJsonlContent(raw, { byteTruncated = false, strict = false } = {})
242
307
  // and tolerated: the first line of a tail-only read (cut by construction)
243
308
  // and an unterminated final line (a crash, a kill mid-write, or a session
244
309
  // still being appended to) — everything before the cut still replays.
310
+ //
311
+ // Deliberate (#8956): the final-line tolerance does NOT require an earlier
312
+ // parsed record. A file whose ONLY content is one unterminated unparseable
313
+ // line reads as an empty SUCCESSFUL transcript. That is the right answer
314
+ // for a session caught mid-write of its first record (crashed or still
315
+ // active), and it is indistinguishable by shape from garbage; a terminated
316
+ // garbage line is still refused. Pinned in transcript-provider-resolution.
245
317
  const tailCutFirstLine = byteTruncated && i === 0
246
318
  const unterminatedFinalLine = i === rawLines.length - 1
247
319
  if (strict && !tailCutFirstLine && !unterminatedFinalLine) {
@@ -261,16 +333,24 @@ function parseJsonlContent(raw, { byteTruncated = false, strict = false } = {})
261
333
  if (entry.type === 'user') {
262
334
  // Extract text from user message content blocks
263
335
  const content = entry.message?.content
264
- if (!Array.isArray(content)) continue
265
-
266
- // Skip tool_result entries (they're part of tool flow, not user text)
267
- const hasToolResult = content.some(b => b.type === 'tool_result')
268
- if (hasToolResult) continue
269
-
270
- const textParts = content
271
- .filter(b => b.type === 'text')
272
- .map(b => b.text)
273
- .join('\n')
336
+ let textParts
337
+ if (typeof content === 'string') {
338
+ // claude-tui writes the prompt as a plain string (#8951). The harness
339
+ // writes string entries nobody typed too; those stay hidden.
340
+ if (!isTypedPromptString(entry, content)) continue
341
+ textParts = content
342
+ } else if (Array.isArray(content)) {
343
+ // Skip tool_result entries (they're part of tool flow, not user text)
344
+ const hasToolResult = content.some(b => b.type === 'tool_result')
345
+ if (hasToolResult) continue
346
+
347
+ textParts = content
348
+ .filter(b => b.type === 'text')
349
+ .map(b => b.text)
350
+ .join('\n')
351
+ } else {
352
+ continue
353
+ }
274
354
 
275
355
  if (textParts) {
276
356
  messages.push({
@@ -492,7 +492,10 @@ export class JsonlSubprocessSession extends BaseSession {
492
492
  // N" error surface and emit the quiet `stopped` event for parity
493
493
  // with CliSession (#4868). SIGINT typically exits with 130 or null
494
494
  // depending on the CLI; both are user-initiated and not crashes.
495
- this.emit('stopped', { code })
495
+ this.emit('stopped', { code, stopRequested: true }) // #9241
496
+ // #9241: BaseSession answered a Stop before any output with the marker, which IS
497
+ // this turn's one terminal result; the fallback below would be a second.
498
+ if (this._stopMarkerEmitted) ctx.didEmitResult = true
496
499
  } else if (code !== 0 && code !== null) {
497
500
  // Prefer high-signal stderr; fall back to raw so the user always
498
501
  // sees *some* explanation when the child died.
package/src/logger.js CHANGED
@@ -20,7 +20,7 @@ import {
20
20
  openSync, readSync, closeSync, writeFileSync, truncateSync,
21
21
  } from 'fs'
22
22
  import { join } from 'path'
23
- import { SENSITIVE_PATTERNS, API_KEY_PATTERNS, redactValue, redactWhole, clipRedacted } from './redaction.js'
23
+ import { SENSITIVE_PATTERNS, API_KEY_PATTERNS, redactValue, redactWhole, clipRedacted, noteRedactionFallback } from './redaction.js'
24
24
  import { configPath } from './config-dir.js'
25
25
 
26
26
  function defaultLogDir() {
@@ -137,14 +137,24 @@ export function redactSensitivePreservingEscapes(s, fill = 'X') {
137
137
  }
138
138
  const chars = s.split('')
139
139
  let changed = false
140
- for (const pattern of [...SENSITIVE_PATTERNS, ...API_KEY_PATTERNS]) {
141
- pattern.lastIndex = 0
142
- let match
143
- while ((match = pattern.exec(stripped)) !== null) {
144
- for (let k = match.index; k < match.index + match[0].length; k++) chars[map[k]] = fill
145
- changed = true
146
- if (match[0].length === 0) pattern.lastIndex++ // guard against a zero-width match
140
+ try {
141
+ for (const pattern of [...SENSITIVE_PATTERNS, ...API_KEY_PATTERNS]) {
142
+ pattern.lastIndex = 0
143
+ let match
144
+ while ((match = pattern.exec(stripped)) !== null) {
145
+ for (let k = match.index; k < match.index + match[0].length; k++) chars[map[k]] = fill
146
+ changed = true
147
+ if (match[0].length === 0) pattern.lastIndex++ // guard against a zero-width match
148
+ }
147
149
  }
150
+ } catch (err) {
151
+ noteRedactionFallback(err)
152
+ // Fail closed (see redactValue): a throw out of a pattern (the regex engine's stack is finite)
153
+ // must not reach the caller, and a half-masked line must not be returned. Mask every character
154
+ // of the stripped text; the escape bytes and the length stay, as the contract says.
155
+ for (const idx of map) chars[idx] = fill
156
+ changed = true
157
+ for (const pattern of [...SENSITIVE_PATTERNS, ...API_KEY_PATTERNS]) pattern.lastIndex = 0
148
158
  }
149
159
  return changed ? chars.join('') : s
150
160
  }
@@ -164,6 +174,24 @@ let _logPath = null
164
174
  let _auditLogPath = null
165
175
  let _writeCount = 0
166
176
  let _quietConsole = false
177
+ // Record framing of the audit file's tail. A failed append (ENOSPC) can leave a PREFIX of the
178
+ // line with no newline; the next accepted line would be glued onto it and neither would parse
179
+ // on its own. 'unchecked' (process start, after a rotation): look at the file's last byte before
180
+ // the next write. 'dirty' (an append threw): start the next write on a fresh line. 'clean': as is.
181
+ let _auditTail = 'unchecked'
182
+
183
+ // Test seam for the file append, so a test can make it fail (ENOSPC, EBADF) without
184
+ // breaking a real disk. Production never sets it; `null` restores the real call.
185
+ let _appendFileSync = appendFileSync
186
+
187
+ /**
188
+ * TEST ONLY. Replace the append used for the daemon log and the audit log. Pass null
189
+ * to restore `fs.appendFileSync`.
190
+ * @param {((path: string, data: string) => void) | null} fn
191
+ */
192
+ export function _setAppendFileSyncForTest(fn) {
193
+ _appendFileSync = typeof fn === 'function' ? fn : appendFileSync
194
+ }
167
195
 
168
196
  /** Set of callbacks for broadcasting log entries (supports multiple WsServer instances) */
169
197
  const _logListeners = new Set()
@@ -233,6 +261,7 @@ export function initFileLogging({ level = 'info', logDir } = {}) {
233
261
  }
234
262
  _logPath = join(_logDir, 'chroxy.log')
235
263
  _auditLogPath = join(_logDir, AUDIT_LOG_NAME)
264
+ _auditTail = 'unchecked'
236
265
  }
237
266
 
238
267
  /**
@@ -272,6 +301,23 @@ export function getAuditLogPath() {
272
301
  return _logToFile ? _auditLogPath : null
273
302
  }
274
303
 
304
+ /**
305
+ * Success-reporting audit write (agent-principals.md section 10.1, `auditOrRefuse`).
306
+ *
307
+ * `logger.audit()` swallows write errors (#746), so it cannot fail closed. This one
308
+ * returns `{ ok: true }` ONLY when the line was appended to the dedicated audit log, and
309
+ * `{ ok: false, reason }` when file logging is off or the append threw. The line has the
310
+ * same format and redaction as `audit()`, and is also mirrored to the daemon log, the
311
+ * console and log listeners exactly like one. A caller that must not act unaudited
312
+ * (a principal effect, #7169's Discord path) acts only on `ok: true`.
313
+ * @param {string} component
314
+ * @param {string} msg
315
+ * @returns {{ ok: true } | { ok: false, reason: 'audit_unavailable' }}
316
+ */
317
+ export function auditOrRefuse(component, msg) {
318
+ return createLogger(component).auditStrict(msg)
319
+ }
320
+
275
321
  /**
276
322
  * #7162: bound the service-manager capture files (launchd StandardOutPath /
277
323
  * systemd StandardOutput=file: / the Windows wrapper's `>>`), which no service
@@ -355,6 +401,7 @@ export function closeFileLogging() {
355
401
  _logDir = defaultLogDir()
356
402
  _logPath = null
357
403
  _auditLogPath = null
404
+ _auditTail = 'unchecked'
358
405
  _writeCount = 0
359
406
  _quietConsole = false
360
407
  _logListeners.clear()
@@ -365,13 +412,13 @@ export function closeFileLogging() {
365
412
  * Rotate: base.N.log (overwritten) <- ... <- base.1.log <- base.log
366
413
  */
367
414
  function _maybeRotateAt(logPath, maxSize, maxFiles) {
368
- if (!logPath) return
415
+ if (!logPath) return false
369
416
  try {
370
417
  const stats = statSync(logPath)
371
- if (stats.size < maxSize) return
418
+ if (stats.size < maxSize) return false
372
419
  } catch (err) {
373
420
  if (err?.code !== 'ENOENT') console.error('[logger] stat failed:', err?.message)
374
- return
421
+ return false
375
422
  }
376
423
 
377
424
  // #7162: anchored to the FINAL '.log' — a first-occurrence string replace
@@ -387,6 +434,30 @@ function _maybeRotateAt(logPath, maxSize, maxFiles) {
387
434
  if (err?.code !== 'ENOENT') console.error('[logger] rename failed:', err?.message)
388
435
  }
389
436
  }
437
+ return true
438
+ }
439
+
440
+ /**
441
+ * Whether the audit file's tail needs a record boundary before the next line: true after a
442
+ * failed append, or when the file's last byte is not a newline (a crash or a partial append
443
+ * from an earlier process). A file we cannot inspect counts as needing one (a stray blank
444
+ * line is harmless; a glued record is not).
445
+ */
446
+ function _auditTailNeedsBoundary() {
447
+ if (_auditTail === 'clean') return false
448
+ if (_auditTail === 'dirty') return true
449
+ let fd = null
450
+ try {
451
+ const size = statSync(_auditLogPath).size
452
+ if (size === 0) return false
453
+ fd = openSync(_auditLogPath, 'r')
454
+ const last = Buffer.alloc(1)
455
+ return readSync(fd, last, 0, 1, size - 1) !== 1 || last[0] !== 0x0a
456
+ } catch (err) {
457
+ return err?.code !== 'ENOENT'
458
+ } finally {
459
+ if (fd !== null) { try { closeSync(fd) } catch { /* nothing to do */ } }
460
+ }
390
461
  }
391
462
 
392
463
  function _maybeRotate() {
@@ -445,7 +516,7 @@ export function createLogger(component, context = {}) {
445
516
  let fileWriteOk = false
446
517
  if (_logToFile && _logPath) {
447
518
  try {
448
- appendFileSync(_logPath, line + '\n')
519
+ _appendFileSync(_logPath, line + '\n')
449
520
  fileWriteOk = true
450
521
  _writeCount++
451
522
  if (_writeCount % ROTATION_CHECK_INTERVAL === 0) {
@@ -495,14 +566,27 @@ export function createLogger(component, context = {}) {
495
566
  // whose retention noise can't touch. Kept fire-and-forget here — #7169's
496
567
  // fail-closed audit writer layers its success-reporting on top of this
497
568
  // sink rather than replacing the level-independent path.
569
+ // `auditWritten` is true ONLY when this append succeeded; `auditStrict` reports it.
570
+ let auditWritten = false
498
571
  if (level === 'audit' && _logToFile && _auditLogPath) {
499
572
  try {
500
- appendFileSync(_auditLogPath, line + '\n')
501
- _maybeRotateAt(_auditLogPath, MAX_AUDIT_LOG_SIZE, MAX_AUDIT_LOG_FILES)
573
+ // A record boundary first, so this line parses on its own whatever the tail holds.
574
+ _appendFileSync(_auditLogPath, (_auditTailNeedsBoundary() ? '\n' : '') + line + '\n')
575
+ auditWritten = true
576
+ _auditTail = 'clean'
502
577
  } catch {
503
- // Same #746 rationale as above.
578
+ // Same #746 rationale as above. The append may have written a prefix.
579
+ _auditTail = 'dirty'
580
+ }
581
+ if (auditWritten) {
582
+ try {
583
+ if (_maybeRotateAt(_auditLogPath, MAX_AUDIT_LOG_SIZE, MAX_AUDIT_LOG_FILES)) _auditTail = 'unchecked'
584
+ } catch {
585
+ // The line is already on disk; a rotation failure does not un-write it.
586
+ }
504
587
  }
505
588
  }
589
+ return auditWritten
506
590
  }
507
591
 
508
592
  return {
@@ -517,6 +601,12 @@ export function createLogger(component, context = {}) {
517
601
  * listeners, and written to the daemon log file like any other line.
518
602
  */
519
603
  audit(msg) { write('audit', msg, { always: true }) },
604
+ /** Like `audit`, but reports whether the line reached the audit log (see `auditOrRefuse`). */
605
+ auditStrict(msg) {
606
+ return write('audit', msg, { always: true }) === true
607
+ ? { ok: true }
608
+ : { ok: false, reason: 'audit_unavailable' }
609
+ },
520
610
  // Backward compat alias
521
611
  log(msg) { write('info', msg) },
522
612
  /** Create a child logger tagged with a session ID. */
@@ -214,6 +214,11 @@ export function handleMailboxPing(server, req, res) {
214
214
  }
215
215
 
216
216
  const reason = injectWakeup(server, to, unreadCount)
217
+ if (reason === 'orchestrated') oweNudge(server, to, unreadCount)
218
+ // Clear the owed nudge only when this ping really reached the agent
219
+ // (`injected`) or the session is gone. `busy` / `pty-dead` / `not-tui` / ...
220
+ // injected nothing, so the earlier refused nudge is still owed.
221
+ else if (reason === 'injected' || reason === 'no-session') clearOwedNudge(server.sessionManager, to)
217
222
  // Record the delivery for the Control Room "Mailbox" tab (observability;
218
223
  // recordMailboxEvent never throws into the delivery path).
219
224
  server.sessionManager?.recordMailboxEvent?.({ to, from, unreadCount, outcome: reason })
@@ -236,6 +241,103 @@ export function handleMailboxPing(server, req, res) {
236
241
  function injectWakeup(server, to, unreadCount) {
237
242
  const session = server.sessionManager?.resolveSessionByAgentCommId?.(to) ?? null
238
243
  if (!session) return 'no-session'
244
+ // #9184: refuse into a session a TurnDriver occupies — same interleaving hazard
245
+ // as a CI wake (#8327), and the session is idle BETWEEN the driver's turns, so
246
+ // the `isRunning` gate in wakeSession does not catch it.
247
+ // #9301, decided: the refused nudge is DEFERRED, not dropped. The mail stays
248
+ // unread in the mailbox, and the daemon owes this agent ONE nudge (`oweNudge`,
249
+ // at most one per mailbox id): delivered through this same function when the
250
+ // last TurnDriver releases the session, unless the agent ran receive_next in
251
+ // the meantime (the mail was read), a newer ping already nudged it, or the
252
+ // session was destroyed. If the session is driven again at release time the
253
+ // nudge stays owed for the next release. The outcome is recorded in the
254
+ // Control Room event ring.
255
+ // Not routed through daemonTurnRefusal: its other refusals (budget, user Stop,
256
+ // wake cap) are deliberately not applied to mailbox wakes (#8326).
257
+ if (server.sessionManager.isAgentCommIdTurnDriven(to)) return 'orchestrated'
239
258
  const countText = unreadCount != null ? `${unreadCount} unread mailbox message(s)` : 'unread mailbox messages'
259
+ // #8326: deliberately NOT counted or capped by the CI wake cap. A mailbox wake
260
+ // is one-shot ("you have unread mail"), not a self-re-arming loop like
261
+ // wake -> push -> CI -> wake, and it never reaches daemonTurnRefusal.
240
262
  return wakeSession(session, `You have ${countText} — run receive_next to process them.`)
241
263
  }
264
+
265
+ /**
266
+ * #9301 — nudges owed to agents whose mailbox wake was refused as `orchestrated`.
267
+ * Per SessionManager: mailboxId -> { sessionId, unreadCount }. Bounded to one entry
268
+ * per mailbox id (a newer refusal replaces it) and cleared on delivery, on read,
269
+ * on a later successful nudge and on session destroy.
270
+ */
271
+ const owed = new WeakMap()
272
+ const subscribed = new WeakSet()
273
+ // The agent-comm MCP tool, as a TOKEN match on the tool id: `receive_next` or any
274
+ // `mcp__<server>__receive_next` (the server name is operator-chosen, so it is not
275
+ // pinned). Not a substring match: `receive_next_batch`-style names do not count.
276
+ // Read-state is a PROXY (chroxy cannot query the mailbox): one receive_next may not
277
+ // drain every message, so a later message can go un-nudged only if no later ping
278
+ // arrives; and for claude-tui the transcript `tool_start` can lag past release, which
279
+ // yields a spurious extra nudge, never a lost one.
280
+ const RECEIVE_NEXT = /(^|__)receive_next$/
281
+
282
+ function owedFor(sm) {
283
+ let m = owed.get(sm)
284
+ if (!m) { m = new Map(); owed.set(sm, m) }
285
+ return m
286
+ }
287
+
288
+ /** Test-only: the owed-nudge map for a manager (leak assertions). */
289
+ export function _owedNudgesForTest(sm) {
290
+ return owed.get(sm) ?? new Map()
291
+ }
292
+
293
+ function clearOwedNudge(sm, to) {
294
+ if (sm) owed.get(sm)?.delete(to)
295
+ }
296
+
297
+ function oweNudge(server, to, unreadCount) {
298
+ const sm = server.sessionManager
299
+ const sessionId = sm?.agentCommIdSessionId?.(to)
300
+ if (!sessionId || typeof sm.on !== 'function') return
301
+ owedFor(sm).set(to, { sessionId, unreadCount })
302
+ if (subscribed.has(sm)) return
303
+ subscribed.add(sm)
304
+ // One set of listeners per manager, attached the first time a nudge is owed.
305
+ sm.on('turn_driven_released', ({ sessionId: sid } = {}) => deliverOwedNudges(server, sid))
306
+ sm.on('session_destroyed', ({ sessionId: sid } = {}) => dropOwedForSession(sm, sid))
307
+ // The agent read its mail itself while driven: nothing left to nudge about.
308
+ sm.on('session_event', (ev) => {
309
+ if (ev?.event !== 'tool_start') return
310
+ const tool = ev.data?.tool ?? ev.data?.toolName
311
+ if (typeof tool === 'string' && RECEIVE_NEXT.test(tool)) dropOwedForSession(sm, ev.sessionId)
312
+ })
313
+ }
314
+
315
+ function dropOwedForSession(sm, sessionId) {
316
+ const m = owed.get(sm)
317
+ if (!m) return
318
+ for (const [to, o] of m) if (o.sessionId === sessionId) m.delete(to)
319
+ }
320
+
321
+ function deliverOwedNudges(server, sessionId) {
322
+ const sm = server.sessionManager
323
+ const m = owed.get(sm)
324
+ if (!m) return
325
+ for (const [to, o] of [...m]) {
326
+ if (o.sessionId !== sessionId) continue
327
+ // Same agent, same session: a mailbox id re-registered to another session
328
+ // is not this agent's mail any more.
329
+ if (sm.agentCommIdSessionId(to) !== sessionId) { m.delete(to); continue }
330
+ if (sm.isAgentCommIdTurnDriven(to)) continue // re-driven: stay owed
331
+ m.delete(to) // before delivery: exactly once
332
+ try {
333
+ const reason = injectWakeup(server, to, o.unreadCount)
334
+ // `busy` (e.g. a TUI still settling one tick after release): nothing was typed,
335
+ // so it stays owed. There is no idle signal to retry on; it is re-delivered by
336
+ // the next ping (which re-evaluates) or the next release.
337
+ if (reason === 'busy') m.set(to, o)
338
+ sm.recordMailboxEvent?.({ to, from: 'daemon', unreadCount: o.unreadCount, outcome: `deferred:${reason}` })
339
+ } catch (err) {
340
+ log.warn(`deferred mailbox nudge for ${to} failed: ${err?.message || err}`)
341
+ }
342
+ }
343
+ }
@@ -67,6 +67,15 @@ import { configPath } from './config-dir.js'
67
67
  * (`notification-categories.ts`) by `tests/notification-category-roster.test.js`
68
68
  * (#7429): add a new category there too, or that test names the one missing.
69
69
  *
70
+ * Deliberately an independent literal, NOT derived from `@chroxy/protocol`
71
+ * (#9163): the protocol exports only the client render roster
72
+ * (`NOTIFICATION_CATEGORIES`), whose order differs from the wire order here,
73
+ * and the daemon must not decide what it can fire from a UI table. Deriving
74
+ * this list from that roster would make the server<->client roster pairs
75
+ * (every server key has a label, every client key is fireable, same set)
76
+ * compare the roster with itself, so they could not go red. Only the
77
+ * `RATE_LIMITS` comparison would still be live.
78
+ *
70
79
  * History: the issue text (#4541) sketches `permission / question / error /
71
80
  * result / inactivity` as user-facing labels; the wire-level set below is
72
81
  * the actual server-emitted categories (the UI in sub-issues #4542/#4543
@@ -124,6 +133,12 @@ export const CATEGORY_DEFAULTS = Object.freeze(
124
133
  *
125
134
  * Users can opt out per-device (`bypassCategories: []`) or extend the
126
135
  * global list to silence even errors if they want.
136
+ * Pinned in both directions to the shared client default in
137
+ * `@chroxy/protocol` by `tests/notification-category-roster.test.js` (#8567).
138
+ * Kept as its own literal for the same reason as `ALL_CATEGORIES` (#9163):
139
+ * if it were imported from the protocol, the bypass pair in the roster test
140
+ * would compare one array with itself in both directions and could not go red;
141
+ * the only remaining check would be the protocol test's literal.
127
142
  */
128
143
  export const DEFAULT_BYPASS_CATEGORIES = Object.freeze(['permission', 'activity_error'])
129
144