@shuind/dsh-codex-harness 0.2.2 → 0.2.4

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.
@@ -1,9 +1,15 @@
1
1
  import { credentialRef } from '@deepseek-ai/dsh-credentials';
2
2
  import { AsyncLocalStorage } from 'node:async_hooks';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { mkdirSync, writeFileSync } from 'node:fs';
5
+ import { homedir } from 'node:os';
6
+ import { join, resolve } from 'node:path';
3
7
  import { APPLY_PATCH_DESCRIPTION, APPLY_PATCH_GRAMMAR } from "./patch.js";
4
8
  const SETTINGS_NAMESPACE = 'llm-pi-ai';
5
9
  const REMOTE_COMPACTION_OPEN = '<codex-remote-compaction>';
6
10
  const REMOTE_COMPACTION_CLOSE = '</codex-remote-compaction>';
11
+ const CONTEXT_WINDOW_EXCEEDED_CODE = 'CONTEXT_WINDOW_EXCEEDED';
12
+ const CODEX_ERROR_DIRECTORY = ['diagnostics', 'openai-codex-errors'];
7
13
  const HOSTED_REQUESTS = new AsyncLocalStorage();
8
14
  let hostedPatchUsers = 0;
9
15
  let hostedPatchRestore;
@@ -52,6 +58,87 @@ function isResponsesRequest(url) {
52
58
  return url.replace(/\/+$/, '').endsWith('/responses');
53
59
  }
54
60
  }
61
+ function diagnosticsDirectory() {
62
+ const configured = process.env['DSH_HOME']?.trim();
63
+ const expanded = configured === undefined || configured.length === 0
64
+ ? join(homedir(), '.dsh')
65
+ : configured === '~'
66
+ ? homedir()
67
+ : configured.startsWith('~/') || configured.startsWith('~\\')
68
+ ? join(homedir(), configured.slice(2))
69
+ : configured;
70
+ return join(resolve(expanded), ...CODEX_ERROR_DIRECTORY);
71
+ }
72
+ function saveCodexErrorPayload(payload) {
73
+ const directory = diagnosticsDirectory();
74
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
75
+ const filename = `${Date.now()}-${randomUUID()}.json`;
76
+ writeFileSync(join(directory, filename), `${payload}\n`, { flag: 'wx', mode: 0o600 });
77
+ }
78
+ function errorPayloadFromSseFrame(frame) {
79
+ const data = frame
80
+ .split(/\r?\n/u)
81
+ .filter(line => line.startsWith('data:'))
82
+ .map(line => line.slice(5).trimStart())
83
+ .join('\n')
84
+ .trim();
85
+ if (data.length === 0 || data === '[DONE]')
86
+ return undefined;
87
+ try {
88
+ const payload = JSON.parse(data);
89
+ return payload.type === 'error' || payload.type === 'response.failed' ? data : undefined;
90
+ }
91
+ catch {
92
+ return undefined;
93
+ }
94
+ }
95
+ async function captureCodexErrorPayloads(response) {
96
+ if (response.body === null)
97
+ return;
98
+ const reader = response.body.getReader();
99
+ const decoder = new TextDecoder();
100
+ let buffer = '';
101
+ try {
102
+ while (true) {
103
+ const { done, value } = await reader.read();
104
+ buffer += decoder.decode(value, { stream: !done });
105
+ while (true) {
106
+ const delimiter = /\r?\n\r?\n/u.exec(buffer);
107
+ if (delimiter?.index === undefined)
108
+ break;
109
+ const frame = buffer.slice(0, delimiter.index);
110
+ buffer = buffer.slice(delimiter.index + delimiter[0].length);
111
+ const payload = errorPayloadFromSseFrame(frame);
112
+ if (payload === undefined)
113
+ continue;
114
+ try {
115
+ saveCodexErrorPayload(payload);
116
+ }
117
+ catch {
118
+ // Diagnostics must never replace the provider response or failure.
119
+ }
120
+ }
121
+ if (done)
122
+ return;
123
+ }
124
+ }
125
+ finally {
126
+ reader.releaseLock();
127
+ }
128
+ }
129
+ function captureCodexErrors(response) {
130
+ if (!response.headers.get('content-type')?.toLowerCase().includes('text/event-stream'))
131
+ return response;
132
+ try {
133
+ void captureCodexErrorPayloads(response.clone()).catch(() => {
134
+ // Reading the diagnostic branch must not affect the provider stream.
135
+ });
136
+ }
137
+ catch {
138
+ // An already-consumed response remains usable by its original consumer.
139
+ }
140
+ return response;
141
+ }
55
142
  function isWebSearchTool(tool) {
56
143
  if (typeof tool !== 'object' || tool === null)
57
144
  return false;
@@ -206,15 +293,17 @@ export function rewriteCodexApplyPatchHistory(body) {
206
293
  return changed ? { ...body, input } : body;
207
294
  }
208
295
  /** Compose the plugin-only Responses rewrites without changing DSH's tool API. */
209
- export function rewriteCodexResponsesBody(body) {
296
+ export function rewriteCodexResponsesBody(body, options = {}) {
210
297
  let next = body;
211
- if (hasWebSearchTool(next)) {
298
+ if (options.hostedWebSearch !== false && hasWebSearchTool(next)) {
212
299
  next = addHostedWebSearch(next);
213
300
  }
214
301
  else if (hasRemoteCompaction(next)) {
215
302
  next = replaceRemoteCompactions(next);
216
303
  }
217
- if (hasFunctionApplyPatchTool(next) && canRewriteApplyPatchHistory(next)) {
304
+ if (options.customApplyPatch !== false
305
+ && hasFunctionApplyPatchTool(next)
306
+ && canRewriteApplyPatchHistory(next)) {
218
307
  next = addCodexApplyPatch(next);
219
308
  next = rewriteCodexApplyPatchHistory(next);
220
309
  }
@@ -266,11 +355,13 @@ function hasRemoteCompaction(body) {
266
355
  && String(part.text).includes(REMOTE_COMPACTION_OPEN)));
267
356
  });
268
357
  }
269
- function canPatchBody(body) {
358
+ function canPatchBody(body, options) {
270
359
  return isGptModel(body.model)
271
- && (hasWebSearchTool(body)
360
+ && ((options.hostedWebSearch !== false && hasWebSearchTool(body))
272
361
  || hasRemoteCompaction(body)
273
- || (hasFunctionApplyPatchTool(body) && canRewriteApplyPatchHistory(body)));
362
+ || (options.customApplyPatch !== false
363
+ && hasFunctionApplyPatchTool(body)
364
+ && canRewriteApplyPatchHistory(body)));
274
365
  }
275
366
  /** Add provider options that older pi-ai adapters do not copy themselves. */
276
367
  function applyRequestWireOptions(body, options) {
@@ -293,20 +384,21 @@ function installGlobalHostedWebSearchPatch() {
293
384
  const request = new Request(input, init);
294
385
  if (!isResponsesRequest(request.url))
295
386
  return original(input, init);
387
+ const requestAndCapture = async (target, requestInit) => captureCodexErrors(await original(target, requestInit));
296
388
  let body;
297
389
  try {
298
390
  body = JSON.parse(await request.clone().text());
299
391
  }
300
392
  catch {
301
- return original(input, init);
393
+ return requestAndCapture(input, init);
302
394
  }
303
395
  const requestBody = applyRequestWireOptions(body, options);
304
- if (!canPatchBody(requestBody)) {
396
+ if (!canPatchBody(requestBody, options)) {
305
397
  if (requestBody === body)
306
- return original(input, init);
398
+ return requestAndCapture(input, init);
307
399
  const headers = new Headers(request.headers);
308
400
  headers.delete('content-length');
309
- return original(new Request(request, {
401
+ return requestAndCapture(new Request(request, {
310
402
  body: JSON.stringify(requestBody),
311
403
  headers,
312
404
  }));
@@ -322,21 +414,21 @@ function installGlobalHostedWebSearchPatch() {
322
414
  const headers = new Headers(request.headers);
323
415
  headers.delete('content-length');
324
416
  const hostedRequest = new Request(request, {
325
- body: JSON.stringify(rewriteCodexResponsesBody(requestBody)),
417
+ body: JSON.stringify(rewriteCodexResponsesBody(requestBody, options)),
326
418
  headers,
327
419
  });
328
420
  try {
329
- const hostedResponse = await original(hostedRequest);
421
+ const hostedResponse = await requestAndCapture(hostedRequest);
330
422
  // A rejected hosted-tool request is retried with the untouched request so
331
423
  // dsh-tool-web can still produce the normal local function-tool path.
332
424
  if (!hostedResponse.ok)
333
- return original(fallbackRequest);
425
+ return requestAndCapture(fallbackRequest);
334
426
  return hostedResponse;
335
427
  }
336
428
  catch {
337
429
  // Network and transport failures must have the same fallback behavior as
338
430
  // an HTTP rejection; the local function-tool path remains available.
339
- return original(fallbackRequest);
431
+ return requestAndCapture(fallbackRequest);
340
432
  }
341
433
  };
342
434
  globalThis.fetch = patched;
@@ -378,6 +470,47 @@ export function hostedWebSearchStream(next, options = {}) {
378
470
  }
379
471
  })();
380
472
  }
473
+ function contextTokens(usage) {
474
+ const fields = [
475
+ usage.inputTokens,
476
+ usage.outputTokens,
477
+ usage.cacheReadTokens ?? 0,
478
+ usage.cacheWriteTokens ?? 0,
479
+ ];
480
+ if (fields.some(value => !Number.isSafeInteger(value) || value < 0))
481
+ return undefined;
482
+ const total = fields.reduce((sum, value) => sum + value, 0);
483
+ return Number.isSafeInteger(total) ? total : undefined;
484
+ }
485
+ /**
486
+ * Correct the usage-only overflow verdict emitted by pi-ai adapters that do
487
+ * not yet consume the request-scoped Codex capacity.
488
+ */
489
+ export function repairLegacyPiAiContextOverflow(stream, model, contextWindow) {
490
+ return (async function* () {
491
+ let usage;
492
+ for await (const chunk of stream) {
493
+ if (chunk.type === 'usage')
494
+ usage = chunk.usage;
495
+ const usedTokens = usage === undefined ? undefined : contextTokens(usage);
496
+ if (chunk.type === 'finish'
497
+ && chunk.reason.kind === 'error'
498
+ && chunk.reason.failure.code === CONTEXT_WINDOW_EXCEEDED_CODE
499
+ && chunk.reason.failure.message === `pi-ai detected context overflow for model "${model}"`
500
+ && typeof contextWindow === 'number'
501
+ && Number.isSafeInteger(contextWindow)
502
+ && contextWindow > 0
503
+ && usage !== undefined
504
+ && usage.outputTokens > 0
505
+ && usedTokens !== undefined
506
+ && usedTokens <= contextWindow) {
507
+ yield { ...chunk, reason: { kind: 'stop' } };
508
+ continue;
509
+ }
510
+ yield chunk;
511
+ }
512
+ })();
513
+ }
381
514
  function textOf(message) {
382
515
  return message.content
383
516
  .filter(block => block.type === 'text')
@@ -436,7 +569,7 @@ function responsesTools(tools) {
436
569
  parameters: tool.parameters,
437
570
  }));
438
571
  }
439
- function compactBody(options) {
572
+ function compactBody(options, wireOptions = {}) {
440
573
  const tools = responsesTools(options.tools);
441
574
  const body = {
442
575
  model: options.model,
@@ -449,7 +582,10 @@ function compactBody(options) {
449
582
  ...options.reasoningEffort === undefined ? {} : { reasoning: { effort: options.reasoningEffort } },
450
583
  };
451
584
  const compacted = replaceRemoteCompactions(body);
452
- return options.tools?.some(tool => tool.name === 'web_search') ? addHostedWebSearch(compacted) : compacted;
585
+ return wireOptions.hostedWebSearch !== false
586
+ && options.tools?.some(tool => tool.name === 'web_search')
587
+ ? addHostedWebSearch(compacted)
588
+ : compacted;
453
589
  }
454
590
  function compactText(body) {
455
591
  const output = Array.isArray(body.output) ? body.output : [];
@@ -494,7 +630,7 @@ function compactUsage(body) {
494
630
  ...cacheWriteTokens !== undefined && cacheWriteTokens > 0 ? { cacheWriteTokens } : {},
495
631
  };
496
632
  }
497
- async function remoteCompact(ctx, options) {
633
+ async function remoteCompact(ctx, options, wireOptions = {}) {
498
634
  const profile = profileOf(ctx, options.provider);
499
635
  if (!supportsResponses(profile, options.provider) || profile?.baseURL === undefined) {
500
636
  throw new Error('Codex remote compaction requires an OpenAI Responses provider with baseURL');
@@ -505,7 +641,7 @@ async function remoteCompact(ctx, options) {
505
641
  const response = await fetch(responsesEndpoint(profile.baseURL, 'responses/compact'), {
506
642
  method: 'POST',
507
643
  headers,
508
- body: JSON.stringify(compactBody(options)),
644
+ body: JSON.stringify(compactBody(options, wireOptions)),
509
645
  ...options.signal === undefined ? {} : { signal: options.signal },
510
646
  });
511
647
  if (!response.ok)
@@ -518,10 +654,10 @@ async function remoteCompact(ctx, options) {
518
654
  return { text, ...usage === undefined ? {} : { usage } };
519
655
  }
520
656
  /** Remote-first compaction waterfall with the existing DSH path as fallback. */
521
- export function remoteCompactStream(ctx, options, next) {
657
+ export function remoteCompactStream(ctx, options, next, wireOptions = {}) {
522
658
  return (async function* () {
523
659
  try {
524
- const result = await remoteCompact(ctx, options);
660
+ const result = await remoteCompact(ctx, options, wireOptions);
525
661
  yield { type: 'block-start', index: 0, blockType: 'text' };
526
662
  yield { type: 'text-delta', index: 0, text: result.text };
527
663
  yield { type: 'block-end', index: 0, block: { type: 'text', text: result.text } };
@@ -537,7 +673,10 @@ export function remoteCompactStream(ctx, options, next) {
537
673
  // The local fallback still replays the marker through a later GPT
538
674
  // Responses request, so it needs the same scoped wire context.
539
675
  const serviceTier = serviceTierOf(options);
540
- yield* hostedWebSearchStream(next, serviceTier === undefined ? {} : { serviceTier });
676
+ yield* hostedWebSearchStream(next, {
677
+ ...wireOptions,
678
+ ...serviceTier === undefined ? {} : { serviceTier },
679
+ });
541
680
  }
542
681
  })();
543
682
  }
@@ -9,6 +9,20 @@ export interface CodexSettings {
9
9
  contextWindow?: number;
10
10
  /** Complete plugin-owned Codex operating prompt. */
11
11
  systemPrompt?: string;
12
+ /** Inject the plugin-owned Codex operating prompt. */
13
+ promptEnabled: boolean;
14
+ /** Expose exec_command and write_stdin. */
15
+ terminalToolsEnabled: boolean;
16
+ /** Expose apply_patch. */
17
+ patchToolEnabled: boolean;
18
+ /** Expose update_plan. */
19
+ planToolEnabled: boolean;
20
+ /** Upgrade local web_search declarations to the hosted Responses tool. */
21
+ hostedWebSearchEnabled: boolean;
22
+ /** Prefer the provider's Responses compact endpoint. */
23
+ remoteCompactionEnabled: boolean;
24
+ /** Show the Codex request/compaction activity indicator. */
25
+ activityIndicatorEnabled: boolean;
12
26
  }
13
27
  /** Default settings exposed even before a Codex session is opened. */
14
28
  export declare const CODEX_SETTINGS_ENTRY: CodexSettings;
@@ -9,10 +9,24 @@ export const CODEX_SETTINGS_NAMESPACE = settingsNamespace('codex');
9
9
  export const CODEX_SETTINGS_ENTRY = {
10
10
  fast: false,
11
11
  systemPrompt: DEFAULT_CODEX_SYSTEM_PROMPT,
12
+ promptEnabled: true,
13
+ terminalToolsEnabled: true,
14
+ patchToolEnabled: true,
15
+ planToolEnabled: true,
16
+ hostedWebSearchEnabled: true,
17
+ remoteCompactionEnabled: true,
18
+ activityIndicatorEnabled: true,
12
19
  };
13
20
  export const CODEX_SETTINGS_SCHEMA = z.object({
14
21
  fast: z.boolean().default(false),
15
22
  contextWindow: z.number().step(1).min(1).max(CODEX_CONTEXT_MAX),
16
23
  systemPrompt: z.string().default(DEFAULT_CODEX_SYSTEM_PROMPT),
24
+ promptEnabled: z.boolean().default(true),
25
+ terminalToolsEnabled: z.boolean().default(true),
26
+ patchToolEnabled: z.boolean().default(true),
27
+ planToolEnabled: z.boolean().default(true),
28
+ hostedWebSearchEnabled: z.boolean().default(true),
29
+ remoteCompactionEnabled: z.boolean().default(true),
30
+ activityIndicatorEnabled: z.boolean().default(true),
17
31
  });
18
32
  //# sourceMappingURL=settings.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shuind/dsh-codex-harness",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "description": "Codex coding preset with customizable prompts and tools for DSH.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -14,10 +14,14 @@
14
14
  config:
15
15
  maxBytes: 65536
16
16
 
17
- # The Codex layer owns its prompt overlay and core tool names; execution
18
- # remains delegated to dsh.
17
+ # The editable Codex operating prompt and its four core tools are available
18
+ # only inside this preset. Global request enhancements are mounted by the
19
+ # bundle row and must not be installed twice in this agent scope.
19
20
  - id: codex-tools
20
21
  name: '@shuind/dsh-codex-harness'
22
+ config:
23
+ globalEnhancements: false
24
+ codexCore: true
21
25
 
22
26
  # Background-job guidance and completion delivery belong to the official
23
27
  # dsh-tool-jobs plugin. Use wakeup delivery so an idle agent also learns about
@@ -28,8 +32,8 @@
28
32
  completionDelivery: wakeup
29
33
 
30
34
  # The generic DSH pi-ai adapter still owns the user's configured provider,
31
- # endpoint, API key, and model. Codex's remote-first transport wrapper is
32
- # installed only in this Codex scope and falls back to the generic DSH path.
35
+ # endpoint, API key, and model. The global Codex capability layer owns the
36
+ # optional remote-first transport wrapper and falls back to the generic path.
33
37
 
34
38
  # Keep the local tool mounted as the fallback. Codex rewrites the final GPT
35
39
  # Responses request to a hosted web_search tool first; a failed remote request