@criogaid/pi-hashline-edit 0.9.0 → 0.11.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 +12 -12
- package/README.zh-CN.md +12 -12
- package/THIRD_PARTY_NOTICES.md +0 -6
- package/package.json +1 -1
- package/src/core/AGENTS.md +4 -5
- package/src/core/apply.test.ts +96 -271
- package/src/core/apply.ts +62 -169
- package/src/core/case-fold.ts +8 -67
- package/src/core/character-set.test.ts +2 -3
- package/src/core/character-set.ts +5 -5
- package/src/core/errors.test.ts +23 -7
- package/src/core/errors.ts +32 -5
- package/src/core/hash.test.ts +8 -16
- package/src/core/hash.ts +3 -23
- package/src/core/lines.ts +2 -4
- package/src/core/ranges.test.ts +2 -1
- package/src/core/ranges.ts +1 -1
- package/src/core/regex.ts +3 -4
- package/src/core/replace.test.ts +47 -1
- package/src/core/replace.ts +19 -13
- package/src/core/search-analysis.test.ts +24 -27
- package/src/core/search-analysis.ts +34 -65
- package/src/core/search-matrix.testing.ts +0 -2
- package/src/core/search.ts +1 -1
- package/src/core/text.test.ts +5 -5
- package/src/core/text.ts +5 -12
- package/src/core/types.ts +8 -44
- package/src/index.ts +8 -8
- package/src/integration/config-registration.test.ts +8 -10
- package/src/integration/fusion-dispatch.test.ts +4 -7
- package/src/integration/grep-errors.test.ts +3 -3
- package/src/integration/grep-flags.test.ts +5 -19
- package/src/integration/grep-js-completeness.test.ts +45 -18
- package/src/integration/grep-line-candidates.test.ts +7 -10
- package/src/integration/grep-matrix.test.ts +6 -9
- package/src/integration/grep-order.test.ts +4 -4
- package/src/integration/grep-path-matrix.test.ts +10 -9
- package/src/integration/grep-prefilter-coverage.test.ts +5 -8
- package/src/integration/grep-process-limits.test.ts +76 -0
- package/src/integration/grep-regex.test.ts +10 -10
- package/src/integration/grep-rg.test.ts +166 -66
- package/src/integration/grep-scan-budget.test.ts +9 -9
- package/src/integration/grep-translation.test.ts +18 -32
- package/src/integration/large-text.test.ts +6 -52
- package/src/integration/model-budget-lifecycle.test.ts +10 -9
- package/src/integration/mutation-file-types.testing.ts +4 -4
- package/src/integration/npm-package.testing.ts +3 -3
- package/src/integration/publication-read-changes.test.ts +161 -83
- package/src/integration/read-changes.test.ts +4 -4
- package/src/integration/replace-worker-boundary.test.ts +22 -12
- package/src/integration/report-replay.test.ts +23 -26
- package/src/integration/utf8-errors.test.ts +4 -4
- package/src/pi/AGENTS.md +18 -17
- package/src/pi/action-fusion.test.ts +241 -353
- package/src/pi/action-fusion.testing.ts +38 -0
- package/src/pi/action-fusion.ts +150 -125
- package/src/pi/anchor-format.test.ts +9 -9
- package/src/pi/anchor-format.ts +6 -8
- package/src/pi/argument-diagnostics.ts +25 -28
- package/src/pi/argument-error.ts +2 -1
- package/src/pi/argument-format.test.ts +19 -18
- package/src/pi/argument-validation.test.ts +334 -283
- package/src/pi/argument-validation.ts +5 -8
- package/src/pi/budgets.ts +6 -8
- package/src/pi/codemode.test.ts +7 -2
- package/src/pi/config.test.ts +7 -3
- package/src/pi/config.ts +12 -9
- package/src/pi/diagnostic-buffer.test.ts +34 -13
- package/src/pi/diagnostic-buffer.ts +1 -2
- package/src/pi/directory-sync.test.ts +0 -1
- package/src/pi/edit-tool.ts +86 -211
- package/src/pi/error-text.ts +10 -9
- package/src/pi/execute.test.ts +249 -345
- package/src/pi/failure-context.test.ts +146 -127
- package/src/pi/failure-context.ts +45 -94
- package/src/pi/failure-path.test.ts +182 -155
- package/src/pi/file-commit.test.ts +156 -71
- package/src/pi/file-commit.ts +126 -146
- package/src/pi/file-snapshot.test.ts +3 -5
- package/src/pi/fusion-card.test.ts +26 -22
- package/src/pi/fusion-card.ts +16 -24
- package/src/pi/grep-candidates.test.ts +19 -120
- package/src/pi/grep-candidates.ts +25 -76
- package/src/pi/grep-matrix.test.ts +5 -5
- package/src/pi/grep-order.test.ts +16 -15
- package/src/pi/grep-output.ts +94 -107
- package/src/pi/grep-render.ts +1 -1
- package/src/pi/grep-reread.ts +97 -0
- package/src/pi/grep-rg.testing.ts +70 -0
- package/src/pi/grep-scope.ts +41 -43
- package/src/pi/grep-search.ts +27 -39
- package/src/pi/grep-tool.ts +63 -106
- package/src/pi/grep.test.ts +177 -156
- package/src/pi/model-budgets.test.ts +27 -24
- package/src/pi/model-budgets.ts +6 -38
- package/src/pi/mutation-outcome.testing.ts +0 -1
- package/src/pi/mutation-result.test.ts +44 -35
- package/src/pi/mutation-result.ts +52 -21
- package/src/pi/mutation-runner.ts +134 -74
- package/src/pi/output-budgets.test.ts +86 -42
- package/src/pi/path.ts +1 -1
- package/src/pi/pi.test.ts +18 -13
- package/src/pi/read-tool.ts +18 -23
- package/src/pi/read.test.ts +22 -41
- package/src/pi/regex-worker-contract.ts +3 -13
- package/src/pi/regex-worker.ts +1 -10
- package/src/pi/registration.test.ts +85 -51
- package/src/pi/render.test.ts +88 -59
- package/src/pi/render.ts +64 -65
- package/src/pi/replace-regex.ts +14 -2
- package/src/pi/replace-tool.ts +22 -94
- package/src/pi/replace-worker.ts +1 -1
- package/src/pi/replace.test.ts +53 -38
- package/src/pi/report-cause.ts +3 -8
- package/src/pi/report-failure.testing.ts +10 -3
- package/src/pi/report-schema.ts +251 -148
- package/src/pi/report.test.ts +215 -67
- package/src/pi/report.ts +50 -98
- package/src/pi/result-safety.test.ts +241 -247
- package/src/pi/rg-process.test.ts +77 -63
- package/src/pi/rg-process.ts +53 -75
- package/src/pi/rg-regex.ts +40 -400
- package/src/pi/schema.ts +35 -0
- package/src/pi/text-stream.test.ts +0 -21
- package/src/pi/text-stream.ts +14 -21
- package/src/pi/tool-factories.testing.ts +59 -0
- package/src/pi/write-tool.ts +36 -71
- package/src/pi/write.test.ts +31 -34
- package/src/testing/regex-translation-corpus.ts +12 -12
- package/src/testing/run-tests.ts +1 -1
- package/src/pi/replace-worker-contract.ts +0 -10
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { AgentToolCallOutcome, AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import type { TestContext } from "node:test";
|
|
4
|
+
import { createToolContext } from "./tool-call.testing.ts";
|
|
5
|
+
|
|
6
|
+
export type SessionCommand = ExtensionToolContext["executeTool"];
|
|
7
|
+
|
|
8
|
+
type CommandResult = Omit<AgentToolResult<unknown>, "details"> & {
|
|
9
|
+
readonly details?: unknown;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export function commandCompletion(
|
|
13
|
+
result: CommandResult,
|
|
14
|
+
isError = false,
|
|
15
|
+
terminate?: boolean,
|
|
16
|
+
structuredContent?: AgentToolResult<unknown>["structuredContent"],
|
|
17
|
+
): AgentToolCallOutcome {
|
|
18
|
+
return {
|
|
19
|
+
toolCall: { type: "toolCall", id: "test/1", name: "bash", arguments: {} },
|
|
20
|
+
result: {
|
|
21
|
+
...result,
|
|
22
|
+
details: result.details ?? {},
|
|
23
|
+
...(terminate === undefined ? {} : { terminate }),
|
|
24
|
+
...(structuredContent === undefined ? {} : { structuredContent }),
|
|
25
|
+
},
|
|
26
|
+
isError,
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function createFusionContext(
|
|
31
|
+
cwd: string,
|
|
32
|
+
t: TestContext,
|
|
33
|
+
executeTool: ExtensionToolContext["executeTool"],
|
|
34
|
+
mode: ExtensionToolContext["mode"] = "json",
|
|
35
|
+
) {
|
|
36
|
+
const context = await createToolContext(cwd, t, mode);
|
|
37
|
+
return { ...context, executeTool };
|
|
38
|
+
}
|
package/src/pi/action-fusion.ts
CHANGED
|
@@ -23,35 +23,31 @@
|
|
|
23
23
|
|
|
24
24
|
import { realpath } from "node:fs/promises";
|
|
25
25
|
import { basename, dirname, resolve } from "node:path";
|
|
26
|
-
import type {
|
|
26
|
+
import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
|
|
27
27
|
import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
|
|
28
28
|
import { Type, type Static, type TObject, type TProperties } from "typebox";
|
|
29
29
|
import { commitFreshness, observeFreshness, type FreshnessObservation } from "./file-commit.ts";
|
|
30
30
|
import {
|
|
31
|
+
CommandNotRun,
|
|
31
32
|
commandText,
|
|
32
|
-
finalizeMutation,
|
|
33
33
|
type CommandFacts,
|
|
34
34
|
type MutationOutcome,
|
|
35
35
|
type MutationResultDetails,
|
|
36
36
|
} from "./mutation-result.ts";
|
|
37
37
|
import { errnoCode, errorMessage } from "../core/errors.ts";
|
|
38
38
|
import { throwIfCancelled } from "./error-text.ts";
|
|
39
|
-
import { causeOf, CommandNotRun, type ReportDetails } from "./report.ts";
|
|
40
|
-
import type { OutputBudgets } from "./budgets.ts";
|
|
41
39
|
import type {
|
|
42
40
|
ActionFusionProgress,
|
|
43
41
|
CommandResult,
|
|
44
42
|
CommandStatus,
|
|
45
43
|
Freshness,
|
|
46
44
|
MutationToolName,
|
|
47
|
-
SuccessReport,
|
|
48
45
|
} from "./report-schema.ts";
|
|
49
|
-
export type { ActionFusionProgress } from "./report-schema.ts";
|
|
50
46
|
|
|
51
47
|
const MILLISECONDS_PER_SECOND = 1_000;
|
|
52
48
|
|
|
53
49
|
// Pi's built-in Bash rejects timeouts above the setTimeout millisecond limit.
|
|
54
|
-
const MAX_BASH_TIMEOUT_SECONDS = 2_147_483_647 /
|
|
50
|
+
const MAX_BASH_TIMEOUT_SECONDS = 2_147_483_647 / MILLISECONDS_PER_SECOND;
|
|
55
51
|
|
|
56
52
|
// Pi's Bash runs on this host, and Pi's prompt does not name the OS; only Windows needs the path note.
|
|
57
53
|
const COMMAND_DESCRIPTION =
|
|
@@ -63,13 +59,13 @@ export const ACTION_FUSION_GUIDELINES = [
|
|
|
63
59
|
"When a check covers several changes, run it once after all of those changes.",
|
|
64
60
|
];
|
|
65
61
|
|
|
66
|
-
type ProgressReporter = (progress: ActionFusionProgress
|
|
62
|
+
type ProgressReporter = (progress: ActionFusionProgress) => void;
|
|
67
63
|
|
|
68
64
|
function createThenRunSchema(tool: MutationToolName) {
|
|
69
65
|
return Type.Optional(
|
|
70
66
|
Type.Object(
|
|
71
67
|
{
|
|
72
|
-
command: Type.String({
|
|
68
|
+
command: Type.String({ pattern: "\\S", description: COMMAND_DESCRIPTION }),
|
|
73
69
|
timeout: Type.Optional(
|
|
74
70
|
Type.Number({
|
|
75
71
|
exclusiveMinimum: 0,
|
|
@@ -85,6 +81,7 @@ function createThenRunSchema(tool: MutationToolName) {
|
|
|
85
81
|
),
|
|
86
82
|
);
|
|
87
83
|
}
|
|
84
|
+
|
|
88
85
|
/** Add the optional then_run field to a mutation schema when Action Fusion is enabled. */
|
|
89
86
|
export function withThenRunSchema<P extends TProperties>(
|
|
90
87
|
schema: TObject<P>,
|
|
@@ -98,6 +95,7 @@ export function withThenRunSchema<P extends TProperties>(
|
|
|
98
95
|
)
|
|
99
96
|
: schema;
|
|
100
97
|
}
|
|
98
|
+
|
|
101
99
|
export type ThenRunInput = NonNullable<Static<ReturnType<typeof createThenRunSchema>>>;
|
|
102
100
|
|
|
103
101
|
/** Name then_run in a mutation tool's description when Action Fusion is enabled. */
|
|
@@ -107,28 +105,29 @@ export function withThenRunDescription(description: string, actionFusion: boolea
|
|
|
107
105
|
: description;
|
|
108
106
|
}
|
|
109
107
|
|
|
108
|
+
/** What a fused call leaves for the mutation runner to report; Fusion builds no result itself. */
|
|
109
|
+
export interface FusedMutation<TDetails, TTool extends MutationToolName> {
|
|
110
|
+
readonly outcome: MutationOutcome<TDetails, TTool>;
|
|
111
|
+
readonly observation: FreshnessObservation;
|
|
112
|
+
/** Absent when the call has no then_run. */
|
|
113
|
+
readonly command?: CommandFacts;
|
|
114
|
+
/** Preserve the session tool's request to stop after this tool batch. */
|
|
115
|
+
readonly terminate?: boolean;
|
|
116
|
+
}
|
|
117
|
+
|
|
110
118
|
/** Keep command state independent of its diagnostic text and of file publication. */
|
|
111
|
-
|
|
119
|
+
interface CommandOutcome {
|
|
112
120
|
readonly status: Exclude<CommandStatus, "skipped">;
|
|
113
121
|
readonly result: CommandResult;
|
|
114
122
|
/** Preserve the session tool's request to stop after this tool batch. */
|
|
115
123
|
readonly terminate?: boolean;
|
|
116
124
|
}
|
|
117
125
|
|
|
118
|
-
|
|
119
|
-
toolCallId: string,
|
|
120
|
-
input: ThenRunInput,
|
|
121
|
-
signal: AbortSignal | undefined,
|
|
122
|
-
ctx: ExtensionToolContext,
|
|
123
|
-
onUpdate?: AgentToolUpdateCallback<unknown>,
|
|
124
|
-
) => Promise<CommandOutcome>;
|
|
125
|
-
|
|
126
|
-
async function defaultCommandRunner(
|
|
127
|
-
_toolCallId: string,
|
|
126
|
+
async function runCommand(
|
|
128
127
|
input: ThenRunInput,
|
|
129
128
|
signal: AbortSignal | undefined,
|
|
130
129
|
ctx: ExtensionToolContext,
|
|
131
|
-
onUpdate
|
|
130
|
+
onUpdate: AgentToolUpdateCallback<unknown>,
|
|
132
131
|
): Promise<CommandOutcome> {
|
|
133
132
|
// Use the session's callable Bash, including overrides, validation, permission
|
|
134
133
|
// hooks and tool_result hooks. Tool failures resolve with isError, not rejection.
|
|
@@ -159,29 +158,112 @@ async function defaultCommandRunner(
|
|
|
159
158
|
}
|
|
160
159
|
|
|
161
160
|
async function canonicalQueueKey(path: string): Promise<string> {
|
|
161
|
+
const folded = (key: string) => (process.platform === "win32" ? key.toLowerCase() : key);
|
|
162
162
|
const resolved = resolve(path);
|
|
163
163
|
let current = resolved;
|
|
164
164
|
const missing: string[] = [];
|
|
165
165
|
while (true) {
|
|
166
166
|
try {
|
|
167
|
-
|
|
168
|
-
return process.platform === "win32" ? canonical.toLowerCase() : canonical;
|
|
167
|
+
return folded(resolve(await realpath(current), ...missing));
|
|
169
168
|
} catch (error) {
|
|
170
169
|
const code = errnoCode(error);
|
|
171
170
|
if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
|
|
172
171
|
const parent = dirname(current);
|
|
173
|
-
if (parent === current)
|
|
174
|
-
return process.platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
172
|
+
if (parent === current) return folded(resolved);
|
|
175
173
|
missing.unshift(basename(current));
|
|
176
174
|
current = parent;
|
|
177
175
|
}
|
|
178
176
|
}
|
|
179
177
|
}
|
|
180
178
|
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
179
|
+
/**
|
|
180
|
+
* One then_run call's display state and the observers that follow it. Display callbacks are
|
|
181
|
+
* observers: their failures must not change publication or command execution, so the first is
|
|
182
|
+
* kept for the report. The tracker owns the heartbeat lifetime; Pi Bash owns timeout and
|
|
183
|
+
* process cleanup.
|
|
184
|
+
*/
|
|
185
|
+
function createProgressTracker<TDetails extends object>({
|
|
186
|
+
toolCallId,
|
|
187
|
+
thenRun,
|
|
188
|
+
onProgress,
|
|
189
|
+
onUpdate,
|
|
190
|
+
}: {
|
|
191
|
+
toolCallId: string;
|
|
192
|
+
thenRun: ThenRunInput;
|
|
193
|
+
onProgress: ProgressReporter;
|
|
194
|
+
onUpdate: AgentToolUpdateCallback<MutationResultDetails<TDetails>> | undefined;
|
|
195
|
+
}) {
|
|
196
|
+
let mutationDetails: TDetails | undefined;
|
|
197
|
+
let failure: unknown;
|
|
198
|
+
let commandResult: CommandResult | undefined;
|
|
199
|
+
let commandTiming: { readonly timeoutSeconds: number; readonly deadlineMs: number } | undefined;
|
|
200
|
+
let heartbeat: ReturnType<typeof setInterval> | undefined;
|
|
201
|
+
|
|
202
|
+
const report = (command: ActionFusionProgress["command"], freshness: Freshness) => {
|
|
203
|
+
const progress: ActionFusionProgress = {
|
|
204
|
+
toolCallId,
|
|
205
|
+
commandText: thenRun.command,
|
|
206
|
+
command,
|
|
207
|
+
freshness,
|
|
208
|
+
...(commandResult ? { result: commandResult } : {}),
|
|
209
|
+
mutationCompleted: mutationDetails !== undefined,
|
|
210
|
+
...(commandTiming
|
|
211
|
+
? {
|
|
212
|
+
timing: {
|
|
213
|
+
timeoutSeconds: commandTiming.timeoutSeconds,
|
|
214
|
+
remainingSeconds: Math.max(
|
|
215
|
+
0,
|
|
216
|
+
Math.ceil((commandTiming.deadlineMs - Date.now()) / MILLISECONDS_PER_SECOND),
|
|
217
|
+
),
|
|
218
|
+
},
|
|
219
|
+
}
|
|
220
|
+
: {}),
|
|
221
|
+
};
|
|
222
|
+
for (const notify of [
|
|
223
|
+
() => onProgress(progress),
|
|
224
|
+
() => onUpdate?.({ content: [], details: { ...mutationDetails, actionFusion: progress } }),
|
|
225
|
+
]) {
|
|
226
|
+
try {
|
|
227
|
+
notify();
|
|
228
|
+
} catch (error) {
|
|
229
|
+
failure ??= error;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
/** Follow the running command's partial results. */
|
|
235
|
+
const followCommand: AgentToolUpdateCallback<unknown> = (partial) => {
|
|
236
|
+
// Pi Bash emits an initial update even for silent commands. Start its
|
|
237
|
+
// countdown here, after session permission hooks have allowed execution.
|
|
238
|
+
if (!commandTiming && thenRun.timeout !== undefined) {
|
|
239
|
+
commandTiming = {
|
|
240
|
+
timeoutSeconds: thenRun.timeout,
|
|
241
|
+
deadlineMs: Date.now() + thenRun.timeout * MILLISECONDS_PER_SECOND,
|
|
242
|
+
};
|
|
243
|
+
heartbeat = setInterval(() => report("running", "unknown"), MILLISECONDS_PER_SECOND);
|
|
244
|
+
heartbeat.unref();
|
|
245
|
+
}
|
|
246
|
+
commandResult = { content: partial.content, details: partial.details };
|
|
247
|
+
report("running", "unknown");
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
return {
|
|
251
|
+
report,
|
|
252
|
+
followCommand,
|
|
253
|
+
failure: () => failure,
|
|
254
|
+
mutationCompleted(details: TDetails) {
|
|
255
|
+
mutationDetails = details;
|
|
256
|
+
},
|
|
257
|
+
stopHeartbeat() {
|
|
258
|
+
if (heartbeat) clearInterval(heartbeat);
|
|
259
|
+
},
|
|
260
|
+
commandSettled(result: CommandResult) {
|
|
261
|
+
commandResult = result;
|
|
262
|
+
},
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export function createActionFusionExecutor(onProgress: ProgressReporter) {
|
|
185
267
|
const queueTails = new Map<string, Promise<void>>();
|
|
186
268
|
|
|
187
269
|
async function withQueue<T>(path: string, work: () => Promise<T>): Promise<T> {
|
|
@@ -204,153 +286,96 @@ export function createActionFusionExecutor(
|
|
|
204
286
|
|
|
205
287
|
return async function execute<TDetails extends object, TTool extends MutationToolName>({
|
|
206
288
|
toolCallId,
|
|
207
|
-
tool,
|
|
208
|
-
displayPath,
|
|
209
289
|
absolutePath,
|
|
210
290
|
thenRun,
|
|
211
|
-
budget,
|
|
212
291
|
mutate,
|
|
213
292
|
signal,
|
|
214
293
|
ctx,
|
|
215
294
|
onUpdate,
|
|
216
295
|
}: {
|
|
217
296
|
toolCallId: string;
|
|
218
|
-
tool: TTool;
|
|
219
|
-
/** The caller-supplied path, as the report states it. */
|
|
220
|
-
displayPath: string;
|
|
221
297
|
absolutePath: string;
|
|
222
298
|
thenRun: ThenRunInput | undefined;
|
|
223
|
-
|
|
224
|
-
mutate: () => Promise<MutationOutcome<TDetails, NoInfer<TTool>>>;
|
|
299
|
+
mutate: () => Promise<MutationOutcome<TDetails, TTool>>;
|
|
225
300
|
signal: AbortSignal | undefined;
|
|
226
301
|
ctx: ExtensionToolContext;
|
|
227
302
|
onUpdate?: AgentToolUpdateCallback<MutationResultDetails<TDetails>>;
|
|
228
|
-
}): Promise<
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
timing: {
|
|
245
|
-
timeoutSeconds: commandTiming.timeoutSeconds,
|
|
246
|
-
remainingSeconds: Math.max(
|
|
247
|
-
0,
|
|
248
|
-
Math.ceil((commandTiming.deadlineMs - Date.now()) / MILLISECONDS_PER_SECOND),
|
|
249
|
-
),
|
|
250
|
-
},
|
|
251
|
-
}
|
|
252
|
-
: {}),
|
|
253
|
-
};
|
|
254
|
-
// Display callbacks are observers: their failures must not change publication or command execution.
|
|
255
|
-
for (const notify of [
|
|
256
|
-
() => onProgress?.(progress, ctx),
|
|
257
|
-
() =>
|
|
258
|
-
onUpdate?.({
|
|
259
|
-
content: [],
|
|
260
|
-
details: { ...completedMutation?.details, actionFusion: progress },
|
|
261
|
-
}),
|
|
262
|
-
]) {
|
|
263
|
-
try {
|
|
264
|
-
notify();
|
|
265
|
-
} catch (error) {
|
|
266
|
-
progressFailure ??= error;
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
};
|
|
303
|
+
}): Promise<FusedMutation<TDetails, TTool>> {
|
|
304
|
+
// Without a command, the mutation still waits for a fused call on the same file.
|
|
305
|
+
if (thenRun === undefined) {
|
|
306
|
+
return withQueue(absolutePath, async () => {
|
|
307
|
+
throwIfCancelled(signal);
|
|
308
|
+
const outcome = await mutate();
|
|
309
|
+
return { outcome, observation: commitFreshness(outcome.commit) };
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const progress = createProgressTracker<TDetails>({
|
|
314
|
+
toolCallId,
|
|
315
|
+
thenRun,
|
|
316
|
+
onProgress,
|
|
317
|
+
onUpdate,
|
|
318
|
+
});
|
|
270
319
|
/** A mutation that did not complete keeps its own failure; Fusion adds only the command status. */
|
|
271
320
|
const notRun = (error: unknown, command: "skipped" | "cancelled") => {
|
|
272
|
-
report(command, "unknown");
|
|
273
|
-
return new CommandNotRun(error, command,
|
|
321
|
+
progress.report(command, "unknown");
|
|
322
|
+
return new CommandNotRun(error, command, progress.failure());
|
|
274
323
|
};
|
|
275
|
-
report("waiting", "unknown");
|
|
276
|
-
|
|
277
|
-
const result = await withQueue(absolutePath, async () => {
|
|
324
|
+
progress.report("waiting", "unknown");
|
|
325
|
+
return withQueue(absolutePath, async () => {
|
|
278
326
|
try {
|
|
279
327
|
throwIfCancelled(signal);
|
|
280
328
|
} catch (error) {
|
|
281
|
-
|
|
282
|
-
throw error;
|
|
329
|
+
throw notRun(error, "cancelled");
|
|
283
330
|
}
|
|
284
331
|
let outcome: MutationOutcome<TDetails, TTool>;
|
|
285
332
|
try {
|
|
286
333
|
outcome = await mutate();
|
|
287
|
-
|
|
334
|
+
progress.mutationCompleted(outcome.details);
|
|
288
335
|
} catch (error) {
|
|
289
|
-
|
|
290
|
-
throw error;
|
|
336
|
+
throw notRun(error, "skipped");
|
|
291
337
|
}
|
|
292
338
|
|
|
293
339
|
const { publishedRevision } = outcome.commit;
|
|
294
|
-
report("waiting", "unknown");
|
|
295
|
-
const settle = (observation: FreshnessObservation, command
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
return finalizeMutation(
|
|
299
|
-
tool,
|
|
300
|
-
displayPath,
|
|
340
|
+
progress.report("waiting", "unknown");
|
|
341
|
+
const settle = (observation: FreshnessObservation, command: CommandFacts) => {
|
|
342
|
+
progress.report(command.status, observation.freshness);
|
|
343
|
+
return {
|
|
301
344
|
outcome,
|
|
302
345
|
observation,
|
|
303
|
-
command
|
|
304
|
-
|
|
305
|
-
);
|
|
346
|
+
command: { ...command, progressError: progress.failure() },
|
|
347
|
+
};
|
|
306
348
|
};
|
|
307
|
-
if (thenRun === undefined) return settle(commitFreshness(outcome.commit));
|
|
308
349
|
|
|
309
350
|
// A completed mutation remains successful; the command is only started on a fresh target.
|
|
310
351
|
const before = await observeFreshness(absolutePath, publishedRevision, true);
|
|
311
352
|
if (signal?.aborted) return settle(before, { status: "cancelled" });
|
|
312
353
|
if (before.freshness !== "unchanged") return settle(before, { status: "skipped" });
|
|
313
354
|
|
|
314
|
-
report("running", "unchanged");
|
|
355
|
+
progress.report("running", "unchanged");
|
|
315
356
|
let command: CommandOutcome;
|
|
316
|
-
// The executor owns the heartbeat lifetime; Pi Bash owns timeout and process cleanup.
|
|
317
|
-
let heartbeat: ReturnType<typeof setInterval> | undefined;
|
|
318
357
|
try {
|
|
319
|
-
command = await
|
|
320
|
-
// Pi Bash emits an initial update even for silent commands. Start its
|
|
321
|
-
// countdown here, after session permission hooks have allowed execution.
|
|
322
|
-
if (!commandTiming && thenRun.timeout !== undefined) {
|
|
323
|
-
commandTiming = {
|
|
324
|
-
timeoutSeconds: thenRun.timeout,
|
|
325
|
-
deadlineMs: Date.now() + thenRun.timeout * MILLISECONDS_PER_SECOND,
|
|
326
|
-
};
|
|
327
|
-
if (onProgress || onUpdate) {
|
|
328
|
-
heartbeat = setInterval(() => report("running", "unknown"), MILLISECONDS_PER_SECOND);
|
|
329
|
-
heartbeat.unref();
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
commandResult = { content: partial.content, details: partial.details };
|
|
333
|
-
report("running", "unknown");
|
|
334
|
-
});
|
|
358
|
+
command = await runCommand(thenRun, signal, ctx, progress.followCommand);
|
|
335
359
|
} catch (error) {
|
|
336
360
|
command = {
|
|
337
361
|
status: signal?.aborted ? "cancelled" : "failed",
|
|
338
362
|
result: { content: [{ type: "text", text: errorMessage(error) }] },
|
|
339
363
|
};
|
|
340
364
|
} finally {
|
|
341
|
-
|
|
365
|
+
progress.stopHeartbeat();
|
|
342
366
|
}
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
return settle(await observeFreshness(absolutePath, publishedRevision), {
|
|
367
|
+
progress.commandSettled(command.result);
|
|
368
|
+
const settled = settle(await observeFreshness(absolutePath, publishedRevision), {
|
|
346
369
|
status: command.status,
|
|
347
370
|
result: command.result,
|
|
348
371
|
});
|
|
372
|
+
return command.terminate === undefined
|
|
373
|
+
? settled
|
|
374
|
+
: { ...settled, terminate: command.terminate };
|
|
349
375
|
}).catch((error: unknown) => {
|
|
350
376
|
// Failures before the mutation started (such as resolving the queue key) also skip the command.
|
|
351
|
-
if (
|
|
377
|
+
if (error instanceof CommandNotRun) throw error;
|
|
352
378
|
throw notRun(error, "skipped");
|
|
353
379
|
});
|
|
354
|
-
return terminate === undefined ? result : { ...result, terminate };
|
|
355
380
|
};
|
|
356
381
|
}
|
|
@@ -10,22 +10,22 @@ import {
|
|
|
10
10
|
plainRow,
|
|
11
11
|
} from "./anchor-format.ts";
|
|
12
12
|
|
|
13
|
+
function token(line: number, content: string, hashLen: number): string {
|
|
14
|
+
return createAnchorFormatter(hashLen).reference(line, computeLineHash(line, content, hashLen));
|
|
15
|
+
}
|
|
16
|
+
|
|
13
17
|
test("anchor formatter binds the supplied hash length and hashes undisplayed content", () => {
|
|
14
18
|
const formatter = createAnchorFormatter(6);
|
|
15
|
-
const shortFormatter = createAnchorFormatter(4);
|
|
16
19
|
|
|
17
|
-
assert.equal(
|
|
20
|
+
assert.equal(token(3, "full content", 6), `3#${computeLineHash(3, "full content", 6)}`);
|
|
18
21
|
assert.equal(formatter.reference(3, "ABCDEF"), "3#ABCDEF");
|
|
19
|
-
assert.match(
|
|
20
|
-
assert.doesNotMatch(
|
|
22
|
+
assert.match(token(3, "full content", 6), new RegExp(anchorPattern(6)));
|
|
23
|
+
assert.doesNotMatch(token(3, "full content", 6), new RegExp(anchorPattern(4)));
|
|
21
24
|
assert.equal(
|
|
22
25
|
formatter.row(3, "full content", "full…"),
|
|
23
26
|
`3#${computeLineHash(3, "full content", 6)}│full…`,
|
|
24
27
|
);
|
|
25
|
-
assert.equal(
|
|
26
|
-
shortFormatter.token(3, "full content"),
|
|
27
|
-
`3#${computeLineHash(3, "full content", 4)}`,
|
|
28
|
-
);
|
|
28
|
+
assert.equal(token(3, "full content", 4), `3#${computeLineHash(3, "full content", 4)}`);
|
|
29
29
|
});
|
|
30
30
|
|
|
31
31
|
test("anchor tokens parse at any hash length so wrong lengths can be explained", () => {
|
|
@@ -38,7 +38,7 @@ test("anchor tokens parse at any hash length so wrong lengths can be explained",
|
|
|
38
38
|
test("anchor rows expose carriage returns while checksums retain source content", () => {
|
|
39
39
|
const formatter = createAnchorFormatter(4);
|
|
40
40
|
assert.equal(formatter.row(1, "a\rb"), `1#${computeLineHash(1, "a\rb", 4)}│a␍b`);
|
|
41
|
-
assert.notEqual(
|
|
41
|
+
assert.notEqual(token(1, "a\rb", 4), token(1, "a␍b", 4));
|
|
42
42
|
});
|
|
43
43
|
|
|
44
44
|
test("anchor syntax rejects characters absent from the checksum alphabet", () => {
|
package/src/pi/anchor-format.ts
CHANGED
|
@@ -9,8 +9,10 @@
|
|
|
9
9
|
|
|
10
10
|
import { computeLineHash, HASH_ALPHABET, HASH_LEN_MIN, HASH_LEN_MAX } from "../core/hash.ts";
|
|
11
11
|
|
|
12
|
+
const LINE_NUMBER = "([1-9][0-9]*)";
|
|
13
|
+
|
|
12
14
|
function anchorSource(hashQuantifier: string): string {
|
|
13
|
-
return
|
|
15
|
+
return `${LINE_NUMBER}#([${HASH_ALPHABET}]${hashQuantifier})`;
|
|
14
16
|
}
|
|
15
17
|
|
|
16
18
|
/** Schema pattern for a `LINE#HASH` anchor whose hash has exactly `hashLen` characters. */
|
|
@@ -32,7 +34,7 @@ const HASHLINE_ROW = new RegExp(
|
|
|
32
34
|
/** Split a `LINE#HASH` token of any hash length; undefined when the shape is wrong. */
|
|
33
35
|
export function parseAnchorToken(value: string): { line: number; hash: string } | undefined {
|
|
34
36
|
const match = ANCHOR_TOKEN.exec(value);
|
|
35
|
-
return match ? { line: Number(match[1]), hash: match[2]
|
|
37
|
+
return match ? { line: Number(match[1]), hash: match[2] } : undefined;
|
|
36
38
|
}
|
|
37
39
|
|
|
38
40
|
interface HashlineRow {
|
|
@@ -48,7 +50,7 @@ export function parseHashline(line: string): HashlineRow | null {
|
|
|
48
50
|
return match ? { lineNo: match[1], content: match[3] } : null;
|
|
49
51
|
}
|
|
50
52
|
|
|
51
|
-
const PLAIN_ROW = new RegExp(
|
|
53
|
+
const PLAIN_ROW = new RegExp(`^${LINE_NUMBER}${ROW_SEPARATOR}(.*)$`, "s");
|
|
52
54
|
|
|
53
55
|
/** Parse an anchored row or a non-editable `LINE│content` row; null for other text. */
|
|
54
56
|
export function parseDisplayRow(line: string): HashlineRow | null {
|
|
@@ -61,7 +63,6 @@ export function parseDisplayRow(line: string): HashlineRow | null {
|
|
|
61
63
|
/** Anchor serialization bound to a caller-supplied hash length. */
|
|
62
64
|
export interface AnchorFormatter {
|
|
63
65
|
reference(line: number, hash: string): string;
|
|
64
|
-
token(line: number, content: string): string;
|
|
65
66
|
row(line: number, content: string, displayContent?: string): string;
|
|
66
67
|
}
|
|
67
68
|
|
|
@@ -77,12 +78,9 @@ export function plainRow(line: number, displayContent: string): string {
|
|
|
77
78
|
|
|
78
79
|
export function createAnchorFormatter(hashLen: number): AnchorFormatter {
|
|
79
80
|
const reference = (line: number, hash: string) => `${line}#${hash}`;
|
|
80
|
-
const token = (line: number, content: string) =>
|
|
81
|
-
reference(line, computeLineHash(line, content, hashLen));
|
|
82
81
|
return {
|
|
83
|
-
token,
|
|
84
82
|
reference,
|
|
85
83
|
row: (line, content, displayContent = content) =>
|
|
86
|
-
`${
|
|
84
|
+
`${reference(line, computeLineHash(line, content, hashLen))}${ROW_SEPARATOR}${displayCarriageReturns(displayContent)}`,
|
|
87
85
|
};
|
|
88
86
|
}
|
|
@@ -61,19 +61,6 @@ function projectValueSchema(
|
|
|
61
61
|
projection.applicable.add(path);
|
|
62
62
|
return Type.Unknown({ enum: [...new Set(choices)] });
|
|
63
63
|
}
|
|
64
|
-
const typed = schema.anyOf.filter((branch) => "type" in branch);
|
|
65
|
-
if (typed.length === schema.anyOf.length) {
|
|
66
|
-
const matches = typed.filter(
|
|
67
|
-
(branch) => "type" in branch && Value.Check(Type.Unknown({ type: branch.type }), value),
|
|
68
|
-
);
|
|
69
|
-
if (matches.length === 1) return projectSchema(matches[0], value, path, projection);
|
|
70
|
-
if (matches.length === 0) {
|
|
71
|
-
const types = typed.flatMap((branch) =>
|
|
72
|
-
"type" in branch ? (Array.isArray(branch.type) ? branch.type : [branch.type]) : [],
|
|
73
|
-
);
|
|
74
|
-
return Type.Unknown({ type: [...new Set(types)] });
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
64
|
return schema;
|
|
78
65
|
}
|
|
79
66
|
if ("type" in schema && !Value.Check(Type.Unknown({ type: schema.type }), value)) return schema;
|
|
@@ -119,14 +106,15 @@ function pointerParts(pointer: string): readonly string[] {
|
|
|
119
106
|
}
|
|
120
107
|
|
|
121
108
|
/**
|
|
122
|
-
* The projection
|
|
123
|
-
* `~` in property names unescaped, so a name spans the fewest segments that form
|
|
124
|
-
* read escaped or as is.
|
|
109
|
+
* The projection paths of the value at `pointer` and of its parent; the root is "". Pi's TypeBox
|
|
110
|
+
* leaves `/` and `~` in property names unescaped, so a name spans the fewest segments that form
|
|
111
|
+
* an own key, read escaped or as is.
|
|
125
112
|
*/
|
|
126
|
-
function
|
|
113
|
+
function valuePaths(pointer: string, prepared: unknown): { path: string; parent: string } {
|
|
127
114
|
const segments = pointer.split("/").slice(1);
|
|
128
115
|
let value = prepared;
|
|
129
116
|
let path = "";
|
|
117
|
+
let parent = "";
|
|
130
118
|
for (let index = 0; index < segments.length; index++) {
|
|
131
119
|
let part = unescapePointer(segments[index]);
|
|
132
120
|
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
|
|
@@ -141,14 +129,15 @@ function valuePath(pointer: string, prepared: unknown): string {
|
|
|
141
129
|
}
|
|
142
130
|
}
|
|
143
131
|
}
|
|
132
|
+
parent = path;
|
|
144
133
|
path = Array.isArray(value) ? `${path}[${part}]` : propertyPath(path, part);
|
|
145
134
|
value = typeof value === "object" && value !== null ? Reflect.get(value, part) : undefined;
|
|
146
135
|
}
|
|
147
|
-
return path;
|
|
136
|
+
return { path, parent };
|
|
148
137
|
}
|
|
149
138
|
|
|
150
139
|
function fieldPath(pointer: string, prepared: unknown, key?: string): string {
|
|
151
|
-
const path =
|
|
140
|
+
const { path } = valuePaths(pointer, prepared);
|
|
152
141
|
return (key === undefined ? path : propertyPath(path, key)) || "$";
|
|
153
142
|
}
|
|
154
143
|
|
|
@@ -181,8 +170,8 @@ function fieldExplanation(schema: TSchema, parts: readonly string[]): string | u
|
|
|
181
170
|
}
|
|
182
171
|
|
|
183
172
|
/** Why a field is not allowed: the fields its object declares. */
|
|
184
|
-
function shapeExplanation(object: TObject): string {
|
|
185
|
-
return `Accepted fields: ${Object.keys(object.properties).join(", ")}.`;
|
|
173
|
+
function shapeExplanation(object: TObject | undefined): string | undefined {
|
|
174
|
+
return object && `Accepted fields: ${Object.keys(object.properties).join(", ")}.`;
|
|
186
175
|
}
|
|
187
176
|
|
|
188
177
|
/** One issue per field: distinct reasons joined, and distinct fixes joined, each in report order. */
|
|
@@ -203,9 +192,9 @@ function combineIssues(issues: readonly ArgumentIssue[]): readonly ArgumentIssue
|
|
|
203
192
|
|
|
204
193
|
/**
|
|
205
194
|
* One issue per native error. Reasons that do not say how to correct the value
|
|
206
|
-
* carry a fix derived from the declared schema: a missing field
|
|
207
|
-
* mismatch
|
|
208
|
-
* object's declared fields.
|
|
195
|
+
* carry a fix derived from the declared schema: a missing field, a pattern
|
|
196
|
+
* mismatch, and a value outside the field's choices explain the field, and a
|
|
197
|
+
* field that is not allowed lists its object's declared fields.
|
|
209
198
|
*/
|
|
210
199
|
function aggregateErrors(
|
|
211
200
|
errors: readonly TLocalizedValidationError[],
|
|
@@ -229,8 +218,8 @@ function aggregateErrors(
|
|
|
229
218
|
break;
|
|
230
219
|
}
|
|
231
220
|
case "additionalProperties": {
|
|
232
|
-
const
|
|
233
|
-
const fix =
|
|
221
|
+
const { path } = valuePaths(error.instancePath, prepared);
|
|
222
|
+
const fix = shapeExplanation(objects.get(path));
|
|
234
223
|
for (const key of error.params.additionalProperties)
|
|
235
224
|
add(fieldPath(error.instancePath, prepared, key), "is not allowed", fix);
|
|
236
225
|
break;
|
|
@@ -242,13 +231,21 @@ function aggregateErrors(
|
|
|
242
231
|
fieldExplanation(parameters, pointerParts(error.instancePath)),
|
|
243
232
|
);
|
|
244
233
|
break;
|
|
245
|
-
case "boolean":
|
|
246
|
-
|
|
234
|
+
case "boolean": {
|
|
235
|
+
// Once TypeBox's error capacity ends before `additionalProperties`, this is the only report.
|
|
236
|
+
const { parent } = valuePaths(error.instancePath, prepared);
|
|
237
|
+
add(
|
|
238
|
+
fieldPath(error.instancePath, prepared),
|
|
239
|
+
"is not allowed",
|
|
240
|
+
shapeExplanation(objects.get(parent)),
|
|
241
|
+
);
|
|
247
242
|
break;
|
|
243
|
+
}
|
|
248
244
|
case "enum":
|
|
249
245
|
add(
|
|
250
246
|
fieldPath(error.instancePath, prepared),
|
|
251
247
|
`expected one of: ${error.params.allowedValues.map((value) => JSON.stringify(value)).join(", ")}`,
|
|
248
|
+
fieldExplanation(parameters, pointerParts(error.instancePath)),
|
|
252
249
|
);
|
|
253
250
|
break;
|
|
254
251
|
default:
|