dsh-lcx-codex 0.6.0 → 0.7.0-pre.1

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
@@ -1,6 +1,6 @@
1
1
  <div align="center">
2
2
 
3
- <img src="https://raw.githubusercontent.com/kk3ya03-star/dsh-lcx-codex/stable/0.6.x/assets/dsh-lcx-codex-banner.svg" alt="LCX Codex" width="100%" />
3
+ <img src="https://raw.githubusercontent.com/kk3ya03-star/dsh-lcx-codex/main/assets/dsh-lcx-codex-banner.svg" alt="LCX Codex" width="100%" />
4
4
 
5
5
  # LCX Codex
6
6
 
@@ -8,9 +8,9 @@
8
8
 
9
9
  [![npm latest](https://img.shields.io/npm/v/dsh-lcx-codex/latest?label=latest)](https://www.npmjs.com/package/dsh-lcx-codex)
10
10
  [![npm prelatest](https://img.shields.io/npm/v/dsh-lcx-codex/prelatest?label=prelatest&color=orange)](https://www.npmjs.com/package/dsh-lcx-codex?activeTab=versions)
11
- [![License](https://img.shields.io/badge/license-MIT-555)](https://github.com/kk3ya03-star/dsh-lcx-codex/blob/stable/0.6.x/LICENSE)
11
+ [![License](https://img.shields.io/badge/license-MIT-555)](https://github.com/kk3ya03-star/dsh-lcx-codex/blob/main/LICENSE)
12
12
 
13
- **简体中文** · [English](https://github.com/kk3ya03-star/dsh-lcx-codex/blob/stable/0.6.x/README_EN.md) · [更新日志](https://github.com/kk3ya03-star/dsh-lcx-codex/blob/stable/0.6.x/CHANGELOG.md) · [问题反馈](https://github.com/kk3ya03-star/dsh-lcx-codex/issues)
13
+ **简体中文** · [English](https://github.com/kk3ya03-star/dsh-lcx-codex/blob/main/README_EN.md) · [更新日志](https://github.com/kk3ya03-star/dsh-lcx-codex/blob/main/CHANGELOG.md) · [问题反馈](https://github.com/kk3ya03-star/dsh-lcx-codex/issues)
14
14
 
15
15
  </div>
16
16
 
@@ -49,7 +49,7 @@ LCX Codex 是 [DeepSeek Harness](https://github.com/deepseek-ai/DeepSeek-Harness
49
49
 
50
50
  `0.7.0-pre.1` 是预发布版,面向 DSH `0.2.2` 预发布系列(从 `0.2.2-alpha.3` 起)。它的安装范围**只有下限**(`>=0.2.2-alpha.3`),没有上限:更新的 DSH 版本也能装上,但**没有经过验证**。本次预发布的验证基线只有 DSH `0.2.2-alpha.3`(host Pi `1.5.0`,plugin Pi `1.5.0`),请不要据此认为其他 DSH 版本受支持。
51
51
 
52
- `0.6.0` 和 `0.7.0-pre.1` 的主要变化(详见[更新日志](https://github.com/kk3ya03-star/dsh-lcx-codex/blob/stable/0.6.x/CHANGELOG.md)):
52
+ `0.6.0` 和 `0.7.0-pre.1` 的主要变化(详见[更新日志](https://github.com/kk3ya03-star/dsh-lcx-codex/blob/main/CHANGELOG.md)):
53
53
 
54
54
  - **内置 Pi 跟随 DSH 升级到 `1.5.0`**:GPT-5.6 / GPT-6 系列模型的工具声明与 DSH 自己的发送方式一致(全部以 `additional_tools` 形式声明,不再发送顶层 `tools`),会话中途新增或删除工具、重启、分叉和压缩之后也保持一致。
55
55
  - **切换推理强度不再让缓存失效**:在 `openai` 的 GPT-6 系列模型上,会话中途切换推理强度会保留已缓存的前缀,与 DSH 自己的处理一致。
@@ -107,7 +107,7 @@ dsh web
107
107
 
108
108
  打开 DSH Web 的插件页面,在 LCX 的配置卡片 **Responses / Codex 能力** 中按需打开下列开关,然后点击 **保存**。
109
109
 
110
- <img src="https://raw.githubusercontent.com/kk3ya03-star/dsh-lcx-codex/stable/0.6.x/assets/settings-card.png" alt="LCX 插件配置卡片" width="720" />
110
+ <img src="https://raw.githubusercontent.com/kk3ya03-star/dsh-lcx-codex/main/assets/settings-card.png" alt="LCX 插件配置卡片" width="720" />
111
111
 
112
112
  **GPT**
113
113
 
@@ -202,11 +202,11 @@ dsh web
202
202
 
203
203
  ## 更多
204
204
 
205
- - [更新日志](https://github.com/kk3ya03-star/dsh-lcx-codex/blob/stable/0.6.x/CHANGELOG.md)
206
- - [架构说明](https://github.com/kk3ya03-star/dsh-lcx-codex/blob/stable/0.6.x/ARCHITECTURE.md)
207
- - [第三方许可](https://github.com/kk3ya03-star/dsh-lcx-codex/blob/stable/0.6.x/THIRD_PARTY_NOTICES.md)
208
- - [参与贡献](https://github.com/kk3ya03-star/dsh-lcx-codex/blob/stable/0.6.x/CONTRIBUTING.md)
205
+ - [更新日志](https://github.com/kk3ya03-star/dsh-lcx-codex/blob/main/CHANGELOG.md)
206
+ - [架构说明](https://github.com/kk3ya03-star/dsh-lcx-codex/blob/main/ARCHITECTURE.md)
207
+ - [第三方许可](https://github.com/kk3ya03-star/dsh-lcx-codex/blob/main/THIRD_PARTY_NOTICES.md)
208
+ - [参与贡献](https://github.com/kk3ya03-star/dsh-lcx-codex/blob/main/CONTRIBUTING.md)
209
209
 
210
210
  ## 许可证
211
211
 
212
- [MIT](https://github.com/kk3ya03-star/dsh-lcx-codex/blob/stable/0.6.x/LICENSE)。独立社区插件,与 OpenAI、xAI、DeepSeek、Sub2API、NewAPI 无隶属关系,也未获得其官方背书。
212
+ [MIT](https://github.com/kk3ya03-star/dsh-lcx-codex/blob/main/LICENSE)。独立社区插件,与 OpenAI、xAI、DeepSeek、Sub2API、NewAPI 无隶属关系,也未获得其官方背书。
package/lib/dsh-compat.js CHANGED
@@ -54,12 +54,12 @@ export function readSelectedAgentRouteState(agent) {
54
54
  const session = sessionFromAgent(agent);
55
55
  if (!session)
56
56
  return route;
57
- // Cold/resumed Agents recover pending selection from DSH's public projection.
58
- const projections = resolveScopedService(agent, "sessionProjections");
59
- if (typeof projections?.stateOf === "function") {
60
- const selection = projections.stateOf(session, "modelSelection");
57
+ // The Agent owns pending and last-used selections, including cold/resumed sessions.
58
+ const model = agentLike(agent)?.model;
59
+ if (typeof model?.current === "function") {
60
+ const selection = model.current();
61
61
  if (mutableService(selection))
62
- return { ...route, requestConfig: selection.pending ?? route.requestConfig };
62
+ return { ...route, requestConfig: selection };
63
63
  }
64
64
  const cached = agentRouteStates.get(session);
65
65
  return cached ? { ...route, requestConfig: cached.pending ?? cached.config } : route;
@@ -429,7 +429,9 @@ async function dshToPiMessages(messages, ctx, options, imageMap, requestImages)
429
429
  }
430
430
  continue;
431
431
  }
432
- result.push({ role: "user", content: flattenMessageText(message), timestamp: 0 });
432
+ const text = flattenMessageText(message);
433
+ if (text.length > 0)
434
+ result.push({ role: "user", content: `<system-reminder>\n${text.replaceAll("</system-reminder>", "<\\/system-reminder>")}\n</system-reminder>`, timestamp: 0 });
433
435
  continue;
434
436
  }
435
437
  if (message.role === "developer") {
@@ -553,14 +555,16 @@ export async function serializeDshMessages(messages, ctx, options = {}) {
553
555
  : await prepareRequestImageVersions(fileProjected, ctx, normalized);
554
556
  const offloadImages = attachments === undefined || normalized.imageSupport === "unsupported"
555
557
  ? 0
556
- : requiredImageOffload(fileProjected, { representation: "base64", maxBytes: normalized.maxRequestImageBytes }, (block) => {
558
+ : requiredImageOffload(fileProjected, { representation: "base64", maxBytes: normalized.maxRequestImageBytes,
559
+ maxImages: positiveSafeInteger(options.maxRequestImages, 50),
560
+ countQuantum: positiveSafeInteger(options.imageOffloadCountQuantum, Math.min(10, positiveSafeInteger(options.maxRequestImages, 50))) }, (block) => {
557
561
  // `requiredImageOffload` applies the base64 expansion itself for a
558
562
  // base64 representation, so this reports raw request-version bytes.
559
563
  const request = requestImages.get(String(block.attachment.attachmentId));
560
564
  return request?.bytes ?? block.attachment.bytes;
561
565
  });
562
566
  if (offloadImages > 0) {
563
- throw new LlmError(`LCX request images exceed the configured base64 bound; ${offloadImages} more oldest occurrence(s) must be offloaded.`, IMAGE_OFFLOAD_REQUIRED_CODE, { offloadImages });
567
+ throw new LlmError(`LCX request images exceed the configured byte or count bound; ${offloadImages} more oldest occurrence(s) must be offloaded.`, IMAGE_OFFLOAD_REQUIRED_CODE, { offloadImages });
564
568
  }
565
569
  const projected = projectOffloadedImages(fileProjected, (ref) => offloadedImageText(ref, attachments === undefined ? undefined : imageAccess(ctx, attachments, ref)));
566
570
  const model = resolvePiResponsesModel(normalized);
@@ -754,21 +758,26 @@ export function inputImageBase64Lengths(input) {
754
758
  */
755
759
  export function assertAggregateImageBudget(options) {
756
760
  const total = options.surfaceBytes.reduce((sum, bytes) => sum + bytes, options.fixedBytes);
757
- if (total <= options.maxBytes)
761
+ const maxImages = positiveSafeInteger(options.maxImages, 50);
762
+ const fixedCount = options.fixedCount ?? 0;
763
+ const excessCount = Math.max(0, fixedCount + options.surfaceBytes.length - maxImages);
764
+ const quantum = positiveSafeInteger(options.countQuantum, Math.min(10, maxImages));
765
+ const removeCount = Math.min(options.surfaceBytes.length, Math.ceil(excessCount / quantum) * quantum);
766
+ if (total <= options.maxBytes && excessCount === 0)
758
767
  return;
759
- const excess = total - options.maxBytes;
768
+ const excess = Math.max(0, total - options.maxBytes);
760
769
  let removed = 0;
761
770
  let count = 0;
762
771
  for (const bytes of options.surfaceBytes) {
763
- if (removed >= excess)
772
+ if (removed >= excess && count >= removeCount)
764
773
  break;
765
774
  removed += bytes;
766
775
  count += 1;
767
776
  }
768
- if (removed >= excess) {
769
- throw new LlmError(`LCX request images exceed the configured base64 bound once checkpoint images are counted; ${count} more oldest occurrence(s) must be offloaded.`, IMAGE_OFFLOAD_REQUIRED_CODE, { offloadImages: count });
777
+ if (removed >= excess && count >= excessCount) {
778
+ throw new LlmError(`LCX request images exceed the configured byte or count bound once checkpoint images are counted; ${count} more oldest occurrence(s) must be offloaded.`, IMAGE_OFFLOAD_REQUIRED_CODE, { offloadImages: count });
770
779
  }
771
- throw codedError(`Images retained in the compaction checkpoint (${options.fixedBytes} base64 bytes) leave no room within the ${options.maxBytes}-byte request image bound, and offloading new images cannot recover it; start a new session or raise maxRequestImageBytes`, "LCX_CHECKPOINT_IMAGE_BUDGET");
780
+ throw codedError(`Images retained in the compaction checkpoint (${options.fixedBytes} base64 bytes) leave no room within the ${options.maxBytes}-byte / ${maxImages}-image request bound, and offloading new images cannot recover it; start a new session or raise maxRequestImageBytes`, "LCX_CHECKPOINT_IMAGE_BUDGET");
772
781
  }
773
782
  export async function hydrateNativeImageReferences(output, ctx, options = {}) {
774
783
  const normalized = {
package/lib/index.js CHANGED
@@ -37,6 +37,8 @@ const ADVANCED_HOSTED_TOOL = "websearch_gpt_advanced";
37
37
  const ALPHA_TOOL = "websearch_alpha";
38
38
  const hostedSearchRouteContext = new AsyncLocalStorage();
39
39
  const WEB_SEARCH_TIMEOUT_MS = 240_000;
40
+ // DSH 0.2.2 defaults to 800; its root export does not expose this constant.
41
+ const WEB_SEARCH_SUMMARY_MAX_CHARS = 800;
40
42
  const AUTO_COMPACTION_THRESHOLD_PERCENT = 90;
41
43
  const EMERGENCY_PRUNE_THRESHOLD_PERCENT = 95;
42
44
  function positiveInteger(value, fallback, maximum) {
@@ -188,6 +190,8 @@ function requestImageOptions(routeConfig, imageSupport, signal, imageMap, extra
188
190
  signal,
189
191
  imageMap,
190
192
  maxRequestImageBytes: routeConfig.maxRequestImageBytes,
193
+ maxRequestImages: routeConfig.maxRequestImages,
194
+ imageOffloadCountQuantum: routeConfig.imageOffloadCountQuantum,
191
195
  requestImagePixelBudget: routeConfig.requestImagePixelBudget,
192
196
  requestImageMaxBytes: routeConfig.requestImageMaxBytes,
193
197
  ...extra,
@@ -266,7 +270,7 @@ function createScopedGptWebSearchTool(ctx, state, getConfig, provider, fetchEnab
266
270
  section: () => () => { },
267
271
  },
268
272
  };
269
- applyWebSearchTool(composition, getConfig().webMaxResults, WEB_SEARCH_MAX_QUERIES, WEB_SEARCH_TIMEOUT_MS, fetchEnabled);
273
+ applyWebSearchTool(composition, getConfig().webMaxResults, WEB_SEARCH_MAX_QUERIES, WEB_SEARCH_SUMMARY_MAX_CHARS, WEB_SEARCH_TIMEOUT_MS, fetchEnabled);
270
274
  if (!definition)
271
275
  throw new Error("DSH web_search composition did not register a tool");
272
276
  const execute = definition.execute.bind(definition);
@@ -683,7 +687,6 @@ async function serializeNativeAware(rawMessages, route, routeConfig, ctx, option
683
687
  // the entire tool-bearing surface; Pi alone owns declarations, removals and incremental notices.
684
688
  const transcript = [];
685
689
  const replacements = new Map();
686
- let fixedImageBytes = 0;
687
690
  for (const message of surfaceMessages) {
688
691
  assertSupportedCheckpointMessage(message);
689
692
  const checkpointId = session && isPersistedMessage(message) ? compactCheckpointId(message) : undefined;
@@ -706,12 +709,12 @@ async function serializeNativeAware(rawMessages, route, routeConfig, ctx, option
706
709
  // the current series' surface or regain instruction authority on a different route.
707
710
  const serialized = await serializeDshMessages(portable, ctx, serializeOptions({
708
711
  systemPromptUpdate: undefined, toolUpdate: undefined, tools: undefined,
712
+ // Fixed replay images cannot be offloaded by the surface owner; check the assembled request below.
713
+ maxRequestImageBytes: Number.MAX_SAFE_INTEGER, maxRequestImages: Number.MAX_SAFE_INTEGER,
709
714
  }));
710
715
  items = serialized.input;
711
716
  mergeMap(imageMap, serialized.imageMap);
712
717
  }
713
- for (const bytes of inputImageBase64Lengths(items))
714
- fixedImageBytes += bytes;
715
718
  const id = String(replacements.size);
716
719
  replacements.set(id, items);
717
720
  transcript.push(marker(id));
@@ -746,11 +749,15 @@ async function serializeNativeAware(rawMessages, route, routeConfig, ctx, option
746
749
  }
747
750
  if (ephemeralPreludeItemCount < 0 || seen.size !== replacements.size || JSON.stringify(input).includes(nonce))
748
751
  throw Object.assign(new Error("LCX could not remove request boundary markers"), { code: "LCX_RESPONSES_INVALID_INPUT" });
752
+ const assembledImages = inputImageBase64Lengths(input);
749
753
  assertAggregateImageBudget({
750
754
  maxBytes: Number.isSafeInteger(routeConfig.maxRequestImageBytes) && Number(routeConfig.maxRequestImageBytes) > 0
751
755
  ? Number(routeConfig.maxRequestImageBytes)
752
756
  : DEFAULT_MAX_REQUEST_IMAGE_BYTES,
753
- fixedBytes: fixedImageBytes,
757
+ fixedBytes: assembledImages.reduce((sum, bytes) => sum + bytes, 0) - surfaceImageBytes.reduce((sum, bytes) => sum + bytes, 0),
758
+ fixedCount: assembledImages.length - surfaceImageBytes.length,
759
+ maxImages: routeConfig.maxRequestImages,
760
+ countQuantum: routeConfig.imageOffloadCountQuantum,
754
761
  surfaceBytes: surfaceImageBytes,
755
762
  });
756
763
  if (!nativeModel)
@@ -792,7 +799,7 @@ async function* remoteCompactionStream(options, routeConfig, ctx, next) {
792
799
  toolSurface: { history: options.toolHistory },
793
800
  });
794
801
  const cacheSessionId = promptCacheSessionId(route, routeConfig, ctx);
795
- const headers = await authenticatedHeaders(ctx, routeConfig, cacheSessionId, cacheSessionId === undefined ? null : route.sessionId, providerDynamicHeaders(routeConfig.provider, options.messages), route.sessionId || undefined);
802
+ const headers = await authenticatedHeaders(ctx, routeConfig, cacheSessionId, cacheSessionId === undefined ? null : route.sessionId, providerDynamicHeaders(routeConfig.provider, options.messages), route.sessionId || undefined, options);
796
803
  const generation = generationControlsFromSession(sessionFor(ctx, route.sessionId), route);
797
804
  const result = await requestNativeCompaction({
798
805
  baseURL: routeConfig.baseURL,
@@ -1097,7 +1104,7 @@ async function* managedResponsesStream(options, routeConfig, ctx) {
1097
1104
  });
1098
1105
  assertSupportedReasoningEffort(options.reasoningEffort, prepared.modelFacts);
1099
1106
  const cacheSessionId = promptCacheSessionId(route, routeConfig, ctx);
1100
- const headers = await authenticatedHeaders(ctx, routeConfig, cacheSessionId, cacheSessionId === undefined ? null : route.sessionId, providerDynamicHeaders(routeConfig.provider, options.messages), route.sessionId || undefined);
1107
+ const headers = await authenticatedHeaders(ctx, routeConfig, cacheSessionId, cacheSessionId === undefined ? null : route.sessionId, providerDynamicHeaders(routeConfig.provider, options.messages), route.sessionId || undefined, options);
1101
1108
  const body = buildResponsesBody({
1102
1109
  model: prepared.model,
1103
1110
  input: prepared.input,
@@ -183,7 +183,11 @@ export function managedFailure(error, signal, upstream) {
183
183
  /time(?:d)?\s*out|timeout/iu.test(String(signalReason?.message ?? "")));
184
184
  const upstreamClass = signal?.aborted ? undefined : classifyUpstreamFailure(upstream);
185
185
  let code = "RESPONSES_ERROR";
186
- if (upstreamClass?.definite === true)
186
+ if (sourceCodes.has("REQUEST_HEADERS"))
187
+ code = "REQUEST_HEADERS";
188
+ else if (sourceCodes.has("MALFORMED_RESPONSE"))
189
+ code = "MALFORMED_RESPONSE";
190
+ else if (upstreamClass?.definite === true)
187
191
  code = upstreamClass.code;
188
192
  else if (signalTimedOut ||
189
193
  facts.status === 408 ||
@@ -246,6 +250,8 @@ export function managedFailure(error, signal, upstream) {
246
250
  if (code === "RESPONSES_ERROR" && upstreamClass !== undefined)
247
251
  code = upstreamClass.code;
248
252
  const messages = {
253
+ MALFORMED_RESPONSE: "Responses provider completed a tool call with malformed arguments",
254
+ REQUEST_HEADERS: error instanceof Error ? error.message : "Request header preparation failed",
249
255
  ABORTED: "Responses request was aborted",
250
256
  AUTH: "Responses request was rejected by authentication",
251
257
  INSUFFICIENT_QUOTA: "服务商额度不足或未满足请求预留额度,请检查中转额度(并非 API 密钥无效) / Provider quota is insufficient for this request",
@@ -1200,6 +1206,7 @@ function successfulFinish(message) {
1200
1206
  */
1201
1207
  async function* toDshChunks(events, signal, wireMeta, nativeReplayRoute) {
1202
1208
  const toolIds = new Map();
1209
+ let argumentsError = false;
1203
1210
  for await (const event of events) {
1204
1211
  switch (event.type) {
1205
1212
  case "start":
@@ -1282,6 +1289,10 @@ async function* toDshChunks(events, signal, wireMeta, nativeReplayRoute) {
1282
1289
  const call = isRecord(event.toolCall)
1283
1290
  ? event.toolCall
1284
1291
  : {};
1292
+ if (call.argumentsError !== undefined) {
1293
+ argumentsError = true;
1294
+ break;
1295
+ }
1285
1296
  yield {
1286
1297
  type: "block-end",
1287
1298
  index: Number(event.contentIndex),
@@ -1299,6 +1310,8 @@ async function* toDshChunks(events, signal, wireMeta, nativeReplayRoute) {
1299
1310
  ? event.message
1300
1311
  : {};
1301
1312
  yield { type: "usage", usage: dshUsage(message.usage) };
1313
+ if (argumentsError && message.stopReason !== "length")
1314
+ throw codedError("Responses provider completed a tool call with malformed arguments", "MALFORMED_RESPONSE");
1302
1315
  const reason = successfulFinish(message);
1303
1316
  const replay = reason.kind === "error"
1304
1317
  ? undefined
package/lib/route.js CHANGED
@@ -2,7 +2,7 @@ import { createHash, randomUUID } from "node:crypto";
2
2
  import { credentialRef } from "@deepseek-ai/dsh-credentials";
3
3
  import { SessionId } from "@deepseek-ai/dsh-session";
4
4
  import "@deepseek-ai/dsh-settings";
5
- import { assertUsableApiKey, attributionHeaders, resolveRetryPolicy } from "@deepseek-ai/dsh-llm";
5
+ import { assertUsableApiKey, attributionHeaders, LlmError, resolveRetryPolicy } from "@deepseek-ai/dsh-llm";
6
6
  import { resolveCatalogModel } from "./model-catalog.js";
7
7
  import { clampOpenAIPromptCacheKey } from "./pi-responses-runtime.js";
8
8
  import { providerSessionHeaders } from "./provider-headers.js";
@@ -362,6 +362,8 @@ export function resolveResponsesRouteConfig(ctx, options, policy, assumeHostServ
362
362
  // These are explicitly LCX-owned transport and request-capability policies.
363
363
  timeoutMs: isPositiveSafeInteger(configured.timeoutMs) ? configured.timeoutMs : policy.timeoutMs,
364
364
  maxAttempts: retryAttempts(configured.retryPolicy, policy.maxAttempts),
365
+ maxRequestImages: isPositiveSafeInteger(configured.maxRequestImages) ? configured.maxRequestImages : 50,
366
+ imageOffloadCountQuantum: isPositiveSafeInteger(configured.imageOffloadCountQuantum) ? configured.imageOffloadCountQuantum : Math.min(10, isPositiveSafeInteger(configured.maxRequestImages) ? configured.maxRequestImages : 50),
365
367
  maxRequestImageBytes: isPositiveSafeInteger(configured.maxRequestImageBytes) ? configured.maxRequestImageBytes : policy.maxRequestImageBytes,
366
368
  requestImagePixelBudget: isPositiveSafeInteger(configured.requestImagePixelBudget) ? configured.requestImagePixelBudget : policy.requestImagePixelBudget,
367
369
  requestImageMaxBytes: isPositiveSafeInteger(configured.requestImageMaxBytes) ? configured.requestImageMaxBytes : policy.requestImageMaxBytes,
@@ -446,6 +448,8 @@ export function resolveGrokResponsesRouteConfig(ctx, options, policy) {
446
448
  ? configured.streamIdleTimeoutMs
447
449
  : DEFAULTS.streamIdleTimeoutMs,
448
450
  maxAttempts: retryAttempts(configured.retryPolicy, policy.maxAttempts),
451
+ maxRequestImages: isPositiveSafeInteger(configured.maxRequestImages) ? configured.maxRequestImages : 50,
452
+ imageOffloadCountQuantum: isPositiveSafeInteger(configured.imageOffloadCountQuantum) ? configured.imageOffloadCountQuantum : Math.min(10, isPositiveSafeInteger(configured.maxRequestImages) ? configured.maxRequestImages : 50),
449
453
  maxRequestImageBytes: isPositiveSafeInteger(configured.maxRequestImageBytes)
450
454
  ? configured.maxRequestImageBytes
451
455
  : policy.maxRequestImageBytes,
@@ -503,18 +507,44 @@ function sessionAffinityFormat(config) {
503
507
  ? "openrouter"
504
508
  : "openai";
505
509
  }
510
+ /** Headers whose owners (credentials, session affinity, correlation) layer them after the contributors. */
511
+ const OWNER_PROTECTED_HEADERS = new Set(["authorization", "session_id", "session-id", "x-session-id", "x-client-request-id", "x-opencode-session"]);
512
+ /** The host exposes profile headers only. Credential and routing headers are layered by their owners later. */
513
+ export function prepareRequestHeaders(ctx, config, options = {}) {
514
+ try {
515
+ const initial = new Headers(config.headers);
516
+ const request = Object.freeze({ provider: config.provider, model: config.model, baseURL: config.baseURL,
517
+ ...(options.sessionId === undefined ? {} : { sessionId: options.sessionId }),
518
+ ...(options.purpose === undefined ? {} : { purpose: options.purpose }) });
519
+ const waterfall = ctx?.waterfall;
520
+ const headers = waterfall === undefined ? initial : waterfall.call(ctx, "llm-pi-ai/request-headers", request, initial, () => initial);
521
+ for (const [name, value] of Object.entries(attributionHeaders()))
522
+ headers.set(name, value);
523
+ return Object.fromEntries(headers);
524
+ }
525
+ catch (error) {
526
+ const diagnostic = error instanceof TypeError
527
+ ? "TypeError during header preparation; check the contributing plugin's header names, values, and configuration"
528
+ : error instanceof Error ? error.message : "the contributing plugin threw a non-Error value; throw an Error with a safe diagnostic";
529
+ throw new LlmError(`pi-ai request header preparation failed for provider "${config.provider}": ${diagnostic}`, "REQUEST_HEADERS", { cause: error });
530
+ }
531
+ }
506
532
  /**
507
533
  * The headers of one GPT request. `sessionId` is the prompt-cache / affinity session (the root session for a
508
534
  * subagent, absent without cache retention); `providerSessionId` is the CURRENT DSH session, which is what Pi's
509
535
  * client sends in provider routing headers (`x-opencode-session`) whatever the cache policy is.
510
536
  */
511
- export async function authenticatedHeaders(ctx, config, sessionId, requestId, dynamicHeaders = {}, providerSessionId) {
537
+ export async function authenticatedHeaders(ctx, config, sessionId, requestId, dynamicHeaders = {}, providerSessionId, request) {
512
538
  const explicit = { ...(config.headers ?? {}) };
539
+ const currentSessionId = providerSessionId ?? (sessionId ? String(sessionId) : undefined);
540
+ // As on the host, the credential is resolved before contributors run: a missing one never reaches them.
541
+ const apiKey = await resolveApiKey(ctx, config);
542
+ const prepared = prepareRequestHeaders(ctx, config, request ?? (currentSessionId === undefined ? {} : { sessionId: currentSessionId }));
513
543
  const sid = sessionId ? String(sessionId) : undefined;
514
544
  const format = sessionAffinityFormat(config);
515
- // Lowest first, as Pi's client layers them: the catalog model's own headers, DSH attribution, the credential,
516
- // the provider's per-request headers (Copilot initiator / vision, OpenCode routing), then the affinity ids.
517
- const headers = layerHeaders(config.catalogHeaders, attributionHeaders(), { authorization: `Bearer ${await resolveApiKey(ctx, config)}` }, dynamicHeaders, providerSessionHeaders(config.provider, providerSessionId ?? sid));
545
+ // Model/provider defaults precede the contributed profile layer. Credentials and session routing
546
+ // are owned by their later layers; attribution is re-applied last.
547
+ const headers = layerHeaders(config.catalogHeaders, dynamicHeaders, prepared, { authorization: `Bearer ${apiKey}` }, providerSessionHeaders(config.provider, providerSessionId ?? sid));
518
548
  if (sid && !hasExplicitSessionAffinity(explicit)) {
519
549
  if (format === "openai")
520
550
  headers.session_id = sid;
@@ -526,8 +556,11 @@ export async function authenticatedHeaders(ctx, config, sessionId, requestId, dy
526
556
  if (correlation)
527
557
  headers["x-client-request-id"] = correlation;
528
558
  }
529
- // The profile's own headers win over every default.
530
- return layerHeaders(headers, explicit);
559
+ // Ordinary profile headers keep whatever the contributors made of them. The owner-protected ones (credential,
560
+ // session affinity, correlation) are the profile's to set over every default and never a contributor's.
561
+ // Attribution is re-applied last, as on the host.
562
+ const protectedProfile = Object.fromEntries(Object.entries(explicit).filter(([name]) => OWNER_PROTECTED_HEADERS.has(name.toLowerCase())));
563
+ return layerHeaders(headers, protectedProfile, attributionHeaders());
531
564
  }
532
565
  /** Grok mirrors Pi createClient ordering without changing accepted GPT headers. */
533
566
  export async function authenticatedGrokHeaders(ctx, config, sessionId, dynamicHeaders = {}, providerSessionId) {
@@ -51,7 +51,7 @@ export const searchUsageProjection = {
51
51
  };
52
52
  const installed = new WeakMap();
53
53
  /** Own a reversible adapter on the public measure method, never a DSH file or private fold. */
54
- export function installSearchMeasurement(meter, projections) {
54
+ export function installSearchMeasurement(meter, projection) {
55
55
  const existing = installed.get(meter);
56
56
  if (existing) {
57
57
  existing.refs++;
@@ -64,7 +64,7 @@ export function installSearchMeasurement(meter, projections) {
64
64
  const original = meter.measure, descriptor = Object.getOwnPropertyDescriptor(meter, 'measure');
65
65
  function measure(session, header) {
66
66
  const value = original.call(this, session, header);
67
- const state = projections.stateOf(session, 'lcxSearchUsage');
67
+ const state = projection.stateOf(session);
68
68
  if (!state?.aggregateContext)
69
69
  return value;
70
70
  const effectiveHeader = header ?? session.requestHeader();
@@ -106,8 +106,10 @@ function release(meter) {
106
106
  }
107
107
  }
108
108
  export function installSearchUsage(ctx) {
109
- ctx.inject(['sessionProjections'], c => { c.sessionProjections.register(searchUsageProjection); });
110
- ctx.inject(['tokenMeter', 'sessionProjections'], c => {
111
- c.effect(() => installSearchMeasurement(c.tokenMeter, c.sessionProjections), 'lcx search context measurement');
109
+ ctx.inject(['sessionProjections'], async (c) => {
110
+ const handle = await c.sessionProjections.register(searchUsageProjection);
111
+ c.inject(['tokenMeter'], c => {
112
+ c.effect(() => installSearchMeasurement(c.tokenMeter, handle), 'lcx search context measurement');
113
+ });
112
114
  });
113
115
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-lcx-codex",
3
- "version": "0.6.0",
3
+ "version": "0.7.0-pre.1",
4
4
  "description": "Model-scoped DSH plugin: GPT Responses lifecycle, Native V2 compaction and Hosted/Alpha Search; Grok native Web/X Search",
5
5
  "icon": "./icon.svg",
6
6
  "keywords": [
@@ -66,9 +66,9 @@
66
66
  }
67
67
  },
68
68
  "devDependencies": {
69
- "@deepseek-ai/dsh": "0.2.1-rc.5",
69
+ "@deepseek-ai/dsh": "0.2.2-alpha.3",
70
70
  "@earendil-works/pi-ai": "1.5.0",
71
- "@deepseek-ai/schemastery": "~3.18.5-alpha.2",
71
+ "@deepseek-ai/schemastery": "~3.18.6-alpha.2",
72
72
  "@types/node": "^22.20.0",
73
73
  "@types/react": "~18.3.1",
74
74
  "esbuild": "^0.28.2",
@@ -76,33 +76,34 @@
76
76
  "typescript": "7.0.2"
77
77
  },
78
78
  "peerDependencies": {
79
- "@deepseek-ai/cordis": ">=4.0.5",
80
- "@deepseek-ai/cordis-plugin-loader": ">=1.0.6",
81
- "@deepseek-ai/dsh-agent": ">=0.2.1-rc.5 <0.2.2-0",
82
- "@deepseek-ai/dsh-api-session-controller": ">=0.2.1-rc.5 <0.2.2-0",
83
- "@deepseek-ai/dsh-attachment": ">=0.2.1-rc.5 <0.2.2-0",
84
- "@deepseek-ai/dsh-client-locale": ">=0.2.1-rc.5 <0.2.2-0",
85
- "@deepseek-ai/dsh-client-modules": ">=0.2.1-rc.5 <0.2.2-0",
86
- "@deepseek-ai/dsh-client-store": ">=0.2.1-rc.5 <0.2.2-0",
87
- "@deepseek-ai/dsh-client-ui-chat": ">=0.2.1-rc.5 <0.2.2-0",
88
- "@deepseek-ai/dsh-client-ui-conversation": ">=0.2.1-rc.5 <0.2.2-0",
89
- "@deepseek-ai/dsh-client-ui-plugin-manager": ">=0.2.1-rc.5 <0.2.2-0",
90
- "@deepseek-ai/dsh-client-ui-settings": ">=0.2.1-rc.5 <0.2.2-0",
91
- "@deepseek-ai/dsh-compaction": ">=0.2.1-rc.5 <0.2.2-0",
92
- "@deepseek-ai/dsh-credentials": ">=0.2.1-rc.5 <0.2.2-0",
93
- "@deepseek-ai/dsh-fs": ">=0.2.1-rc.5 <0.2.2-0",
94
- "@deepseek-ai/dsh-llm": ">=0.2.1-rc.5 <0.2.2-0",
95
- "@deepseek-ai/dsh-session": ">=0.2.1-rc.5 <0.2.2-0",
96
- "@deepseek-ai/dsh-session-query": ">=0.2.1-rc.5 <0.2.2-0",
97
- "@deepseek-ai/dsh-settings": ">=0.2.1-rc.5 <0.2.2-0",
98
- "@deepseek-ai/dsh-tool-web": ">=0.2.1-rc.5 <0.2.2-0",
99
- "@deepseek-ai/dsh-tools": ">=0.2.1-rc.5 <0.2.2-0",
100
- "@deepseek-ai/dsh-web": ">=0.2.1-rc.5 <0.2.2-0",
101
- "@deepseek-ai/schemastery": ">=3.18.5",
79
+ "@deepseek-ai/cordis": ">=4.0.6-alpha.2",
80
+ "@deepseek-ai/cordis-plugin-loader": ">=1.0.7-alpha.2",
81
+ "@deepseek-ai/dsh-agent": ">=0.2.2-alpha.3",
82
+ "@deepseek-ai/dsh-api-session-controller": ">=0.2.2-alpha.3",
83
+ "@deepseek-ai/dsh-attachment": ">=0.2.2-alpha.3",
84
+ "@deepseek-ai/dsh-client-locale": ">=0.2.2-alpha.3",
85
+ "@deepseek-ai/dsh-client-modules": ">=0.2.2-alpha.3",
86
+ "@deepseek-ai/dsh-client-store": ">=0.2.2-alpha.3",
87
+ "@deepseek-ai/dsh-client-ui-chat": ">=0.2.2-alpha.3",
88
+ "@deepseek-ai/dsh-client-ui-conversation": ">=0.2.2-alpha.3",
89
+ "@deepseek-ai/dsh-client-ui-plugin-manager": ">=0.2.2-alpha.3",
90
+ "@deepseek-ai/dsh-client-ui-settings": ">=0.2.2-alpha.3",
91
+ "@deepseek-ai/dsh-compaction": ">=0.2.2-alpha.3",
92
+ "@deepseek-ai/dsh-credentials": ">=0.2.2-alpha.3",
93
+ "@deepseek-ai/dsh-fs": ">=0.2.2-alpha.3",
94
+ "@deepseek-ai/dsh-llm": ">=0.2.2-alpha.3",
95
+ "@deepseek-ai/dsh-session": ">=0.2.2-alpha.3",
96
+ "@deepseek-ai/dsh-session-query": ">=0.2.2-alpha.3",
97
+ "@deepseek-ai/dsh-settings": ">=0.2.2-alpha.3",
98
+ "@deepseek-ai/dsh-tool-web": ">=0.2.2-alpha.3",
99
+ "@deepseek-ai/dsh-tools": ">=0.2.2-alpha.3",
100
+ "@deepseek-ai/dsh-web": ">=0.2.2-alpha.3",
101
+ "@deepseek-ai/schemastery": ">=3.18.6-alpha.2",
102
102
  "react": "^18.2.0",
103
- "@deepseek-ai/dsh-token-meter": ">=0.2.1-rc.5 <0.2.2-0",
104
- "@deepseek-ai/dsh-session-projection": ">=0.2.1-rc.5 <0.2.2-0",
105
- "zod": "^4.5.4"
103
+ "@deepseek-ai/dsh-token-meter": ">=0.2.2-alpha.3",
104
+ "@deepseek-ai/dsh-session-projection": ">=0.2.2-alpha.3",
105
+ "zod": "^4.5.4",
106
+ "@deepseek-ai/dsh-tool-executor-ptc": ">=0.2.2-alpha.3"
106
107
  },
107
108
  "peerDependenciesMeta": {
108
109
  "@deepseek-ai/cordis-plugin-loader": {
@@ -167,6 +168,9 @@
167
168
  },
168
169
  "@deepseek-ai/dsh-web": {
169
170
  "optional": true
171
+ },
172
+ "@deepseek-ai/dsh-tool-executor-ptc": {
173
+ "optional": true
170
174
  }
171
175
  },
172
176
  "scripts": {
@@ -188,8 +192,8 @@
188
192
  },
189
193
  "license": "MIT",
190
194
  "lcxCompatibility": {
191
- "dshInstallRange": ">=0.2.1-rc.5 <0.2.2-0",
192
- "verifiedDsh": "0.2.1-rc.5",
195
+ "dshInstallRange": ">=0.2.2-alpha.3",
196
+ "verifiedDsh": "0.2.2-alpha.3",
193
197
  "verifiedHostPi": "1.5.0",
194
198
  "verifiedPluginPi": "1.5.0"
195
199
  }