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