@criogaid/pi-hashline-edit 0.5.1 → 0.6.0
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 +51 -15
- package/package.json +6 -6
- package/src/core/apply.test.ts +66 -16
- package/src/core/apply.ts +36 -19
- package/src/core/lines.ts +3 -3
- package/src/index.ts +2 -0
- package/src/integration/forget-grep.test.ts +98 -0
- package/src/integration/fusion-dispatch.test.ts +343 -0
- package/src/integration/grep-rg.test.ts +269 -33
- package/src/integration/mutation-file-types.test.ts +44 -0
- package/src/pi/action-fusion.test.ts +71 -128
- package/src/pi/action-fusion.ts +83 -45
- package/src/pi/argument-validation.test.ts +136 -0
- package/src/pi/argument-validation.ts +103 -0
- package/src/pi/budgets.ts +4 -1
- package/src/pi/config.test.ts +1 -0
- package/src/pi/config.ts +4 -0
- package/src/pi/directory-sync.test.ts +1 -1
- package/src/pi/edit-tool.ts +55 -36
- package/src/pi/execute.test.ts +185 -645
- package/src/pi/failure-context.test.ts +4 -3
- package/src/pi/failure-path.test.ts +3 -3
- package/src/pi/file-commit.test.ts +24 -17
- package/src/pi/file-commit.ts +36 -9
- package/src/pi/file-snapshot.test.ts +24 -0
- package/src/pi/forget-tool.ts +268 -0
- package/src/pi/forget.test.ts +343 -0
- package/src/pi/forget.testing.ts +273 -0
- package/src/pi/grep-output.ts +57 -28
- package/src/pi/grep-search.ts +35 -12
- package/src/pi/grep-tool.ts +28 -9
- package/src/pi/grep.test.ts +173 -152
- package/src/pi/mutation-result.test.ts +23 -0
- package/src/pi/mutation-runner.ts +8 -4
- package/src/pi/path.ts +16 -2
- package/src/pi/pi.test.ts +3 -2
- package/src/pi/read-tool.ts +58 -26
- package/src/pi/read.test.ts +361 -0
- package/src/pi/registration.test.ts +115 -2
- package/src/pi/render.test.ts +45 -14
- package/src/pi/replace-tool.ts +18 -27
- package/src/pi/replace.test.ts +8 -107
- package/src/pi/result-safety.test.ts +123 -149
- package/src/pi/rg-match-bytes.ts +95 -0
- package/src/pi/rg-process.test.ts +40 -59
- package/src/pi/rg-text-view.ts +52 -5
- package/src/pi/tool-call.testing.ts +50 -0
- package/src/pi/tool-prompts.ts +15 -0
- package/src/pi/write-tool.ts +17 -26
- package/src/pi/write.test.ts +70 -61
- package/src/pi/e2e-scenarios.test.ts +0 -361
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { test } from "node:test";
|
|
5
|
+
import { FORGET_MIN_BYTES } from "./budgets.ts";
|
|
6
|
+
import { withResultTag } from "./forget-tool.ts";
|
|
7
|
+
import { DEFAULT_CONFIG } from "./config.ts";
|
|
8
|
+
import {
|
|
9
|
+
assertForgotten,
|
|
10
|
+
finish,
|
|
11
|
+
forgetCall,
|
|
12
|
+
openForgetSession,
|
|
13
|
+
SESSION_TIMEOUT_MS,
|
|
14
|
+
taggedResultId,
|
|
15
|
+
toolResponse,
|
|
16
|
+
toolResult,
|
|
17
|
+
} from "./forget.testing.ts";
|
|
18
|
+
|
|
19
|
+
const LOG_BODY = `build payload ${"x".repeat(FORGET_MIN_BYTES)}\nlast line\n`;
|
|
20
|
+
const PNG = Buffer.from(
|
|
21
|
+
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",
|
|
22
|
+
"base64",
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
for (const { name, filename, body, receiptSuffix } of [
|
|
26
|
+
{ name: "ordinary log", filename: "build.log", body: LOG_BODY, receiptSuffix: " · lines 1–2" },
|
|
27
|
+
{
|
|
28
|
+
name: "NUL log containing a row-like source line",
|
|
29
|
+
filename: "build.log",
|
|
30
|
+
body: `${LOG_BODY}\0\n1│source text\n`,
|
|
31
|
+
receiptSuffix: "",
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
name: "UTF-8 log containing a Unicode line separator",
|
|
35
|
+
filename: "build.log",
|
|
36
|
+
body: `before\u2028${LOG_BODY}`,
|
|
37
|
+
receiptSuffix: " · lines 1–2",
|
|
38
|
+
},
|
|
39
|
+
{ name: "PNG image", filename: "picture.png", body: PNG, receiptSuffix: " · image" },
|
|
40
|
+
]) {
|
|
41
|
+
test(`${name} read then forgotten → the next request contains only a receipt`, {
|
|
42
|
+
timeout: SESSION_TIMEOUT_MS,
|
|
43
|
+
}, async (t) => {
|
|
44
|
+
const f = await openForgetSession(t);
|
|
45
|
+
await writeFile(join(f.cwd, filename), body);
|
|
46
|
+
await f.prompt(
|
|
47
|
+
toolResponse(f.read("read-log", filename)),
|
|
48
|
+
(messages) => toolResponse(forgetCall(messages, "read-log")),
|
|
49
|
+
finish,
|
|
50
|
+
);
|
|
51
|
+
const original = toolResult(f.requests[1], "read-log");
|
|
52
|
+
const id = taggedResultId(original);
|
|
53
|
+
assert.ok(id);
|
|
54
|
+
if (typeof body === "string") {
|
|
55
|
+
for (const line of body.trimEnd().split("\n")) {
|
|
56
|
+
assert.ok(
|
|
57
|
+
original.content.some((block) => block.type === "text" && block.text.includes(line)),
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
} else {
|
|
61
|
+
assert.ok(original.content.some((block) => block.type === "image"));
|
|
62
|
+
}
|
|
63
|
+
assert.equal(f.requests.length, 3, "A standalone forget must allow the model to continue");
|
|
64
|
+
const forgotten = toolResult(f.requests[2], "read-log");
|
|
65
|
+
const remainingText = forgotten.content
|
|
66
|
+
.filter((block) => block.type === "text")
|
|
67
|
+
.map((block) => block.text)
|
|
68
|
+
.join("\n");
|
|
69
|
+
assert.ok(
|
|
70
|
+
!remainingText.includes("build payload"),
|
|
71
|
+
"Consumed file content must not be sent again",
|
|
72
|
+
);
|
|
73
|
+
assert.ok(!remainingText.includes(filename), "File headers are forgotten with the body");
|
|
74
|
+
assertForgotten(forgotten, id);
|
|
75
|
+
const receipt = `${join(f.cwd, filename)}${receiptSuffix}`;
|
|
76
|
+
assert.deepEqual(f.rawResult("forget-call").details, { forgotten: [{ id, receipt }] });
|
|
77
|
+
assert.ok(f.renderForgetCard().includes(receipt));
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
test("forget in a mixed tool batch → work continues and unselected results stay intact", {
|
|
82
|
+
timeout: SESSION_TIMEOUT_MS,
|
|
83
|
+
}, async (t) => {
|
|
84
|
+
const f = await openForgetSession(t);
|
|
85
|
+
for (const filename of ["build.log", "test.log", "keep.log"]) {
|
|
86
|
+
await writeFile(join(f.cwd, filename), LOG_BODY);
|
|
87
|
+
}
|
|
88
|
+
await writeFile(join(f.cwd, "next.txt"), "next task");
|
|
89
|
+
await f.prompt(
|
|
90
|
+
toolResponse(
|
|
91
|
+
f.read("selected"),
|
|
92
|
+
f.read("selected-too", "test.log"),
|
|
93
|
+
f.read("kept", "keep.log"),
|
|
94
|
+
),
|
|
95
|
+
(messages) =>
|
|
96
|
+
toolResponse(forgetCall(messages, "selected", "selected-too"), f.read("next", "next.txt")),
|
|
97
|
+
finish,
|
|
98
|
+
);
|
|
99
|
+
assert.equal(f.requests.length, 3);
|
|
100
|
+
for (const callId of ["selected", "selected-too"]) {
|
|
101
|
+
const id = taggedResultId(toolResult(f.requests[1], callId));
|
|
102
|
+
assert.ok(id);
|
|
103
|
+
assertForgotten(toolResult(f.requests[2], callId), id);
|
|
104
|
+
}
|
|
105
|
+
assert.deepEqual(toolResult(f.requests[2], "kept"), toolResult(f.requests[1], "kept"));
|
|
106
|
+
assert.equal(toolResult(f.requests[2], "next").isError, false);
|
|
107
|
+
const expected = ["selected", "selected-too"].map((callId, index) => ({
|
|
108
|
+
id: taggedResultId(toolResult(f.requests[1], callId)),
|
|
109
|
+
receipt: `${join(f.cwd, index === 0 ? "build.log" : "test.log")} · lines 1–2`,
|
|
110
|
+
}));
|
|
111
|
+
assert.deepEqual(f.rawResult("forget-call").details, { forgotten: expected });
|
|
112
|
+
const displayed = f.renderForgetCard();
|
|
113
|
+
assert.equal(displayed.split("\n")[0].trimEnd(), `forget · ${expected.length} results`);
|
|
114
|
+
assert.doesNotMatch(displayed, /Forgotten ·/);
|
|
115
|
+
const expanded = f.renderForgetCard(true);
|
|
116
|
+
for (const { id, receipt } of expected) {
|
|
117
|
+
assert.ok(id);
|
|
118
|
+
assert.ok(displayed.includes(receipt));
|
|
119
|
+
assert.ok(!displayed.includes(id));
|
|
120
|
+
assert.ok(expanded.includes(`${id} · ${receipt}`));
|
|
121
|
+
}
|
|
122
|
+
assert.ok(!displayed.includes("keep.log"));
|
|
123
|
+
const payload = JSON.stringify(await f.requestPayload(2));
|
|
124
|
+
assert.doesNotMatch(payload, /"forgetReceipt"|"forgotten":/);
|
|
125
|
+
for (const { receipt } of expected) assert.ok(!payload.includes(receipt));
|
|
126
|
+
const response = toolResult(f.requests[2], "forget-call");
|
|
127
|
+
assert.deepEqual(response.content, f.rawResult("forget-call").content);
|
|
128
|
+
for (const block of response.content) {
|
|
129
|
+
if (block.type === "text") assert.ok(payload.includes(block.text));
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
for (const mode of ["pagination", "byte truncation"] as const) {
|
|
134
|
+
test(`read stops at ${mode} → forget receipt names only the returned lines`, {
|
|
135
|
+
timeout: SESSION_TIMEOUT_MS,
|
|
136
|
+
}, async (t) => {
|
|
137
|
+
const f = await openForgetSession(t);
|
|
138
|
+
const path = join(f.cwd, "build.log");
|
|
139
|
+
const maxReadBytes = DEFAULT_CONFIG.read.maxKiB * 1024;
|
|
140
|
+
const trailingLine = mode === "byte truncation" ? "y".repeat(maxReadBytes) : "next page";
|
|
141
|
+
await writeFile(path, `skip this line\n${LOG_BODY}${trailingLine}\n`);
|
|
142
|
+
const read = f.read("read-log");
|
|
143
|
+
await f.prompt(
|
|
144
|
+
toolResponse({
|
|
145
|
+
...read,
|
|
146
|
+
arguments: { ...read.arguments, offset: 2, limit: mode === "pagination" ? 2 : 3 },
|
|
147
|
+
}),
|
|
148
|
+
(messages) => toolResponse(forgetCall(messages, "read-log")),
|
|
149
|
+
finish,
|
|
150
|
+
);
|
|
151
|
+
const id = taggedResultId(toolResult(f.requests[1], "read-log"));
|
|
152
|
+
assert.ok(id);
|
|
153
|
+
const receipt = `${path} · lines 2–3${mode === "byte truncation" ? " · truncated" : ""}`;
|
|
154
|
+
assert.deepEqual(f.rawResult("forget-call").details, { forgotten: [{ id, receipt }] });
|
|
155
|
+
assert.ok(f.renderForgetCard().includes(receipt));
|
|
156
|
+
assertForgotten(toolResult(f.requests[2], "read-log"), id);
|
|
157
|
+
const details = f.rawResult("read-log").details;
|
|
158
|
+
assert.ok(details && typeof details === "object");
|
|
159
|
+
assert.ok(mode === "pagination" ? "pagination" in details : "truncation" in details);
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
test("forget with a note → calls, saved facts, source bytes and raw session remain", {
|
|
164
|
+
timeout: SESSION_TIMEOUT_MS,
|
|
165
|
+
}, async (t) => {
|
|
166
|
+
const f = await openForgetSession(t);
|
|
167
|
+
const path = join(f.cwd, "build.log");
|
|
168
|
+
const note = "Build failed during dependency installation.";
|
|
169
|
+
const read = f.read("read-log");
|
|
170
|
+
await writeFile(path, LOG_BODY);
|
|
171
|
+
await f.prompt(
|
|
172
|
+
toolResponse(read),
|
|
173
|
+
(messages) => {
|
|
174
|
+
const call = forgetCall(messages, "read-log");
|
|
175
|
+
return toolResponse({ ...call, arguments: { ...call.arguments, note } });
|
|
176
|
+
},
|
|
177
|
+
finish,
|
|
178
|
+
);
|
|
179
|
+
const calls = f.requests[2].flatMap((message) =>
|
|
180
|
+
message.role === "assistant"
|
|
181
|
+
? message.content.filter((block) => block.type === "toolCall")
|
|
182
|
+
: [],
|
|
183
|
+
);
|
|
184
|
+
assert.deepEqual(
|
|
185
|
+
calls.find((call) => call.id === read.id),
|
|
186
|
+
read,
|
|
187
|
+
);
|
|
188
|
+
assert.equal(calls.find((call) => call.name === "forget")?.arguments.note, note);
|
|
189
|
+
const original = f.sessionManager
|
|
190
|
+
.getEntries()
|
|
191
|
+
.find(
|
|
192
|
+
(entry) =>
|
|
193
|
+
entry.type === "message" &&
|
|
194
|
+
entry.message.role === "toolResult" &&
|
|
195
|
+
entry.message.toolCallId === read.id,
|
|
196
|
+
);
|
|
197
|
+
assert.ok(original?.type === "message" && original.message.role === "toolResult");
|
|
198
|
+
assert.deepEqual(original.message.content, toolResult(f.requests[1], read.id).content);
|
|
199
|
+
assert.equal(await readFile(path, "utf8"), LOG_BODY);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
for (const invalid of ["old result", "unknown result"] as const) {
|
|
203
|
+
test(`eligible id combined with ${invalid} → the whole forget call is rejected`, {
|
|
204
|
+
timeout: SESSION_TIMEOUT_MS,
|
|
205
|
+
}, async (t) => {
|
|
206
|
+
const f = await openForgetSession(t);
|
|
207
|
+
await writeFile(join(f.cwd, "build.log"), LOG_BODY);
|
|
208
|
+
await f.prompt(
|
|
209
|
+
toolResponse(f.read("old")),
|
|
210
|
+
toolResponse(f.read("current")),
|
|
211
|
+
(messages) => {
|
|
212
|
+
const current = forgetCall(messages, "current");
|
|
213
|
+
const currentId = taggedResultId(toolResult(messages, "current"));
|
|
214
|
+
assert.ok(currentId);
|
|
215
|
+
const old = taggedResultId(toolResult(messages, "old"));
|
|
216
|
+
assert.ok(old);
|
|
217
|
+
const invalidId = invalid === "old result" ? old : "r00000";
|
|
218
|
+
assert.notEqual(taggedResultId(toolResult(messages, "current")), invalidId);
|
|
219
|
+
return toolResponse({ ...current, arguments: { ids: [currentId, invalidId] } });
|
|
220
|
+
},
|
|
221
|
+
finish,
|
|
222
|
+
);
|
|
223
|
+
assert.equal(toolResult(f.requests[3], "forget-call").isError, true);
|
|
224
|
+
for (const id of ["old", "current"]) {
|
|
225
|
+
assert.deepEqual(toolResult(f.requests[3], id), toolResult(f.requests[2], id));
|
|
226
|
+
}
|
|
227
|
+
assert.ok(!f.sessionManager.getEntries().some((entry) => entry.type === "context_edit"));
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
for (const invalid of [
|
|
232
|
+
"empty ids",
|
|
233
|
+
"duplicate ids",
|
|
234
|
+
"malformed id",
|
|
235
|
+
"multiple invalid fields",
|
|
236
|
+
] as const) {
|
|
237
|
+
test(`${invalid} from a model call → schema rejection leaves the result intact`, {
|
|
238
|
+
timeout: SESSION_TIMEOUT_MS,
|
|
239
|
+
}, async (t) => {
|
|
240
|
+
const f = await openForgetSession(t);
|
|
241
|
+
await writeFile(join(f.cwd, "build.log"), LOG_BODY);
|
|
242
|
+
await f.prompt(
|
|
243
|
+
toolResponse(f.read("read-log")),
|
|
244
|
+
(messages) => {
|
|
245
|
+
const id = taggedResultId(toolResult(messages, "read-log"));
|
|
246
|
+
assert.ok(id);
|
|
247
|
+
const ids =
|
|
248
|
+
invalid === "empty ids"
|
|
249
|
+
? []
|
|
250
|
+
: invalid === "duplicate ids"
|
|
251
|
+
? [id, id]
|
|
252
|
+
: ["not-a-result-id"];
|
|
253
|
+
return toolResponse({
|
|
254
|
+
type: "toolCall",
|
|
255
|
+
id: "forget-call",
|
|
256
|
+
name: "forget",
|
|
257
|
+
arguments: invalid === "multiple invalid fields" ? { ids, note: "" } : { ids },
|
|
258
|
+
});
|
|
259
|
+
},
|
|
260
|
+
finish,
|
|
261
|
+
);
|
|
262
|
+
const rejection = toolResult(f.requests[2], "forget-call");
|
|
263
|
+
assert.equal(rejection.isError, true);
|
|
264
|
+
if (invalid === "multiple invalid fields") {
|
|
265
|
+
const text = rejection.content
|
|
266
|
+
.filter((block) => block.type === "text")
|
|
267
|
+
.map((block) => block.text)
|
|
268
|
+
.join("\n");
|
|
269
|
+
assert.match(text, /\n - ids/);
|
|
270
|
+
assert.match(text, /\n - note:/);
|
|
271
|
+
}
|
|
272
|
+
assert.deepEqual(toolResult(f.requests[2], "read-log"), toolResult(f.requests[1], "read-log"));
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function collidingToolCallIds() {
|
|
277
|
+
const maxCandidateCalls = 20_000;
|
|
278
|
+
const seen = new Map<string, string>();
|
|
279
|
+
for (let index = 0; index < maxCandidateCalls; index++) {
|
|
280
|
+
const callId = `call_collision_${index}`;
|
|
281
|
+
const id = taggedResultId(
|
|
282
|
+
withResultTag(
|
|
283
|
+
callId,
|
|
284
|
+
{ content: [{ type: "text", text: LOG_BODY }] },
|
|
285
|
+
true,
|
|
286
|
+
() => "build.log",
|
|
287
|
+
),
|
|
288
|
+
);
|
|
289
|
+
assert.ok(id);
|
|
290
|
+
const earlier = seen.get(id);
|
|
291
|
+
if (earlier) return [earlier, callId];
|
|
292
|
+
seen.set(id, callId);
|
|
293
|
+
}
|
|
294
|
+
throw new Error("No colliding public result tags found within the fixture search bound");
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
for (const batch of ["same batch", "older visible batch"] as const) {
|
|
298
|
+
test(`distinct read calls have colliding tags in the ${batch} → neither result is forgotten`, {
|
|
299
|
+
timeout: SESSION_TIMEOUT_MS,
|
|
300
|
+
}, async (t) => {
|
|
301
|
+
const f = await openForgetSession(t);
|
|
302
|
+
await writeFile(join(f.cwd, "build.log"), LOG_BODY);
|
|
303
|
+
// Find real call ids that collide, then let actual reads produce the tagged results.
|
|
304
|
+
const [first, second] = collidingToolCallIds();
|
|
305
|
+
const reads =
|
|
306
|
+
batch === "same batch"
|
|
307
|
+
? [toolResponse(f.read(first), f.read(second))]
|
|
308
|
+
: [toolResponse(f.read(first)), toolResponse(f.read(second))];
|
|
309
|
+
await f.prompt(
|
|
310
|
+
...reads,
|
|
311
|
+
(messages) => {
|
|
312
|
+
assert.equal(
|
|
313
|
+
taggedResultId(toolResult(messages, first)),
|
|
314
|
+
taggedResultId(toolResult(messages, second)),
|
|
315
|
+
);
|
|
316
|
+
return toolResponse(forgetCall(messages, second));
|
|
317
|
+
},
|
|
318
|
+
finish,
|
|
319
|
+
);
|
|
320
|
+
const before = f.requests[reads.length];
|
|
321
|
+
const after = f.requests[reads.length + 1];
|
|
322
|
+
assert.equal(toolResult(after, "forget-call").isError, true);
|
|
323
|
+
assert.deepEqual(toolResult(after, first), toolResult(before, first));
|
|
324
|
+
assert.deepEqual(toolResult(after, second), toolResult(before, second));
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
test("model output is truncated while requesting forget → Pi rejects the call and retains the result", {
|
|
329
|
+
timeout: SESSION_TIMEOUT_MS,
|
|
330
|
+
}, async (t) => {
|
|
331
|
+
const f = await openForgetSession(t);
|
|
332
|
+
await writeFile(join(f.cwd, "build.log"), LOG_BODY);
|
|
333
|
+
await f.prompt(
|
|
334
|
+
toolResponse(f.read("read-log")),
|
|
335
|
+
(messages) => ({
|
|
336
|
+
content: [forgetCall(messages, "read-log")],
|
|
337
|
+
stopReason: "length",
|
|
338
|
+
}),
|
|
339
|
+
finish,
|
|
340
|
+
);
|
|
341
|
+
assert.equal(toolResult(f.requests[2], "forget-call").isError, true);
|
|
342
|
+
assert.deepEqual(toolResult(f.requests[2], "read-log"), toolResult(f.requests[1], "read-log"));
|
|
343
|
+
});
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
/** Real Pi sessions with scripted model responses; no provider requests leave the process. */
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { stripVTControlCharacters } from "node:util";
|
|
7
|
+
import type { TestContext } from "node:test";
|
|
8
|
+
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
9
|
+
import type { AssistantMessage, Message, ToolCall } from "@earendil-works/pi-ai";
|
|
10
|
+
import { AssistantMessageEventStream } from "@earendil-works/pi-ai/utils/event-stream";
|
|
11
|
+
import { normalizeContext } from "@earendil-works/pi-ai/utils/transcript";
|
|
12
|
+
import { stream as streamCompletions } from "@earendil-works/pi-ai/api/openai-completions";
|
|
13
|
+
import {
|
|
14
|
+
createAgentSession,
|
|
15
|
+
initTheme,
|
|
16
|
+
DefaultResourceLoader,
|
|
17
|
+
ModelRuntime,
|
|
18
|
+
SessionManager,
|
|
19
|
+
SettingsManager,
|
|
20
|
+
} from "@earendil-works/pi-coding-agent";
|
|
21
|
+
import { DEFAULT_CONFIG } from "./config.ts";
|
|
22
|
+
import { registerForgetTool } from "./forget-tool.ts";
|
|
23
|
+
import { makeGrepOverride } from "./grep-tool.ts";
|
|
24
|
+
import { makeReadOverride } from "./read-tool.ts";
|
|
25
|
+
import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
|
|
26
|
+
|
|
27
|
+
export const SESSION_TIMEOUT_MS = 30_000;
|
|
28
|
+
type Response = Pick<AssistantMessage, "content" | "stopReason">;
|
|
29
|
+
type Script = Response | ((messages: readonly Message[]) => Response);
|
|
30
|
+
export const finish: Response = {
|
|
31
|
+
content: [{ type: "text", text: "Processed." }],
|
|
32
|
+
stopReason: "stop",
|
|
33
|
+
};
|
|
34
|
+
export const toolResponse = (...content: ToolCall[]): Response => ({
|
|
35
|
+
content,
|
|
36
|
+
stopReason: "toolUse",
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
/** Extract the public result tag without assuming how its id is generated. */
|
|
40
|
+
export function taggedResultId(result: Pick<AgentToolResult<unknown>, "content">) {
|
|
41
|
+
const last = result.content.at(-1);
|
|
42
|
+
return last?.type === "text" ? /^\[result (r[0-9a-f]{5})\]$/.exec(last.text)?.[1] : undefined;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function toolResult(messages: readonly Message[], id: string) {
|
|
46
|
+
const result = messages.find(
|
|
47
|
+
(message) => message.role === "toolResult" && message.toolCallId === id,
|
|
48
|
+
);
|
|
49
|
+
assert.ok(result?.role === "toolResult", `Missing result for ${id}`);
|
|
50
|
+
return result;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function forgetCall(messages: readonly Message[], ...sourceIds: string[]): ToolCall {
|
|
54
|
+
const ids = sourceIds.map((sourceId) => {
|
|
55
|
+
const result = toolResult(messages, sourceId);
|
|
56
|
+
assert.equal(result.isError, false);
|
|
57
|
+
const id = taggedResultId(result);
|
|
58
|
+
assert.ok(id, `Result ${sourceId} must be eligible for forgetting`);
|
|
59
|
+
return id;
|
|
60
|
+
});
|
|
61
|
+
return { type: "toolCall", id: "forget-call", name: "forget", arguments: { ids } };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function openForgetSession(t: TestContext) {
|
|
65
|
+
const cwd = await mkdtemp(join(tmpdir(), "hashline-forget-"));
|
|
66
|
+
let disposeSession: (() => void) | undefined;
|
|
67
|
+
t.after(async () => {
|
|
68
|
+
disposeSession?.();
|
|
69
|
+
await rm(cwd, { recursive: true, force: true });
|
|
70
|
+
});
|
|
71
|
+
const modelRuntime = await ModelRuntime.create({
|
|
72
|
+
authPath: join(cwd, "auth.json"),
|
|
73
|
+
modelsPath: null,
|
|
74
|
+
modelsStorePath: join(cwd, "models.json"),
|
|
75
|
+
refreshOnCreate: false,
|
|
76
|
+
allowModelNetwork: false,
|
|
77
|
+
});
|
|
78
|
+
modelRuntime.registerProvider("forget-test", {
|
|
79
|
+
api: "openai-completions",
|
|
80
|
+
baseUrl: "https://unused.invalid",
|
|
81
|
+
apiKey: "local-test-placeholder",
|
|
82
|
+
models: [
|
|
83
|
+
{
|
|
84
|
+
id: "test",
|
|
85
|
+
name: "Test",
|
|
86
|
+
input: ["text", "image"],
|
|
87
|
+
reasoning: false,
|
|
88
|
+
contextWindow: 100_000,
|
|
89
|
+
maxTokens: 1000,
|
|
90
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
91
|
+
},
|
|
92
|
+
],
|
|
93
|
+
});
|
|
94
|
+
const model = modelRuntime.getModel("forget-test", "test");
|
|
95
|
+
assert.ok(model);
|
|
96
|
+
const sessionManager = SessionManager.inMemory(cwd);
|
|
97
|
+
const settingsManager = SettingsManager.inMemory({
|
|
98
|
+
compaction: { enabled: false },
|
|
99
|
+
retry: { enabled: false },
|
|
100
|
+
});
|
|
101
|
+
const loader = new DefaultResourceLoader({
|
|
102
|
+
cwd,
|
|
103
|
+
agentDir: cwd,
|
|
104
|
+
settingsManager,
|
|
105
|
+
noExtensions: true,
|
|
106
|
+
noSkills: true,
|
|
107
|
+
noPromptTemplates: true,
|
|
108
|
+
noThemes: true,
|
|
109
|
+
noContextFiles: true,
|
|
110
|
+
extensionFactories: [
|
|
111
|
+
(pi) => {
|
|
112
|
+
const config = { ...DEFAULT_CONFIG, forget: true };
|
|
113
|
+
pi.registerTool(makeReadOverride(cwd, config));
|
|
114
|
+
pi.registerTool(makeGrepOverride(cwd, config));
|
|
115
|
+
registerForgetTool(pi);
|
|
116
|
+
},
|
|
117
|
+
],
|
|
118
|
+
});
|
|
119
|
+
await loader.reload();
|
|
120
|
+
const { session, extensionsResult } = await createAgentSession({
|
|
121
|
+
cwd,
|
|
122
|
+
agentDir: cwd,
|
|
123
|
+
modelRuntime,
|
|
124
|
+
model,
|
|
125
|
+
settingsManager,
|
|
126
|
+
resourceLoader: loader,
|
|
127
|
+
sessionManager,
|
|
128
|
+
tools: ["read", "grep", "forget"],
|
|
129
|
+
});
|
|
130
|
+
disposeSession = () => session.dispose();
|
|
131
|
+
assert.deepEqual(extensionsResult.errors, []);
|
|
132
|
+
const requests: Message[][] = [];
|
|
133
|
+
const scripts: Script[] = [];
|
|
134
|
+
session.agent.streamFunction = (_model, context) => {
|
|
135
|
+
requests.push(structuredClone(context.messages));
|
|
136
|
+
const script = scripts.shift();
|
|
137
|
+
assert.ok(script, "Unexpected model request after the scripted responses");
|
|
138
|
+
const response = typeof script === "function" ? script(context.messages) : script;
|
|
139
|
+
const message: AssistantMessage = {
|
|
140
|
+
role: "assistant",
|
|
141
|
+
...response,
|
|
142
|
+
api: model.api,
|
|
143
|
+
provider: model.provider,
|
|
144
|
+
model: model.id,
|
|
145
|
+
timestamp: Date.now(),
|
|
146
|
+
usage: {
|
|
147
|
+
input: 0,
|
|
148
|
+
output: 0,
|
|
149
|
+
cacheRead: 0,
|
|
150
|
+
cacheWrite: 0,
|
|
151
|
+
totalTokens: 0,
|
|
152
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
153
|
+
},
|
|
154
|
+
};
|
|
155
|
+
const stream = new AssistantMessageEventStream();
|
|
156
|
+
stream.push({ type: "start", partial: message });
|
|
157
|
+
assert.ok(message.stopReason !== "pending");
|
|
158
|
+
if (message.stopReason === "error" || message.stopReason === "aborted") {
|
|
159
|
+
stream.push({ type: "error", reason: message.stopReason, error: message });
|
|
160
|
+
} else {
|
|
161
|
+
stream.push({ type: "done", reason: message.stopReason, message });
|
|
162
|
+
}
|
|
163
|
+
return stream;
|
|
164
|
+
};
|
|
165
|
+
await session.bindExtensions({});
|
|
166
|
+
const rawResult = (id: string) => {
|
|
167
|
+
const entry = sessionManager
|
|
168
|
+
.getEntries()
|
|
169
|
+
.find(
|
|
170
|
+
(entry) =>
|
|
171
|
+
entry.type === "message" &&
|
|
172
|
+
entry.message.role === "toolResult" &&
|
|
173
|
+
entry.message.toolCallId === id,
|
|
174
|
+
);
|
|
175
|
+
assert.ok(entry?.type === "message" && entry.message.role === "toolResult");
|
|
176
|
+
return entry.message;
|
|
177
|
+
};
|
|
178
|
+
return {
|
|
179
|
+
cwd,
|
|
180
|
+
requests,
|
|
181
|
+
sessionManager,
|
|
182
|
+
rawResult,
|
|
183
|
+
renderForgetCard(expanded = false) {
|
|
184
|
+
const id = "forget-call";
|
|
185
|
+
const tool = session.getToolDefinition("forget");
|
|
186
|
+
assert.ok(tool?.renderResult);
|
|
187
|
+
const call = session.agent.state.messages
|
|
188
|
+
.flatMap((message) =>
|
|
189
|
+
message.role === "assistant"
|
|
190
|
+
? message.content.filter((block) => block.type === "toolCall")
|
|
191
|
+
: [],
|
|
192
|
+
)
|
|
193
|
+
.find((call) => call.id === id);
|
|
194
|
+
assert.ok(call);
|
|
195
|
+
const result = rawResult(id);
|
|
196
|
+
const context: Parameters<typeof tool.renderResult>[3] = {
|
|
197
|
+
args: call.arguments,
|
|
198
|
+
toolCallId: id,
|
|
199
|
+
cwd,
|
|
200
|
+
state: {},
|
|
201
|
+
invalidate() {},
|
|
202
|
+
lastComponent: undefined,
|
|
203
|
+
executionStarted: true,
|
|
204
|
+
argsComplete: true,
|
|
205
|
+
isPartial: false,
|
|
206
|
+
expanded,
|
|
207
|
+
showImages: false,
|
|
208
|
+
isError: result.isError,
|
|
209
|
+
};
|
|
210
|
+
initTheme("dark");
|
|
211
|
+
const header = tool.renderCall?.(call.arguments, theme, context);
|
|
212
|
+
const component = tool.renderResult(
|
|
213
|
+
{ ...result, details: result.details },
|
|
214
|
+
{ expanded, isPartial: false },
|
|
215
|
+
theme,
|
|
216
|
+
context,
|
|
217
|
+
);
|
|
218
|
+
return stripVTControlCharacters(
|
|
219
|
+
[...(header?.render(240) ?? []), ...component.render(240)].join("\n"),
|
|
220
|
+
);
|
|
221
|
+
},
|
|
222
|
+
async requestPayload(index: number) {
|
|
223
|
+
assert.equal(model.api, "openai-completions");
|
|
224
|
+
const messages = requests[index];
|
|
225
|
+
assert.ok(messages);
|
|
226
|
+
let payload: unknown;
|
|
227
|
+
let networkCalls = 0;
|
|
228
|
+
await streamCompletions(
|
|
229
|
+
{ ...model, api: "openai-completions" },
|
|
230
|
+
normalizeContext({ messages }),
|
|
231
|
+
{
|
|
232
|
+
apiKey: "local-test-placeholder",
|
|
233
|
+
maxRetries: 0,
|
|
234
|
+
onPayload(value) {
|
|
235
|
+
payload = value;
|
|
236
|
+
throw new Error("Payload captured before sending.");
|
|
237
|
+
},
|
|
238
|
+
async fetch() {
|
|
239
|
+
networkCalls++;
|
|
240
|
+
throw new Error("Provider requests are forbidden in this fixture.");
|
|
241
|
+
},
|
|
242
|
+
},
|
|
243
|
+
).result();
|
|
244
|
+
assert.ok(payload !== undefined, "Pi must construct the provider payload");
|
|
245
|
+
assert.equal(networkCalls, 0);
|
|
246
|
+
return payload;
|
|
247
|
+
},
|
|
248
|
+
read(id: string, name = "build.log"): ToolCall {
|
|
249
|
+
return { type: "toolCall", id, name: "read", arguments: { path: join(cwd, name) } };
|
|
250
|
+
},
|
|
251
|
+
async prompt(...responses: Script[]) {
|
|
252
|
+
scripts.push(...responses);
|
|
253
|
+
await session.prompt("Continue.");
|
|
254
|
+
assert.equal(
|
|
255
|
+
scripts.length,
|
|
256
|
+
0,
|
|
257
|
+
session.agent.state.errorMessage ?? "Unused scripted responses",
|
|
258
|
+
);
|
|
259
|
+
assert.equal(session.agent.state.errorMessage, undefined);
|
|
260
|
+
},
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** The entire model-facing result becomes one receipt, including for image reads. */
|
|
265
|
+
export function assertForgotten(result: ReturnType<typeof toolResult>, id: string) {
|
|
266
|
+
assert.equal(result.isError, false);
|
|
267
|
+
assert.equal(result.content.length, 1);
|
|
268
|
+
const receipt = result.content[0];
|
|
269
|
+
assert.equal(receipt.type, "text");
|
|
270
|
+
assert.ok(receipt.type === "text" && receipt.text.includes(id));
|
|
271
|
+
assert.ok(receipt.type === "text" && receipt.text.includes("forgotten"));
|
|
272
|
+
assert.equal(taggedResultId(result), undefined);
|
|
273
|
+
}
|