wave-agent-sdk 0.4.0 → 0.6.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.
- package/dist/agent.d.ts +42 -11
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +114 -115
- package/dist/constants/prompts.d.ts +18 -14
- package/dist/constants/prompts.d.ts.map +1 -1
- package/dist/constants/prompts.js +130 -54
- package/dist/constants/tools.d.ts +6 -3
- package/dist/constants/tools.d.ts.map +1 -1
- package/dist/constants/tools.js +6 -3
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/managers/MemoryRuleManager.js +1 -1
- package/dist/managers/aiManager.d.ts +5 -3
- package/dist/managers/aiManager.d.ts.map +1 -1
- package/dist/managers/aiManager.js +57 -20
- package/dist/managers/backgroundBashManager.d.ts.map +1 -1
- package/dist/managers/backgroundBashManager.js +1 -0
- package/dist/managers/backgroundTaskManager.d.ts +35 -0
- package/dist/managers/backgroundTaskManager.d.ts.map +1 -0
- package/dist/managers/backgroundTaskManager.js +255 -0
- package/dist/managers/foregroundTaskManager.d.ts +9 -0
- package/dist/managers/foregroundTaskManager.d.ts.map +1 -0
- package/dist/managers/foregroundTaskManager.js +21 -0
- package/dist/managers/liveConfigManager.d.ts +1 -1
- package/dist/managers/lspManager.d.ts.map +1 -1
- package/dist/managers/lspManager.js +3 -1
- package/dist/managers/mcpManager.d.ts.map +1 -1
- package/dist/managers/messageManager.d.ts +26 -12
- package/dist/managers/messageManager.d.ts.map +1 -1
- package/dist/managers/messageManager.js +138 -64
- package/dist/managers/permissionManager.d.ts.map +1 -1
- package/dist/managers/permissionManager.js +26 -22
- package/dist/managers/planManager.d.ts +1 -1
- package/dist/managers/planManager.d.ts.map +1 -1
- package/dist/managers/planManager.js +2 -2
- package/dist/managers/pluginManager.d.ts.map +1 -1
- package/dist/managers/pluginManager.js +3 -2
- package/dist/managers/slashCommandManager.d.ts +6 -0
- package/dist/managers/slashCommandManager.d.ts.map +1 -1
- package/dist/managers/slashCommandManager.js +8 -2
- package/dist/managers/subagentManager.d.ts +15 -2
- package/dist/managers/subagentManager.d.ts.map +1 -1
- package/dist/managers/subagentManager.js +153 -39
- package/dist/managers/toolManager.d.ts +18 -1
- package/dist/managers/toolManager.d.ts.map +1 -1
- package/dist/managers/toolManager.js +29 -5
- package/dist/services/GitService.d.ts.map +1 -1
- package/dist/services/GitService.js +6 -2
- package/dist/services/MarketplaceService.d.ts +2 -2
- package/dist/services/MarketplaceService.d.ts.map +1 -1
- package/dist/services/MarketplaceService.js +18 -11
- package/dist/services/MemoryRuleService.d.ts +1 -1
- package/dist/services/MemoryRuleService.d.ts.map +1 -1
- package/dist/services/MemoryRuleService.js +13 -2
- package/dist/services/aiService.d.ts +0 -1
- package/dist/services/aiService.d.ts.map +1 -1
- package/dist/services/aiService.js +4 -140
- package/dist/services/memory.d.ts +0 -3
- package/dist/services/memory.d.ts.map +1 -1
- package/dist/services/memory.js +1 -60
- package/dist/services/session.d.ts +15 -1
- package/dist/services/session.d.ts.map +1 -1
- package/dist/services/session.js +57 -1
- package/dist/services/taskManager.d.ts +21 -0
- package/dist/services/taskManager.d.ts.map +1 -0
- package/dist/services/taskManager.js +158 -0
- package/dist/tools/askUserQuestion.d.ts.map +1 -1
- package/dist/tools/askUserQuestion.js +39 -25
- package/dist/tools/bashTool.d.ts +0 -8
- package/dist/tools/bashTool.d.ts.map +1 -1
- package/dist/tools/bashTool.js +48 -172
- package/dist/tools/editTool.d.ts.map +1 -1
- package/dist/tools/editTool.js +8 -6
- package/dist/tools/exitPlanMode.d.ts.map +1 -1
- package/dist/tools/exitPlanMode.js +25 -1
- package/dist/tools/globTool.d.ts.map +1 -1
- package/dist/tools/globTool.js +8 -2
- package/dist/tools/grepTool.d.ts.map +1 -1
- package/dist/tools/grepTool.js +17 -6
- package/dist/tools/lsTool.d.ts.map +1 -1
- package/dist/tools/lsTool.js +3 -1
- package/dist/tools/multiEditTool.d.ts.map +1 -1
- package/dist/tools/multiEditTool.js +7 -6
- package/dist/tools/readTool.d.ts.map +1 -1
- package/dist/tools/readTool.js +16 -1
- package/dist/tools/taskManagementTools.d.ts +6 -0
- package/dist/tools/taskManagementTools.d.ts.map +1 -0
- package/dist/tools/taskManagementTools.js +453 -0
- package/dist/tools/taskOutputTool.d.ts +3 -0
- package/dist/tools/taskOutputTool.d.ts.map +1 -0
- package/dist/tools/taskOutputTool.js +173 -0
- package/dist/tools/taskStopTool.d.ts +3 -0
- package/dist/tools/taskStopTool.d.ts.map +1 -0
- package/dist/tools/taskStopTool.js +71 -0
- package/dist/tools/taskTool.d.ts.map +1 -1
- package/dist/tools/taskTool.js +110 -63
- package/dist/tools/types.d.ts +12 -0
- package/dist/tools/types.d.ts.map +1 -1
- package/dist/tools/writeTool.d.ts.map +1 -1
- package/dist/tools/writeTool.js +9 -1
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js +1 -0
- package/dist/types/marketplace.d.ts +1 -0
- package/dist/types/marketplace.d.ts.map +1 -1
- package/dist/types/messaging.d.ts +3 -8
- package/dist/types/messaging.d.ts.map +1 -1
- package/dist/types/processes.d.ts +29 -4
- package/dist/types/processes.d.ts.map +1 -1
- package/dist/types/tasks.d.ts +13 -0
- package/dist/types/tasks.d.ts.map +1 -0
- package/dist/types/tasks.js +1 -0
- package/dist/types/tools.d.ts +4 -1
- package/dist/types/tools.d.ts.map +1 -1
- package/dist/utils/builtinSubagents.d.ts.map +1 -1
- package/dist/utils/builtinSubagents.js +38 -1
- package/dist/utils/cacheControlUtils.d.ts.map +1 -1
- package/dist/utils/cacheControlUtils.js +18 -12
- package/dist/utils/constants.d.ts +0 -4
- package/dist/utils/constants.d.ts.map +1 -1
- package/dist/utils/constants.js +0 -4
- package/dist/utils/convertMessagesForAPI.js +2 -2
- package/dist/utils/editUtils.d.ts +2 -11
- package/dist/utils/editUtils.d.ts.map +1 -1
- package/dist/utils/editUtils.js +52 -79
- package/dist/utils/messageOperations.d.ts +5 -36
- package/dist/utils/messageOperations.d.ts.map +1 -1
- package/dist/utils/messageOperations.js +9 -98
- package/dist/utils/nameGenerator.d.ts +1 -1
- package/dist/utils/nameGenerator.d.ts.map +1 -1
- package/dist/utils/nameGenerator.js +19 -3
- package/package.json +5 -5
- package/src/agent.ts +157 -134
- package/src/constants/prompts.ts +156 -65
- package/src/constants/tools.ts +6 -3
- package/src/index.ts +1 -0
- package/src/managers/MemoryRuleManager.ts +1 -1
- package/src/managers/aiManager.ts +77 -35
- package/src/managers/backgroundBashManager.ts +1 -0
- package/src/managers/backgroundTaskManager.ts +305 -0
- package/src/managers/foregroundTaskManager.ts +27 -0
- package/src/managers/lspManager.ts +3 -1
- package/src/managers/mcpManager.ts +6 -3
- package/src/managers/messageManager.ts +185 -75
- package/src/managers/permissionManager.ts +33 -28
- package/src/managers/planManager.ts +2 -2
- package/src/managers/pluginManager.ts +4 -3
- package/src/managers/slashCommandManager.ts +15 -2
- package/src/managers/subagentManager.ts +194 -35
- package/src/managers/toolManager.ts +48 -6
- package/src/services/GitService.ts +6 -2
- package/src/services/MarketplaceService.ts +30 -12
- package/src/services/MemoryRuleService.ts +18 -6
- package/src/services/aiService.ts +3 -145
- package/src/services/memory.ts +1 -73
- package/src/services/session.ts +73 -0
- package/src/services/taskManager.ts +188 -0
- package/src/tools/askUserQuestion.ts +51 -29
- package/src/tools/bashTool.ts +63 -196
- package/src/tools/editTool.ts +9 -18
- package/src/tools/exitPlanMode.ts +26 -2
- package/src/tools/globTool.ts +10 -2
- package/src/tools/grepTool.ts +17 -6
- package/src/tools/lsTool.ts +3 -1
- package/src/tools/multiEditTool.ts +7 -18
- package/src/tools/readTool.ts +17 -1
- package/src/tools/taskManagementTools.ts +498 -0
- package/src/tools/taskOutputTool.ts +196 -0
- package/src/tools/taskStopTool.ts +78 -0
- package/src/tools/taskTool.ts +136 -74
- package/src/tools/types.ts +13 -0
- package/src/tools/writeTool.ts +9 -2
- package/src/types/index.ts +1 -0
- package/src/types/marketplace.ts +1 -0
- package/src/types/messaging.ts +2 -9
- package/src/types/processes.ts +39 -4
- package/src/types/tasks.ts +13 -0
- package/src/types/tools.ts +4 -1
- package/src/utils/builtinSubagents.ts +47 -1
- package/src/utils/cacheControlUtils.ts +26 -18
- package/src/utils/constants.ts +0 -5
- package/src/utils/convertMessagesForAPI.ts +2 -2
- package/src/utils/editUtils.ts +65 -103
- package/src/utils/messageOperations.ts +12 -136
- package/src/utils/nameGenerator.ts +20 -3
- package/dist/tools/todoWriteTool.d.ts +0 -6
- package/dist/tools/todoWriteTool.d.ts.map +0 -1
- package/dist/tools/todoWriteTool.js +0 -220
- package/src/tools/todoWriteTool.ts +0 -257
|
@@ -21,10 +21,7 @@ import * as os from "os";
|
|
|
21
21
|
import * as fs from "fs";
|
|
22
22
|
import * as path from "path";
|
|
23
23
|
|
|
24
|
-
import {
|
|
25
|
-
DEFAULT_SYSTEM_PROMPT,
|
|
26
|
-
buildSystemPrompt,
|
|
27
|
-
} from "../constants/prompts.js";
|
|
24
|
+
import { COMPRESS_MESSAGES_SYSTEM_PROMPT } from "../constants/prompts.js";
|
|
28
25
|
|
|
29
26
|
/**
|
|
30
27
|
* Interface for debug data saved during 400 errors
|
|
@@ -66,28 +63,6 @@ interface ErrorData {
|
|
|
66
63
|
* Instead of parsing JSON, we use the raw chunk for efficient streaming
|
|
67
64
|
*/
|
|
68
65
|
|
|
69
|
-
/**
|
|
70
|
-
* Check if a directory is a git repository
|
|
71
|
-
* @param dirPath Directory path to check
|
|
72
|
-
* @returns "Yes" if it's a git repo, "No" otherwise
|
|
73
|
-
*/
|
|
74
|
-
function isGitRepository(dirPath: string): string {
|
|
75
|
-
try {
|
|
76
|
-
// Check if .git directory exists in current directory or any parent directory
|
|
77
|
-
let currentPath = path.resolve(dirPath);
|
|
78
|
-
while (currentPath !== path.dirname(currentPath)) {
|
|
79
|
-
const gitPath = path.join(currentPath, ".git");
|
|
80
|
-
if (fs.existsSync(gitPath)) {
|
|
81
|
-
return "Yes";
|
|
82
|
-
}
|
|
83
|
-
currentPath = path.dirname(currentPath);
|
|
84
|
-
}
|
|
85
|
-
return "No";
|
|
86
|
-
} catch {
|
|
87
|
-
return "No";
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
66
|
/**
|
|
92
67
|
* OpenAI model configuration type, based on OpenAI parameters but excluding messages
|
|
93
68
|
*/
|
|
@@ -144,7 +119,6 @@ export interface CallAgentOptions {
|
|
|
144
119
|
messages: ChatCompletionMessageParam[];
|
|
145
120
|
sessionId?: string;
|
|
146
121
|
abortSignal?: AbortSignal;
|
|
147
|
-
memory?: string; // Memory content parameter, content read from AGENTS.md
|
|
148
122
|
workdir: string; // Current working directory
|
|
149
123
|
tools?: ChatCompletionFunctionTool[]; // Tool configuration
|
|
150
124
|
model?: string; // Custom model
|
|
@@ -187,7 +161,6 @@ export async function callAgent(
|
|
|
187
161
|
modelConfig,
|
|
188
162
|
messages,
|
|
189
163
|
abortSignal,
|
|
190
|
-
memory,
|
|
191
164
|
workdir,
|
|
192
165
|
tools,
|
|
193
166
|
model,
|
|
@@ -216,28 +189,7 @@ export async function callAgent(
|
|
|
216
189
|
});
|
|
217
190
|
|
|
218
191
|
// Build system prompt content
|
|
219
|
-
|
|
220
|
-
systemPrompt || DEFAULT_SYSTEM_PROMPT,
|
|
221
|
-
tools || [],
|
|
222
|
-
);
|
|
223
|
-
|
|
224
|
-
// Always add environment information
|
|
225
|
-
systemContent += `
|
|
226
|
-
|
|
227
|
-
Here is useful information about the environment you are running in:
|
|
228
|
-
<env>
|
|
229
|
-
Working directory: ${workdir}
|
|
230
|
-
Is directory a git repo: ${isGitRepository(workdir)}
|
|
231
|
-
Platform: ${os.platform()}
|
|
232
|
-
OS Version: ${os.type()} ${os.release()}
|
|
233
|
-
Today's date: ${new Date().toISOString().split("T")[0]}
|
|
234
|
-
</env>
|
|
235
|
-
`;
|
|
236
|
-
|
|
237
|
-
// If there is memory content, add it to the system prompt
|
|
238
|
-
if (memory && memory.trim()) {
|
|
239
|
-
systemContent += `\n## Memory Context\n\nThe following is important context and memory from previous interactions:\n\n${memory}`;
|
|
240
|
-
}
|
|
192
|
+
const systemContent = systemPrompt || "";
|
|
241
193
|
|
|
242
194
|
// Add system prompt
|
|
243
195
|
const systemMessage: ChatCompletionMessageParam = {
|
|
@@ -792,101 +744,7 @@ export async function compressMessages(
|
|
|
792
744
|
messages: [
|
|
793
745
|
{
|
|
794
746
|
role: "system",
|
|
795
|
-
content:
|
|
796
|
-
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.
|
|
797
|
-
|
|
798
|
-
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:
|
|
799
|
-
|
|
800
|
-
1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
|
|
801
|
-
- The user's explicit requests and intents
|
|
802
|
-
- Your approach to addressing the user's requests
|
|
803
|
-
- Key decisions, technical concepts and code patterns
|
|
804
|
-
- Specific details like:
|
|
805
|
-
- file names
|
|
806
|
-
- full code snippets
|
|
807
|
-
- function signatures
|
|
808
|
-
- file edits
|
|
809
|
-
- Errors that you ran into and how you fixed them
|
|
810
|
-
- Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
|
|
811
|
-
2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.
|
|
812
|
-
|
|
813
|
-
Your summary should include the following sections:
|
|
814
|
-
|
|
815
|
-
1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
|
|
816
|
-
2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
|
|
817
|
-
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.
|
|
818
|
-
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.
|
|
819
|
-
5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
|
|
820
|
-
6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
|
|
821
|
-
6. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
|
|
822
|
-
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.
|
|
823
|
-
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.
|
|
824
|
-
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.
|
|
825
|
-
|
|
826
|
-
Here's an example of how your output should be structured:
|
|
827
|
-
|
|
828
|
-
<example>
|
|
829
|
-
<analysis>
|
|
830
|
-
[Your thought process, ensuring all points are covered thoroughly and accurately]
|
|
831
|
-
</analysis>
|
|
832
|
-
|
|
833
|
-
<summary>
|
|
834
|
-
1. Primary Request and Intent:
|
|
835
|
-
[Detailed description]
|
|
836
|
-
|
|
837
|
-
2. Key Technical Concepts:
|
|
838
|
-
- [Concept 1]
|
|
839
|
-
- [Concept 2]
|
|
840
|
-
- [...]
|
|
841
|
-
|
|
842
|
-
3. Files and Code Sections:
|
|
843
|
-
- [File Name 1]
|
|
844
|
-
- [Summary of why this file is important]
|
|
845
|
-
- [Summary of the changes made to this file, if any]
|
|
846
|
-
- [Important Code Snippet]
|
|
847
|
-
- [File Name 2]
|
|
848
|
-
- [Important Code Snippet]
|
|
849
|
-
- [...]
|
|
850
|
-
|
|
851
|
-
4. Errors and fixes:
|
|
852
|
-
- [Detailed description of error 1]:
|
|
853
|
-
- [How you fixed the error]
|
|
854
|
-
- [User feedback on the error if any]
|
|
855
|
-
- [...]
|
|
856
|
-
|
|
857
|
-
5. Problem Solving:
|
|
858
|
-
[Description of solved problems and ongoing troubleshooting]
|
|
859
|
-
|
|
860
|
-
6. All user messages:
|
|
861
|
-
- [Detailed non tool use user message]
|
|
862
|
-
- [...]
|
|
863
|
-
|
|
864
|
-
7. Pending Tasks:
|
|
865
|
-
- [Task 1]
|
|
866
|
-
- [Task 2]
|
|
867
|
-
- [...]
|
|
868
|
-
|
|
869
|
-
8. Current Work:
|
|
870
|
-
[Precise description of current work]
|
|
871
|
-
|
|
872
|
-
9. Optional Next Step:
|
|
873
|
-
[Optional Next step to take]
|
|
874
|
-
|
|
875
|
-
</summary>
|
|
876
|
-
</example>
|
|
877
|
-
|
|
878
|
-
Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.
|
|
879
|
-
|
|
880
|
-
There may be additional summarization instructions provided in the included context. If so, remember to follow these instructions when creating the above summary. Examples of instructions include:
|
|
881
|
-
<example>
|
|
882
|
-
## Compact Instructions
|
|
883
|
-
When summarizing the conversation focus on typescript code changes and also remember the mistakes you made and how you fixed them.
|
|
884
|
-
</example>
|
|
885
|
-
|
|
886
|
-
<example>
|
|
887
|
-
# Summary instructions
|
|
888
|
-
When you are using compact - please focus on test output and code changes. Include file reads verbatim.
|
|
889
|
-
</example>`,
|
|
747
|
+
content: COMPRESS_MESSAGES_SYSTEM_PROMPT,
|
|
890
748
|
},
|
|
891
749
|
...messages,
|
|
892
750
|
{
|
package/src/services/memory.ts
CHANGED
|
@@ -4,54 +4,6 @@ import { USER_MEMORY_FILE, DATA_DIRECTORY } from "../utils/constants.js";
|
|
|
4
4
|
import { logger } from "../utils/globalLogger.js";
|
|
5
5
|
|
|
6
6
|
// Project memory related methods
|
|
7
|
-
export const isMemoryMessage = (message: string): boolean => {
|
|
8
|
-
return message.trim().startsWith("#");
|
|
9
|
-
};
|
|
10
|
-
|
|
11
|
-
export const addMemory = async (
|
|
12
|
-
message: string,
|
|
13
|
-
workdir: string,
|
|
14
|
-
): Promise<void> => {
|
|
15
|
-
if (!isMemoryMessage(message)) {
|
|
16
|
-
return;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
try {
|
|
20
|
-
const memoryFilePath = path.join(workdir, "AGENTS.md");
|
|
21
|
-
|
|
22
|
-
// Format memory entry, starting with -, no timestamp
|
|
23
|
-
const memoryEntry = `- ${message.substring(1).trim()}\n`;
|
|
24
|
-
|
|
25
|
-
// Check if file exists
|
|
26
|
-
let existingContent = "";
|
|
27
|
-
try {
|
|
28
|
-
existingContent = await fs.readFile(memoryFilePath, "utf-8");
|
|
29
|
-
} catch (error) {
|
|
30
|
-
// File does not exist, create new file
|
|
31
|
-
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
|
32
|
-
logger.info("Memory file does not exist, will create new one", {
|
|
33
|
-
memoryFilePath,
|
|
34
|
-
});
|
|
35
|
-
existingContent =
|
|
36
|
-
"# Memory\n\nThis is the AI assistant's memory file, recording important information and context.\n\n";
|
|
37
|
-
} else {
|
|
38
|
-
throw error;
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
// Append new memory entry to the end of the file
|
|
43
|
-
const updatedContent = existingContent + memoryEntry;
|
|
44
|
-
|
|
45
|
-
// Write file
|
|
46
|
-
await fs.writeFile(memoryFilePath, updatedContent, "utf-8");
|
|
47
|
-
|
|
48
|
-
logger.debug(`Memory added to ${memoryFilePath}:`, message);
|
|
49
|
-
} catch (error) {
|
|
50
|
-
logger.error("Failed to add memory:", error);
|
|
51
|
-
throw new Error(`Failed to add memory: ${(error as Error).message}`);
|
|
52
|
-
}
|
|
53
|
-
};
|
|
54
|
-
|
|
55
7
|
// User memory related methods
|
|
56
8
|
export const ensureUserMemoryFile = async (): Promise<void> => {
|
|
57
9
|
try {
|
|
@@ -83,30 +35,6 @@ export const ensureUserMemoryFile = async (): Promise<void> => {
|
|
|
83
35
|
}
|
|
84
36
|
};
|
|
85
37
|
|
|
86
|
-
export const addUserMemory = async (message: string): Promise<void> => {
|
|
87
|
-
try {
|
|
88
|
-
// Ensure user memory file exists
|
|
89
|
-
await ensureUserMemoryFile();
|
|
90
|
-
|
|
91
|
-
// Format memory entry, starting with -
|
|
92
|
-
const memoryEntry = `- ${message.substring(1).trim()}\n`;
|
|
93
|
-
|
|
94
|
-
// Read existing content
|
|
95
|
-
const existingContent = await fs.readFile(USER_MEMORY_FILE, "utf-8");
|
|
96
|
-
|
|
97
|
-
// Append new memory entry to the end of the file
|
|
98
|
-
const updatedContent = existingContent + memoryEntry;
|
|
99
|
-
|
|
100
|
-
// Write file
|
|
101
|
-
await fs.writeFile(USER_MEMORY_FILE, updatedContent, "utf-8");
|
|
102
|
-
|
|
103
|
-
logger.debug(`User memory added to ${USER_MEMORY_FILE}:`, message);
|
|
104
|
-
} catch (error) {
|
|
105
|
-
logger.error("Failed to add user memory:", error);
|
|
106
|
-
throw new Error(`Failed to add user memory: ${(error as Error).message}`);
|
|
107
|
-
}
|
|
108
|
-
};
|
|
109
|
-
|
|
110
38
|
export const getUserMemoryContent = async (): Promise<string> => {
|
|
111
39
|
try {
|
|
112
40
|
await ensureUserMemoryFile();
|
|
@@ -142,7 +70,7 @@ export const readMemoryFile = async (workdir: string): Promise<string> => {
|
|
|
142
70
|
return "";
|
|
143
71
|
}
|
|
144
72
|
logger.error("Failed to read memory file", { memoryFilePath, error });
|
|
145
|
-
|
|
73
|
+
return "";
|
|
146
74
|
}
|
|
147
75
|
};
|
|
148
76
|
|
package/src/services/session.ts
CHANGED
|
@@ -28,6 +28,8 @@ import { logger } from "../utils/globalLogger.js";
|
|
|
28
28
|
|
|
29
29
|
export interface SessionData {
|
|
30
30
|
id: string;
|
|
31
|
+
rootSessionId?: string;
|
|
32
|
+
parentSessionId?: string;
|
|
31
33
|
messages: Message[];
|
|
32
34
|
metadata: {
|
|
33
35
|
workdir: string;
|
|
@@ -38,6 +40,8 @@ export interface SessionData {
|
|
|
38
40
|
|
|
39
41
|
export interface SessionMetadata {
|
|
40
42
|
id: string;
|
|
43
|
+
rootSessionId?: string;
|
|
44
|
+
parentSessionId?: string;
|
|
41
45
|
sessionType: "main" | "subagent";
|
|
42
46
|
subagentType?: string;
|
|
43
47
|
workdir: string;
|
|
@@ -101,6 +105,7 @@ async function updateSessionIndex(
|
|
|
101
105
|
...rest,
|
|
102
106
|
lastActiveAt: metadata.lastActiveAt.toISOString(),
|
|
103
107
|
firstMessage: metadata.firstMessage || index.sessions[id]?.firstMessage,
|
|
108
|
+
parentSessionId: metadata.parentSessionId,
|
|
104
109
|
};
|
|
105
110
|
index.lastUpdated = new Date().toISOString();
|
|
106
111
|
|
|
@@ -191,6 +196,8 @@ export async function appendMessages(
|
|
|
191
196
|
newMessages: Message[],
|
|
192
197
|
workdir: string,
|
|
193
198
|
sessionType: "main" | "subagent" = "main",
|
|
199
|
+
rootSessionId?: string,
|
|
200
|
+
parentSessionId?: string,
|
|
194
201
|
): Promise<void> {
|
|
195
202
|
// Do not save session files in test environment
|
|
196
203
|
if (process.env.NODE_ENV === "test") {
|
|
@@ -252,6 +259,8 @@ export async function appendMessages(
|
|
|
252
259
|
|
|
253
260
|
await updateSessionIndex(projectDir.encodedPath, {
|
|
254
261
|
id: sessionId,
|
|
262
|
+
rootSessionId,
|
|
263
|
+
parentSessionId,
|
|
255
264
|
sessionType,
|
|
256
265
|
workdir,
|
|
257
266
|
lastActiveAt: new Date(lastMessage.timestamp),
|
|
@@ -294,8 +303,28 @@ export async function loadSessionFromJsonl(
|
|
|
294
303
|
// Extract metadata from messages
|
|
295
304
|
const lastMessage = messages[messages.length - 1];
|
|
296
305
|
|
|
306
|
+
// Try to get rootSessionId and parentSessionId from index
|
|
307
|
+
let rootSessionId: string | undefined;
|
|
308
|
+
let parentSessionId: string | undefined;
|
|
309
|
+
try {
|
|
310
|
+
const encoder = new PathEncoder();
|
|
311
|
+
const projectDir = await encoder.getProjectDirectory(
|
|
312
|
+
workdir,
|
|
313
|
+
SESSION_DIR,
|
|
314
|
+
);
|
|
315
|
+
const indexPath = join(projectDir.encodedPath, SESSION_INDEX_FILENAME);
|
|
316
|
+
const indexContent = await fs.readFile(indexPath, "utf8");
|
|
317
|
+
const index = JSON.parse(indexContent) as SessionIndex;
|
|
318
|
+
rootSessionId = index.sessions[sessionId]?.rootSessionId;
|
|
319
|
+
parentSessionId = index.sessions[sessionId]?.parentSessionId;
|
|
320
|
+
} catch {
|
|
321
|
+
// Ignore index errors
|
|
322
|
+
}
|
|
323
|
+
|
|
297
324
|
const sessionData: SessionData = {
|
|
298
325
|
id: sessionId,
|
|
326
|
+
rootSessionId: rootSessionId || sessionId,
|
|
327
|
+
parentSessionId,
|
|
299
328
|
messages: messages.map((msg) => {
|
|
300
329
|
// Remove timestamp property for backward compatibility
|
|
301
330
|
const { timestamp: _ignored, ...messageWithoutTimestamp } = msg;
|
|
@@ -841,3 +870,47 @@ export async function handleSessionRestoration(
|
|
|
841
870
|
process.exit(1);
|
|
842
871
|
}
|
|
843
872
|
}
|
|
873
|
+
|
|
874
|
+
/**
|
|
875
|
+
* Load the full message thread by following parentSessionId links
|
|
876
|
+
* @param currentSessionId - The ID of the current session
|
|
877
|
+
* @param workdir - Working directory for the session
|
|
878
|
+
* @returns Promise that resolves to an array of all messages in the thread
|
|
879
|
+
*/
|
|
880
|
+
export async function loadFullMessageThread(
|
|
881
|
+
currentSessionId: string,
|
|
882
|
+
workdir: string,
|
|
883
|
+
): Promise<{ messages: Message[]; sessionIds: string[] }> {
|
|
884
|
+
const sessionIds: string[] = [];
|
|
885
|
+
let currentId: string | undefined = currentSessionId;
|
|
886
|
+
const allMessages: Message[] = [];
|
|
887
|
+
|
|
888
|
+
while (currentId) {
|
|
889
|
+
const sessionData = await loadSessionFromJsonl(currentId, workdir);
|
|
890
|
+
if (!sessionData) break;
|
|
891
|
+
|
|
892
|
+
sessionIds.unshift(currentId);
|
|
893
|
+
// Add messages from this session to the beginning of the list
|
|
894
|
+
// But skip the "compress" block if it's not the first session in our traversal (which is the latest)
|
|
895
|
+
// Actually, we should probably keep all messages and let the UI/logic handle it.
|
|
896
|
+
// But wait, if we are concatenating, the "compress" block in session N summarizes session N-1.
|
|
897
|
+
// So if we have session N-1 and session N, we should probably skip the compress block in session N.
|
|
898
|
+
|
|
899
|
+
const messages = sessionData.messages;
|
|
900
|
+
if (allMessages.length > 0) {
|
|
901
|
+
// If we already have messages (from "later" sessions),
|
|
902
|
+
// we are now adding messages from an "earlier" session.
|
|
903
|
+
// The later session's first message might be a "compress" block.
|
|
904
|
+
if (allMessages[0].blocks.some((b) => b.type === "compress")) {
|
|
905
|
+
// Remove the compress block from the later session's messages
|
|
906
|
+
// because we are now providing the actual messages it summarized.
|
|
907
|
+
allMessages.shift();
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
allMessages.unshift(...messages);
|
|
912
|
+
currentId = sessionData.parentSessionId;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
return { messages: allMessages, sessionIds };
|
|
916
|
+
}
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { promises as fs } from "fs";
|
|
2
|
+
import { join } from "path";
|
|
3
|
+
import { homedir } from "os";
|
|
4
|
+
import { EventEmitter } from "events";
|
|
5
|
+
import { Task } from "../types/tasks.js";
|
|
6
|
+
import { logger } from "../utils/globalLogger.js";
|
|
7
|
+
|
|
8
|
+
export class TaskManager extends EventEmitter {
|
|
9
|
+
private readonly baseDir: string;
|
|
10
|
+
private taskListId: string;
|
|
11
|
+
|
|
12
|
+
constructor(taskListId: string) {
|
|
13
|
+
super();
|
|
14
|
+
this.taskListId = taskListId;
|
|
15
|
+
this.baseDir = join(homedir(), ".wave", "tasks");
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
public getTaskListId(): string {
|
|
19
|
+
return this.taskListId;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
public setTaskListId(taskListId: string): void {
|
|
23
|
+
this.taskListId = taskListId;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
private getSessionDir(): string {
|
|
27
|
+
return join(this.baseDir, this.taskListId);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
private getTaskPath(taskId: string): string {
|
|
31
|
+
return join(this.getSessionDir(), `${taskId}.json`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
private getLockPath(): string {
|
|
35
|
+
return join(this.getSessionDir(), `.lock`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async ensureSessionDir(): Promise<void> {
|
|
39
|
+
await fs.mkdir(this.getSessionDir(), { recursive: true });
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
private async withLock<T>(operation: () => Promise<T>): Promise<T> {
|
|
43
|
+
const lockPath = this.getLockPath();
|
|
44
|
+
let lockHandle;
|
|
45
|
+
const maxRetries = 100;
|
|
46
|
+
const retryDelay = process.env.NODE_ENV === "test" ? 10 : 100;
|
|
47
|
+
|
|
48
|
+
await this.ensureSessionDir();
|
|
49
|
+
|
|
50
|
+
for (let i = 0; i < maxRetries; i++) {
|
|
51
|
+
try {
|
|
52
|
+
lockHandle = await fs.open(lockPath, "wx");
|
|
53
|
+
break;
|
|
54
|
+
} catch (error) {
|
|
55
|
+
if ((error as NodeJS.ErrnoException).code === "EEXIST") {
|
|
56
|
+
if (i === maxRetries - 1) {
|
|
57
|
+
throw new Error(
|
|
58
|
+
`Could not acquire lock for task list ${this.taskListId} after ${maxRetries} retries`,
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
await new Promise((resolve) => setTimeout(resolve, retryDelay));
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
try {
|
|
69
|
+
return await operation();
|
|
70
|
+
} finally {
|
|
71
|
+
if (lockHandle) {
|
|
72
|
+
await lockHandle.close();
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
await fs.unlink(lockPath);
|
|
76
|
+
} catch (error) {
|
|
77
|
+
logger.error(
|
|
78
|
+
`Failed to release lock for task list ${this.taskListId}:`,
|
|
79
|
+
error,
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
private validateTask(task: Task): void {
|
|
86
|
+
if (!task.id || typeof task.id !== "string")
|
|
87
|
+
throw new Error("Invalid task ID");
|
|
88
|
+
if (!task.subject || typeof task.subject !== "string")
|
|
89
|
+
throw new Error("Invalid task subject");
|
|
90
|
+
if (!task.description || typeof task.description !== "string")
|
|
91
|
+
throw new Error("Invalid task description");
|
|
92
|
+
if (
|
|
93
|
+
!task.status ||
|
|
94
|
+
!["pending", "in_progress", "completed", "deleted"].includes(task.status)
|
|
95
|
+
) {
|
|
96
|
+
throw new Error(`Invalid task status: ${task.status}`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async createTask(task: Omit<Task, "id">): Promise<string> {
|
|
101
|
+
return await this.withLock(async () => {
|
|
102
|
+
const taskId = await this.getNextTaskId();
|
|
103
|
+
const fullTask: Task = { ...task, id: taskId };
|
|
104
|
+
this.validateTask(fullTask);
|
|
105
|
+
const taskPath = this.getTaskPath(taskId);
|
|
106
|
+
const content = JSON.stringify(fullTask, null, 2);
|
|
107
|
+
await fs.writeFile(taskPath, content, "utf8");
|
|
108
|
+
this.emit("tasksChange", this.taskListId);
|
|
109
|
+
logger.info(`Task ${taskId} created in task list ${this.taskListId}`);
|
|
110
|
+
return taskId;
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async getTask(taskId: string): Promise<Task | null> {
|
|
115
|
+
const taskPath = this.getTaskPath(taskId);
|
|
116
|
+
try {
|
|
117
|
+
const content = await fs.readFile(taskPath, "utf8");
|
|
118
|
+
try {
|
|
119
|
+
return JSON.parse(content.trim()) as Task;
|
|
120
|
+
} catch (parseError) {
|
|
121
|
+
logger.error(`Failed to parse task file ${taskPath}:`, parseError);
|
|
122
|
+
logger.error(`Corrupted content: ${content}`);
|
|
123
|
+
throw parseError;
|
|
124
|
+
}
|
|
125
|
+
} catch (error) {
|
|
126
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
throw error;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async updateTask(task: Task): Promise<void> {
|
|
134
|
+
this.validateTask(task);
|
|
135
|
+
await this.withLock(async () => {
|
|
136
|
+
const taskPath = this.getTaskPath(task.id);
|
|
137
|
+
const content = JSON.stringify(task, null, 2);
|
|
138
|
+
await fs.writeFile(taskPath, content, "utf8");
|
|
139
|
+
this.emit("tasksChange", this.taskListId);
|
|
140
|
+
logger.info(`Task ${task.id} updated in task list ${this.taskListId}`);
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async listTasks(): Promise<Task[]> {
|
|
145
|
+
const sessionDir = this.getSessionDir();
|
|
146
|
+
try {
|
|
147
|
+
const files = await fs.readdir(sessionDir);
|
|
148
|
+
const taskFiles = files.filter((f) => f.endsWith(".json"));
|
|
149
|
+
|
|
150
|
+
const tasks = await Promise.all(
|
|
151
|
+
taskFiles.map(async (file) => {
|
|
152
|
+
const taskPath = join(sessionDir, file);
|
|
153
|
+
try {
|
|
154
|
+
const content = await fs.readFile(taskPath, "utf8");
|
|
155
|
+
return JSON.parse(content.trim()) as Task;
|
|
156
|
+
} catch (error) {
|
|
157
|
+
logger.error(
|
|
158
|
+
`Failed to read or parse task file ${taskPath}:`,
|
|
159
|
+
error,
|
|
160
|
+
);
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
}),
|
|
164
|
+
);
|
|
165
|
+
|
|
166
|
+
return tasks.filter((t): t is Task => t !== null);
|
|
167
|
+
} catch (error) {
|
|
168
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
|
169
|
+
return [];
|
|
170
|
+
}
|
|
171
|
+
throw error;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async getNextTaskId(): Promise<string> {
|
|
176
|
+
const tasks = await this.listTasks();
|
|
177
|
+
if (tasks.length === 0) {
|
|
178
|
+
return "1";
|
|
179
|
+
}
|
|
180
|
+
const ids = tasks.map((t) => parseInt(t.id, 10)).filter((id) => !isNaN(id));
|
|
181
|
+
|
|
182
|
+
if (ids.length === 0) {
|
|
183
|
+
return (tasks.length + 1).toString();
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
return (Math.max(...ids) + 1).toString();
|
|
187
|
+
}
|
|
188
|
+
}
|