@criogaid/pi-hashline-edit 0.13.0 → 0.15.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 +18 -12
- package/README.zh-CN.md +18 -12
- package/package.json +8 -1
- package/src/core/AGENTS.md +3 -1
- package/src/core/apply.ts +110 -117
- package/src/core/character-set.ts +2 -3
- package/src/core/copy-span.ts +15 -0
- package/src/core/errors.ts +24 -9
- package/src/core/lines.ts +71 -17
- package/src/core/ranges.ts +5 -4
- package/src/core/replace-schema.ts +3 -1
- package/src/core/replace.ts +50 -29
- package/src/core/search-analysis.ts +21 -22
- package/src/core/search.ts +15 -32
- package/src/core/types.ts +3 -0
- package/src/index.ts +47 -39
- package/src/pi/AGENTS.md +30 -19
- package/src/pi/action-fusion.ts +284 -211
- package/src/pi/argument-diagnostics.ts +50 -37
- package/src/pi/argument-error.ts +2 -2
- package/src/pi/argument-validation.ts +163 -66
- package/src/pi/budgets.ts +12 -0
- package/src/pi/diagnostic-buffer.ts +12 -11
- package/src/pi/edit-tool.ts +138 -115
- package/src/pi/error-text.ts +10 -2
- package/src/pi/failure-context.ts +24 -37
- package/src/pi/file-commit.ts +131 -164
- package/src/pi/file-read.ts +122 -31
- package/src/pi/fusion-arguments.ts +214 -0
- package/src/pi/fusion-card.ts +102 -60
- package/src/pi/grep-candidates.ts +35 -22
- package/src/pi/grep-output.ts +197 -190
- package/src/pi/grep-render.ts +22 -13
- package/src/pi/grep-reread.ts +7 -6
- package/src/pi/grep-scope.ts +31 -16
- package/src/pi/grep-search.ts +56 -47
- package/src/pi/grep-tool.ts +35 -33
- package/src/pi/grep-worker.ts +3 -4
- package/src/pi/mutation-diff.ts +238 -0
- package/src/pi/mutation-result.ts +102 -79
- package/src/pi/mutation-runner.ts +107 -84
- package/src/pi/native-bash.ts +41 -0
- package/src/pi/path.ts +59 -6
- package/src/pi/read-tool.ts +173 -138
- package/src/pi/regex-worker.ts +14 -8
- package/src/pi/render.ts +101 -54
- package/src/pi/replace-regex.ts +1 -1
- package/src/pi/replace-tool.ts +14 -7
- package/src/pi/report-cause.ts +34 -17
- package/src/pi/report-schema.ts +184 -85
- package/src/pi/report.ts +133 -64
- package/src/pi/rg-process.ts +68 -48
- package/src/pi/schema.ts +4 -0
- package/src/pi/text-stream.ts +81 -87
- package/src/pi/workspace-cwd.js +2 -0
- package/src/pi/workspace.ts +46 -0
- package/src/pi/write-tool.ts +19 -13
- package/src/core/apply.test.ts +0 -644
- package/src/core/case-fold.test.ts +0 -35
- package/src/core/character-set.test.ts +0 -97
- package/src/core/errors.test.ts +0 -39
- package/src/core/hash.test.ts +0 -64
- package/src/core/lines.test.ts +0 -63
- package/src/core/ranges.test.ts +0 -123
- package/src/core/replace.test.ts +0 -187
- package/src/core/search-analysis.test.ts +0 -210
- package/src/core/search-matrix.test.ts +0 -64
- package/src/core/search-matrix.testing.ts +0 -171
- package/src/core/search.test.ts +0 -132
- package/src/core/text.test.ts +0 -52
- package/src/integration/config-registration.test.ts +0 -291
- package/src/integration/fusion-dispatch.test.ts +0 -320
- package/src/integration/grep-errors.test.ts +0 -81
- package/src/integration/grep-flags.test.ts +0 -76
- package/src/integration/grep-js-completeness.test.ts +0 -278
- package/src/integration/grep-line-candidates.test.ts +0 -201
- package/src/integration/grep-matrix.test.ts +0 -118
- package/src/integration/grep-order.test.ts +0 -78
- package/src/integration/grep-path-matrix.test.ts +0 -128
- package/src/integration/grep-prefilter-coverage.test.ts +0 -204
- package/src/integration/grep-process-limits.test.ts +0 -122
- package/src/integration/grep-regex.test.ts +0 -412
- package/src/integration/grep-rg.test.ts +0 -1659
- package/src/integration/grep-scan-budget.test.ts +0 -111
- package/src/integration/grep-translation.test.ts +0 -199
- package/src/integration/large-text.test.ts +0 -70
- package/src/integration/model-budget-lifecycle.test.ts +0 -186
- package/src/integration/mutation-file-types.test.ts +0 -30
- package/src/integration/mutation-file-types.testing.ts +0 -33
- package/src/integration/npm-package.test.ts +0 -19
- package/src/integration/npm-package.testing.ts +0 -243
- package/src/integration/publication-read-changes.test.ts +0 -454
- package/src/integration/read-changes.test.ts +0 -98
- package/src/integration/replace-package.test.ts +0 -22
- package/src/integration/replace-package.testing.ts +0 -36
- package/src/integration/replace-worker-boundary.test.ts +0 -127
- package/src/integration/report-replay.test.ts +0 -91
- package/src/integration/utf8-errors.test.ts +0 -46
- package/src/pi/action-fusion.test.ts +0 -659
- package/src/pi/action-fusion.testing.ts +0 -38
- package/src/pi/anchor-format.test.ts +0 -124
- package/src/pi/argument-error.testing.ts +0 -46
- package/src/pi/argument-format.test.ts +0 -196
- package/src/pi/argument-validation.test.ts +0 -1007
- package/src/pi/codemode.test.ts +0 -101
- package/src/pi/config.test.ts +0 -204
- package/src/pi/diagnostic-buffer.test.ts +0 -115
- package/src/pi/directory-sync.test.ts +0 -57
- package/src/pi/execute.test.ts +0 -1257
- package/src/pi/extension-loading.test.ts +0 -14
- package/src/pi/extension-loading.testing.ts +0 -3
- package/src/pi/failure-context.test.ts +0 -370
- package/src/pi/failure-path.test.ts +0 -289
- package/src/pi/file-commit.test.ts +0 -628
- package/src/pi/file-read.test.ts +0 -29
- package/src/pi/file-snapshot.test.ts +0 -22
- package/src/pi/fusion-card-interaction.test.ts +0 -143
- package/src/pi/fusion-card.test.ts +0 -353
- package/src/pi/grep-candidates.test.ts +0 -26
- package/src/pi/grep-matrix.test.ts +0 -68
- package/src/pi/grep-order.test.ts +0 -447
- package/src/pi/grep-output.testing.ts +0 -24
- package/src/pi/grep-rg.testing.ts +0 -73
- package/src/pi/grep.test.ts +0 -1670
- package/src/pi/model-budgets.test.ts +0 -96
- package/src/pi/mutation-outcome.testing.ts +0 -20
- package/src/pi/mutation-result.test.ts +0 -96
- package/src/pi/output-budgets.test.ts +0 -221
- package/src/pi/pi.test.ts +0 -158
- package/src/pi/read-delegation.test.ts +0 -119
- package/src/pi/read.test.ts +0 -735
- package/src/pi/regex-worker.test.ts +0 -42
- package/src/pi/registration.test.ts +0 -549
- package/src/pi/render.test.ts +0 -841
- package/src/pi/replace.test.ts +0 -634
- package/src/pi/report-failure.testing.ts +0 -27
- package/src/pi/report.test.ts +0 -533
- package/src/pi/result-safety.test.ts +0 -597
- package/src/pi/rg-process.test.ts +0 -133
- package/src/pi/rg-regex.test.ts +0 -40
- package/src/pi/text-stream.test.ts +0 -281
- package/src/pi/tool-call.testing.ts +0 -61
- package/src/pi/tool-factories.testing.ts +0 -59
- package/src/pi/write.test.ts +0 -256
- package/src/testing/extension-loader.testing.ts +0 -24
- package/src/testing/installation.testing.ts +0 -77
- package/src/testing/process.testing.ts +0 -33
- package/src/testing/regex-host.testing.ts +0 -20
- package/src/testing/regex-translation-corpus.ts +0 -267
- package/src/testing/rg-line-listing.fixture.mjs +0 -7
- package/src/testing/run-tests.ts +0 -47
- package/src/testing/session.testing.ts +0 -127
package/src/pi/action-fusion.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* - Pi's `withFileMutationQueue` (entered by the mutation runner) serializes
|
|
6
6
|
* the read-modify-write itself and is shared with every tool that uses it.
|
|
7
7
|
* It is released as soon as the file is published.
|
|
8
|
-
* - The
|
|
8
|
+
* - The scheduler's own queue wraps mutation, freshness check, and command, so
|
|
9
9
|
* a later fused call on the same file waits until this command finishes and
|
|
10
10
|
* cannot change the revision the command started from. Its key resolves the nearest
|
|
11
11
|
* existing ancestor and folds case on Windows, so it is never looser than
|
|
@@ -22,34 +22,38 @@
|
|
|
22
22
|
*/
|
|
23
23
|
|
|
24
24
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
25
|
+
import { addAbortListener } from "node:events";
|
|
25
26
|
import { realpath } from "node:fs/promises";
|
|
26
27
|
import { basename, dirname, resolve } from "node:path";
|
|
27
28
|
import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
|
|
28
|
-
import
|
|
29
|
-
import
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
29
|
+
import { contentText } from "@earendil-works/pi-ai";
|
|
30
|
+
import type {
|
|
31
|
+
BashToolCallEvent,
|
|
32
|
+
ExtensionToolContext,
|
|
33
|
+
ToolCallEvent,
|
|
34
|
+
} from "@earendil-works/pi-coding-agent";
|
|
35
|
+
import type { ThenRunInput } from "./fusion-arguments.ts";
|
|
36
|
+
import { MILLISECONDS_PER_SECOND, MAX_BASH_TIMEOUT_SECONDS } from "./fusion-arguments.ts";
|
|
37
|
+
import { observeFreshness, type FreshnessObservation } from "./file-commit.ts";
|
|
38
|
+
import { projectBashDetails } from "./fusion-card.ts";
|
|
39
|
+
import { snapshotBashOutput } from "./native-bash.ts";
|
|
40
|
+
import type {
|
|
41
|
+
CommandFacts,
|
|
42
|
+
MutationCommandFacts,
|
|
43
|
+
MutationResultDetails,
|
|
44
|
+
MutationScheduler,
|
|
37
45
|
} from "./mutation-result.ts";
|
|
38
|
-
import { errnoCode, errorMessage } from "../core/errors.ts";
|
|
39
|
-
import { throwIfCancelled } from "./error-text.ts";
|
|
46
|
+
import { errnoCode, errorMessage, HashlineError } from "../core/errors.ts";
|
|
47
|
+
import { cancellationError, throwIfCancelled } from "./error-text.ts";
|
|
48
|
+
import { Value } from "typebox/value";
|
|
49
|
+
import { COMMAND_IMAGE_SCHEMA } from "./report-schema.ts";
|
|
40
50
|
import type {
|
|
41
51
|
ActionFusionProgress,
|
|
42
52
|
CommandResult,
|
|
43
53
|
CommandStatus,
|
|
44
54
|
Freshness,
|
|
45
|
-
MutationToolName,
|
|
46
55
|
} from "./report-schema.ts";
|
|
47
56
|
|
|
48
|
-
const MILLISECONDS_PER_SECOND = 1_000;
|
|
49
|
-
|
|
50
|
-
// Pi's built-in Bash rejects timeouts above the setTimeout millisecond limit.
|
|
51
|
-
const MAX_BASH_TIMEOUT_SECONDS = 2_147_483_647 / MILLISECONDS_PER_SECOND;
|
|
52
|
-
|
|
53
57
|
// The one place the model is told when to use then_run; the tools' descriptions stay their own.
|
|
54
58
|
export const ACTION_FUSION_GUIDELINES = [
|
|
55
59
|
`Set then_run on edit, replace, or write for a check that can run right after that change. Use a separate bash call when the command requires approval, needs information from the tool's result, must wait for reload, or covers several changes; run that check once after all of them.${
|
|
@@ -62,93 +66,19 @@ export const ACTION_FUSION_GUIDELINES = [
|
|
|
62
66
|
|
|
63
67
|
type ProgressReporter = (progress: ActionFusionProgress) => void;
|
|
64
68
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
{
|
|
69
|
-
command: Type.String({ pattern: "\\S", description: "Bash command to run." }),
|
|
70
|
-
timeout: Type.Optional(
|
|
71
|
-
Type.Number({
|
|
72
|
-
exclusiveMinimum: 0,
|
|
73
|
-
maximum: MAX_BASH_TIMEOUT_SECONDS,
|
|
74
|
-
description: "Timeout in seconds; none when omitted.",
|
|
75
|
-
}),
|
|
76
|
-
),
|
|
77
|
-
},
|
|
78
|
-
{
|
|
79
|
-
description: `Command to run once after ${tool} succeeds; failure does not roll back the file.`,
|
|
80
|
-
additionalProperties: false,
|
|
81
|
-
},
|
|
82
|
-
),
|
|
83
|
-
);
|
|
69
|
+
interface BashCallScope {
|
|
70
|
+
readonly toolCallId: string;
|
|
71
|
+
input?: BashToolCallEvent["input"] | Record<string, unknown>;
|
|
84
72
|
}
|
|
85
73
|
|
|
86
|
-
|
|
87
|
-
export function withThenRunSchema<P extends TProperties>(
|
|
88
|
-
schema: TObject<P>,
|
|
89
|
-
tool: MutationToolName,
|
|
90
|
-
actionFusion: boolean,
|
|
91
|
-
): TObject<P> | TObject<P & { then_run: ReturnType<typeof createThenRunSchema> }> {
|
|
92
|
-
return actionFusion
|
|
93
|
-
? Type.Object(
|
|
94
|
-
{ ...schema.properties, then_run: createThenRunSchema(tool) },
|
|
95
|
-
{ additionalProperties: false },
|
|
96
|
-
)
|
|
97
|
-
: schema;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
export type ThenRunInput = NonNullable<Static<ReturnType<typeof createThenRunSchema>>>;
|
|
74
|
+
const bashCallScope = new AsyncLocalStorage<BashCallScope>();
|
|
101
75
|
|
|
102
|
-
/**
|
|
103
|
-
export
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
/** Preserve the session tool's request to stop after this tool batch. */
|
|
109
|
-
readonly terminate?: boolean;
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
/** Keep command state independent of its diagnostic text and of file publication. */
|
|
113
|
-
interface CommandOutcome {
|
|
114
|
-
readonly status: Exclude<CommandStatus, "skipped">;
|
|
115
|
-
readonly result: CommandResult;
|
|
116
|
-
/** Preserve the session tool's request to stop after this tool batch. */
|
|
117
|
-
readonly terminate?: boolean;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
async function runCommand(
|
|
121
|
-
input: ThenRunInput,
|
|
122
|
-
signal: AbortSignal | undefined,
|
|
123
|
-
ctx: ExtensionToolContext,
|
|
124
|
-
onUpdate: AgentToolUpdateCallback<unknown>,
|
|
125
|
-
): Promise<CommandOutcome> {
|
|
126
|
-
// Use the session's callable Bash, including overrides, validation, permission
|
|
127
|
-
// hooks and tool_result hooks. Tool failures resolve with isError, not rejection.
|
|
128
|
-
const { result, isError } = await ctx.executeTool("bash", input, { signal, onUpdate });
|
|
129
|
-
const command = {
|
|
130
|
-
terminate: result.terminate,
|
|
131
|
-
result: { content: result.content, details: result.details },
|
|
132
|
-
};
|
|
133
|
-
if (!isError) return { status: "succeeded", ...command };
|
|
134
|
-
if (signal?.aborted) return { status: "cancelled", ...command };
|
|
135
|
-
|
|
136
|
-
const structured = result.structuredContent;
|
|
137
|
-
const hasExitCode =
|
|
138
|
-
structured !== null &&
|
|
139
|
-
typeof structured === "object" &&
|
|
140
|
-
"exit_code" in structured &&
|
|
141
|
-
typeof structured.exit_code === "number";
|
|
142
|
-
// Pi's Bash supplies exit_code for ordinary exits, but serializes a thrown
|
|
143
|
-
// timeout as text. Only recognize its final diagnostic for the requested
|
|
144
|
-
// timeout; a failed command's output may itself mention or quote a timeout.
|
|
145
|
-
const timeoutDiagnostic = `Command timed out after ${input.timeout} seconds`;
|
|
146
|
-
const output = commandText(result.content);
|
|
147
|
-
const timedOut =
|
|
148
|
-
!hasExitCode &&
|
|
149
|
-
input.timeout !== undefined &&
|
|
150
|
-
(output === timeoutDiagnostic || output.endsWith(`\n${timeoutDiagnostic}`));
|
|
151
|
-
return { status: timedOut ? "timeout" : "failed", ...command };
|
|
76
|
+
/** Retain the args Pi shares with the remaining permission hooks and the nested Bash call. */
|
|
77
|
+
export function observeFusionToolCall(event: ToolCallEvent): void {
|
|
78
|
+
const scope = bashCallScope.getStore();
|
|
79
|
+
if (scope && event.parentToolCallId === scope.toolCallId && event.toolName === "bash") {
|
|
80
|
+
scope.input = event.input;
|
|
81
|
+
}
|
|
152
82
|
}
|
|
153
83
|
|
|
154
84
|
async function canonicalQueueKey(path: string): Promise<string> {
|
|
@@ -170,44 +100,98 @@ async function canonicalQueueKey(path: string): Promise<string> {
|
|
|
170
100
|
}
|
|
171
101
|
}
|
|
172
102
|
|
|
103
|
+
function bashTimeoutSeconds(timeout: unknown): number | undefined {
|
|
104
|
+
if (typeof timeout === "number" && timeout > 0 && timeout <= MAX_BASH_TIMEOUT_SECONDS)
|
|
105
|
+
return timeout;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Session listeners can replace array methods and block properties. Read indexed values once. */
|
|
109
|
+
function snapshotOutput(
|
|
110
|
+
source: CommandResult["content"],
|
|
111
|
+
recordObserverFailure: (error: unknown) => void,
|
|
112
|
+
) {
|
|
113
|
+
const content: CommandResult["content"] = [];
|
|
114
|
+
const length = source.length;
|
|
115
|
+
for (let i = 0; i < length; i++) {
|
|
116
|
+
if (!(i in source)) continue;
|
|
117
|
+
const block = source[i];
|
|
118
|
+
const type = block.type;
|
|
119
|
+
if (type === "text") {
|
|
120
|
+
const { text, textSignature } = block;
|
|
121
|
+
if (typeof text !== "string") throw new Error("Invalid then_run text block.");
|
|
122
|
+
content.push(
|
|
123
|
+
typeof textSignature === "string" ? { type, text, textSignature } : { type, text },
|
|
124
|
+
);
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (type !== "image") throw new Error("Invalid then_run content block type.");
|
|
128
|
+
try {
|
|
129
|
+
const image = { type, data: block.data, mimeType: block.mimeType };
|
|
130
|
+
if (!Value.Check(COMMAND_IMAGE_SCHEMA, image))
|
|
131
|
+
throw new Error("Invalid then_run image block.");
|
|
132
|
+
content.push(image);
|
|
133
|
+
} catch (error) {
|
|
134
|
+
recordObserverFailure(error);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return content;
|
|
138
|
+
}
|
|
139
|
+
|
|
173
140
|
/**
|
|
174
|
-
*
|
|
175
|
-
*
|
|
176
|
-
*
|
|
177
|
-
* process cleanup.
|
|
141
|
+
* Coordinates one session Bash call and its display. Display callbacks are observers.
|
|
142
|
+
* Their failures are kept for the report without affecting publication or execution.
|
|
143
|
+
* Fusion owns the heartbeat lifetime. Pi Bash owns timeout and process cleanup.
|
|
178
144
|
*/
|
|
179
|
-
function
|
|
145
|
+
function createBashCallCoordinator<TDetails extends object>({
|
|
180
146
|
toolCallId,
|
|
181
|
-
|
|
147
|
+
commandText,
|
|
182
148
|
onProgress,
|
|
183
149
|
onUpdate,
|
|
150
|
+
recordCommand,
|
|
184
151
|
}: {
|
|
185
152
|
toolCallId: string;
|
|
186
|
-
|
|
153
|
+
commandText: string;
|
|
187
154
|
onProgress: ProgressReporter;
|
|
188
|
-
onUpdate: AgentToolUpdateCallback<MutationResultDetails<TDetails
|
|
155
|
+
onUpdate: AgentToolUpdateCallback<MutationResultDetails<TDetails>>;
|
|
156
|
+
recordCommand: (facts: MutationCommandFacts) => void;
|
|
189
157
|
}) {
|
|
158
|
+
const bashCall: BashCallScope = { toolCallId };
|
|
190
159
|
let mutationDetails: TDetails | undefined;
|
|
191
|
-
let
|
|
160
|
+
let displayedCommand = commandText;
|
|
192
161
|
let commandResult: CommandResult | undefined;
|
|
193
|
-
let
|
|
194
|
-
let
|
|
162
|
+
let finalStatus: CommandStatus | undefined;
|
|
163
|
+
let launchTimeoutSeconds: number | undefined;
|
|
164
|
+
/** A command with a timeout counts down once Bash first reports, refreshed by its heartbeat. */
|
|
165
|
+
let countdown:
|
|
166
|
+
| {
|
|
167
|
+
readonly timeoutSeconds: number;
|
|
168
|
+
readonly deadlineMs: number;
|
|
169
|
+
readonly heartbeat: ReturnType<typeof setInterval>;
|
|
170
|
+
}
|
|
171
|
+
| undefined;
|
|
172
|
+
|
|
173
|
+
const recordObserverFailure = (error: unknown) => recordCommand({ progressFailure: { error } });
|
|
174
|
+
|
|
175
|
+
const recordStatus = (status: CommandStatus) => {
|
|
176
|
+
finalStatus = status;
|
|
177
|
+
recordCommand({ status });
|
|
178
|
+
};
|
|
195
179
|
|
|
196
180
|
const report = (command: ActionFusionProgress["command"], freshness: Freshness) => {
|
|
197
181
|
const progress: ActionFusionProgress = {
|
|
198
182
|
toolCallId,
|
|
199
|
-
commandText:
|
|
183
|
+
commandText: displayedCommand,
|
|
200
184
|
command,
|
|
201
185
|
freshness,
|
|
202
186
|
...(commandResult ? { result: commandResult } : {}),
|
|
203
187
|
mutationCompleted: mutationDetails !== undefined,
|
|
204
|
-
...(
|
|
188
|
+
...(countdown
|
|
205
189
|
? {
|
|
206
190
|
timing: {
|
|
207
|
-
timeoutSeconds:
|
|
191
|
+
timeoutSeconds: countdown.timeoutSeconds,
|
|
208
192
|
remainingSeconds: Math.max(
|
|
209
193
|
0,
|
|
210
|
-
Math.ceil((
|
|
194
|
+
Math.ceil((countdown.deadlineMs - Date.now()) / MILLISECONDS_PER_SECOND),
|
|
211
195
|
),
|
|
212
196
|
},
|
|
213
197
|
}
|
|
@@ -215,76 +199,174 @@ function createProgressTracker<TDetails extends object>({
|
|
|
215
199
|
};
|
|
216
200
|
for (const notify of [
|
|
217
201
|
() => onProgress(progress),
|
|
218
|
-
() => onUpdate
|
|
202
|
+
() => onUpdate({ content: [], details: { ...mutationDetails, actionFusion: progress } }),
|
|
219
203
|
]) {
|
|
220
204
|
try {
|
|
221
205
|
notify();
|
|
222
206
|
} catch (error) {
|
|
223
|
-
|
|
207
|
+
recordObserverFailure(error);
|
|
224
208
|
}
|
|
225
209
|
}
|
|
226
210
|
};
|
|
227
211
|
|
|
228
|
-
/** Follow the running command's partial results. */
|
|
229
212
|
const followCommand: AgentToolUpdateCallback<unknown> = (partial) => {
|
|
230
|
-
//
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
213
|
+
// Built-in Bash first updates at launch, after permission hooks and before result hooks.
|
|
214
|
+
if (bashCall.input) {
|
|
215
|
+
const { command, timeout } = bashCall.input;
|
|
216
|
+
delete bashCall.input;
|
|
217
|
+
if (typeof command === "string") displayedCommand = command;
|
|
218
|
+
launchTimeoutSeconds = bashTimeoutSeconds(timeout);
|
|
219
|
+
if (launchTimeoutSeconds !== undefined) {
|
|
220
|
+
const deadlineMs = Date.now() + launchTimeoutSeconds * MILLISECONDS_PER_SECOND;
|
|
221
|
+
const heartbeat = setInterval(() => report("running", "unknown"), MILLISECONDS_PER_SECOND);
|
|
222
|
+
heartbeat.unref();
|
|
223
|
+
countdown = { timeoutSeconds: launchTimeoutSeconds, deadlineMs, heartbeat };
|
|
224
|
+
}
|
|
239
225
|
}
|
|
240
226
|
commandResult = { content: partial.content, details: partial.details };
|
|
241
227
|
report("running", "unknown");
|
|
242
228
|
};
|
|
243
229
|
|
|
230
|
+
function failCommand(status: "failed" | "cancelled", message: string): CommandFacts {
|
|
231
|
+
recordStatus(status);
|
|
232
|
+
return snapshotCommand({ content: [{ type: "text", text: message }] }, status, undefined);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async function runCommand(
|
|
236
|
+
thenRun: ThenRunInput,
|
|
237
|
+
signal: AbortSignal,
|
|
238
|
+
ctx: ExtensionToolContext,
|
|
239
|
+
): Promise<CommandFacts> {
|
|
240
|
+
let completion;
|
|
241
|
+
let hookInput;
|
|
242
|
+
try {
|
|
243
|
+
completion = await bashCallScope.run(bashCall, () =>
|
|
244
|
+
ctx.executeTool("bash", thenRun, { onUpdate: followCommand }),
|
|
245
|
+
);
|
|
246
|
+
} catch (error) {
|
|
247
|
+
const status = signal.aborted ? "cancelled" : "failed";
|
|
248
|
+
return failCommand(status, errorMessage(error));
|
|
249
|
+
} finally {
|
|
250
|
+
hookInput = bashCall.input;
|
|
251
|
+
delete bashCall.input;
|
|
252
|
+
if (countdown) clearInterval(countdown.heartbeat);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
return readCompletion(completion, hookInput, signal);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function snapshotCommand(
|
|
259
|
+
result: CommandResult,
|
|
260
|
+
status: Exclude<CommandStatus, "skipped">,
|
|
261
|
+
structured: ReturnType<typeof snapshotBashOutput>["structured"],
|
|
262
|
+
content = snapshotOutput(result.content, recordObserverFailure),
|
|
263
|
+
): CommandFacts {
|
|
264
|
+
// Progress subscribers may mutate the card's blocks before the mutation is finalized.
|
|
265
|
+
commandResult = { content: content.map((block) => ({ ...block })) };
|
|
266
|
+
try {
|
|
267
|
+
const details = projectBashDetails(result.details);
|
|
268
|
+
if (details !== undefined) commandResult.details = details;
|
|
269
|
+
} catch (error) {
|
|
270
|
+
recordObserverFailure(error);
|
|
271
|
+
}
|
|
272
|
+
return { script: { status, ...structured }, content };
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function readCompletion(
|
|
276
|
+
{ result, isError, durationMs }: Awaited<ReturnType<ExtensionToolContext["executeTool"]>>,
|
|
277
|
+
hookInput: BashCallScope["input"],
|
|
278
|
+
signal: AbortSignal,
|
|
279
|
+
): CommandFacts {
|
|
280
|
+
// Keep a safe terminal card even if reading the final output fails.
|
|
281
|
+
commandResult = { content: [] };
|
|
282
|
+
if (!isError) recordStatus("succeeded");
|
|
283
|
+
const terminate = result.terminate;
|
|
284
|
+
if (typeof terminate === "boolean") recordCommand({ terminate });
|
|
285
|
+
const { exited, structured } = snapshotBashOutput(result, recordObserverFailure);
|
|
286
|
+
if (!isError) return snapshotCommand(result, "succeeded", structured);
|
|
287
|
+
|
|
288
|
+
const finishError = (
|
|
289
|
+
status: "failed" | "timeout" | "cancelled",
|
|
290
|
+
snapshot?: ReturnType<typeof snapshotOutput>,
|
|
291
|
+
): CommandFacts => {
|
|
292
|
+
recordStatus(status);
|
|
293
|
+
return snapshotCommand(result, status, structured, snapshot);
|
|
294
|
+
};
|
|
295
|
+
|
|
296
|
+
if (exited) return finishError("failed");
|
|
297
|
+
if (durationMs === undefined) {
|
|
298
|
+
if (!signal.aborted) return finishError("failed");
|
|
299
|
+
recordStatus("cancelled");
|
|
300
|
+
commandResult = undefined;
|
|
301
|
+
return { script: { status: "cancelled" }, content: [] };
|
|
302
|
+
}
|
|
303
|
+
const timeout = launchTimeoutSeconds ?? bashTimeoutSeconds(hookInput?.timeout);
|
|
304
|
+
if (timeout === undefined) return finishError(signal.aborted ? "cancelled" : "failed");
|
|
305
|
+
const snapshot = snapshotOutput(result.content, recordObserverFailure);
|
|
306
|
+
const text = contentText(snapshot);
|
|
307
|
+
const diagnostic = `Command timed out after ${timeout} seconds`;
|
|
308
|
+
if (text === diagnostic || text.endsWith(`\n${diagnostic}`))
|
|
309
|
+
return finishError("timeout", snapshot);
|
|
310
|
+
return finishError(signal.aborted ? "cancelled" : "failed", snapshot);
|
|
311
|
+
}
|
|
312
|
+
|
|
244
313
|
return {
|
|
245
314
|
report,
|
|
246
|
-
|
|
247
|
-
|
|
315
|
+
runCommand,
|
|
316
|
+
failCommand,
|
|
317
|
+
reportCompletion() {
|
|
318
|
+
if (finalStatus !== undefined) report(finalStatus, "unknown");
|
|
319
|
+
},
|
|
248
320
|
mutationCompleted(details: TDetails) {
|
|
249
321
|
mutationDetails = details;
|
|
250
322
|
},
|
|
251
|
-
stopHeartbeat() {
|
|
252
|
-
if (heartbeat) clearInterval(heartbeat);
|
|
253
|
-
},
|
|
254
|
-
commandSettled(result: CommandResult) {
|
|
255
|
-
commandResult = result;
|
|
256
|
-
},
|
|
257
323
|
};
|
|
258
324
|
}
|
|
259
325
|
|
|
260
|
-
|
|
326
|
+
/** The scheduler of mutation calls when Action Fusion is on, shared by every mutation tool. */
|
|
327
|
+
export function createActionFusionScheduler(onProgress: ProgressReporter): MutationScheduler {
|
|
261
328
|
const queueTails = new Map<string, Promise<void>>();
|
|
262
329
|
const commandScope = new AsyncLocalStorage<{ active: boolean }>();
|
|
263
330
|
|
|
264
|
-
async function withQueue<T>(
|
|
331
|
+
async function withQueue<T>(
|
|
332
|
+
path: string,
|
|
333
|
+
signal: AbortSignal,
|
|
334
|
+
work: () => Promise<T>,
|
|
335
|
+
): Promise<T> {
|
|
265
336
|
const key = await canonicalQueueKey(path);
|
|
266
|
-
const previous = queueTails.get(key)
|
|
267
|
-
if (
|
|
337
|
+
const previous = queueTails.get(key);
|
|
338
|
+
if (previous && commandScope.getStore()?.active) {
|
|
268
339
|
throw new Error(
|
|
269
340
|
"A then_run command cannot call a mutation tool for a target with a pending mutation.",
|
|
270
341
|
);
|
|
271
342
|
}
|
|
272
|
-
|
|
273
|
-
const
|
|
274
|
-
release = resolve;
|
|
275
|
-
});
|
|
276
|
-
const tail = previous.then(() => owned);
|
|
343
|
+
const owned = Promise.withResolvers<void>();
|
|
344
|
+
const tail = previous ? previous.then(() => owned.promise) : owned.promise;
|
|
277
345
|
queueTails.set(key, tail);
|
|
278
|
-
|
|
346
|
+
// A cancelled waiter releases its own turn, while its predecessor still owns the queue.
|
|
347
|
+
void tail.then(() => {
|
|
348
|
+
if (queueTails.get(key) === tail) queueTails.delete(key);
|
|
349
|
+
});
|
|
279
350
|
try {
|
|
351
|
+
if (previous) {
|
|
352
|
+
const cancelled = Promise.withResolvers<never>();
|
|
353
|
+
const subscription = addAbortListener(signal, () => cancelled.reject(cancellationError()));
|
|
354
|
+
try {
|
|
355
|
+
await Promise.race([previous, cancelled.promise]);
|
|
356
|
+
} finally {
|
|
357
|
+
subscription[Symbol.dispose]();
|
|
358
|
+
}
|
|
359
|
+
} else {
|
|
360
|
+
await previous;
|
|
361
|
+
}
|
|
362
|
+
throwIfCancelled(signal);
|
|
280
363
|
return await work();
|
|
281
364
|
} finally {
|
|
282
|
-
|
|
283
|
-
if (queueTails.get(key) === tail) queueTails.delete(key);
|
|
365
|
+
owned.resolve();
|
|
284
366
|
}
|
|
285
367
|
}
|
|
286
368
|
|
|
287
|
-
|
|
369
|
+
const schedule: MutationScheduler = async ({
|
|
288
370
|
toolCallId,
|
|
289
371
|
absolutePath,
|
|
290
372
|
thenRun,
|
|
@@ -292,94 +374,85 @@ export function createActionFusionExecutor(onProgress: ProgressReporter) {
|
|
|
292
374
|
signal,
|
|
293
375
|
ctx,
|
|
294
376
|
onUpdate,
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
absolutePath: string;
|
|
298
|
-
thenRun: ThenRunInput | undefined;
|
|
299
|
-
mutate: () => Promise<MutationOutcome<TDetails, TTool>>;
|
|
300
|
-
signal: AbortSignal | undefined;
|
|
301
|
-
ctx: ExtensionToolContext;
|
|
302
|
-
onUpdate?: AgentToolUpdateCallback<MutationResultDetails<TDetails>>;
|
|
303
|
-
}): Promise<FusedMutation<TDetails, TTool>> {
|
|
377
|
+
recordCommand,
|
|
378
|
+
}) => {
|
|
304
379
|
// 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
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
});
|
|
311
|
-
}
|
|
380
|
+
if (thenRun === undefined)
|
|
381
|
+
return withQueue(absolutePath, signal, async () => ({
|
|
382
|
+
kind: "alone" as const,
|
|
383
|
+
outcome: await mutate(),
|
|
384
|
+
}));
|
|
312
385
|
|
|
313
|
-
const progress =
|
|
386
|
+
const progress = createBashCallCoordinator({
|
|
314
387
|
toolCallId,
|
|
315
|
-
thenRun,
|
|
388
|
+
commandText: "command" in thenRun ? thenRun.command : thenRun.commandText,
|
|
316
389
|
onProgress,
|
|
317
390
|
onUpdate,
|
|
391
|
+
recordCommand,
|
|
318
392
|
});
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
progress.report(
|
|
322
|
-
return new CommandNotRun(error, command, progress.failure());
|
|
393
|
+
const notRun = (status: "skipped" | "cancelled") => {
|
|
394
|
+
recordCommand({ status });
|
|
395
|
+
progress.report(status, "unknown");
|
|
323
396
|
};
|
|
324
397
|
progress.report("waiting", "unknown");
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
outcome = await mutate();
|
|
334
|
-
progress.mutationCompleted(outcome.details);
|
|
335
|
-
} catch (error) {
|
|
336
|
-
throw notRun(error, "skipped");
|
|
337
|
-
}
|
|
398
|
+
let started = false;
|
|
399
|
+
return withQueue(absolutePath, signal, async () => {
|
|
400
|
+
started = true;
|
|
401
|
+
const outcome = await mutate().catch((error: unknown) => {
|
|
402
|
+
notRun("skipped");
|
|
403
|
+
throw error;
|
|
404
|
+
});
|
|
405
|
+
progress.mutationCompleted(outcome.details);
|
|
338
406
|
|
|
339
407
|
const { publishedRevision } = outcome.commit;
|
|
340
408
|
progress.report("waiting", "unknown");
|
|
341
409
|
const settle = (observation: FreshnessObservation, command: CommandFacts) => {
|
|
342
|
-
progress.report(command.status, observation.freshness);
|
|
410
|
+
progress.report(command.script.status, observation.freshness);
|
|
343
411
|
return {
|
|
412
|
+
kind: "fused" as const,
|
|
344
413
|
outcome,
|
|
345
414
|
observation,
|
|
346
|
-
command
|
|
415
|
+
command,
|
|
347
416
|
};
|
|
348
417
|
};
|
|
349
418
|
|
|
419
|
+
if ("error" in thenRun)
|
|
420
|
+
return settle(outcome.commit, progress.failCommand("failed", thenRun.error));
|
|
421
|
+
|
|
350
422
|
// A completed mutation remains successful; the command is only started on a fresh target.
|
|
351
|
-
const before = await observeFreshness(absolutePath, publishedRevision,
|
|
352
|
-
|
|
353
|
-
|
|
423
|
+
const before = await observeFreshness(absolutePath, publishedRevision, "before-command");
|
|
424
|
+
const beforeStatus = signal.aborted
|
|
425
|
+
? "cancelled"
|
|
426
|
+
: before.freshness !== "unchanged"
|
|
427
|
+
? "skipped"
|
|
428
|
+
: undefined;
|
|
429
|
+
if (beforeStatus !== undefined) {
|
|
430
|
+
recordCommand({ status: beforeStatus });
|
|
431
|
+
return settle(before, { script: { status: beforeStatus }, content: [] });
|
|
432
|
+
}
|
|
354
433
|
|
|
355
434
|
progress.report("running", "unchanged");
|
|
356
435
|
const scope = { active: true };
|
|
357
|
-
let command: CommandOutcome;
|
|
358
436
|
try {
|
|
359
|
-
command = await commandScope
|
|
360
|
-
runCommand(thenRun, signal, ctx
|
|
437
|
+
const command = await commandScope
|
|
438
|
+
.run(scope, () => progress.runCommand(thenRun, signal, ctx))
|
|
439
|
+
.finally(() => {
|
|
440
|
+
scope.active = false;
|
|
441
|
+
});
|
|
442
|
+
return settle(
|
|
443
|
+
await observeFreshness(absolutePath, publishedRevision, "after-command"),
|
|
444
|
+
command,
|
|
361
445
|
);
|
|
362
446
|
} catch (error) {
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
result: { content: [{ type: "text", text: errorMessage(error) }] },
|
|
366
|
-
};
|
|
367
|
-
} finally {
|
|
368
|
-
scope.active = false;
|
|
369
|
-
progress.stopHeartbeat();
|
|
447
|
+
progress.reportCompletion();
|
|
448
|
+
throw error;
|
|
370
449
|
}
|
|
371
|
-
progress.commandSettled(command.result);
|
|
372
|
-
const settled = settle(await observeFreshness(absolutePath, publishedRevision), {
|
|
373
|
-
status: command.status,
|
|
374
|
-
result: command.result,
|
|
375
|
-
});
|
|
376
|
-
return command.terminate === undefined
|
|
377
|
-
? settled
|
|
378
|
-
: { ...settled, terminate: command.terminate };
|
|
379
450
|
}).catch((error: unknown) => {
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
451
|
+
if (started) throw error;
|
|
452
|
+
const cancelled = error instanceof HashlineError && error.errorCode === "OPERATION_ABORTED";
|
|
453
|
+
notRun(cancelled ? "cancelled" : "skipped");
|
|
454
|
+
throw error;
|
|
383
455
|
});
|
|
384
456
|
};
|
|
457
|
+
return schedule;
|
|
385
458
|
}
|