@chroxy/server 0.10.0 → 0.11.0

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 (160) hide show
  1. package/CONFIG.md +411 -14
  2. package/hooks/permission-hook.sh +253 -3
  3. package/package.json +8 -15
  4. package/sidecar/node_modules/.package-lock.json +29 -0
  5. package/sidecar/node_modules/ws/LICENSE +20 -0
  6. package/sidecar/node_modules/ws/README.md +548 -0
  7. package/sidecar/node_modules/ws/browser.js +8 -0
  8. package/sidecar/node_modules/ws/index.js +22 -0
  9. package/sidecar/node_modules/ws/lib/buffer-util.js +131 -0
  10. package/sidecar/node_modules/ws/lib/constants.js +19 -0
  11. package/sidecar/node_modules/ws/lib/event-target.js +292 -0
  12. package/sidecar/node_modules/ws/lib/extension.js +203 -0
  13. package/sidecar/node_modules/ws/lib/limiter.js +55 -0
  14. package/sidecar/node_modules/ws/lib/permessage-deflate.js +528 -0
  15. package/sidecar/node_modules/ws/lib/receiver.js +706 -0
  16. package/sidecar/node_modules/ws/lib/sender.js +602 -0
  17. package/sidecar/node_modules/ws/lib/stream.js +161 -0
  18. package/sidecar/node_modules/ws/lib/subprotocol.js +62 -0
  19. package/sidecar/node_modules/ws/lib/validation.js +152 -0
  20. package/sidecar/node_modules/ws/lib/websocket-server.js +554 -0
  21. package/sidecar/node_modules/ws/lib/websocket.js +1393 -0
  22. package/sidecar/node_modules/ws/package.json +70 -0
  23. package/sidecar/node_modules/ws/wrapper.mjs +21 -0
  24. package/src/base-session.js +151 -6
  25. package/src/billing-budget.js +5 -1
  26. package/src/binary-provenance-trust.js +95 -0
  27. package/src/built-in-tools/file-ops.js +5 -4
  28. package/src/byok-mcp-client.js +1061 -13
  29. package/src/byok-mcp-config.js +1201 -4
  30. package/src/byok-mcp-fleet.js +374 -29
  31. package/src/byok-mcp-oauth-store.js +327 -0
  32. package/src/byok-mcp-oauth.js +635 -0
  33. package/src/byok-mcp-trust.js +254 -37
  34. package/src/byok-session.js +789 -13
  35. package/src/byok-tool-executor.js +20 -13
  36. package/src/checkpoint-manager.js +33 -6
  37. package/src/chroxy-host-metadata.js +122 -0
  38. package/src/claude-stream-parser.js +56 -0
  39. package/src/claude-tui/pty-driver.js +54 -14
  40. package/src/claude-tui-session.js +106 -7
  41. package/src/cli/config-cmd.js +2 -2
  42. package/src/cli/deploy-cmd.js +1 -1
  43. package/src/cli/init-cmd.js +1 -1
  44. package/src/cli/providers-cmd.js +3 -3
  45. package/src/cli/schedule-cmd.js +775 -0
  46. package/src/cli/server-cmd.js +16 -1
  47. package/src/cli/service-cmd.js +39 -19
  48. package/src/cli/shared.js +7 -4
  49. package/src/cli/tokens-cmd.js +213 -0
  50. package/src/cli/tunnel-cmd.js +1 -1
  51. package/src/cli-session.js +66 -10
  52. package/src/cli.js +4 -0
  53. package/src/codex-app-server-session.js +671 -39
  54. package/src/codex-session.js +121 -18
  55. package/src/config.js +453 -27
  56. package/src/control-room/integrations.js +16 -10
  57. package/src/control-room/skills-inventory.js +6 -1
  58. package/src/control-room/survey.js +32 -0
  59. package/src/credential-store.js +256 -10
  60. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  61. package/src/diagnostics.js +3 -0
  62. package/src/docker-sdk-session.js +16 -1
  63. package/src/docker-session.js +9 -0
  64. package/src/doctor.js +19 -8
  65. package/src/environments/backends/docker.js +8 -0
  66. package/src/environments/backends/k8s.js +9 -0
  67. package/src/event-ingest.js +19 -1
  68. package/src/event-normalizer.js +354 -19
  69. package/src/external-session-registry.js +0 -0
  70. package/src/gemini-session.js +19 -2
  71. package/src/github-webhook.js +188 -4
  72. package/src/handler-utils.js +42 -8
  73. package/src/handlers/checkpoint-handlers.js +126 -19
  74. package/src/handlers/control-room-handlers.js +48 -18
  75. package/src/handlers/conversation-handlers.js +127 -2
  76. package/src/handlers/credential-handlers.js +43 -2
  77. package/src/handlers/file-handlers.js +47 -3
  78. package/src/handlers/github-webhook-handlers.js +204 -0
  79. package/src/handlers/input-handlers.js +4 -0
  80. package/src/handlers/orchestration-handlers.js +238 -0
  81. package/src/handlers/scheduler-handlers.js +510 -0
  82. package/src/handlers/session-handlers.js +10 -2
  83. package/src/handlers/settings-handlers.js +510 -11
  84. package/src/handlers/token-handlers.js +11 -2
  85. package/src/http-routes.js +159 -0
  86. package/src/jsonl-reader.js +60 -6
  87. package/src/jsonl-subprocess-session.js +35 -6
  88. package/src/keychain.js +159 -12
  89. package/src/logger.js +182 -19
  90. package/src/notification-prefs.js +88 -6
  91. package/src/notifications/discord-webhook-sink.js +30 -1
  92. package/src/orchestration/build-manager.js +56 -0
  93. package/src/orchestration/decision-contract.js +245 -0
  94. package/src/orchestration/git-ops.js +347 -0
  95. package/src/orchestration/orchestration-manager.js +1295 -0
  96. package/src/orchestration/permission-gate.js +109 -0
  97. package/src/orchestration/role-prompts.js +136 -0
  98. package/src/orchestration/run-budget.js +81 -0
  99. package/src/orchestration/run-ledger.js +487 -0
  100. package/src/orchestration/run-model.js +205 -0
  101. package/src/orchestration/run-record.js +336 -0
  102. package/src/orchestration/run-report.js +194 -0
  103. package/src/orchestration/to-wire.js +201 -0
  104. package/src/orchestration/turn-driver.js +398 -0
  105. package/src/pairing.js +146 -1
  106. package/src/permission-audit.js +79 -3
  107. package/src/permission-floor.js +455 -0
  108. package/src/permission-manager.js +492 -40
  109. package/src/permission-resolver.js +55 -7
  110. package/src/permission-rule-store.js +411 -0
  111. package/src/platform.js +367 -23
  112. package/src/providers.js +21 -2
  113. package/src/schedule-parser.js +311 -0
  114. package/src/scheduled-task-store.js +653 -0
  115. package/src/scheduler.js +1029 -0
  116. package/src/sdk-session.js +338 -5
  117. package/src/server-cli/server-orchestrator.js +23 -0
  118. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  119. package/src/server-cli.js +238 -26
  120. package/src/server-identity.js +28 -4
  121. package/src/service.js +291 -33
  122. package/src/session-manager.js +417 -25
  123. package/src/session-message-history.js +27 -21
  124. package/src/session-title.js +168 -0
  125. package/src/session-token-store.js +60 -35
  126. package/src/skills-usage.js +20 -2
  127. package/src/statusline.js +584 -0
  128. package/src/subagent-counter.js +9 -1
  129. package/src/supervisor.js +77 -27
  130. package/src/token-manager.js +39 -9
  131. package/src/transcript-tasks.js +41 -6
  132. package/src/tunnel/cloudflare.js +115 -8
  133. package/src/tunnel/index.js +4 -1
  134. package/src/tunnel-check.js +1 -1
  135. package/src/turn-tracker.js +0 -0
  136. package/src/usage-normalize.js +118 -0
  137. package/src/user-shell-session.js +98 -32
  138. package/src/utils/componentwise-resolver.js +205 -0
  139. package/src/utils/composite-key.js +45 -0
  140. package/src/utils/iso-datetime.js +51 -0
  141. package/src/utils/preflight.js +140 -28
  142. package/src/utils/spawn-env.js +8 -2
  143. package/src/utils/verify-binary.js +276 -0
  144. package/src/utils/verify-provenance.js +241 -0
  145. package/src/utils/wire-counters.js +48 -0
  146. package/src/worktree-gc.js +4 -1
  147. package/src/ws-file-ops/browser.js +42 -11
  148. package/src/ws-file-ops/common.js +68 -1
  149. package/src/ws-file-ops/git.js +221 -3
  150. package/src/ws-file-ops/index.js +5 -0
  151. package/src/ws-file-ops/memory.js +358 -0
  152. package/src/ws-file-ops/reader.js +124 -0
  153. package/src/ws-forwarding.js +44 -16
  154. package/src/ws-handler-context.js +19 -0
  155. package/src/ws-history.js +84 -11
  156. package/src/ws-message-handlers.js +6 -0
  157. package/src/ws-outbound-schemas.js +207 -0
  158. package/src/ws-permissions.js +285 -4
  159. package/src/ws-schemas.js +1 -0
  160. package/src/ws-server.js +301 -17
@@ -1,9 +1,11 @@
1
- import { query } from '@anthropic-ai/claude-agent-sdk'
1
+ import { query, forkSession } from '@anthropic-ai/claude-agent-sdk'
2
2
  import { join } from 'path'
3
3
  import { homedir } from 'os'
4
+ import { performance } from 'node:perf_hooks'
4
5
  import { updateModels, saveModelsCache, updateContextWindow, getModels, ALLOWED_MODEL_IDS } from './models.js'
5
6
  import { CLAUDE_FALLBACK_MODELS, claudeModelMetadata } from './claude-model-catalog.js'
6
7
  import { BaseSession, buildBaseSessionOpts } from './base-session.js'
8
+ import { normalizeSdkModelUsage } from './usage-normalize.js'
7
9
  import { buildContentBlocks } from './content-blocks.js'
8
10
  import { MessageTransformPipeline } from './message-transform.js'
9
11
  import { emitToolResults } from './tool-result.js'
@@ -13,7 +15,7 @@ import {
13
15
  isRunInBackgroundInput,
14
16
  parseBashOutputShellId,
15
17
  } from './background-shells.js'
16
- import { buildToolStartData, extractToolInputSemantics } from './claude-stream-parser.js'
18
+ import { buildToolStartData, extractToolInputSemantics, parseCompactBoundaryMeta, formatCompactBoundaryContent } from './claude-stream-parser.js'
17
19
  import { createLogger, loggerForSession } from './logger.js'
18
20
  import { PermissionManager, wirePermissionManager } from './permission-manager.js'
19
21
  import { formatBytes } from './utils/format-bytes.js'
@@ -94,6 +96,12 @@ export class SdkSession extends BaseSession {
94
96
  // model ids + the shared models registry). Docker subclasses inherit it.
95
97
  static claudeFamily = true
96
98
 
99
+ // #6769: cap on how long the end-of-turn getContextUsage() control request
100
+ // may delay the `result` broadcast. The CLI answers in milliseconds when
101
+ // alive; the cap only bites when the process is already shutting down —
102
+ // in which case the snapshot is skipped and the result emits without it.
103
+ static CONTEXT_USAGE_SNAPSHOT_TIMEOUT_MS = 2000
104
+
97
105
  /**
98
106
  * Human-readable label shown in the startup banner and anywhere else the
99
107
  * server needs to name this provider (#2953). Each provider owns its own
@@ -133,12 +141,27 @@ export class SdkSession extends BaseSession {
133
141
  // providers — claude-tui sets this to false (deliver-on-complete), all
134
142
  // others stream incremental deltas via stream_delta during a turn.
135
143
  streaming: true,
144
+ // #6888: true when an operator's free-text deny reason (PermissionPrompt's
145
+ // "sent with Deny" textarea) actually reaches the agent. The in-process
146
+ // PermissionManager path feeds it back as the tool's denial message
147
+ // (permission-manager.js buildDenyMessage) on the very next turn — the SDK
148
+ // honors this end to end. Gates the dashboard's deny-reason affordance so
149
+ // it isn't shown on providers that silently drop it (legacy-CLI, codex).
150
+ denyReason: true,
136
151
  // #3209/#3246: SDK rebuilds systemPrompt.append on every turn
137
152
  // (see sdk-session.js#_callQuery), so a runtime toggle of
138
153
  // _activeManualSkills + _loadSkills() takes effect on the next
139
154
  // user message. Subprocess providers don't get this for free —
140
155
  // they snapshot the skills text at session start.
141
156
  skillToggle: true,
157
+ // #6767: the SDK can fork/truncate a resumed conversation to a message
158
+ // boundary (`forkSession({ upToMessageId })`), so a checkpoint restore
159
+ // can branch the conversation ('conversation' / 'both' modes), not just
160
+ // the files. Advertised so the checkpoint UI enables the "Conversation"
161
+ // restore-mode option only where the server can actually honor it.
162
+ // DockerSdkSession overrides this to false — see the instance-level
163
+ // `supportsConversationFork` getter (transcript lives in-container).
164
+ conversationFork: true,
142
165
  }
143
166
  }
144
167
 
@@ -351,6 +374,18 @@ export class SdkSession extends BaseSession {
351
374
  this._query = null
352
375
  this._thinkingLevel = null
353
376
 
377
+ // #6766: last SDK transcript message UUID seen this session. Captured from
378
+ // each full `assistant` message in the query loop and used as the fork
379
+ // boundary (`upToMessageId`) when a checkpoint created just after this
380
+ // point is later restored — so rewind truncates the conversation to the
381
+ // checkpoint instead of resuming the full latest transcript. Only the SDK
382
+ // provider tracks this; subprocess providers leave `lastMessageUuid` null.
383
+ this._lastMessageUuid = null
384
+ // #6766: injectable handle for the SDK's standalone `forkSession` so tests
385
+ // can stub the on-disk transcript fork without a live session (mirrors the
386
+ // instance-level `_query` injection the rest of the suite uses).
387
+ this._forkSessionImpl = forkSession
388
+
354
389
  // #5269 (Control Room Phase 2a): map a Task subagent's tool_use_id (the id
355
390
  // chroxy keys activity/agent nodes by) → the SDK's separate `task_id`,
356
391
  // captured from `task_started` system messages. cancelActivity() needs the
@@ -366,7 +401,11 @@ export class SdkSession extends BaseSession {
366
401
  // a pending prompt silently goes unresponsive after 5 min (#2831). The
367
402
  // pause uses a reference count so concurrent prompts keep the timer
368
403
  // suspended until the last one resolves. (Shared wiring extracted in P2-9.)
369
- this._permissions = new PermissionManager({ log })
404
+ // #6794 — pass cwd so the protected-path floor can resolve relative tool
405
+ // targets (.git/.claude/.env…) against this session's working directory.
406
+ // #6771 — pass the durable rule store so an `allowAlways` decision persists
407
+ // a project-scoped rule and this session seeds from prior grants for its cwd.
408
+ this._permissions = new PermissionManager({ log, cwd: this.cwd, ruleStore: this._permissionRuleStore })
370
409
  wirePermissionManager(this, this._permissions, {
371
410
  onRequest: () => this._pauseResultTimeoutForPermission(),
372
411
  onResolved: () => this._resumeResultTimeoutForPermission(),
@@ -430,6 +469,69 @@ export class SdkSession extends BaseSession {
430
469
  return this._sdkSessionId
431
470
  }
432
471
 
472
+ /**
473
+ * #6766: the transcript UUID of the last full assistant message seen this
474
+ * session, or null before the first turn completes. Checkpoint creation reads
475
+ * this to record a fork boundary; `null` on providers that don't track it.
476
+ * @returns {string|null}
477
+ */
478
+ get lastMessageUuid() {
479
+ return this._lastMessageUuid || null
480
+ }
481
+
482
+ /**
483
+ * #6766: whether this provider can fork/truncate a resumed conversation to a
484
+ * message boundary. True for the SDK provider (the Agent SDK exposes
485
+ * `forkSession({ upToMessageId })`); overridden false where the transcript is
486
+ * not reachable by the host-side fork (see DockerSdkSession — the transcript
487
+ * lives inside the container). The checkpoint restore path gates the real
488
+ * conversation rewind on this; when false it degrades to a files-only restore.
489
+ * @returns {boolean}
490
+ */
491
+ get supportsConversationFork() {
492
+ return true
493
+ }
494
+
495
+ /**
496
+ * #6766: record the fork boundary from a full SDK message. Guarded so a
497
+ * message without a string `uuid` leaves the previous boundary intact.
498
+ * Extracted from the query loop so it can be unit-tested directly.
499
+ * @param {object} msg - An SDK stream message (expects a `uuid` field).
500
+ */
501
+ _captureBoundaryMessage(msg) {
502
+ if (msg && typeof msg.uuid === 'string' && msg.uuid) {
503
+ this._lastMessageUuid = msg.uuid
504
+ }
505
+ }
506
+
507
+ /**
508
+ * #6766: fork a conversation into a new, independent SDK session truncated to
509
+ * a message boundary. Wraps the Agent SDK's standalone `forkSession`, which
510
+ * copies the source transcript (remapping UUIDs) up to and including
511
+ * `upToMessageId`, then returns the new session's id — resumable like any
512
+ * other conversation id. This is what makes checkpoint "Rewind" actually
513
+ * branch the conversation (not just the files) for the SDK provider.
514
+ *
515
+ * @param {object} params
516
+ * @param {string} [params.sessionId] - Source conversation id to fork.
517
+ * Defaults to this session's current SDK id.
518
+ * @param {string} [params.upToMessageId] - Fork boundary (inclusive). Omitted
519
+ * → full copy.
520
+ * @returns {Promise<string|null>} The forked conversation id, or null if the
521
+ * SDK returned no id.
522
+ */
523
+ async forkConversation({ sessionId, upToMessageId } = {}) {
524
+ const source = sessionId || this._sdkSessionId
525
+ if (!source) throw new Error('Cannot fork conversation: no source session id')
526
+ const opts = {}
527
+ if (typeof upToMessageId === 'string' && upToMessageId) opts.upToMessageId = upToMessageId
528
+ // Scope the transcript search to this session's project dir when known; the
529
+ // SDK falls back to searching all project dirs when `dir` is omitted.
530
+ if (this.cwd) opts.dir = this.cwd
531
+ const result = await this._forkSessionImpl(source, opts)
532
+ return result?.sessionId || null
533
+ }
534
+
433
535
  /**
434
536
  * Public accessor for the cumulative stdin_dropped totals (#3544).
435
537
  *
@@ -547,6 +649,22 @@ export class SdkSession extends BaseSession {
547
649
  // false, but the turn may have streamed before the timeout landed).
548
650
  const streamState = { hasStreamStarted: false }
549
651
  let didStreamText = false
652
+ // #6756 — extended-thinking forwarding. Each thinking / redacted_thinking
653
+ // content block gets a DISTINCT thinking messageId (`<turnId>-thinking-<n>`)
654
+ // so its stream never collides with the response text stream. `thinkingBlocks`
655
+ // maps the SDK stream event `index` → that thinking id so the thinking_delta
656
+ // and content_block_stop events (which carry only the index) route correctly.
657
+ const thinkingBlocks = new Map()
658
+ // #6391 (chat-redesign footer-stat) — thinkingId -> performance.now() when
659
+ // the reasoning block opened, so its content_block_stop can stamp the
660
+ // elapsed `thinkingDurationMs` on the thinking stream_end. Turn-local;
661
+ // entries are deleted alongside thinkingBlocks when the block closes.
662
+ // #6943: monotonic clock (perf_hooks), not Date.now() — wall-clock jumps
663
+ // (NTP step, manual change, DST) would otherwise clamp a backward jump to
664
+ // 0 or inflate a forward jump.
665
+ const thinkingStartMs = new Map()
666
+ let thinkingBlockCount = 0
667
+ let didStreamThinking = false
550
668
 
551
669
  const sdkPermMode = this._sdkPermissionMode()
552
670
  // Skills MVP (#2957) — append shared skills via SDK systemPrompt.append.
@@ -774,6 +892,28 @@ export class SdkSession extends BaseSession {
774
892
  // sweep. Idempotent (no-op if already finalized).
775
893
  this._finalizeAgentByToolUseId(msg.tool_use_id)
776
894
  break
895
+ } else if (msg.subtype === 'compact_boundary') {
896
+ // #6768: the SDK compacted the conversation (auto-triggered
897
+ // near the context limit, or manually via `/compact`). Parse
898
+ // the structured `compact_metadata` into a distinct marker
899
+ // instead of letting it fall through to the generic
900
+ // "unknown system event" branch below, which would forward
901
+ // the literal string `compact_boundary` as `content` with no
902
+ // human-readable text and drop trigger/token/duration data
903
+ // entirely.
904
+ const meta = parseCompactBoundaryMeta(msg.compact_metadata)
905
+ ;(this._log || log).info(
906
+ `Context compacted (${meta.trigger}): ${meta.preTokens ?? '?'} -> ${meta.postTokens ?? '?'} tokens` +
907
+ (meta.durationMs != null ? ` in ${meta.durationMs}ms` : '')
908
+ )
909
+ this.emit('message', {
910
+ type: 'system',
911
+ subtype: 'compact_boundary',
912
+ content: formatCompactBoundaryContent(meta),
913
+ compactMetadata: meta,
914
+ timestamp: Date.now(),
915
+ })
916
+ break
777
917
  } else {
778
918
  // Forward non-init system events (e.g. /usage, /cost, other
779
919
  // slash command responses) as system messages to the client
@@ -811,6 +951,35 @@ export class SdkSession extends BaseSession {
811
951
  // #4628: defense-in-depth — track so _emitResult sweep
812
952
  // catches any orphan if the API ever drops a tool_result.
813
953
  this._trackToolStart(toolStartData.toolUseId, event.content_block.name)
954
+ } else if (blockType === 'thinking' || blockType === 'redacted_thinking') {
955
+ // #6756 — extended-thinking block opened. Open a thinking
956
+ // stream on a distinct id so reasoning content streams into a
957
+ // `type: 'thinking'` bubble (not the response slot).
958
+ // Copilot review on #6817: if a reordered thinking_delta for
959
+ // this block index already lazily opened the stream, REUSE its
960
+ // id and don't re-emit stream_start — one block must never
961
+ // produce two streams.
962
+ let thinkingId = thinkingBlocks.get(event.index)
963
+ if (!thinkingId) {
964
+ thinkingId = `${messageId}-thinking-${thinkingBlockCount++}`
965
+ thinkingBlocks.set(event.index, thinkingId)
966
+ // #6391 footer-stat: mark the block's start for the
967
+ // content_block_stop elapsed-time computation. #6943:
968
+ // performance.now() (monotonic), not Date.now().
969
+ thinkingStartMs.set(thinkingId, performance.now())
970
+ this.emit('stream_start', { messageId: thinkingId, thinking: true })
971
+ }
972
+ didStreamThinking = true
973
+ if (blockType === 'redacted_thinking') {
974
+ // Redacted thinking carries encrypted `data`, never readable
975
+ // text — forward a marker so the block is never silently
976
+ // dropped (its content_block_stop still closes the stream).
977
+ this.emit('stream_delta', {
978
+ messageId: thinkingId,
979
+ delta: '[redacted thinking]',
980
+ thinking: true,
981
+ })
982
+ }
814
983
  }
815
984
  break
816
985
  }
@@ -830,6 +999,50 @@ export class SdkSession extends BaseSession {
830
999
  // because both ends are this same process; it's a true
831
1000
  // elapsed duration, unlike the cross-machine serverTs field.
832
1001
  this.emit('stream_delta', { messageId, delta: delta.text, _emitMonoMs: Number(process.hrtime.bigint() / 1_000_000n) })
1002
+ } else if (delta.type === 'thinking_delta' && typeof delta.thinking === 'string') {
1003
+ // #6756 — reasoning delta. Route to the thinking id opened on
1004
+ // this block's content_block_start; lazy-open if the start was
1005
+ // reordered/dropped so a delta is never lost. `signature_delta`
1006
+ // (the block's signature, not content) falls through untouched.
1007
+ let thinkingId = thinkingBlocks.get(event.index)
1008
+ if (!thinkingId) {
1009
+ thinkingId = `${messageId}-thinking-${thinkingBlockCount++}`
1010
+ thinkingBlocks.set(event.index, thinkingId)
1011
+ // #6391 footer-stat: mark the block's start (lazy-open path)
1012
+ // for the content_block_stop elapsed-time computation.
1013
+ // #6943: performance.now() (monotonic), not Date.now().
1014
+ thinkingStartMs.set(thinkingId, performance.now())
1015
+ this.emit('stream_start', { messageId: thinkingId, thinking: true })
1016
+ }
1017
+ didStreamThinking = true
1018
+ this.emit('stream_delta', { messageId: thinkingId, delta: delta.thinking, thinking: true })
1019
+ }
1020
+ break
1021
+ }
1022
+
1023
+ case 'content_block_stop': {
1024
+ // #6756 — close the thinking stream for this block so the client
1025
+ // finalises its "Thinking… → Thought" label. Only thinking
1026
+ // blocks are tracked here; text/tool_use blocks are a no-op.
1027
+ const thinkingId = thinkingBlocks.get(event.index)
1028
+ if (thinkingId) {
1029
+ thinkingBlocks.delete(event.index)
1030
+ // #6391 footer-stat: elapsed monotonic time from the block's
1031
+ // open to now → the client's `thought for Xs` footer. Omit
1032
+ // when the start wasn't tracked (defensive) so we never send
1033
+ // a bogus 0. No token count: Anthropic's usage folds thinking
1034
+ // tokens into output_tokens with no per-block breakdown (see
1035
+ // follow-up). #6943: startMs is a performance.now() sample
1036
+ // (monotonic, immune to wall-clock jumps), so elapsed can
1037
+ // never legitimately be negative — Math.max(0, …) is a
1038
+ // defensive floor only, not a correctness requirement.
1039
+ const startMs = thinkingStartMs.get(thinkingId)
1040
+ thinkingStartMs.delete(thinkingId)
1041
+ const streamEndMsg = { messageId: thinkingId, thinking: true }
1042
+ if (typeof startMs === 'number') {
1043
+ streamEndMsg.thinkingDurationMs = Math.max(0, Math.round(performance.now() - startMs))
1044
+ }
1045
+ this.emit('stream_end', streamEndMsg)
833
1046
  }
834
1047
  break
835
1048
  }
@@ -838,6 +1051,11 @@ export class SdkSession extends BaseSession {
838
1051
  }
839
1052
 
840
1053
  case 'assistant': {
1054
+ // #6766: remember this message's transcript UUID as the fork
1055
+ // boundary. A checkpoint auto-created at the start of the NEXT turn
1056
+ // captures this as its boundary, so restoring that checkpoint can
1057
+ // fork the conversation truncated to exactly this point.
1058
+ this._captureBoundaryMessage(msg)
841
1059
  // Full assistant message — process content blocks for tool detection
842
1060
  const content = msg.message?.content
843
1061
  if (!Array.isArray(content)) break
@@ -852,6 +1070,20 @@ export class SdkSession extends BaseSession {
852
1070
  })
853
1071
  }
854
1072
 
1073
+ // #6756 — fallback for thinking delivered only on the full
1074
+ // assistant message (partial-message streaming off, or a block the
1075
+ // stream_event path never surfaced). Only fires when NOTHING was
1076
+ // streamed this turn, so the streaming path is never double-emitted.
1077
+ if ((block.type === 'thinking' || block.type === 'redacted_thinking') && !didStreamThinking) {
1078
+ const thinkingId = `${messageId}-thinking-${thinkingBlockCount++}`
1079
+ const text = block.type === 'redacted_thinking'
1080
+ ? '[redacted thinking]'
1081
+ : (typeof block.thinking === 'string' ? block.thinking : '')
1082
+ this.emit('stream_start', { messageId: thinkingId, thinking: true })
1083
+ if (text) this.emit('stream_delta', { messageId: thinkingId, delta: text, thinking: true })
1084
+ this.emit('stream_end', { messageId: thinkingId, thinking: true })
1085
+ }
1086
+
855
1087
  if (block.type === 'tool_use') {
856
1088
  this._handleToolUseBlock(messageId, block)
857
1089
  }
@@ -921,6 +1153,17 @@ export class SdkSession extends BaseSession {
921
1153
  this.emit('models_updated', { models: getModels() })
922
1154
  }
923
1155
 
1156
+ // #6769: end-of-turn occupancy snapshot via the SDK's
1157
+ // getContextUsage() control API — the same number Claude Code's
1158
+ // own /context shows. Queried while `this._query` is still live
1159
+ // (we're inside the for-await; the CLI process is alive until
1160
+ // the generator completes). `msg.usage` below is the per-turn
1161
+ // BILLING aggregate (summed across agent-loop rounds) and must
1162
+ // never be read as occupancy — see context-window.ts (#6769).
1163
+ // Null on timeout/old-CLI/error → field omitted → clients keep
1164
+ // their previous snapshot (or the honest dash state).
1165
+ const contextUsageSnapshot = await this._getContextUsageSnapshot()
1166
+
924
1167
  // #4628: sweep any orphan tool_starts before emitting result
925
1168
  // so the dashboard's activeTools clears as part of the same
926
1169
  // turn-end burst. _clearMessageState (called next) would also
@@ -931,6 +1174,16 @@ export class SdkSession extends BaseSession {
931
1174
  cost: msg.total_cost_usd,
932
1175
  duration: msg.duration_ms,
933
1176
  usage: msg.usage,
1177
+ // #6692: surface the per-model split + turn metadata the SDK
1178
+ // already reports instead of discarding them. Additive — every
1179
+ // existing result consumer ignores unknown fields.
1180
+ numTurns: Number.isFinite(msg.num_turns) ? msg.num_turns : null,
1181
+ apiDurationMs: Number.isFinite(msg.duration_api_ms) ? msg.duration_api_ms : null,
1182
+ modelUsage: normalizeSdkModelUsage(msg.modelUsage),
1183
+ // #6769: occupancy snapshot (or absent when unavailable).
1184
+ // Wire field is contextOccupancy — NOT contextUsage — so it can
1185
+ // never be confused with the billing `usage` aggregate above.
1186
+ ...(contextUsageSnapshot ? { contextOccupancy: contextUsageSnapshot } : {}),
934
1187
  }, 'turn_ended_with_orphan_tool_start')
935
1188
 
936
1189
  this._clearMessageState()
@@ -1012,6 +1265,63 @@ export class SdkSession extends BaseSession {
1012
1265
  return query(queryArgs)
1013
1266
  }
1014
1267
 
1268
+ /**
1269
+ * #6769: fetch the end-of-turn context-window OCCUPANCY snapshot from the
1270
+ * SDK's `getContextUsage()` control API (verified on
1271
+ * @anthropic-ai/claude-agent-sdk 0.2.114: sdk.d.ts declares
1272
+ * `Query.getContextUsage(): Promise<SDKControlGetContextUsageResponse>` with
1273
+ * `totalTokens` / `maxTokens` / `percentage` / `autoCompactThreshold` (in
1274
+ * TOKENS — the CLI compares it directly against token counts) /
1275
+ * `isAutoCompactEnabled`).
1276
+ *
1277
+ * This is the ONLY honest occupancy source for this provider: the result
1278
+ * message's own `usage` is the per-turn billing aggregate summed across
1279
+ * agent-loop rounds (+ subagents) and over-reads window fill ≈N× on an
1280
+ * N-round turn.
1281
+ *
1282
+ * Fail-soft by design — returns null (result emits without the field) when:
1283
+ * - the query is gone or the installed SDK predates the API (typeof guard)
1284
+ * - the control request errors (CLI already shutting down post-result)
1285
+ * - the response doesn't arrive within the timeout (bounds the latency
1286
+ * this adds to the turn-end result broadcast)
1287
+ * - the response lacks a finite totalTokens
1288
+ * Clients treat a missing field as "keep the previous snapshot / dash".
1289
+ *
1290
+ * @returns {Promise<{totalTokens: number, maxTokens: number|null, autoCompactThreshold: number|null, isAutoCompactEnabled: boolean|null, source: 'context-usage-api'}|null>}
1291
+ */
1292
+ async _getContextUsageSnapshot() {
1293
+ const q = this._query
1294
+ if (!q || typeof q.getContextUsage !== 'function') return null
1295
+ let timer = null
1296
+ try {
1297
+ const timeout = new Promise((resolve) => {
1298
+ timer = setTimeout(() => resolve(null), SdkSession.CONTEXT_USAGE_SNAPSHOT_TIMEOUT_MS)
1299
+ // Don't hold the process open for a race that already resolved (#6027).
1300
+ if (typeof timer.unref === 'function') timer.unref()
1301
+ })
1302
+ const res = await Promise.race([q.getContextUsage(), timeout])
1303
+ if (!res || typeof res.totalTokens !== 'number' || !Number.isFinite(res.totalTokens) || res.totalTokens < 0) {
1304
+ if (!res) {
1305
+ ;(this._log || log).debug('getContextUsage() timed out or returned nothing — result emits without occupancy')
1306
+ }
1307
+ return null
1308
+ }
1309
+ const pos = (v) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : null)
1310
+ return {
1311
+ totalTokens: res.totalTokens,
1312
+ maxTokens: pos(res.maxTokens),
1313
+ autoCompactThreshold: pos(res.autoCompactThreshold),
1314
+ isAutoCompactEnabled: typeof res.isAutoCompactEnabled === 'boolean' ? res.isAutoCompactEnabled : null,
1315
+ source: 'context-usage-api',
1316
+ }
1317
+ } catch (err) {
1318
+ ;(this._log || log).debug(`getContextUsage() failed (${err?.message || err}) — result emits without occupancy`)
1319
+ return null
1320
+ } finally {
1321
+ if (timer) clearTimeout(timer)
1322
+ }
1323
+ }
1324
+
1015
1325
  /**
1016
1326
  * Hook for subclasses to modify query options before they're passed to query().
1017
1327
  * Default implementation is a no-op. Override in subclasses that need to inject
@@ -1292,8 +1602,8 @@ export class SdkSession extends BaseSession {
1292
1602
  * Resolve a pending permission request (called by WsServer when
1293
1603
  * the app sends permission_response).
1294
1604
  */
1295
- respondToPermission(requestId, decision, editedInput) {
1296
- return this._permissions.respondToPermission(requestId, decision, editedInput)
1605
+ respondToPermission(requestId, decision, editedInput, reason) {
1606
+ return this._permissions.respondToPermission(requestId, decision, editedInput, reason)
1297
1607
  }
1298
1608
 
1299
1609
  /**
@@ -1358,6 +1668,29 @@ export class SdkSession extends BaseSession {
1358
1668
  }
1359
1669
  }
1360
1670
 
1671
+ /**
1672
+ * #6771 — durable (project-scoped) permission rules currently applied to this
1673
+ * session, tagged `persist:'project'`. Delegates to PermissionManager.
1674
+ * @returns {Array<{tool: string, decision: string, persist: 'project'}>}
1675
+ */
1676
+ getPersistentPermissionRules() {
1677
+ if (typeof this._permissions.getPersistentRules === 'function') {
1678
+ return this._permissions.getPersistentRules()
1679
+ }
1680
+ return []
1681
+ }
1682
+
1683
+ /**
1684
+ * #6771 — re-seed this session's in-memory durable rule set (does NOT persist;
1685
+ * the caller owns the store write). Delegates to PermissionManager.
1686
+ * @param {Array<{tool: string, decision: string}>} rules
1687
+ */
1688
+ setPersistentPermissionRules(rules) {
1689
+ if (typeof this._permissions.setPersistentRules === 'function') {
1690
+ this._permissions.setPersistentRules(rules)
1691
+ }
1692
+ }
1693
+
1361
1694
  /**
1362
1695
  * Set thinking level by adjusting max thinking tokens.
1363
1696
  * @param {string} level - 'default' | 'high' | 'max'
@@ -33,6 +33,8 @@ export class ServerOrchestrator {
33
33
  pairingManager,
34
34
  pushManager = null,
35
35
  billingCanaryMonitor = null,
36
+ orchestrationManager = null,
37
+ schedulerEngine = null,
36
38
  modelsOverlayWatcher = null,
37
39
  getWorktreeReapTimer,
38
40
  emergencyCleanupSync,
@@ -52,6 +54,11 @@ export class ServerOrchestrator {
52
54
  this._pairingManager = pairingManager
53
55
  this._pushManager = pushManager
54
56
  this._billingCanaryMonitor = billingCanaryMonitor
57
+ // #6691 (E-4): the orchestration engine (null when the feature is off).
58
+ // Disposed on shutdown: unhooks its SessionManager listeners (permission
59
+ // gate + turn driver) and flushes the run ledger's pending snapshot writes.
60
+ this._orchestrationManager = orchestrationManager
61
+ this._schedulerEngine = schedulerEngine
55
62
  // #5932: the models.json overlay fs-watcher handle (or null when watching
56
63
  // couldn't be established). Closed on shutdown so the watch doesn't outlive
57
64
  // the daemon.
@@ -109,6 +116,22 @@ export class ServerOrchestrator {
109
116
  if (this._billingCanaryMonitor) {
110
117
  try { this._billingCanaryMonitor.stop() } catch {}
111
118
  }
119
+ // #6691 (E-4): tear down the orchestration engine BEFORE destroying the
120
+ // sessions it may own — dispose unhooks its listeners and flushes the run
121
+ // ledger, so the subsequent destroyAll can't race a debounced snapshot write.
122
+ if (this._orchestrationManager) {
123
+ try { this._orchestrationManager.dispose() } catch (err) {
124
+ log.warn(`Orchestration engine dispose failed: ${err?.message || err}`)
125
+ }
126
+ }
127
+ // #6865: stop the scheduler BEFORE destroying sessions — destroy() clears its
128
+ // armed timer and detaches its permission answerer, so no scheduled task can
129
+ // fire (or start a session) while the daemon is tearing down.
130
+ if (this._schedulerEngine) {
131
+ try { this._schedulerEngine.destroy() } catch (err) {
132
+ log.warn(`Scheduler engine destroy failed: ${err?.message || err}`)
133
+ }
134
+ }
112
135
  // Persist sessions before destroying (enables restore on restart)
113
136
  try { this._sessionManager.serializeState() } catch (err) {
114
137
  log.error(`Failed to serialize session state: ${err?.message || err}`)
@@ -28,7 +28,7 @@ export class TunnelLifecycleHandler {
28
28
  * @param {{
29
29
  * createTunnel: Function, emergencyCleanup: Function, wireTunnelEvents: Function,
30
30
  * waitForTunnel: Function, buildTunnelWarmingStatus: Function, buildTunnelReadyStatus: Function,
31
- * config: { port: number, tunnelArg: { mode: string }, tunnelConfig?: object, tunnelName?: string|null, tunnelHostname?: string|null },
31
+ * config: { port: number, tunnelArg: { mode: string }, tunnelConfig?: object, tunnelName?: string|null, tunnelHostname?: string|null, binaryProvenance?: object|null },
32
32
  * wsServer: object, startupDisplay: object, pairingManager: (object|null),
33
33
  * cleanupRefs: { mdnsService?: object, bonjourInstance?: object, tokenManager?: object, sessionManager: object },
34
34
  * logger: object,
@@ -73,7 +73,7 @@ export class TunnelLifecycleHandler {
73
73
  * @returns {Promise<{ ok: boolean, tunnel?: object }>}
74
74
  */
75
75
  async createAndStart() {
76
- const { port, tunnelArg, tunnelConfig, tunnelName, tunnelHostname } = this._config
76
+ const { port, tunnelArg, tunnelConfig, tunnelName, tunnelHostname, binaryProvenance } = this._config
77
77
  const wsServer = this._wsServer
78
78
  const startupDisplay = this._startupDisplay
79
79
  const pairingManager = this._pairingManager
@@ -95,6 +95,7 @@ export class TunnelLifecycleHandler {
95
95
  tunnelConfig,
96
96
  tunnelName: tunnelName || null,
97
97
  tunnelHostname: tunnelHostname || null,
98
+ binaryProvenance: binaryProvenance || null,
98
99
  })
99
100
  let wsUrl, httpUrl
100
101
  try {