Files
learnharness/src/agent/tools/find.ts
T
amosblomqvist 7a3e19e95f feat(sources v1): the agent locates files itself — ls/find/grep + tool-call cards
User pivot (2026-09-19): no attachments UI at all. Pasting paths is native
for technical users and alien for everyone else - so the agent gets the
tools to find what the learner merely NAMES. The learner communicates in
messages; the agent locates and reads. Zero cross-stream seams: paths
already live in tool parts, so the sources "list" is the transcript.

- ls/find/grep: pi-verbatim schemas, descriptions, and output formats
  (fd's glob semantics, rg's path:line: match format, pi's truncation
  notices), ported to pure Node - no binaries, no shell-out, read-only by
  construction. Deltas from pi: home-anchored resolution (the harness has
  no cwd), .gitignore replaced by hard noise exclusions
  (node_modules/.git/Library/.Trash), 10s walk timeout with partial results.
- read: description swapped to pi-verbatim (doctrine moved to the prompt);
  relative paths now resolve against the learner's home like the rest.
- prompts/shared/05-learner-files.md: one minimal doctrine fragment
  composed into BOTH agents (composeInstructions grew a shared/ dir,
  before the agent's own fragments). teacher/30-jobs.md keeps only the
  pdf-dispatch addendum.
- ToolCallCard: the generic quiet tool-call card the user specced -
  collapsed one-liner (tool name + headline argument), expandable to full
  input/output, errors red, image payloads never render. Registered for
  read/ls/find/grep.
- ui-message.ts: TeacherUITools entries for the four tools (mechanical).
- tests: fs-tools suite (glob semantics, pi formats, exclusions, limits),
  registry/card renders, shared-fragment composition pins, tool-registry
  key updates, read re-anchor.
2026-09-19 16:50:20 +03:00

79 lines
2.9 KiB
TypeScript

import * as fs from "node:fs/promises";
import * as path from "node:path";
import { z } from "zod";
import { lhTool } from "../lh-tool.ts";
import {
capOutput,
formatSize,
MAX_OUTPUT_BYTES,
matchGlob,
resolveSourcePath,
walkFiles,
} from "./fs-shared.ts";
/**
* The find tool — sources v1 (2026-09-19): pi's dist/core/tools/find.js
* ported to a pure-Node walker (pi shells out to fd; no binaries here —
* Electron/Windows-safe, fs-shared.ts). Schemas, fd's glob semantics
* (basename-mode without a slash, implied deep prefix with one), relativized output,
* and the notice formats are pi-verbatim; the deltas: home-anchored
* default, .gitignore replaced by hard noise exclusions, and a wall-clock
* timeout with partial results. Read-only by construction.
*/
const DEFAULT_LIMIT = 1000;
const findInputSchema = z.object({
pattern: z
.string()
.min(1)
.describe("Glob pattern to match files, e.g. '*.ts', '**/*.json', or 'src/**/*.spec.ts'"),
path: z.string().optional().describe("Directory to search in (default: the learner's home directory)"),
limit: z.number().int().positive().optional().describe("Maximum number of results (default: 1000)"),
});
export const findTool = lhTool({
name: "find",
description: `Search for files by glob pattern. Returns matching file paths relative to the search directory. Ignores node_modules, .git, and Library directories. Output is truncated to ${DEFAULT_LIMIT} results or ${formatSize(MAX_OUTPUT_BYTES)} (whichever is hit first).`,
schema: findInputSchema,
async execute(input) {
const searchPath = resolveSourcePath(input.path);
let stat;
try {
stat = await fs.stat(searchPath);
} catch {
throw new Error(`Path not found: ${searchPath}`);
}
if (!stat.isDirectory()) throw new Error(`Not a directory: ${searchPath}`);
const effectiveLimit = input.limit ?? DEFAULT_LIMIT;
const matches: string[] = [];
let limitReached = false;
const { timedOut } = await walkFiles(
searchPath,
(filePath) => {
const rel = path.relative(searchPath, filePath).split(path.sep).join("/");
if (!matchGlob(rel, input.pattern)) return false;
if (matches.length >= effectiveLimit) {
limitReached = true;
return true; // stop the walk
}
matches.push(rel);
return false;
},
);
if (matches.length === 0 && !limitReached) {
return timedOut
? `Search timed out after 10s with no matches yet. Narrow the search to a subdirectory.`
: "No files found matching pattern";
}
const { content, truncated } = capOutput(matches);
const notices: string[] = [];
if (limitReached || matches.length >= effectiveLimit) notices.push(`${effectiveLimit} results limit reached`);
if (truncated) notices.push(`${formatSize(MAX_OUTPUT_BYTES)} limit reached`);
if (timedOut) notices.push("search timed out after 10s — partial results, narrow the directory");
return notices.length > 0 ? `${content}\n\n[${notices.join(". ")}]` : content;
},
});