@napuketto/adapter 0.18.22 → 0.20.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.
@@ -15,5 +15,5 @@
15
15
  * 配置兼容:`ProtocolConfig` 是 `ConfigBase` 的历史别名(loader 动态 import
16
16
  * 仍按该名字构造),保留导出避免运行期断链。
17
17
  */
18
- import { _ as ErrorCodeMap, a as ProtocolConfig, c as ProtocolHooks, d as TokenAuthOptions, f as createTokenAuthorize, g as ActionOutcome, h as ActionKernelSpec, i as ConfigSchema, l as resolveProtocolConfig, m as ActionRegistry, n as ConfigFormat, o as createServerSchema, p as matchTokenCredential, r as ConfigOptions, s as BaseProtocolAdapter, t as ConfigBase, u as BEARER_PREFIX, v as runAction } from "../index-BZfGz6FA.mjs";
18
+ import { _ as ErrorCodeMap, a as ProtocolConfig, c as ProtocolHooks, d as TokenAuthOptions, f as createTokenAuthorize, g as ActionOutcome, h as ActionKernelSpec, i as ConfigSchema, l as resolveProtocolConfig, m as ActionRegistry, n as ConfigFormat, o as createServerSchema, p as matchTokenCredential, r as ConfigOptions, s as BaseProtocolAdapter, t as ConfigBase, u as BEARER_PREFIX, v as runAction } from "../index-BO1TgLTT.mjs";
19
19
  export { type ActionKernelSpec, type ActionOutcome, ActionRegistry, BEARER_PREFIX, BaseProtocolAdapter, ConfigBase, type ConfigFormat, type ConfigOptions, type ConfigSchema, type ErrorCodeMap, ProtocolConfig, type ProtocolHooks, type TokenAuthOptions, createServerSchema, createTokenAuthorize, matchTokenCredential, resolveProtocolConfig, runAction };
@@ -1 +1 @@
1
- export { u as ActionRegistry, o as BEARER_PREFIX, i as BaseProtocolAdapter, t as ConfigBase, n as ProtocolConfig, r as createServerSchema, s as createTokenAuthorize, c as matchTokenCredential, a as resolveProtocolConfig, d as runAction } from "../framework-BbtmlUXJ.mjs";
1
+ export { f as ActionRegistry, c as BEARER_PREFIX, o as BaseProtocolAdapter, t as ConfigBase, n as ProtocolConfig, r as createServerSchema, l as createTokenAuthorize, u as matchTokenCredential, s as resolveProtocolConfig, p as runAction } from "../framework-CA3087JP.mjs";
@@ -1,6 +1,7 @@
1
1
  import { ConfigBase, ConfigBase as ConfigBase$1, ConfigBase as ProtocolConfig, isKernelError, isRecord } from "@napuketto/kernel";
2
2
  import { createHash, timingSafeEqual } from "node:crypto";
3
3
  import { EventBroadcaster } from "@napuketto/network";
4
+ import { isIP } from "node:net";
4
5
  import { z } from "zod";
5
6
  // src/framework/action-kernel.ts
6
7
  /**
@@ -107,8 +108,8 @@ function matchTokenCredential(ctx, token, opts) {
107
108
  if (opts?.allowRawHeader === true && tokenEquals(auth, token)) return true;
108
109
  if (opts?.allowQueryToken === true) try {
109
110
  return tokenEquals(new URL(ctx.url, QUERY_BASE).searchParams.get("access_token"), token);
110
- } catch (err) {
111
- opts.onQueryParseError?.(ctx.url, err);
111
+ } catch {
112
+ opts.onQueryParseError?.();
112
113
  return false;
113
114
  }
114
115
  return false;
@@ -248,6 +249,37 @@ var BaseProtocolAdapter = class {
248
249
  * HTTP 反向服务器 / WS 事件服务器的实例级 schema 结构两协议一致,仅默认
249
250
  * 端口与各协议扩展字段不同——单一工厂按默认端口生成,各协议按需调用。
250
251
  */
252
+ const PLACEHOLDER_TOKENS = /* @__PURE__ */ new Set([
253
+ "change-me",
254
+ "changeme",
255
+ "replace_with_random_token"
256
+ ]);
257
+ const MAPPED_IPV4_LOOPBACK = /^\[::ffff:7f[\da-f]{2}:[\da-f]{1,4}\]$/;
258
+ /** 只信任可在校验时确认的回环 IP。主机名的最终绑定由运行环境解析。 */
259
+ function isLoopbackHost(host) {
260
+ const family = isIP(host);
261
+ if (family === 4) return host.startsWith("127.");
262
+ if (family !== 6 || host.includes("%")) return false;
263
+ const { hostname } = new URL(`http://[${host}]`);
264
+ return hostname === "[::1]" || MAPPED_IPV4_LOOPBACK.test(hostname);
265
+ }
266
+ function validateListenerToken(host, token, ctx, path) {
267
+ if (isLoopbackHost(host)) return;
268
+ const value = token?.trim().toLowerCase();
269
+ if (!value || PLACEHOLDER_TOKENS.has(value)) ctx.addIssue({
270
+ code: "custom",
271
+ path,
272
+ message: "非回环监听要求有效 token。请设置随机 token(实例可继承协议级 token),或仅供可信本机使用时改绑 127.0.0.1 / ::1。"
273
+ });
274
+ }
275
+ /** 对启用的实例使用与装配相同的 token 覆盖规则。 */
276
+ function validateServerTokens(config, ctx) {
277
+ for (const key of ["httpServers", "wsServers"]) for (const [index, item] of config[key].entries()) if (item.enabled) validateListenerToken(item.host, item.token ?? config.token, ctx, [
278
+ key,
279
+ index,
280
+ "token"
281
+ ]);
282
+ }
251
283
  /**
252
284
  * 传输实例 schema(enabled/host/port/token 骨架;HTTP 反向服务器与 WS 事件
253
285
  * 服务器共用同一结构,OB11 / Satori 仅默认端口不同)。
@@ -261,4 +293,4 @@ function createServerSchema(defaultPort) {
261
293
  token: z.string().optional()
262
294
  });
263
295
  }
264
- export { resolveProtocolConfig as a, matchTokenCredential as c, runAction as d, BaseProtocolAdapter as i, tokenEquals as l, ProtocolConfig as n, BEARER_PREFIX as o, createServerSchema as r, createTokenAuthorize as s, ConfigBase$1 as t, ActionRegistry as u };
296
+ export { validateServerTokens as a, BEARER_PREFIX as c, tokenEquals as d, ActionRegistry as f, validateListenerToken as i, createTokenAuthorize as l, ProtocolConfig as n, BaseProtocolAdapter as o, runAction as p, createServerSchema as r, resolveProtocolConfig as s, ConfigBase$1 as t, matchTokenCredential as u };
@@ -1,10 +1,11 @@
1
1
  import { errorMessage, kernelError } from "@napuketto/kernel";
2
2
  import { randomUUID } from "node:crypto";
3
+ import { z } from "zod";
3
4
  import { AsyncLocalStorage } from "node:async_hooks";
4
5
  import { copyFile, lstat, mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rm, rmdir, stat, unlink, writeFile } from "node:fs/promises";
5
6
  import { tmpdir } from "node:os";
6
7
  import { basename, dirname, extname, join, resolve } from "node:path";
7
- import { downloadUrl, encodePcmToSilk, extractVideoFrame, getVideoInfo } from "@napuketto/media";
8
+ import { downloadPublicUrl, downloadUrl, encodePcmToSilk, extractVideoFrame, getVideoInfo } from "@napuketto/media";
8
9
  import { fileURLToPath } from "node:url";
9
10
  // src/internal/infra/media-cache.ts
10
11
  const CACHE_DIR = ".napuketto-media-v1";
@@ -415,32 +416,17 @@ function fileUriToPath(uri) {
415
416
  return FILE_URI_PREFIX_RE.test(uri) ? uri.replace(FILE_URI_PREFIX_RE, "") : uri;
416
417
  }
417
418
  }
418
- /**
419
- * 远程 URL → 本地文件(异步 mkdir + 流式落盘,全仓协议层唯一落盘入口)。
420
- *
421
- * - 走 `@napuketto/media` 的 `downloadUrl`:超时、大小上限、流式落盘、协议白名单
422
- * 与「逐跳复检」的重定向策略都在那里统一(此前这里是裸 `fetch` + `arrayBuffer()`,
423
- * 无超时无上限:恶意超大响应可直接打爆 Node 堆);
424
- * - 父目录不存在时自动创建;
425
- * - 失败统一包成 KernelError SEND_FAILED(`label` 供调用方定制前缀,如「头像下载失败」);
426
- * - 返回落盘路径(便于调用方直接回传)。
427
- */
428
- async function downloadBufferToFile(url, filePath, init, label = "下载失败") {
419
+ /** 协议动作默认走公网下载,兼容模式由受信任的装配方显式启用。 */
420
+ function mediaDownloader(policy) {
421
+ return policy === "compat" ? downloadUrl : downloadPublicUrl;
422
+ }
423
+ /** 转换有上传语义的下载失败,保留既有 SEND_FAILED 信封。 */
424
+ async function downloadProtocolMedia(url, filePath, options = {}) {
429
425
  try {
430
- const headers = init?.headers === void 0 ? void 0 : normalizeHeaders(init.headers);
431
- await downloadUrl(url, filePath, headers === void 0 ? {} : { headers });
426
+ await mediaDownloader(options.outboundPolicy)(url, filePath, { headers: options.headers });
432
427
  } catch (err) {
433
- throw kernelError(`${label}: ${errorMessage(err)}`, "SEND_FAILED", { cause: err });
428
+ throw kernelError(`${options.errorLabel ?? "下载失败"}: ${errorMessage(err)}`, "SEND_FAILED", { cause: err });
434
429
  }
435
- return filePath;
436
- }
437
- /** RequestInit.headers(Headers / 元组数组 / 普通对象)→ 普通字符串对象。 */
438
- function normalizeHeaders(headers) {
439
- const out = {};
440
- new Headers(headers).forEach((value, key) => {
441
- out[key] = value;
442
- });
443
- return out;
444
430
  }
445
431
  /** 读文件头 8 字节(判断 silk 魔数)。 */
446
432
  async function readFileHead(path) {
@@ -537,6 +523,8 @@ async function prepareVideoElements(elements) {
537
523
  throw err;
538
524
  }
539
525
  }
526
+ // src/internal/infra/media-config.ts
527
+ const protocolMediaSchema = z.object({ outboundPolicy: z.enum(["public-only", "compat"]).optional() });
540
528
  // src/internal/infra/log.ts
541
529
  /**
542
530
  * raw 日志截断与最小 logger 面(协议 adapter 校准日志共用,自
@@ -614,4 +602,4 @@ function firstUntranslatedGrayTip(msg) {
614
602
  function findRevokeElement(msg) {
615
603
  return msg.elements.find((el) => el.grayTipElement?.revokeElement != null)?.grayTipElement?.revokeElement ?? void 0;
616
604
  }
617
- export { logEventFailure as a, downloadBufferToFile as c, prepareVideoElements as d, MediaCache as f, withMediaScope as h, hasGrayTip as i, ensureSilk as l, protectMediaPath as m, findRevokeElement as n, sliceRaw as o, cacheMediaFile as p, firstUntranslatedGrayTip as r, truncRaw as s, collectGrayTipUids as t, fileUriToPath as u };
605
+ export { withMediaScope as _, logEventFailure as a, protocolMediaSchema as c, fileUriToPath as d, mediaDownloader as f, protectMediaPath as g, cacheMediaFile as h, hasGrayTip as i, downloadProtocolMedia as l, MediaCache as m, findRevokeElement as n, sliceRaw as o, prepareVideoElements as p, firstUntranslatedGrayTip as r, truncRaw as s, collectGrayTipUids as t, ensureSilk as u };
@@ -56,8 +56,8 @@ interface TokenAuthOptions {
56
56
  allowQueryToken?: boolean | undefined;
57
57
  /** 是否允许裸 authorization 头直接等于 token(OB11 兼容,默认 false)。 */
58
58
  allowRawHeader?: boolean | undefined;
59
- /** 查询参数 URL 解析异常回调(Milky debug 校准日志用)。 */
60
- onQueryParseError?: ((url: string, err: unknown) => void) | undefined;
59
+ /** 查询参数 URL 解析失败通知,避免诊断路径携带请求原文。 */
60
+ onQueryParseError?: (() => void) | undefined;
61
61
  }
62
62
  /**
63
63
  * 请求凭据匹配(头优先,查询参数兜底)。
@@ -1,9 +1,10 @@
1
- import { m as ActionRegistry, s as BaseProtocolAdapter, t as ConfigBase$1 } from "./index-BZfGz6FA.mjs";
1
+ import { m as ActionRegistry, s as BaseProtocolAdapter, t as ConfigBase$1 } from "./index-BO1TgLTT.mjs";
2
2
  import { n as AdapterLoggerLike, t as MediaCache } from "./media-cache-C_0C9eCV.mjs";
3
3
  import "./gray-tip-CcpfI1Og.mjs";
4
4
  import { CanonicalElement, FriendApi, GroupApi, GroupCache, GroupNotifyApi, KernelErrorCode, MsgApi, MsgEventChannel, Peer, ProfileApi } from "@napuketto/kernel";
5
5
  import { EventBroadcaster, TransportAdapter } from "@napuketto/network";
6
6
  import { ZodType, z } from "zod";
7
+ import { MediaOutboundPolicy } from "@napuketto/media";
7
8
  /** Satori 消息元素(与规范 satori-parse 形状一致;type="text" 为文本节点)。 */
8
9
  interface SatoriElement {
9
10
  type: string;
@@ -24,6 +25,7 @@ interface SatoriToCanonicalDeps {
24
25
  uinToUid: (uins: string[]) => Promise<Map<string, string>>;
25
26
  /** 资源(img/audio/video/file)下载缓存目录。 */
26
27
  cacheDir: string;
28
+ outboundPolicy?: MediaOutboundPolicy | undefined;
27
29
  /** 转码成功即转移输出文件及其父临时目录的所有权;发送消费结束后清理。 */
28
30
  onVideoTranscoded?: (path: string) => void;
29
31
  }
@@ -66,7 +68,8 @@ declare class SatoriApi {
66
68
  * 规则区分,需从事件/查询回填——QQ 平台群号与用户 uin 同为数字)。
67
69
  */
68
70
  private readonly channelTypeCache;
69
- constructor(opts: SatoriApiOptions);
71
+ private readonly getMediaOutboundPolicy;
72
+ constructor(opts: SatoriApiOptions, getMediaOutboundPolicy?: () => MediaOutboundPolicy | undefined);
70
73
  /** 记录频道类型(消息事件翻译时回填:chatType GROUP → true)。 */
71
74
  setChannelType(channelId: string, isGroup: boolean): void;
72
75
  /**
@@ -105,8 +108,13 @@ interface SatoriActionDeps {
105
108
  type SatoriActionRegistry = ActionRegistry<SatoriActionHandler<unknown, unknown>>;
106
109
  /** 创建 Satori 动作注册表。 */
107
110
  declare function createSatoriActionRegistry(deps: SatoriActionDeps): SatoriActionRegistry;
108
- /** Satori 配置 schema。 */
109
111
  declare const satoriConfigSchema: z.ZodObject<{
112
+ media: z.ZodOptional<z.ZodObject<{
113
+ outboundPolicy: z.ZodOptional<z.ZodEnum<{
114
+ compat: "compat";
115
+ "public-only": "public-only";
116
+ }>>;
117
+ }, z.core.$strip>>;
110
118
  token: z.ZodOptional<z.ZodString>;
111
119
  cacheDir: z.ZodOptional<z.ZodString>;
112
120
  httpServers: z.ZodDefault<z.ZodArray<z.ZodObject<{
@@ -1,9 +1,10 @@
1
- import { _ as ErrorCodeMap, m as ActionRegistry, s as BaseProtocolAdapter, t as ConfigBase$1 } from "./index-BZfGz6FA.mjs";
1
+ import { _ as ErrorCodeMap, m as ActionRegistry, s as BaseProtocolAdapter, t as ConfigBase$1 } from "./index-BO1TgLTT.mjs";
2
2
  import { n as AdapterLoggerLike, t as MediaCache } from "./media-cache-C_0C9eCV.mjs";
3
3
  import "./gray-tip-CcpfI1Og.mjs";
4
4
  import { BuddyCacheEventChannel, BuddyEventChannel, CanonicalElement, FlashTransferApi, FriendApi, GroupApi, GroupCache, GroupEventChannel, GroupNotifyApi, MsgApi, MsgEventChannel, Peer, ProfileApi, ProfileLikeApi, RichMediaApi, TicketApi, WebApi } from "@napuketto/kernel";
5
5
  import { EventBroadcaster, TransportAdapter } from "@napuketto/network";
6
6
  import { ZodType, z } from "zod";
7
+ import { MediaOutboundPolicy } from "@napuketto/media";
7
8
  /**
8
9
  * OneBot 11 类型定义(自研描述,参考公开协议规范)
9
10
  * 对应:接口签名是外部协议事实,可自研描述,不复制实现。
@@ -293,6 +294,7 @@ interface OneBotApiOptions {
293
294
  */
294
295
  declare class OneBotApi {
295
296
  readonly mediaCache: MediaCache;
297
+ readonly getMediaOutboundPolicy?: (() => MediaOutboundPolicy | undefined) | undefined;
296
298
  /** kernel 消息 API(send_msg 等消息类动作用)。 */
297
299
  readonly msgApi: MsgApi;
298
300
  /** kernel 群 API。 */
@@ -338,7 +340,7 @@ declare class OneBotApi {
338
340
  readonly restart: (() => Promise<void>) | undefined;
339
341
  /** 降级分支可观测出口(缺省静默)。 */
340
342
  readonly logger?: AdapterLoggerLike | undefined;
341
- constructor(opts: OneBotApiOptions);
343
+ constructor(opts: OneBotApiOptions, getMediaOutboundPolicy?: () => MediaOutboundPolicy | undefined);
342
344
  /**
343
345
  * uin→uid 转换(委托 groupApi;私聊目标/成员 user_id 用)。
344
346
  * 类字段箭头函数:动作会把本方法作为回调裸传(resolveUid 等),必须绑定实例,
@@ -438,8 +440,13 @@ declare function parseCqMessage(text: string): Array<string | CqCode>;
438
440
  declare function serializeCqParts(parts: Array<string | CqCode>): string;
439
441
  /** OB11 segment 数组 → CQ 码字符串(text 段转义拼接,特殊段编码)。 */
440
442
  declare function segmentsToCqMessage(segments: OB11MessageSegment[]): string;
441
- /** OB11 配置 schema。 */
442
443
  declare const ob11ConfigSchema: z.ZodObject<{
444
+ media: z.ZodOptional<z.ZodObject<{
445
+ outboundPolicy: z.ZodOptional<z.ZodEnum<{
446
+ compat: "compat";
447
+ "public-only": "public-only";
448
+ }>>;
449
+ }, z.core.$strip>>;
443
450
  token: z.ZodOptional<z.ZodString>;
444
451
  heartbeatInterval: z.ZodDefault<z.ZodNumber>;
445
452
  reportSelfMessage: z.ZodDefault<z.ZodBoolean>;
@@ -810,8 +817,8 @@ declare class NapukettoOneBot11Adapter extends BaseProtocolAdapter<OB11Config> {
810
817
  }
811
818
  /** 正向 WS client 首连失败的后台重连参数(HTTP 上报无连接,不参与)。 */
812
819
  interface Ob11OutboundWsReconnect {
813
- /** 对端地址(日志标识 + 同配置内唯一)。 */
814
- url: string;
820
+ /** 配置项序号,用于定位日志。 */
821
+ index: number;
815
822
  /** 首次重连延迟(毫秒;后续按 2 倍指数退避)。 */
816
823
  delayMs: number;
817
824
  /** 最大重连次数(不含首连);缺省无限。 */
@@ -1,8 +1,9 @@
1
- import { m as ActionRegistry, s as BaseProtocolAdapter, t as ConfigBase$1 } from "./index-BZfGz6FA.mjs";
1
+ import { m as ActionRegistry, s as BaseProtocolAdapter, t as ConfigBase$1 } from "./index-BO1TgLTT.mjs";
2
2
  import { t as MediaCache } from "./media-cache-C_0C9eCV.mjs";
3
3
  import { BuddyEventChannel, ChatType, FlashTransferApi, FriendApi, GroupApi, GroupCache, GroupEventChannel, GroupNotifyApi, KernelErrorCode, LoginEventChannel, MsgApi, MsgEventChannel, Peer, ProfileApi, ProfileLikeApi, RawMessage, RecentContactApi, RecentContactEventChannel, RichMediaApi, TicketApi, WebApi } from "@napuketto/kernel";
4
4
  import { EventBroadcaster, TransportAdapter } from "@napuketto/network";
5
5
  import { ZodType, z } from "zod";
6
+ import { MediaOutboundPolicy } from "@napuketto/media";
6
7
  /**
7
8
  * Milky 动作结果(retcode 为规范负数族;transport 原样组装信封)。
8
9
  *
@@ -68,8 +69,13 @@ declare class MessageSeqIndex {
68
69
  /** FIFO 淘汰到容量上限内。 */
69
70
  private evict;
70
71
  }
71
- /** Milky 配置 schema。 */
72
72
  declare const milkyConfigSchema: z.ZodObject<{
73
+ media: z.ZodOptional<z.ZodObject<{
74
+ outboundPolicy: z.ZodOptional<z.ZodEnum<{
75
+ compat: "compat";
76
+ "public-only": "public-only";
77
+ }>>;
78
+ }, z.core.$strip>>;
73
79
  enabled: z.ZodDefault<z.ZodBoolean>;
74
80
  host: z.ZodDefault<z.ZodString>;
75
81
  port: z.ZodDefault<z.ZodNumber>;
@@ -159,11 +165,12 @@ declare class MilkyApi {
159
165
  readonly qqVersion: string;
160
166
  readonly implVersion: string;
161
167
  readonly mediaDir: string | undefined;
168
+ readonly getMediaOutboundPolicy?: (() => MediaOutboundPolicy | undefined) | undefined;
162
169
  /** 动作层可观测出口(缺省静默)。 */
163
170
  readonly logger: MilkyLoggerLike | undefined;
164
171
  /** message_seq ↔ msgId 双向映射(接收链路 record,动作侧反查)。 */
165
172
  readonly seqIndex: MessageSeqIndex;
166
- constructor(opts: MilkyApiOptions, seqIndex: MessageSeqIndex);
173
+ constructor(opts: MilkyApiOptions, seqIndex: MessageSeqIndex, getMediaOutboundPolicy?: () => MediaOutboundPolicy | undefined);
167
174
  /** uin → uid(私聊目标 / at 段发送转换 / 群管动作的 uid 入参)。 */
168
175
  uinToUid(uins: string[]): Promise<Map<string, string>>;
169
176
  /** uid → uin(事件路径 mention 转换)。 */
@@ -1,4 +1,4 @@
1
- import { s as BaseProtocolAdapter, t as ConfigBase$1 } from "./index-BZfGz6FA.mjs";
1
+ import { s as BaseProtocolAdapter, t as ConfigBase$1 } from "./index-BO1TgLTT.mjs";
2
2
  import { CanonicalElement, MsgEventChannel, Peer, RawMessage } from "@napuketto/kernel";
3
3
  import { z } from "zod";
4
4
  /** kurobot 配置 schema。 */
package/dist/index.d.mts CHANGED
@@ -15,9 +15,9 @@
15
15
  * 子路径导出(./core、./onebot11、./satori、./kurobot、./milky)保持不变;
16
16
  * 本文件只追加聚合,不改变任何子路径的解析结果。
17
17
  */
18
- import { _ as ErrorCodeMap, a as ProtocolConfig, c as ProtocolHooks, g as ActionOutcome, h as ActionKernelSpec, i as ConfigSchema, m as ActionRegistry, n as ConfigFormat, o as createServerSchema, r as ConfigOptions, s as BaseProtocolAdapter, t as ConfigBase, v as runAction } from "./index-BZfGz6FA.mjs";
19
- import { et as KurobotConfig, l as KurobotAdapterOptions, nt as kurobotConfigSchema, u as NapukettoKurobotAdapter } from "./index-oinf9f75.mjs";
20
- import { G as MilkyConfig, K as milkyConfigSchema, L as MilkyAdapterOptions, R as NapukettoMilkyAdapter } from "./index-CKWWp8-H.mjs";
21
- import { C as ob11ConfigSchema, S as OB11Config, o as NapukettoOneBot11Adapter, s as OneBot11AdapterOptions } from "./index-DrPCnj64.mjs";
22
- import { R as SatoriConfig, d as NapukettoSatoriAdapter, f as SatoriAdapterOptions, z as satoriConfigSchema } from "./index-tljZ0fmt.mjs";
18
+ import { _ as ErrorCodeMap, a as ProtocolConfig, c as ProtocolHooks, g as ActionOutcome, h as ActionKernelSpec, i as ConfigSchema, m as ActionRegistry, n as ConfigFormat, o as createServerSchema, r as ConfigOptions, s as BaseProtocolAdapter, t as ConfigBase, v as runAction } from "./index-BO1TgLTT.mjs";
19
+ import { et as KurobotConfig, l as KurobotAdapterOptions, nt as kurobotConfigSchema, u as NapukettoKurobotAdapter } from "./index-tW3a05Du.mjs";
20
+ import { G as MilkyConfig, K as milkyConfigSchema, L as MilkyAdapterOptions, R as NapukettoMilkyAdapter } from "./index-Dsfxdjz5.mjs";
21
+ import { C as ob11ConfigSchema, S as OB11Config, o as NapukettoOneBot11Adapter, s as OneBot11AdapterOptions } from "./index-CufnIU9v.mjs";
22
+ import { R as SatoriConfig, d as NapukettoSatoriAdapter, f as SatoriAdapterOptions, z as satoriConfigSchema } from "./index-CX7UKc6W.mjs";
23
23
  export { type ActionKernelSpec, type ActionOutcome, ActionRegistry, BaseProtocolAdapter, ConfigBase, type ConfigFormat, type ConfigOptions, type ConfigSchema, type ErrorCodeMap, type KurobotAdapterOptions, type KurobotConfig, type MilkyAdapterOptions, type MilkyConfig, NapukettoKurobotAdapter, NapukettoMilkyAdapter, NapukettoOneBot11Adapter, NapukettoSatoriAdapter, type OB11Config, type OneBot11AdapterOptions, ProtocolConfig, type ProtocolHooks, type SatoriAdapterOptions, type SatoriConfig, createServerSchema, kurobotConfigSchema, milkyConfigSchema, ob11ConfigSchema, runAction, satoriConfigSchema };
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { d as runAction, i as BaseProtocolAdapter, n as ProtocolConfig, r as createServerSchema, t as ConfigBase, u as ActionRegistry } from "./framework-BbtmlUXJ.mjs";
2
- import { N as kurobotConfigSchema, t as NapukettoKurobotAdapter } from "./kurobot-BUJkleqO.mjs";
3
- import { r as milkyConfigSchema, t as NapukettoMilkyAdapter } from "./milky-Dj45WP4r.mjs";
4
- import { t as NapukettoOneBot11Adapter, u as ob11ConfigSchema } from "./onebot11-CUK6blMn.mjs";
5
- import { m as satoriConfigSchema, t as NapukettoSatoriAdapter } from "./satori-CDxpqL3l.mjs";
1
+ import { f as ActionRegistry, n as ProtocolConfig, o as BaseProtocolAdapter, p as runAction, r as createServerSchema, t as ConfigBase } from "./framework-CA3087JP.mjs";
2
+ import { N as kurobotConfigSchema, t as NapukettoKurobotAdapter } from "./kurobot-8YrYipGI.mjs";
3
+ import { r as milkyConfigSchema, t as NapukettoMilkyAdapter } from "./milky-79AYb8fV.mjs";
4
+ import { t as NapukettoOneBot11Adapter, u as ob11ConfigSchema } from "./onebot11-BW56Dqc6.mjs";
5
+ import { m as satoriConfigSchema, t as NapukettoSatoriAdapter } from "./satori-Cetkw86t.mjs";
6
6
  export { ActionRegistry, BaseProtocolAdapter, ConfigBase, NapukettoKurobotAdapter, NapukettoMilkyAdapter, NapukettoOneBot11Adapter, NapukettoSatoriAdapter, ProtocolConfig, createServerSchema, kurobotConfigSchema, milkyConfigSchema, ob11ConfigSchema, runAction, satoriConfigSchema };
@@ -2,5 +2,5 @@
2
2
  * kurobot 协议适配器(KuroBot MVP-3)
3
3
  * 公共面:镜像协议 schema + 配置 schema + 连接层 + 适配器。
4
4
  */
5
- import { $ as wireFrameSchema, A as PROTOCOL_NAME, B as encodeFrame, C as CommandResultBody, D as HelloBody, E as HelloAckBody, F as WS_SUBPROTOCOL, G as joinFrame, H as helloAckFrame, I as bindingsUpdatedFrame, J as platformChatFrame, K as leaveFrame, L as commandFrame, M as PlatformChatBody, N as QueryResultBody, O as JoinBody, P as StatusBody, Q as statusFrame, R as commandResultFrame, S as CommandFrame, T as GameChatBody, U as helloFrame, V as gameChatFrame, W as isProtocolVersionCompatible, X as queryFrame, Y as pongFrame, Z as queryResultFrame, _ as KurobotHello, a as renderDeathText, b as BindingsUpdatedBody, c as truncateForGroup, d as KurobotConnFace, et as KurobotConfig, f as KurobotMsgApi, g as KurobotConnectionOptions, h as KurobotConnection, i as renderCommandResult, j as PROTOCOL_VERSION, k as LeaveBody, l as KurobotAdapterOptions, m as ConnectionEndedReason, n as degradeElements, nt as kurobotConfigSchema, o as renderTemplate, p as ReceiveLogFilterHolder, q as pingFrame, r as degradeMessage, s as resolveSenderName, t as MAX_GROUP_TEXT_LENGTH, tt as kurobotConfigDefaults, u as NapukettoKurobotAdapter, v as KurobotLogger, w as DeathBody, x as CommandBody, y as ServerEventMessage, z as deathFrame } from "../index-oinf9f75.mjs";
5
+ import { $ as wireFrameSchema, A as PROTOCOL_NAME, B as encodeFrame, C as CommandResultBody, D as HelloBody, E as HelloAckBody, F as WS_SUBPROTOCOL, G as joinFrame, H as helloAckFrame, I as bindingsUpdatedFrame, J as platformChatFrame, K as leaveFrame, L as commandFrame, M as PlatformChatBody, N as QueryResultBody, O as JoinBody, P as StatusBody, Q as statusFrame, R as commandResultFrame, S as CommandFrame, T as GameChatBody, U as helloFrame, V as gameChatFrame, W as isProtocolVersionCompatible, X as queryFrame, Y as pongFrame, Z as queryResultFrame, _ as KurobotHello, a as renderDeathText, b as BindingsUpdatedBody, c as truncateForGroup, d as KurobotConnFace, et as KurobotConfig, f as KurobotMsgApi, g as KurobotConnectionOptions, h as KurobotConnection, i as renderCommandResult, j as PROTOCOL_VERSION, k as LeaveBody, l as KurobotAdapterOptions, m as ConnectionEndedReason, n as degradeElements, nt as kurobotConfigSchema, o as renderTemplate, p as ReceiveLogFilterHolder, q as pingFrame, r as degradeMessage, s as resolveSenderName, t as MAX_GROUP_TEXT_LENGTH, tt as kurobotConfigDefaults, u as NapukettoKurobotAdapter, v as KurobotLogger, w as DeathBody, x as CommandBody, y as ServerEventMessage, z as deathFrame } from "../index-tW3a05Du.mjs";
6
6
  export { type BindingsUpdatedBody, type CommandBody, type CommandFrame, type CommandResultBody, type ConnectionEndedReason, type DeathBody, type GameChatBody, type HelloAckBody, type HelloBody, type JoinBody, type KurobotAdapterOptions, type KurobotConfig, type KurobotConnFace, KurobotConnection, type KurobotConnectionOptions, type KurobotHello, type KurobotLogger, type KurobotMsgApi, type LeaveBody, MAX_GROUP_TEXT_LENGTH, NapukettoKurobotAdapter, PROTOCOL_NAME, PROTOCOL_VERSION, type PlatformChatBody, type QueryResultBody, type ReceiveLogFilterHolder, type ServerEventMessage, type StatusBody, WS_SUBPROTOCOL, bindingsUpdatedFrame, commandFrame, commandResultFrame, deathFrame, degradeElements, degradeMessage, encodeFrame, gameChatFrame, helloAckFrame, helloFrame, isProtocolVersionCompatible, joinFrame, kurobotConfigDefaults, kurobotConfigSchema, leaveFrame, pingFrame, platformChatFrame, pongFrame, queryFrame, queryResultFrame, renderCommandResult, renderDeathText, renderTemplate, resolveSenderName, statusFrame, truncateForGroup, wireFrameSchema };
@@ -1 +1 @@
1
- export { u as KurobotConnection, n as MAX_GROUP_TEXT_LENGTH, t as NapukettoKurobotAdapter, d as PROTOCOL_NAME, f as PROTOCOL_VERSION, p as WS_SUBPROTOCOL, m as bindingsUpdatedFrame, h as commandFrame, g as commandResultFrame, _ as deathFrame, r as degradeElements, i as degradeMessage, v as encodeFrame, y as gameChatFrame, b as helloAckFrame, x as helloFrame, S as isProtocolVersionCompatible, C as joinFrame, M as kurobotConfigDefaults, N as kurobotConfigSchema, w as leaveFrame, T as pingFrame, E as platformChatFrame, D as pongFrame, O as queryFrame, k as queryResultFrame, a as renderCommandResult, o as renderDeathText, s as renderTemplate, c as resolveSenderName, A as statusFrame, l as truncateForGroup, j as wireFrameSchema } from "../kurobot-BUJkleqO.mjs";
1
+ export { u as KurobotConnection, n as MAX_GROUP_TEXT_LENGTH, t as NapukettoKurobotAdapter, d as PROTOCOL_NAME, f as PROTOCOL_VERSION, p as WS_SUBPROTOCOL, m as bindingsUpdatedFrame, h as commandFrame, g as commandResultFrame, _ as deathFrame, r as degradeElements, i as degradeMessage, v as encodeFrame, y as gameChatFrame, b as helloAckFrame, x as helloFrame, S as isProtocolVersionCompatible, C as joinFrame, M as kurobotConfigDefaults, N as kurobotConfigSchema, w as leaveFrame, T as pingFrame, E as platformChatFrame, D as pongFrame, O as queryFrame, k as queryResultFrame, a as renderCommandResult, o as renderDeathText, s as renderTemplate, c as resolveSenderName, A as statusFrame, l as truncateForGroup, j as wireFrameSchema } from "../kurobot-8YrYipGI.mjs";
@@ -1,4 +1,4 @@
1
- import { a as resolveProtocolConfig, i as BaseProtocolAdapter } from "./framework-BbtmlUXJ.mjs";
1
+ import { o as BaseProtocolAdapter, s as resolveProtocolConfig } from "./framework-CA3087JP.mjs";
2
2
  import { r as subscribeRawMessages } from "./raw-message-DU8YOhLV.mjs";
3
3
  import { ChatType, errorMessage, getOwnProp, isRecord, kernelError, toCanonicalElements } from "@napuketto/kernel";
4
4
  import { randomUUID } from "node:crypto";
@@ -5,5 +5,5 @@
5
5
  * 对齐 ./onebot11 与 ./satori 的导出口径。装配方(loader assemble-protocols)
6
6
  * 动态 import 本入口。
7
7
  */
8
- import { A as MessageRecallData, B as MilkyApi, C as GroupMuteData, D as IncomingForwardedMessage, E as GroupWholeMuteData, F as PeerPinChangeData, G as MilkyConfig, H as MilkyLoggerLike, I as SendMessageOutput, J as milkyErrorCodeMap, K as milkyConfigSchema, L as MilkyAdapterOptions, M as MilkyEvent, N as OutgoingForwardedMessage, O as IncomingMessage, P as OutgoingSegment, R as NapukettoMilkyAdapter, S as GroupMessageReactionData, T as GroupNotificationEntity, U as MilkyTransportSet, V as MilkyApiOptions, W as assembleMilkyTransports, _ as GroupInvitedJoinRequestData, a as FriendRequestEntity, b as GroupMemberEntity, c as GetLoginInfoOutput, d as GroupEntity, f as GroupEssenceMessage, g as GroupInvitationData, h as GroupFolderEntity, i as FriendRequestData, j as MessageScene, k as IncomingSegment, l as GroupAnnouncementEntity, m as GroupFileUploadData, n as FriendCategoryEntity, o as GetCookiesOutput, p as GroupFileEntity, q as MilkyAction, r as FriendEntity, s as GetImplInfoOutput, t as BotOfflineData, u as GroupDisbandData, v as GroupJoinRequestData, w as GroupNameChangeData, x as GroupMemberIncreaseData, y as GroupMemberDecreaseData, z as createMilkyActionRegistry } from "../index-CKWWp8-H.mjs";
8
+ import { A as MessageRecallData, B as MilkyApi, C as GroupMuteData, D as IncomingForwardedMessage, E as GroupWholeMuteData, F as PeerPinChangeData, G as MilkyConfig, H as MilkyLoggerLike, I as SendMessageOutput, J as milkyErrorCodeMap, K as milkyConfigSchema, L as MilkyAdapterOptions, M as MilkyEvent, N as OutgoingForwardedMessage, O as IncomingMessage, P as OutgoingSegment, R as NapukettoMilkyAdapter, S as GroupMessageReactionData, T as GroupNotificationEntity, U as MilkyTransportSet, V as MilkyApiOptions, W as assembleMilkyTransports, _ as GroupInvitedJoinRequestData, a as FriendRequestEntity, b as GroupMemberEntity, c as GetLoginInfoOutput, d as GroupEntity, f as GroupEssenceMessage, g as GroupInvitationData, h as GroupFolderEntity, i as FriendRequestData, j as MessageScene, k as IncomingSegment, l as GroupAnnouncementEntity, m as GroupFileUploadData, n as FriendCategoryEntity, o as GetCookiesOutput, p as GroupFileEntity, q as MilkyAction, r as FriendEntity, s as GetImplInfoOutput, t as BotOfflineData, u as GroupDisbandData, v as GroupJoinRequestData, w as GroupNameChangeData, x as GroupMemberIncreaseData, y as GroupMemberDecreaseData, z as createMilkyActionRegistry } from "../index-Dsfxdjz5.mjs";
9
9
  export { type BotOfflineData, type FriendCategoryEntity, type FriendEntity, type FriendRequestData, type FriendRequestEntity, type GetCookiesOutput, type GetImplInfoOutput, type GetLoginInfoOutput, type GroupAnnouncementEntity, type GroupDisbandData, type GroupEntity, type GroupEssenceMessage, type GroupFileEntity, type GroupFileUploadData, type GroupFolderEntity, type GroupInvitationData, type GroupInvitedJoinRequestData, type GroupJoinRequestData, type GroupMemberDecreaseData, type GroupMemberEntity, type GroupMemberIncreaseData, type GroupMessageReactionData, type GroupMuteData, type GroupNameChangeData, type GroupNotificationEntity, type GroupWholeMuteData, type IncomingForwardedMessage, type MessageRecallData, type MessageScene, type MilkyAction, type MilkyAdapterOptions, MilkyApi, type MilkyApiOptions, type MilkyConfig, type MilkyEvent, type IncomingMessage as MilkyIncomingMessage, type IncomingSegment as MilkyIncomingSegment, type MilkyLoggerLike, type OutgoingSegment as MilkyOutgoingSegment, type MilkyTransportSet, NapukettoMilkyAdapter, type OutgoingForwardedMessage, type PeerPinChangeData, type SendMessageOutput, assembleMilkyTransports, createMilkyActionRegistry, milkyConfigSchema, milkyErrorCodeMap };
@@ -1 +1 @@
1
- export { a as MilkyApi, t as NapukettoMilkyAdapter, n as assembleMilkyTransports, i as createMilkyActionRegistry, r as milkyConfigSchema, o as milkyErrorCodeMap } from "../milky-Dj45WP4r.mjs";
1
+ export { a as MilkyApi, t as NapukettoMilkyAdapter, n as assembleMilkyTransports, i as createMilkyActionRegistry, r as milkyConfigSchema, o as milkyErrorCodeMap } from "../milky-79AYb8fV.mjs";
@@ -1,12 +1,12 @@
1
- import { a as resolveProtocolConfig, c as matchTokenCredential, d as runAction, i as BaseProtocolAdapter, o as BEARER_PREFIX, s as createTokenAuthorize, u as ActionRegistry } from "./framework-BbtmlUXJ.mjs";
2
- import { a as logEventFailure, f as MediaCache, h as withMediaScope, i as hasGrayTip, m as protectMediaPath, n as findRevokeElement, o as sliceRaw, p as cacheMediaFile, r as firstUntranslatedGrayTip, t as collectGrayTipUids, u as fileUriToPath } from "./gray-tip-BL1rhwZK.mjs";
1
+ import { c as BEARER_PREFIX, f as ActionRegistry, i as validateListenerToken, l as createTokenAuthorize, o as BaseProtocolAdapter, p as runAction, s as resolveProtocolConfig } from "./framework-CA3087JP.mjs";
2
+ import { _ as withMediaScope, a as logEventFailure, c as protocolMediaSchema, d as fileUriToPath, f as mediaDownloader, g as protectMediaPath, h as cacheMediaFile, i as hasGrayTip, m as MediaCache, n as findRevokeElement, o as sliceRaw, r as firstUntranslatedGrayTip, t as collectGrayTipUids } from "./gray-tip-BtiJls6z.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, o as stringOrUndefined, p as resolveUin, r as subscribeRawMessages, s as startupBaselineSec, t as forEachRawMessage } from "./raw-message-DU8YOhLV.mjs";
4
4
  import { a as processSysMsgBlob, c as varintAt, d as processInboundBuddyReqs, i as nodeAt, l as varintOf, n as OBSERVED_UNNAMED_SYSMSG_KEYS, o as recognizeSysMsg, r as narrowSysMsgBlobs, s as textOf, t as extractEssenceSetSysMsg, u as BuddyReqDedup } from "./essence-Cn1oRaLw.mjs";
5
5
  import { ChatType, EssenceListSync, GrayTipSubType, GroupApi, GroupNotifyMsgStatus, GroupNotifyMsgType, NTGroupMemberRole, NTGroupRequestOperateTypes, TicketApi, TipGroupElementType, errorMessage, hasNumberProp, hasStringProp, isRecord, kernelError, narrowEssenceGroupArg, toCanonicalElements } from "@napuketto/kernel";
6
6
  import { HttpClient, HttpServer, createSseResponse, sendWsText } from "@napuketto/network";
7
7
  import { z } from "zod";
8
8
  import { rename, writeFile } from "node:fs/promises";
9
- import { detectFileType, downloadUrl, inferExtension } from "@napuketto/media";
9
+ import { detectFileType, inferExtension } from "@napuketto/media";
10
10
  // src/milky/action/base-action.ts
11
11
  /** KernelErrorCode → Milky retcode 映射表(-400/-403 规范语义,其余取常见 HTTP 语义近似负数)。 */
12
12
  const milkyErrorCodeMap = {
@@ -323,16 +323,16 @@ function essenceToEntity(item, groupId) {
323
323
  * 规范支持 file:// / http(s):// / base64:// 三种(image/record/video 共用):
324
324
  * - file:// → 平台路径(segments.ts 的同步面已处理)
325
325
  * - base64:// → 解码落盘 cacheDir/milky/,file-type 探测扩展名后改名
326
- * - http(s):// → @napuketto/media downloadUrl 落盘 cacheDir/milky/
326
+ * - http(s):// → 按媒体出站策略下载落盘 cacheDir/milky/
327
327
  * 未配置 mediaDir 时远程 URI 报错(不发静默空消息)。
328
328
  */
329
329
  const DETECTED_EXTENSION_RE = /^[a-zA-Z0-9]+$/;
330
330
  /** 解析远程媒体 URI 为本地绝对路径(base64:// / http(s)://;file:// 走同步面)。 */
331
- async function resolveMediaUri(uri, mediaDir) {
331
+ async function resolveMediaUri(uri, mediaDir, outboundPolicy) {
332
332
  if (mediaDir === void 0 || mediaDir === "") throw kernelError("远程媒体发送需要配置 [accounts.milky] cacheDir(下载缓存目录)", "INVALID_PARAM");
333
333
  if (uri.startsWith("base64://")) return await writeBase64(uri.slice(9), mediaDir);
334
334
  return await cacheMediaFile(mediaDir, inferExtension(null, uri), async (dest) => {
335
- await downloadUrl(uri, dest);
335
+ await mediaDownloader(outboundPolicy)(uri, dest);
336
336
  });
337
337
  }
338
338
  /**
@@ -340,9 +340,9 @@ async function resolveMediaUri(uri, mediaDir) {
340
340
  * 失败裸剥离兜底,与 segments.ts 同步面同规则);http(s):// / base64:// 复用
341
341
  * resolveMediaUri 落盘;裸路径(go-cqhttp 惯例)原样。
342
342
  */
343
- async function resolveUriToPath(uri, mediaDir) {
343
+ async function resolveUriToPath(uri, mediaDir, outboundPolicy) {
344
344
  if (uri.startsWith("file://")) return await protectMediaPath(fileUriToPath(uri));
345
- if (uri.startsWith("http://") || uri.startsWith("https://") || uri.startsWith("base64://")) return await resolveMediaUri(uri, mediaDir);
345
+ if (uri.startsWith("http://") || uri.startsWith("https://") || uri.startsWith("base64://")) return await resolveMediaUri(uri, mediaDir, outboundPolicy);
346
346
  return await protectMediaPath(uri);
347
347
  }
348
348
  /** base64 载荷 → 落盘(先写 .bin,探测到扩展名再改名)。 */
@@ -471,7 +471,7 @@ function createGroupFileActions(api) {
471
471
  file_name: z.string().min(1)
472
472
  }),
473
473
  handle: async (payload) => {
474
- const path = await resolveUriToPath(payload.file_uri, api.mediaDir);
474
+ const path = await resolveUriToPath(payload.file_uri, api.mediaDir, api.getMediaOutboundPolicy?.());
475
475
  const peer = {
476
476
  chatType: ChatType.GROUP,
477
477
  peerUid: String(payload.group_id)
@@ -555,11 +555,13 @@ var MilkyApi = class {
555
555
  qqVersion;
556
556
  implVersion;
557
557
  mediaDir;
558
+ getMediaOutboundPolicy;
558
559
  /** 动作层可观测出口(缺省静默)。 */
559
560
  logger;
560
561
  /** message_seq ↔ msgId 双向映射(接收链路 record,动作侧反查)。 */
561
562
  seqIndex;
562
- constructor(opts, seqIndex) {
563
+ constructor(opts, seqIndex, getMediaOutboundPolicy) {
564
+ this.getMediaOutboundPolicy = getMediaOutboundPolicy;
563
565
  this.mediaCache = new MediaCache({
564
566
  root: opts.mediaDir,
565
567
  logger: opts.logger
@@ -806,7 +808,7 @@ function createGroupManageActions(api) {
806
808
  image_uri: z.string().min(1)
807
809
  }),
808
810
  handle: async (payload) => {
809
- const imagePath = await resolveUriToPath(payload.image_uri, api.mediaDir);
811
+ const imagePath = await resolveUriToPath(payload.image_uri, api.mediaDir, api.getMediaOutboundPolicy?.());
810
812
  await api.groupApi.setGroupAvatar(String(payload.group_id), imagePath);
811
813
  return {};
812
814
  }
@@ -834,7 +836,7 @@ function createGroupManageActions(api) {
834
836
  handle: async (payload) => {
835
837
  const groupCode = String(payload.group_id);
836
838
  let imagePath;
837
- if (payload.image_uri !== void 0 && payload.image_uri !== null && payload.image_uri !== "") imagePath = await resolveUriToPath(payload.image_uri, api.mediaDir);
839
+ if (payload.image_uri !== void 0 && payload.image_uri !== null && payload.image_uri !== "") imagePath = await resolveUriToPath(payload.image_uri, api.mediaDir, api.getMediaOutboundPolicy?.());
838
840
  await api.groupApi.publishGroupAnnouncement(groupCode, payload.content, imagePath);
839
841
  return {};
840
842
  }
@@ -1770,7 +1772,7 @@ function createMessageOpsActions(api) {
1770
1772
  file_name: z.string().min(1)
1771
1773
  }),
1772
1774
  handle: async (payload) => {
1773
- const path = await resolveUriToPath(payload.file_uri, api.mediaDir);
1775
+ const path = await resolveUriToPath(payload.file_uri, api.mediaDir, api.getMediaOutboundPolicy?.());
1774
1776
  const peer = await api.resolvePeer("friend", payload.user_id);
1775
1777
  return { file_id: (await api.flashTransferApi.sendFile(peer, [path], { name: payload.file_name })).fileSetId };
1776
1778
  }
@@ -1917,7 +1919,7 @@ async function resolveElement(el, uinToUid, api) {
1917
1919
  };
1918
1920
  if ((el.type === "image" || el.type === "voice" || el.type === "video") && isRemoteMediaUri(el)) return {
1919
1921
  ...el,
1920
- path: await resolveMediaUri(el.path, api.mediaDir)
1922
+ path: await resolveMediaUri(el.path, api.mediaDir, api.getMediaOutboundPolicy?.())
1921
1923
  };
1922
1924
  if ("path" in el) await protectMediaPath(el.path);
1923
1925
  return el;
@@ -1976,7 +1978,7 @@ function createProfileActions(api) {
1976
1978
  name: "set_avatar",
1977
1979
  schema: z.object({ uri: z.string().min(1) }),
1978
1980
  handle: async (payload) => {
1979
- const path = await resolveMediaUri(payload.uri, api.mediaDir);
1981
+ const path = await resolveMediaUri(payload.uri, api.mediaDir, api.getMediaOutboundPolicy?.());
1980
1982
  await api.profileApi.setHeader(path);
1981
1983
  return {};
1982
1984
  }
@@ -2241,22 +2243,15 @@ function createMilkyActionRegistry(opts) {
2241
2243
  });
2242
2244
  return registry;
2243
2245
  }
2244
- // src/milky/config.ts
2245
- /**
2246
- * Milky 协议配置(zod schema,归属本包)
2247
- *
2248
- * 单一 TOML 的 `[accounts.milky]` 账号段(docs/protocols/milky.md §4):
2249
- * 单端口 HTTP 模型(/api + /event 同端口),`enabled` 缺省 false = 不启用。
2250
- */
2251
- /** Milky 配置 schema。 */
2252
2246
  const milkyConfigSchema = z.object({
2247
+ media: protocolMediaSchema.optional(),
2253
2248
  /** 启用开关(缺省 false:账号段存在但 enabled 未开 = 装配为空转)。 */
2254
2249
  enabled: z.boolean().default(false),
2255
2250
  /** HTTP 监听地址。 */
2256
2251
  host: z.string().min(1).default("127.0.0.1"),
2257
2252
  /** HTTP 监听端口(/api 与 /event 同端口)。 */
2258
2253
  port: z.number().int().min(0).max(65535).default(3001),
2259
- /** access_token(空 = 不校验,仅限内网)。 */
2254
+ /** access_token(仅数值回环监听可以省略)。 */
2260
2255
  token: z.string().default(""),
2261
2256
  /** /event 允许的连接形态(缺省两者都开)。 */
2262
2257
  eventModes: z.array(z.enum(["sse", "ws"])).default(["sse", "ws"]),
@@ -2264,6 +2259,8 @@ const milkyConfigSchema = z.object({
2264
2259
  webhooks: z.array(z.string().min(1)).default([]),
2265
2260
  /** 发送媒体 http(s) URI 下载缓存目录(缺省不下载 = http(s) 发送媒体不可用)。 */
2266
2261
  cacheDir: z.string().optional()
2262
+ }).superRefine((config, ctx) => {
2263
+ if (config.enabled) validateListenerToken(config.host, config.token, ctx, ["token"]);
2267
2264
  });
2268
2265
  // src/milky/enrichment.ts
2269
2266
  /** Milky 收链路异步回填器。 */
@@ -3129,19 +3126,6 @@ var MilkyInboundSysMsg = class {
3129
3126
  }
3130
3127
  };
3131
3128
  // src/milky/transport.ts
3132
- /**
3133
- * Milky 传输装配(单端口 HTTP:POST /api/:api + GET /event SSE + /event WS 升级
3134
- * + WebHook 主动推送,docs/protocols/milky.md §4)
3135
- *
3136
- * - HTTP API:HttpServer onPathRequest 分发 → 动作注册表 → 规范响应信封
3137
- * (200 ok / 200 failed(-400/-403/自定) / 401 鉴权 / 404 API 不存在(空 body)/
3138
- * 415 Content-Type)。
3139
- * - /event:onRawRequest 承接 SSE(createSseResponse,event: milky_event);
3140
- * onUpgrade 承接同端口 WS 升级(网络原语 下沉 network)。
3141
- * - WebHook:HttpClient(fire-and-forget POST,Authorization 头带 token)。
3142
- *
3143
- * 事件推送统一经 MilkyEventHub(注册到 EventBroadcaster,send → SSE/WS 客户端)。
3144
- */
3145
3129
  /** /event 路径(规范固定)。 */
3146
3130
  const EVENT_PATH = "/event";
3147
3131
  /** /api/ 前缀 + 动作名(小写字母开头,小写/数字/下划线)。 */
@@ -3156,7 +3140,7 @@ var MilkyEventHub = class {
3156
3140
  sseClients = /* @__PURE__ */ new Set();
3157
3141
  sockets = /* @__PURE__ */ new Set();
3158
3142
  /** 把 /event 的 SSE(onRawRequest)与 WS 升级(onUpgrade)挂到 HTTP server。 */
3159
- attachTo(server, config) {
3143
+ attachTo(server, config, authorize, logger) {
3160
3144
  server.onRawRequest = (ctx) => {
3161
3145
  if (ctx.path !== EVENT_PATH || ctx.method !== "GET") return;
3162
3146
  if (!config.eventModes.includes("sse")) return new Response("event mode sse disabled", { status: 404 });
@@ -3168,13 +3152,22 @@ var MilkyEventHub = class {
3168
3152
  });
3169
3153
  };
3170
3154
  server.onUpgrade = (req, accept, reject) => {
3171
- if (pathnameOf(req.url) !== EVENT_PATH) return;
3155
+ const target = URL.parse(req.url, "http://localhost");
3156
+ if (target === null) {
3157
+ logger?.debug({ category: "invalid_upgrade_target" }, "milky: 升级目标解析失败");
3158
+ reject(400);
3159
+ return;
3160
+ }
3161
+ if (target.pathname !== EVENT_PATH) {
3162
+ reject(404);
3163
+ return;
3164
+ }
3172
3165
  if (!config.eventModes.includes("ws")) {
3173
- reject(404, "event mode ws disabled");
3166
+ reject(404);
3174
3167
  return;
3175
3168
  }
3176
- if (config.token !== "" && !matchTokenCredential(req, config.token, { allowQueryToken: true })) {
3177
- reject(401, "unauthorized");
3169
+ if (authorize && !authorize(req)) {
3170
+ reject(401);
3178
3171
  return;
3179
3172
  }
3180
3173
  accept((socket) => {
@@ -3209,11 +3202,8 @@ function assembleMilkyTransports(opts) {
3209
3202
  const token = config.token;
3210
3203
  const authorize = createTokenAuthorize(token, {
3211
3204
  allowQueryToken: true,
3212
- onQueryParseError: (url, err) => {
3213
- logger?.debug({
3214
- url,
3215
- error: errorMessage(err)
3216
- }, "milky: 鉴权 URL 解析失败,按未授权拒绝");
3205
+ onQueryParseError: () => {
3206
+ logger?.debug({ category: "invalid_auth_target" }, "milky: 鉴权 URL 解析失败,按未授权拒绝");
3217
3207
  }
3218
3208
  });
3219
3209
  const server = new HttpServer({
@@ -3221,20 +3211,20 @@ function assembleMilkyTransports(opts) {
3221
3211
  port: config.port,
3222
3212
  ...authorize !== void 0 ? { authorize } : {}
3223
3213
  });
3224
- hub.attachTo(server, config);
3214
+ hub.attachTo(server, config, authorize, logger);
3225
3215
  server.onPathRequest = (ctx, req, respond) => {
3226
3216
  handleMilkyHttpRequest(ctx, req, respond, registry, logger);
3227
3217
  };
3228
3218
  const adapters = [server, hub];
3229
- for (const url of config.webhooks) {
3219
+ for (const [index, url] of config.webhooks.entries()) {
3230
3220
  const client = new HttpClient({
3231
3221
  url,
3232
3222
  ...token !== "" ? { headers: { authorization: `${BEARER_PREFIX}${token}` } } : {},
3233
3223
  timeoutMs: 5e3,
3234
- onError: (err) => {
3224
+ onError: () => {
3235
3225
  logger?.warn({
3236
- url,
3237
- err: String(err)
3226
+ category: "webhook_delivery_failed",
3227
+ index
3238
3228
  }, "milky: webhook 推送失败");
3239
3229
  }
3240
3230
  });
@@ -3290,10 +3280,10 @@ function handleMilkyHttpRequest(ctx, req, respond, registry, logger) {
3290
3280
  data: null,
3291
3281
  message: result.message
3292
3282
  });
3293
- }).catch((err) => {
3283
+ }).catch(() => {
3294
3284
  logger?.warn({
3295
- path: ctx.path,
3296
- error: errorMessage(err)
3285
+ path: "/api/:api",
3286
+ category: "action_dispatch_failed"
3297
3287
  }, "milky: 动作分发异常,已回 -500");
3298
3288
  respond({
3299
3289
  status: "failed",
@@ -3303,14 +3293,6 @@ function handleMilkyHttpRequest(ctx, req, respond, registry, logger) {
3303
3293
  });
3304
3294
  });
3305
3295
  }
3306
- /** URL 路径部分(无 scheme 相对 url 容错)。 */
3307
- function pathnameOf(url) {
3308
- try {
3309
- return new URL(url, "http://localhost").pathname;
3310
- } catch {
3311
- return url.split("?")[0] ?? "";
3312
- }
3313
- }
3314
3296
  // src/milky/adapter.ts
3315
3297
  var NapukettoMilkyAdapter = class extends BaseProtocolAdapter {
3316
3298
  protocol = "milky";
@@ -3336,7 +3318,7 @@ var NapukettoMilkyAdapter = class extends BaseProtocolAdapter {
3336
3318
  hooks
3337
3319
  });
3338
3320
  this.calibLogger = opts.logger;
3339
- this.api = new MilkyApi(opts, this.seqIndex);
3321
+ this.api = new MilkyApi(opts, this.seqIndex, () => config.get?.()?.media?.outboundPolicy);
3340
3322
  const base = {
3341
3323
  api: this.api,
3342
3324
  seqIndex: this.seqIndex,
@@ -2,5 +2,5 @@
2
2
  * OneBot 11 协议适配器(当前主战场)
3
3
  * 公共面:类型 + 动作注册表 + 配置 schema + 翻译层(adapter.ts 于 打通 kernel 事件后接入)。
4
4
  */
5
- import { $ as OB11MessageInfo, A as serializeCqParts, B as canonicalToCqMessage, C as ob11ConfigSchema, D as escapeCqParam, E as encodeCqCode, F as ob11ErrorCodeMap, G as CurrentTalkative, H as cqMessageToCanonical, I as OneBotApi, J as GroupInfo, K as FriendInfo, L as OneBotApiOptions, M as Ob11ActionDeps, N as createOb11ActionRegistry, O as escapeCqText, P as AtAllRemainInfo, Q as OB11Message, R as OneBotSystemOptions, S as OB11Config, T as CqCode, U as cqMessageToSegments, V as canonicalToSegments, W as segmentsToCanonical, X as HonorMember, Y as GroupMemberInfo, Z as LoginInfo, _ as OB11GroupMessageEvent, a as assembleOb11Transports, at as VersionInfo, b as OB11BaseEvent, c as OB11Event, d as OB11RequestEvent, et as OB11MessageSegment, f as OB11NoticeEvent, g as OB11Status, h as OB11MetaEvent, i as Ob11TransportSet, it as StrangerInfo, j as unescapeCqText, k as parseCqMessage, l as OB11FriendRequestEvent, m as OB11LifecycleMetaEvent, n as Ob11OutboundTransport, nt as Sender, o as NapukettoOneBot11Adapter, p as OB11HeartbeatMetaEvent, q as GroupHonorInfo, r as Ob11OutboundWsReconnect, rt as Sex, s as OneBot11AdapterOptions, t as AssembleOb11TransportsOptions, tt as OB11Return, u as OB11GroupRequestEvent, v as OB11MessageEvent, w as segmentsToCqMessage, x as OB11PostType, y as OB11PrivateMessageEvent, z as MessageUnique } from "../index-DrPCnj64.mjs";
5
+ import { $ as OB11MessageInfo, A as serializeCqParts, B as canonicalToCqMessage, C as ob11ConfigSchema, D as escapeCqParam, E as encodeCqCode, F as ob11ErrorCodeMap, G as CurrentTalkative, H as cqMessageToCanonical, I as OneBotApi, J as GroupInfo, K as FriendInfo, L as OneBotApiOptions, M as Ob11ActionDeps, N as createOb11ActionRegistry, O as escapeCqText, P as AtAllRemainInfo, Q as OB11Message, R as OneBotSystemOptions, S as OB11Config, T as CqCode, U as cqMessageToSegments, V as canonicalToSegments, W as segmentsToCanonical, X as HonorMember, Y as GroupMemberInfo, Z as LoginInfo, _ as OB11GroupMessageEvent, a as assembleOb11Transports, at as VersionInfo, b as OB11BaseEvent, c as OB11Event, d as OB11RequestEvent, et as OB11MessageSegment, f as OB11NoticeEvent, g as OB11Status, h as OB11MetaEvent, i as Ob11TransportSet, it as StrangerInfo, j as unescapeCqText, k as parseCqMessage, l as OB11FriendRequestEvent, m as OB11LifecycleMetaEvent, n as Ob11OutboundTransport, nt as Sender, o as NapukettoOneBot11Adapter, p as OB11HeartbeatMetaEvent, q as GroupHonorInfo, r as Ob11OutboundWsReconnect, rt as Sex, s as OneBot11AdapterOptions, t as AssembleOb11TransportsOptions, tt as OB11Return, u as OB11GroupRequestEvent, v as OB11MessageEvent, w as segmentsToCqMessage, x as OB11PostType, y as OB11PrivateMessageEvent, z as MessageUnique } from "../index-CufnIU9v.mjs";
6
6
  export { type AssembleOb11TransportsOptions, type AtAllRemainInfo, type CqCode, type CurrentTalkative, type FriendInfo, type GroupHonorInfo, type GroupInfo, type GroupMemberInfo, type HonorMember, type LoginInfo, MessageUnique, NapukettoOneBot11Adapter, type OB11BaseEvent, type OB11Config, type OB11Event, type OB11FriendRequestEvent, type OB11GroupMessageEvent, type OB11GroupRequestEvent, type OB11HeartbeatMetaEvent, type OB11LifecycleMetaEvent, type OB11Message, type OB11MessageEvent, type OB11MessageInfo, type OB11MessageSegment, type OB11MetaEvent, type OB11NoticeEvent, type OB11PostType, type OB11PrivateMessageEvent, type OB11RequestEvent, type OB11Return, type OB11Status, type Ob11ActionDeps, type Ob11OutboundTransport, type Ob11OutboundWsReconnect, type Ob11TransportSet, type OneBot11AdapterOptions, OneBotApi, type OneBotApiOptions, type OneBotSystemOptions, type Sender, type Sex, type StrangerInfo, type VersionInfo, assembleOb11Transports, canonicalToCqMessage, canonicalToSegments, cqMessageToCanonical, cqMessageToSegments, createOb11ActionRegistry, encodeCqCode, escapeCqParam, escapeCqText, ob11ConfigSchema, ob11ErrorCodeMap, parseCqMessage, segmentsToCanonical, segmentsToCqMessage, serializeCqParts, unescapeCqText };
@@ -1 +1 @@
1
- export { y as MessageUnique, t as NapukettoOneBot11Adapter, r as OneBotApi, n as assembleOb11Transports, a as canonicalToCqMessage, o as canonicalToSegments, s as cqMessageToCanonical, c as cqMessageToSegments, i as createOb11ActionRegistry, f as encodeCqCode, p as escapeCqParam, m as escapeCqText, u as ob11ConfigSchema, v as ob11ErrorCodeMap, h as parseCqMessage, l as segmentsToCanonical, d as segmentsToCqMessage, g as serializeCqParts, _ as unescapeCqText } from "../onebot11-CUK6blMn.mjs";
1
+ export { y as MessageUnique, t as NapukettoOneBot11Adapter, r as OneBotApi, n as assembleOb11Transports, a as canonicalToCqMessage, o as canonicalToSegments, s as cqMessageToCanonical, c as cqMessageToSegments, i as createOb11ActionRegistry, f as encodeCqCode, p as escapeCqParam, m as escapeCqText, u as ob11ConfigSchema, v as ob11ErrorCodeMap, h as parseCqMessage, l as segmentsToCanonical, d as segmentsToCqMessage, g as serializeCqParts, _ as unescapeCqText } from "../onebot11-BW56Dqc6.mjs";
@@ -1,5 +1,5 @@
1
- import { a as resolveProtocolConfig, d as runAction, i as BaseProtocolAdapter, o as BEARER_PREFIX, r as createServerSchema, s as createTokenAuthorize, u as ActionRegistry } from "./framework-BbtmlUXJ.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";
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 { _ as withMediaScope, a as logEventFailure, c as protocolMediaSchema, d as fileUriToPath, f as mediaDownloader, g as protectMediaPath, h as cacheMediaFile, i as hasGrayTip, l as downloadProtocolMedia, m as MediaCache, o as sliceRaw, p as prepareVideoElements, r as firstUntranslatedGrayTip, s as truncRaw, t as collectGrayTipUids, u as ensureSilk } from "./gray-tip-BtiJls6z.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";
@@ -7,7 +7,7 @@ import { HttpClient, HttpServer, WsClient, WsServer } from "@napuketto/network";
7
7
  import { z } from "zod";
8
8
  import { existsSync } from "node:fs";
9
9
  import { join } from "node:path";
10
- import { downloadUrl, inferExtension } from "@napuketto/media";
10
+ import { inferExtension } from "@napuketto/media";
11
11
  // src/onebot11/helper/message-unique.ts
12
12
  /** OB11 message_id 上限(int32 max = 0x7FFF_FFFF)。 */
13
13
  const INT32_MAX = 2147483647;
@@ -1421,8 +1421,8 @@ const wsReverseSchema = z.object({
1421
1421
  /** WS ping 间隔(毫秒)。 */
1422
1422
  heartbeatInterval: z.number().int().default(DEFAULT_WS_HEARTBEAT_MS)
1423
1423
  });
1424
- /** OB11 配置 schema。 */
1425
1424
  const ob11ConfigSchema = z.object({
1425
+ media: protocolMediaSchema.optional(),
1426
1426
  /** 鉴权 token(全局默认,实例未指定时继承)。 */
1427
1427
  token: z.string().optional(),
1428
1428
  /** 心跳 meta 事件间隔(毫秒),0 关闭心跳。 */
@@ -1445,7 +1445,7 @@ const ob11ConfigSchema = z.object({
1445
1445
  wsServers: z.array(wsServerSchema).default([]),
1446
1446
  /** 正向 WS client 列表。 */
1447
1447
  wsReverseUrls: z.array(wsReverseSchema).default([])
1448
- });
1448
+ }).superRefine(validateServerTokens);
1449
1449
  // src/onebot11/helper/data.ts
1450
1450
  /** canonical 元素数组 → OB11 segment 数组(无法表达的元素静默跳过)。 */
1451
1451
  function canonicalToSegments(elements) {
@@ -2122,7 +2122,7 @@ function createHistoryActions(api) {
2122
2122
  * downloadRichMedia)。message_id 反查 → fetchMsgsByMsgId → 找 PIC/PTT 元素:
2123
2123
  * - 本地文件解析:NT 相对路径(sourcePath/filePath)按 mediaBaseDir(QQ NT
2124
2124
  * global 目录)解析为绝对路径,命中磁盘即返回 file
2125
- * - 图片主动下载:本地未命中且有 picUrl → @napuketto/media downloadUrl 落
2125
+ * - 图片主动下载:本地未命中且有 picUrl → 按媒体出站策略下载落
2126
2126
  * cacheDir/media/,返回 file(绝对路径)+ url + file_size/file_name
2127
2127
  * - 语音主动下载:本地未命中 → kernel MsgApi.downloadPtt(原生
2128
2128
  * downloadRichMedia + 轮询元素回查)→ filePath 落盘后返回绝对路径;
@@ -2156,13 +2156,10 @@ async function downloadImageToCache(url, deps) {
2156
2156
  if (cacheDir === void 0 || cacheDir === "") return null;
2157
2157
  try {
2158
2158
  return await cacheMediaFile(cacheDir, inferExtension(null, url), async (dest) => {
2159
- await downloadUrl(url, dest);
2159
+ await mediaDownloader(deps.getMediaOutboundPolicy?.())(url, dest);
2160
2160
  }, "reference");
2161
2161
  } catch (err) {
2162
- deps.logger?.warn({
2163
- url,
2164
- error: errorMessage(err)
2165
- }, "ob11: 图片主动下载失败,get_image 退原始 url");
2162
+ deps.logger?.warn({ error: errorMessage(err) }, "ob11: 图片主动下载失败,get_image 退原始 url");
2166
2163
  return null;
2167
2164
  }
2168
2165
  }
@@ -2529,10 +2526,14 @@ const setQQAvatarSchema = z.object({
2529
2526
  /** 本地路径(URL 需先下载,由装配方 cacheDir 支持)。 */
2530
2527
  file: z.string() });
2531
2528
  /** URL 头像下载到缓存目录(cacheDir 缺省抛错)。 */
2532
- async function downloadAvatarToCache(url, cacheDir) {
2529
+ async function downloadAvatarToCache(url, api) {
2530
+ const { cacheDir } = api;
2533
2531
  if (cacheDir === void 0 || cacheDir === "") throw kernelError("set_qq_avatar 处理 URL 需要缓存目录(装配方未注入)", "INVALID_STATE");
2534
2532
  return await cacheMediaFile(cacheDir, inferExtension(null, url), async (path) => {
2535
- await downloadBufferToFile(url, path, void 0, "头像下载失败");
2533
+ await downloadProtocolMedia(url, path, {
2534
+ outboundPolicy: api.getMediaOutboundPolicy?.(),
2535
+ errorLabel: "头像下载失败"
2536
+ });
2536
2537
  });
2537
2538
  }
2538
2539
  /**
@@ -2606,7 +2607,7 @@ function createSystemAccountActions(api) {
2606
2607
  schema: setQQAvatarSchema,
2607
2608
  handle: async (payload) => {
2608
2609
  let filePath = payload.file;
2609
- if (URL_PREFIX.test(filePath)) filePath = await downloadAvatarToCache(filePath, api.cacheDir);
2610
+ if (URL_PREFIX.test(filePath)) filePath = await downloadAvatarToCache(filePath, api);
2610
2611
  if (!existsSync(filePath)) throw kernelError(`头像文件不存在: ${filePath}`, "NOT_FOUND");
2611
2612
  await api.profileApi.setHeader(await protectMediaPath(filePath));
2612
2613
  return null;
@@ -2618,8 +2619,7 @@ function createSystemAccountActions(api) {
2618
2619
  /**
2619
2620
  * 文件收发域动作
2620
2621
  *
2621
- * - download_file:url → fetch 下载 → 存 cacheDir(缺省抛错)→ 返回
2622
- * { file }。文件名:download-<timestamp>-<basename>(headers 等扩展字段忽略)
2622
+ * - download_file:按媒体出站策略下载到 cacheDir 的独立缓存文件,返回 { file }。
2623
2623
  * - upload_group_file / upload_private_file——**闪传通道**
2624
2624
  *
2625
2625
  * ⚠️ 语义降级(探测依据见 kernel design §15):
@@ -2675,10 +2675,11 @@ function createSystemFileActions(api) {
2675
2675
  handle: async (payload) => {
2676
2676
  const { cacheDir } = api;
2677
2677
  if (cacheDir === void 0 || cacheDir === "") throw kernelError("download_file 未配置缓存目录(装配方未注入)", "INVALID_STATE");
2678
- const init = {};
2679
- if (payload.headers !== void 0) init.headers = payload.headers;
2680
2678
  return { file: await cacheMediaFile(cacheDir, inferExtension(null, payload.url), async (path) => {
2681
- await downloadBufferToFile(payload.url, path, init);
2679
+ await downloadProtocolMedia(payload.url, path, {
2680
+ outboundPolicy: api.getMediaOutboundPolicy?.(),
2681
+ headers: payload.headers
2682
+ });
2682
2683
  }, "reference") };
2683
2684
  }
2684
2685
  }),
@@ -2926,23 +2927,6 @@ function createOb11ActionRegistry(deps) {
2926
2927
  return registry;
2927
2928
  }
2928
2929
  // src/internal/infra/outbound-open.ts
2929
- /**
2930
- * 出向传输首连容错(issue #144)
2931
- *
2932
- * 背景:`network.WsClient.open()` 的契约是「首连失败即 reject,不自动重试」
2933
- * (重连只覆盖已建立连接后的断线,见 `WsClient.onClose`)。协议装配层若直接
2934
- * `await client.open()`,对端 WS 服务暂时未启动/不可达(ECONNREFUSED、
2935
- * ENOTFOUND host.docker.internal)就会让整个 `startProtocols` 抛错 →
2936
- * `self-host` exit 1,已登录成功的 QQ 宿主被一个外部服务拖死。
2937
- *
2938
- * 本模块在 adapter 层补足容错:首连失败只记 warn,并在后台按指数退避重试,
2939
- * 不阻塞协议装配、不影响宿主运行;`stop()` 时经返回的取消函数清掉定时器。
2940
- * 底层 `WsClient.open()` 失败语义保持不变(network 单测契约不动)。
2941
- *
2942
- * 退避从配置的 `reconnectDelayMs` 起按 2 倍递增并封顶(60s),与 supervisor
2943
- * 的子进程重启退避同一思路;连接建立后的断线仍由 `WsClient` 自己的 reconnect
2944
- * 策略处理,两者不重叠。
2945
- */
2946
2930
  /** 后台重连延迟上限(毫秒)。 */
2947
2931
  const MAX_RETRY_DELAY_MS = 6e4;
2948
2932
  /**
@@ -2975,10 +2959,10 @@ function openOutboundWithRetry(transport, opts) {
2975
2959
  if (stopped) return;
2976
2960
  try {
2977
2961
  await transport.open();
2978
- } catch (err) {
2962
+ } catch {
2979
2963
  if (stopped) return;
2980
2964
  opts.logger?.warn({
2981
- err: errorMessage(err),
2965
+ category: "outbound_open_failed",
2982
2966
  label: opts.label,
2983
2967
  retry: attempt + 1
2984
2968
  }, "出向传输连接失败,后台按重连策略重试(不影响宿主运行)");
@@ -2987,9 +2971,9 @@ function openOutboundWithRetry(transport, opts) {
2987
2971
  }
2988
2972
  if (stopped) try {
2989
2973
  await transport.close();
2990
- } catch (err) {
2974
+ } catch {
2991
2975
  opts.logger?.warn({
2992
- err: errorMessage(err),
2976
+ category: "outbound_close_failed",
2993
2977
  label: opts.label
2994
2978
  }, "取消后关闭出向传输失败");
2995
2979
  }
@@ -3010,6 +2994,7 @@ function openOutboundWithRetry(transport, opts) {
3010
2994
  */
3011
2995
  var OneBotApi = class {
3012
2996
  mediaCache;
2997
+ getMediaOutboundPolicy;
3013
2998
  /** kernel 消息 API(send_msg 等消息类动作用)。 */
3014
2999
  msgApi;
3015
3000
  /** kernel 群 API。 */
@@ -3052,7 +3037,8 @@ var OneBotApi = class {
3052
3037
  restart;
3053
3038
  /** 降级分支可观测出口(缺省静默)。 */
3054
3039
  logger;
3055
- constructor(opts) {
3040
+ constructor(opts, getMediaOutboundPolicy) {
3041
+ this.getMediaOutboundPolicy = getMediaOutboundPolicy;
3056
3042
  this.mediaCache = new MediaCache({
3057
3043
  root: opts.system?.cacheDir,
3058
3044
  logger: opts.logger
@@ -3834,7 +3820,7 @@ function assembleHttpPosts(config, selfUin, transports, outbound) {
3834
3820
  }
3835
3821
  /** 装配正向 WS client 列表(双向,心跳 + 重连 + 证书选项)。 */
3836
3822
  function assembleWsReverses(config, selfUin, handleRequest, transports, outbound) {
3837
- for (const item of config.wsReverseUrls) if (item.enabled && item.url !== void 0) {
3823
+ for (const [index, item] of config.wsReverseUrls.entries()) if (item.enabled && item.url !== void 0) {
3838
3824
  const headers = {
3839
3825
  ...oneBotClientHeaders(selfUin),
3840
3826
  ...authorizeHeader(item.token ?? config.token) ?? {}
@@ -3857,7 +3843,7 @@ function assembleWsReverses(config, selfUin, handleRequest, transports, outbound
3857
3843
  outbound.push({
3858
3844
  transport: client,
3859
3845
  wsReconnect: {
3860
- url: item.url,
3846
+ index,
3861
3847
  delayMs: item.reconnectDelayMs,
3862
3848
  ...item.maxReconnectAttempts !== void 0 ? { maxAttempts: item.maxReconnectAttempts } : {}
3863
3849
  }
@@ -3900,7 +3886,7 @@ var NapukettoOneBot11Adapter = class extends BaseProtocolAdapter {
3900
3886
  });
3901
3887
  this.selfUin = opts.self.uin;
3902
3888
  this.logger = opts.logger;
3903
- this.oneBotApi = new OneBotApi(opts);
3889
+ this.oneBotApi = new OneBotApi(opts, () => config.get?.()?.media?.outboundPolicy);
3904
3890
  this.pipeline = new Ob11EventPipeline({
3905
3891
  selfUin: this.selfUin,
3906
3892
  api: this.oneBotApi,
@@ -3978,7 +3964,7 @@ var NapukettoOneBot11Adapter = class extends BaseProtocolAdapter {
3978
3964
  continue;
3979
3965
  }
3980
3966
  this.outboundCancels.push(openOutboundWithRetry(item.transport, {
3981
- label: `onebot11 正向 WS ${reconnect.url}`,
3967
+ label: `onebot11 wsReverseUrls[${reconnect.index}]`,
3982
3968
  delayMs: reconnect.delayMs,
3983
3969
  ...reconnect.maxAttempts !== void 0 ? { maxAttempts: reconnect.maxAttempts } : {},
3984
3970
  ...this.logger !== void 0 ? { logger: this.logger } : {}
@@ -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-tljZ0fmt.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-CX7UKc6W.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-CDxpqL3l.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-Cetkw86t.mjs";
@@ -1,5 +1,5 @@
1
- import { a as resolveProtocolConfig, d as runAction, i as BaseProtocolAdapter, l as tokenEquals, r as createServerSchema, s as createTokenAuthorize, u as ActionRegistry } from "./framework-BbtmlUXJ.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";
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 { _ as withMediaScope, a as logEventFailure, c as protocolMediaSchema, g as protectMediaPath, h as cacheMediaFile, l as downloadProtocolMedia, m as MediaCache, t as collectGrayTipUids, u as ensureSilk } from "./gray-tip-BtiJls6z.mjs";
3
3
  import { c as MS_TO_SEC, h as toUinString, i as toUnixSeconds, r as subscribeRawMessages } from "./raw-message-DU8YOhLV.mjs";
4
4
  import { ChatType, GrayTipSubType, NTGroupRequestOperateTypes, TipGroupElementType, isRecord, kernelError, toCanonicalElements } from "@napuketto/kernel";
5
5
  import { HttpServer, WsServer, isWsOpen, sendWsText } from "@napuketto/network";
@@ -21,8 +21,8 @@ const DEFAULT_WS_PORT = 5501;
21
21
  const httpServerSchema = createServerSchema(DEFAULT_HTTP_PORT);
22
22
  /** WS 事件服务实例(/v1/events 信令,第三方 SDK 连入)。 */
23
23
  const wsServerSchema = createServerSchema(DEFAULT_WS_PORT);
24
- /** Satori 配置 schema。 */
25
24
  const satoriConfigSchema = z.object({
25
+ media: protocolMediaSchema.optional(),
26
26
  /** 鉴权 token(全局默认,实例未指定时继承)。 */
27
27
  token: z.string().optional(),
28
28
  /** 媒体资源(img/audio/video/file)下载缓存目录。 */
@@ -31,7 +31,7 @@ const satoriConfigSchema = z.object({
31
31
  httpServers: z.array(httpServerSchema).default([]),
32
32
  /** WS 事件服务列表。 */
33
33
  wsServers: z.array(wsServerSchema).default([])
34
- });
34
+ }).superRefine(validateServerTokens);
35
35
  // src/satori/helper/error.ts
36
36
  /** KernelErrorCode → HTTP 状态码映射表。 */
37
37
  const satoriHttpStatusMap = {
@@ -856,8 +856,7 @@ function createLoginActions(deps) {
856
856
  * Satori 发方向资源处理(从 element-convert.ts 拆分,FTA 优化)
857
857
  *
858
858
  * - resolveAsset:internal: 路径 / http(s) 下载 / 本地路径原样
859
- * - ensureSilk 已上移到 adapter core(core/media.ts,onebot11/satori 共用)
860
- * - 下载落盘统一走 shared/media.ts 的 downloadBufferToFile(异步 I/O 单一入口)
859
+ * - HTTP(S) 下载遵循当前协议配置的媒体出站策略。
861
860
  */
862
861
  /** internal:{platform}/{user.id}/{path} → 本地路径(取 _tmp 之后的路径,回落 cacheDir)。 */
863
862
  function resolveInternalPath(src) {
@@ -884,23 +883,22 @@ function assetFileName(src) {
884
883
  * - http(s):// → 下载到 cacheDir
885
884
  * - 其他 → 视为本地路径原样返回
886
885
  */
887
- async function resolveAsset(src, cacheDir) {
886
+ async function resolveAsset(src, cacheDir, outboundPolicy) {
888
887
  if (src.startsWith("internal:")) return await protectMediaPath(resolveInternalPath(src));
889
- if (HTTP_URL_RE.test(src)) return downloadAsset(src, cacheDir);
890
- return await protectMediaPath(src);
891
- }
892
- /** 下载 URL 资源到缓存目录(返回本地路径)。 */
893
- async function downloadAsset(url, cacheDir) {
894
- return await cacheMediaFile(cacheDir, inferExtension(null, url), async (path) => {
895
- await downloadBufferToFile(url, path, void 0, "下载资源失败");
888
+ if (HTTP_URL_RE.test(src)) return await cacheMediaFile(cacheDir, inferExtension(null, src), async (path) => {
889
+ await downloadProtocolMedia(src, path, {
890
+ outboundPolicy,
891
+ errorLabel: "下载资源失败"
892
+ });
896
893
  });
894
+ return await protectMediaPath(src);
897
895
  }
898
896
  // src/satori/helper/element/media-convert.ts
899
897
  /** 解析元素媒体 src(空 → null 忽略),返回本地路径。 */
900
898
  async function resolveMediaSrc(el, deps) {
901
899
  const src = el.attrs?.["src"] ?? "";
902
900
  if (src === "") return null;
903
- return resolveAsset(src, deps.cacheDir);
901
+ return resolveAsset(src, deps.cacheDir, deps.outboundPolicy);
904
902
  }
905
903
  /** Satori img → canonical image。 */
906
904
  async function imgToCanonical(el, deps) {
@@ -1338,7 +1336,9 @@ var SatoriApi = class {
1338
1336
  * 规则区分,需从事件/查询回填——QQ 平台群号与用户 uin 同为数字)。
1339
1337
  */
1340
1338
  channelTypeCache = /* @__PURE__ */ new Map();
1341
- constructor(opts) {
1339
+ getMediaOutboundPolicy;
1340
+ constructor(opts, getMediaOutboundPolicy) {
1341
+ this.getMediaOutboundPolicy = getMediaOutboundPolicy;
1342
1342
  this.msgApi = opts.msgApi;
1343
1343
  this.groupApi = opts.groupApi;
1344
1344
  this.groupNotifyApi = opts.groupNotifyApi;
@@ -1397,7 +1397,8 @@ var SatoriApi = class {
1397
1397
  toCanonicalDeps() {
1398
1398
  return {
1399
1399
  uinToUid: (uins) => this.groupApi.uinToUid(uins),
1400
- cacheDir: this.cacheDir
1400
+ cacheDir: this.cacheDir,
1401
+ outboundPolicy: this.getMediaOutboundPolicy?.()
1401
1402
  };
1402
1403
  }
1403
1404
  };
@@ -1785,7 +1786,7 @@ var NapukettoSatoriAdapter = class extends BaseProtocolAdapter {
1785
1786
  }
1786
1787
  });
1787
1788
  this.msgChannel = opts.msgChannel;
1788
- this.api = new SatoriApi(opts);
1789
+ this.api = new SatoriApi(opts, () => config.get?.()?.media?.outboundPolicy);
1789
1790
  this.logger = opts.logger;
1790
1791
  this.registry = createSatoriActionRegistry({ api: this.api });
1791
1792
  }
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.18.22",
4
+ "version": "0.20.0",
5
5
  "type": "module",
6
6
  "description": "Protocol adapters (OneBot11 / Satori / KuroBot / Milky) for NapukettoQQ",
7
7
  "keywords": [
@@ -84,8 +84,8 @@
84
84
  },
85
85
  "dependencies": {
86
86
  "@napuketto/kernel": "^0.16.4",
87
- "@napuketto/media": "^0.2.3",
88
- "@napuketto/network": "^0.4.5",
87
+ "@napuketto/media": "^0.3.0",
88
+ "@napuketto/network": "^0.5.0",
89
89
  "zod": "^4.6.7"
90
90
  },
91
91
  "devDependencies": {