@shuind/dsh-codex-harness 0.2.16 → 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.
@@ -3,7 +3,7 @@ import { readFile, realpath, stat, unlink } from 'node:fs/promises';
3
3
  import { dirname, isAbsolute, relative, resolve } from 'node:path';
4
4
  import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol';
5
5
  import { isMap, isScalar, isSeq, parseDocument, Scalar, YAMLMap } from 'yaml';
6
- import { DEFAULT_CODEX_SYSTEM_PROMPT } from "./prompt.js";
6
+ import { DEFAULT_CODEX_PERSONA, DEFAULT_CODEX_SYSTEM_PROMPT, DEFAULT_DSH_CORE_SOURCE_PROMPT, DEFAULT_DSH_CORE_WEB_PROMPT } from "./prompt.js";
7
7
  let atomicWriteModule;
8
8
  function loadAtomicWrite() {
9
9
  return atomicWriteModule ??= import('@deepseek-ai/dsh-atomic-write');
@@ -53,6 +53,179 @@ function explicitPrompt(content) {
53
53
  throw new Error('unsupported-prompt-expression');
54
54
  return node.value;
55
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
+ }
56
229
  export function readCodexPresetOptions(content) {
57
230
  try {
58
231
  const { config } = harnessConfig(content);
@@ -206,13 +379,25 @@ async function assertWithinRoot(path, roots) {
206
379
  throw new Error('preset-outside-user-root');
207
380
  }
208
381
  export class CodexPresetEditor extends TypertRemoteService {
209
- static inject = ['agentPresets'];
382
+ static inject = ['agentPresets', 'settings'];
210
383
  agentPresets;
384
+ sharedSettings;
385
+ indexed;
211
386
  constructor(ctx, _config) {
212
387
  super(ctx, 'codexPresetEditor');
213
388
  this.agentPresets = ctx.get('agentPresets');
389
+ const settings = ctx.get('settings');
390
+ this.sharedSettings = () => settings?.get('codex') ?? {};
214
391
  }
215
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
+ }
216
401
  const roster = await this.agentPresets.remoteExportList();
217
402
  // Listing must not read/resolve every composition: each host read rescans roots.
218
403
  const presets = roster.presets.filter(row => row.broken === undefined).map(row => ({
@@ -222,17 +407,41 @@ export class CodexPresetEditor extends TypertRemoteService {
222
407
  return { presets, authorable: roster.authorable, excludedCount: roster.presets.length - presets.length };
223
408
  }
224
409
  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'));
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'))]);
228
417
  const meta = metadata ? yaml(metadata) : undefined;
229
418
  validateComposition(composition);
230
419
  const codex = supportsCodex(composition);
231
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
+ }
232
441
  return { id, name: String(meta?.get('name') ?? id), description: String(meta?.get('description') ?? ''),
233
- systemPrompt: prompt ?? DEFAULT_CODEX_SYSTEM_PROMPT, inheritPrompt: prompt === undefined,
442
+ systemPrompt: prompt ?? shared.systemPrompt ?? DEFAULT_CODEX_SYSTEM_PROMPT, inheritPrompt: prompt === undefined,
234
443
  revision: revision(composition, metadata), editable: preset.trust === 'user', codex,
235
- codexOptions: readCodexPresetOptions(composition), composition };
444
+ codexOptions: readCodexPresetOptions(composition), composition, promptSections };
236
445
  }
237
446
  async create(rawInput) {
238
447
  const input = validate(rawInput);
@@ -282,6 +491,8 @@ export class CodexPresetEditor extends TypertRemoteService {
282
491
  if (input.codexOptions !== undefined)
283
492
  nextComposition = patchCodexPresetOptions(nextComposition, input.codexOptions);
284
493
  }
494
+ if (input.promptSections)
495
+ nextComposition = patchPromptSections(nextComposition, input.promptSections);
285
496
  validateComposition(nextComposition);
286
497
  const nextMetadata = patchPresetMetadata(oldMetadata ?? '', input.name, input.description);
287
498
  const compositionMode = await mode(composition);
@@ -293,6 +504,7 @@ export class CodexPresetEditor extends TypertRemoteService {
293
504
  const result = await this.agentPresets.resolve(input.id);
294
505
  if (result.broken !== undefined)
295
506
  throw new Error('invalid-preset-after-save');
507
+ this.indexed?.set(input.id, result);
296
508
  return await this.read(input.id);
297
509
  }
298
510
  catch (error) {
@@ -312,6 +524,8 @@ export class CodexPresetEditor extends TypertRemoteService {
312
524
  const preset = await this.agentPresets.resolve(id);
313
525
  if (preset.broken !== undefined)
314
526
  throw new Error('invalid-preset');
527
+ this.indexed ??= new Map();
528
+ this.indexed.set(id, preset);
315
529
  return preset;
316
530
  }
317
531
  }
@@ -0,0 +1,15 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { PromptAssembly } from '@deepseek-ai/dsh-system-prompt';
3
+ import z from '@deepseek-ai/schemastery';
4
+ export interface Config {
5
+ persona?: string;
6
+ harnessSourcePrompt?: string;
7
+ webSurfacePrompt?: string;
8
+ }
9
+ export declare const Config: z<Config>;
10
+ export declare const name = "preset-prompt-sections";
11
+ export declare const inject: string[];
12
+ /** Override only existing sections; dynamic runtime context and tool guidance remain host-owned. */
13
+ export declare function applyPromptSections(assembly: PromptAssembly, config: Config): PromptAssembly;
14
+ export declare function apply(ctx: Context, config: Config): void;
15
+ //# sourceMappingURL=prompt-sections.d.ts.map
@@ -0,0 +1,23 @@
1
+ import z from '@deepseek-ai/schemastery';
2
+ export const Config = z.object({ persona: z.string(), harnessSourcePrompt: z.string(), webSurfacePrompt: z.string() });
3
+ export const name = 'preset-prompt-sections';
4
+ export const inject = ['systemPrompt'];
5
+ /** Override only existing sections; dynamic runtime context and tool guidance remain host-owned. */
6
+ export function applyPromptSections(assembly, config) {
7
+ const variables = { ...assembly.variables };
8
+ variables.sourceRoot ??= assembly.sections.find(s => s.name === 'harness:source')?.text.match(/^The DeepSeek Harness implementation checkout is at (.+?)\. The checkout location/u)?.[1];
9
+ variables.webUrl ??= assembly.sections.find(s => s.name === 'app:web-surface')?.text.match(/^You are interacting with the user through the DeepSeek Harness Web GUI at (.+?)\. When/u)?.[1];
10
+ const values = {
11
+ 'deployment:persona': config.persona,
12
+ 'harness:source': config.harnessSourcePrompt,
13
+ 'app:web-surface': config.webSurfacePrompt,
14
+ };
15
+ return { ...assembly, sections: assembly.sections.map(section => {
16
+ const text = values[section.name];
17
+ return text === undefined ? section : { ...section, text: text.replace(/\{\{([\w.-]+)\}\}/g, (whole, key) => variables[key] ?? whole) };
18
+ }) };
19
+ }
20
+ export function apply(ctx, config) {
21
+ ctx.on('system-prompt/assemble', async (_assembly, _context, next) => applyPromptSections(await next(), config));
22
+ }
23
+ //# sourceMappingURL=prompt-sections.js.map
@@ -0,0 +1,47 @@
1
+ import { z } from 'zod';
2
+ /** Host-side Remote contract consumed by the browser's preset editor. */
3
+ export declare const TYPERT: {
4
+ package: string;
5
+ face: "host";
6
+ schemas: never[];
7
+ invocations: {
8
+ id: string;
9
+ service: string;
10
+ namespace: string;
11
+ method: string;
12
+ invocation: {
13
+ kind: "direct";
14
+ };
15
+ parameters: {
16
+ name: string;
17
+ wire: string;
18
+ source: "json";
19
+ codec: {
20
+ mode: "strict";
21
+ typeSymbol: string;
22
+ schema: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
23
+ };
24
+ }[];
25
+ result: {
26
+ mode: "strict";
27
+ typeSymbol: string;
28
+ schema: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
29
+ };
30
+ }[];
31
+ model: {
32
+ services: {
33
+ description: string;
34
+ summary: string;
35
+ tags: never[];
36
+ jsDoc: string;
37
+ key: string;
38
+ exportName: string;
39
+ members: never[];
40
+ types: never[];
41
+ }[];
42
+ events: never[];
43
+ objects: never[];
44
+ };
45
+ };
46
+ export default TYPERT;
47
+ //# sourceMappingURL=typert.host.d.ts.map
@@ -0,0 +1,99 @@
1
+ import { z } from 'zod';
2
+ const PACKAGE = '@shuind/dsh-codex-harness';
3
+ const SERVICE = 'codexPresetEditor';
4
+ const promptSections = z.array(z.object({ id: z.string(), label: z.string(), text: z.string().max(1_000_000), editable: z.boolean(), suppressed: z.boolean().optional() })).max(200);
5
+ const fields = {
6
+ name: z.string().max(200),
7
+ description: z.string().max(4000),
8
+ systemPrompt: z.string().max(1_000_000),
9
+ inheritPrompt: z.boolean(),
10
+ };
11
+ const codexOptions = z.object({
12
+ promptEnabled: z.boolean(),
13
+ terminalToolsEnabled: z.boolean(),
14
+ patchToolEnabled: z.boolean(),
15
+ planToolEnabled: z.boolean(),
16
+ hostedWebSearchEnabled: z.boolean(),
17
+ remoteCompactionEnabled: z.boolean(),
18
+ });
19
+ const document = z.object({
20
+ ...fields,
21
+ id: z.string(),
22
+ revision: z.string(),
23
+ editable: z.boolean(),
24
+ codex: z.boolean(),
25
+ codexOptions,
26
+ promptSections, composition: z.string(),
27
+ });
28
+ const catalog = z.object({
29
+ presets: z.array(z.object({
30
+ id: z.string(),
31
+ name: z.string(),
32
+ description: z.string(),
33
+ editable: z.boolean(),
34
+ isDefault: z.boolean(),
35
+ })),
36
+ authorable: z.boolean(),
37
+ excludedCount: z.number(),
38
+ });
39
+ const codexOptionsPatch = codexOptions.partial();
40
+ function descriptor(method, parameter, input, output) {
41
+ const id = `${PACKAGE}#${SERVICE}/${method}`;
42
+ return {
43
+ id,
44
+ service: SERVICE,
45
+ namespace: SERVICE,
46
+ method,
47
+ invocation: { kind: 'direct' },
48
+ parameters: parameter === undefined ? [] : [{
49
+ name: parameter,
50
+ wire: parameter,
51
+ source: 'json',
52
+ codec: { mode: 'strict', typeSymbol: `${id}:${parameter}`, schema: input },
53
+ }],
54
+ result: { mode: 'strict', typeSymbol: `${id}:result`, schema: output },
55
+ };
56
+ }
57
+ const updateInput = z.object({
58
+ ...fields,
59
+ id: z.string(),
60
+ revision: z.string().optional(),
61
+ composition: z.string().max(1_000_000).optional(),
62
+ enableCodex: z.boolean().optional(),
63
+ promptSections: promptSections.optional(), codexOptions: codexOptionsPatch.optional(),
64
+ });
65
+ const createInput = z.object({
66
+ ...fields,
67
+ sourceId: z.string(),
68
+ enableCodex: z.boolean().optional(),
69
+ composition: z.string().max(1_000_000).optional(),
70
+ promptSections: promptSections.optional(), codexOptions: codexOptionsPatch.optional(),
71
+ });
72
+ /** Host-side Remote contract consumed by the browser's preset editor. */
73
+ export const TYPERT = {
74
+ package: PACKAGE,
75
+ face: 'host',
76
+ schemas: [],
77
+ invocations: [
78
+ descriptor('catalog', undefined, z.unknown(), catalog),
79
+ descriptor('read', 'id', z.string(), document),
80
+ descriptor('update', 'rawInput', updateInput, document),
81
+ descriptor('create', 'rawInput', createInput, document),
82
+ ],
83
+ model: {
84
+ services: [{
85
+ description: 'Author and inspect DSH agent presets with Codex capabilities.',
86
+ summary: 'Codex preset editor.',
87
+ tags: [],
88
+ jsDoc: '',
89
+ key: SERVICE,
90
+ exportName: 'CodexPresetEditor',
91
+ members: [],
92
+ types: [],
93
+ }],
94
+ events: [],
95
+ objects: [],
96
+ },
97
+ };
98
+ export default TYPERT;
99
+ //# sourceMappingURL=typert.host.js.map