@napuketto/adapter 0.19.0 → 0.21.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.
@@ -1,13 +1,12 @@
1
1
  import { a as validateServerTokens, c as BEARER_PREFIX, f as ActionRegistry, l as createTokenAuthorize, o as BaseProtocolAdapter, p as runAction, r as createServerSchema, s as resolveProtocolConfig } from "./framework-CA3087JP.mjs";
2
- import { a as logEventFailure, c as downloadBufferToFile, d as prepareVideoElements, f as MediaCache, h as withMediaScope, i as hasGrayTip, l as ensureSilk, m as protectMediaPath, o as sliceRaw, p as cacheMediaFile, r as firstUntranslatedGrayTip, s as truncRaw, t as collectGrayTipUids, u as fileUriToPath } from "./gray-tip-BL1rhwZK.mjs";
2
+ import { _ as cacheMediaFile, a as logEventFailure, c as protocolMediaSchema, d as mediaDownloader, f as prepareVideoElements, g as MediaCache, h as resolveLocalMedia, i as hasGrayTip, l as downloadProtocolMedia, m as exportQqMedia, o as sliceRaw, p as bindLocalMediaRoots, r as firstUntranslatedGrayTip, s as truncRaw, t as collectGrayTipUids, u as ensureSilk, y as withMediaScope } from "./gray-tip-D0SfHr7q.mjs";
3
3
  import { a as firstNonEmptyString, c as MS_TO_SEC, d as numericUin, f as resolveUidToUinWithFallback, i as toUnixSeconds, l as NUMERIC_RE, m as toUin, n as senderNickname, o as stringOrUndefined, r as subscribeRawMessages, s as startupBaselineSec, u as collectGroupNotifyUids } from "./raw-message-DU8YOhLV.mjs";
4
4
  import { a as processSysMsgBlob, d as processInboundBuddyReqs, n as OBSERVED_UNNAMED_SYSMSG_KEYS, o as recognizeSysMsg, r as narrowSysMsgBlobs, t as extractEssenceSetSysMsg, u as BuddyReqDedup } from "./essence-Cn1oRaLw.mjs";
5
5
  import { ChatType, EssenceListSync, GrayTipSubType, GroupApi, GroupNotifyMsgStatus, GroupNotifyMsgType, NTGroupMemberRole, NTGroupRequestOperateTypes, TicketApi, TipGroupElementType, WebHonorType, errorMessage, hasStringProp, isRecord, kernelError, narrowEssenceGroupArg, toCanonicalElements } from "@napuketto/kernel";
6
6
  import { HttpClient, HttpServer, WsClient, WsServer } from "@napuketto/network";
7
7
  import { z } from "zod";
8
- import { existsSync } from "node:fs";
9
- import { join } from "node:path";
10
- import { downloadUrl, inferExtension } from "@napuketto/media";
8
+ import { basename } from "node:path";
9
+ import { inferExtension } from "@napuketto/media";
11
10
  // src/onebot11/helper/message-unique.ts
12
11
  /** OB11 message_id 上限(int32 max = 0x7FFF_FFFF)。 */
13
12
  const INT32_MAX = 2147483647;
@@ -1422,6 +1421,7 @@ const wsReverseSchema = z.object({
1422
1421
  heartbeatInterval: z.number().int().default(DEFAULT_WS_HEARTBEAT_MS)
1423
1422
  });
1424
1423
  const ob11ConfigSchema = z.object({
1424
+ media: protocolMediaSchema.optional(),
1425
1425
  /** 鉴权 token(全局默认,实例未指定时继承)。 */
1426
1426
  token: z.string().optional(),
1427
1427
  /** 心跳 meta 事件间隔(毫秒),0 关闭心跳。 */
@@ -2117,17 +2117,8 @@ function createHistoryActions(api) {
2117
2117
  /**
2118
2118
  * 消息媒体域动作
2119
2119
  *
2120
- * - get_image / get_record:获取图片/语音文件(图片接主动下载;语音接原生
2121
- * downloadRichMedia)。message_id 反查 → fetchMsgsByMsgId → 找 PIC/PTT 元素:
2122
- * - 本地文件解析:NT 相对路径(sourcePath/filePath)按 mediaBaseDir(QQ NT
2123
- * global 目录)解析为绝对路径,命中磁盘即返回 file
2124
- * - 图片主动下载:本地未命中且有 picUrl → @napuketto/media downloadUrl 落
2125
- * cacheDir/media/,返回 file(绝对路径)+ url + file_size/file_name
2126
- * - 语音主动下载:本地未命中 → kernel MsgApi.downloadPtt(原生
2127
- * downloadRichMedia + 轮询元素回查)→ filePath 落盘后返回绝对路径;
2128
- * 失败回退原始 filePath(NT 相对/绝对)+ 元数据,不抛错
2129
- * - fetch_ptt_text:message_id → MsgApi.fetchPttText(内部:拉消息 → 找 PTT 元素
2130
- * → translatePtt2Text → 再拉取读 pttElement.text)
2120
+ * - get_image/get_record:经当前账号的消息 API 取资源,并导出到带租约的缓存。
2121
+ * - fetch_ptt_text:经内核拉取语音转文字。
2131
2122
  */
2132
2123
  const getMediaSchema = z.object({
2133
2124
  /** CQ 码 file 字段或 message_id(简化:message_id 反查)。 */
@@ -2135,33 +2126,16 @@ const getMediaSchema = z.object({
2135
2126
  message_id: z.union([z.number(), z.string()]).optional()
2136
2127
  });
2137
2128
  const fetchPttTextSchema = z.object({ message_id: z.union([z.number(), z.string()]) });
2138
- /**
2139
- * NT 相对路径 → 本地绝对路径(存在才返回)。
2140
- * 候选:原样绝对路径 / mediaBaseDir 下相对路径(反斜杠归一化)。
2141
- */
2142
- function resolveLocalMediaFile(relPath, deps) {
2143
- if (relPath === "") return null;
2144
- if (existsSync(relPath)) return relPath;
2145
- const base = deps.mediaBaseDir;
2146
- if (base !== void 0 && base !== "") {
2147
- const joined = join(base, relPath.replaceAll("\\", "/"));
2148
- if (existsSync(joined)) return joined;
2149
- }
2150
- return null;
2151
- }
2152
2129
  /** 图片主动下载(picUrl → cacheDir/media/<uuid>.<ext>;无 cacheDir/url 返回 null)。 */
2153
2130
  async function downloadImageToCache(url, deps) {
2154
2131
  const cacheDir = deps.cacheDir;
2155
2132
  if (cacheDir === void 0 || cacheDir === "") return null;
2156
2133
  try {
2157
2134
  return await cacheMediaFile(cacheDir, inferExtension(null, url), async (dest) => {
2158
- await downloadUrl(url, dest);
2135
+ await mediaDownloader(deps.getMediaOutboundPolicy?.())(url, dest);
2159
2136
  }, "reference");
2160
2137
  } catch (err) {
2161
- deps.logger?.warn({
2162
- url,
2163
- error: errorMessage(err)
2164
- }, "ob11: 图片主动下载失败,get_image 退原始 url");
2138
+ deps.logger?.warn({ error: errorMessage(err) }, "ob11: 图片主动下载失败,get_image 退原始 url");
2165
2139
  return null;
2166
2140
  }
2167
2141
  }
@@ -2174,7 +2148,7 @@ async function resolveMedia(id, label, deps, extract) {
2174
2148
  const [first] = await deps.msgApi.fetchMsgsByMsgId(peer, [msgId]);
2175
2149
  if (first === void 0) throw kernelError(`消息 ${id} 不存在或已被撤回`, "NOT_FOUND");
2176
2150
  for (const el of first.elements) {
2177
- const found = extract(el);
2151
+ const found = await extract(el);
2178
2152
  if (found !== void 0) return found;
2179
2153
  }
2180
2154
  throw kernelError(`消息 ${id} 不包含${label}`, "NOT_FOUND");
@@ -2186,17 +2160,17 @@ function takeId(payload, actionName) {
2186
2160
  return id;
2187
2161
  }
2188
2162
  /** 提取 pic 元素 → 媒体信息(url / 本地 file / 元数据;非 pic 元素返回 undefined)。 */
2189
- function extractPicElement(el, deps) {
2163
+ async function extractPicElement(el, deps) {
2190
2164
  const pic = el.picElement;
2191
2165
  if (pic == null) return;
2192
2166
  const out = {};
2193
2167
  if (pic.fileSize != null) out.file_size = pic.fileSize;
2194
2168
  if (pic.fileName != null) out.file_name = pic.fileName;
2195
2169
  if (pic.picUrl != null) out.url = pic.picUrl;
2196
- const rel = pic.sourcePath ?? pic.picPath;
2170
+ const rel = pic.sourcePath || pic.picPath;
2197
2171
  if (rel != null) {
2198
- const local = resolveLocalMediaFile(rel, deps);
2199
- if (local !== null) out.file = local;
2172
+ const local = await exportQqMedia(rel, deps.mediaBaseDir, deps.cacheDir);
2173
+ if (local !== void 0) out.file = local;
2200
2174
  }
2201
2175
  return out;
2202
2176
  }
@@ -2206,8 +2180,8 @@ async function downloadPttFallback(msgId, peer, id, deps) {
2206
2180
  const downloaded = await deps.msgApi.downloadPtt(msgId, peer);
2207
2181
  const rel = downloaded.filePath;
2208
2182
  if (rel != null && rel !== "") {
2209
- const localAfter = resolveLocalMediaFile(rel, deps);
2210
- if (localAfter !== null) return {
2183
+ const localAfter = await exportQqMedia(rel, deps.mediaBaseDir, deps.cacheDir);
2184
+ if (localAfter !== void 0) return {
2211
2185
  ...downloaded.fileSize != null ? { file_size: downloaded.fileSize } : {},
2212
2186
  ...downloaded.fileName != null ? { file_name: downloaded.fileName } : {},
2213
2187
  file: localAfter
@@ -2217,7 +2191,7 @@ async function downloadPttFallback(msgId, peer, id, deps) {
2217
2191
  deps.logger?.warn({
2218
2192
  message_id: id,
2219
2193
  error: errorMessage(err)
2220
- }, "ob11: 语音原生下载失败,get_record 回退原始路径");
2194
+ }, "ob11: 语音原生下载失败,get_record 回退元数据");
2221
2195
  }
2222
2196
  return null;
2223
2197
  }
@@ -2251,15 +2225,12 @@ function createMediaActions(api) {
2251
2225
  ...ptt.fileSize != null ? { file_size: ptt.fileSize } : {},
2252
2226
  ...ptt.fileName != null ? { file_name: ptt.fileName } : {}
2253
2227
  });
2254
- const local = resolveLocalMediaFile(filePath, api);
2255
- if (local !== null) return {
2228
+ const local = await exportQqMedia(filePath, api.mediaBaseDir, api.cacheDir);
2229
+ if (local !== void 0) return {
2256
2230
  ...meta(),
2257
2231
  file: local
2258
2232
  };
2259
- return await downloadPttFallback(msgId, peer, id, api) ?? {
2260
- ...meta(),
2261
- file: filePath
2262
- };
2233
+ return await downloadPttFallback(msgId, peer, id, api) ?? meta();
2263
2234
  }
2264
2235
  }),
2265
2236
  defineOb11Action({
@@ -2420,7 +2391,7 @@ async function sendOb11Message(payload, deps) {
2420
2391
  let canonical;
2421
2392
  if (Array.isArray(payload.message)) canonical = segmentsToCanonical(parseOB11MessageSegments(payload.message));
2422
2393
  else canonical = cqMessageToCanonical(payload.message);
2423
- await protectElements(canonical);
2394
+ canonical = await prepareLocalElements(canonical, deps);
2424
2395
  const atUins = [];
2425
2396
  for (const el of canonical) if (el.type === "at" && el.target !== "all") atUins.push(el.target);
2426
2397
  let uinToUid;
@@ -2452,11 +2423,26 @@ async function sendOb11Message(payload, deps) {
2452
2423
  await prepared.cleanup();
2453
2424
  }
2454
2425
  }
2455
- async function protectElements(elements) {
2426
+ async function prepareLocalElements(elements, deps) {
2427
+ const roots = deps.getLocalMediaRoots?.();
2428
+ const prepared = [];
2456
2429
  for (const el of elements) {
2457
- if ("path" in el) await protectMediaPath(el.path);
2458
- if (el.type === "video" && el.thumbPath) await protectMediaPath(el.thumbPath);
2430
+ if (!("path" in el)) {
2431
+ prepared.push(el);
2432
+ continue;
2433
+ }
2434
+ const path = await resolveLocalMedia(el.path, roots);
2435
+ if (el.type === "video" && el.thumbPath) prepared.push({
2436
+ ...el,
2437
+ path,
2438
+ thumbPath: await resolveLocalMedia(el.thumbPath, roots)
2439
+ });
2440
+ else prepared.push({
2441
+ ...el,
2442
+ path
2443
+ });
2459
2444
  }
2445
+ return prepared;
2460
2446
  }
2461
2447
  /** CQ 特殊字符转义(auto_escape,&、[、]、, 前置 &amp;)。 */
2462
2448
  function escapeText(text) {
@@ -2528,10 +2514,14 @@ const setQQAvatarSchema = z.object({
2528
2514
  /** 本地路径(URL 需先下载,由装配方 cacheDir 支持)。 */
2529
2515
  file: z.string() });
2530
2516
  /** URL 头像下载到缓存目录(cacheDir 缺省抛错)。 */
2531
- async function downloadAvatarToCache(url, cacheDir) {
2517
+ async function downloadAvatarToCache(url, api) {
2518
+ const { cacheDir } = api;
2532
2519
  if (cacheDir === void 0 || cacheDir === "") throw kernelError("set_qq_avatar 处理 URL 需要缓存目录(装配方未注入)", "INVALID_STATE");
2533
2520
  return await cacheMediaFile(cacheDir, inferExtension(null, url), async (path) => {
2534
- await downloadBufferToFile(url, path, void 0, "头像下载失败");
2521
+ await downloadProtocolMedia(url, path, {
2522
+ outboundPolicy: api.getMediaOutboundPolicy?.(),
2523
+ errorLabel: "头像下载失败"
2524
+ });
2535
2525
  });
2536
2526
  }
2537
2527
  /**
@@ -2604,10 +2594,8 @@ function createSystemAccountActions(api) {
2604
2594
  name: "set_qq_avatar",
2605
2595
  schema: setQQAvatarSchema,
2606
2596
  handle: async (payload) => {
2607
- let filePath = payload.file;
2608
- if (URL_PREFIX.test(filePath)) filePath = await downloadAvatarToCache(filePath, api.cacheDir);
2609
- if (!existsSync(filePath)) throw kernelError(`头像文件不存在: ${filePath}`, "NOT_FOUND");
2610
- await api.profileApi.setHeader(await protectMediaPath(filePath));
2597
+ const filePath = URL_PREFIX.test(payload.file) ? await downloadAvatarToCache(payload.file, api) : await resolveLocalMedia(payload.file, api.getLocalMediaRoots?.());
2598
+ await api.profileApi.setHeader(filePath);
2611
2599
  return null;
2612
2600
  }
2613
2601
  })
@@ -2617,8 +2605,7 @@ function createSystemAccountActions(api) {
2617
2605
  /**
2618
2606
  * 文件收发域动作
2619
2607
  *
2620
- * - download_file:url → fetch 下载 → 存 cacheDir(缺省抛错)→ 返回
2621
- * { file }。文件名:download-<timestamp>-<basename>(headers 等扩展字段忽略)
2608
+ * - download_file:按媒体出站策略下载到 cacheDir 的独立缓存文件,返回 { file }。
2622
2609
  * - upload_group_file / upload_private_file——**闪传通道**
2623
2610
  *
2624
2611
  * ⚠️ 语义降级(探测依据见 kernel design §15):
@@ -2634,8 +2621,6 @@ function createSystemAccountActions(api) {
2634
2621
  * 输入只接受本地路径与 `file://` URI:远程 `http(s)://` / `base64://` 需要下载缓存与媒体
2635
2622
  * 依赖,当前未接(明确报错,不静默失败)。
2636
2623
  */
2637
- /** 路径分隔符(取文件名用)。 */
2638
- const PATH_SEPARATORS = /[\\/]/;
2639
2624
  const downloadFileSchema = z.object({
2640
2625
  url: z.string(),
2641
2626
  thread_count: z.number().optional(),
@@ -2653,18 +2638,6 @@ const uploadPrivateFileSchema = z.object({
2653
2638
  file: z.string().min(1),
2654
2639
  name: z.string().optional()
2655
2640
  });
2656
- /** 本地路径 / file:// 展开;远程 URI 明确拒绝(未接下载缓存)。 */
2657
- function resolveLocalFile(file) {
2658
- if (file.startsWith("http://") || file.startsWith("https://") || file.startsWith("base64://")) throw kernelError("upload_group_file/upload_private_file 目前只支持本地路径与 file:// URI(远程 URI 需要下载缓存,未接入)", "INVALID_PARAM");
2659
- if (file.startsWith("file://")) return fileUriToPath(file);
2660
- return file;
2661
- }
2662
- /** 取路径末段作为缺省文件集名(卡片标题)。 */
2663
- function basename$1(path) {
2664
- const parts = path.split(PATH_SEPARATORS);
2665
- const last = parts[parts.length - 1] ?? "";
2666
- return last === "" ? "文件" : last;
2667
- }
2668
2641
  /** 文件收发域动作工厂(download_file / upload_group_file / upload_private_file)。 */
2669
2642
  function createSystemFileActions(api) {
2670
2643
  return [
@@ -2674,10 +2647,11 @@ function createSystemFileActions(api) {
2674
2647
  handle: async (payload) => {
2675
2648
  const { cacheDir } = api;
2676
2649
  if (cacheDir === void 0 || cacheDir === "") throw kernelError("download_file 未配置缓存目录(装配方未注入)", "INVALID_STATE");
2677
- const init = {};
2678
- if (payload.headers !== void 0) init.headers = payload.headers;
2679
2650
  return { file: await cacheMediaFile(cacheDir, inferExtension(null, payload.url), async (path) => {
2680
- await downloadBufferToFile(payload.url, path, init);
2651
+ await downloadProtocolMedia(payload.url, path, {
2652
+ outboundPolicy: api.getMediaOutboundPolicy?.(),
2653
+ headers: payload.headers
2654
+ });
2681
2655
  }, "reference") };
2682
2656
  }
2683
2657
  }),
@@ -2685,21 +2659,21 @@ function createSystemFileActions(api) {
2685
2659
  name: "upload_group_file",
2686
2660
  schema: uploadGroupFileSchema,
2687
2661
  handle: async (payload) => {
2688
- const path = await protectMediaPath(resolveLocalFile(payload.file));
2662
+ const path = await resolveLocalMedia(payload.file, api.getLocalMediaRoots?.());
2689
2663
  const peer = {
2690
2664
  chatType: ChatType.GROUP,
2691
2665
  peerUid: String(payload.group_id)
2692
2666
  };
2693
- return { file_id: (await api.flashTransferApi.sendFile(peer, [path], { name: payload.name ?? basename$1(path) })).fileSetId };
2667
+ return { file_id: (await api.flashTransferApi.sendFile(peer, [path], { name: payload.name ?? basename(path) })).fileSetId };
2694
2668
  }
2695
2669
  }),
2696
2670
  defineOb11Action({
2697
2671
  name: "upload_private_file",
2698
2672
  schema: uploadPrivateFileSchema,
2699
2673
  handle: async (payload) => {
2700
- const path = await protectMediaPath(resolveLocalFile(payload.file));
2674
+ const path = await resolveLocalMedia(payload.file, api.getLocalMediaRoots?.());
2701
2675
  const peer = await resolveTargetPeer({ user_id: payload.user_id }, api, "upload_private_file 需要 user_id");
2702
- return { file_id: (await api.flashTransferApi.sendFile(peer, [path], { name: payload.name ?? basename$1(path) })).fileSetId };
2676
+ return { file_id: (await api.flashTransferApi.sendFile(peer, [path], { name: payload.name ?? basename(path) })).fileSetId };
2703
2677
  }
2704
2678
  })
2705
2679
  ];
@@ -2992,6 +2966,8 @@ function openOutboundWithRetry(transport, opts) {
2992
2966
  */
2993
2967
  var OneBotApi = class {
2994
2968
  mediaCache;
2969
+ getLocalMediaRoots;
2970
+ getMediaOutboundPolicy;
2995
2971
  /** kernel 消息 API(send_msg 等消息类动作用)。 */
2996
2972
  msgApi;
2997
2973
  /** kernel 群 API。 */
@@ -3034,10 +3010,16 @@ var OneBotApi = class {
3034
3010
  restart;
3035
3011
  /** 降级分支可观测出口(缺省静默)。 */
3036
3012
  logger;
3037
- constructor(opts) {
3013
+ constructor(opts, getMediaOutboundPolicy, getLocalMediaRoots) {
3014
+ this.getMediaOutboundPolicy = getMediaOutboundPolicy;
3015
+ this.getLocalMediaRoots = bindLocalMediaRoots(opts.localMediaBaseDir, getLocalMediaRoots);
3038
3016
  this.mediaCache = new MediaCache({
3039
3017
  root: opts.system?.cacheDir,
3040
- logger: opts.logger
3018
+ logger: opts.logger,
3019
+ owner: {
3020
+ protocol: "onebot11",
3021
+ account: opts.self.uin
3022
+ }
3041
3023
  });
3042
3024
  this.msgApi = opts.msgApi;
3043
3025
  this.groupApi = opts.groupApi;
@@ -3882,7 +3864,7 @@ var NapukettoOneBot11Adapter = class extends BaseProtocolAdapter {
3882
3864
  });
3883
3865
  this.selfUin = opts.self.uin;
3884
3866
  this.logger = opts.logger;
3885
- this.oneBotApi = new OneBotApi(opts);
3867
+ this.oneBotApi = new OneBotApi(opts, () => config.get?.()?.media?.outboundPolicy, () => config.get?.()?.media?.localMediaRoots);
3886
3868
  this.pipeline = new Ob11EventPipeline({
3887
3869
  selfUin: this.selfUin,
3888
3870
  api: this.oneBotApi,
@@ -2,5 +2,5 @@
2
2
  * Satori 协议适配器
3
3
  * 公共面:类型 + 动作注册表 + 配置 schema + 传输装配 + 适配器。
4
4
  */
5
- import { A as Message, B as SatoriActionDeps, C as Emoji, D as GuildRole, E as GuildMember, F as Order, G as SatoriToCanonicalDeps, H as SatoriActionError, I as HTTP_STATUS, J as renderElements, K as SatoriElement, L as satoriHttpStatusMap, M as BidiList, N as Direction, O as Login, P as List, R as SatoriConfig, S as ChannelType, T as Guild, U as SatoriApi, V as createSatoriActionRegistry, W as SatoriApiOptions, _ as MetaBody, a as parseContentToCanonical, b as Signal, c as canonicalToSatoriElements, d as NapukettoSatoriAdapter, f as SatoriAdapterOptions, g as IdentifyBody, h as Event, i as toEventSignal, j as User, k as LoginStatus, l as SatoriEventContent, m as Button, n as SatoriTransportSet, o as satoriToCanonicalElements, p as Argv, q as parseElements, r as assembleSatoriTransports, s as CanonicalToSatoriDeps, t as AssembleSatoriTransportsOptions, u as SatoriEventDeps, v as Opcode, w as Friend, x as Channel, y as ReadyBody, z as satoriConfigSchema } from "../index-D93z0TYf.mjs";
5
+ import { A as Message, B as SatoriActionDeps, C as Emoji, D as GuildRole, E as GuildMember, F as Order, G as SatoriToCanonicalDeps, H as SatoriActionError, I as HTTP_STATUS, J as renderElements, K as SatoriElement, L as satoriHttpStatusMap, M as BidiList, N as Direction, O as Login, P as List, R as SatoriConfig, S as ChannelType, T as Guild, U as SatoriApi, V as createSatoriActionRegistry, W as SatoriApiOptions, _ as MetaBody, a as parseContentToCanonical, b as Signal, c as canonicalToSatoriElements, d as NapukettoSatoriAdapter, f as SatoriAdapterOptions, g as IdentifyBody, h as Event, i as toEventSignal, j as User, k as LoginStatus, l as SatoriEventContent, m as Button, n as SatoriTransportSet, o as satoriToCanonicalElements, p as Argv, q as parseElements, r as assembleSatoriTransports, s as CanonicalToSatoriDeps, t as AssembleSatoriTransportsOptions, u as SatoriEventDeps, v as Opcode, w as Friend, x as Channel, y as ReadyBody, z as satoriConfigSchema } from "../index-DAoLsewN.mjs";
6
6
  export { type Argv, type AssembleSatoriTransportsOptions, type BidiList, type Button, type CanonicalToSatoriDeps, type Channel, type ChannelType, type Direction, type Emoji, type Event, type Friend, type Guild, type GuildMember, type GuildRole, HTTP_STATUS, type IdentifyBody, type List, type Login, type LoginStatus, type Message, type MetaBody, NapukettoSatoriAdapter, type Opcode, type Order, type ReadyBody, type SatoriActionDeps, SatoriActionError, type SatoriAdapterOptions, SatoriApi, type SatoriApiOptions, type SatoriConfig, type SatoriElement, type SatoriEventContent, type SatoriEventDeps, type SatoriToCanonicalDeps, type SatoriTransportSet, type Signal, type User, assembleSatoriTransports, canonicalToSatoriElements, createSatoriActionRegistry, parseContentToCanonical, parseElements, renderElements, satoriConfigSchema, satoriHttpStatusMap, satoriToCanonicalElements, toEventSignal };
@@ -1 +1 @@
1
- export { f as HTTP_STATUS, t as NapukettoSatoriAdapter, c as SatoriActionError, i as SatoriApi, n as assembleSatoriTransports, d as canonicalToSatoriElements, a as createSatoriActionRegistry, o as parseContentToCanonical, l as parseElements, u as renderElements, m as satoriConfigSchema, p as satoriHttpStatusMap, s as satoriToCanonicalElements, r as toEventSignal } from "../satori-VkOP24Vc.mjs";
1
+ export { f as HTTP_STATUS, t as NapukettoSatoriAdapter, c as SatoriActionError, i as SatoriApi, n as assembleSatoriTransports, d as canonicalToSatoriElements, a as createSatoriActionRegistry, o as parseContentToCanonical, l as parseElements, u as renderElements, m as satoriConfigSchema, p as satoriHttpStatusMap, s as satoriToCanonicalElements, r as toEventSignal } from "../satori-Cna8fauQ.mjs";
@@ -1,12 +1,12 @@
1
1
  import { a as validateServerTokens, d as tokenEquals, f as ActionRegistry, l as createTokenAuthorize, o as BaseProtocolAdapter, p as runAction, r as createServerSchema, s as resolveProtocolConfig } from "./framework-CA3087JP.mjs";
2
- import { a as logEventFailure, c as downloadBufferToFile, f as MediaCache, h as withMediaScope, l as ensureSilk, m as protectMediaPath, p as cacheMediaFile, t as collectGrayTipUids } from "./gray-tip-BL1rhwZK.mjs";
2
+ import { _ as cacheMediaFile, a as logEventFailure, c as protocolMediaSchema, g as MediaCache, h as resolveLocalMedia, l as downloadProtocolMedia, m as exportQqMedia, p as bindLocalMediaRoots, t as collectGrayTipUids, u as ensureSilk, v as leaseInternalMedia, y as withMediaScope } from "./gray-tip-D0SfHr7q.mjs";
3
3
  import { c as MS_TO_SEC, h as toUinString, i as toUnixSeconds, r as subscribeRawMessages } from "./raw-message-DU8YOhLV.mjs";
4
- import { ChatType, GrayTipSubType, NTGroupRequestOperateTypes, TipGroupElementType, isRecord, kernelError, toCanonicalElements } from "@napuketto/kernel";
4
+ import { ChatType, GrayTipSubType, NTGroupRequestOperateTypes, TipGroupElementType, errorMessage, isRecord, kernelError, toCanonicalElements } from "@napuketto/kernel";
5
5
  import { HttpServer, WsServer, isWsOpen, sendWsText } from "@napuketto/network";
6
6
  import { z } from "zod";
7
7
  import { rm, rmdir } from "node:fs/promises";
8
8
  import { tmpdir } from "node:os";
9
- import { dirname, join } from "node:path";
9
+ import { basename, dirname, join } from "node:path";
10
10
  import { inferExtension, transcodeVideo } from "@napuketto/media";
11
11
  // src/satori/helper/config.ts
12
12
  /**
@@ -22,6 +22,7 @@ const httpServerSchema = createServerSchema(DEFAULT_HTTP_PORT);
22
22
  /** WS 事件服务实例(/v1/events 信令,第三方 SDK 连入)。 */
23
23
  const wsServerSchema = createServerSchema(DEFAULT_WS_PORT);
24
24
  const satoriConfigSchema = z.object({
25
+ media: protocolMediaSchema.optional(),
25
26
  /** 鉴权 token(全局默认,实例未指定时继承)。 */
26
27
  token: z.string().optional(),
27
28
  /** 媒体资源(img/audio/video/file)下载缓存目录。 */
@@ -560,11 +561,22 @@ function renderElement(el) {
560
561
  * 收方向 ID 空间:canonical at.target 是 uid,Satori 规范是 uin——经
561
562
  * uidToUin 批量转换(依赖注入,与 OB11 的 ReceiveTranslateContext 同思路)。
562
563
  */
563
- /** RawMessage → Satori Message(资源提升:message 不嵌套 user/member/channel)。 */
564
- async function toSatoriMessage(raw, deps) {
564
+ async function renderMessageContent(raw, deps) {
565
565
  const elementDeps = {};
566
566
  if (deps.uidToUin !== void 0) elementDeps.uidToUin = deps.uidToUin;
567
- const content = renderElements(await canonicalToSatoriElements(toCanonicalElements(raw), elementDeps));
567
+ const elements = await canonicalToSatoriElements(toCanonicalElements(raw), elementDeps);
568
+ if (deps.publishLocalAsset !== void 0) for (const element of elements) {
569
+ const attrs = element.attrs;
570
+ const source = attrs?.["src"];
571
+ if (!attrs || !source) continue;
572
+ const reference = await deps.publishLocalAsset(source);
573
+ if (reference !== void 0) attrs["src"] = reference;
574
+ }
575
+ return renderElements(elements);
576
+ }
577
+ /** RawMessage → Satori Message(资源提升:message 不嵌套 user/member/channel)。 */
578
+ async function toSatoriMessage(raw, deps) {
579
+ const content = await renderMessageContent(raw, deps);
568
580
  const isGroup = raw.chatType === ChatType.GROUP;
569
581
  const peerUin = String(raw.peerUin ?? "");
570
582
  const senderUin = String(raw.senderUin ?? "");
@@ -851,23 +863,6 @@ function createLoginActions(deps) {
851
863
  })];
852
864
  }
853
865
  // src/satori/helper/element/asset.ts
854
- /**
855
- * Satori 发方向资源处理(从 element-convert.ts 拆分,FTA 优化)
856
- *
857
- * - resolveAsset:internal: 路径 / http(s) 下载 / 本地路径原样
858
- * - ensureSilk 已上移到 adapter core(core/media.ts,onebot11/satori 共用)
859
- * - 下载落盘统一走 shared/media.ts 的 downloadBufferToFile(异步 I/O 单一入口)
860
- */
861
- /** internal:{platform}/{user.id}/{path} → 本地路径(取 _tmp 之后的路径,回落 cacheDir)。 */
862
- function resolveInternalPath(src) {
863
- const pathPart = src.slice(9);
864
- const slash1 = pathPart.indexOf("/");
865
- const slash2 = slash1 === -1 ? -1 : pathPart.indexOf("/", slash1 + 1);
866
- if (slash2 === -1) return pathPart;
867
- const rest = pathPart.slice(slash2 + 1);
868
- const tmpIdx = rest.indexOf("_tmp/");
869
- return tmpIdx === -1 ? rest : rest.slice(tmpIdx + 5);
870
- }
871
866
  /** http(s) URL 前缀。 */
872
867
  const HTTP_URL_RE = /^https?:\/\//i;
873
868
  const UNSAFE_NAME_RE = /[^a-zA-Z0-9._-]/g;
@@ -877,29 +872,26 @@ function assetFileName(src) {
877
872
  const name = (src.split("/").pop() ?? "").replace(UNSAFE_NAME_RE, "_");
878
873
  return name === "" || name === "." || name === ".." ? void 0 : name;
879
874
  }
880
- /**
881
- * 解析资源 src:
882
- * - internal:{platform}/{user.id}/{path} → 本地路径(第一版仅支持 _tmp 保留路径)
883
- * - http(s):// → 下载到 cacheDir
884
- * - 其他 → 视为本地路径原样返回
885
- */
886
- async function resolveAsset(src, cacheDir) {
887
- if (src.startsWith("internal:")) return await protectMediaPath(resolveInternalPath(src));
888
- if (HTTP_URL_RE.test(src)) return downloadAsset(src, cacheDir);
889
- return await protectMediaPath(src);
890
- }
891
- /** 下载 URL 资源到缓存目录(返回本地路径)。 */
892
- async function downloadAsset(url, cacheDir) {
893
- return await cacheMediaFile(cacheDir, inferExtension(null, url), async (path) => {
894
- await downloadBufferToFile(url, path, void 0, "下载资源失败");
875
+ async function resolveAsset(src, cacheDir, opts = {}) {
876
+ if (src.startsWith("internal:")) {
877
+ const [platform, account, namespace, entry, file, extra] = src.slice(9).split("/");
878
+ if (platform !== "qq" || account === void 0 || account !== opts.account || namespace !== "_tmp" || entry === void 0 || file === void 0 || extra !== void 0) throw kernelError("内部媒体引用不属于当前平台及账号", "INVALID_PARAM");
879
+ return await leaseInternalMedia(cacheDir, account, entry, file);
880
+ }
881
+ if (HTTP_URL_RE.test(src)) return await cacheMediaFile(cacheDir, inferExtension(null, src), async (path) => {
882
+ await downloadProtocolMedia(src, path, {
883
+ outboundPolicy: opts.outboundPolicy,
884
+ errorLabel: "下载资源失败"
885
+ });
895
886
  });
887
+ return await resolveLocalMedia(src, opts.localMediaRoots);
896
888
  }
897
889
  // src/satori/helper/element/media-convert.ts
898
890
  /** 解析元素媒体 src(空 → null 忽略),返回本地路径。 */
899
891
  async function resolveMediaSrc(el, deps) {
900
892
  const src = el.attrs?.["src"] ?? "";
901
893
  if (src === "") return null;
902
- return resolveAsset(src, deps.cacheDir);
894
+ return resolveAsset(src, deps.cacheDir, deps);
903
895
  }
904
896
  /** Satori img → canonical image。 */
905
897
  async function imgToCanonical(el, deps) {
@@ -1129,7 +1121,8 @@ function createMessageActions(deps) {
1129
1121
  deps.setChannelType(channelId, peer.chatType === 2);
1130
1122
  return toSatoriMessage(first, {
1131
1123
  selfUin: deps.selfUin,
1132
- uidToUin: (uids) => deps.uidToUin(uids)
1124
+ uidToUin: (uids) => deps.uidToUin(uids),
1125
+ publishLocalAsset: deps.publishLocalAsset
1133
1126
  });
1134
1127
  }
1135
1128
  }),
@@ -1323,6 +1316,7 @@ const notImplementedSchema = z.object({}).passthrough();
1323
1316
  /** Satori 动作统一依赖聚合。 */
1324
1317
  var SatoriApi = class {
1325
1318
  mediaCache;
1319
+ getLocalMediaRoots;
1326
1320
  msgApi;
1327
1321
  groupApi;
1328
1322
  groupNotifyApi;
@@ -1331,13 +1325,17 @@ var SatoriApi = class {
1331
1325
  self;
1332
1326
  selfUin;
1333
1327
  cacheDir;
1328
+ publishLocalAsset;
1334
1329
  groupCache;
1335
1330
  /**
1336
1331
  * 频道类型缓存:channel_id → isGroup(群聊频道 id 与私聊 uin 无法从数字
1337
1332
  * 规则区分,需从事件/查询回填——QQ 平台群号与用户 uin 同为数字)。
1338
1333
  */
1339
1334
  channelTypeCache = /* @__PURE__ */ new Map();
1340
- constructor(opts) {
1335
+ getMediaOutboundPolicy;
1336
+ constructor(opts, getMediaOutboundPolicy, getLocalMediaRoots) {
1337
+ this.getMediaOutboundPolicy = getMediaOutboundPolicy;
1338
+ this.getLocalMediaRoots = bindLocalMediaRoots(opts.localMediaBaseDir, getLocalMediaRoots);
1341
1339
  this.msgApi = opts.msgApi;
1342
1340
  this.groupApi = opts.groupApi;
1343
1341
  this.groupNotifyApi = opts.groupNotifyApi;
@@ -1348,8 +1346,23 @@ var SatoriApi = class {
1348
1346
  this.cacheDir = opts.cacheDir ?? join(tmpdir(), "napuketto-satori-cache");
1349
1347
  this.mediaCache = new MediaCache({
1350
1348
  root: this.cacheDir,
1351
- logger: opts.logger
1349
+ logger: opts.logger,
1350
+ owner: {
1351
+ protocol: "satori",
1352
+ account: opts.self.uin
1353
+ }
1352
1354
  });
1355
+ const mediaBaseDir = opts.mediaBaseDir;
1356
+ if (mediaBaseDir !== void 0) this.publishLocalAsset = async (source) => {
1357
+ try {
1358
+ const file = await exportQqMedia(source, mediaBaseDir, this.cacheDir);
1359
+ if (file === void 0) return void 0;
1360
+ return `internal:qq/${this.selfUin}/_tmp/${basename(dirname(file))}/${basename(file)}`;
1361
+ } catch (err) {
1362
+ opts.logger?.warn({ error: errorMessage(err) }, "satori: 媒体导出失败");
1363
+ return;
1364
+ }
1365
+ };
1353
1366
  this.groupCache = opts.groupCache;
1354
1367
  }
1355
1368
  /** 记录频道类型(消息事件翻译时回填:chatType GROUP → true)。 */
@@ -1396,7 +1409,10 @@ var SatoriApi = class {
1396
1409
  toCanonicalDeps() {
1397
1410
  return {
1398
1411
  uinToUid: (uins) => this.groupApi.uinToUid(uins),
1399
- cacheDir: this.cacheDir
1412
+ cacheDir: this.cacheDir,
1413
+ outboundPolicy: this.getMediaOutboundPolicy?.(),
1414
+ localMediaRoots: this.getLocalMediaRoots?.(),
1415
+ account: this.selfUin
1400
1416
  };
1401
1417
  }
1402
1418
  };
@@ -1773,18 +1789,19 @@ var NapukettoSatoriAdapter = class extends BaseProtocolAdapter {
1773
1789
  unsubscribe = null;
1774
1790
  eventSn = 0;
1775
1791
  constructor(opts) {
1792
+ const { broadcaster, msgChannel } = opts;
1776
1793
  const config = resolveProtocolConfig(opts.config, satoriConfigSchema, satoriConfigSchema.parse({}));
1777
1794
  super({
1778
1795
  config,
1779
- broadcaster: opts.broadcaster,
1796
+ broadcaster,
1780
1797
  hooks: {
1781
1798
  onStart: (config) => this.startTransports(config),
1782
1799
  onStop: () => this.stopAll(),
1783
1800
  onReload: (config) => this.reloadTransports(config)
1784
1801
  }
1785
1802
  });
1786
- this.msgChannel = opts.msgChannel;
1787
- this.api = new SatoriApi(opts);
1803
+ this.msgChannel = msgChannel;
1804
+ this.api = new SatoriApi(opts, () => config.get?.()?.media?.outboundPolicy, () => config.get?.()?.media?.localMediaRoots);
1788
1805
  this.logger = opts.logger;
1789
1806
  this.registry = createSatoriActionRegistry({ api: this.api });
1790
1807
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@napuketto/adapter",
4
- "version": "0.19.0",
4
+ "version": "0.21.0",
5
5
  "type": "module",
6
6
  "description": "Protocol adapters (OneBot11 / Satori / KuroBot / Milky) for NapukettoQQ",
7
7
  "keywords": [
@@ -84,7 +84,7 @@
84
84
  },
85
85
  "dependencies": {
86
86
  "@napuketto/kernel": "^0.16.4",
87
- "@napuketto/media": "^0.2.3",
87
+ "@napuketto/media": "^0.3.0",
88
88
  "@napuketto/network": "^0.5.0",
89
89
  "zod": "^4.6.7"
90
90
  },