wave-agent-sdk 1.0.4 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/dist/agent.d.ts +23 -1
  2. package/dist/agent.js +34 -4
  3. package/dist/managers/aiManager.d.ts +36 -0
  4. package/dist/managers/aiManager.js +240 -8
  5. package/dist/managers/messageManager.d.ts +1 -3
  6. package/dist/managers/messageManager.js +19 -9
  7. package/dist/managers/slashCommandManager.js +28 -0
  8. package/dist/managers/subagentManager.d.ts +0 -2
  9. package/dist/services/session.js +2 -9
  10. package/dist/telemetry/instrumentation.d.ts +1 -1
  11. package/dist/telemetry/instrumentation.js +57 -28
  12. package/dist/tools/bashTool.js +16 -6
  13. package/dist/tools/grepTool.js +11 -3
  14. package/dist/types/index.d.ts +3 -0
  15. package/dist/types/messaging.d.ts +2 -0
  16. package/dist/utils/containerSetup.js +0 -3
  17. package/dist/utils/messageOperations.d.ts +10 -1
  18. package/dist/utils/messageOperations.js +19 -1
  19. package/dist/utils/notificationXml.js +5 -0
  20. package/dist/utils/ripgrep.d.ts +4 -4
  21. package/dist/utils/ripgrep.js +4 -27
  22. package/package.json +20 -8
  23. package/bin/rg +0 -79
  24. package/dist/managers/forkedAgentManager.d.ts +0 -50
  25. package/dist/managers/forkedAgentManager.js +0 -130
  26. package/scripts/install_ripgrep.js +0 -111
  27. package/scripts/postinstall.js +0 -38
  28. package/src/agent.ts +0 -1271
  29. package/src/constants/subagents.ts +0 -4
  30. package/src/constants/toolLimits.ts +0 -15
  31. package/src/constants/tools.ts +0 -24
  32. package/src/core/plugin.ts +0 -237
  33. package/src/core/session.ts +0 -9
  34. package/src/index.ts +0 -38
  35. package/src/managers/MemoryRuleManager.ts +0 -198
  36. package/src/managers/aiManager.ts +0 -2429
  37. package/src/managers/backgroundTaskManager.ts +0 -480
  38. package/src/managers/bangManager.ts +0 -119
  39. package/src/managers/cronManager.ts +0 -401
  40. package/src/managers/foregroundTaskManager.ts +0 -30
  41. package/src/managers/forkedAgentManager.ts +0 -216
  42. package/src/managers/hookManager.ts +0 -1089
  43. package/src/managers/liveConfigManager.ts +0 -445
  44. package/src/managers/lspManager.ts +0 -470
  45. package/src/managers/mcpManager.ts +0 -1010
  46. package/src/managers/messageManager.ts +0 -1180
  47. package/src/managers/messageQueue.ts +0 -157
  48. package/src/managers/permissionManager.ts +0 -1140
  49. package/src/managers/planManager.ts +0 -112
  50. package/src/managers/pluginManager.ts +0 -330
  51. package/src/managers/pluginScopeManager.ts +0 -124
  52. package/src/managers/reversionManager.ts +0 -178
  53. package/src/managers/skillManager.ts +0 -578
  54. package/src/managers/slashCommandManager.ts +0 -564
  55. package/src/managers/subagentManager.ts +0 -915
  56. package/src/managers/toolManager.ts +0 -489
  57. package/src/managers/workflowManager.ts +0 -493
  58. package/src/prompts/autoMemory.ts +0 -33
  59. package/src/prompts/autoMemoryExtraction.ts +0 -146
  60. package/src/prompts/index.ts +0 -506
  61. package/src/prompts/planModeReminders.ts +0 -126
  62. package/src/services/GitService.ts +0 -131
  63. package/src/services/MarketplaceService.ts +0 -1052
  64. package/src/services/MemoryRuleService.ts +0 -71
  65. package/src/services/aiService.ts +0 -919
  66. package/src/services/authService.ts +0 -565
  67. package/src/services/autoMemoryService.ts +0 -280
  68. package/src/services/configurationService.ts +0 -1520
  69. package/src/services/fileWatcher.ts +0 -319
  70. package/src/services/hook.ts +0 -348
  71. package/src/services/initializationService.ts +0 -357
  72. package/src/services/interactionService.ts +0 -229
  73. package/src/services/jsonlHandler.ts +0 -295
  74. package/src/services/memory.ts +0 -234
  75. package/src/services/pluginLoader.ts +0 -252
  76. package/src/services/remoteSettingsService.ts +0 -366
  77. package/src/services/reversionService.ts +0 -122
  78. package/src/services/session.ts +0 -922
  79. package/src/services/taskManager.ts +0 -321
  80. package/src/telemetry/events.ts +0 -65
  81. package/src/telemetry/instrumentation.ts +0 -499
  82. package/src/telemetry/sessionTracing.ts +0 -348
  83. package/src/tools/agentTool.ts +0 -322
  84. package/src/tools/askUserQuestion.ts +0 -160
  85. package/src/tools/bashTool.ts +0 -621
  86. package/src/tools/buildTool.ts +0 -61
  87. package/src/tools/cronCreateTool.ts +0 -161
  88. package/src/tools/cronDeleteTool.ts +0 -51
  89. package/src/tools/cronListTool.ts +0 -47
  90. package/src/tools/editTool.ts +0 -313
  91. package/src/tools/enterPlanMode.ts +0 -124
  92. package/src/tools/enterWorktreeTool.ts +0 -190
  93. package/src/tools/exitPlanMode.ts +0 -139
  94. package/src/tools/exitWorktreeTool.ts +0 -236
  95. package/src/tools/globTool.ts +0 -167
  96. package/src/tools/grepTool.ts +0 -399
  97. package/src/tools/lspTool.ts +0 -883
  98. package/src/tools/readTool.ts +0 -426
  99. package/src/tools/skillTool.ts +0 -248
  100. package/src/tools/taskManagementTools.ts +0 -574
  101. package/src/tools/taskStopTool.ts +0 -78
  102. package/src/tools/types.ts +0 -137
  103. package/src/tools/webFetchTool.ts +0 -373
  104. package/src/tools/workflowTool.ts +0 -205
  105. package/src/tools/writeTool.ts +0 -267
  106. package/src/types/agent.ts +0 -128
  107. package/src/types/auth.ts +0 -19
  108. package/src/types/commands.ts +0 -30
  109. package/src/types/config.ts +0 -43
  110. package/src/types/configuration.ts +0 -168
  111. package/src/types/core.ts +0 -105
  112. package/src/types/cron.ts +0 -13
  113. package/src/types/environment.ts +0 -106
  114. package/src/types/fileSearch.ts +0 -4
  115. package/src/types/history.ts +0 -7
  116. package/src/types/hooks.ts +0 -256
  117. package/src/types/index.ts +0 -41
  118. package/src/types/lsp.ts +0 -98
  119. package/src/types/marketplace.ts +0 -71
  120. package/src/types/mcp.ts +0 -43
  121. package/src/types/memoryRule.ts +0 -31
  122. package/src/types/messaging.ts +0 -114
  123. package/src/types/permissions.ts +0 -80
  124. package/src/types/plugins.ts +0 -39
  125. package/src/types/processes.ts +0 -99
  126. package/src/types/reversion.ts +0 -29
  127. package/src/types/session.ts +0 -12
  128. package/src/types/skills.ts +0 -108
  129. package/src/types/tasks.ts +0 -13
  130. package/src/types/telemetry.ts +0 -98
  131. package/src/types/tools.ts +0 -44
  132. package/src/types/workflow.ts +0 -6
  133. package/src/utils/abortUtils.ts +0 -118
  134. package/src/utils/atomicWrite.ts +0 -61
  135. package/src/utils/bashParser.ts +0 -899
  136. package/src/utils/cacheControlUtils.ts +0 -426
  137. package/src/utils/commandArgumentParser.ts +0 -161
  138. package/src/utils/commandPathResolver.ts +0 -88
  139. package/src/utils/configPaths.ts +0 -220
  140. package/src/utils/configValidator.ts +0 -100
  141. package/src/utils/constants.ts +0 -39
  142. package/src/utils/container.ts +0 -92
  143. package/src/utils/containerSetup.ts +0 -371
  144. package/src/utils/convertMessagesForAPI.ts +0 -326
  145. package/src/utils/cronTasks.ts +0 -128
  146. package/src/utils/cronTasksLock.ts +0 -182
  147. package/src/utils/cronToHuman.ts +0 -99
  148. package/src/utils/customCommands.ts +0 -95
  149. package/src/utils/editUtils.ts +0 -20
  150. package/src/utils/fileFormat.ts +0 -40
  151. package/src/utils/fileSearch.ts +0 -151
  152. package/src/utils/fileUtils.ts +0 -223
  153. package/src/utils/gitUtils.ts +0 -315
  154. package/src/utils/globalLogger.ts +0 -128
  155. package/src/utils/groupMessagesByApiRound.ts +0 -121
  156. package/src/utils/hookMatcher.ts +0 -176
  157. package/src/utils/markdownParser.ts +0 -317
  158. package/src/utils/mcpUtils.ts +0 -138
  159. package/src/utils/messageOperations.ts +0 -641
  160. package/src/utils/modelCapabilities.ts +0 -30
  161. package/src/utils/nameGenerator.ts +0 -99
  162. package/src/utils/notificationXml.ts +0 -57
  163. package/src/utils/openaiClient.ts +0 -251
  164. package/src/utils/parseCronExpression.ts +0 -78
  165. package/src/utils/path.ts +0 -72
  166. package/src/utils/pathEncoder.ts +0 -400
  167. package/src/utils/pathSafety.ts +0 -40
  168. package/src/utils/promptHistory.ts +0 -168
  169. package/src/utils/ripgrep.ts +0 -35
  170. package/src/utils/shellResolver.ts +0 -190
  171. package/src/utils/skillParser.ts +0 -246
  172. package/src/utils/stringUtils.ts +0 -156
  173. package/src/utils/subagentParser.ts +0 -279
  174. package/src/utils/taskReminder.ts +0 -96
  175. package/src/utils/tokenCalculation.ts +0 -43
  176. package/src/utils/tokenEstimate.ts +0 -34
  177. package/src/utils/toolResultStorage.ts +0 -117
  178. package/src/utils/worktreeSession.ts +0 -26
  179. package/src/utils/worktreeUtils.ts +0 -786
  180. package/src/workflow/budgetTracker.ts +0 -34
  181. package/src/workflow/concurrencyLimiter.ts +0 -47
  182. package/src/workflow/journal.ts +0 -95
  183. package/src/workflow/progressReporter.ts +0 -141
  184. package/src/workflow/runState.ts +0 -65
  185. package/src/workflow/scriptRuntime.ts +0 -274
  186. package/src/workflow/structuredOutput.ts +0 -123
  187. package/src/workflow/types.ts +0 -101
  188. package/src/workflow/workflowApis.ts +0 -410
  189. package/vendor/ripgrep/linux-aarch64/rg +0 -0
  190. package/vendor/ripgrep/linux-x86_64/rg +0 -0
  191. package/vendor/ripgrep/macos-aarch64/rg +0 -0
  192. package/vendor/ripgrep/macos-x86_64/rg +0 -0
  193. package/vendor/ripgrep/windows-aarch64/rg.exe +0 -0
  194. package/vendor/ripgrep/windows-x86_64/rg.exe +0 -0
@@ -1,295 +0,0 @@
1
- /**
2
- * JSONL file operations service
3
- * Handles reading and writing JSONL (JSON Lines) session files for improved performance
4
- */
5
-
6
- import { appendFile, readFile, writeFile, stat, mkdir } from "fs/promises";
7
- import { dirname } from "path";
8
- import { getLastLine } from "../utils/fileUtils.js";
9
-
10
- import type { Message } from "../types/index.js";
11
- import type { SessionFilename } from "../types/session.js";
12
-
13
- /**
14
- * JSONL write options
15
- */
16
- export interface JsonlWriteOptions {
17
- // Safety options
18
- atomic?: boolean; // Default: true (write to temp file first)
19
- }
20
-
21
- /**
22
- * JSONL handler class for message persistence operations
23
- */
24
- export class JsonlHandler {
25
- private readonly defaultWriteOptions: Required<JsonlWriteOptions>;
26
-
27
- constructor() {
28
- this.defaultWriteOptions = {
29
- atomic: true,
30
- };
31
- }
32
-
33
- /**
34
- * Create a new session file (simplified - no metadata header)
35
- */
36
- async createSession(filePath: string): Promise<void> {
37
- // Ensure directory exists
38
- await this.ensureDirectory(dirname(filePath));
39
-
40
- // Create empty file (no metadata line needed)
41
- await writeFile(filePath, "", "utf8");
42
- }
43
-
44
- /**
45
- * Append a single message to JSONL file
46
- */
47
- async appendMessage(filePath: string, message: Message): Promise<void> {
48
- return this.appendMessages(filePath, [message]);
49
- }
50
-
51
- /**
52
- * Append multiple messages to JSONL file
53
- */
54
- async appendMessages(filePath: string, messages: Message[]): Promise<void> {
55
- if (messages.length === 0) {
56
- return;
57
- }
58
-
59
- return this.append(filePath, messages);
60
- }
61
-
62
- /**
63
- * Append messages to JSONL file
64
- */
65
- async append(
66
- filePath: string,
67
- messages: Message[],
68
- options?: JsonlWriteOptions,
69
- ): Promise<void> {
70
- if (messages.length === 0) {
71
- return;
72
- }
73
-
74
- const opts = { ...this.defaultWriteOptions, ...options };
75
-
76
- // Validate messages (always enabled for data integrity)
77
- this.validateMessages(messages);
78
-
79
- // Ensure directory exists
80
- await this.ensureDirectory(dirname(filePath));
81
-
82
- // Convert messages to JSONL lines (compact JSON, timestamp first)
83
- const lines = messages.map((message) => {
84
- const { timestamp, ...rest } = message;
85
- return JSON.stringify({ timestamp, ...rest });
86
- });
87
-
88
- const content = lines.join("\n") + "\n";
89
-
90
- if (opts.atomic) {
91
- // Write to temp file first, then rename
92
- const tempPath = `${filePath}.tmp`;
93
- await writeFile(tempPath, content, "utf8");
94
-
95
- // Atomic rename
96
- const { rename } = await import("fs/promises");
97
- await rename(tempPath, filePath);
98
- } else {
99
- // Direct append
100
- await appendFile(filePath, content, "utf8");
101
- }
102
- }
103
-
104
- /**
105
- * Read all messages from JSONL file (simplified - no metadata handling)
106
- */
107
- async read(filePath: string): Promise<Message[]> {
108
- try {
109
- const content = await readFile(filePath, "utf8");
110
- const lines = content
111
- .split(/\r?\n/)
112
- .map((line: string) => line.trim())
113
- .filter((line: string) => line.length > 0);
114
-
115
- if (lines.length === 0) {
116
- return [];
117
- }
118
-
119
- const allMessages: Message[] = [];
120
-
121
- // Parse all messages (no metadata line to skip)
122
- for (let i = 0; i < lines.length; i++) {
123
- const line = lines[i];
124
-
125
- try {
126
- const message = JSON.parse(line) as Message;
127
- if (message.timestamp) allMessages.push(message);
128
- } catch (error) {
129
- // Throw error for invalid JSON lines with line number
130
- throw new Error(`Invalid JSON at line ${i + 1}: ${error}`);
131
- }
132
- }
133
-
134
- return allMessages;
135
- } catch (error) {
136
- if ((error as NodeJS.ErrnoException).code === "ENOENT") {
137
- return [];
138
- }
139
- throw new Error(`Failed to read JSONL file "${filePath}": ${error}`);
140
- }
141
- }
142
-
143
- /**
144
- * Get the last message from JSONL file using efficient file reading (simplified)
145
- */
146
- async getLastMessage(filePath: string): Promise<Message | null> {
147
- try {
148
- // First check if file exists
149
- try {
150
- await stat(filePath);
151
- } catch (err) {
152
- if ((err as NodeJS.ErrnoException).code === "ENOENT") {
153
- return null;
154
- }
155
- throw err;
156
- }
157
-
158
- // Use our elegant utility to get the last line
159
- const lastLine = await getLastLine(filePath);
160
-
161
- if (!lastLine) {
162
- return null;
163
- }
164
-
165
- try {
166
- const parsed = JSON.parse(lastLine);
167
- return parsed as Message;
168
- } catch (error) {
169
- throw new Error(`Invalid JSON in last line of "${filePath}": ${error}`);
170
- }
171
- } catch (error) {
172
- throw new Error(
173
- `Failed to get last message from "${filePath}": ${error}`,
174
- );
175
- }
176
- }
177
-
178
- /**
179
- * Validate messages before writing
180
- */
181
- private validateMessages(messages: Message[]): void {
182
- for (let i = 0; i < messages.length; i++) {
183
- const message = messages[i];
184
-
185
- if (!message.id) {
186
- throw new Error(`Message at index ${i} is missing required field: id`);
187
- }
188
-
189
- if (!message.role) {
190
- throw new Error(
191
- `Message at index ${i} is missing required field: role`,
192
- );
193
- }
194
-
195
- if (!message.blocks) {
196
- throw new Error(
197
- `Message at index ${i} is missing required field: blocks`,
198
- );
199
- }
200
-
201
- if (!Array.isArray(message.blocks)) {
202
- throw new Error(
203
- `Message at index ${i} has invalid blocks field: must be an array`,
204
- );
205
- }
206
- }
207
- }
208
-
209
- /**
210
- * Ensure directory exists for the given file path
211
- */
212
- private async ensureDirectory(dirPath: string): Promise<void> {
213
- try {
214
- await mkdir(dirPath, { recursive: true });
215
- } catch (error) {
216
- const err = error as NodeJS.ErrnoException;
217
- if (err.code !== "EEXIST") {
218
- throw error;
219
- }
220
- }
221
- }
222
-
223
- /**
224
- * Parse session metadata from filename
225
- * @param filePath - Path to the session file
226
- * @returns Parsed session filename metadata
227
- */
228
- parseSessionFilename(filePath: string): SessionFilename {
229
- // Extract filename from path
230
- const filename = filePath.split("/").pop() || "";
231
-
232
- // Check if it's a subagent session
233
- const subagentMatch = filename.match(
234
- /^subagent-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/,
235
- );
236
- if (subagentMatch) {
237
- return {
238
- sessionId: subagentMatch[1],
239
- sessionType: "subagent",
240
- };
241
- }
242
-
243
- // Check if it's a main session
244
- const mainMatch = filename.match(
245
- /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/,
246
- );
247
- if (mainMatch) {
248
- return {
249
- sessionId: mainMatch[1],
250
- sessionType: "main",
251
- };
252
- }
253
-
254
- throw new Error(`Invalid session filename format: ${filename}`);
255
- }
256
-
257
- /**
258
- * Validate filename format
259
- * @param filename - Filename to validate
260
- * @returns True if valid, false otherwise
261
- */
262
- isValidSessionFilename(filename: string): boolean {
263
- // UUID validation patterns
264
- const uuidPattern =
265
- /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/;
266
- const subagentPattern =
267
- /^subagent-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/;
268
-
269
- return uuidPattern.test(filename) || subagentPattern.test(filename);
270
- }
271
-
272
- /**
273
- * Generate simple filename for sessions
274
- * @param sessionId - UUID session identifier
275
- * @param sessionType - Type of session ("main" or "subagent")
276
- * @returns Generated filename
277
- */
278
- generateSessionFilename(
279
- sessionId: string,
280
- sessionType: "main" | "subagent",
281
- ): string {
282
- // Validate sessionId is a valid UUID
283
- const uuidPattern =
284
- /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
285
- if (!uuidPattern.test(sessionId)) {
286
- throw new Error(`Invalid session ID format: ${sessionId}`);
287
- }
288
-
289
- if (sessionType === "subagent") {
290
- return `subagent-${sessionId}.jsonl`;
291
- } else {
292
- return `${sessionId}.jsonl`;
293
- }
294
- }
295
- }
@@ -1,234 +0,0 @@
1
- import * as fs from "node:fs/promises";
2
- import * as path from "node:path";
3
- import { homedir } from "node:os";
4
- import { USER_MEMORY_FILE, DATA_DIRECTORY } from "../utils/constants.js";
5
- import { logger } from "../utils/globalLogger.js";
6
- import { Container } from "../utils/container.js";
7
- import { getGitCommonDir } from "../utils/gitUtils.js";
8
- import { pathEncoder } from "../utils/pathEncoder.js";
9
-
10
- export class MemoryService {
11
- private _cachedProjectMemory: string | null = null;
12
- private _cachedUserMemory: string | null = null;
13
- private _cachedCombinedMemory: string | null = null;
14
- private _cachedAutoMemoryContent: string | null = null;
15
-
16
- constructor(private container: Container) {}
17
-
18
- public get cachedProjectMemory(): string {
19
- return this._cachedProjectMemory ?? "";
20
- }
21
-
22
- public get cachedUserMemory(): string {
23
- return this._cachedUserMemory ?? "";
24
- }
25
-
26
- public clearCache(): void {
27
- this._cachedProjectMemory = null;
28
- this._cachedUserMemory = null;
29
- this._cachedCombinedMemory = null;
30
- this._cachedAutoMemoryContent = null;
31
- }
32
-
33
- /**
34
- * Get the project-specific auto-memory directory.
35
- * Uses the git common directory to ensure worktrees share the same memory.
36
- */
37
- getAutoMemoryDirectory(workdir: string): string {
38
- const commonDir = getGitCommonDir(workdir);
39
- // If the common directory is a .git directory, use its parent as the project root
40
- // for a cleaner encoded name while maintaining stability across worktrees.
41
- const projectRoot =
42
- path.basename(commonDir) === ".git" ? path.dirname(commonDir) : commonDir;
43
- const encodedName = pathEncoder.encodeSync(projectRoot);
44
- return path.join(homedir(), ".wave", "projects", encodedName, "memory");
45
- }
46
-
47
- /**
48
- * Ensure the auto-memory directory and initial MEMORY.md exist.
49
- */
50
- async ensureAutoMemoryDirectory(workdir: string): Promise<void> {
51
- const memoryDir = this.getAutoMemoryDirectory(workdir);
52
- const memoryFile = path.join(memoryDir, "MEMORY.md");
53
-
54
- try {
55
- await fs.mkdir(memoryDir, { recursive: true });
56
-
57
- try {
58
- await fs.access(memoryFile);
59
- } catch (error) {
60
- if ((error as NodeJS.ErrnoException).code === "ENOENT") {
61
- const initialContent =
62
- "# Project Memory\n\nThis file serves as an index for the project's auto-memory. Wave uses this to track knowledge across sessions.\n\n";
63
- await fs.writeFile(memoryFile, initialContent, "utf-8");
64
- logger.debug(`Created auto-memory file: ${memoryFile}`);
65
- } else {
66
- throw error;
67
- }
68
- }
69
- } catch (error) {
70
- logger.error("Failed to ensure auto-memory directory:", error);
71
- throw new Error(
72
- `Failed to ensure auto-memory directory: ${(error as Error).message}`,
73
- );
74
- }
75
- }
76
-
77
- /**
78
- * Get the first 200 lines of MEMORY.md.
79
- */
80
- async getAutoMemoryContent(workdir: string): Promise<string> {
81
- if (this._cachedAutoMemoryContent !== null) {
82
- return this._cachedAutoMemoryContent;
83
- }
84
- const memoryDir = this.getAutoMemoryDirectory(workdir);
85
- const memoryFile = path.join(memoryDir, "MEMORY.md");
86
-
87
- try {
88
- const content = await fs.readFile(memoryFile, "utf-8");
89
- const lines = content.split("\n").slice(0, 200);
90
- this._cachedAutoMemoryContent = lines.join("\n");
91
- return this._cachedAutoMemoryContent;
92
- } catch (error) {
93
- if ((error as NodeJS.ErrnoException).code === "ENOENT") {
94
- this._cachedAutoMemoryContent = "";
95
- return "";
96
- }
97
- logger.error("Failed to read auto-memory content:", error);
98
- return "";
99
- }
100
- }
101
-
102
- async ensureUserMemoryFile(): Promise<void> {
103
- try {
104
- // Ensure data directory exists
105
- await fs.mkdir(DATA_DIRECTORY, { recursive: true });
106
-
107
- // Check if user memory file exists
108
- try {
109
- await fs.access(USER_MEMORY_FILE);
110
- } catch (error) {
111
- // File does not exist, create new file
112
- if ((error as NodeJS.ErrnoException).code === "ENOENT") {
113
- logger.info("Creating new user memory file", {
114
- userMemoryFile: USER_MEMORY_FILE,
115
- });
116
- const initialContent =
117
- "# User Memory\n\nThis is the user-level memory file, recording important information and context across projects.\n\n";
118
- await fs.writeFile(USER_MEMORY_FILE, initialContent, "utf-8");
119
- logger.debug(`Created user memory file: ${USER_MEMORY_FILE}`);
120
- } else {
121
- throw error;
122
- }
123
- }
124
- } catch (error) {
125
- logger.error("Failed to ensure user memory file:", error);
126
- throw new Error(
127
- `Failed to ensure user memory file: ${(error as Error).message}`,
128
- );
129
- }
130
- }
131
-
132
- async getUserMemoryContent(): Promise<string> {
133
- if (this._cachedUserMemory !== null) {
134
- return this._cachedUserMemory;
135
- }
136
- try {
137
- await this.ensureUserMemoryFile();
138
- const content = await fs.readFile(USER_MEMORY_FILE, "utf-8");
139
- logger.debug("User memory content read successfully", {
140
- userMemoryFile: USER_MEMORY_FILE,
141
- contentLength: content.length,
142
- });
143
-
144
- // If the file is still the default empty template, fallback to ~/.claude/AGENTS.md
145
- const defaultTemplate =
146
- "# User Memory\n\nThis is the user-level memory file, recording important information and context across projects.\n\n";
147
- if (content === defaultTemplate) {
148
- const claudeMemoryPath = path.join(homedir(), ".claude", "AGENTS.md");
149
- try {
150
- const claudeContent = await fs.readFile(claudeMemoryPath, "utf-8");
151
- logger.debug(
152
- "User memory content read from ~/.claude/AGENTS.md fallback",
153
- {
154
- claudeMemoryPath,
155
- contentLength: claudeContent.length,
156
- },
157
- );
158
- this._cachedUserMemory = claudeContent;
159
- return this._cachedUserMemory;
160
- } catch {
161
- // CLAUDE.md doesn't exist or can't be read, return the default template
162
- }
163
- }
164
-
165
- this._cachedUserMemory = content;
166
- return this._cachedUserMemory;
167
- } catch (error) {
168
- logger.error("Failed to read user memory:", error);
169
- return "";
170
- }
171
- }
172
-
173
- async readMemoryFile(workdir: string): Promise<string> {
174
- if (this._cachedProjectMemory !== null) {
175
- return this._cachedProjectMemory;
176
- }
177
- const memoryFilePath = path.join(workdir, "AGENTS.md");
178
- try {
179
- const content = await fs.readFile(memoryFilePath, "utf-8");
180
- logger.debug("Memory file read successfully via direct file access", {
181
- memoryFilePath,
182
- contentLength: content.length,
183
- });
184
- this._cachedProjectMemory = content;
185
- return this._cachedProjectMemory;
186
- } catch (error) {
187
- if ((error as NodeJS.ErrnoException).code === "ENOENT") {
188
- // Fallback to CLAUDE.md
189
- const claudeMemoryPath = path.join(workdir, "CLAUDE.md");
190
- try {
191
- const content = await fs.readFile(claudeMemoryPath, "utf-8");
192
- logger.debug("Memory file read from CLAUDE.md fallback", {
193
- memoryFilePath: claudeMemoryPath,
194
- contentLength: content.length,
195
- });
196
- this._cachedProjectMemory = content;
197
- return this._cachedProjectMemory;
198
- } catch (claudeError) {
199
- if ((claudeError as NodeJS.ErrnoException).code === "ENOENT") {
200
- logger.debug("Neither AGENTS.md nor CLAUDE.md found", {
201
- memoryFilePath,
202
- });
203
- this._cachedProjectMemory = "";
204
- return "";
205
- }
206
- logger.error("Failed to read CLAUDE.md fallback", {
207
- memoryFilePath: claudeMemoryPath,
208
- error: claudeError,
209
- });
210
- return "";
211
- }
212
- }
213
- logger.error("Failed to read memory file", { memoryFilePath, error });
214
- return "";
215
- }
216
- }
217
-
218
- async getCombinedMemoryContent(workdir: string): Promise<string> {
219
- if (this._cachedCombinedMemory !== null) {
220
- return this._cachedCombinedMemory;
221
- }
222
- const projectMemory = await this.readMemoryFile(workdir);
223
- const userMemory = await this.getUserMemoryContent();
224
-
225
- let combined = "";
226
- if (projectMemory.trim()) combined += projectMemory;
227
- if (userMemory.trim()) {
228
- if (combined) combined += "\n\n";
229
- combined += userMemory;
230
- }
231
- this._cachedCombinedMemory = combined;
232
- return combined;
233
- }
234
- }