@serjm/deepseek-code 0.3.1

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 (216) hide show
  1. package/CONTRIBUTING.md +73 -0
  2. package/README.md +194 -0
  3. package/README.ru.md +194 -0
  4. package/dist/api/index.d.ts +77 -0
  5. package/dist/api/index.d.ts.map +1 -0
  6. package/dist/api/index.js +263 -0
  7. package/dist/api/index.js.map +1 -0
  8. package/dist/cli/headless.d.ts +22 -0
  9. package/dist/cli/headless.d.ts.map +1 -0
  10. package/dist/cli/headless.js +122 -0
  11. package/dist/cli/headless.js.map +1 -0
  12. package/dist/cli/index.d.ts +3 -0
  13. package/dist/cli/index.d.ts.map +1 -0
  14. package/dist/cli/index.js +90 -0
  15. package/dist/cli/index.js.map +1 -0
  16. package/dist/cli/interactive.d.ts +18 -0
  17. package/dist/cli/interactive.d.ts.map +1 -0
  18. package/dist/cli/interactive.js +75 -0
  19. package/dist/cli/interactive.js.map +1 -0
  20. package/dist/commands/index.d.ts +30 -0
  21. package/dist/commands/index.d.ts.map +1 -0
  22. package/dist/commands/index.js +964 -0
  23. package/dist/commands/index.js.map +1 -0
  24. package/dist/config/defaults.d.ts +37 -0
  25. package/dist/config/defaults.d.ts.map +1 -0
  26. package/dist/config/defaults.js +39 -0
  27. package/dist/config/defaults.js.map +1 -0
  28. package/dist/config/loader.d.ts +4 -0
  29. package/dist/config/loader.d.ts.map +1 -0
  30. package/dist/config/loader.js +76 -0
  31. package/dist/config/loader.js.map +1 -0
  32. package/dist/core/agent-loop.d.ts +111 -0
  33. package/dist/core/agent-loop.d.ts.map +1 -0
  34. package/dist/core/agent-loop.js +485 -0
  35. package/dist/core/agent-loop.js.map +1 -0
  36. package/dist/core/checkpoint.d.ts +10 -0
  37. package/dist/core/checkpoint.d.ts.map +1 -0
  38. package/dist/core/checkpoint.js +83 -0
  39. package/dist/core/checkpoint.js.map +1 -0
  40. package/dist/core/extensions.d.ts +55 -0
  41. package/dist/core/extensions.d.ts.map +1 -0
  42. package/dist/core/extensions.js +113 -0
  43. package/dist/core/extensions.js.map +1 -0
  44. package/dist/core/git.d.ts +68 -0
  45. package/dist/core/git.d.ts.map +1 -0
  46. package/dist/core/git.js +148 -0
  47. package/dist/core/git.js.map +1 -0
  48. package/dist/core/hooks.d.ts +37 -0
  49. package/dist/core/hooks.d.ts.map +1 -0
  50. package/dist/core/hooks.js +77 -0
  51. package/dist/core/hooks.js.map +1 -0
  52. package/dist/core/i18n.d.ts +90 -0
  53. package/dist/core/i18n.d.ts.map +1 -0
  54. package/dist/core/i18n.js +253 -0
  55. package/dist/core/i18n.js.map +1 -0
  56. package/dist/core/lsp.d.ts +74 -0
  57. package/dist/core/lsp.d.ts.map +1 -0
  58. package/dist/core/lsp.js +239 -0
  59. package/dist/core/lsp.js.map +1 -0
  60. package/dist/core/mcp.d.ts +49 -0
  61. package/dist/core/mcp.d.ts.map +1 -0
  62. package/dist/core/mcp.js +195 -0
  63. package/dist/core/mcp.js.map +1 -0
  64. package/dist/core/memory.d.ts +38 -0
  65. package/dist/core/memory.d.ts.map +1 -0
  66. package/dist/core/memory.js +231 -0
  67. package/dist/core/memory.js.map +1 -0
  68. package/dist/core/metrics.d.ts +36 -0
  69. package/dist/core/metrics.d.ts.map +1 -0
  70. package/dist/core/metrics.js +111 -0
  71. package/dist/core/metrics.js.map +1 -0
  72. package/dist/core/review.d.ts +27 -0
  73. package/dist/core/review.d.ts.map +1 -0
  74. package/dist/core/review.js +201 -0
  75. package/dist/core/review.js.map +1 -0
  76. package/dist/core/sandbox.d.ts +52 -0
  77. package/dist/core/sandbox.d.ts.map +1 -0
  78. package/dist/core/sandbox.js +140 -0
  79. package/dist/core/sandbox.js.map +1 -0
  80. package/dist/core/scheduler.d.ts +56 -0
  81. package/dist/core/scheduler.d.ts.map +1 -0
  82. package/dist/core/scheduler.js +167 -0
  83. package/dist/core/scheduler.js.map +1 -0
  84. package/dist/core/session.d.ts +49 -0
  85. package/dist/core/session.d.ts.map +1 -0
  86. package/dist/core/session.js +127 -0
  87. package/dist/core/session.js.map +1 -0
  88. package/dist/core/skills.d.ts +36 -0
  89. package/dist/core/skills.d.ts.map +1 -0
  90. package/dist/core/skills.js +90 -0
  91. package/dist/core/skills.js.map +1 -0
  92. package/dist/core/subagent.d.ts +45 -0
  93. package/dist/core/subagent.d.ts.map +1 -0
  94. package/dist/core/subagent.js +130 -0
  95. package/dist/core/subagent.js.map +1 -0
  96. package/dist/core/themes.d.ts +35 -0
  97. package/dist/core/themes.d.ts.map +1 -0
  98. package/dist/core/themes.js +188 -0
  99. package/dist/core/themes.js.map +1 -0
  100. package/dist/tools/bash.d.ts +3 -0
  101. package/dist/tools/bash.d.ts.map +1 -0
  102. package/dist/tools/bash.js +92 -0
  103. package/dist/tools/bash.js.map +1 -0
  104. package/dist/tools/chrome-manager.d.ts +35 -0
  105. package/dist/tools/chrome-manager.d.ts.map +1 -0
  106. package/dist/tools/chrome-manager.js +163 -0
  107. package/dist/tools/chrome-manager.js.map +1 -0
  108. package/dist/tools/chrome.d.ts +78 -0
  109. package/dist/tools/chrome.d.ts.map +1 -0
  110. package/dist/tools/chrome.js +1058 -0
  111. package/dist/tools/chrome.js.map +1 -0
  112. package/dist/tools/edit.d.ts +3 -0
  113. package/dist/tools/edit.d.ts.map +1 -0
  114. package/dist/tools/edit.js +81 -0
  115. package/dist/tools/edit.js.map +1 -0
  116. package/dist/tools/glob.d.ts +3 -0
  117. package/dist/tools/glob.d.ts.map +1 -0
  118. package/dist/tools/glob.js +41 -0
  119. package/dist/tools/glob.js.map +1 -0
  120. package/dist/tools/grep.d.ts +3 -0
  121. package/dist/tools/grep.d.ts.map +1 -0
  122. package/dist/tools/grep.js +74 -0
  123. package/dist/tools/grep.js.map +1 -0
  124. package/dist/tools/path-safety.d.ts +3 -0
  125. package/dist/tools/path-safety.d.ts.map +1 -0
  126. package/dist/tools/path-safety.js +19 -0
  127. package/dist/tools/path-safety.js.map +1 -0
  128. package/dist/tools/read.d.ts +3 -0
  129. package/dist/tools/read.d.ts.map +1 -0
  130. package/dist/tools/read.js +58 -0
  131. package/dist/tools/read.js.map +1 -0
  132. package/dist/tools/registry.d.ts +4 -0
  133. package/dist/tools/registry.d.ts.map +1 -0
  134. package/dist/tools/registry.js +43 -0
  135. package/dist/tools/registry.js.map +1 -0
  136. package/dist/tools/types.d.ts +47 -0
  137. package/dist/tools/types.d.ts.map +1 -0
  138. package/dist/tools/types.js +90 -0
  139. package/dist/tools/types.js.map +1 -0
  140. package/dist/tools/write.d.ts +3 -0
  141. package/dist/tools/write.d.ts.map +1 -0
  142. package/dist/tools/write.js +51 -0
  143. package/dist/tools/write.js.map +1 -0
  144. package/dist/ui/activity-cards.d.ts +50 -0
  145. package/dist/ui/activity-cards.d.ts.map +1 -0
  146. package/dist/ui/activity-cards.js +185 -0
  147. package/dist/ui/activity-cards.js.map +1 -0
  148. package/dist/ui/app.d.ts +9 -0
  149. package/dist/ui/app.d.ts.map +1 -0
  150. package/dist/ui/app.js +852 -0
  151. package/dist/ui/app.js.map +1 -0
  152. package/dist/ui/chat-view.d.ts +10 -0
  153. package/dist/ui/chat-view.d.ts.map +1 -0
  154. package/dist/ui/chat-view.js +94 -0
  155. package/dist/ui/chat-view.js.map +1 -0
  156. package/dist/ui/error-boundary.d.ts +13 -0
  157. package/dist/ui/error-boundary.d.ts.map +1 -0
  158. package/dist/ui/error-boundary.js +16 -0
  159. package/dist/ui/error-boundary.js.map +1 -0
  160. package/dist/ui/fade-in.d.ts +8 -0
  161. package/dist/ui/fade-in.d.ts.map +1 -0
  162. package/dist/ui/fade-in.js +14 -0
  163. package/dist/ui/fade-in.js.map +1 -0
  164. package/dist/ui/input-bar.d.ts +16 -0
  165. package/dist/ui/input-bar.d.ts.map +1 -0
  166. package/dist/ui/input-bar.js +269 -0
  167. package/dist/ui/input-bar.js.map +1 -0
  168. package/dist/ui/markdown-view.d.ts +9 -0
  169. package/dist/ui/markdown-view.d.ts.map +1 -0
  170. package/dist/ui/markdown-view.js +240 -0
  171. package/dist/ui/markdown-view.js.map +1 -0
  172. package/dist/ui/matrix-rain.d.ts +2 -0
  173. package/dist/ui/matrix-rain.d.ts.map +1 -0
  174. package/dist/ui/matrix-rain.js +134 -0
  175. package/dist/ui/matrix-rain.js.map +1 -0
  176. package/dist/ui/reasoning-view.d.ts +12 -0
  177. package/dist/ui/reasoning-view.d.ts.map +1 -0
  178. package/dist/ui/reasoning-view.js +34 -0
  179. package/dist/ui/reasoning-view.js.map +1 -0
  180. package/dist/ui/results-panel.d.ts +11 -0
  181. package/dist/ui/results-panel.d.ts.map +1 -0
  182. package/dist/ui/results-panel.js +17 -0
  183. package/dist/ui/results-panel.js.map +1 -0
  184. package/dist/ui/setup-wizard.d.ts +30 -0
  185. package/dist/ui/setup-wizard.d.ts.map +1 -0
  186. package/dist/ui/setup-wizard.js +166 -0
  187. package/dist/ui/setup-wizard.js.map +1 -0
  188. package/dist/ui/status-bar.d.ts +14 -0
  189. package/dist/ui/status-bar.d.ts.map +1 -0
  190. package/dist/ui/status-bar.js +63 -0
  191. package/dist/ui/status-bar.js.map +1 -0
  192. package/dist/ui/tool-activity-card.d.ts +9 -0
  193. package/dist/ui/tool-activity-card.d.ts.map +1 -0
  194. package/dist/ui/tool-activity-card.js +172 -0
  195. package/dist/ui/tool-activity-card.js.map +1 -0
  196. package/dist/ui/tool-call-view.d.ts +9 -0
  197. package/dist/ui/tool-call-view.d.ts.map +1 -0
  198. package/dist/ui/tool-call-view.js +149 -0
  199. package/dist/ui/tool-call-view.js.map +1 -0
  200. package/dist/utils/clipboard.d.ts +6 -0
  201. package/dist/utils/clipboard.d.ts.map +1 -0
  202. package/dist/utils/clipboard.js +56 -0
  203. package/dist/utils/clipboard.js.map +1 -0
  204. package/dist/utils/ignore.d.ts +6 -0
  205. package/dist/utils/ignore.d.ts.map +1 -0
  206. package/dist/utils/ignore.js +40 -0
  207. package/dist/utils/ignore.js.map +1 -0
  208. package/dist/utils/logger.d.ts +4 -0
  209. package/dist/utils/logger.d.ts.map +1 -0
  210. package/dist/utils/logger.js +13 -0
  211. package/dist/utils/logger.js.map +1 -0
  212. package/dist/utils/string-width.d.ts +6 -0
  213. package/dist/utils/string-width.d.ts.map +1 -0
  214. package/dist/utils/string-width.js +37 -0
  215. package/dist/utils/string-width.js.map +1 -0
  216. package/package.json +68 -0
@@ -0,0 +1,485 @@
1
+ import { DeepSeekAPI } from '../api/index.js';
2
+ import { toOpenAITools, sanitizeArgs } from '../tools/types.js';
3
+ import { getDefaultTools, getToolsForMode } from '../tools/registry.js';
4
+ import { EventEmitter } from 'node:events';
5
+ import { i18n } from './i18n.js';
6
+ import { readFileSync, readdirSync, existsSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ import { platform, release, type } from 'node:os';
9
+ import { MetricsCollector } from './metrics.js';
10
+ import { hooksManager } from './hooks.js';
11
+ /**
12
+ * Build a dynamic system prompt with project context.
13
+ */
14
+ function buildSystemPrompt(cwd, approvalMode) {
15
+ const osInfo = `${type()} ${release()} (${platform()})`;
16
+ let projectInfo = '';
17
+ if (cwd) {
18
+ projectInfo += '\n## Project Context\n';
19
+ projectInfo += `- **Working directory:** \`${cwd}\`\n`;
20
+ projectInfo += `- **OS:** ${osInfo}\n`;
21
+ // Try to read package.json for project name and description
22
+ const pkgPath = join(cwd, 'package.json');
23
+ if (existsSync(pkgPath)) {
24
+ try {
25
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));
26
+ if (pkg.name)
27
+ projectInfo += `- **Project:** ${pkg.name}\n`;
28
+ if (pkg.version)
29
+ projectInfo += `- **Version:** ${pkg.version}\n`;
30
+ if (pkg.description)
31
+ projectInfo += `- **Description:** ${pkg.description}\n`;
32
+ }
33
+ catch {
34
+ // Ignore parse errors
35
+ }
36
+ }
37
+ // List top-level directory structure (non-recursive, max 30 entries)
38
+ try {
39
+ const entries = readdirSync(cwd, { withFileTypes: true });
40
+ const dirs = entries.filter(e => e.isDirectory()).map(e => ` 📁 ${e.name}/`).slice(0, 15);
41
+ const files = entries.filter(e => e.isFile()).map(e => ` 📄 ${e.name}`).slice(0, 15);
42
+ if (dirs.length > 0 || files.length > 0) {
43
+ projectInfo += '\n### Project Structure (top-level)\n';
44
+ projectInfo += [...dirs, ...files].join('\n');
45
+ if (entries.length > 30) {
46
+ projectInfo += `\n ... and ${entries.length - 30} more entries`;
47
+ }
48
+ }
49
+ }
50
+ catch {
51
+ // Ignore read errors
52
+ }
53
+ // Check for common config files
54
+ const configFiles = ['.gitignore', '.env', '.editorconfig', 'tsconfig.json', 'eslint.config.js', '.prettierrc'];
55
+ const foundConfigs = configFiles.filter(f => existsSync(join(cwd, f)));
56
+ if (foundConfigs.length > 0) {
57
+ projectInfo += '\n### Config Files\n';
58
+ projectInfo += foundConfigs.map(f => ` - \`${f}\``).join('\n');
59
+ }
60
+ }
61
+ // Build tools capability section from registry
62
+ const allTools = getDefaultTools();
63
+ const mode = approvalMode ?? 'default';
64
+ const modeTools = getToolsForMode(mode);
65
+ const modeToolNames = new Set(modeTools.map(t => t.tool.name));
66
+ const toolListLines = allTools.map(def => {
67
+ const t = def.tool;
68
+ const available = modeToolNames.has(t.name);
69
+ const note = available ? '' : ' (заблокирован в текущем режиме)';
70
+ return ` - \`${t.name}\` — ${t.description}${note}`;
71
+ });
72
+ const capabilitiesSection = [
73
+ `\n## Current Mode: ${mode}`,
74
+ '',
75
+ ...toolListLines,
76
+ ].join('\n');
77
+ return `You are DeepSeek Code, an AI-powered CLI agent for software development.
78
+
79
+ You have access to a set of tools that allow you to read, write, and edit files, run shell commands, search code, and use a real browser when rendered UI or web behavior matters.${projectInfo}${capabilitiesSection}
80
+
81
+ ## Guidelines
82
+ 1. **Plan first** — Before making changes, explore the codebase to understand the context.
83
+ 2. **Use the right tool** — Choose the most appropriate tool for each task.
84
+ 3. **Be precise** — When editing files, provide exact text matches.
85
+ 4. **Verify** — After changes, run tests or linting to ensure correctness.
86
+ 5. **Explain** — After completing a task, summarize what was done.
87
+
88
+ ## Tool Usage
89
+ - Read files with \`read_file\` before editing them
90
+ - Search with \`grep_search\` or \`glob\` to find relevant code
91
+ - Use \`run_shell_command\` to run build/test commands
92
+ - Create or overwrite files with \`write_file\`
93
+ - Make targeted edits with \`edit\` (prefer over write_file for small changes)
94
+ - Use \`chrome\` proactively for UI flows, localhost app validation, rendered DOM state, screenshots, console logs, and network inspection
95
+
96
+ When you need to run multiple tools, call them one at a time and wait for results before deciding the next step.
97
+
98
+ ## Important
99
+ - ALWAYS use absolute paths when referring to files. The project root is \`${cwd || 'the current working directory'}\`.
100
+ - When asked to audit or explore the project, start with \`glob\`, \`grep_search\`, and targeted reads to discover structure.
101
+ - If the task implies a browser or rendered UI check, do not wait for the user to explicitly say "open browser" before using \`chrome\`.
102
+ - Do NOT guess file paths — use \`glob\` or \`grep_search\` to discover them first.
103
+ - When asked about your capabilities, answer based on the tools listed in the "Current Mode" section above. Do NOT claim you lack tools that are listed there but blocked by mode — instead explain that the current mode restricts them.
104
+ - If the user asks "what tools do you have" or "what are your capabilities", refer to this prompt's tool list. If write_file or edit are listed as blocked, explain that they exist but are restricted in the current mode.
105
+ - **CRITICAL: Never claim an action was performed without an actual tool call.** Do not say "opening browser", "running eval", "taking screenshot", "passing captcha", "navigating to page", or any other action unless you have actually called the corresponding tool and received a result. If a tool call was not made, state honestly that it was not executed. If a tool is blocked by the current mode, do not promise to use it — explain that it is unavailable in this mode. If a captcha or site protection is encountered, do not claim to bypass it — stop and report the issue honestly.
106
+ - **CRITICAL: No post-factum reports without tool calls.** If Tool uses is 0 in the current response, do not claim "I checked the log", "I reviewed the previous run", "step X was successful", or any other retrospective analysis. You may only say: "I did not perform a check right now. Based on visible context I can assume..." Always separate findings into: **Verified** (confirmed by actual tool calls this turn), **Assumption** (inferred from visible context), **Not checked** (not examined this turn). Do not write "successful" for a step that was not actually executed or has no saved result. Use the \`/last-browser-test\` command to retrieve the last saved browser test report — do not reconstruct it from memory.`;
107
+ }
108
+ /**
109
+ * AgentLoop — manages the "request → tool call → result → next request" cycle.
110
+ *
111
+ * This is the core loop that turns DeepSeek Code from a chat wrapper
112
+ * into a real AI agent with tool access.
113
+ */
114
+ export class AgentLoop extends EventEmitter {
115
+ api;
116
+ tools;
117
+ options;
118
+ messages = [];
119
+ toolCallHistory = new Map();
120
+ metrics = new MetricsCollector();
121
+ iterationCount = 0;
122
+ constructor(config, options = {}) {
123
+ super();
124
+ this.api = new DeepSeekAPI(config);
125
+ const defaultSystemPrompt = buildSystemPrompt(options.cwd || process.cwd(), options.approvalMode);
126
+ this.options = {
127
+ maxIterations: 100,
128
+ toolTimeout: 30000,
129
+ approvalMode: 'default',
130
+ cwd: process.cwd(),
131
+ onToolCall: () => { },
132
+ onToolResult: () => { },
133
+ onStreamChunk: () => { },
134
+ onReasoningChunk: () => { },
135
+ onResponse: () => { },
136
+ onError: () => { },
137
+ onApprovalRequest: async () => true,
138
+ systemPrompt: defaultSystemPrompt,
139
+ signal: undefined,
140
+ ...options,
141
+ };
142
+ this.tools = getToolsForMode(this.options.approvalMode);
143
+ }
144
+ /** Get the current message history */
145
+ getMessages() {
146
+ return [...this.messages];
147
+ }
148
+ /** Get tool call history for the current session */
149
+ getToolCallHistory() {
150
+ return Array.from(this.toolCallHistory.values());
151
+ }
152
+ /** Get the current iteration count */
153
+ getIterationCount() {
154
+ return this.iterationCount;
155
+ }
156
+ /** Get the metrics collector for this session */
157
+ getMetrics() {
158
+ return this.metrics;
159
+ }
160
+ /**
161
+ * Set approval mode — updates which tools are available and rebuilds system prompt.
162
+ */
163
+ setApprovalMode(mode) {
164
+ this.options.approvalMode = mode;
165
+ this.tools = getToolsForMode(mode);
166
+ // Rebuild system prompt with updated mode info
167
+ this.options.systemPrompt = buildSystemPrompt(this.options.cwd, mode);
168
+ // Update the system message if it exists
169
+ const sysIdx = this.messages.findIndex(m => m.role === 'system');
170
+ if (sysIdx !== -1) {
171
+ this.messages[sysIdx] = { role: 'system', content: this.options.systemPrompt };
172
+ }
173
+ }
174
+ /**
175
+ * Run the agent loop with a user prompt.
176
+ * Returns the final assistant response text.
177
+ */
178
+ async run(prompt, history) {
179
+ this.iterationCount = 0;
180
+ this.toolCallHistory.clear();
181
+ // Start with system prompt
182
+ this.messages = [
183
+ { role: 'system', content: this.options.systemPrompt },
184
+ ...(history ?? []),
185
+ { role: 'user', content: prompt },
186
+ ];
187
+ return this.executeLoop();
188
+ }
189
+ /**
190
+ * Continue the loop with additional context (e.g., after a tool result was added externally).
191
+ */
192
+ async continueWithMessages(messages) {
193
+ this.messages = messages;
194
+ return this.executeLoop();
195
+ }
196
+ /**
197
+ * Execute the agent loop until a text response is received or max iterations reached.
198
+ * Uses streaming for real-time text output via onStreamChunk callback.
199
+ */
200
+ async executeLoop() {
201
+ const openAITools = toOpenAITools(this.tools);
202
+ // Execute hooks at start of loop
203
+ await hooksManager.execute('AgentLoopStart', {
204
+ event: 'AgentLoopStart',
205
+ projectDir: this.options.cwd,
206
+ messageCount: this.messages.length,
207
+ }).catch(() => { });
208
+ while (this.iterationCount < this.options.maxIterations) {
209
+ this.iterationCount++;
210
+ try {
211
+ // Use streaming chat to get real-time output
212
+ const stream = this.api.streamChat(this.messages, openAITools);
213
+ let responseContent = '';
214
+ let toolCalls = [];
215
+ // Check for cancellation
216
+ if (this.options.signal?.aborted) {
217
+ const cancelledMsg = i18n.t('agentCancelled');
218
+ this.messages.push({ role: 'assistant', content: cancelledMsg });
219
+ this.options.onResponse(cancelledMsg);
220
+ return cancelledMsg;
221
+ }
222
+ for await (const chunk of stream) {
223
+ // Check for cancellation during streaming
224
+ if (this.options.signal?.aborted) {
225
+ const cancelledMsg = i18n.t('agentCancelled');
226
+ this.messages.push({ role: 'assistant', content: cancelledMsg });
227
+ this.options.onResponse(cancelledMsg);
228
+ return cancelledMsg;
229
+ }
230
+ if (chunk.type === 'usage' && chunk.usage) {
231
+ this.metrics.recordTokens(chunk.usage.input, chunk.usage.output);
232
+ }
233
+ else if (chunk.type === 'reasoning') {
234
+ this.options.onReasoningChunk(chunk.content);
235
+ }
236
+ else if (chunk.type === 'text') {
237
+ responseContent += chunk.content;
238
+ this.options.onStreamChunk(chunk.content);
239
+ }
240
+ else if (chunk.type === 'tool_use') {
241
+ // Collect tool call from stream
242
+ if (chunk.toolCallId && chunk.toolName) {
243
+ toolCalls.push({
244
+ id: chunk.toolCallId,
245
+ type: 'function',
246
+ function: {
247
+ name: chunk.toolName,
248
+ arguments: JSON.stringify(chunk.toolInput ?? {}),
249
+ },
250
+ });
251
+ }
252
+ }
253
+ }
254
+ if (toolCalls.length === 0 && (!responseContent || responseContent.trim().length === 0)) {
255
+ // Streaming не дал результата — пробуем non-streaming как fallback
256
+ const fallbackResult = await this.api.chat(this.messages, openAITools);
257
+ if (fallbackResult.usage) {
258
+ this.metrics.recordTokens(fallbackResult.usage.input, fallbackResult.usage.output);
259
+ }
260
+ if (fallbackResult.toolCalls && fallbackResult.toolCalls.length > 0) {
261
+ toolCalls = fallbackResult.toolCalls;
262
+ responseContent = fallbackResult.content ?? '';
263
+ }
264
+ else if (fallbackResult.content && fallbackResult.content.trim().length > 0) {
265
+ responseContent = fallbackResult.content;
266
+ this.options.onStreamChunk(responseContent);
267
+ }
268
+ else {
269
+ const fallback = i18n.t('agentEmptyResponse');
270
+ this.messages.push({ role: 'assistant', content: fallback });
271
+ this.options.onResponse(fallback);
272
+ return fallback;
273
+ }
274
+ }
275
+ if (toolCalls.length > 0) {
276
+ // Add assistant message with tool calls to history
277
+ this.messages.push({
278
+ role: 'assistant',
279
+ content: responseContent,
280
+ tool_calls: toolCalls,
281
+ });
282
+ // Execute each tool call
283
+ for (const tc of toolCalls) {
284
+ const args = this.parseArguments(tc.function.arguments);
285
+ const toolCallEvent = {
286
+ id: tc.id,
287
+ name: tc.function.name,
288
+ arguments: args,
289
+ status: 'pending',
290
+ };
291
+ this.toolCallHistory.set(tc.id, toolCallEvent);
292
+ this.options.onToolCall(toolCallEvent);
293
+ // Check approval — skip only for 'never' (read-only tools)
294
+ const approval = this.getToolApproval(tc.function.name);
295
+ if (approval !== 'never') {
296
+ // If signal is already aborted, reject without asking
297
+ if (this.options.signal?.aborted) {
298
+ toolCallEvent.status = 'rejected';
299
+ this.toolCallHistory.set(tc.id, toolCallEvent);
300
+ this.messages.push({
301
+ role: 'tool',
302
+ content: `Tool call "${tc.function.name}" aborted (cancellation signal).`,
303
+ tool_call_id: tc.id,
304
+ });
305
+ continue;
306
+ }
307
+ const approved = await this.options.onApprovalRequest(tc.function.name, args, approval);
308
+ if (!approved) {
309
+ toolCallEvent.status = 'rejected';
310
+ this.toolCallHistory.set(tc.id, toolCallEvent);
311
+ this.messages.push({
312
+ role: 'tool',
313
+ content: `Tool call "${tc.function.name}" rejected by user.`,
314
+ tool_call_id: tc.id,
315
+ });
316
+ continue;
317
+ }
318
+ // Re-check signal after approval dialog (user may have taken long)
319
+ if (this.options.signal?.aborted) {
320
+ toolCallEvent.status = 'rejected';
321
+ this.toolCallHistory.set(tc.id, toolCallEvent);
322
+ this.messages.push({
323
+ role: 'tool',
324
+ content: `Tool call "${tc.function.name}" aborted after approval.`,
325
+ tool_call_id: tc.id,
326
+ });
327
+ continue;
328
+ }
329
+ }
330
+ // Execute the tool
331
+ toolCallEvent.status = 'running';
332
+ toolCallEvent.startedAt = Date.now();
333
+ this.toolCallHistory.set(tc.id, toolCallEvent);
334
+ this.metrics.recordToolCallStart(tc.function.name);
335
+ const startTime = toolCallEvent.startedAt;
336
+ try {
337
+ const toolResult = await this.executeTool(tc.function.name, args);
338
+ const duration = Date.now() - startTime;
339
+ this.metrics.recordToolCallEnd(tc.function.name, toolResult.success);
340
+ toolCallEvent.status = toolResult.success ? 'completed' : 'failed';
341
+ toolCallEvent.result = toolResult.output;
342
+ toolCallEvent.error = toolResult.error;
343
+ toolCallEvent.durationMs = duration;
344
+ this.toolCallHistory.set(tc.id, toolCallEvent);
345
+ this.options.onToolResult({
346
+ toolCallId: tc.id,
347
+ toolName: tc.function.name,
348
+ success: toolResult.success,
349
+ output: toolResult.output,
350
+ durationMs: duration,
351
+ error: toolResult.error,
352
+ });
353
+ // Add tool result to message history
354
+ this.messages.push({
355
+ role: 'tool',
356
+ content: this.formatToolResult(toolResult, duration),
357
+ tool_call_id: tc.id,
358
+ });
359
+ }
360
+ catch (err) {
361
+ const duration = Date.now() - startTime;
362
+ const errorMsg = err.message;
363
+ this.metrics.recordToolCallEnd(tc.function.name, false);
364
+ toolCallEvent.status = 'failed';
365
+ toolCallEvent.error = errorMsg;
366
+ toolCallEvent.durationMs = duration;
367
+ this.toolCallHistory.set(tc.id, toolCallEvent);
368
+ this.options.onToolResult({
369
+ toolCallId: tc.id,
370
+ toolName: tc.function.name,
371
+ success: false,
372
+ output: '',
373
+ durationMs: duration,
374
+ error: errorMsg,
375
+ });
376
+ this.messages.push({
377
+ role: 'tool',
378
+ content: `Tool "${tc.function.name}" execution error: ${errorMsg}`,
379
+ tool_call_id: tc.id,
380
+ });
381
+ }
382
+ }
383
+ // Continue loop — send results back to AI
384
+ continue;
385
+ }
386
+ // Text response — agent is done
387
+ if (!responseContent || responseContent.trim().length === 0) {
388
+ // DeepSeek API returned empty response — model may have "changed its mind", add fallback
389
+ const fallback = 'I have completed the requested actions. What else would you like me to do?';
390
+ this.messages.push({ role: 'assistant', content: fallback });
391
+ this.options.onResponse(fallback);
392
+ const summary = this.metrics.getSummary();
393
+ this.options.onStreamChunk(summary);
394
+ return fallback;
395
+ }
396
+ this.messages.push({ role: 'assistant', content: responseContent });
397
+ this.options.onResponse(responseContent);
398
+ // Output execution summary
399
+ const summary = this.metrics.getSummary();
400
+ this.options.onStreamChunk(summary);
401
+ return responseContent;
402
+ }
403
+ catch (err) {
404
+ const error = err;
405
+ this.options.onError(error);
406
+ throw error;
407
+ }
408
+ }
409
+ // Max iterations reached
410
+ const timeoutMsg = `Агент достиг максимального числа итераций (${this.options.maxIterations}). Задача может быть не завершена.`;
411
+ this.messages.push({ role: 'assistant', content: timeoutMsg });
412
+ this.options.onResponse(timeoutMsg);
413
+ return timeoutMsg;
414
+ }
415
+ /**
416
+ * Parse tool arguments from JSON string.
417
+ */
418
+ parseArguments(argsStr) {
419
+ try {
420
+ return JSON.parse(argsStr);
421
+ }
422
+ catch {
423
+ return {};
424
+ }
425
+ }
426
+ /**
427
+ * Get the approval requirement for a tool by name.
428
+ */
429
+ getToolApproval(toolName) {
430
+ const def = this.tools.find(t => t.tool.name === toolName);
431
+ return def?.approval ?? 'always';
432
+ }
433
+ /**
434
+ * Execute a tool by name with given arguments.
435
+ */
436
+ async executeTool(name, args) {
437
+ const def = this.tools.find(t => t.tool.name === name);
438
+ if (!def) {
439
+ return { success: false, output: '', error: `Неизвестный инструмент: "${name}"` };
440
+ }
441
+ // Sanitize arguments before execution
442
+ try {
443
+ args = sanitizeArgs(args, def.tool.parameters);
444
+ }
445
+ catch (err) {
446
+ return {
447
+ success: false,
448
+ output: '',
449
+ error: `Argument validation error for "${name}": ${err.message}`,
450
+ };
451
+ }
452
+ try {
453
+ const result = await def.tool.execute(args);
454
+ return {
455
+ success: result.success,
456
+ output: result.output,
457
+ error: result.error,
458
+ };
459
+ }
460
+ catch (err) {
461
+ return {
462
+ success: false,
463
+ output: '',
464
+ error: err.message,
465
+ };
466
+ }
467
+ }
468
+ /**
469
+ * Format tool result for the AI model.
470
+ * Truncate very long outputs to save tokens.
471
+ */
472
+ formatToolResult(result, durationMs) {
473
+ const maxOutputLength = 50000; // 50KB max for tool output
474
+ let output = result.output;
475
+ if (output.length > maxOutputLength) {
476
+ output = output.slice(0, maxOutputLength) +
477
+ `\n\n... [truncated ${output.length - maxOutputLength} chars]`;
478
+ }
479
+ if (!result.success) {
480
+ return `Tool execution error (${durationMs}ms):\n${result.error ?? result.output}`;
481
+ }
482
+ return `Tool output (${durationMs}ms):\n${output}`;
483
+ }
484
+ }
485
+ //# sourceMappingURL=agent-loop.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-loop.js","sourceRoot":"","sources":["../../src/core/agent-loop.ts"],"names":[],"m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@@ -0,0 +1,10 @@
1
+ export interface Checkpoint {
2
+ id: string;
3
+ timestamp: string;
4
+ message: string;
5
+ files: string[];
6
+ }
7
+ export declare function createCheckpoint(message: string): Promise<Checkpoint | null>;
8
+ export declare function listCheckpoints(): Promise<Checkpoint[]>;
9
+ export declare function restoreCheckpoint(id: string): Promise<boolean>;
10
+ //# sourceMappingURL=checkpoint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"checkpoint.d.ts","sourceRoot":"","sources":["../../src/core/checkpoint.ts"],"names":[],"mappings":"AAOA,MAAM,WAAW,UAAU;IACzB,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,EAAE,CAAC;CACjB;AAUD,wBAAsB,gBAAgB,CAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAgDnF;AAED,wBAAsB,eAAe,IAAK,OAAO,CAAC,UAAU,EAAE,CAAC,CAY9D;AAED,wBAAsB,iBAAiB,CAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAarE"}
@@ -0,0 +1,83 @@
1
+ import { execSync } from 'node:child_process';
2
+ import { readFile, writeFile, mkdir } from 'node:fs/promises';
3
+ import { existsSync } from 'node:fs';
4
+ import { homedir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { createHash } from 'node:crypto';
7
+ function getCheckpointsDir() {
8
+ return join(homedir(), '.deepseek-code', 'checkpoints');
9
+ }
10
+ function getProjectHash() {
11
+ return createHash('sha256').update(process.cwd()).digest('hex').slice(0, 16);
12
+ }
13
+ export async function createCheckpoint(message) {
14
+ // Only works in git repos
15
+ try {
16
+ execSync('git rev-parse --git-dir', { encoding: 'utf-8', stdio: 'pipe' });
17
+ }
18
+ catch {
19
+ return null;
20
+ }
21
+ const projectHash = getProjectHash();
22
+ const checkpointDir = join(getCheckpointsDir(), projectHash);
23
+ if (!existsSync(checkpointDir)) {
24
+ await mkdir(checkpointDir, { recursive: true });
25
+ }
26
+ const id = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
27
+ const timestamp = new Date().toISOString();
28
+ // Get list of changed files
29
+ let files = [];
30
+ try {
31
+ const status = execSync('git status --porcelain', { encoding: 'utf-8' });
32
+ files = status.split('\n')
33
+ .filter(Boolean)
34
+ .map(line => line.slice(3).trim());
35
+ }
36
+ catch { /* ignore */ }
37
+ // Create a patch file
38
+ try {
39
+ const patch = execSync('git diff', { encoding: 'utf-8', maxBuffer: 10 * 1024 * 1024 });
40
+ if (patch.trim()) {
41
+ await writeFile(join(checkpointDir, `${id}.patch`), patch, 'utf-8');
42
+ }
43
+ }
44
+ catch { /* ignore */ }
45
+ // Save metadata
46
+ const checkpoint = {
47
+ id,
48
+ timestamp,
49
+ message,
50
+ files,
51
+ };
52
+ // Append to checkpoint log
53
+ const logPath = join(checkpointDir, 'checkpoints.jsonl');
54
+ await writeFile(logPath, JSON.stringify(checkpoint) + '\n', { flag: 'a' });
55
+ return checkpoint;
56
+ }
57
+ export async function listCheckpoints() {
58
+ const projectHash = getProjectHash();
59
+ const checkpointDir = join(getCheckpointsDir(), projectHash);
60
+ const logPath = join(checkpointDir, 'checkpoints.jsonl');
61
+ if (!existsSync(logPath))
62
+ return [];
63
+ const content = await readFile(logPath, 'utf-8');
64
+ return content.split('\n')
65
+ .filter(Boolean)
66
+ .map(line => JSON.parse(line))
67
+ .reverse();
68
+ }
69
+ export async function restoreCheckpoint(id) {
70
+ const projectHash = getProjectHash();
71
+ const checkpointDir = join(getCheckpointsDir(), projectHash);
72
+ const patchPath = join(checkpointDir, `${id}.patch`);
73
+ if (!existsSync(patchPath))
74
+ return false;
75
+ try {
76
+ execSync(`git apply "${patchPath}"`, { encoding: 'utf-8', stdio: 'pipe' });
77
+ return true;
78
+ }
79
+ catch {
80
+ return false;
81
+ }
82
+ }
83
+ //# sourceMappingURL=checkpoint.js.map
@@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