dsh-hashline-edit 0.5.1 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -808,12 +808,12 @@ async function resolveTarget(path) {
808
808
  if (remainingParts.length === 0) {
809
809
  return currentPath;
810
810
  }
811
- const [nextPart, ...tail] = remainingParts;
811
+ const [nextPart, ...tail2] = remainingParts;
812
812
  const candidatePath = join4(currentPath, nextPart);
813
813
  try {
814
814
  const candidateStats = await lstat(candidatePath);
815
815
  if (!candidateStats.isSymbolicLink()) {
816
- return resParts(candidatePath, tail);
816
+ return resParts(candidatePath, tail2);
817
817
  }
818
818
  if (visitedSymlinks.has(candidatePath)) {
819
819
  const error = new Error(
@@ -825,10 +825,10 @@ async function resolveTarget(path) {
825
825
  visitedSymlinks.add(candidatePath);
826
826
  const linkTargetPath = resolve(dirname2(candidatePath), await readlink(candidatePath));
827
827
  const targetParts = linkTargetPath.slice(parse(linkTargetPath).root.length).split(sep).filter((part) => part.length > 0);
828
- return resParts(parse(linkTargetPath).root, [...targetParts, ...tail]);
828
+ return resParts(parse(linkTargetPath).root, [...targetParts, ...tail2]);
829
829
  } catch (error) {
830
830
  if (errCode(error) === "ENOENT") {
831
- return join4(candidatePath, ...tail);
831
+ return join4(candidatePath, ...tail2);
832
832
  }
833
833
  throw error;
834
834
  }
@@ -1598,7 +1598,7 @@ function registerNativeToolHiding(rootCtx, agentCtx, config) {
1598
1598
  });
1599
1599
  if (disposeAssemble !== void 0) disposers.push(disposeAssemble);
1600
1600
  const disposeGuard = tools?.guard?.(
1601
- (execution) => hidden.has(execution.name) ? nativeEditorDenial(config.toolNames, execution.name) : void 0
1601
+ (execution) => hidden.has(execution.name) ? config.denialText?.(execution.name) ?? nativeEditorDenial(config.toolNames, execution.name) : void 0
1602
1602
  );
1603
1603
  if (disposeGuard !== void 0) disposers.push(disposeGuard);
1604
1604
  return () => {
@@ -1965,6 +1965,13 @@ var GUIDANCE_SECTIONS = [
1965
1965
  orderName: "TOOL_READ",
1966
1966
  renderDefault: () => guidanceText("", loadGuide("../prompts/read-guidelines.md"))
1967
1967
  },
1968
+ {
1969
+ name: "tool:rg",
1970
+ // WHY: this tool replaces the native grep, so its brief belongs in that tool's prompt slot.
1971
+ defaultOrder: 1500,
1972
+ orderName: "TOOL_GREP",
1973
+ renderDefault: () => guidanceText("", loadGuide("../prompts/rg-guidelines.md"))
1974
+ },
1968
1975
  {
1969
1976
  name: "tool:codegraph",
1970
1977
  defaultOrder: 1200,
@@ -2020,6 +2027,7 @@ function orderResolver(registry) {
2020
2027
  function sectionEnabled(name2, toggles) {
2021
2028
  if (toggles === void 0) return true;
2022
2029
  if (name2 === "tool:read") return toggles.read;
2030
+ if (name2 === "tool:rg") return toggles.rg === true;
2023
2031
  if (name2 === "tool:write") return toggles.applyPatch || toggles.edit;
2024
2032
  if (name2 === "tool:apply_patch") return toggles.applyPatch;
2025
2033
  if (name2 === "tool:edit") return toggles.edit;
@@ -3872,8 +3880,8 @@ function contextLinesToShow(displayLines, lastWasChange, nextPartIsChange, conte
3872
3880
  skipStart = Math.max(0, displayLines.length - contextLines);
3873
3881
  linesToShow = displayLines.slice(skipStart);
3874
3882
  } else if (nextPartIsChange && displayLines.length > contextLines * 2) {
3875
- const tail = contextLines === 0 ? [] : displayLines.slice(-contextLines);
3876
- linesToShow = [...displayLines.slice(0, contextLines), UNTOUCHED_MARKER, ...tail];
3883
+ const tail2 = contextLines === 0 ? [] : displayLines.slice(-contextLines);
3884
+ linesToShow = [...displayLines.slice(0, contextLines), UNTOUCHED_MARKER, ...tail2];
3877
3885
  skipMiddle = displayLines.length - contextLines * 2;
3878
3886
  } else if (!nextPartIsChange && linesToShow.length > contextLines) {
3879
3887
  linesToShow = linesToShow.slice(0, contextLines);
@@ -6025,9 +6033,9 @@ function buildRangeServeBlock(startLine, endLine, fileHashes, fileLines) {
6025
6033
  const last = Math.max(first, Math.min(endLine, Math.max(len, first)));
6026
6034
  const servedRows = buildRangeServeRows(first, last, fileHashes);
6027
6035
  const totalLen = endLine - startLine + 1;
6028
- const tail = first === startLine && servedRows.length < totalLen ? `
6036
+ const tail2 = first === startLine && servedRows.length < totalLen ? `
6029
6037
  ${paginationHint(startLine + servedRows.length, totalLen - servedRows.length)}` : "";
6030
- return { servedRows, rendered: fmtServedRows(servedRows, fileLines) + tail };
6038
+ return { servedRows, rendered: fmtServedRows(servedRows, fileLines) + tail2 };
6031
6039
  }
6032
6040
  function assembleRejectAndServe(args) {
6033
6041
  const { servedRows, rendered } = buildRangeServeBlock(
@@ -10221,16 +10229,16 @@ function createDefaultReadSpanProvider(io) {
10221
10229
  };
10222
10230
  return createReadSpanProvider(readTextFile === void 0 ? {} : { readTextFile });
10223
10231
  }
10224
- async function loadGovernedText(deps, absolutePath, displayPath, signal) {
10232
+ async function loadGovernedText(deps, absolutePath, displayPath2, signal) {
10225
10233
  const loaded = await loadFileKindAndText(absolutePath, {
10226
- displayPath,
10234
+ displayPath: displayPath2,
10227
10235
  ...deps.coreIo === void 0 ? {} : { io: deps.coreIo },
10228
10236
  ...signal === void 0 ? {} : { signal }
10229
10237
  });
10230
- if (loaded.kind !== "text") throw unsupportedLoaded(displayPath, loaded);
10238
+ if (loaded.kind !== "text") throw unsupportedLoaded(displayPath2, loaded);
10231
10239
  const decoded = decodeUtf8Strict(
10232
10240
  deps.coreIo === void 0 ? await deps.io.read(absolutePath, signal) : await deps.coreIo.readFile(await deps.coreIo.resolve(absolutePath), signal),
10233
- displayPath
10241
+ displayPath2
10234
10242
  );
10235
10243
  const stats = loaded.stats;
10236
10244
  return {
@@ -11247,6 +11255,8 @@ async function plan(deps, request) {
11247
11255
  }
11248
11256
  }
11249
11257
  var GREP_TOOL_NAME = "grep";
11258
+ var RG_TOOL_NAME = "rg";
11259
+ var GREP_TOOL_NAMES = [GREP_TOOL_NAME, RG_TOOL_NAME];
11250
11260
  var GREP_INLINE_MAX_MATCHES = 250;
11251
11261
  var GREP_VIEW_MAX_INLINE_TOKENS = 12500;
11252
11262
  var TOKEN_CHARS_PER_UNIT = 4;
@@ -11451,7 +11461,7 @@ function createShellHooks(deps) {
11451
11461
  async postExecute(exec, result, next) {
11452
11462
  const elapsed = deps.metrics === void 0 ? void 0 : stopwatch();
11453
11463
  const decision = await next();
11454
- if (exec.name === GREP_TOOL_NAME)
11464
+ if (GREP_TOOL_NAMES.includes(exec.name))
11455
11465
  return grepPostExecute(deps, exec, result, decision, elapsed);
11456
11466
  if (!SHELL_TOOL_NAMES.includes(exec.name)) return decision;
11457
11467
  if (result.isError || decision.kind !== "accept") return decision;
@@ -12375,8 +12385,8 @@ function resolveRequestPath(path, cwd) {
12375
12385
  }
12376
12386
  const cwdAbsolute = resolvePath2(cwd);
12377
12387
  const absolutePath = isAbsolute6(path) ? resolvePath2(path) : resolvePath2(cwdAbsolute, path);
12378
- const relative2 = relativePath(cwdAbsolute, absolutePath);
12379
- if (relative2.startsWith("..") || isAbsolute6(relative2)) {
12388
+ const relative3 = relativePath(cwdAbsolute, absolutePath);
12389
+ if (relative3.startsWith("..") || isAbsolute6(relative3)) {
12380
12390
  return { ok: false, message: "path must stay inside the workspace" };
12381
12391
  }
12382
12392
  return { ok: true, value: { path, absolutePath } };
@@ -16817,13 +16827,135 @@ function runCodegraph(invocation, args, options) {
16817
16827
  });
16818
16828
  }
16819
16829
 
16830
+ // dsh/rg/cli.ts
16831
+ import { spawn as spawn2 } from "node:child_process";
16832
+ import { existsSync as existsSync6 } from "node:fs";
16833
+ import { join as join11 } from "node:path";
16834
+ var WINDOWS_RG_NAMES = ["rg.exe", "rg", "rg.cmd", "rg.bat"];
16835
+ var POSIX_RG_NAMES = ["rg"];
16836
+ function isCommandShim2(entry) {
16837
+ const lower = entry.toLowerCase();
16838
+ return lower.endsWith(".cmd") || lower.endsWith(".bat");
16839
+ }
16840
+ function resolveRgInvocation(options = {}) {
16841
+ const platform = options.platform ?? process.platform;
16842
+ const exists = options.exists ?? existsSync6;
16843
+ const explicit = options.explicitPath?.trim() ?? "";
16844
+ if (explicit !== "") {
16845
+ if (!exists(explicit)) {
16846
+ return { ok: false, problem: `rgPath points at "${explicit}", which does not exist` };
16847
+ }
16848
+ if (isCommandShim2(explicit)) {
16849
+ return {
16850
+ ok: false,
16851
+ problem: `rgPath "${explicit}" is a shell shim; point it at rg.exe instead`
16852
+ };
16853
+ }
16854
+ return { ok: true, invocation: { command: explicit, prefixArgs: [], source: explicit } };
16855
+ }
16856
+ const pathValue = options.pathValue ?? process.env.PATH ?? "";
16857
+ const separator = platform === "win32" ? ";" : ":";
16858
+ const names = platform === "win32" ? WINDOWS_RG_NAMES : POSIX_RG_NAMES;
16859
+ let shim;
16860
+ for (const directory of pathValue.split(separator)) {
16861
+ if (directory === "") continue;
16862
+ for (const name2 of names) {
16863
+ const entry = join11(directory, name2);
16864
+ if (!exists(entry)) continue;
16865
+ if (isCommandShim2(entry)) {
16866
+ shim ??= entry;
16867
+ continue;
16868
+ }
16869
+ return { ok: true, invocation: { command: entry, prefixArgs: [], source: entry } };
16870
+ }
16871
+ }
16872
+ if (shim !== void 0) {
16873
+ return {
16874
+ ok: false,
16875
+ problem: `only a shell shim was found at "${shim}"; put the real rg.exe on PATH`
16876
+ };
16877
+ }
16878
+ return { ok: false, problem: "no rg executable was found on PATH" };
16879
+ }
16880
+ var RG_TIMEOUT_MS = 3e4;
16881
+ var MAX_CAPTURE_CHARS2 = 8e6;
16882
+ function runRg(invocation, args, options) {
16883
+ options.signal?.throwIfAborted();
16884
+ const timeoutMs = options.timeoutMs ?? RG_TIMEOUT_MS;
16885
+ const env = {
16886
+ ...process.env,
16887
+ // WHY: the transport is machine-read JSON; a colour escape would corrupt a parsed line.
16888
+ NO_COLOR: "1",
16889
+ FORCE_COLOR: "0",
16890
+ ...options.env
16891
+ };
16892
+ return new Promise((resolve6, reject) => {
16893
+ const child = spawn2(invocation.command, [...invocation.prefixArgs, ...args], {
16894
+ cwd: options.cwd,
16895
+ env,
16896
+ windowsHide: true,
16897
+ stdio: ["ignore", "pipe", "pipe"]
16898
+ });
16899
+ let stdout = "";
16900
+ let stderr = "";
16901
+ let timedOut = false;
16902
+ let overflow = false;
16903
+ let settled = false;
16904
+ const capture = (current, chunk) => {
16905
+ if (current.length >= MAX_CAPTURE_CHARS2) {
16906
+ overflow = true;
16907
+ return current;
16908
+ }
16909
+ const next = current + chunk;
16910
+ if (next.length > MAX_CAPTURE_CHARS2) {
16911
+ overflow = true;
16912
+ return next.slice(0, MAX_CAPTURE_CHARS2);
16913
+ }
16914
+ return next;
16915
+ };
16916
+ const stop = () => {
16917
+ if (settled) return;
16918
+ settled = true;
16919
+ clearTimeout(timer);
16920
+ options.signal?.removeEventListener("abort", onAbort);
16921
+ };
16922
+ const onAbort = () => {
16923
+ child.kill();
16924
+ stop();
16925
+ reject(options.signal?.reason ?? new Error("grep run aborted"));
16926
+ };
16927
+ const timer = setTimeout(() => {
16928
+ timedOut = true;
16929
+ child.kill();
16930
+ }, timeoutMs);
16931
+ child.stdout?.setEncoding("utf8");
16932
+ child.stderr?.setEncoding("utf8");
16933
+ child.stdout?.on("data", (chunk) => {
16934
+ stdout = capture(stdout, chunk);
16935
+ });
16936
+ child.stderr?.on("data", (chunk) => {
16937
+ stderr = capture(stderr, chunk);
16938
+ });
16939
+ child.on("error", (error) => {
16940
+ stop();
16941
+ reject(error);
16942
+ });
16943
+ child.on("close", (code) => {
16944
+ if (settled) return;
16945
+ stop();
16946
+ resolve6({ stdout, stderr, code, timedOut, overflow });
16947
+ });
16948
+ options.signal?.addEventListener("abort", onAbort, { once: true });
16949
+ });
16950
+ }
16951
+
16820
16952
  // dsh/codegraph/tools.ts
16821
16953
  import {
16822
16954
  defineTool as defineTool4
16823
16955
  } from "@deepseek-ai/dsh-tools";
16824
16956
 
16825
16957
  // dsh/codegraph/project.ts
16826
- import { dirname as dirname11, join as join11 } from "node:path";
16958
+ import { dirname as dirname11, join as join12 } from "node:path";
16827
16959
  var CODEGRAPH_DIR = ".codegraph";
16828
16960
  var REPOSITORY_MARKER = ".git";
16829
16961
  async function resolveProjectPath(io, request) {
@@ -16832,8 +16964,8 @@ async function resolveProjectPath(io, request) {
16832
16964
  let distance = 0;
16833
16965
  for (; ; ) {
16834
16966
  request.signal?.throwIfAborted();
16835
- const index = await io.stat(join11(directory, CODEGRAPH_DIR), request.signal);
16836
- const repository = await io.stat(join11(directory, REPOSITORY_MARKER), request.signal);
16967
+ const index = await io.stat(join12(directory, CODEGRAPH_DIR), request.signal);
16968
+ const repository = await io.stat(join12(directory, REPOSITORY_MARKER), request.signal);
16837
16969
  const isRepository = repository !== void 0;
16838
16970
  if (index?.isDirectory === true && (distance === 0 || isRepository)) {
16839
16971
  return { ok: true, projectPath: directory, distance };
@@ -17357,17 +17489,17 @@ function buildCodegraphTools(deps, options) {
17357
17489
  }
17358
17490
 
17359
17491
  // dsh/diagnostics/tools.ts
17360
- import { dirname as dirname14, join as join13 } from "node:path";
17492
+ import { dirname as dirname14, join as join14 } from "node:path";
17361
17493
  import {
17362
17494
  defineTool as defineTool5
17363
17495
  } from "@deepseek-ai/dsh-tools";
17364
17496
 
17365
17497
  // dsh/diagnostics/cli.ts
17366
- import { spawn as spawn2 } from "node:child_process";
17367
- import { existsSync as existsSync6 } from "node:fs";
17368
- import { dirname as dirname12, extname as extname2, join as join12 } from "node:path";
17498
+ import { spawn as spawn3 } from "node:child_process";
17499
+ import { existsSync as existsSync7 } from "node:fs";
17500
+ import { dirname as dirname12, extname as extname2, join as join13 } from "node:path";
17369
17501
  var DIAGNOSTICS_TOOL_NAMES = ["cargo-check", "cargo-clippy", "tsc"];
17370
- var TSC_SCRIPT = join12("node_modules", "typescript", "bin", "tsc");
17502
+ var TSC_SCRIPT = join13("node_modules", "typescript", "bin", "tsc");
17371
17503
  var WINDOWS_CARGO_NAMES = ["cargo.exe", "cargo.cmd", "cargo.bat", "cargo"];
17372
17504
  var POSIX_CARGO_NAMES = ["cargo"];
17373
17505
  var WINDOWS_TSC_NAMES = ["tsc.cmd", "tsc.exe", "tsc.bat", "tsc"];
@@ -17387,7 +17519,7 @@ function isScript2(entry) {
17387
17519
  const ext = extname2(entry).toLowerCase();
17388
17520
  return ext === ".js" || ext === ".mjs" || ext === ".cjs";
17389
17521
  }
17390
- function isCommandShim2(entry) {
17522
+ function isCommandShim3(entry) {
17391
17523
  const lower = entry.toLowerCase();
17392
17524
  return lower.endsWith(".cmd") || lower.endsWith(".bat");
17393
17525
  }
@@ -17397,7 +17529,7 @@ function pathDirectories(pathValue, platform) {
17397
17529
  }
17398
17530
  function runnableEntry(entry, platform) {
17399
17531
  if (isScript2(entry)) return { command: process.execPath, prefixArgs: [entry], source: entry };
17400
- if (isCommandShim2(entry)) return void 0;
17532
+ if (isCommandShim3(entry)) return void 0;
17401
17533
  const ext = extname2(entry).toLowerCase();
17402
17534
  if (ext === "" && platform === "win32") return void 0;
17403
17535
  return { command: entry, prefixArgs: [], source: entry };
@@ -17414,15 +17546,15 @@ function findUpward(start, candidate, exists) {
17414
17546
  }
17415
17547
  function resolveCargoInvocation(options = {}) {
17416
17548
  const platform = options.platform ?? process.platform;
17417
- const exists = options.exists ?? existsSync6;
17549
+ const exists = options.exists ?? existsSync7;
17418
17550
  const names = platform === "win32" ? WINDOWS_CARGO_NAMES : POSIX_CARGO_NAMES;
17419
17551
  let shim;
17420
17552
  for (const directory of pathDirectories(options.pathValue ?? process.env.PATH ?? "", platform)) {
17421
17553
  for (const name2 of names) {
17422
- const entry = join12(directory, name2);
17554
+ const entry = join13(directory, name2);
17423
17555
  if (!exists(entry)) continue;
17424
- if (isCommandShim2(entry)) {
17425
- const sibling = join12(directory, "cargo.exe");
17556
+ if (isCommandShim3(entry)) {
17557
+ const sibling = join13(directory, "cargo.exe");
17426
17558
  if (!exists(sibling)) {
17427
17559
  shim ??= entry;
17428
17560
  continue;
@@ -17443,8 +17575,8 @@ function resolveCargoInvocation(options = {}) {
17443
17575
  }
17444
17576
  function resolveTscInvocation(cwd, options = {}) {
17445
17577
  const platform = options.platform ?? process.platform;
17446
- const exists = options.exists ?? existsSync6;
17447
- const local = findUpward(cwd, (directory) => join12(directory, TSC_SCRIPT), exists);
17578
+ const exists = options.exists ?? existsSync7;
17579
+ const local = findUpward(cwd, (directory) => join13(directory, TSC_SCRIPT), exists);
17448
17580
  if (local !== void 0) {
17449
17581
  return {
17450
17582
  ok: true,
@@ -17455,12 +17587,12 @@ function resolveTscInvocation(cwd, options = {}) {
17455
17587
  let shim;
17456
17588
  for (const directory of pathDirectories(options.pathValue ?? process.env.PATH ?? "", platform)) {
17457
17589
  for (const name2 of names) {
17458
- const entry = join12(directory, name2);
17590
+ const entry = join13(directory, name2);
17459
17591
  if (!exists(entry)) continue;
17460
- if (isCommandShim2(entry)) {
17592
+ if (isCommandShim3(entry)) {
17461
17593
  const binDir = dirname12(entry);
17462
17594
  for (const root of [binDir, dirname12(binDir)]) {
17463
- const script = join12(root, TSC_SCRIPT);
17595
+ const script = join13(root, TSC_SCRIPT);
17464
17596
  if (!exists(script)) continue;
17465
17597
  return {
17466
17598
  ok: true,
@@ -17486,7 +17618,7 @@ function resolveTscInvocation(cwd, options = {}) {
17486
17618
  };
17487
17619
  }
17488
17620
  var DIAGNOSTICS_TIMEOUT_MS = 12e4;
17489
- var MAX_CAPTURE_CHARS2 = 2e6;
17621
+ var MAX_CAPTURE_CHARS3 = 2e6;
17490
17622
  function runDiagnosticsCommand(invocation, args, options) {
17491
17623
  options.signal?.throwIfAborted();
17492
17624
  const timeoutMs = options.timeoutMs ?? DIAGNOSTICS_TIMEOUT_MS;
@@ -17500,7 +17632,7 @@ function runDiagnosticsCommand(invocation, args, options) {
17500
17632
  ...options.env
17501
17633
  };
17502
17634
  return new Promise((resolve6, reject) => {
17503
- const child = spawn2(invocation.command, [...invocation.prefixArgs, ...args], {
17635
+ const child = spawn3(invocation.command, [...invocation.prefixArgs, ...args], {
17504
17636
  cwd: options.cwd,
17505
17637
  env,
17506
17638
  windowsHide: true,
@@ -17510,7 +17642,7 @@ function runDiagnosticsCommand(invocation, args, options) {
17510
17642
  let stderr = "";
17511
17643
  let timedOut = false;
17512
17644
  let settled = false;
17513
- const capture = (current, chunk) => current.length >= MAX_CAPTURE_CHARS2 ? current : (current + chunk).slice(0, MAX_CAPTURE_CHARS2);
17645
+ const capture = (current, chunk) => current.length >= MAX_CAPTURE_CHARS3 ? current : (current + chunk).slice(0, MAX_CAPTURE_CHARS3);
17514
17646
  const stop = () => {
17515
17647
  if (settled) return;
17516
17648
  settled = true;
@@ -17905,7 +18037,7 @@ async function hasProjectConfig(deps, cwd, signal) {
17905
18037
  let directory = cwd;
17906
18038
  for (; ; ) {
17907
18039
  for (const name2 of TSCONFIG_NAMES) {
17908
- const info = await deps.io.stat(join13(directory, name2), signal).catch(() => void 0);
18040
+ const info = await deps.io.stat(join14(directory, name2), signal).catch(() => void 0);
17909
18041
  if (info?.isFile === true) return true;
17910
18042
  }
17911
18043
  const parent = dirname14(directory);
@@ -18004,6 +18136,359 @@ function buildDiagnosticsTools(deps, options = {}) {
18004
18136
  return [buildDiagnosticsTool(deps, options)];
18005
18137
  }
18006
18138
 
18139
+ // dsh/rg/tools.ts
18140
+ import {
18141
+ defineTool as defineTool6
18142
+ } from "@deepseek-ai/dsh-tools";
18143
+
18144
+ // dsh/rg/command.ts
18145
+ import { isAbsolute as isAbsolute8, relative as relative2 } from "node:path";
18146
+ function validateInclude(include) {
18147
+ if (include.trim().length === 0) throw new Error("include must be a non-empty glob when given");
18148
+ if (include.startsWith("!"))
18149
+ throw new Error(
18150
+ 'include must be a positive glob filter; negated patterns ("!\u2026") are not supported'
18151
+ );
18152
+ let braceDepth = 0;
18153
+ for (const character of include) {
18154
+ if (character === "{") braceDepth += 1;
18155
+ else if (character === "}") braceDepth = Math.max(0, braceDepth - 1);
18156
+ else if (character === "," && braceDepth === 0) {
18157
+ throw new Error(
18158
+ "include must be one glob, not a comma-separated list (use {a,b} alternation instead)"
18159
+ );
18160
+ }
18161
+ }
18162
+ }
18163
+ function booleanArg2(record, key) {
18164
+ const value = record[key];
18165
+ if (value === void 0) return void 0;
18166
+ if (typeof value !== "boolean") throw new Error(`${key} must be a boolean when given`);
18167
+ return value;
18168
+ }
18169
+ function parseRgArgs(raw) {
18170
+ const record = typeof raw === "object" && raw !== null ? raw : {};
18171
+ const pattern = record.pattern;
18172
+ if (typeof pattern !== "string" || pattern.length === 0)
18173
+ throw new Error("pattern must be a non-empty string");
18174
+ const path = record.path;
18175
+ if (path !== void 0 && (typeof path !== "string" || path.trim().length === 0)) {
18176
+ throw new Error("path must be a non-empty string when given");
18177
+ }
18178
+ const rawInclude = record.include;
18179
+ if (rawInclude !== void 0 && typeof rawInclude !== "string")
18180
+ throw new Error("include must be a string when given");
18181
+ const include = rawInclude === "" ? void 0 : rawInclude;
18182
+ if (include !== void 0) validateInclude(include);
18183
+ return {
18184
+ pattern,
18185
+ ...path === void 0 ? {} : { path },
18186
+ ...include === void 0 ? {} : { include },
18187
+ ...booleanArg2(record, "ignoreCase") === true ? { ignoreCase: true } : {},
18188
+ ...booleanArg2(record, "fixedStrings") === true ? { fixedStrings: true } : {},
18189
+ ...booleanArg2(record, "wordMatch") === true ? { wordMatch: true } : {},
18190
+ ...booleanArg2(record, "hidden") === true ? { hidden: true } : {},
18191
+ ...booleanArg2(record, "noIgnore") === true ? { noIgnore: true } : {}
18192
+ };
18193
+ }
18194
+ function buildRgCommand(input) {
18195
+ const parts = ["--json", `--regexp=${input.pattern}`];
18196
+ if (input.include !== void 0) parts.push(`--glob=${input.include}`);
18197
+ if (input.ignoreCase === true) parts.push("--ignore-case");
18198
+ if (input.fixedStrings === true) parts.push("--fixed-strings");
18199
+ if (input.wordMatch === true) parts.push("--word-regexp");
18200
+ if (input.hidden === true) parts.push("--hidden");
18201
+ if (input.noIgnore === true) parts.push("--no-ignore");
18202
+ if (input.path !== void 0) parts.push("--", input.path);
18203
+ return parts;
18204
+ }
18205
+ function malformedRecord(detail) {
18206
+ return new Error(`rg received malformed --json output (${detail})`);
18207
+ }
18208
+ function parseRecord(line) {
18209
+ let parsed;
18210
+ try {
18211
+ parsed = JSON.parse(line);
18212
+ } catch {
18213
+ throw malformedRecord("a line is not JSON");
18214
+ }
18215
+ if (typeof parsed !== "object" || parsed === null)
18216
+ throw malformedRecord("a record is not an object");
18217
+ const record = parsed;
18218
+ if (record.type !== "match") return void 0;
18219
+ if (typeof record.data !== "object" || record.data === null)
18220
+ throw malformedRecord("a match record has no data");
18221
+ const data = record.data;
18222
+ const pathText = typeof data.path === "object" && data.path !== null ? data.path.text : void 0;
18223
+ if (typeof pathText !== "string") throw malformedRecord("a match record has no path text");
18224
+ if (typeof data.line_number !== "number")
18225
+ throw malformedRecord("a match record has no line number");
18226
+ if (typeof data.lines !== "object" || data.lines === null)
18227
+ throw malformedRecord("a match record has no line content");
18228
+ const lines = data.lines;
18229
+ if (typeof lines.text === "string") {
18230
+ return { path: pathText, lineNumber: data.line_number, line: lines.text.replace(/\r?\n$/, "") };
18231
+ }
18232
+ if (typeof lines.bytes === "string") {
18233
+ return { path: pathText, lineNumber: data.line_number, line: "(line is not valid UTF-8)" };
18234
+ }
18235
+ throw malformedRecord("a match record has neither line text nor bytes");
18236
+ }
18237
+ function parseRgOutput(stdout) {
18238
+ const matches = [];
18239
+ for (const line of stdout.split("\n")) {
18240
+ if (line.length === 0) continue;
18241
+ const match = parseRecord(line);
18242
+ if (match !== void 0) matches.push(match);
18243
+ }
18244
+ return matches;
18245
+ }
18246
+ function displayPath(rawPath, cwd) {
18247
+ const stripped = rawPath.startsWith("./") ? rawPath.slice(2) : rawPath;
18248
+ if (!isAbsolute8(stripped)) return stripped;
18249
+ const relativePath2 = relative2(cwd, stripped);
18250
+ if (relativePath2 === "" || isAbsolute8(relativePath2) || relativePath2.startsWith(".."))
18251
+ return stripped;
18252
+ return relativePath2;
18253
+ }
18254
+
18255
+ // dsh/rg/view.ts
18256
+ var GREP_MAX_LINE_BYTES = 2e3;
18257
+ var GREP_META_MAX_BYTES = 65536;
18258
+ function matchNoun(count) {
18259
+ return count === 1 ? "match" : "matches";
18260
+ }
18261
+ function previewLine(line, maxBytes = GREP_MAX_LINE_BYTES) {
18262
+ if (Buffer.byteLength(line, "utf8") <= maxBytes) return line;
18263
+ let used = 0;
18264
+ let cut = "";
18265
+ for (const character of line) {
18266
+ const size = Buffer.byteLength(character, "utf8");
18267
+ if (used + size > maxBytes) break;
18268
+ used += size;
18269
+ cut += character;
18270
+ }
18271
+ return cut + "\u2026";
18272
+ }
18273
+ function retainMatches(matches, maxMatches = GREP_INLINE_MAX_MATCHES) {
18274
+ const items = matches.slice(0, maxMatches);
18275
+ return { items, seen: matches.length, truncated: matches.length > items.length };
18276
+ }
18277
+ function groupByFile(matches) {
18278
+ const byFile = /* @__PURE__ */ new Map();
18279
+ for (const match of matches) {
18280
+ const entry = { lineNumber: match.lineNumber, line: previewLine(match.line) };
18281
+ const group = byFile.get(match.path);
18282
+ if (group !== void 0) group.push(entry);
18283
+ else byFile.set(match.path, [entry]);
18284
+ }
18285
+ return Array.from(byFile, ([path, fileMatches]) => ({ path, matches: fileMatches }));
18286
+ }
18287
+ function formatRgText(matches) {
18288
+ const retained = retainMatches(matches);
18289
+ if (retained.seen === 0) return "No matches found";
18290
+ const header = retained.truncated ? "Found " + retained.items.length + " of " + retained.seen + " matches" : "Found " + retained.seen + " " + matchNoun(retained.seen);
18291
+ const blocks = groupByFile(retained.items).map(
18292
+ (group) => [
18293
+ group.path,
18294
+ group.matches.map((match) => "Line " + match.lineNumber + ": " + match.line).join("\n")
18295
+ ].join("\n")
18296
+ );
18297
+ const omitted = retained.seen - retained.items.length;
18298
+ const footer = omitted === 0 ? "" : "\n\n(" + omitted + " more " + matchNoun(omitted) + (omitted === 1 ? " was" : " were") + " not shown; narrow the pattern, path, or include.)";
18299
+ return header + "\n\n" + blocks.join("\n\n") + footer;
18300
+ }
18301
+ function metaBytes(meta) {
18302
+ return Buffer.byteLength(JSON.stringify(meta), "utf8");
18303
+ }
18304
+ function capMetaBytes(meta, maxMetaBytes) {
18305
+ if (metaBytes(meta) <= maxMetaBytes) return meta;
18306
+ const files = [...meta.files];
18307
+ while (files.length > 1 && metaBytes({ ...meta, files, truncated: true }) > maxMetaBytes)
18308
+ files.pop();
18309
+ return { ...meta, files, truncated: true };
18310
+ }
18311
+ function rgMeta(matches, failed = false) {
18312
+ const retained = retainMatches(matches);
18313
+ const meta = {
18314
+ shape: "matches",
18315
+ files: groupByFile(retained.items),
18316
+ truncated: retained.truncated,
18317
+ total: retained.seen,
18318
+ ...failed ? { failed: true } : {}
18319
+ };
18320
+ return capMetaBytes(meta, GREP_META_MAX_BYTES);
18321
+ }
18322
+ function isFileMatches(value) {
18323
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
18324
+ const { path, matches } = value;
18325
+ if (typeof path !== "string" || !Array.isArray(matches)) return false;
18326
+ return matches.every((match) => {
18327
+ if (typeof match !== "object" || match === null || Array.isArray(match)) return false;
18328
+ const { lineNumber, line } = match;
18329
+ return typeof lineNumber === "number" && typeof line === "string";
18330
+ });
18331
+ }
18332
+ function searchViewFromMeta(meta) {
18333
+ if (typeof meta !== "object" || meta === null || Array.isArray(meta)) return void 0;
18334
+ const record = meta;
18335
+ if (record.shape !== "matches" || record.failed === true) return void 0;
18336
+ const { files, truncated, total } = record;
18337
+ if (!Array.isArray(files) || !files.every(isFileMatches)) return void 0;
18338
+ if (typeof truncated !== "boolean" || typeof total !== "number") return void 0;
18339
+ return { card: "search", shape: "matches", files, truncated, total };
18340
+ }
18341
+
18342
+ // dsh/rg/tools.ts
18343
+ var RG_TOOL_NAME2 = "rg";
18344
+ var CALL_TIMEOUT_MARGIN_MS = 5e3;
18345
+ var CAPTURE_BUDGET_MB = 8;
18346
+ var DESCRIPTION2 = [
18347
+ "Search file contents with a ripgrep regular expression, executed by the `rg` on PATH (ripgrep's own config and ignore rules apply). Returns matching lines with line numbers, grouped by file.",
18348
+ "This tool is `rg`: use it \u2014 not a shell `grep` or `rg` command \u2014 for file-content search. Matching defaults to ripgrep's smart case; `ignoreCase`, `fixedStrings` and `wordMatch` change how the pattern matches, and `hidden`/`noIgnore` widen which files are searched.",
18349
+ "When the `read` switch is on, every matched line is served as `HASH\u2502content` rows, so the following `edit` or `apply_patch` needs no separate `read`.",
18350
+ "Expected states \u2014 no `rg` on PATH, a rejected pattern, an unreadable target, the 30 s budget \u2014 come back as text guidance, not as an error."
18351
+ ].join("\n\n");
18352
+ var PARAMETERS2 = {
18353
+ pattern: {
18354
+ type: "string",
18355
+ required: true,
18356
+ description: "Regular expression to search for (ripgrep syntax)."
18357
+ },
18358
+ path: {
18359
+ type: "string",
18360
+ description: "File or directory to search. Defaults to the session working directory; a relative path resolves against it."
18361
+ },
18362
+ include: {
18363
+ type: "string",
18364
+ description: 'One glob filter for which files to search (e.g. "*.ts", "*.{js,jsx}"). Not a list; negation is not supported.'
18365
+ },
18366
+ ignoreCase: {
18367
+ type: "boolean",
18368
+ description: "Search case-insensitively (`-i`). Default keeps ripgrep's smart case: insensitive only when the pattern has no uppercase letter."
18369
+ },
18370
+ fixedStrings: {
18371
+ type: "boolean",
18372
+ description: "Treat `pattern` as literal text (`-F`) instead of a regular expression."
18373
+ },
18374
+ wordMatch: {
18375
+ type: "boolean",
18376
+ description: "Only match whole words (`-w`)."
18377
+ },
18378
+ hidden: {
18379
+ type: "boolean",
18380
+ description: "Also search hidden files and directories (`--hidden`)."
18381
+ },
18382
+ noIgnore: {
18383
+ type: "boolean",
18384
+ description: "Ignore `.gitignore`/`.ignore` rules and search every file (`--no-ignore`)."
18385
+ }
18386
+ };
18387
+ var OUTCOME_SCHEMA3 = {
18388
+ type: "object",
18389
+ properties: {
18390
+ matches: {
18391
+ type: "array",
18392
+ required: true,
18393
+ items: {
18394
+ type: "object",
18395
+ additionalProperties: false,
18396
+ properties: {
18397
+ path: { type: "string", required: true },
18398
+ lineNumber: { type: "integer", required: true },
18399
+ line: { type: "string", required: true }
18400
+ }
18401
+ }
18402
+ },
18403
+ note: { type: "string" }
18404
+ },
18405
+ additionalProperties: false
18406
+ };
18407
+ function missingRgText(problem) {
18408
+ return "rg could not run: " + problem + ". Install ripgrep (https://github.com/BurntSushi/ripgrep) and put `rg` on PATH, or set this plugin's `rgPath` config to the executable.";
18409
+ }
18410
+ function tail(text, maxLines = 20) {
18411
+ const lines = text.trimEnd().split("\n");
18412
+ return lines.slice(Math.max(0, lines.length - maxLines)).join("\n");
18413
+ }
18414
+ function outcomeFor(run, cwd, timeoutMs) {
18415
+ if (run.timedOut) {
18416
+ return {
18417
+ matches: [],
18418
+ note: "rg stopped after " + timeoutMs + " ms without finishing. Narrow the pattern, path, or include."
18419
+ };
18420
+ }
18421
+ if (run.overflow) {
18422
+ return {
18423
+ matches: [],
18424
+ note: "rg produced more output than the " + CAPTURE_BUDGET_MB + " MB capture budget and was not parsed. Narrow the pattern, path, or include."
18425
+ };
18426
+ }
18427
+ if (run.code === 1) return { matches: [] };
18428
+ if (run.code !== 0) {
18429
+ const diagnostics = tail(run.stderr);
18430
+ const detail = diagnostics === "" ? " (no stderr output)" : "\n" + diagnostics;
18431
+ return { matches: [], note: "rg exited with code " + String(run.code) + ":" + detail };
18432
+ }
18433
+ return {
18434
+ matches: parseRgOutput(run.stdout).map((match) => ({
18435
+ ...match,
18436
+ path: displayPath(match.path, cwd)
18437
+ }))
18438
+ };
18439
+ }
18440
+ function presentCall(args) {
18441
+ const where = args.path !== void 0 ? " in " + args.path : "";
18442
+ const filter = args.include !== void 0 && args.include !== "" ? " (" + args.include + ")" : "";
18443
+ return {
18444
+ card: "generic",
18445
+ title: "Rg " + args.pattern + where + filter,
18446
+ kind: "search",
18447
+ rawInput: args.pattern
18448
+ };
18449
+ }
18450
+ function buildRgTool(options = {}) {
18451
+ const timeoutMs = options.timeoutMs ?? RG_TIMEOUT_MS;
18452
+ return defineTool6({
18453
+ name: RG_TOOL_NAME2,
18454
+ description: DESCRIPTION2,
18455
+ parameters: PARAMETERS2,
18456
+ // WHY: the spawn timer reports its own timeout as guidance, so the cooperative budget must
18457
+ // WHY: never preempt that message — it only backstops a run that never settles.
18458
+ timeoutMs: timeoutMs + CALL_TIMEOUT_MARGIN_MS,
18459
+ output: {
18460
+ schema: OUTCOME_SCHEMA3,
18461
+ render: (_args, value) => [{ type: "text", text: value.note ?? formatRgText(value.matches) }],
18462
+ presentationMeta: (_args, value) => rgMeta(value.matches, value.note !== void 0)
18463
+ },
18464
+ async execute(args, exec) {
18465
+ const input = parseRgArgs(args);
18466
+ const ctx = resolveToolContext(exec);
18467
+ const locate = options.resolveRg ?? (() => resolveRgInvocation());
18468
+ const resolution = locate();
18469
+ if (!resolution.ok) return { matches: [], note: missingRgText(resolution.problem) };
18470
+ const runner = options.run ?? runRg;
18471
+ let run;
18472
+ try {
18473
+ run = await runner(resolution.invocation, buildRgCommand(input), {
18474
+ cwd: ctx.cwd,
18475
+ signal: ctx.signal,
18476
+ timeoutMs
18477
+ });
18478
+ } catch (error) {
18479
+ ctx.signal?.throwIfAborted();
18480
+ return {
18481
+ matches: [],
18482
+ note: "rg could not start: " + (error instanceof Error ? error.message : String(error))
18483
+ };
18484
+ }
18485
+ return outcomeFor(run, ctx.cwd, timeoutMs);
18486
+ },
18487
+ presentCall,
18488
+ presentResult: (_args, result) => result.isError ? void 0 : searchViewFromMeta(result.meta)
18489
+ });
18490
+ }
18491
+
18007
18492
  // dsh/write-hook.ts
18008
18493
  var AUTO_READ_HEADING = "--- Auto-read (hashline anchors) ---";
18009
18494
  function errorMessage3(error) {
@@ -18196,7 +18681,9 @@ var Config = Schema.object({
18196
18681
  edit: Schema.boolean().default(false).volatile(),
18197
18682
  codegraph: Schema.boolean().default(false).volatile(),
18198
18683
  codegraphPath: Schema.string().default("").volatile(),
18199
- diagnostics: Schema.boolean().default(false).volatile()
18684
+ diagnostics: Schema.boolean().default(false).volatile(),
18685
+ rg: Schema.boolean().default(true).volatile(),
18686
+ rgPath: Schema.string().default("").volatile()
18200
18687
  });
18201
18688
  function switchValue(value, fallback) {
18202
18689
  if (typeof value === "boolean") return value;
@@ -18230,7 +18717,9 @@ function resolveSwitches(config = {}) {
18230
18717
  edit: switchValue(fields.edit, false),
18231
18718
  codegraph: switchValue(fields.codegraph, false),
18232
18719
  codegraphPath: stringValue(fields.codegraphPath, ""),
18233
- diagnostics: switchValue(fields.diagnostics, false)
18720
+ diagnostics: switchValue(fields.diagnostics, false),
18721
+ rg: switchValue(fields.rg, true),
18722
+ rgPath: stringValue(fields.rgPath, "")
18234
18723
  };
18235
18724
  }
18236
18725
  function toolsOfAgent(agent) {
@@ -18302,14 +18791,26 @@ function installAgentTools(rootCtx, agent, metrics, config = {}) {
18302
18791
  if (dispose !== void 0) disposers.push(dispose);
18303
18792
  }
18304
18793
  }
18305
- if (registered.length > 0) {
18794
+ if (switches.rg) {
18795
+ const rg = buildRgTool({
18796
+ resolveRg: () => resolveRgInvocation({ explicitPath: switches.rgPath })
18797
+ });
18798
+ const dispose = registerToolQuietly(rootCtx, agent, rg, "rg");
18799
+ if (dispose !== void 0) disposers.push(dispose);
18800
+ }
18801
+ if (registered.length > 0 || switches.rg) {
18306
18802
  disposers.push(
18307
18803
  registerNativeToolHiding(rootCtx, agent.ctx, {
18308
18804
  toolNames: registered,
18309
- // WHY: never empty `tool:edit`: the native `edit` is hidden only while this
18310
- // WHY: plugin registers its own `edit` brief, and stays visible (with its
18311
- // WHY: brief) otherwise, so the section is never a stale native leftover.
18312
- guidanceToClear: [],
18805
+ // WHY: the `rg` lane replaces the native search tool under a different name, which
18806
+ // WHY: no same-name probe can mask.
18807
+ hiddenToolNames: switches.rg ? ["grep"] : [],
18808
+ // WHY: the native `grep` brief describes a tool this profile no longer has; the
18809
+ // WHY: replacement carries its own `tool:rg` brief.
18810
+ guidanceToClear: switches.rg ? ["tool:grep"] : [],
18811
+ ...switches.rg ? {
18812
+ denialText: (name2) => name2 === "grep" ? "`grep` is disabled in this profile: file-content search goes through the `rg` tool. Call `rg` \u2014 not a shell `grep` or `rg` command." : void 0
18813
+ } : {},
18313
18814
  scope: agent
18314
18815
  })
18315
18816
  );
@@ -18442,6 +18943,21 @@ function apply2(rootCtx, config = {}) {
18442
18943
  }
18443
18944
  }
18444
18945
  }
18946
+ if (switches.rg) {
18947
+ try {
18948
+ disposers.push(
18949
+ rootCtx.tools.register(
18950
+ buildRgTool({
18951
+ resolveRg: () => resolveRgInvocation({ explicitPath: switches.rgPath })
18952
+ })
18953
+ )
18954
+ );
18955
+ } catch (error) {
18956
+ rootCtx.logger.warn(
18957
+ `dsh-hashline-edit: root rg tool registration failed: ${error instanceof Error ? error.message : String(error)}`
18958
+ );
18959
+ }
18960
+ }
18445
18961
  } catch (error) {
18446
18962
  disposeReverse(disposers);
18447
18963
  rootCtx.logger.warn(