@vibedev-si/dsh-vibedev 0.12.0 → 0.13.0
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/THIRD-PARTY-NOTICES.txt +1 -1
- package/lib/index.js +596 -204
- package/lib/llm/adapter.d.ts +3 -0
- package/lib/llm/context.d.ts +2 -0
- package/lib/llm/file-placement.d.ts +31 -0
- package/lib/llm/native-files.d.ts +4 -14
- package/lib/llm/verified-files.d.ts +63 -0
- package/package.json +1 -1
package/THIRD-PARTY-NOTICES.txt
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
THIRD-PARTY NOTICES · @vibedev-si/dsh-vibedev 0.
|
|
1
|
+
THIRD-PARTY NOTICES · @vibedev-si/dsh-vibedev 0.13.0
|
|
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.
|
package/lib/index.js
CHANGED
|
@@ -51,7 +51,7 @@ const MIN_READ_SPACING_MS = 5e3;
|
|
|
51
51
|
*/
|
|
52
52
|
const CATALOG_REFRESH_GAP_MS = 6e4;
|
|
53
53
|
const record$17 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
54
|
-
const text$
|
|
54
|
+
const text$11 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
|
|
55
55
|
/**
|
|
56
56
|
* A gateway amount as plain decimal text: a number as JavaScript writes it (`99976091.91426945`; the few numbers it
|
|
57
57
|
* writes with an exponent are spelled out), a string as sent; anything else, or text that is not a plain decimal, is
|
|
@@ -63,7 +63,7 @@ function amountOf(value) {
|
|
|
63
63
|
if (!Number.isFinite(value)) return void 0;
|
|
64
64
|
raw = String(value);
|
|
65
65
|
if (raw.includes("e")) raw = Math.abs(value) >= 1 ? BigInt(value).toString() : value.toFixed(20).replace(/0+$/, "").replace(/\.$/, "");
|
|
66
|
-
} else raw = text$
|
|
66
|
+
} else raw = text$11(value);
|
|
67
67
|
return raw !== void 0 && /^-?\d+(\.\d+)?$/.test(raw) ? raw : void 0;
|
|
68
68
|
}
|
|
69
69
|
/** What a read showed, for telling whether the next one changed anything (when it was read is not a change). */
|
|
@@ -309,11 +309,11 @@ var AccountService = class {
|
|
|
309
309
|
const body = record$17(await response.json().catch(() => void 0));
|
|
310
310
|
const data = record$17(body?.data) ?? body;
|
|
311
311
|
const balance = amountOf(data?.balance);
|
|
312
|
-
const currency = text$
|
|
312
|
+
const currency = text$11(data?.currency) ?? "CNY";
|
|
313
313
|
const frozen = amountOf(data?.frozen_balance);
|
|
314
|
-
const id = typeof data?.id === "number" ? String(data.id) : text$
|
|
315
|
-
const nickname = text$
|
|
316
|
-
const email = text$
|
|
314
|
+
const id = typeof data?.id === "number" ? String(data.id) : text$11(data?.id);
|
|
315
|
+
const nickname = text$11(data?.nickname) ?? text$11(data?.username);
|
|
316
|
+
const email = text$11(data?.email);
|
|
317
317
|
const user = id === void 0 && nickname === void 0 && email === void 0 ? void 0 : {
|
|
318
318
|
...id === void 0 ? {} : { id },
|
|
319
319
|
...email === void 0 ? {} : { email },
|
|
@@ -610,7 +610,7 @@ function normalizeErrorStage(value) {
|
|
|
610
610
|
function record$16(value) {
|
|
611
611
|
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
612
612
|
}
|
|
613
|
-
function text$
|
|
613
|
+
function text$10(value) {
|
|
614
614
|
return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
|
|
615
615
|
}
|
|
616
616
|
function count$1(value) {
|
|
@@ -619,7 +619,7 @@ function count$1(value) {
|
|
|
619
619
|
/** A CNY amount the gateway sends as a two-decimal string (a number is accepted too). */
|
|
620
620
|
function amount$2(value) {
|
|
621
621
|
if (typeof value === "number" && Number.isFinite(value)) return value.toFixed(2);
|
|
622
|
-
const raw = text$
|
|
622
|
+
const raw = text$10(value);
|
|
623
623
|
return raw !== void 0 && /^-?\d+(?:\.\d+)?$/.test(raw) ? raw : void 0;
|
|
624
624
|
}
|
|
625
625
|
/**
|
|
@@ -637,12 +637,12 @@ function parseGatewayFailure(body) {
|
|
|
637
637
|
if (root === void 0) return {};
|
|
638
638
|
const source = record$16(root.error) ?? root;
|
|
639
639
|
const metadata = record$16(source.metadata) ?? record$16(root.metadata);
|
|
640
|
-
const gatewayCode = text$
|
|
641
|
-
const code = gatewayCode ?? text$
|
|
642
|
-
const message = text$
|
|
643
|
-
const field = text$
|
|
644
|
-
const rule = text$
|
|
645
|
-
const rechargeUrl = text$
|
|
640
|
+
const gatewayCode = text$10(source.gateway_code) ?? text$10(root.gateway_code);
|
|
641
|
+
const code = gatewayCode ?? text$10(source.code) ?? text$10(source.type) ?? text$10(root.reason);
|
|
642
|
+
const message = text$10(source.message) ?? (typeof root.error === "string" ? text$10(root.error) : void 0);
|
|
643
|
+
const field = text$10(source.field) ?? text$10(metadata?.field);
|
|
644
|
+
const rule = text$10(source.rule) ?? text$10(metadata?.rule);
|
|
645
|
+
const rechargeUrl = text$10(source.recharge_url) ?? text$10(root.recharge_url);
|
|
646
646
|
const numbers = {
|
|
647
647
|
active: count$1(source.active),
|
|
648
648
|
limit: count$1(source.limit)
|
|
@@ -652,19 +652,19 @@ function parseGatewayFailure(body) {
|
|
|
652
652
|
availableCny: amount$2(source.available_cny),
|
|
653
653
|
pendingCny: amount$2(source.pending_cny)
|
|
654
654
|
};
|
|
655
|
-
const submissionState = text$
|
|
656
|
-
const retryAction = text$
|
|
657
|
-
const assetId = text$
|
|
655
|
+
const submissionState = text$10(source.submission_state) ?? text$10(root.submission_state);
|
|
656
|
+
const retryAction = text$10(source.retry_action) ?? text$10(root.retry_action);
|
|
657
|
+
const assetId = text$10(source.asset_id) ?? text$10(root.asset_id);
|
|
658
658
|
return {
|
|
659
659
|
...gatewayCode === void 0 ? {} : { gatewayCode },
|
|
660
660
|
...Object.fromEntries(Object.entries({
|
|
661
|
-
category: normalizeErrorCategory(text$
|
|
662
|
-
stage: normalizeErrorStage(text$
|
|
663
|
-
requestId: text$
|
|
664
|
-
taskId: text$
|
|
665
|
-
operationId: text$
|
|
666
|
-
billingState: text$
|
|
667
|
-
retryAt: text$
|
|
661
|
+
category: normalizeErrorCategory(text$10(source.category) ?? text$10(root.category), code),
|
|
662
|
+
stage: normalizeErrorStage(text$10(source.stage) ?? text$10(root.stage)),
|
|
663
|
+
requestId: text$10(source.request_id) ?? text$10(root.request_id),
|
|
664
|
+
taskId: text$10(source.task_id) ?? text$10(root.task_id),
|
|
665
|
+
operationId: text$10(source.operation_id) ?? text$10(root.operation_id),
|
|
666
|
+
billingState: text$10(source.billing_state) ?? text$10(root.billing_state),
|
|
667
|
+
retryAt: text$10(source.retry_at) ?? text$10(root.retry_at),
|
|
668
668
|
retryAfterSeconds: count$1(source.retry_after_seconds) ?? count$1(root.retry_after_seconds)
|
|
669
669
|
}).filter(([, value]) => value !== void 0)),
|
|
670
670
|
...code === void 0 ? {} : { code },
|
|
@@ -731,11 +731,11 @@ function gatewayFailureWithHeaders(body, headers) {
|
|
|
731
731
|
const failure = parseGatewayFailure(body);
|
|
732
732
|
return {
|
|
733
733
|
...failure,
|
|
734
|
-
code: failure.gatewayCode ?? text$
|
|
735
|
-
category: normalizeErrorCategory(failure.category ?? text$
|
|
736
|
-
requestId: failure.requestId ?? text$
|
|
737
|
-
retryAction: failure.retryAction ?? text$
|
|
738
|
-
retryAt: failure.retryAt ?? text$
|
|
734
|
+
code: failure.gatewayCode ?? text$10(headers.get("x-vibedev-error-code")) ?? failure.code,
|
|
735
|
+
category: normalizeErrorCategory(failure.category ?? text$10(headers.get("x-vibedev-error-category")), failure.gatewayCode ?? text$10(headers.get("x-vibedev-error-code")) ?? failure.code),
|
|
736
|
+
requestId: failure.requestId ?? text$10(headers.get("x-request-id")),
|
|
737
|
+
retryAction: failure.retryAction ?? text$10(headers.get("x-vibedev-retry-action")),
|
|
738
|
+
retryAt: failure.retryAt ?? text$10(headers.get("x-vibedev-retry-at"))
|
|
739
739
|
};
|
|
740
740
|
}
|
|
741
741
|
function isUserAuthenticationFailure(failure) {
|
|
@@ -744,14 +744,14 @@ function isUserAuthenticationFailure(failure) {
|
|
|
744
744
|
function sdkGatewayFailure(message, headers = {}) {
|
|
745
745
|
const prefix = /\bvibedev:([A-Z][A-Z0-9_]{1,100}):/.exec(message)?.[1];
|
|
746
746
|
const legacy = /["'](?:gateway_code|code)["']\s*:\s*["'](APP_TOKEN_EXPIRED|APP_TOKEN_INVALID|INVALID_API_KEY|APP_SESSION_REVOKED|SESSION_REVOKED|AUTHENTICATION_REQUIRED)["']/.exec(message)?.[1];
|
|
747
|
-
const code = text$
|
|
748
|
-
const category = text$
|
|
747
|
+
const code = text$10(headers["x-vibedev-error-code"]) ?? prefix ?? legacy;
|
|
748
|
+
const category = text$10(headers["x-vibedev-error-category"]) ?? (code === void 0 ? void 0 : /^(?:APP_TOKEN_EXPIRED|APP_TOKEN_INVALID|INVALID_API_KEY|APP_SESSION_REVOKED|SESSION_REVOKED|AUTHENTICATION_REQUIRED)$/.test(code) ? "authentication" : /^(?:BALANCE_INSUFFICIENT|SUBSCRIPTION_QUOTA_EXHAUSTED|MODEL_NOT_INCLUDED|BILLING_SOURCE_UNAVAILABLE)$/.test(code) ? "billing" : code === "CONTENT_REJECTED" ? "content_rejected" : code === "SUBMISSION_UNCERTAIN" ? "submission_uncertain" : /^(?:UPSTREAM_UNAVAILABLE|TASK_QUERY_UNAVAILABLE|RESULT_DOWNLOAD_UNAVAILABLE)$/.test(code) ? "service_unavailable" : "internal_error");
|
|
749
749
|
if (code === void 0 && category === void 0) return void 0;
|
|
750
750
|
return {
|
|
751
751
|
code,
|
|
752
752
|
category: normalizeErrorCategory(category, code),
|
|
753
|
-
requestId: text$
|
|
754
|
-
retryAction: text$
|
|
753
|
+
requestId: text$10(headers["x-request-id"]),
|
|
754
|
+
retryAction: text$10(headers["x-vibedev-retry-action"])
|
|
755
755
|
};
|
|
756
756
|
}
|
|
757
757
|
//#endregion
|
|
@@ -2811,7 +2811,7 @@ const unavailable = () => json$2(200, {
|
|
|
2811
2811
|
unread: 0
|
|
2812
2812
|
});
|
|
2813
2813
|
const record$13 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
2814
|
-
const text$
|
|
2814
|
+
const text$9 = (value) => typeof value === "string" ? value : void 0;
|
|
2815
2815
|
const identifier = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
|
|
2816
2816
|
/**
|
|
2817
2817
|
* One announcement from the wire, with every field it needs and nothing else.
|
|
@@ -2822,9 +2822,9 @@ function parseAnnouncement(value) {
|
|
|
2822
2822
|
const item = record$13(value);
|
|
2823
2823
|
if (item === void 0) return void 0;
|
|
2824
2824
|
const id = identifier(item.id);
|
|
2825
|
-
const title = text$
|
|
2826
|
-
const content = text$
|
|
2827
|
-
const createdAt = text$
|
|
2825
|
+
const title = text$9(item.title);
|
|
2826
|
+
const content = text$9(item.content);
|
|
2827
|
+
const createdAt = text$9(item.created_at);
|
|
2828
2828
|
if (id === void 0 || title === void 0 || content === void 0 || createdAt === void 0) return void 0;
|
|
2829
2829
|
return {
|
|
2830
2830
|
id,
|
|
@@ -2834,7 +2834,7 @@ function parseAnnouncement(value) {
|
|
|
2834
2834
|
notifyMode: item.notify_mode === "popup" ? "popup" : "silent",
|
|
2835
2835
|
...typeof item.starts_at === "string" ? { startsAt: item.starts_at } : {},
|
|
2836
2836
|
...typeof item.ends_at === "string" ? { endsAt: item.ends_at } : {},
|
|
2837
|
-
readAt: text$
|
|
2837
|
+
readAt: text$9(item.read_at) ?? null
|
|
2838
2838
|
};
|
|
2839
2839
|
}
|
|
2840
2840
|
/**
|
|
@@ -5186,13 +5186,13 @@ const CALLBACK_PATH = "/dsh-media/callback";
|
|
|
5186
5186
|
*/
|
|
5187
5187
|
function refusalCode(body) {
|
|
5188
5188
|
const raw = record$11(body);
|
|
5189
|
-
return text$
|
|
5189
|
+
return text$8(raw?.reason) ?? text$8(raw?.code) ?? text$8(record$11(raw?.error)?.code);
|
|
5190
5190
|
}
|
|
5191
5191
|
function base64url(data) {
|
|
5192
5192
|
return data.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
5193
5193
|
}
|
|
5194
5194
|
const record$11 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
5195
|
-
const text$
|
|
5195
|
+
const text$8 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
|
|
5196
5196
|
/**
|
|
5197
5197
|
* Read a token answer (`redeem` or `refresh`).
|
|
5198
5198
|
* @param body - the parsed envelope `{code, data}` or a bare data object.
|
|
@@ -5203,16 +5203,16 @@ const text$7 = (value) => typeof value === "string" && value.trim() !== "" ? val
|
|
|
5203
5203
|
function parseGrant(body, now, previous) {
|
|
5204
5204
|
const envelope = record$11(body);
|
|
5205
5205
|
const data = record$11(envelope?.data) ?? envelope;
|
|
5206
|
-
const accessToken = text$
|
|
5207
|
-
const refreshToken = text$
|
|
5206
|
+
const accessToken = text$8(data?.access_token);
|
|
5207
|
+
const refreshToken = text$8(data?.refresh_token);
|
|
5208
5208
|
if (data === void 0 || accessToken === void 0 || refreshToken === void 0) return void 0;
|
|
5209
5209
|
const seconds = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
|
|
5210
5210
|
const user = record$11(data.user);
|
|
5211
|
-
const sessionId = text$
|
|
5211
|
+
const sessionId = text$8(data.session_id) ?? previous?.sessionId;
|
|
5212
5212
|
const parsedUser = user === void 0 ? previous?.user : {
|
|
5213
|
-
...text$
|
|
5214
|
-
...text$
|
|
5215
|
-
...text$
|
|
5213
|
+
...text$8(user.id) === void 0 && typeof user.id !== "number" ? {} : { id: String(user.id) },
|
|
5214
|
+
...text$8(user.email) === void 0 ? {} : { email: text$8(user.email) },
|
|
5215
|
+
...text$8(user.nickname) === void 0 ? {} : { nickname: text$8(user.nickname) }
|
|
5216
5216
|
};
|
|
5217
5217
|
return {
|
|
5218
5218
|
accessToken,
|
|
@@ -6278,6 +6278,141 @@ function toPiAssistant(message, onDegrade) {
|
|
|
6278
6278
|
}
|
|
6279
6279
|
}
|
|
6280
6280
|
//#endregion
|
|
6281
|
+
//#region src/llm/file-placement.ts
|
|
6282
|
+
/** Chat Completions places tool-result media in the SDK's adjacent user message. */
|
|
6283
|
+
const TOOL_RESULT_MEDIA_TEXT = "Attached media from tool result:";
|
|
6284
|
+
const imageHeading = "Attached image(s) from tool result:";
|
|
6285
|
+
const bridge = "I have processed the tool results.";
|
|
6286
|
+
function isRecord$1(value) {
|
|
6287
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
6288
|
+
}
|
|
6289
|
+
/**
|
|
6290
|
+
* Visit the user and tool text fields in which a generated attachment caption may appear.
|
|
6291
|
+
* @param messages - SDK Chat Completions messages.
|
|
6292
|
+
* @param visit - replace the visible text; content index -1 identifies a scalar string.
|
|
6293
|
+
* @returns messages with only the visited text fields replaced.
|
|
6294
|
+
*/
|
|
6295
|
+
function mapMediaText(messages, visit) {
|
|
6296
|
+
return messages.map((message, index) => {
|
|
6297
|
+
if (!isRecord$1(message) || message.role !== "user" && message.role !== "tool") return message;
|
|
6298
|
+
const role = message.role;
|
|
6299
|
+
if (typeof message.content === "string") return {
|
|
6300
|
+
...message,
|
|
6301
|
+
content: visit(message.content, role, index, -1)
|
|
6302
|
+
};
|
|
6303
|
+
if (!Array.isArray(message.content)) return message;
|
|
6304
|
+
const content = message.content.map((part, i) => isRecord$1(part) && part.type === "text" && typeof part.text === "string" ? {
|
|
6305
|
+
...part,
|
|
6306
|
+
text: visit(part.text, role, index, i)
|
|
6307
|
+
} : part);
|
|
6308
|
+
return {
|
|
6309
|
+
...message,
|
|
6310
|
+
content
|
|
6311
|
+
};
|
|
6312
|
+
});
|
|
6313
|
+
}
|
|
6314
|
+
/**
|
|
6315
|
+
* Strip every native file from message content, including in an unsupported role.
|
|
6316
|
+
* @param messages - SDK messages before placement of verified files.
|
|
6317
|
+
* @returns the filtered messages, or undefined if the body already has no files.
|
|
6318
|
+
*/
|
|
6319
|
+
function stripVisibleNativeFiles(messages) {
|
|
6320
|
+
let changed = false;
|
|
6321
|
+
const stripped = messages.map((message) => {
|
|
6322
|
+
if (!isRecord$1(message) || !Array.isArray(message.content)) return message;
|
|
6323
|
+
const content = message.content.filter((part) => !isRecord$1(part) || part.type !== "file");
|
|
6324
|
+
if (content.length === message.content.length) return message;
|
|
6325
|
+
changed = true;
|
|
6326
|
+
return {
|
|
6327
|
+
...message,
|
|
6328
|
+
content
|
|
6329
|
+
};
|
|
6330
|
+
});
|
|
6331
|
+
return changed ? stripped : void 0;
|
|
6332
|
+
}
|
|
6333
|
+
function toolMessage(item) {
|
|
6334
|
+
return isRecord$1(item) && item.role === "tool";
|
|
6335
|
+
}
|
|
6336
|
+
function imageFollowUp(item) {
|
|
6337
|
+
if (!isRecord$1(item) || item.role !== "user" || !Array.isArray(item.content)) return false;
|
|
6338
|
+
const first = item.content[0];
|
|
6339
|
+
return isRecord$1(first) && first.type === "text" && first.text === imageHeading && item.content.some((part) => isRecord$1(part) && part.type === "image_url");
|
|
6340
|
+
}
|
|
6341
|
+
/** Resolve exact user parts or tool-result lines. All other messages, calls and image parts keep their order. */
|
|
6342
|
+
function placeNativeFiles(payload, resolve, assistantAfterToolResult = false) {
|
|
6343
|
+
if (!isRecord$1(payload) || !Array.isArray(payload.messages)) return void 0;
|
|
6344
|
+
const original = payload.messages;
|
|
6345
|
+
const messages = [];
|
|
6346
|
+
let changed = false;
|
|
6347
|
+
let index = 0;
|
|
6348
|
+
while (index < original.length) {
|
|
6349
|
+
const message = original[index];
|
|
6350
|
+
if (!toolMessage(message)) {
|
|
6351
|
+
if (isRecord$1(message) && message.role === "user" && Array.isArray(message.content)) {
|
|
6352
|
+
const content = message.content.flatMap((part) => {
|
|
6353
|
+
if (!isRecord$1(part) || part.type !== "text" || typeof part.text !== "string") return [part];
|
|
6354
|
+
const replacement = resolve(part.text, "user", index);
|
|
6355
|
+
if (replacement === void 0) return [part];
|
|
6356
|
+
changed = true;
|
|
6357
|
+
return [...replacement];
|
|
6358
|
+
});
|
|
6359
|
+
messages.push({
|
|
6360
|
+
...message,
|
|
6361
|
+
content
|
|
6362
|
+
});
|
|
6363
|
+
} else messages.push(message);
|
|
6364
|
+
index++;
|
|
6365
|
+
continue;
|
|
6366
|
+
}
|
|
6367
|
+
const moved = [];
|
|
6368
|
+
for (; index < original.length && toolMessage(original[index]); index++) {
|
|
6369
|
+
const tool = original[index];
|
|
6370
|
+
let stripped = false;
|
|
6371
|
+
const keep = (line) => {
|
|
6372
|
+
const replacement = resolve(line, "tool", index);
|
|
6373
|
+
if (replacement === void 0) return true;
|
|
6374
|
+
moved.push(...replacement);
|
|
6375
|
+
stripped = true;
|
|
6376
|
+
return false;
|
|
6377
|
+
};
|
|
6378
|
+
const content = typeof tool.content === "string" ? tool.content.split("\n").filter(keep).join("\n") || "(see attached media)" : Array.isArray(tool.content) ? tool.content.filter((part) => !(isRecord$1(part) && part.type === "text" && typeof part.text === "string") || keep(part.text)) : tool.content;
|
|
6379
|
+
changed ||= stripped;
|
|
6380
|
+
messages.push(stripped ? {
|
|
6381
|
+
...tool,
|
|
6382
|
+
content
|
|
6383
|
+
} : tool);
|
|
6384
|
+
}
|
|
6385
|
+
if (!moved.length) continue;
|
|
6386
|
+
const next = original[index];
|
|
6387
|
+
const hasBridge = isRecord$1(next) && next.role === "assistant" && next.content === bridge;
|
|
6388
|
+
const followUp = original[index + Number(hasBridge)];
|
|
6389
|
+
if (imageFollowUp(followUp)) {
|
|
6390
|
+
if (hasBridge) messages.push(next);
|
|
6391
|
+
messages.push({
|
|
6392
|
+
...followUp,
|
|
6393
|
+
content: [...followUp.content, ...moved]
|
|
6394
|
+
});
|
|
6395
|
+
index += 1 + Number(hasBridge);
|
|
6396
|
+
} else {
|
|
6397
|
+
if (assistantAfterToolResult) messages.push({
|
|
6398
|
+
role: "assistant",
|
|
6399
|
+
content: bridge
|
|
6400
|
+
});
|
|
6401
|
+
messages.push({
|
|
6402
|
+
role: "user",
|
|
6403
|
+
content: [{
|
|
6404
|
+
type: "text",
|
|
6405
|
+
text: TOOL_RESULT_MEDIA_TEXT
|
|
6406
|
+
}, ...moved]
|
|
6407
|
+
});
|
|
6408
|
+
}
|
|
6409
|
+
}
|
|
6410
|
+
return changed ? {
|
|
6411
|
+
...payload,
|
|
6412
|
+
messages
|
|
6413
|
+
} : void 0;
|
|
6414
|
+
}
|
|
6415
|
+
//#endregion
|
|
6281
6416
|
//#region src/llm/native-files.ts
|
|
6282
6417
|
/**
|
|
6283
6418
|
* Native audio/video delivery for the gateway's Chat Completions models.
|
|
@@ -6343,12 +6478,6 @@ const GEMINI_INLINE_MEDIA_TYPES = Object.freeze([
|
|
|
6343
6478
|
"audio/ogg",
|
|
6344
6479
|
"audio/flac"
|
|
6345
6480
|
]);
|
|
6346
|
-
/** Text that opens the user message carrying tool-result media. */
|
|
6347
|
-
const TOOL_RESULT_MEDIA_TEXT = "Attached media from tool result:";
|
|
6348
|
-
/** Text pi-ai opens its tool-result image follow-up with; media joins that message. */
|
|
6349
|
-
const PI_TOOL_RESULT_IMAGE_TEXT = "Attached image(s) from tool result:";
|
|
6350
|
-
/** pi-ai's bridge between tool results and a user message under `requiresAssistantAfterToolResult`. */
|
|
6351
|
-
const PI_TOOL_RESULT_BRIDGE = "I have processed the tool results.";
|
|
6352
6481
|
/**
|
|
6353
6482
|
* Text part that holds one delivered file's place until the payload hook replaces it. Deterministic, so identical
|
|
6354
6483
|
* histories convert identically, and NUL-delimited, so no user-authored text block equals it.
|
|
@@ -6412,8 +6541,8 @@ async function readNativeFiles(messages, attachments, files, signal) {
|
|
|
6412
6541
|
}
|
|
6413
6542
|
try {
|
|
6414
6543
|
const file = await readFileRequest.call(attachments, ref, {
|
|
6415
|
-
|
|
6416
|
-
|
|
6544
|
+
maxBytes,
|
|
6545
|
+
...target.mediaTypes === void 0 ? {} : { mediaTypes: target.mediaTypes }
|
|
6417
6546
|
}, signal);
|
|
6418
6547
|
if (!(file.data instanceof Uint8Array) || typeof file.mediaType !== "string" || file.mediaType === "") throw new Error("the attachment provider returned no bytes or media type");
|
|
6419
6548
|
if (file.data.byteLength > maxBytes) throw new Error(`the file read has ${file.data.byteLength} bytes, over the ${maxBytes}-byte native file limit`);
|
|
@@ -6446,143 +6575,11 @@ function nativeFilePart(file) {
|
|
|
6446
6575
|
file: { file_data: `data:${file.mediaType};base64,${Buffer.from(file.data.buffer, file.data.byteOffset, file.data.byteLength).toString("base64")}` }
|
|
6447
6576
|
};
|
|
6448
6577
|
}
|
|
6449
|
-
|
|
6450
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
6451
|
-
}
|
|
6452
|
-
function isToolMessage(message) {
|
|
6453
|
-
return isRecord$1(message) && message.role === "tool";
|
|
6454
|
-
}
|
|
6455
|
-
/** pi-ai's tool-result image follow-up, whose image parts the moved media joins. */
|
|
6456
|
-
function isImageFollowUp(message) {
|
|
6457
|
-
if (!isRecord$1(message) || message.role !== "user" || !Array.isArray(message.content)) return false;
|
|
6458
|
-
const first = message.content[0];
|
|
6459
|
-
return isRecord$1(first) && first.type === "text" && first.text === PI_TOOL_RESULT_IMAGE_TEXT;
|
|
6460
|
-
}
|
|
6461
|
-
function isToolResultBridge(message) {
|
|
6462
|
-
return isRecord$1(message) && message.role === "assistant" && message.content === PI_TOOL_RESULT_BRIDGE;
|
|
6463
|
-
}
|
|
6464
|
-
/**
|
|
6465
|
-
* Take the markers out of one tool message. pi-ai joins a tool result's text parts with newlines and each marker is a
|
|
6466
|
-
* part of its own (the conversion puts them after the result's text), so dropping the marker lines leaves exactly
|
|
6467
|
-
* the text the result has without its files.
|
|
6468
|
-
*/
|
|
6469
|
-
function stripToolMarkers(message, markers) {
|
|
6470
|
-
const files = [];
|
|
6471
|
-
const content = message.content;
|
|
6472
|
-
if (typeof content === "string") {
|
|
6473
|
-
if (!content.includes("\0")) return {
|
|
6474
|
-
message,
|
|
6475
|
-
files
|
|
6476
|
-
};
|
|
6477
|
-
const lines = content.split("\n").filter((line) => {
|
|
6478
|
-
const file = markers.get(line);
|
|
6479
|
-
if (file !== void 0) files.push(file);
|
|
6480
|
-
return file === void 0;
|
|
6481
|
-
});
|
|
6482
|
-
if (files.length === 0) return {
|
|
6483
|
-
message,
|
|
6484
|
-
files
|
|
6485
|
-
};
|
|
6486
|
-
const text = lines.join("\n");
|
|
6487
|
-
return {
|
|
6488
|
-
message: {
|
|
6489
|
-
...message,
|
|
6490
|
-
content: text.length > 0 ? text : "(see attached media)"
|
|
6491
|
-
},
|
|
6492
|
-
files
|
|
6493
|
-
};
|
|
6494
|
-
}
|
|
6495
|
-
if (Array.isArray(content)) {
|
|
6496
|
-
const parts = content.filter((part) => {
|
|
6497
|
-
const file = isRecord$1(part) && part.type === "text" && typeof part.text === "string" ? markers.get(part.text) : void 0;
|
|
6498
|
-
if (file !== void 0) files.push(file);
|
|
6499
|
-
return file === void 0;
|
|
6500
|
-
});
|
|
6501
|
-
if (files.length > 0) return {
|
|
6502
|
-
message: {
|
|
6503
|
-
...message,
|
|
6504
|
-
content: parts
|
|
6505
|
-
},
|
|
6506
|
-
files
|
|
6507
|
-
};
|
|
6508
|
-
}
|
|
6509
|
-
return {
|
|
6510
|
-
message,
|
|
6511
|
-
files
|
|
6512
|
-
};
|
|
6513
|
-
}
|
|
6514
|
-
/**
|
|
6515
|
-
* Put every delivered file part into a Chat Completions payload. A marker part in a user message becomes the file
|
|
6516
|
-
* part in place. A Chat Completions `tool` message holds text only, so markers in a run of consecutive `tool`
|
|
6517
|
-
* messages leave the tool text (the handle text stays) and their parts, in tool-result then block order, go to the
|
|
6518
|
-
* user message right after the run: appended to pi-ai's "Attached image(s) from tool result:" message when pi-ai
|
|
6519
|
-
* added one, otherwise in a new `{role:'user',content:[{type:'text',text:'Attached media from tool result:'},…]}`,
|
|
6520
|
-
* preceded by pi-ai's bridging assistant message when the model requires one.
|
|
6521
|
-
* @param payload - the request body pi-ai built.
|
|
6522
|
-
* @param delivered - file parts by marker index.
|
|
6523
|
-
* @param options - the model's tool-result ordering rule.
|
|
6524
|
-
* @returns a shallow-copied payload, or undefined to keep it when no marker is present.
|
|
6525
|
-
*/
|
|
6578
|
+
/** Place each marker from a request projected by a legacy host. */
|
|
6526
6579
|
function injectNativeFiles(payload, delivered, options = {}) {
|
|
6527
|
-
if (delivered.length
|
|
6528
|
-
const markers = new Map(delivered.map((part, index) => [nativeFileMarker(index), part]));
|
|
6529
|
-
|
|
6530
|
-
const inPlace = (message) => {
|
|
6531
|
-
if (!isRecord$1(message) || !Array.isArray(message.content)) return message;
|
|
6532
|
-
const parts = message.content;
|
|
6533
|
-
if (!parts.some((part) => fileOf(part) !== void 0)) return message;
|
|
6534
|
-
return {
|
|
6535
|
-
...message,
|
|
6536
|
-
content: parts.map((part) => fileOf(part) ?? part)
|
|
6537
|
-
};
|
|
6538
|
-
};
|
|
6539
|
-
const original = payload.messages;
|
|
6540
|
-
const messages = [];
|
|
6541
|
-
let changed = false;
|
|
6542
|
-
let index = 0;
|
|
6543
|
-
while (index < original.length) {
|
|
6544
|
-
if (!isToolMessage(original[index])) {
|
|
6545
|
-
const message = inPlace(original[index]);
|
|
6546
|
-
changed ||= message !== original[index];
|
|
6547
|
-
messages.push(message);
|
|
6548
|
-
index++;
|
|
6549
|
-
continue;
|
|
6550
|
-
}
|
|
6551
|
-
const moved = [];
|
|
6552
|
-
for (; index < original.length && isToolMessage(original[index]); index++) {
|
|
6553
|
-
const stripped = stripToolMarkers(original[index], markers);
|
|
6554
|
-
messages.push(stripped.message);
|
|
6555
|
-
moved.push(...stripped.files);
|
|
6556
|
-
}
|
|
6557
|
-
if (moved.length === 0) continue;
|
|
6558
|
-
changed = true;
|
|
6559
|
-
const bridged = isToolResultBridge(original[index]) ? 1 : 0;
|
|
6560
|
-
const followUp = original[index + bridged];
|
|
6561
|
-
if (isImageFollowUp(followUp)) {
|
|
6562
|
-
if (bridged === 1) messages.push(original[index]);
|
|
6563
|
-
messages.push({
|
|
6564
|
-
...followUp,
|
|
6565
|
-
content: [...followUp.content, ...moved]
|
|
6566
|
-
});
|
|
6567
|
-
index += bridged + 1;
|
|
6568
|
-
continue;
|
|
6569
|
-
}
|
|
6570
|
-
if (options.assistantAfterToolResult === true) messages.push({
|
|
6571
|
-
role: "assistant",
|
|
6572
|
-
content: PI_TOOL_RESULT_BRIDGE
|
|
6573
|
-
});
|
|
6574
|
-
messages.push({
|
|
6575
|
-
role: "user",
|
|
6576
|
-
content: [{
|
|
6577
|
-
type: "text",
|
|
6578
|
-
text: TOOL_RESULT_MEDIA_TEXT
|
|
6579
|
-
}, ...moved]
|
|
6580
|
-
});
|
|
6581
|
-
}
|
|
6582
|
-
return changed ? {
|
|
6583
|
-
...payload,
|
|
6584
|
-
messages
|
|
6585
|
-
} : void 0;
|
|
6580
|
+
if (!delivered.length) return void 0;
|
|
6581
|
+
const markers = new Map(delivered.map((part, index) => [nativeFileMarker(index), [part]]));
|
|
6582
|
+
return placeNativeFiles(payload, (value) => markers.get(value), options.assistantAfterToolResult);
|
|
6586
6583
|
}
|
|
6587
6584
|
//#endregion
|
|
6588
6585
|
//#region src/llm/context.ts
|
|
@@ -6636,7 +6633,7 @@ function assertSupportedHistory(messages) {
|
|
|
6636
6633
|
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");
|
|
6637
6634
|
}
|
|
6638
6635
|
}
|
|
6639
|
-
function userContent(blocks, requestImages, resolveImageAccess, files) {
|
|
6636
|
+
function userContent(blocks, requestImages, resolveImageAccess, files, isWireMarker) {
|
|
6640
6637
|
const content = [];
|
|
6641
6638
|
let markers = 0;
|
|
6642
6639
|
for (const block of blocks) switch (block.type) {
|
|
@@ -6645,6 +6642,7 @@ function userContent(blocks, requestImages, resolveImageAccess, files) {
|
|
|
6645
6642
|
type: "text",
|
|
6646
6643
|
text: block.text
|
|
6647
6644
|
});
|
|
6645
|
+
if (isWireMarker?.(block.text)) markers++;
|
|
6648
6646
|
break;
|
|
6649
6647
|
case "file": {
|
|
6650
6648
|
const file = files?.read.get(block.attachment.attachmentId);
|
|
@@ -6680,17 +6678,18 @@ function userContent(blocks, requestImages, resolveImageAccess, files) {
|
|
|
6680
6678
|
* text only), dropping the marker's line. A text-only result keeps its text joined as without files, with the markers
|
|
6681
6679
|
* after it, so the tool text the model reads is the same whether or not a file went along.
|
|
6682
6680
|
*/
|
|
6683
|
-
function toolContent(blocks, requestImages, resolveImageAccess, files) {
|
|
6681
|
+
function toolContent(blocks, requestImages, resolveImageAccess, files, isWireMarker) {
|
|
6684
6682
|
const before = files?.delivered.length ?? 0;
|
|
6685
|
-
const content = userContent(blocks, requestImages, resolveImageAccess, files);
|
|
6686
|
-
if (typeof content === "string"
|
|
6683
|
+
const content = userContent(blocks, requestImages, resolveImageAccess, files, isWireMarker);
|
|
6684
|
+
if (typeof content === "string") return content;
|
|
6687
6685
|
if (!content.every((block) => block.type === "text")) return content;
|
|
6688
|
-
const markers = new Set(files
|
|
6689
|
-
const
|
|
6686
|
+
const markers = new Set(files?.delivered.slice(before).map((_, index) => nativeFileMarker(before + index)));
|
|
6687
|
+
const isMarker = (block) => markers.has(block.text) || isWireMarker?.(block.text) === true;
|
|
6688
|
+
const text = content.filter((block) => !isMarker(block)).map((block) => block.text).join("");
|
|
6690
6689
|
return [...text.length > 0 ? [{
|
|
6691
6690
|
type: "text",
|
|
6692
6691
|
text
|
|
6693
|
-
}] : [], ...content.filter(
|
|
6692
|
+
}] : [], ...content.filter(isMarker)];
|
|
6694
6693
|
}
|
|
6695
6694
|
function collectImageRefs(blocks, refs) {
|
|
6696
6695
|
for (const block of blocks) if (block.type === "image") {
|
|
@@ -6829,10 +6828,10 @@ async function toPiContextWithImages(options, images, onReplayDegrade) {
|
|
|
6829
6828
|
for (const message of exactMessages) {
|
|
6830
6829
|
if (appendSystemOrAssistant(message, messages, toolNames, onReplayDegrade)) continue;
|
|
6831
6830
|
if (message.role === "tool") {
|
|
6832
|
-
messages.push(toolResultOf(message, toolNames, toolContent(message.content, requestImages, resolveImageAccess, files)));
|
|
6831
|
+
messages.push(toolResultOf(message, toolNames, toolContent(message.content, requestImages, resolveImageAccess, files, images.isWireMarker)));
|
|
6833
6832
|
continue;
|
|
6834
6833
|
}
|
|
6835
|
-
const content = userContent(message.content, requestImages, resolveImageAccess, files);
|
|
6834
|
+
const content = userContent(message.content, requestImages, resolveImageAccess, files, images.isWireMarker);
|
|
6836
6835
|
messages.push({
|
|
6837
6836
|
role: "user",
|
|
6838
6837
|
content,
|
|
@@ -6842,6 +6841,369 @@ async function toPiContextWithImages(options, images, onReplayDegrade) {
|
|
|
6842
6841
|
return piContext(split.systemPrompt, options, messages);
|
|
6843
6842
|
}
|
|
6844
6843
|
//#endregion
|
|
6844
|
+
//#region src/llm/verified-files.ts
|
|
6845
|
+
/** Request-local projection and final Chat Completions file/handle reconciliation. Mirrored in llm-pi-ai. */
|
|
6846
|
+
function fileReceiptAttempt(observe) {
|
|
6847
|
+
if (!observe) return void 0;
|
|
6848
|
+
const attemptId = randomUUID();
|
|
6849
|
+
let snapshot;
|
|
6850
|
+
function emit(stage, httpStatus) {
|
|
6851
|
+
if (!snapshot) return;
|
|
6852
|
+
try {
|
|
6853
|
+
observe({
|
|
6854
|
+
attemptId,
|
|
6855
|
+
...snapshot,
|
|
6856
|
+
stage,
|
|
6857
|
+
...httpStatus === void 0 ? {} : { httpStatus }
|
|
6858
|
+
});
|
|
6859
|
+
} catch {}
|
|
6860
|
+
}
|
|
6861
|
+
return {
|
|
6862
|
+
payload: (files) => {
|
|
6863
|
+
snapshot = {
|
|
6864
|
+
fileCount: files.length,
|
|
6865
|
+
files: files.slice(0, 64)
|
|
6866
|
+
};
|
|
6867
|
+
emit("payload");
|
|
6868
|
+
},
|
|
6869
|
+
fetching: () => {
|
|
6870
|
+
emit("fetch");
|
|
6871
|
+
},
|
|
6872
|
+
responded: (status) => {
|
|
6873
|
+
emit("response", status);
|
|
6874
|
+
}
|
|
6875
|
+
};
|
|
6876
|
+
}
|
|
6877
|
+
const mismatch = "the stored attachment does not match its reference";
|
|
6878
|
+
const mapping = "the SDK could not verify the attachment position";
|
|
6879
|
+
const budget = "the request media budget is full; read this attachment separately";
|
|
6880
|
+
const noSelection = "the selected attachment is missing from this request";
|
|
6881
|
+
const clipName = /^clip-([a-f0-9]{12})-(\d+)-(\d+)ms\.mp4$/u;
|
|
6882
|
+
const kindOf$1 = (name) => {
|
|
6883
|
+
if (/\.(?:mp4|m4v|mov|webm|mkv|avi|mpeg|mpg|3gp|flv|wmv)$/iu.test(name)) return "video";
|
|
6884
|
+
if (/\.(?:mp3|wav|m4a|aac|flac|ogg|oga|opus|aiff|aif|amr|wma)$/iu.test(name)) return "audio";
|
|
6885
|
+
};
|
|
6886
|
+
const text$7 = (value) => ({
|
|
6887
|
+
type: "text",
|
|
6888
|
+
text: value
|
|
6889
|
+
});
|
|
6890
|
+
const referenceOnly = (label, why) => `${label} — reference only in this request (${why}).`;
|
|
6891
|
+
function describe(ref, mediaId, occurrence) {
|
|
6892
|
+
const range = occurrence?.rangeLabel && clipName.exec(ref.name);
|
|
6893
|
+
const name = JSON.stringify(ref.name);
|
|
6894
|
+
const label = occurrence?.rangeLabel ?? occurrence?.label ?? `Attachment ${mediaId}`;
|
|
6895
|
+
if (range && !label.includes(ref.name)) return `${label} · source ${range[1]} [${range[2]}, ${range[3]}) ms · ${name}`;
|
|
6896
|
+
return label.includes(ref.name) ? label : `${label} · ${name}`;
|
|
6897
|
+
}
|
|
6898
|
+
function eligibleTarget(slot, options) {
|
|
6899
|
+
const ref = slot.file.attachment;
|
|
6900
|
+
let target;
|
|
6901
|
+
try {
|
|
6902
|
+
target = options.target(ref);
|
|
6903
|
+
} catch {}
|
|
6904
|
+
const kind = kindOf$1(ref.name);
|
|
6905
|
+
if (!target || !Number.isSafeInteger(target.maxBytes) || target.maxBytes < 0 || !kind || options.modalities && !options.modalities.includes(kind)) slot.reason = "the route does not support this attachment";
|
|
6906
|
+
else if (!Number.isSafeInteger(ref.bytes) || ref.bytes < 0) slot.reason = mismatch;
|
|
6907
|
+
else if (ref.bytes > Math.min(target.maxBytes, options.maxBytes)) slot.reason = "the single-file size limit was exceeded";
|
|
6908
|
+
else slot.target = {
|
|
6909
|
+
maxBytes: Math.min(target.maxBytes, options.maxBytes),
|
|
6910
|
+
mediaTypes: target.mediaTypes ?? options.mediaTypes
|
|
6911
|
+
};
|
|
6912
|
+
}
|
|
6913
|
+
/** A projected request can only lose files here. For a direct call, choose the last eligible occurrence per ID. */
|
|
6914
|
+
function select(slots, unique, options) {
|
|
6915
|
+
const last = /* @__PURE__ */ new Map();
|
|
6916
|
+
const conflicts = /* @__PURE__ */ new Set();
|
|
6917
|
+
for (const slot of slots) {
|
|
6918
|
+
if (slot.reason) continue;
|
|
6919
|
+
eligibleTarget(slot, options);
|
|
6920
|
+
if (slot.reason) continue;
|
|
6921
|
+
const ref = slot.file.attachment;
|
|
6922
|
+
const previous = last.get(ref.attachmentId);
|
|
6923
|
+
if (previous && (previous.file.attachment.bytes !== ref.bytes || kindOf$1(previous.file.attachment.name) !== kindOf$1(ref.name))) conflicts.add(ref.attachmentId);
|
|
6924
|
+
last.set(ref.attachmentId, slot);
|
|
6925
|
+
}
|
|
6926
|
+
let total = 0;
|
|
6927
|
+
const candidates = [];
|
|
6928
|
+
for (const slot of slots) {
|
|
6929
|
+
if (slot.reason) continue;
|
|
6930
|
+
const ref = slot.file.attachment;
|
|
6931
|
+
const representative = last.get(ref.attachmentId);
|
|
6932
|
+
if (conflicts.has(ref.attachmentId)) slot.reason = mismatch;
|
|
6933
|
+
else if (unique && slot !== representative) slot.representative = representative;
|
|
6934
|
+
else {
|
|
6935
|
+
candidates.push(slot);
|
|
6936
|
+
total += 4 * Math.ceil(ref.bytes / 3);
|
|
6937
|
+
}
|
|
6938
|
+
}
|
|
6939
|
+
for (const slot of candidates) {
|
|
6940
|
+
if (total <= options.maxEncoded) break;
|
|
6941
|
+
slot.reason = budget;
|
|
6942
|
+
total -= 4 * Math.ceil(slot.file.attachment.bytes / 3);
|
|
6943
|
+
}
|
|
6944
|
+
for (const slot of slots) if (!last.has(slot.file.attachment.attachmentId)) last.set(slot.file.attachment.attachmentId, slot);
|
|
6945
|
+
return last;
|
|
6946
|
+
}
|
|
6947
|
+
async function readSelected(slots, options) {
|
|
6948
|
+
const read = options.attachments?.readFileRequest;
|
|
6949
|
+
const byId = /* @__PURE__ */ new Map();
|
|
6950
|
+
for (const slot of slots) {
|
|
6951
|
+
if (slot.reason || slot.representative) continue;
|
|
6952
|
+
options.signal.throwIfAborted();
|
|
6953
|
+
const ref = slot.file.attachment;
|
|
6954
|
+
let result = byId.get(ref.attachmentId);
|
|
6955
|
+
if (!result) {
|
|
6956
|
+
if (typeof read !== "function") result = "the attachment service cannot read request files";
|
|
6957
|
+
else try {
|
|
6958
|
+
const file = await read.call(options.attachments, ref, slot.target, options.signal);
|
|
6959
|
+
options.signal.throwIfAborted();
|
|
6960
|
+
if (!(file.data instanceof Uint8Array) || file.data.byteLength !== ref.bytes || file.bytes !== ref.bytes || file.attachment?.attachmentId !== ref.attachmentId || file.attachment.bytes !== ref.bytes) result = mismatch;
|
|
6961
|
+
else if (!slot.target.mediaTypes.includes(file.mediaType) || file.mediaType.split("/")[0] !== kindOf$1(ref.name)) result = "the stored media type does not match this file or route";
|
|
6962
|
+
else if (/^sha256:[a-f0-9]{64}$/u.test(ref.attachmentId) && `sha256:${createHash("sha256").update(file.data).digest("hex")}` !== ref.attachmentId) result = mismatch;
|
|
6963
|
+
else result = {
|
|
6964
|
+
type: "file",
|
|
6965
|
+
file: { file_data: `data:${file.mediaType};base64,${Buffer.from(file.data.buffer, file.data.byteOffset, file.data.byteLength).toString("base64")}` }
|
|
6966
|
+
};
|
|
6967
|
+
} catch (error) {
|
|
6968
|
+
options.signal.throwIfAborted();
|
|
6969
|
+
const code = isRecord$1(error) ? error.code : void 0;
|
|
6970
|
+
result = code === "ATTACHMENT_CORRUPT" ? mismatch : code === "ATTACHMENT_PROJECTION_UNSUPPORTED" ? "the stored media type or size is unsupported" : "the stored attachment could not be read";
|
|
6971
|
+
}
|
|
6972
|
+
byId.set(ref.attachmentId, result);
|
|
6973
|
+
}
|
|
6974
|
+
if (typeof result === "string") slot.reason = result;
|
|
6975
|
+
else slot.part = slot.range ? {
|
|
6976
|
+
...result,
|
|
6977
|
+
file: {
|
|
6978
|
+
...result.file,
|
|
6979
|
+
filename: ref.name
|
|
6980
|
+
}
|
|
6981
|
+
} : result;
|
|
6982
|
+
}
|
|
6983
|
+
}
|
|
6984
|
+
/** Replace only this attempt's tokens, wherever the SDK stored a string. Original payload/history stay immutable. */
|
|
6985
|
+
function mapStrings(value, visit) {
|
|
6986
|
+
if (typeof value === "string") return visit(value);
|
|
6987
|
+
if (Array.isArray(value)) return value.map((part) => mapStrings(part, visit));
|
|
6988
|
+
if (!isRecord$1(value)) return value;
|
|
6989
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, mapStrings(item, visit)]));
|
|
6990
|
+
}
|
|
6991
|
+
function receiptFiles(slots, invalid) {
|
|
6992
|
+
return slots.map((slot, index) => {
|
|
6993
|
+
const rep = slot.representative ?? slot;
|
|
6994
|
+
return {
|
|
6995
|
+
position: index + 1,
|
|
6996
|
+
mediaId: /^m[1-9]\d*$/u.test(slot.mediaId) ? slot.mediaId : `m${index + 1}`,
|
|
6997
|
+
bytes: Number.isSafeInteger(slot.file.attachment.bytes) && slot.file.attachment.bytes >= 0 ? slot.file.attachment.bytes : 0,
|
|
6998
|
+
state: rep.part && !invalid.has(rep) ? slot.representative ? "shared" : "included" : "reference-only"
|
|
6999
|
+
};
|
|
7000
|
+
});
|
|
7001
|
+
}
|
|
7002
|
+
/** Files in an actual SDK-supplied content array, not similarly spelled text inside tool arguments. */
|
|
7003
|
+
function payloadFiles(payload) {
|
|
7004
|
+
if (!isRecord$1(payload) || !Array.isArray(payload.messages)) return [];
|
|
7005
|
+
return payload.messages.flatMap((message) => isRecord$1(message) && Array.isArray(message.content) ? message.content.filter((part) => isRecord$1(part) && part.type === "file") : []);
|
|
7006
|
+
}
|
|
7007
|
+
function paired(anchor, file) {
|
|
7008
|
+
if (!file || anchor.role !== file.role || anchor.messageIndex !== file.messageIndex) return false;
|
|
7009
|
+
if (file.role === "user") return anchor.atEnd && anchor.contentIndex >= 0 && file.contentIndex === anchor.contentIndex + 1;
|
|
7010
|
+
return anchor.contentIndex < file.contentIndex || anchor.contentIndex === file.contentIndex && anchor.offset < file.offset;
|
|
7011
|
+
}
|
|
7012
|
+
function reconciler(prefix, markers, captions, slots, onDegrade) {
|
|
7013
|
+
return (payload, assistantAfterToolResult = false, written) => {
|
|
7014
|
+
const owners = /* @__PURE__ */ new Map();
|
|
7015
|
+
const invalid = /* @__PURE__ */ new Set();
|
|
7016
|
+
const ordered = [];
|
|
7017
|
+
if (!isRecord$1(payload) || !Array.isArray(payload.messages)) throw new Error("Unable to verify the Chat Completions message envelope.");
|
|
7018
|
+
if (!markers.size) {
|
|
7019
|
+
const messages = stripVisibleNativeFiles(payload.messages);
|
|
7020
|
+
written?.(receiptFiles(slots, invalid));
|
|
7021
|
+
return messages ? {
|
|
7022
|
+
...payload,
|
|
7023
|
+
messages
|
|
7024
|
+
} : void 0;
|
|
7025
|
+
}
|
|
7026
|
+
placeNativeFiles(payload, (value, role, index) => {
|
|
7027
|
+
const slot = markers.get(value);
|
|
7028
|
+
if (!slot) return void 0;
|
|
7029
|
+
if (slot.role !== role || owners.has(slot)) invalid.add(slot);
|
|
7030
|
+
owners.set(slot, index);
|
|
7031
|
+
ordered.push(slot);
|
|
7032
|
+
return [];
|
|
7033
|
+
});
|
|
7034
|
+
const counts = /* @__PURE__ */ new Map();
|
|
7035
|
+
const locations = /* @__PURE__ */ new Map();
|
|
7036
|
+
const tokens = new RegExp(`${prefix}(?:f|h)\\d+!`, "gu");
|
|
7037
|
+
mapMediaText(payload.messages, (value, role, messageIndex, contentIndex) => {
|
|
7038
|
+
if (value.includes(prefix)) for (const match of value.matchAll(tokens)) {
|
|
7039
|
+
const token = match[0];
|
|
7040
|
+
counts.set(token, (counts.get(token) ?? 0) + 1);
|
|
7041
|
+
locations.set(token, {
|
|
7042
|
+
role,
|
|
7043
|
+
messageIndex,
|
|
7044
|
+
contentIndex,
|
|
7045
|
+
offset: match.index,
|
|
7046
|
+
atEnd: match.index + token.length === value.length
|
|
7047
|
+
});
|
|
7048
|
+
}
|
|
7049
|
+
return value;
|
|
7050
|
+
});
|
|
7051
|
+
for (const [marker, slot] of markers) if (counts.get(marker) !== 1 || !owners.has(slot)) invalid.add(slot);
|
|
7052
|
+
const absent = [];
|
|
7053
|
+
const fileLocation = new Map([...markers].map(([marker, slot]) => [slot, locations.get(marker)]));
|
|
7054
|
+
for (const caption of captions) {
|
|
7055
|
+
const anchor = locations.get(caption.marker);
|
|
7056
|
+
if (!anchor || anchor.role !== caption.role) {
|
|
7057
|
+
invalid.add(caption.slot);
|
|
7058
|
+
absent.push(caption);
|
|
7059
|
+
} else if (counts.get(caption.marker) !== 1 || caption.anchor && !paired(anchor, fileLocation.get(caption.slot))) invalid.add(caption.slot);
|
|
7060
|
+
}
|
|
7061
|
+
const actual = ordered.filter((slot) => !invalid.has(slot));
|
|
7062
|
+
if ([...markers.values()].filter((slot) => !invalid.has(slot)).some((slot, i) => slot !== actual[i])) for (const slot of markers.values()) invalid.add(slot);
|
|
7063
|
+
const placement = placeNativeFiles(payload, (value, role) => {
|
|
7064
|
+
const slot = markers.get(value);
|
|
7065
|
+
if (!slot) return void 0;
|
|
7066
|
+
if (invalid.has(slot)) return [];
|
|
7067
|
+
return role === "tool" || slot.range ? [text$7(slot.label), slot.part] : [slot.part];
|
|
7068
|
+
}, assistantAfterToolResult);
|
|
7069
|
+
let messages = isRecord$1(placement) && Array.isArray(placement.messages) ? placement.messages : payload.messages;
|
|
7070
|
+
const expected = [...markers.values()].filter((slot) => !invalid.has(slot));
|
|
7071
|
+
const materialized = payloadFiles({ messages });
|
|
7072
|
+
if (materialized.length !== expected.length || materialized.some((part, index) => part !== expected[index]?.part)) {
|
|
7073
|
+
for (const slot of markers.values()) invalid.add(slot);
|
|
7074
|
+
messages = stripVisibleNativeFiles(payload.messages) ?? payload.messages;
|
|
7075
|
+
}
|
|
7076
|
+
const status = /* @__PURE__ */ new Map();
|
|
7077
|
+
for (const caption of captions) {
|
|
7078
|
+
const delivery = caption.duplicate ? `same content as ${caption.slot.mediaId}, included once` : "included";
|
|
7079
|
+
status.set(caption.marker, invalid.has(caption.slot) ? referenceOnly(caption.label, mapping) : `${caption.label} — ${delivery} in this request.`);
|
|
7080
|
+
}
|
|
7081
|
+
for (const caption of absent) status.delete(caption.marker);
|
|
7082
|
+
for (const slot of invalid) onDegrade?.(slot.mediaId, mapping);
|
|
7083
|
+
const residue = new RegExp(`${prefix.slice(1)}(?:[fh]\\d*!?)?`, "gu");
|
|
7084
|
+
messages = mapMediaText(messages, (value) => value.includes(prefix) ? value.replace(tokens, (token) => status.get(token) ?? "") : value);
|
|
7085
|
+
const cleaned = mapStrings({
|
|
7086
|
+
...payload,
|
|
7087
|
+
messages
|
|
7088
|
+
}, (value) => value.includes(prefix.slice(1)) ? value.replace(tokens, "").replace(residue, "") : value);
|
|
7089
|
+
if (absent.length) {
|
|
7090
|
+
const output = cleaned.messages;
|
|
7091
|
+
if (assistantAfterToolResult && isRecord$1(output.at(-1)) && output.at(-1).role === "tool") output.push({
|
|
7092
|
+
role: "assistant",
|
|
7093
|
+
content: "I have processed the tool results."
|
|
7094
|
+
});
|
|
7095
|
+
output.push({
|
|
7096
|
+
role: "user",
|
|
7097
|
+
content: [...new Set(absent.map((item) => referenceOnly(item.label, mapping)))].join("\n")
|
|
7098
|
+
});
|
|
7099
|
+
}
|
|
7100
|
+
written?.(receiptFiles(slots, invalid));
|
|
7101
|
+
return cleaned;
|
|
7102
|
+
};
|
|
7103
|
+
}
|
|
7104
|
+
/** Prepare only the blocks already handed to this adapter. An old host's absent policy keeps its legacy path. */
|
|
7105
|
+
async function prepareVerifiedFiles(request, options) {
|
|
7106
|
+
if (request.nativeFilePolicy !== "unique-v1" && (request.nativeFilePolicy !== "legacy" || !request.nativeFileOccurrences)) return void 0;
|
|
7107
|
+
const occurrences = request.nativeFileOccurrences;
|
|
7108
|
+
const fileEntries = new Map(occurrences?.filter((item) => item.file && item.status === "selected").map((item) => [item.file, item]));
|
|
7109
|
+
const handles = new Map(occurrences?.filter((item) => item.status === "selected" || item.status === "duplicate").map((item) => [item.handle, item]));
|
|
7110
|
+
const missing = new Set(handles.keys());
|
|
7111
|
+
const slots = [];
|
|
7112
|
+
const at = /* @__PURE__ */ new Map();
|
|
7113
|
+
const ids = /* @__PURE__ */ new Map();
|
|
7114
|
+
const messages = request.messages.map((message) => {
|
|
7115
|
+
if (message.role !== "user" && message.role !== "tool") return message;
|
|
7116
|
+
const role = message.role;
|
|
7117
|
+
return {
|
|
7118
|
+
...message,
|
|
7119
|
+
content: message.content.map((block, position) => {
|
|
7120
|
+
if (block.type === "text") missing.delete(block);
|
|
7121
|
+
if (block.type !== "file") return block;
|
|
7122
|
+
const ref = block.attachment;
|
|
7123
|
+
const entry = fileEntries.get(block);
|
|
7124
|
+
const mediaId = entry?.mediaId ?? ids.get(ref.attachmentId) ?? `m${ids.size + 1}`;
|
|
7125
|
+
ids.set(ref.attachmentId, mediaId);
|
|
7126
|
+
const file = { ...block };
|
|
7127
|
+
const slot = {
|
|
7128
|
+
file,
|
|
7129
|
+
role,
|
|
7130
|
+
mediaId,
|
|
7131
|
+
label: describe(ref, mediaId, entry),
|
|
7132
|
+
range: !!entry?.rangeLabel
|
|
7133
|
+
};
|
|
7134
|
+
if (request.purpose !== void 0) slot.reason = "auxiliary requests use file references";
|
|
7135
|
+
else if (occurrences && (!entry || entry.attachmentId !== ref.attachmentId || message.content[position - 1] !== entry.handle)) slot.reason = noSelection;
|
|
7136
|
+
slots.push(slot);
|
|
7137
|
+
at.set(file, slot);
|
|
7138
|
+
return file;
|
|
7139
|
+
})
|
|
7140
|
+
};
|
|
7141
|
+
});
|
|
7142
|
+
if (!slots.length && !occurrences?.length) return void 0;
|
|
7143
|
+
const detached = [...missing].map((handle) => handles.get(handle));
|
|
7144
|
+
if (detached.length) {
|
|
7145
|
+
const affected = new Set(detached.map((item) => item.attachmentId));
|
|
7146
|
+
for (const slot of slots) if (affected.has(slot.file.attachment.attachmentId)) slot.reason = mapping;
|
|
7147
|
+
}
|
|
7148
|
+
const last = select(slots, request.nativeFilePolicy === "unique-v1", options);
|
|
7149
|
+
await readSelected(slots, options);
|
|
7150
|
+
const originalToSlot = /* @__PURE__ */ new Map();
|
|
7151
|
+
let index = 0;
|
|
7152
|
+
for (const message of request.messages) if (message.role === "user" || message.role === "tool") {
|
|
7153
|
+
for (const block of message.content) if (block.type === "file") originalToSlot.set(block, slots[index++]);
|
|
7154
|
+
}
|
|
7155
|
+
const prefix = `!dsh-native-file-${randomUUID()}-`;
|
|
7156
|
+
const markers = /* @__PURE__ */ new Map();
|
|
7157
|
+
const captions = [];
|
|
7158
|
+
const feedback = (slot, role, label, duplicate, anchor) => {
|
|
7159
|
+
const rep = slot?.representative ?? slot;
|
|
7160
|
+
if (!rep?.part) return referenceOnly(label, rep?.reason ?? noSelection);
|
|
7161
|
+
const marker = `${prefix}h${captions.length}!`;
|
|
7162
|
+
captions.push({
|
|
7163
|
+
marker,
|
|
7164
|
+
slot: rep,
|
|
7165
|
+
role,
|
|
7166
|
+
label,
|
|
7167
|
+
duplicate,
|
|
7168
|
+
anchor
|
|
7169
|
+
});
|
|
7170
|
+
return marker;
|
|
7171
|
+
};
|
|
7172
|
+
for (const slot of slots) if (slot.reason) options.onDegrade?.(slot.mediaId, slot.reason);
|
|
7173
|
+
const projected = messages.map((message) => {
|
|
7174
|
+
if (message.role !== "tool" && message.role !== "user") return message;
|
|
7175
|
+
return {
|
|
7176
|
+
...message,
|
|
7177
|
+
content: message.content.flatMap((block) => {
|
|
7178
|
+
const entry = block.type === "text" && handles.get(block);
|
|
7179
|
+
if (entry) {
|
|
7180
|
+
const slot = entry.file ? originalToSlot.get(entry.file) : last.get(entry.attachmentId);
|
|
7181
|
+
return [text$7(`${entry.referenceText}\n${feedback(slot, message.role, entry.label, entry.status === "duplicate", entry.status === "selected")}`)];
|
|
7182
|
+
}
|
|
7183
|
+
if (block.type !== "file") return [block];
|
|
7184
|
+
const slot = at.get(block);
|
|
7185
|
+
const parts = [];
|
|
7186
|
+
if (!occurrences || !slot.part && slot.reason === noSelection) parts.push(text$7(feedback(slot, message.role, slot.label, !!slot.representative, !slot.representative)));
|
|
7187
|
+
if (slot.part) {
|
|
7188
|
+
const marker = `${prefix}f${markers.size}!`;
|
|
7189
|
+
markers.set(marker, slot);
|
|
7190
|
+
parts.push(text$7(marker));
|
|
7191
|
+
}
|
|
7192
|
+
return parts;
|
|
7193
|
+
})
|
|
7194
|
+
};
|
|
7195
|
+
});
|
|
7196
|
+
if (detached.length) projected.push({
|
|
7197
|
+
role: "user",
|
|
7198
|
+
content: [text$7(`Media status for this request:\n${detached.map((item) => referenceOnly(item.label, mapping)).join("\n")}`)]
|
|
7199
|
+
});
|
|
7200
|
+
return {
|
|
7201
|
+
messages: projected,
|
|
7202
|
+
isMarker: (value) => markers.has(value),
|
|
7203
|
+
inject: reconciler(prefix, markers, captions, slots, options.onDegrade)
|
|
7204
|
+
};
|
|
7205
|
+
}
|
|
7206
|
+
//#endregion
|
|
6845
7207
|
//#region node_modules/@earendil-works/pi-ai/dist/utils/overflow.js
|
|
6846
7208
|
/**
|
|
6847
7209
|
* Regex patterns to detect context overflow errors from different providers.
|
|
@@ -7972,7 +8334,8 @@ var GatewayAdapter = class extends LlmAdapter {
|
|
|
7972
8334
|
if (entry === void 0 || entry.api !== "openai-completions" || (entry.nativeMedia?.length ?? 0) === 0) return void 0;
|
|
7973
8335
|
return snapshot.models.getModel(provider, model) === void 0 ? void 0 : {
|
|
7974
8336
|
maxBytes: NATIVE_FILE_MAX_BYTES,
|
|
7975
|
-
mediaTypes: GEMINI_INLINE_MEDIA_TYPES
|
|
8337
|
+
mediaTypes: GEMINI_INLINE_MEDIA_TYPES,
|
|
8338
|
+
supportsRangeLabels: true
|
|
7976
8339
|
};
|
|
7977
8340
|
}
|
|
7978
8341
|
providerInfo(provider) {
|
|
@@ -8097,13 +8460,27 @@ var GatewayAdapter = class extends LlmAdapter {
|
|
|
8097
8460
|
});
|
|
8098
8461
|
} catch {}
|
|
8099
8462
|
};
|
|
8100
|
-
|
|
8463
|
+
const verified = model.api === "openai-completions" ? await prepareVerifiedFiles(options, {
|
|
8464
|
+
attachments,
|
|
8465
|
+
target: () => this.fileTargetIn(snapshot, options.provider, options.model),
|
|
8466
|
+
mediaTypes: GEMINI_INLINE_MEDIA_TYPES,
|
|
8467
|
+
modalities: catalog.nativeMedia,
|
|
8468
|
+
maxBytes: NATIVE_FILE_MAX_BYTES,
|
|
8469
|
+
maxEncoded: NATIVE_FILE_MAX_REQUEST_BASE64_BYTES,
|
|
8470
|
+
onDegrade: onNativeFileDegrade,
|
|
8471
|
+
signal: watchdog.signal
|
|
8472
|
+
}) : void 0;
|
|
8473
|
+
if (!verified && containsNativeFile && attachments === void 0) for (const message of options.messages) {
|
|
8101
8474
|
if (!carriesFiles(message)) continue;
|
|
8102
8475
|
for (const block of message.content) if (block.type === "file") onNativeFileDegrade(block.attachment.name, "no durable attachment service to read it from");
|
|
8103
8476
|
}
|
|
8104
8477
|
const nativeFiles = [];
|
|
8105
|
-
const
|
|
8478
|
+
const request = verified ? {
|
|
8106
8479
|
...options,
|
|
8480
|
+
messages: verified.messages
|
|
8481
|
+
} : options;
|
|
8482
|
+
const context = attachments === void 0 ? toPiContext(request, void 0, onReplayDegrade) : await toPiContext({
|
|
8483
|
+
...request,
|
|
8107
8484
|
signal: watchdog.signal
|
|
8108
8485
|
}, {
|
|
8109
8486
|
attachments,
|
|
@@ -8113,7 +8490,8 @@ var GatewayAdapter = class extends LlmAdapter {
|
|
|
8113
8490
|
maxPixels: DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET,
|
|
8114
8491
|
maxBytes: DEFAULT_REQUEST_IMAGE_MAX_BYTES
|
|
8115
8492
|
},
|
|
8116
|
-
...
|
|
8493
|
+
...verified ? { isWireMarker: verified.isMarker } : {},
|
|
8494
|
+
...containsNativeFile && !verified ? { files: {
|
|
8117
8495
|
target: () => this.fileTargetIn(snapshot, options.provider, options.model),
|
|
8118
8496
|
onDegrade: (ref, reason) => {
|
|
8119
8497
|
onNativeFileDegrade(ref.name, reason);
|
|
@@ -8125,14 +8503,17 @@ var GatewayAdapter = class extends LlmAdapter {
|
|
|
8125
8503
|
const offersNone = catalog.reasoningLevels?.includes("none") === true;
|
|
8126
8504
|
for (let attempt = 0;; attempt++) {
|
|
8127
8505
|
const token = credential.token;
|
|
8506
|
+
const receipt = verified && fileReceiptAttempt(this.config.onNativeFileReceipt);
|
|
8128
8507
|
let response;
|
|
8129
8508
|
const observingFetch = async (input, init) => {
|
|
8130
8509
|
const url = input instanceof Request ? input.url : String(input);
|
|
8131
8510
|
if (new URL(url).origin !== snapshot.origin) throw new Error("Refusing a model request to another gateway origin.");
|
|
8511
|
+
receipt?.fetching();
|
|
8132
8512
|
const received = await fetch(input, {
|
|
8133
8513
|
...init,
|
|
8134
8514
|
redirect: "error"
|
|
8135
8515
|
});
|
|
8516
|
+
receipt?.responded(received.status);
|
|
8136
8517
|
answered = true;
|
|
8137
8518
|
response = {
|
|
8138
8519
|
status: received.status,
|
|
@@ -8166,7 +8547,11 @@ var GatewayAdapter = class extends LlmAdapter {
|
|
|
8166
8547
|
off: reasoning === "off" && offersNone,
|
|
8167
8548
|
reasoning: enabledReasoning !== void 0,
|
|
8168
8549
|
claudeCacheTtl,
|
|
8169
|
-
nativeFiles
|
|
8550
|
+
nativeFiles,
|
|
8551
|
+
...verified ? {
|
|
8552
|
+
verified,
|
|
8553
|
+
receipt
|
|
8554
|
+
} : {}
|
|
8170
8555
|
}),
|
|
8171
8556
|
fetch: observingFetch,
|
|
8172
8557
|
onResponse: (received) => {
|
|
@@ -8250,6 +8635,10 @@ var GatewayAdapter = class extends LlmAdapter {
|
|
|
8250
8635
|
shaped.thinking = { type: "disabled" };
|
|
8251
8636
|
delete shaped.reasoning_effort;
|
|
8252
8637
|
} else if (request.off) shaped.reasoning_effort = "none";
|
|
8638
|
+
if (request.verified) {
|
|
8639
|
+
const bridge = model.compat?.requiresAssistantAfterToolResult === true;
|
|
8640
|
+
return request.verified.inject(shaped, bridge, request.receipt?.payload) ?? shaped;
|
|
8641
|
+
}
|
|
8253
8642
|
if (request.nativeFiles !== void 0 && request.nativeFiles.length > 0) {
|
|
8254
8643
|
const assistantAfterToolResult = model.compat?.requiresAssistantAfterToolResult === true;
|
|
8255
8644
|
return injectNativeFiles(shaped, request.nativeFiles, { assistantAfterToolResult }) ?? shaped;
|
|
@@ -8409,6 +8798,9 @@ function installGatewayModels(ctx, options) {
|
|
|
8409
8798
|
onNativeFileDegrade: ({ provider, model, file, reason }) => {
|
|
8410
8799
|
ctx.logger.warn(`dsh-vibedev: sending "${file}" to ${provider}/${model} as its file handle text only: ${reason}`);
|
|
8411
8800
|
},
|
|
8801
|
+
onNativeFileReceipt: (receipt) => {
|
|
8802
|
+
ctx.logger.debug(`dsh-vibedev native media: ${JSON.stringify(receipt)}`);
|
|
8803
|
+
},
|
|
8412
8804
|
...options.onRequestEnded === void 0 ? {} : { onRequestEnded: options.onRequestEnded },
|
|
8413
8805
|
...options.promotions === void 0 ? {} : { promotions: options.promotions }
|
|
8414
8806
|
});
|
package/lib/llm/adapter.d.ts
CHANGED
|
@@ -29,6 +29,7 @@ import type { GenerateOptions, ImageAttachmentAccess, LlmModelInfo, LlmProviderI
|
|
|
29
29
|
import type { AttachmentStore, FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment';
|
|
30
30
|
import type { GatewayModel } from './catalog.js';
|
|
31
31
|
import type { FileRequestTarget } from './native-files.js';
|
|
32
|
+
import { type NativeFileReceipt } from './verified-files.js';
|
|
32
33
|
import { type ActivePromotion } from './promotions.js';
|
|
33
34
|
import { type ClaudeCacheTtl } from './cache-ttl.js';
|
|
34
35
|
/** The credential for one request. */
|
|
@@ -109,6 +110,8 @@ export interface GatewayAdapterOptions {
|
|
|
109
110
|
file: string;
|
|
110
111
|
reason: string;
|
|
111
112
|
}) => void;
|
|
113
|
+
/** Optional, bounded diagnostics for a single request attempt. No filenames, paths or content. */
|
|
114
|
+
readonly onNativeFileReceipt?: (receipt: NativeFileReceipt) => void;
|
|
112
115
|
/** A request reached the gateway and ended, however it ended: it may have been charged. */
|
|
113
116
|
readonly onRequestEnded?: () => void;
|
|
114
117
|
/**
|
package/lib/llm/context.d.ts
CHANGED
|
@@ -31,6 +31,8 @@ export interface PiImageRequestContext {
|
|
|
31
31
|
* Only Chat Completions models supply it.
|
|
32
32
|
*/
|
|
33
33
|
files?: PiFileRequestContext;
|
|
34
|
+
/** Keeps the current request's verified media placeholders in independent pi text parts. */
|
|
35
|
+
isWireMarker?: (text: string) => boolean;
|
|
34
36
|
}
|
|
35
37
|
/** Per-route budgets from which each request image's target is derived. */
|
|
36
38
|
export interface PiImageRequestBudget {
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** Chat Completions places tool-result media in the SDK's adjacent user message. */
|
|
2
|
+
export declare const TOOL_RESULT_MEDIA_TEXT = "Attached media from tool result:";
|
|
3
|
+
export declare function isRecord(value: unknown): value is Record<string, unknown>;
|
|
4
|
+
export interface NativeFilePart {
|
|
5
|
+
type: 'file';
|
|
6
|
+
file: {
|
|
7
|
+
file_data: string;
|
|
8
|
+
filename?: string;
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Visit the user and tool text fields in which a generated attachment caption may appear.
|
|
13
|
+
* @param messages - SDK Chat Completions messages.
|
|
14
|
+
* @param visit - replace the visible text; content index -1 identifies a scalar string.
|
|
15
|
+
* @returns messages with only the visited text fields replaced.
|
|
16
|
+
*/
|
|
17
|
+
export declare function mapMediaText(messages: readonly unknown[], visit: (value: string, role: 'user' | 'tool', messageIndex: number, contentIndex: number) => string): unknown[];
|
|
18
|
+
/**
|
|
19
|
+
* Strip every native file from message content, including in an unsupported role.
|
|
20
|
+
* @param messages - SDK messages before placement of verified files.
|
|
21
|
+
* @returns the filtered messages, or undefined if the body already has no files.
|
|
22
|
+
*/
|
|
23
|
+
export declare function stripVisibleNativeFiles(messages: readonly unknown[]): unknown[] | undefined;
|
|
24
|
+
type Part = NativeFilePart | {
|
|
25
|
+
type: 'text';
|
|
26
|
+
text: string;
|
|
27
|
+
};
|
|
28
|
+
type Resolve = (text: string, role: 'user' | 'tool', messageIndex: number) => readonly Part[] | undefined;
|
|
29
|
+
/** Resolve exact user parts or tool-result lines. All other messages, calls and image parts keep their order. */
|
|
30
|
+
export declare function placeNativeFiles(payload: unknown, resolve: Resolve, assistantAfterToolResult?: boolean): unknown;
|
|
31
|
+
export {};
|
|
@@ -40,8 +40,7 @@ export declare const NATIVE_FILE_MAX_REQUEST_BASE64_BYTES: number;
|
|
|
40
40
|
* WMA, …) keeps its handle text only: one type the provider refuses would fail the whole request.
|
|
41
41
|
*/
|
|
42
42
|
export declare const GEMINI_INLINE_MEDIA_TYPES: readonly string[];
|
|
43
|
-
|
|
44
|
-
export declare const TOOL_RESULT_MEDIA_TEXT = "Attached media from tool result:";
|
|
43
|
+
export { TOOL_RESULT_MEDIA_TEXT } from './file-placement.js';
|
|
45
44
|
/** `FileRequestTarget` of `@deepseek-ai/dsh-attachment` (VibeDev fork): the route's limits for one file. */
|
|
46
45
|
export interface FileRequestTarget {
|
|
47
46
|
/** Hard raw-byte limit before base64 expansion; a larger file is refused before any byte is read. */
|
|
@@ -52,6 +51,8 @@ export interface FileRequestTarget {
|
|
|
52
51
|
* Absent means {@link GEMINI_INLINE_MEDIA_TYPES}.
|
|
53
52
|
*/
|
|
54
53
|
mediaTypes?: readonly string[];
|
|
54
|
+
/** The adapter can keep a source-range caption next to each delivered clip. */
|
|
55
|
+
supportsRangeLabels?: boolean;
|
|
55
56
|
}
|
|
56
57
|
/** `RequestFileAttachment` of `@deepseek-ai/dsh-attachment` (VibeDev fork): one file read whole for one request. */
|
|
57
58
|
export interface RequestFileAttachment {
|
|
@@ -117,16 +118,5 @@ export interface NativeFileInjectionOptions {
|
|
|
117
118
|
*/
|
|
118
119
|
readonly assistantAfterToolResult?: boolean;
|
|
119
120
|
}
|
|
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
|
-
*/
|
|
121
|
+
/** Place each marker from a request projected by a legacy host. */
|
|
132
122
|
export declare function injectNativeFiles(payload: unknown, delivered: readonly NativeFilePart[], options?: NativeFileInjectionOptions): unknown;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { ContentBlock, GenerateOptions, RequestMessage } from '@deepseek-ai/dsh-llm';
|
|
2
|
+
import type { AttachmentStore, FileAttachmentRef } from '@deepseek-ai/dsh-attachment';
|
|
3
|
+
type FileBlock = Extract<ContentBlock, {
|
|
4
|
+
type: 'file';
|
|
5
|
+
}>;
|
|
6
|
+
type TextBlock = Extract<ContentBlock, {
|
|
7
|
+
type: 'text';
|
|
8
|
+
}>;
|
|
9
|
+
interface Occurrence {
|
|
10
|
+
readonly attachmentId: string;
|
|
11
|
+
readonly mediaId: string;
|
|
12
|
+
readonly status: string;
|
|
13
|
+
readonly handle: TextBlock;
|
|
14
|
+
readonly file?: FileBlock;
|
|
15
|
+
readonly label: string;
|
|
16
|
+
readonly rangeLabel?: string;
|
|
17
|
+
readonly referenceText: string;
|
|
18
|
+
}
|
|
19
|
+
type ProjectedRequest = GenerateOptions & {
|
|
20
|
+
readonly nativeFilePolicy?: 'legacy' | 'unique-v1';
|
|
21
|
+
readonly nativeFileOccurrences?: readonly Occurrence[];
|
|
22
|
+
};
|
|
23
|
+
interface Target {
|
|
24
|
+
maxBytes: number;
|
|
25
|
+
mediaTypes?: readonly string[];
|
|
26
|
+
}
|
|
27
|
+
/** Only request-local ordinal, anonymous media ID and byte count enter debug diagnostics. */
|
|
28
|
+
interface ReceiptFile {
|
|
29
|
+
position: number;
|
|
30
|
+
mediaId: string;
|
|
31
|
+
bytes: number;
|
|
32
|
+
state: 'included' | 'reference-only' | 'shared';
|
|
33
|
+
}
|
|
34
|
+
export interface NativeFileReceipt {
|
|
35
|
+
attemptId: string;
|
|
36
|
+
stage: 'payload' | 'fetch' | 'response';
|
|
37
|
+
fileCount: number;
|
|
38
|
+
files: readonly ReceiptFile[];
|
|
39
|
+
httpStatus?: number;
|
|
40
|
+
}
|
|
41
|
+
export declare function fileReceiptAttempt(observe?: (receipt: NativeFileReceipt) => void): {
|
|
42
|
+
payload: (files: ReceiptFile[]) => void;
|
|
43
|
+
fetching: () => void;
|
|
44
|
+
responded: (status: number) => void;
|
|
45
|
+
} | undefined;
|
|
46
|
+
interface ReadOptions {
|
|
47
|
+
attachments?: AttachmentStore | undefined;
|
|
48
|
+
target: (ref: FileAttachmentRef) => Target | undefined;
|
|
49
|
+
mediaTypes: readonly string[];
|
|
50
|
+
modalities?: readonly string[] | undefined;
|
|
51
|
+
maxBytes: number;
|
|
52
|
+
maxEncoded: number;
|
|
53
|
+
onDegrade?: (mediaId: string, reason: string) => void;
|
|
54
|
+
signal: AbortSignal;
|
|
55
|
+
}
|
|
56
|
+
export interface VerifiedFiles {
|
|
57
|
+
messages: RequestMessage[];
|
|
58
|
+
isMarker: (value: string) => boolean;
|
|
59
|
+
inject: (payload: unknown, assistantAfterToolResult?: boolean, written?: (files: ReceiptFile[]) => void) => unknown;
|
|
60
|
+
}
|
|
61
|
+
/** Prepare only the blocks already handed to this adapter. An old host's absent policy keeps its legacy path. */
|
|
62
|
+
export declare function prepareVerifiedFiles(request: ProjectedRequest, options: ReadOptions): Promise<VerifiedFiles | undefined>;
|
|
63
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vibedev-si/dsh-vibedev",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.13.0",
|
|
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",
|