@criogaid/pi-hashline-edit 0.7.0 → 0.8.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 +74 -222
- package/README.zh-CN.md +162 -0
- package/package.json +2 -1
- package/src/core/AGENTS.md +1 -1
- package/src/core/apply.test.ts +172 -134
- package/src/core/apply.ts +28 -30
- package/src/core/case-fold.test.ts +11 -7
- package/src/core/case-fold.ts +2 -6
- package/src/core/character-set.ts +14 -0
- package/src/core/hash.test.ts +1 -25
- package/src/core/hash.ts +0 -5
- package/src/core/lines.ts +25 -7
- package/src/core/ranges.test.ts +41 -9
- package/src/core/ranges.ts +11 -4
- package/src/core/regex.ts +36 -6
- package/src/core/replace-schema.ts +18 -11
- package/src/core/replace.test.ts +90 -0
- package/src/core/replace.ts +6 -5
- package/src/core/search-analysis.test.ts +9 -0
- package/src/core/search-analysis.ts +35 -31
- package/src/core/search.ts +1 -1
- package/src/core/types.ts +5 -7
- package/src/index.ts +2 -4
- package/src/integration/config-registration.test.ts +16 -8
- package/src/integration/fusion-dispatch.test.ts +41 -22
- package/src/integration/grep-flags.test.ts +6 -13
- package/src/integration/grep-js-completeness.test.ts +41 -31
- package/src/integration/grep-order.test.ts +78 -0
- package/src/integration/grep-path-matrix.test.ts +4 -3
- package/src/integration/grep-regex.test.ts +13 -16
- package/src/integration/grep-rg.test.ts +127 -87
- package/src/integration/grep-scan-budget.test.ts +27 -5
- package/src/integration/large-text.test.ts +3 -4
- package/src/integration/model-budget-lifecycle.test.ts +15 -6
- package/src/integration/mutation-file-types.test.ts +0 -1
- package/src/integration/mutation-file-types.testing.ts +1 -1
- package/src/integration/npm-package.testing.ts +6 -32
- package/src/integration/publication-read-changes.test.ts +58 -26
- package/src/integration/replace-package.testing.ts +4 -1
- package/src/integration/replace-worker-boundary.test.ts +34 -24
- package/src/integration/report-replay.test.ts +2 -2
- package/src/integration/utf8-errors.test.ts +2 -2
- package/src/pi/AGENTS.md +12 -13
- package/src/pi/action-fusion.test.ts +71 -216
- package/src/pi/action-fusion.ts +37 -74
- package/src/pi/anchor-format.test.ts +16 -0
- package/src/pi/anchor-format.ts +7 -3
- package/src/pi/argument-diagnostics.ts +1 -1
- package/src/pi/argument-error.testing.ts +7 -4
- package/src/pi/argument-error.ts +5 -7
- package/src/pi/argument-format.test.ts +5 -16
- package/src/pi/argument-validation.test.ts +59 -25
- package/src/pi/argument-validation.ts +4 -5
- package/src/pi/budgets.ts +5 -7
- package/src/pi/config.test.ts +15 -5
- package/src/pi/config.ts +6 -6
- package/src/pi/diagnostic-buffer.test.ts +2 -3
- package/src/pi/diagnostic-buffer.ts +2 -2
- package/src/pi/edit-tool.ts +9 -12
- package/src/pi/execute.test.ts +80 -149
- package/src/pi/failure-context.test.ts +61 -16
- package/src/pi/failure-context.ts +12 -9
- package/src/pi/failure-path.test.ts +115 -50
- package/src/pi/file-commit.test.ts +30 -46
- package/src/pi/file-commit.ts +11 -40
- package/src/pi/file-revision.ts +25 -0
- package/src/pi/fusion-card-interaction.test.ts +143 -0
- package/src/pi/fusion-card.test.ts +193 -37
- package/src/pi/fusion-card.ts +186 -116
- package/src/pi/grep-candidates.ts +25 -27
- package/src/pi/grep-matrix.test.ts +1 -1
- package/src/pi/grep-order.test.ts +323 -0
- package/src/pi/grep-output.testing.ts +24 -0
- package/src/pi/grep-output.ts +62 -69
- package/src/pi/grep-render.ts +4 -1
- package/src/pi/grep-scope.ts +1 -1
- package/src/pi/grep-search.ts +85 -56
- package/src/pi/grep-tool.ts +17 -48
- package/src/pi/grep.test.ts +270 -169
- package/src/pi/mutation-outcome.testing.ts +2 -3
- package/src/pi/mutation-result.test.ts +26 -19
- package/src/pi/mutation-result.ts +25 -40
- package/src/pi/mutation-runner.ts +9 -17
- package/src/pi/output-budgets.test.ts +25 -16
- package/src/pi/path.ts +3 -1
- package/src/pi/pi.test.ts +4 -5
- package/src/pi/read-tool.ts +32 -80
- package/src/pi/read.test.ts +145 -92
- package/src/pi/regex-worker-contract.ts +5 -23
- package/src/pi/regex-worker.ts +4 -10
- package/src/pi/registration.test.ts +54 -49
- package/src/pi/render.test.ts +196 -93
- package/src/pi/render.ts +32 -22
- package/src/pi/replace-regex.ts +3 -5
- package/src/pi/replace-tool.ts +27 -26
- package/src/pi/replace-worker-contract.ts +3 -12
- package/src/pi/replace.test.ts +144 -226
- package/src/pi/report-cause.ts +23 -19
- package/src/pi/report-failure.testing.ts +2 -2
- package/src/pi/report-schema.ts +55 -43
- package/src/pi/report.test.ts +138 -71
- package/src/pi/report.ts +40 -43
- package/src/pi/result-safety.test.ts +157 -117
- package/src/pi/rg-process.test.ts +36 -10
- package/src/pi/rg-process.ts +9 -3
- package/src/pi/rg-regex.test.ts +17 -0
- package/src/pi/rg-regex.ts +28 -22
- package/src/pi/text-stream.test.ts +35 -36
- package/src/pi/text-stream.ts +14 -14
- package/src/pi/tool-call.testing.ts +17 -7
- package/src/pi/write-tool.ts +9 -11
- package/src/pi/write.test.ts +43 -75
- package/src/testing/regex-translation-corpus.ts +16 -0
- package/src/testing/rg-line-listing.fixture.mjs +1 -1
- package/src/integration/forget-grep.test.ts +0 -148
- package/src/pi/forget-tool.ts +0 -367
- package/src/pi/forget.test.ts +0 -630
- package/src/pi/forget.testing.ts +0 -201
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
2
|
-
import { byteRevision } from "./file-
|
|
2
|
+
import { byteRevision } from "./file-revision.ts";
|
|
3
3
|
import type { MutationOutcome } from "./mutation-result.ts";
|
|
4
4
|
|
|
5
5
|
/** Build a completed overwrite fixture with matching published and observed bytes. */
|
|
@@ -7,13 +7,12 @@ export function publishedMutation<T extends object | undefined>(
|
|
|
7
7
|
content: string,
|
|
8
8
|
result: AgentToolResult<T>,
|
|
9
9
|
): MutationOutcome<T extends object ? T : object> {
|
|
10
|
-
const revision = byteRevision(content);
|
|
10
|
+
const revision = byteRevision(Buffer.from(content));
|
|
11
11
|
return {
|
|
12
12
|
details: (result.details ?? {}) as T extends object ? T : object,
|
|
13
13
|
facts: {},
|
|
14
14
|
commit: {
|
|
15
15
|
publication: "PUBLISHED",
|
|
16
|
-
baseRevision: byteRevision("before\n"),
|
|
17
16
|
publishedRevision: revision,
|
|
18
17
|
observedRevision: revision,
|
|
19
18
|
created: false,
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { test } from "node:test";
|
|
2
2
|
import assert from "node:assert/strict";
|
|
3
|
-
import { generateDiffString
|
|
3
|
+
import { generateDiffString } from "@earendil-works/pi-coding-agent";
|
|
4
4
|
import {
|
|
5
|
+
commandText,
|
|
5
6
|
finalizeMutation,
|
|
6
7
|
generateMutationDetails,
|
|
7
8
|
type MutationFacts,
|
|
@@ -9,7 +10,7 @@ import {
|
|
|
9
10
|
type MutationOutcome,
|
|
10
11
|
} from "./mutation-result.ts";
|
|
11
12
|
import { displayCarriageReturns } from "./anchor-format.ts";
|
|
12
|
-
import {
|
|
13
|
+
import { DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
|
|
13
14
|
|
|
14
15
|
// Checked by tsc; these callers must never run.
|
|
15
16
|
function invalidMutationConstruction(
|
|
@@ -18,12 +19,30 @@ function invalidMutationConstruction(
|
|
|
18
19
|
) {
|
|
19
20
|
// @ts-expect-error edit has no replacement-count fact.
|
|
20
21
|
const editFacts: MutationFacts<"edit"> = { matches: 1 };
|
|
21
|
-
|
|
22
|
-
|
|
22
|
+
finalizeMutation(
|
|
23
|
+
"edit",
|
|
24
|
+
"file.txt",
|
|
25
|
+
// @ts-expect-error Replacement facts cannot be finalized as edit facts.
|
|
26
|
+
replacement,
|
|
27
|
+
{ freshness: "unchanged" },
|
|
28
|
+
undefined,
|
|
29
|
+
DEFAULT_OUTPUT_BUDGETS,
|
|
30
|
+
);
|
|
23
31
|
// @ts-expect-error A failed mutation has no diff details.
|
|
24
32
|
const diff: string = result.diff;
|
|
25
33
|
}
|
|
26
34
|
|
|
35
|
+
test("command content includes images → report text joins only text blocks", () => {
|
|
36
|
+
assert.equal(
|
|
37
|
+
commandText([
|
|
38
|
+
{ type: "text", text: "first" },
|
|
39
|
+
{ type: "image", data: "iVBORw0KGgo=", mimeType: "image/png" },
|
|
40
|
+
{ type: "text", text: "second" },
|
|
41
|
+
]),
|
|
42
|
+
"first\nsecond",
|
|
43
|
+
);
|
|
44
|
+
});
|
|
45
|
+
|
|
27
46
|
for (const [name, before, after] of [
|
|
28
47
|
["LF", "guard\nold\ntail\n", "guard\nnew\ntail\n"],
|
|
29
48
|
["CRLF", "guard\r\nold\r\ntail\r\n", "guard\r\nnew\r\ntail\r\n"],
|
|
@@ -34,23 +53,11 @@ for (const [name, before, after] of [
|
|
|
34
53
|
["BOM and literal escapes", "\uFEFFguard\nold\\n\\0", "\uFEFFguard\nnew\\n\\0"],
|
|
35
54
|
["no-op", "unchanged\n", "unchanged\n"],
|
|
36
55
|
] as const) {
|
|
37
|
-
test(
|
|
38
|
-
const
|
|
39
|
-
baseRevision: byteRevision(before),
|
|
40
|
-
publishedRevision: byteRevision(after),
|
|
41
|
-
observedRevision: byteRevision(after),
|
|
42
|
-
};
|
|
43
|
-
const publication = before === after ? "NOT_PUBLISHED" : "PUBLISHED";
|
|
44
|
-
const details = generateMutationDetails("file.txt", before, after, versions, publication);
|
|
45
|
-
const raw = generateDiffString(before, after);
|
|
56
|
+
test(`${name} mutation → details contain only the logical-view diff`, () => {
|
|
57
|
+
const details = generateMutationDetails(before, after);
|
|
46
58
|
const logical = generateDiffString(before.replace(/\r\n/g, "\n"), after.replace(/\r\n/g, "\n"));
|
|
47
59
|
assert.deepEqual(details, {
|
|
48
|
-
diff: displayCarriageReturns(
|
|
49
|
-
displayDiff: displayCarriageReturns(logical.diff),
|
|
50
|
-
firstChangedLine: raw.firstChangedLine,
|
|
51
|
-
patch: generateUnifiedPatch("file.txt", before, after),
|
|
52
|
-
publication,
|
|
53
|
-
...versions,
|
|
60
|
+
diff: displayCarriageReturns(logical.diff),
|
|
54
61
|
});
|
|
55
62
|
});
|
|
56
63
|
}
|
|
@@ -6,16 +6,12 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
9
|
-
import {
|
|
10
|
-
|
|
11
|
-
type CommitResult,
|
|
12
|
-
type FreshnessObservation,
|
|
13
|
-
type MutationVersions,
|
|
14
|
-
} from "./file-commit.ts";
|
|
15
|
-
import { generateDiffString, generateUnifiedPatch } from "@earendil-works/pi-coding-agent";
|
|
9
|
+
import { FileMutationError, type CommitResult, type FreshnessObservation } from "./file-commit.ts";
|
|
10
|
+
import { generateDiffString } from "@earendil-works/pi-coding-agent";
|
|
16
11
|
import { displayCarriageReturns } from "./anchor-format.ts";
|
|
17
12
|
import { normalizeLineEndings } from "../core/lines.ts";
|
|
18
13
|
import type {
|
|
14
|
+
CommandResult,
|
|
19
15
|
CommandStatus,
|
|
20
16
|
FailureReport,
|
|
21
17
|
MutationToolName,
|
|
@@ -24,12 +20,12 @@ import type {
|
|
|
24
20
|
SuccessReport,
|
|
25
21
|
} from "./report-schema.ts";
|
|
26
22
|
import { causeOf, reportResult, type ReportDetails } from "./report.ts";
|
|
27
|
-
import {
|
|
28
|
-
import type {
|
|
23
|
+
import type { OutputBudgets } from "./budgets.ts";
|
|
24
|
+
import type { ActionFusionProgress } from "./action-fusion.ts";
|
|
29
25
|
|
|
30
|
-
/** Final success carries tool details; final failure carries only its report. */
|
|
26
|
+
/** Final success carries tool details; final failure carries only its report; neither carries progress. */
|
|
31
27
|
export type MutationFinalDetails<TDetails> =
|
|
32
|
-
| (TDetails & ReportDetails<SuccessReport> & { actionFusion?:
|
|
28
|
+
| (TDetails & ReportDetails<SuccessReport> & { actionFusion?: never })
|
|
33
29
|
| (ReportDetails<FailureReport> & { actionFusion?: never });
|
|
34
30
|
|
|
35
31
|
/** Progress can precede the mutation and carries no final report yet. */
|
|
@@ -37,29 +33,10 @@ export type MutationResultDetails<TDetails> =
|
|
|
37
33
|
| MutationFinalDetails<TDetails>
|
|
38
34
|
| (Partial<TDetails> & { actionFusion: ActionFusionProgress });
|
|
39
35
|
|
|
40
|
-
/**
|
|
41
|
-
export function generateMutationDetails(
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
after: string,
|
|
45
|
-
versions: MutationVersions,
|
|
46
|
-
publication: PublicationStatus,
|
|
47
|
-
) {
|
|
48
|
-
const { diff, firstChangedLine } = generateDiffString(before, after);
|
|
49
|
-
const logicalBefore = normalizeLineEndings(before);
|
|
50
|
-
const logicalAfter = normalizeLineEndings(after);
|
|
51
|
-
const displayDiff =
|
|
52
|
-
logicalBefore === before && logicalAfter === after
|
|
53
|
-
? diff
|
|
54
|
-
: generateDiffString(logicalBefore, logicalAfter).diff;
|
|
55
|
-
return {
|
|
56
|
-
diff: displayCarriageReturns(diff),
|
|
57
|
-
displayDiff: displayCarriageReturns(displayDiff),
|
|
58
|
-
firstChangedLine,
|
|
59
|
-
patch: generateUnifiedPatch(path, before, after),
|
|
60
|
-
publication,
|
|
61
|
-
...versions,
|
|
62
|
-
};
|
|
36
|
+
/** The diff of the shared logical text, which the card and Pi's session export both show. */
|
|
37
|
+
export function generateMutationDetails(before: string, after: string) {
|
|
38
|
+
const { diff } = generateDiffString(normalizeLineEndings(before), normalizeLineEndings(after));
|
|
39
|
+
return { diff: displayCarriageReturns(diff) };
|
|
63
40
|
}
|
|
64
41
|
|
|
65
42
|
/** Keep result-building failures distinct from file publication failures. */
|
|
@@ -92,10 +69,19 @@ export interface MutationOutcome<TDetails, TTool extends MutationToolName = Muta
|
|
|
92
69
|
readonly facts: MutationFacts<TTool>;
|
|
93
70
|
}
|
|
94
71
|
|
|
72
|
+
/** The text blocks of a command result, joined as then_run reports its output. */
|
|
73
|
+
export function commandText(content: CommandResult["content"]): string {
|
|
74
|
+
return content
|
|
75
|
+
.filter((block) => block.type === "text")
|
|
76
|
+
.map((block) => block.text)
|
|
77
|
+
.join("\n");
|
|
78
|
+
}
|
|
79
|
+
|
|
95
80
|
/** What Action Fusion states about the command; it never restates file state. */
|
|
96
81
|
export interface CommandFacts {
|
|
97
82
|
readonly status: CommandStatus;
|
|
98
|
-
|
|
83
|
+
/** Absent when the command never produced a result. */
|
|
84
|
+
readonly result?: CommandResult;
|
|
99
85
|
/** A progress observer failed; command and file outcomes are unaffected. */
|
|
100
86
|
readonly progressError?: unknown;
|
|
101
87
|
}
|
|
@@ -106,10 +92,11 @@ export function finalizeMutation<TDetails extends object, TTool extends Mutation
|
|
|
106
92
|
path: string,
|
|
107
93
|
{ commit, details, facts }: MutationOutcome<TDetails, NoInfer<TTool>>,
|
|
108
94
|
observation: FreshnessObservation,
|
|
109
|
-
command
|
|
110
|
-
budget: OutputBudgets
|
|
95
|
+
command: CommandFacts | undefined,
|
|
96
|
+
budget: OutputBudgets,
|
|
111
97
|
): AgentToolResult<TDetails & ReportDetails<SuccessReport>> {
|
|
112
98
|
const fresh = observation.freshness === "unchanged";
|
|
99
|
+
const output = command?.result ? commandText(command.result.content) : "";
|
|
113
100
|
// Tool-indexed facts preserve the correlation that object spread loses.
|
|
114
101
|
const report = {
|
|
115
102
|
tool,
|
|
@@ -118,9 +105,7 @@ export function finalizeMutation<TDetails extends object, TTool extends Mutation
|
|
|
118
105
|
...facts,
|
|
119
106
|
freshness: fresh ? undefined : observation.freshness,
|
|
120
107
|
freshnessError: causeOf(observation.error, budget.fieldBytes),
|
|
121
|
-
then_run: command
|
|
122
|
-
? { status: command.status, ...(command.output ? { output: command.output } : {}) }
|
|
123
|
-
: undefined,
|
|
108
|
+
then_run: command ? { status: command.status, ...(output ? { output } : {}) } : undefined,
|
|
124
109
|
progressError: causeOf(command?.progressError, budget.fieldBytes),
|
|
125
110
|
} as SuccessReport;
|
|
126
111
|
return reportResult(report, [], details);
|
|
@@ -35,7 +35,7 @@ import {
|
|
|
35
35
|
import { canonicalPath } from "./path.ts";
|
|
36
36
|
import { throwIfCancelled } from "./error-text.ts";
|
|
37
37
|
import { runTool } from "./report.ts";
|
|
38
|
-
import {
|
|
38
|
+
import type { OutputBudgetProvider, OutputBudgets } from "./budgets.ts";
|
|
39
39
|
|
|
40
40
|
export type ActionFusionExecutor = ReturnType<typeof createActionFusionExecutor>;
|
|
41
41
|
|
|
@@ -45,13 +45,11 @@ export type TextMutationDetails = ReturnType<typeof generateMutationDetails>;
|
|
|
45
45
|
/** The file a mutation targets, resolved once per call. */
|
|
46
46
|
export interface MutationTarget {
|
|
47
47
|
readonly absolutePath: string;
|
|
48
|
-
/** The caller-supplied path, used in reports and diffs. */
|
|
49
|
-
readonly displayPath: string;
|
|
50
48
|
readonly signal: AbortSignal | undefined;
|
|
51
49
|
readonly budget: OutputBudgets;
|
|
52
50
|
}
|
|
53
51
|
|
|
54
|
-
|
|
52
|
+
interface MutationToolSpec<
|
|
55
53
|
TParams extends { path: string },
|
|
56
54
|
TDetails,
|
|
57
55
|
TTool extends MutationToolName,
|
|
@@ -59,7 +57,7 @@ export interface MutationToolSpec<
|
|
|
59
57
|
readonly tool: TTool;
|
|
60
58
|
readonly cwd: string;
|
|
61
59
|
readonly fusion: ActionFusionExecutor | undefined;
|
|
62
|
-
readonly budgets
|
|
60
|
+
readonly budgets: OutputBudgetProvider;
|
|
63
61
|
/** Perform the mutation. Runs inside the file mutation queue. */
|
|
64
62
|
run(
|
|
65
63
|
params: Omit<TParams, "then_run">,
|
|
@@ -67,7 +65,7 @@ export interface MutationToolSpec<
|
|
|
67
65
|
): Promise<MutationOutcome<TDetails, TTool>>;
|
|
68
66
|
}
|
|
69
67
|
|
|
70
|
-
|
|
68
|
+
interface MutationCall<TParams, TDetails> {
|
|
71
69
|
readonly toolCallId: string;
|
|
72
70
|
/** Arguments already prepared and validated by Pi against the tool schema. */
|
|
73
71
|
readonly params: TParams & { then_run?: ThenRunInput };
|
|
@@ -89,10 +87,10 @@ export async function executeMutation<
|
|
|
89
87
|
const { toolCallId, signal, onUpdate, ctx } = call;
|
|
90
88
|
const { then_run, ...mutationParams } = call.params;
|
|
91
89
|
const displayPath = mutationParams.path;
|
|
92
|
-
const budget =
|
|
93
|
-
return runTool(tool, { path: displayPath,
|
|
90
|
+
const budget = spec.budgets();
|
|
91
|
+
return runTool(tool, { path: displayPath, signal, budget }, async () => {
|
|
94
92
|
const absolutePath = canonicalPath(cwd, displayPath);
|
|
95
|
-
const target: MutationTarget = { absolutePath,
|
|
93
|
+
const target: MutationTarget = { absolutePath, signal, budget };
|
|
96
94
|
const mutate = (): Promise<MutationOutcome<TDetails, TTool>> =>
|
|
97
95
|
withFileMutationQueue(absolutePath, () => spec.run(mutationParams, target));
|
|
98
96
|
if (!fusion) {
|
|
@@ -137,7 +135,7 @@ export async function runTextMutation<TTool extends MutationToolName>(
|
|
|
137
135
|
target: MutationTarget,
|
|
138
136
|
change: (currentText: string) => TextChange<TTool> | Promise<TextChange<TTool>>,
|
|
139
137
|
): Promise<MutationOutcome<TextMutationDetails, TTool>> {
|
|
140
|
-
const { absolutePath,
|
|
138
|
+
const { absolutePath, signal } = target;
|
|
141
139
|
|
|
142
140
|
const { text: currentText, baseRevision } = await readEditableSnapshot(absolutePath, signal);
|
|
143
141
|
// Cancelled after read: don't transform; the file stays untouched.
|
|
@@ -151,13 +149,7 @@ export async function runTextMutation<TTool extends MutationToolName>(
|
|
|
151
149
|
const commit = await commitReplacement(absolutePath, next.text, baseRevision, signal);
|
|
152
150
|
return postProcessMutation(commit.publication, () => ({
|
|
153
151
|
commit,
|
|
154
|
-
details: generateMutationDetails(
|
|
155
|
-
displayPath,
|
|
156
|
-
currentText,
|
|
157
|
-
next.text,
|
|
158
|
-
commit,
|
|
159
|
-
commit.publication,
|
|
160
|
-
),
|
|
152
|
+
details: generateMutationDetails(currentText, next.text),
|
|
161
153
|
facts: next.facts,
|
|
162
154
|
}));
|
|
163
155
|
}
|
|
@@ -9,7 +9,7 @@ import { HashlineError } from "../core/errors.ts";
|
|
|
9
9
|
import { computeLineHash } from "../core/hash.ts";
|
|
10
10
|
import { createAnchorFormatter } from "./anchor-format.ts";
|
|
11
11
|
import { formatArgumentError } from "./argument-error.ts";
|
|
12
|
-
import { outputBudgetsFor } from "./budgets.ts";
|
|
12
|
+
import { formatByteSize, outputBudgetsFor } from "./budgets.ts";
|
|
13
13
|
import { DEFAULT_CONFIG } from "./config.ts";
|
|
14
14
|
import { makeEditOverride } from "./edit-tool.ts";
|
|
15
15
|
import { describeEditFailure } from "./failure-context.ts";
|
|
@@ -29,6 +29,18 @@ function wrongHash(text: string): string {
|
|
|
29
29
|
return (hash[0] === "0" ? "1" : "0") + hash.slice(1);
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
+
test("byte budget size → uses MiB for whole MiB and KiB otherwise", () => {
|
|
33
|
+
for (const [bytes, expected] of [
|
|
34
|
+
[1024, "1 KiB"],
|
|
35
|
+
[1023 * 1024, "1023 KiB"],
|
|
36
|
+
[1024 * 1024, "1 MiB"],
|
|
37
|
+
[1025 * 1024, "1025 KiB"],
|
|
38
|
+
[4 * 1024 * 1024, "4 MiB"],
|
|
39
|
+
] as const) {
|
|
40
|
+
assert.equal(formatByteSize(bytes), expected);
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
|
|
32
44
|
test("model budget grows → argument issues remain complete JSON with counted omissions", () => {
|
|
33
45
|
const issues = Array.from({ length: 100 }, (_, index) => ({
|
|
34
46
|
field: `edits[${index}].body`,
|
|
@@ -36,9 +48,9 @@ test("model budget grows → argument issues remain complete JSON with counted o
|
|
|
36
48
|
fix: "Supply a line.",
|
|
37
49
|
}));
|
|
38
50
|
const reports = [outputBudgetsFor(1), small, large].map((budget) => {
|
|
39
|
-
const text = formatArgumentError(
|
|
51
|
+
const text = formatArgumentError(issues, false, budget);
|
|
40
52
|
assert.ok(Buffer.byteLength(text) <= budget.blockBytes);
|
|
41
|
-
const report = decodeReport(text);
|
|
53
|
+
const report = decodeReport(text, "edit");
|
|
42
54
|
assert.ok(report);
|
|
43
55
|
assert.equal((report.issues?.length ?? 0) + (report.omittedIssues ?? 0), issues.length);
|
|
44
56
|
return report;
|
|
@@ -50,7 +62,7 @@ test("model row allowance grows → anchor failures return complete observations
|
|
|
50
62
|
const text = "中文🙂".repeat(800);
|
|
51
63
|
const applied = applyEdits(
|
|
52
64
|
text,
|
|
53
|
-
[{ op: "delete",
|
|
65
|
+
[{ op: "delete", anchor: { line: 1, hash: wrongHash(text) } }],
|
|
54
66
|
DEFAULT_CONFIG.hashLen,
|
|
55
67
|
0,
|
|
56
68
|
);
|
|
@@ -61,15 +73,15 @@ test("model row allowance grows → anchor failures return complete observations
|
|
|
61
73
|
const report = describeFailure(
|
|
62
74
|
"edit",
|
|
63
75
|
describeEditFailure(applied.failure, snapshot, false, budget),
|
|
64
|
-
{
|
|
76
|
+
{ budget },
|
|
65
77
|
);
|
|
66
78
|
assert.equal(report.error, "ANCHOR_MISMATCH");
|
|
67
79
|
return report;
|
|
68
80
|
});
|
|
69
|
-
assert.ok(reports[0].failures?.[0].
|
|
81
|
+
assert.ok(reports[0].failures?.[0].omitted);
|
|
70
82
|
assert.equal(reports[0].failures?.[0].observed, undefined);
|
|
71
83
|
assert.equal(reports[1].failures?.[0].observed, snapshot.anchors.row(1, text));
|
|
72
|
-
assert.equal(reports[1].failures?.[0].
|
|
84
|
+
assert.equal(reports[1].failures?.[0].omitted, undefined);
|
|
73
85
|
for (const report of reports) {
|
|
74
86
|
assert.equal(report.publication, "NOT_PUBLISHED");
|
|
75
87
|
assert.ok(report.next?.includes("intended target"));
|
|
@@ -82,9 +94,7 @@ test("model budget grows → grep payload and diagnostics use that call's allowa
|
|
|
82
94
|
const outputs = [small, large].map((budget) =>
|
|
83
95
|
assembleGrepOutput({
|
|
84
96
|
formatted: {
|
|
85
|
-
blocks: [payload],
|
|
86
|
-
linesTruncated: false,
|
|
87
|
-
invalidUtf8: [],
|
|
97
|
+
blocks: [{ lines: payload.split("\n") }],
|
|
88
98
|
matches: 3_000,
|
|
89
99
|
files: 1,
|
|
90
100
|
},
|
|
@@ -95,7 +105,7 @@ test("model budget grows → grep payload and diagnostics use that call's allowa
|
|
|
95
105
|
budget,
|
|
96
106
|
}),
|
|
97
107
|
);
|
|
98
|
-
assert.
|
|
108
|
+
assert.equal(outputs[0].facts.outputLimit, formatByteSize(small.grepBytes));
|
|
99
109
|
assert.equal(outputs[1].payload, payload);
|
|
100
110
|
assert.equal(outputs[1].facts.outputLimit, undefined);
|
|
101
111
|
assert.ok(Buffer.byteLength(outputs[0].facts.diagnostics!) <= small.fieldBytes);
|
|
@@ -114,9 +124,7 @@ test("worker error reaches the tool → text is bounded once using the selected
|
|
|
114
124
|
);
|
|
115
125
|
assert.ok(reply && "error" in reply);
|
|
116
126
|
const error = restoreWorkerError(reply.error);
|
|
117
|
-
const reports = [small, large].map((budget) =>
|
|
118
|
-
describeFailure("replace", error, { mutation: true, budget }),
|
|
119
|
-
);
|
|
127
|
+
const reports = [small, large].map((budget) => describeFailure("replace", error, { budget }));
|
|
120
128
|
assert.ok(Buffer.byteLength(reports[0].message!) <= small.fieldBytes);
|
|
121
129
|
assert.ok(Buffer.byteLength(reports[0].cause!.message) <= small.fieldBytes);
|
|
122
130
|
assert.equal(reports[1].message, text);
|
|
@@ -146,14 +154,15 @@ test("model switches while a mutation waits → failure uses its starting budget
|
|
|
146
154
|
model = { ...model, id: "large", contextWindow: 1_048_576 };
|
|
147
155
|
assert.equal(budgets().readBytes, large.readBytes);
|
|
148
156
|
release.resolve();
|
|
149
|
-
const report = reportOf(await running);
|
|
150
|
-
assert.ok(report?.failures?.[0].
|
|
157
|
+
const report = reportOf(await running, "edit");
|
|
158
|
+
assert.ok(report?.failures?.[0].omitted);
|
|
151
159
|
assert.equal(report.failures[0].observed, undefined);
|
|
152
160
|
const next = reportOf(
|
|
153
161
|
await callTool(makeEditOverride(dir, DEFAULT_CONFIG, undefined, budgets), {
|
|
154
162
|
path,
|
|
155
163
|
edits: [{ op: "delete", anchor: `1#${wrongHash(text)}` }],
|
|
156
164
|
}),
|
|
165
|
+
"edit",
|
|
157
166
|
);
|
|
158
167
|
assert.equal(
|
|
159
168
|
next?.failures?.[0].observed,
|
package/src/pi/path.ts
CHANGED
|
@@ -41,7 +41,9 @@ export function serializePath(cwd: string, path: string): string {
|
|
|
41
41
|
const absolute = resolve(cwd, path);
|
|
42
42
|
const rel = relative(cwd, absolute);
|
|
43
43
|
const local = rel && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
|
|
44
|
-
|
|
44
|
+
// Windows accepts "/" too: one separator keeps paths alike inside and outside the cwd.
|
|
45
|
+
const native = local ? rel : absolute;
|
|
46
|
+
const candidate = sep === "\\" ? native.replaceAll(sep, "/") : native;
|
|
45
47
|
// A file URL preserves names whose spaces are normalized on input, and keeps headers single-line.
|
|
46
48
|
if (!/[\r\n]/.test(candidate)) {
|
|
47
49
|
if (canonicalPath(cwd, candidate) === absolute) return candidate;
|
package/src/pi/pi.test.ts
CHANGED
|
@@ -88,7 +88,7 @@ test("file tools share Pi-style URL and @ path resolution", async () => {
|
|
|
88
88
|
assert.match(read.content[0].text, /before/);
|
|
89
89
|
await callTool(
|
|
90
90
|
makeReplaceTool(dir, DEFAULT_CONFIG),
|
|
91
|
-
{ path: url, replacements: [{ find: "before", replace: "after" }] },
|
|
91
|
+
{ path: url, replacements: [{ literal: true, find: "before", replace: "after" }] },
|
|
92
92
|
{ toolCallId: "replace", ctx },
|
|
93
93
|
);
|
|
94
94
|
await callTool(
|
|
@@ -104,14 +104,15 @@ test("file tools share Pi-style URL and @ path resolution", async () => {
|
|
|
104
104
|
{ path: `@${url}`, pattern: "edited", literal: true },
|
|
105
105
|
{ toolCallId: "grep" },
|
|
106
106
|
);
|
|
107
|
+
assert.equal(matches.content[0].type, "text");
|
|
107
108
|
assert.match(matches.content[0].text, /edited/);
|
|
108
109
|
assert.equal(await readFile(file, "utf8"), "edited\n");
|
|
109
110
|
let commands = 0;
|
|
110
111
|
const fusion = createActionFusionExecutor(async () => {
|
|
111
112
|
commands++;
|
|
112
|
-
return { status: "succeeded",
|
|
113
|
+
return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
|
|
113
114
|
});
|
|
114
|
-
|
|
115
|
+
await callTool(
|
|
115
116
|
makeWriteOverride(dir, fusion),
|
|
116
117
|
{
|
|
117
118
|
path: `@${url}`,
|
|
@@ -121,8 +122,6 @@ test("file tools share Pi-style URL and @ path resolution", async () => {
|
|
|
121
122
|
},
|
|
122
123
|
{ toolCallId: "fused", ctx },
|
|
123
124
|
);
|
|
124
|
-
assert.ok(fused.details.actionFusion);
|
|
125
|
-
assert.equal(fused.details.actionFusion.command, "succeeded");
|
|
126
125
|
assert.equal(commands, 1);
|
|
127
126
|
} finally {
|
|
128
127
|
await rm(dir, { recursive: true, force: true });
|
package/src/pi/read-tool.ts
CHANGED
|
@@ -25,26 +25,20 @@ import { Text } from "@earendil-works/pi-tui";
|
|
|
25
25
|
import { Type } from "typebox";
|
|
26
26
|
import { scanTextLines } from "./text-stream.ts";
|
|
27
27
|
import { createAnchorFormatter, displayCarriageReturns, parseHashline } from "./anchor-format.ts";
|
|
28
|
-
import { canonicalPath } from "./path.ts";
|
|
29
|
-
import { renderToolError, reportLines,
|
|
30
|
-
import { type ForgetReceiptDetails, readReceipt, withResultTag } from "./forget-tool.ts";
|
|
28
|
+
import { canonicalPath, serializePath } from "./path.ts";
|
|
29
|
+
import { renderToolError, reportLines, splitReport } from "./render.ts";
|
|
31
30
|
import { POSITIVE_SAFE_INTEGER } from "./schema.ts";
|
|
32
31
|
import { errnoCode } from "../core/errors.ts";
|
|
33
32
|
import { throwIfCancelled } from "./error-text.ts";
|
|
34
|
-
import {
|
|
35
|
-
import { defaultOutputBudgets,
|
|
33
|
+
import { reportResult, runTool, type ReportDetails } from "./report.ts";
|
|
34
|
+
import { defaultOutputBudgets, formatByteSize, type OutputBudgetProvider } from "./budgets.ts";
|
|
36
35
|
import type { HashlineEditConfig } from "./config.ts";
|
|
37
36
|
import { createArgumentPreparer } from "./argument-validation.ts";
|
|
38
37
|
|
|
39
38
|
const DEFAULT_OFFSET = 1;
|
|
40
39
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
pagination?: NonNullable<Report["pagination"]>;
|
|
44
|
-
} & ForgetReceiptDetails &
|
|
45
|
-
Partial<ReportDetails>;
|
|
46
|
-
/** The read card shows the forget id only on the forget card. */
|
|
47
|
-
const READ_CARD_SHOWN = new Set(["resultId"]);
|
|
40
|
+
/** Pi's read details for a delegated native read; the report states this read's own facts. */
|
|
41
|
+
type ReadDetails = (ReadToolDetails & { nativeRead?: true }) & Partial<ReportDetails>;
|
|
48
42
|
|
|
49
43
|
/**
|
|
50
44
|
* First result line: `<path> · <N> lines`, optionally ` (from line <offset>)` and
|
|
@@ -61,7 +55,7 @@ function formatReadHeader(
|
|
|
61
55
|
const shownFrom = start > DEFAULT_OFFSET ? ` (from line ${start})` : "";
|
|
62
56
|
return `${path} · ${totalLines} lines${shownFrom}${finalNewline ? "" : " · no trailing newline"}`;
|
|
63
57
|
}
|
|
64
|
-
const READ_HEADER = /^(.+?) · (\d+ lines(?: \(from line \d+\))?(?: · no trailing newline)?)
|
|
58
|
+
const READ_HEADER = /^(.+?) · (\d+ lines(?: \(from line \d+\))?(?: · no trailing newline)?)$/s;
|
|
65
59
|
|
|
66
60
|
/**
|
|
67
61
|
* Render the expanded read body for the TUI: color the header, strip the
|
|
@@ -149,7 +143,7 @@ export function makeReadOverride(
|
|
|
149
143
|
name: "read" as const,
|
|
150
144
|
label: "read",
|
|
151
145
|
description:
|
|
152
|
-
"Read a file. Text lines show as LINE#HASH│content anchors for edit; CRLF line endings show as LF.
|
|
146
|
+
"Read a file. Text lines show as LINE#HASH│content anchors for edit; CRLF line endings show as LF.",
|
|
153
147
|
promptSnippet: "Read files with editable line anchors",
|
|
154
148
|
parameters: parameters as typeof builtin.parameters,
|
|
155
149
|
prepareArguments: createArgumentPreparer("read", parameters, undefined, budgets),
|
|
@@ -160,19 +154,18 @@ export function makeReadOverride(
|
|
|
160
154
|
renderResult(result, options, theme, context) {
|
|
161
155
|
const { isPartial, expanded } = options;
|
|
162
156
|
if (isPartial) return new Text(theme.fg("warning", "Reading…"), 0, 0);
|
|
163
|
-
if (context?.isError) return renderToolError(result, theme, expanded);
|
|
157
|
+
if (context?.isError) return renderToolError(result, "read", theme, expanded);
|
|
158
|
+
const { content, report } = splitReport(result);
|
|
164
159
|
if (result.details?.nativeRead)
|
|
165
|
-
return builtin.renderResult!(
|
|
160
|
+
return builtin.renderResult!({ ...result, content }, options, theme, context);
|
|
166
161
|
// Collapsed (not expanded): show nothing — the call line carries the
|
|
167
162
|
// title, matching the built-in read's fold behavior.
|
|
168
163
|
if (!expanded) return new Text("", 0, 0);
|
|
169
|
-
const
|
|
170
|
-
const raw = content?.type === "text" ? content.text : "";
|
|
171
|
-
const report = result.details?.report;
|
|
164
|
+
const raw = content[0]?.type === "text" ? content[0].text : "";
|
|
172
165
|
return new Text(
|
|
173
166
|
[
|
|
174
167
|
renderReadBody(raw, String(context?.args?.path ?? ""), theme),
|
|
175
|
-
...(report ? reportLines(report, theme
|
|
168
|
+
...(report ? reportLines(report, theme) : []),
|
|
176
169
|
].join("\n"),
|
|
177
170
|
0,
|
|
178
171
|
0,
|
|
@@ -197,22 +190,10 @@ export function makeReadOverride(
|
|
|
197
190
|
const report = { tool: "read" as const, path: params.path };
|
|
198
191
|
const readNative = async () => {
|
|
199
192
|
const result = await builtin.execute(toolCallId, params, signal, onUpdate, ctx);
|
|
200
|
-
return
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
payload: result.content,
|
|
205
|
-
details: { ...result.details, nativeRead: true as const },
|
|
206
|
-
},
|
|
207
|
-
config.forget,
|
|
208
|
-
() =>
|
|
209
|
-
readReceipt(
|
|
210
|
-
params.path,
|
|
211
|
-
result.content.some((block) => block.type === "image")
|
|
212
|
-
? { image: true }
|
|
213
|
-
: undefined,
|
|
214
|
-
),
|
|
215
|
-
);
|
|
193
|
+
return reportResult(report, result.content, {
|
|
194
|
+
...result.details,
|
|
195
|
+
nativeRead: true as const,
|
|
196
|
+
});
|
|
216
197
|
};
|
|
217
198
|
|
|
218
199
|
const absPath = canonicalPath(cwd, params.path);
|
|
@@ -226,8 +207,6 @@ export function makeReadOverride(
|
|
|
226
207
|
|
|
227
208
|
const rows: string[] = [];
|
|
228
209
|
const crExpansion = Buffer.byteLength(displayCarriageReturns("\r")) - 1;
|
|
229
|
-
let totalRows = 0;
|
|
230
|
-
let totalBytes = 0;
|
|
231
210
|
let outputBytes = 0;
|
|
232
211
|
let truncated = false;
|
|
233
212
|
let firstLineExceedsLimit = false;
|
|
@@ -237,12 +216,11 @@ export function makeReadOverride(
|
|
|
237
216
|
absPath,
|
|
238
217
|
(number) => number >= start && number - start < limit,
|
|
239
218
|
(line) => {
|
|
219
|
+
if (truncated) return;
|
|
240
220
|
const rowBytes =
|
|
241
221
|
line.byteLength +
|
|
242
222
|
line.carriageReturns * crExpansion +
|
|
243
223
|
Buffer.byteLength(anchors.row(line.number, ""));
|
|
244
|
-
totalBytes += rowBytes + (totalRows++ > 0 ? 1 : 0);
|
|
245
|
-
if (truncated) return;
|
|
246
224
|
const nextBytes = outputBytes + rowBytes + (rows.length > 0 ? 1 : 0);
|
|
247
225
|
if (nextBytes > maxBytes) {
|
|
248
226
|
truncated = true;
|
|
@@ -262,9 +240,13 @@ export function makeReadOverride(
|
|
|
262
240
|
throw error;
|
|
263
241
|
}
|
|
264
242
|
if (stats.hasNul) return readNative();
|
|
265
|
-
// Rows were returned and more remain
|
|
243
|
+
// Rows were returned and more remain. A caller's own limit is a chosen window: its header
|
|
244
|
+
// and rows already show where it ends, so only a window the extension cut (default limit
|
|
245
|
+
// or byte budget) gets a report.
|
|
266
246
|
const pagination =
|
|
267
|
-
|
|
247
|
+
(params.limit === undefined || truncated) &&
|
|
248
|
+
rows.length > 0 &&
|
|
249
|
+
start + rows.length <= stats.totalLines
|
|
268
250
|
? {
|
|
269
251
|
start,
|
|
270
252
|
end: start + (rows.length - 1),
|
|
@@ -272,47 +254,17 @@ export function makeReadOverride(
|
|
|
272
254
|
nextOffset: start + rows.length,
|
|
273
255
|
}
|
|
274
256
|
: undefined;
|
|
275
|
-
|
|
276
|
-
const
|
|
277
|
-
content: rows.join("\n"),
|
|
278
|
-
truncated,
|
|
279
|
-
truncatedBy: truncated ? ("bytes" as const) : null,
|
|
280
|
-
totalLines: totalRows,
|
|
281
|
-
totalBytes,
|
|
282
|
-
outputLines: rows.length,
|
|
283
|
-
outputBytes,
|
|
284
|
-
lastLinePartial: false,
|
|
285
|
-
firstLineExceedsLimit,
|
|
286
|
-
maxLines: totalRows,
|
|
287
|
-
maxBytes,
|
|
288
|
-
};
|
|
289
|
-
|
|
290
|
-
const header = `${formatReadHeader(params.path, stats.totalLines, start, stats.finalNewline)}\n`;
|
|
291
|
-
const limitText = formatKiB(maxBytes);
|
|
257
|
+
const header = `${formatReadHeader(serializePath(cwd, absPath), stats.totalLines, start, stats.finalNewline)}\n`;
|
|
258
|
+
const limitText = formatByteSize(maxBytes);
|
|
292
259
|
|
|
293
|
-
return
|
|
294
|
-
toolCallId,
|
|
260
|
+
return reportResult(
|
|
295
261
|
{
|
|
296
|
-
report
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
lineTooLong: firstLineExceedsLimit ? { line: start, limit: limitText } : undefined,
|
|
301
|
-
},
|
|
302
|
-
payload: [{ type: "text" as const, text: header + truncation.content }],
|
|
303
|
-
details: {
|
|
304
|
-
...(truncated ? { truncation } : {}),
|
|
305
|
-
...(pagination ? { pagination } : {}),
|
|
306
|
-
},
|
|
262
|
+
...report,
|
|
263
|
+
pagination,
|
|
264
|
+
outputLimit: truncated && !firstLineExceedsLimit ? limitText : undefined,
|
|
265
|
+
lineTooLong: firstLineExceedsLimit ? { line: start, limit: limitText } : undefined,
|
|
307
266
|
},
|
|
308
|
-
|
|
309
|
-
() =>
|
|
310
|
-
readReceipt(
|
|
311
|
-
params.path,
|
|
312
|
-
rows.length > 0
|
|
313
|
-
? { start, end: start + rows.length - 1, truncated: truncation.truncated }
|
|
314
|
-
: undefined,
|
|
315
|
-
),
|
|
267
|
+
[{ type: "text" as const, text: header + rows.join("\n") }],
|
|
316
268
|
);
|
|
317
269
|
});
|
|
318
270
|
},
|