@shuind/dsh-codex-harness 0.2.1 → 0.2.3

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,14 @@
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 CODEX_ERROR_DIRECTORY = ['diagnostics', 'openai-codex-errors'];
7
12
  const HOSTED_REQUESTS = new AsyncLocalStorage();
8
13
  let hostedPatchUsers = 0;
9
14
  let hostedPatchRestore;
@@ -52,6 +57,87 @@ function isResponsesRequest(url) {
52
57
  return url.replace(/\/+$/, '').endsWith('/responses');
53
58
  }
54
59
  }
60
+ function diagnosticsDirectory() {
61
+ const configured = process.env['DSH_HOME']?.trim();
62
+ const expanded = configured === undefined || configured.length === 0
63
+ ? join(homedir(), '.dsh')
64
+ : configured === '~'
65
+ ? homedir()
66
+ : configured.startsWith('~/') || configured.startsWith('~\\')
67
+ ? join(homedir(), configured.slice(2))
68
+ : configured;
69
+ return join(resolve(expanded), ...CODEX_ERROR_DIRECTORY);
70
+ }
71
+ function saveCodexErrorPayload(payload) {
72
+ const directory = diagnosticsDirectory();
73
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
74
+ const filename = `${Date.now()}-${randomUUID()}.json`;
75
+ writeFileSync(join(directory, filename), `${payload}\n`, { flag: 'wx', mode: 0o600 });
76
+ }
77
+ function errorPayloadFromSseFrame(frame) {
78
+ const data = frame
79
+ .split(/\r?\n/u)
80
+ .filter(line => line.startsWith('data:'))
81
+ .map(line => line.slice(5).trimStart())
82
+ .join('\n')
83
+ .trim();
84
+ if (data.length === 0 || data === '[DONE]')
85
+ return undefined;
86
+ try {
87
+ const payload = JSON.parse(data);
88
+ return payload.type === 'error' || payload.type === 'response.failed' ? data : undefined;
89
+ }
90
+ catch {
91
+ return undefined;
92
+ }
93
+ }
94
+ async function captureCodexErrorPayloads(response) {
95
+ if (response.body === null)
96
+ return;
97
+ const reader = response.body.getReader();
98
+ const decoder = new TextDecoder();
99
+ let buffer = '';
100
+ try {
101
+ while (true) {
102
+ const { done, value } = await reader.read();
103
+ buffer += decoder.decode(value, { stream: !done });
104
+ while (true) {
105
+ const delimiter = /\r?\n\r?\n/u.exec(buffer);
106
+ if (delimiter?.index === undefined)
107
+ break;
108
+ const frame = buffer.slice(0, delimiter.index);
109
+ buffer = buffer.slice(delimiter.index + delimiter[0].length);
110
+ const payload = errorPayloadFromSseFrame(frame);
111
+ if (payload === undefined)
112
+ continue;
113
+ try {
114
+ saveCodexErrorPayload(payload);
115
+ }
116
+ catch {
117
+ // Diagnostics must never replace the provider response or failure.
118
+ }
119
+ }
120
+ if (done)
121
+ return;
122
+ }
123
+ }
124
+ finally {
125
+ reader.releaseLock();
126
+ }
127
+ }
128
+ function captureCodexErrors(response) {
129
+ if (!response.headers.get('content-type')?.toLowerCase().includes('text/event-stream'))
130
+ return response;
131
+ try {
132
+ void captureCodexErrorPayloads(response.clone()).catch(() => {
133
+ // Reading the diagnostic branch must not affect the provider stream.
134
+ });
135
+ }
136
+ catch {
137
+ // An already-consumed response remains usable by its original consumer.
138
+ }
139
+ return response;
140
+ }
55
141
  function isWebSearchTool(tool) {
56
142
  if (typeof tool !== 'object' || tool === null)
57
143
  return false;
@@ -206,15 +292,17 @@ export function rewriteCodexApplyPatchHistory(body) {
206
292
  return changed ? { ...body, input } : body;
207
293
  }
208
294
  /** Compose the plugin-only Responses rewrites without changing DSH's tool API. */
209
- export function rewriteCodexResponsesBody(body) {
295
+ export function rewriteCodexResponsesBody(body, options = {}) {
210
296
  let next = body;
211
- if (hasWebSearchTool(next)) {
297
+ if (options.hostedWebSearch !== false && hasWebSearchTool(next)) {
212
298
  next = addHostedWebSearch(next);
213
299
  }
214
300
  else if (hasRemoteCompaction(next)) {
215
301
  next = replaceRemoteCompactions(next);
216
302
  }
217
- if (hasFunctionApplyPatchTool(next) && canRewriteApplyPatchHistory(next)) {
303
+ if (options.customApplyPatch !== false
304
+ && hasFunctionApplyPatchTool(next)
305
+ && canRewriteApplyPatchHistory(next)) {
218
306
  next = addCodexApplyPatch(next);
219
307
  next = rewriteCodexApplyPatchHistory(next);
220
308
  }
@@ -266,11 +354,13 @@ function hasRemoteCompaction(body) {
266
354
  && String(part.text).includes(REMOTE_COMPACTION_OPEN)));
267
355
  });
268
356
  }
269
- function canPatchBody(body) {
357
+ function canPatchBody(body, options) {
270
358
  return isGptModel(body.model)
271
- && (hasWebSearchTool(body)
359
+ && ((options.hostedWebSearch !== false && hasWebSearchTool(body))
272
360
  || hasRemoteCompaction(body)
273
- || (hasFunctionApplyPatchTool(body) && canRewriteApplyPatchHistory(body)));
361
+ || (options.customApplyPatch !== false
362
+ && hasFunctionApplyPatchTool(body)
363
+ && canRewriteApplyPatchHistory(body)));
274
364
  }
275
365
  /** Add provider options that older pi-ai adapters do not copy themselves. */
276
366
  function applyRequestWireOptions(body, options) {
@@ -293,20 +383,21 @@ function installGlobalHostedWebSearchPatch() {
293
383
  const request = new Request(input, init);
294
384
  if (!isResponsesRequest(request.url))
295
385
  return original(input, init);
386
+ const requestAndCapture = async (target, requestInit) => captureCodexErrors(await original(target, requestInit));
296
387
  let body;
297
388
  try {
298
389
  body = JSON.parse(await request.clone().text());
299
390
  }
300
391
  catch {
301
- return original(input, init);
392
+ return requestAndCapture(input, init);
302
393
  }
303
394
  const requestBody = applyRequestWireOptions(body, options);
304
- if (!canPatchBody(requestBody)) {
395
+ if (!canPatchBody(requestBody, options)) {
305
396
  if (requestBody === body)
306
- return original(input, init);
397
+ return requestAndCapture(input, init);
307
398
  const headers = new Headers(request.headers);
308
399
  headers.delete('content-length');
309
- return original(new Request(request, {
400
+ return requestAndCapture(new Request(request, {
310
401
  body: JSON.stringify(requestBody),
311
402
  headers,
312
403
  }));
@@ -322,21 +413,21 @@ function installGlobalHostedWebSearchPatch() {
322
413
  const headers = new Headers(request.headers);
323
414
  headers.delete('content-length');
324
415
  const hostedRequest = new Request(request, {
325
- body: JSON.stringify(rewriteCodexResponsesBody(requestBody)),
416
+ body: JSON.stringify(rewriteCodexResponsesBody(requestBody, options)),
326
417
  headers,
327
418
  });
328
419
  try {
329
- const hostedResponse = await original(hostedRequest);
420
+ const hostedResponse = await requestAndCapture(hostedRequest);
330
421
  // A rejected hosted-tool request is retried with the untouched request so
331
422
  // dsh-tool-web can still produce the normal local function-tool path.
332
423
  if (!hostedResponse.ok)
333
- return original(fallbackRequest);
424
+ return requestAndCapture(fallbackRequest);
334
425
  return hostedResponse;
335
426
  }
336
427
  catch {
337
428
  // Network and transport failures must have the same fallback behavior as
338
429
  // an HTTP rejection; the local function-tool path remains available.
339
- return original(fallbackRequest);
430
+ return requestAndCapture(fallbackRequest);
340
431
  }
341
432
  };
342
433
  globalThis.fetch = patched;
@@ -436,7 +527,7 @@ function responsesTools(tools) {
436
527
  parameters: tool.parameters,
437
528
  }));
438
529
  }
439
- function compactBody(options) {
530
+ function compactBody(options, wireOptions = {}) {
440
531
  const tools = responsesTools(options.tools);
441
532
  const body = {
442
533
  model: options.model,
@@ -449,7 +540,10 @@ function compactBody(options) {
449
540
  ...options.reasoningEffort === undefined ? {} : { reasoning: { effort: options.reasoningEffort } },
450
541
  };
451
542
  const compacted = replaceRemoteCompactions(body);
452
- return options.tools?.some(tool => tool.name === 'web_search') ? addHostedWebSearch(compacted) : compacted;
543
+ return wireOptions.hostedWebSearch !== false
544
+ && options.tools?.some(tool => tool.name === 'web_search')
545
+ ? addHostedWebSearch(compacted)
546
+ : compacted;
453
547
  }
454
548
  function compactText(body) {
455
549
  const output = Array.isArray(body.output) ? body.output : [];
@@ -494,7 +588,7 @@ function compactUsage(body) {
494
588
  ...cacheWriteTokens !== undefined && cacheWriteTokens > 0 ? { cacheWriteTokens } : {},
495
589
  };
496
590
  }
497
- async function remoteCompact(ctx, options) {
591
+ async function remoteCompact(ctx, options, wireOptions = {}) {
498
592
  const profile = profileOf(ctx, options.provider);
499
593
  if (!supportsResponses(profile, options.provider) || profile?.baseURL === undefined) {
500
594
  throw new Error('Codex remote compaction requires an OpenAI Responses provider with baseURL');
@@ -505,7 +599,7 @@ async function remoteCompact(ctx, options) {
505
599
  const response = await fetch(responsesEndpoint(profile.baseURL, 'responses/compact'), {
506
600
  method: 'POST',
507
601
  headers,
508
- body: JSON.stringify(compactBody(options)),
602
+ body: JSON.stringify(compactBody(options, wireOptions)),
509
603
  ...options.signal === undefined ? {} : { signal: options.signal },
510
604
  });
511
605
  if (!response.ok)
@@ -518,10 +612,10 @@ async function remoteCompact(ctx, options) {
518
612
  return { text, ...usage === undefined ? {} : { usage } };
519
613
  }
520
614
  /** Remote-first compaction waterfall with the existing DSH path as fallback. */
521
- export function remoteCompactStream(ctx, options, next) {
615
+ export function remoteCompactStream(ctx, options, next, wireOptions = {}) {
522
616
  return (async function* () {
523
617
  try {
524
- const result = await remoteCompact(ctx, options);
618
+ const result = await remoteCompact(ctx, options, wireOptions);
525
619
  yield { type: 'block-start', index: 0, blockType: 'text' };
526
620
  yield { type: 'text-delta', index: 0, text: result.text };
527
621
  yield { type: 'block-end', index: 0, block: { type: 'text', text: result.text } };
@@ -537,7 +631,10 @@ export function remoteCompactStream(ctx, options, next) {
537
631
  // The local fallback still replays the marker through a later GPT
538
632
  // Responses request, so it needs the same scoped wire context.
539
633
  const serviceTier = serviceTierOf(options);
540
- yield* hostedWebSearchStream(next, serviceTier === undefined ? {} : { serviceTier });
634
+ yield* hostedWebSearchStream(next, {
635
+ ...wireOptions,
636
+ ...serviceTier === undefined ? {} : { serviceTier },
637
+ });
541
638
  }
542
639
  })();
543
640
  }
@@ -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.1",
3
+ "version": "0.2.3",
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