@swifty.js/swifty 0.0.27 → 0.0.28
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/README.md +14 -6
- package/dist/agent-3NON2EXE.js +4 -0
- package/dist/anthropic-BJ5GN2VT.js +4 -0
- package/dist/checker-N5TIJEN5.js +4 -0
- package/dist/chunk-D34FUVGU.js +4 -0
- package/dist/chunk-JGSIQXEN.js +4 -0
- package/dist/{chunk-UGJVMFGH.js → chunk-K5ZK27BX.js} +1 -1
- package/dist/chunk-LZBOXJX2.js +301 -0
- package/dist/chunk-OTVZGPHD.js +121 -0
- package/dist/chunk-QCKJLO6X.js +4 -0
- package/dist/chunk-R63ASIIW.js +407 -0
- package/dist/chunk-WX3B64R4.js +4 -0
- package/dist/chunk-Y6SQB5FG.js +4 -0
- package/dist/glob.wasm +0 -0
- package/dist/lib/agent-XYO2MXXK.js +11 -0
- package/dist/lib/{anthropic-RYPJDHQM.js → anthropic-TGJGAP5R.js} +4 -5
- package/dist/lib/{checker-6BW4222R.js → checker-AXHPKVBY.js} +2 -2
- package/dist/lib/{chunk-HK2Z6WP4.js → chunk-2IVEVG5N.js} +5 -1
- package/dist/lib/{chunk-2AUSNVIB.js → chunk-ALJAVRRX.js} +28 -34
- package/dist/lib/{chunk-GNI7YX6F.js → chunk-DJ6AILPN.js} +70 -24
- package/dist/lib/chunk-DV6RV5WU.js +2345 -0
- package/dist/lib/{chunk-3LU4APFB.js → chunk-FBSPZQGC.js} +126 -73
- package/dist/lib/chunk-IB5IQK2S.js +136 -0
- package/dist/lib/{chunk-PZ42NAFA.js → chunk-KG4MJGKQ.js} +19 -21
- package/dist/lib/{chunk-XFSN4LMA.js → chunk-P4F46PEF.js} +43 -14
- package/dist/lib/glob.wasm +0 -0
- package/dist/lib/index.d.ts +145 -123
- package/dist/lib/index.js +2185 -1722
- package/dist/lib/{openai-VX5VBXZ4.js → openai-5UCIIDPO.js} +2 -3
- package/dist/lib/{tool-filter-VF7TZRE5.js → tool-filter-R6HDDJHE.js} +1 -1
- package/dist/main.js +204 -195
- package/dist/{openai-5FDSLJNM.js → openai-YLS2LUAI.js} +14 -14
- package/dist/{server-F666APPN.js → server-GX72MJQF.js} +21 -21
- package/dist/{tool-filter-NO7I3HFD.js → tool-filter-VBP6WOGO.js} +1 -1
- package/package.json +1 -1
- package/dist/agent-OMC6YIMW.js +0 -4
- package/dist/anthropic-T5K4BQPB.js +0 -4
- package/dist/checker-TOQVEG3P.js +0 -4
- package/dist/chunk-5I2WXSGV.js +0 -90
- package/dist/chunk-A2VR3BC4.js +0 -4
- package/dist/chunk-A57FEYSN.js +0 -4
- package/dist/chunk-BRC5L644.js +0 -130
- package/dist/chunk-FZPTNGTU.js +0 -4
- package/dist/chunk-G6YIQW3Z.js +0 -238
- package/dist/chunk-I2XG2PXV.js +0 -4
- package/dist/chunk-LVSHXIBK.js +0 -389
- package/dist/chunk-SULWNDNC.js +0 -4
- package/dist/chunk-WO6DL7OB.js +0 -35
- package/dist/lib/agent-U7MIUCKT.js +0 -9
- package/dist/lib/chunk-2QILP24G.js +0 -1120
- package/dist/lib/chunk-OO2CLOEE.js +0 -88
- package/dist/lib/chunk-RKJYTYQM.js +0 -1285
|
@@ -1,1285 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
AutoCompactTrackingState,
|
|
3
|
-
forceCompact,
|
|
4
|
-
getSessionFilePath,
|
|
5
|
-
manageContext,
|
|
6
|
-
saveMessage,
|
|
7
|
-
toolResultsToRecords,
|
|
8
|
-
toolUsesToRecords
|
|
9
|
-
} from "./chunk-2QILP24G.js";
|
|
10
|
-
import {
|
|
11
|
-
ContextTooLongError,
|
|
12
|
-
REJECTED_TOOL_RESULT,
|
|
13
|
-
RateLimitError
|
|
14
|
-
} from "./chunk-OO2CLOEE.js";
|
|
15
|
-
import {
|
|
16
|
-
asErrorString,
|
|
17
|
-
asRecord,
|
|
18
|
-
createChildLogger,
|
|
19
|
-
isObject,
|
|
20
|
-
strArg
|
|
21
|
-
} from "./chunk-EY7HE52Q.js";
|
|
22
|
-
|
|
23
|
-
// src/compact/recovery.ts
|
|
24
|
-
var RECOVERY_FILE_LIMIT = 5;
|
|
25
|
-
var RECOVERY_TOKENS_PER_FILE = 5e3;
|
|
26
|
-
var RECOVERY_SKILLS_BUDGET = 25e3;
|
|
27
|
-
var RECOVERY_TOKENS_PER_SKILL = 5e3;
|
|
28
|
-
var RECOVERY_CHARS_PER_TOKEN = 3.5;
|
|
29
|
-
function approxTokens(s) {
|
|
30
|
-
if (!s) {
|
|
31
|
-
return 0;
|
|
32
|
-
}
|
|
33
|
-
return Math.floor(s.length / RECOVERY_CHARS_PER_TOKEN);
|
|
34
|
-
}
|
|
35
|
-
function truncateByTokens(s, tokenBudget) {
|
|
36
|
-
if (tokenBudget <= 0 || !s) {
|
|
37
|
-
return s;
|
|
38
|
-
}
|
|
39
|
-
if (approxTokens(s) <= tokenBudget) {
|
|
40
|
-
return s;
|
|
41
|
-
}
|
|
42
|
-
const maxChars = Math.floor(tokenBudget * RECOVERY_CHARS_PER_TOKEN);
|
|
43
|
-
if (maxChars <= 0 || maxChars >= s.length) {
|
|
44
|
-
return s;
|
|
45
|
-
}
|
|
46
|
-
const suffix = "\n\u2026 (content truncated)";
|
|
47
|
-
if (maxChars <= suffix.length) {
|
|
48
|
-
return suffix.slice(0, maxChars);
|
|
49
|
-
}
|
|
50
|
-
return s.slice(0, maxChars - suffix.length) + suffix;
|
|
51
|
-
}
|
|
52
|
-
var RecoveryState = class {
|
|
53
|
-
files = /* @__PURE__ */ new Map();
|
|
54
|
-
skills = /* @__PURE__ */ new Map();
|
|
55
|
-
recordFileRead(path, content) {
|
|
56
|
-
this.files.delete(path);
|
|
57
|
-
this.files.set(path, {
|
|
58
|
-
path,
|
|
59
|
-
content: truncateByTokens(content, RECOVERY_TOKENS_PER_FILE),
|
|
60
|
-
timestamp: Date.now()
|
|
61
|
-
});
|
|
62
|
-
while (this.files.size > RECOVERY_FILE_LIMIT) {
|
|
63
|
-
const oldestPath = this.files.keys().next().value;
|
|
64
|
-
if (typeof oldestPath !== "string") {
|
|
65
|
-
break;
|
|
66
|
-
}
|
|
67
|
-
this.files.delete(oldestPath);
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
recordSkillInvocation(name, body) {
|
|
71
|
-
this.skills.set(name, { name, body, timestamp: Date.now() });
|
|
72
|
-
}
|
|
73
|
-
snapshotFiles(limit = RECOVERY_FILE_LIMIT) {
|
|
74
|
-
const sorted = [...this.files.values()].sort((a, b) => b.timestamp - a.timestamp);
|
|
75
|
-
return sorted.slice(0, limit);
|
|
76
|
-
}
|
|
77
|
-
snapshotSkills() {
|
|
78
|
-
return [...this.skills.values()].sort((a, b) => b.timestamp - a.timestamp);
|
|
79
|
-
}
|
|
80
|
-
buildRecoveryAttachment(toolSchemaNames) {
|
|
81
|
-
const sections = [];
|
|
82
|
-
const recentFiles = this.snapshotFiles();
|
|
83
|
-
if (recentFiles.length > 0) {
|
|
84
|
-
sections.push("## Recently read files\n");
|
|
85
|
-
sections.push(
|
|
86
|
-
"These snapshots are what the file-reading tool last returned. Re-open with the tool if you need the current bytes.\n"
|
|
87
|
-
);
|
|
88
|
-
for (const f of recentFiles) {
|
|
89
|
-
const content = truncateByTokens(f.content, RECOVERY_TOKENS_PER_FILE);
|
|
90
|
-
const ts = new Date(f.timestamp).toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
91
|
-
sections.push(
|
|
92
|
-
`### ${f.path} (read ${ts})
|
|
93
|
-
|
|
94
|
-
\`\`\`
|
|
95
|
-
${content}${content.endsWith("\n") ? "" : "\n"}\`\`\``
|
|
96
|
-
);
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
const skills = this.snapshotSkills();
|
|
100
|
-
if (skills.length > 0) {
|
|
101
|
-
let used = 0;
|
|
102
|
-
const skillParts = [];
|
|
103
|
-
skillParts.push("## Active skills\n");
|
|
104
|
-
skillParts.push(
|
|
105
|
-
"These skills were invoked earlier in the session. Continue to follow each SOP when its triggering condition applies.\n"
|
|
106
|
-
);
|
|
107
|
-
let emitted = false;
|
|
108
|
-
for (const sk of skills) {
|
|
109
|
-
const body = truncateByTokens(sk.body, RECOVERY_TOKENS_PER_SKILL);
|
|
110
|
-
const tokens = approxTokens(body) + approxTokens(sk.name) + 8;
|
|
111
|
-
if (used + tokens > RECOVERY_SKILLS_BUDGET) {
|
|
112
|
-
break;
|
|
113
|
-
}
|
|
114
|
-
used += tokens;
|
|
115
|
-
skillParts.push(`### ${sk.name}
|
|
116
|
-
|
|
117
|
-
${body}`);
|
|
118
|
-
emitted = true;
|
|
119
|
-
}
|
|
120
|
-
if (emitted) {
|
|
121
|
-
sections.push(skillParts.join("\n\n"));
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
if (toolSchemaNames.length > 0) {
|
|
125
|
-
sections.push(
|
|
126
|
-
"## Available tools\n\nYou still have access to the following tools \u2014 call them directly when the task needs one:\n\n" + toolSchemaNames.map((n) => `- ${n}`).join("\n")
|
|
127
|
-
);
|
|
128
|
-
}
|
|
129
|
-
if (sections.length === 0) {
|
|
130
|
-
return "";
|
|
131
|
-
}
|
|
132
|
-
sections.push(
|
|
133
|
-
"## Note\n\nEverything above the divider is reconstructed context. For exact code, error strings, or user-typed text, re-read the source rather than guess from the summary."
|
|
134
|
-
);
|
|
135
|
-
return sections.join("\n\n");
|
|
136
|
-
}
|
|
137
|
-
};
|
|
138
|
-
|
|
139
|
-
// src/plan-file/plan-file.ts
|
|
140
|
-
import { readFileSync, writeFileSync, mkdirSync, existsSync } from "fs";
|
|
141
|
-
import { join, resolve } from "path";
|
|
142
|
-
var log = createChildLogger({ module: "plan-file" });
|
|
143
|
-
var ADJECTIVES = [
|
|
144
|
-
"brave",
|
|
145
|
-
"calm",
|
|
146
|
-
"dark",
|
|
147
|
-
"eager",
|
|
148
|
-
"fair",
|
|
149
|
-
"gentle",
|
|
150
|
-
"happy",
|
|
151
|
-
"kind",
|
|
152
|
-
"lively",
|
|
153
|
-
"mighty",
|
|
154
|
-
"noble",
|
|
155
|
-
"proud",
|
|
156
|
-
"quiet",
|
|
157
|
-
"swift",
|
|
158
|
-
"warm",
|
|
159
|
-
"wise"
|
|
160
|
-
];
|
|
161
|
-
var NOUNS = [
|
|
162
|
-
"crystal",
|
|
163
|
-
"dragon",
|
|
164
|
-
"eagle",
|
|
165
|
-
"falcon",
|
|
166
|
-
"flame",
|
|
167
|
-
"forest",
|
|
168
|
-
"frost",
|
|
169
|
-
"mountain",
|
|
170
|
-
"ocean",
|
|
171
|
-
"phoenix",
|
|
172
|
-
"river",
|
|
173
|
-
"shadow",
|
|
174
|
-
"thunder",
|
|
175
|
-
"tiger"
|
|
176
|
-
];
|
|
177
|
-
function generateSlug() {
|
|
178
|
-
const adj = ADJECTIVES[Math.floor(Math.random() * ADJECTIVES.length)];
|
|
179
|
-
const noun = NOUNS[Math.floor(Math.random() * NOUNS.length)];
|
|
180
|
-
const ts = Date.now().toString(36).slice(-4);
|
|
181
|
-
return `${adj}-${noun}-${ts}`;
|
|
182
|
-
}
|
|
183
|
-
var currentPlanPath = null;
|
|
184
|
-
function isPlanUnderWorkDir(planPath, workDir) {
|
|
185
|
-
const plansDir = resolve(workDir, ".swifty", "plans");
|
|
186
|
-
const resolved = resolve(planPath);
|
|
187
|
-
return resolved.startsWith(plansDir + "/");
|
|
188
|
-
}
|
|
189
|
-
function getOrCreatePlanPath(workDir) {
|
|
190
|
-
if (currentPlanPath && existsSync(currentPlanPath)) {
|
|
191
|
-
if (!isPlanUnderWorkDir(currentPlanPath, workDir)) {
|
|
192
|
-
log.warn({ planPath: currentPlanPath, workDir }, "current plan path is not under work dir");
|
|
193
|
-
} else {
|
|
194
|
-
return currentPlanPath;
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
const dir = join(workDir, ".swifty", "plans");
|
|
198
|
-
mkdirSync(dir, { recursive: true });
|
|
199
|
-
const slug = generateSlug();
|
|
200
|
-
currentPlanPath = join(dir, `${slug}.md`);
|
|
201
|
-
writeFileSync(currentPlanPath, "", "utf-8");
|
|
202
|
-
return currentPlanPath;
|
|
203
|
-
}
|
|
204
|
-
function savePlan(workDir, content) {
|
|
205
|
-
const path = getOrCreatePlanPath(workDir);
|
|
206
|
-
writeFileSync(path, content, "utf-8");
|
|
207
|
-
}
|
|
208
|
-
function loadPlan() {
|
|
209
|
-
if (!currentPlanPath || !existsSync(currentPlanPath)) {
|
|
210
|
-
return null;
|
|
211
|
-
}
|
|
212
|
-
return readFileSync(currentPlanPath, "utf-8");
|
|
213
|
-
}
|
|
214
|
-
function planExists(workDir) {
|
|
215
|
-
if (!currentPlanPath || !existsSync(currentPlanPath)) {
|
|
216
|
-
return false;
|
|
217
|
-
}
|
|
218
|
-
if (!isPlanUnderWorkDir(currentPlanPath, workDir)) {
|
|
219
|
-
log.warn({ planPath: currentPlanPath, workDir }, "current plan path is not under work dir");
|
|
220
|
-
return false;
|
|
221
|
-
}
|
|
222
|
-
return true;
|
|
223
|
-
}
|
|
224
|
-
function resetPlanPath() {
|
|
225
|
-
currentPlanPath = null;
|
|
226
|
-
}
|
|
227
|
-
function getCurrentPlanPath() {
|
|
228
|
-
return currentPlanPath;
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
// src/prompt/coordinator.ts
|
|
232
|
-
var coordinatorPrompt = `You are Swifty, an AI assistant that orchestrates software engineering tasks across multiple workers.
|
|
233
|
-
|
|
234
|
-
## 1. Your Role
|
|
235
|
-
|
|
236
|
-
You are a **coordinator**. Your job is to:
|
|
237
|
-
- Help the user achieve their goal
|
|
238
|
-
- Direct workers to research, implement and verify code changes
|
|
239
|
-
- Synthesize results and communicate with the user
|
|
240
|
-
- Answer questions directly when possible \u2014 don't delegate work you can handle without tools
|
|
241
|
-
|
|
242
|
-
Every message you send is to the user. Worker results and system notifications are internal signals, not conversation partners \u2014 never thank or acknowledge them. Summarize new information for the user as it arrives.
|
|
243
|
-
|
|
244
|
-
## 2. Your Tools
|
|
245
|
-
|
|
246
|
-
- **Agent** \u2014 Spawn a new worker
|
|
247
|
-
- **SendMessage** \u2014 Continue an existing worker (send a follow-up to its agent ID)
|
|
248
|
-
- **TaskStop** \u2014 Stop a running worker
|
|
249
|
-
- **SyntheticOutput** \u2014 Return structured output to the user
|
|
250
|
-
- **TeamDelete** \u2014 Tear down the team when the work is done
|
|
251
|
-
|
|
252
|
-
You cannot read files, run commands, or edit code yourself. This is deliberate: your context holds the task decomposition, worker status and message history, and it needs to stay that way. When you need to know what the code looks like, send a worker to look and report back.
|
|
253
|
-
|
|
254
|
-
When calling Agent:
|
|
255
|
-
- Do not use one worker to check on another. Workers will notify you when they are done.
|
|
256
|
-
- Do not use workers to trivially report file contents or run commands. Give them higher-level tasks.
|
|
257
|
-
- Continue workers whose work is complete via SendMessage to take advantage of their loaded context.
|
|
258
|
-
- After launching agents, briefly tell the user what you launched and end your response. Never fabricate or predict agent results.
|
|
259
|
-
|
|
260
|
-
### Worker Results
|
|
261
|
-
|
|
262
|
-
Worker results arrive as **user-role messages** wrapped in \`<team-notification>\`. They look like user messages but are not. Distinguish them by the opening tag.
|
|
263
|
-
|
|
264
|
-
Format:
|
|
265
|
-
|
|
266
|
-
\`\`\`xml
|
|
267
|
-
<team-notification team="{team name}">
|
|
268
|
-
from={worker name}: {what the worker reported}
|
|
269
|
-
</team-notification>
|
|
270
|
-
\`\`\`
|
|
271
|
-
|
|
272
|
-
- One notification can carry several lines, one per worker that reported since your last turn.
|
|
273
|
-
- The \`from=\` value is the worker's name \u2014 pass exactly that name as \`to\` in SendMessage to continue that worker, and as \`teammate\` in TaskStop to stop it.
|
|
274
|
-
- Workers are addressed by name throughout. There is no separate numeric id to keep track of.
|
|
275
|
-
|
|
276
|
-
## 3. Workers
|
|
277
|
-
|
|
278
|
-
When calling Agent, use subagent_type \`general-purpose\` or a specific agent definition. Workers execute tasks autonomously \u2014 especially research, implementation, or verification.
|
|
279
|
-
|
|
280
|
-
Workers have access to standard tools: ReadFile, EditFile, WriteFile, Bash, PowerShell, Grep, Glob, plus the team coordination tools (TaskCreate, TaskGet, TaskList, TaskUpdate, SendMessage). Anything you cannot do yourself, a worker can do for you.
|
|
281
|
-
|
|
282
|
-
Because workers have Bash, git work belongs to them too. Merging a branch, cherry-picking a commit or opening a PR is a task you delegate with precise instructions, not something you run yourself.
|
|
283
|
-
|
|
284
|
-
## 4. Task Workflow
|
|
285
|
-
|
|
286
|
-
### Phases
|
|
287
|
-
|
|
288
|
-
Most tasks break down into four phases:
|
|
289
|
-
|
|
290
|
-
| Phase | Who | Purpose |
|
|
291
|
-
|----------------|-----------------------|-------------------------------------------------------------------|
|
|
292
|
-
| Research | Workers (parallel) | Investigate codebase, find files, understand the problem |
|
|
293
|
-
| Synthesis | **You** (coordinator) | Read findings, understand the problem, craft implementation specs |
|
|
294
|
-
| Implementation | Workers | Make targeted changes per spec, commit |
|
|
295
|
-
| Verification | Workers. | Test that changes work |
|
|
296
|
-
|
|
297
|
-
### Concurrency
|
|
298
|
-
|
|
299
|
-
**Parallelism is your superpower. Workers are async. Launch independent workers concurrently whenever possible. To launch workers in parallel, make multiple tool calls in a single message.**
|
|
300
|
-
|
|
301
|
-
- **Read-only tasks** (research) \u2014 run in parallel freely
|
|
302
|
-
- **Write-heavy tasks** (implementation) \u2014 one at a time per set of files
|
|
303
|
-
- **Verification** can sometimes run alongside implementation on different file areas
|
|
304
|
-
|
|
305
|
-
### Verification MUST be a separate worker
|
|
306
|
-
|
|
307
|
-
**Never let the implementation worker verify its own work.** Spawn a fresh worker after implementation completes. The implementation worker is anchored on its own approach and will rubber-stamp its own code; a fresh verifier sees the code with no assumptions.
|
|
308
|
-
|
|
309
|
-
Real verification means running tests with the feature enabled, investigating typecheck errors instead of dismissing them as unrelated, and proving the change works rather than confirming it exists.
|
|
310
|
-
|
|
311
|
-
### Handling Worker Failures
|
|
312
|
-
|
|
313
|
-
When a worker reports failure, continue that same worker with SendMessage \u2014 it has the full error context. If a correction attempt fails, try a different approach or report to the user.
|
|
314
|
-
|
|
315
|
-
### Stopping Workers
|
|
316
|
-
|
|
317
|
-
Use TaskStop on a worker you sent in the wrong direction, for example when the user changes requirements after you launched it. Stopped workers can be continued later with SendMessage.
|
|
318
|
-
|
|
319
|
-
## 5. Writing Worker Prompts
|
|
320
|
-
|
|
321
|
-
**Workers can't see your conversation.** Every prompt must be self-contained.
|
|
322
|
-
|
|
323
|
-
### Always synthesize \u2014 your most important job
|
|
324
|
-
|
|
325
|
-
When workers report research findings, you must understand them before directing follow-up work. Read the findings, identify the approach, then write a prompt that proves you understood it by naming specific file paths, line numbers, and exactly what to change.
|
|
326
|
-
|
|
327
|
-
Never write "based on your findings" or "based on the research". These phrases hand your understanding off to a worker, which is the one thing you must not delegate.
|
|
328
|
-
|
|
329
|
-
\`\`\`
|
|
330
|
-
// Anti-pattern \u2014 lazy delegation
|
|
331
|
-
Agent(prompt="Based on your findings, fix the auth bug")
|
|
332
|
-
|
|
333
|
-
// Good \u2014 synthesized spec
|
|
334
|
-
Agent(prompt="Fix the null pointer in src/auth/validate.ts:42. The user field on Session is undefined when the session expires but the token is still cached. Add a null check before accessing user.id \u2014 if null, return 401 with 'Session expired'. Commit and report the hash.")
|
|
335
|
-
\`\`\`
|
|
336
|
-
|
|
337
|
-
### Add a purpose statement
|
|
338
|
-
|
|
339
|
-
Include a brief purpose so workers can calibrate depth and emphasis:
|
|
340
|
-
- "This research will inform a PR description \u2014 focus on user-facing changes."
|
|
341
|
-
- "I need this to plan an implementation \u2014 report file paths, line numbers, and type signatures."
|
|
342
|
-
- "This is a quick check before we merge \u2014 just verify the happy path."
|
|
343
|
-
|
|
344
|
-
### Choose continue vs. spawn by context overlap
|
|
345
|
-
|
|
346
|
-
| Situation | Mechanism | Why |
|
|
347
|
-
|-------------------------------------------------------|----------------------------|----------------------------------------------|
|
|
348
|
-
| Research explored exactly the files that need editing | **Continue** (SendMessage) | Worker already has the files in context |
|
|
349
|
-
| Research was broad but implementation is narrow | **Spawn fresh** (Agent) | Avoid dragging along exploration noise |
|
|
350
|
-
| Correcting a failure or extending recent work | **Continue** | Worker has the error context |
|
|
351
|
-
| Verifying code a different worker just wrote | **Spawn fresh** | Verifier should see the code with fresh eyes |
|
|
352
|
-
| First attempt used the wrong approach entirely | **Spawn fresh** | Wrong-approach context pollutes the retry |
|
|
353
|
-
|
|
354
|
-
### Prompt tips
|
|
355
|
-
|
|
356
|
-
- Include file paths, line numbers and error messages \u2014 workers start fresh and need complete context
|
|
357
|
-
- State what "done" looks like
|
|
358
|
-
- For implementation: "Run relevant tests, then commit and report the hash"
|
|
359
|
-
- For research: "Report findings \u2014 do not modify files"
|
|
360
|
-
- Be precise about git operations: name the branch, the commit hash, draft vs ready
|
|
361
|
-
- For verification: "Prove the code works, don't just confirm it exists"
|
|
362
|
-
|
|
363
|
-
## 6. Example Session
|
|
364
|
-
|
|
365
|
-
User: "There's a null pointer in the auth module. Can you fix it?"
|
|
366
|
-
|
|
367
|
-
You:
|
|
368
|
-
Let me investigate first.
|
|
369
|
-
|
|
370
|
-
Agent({ description: "Investigate auth bug", subagent_type: "general-purpose", prompt: "Investigate the auth module in src/auth/. Find where null pointer errors could occur around session handling and token validation. Report specific file paths, line numbers, and types involved. Do not modify files." })
|
|
371
|
-
Agent({ description: "Research auth tests", subagent_type: "general-purpose", prompt: "Find all test files related to src/auth/. Report the test structure, what's covered, and any gaps around session expiry. Do not modify files." })
|
|
372
|
-
|
|
373
|
-
Investigating from two angles \u2014 I'll report back with findings.
|
|
374
|
-
|
|
375
|
-
User:
|
|
376
|
-
<team-notification team="auth-fix">
|
|
377
|
-
from=investigator: Found null pointer in src/auth/validate.ts:42. The user field on Session is undefined when the session expires but the token is still cached.
|
|
378
|
-
</team-notification>
|
|
379
|
-
|
|
380
|
-
You:
|
|
381
|
-
Found the bug \u2014 null pointer in validate.ts:42.
|
|
382
|
-
|
|
383
|
-
SendMessage({ to: "investigator", message: "Fix the null pointer in src/auth/validate.ts:42. Add a null check before accessing user.id \u2014 if null, return 401. Commit and report the hash." })
|
|
384
|
-
|
|
385
|
-
Fix is in progress.`;
|
|
386
|
-
var coordinatorSparseReminder = `Coordinator mode still active (see full instructions earlier in conversation). You cannot read files, run commands, or edit code \u2014 send a worker instead. Tools: Agent, SendMessage, TaskStop, SyntheticOutput, TeamDelete. Address workers by the name in the from= field of a team-notification. Synthesize worker findings yourself before directing follow-up work.`;
|
|
387
|
-
var REMINDER_INTERVAL = 5;
|
|
388
|
-
function coordinatorReminder(iteration = 1) {
|
|
389
|
-
if (iteration <= 1 || (iteration - 1) % REMINDER_INTERVAL === 0) {
|
|
390
|
-
return coordinatorPrompt;
|
|
391
|
-
}
|
|
392
|
-
return coordinatorSparseReminder;
|
|
393
|
-
}
|
|
394
|
-
|
|
395
|
-
// src/prompt/plan-mode.ts
|
|
396
|
-
var planModeFullReminder = `Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits (with the exception of the plan file mentioned below), run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.
|
|
397
|
-
|
|
398
|
-
## Plan File Info:
|
|
399
|
-
|
|
400
|
-
%PLAN_FILE_INFO%
|
|
401
|
-
You should build your plan incrementally by writing to or editing this file. NOTE that this is the only file you are allowed to edit - other than this you are only allowed to take READ-ONLY actions.
|
|
402
|
-
|
|
403
|
-
## Plan Workflow
|
|
404
|
-
|
|
405
|
-
### Phase 1: Initial Understanding
|
|
406
|
-
|
|
407
|
-
Goal: Gain a comprehensive understanding of the user's request by reading through code and asking them questions. Critical: In this phase you should use the Agent tool with subagent_type="explore".
|
|
408
|
-
|
|
409
|
-
1. Focus on understanding the user's request and the code associated with their request. Actively search for existing functions, utilities, and patterns that can be reused \u2014 avoid proposing new code when suitable implementations already exist.
|
|
410
|
-
|
|
411
|
-
2. **Call the Agent tool with subagent_type="explore" to explore the codebase.** You can launch up to 3 explore agents IN PARALLEL by making multiple Agent tool calls in a single response.
|
|
412
|
-
|
|
413
|
-
### Phase 2: Design
|
|
414
|
-
|
|
415
|
-
Goal: Design an implementation approach.
|
|
416
|
-
|
|
417
|
-
Call the Agent tool with subagent_type="plan" to design the implementation based on the user's intent and your exploration results from Phase 1.
|
|
418
|
-
|
|
419
|
-
### Phase 3: Review
|
|
420
|
-
|
|
421
|
-
Goal: Review the plan(s) from Phase 2 and ensure alignment with the user's intentions.
|
|
422
|
-
|
|
423
|
-
1. Read the critical files identified by agents to deepen your understanding
|
|
424
|
-
2. Ensure that the plans align with the user's original request
|
|
425
|
-
3. Use AskUserQuestion to clarify any remaining questions with the user.
|
|
426
|
-
|
|
427
|
-
### Phase 4: Final Plan
|
|
428
|
-
|
|
429
|
-
Goal: Write your final plan to the plan file (the only file you can edit).
|
|
430
|
-
|
|
431
|
-
- Begin with a **Context** section
|
|
432
|
-
- Include only your recommended approach
|
|
433
|
-
- Include the paths of critical files to be modified
|
|
434
|
-
- Include a verification section
|
|
435
|
-
|
|
436
|
-
### Phase 5: Call ExitPlanMode
|
|
437
|
-
|
|
438
|
-
At the very end of your turn, once you have asked the user questions and are happy with your final plan file - you should always call ExitPlanMode.
|
|
439
|
-
`;
|
|
440
|
-
var planModeSparseReminder = `Plan mode still active (see full instructions earlier in conversation). Read-only except plan file (%PLAN_PATH%). Follow 5-phase workflow. End turns with AskUserQuestion (for clarifications) or ExitPlanMode (for plan approval). Never ask about plan approval via text or AskUserQuestion.`;
|
|
441
|
-
var planModeExitTemplate = `## Exited Plan Mode
|
|
442
|
-
|
|
443
|
-
You have exited plan mode. You can now make edits, run tools, and take actions.%EXTRA%`;
|
|
444
|
-
var planModeReentryTemplate = `You have re-entered plan mode. Your previous plan file is at %PLAN_PATH%. Review it and continue from where you left off. You can update, refine, or restart the plan as needed. Follow the same 5-phase workflow as before.`;
|
|
445
|
-
var reminderInterval = 5;
|
|
446
|
-
function buildPlanModeReminder(planPath, planExist, iteration) {
|
|
447
|
-
let planFileInfo = `Plan file: ${planPath}`;
|
|
448
|
-
if (planExist) {
|
|
449
|
-
planFileInfo += `
|
|
450
|
-
A plan file already exists at ${planPath}. You can read it and make incremental edits using the EditFile tool.`;
|
|
451
|
-
} else {
|
|
452
|
-
planFileInfo += `
|
|
453
|
-
No plan file exists yet. You should create your plan at ${planPath} using the WriteFile tool.`;
|
|
454
|
-
}
|
|
455
|
-
if ((iteration - 1) % reminderInterval === 0) {
|
|
456
|
-
return planModeFullReminder.replace("%PLAN_FILE_INFO%", planFileInfo);
|
|
457
|
-
}
|
|
458
|
-
return planModeSparseReminder.replace("%PLAN_PATH%", planPath);
|
|
459
|
-
}
|
|
460
|
-
function buildPlanModeExitReminder(planPath, planExists2) {
|
|
461
|
-
let extra = "";
|
|
462
|
-
if (planExists2) {
|
|
463
|
-
extra = ` The plan file is located at ${planPath} if you need to reference it.`;
|
|
464
|
-
}
|
|
465
|
-
return planModeExitTemplate.replace("%EXTRA%", extra);
|
|
466
|
-
}
|
|
467
|
-
function buildPlanModeReentryReminder(planPath, planFileExists) {
|
|
468
|
-
if (!planFileExists) {
|
|
469
|
-
return "";
|
|
470
|
-
}
|
|
471
|
-
return planModeReentryTemplate.replace("%PLAN_PATH%", planPath);
|
|
472
|
-
}
|
|
473
|
-
|
|
474
|
-
// src/tool-result/budget.ts
|
|
475
|
-
import { writeFileSync as writeFileSync2, mkdirSync as mkdirSync2 } from "fs";
|
|
476
|
-
import { join as join2, resolve as resolve2 } from "path";
|
|
477
|
-
var log2 = createChildLogger({ module: "tool-result" });
|
|
478
|
-
var MESSAGE_AGGREGATE_LIMIT = 2e5;
|
|
479
|
-
var TOOL_RESULT_PREVIEW_CHARS = 2e3;
|
|
480
|
-
function spillDir(workDir, sessionId) {
|
|
481
|
-
const id = sessionId || "default";
|
|
482
|
-
return join2(workDir, ".swifty", "sessions", id, "tool-results");
|
|
483
|
-
}
|
|
484
|
-
function writeSpill(workDir, sessionId, toolUseId, content) {
|
|
485
|
-
const dir = spillDir(workDir, sessionId);
|
|
486
|
-
mkdirSync2(dir, { recursive: true });
|
|
487
|
-
const path = join2(dir, toolUseId + ".txt");
|
|
488
|
-
try {
|
|
489
|
-
writeFileSync2(path, content, { encoding: "utf-8", flag: "wx" });
|
|
490
|
-
} catch (err) {
|
|
491
|
-
log2.error({ err }, "tool-result operation failed");
|
|
492
|
-
if (isObject(err) && "code" in err && err.code !== "EEXIST") {
|
|
493
|
-
throw err;
|
|
494
|
-
}
|
|
495
|
-
}
|
|
496
|
-
return path;
|
|
497
|
-
}
|
|
498
|
-
function toDisplayPreview(content) {
|
|
499
|
-
if (content.length <= TOOL_RESULT_PREVIEW_CHARS) {
|
|
500
|
-
return content;
|
|
501
|
-
}
|
|
502
|
-
return content.slice(0, TOOL_RESULT_PREVIEW_CHARS) + `
|
|
503
|
-
\u2026 ${String(content.length - TOOL_RESULT_PREVIEW_CHARS)} chars omitted from transcript`;
|
|
504
|
-
}
|
|
505
|
-
function replaceToolResultContent(result, content) {
|
|
506
|
-
result.content = content;
|
|
507
|
-
if (result.contentBlocks?.length) {
|
|
508
|
-
result.contentBlocks = [
|
|
509
|
-
{ type: "text", text: content },
|
|
510
|
-
...result.contentBlocks.filter((block) => block.type !== "text")
|
|
511
|
-
];
|
|
512
|
-
}
|
|
513
|
-
}
|
|
514
|
-
function buildSpillPreview(content, spillPath) {
|
|
515
|
-
const sizeKB = Math.floor(content.length / 1024);
|
|
516
|
-
const preview = content.slice(0, TOOL_RESULT_PREVIEW_CHARS);
|
|
517
|
-
const hasMore = content.length > TOOL_RESULT_PREVIEW_CHARS;
|
|
518
|
-
let msg = `<persisted-output>
|
|
519
|
-
`;
|
|
520
|
-
msg += `Output too large (${String(sizeKB)}KB). Full content saved to:
|
|
521
|
-
${spillPath}
|
|
522
|
-
|
|
523
|
-
`;
|
|
524
|
-
msg += `Preview (first 2KB):
|
|
525
|
-
${preview}`;
|
|
526
|
-
if (hasMore) {
|
|
527
|
-
msg += "\n...";
|
|
528
|
-
}
|
|
529
|
-
msg += "\n</persisted-output>";
|
|
530
|
-
return msg;
|
|
531
|
-
}
|
|
532
|
-
function isSpillReadback(toolName, args, workDir, sessionId) {
|
|
533
|
-
if (toolName !== "ReadFile" || !args) {
|
|
534
|
-
return false;
|
|
535
|
-
}
|
|
536
|
-
const raw = args.file_path;
|
|
537
|
-
if (typeof raw !== "string" || !raw) {
|
|
538
|
-
return false;
|
|
539
|
-
}
|
|
540
|
-
return resolve2(raw).startsWith(resolve2(spillDir(workDir, sessionId)));
|
|
541
|
-
}
|
|
542
|
-
function applyBudget(toolResults, workDir, sessionId, exemptIds) {
|
|
543
|
-
let total = toolResults.reduce((sum, result) => sum + result.content.length, 0);
|
|
544
|
-
if (total <= MESSAGE_AGGREGATE_LIMIT) {
|
|
545
|
-
return;
|
|
546
|
-
}
|
|
547
|
-
const sorted = toolResults.toSorted((a, b) => b.content.length - a.content.length);
|
|
548
|
-
for (const r of sorted) {
|
|
549
|
-
if (total <= MESSAGE_AGGREGATE_LIMIT) {
|
|
550
|
-
break;
|
|
551
|
-
}
|
|
552
|
-
if (exemptIds?.has(r.toolUseId)) {
|
|
553
|
-
continue;
|
|
554
|
-
}
|
|
555
|
-
const content = r.content;
|
|
556
|
-
if (content.length <= TOOL_RESULT_PREVIEW_CHARS) {
|
|
557
|
-
continue;
|
|
558
|
-
}
|
|
559
|
-
let spillPath;
|
|
560
|
-
try {
|
|
561
|
-
spillPath = writeSpill(workDir, sessionId, r.toolUseId, content);
|
|
562
|
-
} catch {
|
|
563
|
-
continue;
|
|
564
|
-
}
|
|
565
|
-
const replacement = buildSpillPreview(content, spillPath);
|
|
566
|
-
total -= content.length - replacement.length;
|
|
567
|
-
replaceToolResultContent(r, replacement);
|
|
568
|
-
}
|
|
569
|
-
}
|
|
570
|
-
function persistLargeResult(workDir, sessionId, toolUseId, content) {
|
|
571
|
-
let path;
|
|
572
|
-
try {
|
|
573
|
-
path = writeSpill(workDir, sessionId, toolUseId, content);
|
|
574
|
-
} catch {
|
|
575
|
-
return content;
|
|
576
|
-
}
|
|
577
|
-
return buildSpillPreview(content, path);
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
// src/agent/streaming-executor.ts
|
|
581
|
-
var log3 = createChildLogger({ module: "agent" });
|
|
582
|
-
var StreamingExecutor = class {
|
|
583
|
-
pending = [];
|
|
584
|
-
registry;
|
|
585
|
-
ctx;
|
|
586
|
-
constructor(registry, ctx) {
|
|
587
|
-
this.registry = registry;
|
|
588
|
-
this.ctx = ctx;
|
|
589
|
-
}
|
|
590
|
-
submit(toolId, toolName, args) {
|
|
591
|
-
this.pending.push({ toolId, toolName, arguments: args });
|
|
592
|
-
}
|
|
593
|
-
async collectResults() {
|
|
594
|
-
const calls = [...this.pending];
|
|
595
|
-
this.pending = [];
|
|
596
|
-
const promises = calls.map(async (call) => {
|
|
597
|
-
const tool = this.registry.get(call.toolName);
|
|
598
|
-
const start = Date.now();
|
|
599
|
-
if (!tool) {
|
|
600
|
-
return {
|
|
601
|
-
toolId: call.toolId,
|
|
602
|
-
toolName: call.toolName,
|
|
603
|
-
result: {
|
|
604
|
-
output: `Error: unknown tool '${call.toolName}'`,
|
|
605
|
-
isError: true
|
|
606
|
-
},
|
|
607
|
-
elapsed: 0
|
|
608
|
-
};
|
|
609
|
-
}
|
|
610
|
-
try {
|
|
611
|
-
const result = await tool.execute(this.ctx, call.arguments);
|
|
612
|
-
return {
|
|
613
|
-
toolId: call.toolId,
|
|
614
|
-
toolName: call.toolName,
|
|
615
|
-
result,
|
|
616
|
-
elapsed: (Date.now() - start) / 1e3
|
|
617
|
-
};
|
|
618
|
-
} catch (err) {
|
|
619
|
-
log3.error({ err }, "agent operation failed");
|
|
620
|
-
return {
|
|
621
|
-
toolId: call.toolId,
|
|
622
|
-
toolName: call.toolName,
|
|
623
|
-
result: {
|
|
624
|
-
output: `Error executing ${call.toolName}: ${asErrorString(err)}`,
|
|
625
|
-
isError: true
|
|
626
|
-
},
|
|
627
|
-
elapsed: (Date.now() - start) / 1e3
|
|
628
|
-
};
|
|
629
|
-
}
|
|
630
|
-
});
|
|
631
|
-
return Promise.all(promises);
|
|
632
|
-
}
|
|
633
|
-
hasPending() {
|
|
634
|
-
return this.pending.length > 0;
|
|
635
|
-
}
|
|
636
|
-
};
|
|
637
|
-
|
|
638
|
-
// src/agent/agent.ts
|
|
639
|
-
var MAX_TOKENS_CEILING = 64e3;
|
|
640
|
-
var MAX_OUTPUT_TOKENS_RECOVERIES = 3;
|
|
641
|
-
var MAX_OUTPUT_CHARS = 5e4;
|
|
642
|
-
var DEFERRED_REMINDER_MARKER = "The following deferred tools are available via ToolSearch.";
|
|
643
|
-
var Agent = class {
|
|
644
|
-
// Deferred tool names announced to the model last time, in lexicographic order.
|
|
645
|
-
// Compared against the current pool to skip re-injection when nothing changed.
|
|
646
|
-
announcedDeferred = [];
|
|
647
|
-
client;
|
|
648
|
-
registry;
|
|
649
|
-
checker;
|
|
650
|
-
conversation;
|
|
651
|
-
workDir;
|
|
652
|
-
sessionId;
|
|
653
|
-
sessionFilePath;
|
|
654
|
-
hookEngine;
|
|
655
|
-
fileHistory;
|
|
656
|
-
fileStateCache;
|
|
657
|
-
abortSignal;
|
|
658
|
-
contextWindow;
|
|
659
|
-
maxOutput;
|
|
660
|
-
recoveryState;
|
|
661
|
-
maxIterations;
|
|
662
|
-
notificationFn;
|
|
663
|
-
onLoopComplete;
|
|
664
|
-
compactTracking = new AutoCompactTrackingState();
|
|
665
|
-
onPermissionRequest;
|
|
666
|
-
toolFilter;
|
|
667
|
-
coordinatorActiveFn;
|
|
668
|
-
activeSkills;
|
|
669
|
-
instructions;
|
|
670
|
-
memoryContent;
|
|
671
|
-
skillSection;
|
|
672
|
-
skillDeltaFn;
|
|
673
|
-
memoryRecallPromise;
|
|
674
|
-
memoryRecallConsumed = false;
|
|
675
|
-
/** Whether the prefetch has settled, and its result. The main loop checks this flag without awaiting. */
|
|
676
|
-
memoryRecallSettled = false;
|
|
677
|
-
memoryRecallValue;
|
|
678
|
-
onMemoriesSurfaced;
|
|
679
|
-
constructor(config) {
|
|
680
|
-
this.client = config.client;
|
|
681
|
-
this.registry = config.registry;
|
|
682
|
-
this.checker = config.checker;
|
|
683
|
-
this.conversation = config.conversation;
|
|
684
|
-
this.workDir = config.workDir;
|
|
685
|
-
this.sessionId = config.sessionId ?? "";
|
|
686
|
-
this.sessionFilePath = config.sessionId ? getSessionFilePath(config.workDir, config.sessionId) : "";
|
|
687
|
-
this.hookEngine = config.hookEngine;
|
|
688
|
-
this.fileHistory = config.fileHistory;
|
|
689
|
-
this.fileStateCache = config.fileStateCache;
|
|
690
|
-
this.abortSignal = config.abortSignal;
|
|
691
|
-
this.contextWindow = config.contextWindow ?? 2e5;
|
|
692
|
-
this.maxOutput = config.maxOutput ?? 8192;
|
|
693
|
-
this.recoveryState = config.recoveryState ?? new RecoveryState();
|
|
694
|
-
this.maxIterations = config.maxIterations ?? 0;
|
|
695
|
-
this.notificationFn = config.notificationFn;
|
|
696
|
-
this.onLoopComplete = config.onLoopComplete;
|
|
697
|
-
this.onPermissionRequest = config.onPermissionRequest;
|
|
698
|
-
this.activeSkills = config.activeSkills ?? /* @__PURE__ */ new Map();
|
|
699
|
-
this.toolFilter = config.toolFilter;
|
|
700
|
-
this.coordinatorActiveFn = config.coordinatorActiveFn;
|
|
701
|
-
this.instructions = config.instructions ?? "";
|
|
702
|
-
this.memoryContent = config.memoryContent ?? "";
|
|
703
|
-
this.skillSection = config.skillSection ?? "";
|
|
704
|
-
this.skillDeltaFn = config.skillDeltaFn;
|
|
705
|
-
this.memoryRecallPromise = config.memoryRecallPromise;
|
|
706
|
-
this.onMemoriesSurfaced = config.onMemoriesSurfaced;
|
|
707
|
-
void this.memoryRecallPromise?.then(
|
|
708
|
-
(r) => {
|
|
709
|
-
this.memoryRecallValue = r;
|
|
710
|
-
this.memoryRecallSettled = true;
|
|
711
|
-
},
|
|
712
|
-
() => {
|
|
713
|
-
this.memoryRecallSettled = true;
|
|
714
|
-
}
|
|
715
|
-
);
|
|
716
|
-
}
|
|
717
|
-
async *run() {
|
|
718
|
-
let toolSchemas = this.registry.getAllSchemas();
|
|
719
|
-
if (this.toolFilter) {
|
|
720
|
-
toolSchemas = toolSchemas.filter((s) => this.toolFilter?.(s.name));
|
|
721
|
-
}
|
|
722
|
-
const toolSchemaNames = this.registry.listTools().map((t) => t.name);
|
|
723
|
-
let maxTokensEscalated = false;
|
|
724
|
-
let outputRecoveries = 0;
|
|
725
|
-
let iteration = 0;
|
|
726
|
-
await this.fireLifecycle("session_start");
|
|
727
|
-
try {
|
|
728
|
-
let looping = true;
|
|
729
|
-
while (looping) {
|
|
730
|
-
iteration++;
|
|
731
|
-
if (this.maxIterations > 0 && iteration > this.maxIterations) {
|
|
732
|
-
yield {
|
|
733
|
-
type: "error",
|
|
734
|
-
error: new Error(`Agent reached maximum iterations (${String(this.maxIterations)})`)
|
|
735
|
-
};
|
|
736
|
-
return;
|
|
737
|
-
}
|
|
738
|
-
let fullText = "";
|
|
739
|
-
const thinkingBlocks = [];
|
|
740
|
-
const toolUses = [];
|
|
741
|
-
let stopReason = "end_turn";
|
|
742
|
-
let lastUsage = null;
|
|
743
|
-
if (this.checker.mode === "plan") {
|
|
744
|
-
const planPath = getOrCreatePlanPath(this.workDir);
|
|
745
|
-
this.checker.planFilePath = planPath;
|
|
746
|
-
this.conversation.addSystemReminder(
|
|
747
|
-
buildPlanModeReminder(planPath, planExists(this.workDir), iteration)
|
|
748
|
-
);
|
|
749
|
-
}
|
|
750
|
-
if (this.coordinatorActiveFn?.()) {
|
|
751
|
-
this.conversation.addSystemReminder(coordinatorReminder(iteration));
|
|
752
|
-
}
|
|
753
|
-
const deferredNames = this.registry.getDeferredToolNames();
|
|
754
|
-
if (deferredNames.length > 0) {
|
|
755
|
-
const poolChanged = deferredNames.length !== this.announcedDeferred.length || deferredNames.some((n, i) => n !== this.announcedDeferred[i]);
|
|
756
|
-
if (poolChanged || !this.conversation.hasReminderContaining(DEFERRED_REMINDER_MARKER)) {
|
|
757
|
-
let reminder = DEFERRED_REMINDER_MARKER + ' Their schemas are NOT loaded - use ToolSearch with query "select:<name>[,<name>...]" to load tool schemas';
|
|
758
|
-
reminder += this.registry.mcpLoadingMode === "dispatch" ? ", then invoke them with the mcp_call tool" : " before calling them";
|
|
759
|
-
this.conversation.addSystemReminder(reminder + ":\n" + deferredNames.join("\n"));
|
|
760
|
-
this.announcedDeferred = deferredNames;
|
|
761
|
-
}
|
|
762
|
-
}
|
|
763
|
-
if (this.hookEngine) {
|
|
764
|
-
for (const note of this.hookEngine.drainNotifications()) {
|
|
765
|
-
this.conversation.addSystemReminder(note);
|
|
766
|
-
}
|
|
767
|
-
}
|
|
768
|
-
if (this.notificationFn) {
|
|
769
|
-
for (const note of this.notificationFn()) {
|
|
770
|
-
this.conversation.addSystemReminder(note);
|
|
771
|
-
}
|
|
772
|
-
}
|
|
773
|
-
if (this.skillDeltaFn) {
|
|
774
|
-
const delta = this.skillDeltaFn();
|
|
775
|
-
if (delta) {
|
|
776
|
-
this.conversation.addSystemReminder("The following skills became available:\n" + delta);
|
|
777
|
-
}
|
|
778
|
-
}
|
|
779
|
-
await this.fireLifecycle("turn_start");
|
|
780
|
-
await this.fireLifecycle("pre_send");
|
|
781
|
-
const mc = await manageContext(
|
|
782
|
-
this.conversation,
|
|
783
|
-
this.client,
|
|
784
|
-
this.contextWindow,
|
|
785
|
-
this.maxOutput,
|
|
786
|
-
this.compactTracking,
|
|
787
|
-
this.recoveryState,
|
|
788
|
-
toolSchemaNames,
|
|
789
|
-
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
|
790
|
-
toolSchemas,
|
|
791
|
-
this.sessionFilePath
|
|
792
|
-
);
|
|
793
|
-
if (mc.message) {
|
|
794
|
-
yield { type: "compact", message: mc.message, boundary: mc.boundary };
|
|
795
|
-
}
|
|
796
|
-
if (mc.compacted) {
|
|
797
|
-
this.conversation.injectLongTermMemory(
|
|
798
|
-
this.instructions,
|
|
799
|
-
this.memoryContent,
|
|
800
|
-
this.skillSection
|
|
801
|
-
);
|
|
802
|
-
}
|
|
803
|
-
try {
|
|
804
|
-
const stream = this.client.stream(
|
|
805
|
-
this.conversation,
|
|
806
|
-
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
|
807
|
-
toolSchemas,
|
|
808
|
-
this.abortSignal
|
|
809
|
-
);
|
|
810
|
-
for await (const event of stream) {
|
|
811
|
-
if (this.abortSignal?.aborted) {
|
|
812
|
-
looping = false;
|
|
813
|
-
break;
|
|
814
|
-
}
|
|
815
|
-
switch (event.type) {
|
|
816
|
-
case "text_delta":
|
|
817
|
-
fullText += event.text;
|
|
818
|
-
yield { type: "stream_text", text: event.text };
|
|
819
|
-
break;
|
|
820
|
-
case "thinking_delta":
|
|
821
|
-
yield { type: "thinking_text", text: event.text };
|
|
822
|
-
break;
|
|
823
|
-
case "thinking_complete":
|
|
824
|
-
thinkingBlocks.push({
|
|
825
|
-
thinking: event.thinking,
|
|
826
|
-
signature: event.signature
|
|
827
|
-
});
|
|
828
|
-
yield {
|
|
829
|
-
type: "thinking_complete",
|
|
830
|
-
thinking: event.thinking,
|
|
831
|
-
signature: event.signature
|
|
832
|
-
};
|
|
833
|
-
break;
|
|
834
|
-
case "tool_call_start":
|
|
835
|
-
break;
|
|
836
|
-
case "tool_call_complete":
|
|
837
|
-
toolUses.push({
|
|
838
|
-
toolUseId: event.toolId,
|
|
839
|
-
toolName: event.toolName,
|
|
840
|
-
arguments: event.arguments
|
|
841
|
-
});
|
|
842
|
-
yield {
|
|
843
|
-
type: "tool_use",
|
|
844
|
-
toolName: event.toolName,
|
|
845
|
-
toolId: event.toolId,
|
|
846
|
-
args: event.arguments
|
|
847
|
-
};
|
|
848
|
-
break;
|
|
849
|
-
case "stream_end":
|
|
850
|
-
stopReason = event.stopReason;
|
|
851
|
-
lastUsage = event.usage;
|
|
852
|
-
yield { type: "usage", usage: event.usage };
|
|
853
|
-
break;
|
|
854
|
-
}
|
|
855
|
-
}
|
|
856
|
-
} catch (err) {
|
|
857
|
-
if (this.abortSignal?.aborted) {
|
|
858
|
-
yield { type: "loop_complete", stopReason: "interrupted" };
|
|
859
|
-
return;
|
|
860
|
-
}
|
|
861
|
-
if (err instanceof ContextTooLongError) {
|
|
862
|
-
try {
|
|
863
|
-
const result = await forceCompact(
|
|
864
|
-
this.conversation,
|
|
865
|
-
this.client,
|
|
866
|
-
this.recoveryState,
|
|
867
|
-
toolSchemaNames,
|
|
868
|
-
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
|
869
|
-
toolSchemas,
|
|
870
|
-
this.sessionFilePath
|
|
871
|
-
);
|
|
872
|
-
this.conversation.clearUsageAnchor();
|
|
873
|
-
this.conversation.injectLongTermMemory(
|
|
874
|
-
this.instructions,
|
|
875
|
-
this.memoryContent,
|
|
876
|
-
this.skillSection
|
|
877
|
-
);
|
|
878
|
-
yield {
|
|
879
|
-
type: "compact",
|
|
880
|
-
message: "Auto-compacted due to context length: " + result.message,
|
|
881
|
-
boundary: result.boundary
|
|
882
|
-
};
|
|
883
|
-
continue;
|
|
884
|
-
} catch {
|
|
885
|
-
yield { type: "error", error: err };
|
|
886
|
-
return;
|
|
887
|
-
}
|
|
888
|
-
}
|
|
889
|
-
if (err instanceof RateLimitError) {
|
|
890
|
-
const waitMs = parseRetryAfter(strArg(asRecord(err), "retryAfter"));
|
|
891
|
-
yield { type: "retry", reason: "rate limited", delay: waitMs };
|
|
892
|
-
if (await this.interruptibleSleep(waitMs)) {
|
|
893
|
-
yield { type: "loop_complete", stopReason: "interrupted" };
|
|
894
|
-
return;
|
|
895
|
-
}
|
|
896
|
-
continue;
|
|
897
|
-
}
|
|
898
|
-
yield {
|
|
899
|
-
type: "error",
|
|
900
|
-
error: err instanceof Error ? err : new Error(JSON.stringify(err))
|
|
901
|
-
};
|
|
902
|
-
return;
|
|
903
|
-
}
|
|
904
|
-
if (this.abortSignal?.aborted) {
|
|
905
|
-
if (fullText) {
|
|
906
|
-
this.conversation.addAssistantFull(fullText, thinkingBlocks, []);
|
|
907
|
-
this.persistLastMessage();
|
|
908
|
-
}
|
|
909
|
-
yield { type: "loop_complete", stopReason: "interrupted" };
|
|
910
|
-
return;
|
|
911
|
-
}
|
|
912
|
-
await this.fireLifecycle("post_receive", fullText);
|
|
913
|
-
if (stopReason === "max_tokens") {
|
|
914
|
-
if (!maxTokensEscalated) {
|
|
915
|
-
this.client.setMaxOutputTokens?.(MAX_TOKENS_CEILING);
|
|
916
|
-
maxTokensEscalated = true;
|
|
917
|
-
if (fullText) {
|
|
918
|
-
this.conversation.addAssistantFull(fullText, thinkingBlocks, []);
|
|
919
|
-
this.persistLastMessage();
|
|
920
|
-
if (lastUsage) {
|
|
921
|
-
this.conversation.recordUsageAnchor(
|
|
922
|
-
lastUsage.inputTokens,
|
|
923
|
-
lastUsage.outputTokens,
|
|
924
|
-
lastUsage.cacheReadInputTokens,
|
|
925
|
-
lastUsage.cacheCreationInputTokens
|
|
926
|
-
);
|
|
927
|
-
}
|
|
928
|
-
this.conversation.addUserMessage(
|
|
929
|
-
"Output token limit hit. Resume directly from where you stopped. Do not apologize or repeat previous content. Pick up mid-thought if needed."
|
|
930
|
-
);
|
|
931
|
-
}
|
|
932
|
-
yield { type: "retry", reason: "max_tokens escalation", delay: 0 };
|
|
933
|
-
continue;
|
|
934
|
-
} else if (outputRecoveries < MAX_OUTPUT_TOKENS_RECOVERIES) {
|
|
935
|
-
outputRecoveries++;
|
|
936
|
-
this.conversation.addAssistantFull(fullText, thinkingBlocks, []);
|
|
937
|
-
this.persistLastMessage();
|
|
938
|
-
if (lastUsage) {
|
|
939
|
-
this.conversation.recordUsageAnchor(
|
|
940
|
-
lastUsage.inputTokens,
|
|
941
|
-
lastUsage.outputTokens,
|
|
942
|
-
lastUsage.cacheReadInputTokens,
|
|
943
|
-
lastUsage.cacheCreationInputTokens
|
|
944
|
-
);
|
|
945
|
-
}
|
|
946
|
-
this.conversation.addUserMessage(
|
|
947
|
-
"Output token limit hit. Resume directly from where you stopped. Break remaining work into smaller pieces."
|
|
948
|
-
);
|
|
949
|
-
yield {
|
|
950
|
-
type: "retry",
|
|
951
|
-
reason: `max_tokens recovery ${String(outputRecoveries)}/${String(MAX_OUTPUT_TOKENS_RECOVERIES)}`,
|
|
952
|
-
delay: 0
|
|
953
|
-
};
|
|
954
|
-
continue;
|
|
955
|
-
}
|
|
956
|
-
} else {
|
|
957
|
-
outputRecoveries = 0;
|
|
958
|
-
}
|
|
959
|
-
this.conversation.addAssistantFull(fullText, thinkingBlocks, toolUses);
|
|
960
|
-
this.persistLastMessage();
|
|
961
|
-
if (lastUsage) {
|
|
962
|
-
this.conversation.recordUsageAnchor(
|
|
963
|
-
lastUsage.inputTokens,
|
|
964
|
-
lastUsage.outputTokens,
|
|
965
|
-
lastUsage.cacheReadInputTokens,
|
|
966
|
-
lastUsage.cacheCreationInputTokens
|
|
967
|
-
);
|
|
968
|
-
}
|
|
969
|
-
if (toolUses.length > 0) {
|
|
970
|
-
const results = await this.executeTools(toolUses);
|
|
971
|
-
for (const r of results) {
|
|
972
|
-
yield r;
|
|
973
|
-
}
|
|
974
|
-
const exemptIds = /* @__PURE__ */ new Set();
|
|
975
|
-
for (const tu of toolUses) {
|
|
976
|
-
if (isSpillReadback(tu.toolName, tu.arguments, this.workDir, this.sessionId)) {
|
|
977
|
-
exemptIds.add(tu.toolUseId);
|
|
978
|
-
}
|
|
979
|
-
}
|
|
980
|
-
const toolResults = [];
|
|
981
|
-
for (const r of results) {
|
|
982
|
-
if (r.type === "tool_result") {
|
|
983
|
-
const toolResult = {
|
|
984
|
-
toolUseId: r.toolId,
|
|
985
|
-
content: r.output,
|
|
986
|
-
...r.contentBlocks?.length ? { contentBlocks: r.contentBlocks } : {},
|
|
987
|
-
isError: r.isError
|
|
988
|
-
};
|
|
989
|
-
if (toolResult.content.length > MAX_OUTPUT_CHARS && !exemptIds.has(r.toolId)) {
|
|
990
|
-
const replacement = persistLargeResult(
|
|
991
|
-
this.workDir,
|
|
992
|
-
this.sessionId,
|
|
993
|
-
r.toolId,
|
|
994
|
-
toolResult.content
|
|
995
|
-
);
|
|
996
|
-
if (replacement !== toolResult.content) {
|
|
997
|
-
replaceToolResultContent(toolResult, replacement);
|
|
998
|
-
}
|
|
999
|
-
exemptIds.add(r.toolId);
|
|
1000
|
-
}
|
|
1001
|
-
toolResults.push(toolResult);
|
|
1002
|
-
}
|
|
1003
|
-
}
|
|
1004
|
-
applyBudget(toolResults, this.workDir, this.sessionId, exemptIds);
|
|
1005
|
-
const exitPlanSucceeded = toolUses.some((tu) => {
|
|
1006
|
-
if (tu.toolName !== "ExitPlanMode") {
|
|
1007
|
-
return false;
|
|
1008
|
-
}
|
|
1009
|
-
const result = results.find(
|
|
1010
|
-
(r) => r.type === "tool_result" && r.toolId === tu.toolUseId
|
|
1011
|
-
);
|
|
1012
|
-
return result?.type === "tool_result" && !result.isError;
|
|
1013
|
-
});
|
|
1014
|
-
this.conversation.addToolResultsMessage(toolResults);
|
|
1015
|
-
this.persistLastMessage();
|
|
1016
|
-
if (this.abortSignal?.aborted) {
|
|
1017
|
-
yield { type: "turn_complete" };
|
|
1018
|
-
yield { type: "loop_complete", stopReason: "interrupted" };
|
|
1019
|
-
return;
|
|
1020
|
-
}
|
|
1021
|
-
if (this.memoryRecallPromise && !this.memoryRecallConsumed && this.memoryRecallSettled) {
|
|
1022
|
-
const recall = this.memoryRecallValue;
|
|
1023
|
-
if (recall?.reminder) {
|
|
1024
|
-
this.conversation.addSystemReminder(recall.reminder);
|
|
1025
|
-
this.onMemoriesSurfaced?.(recall.paths);
|
|
1026
|
-
}
|
|
1027
|
-
this.memoryRecallConsumed = true;
|
|
1028
|
-
}
|
|
1029
|
-
if (exitPlanSucceeded) {
|
|
1030
|
-
yield { type: "turn_complete" };
|
|
1031
|
-
yield { type: "loop_complete", stopReason: "end_turn" };
|
|
1032
|
-
return;
|
|
1033
|
-
}
|
|
1034
|
-
yield { type: "turn_complete" };
|
|
1035
|
-
await this.fireLifecycle("turn_end");
|
|
1036
|
-
} else {
|
|
1037
|
-
looping = false;
|
|
1038
|
-
if (this.fileHistory) {
|
|
1039
|
-
const summary = fullText.length > 60 ? fullText.slice(0, 60) + "..." : fullText;
|
|
1040
|
-
this.fileHistory.makeSnapshot(this.conversation.len(), summary);
|
|
1041
|
-
}
|
|
1042
|
-
yield { type: "loop_complete", stopReason };
|
|
1043
|
-
if (this.onLoopComplete) {
|
|
1044
|
-
try {
|
|
1045
|
-
this.onLoopComplete(this.conversation);
|
|
1046
|
-
} catch {
|
|
1047
|
-
}
|
|
1048
|
-
}
|
|
1049
|
-
}
|
|
1050
|
-
}
|
|
1051
|
-
} finally {
|
|
1052
|
-
await this.fireLifecycle("session_end");
|
|
1053
|
-
}
|
|
1054
|
-
}
|
|
1055
|
-
// Fire a lifecycle hook event and queue any non-empty hook output as a
|
|
1056
|
-
// notification to be surfaced on the next turn. No-op without a HookEngine.
|
|
1057
|
-
async fireLifecycle(event, message) {
|
|
1058
|
-
if (!this.hookEngine) {
|
|
1059
|
-
return;
|
|
1060
|
-
}
|
|
1061
|
-
const results = await this.hookEngine.fire(event, { event, message });
|
|
1062
|
-
for (const r of results) {
|
|
1063
|
-
if (r.output) {
|
|
1064
|
-
this.hookEngine.recordNotification(r.output);
|
|
1065
|
-
}
|
|
1066
|
-
}
|
|
1067
|
-
}
|
|
1068
|
-
// Sleep for ms, resolving early with `true` if the abort signal fires during
|
|
1069
|
-
// the wait (ctx-aware). Resolves `false` on timeout.
|
|
1070
|
-
interruptibleSleep(ms) {
|
|
1071
|
-
return new Promise((resolve3) => {
|
|
1072
|
-
if (this.abortSignal?.aborted) {
|
|
1073
|
-
resolve3(true);
|
|
1074
|
-
return;
|
|
1075
|
-
}
|
|
1076
|
-
const onAbort = () => {
|
|
1077
|
-
clearTimeout(timer);
|
|
1078
|
-
resolve3(true);
|
|
1079
|
-
};
|
|
1080
|
-
const timer = setTimeout(() => {
|
|
1081
|
-
this.abortSignal?.removeEventListener("abort", onAbort);
|
|
1082
|
-
resolve3(false);
|
|
1083
|
-
}, ms);
|
|
1084
|
-
this.abortSignal?.addEventListener("abort", onAbort, { once: true });
|
|
1085
|
-
});
|
|
1086
|
-
}
|
|
1087
|
-
async executeTools(toolUses) {
|
|
1088
|
-
const events = [];
|
|
1089
|
-
const batches = this.partitionToolCalls(toolUses);
|
|
1090
|
-
for (const batch of batches) {
|
|
1091
|
-
const batchEvents = await this.executeBatch(
|
|
1092
|
-
batch.blocks,
|
|
1093
|
-
batch.concurrent && batch.blocks.length > 1
|
|
1094
|
-
);
|
|
1095
|
-
events.push(...batchEvents);
|
|
1096
|
-
}
|
|
1097
|
-
return events;
|
|
1098
|
-
}
|
|
1099
|
-
partitionToolCalls(toolUses) {
|
|
1100
|
-
const batches = [];
|
|
1101
|
-
for (const tu of toolUses) {
|
|
1102
|
-
const tool = this.registry.get(tu.toolName);
|
|
1103
|
-
const safe = tool ? tool.isConcurrencySafe?.(tu.arguments ?? {}) ?? tool.category === "read" : false;
|
|
1104
|
-
if (safe && batches.length > 0 && batches[batches.length - 1].concurrent) {
|
|
1105
|
-
batches[batches.length - 1].blocks.push(tu);
|
|
1106
|
-
} else {
|
|
1107
|
-
batches.push({ concurrent: safe, blocks: [tu] });
|
|
1108
|
-
}
|
|
1109
|
-
}
|
|
1110
|
-
return batches;
|
|
1111
|
-
}
|
|
1112
|
-
// executeBatch runs a set of tool calls through permission checks, hooks,
|
|
1113
|
-
// and the streaming executor. When parallel is true all calls run
|
|
1114
|
-
// concurrently; otherwise they run one at a time.
|
|
1115
|
-
async executeBatch(toolUses, parallel) {
|
|
1116
|
-
const events = [];
|
|
1117
|
-
const executor = new StreamingExecutor(this.registry, {
|
|
1118
|
-
workDir: this.workDir,
|
|
1119
|
-
abortSignal: this.abortSignal,
|
|
1120
|
-
fileHistory: this.fileHistory,
|
|
1121
|
-
fileStateCache: this.fileStateCache
|
|
1122
|
-
});
|
|
1123
|
-
for (const tu of toolUses) {
|
|
1124
|
-
if (this.abortSignal?.aborted) {
|
|
1125
|
-
events.push({
|
|
1126
|
-
type: "tool_result",
|
|
1127
|
-
toolName: tu.toolName,
|
|
1128
|
-
toolId: tu.toolUseId,
|
|
1129
|
-
output: "Error: command interrupted",
|
|
1130
|
-
isError: true,
|
|
1131
|
-
elapsed: 0
|
|
1132
|
-
});
|
|
1133
|
-
continue;
|
|
1134
|
-
}
|
|
1135
|
-
if (this.hookEngine) {
|
|
1136
|
-
const hookResult = await this.hookEngine.firePreToolHooks(tu.toolName, tu.arguments);
|
|
1137
|
-
if (hookResult.rejected) {
|
|
1138
|
-
events.push({
|
|
1139
|
-
type: "tool_result",
|
|
1140
|
-
toolName: tu.toolName,
|
|
1141
|
-
toolId: tu.toolUseId,
|
|
1142
|
-
output: `Rejected by hook: ${hookResult.reason}`,
|
|
1143
|
-
isError: true,
|
|
1144
|
-
elapsed: 0
|
|
1145
|
-
});
|
|
1146
|
-
continue;
|
|
1147
|
-
}
|
|
1148
|
-
}
|
|
1149
|
-
const tool = this.registry.get(tu.toolName);
|
|
1150
|
-
const category = tool?.category ?? "command";
|
|
1151
|
-
const decision = this.checker.check(tu.toolName, category, tu.arguments);
|
|
1152
|
-
if (decision.effect === "deny") {
|
|
1153
|
-
events.push({
|
|
1154
|
-
type: "tool_result",
|
|
1155
|
-
toolName: tu.toolName,
|
|
1156
|
-
toolId: tu.toolUseId,
|
|
1157
|
-
output: `Permission denied: ${decision.reason}. This operation has been blocked by the security policy. Inform the user that the command was denied; do not describe what the command would do.`,
|
|
1158
|
-
isError: true,
|
|
1159
|
-
elapsed: 0
|
|
1160
|
-
});
|
|
1161
|
-
continue;
|
|
1162
|
-
}
|
|
1163
|
-
if (decision.effect === "ask" && this.onPermissionRequest) {
|
|
1164
|
-
const response = await this.onPermissionRequest(tu.toolName, tu.arguments, decision);
|
|
1165
|
-
if (response === "deny") {
|
|
1166
|
-
events.push({
|
|
1167
|
-
type: "tool_result",
|
|
1168
|
-
toolName: tu.toolName,
|
|
1169
|
-
toolId: tu.toolUseId,
|
|
1170
|
-
output: REJECTED_TOOL_RESULT,
|
|
1171
|
-
isError: true,
|
|
1172
|
-
elapsed: 0
|
|
1173
|
-
});
|
|
1174
|
-
continue;
|
|
1175
|
-
}
|
|
1176
|
-
if (response === "allowAlways") {
|
|
1177
|
-
this.checker.allowAlways(tu.toolName, tu.arguments);
|
|
1178
|
-
}
|
|
1179
|
-
}
|
|
1180
|
-
executor.submit(tu.toolUseId, tu.toolName, tu.arguments);
|
|
1181
|
-
if (!parallel) {
|
|
1182
|
-
const batchResults = await executor.collectResults();
|
|
1183
|
-
for (const r of batchResults) {
|
|
1184
|
-
await this.processToolResult(r, toolUses, events);
|
|
1185
|
-
}
|
|
1186
|
-
}
|
|
1187
|
-
}
|
|
1188
|
-
if (parallel) {
|
|
1189
|
-
const batchResults = await executor.collectResults();
|
|
1190
|
-
for (const r of batchResults) {
|
|
1191
|
-
await this.processToolResult(r, toolUses, events);
|
|
1192
|
-
}
|
|
1193
|
-
}
|
|
1194
|
-
return events;
|
|
1195
|
-
}
|
|
1196
|
-
// processToolResult handles a single executor result: records file-read
|
|
1197
|
-
// snapshots, emits the tool_result event, and fires post-tool hooks.
|
|
1198
|
-
async processToolResult(r, toolUses, events) {
|
|
1199
|
-
if (!r.result.isError && r.toolName === "ReadFile" && !r.result.contentBlocks?.length) {
|
|
1200
|
-
const tu = toolUses.find((t) => t.toolUseId === r.toolId);
|
|
1201
|
-
const p = strArg(tu?.arguments ?? {}, "file_path");
|
|
1202
|
-
if (p) {
|
|
1203
|
-
this.recoveryState.recordFileRead(p, r.result.output);
|
|
1204
|
-
}
|
|
1205
|
-
}
|
|
1206
|
-
events.push({
|
|
1207
|
-
type: "tool_result",
|
|
1208
|
-
toolName: r.toolName,
|
|
1209
|
-
toolId: r.toolId,
|
|
1210
|
-
output: r.result.output,
|
|
1211
|
-
...r.result.contentBlocks?.length ? { contentBlocks: r.result.contentBlocks } : {},
|
|
1212
|
-
isError: r.result.isError,
|
|
1213
|
-
elapsed: r.elapsed
|
|
1214
|
-
});
|
|
1215
|
-
if (this.hookEngine) {
|
|
1216
|
-
const hookResults = await this.hookEngine.fire("post_tool_use", {
|
|
1217
|
-
event: "post_tool_use",
|
|
1218
|
-
toolName: r.toolName,
|
|
1219
|
-
message: r.result.output
|
|
1220
|
-
});
|
|
1221
|
-
for (const hr of hookResults) {
|
|
1222
|
-
if (hr.output) {
|
|
1223
|
-
this.hookEngine.recordNotification(hr.output);
|
|
1224
|
-
}
|
|
1225
|
-
}
|
|
1226
|
-
}
|
|
1227
|
-
}
|
|
1228
|
-
/**
|
|
1229
|
-
* Persist the most recently appended conversation message to the session log.
|
|
1230
|
-
*
|
|
1231
|
-
* Persistence lives in the main loop rather than in individual frontends: both
|
|
1232
|
-
* the TUI and Web share the same recording path, ensuring intermediate assistant
|
|
1233
|
-
* text and complete tool-call chains are captured for session restoration.
|
|
1234
|
-
* Skipped when sessionId is empty (one-shot invocations, sub-agents).
|
|
1235
|
-
*/
|
|
1236
|
-
persistLastMessage() {
|
|
1237
|
-
if (!this.workDir || !this.sessionId) {
|
|
1238
|
-
return;
|
|
1239
|
-
}
|
|
1240
|
-
const msgs = this.conversation.getMessages();
|
|
1241
|
-
if (msgs.length === 0) {
|
|
1242
|
-
return;
|
|
1243
|
-
}
|
|
1244
|
-
const last = msgs[msgs.length - 1];
|
|
1245
|
-
saveMessage(this.workDir, this.sessionId, {
|
|
1246
|
-
role: last.role,
|
|
1247
|
-
content: last.content,
|
|
1248
|
-
timestamp: Math.floor(Date.now() / 1e3),
|
|
1249
|
-
...last.toolUses?.length ? { tool_uses: toolUsesToRecords(last.toolUses) } : {},
|
|
1250
|
-
...last.toolResults?.length ? { tool_results: toolResultsToRecords(last.toolResults) } : {}
|
|
1251
|
-
});
|
|
1252
|
-
}
|
|
1253
|
-
};
|
|
1254
|
-
function parseRetryAfter(header) {
|
|
1255
|
-
if (!header) {
|
|
1256
|
-
return 5e3;
|
|
1257
|
-
}
|
|
1258
|
-
const secs = parseInt(header, 10);
|
|
1259
|
-
if (!Number.isNaN(secs)) {
|
|
1260
|
-
return secs * 1e3;
|
|
1261
|
-
}
|
|
1262
|
-
return 5e3;
|
|
1263
|
-
}
|
|
1264
|
-
|
|
1265
|
-
export {
|
|
1266
|
-
RecoveryState,
|
|
1267
|
-
getOrCreatePlanPath,
|
|
1268
|
-
savePlan,
|
|
1269
|
-
loadPlan,
|
|
1270
|
-
planExists,
|
|
1271
|
-
resetPlanPath,
|
|
1272
|
-
getCurrentPlanPath,
|
|
1273
|
-
coordinatorReminder,
|
|
1274
|
-
buildPlanModeReminder,
|
|
1275
|
-
buildPlanModeExitReminder,
|
|
1276
|
-
buildPlanModeReentryReminder,
|
|
1277
|
-
TOOL_RESULT_PREVIEW_CHARS,
|
|
1278
|
-
toDisplayPreview,
|
|
1279
|
-
replaceToolResultContent,
|
|
1280
|
-
isSpillReadback,
|
|
1281
|
-
applyBudget,
|
|
1282
|
-
persistLargeResult,
|
|
1283
|
-
StreamingExecutor,
|
|
1284
|
-
Agent
|
|
1285
|
-
};
|