@vibedev-si/dsh-vibedev 0.11.0 → 0.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,6 +10,28 @@
10
10
 
11
11
  本插件由 `dsh-media` 改名而来,见下面的「从 dsh-media 升级」。
12
12
 
13
+ ## 0.11.2 用户可见更新
14
+
15
+ **音频、视频直接发给模型**:在对话里附上音频或视频文件,声明支持音频/视频的 VibeDev 模型现在能直接「看到」「听到」文件内容,不用再先转写或抽帧。
16
+
17
+ - **哪些模型会收到**:只有走 Chat Completions 协议、且网关目录在 `input_modalities` 里声明了 `audio` / `video` 的模型(例如经网关的 Gemini);声明了哪种就只收哪种。Claude(走 Messages 协议)、GPT(走 Responses 协议)以及没有声明的模型不会收到文件字节,照旧只收到文件说明(文件名、大小和只读保存路径),可以用工具去读。
18
+ - **怎么发**:文件按 OpenAI 兼容格式 `{"type":"file","file":{"file_data":"data:video/mp4;base64,…"}}` 紧跟在它的文件说明后面发出,由网关转成上游自己的格式(Gemini 的 `inlineData` 等)。
19
+ - **历史媒体不重发**:音视频只在它到达的那一轮随请求发送(旧宿主上是最近一条带文件的消息);之后的轮次只保留文件说明,不会每轮重复上传、重复计费。模型需要再看时,宿主提供的读媒体工具(`read_media`)会把它重新读进当轮。
20
+ - **工具结果里的媒体**:模型用工具读到的音视频(例如 `read_media`)也会直接发给模型。Chat Completions 的 `tool` 消息只能放文字,所以工具消息里只留文件说明,文件本体放在这组工具结果后面紧跟的一条 `user` 消息里:`{"role":"user","content":[{"type":"text","text":"Attached media from tool result:"},{"type":"file","file":{"file_data":"data:video/mp4;base64,…"}}]}`;同一组工具结果里还有图片时,直接追加到 pi-ai 的「Attached image(s) from tool result:」那条消息里。网关把它转成 Gemini 的 `functionResponse` + `inlineData`。
21
+ - **只发 Gemini 认的格式**:嗅探出的类型必须是 `video/mp4`、`video/mpeg`、`video/quicktime`、`video/x-msvideo`、`video/x-flv`、`video/webm`、`video/x-ms-wmv`、`video/3gpp`、`audio/mpeg`、`audio/wav`、`audio/aiff`、`audio/aac`、`audio/ogg`、`audio/flac` 之一;mkv、m4a、opus、amr、wma 等只发文件说明、记一条警告,不报错。插件把这份名单交给宿主,并在读出文件后自己再查一次,所以不认识这项设置的旧宿主上也一样。
22
+ - **超限退化**:单个文件超过 14 MiB、或一次请求的音视频 base64 总量超过 20 MiB(超出时先舍弃较早的文件)、读取文件失败、宿主不支持时,这个文件退回为只发文件说明,并在日志里记一条警告;对话不会因此报错。
23
+ - **计费提示**:音视频按模型的输入计费,通常比同样内容的文字贵得多(视频尤其明显),费用以 VibeDev 网关回执为准。不需要模型直接理解内容时,换一个不声明音视频的模型即可只发文件说明。
24
+ - **需要宿主支持**:这项功能要宿主(VibeDev 桌面版所带的 DeepSeek Harness)提供原生文件投递;在不支持的宿主上插件照常工作,音视频只发文件说明,不会报错。
25
+ - **VibeDev 桌面版**:用桌面版自己的 VibeDev 账号登录时,模型由桌面版的账号通道提供,插件的 VibeDev 模型组为空,这项改动只影响插件自己的登录(或开发密钥)下列出的模型。
26
+
27
+ ## 0.11.1 用户可见更新
28
+
29
+ 兼容 DSH 0.2.3:修复发送图片失败。桌面版升级到 DeepSeek Harness 0.2.3 后,用 VibeDev 网关的模型发一张图片,那一轮会失败,并提示 `Image request maxImageBytes must be a positive integer.`;图片留在对话里后,之后每一轮和 `/compact` 也会失败。0.11.1 修好了这些,改版后不需要清理或重发对话。
30
+
31
+ - **图片**:请求图片的大小上限同时按 0.2.3 的新规则和 0.2.2-rc.5 的旧规则给出,每张图片仍限制在 1 MiB 以内(超过时会继续缩小)。DeepSeek Harness 0.2.2-rc.5 及以上继续可用。
32
+ - **系统提示**:0.2.3 把系统提示按段落分别保存,插件原来把它们直接连在一起;现在按空行分隔,之后补充的系统指令以「系统提醒」的形式发给模型,不再混作你说的话。
33
+ - **Computer Use 截图**:Computer Use 取截图尺寸用的是插件给出的同一套图片预算,截图只缩一次,模型看到的尺寸和点击坐标一致。
34
+ - **凭据**:向 VibeDev 网关取宿主登录凭据时,优先使用 0.2.3 的公开接口,找不到时才用旧接口;两者都没有时回退到插件自己的登录,不会让所有请求都取不到凭据。
13
35
  ## 0.11.0 用户可见更新
14
36
 
15
37
  - **公告改叫「通知」**:账户中心的「消息」页改名为「通知」,账号菜单里的那一行也一起改,例如「通知(3)」;行上的未读提示写「3 条未读通知」,空的时候写「还没有未读通知」,公告弹窗里的按钮是「查看全部通知」。弹窗标题仍是「VibeDev 公告」。改名是为了和 VibeDev 桌面的聊天「消息」分开;公告内容、红点和已读规则都不变。英文界面是 Notifications。
@@ -437,7 +459,7 @@ npm run build
437
459
 
438
460
  ## 第三方代码
439
461
 
440
- `src/llm/` 的模型线路移植自 VibeDev 应用;其中 `context.ts`、`replay.ts`、`stream.ts` 复制自 DeepSeek Harness 的 `@deepseek-ai/dsh-llm-pi-ai`(MIT)。打包进来的 pi-ai、Anthropic SDK、OpenAI SDK 等的许可文本见包内的 `THIRD-PARTY-NOTICES.txt`。
462
+ `src/llm/` 的模型线路移植自 VibeDev 应用;其中 `context.ts`、`replay.ts`、`stream.ts` 复制自 DeepSeek Harness 的 `@deepseek-ai/dsh-llm-pi-ai`(MIT),`native-files.ts` 改编自它的 VibeDev 分支。打包进来的 pi-ai、Anthropic SDK、OpenAI SDK 等的许可文本见包内的 `THIRD-PARTY-NOTICES.txt`。
441
463
 
442
464
  ---
443
465
 
@@ -445,6 +467,28 @@ npm run build
445
467
 
446
468
  ## English
447
469
 
470
+ ### What changes in 0.11.2
471
+
472
+ **Audio and video reach the model directly**: attach an audio or video file in the chat, and VibeDev models that declare audio/video input now take the file's content itself, with no transcription or frame extraction first.
473
+
474
+ - **Which models receive it**: only models called over Chat Completions whose gateway catalog entry lists `audio` / `video` in `input_modalities` (Gemini through the gateway, for example), and only the kinds they declare. Claude (over Messages), GPT (over Responses) and models that declare neither receive no file bytes; they get the file's handle text as before (name, size and the read-only saved path) and can read it with tools.
475
+ - **How it is sent**: the file follows its handle text as an OpenAI-compatible part, `{"type":"file","file":{"file_data":"data:video/mp4;base64,…"}}`, which the gateway turns into the upstream provider's own form (Gemini `inlineData`, say).
476
+ - **Earlier media is not re-sent**: audio/video travels only with the requests of the turn it arrived in (on older hosts, the latest message carrying files); later turns keep only its handle text, so it is not uploaded or billed again every turn. When the model needs it again, the host's media-reading tool (`read_media`) reads it back into the current turn.
477
+ - **Media in tool results**: audio/video a tool reads for the model (`read_media`, say) reaches the model directly too. A Chat Completions `tool` message holds text only, so the tool message keeps the handle text and the file itself goes in the `user` message right after that run of tool results: `{"role":"user","content":[{"type":"text","text":"Attached media from tool result:"},{"type":"file","file":{"file_data":"data:video/mp4;base64,…"}}]}`; when those tool results also carry images, it joins pi-ai's "Attached image(s) from tool result:" message instead. The gateway turns it into Gemini's `functionResponse` plus `inlineData`.
478
+ - **Only formats Gemini takes**: the sniffed type must be one of `video/mp4`, `video/mpeg`, `video/quicktime`, `video/x-msvideo`, `video/x-flv`, `video/webm`, `video/x-ms-wmv`, `video/3gpp`, `audio/mpeg`, `audio/wav`, `audio/aiff`, `audio/aac`, `audio/ogg`, `audio/flac`; MKV, M4A, Opus, AMR, WMA and the like go as handle text with a warning, never as an error. The plugin hands this list to the host and checks it again after the read, so hosts that do not know the setting behave the same.
479
+ - **Over a limit, it degrades**: a file over 14 MiB, a request whose audio/video base64 would exceed 20 MiB (the earliest files are dropped first), a failed read or a host without support all send that file as its handle text alone, with a warning in the log; the conversation never fails because of it.
480
+ - **Billing**: audio and video are billed as model input and usually cost far more than the same content as text (video especially); the VibeDev gateway receipt is authoritative. When the model need not take the content directly, pick a model that does not declare audio/video and only the handle text is sent.
481
+ - **Needs host support**: native file delivery is provided by the host (the DeepSeek Harness inside the VibeDev desktop). On a host without it the plugin works as before and audio/video go as handle text, without errors.
482
+ - **VibeDev desktop**: signed in with the desktop's own VibeDev account, the desktop's account channel serves the models and the plugin's VibeDev group stays empty; this change applies to the models the plugin lists under its own sign-in (or a development key).
483
+
484
+ ### What changes in 0.11.1
485
+
486
+ Compatible with DSH 0.2.3: fixes sending images. After the desktop app moved to DeepSeek Harness 0.2.3, sending a picture with a VibeDev gateway model failed that turn with `Image request maxImageBytes must be a positive integer.`; once the picture was in the conversation, every later turn and `/compact` failed too. 0.11.1 fixes this; no need to clear or resend the conversation.
487
+
488
+ - **Images**: the request-image size limit is now given in both the 0.2.3 shape and the 0.2.2-rc.5 shape, and each image stays within 1 MiB (a larger one is shrunk further). DeepSeek Harness 0.2.2-rc.5 and later keep working.
489
+ - **System prompt**: 0.2.3 stores the system prompt one section at a time, and the plugin used to run the sections together. They are now separated by a blank line, and system instructions added later reach the model as a system reminder instead of looking like something you said.
490
+ - **Computer Use screenshots**: Computer Use now sizes a screenshot with the same image budget the plugin uses for the request, so a screenshot is shrunk once and the coordinates the model sees match the click targets.
491
+ - **Credentials**: the host's signed-in credential for the VibeDev gateway is read through 0.2.3's public interface first and the older one only when that is missing; with neither, the plugin's own sign-in answers instead of every request losing its credential.
448
492
  ### What changes in 0.11.0
449
493
 
450
494
  - **Announcements are now Notifications**: the account center's Messages page is renamed Notifications (通知), and so is its row in the account menus, for example "Notifications (3)". The row's unread hint says "3 unread notifications", an empty page says "No unread notifications", and the announcement dialog's button says "See all notifications". The dialog title stays "VibeDev announcement". The rename keeps announcements apart from the VibeDev desktop's chat, which is called Messages; content, the red dot and the read rules are unchanged.
@@ -659,7 +703,7 @@ For explicit joint acceptance, run node scripts/verify-fetch-joint.mjs with one
659
703
 
660
704
  **For other plugins**: the `vibedevMedia` service generates images, videos and audio (`startAudio`: music, podcasts and speech) through the same model choice, reference checks, idempotent submission and background saving; the film workbench ([dsh-film](https://github.com/VibeDev-Si/dsh-film)) storyboard uses it. `models()` lists the account's media models; an image model carries the size tiers and ratios it declares (`imageSizes`, `imageRatios`). `audioForms()` describes the form of each audio model (only its declared fields, choices and limits, and its price). `videoQuote(request)` quotes a video request from the cached catalog alone (no upload, no submission): a video Token estimate with its rule and basis, a legacy estimate, or why there is none. Task views carry `settlement`, `settlementPendingReason`, `chargedCny` (only once settled, exactly as the gateway wrote it) and `billing.tokens`. Every task is read the same way: `task` (as recorded), `refreshTask` (ask the gateway again — fresh links, settlement; same-key recovery while unconfirmed; query only after a task ID is known), `onTask` (each change) and `result` (the files to play or download). Pass the same `operationId` when one click is retried: the recorded task is returned or checked under its original key and saved body; no new operation is created.
661
705
 
662
- **Third-party code**: the model route in `src/llm/` is ported from the VibeDev app; `context.ts`, `replay.ts` and `stream.ts` are copied from DeepSeek Harness's `@deepseek-ai/dsh-llm-pi-ai` (MIT). The licences of the bundled pi-ai, Anthropic SDK, OpenAI SDK and their dependencies are in `THIRD-PARTY-NOTICES.txt`.
706
+ **Third-party code**: the model route in `src/llm/` is ported from the VibeDev app; `context.ts`, `replay.ts` and `stream.ts` are copied from DeepSeek Harness's `@deepseek-ai/dsh-llm-pi-ai` (MIT), and `native-files.ts` is adapted from its VibeDev fork. The licences of the bundled pi-ai, Anthropic SDK, OpenAI SDK and their dependencies are in `THIRD-PARTY-NOTICES.txt`.
663
707
 
664
708
  ### One-step chat consent: `vibedevDesktopChatConsent` (0.11.0)
665
709
 
@@ -1,4 +1,4 @@
1
- THIRD-PARTY NOTICES · @vibedev-si/dsh-vibedev 0.11.0
1
+ THIRD-PARTY NOTICES · @vibedev-si/dsh-vibedev 0.11.2
2
2
 
3
3
  This package bundles code from the projects below. Each is used under the licence that
4
4
  follows its name; the licence texts are reproduced as the projects ship them.
@@ -7,8 +7,8 @@ follows its name; the licence texts are reproduced as the projects ship them.
7
7
  DeepSeek Harness — @deepseek-ai/dsh-llm-pi-ai (MIT)
8
8
  https://github.com/deepseek-ai/deepseek-harness
9
9
  src/llm/context.ts, src/llm/replay.ts and src/llm/stream.ts (bundled into lib/) are copied from
10
- @deepseek-ai/dsh-llm-pi-ai (dsh-v0.2.0-rc.2), and the bundled pi-ai carries the Harness's
11
- patch to its streaming tool-argument parsing.
10
+ @deepseek-ai/dsh-llm-pi-ai (dsh-v0.2.0-rc.2), src/llm/native-files.ts is adapted from its VibeDev
11
+ fork, and the bundled pi-ai carries the Harness's patch to its streaming tool-argument parsing.
12
12
  ==============================================================================
13
13
  MIT License
14
14
 
@@ -24,6 +24,8 @@ export interface CredentialChainOptions {
24
24
  /** Resolves the credential for each request and routes rejections back to its owner. */
25
25
  export declare class CredentialChain {
26
26
  private readonly options;
27
+ /** The host credential released last through `resolveRequestCredential`, so a rejection can use its own invalidation. */
28
+ private released;
27
29
  /**
28
30
  * @param options - origin and the three sources.
29
31
  */
@@ -35,6 +37,12 @@ export declare class CredentialChain {
35
37
  * @param credential - the rejected credential.
36
38
  */
37
39
  reject(credential: GatewayCredential): Promise<void>;
40
+ /**
41
+ * The host account's token for the gateway, whichever way this DSH release offers it. A host that offers neither
42
+ * method, or whose lookup fails (synchronously or not), yields nothing and the chain moves on to the plugin's own sign-in.
43
+ */
44
+ private hostedToken;
45
+ private rejectHosted;
38
46
  }
39
47
  /** Credential identity for one gateway; never consult another gateway's record. */
40
48
  export declare function gatewayGrantKey(origin: string): import("@deepseek-ai/dsh-credentials").CredentialKey;
package/lib/index.js CHANGED
@@ -2,6 +2,7 @@ import { p as lazyApi, r as createModels$1 } from "./models-CAcLevEN.js";
2
2
  import { createWriteStream, readFileSync } from "node:fs";
3
3
  import Schema from "@deepseek-ai/schemastery";
4
4
  import { createHash, randomBytes, randomUUID } from "node:crypto";
5
+ import * as dshLlm from "@deepseek-ai/dsh-llm";
5
6
  import { APP_IDENTITY, CONTEXT_WINDOW_EXCEEDED_CODE, EMPTY_RESPONSE_CODE, HarnessError, IMAGE_OFFLOAD_REQUIRED_CODE, LlmAdapter, LlmError, QUOTA_EXCEEDED_CODE, ReasoningEffortId, attributionHeaders, contentHasImage, isContextWindowExceededError, isQuotaExceededError, offloadedImageText, projectOffloadedImages, requestImageHandleText, requiredImageOffload, resolveImageAttachmentAccess } from "@deepseek-ai/dsh-llm";
6
7
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
7
8
  import { arch, homedir, platform, release } from "node:os";
@@ -4882,9 +4883,13 @@ function developmentKey(origin, name, env = process.env) {
4882
4883
  * key named by an environment variable.
4883
4884
  * @module dsh-vibedev/auth/credentials
4884
4885
  */
4886
+ /** The header `resolveRequestCredential` carries the account token in (`ACCOUNT_TOKEN_HEADER` of the 0.2.3 account service). */
4887
+ const HOST_ACCOUNT_TOKEN_HEADER = "x-dsh-auth-token";
4885
4888
  /** Resolves the credential for each request and routes rejections back to its owner. */
4886
4889
  var CredentialChain = class {
4887
4890
  options;
4891
+ /** The host credential released last through `resolveRequestCredential`, so a rejection can use its own invalidation. */
4892
+ released;
4888
4893
  /**
4889
4894
  * @param options - origin and the three sources.
4890
4895
  */
@@ -4893,7 +4898,7 @@ var CredentialChain = class {
4893
4898
  }
4894
4899
  /** The credential for the next request, or undefined while nobody is signed in. */
4895
4900
  async resolve() {
4896
- const hosted = await this.options.account()?.resolveToken(`${this.options.origin.replace(/\/+$/, "")}/v1/models`).catch(() => void 0);
4901
+ const hosted = await this.hostedToken(`${this.options.origin.replace(/\/+$/, "")}/v1/models`);
4897
4902
  if (hosted !== void 0 && hosted !== "") return {
4898
4903
  token: hosted,
4899
4904
  kind: "account"
@@ -4914,9 +4919,42 @@ var CredentialChain = class {
4914
4919
  * @param credential - the rejected credential.
4915
4920
  */
4916
4921
  async reject(credential) {
4917
- if (credential.kind === "account") await this.options.account()?.rejectToken(credential.token);
4922
+ if (credential.kind === "account") await this.rejectHosted(credential.token);
4918
4923
  else if (credential.kind === "plugin") await this.options.plugin?.reject(credential.token);
4919
4924
  }
4925
+ /**
4926
+ * The host account's token for the gateway, whichever way this DSH release offers it. A host that offers neither
4927
+ * method, or whose lookup fails (synchronously or not), yields nothing and the chain moves on to the plugin's own sign-in.
4928
+ */
4929
+ async hostedToken(url) {
4930
+ const account = this.options.account();
4931
+ if (account === void 0) return void 0;
4932
+ try {
4933
+ if (typeof account.resolveRequestCredential === "function") {
4934
+ const credential = await account.resolveRequestCredential(url);
4935
+ if (credential === void 0) return void 0;
4936
+ const token = credential.headers[HOST_ACCOUNT_TOKEN_HEADER];
4937
+ if (typeof token === "string" && token !== "") {
4938
+ this.released = {
4939
+ token,
4940
+ reject: () => credential.reject()
4941
+ };
4942
+ return token;
4943
+ }
4944
+ }
4945
+ if (typeof account.resolveToken === "function") return await account.resolveToken(url);
4946
+ } catch {}
4947
+ }
4948
+ async rejectHosted(token) {
4949
+ const released = this.released;
4950
+ if (released?.token === token) {
4951
+ this.released = void 0;
4952
+ await released.reject();
4953
+ return;
4954
+ }
4955
+ const account = this.options.account();
4956
+ if (typeof account?.rejectToken === "function") await account.rejectToken(token);
4957
+ }
4920
4958
  };
4921
4959
  /** Credential identity for one gateway; never consult another gateway's record. */
4922
4960
  function gatewayGrantKey(origin) {
@@ -5631,7 +5669,12 @@ var PluginLogin = class {
5631
5669
  const DEFAULT_MAX_REQUEST_IMAGE_BYTES = 20971520;
5632
5670
  /** Total-pixel budget that preserves the complete 2048px normalized attachment. */
5633
5671
  const DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET = 4194304;
5634
- /** Raw encoded-byte target before inline base64 expansion. */
5672
+ /**
5673
+ * Raw encoded bytes allowed for one request image, before inline base64 expansion. A hard limit under DSH 0.2.3 (a larger
5674
+ * encoding is shrunk further; that is also the preferred size) and a target under rc.5. DSH's pi-ai default is 0.75 MiB
5675
+ * (a 20 MiB request over 20 images); 1 MiB keeps what 0.11.0 sent, and the oldest images are offloaded when the request
5676
+ * exceeds `DEFAULT_MAX_REQUEST_IMAGE_BYTES`.
5677
+ */
5635
5678
  const DEFAULT_REQUEST_IMAGE_MAX_BYTES = 1048576;
5636
5679
  //#endregion
5637
5680
  //#region src/llm/relay.ts
@@ -5705,6 +5748,8 @@ const REASONING_LEVELS = [
5705
5748
  "xhigh",
5706
5749
  "max"
5707
5750
  ];
5751
+ /** The file kinds a model can take natively, in the order `nativeMedia` lists them. */
5752
+ const NATIVE_MEDIA = ["audio", "video"];
5708
5753
  /** The endpoint each protocol is called on, as `allowed_endpoints` lists it. */
5709
5754
  const ENDPOINT = {
5710
5755
  "anthropic-messages": "/v1/messages",
@@ -5786,6 +5831,7 @@ function parseCatalog(body) {
5786
5831
  const levels = reasoningLevelsOf(capabilities.reasoning_levels);
5787
5832
  const defaultReasoning = typeof capabilities.default_reasoning === "string" && levels?.includes(capabilities.default_reasoning) ? capabilities.default_reasoning : void 0;
5788
5833
  const inputs = strings$1(capabilities.input_modalities) ?? [];
5834
+ const nativeMedia = api === "openai-completions" ? NATIVE_MEDIA.filter((kind) => inputs.includes(kind)) : [];
5789
5835
  const maxInputTokens = positive$2(capabilities.max_input_tokens);
5790
5836
  const rawFamily = record$8(entry.model_family);
5791
5837
  const familyId = typeof rawFamily?.id === "string" ? rawFamily.id.trim() : "";
@@ -5803,6 +5849,7 @@ function parseCatalog(body) {
5803
5849
  ...maxInputTokens === void 0 ? {} : { maxInputTokens },
5804
5850
  maxTokens: positive$2(capabilities.max_output_tokens) ?? 32768,
5805
5851
  input: inputs.includes("image") ? ["text", "image"] : ["text"],
5852
+ ...nativeMedia.length === 0 ? {} : { nativeMedia },
5806
5853
  ...levels === void 0 ? {} : { reasoningLevels: levels },
5807
5854
  ...defaultReasoning === void 0 ? {} : { defaultReasoning },
5808
5855
  adaptiveThinking: capabilities.adaptive_thinking === true,
@@ -6069,6 +6116,313 @@ function toPiAssistant(message, onDegrade) {
6069
6116
  }
6070
6117
  }
6071
6118
  //#endregion
6119
+ //#region src/llm/native-files.ts
6120
+ /**
6121
+ * Native audio/video delivery for the gateway's Chat Completions models.
6122
+ *
6123
+ * Adapted from the VibeDev fork of DeepSeek Harness `@deepseek-ai/dsh-llm-pi-ai` (src/native-files.ts, vibedev
6124
+ * 5be6bcec; MIT, Copyright (c) 2026 DeepSeek — see THIRD-PARTY-NOTICES.txt). Keep it in step with upstream.
6125
+ *
6126
+ * Request assembly (the host's LLM runtime) decides which audio/video occurrences a request carries natively: the
6127
+ * current turn's user messages and tool results (DSH 0.2.3-era VibeDev hosts: only the latest user message that
6128
+ * carries files), only kinds the model declares, within 14 MiB per file and 20 MiB of base64 per request, and never
6129
+ * for an auxiliary call. It leaves each kept `{type:'file'}` block right after the file's handle text. This module
6130
+ * reads the kept files' bytes and serializes them; it decides nothing beyond a defensive re-check of the same size
6131
+ * ceilings and of the media types the gateway's models take ({@link GEMINI_INLINE_MEDIA_TYPES}).
6132
+ *
6133
+ * pi-ai's Context has no file content, so conversion leaves one marker text part where each delivered file belongs
6134
+ * and the payload hook swaps every marker for an OpenAI-compatible `file` content part carrying the bytes as a data
6135
+ * URL: `{"type":"file","file":{"file_data":"data:<mediaType>;base64,<…>"}}`. The gateway turns it into the
6136
+ * provider's own form (Gemini `inlineData`, say). A Chat Completions `tool` message carries text only, so a file in a
6137
+ * tool result moves to a `user` message right after that run of tool messages, the way pi-ai sends tool-result
6138
+ * images (see {@link injectNativeFiles}).
6139
+ *
6140
+ * Nothing here can fail a request: a file without a target, a host without `readFileRequest`, a read that fails or
6141
+ * a file over a ceiling all fall back to the handle text that is already in the message, with a warning. Only
6142
+ * cancellation propagates.
6143
+ *
6144
+ * Hosts whose `@deepseek-ai/dsh-llm` and `@deepseek-ai/dsh-attachment` predate native files (DSH 0.2.2-rc.5,
6145
+ * upstream 0.2.3) never keep a file block, so none of this runs there; the types the newer packages declare are
6146
+ * restated structurally below so the plugin builds and loads against either.
6147
+ *
6148
+ * @module dsh-vibedev/llm/native-files
6149
+ */
6150
+ /**
6151
+ * A named export of `@deepseek-ai/dsh-llm` that older hosts do not have. Read off the module namespace, never as a
6152
+ * named import: a missing named import of an ES module fails the plugin's whole load, a missing namespace member is
6153
+ * just undefined.
6154
+ */
6155
+ function hostNumber(name) {
6156
+ const value = dshLlm[name];
6157
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
6158
+ }
6159
+ /** Raw-byte ceiling for one natively delivered file: the host's `NATIVE_FILE_MAX_BYTES`, 14 MiB where it has none. */
6160
+ const NATIVE_FILE_MAX_BYTES = hostNumber("NATIVE_FILE_MAX_BYTES") ?? 14680064;
6161
+ /** Ceiling on the base64 total of a request's native files: the host's own, 20 MiB where it has none. */
6162
+ const NATIVE_FILE_MAX_REQUEST_BASE64_BYTES = hostNumber("NATIVE_FILE_MAX_REQUEST_BASE64_BYTES") ?? 20971520;
6163
+ /**
6164
+ * Media types the gateway's Chat Completions models take inline: the containers Gemini documents for inline
6165
+ * audio/video, spelled as the host's `sniffFileMediaType` spells them. Anything else (Matroska, M4A, Opus, AMR,
6166
+ * WMA, …) keeps its handle text only: one type the provider refuses would fail the whole request.
6167
+ */
6168
+ const GEMINI_INLINE_MEDIA_TYPES = Object.freeze([
6169
+ "video/mp4",
6170
+ "video/mpeg",
6171
+ "video/quicktime",
6172
+ "video/x-msvideo",
6173
+ "video/x-flv",
6174
+ "video/webm",
6175
+ "video/x-ms-wmv",
6176
+ "video/3gpp",
6177
+ "audio/mpeg",
6178
+ "audio/wav",
6179
+ "audio/aiff",
6180
+ "audio/aac",
6181
+ "audio/ogg",
6182
+ "audio/flac"
6183
+ ]);
6184
+ /** Text that opens the user message carrying tool-result media. */
6185
+ const TOOL_RESULT_MEDIA_TEXT = "Attached media from tool result:";
6186
+ /** Text pi-ai opens its tool-result image follow-up with; media joins that message. */
6187
+ const PI_TOOL_RESULT_IMAGE_TEXT = "Attached image(s) from tool result:";
6188
+ /** pi-ai's bridge between tool results and a user message under `requiresAssistantAfterToolResult`. */
6189
+ const PI_TOOL_RESULT_BRIDGE = "I have processed the tool results.";
6190
+ /**
6191
+ * Text part that holds one delivered file's place until the payload hook replaces it. Deterministic, so identical
6192
+ * histories convert identically, and NUL-delimited, so no user-authored text block equals it.
6193
+ * @param index - position in {@link PiFileRequestContext.delivered}.
6194
+ * @returns the marker text.
6195
+ */
6196
+ function nativeFileMarker(index) {
6197
+ return `\u0000dsh-native-file:${index}\u0000`;
6198
+ }
6199
+ /** Length of the base64 encoding of `bytes` raw bytes. */
6200
+ function base64Length(bytes) {
6201
+ return Math.ceil(bytes / 3) * 4;
6202
+ }
6203
+ /**
6204
+ * Read every file the request delivers natively, once per attachment. A file whose target is gone, whose read fails
6205
+ * (the host's `ATTACHMENT_PROJECTION_UNSUPPORTED` for a media type outside the target's list included), whose sniffed
6206
+ * media type the target does not accept, or that breaks a ceiling is left out, so its occurrences keep only their
6207
+ * handle text; cancellation still propagates. When the base64 total of the occurrences read exceeds
6208
+ * {@link NATIVE_FILE_MAX_REQUEST_BASE64_BYTES} (a host that did not budget them), the earliest files are left out
6209
+ * first, as request assembly would.
6210
+ * @param messages - converted history; user- and tool-role file blocks are read.
6211
+ * @param attachments - durable provider of the verbatim bytes.
6212
+ * @param files - route target and degrade observer.
6213
+ * @param signal - request cancellation.
6214
+ * @returns request bytes by attachment id.
6215
+ */
6216
+ async function readNativeFiles(messages, attachments, files, signal) {
6217
+ const refs = /* @__PURE__ */ new Map();
6218
+ const occurrences = /* @__PURE__ */ new Map();
6219
+ for (const message of messages) {
6220
+ if (message.role !== "user" && message.role !== "tool") continue;
6221
+ for (const block of message.content) {
6222
+ if (block.type !== "file") continue;
6223
+ const id = block.attachment.attachmentId;
6224
+ if (!refs.has(id)) refs.set(id, block.attachment);
6225
+ occurrences.set(id, (occurrences.get(id) ?? 0) + 1);
6226
+ }
6227
+ }
6228
+ const read = /* @__PURE__ */ new Map();
6229
+ if (refs.size === 0) return read;
6230
+ const readFileRequest = attachments.readFileRequest;
6231
+ if (typeof readFileRequest !== "function") {
6232
+ for (const ref of refs.values()) files.onDegrade?.(ref, "the attachment provider cannot read request files");
6233
+ return read;
6234
+ }
6235
+ for (const [id, ref] of refs) {
6236
+ let target;
6237
+ try {
6238
+ target = files.target(ref);
6239
+ } catch {
6240
+ target = void 0;
6241
+ }
6242
+ if (target === void 0) {
6243
+ files.onDegrade?.(ref, "the route offers no native file target");
6244
+ continue;
6245
+ }
6246
+ const maxBytes = Math.min(target.maxBytes, NATIVE_FILE_MAX_BYTES);
6247
+ if (ref.bytes > maxBytes) {
6248
+ files.onDegrade?.(ref, `the file has ${ref.bytes} bytes, over the ${maxBytes}-byte native file limit`);
6249
+ continue;
6250
+ }
6251
+ try {
6252
+ const file = await readFileRequest.call(attachments, ref, {
6253
+ ...target,
6254
+ maxBytes
6255
+ }, signal);
6256
+ if (!(file.data instanceof Uint8Array) || typeof file.mediaType !== "string" || file.mediaType === "") throw new Error("the attachment provider returned no bytes or media type");
6257
+ if (file.data.byteLength > maxBytes) throw new Error(`the file read has ${file.data.byteLength} bytes, over the ${maxBytes}-byte native file limit`);
6258
+ if (!(target.mediaTypes ?? GEMINI_INLINE_MEDIA_TYPES).includes(file.mediaType)) throw new Error(`the route does not accept media type ${file.mediaType}`);
6259
+ read.set(id, file);
6260
+ } catch (error) {
6261
+ signal?.throwIfAborted();
6262
+ files.onDegrade?.(ref, error instanceof Error ? error.message : String(error));
6263
+ }
6264
+ }
6265
+ const order = [...read.keys()];
6266
+ let total = order.reduce((sum, id) => sum + base64Length(read.get(id).data.byteLength) * (occurrences.get(id) ?? 1), 0);
6267
+ for (const id of order) {
6268
+ if (total <= NATIVE_FILE_MAX_REQUEST_BASE64_BYTES) break;
6269
+ const file = read.get(id);
6270
+ total -= base64Length(file.data.byteLength) * (occurrences.get(id) ?? 1);
6271
+ read.delete(id);
6272
+ files.onDegrade?.(file.attachment, `the request's native files exceed the ${NATIVE_FILE_MAX_REQUEST_BASE64_BYTES}-byte base64 budget`);
6273
+ }
6274
+ return read;
6275
+ }
6276
+ /**
6277
+ * The Chat Completions content part for one delivered file.
6278
+ * @param file - bytes and sniffed media type.
6279
+ * @returns the part the gateway accepts.
6280
+ */
6281
+ function nativeFilePart(file) {
6282
+ return {
6283
+ type: "file",
6284
+ file: { file_data: `data:${file.mediaType};base64,${Buffer.from(file.data.buffer, file.data.byteOffset, file.data.byteLength).toString("base64")}` }
6285
+ };
6286
+ }
6287
+ function isRecord$1(value) {
6288
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6289
+ }
6290
+ function isToolMessage(message) {
6291
+ return isRecord$1(message) && message.role === "tool";
6292
+ }
6293
+ /** pi-ai's tool-result image follow-up, whose image parts the moved media joins. */
6294
+ function isImageFollowUp(message) {
6295
+ if (!isRecord$1(message) || message.role !== "user" || !Array.isArray(message.content)) return false;
6296
+ const first = message.content[0];
6297
+ return isRecord$1(first) && first.type === "text" && first.text === PI_TOOL_RESULT_IMAGE_TEXT;
6298
+ }
6299
+ function isToolResultBridge(message) {
6300
+ return isRecord$1(message) && message.role === "assistant" && message.content === PI_TOOL_RESULT_BRIDGE;
6301
+ }
6302
+ /**
6303
+ * Take the markers out of one tool message. pi-ai joins a tool result's text parts with newlines and each marker is a
6304
+ * part of its own (the conversion puts them after the result's text), so dropping the marker lines leaves exactly
6305
+ * the text the result has without its files.
6306
+ */
6307
+ function stripToolMarkers(message, markers) {
6308
+ const files = [];
6309
+ const content = message.content;
6310
+ if (typeof content === "string") {
6311
+ if (!content.includes("\0")) return {
6312
+ message,
6313
+ files
6314
+ };
6315
+ const lines = content.split("\n").filter((line) => {
6316
+ const file = markers.get(line);
6317
+ if (file !== void 0) files.push(file);
6318
+ return file === void 0;
6319
+ });
6320
+ if (files.length === 0) return {
6321
+ message,
6322
+ files
6323
+ };
6324
+ const text = lines.join("\n");
6325
+ return {
6326
+ message: {
6327
+ ...message,
6328
+ content: text.length > 0 ? text : "(see attached media)"
6329
+ },
6330
+ files
6331
+ };
6332
+ }
6333
+ if (Array.isArray(content)) {
6334
+ const parts = content.filter((part) => {
6335
+ const file = isRecord$1(part) && part.type === "text" && typeof part.text === "string" ? markers.get(part.text) : void 0;
6336
+ if (file !== void 0) files.push(file);
6337
+ return file === void 0;
6338
+ });
6339
+ if (files.length > 0) return {
6340
+ message: {
6341
+ ...message,
6342
+ content: parts
6343
+ },
6344
+ files
6345
+ };
6346
+ }
6347
+ return {
6348
+ message,
6349
+ files
6350
+ };
6351
+ }
6352
+ /**
6353
+ * Put every delivered file part into a Chat Completions payload. A marker part in a user message becomes the file
6354
+ * part in place. A Chat Completions `tool` message holds text only, so markers in a run of consecutive `tool`
6355
+ * messages leave the tool text (the handle text stays) and their parts, in tool-result then block order, go to the
6356
+ * user message right after the run: appended to pi-ai's "Attached image(s) from tool result:" message when pi-ai
6357
+ * added one, otherwise in a new `{role:'user',content:[{type:'text',text:'Attached media from tool result:'},…]}`,
6358
+ * preceded by pi-ai's bridging assistant message when the model requires one.
6359
+ * @param payload - the request body pi-ai built.
6360
+ * @param delivered - file parts by marker index.
6361
+ * @param options - the model's tool-result ordering rule.
6362
+ * @returns a shallow-copied payload, or undefined to keep it when no marker is present.
6363
+ */
6364
+ function injectNativeFiles(payload, delivered, options = {}) {
6365
+ if (delivered.length === 0 || !isRecord$1(payload) || !Array.isArray(payload.messages)) return void 0;
6366
+ const markers = new Map(delivered.map((part, index) => [nativeFileMarker(index), part]));
6367
+ const fileOf = (part) => isRecord$1(part) && part.type === "text" && typeof part.text === "string" ? markers.get(part.text) : void 0;
6368
+ const inPlace = (message) => {
6369
+ if (!isRecord$1(message) || !Array.isArray(message.content)) return message;
6370
+ const parts = message.content;
6371
+ if (!parts.some((part) => fileOf(part) !== void 0)) return message;
6372
+ return {
6373
+ ...message,
6374
+ content: parts.map((part) => fileOf(part) ?? part)
6375
+ };
6376
+ };
6377
+ const original = payload.messages;
6378
+ const messages = [];
6379
+ let changed = false;
6380
+ let index = 0;
6381
+ while (index < original.length) {
6382
+ if (!isToolMessage(original[index])) {
6383
+ const message = inPlace(original[index]);
6384
+ changed ||= message !== original[index];
6385
+ messages.push(message);
6386
+ index++;
6387
+ continue;
6388
+ }
6389
+ const moved = [];
6390
+ for (; index < original.length && isToolMessage(original[index]); index++) {
6391
+ const stripped = stripToolMarkers(original[index], markers);
6392
+ messages.push(stripped.message);
6393
+ moved.push(...stripped.files);
6394
+ }
6395
+ if (moved.length === 0) continue;
6396
+ changed = true;
6397
+ const bridged = isToolResultBridge(original[index]) ? 1 : 0;
6398
+ const followUp = original[index + bridged];
6399
+ if (isImageFollowUp(followUp)) {
6400
+ if (bridged === 1) messages.push(original[index]);
6401
+ messages.push({
6402
+ ...followUp,
6403
+ content: [...followUp.content, ...moved]
6404
+ });
6405
+ index += bridged + 1;
6406
+ continue;
6407
+ }
6408
+ if (options.assistantAfterToolResult === true) messages.push({
6409
+ role: "assistant",
6410
+ content: PI_TOOL_RESULT_BRIDGE
6411
+ });
6412
+ messages.push({
6413
+ role: "user",
6414
+ content: [{
6415
+ type: "text",
6416
+ text: TOOL_RESULT_MEDIA_TEXT
6417
+ }, ...moved]
6418
+ });
6419
+ }
6420
+ return changed ? {
6421
+ ...payload,
6422
+ messages
6423
+ } : void 0;
6424
+ }
6425
+ //#endregion
6072
6426
  //#region src/llm/context.ts
6073
6427
  /**
6074
6428
  * Copied (by way of the VibeDev app) from DeepSeek Harness `@deepseek-ai/dsh-llm-pi-ai` (src/context.ts,
@@ -6076,6 +6430,10 @@ function toPiAssistant(message, onDegrade) {
6076
6430
  * image-limit import moved to ./limits.ts,
6077
6431
  * so the gateway adapter can choose a wire protocol per model. Keep it in step with upstream.
6078
6432
  *
6433
+ * Kept in step with 0.2.3 for what changes at run time: the request-image target (see `requestImageTarget`) and the text of a
6434
+ * system message (see `systemText`). Native audio/video files (`files`, see ./native-files.ts) follow the VibeDev fork
6435
+ * (vibedev 5be6bcec).
6436
+ *
6079
6437
  * Harness request-history conversion into pi-ai's Context vocabulary.
6080
6438
  *
6081
6439
  * @module dsh-llm-pi-ai/context
@@ -6084,6 +6442,16 @@ function toPiAssistant(message, onDegrade) {
6084
6442
  function flattenText(message) {
6085
6443
  return message.content.filter((block) => block.type === "text").map((block) => block.text).join("");
6086
6444
  }
6445
+ /**
6446
+ * The text of a system message: each text block trimmed, empty ones dropped, the rest joined with blank lines.
6447
+ * DSH 0.2.3 stores one system message as one trimmed text block per prompt section and leaves the separators to the
6448
+ * adapter (rc.5 stored the whole prompt as a single block, which this leaves as it was but for its outer whitespace).
6449
+ * Joining the blocks with nothing, as `flattenText` does, would run the sections together.
6450
+ * Same as `systemText` of DSH's own pi-ai adapter.
6451
+ */
6452
+ function systemText(message) {
6453
+ return message.content.filter((block) => block.type === "text").map((block) => block.text.trim()).filter((text) => text.length > 0).join("\n\n");
6454
+ }
6087
6455
  /** Recover the pi-ai toolResult message for one harness tool-role message. */
6088
6456
  function toolResultOf(message, toolNames, content) {
6089
6457
  return {
@@ -6106,8 +6474,9 @@ function assertSupportedHistory(messages) {
6106
6474
  if (message.role !== "user" && message.role !== "tool" && contentHasImage(message.content)) throw new LlmError(`pi-ai cannot represent an image in an in-history ${message.role} message`, "UNSUPPORTED_CONTENT");
6107
6475
  }
6108
6476
  }
6109
- function userContent(blocks, requestImages, resolveImageAccess) {
6477
+ function userContent(blocks, requestImages, resolveImageAccess, files) {
6110
6478
  const content = [];
6479
+ let markers = 0;
6111
6480
  for (const block of blocks) switch (block.type) {
6112
6481
  case "text":
6113
6482
  if (block.text.length > 0) content.push({
@@ -6115,6 +6484,17 @@ function userContent(blocks, requestImages, resolveImageAccess) {
6115
6484
  text: block.text
6116
6485
  });
6117
6486
  break;
6487
+ case "file": {
6488
+ const file = files?.read.get(block.attachment.attachmentId);
6489
+ if (files === void 0 || file === void 0) break;
6490
+ content.push({
6491
+ type: "text",
6492
+ text: nativeFileMarker(files.delivered.length)
6493
+ });
6494
+ files.delivered.push(nativeFilePart(file));
6495
+ markers++;
6496
+ break;
6497
+ }
6118
6498
  case "image": {
6119
6499
  const version = requestImages.get(block.attachment.attachmentId);
6120
6500
  content.push({
@@ -6129,9 +6509,27 @@ function userContent(blocks, requestImages, resolveImageAccess) {
6129
6509
  break;
6130
6510
  }
6131
6511
  }
6132
- if (content.every((block) => block.type === "text")) return content.map((block) => block.text).join("");
6512
+ if (markers === 0 && content.every((block) => block.type === "text")) return content.map((block) => block.text).join("");
6133
6513
  return content;
6134
6514
  }
6515
+ /**
6516
+ * A tool result's content with its native file markers. pi-ai sends a tool result as one text joined with newlines,
6517
+ * and the payload hook moves each marker's file to a user message after the tool messages (a `tool` message holds
6518
+ * text only), dropping the marker's line. A text-only result keeps its text joined as without files, with the markers
6519
+ * after it, so the tool text the model reads is the same whether or not a file went along.
6520
+ */
6521
+ function toolContent(blocks, requestImages, resolveImageAccess, files) {
6522
+ const before = files?.delivered.length ?? 0;
6523
+ const content = userContent(blocks, requestImages, resolveImageAccess, files);
6524
+ if (typeof content === "string" || files === void 0 || files.delivered.length === before) return content;
6525
+ if (!content.every((block) => block.type === "text")) return content;
6526
+ const markers = new Set(files.delivered.slice(before).map((_, index) => nativeFileMarker(before + index)));
6527
+ const text = content.filter((block) => !markers.has(block.text)).map((block) => block.text).join("");
6528
+ return [...text.length > 0 ? [{
6529
+ type: "text",
6530
+ text
6531
+ }] : [], ...content.filter((block) => markers.has(block.text))];
6532
+ }
6135
6533
  function collectImageRefs(blocks, refs) {
6136
6534
  for (const block of blocks) if (block.type === "image") {
6137
6535
  if (block.offloaded !== true) refs.set(block.attachment.attachmentId, block.attachment);
@@ -6156,25 +6554,21 @@ function toolsOf(options) {
6156
6554
  }
6157
6555
  /**
6158
6556
  * Select the pi-ai `systemPrompt` source shared by both conversion paths.
6159
- * `options.system` wins when defined and every history message converts,
6160
- * including a leading `system` message, which then folds into a `user`
6161
- * message. Otherwise a leading `system` history message supplies the prompt
6162
- * and leaves the converted history; empty leading text sends no prompt.
6557
+ * `options.system`, when defined, comes first; every leading `system` history message follows it, all joined with
6558
+ * blank lines, and those messages leave the converted history. Empty text sends no prompt.
6163
6559
  */
6164
6560
  function splitSystemPrompt(options) {
6165
- if (options.system !== void 0) return {
6166
- systemPrompt: options.system,
6167
- messages: options.messages
6168
- };
6169
- const [first, ...rest] = options.messages;
6170
- if (first?.role !== "system") return {
6171
- systemPrompt: void 0,
6172
- messages: options.messages
6173
- };
6174
- const text = flattenText(first);
6561
+ const text = [options.system];
6562
+ let end = 0;
6563
+ for (const message of options.messages) {
6564
+ if (message.role !== "system") break;
6565
+ text.push(systemText(message));
6566
+ end++;
6567
+ }
6568
+ const systemPrompt = text.filter(Boolean).join("\n\n");
6175
6569
  return {
6176
- systemPrompt: text.length > 0 ? text : void 0,
6177
- messages: rest
6570
+ systemPrompt: systemPrompt.length > 0 ? systemPrompt : void 0,
6571
+ messages: options.messages.slice(end)
6178
6572
  };
6179
6573
  }
6180
6574
  /** Assemble the request-level pi-ai context envelope shared by both conversion paths. */
@@ -6194,11 +6588,15 @@ function appendAssistant(message, messages, toolNames, onReplayDegrade) {
6194
6588
  /** Append the system and assistant roles both context builders treat identically; true when consumed. */
6195
6589
  function appendSystemOrAssistant(message, messages, toolNames, onReplayDegrade) {
6196
6590
  if (message.role === "system") {
6197
- messages.push({
6198
- role: "user",
6199
- content: flattenText(message),
6200
- timestamp: 0
6201
- });
6591
+ const content = systemText(message);
6592
+ if (content.length > 0) {
6593
+ const reminder = content.replaceAll("</system-reminder>", "<\\/system-reminder>");
6594
+ messages.push({
6595
+ role: "user",
6596
+ content: `<system-reminder>\n${reminder}\n</system-reminder>`,
6597
+ timestamp: 0
6598
+ });
6599
+ }
6202
6600
  return true;
6203
6601
  }
6204
6602
  if (message.role === "assistant") {
@@ -6227,11 +6625,17 @@ function textOnlyContext(options, onReplayDegrade) {
6227
6625
  }
6228
6626
  return piContext(split.systemPrompt, options, messages);
6229
6627
  }
6230
- /** Deterministic request target for one source under the route budgets. */
6628
+ /**
6629
+ * Deterministic request target for one source under the route budgets.
6630
+ * Assigned to `ImageRequestTarget` of whichever `@deepseek-ai/dsh-attachment` the host runs: the declared type
6631
+ * changed in 0.2.3, and the object satisfies both.
6632
+ */
6231
6633
  function requestImageTarget(ref, budget) {
6232
6634
  return {
6233
6635
  ...requestImageDimensions(ref.width, ref.height, budget.maxPixels),
6234
- maxBytes: budget.maxBytes
6636
+ maxBytes: budget.maxBytes,
6637
+ maxImageBytes: budget.maxBytes,
6638
+ imageTargetBytes: budget.maxBytes
6235
6639
  };
6236
6640
  }
6237
6641
  function toPiContext(options, images, onReplayDegrade) {
@@ -6254,15 +6658,19 @@ async function toPiContextWithImages(options, images, onReplayDegrade) {
6254
6658
  if (offloadImages > 0) throw new LlmError(`pi-ai request images exceed the ${maxRequestImageBytes}-byte base64 bound; ${offloadImages} more oldest occurrence(s) must be offloaded.`, IMAGE_OFFLOAD_REQUIRED_CODE, { offloadImages });
6255
6659
  }
6256
6660
  const exactMessages = projectOffloadedImages(split.messages, (ref) => offloadedImageText(ref, resolveImageAccess(ref)));
6661
+ const files = images.files === void 0 ? void 0 : {
6662
+ read: await readNativeFiles(split.messages, attachments, images.files, options.signal),
6663
+ delivered: images.files.delivered
6664
+ };
6257
6665
  const toolNames = /* @__PURE__ */ new Map();
6258
6666
  const messages = [];
6259
6667
  for (const message of exactMessages) {
6260
6668
  if (appendSystemOrAssistant(message, messages, toolNames, onReplayDegrade)) continue;
6261
6669
  if (message.role === "tool") {
6262
- messages.push(toolResultOf(message, toolNames, userContent(message.content, requestImages, resolveImageAccess)));
6670
+ messages.push(toolResultOf(message, toolNames, toolContent(message.content, requestImages, resolveImageAccess, files)));
6263
6671
  continue;
6264
6672
  }
6265
- const content = userContent(message.content, requestImages, resolveImageAccess);
6673
+ const content = userContent(message.content, requestImages, resolveImageAccess, files);
6266
6674
  messages.push({
6267
6675
  role: "user",
6268
6676
  content,
@@ -7246,6 +7654,12 @@ function _usingCtx() {
7246
7654
  * raise its sign-in prompt; the chat shows this failure's own message.
7247
7655
  */
7248
7656
  const SIGN_IN_REQUIRED_CODE = "VIBEDEV_SIGN_IN_REQUIRED";
7657
+ /**
7658
+ * LlmError's constructor takes only built-in codes in DSH 0.2.3's types, though it accepts any non-empty string at run time
7659
+ * (0.2.2-rc.5 and 0.2.3 alike; LlmError.fromFailure is the upstream route for a foreign code but rc.5 lacks it). The
7660
+ * plugin's own code is therefore passed through the constructor's parameter type, which is a cast that holds in both.
7661
+ */
7662
+ const SIGN_IN_REQUIRED_LLM_CODE = SIGN_IN_REQUIRED_CODE;
7249
7663
  /** Failure code for a used-up balance; not the Harness's `ACCOUNT_QUOTA`, which opens the DeepSeek top-up. */
7250
7664
  const INSUFFICIENT_BALANCE_CODE = "VIBEDEV_INSUFFICIENT_BALANCE";
7251
7665
  /** No promotions apply, shared so an unlabelled listing allocates nothing. */
@@ -7290,6 +7704,19 @@ function reasoningInfo(model, catalog) {
7290
7704
  ...starting === void 0 ? {} : { defaultEffort: ReasoningEffortId(effortOf(starting)) }
7291
7705
  } };
7292
7706
  }
7707
+ /**
7708
+ * The modalities the host reads for one model: pi-ai's `input` (text, image) plus the media files the model takes
7709
+ * natively. The host's request assembly keeps an audio/video file block only for a model that lists its kind here.
7710
+ * `ModelModality` names only text and image in the Harness types this plugin builds against; the VibeDev fork adds
7711
+ * audio and video, and older hosts ignore modalities they do not know.
7712
+ */
7713
+ function inputModalitiesOf(model, catalog) {
7714
+ return [...model.input, ...catalog?.nativeMedia ?? []];
7715
+ }
7716
+ /** Warn about one native file that goes as handle text alone; the default {@link GatewayAdapterOptions.onNativeFileDegrade}. */
7717
+ function warnNativeFileDegrade(detail) {
7718
+ console.warn(`dsh-vibedev: sending "${detail.file}" to ${detail.provider}/${detail.model} as its file handle text only: ${detail.reason}`);
7719
+ }
7293
7720
  /** A JSON object payload pi-ai is about to send, or undefined for anything else. */
7294
7721
  function objectPayload(payload) {
7295
7722
  return typeof payload === "object" && payload !== null && !Array.isArray(payload) ? payload : void 0;
@@ -7341,7 +7768,7 @@ var GatewayAdapter = class extends LlmAdapter {
7341
7768
  }
7342
7769
  modelOf(snapshot, provider, id) {
7343
7770
  this.assertOwned(provider);
7344
- if (snapshot.catalog.length === 0) throw new LlmError(SIGN_IN_MESSAGE, SIGN_IN_REQUIRED_CODE);
7771
+ if (snapshot.catalog.length === 0) throw new LlmError(SIGN_IN_MESSAGE, SIGN_IN_REQUIRED_LLM_CODE);
7345
7772
  const catalog = snapshot.byId.get(id);
7346
7773
  const model = snapshot.models.getModel(provider, id);
7347
7774
  if (catalog === void 0 || model === void 0) throw new LlmError(`VibeDev has no model "${id}"`, "UNKNOWN_MODEL");
@@ -7350,6 +7777,42 @@ var GatewayAdapter = class extends LlmAdapter {
7350
7777
  catalog
7351
7778
  };
7352
7779
  }
7780
+ /**
7781
+ * The request-image target for a stored image: the one `toPiContext` reads the request version with, from the same
7782
+ * function and the same budgets. Computer Use asks for it to size and encode a screenshot and to map coordinates onto
7783
+ * the image the model sees; the base class returns the source size, which would let `toPiContext` shrink the
7784
+ * screenshot again afterwards and put the model's coordinates out of step with the tool's.
7785
+ */
7786
+ imageRequestTarget(_provider, _model, image) {
7787
+ return requestImageTarget(image, {
7788
+ maxPixels: DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET,
7789
+ maxBytes: DEFAULT_REQUEST_IMAGE_MAX_BYTES
7790
+ });
7791
+ }
7792
+ /**
7793
+ * The raw-byte target under which this route delivers one audio/video file natively (the VibeDev fork's
7794
+ * `LlmAdapter.fileRequestTarget`; hosts without it never ask). Chat Completions models that declare audio or video
7795
+ * get the host's per-file ceiling and the media types they take inline (`GEMINI_INLINE_MEDIA_TYPES`; hosts that
7796
+ * predate `mediaTypes` ignore it, and the plugin checks it again after the read); every other model — Claude over
7797
+ * Messages, GPT over Responses, a model that declares neither — gets none, so request assembly sends those files as
7798
+ * handle text. Synchronous and I/O-free; request assembly also checks the file's kind against the model's
7799
+ * `inputModalities`.
7800
+ *
7801
+ * Not marked `override`: the Harness types this plugin builds against do not declare the hook yet.
7802
+ */
7803
+ fileRequestTarget(provider, model, _file) {
7804
+ return this.fileTargetIn(this.current(), provider, model);
7805
+ }
7806
+ /** {@link fileRequestTarget} on one snapshot, so a request reads its files under the catalog it began with. */
7807
+ fileTargetIn(snapshot, provider, model) {
7808
+ if (!this.owns(provider)) return void 0;
7809
+ const entry = snapshot.byId.get(model);
7810
+ if (entry === void 0 || entry.api !== "openai-completions" || (entry.nativeMedia?.length ?? 0) === 0) return void 0;
7811
+ return snapshot.models.getModel(provider, model) === void 0 ? void 0 : {
7812
+ maxBytes: NATIVE_FILE_MAX_BYTES,
7813
+ mediaTypes: GEMINI_INLINE_MEDIA_TYPES
7814
+ };
7815
+ }
7353
7816
  providerInfo(provider) {
7354
7817
  this.assertOwned(provider);
7355
7818
  const relay = this.config.relayProvider;
@@ -7371,7 +7834,8 @@ var GatewayAdapter = class extends LlmAdapter {
7371
7834
  const promotions = await this.promotions();
7372
7835
  return listed.filter((model) => !hideRelay || !relayIdentity(model.id).relay).map((model) => {
7373
7836
  const promotion = promotions.get(model.id);
7374
- const family = snapshot.byId.get(model.id)?.family;
7837
+ const entry = snapshot.byId.get(model.id);
7838
+ const family = entry?.family;
7375
7839
  const pinOrder = preferred.get(model.id);
7376
7840
  const picker = family === void 0 && pinOrder === void 0 ? void 0 : {
7377
7841
  ...family === void 0 ? {} : { family },
@@ -7381,7 +7845,7 @@ var GatewayAdapter = class extends LlmAdapter {
7381
7845
  provider,
7382
7846
  id: model.id,
7383
7847
  name: model.name,
7384
- inputModalities: [...model.input],
7848
+ inputModalities: inputModalitiesOf(model, entry),
7385
7849
  ...picker === void 0 ? {} : { picker },
7386
7850
  ...promotion === void 0 ? {} : {
7387
7851
  badge: promotionBadge(promotion),
@@ -7410,7 +7874,7 @@ var GatewayAdapter = class extends LlmAdapter {
7410
7874
  provider,
7411
7875
  id,
7412
7876
  name: model.name,
7413
- inputModalities: [...model.input],
7877
+ inputModalities: inputModalitiesOf(model, catalog),
7414
7878
  context: { contextWindow: model.contextWindow },
7415
7879
  defaultMaxTokens: model.maxTokens,
7416
7880
  ...reasoningInfo(model, catalog)
@@ -7439,7 +7903,7 @@ var GatewayAdapter = class extends LlmAdapter {
7439
7903
  const starting = startingReasoning(catalog);
7440
7904
  const reasoning = resolveReasoningLevel(model, options.reasoningEffort ?? (starting === void 0 ? void 0 : effortOf(starting)));
7441
7905
  let credential = await this.config.resolveCredential();
7442
- if (credential === void 0) throw new LlmError(SIGN_IN_MESSAGE, SIGN_IN_REQUIRED_CODE);
7906
+ if (credential === void 0) throw new LlmError(SIGN_IN_MESSAGE, SIGN_IN_REQUIRED_LLM_CODE);
7443
7907
  const sessionId = options.sessionId === void 0 ? void 0 : String(options.sessionId);
7444
7908
  const deviceId = model.api === "anthropic-messages" && sessionId !== void 0 ? await this.config.deviceId?.() : void 0;
7445
7909
  const consumer = new AbortController();
@@ -7450,7 +7914,9 @@ var GatewayAdapter = class extends LlmAdapter {
7450
7914
  try {
7451
7915
  const containsImage = options.messages.some((message) => contentHasImage(message.content));
7452
7916
  if (containsImage && !model.input.includes("image")) throw new LlmError(`VibeDev model "${model.id}" does not support image input`, "UNSUPPORTED_CONTENT");
7453
- const attachments = containsImage ? this.config.resolveAttachments?.() : void 0;
7917
+ const carriesFiles = (message) => (message.role === "user" || message.role === "tool") && message.content.some((block) => block.type === "file");
7918
+ const containsNativeFile = model.api === "openai-completions" && options.messages.some(carriesFiles);
7919
+ const attachments = containsImage || containsNativeFile ? this.config.resolveAttachments?.() : void 0;
7454
7920
  if (containsImage && attachments === void 0) throw new LlmError("image input requires the durable attachment service", "UNSUPPORTED_CONTENT");
7455
7921
  const onReplayDegrade = (reason) => {
7456
7922
  this.config.onReplayDegrade?.({
@@ -7459,6 +7925,21 @@ var GatewayAdapter = class extends LlmAdapter {
7459
7925
  reason
7460
7926
  });
7461
7927
  };
7928
+ const onNativeFileDegrade = (file, reason) => {
7929
+ try {
7930
+ (this.config.onNativeFileDegrade ?? warnNativeFileDegrade)({
7931
+ provider: options.provider,
7932
+ model: options.model,
7933
+ file,
7934
+ reason
7935
+ });
7936
+ } catch {}
7937
+ };
7938
+ if (containsNativeFile && attachments === void 0) for (const message of options.messages) {
7939
+ if (!carriesFiles(message)) continue;
7940
+ for (const block of message.content) if (block.type === "file") onNativeFileDegrade(block.attachment.name, "no durable attachment service to read it from");
7941
+ }
7942
+ const nativeFiles = [];
7462
7943
  const context = attachments === void 0 ? toPiContext(options, void 0, onReplayDegrade) : await toPiContext({
7463
7944
  ...options,
7464
7945
  signal: watchdog.signal
@@ -7469,7 +7950,14 @@ var GatewayAdapter = class extends LlmAdapter {
7469
7950
  requestImagePolicy: {
7470
7951
  maxPixels: DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET,
7471
7952
  maxBytes: DEFAULT_REQUEST_IMAGE_MAX_BYTES
7472
- }
7953
+ },
7954
+ ...containsNativeFile ? { files: {
7955
+ target: () => this.fileTargetIn(snapshot, options.provider, options.model),
7956
+ onDegrade: (ref, reason) => {
7957
+ onNativeFileDegrade(ref.name, reason);
7958
+ },
7959
+ delivered: nativeFiles
7960
+ } } : {}
7473
7961
  }, onReplayDegrade);
7474
7962
  const enabledReasoning = reasoning === void 0 || reasoning === "off" ? void 0 : reasoning;
7475
7963
  const offersNone = catalog.reasoningLevels?.includes("none") === true;
@@ -7515,7 +8003,8 @@ var GatewayAdapter = class extends LlmAdapter {
7515
8003
  ...sessionId === void 0 ? {} : { sessionId },
7516
8004
  off: reasoning === "off" && offersNone,
7517
8005
  reasoning: enabledReasoning !== void 0,
7518
- claudeCacheTtl
8006
+ claudeCacheTtl,
8007
+ nativeFiles
7519
8008
  }),
7520
8009
  fetch: observingFetch,
7521
8010
  onResponse: (received) => {
@@ -7584,7 +8073,9 @@ var GatewayAdapter = class extends LlmAdapter {
7584
8073
  /**
7585
8074
  * Fit pi-ai's payload to the gateway: Chat Completions gets the session's cache key (pi-ai sends it
7586
8075
  * only to api.openai.com), "off" is spelled out where the catalog offers `none`, and Responses
7587
- * drops `temperature` while reasoning, which reasoning models refuse.
8076
+ * drops `temperature` while reasoning, which reasoning models refuse. Chat Completions also gets
8077
+ * its native audio/video files: each marker the conversion left becomes a `file` part, in place in
8078
+ * a user message and in a user message after the tool messages for a tool result.
7588
8079
  */
7589
8080
  shapePayload(payload, model, request) {
7590
8081
  const body = objectPayload(payload);
@@ -7597,6 +8088,10 @@ var GatewayAdapter = class extends LlmAdapter {
7597
8088
  shaped.thinking = { type: "disabled" };
7598
8089
  delete shaped.reasoning_effort;
7599
8090
  } else if (request.off) shaped.reasoning_effort = "none";
8091
+ if (request.nativeFiles !== void 0 && request.nativeFiles.length > 0) {
8092
+ const assistantAfterToolResult = model.compat?.requiresAssistantAfterToolResult === true;
8093
+ return injectNativeFiles(shaped, request.nativeFiles, { assistantAfterToolResult }) ?? shaped;
8094
+ }
7600
8095
  break;
7601
8096
  case "openai-responses":
7602
8097
  if (request.off) shaped.reasoning = {
@@ -7749,6 +8244,9 @@ function installGatewayModels(ctx, options) {
7749
8244
  onReplayDegrade: ({ provider, model, reason }) => {
7750
8245
  ctx.logger.warn(`dsh-vibedev: unusable replay state on assistant history for "${provider}/${model}"; sending provider-neutral content (${reason})`);
7751
8246
  },
8247
+ onNativeFileDegrade: ({ provider, model, file, reason }) => {
8248
+ ctx.logger.warn(`dsh-vibedev: sending "${file}" to ${provider}/${model} as its file handle text only: ${reason}`);
8249
+ },
7752
8250
  ...options.onRequestEnded === void 0 ? {} : { onRequestEnded: options.onRequestEnded },
7753
8251
  ...options.promotions === void 0 ? {} : { promotions: options.promotions }
7754
8252
  });
@@ -26,8 +26,9 @@
26
26
  */
27
27
  import { LlmAdapter } from '@deepseek-ai/dsh-llm';
28
28
  import type { GenerateOptions, ImageAttachmentAccess, LlmModelInfo, LlmProviderInfo, LlmResolvedModelInfo, PreparedAdapterCall, ResolvedRetryPolicy, StreamChunk } from '@deepseek-ai/dsh-llm';
29
- import type { AttachmentStore, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment';
29
+ import type { AttachmentStore, FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment';
30
30
  import type { GatewayModel } from './catalog.js';
31
+ import type { FileRequestTarget } from './native-files.js';
31
32
  import { type ActivePromotion } from './promotions.js';
32
33
  import { type ClaudeCacheTtl } from './cache-ttl.js';
33
34
  /** The credential for one request. */
@@ -98,6 +99,16 @@ export interface GatewayAdapterOptions {
98
99
  model: string;
99
100
  reason: string;
100
101
  }) => void;
102
+ /**
103
+ * One audio/video file request assembly kept for native delivery goes as its handle text alone (no attachment
104
+ * service, a failed read, a ceiling). Default: `console.warn`. Never fails the request.
105
+ */
106
+ readonly onNativeFileDegrade?: (detail: {
107
+ provider: string;
108
+ model: string;
109
+ file: string;
110
+ reason: string;
111
+ }) => void;
101
112
  /** A request reached the gateway and ended, however it ended: it may have been charged. */
102
113
  readonly onRequestEnded?: () => void;
103
114
  /**
@@ -125,6 +136,27 @@ export declare class GatewayAdapter extends LlmAdapter {
125
136
  private owns;
126
137
  private assertOwned;
127
138
  private modelOf;
139
+ /**
140
+ * The request-image target for a stored image: the one `toPiContext` reads the request version with, from the same
141
+ * function and the same budgets. Computer Use asks for it to size and encode a screenshot and to map coordinates onto
142
+ * the image the model sees; the base class returns the source size, which would let `toPiContext` shrink the
143
+ * screenshot again afterwards and put the model's coordinates out of step with the tool's.
144
+ */
145
+ imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): import("./context.js").CompatImageRequestTarget;
146
+ /**
147
+ * The raw-byte target under which this route delivers one audio/video file natively (the VibeDev fork's
148
+ * `LlmAdapter.fileRequestTarget`; hosts without it never ask). Chat Completions models that declare audio or video
149
+ * get the host's per-file ceiling and the media types they take inline (`GEMINI_INLINE_MEDIA_TYPES`; hosts that
150
+ * predate `mediaTypes` ignore it, and the plugin checks it again after the read); every other model — Claude over
151
+ * Messages, GPT over Responses, a model that declares neither — gets none, so request assembly sends those files as
152
+ * handle text. Synchronous and I/O-free; request assembly also checks the file's kind against the model's
153
+ * `inputModalities`.
154
+ *
155
+ * Not marked `override`: the Harness types this plugin builds against do not declare the hook yet.
156
+ */
157
+ fileRequestTarget(provider: string, model: string, _file: FileAttachmentRef): FileRequestTarget | undefined;
158
+ /** {@link fileRequestTarget} on one snapshot, so a request reads its files under the catalog it began with. */
159
+ private fileTargetIn;
128
160
  providerInfo(provider: string): LlmProviderInfo;
129
161
  providerRetryPolicy(provider: string): ResolvedRetryPolicy | undefined;
130
162
  listModels(provider: string): Promise<readonly GatewayListedModel[]>;
@@ -139,7 +171,9 @@ export declare class GatewayAdapter extends LlmAdapter {
139
171
  /**
140
172
  * Fit pi-ai's payload to the gateway: Chat Completions gets the session's cache key (pi-ai sends it
141
173
  * only to api.openai.com), "off" is spelled out where the catalog offers `none`, and Responses
142
- * drops `temperature` while reasoning, which reasoning models refuse.
174
+ * drops `temperature` while reasoning, which reasoning models refuse. Chat Completions also gets
175
+ * its native audio/video files: each marker the conversion left becomes a `file` part, in place in
176
+ * a user message and in a user message after the tool messages for a tool result.
143
177
  */
144
178
  private shapePayload;
145
179
  /**
@@ -32,6 +32,13 @@ export interface GatewayModel {
32
32
  readonly maxInputTokens?: number;
33
33
  readonly maxTokens: number;
34
34
  readonly input: readonly ('text' | 'image')[];
35
+ /**
36
+ * The media files this model takes natively (`input_modalities` lists `audio`/`video`), in that order. Only Chat
37
+ * Completions models carry it: that is the only protocol the plugin sends files on, as a `file` content part the
38
+ * gateway turns into the provider's own form (Claude over Messages would refuse one). Absent when there are none. pi-ai's descriptor
39
+ * keeps `input` (text/image); the host reads these through `inputModalities`.
40
+ */
41
+ readonly nativeMedia?: readonly ('audio' | 'video')[];
35
42
  /**
36
43
  * Levels the user may pick, in escalation order; `undefined` when the catalog
37
44
  * states none (no level control), `[]` when the model thinks with no levels.
@@ -4,13 +4,18 @@
4
4
  * image-limit import moved to ./limits.ts,
5
5
  * so the gateway adapter can choose a wire protocol per model. Keep it in step with upstream.
6
6
  *
7
+ * Kept in step with 0.2.3 for what changes at run time: the request-image target (see `requestImageTarget`) and the text of a
8
+ * system message (see `systemText`). Native audio/video files (`files`, see ./native-files.ts) follow the VibeDev fork
9
+ * (vibedev 5be6bcec).
10
+ *
7
11
  * Harness request-history conversion into pi-ai's Context vocabulary.
8
12
  *
9
13
  * @module dsh-llm-pi-ai/context
10
14
  */
11
15
  import type { GenerateOptions, ImageAttachmentAccessResolver } from '@deepseek-ai/dsh-llm';
12
- import type { AttachmentStore } from '@deepseek-ai/dsh-attachment';
16
+ import type { AttachmentStore, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment';
13
17
  import type { Context as PiContext } from '@earendil-works/pi-ai';
18
+ import type { PiFileRequestContext } from './native-files.js';
14
19
  /** Inputs that bind deterministic request images to one current tool execution world. */
15
20
  export interface PiImageRequestContext {
16
21
  /** Durable provider that resolves request-image bytes and provider-owned host objects. */
@@ -21,14 +26,48 @@ export interface PiImageRequestContext {
21
26
  maxRequestImageBytes?: number;
22
27
  /** Route pixel and raw encoded-byte budgets. */
23
28
  requestImagePolicy?: PiImageRequestBudget;
29
+ /**
30
+ * Native delivery of the file blocks request assembly kept; omission drops them, leaving their handle text.
31
+ * Only Chat Completions models supply it.
32
+ */
33
+ files?: PiFileRequestContext;
24
34
  }
25
35
  /** Per-route budgets from which each request image's target is derived. */
26
36
  export interface PiImageRequestBudget {
27
37
  /** Total-pixel budget; larger sources are downscaled proportionally. */
28
38
  maxPixels: number;
29
- /** Encoded-byte target for one request image. */
39
+ /**
40
+ * Raw encoded bytes for one request image. DSH 0.2.3 treats it as a hard limit (a larger encoding is shrunk
41
+ * further) and also as the preferred size; DSH 0.2.2-rc.5 treated it as a target only.
42
+ */
30
43
  maxBytes: number;
31
44
  }
45
+ /**
46
+ * A request-image target that both DSH generations accept. `ImageRequestTarget` changed between them:
47
+ * - DSH 0.2.2-rc.5: `{ width, height, maxBytes }`;
48
+ * - DSH 0.2.3: `{ width, height, maxImageBytes, imageTargetBytes }`, where `maxImageBytes` is the hard limit,
49
+ * `imageTargetBytes` the preferred size (never above the limit), and `readImageRequest` rejects a target
50
+ * missing either with `INVALID_ATTACHMENT_REF` ("maxImageBytes must be a positive integer").
51
+ * 0.2.3 validates only the fields it knows and rc.5 ignores extra ones, so one object carries all three byte fields,
52
+ * each the same budget (the shape DSH's own pi-ai adapter builds, which sets `imageTargetBytes = maxImageBytes`).
53
+ * Drop `maxBytes` once rc.5 is no longer supported.
54
+ */
55
+ export interface CompatImageRequestTarget {
56
+ width: number;
57
+ height: number;
58
+ /** rc.5's byte target. */
59
+ maxBytes: number;
60
+ /** 0.2.3's hard limit on the encoded bytes. */
61
+ maxImageBytes: number;
62
+ /** 0.2.3's preferred encoded size; not above `maxImageBytes`. */
63
+ imageTargetBytes: number;
64
+ }
65
+ /**
66
+ * Deterministic request target for one source under the route budgets.
67
+ * Assigned to `ImageRequestTarget` of whichever `@deepseek-ai/dsh-attachment` the host runs: the declared type
68
+ * changed in 0.2.3, and the object satisfies both.
69
+ */
70
+ export declare function requestImageTarget(ref: ImageAttachmentRef, budget: PiImageRequestBudget): CompatImageRequestTarget;
32
71
  /**
33
72
  * Convert text-only harness history to a synchronous pi-ai Context. Tool
34
73
  * result names are recovered from preceding assistant tool calls.
@@ -9,7 +9,12 @@
9
9
  export declare const DEFAULT_MAX_REQUEST_IMAGE_BYTES: number;
10
10
  /** Total-pixel budget that preserves the complete 2048px normalized attachment. */
11
11
  export declare const DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET: number;
12
- /** Raw encoded-byte target before inline base64 expansion. */
12
+ /**
13
+ * Raw encoded bytes allowed for one request image, before inline base64 expansion. A hard limit under DSH 0.2.3 (a larger
14
+ * encoding is shrunk further; that is also the preferred size) and a target under rc.5. DSH's pi-ai default is 0.75 MiB
15
+ * (a 20 MiB request over 20 images); 1 MiB keeps what 0.11.0 sent, and the oldest images are offloaded when the request
16
+ * exceeds `DEFAULT_MAX_REQUEST_IMAGE_BYTES`.
17
+ */
13
18
  export declare const DEFAULT_REQUEST_IMAGE_MAX_BYTES: number;
14
19
  /** Maximum provider idle time while one stream read is outstanding. */
15
20
  export declare const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 300000;
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Native audio/video delivery for the gateway's Chat Completions models.
3
+ *
4
+ * Adapted from the VibeDev fork of DeepSeek Harness `@deepseek-ai/dsh-llm-pi-ai` (src/native-files.ts, vibedev
5
+ * 5be6bcec; MIT, Copyright (c) 2026 DeepSeek — see THIRD-PARTY-NOTICES.txt). Keep it in step with upstream.
6
+ *
7
+ * Request assembly (the host's LLM runtime) decides which audio/video occurrences a request carries natively: the
8
+ * current turn's user messages and tool results (DSH 0.2.3-era VibeDev hosts: only the latest user message that
9
+ * carries files), only kinds the model declares, within 14 MiB per file and 20 MiB of base64 per request, and never
10
+ * for an auxiliary call. It leaves each kept `{type:'file'}` block right after the file's handle text. This module
11
+ * reads the kept files' bytes and serializes them; it decides nothing beyond a defensive re-check of the same size
12
+ * ceilings and of the media types the gateway's models take ({@link GEMINI_INLINE_MEDIA_TYPES}).
13
+ *
14
+ * pi-ai's Context has no file content, so conversion leaves one marker text part where each delivered file belongs
15
+ * and the payload hook swaps every marker for an OpenAI-compatible `file` content part carrying the bytes as a data
16
+ * URL: `{"type":"file","file":{"file_data":"data:<mediaType>;base64,<…>"}}`. The gateway turns it into the
17
+ * provider's own form (Gemini `inlineData`, say). A Chat Completions `tool` message carries text only, so a file in a
18
+ * tool result moves to a `user` message right after that run of tool messages, the way pi-ai sends tool-result
19
+ * images (see {@link injectNativeFiles}).
20
+ *
21
+ * Nothing here can fail a request: a file without a target, a host without `readFileRequest`, a read that fails or
22
+ * a file over a ceiling all fall back to the handle text that is already in the message, with a warning. Only
23
+ * cancellation propagates.
24
+ *
25
+ * Hosts whose `@deepseek-ai/dsh-llm` and `@deepseek-ai/dsh-attachment` predate native files (DSH 0.2.2-rc.5,
26
+ * upstream 0.2.3) never keep a file block, so none of this runs there; the types the newer packages declare are
27
+ * restated structurally below so the plugin builds and loads against either.
28
+ *
29
+ * @module dsh-vibedev/llm/native-files
30
+ */
31
+ import type { RequestMessage } from '@deepseek-ai/dsh-llm';
32
+ import type { AttachmentId, AttachmentStore, FileAttachmentRef } from '@deepseek-ai/dsh-attachment';
33
+ /** Raw-byte ceiling for one natively delivered file: the host's `NATIVE_FILE_MAX_BYTES`, 14 MiB where it has none. */
34
+ export declare const NATIVE_FILE_MAX_BYTES: number;
35
+ /** Ceiling on the base64 total of a request's native files: the host's own, 20 MiB where it has none. */
36
+ export declare const NATIVE_FILE_MAX_REQUEST_BASE64_BYTES: number;
37
+ /**
38
+ * Media types the gateway's Chat Completions models take inline: the containers Gemini documents for inline
39
+ * audio/video, spelled as the host's `sniffFileMediaType` spells them. Anything else (Matroska, M4A, Opus, AMR,
40
+ * WMA, …) keeps its handle text only: one type the provider refuses would fail the whole request.
41
+ */
42
+ export declare const GEMINI_INLINE_MEDIA_TYPES: readonly string[];
43
+ /** Text that opens the user message carrying tool-result media. */
44
+ export declare const TOOL_RESULT_MEDIA_TEXT = "Attached media from tool result:";
45
+ /** `FileRequestTarget` of `@deepseek-ai/dsh-attachment` (VibeDev fork): the route's limits for one file. */
46
+ export interface FileRequestTarget {
47
+ /** Hard raw-byte limit before base64 expansion; a larger file is refused before any byte is read. */
48
+ maxBytes: number;
49
+ /**
50
+ * Media types the route accepts; a host whose attachment provider knows the field refuses any other sniffed type
51
+ * with `ATTACHMENT_PROJECTION_UNSUPPORTED`. Older hosts ignore it, so {@link readNativeFiles} checks it again.
52
+ * Absent means {@link GEMINI_INLINE_MEDIA_TYPES}.
53
+ */
54
+ mediaTypes?: readonly string[];
55
+ }
56
+ /** `RequestFileAttachment` of `@deepseek-ai/dsh-attachment` (VibeDev fork): one file read whole for one request. */
57
+ export interface RequestFileAttachment {
58
+ attachment: FileAttachmentRef;
59
+ /** Exact stored bytes. */
60
+ data: Uint8Array;
61
+ /** Media type sniffed from the leading bytes, falling back to the name's extension. */
62
+ mediaType: string;
63
+ /** Exact byte length of `data`. */
64
+ bytes: number;
65
+ }
66
+ /** Inputs that let request conversion deliver the runtime-selected files natively. */
67
+ export interface PiFileRequestContext {
68
+ /** Route raw-byte target for one file; undefined drops the occurrence, leaving its handle text. */
69
+ target: (ref: FileAttachmentRef) => FileRequestTarget | undefined;
70
+ /** Observe one occurrence that falls back to its handle text. */
71
+ onDegrade?: (ref: FileAttachmentRef, reason: string) => void;
72
+ /**
73
+ * Receives each delivered occurrence's wire part in marker order; the converted context carries
74
+ * {@link nativeFileMarker} of the same index.
75
+ */
76
+ delivered: NativeFilePart[];
77
+ }
78
+ /** OpenAI-compatible Chat Completions file content part. */
79
+ export interface NativeFilePart {
80
+ type: 'file';
81
+ file: {
82
+ file_data: string;
83
+ };
84
+ }
85
+ /**
86
+ * Text part that holds one delivered file's place until the payload hook replaces it. Deterministic, so identical
87
+ * histories convert identically, and NUL-delimited, so no user-authored text block equals it.
88
+ * @param index - position in {@link PiFileRequestContext.delivered}.
89
+ * @returns the marker text.
90
+ */
91
+ export declare function nativeFileMarker(index: number): string;
92
+ /**
93
+ * Read every file the request delivers natively, once per attachment. A file whose target is gone, whose read fails
94
+ * (the host's `ATTACHMENT_PROJECTION_UNSUPPORTED` for a media type outside the target's list included), whose sniffed
95
+ * media type the target does not accept, or that breaks a ceiling is left out, so its occurrences keep only their
96
+ * handle text; cancellation still propagates. When the base64 total of the occurrences read exceeds
97
+ * {@link NATIVE_FILE_MAX_REQUEST_BASE64_BYTES} (a host that did not budget them), the earliest files are left out
98
+ * first, as request assembly would.
99
+ * @param messages - converted history; user- and tool-role file blocks are read.
100
+ * @param attachments - durable provider of the verbatim bytes.
101
+ * @param files - route target and degrade observer.
102
+ * @param signal - request cancellation.
103
+ * @returns request bytes by attachment id.
104
+ */
105
+ export declare function readNativeFiles(messages: readonly RequestMessage[], attachments: AttachmentStore, files: PiFileRequestContext, signal?: AbortSignal): Promise<ReadonlyMap<AttachmentId, RequestFileAttachment>>;
106
+ /**
107
+ * The Chat Completions content part for one delivered file.
108
+ * @param file - bytes and sniffed media type.
109
+ * @returns the part the gateway accepts.
110
+ */
111
+ export declare function nativeFilePart(file: RequestFileAttachment): NativeFilePart;
112
+ /** How {@link injectNativeFiles} places tool-result media. */
113
+ export interface NativeFileInjectionOptions {
114
+ /**
115
+ * The model's `compat.requiresAssistantAfterToolResult`: a new media message after tool results is preceded by
116
+ * pi-ai's own bridging assistant message, exactly as pi-ai does for tool-result images.
117
+ */
118
+ readonly assistantAfterToolResult?: boolean;
119
+ }
120
+ /**
121
+ * Put every delivered file part into a Chat Completions payload. A marker part in a user message becomes the file
122
+ * part in place. A Chat Completions `tool` message holds text only, so markers in a run of consecutive `tool`
123
+ * messages leave the tool text (the handle text stays) and their parts, in tool-result then block order, go to the
124
+ * user message right after the run: appended to pi-ai's "Attached image(s) from tool result:" message when pi-ai
125
+ * added one, otherwise in a new `{role:'user',content:[{type:'text',text:'Attached media from tool result:'},…]}`,
126
+ * preceded by pi-ai's bridging assistant message when the model requires one.
127
+ * @param payload - the request body pi-ai built.
128
+ * @param delivered - file parts by marker index.
129
+ * @param options - the model's tool-result ordering rule.
130
+ * @returns a shallow-copied payload, or undefined to keep it when no marker is present.
131
+ */
132
+ export declare function injectNativeFiles(payload: unknown, delivered: readonly NativeFilePart[], options?: NativeFileInjectionOptions): unknown;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vibedev-si/dsh-vibedev",
3
- "version": "0.11.0",
3
+ "version": "0.11.2",
4
4
  "description": "VibeDev 账号与模型:在 DeepSeek Harness 里登录 VibeDev,与 DeepSeek 账号并存,使用 VibeDev 网关的模型(Claude、GPT 等),并生成图片、视频、音乐和播客 · VibeDev account and models for DeepSeek Harness: sign in to VibeDev next to the DeepSeek account and use the VibeDev gateway's models (Claude, GPT and more), plus image, video, music and podcast generation",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",