@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,103 @@
1
+ /** Shared host-side Codex settings contract, Host reader, and GPT route matcher. */
2
+
3
+ import type { Context } from '@deepseek-ai/cordis'
4
+ import z from '@deepseek-ai/schemastery'
5
+ import type { SettingsNamespace } from '@deepseek-ai/dsh-settings'
6
+ import { CODEX_CONTEXT_MAX } from './ui-contracts.ts'
7
+ import {
8
+ DEFAULT_CODEX_PERSONA,
9
+ DEFAULT_CODEX_SYSTEM_PROMPT,
10
+ DEFAULT_DSH_CORE_SOURCE_PROMPT,
11
+ DEFAULT_DSH_CORE_WEB_PROMPT,
12
+ } from './prompt.ts'
13
+
14
+ /** Live Codex controls shared by the Web UI and agent layer. */
15
+ export const CODEX_SETTINGS_NAMESPACE = 'codex' as SettingsNamespace
16
+
17
+ export interface CodexSettings {
18
+ /** Use the Responses priority service tier for GPT requests. */
19
+ fast: boolean
20
+ /** Show the Fast mode switch in the conversation composer. */
21
+ fastModeControlEnabled: boolean
22
+ /** Show the quick context-window control in the conversation composer. */
23
+ contextWindowControlEnabled: boolean
24
+ /** Optional context capacity override, in tokens. */
25
+ contextWindow?: number
26
+ /** Deployment Persona template; supports the host's prompt variables. */
27
+ persona?: string
28
+ /** DSH Core source-checkout guidance template. */
29
+ harnessSourcePrompt?: string
30
+ /** DSH Core Web GUI guidance template. */
31
+ webSurfacePrompt?: string
32
+ /** Complete plugin-owned Codex operating prompt. */
33
+ systemPrompt?: string
34
+ /** Inject the plugin-owned Codex operating prompt. */
35
+ promptEnabled: boolean
36
+ /** Deprecated compatibility baseline, snapshotted into future Agent tool plans. */
37
+ terminalToolsEnabled: boolean
38
+ /** Deprecated tool baseline; also retains the legacy JSON/custom wire-format preference. */
39
+ patchToolEnabled: boolean
40
+ /** Deprecated compatibility baseline, not a live veto of a compiled plan. */
41
+ planToolEnabled: boolean
42
+ /** Upgrade local web_search declarations to the hosted Responses tool. */
43
+ hostedWebSearchEnabled: boolean
44
+ /** Prefer the provider's Responses compact endpoint. */
45
+ remoteCompactionEnabled: boolean
46
+ /** Show the Codex request/compaction activity indicator. */
47
+ activityIndicatorEnabled: boolean
48
+ }
49
+
50
+ /** Default settings exposed even before a Codex session is opened. */
51
+ export const CODEX_SETTINGS_ENTRY: CodexSettings = {
52
+ fast: false,
53
+ fastModeControlEnabled: true,
54
+ contextWindowControlEnabled: true,
55
+ persona: DEFAULT_CODEX_PERSONA,
56
+ harnessSourcePrompt: DEFAULT_DSH_CORE_SOURCE_PROMPT,
57
+ webSurfacePrompt: DEFAULT_DSH_CORE_WEB_PROMPT,
58
+ systemPrompt: DEFAULT_CODEX_SYSTEM_PROMPT,
59
+ promptEnabled: true,
60
+ terminalToolsEnabled: true,
61
+ patchToolEnabled: true,
62
+ planToolEnabled: true,
63
+ hostedWebSearchEnabled: true,
64
+ remoteCompactionEnabled: true,
65
+ activityIndicatorEnabled: true,
66
+ }
67
+
68
+ export const CODEX_SETTINGS_SCHEMA: z<CodexSettings> = z.object({
69
+ fast: z.boolean().default(false),
70
+ fastModeControlEnabled: z.boolean().default(true),
71
+ contextWindowControlEnabled: z.boolean().default(true),
72
+ contextWindow: z.number().step(1).min(1).max(CODEX_CONTEXT_MAX).hidden(),
73
+ persona: z.string().default(DEFAULT_CODEX_PERSONA),
74
+ harnessSourcePrompt: z.string().default(DEFAULT_DSH_CORE_SOURCE_PROMPT),
75
+ webSurfacePrompt: z.string().default(DEFAULT_DSH_CORE_WEB_PROMPT),
76
+ systemPrompt: z.string().default(DEFAULT_CODEX_SYSTEM_PROMPT),
77
+ promptEnabled: z.boolean().default(true),
78
+ terminalToolsEnabled: z.boolean().default(true).hidden(),
79
+ patchToolEnabled: z.boolean().default(true).hidden(),
80
+ planToolEnabled: z.boolean().default(true).hidden(),
81
+ hostedWebSearchEnabled: z.boolean().default(true),
82
+ remoteCompactionEnabled: z.boolean().default(true),
83
+ activityIndicatorEnabled: z.boolean().default(true),
84
+ })
85
+
86
+ interface SettingsReader {
87
+ describe?: () => Array<{ ns: string; value: unknown }>
88
+ }
89
+
90
+ /** Host-only reads: never expose the unredacted provider configuration to clients. */
91
+ export function readHostSettings<T>(ctx: Context, namespace: string): T | undefined {
92
+ if (namespace === 'codex') {
93
+ const preferences = ctx.get('codexPreferences') as { current(): T } | undefined
94
+ if (preferences !== undefined) return preferences.current()
95
+ }
96
+ const settings = ctx.get('settings') as SettingsReader | undefined
97
+ return settings?.describe?.().find(row => row.ns === namespace)?.value as T | undefined
98
+ }
99
+
100
+ /** Match GPT / ChatGPT model ids that consume Codex wire & capacity extensions. */
101
+ export function isGptModel(model: unknown): model is string {
102
+ return typeof model === 'string' && /(?:^|\/)(?:gpt|chatgpt)(?:[-_.]|\d|$)/i.test(model)
103
+ }
@@ -0,0 +1,93 @@
1
+ /** Client-safe tool choices. The concrete adapters remain Host-owned. */
2
+ import type { PresetPromptOverride } from './ui-contracts.ts'
3
+ export { PRESET_PROMPT_NAMES } from './ui-contracts.ts'
4
+ export type { PresetPromptName, PresetPromptOverride, PresetPromptEntry, PresetPromptCatalog } from './ui-contracts.ts'
5
+
6
+ export type ToolAction = 'keep' | 'hide' | 'defer' | 'codex-exec' | 'codex-plan' | 'codex-patch'
7
+ export type ReplacementAction = Extract<ToolAction, 'codex-exec' | 'codex-plan' | 'codex-patch'>
8
+ export type CodexCapability = 'terminalToolsEnabled' | 'planToolEnabled' | 'patchToolEnabled'
9
+ export type LegacyCapabilities = Partial<Record<CodexCapability, boolean>>
10
+
11
+ /** Ownership metadata, not a promise that `keep` admits a locally disabled tool. */
12
+ export interface CodexToolMetadata {
13
+ readonly capability: CodexCapability
14
+ readonly presetEnabled: boolean
15
+ /** An explicit old per-preset boolean already overrode the shared baseline. */
16
+ readonly presetOverridesLegacy?: boolean
17
+ }
18
+
19
+ export interface ToolActionContext {
20
+ readonly legacyCapabilities?: LegacyCapabilities
21
+ readonly codexTool?: CodexToolMetadata
22
+ readonly defaultDeferred?: boolean
23
+ }
24
+
25
+ export interface ToolActionRule {
26
+ readonly name: string
27
+ readonly action: ToolAction
28
+ }
29
+
30
+ export interface ToolPolicyRule {
31
+ readonly preset: string
32
+ readonly allow?: readonly string[]
33
+ readonly deny?: readonly string[]
34
+ /** Legacy category defaults; new UI rules explicitly set replaceShell/replacePlan to false. */
35
+ readonly replaceShell?: boolean
36
+ readonly replacePlan?: boolean
37
+ readonly replacePatch?: boolean
38
+ /** Explicit per-source choices override the legacy masks and category defaults. */
39
+ readonly tools?: readonly ToolActionRule[]
40
+ /** Exact reviewed section replacements, scoped to future Agents of this preset. */
41
+ readonly promptOverrides?: readonly PresetPromptOverride[]
42
+ }
43
+
44
+ export interface PresetToolReplacement {
45
+ readonly action: ReplacementAction
46
+ readonly tools: readonly string[]
47
+ readonly available: boolean
48
+ readonly reason?: 'conditional' | 'target-exists'
49
+ }
50
+
51
+ export interface PresetToolEntry {
52
+ readonly name: string
53
+ readonly description: string
54
+ readonly conditional: boolean
55
+ readonly defaultDeferred?: boolean
56
+ readonly replacements: readonly PresetToolReplacement[]
57
+ readonly codexTool?: CodexToolMetadata
58
+ }
59
+
60
+ export interface PresetToolCatalog {
61
+ readonly preset: string
62
+ /** Registration snapshot, not admission for a particular Agent/model step. */
63
+ readonly registeredOnly: true
64
+ readonly tools: readonly PresetToolEntry[]
65
+ readonly legacyCapabilities?: LegacyCapabilities
66
+ }
67
+
68
+ /** Legacy configuration remains a baseline, never a live second veto of an explicit choice. */
69
+ export function legacyToolAction(rule: ToolPolicyRule | undefined, name: string, context: ToolActionContext = {}): ToolAction {
70
+ let action: ToolAction = 'keep'
71
+ if (rule !== undefined) {
72
+ if ((rule.allow !== undefined && !rule.allow.includes(name)) || rule.deny?.includes(name)) return 'hide'
73
+ if ((name === 'bash' || name === 'pwsh') && rule.replaceShell !== false) action = 'codex-exec'
74
+ if (name === 'todo_write' && rule.replacePlan !== false) action = 'codex-plan'
75
+ if ((name === 'edit' || name === 'write') && rule.replacePatch === true) action = 'codex-patch'
76
+ }
77
+ if (action === 'keep' && context.defaultDeferred === true) action = 'defer'
78
+ const capability = context.codexTool?.capability
79
+ ?? (action === 'codex-exec' ? 'terminalToolsEnabled'
80
+ : action === 'codex-plan' ? 'planToolEnabled'
81
+ : action === 'codex-patch' ? 'patchToolEnabled'
82
+ : undefined)
83
+ // Only owned definitions and chosen Codex adapters consume the legacy baseline.
84
+ // A third-party tool with the same name does not become a Codex capability.
85
+ const presetOverride = context.codexTool?.presetOverridesLegacy === true && context.codexTool.presetEnabled
86
+ if (!presetOverride && capability !== undefined && context.legacyCapabilities?.[capability] === false) return 'hide'
87
+ return action
88
+ }
89
+
90
+ /** Policy action only: `keep` still respects the original preset's local enablement. */
91
+ export function effectiveToolAction(rule: ToolPolicyRule | undefined, name: string, context: ToolActionContext = {}): ToolAction {
92
+ return rule?.tools?.find(tool => tool.name === name)?.action ?? legacyToolAction(rule, name, context)
93
+ }
@@ -0,0 +1,173 @@
1
+ /** Browser-safe shared constants, activity shapes, and read-only preset contracts. */
2
+
3
+ /** User-selectable Codex context controls use whole K-token units. */
4
+ export const CODEX_CONTEXT_UNIT = 1_000
5
+ export const CODEX_CONTEXT_MIN = 16_000
6
+ export const CODEX_CONTEXT_MAX = 1_000_000
7
+ export const OPENAI_CODEX_PROVIDER = 'openai-codex'
8
+ export const OPENAI_CODEX_SETTINGS_NAMESPACE = 'llm-openai-codex'
9
+ export const OPENAI_CODEX_MODEL_CATALOG_PATH = '/plugins/dsh-codex-connect/models'
10
+
11
+ export interface ContextWindowBounds {
12
+ readonly defaultTokens?: number
13
+ readonly maxTokens: number
14
+ }
15
+
16
+ export const OPENAI_CODEX_MODEL_LIMITS: Readonly<Record<string, { readonly defaultTokens: number; readonly maxTokens: number }>> = {
17
+ 'gpt-6.1-sol': { defaultTokens: 500_000, maxTokens: 872_000 },
18
+ 'gpt-6.1-terra': { defaultTokens: 500_000, maxTokens: 872_000 },
19
+ 'gpt-6-astra': { defaultTokens: 272_000, maxTokens: 872_000 },
20
+ 'gpt-6-sol': { defaultTokens: 272_000, maxTokens: 872_000 },
21
+ 'gpt-6-luna': { defaultTokens: 272_000, maxTokens: 872_000 },
22
+ 'gpt-5.6-sol': { defaultTokens: 272_000, maxTokens: 872_000 },
23
+ 'gpt-5.6-terra': { defaultTokens: 272_000, maxTokens: 872_000 },
24
+ 'gpt-5.6-luna': { defaultTokens: 272_000, maxTokens: 872_000 },
25
+ 'gpt-5.4': { defaultTokens: 272_000, maxTokens: 1_000_000 },
26
+ 'gpt-5.5': { defaultTokens: 272_000, maxTokens: 272_000 },
27
+ 'gpt-5.4-mini': { defaultTokens: 272_000, maxTokens: 272_000 },
28
+ }
29
+
30
+ const CONTEXT_PRESET_TIERS: readonly number[] = [64_000, 128_000, 200_000, 272_000, 400_000, 500_000, 872_000, 1_000_000]
31
+
32
+ export function resolveContextWindowBounds(
33
+ provider: string | undefined,
34
+ model: string | undefined,
35
+ dynamicCatalog?: Readonly<Record<string, { readonly defaultTokens: number; readonly maxTokens: number }>>,
36
+ ): ContextWindowBounds {
37
+ if (provider === OPENAI_CODEX_PROVIDER) {
38
+ return (model !== undefined ? dynamicCatalog?.[model] ?? OPENAI_CODEX_MODEL_LIMITS[model] : undefined)
39
+ ?? { defaultTokens: 272_000, maxTokens: 272_000 }
40
+ }
41
+ return { maxTokens: CODEX_CONTEXT_MAX }
42
+ }
43
+
44
+ export function formatCompactTokens(tokens: number): string {
45
+ if (tokens >= 1_000) {
46
+ return tokens % 1_000 === 0
47
+ ? `${tokens / 1_000}k`
48
+ : `${(tokens / 1_000).toFixed(1).replace(/\.0$/, '')}k`
49
+ }
50
+ return `${tokens}`
51
+ }
52
+
53
+ export function contextPresetsForBounds(bounds: ContextWindowBounds): number[] {
54
+ const filtered = CONTEXT_PRESET_TIERS.filter(v => v <= bounds.maxTokens && v !== bounds.defaultTokens)
55
+ if (bounds.maxTokens > 0 && bounds.maxTokens !== bounds.defaultTokens && !filtered.includes(bounds.maxTokens)) {
56
+ filtered.push(bounds.maxTokens)
57
+ }
58
+ return filtered.sort((a, b) => a - b)
59
+ }
60
+
61
+ export function parseCustomContextInput(raw: string, maxTokens: number): number | undefined {
62
+ const trimmed = raw.trim()
63
+ if (trimmed.length === 0) return undefined
64
+ const match = /^(\d+(?:\.\d+)?)\s*(k)?$/i.exec(trimmed)
65
+ if (match === null) return undefined
66
+ const num = Number(match[1])
67
+ if (!Number.isFinite(num) || num <= 0) return undefined
68
+ const tokens = match[2] !== undefined
69
+ ? Math.round(num * CODEX_CONTEXT_UNIT)
70
+ : Number.isSafeInteger(num) && num > Math.floor(maxTokens / CODEX_CONTEXT_UNIT) && num <= maxTokens
71
+ ? num
72
+ : Math.round(num * CODEX_CONTEXT_UNIT)
73
+ return Number.isSafeInteger(tokens) && tokens >= Math.min(CODEX_CONTEXT_MIN, maxTokens) && tokens <= maxTokens ? tokens : undefined
74
+ }
75
+
76
+ export function nextOpenAICodexOverrides(
77
+ currentValue: Readonly<Record<string, unknown>> | undefined,
78
+ baseValue: Readonly<Record<string, unknown>> | undefined,
79
+ modelId: string,
80
+ tokens: number | undefined,
81
+ ): Record<string, number | null> | undefined {
82
+ const next: Record<string, number | null> = {}
83
+ if (currentValue !== undefined) {
84
+ for (const [id, value] of Object.entries(currentValue)) {
85
+ if (id.length > 0 && id.trim() === id && (value === null || (typeof value === 'number' && Number.isSafeInteger(value) && value > 0))) {
86
+ next[id] = value
87
+ }
88
+ }
89
+ }
90
+ if (tokens !== undefined) {
91
+ next[modelId] = tokens
92
+ return next
93
+ }
94
+ if (typeof baseValue?.[modelId] === 'number') next[modelId] = null
95
+ else delete next[modelId]
96
+ return Object.keys(next).length === 0 ? undefined : next
97
+ }
98
+
99
+ /** Pure client/host-shared type for the Codex activity projection value. */
100
+ export type CodexActivity = {
101
+ activity: 'compaction' | 'requesting-model' | 'model-reply'
102
+ startedAt: number
103
+ }
104
+
105
+ /** Client-safe read-only preset catalog and definition types for Harness 0.2.2+. */
106
+ export interface PresetCatalogRow {
107
+ readonly id: string
108
+ readonly name: string
109
+ readonly description: string
110
+ readonly isDefault: boolean
111
+ }
112
+
113
+ export interface PresetCatalog {
114
+ readonly presets: readonly PresetCatalogRow[]
115
+ readonly excludedCount: number
116
+ }
117
+
118
+ export interface PresetDefinitionDocument {
119
+ readonly id: string
120
+ readonly name: string
121
+ readonly description: string
122
+ readonly composition: string
123
+ }
124
+
125
+ /** Client-safe current-preset prompt catalog; editable targets have reviewed native contracts. */
126
+ export const PRESET_PROMPT_NAMES = ['deployment:persona-prefix', 'deployment:persona-suffix', 'codex:base'] as const
127
+ export type PresetPromptName = typeof PRESET_PROMPT_NAMES[number]
128
+
129
+ export interface PresetPromptOverride {
130
+ readonly name: PresetPromptName
131
+ readonly text: string
132
+ }
133
+
134
+ export interface PresetPromptEntry {
135
+ readonly name: string
136
+ readonly label: string
137
+ readonly text: string
138
+ readonly editable: boolean
139
+ readonly order?: number
140
+ readonly complete?: boolean
141
+ readonly interpolate?: boolean
142
+ readonly reason?: string
143
+ }
144
+
145
+ export interface ModelDirectorySnapshot {
146
+ readonly status?: string
147
+ readonly current?: { readonly provider?: string; readonly model?: string } | undefined
148
+ }
149
+
150
+ export interface ModelDirectoryStore {
151
+ subscribe(listener: () => void): () => void
152
+ getSnapshot(): ModelDirectorySnapshot | undefined
153
+ }
154
+
155
+ export interface CodexConnectSnapshot {
156
+ readonly status: string
157
+ readonly writable: boolean
158
+ readonly overrides?: Readonly<Record<string, number | null>> | undefined
159
+ readonly baseOverrides?: Readonly<Record<string, number | null>> | undefined
160
+ readonly nativeCompaction?: boolean | undefined
161
+ }
162
+
163
+ export interface CodexConnectScope {
164
+ getSnapshot(): CodexConnectSnapshot
165
+ subscribe(listener: () => void): () => void
166
+ setModelOverride(modelId: string, tokens: number | undefined): Promise<void>
167
+ setNativeCompaction?(enabled: boolean): Promise<void>
168
+ }
169
+
170
+ export interface PresetPromptCatalog {
171
+ readonly preset: string
172
+ readonly sections: readonly PresetPromptEntry[]
173
+ }
@@ -0,0 +1,14 @@
1
+ /** Client plugin entry for DSH 0.2.2+ Web/Desktop ConfigForms. */
2
+ import type { Context } from '@deepseek-ai/cordis'
3
+ import { apply as applyDesktop } from '../client/desktop.tsx'
4
+
5
+ export const inject = [
6
+ 'commandUi', 'sessions', 'slots', 'locale',
7
+ 'remote',
8
+ ]
9
+
10
+ export function apply(ctx: Context): void {
11
+ ctx.inject(['configForms'], host => applyDesktop(host))
12
+ }
13
+
14
+ export default { inject, apply }
@@ -0,0 +1,256 @@
1
+ /** Codex-aware `/compact` command with an optional transport preference. */
2
+
3
+ import type { Context } from '@deepseek-ai/cordis'
4
+ import { ManualCompactionError } from '@deepseek-ai/dsh-compaction'
5
+ import type { Agent } from '@deepseek-ai/dsh-agent'
6
+ import { readHostSettings } from '../contracts/settings.ts'
7
+ import { OPENAI_CODEX_PROVIDER, OPENAI_CODEX_SETTINGS_NAMESPACE } from '../contracts/ui-contracts.ts'
8
+ import { runCodexCompactionMode, type CodexCompactionMode } from './compaction.ts'
9
+
10
+ const USAGE = 'Usage: /compact [remote|local]'
11
+
12
+ interface CommandInvocation {
13
+ commandId: string
14
+ agent: Agent
15
+ rawInput: string
16
+ signal: AbortSignal
17
+ }
18
+
19
+ type CommandResult = {
20
+ kind: 'success'
21
+ text?: string
22
+ sourceEventSeq?: number
23
+ } | {
24
+ kind: 'error'
25
+ text: string
26
+ }
27
+
28
+ interface CommandDefinition {
29
+ name: string
30
+ description: string
31
+ input: { hint: string }
32
+ handler: (invocation: CommandInvocation) => CommandResult | Promise<CommandResult>
33
+ }
34
+
35
+ interface CommandsRuntime {
36
+ register(definition: CommandDefinition): () => void
37
+ }
38
+
39
+ interface CompactionService {
40
+ compactNow: NonNullable<Context['compaction']>['compactNow']
41
+ }
42
+
43
+ interface AgentPresetsLookup {
44
+ serviceFor?: (agent: unknown, name: string) => unknown
45
+ }
46
+
47
+ type CommandContext = Context & { commands: CommandsRuntime }
48
+
49
+ /** Convert expected backend failures into the same concise command results as DSH Core. */
50
+ function expectedFailure(error: ManualCompactionError): CommandResult {
51
+ switch (error.code) {
52
+ case 'busy':
53
+ return { kind: 'error', text: 'Compaction is unavailable because this process has an active compaction, or the agent is not idle.' }
54
+ case 'cancelled':
55
+ return { kind: 'error', text: 'Compaction cancelled.' }
56
+ case 'changed':
57
+ return { kind: 'error', text: 'Compaction could not replace the selected history because it changed. The conversation is unchanged.' }
58
+ case 'summary':
59
+ return { kind: 'error', text: 'Compaction could not produce a useful summary. The conversation is unchanged; the attempt is recorded in the session log.' }
60
+ case 'commit':
61
+ return { kind: 'error', text: 'Compaction did not finish cleanly; inspect the current session state before retrying.' }
62
+ case 'persistence':
63
+ return { kind: 'error', text: 'Compaction finished, but the session could not be saved.' }
64
+ default:
65
+ return { kind: 'error', text: `Unknown compaction failure: ${String(error.code)}` }
66
+ }
67
+ }
68
+
69
+ function modeOf(rawInput: string): CodexCompactionMode | undefined | 'invalid' {
70
+ const value = rawInput.trim().toLowerCase()
71
+ if (value === '') return undefined
72
+ if (value === 'remote' || value === 'local') return value
73
+ return 'invalid'
74
+ }
75
+
76
+ function resolveCompactionService(hostCtx: Context, agent: Agent): CompactionService | undefined {
77
+ const fromPreset = (hostCtx as unknown as {
78
+ get?: (name: string) => AgentPresetsLookup | undefined
79
+ }).get?.('agentPresets')?.serviceFor?.(agent, 'compaction') as CompactionService | undefined
80
+ if (fromPreset?.compactNow !== undefined) return fromPreset
81
+
82
+ const fromAgent = (agent as unknown as {
83
+ ctx?: { get?: (name: string) => CompactionService | undefined }
84
+ }).ctx?.get?.('compaction')
85
+ if (fromAgent?.compactNow !== undefined) return fromAgent
86
+
87
+ const fromHost = (hostCtx as unknown as {
88
+ get?: (name: string) => CompactionService | undefined
89
+ }).get?.('compaction') ?? (hostCtx as unknown as { compaction?: CompactionService }).compaction
90
+ return fromHost?.compactNow !== undefined ? fromHost : undefined
91
+ }
92
+
93
+ function needsCodexConnectRemoteHint(
94
+ hostCtx: Context,
95
+ agent: Agent,
96
+ mode: CodexCompactionMode | undefined,
97
+ ): boolean {
98
+ if (mode !== 'remote') return false
99
+ const agentRef = agent as unknown as {
100
+ session?: { requestHeader?: () => { config?: { provider?: unknown } } | undefined }
101
+ model?: { current?: () => { provider?: unknown } | undefined }
102
+ }
103
+ const provider = agentRef.session?.requestHeader?.()?.config?.provider ?? agentRef.model?.current?.()?.provider
104
+ if (provider !== OPENAI_CODEX_PROVIDER) return false
105
+ const descriptors = (hostCtx as unknown as {
106
+ get?: (name: string) => { describe?: () => Array<{ ns: string; value?: unknown }> } | undefined
107
+ }).get?.('settings')?.describe?.()
108
+ if (descriptors === undefined || !descriptors.some(d => d.ns === OPENAI_CODEX_SETTINGS_NAMESPACE)) return false
109
+ const connectSettings = readHostSettings<{ enableNativeCompaction?: boolean }>(
110
+ hostCtx,
111
+ OPENAI_CODEX_SETTINGS_NAMESPACE,
112
+ )
113
+ return connectSettings?.enableNativeCompaction !== true
114
+ }
115
+
116
+ async function ensureCodexConnectRemoteCompaction(
117
+ hostCtx: Context,
118
+ agent: Agent,
119
+ mode: CodexCompactionMode | undefined,
120
+ ): Promise<boolean> {
121
+ if (!needsCodexConnectRemoteHint(hostCtx, agent, mode)) return false
122
+ const settings = (hostCtx as unknown as {
123
+ get?: (name: string) => { update?: (ns: string, patch: Record<string, unknown>) => Promise<void> } | undefined
124
+ }).get?.('settings')
125
+ if (typeof settings?.update !== 'function') return true
126
+ try {
127
+ await settings.update(OPENAI_CODEX_SETTINGS_NAMESPACE, { enableNativeCompaction: true })
128
+ return needsCodexConnectRemoteHint(hostCtx, agent, mode)
129
+ } catch {
130
+ return true
131
+ }
132
+ }
133
+
134
+ async function executeCompact(hostCtx: Context, invocation: CommandInvocation): Promise<CommandResult> {
135
+ const mode = modeOf(invocation.rawInput)
136
+ if (mode === 'invalid') return { kind: 'error', text: USAGE }
137
+ const compaction = resolveCompactionService(hostCtx, invocation.agent)
138
+ if (compaction === undefined) {
139
+ return { kind: 'error', text: 'Compaction is unavailable because no compaction service is configured for this session.' }
140
+ }
141
+ const needsHint = await ensureCodexConnectRemoteCompaction(hostCtx, invocation.agent, mode)
142
+ const compact = () => compaction.compactNow(
143
+ invocation.agent,
144
+ invocation.signal,
145
+ invocation.commandId as Parameters<NonNullable<Context['compaction']>['compactNow']>[2],
146
+ )
147
+ try {
148
+ const result = mode === undefined ? await compact() : await runCodexCompactionMode(mode, compact)
149
+ if (result === null) return { kind: 'success', text: 'No compactable history yet.' }
150
+ const suffix = needsHint
151
+ ? '; enable Native Compaction in Codex Connect settings for remote mode'
152
+ : ''
153
+ return {
154
+ kind: 'success',
155
+ text: `Compacted ${result.shadowedSeqs.length} history items (~${result.shadowedTokenCount} tokens${suffix}).`,
156
+ sourceEventSeq: result.summarySeq,
157
+ }
158
+ } catch (error) {
159
+ if (invocation.signal.aborted) return { kind: 'error', text: 'Compaction cancelled.' }
160
+ if (error instanceof ManualCompactionError) return expectedFailure(error)
161
+ throw error
162
+ }
163
+ }
164
+
165
+ function createCompactDefinition(hostCtx: Context, active: Set<Promise<CommandResult>>): CommandDefinition {
166
+ const handler = (invocation: CommandInvocation): Promise<CommandResult> => {
167
+ const operation = executeCompact(hostCtx, invocation)
168
+ active.add(operation)
169
+ const retire = (): void => { active.delete(operation) }
170
+ operation.then(retire, retire)
171
+ return operation
172
+ }
173
+ return {
174
+ name: 'compact',
175
+ description: 'Compact older conversation history, optionally using remote or local mode',
176
+ input: { hint: '[remote|local]' },
177
+ handler,
178
+ }
179
+ }
180
+
181
+ function mountPerAgentCommands(commandsCtx: Context): () => Promise<void> {
182
+ const active = new Set<Promise<CommandResult>>()
183
+ const disposers = new Map<object, () => void>()
184
+ const definition = createCompactDefinition(commandsCtx, active)
185
+ const attach = (agent: Agent | undefined): void => {
186
+ if (agent === undefined || typeof agent !== 'object' || disposers.has(agent)) return
187
+ const agentCommands = (agent as unknown as {
188
+ ctx?: { get?: (name: string) => CommandsRuntime | undefined }
189
+ }).ctx?.get?.('commands')
190
+ if (agentCommands?.register === undefined) return
191
+ disposers.set(agent, agentCommands.register(definition))
192
+ }
193
+ const existing = (commandsCtx as unknown as {
194
+ get?: (name: string) => { list?: () => readonly Agent[] } | undefined
195
+ }).get?.('agents')?.list?.() ?? []
196
+ for (const agent of existing) attach(agent)
197
+
198
+ const offCreated = commandsCtx.on(
199
+ 'agent/created',
200
+ (({ agent }: { agent: Agent }) => { attach(agent) }) as never,
201
+ ) as unknown as (() => void) | undefined
202
+ const offDisposed = commandsCtx.on(
203
+ 'agent/disposed',
204
+ (({ agent }: { agent: Agent }) => {
205
+ const off = disposers.get(agent)
206
+ disposers.delete(agent)
207
+ off?.()
208
+ }) as never,
209
+ ) as unknown as (() => void) | undefined
210
+
211
+ return async () => {
212
+ offCreated?.()
213
+ offDisposed?.()
214
+ for (const off of disposers.values()) off()
215
+ disposers.clear()
216
+ await Promise.allSettled(active)
217
+ }
218
+ }
219
+
220
+ /** Register `/compact [remote|local]` on each live and future Agent scope across all presets. */
221
+ export function installGlobalCompactCommand(ctx: Context): void {
222
+ if (typeof (ctx as { on?: unknown }).on !== 'function') return
223
+ if (typeof (ctx as { inject?: unknown }).inject === 'function') {
224
+ ctx.inject(['commands' as never], ((commandsCtx: Context) => {
225
+ const cleanup = mountPerAgentCommands(commandsCtx)
226
+ ;(commandsCtx as { effect?: (fn: () => () => Promise<void>, label?: string) => void }).effect?.(
227
+ () => cleanup,
228
+ 'codex: per-agent /compact command',
229
+ )
230
+ }) as never)
231
+ return
232
+ }
233
+ if ((ctx as unknown as { get?: (name: string) => unknown }).get?.('commands') !== undefined) {
234
+ const cleanup = mountPerAgentCommands(ctx)
235
+ ;(ctx as { effect?: (fn: () => () => Promise<void>, label?: string) => void }).effect?.(
236
+ () => cleanup,
237
+ 'codex: per-agent /compact command',
238
+ )
239
+ }
240
+ }
241
+
242
+ /** Replace the Core command inside the Codex compaction scope. */
243
+ export function apply(ctx: Context): void {
244
+ const commands = (ctx as CommandContext).commands
245
+ const active = new Set<Promise<CommandResult>>()
246
+ const definition = createCompactDefinition(ctx, active)
247
+ ctx.effect(function* () {
248
+ yield async () => { await Promise.allSettled(active) }
249
+ yield commands.register(definition)
250
+ }, 'codex compact command lifecycle')
251
+ }
252
+
253
+ export const name = 'compact-command'
254
+ export const inject = ['commands', 'compaction']
255
+
256
+ export default { name, inject, apply }