aegiscode 3.1.10 → 3.4.2

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 (209) hide show
  1. package/bin/aegis.js +165 -0
  2. package/package.json +18 -86
  3. package/LICENSE +0 -21
  4. package/README.md +0 -394
  5. package/dist/main.js +0 -2171
  6. package/gui/run-gui.cjs +0 -13
  7. package/src/agent/Agent.ts +0 -903
  8. package/src/agent/SimpleAgent.ts +0 -48
  9. package/src/agent/index.ts +0 -54
  10. package/src/agent/orchestrator/AppBuilder.ts +0 -443
  11. package/src/agent/orchestrator/CouncilAgent.ts +0 -310
  12. package/src/agent/orchestrator/DiscussionRoom.ts +0 -462
  13. package/src/agent/orchestrator/OrchestratorAgent.ts +0 -637
  14. package/src/agent/orchestrator/index.ts +0 -38
  15. package/src/agent/orchestrator/utils.ts +0 -397
  16. package/src/agent/pricing.ts +0 -115
  17. package/src/agent/router.ts +0 -74
  18. package/src/agent/routerStats.ts +0 -121
  19. package/src/agent/types.ts +0 -318
  20. package/src/auth/login.ts +0 -383
  21. package/src/cli/config.ts +0 -189
  22. package/src/cli/index.ts +0 -17
  23. package/src/cli/middleware.ts +0 -119
  24. package/src/cli/types.ts +0 -75
  25. package/src/config/ConfigManager.ts +0 -587
  26. package/src/config/index.ts +0 -7
  27. package/src/config/types.ts +0 -584
  28. package/src/context/CompactionService.ts +0 -300
  29. package/src/context/ContextManager.ts +0 -450
  30. package/src/context/FileAnalyzer.ts +0 -267
  31. package/src/context/TokenCounter.ts +0 -265
  32. package/src/context/index.ts +0 -27
  33. package/src/context/storage/CacheStore.ts +0 -176
  34. package/src/context/storage/JSONLStore.ts +0 -201
  35. package/src/context/storage/MemoryStore.ts +0 -205
  36. package/src/context/storage/PersistentStore.ts +0 -327
  37. package/src/context/storage/index.ts +0 -9
  38. package/src/context/storage/pathUtils.ts +0 -114
  39. package/src/context/test.ts +0 -309
  40. package/src/context/types.ts +0 -268
  41. package/src/hooks/HookExecutor.ts +0 -434
  42. package/src/hooks/HookManager.ts +0 -596
  43. package/src/hooks/HookService.ts +0 -269
  44. package/src/hooks/Matcher.ts +0 -157
  45. package/src/hooks/index.ts +0 -63
  46. package/src/hooks/types.ts +0 -424
  47. package/src/main.tsx +0 -596
  48. package/src/mcp/HealthMonitor.ts +0 -150
  49. package/src/mcp/McpClient.ts +0 -491
  50. package/src/mcp/McpRegistry.ts +0 -321
  51. package/src/mcp/createMcpTool.ts +0 -251
  52. package/src/mcp/index.ts +0 -15
  53. package/src/mcp/server.ts +0 -334
  54. package/src/mcp/test-server.ts +0 -88
  55. package/src/mcp/test.ts +0 -372
  56. package/src/mcp/types.ts +0 -247
  57. package/src/memory/AgentMemoryBus.ts +0 -432
  58. package/src/memory/CloudSync.ts +0 -99
  59. package/src/memory/DriveSync.ts +0 -106
  60. package/src/memory/SharedMemory.ts +0 -951
  61. package/src/memory/index.ts +0 -14
  62. package/src/memory/machineFingerprint.ts +0 -40
  63. package/src/orchestrator/SubAgentMetadata.ts +0 -136
  64. package/src/prompts/builder.ts +0 -213
  65. package/src/prompts/default.ts +0 -144
  66. package/src/prompts/index.ts +0 -16
  67. package/src/prompts/plan.ts +0 -64
  68. package/src/prompts/test.ts +0 -78
  69. package/src/services/AnthropicChatService.ts +0 -341
  70. package/src/services/ChatService.ts +0 -347
  71. package/src/services/ClaudeCliChatService.ts +0 -256
  72. package/src/services/CloudSync.ts +0 -168
  73. package/src/services/CostLedger.ts +0 -211
  74. package/src/services/Heartbeat.ts +0 -135
  75. package/src/services/LearningCollector.ts +0 -291
  76. package/src/services/OllamaInstaller.ts +0 -342
  77. package/src/services/VersionChecker.ts +0 -445
  78. package/src/services/index.ts +0 -57
  79. package/src/services/streaming/OpenAIEventAdapter.ts +0 -126
  80. package/src/services/streaming/RenderingProfile.ts +0 -90
  81. package/src/services/streaming/StreamEventParser.ts +0 -181
  82. package/src/services/streaming/ThrottledRenderer.ts +0 -139
  83. package/src/services/streaming/TranscriptBuffer.ts +0 -574
  84. package/src/services/streaming/eventStatusMap.ts +0 -52
  85. package/src/services/streaming/index.ts +0 -46
  86. package/src/services/streaming/renderFormatting.ts +0 -79
  87. package/src/services/streaming/types.ts +0 -234
  88. package/src/skills/SkillLoader.ts +0 -126
  89. package/src/skills/SkillRegistry.ts +0 -366
  90. package/src/skills/index.ts +0 -48
  91. package/src/skills/types.ts +0 -146
  92. package/src/slash-commands/billing.ts +0 -70
  93. package/src/slash-commands/build.ts +0 -413
  94. package/src/slash-commands/builtinCommands.ts +0 -2733
  95. package/src/slash-commands/clone.ts +0 -242
  96. package/src/slash-commands/council.ts +0 -125
  97. package/src/slash-commands/custom/CustomCommandExecutor.ts +0 -143
  98. package/src/slash-commands/custom/CustomCommandLoader.ts +0 -251
  99. package/src/slash-commands/custom/CustomCommandRegistry.ts +0 -144
  100. package/src/slash-commands/custom/index.ts +0 -7
  101. package/src/slash-commands/debate.ts +0 -254
  102. package/src/slash-commands/gmail.ts +0 -105
  103. package/src/slash-commands/index.ts +0 -388
  104. package/src/slash-commands/mcpCommand.ts +0 -205
  105. package/src/slash-commands/types.ts +0 -201
  106. package/src/store/index.ts +0 -76
  107. package/src/store/selectors.ts +0 -246
  108. package/src/store/slices/appSlice.ts +0 -205
  109. package/src/store/slices/commandSlice.ts +0 -115
  110. package/src/store/slices/configSlice.ts +0 -46
  111. package/src/store/slices/focusSlice.ts +0 -64
  112. package/src/store/slices/index.ts +0 -9
  113. package/src/store/slices/sessionSlice.ts +0 -424
  114. package/src/store/streaming-buffer.ts +0 -425
  115. package/src/store/test.ts +0 -296
  116. package/src/store/types.ts +0 -274
  117. package/src/store/vanilla.ts +0 -186
  118. package/src/tools/builtin/bash.ts +0 -236
  119. package/src/tools/builtin/council.ts +0 -105
  120. package/src/tools/builtin/edit.ts +0 -213
  121. package/src/tools/builtin/glob.ts +0 -136
  122. package/src/tools/builtin/grep.ts +0 -263
  123. package/src/tools/builtin/index.ts +0 -61
  124. package/src/tools/builtin/memory.ts +0 -66
  125. package/src/tools/builtin/read.ts +0 -168
  126. package/src/tools/builtin/skill.ts +0 -97
  127. package/src/tools/builtin/snapshot.ts +0 -40
  128. package/src/tools/builtin/task.ts +0 -106
  129. package/src/tools/builtin/write.ts +0 -134
  130. package/src/tools/createTool.ts +0 -221
  131. package/src/tools/execution/ExecutionPipeline.ts +0 -263
  132. package/src/tools/execution/index.ts +0 -40
  133. package/src/tools/execution/stages/CacheStage.ts +0 -131
  134. package/src/tools/execution/stages/ConfirmationStage.ts +0 -203
  135. package/src/tools/execution/stages/DiscoveryStage.ts +0 -46
  136. package/src/tools/execution/stages/ExecutionStage.ts +0 -48
  137. package/src/tools/execution/stages/FormattingStage.ts +0 -44
  138. package/src/tools/execution/stages/HookStage.ts +0 -72
  139. package/src/tools/execution/stages/PermissionStage.ts +0 -287
  140. package/src/tools/execution/stages/PostHookStage.ts +0 -71
  141. package/src/tools/execution/stages/index.ts +0 -12
  142. package/src/tools/execution/test.ts +0 -266
  143. package/src/tools/execution/types.ts +0 -273
  144. package/src/tools/index.ts +0 -81
  145. package/src/tools/registry.ts +0 -304
  146. package/src/tools/schemas.ts +0 -109
  147. package/src/tools/test.ts +0 -220
  148. package/src/tools/types.ts +0 -175
  149. package/src/tools/validation/PermissionChecker.ts +0 -242
  150. package/src/tools/validation/SensitiveFileDetector.ts +0 -210
  151. package/src/tools/validation/index.ts +0 -11
  152. package/src/ui/App.tsx +0 -166
  153. package/src/ui/components/AegisInterface.tsx +0 -484
  154. package/src/ui/components/common/ChatSearch.tsx +0 -150
  155. package/src/ui/components/common/ErrorBoundary.tsx +0 -82
  156. package/src/ui/components/common/ExitMessage.tsx +0 -120
  157. package/src/ui/components/common/LoadingIndicator.tsx +0 -49
  158. package/src/ui/components/common/index.ts +0 -6
  159. package/src/ui/components/dialog/ConfirmationPrompt.tsx +0 -208
  160. package/src/ui/components/dialog/InteractiveSelector.tsx +0 -149
  161. package/src/ui/components/dialog/SetupWizard.tsx +0 -297
  162. package/src/ui/components/dialog/UpdatePrompt.tsx +0 -155
  163. package/src/ui/components/dialog/index.ts +0 -8
  164. package/src/ui/components/index.ts +0 -28
  165. package/src/ui/components/input/CommandSuggestions.tsx +0 -139
  166. package/src/ui/components/input/CustomTextInput.tsx +0 -220
  167. package/src/ui/components/input/InputArea.tsx +0 -361
  168. package/src/ui/components/input/PromptSuggestions.tsx +0 -66
  169. package/src/ui/components/input/index.ts +0 -6
  170. package/src/ui/components/layout/ChatStatusBar.tsx +0 -90
  171. package/src/ui/components/layout/ContextBar.tsx +0 -79
  172. package/src/ui/components/layout/MessageArea.tsx +0 -96
  173. package/src/ui/components/layout/MessageList.tsx +0 -647
  174. package/src/ui/components/layout/MessageSeparator.tsx +0 -26
  175. package/src/ui/components/layout/WelcomeMessage.tsx +0 -93
  176. package/src/ui/components/layout/index.ts +0 -7
  177. package/src/ui/components/markdown/CodeHighlighter.tsx +0 -292
  178. package/src/ui/components/markdown/MessageRenderer.tsx +0 -1211
  179. package/src/ui/components/markdown/index.ts +0 -8
  180. package/src/ui/components/markdown/parser.ts +0 -336
  181. package/src/ui/components/markdown/types.ts +0 -66
  182. package/src/ui/focus/FocusManager.ts +0 -137
  183. package/src/ui/focus/index.ts +0 -13
  184. package/src/ui/focus/types.ts +0 -54
  185. package/src/ui/focus/useFocus.ts +0 -75
  186. package/src/ui/hooks/index.ts +0 -11
  187. package/src/ui/hooks/useAgent.ts +0 -284
  188. package/src/ui/hooks/useCommandHistory.ts +0 -87
  189. package/src/ui/hooks/useCommandProcessor.ts +0 -443
  190. package/src/ui/hooks/useConfirmation.ts +0 -99
  191. package/src/ui/hooks/useCtrlCHandler.ts +0 -100
  192. package/src/ui/hooks/useInputBuffer.ts +0 -122
  193. package/src/ui/hooks/useTerminalSize.ts +0 -68
  194. package/src/ui/hooks/useTerminalWidth.ts +0 -5
  195. package/src/ui/hooks/useWindowedList.ts +0 -118
  196. package/src/ui/render-debugger.ts +0 -621
  197. package/src/ui/test.ts +0 -189
  198. package/src/ui/themes/ThemeManager.ts +0 -332
  199. package/src/ui/themes/aegisTheme.ts +0 -87
  200. package/src/ui/themes/darkTheme.ts +0 -87
  201. package/src/ui/themes/defaultTheme.ts +0 -85
  202. package/src/ui/themes/index.ts +0 -10
  203. package/src/ui/themes/lightTheme.ts +0 -89
  204. package/src/ui/themes/popularThemes.ts +0 -187
  205. package/src/ui/themes/types.ts +0 -130
  206. package/src/utils/clipboard.ts +0 -48
  207. package/src/utils/debug.ts +0 -43
  208. package/src/utils/environment.ts +0 -68
  209. package/src/utils/index.ts +0 -10
@@ -1,115 +0,0 @@
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
- });
@@ -1,46 +0,0 @@
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
- });
@@ -1,64 +0,0 @@
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
- });
@@ -1,9 +0,0 @@
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';
@@ -1,424 +0,0 @@
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
- });