@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
@@ -7,6 +7,7 @@ import { mkdirSync, rmSync, writeFileSync } from 'fs'
7
7
  import { normalizeSdkModelUsage } from './usage-normalize.js'
8
8
  import { tmpdir } from 'os'
9
9
  import { claudeConfigDir } from './utils/claude-config-dir.js'
10
+ import { claudeSettingSourcesValueFor, projectSettingsAllowedAsync, projectSettingsDecidedWithoutScan } from './claude-setting-sources.js'
10
11
  import { join } from 'path'
11
12
  import { createPermissionHookManager } from './permission-hook.js'
12
13
  import { guardChildStreams } from './child-stream-guard.js'
@@ -14,7 +15,7 @@ import { BaseSession, buildBaseSessionOpts, reportInputAdmission, spawnRefusalAd
14
15
  import { buildContentBlocks } from './content-blocks.js'
15
16
  import { ALLOWED_MODEL_IDS } from './models.js'
16
17
  import { CLAUDE_FALLBACK_MODELS, claudeModelMetadata } from './claude-model-catalog.js'
17
- import { forceKill, killProcessTree } from './platform.js'
18
+ import { forceKill, killProcessTree, killRecordedTree, recordProcessTree } from './platform.js'
18
19
  import { MessageTransformPipeline } from './message-transform.js'
19
20
  import { emitToolResults } from './tool-result.js'
20
21
  import { buildToolStartData, extractToolInputSemantics, parseCompactBoundaryMeta, formatCompactBoundaryContent, formatStatusContent } from './claude-stream-parser.js'
@@ -158,9 +159,10 @@ export function stderrIndicatesUnknownResumeCompacted(lines, windowLines = 10) {
158
159
  * @param {string[]} opts.allowedTools
159
160
  * @param {string} opts.skillsText
160
161
  * @param {string|null} opts.resumeSessionId
162
+ * @param {boolean} [opts.projectAllowed] - the launch decision for the session folder (claude-setting-sources.js); absent means not allowed
161
163
  * @returns {string[]}
162
164
  */
163
- export function buildClaudeCliArgs({ model, permissionMode, allowedTools, skillsText, resumeSessionId } = {}) {
165
+ export function buildClaudeCliArgs({ model, permissionMode, allowedTools, skillsText, resumeSessionId, projectAllowed } = {}) {
164
166
  const args = [
165
167
  '-p',
166
168
  '--input-format', 'stream-json',
@@ -168,6 +170,8 @@ export function buildClaudeCliArgs({ model, permissionMode, allowedTools, skills
168
170
  '--verbose',
169
171
  '--include-partial-messages',
170
172
  ]
173
+ const allowed = projectAllowed === true
174
+ args.push('--setting-sources', claudeSettingSourcesValueFor(allowed))
171
175
 
172
176
  if (model) {
173
177
  args.push('--model', model)
@@ -518,6 +522,14 @@ export class CliSession extends BaseSession {
518
522
  // on "the child is gone".
519
523
  this._stoppedByUser = false
520
524
 
525
+ // #9267: children the 5 s Stop timer retired, each with the descendants
526
+ // recorded (pid + start time) before it was signalled, so the escalation and
527
+ // destroy() can still reap a tree whose parent already exited. `_treeDeps`
528
+ // is the test seam for the ps / process.kill the tree operations use.
529
+ this._retiredChildren = new Set()
530
+ this._drainOutgoingFirst = false
531
+ this._treeDeps = {}
532
+
521
533
  // Hook manager (shared module)
522
534
  this._hookManager = (this._port) ? createPermissionHookManager(this, { settingsPath }) : null
523
535
 
@@ -567,6 +579,10 @@ export class CliSession extends BaseSession {
567
579
  // respawn, model-switch respawn, restart-on-input), so the stop latch is
568
580
  // spent. Cleared FIRST so a throw below cannot leave it armed.
569
581
  this._stoppedByUser = false
582
+ // Every start takes a new generation; a verification still pending for an older
583
+ // one never launches (see below).
584
+ const startGen = (this._startGen = (this._startGen || 0) + 1)
585
+ this._pendingStartGen = null
570
586
 
571
587
  // Register permission hook before starting the process (only once, not on respawn)
572
588
  if (this._hookManager && this._respawnCount === 0) {
@@ -577,6 +593,33 @@ export class CliSession extends BaseSession {
577
593
  // _buildChildEnv() reads `_permissionModeFile` to point the child at it.
578
594
  this._ensurePermissionModeSidecar()
579
595
 
596
+ // One project-settings decision per launch: it picks the argv and is what is
597
+ // reported as loaded in this running process. A folder with no trust record is
598
+ // decided at once; a trusted one is verified by a fresh scan off the main
599
+ // thread, and the process is launched when that answers (unless the session
600
+ // was stopped or destroyed meanwhile).
601
+ const decided = projectSettingsDecidedWithoutScan(this.cwd)
602
+ if (decided !== null) {
603
+ this._launchPersistent(decided)
604
+ return
605
+ }
606
+ this._pendingStartGen = startGen
607
+ projectSettingsAllowedAsync(this.cwd).catch(() => false).then((allowed) => {
608
+ if (this._pendingStartGen === startGen) this._pendingStartGen = null
609
+ // Launch only if nothing started, stopped or destroyed the session since, and no
610
+ // child exists (a newer start that took the fast path has already spawned one).
611
+ if (this._startGen !== startGen || this._destroying || this._stoppedByUser || this._child) return
612
+ try {
613
+ this._launchPersistent(allowed)
614
+ } catch (err) {
615
+ ;(this._log || log).error(`Start failed: ${err.message}`)
616
+ this.emit('error', { message: `Failed to start the Claude process: ${err.message}` })
617
+ }
618
+ })
619
+ }
620
+
621
+ /** Build the argv for the decided project-settings scope and spawn the persistent process. */
622
+ _launchPersistent(projectAllowed) {
580
623
  // Skills MVP (#2957) — append shared skills to the Claude CLI system prompt.
581
624
  const skillsText = this._buildSystemPrompt()
582
625
 
@@ -586,12 +629,14 @@ export class CliSession extends BaseSession {
586
629
  // would otherwise lose every prior turn in the model's context window and
587
630
  // the user would see the dashboard transcript replay correctly while the
588
631
  // model itself starts cold mid-conversation.
632
+ this._launchedWithProject = projectAllowed
589
633
  const args = buildClaudeCliArgs({
590
634
  model: this.model,
591
635
  permissionMode: this.permissionMode,
592
636
  allowedTools: this.allowedTools,
593
637
  skillsText,
594
638
  resumeSessionId: this._sessionId,
639
+ projectAllowed,
595
640
  })
596
641
 
597
642
  const resumeNote = this._sessionId ? ` (resume ${this._sessionId})` : ''
@@ -723,7 +768,9 @@ export class CliSession extends BaseSession {
723
768
  const rl = createInterface({ input: child.stdout })
724
769
  this._rl = rl
725
770
 
726
- rl.on('line', (line) => this._handleStdoutLine(line))
771
+ // #9267: tag every line with the child that wrote it, so a child the Stop
772
+ // safety timer retired cannot feed its late reply into the session.
773
+ rl.on('line', (line) => this._handleStdoutLine(line, child))
727
774
 
728
775
  // Log stderr for debugging
729
776
  const stderrRL = createInterface({ input: child.stderr })
@@ -805,7 +852,32 @@ export class CliSession extends BaseSession {
805
852
  return false
806
853
  }
807
854
 
855
+ /**
856
+ * #8281: the startup queue (`_pendingQueue`) counts as queued prompts. Both
857
+ * drains shift an item and call `sendMessage` (which sets busy) in the same
858
+ * synchronous step, so the item is in this queue until the instant the session
859
+ * is busy: the post-result drain's nextTick window and the respawn-to-ready
860
+ * window are both covered by the length alone, with no in-flight marker.
861
+ * @returns {number}
862
+ */
863
+ _extraQueuedPromptCount() {
864
+ return this._pendingQueue.length
865
+ }
866
+
808
867
  _drainPendingQueue() {
868
+ // #9267: the warmup of the child the Stop timer's retirement started drains the
869
+ // OUTGOING queue first (a follow-up accepted during the 5 s window is older than
870
+ // anything parked behind the fresh child), one turn at a time: the rest, startup
871
+ // queue included, follows from each `result` in the order the result path keeps.
872
+ // Only that restart sets the flag; crash and model/permission-mode respawns drain
873
+ // exactly what they always did.
874
+ if (this._drainOutgoingFirst) {
875
+ this._drainOutgoingFirst = false
876
+ if (!this._isBusy && this._outgoingQueue.length > 0) {
877
+ this.dequeueNextOutgoing()
878
+ return
879
+ }
880
+ }
809
881
  while (this._pendingQueue.length > 0 && !this._isBusy) {
810
882
  const pending = this._pendingQueue.shift()
811
883
  if (!this._admitPendingItem(pending)) continue
@@ -983,6 +1055,10 @@ export class CliSession extends BaseSession {
983
1055
  ;(this._log || log).info(`Process not ready, queuing message (queue depth: ${this._pendingQueue.length + 1})`)
984
1056
  this._pendingQueue.push({ prompt, attachments, options })
985
1057
  reportInputAdmission(options, { status: 'queued', delivery: 'queued' })
1058
+ // #9267: the restart above can finish its warmup synchronously (an existing
1059
+ // container, a folder needing no trust scan), i.e. BEFORE this push, leaving
1060
+ // nothing to drain the prompt just parked. Ready and idle now means drain now.
1061
+ if (this._processReady && !this._isBusy) this._drainPendingQueue()
986
1062
  return
987
1063
  }
988
1064
 
@@ -1302,8 +1378,13 @@ export class CliSession extends BaseSession {
1302
1378
  * a real readline interface.
1303
1379
  *
1304
1380
  * @param {string} line
1381
+ * @param {object} [child] #9267: the child that wrote the line. When given and
1382
+ * it is no longer the session's current child (the Stop safety timer retired
1383
+ * it, or a respawn replaced it) the line is dropped before it can touch the
1384
+ * turn state of whatever the session is doing now.
1305
1385
  */
1306
- _handleStdoutLine(line) {
1386
+ _handleStdoutLine(line, child) {
1387
+ if (child && this._child !== child) return
1307
1388
  if (!line.trim()) return
1308
1389
 
1309
1390
  let data
@@ -1728,6 +1809,8 @@ export class CliSession extends BaseSession {
1728
1809
  // carries the same stop_reason / subtype / terminal_reason.
1729
1810
  declarationEligible: sdkDeclarationEligible(data),
1730
1811
  ...turnOutcomeField(outcomeFromSdkResult(data)),
1812
+ // #9241: `aborted_*` is the child saying the abort ended the turn.
1813
+ ...(outcomeFromSdkResult(data) === 'stopped' ? { stopRequested: true } : {}),
1731
1814
  })
1732
1815
 
1733
1816
  // Message complete — ready for next message.
@@ -2393,7 +2476,10 @@ export class CliSession extends BaseSession {
2393
2476
  // are reported as "the turn was terminated under it" rather than as failed
2394
2477
  // commands. Supplied by each caller -- this is shared by the panic-button,
2395
2478
  // mid-turn setModel, Stop, a crash and both watchdogs -- and never inferred.
2396
- _emitInterruptedTurnResult(duration = 0, terminatedReason) {
2479
+ // #9241: `stopSignal` is the caller's word that the Stop is why the turn ended: a real
2480
+ // child close after it. The 5 s safety timer does NOT give it (the child may still be
2481
+ // running and answer), and the stall / hard-timeout watchdogs never did.
2482
+ _emitInterruptedTurnResult(duration = 0, terminatedReason, { stopSignal = false } = {}) {
2397
2483
  if (!this._isBusy || !this._currentMessageId) return
2398
2484
  const messageId = this._currentMessageId
2399
2485
  const sessionId = this._sessionId
@@ -2403,7 +2489,7 @@ export class CliSession extends BaseSession {
2403
2489
  }
2404
2490
  this._clearMessageState({ terminatedReason })
2405
2491
  // #7072: terminal but not a completed turn (internal; not on the wire).
2406
- this.emit('result', { cost: null, duration, usage: null, sessionId, interrupted: true })
2492
+ this.emit('result', { cost: null, duration, usage: null, sessionId, interrupted: true, ...(stopSignal ? { stopRequested: true } : {}) })
2407
2493
  }
2408
2494
 
2409
2495
  _handleChildClose(code) {
@@ -2459,7 +2545,7 @@ export class CliSession extends BaseSession {
2459
2545
 
2460
2546
  // #7376: Stop (SIGINT -> the child exits here) and a crash both reach this
2461
2547
  // point; the tools they leave in flight are worded differently.
2462
- this._emitInterruptedTurnResult(0, wasIntentionalStop ? 'user_stop' : 'process_exit')
2548
+ this._emitInterruptedTurnResult(0, wasIntentionalStop ? 'user_stop' : 'process_exit', { stopSignal: wasIntentionalStop })
2463
2549
 
2464
2550
  // #4602: user-initiated Stop sent SIGINT via interrupt(). The child
2465
2551
  // exited cleanly as a result — do NOT show "exited unexpectedly" and
@@ -2473,7 +2559,7 @@ export class CliSession extends BaseSession {
2473
2559
  // _restartAfterStop). Stop halts the turn; it must not end the session's
2474
2560
  // ability to answer the follow-up.
2475
2561
  this._stoppedByUser = true
2476
- this.emit('stopped', { code })
2562
+ this.emit('stopped', { code, stopRequested: true }) // #9241
2477
2563
  return
2478
2564
  }
2479
2565
 
@@ -2648,9 +2734,12 @@ export class CliSession extends BaseSession {
2648
2734
  */
2649
2735
  _restartAfterStop() {
2650
2736
  if (!this._stoppedByUser && !this._spawnRefusal) return
2651
- if (this._destroying) return
2652
- if (this._respawning) return
2653
- if (this._respawnScheduled) return
2737
+ // #9267: no restart of OURS is coming in these three, so a pending drain-first flag
2738
+ // must not be left for another respawn's warmup to consume.
2739
+ if (this._destroying || this._respawning || this._respawnScheduled) {
2740
+ this._drainOutgoingFirst = false
2741
+ return
2742
+ }
2654
2743
  // A child already exists — whoever spawned it owns the warmup drain.
2655
2744
  if (this._child) return
2656
2745
 
@@ -2671,7 +2760,9 @@ export class CliSession extends BaseSession {
2671
2760
  this._spawnRefusal = null
2672
2761
  try {
2673
2762
  this.start()
2763
+ if (this._spawnRefusal) this._drainOutgoingFirst = false // the gate refused: no child is coming
2674
2764
  } catch (err) {
2765
+ this._drainOutgoingFirst = false
2675
2766
  // Re-arm the latch: start() threw synchronously (spawn/arg failure) BEFORE
2676
2767
  // any child or container launch, so nothing was started. Without this the
2677
2768
  // latch stays consumed and the next sendMessage would only enqueue — never
@@ -2688,6 +2779,60 @@ export class CliSession extends BaseSession {
2688
2779
  }
2689
2780
  }
2690
2781
 
2782
+ /**
2783
+ * #9267: the Stop safety timer fired and the child had not answered SIGINT.
2784
+ * The turn is being reported as stopped, so the child is abandoned like a
2785
+ * respawn abandons one, minus the immediate respawn: its readlines are closed,
2786
+ * it stops being `_child` (so its stdout lines and its eventual `close` are
2787
+ * ignored -- no second result, no stop marker, no "exited unexpectedly"), its
2788
+ * tree is SIGTERMed, and the session is left as a Stop leaves it, revivable by
2789
+ * the next send (`_stoppedByUser`).
2790
+ *
2791
+ * The tree is recorded BEFORE the signal (pid + start time) and kept in
2792
+ * `_retiredChildren` until the escalation, so it still gets SIGKILLed when
2793
+ * the parent exits on SIGTERM but a descendant does not, and so `destroy()`
2794
+ * can reach it although `_child` no longer points at it. Recorded descendants
2795
+ * are signalled only while their start time still matches (never a recycled
2796
+ * pid), and the escalation is NOT cancelled by the parent's close.
2797
+ */
2798
+ _retireUnresponsiveChild(child) {
2799
+ this._cleanupReadlines()
2800
+ this._processReady = false
2801
+ this._child = null
2802
+ this._stoppedByUser = true
2803
+ ;(this._log || log).warn('Retiring the claude process that ignored the Stop signal; the next message starts a fresh one')
2804
+ this._expirePendingPermissions('Permission request expired (the session process was stopped before it could be answered)')
2805
+ this._completeAgents()
2806
+ this._clearPendingBackgroundShells() // the shells died with the child, as on a respawn
2807
+ const entry = { child, recorded: this._recordChildTree(child), timer: null }
2808
+ this._retiredChildren.add(entry)
2809
+ entry.timer = setTimeout(() => {
2810
+ this._retiredChildren.delete(entry)
2811
+ try { this._killChildTree(child, { force: true, recorded: entry.recorded, handleOnly: true }) } catch {}
2812
+ }, 3000)
2813
+ if (typeof entry.timer.unref === 'function') entry.timer.unref()
2814
+ this._killChildTree(child, { recorded: entry.recorded })
2815
+ }
2816
+
2817
+ /** #9267: snapshot the tree to reap (a seam: `_treeDeps` carries the ps stubs). */
2818
+ _recordChildTree(child) {
2819
+ try {
2820
+ return recordProcessTree(child, this._treeDeps)
2821
+ } catch (err) {
2822
+ ;(this._log || log).warn(`Could not record the retired child's process tree: ${err.message}`)
2823
+ return [] // fail safe: the handle-only kill still runs
2824
+ }
2825
+ }
2826
+
2827
+ /**
2828
+ * #9267: the one seam for signalling a retired child's process tree. Defaults
2829
+ * to the platform helper; tests whose mock child carries a numeric pid inject
2830
+ * `_treeDeps` (or override this) so no real process is enumerated or signalled.
2831
+ */
2832
+ _killChildTree(child, { force = false, recorded = [], handleOnly = false } = {}) {
2833
+ killRecordedTree(child, recorded, { force, handleOnly, ...this._treeDeps })
2834
+ }
2835
+
2691
2836
  /** Interrupt the current message (send SIGINT to child process) */
2692
2837
  interrupt() {
2693
2838
  // #5936: a deliberate Stop cancels the owner's queued follow-ups (cancel,
@@ -2697,6 +2842,15 @@ export class CliSession extends BaseSession {
2697
2842
  // never stranded.
2698
2843
  this.clearOutgoingQueue()
2699
2844
 
2845
+ // A Stop while a start is still verifying the folder: that start never launches, and
2846
+ // the session is left as a Stop leaves it, revivable by the next send.
2847
+ if (this._pendingStartGen !== null && this._pendingStartGen !== undefined) {
2848
+ this._pendingStartGen = null
2849
+ this._startGen = (this._startGen || 0) + 1
2850
+ this._stoppedByUser = true
2851
+ return
2852
+ }
2853
+
2700
2854
  if (!this._child) return
2701
2855
 
2702
2856
  // #4602: mark the imminent child exit as user-initiated so
@@ -2718,6 +2872,7 @@ export class CliSession extends BaseSession {
2718
2872
  clearTimeout(this._interruptTimer)
2719
2873
  this._interruptTimer = null
2720
2874
  }
2875
+ const interruptedChild = this._child
2721
2876
  this._interruptTimer = setTimeout(() => {
2722
2877
  this._interruptTimer = null
2723
2878
  // #4602: if the child survived SIGINT (claude only aborted the turn),
@@ -2727,7 +2882,23 @@ export class CliSession extends BaseSession {
2727
2882
  if (this._isBusy) {
2728
2883
  // #4828: session-scoped.
2729
2884
  ;(this._log || log).warn('Interrupt safety timeout — force-clearing busy state')
2885
+ // #9267: the child ignored SIGINT and the turn is being reported as
2886
+ // stopped. Retire THAT child first, so nothing it says later can grow a
2887
+ // reply onto the ended turn, and so a send from the result listener
2888
+ // starts a fresh child instead of writing to this one.
2889
+ const retired = this._child === interruptedChild
2890
+ if (retired) this._retireUnresponsiveChild(interruptedChild)
2891
+ // The follow-ups accepted in the window must go first whichever restart happens, the
2892
+ // timer's or a synchronous `result` listener's send, so decide BEFORE the emit.
2893
+ if (retired && this._outgoingQueue.length > 0) this._drainOutgoingFirst = true
2730
2894
  this._emitInterruptedTurnResult(0, 'user_stop')
2895
+ // #9267: a follow-up accepted during the window is parked behind a child that
2896
+ // is gone; start the fresh one now (the path a new send takes) rather than
2897
+ // leaving it to wait for yet another message.
2898
+ if (this._stoppedByUser) {
2899
+ if (this._outgoingQueue.length > 0) this._restartAfterStop()
2900
+ else this._drainOutgoingFirst = false // nothing left to put first, and no restart is coming
2901
+ }
2731
2902
  }
2732
2903
  }, 5000)
2733
2904
  // #6043: fire-and-forget busy-state safety net — never gate process exit on
@@ -2740,6 +2911,14 @@ export class CliSession extends BaseSession {
2740
2911
  destroy() {
2741
2912
  this._destroying = true
2742
2913
  this._respawning = false
2914
+ this._drainOutgoingFirst = false
2915
+ // #9267: a child the Stop timer retired is no longer `_child`, so reach its
2916
+ // tree here; the escalation timer is moot once the session is going away.
2917
+ for (const entry of this._retiredChildren) {
2918
+ clearTimeout(entry.timer)
2919
+ try { this._killChildTree(entry.child, { force: true, recorded: entry.recorded, handleOnly: true }) } catch {}
2920
+ }
2921
+ this._retiredChildren.clear()
2743
2922
  // #5936: tear down the shared outgoing queue silently (no message_dequeued
2744
2923
  // for a session that's going away).
2745
2924
  this.clearOutgoingQueue({ emit: false })
package/src/cli.js CHANGED
@@ -31,6 +31,8 @@ import { registerIdentityCommand } from './cli/identity-cmd.js'
31
31
  import { registerTokensCommand } from './cli/tokens-cmd.js'
32
32
  import { registerScheduleCommands } from './cli/schedule-cmd.js'
33
33
  import { registerAgentControlCommand } from './cli/agent-control-cmd.js'
34
+ import { registerFreshnessCommand } from './cli/freshness-cmd.js'
35
+ import { registerAgentCommand } from './cli/agent-cmd.js'
34
36
 
35
37
  const require = createRequire(import.meta.url)
36
38
  const { version } = require('../package.json')
@@ -64,5 +66,7 @@ registerIdentityCommand(program)
64
66
  registerTokensCommand(program)
65
67
  registerScheduleCommands(program)
66
68
  registerAgentControlCommand(program)
69
+ registerAgentCommand(program)
70
+ registerFreshnessCommand(program)
67
71
 
68
72
  program.parse()
@@ -16,6 +16,7 @@ import {
16
16
  MODEL_UNSUPPORTED_CODE, detectModelRejection, codexClientKey, recordModelRejection,
17
17
  rejectedDefaultFor, rejectedModelsFor, suggestFallbackModel,
18
18
  } from './codex-model-rejections.js'
19
+ import { describeCodexError, formatCodexError, rawCodexErrorForLog, UNREADABLE_CODEX_ERROR } from './codex-error-text.js'
19
20
  import { PermissionManager, wirePermissionManager } from './permission-manager.js'
20
21
  import { materializeAttachments, buildAttachmentsPromptSuffix } from './claude-tui-attachments.js'
21
22
  import { buildSpawnEnv } from './utils/spawn-env.js'
@@ -1141,6 +1142,16 @@ export class CodexAppServerSession extends BaseSession {
1141
1142
  return (!this._processReady || !this._client) ? 'not-started' : null
1142
1143
  }
1143
1144
 
1145
+ /**
1146
+ * #8281: `_activeTurn` is set when the turn is dispatched, before codex has
1147
+ * answered with a turn id (`turnId` is null until `turn/start` returns). That
1148
+ * window is still a turn in flight for a handoff.
1149
+ * @returns {boolean}
1150
+ */
1151
+ _hasTurnInFlight() {
1152
+ return !!this._activeTurn || super._hasTurnInFlight()
1153
+ }
1154
+
1144
1155
  async sendMessage(prompt, attachments, sendOptions = {}) {
1145
1156
  if (this._isBusy) {
1146
1157
  const queued = this.enqueueOutgoingMessage({ prompt, attachments, sendOptions })
@@ -1418,9 +1429,10 @@ export class CodexAppServerSession extends BaseSession {
1418
1429
  // notification — the result timeout (re-armed by _resetResultTimeout above)
1419
1430
  // is the backstop if codex never recovers, and codex's terminal give-up
1420
1431
  // (a disconnect WITHOUT a reconnecting message) still falls through to fail.
1432
+ // #8754 — codex says whether it retries (`willRetry`); see _codexWillRetry.
1421
1433
  const err = this._errorPayload(params)
1422
- if (this._isTransientReconnect(err)) {
1423
- ;(this._log || log).warn(`codex app-server response stream reconnecting (turn kept open): ${err.message || 'responseStreamDisconnected'}`)
1434
+ if (this._codexWillRetry(params, err)) {
1435
+ ;(this._log || log).warn(`codex app-server retrying (turn kept open): ${err.message || 'stream error'}`)
1424
1436
  // #6629 — arm the bounded watchdog so a reconnect that NEVER recovers
1425
1437
  // (nor emits codex's terminal give-up) still reconciles the stale
1426
1438
  // working state, even when a pending permission has paused the result
@@ -1440,6 +1452,7 @@ export class CodexAppServerSession extends BaseSession {
1440
1452
  // #8710 — codex has ended this turn: its `turn/completed` follows.
1441
1453
  this._noteNativeTurnEnded(turnId ?? t.turnId)
1442
1454
  const { message, code } = this._terminalErrorPayload(err, params)
1455
+ this._logRawTerminalError(params)
1443
1456
  this._failTurn(message, { code })
1444
1457
  break
1445
1458
  }
@@ -1495,12 +1508,15 @@ export class CodexAppServerSession extends BaseSession {
1495
1508
  const err = this._errorPayload(params)
1496
1509
  // `willRetry` (required in 0.163.0) marks codex's own retry of a turn it is
1497
1510
  // still running: not an end, and that turn's later notifications are live.
1498
- if (params?.willRetry === true || this._isTransientReconnect(err)) {
1511
+ // #8754: the same rule as an active turn (_codexWillRetry), so an explicit
1512
+ // `willRetry: false` is an end here too.
1513
+ if (this._codexWillRetry(params, err)) {
1499
1514
  tlog.debug(`codex app-server retrying with no turn open: ${err.message || 'stream error'}`)
1500
1515
  return false
1501
1516
  }
1502
1517
  this._noteNativeTurnEnded(turnId)
1503
1518
  const payload = this._terminalErrorPayload(err, params)
1519
+ this._logRawTerminalError(params)
1504
1520
  tlog.warn(`codex app-server error with no turn open (turn=${turnId}): ${payload.message}`)
1505
1521
  this.emit('error', payload)
1506
1522
  return false
@@ -1510,6 +1526,7 @@ export class CodexAppServerSession extends BaseSession {
1510
1526
  const turn = params?.turn
1511
1527
  if (turn?.status === 'failed') {
1512
1528
  const payload = this._terminalErrorPayload(turn.error, turn.error)
1529
+ this._logRawTerminalError(turn.error)
1513
1530
  tlog.warn(`codex app-server turn ${turnId} failed with no turn open: ${payload.message}`)
1514
1531
  this.emit('error', payload)
1515
1532
  } else {
@@ -1532,11 +1549,17 @@ export class CodexAppServerSession extends BaseSession {
1532
1549
  /**
1533
1550
  * #8710 — what a turn-ending codex error tells the client. A usage limit
1534
1551
  * carries codex's own sentence (it names when the limit resets) and the
1535
- * `usage_limit` code claude-tui sessions use for the same stop (#8400); any
1536
- * other error keeps the raw payload this path has always shown, and a failed
1537
- * turn that names no error says only that it failed.
1552
+ * `usage_limit` code claude-tui sessions use for the same stop (#8400); a
1553
+ * failed turn that names no error says only that it failed.
1538
1554
  * `usageLimitExceeded` is the v2 `CodexErrorInfo` spelling (codex-cli 0.163.0
1539
1555
  * `generate-json-schema`).
1556
+ *
1557
+ * #8610 — any other error shows its readable message, decoding nested
1558
+ * JSON-encoded errors within fixed bounds (codex-error-text.js), with HTTP
1559
+ * status and error type as secondary detail. When nothing readable is found it
1560
+ * says so; the raw payload is never shown. The usage-limit and model-rejection
1561
+ * branches above keep their precedence, and nothing here changes whether the
1562
+ * turn ends.
1540
1563
  */
1541
1564
  _terminalErrorPayload(err, raw) {
1542
1565
  if (err?.codexErrorInfo === 'usageLimitExceeded' && typeof err.message === 'string' && err.message) {
@@ -1545,7 +1568,16 @@ export class CodexAppServerSession extends BaseSession {
1545
1568
  const rejection = detectModelRejection(err, raw)
1546
1569
  if (rejection) return this._modelUnsupportedPayload(rejection)
1547
1570
  if (raw == null) return { message: 'Codex turn failed' }
1548
- return { message: `Codex error: ${JSON.stringify(raw).slice(0, 200)}` }
1571
+ const readable = describeCodexError(err ?? raw)
1572
+ return { message: readable ? formatCodexError(readable) : UNREADABLE_CODEX_ERROR }
1573
+ }
1574
+
1575
+ /**
1576
+ * #8610 — the chat card shows only the readable message, so the full raw payload
1577
+ * goes to the server log: one line, redacted, cut at a fixed length (codex-error-text.js).
1578
+ */
1579
+ _logRawTerminalError(raw) {
1580
+ ;(this._log || log).warn(`codex app-server terminal error payload: ${rawCodexErrorForLog(raw)}`)
1549
1581
  }
1550
1582
 
1551
1583
  /**
@@ -1959,14 +1991,16 @@ export class CodexAppServerSession extends BaseSession {
1959
1991
  }
1960
1992
  }
1961
1993
 
1962
- // #7072 -- UNVERIFIED against a live binary: a turn the operator stopped may
1963
- // arrive HERE. `interrupt()` sends `turn/interrupt`; if the binary answers it
1964
- // with `turn/completed` (the protocol's TurnStatus enum has an `interrupted`
1965
- // value, which this method never reads) rather than an `error` notification, the
1966
- // cut-off turn is reported below as a NORMAL result with no `interrupted` mark, and
1967
- // an orchestration TurnDriver settles it as a success. Do not infer the binary's
1968
- // behaviour from tests: #6606's C1 test only MODELS turn/completed-after-interrupt.
1969
- // Pin it with a live probe before changing this.
1994
+ // #7072 / #9241: a turn the operator stopped arrives HERE. `interrupt()` sends
1995
+ // `turn/interrupt`, and codex documents the answer as `turn/completed` with
1996
+ // `status: 'interrupted'` (app-server docs, "Interrupt a turn"), not an `error`
1997
+ // notification. It is reported as a `stopped` result (BaseSession marks it
1998
+ // `interrupted`, so an orchestration TurnDriver no longer settles it as a success),
1999
+ // and the requested-Stop handling there applies: no chip, the quiet `stopped`, and
2000
+ // the stop-before-reply marker when nothing had been produced. CAVEAT: this shape is
2001
+ // documented by OpenAI but NOT pinned by a live probe in this repo's tests (#6606's C1
2002
+ // test only models turn/completed-after-interrupt); a binary that answers differently
2003
+ // gets the old behaviour, a normal result.
1970
2004
  _finishTurn(turn, turnId = null) {
1971
2005
  if (!this._activeTurn) return
1972
2006
  const t = this._activeTurn
@@ -1992,6 +2026,11 @@ export class CodexAppServerSession extends BaseSession {
1992
2026
  // default codex session's per-model usage split was silently dropped.
1993
2027
  modelUsage: synthesizeModelUsage(this._effectiveModelId(), this._lastUsage),
1994
2028
  sessionId: this._threadId,
2029
+ // #9241: codex answers `turn/interrupt` with `turn/completed {status:'interrupted'}`
2030
+ // (TurnStatus), not an error. That is a cancelled turn, which BaseSession then treats
2031
+ // like every other provider's Stop (no chip for a requested one, the marker when
2032
+ // nothing had been produced).
2033
+ ...(turn?.status === 'interrupted' ? { turnOutcome: 'stopped', stopRequested: true } : {}),
1995
2034
  // #7794 — occupancy snapshot, or the field omitted entirely when codex
1996
2035
  // sent no usable one (clients then keep their previous snapshot / the
1997
2036
  // honest dash). Wire name is contextOccupancy, NOT contextUsage: the
@@ -2016,6 +2055,7 @@ export class CodexAppServerSession extends BaseSession {
2016
2055
  // `turn/completed` never gets here.
2017
2056
  if (turn?.status === 'failed') {
2018
2057
  const payload = this._terminalErrorPayload(turn.error, turn.error)
2058
+ this._logRawTerminalError(turn.error)
2019
2059
  ;(this._log || log).warn(`codex app-server turn failed: ${payload.message}`)
2020
2060
  this.emit('error', payload)
2021
2061
  }
@@ -2062,6 +2102,26 @@ export class CodexAppServerSession extends BaseSession {
2062
2102
  return /reconnect/i.test(typeof err?.message === 'string' ? err.message : '')
2063
2103
  }
2064
2104
 
2105
+ // #8754 — is this `error` notification codex retrying on its own (the turn goes on)
2106
+ // or a turn-ending error? Since codex-cli 0.163.0 the app-server says so:
2107
+ // `ErrorNotification.willRetry` is required, `true` for an EventMsg::StreamError that
2108
+ // codex retries itself and `false` for a turn-ending EventMsg::Error. When the field
2109
+ // is PRESENT it decides, both ways: only `true` keeps the turn open, even when the
2110
+ // message does not look like a reconnect (e.g. responseStreamConnectionFailed), and
2111
+ // anything else ends it, even when the message does. That includes a malformed value
2112
+ // (`null`, `'true'`, `1`): a codex that sends the field has stopped promising the
2113
+ // #6623 shape, so its message is no evidence of a retry, and ending the turn is the
2114
+ // conservative reading. Only a payload WITHOUT the field (an older codex) falls back
2115
+ // to the #6623 heuristic above. Keeping the turn open never removes the hard bounds:
2116
+ // the #6629 watchdog and the #6856 one-shot deadline are armed exactly as for a
2117
+ // #6623 reconnect.
2118
+ _codexWillRetry(params, err) {
2119
+ if (params && typeof params === 'object' && Object.hasOwn(params, 'willRetry')) {
2120
+ return params.willRetry === true
2121
+ }
2122
+ return this._isTransientReconnect(err)
2123
+ }
2124
+
2065
2125
  // #6638: also release cached fileChange diffs when per-turn state is cleared
2066
2126
  // (turn end / fail / destroy), so a diff can't outlive its turn.
2067
2127
  // #7340: forward the opts to super. `turnEndedCleanly` decides whether a
@@ -2429,8 +2489,8 @@ export class CodexAppServerSession extends BaseSession {
2429
2489
 
2430
2490
  // In-process permission responses (capabilities.inProcessPermissions) — thin
2431
2491
  // delegators to the PermissionManager, mirroring SdkSession.
2432
- respondToPermission(requestId, decision, editedInput, reason, scope) {
2433
- return this._permissions.respondToPermission(requestId, decision, editedInput, reason, scope)
2492
+ respondToPermission(requestId, decision, editedInput, reason, scope, resolvedBy) {
2493
+ return this._permissions.respondToPermission(requestId, decision, editedInput, reason, scope, resolvedBy)
2434
2494
  }
2435
2495
 
2436
2496
  respondToQuestion(text, answers, toolUseId) {
@@ -2511,6 +2571,7 @@ export class CodexAppServerSession extends BaseSession {
2511
2571
  async interrupt() {
2512
2572
  this.clearOutgoingQueue()
2513
2573
  this.markIntentionalStop()
2574
+ this._noteTurnStopRequested() // #9241: so a `turn/completed{interrupted}` takes the Stop path
2514
2575
  // Stop must not wait on a prompt: abort this turn's approval scope so a
2515
2576
  // pending permission_request resolves (deny → decline) immediately, instead
2516
2577
  // of leaving the turn wedged until the 5-min timeout (#6611 review).