@shuind/dsh-codex-harness 0.1.7
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/LICENSE +21 -0
- package/README.md +100 -0
- package/README.zh.md +100 -0
- package/cordis.patch.yml +5 -0
- package/lib/index.js +843 -0
- package/lib/installer.js +59 -0
- package/lib/invariant.js +23 -0
- package/lib/types/exec.d.ts +43 -0
- package/lib/types/exec.js +251 -0
- package/lib/types/index.d.ts +28 -0
- package/lib/types/index.js +321 -0
- package/lib/types/installer.d.ts +23 -0
- package/lib/types/installer.js +64 -0
- package/lib/types/invariant.d.ts +16 -0
- package/lib/types/invariant.js +22 -0
- package/lib/types/patch.d.ts +36 -0
- package/lib/types/patch.js +186 -0
- package/package.json +114 -0
- package/presets/codex/agent.cordis.yml +44 -0
- package/presets/codex/preset.yml +3 -0
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
/** Codex-compatible prompt overlay and core tools for a dsh agent preset. */
|
|
2
|
+
import z from '@deepseek-ai/schemastery';
|
|
3
|
+
import { defineTool } from '@deepseek-ai/dsh-tools';
|
|
4
|
+
import { applyPatchHunks, parsePatch } from "./patch.js";
|
|
5
|
+
import { renderExecResult, runExecCommand, runWriteStdin } from "./exec.js";
|
|
6
|
+
export const name = 'codex';
|
|
7
|
+
export const inject = ['tools', 'systemPrompt', 'shell', 'fs'];
|
|
8
|
+
/** Runtime configuration schema for the Codex tool bridge. */
|
|
9
|
+
export const Config = z.object({
|
|
10
|
+
defaultYieldTimeMs: z.number().step(1).min(0).default(10_000),
|
|
11
|
+
pollYieldTimeMs: z.number().step(1).min(0).default(5_000),
|
|
12
|
+
writeYieldTimeMs: z.number().step(1).min(0).default(250),
|
|
13
|
+
maxOutputBytes: z.number().step(1).min(1).default(64_000),
|
|
14
|
+
});
|
|
15
|
+
const CODEX_BASE_PROMPT = String.raw `You are Codex, based on {{model}}. You are running as a coding agent in dsh Web on a user's computer.
|
|
16
|
+
|
|
17
|
+
## General
|
|
18
|
+
|
|
19
|
+
- When searching for text or files, prefer using rg or rg --files respectively because rg is much faster than alternatives like grep. If rg is not available, use the next best alternative.
|
|
20
|
+
|
|
21
|
+
## Editing constraints
|
|
22
|
+
|
|
23
|
+
- Default to ASCII when editing or creating files. Only introduce non-ASCII or other Unicode characters when there is a clear justification and the file already uses them.
|
|
24
|
+
- Add succinct code comments that explain non-obvious code. Do not add comments that merely narrate assignments or control flow.
|
|
25
|
+
- Use apply_patch for single-file edits when practical. The apply_patch tool accepts its freeform patch language; do not wrap that patch in JSON.
|
|
26
|
+
- You may be in a dirty git worktree. Never revert existing changes you did not make unless the user explicitly requests it. If unrelated files are changed, leave them alone.
|
|
27
|
+
|
|
28
|
+
## Planning
|
|
29
|
+
|
|
30
|
+
- Use update_plan for work with multiple meaningful steps. Keep the plan current as the task progresses.
|
|
31
|
+
- Do not use a plan for a trivial one-step request.
|
|
32
|
+
|
|
33
|
+
## dsh session
|
|
34
|
+
|
|
35
|
+
- The user and you share one workspace. Inspect the repository and every applicable AGENTS.md before editing.
|
|
36
|
+
- This session's preset was selected when the session was created and stays fixed for its lifetime. Do not attempt to switch the preset or replace its tool catalog while the session is running.
|
|
37
|
+
- dsh provides the execution, filesystem, session, policy, and Skills capabilities behind these tools. Use those extension points as supplied; do not invent a second harness or bypass the filesystem service for file edits.
|
|
38
|
+
- The core Codex tool names, arguments, and result formats are fixed: use exec_command for terminal work, write_stdin for an existing interactive command, apply_patch for file changes, and update_plan for multi-step tasks.
|
|
39
|
+
|
|
40
|
+
## Task execution
|
|
41
|
+
|
|
42
|
+
- Keep the user informed with concise progress updates and lead with the result.
|
|
43
|
+
- Prefer existing functions and extension points over new machinery.
|
|
44
|
+
- Do not claim that a command, edit, or test succeeded unless it actually succeeded.
|
|
45
|
+
- Use the exact tool names and argument formats supplied by this session; do not invent replacement editing tools.
|
|
46
|
+
|
|
47
|
+
## Presenting your work
|
|
48
|
+
|
|
49
|
+
- Be concise, direct, friendly, and actionable.
|
|
50
|
+
- For substantial work, explain what changed and why, then mention relevant verification and next steps.
|
|
51
|
+
- Do not dump large files into the conversation; refer to their paths.
|
|
52
|
+
- Use plain text with short sections only when they improve scanability.
|
|
53
|
+
`;
|
|
54
|
+
const EXEC_COMMAND_DESCRIPTION = 'Runs a command in a PTY, returning output or a session ID for ongoing interaction.';
|
|
55
|
+
const WRITE_STDIN_DESCRIPTION = 'Writes characters to an existing unified exec session and returns recent output.';
|
|
56
|
+
const APPLY_PATCH_DESCRIPTION = 'The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the patch in JSON.';
|
|
57
|
+
const UPDATE_PLAN_DESCRIPTION = 'Updates the task plan.\nProvide an optional explanation and a list of plan items, each with a step and status.\nAt most one step can be in_progress at a time.';
|
|
58
|
+
const PLAN_STATUSES = ['pending', 'in_progress', 'completed'];
|
|
59
|
+
function sessionCwd(exec) {
|
|
60
|
+
return exec.agent?.session.header.cwd;
|
|
61
|
+
}
|
|
62
|
+
function resolvePolicy(ctx, exec) {
|
|
63
|
+
const policy = ctx.get('sandboxPolicy');
|
|
64
|
+
return policy?.resolve(exec.agent === undefined ? {} : { session: exec.agent.session });
|
|
65
|
+
}
|
|
66
|
+
async function resolveTarget(ctx, path, exec) {
|
|
67
|
+
const cwd = sessionCwd(exec);
|
|
68
|
+
return ctx.fs.resolve(path, cwd === undefined ? { signal: exec.signal } : { cwd, signal: exec.signal });
|
|
69
|
+
}
|
|
70
|
+
async function observedTarget(ctx, target, exec) {
|
|
71
|
+
const info = await ctx.fs.stat(target, exec.signal);
|
|
72
|
+
if (info === undefined)
|
|
73
|
+
throw new Error(`apply_patch: file not found: ${target.displayPath}`);
|
|
74
|
+
if (info.type !== 'file')
|
|
75
|
+
throw new Error(`apply_patch: not a regular file: ${target.displayPath}`);
|
|
76
|
+
ctx.emit('fs/observed', target, { kind: 'present', version: info.version }, exec);
|
|
77
|
+
return info;
|
|
78
|
+
}
|
|
79
|
+
async function writePatchedFile(ctx, target, content, fallback, exec, policy) {
|
|
80
|
+
const intent = await ctx.waterfall('fs/write-intent', target, exec, () => fallback);
|
|
81
|
+
const outcome = await ctx.fs.writeText(target, content, intent, exec.signal, policy);
|
|
82
|
+
ctx.emit('fs/observed', target, { kind: 'present', version: outcome.version }, exec);
|
|
83
|
+
return outcome.operation === 'create' ? 'created' : 'updated';
|
|
84
|
+
}
|
|
85
|
+
async function deletePatchedFile(ctx, target, version, exec, policy) {
|
|
86
|
+
const remove = ctx.fs.remove;
|
|
87
|
+
if (typeof remove !== 'function') {
|
|
88
|
+
throw new Error('apply_patch: the configured dsh filesystem does not support file deletion');
|
|
89
|
+
}
|
|
90
|
+
await remove.call(ctx.fs, target, { version }, exec.signal, policy);
|
|
91
|
+
ctx.emit('fs/observed', target, { kind: 'absent' }, exec);
|
|
92
|
+
}
|
|
93
|
+
async function applyOnePatch(ctx, file, exec, policy) {
|
|
94
|
+
const target = await resolveTarget(ctx, file.path, exec);
|
|
95
|
+
if (file.kind === 'add') {
|
|
96
|
+
const existing = await ctx.fs.stat(target, exec.signal);
|
|
97
|
+
if (existing !== undefined)
|
|
98
|
+
throw new Error(`apply_patch: file already exists: ${target.displayPath}`);
|
|
99
|
+
ctx.emit('fs/observed', target, { kind: 'absent' }, exec);
|
|
100
|
+
await writePatchedFile(ctx, target, file.content, { kind: 'createIfAbsent' }, exec, policy);
|
|
101
|
+
return { path: file.path, operation: 'created' };
|
|
102
|
+
}
|
|
103
|
+
const sourceInfo = await observedTarget(ctx, target, exec);
|
|
104
|
+
const original = await ctx.fs.readText(target, exec.signal);
|
|
105
|
+
const updated = file.kind === 'delete' ? undefined : applyPatchHunks(original, file.hunks);
|
|
106
|
+
if (file.kind === 'delete') {
|
|
107
|
+
await deletePatchedFile(ctx, target, sourceInfo.version, exec, policy);
|
|
108
|
+
return { path: file.path, operation: 'deleted' };
|
|
109
|
+
}
|
|
110
|
+
if (file.moveTo === undefined) {
|
|
111
|
+
await writePatchedFile(ctx, target, updated, { kind: 'replaceIfVersion', version: sourceInfo.version }, exec, policy);
|
|
112
|
+
return { path: file.path, operation: 'updated' };
|
|
113
|
+
}
|
|
114
|
+
const destination = await resolveTarget(ctx, file.moveTo, exec);
|
|
115
|
+
if (destination.targetKey === target.targetKey) {
|
|
116
|
+
await writePatchedFile(ctx, target, updated, { kind: 'replaceIfVersion', version: sourceInfo.version }, exec, policy);
|
|
117
|
+
return { path: file.path, operation: 'updated', moveTo: file.moveTo };
|
|
118
|
+
}
|
|
119
|
+
const destinationInfo = await ctx.fs.stat(destination, exec.signal);
|
|
120
|
+
if (destinationInfo !== undefined)
|
|
121
|
+
throw new Error(`apply_patch: move destination already exists: ${destination.displayPath}`);
|
|
122
|
+
ctx.emit('fs/observed', destination, { kind: 'absent' }, exec);
|
|
123
|
+
await writePatchedFile(ctx, destination, updated, { kind: 'createIfAbsent' }, exec, policy);
|
|
124
|
+
await deletePatchedFile(ctx, target, sourceInfo.version, exec, policy);
|
|
125
|
+
return { path: file.path, operation: 'moved', moveTo: file.moveTo };
|
|
126
|
+
}
|
|
127
|
+
function patchSummary(value) {
|
|
128
|
+
const letter = (operation) => {
|
|
129
|
+
switch (operation) {
|
|
130
|
+
case 'created': return 'A';
|
|
131
|
+
case 'updated': return 'M';
|
|
132
|
+
case 'deleted': return 'D';
|
|
133
|
+
case 'moved': return 'M';
|
|
134
|
+
default: return operation;
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
return `Success. Updated the following files:\n${value.files.map(file => `${letter(file.operation)} ${file.operation === 'moved' ? file.moveTo : file.path}`).join('\n')}\n`;
|
|
138
|
+
}
|
|
139
|
+
function planTodos(args) {
|
|
140
|
+
const seen = new Set();
|
|
141
|
+
let active = 0;
|
|
142
|
+
const todos = [];
|
|
143
|
+
for (const item of args.plan) {
|
|
144
|
+
const content = item.step.trim();
|
|
145
|
+
if (content.length === 0)
|
|
146
|
+
throw new Error('update_plan: every step must be non-empty');
|
|
147
|
+
if (seen.has(content))
|
|
148
|
+
throw new Error(`update_plan: duplicate step ${JSON.stringify(content)}`);
|
|
149
|
+
seen.add(content);
|
|
150
|
+
if (item.status === 'in_progress')
|
|
151
|
+
active++;
|
|
152
|
+
todos.push({ content, status: item.status });
|
|
153
|
+
}
|
|
154
|
+
if (active > 1)
|
|
155
|
+
throw new Error('update_plan: at most one step may be in_progress');
|
|
156
|
+
return todos;
|
|
157
|
+
}
|
|
158
|
+
function registerExecTools(ctx, config) {
|
|
159
|
+
ctx.tools.register(defineTool({
|
|
160
|
+
name: 'exec_command',
|
|
161
|
+
description: EXEC_COMMAND_DESCRIPTION,
|
|
162
|
+
parameters: {
|
|
163
|
+
cmd: { type: 'string', required: true, description: 'Shell command to execute.' },
|
|
164
|
+
workdir: { type: 'string', description: 'Working directory for the command. Defaults to the turn cwd.' },
|
|
165
|
+
tty: { type: 'boolean', description: 'True allocates a PTY for the command; false or omitted uses plain pipes.' },
|
|
166
|
+
yield_time_ms: { type: 'number', description: 'Wait before yielding output. Defaults to 10000 ms; effective range is 250-30000 ms.' },
|
|
167
|
+
max_output_tokens: { type: 'number', description: 'Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy.' },
|
|
168
|
+
shell: { type: 'string', description: "Shell binary to launch. Defaults to the user's default shell." },
|
|
169
|
+
login: { type: 'boolean', description: 'True runs the shell with -l/-i semantics; false disables them. Defaults to true.' },
|
|
170
|
+
},
|
|
171
|
+
output: {
|
|
172
|
+
schema: {
|
|
173
|
+
type: 'object',
|
|
174
|
+
additionalProperties: false,
|
|
175
|
+
properties: {
|
|
176
|
+
chunk_id: { type: 'string' },
|
|
177
|
+
wall_time_seconds: { type: 'number', required: true },
|
|
178
|
+
exit_code: { type: 'number' },
|
|
179
|
+
session_id: { type: 'number' },
|
|
180
|
+
original_token_count: { type: 'number' },
|
|
181
|
+
output: { type: 'string', required: true },
|
|
182
|
+
},
|
|
183
|
+
},
|
|
184
|
+
render: (_args, value) => [{ type: 'text', text: renderExecResult(value) }],
|
|
185
|
+
},
|
|
186
|
+
async execute(args, exec) {
|
|
187
|
+
return runExecCommand(ctx, args, exec, config);
|
|
188
|
+
},
|
|
189
|
+
presentCall: args => ({
|
|
190
|
+
card: 'terminal',
|
|
191
|
+
title: args.cmd,
|
|
192
|
+
...args.workdir === undefined ? {} : { cwd: args.workdir },
|
|
193
|
+
}),
|
|
194
|
+
}));
|
|
195
|
+
ctx.tools.register(defineTool({
|
|
196
|
+
name: 'write_stdin',
|
|
197
|
+
description: WRITE_STDIN_DESCRIPTION,
|
|
198
|
+
parameters: {
|
|
199
|
+
session_id: { type: 'number', required: true, description: 'Identifier of the running unified exec session.' },
|
|
200
|
+
chars: { type: 'string', description: 'Bytes to write to stdin. Defaults to empty, which polls without writing.' },
|
|
201
|
+
yield_time_ms: { type: 'number', description: 'Wait before yielding output. Non-empty writes default to 250 ms and cap at 30000 ms; empty polls wait 5000-300000 ms by default.' },
|
|
202
|
+
max_output_tokens: { type: 'number', description: 'Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy.' },
|
|
203
|
+
},
|
|
204
|
+
output: {
|
|
205
|
+
schema: {
|
|
206
|
+
type: 'object',
|
|
207
|
+
additionalProperties: false,
|
|
208
|
+
properties: {
|
|
209
|
+
chunk_id: { type: 'string' },
|
|
210
|
+
wall_time_seconds: { type: 'number', required: true },
|
|
211
|
+
exit_code: { type: 'number' },
|
|
212
|
+
session_id: { type: 'number' },
|
|
213
|
+
original_token_count: { type: 'number' },
|
|
214
|
+
output: { type: 'string', required: true },
|
|
215
|
+
},
|
|
216
|
+
},
|
|
217
|
+
render: (_args, value) => [{ type: 'text', text: renderExecResult(value) }],
|
|
218
|
+
},
|
|
219
|
+
async execute(args, exec) {
|
|
220
|
+
return runWriteStdin(ctx, args, exec, config);
|
|
221
|
+
},
|
|
222
|
+
}));
|
|
223
|
+
}
|
|
224
|
+
function registerPatchTool(ctx) {
|
|
225
|
+
ctx.tools.register(defineTool({
|
|
226
|
+
name: 'apply_patch',
|
|
227
|
+
description: APPLY_PATCH_DESCRIPTION,
|
|
228
|
+
parameters: {
|
|
229
|
+
input: { type: 'string', required: true, description: 'The complete patch text.' },
|
|
230
|
+
},
|
|
231
|
+
output: {
|
|
232
|
+
schema: {
|
|
233
|
+
type: 'object',
|
|
234
|
+
additionalProperties: false,
|
|
235
|
+
properties: {
|
|
236
|
+
files: {
|
|
237
|
+
type: 'array',
|
|
238
|
+
required: true,
|
|
239
|
+
items: {
|
|
240
|
+
type: 'object',
|
|
241
|
+
additionalProperties: false,
|
|
242
|
+
properties: {
|
|
243
|
+
path: { type: 'string', required: true },
|
|
244
|
+
operation: { type: 'string', required: true, enum: ['created', 'updated', 'deleted', 'moved'] },
|
|
245
|
+
moveTo: { type: 'string' },
|
|
246
|
+
},
|
|
247
|
+
},
|
|
248
|
+
},
|
|
249
|
+
},
|
|
250
|
+
},
|
|
251
|
+
render: (_args, value) => [{ type: 'text', text: patchSummary(value) }],
|
|
252
|
+
},
|
|
253
|
+
async execute(args, exec) {
|
|
254
|
+
const files = parsePatch(args.input);
|
|
255
|
+
const policy = resolvePolicy(ctx, exec);
|
|
256
|
+
const applied = [];
|
|
257
|
+
for (const file of files)
|
|
258
|
+
applied.push(await applyOnePatch(ctx, file, exec, policy));
|
|
259
|
+
return { files: applied };
|
|
260
|
+
},
|
|
261
|
+
presentCall(args) {
|
|
262
|
+
return {
|
|
263
|
+
card: 'generic',
|
|
264
|
+
title: 'Apply patch',
|
|
265
|
+
kind: 'edit',
|
|
266
|
+
rawInput: args.input,
|
|
267
|
+
};
|
|
268
|
+
},
|
|
269
|
+
}));
|
|
270
|
+
}
|
|
271
|
+
function registerPlanTool(ctx) {
|
|
272
|
+
ctx.tools.register(defineTool({
|
|
273
|
+
name: 'update_plan',
|
|
274
|
+
description: UPDATE_PLAN_DESCRIPTION,
|
|
275
|
+
parameters: {
|
|
276
|
+
explanation: { type: 'string', description: 'Optional explanation for this plan update.' },
|
|
277
|
+
plan: {
|
|
278
|
+
type: 'array',
|
|
279
|
+
required: true,
|
|
280
|
+
description: 'The list of steps',
|
|
281
|
+
items: {
|
|
282
|
+
type: 'object',
|
|
283
|
+
additionalProperties: false,
|
|
284
|
+
properties: {
|
|
285
|
+
step: { type: 'string', required: true, description: 'Task step text.' },
|
|
286
|
+
status: { type: 'string', required: true, enum: [...PLAN_STATUSES], description: 'Step status.' },
|
|
287
|
+
},
|
|
288
|
+
},
|
|
289
|
+
},
|
|
290
|
+
},
|
|
291
|
+
output: {
|
|
292
|
+
schema: { type: 'object', additionalProperties: false, properties: {} },
|
|
293
|
+
render: () => [{ type: 'text', text: 'Plan updated' }],
|
|
294
|
+
},
|
|
295
|
+
execute(args, exec) {
|
|
296
|
+
const agent = exec.agent;
|
|
297
|
+
if (agent === undefined)
|
|
298
|
+
throw new Error('update_plan requires an owning agent session');
|
|
299
|
+
agent.session.append('todo/write', { todos: planTodos(args) });
|
|
300
|
+
return Promise.resolve({});
|
|
301
|
+
},
|
|
302
|
+
}));
|
|
303
|
+
}
|
|
304
|
+
/** Mount the Codex prompt/tool layer inside one fixed agent preset. */
|
|
305
|
+
export function apply(ctx, config = {}) {
|
|
306
|
+
const resolved = {
|
|
307
|
+
defaultYieldTimeMs: config.defaultYieldTimeMs ?? 10_000,
|
|
308
|
+
pollYieldTimeMs: config.pollYieldTimeMs ?? 5_000,
|
|
309
|
+
writeYieldTimeMs: config.writeYieldTimeMs ?? 250,
|
|
310
|
+
maxOutputBytes: config.maxOutputBytes ?? 64_000,
|
|
311
|
+
};
|
|
312
|
+
if (ctx.fs.sandboxMode !== undefined && ctx.get('sandboxPolicy') === undefined) {
|
|
313
|
+
throw new Error('codex: a sandboxing filesystem requires ctx.sandboxPolicy');
|
|
314
|
+
}
|
|
315
|
+
ctx.systemPrompt.section({ name: 'codex:base', order: 10, text: CODEX_BASE_PROMPT });
|
|
316
|
+
registerExecTools(ctx, resolved);
|
|
317
|
+
registerPatchTool(ctx);
|
|
318
|
+
registerPlanTool(ctx);
|
|
319
|
+
}
|
|
320
|
+
export default { name, inject, Config, apply };
|
|
321
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Install the user-visible Codex agent preset supplied by this bundle. */
|
|
2
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
3
|
+
/** Bundle plugin name for the preset installer. */
|
|
4
|
+
export declare const name = "codex-preset-installer";
|
|
5
|
+
/**
|
|
6
|
+
* Install the shipped Codex preset only when the user has not authored one.
|
|
7
|
+
*
|
|
8
|
+
* The directory is committed with a staging rename so a failed copy cannot
|
|
9
|
+
* leave a half-written preset that hides the mode from the roster. Existing
|
|
10
|
+
* directories are intentionally preserved, including user customizations.
|
|
11
|
+
*
|
|
12
|
+
* @param targetDir - destination preset directory.
|
|
13
|
+
* @param sourceDir - directory containing the packaged preset files.
|
|
14
|
+
*/
|
|
15
|
+
export declare function installCodexPreset(targetDir?: string, sourceDir?: string): void;
|
|
16
|
+
/** Install the preset during profile boot without changing the host tool catalog. */
|
|
17
|
+
export declare function apply(ctx: Context): void;
|
|
18
|
+
declare const _default: {
|
|
19
|
+
name: string;
|
|
20
|
+
apply: typeof apply;
|
|
21
|
+
};
|
|
22
|
+
export default _default;
|
|
23
|
+
//# sourceMappingURL=installer.d.ts.map
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/** Install the user-visible Codex agent preset supplied by this bundle. */
|
|
2
|
+
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, renameSync, rmSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { dirname, join, resolve } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
const PRESET_ID = 'codex';
|
|
7
|
+
const PRESET_FILES = ['agent.cordis.yml', 'preset.yml'];
|
|
8
|
+
const SOURCE_PRESET_DIR = fileURLToPath(new URL('../presets/codex/', import.meta.url));
|
|
9
|
+
function dshHomePath(...segments) {
|
|
10
|
+
const configured = process.env.DSH_HOME?.trim();
|
|
11
|
+
const expanded = configured === undefined || configured.length === 0
|
|
12
|
+
? join(homedir(), '.dsh')
|
|
13
|
+
: configured === '~'
|
|
14
|
+
? homedir()
|
|
15
|
+
: configured.startsWith('~/') || configured.startsWith('~\\')
|
|
16
|
+
? join(homedir(), configured.slice(2))
|
|
17
|
+
: configured;
|
|
18
|
+
return join(resolve(expanded), ...segments);
|
|
19
|
+
}
|
|
20
|
+
/** Bundle plugin name for the preset installer. */
|
|
21
|
+
export const name = 'codex-preset-installer';
|
|
22
|
+
/**
|
|
23
|
+
* Install the shipped Codex preset only when the user has not authored one.
|
|
24
|
+
*
|
|
25
|
+
* The directory is committed with a staging rename so a failed copy cannot
|
|
26
|
+
* leave a half-written preset that hides the mode from the roster. Existing
|
|
27
|
+
* directories are intentionally preserved, including user customizations.
|
|
28
|
+
*
|
|
29
|
+
* @param targetDir - destination preset directory.
|
|
30
|
+
* @param sourceDir - directory containing the packaged preset files.
|
|
31
|
+
*/
|
|
32
|
+
export function installCodexPreset(targetDir = dshHomePath('.agent-presets', PRESET_ID), sourceDir = SOURCE_PRESET_DIR) {
|
|
33
|
+
if (existsSync(targetDir))
|
|
34
|
+
return;
|
|
35
|
+
const parentDir = dirname(targetDir);
|
|
36
|
+
mkdirSync(parentDir, { recursive: true });
|
|
37
|
+
const stagingDir = mkdtempSync(join(parentDir, `.${PRESET_ID}-`));
|
|
38
|
+
try {
|
|
39
|
+
for (const file of PRESET_FILES)
|
|
40
|
+
copyFileSync(join(sourceDir, file), join(stagingDir, file));
|
|
41
|
+
try {
|
|
42
|
+
renameSync(stagingDir, targetDir);
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
if (!existsSync(targetDir))
|
|
46
|
+
throw error;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
finally {
|
|
50
|
+
if (existsSync(stagingDir))
|
|
51
|
+
rmSync(stagingDir, { recursive: true, force: true });
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/** Install the preset during profile boot without changing the host tool catalog. */
|
|
55
|
+
export function apply(ctx) {
|
|
56
|
+
try {
|
|
57
|
+
installCodexPreset();
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
ctx.logger.warn(`dsh-codex: could not install the Codex preset: ${String(error)}`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
export default { name, apply };
|
|
64
|
+
//# sourceMappingURL=installer.js.map
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Package-owned invariant companion for `@shuind/dsh-codex-harness`.
|
|
3
|
+
* @module @shuind/dsh-codex-harness/invariant
|
|
4
|
+
*/
|
|
5
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
6
|
+
/** Codex companion plugin name. */
|
|
7
|
+
export declare const name = "codex-invariant";
|
|
8
|
+
/** Service required before the companion can reserve package ownership. */
|
|
9
|
+
export declare const inject: string[];
|
|
10
|
+
/**
|
|
11
|
+
* Register this package's invariant companion.
|
|
12
|
+
* @param ctx - Cordis context carrying the invariant service.
|
|
13
|
+
* @returns the installed registration's disposer after setup succeeds.
|
|
14
|
+
*/
|
|
15
|
+
export declare const apply: (ctx: Context) => Promise<() => void>;
|
|
16
|
+
//# sourceMappingURL=invariant.d.ts.map
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Package-owned invariant companion for `@shuind/dsh-codex-harness`.
|
|
3
|
+
* @module @shuind/dsh-codex-harness/invariant
|
|
4
|
+
*/
|
|
5
|
+
const PACKAGE_NAME = '@shuind/dsh-codex-harness';
|
|
6
|
+
/** Codex companion plugin name. */
|
|
7
|
+
export const name = 'codex-invariant';
|
|
8
|
+
/** Service required before the companion can reserve package ownership. */
|
|
9
|
+
export const inject = ['invariants'];
|
|
10
|
+
/**
|
|
11
|
+
* Codex has no independent lifecycle stream: its model-visible state is owned
|
|
12
|
+
* by the tool registry and session projection services it consumes.
|
|
13
|
+
*/
|
|
14
|
+
const install = () => { };
|
|
15
|
+
/**
|
|
16
|
+
* Register this package's invariant companion.
|
|
17
|
+
* @param ctx - Cordis context carrying the invariant service.
|
|
18
|
+
* @returns the installed registration's disposer after setup succeeds.
|
|
19
|
+
*/
|
|
20
|
+
export const apply = (ctx) => Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install));
|
|
21
|
+
/* jscpd:ignore-end */
|
|
22
|
+
//# sourceMappingURL=invariant.js.map
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** Parser and line-oriented applicator for Codex's `apply_patch` language. */
|
|
2
|
+
/** The grammar sent to providers that support OpenAI custom grammar tools. */
|
|
3
|
+
export declare const APPLY_PATCH_GRAMMAR: string;
|
|
4
|
+
export type PatchLine = {
|
|
5
|
+
kind: 'context';
|
|
6
|
+
text: string;
|
|
7
|
+
} | {
|
|
8
|
+
kind: 'delete';
|
|
9
|
+
text: string;
|
|
10
|
+
} | {
|
|
11
|
+
kind: 'add';
|
|
12
|
+
text: string;
|
|
13
|
+
};
|
|
14
|
+
export interface PatchHunk {
|
|
15
|
+
context?: string;
|
|
16
|
+
lines: PatchLine[];
|
|
17
|
+
endOfFile: boolean;
|
|
18
|
+
}
|
|
19
|
+
export type PatchFile = {
|
|
20
|
+
kind: 'add';
|
|
21
|
+
path: string;
|
|
22
|
+
content: string;
|
|
23
|
+
} | {
|
|
24
|
+
kind: 'delete';
|
|
25
|
+
path: string;
|
|
26
|
+
} | {
|
|
27
|
+
kind: 'update';
|
|
28
|
+
path: string;
|
|
29
|
+
moveTo?: string;
|
|
30
|
+
hunks: PatchHunk[];
|
|
31
|
+
};
|
|
32
|
+
/** Parse one complete Codex patch after normalizing CRLF input to LF. */
|
|
33
|
+
export declare function parsePatch(input: string): PatchFile[];
|
|
34
|
+
/** Apply parsed update hunks and return LF-normalized text. */
|
|
35
|
+
export declare function applyPatchHunks(original: string, hunks: readonly PatchHunk[]): string;
|
|
36
|
+
//# sourceMappingURL=patch.d.ts.map
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/** Parser and line-oriented applicator for Codex's `apply_patch` language. */
|
|
2
|
+
/** The grammar sent to providers that support OpenAI custom grammar tools. */
|
|
3
|
+
export const APPLY_PATCH_GRAMMAR = String.raw `start: begin_patch hunk+ end_patch
|
|
4
|
+
begin_patch: "*** Begin Patch" LF
|
|
5
|
+
end_patch: "*** End Patch" LF?
|
|
6
|
+
hunk: add_hunk | delete_hunk | update_hunk
|
|
7
|
+
add_hunk: "*** Add File: " filename LF add_line+
|
|
8
|
+
delete_hunk: "*** Delete File: " filename LF
|
|
9
|
+
update_hunk: "*** Update File: " filename LF change_move? change?
|
|
10
|
+
filename: /(.+)/
|
|
11
|
+
add_line: "+" /(.*)/ LF -> line
|
|
12
|
+
change_move: "*** Move to: " filename LF
|
|
13
|
+
change: (change_context | change_line)+ eof_line?
|
|
14
|
+
change_context: ("@@" | "@@ " /(.+)/) LF
|
|
15
|
+
change_line: ("+" | "-" | " ") /(.*)/ LF
|
|
16
|
+
eof_line: "*** End of File" LF
|
|
17
|
+
%import common.LF
|
|
18
|
+
`;
|
|
19
|
+
function invalid(message) {
|
|
20
|
+
throw new Error(`apply_patch: ${message}`);
|
|
21
|
+
}
|
|
22
|
+
function isFileHeader(line) {
|
|
23
|
+
const trimmed = line.trim();
|
|
24
|
+
return trimmed.startsWith('*** Add File: ')
|
|
25
|
+
|| trimmed.startsWith('*** Delete File: ')
|
|
26
|
+
|| trimmed.startsWith('*** Update File: ');
|
|
27
|
+
}
|
|
28
|
+
function pathFrom(line, prefix) {
|
|
29
|
+
const path = line.slice(prefix.length).trim();
|
|
30
|
+
if (path.length === 0)
|
|
31
|
+
invalid(`${prefix.trim()} requires a file path`);
|
|
32
|
+
return path;
|
|
33
|
+
}
|
|
34
|
+
function isChangeMarker(line) {
|
|
35
|
+
const marker = line.trimEnd();
|
|
36
|
+
return marker === '@@' || marker.startsWith('@@ ');
|
|
37
|
+
}
|
|
38
|
+
function isPotentialChangeMarker(line) {
|
|
39
|
+
return line.trimEnd().startsWith('@@');
|
|
40
|
+
}
|
|
41
|
+
/** Parse one complete Codex patch after normalizing CRLF input to LF. */
|
|
42
|
+
export function parsePatch(input) {
|
|
43
|
+
const lines = input.replaceAll('\r\n', '\n').trim().split('\n');
|
|
44
|
+
if (lines[0]?.trim() !== '*** Begin Patch')
|
|
45
|
+
invalid('input must start with "*** Begin Patch"');
|
|
46
|
+
if (lines.at(-1)?.trim() !== '*** End Patch')
|
|
47
|
+
invalid('input must end with "*** End Patch"');
|
|
48
|
+
const files = [];
|
|
49
|
+
let index = 1;
|
|
50
|
+
const end = lines.length - 1;
|
|
51
|
+
while (index < end) {
|
|
52
|
+
const header = lines[index++]?.trim();
|
|
53
|
+
if (header === undefined)
|
|
54
|
+
invalid('unexpected end of input');
|
|
55
|
+
if (header.startsWith('*** Add File: ')) {
|
|
56
|
+
const path = pathFrom(header, '*** Add File: ');
|
|
57
|
+
const content = [];
|
|
58
|
+
while (index < end && lines[index]?.startsWith('+') === true) {
|
|
59
|
+
content.push(lines[index].slice(1));
|
|
60
|
+
index++;
|
|
61
|
+
}
|
|
62
|
+
if (content.length === 0)
|
|
63
|
+
invalid(`add file ${JSON.stringify(path)} needs at least one content line`);
|
|
64
|
+
files.push({ kind: 'add', path, content: `${content.join('\n')}\n` });
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (header.startsWith('*** Delete File: ')) {
|
|
68
|
+
files.push({ kind: 'delete', path: pathFrom(header, '*** Delete File: ') });
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (!header.startsWith('*** Update File: '))
|
|
72
|
+
invalid(`unexpected directive ${JSON.stringify(header)}`);
|
|
73
|
+
const path = pathFrom(header, '*** Update File: ');
|
|
74
|
+
let moveTo;
|
|
75
|
+
if (lines[index]?.trim().startsWith('*** Move to: ') === true) {
|
|
76
|
+
moveTo = pathFrom(lines[index].trim(), '*** Move to: ');
|
|
77
|
+
index++;
|
|
78
|
+
}
|
|
79
|
+
const hunks = [];
|
|
80
|
+
while (index < end && !isFileHeader(lines[index])) {
|
|
81
|
+
const patchLines = [];
|
|
82
|
+
let context;
|
|
83
|
+
if (isPotentialChangeMarker(lines[index])) {
|
|
84
|
+
const marker = lines[index].trimEnd();
|
|
85
|
+
if (!isChangeMarker(marker)) {
|
|
86
|
+
invalid(`invalid update hunk marker ${JSON.stringify(lines[index])}`);
|
|
87
|
+
}
|
|
88
|
+
index++;
|
|
89
|
+
context = marker.length === 2 ? undefined : marker.slice(3);
|
|
90
|
+
}
|
|
91
|
+
while (index < end && !isFileHeader(lines[index])
|
|
92
|
+
&& !isPotentialChangeMarker(lines[index])
|
|
93
|
+
&& lines[index].trimEnd() !== '*** End of File') {
|
|
94
|
+
const line = lines[index++];
|
|
95
|
+
const kind = line[0];
|
|
96
|
+
if (kind !== ' ' && kind !== '+' && kind !== '-') {
|
|
97
|
+
invalid(`unexpected update line ${JSON.stringify(line)}`);
|
|
98
|
+
}
|
|
99
|
+
patchLines.push({ kind: kind === ' ' ? 'context' : kind === '+' ? 'add' : 'delete', text: line.slice(1) });
|
|
100
|
+
}
|
|
101
|
+
const endOfFile = lines[index]?.trimEnd() === '*** End of File';
|
|
102
|
+
if (endOfFile)
|
|
103
|
+
index++;
|
|
104
|
+
if (patchLines.length === 0) {
|
|
105
|
+
if (context !== undefined || endOfFile)
|
|
106
|
+
invalid('an update hunk needs context or changed lines');
|
|
107
|
+
break;
|
|
108
|
+
}
|
|
109
|
+
hunks.push({
|
|
110
|
+
...context === undefined ? {} : { context },
|
|
111
|
+
lines: patchLines,
|
|
112
|
+
endOfFile,
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
if (hunks.length === 0 && moveTo === undefined)
|
|
116
|
+
invalid(`update file ${JSON.stringify(path)} has no changes`);
|
|
117
|
+
files.push({
|
|
118
|
+
kind: 'update',
|
|
119
|
+
path,
|
|
120
|
+
...moveTo === undefined ? {} : { moveTo },
|
|
121
|
+
hunks,
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
if (files.length === 0)
|
|
125
|
+
invalid('no files were modified');
|
|
126
|
+
return files;
|
|
127
|
+
}
|
|
128
|
+
function splitText(text) {
|
|
129
|
+
if (text.length === 0)
|
|
130
|
+
return { lines: [], trailingNewline: false };
|
|
131
|
+
const trailingNewline = text.endsWith('\n');
|
|
132
|
+
const lines = text.split('\n');
|
|
133
|
+
if (trailingNewline)
|
|
134
|
+
lines.pop();
|
|
135
|
+
return { lines, trailingNewline };
|
|
136
|
+
}
|
|
137
|
+
function joinText(value) {
|
|
138
|
+
const body = value.lines.join('\n');
|
|
139
|
+
return value.trailingNewline ? `${body}\n` : body;
|
|
140
|
+
}
|
|
141
|
+
function findSequence(lines, expected, from, endOfFile) {
|
|
142
|
+
if (expected.length === 0)
|
|
143
|
+
return Math.min(from, lines.length);
|
|
144
|
+
if (expected.length > lines.length)
|
|
145
|
+
return -1;
|
|
146
|
+
const first = endOfFile ? Math.max(from, lines.length - expected.length) : from;
|
|
147
|
+
const last = lines.length - expected.length;
|
|
148
|
+
const matchers = [
|
|
149
|
+
(actual, wanted) => actual === wanted,
|
|
150
|
+
(actual, wanted) => actual.trimEnd() === wanted.trimEnd(),
|
|
151
|
+
(actual, wanted) => actual.trim() === wanted.trim(),
|
|
152
|
+
];
|
|
153
|
+
for (const matchesLine of matchers) {
|
|
154
|
+
for (let index = first; index <= last; index++) {
|
|
155
|
+
let matches = true;
|
|
156
|
+
for (let offset = 0; offset < expected.length; offset++) {
|
|
157
|
+
if (!matchesLine(lines[index + offset], expected[offset])) {
|
|
158
|
+
matches = false;
|
|
159
|
+
break;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
if (matches)
|
|
163
|
+
return index;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return -1;
|
|
167
|
+
}
|
|
168
|
+
/** Apply parsed update hunks and return LF-normalized text. */
|
|
169
|
+
export function applyPatchHunks(original, hunks) {
|
|
170
|
+
const value = splitText(original.replaceAll('\r\n', '\n'));
|
|
171
|
+
let cursor = 0;
|
|
172
|
+
for (const hunk of hunks) {
|
|
173
|
+
const expected = hunk.lines.filter(line => line.kind !== 'add').map(line => line.text);
|
|
174
|
+
const start = findSequence(value.lines, expected, cursor, hunk.endOfFile);
|
|
175
|
+
if (start < 0) {
|
|
176
|
+
const detail = expected.join('\n');
|
|
177
|
+
invalid(`could not find expected lines${detail.length === 0 ? '' : `:\n${detail}`}`);
|
|
178
|
+
}
|
|
179
|
+
const replacement = hunk.lines.filter(line => line.kind !== 'delete').map(line => line.text);
|
|
180
|
+
value.lines.splice(start, expected.length, ...replacement);
|
|
181
|
+
cursor = start + replacement.length;
|
|
182
|
+
value.trailingNewline = !hunk.endOfFile;
|
|
183
|
+
}
|
|
184
|
+
return joinText(value);
|
|
185
|
+
}
|
|
186
|
+
//# sourceMappingURL=patch.js.map
|