@criogaid/pi-hashline-edit 0.3.0 → 0.4.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 +59 -50
- package/package.json +8 -3
- package/src/core/apply.test.ts +366 -310
- package/src/core/apply.ts +269 -202
- package/src/core/hash.test.ts +61 -23
- package/src/core/hash.ts +45 -16
- package/src/core/lines.test.ts +46 -27
- package/src/core/lines.ts +36 -28
- package/src/core/ranges.test.ts +73 -19
- package/src/core/ranges.ts +15 -15
- package/src/core/text.test.ts +3 -3
- package/src/core/text.ts +28 -9
- package/src/core/types.ts +54 -36
- package/src/index.ts +22 -16
- package/src/integration/grep-rg.test.ts +834 -219
- package/src/integration/large-text.test.ts +62 -0
- package/src/integration/replace-package.test.ts +37 -0
- package/src/pi/action-fusion.test.ts +535 -206
- package/src/pi/action-fusion.ts +469 -244
- package/src/pi/anchor-format.test.ts +30 -19
- package/src/pi/anchor-format.ts +27 -14
- package/src/pi/budgets.ts +20 -0
- package/src/pi/config.test.ts +60 -30
- package/src/pi/config.ts +45 -32
- package/src/pi/directory-sync.test.ts +55 -0
- package/src/pi/e2e-scenarios.test.ts +359 -0
- package/src/pi/edit-tool.ts +426 -262
- package/src/pi/error-text.ts +21 -0
- package/src/pi/execute.test.ts +1594 -694
- package/src/pi/failure-context.test.ts +105 -83
- package/src/pi/failure-context.ts +83 -71
- package/src/pi/failure-path.test.ts +171 -64
- package/src/pi/file-commit.test.ts +446 -233
- package/src/pi/file-commit.ts +347 -203
- package/src/pi/fusion-card.test.ts +118 -83
- package/src/pi/fusion-card.ts +120 -85
- package/src/pi/grep-output.ts +208 -0
- package/src/pi/grep-render.ts +58 -0
- package/src/pi/grep-scope.ts +152 -0
- package/src/pi/grep-search.ts +217 -0
- package/src/pi/grep-tool.ts +191 -766
- package/src/pi/grep.test.ts +562 -150
- package/src/pi/mutation-result.test.ts +37 -0
- package/src/pi/mutation-result.ts +107 -59
- package/src/pi/mutation-runner.ts +168 -0
- package/src/pi/path.ts +20 -12
- package/src/pi/pi.test.ts +95 -52
- package/src/pi/read-tool.ts +219 -130
- package/src/pi/registration.test.ts +274 -113
- package/src/pi/render.test.ts +218 -83
- package/src/pi/render.ts +152 -95
- package/src/pi/replace-apply.ts +109 -0
- package/src/pi/replace-tool.ts +280 -240
- package/src/pi/replace-worker.mjs +4 -0
- package/src/pi/replace-worker.ts +10 -0
- package/src/pi/replace.test.ts +773 -389
- package/src/pi/result-safety.test.ts +779 -342
- package/src/pi/rg-line-filter.test.ts +64 -36
- package/src/pi/rg-line-filter.ts +40 -124
- package/src/pi/rg-line-ranges.test.ts +57 -31
- package/src/pi/rg-line-ranges.ts +44 -82
- package/src/pi/rg-text-view.ts +106 -36
- package/src/pi/schema.ts +27 -0
- package/src/pi/state.ts +7 -7
- package/src/pi/text-stream.test.ts +118 -0
- package/src/pi/text-stream.ts +136 -0
- package/src/pi/tool-call.testing.ts +37 -0
- package/src/pi/write-tool.ts +115 -52
- package/src/pi/write.test.ts +248 -96
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { test } from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { generateDiffString, generateUnifiedPatch } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { generateMutationDetails } from "./mutation-result.ts";
|
|
5
|
+
import { displayCarriageReturns } from "./anchor-format.ts";
|
|
6
|
+
import { byteRevision } from "./file-commit.ts";
|
|
7
|
+
|
|
8
|
+
for (const [name, before, after] of [
|
|
9
|
+
["LF", "guard\nold\ntail\n", "guard\nnew\ntail\n"],
|
|
10
|
+
["CRLF", "guard\r\nold\r\ntail\r\n", "guard\r\nnew\r\ntail\r\n"],
|
|
11
|
+
["mixed", "guard\r\nold\ntail", "guard\r\nnew\ntail"],
|
|
12
|
+
["standalone CR", "guard\nold\rtail", "guard\nnew\rtail"],
|
|
13
|
+
["ending conversion", "same\r\n", "same\n"],
|
|
14
|
+
["empty file", "", "created"],
|
|
15
|
+
["BOM and literal escapes", "\uFEFFguard\nold\\n\\0", "\uFEFFguard\nnew\\n\\0"],
|
|
16
|
+
["no-op", "unchanged\n", "unchanged\n"],
|
|
17
|
+
] as const) {
|
|
18
|
+
test(`mutation evidence preserves raw patch and logical preview for ${name}`, () => {
|
|
19
|
+
const versions = {
|
|
20
|
+
baseRevision: byteRevision(before),
|
|
21
|
+
publishedRevision: byteRevision(after),
|
|
22
|
+
observedRevision: byteRevision(after),
|
|
23
|
+
};
|
|
24
|
+
const publication = before === after ? "NOT_PUBLISHED" : "PUBLISHED";
|
|
25
|
+
const details = generateMutationDetails("file.txt", before, after, versions, publication);
|
|
26
|
+
const raw = generateDiffString(before, after);
|
|
27
|
+
const logical = generateDiffString(before.replace(/\r\n/g, "\n"), after.replace(/\r\n/g, "\n"));
|
|
28
|
+
assert.deepEqual(details, {
|
|
29
|
+
diff: displayCarriageReturns(raw.diff),
|
|
30
|
+
displayDiff: displayCarriageReturns(logical.diff),
|
|
31
|
+
firstChangedLine: raw.firstChangedLine,
|
|
32
|
+
patch: generateUnifiedPatch("file.txt", before, after),
|
|
33
|
+
publication,
|
|
34
|
+
...versions,
|
|
35
|
+
});
|
|
36
|
+
});
|
|
37
|
+
}
|
|
@@ -3,83 +3,131 @@ import { FileMutationError, type MutationVersions, type PublicationStatus } from
|
|
|
3
3
|
import { generateDiffString, generateUnifiedPatch } from "@earendil-works/pi-coding-agent";
|
|
4
4
|
import { displayCarriageReturns, type AnchorFormatter } from "./anchor-format.ts";
|
|
5
5
|
import { normalizeLineEndings } from "../core/lines.ts";
|
|
6
|
+
import { errorMessage } from "./error-text.ts";
|
|
7
|
+
import { formatKiB, MAX_BLOCK_BYTES } from "./budgets.ts";
|
|
6
8
|
|
|
7
9
|
/** Keep byte-faithful diff/patch data and a separate preview of the shared logical text. */
|
|
8
|
-
export function generateMutationDetails(
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
10
|
+
export function generateMutationDetails(
|
|
11
|
+
path: string,
|
|
12
|
+
before: string,
|
|
13
|
+
after: string,
|
|
14
|
+
versions: MutationVersions,
|
|
15
|
+
publication: PublicationStatus,
|
|
16
|
+
) {
|
|
17
|
+
const { diff, firstChangedLine } = generateDiffString(before, after);
|
|
18
|
+
const logicalBefore = normalizeLineEndings(before);
|
|
19
|
+
const logicalAfter = normalizeLineEndings(after);
|
|
20
|
+
const displayDiff =
|
|
21
|
+
logicalBefore === before && logicalAfter === after
|
|
22
|
+
? diff
|
|
23
|
+
: generateDiffString(logicalBefore, logicalAfter).diff;
|
|
24
|
+
return {
|
|
25
|
+
diff: displayCarriageReturns(diff),
|
|
26
|
+
displayDiff: displayCarriageReturns(displayDiff),
|
|
27
|
+
firstChangedLine,
|
|
28
|
+
patch: generateUnifiedPatch(path, before, after),
|
|
29
|
+
publication,
|
|
30
|
+
...versions,
|
|
31
|
+
};
|
|
19
32
|
}
|
|
20
33
|
|
|
21
34
|
/** Keep result-building failures distinct from file publication failures. */
|
|
22
|
-
export function postProcessMutation<T>(
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
35
|
+
export function postProcessMutation<T>(
|
|
36
|
+
tool: string,
|
|
37
|
+
publication: PublicationStatus,
|
|
38
|
+
build: () => T,
|
|
39
|
+
): T {
|
|
40
|
+
try {
|
|
41
|
+
return build();
|
|
42
|
+
} catch (error) {
|
|
43
|
+
throw new FileMutationError(
|
|
44
|
+
"post_process",
|
|
45
|
+
publication,
|
|
46
|
+
`${tool} result generation failed; publication=${publication}: ${errorMessage(error)}`,
|
|
47
|
+
{ cause: error },
|
|
48
|
+
);
|
|
49
|
+
}
|
|
26
50
|
}
|
|
27
51
|
|
|
28
52
|
/** Append only to the summary block after the caller confirms anchor freshness. */
|
|
29
|
-
export function appendMutationAnchors<T>(
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
53
|
+
export function appendMutationAnchors<T>(
|
|
54
|
+
result: AgentToolResult<T>,
|
|
55
|
+
anchors: string,
|
|
56
|
+
publish: boolean,
|
|
57
|
+
): AgentToolResult<T> {
|
|
58
|
+
return {
|
|
59
|
+
...result,
|
|
60
|
+
content: result.content.map((block, index) =>
|
|
61
|
+
index === 0 && block.type === "text"
|
|
62
|
+
? { ...block, text: `${block.text}${publish ? anchors : ""}` }
|
|
63
|
+
: block,
|
|
64
|
+
),
|
|
65
|
+
};
|
|
35
66
|
}
|
|
36
67
|
|
|
37
|
-
export function observedFreshness(
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
68
|
+
export function observedFreshness(
|
|
69
|
+
result: AgentToolResult<unknown>,
|
|
70
|
+
): "unchanged" | "changed" | "unknown" {
|
|
71
|
+
const versions = result.details as Partial<MutationVersions> | undefined;
|
|
72
|
+
if (!versions?.publishedRevision || !versions.observedRevision) return "unknown";
|
|
73
|
+
return versions.publishedRevision === versions.observedRevision ? "unchanged" : "changed";
|
|
41
74
|
}
|
|
42
75
|
|
|
43
76
|
/** Finalize from the observed commit revision unless a later freshness check supplies the decision. */
|
|
44
77
|
export function finalizeMutationResult<T>(
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
78
|
+
result: AgentToolResult<T>,
|
|
79
|
+
finalize: (result: AgentToolResult<T>, publishAnchors: boolean) => AgentToolResult<T>,
|
|
80
|
+
publishAnchors = observedFreshness(result) === "unchanged",
|
|
81
|
+
staleNotice = "Anchors omitted: target revision was not confirmed unchanged. Re-read before further edits.",
|
|
49
82
|
): AgentToolResult<T> {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
83
|
+
try {
|
|
84
|
+
const finalized = finalize(result, publishAnchors);
|
|
85
|
+
return publishAnchors
|
|
86
|
+
? finalized
|
|
87
|
+
: {
|
|
88
|
+
...finalized,
|
|
89
|
+
content: [...finalized.content, { type: "text", text: staleNotice }],
|
|
90
|
+
};
|
|
91
|
+
} catch (error) {
|
|
92
|
+
const publication =
|
|
93
|
+
(result.details as { publication?: PublicationStatus } | undefined)?.publication ?? "UNKNOWN";
|
|
94
|
+
throw new FileMutationError(
|
|
95
|
+
"post_process",
|
|
96
|
+
publication,
|
|
97
|
+
`Result generation failed; publication=${publication}. Re-read before retrying: ${errorMessage(error)}`,
|
|
98
|
+
{ cause: error },
|
|
99
|
+
);
|
|
100
|
+
}
|
|
60
101
|
}
|
|
61
102
|
|
|
62
103
|
/** Return compact changed-position anchors; selected context rows retain full content within the byte budget. */
|
|
63
104
|
export function formatMutationAnchors(
|
|
64
|
-
|
|
65
|
-
|
|
105
|
+
beforeLines: readonly string[],
|
|
106
|
+
lines: readonly string[],
|
|
107
|
+
indices: Iterable<number>,
|
|
108
|
+
anchors: AnchorFormatter,
|
|
109
|
+
heading: string,
|
|
110
|
+
contentIndices?: ReadonlySet<number>,
|
|
66
111
|
): string {
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
112
|
+
const notice = `\n… (additional anchors omitted: ${formatKiB(MAX_BLOCK_BYTES)} limit; use read for omitted positions)`;
|
|
113
|
+
const rows: string[] = [];
|
|
114
|
+
let bytes = Buffer.byteLength(`\n${heading}\n`) + Buffer.byteLength(notice);
|
|
115
|
+
let omitted = false;
|
|
116
|
+
for (const index of indices) {
|
|
117
|
+
const content = lines[index];
|
|
118
|
+
// Compare source content, not short hashes: a collision must not suppress a changed row.
|
|
119
|
+
// Deletion successors (contentIndices) shifted into this position and must not be skipped.
|
|
120
|
+
if (beforeLines[index] === content && !contentIndices?.has(index)) continue;
|
|
121
|
+
const row = contentIndices?.has(index)
|
|
122
|
+
? anchors.row(index + 1, content)
|
|
123
|
+
: anchors.token(index + 1, content);
|
|
124
|
+
const rowBytes = Buffer.byteLength(row) + 1;
|
|
125
|
+
if (bytes + rowBytes > MAX_BLOCK_BYTES) {
|
|
126
|
+
omitted = true;
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
rows.push(row);
|
|
130
|
+
bytes += rowBytes;
|
|
131
|
+
}
|
|
132
|
+
return rows.length || omitted ? `\n${heading}\n${rows.join("\n")}${omitted ? notice : ""}` : "";
|
|
85
133
|
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared execution pipeline for the file mutation tools (edit, replace, write).
|
|
3
|
+
*
|
|
4
|
+
* Owns the sequencing every mutation tool must keep identical: then_run
|
|
5
|
+
* availability, schema validation, path resolution, the shared file mutation
|
|
6
|
+
* queue, and the hand-off to Action Fusion or plain finalization. Anchor
|
|
7
|
+
* publication is an explicit outcome field rather than a side channel, so the
|
|
8
|
+
* freshness rule (anchors only for an unchanged published revision) lives here.
|
|
9
|
+
*
|
|
10
|
+
* `runTextMutation` adds the read-modify-write sequence shared by edit and
|
|
11
|
+
* replace: snapshot bound to the bytes read, cancellation before apply and
|
|
12
|
+
* before write, revision-checked commit, and result generation that keeps the
|
|
13
|
+
* publication status on failure. Tools supply only the text transformation.
|
|
14
|
+
*
|
|
15
|
+
* @module pi-hashline-edit/pi
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { withFileMutationQueue, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
19
|
+
import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
|
|
20
|
+
import type {
|
|
21
|
+
ActionFusionDetails,
|
|
22
|
+
createActionFusionExecutor,
|
|
23
|
+
ThenRunInput,
|
|
24
|
+
} from "./action-fusion.ts";
|
|
25
|
+
import { commitReplacement, readEditableSnapshot } from "./file-commit.ts";
|
|
26
|
+
import {
|
|
27
|
+
appendMutationAnchors,
|
|
28
|
+
finalizeMutationResult,
|
|
29
|
+
generateMutationDetails,
|
|
30
|
+
postProcessMutation,
|
|
31
|
+
} from "./mutation-result.ts";
|
|
32
|
+
import { canonicalPath } from "./path.ts";
|
|
33
|
+
import { throwIfCancelled } from "./error-text.ts";
|
|
34
|
+
|
|
35
|
+
export type ActionFusionExecutor = ReturnType<typeof createActionFusionExecutor>;
|
|
36
|
+
export type MutationToolName = "edit" | "replace" | "write";
|
|
37
|
+
|
|
38
|
+
/** Result details shared by the read-modify-write tools. */
|
|
39
|
+
export type TextMutationDetails = ReturnType<typeof generateMutationDetails> & {
|
|
40
|
+
actionFusion?: ActionFusionDetails;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/** The file a mutation targets, resolved once per call. */
|
|
44
|
+
export interface MutationTarget {
|
|
45
|
+
readonly absolutePath: string;
|
|
46
|
+
/** The caller-supplied path, used in result text and diffs. */
|
|
47
|
+
readonly displayPath: string;
|
|
48
|
+
readonly signal: AbortSignal | undefined;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface MutationOutcome<TDetails> {
|
|
52
|
+
readonly result: AgentToolResult<TDetails>;
|
|
53
|
+
/** Fresh anchor report; appended to the summary only once freshness is confirmed. */
|
|
54
|
+
readonly anchors?: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface MutationToolSpec<TParams extends { path: string }, TDetails> {
|
|
58
|
+
readonly cwd: string;
|
|
59
|
+
readonly fusion: ActionFusionExecutor | undefined;
|
|
60
|
+
/**
|
|
61
|
+
* Whether results carry fresh anchors. Anchor-reporting tools append a stale
|
|
62
|
+
* notice when freshness is unconfirmed; others leave staleness to then_run.
|
|
63
|
+
*/
|
|
64
|
+
readonly reportsAnchors: boolean;
|
|
65
|
+
/** Perform the mutation. Runs inside the file mutation queue. */
|
|
66
|
+
run(params: TParams, target: MutationTarget): Promise<MutationOutcome<TDetails>>;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface MutationCall<TParams, TDetails> {
|
|
70
|
+
readonly toolCallId: string;
|
|
71
|
+
/** Arguments already prepared and validated by Pi against the tool schema. */
|
|
72
|
+
readonly params: TParams & { then_run?: ThenRunInput };
|
|
73
|
+
readonly signal: AbortSignal | undefined;
|
|
74
|
+
readonly onUpdate: AgentToolUpdateCallback<TDetails> | undefined;
|
|
75
|
+
readonly ctx: ExtensionContext;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Queue and publish one validated mutation call, then run its then_run command when fused. */
|
|
79
|
+
export async function executeMutation<TParams extends { path: string }, TDetails>(
|
|
80
|
+
spec: MutationToolSpec<TParams, TDetails>,
|
|
81
|
+
call: MutationCall<TParams, TDetails>,
|
|
82
|
+
): Promise<AgentToolResult<TDetails>> {
|
|
83
|
+
const { cwd, fusion } = spec;
|
|
84
|
+
const { toolCallId, signal, onUpdate, ctx } = call;
|
|
85
|
+
const { then_run, ...mutationParams } = call.params;
|
|
86
|
+
const absolutePath = canonicalPath(cwd, mutationParams.path);
|
|
87
|
+
const target: MutationTarget = { absolutePath, displayPath: mutationParams.path, signal };
|
|
88
|
+
let anchors = "";
|
|
89
|
+
const mutate = (): Promise<AgentToolResult<TDetails>> =>
|
|
90
|
+
withFileMutationQueue(absolutePath, async () => {
|
|
91
|
+
const outcome = await spec.run(mutationParams as unknown as TParams, target);
|
|
92
|
+
anchors = outcome.anchors ?? "";
|
|
93
|
+
return outcome.result;
|
|
94
|
+
});
|
|
95
|
+
const finalizeMutation = spec.reportsAnchors
|
|
96
|
+
? (result: AgentToolResult<TDetails>, publishAnchors: boolean) =>
|
|
97
|
+
appendMutationAnchors(result, anchors, publishAnchors)
|
|
98
|
+
: undefined;
|
|
99
|
+
if (!fusion) {
|
|
100
|
+
const result = await mutate();
|
|
101
|
+
return finalizeMutation ? finalizeMutationResult(result, finalizeMutation) : result;
|
|
102
|
+
}
|
|
103
|
+
return fusion({
|
|
104
|
+
toolCallId,
|
|
105
|
+
absolutePath,
|
|
106
|
+
thenRun: then_run,
|
|
107
|
+
mutate,
|
|
108
|
+
finalizeMutation,
|
|
109
|
+
signal,
|
|
110
|
+
ctx,
|
|
111
|
+
onUpdate,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** A whole-file text transformation produced from one snapshot. */
|
|
116
|
+
export interface TextChange {
|
|
117
|
+
/** Complete replacement text; equal to the snapshot for a no-op. */
|
|
118
|
+
readonly text: string;
|
|
119
|
+
/** Fresh anchor report for the committed text. Called during result generation. */
|
|
120
|
+
anchors(): string;
|
|
121
|
+
/** First result line. Called during result generation. */
|
|
122
|
+
summary(): string;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Read-modify-write against the bytes read: the commit is rejected if the file
|
|
127
|
+
* changed since the snapshot, and result-generation failures keep publication.
|
|
128
|
+
*/
|
|
129
|
+
export async function runTextMutation(
|
|
130
|
+
tool: Exclude<MutationToolName, "write">,
|
|
131
|
+
target: MutationTarget,
|
|
132
|
+
change: (currentText: string) => TextChange | Promise<TextChange>,
|
|
133
|
+
): Promise<MutationOutcome<TextMutationDetails>> {
|
|
134
|
+
const { absolutePath, displayPath, signal } = target;
|
|
135
|
+
|
|
136
|
+
const { text: currentText, baseRevision } = await readEditableSnapshot(absolutePath, displayPath);
|
|
137
|
+
// Cancelled after read: don't transform; the file stays untouched.
|
|
138
|
+
throwIfCancelled(signal, `before apply; ${displayPath} was not changed.`);
|
|
139
|
+
|
|
140
|
+
const next = await change(currentText);
|
|
141
|
+
|
|
142
|
+
// Cancelled before write: don't touch the disk.
|
|
143
|
+
throwIfCancelled(signal, `before write; ${displayPath} was not changed.`);
|
|
144
|
+
|
|
145
|
+
const versions = await commitReplacement(
|
|
146
|
+
absolutePath,
|
|
147
|
+
displayPath,
|
|
148
|
+
next.text,
|
|
149
|
+
baseRevision,
|
|
150
|
+
signal,
|
|
151
|
+
);
|
|
152
|
+
let anchors = "";
|
|
153
|
+
const result = postProcessMutation(tool, versions.publication, () => {
|
|
154
|
+
const details = generateMutationDetails(
|
|
155
|
+
displayPath,
|
|
156
|
+
currentText,
|
|
157
|
+
next.text,
|
|
158
|
+
versions,
|
|
159
|
+
versions.publication,
|
|
160
|
+
);
|
|
161
|
+
anchors = next.anchors();
|
|
162
|
+
return {
|
|
163
|
+
content: [{ type: "text" as const, text: next.summary() }],
|
|
164
|
+
details,
|
|
165
|
+
};
|
|
166
|
+
});
|
|
167
|
+
return { result, anchors };
|
|
168
|
+
}
|
package/src/pi/path.ts
CHANGED
|
@@ -7,16 +7,24 @@ const WINDOWS_SHELL_DRIVE = /^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i;
|
|
|
7
7
|
|
|
8
8
|
/** Resolve model-supplied paths with the same input conventions as Pi's built-in file tools. */
|
|
9
9
|
export function canonicalPath(cwd: string, path: string): string {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
10
|
+
let normalized = path.replace(UNICODE_SPACES, " ");
|
|
11
|
+
if (normalized.startsWith("@")) normalized = normalized.slice(1);
|
|
12
|
+
if (
|
|
13
|
+
process.platform === "win32" &&
|
|
14
|
+
normalized.startsWith("/") &&
|
|
15
|
+
!normalized.startsWith("//") &&
|
|
16
|
+
!normalized.includes("\\")
|
|
17
|
+
) {
|
|
18
|
+
const match = WINDOWS_SHELL_DRIVE.exec(normalized);
|
|
19
|
+
if (match) normalized = `${match[1]!.toUpperCase()}:\\${match[2]?.replaceAll("/", "\\") ?? ""}`;
|
|
20
|
+
}
|
|
21
|
+
if (normalized === "~") normalized = homedir();
|
|
22
|
+
else if (
|
|
23
|
+
normalized.startsWith("~/") ||
|
|
24
|
+
(process.platform === "win32" && normalized.startsWith("~\\"))
|
|
25
|
+
) {
|
|
26
|
+
normalized = join(homedir(), normalized.slice(2));
|
|
27
|
+
}
|
|
28
|
+
if (normalized.startsWith("file://")) normalized = fileURLToPath(normalized);
|
|
29
|
+
return isAbsolute(normalized) ? resolve(normalized) : resolve(cwd, normalized);
|
|
22
30
|
}
|
package/src/pi/pi.test.ts
CHANGED
|
@@ -12,70 +12,113 @@ import { makeWriteOverride } from "./write-tool.ts";
|
|
|
12
12
|
import { canonicalPath } from "./path.ts";
|
|
13
13
|
import { join, resolve } from "node:path";
|
|
14
14
|
import { pathToFileURL } from "node:url";
|
|
15
|
+
import { callTool } from "./tool-call.testing.ts";
|
|
15
16
|
|
|
16
17
|
test("canonicalPath resolves relative and absolute", () => {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
18
|
+
const cwd = resolve("/cwd");
|
|
19
|
+
const absolute = resolve("/abs/x.ts");
|
|
20
|
+
assert.equal(canonicalPath(cwd, "foo.ts"), join(cwd, "foo.ts"));
|
|
21
|
+
assert.equal(canonicalPath(cwd, "./foo.ts"), join(cwd, "foo.ts"));
|
|
22
|
+
assert.equal(canonicalPath(cwd, absolute), absolute);
|
|
22
23
|
});
|
|
23
24
|
|
|
24
25
|
test("canonicalPath expands ~ to home directory", () => {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
26
|
+
const home = homedir();
|
|
27
|
+
assert.equal(canonicalPath("/cwd", "~"), home);
|
|
28
|
+
assert.equal(canonicalPath("/cwd", "~/foo.ts"), join(home, "foo.ts"));
|
|
28
29
|
});
|
|
29
30
|
|
|
30
31
|
test("canonicalPath matches Pi's file URL, @ prefix, and Unicode space handling", () => {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
32
|
+
const cwd = resolve("/cwd");
|
|
33
|
+
const target = join(cwd, "space name.txt");
|
|
34
|
+
const fileUrl = pathToFileURL(target).href;
|
|
35
|
+
for (const input of [
|
|
36
|
+
"space name.txt",
|
|
37
|
+
"space\u00a0name.txt",
|
|
38
|
+
"space\u2009name.txt",
|
|
39
|
+
"@space name.txt",
|
|
40
|
+
fileUrl,
|
|
41
|
+
`@${fileUrl}`,
|
|
42
|
+
]) {
|
|
43
|
+
assert.equal(canonicalPath(cwd, input), target, input);
|
|
44
|
+
}
|
|
45
|
+
assert.throws(() => canonicalPath(cwd, "file:///bad%ZZ"));
|
|
38
46
|
});
|
|
39
47
|
|
|
40
48
|
test("canonicalPath follows Pi's Windows shell-path conventions", () => {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
49
|
+
const cwd = resolve("/cwd");
|
|
50
|
+
if (process.platform === "win32") {
|
|
51
|
+
const target = "C:\\src\\file.txt";
|
|
52
|
+
for (const input of [
|
|
53
|
+
"/c/src/file.txt",
|
|
54
|
+
"/mnt/c/src/file.txt",
|
|
55
|
+
"/cygdrive/c/src/file.txt",
|
|
56
|
+
"@/c/src/file.txt",
|
|
57
|
+
]) {
|
|
58
|
+
assert.equal(canonicalPath(cwd, input), target, input);
|
|
59
|
+
}
|
|
60
|
+
assert.equal(canonicalPath(cwd, "~\\file.txt"), join(homedir(), "file.txt"));
|
|
61
|
+
assert.equal(canonicalPath(cwd, "@~\\file.txt"), join(homedir(), "file.txt"));
|
|
62
|
+
} else {
|
|
63
|
+
assert.equal(canonicalPath(cwd, "/c/src/file.txt"), "/c/src/file.txt");
|
|
64
|
+
}
|
|
52
65
|
});
|
|
53
66
|
|
|
54
67
|
test("file tools share Pi-style URL and @ path resolution", async () => {
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
68
|
+
const dir = await mkdtemp(join(tmpdir(), "hashline-path-"));
|
|
69
|
+
try {
|
|
70
|
+
const file = join(dir, "target.txt");
|
|
71
|
+
const url = pathToFileURL(file).href;
|
|
72
|
+
const ctx = { cwd: dir } as Parameters<ReturnType<typeof makeReadOverride>["execute"]>[4];
|
|
73
|
+
await callTool(
|
|
74
|
+
makeWriteOverride(dir),
|
|
75
|
+
{ path: `@${url}`, content: "before\n" },
|
|
76
|
+
{
|
|
77
|
+
toolCallId: "write",
|
|
78
|
+
ctx,
|
|
79
|
+
},
|
|
80
|
+
);
|
|
81
|
+
const read = await callTool(makeReadOverride(dir), { path: url }, { toolCallId: "read", ctx });
|
|
82
|
+
if (read.content[0]?.type !== "text") throw new Error("Expected a text read result");
|
|
83
|
+
assert.match(read.content[0].text, /before/);
|
|
84
|
+
await callTool(
|
|
85
|
+
makeReplaceTool(dir),
|
|
86
|
+
{ path: url, replacements: [{ find: "before", replace: "after" }] },
|
|
87
|
+
{ toolCallId: "replace", ctx },
|
|
88
|
+
);
|
|
89
|
+
await callTool(
|
|
90
|
+
makeEditOverride(dir),
|
|
91
|
+
{
|
|
92
|
+
path: `@${url}`,
|
|
93
|
+
edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "after")}`, body: ["edited"] }],
|
|
94
|
+
},
|
|
95
|
+
{ toolCallId: "edit", ctx },
|
|
96
|
+
);
|
|
97
|
+
const matches = await callTool(
|
|
98
|
+
makeGrepOverride(dir),
|
|
99
|
+
{ path: `@${url}`, pattern: "edited" },
|
|
100
|
+
{ toolCallId: "grep" },
|
|
101
|
+
);
|
|
102
|
+
assert.match(matches.content[0].text, /edited/);
|
|
103
|
+
assert.equal(await readFile(file, "utf8"), "edited\n");
|
|
104
|
+
let commands = 0;
|
|
105
|
+
const fusion = createActionFusionExecutor(async () => {
|
|
106
|
+
commands++;
|
|
107
|
+
return "checked";
|
|
108
|
+
});
|
|
109
|
+
const fused = await callTool(
|
|
110
|
+
makeWriteOverride(dir, fusion),
|
|
111
|
+
{
|
|
112
|
+
path: `@${url}`,
|
|
113
|
+
content: "edited\n",
|
|
114
|
+
then_run: { command: "check" },
|
|
115
|
+
},
|
|
116
|
+
{ toolCallId: "fused", ctx },
|
|
117
|
+
);
|
|
118
|
+
assert.ok(fused.details.actionFusion);
|
|
119
|
+
assert.equal(fused.details.actionFusion.command, "succeeded");
|
|
120
|
+
assert.equal(commands, 1);
|
|
121
|
+
} finally {
|
|
122
|
+
await rm(dir, { recursive: true, force: true });
|
|
123
|
+
}
|
|
81
124
|
});
|