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,493 +0,0 @@
1
- import { randomUUID } from "crypto";
2
- import * as os from "os";
3
- import * as fs from "fs";
4
- import * as path from "path";
5
- import { Container } from "../utils/container.js";
6
- import { BackgroundTaskManager } from "./backgroundTaskManager.js";
7
- import { MessageQueue } from "./messageQueue.js";
8
- import { SubagentManager } from "./subagentManager.js";
9
- import { taskNotificationToXml } from "../utils/notificationXml.js";
10
- import { ConcurrencyLimiter } from "../workflow/concurrencyLimiter.js";
11
- import { BudgetTracker } from "../workflow/budgetTracker.js";
12
- import { ProgressReporter } from "../workflow/progressReporter.js";
13
- import { Journal } from "../workflow/journal.js";
14
- import { createWorkflowApis } from "../workflow/workflowApis.js";
15
- import {
16
- validateScript,
17
- parseScript,
18
- executeScript,
19
- } from "../workflow/scriptRuntime.js";
20
- import type { WorkflowRun } from "../workflow/types.js";
21
- import { RunStateStore } from "../workflow/runState.js";
22
- import { logger } from "../utils/globalLogger.js";
23
-
24
- const DEFAULT_CONCURRENCY = () =>
25
- Math.max(1, Math.min(16, os.cpus().length - 2));
26
-
27
- export class WorkflowManager {
28
- private runs = new Map<string, WorkflowRun>();
29
- private abortControllers = new Map<string, AbortController>();
30
- private agentControllers = new Map<string, Map<number, AbortController>>();
31
- private container: Container;
32
- private runStateStore: RunStateStore | null = null;
33
-
34
- constructor(container: Container) {
35
- this.container = container;
36
- // Initialize RunStateStore lazily (sessionDir depends on MessageManager)
37
- }
38
-
39
- private get stateStore(): RunStateStore {
40
- if (!this.runStateStore) {
41
- this.runStateStore = new RunStateStore(
42
- path.join(this.sessionDir, "workflows"),
43
- );
44
- }
45
- return this.runStateStore;
46
- }
47
-
48
- private get backgroundTaskManager(): BackgroundTaskManager {
49
- return this.container.get<BackgroundTaskManager>("BackgroundTaskManager")!;
50
- }
51
-
52
- private get messageQueue(): MessageQueue {
53
- return this.container.get<MessageQueue>("MessageQueue")!;
54
- }
55
-
56
- private get subagentManager(): SubagentManager {
57
- return this.container.get<SubagentManager>("SubagentManager")!;
58
- }
59
-
60
- private get workdir(): string {
61
- return this.container.get<string>("workdir") || process.cwd();
62
- }
63
-
64
- private get sessionDir(): string {
65
- const messageManager =
66
- this.container.get<import("./messageManager.js").MessageManager>(
67
- "MessageManager",
68
- );
69
- return (
70
- messageManager?.getSessionDir() ||
71
- path.join(os.homedir(), ".wave", "sessions")
72
- );
73
- }
74
-
75
- /**
76
- * Create a new workflow run from a script string or file path.
77
- * Persists the script to the session directory.
78
- */
79
- async createRun(
80
- script: string,
81
- args?: unknown,
82
- opts?: { budget?: number | null; resumeFromRunId?: string },
83
- ): Promise<WorkflowRun> {
84
- // Validate script
85
- const validation = validateScript(script);
86
- if (!validation.valid) {
87
- throw new Error(
88
- `Script validation failed:\n${validation.errors.join("\n")}`,
89
- );
90
- }
91
-
92
- // Parse meta for the run object
93
- const { meta } = parseScript(script);
94
-
95
- // Validate resumeFromRunId if provided
96
- if (opts?.resumeFromRunId) {
97
- const prevRun = this.runs.get(opts.resumeFromRunId);
98
- if (!prevRun) {
99
- throw new Error(`Cannot resume: run ${opts.resumeFromRunId} not found`);
100
- }
101
- }
102
-
103
- // Generate run ID and persist script
104
- const runId = `wf_${randomUUID().slice(0, 8)}`;
105
- const runDir = path.join(this.sessionDir, "workflows", runId);
106
- await fs.promises.mkdir(path.join(runDir, "agents"), { recursive: true });
107
- const scriptPath = path.join(runDir, "script.js");
108
- await fs.promises.writeFile(scriptPath, script, "utf-8");
109
-
110
- const run: WorkflowRun = {
111
- runId,
112
- meta,
113
- status: "running",
114
- scriptPath,
115
- args,
116
- startTime: Date.now(),
117
- phases: [],
118
- totalAgents: 0,
119
- totalTokens: 0,
120
- resumeFromRunId: opts?.resumeFromRunId,
121
- };
122
-
123
- this.runs.set(runId, run);
124
-
125
- // Persist run state
126
- this.stateStore.save(run).catch((err) => {
127
- logger.warn(
128
- `[Workflow] Failed to persist run state: ${err instanceof Error ? err.message : String(err)}`,
129
- );
130
- });
131
-
132
- return run;
133
- }
134
-
135
- /**
136
- * Start executing a workflow run in the background.
137
- * Returns immediately; the workflow runs asynchronously.
138
- */
139
- async startRun(
140
- runId: string,
141
- opts?: { retryAgentIndex?: number },
142
- ): Promise<void> {
143
- const run = this.runs.get(runId);
144
- if (!run) throw new Error(`Workflow run ${runId} not found`);
145
- if (run.status !== "running")
146
- throw new Error(`Workflow run ${runId} is not in running state`);
147
-
148
- const abortController = new AbortController();
149
- this.abortControllers.set(runId, abortController);
150
- const runAgentControllers = new Map<number, AbortController>();
151
- this.agentControllers.set(runId, runAgentControllers);
152
-
153
- // Read script from file
154
- const script = await fs.promises.readFile(run.scriptPath, "utf-8");
155
-
156
- // Set up infrastructure
157
- const concurrencyLimiter = new ConcurrencyLimiter(DEFAULT_CONCURRENCY());
158
- const budgetTracker = new BudgetTracker(
159
- run.args &&
160
- typeof run.args === "object" &&
161
- "budget" in (run.args as Record<string, unknown>)
162
- ? ((run.args as Record<string, unknown>).budget as number | null)
163
- : null,
164
- );
165
- const progressReporter = new ProgressReporter(run.meta, runId);
166
-
167
- // Forward progress events: mirror live counts onto the WorkflowRun and
168
- // trigger a UI refresh so /workflows updates mid-execution (not just at
169
- // completion). The UI reads getWorkflowRuns() -> listRuns(), which returns
170
- // these same in-memory run objects.
171
- const onProgress = (
172
- event: import("../workflow/types.js").WorkflowProgressEvent,
173
- ) => {
174
- logger.debug(
175
- `[Workflow:${runId}] progress: ${event.type} phase=${event.phaseIndex} agent=${event.agentIndex}`,
176
- );
177
- run.phases = progressReporter.getPhaseStates();
178
- run.totalAgents = progressReporter.totalAgents;
179
- run.totalTokens = progressReporter.totalTokens;
180
- this.backgroundTaskManager.notifyTasksChange();
181
- };
182
- progressReporter.onEvent(onProgress);
183
-
184
- // Journal — load previous journal if resuming
185
- let journal: Journal;
186
- let initialAgentCount = 0;
187
- if (run.resumeFromRunId || opts?.retryAgentIndex !== undefined) {
188
- // Try new-format path first, fall back to old format
189
- const sourceRunId = run.resumeFromRunId || runId;
190
- const newJournalPath = path.join(
191
- this.sessionDir,
192
- "workflows",
193
- sourceRunId,
194
- "journal.jsonl",
195
- );
196
- const oldJournalPath = path.join(
197
- this.sessionDir,
198
- "workflows",
199
- `journal-${sourceRunId}.jsonl`,
200
- );
201
- const journalPath = (await fs.promises
202
- .access(newJournalPath)
203
- .then(() => true)
204
- .catch(() => false))
205
- ? newJournalPath
206
- : oldJournalPath;
207
- journal = await Journal.load(journalPath);
208
-
209
- // When retrying a specific agent, remove its failed entry
210
- if (opts?.retryAgentIndex !== undefined) {
211
- journal.removeFailedEntry(opts.retryAgentIndex);
212
- }
213
-
214
- // Count existing agent entries to offset the counter
215
- initialAgentCount = journal.agentEntryCount;
216
- // Re-open for appending (load() doesn't open the write stream)
217
- await journal.init();
218
- logger.info(
219
- `[Workflow] Resuming from ${sourceRunId} with ${initialAgentCount} cached agent results`,
220
- );
221
- } else {
222
- const journalPath = path.join(
223
- this.sessionDir,
224
- "workflows",
225
- runId,
226
- "journal.jsonl",
227
- );
228
- journal = new Journal(journalPath);
229
- await journal.init();
230
- }
231
-
232
- // Register as background task
233
- const taskId = this.backgroundTaskManager.generateId();
234
- this.backgroundTaskManager.addTask({
235
- id: taskId,
236
- type: "workflow",
237
- status: "running",
238
- startTime: Date.now(),
239
- stdout: "",
240
- stderr: "",
241
- description: `Workflow: ${run.meta.name}`,
242
- runId,
243
- onStop: () => {
244
- abortController.abort();
245
- },
246
- });
247
-
248
- // Create workflow APIs
249
- const apis = createWorkflowApis({
250
- subagentManager: this.subagentManager,
251
- concurrencyLimiter,
252
- budgetTracker,
253
- progressReporter,
254
- journal,
255
- abortSignal: abortController.signal,
256
- args: run.args,
257
- initialAgentCount,
258
- sessionDir: this.sessionDir,
259
- runDir: path.join(this.sessionDir, "workflows", runId),
260
- agentControllers: runAgentControllers,
261
- onLog: (message: string) => {
262
- logger.info(`[Workflow:${runId}] ${message}`);
263
- },
264
- });
265
-
266
- // Execute in background
267
- run.completionPromise = (async () => {
268
- try {
269
- const { result } = await executeScript(
270
- script,
271
- apis,
272
- abortController.signal,
273
- );
274
-
275
- // Update run state
276
- run.status = "completed";
277
- run.endTime = Date.now();
278
- run.result = result;
279
- run.phases = progressReporter.getPhaseStates();
280
- run.totalAgents = progressReporter.totalAgents;
281
- run.totalTokens = progressReporter.totalTokens;
282
-
283
- // Persist final state
284
- this.stateStore.save(run).catch(() => {});
285
-
286
- // Close journal
287
- await journal.close();
288
-
289
- // Update background task status
290
- const task = this.backgroundTaskManager.getTask(taskId);
291
- if (task) {
292
- task.status = "completed";
293
- task.endTime = Date.now();
294
- }
295
-
296
- // Enqueue completion notification
297
- const journalPath = journal.filePath;
298
- this.messageQueue.enqueueNotification(
299
- taskNotificationToXml({
300
- type: "task_notification",
301
- taskId: runId,
302
- taskType: "workflow",
303
- status: "completed",
304
- summary: `Workflow "${run.meta.name}" completed — ${run.totalAgents} agents, ${(run.totalTokens / 1000).toFixed(1)}k tokens`,
305
- ...(journalPath && { outputFile: journalPath }),
306
- }),
307
- );
308
-
309
- logger.info(
310
- `[Workflow] Run ${runId} completed: ${run.totalAgents} agents, ${run.totalTokens} tokens`,
311
- );
312
- } catch (error) {
313
- // Only update if stopRun hasn't already set the status
314
- if (run.status === "running") {
315
- if (abortController.signal.aborted) {
316
- run.status = "aborted";
317
- } else {
318
- run.status = "failed";
319
- run.error = error instanceof Error ? error.message : String(error);
320
- }
321
- run.endTime = Date.now();
322
- }
323
- run.phases = progressReporter.getPhaseStates();
324
- run.totalAgents = progressReporter.totalAgents;
325
- run.totalTokens = progressReporter.totalTokens;
326
-
327
- // Persist failure/abort state
328
- this.stateStore.save(run).catch(() => {});
329
-
330
- await journal.close();
331
-
332
- // Update background task status
333
- const task = this.backgroundTaskManager.getTask(taskId);
334
- if (task) {
335
- task.status = abortController.signal.aborted ? "killed" : "failed";
336
- task.stderr = run.error || "";
337
- task.endTime = Date.now();
338
- }
339
-
340
- this.messageQueue.enqueueNotification(
341
- taskNotificationToXml({
342
- type: "task_notification",
343
- taskId: runId,
344
- taskType: "workflow",
345
- status: run.status === "aborted" ? "aborted" : "failed",
346
- summary: `Workflow "${run.meta.name}" ${run.status}${run.error ? `: ${run.error}` : ""}`,
347
- }),
348
- );
349
-
350
- logger.warn(
351
- `[Workflow] Run ${runId} ${run.status}: ${run.error || "aborted"}`,
352
- );
353
- } finally {
354
- this.abortControllers.delete(runId);
355
- this.agentControllers.delete(runId);
356
- }
357
- })();
358
-
359
- // Don't await — let it run in background
360
- run.completionPromise.catch(() => {}); // Prevent unhandled rejection
361
- }
362
-
363
- /**
364
- * Resume a workflow run from its journal.
365
- */
366
- async resumeRun(runId: string): Promise<void> {
367
- const run = this.runs.get(runId);
368
- if (!run) throw new Error(`Workflow run ${runId} not found`);
369
-
370
- run.status = "running";
371
- await this.startRun(runId);
372
- }
373
-
374
- /**
375
- * Stop a running workflow.
376
- */
377
- stopRun(runId: string): void {
378
- const controller = this.abortControllers.get(runId);
379
- if (controller) {
380
- controller.abort();
381
- }
382
- const run = this.runs.get(runId);
383
- if (run && run.status === "running") {
384
- run.status = "aborted";
385
- run.endTime = Date.now();
386
- }
387
- }
388
-
389
- /**
390
- * Skip a specific agent in a running workflow.
391
- * Aborts the agent's controller and lets the workflow continue.
392
- */
393
- skipAgent(runId: string, agentIndex: number): void {
394
- const run = this.runs.get(runId);
395
- if (!run || run.status !== "running") return;
396
-
397
- const agentController = this.agentControllers.get(runId)?.get(agentIndex);
398
- if (agentController) {
399
- agentController.abort();
400
- }
401
- }
402
-
403
- /**
404
- * Retry a specific agent by removing its journal entry and resuming.
405
- */
406
- async retryAgent(runId: string, agentIndex: number): Promise<void> {
407
- const run = this.runs.get(runId);
408
- if (!run) throw new Error(`Workflow run ${runId} not found`);
409
-
410
- // Stop the current execution
411
- this.stopRun(runId);
412
-
413
- // The journal will have cached results; when we resume,
414
- // the agent_failed entry for this index will cause getCachedResult
415
- // to return undefined, forcing re-execution
416
- run.status = "running";
417
- run.error = undefined;
418
- run.failedAgentIndex = undefined;
419
- run.failedAgentError = undefined;
420
- await this.startRun(runId, { retryAgentIndex: agentIndex });
421
- }
422
-
423
- /**
424
- * Kill a running workflow — aborts all agent controllers plus the run controller.
425
- */
426
- killRun(runId: string): void {
427
- // Abort all per-agent controllers
428
- const agentControllers = this.agentControllers.get(runId);
429
- if (agentControllers) {
430
- for (const controller of agentControllers.values()) {
431
- controller.abort();
432
- }
433
- }
434
-
435
- // Abort the run controller
436
- const controller = this.abortControllers.get(runId);
437
- if (controller) {
438
- controller.abort();
439
- }
440
-
441
- const run = this.runs.get(runId);
442
- if (run && run.status === "running") {
443
- run.status = "aborted";
444
- run.endTime = Date.now();
445
- }
446
- }
447
-
448
- /**
449
- * List all workflow runs (includes in-memory and persisted).
450
- */
451
- async listRuns(): Promise<WorkflowRun[]> {
452
- // Load persisted runs that aren't already in memory
453
- const persistedIds = await this.stateStore.listRuns();
454
- for (const runId of persistedIds) {
455
- if (!this.runs.has(runId)) {
456
- const run = await this.stateStore.load(runId);
457
- if (run) {
458
- this.runs.set(runId, run);
459
- }
460
- }
461
- }
462
- return Array.from(this.runs.values());
463
- }
464
-
465
- /**
466
- * Get a specific workflow run.
467
- */
468
- getRun(runId: string): WorkflowRun | undefined {
469
- return this.runs.get(runId);
470
- }
471
-
472
- /**
473
- * Clean up all running workflows.
474
- */
475
- cleanup(): void {
476
- for (const controller of this.abortControllers.values()) {
477
- controller.abort();
478
- }
479
- this.abortControllers.clear();
480
- for (const agentMap of this.agentControllers.values()) {
481
- for (const controller of agentMap.values()) {
482
- controller.abort();
483
- }
484
- }
485
- this.agentControllers.clear();
486
- for (const run of this.runs.values()) {
487
- if (run.status === "running") {
488
- run.status = "aborted";
489
- run.endTime = Date.now();
490
- }
491
- }
492
- }
493
- }
@@ -1,33 +0,0 @@
1
- export function buildAutoMemoryPrompt(memoryDir: string): string {
2
- return `
3
- # auto memory
4
-
5
- You have a persistent auto memory directory at \`${memoryDir}\`. Its contents persist across conversations.
6
-
7
- As you work, consult your memory files to build on previous experience.
8
-
9
- ## How to save memories:
10
- - Organize memory semantically by topic, not chronologically
11
- - Use the Write and Edit tools to update your memory files
12
- - \`MEMORY.md\` is always loaded into your conversation context — lines after 200 will be truncated, so keep it concise
13
- - Create separate topic files (e.g., \`debugging.md\`, \`patterns.md\`) for detailed notes and link to them from MEMORY.md
14
- - Update or remove memories that turn out to be wrong or outdated
15
- - Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one.
16
-
17
- ## What to save:
18
- - Stable patterns and conventions confirmed across multiple interactions
19
- - Key architectural decisions, important file paths, and project structure
20
- - User preferences for workflow, tools, and communication style
21
- - Solutions to recurring problems and debugging insights
22
-
23
- ## What NOT to save:
24
- - Session-specific context (current task details, in-progress work, temporary state)
25
- - Information that might be incomplete — verify against project docs before writing
26
- - Anything that duplicates or contradicts existing AGENTS.md instructions
27
- - Speculative or unverified conclusions from reading a single file
28
-
29
- ## Explicit user requests:
30
- - When the user asks you to remember something across sessions (e.g., "always use bun", "never auto-commit"), save it — no need to wait for multiple interactions
31
- - When the user asks to forget or stop remembering something, find and remove the relevant entries from your memory files
32
- `;
33
- }
@@ -1,146 +0,0 @@
1
- /**
2
- * Memory types taxonomy and examples.
3
- */
4
- const MEMORY_TYPES = ["user", "feedback", "project", "reference"] as const;
5
-
6
- const TYPES_SECTION = [
7
- "## Types of memory",
8
- "",
9
- "There are several discrete types of memory that you can store in your memory system:",
10
- "",
11
- "<types>",
12
- "<type>",
13
- " <name>user</name>",
14
- " <description>Contain information about the user's role, goals, responsibilities, and knowledge. Great user memories help you tailor your future behavior to the user's preferences and perspective. Your goal in reading and writing these memories is to build up an understanding of who the user is and how you can be most helpful to them specifically. For example, you should collaborate with a senior software engineer differently than a student who is coding for the very first time. Keep in mind, that the aim here is to be helpful to the user. Avoid writing memories about the user that could be viewed as a negative judgement or that are not relevant to the work you're trying to accomplish together.</description>",
15
- " <when_to_save>When you learn any details about the user's role, preferences, responsibilities, or knowledge</when_to_save>",
16
- " <how_to_use>When your work should be informed by the user's profile or perspective. For example, if the user is asking you to explain a part of the code, you should answer that question in a way that is tailored to the specific details that they will find most valuable or that helps them build their mental model in relation to domain knowledge they already have.</how_to_use>",
17
- " <examples>",
18
- " user: I'm a data scientist investigating what logging we have in place",
19
- " assistant: [saves user memory: user is a data scientist, currently focused on observability/logging]",
20
- "",
21
- " user: I've been writing Go for ten years but this is my first time touching the React side of this repo",
22
- " assistant: [saves user memory: deep Go expertise, new to React and this project's frontend — frame frontend explanations in terms of backend analogues]",
23
- " </examples>",
24
- "</type>",
25
- "<type>",
26
- " <name>feedback</name>",
27
- " <description>Guidance the user has given you about how to approach work — both what to avoid and what to keep doing. These are a very important type of memory to read and write as they allow you to remain coherent and responsive to the way you should approach work in the project. Record from failure AND success: if you only save corrections, you will avoid past mistakes but drift away from approaches the user has already validated, and may grow overly cautious.</description>",
28
- ' <when_to_save>Any time the user corrects your approach ("no not that", "don\'t", "stop doing X") OR confirms a non-obvious approach worked ("yes exactly", "perfect, keep doing that", accepting an unusual choice without pushback). Corrections are easy to notice; confirmations are quieter — watch for them. In both cases, save what is applicable to future conversations, especially if surprising or not obvious from the code. Include *why* so you can judge edge cases later.</when_to_save>',
29
- " <how_to_use>Let these memories guide your behavior so that the user does not need to offer the same guidance twice.</how_to_use>",
30
- " <body_structure>Lead with the rule itself, then a **Why:** line (the reason the user gave — often a past incident or strong preference) and a **How to apply:** line (when/where this guidance kicks in). Knowing *why* lets you judge edge cases instead of blindly following the rule.</body_structure>",
31
- " <examples>",
32
- " user: don't mock the database in these tests — we got burned last quarter when mocked tests passed but the prod migration failed",
33
- " assistant: [saves feedback memory: integration tests must hit a real database, not mocks. Reason: prior incident where mock/prod divergence masked a broken migration]",
34
- "",
35
- " user: stop summarizing what you just did at the end of every response, I can read the diff",
36
- " assistant: [saves feedback memory: this user wants terse responses with no trailing summaries]",
37
- "",
38
- " user: yeah the single bundled PR was the right call here, splitting this one would've just been churn",
39
- " assistant: [saves feedback memory: for refactors in this area, user prefers one bundled PR over many small ones. Confirmed after I chose this approach — a validated judgment call, not a correction]",
40
- " </examples>",
41
- "</type>",
42
- "<type>",
43
- " <name>project</name>",
44
- " <description>Information that you learn about ongoing work, goals, initiatives, bugs, or incidents within the project that is not otherwise derivable from the code or git history. Project memories help you understand the broader context and motivation behind the work the user is doing within this working directory.</description>",
45
- ' <when_to_save>When you learn who is doing what, why, or by when. These states change relatively quickly so try to keep your understanding of this up to date. Always convert relative dates in user messages to absolute dates when saving (e.g., "Thursday" → "2026-03-05"), so the memory remains interpretable after time passes.</when_to_save>',
46
- " <how_to_use>Use these memories to more fully understand the details and nuance behind the user's request and make better informed suggestions.</how_to_use>",
47
- " <body_structure>Lead with the fact or decision, then a **Why:** line (the motivation — often a constraint, deadline, or stakeholder ask) and a **How to apply:** line (how this should shape your suggestions). Project memories decay fast, so the why helps future-you judge whether the memory is still load-bearing.</body_structure>",
48
- " <examples>",
49
- " user: we're freezing all non-critical merges after Thursday — mobile team is cutting a release branch",
50
- " assistant: [saves project memory: merge freeze begins 2026-03-05 for mobile release cut. Flag any non-critical PR work scheduled after that date]",
51
- "",
52
- " user: the reason we're ripping out the old auth middleware is that legal flagged it for storing session tokens in a way that doesn't meet the new compliance requirements",
53
- " assistant: [saves project memory: auth middleware rewrite is driven by legal/compliance requirements around session token storage, not tech-debt cleanup — scope decisions should favor compliance over ergonomics]",
54
- " </examples>",
55
- "</type>",
56
- "<type>",
57
- " <name>reference</name>",
58
- " <description>Stores pointers to where information can be found in external systems. These memories allow you to remember where to look to find up-to-date information outside of the project directory.</description>",
59
- " <when_to_save>When you learn about resources in external systems and their purpose. For example, that bugs are tracked in a specific project in Linear or that feedback can be found in a specific Slack channel.</when_to_save>",
60
- " <how_to_use>When the user references an external system or information that may be in an external system.</how_to_use>",
61
- " <examples>",
62
- ' user: check the Linear project "INGEST" if you want context on these tickets, that\'s where we track all pipeline bugs',
63
- ' assistant: [saves reference memory: pipeline bugs are tracked in Linear project "INGEST"]',
64
- "",
65
- " user: the Grafana board at grafana.internal/d/api-latency is what oncall watches — if you're touching request handling, that's the thing that'll page someone",
66
- " assistant: [saves reference memory: grafana.internal/d/api-latency is the oncall latency dashboard — check it when editing request-path code]",
67
- " </examples>",
68
- "</type>",
69
- "</types>",
70
- ].join("\n");
71
-
72
- const WHAT_NOT_TO_SAVE_SECTION = [
73
- "## What NOT to save in memory",
74
- "",
75
- "- Code patterns, conventions, architecture, file paths, or project structure — these can be derived by reading the current project state.",
76
- "- Git history, recent changes, or who-changed-what — `git log` / `git blame` are authoritative.",
77
- "- Debugging solutions or fix recipes — the fix is in the code; the commit message has the context.",
78
- "- Anything already documented in CLAUDE.md files.",
79
- "- Ephemeral task details: in-progress work, temporary state, current conversation context.",
80
- "",
81
- "These exclusions apply even when the user explicitly asks you to save. If they ask you to save a PR list or activity summary, ask what was *surprising* or *non-obvious* about it — that is the part worth keeping.",
82
- ].join("\n");
83
-
84
- const MEMORY_FRONTMATTER_EXAMPLE = [
85
- "```markdown",
86
- "---",
87
- "name: {{memory name}}",
88
- "description: {{one-line description — used to decide relevance in future conversations, so be specific}}",
89
- `type: {{${MEMORY_TYPES.join(", ")}}}`,
90
- "---",
91
- "",
92
- "{{memory content — for feedback/project types, structure as: rule/fact, then **Why:** and **How to apply:** lines}}",
93
- "```",
94
- ].join("\n");
95
-
96
- /**
97
- * Build the auto-memory extraction prompt for the background agent.
98
- */
99
- export function buildAutoMemoryExtractionPrompt(
100
- newMessageCount: number,
101
- existingMemoriesManifest: string,
102
- ): string {
103
- const manifestSection =
104
- existingMemoriesManifest.length > 0
105
- ? `\n\n## Existing memory files\n\n${existingMemoriesManifest}\n\nCheck this list before writing — update an existing file rather than creating a duplicate.`
106
- : "";
107
-
108
- const howToSave = [
109
- "## How to save memories",
110
- "",
111
- "Saving a memory is a two-step process:",
112
- "",
113
- "**Step 1** — write the memory to its own file (e.g., `user_role.md`, `feedback_testing.md`) using this frontmatter format:",
114
- "",
115
- MEMORY_FRONTMATTER_EXAMPLE,
116
- "",
117
- "**Step 2** — add a pointer to that file in `MEMORY.md`. `MEMORY.md` is an index, not a memory — each entry should be one line, under ~150 characters: `- [Title](file.md) — one-line hook`. It has no frontmatter. Never write memory content directly into `MEMORY.md`.",
118
- "",
119
- "- `MEMORY.md` is always loaded into your system prompt — lines after 200 will be truncated, so keep the index concise",
120
- "- Organize memory semantically by topic, not chronologically",
121
- "- Update or remove memories that turn out to be wrong or outdated",
122
- "- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one.",
123
- ].join("\n");
124
-
125
- return [
126
- `You are now acting as the memory extraction subagent. Analyze the most recent ~${newMessageCount} messages above and use them to update your persistent memory systems.`,
127
- "",
128
- `Available tools: Read, Grep, Glob, read-only Bash (ls/find/cat/stat/wc/head/tail and similar), and Write/Edit for paths inside the memory directory only. Bash rm is not permitted. All other tools — MCP, Agent, write-capable Bash, etc — will be denied.`,
129
- "",
130
- `You have a limited turn budget. Edit requires a prior Read of the same file, so the efficient strategy is: turn 1 — issue all Read calls in parallel for every file you might update; turn 2 — issue all Write/Edit calls in parallel. Do not interleave reads and writes across multiple turns.`,
131
- "",
132
- `You MUST only use content from the last ~${newMessageCount} messages to update your persistent memories. Do not waste any turns attempting to investigate or verify that content further — no grepping source files, no reading code to confirm a pattern exists, no git commands.` +
133
- manifestSection,
134
- "",
135
- "If the user explicitly asks you to remember something, save it immediately as whichever type fits best. If they ask you to forget something, find and remove the relevant entry.",
136
- "",
137
- TYPES_SECTION,
138
- "",
139
- WHAT_NOT_TO_SAVE_SECTION,
140
- "",
141
- howToSave,
142
- "",
143
- "### Task:",
144
- "Extract new memories from the latest turns and save them to the memory directory.",
145
- ].join("\n");
146
- }