(sandbox: Sandbox)
| 7 | import type { AgentTool } from '@mariozechner/pi-agent-core' |
| 8 | |
| 9 | export function createWriteTool(sandbox: Sandbox): AgentTool { |
| 10 | return { |
| 11 | name: `write`, |
| 12 | label: `Write File`, |
| 13 | description: `Create or overwrite a file. Path must be within the working directory. Parent directories are created as needed.`, |
| 14 | parameters: Type.Object({ |
| 15 | path: Type.String({ |
| 16 | description: `File path (relative to working directory)`, |
| 17 | }), |
| 18 | content: Type.String({ |
| 19 | description: `Full file contents to write`, |
| 20 | }), |
| 21 | }), |
| 22 | execute: async (_toolCallId, params) => { |
| 23 | const { path: filePath, content } = params as { |
| 24 | path: string |
| 25 | content: string |
| 26 | } |
| 27 | // Containment is enforced by the sandbox (it owns the filesystem); |
| 28 | // an escaping path rejects with SandboxError('policy'), handled below. |
| 29 | // `key`/`rel` are pure-string normalizations for the diff header — not a security check. |
| 30 | const key = resolve(sandbox.workingDirectory, filePath) |
| 31 | const rel = relative(sandbox.workingDirectory, key) |
| 32 | try { |
| 33 | let original = `` |
| 34 | const existed = await sandbox.exists(filePath) |
| 35 | if (existed) { |
| 36 | const buf = await sandbox.readFile(filePath) |
| 37 | original = buf.toString(`utf-8`) |
| 38 | } |
| 39 | |
| 40 | await sandbox.mkdir(dirname(filePath), { recursive: true }) |
| 41 | await sandbox.writeFile(filePath, content) |
| 42 | |
| 43 | const bytesWritten = Buffer.byteLength(content, `utf-8`) |
| 44 | const patch = createTwoFilesPatch( |
| 45 | existed ? rel : `/dev/null`, |
| 46 | rel, |
| 47 | original, |
| 48 | content, |
| 49 | undefined, |
| 50 | undefined, |
| 51 | { context: 3 } |
| 52 | ) |
| 53 | return { |
| 54 | content: [ |
| 55 | { |
| 56 | type: `text` as const, |
| 57 | text: `Wrote ${bytesWritten} bytes to ${rel}`, |
| 58 | }, |
| 59 | ], |
| 60 | details: { bytesWritten, diff: patch, existed }, |
| 61 | } |
| 62 | } catch (err) { |
| 63 | if (err instanceof SandboxError && err.kind === `policy`) { |
| 64 | return { |
| 65 | content: [ |
| 66 | { |
no test coverage detected