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
631 lines (543 loc) · 22.2 KB
/
Copy pathprompt.ts
File metadata and controls
631 lines (543 loc) · 22.2 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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
import { execFileSync, execSync } from "child_process";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { fileURLToPath } from "url";
import ejs from "ejs";
import type { SessionMessage } from "./session";
import { findGitBashPath, resolveShellPath } from "./common/shell-utils";
import { supportsMultimodal } from "./common/model-capabilities";
export const AGENT_DRIFT_GUARD_SKILL = `
---
name: agent-drift-guard
description: Detect and correct execution drift while working on user requests. Use when you are actively implementing, debugging, reviewing, or investigating and there is a risk of wandering beyond the user's goal, adding unrequested work, touching live systems, over-exploring, or ignoring repeated user boundary corrections. Especially useful during multi-step coding tasks, production-adjacent requests, ambiguous scopes, and anytime you should self-check whether it is still solving the requested problem.
---
# Agent Drift Guard
Keep execution tightly aligned with the user's actual request.
## Quick Start
Run this mental check before substantial work and again whenever the plan expands:
1. State the user's requested outcome in one sentence.
2. List explicit non-goals or boundaries the user has set.
3. Ask whether the next action directly advances the requested outcome.
4. If not, either cut it or pause to confirm.
## Drift Signals
Treat these as warning signs that execution may be drifting:
- Exploring broadly before opening the most relevant file, command, or artifact.
- Solving adjacent operational issues when the user asked only for code changes.
- Adding extra safeguards, scripts, docs, refactors, or cleanup that the user did not ask for.
- Reframing the task around what seems "better" instead of what was requested.
- Continuing with a broader plan after the user narrows the scope.
- Repeating searches or tool calls without increasing certainty.
- Mixing diagnosis, remediation, and feature work when the user asked for only one of them.
- Touching production-like state, external systems, or live data without explicit permission.
## Severity Levels
### Level 1: Mild Drift
Examples:
- One or two extra exploratory commands.
- Considering a broader solution but not acting on it yet.
- Briefly over-explaining instead of moving the task forward.
Response:
- Auto-correct silently.
- Narrow to the smallest next action.
- Do not interrupt the user.
### Level 2: Material Drift
Examples:
- Planning additional deliverables not requested.
- Writing helper scripts, migrations, docs, or tests outside the asked scope.
- Expanding from code changes into operational fixes.
- Continuing after the user has already corrected the scope once.
Response:
- Stop and realign internally first.
- If the broader action is avoidable, drop it and continue on scope.
- If the broader action has non-obvious tradeoffs, ask a brief confirmation question.
### Level 3: Boundary or Risk Violation
Examples:
- Modifying live systems, production data, external services, or user-owned state without being asked.
- Taking destructive or hard-to-reverse actions outside the requested scope.
- Ignoring repeated user instructions about what not to do.
Response:
- Pause before acting.
- Surface the exact boundary and ask for confirmation.
- Offer the smallest on-scope option first.
## Self-Check Loop
Use this loop during execution:
### Before the first meaningful action
Write down mentally:
- Requested outcome
- Allowed scope
- Forbidden scope
- Smallest useful next step
### After each non-trivial step
Ask:
- Did this step directly help deliver the requested outcome?
- Did I learn something that changes scope, or only implementation?
- Am I about to do more than the user asked?
### After a user correction
Treat the correction as a hard boundary update.
Then:
- Remove the old broader plan.
- Do not defend the discarded work.
- Continue from the narrowed scope.
- If needed, acknowledge briefly and move on.
## Decision Rules
Use these rules in order:
1. Prefer the most direct artifact first.
- Open the relevant file before scanning the whole repo.
- Inspect the specific failing path before designing a general framework.
2. Prefer the smallest complete fix.
- Solve the asked problem before improving related systems.
- Avoid bonus work unless it is required for correctness.
3. Prefer internal correction over user interruption.
- If you can shrink back to scope confidently, do it.
- Ask only when the next step changes deliverables, risk, or ownership.
4. Treat repeated user constraints as priority signals.
- A repeated instruction means your execution style is currently misaligned.
- Tighten scope immediately.
5. Separate categories of work.
- Code change, investigation, production remediation, cleanup, and documentation are distinct tasks unless the user explicitly combines them.
## Good Intervention Style
When you must pause, keep it short and specific:
- State the potential drift in one sentence.
- Name the tradeoff or boundary.
- Offer the smallest on-scope option first.
Example:
"Quick alignment check: I can keep this to the code fix only, or also add an ops cleanup step. I'll stick to the code fix unless you want both."
## Anti-Patterns
Do not:
- Create cleanup scripts, docs, or side tools just because they seem useful.
- Broaden the task after discovering a neighboring problem.
- Continue with a plan the user has already rejected.
- Justify drift with "best practice" when the user asked for a narrower deliverable.
- Hide extra work inside a larger patch.
## Final Check Before Responding
Before sending the final answer, verify:
- The delivered work matches the requested outcome.
- No extra deliverables were added without confirmation.
- Any assumptions are stated briefly.
- Suggested next steps are optional, not bundled into the completed work.
`;
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) 你确定的官方文档主域名。在输出前,必须自查该链接是否存在于你的上下文记忆中;若不存在,请明确说明无法提供。`;
type PromptToolOptions = {
model?: string;
webSearchEnabled?: boolean;
};
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 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);
const basePrompt = toolDocs ? `${SYSTEM_PROMPT_BASE}\n\n# Available Tools\n\n${toolDocs}` : SYSTEM_PROMPT_BASE;
return `${basePrompt}\n\n${getCurrentDateAndModelPrompt(options.model)}\n\n${getRuntimeContext(projectRoot)}`;
}
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\`\`\``;
}
function getRuntimeContext(projectRoot: 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 `# Local Workspace Environment\n\n\`\`\`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()}`;
}
}
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.',
},
},
required: ["command"],
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: "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: {
file_path: {
type: "string",
description: "Absolute path to file. Optional when snippet_id is provided.",
},
snippet_id: {
type: "string",
description:
"Snippet id returned by the Read or Edit tool to scope the search range after a partial read.",
},
old_string: {
type: "string",
description: "Exact text to replace inside the file or snippet 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: ["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);
}
return tools;
}