@zhin.js/adapter-milky 1.1.25 → 1.1.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,160 @@
1
1
  # @zhin.js/adapter-milky
2
2
 
3
+ ## 1.1.27
4
+
5
+ ### Patch Changes
6
+
7
+ - c606d51: 各适配器按平台能力上报入站发送者的 `sender.platform`(ADR 0056 §1),并在能力画像 `scene.platformStanding` 中声明:OneBot11、NapCat、Milky、ICQQ 群消息上报群主 / 管理员 / 成员;QQ 官方频道上报频道主 / 超级管理员与身份组;Discord 服务器频道上报所有者 / 管理员 / 成员、身份组与 snake*case 权限位;Telegram 群消息按 `getChatMember` 上报 creator / administrator / member / 已离开,以及管理员的 `can*\*` 权限;KOOK 服务器频道上报服务器主 / 管理员角色、角色列表与权限位;飞书、钉钉群消息上报群主 / 管理员 / 成员;Sandbox 把模拟角色作为平台身份上报,不再授予框架主人角色。Satori、Slack、OneBot12、企业微信、LINE 的事件不带可靠的成员身份,不上报。README 补充「成员身份」说明。
8
+
9
+ 机器人自身身份(`management.inspectSelfStanding` + 能力画像 `scene.selfStanding`,供 `bot:*` permit):ICQQ、OneBot11、NapCat、Milky 群(`get_group_member_info` self);QQ 官方群(`getBotState`)与频道(机器人频道成员身份组);Discord(`guild.members.me` 身份组与频道权限);Telegram(`getChatMember` bot);KOOK(`/v3/user/view` self 的服务器角色与权限位);飞书(`chat.get` 群主与 `bot_manager_id_list`)。钉钉没有对应接口,不声明。群管理类 Agent 工具补上 `bot:admin` / `bot:owner` / `bot-permission:*`,需要发言者是群管的平台操作改用 `platform:admin` 等。
10
+
11
+ - 53932e5: 修复平台身份 permit 与操作目标不一致的问题(ADR 0056 §5):`platform:*` / `platform-permission:*` / `bot:*` / `bot-permission:*` 按**当前会话**判定,但群管理工具此前接受模型传入的任意群 / 服务器 / 频道 ID,机器人同在 A、B 两群当管理员时,A 群管理员可让 Agent 在 B 群踢人。
12
+
13
+ - 目标改为取自当前会话、去掉目标 ID 入参(模型传入的 ID 被忽略):ICQQ(踢人、禁言、设管理员、头衔、公告、匿名;设精华校验消息属于本群)、Telegram(邀请链接、置顶 / 取消置顶、群描述、默认权限)、Discord(加 / 移除身份组、身份组列表、建子线程)、KOOK(黑名单、授予 / 撤销 / 创建 / 删除角色)、飞书(加成员、设 / 撤管理员、改群信息、解散群)、NapCat(群公告、删公告、头衔、群头像;精华消息校验属于本群)、OneBot11(头衔)、QQ 官方频道(身份组增删建与列表、子频道列表、成员详情;子频道详情只限本频道)。核心场景治理工具工厂(`createSceneManagementTools`)同样只作用于调用消息所在会话,没有会话时拒绝;Agent 侧同名工厂改用与核心一致的 `platform:<地位>` + `bot:<地位>`(此前误作 zhin 角色)。
14
+ - 钉钉群管理接口使用旧版 `chatid`(无法由当前会话推出),`dingtalk_add_chat_members` / `dingtalk_update_chat` 改为要求 zhin `owner`(`update_chat` 此前没有任何门禁);`dingtalk_create_chat` 改为要求 zhin `trusted`(`admin` / `owner` 亦满足),不再依赖钉钉从不上报的 `platform-permission:chat_owner`。
15
+ - Slack 不上报发言者平台身份,频道工具改用 zhin 角色并只作用于当前频道:话题、用途、邀请、置顶 / 取消置顶要求 `admin`,归档 / 恢复归档要求 `owner`;`PERMITS.md` 同步修正。
16
+ - Discord:加 / 移除身份组要求目标身份组低于发起者的最高身份组(服务器主豁免;托管身份组拒绝),低位 `manage_roles` 管理员不能借机器人给自己加更高身份组。平台权限统一为服务器级:机器人自身改读 `GuildMember.permissions`(不再用频道级 `permissionsFor`);Interactions 模式的位域含频道覆盖,只上报不能被频道覆盖的权限(管理员上报全部),并用最近一次交互的 `app_permissions` 上报机器人自身身份(同一口径,10 分钟内有效)。
17
+ - Telegram:`set_permissions` 改要求 `platform-permission:restrict_members`,`set_description` 改 `change_info`,`create_invite` 改 `invite_users`;发送者 `getChatMember` 并发合并为一次、失败负缓存 10 秒,收到 `chat_member` / `my_chat_member` 更新时以新状态覆盖缓存(默认 `allowedUpdates` 增加这两项);restricted 成员的个人 `can_*` 不再作为平台权限上报(与普通成员一致,只有管理员上报权限)。
18
+ - KOOK:服务器主与持有「管理员」位的成员(含机器人自身)展开为全部权限;并入「全体成员」(role_id 0)的基础权限。
19
+ - 飞书:`chat.get` 失败或未返回 `owner_id` 时发送者 / 机器人地位为未知(不再报确定的 `member` 并缓存 60 秒),失败负缓存 10 秒。
20
+ - QQ 官方:发送者平台身份只在频道子频道上报(群、单聊、频道私信不上报)。
21
+ - `AdapterIndex.selfStanding`:共享查询使用独立的 10 秒期限,调用方的 `signal` 只中止自己的等待,不再取消他人共享的查询或把结果缓存为未知;查询期间被 `invalidateSelfStanding` 失效时不写回旧结果。
22
+ - OneBot11 / NapCat / Milky:机器人自身身份不再永久记住首次 `get_login_info` 的账号(重连或换号后刷新;只为合并突发请求复用 5 秒,查询失败即丢弃)。
23
+ - 删除遗留导出(生成永不匹配的 permit 或已不再注册):`discordGroupPermitResolver` / `checkDiscordPlatformPermit` / `normalizeDiscordSenderForPermit`、`telegramGroupPermitResolver` / `checkTelegramPlatformPermit` / `normalizeTelegramChatMember`、`kookGroupPermitResolver` / `checkKookPlatformPermit` / `normalizeKookSenderForPermit` / `KookSenderInfo`、`larkGroupPermitResolver` / `checkLarkPlatformPermit` / `normalizeLarkSenderForPermit`、`slackGroupPermitResolver` / `checkSlackPlatformPermit` / `normalizeSlackSenderForPermit`、`dingtalkGroupPermitResolver` / `checkDingtalkPlatformPermit` / `normalizeDingtalkSenderForPermit`、`wecomGroupPermitResolver` / `checkWecomPlatformPermit` / `normalizeWecomSenderForPermit`、`qqGuildPermitResolver` / `checkQqPlatformPermit` / `normalizeQqGuildSenderForPermit`。permit 一律交给内置评估器(`@zhin.js/permission`),`platformPermit()` 仍保留;各适配器 `PERMITS.md` 按实际上报的字段重写。
24
+
25
+ - 57c6cdc: fix: 全仓审计修复
26
+
27
+ - kernel: 模板求值沙箱不再泄漏宿主对象——宿主函数的返回值与抛出的错误会重新包裹代理(`segments.map(x=>x).constructor.constructor(...)` 之前可拿到宿主 `Function`),并禁止通过代理写入/删除宿主属性。
28
+ - agent: exec 白名单正则按整体锚定(`git|npm` 不再匹配 `gitevil`);SSRF 主机名黑名单识别尾点形式(`localhost.`);Docker 沙箱 `always` 模式的 fail-closed 分支可被触达;声明缺失的 `chalk` 依赖。
29
+ - ai: 摘要按最新优先加载(超过 500 条时不再使用过期锚点);修复 `test` 脚本指向不存在的配置。
30
+ - cli: `ZHIN_LOG_LEVEL` 生效(修复运算符优先级);移除旧守护进程遗留的无引用进程辅助函数。
31
+ - logger: `formatCompact` 不再把 `config: 'yaml'`、`direction: 'in'` 这类非路径值改写成 `./yaml`。
32
+ - host-http: 未配置数据库时 `db:tables` 与有数据库时一致返回 `{ tables }`。
33
+ - a2a: 405 响应把 `Allow` 放进响应头。
34
+ - pagemanager: 内联进 `<script>` 的页面元数据转义 `<`。
35
+ - client: 事件历史请求失败时携带 HTTP 状态,token 失效可触发重新登录。
36
+ - scaffold-wizard / create-zhin-app: 修正适配器文档 URL 与模板里的 `@zhin.js/tool` 导入。
37
+ - adapter-wechat-mp: 签名比较改为常量时间。
38
+ - adapter-kook: 声明运行时依赖 `ws`。
39
+ - plugin-lottery: 遗漏值按最近一次出现计算;推送目标 schema 字段与实现一致(`endpointKey`)。
40
+ - plugin-code-runner: 语言校验改用自有属性判断。
41
+ - plugin-link-poster: 抓取前校验主机名白名单(修复 SSRF),超时覆盖响应体读取。
42
+ - 其余包:从 `files` 中移除不存在的目录。
43
+ - feature-kit / middleware: 修正 README 中层级错误的文档链接。
44
+
45
+ - e1fda87: fix: 按审计待审清单处理(安全、功能、清理)
46
+
47
+ **行为变更(升级前请阅读)**
48
+
49
+ - kernel / core / zhin.js:出站文本中的 `${…}` 不再用 `vm` 求值,只替换 `TemplateContext` 上能解析到值的属性路径(如 `${sender.name}`);表达式、函数调用、未知名字原样保留。整套 vm 沙箱(`evaluate` / `execute` / `compiler` / `getValueWithRuntime`)已移除。
50
+ - kernel / core / zhin.js:移除零引用的遗留导出——`Scheduler`、错误管理器与 `ZhinError` 子类、`compose`、`segment.from/toString`、AI 触发/准入函数、`@zhin.js/core/queue-im-field-contract`、`zhin.js/contexts`。
51
+ - agent:readonly 执行预设不再放行重定向、后台 `&`、进程替换、`find -delete/-exec`、`sed -i`、`sort -o`、`tee`、`xargs`、awk;curl/wget 校验每个 URL 与裸主机并识别更多上传参数;自定义 `execAllowlist` 中的只读命令带写入风险时改走审批。沙箱超时/取消会杀掉进程组或具名容器,默认镜像改为 `node:22-bookworm-slim` + `bash`。移除无生产调用的 `AuditLogger`、`AnomalyDetector`、旧 vision 回合等导出。
52
+ - ai:移除 `storage`、`FileStateCache`、`CostTracker`、`model-name-utils`、`./agent-step-checkpoint` 子路径、`ContextManager` 及旧压缩管线;延迟工具快照改为有界 LRU。
53
+ - cli:`zhin send` / `watch` / `schedule` 改为与运行中的 Host 通信(新增 `POST /message/send` 与 `/assistant/jobs` 写接口),`schedule` 不再支持离线改文件;移除 `zhin uninstall service`(用 `zhin service uninstall`)、`build --analyze`、`install -S`;`zhin stop` 杀不掉进程时保留 pid 文件并以非零退出;`runtime migrate` 新增 `verify`;未设置 `TZ` 时调度默认时区改为系统时区;不带 `ZHIN_SUPERVISOR_PID` 的进程被 init 接管后不再自行退出。
54
+ - schedule:后台 reconcile 出错不再产生未处理 rejection(新增 `onStoreError`);启动途中 `stop()` 不再遗留定时器。
55
+ - schema:元组校验与 `safeParse`、JSON Schema 一致(空数组不通过,缺省的可选元组为 `undefined`)。
56
+ - client / contract:删除无后端路由的 agent-stream API、未使用的 `definePage` 与旧 PageManager 类型;`@zhin.js/contract` 不再依赖 `@zhin.js/ai`;客户端收到 401 会清除已保存的凭据;安装/更新/卸载 RPC 默认超时 120 秒。
57
+ - a2a:流式响应中途出错写入 SSE error 并结束;未配置 token 的非生产环境只接受本机请求;任务存储有上限与过期;Mailbox 凭据回退与生产环境缺密钥检查修复。
58
+ - speech:`provider: openai` 不再套用 Ollama 的默认 host/model;识别语言改为可配置,不再写死 `zh`。
59
+ - adapter-lark:支持 `encryptKey` 加密事件解密。adapter-github:Device Flow 可取消、带超时并回复失败原因。adapter-wecom / dingtalk:请求加超时并校验 HTTP 状态。adapter-weixin-ilink:输入关闭期间暂停轮询。adapter-milky:SSE 支持 CRLF、缓冲上限与空闲重连。adapter-onebot-events:好友删除通知改为 `notice.friend.decrease`。
60
+ - plugin-group-suite:`teachAllowRegex` 默认关闭,正则安全检查更严格。plugin-qrcode:改为本地生成,回复 data URL 图片。plugin-rss / short-url / link-poster:拒绝解析到内网的地址;rss 修复条目每周重复推送;short-url 的 Console 创建改为真实调用 is.gd。plugin-lottery:按 `historyLimit` 同步。
61
+
62
+ **其余**
63
+
64
+ - host-http:插件市场详情加缓存与包名校验,SSE 回放容忍背压。host-http-contract:新增 `readTextBody()`,九个适配器改用它。
65
+ - pagemanager:页面外壳 importmap 升级到 React 19.2.8 / react-router 7.12.0。console-contract:`definePage` 接受 `description` / `group` / `parent` / `fullWidth`。
66
+ - command:进度提示本地化,匹配不再重复拷贝消息段。runtime:源码监听降级后退避重试原生监听。
67
+ - html-renderer:删除未接线的 `aiTextAsImage`。create-zhin-app / scaffold-wizard:移除不起作用的"全局安装 CLI"与运行时选择提示。
68
+ - 依赖声明清理、发布清单不再携带解析不到的 `src` 目录、移除未使用的 Skill 挂载、README 与示例配置按当前实现更正。
69
+
70
+ - 120e225: 聊天角色(ADR 0056,2026-11-12 修订):zhin 角色 owner / admin / trusted 分四级、只来自授予;发言者的平台身份与机器人自身的平台身份是独立维度,命令、Agent 工具 / 技能、中间件与按钮按三条维度共用一个评估器过滤。升级说明见 docs/migrations/chat-roles.md。
71
+
72
+ - zhin.js:实例首次启动把适配器 `master` / `trusted`、`endpoints[i].master|trusted` 与 `ai.trigger.masters|trusted` 迁入项目数据库 `chat_roles`(先记入 `.zhin/chat-roles-migration.json`,再从配置移除并记日志);之后配置再出现这些字段时启动报错并指向升级指南。平台身份不再映射为 zhin 角色:删除 `roles.mappings`(适配器块与 `endpoints[i].roles` 出现即启动报错)、`chat_role_mappings` 表与 Console `chat-roles.mappings` / `chat-roles.set-mappings`;`features.selfService.platformAdmins|roles|allowUsers` 删除;群内「功能」「角色」命令只认 zhin 角色,平台群主不再自动具备;聊天改配置、聊天重启、Agent 主人审批按 zhin `owner` 判断。
73
+ - @zhin.js/core(minor,破坏性):角色模型与解析移入 core(`ChatRoleService`、`createChatRoleSenderEnricher`),入站消息带 `sender.chatRole` 与归一的 `sender.platform`;删除 `SenderRole`、`senderRolesFromMessage`、`roleSatisfies` 等,`master` 改名 `owner`;删除映射规则 API(`createMappingChatRoleSource`、`DEFAULT_CHAT_ROLE_MAPPINGS` 等)与 `ChatRoleSource`;`createSenderEnricher` / `createConfigurationChatAuthorizer` 改为基于聊天角色。IM Runtime 为 PermissionHost 提供机器人自身身份(经 Adapter 索引缓存),机器人的角色变化事件使缓存失效;命令拒绝回复说明缺少的平台 / 机器人条件;`<Button permit>` 按点击者鉴权;场景治理工具工厂同时要求 `platform:*` 与 `bot:*`;`ai.trigger.masters|trusted` 删除。
74
+ - @zhin.js/permission(minor,破坏性):permit 语法 `owner` / `admin` / `trusted` / `role(...)`(zhin 角色)、`platform:owner|admin`、`platform-role:<id>`、`platform-permission:<name>`(发言者平台身份),新增 `bot:owner|admin`、`bot-role:<id>`、`bot-permission:<name>`(机器人自身平台身份,`PermissionSubject.bot`);`PermissionHost` 新增 `setBotStandingResolver`、`withBotStanding`、`firstDenied`,`checkAll` 可带 `source` 解析机器人身份;新增 `describeDeniedPermit`、`permitsNeedBotStanding`。删除 `role(master)`、`scene_admin`、`scene_owner`、`platform(adapter,perm)` 及 `registerPlatform`、`createSceneRolePlatformChecker`、`platformPermission`、`definePlatformPermission`,定义时报错并给出替代写法。
75
+ - @zhin.js/command(minor,破坏性):命令会话的发送者改为 `chatRole` / `platform`,不再从 metadata 读角色;`CONVERSATION_MANAGER_PERMIT` 改为 `admin`(平台群主不再自动满足);分发结果 `denied` 带 `denial`(第一条不满足的规则与原因);指令菜单只列出当前发送者在本会话可用的命令。
76
+ - @zhin.js/agent(minor,破坏性):危险工具、文件 / exec 策略、主人审批、Agent 回合主体只读 zhin 角色(`principal.roles` 只含展开的聊天角色,平台地位在 `principal.platform`);`SenderRole` → `PrincipalRole`,`SELF_CHANGE_MASTER_ROLE` → `SELF_CHANGE_OWNER_ROLE`;回合开始时读取机器人自身身份(`contextState.bot.platform`),按三条维度过滤 tool / skill / Agent 包后才披露,执行工具时再校验一次;群规「群主和管理员豁免」改为平台群主 / 管理员与 zhin `owner`。
77
+ - @zhin.js/feature-kit:`OperationSession.sender` 改为 `chatRole` / `platform`。
78
+ - @zhin.js/im-contract:新增 `PlatformStanding`、`SelfStandingRequest`、`standingFromMemberRole`。
79
+ - @zhin.js/adapter:入站 sender 可带 `platform`;账号管理命令需要聊天角色 `owner`;`EndpointManagement` 新增可选 `inspectSelfStanding`,能力画像新增 `scene.selfStanding`(声明即须实现),`AdapterIndex.selfStanding` / `invalidateSelfStanding` 按会话缓存机器人自身身份。
80
+ - @zhin.js/middleware:入站中间件可声明 `permit`,不满足时跳过该中间件(机器人身份只读缓存)。
81
+ - @zhin.js/tool:定义工具时拒绝已移除的 permit 写法。
82
+ - @zhin.js/ai:注释更新。
83
+ - @zhin.js/console-protocol:`chat-roles.list|grant|revoke`(`iam.manage`);`ConsoleChatRoleSource` 只有 `grant`。
84
+ - @zhin.js/runtime:Host 配置 Schema 删除 `features.selfService.platformAdmins|roles|allowUsers`。
85
+ - @zhin.js/testing:伪造消息与 `PluginTestKit` 用 `sender.chatRole` 声明测试身份。
86
+ - @zhin.js/scaffold-wizard:ICQQ 向导不再写 `master`,完成后提示在 Console 账号「角色」页签或聊天 `角色 授予` 设置 owner。
87
+ - 适配器:配置 Schema 删除 `master` / `trusted`(以及预览版的 `roles`);群管理类工具同时声明发言者条件与机器人条件(如 `platform:admin` + `bot:admin`、`bot-permission:manage_roles`),NapCat / OneBot11 工具不再使用已移除的 `platform(adapter,…)` 写法。
88
+ - 插件:内容审核以 `inbound.bypass`(permit 列表,默认 `owner` 或 `platform:admin`)取代 `masters` / `inbound.bypassMasters`;群管、音乐、日历、地震、B 站、轮盘赌的权限改用 zhin 角色,订阅类命令只认 zhin `admin` / `owner`。
89
+
90
+ - c2bbdcf: Console 访问控制(ADR 0049):用户、角色、会话、API 令牌与审计日志存入项目数据库,每个 Console RPC、`/api` 路由与 Host 鉴权的 WebSocket 都按 `@zhin.js/console-protocol` 的权限表放行,未登记的一律拒绝。
91
+
92
+ **破坏性变更**
93
+
94
+ - `http.tokens` 与演示模式(`scope: demo` / `user`)删除;配置里仍有 `http.tokens` 时 Host 拒绝启动。Host 配置 Schema 同步删除该字段。
95
+ - `http.token` 变为初始化令牌:只在创建第一个所有者之前有效,之后在所有接口上被拒绝。
96
+ - 未在 `CONSOLE_WS_PERMISSIONS` 登记、又使用 Host 鉴权的插件 WebSocket 不再接受 Console 账号;插件自己的 WebSocket 应改用 `ws(path, { auth: 'protocol' })` 并自行校验凭据(新增 `verifyProtocolAccessToken`、`isLoopbackAddress`)。
97
+ - OneBot 11 / 12、NapCat、Milky 的反向 WebSocket 改为只认适配器自己的 `access_token`;未配置 `access_token` 时只接受本机回环连接。
98
+ - `zhin doctor --live` 等改从 `ZHIN_CONSOLE_TOKEN` 读取 API 令牌(仍兼容 `ZHIN_HTTP_TOKEN`)。
99
+
100
+ **迁移步骤**(详见文档「升级到 Console 访问控制」)
101
+
102
+ 1. 升级后用 `http.token` 打开 Console 初始化向导创建第一个所有者,或运行 `zhin console init`(脚本:`zhin console init --yes --owner <名> --password-stdin`)。
103
+ 2. 删除配置里的 `http.tokens`,在 Console「访问控制」里为原来的令牌持有人创建用户并绑定角色(`viewer` / `operator` / `admin`);演示环境改用 `viewer` 账号。
104
+ 3. 自动化在 Console 签发 API 令牌,放进 `ZHIN_CONSOLE_TOKEN`。
105
+ 4. 从其他机器或容器连接的反向 WebSocket endpoint 补上 `access_token`。
106
+ 5. 忘记密码或所有者被锁时,停下 Host,用 `zhin console user passwd|enable|create` 离线恢复。
107
+
108
+ MCP / A2A 的 Bearer 访问同样接受用户 API 令牌(分别需要 `mcp.access`、`a2a.access`)。适配器与插件文档同步改为账号与角色的说法。
109
+
110
+ - 5cd9d3d: HTTP 路由契约改为 Web 标准 `Request` / `Response`(ADR 0054 §2,B1.0)
111
+
112
+ - host-http-contract:路由处理函数签名改为 `(request, context) => Response`,`context` 提供 `url`、`params`、`principal`、`remoteAddress`;新增 `readBodyBytes` / `readTextBody` / `readJsonBody`(带大小上限,超限先读完再报 413)、`jsonResponse` / `emptyResponse`、带背压的 `createResponseStream`(SSE、大文件下载)与 `WsConnection`。契约不再引用 `node:http` / `ws`。
113
+ - host-http:Node 服务器移到 `@zhin.js/host-http/node`(`createHttpHost`),负责 Node 请求与 `Request` / `Response` 的互转;认证结果经 `context.principal` 传给路由,删除旧的按请求取主体的辅助函数;未预期的异常只返回通用错误信息,细节写日志。
114
+ - runtime、mcp、a2a、gateway、zhin.js、calendar 插件与各适配器的 Webhook / 反向 WebSocket 路由迁移到新契约,行为不变。
115
+
116
+ - Updated dependencies [53932e5]
117
+ - Updated dependencies [57c6cdc]
118
+ - Updated dependencies [e1fda87]
119
+ - Updated dependencies [4e8ba38]
120
+ - Updated dependencies [a9c7a13]
121
+ - Updated dependencies [120e225]
122
+ - Updated dependencies [c2bbdcf]
123
+ - Updated dependencies [c2bbdcf]
124
+ - Updated dependencies [63595fc]
125
+ - Updated dependencies [fd055d2]
126
+ - Updated dependencies [4e8ba38]
127
+ - Updated dependencies [cc7a5f9]
128
+ - Updated dependencies [4e8ba38]
129
+ - Updated dependencies [f8bf684]
130
+ - Updated dependencies [e0bc008]
131
+ - Updated dependencies [5cd9d3d]
132
+ - Updated dependencies [5cd9d3d]
133
+ - Updated dependencies [c2bbdcf]
134
+ - Updated dependencies [f8bf684]
135
+ - Updated dependencies [663473b]
136
+ - Updated dependencies [c606d51]
137
+ - Updated dependencies [5cd9d3d]
138
+ - Updated dependencies [d655ef0]
139
+ - Updated dependencies [1e54b1e]
140
+ - @zhin.js/adapter@1.1.33
141
+ - @zhin.js/core@1.2.0
142
+ - @zhin.js/logger@1.1.3
143
+ - @zhin.js/host-http@1.2.0
144
+ - @zhin.js/feature-kit@1.1.16
145
+ - @zhin.js/console-contract@1.1.6
146
+ - @zhin.js/im-contract@1.1.14
147
+ - @zhin.js/page@1.1.18
148
+
149
+ ## 1.1.26
150
+
151
+ ### Patch Changes
152
+
153
+ - 0d76a7c: Overhaul Console interactive workbenches, platform-specific adapter account onboarding/login flows, DeclarativePageView visual/interactive capabilities, and official utility plugin Console pages.
154
+ - Updated dependencies [0d76a7c]
155
+ - @zhin.js/adapter@1.1.32
156
+ - @zhin.js/core@1.1.60
157
+
3
158
  ## 1.1.25
4
159
 
5
160
  ### Patch Changes
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 凉菜
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/PERMITS.md CHANGED
@@ -6,9 +6,9 @@
6
6
 
7
7
  ## Permit 词汇表
8
8
 
9
- | `platform(milky,…)` | 含义 |
9
+ | `platform-permission:…` | 含义 |
10
10
  |---------------------|------|
11
- | `scene_owner` | 群主 |
12
- | `scene_admin` | 群管理员(含群主) |
11
+ | `platform:owner` | 群主 |
12
+ | `platform:admin` | 群管理员(含群主) |
13
13
 
14
14
  与 OneBot QQ 系相同,使用 core 默认 checker。
package/README.md CHANGED
@@ -85,13 +85,12 @@ milky:
85
85
  | 类别 | 路径 |
86
86
  |------|------|
87
87
  | Permit 词汇 | `PERMITS.md` |
88
- | 技能说明 | `skills/milky/SKILL.md` |
89
88
 
90
89
  ## 文档链接
91
90
 
92
91
  - [Milky 快速开始](https://milky.ntqqrev.org/)
93
92
  - [Milky 通信](https://milky.ntqqrev.org/guide/communication)
94
- - [适配器概览](https://zhin.js.org/essentials/adapters)
93
+ - [适配器概览](https://zhin.js.org/adapters/)
95
94
 
96
95
  ## Console 页面
97
96
 
@@ -101,7 +100,7 @@ milky:
101
100
  - 经所属 Adapter 增删持久化账号、启停单个 Endpoint;凭据由 Host 加密仓储保存,不改启动 YAML 或 `.env`,不重启进程;
102
101
  - 如果适配器要求登录,页面会显示 LoginAssist 的扫码 / 滑块 / 设备确认待办;
103
102
 
104
- 读取需要 `milky:read`,写操作需要 `milky:write`;管理员 full token 不受限。页面里的「添加 endpoint」等价于原来的 `milky endpoint add`。
103
+ 读取需要 `milky:read`(`read` 级别,内置角色 `viewer` 及以上都有);增删改账号等写操作需要 `milky:write`(`operate` 级别,`operator` 及以上都有,绑定到本适配器的角色也算),首次迁移还需管理员身份;全局所有者不受限,见[插件权限的级别](https://zhin.js.org/console/#插件权限的级别)。页面里的「添加 endpoint」等价于原来的 `milky endpoint add`。
105
104
 
106
105
  ## 故障排查
107
106
 
@@ -115,3 +114,7 @@ milky:
115
114
  ## 许可证
116
115
 
117
116
  MIT License
117
+
118
+ ## 成员身份
119
+
120
+ 群消息的 `group_member.role`(`owner` / `admin` / `member`)归一为 `sender.platform.standing`;私聊、临时会话不上报。Milky 没有平台原生角色与权限位。能力画像:`group.scene.platformStanding = { standing: true }`。详见 [ADR 0056 §1](https://github.com/zhinjs/zhin/blob/main/docs/adr/0056-chat-roles.md)。
@@ -25,6 +25,9 @@ export default defineAdapter({
25
25
  },
26
26
  delivery: { send: true, proactive: true, spool: true },
27
27
  },
28
+ // ADR 0056 §1:群消息 group_member.role → sender.platform.standing。
29
+ // ADR 0056 §1:发言者与机器人自身的群内地位(get_group_member_info self,供 bot:* permit)。
30
+ group: { scene: { platformStanding: { standing: true }, selfStanding: { standing: true } } },
28
31
  },
29
32
  createAdapter: context => new MilkyAdapter(context),
30
33
  });
@@ -42,6 +42,9 @@ export default defineAdapter<MilkyEndpointConfig>({
42
42
  },
43
43
  delivery: { send: true, proactive: true, spool: true },
44
44
  },
45
+ // ADR 0056 §1:群消息 group_member.role → sender.platform.standing。
46
+ // ADR 0056 §1:发言者与机器人自身的群内地位(get_group_member_info self,供 bot:* permit)。
47
+ group: { scene: { platformStanding: { standing: true }, selfStanding: { standing: true } } },
45
48
  },
46
49
  createAdapter: context => new MilkyAdapter(context),
47
50
  });
@@ -2,9 +2,39 @@ export const milkyConsoleSpec = {
2
2
  adapterKey: 'milky',
3
3
  adapterDisplayName: 'Milky',
4
4
  fields: [
5
- { key: 'baseUrl', required: true, description: 'Milky HTTP API base URL' },
6
- { key: 'path', description: 'webhook / reverse-wss 路径', descriptionI18n: { en: 'Webhook / reverse-wss path' } },
7
- { key: 'access_token', env: true, description: 'Milky access token' },
5
+ {
6
+ key: 'baseUrl',
7
+ required: true,
8
+ label: 'Milky 服务地址',
9
+ labelI18n: { en: 'Milky Base URL' },
10
+ group: '连接模式',
11
+ groupI18n: { en: 'Connection Mode' },
12
+ placeholder: 'http://127.0.0.1:3000',
13
+ description: 'Milky HTTP API base URL',
14
+ descriptionI18n: { en: 'Milky HTTP API base URL' },
15
+ },
16
+ {
17
+ key: 'path',
18
+ label: '事件回调 / 反向 WS 路径',
19
+ labelI18n: { en: 'Webhook / Reverse WS Path' },
20
+ group: '连接模式',
21
+ groupI18n: { en: 'Connection Mode' },
22
+ placeholder: '/milky/event',
23
+ description: 'webhook / reverse-wss 路径',
24
+ descriptionI18n: { en: 'Webhook / reverse-wss path' },
25
+ },
26
+ {
27
+ key: 'access_token',
28
+ env: true,
29
+ label: 'Access Token (访问令牌)',
30
+ labelI18n: { en: 'Access Token' },
31
+ group: '安全认证',
32
+ groupI18n: { en: 'Authentication' },
33
+ placeholder: 'Milky 服务端配置的 Access Token',
34
+ placeholderI18n: { en: 'Access token configured on Milky server' },
35
+ description: 'Milky 接口鉴权令牌(Access Token)',
36
+ descriptionI18n: { en: 'Milky access token' },
37
+ },
8
38
  ],
9
39
  docsUrl: 'https://zhin.js.org/adapters/milky',
10
40
  readPermission: 'milky:read',
@@ -1,5 +1,42 @@
1
+ import { standingFromMemberRole } from '@zhin.js/im-contract';
2
+ /** How long one `get_login_info` answer is reused (bursts only; see inspectSelfStanding). */
3
+ const SELF_ID_TTL_MS = 5_000;
1
4
  export function createMilkyEndpointManagement(endpoint) {
5
+ // The login account can change across reconnects (or a different account on the same
6
+ // connection), so `get_login_info` is not remembered for the endpoint's lifetime: only briefly,
7
+ // to coalesce bursts, and never across a failed lookup.
8
+ let login;
9
+ const loginId = async (signal) => {
10
+ if (login && Date.now() - login.at < SELF_ID_TTL_MS)
11
+ return login.id;
12
+ login = undefined;
13
+ const info = asRecord(await endpoint.callApi({ action: 'get_login_info', signal }));
14
+ const id = info.uin ?? info.user_id;
15
+ const value = (typeof id === 'number' && id > 0) || (typeof id === 'string' && id.trim() !== '' && id !== '0') ? String(id) : undefined;
16
+ if (value)
17
+ login = { id: value, at: Date.now() };
18
+ return value;
19
+ };
2
20
  return Object.freeze({
21
+ /** ADR 0056 §1: the Bot's own group role (`get_login_info`, then `get_group_member_info` self). */
22
+ async inspectSelfStanding({ conversation, signal }) {
23
+ if (conversation.kind !== 'group')
24
+ return undefined;
25
+ const selfId = await loginId(signal);
26
+ if (!selfId)
27
+ return undefined;
28
+ let data;
29
+ try {
30
+ data = asRecord(await endpoint.callApi({ action: 'get_group_member_info', signal, params: {
31
+ group_id: toNumberId(conversation.id, 'group_id'), user_id: toNumberId(selfId, 'user_id'), no_cache: true,
32
+ } }));
33
+ }
34
+ catch (error) {
35
+ login = undefined;
36
+ throw error;
37
+ }
38
+ return standingFromMemberRole(asRecord(data.member).role ?? data.role);
39
+ },
3
40
  async listFriends(request = {}) {
4
41
  const data = asRecord(await endpoint.callApi({ action: 'get_friend_list', signal: request.signal }));
5
42
  return toArray(data.friends).map((value) => {
@@ -1,2 +1,2 @@
1
- import type { IncomingMessage } from 'node:http';
2
- export declare function verifyMilkyAccessToken(accessToken: string | undefined, request: IncomingMessage): boolean;
1
+ import { type ProtocolAuthRequest } from '@zhin.js/host-http';
2
+ export declare function verifyMilkyAccessToken(accessToken: string | undefined, request: ProtocolAuthRequest): boolean;
package/lib/milky-auth.js CHANGED
@@ -1,16 +1,7 @@
1
+ import { verifyProtocolAccessToken } from '@zhin.js/host-http';
1
2
  export function verifyMilkyAccessToken(accessToken, request) {
3
+ // Webhook semantics: no configured token admits any caller (reverse sockets use verifyProtocolAccessToken).
2
4
  if (!accessToken)
3
5
  return true;
4
- const auth = request.headers.authorization ?? '';
5
- if (auth === `Bearer ${accessToken}`)
6
- return true;
7
- try {
8
- const url = new URL(request.url ?? '/', 'http://localhost');
9
- if (url.searchParams.get('access_token') === accessToken)
10
- return true;
11
- }
12
- catch {
13
- /* ignore */
14
- }
15
- return false;
6
+ return verifyProtocolAccessToken(accessToken, request);
16
7
  }
package/lib/protocol.d.ts CHANGED
@@ -4,7 +4,7 @@ import type { EndpointProfileConfiguration } from 'zhin.js/adapter';
4
4
  * Canonicalization is owned by gateway/core before endpoint.send.
5
5
  * Spec: https://milky.ntqqrev.org/
6
6
  */
7
- import { type ConversationRef } from '@zhin.js/im-contract';
7
+ import { type ConversationRef, type PlatformStanding } from '@zhin.js/im-contract';
8
8
  import type { Segment } from '@zhin.js/core/runtime';
9
9
  /** One endpoint config after AdapterIndex expands `plugins.<instanceKey>.endpoints`. */
10
10
  export interface MilkyEndpointConfig extends EndpointProfileConfiguration {
@@ -127,6 +127,11 @@ export declare function formatInboundSegments(data: MilkyIncomingMessage): Segme
127
127
  /** First audio URI from inbound segments (for Agent Host STT preprocess). */
128
128
  export declare function extractInboundAudioUrl(data: MilkyIncomingMessage): string | undefined;
129
129
  /** 发送者显示名(群名片/群昵称/好友昵称);没有可靠的显示名时返回 undefined。 */
130
+ /**
131
+ * ADR 0056 §1:群消息 `group_member.role`(owner / admin / member)→ `sender.platform.standing`。
132
+ * 私聊 / 临时会话与未知角色词不上报;Milky 没有平台原生角色与权限位。
133
+ */
134
+ export declare function milkySenderStanding(data: MilkyIncomingMessage): PlatformStanding | undefined;
130
135
  export declare function senderNickname(data: MilkyIncomingMessage): string | undefined;
131
136
  /** 消息段中含 @ 本机(mention 段 user_id 等于协议端上报的 self_id)。 */
132
137
  export declare function isMentioned(data: MilkyIncomingMessage, selfId: number | undefined): boolean;
package/lib/protocol.js CHANGED
@@ -278,6 +278,16 @@ export function extractInboundAudioUrl(data) {
278
278
  return undefined;
279
279
  }
280
280
  /** 发送者显示名(群名片/群昵称/好友昵称);没有可靠的显示名时返回 undefined。 */
281
+ /**
282
+ * ADR 0056 §1:群消息 `group_member.role`(owner / admin / member)→ `sender.platform.standing`。
283
+ * 私聊 / 临时会话与未知角色词不上报;Milky 没有平台原生角色与权限位。
284
+ */
285
+ export function milkySenderStanding(data) {
286
+ if (data.message_scene !== 'group')
287
+ return undefined;
288
+ const role = data.group_member?.role;
289
+ return role === 'owner' || role === 'admin' || role === 'member' ? { standing: role } : undefined;
290
+ }
281
291
  export function senderNickname(data) {
282
292
  const isGroup = data.message_scene === 'group';
283
293
  const name = isGroup
@@ -10,7 +10,13 @@ export interface SseClientOptions {
10
10
  readonly onMessage: (data: string) => void;
11
11
  readonly onError?: (error: Error) => void;
12
12
  readonly onOpen?: () => void;
13
+ /** Abort and report an error when no bytes arrive for this long (default 5 min; 0 disables). */
14
+ readonly idleTimeoutMs?: number;
15
+ /** Abort and report an error when an unterminated frame grows past this many characters (default 8 Mi). */
16
+ readonly maxBufferLength?: number;
13
17
  }
18
+ export declare const SSE_DEFAULT_IDLE_TIMEOUT_MS = 300000;
19
+ export declare const SSE_DEFAULT_MAX_BUFFER_LENGTH: number;
14
20
  export interface SseClientHandle {
15
21
  readonly closed: Promise<void>;
16
22
  close(): void;
package/lib/sse-client.js CHANGED
@@ -1,8 +1,24 @@
1
+ export const SSE_DEFAULT_IDLE_TIMEOUT_MS = 300_000;
2
+ export const SSE_DEFAULT_MAX_BUFFER_LENGTH = 8 * 1024 * 1024;
1
3
  export function openSseStream(options) {
2
4
  const controller = new AbortController();
3
5
  const fetchImpl = options.fetch ?? globalThis.fetch;
4
6
  let settle;
5
7
  const closed = new Promise((resolve) => { settle = resolve; });
8
+ const idleTimeoutMs = options.idleTimeoutMs ?? SSE_DEFAULT_IDLE_TIMEOUT_MS;
9
+ const maxBufferLength = options.maxBufferLength ?? SSE_DEFAULT_MAX_BUFFER_LENGTH;
10
+ let idleTimer;
11
+ // Set before aborting our own controller so the abort is still reported as an error.
12
+ let failure;
13
+ const armIdleTimer = () => {
14
+ if (idleTimeoutMs <= 0)
15
+ return;
16
+ clearTimeout(idleTimer);
17
+ idleTimer = setTimeout(() => {
18
+ failure = new Error(`SSE idle for ${idleTimeoutMs}ms`);
19
+ controller.abort();
20
+ }, idleTimeoutMs);
21
+ };
6
22
  const run = async () => {
7
23
  try {
8
24
  const response = await fetchImpl(options.url, {
@@ -23,23 +39,34 @@ export function openSseStream(options) {
23
39
  const reader = response.body.getReader();
24
40
  const decoder = new TextDecoder();
25
41
  let buffer = '';
42
+ armIdleTimer();
26
43
  while (true) {
27
44
  const { done, value } = await reader.read();
28
45
  if (done)
29
46
  break;
47
+ armIdleTimer();
30
48
  buffer += decoder.decode(value, { stream: true });
31
49
  buffer = consumeSseBuffer(buffer, options.onMessage);
50
+ if (buffer.length > maxBufferLength) {
51
+ throw new Error(`SSE frame exceeds ${maxBufferLength} characters`);
52
+ }
32
53
  }
33
54
  buffer += decoder.decode();
34
55
  consumeSseBuffer(`${buffer}\n\n`, options.onMessage);
35
56
  }
36
57
  catch (error) {
37
- if (!controller.signal.aborted) {
58
+ if (failure) {
59
+ options.onError?.(failure);
60
+ }
61
+ else if (!controller.signal.aborted) {
38
62
  const err = error instanceof Error ? error : new Error(String(error));
39
63
  options.onError?.(err);
40
64
  }
41
65
  }
42
66
  finally {
67
+ clearTimeout(idleTimer);
68
+ // Release the connection after an oversize frame; a no-op when already closed.
69
+ controller.abort();
43
70
  settle();
44
71
  }
45
72
  };
@@ -51,9 +78,21 @@ export function openSseStream(options) {
51
78
  },
52
79
  };
53
80
  }
81
+ /**
82
+ * Normalize CRLF / lone CR line endings to LF (all three are valid in
83
+ * `text/event-stream`). A trailing CR is kept: it may be half of a CRLF split
84
+ * across chunks.
85
+ */
86
+ function normalizeSseNewlines(buffer) {
87
+ if (!buffer.includes('\r'))
88
+ return buffer;
89
+ const tail = buffer.endsWith('\r') ? '\r' : '';
90
+ const body = tail ? buffer.slice(0, -1) : buffer;
91
+ return body.replace(/\r\n?/g, '\n') + tail;
92
+ }
54
93
  /** Exported for unit tests. */
55
94
  export function consumeSseBuffer(buffer, onMessage) {
56
- let rest = buffer;
95
+ let rest = normalizeSseNewlines(buffer);
57
96
  while (true) {
58
97
  const sep = rest.indexOf('\n\n');
59
98
  if (sep < 0)
@@ -6,7 +6,7 @@ import { createEndpointSpecification, endpointSpec, createRecallEndpointControl,
6
6
  import { formatCompact, getAdapterLogger } from '@zhin.js/logger';
7
7
  import { createMilkyEndpointManagement } from './endpoint-management.js';
8
8
  import { createMilkyActionCaller, readMilkyResponse, milkyClientOptions, forwardMilkyClientEvents, MilkyClient } from './client.js';
9
- import { buildSendAction, buildSseConnectOptions, callApi, extractInboundAudioUrl, formatInboundContent, formatInboundMessageId, formatInboundSegments, formatOutboundMessageId, formatOutboundSegments, isMentioned, milkyInboundConversation, parseMessageReceiveData, parseMilkyMessageId, senderNickname, } from './protocol.js';
9
+ import { buildSendAction, buildSseConnectOptions, callApi, extractInboundAudioUrl, formatInboundContent, formatInboundMessageId, formatInboundSegments, formatOutboundMessageId, formatOutboundSegments, isMentioned, milkyInboundConversation, milkySenderStanding, parseMessageReceiveData, parseMilkyMessageId, senderNickname, } from './protocol.js';
10
10
  import { openSseStream } from './sse-client.js';
11
11
  export class MilkySseEndpoint extends MilkyClient {
12
12
  [endpointSpec];
@@ -124,6 +124,7 @@ export class MilkySseEndpoint extends MilkyClient {
124
124
  const segments = formatInboundSegments(data);
125
125
  const audioUrl = extractInboundAudioUrl(data);
126
126
  const nickname = senderNickname(data);
127
+ const platform = milkySenderStanding(data);
127
128
  const mentioned = isMentioned(data, event.self_id);
128
129
  void this[endpointSpec].events.message({
129
130
  event,
@@ -132,7 +133,7 @@ export class MilkySseEndpoint extends MilkyClient {
132
133
  message: { conversation, id: formatInboundMessageId(data) },
133
134
  content,
134
135
  segments,
135
- sender: { id: String(data.sender_id), name: nickname },
136
+ sender: { id: String(data.sender_id), name: nickname, ...(platform ? { platform } : {}) },
136
137
  endpointId: this.#options.config.id,
137
138
  ...(mentioned ? { mentioned: true } : {}),
138
139
  metadata: Object.freeze({
@@ -1,11 +1,14 @@
1
1
  import { createMilkySelfProfile } from './self-profile.js';
2
+ /**
3
+ * Milky webhook endpoint — httpHostToken POST inbound + baseUrl HTTP API outbound.
4
+ */
2
5
  import { acceptHttpIngress } from 'imhelper';
3
6
  import { createEndpointSpecification, endpointSpec, createRecallEndpointControl, } from 'zhin.js/adapter';
4
7
  import { formatCompact, getAdapterLogger } from '@zhin.js/logger';
5
8
  import { verifyMilkyAccessToken } from './milky-auth.js';
6
9
  import { createMilkyEndpointManagement } from './endpoint-management.js';
7
10
  import { createMilkyActionCaller, readMilkyResponse, milkyClientOptions, forwardMilkyClientEvents, MilkyClient } from './client.js';
8
- import { buildSendAction, callApi, extractInboundAudioUrl, formatInboundContent, formatInboundMessageId, formatInboundSegments, formatOutboundMessageId, formatOutboundSegments, isMentioned, milkyInboundConversation, parseMessageReceiveData, parseMilkyMessageId, senderNickname, } from './protocol.js';
11
+ import { buildSendAction, callApi, extractInboundAudioUrl, formatInboundContent, formatInboundMessageId, formatInboundSegments, formatOutboundMessageId, formatOutboundSegments, isMentioned, milkyInboundConversation, milkySenderStanding, parseMessageReceiveData, parseMilkyMessageId, senderNickname, } from './protocol.js';
9
12
  export class MilkyWebhookEndpoint extends MilkyClient {
10
13
  [endpointSpec];
11
14
  #open = false;
@@ -111,6 +114,7 @@ export class MilkyWebhookEndpoint extends MilkyClient {
111
114
  const segments = formatInboundSegments(data);
112
115
  const audioUrl = extractInboundAudioUrl(data);
113
116
  const nickname = senderNickname(data);
117
+ const platform = milkySenderStanding(data);
114
118
  const mentioned = isMentioned(data, event.self_id);
115
119
  void this[endpointSpec].events.message({
116
120
  event,
@@ -119,7 +123,7 @@ export class MilkyWebhookEndpoint extends MilkyClient {
119
123
  message: { conversation, id: formatInboundMessageId(data) },
120
124
  content,
121
125
  segments,
122
- sender: { id: String(data.sender_id), name: nickname },
126
+ sender: { id: String(data.sender_id), name: nickname, ...(platform ? { platform } : {}) },
123
127
  endpointId: this.#options.config.id,
124
128
  ...(mentioned ? { mentioned: true } : {}),
125
129
  metadata: Object.freeze({
@@ -141,33 +145,25 @@ export class MilkyWebhookEndpoint extends MilkyClient {
141
145
  }
142
146
  #setupRoutes() {
143
147
  const path = this.#options.config.path;
144
- this.#routeReleases.push(this.#options.http.route('POST', path, async (request, response) => {
145
- await this.#handleWebhook(request, response);
146
- }, { summary: 'Milky webhook callback', tags: ['milky'] }));
148
+ this.#routeReleases.push(this.#options.http.route('POST', path, (request) => this.#handleWebhook(request), { summary: 'Milky webhook callback', tags: ['milky'] }));
147
149
  }
148
- async #handleWebhook(request, response) {
150
+ async #handleWebhook(request) {
149
151
  try {
150
152
  if (!verifyMilkyAccessToken(this.#options.config.access_token, request)) {
151
- response.writeHead(403, { 'Content-Type': 'application/json' });
152
- response.end(JSON.stringify({ message: 'Unauthorized' }));
153
- return;
153
+ return new Response(JSON.stringify({ message: 'Unauthorized' }), { status: 403, headers: { 'Content-Type': 'application/json' } });
154
154
  }
155
155
  if (!this.#open) {
156
- response.writeHead(200, { 'Content-Type': 'application/json' });
157
- response.end(JSON.stringify({ status: 'ok' }));
158
- return;
156
+ return new Response(JSON.stringify({ status: 'ok' }), { status: 200, headers: { 'Content-Type': 'application/json' } });
159
157
  }
160
- await acceptHttpIngress(request, response, event => {
158
+ const result = await acceptHttpIngress(request, undefined, event => {
161
159
  void this[endpointSpec].events.run(() => this.ingest(event))
162
160
  .catch(error => this.#warnPlatformEvent(error));
163
161
  });
162
+ return new Response(JSON.stringify(result.body), { status: result.status, headers: result.headers });
164
163
  }
165
164
  catch (error) {
166
165
  this.#logger.error('Milky webhook error:', error);
167
- if (!response.headersSent) {
168
- response.writeHead(500, { 'Content-Type': 'application/json' });
169
- response.end(JSON.stringify({ message: 'Internal Server Error' }));
170
- }
166
+ return new Response(JSON.stringify({ message: 'Internal Server Error' }), { status: 500, headers: { 'Content-Type': 'application/json' } });
171
167
  }
172
168
  }
173
169
  }