@shuind/dsh-codex-harness 0.2.15 → 0.2.17

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.
@@ -0,0 +1,69 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import { TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol';
3
+ import type { CodexSettings } from './settings.ts';
4
+ import type { CodexPresetOptions, PresetCatalog, PresetCreateInput, PresetEditorInput, PresetEditorDocument, PresetPromptSection } from './preset-contract.ts';
5
+ export type { PresetEditorInput, PresetEditorDocument } from './preset-contract.ts';
6
+ export declare const DEFAULT_CODEX_PRESET_OPTIONS: CodexPresetOptions;
7
+ export interface ResolvedPresetForEditor {
8
+ id: string;
9
+ trust: 'system' | 'user';
10
+ path: string;
11
+ broken?: string;
12
+ name?: string;
13
+ description?: string;
14
+ }
15
+ export interface AgentPresetsForEditor {
16
+ list?(): Promise<ResolvedPresetForEditor[]>;
17
+ readonly defaultId?: string;
18
+ readonly authorable?: boolean;
19
+ resolve(id: string): Promise<ResolvedPresetForEditor>;
20
+ readDocument(id: string): Promise<{
21
+ content: string;
22
+ name?: string;
23
+ description?: string;
24
+ }>;
25
+ remoteExportList(): Promise<{
26
+ presets: Array<{
27
+ id: string;
28
+ name?: string;
29
+ description?: string;
30
+ trust: 'system' | 'user';
31
+ isDefault: boolean;
32
+ broken?: string;
33
+ }>;
34
+ authorable: boolean;
35
+ }>;
36
+ copy(from: string, id: string, name?: string): Promise<void>;
37
+ remove(id: string): Promise<void>;
38
+ readonly roots?: readonly {
39
+ path: string;
40
+ trust: 'system' | 'user';
41
+ }[];
42
+ }
43
+ export declare function readPromptSections(content: string, shared?: Partial<CodexSettings>): PresetPromptSection[];
44
+ /** Patch the contributing fields, not a disconnected secondary prompt. */
45
+ export declare function patchPromptSections(content: string, sections: PresetPromptSection[]): string;
46
+ export declare function readCodexPresetOptions(content: string): CodexPresetOptions;
47
+ export declare function supportsCodex(content: string): boolean;
48
+ /** Structural validation only: executable tags stay inert until DSH mounts a selected preset. */
49
+ export declare function validateComposition(content: string): void;
50
+ export declare function enhanceComposition(content: string): string;
51
+ export declare function readPresetSystemPrompt(content: string): string;
52
+ export declare function patchPresetComposition(content: string, prompt: string, inherit?: boolean): string;
53
+ /** Store user-facing Codex capability switches in the Harness row. */
54
+ export declare function patchCodexPresetOptions(content: string, options: Partial<CodexPresetOptions>): string;
55
+ export declare function patchPresetMetadata(content: string, name: string, description: string): string;
56
+ export declare class CodexPresetEditor extends TypertRemoteService {
57
+ static inject: string[];
58
+ private readonly agentPresets;
59
+ private sharedSettings?;
60
+ private indexed?;
61
+ constructor(ctx: Context, _config?: undefined);
62
+ catalog(): Promise<PresetCatalog>;
63
+ read(id: string): Promise<PresetEditorDocument>;
64
+ create(rawInput: PresetCreateInput): Promise<PresetEditorDocument>;
65
+ update(rawInput: PresetEditorInput): Promise<PresetEditorDocument>;
66
+ private preset;
67
+ }
68
+ export default CodexPresetEditor;
69
+ //# sourceMappingURL=preset-editor.d.ts.map
@@ -0,0 +1,546 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { readFile, realpath, stat, unlink } from 'node:fs/promises';
3
+ import { dirname, isAbsolute, relative, resolve } from 'node:path';
4
+ import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol';
5
+ import { isMap, isScalar, isSeq, parseDocument, Scalar, YAMLMap } from 'yaml';
6
+ import { DEFAULT_CODEX_PERSONA, DEFAULT_CODEX_SYSTEM_PROMPT, DEFAULT_DSH_CORE_SOURCE_PROMPT, DEFAULT_DSH_CORE_WEB_PROMPT } from "./prompt.js";
7
+ let atomicWriteModule;
8
+ function loadAtomicWrite() {
9
+ return atomicWriteModule ??= import('@deepseek-ai/dsh-atomic-write');
10
+ }
11
+ const PRESET_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
12
+ export const DEFAULT_CODEX_PRESET_OPTIONS = {
13
+ promptEnabled: true,
14
+ terminalToolsEnabled: true,
15
+ patchToolEnabled: true,
16
+ planToolEnabled: true,
17
+ hostedWebSearchEnabled: true,
18
+ remoteCompactionEnabled: true,
19
+ };
20
+ const CODEX_OPTION_KEYS = Object.keys(DEFAULT_CODEX_PRESET_OPTIONS);
21
+ /** Parse tags as syntax only; never execute !!js or resolve aliases into objects. */
22
+ function yaml(content) {
23
+ const doc = parseDocument(content, { strict: true, uniqueKeys: true });
24
+ if (doc.errors.length)
25
+ throw new Error('invalid-preset-yaml');
26
+ return doc;
27
+ }
28
+ function harnessConfig(content) {
29
+ const doc = yaml(content);
30
+ if (!isSeq(doc.contents))
31
+ throw new Error('unsupported-preset');
32
+ const rows = doc.contents.items.filter(row => isMap(row)
33
+ && row.get('name') === '@shuind/dsh-codex-harness'
34
+ && row.get('disabled') !== true);
35
+ if (rows.length !== 1)
36
+ throw new Error('unsupported-preset');
37
+ const row = rows[0];
38
+ let config = row.get('config', true);
39
+ if (config === undefined) {
40
+ config = new YAMLMap();
41
+ row.set('config', config);
42
+ }
43
+ if (!isMap(config) || config.get('codexCore') === false)
44
+ throw new Error('unsupported-preset');
45
+ return { doc, config };
46
+ }
47
+ function explicitPrompt(content) {
48
+ const { config } = harnessConfig(content);
49
+ const node = config.get('presetPrompt', true) ?? config.get('systemPrompt', true);
50
+ if (node === undefined)
51
+ return undefined;
52
+ if (!isScalar(node) || typeof node.value !== 'string' || node.tag)
53
+ throw new Error('unsupported-prompt-expression');
54
+ return node.value;
55
+ }
56
+ const SECTION_PLUGIN = '@shuind/dsh-codex-harness/prompt-sections';
57
+ function promptFile(node) {
58
+ if (!node.tag || typeof node.value !== 'string')
59
+ return undefined;
60
+ // Recognize this literal file reference only. Never evaluate arbitrary JS.
61
+ return node.value.match(/^process\.getBuiltinModule\(['"]node:fs['"]\)\.readFileSync\(new URL\(['"]([^'"]+)['"],\s*baseUrl\),\s*['"]utf8['"]\)$/)?.[1];
62
+ }
63
+ /** Read the actual literal prompt fields, including nested groups, without evaluating YAML tags. */
64
+ function promptFields(doc) {
65
+ const fields = [];
66
+ function visit(sequence, parents = []) {
67
+ if (!isSeq(sequence))
68
+ return;
69
+ for (const row of sequence.items) {
70
+ if (!isMap(row) || row.get('disabled') === true)
71
+ continue;
72
+ const path = [...parents, String(row.get('id'))];
73
+ const config = row.get('config', true);
74
+ if (isSeq(config)) {
75
+ visit(config, path);
76
+ continue;
77
+ }
78
+ if (!isMap(config))
79
+ continue;
80
+ const plugin = String(row.get('name'));
81
+ // Plan-mode instructions are mode-specific policy, not preset prompt customization.
82
+ if (plugin === '@deepseek-ai/dsh-plan-mode')
83
+ continue;
84
+ const keys = plugin === '@deepseek-ai/dsh-persona' ? ['prefix', 'text', 'suffix']
85
+ : plugin === '@shuind/dsh-codex-harness' || plugin === SECTION_PLUGIN ? []
86
+ : ['prefix', 'suffix', 'text', 'section', 'prompt', 'systemPrompt', 'instructions'];
87
+ for (const key of keys) {
88
+ const node = config.get(key, true);
89
+ if (!isScalar(node))
90
+ continue;
91
+ fields.push({ id: JSON.stringify([...path, key]), label: plugin === '@deepseek-ai/dsh-persona'
92
+ ? (key === 'suffix' ? 'Persona · suffix' : 'Persona') : `${path.join(' / ')} · ${key}`, node, row: config, key });
93
+ }
94
+ }
95
+ }
96
+ visit(doc.contents);
97
+ return fields;
98
+ }
99
+ function sectionConfig(content) {
100
+ if (supportsCodex(content)) {
101
+ const value = harnessConfig(content).config.get('presetSections', true);
102
+ return isMap(value) ? value : undefined;
103
+ }
104
+ const doc = yaml(content);
105
+ if (!isSeq(doc.contents))
106
+ return undefined;
107
+ const row = doc.contents.items.find(row => isMap(row) && row.get('name') === SECTION_PLUGIN);
108
+ const config = isMap(row) ? row.get('config', true) : undefined;
109
+ return isMap(config) ? config : undefined;
110
+ }
111
+ /** Some presets intentionally shadow host prompt sections with empty entries. */
112
+ function suppressesHostSections(content) {
113
+ const doc = yaml(content);
114
+ let suppressed = false;
115
+ function visit(sequence) {
116
+ if (!isSeq(sequence))
117
+ return;
118
+ for (const row of sequence.items) {
119
+ if (!isMap(row))
120
+ continue;
121
+ const id = String(row.get('id') ?? '');
122
+ const plugin = String(row.get('name') ?? '');
123
+ if (id === 'story-prompt-clean-slate' || plugin === './tools/prompt/clean-slate.mjs' || /(?:^|[\\/])clean-slate\.mjs$/u.test(plugin)) {
124
+ suppressed = true;
125
+ return;
126
+ }
127
+ const config = row.get('config', true);
128
+ if (isSeq(config))
129
+ visit(config);
130
+ if (suppressed)
131
+ return;
132
+ }
133
+ }
134
+ visit(doc.contents);
135
+ return suppressed;
136
+ }
137
+ export function readPromptSections(content, shared = {}) {
138
+ const codex = supportsCodex(content);
139
+ const overrides = sectionConfig(content);
140
+ const fields = promptFields(yaml(content));
141
+ const sections = fields.map(({ id, label, node }) => ({ id, label, text: String(node.value ?? ''), editable: !node.tag && typeof node.value === 'string' }));
142
+ // Legacy Codex global overrides remain visible until the preset is saved locally.
143
+ const persona = sections.find(section => section.label === 'Persona');
144
+ const personaOverride = !overrides?.has('persona') && codex ? shared.persona : undefined;
145
+ if (persona && typeof personaOverride === 'string' && personaOverride !== DEFAULT_CODEX_PERSONA)
146
+ persona.text = personaOverride;
147
+ const complete = fields.some(field => field.label.startsWith('Persona') && field.row.get('complete') === true);
148
+ // These are host prompt sections, not Codex capability toggles. The Web
149
+ // host registers them for non-complete agents unless the composition
150
+ // explicitly shadows them (Story's clean-slate plugin does exactly that).
151
+ const hasHostSections = !complete && !suppressesHostSections(content);
152
+ if (hasHostSections)
153
+ sections.splice(persona ? 1 : 0, 0, { id: 'harness:source', label: 'DSH Core 源码说明', text: String(overrides?.get('harnessSourcePrompt') ?? (codex ? shared.harnessSourcePrompt : undefined) ?? DEFAULT_DSH_CORE_SOURCE_PROMPT), editable: true }, { id: 'app:web-surface', label: 'DSH Core Web 说明', text: String(overrides?.get('webSurfacePrompt') ?? (codex ? shared.webSurfacePrompt : undefined) ?? DEFAULT_DSH_CORE_WEB_PROMPT), editable: true });
154
+ if (codex) {
155
+ const index = persona ? (hasHostSections ? 3 : 1) : (hasHostSections ? 2 : 0);
156
+ sections.splice(index, 0, { id: 'codex:base', label: 'Codex 操作提示词', text: explicitPrompt(content) ?? shared.systemPrompt ?? DEFAULT_CODEX_SYSTEM_PROMPT, editable: true });
157
+ }
158
+ return sections;
159
+ }
160
+ /** Patch the contributing fields, not a disconnected secondary prompt. */
161
+ export function patchPromptSections(content, sections) {
162
+ const doc = yaml(content);
163
+ const fields = promptFields(doc);
164
+ const known = new Map(readPromptSections(content).map(section => [section.id, section]));
165
+ const overrides = {};
166
+ const seen = new Set();
167
+ for (const section of sections) {
168
+ const field = fields.find(field => field.id === section.id);
169
+ if (seen.has(section.id) || (!known.get(section.id)?.editable && !(field && promptFile(field.node))) || typeof section.text !== 'string' || section.text.length > 1_000_000)
170
+ throw new Error('invalid-prompt-section');
171
+ seen.add(section.id);
172
+ if (field) {
173
+ const node = new Scalar(section.text);
174
+ node.type = Scalar.BLOCK_LITERAL;
175
+ field.row.set(field.key, node);
176
+ continue;
177
+ }
178
+ // Merely saving a generic preset must not freeze inherited DSH defaults or
179
+ // install an override plugin. An actual edit is enough; it never needs Codex.
180
+ if (!supportsCodex(content) && known.get(section.id)?.text === section.text)
181
+ continue;
182
+ if (section.id === 'harness:source')
183
+ overrides.harnessSourcePrompt = section.text;
184
+ if (section.id === 'app:web-surface')
185
+ overrides.webSurfacePrompt = section.text;
186
+ }
187
+ // Persona is edited at its original source. Override legacy shared settings with
188
+ // that same value in Codex scopes, without touching another preset's identity.
189
+ const personaFields = fields.filter(field => known.get(field.id)?.label.startsWith('Persona'));
190
+ if (supportsCodex(content) && personaFields.length)
191
+ overrides.persona = personaFields.map(field => sections.find(section => section.id === field.id)?.text ?? String(field.node.value)).join('\n\n');
192
+ let result = doc.toString({ lineWidth: 0 });
193
+ if (supportsCodex(result)) {
194
+ const { doc: next, config } = harnessConfig(result);
195
+ const previous = config.get('presetSections', true);
196
+ const merged = isMap(previous) ? previous : new YAMLMap();
197
+ for (const [key, value] of Object.entries(overrides))
198
+ merged.set(key, value);
199
+ config.set('presetSections', merged);
200
+ result = next.toString({ lineWidth: 0 });
201
+ const operating = sections.find(section => section.id === 'codex:base');
202
+ if (operating)
203
+ result = patchPresetComposition(result, operating.text);
204
+ }
205
+ else if (Object.keys(overrides).length) {
206
+ const next = yaml(result);
207
+ if (!isSeq(next.contents))
208
+ throw new Error('invalid-preset-yaml');
209
+ let row = next.contents.items.find(row => isMap(row) && row.get('name') === SECTION_PLUGIN);
210
+ if (!isMap(row)) {
211
+ const created = new YAMLMap();
212
+ created.set('id', `prompt-sections-${randomUUID().slice(0, 8)}`);
213
+ created.set('name', SECTION_PLUGIN);
214
+ next.add(created);
215
+ row = created;
216
+ }
217
+ const map = row;
218
+ let config = map.get('config', true);
219
+ if (!isMap(config)) {
220
+ config = new YAMLMap();
221
+ map.set('config', config);
222
+ }
223
+ for (const [key, value] of Object.entries(overrides))
224
+ config.set(key, value);
225
+ result = next.toString({ lineWidth: 0 });
226
+ }
227
+ return result;
228
+ }
229
+ export function readCodexPresetOptions(content) {
230
+ try {
231
+ const { config } = harnessConfig(content);
232
+ const options = { ...DEFAULT_CODEX_PRESET_OPTIONS };
233
+ for (const key of CODEX_OPTION_KEYS) {
234
+ const value = config.get(key);
235
+ if (typeof value === 'boolean')
236
+ options[key] = value;
237
+ }
238
+ return options;
239
+ }
240
+ catch {
241
+ return { ...DEFAULT_CODEX_PRESET_OPTIONS };
242
+ }
243
+ }
244
+ export function supportsCodex(content) {
245
+ try {
246
+ harnessConfig(content);
247
+ return true;
248
+ }
249
+ catch {
250
+ return false;
251
+ }
252
+ }
253
+ /** Structural validation only: executable tags stay inert until DSH mounts a selected preset. */
254
+ export function validateComposition(content) {
255
+ if (content.length > 1_000_000)
256
+ throw new Error('invalid-preset-yaml');
257
+ const doc = yaml(content);
258
+ if (!isSeq(doc.contents) || !doc.contents.items.length)
259
+ throw new Error('invalid-preset-yaml');
260
+ const ids = new Set();
261
+ for (const entry of doc.contents.items) {
262
+ if (!isMap(entry))
263
+ throw new Error('invalid-preset-yaml');
264
+ const row = entry;
265
+ if (typeof row.get('name') !== 'string')
266
+ throw new Error('invalid-preset-yaml');
267
+ const id = row.get('id');
268
+ if (typeof id !== 'string' || ids.has(id))
269
+ throw new Error('invalid-preset-yaml');
270
+ ids.add(id);
271
+ }
272
+ }
273
+ export function enhanceComposition(content) {
274
+ validateComposition(content);
275
+ if (supportsCodex(content))
276
+ return content;
277
+ // A disabled/ambiguous Harness row needs explicit advanced editing, not a second instance.
278
+ const doc = yaml(content);
279
+ if (!isSeq(doc.contents))
280
+ throw new Error('invalid-preset-yaml');
281
+ if (doc.contents.items.some(row => isMap(row) && row.get('name') === '@shuind/dsh-codex-harness'))
282
+ throw new Error('ambiguous-harness-row');
283
+ // A complete persona suppresses all contributed sections, including Codex's.
284
+ // Keep its identity text while allowing the enhanced copy to compose prompts.
285
+ for (const row of doc.contents.items) {
286
+ if (!isMap(row) || row.get('name') !== '@deepseek-ai/dsh-persona')
287
+ continue;
288
+ const persona = row.get('config', true);
289
+ if (isMap(persona) && persona.get('complete') === true)
290
+ persona.set('complete', false);
291
+ }
292
+ doc.add(doc.createNode({ id: `codex-harness-${randomUUID().slice(0, 8)}`,
293
+ name: '@shuind/dsh-codex-harness', config: { globalEnhancements: false, codexCore: true } }));
294
+ return doc.toString({ lineWidth: 0 });
295
+ }
296
+ export function readPresetSystemPrompt(content) {
297
+ return explicitPrompt(content) ?? DEFAULT_CODEX_SYSTEM_PROMPT;
298
+ }
299
+ export function patchPresetComposition(content, prompt, inherit = false) {
300
+ const { doc, config } = harnessConfig(content);
301
+ // Migrate the old field, avoiding two competing prompt sources.
302
+ config.delete('systemPrompt');
303
+ if (inherit)
304
+ config.delete('presetPrompt');
305
+ else {
306
+ const node = new Scalar(prompt);
307
+ node.type = prompt.includes('\n') ? Scalar.BLOCK_LITERAL : Scalar.QUOTE_DOUBLE;
308
+ config.set('presetPrompt', node);
309
+ }
310
+ return doc.toString({ lineWidth: 0 });
311
+ }
312
+ /** Store user-facing Codex capability switches in the Harness row. */
313
+ export function patchCodexPresetOptions(content, options) {
314
+ const { doc, config } = harnessConfig(content);
315
+ for (const key of CODEX_OPTION_KEYS) {
316
+ const value = options[key];
317
+ if (value !== undefined)
318
+ config.set(key, value);
319
+ }
320
+ return doc.toString({ lineWidth: 0 });
321
+ }
322
+ export function patchPresetMetadata(content, name, description) {
323
+ const doc = yaml(content);
324
+ if (doc.contents !== null && !isMap(doc.contents))
325
+ throw new Error('invalid-preset-metadata');
326
+ for (const [key, value] of Object.entries({ name, description })) {
327
+ const node = new Scalar(value);
328
+ node.type = Scalar.QUOTE_DOUBLE;
329
+ doc.set(key, node);
330
+ }
331
+ return doc.toString({ lineWidth: 0 });
332
+ }
333
+ function validate(input) {
334
+ if (typeof input.name !== 'string' || !input.name.trim() || /[\r\n]/.test(input.name) || input.name.length > 200)
335
+ throw new Error('invalid-preset-name');
336
+ if (typeof input.description !== 'string' || input.description.length > 4000)
337
+ throw new Error('invalid-preset-description');
338
+ if (typeof input.systemPrompt !== 'string' || input.systemPrompt.length > 1_000_000)
339
+ throw new Error('invalid-preset-prompt');
340
+ return { ...input, name: input.name.trim() };
341
+ }
342
+ function revision(composition, metadata) {
343
+ return createHash('sha256').update(composition).update('\0').update(metadata ?? '').digest('hex');
344
+ }
345
+ async function optionalFile(path) {
346
+ try {
347
+ return await readFile(path, 'utf8');
348
+ }
349
+ catch (error) {
350
+ if (error.code === 'ENOENT')
351
+ return undefined;
352
+ throw error;
353
+ }
354
+ }
355
+ async function mode(path) {
356
+ try {
357
+ return (await stat(path)).mode & 0o777;
358
+ }
359
+ catch {
360
+ return 0o600;
361
+ }
362
+ }
363
+ async function assertWithinRoot(path, roots) {
364
+ if (!roots?.length)
365
+ throw new Error('preset-root-unavailable');
366
+ const target = await realpath(path);
367
+ for (const root of roots) {
368
+ if (root.trust !== 'user')
369
+ continue;
370
+ const home = process.env.DSH_HOME ?? process.env.USERPROFILE ?? process.env.HOME ?? '';
371
+ const expanded = root.path.replace(/^~(?=[\\/]|$)/, home);
372
+ try {
373
+ const rel = relative(await realpath(resolve(expanded)), target);
374
+ if (!isAbsolute(rel) && rel !== '..' && !rel.startsWith('../') && !rel.startsWith('..\\'))
375
+ return;
376
+ }
377
+ catch { /* An absent root cannot own this path. */ }
378
+ }
379
+ throw new Error('preset-outside-user-root');
380
+ }
381
+ export class CodexPresetEditor extends TypertRemoteService {
382
+ static inject = ['agentPresets', 'settings'];
383
+ agentPresets;
384
+ sharedSettings;
385
+ indexed;
386
+ constructor(ctx, _config) {
387
+ super(ctx, 'codexPresetEditor');
388
+ this.agentPresets = ctx.get('agentPresets');
389
+ const settings = ctx.get('settings');
390
+ this.sharedSettings = () => settings?.get('codex') ?? {};
391
+ }
392
+ async catalog() {
393
+ if (this.agentPresets.list) {
394
+ const rows = await this.agentPresets.list();
395
+ this.indexed = new Map(rows.map(row => [row.id, row]));
396
+ return { presets: rows.filter(row => row.broken === undefined).map(row => ({
397
+ id: row.id, name: row.name || row.id, description: row.description ?? '',
398
+ editable: row.trust === 'user', isDefault: row.id === this.agentPresets.defaultId,
399
+ })), authorable: this.agentPresets.authorable ?? false, excludedCount: rows.filter(row => row.broken !== undefined).length };
400
+ }
401
+ const roster = await this.agentPresets.remoteExportList();
402
+ // Listing must not read/resolve every composition: each host read rescans roots.
403
+ const presets = roster.presets.filter(row => row.broken === undefined).map(row => ({
404
+ id: row.id, name: row.name || row.id, description: row.description ?? '',
405
+ editable: row.trust === 'user', isDefault: row.isDefault,
406
+ }));
407
+ return { presets, authorable: roster.authorable, excludedCount: roster.presets.length - presets.length };
408
+ }
409
+ async read(id) {
410
+ // The catalog owns path discovery. Re-read the selected files on every cache
411
+ // miss, and rebuild paths on Refresh; elapsed time must not trigger a full scan.
412
+ const cached = this.indexed?.get(id);
413
+ const preset = cached ?? await this.preset(id);
414
+ if (preset.broken !== undefined)
415
+ throw new Error('invalid-preset');
416
+ const [composition, metadata] = await Promise.all([readFile(preset.path, 'utf8'), optionalFile(resolve(dirname(preset.path), 'preset.yml'))]);
417
+ const meta = metadata ? yaml(metadata) : undefined;
418
+ validateComposition(composition);
419
+ const codex = supportsCodex(composition);
420
+ const prompt = codex ? explicitPrompt(composition) : undefined;
421
+ const shared = this.sharedSettings?.() ?? {};
422
+ const promptSections = readPromptSections(composition, shared);
423
+ for (const field of promptFields(yaml(composition))) {
424
+ const reference = promptFile(field.node);
425
+ if (!reference)
426
+ continue;
427
+ const section = promptSections.find(section => section.id === field.id);
428
+ try {
429
+ const root = await realpath(dirname(preset.path));
430
+ const target = await realpath(resolve(root, reference));
431
+ const rel = relative(root, target);
432
+ if (isAbsolute(rel) || rel === '..' || rel.startsWith('../') || rel.startsWith('..\\'))
433
+ continue;
434
+ if ((await stat(target)).size > 1_000_000)
435
+ continue;
436
+ section.text = await readFile(target, 'utf8');
437
+ section.editable = true;
438
+ }
439
+ catch { /* Unavailable references remain visible and read-only, with their expression intact. */ }
440
+ }
441
+ return { id, name: String(meta?.get('name') ?? id), description: String(meta?.get('description') ?? ''),
442
+ systemPrompt: prompt ?? shared.systemPrompt ?? DEFAULT_CODEX_SYSTEM_PROMPT, inheritPrompt: prompt === undefined,
443
+ revision: revision(composition, metadata), editable: preset.trust === 'user', codex,
444
+ codexOptions: readCodexPresetOptions(composition), composition, promptSections };
445
+ }
446
+ async create(rawInput) {
447
+ const input = validate(rawInput);
448
+ await this.preset(input.sourceId);
449
+ const id = `codex-${randomUUID().slice(0, 12)}`;
450
+ await this.agentPresets.copy(input.sourceId, id, input.name);
451
+ try {
452
+ const copy = await this.read(id);
453
+ const base = input.composition ?? copy.composition;
454
+ const composition = input.enableCodex ? enhanceComposition(base) : base;
455
+ let next = composition;
456
+ if (supportsCodex(next)) {
457
+ next = patchPresetComposition(next, input.systemPrompt, input.inheritPrompt);
458
+ next = patchCodexPresetOptions(next, input.codexOptions ?? {});
459
+ }
460
+ return await this.update({ ...input, id, revision: copy.revision, composition: next });
461
+ }
462
+ catch (error) {
463
+ // Only the copy created by this operation is rolled back.
464
+ await this.agentPresets.remove(id);
465
+ throw error;
466
+ }
467
+ }
468
+ async update(rawInput) {
469
+ const input = validate(rawInput);
470
+ const preset = await this.preset(input.id);
471
+ if (preset.trust !== 'user')
472
+ throw new Error('built-in presets cannot be edited here');
473
+ const composition = resolve(preset.path);
474
+ if (composition.split(/[\\/]/).at(-1) !== 'agent.cordis.yml')
475
+ throw new Error('invalid-preset-path');
476
+ await assertWithinRoot(composition, this.agentPresets.roots);
477
+ const metadata = resolve(dirname(composition), 'preset.yml');
478
+ if (await optionalFile(metadata) !== undefined)
479
+ await assertWithinRoot(metadata, this.agentPresets.roots);
480
+ const { withFileLock, writeFileAtomic } = await loadAtomicWrite();
481
+ return withFileLock(composition, async () => {
482
+ const oldComposition = await readFile(composition, 'utf8');
483
+ const oldMetadata = await optionalFile(metadata);
484
+ if (input.revision !== undefined && input.revision !== revision(oldComposition, oldMetadata))
485
+ throw new Error('preset-conflict');
486
+ const editedComposition = input.composition !== undefined ? input.composition : oldComposition;
487
+ let nextComposition = input.enableCodex && !supportsCodex(editedComposition)
488
+ ? enhanceComposition(editedComposition) : editedComposition;
489
+ if (supportsCodex(nextComposition)) {
490
+ nextComposition = patchPresetComposition(nextComposition, input.systemPrompt, input.inheritPrompt);
491
+ if (input.codexOptions !== undefined)
492
+ nextComposition = patchCodexPresetOptions(nextComposition, input.codexOptions);
493
+ }
494
+ if (input.promptSections)
495
+ nextComposition = patchPromptSections(nextComposition, input.promptSections);
496
+ validateComposition(nextComposition);
497
+ const nextMetadata = patchPresetMetadata(oldMetadata ?? '', input.name, input.description);
498
+ const compositionMode = await mode(composition);
499
+ const metadataMode = await mode(metadata);
500
+ await writeFileAtomic(resolve(dirname(composition), '.codex-editor-backup.json'), JSON.stringify({ composition: oldComposition, metadata: oldMetadata ?? null }), { mode: 0o600, dirMode: 0o700 });
501
+ try {
502
+ await writeFileAtomic(composition, nextComposition, { mode: compositionMode, dirMode: 0o700 });
503
+ await writeFileAtomic(metadata, nextMetadata, { mode: metadataMode, dirMode: 0o700 });
504
+ const result = await this.agentPresets.resolve(input.id);
505
+ if (result.broken !== undefined)
506
+ throw new Error('invalid-preset-after-save');
507
+ this.indexed?.set(input.id, result);
508
+ return await this.read(input.id);
509
+ }
510
+ catch (error) {
511
+ await writeFileAtomic(composition, oldComposition, { mode: compositionMode, dirMode: 0o700 });
512
+ if (oldMetadata !== undefined)
513
+ await writeFileAtomic(metadata, oldMetadata, { mode: metadataMode, dirMode: 0o700 });
514
+ else
515
+ await unlink(metadata).catch(cause => { if (cause.code !== 'ENOENT')
516
+ throw cause; });
517
+ throw error;
518
+ }
519
+ }, { waitMs: 10_000 });
520
+ }
521
+ async preset(id) {
522
+ if (!PRESET_ID.test(id))
523
+ throw new Error('invalid-preset-id');
524
+ const preset = await this.agentPresets.resolve(id);
525
+ if (preset.broken !== undefined)
526
+ throw new Error('invalid-preset');
527
+ this.indexed ??= new Map();
528
+ this.indexed.set(id, preset);
529
+ return preset;
530
+ }
531
+ }
532
+ // Same decorator registration as the host, consumable by the Vitest transform.
533
+ function markRemoteMethod(methodName) {
534
+ const descriptor = Object.getOwnPropertyDescriptor(CodexPresetEditor.prototype, methodName);
535
+ const initializers = [];
536
+ const decorator = Remote(methodName);
537
+ decorator(descriptor.value, { kind: 'method', name: methodName, static: false, private: false,
538
+ addInitializer: initializer => { initializers.push(initializer); } });
539
+ const receiver = Object.create(CodexPresetEditor.prototype);
540
+ for (const initializer of initializers)
541
+ initializer.call(receiver);
542
+ }
543
+ for (const method of ['read', 'update', 'catalog', 'create'])
544
+ markRemoteMethod(method);
545
+ export default CodexPresetEditor;
546
+ //# sourceMappingURL=preset-editor.js.map
@@ -0,0 +1,36 @@
1
+ /** Extend this registry to add task-specific starting instructions without new UI branches. */
2
+ export declare const PRESET_TEMPLATES: readonly [{
3
+ readonly id: "general";
4
+ readonly label: "pmGeneral";
5
+ readonly description: "pmGeneralDesc";
6
+ readonly inheritPrompt: true;
7
+ readonly prompt: string;
8
+ }, {
9
+ readonly id: "review";
10
+ readonly label: "pmReview";
11
+ readonly description: "pmReviewDesc";
12
+ readonly inheritPrompt: false;
13
+ readonly prompt: `${string}
14
+
15
+ # Code review workflow
16
+ Review the requested changes for concrete correctness defects, regressions, and missing tests. Cite the affected code and a reproducible scenario. Prioritize findings by impact. Do not change files unless the user asks for a fix. If no actionable findings are found, say so and state any testing gaps.`;
17
+ }, {
18
+ readonly id: "debug";
19
+ readonly label: "pmDebug";
20
+ readonly description: "pmDebugDesc";
21
+ readonly inheritPrompt: false;
22
+ readonly prompt: `${string}
23
+
24
+ # Debugging workflow
25
+ Start from a reproducible symptom and preserve evidence. Form a narrow hypothesis, test it, and fix the root cause with the smallest correct change. Verify the original failure and relevant regressions. Report what was confirmed, what changed, and any remaining uncertainty.`;
26
+ }, {
27
+ readonly id: "docs";
28
+ readonly label: "pmDocs";
29
+ readonly description: "pmDocsDesc";
30
+ readonly inheritPrompt: false;
31
+ readonly prompt: `${string}
32
+
33
+ # Documentation workflow
34
+ Check the current source and supported interfaces before writing. Explain the reader's goal, prerequisites, and a working example. Keep commands and paths accurate. Do not invent features or guarantees. Keep documentation changes focused and verify examples where practical.`;
35
+ }];
36
+ //# sourceMappingURL=preset-templates.d.ts.map
@@ -0,0 +1,12 @@
1
+ import { DEFAULT_CODEX_SYSTEM_PROMPT } from "./prompt.js";
2
+ /** Extend this registry to add task-specific starting instructions without new UI branches. */
3
+ export const PRESET_TEMPLATES = [
4
+ { id: 'general', label: 'pmGeneral', description: 'pmGeneralDesc', inheritPrompt: true, prompt: DEFAULT_CODEX_SYSTEM_PROMPT },
5
+ { id: 'review', label: 'pmReview', description: 'pmReviewDesc', inheritPrompt: false,
6
+ prompt: `${DEFAULT_CODEX_SYSTEM_PROMPT}\n\n# Code review workflow\nReview the requested changes for concrete correctness defects, regressions, and missing tests. Cite the affected code and a reproducible scenario. Prioritize findings by impact. Do not change files unless the user asks for a fix. If no actionable findings are found, say so and state any testing gaps.` },
7
+ { id: 'debug', label: 'pmDebug', description: 'pmDebugDesc', inheritPrompt: false,
8
+ prompt: `${DEFAULT_CODEX_SYSTEM_PROMPT}\n\n# Debugging workflow\nStart from a reproducible symptom and preserve evidence. Form a narrow hypothesis, test it, and fix the root cause with the smallest correct change. Verify the original failure and relevant regressions. Report what was confirmed, what changed, and any remaining uncertainty.` },
9
+ { id: 'docs', label: 'pmDocs', description: 'pmDocsDesc', inheritPrompt: false,
10
+ prompt: `${DEFAULT_CODEX_SYSTEM_PROMPT}\n\n# Documentation workflow\nCheck the current source and supported interfaces before writing. Explain the reader's goal, prerequisites, and a working example. Keep commands and paths accurate. Do not invent features or guarantees. Keep documentation changes focused and verify examples where practical.` },
11
+ ];
12
+ //# sourceMappingURL=preset-templates.js.map