1import { existsSync, readdirSync, statSync } from "node:fs";
2import { join } from "node:path";
3import { Type } from "@sinclair/typebox";
4import type { AgentTool } from "@mariozechner/pi-ai";
5import { resolveToCwd } from "./path-utils.js";
6import { DEFAULT_MAX_BYTES, formatSize, truncateHead } from "../../util/truncate.js";
7
8const DEFAULT_LIMIT = 500;
9
10const LsSchema = Type.Object({
11 path: Type.Optional(Type.String({ description: "Directory to list (default: current directory)" })),
12 limit: Type.Optional(Type.Number({ description: "Maximum number of entries to return (default: 500)" })),
13});
14
15export const createLsTool = (workspacePath: string): AgentTool => ({
16 name: "ls",
17 label: "List Directory",
18 description: `List directory contents. Returns up to ${DEFAULT_LIMIT} entries and ${DEFAULT_MAX_BYTES / 1024} KB of output.`,
19 parameters: LsSchema as any,
20 execute: async (_toolCallId: string, params: any) => {
21 const resolved = resolveToCwd(params.path || ".", workspacePath);
22
23 if (!existsSync(resolved)) {
24 throw new Error(`Path does not exist: ${params.path || "."}`);
25 }
26
27 const stats = statSync(resolved);
28 if (!stats.isDirectory()) {
29 throw new Error(`Not a directory: ${params.path || "."}`);
30 }
31
32 const entries = readdirSync(resolved);
33 entries.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }));
34
35 const effectiveLimit = params.limit ?? DEFAULT_LIMIT;
36 const limited = entries.slice(0, effectiveLimit);
37 const entryLimitReached = entries.length > effectiveLimit;
38
39 const lines = limited.map((entry) => {
40 const entryPath = join(resolved, entry);
41 try {
42 const entryStat = statSync(entryPath);
43 return entryStat.isDirectory() ? `${entry}/` : entry;
44 } catch {
45 return entry;
46 }
47 });
48
49 if (lines.length === 0) {
50 return {
51 content: [{ type: "text", text: "(empty directory)" }],
52 details: {},
53 };
54 }
55
56 const rawOutput = lines.join("\n");
57 const truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER });
58
59 const notices: string[] = [];
60 if (entryLimitReached) {
61 notices.push(`Entry limit reached: showing ${effectiveLimit} of ${entries.length} entries.`);
62 }
63 if (truncation.truncated) {
64 notices.push(
65 `Output truncated: showing ${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)}.`,
66 );
67 }
68
69 let output = truncation.content;
70 if (notices.length > 0) {
71 output += `\n\n[${notices.join(" ")}]`;
72 }
73
74 return {
75 content: [{ type: "text", text: output }],
76 details: {
77 ...(truncation.truncated ? { truncation } : {}),
78 ...(entryLimitReached ? { entryLimitReached: true } : {}),
79 },
80 };
81 },
82});