Z ZPI 文档 v0.3.8
介绍页

源码

packages/coding-agent/src/core/tools/pi/write.ts

typescript90 行查看原文
// Adapted from Pi c20cb09772bf4e2590a316cb54514cef76df4293.
// Copyright (c) 2025 Mario Zechner. MIT license: licenses/third-party-notices.txt.

import { mkdir as fsMkdir, writeFile as fsWriteFile } from "node:fs/promises";
import { dirname } from "node:path";
import { Type } from "typebox";
import type { ToolContext, ToolDefinition } from "../../types.ts";
import { withFileMutationQueue } from "./file-mutation-queue.ts";
import type { FileReadState } from "./file-read-state.ts";
import { resolveToCwd } from "./path-utils.ts";

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" }),
});

export const writeToolSystemPromptContribution = {
  snippet: "Create or overwrite files",
  guidelines: ["Use write only for new files or complete rewrites."],
} as const;

/**
 * Pluggable operations for the write tool.
 * Override these to delegate file writing to remote systems (for example SSH).
 */
export interface WriteOperations {
  /** Write content to a file */
  writeFile: (absolutePath: string, content: string) => Promise<void>;
  /** Create directory recursively */
  mkdir: (dir: string) => Promise<void>;
}

const defaultWriteOperations: WriteOperations = {
  writeFile: (path, content) => fsWriteFile(path, content, "utf-8"),
  mkdir: (dir) => fsMkdir(dir, { recursive: true }).then(() => {}),
};

export interface WriteToolOptions {
  /** Shared knowledge of file contents in the current model context. */
  fileReadState?: FileReadState;
  /** Custom operations for file writing. Default: local filesystem */
  operations?: WriteOperations;
}

export function createWriteToolDefinition(cwd: string, options?: WriteToolOptions) {
  const ops = options?.operations ?? defaultWriteOperations;
  return {
    name: "write",
    label: "write",
    description:
      "Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.",
    promptSnippet: writeToolSystemPromptContribution.snippet,
    promptGuidelines: [...writeToolSystemPromptContribution.guidelines],
    parameters: writeSchema,
    async execute(
      _toolCallId,
      { path, content }: { path: string; content: string },
      signal?: AbortSignal,
      _onUpdate?,
      ctx?: Partial<ToolContext>,
    ) {
      const absolutePath = resolveToCwd(path, ctx?.cwd || cwd);
      const dir = dirname(absolutePath);
      return withFileMutationQueue(absolutePath, async () => {
        // Do not reject from an abort event listener here: that would release the
        // mutation queue while an in-flight filesystem operation may still finish.
        // Check cancellation before writing, and keep the queue locked until the
        // write settles. A successful write must still be reported as successful.
        const throwIfAborted = (): void => {
          if (signal?.aborted) throw new Error("Operation aborted");
        };

        throwIfAborted();
        // Create parent directories if needed.
        await ops.mkdir(dir);
        throwIfAborted();

        // Write the file contents.
        await ops.writeFile(absolutePath, content);
        options?.fileReadState?.recordWrite(absolutePath, content);

        return {
          content: [{ type: "text", text: `Successfully wrote to ${path}` }],
          details: undefined,
        };
      });
    },
  } satisfies ToolDefinition<typeof writeSchema, undefined>;
}