@cortex-agent/server 2026.10.15-2 → 2026.10.21

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 (171) hide show
  1. package/README.md +70 -31
  2. package/defaults/board/board.css +140 -62
  3. package/defaults/board/scaffold.html +36 -13
  4. package/defaults/plugins/cortex-board/skills/board/SKILL.md +30 -22
  5. package/defaults/plugins/cortex-system/plugin.json +2 -2
  6. package/defaults/plugins/cortex-system/skills/browser/SKILL.md +56 -0
  7. package/dist/agent-adapter/claude/adapter.d.ts +2 -5
  8. package/dist/agent-adapter/claude/adapter.js +6 -5
  9. package/dist/agent-adapter/claude/assistant-blocks.d.ts +5 -0
  10. package/dist/agent-adapter/claude/assistant-blocks.js +61 -0
  11. package/dist/agent-adapter/claude/cache-refresh.d.ts +58 -0
  12. package/dist/agent-adapter/claude/cache-refresh.js +145 -0
  13. package/dist/agent-adapter/claude/cache-touch.d.ts +12 -0
  14. package/dist/agent-adapter/claude/cache-touch.js +75 -0
  15. package/dist/agent-adapter/claude/event-parser.d.ts +8 -3
  16. package/dist/agent-adapter/claude/event-parser.js +33 -17
  17. package/dist/agent-adapter/claude/event-translator.d.ts +2 -0
  18. package/dist/agent-adapter/claude/event-translator.js +2 -0
  19. package/dist/agent-adapter/claude/session-options.d.ts +0 -4
  20. package/dist/agent-adapter/claude/session-options.js +0 -9
  21. package/dist/agent-adapter/claude/spawn-args.d.ts +0 -3
  22. package/dist/agent-adapter/claude/spawn-args.js +2 -5
  23. package/dist/agent-adapter/claude/transcript-clear.d.ts +42 -0
  24. package/dist/agent-adapter/claude/transcript-clear.js +217 -0
  25. package/dist/agent-adapter/claude/turn-machine.d.ts +3 -2
  26. package/dist/agent-adapter/claude/turn-machine.js +21 -68
  27. package/dist/agent-adapter/claude/window-warmup.d.ts +13 -0
  28. package/dist/agent-adapter/claude/window-warmup.js +38 -0
  29. package/dist/agent-adapter/continuation-phase.js +3 -0
  30. package/dist/agent-adapter/normalize/event-types.d.ts +8 -0
  31. package/dist/agent-adapter/pi/event-parser.d.ts +1 -1
  32. package/dist/agent-adapter/pi/event-parser.js +43 -27
  33. package/dist/agent-adapter/pi/mcp-bridge.d.ts +1 -1
  34. package/dist/agent-adapter/pi/pi-session.d.ts +2 -0
  35. package/dist/agent-adapter/pi/pi-session.js +15 -0
  36. package/dist/agent-adapter/pi/session-options.d.ts +2 -6
  37. package/dist/agent-adapter/pi/session-options.js +2 -11
  38. package/dist/agent-adapter/run-events.d.ts +10 -0
  39. package/dist/agent-adapter/run-events.js +2 -0
  40. package/dist/agent-adapter/types.d.ts +1 -1
  41. package/dist/client-bundle/manifest.json +1 -1
  42. package/dist/core/locales/en.d.ts +1 -0
  43. package/dist/core/locales/slices/commands.d.ts +1 -0
  44. package/dist/core/locales/slices/commands.js +2 -0
  45. package/dist/core/settings-spec.d.ts +25 -0
  46. package/dist/core/settings-spec.js +34 -0
  47. package/dist/domain/agents/engine-selection.js +1 -1
  48. package/dist/domain/agents/subagent/registry.d.ts +2 -0
  49. package/dist/domain/agents/subagent/registry.js +8 -0
  50. package/dist/domain/agents/subagent/runner.js +0 -1
  51. package/dist/domain/browser/broker.d.ts +99 -0
  52. package/dist/domain/browser/broker.js +487 -0
  53. package/dist/domain/costs/claude-account.js +21 -0
  54. package/dist/domain/costs/rate-limit-throttle.js +3 -1
  55. package/dist/domain/costs/reset-account.d.ts +2 -0
  56. package/dist/domain/costs/usage-service.d.ts +1 -1
  57. package/dist/domain/costs/usage-service.js +20 -7
  58. package/dist/domain/mcp/tools/ui-file.js +1 -1
  59. package/dist/domain/remote/device-browser.js +1 -1
  60. package/dist/domain/remote/device-chrome-commands.js +2 -0
  61. package/dist/domain/remote/device-port.js +2 -2
  62. package/dist/domain/runs/builders.d.ts +2 -2
  63. package/dist/domain/runs/builders.js +2 -3
  64. package/dist/domain/runs/engine-spec.d.ts +5 -0
  65. package/dist/domain/runs/engine-spec.js +1 -2
  66. package/dist/domain/runs/request.d.ts +0 -1
  67. package/dist/domain/sessions/session-lifecycle.d.ts +0 -4
  68. package/dist/domain/sessions/session-lifecycle.js +1 -1
  69. package/dist/domain/system/own-bin-path.d.ts +13 -0
  70. package/dist/domain/system/own-bin-path.js +36 -0
  71. package/dist/domain/system/terminal-cli/index.d.ts +58 -0
  72. package/dist/domain/system/terminal-cli/index.js +100 -0
  73. package/dist/domain/system/terminal-cli/posix-profiles.d.ts +23 -0
  74. package/dist/domain/system/terminal-cli/posix-profiles.js +74 -0
  75. package/dist/domain/system/terminal-cli/registrar.d.ts +12 -0
  76. package/dist/domain/system/terminal-cli/registrar.js +1 -0
  77. package/dist/domain/system/terminal-cli/shims.d.ts +27 -0
  78. package/dist/domain/system/terminal-cli/shims.js +108 -0
  79. package/dist/domain/system/terminal-cli/state.d.ts +7 -0
  80. package/dist/domain/system/terminal-cli/state.js +36 -0
  81. package/dist/domain/system/terminal-cli/windows-user-path.d.ts +13 -0
  82. package/dist/domain/system/terminal-cli/windows-user-path.js +67 -0
  83. package/dist/domain/tui-session/tui-session-service.js +1 -1
  84. package/dist/domain/tui-session/types.d.ts +1 -1
  85. package/dist/domain/ui-service/app-router.d.ts +17 -6
  86. package/dist/domain/ui-service/app-router.js +3 -1
  87. package/dist/domain/ui-service/assistant-snapshots.js +2 -0
  88. package/dist/domain/ui-service/inline-media-types.d.ts +18 -0
  89. package/dist/domain/ui-service/inline-media-types.js +1 -0
  90. package/dist/domain/ui-service/input-schemas.d.ts +17 -17
  91. package/dist/domain/ui-service/input-schemas.js +9 -9
  92. package/dist/domain/ui-service/mutate/models.d.ts +3 -0
  93. package/dist/domain/ui-service/mutate/models.js +21 -2
  94. package/dist/domain/ui-service/mutate/resolve-media.d.ts +4 -0
  95. package/dist/domain/ui-service/mutate/resolve-media.js +17 -0
  96. package/dist/domain/ui-service/mutate/sessions.js +1 -4
  97. package/dist/domain/ui-service/query/sessions.js +1 -1
  98. package/dist/domain/ui-service/types.d.ts +8 -10
  99. package/dist/domain/ui-service/ui-service.d.ts +9 -6
  100. package/dist/domain/ui-service/ui-service.js +4 -1
  101. package/dist/entry/app.js +23 -0
  102. package/dist/entry/browser-cli.d.ts +39 -0
  103. package/dist/entry/browser-cli.js +317 -0
  104. package/dist/entry/cli-help.d.ts +1 -0
  105. package/dist/entry/cli-help.js +30 -0
  106. package/dist/entry/cli.js +2 -0
  107. package/dist/entry/daemon.js +2 -0
  108. package/dist/entry/path-cli.d.ts +4 -0
  109. package/dist/entry/path-cli.js +65 -0
  110. package/dist/entry/shutdown.js +7 -0
  111. package/dist/entry/start-ui-http.js +8 -0
  112. package/dist/entry/ui-service-wiring.js +2 -0
  113. package/dist/events/event-types.d.ts +2 -1
  114. package/dist/orchestration/agent-runner.d.ts +2 -2
  115. package/dist/orchestration/agent-runner.js +6 -6
  116. package/dist/orchestration/browser-webhook.d.ts +11 -0
  117. package/dist/orchestration/browser-webhook.js +28 -0
  118. package/dist/orchestration/cache-keep-warm.d.ts +77 -0
  119. package/dist/orchestration/cache-keep-warm.js +213 -0
  120. package/dist/orchestration/claude-window-warmup.d.ts +40 -0
  121. package/dist/orchestration/claude-window-warmup.js +126 -0
  122. package/dist/orchestration/conversation-request.d.ts +4 -7
  123. package/dist/orchestration/conversation-request.js +1 -2
  124. package/dist/orchestration/delta-coalescer.d.ts +4 -2
  125. package/dist/orchestration/delta-coalescer.js +5 -5
  126. package/dist/orchestration/edit-retry.js +3 -6
  127. package/dist/orchestration/inline-media-eager.d.ts +13 -0
  128. package/dist/orchestration/inline-media-eager.js +58 -0
  129. package/dist/orchestration/inline-media.d.ts +22 -0
  130. package/dist/orchestration/inline-media.js +151 -0
  131. package/dist/orchestration/interactions/ask-user-resume.js +3 -7
  132. package/dist/orchestration/routing/commands/usage-format.js +3 -0
  133. package/dist/orchestration/routing/webhook.js +4 -0
  134. package/dist/orchestration/session-compact.js +5 -7
  135. package/dist/orchestration/session-events.d.ts +2 -1
  136. package/dist/orchestration/session-events.js +1 -0
  137. package/dist/orchestration/transcript-sink.d.ts +6 -0
  138. package/dist/orchestration/transcript-sink.js +21 -2
  139. package/dist/orchestration/turn/turn-prep.d.ts +0 -8
  140. package/dist/orchestration/turn/turn-prep.js +0 -51
  141. package/dist/orchestration/turn/turn.js +4 -0
  142. package/dist/platform/adapters/tui/ports.d.ts +1 -1
  143. package/dist/platform/adapters/tui/tui-transcript.js +2 -0
  144. package/dist/platform/browser/agent-browser.d.ts +50 -0
  145. package/dist/platform/browser/agent-browser.js +165 -0
  146. package/dist/platform/browser/managed-browser.d.ts +1 -11
  147. package/dist/platform/browser/managed-browser.js +4 -12
  148. package/dist/platform/ui-http/browser-stream.d.ts +110 -0
  149. package/dist/platform/ui-http/browser-stream.js +447 -0
  150. package/dist/platform/ui-http/ui-http-server.d.ts +12 -0
  151. package/dist/platform/ui-http/ui-http-server.js +23 -6
  152. package/dist/store/conversation-history-reader.js +8 -0
  153. package/dist/store/conversation-history-repo.d.ts +8 -1
  154. package/dist/store/conversation-history-repo.js +5 -0
  155. package/dist/store/session-registry-journal.d.ts +0 -8
  156. package/dist/store/session-registry-journal.js +5 -17
  157. package/dist/store/session-registry-repo.d.ts +2 -3
  158. package/dist/store/session-registry-repo.js +0 -2
  159. package/package.json +4 -2
  160. package/web/dist/assets/board-math-css-CB4GJ6qO.js +2 -0
  161. package/web/dist/assets/index-CaSZPg_H.css +1 -0
  162. package/web/dist/assets/index-CzOR7Edh.js +522 -0
  163. package/web/dist/assets/{index-DaViXAg-.js → index-cIGFv27z.js} +1 -1
  164. package/web/dist/index.html +3 -2
  165. package/web/dist/theme.css +6 -0
  166. package/dist/agent-adapter/browser-mcp-server.d.ts +0 -13
  167. package/dist/agent-adapter/browser-mcp-server.js +0 -28
  168. package/dist/agent-adapter/claude/browser-mcp.d.ts +0 -9
  169. package/dist/agent-adapter/claude/browser-mcp.js +0 -10
  170. package/web/dist/assets/index-Cgx3gdHV.css +0 -1
  171. package/web/dist/assets/index-CpZWBVHr.js +0 -494
@@ -15,23 +15,43 @@ export function parseModelFallbackEvent(raw) {
15
15
  return { type: 'model_fallback', originalModel, fallbackModel };
16
16
  }
17
17
  export function createStreamDeltaState() {
18
- return { messageId: null, model: null, textBlockId: null };
18
+ return { messageId: null, model: null, textBlockId: null, thinkingBlockId: null };
19
19
  }
20
20
  function observeMessageStart(event, state) {
21
21
  state.messageId = typeof event.message?.id === 'string' ? event.message.id : null;
22
22
  state.model = typeof event.message?.model === 'string' ? event.message.model : null;
23
23
  state.textBlockId = null;
24
+ state.thinkingBlockId = null;
24
25
  }
25
26
  function observeBlockStart(event, state) {
26
- if (event.content_block?.type !== 'text' || !state.messageId)
27
- return;
28
- if (typeof event.index !== 'number')
27
+ if (!state.messageId || typeof event.index !== 'number')
29
28
  return;
30
- state.textBlockId = `${state.messageId}:${event.index}`;
29
+ const blockId = `${state.messageId}:${event.index}`;
30
+ if (event.content_block?.type === 'text')
31
+ state.textBlockId = blockId;
32
+ if (event.content_block?.type === 'thinking')
33
+ state.thinkingBlockId = blockId;
31
34
  }
32
- /** Translate a partial stdout event into one text delta while advancing the message cursor. */
35
+ function parseBlockDelta(event, state) {
36
+ const kind = event.delta?.type;
37
+ if (kind !== 'text_delta' && kind !== 'thinking_delta')
38
+ return null;
39
+ const text = kind === 'thinking_delta' ? event.delta.thinking : event.delta.text;
40
+ if (typeof text !== 'string' || text.length === 0)
41
+ return null;
42
+ if (!state.messageId || typeof event.index !== 'number')
43
+ return null;
44
+ const blockId = `${state.messageId}:${event.index}`;
45
+ if (kind === 'thinking_delta') {
46
+ state.thinkingBlockId = blockId;
47
+ return { kind: 'thinking', text, blockId };
48
+ }
49
+ state.textBlockId = blockId;
50
+ return { text, blockId };
51
+ }
52
+ /** Translate a partial stdout event while advancing only its own block cursor. */
33
53
  export function parseStreamEvent(data, state) {
34
- if (!data || data.type !== 'stream_event')
54
+ if (!data || data.type !== 'stream_event' || data.parent_tool_use_id)
35
55
  return null;
36
56
  const event = data.event;
37
57
  if (!event || typeof event.type !== 'string')
@@ -44,16 +64,7 @@ export function parseStreamEvent(data, state) {
44
64
  observeBlockStart(event, state);
45
65
  return null;
46
66
  }
47
- if (event.type !== 'content_block_delta' || event.delta?.type !== 'text_delta')
48
- return null;
49
- const text = event.delta.text;
50
- if (typeof text !== 'string' || text.length === 0)
51
- return null;
52
- if (!state.messageId || typeof event.index !== 'number')
53
- return null;
54
- const blockId = `${state.messageId}:${event.index}`;
55
- state.textBlockId = blockId;
56
- return { text, blockId };
67
+ return event.type === 'content_block_delta' ? parseBlockDelta(event, state) : null;
57
68
  }
58
69
  /**
59
70
  * Consume the blockId of the streamed text block that the complete `assistant` event now being
@@ -68,6 +79,11 @@ export function takeTextBlockId(state) {
68
79
  state.textBlockId = null;
69
80
  return id;
70
81
  }
82
+ export function takeThinkingBlockId(state) {
83
+ const id = state.thinkingBlockId;
84
+ state.thinkingBlockId = null;
85
+ return id;
86
+ }
71
87
  export function formatAssistantEvent(data) {
72
88
  const parts = [];
73
89
  for (const block of (data.message?.content || [])) {
@@ -22,6 +22,8 @@ export interface ClaudeTurnCallbacks {
22
22
  onProgress?: ((progress: any) => void) | null;
23
23
  onAssistantMessage?: ((text: string, blockId?: string, model?: string | null, subagent?: ToolUseSubagent) => void) | null;
24
24
  onAssistantDelta?: ((text: string, blockId: string) => void) | null;
25
+ onAssistantThinking?: ((text: string, blockId?: string) => void) | null;
26
+ onAssistantThinkingDelta?: ((text: string, blockId: string) => void) | null;
25
27
  onToolUse?: ((name: string, input: any, toolUseId: string, subagent?: ToolUseSubagent) => void) | null;
26
28
  onToolResult?: ((toolUseId: string, content: string, isError: boolean, subagent?: ToolUseSubagent, images?: ToolResultImage[]) => void) | null;
27
29
  onCompact?: ((info: {
@@ -28,6 +28,8 @@ export function claudeTurnCallbacks(push) {
28
28
  // Token-level preview of the block above. Same FIFO stream, so every delta is delivered
29
29
  // before the complete message that supersedes it.
30
30
  onAssistantDelta: (text, blockId) => push({ type: 'assistant_delta', text, blockId }),
31
+ onAssistantThinking: (text, blockId) => push({ type: 'assistant_thinking', text, ...(blockId ? { blockId } : {}) }),
32
+ onAssistantThinkingDelta: (text, blockId) => push({ type: 'assistant_thinking_delta', text, blockId }),
31
33
  onToolUse: (name, input, toolUseId, subagent) => {
32
34
  push({ type: 'tool_use', toolUseId, name, input, ...(subagent ? { subagent } : {}) });
33
35
  // Derived semantic event alongside the raw call (cf. plan_written /
@@ -25,10 +25,6 @@ export interface ClaudeSessionOptions {
25
25
  mcpToolAllowlist?: string[];
26
26
  supplementalMcpConfigPath?: string | null;
27
27
  supplementalMcpConfigIdentity?: string | null;
28
- /** Playwright MCP config for a browser-enabled session. Kept separate from the supplemental
29
- * (plugin) config because a session can legitimately have both. */
30
- browserMcpConfigPath?: string | null;
31
- browserMcpConfigIdentity?: string | null;
32
28
  pluginCapabilityFingerprint?: string | null;
33
29
  disableHooks?: boolean;
34
30
  /** Drop the CLI's whole skill layer; see {@link ClaudeSpawnOptions.disableSkills}. */
@@ -5,7 +5,6 @@ import { encodeMcpBundles, MCP_BUNDLES_ENV } from '../../core/mcp-bundles.js';
5
5
  import { resolveMcpComposition } from '../types.js';
6
6
  import { buildClaudeEnv, buildSpawnArgs, resolveClaudeMcpBundles, } from './spawn-args.js';
7
7
  import { writeClaudeSupplementalMcpConfig } from './mcp-config.js';
8
- import { writeBrowserMcpConfig } from './browser-mcp.js';
9
8
  /** The prompt and model half of the CLI options. An empty string reads as unset. */
10
9
  function promptSpawnOptions(options) {
11
10
  return {
@@ -26,7 +25,6 @@ function surfaceSpawnOptions(options) {
26
25
  mcpConfigPaths: options.mcpConfigPaths,
27
26
  mcpToolAllowlist: options.mcpToolAllowlist,
28
27
  supplementalMcpConfigPath: options.supplementalMcpConfigPath ?? null,
29
- browserMcpConfigPath: options.browserMcpConfigPath ?? null,
30
28
  disableHooks: options.disableHooks === true,
31
29
  disableSkills: options.disableSkills === true,
32
30
  settingSources: options.settingSources,
@@ -107,11 +105,6 @@ function sessionPresentationOptions(spec) {
107
105
  }
108
106
  function sessionRuntimeOptions(spec, composition) {
109
107
  const supplemental = supplementalMcpConfig(spec, composition);
110
- // Browser tools ride on the direct composition only: an agent configured with composition
111
- // `none` gets no Cortex MCP servers, the browser included.
112
- const browser = spec.mcp.browserCdpEndpoint && composition === 'direct'
113
- ? writeBrowserMcpConfig(spec.mcp.browserCdpEndpoint)
114
- : null;
115
108
  return {
116
109
  anthropicBaseUrl: spec.route.anthropicBaseUrl,
117
110
  routeEnv: spec.env.sets,
@@ -122,8 +115,6 @@ function sessionRuntimeOptions(spec, composition) {
122
115
  mcpToolAllowlist: spec.mcp.allowlist,
123
116
  supplementalMcpConfigPath: supplemental?.path ?? null,
124
117
  supplementalMcpConfigIdentity: supplemental?.identity ?? null,
125
- browserMcpConfigPath: browser?.path ?? null,
126
- browserMcpConfigIdentity: browser?.identity ?? null,
127
118
  pluginCapabilityFingerprint: spec.plugins.fingerprint ?? null,
128
119
  disableHooks: spec.flags.disableHooks,
129
120
  disableSkills: spec.flags.disableSkills,
@@ -35,9 +35,6 @@ export interface ClaudeSpawnOptions {
35
35
  loadFeishuMcp?: boolean;
36
36
  /** Select Web tools in the bundled server for Web-originated direct sessions. */
37
37
  loadWebMcp?: boolean;
38
- /** Path to a Playwright MCP config for a browser-enabled session. Absent → the session gets zero
39
- * browser tools, which is the default and the reason this is opt-in at all. */
40
- browserMcpConfigPath?: string | null;
41
38
  /** Selected thinking level → `--effort <level>`
42
39
  * (low/medium/high/xhigh/max). Absent → no flag. */
43
40
  thinking?: string | null;
@@ -17,10 +17,6 @@ const MCP_CONFIGS = {
17
17
  direct: [MCP_CONFIG],
18
18
  none: [EMPTY_MCP_CONFIG],
19
19
  };
20
- function appendBrowserMcpConfig(configs, options, isDirect) {
21
- if (options.browserMcpConfigPath && isDirect)
22
- configs.push(options.browserMcpConfigPath);
23
- }
24
20
  function resolveMcpConfigs(options, composition) {
25
21
  const configs = options.mcpConfigPaths
26
22
  ? [...options.mcpConfigPaths]
@@ -28,7 +24,6 @@ function resolveMcpConfigs(options, composition) {
28
24
  if (options.supplementalMcpConfigPath && composition === 'direct') {
29
25
  configs.push(options.supplementalMcpConfigPath);
30
26
  }
31
- appendBrowserMcpConfig(configs, options, composition === 'direct');
32
27
  const bundles = resolveClaudeMcpBundles(options);
33
28
  // Only an explicitly declared allowlist materializes a gated config (subagents). A direct session
34
29
  // declares none and therefore registers its bundles whole — deliberate since DR-0037 v4: no tool
@@ -48,6 +43,8 @@ function printModeArgs(options) {
48
43
  if (options.streamDeltas ?? isStreamDeltasEnabled()) {
49
44
  args.push('--include-partial-messages');
50
45
  }
46
+ if (getSettings().showThinking)
47
+ args.push('--thinking-display', 'summarized');
51
48
  return args;
52
49
  }
53
50
  export function resolveClaudeMcpBundles(options) {
@@ -0,0 +1,42 @@
1
+ /** The stub Claude Code itself writes when it clears an old tool result. */
2
+ export declare const CLEARED_TOOL_RESULT = "[Old tool result content cleared]";
3
+ export interface ToolResultClearing {
4
+ lines: string[];
5
+ clearedCount: number;
6
+ charsRemoved: number;
7
+ }
8
+ export type ColdResumeSkip = 'disabled' | 'warm' | 'unreadable' | 'small-context' | 'too-little' | 'write-failed';
9
+ export type ColdResumeClearing = {
10
+ cleared: true;
11
+ clearedCount: number;
12
+ charsRemoved: number;
13
+ } | {
14
+ cleared: false;
15
+ reason: ColdResumeSkip;
16
+ };
17
+ /** The file operations the clearing needs; replaced in tests. */
18
+ export interface TranscriptFs {
19
+ readFileSync(path: string): Buffer;
20
+ statSync(path: string): {
21
+ mode: number;
22
+ };
23
+ writeFileSync(path: string, data: Buffer, mode: number): void;
24
+ appendFileSync(path: string, data: string): void;
25
+ renameSync(from: string, to: string): void;
26
+ unlinkSync(path: string): void;
27
+ }
28
+ /**
29
+ * Stub the content of every tool result after the last compact boundary except the most recent
30
+ * `keepRecent`. Only `message.content` of those blocks changes; every other line, and every field
31
+ * of a changed line, is kept, and an unchanged line is returned as the same string.
32
+ */
33
+ export declare function clearOldToolResults(lines: readonly string[], keepRecent?: number): ToolResultClearing;
34
+ /** The context size the last model request after the last compact boundary carried, if any. */
35
+ export declare function liveContextTokens(lines: readonly string[]): number | null;
36
+ /**
37
+ * Before `--resume` of a session whose prompt cache has certainly expired, stub all but the most
38
+ * recent tool results so the CLI re-sends a smaller context. The cache is cold either way, so no
39
+ * cached prefix is lost; the turn's pre-run snapshot keeps the uncleared transcript for rewind. Any
40
+ * failure leaves the transcript untouched.
41
+ */
42
+ export declare function clearToolResultsForColdResume(transcriptPath: string, backendSessionId: string, now?: number, io?: TranscriptFs): ColdResumeClearing;
@@ -0,0 +1,217 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { isUtf8 } from 'node:buffer';
4
+ import { createLogger } from '../../core/log.js';
5
+ import { getSettings } from '../../core/settings.js';
6
+ import { lastCacheTouch } from './cache-touch.js';
7
+ const log = createLogger('claude-bridge');
8
+ /** The stub Claude Code itself writes when it clears an old tool result. */
9
+ export const CLEARED_TOOL_RESULT = '[Old tool result content cleared]';
10
+ const KEEP_RECENT_TOOL_RESULTS = 10;
11
+ /** Past the 1h prompt-cache TTL with margin; also the idle close, so an ordinary cold wake qualifies. */
12
+ const COLD_CACHE_MS = 65 * 60_000;
13
+ const MIN_CONTEXT_TOKENS = 100_000;
14
+ const MIN_CHARS_REMOVED = 40_000;
15
+ const BOUNDARY_NEEDLE = Buffer.from('"compact_boundary"');
16
+ const nodeFs = {
17
+ readFileSync: (p) => fs.readFileSync(p),
18
+ statSync: (p) => fs.statSync(p),
19
+ writeFileSync: (p, data, mode) => fs.writeFileSync(p, data, { mode }),
20
+ appendFileSync: (p, data) => fs.appendFileSync(p, data),
21
+ renameSync: (from, to) => fs.renameSync(from, to),
22
+ unlinkSync: (p) => fs.unlinkSync(p),
23
+ };
24
+ function parseRecord(line) {
25
+ try {
26
+ const value = JSON.parse(line);
27
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : null;
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ function isCompactBoundary(line) {
34
+ if (!line.includes('"compact_boundary"'))
35
+ return false;
36
+ const record = parseRecord(line);
37
+ return record?.type === 'system' && record.subtype === 'compact_boundary';
38
+ }
39
+ /** Index of the first line the resumed model still sees: right after the last compact boundary. */
40
+ function liveSegmentStart(lines) {
41
+ for (let i = lines.length - 1; i >= 0; i--) {
42
+ if (isCompactBoundary(lines[i]))
43
+ return i + 1;
44
+ }
45
+ return 0;
46
+ }
47
+ function messageOf(record) {
48
+ const message = record?.message;
49
+ return message !== null && typeof message === 'object' ? message : null;
50
+ }
51
+ function toolResultBlocks(record) {
52
+ if (record?.type !== 'user' || record.isSidechain === true)
53
+ return [];
54
+ const content = messageOf(record)?.content;
55
+ if (!Array.isArray(content))
56
+ return [];
57
+ return content.filter((block) => block !== null && typeof block === 'object' && block.type === 'tool_result');
58
+ }
59
+ function collectToolResults(lines, start) {
60
+ const refs = [];
61
+ for (let line = start; line < lines.length; line++) {
62
+ if (!lines[line].includes('"tool_result"'))
63
+ continue;
64
+ const record = parseRecord(lines[line]);
65
+ for (const block of toolResultBlocks(record))
66
+ refs.push({ line, record: record, block });
67
+ }
68
+ return refs;
69
+ }
70
+ const PLACEHOLDER_CHARS = JSON.stringify(CLEARED_TOOL_RESULT).length;
71
+ /** Stub one block; returns the characters saved. A result no longer than the stub stays as it is. */
72
+ function clearBlock(block) {
73
+ const saved = JSON.stringify(block.content ?? '').length - PLACEHOLDER_CHARS;
74
+ if (saved <= 0)
75
+ return 0;
76
+ block.content = CLEARED_TOOL_RESULT;
77
+ return saved;
78
+ }
79
+ /**
80
+ * Stub the content of every tool result after the last compact boundary except the most recent
81
+ * `keepRecent`. Only `message.content` of those blocks changes; every other line, and every field
82
+ * of a changed line, is kept, and an unchanged line is returned as the same string.
83
+ */
84
+ export function clearOldToolResults(lines, keepRecent = KEEP_RECENT_TOOL_RESULTS) {
85
+ const refs = collectToolResults(lines, liveSegmentStart(lines));
86
+ const changed = new Map();
87
+ let clearedCount = 0;
88
+ let charsRemoved = 0;
89
+ for (const ref of refs.slice(0, Math.max(0, refs.length - keepRecent))) {
90
+ const saved = clearBlock(ref.block);
91
+ if (saved === 0)
92
+ continue;
93
+ changed.set(ref.line, ref.record);
94
+ clearedCount++;
95
+ charsRemoved += saved;
96
+ }
97
+ const out = lines.map((line, i) => (changed.has(i) ? JSON.stringify(changed.get(i)) : line));
98
+ return { lines: out, clearedCount, charsRemoved };
99
+ }
100
+ function tokenCount(value) {
101
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
102
+ }
103
+ function assistantContextTokens(record) {
104
+ if (record?.type !== 'assistant' || record.isSidechain === true)
105
+ return null;
106
+ const usage = messageOf(record)?.usage;
107
+ if (usage === null || typeof usage !== 'object')
108
+ return null;
109
+ const total = tokenCount(usage.input_tokens) + tokenCount(usage.cache_read_input_tokens)
110
+ + tokenCount(usage.cache_creation_input_tokens);
111
+ // A synthetic assistant message (an API error, an interrupted turn) reports all zeros.
112
+ return total > 0 ? total : null;
113
+ }
114
+ /** The context size the last model request after the last compact boundary carried, if any. */
115
+ export function liveContextTokens(lines) {
116
+ const start = liveSegmentStart(lines);
117
+ for (let i = lines.length - 1; i >= start; i--) {
118
+ if (!lines[i].includes('"usage"'))
119
+ continue;
120
+ const tokens = assistantContextTokens(parseRecord(lines[i]));
121
+ if (tokens !== null)
122
+ return tokens;
123
+ }
124
+ return null;
125
+ }
126
+ /**
127
+ * Byte offset of the line holding the last compact boundary, or 0. Everything before it is outside
128
+ * the resumed context, so it is copied through without being decoded.
129
+ */
130
+ function liveSegmentOffset(buf) {
131
+ let hit = buf.lastIndexOf(BOUNDARY_NEEDLE);
132
+ while (hit !== -1) {
133
+ const lineStart = buf.lastIndexOf(0x0a, hit) + 1;
134
+ const newline = buf.indexOf(0x0a, hit);
135
+ if (isCompactBoundary(buf.toString('utf8', lineStart, newline === -1 ? buf.length : newline)))
136
+ return lineStart;
137
+ if (lineStart === 0)
138
+ return 0;
139
+ hit = buf.lastIndexOf(BOUNDARY_NEEDLE, lineStart - 1);
140
+ }
141
+ return 0;
142
+ }
143
+ function coldGate(transcriptPath, backendSessionId, now) {
144
+ if (!getSettings().coldResumeClearToolResults)
145
+ return 'disabled';
146
+ const touched = lastCacheTouch(transcriptPath, backendSessionId);
147
+ return touched === null || now - touched <= COLD_CACHE_MS ? 'warm' : null;
148
+ }
149
+ function readTranscript(transcriptPath, io) {
150
+ try {
151
+ return io.readFileSync(transcriptPath);
152
+ }
153
+ catch {
154
+ return null;
155
+ }
156
+ }
157
+ function planClearing(liveText) {
158
+ const lines = liveText.split('\n');
159
+ const tokens = liveContextTokens(lines);
160
+ if (tokens === null || tokens < MIN_CONTEXT_TOKENS)
161
+ return 'small-context';
162
+ const clearing = clearOldToolResults(lines);
163
+ return clearing.charsRemoved < MIN_CHARS_REMOVED ? 'too-little' : clearing;
164
+ }
165
+ /** Same-directory temp file, then rename over the transcript. Throws with the temp file removed. */
166
+ function replaceTranscript(transcriptPath, head, liveText, io) {
167
+ const tmp = `${transcriptPath}.${process.pid}.clear.tmp`;
168
+ try {
169
+ io.writeFileSync(tmp, head, io.statSync(transcriptPath).mode & 0o777);
170
+ io.appendFileSync(tmp, liveText);
171
+ io.renameSync(tmp, transcriptPath);
172
+ }
173
+ catch (error) {
174
+ try {
175
+ io.unlinkSync(tmp);
176
+ }
177
+ catch { /* never created */ }
178
+ throw error;
179
+ }
180
+ }
181
+ function writeClearing(transcriptPath, head, clearing, io) {
182
+ try {
183
+ replaceTranscript(transcriptPath, head, clearing.lines.join('\n'), io);
184
+ }
185
+ catch (error) {
186
+ log.warn(`Cold-resume tool-result clearing failed for ${path.basename(transcriptPath)}, resuming it as is: ${error.message}`);
187
+ return { cleared: false, reason: 'write-failed' };
188
+ }
189
+ return { cleared: true, clearedCount: clearing.clearedCount, charsRemoved: clearing.charsRemoved };
190
+ }
191
+ function clearTranscript(transcriptPath, io) {
192
+ const buf = readTranscript(transcriptPath, io);
193
+ if (!buf)
194
+ return { cleared: false, reason: 'unreadable' };
195
+ const offset = liveSegmentOffset(buf);
196
+ const live = buf.subarray(offset);
197
+ if (!isUtf8(live))
198
+ return { cleared: false, reason: 'unreadable' };
199
+ const plan = planClearing(live.toString('utf8'));
200
+ if (typeof plan === 'string')
201
+ return { cleared: false, reason: plan };
202
+ return writeClearing(transcriptPath, buf.subarray(0, offset), plan, io);
203
+ }
204
+ /**
205
+ * Before `--resume` of a session whose prompt cache has certainly expired, stub all but the most
206
+ * recent tool results so the CLI re-sends a smaller context. The cache is cold either way, so no
207
+ * cached prefix is lost; the turn's pre-run snapshot keeps the uncleared transcript for rewind. Any
208
+ * failure leaves the transcript untouched.
209
+ */
210
+ export function clearToolResultsForColdResume(transcriptPath, backendSessionId, now = Date.now(), io = nodeFs) {
211
+ const gated = coldGate(transcriptPath, backendSessionId, now);
212
+ const outcome = gated ? { cleared: false, reason: gated } : clearTranscript(transcriptPath, io);
213
+ if (outcome.cleared) {
214
+ log.info(`Cleared ${outcome.clearedCount} old tool results before cold resume: ${backendSessionId.substring(0, 8)} (-${outcome.charsRemoved} chars)`);
215
+ }
216
+ return outcome;
217
+ }
@@ -30,6 +30,8 @@ export interface PendingTurn {
30
30
  /** Incremental text chunk while a block is still being generated (never the accumulated total).
31
31
  * Web UI preview only — the complete message above stays authoritative. */
32
32
  onAssistantDelta: ((text: string, blockId: string) => void) | null;
33
+ onAssistantThinking: ((text: string, blockId?: string) => void) | null;
34
+ onAssistantThinkingDelta: ((text: string, blockId: string) => void) | null;
33
35
  /** `subagent` is set only when a native subagent made the call (see ToolUseSubagent).
34
36
  * Optional so existing implementations that ignore attribution still satisfy the type. */
35
37
  onToolUse: ((name: string, input: any, toolUseId: string, subagent?: ToolUseSubagent) => void) | null;
@@ -193,9 +195,8 @@ export declare class ClaudeTurnMachine {
193
195
  * anything from a subagent that ran beside it.
194
196
  */
195
197
  private handleOrphanSubagentLine;
196
- private handleAssistantToolBlock;
197
- private handleAssistantTextBlock;
198
198
  private handleAssistantEvent;
199
+ private handleStreamEvent;
199
200
  private emitContextUsage;
200
201
  /**
201
202
  * OC-11 / §17 G4-SA5 — read the linkage the CLI already puts on the wire. A non-null
@@ -3,9 +3,11 @@ import { Writable } from 'stream';
3
3
  import * as path from 'path';
4
4
  import { readableTimestamp } from '../../core/utils.js';
5
5
  import { createLogger } from '../../core/log.js';
6
+ import { getSettings } from '../../core/settings.js';
7
+ import { handleAssistantBlocks } from './assistant-blocks.js';
6
8
  import { toolResultImages } from '../normalize/tool-result-images.js';
7
9
  import { CancelledError, LOGS_DIR } from './defaults.js';
8
- import { buildPrompt, clearActivePlanFile, extractResult, formatEvent, isPlanFilePath, setActivePlanFile, createStreamDeltaState, parseStreamEvent, takeTextBlockId, parseModelFallbackEvent, } from './event-parser.js';
10
+ import { buildPrompt, clearActivePlanFile, extractResult, formatEvent, createStreamDeltaState, parseStreamEvent, parseModelFallbackEvent, } from './event-parser.js';
9
11
  import { BgTaskTracker, isContinuationResult, routeLine } from './bg-task-tracker.js';
10
12
  import { promptAccounting, tokenValue, } from './event-translator.js';
11
13
  import { activeClaudeCaptureRegistry } from './active-capture-registry.js';
@@ -197,6 +199,8 @@ export class ClaudeTurnMachine {
197
199
  onProgress: options.onProgress || null,
198
200
  onAssistantMessage: options.onAssistantMessage || null,
199
201
  onAssistantDelta: options.onAssistantDelta || null,
202
+ onAssistantThinking: options.onAssistantThinking || null,
203
+ onAssistantThinkingDelta: options.onAssistantThinkingDelta || null,
200
204
  onToolUse: options.onToolUse || null,
201
205
  onToolResult: options.onToolResult || null,
202
206
  onCompact: options.onCompact || null,
@@ -301,6 +305,7 @@ export class ClaudeTurnMachine {
301
305
  resolve: (value) => this.deliverContinuation(sink => sink.onResult(value)),
302
306
  reject: (error) => log.warn('continuation turn rejected:', error?.message ?? String(error)),
303
307
  onAssistantMessage: (text, _blockId, model, subagent) => this.deliverContinuation(sink => sink.onAssistantText(text, model, subagent)),
308
+ onAssistantThinking: (text, blockId) => this.deliverContinuation(sink => sink.onAssistantThinking?.(text, blockId)),
304
309
  onToolUse: (name, input, id, subagent) => this.deliverContinuation(sink => sink.onToolUse?.(name, input, id, subagent)),
305
310
  onToolResult: (id, content, isError, subagent, images) => this.deliverContinuation(sink => sink.onToolResult?.(id, content, isError, subagent, images)),
306
311
  onContextUsage: (usage) => this.deliverContinuation(sink => sink.onContextUsage?.(usage)),
@@ -323,7 +328,7 @@ export class ClaudeTurnMachine {
323
328
  capturePairKey: streams.pairKey,
324
329
  releaseCapture: streams.releaseCapture,
325
330
  onProgress: null, onAssistantDelta: null, onCompact: null, onSubagentActivity: null,
326
- onSubagentEnd: null,
331
+ onSubagentEnd: null, onAssistantThinkingDelta: null,
327
332
  rawStream: streams.rawStream, txtStream: streams.txtStream,
328
333
  killed: false, spontaneous: true,
329
334
  };
@@ -471,65 +476,22 @@ export class ClaudeTurnMachine {
471
476
  }
472
477
  }
473
478
  }
474
- handleAssistantToolBlock(turn, block, subagent) {
475
- if (block.name === 'Write' && isPlanFilePath(block.input?.file_path)) {
476
- turn.planFilePath = block.input.file_path;
477
- setActivePlanFile(this.host.sessionId, block.input.file_path);
478
- }
479
- if (block.name === 'EnterPlanMode')
480
- turn.enteredPlanMode = true;
481
- if (block.name === 'ExitPlanMode')
482
- turn.exitedPlanMode = true;
483
- if (typeof turn.onToolUse !== 'function')
484
- return;
485
- try {
486
- turn.onToolUse(block.name || '?', block.input || {}, typeof block.id === 'string' ? block.id : '', subagent);
487
- }
488
- catch (error) {
489
- log.warn('onToolUse threw:', error.message);
490
- }
479
+ handleAssistantEvent(turn, data) {
480
+ handleAssistantBlocks(turn, data, this.streamDeltaState, this.host.sessionId, subagentAttribution(data));
491
481
  }
492
- handleAssistantTextBlock(turn, data, block, subagent) {
493
- if (!block.text)
494
- return;
495
- const model = typeof data.message?.model === 'string' ? data.message.model : null;
496
- // A subagent's text is NOT this turn's answer, and it did not stream: the CLI attaches subagent
497
- // linkage only to complete `assistant`/`user` messages, never to `stream_event`. So it must not
498
- // become finalOutput, must not win longestOutput, and — above all — must not consume the delta
499
- // cursor, which belongs to a main-agent block still being streamed.
500
- if (subagent) {
501
- turn.onAssistantMessage?.(block.text, undefined, model, subagent);
482
+ handleStreamEvent(data) {
483
+ this.emitContextUsage(data);
484
+ const delta = parseStreamEvent(data, this.streamDeltaState);
485
+ if (!delta)
502
486
  return;
487
+ const callback = delta.kind === 'thinking'
488
+ ? (getSettings().showThinking ? this.currentTurn?.onAssistantThinkingDelta : null)
489
+ : this.currentTurn?.onAssistantDelta;
490
+ try {
491
+ callback?.(delta.text, delta.blockId);
503
492
  }
504
- turn.finalOutput = block.text;
505
- if (block.text.length > (turn.longestOutput?.length || 0))
506
- turn.longestOutput = block.text;
507
- const blockId = takeTextBlockId(this.streamDeltaState) ?? undefined;
508
- const streamedModel = this.streamDeltaState.messageId === data.message?.id
509
- ? this.streamDeltaState.model
510
- : null;
511
- turn.onAssistantMessage?.(block.text, blockId, model ?? streamedModel);
512
- }
513
- handleAssistantEvent(turn, data) {
514
- // Every line still walks every branch below — subagent lines are TAGGED, never dropped, so the
515
- // journal keeps a complete trajectory. What the tag changes is attribution: a subagent's turns
516
- // are counted apart from the main agent's, and its text cannot be mistaken for the answer.
517
- const subagent = subagentAttribution(data);
518
- if (subagent)
519
- turn.subagentTurnCount += 1;
520
- else
521
- turn.turnCount += 1;
522
- for (const block of (data.message?.content || [])) {
523
- if (block.type === 'tool_use')
524
- this.handleAssistantToolBlock(turn, block, subagent);
525
- if (block.type === 'text')
526
- this.handleAssistantTextBlock(turn, data, block, subagent);
527
- }
528
- // A subagent's message did not advance the main agent's turn, so re-rendering progress would
529
- // redraw the same number. The JSONL path withholds turn_progress on sidechain records for the
530
- // same reason.
531
- if (!subagent) {
532
- turn.onProgress?.({ num_turns: turn.turnCount, total_cost_usd: null, duration_ms: null });
493
+ catch (e) {
494
+ log.warn('assistant delta callback threw:', e.message);
533
495
  }
534
496
  }
535
497
  emitContextUsage(data) {
@@ -599,16 +561,7 @@ export class ClaudeTurnMachine {
599
561
  // are deliberately kept out of the per-turn raw jsonl and the daemon log. Handled first, and
600
562
  // separately, because everything below is about complete events.
601
563
  if (isJson && parsed?.type === 'stream_event') {
602
- this.emitContextUsage(parsed);
603
- const delta = parseStreamEvent(parsed, this.streamDeltaState);
604
- if (delta && typeof this.currentTurn?.onAssistantDelta === 'function') {
605
- try {
606
- this.currentTurn.onAssistantDelta(delta.text, delta.blockId);
607
- }
608
- catch (e) {
609
- log.warn('onAssistantDelta threw:', e.message);
610
- }
611
- }
564
+ this.handleStreamEvent(parsed);
612
565
  return;
613
566
  }
614
567
  if (this.currentTurn?.rawStream)
@@ -0,0 +1,13 @@
1
+ import { runFile } from '../../core/exec-async.js';
2
+ export declare const WINDOW_WARMUP_TIMEOUT_MS = 120000;
3
+ /** No tools, no MCP servers, no session file. The prompt goes on stdin because `--tools` takes a
4
+ * variable number of values and would swallow a trailing positional prompt. */
5
+ export declare const WINDOW_WARMUP_ARGS: readonly string[];
6
+ export interface WindowWarmupLaunch {
7
+ command: string;
8
+ env: NodeJS.ProcessEnv;
9
+ cwd: string;
10
+ }
11
+ export type WindowWarmupRunner = typeof runFile;
12
+ /** Resolves once Claude answered; rejects with the CLI's own error text otherwise. */
13
+ export declare function runWindowWarmup(launch: WindowWarmupLaunch, run?: WindowWarmupRunner): Promise<void>;
@@ -0,0 +1,38 @@
1
+ import { runFile } from '../../core/exec-async.js';
2
+ // One tiny request through Claude Code itself. It opens Claude's five-hour subscription window, and
3
+ // on the way Claude Code refreshes its own login under its own lock, which Cortex must not do
4
+ // behind its back.
5
+ export const WINDOW_WARMUP_TIMEOUT_MS = 120_000;
6
+ const WARMUP_PROMPT = 'ok';
7
+ /** No tools, no MCP servers, no session file. The prompt goes on stdin because `--tools` takes a
8
+ * variable number of values and would swallow a trailing positional prompt. */
9
+ export const WINDOW_WARMUP_ARGS = [
10
+ '-p', '--output-format', 'json', '--model', 'haiku', '--max-turns', '1',
11
+ '--no-session-persistence', '--strict-mcp-config',
12
+ '--system-prompt', 'Reply with exactly: ok', '--tools', '',
13
+ ];
14
+ function parseResult(stdout) {
15
+ try {
16
+ const record = JSON.parse(stdout.trim());
17
+ return record && typeof record === 'object' && record.type === 'result' ? record : null;
18
+ }
19
+ catch {
20
+ return null;
21
+ }
22
+ }
23
+ function failureText(result, output) {
24
+ if (result.timedOut)
25
+ return `timed out after ${WINDOW_WARMUP_TIMEOUT_MS}ms`;
26
+ const text = typeof output?.result === 'string' ? output.result : result.stderr.trim() || result.error;
27
+ return (text || `exit ${result.code}`).slice(-300);
28
+ }
29
+ /** Resolves once Claude answered; rejects with the CLI's own error text otherwise. */
30
+ export async function runWindowWarmup(launch, run = runFile) {
31
+ const result = await run(launch.command, WINDOW_WARMUP_ARGS, {
32
+ cwd: launch.cwd, env: launch.env, timeoutMs: WINDOW_WARMUP_TIMEOUT_MS, stdin: WARMUP_PROMPT,
33
+ });
34
+ const output = parseResult(result.stdout);
35
+ if (result.ok && output && output.is_error !== true)
36
+ return;
37
+ throw new Error(`Claude warm-up failed: ${failureText(result, output)}`);
38
+ }