@shuind/dsh-codex-harness 0.2.21 → 0.3.0

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 (200) hide show
  1. package/CHANGELOG.md +185 -0
  2. package/README.md +38 -50
  3. package/RELEASE.md +61 -0
  4. package/assets/codex.svg +5 -0
  5. package/cordis.patch.yml +181 -6
  6. package/docs/preset-library.md +33 -23
  7. package/docs/tool-policy-benchmark.json +310 -0
  8. package/docs/tool-policy.md +148 -0
  9. package/lib/client.js +4774 -2416
  10. package/lib/compact-command.js +416 -0
  11. package/lib/compaction.js +141 -12
  12. package/lib/hybrid-executor.js +1196 -0
  13. package/lib/index.js +3658 -2334
  14. package/lib/preferences.js +117 -0
  15. package/lib/tool-policy.js +2422 -0
  16. package/lib/typert.js +86 -79
  17. package/lib/types/client/activity.d.ts +33 -9
  18. package/lib/types/client/activity.js +4 -3
  19. package/lib/types/client/desktop.d.ts +67 -0
  20. package/lib/types/client/desktop.js +229 -0
  21. package/lib/types/client/index.d.ts +207 -110
  22. package/lib/types/client/index.js +99 -492
  23. package/lib/types/client/policy-drafts.d.ts +25 -0
  24. package/lib/types/client/policy-drafts.js +47 -0
  25. package/lib/types/client/policy-locale.d.ts +260 -0
  26. package/lib/types/client/policy-locale.js +357 -0
  27. package/lib/types/client/preset-manager.d.ts +38 -10
  28. package/lib/types/client/preset-manager.js +235 -185
  29. package/lib/types/client/preset-requests.d.ts +12 -0
  30. package/lib/types/client/preset-requests.js +101 -0
  31. package/lib/types/client/tool-policy.d.ts +33 -0
  32. package/lib/types/client/tool-policy.js +336 -0
  33. package/lib/types/contracts/preset-editor-schema.d.ts +78 -0
  34. package/lib/types/contracts/preset-editor-schema.js +95 -0
  35. package/lib/types/{prompt.js → contracts/prompt.js} +13 -7
  36. package/lib/types/{settings.d.ts → contracts/settings.d.ts} +11 -4
  37. package/lib/types/{settings.js → contracts/settings.js} +22 -6
  38. package/lib/types/contracts/tool-policy-contract.d.ts +63 -0
  39. package/lib/types/contracts/tool-policy-contract.js +33 -0
  40. package/lib/types/contracts/ui-contracts.d.ts +92 -0
  41. package/lib/types/contracts/ui-contracts.js +83 -0
  42. package/lib/types/entries/client.d.ts +10 -0
  43. package/lib/types/entries/client.js +10 -0
  44. package/lib/types/{compact-command.d.ts → entries/compact-command.d.ts} +2 -0
  45. package/lib/types/entries/compact-command.js +176 -0
  46. package/lib/types/{compaction.d.ts → entries/compaction.d.ts} +15 -3
  47. package/lib/types/{compaction.js → entries/compaction.js} +47 -11
  48. package/lib/types/entries/hybrid-executor.d.ts +19 -0
  49. package/lib/types/entries/hybrid-executor.js +57 -0
  50. package/lib/types/entries/index.d.ts +66 -0
  51. package/lib/types/entries/index.js +192 -0
  52. package/lib/types/entries/preferences.d.ts +11 -0
  53. package/lib/types/entries/preferences.js +16 -0
  54. package/lib/types/entries/tool-policy.d.ts +97 -0
  55. package/lib/types/entries/tool-policy.js +158 -0
  56. package/lib/types/entries/typert.host.d.ts +23 -0
  57. package/lib/types/entries/typert.host.js +24 -0
  58. package/lib/types/hybrid/codex-hybrid-executor.d.ts +44 -0
  59. package/lib/types/hybrid/codex-hybrid-executor.js +257 -0
  60. package/lib/types/hybrid/hybrid-sdk.d.ts +13 -0
  61. package/lib/types/hybrid/hybrid-sdk.js +196 -0
  62. package/lib/types/hybrid/program-calls.d.ts +28 -0
  63. package/lib/types/hybrid/program-calls.js +193 -0
  64. package/lib/types/hybrid/subcall-scheduler.d.ts +90 -0
  65. package/lib/types/hybrid/subcall-scheduler.js +343 -0
  66. package/lib/types/policy/deferred-tools.d.ts +42 -0
  67. package/lib/types/policy/deferred-tools.js +264 -0
  68. package/lib/types/policy/overlay-installer.d.ts +12 -0
  69. package/lib/types/policy/overlay-installer.js +179 -0
  70. package/lib/types/policy/rule-resolver.d.ts +94 -0
  71. package/lib/types/policy/rule-resolver.js +114 -0
  72. package/lib/types/policy/tool-capabilities.d.ts +33 -0
  73. package/lib/types/policy/tool-capabilities.js +46 -0
  74. package/lib/types/{activity.d.ts → presets/activity.d.ts} +3 -5
  75. package/lib/types/{activity.js → presets/activity.js} +51 -27
  76. package/lib/types/presets/desktop-preset.d.ts +22 -0
  77. package/lib/types/presets/desktop-preset.js +43 -0
  78. package/lib/types/presets/preset-editor.d.ts +47 -0
  79. package/lib/types/presets/preset-editor.js +81 -0
  80. package/lib/types/presets/preset-prompt-catalog.d.ts +23 -0
  81. package/lib/types/presets/preset-prompt-catalog.js +215 -0
  82. package/lib/types/presets/preset-tool-catalog.d.ts +5 -0
  83. package/lib/types/presets/preset-tool-catalog.js +58 -0
  84. package/lib/types/presets/runtime-enhancements.d.ts +45 -0
  85. package/lib/types/presets/runtime-enhancements.js +349 -0
  86. package/lib/types/presets/small-window-compaction.d.ts +15 -0
  87. package/lib/types/presets/small-window-compaction.js +121 -0
  88. package/lib/types/responses/compact-checkpoint.d.ts +27 -0
  89. package/lib/types/responses/compact-checkpoint.js +257 -0
  90. package/lib/types/responses/fetch-transport.d.ts +16 -0
  91. package/lib/types/responses/fetch-transport.js +257 -0
  92. package/lib/types/responses/remote-compact.d.ts +13 -0
  93. package/lib/types/responses/remote-compact.js +319 -0
  94. package/lib/types/responses/sse-diagnostics.d.ts +9 -0
  95. package/lib/types/responses/sse-diagnostics.js +157 -0
  96. package/lib/types/responses/wire-rewrite.d.ts +35 -0
  97. package/lib/types/responses/wire-rewrite.js +237 -0
  98. package/lib/types/tools/exec-output.d.ts +58 -0
  99. package/lib/types/tools/exec-output.js +173 -0
  100. package/lib/types/tools/exec-plan-tools.d.ts +37 -0
  101. package/lib/types/tools/exec-plan-tools.js +265 -0
  102. package/lib/types/tools/exec-runner.d.ts +21 -0
  103. package/lib/types/tools/exec-runner.js +385 -0
  104. package/lib/types/tools/patch-tool.d.ts +16 -0
  105. package/lib/types/tools/patch-tool.js +258 -0
  106. package/lib/types/{patch.d.ts → tools/patch.d.ts} +1 -1
  107. package/lib/types/{patch.js → tools/patch.js} +96 -21
  108. package/locale/en.json +6 -0
  109. package/locale/hybrid-executor/en.json +6 -0
  110. package/locale/hybrid-executor/zh.json +6 -0
  111. package/locale/tool-policy/en.json +6 -0
  112. package/locale/tool-policy/zh.json +6 -0
  113. package/locale/zh.json +6 -0
  114. package/package.json +297 -299
  115. package/presets/{codex-collaboration → codex-hybrid}/agent.cordis.yml +45 -48
  116. package/presets/codex-hybrid/preset.yml +3 -0
  117. package/scripts/benchmark-tool-policy.mjs +186 -0
  118. package/scripts/build-preset.mjs +19 -0
  119. package/scripts/clean-build.mjs +11 -0
  120. package/src/client/activity.ts +83 -0
  121. package/src/client/desktop.tsx +276 -0
  122. package/src/client/index.tsx +391 -0
  123. package/src/client/policy-drafts.ts +56 -0
  124. package/src/client/policy-locale.ts +362 -0
  125. package/src/client/preset-manager.tsx +376 -0
  126. package/src/client/preset-requests.ts +113 -0
  127. package/src/client/tool-policy.tsx +402 -0
  128. package/src/contracts/preset-editor-schema.ts +110 -0
  129. package/src/contracts/prompt.ts +66 -0
  130. package/src/contracts/settings.ts +103 -0
  131. package/src/contracts/tool-policy-contract.ts +93 -0
  132. package/src/contracts/ui-contracts.ts +173 -0
  133. package/src/entries/client.tsx +14 -0
  134. package/src/entries/compact-command.ts +256 -0
  135. package/src/entries/compaction.ts +218 -0
  136. package/src/entries/hybrid-executor.ts +76 -0
  137. package/src/entries/index.ts +298 -0
  138. package/src/entries/preferences.ts +17 -0
  139. package/src/entries/tool-policy.ts +162 -0
  140. package/src/entries/typert.host.ts +29 -0
  141. package/src/hybrid/codex-hybrid-executor.ts +310 -0
  142. package/src/hybrid/hybrid-sdk.ts +217 -0
  143. package/src/hybrid/program-calls.ts +202 -0
  144. package/src/hybrid/subcall-scheduler.ts +446 -0
  145. package/src/policy/deferred-tools.ts +331 -0
  146. package/src/policy/overlay-installer.ts +191 -0
  147. package/src/policy/rule-resolver.ts +128 -0
  148. package/src/policy/tool-capabilities.ts +88 -0
  149. package/src/presets/activity.ts +146 -0
  150. package/src/presets/desktop-preset.ts +60 -0
  151. package/src/presets/preset-editor.ts +101 -0
  152. package/src/presets/preset-prompt-catalog.ts +221 -0
  153. package/src/presets/preset-tool-catalog.ts +58 -0
  154. package/src/presets/runtime-enhancements.ts +415 -0
  155. package/src/presets/small-window-compaction.ts +166 -0
  156. package/src/responses/compact-checkpoint.ts +264 -0
  157. package/src/responses/fetch-transport.ts +290 -0
  158. package/src/responses/remote-compact.ts +393 -0
  159. package/src/responses/sse-diagnostics.ts +156 -0
  160. package/src/responses/wire-rewrite.ts +261 -0
  161. package/src/tools/exec-output.ts +211 -0
  162. package/src/tools/exec-plan-tools.ts +307 -0
  163. package/src/tools/exec-runner.ts +445 -0
  164. package/src/tools/patch-tool.ts +331 -0
  165. package/src/tools/patch.ts +328 -0
  166. package/tsconfig.json +29 -0
  167. package/tsdown.config.ts +110 -0
  168. package/lib/installer.js +0 -237
  169. package/lib/invariant.js +0 -23
  170. package/lib/types/activity-types.d.ts +0 -6
  171. package/lib/types/activity-types.js +0 -3
  172. package/lib/types/client/preset-copy.d.ts +0 -42
  173. package/lib/types/client/preset-copy.js +0 -81
  174. package/lib/types/compact-command.js +0 -79
  175. package/lib/types/context.d.ts +0 -8
  176. package/lib/types/context.js +0 -14
  177. package/lib/types/exec.d.ts +0 -46
  178. package/lib/types/exec.js +0 -365
  179. package/lib/types/index.d.ts +0 -95
  180. package/lib/types/index.js +0 -738
  181. package/lib/types/installer.d.ts +0 -27
  182. package/lib/types/installer.js +0 -146
  183. package/lib/types/invariant.d.ts +0 -16
  184. package/lib/types/invariant.js +0 -22
  185. package/lib/types/preset-contract.d.ts +0 -69
  186. package/lib/types/preset-contract.js +0 -22
  187. package/lib/types/preset-editor-remote.d.ts +0 -30
  188. package/lib/types/preset-editor-remote.js +0 -37
  189. package/lib/types/preset-editor.d.ts +0 -69
  190. package/lib/types/preset-editor.js +0 -557
  191. package/lib/types/preset-templates.d.ts +0 -36
  192. package/lib/types/preset-templates.js +0 -12
  193. package/lib/types/prompt-sections.d.ts +0 -15
  194. package/lib/types/prompt-sections.js +0 -23
  195. package/lib/types/remote.d.ts +0 -40
  196. package/lib/types/remote.js +0 -683
  197. package/lib/types/typert.host.d.ts +0 -47
  198. package/lib/types/typert.host.js +0 -99
  199. package/presets/codex-collaboration/preset.yml +0 -3
  200. /package/lib/types/{prompt.d.ts → contracts/prompt.d.ts} +0 -0
@@ -0,0 +1,88 @@
1
+ /** Host-only ownership marks and the optional Agent-snapshot availability seam. */
2
+ import type { Context } from '@deepseek-ai/cordis'
3
+ import type { Agent } from '@deepseek-ai/dsh-agent'
4
+ import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
5
+ import type { ScopeKey } from '@deepseek-ai/dsh-scope'
6
+ import type { AssembleContext } from '@deepseek-ai/dsh-system-prompt'
7
+ import { CODEX_SETTINGS_ENTRY, CODEX_SETTINGS_NAMESPACE, readHostSettings } from '../contracts/settings.ts'
8
+ import type { CodexSettings } from '../contracts/settings.ts'
9
+ import type { CodexCapability, CodexToolMetadata, LegacyCapabilities } from '../contracts/tool-policy-contract.ts'
10
+
11
+ // Core and policy are bundled separately. A global symbol survives that boundary;
12
+ // matching an unmarked third-party tool by name would not establish ownership.
13
+ const OWNED_TOOL = Symbol.for('@shuind/dsh-codex-harness:tool-capability:v1')
14
+ const CAPABILITIES: readonly CodexCapability[] = ['terminalToolsEnabled', 'planToolEnabled', 'patchToolEnabled']
15
+
16
+ export interface CodexToolPolicyResolver {
17
+ /** Undefined means an older, unsnapshotted Agent retains the compatibility path. */
18
+ enabled(agent: Agent, name: string, metadata: CodexToolMetadata): boolean | undefined
19
+ hasPromptOverride?(scope: ScopeKey, name: string): boolean
20
+ }
21
+
22
+ declare module '@deepseek-ai/dsh-system-prompt' {
23
+ interface AssembleContext {
24
+ /** Read-only own-plugin probe: do not reapply obsolete Codex prompt preferences. */
25
+ codexPresetPromptProbe?: true
26
+ }
27
+ }
28
+
29
+ /** Only our old presentation hooks consume this; registrations remain provider-owned. */
30
+ export function hasPresetPromptOverride(ctx: Context, context: AssembleContext, name: string): boolean {
31
+ if (context.codexPresetPromptProbe === true) return ['deployment:persona-prefix', 'deployment:persona-suffix', 'codex:base'].includes(name)
32
+ return context.scope !== undefined && ctx.get('codexToolPolicy')?.hasPromptOverride?.(context.scope, name) === true
33
+ }
34
+
35
+ declare module '@deepseek-ai/cordis' {
36
+ interface Context {
37
+ codexToolPolicy: CodexToolPolicyResolver
38
+ }
39
+ }
40
+
41
+ export function markCodexTool<T extends ToolDefinition>(definition: T, metadata: CodexToolMetadata): T {
42
+ Object.defineProperty(definition, OWNED_TOOL, { value: Object.freeze({ ...metadata }) })
43
+ return definition
44
+ }
45
+
46
+ export function codexToolMetadata(definition: ToolDefinition): CodexToolMetadata | undefined {
47
+ const value = (definition as unknown as Record<symbol, unknown>)[OWNED_TOOL]
48
+ if (value === null || typeof value !== 'object') return undefined
49
+ const data = value as Partial<CodexToolMetadata>
50
+ if (!CAPABILITIES.includes(data.capability as CodexCapability) || typeof data.presetEnabled !== 'boolean'
51
+ || data.presetOverridesLegacy !== undefined && typeof data.presetOverridesLegacy !== 'boolean') return undefined
52
+ return { capability: data.capability as CodexCapability, presetEnabled: data.presetEnabled,
53
+ ...(data.presetOverridesLegacy === undefined ? {} : { presetOverridesLegacy: data.presetOverridesLegacy }) }
54
+ }
55
+
56
+ /** Read once for a new Agent or catalog. No caller keeps the live preference object. */
57
+ export function readLegacyCapabilities(ctx: Context): Readonly<Required<LegacyCapabilities>> {
58
+ const current = readHostSettings<Partial<CodexSettings>>(ctx, CODEX_SETTINGS_NAMESPACE)
59
+ return Object.freeze(Object.fromEntries(CAPABILITIES.map(key => [key, current?.[key] ?? CODEX_SETTINGS_ENTRY[key]]))) as Required<LegacyCapabilities>
60
+ }
61
+
62
+ export function codexToolEnabled(
63
+ ctx: Context,
64
+ agent: Agent | undefined,
65
+ name: string,
66
+ metadata: CodexToolMetadata,
67
+ fallback: () => CodexSettings,
68
+ authority?: boolean,
69
+ ): boolean {
70
+ if (!metadata.presetEnabled) return false
71
+ // Only a successfully compiled adapter plan supplies this authority.
72
+ if (authority !== undefined) return authority
73
+ const decision = agent === undefined ? undefined : ctx.get('codexToolPolicy')?.enabled(agent, name, metadata)
74
+ return decision ?? fallback()[metadata.capability] !== false
75
+ }
76
+
77
+ export function assertCapabilityEnabled(
78
+ ctx: Context,
79
+ current: () => CodexSettings,
80
+ toolName: string,
81
+ agent: Agent | undefined,
82
+ metadata: CodexToolMetadata,
83
+ authority?: boolean,
84
+ ): void {
85
+ if (!codexToolEnabled(ctx, agent, toolName, metadata, current, authority)) {
86
+ throw new Error(`${toolName}: disabled in Codex Harness plugin settings`)
87
+ }
88
+ }
@@ -0,0 +1,146 @@
1
+ /** Host-side activity projection for the Codex status line. */
2
+
3
+ import type { Context } from '@deepseek-ai/cordis'
4
+ import type { StreamChunk } from '@deepseek-ai/dsh-llm/types'
5
+ import { z, type ZodType } from 'zod'
6
+ import type { CodexActivity } from '../contracts/ui-contracts.ts'
7
+
8
+ export type { CodexActivity } from '../contracts/ui-contracts.ts'
9
+
10
+ /** Long-running Codex activities currently surfaced to the client. */
11
+ export type CodexActivityState = CodexActivity | null
12
+
13
+ /** Minimal event shape needed by this projection; no compaction package import is required. */
14
+ export interface CodexActivityEvent {
15
+ type: string
16
+ time: number
17
+ data?: unknown
18
+ }
19
+
20
+ /**
21
+ * Whether a stream chunk carries visible model output.
22
+ *
23
+ * DSH 0.1.2 removed the runtime `isTokenDelta` helper from `dsh-llm/message`
24
+ * while keeping the StreamChunk vocabulary unchanged. Keep this small
25
+ * predicate local so the harness works with both the old and new DSH bundles.
26
+ */
27
+ function isTokenDelta(chunk: StreamChunk): boolean {
28
+ switch (chunk.type) {
29
+ case 'text-delta':
30
+ case 'reasoning-delta':
31
+ return chunk.text !== ''
32
+ case 'tool-call-delta':
33
+ return chunk.argumentsDelta !== '' || chunk.name !== undefined
34
+ default:
35
+ return false
36
+ }
37
+ }
38
+
39
+ /** Read packed v2 streams without importing a helper absent from older DSH packages. */
40
+ function streamReplyTime(stream: readonly unknown[]): number | undefined {
41
+ for (const value of stream) {
42
+ if (typeof value !== 'object' || value === null) continue
43
+ const record = value as {
44
+ type?: string; time?: number; chunk?: StreamChunk
45
+ time0?: number; dt?: number[]; texts?: string[]; args?: string[]; name?: string
46
+ }
47
+ if (record.type === 'chunk') {
48
+ if (record.chunk !== undefined && isTokenDelta(record.chunk)) return record.time
49
+ continue
50
+ }
51
+ if (record.type !== 'text-chunks' && record.type !== 'reasoning-chunks' && record.type !== 'tool-call-chunks') continue
52
+ const fragments = record.type === 'tool-call-chunks' ? record.args : record.texts
53
+ if (fragments === undefined || record.time0 === undefined) continue
54
+ let time = record.time0
55
+ for (const [index, text] of fragments.entries()) {
56
+ if (index > 0) time += record.dt?.[index - 1] ?? 0
57
+ if (text !== '' || (record.type === 'tool-call-chunks' && record.name !== undefined)) return time
58
+ }
59
+ }
60
+ return undefined
61
+ }
62
+
63
+ /** Only a non-empty delta starts the reply phase; preserve its original stream time. */
64
+ function modelReplyTime(event: CodexActivityEvent): number | undefined {
65
+ const data = typeof event.data === 'object' && event.data !== null
66
+ ? event.data as { chunk?: StreamChunk; stream?: unknown[] }
67
+ : undefined
68
+ if (event.type === 'assistant/chunk') {
69
+ return data?.chunk !== undefined && isTokenDelta(data.chunk) ? event.time : undefined
70
+ }
71
+ if (event.type === 'assistant/message' || event.type === 'assistant/attempt') {
72
+ if (data?.stream !== undefined) return streamReplyTime(data.stream)
73
+ // Legacy/non-streaming adapters did not carry a packed stream on settlement.
74
+ if (event.type === 'assistant/message') return event.time
75
+ }
76
+ return undefined
77
+ }
78
+
79
+ /** Persisted and wire shape of the Codex activity value. */
80
+ export const codexActivitySchema: ZodType<CodexActivityState> = z.union([
81
+ z.object({
82
+ activity: z.literal('compaction'),
83
+ startedAt: z.number().int().nonnegative(),
84
+ }),
85
+ z.object({
86
+ activity: z.literal('requesting-model'),
87
+ startedAt: z.number().int().nonnegative(),
88
+ }),
89
+ z.object({
90
+ activity: z.literal('model-reply'),
91
+ startedAt: z.number().int().nonnegative(),
92
+ }),
93
+ z.null(),
94
+ ])
95
+
96
+ /** Pure event fold, exported so its reset and reference-stability rules can be tested directly. */
97
+ export function applyCodexActivity(
98
+ state: CodexActivityState,
99
+ event: CodexActivityEvent,
100
+ ): CodexActivityState {
101
+ if (event.type === 'compaction/start') return { activity: 'compaction', startedAt: event.time }
102
+ if (event.type === 'step/start' || event.type === 'llm/retry-started') {
103
+ return { activity: 'requesting-model', startedAt: event.time }
104
+ }
105
+ if (state?.activity === 'requesting-model') {
106
+ const startedAt = modelReplyTime(event)
107
+ if (startedAt !== undefined) return { activity: 'model-reply', startedAt }
108
+ }
109
+ if (event.type === 'turn/start' || event.type === 'turn/end' || event.type === 'compaction/end') return null
110
+ // Keep the line through reasoning and streamed output. It is the only
111
+ // visible indication that the model is still progressing; tool cards have
112
+ // their own status, so a tool dispatch retires this ambient line.
113
+ if ((state?.activity === 'requesting-model' || state?.activity === 'model-reply')
114
+ && (event.type === 'llm/retry'
115
+ || event.type === 'tool/call'
116
+ || event.type === 'step/end')) return null
117
+ return state
118
+ }
119
+
120
+ export const codexActivityProjection = {
121
+ key: 'codexActivity',
122
+ stateSchema: codexActivitySchema,
123
+ init: (): CodexActivityState => null,
124
+ apply: applyCodexActivity,
125
+ wire: {
126
+ viewSchema: codexActivitySchema,
127
+ view: (state: CodexActivityState): CodexActivityState => state,
128
+ },
129
+ stateVersion: 3,
130
+ } as const
131
+
132
+ type CodexActivityRegistry = {
133
+ register(definition: typeof codexActivityProjection): unknown
134
+ }
135
+
136
+ type ProjectionContext = Context & {
137
+ sessionProjections: CodexActivityRegistry
138
+ }
139
+
140
+ /** Register the optional activity unit without requiring the projection seam in every assembly. */
141
+ export function registerCodexActivityProjection(ctx: Context): void {
142
+ ctx.inject(['sessionProjections'], async (projectionCtx) => {
143
+ // Await readiness, but do not return the new ProjectionHandle as a Cordis effect.
144
+ await (projectionCtx as ProjectionContext).sessionProjections.register(codexActivityProjection)
145
+ })
146
+ }
@@ -0,0 +1,60 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { parseDocument } from 'yaml'
4
+
5
+ export interface DesktopPresetRow {
6
+ id: string
7
+ name: string
8
+ group?: boolean
9
+ disabled?: boolean | { __jsExpr: string }
10
+ config?: Record<string, unknown> | DesktopPresetRow[]
11
+ isolate?: Record<string, boolean>
12
+ }
13
+
14
+ export interface DesktopPresetDefinition {
15
+ id: string
16
+ name?: string
17
+ description?: string
18
+ order?: number
19
+ plugins: DesktopPresetRow[]
20
+ }
21
+
22
+ /** Keep expressions literal for the Desktop Loader, not YAML strings or eager eval. */
23
+ function readYaml(path: string): unknown {
24
+ const document = parseDocument(readFileSync(path, 'utf8'), {
25
+ customTags: [{
26
+ tag: 'tag:yaml.org,2002:js',
27
+ resolve: (expression: string) => ({ __jsExpr: expression }),
28
+ }],
29
+ })
30
+ if (document.errors.length) throw document.errors[0]
31
+ return document.toJS()
32
+ }
33
+
34
+ /** Convert the legacy file composition to Harness 0.2.2's declarative preset APIs. */
35
+ export function desktopCodexPreset(sourceDirectory: string, id = 'codex-hybrid'): DesktopPresetDefinition {
36
+ const metadata = readYaml(join(sourceDirectory, 'preset.yml')) as Omit<DesktopPresetDefinition, 'id' | 'plugins'>
37
+ const plugins = readYaml(join(sourceDirectory, 'agent.cordis.yml')) as DesktopPresetRow[]
38
+ function adapt(rows: DesktopPresetRow[]): DesktopPresetRow[] {
39
+ // Child discovery now belongs to the control plugin's root export.
40
+ return rows.filter(row => row.name !== '@deepseek-ai/dsh-tool-subagent-control/list-agents').map(row => {
41
+ if (row.name === '@deepseek-ai/dsh-workflow-worker-thread') {
42
+ row.name = '@deepseek-ai/dsh-workflow-ptc'
43
+ }
44
+ if (row.name === '@deepseek-ai/dsh-tool-subagent' && row.config && !Array.isArray(row.config)) {
45
+ const { modelSelectionSettings, backgroundMode: _backgroundMode, ...config } = row.config
46
+ row.config = modelSelectionSettings === undefined ? config : {
47
+ ...config, modelSelection: modelSelectionSettings, modelDiscovery: modelSelectionSettings,
48
+ }
49
+ }
50
+ if (row.group && Array.isArray(row.config)) row.config = adapt(row.config)
51
+ return row
52
+ })
53
+ }
54
+ return { ...metadata, id, plugins: adapt(plugins) }
55
+ }
56
+
57
+ /** Build the experimental asymmetric hybrid Codex preset declaration. */
58
+ export function desktopCodexHybridPreset(sourceDirectory: string): DesktopPresetDefinition {
59
+ return desktopCodexPreset(sourceDirectory, 'codex-hybrid')
60
+ }
@@ -0,0 +1,101 @@
1
+ /** Read-only Host Remote service for inspecting declarative agent presets. */
2
+ import type { Context } from '@deepseek-ai/cordis'
3
+ import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
4
+ import type { PresetCatalog, PresetDefinitionDocument, PresetPromptCatalog } from '../contracts/ui-contracts.ts'
5
+ import { PRESET_EDITOR_SERVICE } from '../contracts/preset-editor-schema.ts'
6
+ import type { PresetToolCatalog } from '../contracts/tool-policy-contract.ts'
7
+ import { readPresetPromptCatalog } from './preset-prompt-catalog.ts'
8
+ import { readPresetToolCatalog } from './preset-tool-catalog.ts'
9
+
10
+ export type { PresetDefinitionDocument } from '../contracts/ui-contracts.ts'
11
+
12
+ export interface AgentPresetsForEditor {
13
+ readonly defaultId?: string
14
+ list?(): Promise<Array<{ id: string; name?: string; description?: string; broken?: string }>>
15
+ remoteExportList?(): Promise<{ presets: Array<{ id: string; name?: string; description?: string; isDefault: boolean; broken?: string }> }>
16
+ resolve(id: string): Promise<{ id: string; name?: string; description?: string; broken?: string }>
17
+ readDocument(id: string): Promise<{ content: string; name?: string; description?: string }>
18
+ }
19
+
20
+ export class CodexPresetEditor extends TypertRemoteService {
21
+ static inject = ['agentPresets']
22
+ private readonly agentPresets: AgentPresetsForEditor
23
+ private readonly toolContext: Context
24
+
25
+ constructor(ctx: Context, _config?: undefined) {
26
+ super(ctx, PRESET_EDITOR_SERVICE)
27
+ this.toolContext = ctx
28
+ this.agentPresets = ctx.get('agentPresets') as unknown as AgentPresetsForEditor
29
+ }
30
+
31
+ async catalog(): Promise<PresetCatalog> {
32
+ if (this.agentPresets.remoteExportList !== undefined) {
33
+ const roster = await this.agentPresets.remoteExportList()
34
+ const presets = roster.presets
35
+ .filter(row => row.broken === undefined)
36
+ .map(row => ({
37
+ id: row.id,
38
+ name: row.name || row.id,
39
+ description: row.description ?? '',
40
+ isDefault: row.isDefault,
41
+ }))
42
+ return { presets, excludedCount: roster.presets.length - presets.length }
43
+ }
44
+ if (this.agentPresets.list !== undefined) {
45
+ const rows = await this.agentPresets.list()
46
+ const presets = rows
47
+ .filter(row => row.broken === undefined)
48
+ .map(row => ({
49
+ id: row.id,
50
+ name: row.name || row.id,
51
+ description: row.description ?? '',
52
+ isDefault: row.id === this.agentPresets.defaultId,
53
+ }))
54
+ return { presets, excludedCount: rows.length - presets.length }
55
+ }
56
+ throw new Error('preset-catalog-unavailable')
57
+ }
58
+
59
+ async tools(id: string): Promise<PresetToolCatalog> {
60
+ return readPresetToolCatalog(this.toolContext, id)
61
+ }
62
+
63
+ async prompts(id: string): Promise<PresetPromptCatalog> {
64
+ return readPresetPromptCatalog(this.toolContext, id)
65
+ }
66
+
67
+ async read(id: string): Promise<PresetDefinitionDocument> {
68
+ if (typeof id !== 'string' || !id.trim() || id.length > 256) throw new Error('invalid-preset-id')
69
+ const resolved = await this.agentPresets.resolve(id)
70
+ if (resolved.broken !== undefined) throw new Error('invalid-preset')
71
+ const doc = await this.agentPresets.readDocument(id)
72
+ return {
73
+ id,
74
+ name: doc.name || resolved.name || id,
75
+ description: doc.description ?? resolved.description ?? '',
76
+ composition: doc.content,
77
+ }
78
+ }
79
+ }
80
+
81
+ // Same decorator registration as the host, consumable by the Vitest transform.
82
+ function markRemoteMethod(methodName: 'catalog' | 'tools' | 'prompts' | 'read'): void {
83
+ const descriptor = Object.getOwnPropertyDescriptor(CodexPresetEditor.prototype, methodName)!
84
+ const initializers: Array<(this: object) => void> = []
85
+ const decorator = Remote(methodName) as unknown as (method: unknown, context: {
86
+ kind: 'method'; name: string; static: false; private: false; addInitializer(initializer: (this: object) => void): void
87
+ }) => void
88
+ decorator(descriptor.value, {
89
+ kind: 'method',
90
+ name: methodName,
91
+ static: false,
92
+ private: false,
93
+ addInitializer: initializer => { initializers.push(initializer) },
94
+ })
95
+ const receiver = Object.create(CodexPresetEditor.prototype) as object
96
+ for (const initializer of initializers) initializer.call(receiver)
97
+ }
98
+
99
+ for (const method of ['catalog', 'tools', 'prompts', 'read'] as const) markRemoteMethod(method)
100
+
101
+ export default CodexPresetEditor
@@ -0,0 +1,221 @@
1
+ /** Public, read-only preset prompt discovery. No private registry, Agent, or JS/YAML evaluation. */
2
+ import { randomUUID } from 'node:crypto'
3
+ import type { Context } from '@deepseek-ai/cordis'
4
+ import type {} from '@deepseek-ai/dsh-agent-preset-registry'
5
+ import { createScope } from '@deepseek-ai/dsh-scope'
6
+ import type { Scope, ScopeKey } from '@deepseek-ai/dsh-scope'
7
+ import { PERSONA_PREFIX_SECTION, PERSONA_SUFFIX_SECTION } from '@deepseek-ai/dsh-system-prompt'
8
+ import type { PromptSection } from '@deepseek-ai/dsh-system-prompt'
9
+ import { isMap, isScalar, isSeq, parseDocument, YAMLMap } from 'yaml'
10
+ import type { PresetPromptCatalog, PresetPromptEntry, PresetPromptName, PresetPromptOverride } from '../contracts/ui-contracts.ts'
11
+
12
+ interface Candidate {
13
+ name: PresetPromptName
14
+ label: string
15
+ module: string
16
+ order: number
17
+ complete: boolean
18
+ interpolate: boolean
19
+ literal?: string
20
+ reason?: string
21
+ }
22
+ export interface PresetPromptProbe {
23
+ readonly catalog: PresetPromptCatalog
24
+ readonly scope: ScopeKey
25
+ readonly modules: string
26
+ readonly definitions: ReadonlyMap<PresetPromptName, PromptSection>
27
+ }
28
+ export interface PreparedPromptOverride {
29
+ readonly scope: ScopeKey
30
+ readonly modules: string
31
+ readonly sections: readonly PromptSection[]
32
+ }
33
+
34
+ function literal(map: YAMLMap, key: string): unknown {
35
+ const node = map.get(key, true)
36
+ return isScalar(node) && !node.tag ? node.value : undefined
37
+ }
38
+
39
+ /** Native Persona's public source owns these exact names/placements/complete semantics. */
40
+ function candidates(content: string, placement: (name: 'DEPLOYMENT_PERSONA_PREFIX' | 'DEPLOYMENT_PERSONA_SUFFIX') => number) {
41
+ const doc = parseDocument(content, { strict: true, uniqueKeys: true, logLevel: 'silent' })
42
+ if (doc.errors.length || !isSeq(doc.contents)) throw new Error('invalid-preset-prompt-declaration')
43
+ const found: Candidate[] = []
44
+ const readonly: PresetPromptEntry[] = []
45
+ function visit(rows: unknown, parent = '', conditionalParent = false, isolatedParent = false): void {
46
+ if (!isSeq(rows)) return
47
+ for (const [index, row] of rows.items.entries()) {
48
+ if (!isMap(row) || literal(row, 'disabled') === true) continue
49
+ const module = literal(row, 'name')
50
+ const path = `${parent}/${String(literal(row, 'id') ?? index)}`
51
+ const conditionalRow = conditionalParent || row.has('disabled') && literal(row, 'disabled') === undefined
52
+ const isolation = row.get('isolate', true)
53
+ const isolated = isolatedParent || row.has('isolate') && (!isMap(isolation) || isolation.has('systemPrompt'))
54
+ let config: unknown = row.get('config', true)
55
+ if (isSeq(config)) { visit(config, path, conditionalRow, isolated); continue }
56
+ if (config === undefined && module === '@shuind/dsh-codex-harness') config = new YAMLMap()
57
+ if (typeof module !== 'string' || !isMap(config)) continue
58
+ if (module === '@deepseek-ai/dsh-persona') {
59
+ const completeNode = config.get('complete', true)
60
+ const complete = literal(config, 'complete')
61
+ const uncertain = conditionalRow || completeNode !== undefined && typeof complete !== 'boolean'
62
+ for (const [key, name, order, label] of [
63
+ ['prefix', PERSONA_PREFIX_SECTION, placement('DEPLOYMENT_PERSONA_PREFIX'), 'Persona'],
64
+ ['suffix', PERSONA_SUFFIX_SECTION, placement('DEPLOYMENT_PERSONA_SUFFIX'), 'Persona · suffix'],
65
+ ] as const) {
66
+ const text = literal(config, key)
67
+ const missingSuffix = key === 'suffix' && !config.has(key)
68
+ // Native Persona validates prefix/suffix to strings at mount, then
69
+ // registers static text. A !!js declaration is never evaluated here;
70
+ // its actual registered text is read by assemble and marker-verified.
71
+ const reason = isolated ? 'isolated-prompt-registry' : uncertain ? 'dynamic-declaration' : undefined
72
+ found.push({ name, label, module, order, complete: key === 'prefix' && complete === true, interpolate: true,
73
+ ...(typeof text === 'string' ? { literal: text } : missingSuffix ? { literal: '' } : {}),
74
+ ...(reason === undefined ? {} : { reason }) })
75
+ }
76
+ } else if (module === '@shuind/dsh-codex-harness' && literal(config, 'codexCore') !== false) {
77
+ found.push({ name: 'codex:base', label: 'Codex 操作提示词', module, order: 10, complete: false, interpolate: true,
78
+ ...(isolated ? { reason: 'isolated-prompt-registry' } : conditionalRow || config.has('codexCore') && literal(config, 'codexCore') === undefined ? { reason: 'dynamic-declaration' } : {}) })
79
+ } else {
80
+ // Unknown field-to-section mappings are not editable just because their
81
+ // spelling resembles a prompt. Never return a !!js expression as prose.
82
+ for (const key of ['prefix', 'suffix', 'text', 'section', 'prompt', 'systemPrompt', 'instructions']) {
83
+ if (!config.has(key) || module === '@deepseek-ai/dsh-plan-mode') continue
84
+ const text = literal(config, key)
85
+ readonly.push({ name: `declaration:${path}:${key}`, label: `${module} · ${key}`,
86
+ text: typeof text === 'string' ? text : '', editable: false,
87
+ reason: typeof text === 'string' ? 'unknown-section-contract' : 'dynamic-declaration' })
88
+ }
89
+ }
90
+ }
91
+ }
92
+ visit(doc.contents)
93
+ return { found, readonly }
94
+ }
95
+
96
+ function moduleSignature(rows: readonly { moduleName: string; baseUrl?: string; useHostBase: boolean }[]): string {
97
+ return JSON.stringify(rows.map(row => [row.moduleName, row.baseUrl ?? '', row.useHostBase]))
98
+ }
99
+
100
+ const probeCache = new WeakMap<ScopeKey, Map<string, PresetPromptProbe>>()
101
+
102
+ async function runProbePresetPrompts(
103
+ ctx: Context,
104
+ preset: string,
105
+ expectedScope: ScopeKey | undefined,
106
+ useCache: boolean,
107
+ ): Promise<PresetPromptProbe> {
108
+ if (typeof preset !== 'string' || !preset.trim() || preset.length > 256) throw new Error('invalid-preset-id')
109
+ const registry = ctx.get('agentPresets')
110
+ const prompt = ctx.get('systemPrompt')
111
+ if (registry === undefined || prompt === undefined || typeof registry.acquireScope !== 'function'
112
+ || typeof registry.readDocument !== 'function' || typeof registry.inspectCompositions !== 'function') {
113
+ throw new Error('preset-prompt-catalog-unavailable')
114
+ }
115
+ const document = await registry.readDocument(preset)
116
+ const lease = await registry.acquireScope(preset)
117
+ let view: Scope | undefined
118
+ try {
119
+ if (expectedScope !== undefined && lease.key !== expectedScope) throw new Error('preset-prompt-revision-mismatch')
120
+ const key = {}
121
+ view = createScope(ctx, key, { parent: lease.key })
122
+ const inspection = registry.inspectCompositions(view.ctx)
123
+ if (inspection.length !== 1 || inspection[0]?.id !== preset) throw new Error('preset-prompt-revision-unavailable')
124
+ const modules = moduleSignature(inspection[0].modules)
125
+ const cacheKey = `${preset}\0${modules}\0${document.content}`
126
+ if (useCache) {
127
+ const cached = probeCache.get(lease.key)?.get(cacheKey)
128
+ if (cached !== undefined) return cached
129
+ }
130
+ const active = new Set(inspection[0].modules.map(row => row.moduleName))
131
+ const declared = candidates(document.content, name => prompt.getSectionOrder(name))
132
+ const definitions = new Map<PresetPromptName, PromptSection>()
133
+ const sections: PresetPromptEntry[] = []
134
+ // Show the actual effective original, including legacy own-plugin rewrites.
135
+ // Only marker validation suppresses those rewrites; no model runs here.
136
+ let baseline
137
+ try { baseline = await prompt.assemble({ scope: key }) }
138
+ catch {
139
+ return { scope: lease.key, modules, definitions, catalog: { preset, sections: [
140
+ ...declared.found.map(row => ({ name: row.name, label: row.label, text: row.literal ?? '', editable: false, reason: 'assembly-unavailable' })),
141
+ ...declared.readonly,
142
+ ].slice(0, 200) } }
143
+ }
144
+ const seen = new Set<string>()
145
+ for (const row of declared.found) {
146
+ if (seen.has(row.name)) continue
147
+ seen.add(row.name)
148
+ const actual = baseline.sections.find(section => section.name === row.name)
149
+ let reason = row.reason
150
+ ?? (!active.has(row.module) ? 'inactive-contribution' : undefined)
151
+ ?? (declared.found.filter(candidate => candidate.name === row.name).length !== 1 ? 'ambiguous-contribution' : undefined)
152
+ ?? (actual === undefined ? 'not-effective-or-complete-suppressed' : undefined)
153
+ if (reason === undefined && row.complete && (baseline.sections.length !== 1 || baseline.sections[0]?.name !== row.name)) reason = 'complete-contract-mismatch'
154
+ if (reason === undefined) {
155
+ const marker = `preset-prompt-probe:${randomUUID()}`
156
+ const undo = view.ctx.get('systemPrompt')!.section({ name: row.name, order: row.order, complete: row.complete,
157
+ interpolate: row.interpolate, text: marker })
158
+ try {
159
+ const probed = await prompt.assemble({ scope: key, codexPresetPromptProbe: true })
160
+ if (probed.sections.find(section => section.name === row.name)?.text !== marker
161
+ || JSON.stringify(probed.sections.map(section => section.name)) !== JSON.stringify(baseline.sections.map(section => section.name))
162
+ || row.complete && (probed.sections.length !== 1 || probed.sections[0]?.name !== row.name)) reason = 'not-directly-overridable'
163
+ } catch { reason = 'not-directly-overridable' }
164
+ finally { undo() }
165
+ }
166
+ const text = actual?.text ?? row.literal ?? ''
167
+ if (text.length > 1_000_000) reason = 'prompt-too-large'
168
+ sections.push({ name: row.name, label: row.label, text: text.slice(0, 1_000_000), editable: reason === undefined,
169
+ order: row.order, complete: row.complete, interpolate: row.interpolate,
170
+ ...(reason === undefined ? {} : { reason }) })
171
+ if (reason === undefined) definitions.set(row.name, { name: row.name, order: row.order, complete: row.complete,
172
+ interpolate: row.interpolate, text })
173
+ }
174
+ for (const row of baseline.sections) {
175
+ if (!seen.has(row.name)) sections.push({ name: row.name, label: row.name, text: row.text.slice(0, 1_000_000), editable: false, reason: 'unknown-or-host-owned-section' })
176
+ }
177
+ sections.push(...declared.readonly)
178
+ if ((await registry.readDocument(preset)).content !== document.content) throw new Error('preset-prompt-revision-mismatch')
179
+ const probe: PresetPromptProbe = { scope: lease.key, modules, definitions, catalog: { preset, sections: sections.slice(0, 200) } }
180
+ if (useCache) {
181
+ let byKey = probeCache.get(lease.key)
182
+ if (byKey === undefined) {
183
+ byKey = new Map()
184
+ probeCache.set(lease.key, byKey)
185
+ }
186
+ byKey.set(cacheKey, probe)
187
+ }
188
+ return probe
189
+ } finally {
190
+ try { await view?.dispose() }
191
+ finally { await lease[Symbol.asyncDispose]() }
192
+ }
193
+ }
194
+
195
+ /** The opaque scope identity is retained only for runtime revision validation, not sent over RPC. */
196
+ export async function probePresetPrompts(ctx: Context, preset: string, expectedScope?: ScopeKey): Promise<PresetPromptProbe> {
197
+ return runProbePresetPrompts(ctx, preset, expectedScope, false)
198
+ }
199
+
200
+ /** Cached variant keyed by live scope identity, active modules, and document content. */
201
+ export async function probePresetPromptsCached(ctx: Context, preset: string, expectedScope?: ScopeKey): Promise<PresetPromptProbe> {
202
+ return runProbePresetPrompts(ctx, preset, expectedScope, true)
203
+ }
204
+
205
+ export async function readPresetPromptCatalog(ctx: Context, preset: string): Promise<PresetPromptCatalog> {
206
+ return (await probePresetPrompts(ctx, preset)).catalog
207
+ }
208
+
209
+ export function preparePromptOverrides(probe: PresetPromptProbe, overrides: readonly PresetPromptOverride[]): PreparedPromptOverride {
210
+ const sections = overrides.map(override => {
211
+ const original = probe.definitions.get(override.name)
212
+ if (original === undefined) throw new Error(`unsupported-preset-prompt-override: ${override.name}`)
213
+ return { ...original, text: override.text }
214
+ })
215
+ return { scope: probe.scope, modules: probe.modules, sections }
216
+ }
217
+
218
+ export function matchesPromptRevision(ctx: Context, preset: string, prepared: PreparedPromptOverride): boolean {
219
+ const inspection = ctx.get('agentPresets')?.inspectCompositions(ctx)
220
+ return inspection?.length === 1 && inspection[0]?.id === preset && moduleSignature(inspection[0].modules) === prepared.modules
221
+ }