@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
@@ -1,6 +1,7 @@
1
1
  import { assistantResponseText, sdkDeclarationEligible } from './assistant-response.js'
2
2
  import { query, forkSession } from '@anthropic-ai/claude-agent-sdk'
3
3
  import { claudeConfigDir } from './utils/claude-config-dir.js'
4
+ import { claudeSettingSourcesFor, projectSettingsAllowedAsync, projectSettingsDecidedWithoutScan } from './claude-setting-sources.js'
4
5
  import { performance } from 'node:perf_hooks'
5
6
  import { CLAUDE_BINARY_CANDIDATES, resolveClaudeBinary } from './utils/claude-binary.js'
6
7
  import { labelBinarySpawnFailure } from './utils/verify-binary.js'
@@ -10,7 +11,7 @@ import { updateModels, saveModelsCache, updateContextWindow, getModels, getRoste
10
11
  import { isWellFormedThinkingLevel, resolveThinkingLevels, LEGACY_DEFAULT_THINKING_LEVEL } from '@chroxy/protocol'
11
12
  import { effortRoster, annotateSupportedModels } from './claude-model-refresh.js'
12
13
  import { CLAUDE_FALLBACK_MODELS, claudeModelMetadata } from './claude-model-catalog.js'
13
- import { BaseSession, buildBaseSessionOpts, reportInputAdmission } from './base-session.js'
14
+ import { BaseSession, buildBaseSessionOpts, reportInputAdmission, NOT_ADMITTED_ADMISSION } from './base-session.js'
14
15
  import { normalizeSdkModelUsage } from './usage-normalize.js'
15
16
  import { buildContentBlocks } from './content-blocks.js'
16
17
  import { MessageTransformPipeline } from './message-transform.js'
@@ -1106,6 +1107,42 @@ export class SdkSession extends BaseSession {
1106
1107
  }
1107
1108
 
1108
1109
  this._isBusy = true
1110
+ // The project-settings decision for this turn, taken before any query state is
1111
+ // set up. A folder with no trust record is decided at once; a trusted one is
1112
+ // verified by a fresh scan in a worker thread (busy is already set, so a
1113
+ // follow-up queues meanwhile).
1114
+ let projectAllowed = projectSettingsDecidedWithoutScan(this.cwd)
1115
+ if (projectAllowed === null) {
1116
+ // interrupt() clears the token, which is how a Stop during the verification is seen.
1117
+ const decisionToken = {}
1118
+ this._pendingDecision = decisionToken
1119
+ projectAllowed = await projectSettingsAllowedAsync(this.cwd)
1120
+ const stopped = this._pendingDecision !== decisionToken
1121
+ if (!stopped) this._pendingDecision = null
1122
+ if (stopped && !this._destroying) {
1123
+ // Stopped before the query started: the turn does not run.
1124
+ this._isBusy = false
1125
+ this._permissions.clearUserStopInFlight()
1126
+ this.emit('stopped', { stopRequested: true }) // #9241
1127
+ // A send that arrived during the verification was queued: deliver it now, as the
1128
+ // end of a stopped turn does.
1129
+ if (this._outgoingQueue.length) this.dequeueNextOutgoing()
1130
+ return
1131
+ }
1132
+ }
1133
+ if (this._destroying) {
1134
+ this._isBusy = false
1135
+ return
1136
+ }
1137
+ // #9242: the verification above is an await; re-ask admission before any turn state
1138
+ // or the query exists. Refused: no dispatch; follow-ups that queued meanwhile go on.
1139
+ if (!this._admitPreparedSend(sendOptions)) {
1140
+ this._isBusy = false
1141
+ this._permissions.clearUserStopInFlight()
1142
+ reportInputAdmission(sendOptions, NOT_ADMITTED_ADMISSION)
1143
+ if (this._outgoingQueue.length) this.dequeueNextOutgoing()
1144
+ return
1145
+ }
1109
1146
  // #7376: a turn starts with no Stop requested, whatever the last one did.
1110
1147
  this._stopRequestedThisTurn = false
1111
1148
  this._stopCancelledToolUseIds.clear() // #8363
@@ -1180,7 +1217,7 @@ export class SdkSession extends BaseSession {
1180
1217
  cwd: this.cwd,
1181
1218
  permissionMode: sdkPermMode,
1182
1219
  includePartialMessages: true,
1183
- settingSources: ['user', 'project', 'local'],
1220
+ settingSources: claudeSettingSourcesFor(projectAllowed),
1184
1221
  systemPrompt,
1185
1222
  tools: { type: 'preset', preset: 'claude_code' },
1186
1223
  // The environment for the `claude` child query() spawns, built per turn
@@ -1384,6 +1421,9 @@ export class SdkSession extends BaseSession {
1384
1421
  // so a stop request cannot be made (and must not be pretended to have been).
1385
1422
  let queryFailed = false
1386
1423
  let queryClosed = false
1424
+ // #8329: set by the catch when the user's Stop is what aborted the turn, so the
1425
+ // shell report says "stopped" rather than "ended abnormally".
1426
+ let endedByUserStop = false
1387
1427
  // #8302: THE routine that asks the CLI to stop the turn's still-tracked
1388
1428
  // shells and turns the answers into reports. Used by the prompt's own result
1389
1429
  // (`finishTurn`, for shells no live task names) AND by the `finally` (every
@@ -1427,7 +1467,7 @@ export class SdkSession extends BaseSession {
1427
1467
  ? `Background shell "${task.description}" was still running when the turn ended and was stopped with it; ${tail}`
1428
1468
  : asked
1429
1469
  ? `Background shell "${task.description}" was still running when the turn ended; the CLI did not acknowledge a stop request, so its termination is UNCONFIRMED. ${tail}`
1430
- : `Background shell "${task.description}" was still tracked when the turn ended abnormally; the turn's query was no longer usable, so it could not be asked to stop and its termination is UNCONFIRMED. ${tail}`,
1470
+ : `Background shell "${task.description}" was still tracked when the turn ${endedByUserStop ? 'was stopped' : 'ended abnormally'}; the turn's query was no longer usable, so it could not be asked to stop and its termination is UNCONFIRMED. ${tail}`,
1431
1471
  toolUseId: null,
1432
1472
  taskId: task.taskId,
1433
1473
  stopped: outcome === 'stopped',
@@ -1651,10 +1691,11 @@ export class SdkSession extends BaseSession {
1651
1691
  code: 'background_task_ended_with_turn',
1652
1692
  message: stopped
1653
1693
  ? `Background ${kind} "${task.description}" was still running when the turn ended and was stopped with it; a claude-sdk session runs background work only within the turn that started it.`
1654
- : `Background ${kind} "${task.description}" was still running when the turn ended and could not be stopped; it may still be running. A claude-sdk session runs background work only within the turn that started it.`,
1694
+ : `Background ${kind} "${task.description}" was still running when the turn ended; the CLI did not acknowledge a stop request, so its termination is UNCONFIRMED. A claude-sdk session runs background work only within the turn that started it.`,
1655
1695
  toolUseId: task.toolUseId,
1656
1696
  taskId: task.taskId,
1657
1697
  stopped,
1698
+ unconfirmed: !stopped,
1658
1699
  recoverable: true,
1659
1700
  })
1660
1701
  // A background shell's `task_id` is the shell id the tool_result
@@ -1771,6 +1812,8 @@ export class SdkSession extends BaseSession {
1771
1812
  declarationTurnId: messageId,
1772
1813
  declarationEligible: !supersededByNewerTurn() && !this._stdinForwardingDisabled && sdkDeclarationEligible(msg),
1773
1814
  ...turnOutcomeField(outcomeFromSdkResult(msg)),
1815
+ // #9241: `aborted_*` is the SDK saying the abort ended the turn.
1816
+ ...(outcomeFromSdkResult(msg) === 'stopped' ? { stopRequested: true } : {}),
1774
1817
  }, 'turn_ended_with_orphan_tool_start', { completion: 'normal' }) // #7376
1775
1818
 
1776
1819
  // #7340: NOT `{ turnEndedCleanly: true }`, however much this looks
@@ -2334,6 +2377,7 @@ export class SdkSession extends BaseSession {
2334
2377
  // classification), and a Stop that lands during that await did not end a turn
2335
2378
  // that had already failed.
2336
2379
  const userStopEndedTurn = this._permissions.isUserStopInFlight()
2380
+ if (wasIntentionalStop) endedByUserStop = true
2337
2381
  if (!this._destroying) {
2338
2382
  if (closedAfterResult && isQueryCloseError(err)) {
2339
2383
  // #8300: finishTurn already emitted this turn's result and closed
@@ -2348,7 +2392,9 @@ export class SdkSession extends BaseSession {
2348
2392
  // with CliSession. No `code` because SDK runs in-process — there
2349
2393
  // is no child-process exit status to carry.
2350
2394
  ;(this._log || log).info('Query aborted after user stop')
2351
- emitTurnEvent('stopped', {})
2395
+ // #9241: `stopRequested` only for the abort the Stop caused, not any other
2396
+ // error that happened to land after it.
2397
+ emitTurnEvent('stopped', isQueryCloseError(err) ? { stopRequested: true } : {})
2352
2398
  } else if (spawnRefused) {
2353
2399
  // #8030: the turn was refused BEFORE query() was ever called — by the
2354
2400
  // per-spawn binary gate (a block-mode hash mismatch, quarantine, a
@@ -3142,8 +3188,8 @@ export class SdkSession extends BaseSession {
3142
3188
  * Resolve a pending permission request (called by WsServer when
3143
3189
  * the app sends permission_response).
3144
3190
  */
3145
- respondToPermission(requestId, decision, editedInput, reason, scope) {
3146
- return this._permissions.respondToPermission(requestId, decision, editedInput, reason, scope)
3191
+ respondToPermission(requestId, decision, editedInput, reason, scope, resolvedBy) {
3192
+ return this._permissions.respondToPermission(requestId, decision, editedInput, reason, scope, resolvedBy)
3147
3193
  }
3148
3194
 
3149
3195
  /**
@@ -3575,6 +3621,13 @@ export class SdkSession extends BaseSession {
3575
3621
  // already settling) so an interrupt never strands a queued message.
3576
3622
  this.clearOutgoingQueue()
3577
3623
 
3624
+ if (this._pendingDecision) {
3625
+ // A Stop while the turn is still verifying the folder: sendMessage sees the
3626
+ // cleared token and does not start the query.
3627
+ this._pendingDecision = null
3628
+ return
3629
+ }
3630
+
3578
3631
  if (!this._query) {
3579
3632
  // #8430: a Stop with nothing to interrupt -- no query yet -- and no prompt
3580
3633
  // open has nothing to label; do not leave it armed for the rest of the turn.
@@ -149,7 +149,12 @@ export class PushNotificationHandler {
149
149
  log.debug(`Push suppressed for ${event} on ${sessionId}: no configured notification sinks`)
150
150
  }
151
151
  if (hasSinks) {
152
- if (event === 'result') {
152
+ if (event === 'result' && data?.turnOutcome === 'stopped_before_output') {
153
+ // #9241: the turn was stopped before any reply, which the person who stopped
154
+ // it just did. "Session idle" (the Expo push and, through the same pipeline,
155
+ // the Discord status embed) would announce a cancellation back to them.
156
+ log.debug(`Idle push suppressed for ${sessionId}: the turn was stopped before any reply`)
157
+ } else if (event === 'result') {
153
158
  // Session idle push (#3866). Gate on noActiveViewers so the user
154
159
  // isn't pinged while actively chatting with this session. The
155
160
  // per-session dedupe Set prevents a duplicate `result` from
package/src/server-cli.js CHANGED
@@ -65,12 +65,15 @@ import { clientActiveProvider, overlayBroadcastReachesProvider, broadcastRosterP
65
65
  // environment-manager.js itself remains behind the dynamic import below
66
66
  // (`if (config?.environments?.enabled)`).
67
67
  import { UNREACHABLE_STATUSES } from './environment-statuses.js'
68
- import { resolveSkipPermissions, buildEnvironmentBackend, isUserShellEnabled, getAllowAnyModelProviders, isSemanticTitlesEnabled, resolveSemanticTitleModel, resolveSemanticTitleTimeoutMs, resolveBinaryProvenanceMode, isBinarySignatureGateEnabled, applyCodexBinaryConfig } from './config.js'
68
+ import { resolveSkipPermissions, buildEnvironmentBackend, isUserShellEnabled, getAllowAnyModelProviders, isSemanticTitlesEnabled, resolveSemanticTitleModel, resolveSemanticTitleTimeoutMs, resolveBinaryProvenanceMode, isBinarySignatureGateEnabled, applyCodexBinaryConfig, resolveSessionNaming } from './config.js'
69
69
  import { sweepStaleProviderDirs } from './sweep-stale-provider-dirs.js'
70
70
  import { buildOrchestrationManager } from './orchestration/build-manager.js'
71
71
  import { buildSchedulerEngine } from './scheduler.js'
72
72
  import { parseDuration } from './duration.js'
73
73
  import { createSessionTokenStore } from './session-token-store.js'
74
+ import { createPrincipalStore } from './principal-store.js'
75
+ import { createPrincipalBrakes } from './principal-brakes.js'
76
+ import { PrincipalJournal } from './principal-journal.js'
74
77
  import { StatusLineManager } from './statusline.js'
75
78
  import { warnIfClaudeConfigDirUnusable } from './utils/claude-config-dir.js'
76
79
 
@@ -1186,6 +1189,8 @@ export async function startCliServer(config) {
1186
1189
  // operator set userShell.enabled:true in the config file. Enforced in
1187
1190
  // SessionManager.createSession so it covers every spawn path.
1188
1191
  userShellEnabled: isUserShellEnabled(config),
1192
+ // Unnamed sessions are named "<project> <n>" unless the operator sets sessionNaming: 'legacy'.
1193
+ sessionNaming: resolveSessionNaming(config),
1189
1194
  // #6378: providers opted into unrestricted model validation (serve any
1190
1195
  // API-valid model id without a release). Empty Set unless the operator set
1191
1196
  // config.providers.allowAnyModel.
@@ -1350,6 +1355,11 @@ export async function startCliServer(config) {
1350
1355
  // (and all timers are .unref()'d, so they never block process exit anyway).
1351
1356
  statusLineManager.stopSession(sessionId)
1352
1357
  })
1358
+ // A session whose folder is no longer trusted stops showing the status line that
1359
+ // came from the folder's own settings (Stop trusting, or an edit that revoked it).
1360
+ sessionManager.on('folder_trust_lost', ({ sessionId }) => {
1361
+ statusLineManager.clearProjectOutput(sessionId)
1362
+ })
1353
1363
  // Turn-boundary refresh for immediacy (mirrors Claude Code's "new assistant
1354
1364
  // message" trigger); the periodic loop in StatusLineManager covers the rest.
1355
1365
  sessionManager.on('session_event', ({ sessionId, event }) => {
@@ -1562,6 +1572,16 @@ export async function startCliServer(config) {
1562
1572
  })
1563
1573
  daemonUpdate.start()
1564
1574
 
1575
+ // The brakes (kill switch + file-backed audit requirement) ride on the store's state().
1576
+ const principalStore = createPrincipalStore()
1577
+ principalStore.attachBrakes(createPrincipalBrakes())
1578
+ const principalJournal = new PrincipalJournal({
1579
+ dir: configPath('principal-journal'),
1580
+ enabled: () => principalStore.hasEntries(),
1581
+ })
1582
+ // A journal whose session no longer exists is dead weight: drop it at boot.
1583
+ try { principalJournal.prune((id) => sessionManager.getSession(id) != null) } catch (err) { log.warn(`principal journal prune failed: ${err?.message || err}`) }
1584
+
1565
1585
  wsServer = new WsServer({
1566
1586
  port: PORT,
1567
1587
  apiToken: API_TOKEN,
@@ -1586,6 +1606,15 @@ export async function startCliServer(config) {
1586
1606
  localhostBypass: !config.encryptLocalhost,
1587
1607
  tokenManager,
1588
1608
  pairingManager,
1609
+ // #9116: the agent-principal store. Hash-only, 0600, read through the trusted-file
1610
+ // read; an absent store is empty and an untrusted one invalidates every principal.
1611
+ // Nothing can mint a token yet (landing order: S11 first), so on a real install this
1612
+ // is empty.
1613
+ principalStore,
1614
+ // #9118: the normalized event journal behind the principal read path. It records only
1615
+ // while the principal store has an entry, so a daemon with no principals journals
1616
+ // nothing (and writes nothing). 0600 sidecar files in <config dir>/principal-journal.
1617
+ principalJournal,
1589
1618
  // #5536 — the identity keypair the WsServer uses to sign each connection's
1590
1619
  // ephemeral exchange public key (both eager and discrete paths). Null when
1591
1620
  // pinning is unavailable (no-auth / no-encrypt / keychain failure).
@@ -124,6 +124,14 @@ export const DEFAULT_DISCOVERY_INTERVAL_MS = 5 * 60_000
124
124
  /** Upper bound on surveys (git + gh subprocesses) started by one tick. */
125
125
  export const DEFAULT_MAX_SURVEYS_PER_TICK = 4
126
126
 
127
+ /**
128
+ * #8326: consecutive daemon wakes a session gets with no user-typed input in
129
+ * between, before the next one is refused (`wake-cap`; the push still goes out).
130
+ * 3 = the failing-CI -> fix -> push cycle gets a few honest attempts, while a
131
+ * runaway model that never converges is stopped within a handful of turns.
132
+ */
133
+ export const DEFAULT_MAX_CONSECUTIVE_WAKES = 3
134
+
127
135
  /**
128
136
  * Consecutive `'undeterminable'` SWEEP readings after which a session is demoted
129
137
  * from every-tick to a capped backoff (#7443).
@@ -342,6 +350,11 @@ export class SessionCiWatcher {
342
350
  * dispatch AND again when a queued wake is about to flush, since the
343
351
  * preceding turn's result can trip the budget pause after the wake queued.
344
352
  * A throw reads as a refusal. Absent = never refused.
353
+ * @param {(handlers: {onReleased: (sessionId: string) => void, onDestroyed: (sessionId: string) => void}) => (() => void)} [opts.subscribeTurnDrivenReleases]
354
+ * - #9301: register for "no TurnDriver occupies this session any more" and
355
+ * "this session is gone"; returns the unsubscribe. Absent = a wake refused as
356
+ * `orchestrated` is dropped (the pre-#9301 behaviour). Attached by `start()`
357
+ * and detached by `stop()`.
345
358
  * @param {boolean} [opts.wakeAgent] - when false, completions notify the user
346
359
  * but never wake a session (neither the PTY route nor the turn-input route).
347
360
  * @param {(wake: {sessionId: string, text: string, messageId: string}) => void} [opts.recordWakeInput]
@@ -353,8 +366,8 @@ export class SessionCiWatcher {
353
366
  * exists only for a turn that really ran. A queued wake is visible to clients
354
367
  * meanwhile through the provider's own `message_queued`/`message_dequeued`
355
368
  * mirror, which shows and then removes it from the queued strip: the flushed
356
- * wake therefore ends as exactly one chat bubble, a cancelled one as none. Absent = the wake still reaches the agent but
357
- * clients do not see it.
369
+ * wake therefore ends as exactly one chat bubble, a cancelled one as none.
370
+ * Absent = the wake still reaches the agent but clients do not see it.
358
371
  * @param {number} [opts.tickIntervalMs]
359
372
  * @param {number} [opts.discoveryIntervalMs]
360
373
  * @param {number} [opts.maxSurveysPerTick]
@@ -370,7 +383,9 @@ export class SessionCiWatcher {
370
383
  survey = surveySessionPrStatus,
371
384
  notify,
372
385
  recordWakeInput,
386
+ noteWakeDispatched,
373
387
  daemonTurnRefusal,
388
+ subscribeTurnDrivenReleases,
374
389
  wakeAgent = true,
375
390
  tickIntervalMs = DEFAULT_TICK_INTERVAL_MS,
376
391
  discoveryIntervalMs = DEFAULT_DISCOVERY_INTERVAL_MS,
@@ -384,8 +399,20 @@ export class SessionCiWatcher {
384
399
  this._survey = survey
385
400
  this._notify = typeof notify === 'function' ? notify : null
386
401
  this._recordWakeInput = typeof recordWakeInput === 'function' ? recordWakeInput : null
402
+ this._noteWakeDispatched = typeof noteWakeDispatched === 'function' ? noteWakeDispatched : null
387
403
  this._daemonTurnRefusal = typeof daemonTurnRefusal === 'function' ? daemonTurnRefusal : null
388
404
  this._wakeSeq = 0
405
+ this._subscribeReleases = typeof subscribeTurnDrivenReleases === 'function' ? subscribeTurnDrivenReleases : null
406
+ this._unsubscribeReleases = null
407
+ /**
408
+ * #9301: sessionId → Map<prNumber, { event, verdict }> — completions whose
409
+ * agent wake was refused as `orchestrated`. At most ONE per (session, PR):
410
+ * a newer fire for the same PR replaces it. Entries leave on delivery, on
411
+ * supersede (a different head for that PR is seen), when the PR is no longer
412
+ * open, and when the session is destroyed — so the map is bounded by live
413
+ * sessions x their open PRs.
414
+ */
415
+ this._deferred = new Map()
389
416
  this._wakeAgent = wakeAgent !== false
390
417
  this._tickIntervalMs = tickIntervalMs
391
418
  this._discoveryIntervalMs = discoveryIntervalMs
@@ -513,6 +540,9 @@ export class SessionCiWatcher {
513
540
  for (const id of this._state.keys()) {
514
541
  if (!live.has(id)) this._state.delete(id)
515
542
  }
543
+ for (const id of this._deferred.keys()) {
544
+ if (!live.has(id)) this._deferred.delete(id)
545
+ }
516
546
 
517
547
  const now = this._now()
518
548
  const due = sessions.filter(s => {
@@ -614,6 +644,7 @@ export class SessionCiWatcher {
614
644
  // left to report on, so drop any arm.
615
645
  if (!snapshot?.pr) {
616
646
  st.armed = null
647
+ this._dropDeferred(sessionId)
617
648
  return 'no-pr'
618
649
  }
619
650
 
@@ -621,6 +652,19 @@ export class SessionCiWatcher {
621
652
  const headRefOid = snapshot.pr.headRefOid
622
653
  const verdict = terminalVerdict(snapshot)
623
654
 
655
+ // #9301: a different head for a PR whose wake is parked means a newer push
656
+ // replaced it — that result is stale, never deliver it. Only on the watcher's
657
+ // OWN reading (`fire`): an `observe()` survey can resolve after a push while
658
+ // reporting the OLDER head, and must not discard the parked wake for the current one.
659
+ const perPr = fire ? this._deferred.get(sessionId) : undefined
660
+ if (perPr) {
661
+ // The session's current PR is `number`: anything parked for another PR is
662
+ // for one it has moved on from. Same PR, different head: superseded.
663
+ for (const [n, { event: parkedEvent }] of [...perPr]) {
664
+ if (n !== number || parkedEvent.headRefOid !== headRefOid) this._dropDeferred(sessionId, n)
665
+ }
666
+ }
667
+
624
668
  if (verdict === null) {
625
669
  // Still going, or no run yet for this head.
626
670
  // Arm only on a run that is actually RUNNING, and only with a head SHA:
@@ -725,6 +769,10 @@ export class SessionCiWatcher {
725
769
  * versa.
726
770
  */
727
771
  _fire(sessionId, snapshot, verdict) {
772
+ // #9301: whatever was parked for this PR is older than this completion (a
773
+ // same-head re-run, or a newer head); never let it be delivered after this
774
+ // one. Re-parked below only if THIS completion is itself refused `orchestrated`.
775
+ this._dropDeferred(sessionId, snapshot.pr.number)
728
776
  const event = {
729
777
  sessionId,
730
778
  prNumber: snapshot.pr.number,
@@ -751,45 +799,125 @@ export class SessionCiWatcher {
751
799
  if (refusal !== null) {
752
800
  // The user is still notified above; only the agent half is withheld, and
753
801
  // nothing is sent, queued or recorded.
802
+ //
803
+ // #9184 / #9301, decided: a refused wake is DROPPED for every reason EXCEPT
804
+ // `orchestrated`. The CI arm for this head is already consumed (`lastFired`),
805
+ // so nothing re-fires it, and a driven turn can last up to the turn timeout:
806
+ // dropping would let the agent miss that head's result. So an `orchestrated`
807
+ // refusal is parked (one per session per PR) and delivered ONCE, through the
808
+ // same wake path, when the last TurnDriver releases the session
809
+ // (`_deliverDeferred`). It is discarded if a newer head replaces it, the PR
810
+ // closes or the session is destroyed. The user push above is never re-sent.
811
+ // Every other refusal (budget, Stop, wake cap, provider state) is still a
812
+ // drop, visible in the log line below.
813
+ if (refusal === 'orchestrated' && this._subscribeReleases) this._deferWake(sessionId, event, verdict)
754
814
  wakeOutcome = refusal
755
815
  } else if (this._wakeAgent && this._resolveSession) {
756
- // Stable, daemon-authored id for the turn-input route: the provider's
757
- // queue mirror and the history entry carry it. The time prefix keeps ids
758
- // unique across daemon restarts (history is persisted, a bare counter
759
- // would repeat). Charset/length satisfy input-handlers' id grammar.
760
- const messageId = `chroxy-ci-wake-${this._now().toString(36)}-${++this._wakeSeq}`
761
- // Admission can land AFTER wakeSession returns (an async provider). The
762
- // flag lets the late callback say so in its own log line instead of the
763
- // outcome in the line below being silently stale.
764
- let firing = true
765
- try {
766
- wakeOutcome = wakeSession(this._resolveSession(sessionId), buildAgentWakeText(event), {
767
- turnInput: true,
768
- clientMessageId: messageId,
769
- admitAtFlush: () => this._wakeRefusal(sessionId) === null,
770
- onAdmission: ({ outcome, line }) => {
771
- // Visible like a typed turn — but only once it has actually been
772
- // DISPATCHED. A rejected wake never reached the model, and a queued
773
- // one may yet be cancelled at flush (budget paused, user Stop,
774
- // interrupt): recording it at enqueue left a phantom user turn in
775
- // history that no model ever saw. `injected` arrives immediately for
776
- // an idle session and at flush for a queued one.
777
- if (outcome === 'injected') this._recordWake(sessionId, line, messageId)
778
- if (!firing) {
779
- this._log?.info?.(`ci-watch: #${event.prNumber} wake for session ${sessionId} admitted late (wake: ${outcome})`)
780
- }
781
- },
782
- })
783
- } catch (err) {
784
- wakeOutcome = 'error'
785
- this._log?.warn?.(`ci-watch: agent wake failed for ${sessionId}: ${getErrorMessage(err, 'unknown error')}`)
786
- } finally {
787
- firing = false
788
- }
816
+ wakeOutcome = this._sendWake(sessionId, event)
789
817
  }
790
818
  this._log?.info?.(`ci-watch: #${event.prNumber} settled ${verdict} for session ${sessionId} (wake: ${wakeOutcome})`)
791
819
  }
792
820
 
821
+ /**
822
+ * Hand the wake to the session (turn-input / PTY route) and report the outcome.
823
+ * Shared by `_fire` and the post-release delivery so both take the SAME path.
824
+ * The caller has already established that no refusal applies.
825
+ */
826
+ _sendWake(sessionId, event) {
827
+ let wakeOutcome = 'disabled'
828
+ // Stable, daemon-authored id for the turn-input route: the provider's
829
+ // queue mirror and the history entry carry it. The time prefix keeps ids
830
+ // unique across daemon restarts (history is persisted, a bare counter
831
+ // would repeat). Charset/length satisfy input-handlers' id grammar.
832
+ const messageId = `chroxy-ci-wake-${this._now().toString(36)}-${++this._wakeSeq}`
833
+ // Admission can land AFTER wakeSession returns (an async provider). The
834
+ // flag lets the late callback say so in its own log line instead of the
835
+ // outcome in the line below being silently stale.
836
+ let firing = true
837
+ // #8326: count each DISPATCHED wake exactly once. The turn-input route
838
+ // reports dispatch through onAdmission('injected') (immediately, or at
839
+ // flush for a queued wake); the claude-tui PTY route returns 'injected'
840
+ // synchronously and never calls onAdmission.
841
+ let counted = false
842
+ const countOnce = () => {
843
+ if (counted) return
844
+ counted = true
845
+ this._noteDispatched(sessionId)
846
+ }
847
+ try {
848
+ wakeOutcome = wakeSession(this._resolveSession(sessionId), buildAgentWakeText(event), {
849
+ turnInput: true,
850
+ clientMessageId: messageId,
851
+ admitAtFlush: () => this._wakeRefusal(sessionId) === null,
852
+ onAdmission: ({ outcome, line }) => {
853
+ // Visible like a typed turn — but only once it has actually been
854
+ // DISPATCHED. A rejected wake never reached the model, and a queued
855
+ // one may yet be cancelled at flush (budget paused, user Stop,
856
+ // interrupt): recording it at enqueue left a phantom user turn in
857
+ // history that no model ever saw. `injected` arrives immediately for
858
+ // an idle session and at flush for a queued one.
859
+ if (outcome === 'injected') {
860
+ countOnce()
861
+ this._recordWake(sessionId, line, messageId)
862
+ }
863
+ if (!firing) {
864
+ this._log?.info?.(outcome === 'rejected'
865
+ ? `ci-watch: #${event.prNumber} wake for session ${sessionId} rejected late, after dispatch was first attempted (wake: ${outcome})`
866
+ : `ci-watch: #${event.prNumber} wake for session ${sessionId} admitted late (wake: ${outcome})`)
867
+ }
868
+ },
869
+ })
870
+ if (wakeOutcome === 'injected') countOnce()
871
+ } catch (err) {
872
+ wakeOutcome = 'error'
873
+ this._log?.warn?.(`ci-watch: agent wake failed for ${sessionId}: ${getErrorMessage(err, 'unknown error')}`)
874
+ } finally {
875
+ firing = false
876
+ }
877
+ return wakeOutcome
878
+ }
879
+
880
+ /** #9301: park a completion whose wake was refused as `orchestrated`. */
881
+ _deferWake(sessionId, event, verdict) {
882
+ let perPr = this._deferred.get(sessionId)
883
+ if (!perPr) { perPr = new Map(); this._deferred.set(sessionId, perPr) }
884
+ perPr.set(event.prNumber, { event, verdict })
885
+ }
886
+
887
+ _dropDeferred(sessionId, prNumber) {
888
+ const perPr = this._deferred.get(sessionId)
889
+ if (!perPr) return
890
+ if (prNumber === undefined) perPr.clear(); else perPr.delete(prNumber)
891
+ if (perPr.size === 0) this._deferred.delete(sessionId)
892
+ }
893
+
894
+ /**
895
+ * #9301: the last TurnDriver let go of `sessionId` — deliver what it deferred,
896
+ * once. Each entry is re-checked first: still the head this watcher last
897
+ * announced for that PR (a newer head would have replaced or cleared it), and
898
+ * the session still wakeable. `orchestrated` again (re-driven in the meantime)
899
+ * KEEPS the entry for the next release; any other refusal drops it, exactly as
900
+ * it would have at fire time. The entry is removed BEFORE dispatch so a
901
+ * re-entrant release cannot deliver it twice.
902
+ */
903
+ _deliverDeferred(sessionId) {
904
+ const perPr = this._deferred.get(sessionId)
905
+ if (!perPr || this._stopped) return
906
+ const st = this._state.get(sessionId)
907
+ for (const [prNumber, { event }] of [...perPr]) {
908
+ const last = st?.lastFired
909
+ if (!last || last.number !== prNumber || last.headRefOid !== event.headRefOid) {
910
+ this._dropDeferred(sessionId, prNumber)
911
+ continue
912
+ }
913
+ const refusal = this._wakeRefusal(sessionId)
914
+ if (refusal === 'orchestrated') continue
915
+ this._dropDeferred(sessionId, prNumber)
916
+ const outcome = refusal ?? this._sendWake(sessionId, event)
917
+ this._log?.info?.(`ci-watch: #${prNumber} deferred wake for session ${sessionId} delivered after release (wake: ${outcome})`)
918
+ }
919
+ }
920
+
793
921
  /**
794
922
  * Why this session must not be handed a wake right now, or null. A throwing
795
923
  * gate refuses, and so does a non-string, non-null answer: only a literal null
@@ -807,6 +935,16 @@ export class SessionCiWatcher {
807
935
  }
808
936
  }
809
937
 
938
+ /** Count a dispatched wake toward the cap; isolated like the recording. */
939
+ _noteDispatched(sessionId) {
940
+ if (!this._noteWakeDispatched) return
941
+ try {
942
+ this._noteWakeDispatched(sessionId)
943
+ } catch (err) {
944
+ this._log?.warn?.(`ci-watch: counting the wake for ${sessionId} failed: ${getErrorMessage(err, 'unknown error')}`)
945
+ }
946
+ }
947
+
810
948
  /** Record + broadcast an admitted wake; isolated so a failure costs nothing else. */
811
949
  _recordWake(sessionId, text, messageId) {
812
950
  if (!this._recordWakeInput) return
@@ -817,9 +955,23 @@ export class SessionCiWatcher {
817
955
  }
818
956
  }
819
957
 
958
+ /** #9301: listen for session release / destroy (idempotent). */
959
+ _attachReleases() {
960
+ if (!this._subscribeReleases || this._unsubscribeReleases) return
961
+ this._unsubscribeReleases = this._subscribeReleases({
962
+ onReleased: sessionId => {
963
+ try { this._deliverDeferred(sessionId) } catch (err) {
964
+ this._log?.warn?.(`ci-watch: deferred wake for ${sessionId} failed: ${getErrorMessage(err, 'unknown error')}`)
965
+ }
966
+ },
967
+ onDestroyed: sessionId => this._dropDeferred(sessionId),
968
+ })
969
+ }
970
+
820
971
  /** Start the periodic sweep. The first tick runs immediately. Idempotent. */
821
972
  start() {
822
973
  this._stopped = false
974
+ this._attachReleases()
823
975
  // A second start() would otherwise leak the first interval: `_timer` is
824
976
  // overwritten and stop() can only ever clear the last one.
825
977
  if (this._timer) return this
@@ -835,6 +987,9 @@ export class SessionCiWatcher {
835
987
  /** Stop the sweep. Idempotent. */
836
988
  stop() {
837
989
  this._stopped = true
990
+ this._unsubscribeReleases?.()
991
+ this._unsubscribeReleases = null
992
+ this._deferred.clear()
838
993
  if (this._timer) {
839
994
  clearInterval(this._timer)
840
995
  this._timer = null
@@ -892,6 +1047,9 @@ export function buildSessionCiWatcher({ config, sessionManager, pushManager = nu
892
1047
  // A non-positive interval would spin the sweep; config.js warns about it, and
893
1048
  // the value is ignored here rather than honoured.
894
1049
  const positive = v => typeof v === 'number' && Number.isFinite(v) && v > 0
1050
+ const maxConsecutiveWakes = positive(sessionCi.maxConsecutiveWakes)
1051
+ ? Math.max(1, Math.floor(sessionCi.maxConsecutiveWakes))
1052
+ : DEFAULT_MAX_CONSECUTIVE_WAKES
895
1053
  return new SessionCiWatcher({
896
1054
  listSessions: () => sessionManager?.listSessions?.() ?? [],
897
1055
  resolveSession: sessionId => sessionManager?.getSession?.(sessionId)?.session ?? null,
@@ -905,12 +1063,27 @@ export function buildSessionCiWatcher({ config, sessionManager, pushManager = nu
905
1063
  // review, measured: 0.5 -> 0 surveys per tick).
906
1064
  ...(positive(sessionCi.maxSurveysPerTick) ? { maxSurveysPerTick: Math.max(1, Math.floor(sessionCi.maxSurveysPerTick)) } : {}),
907
1065
  ...(survey ? { survey } : {}),
908
- // #8301: a turn-input wake is a user turn the provider ADMITTED — put it in
1066
+ // #8301: a turn-input wake is a user turn the provider DISPATCHED — put it in
909
1067
  // history and on the wire the way a typed input is. The manager method is the
910
1068
  // seam: this module never imports a transport.
911
1069
  // One refusal seam on the manager: the cost-budget pause (which refuses typed
912
1070
  // input), a user Stop, and the provider's own unwilling states.
913
- daemonTurnRefusal: (sessionId) => sessionManager?.daemonTurnRefusal?.(sessionId) ?? null,
1071
+ // #8326: the cap on consecutive daemon wakes with no user-typed input between.
1072
+ daemonTurnRefusal: (sessionId) => sessionManager?.daemonTurnRefusal?.(sessionId, { maxConsecutiveWakes }) ?? null,
1073
+ noteWakeDispatched: (sessionId) => sessionManager?.noteDaemonWake?.(sessionId),
1074
+ // #9301: deliver a wake refused as `orchestrated` once the driver releases.
1075
+ subscribeTurnDrivenReleases: sessionManager?.on
1076
+ ? ({ onReleased, onDestroyed }) => {
1077
+ const released = ({ sessionId } = {}) => onReleased(sessionId)
1078
+ const destroyed = ({ sessionId } = {}) => onDestroyed(sessionId)
1079
+ sessionManager.on('turn_driven_released', released)
1080
+ sessionManager.on('session_destroyed', destroyed)
1081
+ return () => {
1082
+ sessionManager.off('turn_driven_released', released)
1083
+ sessionManager.off('session_destroyed', destroyed)
1084
+ }
1085
+ }
1086
+ : undefined,
914
1087
  recordWakeInput: ({ sessionId, text, messageId }) => {
915
1088
  sessionManager?.recordDaemonUserInput?.(sessionId, text, messageId)
916
1089
  },