@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,257 @@
1
+ /** Trusted remote-compaction checkpoints (V1 & V2), retained-user budgeting, and SSE parsing. */
2
+ import { isCompactCheckpointSource } from '@deepseek-ai/dsh-compaction';
3
+ export const REMOTE_COMPACTION_OPEN = '<codex-remote-compaction>';
4
+ export const REMOTE_COMPACTION_CLOSE = '</codex-remote-compaction>';
5
+ export const CODEX_CONNECT_COMPACTION_OPEN = '<dsh-codex-connect-native-compaction-v1>';
6
+ export const MAX_RETAINED_USER_BYTES = 64_000;
7
+ const V2_PREFIX = 'v2:';
8
+ const MAX_CHECKPOINT_PAYLOAD_BYTES = 2 * 1024 * 1024;
9
+ const MAX_COMPACT_STREAM_BYTES = 8 * 1024 * 1024;
10
+ function isJsonObject(value) {
11
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
12
+ }
13
+ function asCompactionItem(item) {
14
+ if (!isJsonObject(item) || item.type !== 'compaction')
15
+ return undefined;
16
+ if (typeof item.encrypted_content !== 'string')
17
+ return undefined;
18
+ const encrypted = item.encrypted_content.trim();
19
+ if (encrypted.length === 0)
20
+ return undefined;
21
+ if (item.id !== undefined && (typeof item.id !== 'string' || item.id.length === 0)) {
22
+ return undefined;
23
+ }
24
+ return {
25
+ type: 'compaction',
26
+ encrypted_content: encrypted,
27
+ ...typeof item.id === 'string' && item.id.length > 0 ? { id: item.id } : {},
28
+ };
29
+ }
30
+ function validateCheckpointItems(items) {
31
+ if (items.length === 0 || items.length > 1024) {
32
+ throw new Error('Invalid Codex v2 compaction checkpoint');
33
+ }
34
+ let compactionCount = 0;
35
+ const validated = [];
36
+ for (const raw of items) {
37
+ const compaction = asCompactionItem(raw);
38
+ if (compaction !== undefined) {
39
+ compactionCount += 1;
40
+ validated.push(compaction);
41
+ continue;
42
+ }
43
+ if (!isJsonObject(raw)
44
+ || raw.role !== 'user'
45
+ || (raw.type !== undefined && raw.type !== 'message')
46
+ || !Array.isArray(raw.content)) {
47
+ throw new Error('Invalid Codex v2 compaction checkpoint');
48
+ }
49
+ validated.push(raw);
50
+ }
51
+ if (compactionCount === 0 || validated.at(-1)?.type !== 'compaction') {
52
+ throw new Error('Invalid Codex v2 compaction checkpoint');
53
+ }
54
+ return validated;
55
+ }
56
+ /** Recognize either harness-owned or `dsh-codex-connect`-owned remote compaction text. */
57
+ export function isAnyRemoteCompactionText(text) {
58
+ return text.includes(REMOTE_COMPACTION_OPEN) || text.includes(CODEX_CONNECT_COMPACTION_OPEN);
59
+ }
60
+ /** Extract inner checkpoint payload bounded by `<codex-remote-compaction>...</codex-remote-compaction>`. */
61
+ export function extractMarkerBody(text) {
62
+ const startOffset = text.indexOf(REMOTE_COMPACTION_OPEN);
63
+ if (startOffset < 0)
64
+ return undefined;
65
+ const start = startOffset + REMOTE_COMPACTION_OPEN.length;
66
+ const end = text.indexOf(REMOTE_COMPACTION_CLOSE, start);
67
+ return end > start ? text.slice(start, end) : undefined;
68
+ }
69
+ /** Read-only scan of request messages returning trusted checkpoint marker bodies. */
70
+ export function collectTrustedCompactionMarkers(messages) {
71
+ const trusted = new Set();
72
+ for (const message of messages) {
73
+ const source = 'source' in message ? message.source : undefined;
74
+ const isTrustedSource = source === undefined
75
+ || (typeof source === 'object' && source !== null
76
+ && isCompactCheckpointSource(source));
77
+ if (!isTrustedSource)
78
+ continue;
79
+ for (const block of message.content) {
80
+ if (block.type !== 'text' || typeof block.text !== 'string')
81
+ continue;
82
+ const inner = extractMarkerBody(block.text);
83
+ if (inner !== undefined)
84
+ trusted.add(inner);
85
+ }
86
+ }
87
+ return trusted;
88
+ }
89
+ /** Retain newest user-role input items within an adaptive byte budget below compacted source size. */
90
+ export function retainedUserMessagesFromInput(input, sourceBytes, encryptedBytes) {
91
+ const adaptiveBudget = Math.floor(sourceBytes * 0.45) - Math.ceil(encryptedBytes * 1.4);
92
+ const budget = Math.max(0, Math.min(MAX_RETAINED_USER_BYTES, adaptiveBudget));
93
+ if (budget <= 2)
94
+ return [];
95
+ const retained = [];
96
+ let used = 0;
97
+ for (let index = input.length - 1; index >= 0; index -= 1) {
98
+ const item = input[index];
99
+ if (item.role !== 'user'
100
+ || (item.type !== undefined && item.type !== 'message')
101
+ || !Array.isArray(item.content)) {
102
+ continue;
103
+ }
104
+ const size = Buffer.byteLength(JSON.stringify(item), 'utf8') + (retained.length === 0 ? 0 : 1);
105
+ if (!Number.isFinite(size) || size <= 0 || size > budget - used)
106
+ continue;
107
+ retained.push(item);
108
+ used += size;
109
+ }
110
+ return retained.reverse();
111
+ }
112
+ /** Encode encrypted compaction items plus retained user turns into a replay marker string. */
113
+ export function encodeRemoteCompactionCheckpoint(retained, compactions) {
114
+ if (compactions.length === 0) {
115
+ throw new Error('Codex remote compaction requires at least one compaction item');
116
+ }
117
+ const validatedCompactions = compactions.map(item => {
118
+ const valid = asCompactionItem(item);
119
+ if (valid === undefined) {
120
+ throw new Error('Codex remote compaction returned an invalid compaction item');
121
+ }
122
+ return valid;
123
+ });
124
+ if (retained.length === 0 && validatedCompactions.length === 1 && validatedCompactions[0].id === undefined) {
125
+ return `${REMOTE_COMPACTION_OPEN}${String(validatedCompactions[0].encrypted_content)}${REMOTE_COMPACTION_CLOSE}`;
126
+ }
127
+ const items = validateCheckpointItems([...retained, ...validatedCompactions]);
128
+ const payload = JSON.stringify({ version: 2, items });
129
+ if (Buffer.byteLength(payload, 'utf8') > MAX_CHECKPOINT_PAYLOAD_BYTES) {
130
+ throw new Error('Codex remote compaction checkpoint exceeds 2 MiB');
131
+ }
132
+ return `${REMOTE_COMPACTION_OPEN}${V2_PREFIX}${Buffer.from(payload, 'utf8').toString('base64url')}${REMOTE_COMPACTION_CLOSE}`;
133
+ }
134
+ /** Decode a V1 or V2 inner checkpoint string back into Responses input items. */
135
+ export function decodeRemoteCompactionMarker(inner) {
136
+ if (inner.length === 0)
137
+ return undefined;
138
+ if (!inner.startsWith(V2_PREFIX)) {
139
+ return [{ type: 'compaction', encrypted_content: inner }];
140
+ }
141
+ const encoded = inner.slice(V2_PREFIX.length);
142
+ if (encoded.length === 0 || Buffer.byteLength(encoded, 'utf8') > Math.ceil(MAX_CHECKPOINT_PAYLOAD_BYTES / 3) * 4 + 32) {
143
+ throw new Error('Invalid Codex v2 compaction checkpoint');
144
+ }
145
+ let decoded;
146
+ try {
147
+ const raw = Buffer.from(encoded, 'base64url');
148
+ if (raw.byteLength > MAX_CHECKPOINT_PAYLOAD_BYTES)
149
+ throw new Error('oversized');
150
+ decoded = JSON.parse(raw.toString('utf8'));
151
+ }
152
+ catch (error) {
153
+ throw new Error('Invalid Codex v2 compaction checkpoint', { cause: error });
154
+ }
155
+ if (!isJsonObject(decoded) || decoded.version !== 2 || !Array.isArray(decoded.items)) {
156
+ throw new Error('Invalid Codex v2 compaction checkpoint');
157
+ }
158
+ return validateCheckpointItems(decoded.items);
159
+ }
160
+ /** Parse either a JSON `/responses/compact` body or a V2 Responses SSE compaction stream. */
161
+ export async function parseCompactResponsePayload(response) {
162
+ const contentType = response.headers.get('content-type')?.toLowerCase() ?? '';
163
+ if (!contentType.includes('text/event-stream')) {
164
+ const body = await response.json();
165
+ const output = Array.isArray(body.output) ? body.output : [];
166
+ const compactions = [];
167
+ for (const item of output) {
168
+ if (!isJsonObject(item) || typeof item.encrypted_content !== 'string')
169
+ continue;
170
+ const encrypted = item.encrypted_content.trim();
171
+ if (encrypted.length === 0)
172
+ continue;
173
+ compactions.push({
174
+ type: 'compaction',
175
+ encrypted_content: encrypted,
176
+ ...typeof item.id === 'string' && item.id.length > 0 ? { id: item.id } : {},
177
+ });
178
+ }
179
+ return {
180
+ compactions,
181
+ ...isJsonObject(body.usage) ? { usage: body.usage } : {},
182
+ };
183
+ }
184
+ if (response.body === null)
185
+ throw new Error('Codex remote compaction stream had no body');
186
+ const reader = response.body.getReader();
187
+ const decoder = new TextDecoder();
188
+ const compactions = [];
189
+ let buffer = '';
190
+ let receivedBytes = 0;
191
+ let completed = false;
192
+ let usage;
193
+ const consumeFrame = (frame) => {
194
+ const data = frame
195
+ .split(/\r?\n/u)
196
+ .filter(line => line.startsWith('data:'))
197
+ .map(line => line.slice(5).trimStart())
198
+ .join('\n')
199
+ .trim();
200
+ if (data.length === 0 || data === '[DONE]')
201
+ return;
202
+ const event = JSON.parse(data);
203
+ if (!isJsonObject(event))
204
+ return;
205
+ if (event.type === 'response.output_item.done') {
206
+ const item = asCompactionItem(event.item);
207
+ if (item !== undefined)
208
+ compactions.push(item);
209
+ return;
210
+ }
211
+ if (event.type === 'response.failed' || event.type === 'error') {
212
+ throw new Error('Codex remote compaction stream reported failure');
213
+ }
214
+ if (event.type !== 'response.completed' && event.type !== 'response.done')
215
+ return;
216
+ const terminal = event.response;
217
+ if (completed || !isJsonObject(terminal) || terminal.status !== 'completed') {
218
+ throw new Error('Codex remote compaction stream ended without completed status');
219
+ }
220
+ if (isJsonObject(terminal.usage))
221
+ usage = terminal.usage;
222
+ completed = true;
223
+ };
224
+ try {
225
+ for (;;) {
226
+ const { done, value } = await reader.read();
227
+ receivedBytes += value?.byteLength ?? 0;
228
+ if (receivedBytes > MAX_COMPACT_STREAM_BYTES) {
229
+ throw new Error('Codex remote compaction stream exceeded 8 MiB limit');
230
+ }
231
+ buffer += decoder.decode(value, { stream: !done });
232
+ for (;;) {
233
+ const match = /\r?\n\r?\n/u.exec(buffer);
234
+ if (match === null)
235
+ break;
236
+ consumeFrame(buffer.slice(0, match.index));
237
+ buffer = buffer.slice(match.index + match[0].length);
238
+ }
239
+ if (done)
240
+ break;
241
+ }
242
+ if (buffer.trim().length > 0)
243
+ consumeFrame(buffer);
244
+ }
245
+ finally {
246
+ await reader.cancel().catch(() => undefined);
247
+ reader.releaseLock();
248
+ }
249
+ if (!completed || compactions.length === 0) {
250
+ throw new Error('Codex remote compaction stream ended without a valid compaction item');
251
+ }
252
+ return {
253
+ compactions,
254
+ ...usage === undefined ? {} : { usage },
255
+ };
256
+ }
257
+ //# sourceMappingURL=compact-checkpoint.js.map
@@ -0,0 +1,16 @@
1
+ /** Scoped fetch interceptor, zstd body codec, and negative capability cache for Responses requests. */
2
+ import type { StreamChunk } from '@deepseek-ai/dsh-llm';
3
+ import type { CodexRequestWireOptions } from './wire-rewrite.ts';
4
+ export declare const CONTEXT_LIMIT_ERROR: RegExp;
5
+ export declare function capabilityKey(url: string, model: unknown): string | undefined;
6
+ export declare function recordUnsupportedCapability(key: string | undefined, flags: {
7
+ hostedWebSearch?: boolean;
8
+ customApplyPatch?: boolean;
9
+ remoteCompact?: boolean;
10
+ }): void;
11
+ export declare function isCompactUnsupported(key: string | undefined): boolean;
12
+ /** Enable the transport patch for this Codex plugin scope only. */
13
+ export declare function installHostedWebSearch(): () => void;
14
+ /** Iterate an existing DSH stream with the hosted-request context installed. */
15
+ export declare function hostedWebSearchStream(next: () => AsyncIterable<StreamChunk>, options?: CodexRequestWireOptions): AsyncIterable<StreamChunk>;
16
+ //# sourceMappingURL=fetch-transport.d.ts.map
@@ -0,0 +1,257 @@
1
+ /** Scoped fetch interceptor, zstd body codec, and negative capability cache for Responses requests. */
2
+ import { AsyncLocalStorage } from 'node:async_hooks';
3
+ import { zstdCompressSync, zstdDecompressSync } from 'node:zlib';
4
+ import { isGptModel } from "../contracts/settings.js";
5
+ import { captureCodexErrors } from "./sse-diagnostics.js";
6
+ import { applyRequestWireOptions, canRewriteApplyPatchHistory, hasFunctionApplyPatchTool, hasRemoteCompaction, hasWebSearchTool, isNativeCompactionTriggerBody, replaceRemoteCompactions, rewriteCodexResponsesBody, } from "./wire-rewrite.js";
7
+ const CAPABILITY_CACHE_TTL_MS = 10 * 60_000;
8
+ const CAPABILITY_CACHE_MAX_ENTRIES = 64;
9
+ export const CONTEXT_LIMIT_ERROR = /context_length_exceeded|maximum context length|context window|too many tokens/i;
10
+ const WEB_SEARCH_ERROR = /web_search|external_web_access/i;
11
+ const CUSTOM_PATCH_ERROR = /apply_patch|custom_tool|custom\s+tool|grammar|lark/i;
12
+ const HOSTED_REQUESTS = new AsyncLocalStorage();
13
+ const unsupportedCapabilities = new Map();
14
+ let hostedPatchUsers = 0;
15
+ let hostedPatchRestore;
16
+ function isResponsesRequest(url) {
17
+ try {
18
+ const path = new URL(url).pathname.replace(/\/+$/, '');
19
+ return path.endsWith('/responses');
20
+ }
21
+ catch {
22
+ return url.replace(/\/+$/, '').endsWith('/responses');
23
+ }
24
+ }
25
+ export function capabilityKey(url, model) {
26
+ if (typeof model !== 'string' || model.length === 0)
27
+ return undefined;
28
+ try {
29
+ const parsed = new URL(url);
30
+ return `${parsed.origin}${parsed.pathname.replace(/\/+$/, '')}\0${model}`;
31
+ }
32
+ catch {
33
+ return `${url.replace(/\/+$/, '')}\0${model}`;
34
+ }
35
+ }
36
+ function effectiveWireOptions(key, options) {
37
+ if (key === undefined)
38
+ return options;
39
+ const cached = unsupportedCapabilities.get(key);
40
+ if (cached === undefined)
41
+ return options;
42
+ if (cached.expiresAt <= Date.now()) {
43
+ unsupportedCapabilities.delete(key);
44
+ return options;
45
+ }
46
+ return {
47
+ ...options,
48
+ ...cached.hostedWebSearch === false ? { hostedWebSearch: false } : {},
49
+ ...cached.customApplyPatch === false ? { customApplyPatch: false } : {},
50
+ };
51
+ }
52
+ export function recordUnsupportedCapability(key, flags) {
53
+ if (key === undefined)
54
+ return;
55
+ const now = Date.now();
56
+ const existing = unsupportedCapabilities.get(key);
57
+ const valid = existing !== undefined && existing.expiresAt > now ? existing : undefined;
58
+ if (existing !== undefined)
59
+ unsupportedCapabilities.delete(key);
60
+ while (unsupportedCapabilities.size >= CAPABILITY_CACHE_MAX_ENTRIES) {
61
+ const oldest = unsupportedCapabilities.keys().next().value;
62
+ if (oldest === undefined)
63
+ break;
64
+ unsupportedCapabilities.delete(oldest);
65
+ }
66
+ unsupportedCapabilities.set(key, {
67
+ ...valid,
68
+ ...flags,
69
+ expiresAt: now + CAPABILITY_CACHE_TTL_MS,
70
+ });
71
+ }
72
+ export function isCompactUnsupported(key) {
73
+ if (key === undefined)
74
+ return false;
75
+ const cached = unsupportedCapabilities.get(key);
76
+ if (cached === undefined)
77
+ return false;
78
+ if (cached.expiresAt <= Date.now()) {
79
+ unsupportedCapabilities.delete(key);
80
+ return false;
81
+ }
82
+ return cached.remoteCompact === false;
83
+ }
84
+ function shouldFallbackResponse(response, errorText) {
85
+ if (response.status !== 400
86
+ && response.status !== 404
87
+ && response.status !== 415
88
+ && response.status !== 422) {
89
+ return false;
90
+ }
91
+ return !CONTEXT_LIMIT_ERROR.test(errorText);
92
+ }
93
+ function isAbortError(error, signal) {
94
+ if (signal.aborted)
95
+ return true;
96
+ return typeof error === 'object' && error !== null && error.name === 'AbortError';
97
+ }
98
+ function isZstdEncoded(headers) {
99
+ return headers.get('content-encoding')?.split(',').some(value => value.trim().toLowerCase() === 'zstd') === true;
100
+ }
101
+ async function parseResponsesBody(request) {
102
+ if (isZstdEncoded(request.headers) && typeof zstdDecompressSync === 'function') {
103
+ const compressed = Buffer.from(await request.clone().arrayBuffer());
104
+ return JSON.parse(zstdDecompressSync(compressed).toString('utf8'));
105
+ }
106
+ return JSON.parse(await request.clone().text());
107
+ }
108
+ function jsonRequest(request, body) {
109
+ const headers = new Headers(request.headers);
110
+ headers.delete('content-length');
111
+ const serialized = JSON.stringify(body);
112
+ if (isZstdEncoded(headers)) {
113
+ if (typeof zstdCompressSync === 'function') {
114
+ return new Request(request, {
115
+ body: new Uint8Array(zstdCompressSync(Buffer.from(serialized, 'utf8'))),
116
+ headers,
117
+ });
118
+ }
119
+ headers.delete('content-encoding');
120
+ }
121
+ return new Request(request, {
122
+ body: serialized,
123
+ headers,
124
+ });
125
+ }
126
+ /**
127
+ * Install a scoped fetch shim for pi-ai's already-built Responses request.
128
+ * The generic DSH adapter remains the owner of auth, streaming, replay, and
129
+ * attachments; this shim changes only Codex's Responses tool and compaction
130
+ * representation at the wire boundary.
131
+ */
132
+ function installGlobalHostedWebSearchPatch() {
133
+ const original = globalThis.fetch;
134
+ const patched = async (input, init) => {
135
+ const options = HOSTED_REQUESTS.getStore();
136
+ if (options === undefined)
137
+ return original(input, init);
138
+ const request = new Request(input, init);
139
+ if (!isResponsesRequest(request.url))
140
+ return original(input, init);
141
+ const requestAndCapture = async (target, requestInit) => captureCodexErrors(await original(target, requestInit));
142
+ let body;
143
+ try {
144
+ body = await parseResponsesBody(request);
145
+ }
146
+ catch {
147
+ return requestAndCapture(input, init);
148
+ }
149
+ if (isNativeCompactionTriggerBody(body))
150
+ return requestAndCapture(input, init);
151
+ const requestBody = applyRequestWireOptions(body, options);
152
+ const baseBody = isGptModel(requestBody.model) && hasRemoteCompaction(requestBody, options.trustedCheckpoints)
153
+ ? replaceRemoteCompactions(requestBody, options.trustedCheckpoints)
154
+ : requestBody;
155
+ const key = capabilityKey(request.url, baseBody.model);
156
+ const activeOptions = effectiveWireOptions(key, options);
157
+ const usesHostedWebSearch = isGptModel(baseBody.model)
158
+ && activeOptions.hostedWebSearch !== false
159
+ && hasWebSearchTool(baseBody);
160
+ const usesCustomApplyPatch = isGptModel(baseBody.model)
161
+ && activeOptions.customApplyPatch !== false
162
+ && hasFunctionApplyPatchTool(baseBody)
163
+ && canRewriteApplyPatchHistory(baseBody);
164
+ if (!usesHostedWebSearch && !usesCustomApplyPatch) {
165
+ return baseBody === body
166
+ ? requestAndCapture(input, init)
167
+ : requestAndCapture(jsonRequest(request, baseBody));
168
+ }
169
+ const hostedBody = rewriteCodexResponsesBody(baseBody, activeOptions);
170
+ const hostedRequest = jsonRequest(request, hostedBody);
171
+ const fallbackRequest = baseBody === body ? request.clone() : jsonRequest(request, baseBody);
172
+ const sendPlainFallback = () => requestAndCapture(fallbackRequest);
173
+ let response;
174
+ try {
175
+ response = await requestAndCapture(hostedRequest);
176
+ }
177
+ catch (error) {
178
+ if (isAbortError(error, request.signal))
179
+ throw error;
180
+ // Transport failures fall back once without poisoning the capability cache.
181
+ return sendPlainFallback();
182
+ }
183
+ if (response.ok)
184
+ return response;
185
+ const errorText = await response.clone().text().catch(() => '');
186
+ if (!shouldFallbackResponse(response, errorText))
187
+ return response;
188
+ const mentionsWebSearch = usesHostedWebSearch && WEB_SEARCH_ERROR.test(errorText);
189
+ const mentionsCustomPatch = usesCustomApplyPatch && CUSTOM_PATCH_ERROR.test(errorText);
190
+ if (usesHostedWebSearch && usesCustomApplyPatch && mentionsWebSearch !== mentionsCustomPatch) {
191
+ const reducedOptions = mentionsWebSearch
192
+ ? { ...activeOptions, hostedWebSearch: false }
193
+ : { ...activeOptions, customApplyPatch: false };
194
+ recordUnsupportedCapability(key, mentionsWebSearch ? { hostedWebSearch: false } : { customApplyPatch: false });
195
+ try {
196
+ const reducedResponse = await requestAndCapture(jsonRequest(request, rewriteCodexResponsesBody(baseBody, reducedOptions)));
197
+ if (reducedResponse.ok)
198
+ return reducedResponse;
199
+ const secondErrorText = await reducedResponse.clone().text().catch(() => '');
200
+ if (!shouldFallbackResponse(reducedResponse, secondErrorText))
201
+ return reducedResponse;
202
+ recordUnsupportedCapability(key, mentionsWebSearch ? { customApplyPatch: false } : { hostedWebSearch: false });
203
+ return sendPlainFallback();
204
+ }
205
+ catch (error) {
206
+ if (isAbortError(error, request.signal))
207
+ throw error;
208
+ return sendPlainFallback();
209
+ }
210
+ }
211
+ recordUnsupportedCapability(key, {
212
+ ...usesHostedWebSearch ? { hostedWebSearch: false } : {},
213
+ ...usesCustomApplyPatch ? { customApplyPatch: false } : {},
214
+ });
215
+ return sendPlainFallback();
216
+ };
217
+ globalThis.fetch = patched;
218
+ return () => {
219
+ if (globalThis.fetch === patched)
220
+ globalThis.fetch = original;
221
+ };
222
+ }
223
+ /** Enable the transport patch for this Codex plugin scope only. */
224
+ export function installHostedWebSearch() {
225
+ hostedPatchUsers += 1;
226
+ hostedPatchRestore ??= installGlobalHostedWebSearchPatch();
227
+ return () => {
228
+ hostedPatchUsers = Math.max(0, hostedPatchUsers - 1);
229
+ if (hostedPatchUsers === 0) {
230
+ hostedPatchRestore?.();
231
+ hostedPatchRestore = undefined;
232
+ unsupportedCapabilities.clear();
233
+ }
234
+ };
235
+ }
236
+ /** Iterate an existing DSH stream with the hosted-request context installed. */
237
+ export function hostedWebSearchStream(next, options = {}) {
238
+ return (async function* () {
239
+ const iterator = HOSTED_REQUESTS.run(options, () => next()[Symbol.asyncIterator]());
240
+ let completed = false;
241
+ try {
242
+ while (true) {
243
+ const item = await HOSTED_REQUESTS.run(options, () => iterator.next());
244
+ if (item.done) {
245
+ completed = true;
246
+ return;
247
+ }
248
+ yield item.value;
249
+ }
250
+ }
251
+ finally {
252
+ if (!completed)
253
+ await HOSTED_REQUESTS.run(options, () => iterator.return?.());
254
+ }
255
+ })();
256
+ }
257
+ //# sourceMappingURL=fetch-transport.js.map
@@ -0,0 +1,13 @@
1
+ /** OpenAI Responses `/responses/compact` and V2 `/responses` transport with local compaction fallback. */
2
+ import type { Context } from '@deepseek-ai/cordis';
3
+ import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm';
4
+ import type { CodexRequestWireOptions } from './wire-rewrite.ts';
5
+ export interface RemoteCodexConfig {
6
+ hostedWebSearch: boolean;
7
+ remoteCompact: boolean;
8
+ }
9
+ /** True only when `llm-pi-ai` configures an OpenAI Responses route directly (never `openai-codex`). */
10
+ export declare function hasDirectResponsesCompactRoute(ctx: Context, provider: string): boolean;
11
+ /** Remote-first compaction waterfall with clean delegation for `openai-codex` and DSH fallback. */
12
+ export declare function remoteCompactStream(ctx: Context, options: GenerateOptions, next: () => AsyncIterable<StreamChunk>, wireOptions?: CodexRequestWireOptions): AsyncIterable<StreamChunk>;
13
+ //# sourceMappingURL=remote-compact.d.ts.map