@shuind/dsh-codex-harness 0.2.14 → 0.2.16

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.
@@ -30,6 +30,15 @@ export interface Config {
30
30
  remoteCompact?: boolean;
31
31
  /** Complete plugin-owned Codex operating prompt. */
32
32
  systemPrompt?: string;
33
+ /** Explicit per-preset operating prompt; overrides the shared prompt only. */
34
+ presetPrompt?: string;
35
+ /** Per-preset Codex capability overrides. Omitted values follow shared settings. */
36
+ promptEnabled?: boolean;
37
+ terminalToolsEnabled?: boolean;
38
+ patchToolEnabled?: boolean;
39
+ planToolEnabled?: boolean;
40
+ hostedWebSearchEnabled?: boolean;
41
+ remoteCompactionEnabled?: boolean;
33
42
  /** Deployment Persona template. */
34
43
  persona?: string;
35
44
  /** DSH Core source-checkout guidance template. */
@@ -71,6 +80,8 @@ export declare function normalizeCodexPromptAssembly(assembly: PromptAssembly):
71
80
  export declare function applyCodexCapabilitySettings(assembly: PromptAssembly, settings: CodexSettings): PromptAssembly;
72
81
  /** Build the complete plugin-owned prompt, preserving an intentional empty value. */
73
82
  export declare function buildCodexSystemPrompt(config?: Pick<Config, 'systemPrompt'>): string;
83
+ /** Explicit preset instructions win without changing shared tools or permissions. */
84
+ export declare function withPresetPrompt(settings: CodexSettings, presetPrompt: string | undefined): CodexSettings;
74
85
  /** Mount the Codex prompt/tool layer inside one fixed agent preset. */
75
86
  export declare function apply(ctx: Context, config?: Config): void;
76
87
  declare const _default: {
@@ -8,11 +8,30 @@ import { registerCodexActivityProjection } from "./activity.js";
8
8
  import { DEFAULT_CODEX_PERSONA, DEFAULT_CODEX_SYSTEM_PROMPT, DEFAULT_DSH_CORE_SOURCE_PROMPT, DEFAULT_DSH_CORE_WEB_PROMPT, resolveCodexSystemPrompt, } from "./prompt.js";
9
9
  import { CODEX_SETTINGS_ENTRY, CODEX_SETTINGS_NAMESPACE, CODEX_SETTINGS_SCHEMA, } from "./settings.js";
10
10
  import { codexCompactionMode } from "./compaction.js";
11
+ import { CodexPresetEditor } from "./preset-editor.js";
11
12
  export { DEFAULT_CODEX_PERSONA, DEFAULT_CODEX_SYSTEM_PROMPT, DEFAULT_DSH_CORE_SOURCE_PROMPT, DEFAULT_DSH_CORE_WEB_PROMPT, } from "./prompt.js";
12
13
  export { CODEX_SETTINGS_NAMESPACE, CODEX_SETTINGS_SCHEMA } from "./settings.js";
13
14
  export const name = 'codex';
14
15
  export const inject = ['tools', 'systemPrompt', 'shell', 'fs', 'llm', 'credentials', 'settings'];
15
16
  const DEFAULT_MAX_OUTPUT_BYTES = 1024 * 1024;
17
+ /** Add the preset editor when DSH's optional user-preset service is available. */
18
+ function installPresetEditor(ctx) {
19
+ // `agentPresets` is supplied by dsh-agent-presets and may be installed after
20
+ // this plugin. Waiting through inject keeps the Codex core usable on hosts
21
+ // without that optional service while still mounting the Remote as soon as
22
+ // the Web preset catalog becomes available.
23
+ ctx.inject(['agentPresets'], presetCtx => {
24
+ void (async () => {
25
+ try {
26
+ await presetCtx.plugin(CodexPresetEditor);
27
+ }
28
+ catch (error) {
29
+ ctx.logger.warn('codex: preset editor is unavailable on this host');
30
+ ctx.logger.warn(error);
31
+ }
32
+ })();
33
+ });
34
+ }
16
35
  /** Runtime configuration schema for the Codex tool bridge. */
17
36
  export const Config = z.object({
18
37
  globalEnhancements: z.boolean().default(true),
@@ -24,6 +43,13 @@ export const Config = z.object({
24
43
  hostedWebSearch: z.boolean().default(true),
25
44
  remoteCompact: z.boolean().default(true),
26
45
  systemPrompt: z.string().default(DEFAULT_CODEX_SYSTEM_PROMPT),
46
+ presetPrompt: z.string(),
47
+ promptEnabled: z.boolean(),
48
+ terminalToolsEnabled: z.boolean(),
49
+ patchToolEnabled: z.boolean(),
50
+ planToolEnabled: z.boolean(),
51
+ hostedWebSearchEnabled: z.boolean(),
52
+ remoteCompactionEnabled: z.boolean(),
27
53
  persona: z.string().default(DEFAULT_CODEX_PERSONA),
28
54
  harnessSourcePrompt: z.string().default(DEFAULT_DSH_CORE_SOURCE_PROMPT),
29
55
  webSurfacePrompt: z.string().default(DEFAULT_DSH_CORE_WEB_PROMPT),
@@ -612,8 +638,13 @@ function registerPlanTool(ctx, currentSettings) {
612
638
  },
613
639
  }));
614
640
  }
641
+ /** Explicit preset instructions win without changing shared tools or permissions. */
642
+ export function withPresetPrompt(settings, presetPrompt) {
643
+ return presetPrompt === undefined ? settings : { ...settings, systemPrompt: presetPrompt };
644
+ }
615
645
  /** Mount the Codex prompt/tool layer inside one fixed agent preset. */
616
646
  export function apply(ctx, config = {}) {
647
+ installPresetEditor(ctx);
617
648
  const resolved = {
618
649
  globalEnhancements: config.globalEnhancements ?? true,
619
650
  codexCore: config.codexCore ?? true,
@@ -633,7 +664,19 @@ export function apply(ctx, config = {}) {
633
664
  && ctx.get('sandboxPolicy') === undefined) {
634
665
  throw new Error('codex: a sandboxing filesystem requires ctx.sandboxPolicy');
635
666
  }
636
- const codexSettings = installCodexSettings(ctx, resolved.systemPrompt, resolved.persona, resolved.harnessSourcePrompt, resolved.webSurfacePrompt);
667
+ const sharedSettings = installCodexSettings(ctx, resolved.systemPrompt, resolved.persona, resolved.harnessSourcePrompt, resolved.webSurfacePrompt);
668
+ const codexSettings = { current: () => {
669
+ const shared = withPresetPrompt(sharedSettings.current(), config.presetPrompt);
670
+ return {
671
+ ...shared,
672
+ ...(config.promptEnabled === undefined ? {} : { promptEnabled: config.promptEnabled }),
673
+ ...(config.terminalToolsEnabled === undefined ? {} : { terminalToolsEnabled: config.terminalToolsEnabled }),
674
+ ...(config.patchToolEnabled === undefined ? {} : { patchToolEnabled: config.patchToolEnabled }),
675
+ ...(config.planToolEnabled === undefined ? {} : { planToolEnabled: config.planToolEnabled }),
676
+ ...(config.hostedWebSearchEnabled === undefined ? {} : { hostedWebSearchEnabled: config.hostedWebSearchEnabled }),
677
+ ...(config.remoteCompactionEnabled === undefined ? {} : { remoteCompactionEnabled: config.remoteCompactionEnabled }),
678
+ };
679
+ } };
637
680
  const execConfig = { ...resolved, currentSettings: codexSettings.current };
638
681
  if (resolved.globalEnhancements) {
639
682
  // The generic pi-ai plugin remains the owner of provider routes. This
@@ -0,0 +1,58 @@
1
+ /** Client-safe, versioned preset authoring contract. No filesystem or runtime imports. */
2
+ export interface PresetFields {
3
+ name: string;
4
+ description: string;
5
+ systemPrompt: string;
6
+ inheritPrompt: boolean;
7
+ }
8
+ /** Codex capabilities stored with a preset. Activity status stays global. */
9
+ export interface CodexPresetOptions {
10
+ promptEnabled: boolean;
11
+ terminalToolsEnabled: boolean;
12
+ patchToolEnabled: boolean;
13
+ planToolEnabled: boolean;
14
+ hostedWebSearchEnabled: boolean;
15
+ remoteCompactionEnabled: boolean;
16
+ }
17
+ export interface PresetEditorDocument extends PresetFields {
18
+ id: string;
19
+ revision: string;
20
+ editable: boolean;
21
+ codex: boolean;
22
+ codexOptions: CodexPresetOptions;
23
+ composition: string;
24
+ }
25
+ export interface PresetEditorInput extends PresetFields {
26
+ id: string;
27
+ revision?: string;
28
+ composition?: string;
29
+ enableCodex?: boolean;
30
+ codexOptions?: Partial<CodexPresetOptions>;
31
+ }
32
+ export interface PresetCreateInput extends PresetFields {
33
+ sourceId: string;
34
+ enableCodex?: boolean;
35
+ composition?: string;
36
+ codexOptions?: Partial<CodexPresetOptions>;
37
+ }
38
+ export interface PresetCatalogRow {
39
+ id: string;
40
+ name: string;
41
+ description: string;
42
+ editable: boolean;
43
+ isDefault: boolean;
44
+ codex?: boolean;
45
+ }
46
+ export interface PresetCatalog {
47
+ presets: PresetCatalogRow[];
48
+ authorable: boolean;
49
+ excludedCount: number;
50
+ }
51
+ /** A portable instruction card, deliberately not executable YAML or a tool bundle. */
52
+ export interface PromptCard extends PresetFields {
53
+ format: 'codex-harness/prompt-card';
54
+ version: 1;
55
+ }
56
+ export declare function parsePromptCard(text: string): PromptCard;
57
+ export declare function exportPromptCard(fields: PresetFields): string;
58
+ //# sourceMappingURL=preset-contract.d.ts.map
@@ -0,0 +1,22 @@
1
+ export function parsePromptCard(text) {
2
+ if (text.length > 1_100_000)
3
+ throw new Error('invalid-prompt-card');
4
+ const value = JSON.parse(text);
5
+ if (!value || typeof value !== 'object')
6
+ throw new Error('invalid-prompt-card');
7
+ const card = value;
8
+ if (card.format !== 'codex-harness/prompt-card' || card.version !== 1
9
+ || typeof card.name !== 'string' || !card.name.trim() || card.name.length > 200
10
+ || typeof card.description !== 'string' || card.description.length > 4000
11
+ || typeof card.systemPrompt !== 'string' || card.systemPrompt.length > 1_000_000
12
+ || typeof card.inheritPrompt !== 'boolean')
13
+ throw new Error('invalid-prompt-card');
14
+ return { format: card.format, version: 1, name: card.name, description: card.description,
15
+ systemPrompt: card.systemPrompt, inheritPrompt: card.inheritPrompt };
16
+ }
17
+ export function exportPromptCard(fields) {
18
+ return JSON.stringify({ format: 'codex-harness/prompt-card', version: 1,
19
+ name: fields.name, description: fields.description, systemPrompt: fields.systemPrompt,
20
+ inheritPrompt: fields.inheritPrompt }, null, 2);
21
+ }
22
+ //# sourceMappingURL=preset-contract.js.map
@@ -0,0 +1,30 @@
1
+ import { z } from 'zod';
2
+ declare const _default: {
3
+ package: string;
4
+ descriptors: {
5
+ id: string;
6
+ service: string;
7
+ namespace: string;
8
+ method: string;
9
+ invocation: {
10
+ kind: "direct";
11
+ };
12
+ parameters: {
13
+ name: string;
14
+ wire: string;
15
+ source: "json";
16
+ codec: {
17
+ mode: "strict";
18
+ typeSymbol: string;
19
+ schema: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
20
+ };
21
+ }[];
22
+ result: {
23
+ mode: "strict";
24
+ typeSymbol: string;
25
+ schema: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
26
+ };
27
+ }[];
28
+ };
29
+ export default _default;
30
+ //# sourceMappingURL=preset-editor-remote.d.ts.map
@@ -0,0 +1,36 @@
1
+ import { z } from 'zod';
2
+ const fields = {
3
+ name: z.string().max(200), description: z.string().max(4000),
4
+ systemPrompt: z.string().max(1_000_000), inheritPrompt: z.boolean(),
5
+ };
6
+ const codexOptions = z.object({
7
+ promptEnabled: z.boolean(), terminalToolsEnabled: z.boolean(), patchToolEnabled: z.boolean(),
8
+ planToolEnabled: z.boolean(), hostedWebSearchEnabled: z.boolean(), remoteCompactionEnabled: z.boolean(),
9
+ });
10
+ const codexOptionsPatch = codexOptions.partial();
11
+ const document = z.object({ ...fields, id: z.string(), revision: z.string(), editable: z.boolean(), codex: z.boolean(), codexOptions, composition: z.string() });
12
+ const catalog = z.object({
13
+ presets: z.array(z.object({ id: z.string(), name: z.string(), description: z.string(),
14
+ editable: z.boolean(), isDefault: z.boolean() })),
15
+ authorable: z.boolean(), excludedCount: z.number(),
16
+ });
17
+ function descriptor(method, parameter, input, output) {
18
+ const id = `@shuind/dsh-codex-harness#codexPresetEditor/${method}`;
19
+ return {
20
+ id, service: 'codexPresetEditor', namespace: 'codexPresetEditor', method,
21
+ invocation: { kind: 'direct' },
22
+ parameters: parameter ? [{ name: parameter, wire: parameter, source: 'json',
23
+ codec: { mode: 'strict', typeSymbol: `${id}:${parameter}`, schema: input } }] : [],
24
+ result: { mode: 'strict', typeSymbol: `${id}:result`, schema: output },
25
+ };
26
+ }
27
+ export default {
28
+ package: '@shuind/dsh-codex-harness',
29
+ descriptors: [
30
+ descriptor('catalog', undefined, z.unknown(), catalog),
31
+ descriptor('read', 'id', z.string(), document),
32
+ descriptor('update', 'rawInput', z.object({ ...fields, id: z.string(), revision: z.string().optional(), composition: z.string().max(1_000_000).optional(), enableCodex: z.boolean().optional(), codexOptions: codexOptionsPatch.optional() }), document),
33
+ descriptor('create', 'rawInput', z.object({ ...fields, sourceId: z.string(), enableCodex: z.boolean().optional(), composition: z.string().max(1_000_000).optional(), codexOptions: codexOptionsPatch.optional() }), document),
34
+ ],
35
+ };
36
+ //# sourceMappingURL=preset-editor-remote.js.map
@@ -0,0 +1,58 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import { TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol';
3
+ import type { CodexPresetOptions, PresetCatalog, PresetCreateInput, PresetEditorInput, PresetEditorDocument } from './preset-contract.ts';
4
+ export type { PresetEditorInput, PresetEditorDocument } from './preset-contract.ts';
5
+ export declare const DEFAULT_CODEX_PRESET_OPTIONS: CodexPresetOptions;
6
+ export interface ResolvedPresetForEditor {
7
+ id: string;
8
+ trust: 'system' | 'user';
9
+ path: string;
10
+ broken?: string;
11
+ }
12
+ export interface AgentPresetsForEditor {
13
+ resolve(id: string): Promise<ResolvedPresetForEditor>;
14
+ readDocument(id: string): Promise<{
15
+ content: string;
16
+ name?: string;
17
+ description?: string;
18
+ }>;
19
+ remoteExportList(): Promise<{
20
+ presets: Array<{
21
+ id: string;
22
+ name?: string;
23
+ description?: string;
24
+ trust: 'system' | 'user';
25
+ isDefault: boolean;
26
+ broken?: string;
27
+ }>;
28
+ authorable: boolean;
29
+ }>;
30
+ copy(from: string, id: string, name?: string): Promise<void>;
31
+ remove(id: string): Promise<void>;
32
+ readonly roots?: readonly {
33
+ path: string;
34
+ trust: 'system' | 'user';
35
+ }[];
36
+ }
37
+ export declare function readCodexPresetOptions(content: string): CodexPresetOptions;
38
+ export declare function supportsCodex(content: string): boolean;
39
+ /** Structural validation only: executable tags stay inert until DSH mounts a selected preset. */
40
+ export declare function validateComposition(content: string): void;
41
+ export declare function enhanceComposition(content: string): string;
42
+ export declare function readPresetSystemPrompt(content: string): string;
43
+ export declare function patchPresetComposition(content: string, prompt: string, inherit?: boolean): string;
44
+ /** Store user-facing Codex capability switches in the Harness row. */
45
+ export declare function patchCodexPresetOptions(content: string, options: Partial<CodexPresetOptions>): string;
46
+ export declare function patchPresetMetadata(content: string, name: string, description: string): string;
47
+ export declare class CodexPresetEditor extends TypertRemoteService {
48
+ static inject: string[];
49
+ private readonly agentPresets;
50
+ constructor(ctx: Context, _config?: undefined);
51
+ catalog(): Promise<PresetCatalog>;
52
+ read(id: string): Promise<PresetEditorDocument>;
53
+ create(rawInput: PresetCreateInput): Promise<PresetEditorDocument>;
54
+ update(rawInput: PresetEditorInput): Promise<PresetEditorDocument>;
55
+ private preset;
56
+ }
57
+ export default CodexPresetEditor;
58
+ //# sourceMappingURL=preset-editor.d.ts.map
@@ -0,0 +1,332 @@
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_SYSTEM_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
+ export function readCodexPresetOptions(content) {
57
+ try {
58
+ const { config } = harnessConfig(content);
59
+ const options = { ...DEFAULT_CODEX_PRESET_OPTIONS };
60
+ for (const key of CODEX_OPTION_KEYS) {
61
+ const value = config.get(key);
62
+ if (typeof value === 'boolean')
63
+ options[key] = value;
64
+ }
65
+ return options;
66
+ }
67
+ catch {
68
+ return { ...DEFAULT_CODEX_PRESET_OPTIONS };
69
+ }
70
+ }
71
+ export function supportsCodex(content) {
72
+ try {
73
+ harnessConfig(content);
74
+ return true;
75
+ }
76
+ catch {
77
+ return false;
78
+ }
79
+ }
80
+ /** Structural validation only: executable tags stay inert until DSH mounts a selected preset. */
81
+ export function validateComposition(content) {
82
+ if (content.length > 1_000_000)
83
+ throw new Error('invalid-preset-yaml');
84
+ const doc = yaml(content);
85
+ if (!isSeq(doc.contents) || !doc.contents.items.length)
86
+ throw new Error('invalid-preset-yaml');
87
+ const ids = new Set();
88
+ for (const entry of doc.contents.items) {
89
+ if (!isMap(entry))
90
+ throw new Error('invalid-preset-yaml');
91
+ const row = entry;
92
+ if (typeof row.get('name') !== 'string')
93
+ throw new Error('invalid-preset-yaml');
94
+ const id = row.get('id');
95
+ if (typeof id !== 'string' || ids.has(id))
96
+ throw new Error('invalid-preset-yaml');
97
+ ids.add(id);
98
+ }
99
+ }
100
+ export function enhanceComposition(content) {
101
+ validateComposition(content);
102
+ if (supportsCodex(content))
103
+ return content;
104
+ // A disabled/ambiguous Harness row needs explicit advanced editing, not a second instance.
105
+ const doc = yaml(content);
106
+ if (!isSeq(doc.contents))
107
+ throw new Error('invalid-preset-yaml');
108
+ if (doc.contents.items.some(row => isMap(row) && row.get('name') === '@shuind/dsh-codex-harness'))
109
+ throw new Error('ambiguous-harness-row');
110
+ // A complete persona suppresses all contributed sections, including Codex's.
111
+ // Keep its identity text while allowing the enhanced copy to compose prompts.
112
+ for (const row of doc.contents.items) {
113
+ if (!isMap(row) || row.get('name') !== '@deepseek-ai/dsh-persona')
114
+ continue;
115
+ const persona = row.get('config', true);
116
+ if (isMap(persona) && persona.get('complete') === true)
117
+ persona.set('complete', false);
118
+ }
119
+ doc.add(doc.createNode({ id: `codex-harness-${randomUUID().slice(0, 8)}`,
120
+ name: '@shuind/dsh-codex-harness', config: { globalEnhancements: false, codexCore: true } }));
121
+ return doc.toString({ lineWidth: 0 });
122
+ }
123
+ export function readPresetSystemPrompt(content) {
124
+ return explicitPrompt(content) ?? DEFAULT_CODEX_SYSTEM_PROMPT;
125
+ }
126
+ export function patchPresetComposition(content, prompt, inherit = false) {
127
+ const { doc, config } = harnessConfig(content);
128
+ // Migrate the old field, avoiding two competing prompt sources.
129
+ config.delete('systemPrompt');
130
+ if (inherit)
131
+ config.delete('presetPrompt');
132
+ else {
133
+ const node = new Scalar(prompt);
134
+ node.type = prompt.includes('\n') ? Scalar.BLOCK_LITERAL : Scalar.QUOTE_DOUBLE;
135
+ config.set('presetPrompt', node);
136
+ }
137
+ return doc.toString({ lineWidth: 0 });
138
+ }
139
+ /** Store user-facing Codex capability switches in the Harness row. */
140
+ export function patchCodexPresetOptions(content, options) {
141
+ const { doc, config } = harnessConfig(content);
142
+ for (const key of CODEX_OPTION_KEYS) {
143
+ const value = options[key];
144
+ if (value !== undefined)
145
+ config.set(key, value);
146
+ }
147
+ return doc.toString({ lineWidth: 0 });
148
+ }
149
+ export function patchPresetMetadata(content, name, description) {
150
+ const doc = yaml(content);
151
+ if (doc.contents !== null && !isMap(doc.contents))
152
+ throw new Error('invalid-preset-metadata');
153
+ for (const [key, value] of Object.entries({ name, description })) {
154
+ const node = new Scalar(value);
155
+ node.type = Scalar.QUOTE_DOUBLE;
156
+ doc.set(key, node);
157
+ }
158
+ return doc.toString({ lineWidth: 0 });
159
+ }
160
+ function validate(input) {
161
+ if (typeof input.name !== 'string' || !input.name.trim() || /[\r\n]/.test(input.name) || input.name.length > 200)
162
+ throw new Error('invalid-preset-name');
163
+ if (typeof input.description !== 'string' || input.description.length > 4000)
164
+ throw new Error('invalid-preset-description');
165
+ if (typeof input.systemPrompt !== 'string' || input.systemPrompt.length > 1_000_000)
166
+ throw new Error('invalid-preset-prompt');
167
+ return { ...input, name: input.name.trim() };
168
+ }
169
+ function revision(composition, metadata) {
170
+ return createHash('sha256').update(composition).update('\0').update(metadata ?? '').digest('hex');
171
+ }
172
+ async function optionalFile(path) {
173
+ try {
174
+ return await readFile(path, 'utf8');
175
+ }
176
+ catch (error) {
177
+ if (error.code === 'ENOENT')
178
+ return undefined;
179
+ throw error;
180
+ }
181
+ }
182
+ async function mode(path) {
183
+ try {
184
+ return (await stat(path)).mode & 0o777;
185
+ }
186
+ catch {
187
+ return 0o600;
188
+ }
189
+ }
190
+ async function assertWithinRoot(path, roots) {
191
+ if (!roots?.length)
192
+ throw new Error('preset-root-unavailable');
193
+ const target = await realpath(path);
194
+ for (const root of roots) {
195
+ if (root.trust !== 'user')
196
+ continue;
197
+ const home = process.env.DSH_HOME ?? process.env.USERPROFILE ?? process.env.HOME ?? '';
198
+ const expanded = root.path.replace(/^~(?=[\\/]|$)/, home);
199
+ try {
200
+ const rel = relative(await realpath(resolve(expanded)), target);
201
+ if (!isAbsolute(rel) && rel !== '..' && !rel.startsWith('../') && !rel.startsWith('..\\'))
202
+ return;
203
+ }
204
+ catch { /* An absent root cannot own this path. */ }
205
+ }
206
+ throw new Error('preset-outside-user-root');
207
+ }
208
+ export class CodexPresetEditor extends TypertRemoteService {
209
+ static inject = ['agentPresets'];
210
+ agentPresets;
211
+ constructor(ctx, _config) {
212
+ super(ctx, 'codexPresetEditor');
213
+ this.agentPresets = ctx.get('agentPresets');
214
+ }
215
+ async catalog() {
216
+ const roster = await this.agentPresets.remoteExportList();
217
+ // Listing must not read/resolve every composition: each host read rescans roots.
218
+ const presets = roster.presets.filter(row => row.broken === undefined).map(row => ({
219
+ id: row.id, name: row.name || row.id, description: row.description ?? '',
220
+ editable: row.trust === 'user', isDefault: row.isDefault,
221
+ }));
222
+ return { presets, authorable: roster.authorable, excludedCount: roster.presets.length - presets.length };
223
+ }
224
+ async read(id) {
225
+ const preset = await this.preset(id);
226
+ const composition = await readFile(preset.path, 'utf8');
227
+ const metadata = await optionalFile(resolve(dirname(preset.path), 'preset.yml'));
228
+ const meta = metadata ? yaml(metadata) : undefined;
229
+ validateComposition(composition);
230
+ const codex = supportsCodex(composition);
231
+ const prompt = codex ? explicitPrompt(composition) : undefined;
232
+ return { id, name: String(meta?.get('name') ?? id), description: String(meta?.get('description') ?? ''),
233
+ systemPrompt: prompt ?? DEFAULT_CODEX_SYSTEM_PROMPT, inheritPrompt: prompt === undefined,
234
+ revision: revision(composition, metadata), editable: preset.trust === 'user', codex,
235
+ codexOptions: readCodexPresetOptions(composition), composition };
236
+ }
237
+ async create(rawInput) {
238
+ const input = validate(rawInput);
239
+ await this.preset(input.sourceId);
240
+ const id = `codex-${randomUUID().slice(0, 12)}`;
241
+ await this.agentPresets.copy(input.sourceId, id, input.name);
242
+ try {
243
+ const copy = await this.read(id);
244
+ const base = input.composition ?? copy.composition;
245
+ const composition = input.enableCodex ? enhanceComposition(base) : base;
246
+ let next = composition;
247
+ if (supportsCodex(next)) {
248
+ next = patchPresetComposition(next, input.systemPrompt, input.inheritPrompt);
249
+ next = patchCodexPresetOptions(next, input.codexOptions ?? {});
250
+ }
251
+ return await this.update({ ...input, id, revision: copy.revision, composition: next });
252
+ }
253
+ catch (error) {
254
+ // Only the copy created by this operation is rolled back.
255
+ await this.agentPresets.remove(id);
256
+ throw error;
257
+ }
258
+ }
259
+ async update(rawInput) {
260
+ const input = validate(rawInput);
261
+ const preset = await this.preset(input.id);
262
+ if (preset.trust !== 'user')
263
+ throw new Error('built-in presets cannot be edited here');
264
+ const composition = resolve(preset.path);
265
+ if (composition.split(/[\\/]/).at(-1) !== 'agent.cordis.yml')
266
+ throw new Error('invalid-preset-path');
267
+ await assertWithinRoot(composition, this.agentPresets.roots);
268
+ const metadata = resolve(dirname(composition), 'preset.yml');
269
+ if (await optionalFile(metadata) !== undefined)
270
+ await assertWithinRoot(metadata, this.agentPresets.roots);
271
+ const { withFileLock, writeFileAtomic } = await loadAtomicWrite();
272
+ return withFileLock(composition, async () => {
273
+ const oldComposition = await readFile(composition, 'utf8');
274
+ const oldMetadata = await optionalFile(metadata);
275
+ if (input.revision !== undefined && input.revision !== revision(oldComposition, oldMetadata))
276
+ throw new Error('preset-conflict');
277
+ const editedComposition = input.composition !== undefined ? input.composition : oldComposition;
278
+ let nextComposition = input.enableCodex && !supportsCodex(editedComposition)
279
+ ? enhanceComposition(editedComposition) : editedComposition;
280
+ if (supportsCodex(nextComposition)) {
281
+ nextComposition = patchPresetComposition(nextComposition, input.systemPrompt, input.inheritPrompt);
282
+ if (input.codexOptions !== undefined)
283
+ nextComposition = patchCodexPresetOptions(nextComposition, input.codexOptions);
284
+ }
285
+ validateComposition(nextComposition);
286
+ const nextMetadata = patchPresetMetadata(oldMetadata ?? '', input.name, input.description);
287
+ const compositionMode = await mode(composition);
288
+ const metadataMode = await mode(metadata);
289
+ await writeFileAtomic(resolve(dirname(composition), '.codex-editor-backup.json'), JSON.stringify({ composition: oldComposition, metadata: oldMetadata ?? null }), { mode: 0o600, dirMode: 0o700 });
290
+ try {
291
+ await writeFileAtomic(composition, nextComposition, { mode: compositionMode, dirMode: 0o700 });
292
+ await writeFileAtomic(metadata, nextMetadata, { mode: metadataMode, dirMode: 0o700 });
293
+ const result = await this.agentPresets.resolve(input.id);
294
+ if (result.broken !== undefined)
295
+ throw new Error('invalid-preset-after-save');
296
+ return await this.read(input.id);
297
+ }
298
+ catch (error) {
299
+ await writeFileAtomic(composition, oldComposition, { mode: compositionMode, dirMode: 0o700 });
300
+ if (oldMetadata !== undefined)
301
+ await writeFileAtomic(metadata, oldMetadata, { mode: metadataMode, dirMode: 0o700 });
302
+ else
303
+ await unlink(metadata).catch(cause => { if (cause.code !== 'ENOENT')
304
+ throw cause; });
305
+ throw error;
306
+ }
307
+ }, { waitMs: 10_000 });
308
+ }
309
+ async preset(id) {
310
+ if (!PRESET_ID.test(id))
311
+ throw new Error('invalid-preset-id');
312
+ const preset = await this.agentPresets.resolve(id);
313
+ if (preset.broken !== undefined)
314
+ throw new Error('invalid-preset');
315
+ return preset;
316
+ }
317
+ }
318
+ // Same decorator registration as the host, consumable by the Vitest transform.
319
+ function markRemoteMethod(methodName) {
320
+ const descriptor = Object.getOwnPropertyDescriptor(CodexPresetEditor.prototype, methodName);
321
+ const initializers = [];
322
+ const decorator = Remote(methodName);
323
+ decorator(descriptor.value, { kind: 'method', name: methodName, static: false, private: false,
324
+ addInitializer: initializer => { initializers.push(initializer); } });
325
+ const receiver = Object.create(CodexPresetEditor.prototype);
326
+ for (const initializer of initializers)
327
+ initializer.call(receiver);
328
+ }
329
+ for (const method of ['read', 'update', 'catalog', 'create'])
330
+ markRemoteMethod(method);
331
+ export default CodexPresetEditor;
332
+ //# sourceMappingURL=preset-editor.js.map