@deepseek-ai/dsh-llm-pi-ai 0.2.2-rc.5 → 0.2.3-alpha.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.i18n.yaml CHANGED
@@ -21,8 +21,8 @@
21
21
  en: f3b761c7c7ecb82f
22
22
  zh: e10d999aa348ef86
23
23
  /deepseek-ai-dsh-llm-pi-ai/use-this-package/configure-provider-routes:
24
- en: 12d3d1506c72ac8b
25
- zh: d966efb555110713
24
+ en: 5f2e3298066947a2
25
+ zh: 0166148523454073
26
26
  /deepseek-ai-dsh-llm-pi-ai/use-this-package/sign-in-to-a-provider:
27
27
  en: c36f66438638ae08
28
28
  zh: 066a2fc4cb97c86f
@@ -45,8 +45,8 @@
45
45
  en: 1598ac8a8bb9b6bf
46
46
  zh: fdd089c5ae7722cd
47
47
  /deepseek-ai-dsh-llm-pi-ai/understand-the-implementation/design-philosophy:
48
- en: db1ac8ccca2d858b
49
- zh: 1d7cd4153aad22b0
48
+ en: 51463a69b90651db
49
+ zh: 97857611c89abf4e
50
50
  /deepseek-ai-dsh-llm-pi-ai/understand-the-implementation/request-headers:
51
51
  en: 615ca9834bf6544f
52
52
  zh: 2d70b548f99000d1
@@ -72,14 +72,14 @@
72
72
  en: e7348db3f7115960
73
73
  zh: 5fd5fb09d7d09982
74
74
  /deepseek-ai-dsh-llm-pi-ai/model-experience/provider-request-through-pi-ai/what-the-model-sees:
75
- en: f618a730aaa904ce
76
- zh: 0b77a5b799b049e3
75
+ en: f1f9af4800b6aaa6
76
+ zh: 3745881f1a9c18a7
77
77
  /deepseek-ai-dsh-llm-pi-ai/model-experience/provider-request-through-pi-ai/token-effect:
78
78
  en: 820221e8ae37aa61
79
79
  zh: 7e6ff4db10067fc0
80
80
  /deepseek-ai-dsh-llm-pi-ai/model-experience/provider-request-through-pi-ai/kv-cache-effect:
81
- en: 6613d52e459d86da
82
- zh: 7d0627e7ff8299e8
81
+ en: c0fd11162e393727
82
+ zh: c4ebcdf7049ae677
83
83
  /deepseek-ai-dsh-llm-pi-ai/model-experience/provider-response:
84
84
  en: 802d7ff60a1d03ff
85
85
  zh: c41c56e28f3e8680
@@ -93,8 +93,8 @@
93
93
  en: b6bd570c0159ba08
94
94
  zh: 7d2d91eea6a8d830
95
95
  /deepseek-ai-dsh-llm-pi-ai/known-limitations-and-deferred-work:
96
- en: fdbe8ce850250b66
97
- zh: d8b9a06a996850c1
96
+ en: ca569aca42ffe0bc
97
+ zh: 2d5e30f0b422166b
98
98
  /deepseek-ai-dsh-llm-pi-ai/known-limitations-and-deferred-work/dev-note:
99
99
  en: 3678dd0f6642c2a5
100
100
  zh: 75cbdd064cc64282
package/README.md CHANGED
@@ -46,7 +46,9 @@ Each profile may set a `retryPolicy`; omission uses normal mode with five retrie
46
46
  baseURL: https://proxy.example.com:8443
47
47
  reasoning: high
48
48
  requestImagePixelBudget: 4194304 # total pixels; 2048 by 2048 default
49
- requestImageMaxBytes: 1048576 # raw bytes before base64 expansion
49
+ requestImageMaxDimension: 3000 # override catalog width and height limits
50
+ requestImageMaxBytes: 1048576 # hard per-image cap before allocation
51
+ requestImageBudgetCount: 20 # fixed number of equal budget shares
50
52
  maxRequestImageBytes: 20971520 # accumulated base64 payload
51
53
  maxRequestImages: 50 # retained image occurrences
52
54
  imageOffloadCountQuantum: 10 # oldest images offloaded per count overflow
@@ -86,12 +88,18 @@ Each profile may set a `retryPolicy`; omission uses normal mode with five retrie
86
88
  | `defaultContextWindow` | `1,000,000` | Capacity fallback for undescribed models |
87
89
  | `defaultMaxTokens` | `128,000` | Output-cap fallback for undescribed models |
88
90
  | `requestImagePixelBudget` | `4,194,304` | Total-pixel budget for each deterministic request image |
89
- | `requestImageMaxBytes` | `1 MiB` | Encoded-byte target for each request image before base64 expansion |
91
+ | `requestImageMaxDimension` | catalog width/height limits | Maximum width and height for each request image; an explicit value overrides both catalog limits |
92
+ | `requestImageMaxBytes` | catalog base64 cap converted to raw bytes; otherwise `1 MiB` | Hard per-image cap before allocation; an explicit value overrides the catalog cap |
93
+ | `requestImageBudgetCount` | `20` | Fixed divisor of the aggregate image budget; independent of retained image count |
90
94
  | `maxRequestImageBytes` | `20 MiB` | Aggregate base64 image-payload bound; a request whose retained images exceed it fails with `IMAGE_OFFLOAD_REQUIRED` |
91
95
  | `maxRequestImages` | `50` | Retained request-image count bound; a request whose retained images exceed it fails with `IMAGE_OFFLOAD_REQUIRED`. The default follows Azure OpenAI's 50-image limit; raise it on routes whose provider accepts more images |
92
96
  | `imageOffloadCountQuantum` | `10`, capped at `maxRequestImages` | Oldest images offloaded per count overflow |
93
97
  | `retryPolicy` | normal, 5 retries | Provider-owned retry policy executed by `dsh-llm-retry` |
94
98
 
99
+ Request images inherit the selected pi-ai model's `inputLimits.images.resize` width, height, and base64-byte cap. `requestImageMaxDimension` overrides both dimensions with one value; it cannot express unequal width and height overrides. `requestImageMaxBytes` overrides the per-image cap in raw encoded bytes. The effective hard limit is `min(3 × floor(maxRequestImageBytes / (4 × requestImageBudgetCount)), requestImageMaxBytes or catalog cap or 1 MiB)`, with the catalog cap converted using `3 × floor(catalogBytes / 4)`. Configuration must allow at least four aggregate base64 bytes per budget share. Defaults allocate 0.75 MiB per image, so 20 images at that limit use at most 20 MiB of base64 payload. Budget shares stay fixed as history grows; `maxRequestImages` separately controls retained occurrences. Missing catalog dimensions leave that axis uncapped, while total pixels remain governed by `requestImagePixelBudget`.
100
+
101
+ pi exposes no separate soft-byte target: the shared encoder's `imageTargetBytes` equals its effective `maxImageBytes`. After the quality ladder, images that still exceed the limit are resized and re-encoded until they fit; an impossible limit fails explicitly. Stored attachments stay unchanged. Image descriptors and screenshot coordinates use the final encoded dimensions. Increase `requestImageBudgetCount` for smaller per-image allocations, or decrease it for larger ones; the aggregate cap still applies to actual payloads.
102
+
95
103
  The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-llm-pi-ai) is the exhaustive source for every accepted field and its JSDoc.
96
104
 
97
105
  ### Sign in to a provider
@@ -142,7 +150,7 @@ This section explains the design behind the adapter; the observable behavior is
142
150
 
143
151
  The adapter is built on immutable snapshots and per-operation resolution. Each operation captures a whole snapshot — the profiles plus a `createModels()` collection holding the `Provider` each route built — before its first `await`, and a configuration change builds a new collection rather than mutating the one in use, so a request that started under one configuration never finishes under another. A route's own credential reference resolves through the harness seam and rides as the request's `apiKey` option, which pi-ai treats as the highest-priority auth override — that is what keeps the fail-loud reference semantics. Everything that override does not cover reaches pi-ai through the collection's own auth: the credential store holds the records a login wrote and a refresh rotates (addressed as `llm-pi-ai/<provider id>`), and the auth context answers the ambient questions a provider asks while resolving. Both are stable across snapshots, so a configuration change rebuilds the collection without forgetting who is signed in. Runtime imports use pi-ai's provider, API, and utility entry points; `src/models.ts` supplies the small model-helper subset this adapter needs without evaluating pi-ai's aggregate entry point.
144
152
 
145
- Initial prompt text and active tools use pi-ai's `Context.systemPrompt` and `Context.tools`; later system and tool updates remain in `Context.messages`. pi-ai normalizes these fields and applies the selected protocol's serialization rules.
153
+ Initial prompt text and active tools use pi-ai's `Context.systemPrompt` and `Context.tools`; later system and tool updates remain in `Context.messages`. pi-ai normalizes these fields and applies the selected protocol's serialization rules. User and tool text blocks remain separate for pi-ai to serialize. System text, including developer updates, is joined with blank lines before delegation because pi-ai otherwise joins separate system blocks with single newlines. The initial prompt and system-reminder fallback use the same separator. Empty text blocks are omitted. System text blocks are trimmed first, so whitespace-only blocks are omitted too; user and tool text keeps its whitespace.
146
154
 
147
155
  <a id="request-headers"></a>
148
156
  ### Request headers
@@ -223,7 +231,7 @@ Read these pages when the package-level contract is not enough. They move from t
223
231
 
224
232
  #### What the model sees
225
233
 
226
- The selected catalog model receives system-message text, conversation history, tools, and supported sampling fields. The adapter preserves later system messages in history order when the catalog model declares `supportsMidConvoSystemMessages`. Otherwise, it converts each non-empty later system message to a user message wrapped in `<system-reminder>` before passing it to pi-ai. The wrapper does not grant system-role priority. One-shot `GenerateOptions.system` precedes the initial history prompt. Repeated system messages remain repeated; empty system messages are skipped without discarding earlier text. Tool-update capabilities select the shared historical declaration projection; pi-ai receives initially active tools and grouped developer updates carrying additions and supported removals. When every projected declaration of an Anthropic request with tool updates is deferred, the initially active tools are one placeholder, `DeferredToolPlaceholder`, whose description tells the model never to call it; a call reaches the ordinary unknown-tool result. Anthropic receives later tool definitions inline in the update message. Replay preserves tool-call namespaces for dynamically loaded Responses tools. Each retained image is preceded by text naming its complete attachment id and actual request dimensions. When the current execution filesystem maps the attachment provider's host object, the text also carries a read-only normalized-object path and warns that normalization or request projection may have resized or re-encoded the upload. Each occurrence selected by a logged image-offload decision keeps its own identity and currently resolved access in replacement text, and its normalized attachment is not read or transformed. When the retained occurrences still exceed the route's `maxRequestImages`, or their exact base64 payload exceeds its `maxRequestImageBytes`, the call fails with `IMAGE_OFFLOAD_REQUIRED` so `dsh-compaction-image-offload` records the selected occurrences in an `image/offload` event and retries the step. Provider-native replay metadata is restored only when the adapter validates it for the historical content. On Anthropic Messages routes, a replayed response whose request prefix changed since generation, for example through compaction, loses its thinking blocks; its text and tool calls remain. `imageRequestTarget(provider, model, image)` exposes the same request-image dimensions and byte target to screenshot consumers; adapters without image resizing preserve the normalized source.
234
+ The selected catalog model receives system-message text, conversation history, tools, and supported sampling fields. The adapter preserves later system messages in history order when the catalog model declares `supportsMidConvoSystemMessages`. Otherwise, it converts each non-empty later system message to a user message wrapped in `<system-reminder>` before passing it to pi-ai. The wrapper does not grant system-role priority. One-shot `GenerateOptions.system` precedes the initial history prompt. Repeated system messages remain repeated; empty system messages are skipped without discarding earlier text. Tool-update capabilities select the shared historical declaration projection; pi-ai receives initially active tools and grouped developer updates carrying additions and supported removals. When every projected declaration of an Anthropic request with tool updates is deferred, the initially active tools are one placeholder, `DeferredToolPlaceholder`, whose description tells the model never to call it; a call reaches the ordinary unknown-tool result. Anthropic receives later tool definitions inline in the update message. Replay preserves tool-call namespaces for dynamically loaded Responses tools. Each retained image is preceded by text naming its complete attachment id and actual request dimensions. When the current execution filesystem maps the attachment provider's host object, the text also carries a read-only normalized-object path and warns that normalization or request projection may have resized or re-encoded the upload. Each occurrence selected by a logged image-offload decision keeps its own identity and currently resolved access in replacement text, and its normalized attachment is not read or transformed. When the retained occurrences still exceed the route's `maxRequestImages`, or their exact base64 payload exceeds its `maxRequestImageBytes`, the call fails with `IMAGE_OFFLOAD_REQUIRED` so `dsh-compaction-image-offload` records the selected occurrences in an `image/offload` event and retries the step. The default allocation limits each encoded image to 0.75 MiB, allowing 20 such images within the 20 MiB aggregate base64 budget. Smaller images can retain more occurrences, subject to the count limit. Provider-native replay metadata is restored only when the adapter validates it for the historical content. On Anthropic Messages routes, a replayed response whose request prefix changed since generation, for example through compaction, loses its thinking blocks; its text and tool calls remain. `imageRequestTarget(provider, model, image)` exposes the maximum dimensions and byte limits to screenshot consumers; `readImageRequest` returns the actual encoded dimensions after enforcing the byte limit.
227
235
 
228
236
  #### Token effect
229
237
 
@@ -231,7 +239,7 @@ Provider tokenization governs exact input. Retained images add the stable attach
231
239
 
232
240
  #### KV Cache effect
233
241
 
234
- Later system messages supplied to the adapter stay out of the initial prompt, preserving the preceding request prefix. This does not change the agent loop’s prompt admission, which consolidates updates on routes without native system-update support. Conversion preserves logical request order, while image handles and offload placeholders add model-visible text. A changed execution-world path rewrites a historical handle and can prevent reuse from that image even when attachment identity and request bytes stay stable. Changing adapter instance, provider, model, or another upstream token has the same suffix effect. Omitting stale Anthropic thinking follows a prefix change that already ended reuse at the changed message. The first request that omits thinking recorded without a digest ends reuse at the first such message once. An offload decision turns an earlier image into placeholder text, so reuse ends at that message; the omission never reverts, so the prefix stays stable until the next decision. A count overflow offloads `imageOffloadCountQuantum` images at once, so a saturated route ends reuse at the oldest retained image once per that many new images.
242
+ Later system messages supplied to the adapter stay out of the initial prompt, preserving the preceding request prefix. This does not change the agent loop’s prompt admission, which consolidates updates on routes without native system-update support. Conversion preserves logical request order, while image handles and offload placeholders add model-visible text. A changed execution-world path rewrites a historical handle and can prevent reuse from that image even when attachment identity and request bytes stay stable. Changing adapter instance, provider, model, or another upstream token has the same suffix effect. Omitting stale Anthropic thinking follows a prefix change that already ended reuse at the changed message. The first request that omits thinking recorded without a digest ends reuse at the first such message once. An offload decision turns an earlier image into placeholder text, so reuse ends at that message; the omission never reverts, so the prefix stays stable until the next decision. Changing configured byte budgets can resize historical request images and end prefix reuse; merely adding an image does not change the per-image allocation. A count overflow offloads `imageOffloadCountQuantum` images at once, so a saturated route ends reuse at the oldest retained image once per that many new images.
235
243
 
236
244
  ### Provider response
237
245
 
@@ -267,7 +275,7 @@ These limits define where the adapter stops and future work begins. They are cur
267
275
  - **Uncataloged models need an unambiguous protocol** — catalog routes preserve each model's protocol, including both Azure APIs under `azure`. A model absent from a mixed-protocol catalog needs an explicit route-level `api`, which overrides every model on the route and must be one of the supported custom protocols. For Azure deployment names, keep the catalog model ID and set `AZURE_OPENAI_DEPLOYMENT_NAME_MAP`.
268
276
  - **A modality declaration is not verified** — a model declaring `image` its gateway does not serve is refused by the provider after prompt admission. The durable image remains in history and the same misdeclared model can fail again; switching to a text-only model remains possible because the shared LLM runtime projects image references into stable text for that request.
269
277
  - **An unauthenticated route depends on its protocol** — a route naming no credential resolves as configured-but-keyless, but pi-ai's OpenAI-compatible implementation still requires an API key or an `Authorization` header, so a keyless local server needs a placeholder credential referenced by `apiKeyEnv` or an `Authorization` entry in `headers`. pi-ai's Gemini implementation refuses a request without an API key, so a `google-generative-ai` route always needs `apiKeyEnv`, whose value it sends as `x-goog-api-key`.
270
- - **Gemini accepts four reasoning levels** — on `google-generative-ai`, pi-ai's Gemini implementation sends only `minimal`, `low`, `medium`, or `high`, compared without case, and fails a request whose `reasoningEfforts` value names anything else; the [Models page](../../client/ui-settings-models/README.md) offers only these levels for such a route. A request without a level, including `off`, sends pi-ai's disabled-thinking configuration, which models that cannot disable thinking, such as Gemini 2.5 Pro, may reject.
278
+ - **Gemini accepts four reasoning levels** — on `google-generative-ai`, pi-ai's Gemini implementation sends only `minimal`, `low`, `medium`, or `high`, compared without case, and fails a request whose `reasoningEfforts` value names anything else; the [Models page](../../client/ui-settings-models/README.md) offers only these levels for a route whose `api` names this protocol. A request without a level, including `off`, sends pi-ai's disabled-thinking configuration, which models that cannot disable thinking, such as Gemini 2.5 Pro, may reject.
271
279
  - **`GenerateOptions.stop` is unsupported** — pi-ai's common stream options cannot guarantee stop-sequence behavior across providers.
272
280
  - **Conversation update support comes only from the installed pi-ai catalog** — native system and tool updates require the catalog model’s mid-conversation compat flags, which profiles cannot set. Hand-declared routes and unflagged models receive later system text as user-role reminders and the complete current tool list at the start of each request.
273
281
  - **Images are accepted only in user and tool-result messages** — images in system, developer, or assistant history fail with `UNSUPPORTED_CONTENT` on both conversion paths.
package/README.zh.md CHANGED
@@ -46,7 +46,9 @@ kind: "package-reference"
46
46
  baseURL: https://proxy.example.com:8443
47
47
  reasoning: high
48
48
  requestImagePixelBudget: 4194304 # total pixels; 2048 by 2048 default
49
- requestImageMaxBytes: 1048576 # raw bytes before base64 expansion
49
+ requestImageMaxDimension: 3000 # override catalog width and height limits
50
+ requestImageMaxBytes: 1048576 # hard per-image cap before allocation
51
+ requestImageBudgetCount: 20 # fixed number of equal budget shares
50
52
  maxRequestImageBytes: 20971520 # accumulated base64 payload
51
53
  maxRequestImages: 50 # retained image occurrences
52
54
  imageOffloadCountQuantum: 10 # oldest images offloaded per count overflow
@@ -86,12 +88,18 @@ kind: "package-reference"
86
88
  | `defaultContextWindow` | `1,000,000` | 未描述模型的容量回退 |
87
89
  | `defaultMaxTokens` | `128,000` | 未描述模型的输出上限回退 |
88
90
  | `requestImagePixelBudget` | `4,194,304` | 每张确定性请求图片的总像素预算 |
89
- | `requestImageMaxBytes` | `1 MiB` | 每张请求图片在 base64 扩展前的编码字节目标 |
91
+ | `requestImageMaxDimension` | 目录中的宽高限制 | 每张请求图片的最大宽度和高度;显式配置会覆盖目录中的两个限制 |
92
+ | `requestImageMaxBytes` | 目录的 base64 上限换算为原始字节;否则为 `1 MiB` | 分摊前的单图硬上限;显式配置会覆盖目录上限 |
93
+ | `requestImageBudgetCount` | `20` | 图片总预算的固定分摊张数,与当前保留图片数量无关 |
90
94
  | `maxRequestImageBytes` | `20 MiB` | base64 图片载荷总上限,保留图片超过时请求以 `IMAGE_OFFLOAD_REQUIRED` 失败 |
91
95
  | `maxRequestImages` | `50` | 保留请求图片数量上限,保留图片超过时请求以 `IMAGE_OFFLOAD_REQUIRED` 失败。默认值取 Azure OpenAI 的 50 张上限;提供方接受更多图片的路由应调高 |
92
96
  | `imageOffloadCountQuantum` | `10`,不超过 `maxRequestImages` | 每次数量超限时省略的最老图片数 |
93
97
  | `retryPolicy` | normal,5 次重试 | 由 `dsh-llm-retry` 执行的提供方自有重试策略 |
94
98
 
99
+ 请求图片继承所选 pi-ai 模型的 `inputLimits.images.resize` 宽度、高度和 base64 字节上限。`requestImageMaxDimension` 用同一个值覆盖宽高,不能分别配置不同的宽度和高度上限。`requestImageMaxBytes` 按原始编码字节覆盖单图上限。最终硬上限为 `min(3 × floor(maxRequestImageBytes / (4 × requestImageBudgetCount)), requestImageMaxBytes 或目录上限或 1 MiB)`,其中目录上限通过 `3 × floor(catalogBytes / 4)` 换算。总预算须为每份预算至少提供 4 个 base64 字节。默认每张图分得 0.75 MiB,20 张达到该上限的图片最多占用 20 MiB base64 载荷。历史增长不会改变分摊张数;`maxRequestImages` 单独控制保留图片数量。目录缺少某个尺寸时,路由不限制该轴,总像素仍由 `requestImagePixelBudget` 控制。
100
+
101
+ pi 不暴露单独的软字节目标,共享编码器的 `imageTargetBytes` 等于最终 `maxImageBytes`。质量阶梯结束后仍超限的图片会继续缩小尺寸并重新编码,直到满足上限;无法满足的极小上限会明确报错。存储附件保持不变。图片描述和截图坐标使用最终编码尺寸。调大 `requestImageBudgetCount` 会减小每张图的分配额度,调小则增加额度;总预算仍按实际载荷执行。
102
+
95
103
  生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-llm-pi-ai)是每个受支持字段及其 JSDoc 的穷尽式真源。
96
104
 
97
105
  ### 登录提供方
@@ -142,7 +150,7 @@ Config 更新严格验证发生变化的 provider。初始加载将已存储的
142
150
 
143
151
  适配器建立在不可变快照与按操作解析之上。每个操作都会在第一次 `await` 前捕获整个快照——profile 加一个持有每条路由所构建 `Provider` 的 `createModels()` 集合——配置变更会构建新集合而非修改使用中的集合,因此在一个配置下开始的请求绝不会在另一个配置下结束。路由自己的凭据引用经 harness seam 解析,并以请求 `apiKey` 选项传入,pi-ai 将其视为优先级最高的 auth 覆盖——这正是明确失败引用语义的所在。该覆盖未覆盖的一切都经集合自身的 auth 到达 pi-ai:凭据存储持有登录写入、刷新轮换的记录(以 `llm-pi-ai/<provider id>` 寻址),auth context 回答提供方解析时提出的 ambient 问题。两者跨快照保持稳定,因此配置变更重建集合时不会忘记谁已登录。运行时 import 使用 pi-ai 的 provider、API 与 utility 入口;`src/models.ts` 提供本适配器所需的少量 model helper,而不会求值 pi-ai 聚合入口。
144
152
 
145
- 初始提示词文本和可用工具分别使用 pi-ai 的 `Context.systemPrompt` 与 `Context.tools`;后续系统消息和工具更新保留在 `Context.messages` 中。pi-ai 负责规范化这些字段,并应用所选协议的序列化规则。
153
+ 初始提示词文本和可用工具分别使用 pi-ai 的 `Context.systemPrompt` 与 `Context.tools`;后续系统消息和工具更新保留在 `Context.messages` 中。pi-ai 负责规范化这些字段,并应用所选协议的序列化规则。用户和工具文本块保持独立,由 pi-ai 序列化。系统文本(包括 developer 更新)在交给 pi-ai 前用空行拼接,因为 pi-ai 原本会用单个换行符拼接独立的系统文本块。初始提示词和 system-reminder 回退使用相同的分隔符。空文本块会被忽略。系统文本块会先去除首尾空白,因此仅含空白的块也会被忽略;用户和工具文本保留其空白。
146
154
 
147
155
  <a id="request-headers"></a>
148
156
  ### 请求头
@@ -223,7 +231,7 @@ Anthropic 可以将每个已签名 thinking 块绑定到生成它时的请求前
223
231
 
224
232
  #### 模型看到什么
225
233
 
226
- 所选目录模型会收到系统消息文本、对话历史、工具以及支持的采样字段。目录模型声明 `supportsMidConvoSystemMessages` 时,适配器按历史顺序保留后续系统消息。否则,适配器在传给 pi-ai 之前,将每条非空的后续系统消息转换为以 `<system-reminder>` 包裹的用户消息。包裹文本不会赋予系统角色优先级。单次调用的 `GenerateOptions.system` 放在初始历史提示词之前。重复的系统消息仍会重复发送;空系统消息会被跳过,不会丢弃之前的文本。工具更新能力选择共享的历史声明投影;pi-ai 接收初始可用工具,以及按开发者消息分组的新增和受支持的移除更新。当包含工具更新的 Anthropic 请求中所有投影后的声明均为延迟加载时,初始可用工具为一个占位工具 `DeferredToolPlaceholder`,其描述要求模型永不调用它;若被调用,会得到普通的未知工具结果。Anthropic 在更新消息中以内联方式接收后续工具定义。回放会保留工具调用命名空间,以支持动态加载的 Responses 工具。每张保留图片前都会有文本,注明其完整附件 id 与实际请求尺寸。当前执行文件系统可以映射附件提供方的宿主对象时,该文本还会携带只读规范化对象路径,并警告规范化或请求投影可能缩放或重新编码上传内容。日志中的图片省略决策选中的每个出现位置都会在替换文本中保留自己的身份与当前已解析访问方式,其规范化附件不会读取或变换。当保留的出现位置数量仍超过路由的 `maxRequestImages`,或其精确 base64 载荷超过 `maxRequestImageBytes` 时,调用以 `IMAGE_OFFLOAD_REQUIRED` 失败,由 `dsh-compaction-image-offload` 用 `image/offload` 事件记录所选位置并重试步骤。提供方原生回放元数据只在适配器针对历史内容校验通过后恢复。在 Anthropic Messages 路由上,如果回放响应的请求前缀自生成后发生变化(例如经过压缩),该响应会丢失 thinking 块;其文本和工具调用保留。 `imageRequestTarget(provider, model, image)` 向截图调用方提供与模型请求一致的图片尺寸和字节目标;不缩放图片的适配器保留归一化后的原图。
234
+ 所选目录模型会收到系统消息文本、对话历史、工具以及支持的采样字段。目录模型声明 `supportsMidConvoSystemMessages` 时,适配器按历史顺序保留后续系统消息。否则,适配器在传给 pi-ai 之前,将每条非空的后续系统消息转换为以 `<system-reminder>` 包裹的用户消息。包裹文本不会赋予系统角色优先级。单次调用的 `GenerateOptions.system` 放在初始历史提示词之前。重复的系统消息仍会重复发送;空系统消息会被跳过,不会丢弃之前的文本。工具更新能力选择共享的历史声明投影;pi-ai 接收初始可用工具,以及按开发者消息分组的新增和受支持的移除更新。当包含工具更新的 Anthropic 请求中所有投影后的声明均为延迟加载时,初始可用工具为一个占位工具 `DeferredToolPlaceholder`,其描述要求模型永不调用它;若被调用,会得到普通的未知工具结果。Anthropic 在更新消息中以内联方式接收后续工具定义。回放会保留工具调用命名空间,以支持动态加载的 Responses 工具。每张保留图片前都会有文本,注明其完整附件 id 与实际请求尺寸。当前执行文件系统可以映射附件提供方的宿主对象时,该文本还会携带只读规范化对象路径,并警告规范化或请求投影可能缩放或重新编码上传内容。日志中的图片省略决策选中的每个出现位置都会在替换文本中保留自己的身份与当前已解析访问方式,其规范化附件不会读取或变换。当保留的出现位置数量仍超过路由的 `maxRequestImages`,或其精确 base64 载荷超过 `maxRequestImageBytes` 时,调用以 `IMAGE_OFFLOAD_REQUIRED` 失败,由 `dsh-compaction-image-offload` 用 `image/offload` 事件记录所选位置并重试步骤。默认每张编码图片最多为 0.75 MiB,20 张达到上限的图片可以放入 20 MiB base64 总预算。较小的图片可以保留更多,但仍受数量上限限制。提供方原生回放元数据只在适配器针对历史内容校验通过后恢复。在 Anthropic Messages 路由上,如果回放响应的请求前缀自生成后发生变化(例如经过压缩),该响应会丢失 thinking 块;其文本和工具调用保留。 `imageRequestTarget(provider, model, image)` 向截图调用方提供最大尺寸和字节上限;`readImageRequest` 返回执行字节限制后的实际编码尺寸。
227
235
 
228
236
  #### Token 影响
229
237
 
@@ -231,7 +239,7 @@ Anthropic 可以将每个已签名 thinking 块绑定到生成它时的请求前
231
239
 
232
240
  #### KV Cache 影响
233
241
 
234
- 传给适配器的后续系统消息不会进入初始提示词,从而保留此前的请求前缀。这不改变 Agent loop 的提示词纳入行为;它仍在不支持原生系统更新的路由上合并更新。转换保持逻辑请求顺序,图片句柄与卸载占位符则会添加模型可见文本。即使附件身份与请求字节保持稳定,执行世界路径变化也会改写历史句柄,并可能从该图片起阻止复用。更换适配器实例、提供方、模型或其他上游 token 具有相同的后缀影响。省略过期的 Anthropic thinking 发生在前缀变化之后,而该变化已在变化的消息处结束复用。第一个省略无摘要记录的 thinking 的请求会在第一条此类消息处结束复用,且仅发生一次。一次省略决策会把较早图片换成占位文本,因此复用在该消息处结束;省略永不回退,在下一次决策前前缀保持稳定。数量超限时一次省略 `imageOffloadCountQuantum` 张图片,因此饱和路由每新增这么多张图片才让复用在最老的保留图片处结束一次。
242
+ 传给适配器的后续系统消息不会进入初始提示词,从而保留此前的请求前缀。这不改变 Agent loop 的提示词纳入行为;它仍在不支持原生系统更新的路由上合并更新。转换保持逻辑请求顺序,图片句柄与卸载占位符则会添加模型可见文本。即使附件身份与请求字节保持稳定,执行世界路径变化也会改写历史句柄,并可能从该图片起阻止复用。更换适配器实例、提供方、模型或其他上游 token 具有相同的后缀影响。省略过期的 Anthropic thinking 发生在前缀变化之后,而该变化已在变化的消息处结束复用。第一个省略无摘要记录的 thinking 的请求会在第一条此类消息处结束复用,且仅发生一次。一次省略决策会把较早图片换成占位文本,因此复用在该消息处结束;省略永不回退,在下一次决策前前缀保持稳定。数量超限时一次省略 `imageOffloadCountQuantum` 张图片,因此饱和路由每新增这么多张图片才让复用在最老的保留图片处结束一次。 修改字节预算配置可能缩放历史请求图片并影响前缀复用;仅新增图片不会改变单图分配额度。
235
243
 
236
244
  ### 提供方响应
237
245
 
@@ -267,7 +275,7 @@ pi-ai 事件变成 harness 的推理、文本、工具调用、用量与 finish
267
275
  - **目录外模型需要明确的协议**——目录路由保留每个模型的协议,包括 `azure` 下的两种 Azure API。混合协议目录中不存在的模型需要显式设置路由级 `api`;该设置覆盖路由上的所有模型,且必须属于受支持的自定义协议。Azure 部署名称应通过 `AZURE_OPENAI_DEPLOYMENT_NAME_MAP` 设置,模型 ID 保持为目录中的 ID。
268
276
  - **模态声明不受校验**——声明 `image` 而其网关不支持的模型会在提示词准入后被提供方拒绝。持久图片仍留在历史中,同一误声明模型可能再次失败;切换到纯文本模型仍然可行,因为共享 LLM 运行时会针对该请求把图片引用投影为稳定文本。
269
277
  - **未认证路由取决于其协议**——不点名凭据的路由解析为已配置但无密钥,但 pi-ai 的 OpenAI 兼容实现仍要求 API 密钥或 `Authorization` 标头,因此无密钥本地服务器需要由 `apiKeyEnv` 引用或 `headers` 中的 `Authorization` 条目提供的占位凭据。pi-ai 的 Gemini 实现会拒绝没有 API 密钥的请求,因此 `google-generative-ai` 路由始终需要 `apiKeyEnv`,其值以 `x-goog-api-key` 发送。
270
- - **Gemini 只接受四个推理等级**——在 `google-generative-ai` 上,pi-ai 的 Gemini 实现只发送 `minimal`、`low`、`medium` 或 `high`(不区分大小写),`reasoningEfforts` 的值为其他名称时请求失败;[模型页](../../client/ui-settings-models/README.zh.md)只为此类路由提供这些档位。不带等级的请求(包括 `off`)会发送 pi-ai 的关闭思考配置,无法关闭思考的模型(例如 Gemini 2.5 Pro)可能拒绝该请求。
278
+ - **Gemini 只接受四个推理等级**——在 `google-generative-ai` 上,pi-ai 的 Gemini 实现只发送 `minimal`、`low`、`medium` 或 `high`(不区分大小写),`reasoningEfforts` 的值为其他名称时请求失败;[模型页](../../client/ui-settings-models/README.zh.md)只为 `api` 指定该协议的路由提供这些档位。不带等级的请求(包括 `off`)会发送 pi-ai 的关闭思考配置,无法关闭思考的模型(例如 Gemini 2.5 Pro)可能拒绝该请求。
271
279
  - **不支持 `GenerateOptions.stop`**——pi-ai 的通用流式选项无法跨提供方保证停止序列行为。
272
280
  - **对话更新支持只来自已安装的 pi-ai 目录**——原生系统与工具更新需要目录模型的对话中 compat 标志,profile 不能设置这些标志。手工声明的路由与未标记的模型会以用户角色提醒接收后续系统文本,并在每次请求开头接收完整的当前工具列表。
273
281
  - **图片只在 user 与工具结果消息中被接受**——system、developer 或 assistant 历史中的图片在两条转换路径上都会以 `UNSUPPORTED_CONTENT` 失败。
package/lib/index.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import { launchEnvironmentOf } from "@deepseek-ai/dsh-launch-environment";
2
- import { CONTEXT_WINDOW_EXCEEDED_CODE, EMPTY_RESPONSE_CODE, IMAGE_OFFLOAD_REQUIRED_CODE, INVALID_CREDENTIAL_CODE, LlmAdapter, LlmError, QUOTA_EXCEEDED_CODE, ReasoningEffortId, RetryPolicySchema, assertUsableApiKey, attributionHeaders, contentHasImage, isContextWindowExceededError, isQuotaExceededError, normalizeApiKey, offloadedImageText, projectOffloadedImages, requestImageHandleText, requiredImageOffload, resolveImageAttachmentAccess, resolveRetryPolicy } from "@deepseek-ai/dsh-llm";
2
+ import { credentialKey, credentialKeyId, credentialKeyScope, credentialRef, isCredentialKeySegment, isCredentialRefName, normalizeApiKey } from "@deepseek-ai/dsh-credentials";
3
+ import { CONTEXT_WINDOW_EXCEEDED_CODE, EMPTY_RESPONSE_CODE, INVALID_CREDENTIAL_CODE, LlmAdapter, LlmError, QUOTA_EXCEEDED_CODE, RetryPolicySchema, attributionHeaders, contentHasImage, isContextWindowExceededError, isQuotaExceededError, offloadedImageText, projectOffloadedImages, requestImageHandleText, resolveImageAttachmentAccess, resolveRetryPolicy } from "@deepseek-ai/dsh-llm";
3
4
  import { deepEqualJson } from "@deepseek-ai/dsh-util-values";
4
- import { MAX_TIMER_DELAY_MS, idleWatchdog, timeoutOf } from "@deepseek-ai/dsh-timeout";
5
5
  import { brandString } from "@deepseek-ai/dsh-brand";
6
+ import { MAX_TIMER_DELAY_MS, idleWatchdog, timeoutOf } from "@deepseek-ai/dsh-timeout";
7
+ import { extractTextContent, requestImageBudgetFailure, uniqueRequestImageRefs } from "@deepseek-ai/dsh-llm/message";
6
8
  import { requestImageDimensions } from "@deepseek-ai/dsh-attachment";
7
9
  import z from "@deepseek-ai/schemastery";
8
- import { credentialKey, credentialKeyId, credentialKeyScope, credentialRef, isCredentialKeySegment, isCredentialRefName } from "@deepseek-ai/dsh-credentials";
9
10
  import { builtinModels, builtinProviders, getAllBuiltinModels, getBuiltinModels } from "@earendil-works/pi-ai/providers/all";
10
11
  import { anthropicMessagesApi } from "@earendil-works/pi-ai/api/anthropic-messages.lazy";
11
12
  import { googleGenerativeAIApi } from "@earendil-works/pi-ai/api/google-generative-ai.lazy";
@@ -28,10 +29,11 @@ import { resolve } from "node:path";
28
29
  */
29
30
  /** Parse tool-call argument JSON; tolerate model malformations with {}. */
30
31
  function parseArguments(raw) {
32
+ let parsed;
31
33
  try {
32
- const parsed = JSON.parse(raw);
33
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) return parsed;
34
- } catch {}
34
+ parsed = JSON.parse(raw);
35
+ } catch (_malformedArguments) {}
36
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) return parsed;
35
37
  return {};
36
38
  }
37
39
  /** Construct the zero usage value required by historical pi-ai messages. */
@@ -951,19 +953,14 @@ function buildProvider(spec) {
951
953
  /** Default maximum idle interval while an adapter stream read is outstanding. */
952
954
  const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 3e5;
953
955
  /**
954
- * Default request-level bound on base64-encoded image payload. Every image in
955
- * history is re-encoded into every request body, so an unbounded conversation
956
- * eventually exceeds a provider or gateway request-size cap and the session
957
- * can never complete another request. The 20MiB default admits fifteen 1MiB
958
- * request versions after base64 expansion and reserves request capacity for
959
- * system prompts, history, tools, and JSON.
960
- * Deployments behind stricter gateways lower it per route.
956
+ * Default cap on aggregate base64 image payload, excluding text, tools, and
957
+ * JSON overhead. Retained image count depends on actual encoded sizes;
958
+ * per-image catalog targets do not raise this cap. Deployments keep it below
959
+ * the gateway's complete request-size limit to leave room for other content.
961
960
  */
962
961
  const DEFAULT_MAX_REQUEST_IMAGE_BYTES = 20 * 1024 * 1024;
963
962
  /** Default total-pixel budget preserves the complete 2048px normalized attachment. */
964
963
  const DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET = 2048 * 2048;
965
- /** Default raw encoded-byte target before inline base64 expansion; the smallest quality-ladder output is used when no quality fits. */
966
- const DEFAULT_REQUEST_IMAGE_MAX_BYTES = 1024 * 1024;
967
964
  /** Context capacity assumed for a model neither configuration nor the catalog sizes. */
968
965
  const DEFAULT_CONTEXT_WINDOW = 1e6;
969
966
  /** Output capability assumed for a model neither configuration nor the catalog sizes. */
@@ -1086,8 +1083,10 @@ const profile = z.object({
1086
1083
  maxRequestImageBytes: z.number().step(1).min(1).default(DEFAULT_MAX_REQUEST_IMAGE_BYTES),
1087
1084
  maxRequestImages: z.number().step(1).min(1).default(50),
1088
1085
  imageOffloadCountQuantum: z.number().step(1).min(1),
1086
+ requestImageBudgetCount: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(20),
1089
1087
  requestImagePixelBudget: z.number().step(1).min(1).default(DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET),
1090
- requestImageMaxBytes: z.number().step(1).min(1).default(DEFAULT_REQUEST_IMAGE_MAX_BYTES),
1088
+ requestImageMaxDimension: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER),
1089
+ requestImageMaxBytes: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER),
1091
1090
  retryPolicy: RetryPolicySchema
1092
1091
  });
1093
1092
  /** Runtime schema for {@link Config}. */
@@ -1131,6 +1130,8 @@ function resolveProfiles(providers, validation = "strict") {
1131
1130
  const resolved = /* @__PURE__ */ new Map();
1132
1131
  for (const [provider, source] of entries) {
1133
1132
  rejectRemovedFields(provider, source);
1133
+ if ("imageTargetBytes" in source) throw new Error("llm-pi-ai: imageTargetBytes is not configurable; pi uses the effective per-image cap as the target");
1134
+ if ("maxImageBytes" in source) throw new Error(`llm-pi-ai: provider "${provider}" must use requestImageMaxBytes to set the per-image cap; maxImageBytes is internal`);
1134
1135
  if (provider.length === 0) throw new Error("llm-pi-ai: provider names must be non-empty");
1135
1136
  if (source.baseURL !== void 0 && source.baseURL.length === 0) throw new Error(`llm-pi-ai: provider "${provider}" has an empty baseURL`);
1136
1137
  if (source.displayName !== void 0 && source.displayName.length === 0) throw new Error(`llm-pi-ai: provider "${provider}" has an empty displayName`);
@@ -1138,15 +1139,20 @@ function resolveProfiles(providers, validation = "strict") {
1138
1139
  const streamIdleTimeoutMs = source.streamIdleTimeoutMs ?? 3e5;
1139
1140
  if (!Number.isFinite(streamIdleTimeoutMs) || streamIdleTimeoutMs <= 0 || streamIdleTimeoutMs > MAX_TIMER_DELAY_MS) throw new Error(`llm-pi-ai: provider "${provider}" streamIdleTimeoutMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);
1140
1141
  const maxRequestImageBytes = source.maxRequestImageBytes ?? 20971520;
1141
- if (!Number.isInteger(maxRequestImageBytes) || maxRequestImageBytes <= 0) throw new Error(`llm-pi-ai: provider "${provider}" maxRequestImageBytes must be a positive integer`);
1142
+ if (!Number.isSafeInteger(maxRequestImageBytes) || maxRequestImageBytes <= 0) throw new Error(`llm-pi-ai: provider "${provider}" maxRequestImageBytes must be a positive integer`);
1143
+ const requestImageBudgetCount = source.requestImageBudgetCount ?? 20;
1144
+ if (!Number.isSafeInteger(requestImageBudgetCount) || requestImageBudgetCount <= 0) throw new Error(`llm-pi-ai: provider "${provider}" requestImageBudgetCount must be a positive safe integer`);
1145
+ if (requestImageBudgetCount > Math.floor(maxRequestImageBytes / 4)) throw new Error(`llm-pi-ai: provider "${provider}" maxRequestImageBytes must allow four base64 bytes per requestImageBudgetCount`);
1142
1146
  const maxRequestImages = source.maxRequestImages ?? 50;
1143
1147
  if (!Number.isSafeInteger(maxRequestImages) || maxRequestImages <= 0) throw new Error(`llm-pi-ai: provider "${provider}" maxRequestImages must be a positive safe integer`);
1144
1148
  const imageOffloadCountQuantum = source.imageOffloadCountQuantum ?? Math.min(10, maxRequestImages);
1145
1149
  if (!Number.isSafeInteger(imageOffloadCountQuantum) || imageOffloadCountQuantum <= 0 || imageOffloadCountQuantum > maxRequestImages) throw new Error(`llm-pi-ai: provider "${provider}" imageOffloadCountQuantum must be a positive safe integer no greater than maxRequestImages`);
1146
1150
  const requestImagePixelBudget = source.requestImagePixelBudget ?? 4194304;
1147
1151
  if (!Number.isSafeInteger(requestImagePixelBudget) || requestImagePixelBudget <= 0) throw new Error(`llm-pi-ai: provider "${provider}" requestImagePixelBudget must be a positive safe integer`);
1148
- const requestImageMaxBytes = source.requestImageMaxBytes ?? 1048576;
1149
- if (!Number.isSafeInteger(requestImageMaxBytes) || requestImageMaxBytes <= 0) throw new Error(`llm-pi-ai: provider "${provider}" requestImageMaxBytes must be a positive safe integer`);
1152
+ for (const field of ["requestImageMaxDimension", "requestImageMaxBytes"]) {
1153
+ const value = source[field];
1154
+ if (value !== void 0 && (!Number.isSafeInteger(value) || value <= 0)) throw new Error(`llm-pi-ai: provider "${provider}" ${field} must be a positive safe integer`);
1155
+ }
1150
1156
  const defaultInput = [...source.defaultInput ?? DEFAULT_INPUT];
1151
1157
  if (defaultInput.length === 0) throw new Error(`llm-pi-ai: provider "${provider}" defaultInput must name at least one modality`);
1152
1158
  const displayName = source.displayName ?? provider;
@@ -1178,9 +1184,10 @@ function resolveProfiles(providers, validation = "strict") {
1178
1184
  if (validation === "strict" || !(error instanceof PiAiCatalogError)) throw error;
1179
1185
  catalogError ??= error.message;
1180
1186
  }
1181
- const { apiKeyEnv, retryPolicy, models: _models, displayName: _displayName, ...rest } = source;
1187
+ const { apiKeyEnv, retryPolicy, models: _models, displayName: _displayName, requestImageMaxBytes, ...rest } = source;
1182
1188
  resolved.set(provider, {
1183
1189
  ...rest,
1190
+ ...requestImageMaxBytes === void 0 ? {} : { maxImageBytes: requestImageMaxBytes },
1184
1191
  provider,
1185
1192
  displayName,
1186
1193
  ...apiKeyEnv === void 0 ? {} : { apiKeyEnv: credentialRef(apiKeyEnv) },
@@ -1189,7 +1196,7 @@ function resolveProfiles(providers, validation = "strict") {
1189
1196
  maxRequestImages,
1190
1197
  imageOffloadCountQuantum,
1191
1198
  requestImagePixelBudget,
1192
- requestImageMaxBytes,
1199
+ requestImageBudgetCount,
1193
1200
  retryPolicy: resolveRetryPolicy(retryPolicy, `llm-pi-ai: provider "${provider}" retryPolicy`),
1194
1201
  ...rest.headers === void 0 ? {} : { headers: { ...rest.headers } },
1195
1202
  ...rest.thinkingBudgets === void 0 ? {} : { thinkingBudgets: { ...rest.thinkingBudgets } },
@@ -1208,9 +1215,15 @@ function resolveProfiles(providers, validation = "strict") {
1208
1215
  *
1209
1216
  * @module dsh-llm-pi-ai/context
1210
1217
  */
1211
- /** Join the text blocks of a harness message. */
1212
- function flattenText(message) {
1213
- return message.content.filter((block) => block.type === "text").map((block) => block.text).join("");
1218
+ function textBlocks(content) {
1219
+ return content.filter((block) => block.type === "text" && block.text.length > 0);
1220
+ }
1221
+ /** Pre-join system text with blank lines because pi-ai joins separate blocks with single newlines. */
1222
+ function systemText(content) {
1223
+ return extractTextContent(content, {
1224
+ separator: "\n\n",
1225
+ trim: true
1226
+ });
1214
1227
  }
1215
1228
  /** Recover the pi-ai toolResult message for one harness tool-role message. */
1216
1229
  function toolResultOf(message, toolNames, content) {
@@ -1218,10 +1231,10 @@ function toolResultOf(message, toolNames, content) {
1218
1231
  role: "toolResult",
1219
1232
  toolCallId: message.toolCallId,
1220
1233
  toolName: toolNames.get(message.toolCallId) ?? "unknown",
1221
- content: typeof content === "string" ? [{
1234
+ content: content.length > 0 ? content : [{
1222
1235
  type: "text",
1223
- text: content || "(no output)"
1224
- }] : content,
1236
+ text: "(no output)"
1237
+ }],
1225
1238
  isError: message.isError ?? false,
1226
1239
  timestamp: 0
1227
1240
  };
@@ -1258,23 +1271,8 @@ function userContent(blocks, requestImages, resolveImageAccess) {
1258
1271
  }
1259
1272
  default: break;
1260
1273
  }
1261
- if (content.every((block) => block.type === "text")) return content.map((block) => block.text).join("");
1262
1274
  return content;
1263
1275
  }
1264
- function collectImageRefs(blocks, refs) {
1265
- for (const block of blocks) if (block.type === "image") {
1266
- if (block.offloaded !== true) refs.set(block.attachment.attachmentId, block.attachment);
1267
- }
1268
- }
1269
- async function prepareRequestImages(messages, attachments, budget, signal) {
1270
- const refs = /* @__PURE__ */ new Map();
1271
- for (const message of messages) collectImageRefs(message.content, refs);
1272
- const orderedRefs = [...refs.values()];
1273
- const prepared = await Promise.all(orderedRefs.map((ref) => attachments.readImageRequest(ref, requestImageTarget(ref, budget), signal)));
1274
- const versions = /* @__PURE__ */ new Map();
1275
- for (const [index, ref] of orderedRefs.entries()) versions.set(ref.attachmentId, prepared[index]);
1276
- return versions;
1277
- }
1278
1276
  /** Convert a projected declaration without its harness-owned activation marker. */
1279
1277
  function piTool(tool) {
1280
1278
  return {
@@ -1292,7 +1290,7 @@ function splitSystemPrompt(options) {
1292
1290
  let end = 0;
1293
1291
  for (const message of options.messages) {
1294
1292
  if (message.role !== "system") break;
1295
- text.push(flattenText(message));
1293
+ text.push(systemText(message.content));
1296
1294
  end++;
1297
1295
  }
1298
1296
  return {
@@ -1311,16 +1309,11 @@ function piContext(systemPrompt, options, messages) {
1311
1309
  }
1312
1310
  /** Keep one developer event in one system update, resolving its projected tool declarations. */
1313
1311
  function appendDeveloper(message, options, messages) {
1314
- const content = [];
1312
+ const content = systemText(message.content);
1315
1313
  const toolsAdded = [];
1316
1314
  const toolsRemoved = [];
1317
1315
  for (const block of message.content) switch (block.type) {
1318
- case "text":
1319
- if (block.text.length > 0) content.push({
1320
- type: "text",
1321
- text: block.text
1322
- });
1323
- break;
1316
+ case "text": break;
1324
1317
  case "tool-addition": {
1325
1318
  const tool = options.tools?.find((tool) => tool.name === block.toolName);
1326
1319
  if (tool === void 0) throw new LlmError(`pi-ai tool update references undeclared tool "${block.toolName}"`, "INVALID_REQUEST");
@@ -1353,7 +1346,7 @@ function appendSharedHistory(message, options, messages, toolNames, supportsMidC
1353
1346
  return true;
1354
1347
  }
1355
1348
  if (message.role === "system") {
1356
- const content = flattenText(message);
1349
+ const content = systemText(message.content);
1357
1350
  if (content.length > 0) if (supportsMidConvoSystemMessages) messages.push({
1358
1351
  role: "system",
1359
1352
  content,
@@ -1384,12 +1377,12 @@ function textOnlyContext(options, supportsMidConvoSystemMessages, onReplayDegrad
1384
1377
  if (contentHasImage(message.content)) throw new LlmError("pi-ai image conversion requires the durable attachment service", "UNSUPPORTED_CONTENT");
1385
1378
  if (appendSharedHistory(message, options, messages, toolNames, supportsMidConvoSystemMessages, onReplayDegrade, prefixDigests)) continue;
1386
1379
  if (message.role === "tool") {
1387
- messages.push(toolResultOf(message, toolNames, flattenText(message)));
1380
+ messages.push(toolResultOf(message, toolNames, textBlocks(message.content)));
1388
1381
  continue;
1389
1382
  }
1390
1383
  messages.push({
1391
1384
  role: "user",
1392
- content: flattenText(message),
1385
+ content: textBlocks(message.content),
1393
1386
  timestamp: 0
1394
1387
  });
1395
1388
  }
@@ -1403,8 +1396,9 @@ function textOnlyContext(options, supportsMidConvoSystemMessages, onReplayDegrad
1403
1396
  */
1404
1397
  function requestImageTarget(ref, budget) {
1405
1398
  return {
1406
- ...requestImageDimensions(ref.width, ref.height, budget.maxPixels),
1407
- maxBytes: budget.maxBytes
1399
+ ...requestImageDimensions(ref.width, ref.height, budget.maxPixels, budget.maxWidth, budget.maxHeight),
1400
+ maxImageBytes: budget.maxImageBytes,
1401
+ imageTargetBytes: budget.maxImageBytes
1408
1402
  };
1409
1403
  }
1410
1404
  function toPiContext(options, images, onReplayDegrade, supportsMidConvoSystemMessages = false, prefixDigests) {
@@ -1414,18 +1408,22 @@ async function toPiContextWithImages(options, images, supportsMidConvoSystemMess
1414
1408
  const { attachments, resolveImageAccess, maxRequestImageBytes, maxRequestImages, imageOffloadCountQuantum } = images;
1415
1409
  const requestImagePolicy = images.requestImagePolicy ?? {
1416
1410
  maxPixels: 4194304,
1417
- maxBytes: 1048576
1411
+ maxImageBytes: 1048576
1418
1412
  };
1419
1413
  assertSupportedHistory(options.messages);
1420
1414
  const split = splitSystemPrompt(options);
1421
- const requestImages = await prepareRequestImages(split.messages, attachments, requestImagePolicy, options.signal);
1422
- const offloadImages = requiredImageOffload(split.messages, {
1415
+ const refs = uniqueRequestImageRefs(split.messages);
1416
+ const requestImages = new Map(await Promise.all(refs.map(async (ref) => {
1417
+ const version = await attachments.readImageRequest(ref, requestImageTarget(ref, requestImagePolicy), options.signal);
1418
+ return [ref.attachmentId, version];
1419
+ })));
1420
+ const failure = requestImageBudgetFailure(split.messages, requestImages, {
1423
1421
  representation: "base64",
1424
1422
  ...maxRequestImageBytes === void 0 ? {} : { maxBytes: maxRequestImageBytes },
1425
1423
  ...maxRequestImages === void 0 ? {} : { maxImages: maxRequestImages },
1426
1424
  ...imageOffloadCountQuantum === void 0 ? {} : { countQuantum: imageOffloadCountQuantum }
1427
- }, (block) => requestImages.get(block.attachment.attachmentId).bytes);
1428
- if (offloadImages > 0) throw new LlmError(`pi-ai request images exceed the route image budget; ${offloadImages} more oldest occurrence(s) must be offloaded.`, IMAGE_OFFLOAD_REQUIRED_CODE, { offloadImages });
1425
+ }, "pi-ai request images exceed the route image budget");
1426
+ if (failure !== void 0) throw LlmError.fromFailure(failure);
1429
1427
  const exactMessages = projectOffloadedImages(split.messages, (ref) => offloadedImageText(ref, resolveImageAccess(ref)));
1430
1428
  const toolNames = /* @__PURE__ */ new Map();
1431
1429
  const messages = [];
@@ -1445,6 +1443,30 @@ async function toPiContextWithImages(options, images, supportsMidConvoSystemMess
1445
1443
  return piContext(split.systemPrompt, options, messages);
1446
1444
  }
1447
1445
  //#endregion
1446
+ //#region lib/types/image-policy.js
1447
+ /** Resolve pi-ai image resize metadata and route-owned overrides. */
1448
+ /**
1449
+ * Resolve one model's image dimensions and hard raw encoded-byte limit.
1450
+ * @param model - selected pi-ai catalog model.
1451
+ * @param profile - validated route with optional overrides.
1452
+ * @returns resize limits shared by request serialization and screenshot coordinates.
1453
+ */
1454
+ function resolveImageRequestBudget(model, profile) {
1455
+ const resize = model.inputLimits?.images?.resize;
1456
+ const maxWidth = profile.requestImageMaxDimension ?? resize?.maxWidth;
1457
+ const maxHeight = profile.requestImageMaxDimension ?? resize?.maxHeight;
1458
+ const catalogBytes = resize?.maxBytes === void 0 ? void 0 : Math.floor(resize.maxBytes / 4) * 3;
1459
+ const allocatedBytes = Math.floor(profile.maxRequestImageBytes / profile.requestImageBudgetCount / 4) * 3;
1460
+ const maxImageBytes = Math.min(allocatedBytes, profile.maxImageBytes ?? catalogBytes ?? 1048576);
1461
+ if (maxImageBytes < 1) throw new LlmError("pi-ai image byte budget cannot encode a nonempty base64 image; increase the image byte limits.", "INVALID_CONFIG");
1462
+ return {
1463
+ maxPixels: profile.requestImagePixelBudget,
1464
+ maxImageBytes,
1465
+ ...maxWidth === void 0 ? {} : { maxWidth },
1466
+ ...maxHeight === void 0 ? {} : { maxHeight }
1467
+ };
1468
+ }
1469
+ //#endregion
1448
1470
  //#region lib/types/stream.js
1449
1471
  /**
1450
1472
  * pi-ai assistant event translation into the Harness streaming protocol.
@@ -1940,10 +1962,10 @@ function reasoningInfo(model, defaultLevel) {
1940
1962
  if (!model.reasoning) return {};
1941
1963
  return { reasoning: {
1942
1964
  efforts: getSupportedThinkingLevels(model).map((level) => ({
1943
- id: ReasoningEffortId(level),
1965
+ id: brandString(level),
1944
1966
  name: `${level.charAt(0).toUpperCase()}${level.slice(1)}`
1945
1967
  })),
1946
- ...defaultLevel === void 0 ? {} : { defaultEffort: ReasoningEffortId(defaultLevel) }
1968
+ ...defaultLevel === void 0 ? {} : { defaultEffort: brandString(defaultLevel) }
1947
1969
  } };
1948
1970
  }
1949
1971
  /** Native header TypeErrors can echo credentials; other plugin errors own their public message. */
@@ -1984,12 +2006,7 @@ var PiAiAdapter = class extends LlmAdapter {
1984
2006
  }
1985
2007
  imageRequestTarget(provider, model, image) {
1986
2008
  const snapshot = this.current();
1987
- this.modelOf(snapshot, provider, model);
1988
- const profile = this.profileOf(snapshot, provider);
1989
- return requestImageTarget(image, {
1990
- maxPixels: profile.requestImagePixelBudget,
1991
- maxBytes: profile.requestImageMaxBytes
1992
- });
2009
+ return requestImageTarget(image, resolveImageRequestBudget(this.modelOf(snapshot, provider, model), this.profileOf(snapshot, provider)));
1993
2010
  }
1994
2011
  /**
1995
2012
  * The snapshot for the current profiles. Resolution memoizes its result, so
@@ -2126,10 +2143,7 @@ var PiAiAdapter = class extends LlmAdapter {
2126
2143
  maxRequestImageBytes: profile.maxRequestImageBytes,
2127
2144
  maxRequestImages: profile.maxRequestImages,
2128
2145
  imageOffloadCountQuantum: profile.imageOffloadCountQuantum,
2129
- requestImagePolicy: {
2130
- maxPixels: profile.requestImagePixelBudget,
2131
- maxBytes: profile.requestImageMaxBytes
2132
- }
2146
+ requestImagePolicy: resolveImageRequestBudget(model, profile)
2133
2147
  }, onReplayDegrade, updates.systemPromptUpdate === "in-history", prefixDigests);
2134
2148
  const manualThinking = model.reasoning && reasoning !== void 0 && reasoning !== "off" && model.compat?.forceAdaptiveThinking !== true;
2135
2149
  const { context, digest } = bindThinkingToPrefix(converted, model.api, prefixDigests, manualThinking, (count) => {
@@ -3092,7 +3106,14 @@ function apply(ctx, config) {
3092
3106
  if (ref === void 0) return void 0;
3093
3107
  const credentials = ctx.get("credentials");
3094
3108
  const hit = credentials !== void 0 ? (await credentials.resolve(ref))?.value : launchEnvironmentOf(ctx).get(ref)?.value;
3095
- if (hit !== void 0 && hit.length > 0) return assertUsableApiKey(hit, "llm-pi-ai", ref);
3109
+ if (hit !== void 0 && hit.length > 0) {
3110
+ const checked = normalizeApiKey(hit);
3111
+ if (checked.ok) return checked.value;
3112
+ throw new LlmError(`llm-pi-ai: the API key resolved from ${ref} ${{
3113
+ empty: `is blank; set ${ref} to the raw key (the web Models page writes it) or export it in the launching environment`,
3114
+ illegalCharacters: `contains characters no HTTP header can carry; set ${ref} to the raw key alone (the web Models page writes it)`
3115
+ }[checked.reason]}`, INVALID_CREDENTIAL_CODE);
3116
+ }
3096
3117
  throw new LlmError(`llm-pi-ai: no credential for provider route "${provider}"; its profile resolves ${ref}, which is not set — store ${ref} through the credentials service (the web Models page writes it) or export it, and remove apiKeyEnv only if this provider should authenticate from pi-ai's own environment discovery`, "MISSING_CREDENTIAL");
3097
3118
  };
3098
3119
  const auth = {
@@ -3167,4 +3188,4 @@ function apply(ctx, config) {
3167
3188
  });
3168
3189
  }
3169
3190
  //#endregion
3170
- export { Config, PiAiAdapter, apply, inject, name, recordKeyFor, supportedProtocols };
3191
+ export { Config, PiAiAdapter, apply, inject, name, supportedProtocols };
@@ -1 +1 @@
1
- {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../../src/adapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,KAAK,EAEV,WAAW,EACX,eAAe,EAOhB,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAGL,UAAU,EAGX,MAAM,sBAAsB,CAAA;AAC7B,OAAO,KAAK,EACV,eAAe,EACf,qBAAqB,EACrB,YAAY,EACZ,eAAe,EACf,oBAAoB,EACpB,mBAAmB,EAEnB,mBAAmB,EACnB,WAAW,EAEZ,MAAM,sBAAsB,CAAA;AAC7B,OAAO,KAAK,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAA;AAEtF,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAA;AAM9D,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAA;AAoB1D,6FAA6F;AAC7F,MAAM,WAAW,kBAAkB;IACjC,+EAA+E;IAC/E,QAAQ,EAAE,MAAM,WAAW,CAAC,MAAM,EAAE,2BAA2B,CAAC,CAAA;IAChE;;;;;;;;OAQG;IACH,aAAa,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,2BAA2B,KAAK,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAA;IACtG;;;;;;;OAOG;IACH,IAAI,EAAE,iBAAiB,CAAA;IACvB;;;;;;;;;;OAUG;IACH,cAAc,CAAC,EAAE,CAAC,OAAO,EAAE,wBAAwB,EAAE,OAAO,EAAE,OAAO,KAAK,OAAO,CAAA;IACjF,uEAAuE;IACvE,kBAAkB,CAAC,EAAE,MAAM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