@shuind/dsh-codex-harness 0.2.21 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/CHANGELOG.md +185 -0
  2. package/README.md +38 -50
  3. package/RELEASE.md +61 -0
  4. package/assets/codex.svg +5 -0
  5. package/cordis.patch.yml +181 -6
  6. package/docs/preset-library.md +33 -23
  7. package/docs/tool-policy-benchmark.json +310 -0
  8. package/docs/tool-policy.md +148 -0
  9. package/lib/client.js +4774 -2416
  10. package/lib/compact-command.js +416 -0
  11. package/lib/compaction.js +141 -12
  12. package/lib/hybrid-executor.js +1196 -0
  13. package/lib/index.js +3658 -2334
  14. package/lib/preferences.js +117 -0
  15. package/lib/tool-policy.js +2422 -0
  16. package/lib/typert.js +86 -79
  17. package/lib/types/client/activity.d.ts +33 -9
  18. package/lib/types/client/activity.js +4 -3
  19. package/lib/types/client/desktop.d.ts +67 -0
  20. package/lib/types/client/desktop.js +229 -0
  21. package/lib/types/client/index.d.ts +207 -110
  22. package/lib/types/client/index.js +99 -492
  23. package/lib/types/client/policy-drafts.d.ts +25 -0
  24. package/lib/types/client/policy-drafts.js +47 -0
  25. package/lib/types/client/policy-locale.d.ts +260 -0
  26. package/lib/types/client/policy-locale.js +357 -0
  27. package/lib/types/client/preset-manager.d.ts +38 -10
  28. package/lib/types/client/preset-manager.js +235 -185
  29. package/lib/types/client/preset-requests.d.ts +12 -0
  30. package/lib/types/client/preset-requests.js +101 -0
  31. package/lib/types/client/tool-policy.d.ts +33 -0
  32. package/lib/types/client/tool-policy.js +336 -0
  33. package/lib/types/contracts/preset-editor-schema.d.ts +78 -0
  34. package/lib/types/contracts/preset-editor-schema.js +95 -0
  35. package/lib/types/{prompt.js → contracts/prompt.js} +13 -7
  36. package/lib/types/{settings.d.ts → contracts/settings.d.ts} +11 -4
  37. package/lib/types/{settings.js → contracts/settings.js} +22 -6
  38. package/lib/types/contracts/tool-policy-contract.d.ts +63 -0
  39. package/lib/types/contracts/tool-policy-contract.js +33 -0
  40. package/lib/types/contracts/ui-contracts.d.ts +92 -0
  41. package/lib/types/contracts/ui-contracts.js +83 -0
  42. package/lib/types/entries/client.d.ts +10 -0
  43. package/lib/types/entries/client.js +10 -0
  44. package/lib/types/{compact-command.d.ts → entries/compact-command.d.ts} +2 -0
  45. package/lib/types/entries/compact-command.js +176 -0
  46. package/lib/types/{compaction.d.ts → entries/compaction.d.ts} +15 -3
  47. package/lib/types/{compaction.js → entries/compaction.js} +47 -11
  48. package/lib/types/entries/hybrid-executor.d.ts +19 -0
  49. package/lib/types/entries/hybrid-executor.js +57 -0
  50. package/lib/types/entries/index.d.ts +66 -0
  51. package/lib/types/entries/index.js +192 -0
  52. package/lib/types/entries/preferences.d.ts +11 -0
  53. package/lib/types/entries/preferences.js +16 -0
  54. package/lib/types/entries/tool-policy.d.ts +97 -0
  55. package/lib/types/entries/tool-policy.js +158 -0
  56. package/lib/types/entries/typert.host.d.ts +23 -0
  57. package/lib/types/entries/typert.host.js +24 -0
  58. package/lib/types/hybrid/codex-hybrid-executor.d.ts +44 -0
  59. package/lib/types/hybrid/codex-hybrid-executor.js +257 -0
  60. package/lib/types/hybrid/hybrid-sdk.d.ts +13 -0
  61. package/lib/types/hybrid/hybrid-sdk.js +196 -0
  62. package/lib/types/hybrid/program-calls.d.ts +28 -0
  63. package/lib/types/hybrid/program-calls.js +193 -0
  64. package/lib/types/hybrid/subcall-scheduler.d.ts +90 -0
  65. package/lib/types/hybrid/subcall-scheduler.js +343 -0
  66. package/lib/types/policy/deferred-tools.d.ts +42 -0
  67. package/lib/types/policy/deferred-tools.js +264 -0
  68. package/lib/types/policy/overlay-installer.d.ts +12 -0
  69. package/lib/types/policy/overlay-installer.js +179 -0
  70. package/lib/types/policy/rule-resolver.d.ts +94 -0
  71. package/lib/types/policy/rule-resolver.js +114 -0
  72. package/lib/types/policy/tool-capabilities.d.ts +33 -0
  73. package/lib/types/policy/tool-capabilities.js +46 -0
  74. package/lib/types/{activity.d.ts → presets/activity.d.ts} +3 -5
  75. package/lib/types/{activity.js → presets/activity.js} +51 -27
  76. package/lib/types/presets/desktop-preset.d.ts +22 -0
  77. package/lib/types/presets/desktop-preset.js +43 -0
  78. package/lib/types/presets/preset-editor.d.ts +47 -0
  79. package/lib/types/presets/preset-editor.js +81 -0
  80. package/lib/types/presets/preset-prompt-catalog.d.ts +23 -0
  81. package/lib/types/presets/preset-prompt-catalog.js +215 -0
  82. package/lib/types/presets/preset-tool-catalog.d.ts +5 -0
  83. package/lib/types/presets/preset-tool-catalog.js +58 -0
  84. package/lib/types/presets/runtime-enhancements.d.ts +45 -0
  85. package/lib/types/presets/runtime-enhancements.js +349 -0
  86. package/lib/types/presets/small-window-compaction.d.ts +15 -0
  87. package/lib/types/presets/small-window-compaction.js +121 -0
  88. package/lib/types/responses/compact-checkpoint.d.ts +27 -0
  89. package/lib/types/responses/compact-checkpoint.js +257 -0
  90. package/lib/types/responses/fetch-transport.d.ts +16 -0
  91. package/lib/types/responses/fetch-transport.js +257 -0
  92. package/lib/types/responses/remote-compact.d.ts +13 -0
  93. package/lib/types/responses/remote-compact.js +319 -0
  94. package/lib/types/responses/sse-diagnostics.d.ts +9 -0
  95. package/lib/types/responses/sse-diagnostics.js +157 -0
  96. package/lib/types/responses/wire-rewrite.d.ts +35 -0
  97. package/lib/types/responses/wire-rewrite.js +237 -0
  98. package/lib/types/tools/exec-output.d.ts +58 -0
  99. package/lib/types/tools/exec-output.js +173 -0
  100. package/lib/types/tools/exec-plan-tools.d.ts +37 -0
  101. package/lib/types/tools/exec-plan-tools.js +265 -0
  102. package/lib/types/tools/exec-runner.d.ts +21 -0
  103. package/lib/types/tools/exec-runner.js +385 -0
  104. package/lib/types/tools/patch-tool.d.ts +16 -0
  105. package/lib/types/tools/patch-tool.js +258 -0
  106. package/lib/types/{patch.d.ts → tools/patch.d.ts} +1 -1
  107. package/lib/types/{patch.js → tools/patch.js} +96 -21
  108. package/locale/en.json +6 -0
  109. package/locale/hybrid-executor/en.json +6 -0
  110. package/locale/hybrid-executor/zh.json +6 -0
  111. package/locale/tool-policy/en.json +6 -0
  112. package/locale/tool-policy/zh.json +6 -0
  113. package/locale/zh.json +6 -0
  114. package/package.json +297 -299
  115. package/presets/{codex-collaboration → codex-hybrid}/agent.cordis.yml +45 -48
  116. package/presets/codex-hybrid/preset.yml +3 -0
  117. package/scripts/benchmark-tool-policy.mjs +186 -0
  118. package/scripts/build-preset.mjs +19 -0
  119. package/scripts/clean-build.mjs +11 -0
  120. package/src/client/activity.ts +83 -0
  121. package/src/client/desktop.tsx +276 -0
  122. package/src/client/index.tsx +391 -0
  123. package/src/client/policy-drafts.ts +56 -0
  124. package/src/client/policy-locale.ts +362 -0
  125. package/src/client/preset-manager.tsx +376 -0
  126. package/src/client/preset-requests.ts +113 -0
  127. package/src/client/tool-policy.tsx +402 -0
  128. package/src/contracts/preset-editor-schema.ts +110 -0
  129. package/src/contracts/prompt.ts +66 -0
  130. package/src/contracts/settings.ts +103 -0
  131. package/src/contracts/tool-policy-contract.ts +93 -0
  132. package/src/contracts/ui-contracts.ts +173 -0
  133. package/src/entries/client.tsx +14 -0
  134. package/src/entries/compact-command.ts +256 -0
  135. package/src/entries/compaction.ts +218 -0
  136. package/src/entries/hybrid-executor.ts +76 -0
  137. package/src/entries/index.ts +298 -0
  138. package/src/entries/preferences.ts +17 -0
  139. package/src/entries/tool-policy.ts +162 -0
  140. package/src/entries/typert.host.ts +29 -0
  141. package/src/hybrid/codex-hybrid-executor.ts +310 -0
  142. package/src/hybrid/hybrid-sdk.ts +217 -0
  143. package/src/hybrid/program-calls.ts +202 -0
  144. package/src/hybrid/subcall-scheduler.ts +446 -0
  145. package/src/policy/deferred-tools.ts +331 -0
  146. package/src/policy/overlay-installer.ts +191 -0
  147. package/src/policy/rule-resolver.ts +128 -0
  148. package/src/policy/tool-capabilities.ts +88 -0
  149. package/src/presets/activity.ts +146 -0
  150. package/src/presets/desktop-preset.ts +60 -0
  151. package/src/presets/preset-editor.ts +101 -0
  152. package/src/presets/preset-prompt-catalog.ts +221 -0
  153. package/src/presets/preset-tool-catalog.ts +58 -0
  154. package/src/presets/runtime-enhancements.ts +415 -0
  155. package/src/presets/small-window-compaction.ts +166 -0
  156. package/src/responses/compact-checkpoint.ts +264 -0
  157. package/src/responses/fetch-transport.ts +290 -0
  158. package/src/responses/remote-compact.ts +393 -0
  159. package/src/responses/sse-diagnostics.ts +156 -0
  160. package/src/responses/wire-rewrite.ts +261 -0
  161. package/src/tools/exec-output.ts +211 -0
  162. package/src/tools/exec-plan-tools.ts +307 -0
  163. package/src/tools/exec-runner.ts +445 -0
  164. package/src/tools/patch-tool.ts +331 -0
  165. package/src/tools/patch.ts +328 -0
  166. package/tsconfig.json +29 -0
  167. package/tsdown.config.ts +110 -0
  168. package/lib/installer.js +0 -237
  169. package/lib/invariant.js +0 -23
  170. package/lib/types/activity-types.d.ts +0 -6
  171. package/lib/types/activity-types.js +0 -3
  172. package/lib/types/client/preset-copy.d.ts +0 -42
  173. package/lib/types/client/preset-copy.js +0 -81
  174. package/lib/types/compact-command.js +0 -79
  175. package/lib/types/context.d.ts +0 -8
  176. package/lib/types/context.js +0 -14
  177. package/lib/types/exec.d.ts +0 -46
  178. package/lib/types/exec.js +0 -365
  179. package/lib/types/index.d.ts +0 -95
  180. package/lib/types/index.js +0 -738
  181. package/lib/types/installer.d.ts +0 -27
  182. package/lib/types/installer.js +0 -146
  183. package/lib/types/invariant.d.ts +0 -16
  184. package/lib/types/invariant.js +0 -22
  185. package/lib/types/preset-contract.d.ts +0 -69
  186. package/lib/types/preset-contract.js +0 -22
  187. package/lib/types/preset-editor-remote.d.ts +0 -30
  188. package/lib/types/preset-editor-remote.js +0 -37
  189. package/lib/types/preset-editor.d.ts +0 -69
  190. package/lib/types/preset-editor.js +0 -557
  191. package/lib/types/preset-templates.d.ts +0 -36
  192. package/lib/types/preset-templates.js +0 -12
  193. package/lib/types/prompt-sections.d.ts +0 -15
  194. package/lib/types/prompt-sections.js +0 -23
  195. package/lib/types/remote.d.ts +0 -40
  196. package/lib/types/remote.js +0 -683
  197. package/lib/types/typert.host.d.ts +0 -47
  198. package/lib/types/typert.host.js +0 -99
  199. package/presets/codex-collaboration/preset.yml +0 -3
  200. /package/lib/types/{prompt.d.ts → contracts/prompt.d.ts} +0 -0
@@ -0,0 +1,331 @@
1
+ /** Shared `apply_patch` tool registration over DSH `ctx.fs` and sandbox policy. */
2
+
3
+ import type { Context } from '@deepseek-ai/cordis'
4
+ import { isAbsolute } from 'node:path'
5
+ import { FsError } from '@deepseek-ai/dsh-fs'
6
+ import type { FsInfo, FsTarget, FsWriteIntent } from '@deepseek-ai/dsh-fs'
7
+ import { sandboxDenialMarker } from '@deepseek-ai/dsh-sandbox'
8
+ import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox'
9
+ import type { Session } from '@deepseek-ai/dsh-session'
10
+ import { defineTool } from '@deepseek-ai/dsh-tools'
11
+ import type { FileDiff, ToolCallView, ToolExecution } from '@deepseek-ai/dsh-tools'
12
+ import { APPLY_PATCH_DESCRIPTION, applyPatchHunks, parsePatch } from './patch.ts'
13
+ import type { PatchFile } from './patch.ts'
14
+ import type { CodexSettings } from '../contracts/settings.ts'
15
+ import { assertCapabilityEnabled, codexToolEnabled, markCodexTool } from '../policy/tool-capabilities.ts'
16
+
17
+ export interface AppliedFile {
18
+ path: string
19
+ operation: 'created' | 'updated' | 'deleted' | 'moved'
20
+ moveTo?: string
21
+ }
22
+
23
+ export interface ApplyPatchResult {
24
+ files: AppliedFile[]
25
+ }
26
+
27
+ function sessionCwd(ctx: Context, exec: ToolExecution): string | undefined {
28
+ if (exec.agent === undefined) return undefined
29
+ const directories = ctx.get('workingDirectory') as { get(session: Session): string } | undefined
30
+ return directories?.get(exec.agent.session) ?? exec.agent.session.header.cwd
31
+ }
32
+
33
+ function resolvePolicy(ctx: Context, exec: ToolExecution): SandboxExecutionPolicy | undefined {
34
+ const policy = ctx.get('sandboxPolicy')
35
+ return policy?.resolve(exec.agent === undefined ? {} : { session: exec.agent.session })
36
+ }
37
+
38
+ async function resolveTarget(ctx: Context, path: string, exec: ToolExecution): Promise<{ target: FsTarget; cwd: string | undefined }> {
39
+ const cwd = sessionCwd(ctx, exec)
40
+ const target = await ctx.fs.resolve(path, cwd === undefined ? { signal: exec.signal } : { cwd, signal: exec.signal })
41
+ return { target, cwd }
42
+ }
43
+
44
+ async function observedTarget(
45
+ ctx: Context,
46
+ target: FsTarget,
47
+ exec: ToolExecution,
48
+ rawPath: string,
49
+ cwd: string | undefined,
50
+ ): Promise<FsInfo> {
51
+ const info = await ctx.fs.stat(target, exec.signal)
52
+ if (info === undefined) {
53
+ const cwdHint = !isAbsolute(rawPath) && cwd !== undefined ? ` (cwd: ${cwd})` : ''
54
+ throw new Error(`apply_patch: file not found: ${target.displayPath}${cwdHint}`)
55
+ }
56
+ if (info.type !== 'file') throw new Error(`apply_patch: not a regular file: ${target.displayPath}`)
57
+ ctx.emit('fs/observed', target, { kind: 'present', version: info.version }, exec)
58
+ return info
59
+ }
60
+
61
+ function withSandboxDenialMarker(error: unknown, policy: SandboxExecutionPolicy | undefined): unknown {
62
+ if (!(error instanceof FsError) || error.code !== 'FS_SANDBOX_DENIED' || policy === undefined) return error
63
+ const marker = sandboxDenialMarker(policy.mode)
64
+ if (error.message.includes(marker)) return error
65
+ return new FsError(`${error.message}\n${marker}`, 'FS_SANDBOX_DENIED', { cause: error })
66
+ }
67
+
68
+ async function writePatchedFile(
69
+ ctx: Context,
70
+ target: FsTarget,
71
+ content: string,
72
+ fallback: FsWriteIntent,
73
+ exec: ToolExecution,
74
+ policy: SandboxExecutionPolicy | undefined,
75
+ ): Promise<FsInfo['version']> {
76
+ const intent = await ctx.waterfall('fs/write-intent', target, exec, () => fallback)
77
+ try {
78
+ const outcome = await ctx.fs.writeText(target, content, intent, exec.signal, policy)
79
+ ctx.emit('fs/observed', target, { kind: 'present', version: outcome.version }, exec)
80
+ return outcome.version
81
+ } catch (error) {
82
+ throw withSandboxDenialMarker(error, policy)
83
+ }
84
+ }
85
+
86
+ async function deletePatchedFile(
87
+ ctx: Context,
88
+ target: FsTarget,
89
+ version: FsInfo['version'],
90
+ exec: ToolExecution,
91
+ policy: SandboxExecutionPolicy | undefined,
92
+ ): Promise<void> {
93
+ const expected = await ctx.waterfall('fs/delete-intent', target, exec, () => ({ version }))
94
+ try {
95
+ await ctx.fs.deleteFile(target, expected, exec.signal, policy)
96
+ ctx.emit('fs/observed', target, { kind: 'absent' }, exec)
97
+ } catch (error) {
98
+ throw withSandboxDenialMarker(error, policy)
99
+ }
100
+ }
101
+
102
+ interface VirtualPatchFile {
103
+ target: FsTarget
104
+ exists: boolean
105
+ content: string
106
+ }
107
+
108
+ type PlannedPatchOp =
109
+ | { kind: 'write'; target: FsTarget; content: string }
110
+ | { kind: 'delete'; target: FsTarget }
111
+
112
+ interface PlannedPatchBatch {
113
+ applied: AppliedFile[]
114
+ ops: PlannedPatchOp[]
115
+ initialVersions: Map<string, FsInfo['version']>
116
+ }
117
+
118
+ async function preflightPatchFiles(
119
+ ctx: Context,
120
+ files: readonly PatchFile[],
121
+ exec: ToolExecution,
122
+ ): Promise<PlannedPatchBatch> {
123
+ const virtual = new Map<string, VirtualPatchFile>()
124
+ const initialVersions = new Map<string, FsInfo['version']>()
125
+ const ops: PlannedPatchOp[] = []
126
+ const applied: AppliedFile[] = []
127
+
128
+ const ensureAbsent = async (target: FsTarget, messagePrefix: string): Promise<void> => {
129
+ const existing = virtual.get(target.targetKey)
130
+ if (existing !== undefined) {
131
+ if (existing.exists) throw new Error(`${messagePrefix}: ${target.displayPath}`)
132
+ return
133
+ }
134
+ const stat = await ctx.fs.stat(target, exec.signal)
135
+ if (stat !== undefined) throw new Error(`${messagePrefix}: ${target.displayPath}`)
136
+ ctx.emit('fs/observed', target, { kind: 'absent' }, exec)
137
+ virtual.set(target.targetKey, { target, exists: false, content: '' })
138
+ }
139
+
140
+ const ensureReadable = async (target: FsTarget, rawPath: string, cwd: string | undefined): Promise<VirtualPatchFile> => {
141
+ const existing = virtual.get(target.targetKey)
142
+ if (existing !== undefined) {
143
+ if (!existing.exists) throw new Error(`apply_patch: file not found: ${target.displayPath}`)
144
+ return existing
145
+ }
146
+ const info = await observedTarget(ctx, target, exec, rawPath, cwd)
147
+ const content = await ctx.fs.readText(target, exec.signal)
148
+ initialVersions.set(target.targetKey, info.version)
149
+ const entry: VirtualPatchFile = { target, exists: true, content }
150
+ virtual.set(target.targetKey, entry)
151
+ return entry
152
+ }
153
+
154
+ for (const file of files) {
155
+ const { target, cwd } = await resolveTarget(ctx, file.path, exec)
156
+ if (file.kind === 'add') {
157
+ await ensureAbsent(target, 'apply_patch: file already exists')
158
+ virtual.set(target.targetKey, { target, exists: true, content: file.content })
159
+ ops.push({ kind: 'write', target, content: file.content })
160
+ applied.push({ path: file.path, operation: 'created' })
161
+ continue
162
+ }
163
+
164
+ const source = await ensureReadable(target, file.path, cwd)
165
+ if (file.kind === 'delete') {
166
+ virtual.set(target.targetKey, { target, exists: false, content: '' })
167
+ ops.push({ kind: 'delete', target })
168
+ applied.push({ path: file.path, operation: 'deleted' })
169
+ continue
170
+ }
171
+
172
+ const updated = applyPatchHunks(source.content, file.hunks, file.path)
173
+ if (file.moveTo === undefined) {
174
+ virtual.set(target.targetKey, { target, exists: true, content: updated })
175
+ ops.push({ kind: 'write', target, content: updated })
176
+ applied.push({ path: file.path, operation: 'updated' })
177
+ continue
178
+ }
179
+
180
+ const { target: destination } = await resolveTarget(ctx, file.moveTo, exec)
181
+ if (destination.targetKey === target.targetKey) {
182
+ virtual.set(target.targetKey, { target, exists: true, content: updated })
183
+ ops.push({ kind: 'write', target, content: updated })
184
+ applied.push({ path: file.path, operation: 'updated', moveTo: file.moveTo })
185
+ continue
186
+ }
187
+
188
+ await ensureAbsent(destination, 'apply_patch: move destination already exists')
189
+ virtual.set(target.targetKey, { target, exists: false, content: '' })
190
+ virtual.set(destination.targetKey, { target: destination, exists: true, content: updated })
191
+ ops.push({ kind: 'write', target: destination, content: updated })
192
+ ops.push({ kind: 'delete', target })
193
+ applied.push({ path: file.path, operation: 'moved', moveTo: file.moveTo })
194
+ }
195
+
196
+ return { applied, ops, initialVersions }
197
+ }
198
+
199
+ async function applyPatchBatch(
200
+ ctx: Context,
201
+ files: readonly PatchFile[],
202
+ exec: ToolExecution,
203
+ policy: SandboxExecutionPolicy | undefined,
204
+ ): Promise<AppliedFile[]> {
205
+ const { applied, ops, initialVersions } = await preflightPatchFiles(ctx, files, exec)
206
+ const versions = new Map(initialVersions)
207
+ for (const op of ops) {
208
+ if (op.kind === 'write') {
209
+ const currentVersion = versions.get(op.target.targetKey)
210
+ const fallback: FsWriteIntent = currentVersion === undefined
211
+ ? { kind: 'createIfAbsent' }
212
+ : { kind: 'replaceIfVersion', version: currentVersion }
213
+ const nextVersion = await writePatchedFile(ctx, op.target, op.content, fallback, exec, policy)
214
+ versions.set(op.target.targetKey, nextVersion)
215
+ continue
216
+ }
217
+ const version = versions.get(op.target.targetKey)
218
+ if (version === undefined) throw new Error(`apply_patch: missing version for delete: ${op.target.displayPath}`)
219
+ await deletePatchedFile(ctx, op.target, version, exec, policy)
220
+ versions.delete(op.target.targetKey)
221
+ }
222
+ return applied
223
+ }
224
+
225
+ export function patchSummary(value: ApplyPatchResult): string {
226
+ const letter = (operation: AppliedFile['operation']): string => {
227
+ switch (operation) {
228
+ case 'created': return 'A'
229
+ case 'updated': return 'M'
230
+ case 'deleted': return 'D'
231
+ case 'moved': return 'M'
232
+ default: return operation satisfies never
233
+ }
234
+ }
235
+ return `Success. Updated the following files:\n${value.files.map(file => `${letter(file.operation)} ${file.operation === 'moved' ? file.moveTo : file.path}`).join('\n')}\n`
236
+ }
237
+
238
+ export function presentPatchCall(input: string): ToolCallView {
239
+ try {
240
+ const files = parsePatch(input)
241
+ const diffs: FileDiff[] = files.flatMap((file): FileDiff[] => {
242
+ if (file.kind === 'add') return [{ path: file.path, oldText: null, newText: file.content }]
243
+ if (file.kind === 'delete') return []
244
+ return [{
245
+ path: file.moveTo ?? file.path,
246
+ oldText: file.hunks.flatMap(hunk => hunk.lines.filter(line => line.kind !== 'add').map(line => line.text)).join('\n') || null,
247
+ newText: file.hunks.flatMap(hunk => hunk.lines.filter(line => line.kind !== 'delete').map(line => line.text)).join('\n'),
248
+ }]
249
+ })
250
+ const paths = new Set(files.flatMap(file => (
251
+ file.kind === 'update' && file.moveTo !== undefined ? [file.path, file.moveTo] : [file.path]
252
+ )))
253
+ return {
254
+ card: 'diff',
255
+ title: `Apply patch (${paths.size} ${paths.size === 1 ? 'file' : 'files'})`,
256
+ diffs,
257
+ locations: [...paths].map(path => ({ path })),
258
+ }
259
+ } catch {
260
+ return {
261
+ card: 'generic',
262
+ title: 'Apply patch',
263
+ kind: 'edit',
264
+ rawInput: input,
265
+ }
266
+ }
267
+ }
268
+
269
+ export function registerPatchTool(
270
+ ctx: Context,
271
+ currentSettings: () => CodexSettings,
272
+ presetEnabled = true,
273
+ authority?: boolean,
274
+ presetOverridesLegacy = false,
275
+ ): () => void {
276
+ const tools = ctx.get('tools')
277
+ if (tools === undefined) throw new Error('Codex patch tools require ctx.tools')
278
+ const fs = ctx.get('fs') ?? (ctx as { fs?: Context['fs'] }).fs
279
+ if (fs === undefined) throw new Error('Codex patch tools require ctx.fs')
280
+ if (fs.sandboxMode !== undefined && ctx.get('sandboxPolicy') === undefined) {
281
+ throw new Error('Codex patch tools: a sandboxing filesystem requires ctx.sandboxPolicy')
282
+ }
283
+ const metadata = {
284
+ capability: 'patchToolEnabled' as const,
285
+ presetEnabled,
286
+ ...(presetOverridesLegacy ? { presetOverridesLegacy: true } : {}),
287
+ }
288
+ return tools.register(markCodexTool(defineTool({
289
+ name: 'apply_patch',
290
+ description: APPLY_PATCH_DESCRIPTION,
291
+ parameters: {
292
+ input: { type: 'string', required: true, description: 'The complete patch text.' },
293
+ },
294
+ output: {
295
+ schema: {
296
+ type: 'object',
297
+ additionalProperties: false,
298
+ properties: {
299
+ files: {
300
+ type: 'array',
301
+ required: true,
302
+ items: {
303
+ type: 'object',
304
+ additionalProperties: false,
305
+ properties: {
306
+ path: { type: 'string', required: true },
307
+ operation: { type: 'string', required: true, enum: ['created', 'updated', 'deleted', 'moved'] },
308
+ moveTo: { type: 'string' },
309
+ },
310
+ },
311
+ },
312
+ },
313
+ },
314
+ render: (_args, value) => [{ type: 'text', text: patchSummary(value) }],
315
+ },
316
+ async execute(args: { input: string }, exec): Promise<ApplyPatchResult> {
317
+ assertCapabilityEnabled(ctx, currentSettings, 'apply_patch', exec.agent, metadata, authority)
318
+ const files = parsePatch(args.input)
319
+ const policy = resolvePolicy(ctx, exec)
320
+ return { files: await applyPatchBatch(ctx, files, exec, policy) }
321
+ },
322
+ presentCall(args): ToolCallView {
323
+ return presentPatchCall(args.input)
324
+ },
325
+ presentResult(args, result) {
326
+ if (result.isError) return undefined
327
+ const view = presentPatchCall(args.input)
328
+ return view.card === 'diff' ? { card: 'diff', title: view.title, diffs: view.diffs } : undefined
329
+ },
330
+ }), metadata), { when: context => codexToolEnabled(ctx, context?.agent, 'apply_patch', metadata, currentSettings, authority) })
331
+ }
@@ -0,0 +1,328 @@
1
+ /** Parser and line-oriented applicator for Codex's `apply_patch` language. */
2
+
3
+ export const APPLY_PATCH_DESCRIPTION = 'Edits files using Codex patch syntax with Begin/End Patch markers and file update directives. In hunk lines, the first character is the operation marker; repeat a source-leading marker when the source line itself starts with one.'
4
+
5
+ /** The grammar sent to providers that support OpenAI custom grammar tools. */
6
+ export const APPLY_PATCH_GRAMMAR = String.raw`start: begin_patch hunk+ end_patch
7
+ begin_patch: "*** Begin Patch" LF
8
+ end_patch: "*** End Patch" LF?
9
+ hunk: add_hunk | delete_hunk | update_hunk
10
+ add_hunk: "*** Add File: " filename LF add_line*
11
+ delete_hunk: "*** Delete File: " filename LF
12
+ update_hunk: "*** Update File: " filename LF change_move? change?
13
+ filename: /(.+)/
14
+ add_line: "+" /(.*)/ LF -> line
15
+ change_move: "*** Move to: " filename LF
16
+ change: (change_context | change_line)+ eof_line?
17
+ change_context: ("@@" | "@@ " /(.+)/) LF
18
+ change_line: ("+" | "-" | " ") /(.*)/ LF
19
+ eof_line: "*** End of File" LF
20
+ %import common.LF
21
+ `
22
+
23
+ export type PatchLine =
24
+ | { kind: 'context'; text: string }
25
+ | { kind: 'delete'; text: string }
26
+ | { kind: 'add'; text: string }
27
+
28
+ export interface PatchHunk {
29
+ context?: string
30
+ lines: PatchLine[]
31
+ endOfFile: boolean
32
+ }
33
+
34
+ export type PatchFile =
35
+ | { kind: 'add'; path: string; content: string }
36
+ | { kind: 'delete'; path: string }
37
+ | { kind: 'update'; path: string; moveTo?: string; hunks: PatchHunk[] }
38
+
39
+ function invalid(message: string): never {
40
+ throw new Error(`apply_patch: ${message}`)
41
+ }
42
+
43
+ function isHunkFileHeader(line: string): boolean {
44
+ const trimmed = line.trimEnd()
45
+ return trimmed.startsWith('*** Add File: ')
46
+ || trimmed.startsWith('*** Delete File: ')
47
+ || trimmed.startsWith('*** Update File: ')
48
+ }
49
+
50
+ function unwrapHeredoc(input: string): string {
51
+ const normalized = input.replaceAll('\r\n', '\n').trim()
52
+ const lines = normalized.split('\n')
53
+ const first = lines[0]?.trim()
54
+ const last = lines.at(-1)?.trim()
55
+ if (lines.length >= 4
56
+ && (first === '<<EOF' || first === "<<'EOF'" || first === '<<"EOF"')
57
+ && last === 'EOF') {
58
+ return lines.slice(1, -1).join('\n').trim()
59
+ }
60
+ return normalized
61
+ }
62
+
63
+ function pathFrom(line: string, prefix: string): string {
64
+ const path = line.slice(prefix.length).trim()
65
+ if (path.length === 0) invalid(`${prefix.trim()} requires a file path`)
66
+ return path
67
+ }
68
+
69
+ function isChangeMarker(line: string): boolean {
70
+ const marker = line.trimEnd()
71
+ return marker === '@@' || marker.startsWith('@@ ')
72
+ }
73
+
74
+ function isPotentialChangeMarker(line: string): boolean {
75
+ return line.trimEnd().startsWith('@@')
76
+ }
77
+
78
+ /** Parse one complete Codex patch after normalizing CRLF input to LF. */
79
+ export function parsePatch(input: string): PatchFile[] {
80
+ const lines = unwrapHeredoc(input).split('\n')
81
+ if (lines[0]?.trim() !== '*** Begin Patch') invalid('input must start with "*** Begin Patch"')
82
+ if (lines.at(-1)?.trim() !== '*** End Patch') invalid('input must end with "*** End Patch"')
83
+
84
+ const files: PatchFile[] = []
85
+ let index = 1
86
+ const end = lines.length - 1
87
+ if (lines[index]?.trim().startsWith('*** Environment ID:') === true) {
88
+ invalid('environment selection is unavailable in this single-environment DSH plugin')
89
+ }
90
+ while (index < end) {
91
+ const header = lines[index++]?.trim()
92
+ if (header === undefined) invalid('unexpected end of input')
93
+ if (header.length === 0) continue
94
+ if (header.startsWith('*** Add File: ')) {
95
+ const path = pathFrom(header, '*** Add File: ')
96
+ const content: string[] = []
97
+ while (index < end && lines[index]?.startsWith('+') === true) {
98
+ content.push(lines[index]!.slice(1))
99
+ index++
100
+ }
101
+ files.push({ kind: 'add', path, content: content.length === 0 ? '' : `${content.join('\n')}\n` })
102
+ continue
103
+ }
104
+ if (header.startsWith('*** Delete File: ')) {
105
+ files.push({ kind: 'delete', path: pathFrom(header, '*** Delete File: ') })
106
+ continue
107
+ }
108
+ if (!header.startsWith('*** Update File: ')) invalid(`unexpected directive ${JSON.stringify(header)}`)
109
+
110
+ const path = pathFrom(header, '*** Update File: ')
111
+ let moveTo: string | undefined
112
+ if (lines[index]?.trim().startsWith('*** Move to: ') === true) {
113
+ moveTo = pathFrom(lines[index]!.trim(), '*** Move to: ')
114
+ index++
115
+ }
116
+ const hunks: PatchHunk[] = []
117
+ while (index < end && !isHunkFileHeader(lines[index]!)) {
118
+ const patchLines: PatchLine[] = []
119
+ let context: string | undefined
120
+ if (isPotentialChangeMarker(lines[index]!)) {
121
+ const marker = lines[index]!.trimEnd()
122
+ if (!isChangeMarker(marker)) {
123
+ invalid(`invalid update hunk marker ${JSON.stringify(lines[index])}`)
124
+ }
125
+ index++
126
+ context = marker.length === 2 ? undefined : marker.slice(3)
127
+ }
128
+ while (index < end && !isHunkFileHeader(lines[index]!)
129
+ && !isPotentialChangeMarker(lines[index]!)
130
+ && lines[index]!.trimEnd() !== '*** End of File') {
131
+ const line = lines[index++]!
132
+ if (line === '') {
133
+ patchLines.push({ kind: 'context', text: '' })
134
+ continue
135
+ }
136
+ const kind = line[0]
137
+ if (kind !== ' ' && kind !== '+' && kind !== '-') {
138
+ invalid(`unexpected update line ${JSON.stringify(line)}`)
139
+ }
140
+ patchLines.push({ kind: kind === ' ' ? 'context' : kind === '+' ? 'add' : 'delete', text: line.slice(1) })
141
+ }
142
+ const endOfFile = lines[index]?.trimEnd() === '*** End of File'
143
+ if (endOfFile) {
144
+ index++
145
+ while (index < end && lines[index] === '') index++
146
+ }
147
+ if (patchLines.length === 0) {
148
+ if (context !== undefined || endOfFile) invalid('an update hunk needs context or changed lines')
149
+ break
150
+ }
151
+ hunks.push({
152
+ ...context === undefined ? {} : { context },
153
+ lines: patchLines,
154
+ endOfFile,
155
+ })
156
+ }
157
+ if (hunks.length === 0 && moveTo === undefined) invalid(`update file ${JSON.stringify(path)} has no changes`)
158
+ files.push({
159
+ kind: 'update',
160
+ path,
161
+ ...moveTo === undefined ? {} : { moveTo },
162
+ hunks,
163
+ })
164
+ }
165
+ if (files.length === 0) invalid('no files were modified')
166
+ return files
167
+ }
168
+
169
+ interface TextLines {
170
+ lines: string[]
171
+ trailingNewline: boolean
172
+ }
173
+
174
+ function splitText(text: string): TextLines {
175
+ if (text.length === 0) return { lines: [], trailingNewline: true }
176
+ const trailingNewline = text.endsWith('\n')
177
+ const lines = text.split('\n')
178
+ if (trailingNewline) lines.pop()
179
+ return { lines, trailingNewline }
180
+ }
181
+
182
+ function joinText(value: TextLines, eol: '\n' | '\r\n'): string {
183
+ if (value.lines.length === 0) return ''
184
+ const body = value.lines.join(eol)
185
+ return value.trailingNewline ? `${body}${eol}` : body
186
+ }
187
+
188
+ function normalizePatchPunctuation(line: string): string {
189
+ return line
190
+ .trim()
191
+ .replaceAll(/[\u2010-\u2015\u2212]/gu, '-')
192
+ .replaceAll(/[\u2018-\u201B]/gu, "'")
193
+ .replaceAll(/[\u201C-\u201F]/gu, '"')
194
+ .replaceAll(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/gu, ' ')
195
+ }
196
+
197
+ function contextAnchor(context: string | undefined): string | undefined {
198
+ if (context === undefined) return undefined
199
+ const trimmed = context.trim()
200
+ if (trimmed.length === 0) return undefined
201
+ const unified = /^-\d+(?:,\d+)?\s+\+\d+(?:,\d+)?(?:\s+@@(?:\s*(.*))?|$)/u.exec(trimmed)
202
+ const anchor = (unified ? (unified[1] ?? '') : trimmed).trim()
203
+ return anchor.length === 0 ? undefined : anchor
204
+ }
205
+
206
+ function findSequence(
207
+ lines: readonly string[],
208
+ expected: readonly string[],
209
+ from: number,
210
+ endOfFile: boolean,
211
+ ): number {
212
+ if (expected.length === 0) return lines.length
213
+ if (expected.length > lines.length) return -1
214
+ const first = endOfFile ? Math.max(from, lines.length - expected.length) : from
215
+ const last = lines.length - expected.length
216
+ const matchers: ((actual: string, wanted: string) => boolean)[] = [
217
+ (actual, wanted) => actual === wanted,
218
+ (actual, wanted) => actual.trimEnd() === wanted.trimEnd(),
219
+ (actual, wanted) => actual.trim() === wanted.trim(),
220
+ (actual, wanted) => normalizePatchPunctuation(actual) === normalizePatchPunctuation(wanted),
221
+ ]
222
+ for (const matchesLine of matchers) {
223
+ for (let index = first; index <= last; index++) {
224
+ let matches = true
225
+ for (let offset = 0; offset < expected.length; offset++) {
226
+ if (!matchesLine(lines[index + offset]!, expected[offset]!)) {
227
+ matches = false
228
+ break
229
+ }
230
+ }
231
+ if (matches) return index
232
+ }
233
+ }
234
+ return -1
235
+ }
236
+
237
+ function displayPatchLine(line: string): string {
238
+ if (line.length === 0) return '<empty>'
239
+ return line.replaceAll(' ', '[space]').replaceAll('\t', '[tab]')
240
+ }
241
+
242
+ function formatPatchExcerpt(lines: readonly string[], start: number, count: number): string {
243
+ if (lines.length === 0) return ' <empty file>'
244
+ const first = Math.max(0, Math.min(start, lines.length - 1))
245
+ return lines.slice(first, first + count)
246
+ .map((line, offset) => ` ${first + offset + 1}: ${displayPatchLine(line)}`)
247
+ .join('\n')
248
+ }
249
+
250
+ function mismatchMessage(
251
+ label: string,
252
+ hunkIndex: number,
253
+ expected: readonly string[],
254
+ actual: readonly string[],
255
+ from: number,
256
+ endOfFile: boolean,
257
+ ): string {
258
+ const expectedPreview = expected.slice(0, 12)
259
+ .map((line, index) => ` ${index + 1}: ${displayPatchLine(line)}`)
260
+ .join('\n')
261
+ const expectedSuffix = expected.length > 12 ? '\n ...' : ''
262
+ const excerptStart = endOfFile ? Math.max(0, actual.length - 6) : Math.max(0, from - 2)
263
+ const earlier = from > 0 && expected.length > 0 ? findSequence(actual, expected, 0, false) : -1
264
+ const orderHint = earlier >= 0 && earlier < from
265
+ ? `\nHint: expected lines match earlier at line ${earlier + 1}, before the previous hunk ended (line ${from + 1}); order hunks top-to-bottom.`
266
+ : ''
267
+ const markerHint = expected.some(wanted => wanted.length > 0 && actual.includes(`-${wanted}`))
268
+ ? '\nHint: if a source line starts with a patch marker, repeat that marker after the operation marker; for example, `-- item` deletes the source line `- item`.'
269
+ : ''
270
+ return `could not find expected lines in ${label} hunk ${hunkIndex + 1} (search starts at line ${from + 1})\nExpected:\n${expectedPreview}${expectedSuffix}\nFile excerpt:\n${formatPatchExcerpt(actual, excerptStart, 10)}${orderHint}${markerHint}`
271
+ }
272
+
273
+ function dominantEol(text: string): '\n' | '\r\n' {
274
+ let crlf = 0
275
+ let lf = 0
276
+ for (let i = 0; i < text.length; i++) {
277
+ if (text[i] === '\n') {
278
+ if (text[i - 1] === '\r') crlf++
279
+ else lf++
280
+ }
281
+ }
282
+ return crlf > lf ? '\r\n' : '\n'
283
+ }
284
+
285
+ /** Apply parsed update hunks while preserving BOM, line endings, and trailing newline. */
286
+ export function applyPatchHunks(original: string, hunks: readonly PatchHunk[], label = 'file'): string {
287
+ const hasBom = original.startsWith('\uFEFF')
288
+ const raw = hasBom ? original.slice(1) : original
289
+ const eol = dominantEol(raw)
290
+ const value = splitText(raw.replaceAll('\r\n', '\n'))
291
+ let cursor = 0
292
+ for (const [hunkIndex, hunk] of hunks.entries()) {
293
+ const expected = hunk.lines.filter(line => line.kind !== 'add').map(line => line.text)
294
+ const anchor = contextAnchor(hunk.context)
295
+ const anchorIndex = anchor === undefined ? -1 : findSequence(value.lines, [anchor], cursor, false)
296
+ let start: number
297
+ if (expected.length === 0) {
298
+ start = anchorIndex >= 0 ? Math.min(anchorIndex + 1, value.lines.length) : value.lines.length
299
+ } else {
300
+ start = anchorIndex >= 0 ? findSequence(value.lines, expected, anchorIndex + 1, hunk.endOfFile) : -1
301
+ if (start < 0 && anchorIndex >= 0) {
302
+ start = findSequence(value.lines, expected, anchorIndex, hunk.endOfFile)
303
+ }
304
+ if (start < 0) {
305
+ start = findSequence(value.lines, expected, cursor, hunk.endOfFile)
306
+ }
307
+ }
308
+ if (start < 0) {
309
+ invalid(mismatchMessage(label, hunkIndex, expected, value.lines, cursor, hunk.endOfFile))
310
+ }
311
+ const replacement: string[] = []
312
+ let oldOffset = 0
313
+ for (const line of hunk.lines) {
314
+ if (line.kind === 'context') {
315
+ replacement.push(value.lines[start + oldOffset]!)
316
+ oldOffset++
317
+ } else if (line.kind === 'delete') {
318
+ oldOffset++
319
+ } else {
320
+ replacement.push(line.text)
321
+ }
322
+ }
323
+ value.lines.splice(start, expected.length, ...replacement)
324
+ cursor = start + replacement.length
325
+ }
326
+ const result = joinText(value, eol)
327
+ return hasBom ? `\uFEFF${result}` : result
328
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2024",
4
+ "module": "esnext",
5
+ "moduleResolution": "bundler",
6
+ "jsx": "react-jsx",
7
+ "declaration": true,
8
+ "sourceMap": true,
9
+ "declarationMap": true,
10
+ "composite": true,
11
+ "incremental": true,
12
+ "skipLibCheck": true,
13
+ "esModuleInterop": true,
14
+ "allowImportingTsExtensions": true,
15
+ "rewriteRelativeImportExtensions": true,
16
+ "verbatimModuleSyntax": false,
17
+ "strict": true,
18
+ "noUncheckedIndexedAccess": true,
19
+ "exactOptionalPropertyTypes": true,
20
+ "noImplicitOverride": true,
21
+ "noFallthroughCasesInSwitch": true,
22
+ "noUnusedLocals": true,
23
+ "noUnusedParameters": true,
24
+ "types": ["node"],
25
+ "rootDir": "src",
26
+ "outDir": "lib/types"
27
+ },
28
+ "include": ["src"]
29
+ }