Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

tools.mjs

92 lines2.9 KB

1// Shell + file-editor tools for the eval agent (E2), implemented over Node
2// child_process / fs. Functionally equivalent to the vended tools other
3// harnesses use; same descriptions where feasible. Large outputs (shell stdout,
4// file content) are the fields the `adorned` arm truncates.
5​
6import { execFile } from 'node:child_process'
7import { readFile, writeFile } from 'node:fs/promises'
8import nodePath from 'node:path'
9import { toolDefinition } from '@tanstack/ai'
10​
11function run(cmd, args, cwd) {
12 return new Promise((resolve) => {
13 execFile(
14 cmd,
15 args,
16 { cwd, maxBuffer: 64 * 1024 * 1024, timeout: 120_000 },
17 (err, stdout, stderr) => {
18 resolve({
19 stdout: String(stdout ?? ''),
20 stderr: String(stderr ?? ''),
21 exitCode: err?.code ?? 0,
22 })
23 },
24 )
25 })
27​
28/** Build the agent's tools, rooted at `cwd`. Pass `{ includeShell: false }` to
29 * force file content through read_file / write_file (no grep/sed shortcut). */
30export function makeTools(cwd, { includeShell = true } = {}) {
31 const runShell = toolDefinition({
32 name: 'run_shell',
33 description:
34 'Run a shell command and return its stdout, stderr, and exit code.',
35 inputSchema: {
36 type: 'object',
37 properties: {
38 command: { type: 'string', description: 'The command line to run.' },
39 },
40 required: ['command'],
41 additionalProperties: false,
42 },
43 outputSchema: {
44 type: 'object',
45 properties: {
46 stdout: { type: 'string' },
47 stderr: { type: 'string' },
48 exitCode: { type: 'number' },
49 },
50 },
51 }).server(async ({ command }) => run('bash', ['-lc', command], cwd))
52​
53 const readFileTool = toolDefinition({
54 name: 'read_file',
55 description: 'Read a UTF-8 file and return its full content.',
56 inputSchema: {
57 type: 'object',
58 properties: { path: { type: 'string' } },
59 required: ['path'],
60 additionalProperties: false,
61 },
62 outputSchema: {
63 type: 'object',
64 properties: { path: { type: 'string' }, content: { type: 'string' } },
65 },
66 }).server(async ({ path }) => ({
67 path,
68 content: await readFile(nodePath.resolve(cwd, path), 'utf8'),
69 }))
70​
71 const writeFileTool = toolDefinition({
72 name: 'write_file',
73 description: 'Write UTF-8 content to a file, creating or overwriting it.',
74 inputSchema: {
75 type: 'object',
76 properties: { path: { type: 'string' }, content: { type: 'string' } },
77 required: ['path', 'content'],
78 additionalProperties: false,
79 },
80 outputSchema: {
81 type: 'object',
82 properties: { path: { type: 'string' }, bytes: { type: 'number' } },
83 },
84 }).server(async ({ path, content }) => {
85 await writeFile(nodePath.resolve(cwd, path), content, 'utf8')
86 return { path, bytes: Buffer.byteLength(content) }
87 })
88​
89 return includeShell
90 ? [runShell, readFileTool, writeFileTool]
91 : [readFileTool, writeFileTool]