@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/read-tool.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Override read: recognized images and NUL-containing files delegate to Pi's
|
|
3
|
-
* built-in read; other valid UTF-8 text
|
|
4
|
-
* `anchors: false`
|
|
3
|
+
* built-in read; other valid UTF-8 text is a header and anchored rows, or with
|
|
4
|
+
* `anchors: false` the lines alone.
|
|
5
5
|
*
|
|
6
6
|
* Hashes are computed from the current content on the fly — nothing is stored.
|
|
7
7
|
* The hash is `(line number, content)`, recomputed and checked at edit time, so
|
|
@@ -17,40 +17,57 @@ import {
|
|
|
17
17
|
detectSupportedImageMimeTypeFromFile,
|
|
18
18
|
getLanguageFromPath,
|
|
19
19
|
highlightCode,
|
|
20
|
-
type ReadToolInput,
|
|
21
20
|
type ReadToolDetails,
|
|
22
|
-
type ExtensionToolContext,
|
|
23
21
|
type Theme,
|
|
24
22
|
type ToolDefinition,
|
|
25
23
|
} from "@earendil-works/pi-coding-agent";
|
|
26
|
-
import type {
|
|
24
|
+
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
25
|
+
import type { ImageContent } from "@earendil-works/pi-ai";
|
|
27
26
|
import { Text } from "@earendil-works/pi-tui";
|
|
28
|
-
import { Type } from "typebox";
|
|
27
|
+
import { IsString, IsUnion, Type, type TSchema } from "typebox";
|
|
29
28
|
import { scanTextLines } from "./text-stream.ts";
|
|
30
29
|
import { createAnchorFormatter, displayCarriageReturns, parseHashline } from "./anchor-format.ts";
|
|
31
|
-
import {
|
|
30
|
+
import { serializePath } from "./path.ts";
|
|
32
31
|
import { renderToolError, reportLines, splitReport } from "./render.ts";
|
|
33
32
|
import { POSITIVE_SAFE_INTEGER, STRICT_SAMPLING } from "./schema.ts";
|
|
34
|
-
import { HashlineError
|
|
35
|
-
import {
|
|
33
|
+
import { HashlineError } from "../core/errors.ts";
|
|
34
|
+
import { requireRegularFile } from "./file-read.ts";
|
|
35
|
+
import { callSignal, throwIfCancelled } from "./error-text.ts";
|
|
36
36
|
import { reportResult, runTool, type ReportDetails } from "./report.ts";
|
|
37
|
+
import { SCRIPT_OUTPUT_SCHEMAS } from "./report-schema.ts";
|
|
37
38
|
import { formatByteSize } from "./budgets.ts";
|
|
38
39
|
import type { ToolEnvironment } from "./config.ts";
|
|
39
|
-
import {
|
|
40
|
+
import { createArgumentBoundary, noArgumentProduct } from "./argument-validation.ts";
|
|
40
41
|
|
|
41
42
|
const DEFAULT_OFFSET = 1;
|
|
42
43
|
|
|
43
|
-
/**
|
|
44
|
-
|
|
44
|
+
/**
|
|
45
|
+
* Pi's read details for a delegated native read; the report states this read's own facts.
|
|
46
|
+
* `header` is the header line of a read with `anchors: false`: the TUI shows it and the
|
|
47
|
+
* result text omits it.
|
|
48
|
+
*/
|
|
49
|
+
type ReadDetails = (ReadToolDetails & { nativeRead?: true; header?: string }) &
|
|
50
|
+
Partial<ReportDetails>;
|
|
45
51
|
|
|
46
|
-
|
|
47
|
-
type
|
|
52
|
+
// Pi's public factory erases the output type. Its toReadOutput emits only these variants.
|
|
53
|
+
type NativeReadOutput = string | (Pick<ImageContent, keyof ImageContent> & { note: string });
|
|
54
|
+
|
|
55
|
+
/** This read's output schema: its own text result, and each result of Pi's read other than plain text. */
|
|
56
|
+
function readOutputSchema(native: TSchema | undefined): TSchema {
|
|
57
|
+
const nativeVariants = native !== undefined && IsUnion(native) ? native.anyOf : [];
|
|
58
|
+
return Type.Union([
|
|
59
|
+
SCRIPT_OUTPUT_SCHEMAS.read,
|
|
60
|
+
...nativeVariants.filter((variant) => !IsString(variant)),
|
|
61
|
+
]);
|
|
62
|
+
}
|
|
48
63
|
|
|
49
64
|
/**
|
|
50
|
-
*
|
|
65
|
+
* Header line: `<path> · <N> line(s)`, optionally ` (from line <offset>)` and
|
|
51
66
|
* ` · no trailing newline`. A missing final newline is a byte-level fact the
|
|
52
67
|
* numbered rows cannot show, so the header, which the model never copies into an
|
|
53
|
-
* edit `lines`, states it.
|
|
68
|
+
* edit `lines`, states it. An anchored read's text starts with this line; a read with
|
|
69
|
+
* `anchors: false` carries it in `details`. READ_HEADER is the TUI's parser for this
|
|
70
|
+
* exact line.
|
|
54
71
|
*/
|
|
55
72
|
function formatReadHeader(
|
|
56
73
|
path: string,
|
|
@@ -59,9 +76,10 @@ function formatReadHeader(
|
|
|
59
76
|
finalNewline: boolean,
|
|
60
77
|
): string {
|
|
61
78
|
const shownFrom = start > DEFAULT_OFFSET ? ` (from line ${start})` : "";
|
|
62
|
-
|
|
79
|
+
const count = `${totalLines} line${totalLines === 1 ? "" : "s"}`;
|
|
80
|
+
return `${path} · ${count}${shownFrom}${finalNewline ? "" : " · no trailing newline"}`;
|
|
63
81
|
}
|
|
64
|
-
const READ_HEADER = /^(.+?) · (\d+ lines(?: \(from line \d
|
|
82
|
+
const READ_HEADER = /^(.+?) · ((\d+) lines?(?: \(from line (\d+)\))?(?: · no trailing newline)?)$/s;
|
|
65
83
|
|
|
66
84
|
/**
|
|
67
85
|
* Render the expanded read body for the TUI: color the header, strip the
|
|
@@ -72,70 +90,66 @@ const READ_HEADER = /^(.+?) · (\d+ lines(?: \(from line \d+\))?(?: · no traili
|
|
|
72
90
|
* line count diverges). Notices are report facts, rendered from the report.
|
|
73
91
|
*/
|
|
74
92
|
function renderReadBody(
|
|
75
|
-
|
|
93
|
+
text: string,
|
|
76
94
|
path: string,
|
|
77
|
-
|
|
78
|
-
lineTooLong:
|
|
95
|
+
plainHeader: string | undefined,
|
|
96
|
+
lineTooLong: string | undefined,
|
|
79
97
|
theme: Theme,
|
|
80
98
|
): string {
|
|
81
|
-
const
|
|
82
|
-
|
|
99
|
+
const plain = plainHeader !== undefined;
|
|
100
|
+
// Interpolation also coerces text supplied by result hooks for unanchored reads.
|
|
101
|
+
const lines = (plain ? `${plainHeader}\n${text}` : text).split("\n");
|
|
102
|
+
const header = READ_HEADER.exec(lines[0]);
|
|
103
|
+
const out = header ? [theme.fg("success", header[1]) + theme.fg("dim", ` · ${header[2]}`)] : [];
|
|
83
104
|
|
|
84
|
-
|
|
85
|
-
//
|
|
86
|
-
let bodyStart =
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
out.push(theme.fg("success", h[1]) + theme.fg("dim", ` · ${h[2]}`));
|
|
90
|
-
bodyStart = 1;
|
|
91
|
-
}
|
|
105
|
+
const firstLine = Number(header?.[4] ?? DEFAULT_OFFSET);
|
|
106
|
+
// Unanchored text cannot distinguish zero rows from one empty row. Use the read's metadata.
|
|
107
|
+
let bodyStart = Number(header !== null);
|
|
108
|
+
if (plain && (lineTooLong !== undefined || firstLine > Number(header?.[3] ?? 0)))
|
|
109
|
+
bodyStart = lines.length;
|
|
92
110
|
|
|
93
|
-
|
|
111
|
+
const parseRow = plain
|
|
112
|
+
? (content: string, index: number) => ({
|
|
113
|
+
lineNo: String(firstLine + index - bodyStart),
|
|
114
|
+
content,
|
|
115
|
+
})
|
|
116
|
+
: parseHashline;
|
|
94
117
|
const lineNos: string[] = [];
|
|
95
|
-
const
|
|
96
|
-
const firstLine = Number(/\(from line (\d+)\)/.exec(h?.[2] ?? "")?.[1] ?? DEFAULT_OFFSET);
|
|
97
|
-
const totalLines = Number(/^(\d+) lines/.exec(h?.[2] ?? "")?.[1] ?? 0);
|
|
98
|
-
// Unanchored rows carry no marker, so no rows and one empty row are the same text: a window
|
|
99
|
-
// past the last line or a first line over the byte limit shows no row.
|
|
100
|
-
if (!anchored && (lineTooLong || firstLine > totalLines)) bodyStart = lines.length;
|
|
118
|
+
const detabbed: string[] = [];
|
|
101
119
|
for (let i = bodyStart; i < lines.length; i++) {
|
|
102
|
-
const row =
|
|
103
|
-
? parseHashline(lines[i])
|
|
104
|
-
: { lineNo: String(firstLine + i - bodyStart), content: lines[i] };
|
|
120
|
+
const row = parseRow(lines[i], i);
|
|
105
121
|
if (!row) break;
|
|
106
122
|
lineNos.push(row.lineNo);
|
|
107
|
-
|
|
123
|
+
detabbed.push(row.content.replace(/\t/g, " "));
|
|
108
124
|
}
|
|
109
125
|
|
|
110
|
-
//
|
|
111
|
-
const detabbed = codeContents.map((l) => l.replace(/\t/g, " "));
|
|
126
|
+
// Highlight the entire block for multi-line constructs; fall back if rows cannot be aligned.
|
|
112
127
|
const lang = getLanguageFromPath(path);
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
}
|
|
128
|
+
const highlighted = lang ? highlightCode(detabbed.join("\n"), lang) : undefined;
|
|
129
|
+
const rendered =
|
|
130
|
+
highlighted?.length === detabbed.length
|
|
131
|
+
? highlighted
|
|
132
|
+
: detabbed.map((line) => theme.fg("toolOutput", line));
|
|
133
|
+
// Line numbers ascend, so the last one is the widest.
|
|
134
|
+
const lineNoWidth = lineNos.at(-1)?.length ?? 0;
|
|
121
135
|
for (let i = 0; i < rendered.length; i++) {
|
|
122
|
-
out.push(theme.fg("dim", ` ${lineNos[i]}: `) + rendered[i]);
|
|
136
|
+
out.push(theme.fg("dim", ` ${lineNos[i].padStart(lineNoWidth)}: `) + rendered[i]);
|
|
123
137
|
}
|
|
124
138
|
|
|
125
139
|
return out.join("\n");
|
|
126
140
|
}
|
|
127
141
|
|
|
142
|
+
const BYTES_PER_KIB = 1024;
|
|
143
|
+
|
|
128
144
|
/** Build the read override (a ToolDefinition fragment for registerTool). */
|
|
129
|
-
export function makeReadOverride(
|
|
130
|
-
cwd,
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
}: ToolEnvironment): ToolDefinition<
|
|
134
|
-
ReturnType<typeof createReadToolDefinition>["parameters"],
|
|
135
|
-
ReadDetails | undefined
|
|
136
|
-
> {
|
|
145
|
+
export function makeReadOverride(
|
|
146
|
+
{ cwd, config, budgets }: ToolEnvironment,
|
|
147
|
+
readAutoResize: () => boolean,
|
|
148
|
+
) {
|
|
137
149
|
const { hashLen } = config;
|
|
138
|
-
const { defaultLimit } = config.read;
|
|
150
|
+
const { defaultLimit, maxKiB } = config.read;
|
|
151
|
+
// An explicit read.maxKiB caps read output; otherwise the selected model's budget does.
|
|
152
|
+
const configuredBytes = maxKiB === undefined ? undefined : maxKiB * BYTES_PER_KIB;
|
|
139
153
|
const builtin = createReadToolDefinition(cwd);
|
|
140
154
|
// A TypeBox object, not a spread of Pi's plain JSON schema: argument diagnostics pick
|
|
141
155
|
// single fields from it, which needs TypeBox's own schema kinds.
|
|
@@ -157,50 +171,56 @@ export function makeReadOverride({
|
|
|
157
171
|
anchors: Type.Optional(
|
|
158
172
|
Type.Boolean({
|
|
159
173
|
description:
|
|
160
|
-
"false
|
|
174
|
+
"false returns the lines as they are in the file, with no header or LINE#HASH│ prefixes, for text you will read or parse but not edit; about a third fewer tokens (default true).",
|
|
161
175
|
}),
|
|
162
176
|
),
|
|
163
177
|
},
|
|
164
178
|
{ additionalProperties: false },
|
|
165
179
|
);
|
|
166
180
|
|
|
181
|
+
const boundary = createArgumentBoundary(parameters, cwd, budgets, () => noArgumentProduct);
|
|
167
182
|
return {
|
|
168
183
|
name: "read" as const,
|
|
169
184
|
label: "read",
|
|
170
185
|
description:
|
|
171
|
-
"Read a file
|
|
172
|
-
promptSnippet: "Read
|
|
173
|
-
promptGuidelines: [
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
// result text otherwise.
|
|
179
|
-
outputSchema: builtin.outputSchema,
|
|
180
|
-
prepareArguments: createArgumentPreparer("read", parameters, undefined, budgets),
|
|
186
|
+
"Read a file's text; images return as attachments. Lines show as LINE#HASH│content anchors for edit after one header line; anchors: false returns the lines alone. CRLF line endings show as LF and standalone CR as ␍.",
|
|
187
|
+
promptSnippet: "Read file text, with line anchors for edit",
|
|
188
|
+
promptGuidelines: ["Files containing NUL go to native read without a Hashline header."],
|
|
189
|
+
parameters,
|
|
190
|
+
// Scripts receive the report's object for text, and Pi's image block for a delegated image.
|
|
191
|
+
outputSchema: readOutputSchema(builtin.outputSchema),
|
|
192
|
+
prepareArguments: boundary.prepareArguments,
|
|
181
193
|
constrainedSampling: STRICT_SAMPLING,
|
|
182
194
|
renderShell: "default" as const,
|
|
183
195
|
|
|
184
196
|
renderCall: builtin.renderCall,
|
|
185
197
|
|
|
186
|
-
renderResult(
|
|
198
|
+
renderResult(
|
|
199
|
+
result,
|
|
200
|
+
options,
|
|
201
|
+
theme,
|
|
202
|
+
context: Parameters<NonNullable<typeof builtin.renderResult>>[3],
|
|
203
|
+
) {
|
|
187
204
|
const { isPartial, expanded } = options;
|
|
188
205
|
if (isPartial) return new Text(theme.fg("warning", "Reading…"), 0, 0);
|
|
189
|
-
if (context.isError) return renderToolError(result, "read", theme, expanded);
|
|
206
|
+
if (context.isError) return renderToolError(result, "read", theme, expanded, context);
|
|
190
207
|
const { content, report } = splitReport(result, "read");
|
|
191
208
|
if (result.details?.nativeRead)
|
|
192
209
|
return builtin.renderResult!({ ...result, content }, options, theme, context);
|
|
193
210
|
// Collapsed (not expanded): show nothing — the call line carries the
|
|
194
211
|
// title, matching the built-in read's fold behavior.
|
|
195
212
|
if (!expanded) return new Text("", 0, 0);
|
|
196
|
-
const
|
|
213
|
+
const payload = content[0];
|
|
214
|
+
const text = payload?.type === "text" ? payload.text : "";
|
|
215
|
+
// Only a read with `anchors: false` carries its header in details, which records the call
|
|
216
|
+
// that ran; arguments Pi cannot coerce do not describe it.
|
|
197
217
|
return new Text(
|
|
198
218
|
[
|
|
199
219
|
renderReadBody(
|
|
200
|
-
|
|
220
|
+
text,
|
|
201
221
|
String(context.args?.path ?? ""),
|
|
202
|
-
|
|
203
|
-
report
|
|
222
|
+
result.details?.header,
|
|
223
|
+
report?.lineTooLong,
|
|
204
224
|
theme,
|
|
205
225
|
),
|
|
206
226
|
...(report ? reportLines(report, theme) : []),
|
|
@@ -211,105 +231,120 @@ export function makeReadOverride({
|
|
|
211
231
|
},
|
|
212
232
|
|
|
213
233
|
async execute(
|
|
214
|
-
toolCallId
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
onUpdate
|
|
218
|
-
ctx
|
|
219
|
-
) {
|
|
234
|
+
toolCallId,
|
|
235
|
+
input,
|
|
236
|
+
piSignal,
|
|
237
|
+
onUpdate,
|
|
238
|
+
ctx,
|
|
239
|
+
): Promise<AgentToolResult<ReadDetails | undefined>> {
|
|
240
|
+
const {
|
|
241
|
+
args,
|
|
242
|
+
paths: [{ absolutePath: absPath }],
|
|
243
|
+
} = boundary.afterHooks(input);
|
|
244
|
+
const { anchors: anchored, ...params } = args;
|
|
245
|
+
const signal = callSignal(piSignal);
|
|
220
246
|
const budget = budgets();
|
|
221
|
-
const maxBytes =
|
|
222
|
-
config.read.maxKiB === undefined ? budget.readBytes : config.read.maxKiB * 1024;
|
|
247
|
+
const maxBytes = configuredBytes ?? budget.readBytes;
|
|
223
248
|
return runTool("read", { path: params.path, signal, budget }, async () => {
|
|
224
249
|
throwIfCancelled(signal);
|
|
225
250
|
const start = params.offset ?? DEFAULT_OFFSET;
|
|
226
251
|
const limit = params.limit ?? defaultLimit;
|
|
227
|
-
const
|
|
228
|
-
const formatRow =
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
: anchors.row;
|
|
252
|
+
const plain = anchored === false;
|
|
253
|
+
const formatRow = plain
|
|
254
|
+
? (_line: number, content: string) => displayCarriageReturns(content)
|
|
255
|
+
: createAnchorFormatter(hashLen).row;
|
|
232
256
|
const report = { tool: "read" as const, path: params.path };
|
|
233
|
-
const absPath = canonicalPath(cwd, params.path);
|
|
234
257
|
const readNative = async () => {
|
|
235
258
|
// Bind I/O to our target: native resolution may normalize or try filename variants.
|
|
236
259
|
const native = createReadToolDefinition(cwd, {
|
|
260
|
+
autoResizeImages: readAutoResize(),
|
|
237
261
|
operations: {
|
|
238
262
|
access: () => access(absPath, constants.R_OK),
|
|
239
263
|
readFile: () => readFile(absPath),
|
|
264
|
+
// Recheck the delegated read's target, which can change after the dispatch probe.
|
|
240
265
|
detectImageMimeType: () => detectSupportedImageMimeTypeFromFile(absPath),
|
|
241
266
|
},
|
|
242
267
|
});
|
|
243
268
|
const result = await native.execute(
|
|
244
269
|
toolCallId,
|
|
245
270
|
{ ...params, path: absPath },
|
|
246
|
-
|
|
271
|
+
piSignal,
|
|
247
272
|
onUpdate,
|
|
248
273
|
ctx,
|
|
249
274
|
);
|
|
250
|
-
|
|
251
|
-
...
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
275
|
+
const delegated = reportResult(report, result.content, budget, {
|
|
276
|
+
details: { ...result.details, nativeRead: true as const },
|
|
277
|
+
});
|
|
278
|
+
// Pi gives scripts an image as its image block; delegated text is the report's `text`.
|
|
279
|
+
const output = result.structuredContent as NativeReadOutput;
|
|
280
|
+
return typeof output === "string"
|
|
281
|
+
? delegated
|
|
282
|
+
: { ...delegated, structuredContent: output };
|
|
257
283
|
};
|
|
258
284
|
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
}
|
|
285
|
+
// Opening a FIFO or device can block before any cancellation check runs.
|
|
286
|
+
requireRegularFile(await stat(absPath));
|
|
262
287
|
if (await detectSupportedImageMimeTypeFromFile(absPath)) return readNative();
|
|
263
288
|
|
|
264
289
|
const rows: string[] = [];
|
|
265
290
|
const crExpansion = Buffer.byteLength(displayCarriageReturns("\r")) - 1;
|
|
266
|
-
let
|
|
267
|
-
let
|
|
291
|
+
let remainingBytes = maxBytes + 1; // The first row has no preceding LF.
|
|
292
|
+
let budgetExceeded = false;
|
|
268
293
|
const stats = await scanTextLines(
|
|
269
294
|
absPath,
|
|
270
|
-
(number) => number >= start && number - start < limit,
|
|
271
|
-
(
|
|
272
|
-
if (firstOmittedLine !== undefined) return;
|
|
295
|
+
(number) => !budgetExceeded && number >= start && number - start < limit,
|
|
296
|
+
({ number, byteLength, carriageReturns, text }) => {
|
|
273
297
|
const rowBytes =
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
if (nextBytes > maxBytes) {
|
|
279
|
-
firstOmittedLine = line.number;
|
|
298
|
+
byteLength + carriageReturns * crExpansion + Buffer.byteLength(formatRow(number, ""));
|
|
299
|
+
const cost = rowBytes + 1;
|
|
300
|
+
if (cost > remainingBytes) {
|
|
301
|
+
budgetExceeded = true;
|
|
280
302
|
return;
|
|
281
303
|
}
|
|
282
|
-
rows.push(formatRow(
|
|
283
|
-
|
|
304
|
+
rows.push(formatRow(number, text));
|
|
305
|
+
remainingBytes -= cost;
|
|
306
|
+
},
|
|
307
|
+
{
|
|
308
|
+
signal,
|
|
309
|
+
// A line longer than the whole budget ends the window.
|
|
310
|
+
bound: { maxBytes, onExceeded: () => (budgetExceeded = true) },
|
|
284
311
|
},
|
|
285
|
-
{ signal, maxLineBytes: maxBytes },
|
|
286
312
|
);
|
|
287
313
|
if (stats.hasNul) return readNative();
|
|
288
|
-
//
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
:
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
const
|
|
298
|
-
const limitText = formatByteSize(maxBytes);
|
|
314
|
+
// Rows without a header show no rows and one empty row as the same text, so a window that
|
|
315
|
+
// starts past the last line is a failure. An empty file read from its first line is empty text.
|
|
316
|
+
if (plain && start > Math.max(stats.totalLines, DEFAULT_OFFSET)) {
|
|
317
|
+
throw new HashlineError("OFFSET_PAST_END", "Offset is past the last line.", {
|
|
318
|
+
facts: { totalLines: stats.totalLines },
|
|
319
|
+
...(stats.totalLines === 0 ? { next: "emptyFile" as const } : {}),
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
const nextOffset = start + rows.length;
|
|
323
|
+
const hasMoreLines = rows.length > 0 && nextOffset <= stats.totalLines;
|
|
324
|
+
const limitText = budgetExceeded ? formatByteSize(maxBytes) : undefined;
|
|
325
|
+
const limitFact =
|
|
326
|
+
rows.length === 0 ? { lineTooLong: limitText } : { outputLimit: limitText };
|
|
327
|
+
const header = formatReadHeader(
|
|
328
|
+
serializePath(cwd, absPath),
|
|
329
|
+
stats.totalLines,
|
|
330
|
+
start,
|
|
331
|
+
stats.finalNewline,
|
|
332
|
+
);
|
|
333
|
+
const body = rows.join("\n");
|
|
334
|
+
const text = plain ? body : `${header}\n${body}`;
|
|
299
335
|
|
|
300
|
-
|
|
336
|
+
return reportResult(
|
|
301
337
|
{
|
|
302
338
|
...report,
|
|
303
|
-
nextOffset,
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
lineTooLong: firstLineTooLong ? limitText : undefined,
|
|
339
|
+
nextOffset: hasMoreLines ? nextOffset : undefined,
|
|
340
|
+
callShowsNextOffset: !budgetExceeded && params.limit !== undefined ? true : undefined,
|
|
341
|
+
...limitFact,
|
|
307
342
|
},
|
|
308
|
-
[{ type: "text"
|
|
343
|
+
[{ type: "text", text }],
|
|
344
|
+
budget,
|
|
345
|
+
{ details: plain ? { header } : undefined },
|
|
309
346
|
);
|
|
310
|
-
const text = result.content.flatMap((block) => (block.type === "text" ? [block.text] : []));
|
|
311
|
-
return { ...result, structuredContent: text.join("\n") };
|
|
312
347
|
});
|
|
313
348
|
},
|
|
314
|
-
}
|
|
349
|
+
} satisfies ToolDefinition<typeof parameters, ReadDetails | undefined>;
|
|
315
350
|
}
|
package/src/pi/regex-worker.ts
CHANGED
|
@@ -12,7 +12,7 @@ export async function withRegexWorker<Input, Result, Output>(
|
|
|
12
12
|
entry: URL,
|
|
13
13
|
decode: (value: unknown) => RegexWorkerReply<Result> | undefined,
|
|
14
14
|
timeoutMs: number,
|
|
15
|
-
signal: AbortSignal
|
|
15
|
+
signal: AbortSignal,
|
|
16
16
|
execute: (run: (input: Input) => Promise<Result>) => Promise<Output>,
|
|
17
17
|
resourceLimits?: ResourceLimits,
|
|
18
18
|
): Promise<Output> {
|
|
@@ -23,14 +23,20 @@ export async function withRegexWorker<Input, Result, Output>(
|
|
|
23
23
|
);
|
|
24
24
|
const worker = new Worker(bootstrap, { resourceLimits });
|
|
25
25
|
let failure: Error | undefined;
|
|
26
|
-
|
|
27
|
-
let
|
|
26
|
+
/** The request awaiting a reply, with its timeout. */
|
|
27
|
+
let pending:
|
|
28
|
+
| {
|
|
29
|
+
readonly resolve: (result: Result) => void;
|
|
30
|
+
readonly reject: (error: Error) => void;
|
|
31
|
+
readonly timer: ReturnType<typeof setTimeout>;
|
|
32
|
+
}
|
|
33
|
+
| undefined;
|
|
28
34
|
let termination: ReturnType<Worker["terminate"]> | undefined;
|
|
29
35
|
const terminate = () => (termination ??= worker.terminate());
|
|
30
36
|
const clear = () => {
|
|
31
|
-
clearTimeout(timer);
|
|
32
37
|
const previous = pending;
|
|
33
38
|
pending = undefined;
|
|
39
|
+
clearTimeout(previous?.timer);
|
|
34
40
|
return previous;
|
|
35
41
|
};
|
|
36
42
|
const fail = (error: Error) => {
|
|
@@ -62,15 +68,14 @@ export async function withRegexWorker<Input, Result, Output>(
|
|
|
62
68
|
}),
|
|
63
69
|
),
|
|
64
70
|
);
|
|
65
|
-
signal
|
|
71
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
66
72
|
// Keep dispatch asynchronous so cancellation can be observed before posting a request.
|
|
67
73
|
const run = (input: Input): Promise<Result> =>
|
|
68
74
|
Promise.resolve().then(() => {
|
|
69
75
|
throwIfCancelled(signal);
|
|
70
76
|
if (failure) throw failure;
|
|
71
77
|
return new Promise<Result>((resolve, reject) => {
|
|
72
|
-
|
|
73
|
-
timer = setTimeout(() => {
|
|
78
|
+
const timer = setTimeout(() => {
|
|
74
79
|
fail(
|
|
75
80
|
new HashlineError("REGEX_TIMEOUT", "Regex evaluation timed out.", {
|
|
76
81
|
facts: { timeoutMs },
|
|
@@ -79,6 +84,7 @@ export async function withRegexWorker<Input, Result, Output>(
|
|
|
79
84
|
// A grep caller may still be scanning for NUL after evaluation times out.
|
|
80
85
|
void terminate();
|
|
81
86
|
}, timeoutMs);
|
|
87
|
+
pending = { resolve, reject, timer };
|
|
82
88
|
worker.postMessage(input);
|
|
83
89
|
});
|
|
84
90
|
});
|
|
@@ -86,7 +92,7 @@ export async function withRegexWorker<Input, Result, Output>(
|
|
|
86
92
|
return await execute(run);
|
|
87
93
|
} finally {
|
|
88
94
|
clear();
|
|
89
|
-
signal
|
|
95
|
+
signal.removeEventListener("abort", abort);
|
|
90
96
|
await terminate();
|
|
91
97
|
}
|
|
92
98
|
}
|