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