{"version":3,"file":"applyPatch.cjs","names":["z"],"sources":["../../src/tools/applyPatch.ts"],"sourcesContent":["import { z } from \"zod/v4\";\nimport { OpenAI as OpenAIClient } from \"openai\";\nimport { tool, type DynamicStructuredTool } from \"@langchain/core/tools\";\n\n/**\n * Re-export operation types from OpenAI SDK for convenience.\n */\nexport type ApplyPatchCreateFileOperation =\n  OpenAIClient.Responses.ResponseApplyPatchToolCall.CreateFile;\nexport type ApplyPatchUpdateFileOperation =\n  OpenAIClient.Responses.ResponseApplyPatchToolCall.UpdateFile;\nexport type ApplyPatchDeleteFileOperation =\n  OpenAIClient.Responses.ResponseApplyPatchToolCall.DeleteFile;\n\n/**\n * Union type of all apply patch operations from OpenAI SDK.\n */\nexport type ApplyPatchOperation = NonNullable<\n  OpenAIClient.Responses.ResponseApplyPatchToolCall[\"operation\"]\n>;\n\n// Zod schemas for apply patch operations\nexport const ApplyPatchCreateFileOperationSchema = z.object({\n  type: z.literal(\"create_file\"),\n  path: z.string(),\n  diff: z.string(),\n});\n\nexport const ApplyPatchUpdateFileOperationSchema = z.object({\n  type: z.literal(\"update_file\"),\n  path: z.string(),\n  diff: z.string(),\n});\n\nexport const ApplyPatchDeleteFileOperationSchema = z.object({\n  type: z.literal(\"delete_file\"),\n  path: z.string(),\n});\n\n// Union schema for all apply patch operations\nexport const ApplyPatchOperationSchema = z.union([\n  ApplyPatchCreateFileOperationSchema,\n  ApplyPatchUpdateFileOperationSchema,\n  ApplyPatchDeleteFileOperationSchema,\n]);\n\n/**\n * Options for the Apply Patch tool.\n */\nexport interface ApplyPatchOptions {\n  /**\n   * Execute function that handles patch operations.\n   * This function receives the operation input and should return a string\n   * describing the result (success or failure message).\n   *\n   * The operation types are:\n   * - `create_file`: Create a new file at the specified path with the diff content\n   * - `update_file`: Modify an existing file using V4A diff format\n   * - `delete_file`: Remove a file at the specified path\n   *\n   * @example\n   * ```typescript\n   * execute: async (operation) => {\n   *   if (operation.type === \"create_file\") {\n   *     const content = applyDiff(\"\", operation.diff, \"create\");\n   *     await fs.writeFile(operation.path, content);\n   *     return `Created ${operation.path}`;\n   *   }\n   *   if (operation.type === \"update_file\") {\n   *     const current = await fs.readFile(operation.path, \"utf-8\");\n   *     const newContent = applyDiff(current, operation.diff);\n   *     await fs.writeFile(operation.path, newContent);\n   *     return `Updated ${operation.path}`;\n   *   }\n   *   if (operation.type === \"delete_file\") {\n   *     await fs.unlink(operation.path);\n   *     return `Deleted ${operation.path}`;\n   *   }\n   *   return \"Unknown operation type\";\n   * }\n   * ```\n   */\n  execute: (operation: ApplyPatchOperation) => string | Promise<string>;\n}\n\n/**\n * OpenAI Apply Patch tool type for the Responses API.\n */\nexport type ApplyPatchTool = OpenAIClient.Responses.ApplyPatchTool;\n\nconst TOOL_NAME = \"apply_patch\";\n\n/**\n * Creates an Apply Patch tool that allows models to propose structured diffs\n * that your integration applies. This enables iterative, multi-step code\n * editing workflows.\n *\n * **Apply Patch** lets GPT-5.1 create, update, and delete files in your codebase\n * using structured diffs. Instead of just suggesting edits, the model emits\n * patch operations that your application applies and then reports back on.\n *\n * **When to use**:\n * - **Multi-file refactors** – Rename symbols, extract helpers, or reorganize modules\n * - **Bug fixes** – Have the model both diagnose issues and emit precise patches\n * - **Tests & docs generation** – Create new test files, fixtures, and documentation\n * - **Migrations & mechanical edits** – Apply repetitive, structured updates\n *\n * **How it works**:\n * The tool operates in a continuous loop:\n * 1. Model sends patch operations (`apply_patch_call` with operation type)\n * 2. Your code applies the patch to your working directory or repo\n * 3. You return success/failure status and optional output\n * 4. Repeat until the task is complete\n *\n * **Security Warning**: Applying patches can modify files in your codebase.\n * Always validate paths, implement backups, and consider sandboxing.\n *\n * @see {@link https://platform.openai.com/docs/guides/tools-apply-patch | OpenAI Apply Patch Documentation}\n *\n * @param options - Configuration options for the Apply Patch tool\n * @returns An Apply Patch tool that can be passed to `bindTools`\n *\n * @example\n * ```typescript\n * import { ChatOpenAI, tools } from \"@langchain/openai\";\n * import { applyDiff } from \"@openai/agents\";\n * import * as fs from \"fs/promises\";\n *\n * const model = new ChatOpenAI({ model: \"gpt-5.1\" });\n *\n * // With execute callback for automatic patch handling\n * const patchTool = tools.applyPatch({\n *   execute: async (operation) => {\n *     if (operation.type === \"create_file\") {\n *       const content = applyDiff(\"\", operation.diff, \"create\");\n *       await fs.writeFile(operation.path, content);\n *       return `Created ${operation.path}`;\n *     }\n *     if (operation.type === \"update_file\") {\n *       const current = await fs.readFile(operation.path, \"utf-8\");\n *       const newContent = applyDiff(current, operation.diff);\n *       await fs.writeFile(operation.path, newContent);\n *       return `Updated ${operation.path}`;\n *     }\n *     if (operation.type === \"delete_file\") {\n *       await fs.unlink(operation.path);\n *       return `Deleted ${operation.path}`;\n *     }\n *     return \"Unknown operation type\";\n *   },\n * });\n *\n * const llmWithPatch = model.bindTools([patchTool]);\n * const response = await llmWithPatch.invoke(\n *   \"Rename the fib() function to fibonacci() in lib/fib.py\"\n * );\n * ```\n *\n * @remarks\n * - Only available through the Responses API (not Chat Completions)\n * - Designed for use with `gpt-5.1` model\n * - Operations include: `create_file`, `update_file`, `delete_file`\n * - Patches use V4A diff format for updates\n * - Always validate paths to prevent directory traversal attacks\n * - Consider backing up files before applying patches\n * - Implement \"all-or-nothing\" semantics if atomicity is required\n */\nexport function applyPatch(options: ApplyPatchOptions) {\n  const patchTool = tool(options.execute, {\n    name: TOOL_NAME,\n    description:\n      \"Apply structured diffs to create, update, or delete files in the codebase.\",\n    schema: ApplyPatchOperationSchema,\n  });\n\n  patchTool.extras = {\n    ...(patchTool.extras ?? {}),\n    providerToolDefinition: {\n      type: \"apply_patch\",\n    } satisfies ApplyPatchTool,\n  };\n\n  return patchTool as DynamicStructuredTool<\n    typeof ApplyPatchOperationSchema,\n    ApplyPatchOperation,\n    unknown,\n    string\n  >;\n}\n"],"mappings":";;;AAsBA,MAAa,sCAAsCA,OAAAA,EAAE,OAAO;CAC1D,MAAMA,OAAAA,EAAE,QAAQ,cAAc;CAC9B,MAAMA,OAAAA,EAAE,QAAQ;CAChB,MAAMA,OAAAA,EAAE,QAAQ;CACjB,CAAC;AAEF,MAAa,sCAAsCA,OAAAA,EAAE,OAAO;CAC1D,MAAMA,OAAAA,EAAE,QAAQ,cAAc;CAC9B,MAAMA,OAAAA,EAAE,QAAQ;CAChB,MAAMA,OAAAA,EAAE,QAAQ;CACjB,CAAC;AAEF,MAAa,sCAAsCA,OAAAA,EAAE,OAAO;CAC1D,MAAMA,OAAAA,EAAE,QAAQ,cAAc;CAC9B,MAAMA,OAAAA,EAAE,QAAQ;CACjB,CAAC;AAGF,MAAa,4BAA4BA,OAAAA,EAAE,MAAM;CAC/C;CACA;CACA;CACD,CAAC;AA8CF,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6ElB,SAAgB,WAAW,SAA4B;CACrD,MAAM,aAAA,GAAA,sBAAA,MAAiB,QAAQ,SAAS;EACtC,MAAM;EACN,aACE;EACF,QAAQ;EACT,CAAC;AAEF,WAAU,SAAS;EACjB,GAAI,UAAU,UAAU,EAAE;EAC1B,wBAAwB,EACtB,MAAM,eACP;EACF;AAED,QAAO"}