aegiscode 3.1.8 → 3.1.10

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 (206) hide show
  1. package/README.md +23 -15
  2. package/dist/main.js +549 -552
  3. package/package.json +4 -2
  4. package/src/agent/Agent.ts +903 -0
  5. package/src/agent/SimpleAgent.ts +48 -0
  6. package/src/agent/index.ts +54 -0
  7. package/src/agent/orchestrator/AppBuilder.ts +443 -0
  8. package/src/agent/orchestrator/CouncilAgent.ts +310 -0
  9. package/src/agent/orchestrator/DiscussionRoom.ts +462 -0
  10. package/src/agent/orchestrator/OrchestratorAgent.ts +637 -0
  11. package/src/agent/orchestrator/index.ts +38 -0
  12. package/src/agent/orchestrator/utils.ts +397 -0
  13. package/src/agent/pricing.ts +115 -0
  14. package/src/agent/router.ts +74 -0
  15. package/src/agent/routerStats.ts +121 -0
  16. package/src/agent/types.ts +318 -0
  17. package/src/auth/login.ts +383 -0
  18. package/src/cli/config.ts +189 -0
  19. package/src/cli/index.ts +17 -0
  20. package/src/cli/middleware.ts +119 -0
  21. package/src/cli/types.ts +75 -0
  22. package/src/config/ConfigManager.ts +587 -0
  23. package/src/config/index.ts +7 -0
  24. package/src/config/types.ts +584 -0
  25. package/src/context/CompactionService.ts +300 -0
  26. package/src/context/ContextManager.ts +450 -0
  27. package/src/context/FileAnalyzer.ts +267 -0
  28. package/src/context/TokenCounter.ts +265 -0
  29. package/src/context/index.ts +27 -0
  30. package/src/context/storage/CacheStore.ts +176 -0
  31. package/src/context/storage/JSONLStore.ts +201 -0
  32. package/src/context/storage/MemoryStore.ts +205 -0
  33. package/src/context/storage/PersistentStore.ts +327 -0
  34. package/src/context/storage/index.ts +9 -0
  35. package/src/context/storage/pathUtils.ts +114 -0
  36. package/src/context/test.ts +309 -0
  37. package/src/context/types.ts +268 -0
  38. package/src/hooks/HookExecutor.ts +434 -0
  39. package/src/hooks/HookManager.ts +596 -0
  40. package/src/hooks/HookService.ts +269 -0
  41. package/src/hooks/Matcher.ts +157 -0
  42. package/src/hooks/index.ts +63 -0
  43. package/src/hooks/types.ts +424 -0
  44. package/src/main.tsx +596 -0
  45. package/src/mcp/HealthMonitor.ts +150 -0
  46. package/src/mcp/McpClient.ts +491 -0
  47. package/src/mcp/McpRegistry.ts +321 -0
  48. package/src/mcp/createMcpTool.ts +251 -0
  49. package/src/mcp/index.ts +15 -0
  50. package/src/mcp/server.ts +334 -0
  51. package/src/mcp/test-server.ts +88 -0
  52. package/src/mcp/test.ts +372 -0
  53. package/src/mcp/types.ts +247 -0
  54. package/src/memory/AgentMemoryBus.ts +432 -0
  55. package/src/memory/CloudSync.ts +99 -0
  56. package/src/memory/DriveSync.ts +106 -0
  57. package/src/memory/SharedMemory.ts +951 -0
  58. package/src/memory/index.ts +14 -0
  59. package/src/memory/machineFingerprint.ts +40 -0
  60. package/src/orchestrator/SubAgentMetadata.ts +136 -0
  61. package/src/prompts/builder.ts +213 -0
  62. package/src/prompts/default.ts +144 -0
  63. package/src/prompts/index.ts +16 -0
  64. package/src/prompts/plan.ts +64 -0
  65. package/src/prompts/test.ts +78 -0
  66. package/src/services/AnthropicChatService.ts +341 -0
  67. package/src/services/ChatService.ts +347 -0
  68. package/src/services/ClaudeCliChatService.ts +256 -0
  69. package/src/services/CloudSync.ts +168 -0
  70. package/src/services/CostLedger.ts +211 -0
  71. package/src/services/Heartbeat.ts +135 -0
  72. package/src/services/LearningCollector.ts +291 -0
  73. package/src/services/OllamaInstaller.ts +342 -0
  74. package/src/services/VersionChecker.ts +445 -0
  75. package/src/services/index.ts +57 -0
  76. package/src/services/streaming/OpenAIEventAdapter.ts +126 -0
  77. package/src/services/streaming/RenderingProfile.ts +90 -0
  78. package/src/services/streaming/StreamEventParser.ts +181 -0
  79. package/src/services/streaming/ThrottledRenderer.ts +139 -0
  80. package/src/services/streaming/TranscriptBuffer.ts +574 -0
  81. package/src/services/streaming/eventStatusMap.ts +52 -0
  82. package/src/services/streaming/index.ts +46 -0
  83. package/src/services/streaming/renderFormatting.ts +79 -0
  84. package/src/services/streaming/types.ts +234 -0
  85. package/src/skills/SkillLoader.ts +126 -0
  86. package/src/skills/SkillRegistry.ts +366 -0
  87. package/src/skills/index.ts +48 -0
  88. package/src/skills/types.ts +146 -0
  89. package/src/slash-commands/billing.ts +70 -0
  90. package/src/slash-commands/build.ts +413 -0
  91. package/src/slash-commands/builtinCommands.ts +2733 -0
  92. package/src/slash-commands/clone.ts +242 -0
  93. package/src/slash-commands/council.ts +125 -0
  94. package/src/slash-commands/custom/CustomCommandExecutor.ts +143 -0
  95. package/src/slash-commands/custom/CustomCommandLoader.ts +251 -0
  96. package/src/slash-commands/custom/CustomCommandRegistry.ts +144 -0
  97. package/src/slash-commands/custom/index.ts +7 -0
  98. package/src/slash-commands/debate.ts +254 -0
  99. package/src/slash-commands/gmail.ts +105 -0
  100. package/src/slash-commands/index.ts +388 -0
  101. package/src/slash-commands/mcpCommand.ts +205 -0
  102. package/src/slash-commands/types.ts +201 -0
  103. package/src/store/index.ts +76 -0
  104. package/src/store/selectors.ts +246 -0
  105. package/src/store/slices/appSlice.ts +205 -0
  106. package/src/store/slices/commandSlice.ts +115 -0
  107. package/src/store/slices/configSlice.ts +46 -0
  108. package/src/store/slices/focusSlice.ts +64 -0
  109. package/src/store/slices/index.ts +9 -0
  110. package/src/store/slices/sessionSlice.ts +424 -0
  111. package/src/store/streaming-buffer.ts +425 -0
  112. package/src/store/test.ts +296 -0
  113. package/src/store/types.ts +274 -0
  114. package/src/store/vanilla.ts +186 -0
  115. package/src/tools/builtin/bash.ts +236 -0
  116. package/src/tools/builtin/council.ts +105 -0
  117. package/src/tools/builtin/edit.ts +213 -0
  118. package/src/tools/builtin/glob.ts +136 -0
  119. package/src/tools/builtin/grep.ts +263 -0
  120. package/src/tools/builtin/index.ts +61 -0
  121. package/src/tools/builtin/memory.ts +66 -0
  122. package/src/tools/builtin/read.ts +168 -0
  123. package/src/tools/builtin/skill.ts +97 -0
  124. package/src/tools/builtin/snapshot.ts +40 -0
  125. package/src/tools/builtin/task.ts +106 -0
  126. package/src/tools/builtin/write.ts +134 -0
  127. package/src/tools/createTool.ts +221 -0
  128. package/src/tools/execution/ExecutionPipeline.ts +263 -0
  129. package/src/tools/execution/index.ts +40 -0
  130. package/src/tools/execution/stages/CacheStage.ts +131 -0
  131. package/src/tools/execution/stages/ConfirmationStage.ts +203 -0
  132. package/src/tools/execution/stages/DiscoveryStage.ts +46 -0
  133. package/src/tools/execution/stages/ExecutionStage.ts +48 -0
  134. package/src/tools/execution/stages/FormattingStage.ts +44 -0
  135. package/src/tools/execution/stages/HookStage.ts +72 -0
  136. package/src/tools/execution/stages/PermissionStage.ts +287 -0
  137. package/src/tools/execution/stages/PostHookStage.ts +71 -0
  138. package/src/tools/execution/stages/index.ts +12 -0
  139. package/src/tools/execution/test.ts +266 -0
  140. package/src/tools/execution/types.ts +273 -0
  141. package/src/tools/index.ts +81 -0
  142. package/src/tools/registry.ts +304 -0
  143. package/src/tools/schemas.ts +109 -0
  144. package/src/tools/test.ts +220 -0
  145. package/src/tools/types.ts +175 -0
  146. package/src/tools/validation/PermissionChecker.ts +242 -0
  147. package/src/tools/validation/SensitiveFileDetector.ts +210 -0
  148. package/src/tools/validation/index.ts +11 -0
  149. package/src/ui/App.tsx +166 -0
  150. package/src/ui/components/AegisInterface.tsx +484 -0
  151. package/src/ui/components/common/ChatSearch.tsx +150 -0
  152. package/src/ui/components/common/ErrorBoundary.tsx +82 -0
  153. package/src/ui/components/common/ExitMessage.tsx +120 -0
  154. package/src/ui/components/common/LoadingIndicator.tsx +49 -0
  155. package/src/ui/components/common/index.ts +6 -0
  156. package/src/ui/components/dialog/ConfirmationPrompt.tsx +208 -0
  157. package/src/ui/components/dialog/InteractiveSelector.tsx +149 -0
  158. package/src/ui/components/dialog/SetupWizard.tsx +297 -0
  159. package/src/ui/components/dialog/UpdatePrompt.tsx +155 -0
  160. package/src/ui/components/dialog/index.ts +8 -0
  161. package/src/ui/components/index.ts +28 -0
  162. package/src/ui/components/input/CommandSuggestions.tsx +139 -0
  163. package/src/ui/components/input/CustomTextInput.tsx +220 -0
  164. package/src/ui/components/input/InputArea.tsx +361 -0
  165. package/src/ui/components/input/PromptSuggestions.tsx +66 -0
  166. package/src/ui/components/input/index.ts +6 -0
  167. package/src/ui/components/layout/ChatStatusBar.tsx +90 -0
  168. package/src/ui/components/layout/ContextBar.tsx +79 -0
  169. package/src/ui/components/layout/MessageArea.tsx +96 -0
  170. package/src/ui/components/layout/MessageList.tsx +647 -0
  171. package/src/ui/components/layout/MessageSeparator.tsx +26 -0
  172. package/src/ui/components/layout/WelcomeMessage.tsx +93 -0
  173. package/src/ui/components/layout/index.ts +7 -0
  174. package/src/ui/components/markdown/CodeHighlighter.tsx +292 -0
  175. package/src/ui/components/markdown/MessageRenderer.tsx +1211 -0
  176. package/src/ui/components/markdown/index.ts +8 -0
  177. package/src/ui/components/markdown/parser.ts +336 -0
  178. package/src/ui/components/markdown/types.ts +66 -0
  179. package/src/ui/focus/FocusManager.ts +137 -0
  180. package/src/ui/focus/index.ts +13 -0
  181. package/src/ui/focus/types.ts +54 -0
  182. package/src/ui/focus/useFocus.ts +75 -0
  183. package/src/ui/hooks/index.ts +11 -0
  184. package/src/ui/hooks/useAgent.ts +284 -0
  185. package/src/ui/hooks/useCommandHistory.ts +87 -0
  186. package/src/ui/hooks/useCommandProcessor.ts +443 -0
  187. package/src/ui/hooks/useConfirmation.ts +99 -0
  188. package/src/ui/hooks/useCtrlCHandler.ts +100 -0
  189. package/src/ui/hooks/useInputBuffer.ts +122 -0
  190. package/src/ui/hooks/useTerminalSize.ts +68 -0
  191. package/src/ui/hooks/useTerminalWidth.ts +5 -0
  192. package/src/ui/hooks/useWindowedList.ts +118 -0
  193. package/src/ui/render-debugger.ts +621 -0
  194. package/src/ui/test.ts +189 -0
  195. package/src/ui/themes/ThemeManager.ts +332 -0
  196. package/src/ui/themes/aegisTheme.ts +87 -0
  197. package/src/ui/themes/darkTheme.ts +87 -0
  198. package/src/ui/themes/defaultTheme.ts +85 -0
  199. package/src/ui/themes/index.ts +10 -0
  200. package/src/ui/themes/lightTheme.ts +89 -0
  201. package/src/ui/themes/popularThemes.ts +187 -0
  202. package/src/ui/themes/types.ts +130 -0
  203. package/src/utils/clipboard.ts +48 -0
  204. package/src/utils/debug.ts +43 -0
  205. package/src/utils/environment.ts +68 -0
  206. package/src/utils/index.ts +10 -0
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Command Slice - 命令状态管理
3
+ */
4
+
5
+ import type { StateCreator } from 'zustand';
6
+ import type { ClawdStore, CommandSlice } from '../types.js';
7
+
8
+ const initialCommandState = {
9
+ isProcessing: false,
10
+ abortController: null as AbortController | null,
11
+ pendingCommands: [] as string[],
12
+ };
13
+
14
+ export const createCommandSlice: StateCreator<
15
+ ClawdStore,
16
+ [],
17
+ [],
18
+ CommandSlice
19
+ > = (set, get) => ({
20
+ ...initialCommandState,
21
+
22
+ actions: {
23
+ /**
24
+ *
25
+ */
26
+ setProcessing: (isProcessing: boolean) => {
27
+ set((state) => ({
28
+ command: { ...state.command, isProcessing },
29
+ }));
30
+ },
31
+
32
+ /**
33
+ *
34
+ */
35
+ createAbortController: () => {
36
+ const controller = new AbortController();
37
+ set((state) => ({
38
+ command: { ...state.command, abortController: controller },
39
+ }));
40
+ return controller;
41
+ },
42
+
43
+ /**
44
+ *
45
+ * - 发送 abort signal
46
+ * - 重置 isProcessing
47
+ * - 重置 isThinking (跨 slice)
48
+ * - 清空待处理队列
49
+ */
50
+ abort: () => {
51
+ const { abortController } = get().command;
52
+
53
+ if (abortController && !abortController.signal.aborted) {
54
+ abortController.abort();
55
+ }
56
+
57
+ // 重置 session 的 isThinking 状
58
+ get().session.actions.setThinking(false);
59
+
60
+ // 重置 command 状态并清空队
61
+ set((state) => ({
62
+ command: {
63
+ ...state.command,
64
+ isProcessing: false,
65
+ abortController: null,
66
+ pendingCommands: [],
67
+ },
68
+ }));
69
+ },
70
+
71
+ /**
72
+ *
73
+ */
74
+ enqueueCommand: (command: string) => {
75
+ set((state) => ({
76
+ command: {
77
+ ...state.command,
78
+ pendingCommands: [...state.command.pendingCommands, command],
79
+ },
80
+ }));
81
+ },
82
+
83
+ /**
84
+ *
85
+ */
86
+ dequeueCommand: () => {
87
+ const { pendingCommands } = get().command;
88
+ if (pendingCommands.length === 0) {
89
+ return undefined;
90
+ }
91
+
92
+ const [nextCommand, ...rest] = pendingCommands;
93
+ set((state) => ({
94
+ command: {
95
+ ...state.command,
96
+ pendingCommands: rest,
97
+ },
98
+ }));
99
+
100
+ return nextCommand;
101
+ },
102
+
103
+ /**
104
+ *
105
+ */
106
+ clearQueue: () => {
107
+ set((state) => ({
108
+ command: {
109
+ ...state.command,
110
+ pendingCommands: [],
111
+ },
112
+ }));
113
+ },
114
+ },
115
+ });
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Config Slice - 配置状态管理
3
+ */
4
+
5
+ import type { StateCreator } from 'zustand';
6
+ import type { ClawdStore, ConfigSlice } from '../types.js';
7
+ import type { RuntimeConfig } from '../../config/types.js';
8
+
9
+ export const createConfigSlice: StateCreator<
10
+ ClawdStore,
11
+ [],
12
+ [],
13
+ ConfigSlice
14
+ > = (set) => ({
15
+ config: null,
16
+
17
+ actions: {
18
+ /**
19
+ *
20
+ */
21
+ setConfig: (config: RuntimeConfig) => {
22
+ set((state) => ({
23
+ config: { ...state.config, config },
24
+ }));
25
+ },
26
+
27
+ /**
28
+ *
29
+ */
30
+ updateConfig: (partial: Partial<RuntimeConfig>) => {
31
+ set((state) => {
32
+ if (!state.config.config) {
33
+ console.warn('[ConfigSlice] Config not initialized, cannot update');
34
+ return state;
35
+ }
36
+
37
+ return {
38
+ config: {
39
+ ...state.config,
40
+ config: { ...state.config.config, ...partial },
41
+ },
42
+ };
43
+ });
44
+ },
45
+ },
46
+ });
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Focus Slice - 焦点状态管理
3
+ */
4
+
5
+ import type { StateCreator } from 'zustand';
6
+ import type { ClawdStore, FocusSlice, FocusId } from '../types.js';
7
+
8
+ const initialFocusState = {
9
+ currentFocus: 'input' as FocusId,
10
+ previousFocus: null as FocusId | null,
11
+ };
12
+
13
+ export const createFocusSlice: StateCreator<
14
+ ClawdStore,
15
+ [],
16
+ [],
17
+ FocusSlice
18
+ > = (set, get) => ({
19
+ ...initialFocusState,
20
+
21
+ actions: {
22
+ /**
23
+ *
24
+ */
25
+ setFocus: (focus: FocusId) => {
26
+ set((state) => ({
27
+ focus: {
28
+ ...state.focus,
29
+ previousFocus: state.focus.currentFocus,
30
+ currentFocus: focus,
31
+ },
32
+ }));
33
+ },
34
+
35
+ /**
36
+ *
37
+ */
38
+ restoreFocus: () => {
39
+ const { previousFocus } = get().focus;
40
+ if (previousFocus) {
41
+ set((state) => ({
42
+ focus: {
43
+ ...state.focus,
44
+ currentFocus: previousFocus,
45
+ previousFocus: null,
46
+ },
47
+ }));
48
+ }
49
+ },
50
+
51
+ /**
52
+ *
53
+ */
54
+ pushFocus: (focus: FocusId) => {
55
+ set((state) => ({
56
+ focus: {
57
+ ...state.focus,
58
+ previousFocus: state.focus.currentFocus,
59
+ currentFocus: focus,
60
+ },
61
+ }));
62
+ },
63
+ },
64
+ });
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Store Slices 导出
3
+ */
4
+
5
+ export { createSessionSlice } from './sessionSlice.js';
6
+ export { createConfigSlice } from './configSlice.js';
7
+ export { createAppSlice } from './appSlice.js';
8
+ export { createFocusSlice } from './focusSlice.js';
9
+ export { createCommandSlice } from './commandSlice.js';
@@ -0,0 +1,424 @@
1
+ /**
2
+ * Session Slice - 会话状态管理
3
+ *
4
+ * Streaming Architecture (Buffer + Store):
5
+ *
6
+ * During streaming, content deltas arrive at high frequency (per-character).
7
+ * Writing each delta to the zustand store triggers cascading re-renders
8
+ * across ALL subscribers — causing visible terminal "blink".
9
+ *
10
+ * Solution: External mutable buffer (streaming-buffer.ts).
11
+ * - deltas → appendToBuffer() — O(1), no store update
12
+ * - MessageList RAF loop polls buffer directly — only MessageList re-renders
13
+ * - Store updated only at: start, flush (tool calls), finish
14
+ *
15
+ * flushStreamBuffer → drainBuffer() → store.set() → initStreamingBuffer()
16
+ * Used mid-streaming (e.g., before a tool call) to persist content to store
17
+ * while keeping the buffer alive for subsequent deltas.
18
+ *
19
+ * finishStreamingMessage → drainBuffer() → store.set() (isStreaming=false)
20
+ * Finalizes the message. No re-init — streaming is done.
21
+ */
22
+
23
+ import type { StateCreator } from 'zustand';
24
+ import type { ClawdStore, SessionSlice, SessionMessage, TokenUsage, ContentBlock, ToolCallStatus } from '../types.js';
25
+ import { appendToBuffer, appendThinkingToBuffer, initStreamingBuffer, drainBuffer, clearBuffer } from '../streaming-buffer.js';
26
+
27
+ const generateId = () => `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
28
+
29
+ // Mutable buffer for in-progress tool inputs.
30
+ // updateToolCallInput accumulates here without touching the store;
31
+ // setToolCallInput flushes the final value in a single set() call.
32
+ const _toolInputBuffer = new Map<string, string>(); // toolCallId → partial JSON
33
+
34
+ const initialSessionState = {
35
+ sessionId: generateId(),
36
+ messages: [] as SessionMessage[],
37
+ isThinking: false,
38
+ isCompacting: false,
39
+ currentCommand: null as string | null,
40
+ error: null as string | null,
41
+ isActive: true,
42
+ tokenUsage: {
43
+ inputTokens: 0,
44
+ outputTokens: 0,
45
+ totalTokens: 0,
46
+ maxContextTokens: 200000,
47
+ modelBreakdown: {},
48
+ } as TokenUsage,
49
+ };
50
+
51
+ export const createSessionSlice: StateCreator<
52
+ ClawdStore,
53
+ [],
54
+ [],
55
+ SessionSlice
56
+ > = (set, get) => ({
57
+ ...initialSessionState,
58
+
59
+ actions: {
60
+ /**
61
+ * Append a fully-formed message (no streaming).
62
+ */
63
+ addMessage: (message: SessionMessage) => {
64
+ set((state) => ({
65
+ session: {
66
+ ...state.session,
67
+ messages: [...state.session.messages, message],
68
+ error: null,
69
+ },
70
+ }));
71
+ },
72
+
73
+ /**
74
+ * Create and append a user message from plain text.
75
+ */
76
+ addUserMessage: (content: string) => {
77
+ const message: SessionMessage = {
78
+ id: `user-${generateId()}`,
79
+ role: 'user',
80
+ content,
81
+ timestamp: Date.now(),
82
+ };
83
+ get().session.actions.addMessage(message);
84
+ },
85
+
86
+ /**
87
+ * Create and append a fully-formed assistant message.
88
+ */
89
+ addAssistantMessage: (content: string) => {
90
+ const message: SessionMessage = {
91
+ id: `assistant-${generateId()}`,
92
+ role: 'assistant',
93
+ content,
94
+ timestamp: Date.now(),
95
+ };
96
+ get().session.actions.addMessage(message);
97
+ },
98
+
99
+ /**
100
+ * Start a new streaming assistant message.
101
+ * Creates an empty placeholder in the store and initializes the buffer.
102
+ * Returns the message ID for subsequent delta/flush/finish calls.
103
+ */
104
+ startStreamingMessage: () => {
105
+ const id = `assistant-${generateId()}`;
106
+ const message: SessionMessage = {
107
+ id,
108
+ role: 'assistant',
109
+ content: '',
110
+ thinking: '',
111
+ timestamp: Date.now(),
112
+ isStreaming: true,
113
+ };
114
+ set((state) => ({
115
+ session: {
116
+ ...state.session,
117
+ messages: [...state.session.messages, message],
118
+ error: null,
119
+ },
120
+ }));
121
+ initStreamingBuffer(id);
122
+ return id;
123
+ },
124
+
125
+ /**
126
+ * Append content delta to the mutable buffer ONLY.
127
+ * No store update — the RAF loop picks up content from the buffer.
128
+ */
129
+ appendToStreamingMessage: (_id: string, contentDelta: string) => {
130
+ appendToBuffer(contentDelta);
131
+ },
132
+
133
+ /**
134
+ * Append thinking delta to the mutable buffer ONLY.
135
+ * No store update — same reasoning as appendToStreamingMessage.
136
+ */
137
+ appendThinkingToStreamingMessage: (_id: string, thinkingDelta: string) => {
138
+ if (thinkingDelta) {
139
+ appendThinkingToBuffer(thinkingDelta);
140
+ }
141
+ },
142
+
143
+ /**
144
+ * Force-flush buffer content to the store, then re-init the buffer.
145
+ *
146
+ * Used before tool calls so preceding text is persisted to the message
147
+ * while the buffer stays alive for tool call arguments and subsequent text.
148
+ *
149
+ * drainBuffer() atomically reads + clears the buffer (but keeps messageId).
150
+ * Then initStreamingBuffer() re-initializes with the same ID so
151
+ * isActiveStreamingMessage() still resolves correctly.
152
+ */
153
+ flushStreamBuffer: (id: string) => {
154
+ const drained = drainBuffer();
155
+ if (!drained || (!drained.content && !drained.thinking && drained.toolCalls.length === 0)) return;
156
+
157
+ set((state) => ({
158
+ session: {
159
+ ...state.session,
160
+ messages: state.session.messages.map(msg =>
161
+ msg.id === id
162
+ ? {
163
+ ...msg,
164
+ content: msg.content + drained.content,
165
+ thinking: (msg.thinking || '') + drained.thinking,
166
+ }
167
+ : msg
168
+ ),
169
+ },
170
+ }));
171
+
172
+ // Re-init so subsequent deltas are tracked under the same message ID.
173
+ initStreamingBuffer(id);
174
+ },
175
+
176
+ /**
177
+ * Write directly to the store message, bypassing the buffer.
178
+ * Used for immediate content (errors, forced updates) during streaming.
179
+ */
180
+ forceAppendToMessage: (id: string, contentDelta: string) => {
181
+ set((state) => ({
182
+ session: {
183
+ ...state.session,
184
+ messages: state.session.messages.map(msg =>
185
+ msg.id === id
186
+ ? { ...msg, content: msg.content + contentDelta }
187
+ : msg
188
+ ),
189
+ },
190
+ }));
191
+ },
192
+
193
+ /**
194
+ * Finalize streaming: drain buffer to store, mark message as complete.
195
+ *
196
+ * drainBuffer() reads and clears the buffer atomically. The content
197
+ * is appended to the store message and isStreaming is set to false.
198
+ * The RAF loop stops polling this message (isStreaming check fails).
199
+ *
200
+ * No re-init needed — streaming is done.
201
+ */
202
+ finishStreamingMessage: (id: string) => {
203
+ const drained = drainBuffer();
204
+ // Clear messageId so getStreamingContent() returns null immediately.
205
+ // Without this, the stale React state window sees a non-null buffer
206
+ // and keeps rendering the streaming cursor.
207
+ clearBuffer();
208
+
209
+ set((state) => ({
210
+ session: {
211
+ ...state.session,
212
+ messages: state.session.messages.map(msg =>
213
+ msg.id === id
214
+ ? {
215
+ ...msg,
216
+ content: msg.content + (drained ? drained.content : ''),
217
+ thinking: (msg.thinking || '') + (drained ? drained.thinking : ''),
218
+ isStreaming: false,
219
+ }
220
+ : msg
221
+ ),
222
+ },
223
+ }));
224
+ },
225
+
226
+ // ===== Content Block Operations =====
227
+
228
+ addContentBlock: (messageId: string, block: ContentBlock) => {
229
+ set((state) => ({
230
+ session: {
231
+ ...state.session,
232
+ messages: state.session.messages.map(msg =>
233
+ msg.id === messageId
234
+ ? {
235
+ ...msg,
236
+ contentBlocks: [...(msg.contentBlocks || []), block],
237
+ }
238
+ : msg
239
+ ),
240
+ },
241
+ }));
242
+ },
243
+
244
+ updateToolCallInput: (_messageId: string, toolCallId: string, partialJson: string) => {
245
+ // Accumulate in mutable buffer only — no store update per character.
246
+ // setToolCallInput flushes the final value in a single set() call.
247
+ _toolInputBuffer.set(toolCallId, (_toolInputBuffer.get(toolCallId) ?? '') + partialJson);
248
+ },
249
+
250
+ setToolCallInput: (messageId: string, toolCallId: string, fullInput: string) => {
251
+ _toolInputBuffer.delete(toolCallId);
252
+ set((state) => ({
253
+ session: {
254
+ ...state.session,
255
+ messages: state.session.messages.map(msg =>
256
+ msg.id === messageId && msg.contentBlocks
257
+ ? {
258
+ ...msg,
259
+ contentBlocks: msg.contentBlocks.map(block =>
260
+ block.type === 'tool_use' && block.id === toolCallId
261
+ ? { ...block, input: fullInput } as ContentBlock
262
+ : block
263
+ ),
264
+ }
265
+ : msg
266
+ ),
267
+ },
268
+ }));
269
+ },
270
+
271
+ updateToolCallStatus: (messageId: string, toolCallId: string, status: ToolCallStatus, completedAt?: number) => {
272
+ set((state) => ({
273
+ session: {
274
+ ...state.session,
275
+ messages: state.session.messages.map(msg =>
276
+ msg.id === messageId && msg.contentBlocks
277
+ ? {
278
+ ...msg,
279
+ contentBlocks: msg.contentBlocks.map(block =>
280
+ block.type === 'tool_use' && block.id === toolCallId
281
+ ? { ...block, status, ...(completedAt ? { completedAt } : {}) } as ContentBlock
282
+ : block
283
+ ),
284
+ }
285
+ : msg
286
+ ),
287
+ },
288
+ }));
289
+ },
290
+
291
+ addToolResultBlock: (messageId: string, toolUseId: string, content: string, isError: boolean) => {
292
+ set((state) => ({
293
+ session: {
294
+ ...state.session,
295
+ messages: state.session.messages.map(msg =>
296
+ msg.id === messageId
297
+ ? {
298
+ ...msg,
299
+ contentBlocks: [
300
+ ...(msg.contentBlocks || []),
301
+ { type: 'tool_result', tool_use_id: toolUseId, content, is_error: isError } as ContentBlock,
302
+ ],
303
+ }
304
+ : msg
305
+ ),
306
+ },
307
+ }));
308
+ },
309
+
310
+ /**
311
+ * Set thinking state indicator.
312
+ */
313
+ setThinking: (isThinking: boolean) => {
314
+ set((state) => ({
315
+ session: { ...state.session, isThinking },
316
+ }));
317
+ },
318
+
319
+ /**
320
+ * Set compacting indicator (context compaction in progress).
321
+ */
322
+ setCompacting: (isCompacting: boolean) => {
323
+ set((state) => ({
324
+ session: { ...state.session, isCompacting },
325
+ }));
326
+ },
327
+
328
+ /**
329
+ * Set the current command being processed.
330
+ */
331
+ setCurrentCommand: (command: string | null) => {
332
+ set((state) => ({
333
+ session: { ...state.session, currentCommand: command },
334
+ }));
335
+ },
336
+
337
+ /**
338
+ * Set error state.
339
+ */
340
+ setError: (error: string | null) => {
341
+ set((state) => ({
342
+ session: { ...state.session, error },
343
+ }));
344
+ },
345
+
346
+ /**
347
+ * Set session ID.
348
+ */
349
+ setSessionId: (sessionId: string) => {
350
+ set((state) => ({
351
+ session: {
352
+ ...state.session,
353
+ sessionId,
354
+ },
355
+ }));
356
+ },
357
+
358
+ /**
359
+ * Restore a session with messages from persistence.
360
+ */
361
+ restoreSession: (sessionId: string, messages: SessionMessage[]) => {
362
+ set((state) => ({
363
+ session: {
364
+ ...state.session,
365
+ sessionId,
366
+ messages,
367
+ error: null,
368
+ isActive: true,
369
+ },
370
+ }));
371
+ },
372
+
373
+ /**
374
+ * Update token usage counters.
375
+ */
376
+ updateTokenUsage: (usage: Partial<TokenUsage>) => {
377
+ set((state) => ({
378
+ session: {
379
+ ...state.session,
380
+ tokenUsage: { ...state.session.tokenUsage, ...usage },
381
+ },
382
+ }));
383
+ },
384
+
385
+ /**
386
+ * Remove the last N messages from the store.
387
+ * Used to rollback messages added before discovering a selector result.
388
+ */
389
+ removeLastMessages: (count: number) => {
390
+ set((state) => ({
391
+ session: {
392
+ ...state.session,
393
+ messages: state.session.messages.slice(0, -count),
394
+ },
395
+ }));
396
+ },
397
+
398
+ /**
399
+ * Clear all messages (new session within same session ID).
400
+ */
401
+ clearMessages: () => {
402
+ set((state) => ({
403
+ session: {
404
+ ...state.session,
405
+ messages: [],
406
+ error: null,
407
+ },
408
+ }));
409
+ },
410
+
411
+ /**
412
+ * Full session reset with a new session ID.
413
+ */
414
+ resetSession: () => {
415
+ set((state) => ({
416
+ session: {
417
+ ...state.session,
418
+ ...initialSessionState,
419
+ sessionId: generateId(),
420
+ },
421
+ }));
422
+ },
423
+ },
424
+ });