@vibedev-si/dsh-vibedev 0.11.1 → 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,20 @@
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
+
13
27
  ## 0.11.1 用户可见更新
14
28
 
15
29
  兼容 DSH 0.2.3:修复发送图片失败。桌面版升级到 DeepSeek Harness 0.2.3 后,用 VibeDev 网关的模型发一张图片,那一轮会失败,并提示 `Image request maxImageBytes must be a positive integer.`;图片留在对话里后,之后每一轮和 `/compact` 也会失败。0.11.1 修好了这些,改版后不需要清理或重发对话。
@@ -445,7 +459,7 @@ npm run build
445
459
 
446
460
  ## 第三方代码
447
461
 
448
- `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`。
449
463
 
450
464
  ---
451
465
 
@@ -453,6 +467,20 @@ npm run build
453
467
 
454
468
  ## English
455
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
+
456
484
  ### What changes in 0.11.1
457
485
 
458
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.
@@ -675,7 +703,7 @@ For explicit joint acceptance, run node scripts/verify-fetch-joint.mjs with one
675
703
 
676
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.
677
705
 
678
- **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`.
679
707
 
680
708
  ### One-step chat consent: `vibedevDesktopChatConsent` (0.11.0)
681
709
 
@@ -1,4 +1,4 @@
1
- THIRD-PARTY NOTICES · @vibedev-si/dsh-vibedev 0.11.1
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
 
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";
@@ -5747,6 +5748,8 @@ const REASONING_LEVELS = [
5747
5748
  "xhigh",
5748
5749
  "max"
5749
5750
  ];
5751
+ /** The file kinds a model can take natively, in the order `nativeMedia` lists them. */
5752
+ const NATIVE_MEDIA = ["audio", "video"];
5750
5753
  /** The endpoint each protocol is called on, as `allowed_endpoints` lists it. */
5751
5754
  const ENDPOINT = {
5752
5755
  "anthropic-messages": "/v1/messages",
@@ -5828,6 +5831,7 @@ function parseCatalog(body) {
5828
5831
  const levels = reasoningLevelsOf(capabilities.reasoning_levels);
5829
5832
  const defaultReasoning = typeof capabilities.default_reasoning === "string" && levels?.includes(capabilities.default_reasoning) ? capabilities.default_reasoning : void 0;
5830
5833
  const inputs = strings$1(capabilities.input_modalities) ?? [];
5834
+ const nativeMedia = api === "openai-completions" ? NATIVE_MEDIA.filter((kind) => inputs.includes(kind)) : [];
5831
5835
  const maxInputTokens = positive$2(capabilities.max_input_tokens);
5832
5836
  const rawFamily = record$8(entry.model_family);
5833
5837
  const familyId = typeof rawFamily?.id === "string" ? rawFamily.id.trim() : "";
@@ -5845,6 +5849,7 @@ function parseCatalog(body) {
5845
5849
  ...maxInputTokens === void 0 ? {} : { maxInputTokens },
5846
5850
  maxTokens: positive$2(capabilities.max_output_tokens) ?? 32768,
5847
5851
  input: inputs.includes("image") ? ["text", "image"] : ["text"],
5852
+ ...nativeMedia.length === 0 ? {} : { nativeMedia },
5848
5853
  ...levels === void 0 ? {} : { reasoningLevels: levels },
5849
5854
  ...defaultReasoning === void 0 ? {} : { defaultReasoning },
5850
5855
  adaptiveThinking: capabilities.adaptive_thinking === true,
@@ -6111,6 +6116,313 @@ function toPiAssistant(message, onDegrade) {
6111
6116
  }
6112
6117
  }
6113
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
6114
6426
  //#region src/llm/context.ts
6115
6427
  /**
6116
6428
  * Copied (by way of the VibeDev app) from DeepSeek Harness `@deepseek-ai/dsh-llm-pi-ai` (src/context.ts,
@@ -6119,7 +6431,8 @@ function toPiAssistant(message, onDegrade) {
6119
6431
  * so the gateway adapter can choose a wire protocol per model. Keep it in step with upstream.
6120
6432
  *
6121
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
6122
- * system message (see `systemText`).
6434
+ * system message (see `systemText`). Native audio/video files (`files`, see ./native-files.ts) follow the VibeDev fork
6435
+ * (vibedev 5be6bcec).
6123
6436
  *
6124
6437
  * Harness request-history conversion into pi-ai's Context vocabulary.
6125
6438
  *
@@ -6161,8 +6474,9 @@ function assertSupportedHistory(messages) {
6161
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");
6162
6475
  }
6163
6476
  }
6164
- function userContent(blocks, requestImages, resolveImageAccess) {
6477
+ function userContent(blocks, requestImages, resolveImageAccess, files) {
6165
6478
  const content = [];
6479
+ let markers = 0;
6166
6480
  for (const block of blocks) switch (block.type) {
6167
6481
  case "text":
6168
6482
  if (block.text.length > 0) content.push({
@@ -6170,6 +6484,17 @@ function userContent(blocks, requestImages, resolveImageAccess) {
6170
6484
  text: block.text
6171
6485
  });
6172
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
+ }
6173
6498
  case "image": {
6174
6499
  const version = requestImages.get(block.attachment.attachmentId);
6175
6500
  content.push({
@@ -6184,9 +6509,27 @@ function userContent(blocks, requestImages, resolveImageAccess) {
6184
6509
  break;
6185
6510
  }
6186
6511
  }
6187
- 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("");
6188
6513
  return content;
6189
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
+ }
6190
6533
  function collectImageRefs(blocks, refs) {
6191
6534
  for (const block of blocks) if (block.type === "image") {
6192
6535
  if (block.offloaded !== true) refs.set(block.attachment.attachmentId, block.attachment);
@@ -6315,15 +6658,19 @@ async function toPiContextWithImages(options, images, onReplayDegrade) {
6315
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 });
6316
6659
  }
6317
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
+ };
6318
6665
  const toolNames = /* @__PURE__ */ new Map();
6319
6666
  const messages = [];
6320
6667
  for (const message of exactMessages) {
6321
6668
  if (appendSystemOrAssistant(message, messages, toolNames, onReplayDegrade)) continue;
6322
6669
  if (message.role === "tool") {
6323
- messages.push(toolResultOf(message, toolNames, userContent(message.content, requestImages, resolveImageAccess)));
6670
+ messages.push(toolResultOf(message, toolNames, toolContent(message.content, requestImages, resolveImageAccess, files)));
6324
6671
  continue;
6325
6672
  }
6326
- const content = userContent(message.content, requestImages, resolveImageAccess);
6673
+ const content = userContent(message.content, requestImages, resolveImageAccess, files);
6327
6674
  messages.push({
6328
6675
  role: "user",
6329
6676
  content,
@@ -7357,6 +7704,19 @@ function reasoningInfo(model, catalog) {
7357
7704
  ...starting === void 0 ? {} : { defaultEffort: ReasoningEffortId(effortOf(starting)) }
7358
7705
  } };
7359
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
+ }
7360
7720
  /** A JSON object payload pi-ai is about to send, or undefined for anything else. */
7361
7721
  function objectPayload(payload) {
7362
7722
  return typeof payload === "object" && payload !== null && !Array.isArray(payload) ? payload : void 0;
@@ -7429,6 +7789,30 @@ var GatewayAdapter = class extends LlmAdapter {
7429
7789
  maxBytes: DEFAULT_REQUEST_IMAGE_MAX_BYTES
7430
7790
  });
7431
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
+ }
7432
7816
  providerInfo(provider) {
7433
7817
  this.assertOwned(provider);
7434
7818
  const relay = this.config.relayProvider;
@@ -7450,7 +7834,8 @@ var GatewayAdapter = class extends LlmAdapter {
7450
7834
  const promotions = await this.promotions();
7451
7835
  return listed.filter((model) => !hideRelay || !relayIdentity(model.id).relay).map((model) => {
7452
7836
  const promotion = promotions.get(model.id);
7453
- const family = snapshot.byId.get(model.id)?.family;
7837
+ const entry = snapshot.byId.get(model.id);
7838
+ const family = entry?.family;
7454
7839
  const pinOrder = preferred.get(model.id);
7455
7840
  const picker = family === void 0 && pinOrder === void 0 ? void 0 : {
7456
7841
  ...family === void 0 ? {} : { family },
@@ -7460,7 +7845,7 @@ var GatewayAdapter = class extends LlmAdapter {
7460
7845
  provider,
7461
7846
  id: model.id,
7462
7847
  name: model.name,
7463
- inputModalities: [...model.input],
7848
+ inputModalities: inputModalitiesOf(model, entry),
7464
7849
  ...picker === void 0 ? {} : { picker },
7465
7850
  ...promotion === void 0 ? {} : {
7466
7851
  badge: promotionBadge(promotion),
@@ -7489,7 +7874,7 @@ var GatewayAdapter = class extends LlmAdapter {
7489
7874
  provider,
7490
7875
  id,
7491
7876
  name: model.name,
7492
- inputModalities: [...model.input],
7877
+ inputModalities: inputModalitiesOf(model, catalog),
7493
7878
  context: { contextWindow: model.contextWindow },
7494
7879
  defaultMaxTokens: model.maxTokens,
7495
7880
  ...reasoningInfo(model, catalog)
@@ -7529,7 +7914,9 @@ var GatewayAdapter = class extends LlmAdapter {
7529
7914
  try {
7530
7915
  const containsImage = options.messages.some((message) => contentHasImage(message.content));
7531
7916
  if (containsImage && !model.input.includes("image")) throw new LlmError(`VibeDev model "${model.id}" does not support image input`, "UNSUPPORTED_CONTENT");
7532
- 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;
7533
7920
  if (containsImage && attachments === void 0) throw new LlmError("image input requires the durable attachment service", "UNSUPPORTED_CONTENT");
7534
7921
  const onReplayDegrade = (reason) => {
7535
7922
  this.config.onReplayDegrade?.({
@@ -7538,6 +7925,21 @@ var GatewayAdapter = class extends LlmAdapter {
7538
7925
  reason
7539
7926
  });
7540
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 = [];
7541
7943
  const context = attachments === void 0 ? toPiContext(options, void 0, onReplayDegrade) : await toPiContext({
7542
7944
  ...options,
7543
7945
  signal: watchdog.signal
@@ -7548,7 +7950,14 @@ var GatewayAdapter = class extends LlmAdapter {
7548
7950
  requestImagePolicy: {
7549
7951
  maxPixels: DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET,
7550
7952
  maxBytes: DEFAULT_REQUEST_IMAGE_MAX_BYTES
7551
- }
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
+ } } : {}
7552
7961
  }, onReplayDegrade);
7553
7962
  const enabledReasoning = reasoning === void 0 || reasoning === "off" ? void 0 : reasoning;
7554
7963
  const offersNone = catalog.reasoningLevels?.includes("none") === true;
@@ -7594,7 +8003,8 @@ var GatewayAdapter = class extends LlmAdapter {
7594
8003
  ...sessionId === void 0 ? {} : { sessionId },
7595
8004
  off: reasoning === "off" && offersNone,
7596
8005
  reasoning: enabledReasoning !== void 0,
7597
- claudeCacheTtl
8006
+ claudeCacheTtl,
8007
+ nativeFiles
7598
8008
  }),
7599
8009
  fetch: observingFetch,
7600
8010
  onResponse: (received) => {
@@ -7663,7 +8073,9 @@ var GatewayAdapter = class extends LlmAdapter {
7663
8073
  /**
7664
8074
  * Fit pi-ai's payload to the gateway: Chat Completions gets the session's cache key (pi-ai sends it
7665
8075
  * only to api.openai.com), "off" is spelled out where the catalog offers `none`, and Responses
7666
- * 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.
7667
8079
  */
7668
8080
  shapePayload(payload, model, request) {
7669
8081
  const body = objectPayload(payload);
@@ -7676,6 +8088,10 @@ var GatewayAdapter = class extends LlmAdapter {
7676
8088
  shaped.thinking = { type: "disabled" };
7677
8089
  delete shaped.reasoning_effort;
7678
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
+ }
7679
8095
  break;
7680
8096
  case "openai-responses":
7681
8097
  if (request.off) shaped.reasoning = {
@@ -7828,6 +8244,9 @@ function installGatewayModels(ctx, options) {
7828
8244
  onReplayDegrade: ({ provider, model, reason }) => {
7829
8245
  ctx.logger.warn(`dsh-vibedev: unusable replay state on assistant history for "${provider}/${model}"; sending provider-neutral content (${reason})`);
7830
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
+ },
7831
8250
  ...options.onRequestEnded === void 0 ? {} : { onRequestEnded: options.onRequestEnded },
7832
8251
  ...options.promotions === void 0 ? {} : { promotions: options.promotions }
7833
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
  /**
@@ -132,6 +143,20 @@ export declare class GatewayAdapter extends LlmAdapter {
132
143
  * screenshot again afterwards and put the model's coordinates out of step with the tool's.
133
144
  */
134
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;
135
160
  providerInfo(provider: string): LlmProviderInfo;
136
161
  providerRetryPolicy(provider: string): ResolvedRetryPolicy | undefined;
137
162
  listModels(provider: string): Promise<readonly GatewayListedModel[]>;
@@ -146,7 +171,9 @@ export declare class GatewayAdapter extends LlmAdapter {
146
171
  /**
147
172
  * Fit pi-ai's payload to the gateway: Chat Completions gets the session's cache key (pi-ai sends it
148
173
  * only to api.openai.com), "off" is spelled out where the catalog offers `none`, and Responses
149
- * 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.
150
177
  */
151
178
  private shapePayload;
152
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.
@@ -5,7 +5,8 @@
5
5
  * so the gateway adapter can choose a wire protocol per model. Keep it in step with upstream.
6
6
  *
7
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`).
8
+ * system message (see `systemText`). Native audio/video files (`files`, see ./native-files.ts) follow the VibeDev fork
9
+ * (vibedev 5be6bcec).
9
10
  *
10
11
  * Harness request-history conversion into pi-ai's Context vocabulary.
11
12
  *
@@ -14,6 +15,7 @@
14
15
  import type { GenerateOptions, ImageAttachmentAccessResolver } from '@deepseek-ai/dsh-llm';
15
16
  import type { AttachmentStore, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment';
16
17
  import type { Context as PiContext } from '@earendil-works/pi-ai';
18
+ import type { PiFileRequestContext } from './native-files.js';
17
19
  /** Inputs that bind deterministic request images to one current tool execution world. */
18
20
  export interface PiImageRequestContext {
19
21
  /** Durable provider that resolves request-image bytes and provider-owned host objects. */
@@ -24,6 +26,11 @@ export interface PiImageRequestContext {
24
26
  maxRequestImageBytes?: number;
25
27
  /** Route pixel and raw encoded-byte budgets. */
26
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;
27
34
  }
28
35
  /** Per-route budgets from which each request image's target is derived. */
29
36
  export interface PiImageRequestBudget {
@@ -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.1",
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",