Files
learnharness/src/agent/tools/find.ts
T
amosblomqvist b87a6925af Wave A: pi-native tool layer — delete LhTool/toPiTool, TypeBox everywhere, terminate on questions
- src/agent/lh-tool.ts deleted: the zod-wrapped LhTool + toPiTool bridge
  (z.toJSONSchema per call, clientQuestion flag, hand-rolled result mapping)
  is gone. Tools are pi-agent-core native AgentTools now.
- New src/agent/tool-execute.ts owns what the wrapper added: the abort guard
  (runWithAbortGuard: run signal + 30s per-call timeout + 250ms grace,
  'Operation aborted' / timeout wording preserved), ToolInputError (the
  retryable '- problem at path' format), result mapping (string verbatim /
  object JSON / image parts, details rides the record's tool part output),
  and questionResult() — placeholder + terminate:true (owner Option A:
  belt of terminate + slim makeQuestionStopper with the clean-question
  rule; maxTurns deleted from the teaching turn entirely per owner).
- All 11 tool files + tools.ts registries converted to TypeBox parameters
  (typebox@1.3.7, pinned to pi-agent-core's copy). zod refinements
  (quizInputProblems, askOptionProblems, live-nodeId) moved from schemas
  into execute — the model sees the same retryable error shape.
- question-core + contracts/probe TypeBox-authored (single source shared
  with the UI); tool-parts parse seam runs the boundary's full chain
  (Convert → Check → Clean → refinement), fixing the live-smoke lockout:
  pi's boundary Value.Converts correctAnswer: 17 → '17' but the record
  keeps raw args, so a parse without Convert rejected a posed quiz
  (invisible pending question, turn ended). Pinned with the real smoke
  emission shape.
- Subagents converted: demo-builder/researcher AgentTool-native,
  visual-maker/pdf-reader declaration-only pi-ai Tools with local execute
  fns, extraction submit schemas re-authored in TypeBox (owner option 2:
  zod defaults → Type.Optional + fill at the submit seam).
- Accepted delta, flagged: TypeBox-native schemas skip pi's JSON-Schema
  primitive coercion fast path... (boundary still Value.Converts), and
  prober-quiz unknown keys ride through (Value.Clean strips at display).
- Tests: 988 passing (was 967 at the recon baseline); tool-abort and
  read-tool rewritten against the native seams; question-core/question-
  tools/tool-parts/demos/web-search/graph-tools/plan-tree/probe-done/
  tool-toggles converted to Value.Check/execute pins.

Live smoke (PORT=3004, real model): native ls turn streams end-to-end; a
real quiz pose (first attempt missing correctAnswer → tool-input-error →
model retry → posed) terminates the turn cleanly and persists pending.
2026-09-25 23:32:13 +03:00

88 lines
3.3 KiB
TypeScript

import * as fs from "node:fs/promises";
import * as path from "node:path";
import { Type } from "typebox";
import type { AgentTool } from "@earendil-works/pi-agent-core";
import { serverExecute } from "../tool-execute.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 findInput = Type.Object({
pattern: Type.String({
minLength: 1,
description: "Glob pattern to match files, e.g. '*.ts', '**/*.json', or 'src/**/*.spec.ts'",
}),
path: Type.Optional(Type.String({ description: "Directory to search in (default: the learner's home directory)" })),
limit: Type.Optional(Type.Integer({ description: "Maximum number of results (default: 1000)" })),
});
export const findTool: AgentTool<typeof findInput> = {
name: "find",
label: "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).`,
parameters: findInput,
execute: serverExecute("find", findInput, async (input, ctx) => {
if (ctx?.signal?.aborted) return "Operation aborted";
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, aborted } = 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;
},
ctx?.signal,
);
if (aborted) {
return matches.length > 0
? `${matches.join("\n")}\n\n[search aborted — partial results]`
: "Search aborted before any results.";
}
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;
}),
};