wave-agent-sdk 0.18.3 → 0.18.4
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.
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +0 -2
- package/dist/managers/MemoryRuleManager.d.ts +9 -0
- package/dist/managers/MemoryRuleManager.d.ts.map +1 -1
- package/dist/managers/MemoryRuleManager.js +18 -0
- package/dist/managers/aiManager.d.ts +1 -1
- package/dist/managers/aiManager.d.ts.map +1 -1
- package/dist/managers/aiManager.js +370 -345
- package/dist/managers/messageManager.d.ts +32 -13
- package/dist/managers/messageManager.d.ts.map +1 -1
- package/dist/managers/messageManager.js +82 -76
- package/dist/prompts/index.d.ts +10 -4
- package/dist/prompts/index.d.ts.map +1 -1
- package/dist/prompts/index.js +21 -20
- package/dist/services/aiService.d.ts +2 -1
- package/dist/services/aiService.d.ts.map +1 -1
- package/dist/services/aiService.js +37 -10
- package/dist/services/memory.d.ts +1 -0
- package/dist/services/memory.d.ts.map +1 -1
- package/dist/services/memory.js +35 -17
- package/dist/tools/agentTool.d.ts.map +1 -1
- package/dist/tools/agentTool.js +24 -2
- package/dist/tools/editTool.js +3 -3
- package/dist/tools/readTool.js +2 -2
- package/dist/tools/writeTool.js +2 -2
- package/dist/utils/containerSetup.d.ts.map +1 -1
- package/dist/utils/containerSetup.js +1 -0
- package/dist/utils/openaiClient.d.ts.map +1 -1
- package/dist/utils/openaiClient.js +28 -7
- package/dist/utils/taskReminder.d.ts +2 -3
- package/dist/utils/taskReminder.d.ts.map +1 -1
- package/dist/utils/taskReminder.js +7 -18
- package/package.json +1 -1
- package/scripts/install_ripgrep.js +21 -1
- package/src/agent.ts +0 -5
- package/src/managers/MemoryRuleManager.ts +23 -0
- package/src/managers/aiManager.ts +473 -434
- package/src/managers/messageManager.ts +99 -82
- package/src/prompts/index.ts +33 -24
- package/src/services/aiService.ts +39 -12
- package/src/services/memory.ts +34 -16
- package/src/tools/agentTool.ts +24 -2
- package/src/tools/editTool.ts +3 -3
- package/src/tools/readTool.ts +2 -2
- package/src/tools/writeTool.ts +2 -2
- package/src/utils/containerSetup.ts +1 -0
- package/src/utils/openaiClient.ts +35 -7
- package/src/utils/taskReminder.ts +7 -19
- package/vendor/ripgrep/linux-aarch64/rg +0 -0
- package/vendor/ripgrep/macos-aarch64/rg +0 -0
- package/vendor/ripgrep/macos-x86_64/rg +0 -0
- package/vendor/ripgrep/windows-aarch64/rg.exe +0 -0
- package/vendor/ripgrep/windows-x86_64/rg.exe +0 -0
|
@@ -2,6 +2,7 @@ import { UserMessageParams, type AgentToolBlockUpdateParams, type ToolBlockUpdat
|
|
|
2
2
|
import type { Message, Usage } from "../types/index.js";
|
|
3
3
|
import { SessionData } from "../services/session.js";
|
|
4
4
|
import { ChatCompletionMessageFunctionToolCall } from "openai/resources.js";
|
|
5
|
+
import type { MemoryRule } from "../types/memoryRule.js";
|
|
5
6
|
import { Container } from "../utils/container.js";
|
|
6
7
|
export interface MessageManagerCallbacks {
|
|
7
8
|
onMessagesChange?: (messages: Message[]) => void;
|
|
@@ -57,7 +58,8 @@ export declare class MessageManager {
|
|
|
57
58
|
private callbacks;
|
|
58
59
|
private transcriptPath;
|
|
59
60
|
private savedMessageCount;
|
|
60
|
-
private
|
|
61
|
+
private pendingFileReadTriggers;
|
|
62
|
+
private loadedRuleIds;
|
|
61
63
|
private recentFileReads;
|
|
62
64
|
private invokedSkills;
|
|
63
65
|
private sessionType;
|
|
@@ -74,15 +76,26 @@ export declare class MessageManager {
|
|
|
74
76
|
getLatestTotalTokens(): number;
|
|
75
77
|
getWorkdir(): string;
|
|
76
78
|
/**
|
|
77
|
-
*
|
|
79
|
+
* Process pending file read triggers: match against conditional rules,
|
|
80
|
+
* return rules not yet loaded (dedup via loadedRuleIds), mark them as loaded.
|
|
81
|
+
* Clears triggers after processing.
|
|
78
82
|
*/
|
|
79
|
-
|
|
83
|
+
processTriggeredRules(): MemoryRule[];
|
|
80
84
|
getSessionDir(): string;
|
|
81
85
|
getTranscriptPath(): string;
|
|
82
86
|
/**
|
|
83
|
-
* Get combined memory content (project memory + user memory +
|
|
87
|
+
* Get combined memory content (project memory + user memory + unconditional rules)
|
|
88
|
+
* Note: conditional rules are handled separately via processTriggeredRules().
|
|
84
89
|
*/
|
|
85
90
|
getCombinedMemory(): Promise<string>;
|
|
91
|
+
/**
|
|
92
|
+
* Get memory content for message-array injection:
|
|
93
|
+
* - prependContent: AGENTS.md + user memory + unconditional rules (for head injection)
|
|
94
|
+
* Conditional rules are handled separately via processTriggeredRules().
|
|
95
|
+
*/
|
|
96
|
+
getMemoryForInjection(): Promise<{
|
|
97
|
+
prependContent: string;
|
|
98
|
+
}>;
|
|
86
99
|
/**
|
|
87
100
|
* Compute the transcript path using cached encoded workdir
|
|
88
101
|
* Called during construction and when sessionId changes
|
|
@@ -94,17 +107,15 @@ export declare class MessageManager {
|
|
|
94
107
|
*/
|
|
95
108
|
private createSessionIfNeeded;
|
|
96
109
|
/**
|
|
97
|
-
*
|
|
98
|
-
|
|
99
|
-
touchFile(filePath: string): void;
|
|
100
|
-
/**
|
|
101
|
-
* Checks if a file has been read or edited in this conversation.
|
|
110
|
+
* Record a file path read via the Read tool, to be matched against
|
|
111
|
+
* conditional memory rules before the next AI call.
|
|
102
112
|
*/
|
|
103
|
-
|
|
113
|
+
triggerFileRead(filePath: string): void;
|
|
104
114
|
/**
|
|
105
|
-
*
|
|
115
|
+
* Check if a file has been read (for read-before-edit enforcement).
|
|
116
|
+
* Uses recentFileReads Map populated from Read tool execution.
|
|
106
117
|
*/
|
|
107
|
-
|
|
118
|
+
hasFileBeenRead(filePath: string): boolean;
|
|
108
119
|
setMessages(messages: Message[]): void;
|
|
109
120
|
/**
|
|
110
121
|
* Save current session
|
|
@@ -200,7 +211,6 @@ export declare class MessageManager {
|
|
|
200
211
|
* Rewrite the session file with the current messages.
|
|
201
212
|
*/
|
|
202
213
|
private rewriteSessionFile;
|
|
203
|
-
private extractPathsFromParams;
|
|
204
214
|
/**
|
|
205
215
|
* Extract file read contents from tool result blocks in a message.
|
|
206
216
|
*/
|
|
@@ -229,5 +239,14 @@ export declare class MessageManager {
|
|
|
229
239
|
* Clear all invoked skills (e.g., after compaction).
|
|
230
240
|
*/
|
|
231
241
|
clearInvokedSkills(): void;
|
|
242
|
+
/**
|
|
243
|
+
* Clear the loaded rule IDs set (e.g., after compaction resets context).
|
|
244
|
+
*/
|
|
245
|
+
clearLoadedRuleIds(): void;
|
|
246
|
+
/**
|
|
247
|
+
* Rebuild loadedRuleIds from persisted messages (session restore / post-compaction).
|
|
248
|
+
* Scans for <!-- rule: {ruleId} --> markers in user meta message content.
|
|
249
|
+
*/
|
|
250
|
+
rebuildLoadedRuleIds(): void;
|
|
232
251
|
}
|
|
233
252
|
//# sourceMappingURL=messageManager.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messageManager.d.ts","sourceRoot":"","sources":["../../src/managers/messageManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAYL,iBAAiB,EACjB,KAAK,0BAA0B,EAC/B,KAAK,6BAA6B,EAClC,KAAK,4BAA4B,EAElC,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAGxD,OAAO,EAIL,WAAW,EAEZ,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,qCAAqC,EAAE,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"messageManager.d.ts","sourceRoot":"","sources":["../../src/managers/messageManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAYL,iBAAiB,EACjB,KAAK,0BAA0B,EAC/B,KAAK,6BAA6B,EAClC,KAAK,4BAA4B,EAElC,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAGxD,OAAO,EAIL,WAAW,EAEZ,MAAM,wBAAwB,CAAC;A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kB,IAAI,IAAI;IAIjC;;OAEG;IACI,kBAAkB,IAAI,IAAI;IAIjC;;;OAGG;IACI,oBAAoB,IAAI,IAAI;CAcpC"}
|
|
@@ -3,11 +3,13 @@ import { getLastApiRounds } from "../utils/groupMessagesByApiRound.js";
|
|
|
3
3
|
import { join, isAbsolute, relative } from "path";
|
|
4
4
|
import { appendMessages, createSession, generateSessionId, SESSION_DIR, } from "../services/session.js";
|
|
5
5
|
import { pathEncoder } from "../utils/pathEncoder.js";
|
|
6
|
+
import { READ_TOOL_NAME } from "../constants/tools.js";
|
|
6
7
|
import { logger } from "../utils/globalLogger.js";
|
|
7
8
|
export class MessageManager {
|
|
8
9
|
constructor(container, options) {
|
|
9
10
|
this.container = container;
|
|
10
|
-
this.
|
|
11
|
+
this.pendingFileReadTriggers = new Set(); // File paths read via Read tool, awaiting rule matching
|
|
12
|
+
this.loadedRuleIds = new Set(); // IDs of conditional rules already injected as meta messages
|
|
11
13
|
this.recentFileReads = new Map(); // Track file read contents
|
|
12
14
|
this.invokedSkills = new Map(); // Track invoked skill names
|
|
13
15
|
this._usages = [];
|
|
@@ -59,10 +61,23 @@ export class MessageManager {
|
|
|
59
61
|
return this.workdir;
|
|
60
62
|
}
|
|
61
63
|
/**
|
|
62
|
-
*
|
|
64
|
+
* Process pending file read triggers: match against conditional rules,
|
|
65
|
+
* return rules not yet loaded (dedup via loadedRuleIds), mark them as loaded.
|
|
66
|
+
* Clears triggers after processing.
|
|
63
67
|
*/
|
|
64
|
-
|
|
65
|
-
|
|
68
|
+
processTriggeredRules() {
|
|
69
|
+
if (!this.memoryRuleManager || this.pendingFileReadTriggers.size === 0) {
|
|
70
|
+
this.pendingFileReadTriggers.clear();
|
|
71
|
+
return [];
|
|
72
|
+
}
|
|
73
|
+
const filePaths = Array.from(this.pendingFileReadTriggers);
|
|
74
|
+
this.pendingFileReadTriggers.clear();
|
|
75
|
+
const { conditional } = this.memoryRuleManager.getActiveRulesSplit(filePaths);
|
|
76
|
+
const newRules = conditional.filter((rule) => !this.loadedRuleIds.has(rule.id));
|
|
77
|
+
for (const rule of newRules) {
|
|
78
|
+
this.loadedRuleIds.add(rule.id);
|
|
79
|
+
}
|
|
80
|
+
return newRules;
|
|
66
81
|
}
|
|
67
82
|
getSessionDir() {
|
|
68
83
|
return SESSION_DIR;
|
|
@@ -71,20 +86,37 @@ export class MessageManager {
|
|
|
71
86
|
return this.transcriptPath;
|
|
72
87
|
}
|
|
73
88
|
/**
|
|
74
|
-
* Get combined memory content (project memory + user memory +
|
|
89
|
+
* Get combined memory content (project memory + user memory + unconditional rules)
|
|
90
|
+
* Note: conditional rules are handled separately via processTriggeredRules().
|
|
75
91
|
*/
|
|
76
92
|
async getCombinedMemory() {
|
|
77
93
|
let combined = await this.memoryService.getCombinedMemoryContent(this.workdir);
|
|
78
94
|
if (this.memoryRuleManager) {
|
|
79
|
-
const
|
|
80
|
-
|
|
81
|
-
if (activeRules.length > 0) {
|
|
95
|
+
const { unconditional } = this.memoryRuleManager.getActiveRulesSplit([]);
|
|
96
|
+
if (unconditional.length > 0) {
|
|
82
97
|
combined += "\n\n";
|
|
83
|
-
combined +=
|
|
98
|
+
combined += unconditional.map((r) => r.content).join("\n\n");
|
|
84
99
|
}
|
|
85
100
|
}
|
|
86
101
|
return combined;
|
|
87
102
|
}
|
|
103
|
+
/**
|
|
104
|
+
* Get memory content for message-array injection:
|
|
105
|
+
* - prependContent: AGENTS.md + user memory + unconditional rules (for head injection)
|
|
106
|
+
* Conditional rules are handled separately via processTriggeredRules().
|
|
107
|
+
*/
|
|
108
|
+
async getMemoryForInjection() {
|
|
109
|
+
const baseMemory = await this.memoryService.getCombinedMemoryContent(this.workdir);
|
|
110
|
+
let prependContent = baseMemory;
|
|
111
|
+
if (this.memoryRuleManager) {
|
|
112
|
+
const { unconditional } = this.memoryRuleManager.getActiveRulesSplit([]);
|
|
113
|
+
if (unconditional.length > 0) {
|
|
114
|
+
prependContent += "\n\n";
|
|
115
|
+
prependContent += unconditional.map((r) => r.content).join("\n\n");
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return { prependContent };
|
|
119
|
+
}
|
|
88
120
|
/**
|
|
89
121
|
* Compute the transcript path using cached encoded workdir
|
|
90
122
|
* Called during construction and when sessionId changes
|
|
@@ -118,55 +150,37 @@ export class MessageManager {
|
|
|
118
150
|
}
|
|
119
151
|
}
|
|
120
152
|
/**
|
|
121
|
-
*
|
|
153
|
+
* Record a file path read via the Read tool, to be matched against
|
|
154
|
+
* conditional memory rules before the next AI call.
|
|
122
155
|
*/
|
|
123
|
-
|
|
156
|
+
triggerFileRead(filePath) {
|
|
124
157
|
const normalizedPath = isAbsolute(filePath)
|
|
125
158
|
? relative(this.workdir, filePath)
|
|
126
159
|
: filePath;
|
|
127
|
-
this.
|
|
160
|
+
this.pendingFileReadTriggers.add(normalizedPath);
|
|
128
161
|
}
|
|
129
162
|
/**
|
|
130
|
-
*
|
|
163
|
+
* Check if a file has been read (for read-before-edit enforcement).
|
|
164
|
+
* Uses recentFileReads Map populated from Read tool execution.
|
|
131
165
|
*/
|
|
132
|
-
|
|
166
|
+
hasFileBeenRead(filePath) {
|
|
133
167
|
const normalizedPath = isAbsolute(filePath)
|
|
134
168
|
? relative(this.workdir, filePath)
|
|
135
169
|
: filePath;
|
|
136
|
-
return this.
|
|
137
|
-
|
|
138
|
-
/**
|
|
139
|
-
* Extracts and adds file paths from a message's tool blocks.
|
|
140
|
-
*/
|
|
141
|
-
addPathsFromMessage(message) {
|
|
142
|
-
for (const block of message.blocks) {
|
|
143
|
-
if (block.type === "tool" && block.parameters) {
|
|
144
|
-
try {
|
|
145
|
-
const params = JSON.parse(block.parameters);
|
|
146
|
-
const paths = this.extractPathsFromParams(params);
|
|
147
|
-
for (const p of paths) {
|
|
148
|
-
this.touchFile(p);
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
catch {
|
|
152
|
-
// Ignore parse errors
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
}
|
|
170
|
+
return (this.recentFileReads.has(normalizedPath) ||
|
|
171
|
+
this.recentFileReads.has(filePath));
|
|
156
172
|
}
|
|
157
173
|
setMessages(messages) {
|
|
158
174
|
const oldLength = this.messages.length;
|
|
159
175
|
this.messages = [...messages];
|
|
160
|
-
// Incrementally
|
|
176
|
+
// Incrementally extract metadata from new messages
|
|
161
177
|
const newMessages = messages.slice(oldLength);
|
|
162
178
|
for (const message of newMessages) {
|
|
163
|
-
this.addPathsFromMessage(message);
|
|
164
179
|
this.extractFileReadsFromMessage(message);
|
|
165
180
|
this.extractSkillInvocationsFromMessage(message);
|
|
166
181
|
}
|
|
167
182
|
// Also check if the last message was updated (common for tool blocks)
|
|
168
183
|
if (messages.length > 0 && messages.length === oldLength) {
|
|
169
|
-
this.addPathsFromMessage(messages[messages.length - 1]);
|
|
170
184
|
this.extractFileReadsFromMessage(messages[messages.length - 1]);
|
|
171
185
|
this.extractSkillInvocationsFromMessage(messages[messages.length - 1]);
|
|
172
186
|
}
|
|
@@ -227,6 +241,8 @@ export class MessageManager {
|
|
|
227
241
|
this.parentSessionId = sessionData.parentSessionId;
|
|
228
242
|
this.setMessages([...sessionData.messages]);
|
|
229
243
|
this.setlatestTotalTokens(sessionData.metadata.latestTotalTokens);
|
|
244
|
+
// Rebuild loadedRuleIds from persisted meta messages (session restore)
|
|
245
|
+
this.rebuildLoadedRuleIds();
|
|
230
246
|
// Set saved message count to the number of loaded messages since they're already saved
|
|
231
247
|
// This must be done after setSessionId which resets it to 0
|
|
232
248
|
this.savedMessageCount = sessionData.messages.length;
|
|
@@ -367,17 +383,9 @@ export class MessageManager {
|
|
|
367
383
|
this.parentSessionId = oldSessionId;
|
|
368
384
|
// Set new message list
|
|
369
385
|
this.setMessages(newMessages);
|
|
370
|
-
//
|
|
371
|
-
this.
|
|
372
|
-
|
|
373
|
-
this.addPathsFromMessage(message);
|
|
374
|
-
}
|
|
375
|
-
// Scan compactedContent for file mentions
|
|
376
|
-
const fileMentionRegex = /(?:^|\s)@([\w.\-/]+)/g;
|
|
377
|
-
let match;
|
|
378
|
-
while ((match = fileMentionRegex.exec(compactedContent)) !== null) {
|
|
379
|
-
this.touchFile(match[1]);
|
|
380
|
-
}
|
|
386
|
+
// Clear and rebuild loaded rule IDs from remaining meta messages
|
|
387
|
+
this.clearLoadedRuleIds();
|
|
388
|
+
this.rebuildLoadedRuleIds();
|
|
381
389
|
// Trigger compaction callback
|
|
382
390
|
this.callbacks.onCompactBlockAdded?.(compactedContent);
|
|
383
391
|
}
|
|
@@ -708,40 +716,13 @@ export class MessageManager {
|
|
|
708
716
|
logger?.error("Failed to rewrite session file:", error);
|
|
709
717
|
}
|
|
710
718
|
}
|
|
711
|
-
extractPathsFromParams(params) {
|
|
712
|
-
const paths = [];
|
|
713
|
-
if (typeof params !== "object" || params === null)
|
|
714
|
-
return paths;
|
|
715
|
-
// Common parameter names for file paths
|
|
716
|
-
const pathKeys = [
|
|
717
|
-
"path",
|
|
718
|
-
"filePath",
|
|
719
|
-
"file_path",
|
|
720
|
-
"target_file",
|
|
721
|
-
"targetFile",
|
|
722
|
-
];
|
|
723
|
-
for (const key of pathKeys) {
|
|
724
|
-
if (typeof params[key] === "string") {
|
|
725
|
-
paths.push(params[key]);
|
|
726
|
-
}
|
|
727
|
-
}
|
|
728
|
-
// Handle arrays of paths (e.g. in Glob or Grep results if we ever track those,
|
|
729
|
-
// but here we track inputs to tools)
|
|
730
|
-
if (Array.isArray(params.files)) {
|
|
731
|
-
for (const f of params.files) {
|
|
732
|
-
if (typeof f === "string")
|
|
733
|
-
paths.push(f);
|
|
734
|
-
}
|
|
735
|
-
}
|
|
736
|
-
return paths;
|
|
737
|
-
}
|
|
738
719
|
/**
|
|
739
720
|
* Extract file read contents from tool result blocks in a message.
|
|
740
721
|
*/
|
|
741
722
|
extractFileReadsFromMessage(message) {
|
|
742
723
|
for (const block of message.blocks) {
|
|
743
724
|
if (block.type === "tool" &&
|
|
744
|
-
block.name ===
|
|
725
|
+
block.name === READ_TOOL_NAME &&
|
|
745
726
|
block.stage === "end" &&
|
|
746
727
|
block.result &&
|
|
747
728
|
block.parameters) {
|
|
@@ -823,4 +804,29 @@ export class MessageManager {
|
|
|
823
804
|
clearInvokedSkills() {
|
|
824
805
|
this.invokedSkills.clear();
|
|
825
806
|
}
|
|
807
|
+
/**
|
|
808
|
+
* Clear the loaded rule IDs set (e.g., after compaction resets context).
|
|
809
|
+
*/
|
|
810
|
+
clearLoadedRuleIds() {
|
|
811
|
+
this.loadedRuleIds.clear();
|
|
812
|
+
}
|
|
813
|
+
/**
|
|
814
|
+
* Rebuild loadedRuleIds from persisted messages (session restore / post-compaction).
|
|
815
|
+
* Scans for <!-- rule: {ruleId} --> markers in user meta message content.
|
|
816
|
+
*/
|
|
817
|
+
rebuildLoadedRuleIds() {
|
|
818
|
+
for (const message of this.messages) {
|
|
819
|
+
if (message.role !== "user" || !message.isMeta)
|
|
820
|
+
continue;
|
|
821
|
+
for (const block of message.blocks) {
|
|
822
|
+
if (block.type === "text") {
|
|
823
|
+
const content = block.content;
|
|
824
|
+
const match = content.match(/<!-- rule: (.+?) -->/);
|
|
825
|
+
if (match) {
|
|
826
|
+
this.loadedRuleIds.add(match[1]);
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
}
|
|
826
832
|
}
|
package/dist/prompts/index.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { ToolPlugin } from "../tools/types.js";
|
|
2
|
-
import { PermissionMode } from "../types/permissions.js";
|
|
3
2
|
export declare const BASE_SYSTEM_PROMPT = "You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.";
|
|
4
3
|
export declare const DOING_TASKS_PROMPT = "# Doing tasks\n- The user will primarily request you to perform software engineering tasks. These may include solving bugs, adding new functionality, refactoring code, explaining code, and more. When given an unclear or generic instruction, consider it in the context of these software engineering tasks and the current working directory. For example, if the user asks you to change \"methodName\" to snake case, do not reply with just \"method_name\", instead find the method in the code and modify the code.\n- You are highly capable and often allow users to complete ambitious tasks that would otherwise be too complex or take too long. You should defer to user judgement about whether a task is too large to attempt.\n- If you notice the user's request is based on a misconception, or spot a bug adjacent to what they asked about, say so. You're a collaborator, not just an executor\u2014users benefit from your judgment, not just your compliance.\n- In general, do not propose changes to code you haven't read. If a user asks about or wants you to modify a file, read it first. Understand existing code before suggesting modifications.\n- Do not create files unless they're absolutely necessary for achieving your goal. Generally prefer editing an existing file to creating a new one, as this prevents file bloat and builds on existing work more effectively.\n- If an approach fails, diagnose why before switching tactics\u2014read the error, check your assumptions, try a focused fix. Don't retry the identical action blindly, but don't abandon a viable approach after a single failure either. Escalate to the user with AskUserQuestion only when you're genuinely stuck after investigation, not as a first response to friction.\n- Be careful not to introduce security vulnerabilities such as command injection, XSS, SQL injection, and other OWASP top 10 vulnerabilities. If you notice that you wrote insecure code, immediately fix it. Prioritize writing safe, secure, and correct code.\n- Avoid over-engineering. Only make changes that are directly requested or clearly necessary. Keep solutions simple and focused.\n - Don't add features, refactor code, or make \"improvements\" beyond what was asked. A bug fix doesn't need surrounding code cleaned up. A simple feature doesn't need extra configurability. Don't add docstrings, comments, or type annotations to code you didn't change. Only add comments where the logic isn't self-evident.\n - Don't add error handling, fallbacks, or validation for scenarios that can't happen. Trust internal code and framework guarantees. Only validate at system boundaries (user input, external APIs). Don't use feature flags or backwards-compatibility shims when you can just change the code.\n - Don't create helpers, utilities, or abstractions for one-time operations. Don't design for hypothetical future requirements. The right amount of complexity is what the task actually requires\u2014no speculative abstractions, but no half-finished implementations either. Three similar lines of code is better than a premature abstraction.\n- Avoid backwards-compatibility hacks like renaming unused _vars, re-exporting types, adding // removed comments for removed code, etc. If you are certain that something is unused, you can delete it completely.\n- Report outcomes faithfully: if tests fail, say so with the relevant output; if you did not run a verification step, say that rather than implying it succeeded. Never claim \"all tests pass\" when output shows failures, never suppress or simplify failing checks (tests, lints, type errors) to manufacture a green result, and never characterize incomplete or broken work as done. Equally, when a check did pass or a task is complete, state it plainly \u2014 do not hedge confirmed results with unnecessary disclaimers, downgrade finished work to \"partial,\" or re-verify things you already checked. The goal is an accurate report, not a defensive one.\n- Before reporting a task complete, verify it actually works: run the test, execute the script, check the output. Minimum complexity means no gold-plating, not skipping the finish line. If you can't verify (no test exists, can't run the code), say so explicitly rather than claiming success.";
|
|
5
4
|
export declare const EXECUTING_ACTIONS_PROMPT = "# Executing actions with care\n\nCarefully consider the reversibility and blast radius of actions. Generally you can freely take local, reversible actions like editing files or running tests. But for actions that are hard to reverse, affect shared systems beyond your local environment, or could otherwise be risky or destructive, check with the user before proceeding. The cost of pausing to confirm is low, while the cost of an unwanted action (lost work, unintended messages sent, deleted branches) can be very high. For actions like these, consider the context, the action, and user instructions, and by default transparently communicate the action and ask for confirmation before proceeding.\n\nExamples of the kind of risky actions that warrant user confirmation:\n- Destructive operations: deleting files/branches, dropping database tables, killing processes, rm -rf, overwriting uncommitted changes\n- Hard-to-reverse operations: force-pushing (can also overwrite upstream), git reset --hard, amending published commits, removing or downgrading packages/dependencies, modifying CI/CD pipelines\n- Actions visible to others or that affect shared state: pushing code, creating/closing/commenting on PRs or issues, sending messages (Slack, email, GitHub), posting to external services\n\nWhen you encounter an obstacle, do not use destructive actions as a shortcut to simply make it go away. For instance, try to identify root causes and fix underlying issues rather than bypassing safety checks (e.g. --no-verify). If you discover unexpected state like unfamiliar files, branches, or configuration, investigate before deleting or overwriting, as it may represent the user's in-progress work. For example, typically resolve merge conflicts rather than discarding changes. In short: only take risky actions carefully, and when in doubt, ask before acting. Follow both the spirit and letter of these instructions - measure twice, cut once.";
|
|
@@ -11,20 +10,27 @@ export declare const OUTPUT_EFFICIENCY_PROMPT = "# Output efficiency\n\nIMPORTAN
|
|
|
11
10
|
export declare const TONE_AND_STYLE_PROMPT = "# Tone and style\n\n- Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.\n- Your responses should be short and concise.\n- When referencing specific functions or pieces of code include the pattern file_path:line_number to allow the user to easily navigate to the source code location.\n- When referencing GitHub issues or pull requests, use the owner/repo#123 format (e.g. anthropics/claude-code#100) so they render as clickable links.\n- Do not use a colon before tool calls. Your tool calls may not be shown directly in the output, so text like \"Let me read the file:\" followed by a read tool call should just be \"Let me read the file.\" with a period.";
|
|
12
11
|
export declare function buildPlanModePrompt(planFilePath: string, planExists: boolean, isSubagent?: boolean): string;
|
|
13
12
|
export declare const DEFAULT_SYSTEM_PROMPT = "You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.";
|
|
13
|
+
/**
|
|
14
|
+
* A block of the system prompt with cacheability metadata.
|
|
15
|
+
* Static blocks (cacheable: true) get cache_control markers for Claude models.
|
|
16
|
+
* Dynamic blocks (cacheable: false) change per-turn and must not invalidate the cache.
|
|
17
|
+
*/
|
|
18
|
+
export interface SystemPromptBlock {
|
|
19
|
+
text: string;
|
|
20
|
+
cacheable: boolean;
|
|
21
|
+
}
|
|
14
22
|
export declare const COMPACT_MESSAGES_SYSTEM_PROMPT = "You are continuing work on a software engineering task. Write a detailed continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary.\n\nFirst, write your analysis in <analysis> tags as a thinking scratchpad:\n- Chronologically review the conversation\n- Identify user intents and goals\n- Note files read/modified, approaches tried, decisions made\n- Check for accuracy and completeness \u2014 ensure nothing critical is missing\n\nThen produce a structured summary in <summary> tags with these sections:\n\n## Primary Request and Intent\n- The user's core request and success criteria\n- Clarifications, constraints, or scope changes\n\n## Key Technical Concepts\n- Frameworks, libraries, patterns, architectural decisions\n\n## Files and Code Sections\n- Files read, modified, created (with full paths)\n- Critical code snippets (function signatures, bug fixes, key logic)\n- Focus on recent messages \u2014 include full code for important sections\n\n## Errors and Fixes\n- Errors encountered, root causes, how they were resolved\n- Approaches tried that didn't work and why\n\n## Problem Solving\n- Approach evolution, trade-offs considered, decisions made\n\n## All User Messages\n- Complete list of all user messages (non-tool content)\n- Preserve exact wording where load-bearing\n\n## Pending Tasks\n- Outstanding work, TODOs, unresolved questions\n\n## Current Work\n- What was being worked on at the time of summarization\n- Exact state of in-progress changes\n\n## Optional Next Step\n- Immediate next action needed\n- Include verbatim quotes from recent conversation if relevant\n\nBe concise but complete \u2014 include information that prevents duplicate work or repeated mistakes.\nRespond with text only. Do NOT call any tools.\nWrap your summary in <summary></summary> tags.";
|
|
15
23
|
export declare const WEB_CONTENT_SYSTEM_PROMPT = "You are a helpful assistant that extracts information from web content. The content is provided in Markdown format.";
|
|
16
24
|
export declare const BTW_SYSTEM_PROMPT = "You are a helpful assistant. Answer the user's side question based on the conversation history. \nDo NOT say things like \"Let me try...\", \"I'll now...\", \"Let me check...\", or promise to take any action. \nIf you don't know the answer, say so - do not offer to look it up or investigate. \nSimply answer the question with the information you have.";
|
|
17
25
|
export declare function buildSystemPrompt(basePrompt: string | undefined, tools: ToolPlugin[], options?: {
|
|
18
26
|
workdir?: string;
|
|
19
27
|
originalWorkdir?: string;
|
|
20
|
-
memory?: string;
|
|
21
28
|
language?: string;
|
|
22
29
|
isSubagent?: boolean;
|
|
23
30
|
autoMemory?: {
|
|
24
31
|
directory: string;
|
|
25
32
|
content: string;
|
|
26
33
|
};
|
|
27
|
-
|
|
28
|
-
}): string;
|
|
34
|
+
}): SystemPromptBlock[];
|
|
29
35
|
export declare function enhanceSystemPromptWithEnvDetails(existingSystemPrompt: string, workdir: string, originalWorkdir?: string): string;
|
|
30
36
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/prompts/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/prompts/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAoB/C,eAAO,MAAM,kBAAkB,oKAAoK,CAAC;AAEpM,eAAO,MAAM,kBAAkB,opIAcqQ,CAAC;AAErS,eAAO,MAAM,wBAAwB,25DASqmB,CAAC;AAE3oB,eAAO,MAAM,WAAW,ihDAWqH,CAAC;AAE9I;;GAEG;AACH,eAAO,MAAM,wBAAwB,+uBAWiH,CAAC;AAEvJ,eAAO,MAAM,qBAAqB,6sBAMuL,CAAC;AAE1N,wBAAgB,mBAAmB,CACjC,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,OAAO,EACnB,UAAU,GAAE,OAAe,GAC1B,MAAM,CAmFR;AAED,eAAO,MAAM,qBAAqB,oKAAqB,CAAC;AAExD;;;;GAIG;AACH,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,OAAO,CAAC;CACpB;AAED,eAAO,MAAM,8BAA8B,44DA8CI,CAAC;AAEhD,eAAO,MAAM,yBAAyB,wHAAwH,CAAC;AAC/J,eAAO,MAAM,iBAAiB,qWAG4B,CAAC;AAE3D,wBAAgB,iBAAiB,CAC/B,UAAU,EAAE,MAAM,GAAG,SAAS,EAC9B,KAAK,EAAE,UAAU,EAAE,EACnB,OAAO,GAAE;IACP,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,UAAU,CAAC,EAAE;QACX,SAAS,EAAE,MAAM,CAAC;QAClB,OAAO,EAAE,MAAM,CAAC;KACjB,CAAC;CACE,GACL,iBAAiB,EAAE,CA8DrB;AAED,wBAAgB,iCAAiC,CAC/C,oBAAoB,EAAE,MAAM,EAC5B,OAAO,EAAE,MAAM,EACf,eAAe,CAAC,EAAE,MAAM,GACvB,MAAM,CAkCR"}
|
package/dist/prompts/index.js
CHANGED
|
@@ -69,12 +69,12 @@ export function buildPlanModePrompt(planFilePath, planExists, isSubagent = false
|
|
|
69
69
|
? `A plan file already exists at ${planFilePath}. You can read it and make incremental edits using the ${EDIT_TOOL_NAME} tool if you need to.`
|
|
70
70
|
: `No plan file exists yet. You should create your plan at ${planFilePath} using the ${WRITE_TOOL_NAME} tool if you need to.`;
|
|
71
71
|
if (isSubagent) {
|
|
72
|
-
return `Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits, run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supercedes any other instructions you have received (for example, to make
|
|
72
|
+
return `Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits, run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supercedes any other instructions you have received (for example, to make tasks). Instead, you should:
|
|
73
73
|
|
|
74
74
|
## Plan File Info:
|
|
75
75
|
${planFileInfo}
|
|
76
76
|
You should build your plan incrementally by writing to or editing this file. NOTE that this is the only file you are allowed to edit - other than this you are only allowed to take READ-ONLY actions.
|
|
77
|
-
Answer the user's query comprehensively, using the ${ASK_USER_QUESTION_TOOL_NAME} tool if you need to ask the user clarifying questions. If you
|
|
77
|
+
Answer the user's query comprehensively, using the ${ASK_USER_QUESTION_TOOL_NAME} tool if you need to ask the user clarifying questions. If you use the ${ASK_USER_QUESTION_TOOL_NAME}, make sure to ask all clarifying questions you need to fully understand the user's intent before proceeding.`;
|
|
78
78
|
}
|
|
79
79
|
return `Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits (with the exception of the plan file mentioned below), run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supercedes any other instructions you have received.
|
|
80
80
|
|
|
@@ -126,14 +126,14 @@ In the agent prompt:
|
|
|
126
126
|
### Phase 3: Review
|
|
127
127
|
Goal: Review the plan(s) from Phase 2 and ensure alignment with the user's intentions.
|
|
128
128
|
1. Read the critical files identified by agents to deepen your understanding
|
|
129
|
-
2. Ensure
|
|
129
|
+
2. Ensure the plans align with the user's original request
|
|
130
130
|
3. Use ${ASK_USER_QUESTION_TOOL_NAME} to clarify any remaining questions with the user
|
|
131
131
|
|
|
132
132
|
### Phase 4: Final Plan
|
|
133
133
|
Goal: Write your final plan to the plan file (the only file you can edit).
|
|
134
134
|
- Begin with a **Context** section: explain why this change is being made — the problem or need it addresses, what prompted it, and the intended outcome
|
|
135
135
|
- Include only your recommended approach, not all alternatives
|
|
136
|
-
- Ensure
|
|
136
|
+
- Ensure the the plan file is concise enough to scan quickly, but detailed enough to execute effectively
|
|
137
137
|
- Include the paths of critical files to be modified
|
|
138
138
|
- Reference existing functions and utilities you found that should be reused, with their file paths
|
|
139
139
|
- Include a verification section describing how to test the changes end-to-end (run the code, use MCP tools, run tests)
|
|
@@ -200,19 +200,20 @@ Do NOT say things like "Let me try...", "I'll now...", "Let me check...", or pro
|
|
|
200
200
|
If you don't know the answer, say so - do not offer to look it up or investigate.
|
|
201
201
|
Simply answer the question with the information you have.`;
|
|
202
202
|
export function buildSystemPrompt(basePrompt, tools, options = {}) {
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
203
|
+
// --- Static block (cacheable) ---
|
|
204
|
+
let staticText = basePrompt || DEFAULT_SYSTEM_PROMPT;
|
|
205
|
+
staticText += `\n\n${DOING_TASKS_PROMPT}`;
|
|
206
|
+
staticText += `\n\n${EXECUTING_ACTIONS_PROMPT}`;
|
|
206
207
|
if (tools.length > 0) {
|
|
207
|
-
|
|
208
|
-
}
|
|
209
|
-
prompt += `\n\n${OUTPUT_EFFICIENCY_PROMPT}`;
|
|
210
|
-
prompt += `\n\n${TONE_AND_STYLE_PROMPT}`;
|
|
211
|
-
if (options.permissionMode === "dontAsk") {
|
|
212
|
-
prompt += `\n\n# Permission Mode\nThe user has selected the 'dontAsk' permission mode. In this mode, any restricted tool call that does not match a pre-approved rule in 'permissions.allow' or 'temporaryRules' will be automatically denied without prompting the user. You will receive a 'Permission denied' error for such calls. This is intended to prevent interruptions for untrusted tools while allowing pre-approved ones to run seamlessly.`;
|
|
208
|
+
staticText += `\n\n${TOOL_POLICY}`;
|
|
213
209
|
}
|
|
210
|
+
staticText += `\n\n${OUTPUT_EFFICIENCY_PROMPT}`;
|
|
211
|
+
staticText += `\n\n${TONE_AND_STYLE_PROMPT}`;
|
|
212
|
+
const blocks = [{ text: staticText, cacheable: true }];
|
|
213
|
+
// --- Dynamic block (not cacheable) ---
|
|
214
|
+
let dynamicText = "";
|
|
214
215
|
if (options.language) {
|
|
215
|
-
|
|
216
|
+
dynamicText += `\n\n# Language\nAlways respond in ${options.language}. Use ${options.language} for all explanations, comments, and communications with the user. Technical terms and code identifiers should remain in their original form.`;
|
|
216
217
|
}
|
|
217
218
|
if (options.workdir) {
|
|
218
219
|
const isGitRepo = isGitRepository(options.workdir);
|
|
@@ -226,7 +227,7 @@ export function buildSystemPrompt(basePrompt, tools, options = {}) {
|
|
|
226
227
|
? "bash"
|
|
227
228
|
: shell;
|
|
228
229
|
const worktreeSession = getCurrentWorktreeSession();
|
|
229
|
-
|
|
230
|
+
dynamicText += `
|
|
230
231
|
|
|
231
232
|
Here is useful information about the environment you are running in:
|
|
232
233
|
<env>
|
|
@@ -240,15 +241,15 @@ Today's date: ${today}
|
|
|
240
241
|
`;
|
|
241
242
|
}
|
|
242
243
|
if (options.autoMemory) {
|
|
243
|
-
|
|
244
|
+
dynamicText += `\n\n${buildAutoMemoryPrompt(options.autoMemory.directory)}`;
|
|
244
245
|
if (options.autoMemory.content.trim()) {
|
|
245
|
-
|
|
246
|
+
dynamicText += `\n\n## MEMORY.md\n\n${options.autoMemory.content}`;
|
|
246
247
|
}
|
|
247
248
|
}
|
|
248
|
-
if (
|
|
249
|
-
|
|
249
|
+
if (dynamicText.trim()) {
|
|
250
|
+
blocks.push({ text: dynamicText, cacheable: false });
|
|
250
251
|
}
|
|
251
|
-
return
|
|
252
|
+
return blocks;
|
|
252
253
|
}
|
|
253
254
|
export function enhanceSystemPromptWithEnvDetails(existingSystemPrompt, workdir, originalWorkdir) {
|
|
254
255
|
const isGitRepo = isGitRepository(workdir);
|
|
@@ -2,6 +2,7 @@ import { ChatCompletionMessageToolCall } from "openai/resources";
|
|
|
2
2
|
import { ChatCompletionMessageParam, ChatCompletionFunctionTool } from "openai/resources.js";
|
|
3
3
|
import type { GatewayConfig, ModelConfig } from "../types/index.js";
|
|
4
4
|
import { type ClaudeUsage } from "../utils/cacheControlUtils.js";
|
|
5
|
+
import { type SystemPromptBlock } from "../prompts/index.js";
|
|
5
6
|
/**
|
|
6
7
|
* Resets the rate limiter state. Primarily used for testing.
|
|
7
8
|
*/
|
|
@@ -15,7 +16,7 @@ export interface CallAgentOptions {
|
|
|
15
16
|
workdir: string;
|
|
16
17
|
tools?: ChatCompletionFunctionTool[];
|
|
17
18
|
model?: string;
|
|
18
|
-
systemPrompt?: string;
|
|
19
|
+
systemPrompt?: string | SystemPromptBlock[];
|
|
19
20
|
maxTokens?: number;
|
|
20
21
|
toolChoice?: "auto" | "none" | "required" | {
|
|
21
22
|
type: "function";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aiService.d.ts","sourceRoot":"","sources":["../../src/services/aiService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,6BAA6B,EAAE,MAAM,kBAAkB,CAAC;AACjE,OAAO,EAGL,0BAA0B,EAC1B,0BAA0B,EAE3B,MAAM,qBAAqB,CAAC;AAI7B,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEpE,OAAO,EAIL,KAAK,WAAW,
|
|
1
|
+
{"version":3,"file":"aiService.d.ts","sourceRoot":"","sources":["../../src/services/aiService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,6BAA6B,EAAE,MAAM,kBAAkB,CAAC;AACjE,OAAO,EAGL,0BAA0B,EAC1B,0BAA0B,EAE3B,MAAM,qBAAqB,CAAC;AAI7B,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEpE,OAAO,EAIL,KAAK,WAAW,EAEjB,MAAM,+BAA+B,CAAC;AAM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ptions: gatewayConfig.fetchOptions,
|
|
102
102
|
fetch: gatewayConfig.fetch,
|
|
103
103
|
});
|
|
104
|
-
//
|
|
105
|
-
const systemContent = systemPrompt || "";
|
|
106
|
-
// Add system prompt
|
|
107
|
-
const systemMessage = {
|
|
108
|
-
role: "system",
|
|
109
|
-
content: systemContent,
|
|
110
|
-
};
|
|
111
|
-
// ChatCompletionMessageParam[] is already in OpenAI format, add system prompt to the beginning
|
|
112
|
-
openaiMessages = [systemMessage, ...messages];
|
|
113
|
-
// Apply cache control for Claude models
|
|
104
|
+
// Determine model early (needed for system prompt construction)
|
|
114
105
|
const currentModel = model || modelConfig.model;
|
|
115
106
|
const resolvedMaxTokens = options.maxTokens ?? modelConfig.maxTokens;
|
|
107
|
+
// Build system message content
|
|
108
|
+
let systemMessage;
|
|
109
|
+
if (Array.isArray(systemPrompt)) {
|
|
110
|
+
if (supportsPromptCaching(currentModel)) {
|
|
111
|
+
// For Claude models, map blocks to content parts with cache_control on cacheable blocks
|
|
112
|
+
const contentParts = systemPrompt.map((block) => {
|
|
113
|
+
const part = {
|
|
114
|
+
type: "text",
|
|
115
|
+
text: block.text,
|
|
116
|
+
};
|
|
117
|
+
if (block.cacheable) {
|
|
118
|
+
part.cache_control = { type: "ephemeral" };
|
|
119
|
+
}
|
|
120
|
+
return part;
|
|
121
|
+
});
|
|
122
|
+
systemMessage = {
|
|
123
|
+
role: "system",
|
|
124
|
+
content: contentParts,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
// For non-Claude models, join blocks into a single string
|
|
129
|
+
systemMessage = {
|
|
130
|
+
role: "system",
|
|
131
|
+
content: systemPrompt.map((b) => b.text).join("\n\n"),
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
else {
|
|
136
|
+
systemMessage = {
|
|
137
|
+
role: "system",
|
|
138
|
+
content: systemPrompt || "",
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
// ChatCompletionMessageParam[] is already in OpenAI format, add system prompt to the beginning
|
|
142
|
+
openaiMessages = [systemMessage, ...messages];
|
|
116
143
|
processedTools = tools;
|
|
117
144
|
if (supportsPromptCaching(currentModel)) {
|
|
118
145
|
openaiMessages = transformMessagesForExplicitCache(openaiMessages, currentModel);
|
|
@@ -4,6 +4,7 @@ export declare class MemoryService {
|
|
|
4
4
|
private _cachedProjectMemory;
|
|
5
5
|
private _cachedUserMemory;
|
|
6
6
|
private _cachedCombinedMemory;
|
|
7
|
+
private _cachedAutoMemoryContent;
|
|
7
8
|
constructor(container: Container);
|
|
8
9
|
get cachedProjectMemory(): string;
|
|
9
10
|
get cachedUserMemory(): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../../src/services/memory.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAIlD,qBAAa,aAAa;
|
|
1
|
+
{"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../../src/services/memory.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAIlD,qBAAa,aAAa;IAMZ,OAAO,CAAC,SAAS;IAL7B,OAAO,CAAC,oBAAoB,CAAuB;IACnD,OAAO,CAAC,iBAAiB,CAAuB;IAChD,OAAO,CAAC,qBAAqB,CAAuB;IACpD,OAAO,CAAC,wBAAwB,CAAuB;gBAEnC,SAAS,EAAE,SAAS;IAExC,IAAW,mBAAmB,IAAI,MAAM,CAEvC;IAED,IAAW,gBAAgB,IAAI,MAAM,CAEpC;IAEM,UAAU,IAAI,IAAI;IAOzB;;;OAGG;IACH,sBAAsB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM;IAU/C;;OAEG;IACG,yBAAyB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA2B/D;;OAEG;IACG,oBAAoB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAsBtD,oBAAoB,IAAI,OAAO,CAAC,IAAI,CAAC;IA8BrC,oBAAoB,IAAI,OAAO,CAAC,MAAM,CAAC;IAyCvC,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IA6ChD,wBAAwB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;CAgBjE"}
|