/**
 * Write tool — creates or overwrites a file with the given content.
 *
 * Automatically creates parent directories. Resolves relative paths
 * against the agent's working directory.
 */
import { Type } from '@sinclair/typebox';
import { mkdir as fsMkdir, writeFile as fsWriteFile } from 'fs/promises';
import { dirname } from 'path';
import { resolveToCwd } from '../../shared/files/path-utils.js';
import { WRITE } from '../../tool-names.js';
import { withAbort } from '../../utils/abort.js';
import { enforceFilesystemPolicy } from '../permissions/filesystem-policy.js';
import { requirePermissionPolicy } from '../permissions/require-policy.js';
const writeSchema = Type.Object({
    path: Type.String({ description: 'Path to the file to write (relative or absolute)' }),
    content: Type.String({ description: 'Content to write to the file' })
});
const defaultWriteOperations = {
    writeFile: (path, content) => fsWriteFile(path, content, 'utf-8'),
    mkdir: (dir) => fsMkdir(dir, { recursive: true }).then(() => { })
};
/** Create the write tool definition. Ensures parent dirs exist before writing. */
export function createWriteTool(cwd, options) {
    const ops = options?.operations ?? defaultWriteOperations;
    return {
        name: WRITE,
        label: WRITE,
        isReadOnly: false,
        description: "Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.",
        parameters: writeSchema,
        execute: async (_toolCallId, { path, content }, signal, _onUpdate, ctx) => {
            const absolutePath = resolveToCwd(path, cwd);
            const permissionPolicy = requirePermissionPolicy(ctx, WRITE);
            await enforceFilesystemPolicy({
                path: absolutePath,
                policy: permissionPolicy.filesystem,
                access: 'write',
                sessionState: ctx?.sessionState,
                approvalGrants: ctx?.approvalGrants?.filesystem
            });
            const dir = dirname(absolutePath);
            return withAbort(signal, async (checkAborted) => {
                await ops.mkdir(dir);
                checkAborted();
                await ops.writeFile(absolutePath, content);
                checkAborted();
                return {
                    content: [
                        { type: 'text', text: `Successfully wrote ${content.length} bytes to ${path}` }
                    ],
                    details: undefined
                };
            });
        }
    };
}
//# sourceMappingURL=write.js.map