@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,349 @@
1
+ /** Host runtime enhancements: GPT model enrichment, context-window projection, and prompt templates. */
2
+ import { DEFAULT_CODEX_PERSONA, DEFAULT_DSH_CORE_SOURCE_PROMPT, DEFAULT_DSH_CORE_WEB_PROMPT, resolveCodexSystemPrompt, } from "../contracts/prompt.js";
3
+ import { CODEX_SETTINGS_NAMESPACE, isGptModel, readHostSettings } from "../contracts/settings.js";
4
+ import { OPENAI_CODEX_MODEL_LIMITS, OPENAI_CODEX_PROVIDER, OPENAI_CODEX_SETTINGS_NAMESPACE, } from "../contracts/ui-contracts.js";
5
+ import { CodexPresetEditor } from "./preset-editor.js";
6
+ /** Add the preset editor when DSH's optional user-preset service is available. */
7
+ export function installPresetEditor(ctx) {
8
+ // `agentPresets` is supplied by dsh-agent-presets and may be installed after
9
+ // this plugin. Waiting through inject keeps the Codex core usable on hosts
10
+ // without that optional service while still mounting the Remote as soon as
11
+ // the Web preset catalog becomes available.
12
+ ctx.inject(['agentPresets'], presetCtx => {
13
+ void (async () => {
14
+ try {
15
+ await presetCtx.plugin(CodexPresetEditor);
16
+ }
17
+ catch (error) {
18
+ ctx.logger.warn('codex: preset editor is unavailable on this host');
19
+ ctx.logger.warn(error);
20
+ }
21
+ })();
22
+ });
23
+ }
24
+ const LLM_PI_AI_SETTINGS = 'llm-pi-ai';
25
+ const GPT_REASONING_EFFORTS = {
26
+ low: 'low',
27
+ medium: 'medium',
28
+ high: 'high',
29
+ xhigh: 'xhigh',
30
+ max: 'max',
31
+ };
32
+ function codexReasoningEfforts(configured) {
33
+ if (configured === false)
34
+ return false;
35
+ const filtered = configured === undefined
36
+ ? {}
37
+ : Object.fromEntries(Object.entries(configured).filter(([level]) => level !== 'off' && level !== 'minimal'));
38
+ return Object.keys(filtered).length === 0 ? GPT_REASONING_EFFORTS : filtered;
39
+ }
40
+ /** Add Codex defaults without overwriting explicit user capabilities. */
41
+ export function enrichCodexModel(model) {
42
+ if (!isGptModel(model.id))
43
+ return model;
44
+ const input = model.input === undefined || model.input.length === 0
45
+ ? ['text', 'image']
46
+ : model.input;
47
+ const efforts = codexReasoningEfforts(model.reasoningEfforts);
48
+ if (input === model.input && efforts === model.reasoningEfforts)
49
+ return model;
50
+ return { ...model, input, reasoningEfforts: efforts };
51
+ }
52
+ /** The settings schema keys modelOverrides by id, so its values must not carry an id field. */
53
+ function enrichCodexOverride(id, model) {
54
+ if (!isGptModel(id))
55
+ return model;
56
+ const enriched = enrichCodexModel({ ...model, id });
57
+ const { id: _id, ...withoutId } = enriched;
58
+ const inputMissing = model.input === undefined || model.input.length === 0;
59
+ const nextEfforts = codexReasoningEfforts(model.reasoningEfforts);
60
+ const reasoningChanged = JSON.stringify(nextEfforts) !== JSON.stringify(model.reasoningEfforts);
61
+ if (!inputMissing && !reasoningChanged)
62
+ return model;
63
+ return { ...withoutId, reasoningEfforts: nextEfforts };
64
+ }
65
+ /** Persist only missing GPT capabilities into the user's existing pi-ai model config. */
66
+ async function enrichConfiguredGptModels(ctx) {
67
+ const settings = ctx.get('settings');
68
+ if (settings === undefined)
69
+ return;
70
+ const current = readHostSettings(ctx, LLM_PI_AI_SETTINGS);
71
+ if (current?.providers === undefined)
72
+ return;
73
+ const providers = {};
74
+ let changed = false;
75
+ for (const [provider, profile] of Object.entries(current.providers)) {
76
+ const models = profile.models;
77
+ const overrides = profile.modelOverrides;
78
+ const nextModels = Array.isArray(models) ? models.map(enrichCodexModel) : undefined;
79
+ const nextOverrides = overrides === undefined
80
+ ? undefined
81
+ : Object.fromEntries(Object.entries(overrides).map(([id, model]) => [id, enrichCodexOverride(id, model)]));
82
+ const modelsChanged = nextModels !== undefined && nextModels.some((model, index) => model !== models?.[index]);
83
+ const overridesChanged = nextOverrides !== undefined
84
+ && overrides !== undefined
85
+ && Object.entries(nextOverrides).some(([id, model]) => model !== overrides[id]);
86
+ if (modelsChanged || overridesChanged) {
87
+ changed = true;
88
+ providers[provider] = {
89
+ ...modelsChanged ? { models: nextModels } : {},
90
+ ...overridesChanged ? { modelOverrides: nextOverrides } : {},
91
+ };
92
+ }
93
+ }
94
+ if (changed)
95
+ await settings.update(LLM_PI_AI_SETTINGS, { providers });
96
+ }
97
+ /** Keep newly edited GPT model entries enriched while Codex mode is mounted. */
98
+ export function watchConfiguredGptModels(ctx) {
99
+ let tail = Promise.resolve();
100
+ const schedule = () => {
101
+ tail = tail.then(() => enrichConfiguredGptModels(ctx)).catch(error => {
102
+ ctx.logger.warn('codex: could not enrich configured GPT model capabilities');
103
+ ctx.logger.warn(error);
104
+ });
105
+ };
106
+ ctx.on('settings/document-updated', (ns) => {
107
+ if (ns === LLM_PI_AI_SETTINGS)
108
+ schedule();
109
+ });
110
+ schedule();
111
+ }
112
+ function hasOpenTurn(session) {
113
+ const events = session.snapshotEvents();
114
+ const start = events.findLast(event => event.type === 'turn/start');
115
+ const end = events.findLast(event => event.type === 'turn/end');
116
+ return start !== undefined && (end === undefined || start.seq > end.seq);
117
+ }
118
+ /**
119
+ * Pair the live Codex capacity with the token-meter context projection.
120
+ *
121
+ * The core loop records adapter metadata in `request/context`, while Codex's
122
+ * setting is a request-scoped LLM capacity. Appending the override after the
123
+ * loop's metadata event keeps the official ContextMeter and compaction engine
124
+ * on the same effective capacity.
125
+ */
126
+ function appendRequestContextWindow(session, provider, model, contextWindow) {
127
+ const current = session.requestContext();
128
+ if (current?.provider === provider
129
+ && current.model === model
130
+ && current.contextWindow === contextWindow)
131
+ return;
132
+ session.append('request/context', {
133
+ provider,
134
+ model,
135
+ contextWindow,
136
+ // Capacity is only one field of the routed capability snapshot.
137
+ ...current?.provider === provider && current.model === model ? {
138
+ ...current.systemPromptUpdate === undefined ? {} : { systemPromptUpdate: current.systemPromptUpdate },
139
+ } : {},
140
+ });
141
+ }
142
+ export function syncCodexContextWindow(session, contextWindow) {
143
+ if (contextWindow === undefined
144
+ || !Number.isSafeInteger(contextWindow)
145
+ || contextWindow <= 0
146
+ || !hasOpenTurn(session))
147
+ return;
148
+ const config = session.requestHeader()?.config;
149
+ if (typeof config?.provider !== 'string'
150
+ || config.provider === OPENAI_CODEX_PROVIDER
151
+ || typeof config.model !== 'string'
152
+ || !isGptModel(config.model))
153
+ return;
154
+ appendRequestContextWindow(session, config.provider, config.model, contextWindow);
155
+ }
156
+ /** Keep open Codex Connect turns aligned with per-model `llm-openai-codex` overrides. */
157
+ export function syncOpenAICodexTurnContext(ctx, session) {
158
+ if (!hasOpenTurn(session))
159
+ return;
160
+ const config = session.requestHeader()?.config;
161
+ if (config?.provider !== OPENAI_CODEX_PROVIDER || typeof config.model !== 'string' || !isGptModel(config.model))
162
+ return;
163
+ const overrides = readHostSettings(ctx, OPENAI_CODEX_SETTINGS_NAMESPACE)?.contextWindowOverrides;
164
+ const override = overrides?.[config.model];
165
+ const llm = ctx.get('llm');
166
+ const effective = typeof override === 'number' && Number.isSafeInteger(override) && override > 0
167
+ ? override
168
+ : OPENAI_CODEX_MODEL_LIMITS[config.model]?.defaultTokens
169
+ ?? llm?.resolveModelInfo?.(OPENAI_CODEX_PROVIDER, config.model)?.contextWindow;
170
+ if (effective === undefined || !Number.isSafeInteger(effective) || effective <= 0)
171
+ return;
172
+ appendRequestContextWindow(session, OPENAI_CODEX_PROVIDER, config.model, effective);
173
+ }
174
+ /** Keep the official context meter synchronized with a live Codex override. */
175
+ export function installCodexContextProjection(ctx, current) {
176
+ const sync = (session, contextWindow = current().contextWindow) => {
177
+ syncCodexContextWindow(session, contextWindow);
178
+ };
179
+ const pending = new WeakSet();
180
+ const syncAfterPublication = (session) => {
181
+ if (pending.has(session))
182
+ return;
183
+ pending.add(session);
184
+ queueMicrotask(() => {
185
+ try {
186
+ sync(session);
187
+ }
188
+ finally {
189
+ pending.delete(session);
190
+ }
191
+ });
192
+ };
193
+ const listSessions = () => {
194
+ const sessions = ctx.get('sessions');
195
+ return sessions?.list?.() ?? [];
196
+ };
197
+ const syncAll = (contextWindow = current().contextWindow) => {
198
+ for (const session of listSessions())
199
+ sync(session, contextWindow);
200
+ };
201
+ ctx.on('session/event', (session, event) => {
202
+ // Session.append() rejects nested appends until every observer returns.
203
+ if (event.type === 'request/header' || event.type === 'request/context')
204
+ syncAfterPublication(session);
205
+ });
206
+ // Restored sessions may already contain their request/header seed, so no
207
+ // session/event is emitted for the initial capacity. Catch them at the
208
+ // store publication boundary as well.
209
+ ctx.on('session/created', syncAfterPublication);
210
+ ctx.on('settings/document-updated', ns => {
211
+ if (ns === CODEX_SETTINGS_NAMESPACE)
212
+ syncAll();
213
+ else if (ns === OPENAI_CODEX_SETTINGS_NAMESPACE) {
214
+ for (const session of listSessions())
215
+ syncOpenAICodexTurnContext(ctx, session);
216
+ }
217
+ });
218
+ syncAll();
219
+ }
220
+ /** Apply the live Codex controls to one agent request without leaking them to other routes. */
221
+ export function applyCodexRequestSettings(request, settings) {
222
+ const { contextWindow: _inheritedContextWindow, serviceTier: _inheritedServiceTier, ...withoutCodexControls } = request;
223
+ if (request.provider === 'openai-codex' || !isGptModel(request.model))
224
+ return withoutCodexControls;
225
+ return {
226
+ ...withoutCodexControls,
227
+ ...settings.contextWindow === undefined ? {} : { contextWindow: settings.contextWindow },
228
+ ...settings.fast ? { serviceTier: 'priority' } : {},
229
+ };
230
+ }
231
+ /** Put the agent persona first and omit the generic Harness identity opener. */
232
+ export function normalizeCodexPromptAssembly(assembly) {
233
+ const sections = assembly.sections.filter(section => section.name !== 'harness:identity');
234
+ const persona = sections.find(section => section.name === 'deployment:persona-prefix')
235
+ ?? sections.find(section => section.name === 'deployment:persona');
236
+ if (persona === undefined)
237
+ return { ...assembly, sections };
238
+ return {
239
+ ...assembly,
240
+ sections: [persona, ...sections.filter(section => section !== persona)],
241
+ };
242
+ }
243
+ function unquoteContextValue(raw) {
244
+ const trimmed = raw.trim().replace(/\.$/, '');
245
+ if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
246
+ try {
247
+ const parsed = JSON.parse(trimmed);
248
+ if (typeof parsed === 'string')
249
+ return parsed;
250
+ }
251
+ catch {
252
+ // Leave unparsed literal text when not a valid JSON string literal.
253
+ }
254
+ }
255
+ return trimmed;
256
+ }
257
+ function cwdContextValue(cwdText) {
258
+ const match = cwdText?.match(/^Current working directory:\s*(.+?)\.?$/u);
259
+ return match?.[1] === undefined ? undefined : unquoteContextValue(match[1]);
260
+ }
261
+ function promptVariables(assembly) {
262
+ const variables = { ...assembly.variables };
263
+ if (variables.cwd === undefined) {
264
+ const cwdText = assembly.contexts?.find(candidate => candidate.name === 'working-directory:current')?.text;
265
+ const contextMatch = cwdContextValue(cwdText);
266
+ if (contextMatch !== undefined)
267
+ variables.cwd = contextMatch;
268
+ }
269
+ if (variables.sourceRoot === undefined) {
270
+ const source = assembly.sections.find(candidate => candidate.name === 'harness:source')?.text;
271
+ const legacyMatch = source?.match(/^The DeepSeek Harness implementation checkout is at (.+?)\. The checkout location/u);
272
+ if (legacyMatch?.[1] !== undefined) {
273
+ variables.sourceRoot = legacyMatch[1];
274
+ }
275
+ else {
276
+ const ctxText = assembly.contexts?.find(candidate => candidate.name === 'harness:source')?.text;
277
+ const contextMatch = ctxText?.match(/^Current DeepSeek Harness implementation checkout:\s*(.+?)\.?$/u);
278
+ if (contextMatch?.[1] !== undefined)
279
+ variables.sourceRoot = unquoteContextValue(contextMatch[1]);
280
+ }
281
+ }
282
+ if (variables.webUrl === undefined) {
283
+ const web = assembly.sections.find(candidate => candidate.name === 'app:web-surface')?.text;
284
+ const legacyMatch = web?.match(/^You are interacting with the user through the DeepSeek Harness Web GUI at (.+?)\. When/u);
285
+ if (legacyMatch?.[1] !== undefined) {
286
+ variables.webUrl = legacyMatch[1];
287
+ }
288
+ else {
289
+ const ctxText = assembly.contexts?.find(candidate => candidate.name === 'app:web-surface')?.text;
290
+ const contextMatch = ctxText?.match(/^Current DeepSeek Harness Web GUI URL:\s*(.+?)\.?$/u);
291
+ if (contextMatch?.[1] !== undefined)
292
+ variables.webUrl = unquoteContextValue(contextMatch[1]);
293
+ }
294
+ }
295
+ return variables;
296
+ }
297
+ function interpolateCodexPrompt(text, variables) {
298
+ return text.replace(/\{\{([\w.-]+)\}\}/g, (whole, key) => variables[key] ?? whole);
299
+ }
300
+ /** Apply user-editable Persona and DSH Core runtime prompt templates. */
301
+ function applyCodexPromptOverrides(assembly, settings) {
302
+ const overrides = {
303
+ 'deployment:persona': settings.persona,
304
+ 'deployment:persona-prefix': settings.persona,
305
+ 'harness:source': settings.harnessSourcePrompt,
306
+ 'app:web-surface': settings.webSurfacePrompt,
307
+ };
308
+ const defaults = {
309
+ 'deployment:persona': DEFAULT_CODEX_PERSONA,
310
+ 'deployment:persona-prefix': DEFAULT_CODEX_PERSONA,
311
+ 'harness:source': DEFAULT_DSH_CORE_SOURCE_PROMPT,
312
+ 'app:web-surface': DEFAULT_DSH_CORE_WEB_PROMPT,
313
+ };
314
+ const hasCustomOverride = Object.entries(overrides).some(([name, text]) => (text !== undefined && text !== defaults[name]));
315
+ if (!hasCustomOverride)
316
+ return assembly;
317
+ const variables = promptVariables(assembly);
318
+ const sections = assembly.sections.map(section => {
319
+ const template = overrides[section.name];
320
+ return template === undefined || template === defaults[section.name]
321
+ ? section
322
+ : { ...section, text: interpolateCodexPrompt(template, variables) };
323
+ });
324
+ return { ...assembly, sections, variables };
325
+ }
326
+ /** Apply Persona/DSH Core prompt overrides and optional ordering normalization. */
327
+ export function applyCodexPresentationSettings(assembly, settings, protectedNames) {
328
+ const promptSettings = { ...settings };
329
+ if (protectedNames?.has('deployment:persona-prefix'))
330
+ delete promptSettings.persona;
331
+ const withOverrides = applyCodexPromptOverrides(assembly, promptSettings);
332
+ const normalized = settings.promptEnabled ? normalizeCodexPromptAssembly(withOverrides) : withOverrides;
333
+ if (normalized.variables.cwd === undefined
334
+ && normalized.sections.some(section => section.interpolate !== false && section.text.includes('{{cwd}}'))) {
335
+ const variables = promptVariables(normalized);
336
+ if (variables.cwd !== undefined)
337
+ return { ...normalized, variables };
338
+ }
339
+ return normalized;
340
+ }
341
+ /** Build the complete plugin-owned prompt, preserving an intentional empty value. */
342
+ export function buildCodexSystemPrompt(config = {}) {
343
+ return resolveCodexSystemPrompt(config.systemPrompt);
344
+ }
345
+ /** Explicit preset instructions win without changing shared tools or permissions. */
346
+ export function withPresetPrompt(settings, presetPrompt) {
347
+ return presetPrompt === undefined ? settings : { ...settings, systemPrompt: presetPrompt };
348
+ }
349
+ //# sourceMappingURL=runtime-enhancements.js.map
@@ -0,0 +1,15 @@
1
+ /** Automatic compaction fallback when a GPT session uses a window below DSH's 65K headroom floor. */
2
+ import type { Context } from '@deepseek-ai/cordis';
3
+ import type { Session, SessionSeq } from '@deepseek-ai/dsh-session';
4
+ import type { TokenMeasurement } from '@deepseek-ai/dsh-token-meter';
5
+ import type { CodexSettings } from '../contracts/settings.ts';
6
+ interface CompactRange {
7
+ readonly start: SessionSeq;
8
+ readonly end: SessionSeq;
9
+ }
10
+ /** Select the oldest tool-balanced span outside `retainTokens`, preserving a leading system node. */
11
+ export declare function selectSmallWindowRange(session: Session, measurement: TokenMeasurement, retainTokens: number): CompactRange | null;
12
+ /** Bridge pre-step and model-switch compaction for small GPT windows under BasicCompactionEngine. */
13
+ export declare function installSmallWindowCompaction(ctx: Context, currentSettings: () => CodexSettings, lastRequestByAgent: WeakMap<object, unknown>): void;
14
+ export {};
15
+ //# sourceMappingURL=small-window-compaction.d.ts.map
@@ -0,0 +1,121 @@
1
+ /** Automatic compaction fallback when a GPT session uses a window below DSH's 65K headroom floor. */
2
+ import { toolPairingBalancedBefore } from '@deepseek-ai/dsh-compaction';
3
+ import { isGptModel } from "../contracts/settings.js";
4
+ const UPSTREAM_HEADROOM_FLOOR = 80_000;
5
+ const DEFAULT_SMALL_THRESHOLD_RATIO = 0.8;
6
+ const DEFAULT_SMALL_RETAIN_RATIO = 0.16;
7
+ /** Select the oldest tool-balanced span outside `retainTokens`, preserving a leading system node. */
8
+ export function selectSmallWindowRange(session, measurement, retainTokens) {
9
+ const pricedNodes = measurement.nodes;
10
+ if (pricedNodes.length === 0)
11
+ return null;
12
+ const surfaceNodes = session.surface.nodes;
13
+ if (surfaceNodes.length !== pricedNodes.length
14
+ || surfaceNodes.some((seq, index) => seq !== pricedNodes[index]?.seq))
15
+ return null;
16
+ const firstIdx = session.eventAt(surfaceNodes[0])?.type === 'system/message' ? 1 : 0;
17
+ let accumulated = 0;
18
+ let keepFromIdx = pricedNodes.length;
19
+ for (let index = pricedNodes.length - 1; index >= 0; index -= 1) {
20
+ accumulated += pricedNodes[index].tokens;
21
+ keepFromIdx = index;
22
+ if (accumulated >= retainTokens)
23
+ break;
24
+ }
25
+ while (keepFromIdx > firstIdx && !toolPairingBalancedBefore(session, surfaceNodes[keepFromIdx])) {
26
+ keepFromIdx -= 1;
27
+ }
28
+ if (keepFromIdx <= firstIdx)
29
+ return null;
30
+ return { start: surfaceNodes[firstIdx], end: surfaceNodes[keepFromIdx - 1] };
31
+ }
32
+ async function compactSmallWindowIfNeeded(ctx, agent, header, signal, currentSettings, requireBelowThreshold) {
33
+ const provider = header.config?.provider;
34
+ const model = header.config?.model;
35
+ if (typeof provider !== 'string' || typeof model !== 'string' || !isGptModel(model))
36
+ return;
37
+ const agentCtx = agent.ctx ?? ctx;
38
+ const agentPresets = ctx.get?.('agentPresets');
39
+ const compaction = (agentPresets?.serviceFor?.(agent, 'compaction') ?? agentCtx.get('compaction'));
40
+ if (compaction?.compactRegion === undefined || compaction.codexSmallWindowReady === true)
41
+ return;
42
+ const tokenMeter = agentCtx.get('tokenMeter');
43
+ if (tokenMeter?.measure === undefined)
44
+ return;
45
+ const llm = agentCtx.get('llm');
46
+ const info = await llm?.resolveModelInfo?.(provider, model, signal);
47
+ const headerWindow = typeof header.config?.contextWindow === 'number' ? header.config.contextWindow : undefined;
48
+ const effectiveWindow = provider === 'openai-codex'
49
+ ? info?.context?.contextWindow
50
+ : (currentSettings().contextWindow ?? headerWindow ?? info?.context?.contextWindow);
51
+ if (typeof effectiveWindow !== 'number'
52
+ || !Number.isSafeInteger(effectiveWindow)
53
+ || effectiveWindow <= 0
54
+ || effectiveWindow >= UPSTREAM_HEADROOM_FLOOR)
55
+ return;
56
+ const thresholdTokens = Math.max(1_024, Math.floor(effectiveWindow * DEFAULT_SMALL_THRESHOLD_RATIO));
57
+ const retainTokens = Math.floor(effectiveWindow * DEFAULT_SMALL_RETAIN_RATIO);
58
+ let measurement = tokenMeter.measure(agent.session, header);
59
+ if (measurement.totalTokens < thresholdTokens)
60
+ return;
61
+ const pruner = (agentPresets?.serviceFor?.(agent, 'toolResultPruner') ?? agentCtx.get('toolResultPruner'));
62
+ if (pruner?.pruneSession !== undefined) {
63
+ pruner.pruneSession(agent.session);
64
+ measurement = tokenMeter.measure(agent.session, header);
65
+ if (measurement.totalTokens < thresholdTokens)
66
+ return;
67
+ }
68
+ for (let attempt = 0; attempt <= 1; attempt += 1) {
69
+ const range = selectSmallWindowRange(agent.session, measurement, retainTokens);
70
+ if (range === null) {
71
+ if (requireBelowThreshold)
72
+ throw new Error('no safe compaction range can reduce context below small-window threshold');
73
+ return;
74
+ }
75
+ await compaction.compactRegion(range.start, range.end, agent, signal);
76
+ measurement = tokenMeter.measure(agent.session, header);
77
+ if (measurement.totalTokens < thresholdTokens)
78
+ return;
79
+ }
80
+ if (requireBelowThreshold)
81
+ throw new Error('compaction still above small-window threshold');
82
+ }
83
+ /** Bridge pre-step and model-switch compaction for small GPT windows under BasicCompactionEngine. */
84
+ export function installSmallWindowCompaction(ctx, currentSettings, lastRequestByAgent) {
85
+ ctx.on('agent/pre-step', (async ({ agent, signal }, next) => {
86
+ if (!signal.aborted) {
87
+ try {
88
+ const header = agent.session.requestHeader();
89
+ if (header !== undefined)
90
+ await compactSmallWindowIfNeeded(ctx, agent, header, signal, currentSettings, false);
91
+ }
92
+ catch (error) {
93
+ ctx.logger?.warn?.(error);
94
+ }
95
+ }
96
+ return next();
97
+ }), { prepend: true });
98
+ ctx.on('agent/request', (async (payload, next) => {
99
+ try {
100
+ return await next();
101
+ }
102
+ catch (error) {
103
+ const code = error?.code;
104
+ const causeText = String(error?.cause ?? error);
105
+ const agent = payload.agent;
106
+ const resolvedConfig = agent !== undefined && typeof agent === 'object' ? lastRequestByAgent.get(agent) : undefined;
107
+ if (!payload.signal?.aborted
108
+ && code === 'MODEL_SWITCH_COMPACTION_FAILED'
109
+ && causeText.includes('headroom tokens')
110
+ && agent !== undefined
111
+ && resolvedConfig !== undefined
112
+ && payload.signal !== undefined) {
113
+ const previous = agent.session.requestHeader();
114
+ await compactSmallWindowIfNeeded(ctx, agent, { ...previous, config: resolvedConfig }, payload.signal, currentSettings, true);
115
+ return resolvedConfig;
116
+ }
117
+ throw error;
118
+ }
119
+ }), { prepend: true });
120
+ }
121
+ //# sourceMappingURL=small-window-compaction.js.map
@@ -0,0 +1,27 @@
1
+ /** Trusted remote-compaction checkpoints (V1 & V2), retained-user budgeting, and SSE parsing. */
2
+ import type { GenerateOptions } from '@deepseek-ai/dsh-llm';
3
+ export interface JsonObject {
4
+ [key: string]: unknown;
5
+ }
6
+ export declare const REMOTE_COMPACTION_OPEN = "<codex-remote-compaction>";
7
+ export declare const REMOTE_COMPACTION_CLOSE = "</codex-remote-compaction>";
8
+ export declare const CODEX_CONNECT_COMPACTION_OPEN = "<dsh-codex-connect-native-compaction-v1>";
9
+ export declare const MAX_RETAINED_USER_BYTES = 64000;
10
+ /** Recognize either harness-owned or `dsh-codex-connect`-owned remote compaction text. */
11
+ export declare function isAnyRemoteCompactionText(text: string): boolean;
12
+ /** Extract inner checkpoint payload bounded by `<codex-remote-compaction>...</codex-remote-compaction>`. */
13
+ export declare function extractMarkerBody(text: string): string | undefined;
14
+ /** Read-only scan of request messages returning trusted checkpoint marker bodies. */
15
+ export declare function collectTrustedCompactionMarkers(messages: GenerateOptions['messages']): ReadonlySet<string>;
16
+ /** Retain newest user-role input items within an adaptive byte budget below compacted source size. */
17
+ export declare function retainedUserMessagesFromInput(input: readonly JsonObject[], sourceBytes: number, encryptedBytes: number): JsonObject[];
18
+ /** Encode encrypted compaction items plus retained user turns into a replay marker string. */
19
+ export declare function encodeRemoteCompactionCheckpoint(retained: readonly JsonObject[], compactions: readonly JsonObject[]): string;
20
+ /** Decode a V1 or V2 inner checkpoint string back into Responses input items. */
21
+ export declare function decodeRemoteCompactionMarker(inner: string): JsonObject[] | undefined;
22
+ /** Parse either a JSON `/responses/compact` body or a V2 Responses SSE compaction stream. */
23
+ export declare function parseCompactResponsePayload(response: Response): Promise<{
24
+ compactions: JsonObject[];
25
+ usage?: JsonObject;
26
+ }>;
27
+ //# sourceMappingURL=compact-checkpoint.d.ts.map