@deepseek-ai/dsh-llm-pi-ai 0.2.1-rc.5 → 0.2.2-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.i18n.yaml +17 -14
- package/README.md +21 -8
- package/README.zh.md +21 -8
- package/lib/index.js +79 -36
- package/lib/types/adapter.d.ts +13 -0
- package/lib/types/catalog.d.ts +1 -0
- package/lib/types/config.d.ts +45 -8
- package/lib/types/context.d.ts +12 -5
- package/lib/types/index.d.ts +20 -0
- package/lib/types/stream.d.ts +3 -1
- package/lib/types/types.d.ts +8 -0
- package/locale/de.json +6 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/pt.json +6 -0
- package/locale/ru.json +6 -0
- package/package.json +31 -27
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:
|
|
25
|
-
zh:
|
|
24
|
+
en: 12d3d1506c72ac8b
|
|
25
|
+
zh: d966efb555110713
|
|
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,11 @@
|
|
|
45
45
|
en: 1598ac8a8bb9b6bf
|
|
46
46
|
zh: fdd089c5ae7722cd
|
|
47
47
|
/deepseek-ai-dsh-llm-pi-ai/understand-the-implementation/design-philosophy:
|
|
48
|
-
en:
|
|
49
|
-
zh:
|
|
48
|
+
en: db1ac8ccca2d858b
|
|
49
|
+
zh: 1d7cd4153aad22b0
|
|
50
|
+
/deepseek-ai-dsh-llm-pi-ai/understand-the-implementation/request-headers:
|
|
51
|
+
en: 615ca9834bf6544f
|
|
52
|
+
zh: 2d70b548f99000d1
|
|
50
53
|
/deepseek-ai-dsh-llm-pi-ai/understand-the-implementation/source-map:
|
|
51
54
|
en: 64912b8a3a336419
|
|
52
55
|
zh: 33a245969b4194f6
|
|
@@ -57,8 +60,8 @@
|
|
|
57
60
|
en: 477d277e9ac35c8f
|
|
58
61
|
zh: 96870ca333fb6510
|
|
59
62
|
/deepseek-ai-dsh-llm-pi-ai/understand-the-implementation/replay-and-vocabulary:
|
|
60
|
-
en:
|
|
61
|
-
zh:
|
|
63
|
+
en: e64173763fdbcfae
|
|
64
|
+
zh: 73ed2c2af54b62f6
|
|
62
65
|
/deepseek-ai-dsh-llm-pi-ai/further-exploration:
|
|
63
66
|
en: a2a2ccdeae59d408
|
|
64
67
|
zh: c47ee091aa90ad91
|
|
@@ -69,20 +72,20 @@
|
|
|
69
72
|
en: e7348db3f7115960
|
|
70
73
|
zh: 5fd5fb09d7d09982
|
|
71
74
|
/deepseek-ai-dsh-llm-pi-ai/model-experience/provider-request-through-pi-ai/what-the-model-sees:
|
|
72
|
-
en:
|
|
73
|
-
zh:
|
|
75
|
+
en: 06f40c26b79df3cb
|
|
76
|
+
zh: 78676d41999b1ef2
|
|
74
77
|
/deepseek-ai-dsh-llm-pi-ai/model-experience/provider-request-through-pi-ai/token-effect:
|
|
75
78
|
en: 820221e8ae37aa61
|
|
76
79
|
zh: 7e6ff4db10067fc0
|
|
77
80
|
/deepseek-ai-dsh-llm-pi-ai/model-experience/provider-request-through-pi-ai/kv-cache-effect:
|
|
78
|
-
en:
|
|
79
|
-
zh:
|
|
81
|
+
en: cc7d4ec548afa30c
|
|
82
|
+
zh: ff3b01a65512f4ac
|
|
80
83
|
/deepseek-ai-dsh-llm-pi-ai/model-experience/provider-response:
|
|
81
84
|
en: 802d7ff60a1d03ff
|
|
82
85
|
zh: c41c56e28f3e8680
|
|
83
86
|
/deepseek-ai-dsh-llm-pi-ai/model-experience/provider-response/what-the-model-sees:
|
|
84
|
-
en:
|
|
85
|
-
zh:
|
|
87
|
+
en: 94ca496012c92fa9
|
|
88
|
+
zh: 9539b08924b5022d
|
|
86
89
|
/deepseek-ai-dsh-llm-pi-ai/model-experience/provider-response/token-effect:
|
|
87
90
|
en: f002b21d0f4c3df0
|
|
88
91
|
zh: 388c8ed4676ed1af
|
|
@@ -90,8 +93,8 @@
|
|
|
90
93
|
en: b6bd570c0159ba08
|
|
91
94
|
zh: 7d2d91eea6a8d830
|
|
92
95
|
/deepseek-ai-dsh-llm-pi-ai/known-limitations-and-deferred-work:
|
|
93
|
-
en:
|
|
94
|
-
zh:
|
|
96
|
+
en: b8117f745275a043
|
|
97
|
+
zh: 29946f7b53ec1681
|
|
95
98
|
/deepseek-ai-dsh-llm-pi-ai/known-limitations-and-deferred-work/dev-note:
|
|
96
99
|
en: 3678dd0f6642c2a5
|
|
97
100
|
zh: 75cbdd064cc64282
|
package/README.md
CHANGED
|
@@ -48,6 +48,8 @@ Each profile may set a `retryPolicy`; omission uses normal mode with five retrie
|
|
|
48
48
|
requestImagePixelBudget: 4194304 # total pixels; 2048 by 2048 default
|
|
49
49
|
requestImageMaxBytes: 1048576 # raw bytes before base64 expansion
|
|
50
50
|
maxRequestImageBytes: 20971520 # accumulated base64 payload
|
|
51
|
+
maxRequestImages: 50 # retained image occurrences
|
|
52
|
+
imageOffloadCountQuantum: 10 # oldest images offloaded per count overflow
|
|
51
53
|
retryPolicy:
|
|
52
54
|
mode: normal
|
|
53
55
|
maxRetries: 3
|
|
@@ -81,11 +83,13 @@ Each profile may set a `retryPolicy`; omission uses normal mode with five retrie
|
|
|
81
83
|
| `models` | installed catalog | Replaces the route's catalog wholesale; each entry defaults from the installed model |
|
|
82
84
|
| `modelOverrides` | none | Reshapes individual installed-catalog models without replacing the rest |
|
|
83
85
|
| `compat` | catalog detection | Wire-compatibility switches for unrecognized endpoints |
|
|
84
|
-
| `defaultContextWindow` | `
|
|
85
|
-
| `defaultMaxTokens` | `
|
|
86
|
+
| `defaultContextWindow` | `1,000,000` | Capacity fallback for undescribed models |
|
|
87
|
+
| `defaultMaxTokens` | `128,000` | Output-cap fallback for undescribed models |
|
|
86
88
|
| `requestImagePixelBudget` | `4,194,304` | Total-pixel budget for each deterministic request image |
|
|
87
89
|
| `requestImageMaxBytes` | `1 MiB` | Encoded-byte target for each request image before base64 expansion |
|
|
88
90
|
| `maxRequestImageBytes` | `20 MiB` | Aggregate base64 image-payload bound; a request whose retained images exceed it fails with `IMAGE_OFFLOAD_REQUIRED` |
|
|
91
|
+
| `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
|
+
| `imageOffloadCountQuantum` | `10`, capped at `maxRequestImages` | Oldest images offloaded per count overflow |
|
|
89
93
|
| `retryPolicy` | normal, 5 retries | Provider-owned retry policy executed by `dsh-llm-retry` |
|
|
90
94
|
|
|
91
95
|
The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-llm-pi-ai) is the exhaustive source for every accepted field and its JSDoc.
|
|
@@ -140,6 +144,13 @@ The adapter is built on immutable snapshots and per-operation resolution. Each o
|
|
|
140
144
|
|
|
141
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.
|
|
142
146
|
|
|
147
|
+
<a id="request-headers"></a>
|
|
148
|
+
### Request headers
|
|
149
|
+
|
|
150
|
+
Plugins can contribute model-hidden transport metadata through the synchronous `llm-pi-ai/request-headers` waterfall. Each inference call supplies immutable routing metadata (`PiAiRequestHeaderContext`) and a fresh `Headers` copy of its profile headers; when configured names differ only in capitalization, the last entry wins. The endpoint belongs to the prepared model, so concurrent calls and configuration changes cannot exchange header state. Listeners edit that copy, call `next()`, and release their references on return; `ctx.on()` removes their registration when the owning plugin unloads. Harness attribution is applied after all contributors, and pi-ai receives a detached header record.
|
|
151
|
+
|
|
152
|
+
This event covers inference calls with or without a Session id, including auxiliary calls, but excludes model discovery. A contributor exception or invalid HTTP header fails the call with `REQUEST_HEADERS` before inference dispatch; no partially prepared request is sent. The failure identifies the provider and includes the contributor's top-level error message, which must exclude credentials and header values. Native header validation can echo values in a `TypeError`, so TypeError details and non-Error throws receive safe guidance instead; nested causes remain attached to the thrown error but are not copied into the public failure. Contributions do not change messages, tool schemas, or the Session log. Direct `PiAiAdapter` consumers can supply the equivalent `prepareHeaders` callback.
|
|
153
|
+
|
|
143
154
|
### Source map
|
|
144
155
|
|
|
145
156
|
| File | Role |
|
|
@@ -182,7 +193,7 @@ The `pre-commit` hook runs `node_modules/.bin/tsx packages/llm/llm-pi-ai/scripts
|
|
|
182
193
|
|
|
183
194
|
### Replay and vocabulary
|
|
184
195
|
|
|
185
|
-
Successful assistant responses store a versioned, lossless-JSON replay state beside the provider and model that produced them — response-level facts plus one per-block entry per streamed block. At request time, `LlmRuntime` passes replay state only when the same adapter instance owns both routes; the adapter validates it and restores native response ids, provider signatures, and optional `providerThinkingLevel` effort metadata, keeping absent effort metadata absent. Replay validates the requested model identity against the assistant source and uses it to retain same-model signatures; provider-reported response models remain diagnostic metadata. Absent or unusable replay state degrades to provider-neutral content while preserving the assistant source’s required provider and model. pi-ai tool-call arguments are parsed objects, so the adapter parses input and re-stringifies output to the harness raw-JSON convention; pi-ai in-stream error events map to terminal `finish` chunks. Protocol conversion operates on request-local copies. Switching from A to B and back to A preserves the stored content, including empty text blocks, tool ids, original block order, and native replay metadata; unsupported signatures
|
|
196
|
+
Successful assistant responses store a versioned, lossless-JSON replay state beside the provider and model that produced them — response-level facts plus one per-block entry per streamed block. At request time, `LlmRuntime` passes replay state only when the same adapter instance owns both routes; the adapter validates it and restores native response ids, provider signatures, and optional `providerThinkingLevel` effort metadata, keeping absent effort metadata absent. Replay validates the requested model identity against the assistant source and uses it to retain same-model signatures; provider-reported response models remain diagnostic metadata. Absent or unusable replay state degrades to provider-neutral content while preserving the assistant source’s required provider and model. pi-ai tool-call arguments are parsed objects, so the adapter parses input and re-stringifies output to the harness raw-JSON convention; pi-ai in-stream error events map to terminal `finish` chunks. Protocol conversion operates on request-local copies. Switching from A to B and back to A preserves the stored content, including empty text blocks, tool ids, original block order, and native replay metadata; requests to a different provider, API, or model omit unsupported signatures and reasoning blocks. Degraded replay without native metadata also omits reasoning. Valid native replay retains the stored reasoning when the original model resumes.
|
|
186
197
|
|
|
187
198
|
</details>
|
|
188
199
|
|
|
@@ -209,7 +220,7 @@ Read these pages when the package-level contract is not enough. They move from t
|
|
|
209
220
|
|
|
210
221
|
#### What the model sees
|
|
211
222
|
|
|
212
|
-
The selected catalog model receives system-message text, conversation history, tools, and supported sampling fields. The adapter preserves later system messages in history order
|
|
223
|
+
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. `imageRequestTarget(provider, model, image)` exposes the same request-image dimensions and byte target to screenshot consumers; adapters without image resizing preserve the normalized source.
|
|
213
224
|
|
|
214
225
|
#### Token effect
|
|
215
226
|
|
|
@@ -217,13 +228,13 @@ Provider tokenization governs exact input. Retained images add the stable attach
|
|
|
217
228
|
|
|
218
229
|
#### KV Cache effect
|
|
219
230
|
|
|
220
|
-
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. 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
|
|
231
|
+
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. 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.
|
|
221
232
|
|
|
222
233
|
### Provider response
|
|
223
234
|
|
|
224
235
|
#### What the model sees
|
|
225
236
|
|
|
226
|
-
pi-ai events become harness reasoning, text, tool-call, usage, and finish chunks. The adapter passes parsed tool arguments to the harness as raw JSON strings.
|
|
237
|
+
pi-ai events become harness reasoning, text, tool-call, usage, and finish chunks. The adapter passes parsed tool arguments to the harness as raw JSON strings. If pi-ai reports invalid completed arguments, the attempt fails with `MALFORMED_RESPONSE` before tool dispatch and publishes no successful replay state. The default normal retry policy excludes this code; an explicit retry policy still controls recovery.
|
|
227
238
|
|
|
228
239
|
#### Token effect
|
|
229
240
|
|
|
@@ -241,6 +252,7 @@ Recorded response content appends to the next request and does not invalidate it
|
|
|
241
252
|
These limits define where the adapter stops and future work begins. They are current package constraints, not a general pi-ai comparison or a task backlog.
|
|
242
253
|
|
|
243
254
|
- **`maxRequestImageBytes` counts base64 image payload only** — text, tools, descriptors, and JSON structure ride outside the bound, so it must sit below the gateway's request-body cap with headroom.
|
|
255
|
+
- **The byte bound has no removal quantum** — at `maxRequestImageBytes`, every new image offloads the minimum oldest prefix, so prompt-cache reuse restarts from that point on each image-adding request.
|
|
244
256
|
- **A sign-in lives only in the process that started it** — an authorization attempt is not durable, so reloading the page mid-login abandons it and the human starts over. Signing out is `deleteRecord` on the stored record, which forgets it locally without telling the issuer.
|
|
245
257
|
- **OpenAI offers no ChatGPT sign-in** — pi-ai's Sign in with ChatGPT identifies the installation to OpenAI with a stable UUID the app supplies, and the harness keeps no installation ID meant for a third-party account sign-in; the `openai` route signs in with an API key.
|
|
246
258
|
- **Provider-native discovery answers through this plugin's ambient context** — a route naming no credential defers to the catalog provider's own resolution, which asks for environment values (`AZURE_OPENAI_API_KEY`, `AWS_PROFILE`, and each provider's own set) and for local credential files. Both questions are answered here: the credential seam is consulted before the process environment, and file existence is checked against the host process's filesystem with `~` expanded. What it cannot do is *read* a credential file's contents — a provider that parses `~/.aws/credentials` itself does so directly, outside the seam.
|
|
@@ -253,11 +265,12 @@ These limits define where the adapter stops and future work begins. They are cur
|
|
|
253
265
|
- **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.
|
|
254
266
|
- **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`.
|
|
255
267
|
- **`GenerateOptions.stop` is unsupported** — pi-ai's common stream options cannot guarantee stop-sequence behavior across providers.
|
|
256
|
-
- **Conversation update support comes only from the installed pi-ai catalog** —
|
|
268
|
+
- **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.
|
|
257
269
|
- **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.
|
|
258
270
|
- **Provider HTTP status is unavailable** — pi-ai error events do not expose a stable HTTP status across providers.
|
|
259
271
|
- **Retry policy is provider-owned, not an SDK retry** — pi-ai SDK retries stay disabled so durable agent steps and `llm/retry` events own every visible attempt, and direct `ctx.llm.stream()` calls remain single-attempt.
|
|
260
|
-
- **Streamed JSON tool-call arguments avoid per-delta reparsing** — the installed pi-ai carries [`patches/@earendil-works__pi-ai@1.
|
|
272
|
+
- **Streamed JSON tool-call arguments avoid per-delta reparsing** — the installed pi-ai carries [`patches/@earendil-works__pi-ai@1.3.0.patch`](../../../patches/@earendil-works__pi-ai@1.3.0.patch), which removes the per-delta re-parse of the whole accumulated argument JSON in every stream adapter (upstream [earendil-works/pi#9265](https://github.com/earendil-works/pi/issues/9265)); unpatched, a multi-megabyte argument stream costs O(n²) CPU on the event loop and stalls every session in the process. Completion events supply parsed arguments; Responses may parse at both argument completion and output-item completion. This adapter reads only delta strings and finalized arguments. Re-apply or retire the patch on every pi-ai upgrade.
|
|
273
|
+
- **Gemini tool-call thought signatures are patched into Chat Completions** — the same patch reads `tool_calls[].extra_content.google.thought_signature` from a streamed OpenAI-compatible response into the tool call's replay signature and sends it back as `extra_content` when the same model resumes (upstream [earendil-works/pi#10157](https://github.com/earendil-works/pi/issues/10157)); unpatched, Gemini rejects the next step of a tool-calling turn with HTTP 400. Encrypted OpenRouter reasoning details keep their `reasoning_details` replay.
|
|
261
274
|
|
|
262
275
|
<a id="dev-note"></a>
|
|
263
276
|
### Dev Note
|
package/README.zh.md
CHANGED
|
@@ -48,6 +48,8 @@ kind: "package-reference"
|
|
|
48
48
|
requestImagePixelBudget: 4194304 # total pixels; 2048 by 2048 default
|
|
49
49
|
requestImageMaxBytes: 1048576 # raw bytes before base64 expansion
|
|
50
50
|
maxRequestImageBytes: 20971520 # accumulated base64 payload
|
|
51
|
+
maxRequestImages: 50 # retained image occurrences
|
|
52
|
+
imageOffloadCountQuantum: 10 # oldest images offloaded per count overflow
|
|
51
53
|
retryPolicy:
|
|
52
54
|
mode: normal
|
|
53
55
|
maxRetries: 3
|
|
@@ -81,11 +83,13 @@ kind: "package-reference"
|
|
|
81
83
|
| `models` | 已安装目录 | 整体替换路由目录;每个条目从已安装模型取默认值 |
|
|
82
84
|
| `modelOverrides` | 无 | 重塑个别已安装目录模型,而不替换其余模型 |
|
|
83
85
|
| `compat` | 目录检测 | 无法识别端点的协议兼容开关 |
|
|
84
|
-
| `defaultContextWindow` | `
|
|
85
|
-
| `defaultMaxTokens` | `
|
|
86
|
+
| `defaultContextWindow` | `1,000,000` | 未描述模型的容量回退 |
|
|
87
|
+
| `defaultMaxTokens` | `128,000` | 未描述模型的输出上限回退 |
|
|
86
88
|
| `requestImagePixelBudget` | `4,194,304` | 每张确定性请求图片的总像素预算 |
|
|
87
89
|
| `requestImageMaxBytes` | `1 MiB` | 每张请求图片在 base64 扩展前的编码字节目标 |
|
|
88
90
|
| `maxRequestImageBytes` | `20 MiB` | base64 图片载荷总上限,保留图片超过时请求以 `IMAGE_OFFLOAD_REQUIRED` 失败 |
|
|
91
|
+
| `maxRequestImages` | `50` | 保留请求图片数量上限,保留图片超过时请求以 `IMAGE_OFFLOAD_REQUIRED` 失败。默认值取 Azure OpenAI 的 50 张上限;提供方接受更多图片的路由应调高 |
|
|
92
|
+
| `imageOffloadCountQuantum` | `10`,不超过 `maxRequestImages` | 每次数量超限时省略的最老图片数 |
|
|
89
93
|
| `retryPolicy` | normal,5 次重试 | 由 `dsh-llm-retry` 执行的提供方自有重试策略 |
|
|
90
94
|
|
|
91
95
|
生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-llm-pi-ai)是每个受支持字段及其 JSDoc 的穷尽式真源。
|
|
@@ -140,6 +144,13 @@ Config 更新严格验证发生变化的 provider。初始加载将已存储的
|
|
|
140
144
|
|
|
141
145
|
初始提示词文本和可用工具分别使用 pi-ai 的 `Context.systemPrompt` 与 `Context.tools`;后续系统消息和工具更新保留在 `Context.messages` 中。pi-ai 负责规范化这些字段,并应用所选协议的序列化规则。
|
|
142
146
|
|
|
147
|
+
<a id="request-headers"></a>
|
|
148
|
+
### 请求头
|
|
149
|
+
|
|
150
|
+
插件可通过同步的 `llm-pi-ai/request-headers` waterfall 贡献模型不可见的传输元数据。每次推理调用提供不可变的路由元数据(`PiAiRequestHeaderContext`)和从 profile 标头复制出的独立 `Headers`;配置名称仅大小写不同时,以最后一个条目为准。端点来自已准备的模型,因此并发调用与配置变更不会交换请求头状态。监听器修改该副本、调用 `next()`,并在返回时释放对它的引用;所属插件卸载时,`ctx.on()` 会移除注册。Harness 的应用标识在所有贡献器之后写入,pi-ai 接收独立的标头记录。
|
|
151
|
+
|
|
152
|
+
该事件覆盖有无 Session id 的推理调用及辅助调用,不用于模型发现。贡献器异常或无效 HTTP 标头会在推理发送前以 `REQUEST_HEADERS` 使调用失败,不发送部分准备好的请求。失败信息包含 provider 和贡献器的顶层错误消息,该消息必须排除凭据与标头值。原生标头校验可能在 `TypeError` 中回显值,因此 TypeError 详情与非 Error 抛出值改用安全的排查提示;嵌套 cause 仍附在抛出的错误上,但不会复制到公开失败信息中。贡献不会改变消息、工具 schema 或 Session 日志。直接使用 `PiAiAdapter` 的调用方可提供等效的 `prepareHeaders` 回调。
|
|
153
|
+
|
|
143
154
|
### 源码地图
|
|
144
155
|
|
|
145
156
|
| 文件 | 职责 |
|
|
@@ -182,7 +193,7 @@ git add packages/llm/llm-pi-ai/src/provider-data.generated.ts
|
|
|
182
193
|
|
|
183
194
|
### 回放与词汇
|
|
184
195
|
|
|
185
|
-
成功 assistant 响应会存储带版本的、无损 JSON 回放状态,与产生它们的提供方和模型放在一起——响应级事实加每个流式块一条逐块条目。请求时,`LlmRuntime` 仅当同一适配器实例拥有两条路由时才传递回放状态;适配器校验它并恢复原生响应 id、提供方签名与可选的 `providerThinkingLevel` effort 元数据,缺失的 effort 元数据仍保持缺失。回放会对照 assistant 来源校验请求模型身份,并用它保留同模型签名;提供方报告的响应模型仅作为诊断元数据。回放状态缺失或无法使用时会降级为提供方无关内容,并保留 assistant 来源中必需的提供方和模型。pi-ai 工具调用参数是解析后的对象,因此适配器解析输入并重新字符串化输出,以符合 harness 原始 JSON 约定;pi-ai 流内错误事件映射为终止 `finish` 分片。 协议转换仅作用于请求副本。从 A 切换到 B 再切回 A 时,存储的内容保持完整,包括空文本块、工具 id
|
|
196
|
+
成功 assistant 响应会存储带版本的、无损 JSON 回放状态,与产生它们的提供方和模型放在一起——响应级事实加每个流式块一条逐块条目。请求时,`LlmRuntime` 仅当同一适配器实例拥有两条路由时才传递回放状态;适配器校验它并恢复原生响应 id、提供方签名与可选的 `providerThinkingLevel` effort 元数据,缺失的 effort 元数据仍保持缺失。回放会对照 assistant 来源校验请求模型身份,并用它保留同模型签名;提供方报告的响应模型仅作为诊断元数据。回放状态缺失或无法使用时会降级为提供方无关内容,并保留 assistant 来源中必需的提供方和模型。pi-ai 工具调用参数是解析后的对象,因此适配器解析输入并重新字符串化输出,以符合 harness 原始 JSON 约定;pi-ai 流内错误事件映射为终止 `finish` 分片。 协议转换仅作用于请求副本。从 A 切换到 B 再切回 A 时,存储的内容保持完整,包括空文本块、工具 id、原始块顺序和原生回放元数据;发给不同提供方、API 或模型的请求会省略不受支持的签名和推理块。缺少原生元数据的降级回放也会省略推理。切回原模型时,有效的原生回放会保留已存储的推理。
|
|
186
197
|
|
|
187
198
|
</details>
|
|
188
199
|
|
|
@@ -209,7 +220,7 @@ git add packages/llm/llm-pi-ai/src/provider-data.generated.ts
|
|
|
209
220
|
|
|
210
221
|
#### 模型看到什么
|
|
211
222
|
|
|
212
|
-
|
|
223
|
+
所选目录模型会收到系统消息文本、对话历史、工具以及支持的采样字段。目录模型声明 `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` 事件记录所选位置并重试步骤。提供方原生回放元数据只在适配器针对历史内容校验通过后恢复。 `imageRequestTarget(provider, model, image)` 向截图调用方提供与模型请求一致的图片尺寸和字节目标;不缩放图片的适配器保留归一化后的原图。
|
|
213
224
|
|
|
214
225
|
#### Token 影响
|
|
215
226
|
|
|
@@ -217,13 +228,13 @@ git add packages/llm/llm-pi-ai/src/provider-data.generated.ts
|
|
|
217
228
|
|
|
218
229
|
#### KV Cache 影响
|
|
219
230
|
|
|
220
|
-
|
|
231
|
+
传给适配器的后续系统消息不会进入初始提示词,从而保留此前的请求前缀。这不改变 Agent loop 的提示词纳入行为;它仍在不支持原生系统更新的路由上合并更新。转换保持逻辑请求顺序,图片句柄与卸载占位符则会添加模型可见文本。即使附件身份与请求字节保持稳定,执行世界路径变化也会改写历史句柄,并可能从该图片起阻止复用。更换适配器实例、提供方、模型或其他上游 token 具有相同的后缀影响。一次省略决策会把较早图片换成占位文本,因此复用在该消息处结束;省略永不回退,在下一次决策前前缀保持稳定。数量超限时一次省略 `imageOffloadCountQuantum` 张图片,因此饱和路由每新增这么多张图片才让复用在最老的保留图片处结束一次。
|
|
221
232
|
|
|
222
233
|
### 提供方响应
|
|
223
234
|
|
|
224
235
|
#### 模型看到什么
|
|
225
236
|
|
|
226
|
-
pi-ai 事件变成 harness 的推理、文本、工具调用、用量与 finish 分片。适配器把解析后的工具参数以原始 JSON 字符串传给 harness
|
|
237
|
+
pi-ai 事件变成 harness 的推理、文本、工具调用、用量与 finish 分片。适配器把解析后的工具参数以原始 JSON 字符串传给 harness。如果 pi-ai 报告已完成调用的参数无效,本次尝试会在分派工具前以 `MALFORMED_RESPONSE` 失败,且不发布成功的回放状态。默认的普通重试策略不重试此错误码;显式重试策略仍然控制恢复。
|
|
227
238
|
|
|
228
239
|
#### Token 影响
|
|
229
240
|
|
|
@@ -241,6 +252,7 @@ pi-ai 事件变成 harness 的推理、文本、工具调用、用量与 finish
|
|
|
241
252
|
这些限制说明适配器在哪里停止、由未来工作接续。它们是当前包约束,不是通用 pi-ai 对比或任务积压。
|
|
242
253
|
|
|
243
254
|
- **`maxRequestImageBytes` 只计算 base64 图片载荷**,文本、工具、描述符与 JSON 结构在该上限之外,因此它必须留有余量地低于网关请求体上限。
|
|
255
|
+
- **字节上限没有移除量子**:达到 `maxRequestImageBytes` 后,每张新图片都只省略最少的最老前缀,因此每个新增图片的请求都会让提示词缓存复用从该位置重新开始。
|
|
244
256
|
- **登录只存在于发起它的进程中**——授权尝试不持久,因此登录中途刷新页面会放弃它,用户需要重新开始。退出登录是对已存储记录执行 `deleteRecord`,只在本地忘记它,不会告知签发方。
|
|
245
257
|
- **OpenAI 不提供 ChatGPT 登录**——pi-ai 的 Sign in with ChatGPT 用应用提供的稳定 UUID 向 OpenAI 标识安装实例,而 harness 没有用于第三方账号登录的安装 ID;`openai` 路由改用 API key 登录。
|
|
246
258
|
- **提供方原生发现经本插件的 ambient context 回答**——不点名凭据的路由交由目录提供方自身解析,它会询问环境值(`AZURE_OPENAI_API_KEY`、`AWS_PROFILE` 及各提供方自有集合)与本地凭据文件。两个问题都在这里得到回答:凭据 seam 先于进程环境被查询,文件存在性则针对宿主进程的文件系统以 `~` 展开后检查。它做不到的是*读取*凭据文件内容——自行解析 `~/.aws/credentials` 的提供方会直接读取,不经该 seam。
|
|
@@ -253,11 +265,12 @@ pi-ai 事件变成 harness 的推理、文本、工具调用、用量与 finish
|
|
|
253
265
|
- **模态声明不受校验**——声明 `image` 而其网关不支持的模型会在提示词准入后被提供方拒绝。持久图片仍留在历史中,同一误声明模型可能再次失败;切换到纯文本模型仍然可行,因为共享 LLM 运行时会针对该请求把图片引用投影为稳定文本。
|
|
254
266
|
- **未认证路由取决于其协议**——不点名凭据的路由解析为已配置但无密钥,但 pi-ai 的 OpenAI 兼容实现仍要求 API 密钥或 `Authorization` 标头,因此无密钥本地服务器需要由 `apiKeyEnv` 引用或 `headers` 中的 `Authorization` 条目提供的占位凭据。
|
|
255
267
|
- **不支持 `GenerateOptions.stop`**——pi-ai 的通用流式选项无法跨提供方保证停止序列行为。
|
|
256
|
-
- **对话更新支持只来自已安装的 pi-ai
|
|
268
|
+
- **对话更新支持只来自已安装的 pi-ai 目录**——原生系统与工具更新需要目录模型的对话中 compat 标志,profile 不能设置这些标志。手工声明的路由与未标记的模型会以用户角色提醒接收后续系统文本,并在每次请求开头接收完整的当前工具列表。
|
|
257
269
|
- **图片只在 user 与工具结果消息中被接受**——system、developer 或 assistant 历史中的图片在两条转换路径上都会以 `UNSUPPORTED_CONTENT` 失败。
|
|
258
270
|
- **提供方 HTTP 状态不可用**——pi-ai 错误事件不跨提供方暴露稳定 HTTP 状态。
|
|
259
271
|
- **重试策略由提供方自有,而非 SDK 重试**——pi-ai SDK 重试保持禁用,因此持久 agent(智能体)步骤与 `llm/retry` 事件拥有每个可见尝试,直接 `ctx.llm.stream()` 调用仍是单次尝试。
|
|
260
|
-
- **流式 JSON 工具调用参数避免逐 delta 重复解析**——安装的 pi-ai 带有 [`patches/@earendil-works__pi-ai@1.
|
|
272
|
+
- **流式 JSON 工具调用参数避免逐 delta 重复解析**——安装的 pi-ai 带有 [`patches/@earendil-works__pi-ai@1.3.0.patch`](../../../patches/@earendil-works__pi-ai@1.3.0.patch),它移除了每个流适配器中对整段累计参数 JSON 的逐 delta 重新解析(上游 [earendil-works/pi#9265](https://github.com/earendil-works/pi/issues/9265));未打补丁时,数 MB 的参数流会在事件循环上消耗 O(n²) CPU,并使进程内所有会话停滞。完成事件提供解析后的参数;Responses 可能在参数完成和输出项完成时分别解析。本适配器只读取 delta 字符串与最终参数。每次升级 pi-ai 时都要重新应用或撤销该补丁。
|
|
273
|
+
- **Chat Completions 中的 Gemini 工具调用思考签名由补丁保留**——同一补丁把 OpenAI 兼容流式响应里的 `tool_calls[].extra_content.google.thought_signature` 读入工具调用的重放签名,并在同一模型继续时以 `extra_content` 发回(上游 [earendil-works/pi#10157](https://github.com/earendil-works/pi/issues/10157));未打补丁时,Gemini 会以 HTTP 400 拒绝工具调用轮次的下一步。OpenRouter 的加密推理详情仍通过 `reasoning_details` 重放。
|
|
261
274
|
|
|
262
275
|
<a id="dev-note"></a>
|
|
263
276
|
### 开发备注
|
package/lib/index.js
CHANGED
|
@@ -434,7 +434,8 @@ const RESPONSES_COMPAT_GATE = {
|
|
|
434
434
|
supportsAdditionalTools: "withhold",
|
|
435
435
|
supportsToolSearch: "withhold",
|
|
436
436
|
supportsExplicitPromptCacheMode: "withhold",
|
|
437
|
-
supportsMidConvoSystemMessages: "withhold"
|
|
437
|
+
supportsMidConvoSystemMessages: "withhold",
|
|
438
|
+
supportsMidConvoEffort: "withhold"
|
|
438
439
|
};
|
|
439
440
|
/**
|
|
440
441
|
* The compat gate of every wire protocol a profile may configure.
|
|
@@ -956,9 +957,9 @@ const DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET = 2048 * 2048;
|
|
|
956
957
|
/** Default raw encoded-byte target before inline base64 expansion; the smallest quality-ladder output is used when no quality fits. */
|
|
957
958
|
const DEFAULT_REQUEST_IMAGE_MAX_BYTES = 1024 * 1024;
|
|
958
959
|
/** Context capacity assumed for a model neither configuration nor the catalog sizes. */
|
|
959
|
-
const DEFAULT_CONTEXT_WINDOW =
|
|
960
|
+
const DEFAULT_CONTEXT_WINDOW = 1e6;
|
|
960
961
|
/** Output capability assumed for a model neither configuration nor the catalog sizes. */
|
|
961
|
-
const DEFAULT_MAX_TOKENS =
|
|
962
|
+
const DEFAULT_MAX_TOKENS = 128e3;
|
|
962
963
|
/**
|
|
963
964
|
* Modalities assumed for a model neither configuration nor the catalog
|
|
964
965
|
* declares. Text is the floor every supported protocol certainly carries, so
|
|
@@ -1075,6 +1076,8 @@ const profile = z.object({
|
|
|
1075
1076
|
websocketConnectTimeoutMs: z.natural(),
|
|
1076
1077
|
streamIdleTimeoutMs: z.number().min(Number.MIN_VALUE).max(MAX_TIMER_DELAY_MS).default(DEFAULT_STREAM_IDLE_TIMEOUT_MS),
|
|
1077
1078
|
maxRequestImageBytes: z.number().step(1).min(1).default(DEFAULT_MAX_REQUEST_IMAGE_BYTES),
|
|
1079
|
+
maxRequestImages: z.number().step(1).min(1).default(50),
|
|
1080
|
+
imageOffloadCountQuantum: z.number().step(1).min(1),
|
|
1078
1081
|
requestImagePixelBudget: z.number().step(1).min(1).default(DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET),
|
|
1079
1082
|
requestImageMaxBytes: z.number().step(1).min(1).default(DEFAULT_REQUEST_IMAGE_MAX_BYTES),
|
|
1080
1083
|
retryPolicy: RetryPolicySchema
|
|
@@ -1128,6 +1131,10 @@ function resolveProfiles(providers, validation = "strict") {
|
|
|
1128
1131
|
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}`);
|
|
1129
1132
|
const maxRequestImageBytes = source.maxRequestImageBytes ?? 20971520;
|
|
1130
1133
|
if (!Number.isInteger(maxRequestImageBytes) || maxRequestImageBytes <= 0) throw new Error(`llm-pi-ai: provider "${provider}" maxRequestImageBytes must be a positive integer`);
|
|
1134
|
+
const maxRequestImages = source.maxRequestImages ?? 50;
|
|
1135
|
+
if (!Number.isSafeInteger(maxRequestImages) || maxRequestImages <= 0) throw new Error(`llm-pi-ai: provider "${provider}" maxRequestImages must be a positive safe integer`);
|
|
1136
|
+
const imageOffloadCountQuantum = source.imageOffloadCountQuantum ?? Math.min(10, maxRequestImages);
|
|
1137
|
+
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`);
|
|
1131
1138
|
const requestImagePixelBudget = source.requestImagePixelBudget ?? 4194304;
|
|
1132
1139
|
if (!Number.isSafeInteger(requestImagePixelBudget) || requestImagePixelBudget <= 0) throw new Error(`llm-pi-ai: provider "${provider}" requestImagePixelBudget must be a positive safe integer`);
|
|
1133
1140
|
const requestImageMaxBytes = source.requestImageMaxBytes ?? 1048576;
|
|
@@ -1147,8 +1154,8 @@ function resolveProfiles(providers, validation = "strict") {
|
|
|
1147
1154
|
...source.modelOverrides === void 0 ? {} : { modelOverrides: source.modelOverrides },
|
|
1148
1155
|
...source.compat === void 0 ? {} : { compat: source.compat },
|
|
1149
1156
|
defaultInput,
|
|
1150
|
-
defaultContextWindow: source.defaultContextWindow ??
|
|
1151
|
-
defaultMaxTokens: source.defaultMaxTokens ??
|
|
1157
|
+
defaultContextWindow: source.defaultContextWindow ?? 1e6,
|
|
1158
|
+
defaultMaxTokens: source.defaultMaxTokens ?? 128e3
|
|
1152
1159
|
}, validation);
|
|
1153
1160
|
catalogError = catalog.modelErrors.values().next().value;
|
|
1154
1161
|
piProvider = buildProvider({
|
|
@@ -1171,6 +1178,8 @@ function resolveProfiles(providers, validation = "strict") {
|
|
|
1171
1178
|
...apiKeyEnv === void 0 ? {} : { apiKeyEnv: credentialRef(apiKeyEnv) },
|
|
1172
1179
|
streamIdleTimeoutMs,
|
|
1173
1180
|
maxRequestImageBytes,
|
|
1181
|
+
maxRequestImages,
|
|
1182
|
+
imageOffloadCountQuantum,
|
|
1174
1183
|
requestImagePixelBudget,
|
|
1175
1184
|
requestImageMaxBytes,
|
|
1176
1185
|
retryPolicy: resolveRetryPolicy(retryPolicy, `llm-pi-ai: provider "${provider}" retryPolicy`),
|
|
@@ -1330,18 +1339,26 @@ function appendAssistant(message, messages, toolNames, onReplayDegrade) {
|
|
|
1330
1339
|
messages.push(assistant);
|
|
1331
1340
|
}
|
|
1332
1341
|
/** Append shared system, developer, and assistant roles; true when consumed. */
|
|
1333
|
-
function appendSharedHistory(message, options, messages, toolNames, onReplayDegrade) {
|
|
1342
|
+
function appendSharedHistory(message, options, messages, toolNames, supportsMidConvoSystemMessages, onReplayDegrade) {
|
|
1334
1343
|
if (message.role === "developer") {
|
|
1335
1344
|
appendDeveloper(message, options, messages);
|
|
1336
1345
|
return true;
|
|
1337
1346
|
}
|
|
1338
1347
|
if (message.role === "system") {
|
|
1339
1348
|
const content = flattenText(message);
|
|
1340
|
-
if (content.length > 0) messages.push({
|
|
1349
|
+
if (content.length > 0) if (supportsMidConvoSystemMessages) messages.push({
|
|
1341
1350
|
role: "system",
|
|
1342
1351
|
content,
|
|
1343
1352
|
timestamp: 0
|
|
1344
1353
|
});
|
|
1354
|
+
else {
|
|
1355
|
+
const reminder = content.replaceAll("</system-reminder>", "<\\/system-reminder>");
|
|
1356
|
+
messages.push({
|
|
1357
|
+
role: "user",
|
|
1358
|
+
content: `<system-reminder>\n${reminder}\n</system-reminder>`,
|
|
1359
|
+
timestamp: 0
|
|
1360
|
+
});
|
|
1361
|
+
}
|
|
1345
1362
|
return true;
|
|
1346
1363
|
}
|
|
1347
1364
|
if (message.role === "assistant") {
|
|
@@ -1350,14 +1367,14 @@ function appendSharedHistory(message, options, messages, toolNames, onReplayDegr
|
|
|
1350
1367
|
}
|
|
1351
1368
|
return false;
|
|
1352
1369
|
}
|
|
1353
|
-
function textOnlyContext(options, onReplayDegrade) {
|
|
1370
|
+
function textOnlyContext(options, supportsMidConvoSystemMessages, onReplayDegrade) {
|
|
1354
1371
|
assertSupportedHistory(options.messages);
|
|
1355
1372
|
const split = splitSystemPrompt(options);
|
|
1356
1373
|
const toolNames = /* @__PURE__ */ new Map();
|
|
1357
1374
|
const messages = [];
|
|
1358
1375
|
for (const message of split.messages) {
|
|
1359
1376
|
if (contentHasImage(message.content)) throw new LlmError("pi-ai image conversion requires the durable attachment service", "UNSUPPORTED_CONTENT");
|
|
1360
|
-
if (appendSharedHistory(message, options, messages, toolNames, onReplayDegrade)) continue;
|
|
1377
|
+
if (appendSharedHistory(message, options, messages, toolNames, supportsMidConvoSystemMessages, onReplayDegrade)) continue;
|
|
1361
1378
|
if (message.role === "tool") {
|
|
1362
1379
|
messages.push(toolResultOf(message, toolNames, flattenText(message)));
|
|
1363
1380
|
continue;
|
|
@@ -1382,11 +1399,11 @@ function requestImageTarget(ref, budget) {
|
|
|
1382
1399
|
maxBytes: budget.maxBytes
|
|
1383
1400
|
};
|
|
1384
1401
|
}
|
|
1385
|
-
function toPiContext(options, images, onReplayDegrade) {
|
|
1386
|
-
return images === void 0 ? textOnlyContext(options, onReplayDegrade) : toPiContextWithImages(options, images, onReplayDegrade);
|
|
1402
|
+
function toPiContext(options, images, onReplayDegrade, supportsMidConvoSystemMessages = false) {
|
|
1403
|
+
return images === void 0 ? textOnlyContext(options, supportsMidConvoSystemMessages, onReplayDegrade) : toPiContextWithImages(options, images, supportsMidConvoSystemMessages, onReplayDegrade);
|
|
1387
1404
|
}
|
|
1388
|
-
async function toPiContextWithImages(options, images, onReplayDegrade) {
|
|
1389
|
-
const { attachments, resolveImageAccess, maxRequestImageBytes } = images;
|
|
1405
|
+
async function toPiContextWithImages(options, images, supportsMidConvoSystemMessages, onReplayDegrade) {
|
|
1406
|
+
const { attachments, resolveImageAccess, maxRequestImageBytes, maxRequestImages, imageOffloadCountQuantum } = images;
|
|
1390
1407
|
const requestImagePolicy = images.requestImagePolicy ?? {
|
|
1391
1408
|
maxPixels: 4194304,
|
|
1392
1409
|
maxBytes: 1048576
|
|
@@ -1394,18 +1411,18 @@ async function toPiContextWithImages(options, images, onReplayDegrade) {
|
|
|
1394
1411
|
assertSupportedHistory(options.messages);
|
|
1395
1412
|
const split = splitSystemPrompt(options);
|
|
1396
1413
|
const requestImages = await prepareRequestImages(split.messages, attachments, requestImagePolicy, options.signal);
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
}
|
|
1402
|
-
|
|
1403
|
-
}
|
|
1414
|
+
const offloadImages = requiredImageOffload(split.messages, {
|
|
1415
|
+
representation: "base64",
|
|
1416
|
+
...maxRequestImageBytes === void 0 ? {} : { maxBytes: maxRequestImageBytes },
|
|
1417
|
+
...maxRequestImages === void 0 ? {} : { maxImages: maxRequestImages },
|
|
1418
|
+
...imageOffloadCountQuantum === void 0 ? {} : { countQuantum: imageOffloadCountQuantum }
|
|
1419
|
+
}, (block) => requestImages.get(block.attachment.attachmentId).bytes);
|
|
1420
|
+
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 });
|
|
1404
1421
|
const exactMessages = projectOffloadedImages(split.messages, (ref) => offloadedImageText(ref, resolveImageAccess(ref)));
|
|
1405
1422
|
const toolNames = /* @__PURE__ */ new Map();
|
|
1406
1423
|
const messages = [];
|
|
1407
1424
|
for (const message of exactMessages) {
|
|
1408
|
-
if (appendSharedHistory(message, options, messages, toolNames, onReplayDegrade)) continue;
|
|
1425
|
+
if (appendSharedHistory(message, options, messages, toolNames, supportsMidConvoSystemMessages, onReplayDegrade)) continue;
|
|
1409
1426
|
if (message.role === "tool") {
|
|
1410
1427
|
messages.push(toolResultOf(message, toolNames, userContent(message.content, requestImages, resolveImageAccess)));
|
|
1411
1428
|
continue;
|
|
@@ -1532,10 +1549,13 @@ function mapStopReason(message, contextWindow) {
|
|
|
1532
1549
|
* in-band terminal error an aborted finish.
|
|
1533
1550
|
* @param requestedModel - request model identity recorded for durable replay.
|
|
1534
1551
|
* @returns the harness chunks, ending with `usage` then `finish`; throws
|
|
1535
|
-
* `LlmError` (`STREAM_CLOSED`) if the source ends without a terminal event
|
|
1552
|
+
* `LlmError` (`STREAM_CLOSED`) if the source ends without a terminal event, or
|
|
1553
|
+
* `MALFORMED_RESPONSE` when completed tool arguments are invalid. Length-limited
|
|
1554
|
+
* output retains its terminal reason so the assembler can discard incomplete calls.
|
|
1536
1555
|
*/
|
|
1537
1556
|
async function* toStreamChunks(events, contextWindow, callerSignal, requestedModel) {
|
|
1538
1557
|
const toolIds = /* @__PURE__ */ new Map();
|
|
1558
|
+
let argumentsError;
|
|
1539
1559
|
for await (const event of events) switch (event.type) {
|
|
1540
1560
|
case "start": break;
|
|
1541
1561
|
case "text_start":
|
|
@@ -1613,6 +1633,10 @@ async function* toStreamChunks(events, contextWindow, callerSignal, requestedMod
|
|
|
1613
1633
|
break;
|
|
1614
1634
|
}
|
|
1615
1635
|
case "toolcall_end":
|
|
1636
|
+
if (event.toolCall.argumentsError !== void 0) {
|
|
1637
|
+
argumentsError ??= `Tool call "${event.toolCall.name}": ${event.toolCall.argumentsError}`;
|
|
1638
|
+
break;
|
|
1639
|
+
}
|
|
1616
1640
|
yield {
|
|
1617
1641
|
type: "block-end",
|
|
1618
1642
|
index: event.contentIndex,
|
|
@@ -1629,6 +1653,7 @@ async function* toStreamChunks(events, contextWindow, callerSignal, requestedMod
|
|
|
1629
1653
|
type: "usage",
|
|
1630
1654
|
usage: mapUsage(event.message.usage)
|
|
1631
1655
|
};
|
|
1656
|
+
if (argumentsError !== void 0 && event.message.stopReason !== "length") throw new LlmError(argumentsError, "MALFORMED_RESPONSE");
|
|
1632
1657
|
yield {
|
|
1633
1658
|
type: "finish",
|
|
1634
1659
|
reason: mapStopReason(event.message, contextWindow),
|
|
@@ -1813,14 +1838,29 @@ function reasoningInfo(model, defaultLevel) {
|
|
|
1813
1838
|
...defaultLevel === void 0 ? {} : { defaultEffort: ReasoningEffortId(defaultLevel) }
|
|
1814
1839
|
} };
|
|
1815
1840
|
}
|
|
1816
|
-
/**
|
|
1817
|
-
function
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1841
|
+
/** Native header TypeErrors can echo credentials; other plugin errors own their public message. */
|
|
1842
|
+
function requestHeaderDiagnostic(error) {
|
|
1843
|
+
if (error instanceof TypeError) return "TypeError during header preparation; check the contributing plugin's header names, values, and configuration";
|
|
1844
|
+
return error instanceof Error ? error.message : "the contributing plugin threw a non-Error value; throw an Error with a safe diagnostic";
|
|
1845
|
+
}
|
|
1846
|
+
/** Prepare request-owned headers without allowing contributors to replace attribution. */
|
|
1847
|
+
function requestHeaders(configured, options, baseURL, prepare) {
|
|
1848
|
+
try {
|
|
1849
|
+
const initial = new Headers();
|
|
1850
|
+
for (const [name, value] of Object.entries(configured ?? {})) initial.set(name, value);
|
|
1851
|
+
const request = Object.freeze({
|
|
1852
|
+
provider: options.provider,
|
|
1853
|
+
model: options.model,
|
|
1854
|
+
baseURL,
|
|
1855
|
+
...options.sessionId === void 0 ? {} : { sessionId: options.sessionId },
|
|
1856
|
+
...options.purpose === void 0 ? {} : { purpose: options.purpose }
|
|
1857
|
+
});
|
|
1858
|
+
const headers = prepare === void 0 ? initial : prepare(request, initial);
|
|
1859
|
+
for (const [name, value] of Object.entries(attributionHeaders())) headers.set(name, value);
|
|
1860
|
+
return Object.fromEntries(headers);
|
|
1861
|
+
} catch (error) {
|
|
1862
|
+
throw new LlmError(`pi-ai request header preparation failed for provider "${options.provider}": ${requestHeaderDiagnostic(error)}`, "REQUEST_HEADERS", { cause: error });
|
|
1863
|
+
}
|
|
1824
1864
|
}
|
|
1825
1865
|
/**
|
|
1826
1866
|
* pi-ai-backed multi-provider adapter. Each operation reads the current
|
|
@@ -1968,25 +2008,27 @@ var PiAiAdapter = class extends LlmAdapter {
|
|
|
1968
2008
|
reason
|
|
1969
2009
|
});
|
|
1970
2010
|
};
|
|
1971
|
-
const context = attachments === void 0 ? toPiContext(request, void 0, onReplayDegrade) : await toPiContext({
|
|
2011
|
+
const context = attachments === void 0 ? toPiContext(request, void 0, onReplayDegrade, updates.systemPromptUpdate === "in-history") : await toPiContext({
|
|
1972
2012
|
...request,
|
|
1973
2013
|
signal: watchdog.signal
|
|
1974
2014
|
}, {
|
|
1975
2015
|
attachments,
|
|
1976
2016
|
resolveImageAccess: (ref) => this.config.resolveImageAccess?.(attachments, ref),
|
|
1977
2017
|
maxRequestImageBytes: profile.maxRequestImageBytes,
|
|
2018
|
+
maxRequestImages: profile.maxRequestImages,
|
|
2019
|
+
imageOffloadCountQuantum: profile.imageOffloadCountQuantum,
|
|
1978
2020
|
requestImagePolicy: {
|
|
1979
2021
|
maxPixels: profile.requestImagePixelBudget,
|
|
1980
2022
|
maxBytes: profile.requestImageMaxBytes
|
|
1981
2023
|
}
|
|
1982
|
-
}, onReplayDegrade);
|
|
2024
|
+
}, onReplayDegrade, updates.systemPromptUpdate === "in-history");
|
|
1983
2025
|
const iterator = toStreamChunks(snapshot.models.streamSimple(model, context, {
|
|
1984
2026
|
...profileOptions(profile, reasoning, apiKey),
|
|
1985
2027
|
...options.temperature === void 0 ? {} : { temperature: options.temperature },
|
|
1986
2028
|
...options.maxTokens === void 0 ? {} : { maxTokens: options.maxTokens },
|
|
1987
2029
|
...options.sessionId === void 0 ? {} : { sessionId: String(options.sessionId) },
|
|
1988
2030
|
signal: watchdog.signal,
|
|
1989
|
-
headers: requestHeaders(profile.headers)
|
|
2031
|
+
headers: requestHeaders(profile.headers, options, model.baseUrl, this.config.prepareHeaders)
|
|
1990
2032
|
}), model.contextWindow, options.signal, model.id)[Symbol.asyncIterator]();
|
|
1991
2033
|
let exhausted = false;
|
|
1992
2034
|
try {
|
|
@@ -2692,7 +2734,7 @@ const PROVIDER_DATA = {
|
|
|
2692
2734
|
},
|
|
2693
2735
|
"kimi-coding": {
|
|
2694
2736
|
env: ["KIMI_API_KEY"],
|
|
2695
|
-
defaultBaseURL: "https://api.kimi.com/coding"
|
|
2737
|
+
defaultBaseURL: "https://api.kimi.com/coding/v1"
|
|
2696
2738
|
},
|
|
2697
2739
|
"meta": {
|
|
2698
2740
|
env: ["META_API_KEY"],
|
|
@@ -2882,9 +2924,9 @@ function apply(ctx, config) {
|
|
|
2882
2924
|
return next;
|
|
2883
2925
|
};
|
|
2884
2926
|
profiles();
|
|
2885
|
-
ctx.on("internal/config",
|
|
2927
|
+
ctx.on("internal/config", (fiber, next) => {
|
|
2886
2928
|
const raw = next();
|
|
2887
|
-
if (
|
|
2929
|
+
if (fiber !== ctx.fiber) return raw;
|
|
2888
2930
|
const candidate = Config(raw);
|
|
2889
2931
|
assertServiceable({ providers: structuredClone(candidate.providers.get()) }, { providers: structuredClone(config.providers.get()) });
|
|
2890
2932
|
return raw;
|
|
@@ -2905,6 +2947,7 @@ function apply(ctx, config) {
|
|
|
2905
2947
|
profiles,
|
|
2906
2948
|
resolveApiKey,
|
|
2907
2949
|
auth,
|
|
2950
|
+
prepareHeaders: (request, headers) => ctx.waterfall("llm-pi-ai/request-headers", request, headers, () => headers),
|
|
2908
2951
|
resolveAttachments: () => ctx.get("attachments"),
|
|
2909
2952
|
resolveImageAccess: (attachments, ref) => resolveImageAttachmentAccess(attachments, (hostPath) => ctx.get("fs")?.processPathFromHostPath(hostPath), ref),
|
|
2910
2953
|
onReplayDegrade: ({ provider, model, reason }) => {
|
package/lib/types/adapter.d.ts
CHANGED
|
@@ -30,6 +30,7 @@ import { LlmAdapter } from '@deepseek-ai/dsh-llm';
|
|
|
30
30
|
import type { GenerateOptions, ImageAttachmentAccess, LlmModelInfo, LlmProviderInfo, LlmResolvedModelInfo, PreparedAdapterCall, ResolvedRetryPolicy, StreamChunk } from '@deepseek-ai/dsh-llm';
|
|
31
31
|
import type { AttachmentStore, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment';
|
|
32
32
|
import type { ResolvedPiAiProviderProfile } from './config.ts';
|
|
33
|
+
import type { PiAiRequestHeaderContext } from './types.ts';
|
|
33
34
|
/** Constructor options for {@link PiAiAdapter}: the two resolution hooks the plugin owns. */
|
|
34
35
|
export interface PiAiAdapterOptions {
|
|
35
36
|
/** Current validated profiles by provider route; called once per operation. */
|
|
@@ -53,6 +54,18 @@ export interface PiAiAdapterOptions {
|
|
|
53
54
|
* every request no matter how often the human signed in.
|
|
54
55
|
*/
|
|
55
56
|
auth: PiAiAuthInjection;
|
|
57
|
+
/**
|
|
58
|
+
* Synchronously prepare this call's headers before SDK dispatch. The input
|
|
59
|
+
* contains a fresh copy of profile headers; attribution is enforced afterward.
|
|
60
|
+
* Omission preserves profile headers. Throws fail the call with REQUEST_HEADERS
|
|
61
|
+
* before inference I/O. Do not retain or mutate headers after returning.
|
|
62
|
+
* Non-TypeError messages become public diagnostics and must exclude secrets;
|
|
63
|
+
* TypeError details and non-Error values are replaced with safe guidance.
|
|
64
|
+
* @param request - immutable routing metadata from the prepared call.
|
|
65
|
+
* @param headers - request-owned headers initialized from the profile.
|
|
66
|
+
* @returns headers to pass to pi-ai after applying Harness attribution.
|
|
67
|
+
*/
|
|
68
|
+
prepareHeaders?: (request: PiAiRequestHeaderContext, headers: Headers) => Headers;
|
|
56
69
|
/** Resolve the optional durable attachment service at request time. */
|
|
57
70
|
resolveAttachments?: () => AttachmentStore | undefined;
|
|
58
71
|
/** Bridge one attachment reference into the current model-tool execution world. */
|
package/lib/types/catalog.d.ts
CHANGED
|
@@ -115,6 +115,7 @@ declare const RESPONSES_COMPAT_GATE: {
|
|
|
115
115
|
readonly supportsToolSearch: "withhold";
|
|
116
116
|
readonly supportsExplicitPromptCacheMode: "withhold";
|
|
117
117
|
readonly supportsMidConvoSystemMessages: "withhold";
|
|
118
|
+
readonly supportsMidConvoEffort: "withhold";
|
|
118
119
|
};
|
|
119
120
|
/** Disposition of every `AnthropicMessagesCompat` field; a drift gate like the one above. */
|
|
120
121
|
declare const ANTHROPIC_COMPAT_GATE: {
|
package/lib/types/config.d.ts
CHANGED
|
@@ -30,14 +30,27 @@ export declare const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 300000;
|
|
|
30
30
|
* Deployments behind stricter gateways lower it per route.
|
|
31
31
|
*/
|
|
32
32
|
export declare const DEFAULT_MAX_REQUEST_IMAGE_BYTES: number;
|
|
33
|
+
/**
|
|
34
|
+
* Default request-level bound on retained image occurrences: Azure OpenAI's
|
|
35
|
+
* documented limit of 50 images per GPT-4o and GPT-4.1 request
|
|
36
|
+
* (https://learn.microsoft.com/azure/foundry/openai/quotas-limits). Routes
|
|
37
|
+
* whose provider accepts more images raise it.
|
|
38
|
+
*/
|
|
39
|
+
export declare const DEFAULT_MAX_REQUEST_IMAGES = 50;
|
|
40
|
+
/**
|
|
41
|
+
* Default number of oldest occurrences one count overflow offloads, so a
|
|
42
|
+
* saturated route rewrites its request prefix once per ten new images rather
|
|
43
|
+
* than once per image.
|
|
44
|
+
*/
|
|
45
|
+
export declare const DEFAULT_IMAGE_OFFLOAD_COUNT_QUANTUM = 10;
|
|
33
46
|
/** Default total-pixel budget preserves the complete 2048px normalized attachment. */
|
|
34
47
|
export declare const DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET: number;
|
|
35
48
|
/** Default raw encoded-byte target before inline base64 expansion; the smallest quality-ladder output is used when no quality fits. */
|
|
36
49
|
export declare const DEFAULT_REQUEST_IMAGE_MAX_BYTES: number;
|
|
37
50
|
/** Context capacity assumed for a model neither configuration nor the catalog sizes. */
|
|
38
|
-
export declare const DEFAULT_CONTEXT_WINDOW =
|
|
51
|
+
export declare const DEFAULT_CONTEXT_WINDOW = 1000000;
|
|
39
52
|
/** Output capability assumed for a model neither configuration nor the catalog sizes. */
|
|
40
|
-
export declare const DEFAULT_MAX_TOKENS =
|
|
53
|
+
export declare const DEFAULT_MAX_TOKENS = 128000;
|
|
41
54
|
/**
|
|
42
55
|
* Modalities assumed for a model neither configuration nor the catalog
|
|
43
56
|
* declares. Text is the floor every supported protocol certainly carries, so
|
|
@@ -89,13 +102,13 @@ export interface PiAiProviderProfile {
|
|
|
89
102
|
compat?: PiAiCompatProfile;
|
|
90
103
|
/**
|
|
91
104
|
* Context capacity for a model this route lists that neither the entry nor
|
|
92
|
-
* the installed catalog sizes (default
|
|
105
|
+
* the installed catalog sizes (default 1,000,000). A guess by construction, so
|
|
93
106
|
* a deployment whose gateway serves smaller models corrects it here.
|
|
94
107
|
*/
|
|
95
108
|
defaultContextWindow?: number;
|
|
96
109
|
/**
|
|
97
110
|
* Output capability for a model this route lists that neither the entry nor
|
|
98
|
-
* the installed catalog sizes (default
|
|
111
|
+
* the installed catalog sizes (default 128,000). This sizes the model; it
|
|
99
112
|
* never becomes a per-request cap on its own.
|
|
100
113
|
*/
|
|
101
114
|
defaultMaxTokens?: number;
|
|
@@ -133,6 +146,18 @@ export interface PiAiProviderProfile {
|
|
|
133
146
|
* requests instead of being rejected by a request-size cap.
|
|
134
147
|
*/
|
|
135
148
|
maxRequestImageBytes?: number;
|
|
149
|
+
/**
|
|
150
|
+
* Maximum retained image occurrences per request. A request carrying more
|
|
151
|
+
* fails with `IMAGE_OFFLOAD_REQUIRED` naming how many of the oldest
|
|
152
|
+
* occurrences to offload.
|
|
153
|
+
*/
|
|
154
|
+
maxRequestImages?: number;
|
|
155
|
+
/**
|
|
156
|
+
* Oldest occurrences offloaded per count overflow (default 10, capped at
|
|
157
|
+
* {@link maxRequestImages}); an explicit value must not exceed it. Larger
|
|
158
|
+
* steps rewrite the request prefix less often.
|
|
159
|
+
*/
|
|
160
|
+
imageOffloadCountQuantum?: number;
|
|
136
161
|
/** Total-pixel budget for each deterministic inline request version. */
|
|
137
162
|
requestImagePixelBudget?: number;
|
|
138
163
|
/**
|
|
@@ -155,6 +180,10 @@ export interface ResolvedPiAiProviderProfile extends Omit<PiAiProviderProfile, '
|
|
|
155
180
|
streamIdleTimeoutMs: number;
|
|
156
181
|
/** Positive request-level base64 image payload bound after defaulting. */
|
|
157
182
|
maxRequestImageBytes: number;
|
|
183
|
+
/** Positive request-level retained image count bound after defaulting. */
|
|
184
|
+
maxRequestImages: number;
|
|
185
|
+
/** Positive count-overflow offload step, at most {@link maxRequestImages}, after defaulting. */
|
|
186
|
+
imageOffloadCountQuantum: number;
|
|
158
187
|
/** Positive total-pixel request-version budget after defaulting. */
|
|
159
188
|
requestImagePixelBudget: number;
|
|
160
189
|
/** Positive raw request-version byte target after defaulting; the smallest quality-ladder output is used when no quality fits. */
|
|
@@ -211,12 +240,14 @@ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
|
|
|
211
240
|
medium?: number | null;
|
|
212
241
|
high?: number | null;
|
|
213
242
|
} & import("@deepseek-ai/cosmokit").Dict) | null;
|
|
214
|
-
cacheRetention?: "none" | "
|
|
243
|
+
cacheRetention?: "none" | "long" | "short" | null;
|
|
215
244
|
transport?: "auto" | "sse" | "websocket" | "websocket-cached" | null;
|
|
216
245
|
timeoutMs?: number | null;
|
|
217
246
|
websocketConnectTimeoutMs?: number | null;
|
|
218
247
|
streamIdleTimeoutMs?: number | null;
|
|
219
248
|
maxRequestImageBytes?: number | null;
|
|
249
|
+
maxRequestImages?: number | null;
|
|
250
|
+
imageOffloadCountQuantum?: number | null;
|
|
220
251
|
requestImagePixelBudget?: number | null;
|
|
221
252
|
requestImageMaxBytes?: number | null;
|
|
222
253
|
retryPolicy?: RetryPolicyConfig | null;
|
|
@@ -244,12 +275,14 @@ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
|
|
|
244
275
|
medium: z<number, number, "plain">;
|
|
245
276
|
high: z<number, number, "plain">;
|
|
246
277
|
}>>, "plain">;
|
|
247
|
-
cacheRetention: z<"none" | "
|
|
278
|
+
cacheRetention: z<"none" | "long" | "short", "none" | "long" | "short", "plain">;
|
|
248
279
|
transport: z<"auto" | "sse" | "websocket" | "websocket-cached", "auto" | "sse" | "websocket" | "websocket-cached", "plain">;
|
|
249
280
|
timeoutMs: z<number, number, "plain">;
|
|
250
281
|
websocketConnectTimeoutMs: z<number, number, "plain">;
|
|
251
282
|
streamIdleTimeoutMs: z<number, number, "defined">;
|
|
252
283
|
maxRequestImageBytes: z<number, number, "defined">;
|
|
284
|
+
maxRequestImages: z<number, number, "defined">;
|
|
285
|
+
imageOffloadCountQuantum: z<number, number, "plain">;
|
|
253
286
|
requestImagePixelBudget: z<number, number, "defined">;
|
|
254
287
|
requestImageMaxBytes: z<number, number, "defined">;
|
|
255
288
|
retryPolicy: z<RetryPolicyConfig>;
|
|
@@ -274,12 +307,14 @@ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
|
|
|
274
307
|
medium?: number | null;
|
|
275
308
|
high?: number | null;
|
|
276
309
|
} & import("@deepseek-ai/cosmokit").Dict) | null;
|
|
277
|
-
cacheRetention?: "none" | "
|
|
310
|
+
cacheRetention?: "none" | "long" | "short" | null;
|
|
278
311
|
transport?: "auto" | "sse" | "websocket" | "websocket-cached" | null;
|
|
279
312
|
timeoutMs?: number | null;
|
|
280
313
|
websocketConnectTimeoutMs?: number | null;
|
|
281
314
|
streamIdleTimeoutMs?: number | null;
|
|
282
315
|
maxRequestImageBytes?: number | null;
|
|
316
|
+
maxRequestImages?: number | null;
|
|
317
|
+
imageOffloadCountQuantum?: number | null;
|
|
283
318
|
requestImagePixelBudget?: number | null;
|
|
284
319
|
requestImageMaxBytes?: number | null;
|
|
285
320
|
retryPolicy?: RetryPolicyConfig | null;
|
|
@@ -307,12 +342,14 @@ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
|
|
|
307
342
|
medium: z<number, number, "plain">;
|
|
308
343
|
high: z<number, number, "plain">;
|
|
309
344
|
}>>, "plain">;
|
|
310
|
-
cacheRetention: z<"none" | "
|
|
345
|
+
cacheRetention: z<"none" | "long" | "short", "none" | "long" | "short", "plain">;
|
|
311
346
|
transport: z<"auto" | "sse" | "websocket" | "websocket-cached", "auto" | "sse" | "websocket" | "websocket-cached", "plain">;
|
|
312
347
|
timeoutMs: z<number, number, "plain">;
|
|
313
348
|
websocketConnectTimeoutMs: z<number, number, "plain">;
|
|
314
349
|
streamIdleTimeoutMs: z<number, number, "defined">;
|
|
315
350
|
maxRequestImageBytes: z<number, number, "defined">;
|
|
351
|
+
maxRequestImages: z<number, number, "defined">;
|
|
352
|
+
imageOffloadCountQuantum: z<number, number, "plain">;
|
|
316
353
|
requestImagePixelBudget: z<number, number, "defined">;
|
|
317
354
|
requestImageMaxBytes: z<number, number, "defined">;
|
|
318
355
|
retryPolicy: z<RetryPolicyConfig>;
|
package/lib/types/context.d.ts
CHANGED
|
@@ -14,6 +14,10 @@ export interface PiImageRequestContext {
|
|
|
14
14
|
resolveImageAccess: ImageAttachmentAccessResolver;
|
|
15
15
|
/** Request-level bound on the base64-encoded payload of retained images; omission leaves the bound unchecked. */
|
|
16
16
|
maxRequestImageBytes?: number;
|
|
17
|
+
/** Request-level bound on retained image occurrences; omission leaves the count unchecked. */
|
|
18
|
+
maxRequestImages?: number;
|
|
19
|
+
/** Oldest occurrences offloaded per count overflow; omission offloads the minimum. */
|
|
20
|
+
imageOffloadCountQuantum?: number;
|
|
17
21
|
/** Route pixel and raw encoded-byte budgets. */
|
|
18
22
|
requestImagePolicy?: PiImageRequestBudget;
|
|
19
23
|
}
|
|
@@ -37,21 +41,24 @@ export declare function requestImageTarget(ref: ImageAttachmentRef, budget: PiIm
|
|
|
37
41
|
* @param options - projected request; one-shot system text precedes the leading history prompt.
|
|
38
42
|
* @param images - absent; selects the synchronous conversion.
|
|
39
43
|
* @param onReplayDegrade - forwarded to {@link toPiAssistant} for each assistant message.
|
|
44
|
+
* @param supportsMidConvoSystemMessages - native model capability; otherwise later system text becomes a user-role system-reminder.
|
|
40
45
|
* @returns the pi-ai context; `tools` is omitted when the request declares none.
|
|
41
46
|
* @throws {LlmError} `UNSUPPORTED_CONTENT` for images in any history role, including a leading system message.
|
|
42
47
|
*/
|
|
43
|
-
export declare function toPiContext(options: GenerateOptions, images?: undefined, onReplayDegrade?: (reason: string) => void): PiContext;
|
|
48
|
+
export declare function toPiContext(options: GenerateOptions, images?: undefined, onReplayDegrade?: (reason: string) => void, supportsMidConvoSystemMessages?: boolean): PiContext;
|
|
44
49
|
/**
|
|
45
50
|
* Convert harness history to a pi-ai Context while resolving durable images.
|
|
46
51
|
* Tool result names are recovered from preceding assistant tool calls. Image
|
|
47
52
|
* occurrences the surface marks offloaded become text placeholders; when the
|
|
48
|
-
* retained occurrences
|
|
49
|
-
* `maxRequestImageBytes`, the call fails with
|
|
50
|
-
* how many more oldest occurrences must be
|
|
53
|
+
* retained occurrences still exceed `maxRequestImages` or their exact base64
|
|
54
|
+
* payload exceeds `maxRequestImageBytes`, the call fails with
|
|
55
|
+
* `IMAGE_OFFLOAD_REQUIRED` naming how many more oldest occurrences must be
|
|
56
|
+
* offloaded, rounded up to `imageOffloadCountQuantum` for a count overflow.
|
|
51
57
|
* @param options - projected request; one-shot system text precedes the leading history prompt.
|
|
52
58
|
* @param images - attachment provider, current path resolver, and request limits.
|
|
53
59
|
* @param onReplayDegrade - forwarded to {@link toPiAssistant} for each assistant message.
|
|
60
|
+
* @param supportsMidConvoSystemMessages - native model capability; otherwise later system text becomes a user-role system-reminder.
|
|
54
61
|
* @returns the asynchronously resolved pi-ai context.
|
|
55
62
|
*/
|
|
56
|
-
export declare function toPiContext(options: GenerateOptions, images: PiImageRequestContext, onReplayDegrade?: (reason: string) => void): Promise<PiContext>;
|
|
63
|
+
export declare function toPiContext(options: GenerateOptions, images: PiImageRequestContext, onReplayDegrade?: (reason: string) => void, supportsMidConvoSystemMessages?: boolean): Promise<PiContext>;
|
|
57
64
|
//# sourceMappingURL=context.d.ts.map
|
package/lib/types/index.d.ts
CHANGED
|
@@ -1,13 +1,33 @@
|
|
|
1
1
|
import type { Context } from '@deepseek-ai/cordis';
|
|
2
2
|
import { Config } from './config.ts';
|
|
3
|
+
import type { PiAiRequestHeaderContext } from './types.ts';
|
|
3
4
|
export { PiAiAdapter } from './adapter.ts';
|
|
4
5
|
export type { PiAiAdapterOptions } from './adapter.ts';
|
|
6
|
+
export type { PiAiRequestHeaderContext } from './types.ts';
|
|
5
7
|
export { Config } from './config.ts';
|
|
6
8
|
export type { Options, PiAiCompatProfile, PiAiModality, PiAiModelOverride, PiAiModelProfile, PiAiProviderProfile, PiAiReasoningEfforts, PiAiThinkingFormat, ResolvedPiAiProviderProfile, } from './config.ts';
|
|
7
9
|
export { recordKeyFor } from './auth.ts';
|
|
8
10
|
export { supportedProtocols } from './provider.ts';
|
|
9
11
|
export declare const name = "llm-pi-ai";
|
|
10
12
|
export declare const inject: string[];
|
|
13
|
+
declare module '@deepseek-ai/cordis' {
|
|
14
|
+
interface Events {
|
|
15
|
+
/**
|
|
16
|
+
* Prepare headers for one pi-ai inference call, excluding model discovery.
|
|
17
|
+
* Listeners run synchronously and must call next(); they may edit only the
|
|
18
|
+
* request-owned headers and must not retain them. Throws fail the call with
|
|
19
|
+
* REQUEST_HEADERS before inference I/O. Harness attribution wins afterward.
|
|
20
|
+
* Non-TypeError messages are user-visible and must exclude secrets. TypeError
|
|
21
|
+
* details and non-Error values are replaced with safe guidance.
|
|
22
|
+
* @mode waterfall
|
|
23
|
+
* @param request - immutable routing metadata from the exact prepared call.
|
|
24
|
+
* @param headers - fresh profile headers, shared only within this dispatch.
|
|
25
|
+
* @param next - continue header preparation through the remaining listeners.
|
|
26
|
+
* @returns headers passed to pi-ai after Harness attribution is applied.
|
|
27
|
+
*/
|
|
28
|
+
'llm-pi-ai/request-headers'(request: PiAiRequestHeaderContext, headers: Headers, next: () => Headers): Headers;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
11
31
|
/** Register one generic pi-ai adapter for all configured provider routes. */
|
|
12
32
|
export declare function apply(ctx: Context, config: Config): void;
|
|
13
33
|
//# sourceMappingURL=index.d.ts.map
|
package/lib/types/stream.d.ts
CHANGED
|
@@ -37,7 +37,9 @@ export declare function mapStopReason(message: AssistantMessage, contextWindow?:
|
|
|
37
37
|
* in-band terminal error an aborted finish.
|
|
38
38
|
* @param requestedModel - request model identity recorded for durable replay.
|
|
39
39
|
* @returns the harness chunks, ending with `usage` then `finish`; throws
|
|
40
|
-
* `LlmError` (`STREAM_CLOSED`) if the source ends without a terminal event
|
|
40
|
+
* `LlmError` (`STREAM_CLOSED`) if the source ends without a terminal event, or
|
|
41
|
+
* `MALFORMED_RESPONSE` when completed tool arguments are invalid. Length-limited
|
|
42
|
+
* output retains its terminal reason so the assembler can discard incomplete calls.
|
|
41
43
|
*/
|
|
42
44
|
export declare function toStreamChunks(events: AsyncIterable<AssistantMessageEvent>, contextWindow?: number, callerSignal?: AbortSignal, requestedModel?: string): AsyncGenerator<StreamChunk>;
|
|
43
45
|
//# sourceMappingURL=stream.d.ts.map
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Request metadata exposed to pi-ai transport-header contributors. */
|
|
2
|
+
import type { GenerateOptions } from '@deepseek-ai/dsh-llm';
|
|
3
|
+
/** Model-hidden routing metadata from the exact prepared adapter call. */
|
|
4
|
+
export interface PiAiRequestHeaderContext extends Readonly<Pick<GenerateOptions<string>, 'provider' | 'model' | 'sessionId' | 'purpose'>> {
|
|
5
|
+
/** Resolved endpoint of the model selected for this call. */
|
|
6
|
+
readonly baseURL: string;
|
|
7
|
+
}
|
|
8
|
+
//# sourceMappingURL=types.d.ts.map
|
package/locale/de.json
ADDED
package/locale/es.json
ADDED
package/locale/fr.json
ADDED
package/locale/ja.json
ADDED
package/locale/pt.json
ADDED
package/locale/ru.json
ADDED
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@deepseek-ai/dsh-llm-pi-ai",
|
|
3
3
|
"description": "pi-ai-backed DeepSeek adapter for the DeepSeek Harness LLM seam (design-verification twin of dsh-llm-deepseek)",
|
|
4
|
-
"version": "0.2.
|
|
4
|
+
"version": "0.2.2-alpha.3",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
7
7
|
},
|
|
@@ -29,36 +29,40 @@
|
|
|
29
29
|
],
|
|
30
30
|
"license": "MIT",
|
|
31
31
|
"peerDependencies": {
|
|
32
|
-
"@deepseek-ai/cordis": "~4.0.
|
|
33
|
-
"@deepseek-ai/
|
|
34
|
-
"@deepseek-ai/dsh-
|
|
35
|
-
"@deepseek-ai/dsh-
|
|
36
|
-
"@deepseek-ai/dsh-
|
|
37
|
-
"@deepseek-ai/dsh-
|
|
38
|
-
"@deepseek-ai/dsh-
|
|
39
|
-
"@deepseek-ai/dsh-
|
|
40
|
-
"@deepseek-ai/
|
|
32
|
+
"@deepseek-ai/cordis": "~4.0.6-alpha.2",
|
|
33
|
+
"@deepseek-ai/cordis-plugin-loader": "~1.0.7-alpha.2",
|
|
34
|
+
"@deepseek-ai/dsh-attachment": "0.2.2-alpha.3",
|
|
35
|
+
"@deepseek-ai/dsh-authorization": "0.2.2-alpha.3",
|
|
36
|
+
"@deepseek-ai/dsh-credentials": "0.2.2-alpha.3",
|
|
37
|
+
"@deepseek-ai/dsh-fs": "0.2.2-alpha.3",
|
|
38
|
+
"@deepseek-ai/dsh-launch-environment": "0.2.2-alpha.3",
|
|
39
|
+
"@deepseek-ai/dsh-llm": "0.2.2-alpha.3",
|
|
40
|
+
"@deepseek-ai/dsh-timeout": "0.2.2-alpha.3"
|
|
41
41
|
},
|
|
42
42
|
"dependencies": {
|
|
43
|
-
"@deepseek-ai/dsh-brand": "0.2.
|
|
44
|
-
"@deepseek-ai/dsh-util-values": "0.2.
|
|
45
|
-
"@deepseek-ai/schemastery": "~3.18.
|
|
46
|
-
"@earendil-works/pi-ai": "^1.
|
|
43
|
+
"@deepseek-ai/dsh-brand": "0.2.2-alpha.3",
|
|
44
|
+
"@deepseek-ai/dsh-util-values": "0.2.2-alpha.3",
|
|
45
|
+
"@deepseek-ai/schemastery": "~3.18.6-alpha.2",
|
|
46
|
+
"@earendil-works/pi-ai": "^1.3.0"
|
|
47
47
|
},
|
|
48
48
|
"devDependencies": {
|
|
49
|
-
"@deepseek-ai/cordis": "~4.0.
|
|
50
|
-
"@deepseek-ai/
|
|
51
|
-
"@deepseek-ai/dsh-
|
|
52
|
-
"@deepseek-ai/dsh-
|
|
53
|
-
"@deepseek-ai/dsh-
|
|
54
|
-
"@deepseek-ai/dsh-
|
|
55
|
-
"@deepseek-ai/dsh-
|
|
56
|
-
"@deepseek-ai/dsh-
|
|
57
|
-
"@deepseek-ai/dsh-
|
|
58
|
-
"@deepseek-ai/dsh-
|
|
59
|
-
"@deepseek-ai/dsh-
|
|
60
|
-
"@deepseek-ai/
|
|
61
|
-
"@deepseek-ai/dsh-
|
|
49
|
+
"@deepseek-ai/cordis": "~4.0.6-alpha.2",
|
|
50
|
+
"@deepseek-ai/cordis-plugin-loader": "~1.0.7-alpha.2",
|
|
51
|
+
"@deepseek-ai/dsh-agent-loop-testkit": "0.2.2-alpha.3",
|
|
52
|
+
"@deepseek-ai/dsh-attachment": "0.2.2-alpha.3",
|
|
53
|
+
"@deepseek-ai/dsh-authorization": "0.2.2-alpha.3",
|
|
54
|
+
"@deepseek-ai/dsh-credentials": "0.2.2-alpha.3",
|
|
55
|
+
"@deepseek-ai/dsh-fs": "0.2.2-alpha.3",
|
|
56
|
+
"@deepseek-ai/dsh-http-proxy": "0.2.2-alpha.3",
|
|
57
|
+
"@deepseek-ai/dsh-launch-environment": "0.2.2-alpha.3",
|
|
58
|
+
"@deepseek-ai/dsh-llm": "0.2.2-alpha.3",
|
|
59
|
+
"@deepseek-ai/dsh-llm-deepseek": "0.2.2-alpha.3",
|
|
60
|
+
"@deepseek-ai/dsh-llm-deepseek-api-key": "0.2.2-alpha.3",
|
|
61
|
+
"@deepseek-ai/dsh-session": "0.2.2-alpha.3",
|
|
62
|
+
"@deepseek-ai/dsh-settings": "0.2.2-alpha.3",
|
|
63
|
+
"@deepseek-ai/dsh-timeout": "0.2.2-alpha.3",
|
|
64
|
+
"@deepseek-ai/dsh-tool-testkit": "0.2.2-alpha.3",
|
|
65
|
+
"@deepseek-ai/dsh-tools": "0.2.2-alpha.3"
|
|
62
66
|
},
|
|
63
67
|
"peerDependenciesMeta": {
|
|
64
68
|
"@deepseek-ai/cordis-plugin-loader": {
|