@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,95 @@
|
|
|
1
|
+
import { createHash, type Hash } from "node:crypto";
|
|
2
|
+
import { searchChangedError } from "./error-text.ts";
|
|
3
|
+
|
|
4
|
+
export interface RawMatchRevision {
|
|
5
|
+
byteOffset: number;
|
|
6
|
+
byteLength: number;
|
|
7
|
+
lineNumber: number;
|
|
8
|
+
endsAtEof: boolean;
|
|
9
|
+
revision: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Retain one bounded digest of the whole rg event, including matched rows omitted by limit. */
|
|
13
|
+
export function rawMatchRevision(
|
|
14
|
+
bytes: Buffer,
|
|
15
|
+
lineNumber: number,
|
|
16
|
+
byteOffset: number | undefined,
|
|
17
|
+
): RawMatchRevision {
|
|
18
|
+
if (
|
|
19
|
+
typeof byteOffset !== "number" ||
|
|
20
|
+
!Number.isSafeInteger(byteOffset) ||
|
|
21
|
+
byteOffset < 0 ||
|
|
22
|
+
!Number.isSafeInteger(byteOffset + bytes.length)
|
|
23
|
+
) {
|
|
24
|
+
throw new Error("Invalid rg raw match byte offset");
|
|
25
|
+
}
|
|
26
|
+
return {
|
|
27
|
+
byteOffset,
|
|
28
|
+
byteLength: bytes.length,
|
|
29
|
+
lineNumber,
|
|
30
|
+
endsAtEof: bytes[bytes.length - 1] !== 10,
|
|
31
|
+
revision: createHash("sha256").update(bytes).digest("hex"),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Verify exact raw match spans and their physical line positions during a bounded file scan. */
|
|
36
|
+
export function rawMatchVerifier(expected: ReadonlySet<RawMatchRevision>) {
|
|
37
|
+
const spans = [...expected].sort((a, b) => a.byteOffset - b.byteOffset);
|
|
38
|
+
let next = 0;
|
|
39
|
+
let offset = 0;
|
|
40
|
+
let lineNumber = 1;
|
|
41
|
+
let lastByte = -1;
|
|
42
|
+
let active: { span: RawMatchRevision; hash: Hash }[] = [];
|
|
43
|
+
return {
|
|
44
|
+
write(bytes: Buffer): void {
|
|
45
|
+
if (next === spans.length && active.length === 0) {
|
|
46
|
+
offset += bytes.length;
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const chunkEnd = offset + bytes.length;
|
|
50
|
+
let countedTo = 0;
|
|
51
|
+
const countLinesBefore = (end: number) => {
|
|
52
|
+
let lf: number;
|
|
53
|
+
while ((lf = bytes.indexOf(10, countedTo)) !== -1 && lf < end) {
|
|
54
|
+
lineNumber++;
|
|
55
|
+
countedTo = lf + 1;
|
|
56
|
+
}
|
|
57
|
+
countedTo = end;
|
|
58
|
+
};
|
|
59
|
+
while (next < spans.length && spans[next].byteOffset < chunkEnd) {
|
|
60
|
+
const span = spans[next++];
|
|
61
|
+
const start = span.byteOffset - offset;
|
|
62
|
+
countLinesBefore(start);
|
|
63
|
+
const previousByte = start === 0 ? lastByte : bytes[start - 1];
|
|
64
|
+
if (lineNumber !== span.lineNumber || (span.byteOffset !== 0 && previousByte !== 10)) {
|
|
65
|
+
throw searchChangedError();
|
|
66
|
+
}
|
|
67
|
+
active.push({ span, hash: createHash("sha256") });
|
|
68
|
+
}
|
|
69
|
+
countLinesBefore(bytes.length);
|
|
70
|
+
active = active.filter(({ span, hash }) => {
|
|
71
|
+
const end = span.byteOffset + span.byteLength;
|
|
72
|
+
hash.update(
|
|
73
|
+
bytes.subarray(
|
|
74
|
+
Math.max(0, span.byteOffset - offset),
|
|
75
|
+
Math.min(bytes.length, end - offset),
|
|
76
|
+
),
|
|
77
|
+
);
|
|
78
|
+
if (end > chunkEnd) return true;
|
|
79
|
+
if (hash.digest("hex") !== span.revision) throw searchChangedError();
|
|
80
|
+
return false;
|
|
81
|
+
});
|
|
82
|
+
offset = chunkEnd;
|
|
83
|
+
lastByte = bytes[bytes.length - 1] ?? lastByte;
|
|
84
|
+
},
|
|
85
|
+
end(): void {
|
|
86
|
+
if (
|
|
87
|
+
next !== spans.length ||
|
|
88
|
+
active.length ||
|
|
89
|
+
spans.some((span) => span.endsAtEof && span.byteOffset + span.byteLength !== offset)
|
|
90
|
+
) {
|
|
91
|
+
throw searchChangedError();
|
|
92
|
+
}
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
}
|
|
@@ -13,65 +13,46 @@ test("explicit case settings bypass the smart-case probe", async () => {
|
|
|
13
13
|
assert.equal(await resolveIgnoreCase("rg", ["foo"], modes, false, undefined, run), false);
|
|
14
14
|
});
|
|
15
15
|
|
|
16
|
-
test("
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
test("multiline smart-case probe uses the same mode as matching", async () => {
|
|
57
|
-
let args: readonly string[] = [];
|
|
58
|
-
const run: RunText = async (_path, received) => {
|
|
59
|
-
args = received;
|
|
60
|
-
return { code: 0, stdout: "a\n\n", stderr: "" };
|
|
61
|
-
};
|
|
62
|
-
assert.equal(
|
|
63
|
-
await resolveIgnoreCase(
|
|
64
|
-
"rg",
|
|
65
|
-
["foo\\nbar"],
|
|
66
|
-
{ literal: false, multiline: true },
|
|
67
|
-
undefined,
|
|
68
|
-
undefined,
|
|
69
|
-
run,
|
|
70
|
-
),
|
|
71
|
-
true,
|
|
72
|
-
);
|
|
73
|
-
assert.ok(args.includes("--multiline"));
|
|
74
|
-
assert.ok(!args.includes("--no-multiline"));
|
|
16
|
+
test("smart-case probes preserve modes and distinguish the sensor from user matches", async () => {
|
|
17
|
+
for (const { patterns, modes, expectedPatterns } of [
|
|
18
|
+
{ patterns: ["(a)|Foo"], modes: lineModes, expectedPatterns: ["(\\p{Lu})", "(a)|Foo"] },
|
|
19
|
+
{
|
|
20
|
+
patterns: ["foo\\S*"],
|
|
21
|
+
modes: { ...lineModes, literal: true },
|
|
22
|
+
expectedPatterns: ["(\\p{Lu})", "foo\\\\S\\*"],
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
patterns: ["foo\\nbar"],
|
|
26
|
+
modes: { ...lineModes, multiline: true },
|
|
27
|
+
expectedPatterns: ["(\\p{Lu})", "foo\\nbar"],
|
|
28
|
+
},
|
|
29
|
+
]) {
|
|
30
|
+
for (const [code, stdout, expected] of [
|
|
31
|
+
[0, "a\n\n", true],
|
|
32
|
+
[0, "\n", false],
|
|
33
|
+
[1, "", false],
|
|
34
|
+
] as const) {
|
|
35
|
+
let calls = 0;
|
|
36
|
+
const run: RunText = async (_path, args, input) => {
|
|
37
|
+
calls++;
|
|
38
|
+
assert.deepEqual(input, Buffer.from("a\n"));
|
|
39
|
+
assert.ok(args.includes("--smart-case"));
|
|
40
|
+
assert.ok(args.includes("--no-config"));
|
|
41
|
+
assert.equal(args.includes("--multiline"), modes.multiline);
|
|
42
|
+
assert.equal(args.includes("--no-multiline"), !modes.multiline);
|
|
43
|
+
assert.deepEqual(
|
|
44
|
+
args.flatMap((arg, index) => (args[index - 1] === "-e" ? [arg] : [])),
|
|
45
|
+
expectedPatterns,
|
|
46
|
+
);
|
|
47
|
+
return { code, stdout, stderr: "" };
|
|
48
|
+
};
|
|
49
|
+
assert.equal(
|
|
50
|
+
await resolveIgnoreCase("rg", patterns, modes, undefined, undefined, run),
|
|
51
|
+
expected,
|
|
52
|
+
);
|
|
53
|
+
assert.equal(calls, 1);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
75
56
|
});
|
|
76
57
|
|
|
77
58
|
test("smart-case probe propagates parser errors and rejects unknown output", async () => {
|
package/src/pi/rg-text-view.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
2
3
|
import { mkdtemp, open, rm } from "node:fs/promises";
|
|
3
4
|
import { tmpdir } from "node:os";
|
|
4
5
|
import { join, resolve, sep } from "node:path";
|
|
@@ -12,13 +13,14 @@ import {
|
|
|
12
13
|
runRgPaths,
|
|
13
14
|
type RgRunResult,
|
|
14
15
|
} from "./rg-process.ts";
|
|
15
|
-
import { scopeArgs, type SearchRunner } from "./grep-search.ts";
|
|
16
|
+
import { scopeArgs, type SearchRunner, type SearchTextView } from "./grep-search.ts";
|
|
16
17
|
import { errorMessage } from "../core/errors.ts";
|
|
17
18
|
import { searchChangedError, throwIfCancelled } from "./error-text.ts";
|
|
18
19
|
|
|
19
20
|
/** CRLF snapshot batches flush after this many files or source bytes (README: 64 files / 8 MiB). */
|
|
20
21
|
const SNAPSHOT_BATCH_FILES = 64;
|
|
21
22
|
const SNAPSHOT_BATCH_BYTES = 8 * 1024 * 1024;
|
|
23
|
+
const LF_VIEW = { kind: "lf" } as const;
|
|
22
24
|
|
|
23
25
|
async function writeLfSnapshot(source: string, destination: string, signal?: AbortSignal) {
|
|
24
26
|
const handle = await open(destination, "w");
|
|
@@ -41,12 +43,18 @@ async function writeLfSnapshot(source: string, destination: string, signal?: Abo
|
|
|
41
43
|
}
|
|
42
44
|
|
|
43
45
|
/** Search LF views in batches while reporting original paths and logical match offsets. */
|
|
44
|
-
export const runRgTextView: SearchRunner = async (
|
|
46
|
+
export const runRgTextView: SearchRunner = async (
|
|
47
|
+
rgPath,
|
|
48
|
+
{ matcher, rawMatcher, scope },
|
|
49
|
+
signal,
|
|
50
|
+
onLine,
|
|
51
|
+
) => {
|
|
45
52
|
let directory: string | undefined;
|
|
46
53
|
const result: RgRunResult = { code: 1, stderr: "", stopped: false };
|
|
47
54
|
const diagnostics = new DiagnosticBuffer(MAX_RG_STDERR_BYTES);
|
|
48
55
|
// Only valid UTF-8 CRLF files use LF snapshots; malformed UTF-8 keeps its raw search view.
|
|
49
56
|
const snapshots = new Map<string, string>();
|
|
57
|
+
const views = new Map<string, SearchTextView>();
|
|
50
58
|
const batchPaths: string[] = [];
|
|
51
59
|
let batchBytes = 0;
|
|
52
60
|
const record = (run: RgRunResult) => {
|
|
@@ -60,6 +68,7 @@ export const runRgTextView: SearchRunner = async (rgPath, { matcher, scope }, si
|
|
|
60
68
|
const searchBatch = async (
|
|
61
69
|
batchPaths: readonly string[],
|
|
62
70
|
rewritePaths: ReadonlyMap<string, string>,
|
|
71
|
+
matcher: readonly string[],
|
|
63
72
|
) => {
|
|
64
73
|
const searchArgs = [
|
|
65
74
|
...matcher,
|
|
@@ -71,13 +80,15 @@ export const runRgTextView: SearchRunner = async (rgPath, { matcher, scope }, si
|
|
|
71
80
|
];
|
|
72
81
|
const run = await runRg(rgPath, searchArgs, signal, async (line) => {
|
|
73
82
|
const event = JSON.parse(line);
|
|
83
|
+
let view: SearchTextView = LF_VIEW;
|
|
74
84
|
if (event.data?.path) {
|
|
75
85
|
const reported = resolve(rgText(event.data.path));
|
|
86
|
+
view = views.get(reported)!;
|
|
76
87
|
const original = rewritePaths.get(reported);
|
|
77
88
|
if (original) event.data.path = { text: original };
|
|
78
89
|
// Passthrough paths need no rewrite — reported path is already the original.
|
|
79
90
|
}
|
|
80
|
-
return onLine(JSON.stringify(event));
|
|
91
|
+
return onLine(JSON.stringify(event), view);
|
|
81
92
|
});
|
|
82
93
|
record(run);
|
|
83
94
|
};
|
|
@@ -85,9 +96,24 @@ export const runRgTextView: SearchRunner = async (rgPath, { matcher, scope }, si
|
|
|
85
96
|
const flush = async () => {
|
|
86
97
|
if (!batchPaths.length) return !result.stopped;
|
|
87
98
|
// Scope filtering belongs to the original paths. Snapshot names have no ignore/glob semantics.
|
|
88
|
-
|
|
99
|
+
if (rawMatcher) {
|
|
100
|
+
const groups = new Map<SearchTextView["kind"], string[]>();
|
|
101
|
+
for (const path of batchPaths) {
|
|
102
|
+
const view = views.get(path)!.kind;
|
|
103
|
+
const paths = groups.get(view) ?? [];
|
|
104
|
+
paths.push(path);
|
|
105
|
+
groups.set(view, paths);
|
|
106
|
+
}
|
|
107
|
+
for (const [view, paths] of groups) {
|
|
108
|
+
await searchBatch(paths, snapshots, view === "raw" ? rawMatcher : matcher);
|
|
109
|
+
if (result.stopped) break;
|
|
110
|
+
}
|
|
111
|
+
} else {
|
|
112
|
+
await searchBatch(batchPaths, snapshots, matcher);
|
|
113
|
+
}
|
|
89
114
|
for (const path of snapshots.keys()) await rm(path);
|
|
90
115
|
snapshots.clear();
|
|
116
|
+
views.clear();
|
|
91
117
|
batchPaths.length = 0;
|
|
92
118
|
batchBytes = 0;
|
|
93
119
|
return !result.stopped;
|
|
@@ -112,15 +138,36 @@ export const runRgTextView: SearchRunner = async (rgPath, { matcher, scope }, si
|
|
|
112
138
|
const original = resolve(path);
|
|
113
139
|
if (directory && original.startsWith(directory + sep)) return true;
|
|
114
140
|
try {
|
|
115
|
-
const
|
|
141
|
+
const hash = createHash("sha256");
|
|
142
|
+
const info = await scanTextFile(
|
|
143
|
+
original,
|
|
144
|
+
undefined,
|
|
145
|
+
signal,
|
|
146
|
+
(bytes) => hash.update(bytes),
|
|
147
|
+
"lossy",
|
|
148
|
+
);
|
|
116
149
|
if (info.hasNul) return true;
|
|
117
150
|
if (info.hasCrLf && info.validUtf8) {
|
|
118
151
|
const dir = await ensureDirectory();
|
|
119
152
|
const snapshot = join(dir, String(snapshots.size));
|
|
120
153
|
await writeLfSnapshot(original, snapshot, signal);
|
|
121
154
|
snapshots.set(snapshot, original);
|
|
155
|
+
views.set(snapshot, LF_VIEW);
|
|
122
156
|
batchPaths.push(snapshot);
|
|
123
157
|
} else {
|
|
158
|
+
views.set(
|
|
159
|
+
original,
|
|
160
|
+
info.validUtf8
|
|
161
|
+
? LF_VIEW
|
|
162
|
+
: {
|
|
163
|
+
kind: "raw",
|
|
164
|
+
snapshot: {
|
|
165
|
+
revision: hash.digest("hex"),
|
|
166
|
+
validUtf8: false,
|
|
167
|
+
totalLines: info.totalLines,
|
|
168
|
+
},
|
|
169
|
+
},
|
|
170
|
+
);
|
|
124
171
|
batchPaths.push(original);
|
|
125
172
|
}
|
|
126
173
|
batchBytes += info.byteLength;
|
|
@@ -8,6 +8,16 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import { validateToolArguments } from "@earendil-works/pi-ai";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
import type { TestContext } from "node:test";
|
|
13
|
+
import {
|
|
14
|
+
createAgentSession,
|
|
15
|
+
DefaultResourceLoader,
|
|
16
|
+
type ExtensionToolContext,
|
|
17
|
+
ModelRuntime,
|
|
18
|
+
SessionManager,
|
|
19
|
+
SettingsManager,
|
|
20
|
+
} from "@earendil-works/pi-coding-agent";
|
|
11
21
|
|
|
12
22
|
interface CallableTool {
|
|
13
23
|
readonly name: string;
|
|
@@ -35,3 +45,43 @@ export async function callTool(tool: CallableTool, args: unknown, options: ToolC
|
|
|
35
45
|
});
|
|
36
46
|
return tool.execute(toolCallId, validated, options.signal, options.onUpdate, options.ctx);
|
|
37
47
|
}
|
|
48
|
+
|
|
49
|
+
/** Create Pi's tool context without loading user credentials or contacting a provider. */
|
|
50
|
+
export async function createToolContext(
|
|
51
|
+
cwd: string,
|
|
52
|
+
t: TestContext,
|
|
53
|
+
mode: ExtensionToolContext["mode"] = "json",
|
|
54
|
+
) {
|
|
55
|
+
const runtime = await ModelRuntime.create({
|
|
56
|
+
authPath: join(cwd, "test-auth.json"),
|
|
57
|
+
modelsPath: null,
|
|
58
|
+
modelsStorePath: join(cwd, "test-models.json"),
|
|
59
|
+
refreshOnCreate: false,
|
|
60
|
+
allowModelNetwork: false,
|
|
61
|
+
});
|
|
62
|
+
const settingsManager = SettingsManager.inMemory();
|
|
63
|
+
const loader = new DefaultResourceLoader({
|
|
64
|
+
cwd,
|
|
65
|
+
agentDir: cwd,
|
|
66
|
+
settingsManager,
|
|
67
|
+
noExtensions: true,
|
|
68
|
+
noSkills: true,
|
|
69
|
+
noPromptTemplates: true,
|
|
70
|
+
noThemes: true,
|
|
71
|
+
noContextFiles: true,
|
|
72
|
+
});
|
|
73
|
+
await loader.reload();
|
|
74
|
+
const { session } = await createAgentSession({
|
|
75
|
+
cwd,
|
|
76
|
+
agentDir: cwd,
|
|
77
|
+
modelRuntime: runtime,
|
|
78
|
+
settingsManager,
|
|
79
|
+
resourceLoader: loader,
|
|
80
|
+
sessionManager: SessionManager.inMemory(cwd),
|
|
81
|
+
tools: [],
|
|
82
|
+
});
|
|
83
|
+
t.after(() => session.dispose());
|
|
84
|
+
await session.bindExtensions({});
|
|
85
|
+
session.extensionRunner.setUIContext(undefined, mode);
|
|
86
|
+
return session.extensionRunner.createToolContext("test", undefined);
|
|
87
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model-facing guidance shared by more than one tool.
|
|
3
|
+
*
|
|
4
|
+
* Text that belongs to one tool stays next to that tool's schema, and Action
|
|
5
|
+
* Fusion keeps its own guidelines and then_run wording in action-fusion.ts.
|
|
6
|
+
* Pi's buildRules merges every active tool's promptGuidelines into one list and
|
|
7
|
+
* drops entries whose trimmed text repeats, so tools that share a rule list the
|
|
8
|
+
* same constant and the model sees it once.
|
|
9
|
+
*
|
|
10
|
+
* @module pi-hashline-edit/pi
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** How edit, replace, and write divide file changes; listed by all three tools. */
|
|
14
|
+
export const MUTATION_TOOL_GUIDELINE =
|
|
15
|
+
"For file changes, use edit for line or block changes, insertions, and deletions; replace for repeated literal or regex substitutions and short changes inside long lines; write for new files and whole-file rewrites.";
|
package/src/pi/write-tool.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { Type, type Static } from "typebox";
|
|
|
2
2
|
import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
|
|
3
3
|
import {
|
|
4
4
|
createWriteToolDefinition,
|
|
5
|
-
type
|
|
5
|
+
type ExtensionToolContext,
|
|
6
6
|
type Theme,
|
|
7
7
|
type ToolRenderResultOptions,
|
|
8
8
|
} from "@earendil-works/pi-coding-agent";
|
|
@@ -12,10 +12,12 @@ import {
|
|
|
12
12
|
type ThenRunInput,
|
|
13
13
|
type ActionFusionDetails,
|
|
14
14
|
} from "./action-fusion.ts";
|
|
15
|
-
import { commitFile, type
|
|
15
|
+
import { commitFile, type CommitResult } from "./file-commit.ts";
|
|
16
16
|
import { postProcessMutation } from "./mutation-result.ts";
|
|
17
17
|
import { executeMutation, type ActionFusionExecutor } from "./mutation-runner.ts";
|
|
18
|
-
import {
|
|
18
|
+
import { MUTATION_TOOL_GUIDELINE } from "./tool-prompts.ts";
|
|
19
|
+
import { throwIfCancelled } from "./error-text.ts";
|
|
20
|
+
import { createArgumentPreparer } from "./argument-validation.ts";
|
|
19
21
|
import { unwritableTextReason } from "../core/text.ts";
|
|
20
22
|
import { renderToolError } from "./render.ts";
|
|
21
23
|
|
|
@@ -25,22 +27,16 @@ const writeSchema = Type.Object(
|
|
|
25
27
|
content: Type.String({
|
|
26
28
|
description: "Complete file content, written exactly as supplied, including line endings.",
|
|
27
29
|
}),
|
|
28
|
-
mode: Type.
|
|
29
|
-
Type.
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
]),
|
|
33
|
-
),
|
|
30
|
+
mode: Type.Union([
|
|
31
|
+
Type.Literal("create", { description: "Fail if the target already exists" }),
|
|
32
|
+
Type.Literal("overwrite", { description: "Fail if the target does not exist" }),
|
|
33
|
+
]),
|
|
34
34
|
},
|
|
35
35
|
{ additionalProperties: false },
|
|
36
36
|
);
|
|
37
37
|
|
|
38
38
|
function createWriteSchema(actionFusion: boolean) {
|
|
39
|
-
return withThenRunSchema(
|
|
40
|
-
writeSchema,
|
|
41
|
-
"Command to run after write succeeds; failure does not roll back the write.",
|
|
42
|
-
actionFusion,
|
|
43
|
-
);
|
|
39
|
+
return withThenRunSchema(writeSchema, "write", actionFusion);
|
|
44
40
|
}
|
|
45
41
|
type WriteParams = Static<typeof writeSchema> & { then_run?: ThenRunInput };
|
|
46
42
|
type WriteDetails = CommitResult & { path: string; actionFusion?: ActionFusionDetails };
|
|
@@ -55,20 +51,15 @@ export function makeWriteOverride(cwd: string, fusion?: ActionFusionExecutor) {
|
|
|
55
51
|
name: "write" as const,
|
|
56
52
|
label: "write",
|
|
57
53
|
description:
|
|
58
|
-
"Write a whole file exactly as supplied, including
|
|
54
|
+
"Write a whole file exactly as supplied, including its line endings. Choose create for a new file or overwrite for an existing file. Creates missing parent directories.",
|
|
59
55
|
promptSnippet: "Write complete file content to a path",
|
|
60
|
-
promptGuidelines: [
|
|
61
|
-
"Use write for creating new files or whole-file overwrites; for targeted changes, prefer edit or replace to preserve surrounding content.",
|
|
62
|
-
...(fusion ? ACTION_FUSION_GUIDELINES : []),
|
|
63
|
-
],
|
|
56
|
+
promptGuidelines: [MUTATION_TOOL_GUIDELINE, ...(fusion ? ACTION_FUSION_GUIDELINES : [])],
|
|
64
57
|
parameters,
|
|
65
|
-
|
|
66
|
-
prepareArguments(args: unknown): WriteParams {
|
|
58
|
+
prepareArguments: createArgumentPreparer("write", parameters, (args, report) => {
|
|
67
59
|
const content = (args as { content?: unknown } | null)?.content;
|
|
68
60
|
const reason = typeof content === "string" ? unwritableTextReason(content) : undefined;
|
|
69
|
-
if (reason)
|
|
70
|
-
|
|
71
|
-
},
|
|
61
|
+
if (reason) report("content", reason);
|
|
62
|
+
}),
|
|
72
63
|
renderShell: "default" as const,
|
|
73
64
|
renderCall(args: WriteParams, theme: Theme, context: WriteRenderContext) {
|
|
74
65
|
return builtin.renderCall!(args, theme, context);
|
|
@@ -87,7 +78,7 @@ export function makeWriteOverride(cwd: string, fusion?: ActionFusionExecutor) {
|
|
|
87
78
|
params: WriteParams,
|
|
88
79
|
signal: AbortSignal | undefined,
|
|
89
80
|
onUpdate: AgentToolUpdateCallback<WriteDetails> | undefined,
|
|
90
|
-
ctx:
|
|
81
|
+
ctx: ExtensionToolContext,
|
|
91
82
|
) {
|
|
92
83
|
return executeMutation<Omit<WriteParams, "then_run">, WriteDetails>(
|
|
93
84
|
{
|
|
@@ -96,7 +87,7 @@ export function makeWriteOverride(cwd: string, fusion?: ActionFusionExecutor) {
|
|
|
96
87
|
async run(mutationParams, { absolutePath, displayPath, signal }) {
|
|
97
88
|
throwIfCancelled(signal, `before write; ${displayPath} was not changed.`);
|
|
98
89
|
const result = await commitFile(absolutePath, mutationParams.content, {
|
|
99
|
-
mode: mutationParams.mode
|
|
90
|
+
mode: mutationParams.mode,
|
|
100
91
|
signal,
|
|
101
92
|
});
|
|
102
93
|
return {
|