dsh-volcengine-provider 0.2.15 → 0.2.17

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.
@@ -0,0 +1,212 @@
1
+ // volc_imagine:方舟 Seedream 文生图 / 图像编辑(单个工具,image/images 可选)。
2
+ // 原图经通用文件附件逐字节保存;会话视觉输入继续使用宿主规范化图片附件。
3
+ import { defineTool } from '@deepseek-ai/dsh-tools';
4
+ import {
5
+ ARK_MEDIA_BASE_URL, arkFetchJson, downloadMediaBytes, mediaExtensionFor,
6
+ assertMediaEnabled, resolveImageSources, sniffMediaType,
7
+ MAX_IMAGE_RESULT_BYTES, MAX_PROMPT_CHARS, MAX_SOURCE_IMAGES, BILLING_NOTE
8
+ } from './media.mjs';
9
+ import { SUPPORTED_IMAGE_MODELS, DEFAULT_IMAGE_MODEL } from './media-config.mjs';
10
+
11
+ export { SUPPORTED_IMAGE_MODELS } from './media-config.mjs';
12
+ export const IMAGE_TOOL = 'volc_imagine';
13
+ export const SUPPORTED_IMAGE_SIZES = ['1K', '1.5K', '2K'];
14
+ export const SUPPORTED_IMAGE_FORMATS = ['png', 'jpeg'];
15
+ const SIZE_PATTERN = /^\d{3,5}x\d{3,5}$/u;
16
+
17
+ const IMAGE_ATTACHMENT_SCHEMA = {
18
+ type: 'object', additionalProperties: false,
19
+ properties: {
20
+ attachmentId: { type: 'string' }, mediaType: { type: 'string' }, bytes: { type: 'number' },
21
+ width: { type: 'number' }, height: { type: 'number' }, name: { type: 'string' }
22
+ }
23
+ };
24
+ const FILE_ATTACHMENT_SCHEMA = {
25
+ type: 'object', additionalProperties: false,
26
+ properties: { attachmentId: { type: 'string' }, name: { type: 'string' }, bytes: { type: 'number' } }
27
+ };
28
+ const ORIGINAL_SCHEMA = {
29
+ type: 'object', additionalProperties: false,
30
+ properties: {
31
+ attachment: FILE_ATTACHMENT_SCHEMA, mediaType: { type: 'string' },
32
+ width: { type: 'number' }, height: { type: 'number' }
33
+ }
34
+ };
35
+ const OUTPUT_SCHEMA = {
36
+ type: 'object', additionalProperties: false,
37
+ properties: {
38
+ text: { type: 'string' }, model: { type: 'string' }, created: { type: 'number' },
39
+ images: { type: 'array', items: IMAGE_ATTACHMENT_SCHEMA },
40
+ originals: { type: 'array', items: ORIGINAL_SCHEMA }
41
+ }
42
+ };
43
+
44
+ function describeArgs(args) {
45
+ const prompt = typeof args?.prompt === 'string' ? args.prompt : '';
46
+ const hasRefs = Boolean(args?.image) || (Array.isArray(args?.images) && args.images.length > 0);
47
+ return `${hasRefs ? '改图' : '文生图'}:${prompt.length > 60 ? `${prompt.slice(0, 60)}…` : prompt}`;
48
+ }
49
+
50
+ function attachmentsFrom(value) {
51
+ const list = Array.isArray(value?.images) ? value.images : [];
52
+ return list.map(image => image?.attachmentId ? {
53
+ attachmentId: image.attachmentId, mediaType: image.mediaType ?? 'image/png',
54
+ bytes: image.bytes ?? 0, width: image.width ?? 0, height: image.height ?? 0,
55
+ ...(image.name ? { name: image.name } : {})
56
+ } : undefined).filter(Boolean);
57
+ }
58
+
59
+ function originalAttachmentsFrom(value) {
60
+ const list = Array.isArray(value?.originals) ? value.originals : [];
61
+ return list.map(item => item?.attachment?.attachmentId ? item.attachment : undefined).filter(Boolean);
62
+ }
63
+
64
+ function presentationContent(value) {
65
+ return [
66
+ ...attachmentsFrom(value).map(attachment => ({ type: 'image', attachment })),
67
+ ...originalAttachmentsFrom(value).map(attachment => ({ type: 'file', attachment }))
68
+ ];
69
+ }
70
+
71
+ function expectedMediaType(outputFormat) {
72
+ return outputFormat === 'png' ? 'image/png' : 'image/jpeg';
73
+ }
74
+
75
+ async function saveResultEntry(attachments, bytes, mediaType, name) {
76
+ const preview = await attachments.saveImage({ data: bytes, mediaType, name });
77
+ const original = await attachments.saveFile({ data: bytes, name });
78
+ const originalRef = original?.attachment ?? original;
79
+ return {
80
+ preview: {
81
+ attachmentId: preview.attachmentId, mediaType: preview.mediaType,
82
+ bytes: preview.bytes, width: preview.width, height: preview.height,
83
+ ...(preview.name ? { name: preview.name } : {})
84
+ },
85
+ original: {
86
+ attachment: {
87
+ attachmentId: String(originalRef.attachmentId),
88
+ name: String(originalRef.name ?? name),
89
+ bytes: Number(originalRef.bytes ?? bytes.byteLength)
90
+ },
91
+ mediaType, width: preview.width, height: preview.height
92
+ }
93
+ };
94
+ }
95
+
96
+ function resolveReadFile(exec) {
97
+ const cwd = exec.agent?.session?.header?.cwd;
98
+ return async path => {
99
+ const fs = exec.agent?.ctx?.fs;
100
+ if (!fs) {
101
+ const { readFile } = await import('node:fs/promises');
102
+ const { isAbsolute, resolve } = await import('node:path');
103
+ const target = isAbsolute(path) ? path : resolve(cwd ?? process.cwd(), path);
104
+ return readFile(target);
105
+ }
106
+ const target = await fs.resolve(path, { cwd, signal: exec.signal });
107
+ return fs.readBytes(target, exec.signal, 30 * 1024 * 1024);
108
+ };
109
+ }
110
+
111
+ export function registerVolcImagineTool(ctx, options) {
112
+ return ctx.tools.register(defineTool({
113
+ name: IMAGE_TOOL,
114
+ description: [
115
+ '用火山方舟 Seedream(Agent Plan)生成或编辑图片。',
116
+ '仅传 prompt 即文生图;传 image/images(会话附件 sha256 引用、本地路径、data URI 或 https URL)即按参考图编辑/多图融合。',
117
+ `模型:${SUPPORTED_IMAGE_MODELS.join('、')}。${BILLING_NOTE}`,
118
+ '原始 PNG/JPEG 以文件附件逐字节返回,另附宿主规范化图片供会话视觉输入;远程下载地址不会暴露。'
119
+ ].join(' '),
120
+ parameters: {
121
+ prompt: { type: 'string', required: true, description: `图片提示词(≤${MAX_PROMPT_CHARS} 字符)` },
122
+ model: { type: 'string', enum: SUPPORTED_IMAGE_MODELS, description: '生成模型;省略时使用设置页选择的默认模型' },
123
+ image: { type: 'string', description: '单张参考图:会话附件引用 / 本地路径 / data URI / https URL' },
124
+ images: { type: 'array', items: { type: 'string' }, description: `多张参考图(与 image 合并,合计 ≤${MAX_SOURCE_IMAGES} 张)` },
125
+ size: { type: 'string', description: '输出尺寸:1K / 1.5K / 2K,或 WpxH 像素(如 1920x1920);默认 2K' },
126
+ output_format: { type: 'string', enum: SUPPORTED_IMAGE_FORMATS, description: '原始文件格式,默认 png' },
127
+ watermark: { type: 'boolean', description: '是否添加水印,默认 true' }
128
+ },
129
+ output: {
130
+ schema: OUTPUT_SCHEMA,
131
+ render(_args, value) {
132
+ return [{ type: 'text', text: String(value?.text ?? '') }, ...presentationContent(value)];
133
+ },
134
+ presentationMeta: (_args, value) => value
135
+ },
136
+ timeoutMs: 300000,
137
+ isConcurrencySafe: () => true,
138
+ presentCall(args) {
139
+ return { card: 'generic', title: `${IMAGE_TOOL} ${describeArgs(args)}`, kind: 'other' };
140
+ },
141
+ presentResult(args, result) {
142
+ return {
143
+ card: 'generic', title: `${IMAGE_TOOL} ${describeArgs(args)}`,
144
+ content: presentationContent(result?.meta)
145
+ };
146
+ },
147
+ async execute(args, exec) {
148
+ assertMediaEnabled(options.enabled, IMAGE_TOOL);
149
+ const prompt = String(args?.prompt ?? '').trim();
150
+ if (!prompt) throw new Error('prompt 必须是非空字符串');
151
+ if (prompt.length > MAX_PROMPT_CHARS) throw new Error(`prompt 超过 ${MAX_PROMPT_CHARS} 字符上限`);
152
+ const model = args?.model ?? options.defaultModel?.() ?? DEFAULT_IMAGE_MODEL;
153
+ if (!SUPPORTED_IMAGE_MODELS.includes(model)) throw new Error(`model 必须是 ${SUPPORTED_IMAGE_MODELS.join(' / ')} 之一`);
154
+ const size = args?.size === undefined ? '2K' : String(args.size).trim();
155
+ if (!SUPPORTED_IMAGE_SIZES.includes(size) && !SIZE_PATTERN.test(size)) {
156
+ throw new Error(`size 必须是 ${SUPPORTED_IMAGE_SIZES.join(' / ')} 或 WpxH(如 1920x1920)`);
157
+ }
158
+ const outputFormat = args?.output_format ?? 'png';
159
+ if (!SUPPORTED_IMAGE_FORMATS.includes(outputFormat)) throw new Error(`output_format 必须是 ${SUPPORTED_IMAGE_FORMATS.join(' / ')} 之一`);
160
+
161
+ const attachments = options.resolveAttachments();
162
+ if (!attachments || typeof attachments.saveImage !== 'function' || typeof attachments.saveFile !== 'function') {
163
+ throw new Error('宿主附件服务不支持原图与预览分开保存,无法保留输出格式');
164
+ }
165
+ const specs = [args?.image, ...(Array.isArray(args?.images) ? args.images : [])].filter(Boolean);
166
+ const images = specs.length
167
+ ? await resolveImageSources(specs, {
168
+ cwd: exec.agent?.session?.header?.cwd,
169
+ readFile: resolveReadFile(exec), attachments, signal: exec.signal
170
+ })
171
+ : [];
172
+ const { key } = await options.credentials();
173
+ const body = {
174
+ model, prompt, size, output_format: outputFormat,
175
+ response_format: 'url', watermark: args?.watermark ?? true
176
+ };
177
+ if (images.length === 1) body.image = images[0].url;
178
+ else if (images.length > 1) body.image = images.map(item => item.url);
179
+ const data = await arkFetchJson(`${ARK_MEDIA_BASE_URL}/images/generations`, {
180
+ method: 'POST', apiKey: key, body, signal: exec.signal, timeoutMs: 300000
181
+ });
182
+ const entries = Array.isArray(data?.data) ? data.data.slice(0, 4) : [];
183
+ if (!entries.length) throw new Error('方舟未返回图片结果');
184
+
185
+ const saved = [];
186
+ for (const [index, entry] of entries.entries()) {
187
+ if (typeof entry?.url !== 'string' || !entry.url.startsWith('https://')) continue;
188
+ const { data: bytes } = await downloadMediaBytes(entry.url, {
189
+ signal: exec.signal, maxBytes: MAX_IMAGE_RESULT_BYTES, label: '图片结果'
190
+ });
191
+ const actualType = sniffMediaType(bytes);
192
+ const expectedType = expectedMediaType(outputFormat);
193
+ if (actualType !== expectedType) {
194
+ throw new Error(`方舟实际返回 ${actualType ?? '未知格式'},与 output_format=${outputFormat} 要求的 ${expectedType} 不一致`);
195
+ }
196
+ const name = `volc-imagine-${Date.now()}-${index + 1}.${mediaExtensionFor(actualType)}`;
197
+ saved.push(await saveResultEntry(attachments, bytes, actualType, name));
198
+ }
199
+ if (!saved.length) throw new Error('方舟返回了空图片结果');
200
+ const value = {
201
+ model: String(data.model ?? model), created: Number(data.created ?? 0),
202
+ images: saved.map(item => item.preview), originals: saved.map(item => item.original)
203
+ };
204
+ const lines = [
205
+ `${images.length ? 'Edited' : 'Generated'} ${saved.length} image(s) with ${model} via 火山方舟 Agent Plan.`,
206
+ ...saved.map((item, index) => `Original ${item.original.mediaType} file${saved.length > 1 ? ` ${index + 1}` : ''}: attachment=${JSON.stringify(item.original.attachment)}`),
207
+ '原始文件保持方舟返回格式;会话图片预览可能经宿主规范化,不影响原文件字节。'
208
+ ];
209
+ return { ...value, text: lines.join(' ') };
210
+ }
211
+ }));
212
+ }
package/lib/media.mjs ADDED
@@ -0,0 +1,263 @@
1
+ // 图片生成的共享工具:方舟端点请求、参考素材解析与受控下载。
2
+ // 设置归一化与模型目录在浏览器安全的 media-config.mjs 中维护。
3
+ import { isAbsolute, resolve } from 'node:path';
4
+
5
+ export {
6
+ MEDIA_TOOL_KEYS, SUPPORTED_IMAGE_MODELS, DEFAULT_IMAGE_MODEL,
7
+ defaultMediaState, normalizeMediaState, mediaToolEnabled, assertMediaEnabled
8
+ } from './media-config.mjs';
9
+ export const ARK_MEDIA_BASE_URL = 'https://ark.cn-beijing.volces.com/api/plan/v3';
10
+ export const ARK_MEDIA_HOST = 'ark.cn-beijing.volces.com';
11
+ export const MAX_JSON_RESPONSE_BYTES = 256 * 1024;
12
+ export const MAX_PROMPT_CHARS = 8000;
13
+ export const MAX_SOURCE_IMAGE_BYTES = 30 * 1024 * 1024;
14
+ export const MAX_IMAGE_RESULT_BYTES = 48 * 1024 * 1024;
15
+ export const MAX_SOURCE_IMAGES = 10;
16
+ // 方舟返回的图像/视频为 24 小时有效的预签名 GET 链接,域名归属火山引擎 TOS/CDN。
17
+ export const MEDIA_DOWNLOAD_HOST_SUFFIXES = ['.volces.com', '.volces.com.cn', '.volcdoc.com', '.volcengine.com'];
18
+ export const MAX_DOWNLOAD_REDIRECTS = 3;
19
+
20
+ export const BILLING_NOTE = '图片按官方 Agent Plan 额度计费并消耗套餐 AFP,提交即视为确认本次消耗。';
21
+
22
+ export class ArkApiError extends Error {
23
+ constructor(message, status) { super(message); this.status = status; }
24
+ }
25
+
26
+ export function redactSecrets(text) {
27
+ return String(text).replace(/Bearer\s+[^"'\\\s]+/giu, 'Bearer ***').replace(/[?&](X-Tos-Signature|Signature|token|access_key|sk|api_key|key)=[^&\s"']*/giu, '$1=***');
28
+ }
29
+
30
+ /** 读取 JSON 响应并限制体积;错误响应只暴露摘要,不携带响应头与凭证。 */
31
+ export async function arkFetchJson(url, { method = 'GET', apiKey, body, signal, timeoutMs = 120000 } = {}) {
32
+ const parsed = url instanceof URL ? url : new URL(url);
33
+ if (parsed.protocol !== 'https:' || parsed.hostname !== ARK_MEDIA_HOST) {
34
+ throw new Error(`媒体请求目标不在方舟白名单内:${parsed.hostname}`);
35
+ }
36
+ const controller = new AbortController();
37
+ const timer = setTimeout(() => controller.abort(new Error('方舟媒体接口请求超时')), timeoutMs);
38
+ const links = signal ? [signal, controller.signal] : [controller.signal];
39
+ try {
40
+ const response = await fetch(parsed, {
41
+ method,
42
+ headers: {
43
+ 'content-type': 'application/json',
44
+ ...(apiKey ? { authorization: `Bearer ${apiKey}` } : {})
45
+ },
46
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
47
+ redirect: 'error',
48
+ signal: AbortSignal.any(links)
49
+ });
50
+ const text = await response.text();
51
+ if (text.length > MAX_JSON_RESPONSE_BYTES) throw new ArkApiError('方舟媒体接口响应过大', response.status);
52
+ let data;
53
+ try { data = text.length ? JSON.parse(text) : {}; }
54
+ catch { throw new ArkApiError(`方舟媒体接口返回非 JSON 内容(HTTP ${response.status})`, response.status); }
55
+ if (!response.ok) {
56
+ const detail = data?.error?.message ?? data?.message ?? data?.error?.code ?? '';
57
+ throw new ArkApiError(`方舟媒体接口错误(HTTP ${response.status})${detail ? `:${redactSecrets(detail).slice(0, 300)}` : ''}`, response.status);
58
+ }
59
+ return data;
60
+ } catch (error) {
61
+ if (error instanceof ArkApiError) throw error;
62
+ if (error?.name === 'AbortError') throw error;
63
+ throw new ArkApiError(`方舟媒体接口请求失败:${redactSecrets(error?.message ?? error)}`);
64
+ } finally { clearTimeout(timer); }
65
+ }
66
+
67
+ function allowedDownloadHost(hostname) {
68
+ return MEDIA_DOWNLOAD_HOST_SUFFIXES.some(suffix => hostname.endsWith(suffix));
69
+ }
70
+
71
+ /**
72
+ * 以流式字节块下载受白名单保护的远程媒体。签名 URL 只在本函数内存活,
73
+ * 不进入状态、日志或工具输出。redirect 手动跟随且每跳重新校验主机。
74
+ */
75
+ export async function downloadMediaChunks(signedUrl, { signal, timeoutMs = 300000, maxBytes = MAX_IMAGE_RESULT_BYTES, label = '图片' } = {}) {
76
+ let current = new URL(signedUrl);
77
+ if (current.protocol !== 'https:') throw new Error(`${label}下载地址必须是 HTTPS`);
78
+ for (let hop = 0; hop <= MAX_DOWNLOAD_REDIRECTS; hop++) {
79
+ if (!allowedDownloadHost(current.hostname)) throw new Error(`${label}下载地址不在火山引擎白名单内:${current.hostname}`);
80
+ const controller = new AbortController();
81
+ const timer = setTimeout(() => controller.abort(new Error(`${label}下载超时`)), timeoutMs);
82
+ try {
83
+ const response = await fetch(current, {
84
+ method: 'GET',
85
+ redirect: 'manual',
86
+ signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal
87
+ });
88
+ if (response.status >= 300 && response.status < 400) {
89
+ const location = response.headers.get('location');
90
+ await response.arrayBuffer().catch(() => {});
91
+ if (!location) throw new Error(`${label}下载重定向缺少目标`);
92
+ current = new URL(location, current);
93
+ if (current.protocol !== 'https:') throw new Error(`${label}下载重定向目标必须是 HTTPS`);
94
+ continue;
95
+ }
96
+ if (!response.ok) throw new Error(`${label}下载失败(HTTP ${response.status})`);
97
+ const declared = Number(response.headers.get('content-length') ?? 0);
98
+ if (declared > maxBytes) {
99
+ await response.arrayBuffer().catch(() => {});
100
+ throw new Error(`${label}超过 ${maxBytes} 字节上限`);
101
+ }
102
+ const stream = (async function* () {
103
+ let total = 0;
104
+ try {
105
+ for await (const chunk of response.body) {
106
+ total += chunk.byteLength;
107
+ if (total > maxBytes) throw new Error(`${label}超过 ${maxBytes} 字节上限`);
108
+ yield chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
109
+ }
110
+ } finally { await response.body.cancel().catch(() => {}); }
111
+ })();
112
+ const expected = declared > 0 ? declared : undefined;
113
+ return { stream, bytes: expected };
114
+ } catch (error) {
115
+ if (error?.name === 'AbortError') throw error;
116
+ throw error instanceof Error ? error : new Error(redactSecrets(String(error)));
117
+ } finally { clearTimeout(timer); }
118
+ }
119
+ throw new Error(`${label}下载重定向次数过多`);
120
+ }
121
+
122
+ export async function downloadMediaBytes(url, options = {}) {
123
+ const { stream, bytes } = await downloadMediaChunks(url, options);
124
+ const chunks = [];
125
+ let total = 0;
126
+ for await (const chunk of stream) { chunks.push(chunk); total += chunk.byteLength; }
127
+ const data = new Uint8Array(total);
128
+ let offset = 0;
129
+ for (const chunk of chunks) { data.set(chunk, offset); offset += chunk.byteLength; }
130
+ return { data, bytes: bytes ?? total };
131
+ }
132
+
133
+ // ---------- 参考素材解析 ----------
134
+
135
+ function prefixBytes(text) { return new TextEncoder().encode(text); }
136
+
137
+ export function sniffMediaType(bytes) {
138
+ const png = [0x89, 0x50, 0x4e, 0x47], jpeg = [0xff, 0xd8, 0xff], gif = prefixBytes('GIF8'), webp = prefixBytes('RIFF');
139
+ const bmp = prefixBytes('BM'), tiffLe = [0x49, 0x49, 0x2a, 0x00], tiffBe = [0x4d, 0x4d, 0x00, 0x2a];
140
+ const match = (list) => list.every((value, index) => bytes[index] === value);
141
+ if (bytes.length >= 8 && match(png)) return 'image/png';
142
+ if (bytes.length >= 3 && match(jpeg)) return 'image/jpeg';
143
+ if (bytes.length >= 4 && match(gif)) return 'image/gif';
144
+ if (bytes.length >= 12 && match(webp) && bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) return 'image/webp';
145
+ if (bytes.length >= 2 && match(bmp)) return 'image/bmp';
146
+ if (bytes.length >= 4 && (match(tiffLe) || match(tiffBe))) return 'image/tiff';
147
+ return undefined;
148
+ }
149
+
150
+ export function mediaExtensionFor(mediaType) {
151
+ return { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp', 'image/gif': 'gif', 'image/bmp': 'bmp', 'image/tiff': 'tif' }[mediaType] ?? 'bin';
152
+ }
153
+
154
+ const ATTACHMENT_ID = /^sha256:[a-f0-9]{64}$/u;
155
+ const ATTACHMENT_ID_ANY = /sha256:[a-f0-9]{64}/u;
156
+
157
+ /** 模型可给出 attachmentId=… / attachment={…json…} / 裸 sha256 id 三种形式。 */
158
+ export function parseAttachmentSpec(value) {
159
+ const text = String(value).trim();
160
+ const embedded = /attachment=(\{[^}]*\})/u.exec(text);
161
+ if (embedded) {
162
+ try {
163
+ const parsed = JSON.parse(embedded[1]);
164
+ if (typeof parsed?.attachmentId === 'string' && ATTACHMENT_ID.test(parsed.attachmentId)) {
165
+ return { attachmentId: parsed.attachmentId, ref: parsed };
166
+ }
167
+ } catch { /* fall through to id matching */ }
168
+ }
169
+ const labeled = /attachmentId\s*=\s*(sha256:[a-f0-9]{64})/u.exec(text);
170
+ if (labeled) return { attachmentId: labeled[1] };
171
+ const bare = ATTACHMENT_ID_ANY.exec(text);
172
+ if (bare && text.replace(ATTACHMENT_ID_ANY, '').replace(/attachmentId\s*=/u, '').trim().length === 0) {
173
+ return { attachmentId: bare[0] };
174
+ }
175
+ return undefined;
176
+ }
177
+
178
+ export function isHttpUrl(value) { return /^https?:\/\//iu.test(value.trim()); }
179
+
180
+ function decodeDataUri(trimmed, maxBytes) {
181
+ const match = /^data:([a-z]+\/[a-z0-9.+-]+);base64,([a-z0-9+/=\s]+)$/iu.exec(trimmed);
182
+ if (!match) throw new Error('data URI 必须是 base64 编码的媒体内容');
183
+ const declared = match[1].toLowerCase();
184
+ const payload = match[2].replace(/\s+/gu, '');
185
+ if (!/^[a-z0-9+/]*={0,2}$/iu.test(payload)) throw new Error('data URI 包含非法 base64 内容');
186
+ const bytes = Buffer.from(payload, 'base64');
187
+ if (bytes.byteLength === 0) throw new Error('data URI 内容为空');
188
+ if (bytes.byteLength > maxBytes) throw new Error(`data URI 为 ${bytes.byteLength} 字节,超过 ${maxBytes} 上限`);
189
+ const sniffed = sniffMediaType(bytes);
190
+ if (!sniffed) throw new Error('data URI 内容不是可识别的图片/媒体格式');
191
+ if (sniffed !== declared) throw new Error(`data URI 声明的 ${declared} 与实际内容 ${sniffed} 不一致`);
192
+ return { bytes, mediaType: sniffed };
193
+ }
194
+
195
+ async function readAttachmentBytes(attachments, attachment, maxBytes, signal) {
196
+ if (!attachments) throw new Error('引用会话附件需要宿主附件服务,当前上下文不可用');
197
+ const id = attachment.attachmentId;
198
+ // 完整 ImageAttachmentRef 走 readImage(存储侧校验字节);裸 id 先经 imageHostPath。
199
+ if (attachment.ref && typeof attachment.ref === 'object' && typeof attachments.readImage === 'function') {
200
+ const stored = await attachments.readImage(attachment.ref, signal);
201
+ const data = stored?.data;
202
+ if (!(data instanceof Uint8Array) || data.byteLength === 0) throw new Error(`附件 ${id} 无法读取`);
203
+ if (data.byteLength > maxBytes) throw new Error(`附件 ${id} 为 ${data.byteLength} 字节,超过 ${maxBytes} 上限`);
204
+ return { bytes: data, mediaType: sniffMediaType(data) ?? attachment.ref.mediaType ?? 'image/png' };
205
+ }
206
+ if (typeof attachments.imageHostPath === 'function' && attachment.ref) {
207
+ const hostPath = attachments.imageHostPath(attachment.ref);
208
+ if (hostPath) {
209
+ const { readFile } = await import('node:fs/promises');
210
+ const data = new Uint8Array(await readFile(hostPath));
211
+ if (data.byteLength > maxBytes) throw new Error(`附件 ${id} 为 ${data.byteLength} 字节,超过 ${maxBytes} 上限`);
212
+ const mediaType = sniffMediaType(data);
213
+ if (!mediaType) throw new Error(`附件 ${id} 不是可识别的图片格式`);
214
+ return { bytes: data, mediaType };
215
+ }
216
+ }
217
+ throw new Error(`附件 ${id} 需要完整 attachment JSON 引用(含 mediaType/bytes/width/height)才能读取`);
218
+ }
219
+
220
+ /**
221
+ * 把模型给出的图像来源(https URL / data URI / 会话附件 / 本地路径)解析为
222
+ * 方舟可接受的 url 字段。本地与附件内容编码为 data URI;远程 URL 原样透传。
223
+ * readFile 由调用方注入(默认 node fs;工具内会换成宿主 fs 服务)。
224
+ */
225
+ export async function resolveImageSources(specs, {
226
+ cwd, maxBytes = MAX_SOURCE_IMAGE_BYTES, maxSources = MAX_SOURCE_IMAGES,
227
+ readFile, attachments, signal
228
+ } = {}) {
229
+ const list = (Array.isArray(specs) ? specs : []).filter(value => typeof value === 'string' && value.trim().length > 0);
230
+ if (list.length > maxSources) throw new Error(`参考图过多:${list.length} 张(最多 ${maxSources} 张)`);
231
+ const resolved = [];
232
+ for (const spec of list) {
233
+ const trimmed = spec.trim();
234
+ if (isHttpUrl(trimmed)) {
235
+ const parsed = new URL(trimmed);
236
+ if (parsed.protocol !== 'https:') throw new Error('参考图 URL 必须使用 HTTPS');
237
+ resolved.push({ url: trimmed, origin: 'url' });
238
+ continue;
239
+ }
240
+ if (/^data:/iu.test(trimmed)) {
241
+ const { mediaType } = decodeDataUri(trimmed, maxBytes);
242
+ resolved.push({ url: trimmed.replace(/^data:[^,]+;/iu, `data:${mediaType};`), origin: 'data-uri', mediaType });
243
+ continue;
244
+ }
245
+ const attachment = parseAttachmentSpec(trimmed);
246
+ if (attachment) {
247
+ const { bytes, mediaType } = await readAttachmentBytes(attachments, attachment, maxBytes, signal);
248
+ resolved.push({ url: `data:${mediaType};base64,${Buffer.from(bytes).toString('base64')}`, origin: 'attachment', mediaType, bytes: bytes.byteLength });
249
+ continue;
250
+ }
251
+ const target = isAbsolute(trimmed) ? trimmed : resolve(cwd ?? process.cwd(), trimmed);
252
+ let bytes;
253
+ try { bytes = readFile ? new Uint8Array(await readFile(trimmed)) : new Uint8Array(await (await import('node:fs/promises')).readFile(target)); }
254
+ catch (error) { throw new Error(`无法读取参考图 ${JSON.stringify(trimmed)}:${error?.message ?? error}`); }
255
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0) throw new Error(`参考图 ${JSON.stringify(trimmed)} 为空或不可读`);
256
+ if (bytes.byteLength > maxBytes) throw new Error(`参考图 ${JSON.stringify(trimmed)} 为 ${bytes.byteLength} 字节,超过 ${maxBytes} 上限`);
257
+ const mediaType = sniffMediaType(bytes);
258
+ if (!mediaType || !mediaType.startsWith('image/')) throw new Error(`参考图 ${JSON.stringify(trimmed)} 不是方舟支持的图片格式`);
259
+ resolved.push({ url: `data:${mediaType};base64,${Buffer.from(bytes).toString('base64')}`, origin: 'file', mediaType, bytes: bytes.byteLength });
260
+ }
261
+ return resolved;
262
+ }
263
+
@@ -0,0 +1,47 @@
1
+ // OAuth 登录态到期元数据:只解读官方 CLI 签发的 refresh_token JWT 的 exp claim。
2
+ // 官方 SSO 的 refresh_token 有效期固定(实测 48 小时)、续期不轮换不延长,
3
+ // 因此它的 exp 就是登录态的权威到期时间。token 本体与其他 claim 不落盘、不返回、不进日志。
4
+ import { readdir, readFile } from 'node:fs/promises';
5
+ import { join } from 'node:path';
6
+
7
+ /**
8
+ * 解读 JWT 的到期时间;只取 exp claim,任何非法输入返回 null。
9
+ *
10
+ * @param {unknown} token refresh_token 文本
11
+ * @returns {number|null} 到期毫秒时间戳;无法解读时 null
12
+ */
13
+ export function refreshTokenExpiry(token) {
14
+ if (typeof token !== 'string') return null;
15
+ const parts = token.split('.');
16
+ if (parts.length !== 3 || !parts[1]) return null;
17
+ try {
18
+ const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
19
+ const exp = payload?.exp;
20
+ if (typeof exp !== 'number' || !Number.isFinite(exp) || exp <= 0) return null;
21
+ return exp * 1000;
22
+ } catch { return null; }
23
+ }
24
+
25
+ /**
26
+ * 从账号隔离 CLI home 读取登录态到期时间。目录缺失、文件损坏或字段缺失返回 null,不抛错;
27
+ * 多个身份目录时取最晚到期(正常只有一个 active 身份)。
28
+ *
29
+ * @param {string} home 隔离 CLI home 绝对路径
30
+ * @returns {Promise<number|null>} 到期毫秒时间戳;未知时 null
31
+ */
32
+ export async function readOAuthExpiry(home) {
33
+ const dir = join(home, '.arkcli', 'identities');
34
+ let entries;
35
+ try { entries = await readdir(dir, { withFileTypes: true }); }
36
+ catch { return null; }
37
+ let latest = null;
38
+ for (const entry of entries) {
39
+ if (!entry.isDirectory()) continue;
40
+ let data;
41
+ try { data = JSON.parse(await readFile(join(dir, entry.name, 'token.json'), 'utf8')); }
42
+ catch { continue; } // 单个身份文件不可读时跳过,不影响其他身份。
43
+ const expiry = refreshTokenExpiry(data?.refresh_token);
44
+ if (expiry !== null && (latest === null || expiry > latest)) latest = expiry;
45
+ }
46
+ return latest;
47
+ }
@@ -0,0 +1,105 @@
1
+ // 额度中间层:Host 定期采集的额度结果先落到这里,Client 只读这份快照。
2
+ //
3
+ // 设计取舍:
4
+ // - 快照是加速层,不是权威数据;文件损坏、版本不符或字段异常都直接丢弃,从空开始重建。
5
+ // - 只保存展示所需字段,不保存凭据、CLI 原始输出或请求参数。
6
+ // - 写入走「临时文件 + rename」,与状态文件同目录;写失败不影响采集结果的内存可用性。
7
+ import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
8
+ import { dirname } from 'node:path';
9
+ import { randomUUID } from 'node:crypto';
10
+
11
+ export const SNAPSHOT_VERSION = 1;
12
+
13
+ /** 额度快照允许保存的字段:其余一律丢弃,避免把内部错误对象写进磁盘。 */
14
+ const VALUE_FIELDS = ['accountId', 'plan', 'state', 'windows', 'error', 'errorKind', 'planName', 'updatedAt', 'refreshError', 'refreshFailedAt'];
15
+
16
+ function cleanValue(value) {
17
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
18
+ const out = {};
19
+ for (const field of VALUE_FIELDS) {
20
+ if (!Object.hasOwn(value, field) || value[field] === undefined) continue;
21
+ try { out[field] = structuredClone(value[field]); }
22
+ catch { /* 不可序列化的值不写入快照 */ }
23
+ }
24
+ return Object.keys(out).length ? out : undefined;
25
+ }
26
+
27
+ export class QuotaSnapshotStore {
28
+ constructor({ path }) { this.path = path; this.entries = new Map(); this.queue = Promise.resolve(); this.closed = false; }
29
+
30
+ /** 读取上次进程留下的快照;任何异常都退回空快照。 */
31
+ async load() {
32
+ if (!this.path) return;
33
+ try {
34
+ const parsed = JSON.parse(await readFile(this.path, 'utf8'));
35
+ if (!parsed || parsed.version !== SNAPSHOT_VERSION || !parsed.entries || typeof parsed.entries !== 'object') return;
36
+ for (const [key, raw] of Object.entries(parsed.entries)) {
37
+ if (!raw || typeof raw !== 'object' || typeof raw.fingerprint !== 'string' || typeof raw.at !== 'number') continue;
38
+ const value = cleanValue(raw.value);
39
+ if (!value) continue;
40
+ this.entries.set(key, { fingerprint: raw.fingerprint, at: raw.at, value });
41
+ }
42
+ } catch { /* 缺失或损坏都从空开始 */ }
43
+ }
44
+
45
+ /** 取一条快照;传 fingerprint 时只有身份一致才返回,避免账号切换后串用旧结果。 */
46
+ get(key, fingerprint) {
47
+ const entry = this.entries.get(key);
48
+ if (!entry) return undefined;
49
+ if (fingerprint && entry.fingerprint !== fingerprint) return undefined;
50
+ return entry;
51
+ }
52
+
53
+ set(key, fingerprint, value, at = Date.now()) {
54
+ const clean = cleanValue(value);
55
+ if (!clean || typeof fingerprint !== 'string') return;
56
+ this.entries.set(key, { fingerprint, at, value: clean });
57
+ this.save();
58
+ }
59
+
60
+ delete(key) {
61
+ if (this.entries.delete(key)) this.save();
62
+ }
63
+
64
+ /** 丢弃不再需要的条目(账号删除、套餐停用等)。 */
65
+ prune(isValid) {
66
+ let changed = false;
67
+ for (const key of [...this.entries.keys()]) {
68
+ if (isValid(key)) continue;
69
+ this.entries.delete(key);
70
+ changed = true;
71
+ }
72
+ if (changed) this.save();
73
+ }
74
+
75
+ /** 供 RPC 下发的只读视图:key → { at, value }。 */
76
+ map() {
77
+ const out = {};
78
+ for (const [key, entry] of this.entries) out[key] = { at: entry.at, value: structuredClone(entry.value) };
79
+ return out;
80
+ }
81
+
82
+ /** 关闭后不再写入;已排队任务仍会完成,调用方可用 whenIdle() 等待。 */
83
+ close() { this.closed = true; return this.queue; }
84
+
85
+ /** 等待所有已排队的落盘任务结束(测试与卸载收尾用)。 */
86
+ whenIdle() { return this.queue; }
87
+
88
+ /** 串行原子写入;写失败只丢快照,不影响内存结果。 */
89
+ save() {
90
+ const path = this.path;
91
+ if (!path || this.closed) return;
92
+ this.queue = this.queue.then(async () => {
93
+ const entries = {};
94
+ for (const [key, entry] of this.entries) entries[key] = { fingerprint: entry.fingerprint, at: entry.at, value: entry.value };
95
+ const temp = `${path}.${process.pid}.${randomUUID()}.tmp`;
96
+ try {
97
+ await mkdir(dirname(path), { recursive: true });
98
+ await writeFile(temp, JSON.stringify({ version: SNAPSHOT_VERSION, entries }) + '\n', { mode: 0o600 });
99
+ await rename(temp, path);
100
+ } catch {
101
+ await rm(temp, { force: true }).catch(() => {});
102
+ }
103
+ }).catch(() => {});
104
+ }
105
+ }
package/lib/state.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { mkdir, readFile, writeFile, rename, rm, open } from 'node:fs/promises';
3
3
  import { dirname } from 'node:path';
4
+ import { normalizeMediaState } from './media.mjs';
4
5
 
5
6
  export const STATE_VERSION = 2;
6
7
  export const PLANS = ['agent-plan', 'coding-plan'];
@@ -169,7 +170,8 @@ export function initialState() {
169
170
  enabled: { 'agent-plan': true, 'coding-plan': true },
170
171
  catalogs: {},
171
172
  oauth: {},
172
- modelSettings: {}
173
+ modelSettings: {},
174
+ media: normalizeMediaState()
173
175
  };
174
176
  }
175
177
  export function validateState(value) {
@@ -208,7 +210,8 @@ export function validateState(value) {
208
210
  enabled[plan] = declared ?? Boolean(active[plan]);
209
211
  }
210
212
  const modelSettings = normalizeModelSettingsMap(value.modelSettings, accounts);
211
- return { version: STATE_VERSION, accounts, active, enabled, catalogs, oauth, modelSettings };
213
+ const media = normalizeMediaState(value.media);
214
+ return { version: STATE_VERSION, accounts, active, enabled, catalogs, oauth, modelSettings, media };
212
215
  }
213
216
  /** Only explicitly supported, non-secret identity fields may enter metadata or RPC. */
214
217
  export function normalizeIdentity(value) {