pi-readseek 0.13.6 → 0.13.8

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.
Files changed (2) hide show
  1. package/dist/index.ts +157 -2656
  2. package/package.json +5 -5
package/dist/index.ts CHANGED
@@ -2,2307 +2,16 @@
2
2
  import { readFile as fsReadFile } from "node:fs/promises";
3
3
  import { createPatch } from "diff";
4
4
  import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
5
- import { Type as Type3 } from "@sinclair/typebox";
5
+ import { Type as Type2 } from "@sinclair/typebox";
6
6
  import { Text as Text3 } from "@earendil-works/pi-tui";
7
7
 
8
- // ../readseek-api/src/contract.ts
9
- var VISION_LEVELS = ["low", "medium", "high"];
10
- var EDIT_VARIANTS = [
11
- "set_line",
12
- "replace_lines",
13
- "insert_after",
14
- "replace",
15
- "replace_symbol"
16
- ];
17
- var GIT_SCOPES = ["tracked", "untracked", "ignored", "all"];
18
- var TOOL_NAMES = [
19
- "show",
20
- "tree",
21
- "meta",
22
- "assets",
23
- "syntax",
24
- "check",
25
- "caption",
26
- "objects",
27
- "ocr",
28
- "search",
29
- "grep",
30
- "def",
31
- "refs",
32
- "edit",
33
- "rename",
34
- "write"
35
- ];
36
- var PARAM_DESCRIPTIONS = {
37
- path: "Absolute or relative file path",
38
- projectPath: "Path relative to the project directory",
39
- projectSearchPath: "File or directory to search; defaults to the project directory",
40
- searchPath: "File or directory to search; defaults to the current directory",
41
- language: "Language override when auto-detection is ambiguous",
42
- languageSymbol: "Language override for symbol replacement",
43
- pattern: "AST pattern (ast-grep style), such as console.log($$$ARGS)",
44
- patternContext: "Surrounding code context for sub-statement patterns",
45
- selector: "Target AST node kind to extract from pattern context",
46
- grepPattern: "Native regex pattern; set literal for exact text. Empty regex matches every line; empty literal is invalid.",
47
- name: "Qualified or unqualified symbol name",
48
- refsName: "Identifier to find references for",
49
- gitScope: "In a Git repository, which files to search: tracked, untracked, ignored (untracked plus ignored), or all. Defaults to tracked plus untracked.",
50
- at: "Location selector: N[:COLUMN], START-END, H[:COLUMN], NAME, line:N[:COLUMN], hash:H[:COLUMN], symbol:NAME, page:N, node:ID, or asset:ID",
51
- assetAt: "Document selector: N, page:N, node:ID, or asset:ID",
52
- rule: "KDL node selection rule, @path, or '-' for standard input",
53
- rules: "KDL structural checks, @path, or '-' for standard input",
54
- stdinName: "File name hint when the target is '-'",
55
- end: "Last line to include",
56
- limit: "Maximum number of lines to include",
57
- depth: "Maximum structural depth for structure output; defaults to 1 in agent tools",
58
- level: "Explicit inference level: low (default), medium, or high",
59
- include: "Additional caption tasks: text and/or objects",
60
- kind: "Restrict structure to this node kind",
61
- outline: "Show outline of document hierarchy or source symbols",
62
- noAnchors: "Omit source line anchors",
63
- edits: "Use set_line, replace_lines, insert_after, replace_symbol, or replace",
64
- editVariant: "Exactly one nested edit variant",
65
- setLine: 'Replace one line: {"set_line":{"anchor":"LINE:HASH","new_text":"..."}}',
66
- replaceLines: 'Replace a range: {"replace_lines":{"start_anchor":"LINE:HASH","end_anchor":"LINE:HASH","new_text":"..."}}',
67
- insertAfter: 'Insert text: {"insert_after":{"anchor":"LINE:HASH","new_text":"..."}}',
68
- replace: 'Replace text: {"replace":{"old_text":"...","new_text":"..."}}',
69
- replaceSymbol: 'Replace a symbol: {"replace_symbol":{"symbol":"name","new_body":"..."}}',
70
- anchor: "Fresh LINE:HASH anchor for the line to replace",
71
- startAnchor: "Fresh LINE:HASH anchor for the first line in the range",
72
- endAnchor: "Fresh LINE:HASH anchor for the last line in the range",
73
- insertAnchor: "Fresh LINE:HASH anchor for the line after which to insert",
74
- newTextLine: "Replacement text; use an empty string to delete the line",
75
- newTextRange: "Replacement text; use an empty string to delete the range",
76
- newTextInsert: "Text to insert after the anchored line",
77
- oldText: "Exact text to find",
78
- newText: "Replacement text",
79
- all: "Replace every exact match",
80
- symbol: "Mapped symbol name",
81
- newBody: "Complete replacement body for the symbol",
82
- apply: "When supported by the host, apply the verified plan instead of previewing only",
83
- applyDefaultTrue: "Apply the verified edits; defaults to true",
84
- planHash: "Require the apply plan to match this dry-run plan hash",
85
- workspace: "Rename across the project",
86
- to: "New symbol name",
87
- postEditVerify: "Read back and verify persisted content",
88
- content: "Complete text file content",
89
- glob: "File-name glob, such as *.ts",
90
- ignoreCase: "Ignore case",
91
- literal: "Treat pattern literally",
92
- context: "Surrounding lines for each match",
93
- matchLimit: "Maximum matches to return",
94
- grepLimit: "Maximum matching lines to return; positive integer, defaults to 100",
95
- summary: "Return per-file counts",
96
- grepScope: "Group matches by enclosing symbol",
97
- scopeContext: "Non-negative context lines within each symbol; requires scope: symbol"
98
- };
99
- var TOOL_DESCRIPTIONS = {
100
- show: "Read source, document content, or image descriptors without inference. Obtain fresh `LINE:HASH` anchors before edits; use at with a column for cursor context. Document results include typed nodes and cached asset paths.",
101
- tree: "Show parsed source or document hierarchy. Use shallow depth for file overviews.",
102
- meta: "Show format, source identity, language, dimensions, or page count without decoding image content or inference.",
103
- assets: "Return selected document asset descriptors with usable cached paths. Adapters attach images from those paths.",
104
- syntax: "Check parser syntax diagnostics. Exit 0 is clean, 1 has findings, 2 is failure; this is not type checking.",
105
- check: "Evaluate KDL structural assertions. Exit 0 is clean, 1 has findings, 2 is failure.",
106
- caption: "Explicitly infer a caption using an installed model. Include text and objects to request OCR and detection too; never downloads models automatically.",
107
- objects: "Explicitly infer object labels and bounding boxes using an installed model.",
108
- ocr: "Explicitly recognize text from pixels using an installed model; reading never silently invokes OCR.",
109
- search: "Find AST nodes by pattern or KDL selection rule. Returns edit-ready anchors. Use `grep` for text and regex.",
110
- grep: "Search with native regex or literal matching. Returns matching-line counts, source LINE:HASH anchors, and document node-local locations. Native glob, context, summary, limits, Git scope, and symbol grouping apply; default limit is 100 matching lines.",
111
- def: "Find a symbol definition or declaration by qualified or unqualified name.",
112
- refs: "Find identifier-name matches with name, or binding-scoped references with at. Use before renaming or deleting a symbol.",
113
- edit: "Edit existing files with fresh `LINE:HASH` anchors. Each edits item contains exactly one set_line, replace_lines, insert_after, replace_symbol, or replace object. Preview before applying a verified plan.",
114
- rename: "Rename a symbol at a line or hash cursor with binding-aware edits and stale-plan protection.",
115
- write: "Create or replace a complete text file and return `LINE:HASH` anchors. Use `edit` for small changes."
116
- };
117
- function rewriteBacktickedToolNames(text, aliases = {}) {
118
- return TOOL_NAMES.reduce((rewritten, toolName) => rewritten.replaceAll(`\`${toolName}\``, `\`${aliases[toolName] ?? toolName}\``), text);
119
- }
120
- function renderToolDescription(name, aliases = {}) {
121
- const desc = TOOL_DESCRIPTIONS[name];
122
- if (!desc)
123
- throw new Error(`Missing TOOL_DESCRIPTIONS for ${name}`);
124
- return rewriteBacktickedToolNames(desc, aliases);
125
- }
126
- var gitScopeSchema = {
127
- gitScope: {
128
- type: "string",
129
- enum: GIT_SCOPES,
130
- description: PARAM_DESCRIPTIONS.gitScope
131
- }
132
- };
133
- var editItemSchema = {
134
- type: "object",
135
- additionalProperties: false,
136
- minProperties: 1,
137
- maxProperties: 1,
138
- properties: {
139
- set_line: {
140
- type: "object",
141
- additionalProperties: false,
142
- required: ["anchor", "new_text"],
143
- properties: {
144
- anchor: { type: "string", description: PARAM_DESCRIPTIONS.anchor },
145
- new_text: { type: "string", description: PARAM_DESCRIPTIONS.newTextLine }
146
- },
147
- description: PARAM_DESCRIPTIONS.setLine
148
- },
149
- replace_lines: {
150
- type: "object",
151
- additionalProperties: false,
152
- required: ["start_anchor", "end_anchor", "new_text"],
153
- properties: {
154
- start_anchor: { type: "string", description: PARAM_DESCRIPTIONS.startAnchor },
155
- end_anchor: { type: "string", description: PARAM_DESCRIPTIONS.endAnchor },
156
- new_text: { type: "string", description: PARAM_DESCRIPTIONS.newTextRange }
157
- },
158
- description: PARAM_DESCRIPTIONS.replaceLines
159
- },
160
- insert_after: {
161
- type: "object",
162
- additionalProperties: false,
163
- required: ["anchor", "new_text"],
164
- properties: {
165
- anchor: { type: "string", description: PARAM_DESCRIPTIONS.insertAnchor },
166
- new_text: { type: "string", description: PARAM_DESCRIPTIONS.newTextInsert }
167
- },
168
- description: PARAM_DESCRIPTIONS.insertAfter
169
- },
170
- replace: {
171
- type: "object",
172
- additionalProperties: false,
173
- required: ["old_text", "new_text"],
174
- properties: {
175
- old_text: { type: "string", description: PARAM_DESCRIPTIONS.oldText },
176
- new_text: { type: "string", description: PARAM_DESCRIPTIONS.newText },
177
- all: { type: "boolean", description: PARAM_DESCRIPTIONS.all }
178
- },
179
- description: PARAM_DESCRIPTIONS.replace
180
- },
181
- replace_symbol: {
182
- type: "object",
183
- additionalProperties: false,
184
- required: ["symbol", "new_body"],
185
- properties: {
186
- symbol: { type: "string", description: PARAM_DESCRIPTIONS.symbol },
187
- new_body: { type: "string", description: PARAM_DESCRIPTIONS.newBody }
188
- },
189
- description: PARAM_DESCRIPTIONS.replaceSymbol
190
- }
191
- },
192
- description: PARAM_DESCRIPTIONS.editVariant
193
- };
194
- var string = (description) => ({ type: "string", description });
195
- var integer = (description, minimum = 1) => ({ type: "integer", minimum, description });
196
- var path = { path: string(PARAM_DESCRIPTIONS.path) };
197
- var at = { at: string(PARAM_DESCRIPTIONS.at) };
198
- var lang = { language: string(PARAM_DESCRIPTIONS.language) };
199
- var stdin = { stdinName: string(PARAM_DESCRIPTIONS.stdinName) };
200
- var noAnchors = { noAnchors: { type: "boolean", description: PARAM_DESCRIPTIONS.noAnchors } };
201
- var level = { level: { type: "string", enum: VISION_LEVELS, description: PARAM_DESCRIPTIONS.level } };
202
- var limit = { limit: integer(PARAM_DESCRIPTIONS.matchLimit) };
203
- var apply = { apply: { type: "boolean", description: PARAM_DESCRIPTIONS.apply }, planHash: string(PARAM_DESCRIPTIONS.planHash) };
204
- function tool(name, title, properties, required) {
205
- return { name, title, description: TOOL_DESCRIPTIONS[name], inputSchema: { type: "object", properties, required, additionalProperties: false } };
206
- }
207
- var TOOL_CONTRACTS = [
208
- tool("show", "Show content", { ...path, ...at, ...lang, ...stdin, ...noAnchors, end: integer(PARAM_DESCRIPTIONS.end), limit: integer(PARAM_DESCRIPTIONS.limit) }, ["path"]),
209
- tool("tree", "Show structure", { ...path, ...at, ...lang, ...stdin, depth: integer(PARAM_DESCRIPTIONS.depth, 0), kind: string(PARAM_DESCRIPTIONS.kind), outline: { type: "boolean", description: PARAM_DESCRIPTIONS.outline } }, ["path"]),
210
- tool("meta", "Show metadata", { ...path, ...lang, ...stdin }, ["path"]),
211
- tool("assets", "Show assets", { ...path, at: string(PARAM_DESCRIPTIONS.assetAt), ...stdin }, ["path"]),
212
- tool("syntax", "Check syntax", { ...path, ...lang, ...stdin }, ["path"]),
213
- tool("check", "Check rules", { path: string(PARAM_DESCRIPTIONS.searchPath), ...gitScopeSchema, rules: string(PARAM_DESCRIPTIONS.rules) }, ["rules"]),
214
- tool("caption", "Generate caption", { ...path, ...at, ...stdin, ...level, include: { type: "array", items: { type: "string", enum: ["text", "objects"] }, minItems: 1, uniqueItems: true, description: PARAM_DESCRIPTIONS.include } }, ["path"]),
215
- tool("objects", "Detect objects", { ...path, ...at, ...stdin, ...level }, ["path"]),
216
- tool("ocr", "Recognize text", { ...path, ...at, ...stdin, ...level }, ["path"]),
217
- tool("search", "Search AST nodes", { ...path, ...lang, ...stdin, ...limit, ...gitScopeSchema, ...noAnchors, pattern: string(PARAM_DESCRIPTIONS.pattern), context: string(PARAM_DESCRIPTIONS.patternContext), selector: string(PARAM_DESCRIPTIONS.selector), rule: string(PARAM_DESCRIPTIONS.rule) }, []),
218
- tool("grep", "Search text", { path: string(PARAM_DESCRIPTIONS.searchPath), limit: { ...integer(PARAM_DESCRIPTIONS.grepLimit), default: 100 }, ...gitScopeSchema, pattern: string(PARAM_DESCRIPTIONS.grepPattern), glob: string(PARAM_DESCRIPTIONS.glob), ignoreCase: { type: "boolean", description: PARAM_DESCRIPTIONS.ignoreCase }, literal: { type: "boolean", description: PARAM_DESCRIPTIONS.literal }, context: integer(PARAM_DESCRIPTIONS.context, 0), summary: { type: "boolean", description: PARAM_DESCRIPTIONS.summary }, scope: { type: "string", enum: ["symbol"], description: PARAM_DESCRIPTIONS.grepScope }, scopeContext: integer(PARAM_DESCRIPTIONS.scopeContext, 0) }, ["pattern"]),
219
- tool("def", "Find definitions", { ...path, ...lang, ...gitScopeSchema, ...noAnchors, name: string(PARAM_DESCRIPTIONS.name) }, ["name"]),
220
- tool("refs", "Find references", { ...path, ...at, ...lang, ...gitScopeSchema, ...noAnchors, name: string(PARAM_DESCRIPTIONS.refsName) }, []),
221
- tool("edit", "Hash-verified edit", { ...path, ...lang, ...gitScopeSchema, ...apply, edits: { type: "array", minItems: 1, items: editItemSchema, description: PARAM_DESCRIPTIONS.edits }, postEditVerify: { type: "boolean", description: PARAM_DESCRIPTIONS.postEditVerify } }, ["path", "edits"]),
222
- tool("rename", "Rename symbol", { ...path, ...at, ...lang, ...gitScopeSchema, ...apply, to: string(PARAM_DESCRIPTIONS.to), workspace: { type: "boolean", description: PARAM_DESCRIPTIONS.workspace } }, ["path", "at", "to"]),
223
- tool("write", "Write file", { ...path, content: string(PARAM_DESCRIPTIONS.content) }, ["path", "content"])
224
- ];
225
- function getToolContract(name) {
226
- const contract = TOOL_CONTRACTS.find((entry) => entry.name === name);
227
- if (!contract)
228
- throw new Error(`missing tool contract: ${name}`);
229
- return contract;
230
- }
231
- // ../readseek-api/src/policy.ts
232
- var REPLACEABLE_TOOLS = [
233
- {
234
- tool: "show",
235
- builtIn: "read",
236
- benefit: "it returns LINE:HASH anchors for safe edits."
237
- },
238
- {
239
- tool: "edit",
240
- builtIn: "edit",
241
- benefit: "it verifies fresh LINE:HASH anchors."
242
- },
243
- {
244
- tool: "grep",
245
- builtIn: "grep",
246
- benefit: "it runs native regex/literal matching and returns source LINE:HASH anchors or document locations."
247
- },
248
- {
249
- tool: "write",
250
- builtIn: "write",
251
- benefit: "it returns LINE:HASH anchors."
252
- }
253
- ];
254
- var TOOL_COMPACT_GUIDELINES = {
255
- show: [
256
- "Use `tree` for shallow overviews and `syntax` for diagnostics; use `def`, `refs`, or `search` for targeted symbol questions."
257
- ],
258
- edit: [
259
- "Prefer set_line, replace_lines, and insert_after; use replace only when anchors are impractical."
260
- ],
261
- grep: [
262
- "Use `grep` with summary first for broad searches, then narrow by path, glob, or pattern."
263
- ],
264
- write: [
265
- "Use anchored edits rather than `write` for small changes or appends."
266
- ],
267
- search: [
268
- "Use `search` for AST patterns; use `grep` for plain text."
269
- ],
270
- refs: [
271
- "Use `refs` before changing a symbol; use at with line:N:C to follow one binding."
272
- ]
273
- };
274
- function resolveToolName(name, aliases = {}) {
275
- return aliases[name] ?? name;
276
- }
277
- function renderCompactGuidelines(name, aliases = {}) {
278
- return (TOOL_COMPACT_GUIDELINES[name] ?? []).map((guideline) => rewriteBacktickedToolNames(guideline, aliases));
279
- }
280
- function renderToolRoutingPolicy(options = {}) {
281
- const aliases = options.aliases ?? {};
282
- const show = resolveToolName("show", aliases);
283
- const edit = resolveToolName("edit", aliases);
284
- const write = resolveToolName("write", aliases);
285
- const grep = resolveToolName("grep", aliases);
286
- const search = resolveToolName("search", aliases);
287
- const def = resolveToolName("def", aliases);
288
- const refs = resolveToolName("refs", aliases);
289
- const rename = resolveToolName("rename", aliases);
290
- const assets = resolveToolName("assets", aliases);
291
- const title = options.title ?? "ReadSeek tool policy:";
292
- const bullets = [];
293
- if (options.preferOverBuiltIns) {
294
- bullets.push("- Prefer ReadSeek tools over built-ins when they can do the job.");
295
- }
296
- bullets.push(`- Read with ${show} first; ${edit} needs fresh LINE:HASH anchors.`, `- Use ${grep} for text/regex, ${search} for AST patterns, ${def}/${refs} for targeted symbols, and shallow ${resolveToolName("tree", aliases)} structures only for file overviews.`, `- Use ${edit} for existing files, ${write} for whole-file creation or replacement, and ${rename} for symbol renames.`, `- Use ${resolveToolName("tree", aliases)} for document structure; run ${resolveToolName("syntax", aliases)} after source edits for a quick syntax check.`, `- Use ${assets} to materialize selected document assets and read their returned paths.`);
297
- if (options.demoteBuiltIns && options.demoteBuiltIns.length > 0) {
298
- bullets.push(`- Do not use built-in ${options.demoteBuiltIns.join(", ")} when a ReadSeek tool can do the job.`);
299
- }
300
- return [title, ...bullets].join(`
301
- `);
302
- }
303
- // ../readseek-api/src/hashline.ts
304
- var HASH_LEN = 6;
305
- var LINE_ANCHOR_RE = /^(\d+):([0-9a-fA-F]{6})$/;
306
- function tryParseLineAnchor(anchor) {
307
- const match = LINE_ANCHOR_RE.exec(anchor.trim());
308
- if (!match) {
309
- return { ok: false, error: `invalid LINE:HASH anchor: ${anchor}` };
310
- }
311
- const digits = match[1];
312
- const line = Number.parseInt(digits, 10);
313
- if (!Number.isSafeInteger(line)) {
314
- return { ok: false, error: `Line number must be a safe integer, got ${digits} in "${anchor}".` };
315
- }
316
- if (line < 1) {
317
- return { ok: false, error: `Line number must be >= 1, got ${line} in "${anchor}".` };
318
- }
319
- return { ok: true, anchor: { line, hash: match[2].toLowerCase() } };
320
- }
321
-
322
- // ../readseek-api/src/validation.ts
323
- function isRecord(value) {
324
- return typeof value === "object" && value !== null && !Array.isArray(value);
325
- }
326
- function validateReferencesSelection(input) {
327
- if (Boolean(input.name) === Boolean(input.at))
328
- return { ok: false, error: "exactly one of name or at is required" };
329
- return { ok: true };
330
- }
331
- function validateGrepParams(input) {
332
- if (!input || typeof input !== "object" || Array.isArray(input)) {
333
- return { ok: false, error: "grep params must be an object" };
334
- }
335
- const params = input;
336
- const allowed = [
337
- "pattern",
338
- "path",
339
- "glob",
340
- "ignoreCase",
341
- "literal",
342
- "context",
343
- "limit",
344
- "summary",
345
- "scope",
346
- "scopeContext",
347
- "gitScope",
348
- "signal",
349
- "stdin",
350
- "timeoutMs",
351
- "cancelable"
352
- ];
353
- if (Object.keys(params).some((key) => !allowed.includes(key)))
354
- return { ok: false, error: "unknown grep parameter" };
355
- if (typeof params.pattern !== "string")
356
- return { ok: false, error: "grep requires a pattern string" };
357
- if (params.literal === true && params.pattern.length === 0)
358
- return { ok: false, error: "literal pattern must not be empty" };
359
- for (const key of ["path", "glob"]) {
360
- if (params[key] !== undefined && (typeof params[key] !== "string" || params[key].length === 0)) {
361
- return { ok: false, error: `${key} must be a non-empty string` };
362
- }
363
- }
364
- for (const key of ["ignoreCase", "literal", "summary"]) {
365
- if (params[key] !== undefined && typeof params[key] !== "boolean")
366
- return { ok: false, error: `${key} must be a boolean` };
367
- }
368
- for (const key of ["context", "limit", "scopeContext"]) {
369
- const value = params[key];
370
- const minimum = key === "limit" ? 1 : 0;
371
- if (value !== undefined && (typeof value !== "number" || !Number.isSafeInteger(value) || value < minimum)) {
372
- return { ok: false, error: `${key} must be a ${minimum === 1 ? "positive" : "non-negative"} integer` };
373
- }
374
- }
375
- if (params.scope !== undefined && params.scope !== "symbol")
376
- return { ok: false, error: "scope must be symbol" };
377
- if (params.scopeContext !== undefined && params.scope !== "symbol")
378
- return { ok: false, error: "scopeContext requires scope" };
379
- if (params.gitScope !== undefined && !GIT_SCOPES.includes(params.gitScope)) {
380
- return { ok: false, error: "invalid gitScope" };
381
- }
382
- return { ok: true };
383
- }
384
- var VARIANT_FIELDS = {
385
- set_line: ["anchor", "new_text"],
386
- replace_lines: ["start_anchor", "end_anchor", "new_text"],
387
- insert_after: ["anchor", "new_text"],
388
- replace: ["old_text", "new_text"],
389
- replace_symbol: ["symbol", "new_body"]
390
- };
391
- function isEditVariant(value) {
392
- return EDIT_VARIANTS.includes(value);
393
- }
394
- function parseEditItem(item, index) {
395
- const keys = Object.keys(item);
396
- const variant = keys[0];
397
- if (keys.length !== 1 || variant === undefined || !isEditVariant(variant)) {
398
- return {
399
- ok: false,
400
- error: `edits[${index}] must contain exactly one of: ${EDIT_VARIANTS.join(", ")}. Got: [${keys.join(", ")}]`
401
- };
402
- }
403
- const payload = item[variant];
404
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
405
- return { ok: false, error: `edits[${index}].${variant} must be an object` };
406
- }
407
- const expected = VARIANT_FIELDS[variant];
408
- const allowed = variant === "replace" ? [...expected, "all"] : [...expected];
409
- const actual = Object.keys(payload);
410
- if (actual.some((field) => !allowed.includes(field)) || expected.some((field) => !actual.includes(field))) {
411
- return { ok: false, error: `edits[${index}].${variant} contains invalid fields` };
412
- }
413
- const values = payload;
414
- for (const field of expected) {
415
- if (typeof values[field] !== "string") {
416
- return { ok: false, error: `edits[${index}].${variant}.${field} must be a string` };
417
- }
418
- }
419
- if (variant === "replace" && values.all !== undefined && typeof values.all !== "boolean") {
420
- return { ok: false, error: `edits[${index}].replace.all must be a boolean` };
421
- }
422
- for (const field of expected) {
423
- if (!field.endsWith("anchor"))
424
- continue;
425
- const parsed = tryParseLineAnchor(values[field]);
426
- if (!parsed.ok) {
427
- return { ok: false, error: `edits[${index}].${variant}.${field}: ${parsed.error}` };
428
- }
429
- }
430
- return { ok: true, edit: item };
431
- }
432
- function validateExactlyOneEditVariant(edits) {
433
- if (!Array.isArray(edits) || edits.length === 0) {
434
- return { ok: false, error: "edits must contain at least one edit" };
435
- }
436
- const normalized = [];
437
- for (let index = 0;index < edits.length; index++) {
438
- const item = edits[index];
439
- if (!item || typeof item !== "object" || Array.isArray(item)) {
440
- return { ok: false, error: `edits[${index}] must be an edit object` };
441
- }
442
- const parsed = parseEditItem(item, index);
443
- if (!parsed.ok)
444
- return parsed;
445
- normalized.push(parsed.edit);
446
- }
447
- return { ok: true, edits: normalized };
448
- }
449
- var BASE10_INT_RE = /^-?\d+$/;
450
- var MIN_SAFE_INTEGER = BigInt(Number.MIN_SAFE_INTEGER);
451
- var MAX_SAFE_INTEGER = BigInt(Number.MAX_SAFE_INTEGER);
452
- function formatReceived(value) {
453
- if (typeof value === "number" || typeof value === "bigint")
454
- return String(value);
455
- return JSON.stringify(value) ?? String(value);
456
- }
457
- function invalidInteger(value, name) {
458
- return {
459
- ok: false,
460
- message: `Invalid ${name}: expected a safe base-10 integer, received ${formatReceived(value)}.`
461
- };
462
- }
463
- function coerceObviousBase10Int(value, name) {
464
- if (value === undefined || typeof value === "string" && value.trim() === "") {
465
- return { ok: true, value: undefined };
466
- }
467
- if (typeof value === "number") {
468
- if (Number.isSafeInteger(value)) {
469
- return { ok: true, value };
470
- }
471
- return invalidInteger(value, name);
472
- }
473
- if (typeof value === "string" && BASE10_INT_RE.test(value)) {
474
- const parsed = BigInt(value);
475
- if (parsed >= MIN_SAFE_INTEGER && parsed <= MAX_SAFE_INTEGER) {
476
- return { ok: true, value: Number(parsed) };
477
- }
478
- }
479
- return invalidInteger(value, name);
480
- }
481
- // ../readseek-api/src/argv.ts
482
- function appendGitScopeArgs(args, input) {
483
- if (input.gitScope !== undefined)
484
- args.push("--git-scope", input.gitScope);
485
- return args;
486
- }
487
- function pushOptionalString(args, flag, value) {
488
- if (value !== undefined)
489
- args.push(flag, value);
490
- }
491
- function pushOptionalNumber(args, flag, value) {
492
- if (value !== undefined)
493
- args.push(flag, String(value));
494
- }
495
- function appendApplyAndPlanHash(args, input) {
496
- const order = input.flagOrder ?? "apply-first";
497
- if (order === "plan-hash-first") {
498
- pushOptionalString(args, "--plan-hash", input.planHash);
499
- if (input.apply)
500
- args.push("--apply");
501
- return args;
502
- }
503
- if (input.apply)
504
- args.push("--apply");
505
- pushOptionalString(args, "--plan-hash", input.planHash);
506
- return args;
507
- }
508
- function validatePositiveInteger(value, name) {
509
- if (!Number.isSafeInteger(value) || value < 1) {
510
- throw new Error(`${name} must be a positive integer`);
511
- }
512
- }
513
- var SELECTOR_KINDS = ["line", "hash", "symbol", "page", "node", "asset"];
514
- function isSelectorKind(value) {
515
- return SELECTOR_KINDS.includes(value);
516
- }
517
- function parsePositiveSelectorInt(raw, name) {
518
- if (!/^-?\d+$/.test(raw))
519
- throw new Error(`invalid ${name} \`${raw}\``);
520
- const parsed = Number(raw);
521
- if (!Number.isSafeInteger(parsed))
522
- throw new Error(`invalid ${name} \`${raw}\``);
523
- if (parsed < 1)
524
- throw new Error(`${name} must be greater than zero`);
525
- return parsed;
526
- }
527
- function parseLineSelector(value, explicitKind) {
528
- const parts = value.split(":");
529
- if (parts.length > 2)
530
- throw new Error("selector has too many components");
531
- const head = parts[0];
532
- if (parts.length === 2) {
533
- if (head.slice(1).includes("-"))
534
- throw new Error("line range cannot include a column");
535
- const line = parsePositiveSelectorInt(head, "line");
536
- const column = parsePositiveSelectorInt(parts[1], "column");
537
- return { kind: "line", value: String(line), column, explicitKind };
538
- }
539
- const dash = head.indexOf("-", 1);
540
- if (dash > 0) {
541
- const start = parsePositiveSelectorInt(head.slice(0, dash), "line");
542
- const endLine = parsePositiveSelectorInt(head.slice(dash + 1), "end line");
543
- if (endLine < start)
544
- throw new Error(`end line ${endLine} precedes start line ${start}`);
545
- return { kind: "line", value: String(start), endLine, explicitKind };
546
- }
547
- const line = parsePositiveSelectorInt(head, "line");
548
- return { kind: "line", value: String(line), explicitKind };
549
- }
550
- function parseHashSelector(value, explicitKind) {
551
- const parts = value.split(":");
552
- if (parts.length > 2)
553
- throw new Error("selector has too many components");
554
- const head = parts[0];
555
- if (!/^[0-9a-fA-F]{6}$/.test(head))
556
- throw new Error(`invalid line hash \`${head}\``);
557
- if (parts.length === 2) {
558
- const column = parsePositiveSelectorInt(parts[1], "column");
559
- return { kind: "hash", value: head, column, explicitKind };
560
- }
561
- return { kind: "hash", value: head, explicitKind };
562
- }
563
- function isDocumentSelector(parsed) {
564
- return ["page", "node", "asset"].includes(parsed.kind) || parsed.kind === "line" && !parsed.explicitKind && parsed.column === undefined && parsed.endLine === undefined;
565
- }
566
- function isBindingSelector(parsed) {
567
- if (parsed.endLine !== undefined)
568
- return false;
569
- if (parsed.kind === "line" || parsed.kind === "hash")
570
- return true;
571
- return parsed.kind === "symbol" && !parsed.explicitKind && /^[0-9a-fA-F]{6}$/.test(parsed.value);
572
- }
573
- function parseSelector(text) {
574
- if (text.length === 0)
575
- throw new Error("selector must not be empty");
576
- const separator = text.indexOf(":");
577
- const hasSingleColon = separator >= 0 && text[separator + 1] !== ":";
578
- if (hasSingleColon) {
579
- const kind = text.slice(0, separator);
580
- const value = text.slice(separator + 1);
581
- if (isSelectorKind(kind)) {
582
- if (value.length === 0)
583
- throw new Error(`${kind} selector must not be empty`);
584
- if (kind === "line")
585
- return parseLineSelector(value, true);
586
- if (kind === "hash")
587
- return parseHashSelector(value, true);
588
- if (kind === "page") {
589
- if (value.includes(":"))
590
- throw new Error("page selector has too many components");
591
- parsePositiveSelectorInt(value, "page");
592
- }
593
- return { kind, value, explicitKind: true };
594
- }
595
- if (/^\d+$/.test(kind))
596
- return parseLineSelector(text, false);
597
- if (/^[0-9a-fA-F]{6}$/.test(kind) && /^\d+$/.test(value))
598
- return parseHashSelector(text, false);
599
- throw new Error(`unknown selector kind \`${kind}\`; expected line, hash, symbol, page, node, or asset`);
600
- }
601
- if (/^[0-9-]/.test(text)) {
602
- if (/^[0-9a-fA-F]{6}$/.test(text) && /[a-fA-F]/.test(text)) {
603
- return parseHashSelector(text, false);
604
- }
605
- return parseLineSelector(text, false);
606
- }
607
- if (/^[0-9a-fA-F]{6}$/.test(text) && /\d/.test(text)) {
608
- return parseHashSelector(text, false);
609
- }
610
- if (/\s/.test(text))
611
- throw new Error(`invalid selector \`${text}\``);
612
- return { kind: "symbol", value: text, explicitKind: false };
613
- }
614
- function start(command, input) {
615
- if (!input.path)
616
- throw new Error(`${command} requires a path`);
617
- if (input.stdinName !== undefined && input.path !== "-")
618
- throw new Error("stdinName requires '-' as the target");
619
- const args = [];
620
- pushOptionalString(args, "--readseek-dir", input.readseekDir);
621
- args.push(command, input.path);
622
- pushOptionalString(args, "--stdin-name", input.stdinName);
623
- return args;
624
- }
625
- function at2(args, value) {
626
- if (value !== undefined) {
627
- parseSelector(value);
628
- args.push("--at", value);
629
- }
630
- }
631
- function finish(args) {
632
- args.push("--kdl");
633
- return args;
634
- }
635
- function language(args, input) {
636
- pushOptionalString(args, "--language", input.language);
637
- }
638
- function limit2(args, value) {
639
- if (value !== undefined)
640
- validatePositiveInteger(value, "limit");
641
- pushOptionalNumber(args, "--limit", value);
642
- }
643
- function anchors(args, input) {
644
- if (input.noAnchors)
645
- args.push("--no-anchors");
646
- }
647
- function buildShowArgs(input) {
648
- if (input.end !== undefined)
649
- validatePositiveInteger(input.end, "end");
650
- if (input.end !== undefined && input.limit !== undefined)
651
- throw new Error("cannot combine end with limit");
652
- const args = start("show", input);
653
- at2(args, input.at);
654
- pushOptionalNumber(args, "--end", input.end);
655
- limit2(args, input.limit);
656
- language(args, input);
657
- anchors(args, input);
658
- return finish(args);
659
- }
660
- function buildTreeArgs(input) {
661
- if (input.depth !== undefined && (!Number.isSafeInteger(input.depth) || input.depth < 0))
662
- throw new Error("depth must be a non-negative integer");
663
- const args = start("tree", input);
664
- at2(args, input.at);
665
- pushOptionalNumber(args, "--depth", input.depth);
666
- pushOptionalString(args, "--kind", input.kind);
667
- language(args, input);
668
- if (input.outline)
669
- args.push("--outline");
670
- return finish(args);
671
- }
672
- function buildMetaArgs(input) {
673
- const args = start("meta", input);
674
- language(args, input);
675
- return finish(args);
676
- }
677
- function buildAssetsArgs(input) {
678
- if (input.at !== undefined && !isDocumentSelector(parseSelector(input.at)))
679
- throw new Error("assets requires a page, node, or asset selector");
680
- const args = start("assets", input);
681
- at2(args, input.at);
682
- return finish(args);
683
- }
684
- function buildSyntaxArgs(input) {
685
- const args = start("syntax", input);
686
- language(args, input);
687
- return finish(args);
688
- }
689
- function visionArgs(command, input) {
690
- if (input.level !== undefined && !VISION_LEVELS.includes(input.level))
691
- throw new Error("invalid vision level");
692
- if (input.at !== undefined && !isDocumentSelector(parseSelector(input.at)))
693
- throw new Error("vision requires a document selector");
694
- const args = start(command, input);
695
- at2(args, input.at);
696
- pushOptionalString(args, "--level", input.level);
697
- return args;
698
- }
699
- function buildCaptionArgs(input) {
700
- const args = visionArgs("caption", input);
701
- if (input.include !== undefined) {
702
- if (input.include.length === 0 || input.include.some((task) => task !== "text" && task !== "objects"))
703
- throw new Error("include requires text or objects");
704
- args.push("--include", input.include.join(","));
705
- }
706
- return finish(args);
707
- }
708
- function buildObjectsArgs(input) {
709
- return finish(visionArgs("objects", input));
710
- }
711
- function buildOcrArgs(input) {
712
- return finish(visionArgs("ocr", input));
713
- }
714
- function buildSearchArgs(input) {
715
- const hasPattern = Boolean(input.pattern);
716
- const hasRule = Boolean(input.rule);
717
- const hasContext = Boolean(input.context);
718
- if (hasRule) {
719
- if (hasPattern || hasContext || input.selector)
720
- throw new Error("rule cannot be combined with pattern, context, or selector");
721
- } else if (!hasPattern && !hasContext) {
722
- throw new Error("search requires pattern, context, or rule");
723
- }
724
- if (hasContext && !input.selector) {
725
- throw new Error("context requires selector");
726
- }
727
- if (hasPattern && hasContext) {
728
- throw new Error("pattern and context cannot be combined");
729
- }
730
- const args = start("search", input);
731
- pushOptionalString(args, "--pattern", input.pattern);
732
- pushOptionalString(args, "--context", input.context);
733
- pushOptionalString(args, "--selector", input.selector);
734
- pushOptionalString(args, "--rule", input.rule);
735
- language(args, input);
736
- limit2(args, input.limit);
737
- appendGitScopeArgs(args, input);
738
- anchors(args, input);
739
- return finish(args);
740
- }
741
- function buildGrepArgs(input) {
742
- const validated = validateGrepParams(input);
743
- if (!validated.ok)
744
- throw new Error(validated.error);
745
- const args = ["grep", "--kdl", `--pattern=${input.pattern}`];
746
- const needsPathTerminator = input.path !== undefined && input.path.startsWith("-") && input.path !== "-";
747
- if (input.path !== undefined && !needsPathTerminator)
748
- args.push(input.path);
749
- if (input.literal)
750
- args.push("--literal");
751
- if (input.ignoreCase)
752
- args.push("--ignore-case");
753
- if (input.glob !== undefined)
754
- args.push(`--glob=${input.glob}`);
755
- pushOptionalNumber(args, "--context", input.context);
756
- limit2(args, input.limit ?? 100);
757
- if (input.summary)
758
- args.push("--summary");
759
- pushOptionalString(args, "--scope", input.scope);
760
- pushOptionalNumber(args, "--scope-context", input.scopeContext);
761
- appendGitScopeArgs(args, input);
762
- if (input.path !== undefined && needsPathTerminator)
763
- args.push("--", input.path);
764
- return args;
765
- }
766
- function buildDefArgs(input) {
767
- const args = start("def", input);
768
- args.push("--name", input.name);
769
- language(args, input);
770
- appendGitScopeArgs(args, input);
771
- anchors(args, input);
772
- return finish(args);
773
- }
774
- function buildRefsArgs(input) {
775
- const validated = validateReferencesSelection(input);
776
- if (!validated.ok)
777
- throw new Error(validated.error);
778
- if (input.at !== undefined && !isBindingSelector(parseSelector(input.at)))
779
- throw new Error("references requires a line or hash selector");
780
- const args = start("refs", input);
781
- pushOptionalString(args, "--name", input.name);
782
- at2(args, input.at);
783
- language(args, input);
784
- appendGitScopeArgs(args, input);
785
- anchors(args, input);
786
- return finish(args);
787
- }
788
- function buildCheckArgs(input) {
789
- const args = start("check", input);
790
- args.push("--rules", input.rules);
791
- appendGitScopeArgs(args, input);
792
- return finish(args);
793
- }
794
- function buildEditArgs(input) {
795
- const args = start("edit", input);
796
- appendApplyAndPlanHash(args, input);
797
- language(args, input);
798
- appendGitScopeArgs(args, input);
799
- if (input.requestFromStdin)
800
- args.push("--edits", "-");
801
- return finish(args);
802
- }
803
- function buildRenameArgs(input) {
804
- if (!isBindingSelector(parseSelector(input.at)))
805
- throw new Error("rename requires a line or hash selector");
806
- const args = start("rename", input);
807
- at2(args, input.at);
808
- args.push("--to", input.to);
809
- if (input.workspace !== undefined)
810
- args.push(`--workspace=${input.workspace}`);
811
- appendApplyAndPlanHash(args, { ...input, flagOrder: input.flagOrder ?? "plan-hash-first" });
812
- language(args, input);
813
- appendGitScopeArgs(args, input);
814
- return finish(args);
815
- }
816
- // ../readseek-api/src/client-output.ts
817
- import { Type } from "@sinclair/typebox";
818
- import { AssertError, Value } from "@sinclair/typebox/value";
819
- var OPERATIONS = ["Clone", "Clean", "Default", "Assert"];
820
- function parse(schema, value, what) {
821
- try {
822
- return Value.Parse(OPERATIONS, schema, value);
823
- } catch (error) {
824
- if (!(error instanceof AssertError))
825
- throw error;
826
- const detail = error.error;
827
- throw new Error(`invalid readseek ${what}${detail?.path ?? ""}: ${detail?.message ?? "invalid value"}`);
828
- }
829
- }
830
- var Int = Type.Integer({ minimum: Number.MIN_SAFE_INTEGER, maximum: Number.MAX_SAFE_INTEGER });
831
- var Str = Type.String();
832
- var Bool = Type.Boolean();
833
- var OptStr = Type.Optional(Str);
834
- var OptInt = Type.Optional(Int);
835
- var Hashline = Type.Object({ line: Int, hash: Str, text: Str });
836
- var Hashlines = Type.Array(Hashline);
837
- var ReadOutput = Type.Object({
838
- file: Str,
839
- language: Str,
840
- line_count: Int,
841
- file_hash: Str,
842
- start_line: Int,
843
- end_line: Int,
844
- hashlines: Hashlines,
845
- truncated: Type.Optional(Bool)
846
- });
847
- var SymbolOutput = Type.Object({
848
- kind: Str,
849
- name: Str,
850
- qualified_name: OptStr,
851
- start_line: Int,
852
- end_line: Int,
853
- start_hash: OptStr,
854
- end_hash: OptStr,
855
- start_anchor: OptStr,
856
- end_anchor: OptStr
857
- });
858
- function mapNodeShape(child) {
859
- return Type.Object({
860
- kind: Str,
861
- name: Str,
862
- start_line: Int,
863
- end_line: Int,
864
- start_anchor: Str,
865
- end_anchor: Str,
866
- children: Type.Array(child)
867
- });
868
- }
869
- function recursiveStructureNode() {
870
- return Type.Recursive((self) => mapNodeShape(self));
871
- }
872
- var StructureNode = typeof Type.Recursive === "function" ? recursiveStructureNode() : Type.Cyclic({ StructureNode: mapNodeShape(Type.Ref("StructureNode")) }, "StructureNode");
873
- var StructureOutput = Type.Object({
874
- file: Str,
875
- language: Str,
876
- line_count: Int,
877
- file_hash: Str,
878
- root: Type.Optional(StructureNode),
879
- symbols: Type.Array(SymbolOutput)
880
- });
881
- var SearchSpan = {
882
- start_byte: OptInt,
883
- end_byte: OptInt,
884
- text: OptStr,
885
- start_line: Int,
886
- end_line: Int,
887
- start_hash: Str,
888
- end_hash: Str,
889
- hashlines: Hashlines
890
- };
891
- var SearchCapture = Type.Object({ name: Str, ...SearchSpan });
892
- var SearchMatch = Type.Object({
893
- pattern_index: Type.Integer({ default: 0 }),
894
- ...SearchSpan,
895
- captures: Type.Array(SearchCapture)
896
- });
897
- var SearchFileOutput = Type.Object({
898
- file: Str,
899
- language: Str,
900
- file_hash: Str,
901
- matches: Type.Array(SearchMatch)
902
- });
903
- var SearchEnvelope = Type.Object({
904
- results: Type.Array(SearchFileOutput),
905
- returned_matches: OptInt,
906
- truncated: Type.Optional(Bool),
907
- byte_basis: OptStr
908
- });
909
- var RefsEnvelope = Type.Object({
910
- references: Type.Array(Type.Object({
911
- file: Str,
912
- line: Int,
913
- column: Int,
914
- line_hash: Str,
915
- text: Str,
916
- symbol: Type.Optional(Type.Object({ qualified_name: OptStr }))
917
- }))
918
- });
919
- var Diagnostic = Type.Object({
920
- kind: Type.Union([Type.Literal("error"), Type.Literal("missing")]),
921
- start_line: Int,
922
- end_line: Int
923
- });
924
- var CheckEnvelope = Type.Object({
925
- file_hash: OptStr,
926
- error_count: Int,
927
- missing_count: Int,
928
- diagnostics: Type.Array(Diagnostic)
929
- });
930
- var DetectedObject = Type.Object({
931
- label: Str,
932
- bbox: Type.Tuple([Int, Int, Int, Int])
933
- });
934
- var SourceDetection = Type.Object({
935
- kind: Type.Literal("source"),
936
- type: Str,
937
- file: Str,
938
- language: Str,
939
- engine: OptStr,
940
- supported: Bool,
941
- mime: OptStr,
942
- syntax: OptStr
943
- });
944
- var ImageDetection = Type.Object({
945
- kind: Type.Literal("image"),
946
- type: Str,
947
- file: Str,
948
- mime: OptStr,
949
- format: Str,
950
- width: Int,
951
- height: Int,
952
- animated: Bool,
953
- ocr: OptStr,
954
- caption: OptStr,
955
- objects: Type.Optional(Type.Array(DetectedObject))
956
- });
957
- var TextDetection = Type.Object({
958
- kind: Type.Literal("text"),
959
- type: Str,
960
- file: Str,
961
- mime: OptStr
962
- });
963
- var PdfDetection = Type.Object({
964
- kind: Type.Literal("pdf"),
965
- type: Type.Literal("application/pdf"),
966
- file: Str,
967
- mime: OptStr,
968
- format: Type.Literal("pdf"),
969
- pages: Int
970
- });
971
- var Detection = Type.Union([SourceDetection, ImageDetection, TextDetection, PdfDetection]);
972
- var SourceDetectionInput = Type.Omit(SourceDetection, ["kind"]);
973
- var ImageDetectionInput = Type.Omit(ImageDetection, ["kind"]);
974
- var TextDetectionInput = Type.Omit(TextDetection, ["kind"]);
975
- var PdfDetectionInput = Type.Omit(PdfDetection, ["kind"]);
976
- var UnspannedContent = Type.Omit(ReadOutput, ["start_line", "end_line"]);
977
- var PdfMetadata = Type.Object({ source: Str, format: Type.Literal("pdf"), pages: Int });
978
- var DocumentCache = Type.Object({
979
- content_hash: Str,
980
- state: Type.Union([Type.Literal("built"), Type.Literal("reused")])
981
- });
982
- var Identifier = Type.Object({
983
- text: Str,
984
- start_column: Int,
985
- end_column: Int,
986
- start_byte: Int,
987
- end_byte: Int
988
- });
989
- var CursorEnvelope = Type.Object({
990
- file: Str,
991
- language: Str,
992
- engine: OptStr,
993
- line_count: Int,
994
- file_hash: Str,
995
- line: Int,
996
- column: Int,
997
- line_hash: Str,
998
- identifier: Type.Optional(Identifier),
999
- symbol: Type.Optional(Type.Object({
1000
- name: Str,
1001
- kind: Str,
1002
- qualified_name: Str,
1003
- start_line: Int,
1004
- end_line: Int
1005
- }))
1006
- });
1007
- var EditOutputSchema = Type.Object({
1008
- file: Str,
1009
- before_hash: Str,
1010
- file_hash: Str,
1011
- plan_hash: Str,
1012
- applied: Bool,
1013
- changed: Bool,
1014
- edit_count: Int,
1015
- before_content: OptStr,
1016
- content: OptStr
1017
- });
1018
- var RenameConflictSchema = Type.Object({ line: Int, column: Int, reason: Str });
1019
- var RenameEditSchema = Type.Object({
1020
- line: Int,
1021
- start_column: Int,
1022
- end_column: Int,
1023
- start_byte: Int,
1024
- end_byte: Int,
1025
- occurrence: Str,
1026
- line_hash: Str,
1027
- text: Str
1028
- });
1029
- var Conflicts = Type.Array(RenameConflictSchema, { default: [] });
1030
- var Edits = Type.Array(RenameEditSchema, { default: [] });
1031
- var RenameFileOutputSchema = Type.Object({
1032
- file: Str,
1033
- language: Str,
1034
- engine: OptStr,
1035
- file_hash: Str,
1036
- conflicts: Conflicts,
1037
- edits: Edits
1038
- });
1039
- var RenameOutputSchema = Type.Object({
1040
- file: Str,
1041
- language: Str,
1042
- engine: OptStr,
1043
- file_hash: Str,
1044
- old_name: Str,
1045
- new_name: Str,
1046
- plan_hash: Str,
1047
- applied: Bool,
1048
- conflicts: Conflicts,
1049
- edits: Edits,
1050
- others: Type.Array(RenameFileOutputSchema, { default: [] })
1051
- });
1052
- var DefEnvelope = Type.Object({
1053
- locations: Type.Array(Type.Object({
1054
- file: Str,
1055
- line: Int,
1056
- column: Int,
1057
- line_hash: Str,
1058
- text: Str,
1059
- kind: OptStr,
1060
- name: OptStr,
1061
- qualified_name: OptStr
1062
- }))
1063
- });
1064
- function parseReadOutput(value) {
1065
- return parse(ReadOutput, value, "read output");
1066
- }
1067
- function parseStructureOutput(value) {
1068
- return parse(StructureOutput, value, "structure output");
1069
- }
1070
- function parseSearchOutput(value) {
1071
- const envelope = parse(SearchEnvelope, value, "search output");
1072
- const results = envelope.results;
1073
- if (envelope.returned_matches !== undefined)
1074
- results.returned_matches = envelope.returned_matches;
1075
- if (envelope.truncated !== undefined)
1076
- results.truncated = envelope.truncated;
1077
- if (envelope.byte_basis !== undefined)
1078
- results.byte_basis = envelope.byte_basis;
1079
- return results;
1080
- }
1081
- function parseRefsOutput(value) {
1082
- return parse(RefsEnvelope, value, "refs output").references.map(({ symbol, ...reference }) => ({
1083
- ...reference,
1084
- enclosingSymbol: symbol?.qualified_name
1085
- }));
1086
- }
1087
- function parseCheckOutput(value) {
1088
- const output = parse(CheckEnvelope, value, "check output");
1089
- return {
1090
- file_hash: output.file_hash,
1091
- errorCount: output.error_count,
1092
- missingCount: output.missing_count,
1093
- diagnostics: output.diagnostics
1094
- };
1095
- }
1096
- function parseDetectOutput(value) {
1097
- const output = value ?? {};
1098
- if (output.type === "application/pdf") {
1099
- return { kind: "pdf", ...parse(PdfDetectionInput, value, "detect output") };
1100
- }
1101
- if (output.width !== undefined || output.height !== undefined) {
1102
- return { kind: "image", ...parse(ImageDetectionInput, value, "detect output") };
1103
- }
1104
- if (output.language !== undefined) {
1105
- return { kind: "source", ...parse(SourceDetectionInput, value, "detect output") };
1106
- }
1107
- return { kind: "text", ...parse(TextDetectionInput, value, "detect output") };
1108
- }
1109
- function parseTextContent(value) {
1110
- const output = value ?? {};
1111
- if (output.hashlines === undefined || output.start_line !== undefined)
1112
- return parseReadOutput(value);
1113
- const spanned = parse(UnspannedContent, value, "content");
1114
- return {
1115
- ...spanned,
1116
- start_line: spanned.hashlines[0]?.line ?? 1,
1117
- end_line: spanned.hashlines[spanned.hashlines.length - 1]?.line ?? 0
1118
- };
1119
- }
1120
- function parseCursorOutput(value) {
1121
- return parse(CursorEnvelope, value, "cursor output");
1122
- }
1123
- function parsePdfMetadata(value) {
1124
- if (!value || typeof value !== "object")
1125
- return;
1126
- if (value.format !== "pdf")
1127
- return;
1128
- const document = parse(PdfMetadata, value, "inspect metadata");
1129
- return { kind: "pdf", type: "application/pdf", file: document.source, format: "pdf", pages: document.pages };
1130
- }
1131
- function parseEditOutput(value) {
1132
- return parse(EditOutputSchema, value, "edit output");
1133
- }
1134
- function parseRenameOutput(value) {
1135
- return parse(RenameOutputSchema, value, "rename output");
1136
- }
1137
- function parseDefOutput(value) {
1138
- return parse(DefEnvelope, value, "def output").locations;
1139
- }
1140
- var Bbox = Type.Object({ x: Type.Number(), y: Type.Number(), width: Type.Number(), height: Type.Number() });
1141
- var Position = { page: OptInt, destination: OptStr, bbox: Type.Optional(Bbox) };
1142
- var Provenance = { inferred: Type.Optional(Bool), model: OptStr, level: OptStr, task: OptStr };
1143
- var ImageDescriptor = Type.Object({
1144
- id: OptStr,
1145
- kind: Type.Optional(Type.Literal("image")),
1146
- content_identity: OptStr,
1147
- path: Str,
1148
- mime: Str,
1149
- width: Int,
1150
- height: Int,
1151
- caption: OptStr,
1152
- ocr: OptStr,
1153
- objects: Type.Optional(Type.Array(DetectedObject)),
1154
- ...Provenance
1155
- });
1156
- var DocumentNode = Type.Object({
1157
- id: Str,
1158
- kind: Str,
1159
- parent_id: OptStr,
1160
- title: OptStr,
1161
- level: OptInt,
1162
- column: OptInt,
1163
- text: OptStr,
1164
- ...Position
1165
- });
1166
- var DocumentAsset = Type.Object({
1167
- id: Str,
1168
- kind: Str,
1169
- mime: Str,
1170
- path: OptStr,
1171
- content_identity: OptStr,
1172
- bytes: OptInt,
1173
- ...Position
1174
- });
1175
- var DocumentVision = Type.Object({
1176
- asset_id: Str,
1177
- mode: OptStr,
1178
- caption: OptStr,
1179
- ocr: OptStr,
1180
- objects: Type.Optional(Type.Array(DetectedObject)),
1181
- caption_requested: Type.Optional(Bool),
1182
- objects_requested: Type.Optional(Bool),
1183
- ocr_requested: Type.Optional(Bool),
1184
- ...Provenance
1185
- });
1186
- var DocumentOutput = Type.Object({
1187
- id: OptStr,
1188
- format: Str,
1189
- source: Str,
1190
- title: OptStr,
1191
- pages: Int,
1192
- nodes: Type.Array(DocumentNode, { default: [] }),
1193
- assets: Type.Array(DocumentAsset, { default: [] }),
1194
- vision: Type.Array(DocumentVision, { default: [] })
1195
- });
1196
- var GrepCount = Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER });
1197
- var GrepPosition = Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER });
1198
- var GrepAnchor = Type.String({ pattern: "^[1-9][0-9]*:[0-9a-f]{6}$" });
1199
- var GrepLineSchema = Type.Object({
1200
- line: GrepPosition,
1201
- hash: Type.String({ pattern: "^[0-9a-f]{6}$" }),
1202
- text: Str,
1203
- kind: Type.Union([Type.Literal("match"), Type.Literal("context")])
1204
- });
1205
- var GrepHitSchema = Type.Object({ line: GrepPosition, column: GrepPosition, start_byte: GrepCount, end_byte: GrepCount, text: Str, anchor: GrepAnchor });
1206
- var GrepSymbolSchema = Type.Object({ name: Str, kind: Str, start_line: GrepPosition, end_line: GrepPosition, lines: Type.Array(GrepLineSchema) });
1207
- var GrepSourceResultSchema = Type.Object({
1208
- file: Str,
1209
- file_hash: Str,
1210
- language: Str,
1211
- total_matches: GrepCount,
1212
- returned_matches: GrepCount,
1213
- hits: Type.Array(GrepHitSchema),
1214
- lines: Type.Array(GrepLineSchema),
1215
- symbols: Type.Array(GrepSymbolSchema)
1216
- });
1217
- var GrepDocumentHitSchema = Type.Object({ node_id: Str, kind: Str, snippet: Str, line: GrepPosition, page: Type.Optional(GrepPosition) });
1218
- var GrepDocumentResultSchema = Type.Object({ file: Str, content_hash: Str, total_matches: GrepCount, returned_matches: GrepCount, hits: Type.Array(GrepDocumentHitSchema) });
1219
- var GrepOutputSchema = Type.Object({
1220
- pattern: Str,
1221
- mode: Type.Union([Type.Literal("regex"), Type.Literal("literal")]),
1222
- ignore_case: Bool,
1223
- summary: Bool,
1224
- total_matches: GrepCount,
1225
- returned_matches: GrepCount,
1226
- truncated: Bool,
1227
- count_unit: Type.Literal("lines"),
1228
- scope: Type.Optional(Type.Literal("symbol")),
1229
- results: Type.Array(GrepSourceResultSchema),
1230
- documents: Type.Array(GrepDocumentResultSchema)
1231
- });
1232
- var RuleFinding = Type.Object({
1233
- name: Str,
1234
- message: Str,
1235
- path: Str,
1236
- language: Str,
1237
- start_byte: Int,
1238
- end_byte: Int,
1239
- line: Int,
1240
- column: Int,
1241
- end_line: Int,
1242
- end_column: Int
1243
- });
1244
- var RulesOutput = Type.Object({
1245
- complete: Bool,
1246
- check_count: Int,
1247
- file_count: Int,
1248
- violation_count: Int,
1249
- diagnostics: Type.Array(RuleFinding)
1250
- });
1251
- function parseDocumentOutput(value) {
1252
- return parse(DocumentOutput, value, "document output");
1253
- }
1254
- function parseContentOutput(value) {
1255
- const output = value;
1256
- if (output?.format !== undefined)
1257
- return parseDocumentOutput(value);
1258
- if (!output || output.metadata === undefined || output.content === undefined)
1259
- throw new Error("invalid readseek content: missing metadata or content");
1260
- const metadata = parseDetectOutput(output.metadata);
1261
- return {
1262
- metadata,
1263
- content: metadata.kind === "image" ? parse(ImageDescriptor, output.content, "image descriptor") : parseTextContent(output.content),
1264
- ...output.cursor !== undefined ? { cursor: parseCursorOutput(output.cursor) } : {}
1265
- };
1266
- }
1267
- function parseStructureEnvelope(value) {
1268
- const output = value;
1269
- if (output?.format !== undefined)
1270
- return parseDocumentOutput(value);
1271
- if (!output || output.structure === undefined)
1272
- throw new Error("invalid readseek structure: missing structure");
1273
- return { ...output.metadata !== undefined ? { metadata: parseDetectOutput(output.metadata) } : {}, structure: parseStructureOutput(output.structure) };
1274
- }
1275
- function parseGrepOutput(value) {
1276
- const output = parse(GrepOutputSchema, value, "grep output");
1277
- const invalid = (message) => {
1278
- throw new Error(`invalid readseek grep output: ${message}`);
1279
- };
1280
- const groups = [...output.results, ...output.documents];
1281
- if (output.returned_matches > output.total_matches || groups.reduce((sum, group) => sum + group.total_matches, 0) !== output.total_matches || groups.reduce((sum, group) => sum + group.returned_matches, 0) !== output.returned_matches)
1282
- invalid("inconsistent counts");
1283
- for (const group of groups) {
1284
- if (group.total_matches === 0 || group.returned_matches > group.total_matches)
1285
- invalid("inconsistent file counts");
1286
- if (output.summary ? group.hits.length !== 0 : group.hits.length !== group.returned_matches)
1287
- invalid("inconsistent hit count");
1288
- }
1289
- for (const result of output.results) {
1290
- if (output.summary && (result.lines.length > 0 || result.symbols.length > 0))
1291
- invalid("summary contains display entries");
1292
- if (output.scope !== "symbol" && result.symbols.length > 0)
1293
- invalid("symbols require symbol scope");
1294
- for (const hit of result.hits) {
1295
- if (hit.end_byte < hit.start_byte || Number(hit.anchor.split(":")[0]) !== hit.line)
1296
- invalid("invalid hit span or anchor");
1297
- }
1298
- for (const symbol of result.symbols) {
1299
- if (symbol.end_line < symbol.start_line || symbol.lines.some((line) => line.line < symbol.start_line || line.line > symbol.end_line))
1300
- invalid("invalid symbol range");
1301
- }
1302
- }
1303
- return output;
1304
- }
1305
- function parseRulesOutput(value) {
1306
- return parse(RulesOutput, value, "rules output");
1307
- }
1308
- var SourceAssetsOutput = Type.Object({ file: OptStr, metadata: Type.Optional(Detection), assets: Type.Array(DocumentAsset, { default: [] }) });
1309
- function parseAssetsOutput(value) {
1310
- const raw = value;
1311
- if (raw?.format !== undefined)
1312
- return parseDocumentOutput(value);
1313
- if (!raw || raw.file === undefined && raw.metadata === undefined)
1314
- throw new Error("invalid readseek assets output: missing file or metadata");
1315
- return parse(SourceAssetsOutput, { ...raw, ...raw.metadata !== undefined ? { metadata: parseDetectOutput(raw.metadata) } : {} }, "assets output");
1316
- }
1317
- var ReadSeekOutput = Object.freeze({
1318
- content: parseContentOutput,
1319
- structureEnvelope: parseStructureEnvelope,
1320
- structure: parseStructureOutput,
1321
- read: parseReadOutput,
1322
- pdfMetadata: parsePdfMetadata,
1323
- detect: parseDetectOutput,
1324
- assets: parseAssetsOutput,
1325
- check: parseCheckOutput,
1326
- rules: parseRulesOutput,
1327
- search: parseSearchOutput,
1328
- grep: parseGrepOutput,
1329
- def: parseDefOutput,
1330
- refs: parseRefsOutput,
1331
- edit: parseEditOutput,
1332
- rename: parseRenameOutput,
1333
- cursor: parseCursorOutput
1334
- });
1335
-
1336
- // ../readseek-api/src/edit-plan.ts
1337
- import { Document, Node, format } from "@bgotink/kdl";
1338
- function node(name, properties, children = []) {
1339
- const result = Node.create(name);
1340
- for (const [key, value] of Object.entries(properties))
1341
- result.setProperty(key, value);
1342
- if (children.length > 0)
1343
- result.children = new Document(children);
1344
- return result;
1345
- }
1346
- function editNode(edit) {
1347
- if ("set_line" in edit) {
1348
- const value = edit.set_line;
1349
- return node("set-line", { anchor: value.anchor, text: value.new_text });
1350
- }
1351
- if ("replace_lines" in edit) {
1352
- const value = edit.replace_lines;
1353
- return node("replace-lines", { start: value.start_anchor, end: value.end_anchor, text: value.new_text });
1354
- }
1355
- if ("insert_after" in edit) {
1356
- const value = edit.insert_after;
1357
- return node("insert-after", { anchor: value.anchor, text: value.new_text });
1358
- }
1359
- if ("replace_symbol" in edit) {
1360
- const value = edit.replace_symbol;
1361
- return node("replace-symbol", { symbol: value.symbol, body: value.new_body });
1362
- }
1363
- const value = edit.replace;
1364
- return node("replace", {
1365
- old: value.old_text,
1366
- new: value.new_text,
1367
- ...value.all === undefined ? {} : { all: value.all }
1368
- });
1369
- }
1370
- function serializeEditPlan(edits) {
1371
- const validation = validateExactlyOneEditVariant(edits);
1372
- if (!validation.ok)
1373
- throw new Error(validation.error);
1374
- return format(new Document([node("plan", {}, validation.edits.map(editNode))]));
1375
- }
1376
-
1377
- // ../readseek-api/src/client.ts
1378
- function classifyReadSeekFailure(err) {
1379
- const failure = err;
1380
- const message = String(failure?.message ?? err);
1381
- const missing = failure?.code === "ENOENT" || /Cannot find package|Cannot find module|no such file/i.test(message);
1382
- if (missing) {
1383
- return { code: "readseek-not-installed", message, hint: "Run npm install to install @jarkkojs/readseek." };
1384
- }
1385
- return { code: "readseek-execution-error", message };
1386
- }
1387
- function runOptions(options, vision = false) {
1388
- return {
1389
- signal: options.signal,
1390
- stdin: options.stdin,
1391
- timeoutMs: options.timeoutMs,
1392
- cancelable: options.cancelable,
1393
- ...vision ? { vision: true } : {}
1394
- };
1395
- }
1396
- function createReadSeekClient(runner) {
1397
- return {
1398
- async show(path, options = {}) {
1399
- const value = await runner.kdl(buildShowArgs({ ...options, path }), runOptions(options));
1400
- return ReadSeekOutput.content(value);
1401
- },
1402
- async tree(path, options = {}) {
1403
- const value = await runner.kdl(buildTreeArgs({ ...options, path }), runOptions(options));
1404
- return ReadSeekOutput.structureEnvelope(value);
1405
- },
1406
- async meta(path, options = {}) {
1407
- const value = await runner.kdl(buildMetaArgs({ ...options, path }), runOptions(options));
1408
- return ReadSeekOutput.pdfMetadata(value) ?? ReadSeekOutput.detect(value?.metadata);
1409
- },
1410
- async assets(path, options = {}) {
1411
- const value = await runner.kdl(buildAssetsArgs({ ...options, path }), runOptions(options));
1412
- return ReadSeekOutput.assets(value);
1413
- },
1414
- async syntax(path, options = {}) {
1415
- const value = await runner.kdl(buildSyntaxArgs({ ...options, path }), runOptions(options));
1416
- return ReadSeekOutput.check(value?.diagnostics ?? value);
1417
- },
1418
- async check(path, options) {
1419
- const value = await runner.kdl(buildCheckArgs({ ...options, path }), runOptions(options));
1420
- return ReadSeekOutput.rules(value);
1421
- },
1422
- async caption(path, options = {}) {
1423
- const value = await runner.kdl(buildCaptionArgs({ ...options, path }), runOptions(options, true));
1424
- return ReadSeekOutput.content(value);
1425
- },
1426
- async objects(path, options = {}) {
1427
- const value = await runner.kdl(buildObjectsArgs({ ...options, path }), runOptions(options, true));
1428
- return ReadSeekOutput.content(value);
1429
- },
1430
- async ocr(path, options = {}) {
1431
- const value = await runner.kdl(buildOcrArgs({ ...options, path }), runOptions(options, true));
1432
- return ReadSeekOutput.content(value);
1433
- },
1434
- async search(path, options) {
1435
- const value = await runner.kdl(buildSearchArgs({ ...options, path }), runOptions(options));
1436
- return ReadSeekOutput.search(value);
1437
- },
1438
- async grep(params) {
1439
- const value = await runner.kdl(buildGrepArgs(params), runOptions(params));
1440
- return ReadSeekOutput.grep(value);
1441
- },
1442
- async def(path, options) {
1443
- const value = await runner.kdl(buildDefArgs({ ...options, path }), runOptions(options));
1444
- return ReadSeekOutput.def(value);
1445
- },
1446
- async refs(path, options) {
1447
- const value = await runner.kdl(buildRefsArgs({ ...options, path }), runOptions(options));
1448
- return ReadSeekOutput.refs(value);
1449
- },
1450
- async edit(path, edits, options = {}) {
1451
- const stdin = serializeEditPlan(edits);
1452
- return ReadSeekOutput.edit(await runner.kdl(buildEditArgs({ ...options, path, requestFromStdin: true }), runOptions({ ...options, stdin })));
1453
- },
1454
- async rename(path, options) {
1455
- const value = await runner.kdl(buildRenameArgs({ ...options, path }), runOptions(options));
1456
- return ReadSeekOutput.rename(value);
1457
- }
1458
- };
1459
- }
1460
- // ../readseek-api/src/show-presentation.ts
1461
- function isShowTool(name) {
1462
- return name === "show" || name === "tree" || name === "meta" || name === "assets";
1463
- }
1464
- function record(value) {
1465
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
1466
- }
1467
- function records(value) {
1468
- return Array.isArray(value) ? value.map(record) : [];
1469
- }
1470
- function text(value) {
1471
- return typeof value === "string" ? value : "";
1472
- }
1473
- function count(value) {
1474
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
1475
- }
1476
- function safe(value, preserveTabs = false) {
1477
- return value.replace(/[\x00-\x09\x0b-\x1f\x7f-\x9f]/g, (char) => {
1478
- if (char === "\t")
1479
- return preserveTabs ? char : "\\t";
1480
- if (char === "\r")
1481
- return "\\r";
1482
- return `\\x${char.charCodeAt(0).toString(16).padStart(2, "0")}`;
1483
- });
1484
- }
1485
- function inline(value) {
1486
- return safe(text(value)).replaceAll(`
1487
- `, "\\n");
1488
- }
1489
- function plural(n, unit) {
1490
- return `${n} ${unit}${n === 1 ? "" : "s"}`;
1491
- }
1492
- function fields(value, omit = []) {
1493
- return Object.entries(value).flatMap(([key, item]) => {
1494
- if (omit.includes(key) || item === undefined || item === null || typeof item === "object")
1495
- return [];
1496
- const label = key.replaceAll("_", " ");
1497
- return [`${label[0]?.toUpperCase() ?? ""}${label.slice(1)}: ${safe(String(item))}`];
1498
- }).join(`
1499
- `);
1500
- }
1501
- function location(value) {
1502
- const start = text(value.start_anchor) || (count(value.start_line) !== undefined ? `${value.start_line}${text(value.start_hash) ? `:${value.start_hash}` : ""}` : "");
1503
- const end = text(value.end_anchor) || (count(value.end_line) !== undefined ? `${value.end_line}${text(value.end_hash) ? `:${value.end_hash}` : ""}` : "");
1504
- return start ? ` ${inline(start)}${end && end !== start ? ` - ${inline(end)}` : ""}` : "";
1505
- }
1506
- function sourceStructure(structure) {
1507
- const sections = [];
1508
- if (structure.root) {
1509
- const lines = [];
1510
- const stack = [{ node: record(structure.root), depth: 0 }];
1511
- while (stack.length > 0) {
1512
- const { node, depth } = stack.pop();
1513
- lines.push(`${" ".repeat(Math.min(depth, 12))}${inline(node.kind) || "node"}${text(node.name) ? ` ${inline(node.name)}` : ""}${location(node)}`);
1514
- const children = records(node.children);
1515
- for (let i = children.length - 1;i >= 0; i--)
1516
- stack.push({ node: children[i], depth: depth + 1 });
1517
- }
1518
- sections.push(`Tree
1519
- ${lines.join(`
1520
- `)}`);
1521
- }
1522
- const symbols = records(structure.symbols);
1523
- if (symbols.length > 0) {
1524
- sections.push(`Symbols
1525
- ${symbols.map((symbol) => `${inline(symbol.kind) || "symbol"} ${inline(symbol.qualified_name || symbol.name)}${location(symbol)}`).join(`
1526
- `)}`);
1527
- }
1528
- return sections.join(`
1529
-
1530
- `) || "No structure found in this selection.";
1531
- }
1532
- function documentNodes(nodes, content) {
1533
- const depths = new Map;
1534
- return nodes.map((node) => {
1535
- const depth = Math.min((depths.get(text(node.parent_id)) ?? -1) + 1, 12);
1536
- depths.set(text(node.id), depth);
1537
- const indent = " ".repeat(depth);
1538
- const label = inline(node.title) || inline(node.kind) || "node";
1539
- const page = count(node.page);
1540
- const selector = text(node.id) ? `node:${inline(node.id)}` : "";
1541
- const position = [selector, page !== undefined ? `page:${page}` : ""].filter(Boolean).join(" · ");
1542
- const heading = `${indent}${label}${position ? ` [${position}]` : ""}`;
1543
- const body = text(node.text);
1544
- return content && body ? `${heading}
1545
- ${safe(body).split(`
1546
- `).map((line) => indent + line).join(`
1547
- `)}` : heading;
1548
- }).join(content ? `
1549
-
1550
- ` : `
1551
- `);
1552
- }
1553
- function assetList(assets) {
1554
- return assets.map((asset) => {
1555
- const id = text(asset.id);
1556
- const page = count(asset.page);
1557
- const heading = [id ? `asset:${inline(id)}` : inline(asset.kind) || "image", inline(asset.mime), page !== undefined ? `page:${page}` : ""].filter(Boolean).join(" · ");
1558
- const details = fields(asset, ["id", "kind", "mime", "page", "bbox", "content_identity"]);
1559
- return `${heading}${details ? `
1560
- ${details.split(`
1561
- `).map((line) => ` ${line}`).join(`
1562
- `)}` : ""}`;
1563
- }).join(`
1564
-
1565
- `);
1566
- }
1567
- function presentShowResult(tool, value, options = {}) {
1568
- const output = record(value);
1569
- const metadata = record(output.metadata);
1570
- const content = record(output.content);
1571
- const cursor = record(output.cursor);
1572
- const structure = record(output.structure);
1573
- const document = typeof output.format === "string" && (Array.isArray(output.nodes) || typeof output.source === "string");
1574
- const path = inline(options.path || output.source || output.file || content.file || structure.file || metadata.file || cursor.file) || "(unknown path)";
1575
- const summary = [];
1576
- const result = { summary: "", body: "", notices: [], metadata: {} };
1577
- if (tool === "meta") {
1578
- const data = Object.keys(metadata).length > 0 ? metadata : output;
1579
- if (text(data.format || data.language || data.type))
1580
- summary.push(inline(data.format || data.language || data.type));
1581
- if (count(data.pages) !== undefined) {
1582
- result.metadata.pages = data.pages;
1583
- summary.push(plural(result.metadata.pages, "page"));
1584
- }
1585
- result.body = fields(data) || "No metadata available.";
1586
- } else if (tool === "assets") {
1587
- const assets = records(output.assets);
1588
- result.metadata.assets = assets.length;
1589
- summary.push(plural(assets.length, "asset"));
1590
- result.body = assetList(assets) || "No assets in this selection.";
1591
- } else if (document) {
1592
- const nodes = records(output.nodes);
1593
- const assets = records(output.assets);
1594
- result.metadata.nodes = nodes.length;
1595
- if (count(output.pages) !== undefined)
1596
- result.metadata.pages = output.pages;
1597
- summary.push(plural(nodes.length, "node"));
1598
- if (result.metadata.pages !== undefined)
1599
- summary.push(plural(result.metadata.pages, "page"));
1600
- const sections = [text(output.title) ? safe(text(output.title)) : "", documentNodes(nodes, tool === "show")];
1601
- if (assets.length > 0) {
1602
- result.metadata.assets = assets.length;
1603
- sections.push(`Assets
1604
- ${assetList(assets)}`);
1605
- }
1606
- result.body = sections.filter(Boolean).join(`
1607
-
1608
- `) || "No content in this selection.";
1609
- } else if (tool === "tree") {
1610
- const symbols = records(structure.symbols);
1611
- result.metadata.symbols = symbols.length;
1612
- summary.push(plural(symbols.length, "symbol"));
1613
- result.body = sourceStructure(structure);
1614
- } else if (content.kind === "image" || count(content.width) !== undefined && count(content.height) !== undefined || count(metadata.width) !== undefined && count(metadata.height) !== undefined || text(content.mime).startsWith("image/") || text(metadata.mime).startsWith("image/") || text(metadata.type).startsWith("image/")) {
1615
- const description = Object.keys(content).length > 0 ? content : Object.keys(metadata).length > 0 ? metadata : output;
1616
- if (count(description.width) !== undefined && count(description.height) !== undefined) {
1617
- summary.push(`${description.width} × ${description.height}`);
1618
- } else if (count(metadata.width) !== undefined && count(metadata.height) !== undefined) {
1619
- summary.push(`${metadata.width} × ${metadata.height}`);
1620
- }
1621
- const mime = text(description.mime || metadata.mime || metadata.type);
1622
- if (mime)
1623
- summary.push(inline(mime));
1624
- result.body = fields(description, ["hashlines"]) || fields(metadata) || "No content in this selection.";
1625
- } else if (Array.isArray(content.hashlines) || Array.isArray(cursor.hashlines)) {
1626
- const lines = records(content.hashlines ?? cursor.hashlines);
1627
- const start = count(content.start_line) ?? count(lines[0]?.line);
1628
- const end = count(content.end_line) ?? count(lines.at(-1)?.line);
1629
- const total = count(content.line_count) ?? count(cursor.line_count);
1630
- if (start !== undefined && end !== undefined && start <= end) {
1631
- result.metadata.start_line = start;
1632
- result.metadata.end_line = end;
1633
- summary.push(`lines ${start}-${end}${total !== undefined ? ` of ${total}` : ""}`);
1634
- } else
1635
- summary.push(plural(lines.length, "line"));
1636
- const lang = text(metadata.language || content.language);
1637
- if (lang)
1638
- summary.push(inline(lang));
1639
- const rows = lines.map((line) => `${line.line}${options.noAnchors ? "" : `:${text(line.hash)}`} | ${safe(text(line.text), true)}`);
1640
- const identifier = record(cursor.identifier);
1641
- if (count(cursor.line) !== undefined)
1642
- result.metadata.line = cursor.line;
1643
- if (count(cursor.column) !== undefined)
1644
- result.metadata.column = cursor.column;
1645
- if (Object.keys(cursor).length > 0) {
1646
- const symbol = record(cursor.symbol);
1647
- const description = [text(identifier.text), text(symbol.qualified_name || symbol.name), text(symbol.kind)].filter(Boolean);
1648
- rows.unshift(`Cursor: ${cursor.line ?? "?"}:${cursor.column ?? "?"}${description.length > 0 ? ` · ${[...new Set(description)].map(inline).join(" · ")}` : ""}`, "");
1649
- }
1650
- result.body = rows.join(`
1651
- `) || "Empty source selection.";
1652
- if (start !== undefined && start > 1)
1653
- result.notices.push(`Earlier lines omitted. Read preceding content with at: line:1 and limit: ${start - 1}.`);
1654
- if (end !== undefined && total !== undefined && end < total) {
1655
- result.notices.push(`More lines available. Continue with at: line:${end + 1}.`);
1656
- } else if (content.truncated === true && (end === undefined || total === undefined)) {
1657
- result.notices.push(`Content is truncated.${end !== undefined ? ` Continue with at: line:${end + 1}.` : " Select a smaller range with at and limit."}`);
1658
- }
1659
- } else {
1660
- const description = Object.keys(content).length > 0 ? content : output;
1661
- result.body = fields(description) || "No content in this selection.";
1662
- }
1663
- if (tool === "tree")
1664
- result.notices.push("Structure is limited to the requested depth, kind, and outline. Use a deeper depth or focus with at to inspect further.");
1665
- if (text(output.warning))
1666
- result.notices.push(safe(text(output.warning)));
1667
- result.summary = summary.join(" · ") || "complete";
1668
- return result;
1669
- }
1670
- function formatShowResult(presentation) {
1671
- return [presentation.summary, presentation.body, ...presentation.notices.map((notice) => `Note: ${notice}`)].filter(Boolean).join(`
1672
-
1673
- `);
1674
- }
1675
- function collectImageAssetPaths(value, paths = new Map) {
1676
- if (!value || typeof value !== "object")
1677
- return paths;
1678
- const item = value;
1679
- if (typeof item.path === "string" && typeof item.mime === "string" && item.mime.startsWith("image/")) {
1680
- paths.set(item.path, item.mime);
1681
- }
1682
- for (const child of Object.values(item))
1683
- collectImageAssetPaths(child, paths);
1684
- return paths;
1685
- }
1686
- // ../readseek-api/src/platform.ts
1687
- import { accessSync, constants as fsConstants, existsSync, statSync } from "node:fs";
1688
- import { createRequire } from "node:module";
1689
- import { homedir } from "node:os";
1690
- import path2 from "node:path";
1691
- var READSEEK_BINARY_ENV = "READSEEK_BINARY";
1692
- var READSEEK_PLATFORM_PACKAGES = {
1693
- "darwin-arm64": "@jarkkojs/readseek-darwin-arm64",
1694
- "linux-arm64": "@jarkkojs/readseek-linux-arm64",
1695
- "linux-x64": "@jarkkojs/readseek-linux-x64",
1696
- "win32-x64": "@jarkkojs/readseek-win32-x64"
1697
- };
1698
- var resolveFromPackage = createRequire(import.meta.url).resolve;
1699
- function readSeekBinaryName(platform = process.platform) {
1700
- if (platform === "linux")
1701
- return "readseek.AppImage";
1702
- return platform === "win32" ? "readseek.exe" : "readseek";
1703
- }
1704
- function readSeekPlatformKey(platform = process.platform, arch = process.arch) {
1705
- return `${platform}-${arch}`;
1706
- }
1707
- function resolveReadSeekBinaryOverride(environment = process.env) {
1708
- const binaryPath = environment[READSEEK_BINARY_ENV];
1709
- if (binaryPath === undefined)
1710
- return null;
1711
- if (!path2.isAbsolute(binaryPath)) {
1712
- throw new Error(`${READSEEK_BINARY_ENV} must be an absolute path to the readseek executable`);
1713
- }
1714
- try {
1715
- if (!statSync(binaryPath).isFile())
1716
- throw new Error("not a regular file");
1717
- accessSync(binaryPath, fsConstants.X_OK);
1718
- } catch (error) {
1719
- throw new Error(`${READSEEK_BINARY_ENV} does not point to an executable file: ${binaryPath}`, {
1720
- cause: error
1721
- });
1722
- }
1723
- return binaryPath;
1724
- }
1725
- function resolveReadSeekBinaryFromPackages(resolver = resolveFromPackage, options = {}) {
1726
- const resolve = typeof resolver === "function" ? resolver : resolver.resolve.bind(resolver);
1727
- const platform = options.platform ?? process.platform;
1728
- const arch = options.arch ?? process.arch;
1729
- const key = readSeekPlatformKey(platform, arch);
1730
- const platformPackage = READSEEK_PLATFORM_PACKAGES[key];
1731
- if (!platformPackage) {
1732
- const supported = Object.keys(READSEEK_PLATFORM_PACKAGES).join(", ");
1733
- throw new Error(`@jarkkojs/readseek ships no binary for ${key}; it supports ${supported}`);
1734
- }
1735
- const metaPackage = options.metaPackage ?? "@jarkkojs/readseek";
1736
- let packageJsonPath;
1737
- try {
1738
- const metaPackageJson = resolve(`${metaPackage}/package.json`);
1739
- const metaPackageDir = path2.dirname(metaPackageJson);
1740
- packageJsonPath = resolve(`${platformPackage}/package.json`, {
1741
- paths: [metaPackageDir]
1742
- });
1743
- } catch {
1744
- packageJsonPath = resolve(`${platformPackage}/package.json`);
1745
- }
1746
- const binaryPath = path2.join(path2.dirname(packageJsonPath), "bin", readSeekBinaryName(platform));
1747
- accessSync(binaryPath, fsConstants.X_OK);
1748
- return binaryPath;
1749
- }
1750
- function resolveReadSeekCacheDir(subPath, options = {}) {
1751
- const env = options.environment ?? process.env;
1752
- const platform = options.platform ?? process.platform;
1753
- const home = options.homedir ? options.homedir() : homedir();
1754
- const cwd = options.cwd ?? process.cwd();
1755
- const localDirName = options.localDirName ?? ".readseek";
1756
- if (localDirName && localDirName.length > 0) {
1757
- let dir = options.walkParents ? path2.resolve(cwd) : cwd;
1758
- while (true) {
1759
- const local = path2.join(dir, localDirName);
1760
- if (existsSync(local))
1761
- return local;
1762
- if (!options.walkParents)
1763
- break;
1764
- const parent = path2.dirname(dir);
1765
- if (parent === dir)
1766
- break;
1767
- dir = parent;
1768
- }
1769
- }
1770
- let base;
1771
- if (options.baseDir !== undefined) {
1772
- base = options.baseDir;
1773
- } else if (platform === "win32") {
1774
- base = env.LOCALAPPDATA ?? path2.join(home, "AppData", "Local");
1775
- } else {
1776
- const xdg = env.XDG_CACHE_HOME?.trim();
1777
- base = xdg && path2.isAbsolute(xdg) ? xdg : path2.join(home, ".cache");
1778
- }
1779
- const pathModule = platform === "win32" ? path2.win32 : path2;
1780
- if (subPath === undefined) {
1781
- return pathModule.join(base, "readseek");
1782
- }
1783
- const parts = Array.isArray(subPath) ? subPath : [subPath];
1784
- return pathModule.join(base, ...parts);
1785
- }
1786
- // ../readseek-api/src/path.ts
1787
- import { homedir as homedir2 } from "node:os";
1788
- import path3 from "node:path";
1789
- var UNICODE_SPACES = /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;
1790
- function expandUserPath(filePath, homedirFn = homedir2) {
1791
- const withoutAt = filePath.startsWith("@") ? filePath.slice(1) : filePath;
1792
- const normalized = withoutAt.replace(UNICODE_SPACES, " ");
1793
- if (normalized === "~")
1794
- return homedirFn();
1795
- if (normalized.startsWith("~/"))
1796
- return homedirFn() + normalized.slice(1);
1797
- return normalized;
1798
- }
1799
- function resolveToCwd(filePath, cwd, homedirFn = homedir2) {
1800
- const expanded = expandUserPath(filePath, homedirFn);
1801
- return path3.isAbsolute(expanded) ? expanded : path3.resolve(cwd, expanded);
1802
- }
1803
- // ../readseek-api/src/error.ts
1804
- var READSEEK_USAGE_HINT = /(?:^|\n)\s*Run readseek(?: [\w-]+)* --help for more information\.?\s*$/;
1805
- function cleanReadSeekErrorText(stderr) {
1806
- return stderr.replace(READSEEK_USAGE_HINT, "").replace(/^error:\s*/i, "").replace(/\s*\n\s*/g, " ").trim();
1807
- }
1808
- // ../readseek-api/src/kdl.ts
1809
- import { parse as parse2 } from "@bgotink/kdl";
1810
- function convertNode(node) {
1811
- if (node.getTag() !== null)
1812
- throw new Error("KDL node annotations are not supported");
1813
- const properties = new Map;
1814
- for (const entry of node.entries) {
1815
- const name = entry.getName();
1816
- if (name === null)
1817
- throw new Error("KDL positional arguments are not supported");
1818
- if (properties.has(name))
1819
- throw new Error(`KDL duplicate property '${name}'`);
1820
- if (entry.getTag() !== null)
1821
- throw new Error("KDL value annotations are not supported");
1822
- const value = entry.getValue();
1823
- if (value === null)
1824
- throw new Error("KDL null values are not supported");
1825
- if (typeof value === "number" && !Number.isFinite(value)) {
1826
- throw new Error("KDL number out of range");
1827
- }
1828
- properties.set(name, value);
1829
- }
1830
- return {
1831
- name: node.getName(),
1832
- properties,
1833
- children: node.children?.nodes.map(convertNode) ?? []
1834
- };
1835
- }
1836
- function parseKdlDocument(text) {
1837
- const document = parse2(text);
1838
- if (document.nodes.length !== 1)
1839
- throw new Error("KDL document must contain exactly one root node");
1840
- return convertNode(document.nodes[0]);
1841
- }
1842
-
1843
- // ../readseek-api/src/output-kdl.ts
1844
- function properties(node) {
1845
- return Object.fromEntries(node.properties);
1846
- }
1847
- function children(node, name) {
1848
- return node.children.filter((child) => child.name === name);
1849
- }
1850
- function child(node, name) {
1851
- return node.children.find((candidate) => candidate.name === name);
1852
- }
1853
- function requireProperty(node, name) {
1854
- const value = node.properties.get(name);
1855
- if (value === undefined)
1856
- throw new Error(`invalid readseek KDL: ${node.name} is missing '${name}'`);
1857
- return value;
1858
- }
1859
- function line(node) {
1860
- const anchor = requireProperty(node, "anchor");
1861
- const content = requireProperty(node, "content");
1862
- if (typeof anchor !== "string" || typeof content !== "string") {
1863
- throw new Error("invalid readseek KDL line");
1864
- }
1865
- const match = /^(\d+):([0-9a-f]+)$/.exec(anchor);
1866
- if (!match)
1867
- throw new Error(`invalid readseek KDL line anchor: ${anchor}`);
1868
- return {
1869
- line: Number(match[1]),
1870
- hash: match[2],
1871
- text: content
1872
- };
1873
- }
1874
- function mapNode(node) {
1875
- return {
1876
- ...properties(node),
1877
- children: children(node, "node").map(mapNode)
1878
- };
1879
- }
1880
- function sourceContent(node) {
1881
- const result = properties(node);
1882
- result.hashlines = children(node, "line").map(line);
1883
- const objects = children(node, "object");
1884
- if (objects.length > 0) {
1885
- result.objects = objects.map((object) => ({
1886
- label: requireProperty(object, "label"),
1887
- bbox: [
1888
- requireProperty(object, "xmin"),
1889
- requireProperty(object, "ymin"),
1890
- requireProperty(object, "xmax"),
1891
- requireProperty(object, "ymax")
1892
- ]
1893
- }));
1894
- }
1895
- return result;
1896
- }
1897
- function sourceMap(node) {
1898
- const root = child(node, "node");
1899
- return {
1900
- ...properties(node),
1901
- ...root ? { root: mapNode(root) } : {},
1902
- symbols: children(node, "symbol").map(properties)
1903
- };
1904
- }
1905
- function diagnostics(node) {
1906
- return {
1907
- ...properties(node),
1908
- diagnostics: children(node, "diagnostic").map(properties)
1909
- };
1910
- }
1911
- function identity(node) {
1912
- const result = properties(node);
1913
- const identifier = child(node, "identifier");
1914
- const symbol = child(node, "symbol");
1915
- if (identifier)
1916
- result.identifier = properties(identifier);
1917
- if (symbol)
1918
- result.symbol = properties(symbol);
1919
- return result;
1920
- }
1921
- function sourceDocument(root) {
1922
- const result = {};
1923
- const metadata = child(root, "metadata");
1924
- const cache = child(root, "cache");
1925
- const content = child(root, "content");
1926
- const structure = child(root, "structure");
1927
- const diagnosticOutput = child(root, "diagnostics");
1928
- const identityOutput = child(root, "cursor");
1929
- if (metadata)
1930
- result.metadata = properties(metadata);
1931
- if (!metadata && !content && !structure && !diagnosticOutput && !identityOutput && root.properties.has("file"))
1932
- result.file = root.properties.get("file");
1933
- const assets = children(root, "asset");
1934
- if (assets.length > 0)
1935
- result.assets = assets.map(genericNode);
1936
- if (cache)
1937
- result.cache = properties(cache);
1938
- if (content)
1939
- result.content = sourceContent(content);
1940
- if (structure)
1941
- result.structure = sourceMap(structure);
1942
- if (diagnosticOutput)
1943
- result.diagnostics = diagnostics(diagnosticOutput);
1944
- if (identityOutput)
1945
- result.cursor = identity(identityOutput);
1946
- return result;
1947
- }
1948
- function hit(node) {
1949
- return {
1950
- ...properties(node),
1951
- hashlines: children(node, "line").map(line),
1952
- captures: children(node, "capture").map((capture) => ({
1953
- ...properties(capture),
1954
- hashlines: children(capture, "line").map(line)
1955
- }))
1956
- };
1957
- }
1958
- function search(root) {
1959
- return {
1960
- ...properties(root),
1961
- results: children(root, "match").map((match) => ({
1962
- ...properties(match),
1963
- matches: children(match, "hit").map(hit)
1964
- })),
1965
- documents: children(root, "document").map((documentNode) => ({
1966
- ...properties(documentNode),
1967
- hits: children(documentNode, "hit").map(properties)
1968
- }))
1969
- };
1970
- }
1971
- function grepChildren(node, allowed) {
1972
- if (node.children.some((child) => !allowed.includes(child.name))) {
1973
- throw new Error(`invalid readseek KDL grep: unexpected child of ${node.name}`);
1974
- }
1975
- }
1976
- function grepLine(node) {
1977
- grepChildren(node, []);
1978
- const parsed = line(node);
1979
- if (requireProperty(node, "number") !== parsed.line)
1980
- throw new Error("invalid readseek KDL grep line number");
1981
- return { ...parsed, kind: requireProperty(node, "kind") };
1982
- }
1983
- function grep(root) {
1984
- grepChildren(root, ["match", "document"]);
1985
- return parseGrepOutput({
1986
- ...properties(root),
1987
- results: children(root, "match").map((match) => {
1988
- grepChildren(match, ["hit", "line", "symbol"]);
1989
- return {
1990
- ...properties(match),
1991
- hits: children(match, "hit").map((hit) => {
1992
- grepChildren(hit, []);
1993
- return properties(hit);
1994
- }),
1995
- lines: children(match, "line").map(grepLine),
1996
- symbols: children(match, "symbol").map((symbol) => {
1997
- grepChildren(symbol, ["line"]);
1998
- return { ...properties(symbol), lines: children(symbol, "line").map(grepLine) };
1999
- })
2000
- };
2001
- }),
2002
- documents: children(root, "document").map((document) => {
2003
- grepChildren(document, ["hit"]);
2004
- return { ...properties(document), hits: children(document, "hit").map((hit) => {
2005
- grepChildren(hit, []);
2006
- return properties(hit);
2007
- }) };
2008
- })
2009
- });
2010
- }
2011
- function references(root) {
2012
- const parsed = children(root, "reference").map((reference) => {
2013
- const sourceLine = child(reference, "line");
2014
- if (!sourceLine)
2015
- throw new Error("invalid readseek KDL reference: missing line");
2016
- const parsedLine = line(sourceLine);
2017
- const symbol = child(reference, "symbol");
2018
- return {
2019
- ...properties(reference),
2020
- line_hash: parsedLine.hash,
2021
- text: parsedLine.text,
2022
- ...symbol ? { symbol: properties(symbol) } : {}
2023
- };
2024
- });
2025
- return {
2026
- references: parsed,
2027
- locations: parsed.map((reference) => {
2028
- const { symbol, ...location } = reference;
2029
- return symbol && typeof symbol === "object" ? { ...location, ...symbol } : location;
2030
- })
2031
- };
2032
- }
2033
- function definitions(root) {
2034
- return {
2035
- locations: children(root, "definition").map((definition) => {
2036
- const symbol = child(definition, "symbol");
2037
- const sourceLine = child(definition, "line");
2038
- if (!symbol || !sourceLine) {
2039
- throw new Error("invalid readseek KDL definition: missing symbol or line");
2040
- }
2041
- const symbolProperties = properties(symbol);
2042
- const parsedLine = line(sourceLine);
2043
- const definitionColumn = definition.properties.get("column");
2044
- const nameByte = symbol.properties.get("name_byte");
2045
- const startByte = symbol.properties.get("start_byte");
2046
- let column = 1;
2047
- if (typeof definitionColumn === "number") {
2048
- column = definitionColumn;
2049
- } else if (typeof nameByte === "number" && typeof startByte === "number") {
2050
- column = nameByte - startByte + 1;
2051
- }
2052
- return {
2053
- file: requireProperty(definition, "file"),
2054
- line: parsedLine.line,
2055
- column,
2056
- line_hash: parsedLine.hash,
2057
- text: parsedLine.text,
2058
- kind: symbolProperties.kind,
2059
- name: symbolProperties.name,
2060
- qualified_name: symbolProperties.qualified_name
2061
- };
2062
- })
2063
- };
2064
- }
2065
- function edit(root) {
2066
- const result = properties(root);
2067
- for (const name of ["before_content", "content"]) {
2068
- const contentNode = child(root, name);
2069
- if (contentNode)
2070
- result[name] = requireProperty(contentNode, "content");
2071
- }
2072
- return result;
2073
- }
2074
- function renameEdit(node) {
2075
- const sourceLine = child(node, "line");
2076
- if (!sourceLine)
2077
- throw new Error("invalid readseek KDL rename edit: missing line");
2078
- return {
2079
- ...properties(node),
2080
- text: requireProperty(sourceLine, "content")
2081
- };
2082
- }
2083
- function renameFile(node) {
2084
- return {
2085
- ...properties(node),
2086
- edits: children(node, "edit").map(renameEdit),
2087
- conflicts: children(node, "conflict").map(properties)
2088
- };
2089
- }
2090
- function rename(root) {
2091
- return {
2092
- ...renameFile(root),
2093
- others: children(root, "other").map(renameFile)
2094
- };
2095
- }
2096
- function genericNode(node) {
2097
- const result = properties(node);
2098
- const textNode = child(node, "text");
2099
- const bbox = child(node, "bbox");
2100
- if (textNode)
2101
- result.text = requireProperty(textNode, "content");
2102
- if (bbox)
2103
- result.bbox = properties(bbox);
2104
- const objects = children(node, "object");
2105
- if (objects.length > 0)
2106
- result.objects = objects.map((object) => ({
2107
- label: requireProperty(object, "label"),
2108
- bbox: [requireProperty(object, "x0"), requireProperty(object, "y0"), requireProperty(object, "x1"), requireProperty(object, "y1")]
2109
- }));
2110
- return result;
2111
- }
2112
- function pdfDocument(root) {
2113
- return {
2114
- ...properties(root),
2115
- nodes: children(root, "node").map(genericNode),
2116
- assets: children(root, "asset").map(genericNode),
2117
- vision: children(root, "vision").map(genericNode)
2118
- };
2119
- }
2120
- function parseReadSeekKdl(text) {
2121
- const root = parseKdlDocument(text);
2122
- switch (root.name) {
2123
- case "document":
2124
- return root.properties.has("format") ? pdfDocument(root) : sourceDocument(root);
2125
- case "search":
2126
- return ["mode", "ignore_case", "summary", "count_unit"].some((key) => root.properties.has(key)) ? grep(root) : search(root);
2127
- case "check":
2128
- return diagnostics(root);
2129
- case "refs":
2130
- return references(root);
2131
- case "def":
2132
- return definitions(root);
2133
- case "edit":
2134
- return edit(root);
2135
- case "edit-batch":
2136
- return { ...properties(root), files: children(root, "file").map(edit) };
2137
- case "rename":
2138
- return rename(root);
2139
- default:
2140
- throw new Error(`unsupported readseek KDL root: ${root.name}`);
2141
- }
2142
- }
2143
- // ../readseek-api/src/process.ts
2144
- var DEFAULT_READSEEK_TIMEOUT_MS = 120000;
2145
- var DEFAULT_MAX_OUTPUT_BYTES = 32 * 1024 * 1024;
2146
- function resolveProcessLimits(options = {}) {
2147
- return {
2148
- timeoutMs: options.timeoutMs ?? DEFAULT_READSEEK_TIMEOUT_MS,
2149
- maxOutputBytes: options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
2150
- cancelable: options.cancelable !== false
2151
- };
2152
- }
2153
- function readSeekCancellationError(signal) {
2154
- const reason = signal?.reason;
2155
- return reason instanceof Error && reason.name !== "AbortError" ? reason : new Error("readseek cancelled");
2156
- }
2157
- function failureFromProcessResult(result, options = {}) {
2158
- if (options.overflow) {
2159
- return new Error(`readseek ${options.overflow} exceeded the ${options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES}-byte output limit`);
2160
- }
2161
- if (options.timedOut) {
2162
- return new Error(`readseek timed out after ${options.timeoutMs ?? DEFAULT_READSEEK_TIMEOUT_MS} ms`);
2163
- }
2164
- const cleaned = cleanReadSeekErrorText(result.stderr);
2165
- if (cleaned)
2166
- return new Error(cleaned);
2167
- if (result.signal)
2168
- return new Error(`readseek killed by signal ${result.signal}`);
2169
- return new Error(`readseek exited with status ${result.exitCode}`);
2170
- }
2171
- function acceptsReadSeekExitCode(args, exitCode) {
2172
- if (exitCode === 0)
2173
- return true;
2174
- if (exitCode !== 1)
2175
- return false;
2176
- let index = 0;
2177
- const valued = new Set(["-C", "--directory", "--output", "--readseek-dir"]);
2178
- while (index < args.length) {
2179
- const arg = args[index];
2180
- if (valued.has(arg)) {
2181
- index += 2;
2182
- continue;
2183
- }
2184
- if ([...valued].some((flag) => arg.startsWith(`${flag}=`)) || arg === "--kdl") {
2185
- index++;
2186
- continue;
2187
- }
2188
- return arg === "grep" || arg === "search" || arg === "def" || arg === "refs" || arg === "syntax" || arg === "check";
2189
- }
2190
- return false;
2191
- }
2192
- function ensureSuccessfulStdout(result, args = []) {
2193
- if (!result.signal && acceptsReadSeekExitCode(args, result.exitCode))
2194
- return result.stdout;
2195
- throw failureFromProcessResult(result);
2196
- }
2197
- // ../readseek-api/src/process-node.ts
2198
- import { spawn } from "node:child_process";
2199
- import { StringDecoder } from "node:string_decoder";
2200
- function attachBoundedStream(stream, maxOutputBytes, onOverflow) {
2201
- const decoder = new StringDecoder("utf8");
2202
- let text = "";
2203
- let bytes = 0;
2204
- let overflowed = false;
2205
- stream.on("data", (chunk) => {
2206
- if (overflowed)
2207
- return;
2208
- const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
2209
- bytes += buffer.length;
2210
- if (bytes > maxOutputBytes) {
2211
- overflowed = true;
2212
- onOverflow();
2213
- return;
2214
- }
2215
- text += decoder.write(buffer);
2216
- });
2217
- return {
2218
- text: () => text + decoder.end()
2219
- };
2220
- }
2221
- async function runReadSeekNode(binaryPath, args, options = {}) {
2222
- const limits = resolveProcessLimits(options);
2223
- if (limits.cancelable && options.signal?.aborted) {
2224
- throw readSeekCancellationError(options.signal);
2225
- }
2226
- return await new Promise((resolve, reject) => {
2227
- let settled = false;
2228
- let child;
2229
- let timer;
2230
- const finish = (result) => {
2231
- if (settled)
2232
- return;
2233
- settled = true;
2234
- if (timer !== undefined)
2235
- clearTimeout(timer);
2236
- options.signal?.removeEventListener("abort", onAbort);
2237
- resolve(result);
2238
- };
2239
- const fail = (error) => {
2240
- if (settled)
2241
- return;
2242
- settled = true;
2243
- if (timer !== undefined)
2244
- clearTimeout(timer);
2245
- options.signal?.removeEventListener("abort", onAbort);
2246
- reject(error instanceof Error ? error : new Error(String(error)));
2247
- };
2248
- const terminate = (error) => {
2249
- if (settled)
2250
- return;
2251
- fail(error);
2252
- try {
2253
- child.kill("SIGKILL");
2254
- } catch {}
2255
- };
2256
- const onAbort = () => {
2257
- terminate(readSeekCancellationError(options.signal));
2258
- };
2259
- try {
2260
- child = spawn(binaryPath, [...args], {
2261
- cwd: options.cwd,
2262
- env: process.env,
2263
- shell: false,
2264
- stdio: [options.stdin === undefined ? "ignore" : "pipe", "pipe", "pipe"],
2265
- windowsHide: true
2266
- });
2267
- } catch (error) {
2268
- fail(error);
2269
- return;
2270
- }
2271
- const stdout = attachBoundedStream(child.stdout, limits.maxOutputBytes, () => {
2272
- terminate(failureFromProcessResult({ stdout: "", stderr: "", exitCode: null, signal: null }, { overflow: "stdout", maxOutputBytes: limits.maxOutputBytes }));
2273
- });
2274
- const stderr = attachBoundedStream(child.stderr, limits.maxOutputBytes, () => {
2275
- terminate(failureFromProcessResult({ stdout: "", stderr: "", exitCode: null, signal: null }, { overflow: "stderr", maxOutputBytes: limits.maxOutputBytes }));
2276
- });
2277
- timer = setTimeout(() => {
2278
- terminate(failureFromProcessResult({ stdout: "", stderr: "", exitCode: null, signal: null }, { timedOut: true, timeoutMs: limits.timeoutMs }));
2279
- }, limits.timeoutMs);
2280
- timer.unref?.();
2281
- if (limits.cancelable && options.signal) {
2282
- options.signal.addEventListener("abort", onAbort, { once: true });
2283
- }
2284
- if (options.stdin !== undefined) {
2285
- child.stdin.on("error", (error) => {
2286
- if (error.code !== "EPIPE")
2287
- fail(error);
2288
- });
2289
- child.stdin.end(options.stdin, "utf8");
2290
- }
2291
- child.on("error", fail);
2292
- child.on("close", (code, signal) => {
2293
- finish({
2294
- stdout: stdout.text(),
2295
- stderr: stderr.text(),
2296
- exitCode: code,
2297
- signal
2298
- });
2299
- });
2300
- });
2301
- }
2302
- async function runReadSeekNodeText(binaryPath, args, options = {}) {
2303
- return ensureSuccessfulStdout(await runReadSeekNode(binaryPath, args, options), args);
2304
- }
2305
8
  // src/tool-prompt-metadata.ts
9
+ import {
10
+ REPLACEABLE_TOOLS,
11
+ TOOL_NAMES,
12
+ renderCompactGuidelines,
13
+ renderToolDescription
14
+ } from "@jarkkojs/readseek-api";
2306
15
  var REPLACEABLE_BY_TOOL = new Map(REPLACEABLE_TOOLS.map((entry) => [entry.tool, entry]));
2307
16
  function toolNameFromPrompt(fileName) {
2308
17
  const name = fileName.replace(/\.md$/, "");
@@ -2344,57 +53,6 @@ function defineToolPromptMetadata(options) {
2344
53
 
2345
54
  // src/edit-diff.ts
2346
55
  import * as Diff from "diff";
2347
-
2348
- // src/hashline.ts
2349
- import xxhashWasm from "xxhash-wasm";
2350
- var ANCHOR_MASK = 16777215;
2351
- var HASHLINE_STATE_KEY = Symbol.for("pi-readseek.hashlineState.v1");
2352
- function getHashlineState() {
2353
- const globalObject = globalThis;
2354
- const state = globalObject[HASHLINE_STATE_KEY] ?? {
2355
- h32Fn: null,
2356
- initPromise: null
2357
- };
2358
- globalObject[HASHLINE_STATE_KEY] = state;
2359
- return state;
2360
- }
2361
- async function ensureHashInit() {
2362
- const state = getHashlineState();
2363
- if (state.h32Fn)
2364
- return;
2365
- if (!state.initPromise) {
2366
- state.initPromise = xxhashWasm().then((hasher) => {
2367
- state.h32Fn = hasher.h32;
2368
- }).catch((error) => {
2369
- state.initPromise = null;
2370
- throw error;
2371
- });
2372
- }
2373
- await state.initPromise;
2374
- }
2375
- function xxh32(input) {
2376
- const state = getHashlineState();
2377
- if (!state.h32Fn)
2378
- throw new Error("Hash not initialized — call ensureHashInit() first");
2379
- return state.h32Fn(input, 0) >>> 0;
2380
- }
2381
- function canonicalizeLine(line) {
2382
- return line.match(/[^\t\r\n ]+/g)?.join(" ") ?? "";
2383
- }
2384
- function computeLineHash(line) {
2385
- return (xxh32(canonicalizeLine(line)) & ANCHOR_MASK).toString(16).padStart(HASH_LEN, "0");
2386
- }
2387
- var DISPLAY_CONTROL_CHAR_RE = /[\x00-\x08\x0b\x0c\x0e-\x1f]/g;
2388
- function escapeControlCharsForDisplay(text) {
2389
- return text.replace(DISPLAY_CONTROL_CHAR_RE, (ch) => {
2390
- return `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`;
2391
- });
2392
- }
2393
- function formatHashlineDisplay(lineNumber, content) {
2394
- return `${lineNumber}:${computeLineHash(content)}|${escapeControlCharsForDisplay(content)}`;
2395
- }
2396
-
2397
- // src/edit-diff.ts
2398
56
  function normalizeToLF(text) {
2399
57
  return text.replace(/\r\n/g, `
2400
58
  `).replace(/\r/g, `
@@ -2475,7 +133,7 @@ function generateDiffString(oldContent, newContent, contextLines = 4) {
2475
133
  return { diff: output.join(`
2476
134
  `), firstChangedLine };
2477
135
  }
2478
- function generateCompactOrFullDiff(oldContent, newContent, contextLines = 4) {
136
+ function generateCompactOrFullDiff(oldContent, newContent, anchors = new Map, contextLines = 4) {
2479
137
  if (oldContent === newContent)
2480
138
  return { diff: "", firstChangedLine: undefined };
2481
139
  const oldLines = oldContent.split(`
@@ -2497,10 +155,9 @@ function generateCompactOrFullDiff(oldContent, newContent, contextLines = 4) {
2497
155
  const lineNum = changedIndex + 1;
2498
156
  const oldLine = oldLines[changedIndex] ?? "";
2499
157
  const newLine = newLines[changedIndex] ?? "";
2500
- const oldHash = computeLineHash(oldLine);
2501
- const newHash = computeLineHash(newLine);
158
+ const newHash = anchors.get(lineNum);
2502
159
  return {
2503
- diff: `${lineNum}:${oldHash}|${oldLine} → ${lineNum}:${newHash}|${newLine}`,
160
+ diff: `${lineNum}|${oldLine} → ${newHash === undefined ? lineNum : `${lineNum}:${newHash}`}|${newLine}`,
2504
161
  firstChangedLine: lineNum
2505
162
  };
2506
163
  }
@@ -2524,15 +181,21 @@ function generateCompactOrFullDiff(oldContent, newContent, contextLines = 4) {
2524
181
  if (!failed && deletedIndex !== -1 && j === newLines.length) {
2525
182
  const lineNum = deletedIndex + 1;
2526
183
  const oldLine = oldLines[deletedIndex] ?? "";
2527
- const oldHash = computeLineHash(oldLine);
2528
184
  return {
2529
- diff: `${lineNum}:${oldHash}|${oldLine} → [deleted]`,
185
+ diff: `${lineNum}|${oldLine} → [deleted]`,
2530
186
  firstChangedLine: lineNum
2531
187
  };
2532
188
  }
2533
189
  }
2534
190
  return generateDiffString(oldContent, newContent, contextLines);
2535
191
  }
192
+
193
+ // src/path-utils.ts
194
+ import {
195
+ expandUserPath,
196
+ resolveToCwd
197
+ } from "@jarkkojs/readseek-api";
198
+
2536
199
  // src/runtime.ts
2537
200
  function throwIfAborted(signal) {
2538
201
  if (signal?.aborted)
@@ -2660,8 +323,9 @@ function buildReadSeekLineWithHash(line, hash, raw) {
2660
323
  display: escapeControlCharsForDisplay(raw)
2661
324
  };
2662
325
  }
2663
- function buildReadSeekLine(line, raw) {
2664
- return buildReadSeekLineWithHash(line, computeLineHash(raw), raw);
326
+ var DISPLAY_CONTROL_CHAR_RE = /[\x00-\x08\x0b\x0c\x0e-\x1f]/g;
327
+ function escapeControlCharsForDisplay(text) {
328
+ return text.replace(DISPLAY_CONTROL_CHAR_RE, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`);
2665
329
  }
2666
330
  function formatAnchoredFileBlocks(files, lineSuffix) {
2667
331
  const blocks = [];
@@ -2861,15 +525,14 @@ function classifyEdit(oldContent, newContent) {
2861
525
  }
2862
526
 
2863
527
  // src/readseek-client.ts
2864
- import { statSync as statSync3 } from "node:fs";
2865
- import { createRequire as createRequire2 } from "node:module";
2866
- import { homedir as homedir4 } from "node:os";
2867
- import path4 from "node:path";
528
+ import { createRequire } from "node:module";
529
+ import { ReadSeekHost } from "@jarkkojs/readseek-api";
2868
530
 
2869
531
  // src/readseek-settings.ts
2870
- import { readFileSync, statSync as statSync2 } from "node:fs";
2871
- import { homedir as homedir3 } from "node:os";
532
+ import { readFileSync, statSync } from "node:fs";
533
+ import { homedir } from "node:os";
2872
534
  import { join } from "node:path";
535
+ import { isRecord } from "@jarkkojs/readseek-api";
2873
536
  var READSEEK_TOOL_REPLACEMENTS = {
2874
537
  read: "readSeek_show",
2875
538
  edit: "readSeek_edit",
@@ -3016,7 +679,7 @@ function validateSettings(raw, source) {
3016
679
  var settingsFileCache = new Map;
3017
680
  function statFileOrNull(path) {
3018
681
  try {
3019
- return statSync2(path);
682
+ return statSync(path);
3020
683
  } catch {
3021
684
  return null;
3022
685
  }
@@ -3052,7 +715,7 @@ function mergeSettings(base, override) {
3052
715
  return settings;
3053
716
  }
3054
717
  function resolveReadSeekJsonSettings() {
3055
- const globalResult = readSettingsFile(join(homedir3(), ".pi/agent/settings.json"));
718
+ const globalResult = readSettingsFile(join(homedir(), ".pi/agent/settings.json"));
3056
719
  const projectResult = readSettingsFile(join(process.cwd(), ".pi/settings.json"));
3057
720
  return {
3058
721
  settings: mergeSettings(globalResult.settings, projectResult.settings),
@@ -3073,108 +736,23 @@ function resolveReadSeekToolDisplayMode(tool) {
3073
736
  }
3074
737
 
3075
738
  // src/readseek-client.ts
3076
- var resolveFromHost = createRequire2(import.meta.url).resolve;
3077
- function readSeekBinaryPath() {
3078
- return resolveReadSeekBinaryOverride() ?? resolveReadSeekBinaryFromPackages(resolveFromHost);
3079
- }
739
+ import {
740
+ classifyReadSeekFailure
741
+ } from "@jarkkojs/readseek-api";
742
+ var host = new ReadSeekHost({
743
+ resolve: createRequire(import.meta.url).resolve,
744
+ timeoutMs: resolveReadSeekTimeoutMs
745
+ });
3080
746
  function readSeekBinaryAvailability() {
3081
- try {
3082
- readSeekBinaryPath();
3083
- return { available: true };
3084
- } catch (err) {
3085
- return { available: false, reason: classifyReadSeekFailure(err).message };
3086
- }
3087
- }
3088
- var defaultReadSeekDirInit;
3089
- function directoryExists(dir) {
3090
- try {
3091
- return statSync3(dir).isDirectory();
3092
- } catch {
3093
- return false;
3094
- }
747
+ const availability = host.availability();
748
+ return availability.available ? { available: true } : availability;
3095
749
  }
3096
- var DEFAULT_READSEEK_VISION_TIMEOUT_MS = 30 * 60000;
3097
- function readSeekTimeoutMs() {
3098
- return resolveReadSeekTimeoutMs() ?? DEFAULT_READSEEK_TIMEOUT_MS;
750
+ var readSeekClient = host.client();
751
+ async function readAnchors(path, options = {}) {
752
+ const envelope = await readSeekClient.show(path, options);
753
+ const content = "content" in envelope ? envelope.content : undefined;
754
+ return content && "hashlines" in content ? content.hashlines : [];
3099
755
  }
3100
- async function ensureDefaultReadSeekDir() {
3101
- const home = homedir4();
3102
- if (!home)
3103
- return null;
3104
- const fallback = path4.join(home, ".pi", "readseek");
3105
- const dir = resolveReadSeekCacheDir("readseek", {
3106
- baseDir: path4.join(home, ".pi"),
3107
- walkParents: true
3108
- });
3109
- if (dir !== fallback)
3110
- return null;
3111
- if (directoryExists(dir))
3112
- return dir;
3113
- defaultReadSeekDirInit ??= runReadSeekNodeText(readSeekBinaryPath(), ["--readseek-dir", dir, "init"], { timeoutMs: readSeekTimeoutMs() }).then(() => directoryExists(dir) ? dir : null).catch(() => null).finally(() => {
3114
- defaultReadSeekDirInit = undefined;
3115
- });
3116
- return defaultReadSeekDirInit;
3117
- }
3118
- function supportsReadSeekDir(args) {
3119
- const first = args[0];
3120
- return first === "init" || first === "show" || first === "assets" || first === "caption" || first === "objects" || first === "ocr";
3121
- }
3122
- async function readSeekInvocationArgs(args) {
3123
- if (!supportsReadSeekDir(args))
3124
- return [...args];
3125
- const readSeekDir = await ensureDefaultReadSeekDir();
3126
- return readSeekDir ? ["--readseek-dir", readSeekDir, ...args] : [...args];
3127
- }
3128
- var visionInvocationTail = Promise.resolve();
3129
- async function runReadSeekVisionRaw(args, options = {}) {
3130
- let release;
3131
- const gate = new Promise((resolve) => {
3132
- release = resolve;
3133
- });
3134
- const predecessor = visionInvocationTail;
3135
- visionInvocationTail = predecessor.then(() => gate);
3136
- const signal = options.signal;
3137
- try {
3138
- if (signal) {
3139
- signal.throwIfAborted();
3140
- await new Promise((resolve, reject) => {
3141
- const onAbort = () => {
3142
- signal.removeEventListener("abort", onAbort);
3143
- reject(signal.reason);
3144
- };
3145
- signal.addEventListener("abort", onAbort, { once: true });
3146
- predecessor.then(() => {
3147
- signal.removeEventListener("abort", onAbort);
3148
- resolve();
3149
- }, (error) => {
3150
- signal.removeEventListener("abort", onAbort);
3151
- reject(error);
3152
- });
3153
- });
3154
- } else {
3155
- await predecessor;
3156
- }
3157
- signal?.throwIfAborted();
3158
- return await runReadSeekNodeText(readSeekBinaryPath(), await readSeekInvocationArgs(args), {
3159
- signal: options.signal,
3160
- stdin: options.stdin,
3161
- timeoutMs: options.timeoutMs ?? resolveReadSeekTimeoutMs() ?? DEFAULT_READSEEK_VISION_TIMEOUT_MS,
3162
- cancelable: options.cancelable
3163
- });
3164
- } finally {
3165
- release();
3166
- }
3167
- }
3168
- var nodeRunner = {
3169
- text: async (args, options = {}) => options.vision ? runReadSeekVisionRaw(args, options) : runReadSeekNodeText(readSeekBinaryPath(), await readSeekInvocationArgs(args), {
3170
- signal: options.signal,
3171
- stdin: options.stdin,
3172
- timeoutMs: options.timeoutMs ?? readSeekTimeoutMs(),
3173
- cancelable: options.cancelable
3174
- }),
3175
- kdl: async (args, options = {}) => parseReadSeekKdl(await nodeRunner.text(args, options))
3176
- };
3177
- var readSeekClient = createReadSeekClient(nodeRunner);
3178
756
 
3179
757
  // src/edit-syntax-validate.ts
3180
758
  function dedupeSortLines(diagnostics) {
@@ -3761,12 +1339,9 @@ function upsertTextComponent(lastComponent, text) {
3761
1339
  }
3762
1340
 
3763
1341
  // src/register-tool.ts
3764
- import { Type as Type2 } from "@sinclair/typebox";
3765
- function optionalIntOrString(description) {
3766
- return Type2.Optional(Type2.Union([Type2.Number({ description }), Type2.String({ description })]));
3767
- }
3768
- function filePathParam() {
3769
- return Type2.String({ description: PARAM_DESCRIPTIONS.path });
1342
+ import { Type } from "@sinclair/typebox";
1343
+ function intOrString(description) {
1344
+ return Type.Union([Type.Number({ description }), Type.String({ description })]);
3770
1345
  }
3771
1346
  function registerReadSeekTool(pi, tool) {
3772
1347
  pi.registerTool(tool);
@@ -3774,46 +1349,11 @@ function registerReadSeekTool(pi, tool) {
3774
1349
  }
3775
1350
 
3776
1351
  // src/edit.ts
3777
- var hashlineEditItemSchema = Type3.Object({
3778
- set_line: Type3.Optional(Type3.Object({
3779
- anchor: Type3.String({ description: PARAM_DESCRIPTIONS.anchor }),
3780
- new_text: Type3.String({ description: PARAM_DESCRIPTIONS.newTextLine })
3781
- }, { additionalProperties: false, description: PARAM_DESCRIPTIONS.setLine })),
3782
- replace_lines: Type3.Optional(Type3.Object({
3783
- start_anchor: Type3.String({ description: PARAM_DESCRIPTIONS.startAnchor }),
3784
- end_anchor: Type3.String({ description: PARAM_DESCRIPTIONS.endAnchor }),
3785
- new_text: Type3.String({ description: PARAM_DESCRIPTIONS.newTextRange })
3786
- }, { additionalProperties: false, description: PARAM_DESCRIPTIONS.replaceLines })),
3787
- insert_after: Type3.Optional(Type3.Object({
3788
- anchor: Type3.String({ description: PARAM_DESCRIPTIONS.insertAnchor }),
3789
- new_text: Type3.String({ description: PARAM_DESCRIPTIONS.newTextInsert })
3790
- }, { additionalProperties: false, description: PARAM_DESCRIPTIONS.insertAfter })),
3791
- replace: Type3.Optional(Type3.Object({
3792
- old_text: Type3.String({ description: PARAM_DESCRIPTIONS.oldText }),
3793
- new_text: Type3.String({ description: PARAM_DESCRIPTIONS.newText }),
3794
- all: Type3.Optional(Type3.Boolean({ description: PARAM_DESCRIPTIONS.all }))
3795
- }, { additionalProperties: false, description: PARAM_DESCRIPTIONS.replace })),
3796
- replace_symbol: Type3.Optional(Type3.Object({
3797
- symbol: Type3.String({ description: PARAM_DESCRIPTIONS.symbol }),
3798
- new_body: Type3.String({ description: PARAM_DESCRIPTIONS.newBody })
3799
- }, { additionalProperties: false, description: PARAM_DESCRIPTIONS.replaceSymbol }))
3800
- }, {
3801
- additionalProperties: false,
3802
- minProperties: 1,
3803
- maxProperties: 1,
3804
- description: PARAM_DESCRIPTIONS.editVariant
3805
- });
3806
- var hashlineEditSchema = Type3.Object({
3807
- path: filePathParam(),
3808
- language: Type3.Optional(Type3.String({ description: PARAM_DESCRIPTIONS.languageSymbol })),
3809
- edits: Type3.Array(hashlineEditItemSchema, {
3810
- minItems: 1,
3811
- description: PARAM_DESCRIPTIONS.edits
3812
- }),
3813
- postEditVerify: Type3.Optional(Type3.Boolean({
3814
- description: PARAM_DESCRIPTIONS.postEditVerify
3815
- }))
3816
- }, { additionalProperties: false });
1352
+ import { getToolContract, PARAM_DESCRIPTIONS, ReadSeekPlanError, validateExactlyOneEditVariant } from "@jarkkojs/readseek-api";
1353
+ var hashlineEditSchema = Type2.Unsafe(getToolContract("edit").project({
1354
+ omit: ["gitScope", "apply", "planHash"],
1355
+ describe: { language: PARAM_DESCRIPTIONS.languageSymbol }
1356
+ }));
3817
1357
  function buildEditError(path, code, message, hint, errorDetails) {
3818
1358
  return {
3819
1359
  content: [{ type: "text", text: message }],
@@ -3843,7 +1383,6 @@ async function executeEdit(opts) {
3843
1383
  const absolutePath = resolveToCwd(path, cwd);
3844
1384
  throwIfAborted(signal);
3845
1385
  try {
3846
- await ensureHashInit();
3847
1386
  return await withFileMutationQueue(absolutePath, async () => {
3848
1387
  throwIfAborted(signal);
3849
1388
  if (wasReadInSession && !wasReadInSession(absolutePath)) {
@@ -3857,21 +1396,19 @@ async function executeEdit(opts) {
3857
1396
  const edits = parsedEdits.edits;
3858
1397
  let plan;
3859
1398
  try {
3860
- plan = await readSeekClient.edit(absolutePath, edits, { signal, language: parsed.language });
1399
+ plan = await readSeekClient.planEdit(absolutePath, edits, { signal, language: parsed.language });
3861
1400
  } catch (err) {
3862
1401
  throwIfAborted(signal);
1402
+ if (err instanceof ReadSeekPlanError)
1403
+ return buildEditError(absolutePath, err.code, err.message);
3863
1404
  const failure = classifyReadSeekFailure(err);
3864
1405
  const code = failure.message.includes("stale anchor") ? "hash-mismatch" : failure.code;
3865
1406
  return buildEditError(absolutePath, code, failure.message, failure.hint);
3866
1407
  }
3867
- if (typeof plan.before_content !== "string" || typeof plan.content !== "string") {
3868
- return buildEditError(absolutePath, "invalid-output", "readseek edit plan did not include before_content and content");
3869
- }
3870
- const original = plan.before_content;
3871
- const result = plan.content;
1408
+ const { before_content: original, content: result } = plan.output;
3872
1409
  const originalForSyntax = normalizeToLF(stripBom(original).text);
3873
1410
  const resultForSyntax = normalizeToLF(stripBom(result).text);
3874
- if (!plan.changed) {
1411
+ if (!plan.output.changed) {
3875
1412
  return buildEditError(absolutePath, "no-op", `No changes made to ${path}. The edits produced identical content.`);
3876
1413
  }
3877
1414
  const syntaxMode = resolveSyntaxValidateMode({ syntaxValidate });
@@ -3891,22 +1428,15 @@ async function executeEdit(opts) {
3891
1428
  }
3892
1429
  }
3893
1430
  throwIfAborted(signal);
3894
- let applied;
3895
1431
  try {
3896
- applied = await readSeekClient.edit(absolutePath, edits, {
3897
- apply: true,
3898
- planHash: plan.plan_hash,
3899
- language: parsed.language,
3900
- cancelable: false
3901
- });
1432
+ await plan.apply({ signal });
3902
1433
  } catch (err) {
3903
1434
  throwIfAborted(signal);
1435
+ if (err instanceof ReadSeekPlanError)
1436
+ return buildEditError(absolutePath, err.code, err.message);
3904
1437
  const failure = classifyReadSeekFailure(err);
3905
1438
  return buildEditError(absolutePath, failure.code, failure.message, failure.hint);
3906
1439
  }
3907
- if (!applied.applied) {
3908
- return buildEditError(absolutePath, "invalid-output", "readseek did not confirm that the edit was applied");
3909
- }
3910
1440
  onFileMutated?.(absolutePath);
3911
1441
  if (parsed.postEditVerify === true) {
3912
1442
  let verifiedContent;
@@ -3915,11 +1445,13 @@ async function executeEdit(opts) {
3915
1445
  } catch (err) {
3916
1446
  return buildEditError(absolutePath, "post-edit-verification-read-failed", `Edit write completed but post-edit verification failed: could not read ${path} after writing.`, undefined, { fsCode: err?.code, fsMessage: err?.message });
3917
1447
  }
3918
- if (verifiedContent !== plan.content) {
3919
- return buildEditError(absolutePath, "post-edit-verification-mismatch", `Edit write completed but post-edit verification did not confirm the intended content for ${path}. Re-read the file before making follow-up edits.`, undefined, { expectedLength: plan.content.length, actualLength: verifiedContent.length });
1448
+ if (verifiedContent !== result) {
1449
+ return buildEditError(absolutePath, "post-edit-verification-mismatch", `Edit write completed but post-edit verification did not confirm the intended content for ${path}. Re-read the file before making follow-up edits.`, undefined, { expectedLength: result.length, actualLength: verifiedContent.length });
3920
1450
  }
3921
1451
  }
3922
- const diffResult = generateCompactOrFullDiff(original, result);
1452
+ const changedLine = generateCompactOrFullDiff(original, result).firstChangedLine;
1453
+ const anchors = changedLine === undefined ? [] : await readAnchors(absolutePath, { at: `line:${changedLine}`, limit: 1 }).catch(() => []);
1454
+ const diffResult = generateCompactOrFullDiff(original, result, new Map(anchors.map((line) => [line.line, line.hash])));
3923
1455
  const patch = createPatch(path, original, result);
3924
1456
  const diffData = buildDiffData({
3925
1457
  path: absolutePath,
@@ -4059,11 +1591,11 @@ ${theme.fg("error", info.errorText)}`;
4059
1591
  }
4060
1592
 
4061
1593
  // src/grep.ts
4062
- import { Type as Type5 } from "@sinclair/typebox";
1594
+ import { Type as Type3 } from "@sinclair/typebox";
4063
1595
  import { Text as Text4 } from "@earendil-works/pi-tui";
4064
1596
 
4065
1597
  // src/grep-output.ts
4066
- import path5 from "node:path";
1598
+ import path from "node:path";
4067
1599
  import { formatSize, truncateHead } from "@earendil-works/pi-coding-agent";
4068
1600
 
4069
1601
  // src/grep-budget.ts
@@ -4086,11 +1618,11 @@ function resolveGrepOutputBudget() {
4086
1618
  // src/grep-output.ts
4087
1619
  function buildGrepOutput(output, cwd) {
4088
1620
  const recordBlocks = new Map;
4089
- const fileCount = new Set([...output.results, ...output.documents].map((group) => path5.resolve(cwd, group.file))).size;
1621
+ const fileCount = new Set([...output.results, ...output.documents].map((group) => path.resolve(cwd, group.file))).size;
4090
1622
  const blocks = [`[${output.total_matches} matches in ${fileCount} files]`];
4091
1623
  for (const group of output.results) {
4092
- const absolutePath = path5.resolve(cwd, group.file);
4093
- const displayPath = path5.relative(cwd, absolutePath) || absolutePath;
1624
+ const absolutePath = path.resolve(cwd, group.file);
1625
+ const displayPath = path.relative(cwd, absolutePath) || absolutePath;
4094
1626
  if (output.summary) {
4095
1627
  blocks.push(`${absolutePath}: ${group.total_matches} matches`);
4096
1628
  continue;
@@ -4111,8 +1643,8 @@ function buildGrepOutput(output, cwd) {
4111
1643
  }
4112
1644
  }
4113
1645
  for (const group of output.documents) {
4114
- const absolutePath = path5.resolve(cwd, group.file);
4115
- const displayPath = path5.relative(cwd, absolutePath) || absolutePath;
1646
+ const absolutePath = path.resolve(cwd, group.file);
1647
+ const displayPath = path.relative(cwd, absolutePath) || absolutePath;
4116
1648
  if (output.summary) {
4117
1649
  blocks.push(`${absolutePath}: ${group.total_matches} matches`);
4118
1650
  continue;
@@ -4199,6 +1731,12 @@ function formatGrepResultText(input) {
4199
1731
  errorText: undefined
4200
1732
  };
4201
1733
  }
1734
+
1735
+ // src/coerce-obvious-int.ts
1736
+ import {
1737
+ coerceObviousBase10Int
1738
+ } from "@jarkkojs/readseek-api";
1739
+
4202
1740
  // src/tui-source-render.ts
4203
1741
  var GREP_ANCHOR_RE = /^(.*?):(>>| )(\d+):([0-9a-zA-Z]{1,16})\|(.*)$/;
4204
1742
  function renderGrepSourceForDisplay(text, anchors, renderPath = (path) => path) {
@@ -4216,36 +1754,15 @@ function renderGrepSourceForDisplay(text, anchors, renderPath = (path) => path)
4216
1754
  `);
4217
1755
  }
4218
1756
 
4219
- // src/readseek-params.ts
4220
- import { Type as Type4 } from "@sinclair/typebox";
4221
- function searchPathParam() {
4222
- return Type4.Optional(Type4.String({ description: PARAM_DESCRIPTIONS.searchPath }));
4223
- }
4224
- function languageParam() {
4225
- return Type4.Optional(Type4.String({ description: PARAM_DESCRIPTIONS.language }));
4226
- }
4227
- function readSeekGitSearchParams() {
4228
- return {
4229
- gitScope: Type4.Optional(Type4.Union(GIT_SCOPES.map((scope) => Type4.Literal(scope)), { description: PARAM_DESCRIPTIONS.gitScope }))
4230
- };
4231
- }
4232
-
4233
1757
  // src/grep.ts
4234
- var grepSchema = Type5.Object({
4235
- pattern: Type5.String({ description: PARAM_DESCRIPTIONS.grepPattern }),
4236
- path: searchPathParam(),
4237
- glob: Type5.Optional(Type5.String({ description: PARAM_DESCRIPTIONS.glob })),
4238
- ignoreCase: Type5.Optional(Type5.Boolean({ description: PARAM_DESCRIPTIONS.ignoreCase })),
4239
- literal: Type5.Optional(Type5.Boolean({ description: PARAM_DESCRIPTIONS.literal })),
4240
- context: optionalIntOrString(PARAM_DESCRIPTIONS.context),
4241
- limit: optionalIntOrString(PARAM_DESCRIPTIONS.matchLimit),
4242
- summary: Type5.Optional(Type5.Boolean({ description: PARAM_DESCRIPTIONS.summary })),
4243
- scope: Type5.Optional(Type5.Literal("symbol", {
4244
- description: PARAM_DESCRIPTIONS.grepScope
4245
- })),
4246
- scopeContext: optionalIntOrString(PARAM_DESCRIPTIONS.scopeContext),
4247
- ...readSeekGitSearchParams()
4248
- });
1758
+ import { getToolContract as getToolContract2, PARAM_DESCRIPTIONS as PARAM_DESCRIPTIONS2 } from "@jarkkojs/readseek-api";
1759
+ var grepSchema = Type3.Unsafe(getToolContract2("grep").project({
1760
+ replace: {
1761
+ context: intOrString(PARAM_DESCRIPTIONS2.context),
1762
+ limit: intOrString(PARAM_DESCRIPTIONS2.grepLimit),
1763
+ scopeContext: intOrString(PARAM_DESCRIPTIONS2.scopeContext)
1764
+ }
1765
+ }));
4249
1766
  async function executeGrep(opts) {
4250
1767
  const { params, signal, cwd, onFileAnchored } = opts;
4251
1768
  signal?.throwIfAborted();
@@ -4384,8 +1901,8 @@ function registerGrepTool(pi, options = {}) {
4384
1901
  }
4385
1902
 
4386
1903
  // src/search.ts
4387
- import path6 from "node:path";
4388
- import { Type as Type6 } from "@sinclair/typebox";
1904
+ import path2 from "node:path";
1905
+ import { Type as Type4 } from "@sinclair/typebox";
4389
1906
 
4390
1907
  // src/stat-search-path.ts
4391
1908
  import { stat as fsStat } from "node:fs/promises";
@@ -4424,6 +1941,7 @@ function buildSearchOutput(input) {
4424
1941
  }
4425
1942
 
4426
1943
  // src/search.ts
1944
+ import { getToolContract as getToolContract3, PARAM_DESCRIPTIONS as PARAM_DESCRIPTIONS3 } from "@jarkkojs/readseek-api";
4427
1945
  function mergeRanges(ranges) {
4428
1946
  if (ranges.length === 0)
4429
1947
  return [];
@@ -4469,7 +1987,7 @@ function linesFromSearchResult(result, ranges) {
4469
1987
  return lines;
4470
1988
  }
4471
1989
  function readSeekLanguageForPath(language, searchPath, isFile) {
4472
- if (language === "typescript" && isFile && path6.extname(searchPath).toLowerCase() === ".tsx")
1990
+ if (language === "typescript" && isFile && path2.extname(searchPath).toLowerCase() === ".tsx")
4473
1991
  return "tsx";
4474
1992
  return language;
4475
1993
  }
@@ -4504,8 +2022,8 @@ async function executeSearch(opts) {
4504
2022
  }
4505
2023
  const readSeekFiles = [];
4506
2024
  for (const result of results) {
4507
- const abs = path6.isAbsolute(result.file) ? result.file : path6.resolve(cwd, result.file);
4508
- const display = path6.relative(cwd, abs) || abs;
2025
+ const abs = path2.isAbsolute(result.file) ? result.file : path2.resolve(cwd, result.file);
2026
+ const display = path2.relative(cwd, abs) || abs;
4509
2027
  const ranges = result.matches.map((match) => ({ startLine: match.start_line, endLine: match.end_line }));
4510
2028
  const mergedRanges = mergeRanges(ranges);
4511
2029
  const lines = linesFromSearchResult(result, mergedRanges);
@@ -4552,16 +2070,10 @@ function registerSearchTool(pi, options = {}) {
4552
2070
  description: SEARCH_PROMPT_METADATA.description,
4553
2071
  promptSnippet: SEARCH_PROMPT_METADATA.promptSnippet,
4554
2072
  promptGuidelines: SEARCH_PROMPT_METADATA.promptGuidelines,
4555
- parameters: Type6.Object({
4556
- pattern: Type6.Optional(Type6.String({ description: PARAM_DESCRIPTIONS.pattern })),
4557
- context: Type6.Optional(Type6.String({ description: PARAM_DESCRIPTIONS.patternContext })),
4558
- selector: Type6.Optional(Type6.String({ description: PARAM_DESCRIPTIONS.selector })),
4559
- language: languageParam(),
4560
- rule: Type6.Optional(Type6.String({ description: PARAM_DESCRIPTIONS.rule })),
4561
- limit: Type6.Optional(Type6.Integer({ minimum: 1 })),
4562
- path: searchPathParam(),
4563
- ...readSeekGitSearchParams()
4564
- }),
2073
+ parameters: Type4.Unsafe(getToolContract3("search").project({
2074
+ omit: ["stdinName", "noAnchors"],
2075
+ describe: { path: PARAM_DESCRIPTIONS3.searchPath }
2076
+ })),
4565
2077
  async execute(_toolCallId, params, signal, _onUpdate, ctx) {
4566
2078
  return executeSearch({ params, signal, cwd: ctx.cwd, onFileAnchored: options.onFileAnchored });
4567
2079
  },
@@ -4585,8 +2097,8 @@ function registerSearchTool(pi, options = {}) {
4585
2097
  }
4586
2098
 
4587
2099
  // src/refs.ts
4588
- import { Type as Type7 } from "@sinclair/typebox";
4589
- import path7 from "node:path";
2100
+ import { Type as Type5 } from "@sinclair/typebox";
2101
+ import path3 from "node:path";
4590
2102
 
4591
2103
  // src/refs-output.ts
4592
2104
  function refsQueryLabel(input) {
@@ -4616,6 +2128,11 @@ function buildRefsOutput(input) {
4616
2128
  }
4617
2129
 
4618
2130
  // src/refs.ts
2131
+ import {
2132
+ getToolContract as getToolContract4,
2133
+ PARAM_DESCRIPTIONS as PARAM_DESCRIPTIONS4,
2134
+ validateReferencesSelection
2135
+ } from "@jarkkojs/readseek-api";
4619
2136
  var REFS_PROMPT_METADATA = defineToolPromptMetadata({
4620
2137
  toolName: "refs",
4621
2138
  promptSnippet: "Find references by identifier name or cursor binding"
@@ -4630,14 +2147,14 @@ function groupReferences(references, cwd) {
4630
2147
  const files = new Map;
4631
2148
  const seen = new Set;
4632
2149
  for (const reference of references) {
4633
- const abs = path7.isAbsolute(reference.file) ? reference.file : path7.resolve(cwd, reference.file);
2150
+ const abs = path3.isAbsolute(reference.file) ? reference.file : path3.resolve(cwd, reference.file);
4634
2151
  const dedupeKey = `${abs}:${reference.line}:${reference.column}`;
4635
2152
  if (seen.has(dedupeKey))
4636
2153
  continue;
4637
2154
  seen.add(dedupeKey);
4638
2155
  let file = files.get(abs);
4639
2156
  if (!file) {
4640
- file = { displayPath: path7.relative(cwd, abs) || abs, path: abs, lines: [] };
2157
+ file = { displayPath: path3.relative(cwd, abs) || abs, path: abs, lines: [] };
4641
2158
  files.set(abs, file);
4642
2159
  }
4643
2160
  file.lines.push(refsLine(reference));
@@ -4694,13 +2211,10 @@ function registerRefsTool(pi, options = {}) {
4694
2211
  description: REFS_PROMPT_METADATA.description,
4695
2212
  promptSnippet: REFS_PROMPT_METADATA.promptSnippet,
4696
2213
  promptGuidelines: REFS_PROMPT_METADATA.promptGuidelines,
4697
- parameters: Type7.Object({
4698
- name: Type7.Optional(Type7.String({ description: PARAM_DESCRIPTIONS.refsName })),
4699
- path: searchPathParam(),
4700
- language: languageParam(),
4701
- at: Type7.Optional(Type7.String({ description: PARAM_DESCRIPTIONS.at })),
4702
- ...readSeekGitSearchParams()
4703
- }),
2214
+ parameters: Type5.Unsafe(getToolContract4("refs").project({
2215
+ omit: ["noAnchors"],
2216
+ describe: { path: PARAM_DESCRIPTIONS4.searchPath }
2217
+ })),
4704
2218
  async execute(_toolCallId, params, signal, _onUpdate, ctx) {
4705
2219
  return executeRefs({ params, signal, cwd: ctx.cwd, onFileAnchored: options.onFileAnchored });
4706
2220
  },
@@ -4725,20 +2239,18 @@ function registerRefsTool(pi, options = {}) {
4725
2239
  }
4726
2240
 
4727
2241
  // src/rename.ts
4728
- import { Type as Type8 } from "@sinclair/typebox";
4729
- import path8 from "node:path";
2242
+ import { Type as Type6 } from "@sinclair/typebox";
2243
+ import path4 from "node:path";
4730
2244
  import { Text as Text5 } from "@earendil-works/pi-tui";
2245
+ import { getToolContract as getToolContract5, isBindingSelector, PARAM_DESCRIPTIONS as PARAM_DESCRIPTIONS5, parseSelector, ReadSeekPlanError as ReadSeekPlanError2 } from "@jarkkojs/readseek-api";
4731
2246
  var RENAME_PROMPT_METADATA = defineToolPromptMetadata({
4732
2247
  toolName: "rename",
4733
2248
  promptSnippet: "Rename a symbol at a source location with verified edits"
4734
2249
  });
4735
- var renameSchema = Type8.Object({
4736
- path: filePathParam(),
4737
- at: Type8.String({ description: PARAM_DESCRIPTIONS.at }),
4738
- to: Type8.String({ description: PARAM_DESCRIPTIONS.to }),
4739
- workspace: Type8.Optional(Type8.Boolean({ description: PARAM_DESCRIPTIONS.workspace })),
4740
- apply: Type8.Optional(Type8.Boolean({ description: PARAM_DESCRIPTIONS.applyDefaultTrue }))
4741
- });
2250
+ var renameSchema = Type6.Unsafe(getToolContract5("rename").project({
2251
+ omit: ["language", "gitScope", "planHash"],
2252
+ describe: { apply: PARAM_DESCRIPTIONS5.applyDefaultTrue }
2253
+ }));
4742
2254
  async function executeRename(opts) {
4743
2255
  const { params, signal, cwd, onFileMutated } = opts;
4744
2256
  const p = params;
@@ -4756,25 +2268,25 @@ async function executeRename(opts) {
4756
2268
  }
4757
2269
  const filePath = resolveToCwd(p.path, cwd);
4758
2270
  try {
4759
- const output = await readSeekClient.rename(filePath, {
2271
+ const plan = await readSeekClient.planRename(filePath, {
4760
2272
  to: p.to,
4761
2273
  at: p.at,
4762
2274
  workspace: p.workspace ? cwd : undefined,
4763
- apply: p.apply ?? true,
4764
2275
  signal
4765
2276
  });
2277
+ const output = p.apply === false ? plan.output : await plan.apply({ signal });
4766
2278
  if (output.applied) {
4767
2279
  for (const file of [output, ...output.others]) {
4768
2280
  if (file.edits.length === 0)
4769
2281
  continue;
4770
- const absoluteFile = path8.isAbsolute(file.file) ? file.file : path8.resolve(cwd, file.file);
2282
+ const absoluteFile = path4.isAbsolute(file.file) ? file.file : path4.resolve(cwd, file.file);
4771
2283
  onFileMutated?.(absoluteFile);
4772
2284
  }
4773
2285
  }
4774
- const primaryAbs = path8.isAbsolute(output.file) ? output.file : path8.resolve(cwd, output.file);
2286
+ const primaryAbs = path4.isAbsolute(output.file) ? output.file : path4.resolve(cwd, output.file);
4775
2287
  const files = [primaryAbs];
4776
2288
  for (const other of output.others) {
4777
- const abs = path8.isAbsolute(other.file) ? other.file : path8.resolve(cwd, other.file);
2289
+ const abs = path4.isAbsolute(other.file) ? other.file : path4.resolve(cwd, other.file);
4778
2290
  if (!files.includes(abs))
4779
2291
  files.push(abs);
4780
2292
  }
@@ -4807,6 +2319,8 @@ First conflict at ${firstConflict.line}:${firstConflict.column}: ${firstConflict
4807
2319
  }
4808
2320
  };
4809
2321
  } catch (err) {
2322
+ if (err instanceof ReadSeekPlanError2)
2323
+ return buildToolErrorResult("rename", err.code, err.message);
4810
2324
  const failure = classifyReadSeekFailure(err);
4811
2325
  return buildToolErrorResult("rename", failure.code, failure.message, failure.hint ? { hint: failure.hint } : {});
4812
2326
  }
@@ -4856,7 +2370,7 @@ function registerRenameTool(pi, options = {}) {
4856
2370
  });
4857
2371
  if (expanded && output) {
4858
2372
  for (const file of outputs) {
4859
- const display = path8.relative(cwd, file.file) || file.file;
2373
+ const display = path4.relative(cwd, file.file) || file.file;
4860
2374
  text += `
4861
2375
  ${linkedPathLine(theme, file.file, display, cwd, ` (${file.edits.length} edits)`, width)}`;
4862
2376
  }
@@ -4874,7 +2388,7 @@ import { mkdir, readFile, writeFile } from "node:fs/promises";
4874
2388
  import { dirname as dirname2, relative as relative3 } from "node:path";
4875
2389
  import { withFileMutationQueue as withFileMutationQueue2, truncateHead as truncateHead2 } from "@earendil-works/pi-coding-agent";
4876
2390
  import { Text as Text6 } from "@earendil-works/pi-tui";
4877
- import { Type as Type9 } from "@sinclair/typebox";
2391
+ import { Type as Type7 } from "@sinclair/typebox";
4878
2392
 
4879
2393
  // src/binary-detect.ts
4880
2394
  import { isUtf8 } from "node:buffer";
@@ -4885,7 +2399,7 @@ function looksLikeBinary(buf) {
4885
2399
  }
4886
2400
 
4887
2401
  // src/pending-diff-preview.ts
4888
- import { existsSync as existsSync2, readFileSync as readFileSync2, realpathSync, statSync as statSync4 } from "node:fs";
2402
+ import { existsSync, readFileSync as readFileSync2, realpathSync, statSync as statSync2 } from "node:fs";
4889
2403
  import { dirname, isAbsolute, relative as relative2, resolve, sep } from "node:path";
4890
2404
  var PENDING_DIFF_MAX_BYTES = 1024 * 1024;
4891
2405
  function skip(reason) {
@@ -4902,7 +2416,7 @@ function resolveWorkspacePreviewPath(rawPath, cwd, allowMissing) {
4902
2416
  const normalizedPath = rawPath.replace(/^@/, "");
4903
2417
  const explicitAbsolute = isAbsolute(normalizedPath);
4904
2418
  const requested = resolve(workspace, normalizedPath);
4905
- if (existsSync2(requested)) {
2419
+ if (existsSync(requested)) {
4906
2420
  const realTarget = realpathSync(requested);
4907
2421
  if (!explicitAbsolute && !isInsidePath(workspace, realTarget))
4908
2422
  return { type: "skip", reason: "path outside workspace" };
@@ -4913,12 +2427,12 @@ function resolveWorkspacePreviewPath(rawPath, cwd, allowMissing) {
4913
2427
  if (!allowMissing)
4914
2428
  return { type: "skip", reason: "file not found" };
4915
2429
  const parent = dirname(requested);
4916
- if (!existsSync2(parent))
2430
+ if (!existsSync(parent))
4917
2431
  return { type: "skip", reason: "parent directory not found" };
4918
2432
  return { type: "ok", path: requested, existed: false };
4919
2433
  }
4920
2434
  function readUtf8File(filePath) {
4921
- const stat = statSync4(filePath);
2435
+ const stat = statSync2(filePath);
4922
2436
  if (!stat.isFile())
4923
2437
  return { type: "skip", reason: "not a file" };
4924
2438
  if (stat.size > PENDING_DIFF_MAX_BYTES)
@@ -5006,6 +2520,7 @@ function resolvePendingDiffPreview(context, stateKey, previewKey, compute) {
5006
2520
  }
5007
2521
 
5008
2522
  // src/write.ts
2523
+ import { getToolContract as getToolContract6 } from "@jarkkojs/readseek-api";
5009
2524
  var WRITE_PENDING_PREVIEW_STATE_KEY = "hashline-write-pending-preview";
5010
2525
  var CONTENT_PREVIEW_MAX_LINES = 200;
5011
2526
  function formatContentPreviewLines(content, theme) {
@@ -5057,9 +2572,9 @@ async function readPreviousTextForDiff(filePath) {
5057
2572
  throw err;
5058
2573
  }
5059
2574
  }
5060
- function generateWriteDiff(previousContent, nextContent) {
2575
+ function generateWriteDiff(previousContent, nextContent, anchors) {
5061
2576
  if (previousContent !== "")
5062
- return generateCompactOrFullDiff(previousContent, nextContent);
2577
+ return generateCompactOrFullDiff(previousContent, nextContent, anchors);
5063
2578
  const normalizedNext = normalizeToLF(nextContent);
5064
2579
  if (normalizedNext === "")
5065
2580
  return { diff: "", firstChangedLine: undefined };
@@ -5082,7 +2597,6 @@ function buildWriteFsErrorResult(err, absolutePath) {
5082
2597
  });
5083
2598
  }
5084
2599
  async function executeWrite(opts) {
5085
- await ensureHashInit();
5086
2600
  const { path: filePath, content, cwd } = opts;
5087
2601
  const warnings = [];
5088
2602
  const readSeekWarnings = [];
@@ -5109,24 +2623,16 @@ async function executeWrite(opts) {
5109
2623
  const { content: previousContent, existed: existedBeforeWrite } = await readPreviousTextForDiff(filePath);
5110
2624
  await mkdir(dirname2(filePath), { recursive: true });
5111
2625
  await writeFile(filePath, content, "utf-8");
5112
- const normalizedContent = stripBom(content).text;
5113
- const rawLines = normalizedContent === "" ? [] : normalizedContent.split(`
5114
- `);
5115
- if (rawLines[rawLines.length - 1] === "")
5116
- rawLines.pop();
5117
- for (let i = 0;i < rawLines.length; i++) {
5118
- if (rawLines[i].endsWith("\r"))
5119
- rawLines[i] = rawLines[i].slice(0, -1);
5120
- }
5121
- const readSeekLines = [];
5122
- const displayLines = [];
5123
- for (let i = 0;i < rawLines.length; i++) {
5124
- const lineNum = i + 1;
5125
- const readSeekLine = buildReadSeekLine(lineNum, rawLines[i]);
5126
- readSeekLines.push(readSeekLine);
5127
- displayLines.push(formatHashlineDisplay(lineNum, rawLines[i]));
2626
+ let readSeekLines = [];
2627
+ try {
2628
+ readSeekLines = (await readAnchors(filePath)).map((line) => buildReadSeekLineWithHash(line.line, line.hash, line.text));
2629
+ } catch (err) {
2630
+ const message = `File written, but readseek could not return anchors (${err instanceof Error ? err.message : String(err)}); call readSeek_show before editing it.`;
2631
+ warnings.push(message);
2632
+ readSeekWarnings.push(buildReadSeekWarning("anchors-unavailable", message));
5128
2633
  }
5129
- const fullText = displayLines.join(`
2634
+ const fullText = readSeekLines.length > 0 ? readSeekLines.map((line) => `${line.anchor}|${line.display}`).join(`
2635
+ `) : warnings.join(`
5130
2636
  `);
5131
2637
  const truncated = truncateHead2(fullText);
5132
2638
  let text = truncated.content;
@@ -5142,7 +2648,7 @@ async function executeWrite(opts) {
5142
2648
  const displayPath = cwd ? relative3(cwd, filePath) || filePath : filePath;
5143
2649
  const normalizedPrevious = normalizeToLF(previousContent);
5144
2650
  const normalizedNext = normalizeToLF(content);
5145
- const diffResult = generateWriteDiff(normalizedPrevious, normalizedNext);
2651
+ const diffResult = generateWriteDiff(normalizedPrevious, normalizedNext, new Map(readSeekLines.map((line) => [line.line, line.hash])));
5146
2652
  const diffData = buildDiffData({
5147
2653
  path: filePath,
5148
2654
  oldContent: normalizedPrevious,
@@ -5178,10 +2684,7 @@ function registerWriteTool(pi, options = {}) {
5178
2684
  description: promptMetadata.description,
5179
2685
  promptSnippet: promptMetadata.promptSnippet,
5180
2686
  promptGuidelines: promptMetadata.promptGuidelines,
5181
- parameters: Type9.Object({
5182
- path: filePathParam(),
5183
- content: Type9.String({ description: PARAM_DESCRIPTIONS.content })
5184
- }),
2687
+ parameters: Type7.Unsafe(getToolContract6("write").project()),
5185
2688
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
5186
2689
  const cwd = ctx?.cwd ?? process.cwd();
5187
2690
  const absolutePath = resolveToCwd(params.path, cwd);
@@ -5279,8 +2782,9 @@ function registerWriteTool(pi, options = {}) {
5279
2782
  }
5280
2783
 
5281
2784
  // src/def.ts
5282
- import { Type as Type10 } from "@sinclair/typebox";
5283
- import path9 from "node:path";
2785
+ import { Type as Type8 } from "@sinclair/typebox";
2786
+ import path5 from "node:path";
2787
+ import { getToolContract as getToolContract7, PARAM_DESCRIPTIONS as PARAM_DESCRIPTIONS6 } from "@jarkkojs/readseek-api";
5284
2788
  var DEF_PROMPT_METADATA = defineToolPromptMetadata({
5285
2789
  toolName: "def",
5286
2790
  promptSnippet: "Go to a symbol definition or declaration by name"
@@ -5312,10 +2816,10 @@ async function executeDef(opts) {
5312
2816
  }
5313
2817
  const files = new Map;
5314
2818
  for (const def of definitions) {
5315
- const abs = path9.isAbsolute(def.file) ? def.file : path9.resolve(cwd, def.file);
2819
+ const abs = path5.isAbsolute(def.file) ? def.file : path5.resolve(cwd, def.file);
5316
2820
  let file = files.get(abs);
5317
2821
  if (!file) {
5318
- file = { displayPath: path9.relative(cwd, abs) || abs, path: abs, lines: [] };
2822
+ file = { displayPath: path5.relative(cwd, abs) || abs, path: abs, lines: [] };
5319
2823
  files.set(abs, file);
5320
2824
  }
5321
2825
  file.lines.push(buildReadSeekLineWithHash(def.line, def.line_hash, def.text));
@@ -5350,12 +2854,10 @@ function registerDefTool(pi, options = {}) {
5350
2854
  description: DEF_PROMPT_METADATA.description,
5351
2855
  promptSnippet: DEF_PROMPT_METADATA.promptSnippet,
5352
2856
  promptGuidelines: DEF_PROMPT_METADATA.promptGuidelines,
5353
- parameters: Type10.Object({
5354
- name: Type10.String({ description: PARAM_DESCRIPTIONS.name }),
5355
- path: searchPathParam(),
5356
- language: languageParam(),
5357
- ...readSeekGitSearchParams()
5358
- }),
2857
+ parameters: Type8.Unsafe(getToolContract7("def").project({
2858
+ omit: ["noAnchors"],
2859
+ describe: { path: PARAM_DESCRIPTIONS6.searchPath }
2860
+ })),
5359
2861
  async execute(_toolCallId, params, signal, _onUpdate, ctx) {
5360
2862
  return executeDef({ params, signal, cwd: ctx.cwd, onFileAnchored: options.onFileAnchored });
5361
2863
  },
@@ -5379,9 +2881,10 @@ function registerDefTool(pi, options = {}) {
5379
2881
 
5380
2882
  // src/access.ts
5381
2883
  import { Text as Text7, wrapTextWithAnsi as wrapTextWithAnsi2 } from "@earendil-works/pi-tui";
5382
- import { Type as Type11 } from "@sinclair/typebox";
2884
+ import { Type as Type9 } from "@sinclair/typebox";
5383
2885
  import { createReadStream } from "node:fs";
5384
2886
  import { stat } from "node:fs/promises";
2887
+ import { collectImageAssetPaths, formatShowResult, getToolContract as getToolContract8, isShowTool, presentShowResult } from "@jarkkojs/readseek-api";
5385
2888
  var MAX_IMAGE_ATTACHMENT_BYTES = 32 * 1024 * 1024;
5386
2889
  var ACCESS_TOOLS = ["show", "tree", "meta", "assets", "syntax", "check", "caption", "objects", "ocr"];
5387
2890
  function resolveNonShowSummary(value) {
@@ -5461,7 +2964,7 @@ async function executeAccess(opts) {
5461
2964
  return buildToolErrorResult(opts.tool, "invalid-parameter", "Expected an object");
5462
2965
  }
5463
2966
  const p = opts.params;
5464
- const contract = getToolContract(opts.tool);
2967
+ const contract = getToolContract8(opts.tool);
5465
2968
  for (const key of Object.keys(p)) {
5466
2969
  if (key === "stdinName" || !Object.hasOwn(contract.inputSchema.properties, key))
5467
2970
  return buildToolErrorResult(opts.tool, "invalid-parameter", `Unknown parameter: ${key}`);
@@ -5526,7 +3029,7 @@ async function executeAccess(opts) {
5526
3029
  function registerAccessTools(pi, options = {}) {
5527
3030
  for (const name of ACCESS_TOOLS) {
5528
3031
  const registeredName = name === "show" ? options.name ?? `readSeek_${name}` : `readSeek_${name}`;
5529
- const contract = getToolContract(name);
3032
+ const contract = getToolContract8(name);
5530
3033
  const metadata = defineToolPromptMetadata({
5531
3034
  toolName: name,
5532
3035
  promptSnippet: contract.title,
@@ -5537,10 +3040,7 @@ function registerAccessTools(pi, options = {}) {
5537
3040
  name: registeredName,
5538
3041
  label: contract.title,
5539
3042
  ...metadata,
5540
- parameters: Type11.Unsafe({
5541
- ...contract.inputSchema,
5542
- properties: Object.fromEntries(Object.entries(contract.inputSchema.properties).filter(([key]) => key !== "stdinName"))
5543
- }),
3043
+ parameters: Type9.Unsafe(contract.project({ omit: ["stdinName"] })),
5544
3044
  async execute(_id, params, signal, _update, ctx) {
5545
3045
  return executeAccess({ tool: name, params, signal, cwd: ctx.cwd, onFileAnchored: options.onFileAnchored, imageMode: options.imageMode, modelSupportsImages: ctx.model?.input.includes("image") ?? false });
5546
3046
  },
@@ -5614,6 +3114,7 @@ class SessionAnchors {
5614
3114
  }
5615
3115
 
5616
3116
  // index.ts
3117
+ import { TOOL_NAMES as TOOL_NAMES2, renderToolRoutingPolicy } from "@jarkkojs/readseek-api";
5617
3118
  var READSEEK_TOOL_ENTRIES = [
5618
3119
  { builtIn: "edit", readSeekName: "readSeek_edit" },
5619
3120
  { builtIn: "grep", readSeekName: "readSeek_grep" },
@@ -5647,7 +3148,7 @@ function piReadSeekExtension(pi) {
5647
3148
  readSeek_grep: grepName,
5648
3149
  readSeek_write: writeName
5649
3150
  };
5650
- const policyAliases = Object.fromEntries(TOOL_NAMES.map((name) => {
3151
+ const policyAliases = Object.fromEntries(TOOL_NAMES2.map((name) => {
5651
3152
  const readSeekName = `readSeek_${name}`;
5652
3153
  return [name, toolAliases[readSeekName] ?? readSeekName];
5653
3154
  }));