forked from lessweb/deepcode-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprompt.ts
More file actions
560 lines (511 loc) · 19.4 KB
/
Copy pathprompt.ts
File metadata and controls
560 lines (511 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
import { execFileSync, execSync } from "child_process";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import ejs from "ejs";
import { fileURLToPath } from "url";
import type { SessionMessage } from "./session";
import { findGitBashPath, resolveShellPath } from "./common/shell-utils";
import { supportsMultimodal } from "./common/model-capabilities";
const COMPACT_PROMPT_BASE = `Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
- The user's explicit requests and intents
- Your approach to addressing the user's requests
- Key decisions, technical concepts and code patterns
- Specific details like:
- file names
- full code snippets
- function signatures
- file edits
- Errors that you ran into and how you fixed them
- Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.
Your summary should include the following sections:
1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
6. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
7. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
8. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.
If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.
Here's an example of how your output should be structured:
<example>
<analysis>
[Your thought process, ensuring all points are covered thoroughly and accurately]
</analysis>
<summary>
1. Primary Request and Intent:
[Detailed description]
2. Key Technical Concepts:
- [Concept 1]
- [Concept 2]
- [...]
3. Files and Code Sections:
- [File Name 1]
- [Summary of why this file is important]
- [Summary of the changes made to this file, if any]
- [Important Code Snippet]
- [File Name 2]
- [Important Code Snippet]
- [...]
4. Errors and fixes:
- [Detailed description of error 1]:
- [How you fixed the error]
- [User feedback on the error if any]
- [...]
5. Problem Solving:
[Description of solved problems and ongoing troubleshooting]
6. All user messages:
- [Detailed non tool use user message]
- [...]
7. Pending Tasks:
- [Task 1]
- [Task 2]
- [...]
8. Current Work:
[Precise description of current work]
9. Optional Next Step:
[Optional Next step to take]
</summary>`;
const SYSTEM_PROMPT_BASE = `你是名叫Deep Code的交互式CLI工具,帮助用户完成软件工程任务。 Use the instructions below and the tools available to you to assist the user.
重要:严禁编造任何非编程相关的 URL。对于编程链接,仅限使用:1) 用户提供的上下文;2) 你确定的官方文档主域名。在输出前,必须自查该链接是否存在于你的上下文记忆中;若不存在,请明确说明无法提供。`;
export type PromptToolOptions = {
model?: string;
webSearchEnabled?: boolean;
planMode?: boolean;
};
const DEFAULT_SKILL_TEMPLATES = ["agent-drift-guard.md", "plan-and-execute.md"];
function readToolDocs(extensionRoot: string, options: PromptToolOptions = {}): string {
const toolsDir = path.join(extensionRoot, "templates", "tools");
if (!fs.existsSync(toolsDir)) {
return "";
}
const entries = fs.readdirSync(toolsDir);
const docs = entries
.filter((entry) => entry.endsWith(".md") || entry.endsWith(".md.ejs"))
.sort()
.map((entry) => {
const fullPath = path.join(toolsDir, entry);
try {
const template = fs.readFileSync(fullPath, "utf8");
const content = entry.endsWith(".ejs")
? ejs.render(template, { supportsMultimodal: supportsMultimodal(options.model ?? "") })
: template;
return content.trim();
} catch {
return "";
}
})
.filter((content) => content.length > 0);
return docs.join("\n\n");
}
function readDefaultSkillDocs(extensionRoot: string): Array<{ name: string; content: string }> {
const skillsDir = path.join(extensionRoot, "templates", "skills");
return DEFAULT_SKILL_TEMPLATES.map((entry) => {
const fullPath = path.join(skillsDir, entry);
try {
return {
name: path.basename(entry, ".md"),
content: fs.readFileSync(fullPath, "utf8").trim(),
};
} catch {
return null;
}
}).filter((skill): skill is { name: string; content: string } => Boolean(skill?.content));
}
export function getDefaultSkillPrompt(): string {
const skillDocs = readDefaultSkillDocs(getExtensionRoot());
if (skillDocs.length === 0) {
return "";
}
const blocks = skillDocs.map(
(skill) => `<${skill.name}-skill>
${skill.content}
</${skill.name}-skill>`
);
return `Use the skill documents below to assist the user:\n${blocks.join("\n\n")}`;
}
function getCurrentDateAndModelPrompt(model?: string): string {
const date = new Date();
let prompt = `今天是${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日。随着对话的进行,时间在流逝。`;
prompt += model ? `\n当前LLM模型为${model},对话中可通过/model命令切换模型。` : "";
return prompt;
}
export function getSystemPrompt(_projectRoot: string, options: PromptToolOptions = {}): string {
const toolDocs = readToolDocs(getExtensionRoot(), options);
return toolDocs ? `${SYSTEM_PROMPT_BASE}\n\n# Available Tools\n\n${toolDocs}` : SYSTEM_PROMPT_BASE;
}
export function getCompactPrompt(sessionMessages: SessionMessage[]): string {
const jsonl = sessionMessages
.map((message) =>
JSON.stringify({
id: message.id,
role: message.role,
content: message.content,
contentParams: message.contentParams,
messageParams: message.messageParams,
createTime: message.createTime,
})
)
.join("\n");
return `${COMPACT_PROMPT_BASE}\n\nconversation below:\n\n\`\`\`jsonl\n${jsonl}\n\`\`\``;
}
export function getRuntimeContext(projectRoot: string, model?: string): string {
const uname = getUnameInfo();
const shellPath = getShellPathInfo();
const shellModeOpts = process.platform === "win32" ? { "shell mode": "git-bash" } : {};
const runtimeVersions = getRuntimeVersionInfo();
const env = {
"root path": projectRoot,
pwd: projectRoot,
homedir: os.homedir(),
"system info": uname,
"shell path": shellPath,
...shellModeOpts,
...runtimeVersions,
"command installed": {
ripgrep: checkToolInstalled("rg"),
jq: checkToolInstalled("jq"),
},
};
return `${getCurrentDateAndModelPrompt(model)}
# Local Workspace Environment
\`\`\`json
${JSON.stringify(env, null, 2)}
\`\`\``;
}
function checkToolInstalled(tool: string): boolean {
try {
if (process.platform === "win32") {
const bashPath = findGitBashPath();
execFileSync(bashPath, ["-lc", `command -v ${shellSingleQuote(tool)}`], {
encoding: "utf8",
stdio: "ignore",
windowsHide: true,
});
return true;
}
execSync(`command -v ${tool}`, { encoding: "utf8", stdio: "ignore" });
return true;
} catch {
return false;
}
}
function getShellPathInfo(): string {
try {
return resolveShellPath();
} catch (error) {
return error instanceof Error ? error.message : String(error);
}
}
function shellSingleQuote(value: string): string {
return `'${value.replace(/'/g, "'\"'\"'")}'`;
}
function getRuntimeVersionInfo(): Record<string, string> {
const versions: Record<string, string> = {};
const pythonVersion = getCommandVersion("python3", ["--version"]);
const nodeVersion = getCommandVersion("node", ["--version"]);
if (pythonVersion) {
versions["python3 version"] = pythonVersion.replace(/^Python\s+/i, "");
}
if (nodeVersion) {
versions["node version"] = nodeVersion;
}
return versions;
}
function getCommandVersion(command: string, args: string[]): string | null {
try {
const commandText = [command, ...args].map(shellSingleQuote).join(" ");
if (process.platform === "win32") {
return execFileSync(findGitBashPath(), ["-lc", `${commandText} 2>&1`], {
encoding: "utf8",
windowsHide: true,
}).trim();
}
return execSync(`${commandText} 2>&1`, { encoding: "utf8" }).trim();
} catch {
return null;
}
}
function getUnameInfo(): string {
try {
if (process.platform === "win32") {
return execFileSync(findGitBashPath(), ["-lc", "uname -a"], {
encoding: "utf8",
windowsHide: true,
}).trim();
}
return execSync("uname -a", { encoding: "utf8" }).trim();
} catch {
return `${os.type()} ${os.release()} ${os.arch()}`;
}
}
export function getExtensionRoot(): string {
// Prefer `__dirname` which is always available in the CJS bundle output.
// Fall back to `import.meta.url` for ESM test environments (tsx --test).
if (typeof __dirname !== "undefined") {
return path.resolve(__dirname, "..");
}
const currentFilePath = fileURLToPath(import.meta.url);
return path.resolve(path.dirname(currentFilePath), "..");
}
export type ToolDefinition = {
type: "function";
function: {
name: string;
description: string;
parameters: {
type: "object";
properties: Record<string, unknown>;
required?: string[];
additionalProperties?: boolean;
};
};
};
export function getTools(_options: PromptToolOptions = {}, externalTools: ToolDefinition[] = []): ToolDefinition[] {
const tools: ToolDefinition[] = [
{
type: "function",
function: {
name: "bash",
description: "Execute shell commands in a persistent bash session.",
parameters: {
type: "object",
properties: {
command: {
type: "string",
description: "The shell command to execute",
},
description: {
type: "string",
description:
'Clear, concise description of what this command does in active voice. Never use words like "complex" or "risk" in the description - just describe what it does.',
},
sideEffects: {
description:
'Permission scopes required by this bash command. Use [] only for commands that do not read, write, delete, or access the network. Use ["unknown"] when the effects cannot be classified safely.',
type: "array",
items: {
type: "string",
enum: [
"read-in-cwd",
"read-out-cwd",
"write-in-cwd",
"write-out-cwd",
"delete-in-cwd",
"delete-out-cwd",
"query-git-log",
"mutate-git-log",
"network",
"unknown",
],
},
uniqueItems: true,
},
},
required: ["command", "sideEffects"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "AskUserQuestion",
description:
"When the task has ambiguities or multiple implementation approaches, use this tool to pause execution and ask the user a question to get clarification or make a decision.",
parameters: {
type: "object",
properties: {
questions: {
type: "array",
description: "Questions to present to the user. Usually only one question is needed at a time.",
items: {
type: "object",
properties: {
question: {
type: "string",
description: "The question to ask the user.",
},
multiSelect: {
type: "boolean",
description: "Whether the user may choose multiple options.",
},
options: {
type: "array",
description: "A list of predefined options for the user to choose from.",
items: {
type: "object",
properties: {
label: {
type: "string",
description: "The display text for the option.",
},
description: {
type: "string",
description:
"A detailed explanation or hint about this option to help the user understand what happens if they choose it.",
},
},
required: ["label"],
},
},
},
required: ["question", "options"],
},
},
},
required: ["questions"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "UpdatePlan",
description:
"Update the current task plan. The plan argument must be the complete markdown task list to show as the latest progress state.",
parameters: {
type: "object",
properties: {
plan: {
type: "string",
description:
"The complete markdown task list, including task status markers such as [ ], [>], [x], and optional notes.",
},
explanation: {
type: "string",
description: "Optional short reason for changing the plan.",
},
},
required: ["plan"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "read",
description: "Read files from the filesystem (text, images, PDFs, notebooks).",
parameters: {
type: "object",
properties: {
file_path: {
type: "string",
description: "UNIX-style path to file",
},
offset: {
type: "number",
description: "Line number to start reading from",
},
limit: {
type: "number",
description: "Number of lines to read",
},
pages: {
type: "string",
description: 'Page range for PDF files (e.g., "1-5", "3", "10-20"). Only applicable to PDF files.',
},
},
required: ["file_path"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "write",
description: "Create files or overwrite them with a complete string payload. Prefer edit for existing files.",
parameters: {
type: "object",
properties: {
file_path: {
type: "string",
description: "Absolute path to file",
},
content: {
type: "string",
description: "Complete file content as a single string. Serialize JSON documents before writing.",
},
},
required: ["file_path", "content"],
additionalProperties: false,
},
},
},
{
type: "function",
function: {
name: "edit",
description: "Perform scoped string replacements in files.",
parameters: {
type: "object",
properties: {
snippet_id: {
type: "string",
description: "Required Read/Edit snippet_id.",
},
file_path: {
type: "string",
description: "Optional absolute path guard; must match snippet_id's file.",
},
old_string: {
type: "string",
description: "Exact text to replace inside snippet_id's scope",
},
new_string: {
type: "string",
description: "Replacement text (must differ from old_string)",
},
replace_all: {
type: "boolean",
description: "Replace all occurences of old_string (default false)",
default: false,
},
expected_occurrences: {
type: "number",
description: "Expected number of matches, especially useful as a safety check with replace_all",
},
},
required: ["snippet_id", "old_string", "new_string"],
additionalProperties: false,
},
},
},
];
tools.push({
type: "function",
function: {
name: "WebSearch",
description: "Perform web searching using a natural language query.",
parameters: {
type: "object",
properties: {
query: {
type: "string",
description:
"A search query phrased as a clear, specific natural language question or statement that includes key context.",
},
},
required: ["query"],
additionalProperties: false,
},
},
});
for (const tool of externalTools) {
tools.push(tool);
}
if (_options.planMode) {
const allowedTools = new Set(["read", "AskUserQuestion", "UpdatePlan", "WebSearch"]);
return tools.filter((tool) => allowedTools.has(tool.function.name));
}
return tools;
}