@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,218 @@
1
+ /** Codex compaction backend that honors the latest durable request capacity. */
2
+
3
+ import { AsyncLocalStorage } from 'node:async_hooks'
4
+ import { Context } from '@deepseek-ai/cordis'
5
+ import BasicCompactionEngine from '@deepseek-ai/dsh-compaction-basic'
6
+ import type { CompactionResult, CompactionTrigger } from '@deepseek-ai/dsh-compaction'
7
+ import type { Session } from '@deepseek-ai/dsh-session'
8
+ import type { GenerateOptions } from '@deepseek-ai/dsh-llm'
9
+ import type {} from '@deepseek-ai/dsh-llm'
10
+ import { CODEX_SETTINGS_NAMESPACE, isGptModel, readHostSettings } from '../contracts/settings.ts'
11
+ import type { CodexSettings } from '../contracts/settings.ts'
12
+
13
+ type LlmService = NonNullable<Context['llm']>
14
+ type CodexGenerateOptions = GenerateOptions & { contextWindow?: number }
15
+
16
+ /** Per-command compaction preference propagated into the LLM stream seam. */
17
+ export type CodexCompactionMode = 'remote' | 'local'
18
+
19
+ /**
20
+ * The main plugin entry and the compact-command subpath can be evaluated as
21
+ * separate bundles. Keep their async context carrier on the process global so
22
+ * an explicit command mode reaches the global llm/stream listener.
23
+ */
24
+ const COMPACTION_MODE_KEY = Symbol.for('shuind.dsh-codex-harness.compaction-mode')
25
+ const COMPACTION_MODE = (() => {
26
+ const registry = globalThis as unknown as Record<PropertyKey, unknown>
27
+ const existing = registry[COMPACTION_MODE_KEY]
28
+ if (existing !== undefined) return existing as AsyncLocalStorage<CodexCompactionMode>
29
+ const storage = new AsyncLocalStorage<CodexCompactionMode>()
30
+ registry[COMPACTION_MODE_KEY] = storage
31
+ return storage
32
+ })()
33
+
34
+ /** Run one manual compaction with an explicit local/remote preference. */
35
+ export function runCodexCompactionMode<T>(
36
+ mode: CodexCompactionMode,
37
+ task: () => Promise<T>,
38
+ ): Promise<T> {
39
+ return COMPACTION_MODE.run(mode, task)
40
+ }
41
+
42
+ /** Read the explicit preference for the current compaction stream, if any. */
43
+ export function codexCompactionMode(): CodexCompactionMode | undefined {
44
+ return COMPACTION_MODE.getStore()
45
+ }
46
+
47
+ interface ConfiguredContextWindow {
48
+ /** Whether the settings service is available and therefore authoritative. */
49
+ available: boolean
50
+ /** The current explicit override; absent means use the model default. */
51
+ value?: number
52
+ }
53
+
54
+ /** Read the live Codex capacity without requiring a custom LLM service API. */
55
+ function configuredContextWindow(ctx: Context): ConfiguredContextWindow {
56
+ const settings = ctx.get('settings') as { describe?: unknown } | undefined
57
+ const preferences = ctx.get('codexPreferences') as { current?: unknown } | undefined
58
+ if (settings?.describe === undefined && preferences?.current === undefined) return { available: false }
59
+ const value = readHostSettings<Pick<CodexSettings, 'contextWindow'>>(ctx, CODEX_SETTINGS_NAMESPACE)
60
+ return {
61
+ available: true,
62
+ ...value?.contextWindow !== undefined
63
+ && Number.isSafeInteger(value.contextWindow)
64
+ && value.contextWindow > 0
65
+ ? { value: value.contextWindow }
66
+ : {},
67
+ }
68
+ }
69
+
70
+ /** Read an explicit capacity persisted in the request header when settings are unavailable. */
71
+ function requestContextWindow(session: Session, provider: string, model: string): number | undefined {
72
+ const config = session.requestHeader()?.config as {
73
+ provider?: unknown
74
+ model?: unknown
75
+ contextWindow?: unknown
76
+ } | undefined
77
+ if (config?.provider !== provider || config.model !== model) return undefined
78
+ const value = config.contextWindow
79
+ return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : undefined
80
+ }
81
+
82
+ /** Resolve the capacity currently in force for an active Codex compaction. */
83
+ function activeContextWindow(
84
+ ctx: Context,
85
+ activeSession: AsyncLocalStorage<Session>,
86
+ provider: string,
87
+ model: string,
88
+ ): number | undefined {
89
+ if (provider === 'openai-codex') return undefined
90
+ const session = activeSession.getStore()
91
+ const requestContext = session?.requestContext()
92
+ const configured = isGptModel(model)
93
+ ? configuredContextWindow(ctx)
94
+ : { available: false }
95
+ // A live setting must win before the old request header: automatic pressure
96
+ // runs before the next request rebuilds that header.
97
+ return configured.available
98
+ ? configured.value
99
+ : (session === undefined ? undefined : requestContextWindow(session, provider, model))
100
+ ?? (requestContext?.provider === provider && requestContext.model === model
101
+ ? requestContext.contextWindow
102
+ : undefined)
103
+ }
104
+
105
+ const DSH_COMPACT_PROMPT_PREFIX = 'You are now acting as a compaction engine'
106
+
107
+ /**
108
+ * When `/compact local` is active, neutralize DSH's exact compaction prompt
109
+ * prefix on a shallow clone so external adapters (`dsh-codex-connect`) fall
110
+ * through to local text summarization instead of firing `compaction_trigger`.
111
+ */
112
+ export function withExplicitLocalCompactionInstruction(options: CodexGenerateOptions): CodexGenerateOptions {
113
+ if (codexCompactionMode() !== 'local' || options.purpose !== 'compaction' || options.messages.length === 0) {
114
+ return options
115
+ }
116
+ const last = options.messages.at(-1)
117
+ if (last === undefined || last.role !== 'user' || ('id' in last && last.id !== undefined)) {
118
+ return options
119
+ }
120
+ const first = last.content[0]
121
+ if (first === undefined || first.type !== 'text' || !first.text.startsWith(DSH_COMPACT_PROMPT_PREFIX)) {
122
+ return options
123
+ }
124
+ const updatedLast = {
125
+ ...last,
126
+ content: [{ ...first, text: `\n${first.text}` }, ...last.content.slice(1)],
127
+ }
128
+ return {
129
+ ...options,
130
+ messages: [...options.messages.slice(0, -1), updatedLast] as GenerateOptions['messages'],
131
+ }
132
+ }
133
+
134
+ /** Overlay capacity lookup and auxiliary summary requests for compaction. */
135
+ function withDurableContextCapacity(
136
+ llm: LlmService,
137
+ ctx: Context,
138
+ activeSession: AsyncLocalStorage<Session>,
139
+ ): LlmService {
140
+ return new Proxy(llm, {
141
+ get(target, property) {
142
+ if (property === 'resolveModelInfo') {
143
+ return async (provider: string, model: string, signal?: AbortSignal) => {
144
+ const info = await target.resolveModelInfo(provider, model, signal)
145
+ const contextWindow = activeContextWindow(ctx, activeSession, provider, model)
146
+ if (contextWindow === undefined) return info
147
+ return {
148
+ ...info,
149
+ context: { ...info.context, contextWindow },
150
+ }
151
+ }
152
+ }
153
+ if (property === 'stream') {
154
+ return (options: CodexGenerateOptions) => {
155
+ const contextWindow = activeContextWindow(ctx, activeSession, options.provider, options.model)
156
+ const patched = withExplicitLocalCompactionInstruction(options)
157
+ if (contextWindow === undefined || patched.contextWindow === contextWindow) {
158
+ return target.stream(patched)
159
+ }
160
+ return target.stream({ ...patched, contextWindow } as GenerateOptions)
161
+ }
162
+ }
163
+ const value = Reflect.get(target, property, target)
164
+ return typeof value === 'function' ? value.bind(target) : value
165
+ },
166
+ }) as LlmService
167
+ }
168
+
169
+ /**
170
+ * Keep the upstream compaction policy, retention, overflow recovery, and
171
+ * transaction implementation intact. The scoped LLM seam changes only the
172
+ * context metadata returned during a pressure check.
173
+ */
174
+ export default class CodexCompactionEngine extends BasicCompactionEngine {
175
+ static override inject = BasicCompactionEngine.inject
176
+ static override Config = BasicCompactionEngine.Config
177
+
178
+ readonly codexSmallWindowReady = true
179
+ private readonly activeSession: AsyncLocalStorage<Session>
180
+
181
+ constructor(ctx: Context, config: ConstructorParameters<typeof BasicCompactionEngine>[1] = {}) {
182
+ const activeSession = new AsyncLocalStorage<Session>()
183
+ const llm = ctx.get('llm')
184
+ if (llm === undefined) throw new Error('codex compaction requires ctx.llm')
185
+ const normalizedConfig = {
186
+ ...config,
187
+ headroomTokens: config.headroomTokens ?? 8_192,
188
+ maxTokens: config.maxTokens ?? config.headroomTokens ?? 65_536,
189
+ }
190
+ super(ctx.extend({ llm: withDurableContextCapacity(llm, ctx, activeSession) }), normalizedConfig)
191
+ this.activeSession = activeSession
192
+ }
193
+
194
+ override compactIfNeeded(
195
+ agent: Parameters<BasicCompactionEngine['compactIfNeeded']>[0],
196
+ trigger: CompactionTrigger,
197
+ signal: AbortSignal,
198
+ ): Promise<CompactionResult | null> {
199
+ return this.activeSession.run(agent.session, () => super.compactIfNeeded(agent, trigger, signal))
200
+ }
201
+
202
+ override compactRegion(
203
+ ...args: Parameters<BasicCompactionEngine['compactRegion']>
204
+ ): Promise<CompactionResult> {
205
+ return this.activeSession.run(args[2].session, () => super.compactRegion(...args))
206
+ }
207
+
208
+ override compactNow(
209
+ agent: Parameters<BasicCompactionEngine['compactNow']>[0],
210
+ signal: AbortSignal,
211
+ sourceCommandId?: Parameters<BasicCompactionEngine['compactNow']>[2],
212
+ ): Promise<CompactionResult | null> {
213
+ return this.activeSession.run(
214
+ agent.session,
215
+ () => super.compactNow(agent, signal, sourceCommandId),
216
+ )
217
+ }
218
+ }
@@ -0,0 +1,76 @@
1
+ /** Asymmetric hybrid executor plugin entry and `codexHybridDefaults` wiring. */
2
+ import type { Context } from '@deepseek-ai/cordis'
3
+ import type {} from '@deepseek-ai/dsh-ptc-runtime'
4
+ import { scopeOf, scopeParentOf } from '@deepseek-ai/dsh-scope'
5
+ import type {} from '@deepseek-ai/dsh-system-prompt'
6
+ import type {} from '@deepseek-ai/dsh-tools'
7
+ import {
8
+ CodexHybridExecutor,
9
+ Config,
10
+ DEFAULT_HYBRID_DIRECT_TOOLS,
11
+ } from '../hybrid/codex-hybrid-executor.ts'
12
+ import { CodeResetFailedError, CodeRunFailedError } from '../hybrid/program-calls.ts'
13
+ import type { PtcDispatchEventData, PtcDispatchLog, PtcDispatchStartEventData } from '../hybrid/subcall-scheduler.ts'
14
+ import {
15
+ ACTIVATE_TOOLS_NAME,
16
+ registerHybridDefaultDeferredTools,
17
+ registerHybridDefaultHiddenTools,
18
+ yieldDeferredToolsOverlay,
19
+ } from '../policy/deferred-tools.ts'
20
+
21
+ export {
22
+ CodexHybridExecutor,
23
+ Config,
24
+ DEFAULT_HYBRID_DIRECT_TOOLS,
25
+ CodeResetFailedError,
26
+ CodeRunFailedError,
27
+ }
28
+ export type { PtcDispatchEventData, PtcDispatchLog, PtcDispatchStartEventData }
29
+
30
+ export const name = 'codex-hybrid-executor'
31
+ export const inject = ['tools', 'systemPrompt', 'ptcRuntime']
32
+
33
+ /** Mount `CodexHybridExecutor` and publish default hidden/deferred tools for the owning scope. */
34
+ export function apply(ctx: Context, config: Partial<Config> = {}): void {
35
+ const resolved = Config(config)
36
+ const executor = new CodexHybridExecutor(ctx, resolved)
37
+ ctx.tools.setExecutor(executor)
38
+ const hiddenSet = new Set(resolved.hiddenTools.map(item => item.trim()).filter(Boolean))
39
+ const deferredSet = new Set(resolved.deferredTools.map(item => item.trim()).filter(Boolean))
40
+ if (hiddenSet.size > 0) {
41
+ ctx.effect(() => registerHybridDefaultHiddenTools(ctx, hiddenSet), 'codex-hybrid: default hidden tools')
42
+ }
43
+ if (deferredSet.size > 0) {
44
+ ctx.effect(() => registerHybridDefaultDeferredTools(ctx, deferredSet), 'codex-hybrid: default deferred tools')
45
+ }
46
+ if ((deferredSet.size > 0 || hiddenSet.size > 0) && typeof (ctx as Partial<Context>).on === 'function') {
47
+ const parentScope = scopeOf(ctx)
48
+ ctx.on('agent/created', ({ agent }) => {
49
+ if (agent.ctx.get('codexToolPolicy') !== undefined) return
50
+ if (parentScope !== undefined && scopeParentOf(agent) !== parentScope) return
51
+ const agentTools = agent.ctx.get('tools')
52
+ const agentPrompt = agent.ctx.get('systemPrompt')
53
+ if (agentTools === undefined || agentPrompt === undefined) return
54
+ if (agentTools.get(ACTIVATE_TOOLS_NAME, agent) !== undefined) return
55
+ const upstream = scopeParentOf(agent)
56
+ const hiddenUpstream = [...hiddenSet].filter(tool => {
57
+ const visible = agentTools.get(tool, agent)
58
+ return visible !== undefined && agentTools.get(tool, upstream) === visible
59
+ })
60
+ const deferredDefs = agentTools.definitions(upstream).filter(def =>
61
+ def.name !== ACTIVATE_TOOLS_NAME
62
+ && !hiddenSet.has(def.name)
63
+ && deferredSet.has(def.name)
64
+ && agentTools.get(def.name, agent) !== undefined
65
+ && agentTools.executable(def.name, agent) === def
66
+ && agentTools.get(def.name, upstream) === def)
67
+ if (hiddenUpstream.length === 0 && deferredDefs.length === 0) return
68
+ agent.ctx.effect(function* () {
69
+ if (hiddenUpstream.length > 0) yield agentTools.restrict({ deny: hiddenUpstream })
70
+ if (deferredDefs.length > 0) yield* yieldDeferredToolsOverlay(agentTools, agentPrompt, deferredDefs, agent)
71
+ }, 'codex-hybrid: standalone baseline tools')
72
+ })
73
+ }
74
+ }
75
+
76
+ export default { name, inject, Config, apply }
@@ -0,0 +1,298 @@
1
+ /** Codex-compatible prompt overlay and core tools for a dsh agent preset. */
2
+
3
+ import type { Context } from '@deepseek-ai/cordis'
4
+ import z from '@deepseek-ai/schemastery'
5
+ import type {} from '@deepseek-ai/dsh-settings'
6
+ import type {} from '@deepseek-ai/dsh-llm'
7
+ import type {} from '@deepseek-ai/dsh-system-prompt'
8
+ import type {} from '@deepseek-ai/dsh-tools'
9
+ import type {} from '@deepseek-ai/dsh-fs'
10
+ import {
11
+ DEFAULT_CODEX_PERSONA,
12
+ DEFAULT_CODEX_SYSTEM_PROMPT,
13
+ DEFAULT_DSH_CORE_SOURCE_PROMPT,
14
+ DEFAULT_DSH_CORE_WEB_PROMPT,
15
+ resolveCodexSystemPrompt,
16
+ } from '../contracts/prompt.ts'
17
+ import {
18
+ CODEX_SETTINGS_ENTRY,
19
+ CODEX_SETTINGS_NAMESPACE,
20
+ isGptModel,
21
+ readHostSettings,
22
+ } from '../contracts/settings.ts'
23
+ import type { CodexSettings } from '../contracts/settings.ts'
24
+ import { CODEX_CONTEXT_MAX, OPENAI_CODEX_MODEL_LIMITS } from '../contracts/ui-contracts.ts'
25
+ import { hasPresetPromptOverride } from '../policy/tool-capabilities.ts'
26
+ import { registerCodexActivityProjection } from '../presets/activity.ts'
27
+ import {
28
+ applyCodexPresentationSettings,
29
+ applyCodexRequestSettings,
30
+ buildCodexSystemPrompt,
31
+ enrichCodexModel,
32
+ installCodexContextProjection,
33
+ installPresetEditor,
34
+ normalizeCodexPromptAssembly,
35
+ syncCodexContextWindow,
36
+ watchConfiguredGptModels,
37
+ withPresetPrompt,
38
+ } from '../presets/runtime-enhancements.ts'
39
+ import type { CodexModelProfile, CodexRequestConfig } from '../presets/runtime-enhancements.ts'
40
+ import { installSmallWindowCompaction } from '../presets/small-window-compaction.ts'
41
+ import { collectTrustedCompactionMarkers } from '../responses/compact-checkpoint.ts'
42
+ import { installHostedWebSearch, hostedWebSearchStream } from '../responses/fetch-transport.ts'
43
+ import { hasDirectResponsesCompactRoute, remoteCompactStream } from '../responses/remote-compact.ts'
44
+ import { repairLegacyPiAiContextOverflow } from '../responses/sse-diagnostics.ts'
45
+ import {
46
+ DEFAULT_MAX_OUTPUT_BYTES,
47
+ registerCodexExecAndPlan,
48
+ registerExecTools,
49
+ registerPlanTool,
50
+ } from '../tools/exec-plan-tools.ts'
51
+ import type { CodexExecAndPlanOptions } from '../tools/exec-plan-tools.ts'
52
+ import { registerPatchTool } from '../tools/patch-tool.ts'
53
+ import { installGlobalCompactCommand } from './compact-command.ts'
54
+ import { codexCompactionMode, withExplicitLocalCompactionInstruction } from './compaction.ts'
55
+
56
+ export {
57
+ DEFAULT_CODEX_PERSONA,
58
+ DEFAULT_CODEX_SYSTEM_PROMPT,
59
+ DEFAULT_DSH_CORE_SOURCE_PROMPT,
60
+ DEFAULT_DSH_CORE_WEB_PROMPT,
61
+ }
62
+ export { CODEX_SETTINGS_NAMESPACE, CODEX_SETTINGS_SCHEMA } from '../contracts/settings.ts'
63
+ export type { CodexSettings }
64
+ export { registerCodexExecAndPlan }
65
+ export type { CodexExecAndPlanOptions }
66
+ export {
67
+ enrichCodexModel,
68
+ syncCodexContextWindow,
69
+ applyCodexRequestSettings,
70
+ normalizeCodexPromptAssembly,
71
+ applyCodexPresentationSettings,
72
+ buildCodexSystemPrompt,
73
+ withPresetPrompt,
74
+ }
75
+ export type { CodexRequestConfig, CodexModelProfile }
76
+
77
+ export const name = 'codex'
78
+ export const inject = ['tools', 'systemPrompt', 'shell', 'fs', 'llm', 'credentials', 'settings']
79
+
80
+ /** Configuration for the Codex shell result bridge. */
81
+ export interface Config {
82
+ /** Install request/transport/activity enhancements for every agent scope. */
83
+ globalEnhancements?: boolean
84
+ /** Install the Codex operating prompt and four core tools in this scope. */
85
+ codexCore?: boolean
86
+ /** Default wait before a pipe-backed command yields a session id. */
87
+ defaultYieldTimeMs?: number
88
+ /** Default wait for an empty `write_stdin` poll. */
89
+ pollYieldTimeMs?: number
90
+ /** Default wait for a non-empty `write_stdin` send. */
91
+ writeYieldTimeMs?: number
92
+ /** Maximum output retained in one canonical result, in UTF-8 bytes. */
93
+ maxOutputBytes?: number
94
+ /** Send GPT Responses requests with the native hosted web_search tool first. */
95
+ hostedWebSearch?: boolean
96
+ /** Use the provider's /responses/compact endpoint before local compaction. */
97
+ remoteCompact?: boolean
98
+ /** Complete plugin-owned Codex operating prompt. */
99
+ systemPrompt?: string
100
+ /** Explicit per-preset operating prompt; overrides the shared prompt only. */
101
+ presetPrompt?: string
102
+ /** Per-preset Codex capability overrides. Omitted values follow shared settings. */
103
+ promptEnabled?: boolean
104
+ terminalToolsEnabled?: boolean
105
+ patchToolEnabled?: boolean
106
+ planToolEnabled?: boolean
107
+ hostedWebSearchEnabled?: boolean
108
+ remoteCompactionEnabled?: boolean
109
+ /** Deployment Persona template. */
110
+ persona?: string
111
+ /** DSH Core source-checkout guidance template. */
112
+ harnessSourcePrompt?: string
113
+ /** DSH Core Web GUI guidance template. */
114
+ webSurfacePrompt?: string
115
+ }
116
+
117
+ /** Runtime configuration schema for the Codex tool bridge. */
118
+ export const Config: z<Config> = z.object({
119
+ globalEnhancements: z.boolean().default(true),
120
+ codexCore: z.boolean().default(true),
121
+ defaultYieldTimeMs: z.number().step(1).min(0).default(10_000),
122
+ pollYieldTimeMs: z.number().step(1).min(0).default(5_000),
123
+ writeYieldTimeMs: z.number().step(1).min(0).default(250),
124
+ maxOutputBytes: z.number().step(1).min(1).default(DEFAULT_MAX_OUTPUT_BYTES),
125
+ hostedWebSearch: z.boolean().default(true),
126
+ remoteCompact: z.boolean().default(true),
127
+ systemPrompt: z.string().default(DEFAULT_CODEX_SYSTEM_PROMPT),
128
+ presetPrompt: z.string(),
129
+ promptEnabled: z.boolean(),
130
+ terminalToolsEnabled: z.boolean(),
131
+ patchToolEnabled: z.boolean(),
132
+ planToolEnabled: z.boolean(),
133
+ hostedWebSearchEnabled: z.boolean(),
134
+ remoteCompactionEnabled: z.boolean(),
135
+ persona: z.string().default(DEFAULT_CODEX_PERSONA),
136
+ harnessSourcePrompt: z.string().default(DEFAULT_DSH_CORE_SOURCE_PROMPT),
137
+ webSurfacePrompt: z.string().default(DEFAULT_DSH_CORE_WEB_PROMPT),
138
+ })
139
+
140
+ /** Mount the Codex prompt/tool layer inside one fixed agent preset. */
141
+ export function apply(ctx: Context, config: Config = {}): void {
142
+ const resolved = {
143
+ globalEnhancements: config.globalEnhancements ?? true,
144
+ codexCore: config.codexCore ?? true,
145
+ defaultYieldTimeMs: config.defaultYieldTimeMs ?? 10_000,
146
+ pollYieldTimeMs: config.pollYieldTimeMs ?? 5_000,
147
+ writeYieldTimeMs: config.writeYieldTimeMs ?? 250,
148
+ maxOutputBytes: config.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
149
+ hostedWebSearch: config.hostedWebSearch ?? true,
150
+ remoteCompact: config.remoteCompact ?? true,
151
+ systemPrompt: config.systemPrompt ?? DEFAULT_CODEX_SYSTEM_PROMPT,
152
+ persona: config.persona ?? DEFAULT_CODEX_PERSONA,
153
+ harnessSourcePrompt: config.harnessSourcePrompt ?? DEFAULT_DSH_CORE_SOURCE_PROMPT,
154
+ webSurfacePrompt: config.webSurfacePrompt ?? DEFAULT_DSH_CORE_WEB_PROMPT,
155
+ }
156
+ if (resolved.codexCore
157
+ && ctx.fs.sandboxMode !== undefined
158
+ && ctx.get('sandboxPolicy') === undefined) {
159
+ throw new Error('codex: a sandboxing filesystem requires ctx.sandboxPolicy')
160
+ }
161
+ const baseSettings: CodexSettings = {
162
+ ...CODEX_SETTINGS_ENTRY,
163
+ systemPrompt: resolved.systemPrompt,
164
+ persona: resolved.persona,
165
+ harnessSourcePrompt: resolved.harnessSourcePrompt,
166
+ webSurfacePrompt: resolved.webSurfacePrompt,
167
+ }
168
+ const sharedSettings = {
169
+ current: (): CodexSettings => ({
170
+ ...baseSettings,
171
+ ...readHostSettings<CodexSettings>(ctx, CODEX_SETTINGS_NAMESPACE),
172
+ }),
173
+ }
174
+ const codexSettings = { current: () => {
175
+ const shared = withPresetPrompt(sharedSettings.current(), config.presetPrompt)
176
+ return {
177
+ ...shared,
178
+ ...(config.promptEnabled === undefined ? {} : { promptEnabled: config.promptEnabled }),
179
+ ...(config.terminalToolsEnabled === undefined ? {} : { terminalToolsEnabled: config.terminalToolsEnabled }),
180
+ ...(config.patchToolEnabled === undefined ? {} : { patchToolEnabled: config.patchToolEnabled }),
181
+ ...(config.planToolEnabled === undefined ? {} : { planToolEnabled: config.planToolEnabled }),
182
+ ...(config.hostedWebSearchEnabled === undefined ? {} : { hostedWebSearchEnabled: config.hostedWebSearchEnabled }),
183
+ ...(config.remoteCompactionEnabled === undefined ? {} : { remoteCompactionEnabled: config.remoteCompactionEnabled }),
184
+ }
185
+ } }
186
+ const execConfig = {
187
+ ...resolved,
188
+ currentSettings: codexSettings.current,
189
+ presetEnabled: config.terminalToolsEnabled !== false,
190
+ presetOverridesLegacy: config.terminalToolsEnabled !== undefined,
191
+ }
192
+
193
+ if (resolved.globalEnhancements) {
194
+ // Native presets reject host services in their isolated composition.
195
+ installPresetEditor(ctx)
196
+ installGlobalCompactCommand(ctx)
197
+ // The generic pi-ai plugin remains the owner of provider routes. This
198
+ // layer adds only request metadata and remote-first transport behavior.
199
+ watchConfiguredGptModels(ctx)
200
+ registerCodexActivityProjection(ctx)
201
+ installCodexContextProjection(ctx, codexSettings.current)
202
+ const lastRequestByAgent = new WeakMap<object, unknown>()
203
+ installSmallWindowCompaction(ctx, codexSettings.current, lastRequestByAgent)
204
+ ctx.on('agent/request', async (payload, next) => {
205
+ const request = await next()
206
+ const updated = applyCodexRequestSettings(request, codexSettings.current())
207
+ const agent = (payload as { agent?: unknown } | undefined)?.agent
208
+ if (agent !== null && typeof agent === 'object') lastRequestByAgent.set(agent, updated)
209
+ return updated
210
+ })
211
+ if (typeof (ctx as unknown as { effect?: unknown }).effect === 'function') {
212
+ const disposeHostedWebSearch = installHostedWebSearch()
213
+ ctx.effect(() => disposeHostedWebSearch, 'codex: Responses transport wrapper')
214
+ }
215
+ ctx.on('llm/stream', ((options: any, next: any) => {
216
+ const settings = codexSettings.current()
217
+ const isCodexConnect = options.provider === 'openai-codex'
218
+ const contextWindow = options.contextWindow ?? (isCodexConnect ? undefined : settings.contextWindow)
219
+ const modelMax = typeof options.model === 'string'
220
+ ? OPENAI_CODEX_MODEL_LIMITS[options.model]?.maxTokens
221
+ : undefined
222
+ const repairCeiling = isCodexConnect
223
+ ? (modelMax ?? CODEX_CONTEXT_MAX)
224
+ : options.purpose === 'compaction'
225
+ ? Math.max(contextWindow ?? 0, modelMax ?? CODEX_CONTEXT_MAX)
226
+ : contextWindow
227
+ const serviceTier: string | undefined = options.serviceTier ?? (!isCodexConnect && settings.fast ? 'priority' : undefined)
228
+ const trustedCheckpoints = Array.isArray(options.messages) ? collectTrustedCompactionMarkers(options.messages) : undefined
229
+ const compactionMode = codexCompactionMode()
230
+ const legacySafeNext = () => repairLegacyPiAiContextOverflow(
231
+ next(),
232
+ options.model,
233
+ repairCeiling,
234
+ )
235
+ if (options.purpose === 'compaction' && isGptModel(options.model)) {
236
+ if (compactionMode === 'local') {
237
+ const localOptions = withExplicitLocalCompactionInstruction(options)
238
+ if (localOptions !== options) {
239
+ if (!Object.isFrozen(options)) {
240
+ options.messages = localOptions.messages
241
+ } else {
242
+ return repairLegacyPiAiContextOverflow(
243
+ ctx.llm.stream(localOptions),
244
+ options.model,
245
+ repairCeiling,
246
+ )
247
+ }
248
+ }
249
+ return legacySafeNext()
250
+ }
251
+ const useRemoteCompaction = compactionMode === 'remote'
252
+ || (compactionMode !== 'local' && resolved.remoteCompact && settings.remoteCompactionEnabled)
253
+ if (useRemoteCompaction && hasDirectResponsesCompactRoute(ctx, options.provider)) {
254
+ return remoteCompactStream(ctx, options, legacySafeNext, {
255
+ ...serviceTier === undefined ? {} : { serviceTier },
256
+ hostedWebSearch: resolved.hostedWebSearch && settings.hostedWebSearchEnabled,
257
+ customApplyPatch: settings.patchToolEnabled,
258
+ ...trustedCheckpoints === undefined ? {} : { trustedCheckpoints },
259
+ })
260
+ }
261
+ return legacySafeNext()
262
+ }
263
+ if (options.purpose === undefined && isGptModel(options.model)) {
264
+ return repairLegacyPiAiContextOverflow(
265
+ hostedWebSearchStream(next, {
266
+ ...serviceTier === undefined ? {} : { serviceTier },
267
+ hostedWebSearch: !isCodexConnect && resolved.hostedWebSearch && settings.hostedWebSearchEnabled,
268
+ customApplyPatch: settings.patchToolEnabled,
269
+ ...trustedCheckpoints === undefined ? {} : { trustedCheckpoints },
270
+ }),
271
+ options.model,
272
+ repairCeiling,
273
+ )
274
+ }
275
+ return next()
276
+ }) as any)
277
+ }
278
+
279
+ if (resolved.codexCore) {
280
+ ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
281
+ const protectedNames = new Set(['deployment:persona-prefix', 'deployment:persona-suffix', 'codex:base']
282
+ .filter(name => hasPresetPromptOverride(ctx, context, name)))
283
+ return applyCodexPresentationSettings(await next(), codexSettings.current(), protectedNames)
284
+ })
285
+ ctx.systemPrompt.section({
286
+ name: 'codex:base',
287
+ order: 10,
288
+ text: () => codexSettings.current().promptEnabled
289
+ ? resolveCodexSystemPrompt(codexSettings.current().systemPrompt)
290
+ : '',
291
+ })
292
+ registerExecTools(ctx, execConfig)
293
+ registerPatchTool(ctx, codexSettings.current, config.patchToolEnabled !== false, undefined, config.patchToolEnabled !== undefined)
294
+ registerPlanTool(ctx, codexSettings.current, config.planToolEnabled !== false, undefined, config.planToolEnabled !== undefined)
295
+ }
296
+ }
297
+
298
+ export default { name, inject, Config, apply }
@@ -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 '../contracts/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
+ }