pi-readseek 0.13.3 → 0.13.4

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 +167 -175
  2. package/package.json +3 -3
package/dist/index.ts CHANGED
@@ -320,6 +320,9 @@ function tryParseLineAnchor(anchor) {
320
320
  }
321
321
 
322
322
  // ../readseek-api/src/validation.ts
323
+ function isRecord(value) {
324
+ return typeof value === "object" && value !== null && !Array.isArray(value);
325
+ }
323
326
  function validateReferencesSelection(input) {
324
327
  if (Boolean(input.name) === Boolean(input.at))
325
328
  return { ok: false, error: "exactly one of name or at is required" };
@@ -1311,6 +1314,24 @@ function parseAssetsOutput(value) {
1311
1314
  throw new Error("invalid readseek assets output: missing file or metadata");
1312
1315
  return parse(SourceAssetsOutput, { ...raw, ...raw.metadata !== undefined ? { metadata: parseDetectOutput(raw.metadata) } : {} }, "assets output");
1313
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
+ });
1314
1335
 
1315
1336
  // ../readseek-api/src/edit-plan.ts
1316
1337
  import { Document, Node, format } from "@bgotink/kdl";
@@ -1376,63 +1397,63 @@ function createReadSeekClient(runner) {
1376
1397
  return {
1377
1398
  async show(path, options = {}) {
1378
1399
  const value = await runner.kdl(buildShowArgs({ ...options, path }), runOptions(options));
1379
- return parseContentOutput(value);
1400
+ return ReadSeekOutput.content(value);
1380
1401
  },
1381
1402
  async tree(path, options = {}) {
1382
1403
  const value = await runner.kdl(buildTreeArgs({ ...options, path }), runOptions(options));
1383
- return parseStructureEnvelope(value);
1404
+ return ReadSeekOutput.structureEnvelope(value);
1384
1405
  },
1385
1406
  async meta(path, options = {}) {
1386
1407
  const value = await runner.kdl(buildMetaArgs({ ...options, path }), runOptions(options));
1387
- return parsePdfMetadata(value) ?? parseDetectOutput(value?.metadata);
1408
+ return ReadSeekOutput.pdfMetadata(value) ?? ReadSeekOutput.detect(value?.metadata);
1388
1409
  },
1389
1410
  async assets(path, options = {}) {
1390
1411
  const value = await runner.kdl(buildAssetsArgs({ ...options, path }), runOptions(options));
1391
- return parseAssetsOutput(value);
1412
+ return ReadSeekOutput.assets(value);
1392
1413
  },
1393
1414
  async syntax(path, options = {}) {
1394
1415
  const value = await runner.kdl(buildSyntaxArgs({ ...options, path }), runOptions(options));
1395
- return parseCheckOutput(value?.diagnostics ?? value);
1416
+ return ReadSeekOutput.check(value?.diagnostics ?? value);
1396
1417
  },
1397
1418
  async check(path, options) {
1398
1419
  const value = await runner.kdl(buildCheckArgs({ ...options, path }), runOptions(options));
1399
- return parseRulesOutput(value);
1420
+ return ReadSeekOutput.rules(value);
1400
1421
  },
1401
1422
  async caption(path, options = {}) {
1402
1423
  const value = await runner.kdl(buildCaptionArgs({ ...options, path }), runOptions(options, true));
1403
- return parseContentOutput(value);
1424
+ return ReadSeekOutput.content(value);
1404
1425
  },
1405
1426
  async objects(path, options = {}) {
1406
1427
  const value = await runner.kdl(buildObjectsArgs({ ...options, path }), runOptions(options, true));
1407
- return parseContentOutput(value);
1428
+ return ReadSeekOutput.content(value);
1408
1429
  },
1409
1430
  async ocr(path, options = {}) {
1410
1431
  const value = await runner.kdl(buildOcrArgs({ ...options, path }), runOptions(options, true));
1411
- return parseContentOutput(value);
1432
+ return ReadSeekOutput.content(value);
1412
1433
  },
1413
1434
  async search(path, options) {
1414
1435
  const value = await runner.kdl(buildSearchArgs({ ...options, path }), runOptions(options));
1415
- return parseSearchOutput(value);
1436
+ return ReadSeekOutput.search(value);
1416
1437
  },
1417
1438
  async grep(params) {
1418
1439
  const value = await runner.kdl(buildGrepArgs(params), runOptions(params));
1419
- return parseGrepOutput(value);
1440
+ return ReadSeekOutput.grep(value);
1420
1441
  },
1421
1442
  async def(path, options) {
1422
1443
  const value = await runner.kdl(buildDefArgs({ ...options, path }), runOptions(options));
1423
- return parseDefOutput(value);
1444
+ return ReadSeekOutput.def(value);
1424
1445
  },
1425
1446
  async refs(path, options) {
1426
1447
  const value = await runner.kdl(buildRefsArgs({ ...options, path }), runOptions(options));
1427
- return parseRefsOutput(value);
1448
+ return ReadSeekOutput.refs(value);
1428
1449
  },
1429
1450
  async edit(path, edits, options = {}) {
1430
1451
  const stdin = serializeEditPlan(edits);
1431
- return parseEditOutput(await runner.kdl(buildEditArgs({ ...options, path, requestFromStdin: true }), runOptions({ ...options, stdin })));
1452
+ return ReadSeekOutput.edit(await runner.kdl(buildEditArgs({ ...options, path, requestFromStdin: true }), runOptions({ ...options, stdin })));
1432
1453
  },
1433
1454
  async rename(path, options) {
1434
1455
  const value = await runner.kdl(buildRenameArgs({ ...options, path }), runOptions(options));
1435
- return parseRenameOutput(value);
1456
+ return ReadSeekOutput.rename(value);
1436
1457
  }
1437
1458
  };
1438
1459
  }
@@ -1651,9 +1672,21 @@ function formatShowResult(presentation) {
1651
1672
 
1652
1673
  `);
1653
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
+ }
1654
1686
  // ../readseek-api/src/platform.ts
1655
1687
  import { accessSync, constants as fsConstants, existsSync, statSync } from "node:fs";
1656
1688
  import { createRequire } from "node:module";
1689
+ import { homedir } from "node:os";
1657
1690
  import path2 from "node:path";
1658
1691
  var READSEEK_BINARY_ENV = "READSEEK_BINARY";
1659
1692
  var READSEEK_PLATFORM_PACKAGES = {
@@ -1714,11 +1747,47 @@ function resolveReadSeekBinaryFromPackages(resolver = resolveFromPackage, option
1714
1747
  accessSync(binaryPath, fsConstants.X_OK);
1715
1748
  return binaryPath;
1716
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
+ }
1717
1786
  // ../readseek-api/src/path.ts
1718
- import { homedir } from "node:os";
1787
+ import { homedir as homedir2 } from "node:os";
1719
1788
  import path3 from "node:path";
1720
1789
  var UNICODE_SPACES = /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;
1721
- function expandUserPath(filePath, homedirFn = homedir) {
1790
+ function expandUserPath(filePath, homedirFn = homedir2) {
1722
1791
  const withoutAt = filePath.startsWith("@") ? filePath.slice(1) : filePath;
1723
1792
  const normalized = withoutAt.replace(UNICODE_SPACES, " ");
1724
1793
  if (normalized === "~")
@@ -1727,7 +1796,7 @@ function expandUserPath(filePath, homedirFn = homedir) {
1727
1796
  return homedirFn() + normalized.slice(1);
1728
1797
  return normalized;
1729
1798
  }
1730
- function resolveToCwd(filePath, cwd, homedirFn = homedir) {
1799
+ function resolveToCwd(filePath, cwd, homedirFn = homedir2) {
1731
1800
  const expanded = expandUserPath(filePath, homedirFn);
1732
1801
  return path3.isAbsolute(expanded) ? expanded : path3.resolve(cwd, expanded);
1733
1802
  }
@@ -2792,14 +2861,14 @@ function classifyEdit(oldContent, newContent) {
2792
2861
  }
2793
2862
 
2794
2863
  // src/readseek-client.ts
2795
- import { existsSync as existsSync2, statSync as statSync3 } from "node:fs";
2864
+ import { statSync as statSync3 } from "node:fs";
2796
2865
  import { createRequire as createRequire2 } from "node:module";
2797
- import { homedir as homedir3 } from "node:os";
2866
+ import { homedir as homedir4 } from "node:os";
2798
2867
  import path4 from "node:path";
2799
2868
 
2800
2869
  // src/readseek-settings.ts
2801
2870
  import { readFileSync, statSync as statSync2 } from "node:fs";
2802
- import { homedir as homedir2 } from "node:os";
2871
+ import { homedir as homedir3 } from "node:os";
2803
2872
  import { join } from "node:path";
2804
2873
  var READSEEK_TOOL_REPLACEMENTS = {
2805
2874
  read: "readSeek_show",
@@ -2815,9 +2884,6 @@ var DEFAULT_DISPLAY_MODES = {
2815
2884
  edit: "expanded",
2816
2885
  write: "expanded"
2817
2886
  };
2818
- function isRecord(value) {
2819
- return typeof value === "object" && value !== null && !Array.isArray(value);
2820
- }
2821
2887
  function invalid(source, path) {
2822
2888
  return { source, path, message: `Invalid readseek setting at ${path}` };
2823
2889
  }
@@ -2986,7 +3052,7 @@ function mergeSettings(base, override) {
2986
3052
  return settings;
2987
3053
  }
2988
3054
  function resolveReadSeekJsonSettings() {
2989
- const globalResult = readSettingsFile(join(homedir2(), ".pi/agent/settings.json"));
3055
+ const globalResult = readSettingsFile(join(homedir3(), ".pi/agent/settings.json"));
2990
3056
  const projectResult = readSettingsFile(join(process.cwd(), ".pi/settings.json"));
2991
3057
  return {
2992
3058
  settings: mergeSettings(globalResult.settings, projectResult.settings),
@@ -3020,10 +3086,6 @@ function readSeekBinaryAvailability() {
3020
3086
  }
3021
3087
  }
3022
3088
  var defaultReadSeekDirInit;
3023
- function defaultReadSeekDir() {
3024
- const home = homedir3();
3025
- return home ? path4.join(home, ".pi", "readseek") : null;
3026
- }
3027
3089
  function directoryExists(dir) {
3028
3090
  try {
3029
3091
  return statSync3(dir).isDirectory();
@@ -3036,8 +3098,15 @@ function readSeekTimeoutMs() {
3036
3098
  return resolveReadSeekTimeoutMs() ?? DEFAULT_READSEEK_TIMEOUT_MS;
3037
3099
  }
3038
3100
  async function ensureDefaultReadSeekDir() {
3039
- const dir = defaultReadSeekDir();
3040
- if (!dir)
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)
3041
3110
  return null;
3042
3111
  if (directoryExists(dir))
3043
3112
  return dir;
@@ -3046,23 +3115,12 @@ async function ensureDefaultReadSeekDir() {
3046
3115
  });
3047
3116
  return defaultReadSeekDirInit;
3048
3117
  }
3049
- function hasProjectReadSeekDir(cwd = process.cwd()) {
3050
- let dir = path4.resolve(cwd);
3051
- while (true) {
3052
- if (existsSync2(path4.join(dir, ".readseek")))
3053
- return true;
3054
- const parent = path4.dirname(dir);
3055
- if (parent === dir)
3056
- return false;
3057
- dir = parent;
3058
- }
3059
- }
3060
3118
  function supportsReadSeekDir(args) {
3061
3119
  const first = args[0];
3062
3120
  return first === "init" || first === "show" || first === "assets" || first === "caption" || first === "objects" || first === "ocr";
3063
3121
  }
3064
3122
  async function readSeekInvocationArgs(args) {
3065
- if (!supportsReadSeekDir(args) || hasProjectReadSeekDir())
3123
+ if (!supportsReadSeekDir(args))
3066
3124
  return [...args];
3067
3125
  const readSeekDir = await ensureDefaultReadSeekDir();
3068
3126
  return readSeekDir ? ["--readseek-dir", readSeekDir, ...args] : [...args];
@@ -3107,31 +3165,16 @@ async function runReadSeekVisionRaw(args, options = {}) {
3107
3165
  release();
3108
3166
  }
3109
3167
  }
3110
- var runner = {
3168
+ var nodeRunner = {
3111
3169
  text: async (args, options = {}) => options.vision ? runReadSeekVisionRaw(args, options) : runReadSeekNodeText(readSeekBinaryPath(), await readSeekInvocationArgs(args), {
3112
3170
  signal: options.signal,
3113
3171
  stdin: options.stdin,
3114
3172
  timeoutMs: options.timeoutMs ?? readSeekTimeoutMs(),
3115
3173
  cancelable: options.cancelable
3116
3174
  }),
3117
- kdl: async (args, options = {}) => parseReadSeekKdl(await runner.text(args, options))
3175
+ kdl: async (args, options = {}) => parseReadSeekKdl(await nodeRunner.text(args, options))
3118
3176
  };
3119
- var client2 = createReadSeekClient(runner);
3120
- var readSeekShow = client2.show;
3121
- var readSeekTree = client2.tree;
3122
- var readSeekMeta = client2.meta;
3123
- var readSeekAssets = client2.assets;
3124
- var readSeekCaption = client2.caption;
3125
- var readSeekObjects = client2.objects;
3126
- var readSeekOcr = client2.ocr;
3127
- var readSeekSearch = client2.search;
3128
- var readSeekGrep = client2.grep;
3129
- var readSeekRefs = client2.refs;
3130
- var readSeekDef = client2.def;
3131
- var readSeekSyntax = client2.syntax;
3132
- var readSeekCheck = client2.check;
3133
- var readSeekEdit = client2.edit;
3134
- var readSeekRename = client2.rename;
3177
+ var readSeekClient = createReadSeekClient(nodeRunner);
3135
3178
 
3136
3179
  // src/edit-syntax-validate.ts
3137
3180
  function dedupeSortLines(diagnostics) {
@@ -3152,8 +3195,8 @@ async function validateSyntaxRegression(input, options = {}) {
3152
3195
  let before;
3153
3196
  let after;
3154
3197
  try {
3155
- before = input.before === undefined ? EMPTY : await readSeekSyntax("-", { stdinName: input.filePath, stdin: input.before, signal: options.signal });
3156
- after = await readSeekSyntax("-", { stdinName: input.filePath, stdin: input.after, signal: options.signal });
3198
+ before = input.before === undefined ? EMPTY : await readSeekClient.syntax("-", { stdinName: input.filePath, stdin: input.before, signal: options.signal });
3199
+ after = await readSeekClient.syntax("-", { stdinName: input.filePath, stdin: input.after, signal: options.signal });
3157
3200
  } catch {
3158
3201
  return null;
3159
3202
  }
@@ -3175,6 +3218,7 @@ function resolveSyntaxValidateMode(opts) {
3175
3218
  }
3176
3219
 
3177
3220
  // src/diff-data.ts
3221
+ import { diffArrays } from "diff";
3178
3222
  var MAX_INLINE_DIFF_LINE_LENGTH = 4096;
3179
3223
  var MAX_INLINE_DIFF_TOKENS = 512;
3180
3224
  var MAX_INLINE_DIFF_CELLS = 200000;
@@ -3276,31 +3320,6 @@ function buildStats(entries) {
3276
3320
  function tokenizeInlineDiff(text) {
3277
3321
  return text.match(INLINE_TOKEN_PATTERN) ?? (text ? [text] : []);
3278
3322
  }
3279
- function longestCommonSubsequence(a, b) {
3280
- const rows = a.length + 1;
3281
- const cols = b.length + 1;
3282
- const table = Array.from({ length: rows }, () => Array(cols).fill(0));
3283
- for (let i = a.length - 1;i >= 0; i--) {
3284
- for (let j = b.length - 1;j >= 0; j--) {
3285
- table[i][j] = a[i] === b[j] ? table[i + 1][j + 1] + 1 : Math.max(table[i + 1][j], table[i][j + 1]);
3286
- }
3287
- }
3288
- const pairs = [];
3289
- let i = 0;
3290
- let j = 0;
3291
- while (i < a.length && j < b.length) {
3292
- if (a[i] === b[j]) {
3293
- pairs.push([i, j]);
3294
- i++;
3295
- j++;
3296
- } else if (table[i + 1][j] >= table[i][j + 1]) {
3297
- i++;
3298
- } else {
3299
- j++;
3300
- }
3301
- }
3302
- return pairs;
3303
- }
3304
3323
  function pushMergedSpan(spans, span) {
3305
3324
  if (!span.text)
3306
3325
  return;
@@ -3322,39 +3341,27 @@ function buildInlineSpans(removeText, addText) {
3322
3341
  return;
3323
3342
  if ((removeTokens.length + 1) * (addTokens.length + 1) > MAX_INLINE_DIFF_CELLS)
3324
3343
  return;
3325
- const pairs = longestCommonSubsequence(removeTokens, addTokens);
3344
+ const changes = diffArrays(removeTokens, addTokens);
3326
3345
  const meaningfulRemoveTokenCount = removeTokens.filter((token) => token.trim().length > 0).length;
3327
3346
  const meaningfulAddTokenCount = addTokens.filter((token) => token.trim().length > 0).length;
3328
- const meaningfulEqualTokenCount = pairs.filter(([removeIndex, addIndex]) => {
3329
- const removeToken = removeTokens[removeIndex] ?? "";
3330
- const addToken = addTokens[addIndex] ?? "";
3331
- return removeToken === addToken && removeToken.trim().length > 0 && addToken.trim().length > 0;
3332
- }).length;
3333
- const similarity = meaningfulEqualTokenCount / Math.max(meaningfulRemoveTokenCount, meaningfulAddTokenCount);
3334
- if (similarity < INLINE_SIMILARITY_THRESHOLD)
3335
- return;
3347
+ let meaningfulEqualTokenCount = 0;
3336
3348
  const removeSpans = [];
3337
3349
  const addSpans = [];
3338
- let removeCursor = 0;
3339
- let addCursor = 0;
3340
- for (const [removeIndex, addIndex] of pairs) {
3341
- if (removeCursor < removeIndex) {
3342
- pushMergedSpan(removeSpans, { kind: "remove", text: removeTokens.slice(removeCursor, removeIndex).join("") });
3343
- }
3344
- if (addCursor < addIndex) {
3345
- pushMergedSpan(addSpans, { kind: "add", text: addTokens.slice(addCursor, addIndex).join("") });
3350
+ for (const change of changes) {
3351
+ const text = change.value.join("");
3352
+ if (change.removed) {
3353
+ pushMergedSpan(removeSpans, { kind: "remove", text });
3354
+ } else if (change.added) {
3355
+ pushMergedSpan(addSpans, { kind: "add", text });
3356
+ } else {
3357
+ meaningfulEqualTokenCount += change.value.filter((token) => token.trim().length > 0).length;
3358
+ pushMergedSpan(removeSpans, { kind: "equal", text });
3359
+ pushMergedSpan(addSpans, { kind: "equal", text });
3346
3360
  }
3347
- pushMergedSpan(removeSpans, { kind: "equal", text: removeTokens[removeIndex] });
3348
- pushMergedSpan(addSpans, { kind: "equal", text: addTokens[addIndex] });
3349
- removeCursor = removeIndex + 1;
3350
- addCursor = addIndex + 1;
3351
- }
3352
- if (removeCursor < removeTokens.length) {
3353
- pushMergedSpan(removeSpans, { kind: "remove", text: removeTokens.slice(removeCursor).join("") });
3354
- }
3355
- if (addCursor < addTokens.length) {
3356
- pushMergedSpan(addSpans, { kind: "add", text: addTokens.slice(addCursor).join("") });
3357
3361
  }
3362
+ const similarity = meaningfulEqualTokenCount / Math.max(meaningfulRemoveTokenCount, meaningfulAddTokenCount);
3363
+ if (similarity < INLINE_SIMILARITY_THRESHOLD)
3364
+ return;
3358
3365
  if (!removeSpans.some((span) => span.kind === "remove") || !addSpans.some((span) => span.kind === "add"))
3359
3366
  return;
3360
3367
  return { removeSpans, addSpans };
@@ -3850,7 +3857,7 @@ async function executeEdit(opts) {
3850
3857
  const edits = parsedEdits.edits;
3851
3858
  let plan;
3852
3859
  try {
3853
- plan = await readSeekEdit(absolutePath, edits, { signal, language: parsed.language });
3860
+ plan = await readSeekClient.edit(absolutePath, edits, { signal, language: parsed.language });
3854
3861
  } catch (err) {
3855
3862
  throwIfAborted(signal);
3856
3863
  const failure = classifyReadSeekFailure(err);
@@ -3886,7 +3893,7 @@ async function executeEdit(opts) {
3886
3893
  throwIfAborted(signal);
3887
3894
  let applied;
3888
3895
  try {
3889
- applied = await readSeekEdit(absolutePath, edits, {
3896
+ applied = await readSeekClient.edit(absolutePath, edits, {
3890
3897
  apply: true,
3891
3898
  planHash: plan.plan_hash,
3892
3899
  language: parsed.language,
@@ -4269,7 +4276,7 @@ async function executeGrep(opts) {
4269
4276
  const message = `Invalid scopeContext: expected a non-negative integer, received ${scopeContext.value}.`;
4270
4277
  return buildToolErrorResult("grep", "invalid-params-combo", message);
4271
4278
  }
4272
- const output = await readSeekGrep({
4279
+ const output = await readSeekClient.grep({
4273
4280
  pattern: rawParams.pattern,
4274
4281
  path: resolveToCwd(rawParams.path ?? ".", cwd),
4275
4282
  glob: rawParams.glob,
@@ -4476,7 +4483,7 @@ async function executeSearch(opts) {
4476
4483
  const searchPathIsFile = statResult.stats.isFile();
4477
4484
  try {
4478
4485
  const effectiveLang = readSeekLanguageForPath(p.language, searchPath, searchPathIsFile);
4479
- const results = await readSeekSearch(searchPath, {
4486
+ const results = await readSeekClient.search(searchPath, {
4480
4487
  pattern: p.pattern,
4481
4488
  context: p.context,
4482
4489
  selector: p.selector,
@@ -4652,7 +4659,7 @@ async function executeRefs(opts) {
4652
4659
  if (!statResult.ok)
4653
4660
  return statResult.error;
4654
4661
  try {
4655
- const references = await readSeekRefs(searchPath, {
4662
+ const references = await readSeekClient.refs(searchPath, {
4656
4663
  name: p.name,
4657
4664
  at: p.at,
4658
4665
  language: p.language,
@@ -4738,12 +4745,18 @@ async function executeRename(opts) {
4738
4745
  if (!p.to.trim()) {
4739
4746
  return buildToolErrorResult("rename", "invalid-parameter", "rename parameter 'to' must not be empty");
4740
4747
  }
4741
- if (typeof p.at !== "string" || !/^(line:[1-9][0-9]*|hash:[0-9a-fA-F]+|[1-9][0-9]*|[0-9a-fA-F]{6})(:[1-9][0-9]*)?$/.test(p.at)) {
4748
+ let validSelector = false;
4749
+ if (typeof p.at === "string") {
4750
+ try {
4751
+ validSelector = isBindingSelector(parseSelector(p.at));
4752
+ } catch {}
4753
+ }
4754
+ if (!validSelector) {
4742
4755
  return buildToolErrorResult("rename", "invalid-parameter", "at must be a line or hash location with an optional positive column");
4743
4756
  }
4744
4757
  const filePath = resolveToCwd(p.path, cwd);
4745
4758
  try {
4746
- const output = await readSeekRename(filePath, {
4759
+ const output = await readSeekClient.rename(filePath, {
4747
4760
  to: p.to,
4748
4761
  at: p.at,
4749
4762
  workspace: p.workspace ? cwd : undefined,
@@ -4812,11 +4825,12 @@ function registerRenameTool(pi, options = {}) {
4812
4825
  renderCall(args, theme, ...rest) {
4813
4826
  const context = rest[0] ?? {};
4814
4827
  const cwd = context.cwd ?? process.cwd();
4815
- const displayPath = typeof args?.path === "string" ? args.path : "?";
4828
+ const record = args && typeof args === "object" ? args : undefined;
4829
+ const displayPath = typeof record?.path === "string" ? record.path : "?";
4816
4830
  let text = theme.fg("toolTitle", theme.bold("readSeek_rename"));
4817
4831
  text += ` ${linkToolPath(theme.fg("accent", displayPath), displayPath, cwd)}`;
4818
- if (args?.to)
4819
- text += theme.fg("dim", ` → ${args.to}`);
4832
+ if (typeof record?.to === "string" && record.to)
4833
+ text += theme.fg("dim", ` → ${record.to}`);
4820
4834
  return new Text5(clampLineToWidth(text, context.width), 0, 0);
4821
4835
  },
4822
4836
  renderResult(result, options, theme, ...rest) {
@@ -4825,8 +4839,7 @@ function registerRenameTool(pi, options = {}) {
4825
4839
  return renderPendingResult("pending readSeek_rename", width, theme);
4826
4840
  const content = result.content?.[0];
4827
4841
  const textContent = content?.type === "text" ? content.text : "";
4828
- const readSeekValue = result.details?.readSeekValue;
4829
- const output = readSeekValue?.output;
4842
+ const output = result.details?.readSeekValue?.output;
4830
4843
  if (isError || result.isError) {
4831
4844
  return renderErrorResult(textContent, { expanded, width, fallback: "readSeek_rename failed", theme });
4832
4845
  }
@@ -4864,19 +4877,15 @@ import { Text as Text6 } from "@earendil-works/pi-tui";
4864
4877
  import { Type as Type9 } from "@sinclair/typebox";
4865
4878
 
4866
4879
  // src/binary-detect.ts
4880
+ import { isUtf8 } from "node:buffer";
4867
4881
  function looksLikeBinary(buf) {
4868
4882
  if (buf.length === 0)
4869
4883
  return false;
4870
- if (buf.includes(0))
4871
- return true;
4872
- const decoded = buf.toString("utf8");
4873
- if (!decoded.includes("�"))
4874
- return false;
4875
- return !Buffer.from(decoded, "utf8").equals(buf);
4884
+ return buf.includes(0) || !isUtf8(buf);
4876
4885
  }
4877
4886
 
4878
4887
  // src/pending-diff-preview.ts
4879
- import { existsSync as existsSync3, readFileSync as readFileSync2, realpathSync, statSync as statSync4 } from "node:fs";
4888
+ import { existsSync as existsSync2, readFileSync as readFileSync2, realpathSync, statSync as statSync4 } from "node:fs";
4880
4889
  import { dirname, isAbsolute, relative as relative2, resolve, sep } from "node:path";
4881
4890
  var PENDING_DIFF_MAX_BYTES = 1024 * 1024;
4882
4891
  function skip(reason) {
@@ -4893,7 +4902,7 @@ function resolveWorkspacePreviewPath(rawPath, cwd, allowMissing) {
4893
4902
  const normalizedPath = rawPath.replace(/^@/, "");
4894
4903
  const explicitAbsolute = isAbsolute(normalizedPath);
4895
4904
  const requested = resolve(workspace, normalizedPath);
4896
- if (existsSync3(requested)) {
4905
+ if (existsSync2(requested)) {
4897
4906
  const realTarget = realpathSync(requested);
4898
4907
  if (!explicitAbsolute && !isInsidePath(workspace, realTarget))
4899
4908
  return { type: "skip", reason: "path outside workspace" };
@@ -4904,7 +4913,7 @@ function resolveWorkspacePreviewPath(rawPath, cwd, allowMissing) {
4904
4913
  if (!allowMissing)
4905
4914
  return { type: "skip", reason: "file not found" };
4906
4915
  const parent = dirname(requested);
4907
- if (!existsSync3(parent))
4916
+ if (!existsSync2(parent))
4908
4917
  return { type: "skip", reason: "parent directory not found" };
4909
4918
  return { type: "ok", path: requested, existed: false };
4910
4919
  }
@@ -5287,7 +5296,7 @@ async function executeDef(opts) {
5287
5296
  if (!statResult.ok)
5288
5297
  return statResult.error;
5289
5298
  try {
5290
- const definitions = await readSeekDef(searchPath, {
5299
+ const definitions = await readSeekClient.def(searchPath, {
5291
5300
  name: p.name,
5292
5301
  language: p.language,
5293
5302
  gitScope: p.gitScope,
@@ -5374,17 +5383,7 @@ import { Type as Type11 } from "@sinclair/typebox";
5374
5383
  import { createReadStream } from "node:fs";
5375
5384
  import { stat } from "node:fs/promises";
5376
5385
  var MAX_IMAGE_ATTACHMENT_BYTES = 32 * 1024 * 1024;
5377
- var operations = {
5378
- show: readSeekShow,
5379
- tree: readSeekTree,
5380
- meta: readSeekMeta,
5381
- assets: readSeekAssets,
5382
- syntax: readSeekSyntax,
5383
- check: readSeekCheck,
5384
- caption: readSeekCaption,
5385
- objects: readSeekObjects,
5386
- ocr: readSeekOcr
5387
- };
5386
+ var ACCESS_TOOLS = ["show", "tree", "meta", "assets", "syntax", "check", "caption", "objects", "ocr"];
5388
5387
  function resolveNonShowSummary(value) {
5389
5388
  if (!value)
5390
5389
  return "complete";
@@ -5457,17 +5456,6 @@ function hasAnchors(value) {
5457
5456
  return true;
5458
5457
  return Object.values(record).some(hasAnchors);
5459
5458
  }
5460
- function imagePaths(value, paths = new Map) {
5461
- if (!value || typeof value !== "object")
5462
- return paths;
5463
- const record = value;
5464
- if (typeof record.path === "string" && typeof record.mime === "string" && record.mime.startsWith("image/")) {
5465
- paths.set(record.path, record.mime);
5466
- }
5467
- for (const child of Object.values(record))
5468
- imagePaths(child, paths);
5469
- return paths;
5470
- }
5471
5459
  async function executeAccess(opts) {
5472
5460
  if (!opts.params || typeof opts.params !== "object" || Array.isArray(opts.params)) {
5473
5461
  return buildToolErrorResult(opts.tool, "invalid-parameter", "Expected an object");
@@ -5486,7 +5474,8 @@ async function executeAccess(opts) {
5486
5474
  const filePath = resolveToCwd(path, opts.cwd);
5487
5475
  try {
5488
5476
  const { path: _path, ...options } = p;
5489
- const envelope = await operations[opts.tool](filePath, { ...options, signal: opts.signal });
5477
+ const invoke = readSeekClient[opts.tool];
5478
+ const envelope = await invoke(filePath, { ...options, signal: opts.signal });
5490
5479
  if (hasAnchors(envelope))
5491
5480
  opts.onFileAnchored?.(filePath);
5492
5481
  const presentation = isShowTool(opts.tool) ? presentShowResult(opts.tool, envelope, p) : undefined;
@@ -5495,7 +5484,7 @@ async function executeAccess(opts) {
5495
5484
  ];
5496
5485
  if (opts.tool === "show" || opts.tool === "assets") {
5497
5486
  let remainingImageBytes = MAX_IMAGE_ATTACHMENT_BYTES;
5498
- for (const [imagePath, mimeType] of imagePaths(envelope)) {
5487
+ for (const [imagePath, mimeType] of collectImageAssetPaths(envelope)) {
5499
5488
  opts.signal?.throwIfAborted();
5500
5489
  if (opts.imageMode === "off")
5501
5490
  content.push({ type: "text", text: `Image available at ${imagePath}; image attachments are disabled by readseek.imageMode.` });
@@ -5535,7 +5524,7 @@ async function executeAccess(opts) {
5535
5524
  }
5536
5525
  }
5537
5526
  function registerAccessTools(pi, options = {}) {
5538
- for (const name of Object.keys(operations)) {
5527
+ for (const name of ACCESS_TOOLS) {
5539
5528
  const registeredName = name === "show" ? options.name ?? `readSeek_${name}` : `readSeek_${name}`;
5540
5529
  const contract = getToolContract(name);
5541
5530
  const metadata = defineToolPromptMetadata({
@@ -5558,19 +5547,20 @@ function registerAccessTools(pi, options = {}) {
5558
5547
  renderCall(args, theme, ...rest) {
5559
5548
  const context = rest[0] ?? {};
5560
5549
  const cwd = context.cwd ?? process.cwd();
5550
+ const record = args && typeof args === "object" ? args : undefined;
5561
5551
  const label = renderToolLabel(theme, registeredName);
5562
- const filePath = typeof args?.path === "string" ? args.path : args?.path ? String(args.path) : "";
5552
+ const filePath = typeof record?.path === "string" ? record.path : record?.path ? String(record.path) : "";
5563
5553
  const renderedPath = filePath ? linkToolPath(theme?.fg ? theme.fg("accent", filePath) : filePath, filePath, cwd) : "";
5564
- const atBadge = args?.at ? theme?.fg ? theme.fg("dim", `@ ${args.at}`) : `@ ${args.at}` : "";
5554
+ const atBadge = record?.at ? theme?.fg ? theme.fg("dim", `@ ${String(record.at)}`) : `@ ${String(record.at)}` : "";
5565
5555
  const flags = [
5566
- args?.limit !== undefined && `limit=${args.limit}`,
5567
- args?.end !== undefined && `end=${args.end}`,
5568
- args?.depth !== undefined && `depth=${args.depth}`,
5569
- args?.kind && `kind=${args.kind}`,
5570
- args?.outline && "outline",
5571
- args?.noAnchors && "no-anchors",
5572
- args?.level && `level=${args.level}`
5573
- ].filter(Boolean);
5556
+ record?.limit !== undefined && `limit=${String(record.limit)}`,
5557
+ record?.end !== undefined && `end=${String(record.end)}`,
5558
+ record?.depth !== undefined && `depth=${String(record.depth)}`,
5559
+ Boolean(record?.kind) && `kind=${String(record?.kind)}`,
5560
+ Boolean(record?.outline) && "outline",
5561
+ Boolean(record?.noAnchors) && "no-anchors",
5562
+ Boolean(record?.level) && `level=${String(record?.level)}`
5563
+ ].filter((flag) => Boolean(flag));
5574
5564
  const flagsBadge = flags.length > 0 ? theme?.fg ? theme.fg("dim", `[${flags.join(",")}]`) : `[${flags.join(",")}]` : "";
5575
5565
  const text = clampLineToWidth([label, renderedPath, atBadge, flagsBadge].filter(Boolean).join(" "), context.width);
5576
5566
  return upsertTextComponent(context.lastComponent, text);
@@ -5582,8 +5572,10 @@ function registerAccessTools(pi, options = {}) {
5582
5572
  const text = result.content?.find((item) => item.type === "text")?.text ?? "";
5583
5573
  if (isError || result.isError)
5584
5574
  return renderErrorResult(text, { expanded, width, fallback: `${registeredName} failed`, theme });
5585
- const presentation = result.details?.readSeekValue?.presentation;
5586
- const envelope = result.details?.readSeekValue?.envelope;
5575
+ const details = result.details;
5576
+ const readSeekValue = details?.readSeekValue;
5577
+ const presentation = readSeekValue?.presentation;
5578
+ const envelope = readSeekValue?.envelope;
5587
5579
  if (presentation) {
5588
5580
  const warning = typeof envelope?.warning === "string" && envelope.warning ? presentation.notices.at(-1) : undefined;
5589
5581
  const attachments = result.content?.filter((item) => item.type === "text").slice(1).map((item) => item.text) ?? [];
@@ -5593,7 +5585,7 @@ function registerAccessTools(pi, options = {}) {
5593
5585
  const summary = summaryLine(presentation.summary, { hidden: hasExpandable && !expanded, theme, style: hasWarning ? "warning" : "success" });
5594
5586
  return renderShowPresentation(summary, presentation.body, extras, expanded, theme, width);
5595
5587
  }
5596
- const nonShowSummary = resolveNonShowSummary(result.details?.readSeekValue);
5588
+ const nonShowSummary = resolveNonShowSummary(readSeekValue?.tool && readSeekValue.envelope !== undefined ? readSeekValue : undefined);
5597
5589
  const summary = summaryLine(nonShowSummary, { hidden: !!text && !expanded, theme, style: "success" });
5598
5590
  return new Text7(clampLinesToWidth((expanded ? `${summary}
5599
5591
  ${text}` : summary).split(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-readseek",
3
- "version": "0.13.3",
3
+ "version": "0.13.4",
4
4
  "description": "Pi extension for LINE:HASH-anchored file operations and structural code navigation",
5
5
  "type": "module",
6
6
  "exports": {
@@ -39,8 +39,8 @@
39
39
  "node": ">=20.0.0"
40
40
  },
41
41
  "dependencies": {
42
- "@jarkkojs/readseek": "^0.13.3",
43
- "@jarkkojs/readseek-api": "^0.13.3",
42
+ "@jarkkojs/readseek": "^0.13.4",
43
+ "@jarkkojs/readseek-api": "^0.13.4",
44
44
  "diff": "^9.0.0",
45
45
  "xxhash-wasm": "^1.1.0"
46
46
  },