@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.
Files changed (128) hide show
  1. package/CHANGELOG.md +121 -0
  2. package/README.md +48 -38
  3. package/RELEASE.md +61 -0
  4. package/assets/codex.svg +5 -0
  5. package/cordis.patch.yml +150 -6
  6. package/docs/preset-library.md +39 -23
  7. package/docs/tool-policy-benchmark.json +310 -0
  8. package/docs/tool-policy.md +144 -0
  9. package/lib/client.js +1639 -111
  10. package/lib/compaction.js +17 -2
  11. package/lib/index.js +799 -188
  12. package/lib/installer.js +50 -6
  13. package/lib/preferences.js +111 -0
  14. package/lib/tool-policy.js +2235 -0
  15. package/lib/typert.js +57 -10
  16. package/lib/types/activity.d.ts +1 -1
  17. package/lib/types/activity.js +50 -14
  18. package/lib/types/client/activity.d.ts +33 -9
  19. package/lib/types/client/desktop.d.ts +43 -0
  20. package/lib/types/client/desktop.js +121 -0
  21. package/lib/types/client/entry.d.ts +10 -0
  22. package/lib/types/client/entry.js +12 -0
  23. package/lib/types/client/index.d.ts +109 -19
  24. package/lib/types/client/index.js +21 -40
  25. package/lib/types/client/policy-drafts.d.ts +25 -0
  26. package/lib/types/client/policy-drafts.js +47 -0
  27. package/lib/types/client/preset-copy.d.ts +1 -0
  28. package/lib/types/client/preset-copy.js +2 -0
  29. package/lib/types/client/preset-manager.d.ts +12 -2
  30. package/lib/types/client/preset-manager.js +70 -25
  31. package/lib/types/client/preset-requests.d.ts +12 -0
  32. package/lib/types/client/preset-requests.js +101 -0
  33. package/lib/types/client/session.d.ts +6 -0
  34. package/lib/types/client/session.js +9 -0
  35. package/lib/types/client/tool-policy.d.ts +120 -0
  36. package/lib/types/client/tool-policy.js +394 -0
  37. package/lib/types/compaction.d.ts +3 -3
  38. package/lib/types/compaction.js +6 -2
  39. package/lib/types/desktop-preset.d.ts +20 -0
  40. package/lib/types/desktop-preset.js +39 -0
  41. package/lib/types/exec.d.ts +4 -0
  42. package/lib/types/exec.js +192 -66
  43. package/lib/types/host-settings.d.ts +4 -0
  44. package/lib/types/host-settings.js +13 -0
  45. package/lib/types/index.d.ts +20 -2
  46. package/lib/types/index.js +181 -68
  47. package/lib/types/installer.js +11 -2
  48. package/lib/types/preferences.d.ts +11 -0
  49. package/lib/types/preferences.js +16 -0
  50. package/lib/types/preset-editor-remote.d.ts +2 -0
  51. package/lib/types/preset-editor-remote.js +6 -2
  52. package/lib/types/preset-editor.d.ts +12 -7
  53. package/lib/types/preset-editor.js +43 -13
  54. package/lib/types/preset-prompt-catalog-schema.d.ts +16 -0
  55. package/lib/types/preset-prompt-catalog-schema.js +11 -0
  56. package/lib/types/preset-prompt-catalog.d.ts +21 -0
  57. package/lib/types/preset-prompt-catalog.js +192 -0
  58. package/lib/types/preset-prompt-contract.d.ts +22 -0
  59. package/lib/types/preset-prompt-contract.js +3 -0
  60. package/lib/types/preset-tool-catalog-schema.d.ts +38 -0
  61. package/lib/types/preset-tool-catalog-schema.js +28 -0
  62. package/lib/types/preset-tool-catalog.d.ts +5 -0
  63. package/lib/types/preset-tool-catalog.js +51 -0
  64. package/lib/types/prompt-sections.d.ts +1 -1
  65. package/lib/types/prompt-sections.js +9 -3
  66. package/lib/types/prompt.js +4 -2
  67. package/lib/types/remote.js +23 -8
  68. package/lib/types/settings.d.ts +3 -3
  69. package/lib/types/settings.js +3 -3
  70. package/lib/types/tool-capabilities.d.ts +32 -0
  71. package/lib/types/tool-capabilities.js +42 -0
  72. package/lib/types/tool-policy-contract.d.ts +60 -0
  73. package/lib/types/tool-policy-contract.js +26 -0
  74. package/lib/types/tool-policy.d.ts +171 -0
  75. package/lib/types/tool-policy.js +367 -0
  76. package/lib/types/typert.host.d.ts +2 -2
  77. package/lib/types/typert.host.js +12 -2
  78. package/locale/en.json +6 -0
  79. package/locale/tool-policy/en.json +6 -0
  80. package/locale/tool-policy/zh.json +6 -0
  81. package/locale/zh.json +6 -0
  82. package/package.json +375 -299
  83. package/scripts/benchmark-tool-policy.mjs +186 -0
  84. package/scripts/build-preset.mjs +19 -0
  85. package/scripts/clean-build.mjs +11 -0
  86. package/src/activity-types.ts +7 -0
  87. package/src/activity.ts +158 -0
  88. package/src/client/activity.ts +82 -0
  89. package/src/client/desktop.tsx +162 -0
  90. package/src/client/entry.tsx +16 -0
  91. package/src/client/index.tsx +972 -0
  92. package/src/client/policy-drafts.ts +56 -0
  93. package/src/client/preset-copy.ts +83 -0
  94. package/src/client/preset-manager.tsx +281 -0
  95. package/src/client/preset-requests.ts +113 -0
  96. package/src/client/session.ts +11 -0
  97. package/src/client/tool-policy.tsx +380 -0
  98. package/src/compact-command.ts +112 -0
  99. package/src/compaction.ts +190 -0
  100. package/src/context.ts +15 -0
  101. package/src/desktop-preset.ts +55 -0
  102. package/src/exec.ts +570 -0
  103. package/src/host-settings.ts +17 -0
  104. package/src/index.ts +1097 -0
  105. package/src/installer.ts +172 -0
  106. package/src/invariant.ts +34 -0
  107. package/src/patch.ts +258 -0
  108. package/src/preferences.ts +17 -0
  109. package/src/preset-contract.ts +85 -0
  110. package/src/preset-editor-remote.ts +41 -0
  111. package/src/preset-editor.ts +502 -0
  112. package/src/preset-prompt-catalog-schema.ts +10 -0
  113. package/src/preset-prompt-catalog.ts +191 -0
  114. package/src/preset-prompt-contract.ts +21 -0
  115. package/src/preset-tool-catalog-schema.ts +28 -0
  116. package/src/preset-tool-catalog.ts +51 -0
  117. package/src/prompt-sections.ts +33 -0
  118. package/src/prompt.ts +62 -0
  119. package/src/remote.ts +748 -0
  120. package/src/settings.ts +79 -0
  121. package/src/tool-capabilities.ts +76 -0
  122. package/src/tool-policy-contract.ts +76 -0
  123. package/src/tool-policy.ts +388 -0
  124. package/src/typert.host.ts +119 -0
  125. package/tsconfig.json +29 -0
  126. package/tsdown.config.ts +110 -0
  127. package/lib/types/preset-templates.d.ts +0 -36
  128. package/lib/types/preset-templates.js +0 -12
@@ -0,0 +1,172 @@
1
+ /** Install the user-visible Codex agent preset supplied by this bundle. */
2
+
3
+ import type { Context } from '@deepseek-ai/cordis'
4
+ import { createHash, randomUUID } from 'node:crypto'
5
+ import {
6
+ copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync,
7
+ } from 'node:fs'
8
+ import { homedir } from 'node:os'
9
+ import { dirname, join, resolve } from 'node:path'
10
+ import { fileURLToPath } from 'node:url'
11
+ import {
12
+ CODEX_SETTINGS_ENTRY, CODEX_SETTINGS_NAMESPACE, CODEX_SETTINGS_SCHEMA,
13
+ } from './settings.ts'
14
+ import { desktopCodexPreset, type DesktopPresetDefinition } from './desktop-preset.ts'
15
+
16
+ const PRESET_FILES = ['agent.cordis.yml', 'preset.yml'] as const
17
+ const MANAGED_SIGNATURE_FILE = '.dsh-codex-harness-managed'
18
+ const BUNDLED_PRESET_ID = 'codex-collaboration'
19
+ const LEGACY_PRESET_ID = 'codex'
20
+ const SOURCE_PRESET_DIR = fileURLToPath(new URL('../presets/codex-collaboration/', import.meta.url))
21
+
22
+ // Exact signatures of every previously shipped preset. Unknown directories
23
+ // remain user-owned; known copies can be migrated without erasing edits.
24
+ const LEGACY_PRESET_SIGNATURES = new Set([
25
+ '2f6222b6c9fed417d0f8fbfef9b221f0c9088c63347466219309c1c2ca2426bb',
26
+ '40ae944220ca57daae93d1483d6cb6264e6847ed77ee84f38171c34c36f0598e',
27
+ 'c6a594797f7044c44c09254635b8381f20533cd26a4661239529dc44ec423d0c',
28
+ '2c373798b9cadbda5fb377dab0d43ac5637263546a5a4fc1740752658fdec658',
29
+ 'a4062b59ad0e512e1b1b7e80ae56d8cde4efdaa5ba958364a17653ba1ff3c2ed',
30
+ '16016e7f68ee61354de232151be5b6ad0cda1785183ca0c72f9d0946b6a1d6cd',
31
+ '7f72b1bea9b30074788f05d20b841a797a5b29bb945dd1fb0597c8d03eb2b9b9',
32
+ '6a6c8dc2e7a7dbc1ac30ce608a53c238f19066a786f951f9a295ada86e56ed9e',
33
+ ])
34
+ const BUNDLED_PRESET_SIGNATURES = new Set([
35
+ '2a7ef181266e69275d25091adc74dd619af7c7d3577573887aaaecd2663e13c8',
36
+ 'd1de30f5c13049621b1c1ae3fb22d35b031797a4762638265822b0ff62749854',
37
+ 'b50e1d616f9b4188a33c0da0fe355478b7b75b615f3792c094e2b67995622cf4',
38
+ '6132523d92893f6ae9214b30105e9cc1ba64854df6ca8a84213069eb6c38d286',
39
+ '7957bc5e9b0f2fa0b74d2d8bae0d4ee153a2ba7bb430f5a848e700386cc7ce3f',
40
+ ])
41
+
42
+ function dshHomePath(...segments: string[]): string {
43
+ const configured = process.env.DSH_HOME?.trim()
44
+ const expanded = configured === undefined || configured.length === 0
45
+ ? join(homedir(), '.dsh')
46
+ : configured === '~'
47
+ ? homedir()
48
+ : configured.startsWith('~/') || configured.startsWith('~\\')
49
+ ? join(homedir(), configured.slice(2))
50
+ : configured
51
+ return join(resolve(expanded), ...segments)
52
+ }
53
+
54
+ /** Bundle plugin name for the preset installer. */
55
+ export const name = 'codex-preset-installer'
56
+ export const inject = ['settings', 'agentPresets']
57
+
58
+ function presetSignature(directory: string): string | undefined {
59
+ if (PRESET_FILES.some(file => !existsSync(join(directory, file)))) return undefined
60
+ const hash = createHash('sha256')
61
+ hash.update(readFileSync(join(directory, PRESET_FILES[0])))
62
+ hash.update(Buffer.from([0]))
63
+ hash.update(readFileSync(join(directory, PRESET_FILES[1])))
64
+ return hash.digest('hex')
65
+ }
66
+
67
+ function stagePreset(targetDir: string, sourceDir: string, presetId: string): string {
68
+ const parentDir = dirname(targetDir)
69
+ mkdirSync(parentDir, { recursive: true })
70
+ const stagingDir = mkdtempSync(join(parentDir, `.${presetId}-`))
71
+ try {
72
+ for (const file of PRESET_FILES) copyFileSync(join(sourceDir, file), join(stagingDir, file))
73
+ const signature = presetSignature(stagingDir)
74
+ if (signature === undefined) throw new Error(`incomplete bundled preset: ${sourceDir}`)
75
+ writeFileSync(join(stagingDir, MANAGED_SIGNATURE_FILE), `${signature}\n`)
76
+ return stagingDir
77
+ } catch (error) {
78
+ rmSync(stagingDir, { recursive: true, force: true })
79
+ throw error
80
+ }
81
+ }
82
+
83
+ function installPreset(targetDir: string, sourceDir: string, presetId: string): void {
84
+ const stagingDir = stagePreset(targetDir, sourceDir, presetId)
85
+ try {
86
+ renameSync(stagingDir, targetDir)
87
+ } catch (error) {
88
+ if (!existsSync(targetDir)) throw error
89
+ rmSync(stagingDir, { recursive: true, force: true })
90
+ }
91
+ }
92
+
93
+ function replacePreset(targetDir: string, sourceDir: string, presetId: string): void {
94
+ const stagingDir = stagePreset(targetDir, sourceDir, presetId)
95
+ const backupDir = join(dirname(targetDir), `.${presetId}-backup-${randomUUID()}`)
96
+ renameSync(targetDir, backupDir)
97
+ try {
98
+ renameSync(stagingDir, targetDir)
99
+ rmSync(backupDir, { recursive: true, force: true })
100
+ } catch (error) {
101
+ if (existsSync(stagingDir)) rmSync(stagingDir, { recursive: true, force: true })
102
+ if (!existsSync(targetDir)) renameSync(backupDir, targetDir)
103
+ throw error
104
+ }
105
+ }
106
+
107
+ function hasMatchingManagedMarker(targetDir: string, signature: string): boolean {
108
+ const marker = join(targetDir, MANAGED_SIGNATURE_FILE)
109
+ return existsSync(marker) && readFileSync(marker, 'utf8').trim() === signature
110
+ }
111
+
112
+ /**
113
+ * Install or upgrade the single shipped Codex preset.
114
+ *
115
+ * The directory is committed with a staging rename so a failed copy cannot
116
+ * leave a half-written preset that hides the mode from the roster. A known
117
+ * shipped copy upgrades in place; any changed or unknown copy is preserved.
118
+ *
119
+ * @param targetDir - destination preset directory.
120
+ * @param sourceDir - directory containing the packaged preset files.
121
+ */
122
+ export function installCodexPreset(
123
+ targetDir = dshHomePath('.agent-presets', BUNDLED_PRESET_ID),
124
+ sourceDir = SOURCE_PRESET_DIR,
125
+ ): void {
126
+ if (!existsSync(targetDir)) {
127
+ installPreset(targetDir, sourceDir, BUNDLED_PRESET_ID)
128
+ return
129
+ }
130
+ const signature = presetSignature(targetDir)
131
+ if (signature !== undefined
132
+ && (BUNDLED_PRESET_SIGNATURES.has(signature) || hasMatchingManagedMarker(targetDir, signature))) {
133
+ replacePreset(targetDir, sourceDir, BUNDLED_PRESET_ID)
134
+ }
135
+ }
136
+
137
+ /** Remove an unmodified copy of the retired second Codex mode. */
138
+ export function retireLegacyCodexPreset(
139
+ targetDir = dshHomePath('.agent-presets', LEGACY_PRESET_ID),
140
+ managedSignatures: ReadonlySet<string> = LEGACY_PRESET_SIGNATURES,
141
+ ): void {
142
+ if (!existsSync(targetDir)) return
143
+ const signature = presetSignature(targetDir)
144
+ if (signature !== undefined && managedSignatures.has(signature)) {
145
+ rmSync(targetDir, { recursive: true, force: true })
146
+ }
147
+ }
148
+
149
+ /** Install the preset during profile boot without changing the host tool catalog. */
150
+ export function apply(ctx: Context): void {
151
+ const registry = (ctx as unknown as {
152
+ agentPresets?: { register?: (definition: DesktopPresetDefinition) => Promise<() => Promise<void>> }
153
+ }).agentPresets
154
+ if (typeof registry?.register === 'function') {
155
+ // Desktop owns live in-memory revisions. The declaring fiber must own the
156
+ // async disposer, including disposal while registration is still mounting.
157
+ ctx.effect(() => registry.register!(desktopCodexPreset(SOURCE_PRESET_DIR)), 'codex.preset')
158
+ return
159
+ }
160
+ try {
161
+ const settings = ctx.settings as unknown as {
162
+ register(namespace: string, schema: unknown, options: { base: typeof CODEX_SETTINGS_ENTRY }): void
163
+ }
164
+ settings.register(CODEX_SETTINGS_NAMESPACE, CODEX_SETTINGS_SCHEMA, { base: CODEX_SETTINGS_ENTRY })
165
+ installCodexPreset()
166
+ retireLegacyCodexPreset()
167
+ } catch (error) {
168
+ ctx.logger.warn(`dsh-codex: could not reconcile the Codex preset: ${String(error)}`)
169
+ }
170
+ }
171
+
172
+ export default { name, inject, apply }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Package-owned invariant companion for `@shuind/dsh-codex-harness`.
3
+ * @module @shuind/dsh-codex-harness/invariant
4
+ */
5
+
6
+ /* jscpd:ignore-start */
7
+ import type { Context } from '@deepseek-ai/cordis'
8
+ // The invariant registry is a legacy optional seam, no longer shipped by current DSH.
9
+ // Keep this companion loadable without resolving the removed package.
10
+ interface InvariantRegistry {
11
+ register(packageName: string, install: () => void): (() => void) | Promise<() => void>
12
+ }
13
+
14
+ const PACKAGE_NAME = '@shuind/dsh-codex-harness'
15
+
16
+ /** Codex companion plugin name. */
17
+ export const name = 'codex-invariant'
18
+ /** Service required before the companion can reserve package ownership. */
19
+ export const inject = ['invariants']
20
+
21
+ /**
22
+ * Codex has no independent lifecycle stream: its model-visible state is owned
23
+ * by the tool registry and session projection services it consumes.
24
+ */
25
+ const install = (): void => {}
26
+
27
+ /**
28
+ * Register this package's invariant companion.
29
+ * @param ctx - Cordis context carrying the invariant service.
30
+ * @returns the installed registration's disposer after setup succeeds.
31
+ */
32
+ export const apply = (ctx: Context): Promise<() => void> =>
33
+ Promise.resolve((ctx as Context & { invariants: InvariantRegistry }).invariants.register(PACKAGE_NAME, install))
34
+ /* jscpd:ignore-end */
package/src/patch.ts ADDED
@@ -0,0 +1,258 @@
1
+ /** Parser and line-oriented applicator for Codex's `apply_patch` language. */
2
+
3
+ export const APPLY_PATCH_DESCRIPTION = 'Edits files using Codex patch syntax with Begin/End Patch markers and file update directives. In hunk lines, the first character is the operation marker; repeat a source-leading marker when the source line itself starts with one.'
4
+
5
+ /** The grammar sent to providers that support OpenAI custom grammar tools. */
6
+ export const APPLY_PATCH_GRAMMAR = String.raw`start: begin_patch hunk+ end_patch
7
+ begin_patch: "*** Begin Patch" LF
8
+ end_patch: "*** End Patch" LF?
9
+ hunk: add_hunk | delete_hunk | update_hunk
10
+ add_hunk: "*** Add File: " filename LF add_line+
11
+ delete_hunk: "*** Delete File: " filename LF
12
+ update_hunk: "*** Update File: " filename LF change_move? change?
13
+ filename: /(.+)/
14
+ add_line: "+" /(.*)/ LF -> line
15
+ change_move: "*** Move to: " filename LF
16
+ change: (change_context | change_line)+ eof_line?
17
+ change_context: ("@@" | "@@ " /(.+)/) LF
18
+ change_line: ("+" | "-" | " ") /(.*)/ LF
19
+ eof_line: "*** End of File" LF
20
+ %import common.LF
21
+ `
22
+
23
+ export type PatchLine =
24
+ | { kind: 'context'; text: string }
25
+ | { kind: 'delete'; text: string }
26
+ | { kind: 'add'; text: string }
27
+
28
+ export interface PatchHunk {
29
+ context?: string
30
+ lines: PatchLine[]
31
+ endOfFile: boolean
32
+ }
33
+
34
+ export type PatchFile =
35
+ | { kind: 'add'; path: string; content: string }
36
+ | { kind: 'delete'; path: string }
37
+ | { kind: 'update'; path: string; moveTo?: string; hunks: PatchHunk[] }
38
+
39
+ function invalid(message: string): never {
40
+ throw new Error(`apply_patch: ${message}`)
41
+ }
42
+
43
+ function isFileHeader(line: string): boolean {
44
+ const trimmed = line.trim()
45
+ return trimmed.startsWith('*** Add File: ')
46
+ || trimmed.startsWith('*** Delete File: ')
47
+ || trimmed.startsWith('*** Update File: ')
48
+ }
49
+
50
+ function unwrapHeredoc(input: string): string {
51
+ const normalized = input.replaceAll('\r\n', '\n').trim()
52
+ const lines = normalized.split('\n')
53
+ const first = lines[0]?.trim()
54
+ const last = lines.at(-1)?.trim()
55
+ if (lines.length >= 4
56
+ && (first === '<<EOF' || first === "<<'EOF'" || first === '<<"EOF"')
57
+ && last === 'EOF') {
58
+ return lines.slice(1, -1).join('\n').trim()
59
+ }
60
+ return normalized
61
+ }
62
+
63
+ function pathFrom(line: string, prefix: string): string {
64
+ const path = line.slice(prefix.length).trim()
65
+ if (path.length === 0) invalid(`${prefix.trim()} requires a file path`)
66
+ return path
67
+ }
68
+
69
+ function isChangeMarker(line: string): boolean {
70
+ const marker = line.trimEnd()
71
+ return marker === '@@' || marker.startsWith('@@ ')
72
+ }
73
+
74
+ function isPotentialChangeMarker(line: string): boolean {
75
+ return line.trimEnd().startsWith('@@')
76
+ }
77
+
78
+ /** Parse one complete Codex patch after normalizing CRLF input to LF. */
79
+ export function parsePatch(input: string): PatchFile[] {
80
+ const lines = unwrapHeredoc(input).split('\n')
81
+ if (lines[0]?.trim() !== '*** Begin Patch') invalid('input must start with "*** Begin Patch"')
82
+ if (lines.at(-1)?.trim() !== '*** End Patch') invalid('input must end with "*** End Patch"')
83
+
84
+ const files: PatchFile[] = []
85
+ let index = 1
86
+ const end = lines.length - 1
87
+ if (lines[index]?.trim().startsWith('*** Environment ID:') === true) {
88
+ invalid('environment selection is unavailable in this single-environment DSH plugin')
89
+ }
90
+ while (index < end) {
91
+ const header = lines[index++]?.trim()
92
+ if (header === undefined) invalid('unexpected end of input')
93
+ if (header.startsWith('*** Add File: ')) {
94
+ const path = pathFrom(header, '*** Add File: ')
95
+ const content: string[] = []
96
+ while (index < end && lines[index]?.startsWith('+') === true) {
97
+ content.push(lines[index]!.slice(1))
98
+ index++
99
+ }
100
+ if (content.length === 0) invalid(`add file ${JSON.stringify(path)} needs at least one content line`)
101
+ files.push({ kind: 'add', path, content: `${content.join('\n')}\n` })
102
+ continue
103
+ }
104
+ if (header.startsWith('*** Delete File: ')) {
105
+ files.push({ kind: 'delete', path: pathFrom(header, '*** Delete File: ') })
106
+ continue
107
+ }
108
+ if (!header.startsWith('*** Update File: ')) invalid(`unexpected directive ${JSON.stringify(header)}`)
109
+
110
+ const path = pathFrom(header, '*** Update File: ')
111
+ let moveTo: string | undefined
112
+ if (lines[index]?.trim().startsWith('*** Move to: ') === true) {
113
+ moveTo = pathFrom(lines[index]!.trim(), '*** Move to: ')
114
+ index++
115
+ }
116
+ const hunks: PatchHunk[] = []
117
+ while (index < end && !isFileHeader(lines[index]!)) {
118
+ const patchLines: PatchLine[] = []
119
+ let context: string | undefined
120
+ if (isPotentialChangeMarker(lines[index]!)) {
121
+ const marker = lines[index]!.trimEnd()
122
+ if (!isChangeMarker(marker)) {
123
+ invalid(`invalid update hunk marker ${JSON.stringify(lines[index])}`)
124
+ }
125
+ index++
126
+ context = marker.length === 2 ? undefined : marker.slice(3)
127
+ }
128
+ while (index < end && !isFileHeader(lines[index]!)
129
+ && !isPotentialChangeMarker(lines[index]!)
130
+ && lines[index]!.trimEnd() !== '*** End of File') {
131
+ const line = lines[index++]!
132
+ const kind = line[0]
133
+ if (kind !== ' ' && kind !== '+' && kind !== '-') {
134
+ invalid(`unexpected update line ${JSON.stringify(line)}`)
135
+ }
136
+ patchLines.push({ kind: kind === ' ' ? 'context' : kind === '+' ? 'add' : 'delete', text: line.slice(1) })
137
+ }
138
+ const endOfFile = lines[index]?.trimEnd() === '*** End of File'
139
+ if (endOfFile) index++
140
+ if (patchLines.length === 0) {
141
+ if (context !== undefined || endOfFile) invalid('an update hunk needs context or changed lines')
142
+ break
143
+ }
144
+ hunks.push({
145
+ ...context === undefined ? {} : { context },
146
+ lines: patchLines,
147
+ endOfFile,
148
+ })
149
+ }
150
+ if (hunks.length === 0 && moveTo === undefined) invalid(`update file ${JSON.stringify(path)} has no changes`)
151
+ files.push({
152
+ kind: 'update',
153
+ path,
154
+ ...moveTo === undefined ? {} : { moveTo },
155
+ hunks,
156
+ })
157
+ }
158
+ if (files.length === 0) invalid('no files were modified')
159
+ return files
160
+ }
161
+
162
+ interface TextLines {
163
+ lines: string[]
164
+ trailingNewline: boolean
165
+ }
166
+
167
+ function splitText(text: string): TextLines {
168
+ if (text.length === 0) return { lines: [], trailingNewline: false }
169
+ const trailingNewline = text.endsWith('\n')
170
+ const lines = text.split('\n')
171
+ if (trailingNewline) lines.pop()
172
+ return { lines, trailingNewline }
173
+ }
174
+
175
+ function joinText(value: TextLines): string {
176
+ const body = value.lines.join('\n')
177
+ return value.trailingNewline ? `${body}\n` : body
178
+ }
179
+
180
+ function findSequence(
181
+ lines: readonly string[],
182
+ expected: readonly string[],
183
+ from: number,
184
+ endOfFile: boolean,
185
+ ): number {
186
+ if (expected.length === 0) return Math.min(from, lines.length)
187
+ if (expected.length > lines.length) return -1
188
+ const first = endOfFile ? Math.max(from, lines.length - expected.length) : from
189
+ const last = lines.length - expected.length
190
+ const matchers: ((actual: string, wanted: string) => boolean)[] = [
191
+ (actual, wanted) => actual === wanted,
192
+ (actual, wanted) => actual.trimEnd() === wanted.trimEnd(),
193
+ (actual, wanted) => actual.trim() === wanted.trim(),
194
+ ]
195
+ for (const matchesLine of matchers) {
196
+ for (let index = first; index <= last; index++) {
197
+ let matches = true
198
+ for (let offset = 0; offset < expected.length; offset++) {
199
+ if (!matchesLine(lines[index + offset]!, expected[offset]!)) {
200
+ matches = false
201
+ break
202
+ }
203
+ }
204
+ if (matches) return index
205
+ }
206
+ }
207
+ return -1
208
+ }
209
+
210
+ function displayPatchLine(line: string): string {
211
+ if (line.length === 0) return '<empty>'
212
+ return line.replaceAll(' ', '[space]').replaceAll('\t', '[tab]')
213
+ }
214
+
215
+ function formatPatchExcerpt(lines: readonly string[], start: number, count: number): string {
216
+ if (lines.length === 0) return ' <empty file>'
217
+ const first = Math.max(0, Math.min(start, lines.length - 1))
218
+ return lines.slice(first, first + count)
219
+ .map((line, offset) => ` ${first + offset + 1}: ${displayPatchLine(line)}`)
220
+ .join('\n')
221
+ }
222
+
223
+ function mismatchMessage(
224
+ label: string,
225
+ hunkIndex: number,
226
+ expected: readonly string[],
227
+ actual: readonly string[],
228
+ from: number,
229
+ endOfFile: boolean,
230
+ ): string {
231
+ const expectedPreview = expected.slice(0, 12)
232
+ .map((line, index) => ` ${index + 1}: ${displayPatchLine(line)}`)
233
+ .join('\n')
234
+ const expectedSuffix = expected.length > 12 ? '\n ...' : ''
235
+ const excerptStart = endOfFile ? Math.max(0, actual.length - 6) : Math.max(0, from - 2)
236
+ const markerHint = expected.some(wanted => wanted.length > 0 && actual.includes(`-${wanted}`))
237
+ ? '\nHint: if a source line starts with a patch marker, repeat that marker after the operation marker; for example, `-- item` deletes the source line `- item`.'
238
+ : ''
239
+ return `could not find expected lines in ${label} hunk ${hunkIndex + 1} (search starts at line ${from + 1})\nExpected:\n${expectedPreview}${expectedSuffix}\nFile excerpt:\n${formatPatchExcerpt(actual, excerptStart, 10)}${markerHint}`
240
+ }
241
+
242
+ /** Apply parsed update hunks and return LF-normalized text. */
243
+ export function applyPatchHunks(original: string, hunks: readonly PatchHunk[], label = 'file'): string {
244
+ const value = splitText(original.replaceAll('\r\n', '\n'))
245
+ let cursor = 0
246
+ for (const [hunkIndex, hunk] of hunks.entries()) {
247
+ const expected = hunk.lines.filter(line => line.kind !== 'add').map(line => line.text)
248
+ const start = findSequence(value.lines, expected, cursor, hunk.endOfFile)
249
+ if (start < 0) {
250
+ invalid(mismatchMessage(label, hunkIndex, expected, value.lines, cursor, hunk.endOfFile))
251
+ }
252
+ const replacement = hunk.lines.filter(line => line.kind !== 'delete').map(line => line.text)
253
+ value.lines.splice(start, expected.length, ...replacement)
254
+ cursor = start + replacement.length
255
+ value.trailingNewline = !hunk.endOfFile
256
+ }
257
+ return joinText(value)
258
+ }
@@ -0,0 +1,17 @@
1
+ /** Profile-backed live preferences on DSH 0.2; legacy hosts keep settings.yaml. */
2
+ import { Service, type Context } from '@deepseek-ai/cordis'
3
+ import { CODEX_SETTINGS_ENTRY, CODEX_SETTINGS_SCHEMA, type CodexSettings } from './settings.ts'
4
+
5
+ export const Config = CODEX_SETTINGS_SCHEMA.default(CODEX_SETTINGS_ENTRY).volatile()
6
+
7
+ export default class CodexPreferences extends Service {
8
+ static Config = Config
9
+
10
+ constructor(ctx: Context, private readonly value: ReturnType<typeof Config>) {
11
+ super(ctx, 'codexPreferences')
12
+ }
13
+
14
+ current(): CodexSettings {
15
+ return this.value.get() ?? CODEX_SETTINGS_ENTRY
16
+ }
17
+ }
@@ -0,0 +1,85 @@
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
+ export interface PresetPromptSection {
9
+ id: string
10
+ label: string
11
+ text: string
12
+ editable: boolean
13
+ /** Excluded by a complete Persona; shown for inspection, never saved as an active section. */
14
+ suppressed?: boolean
15
+ }
16
+ /** Codex capabilities stored with a preset. Activity status stays global. */
17
+ export interface CodexPresetOptions {
18
+ promptEnabled: boolean
19
+ terminalToolsEnabled: boolean
20
+ patchToolEnabled: boolean
21
+ planToolEnabled: boolean
22
+ hostedWebSearchEnabled: boolean
23
+ remoteCompactionEnabled: boolean
24
+ }
25
+ export interface PresetEditorDocument extends PresetFields {
26
+ id: string
27
+ revision: string
28
+ editable: boolean
29
+ codex: boolean
30
+ codexOptions: CodexPresetOptions
31
+ composition: string
32
+ promptSections: PresetPromptSection[]
33
+ }
34
+ export interface PresetEditorInput extends PresetFields {
35
+ id: string
36
+ revision?: string
37
+ composition?: string
38
+ enableCodex?: boolean
39
+ promptSections?: PresetPromptSection[]
40
+ codexOptions?: Partial<CodexPresetOptions>
41
+ }
42
+ export interface PresetCreateInput extends PresetFields {
43
+ sourceId: string
44
+ enableCodex?: boolean
45
+ promptSections?: PresetPromptSection[]
46
+ composition?: string
47
+ codexOptions?: Partial<CodexPresetOptions>
48
+ }
49
+ export interface PresetCatalogRow {
50
+ id: string
51
+ name: string
52
+ description: string
53
+ editable: boolean
54
+ isDefault: boolean
55
+ codex?: boolean
56
+ }
57
+ export interface PresetCatalog {
58
+ presets: PresetCatalogRow[]
59
+ authorable: boolean
60
+ excludedCount: number
61
+ }
62
+
63
+ /** A portable instruction card, deliberately not executable YAML or a tool bundle. */
64
+ export interface PromptCard extends PresetFields {
65
+ format: 'codex-harness/prompt-card'
66
+ version: 1
67
+ }
68
+ export function parsePromptCard(text: string): PromptCard {
69
+ if (text.length > 1_100_000) throw new Error('invalid-prompt-card')
70
+ const value: unknown = JSON.parse(text)
71
+ if (!value || typeof value !== 'object') throw new Error('invalid-prompt-card')
72
+ const card = value as Record<string, unknown>
73
+ if (card.format !== 'codex-harness/prompt-card' || card.version !== 1
74
+ || typeof card.name !== 'string' || !card.name.trim() || card.name.length > 200
75
+ || typeof card.description !== 'string' || card.description.length > 4000
76
+ || typeof card.systemPrompt !== 'string' || card.systemPrompt.length > 1_000_000
77
+ || typeof card.inheritPrompt !== 'boolean') throw new Error('invalid-prompt-card')
78
+ return { format: card.format, version: 1, name: card.name, description: card.description,
79
+ systemPrompt: card.systemPrompt, inheritPrompt: card.inheritPrompt }
80
+ }
81
+ export function exportPromptCard(fields: PresetFields): string {
82
+ return JSON.stringify({ format: 'codex-harness/prompt-card', version: 1,
83
+ name: fields.name, description: fields.description, systemPrompt: fields.systemPrompt,
84
+ inheritPrompt: fields.inheritPrompt }, null, 2)
85
+ }
@@ -0,0 +1,41 @@
1
+ import { z } from 'zod'
2
+ import type { TypertRemoteContribution } from '@deepseek-ai/dsh-typert-protocol'
3
+ import { presetToolCatalogSchema } from './preset-tool-catalog-schema.ts'
4
+ import { presetPromptCatalogSchema } from './preset-prompt-catalog-schema.ts'
5
+ 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)
6
+ const fields = {
7
+ name: z.string().max(200), description: z.string().max(4000),
8
+ systemPrompt: z.string().max(1_000_000), inheritPrompt: z.boolean(),
9
+ }
10
+ const codexOptions = z.object({
11
+ promptEnabled: z.boolean(), terminalToolsEnabled: z.boolean(), patchToolEnabled: z.boolean(),
12
+ planToolEnabled: z.boolean(), hostedWebSearchEnabled: z.boolean(), remoteCompactionEnabled: z.boolean(),
13
+ })
14
+ const codexOptionsPatch = codexOptions.partial()
15
+ const document = z.object({ ...fields, id: z.string(), revision: z.string(), editable: z.boolean(), codex: z.boolean(), codexOptions, promptSections, composition: z.string() })
16
+ const catalog = z.object({
17
+ presets: z.array(z.object({ id: z.string(), name: z.string(), description: z.string(),
18
+ editable: z.boolean(), isDefault: z.boolean() })),
19
+ authorable: z.boolean(), excludedCount: z.number(),
20
+ })
21
+ function descriptor(method: string, parameter: string | undefined, input: z.ZodType, output: z.ZodType) {
22
+ const id = `@shuind/dsh-codex-harness#codexPresetEditor/${method}`
23
+ return {
24
+ id, service: 'codexPresetEditor', namespace: 'codexPresetEditor', method,
25
+ invocation: { kind: 'direct' as const },
26
+ parameters: parameter ? [{ name: parameter, wire: parameter, source: 'json' as const,
27
+ codec: { mode: 'strict' as const, typeSymbol: `${id}:${parameter}`, schema: input, create: () => input } }] : [],
28
+ result: { mode: 'strict' as const, typeSymbol: `${id}:result`, schema: output, create: () => output },
29
+ }
30
+ }
31
+ export default {
32
+ package: '@shuind/dsh-codex-harness',
33
+ descriptors: [
34
+ descriptor('catalog', undefined, z.unknown(), catalog),
35
+ descriptor('tools', 'id', z.string().min(1).max(256), presetToolCatalogSchema),
36
+ descriptor('prompts', 'id', z.string().min(1).max(256), presetPromptCatalogSchema),
37
+ descriptor('read', 'id', z.string(), document),
38
+ 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(), promptSections: promptSections.optional(), codexOptions: codexOptionsPatch.optional() }), document),
39
+ descriptor('create', 'rawInput', z.object({ ...fields, sourceId: z.string(), enableCodex: z.boolean().optional(), composition: z.string().max(1_000_000).optional(), promptSections: promptSections.optional(), codexOptions: codexOptionsPatch.optional() }), document),
40
+ ],
41
+ } satisfies TypertRemoteContribution