@shuind/dsh-codex-harness 0.1.22 → 0.1.23

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.
package/README.md CHANGED
@@ -10,6 +10,7 @@
10
10
  - **GPT 能力补全**:为 GPT 系列模型补充图片输入和思考强度选项;不会覆盖用户已有的显式配置。
11
11
  - **Fast**:仅在 Codex preset 的模型选择菜单中显示,开启后向 Responses 请求发送 `service_tier: "priority"`。
12
12
  - **旧版 Web 兼容**:在未提供新版模型设置/上下文设置 slot 的 DSH Web 中,Fast 和上下文容量会自动回退到旧版 composer slot;client 注入不依赖纯类型 slot 包。
13
+ - **Responses 原生 apply_patch**:在 GPT Responses 请求的插件传输边界,把普通 JSON function tool 改写为 `type: "custom"` + OpenAI `lark` grammar;下一轮历史同步改写为 `custom_tool_call`。如果中转站拒绝 custom tool,则自动回退到普通 function tool,不改变 DSH 工具执行器。
13
14
  - **远程搜索与压缩**:OpenAI Responses 请求默认优先使用 hosted `web_search` 和 `/responses/compact`;失败时回退到 DSH 的本地实现。
14
15
  - **上下文容量**:在 Web 中设置 `1K`–`1000K` tokens,设置值作用于下一次请求。
15
16
  - **活动状态**:Codex 等待模型响应或进行上下文压缩时,在输入框上方显示对应状态和耗时,让长时间 Deep Diving 不再像卡住。
@@ -17,7 +18,7 @@
17
18
  ## 安装
18
19
 
19
20
  ```sh
20
- dsh plugin --profile web add @shuind/dsh-codex-harness@0.1.22
21
+ dsh plugin --profile web add @shuind/dsh-codex-harness@0.1.23
21
22
  ```
22
23
 
23
24
  重启 Web,创建新会话,在模式菜单中选择 **Codex 模式**。
@@ -56,7 +57,7 @@ Fast 设置保存在 `codex` 命名空间,只对 Codex preset 生效。
56
57
 
57
58
  ### 活动状态
58
59
 
59
- Codex 等待模型首个输出时,Web 输入框上方会显示 `正在等待模型响应... · Ns`;开始上下文压缩后会切换为 `正在压缩上下文... · Ns`。收到模型输出、压缩结束或下一轮开始后自动隐藏。该状态由 Host 的 `sessionProjections` 投影驱动,因此本地压缩和远程 `/responses/compact` 都会显示同一种状态。
60
+ Codex 等待模型首个输出时,Web 会在 `Deep diving...` 右侧显示 `正在等待模型响应... · Ns`;开始上下文压缩后会切换为 `正在压缩上下文... · Ns`。收到模型输出、压缩结束或下一轮开始后自动隐藏。该状态由 Host 的 `sessionProjections` 投影驱动,因此本地压缩和远程 `/responses/compact` 都会显示同一种状态。
60
61
 
61
62
  如果当前 DSH 组合没有加载 projection 服务,插件会跳过注册,客户端也会自动隐藏这行,不影响普通会话。
62
63
 
@@ -127,6 +128,7 @@ Make things as effortless as possible for the user.
127
128
  - preset 在创建会话时确定;已有会话不会自动切换到 Codex 模式。
128
129
  - GPT 模型的图片输入和思考强度属于能力补全;用户已明确配置的字段会被保留。
129
130
  - hosted search、远程压缩以及 reasoning 参数的可用性取决于实际 Responses 中转站和模型。
131
+ - `apply_patch` 的 custom grammar 改写只作用于 GPT Responses 请求;中转站必须接受 OpenAI custom tools 和 Lark grammar。拒绝时插件会自动发送原始 JSON function-call 请求。
130
132
 
131
133
  ## License
132
134
 
package/lib/client.js CHANGED
@@ -30,6 +30,8 @@ window.__ModuleLoader__.load({
30
30
  const SETTINGS_NAMESPACE = "codex";
31
31
  const MODEL_SETTINGS_SLOT = "conversation.input.model.settings";
32
32
  const CONTEXT_SETTINGS_SLOT = "conversation.input.context.settings";
33
+ const ACTIVITY_SLOT = "conversation.chat.status";
34
+ const ACTIVITY_FALLBACK_SLOT = "conversation.composer.dock";
33
35
  const FAST_FALLBACK_SLOT = "conversation.input.right";
34
36
  const CONTEXT_FALLBACK_SLOT = "conversation.input.dock";
35
37
  const DEFAULT_CONTEXT_WINDOW = 262144;
@@ -292,19 +294,19 @@ window.__ModuleLoader__.load({
292
294
  }, [agentPreset, activity?.startedAt]);
293
295
  if (agentPreset !== "codex" || activity === void 0 || activity === null) return null;
294
296
  const label = activity.activity === "awaiting-model" ? t("activityAwaitingModel") : t("activityCompacting");
295
- return (0, react_jsx_runtime.jsxs)("div", {
297
+ return (0, react_jsx_runtime.jsxs)("span", {
296
298
  id: "codex-activity",
297
299
  role: "status",
298
300
  "aria-live": "polite",
299
301
  style: {
300
- display: "flex",
302
+ display: "inline-flex",
301
303
  alignItems: "center",
302
304
  gap: 7,
303
- minHeight: 28,
304
- padding: "4px 10px",
305
+ minHeight: 26,
305
306
  color: "var(--dsw-alias-label-secondary)",
306
307
  fontSize: 12,
307
- lineHeight: "20px"
308
+ lineHeight: "20px",
309
+ whiteSpace: "nowrap"
308
310
  },
309
311
  children: [
310
312
  (0, react_jsx_runtime.jsx)("span", {
@@ -329,6 +331,18 @@ window.__ModuleLoader__.load({
329
331
  ]
330
332
  });
331
333
  }
334
+ /** Preserve the old composer-dock footprint for hosts without the chat status seat. */
335
+ function ActivityDock(props) {
336
+ return (0, react_jsx_runtime.jsx)("div", {
337
+ style: {
338
+ display: "flex",
339
+ alignItems: "center",
340
+ minHeight: 28,
341
+ padding: "4px 10px"
342
+ },
343
+ children: (0, react_jsx_runtime.jsx)(ActivityLine, { ...props })
344
+ });
345
+ }
332
346
  const inject = [
333
347
  "slots",
334
348
  "locale",
@@ -342,6 +356,16 @@ window.__ModuleLoader__.load({
342
356
  const registry = ctx.slots;
343
357
  return typeof registry.spec === "function" && registry.spec.call(ctx.slots, slot) !== void 0;
344
358
  }
359
+ /** Register an optional host slot without claiming it in older SlotMap declarations. */
360
+ function injectOptionalActivitySlot(ctx, slot) {
361
+ const registry = ctx.slots;
362
+ registry.inject(slot, () => registry.register({
363
+ name: slot,
364
+ id: "codex-activity",
365
+ order: 5,
366
+ locale: NS
367
+ }, ActivityLine));
368
+ }
345
369
  /** Mount Codex controls in the newest named seats, with legacy composer fallbacks. */
346
370
  function apply(ctx) {
347
371
  ctx.effect(() => ctx.locale.register(NS, {
@@ -382,12 +406,13 @@ window.__ModuleLoader__.load({
382
406
  locale: NS,
383
407
  inject: injected
384
408
  }, LegacyContextSizeControl));
385
- ctx.slots.inject("conversation.composer.dock", () => ctx.slots.register({
386
- name: "conversation.composer.dock",
409
+ if (chooseDeclaredSlot(ACTIVITY_SLOT, ACTIVITY_FALLBACK_SLOT, (slot) => slotIsDeclared(ctx, slot)) === ACTIVITY_SLOT) injectOptionalActivitySlot(ctx, ACTIVITY_SLOT);
410
+ else ctx.slots.inject(ACTIVITY_FALLBACK_SLOT, () => ctx.slots.register({
411
+ name: ACTIVITY_FALLBACK_SLOT,
387
412
  id: "codex-activity",
388
413
  order: 5,
389
414
  locale: NS
390
- }, ActivityLine));
415
+ }, ActivityDock));
391
416
  }
392
417
  var client_default = {
393
418
  inject,
package/lib/index.js CHANGED
@@ -8,7 +8,12 @@ import { AsyncLocalStorage } from "node:async_hooks";
8
8
  import { z as z$1 } from "zod";
9
9
  //#region lib/types/context.js
10
10
  const CODEX_CONTEXT_MAX = 1e6;
11
- String.raw`start: begin_patch environment_id? hunk+ end_patch
11
+ //#endregion
12
+ //#region lib/types/patch.js
13
+ /** Parser and line-oriented applicator for Codex's `apply_patch` language. */
14
+ const APPLY_PATCH_DESCRIPTION = "Edits files using Codex patch syntax with Begin/End Patch markers and file update directives. In hunk lines, the first character is the operation marker; repeat a source-leading marker when the source line itself starts with one.";
15
+ /** The grammar sent to providers that support OpenAI custom grammar tools. */
16
+ const APPLY_PATCH_GRAMMAR = String.raw`start: begin_patch environment_id? hunk+ end_patch
12
17
  begin_patch: "*** Begin Patch" LF
13
18
  environment_id: "*** Environment ID: " filename LF
14
19
  end_patch: "*** End Patch" LF?
@@ -575,6 +580,134 @@ function isWebSearchTool(tool) {
575
580
  function hasWebSearchTool(body) {
576
581
  return Array.isArray(body.tools) && body.tools.some(isWebSearchTool);
577
582
  }
583
+ function toolName(tool) {
584
+ if (typeof tool !== "object" || tool === null) return void 0;
585
+ const value = tool;
586
+ if (typeof value.name === "string") return value.name;
587
+ const fn = value.function;
588
+ return typeof fn === "object" && fn !== null && typeof fn.name === "string" ? fn.name : void 0;
589
+ }
590
+ function isApplyPatchTool(tool) {
591
+ return toolName(tool) === "apply_patch";
592
+ }
593
+ function isFunctionApplyPatchTool(tool) {
594
+ if (!isApplyPatchTool(tool) || typeof tool !== "object" || tool === null) return false;
595
+ return tool.type !== "custom";
596
+ }
597
+ function hasFunctionApplyPatchTool(body) {
598
+ return Array.isArray(body.tools) && body.tools.some(isFunctionApplyPatchTool);
599
+ }
600
+ function applyPatchTool(tool) {
601
+ const value = tool;
602
+ const fn = value.function;
603
+ const custom = {
604
+ type: "custom",
605
+ name: "apply_patch",
606
+ description: typeof value.description === "string" ? value.description : typeof fn === "object" && fn !== null && typeof fn.description === "string" ? fn.description : APPLY_PATCH_DESCRIPTION,
607
+ format: {
608
+ type: "grammar",
609
+ syntax: "lark",
610
+ definition: APPLY_PATCH_GRAMMAR
611
+ }
612
+ };
613
+ if (value.defer_loading !== void 0) custom.defer_loading = value.defer_loading;
614
+ return custom;
615
+ }
616
+ /** Replace DSH's JSON function declaration with the Responses custom grammar tool. */
617
+ function addCodexApplyPatch(body) {
618
+ if (!Array.isArray(body.tools)) return body;
619
+ let changed = false;
620
+ const tools = body.tools.map((tool) => {
621
+ if (!isApplyPatchTool(tool) || typeof tool !== "object" || tool === null) return tool;
622
+ if (tool.type === "custom") return tool;
623
+ changed = true;
624
+ return applyPatchTool(tool);
625
+ });
626
+ return changed ? {
627
+ ...body,
628
+ tools
629
+ } : body;
630
+ }
631
+ function applyPatchInputOfCall(item) {
632
+ if (item.type !== "function_call" || item.name !== "apply_patch") return void 0;
633
+ if (typeof item.call_id !== "string" || item.call_id.length === 0) return void 0;
634
+ const raw = item.arguments;
635
+ const argumentsObject = typeof raw === "string" ? (() => {
636
+ try {
637
+ return JSON.parse(raw);
638
+ } catch {
639
+ return;
640
+ }
641
+ })() : raw;
642
+ if (typeof argumentsObject !== "object" || argumentsObject === null) return void 0;
643
+ const input = argumentsObject.input;
644
+ return typeof input === "string" ? {
645
+ callId: item.call_id,
646
+ input
647
+ } : void 0;
648
+ }
649
+ function canRewriteApplyPatchHistory(body) {
650
+ if (!Array.isArray(body.input)) return true;
651
+ return body.input.every((item) => {
652
+ if (typeof item !== "object" || item === null) return true;
653
+ const value = item;
654
+ return value.type !== "function_call" || value.name !== "apply_patch" || applyPatchInputOfCall(value) !== void 0;
655
+ });
656
+ }
657
+ /** Replay apply_patch calls as custom tool items after pi-ai's generic conversion. */
658
+ function rewriteCodexApplyPatchHistory(body) {
659
+ if (!Array.isArray(body.input) || !canRewriteApplyPatchHistory(body)) return body;
660
+ const applyCallIds = /* @__PURE__ */ new Set();
661
+ for (const item of body.input) {
662
+ if (typeof item !== "object" || item === null) continue;
663
+ const value = item;
664
+ if (value.type === "custom_tool_call" && value.name === "apply_patch" && typeof value.call_id === "string") applyCallIds.add(value.call_id);
665
+ const call = applyPatchInputOfCall(value);
666
+ if (call !== void 0) applyCallIds.add(call.callId);
667
+ }
668
+ if (applyCallIds.size === 0) return body;
669
+ let changed = false;
670
+ const input = body.input.map((item) => {
671
+ if (typeof item !== "object" || item === null) return item;
672
+ const value = item;
673
+ const call = applyPatchInputOfCall(value);
674
+ if (call !== void 0) {
675
+ const next = {
676
+ type: "custom_tool_call",
677
+ call_id: call.callId,
678
+ name: "apply_patch",
679
+ input: call.input
680
+ };
681
+ if (typeof value.id === "string") next.id = value.id;
682
+ changed = true;
683
+ return next;
684
+ }
685
+ if (value.type === "function_call_output" && typeof value.call_id === "string" && applyCallIds.has(value.call_id)) {
686
+ changed = true;
687
+ return {
688
+ type: "custom_tool_call_output",
689
+ call_id: value.call_id,
690
+ output: value.output
691
+ };
692
+ }
693
+ return item;
694
+ });
695
+ return changed ? {
696
+ ...body,
697
+ input
698
+ } : body;
699
+ }
700
+ /** Compose the plugin-only Responses rewrites without changing DSH's tool API. */
701
+ function rewriteCodexResponsesBody(body) {
702
+ let next = body;
703
+ if (hasWebSearchTool(next)) next = addHostedWebSearch(next);
704
+ else if (hasRemoteCompaction(next)) next = replaceRemoteCompactions(next);
705
+ if (hasFunctionApplyPatchTool(next) && canRewriteApplyPatchHistory(next)) {
706
+ next = addCodexApplyPatch(next);
707
+ next = rewriteCodexApplyPatchHistory(next);
708
+ }
709
+ return next;
710
+ }
578
711
  /** Convert a generic DSH Responses tool list to the hosted Codex variant. */
579
712
  function addHostedWebSearch(body) {
580
713
  const tools = Array.isArray(body.tools) ? body.tools.filter((tool) => !isWebSearchTool(tool)) : [];
@@ -618,12 +751,13 @@ function hasRemoteCompaction(body) {
618
751
  });
619
752
  }
620
753
  function canPatchBody(body) {
621
- return isGptModel$1(body.model) && (hasWebSearchTool(body) || hasRemoteCompaction(body));
754
+ return isGptModel$1(body.model) && (hasWebSearchTool(body) || hasRemoteCompaction(body) || hasFunctionApplyPatchTool(body) && canRewriteApplyPatchHistory(body));
622
755
  }
623
756
  /**
624
757
  * Install a scoped fetch shim for pi-ai's already-built Responses request.
625
758
  * The generic DSH adapter remains the owner of auth, streaming, replay, and
626
- * attachments; this shim changes only the hosted-tool portion of the wire body.
759
+ * attachments; this shim changes only Codex's Responses tool and compaction
760
+ * representation at the wire boundary.
627
761
  */
628
762
  function installGlobalHostedWebSearchPatch() {
629
763
  const original = globalThis.fetch;
@@ -642,7 +776,7 @@ function installGlobalHostedWebSearchPatch() {
642
776
  const headers = new Headers(request.headers);
643
777
  headers.delete("content-length");
644
778
  const hostedRequest = new Request(request, {
645
- body: JSON.stringify(hasWebSearchTool(body) ? addHostedWebSearch(body) : replaceRemoteCompactions(body)),
779
+ body: JSON.stringify(rewriteCodexResponsesBody(body)),
646
780
  headers
647
781
  });
648
782
  try {
@@ -1063,7 +1197,6 @@ function buildCodexSystemPrompt(config = {}) {
1063
1197
  }
1064
1198
  const EXEC_COMMAND_DESCRIPTION = "Runs a command in a PTY, returning output, a session ID for ongoing interaction, or a background job ID when requested.";
1065
1199
  const WRITE_STDIN_DESCRIPTION = "Writes characters to an existing unified exec session and returns recent output.";
1066
- const APPLY_PATCH_DESCRIPTION = "Edits files using Codex patch syntax with Begin/End Patch markers and file update directives. In hunk lines, the first character is the operation marker; repeat a source-leading marker when the source line itself starts with one.";
1067
1200
  const UPDATE_PLAN_DESCRIPTION = "Updates the task plan.\nProvide an optional explanation and a list of plan items, each with a step and status.\nAt most one step can be in_progress at a time.";
1068
1201
  const PLAN_STATUSES = [
1069
1202
  "pending",
@@ -1445,13 +1578,13 @@ function apply(ctx, config = {}) {
1445
1578
  ctx.on("agent/request", async (_payload, next) => {
1446
1579
  return applyCodexRequestSettings(await next(), codexSettings.current());
1447
1580
  });
1448
- if ((resolved.hostedWebSearch || resolved.remoteCompact) && typeof ctx.effect === "function") {
1581
+ if (typeof ctx.effect === "function") {
1449
1582
  const disposeHostedWebSearch = installHostedWebSearch();
1450
1583
  ctx.effect(() => disposeHostedWebSearch, "codex: Responses transport wrapper");
1451
1584
  }
1452
- if (resolved.hostedWebSearch || resolved.remoteCompact) ctx.on("llm/stream", ((options, next) => {
1585
+ ctx.on("llm/stream", ((options, next) => {
1453
1586
  if (resolved.remoteCompact && options.purpose === "compaction" && isGptModel(options.model)) return remoteCompactStream(ctx, options, next);
1454
- if ((resolved.hostedWebSearch || resolved.remoteCompact) && options.purpose === void 0 && isGptModel(options.model)) return hostedWebSearchStream(next);
1587
+ if (options.purpose === void 0 && isGptModel(options.model)) return hostedWebSearchStream(next);
1455
1588
  return next();
1456
1589
  }));
1457
1590
  ctx.on("system-prompt/assemble", async (_assembly, _context, next) => normalizeCodexPromptAssembly(await next()));
@@ -32,7 +32,8 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
32
32
  };
33
33
  }
34
34
  }
35
- type ActivityProps = PropsRuntime<'conversation.composer.dock'> & PropsLocale<'codex'>;
35
+ type ActivityDockProps = PropsRuntime<'conversation.composer.dock'> & PropsLocale<'codex'>;
36
+ type ActivityProps = ActivityDockProps;
36
37
  export declare function ActivityLine({ sessionId, useSession, useSessions, useProjection, t }: ActivityProps): import("react").JSX.Element | null;
37
38
  export declare const inject: string[];
38
39
  /** Select a preferred slot when the host declares it, otherwise use a stable legacy composer seat. */
@@ -7,6 +7,10 @@ const NS = 'codex';
7
7
  const SETTINGS_NAMESPACE = 'codex';
8
8
  const MODEL_SETTINGS_SLOT = 'conversation.input.model.settings';
9
9
  const CONTEXT_SETTINGS_SLOT = 'conversation.input.context.settings';
10
+ // Prefer a dedicated status seat when a newer host declares it; the current
11
+ // conversation contract falls back to the ambient composer dock below.
12
+ const ACTIVITY_SLOT = 'conversation.chat.status';
13
+ const ACTIVITY_FALLBACK_SLOT = 'conversation.composer.dock';
10
14
  const FAST_FALLBACK_SLOT = 'conversation.input.right';
11
15
  const CONTEXT_FALLBACK_SLOT = 'conversation.input.dock';
12
16
  const DEFAULT_CONTEXT_WINDOW = 262_144;
@@ -161,15 +165,15 @@ export function ActivityLine({ sessionId, useSession, useSessions, useProjection
161
165
  const label = activity.activity === 'awaiting-model'
162
166
  ? t('activityAwaitingModel')
163
167
  : t('activityCompacting');
164
- return (_jsxs("div", { id: "codex-activity", role: "status", "aria-live": "polite", style: {
165
- display: 'flex',
168
+ return (_jsxs("span", { id: "codex-activity", role: "status", "aria-live": "polite", style: {
169
+ display: 'inline-flex',
166
170
  alignItems: 'center',
167
171
  gap: 7,
168
- minHeight: 28,
169
- padding: '4px 10px',
172
+ minHeight: 26,
170
173
  color: 'var(--dsw-alias-label-secondary)',
171
174
  fontSize: 12,
172
175
  lineHeight: '20px',
176
+ whiteSpace: 'nowrap',
173
177
  }, children: [_jsx("span", { "aria-hidden": "true", style: {
174
178
  width: 7,
175
179
  height: 7,
@@ -178,6 +182,10 @@ export function ActivityLine({ sessionId, useSession, useSessions, useProjection
178
182
  background: 'var(--dsw-static-blue-500)',
179
183
  } }), _jsx("span", { children: label }), _jsxs("span", { style: { color: 'var(--dsw-alias-label-tertiary)' }, children: ["\u00B7 ", elapsedSeconds(activity.startedAt, now), "s"] })] }));
180
184
  }
185
+ /** Preserve the old composer-dock footprint for hosts without the chat status seat. */
186
+ function ActivityDock(props) {
187
+ return (_jsx("div", { style: { display: 'flex', alignItems: 'center', minHeight: 28, padding: '4px 10px' }, children: _jsx(ActivityLine, { ...props }) }));
188
+ }
181
189
  export const inject = ['slots', 'locale', 'settingsScope'];
182
190
  /** Select a preferred slot when the host declares it, otherwise use a stable legacy composer seat. */
183
191
  export function chooseDeclaredSlot(preferred, fallback, isDeclared) {
@@ -187,6 +195,16 @@ function slotIsDeclared(ctx, slot) {
187
195
  const registry = ctx.slots;
188
196
  return typeof registry.spec === 'function' && registry.spec.call(ctx.slots, slot) !== undefined;
189
197
  }
198
+ /** Register an optional host slot without claiming it in older SlotMap declarations. */
199
+ function injectOptionalActivitySlot(ctx, slot) {
200
+ const registry = ctx.slots;
201
+ registry.inject(slot, () => registry.register({
202
+ name: slot,
203
+ id: 'codex-activity',
204
+ order: 5,
205
+ locale: NS,
206
+ }, ActivityLine));
207
+ }
190
208
  /** Mount Codex controls in the newest named seats, with legacy composer fallbacks. */
191
209
  export function apply(ctx) {
192
210
  ctx.effect(() => ctx.locale.register(NS, { en, zh }), 'codex client: dictionaries');
@@ -234,12 +252,18 @@ export function apply(ctx) {
234
252
  inject: injected,
235
253
  }, LegacyContextSizeControl));
236
254
  }
237
- ctx.slots.inject('conversation.composer.dock', () => ctx.slots.register({
238
- name: 'conversation.composer.dock',
239
- id: 'codex-activity',
240
- order: 5,
241
- locale: NS,
242
- }, ActivityLine));
255
+ const activitySlot = chooseDeclaredSlot(ACTIVITY_SLOT, ACTIVITY_FALLBACK_SLOT, slot => slotIsDeclared(ctx, slot));
256
+ if (activitySlot === ACTIVITY_SLOT) {
257
+ injectOptionalActivitySlot(ctx, ACTIVITY_SLOT);
258
+ }
259
+ else {
260
+ ctx.slots.inject(ACTIVITY_FALLBACK_SLOT, () => ctx.slots.register({
261
+ name: ACTIVITY_FALLBACK_SLOT,
262
+ id: 'codex-activity',
263
+ order: 5,
264
+ locale: NS,
265
+ }, ActivityDock));
266
+ }
243
267
  }
244
268
  export default { inject, apply };
245
269
  //# sourceMappingURL=index.js.map
@@ -3,7 +3,7 @@ import z from '@deepseek-ai/schemastery';
3
3
  import { installSettingsSection, settingsNamespace } from '@deepseek-ai/dsh-settings';
4
4
  import { defineTool } from '@deepseek-ai/dsh-tools';
5
5
  import { CODEX_CONTEXT_MAX } from "./context.js";
6
- import { applyPatchHunks, parsePatch } from "./patch.js";
6
+ import { APPLY_PATCH_DESCRIPTION, applyPatchHunks, parsePatch } from "./patch.js";
7
7
  import { renderExecResult, runExecCommand, runWriteStdin } from "./exec.js";
8
8
  import { hostedWebSearchStream, installHostedWebSearch, remoteCompactStream } from "./remote.js";
9
9
  import { registerCodexActivityProjection } from "./activity.js";
@@ -196,7 +196,6 @@ export function buildCodexSystemPrompt(config = {}) {
196
196
  }
197
197
  const EXEC_COMMAND_DESCRIPTION = 'Runs a command in a PTY, returning output, a session ID for ongoing interaction, or a background job ID when requested.';
198
198
  const WRITE_STDIN_DESCRIPTION = 'Writes characters to an existing unified exec session and returns recent output.';
199
- const APPLY_PATCH_DESCRIPTION = 'Edits files using Codex patch syntax with Begin/End Patch markers and file update directives. In hunk lines, the first character is the operation marker; repeat a source-leading marker when the source line itself starts with one.';
200
199
  const UPDATE_PLAN_DESCRIPTION = 'Updates the task plan.\nProvide an optional explanation and a list of plan items, each with a step and status.\nAt most one step can be in_progress at a time.';
201
200
  const PLAN_STATUSES = ['pending', 'in_progress', 'completed'];
202
201
  function sessionCwd(exec) {
@@ -473,23 +472,22 @@ export function apply(ctx, config = {}) {
473
472
  const request = await next();
474
473
  return applyCodexRequestSettings(request, codexSettings.current());
475
474
  });
476
- if ((resolved.hostedWebSearch || resolved.remoteCompact) && typeof ctx.effect === 'function') {
475
+ if (typeof ctx.effect === 'function') {
477
476
  const disposeHostedWebSearch = installHostedWebSearch();
478
477
  ctx.effect(() => disposeHostedWebSearch, 'codex: Responses transport wrapper');
479
478
  }
480
- if (resolved.hostedWebSearch || resolved.remoteCompact) {
481
- ctx.on('llm/stream', ((options, next) => {
482
- if (resolved.remoteCompact && options.purpose === 'compaction' && isGptModel(options.model)) {
483
- return remoteCompactStream(ctx, options, next);
484
- }
485
- if ((resolved.hostedWebSearch || resolved.remoteCompact)
486
- && options.purpose === undefined
487
- && isGptModel(options.model)) {
488
- return hostedWebSearchStream(next);
489
- }
490
- return next();
491
- }));
492
- }
479
+ ctx.on('llm/stream', ((options, next) => {
480
+ if (resolved.remoteCompact && options.purpose === 'compaction' && isGptModel(options.model)) {
481
+ return remoteCompactStream(ctx, options, next);
482
+ }
483
+ // Keep all ordinary GPT Responses calls inside the plugin-owned transport
484
+ // scope so apply_patch can use the same wire bridge even when hosted search
485
+ // and remote compaction are disabled.
486
+ if (options.purpose === undefined && isGptModel(options.model)) {
487
+ return hostedWebSearchStream(next);
488
+ }
489
+ return next();
490
+ }));
493
491
  ctx.on('system-prompt/assemble', async (_assembly, _context, next) => normalizeCodexPromptAssembly(await next()));
494
492
  ctx.systemPrompt.section({ name: 'codex:base', order: 10, text: buildCodexSystemPrompt(resolved) });
495
493
  registerExecTools(ctx, resolved);
@@ -1,4 +1,5 @@
1
1
  /** Parser and line-oriented applicator for Codex's `apply_patch` language. */
2
+ export declare const APPLY_PATCH_DESCRIPTION = "Edits files using Codex patch syntax with Begin/End Patch markers and file update directives. In hunk lines, the first character is the operation marker; repeat a source-leading marker when the source line itself starts with one.";
2
3
  /** The grammar sent to providers that support OpenAI custom grammar tools. */
3
4
  export declare const APPLY_PATCH_GRAMMAR: string;
4
5
  export type PatchLine = {
@@ -1,4 +1,5 @@
1
1
  /** Parser and line-oriented applicator for Codex's `apply_patch` language. */
2
+ export const APPLY_PATCH_DESCRIPTION = 'Edits files using Codex patch syntax with Begin/End Patch markers and file update directives. In hunk lines, the first character is the operation marker; repeat a source-leading marker when the source line itself starts with one.';
2
3
  /** The grammar sent to providers that support OpenAI custom grammar tools. */
3
4
  export const APPLY_PATCH_GRAMMAR = String.raw `start: begin_patch environment_id? hunk+ end_patch
4
5
  begin_patch: "*** Begin Patch" LF
@@ -7,6 +7,12 @@ export interface RemoteCodexConfig {
7
7
  interface JsonObject {
8
8
  [key: string]: unknown;
9
9
  }
10
+ /** Replace DSH's JSON function declaration with the Responses custom grammar tool. */
11
+ export declare function addCodexApplyPatch(body: JsonObject): JsonObject;
12
+ /** Replay apply_patch calls as custom tool items after pi-ai's generic conversion. */
13
+ export declare function rewriteCodexApplyPatchHistory(body: JsonObject): JsonObject;
14
+ /** Compose the plugin-only Responses rewrites without changing DSH's tool API. */
15
+ export declare function rewriteCodexResponsesBody(body: JsonObject): JsonObject;
10
16
  /** Convert a generic DSH Responses tool list to the hosted Codex variant. */
11
17
  export declare function addHostedWebSearch(body: JsonObject): JsonObject;
12
18
  /** Replace the text placeholder written by dsh-compaction-basic with the native item. */
@@ -1,5 +1,6 @@
1
1
  import { credentialRef } from '@deepseek-ai/dsh-credentials';
2
2
  import { AsyncLocalStorage } from 'node:async_hooks';
3
+ import { APPLY_PATCH_DESCRIPTION, APPLY_PATCH_GRAMMAR } from "./patch.js";
3
4
  const SETTINGS_NAMESPACE = 'llm-pi-ai';
4
5
  const REMOTE_COMPACTION_OPEN = '<codex-remote-compaction>';
5
6
  const REMOTE_COMPACTION_CLOSE = '</codex-remote-compaction>';
@@ -59,6 +60,162 @@ function isWebSearchTool(tool) {
59
60
  function hasWebSearchTool(body) {
60
61
  return Array.isArray(body.tools) && body.tools.some(isWebSearchTool);
61
62
  }
63
+ function toolName(tool) {
64
+ if (typeof tool !== 'object' || tool === null)
65
+ return undefined;
66
+ const value = tool;
67
+ if (typeof value.name === 'string')
68
+ return value.name;
69
+ const fn = value.function;
70
+ return typeof fn === 'object' && fn !== null && typeof fn.name === 'string'
71
+ ? fn.name
72
+ : undefined;
73
+ }
74
+ function isApplyPatchTool(tool) {
75
+ return toolName(tool) === 'apply_patch';
76
+ }
77
+ function isFunctionApplyPatchTool(tool) {
78
+ if (!isApplyPatchTool(tool) || typeof tool !== 'object' || tool === null)
79
+ return false;
80
+ return tool.type !== 'custom';
81
+ }
82
+ function hasFunctionApplyPatchTool(body) {
83
+ return Array.isArray(body.tools) && body.tools.some(isFunctionApplyPatchTool);
84
+ }
85
+ function applyPatchTool(tool) {
86
+ const value = tool;
87
+ const fn = value.function;
88
+ const description = typeof value.description === 'string'
89
+ ? value.description
90
+ : typeof fn === 'object' && fn !== null && typeof fn.description === 'string'
91
+ ? fn.description
92
+ : APPLY_PATCH_DESCRIPTION;
93
+ const custom = {
94
+ type: 'custom',
95
+ name: 'apply_patch',
96
+ description,
97
+ format: {
98
+ type: 'grammar',
99
+ syntax: 'lark',
100
+ definition: APPLY_PATCH_GRAMMAR,
101
+ },
102
+ };
103
+ if (value.defer_loading !== undefined)
104
+ custom.defer_loading = value.defer_loading;
105
+ return custom;
106
+ }
107
+ /** Replace DSH's JSON function declaration with the Responses custom grammar tool. */
108
+ export function addCodexApplyPatch(body) {
109
+ if (!Array.isArray(body.tools))
110
+ return body;
111
+ let changed = false;
112
+ const tools = body.tools.map(tool => {
113
+ if (!isApplyPatchTool(tool) || typeof tool !== 'object' || tool === null)
114
+ return tool;
115
+ if (tool.type === 'custom')
116
+ return tool;
117
+ changed = true;
118
+ return applyPatchTool(tool);
119
+ });
120
+ return changed ? { ...body, tools } : body;
121
+ }
122
+ function applyPatchInputOfCall(item) {
123
+ if (item.type !== 'function_call' || item.name !== 'apply_patch')
124
+ return undefined;
125
+ if (typeof item.call_id !== 'string' || item.call_id.length === 0)
126
+ return undefined;
127
+ const raw = item.arguments;
128
+ const argumentsObject = typeof raw === 'string'
129
+ ? (() => {
130
+ try {
131
+ return JSON.parse(raw);
132
+ }
133
+ catch {
134
+ return undefined;
135
+ }
136
+ })()
137
+ : raw;
138
+ if (typeof argumentsObject !== 'object' || argumentsObject === null)
139
+ return undefined;
140
+ const input = argumentsObject.input;
141
+ return typeof input === 'string' ? { callId: item.call_id, input } : undefined;
142
+ }
143
+ function canRewriteApplyPatchHistory(body) {
144
+ if (!Array.isArray(body.input))
145
+ return true;
146
+ return body.input.every(item => {
147
+ if (typeof item !== 'object' || item === null)
148
+ return true;
149
+ const value = item;
150
+ return value.type !== 'function_call' || value.name !== 'apply_patch'
151
+ || applyPatchInputOfCall(value) !== undefined;
152
+ });
153
+ }
154
+ /** Replay apply_patch calls as custom tool items after pi-ai's generic conversion. */
155
+ export function rewriteCodexApplyPatchHistory(body) {
156
+ if (!Array.isArray(body.input) || !canRewriteApplyPatchHistory(body))
157
+ return body;
158
+ const applyCallIds = new Set();
159
+ for (const item of body.input) {
160
+ if (typeof item !== 'object' || item === null)
161
+ continue;
162
+ const value = item;
163
+ if (value.type === 'custom_tool_call' && value.name === 'apply_patch' && typeof value.call_id === 'string') {
164
+ applyCallIds.add(value.call_id);
165
+ }
166
+ const call = applyPatchInputOfCall(value);
167
+ if (call !== undefined)
168
+ applyCallIds.add(call.callId);
169
+ }
170
+ if (applyCallIds.size === 0)
171
+ return body;
172
+ let changed = false;
173
+ const input = body.input.map(item => {
174
+ if (typeof item !== 'object' || item === null)
175
+ return item;
176
+ const value = item;
177
+ const call = applyPatchInputOfCall(value);
178
+ if (call !== undefined) {
179
+ const next = {
180
+ type: 'custom_tool_call',
181
+ call_id: call.callId,
182
+ name: 'apply_patch',
183
+ input: call.input,
184
+ };
185
+ if (typeof value.id === 'string')
186
+ next.id = value.id;
187
+ changed = true;
188
+ return next;
189
+ }
190
+ if (value.type === 'function_call_output'
191
+ && typeof value.call_id === 'string'
192
+ && applyCallIds.has(value.call_id)) {
193
+ changed = true;
194
+ return {
195
+ type: 'custom_tool_call_output',
196
+ call_id: value.call_id,
197
+ output: value.output,
198
+ };
199
+ }
200
+ return item;
201
+ });
202
+ return changed ? { ...body, input } : body;
203
+ }
204
+ /** Compose the plugin-only Responses rewrites without changing DSH's tool API. */
205
+ export function rewriteCodexResponsesBody(body) {
206
+ let next = body;
207
+ if (hasWebSearchTool(next)) {
208
+ next = addHostedWebSearch(next);
209
+ }
210
+ else if (hasRemoteCompaction(next)) {
211
+ next = replaceRemoteCompactions(next);
212
+ }
213
+ if (hasFunctionApplyPatchTool(next) && canRewriteApplyPatchHistory(next)) {
214
+ next = addCodexApplyPatch(next);
215
+ next = rewriteCodexApplyPatchHistory(next);
216
+ }
217
+ return next;
218
+ }
62
219
  /** Convert a generic DSH Responses tool list to the hosted Codex variant. */
63
220
  export function addHostedWebSearch(body) {
64
221
  const tools = Array.isArray(body.tools) ? body.tools.filter(tool => !isWebSearchTool(tool)) : [];
@@ -107,12 +264,15 @@ function hasRemoteCompaction(body) {
107
264
  }
108
265
  function canPatchBody(body) {
109
266
  return isGptModel(body.model)
110
- && (hasWebSearchTool(body) || hasRemoteCompaction(body));
267
+ && (hasWebSearchTool(body)
268
+ || hasRemoteCompaction(body)
269
+ || (hasFunctionApplyPatchTool(body) && canRewriteApplyPatchHistory(body)));
111
270
  }
112
271
  /**
113
272
  * Install a scoped fetch shim for pi-ai's already-built Responses request.
114
273
  * The generic DSH adapter remains the owner of auth, streaming, replay, and
115
- * attachments; this shim changes only the hosted-tool portion of the wire body.
274
+ * attachments; this shim changes only Codex's Responses tool and compaction
275
+ * representation at the wire boundary.
116
276
  */
117
277
  function installGlobalHostedWebSearchPatch() {
118
278
  const original = globalThis.fetch;
@@ -135,7 +295,7 @@ function installGlobalHostedWebSearchPatch() {
135
295
  const headers = new Headers(request.headers);
136
296
  headers.delete('content-length');
137
297
  const hostedRequest = new Request(request, {
138
- body: JSON.stringify(hasWebSearchTool(body) ? addHostedWebSearch(body) : replaceRemoteCompactions(body)),
298
+ body: JSON.stringify(rewriteCodexResponsesBody(body)),
139
299
  headers,
140
300
  });
141
301
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shuind/dsh-codex-harness",
3
- "version": "0.1.22",
3
+ "version": "0.1.23",
4
4
  "description": "A Codex harness with a streamlined system prompt for GPT models that do not fit DSH's native interface, while remaining compatible with the DSH plugin ecosystem.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",