@zhin.js/adapter-sandbox 1.1.30 → 1.1.31

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,140 @@
1
1
  # @zhin.js/adapter-process
2
2
 
3
+ ## 1.1.31
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
+ - 57c6cdc: fix: 全仓审计修复
12
+
13
+ - kernel: 模板求值沙箱不再泄漏宿主对象——宿主函数的返回值与抛出的错误会重新包裹代理(`segments.map(x=>x).constructor.constructor(...)` 之前可拿到宿主 `Function`),并禁止通过代理写入/删除宿主属性。
14
+ - agent: exec 白名单正则按整体锚定(`git|npm` 不再匹配 `gitevil`);SSRF 主机名黑名单识别尾点形式(`localhost.`);Docker 沙箱 `always` 模式的 fail-closed 分支可被触达;声明缺失的 `chalk` 依赖。
15
+ - ai: 摘要按最新优先加载(超过 500 条时不再使用过期锚点);修复 `test` 脚本指向不存在的配置。
16
+ - cli: `ZHIN_LOG_LEVEL` 生效(修复运算符优先级);移除旧守护进程遗留的无引用进程辅助函数。
17
+ - logger: `formatCompact` 不再把 `config: 'yaml'`、`direction: 'in'` 这类非路径值改写成 `./yaml`。
18
+ - host-http: 未配置数据库时 `db:tables` 与有数据库时一致返回 `{ tables }`。
19
+ - a2a: 405 响应把 `Allow` 放进响应头。
20
+ - pagemanager: 内联进 `<script>` 的页面元数据转义 `<`。
21
+ - client: 事件历史请求失败时携带 HTTP 状态,token 失效可触发重新登录。
22
+ - scaffold-wizard / create-zhin-app: 修正适配器文档 URL 与模板里的 `@zhin.js/tool` 导入。
23
+ - adapter-wechat-mp: 签名比较改为常量时间。
24
+ - adapter-kook: 声明运行时依赖 `ws`。
25
+ - plugin-lottery: 遗漏值按最近一次出现计算;推送目标 schema 字段与实现一致(`endpointKey`)。
26
+ - plugin-code-runner: 语言校验改用自有属性判断。
27
+ - plugin-link-poster: 抓取前校验主机名白名单(修复 SSRF),超时覆盖响应体读取。
28
+ - 其余包:从 `files` 中移除不存在的目录。
29
+ - feature-kit / middleware: 修正 README 中层级错误的文档链接。
30
+
31
+ - e1fda87: fix: 按审计待审清单处理(安全、功能、清理)
32
+
33
+ **行为变更(升级前请阅读)**
34
+
35
+ - kernel / core / zhin.js:出站文本中的 `${…}` 不再用 `vm` 求值,只替换 `TemplateContext` 上能解析到值的属性路径(如 `${sender.name}`);表达式、函数调用、未知名字原样保留。整套 vm 沙箱(`evaluate` / `execute` / `compiler` / `getValueWithRuntime`)已移除。
36
+ - kernel / core / zhin.js:移除零引用的遗留导出——`Scheduler`、错误管理器与 `ZhinError` 子类、`compose`、`segment.from/toString`、AI 触发/准入函数、`@zhin.js/core/queue-im-field-contract`、`zhin.js/contexts`。
37
+ - agent:readonly 执行预设不再放行重定向、后台 `&`、进程替换、`find -delete/-exec`、`sed -i`、`sort -o`、`tee`、`xargs`、awk;curl/wget 校验每个 URL 与裸主机并识别更多上传参数;自定义 `execAllowlist` 中的只读命令带写入风险时改走审批。沙箱超时/取消会杀掉进程组或具名容器,默认镜像改为 `node:22-bookworm-slim` + `bash`。移除无生产调用的 `AuditLogger`、`AnomalyDetector`、旧 vision 回合等导出。
38
+ - ai:移除 `storage`、`FileStateCache`、`CostTracker`、`model-name-utils`、`./agent-step-checkpoint` 子路径、`ContextManager` 及旧压缩管线;延迟工具快照改为有界 LRU。
39
+ - 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 接管后不再自行退出。
40
+ - schedule:后台 reconcile 出错不再产生未处理 rejection(新增 `onStoreError`);启动途中 `stop()` 不再遗留定时器。
41
+ - schema:元组校验与 `safeParse`、JSON Schema 一致(空数组不通过,缺省的可选元组为 `undefined`)。
42
+ - client / contract:删除无后端路由的 agent-stream API、未使用的 `definePage` 与旧 PageManager 类型;`@zhin.js/contract` 不再依赖 `@zhin.js/ai`;客户端收到 401 会清除已保存的凭据;安装/更新/卸载 RPC 默认超时 120 秒。
43
+ - a2a:流式响应中途出错写入 SSE error 并结束;未配置 token 的非生产环境只接受本机请求;任务存储有上限与过期;Mailbox 凭据回退与生产环境缺密钥检查修复。
44
+ - speech:`provider: openai` 不再套用 Ollama 的默认 host/model;识别语言改为可配置,不再写死 `zh`。
45
+ - adapter-lark:支持 `encryptKey` 加密事件解密。adapter-github:Device Flow 可取消、带超时并回复失败原因。adapter-wecom / dingtalk:请求加超时并校验 HTTP 状态。adapter-weixin-ilink:输入关闭期间暂停轮询。adapter-milky:SSE 支持 CRLF、缓冲上限与空闲重连。adapter-onebot-events:好友删除通知改为 `notice.friend.decrease`。
46
+ - plugin-group-suite:`teachAllowRegex` 默认关闭,正则安全检查更严格。plugin-qrcode:改为本地生成,回复 data URL 图片。plugin-rss / short-url / link-poster:拒绝解析到内网的地址;rss 修复条目每周重复推送;short-url 的 Console 创建改为真实调用 is.gd。plugin-lottery:按 `historyLimit` 同步。
47
+
48
+ **其余**
49
+
50
+ - host-http:插件市场详情加缓存与包名校验,SSE 回放容忍背压。host-http-contract:新增 `readTextBody()`,九个适配器改用它。
51
+ - pagemanager:页面外壳 importmap 升级到 React 19.2.8 / react-router 7.12.0。console-contract:`definePage` 接受 `description` / `group` / `parent` / `fullWidth`。
52
+ - command:进度提示本地化,匹配不再重复拷贝消息段。runtime:源码监听降级后退避重试原生监听。
53
+ - html-renderer:删除未接线的 `aiTextAsImage`。create-zhin-app / scaffold-wizard:移除不起作用的"全局安装 CLI"与运行时选择提示。
54
+ - 依赖声明清理、发布清单不再携带解析不到的 `src` 目录、移除未使用的 Skill 挂载、README 与示例配置按当前实现更正。
55
+
56
+ - 120e225: 聊天角色(ADR 0056,2026-11-12 修订):zhin 角色 owner / admin / trusted 分四级、只来自授予;发言者的平台身份与机器人自身的平台身份是独立维度,命令、Agent 工具 / 技能、中间件与按钮按三条维度共用一个评估器过滤。升级说明见 docs/migrations/chat-roles.md。
57
+
58
+ - 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` 判断。
59
+ - @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` 删除。
60
+ - @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`,定义时报错并给出替代写法。
61
+ - @zhin.js/command(minor,破坏性):命令会话的发送者改为 `chatRole` / `platform`,不再从 metadata 读角色;`CONVERSATION_MANAGER_PERMIT` 改为 `admin`(平台群主不再自动满足);分发结果 `denied` 带 `denial`(第一条不满足的规则与原因);指令菜单只列出当前发送者在本会话可用的命令。
62
+ - @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`。
63
+ - @zhin.js/feature-kit:`OperationSession.sender` 改为 `chatRole` / `platform`。
64
+ - @zhin.js/im-contract:新增 `PlatformStanding`、`SelfStandingRequest`、`standingFromMemberRole`。
65
+ - @zhin.js/adapter:入站 sender 可带 `platform`;账号管理命令需要聊天角色 `owner`;`EndpointManagement` 新增可选 `inspectSelfStanding`,能力画像新增 `scene.selfStanding`(声明即须实现),`AdapterIndex.selfStanding` / `invalidateSelfStanding` 按会话缓存机器人自身身份。
66
+ - @zhin.js/middleware:入站中间件可声明 `permit`,不满足时跳过该中间件(机器人身份只读缓存)。
67
+ - @zhin.js/tool:定义工具时拒绝已移除的 permit 写法。
68
+ - @zhin.js/ai:注释更新。
69
+ - @zhin.js/console-protocol:`chat-roles.list|grant|revoke`(`iam.manage`);`ConsoleChatRoleSource` 只有 `grant`。
70
+ - @zhin.js/runtime:Host 配置 Schema 删除 `features.selfService.platformAdmins|roles|allowUsers`。
71
+ - @zhin.js/testing:伪造消息与 `PluginTestKit` 用 `sender.chatRole` 声明测试身份。
72
+ - @zhin.js/scaffold-wizard:ICQQ 向导不再写 `master`,完成后提示在 Console 账号「角色」页签或聊天 `角色 授予` 设置 owner。
73
+ - 适配器:配置 Schema 删除 `master` / `trusted`(以及预览版的 `roles`);群管理类工具同时声明发言者条件与机器人条件(如 `platform:admin` + `bot:admin`、`bot-permission:manage_roles`),NapCat / OneBot11 工具不再使用已移除的 `platform(adapter,…)` 写法。
74
+ - 插件:内容审核以 `inbound.bypass`(permit 列表,默认 `owner` 或 `platform:admin`)取代 `masters` / `inbound.bypassMasters`;群管、音乐、日历、地震、B 站、轮盘赌的权限改用 zhin 角色,订阅类命令只认 zhin `admin` / `owner`。
75
+
76
+ - c2bbdcf: Console 访问控制(ADR 0049):用户、角色、会话、API 令牌与审计日志存入项目数据库,每个 Console RPC、`/api` 路由与 Host 鉴权的 WebSocket 都按 `@zhin.js/console-protocol` 的权限表放行,未登记的一律拒绝。
77
+
78
+ **破坏性变更**
79
+
80
+ - `http.tokens` 与演示模式(`scope: demo` / `user`)删除;配置里仍有 `http.tokens` 时 Host 拒绝启动。Host 配置 Schema 同步删除该字段。
81
+ - `http.token` 变为初始化令牌:只在创建第一个所有者之前有效,之后在所有接口上被拒绝。
82
+ - 未在 `CONSOLE_WS_PERMISSIONS` 登记、又使用 Host 鉴权的插件 WebSocket 不再接受 Console 账号;插件自己的 WebSocket 应改用 `ws(path, { auth: 'protocol' })` 并自行校验凭据(新增 `verifyProtocolAccessToken`、`isLoopbackAddress`)。
83
+ - OneBot 11 / 12、NapCat、Milky 的反向 WebSocket 改为只认适配器自己的 `access_token`;未配置 `access_token` 时只接受本机回环连接。
84
+ - `zhin doctor --live` 等改从 `ZHIN_CONSOLE_TOKEN` 读取 API 令牌(仍兼容 `ZHIN_HTTP_TOKEN`)。
85
+
86
+ **迁移步骤**(详见文档「升级到 Console 访问控制」)
87
+
88
+ 1. 升级后用 `http.token` 打开 Console 初始化向导创建第一个所有者,或运行 `zhin console init`(脚本:`zhin console init --yes --owner <名> --password-stdin`)。
89
+ 2. 删除配置里的 `http.tokens`,在 Console「访问控制」里为原来的令牌持有人创建用户并绑定角色(`viewer` / `operator` / `admin`);演示环境改用 `viewer` 账号。
90
+ 3. 自动化在 Console 签发 API 令牌,放进 `ZHIN_CONSOLE_TOKEN`。
91
+ 4. 从其他机器或容器连接的反向 WebSocket endpoint 补上 `access_token`。
92
+ 5. 忘记密码或所有者被锁时,停下 Host,用 `zhin console user passwd|enable|create` 离线恢复。
93
+
94
+ MCP / A2A 的 Bearer 访问同样接受用户 API 令牌(分别需要 `mcp.access`、`a2a.access`)。适配器与插件文档同步改为账号与角色的说法。
95
+
96
+ - 5cd9d3d: HTTP 路由契约改为 Web 标准 `Request` / `Response`(ADR 0054 §2,B1.0)
97
+
98
+ - host-http-contract:路由处理函数签名改为 `(request, context) => Response`,`context` 提供 `url`、`params`、`principal`、`remoteAddress`;新增 `readBodyBytes` / `readTextBody` / `readJsonBody`(带大小上限,超限先读完再报 413)、`jsonResponse` / `emptyResponse`、带背压的 `createResponseStream`(SSE、大文件下载)与 `WsConnection`。契约不再引用 `node:http` / `ws`。
99
+ - host-http:Node 服务器移到 `@zhin.js/host-http/node`(`createHttpHost`),负责 Node 请求与 `Request` / `Response` 的互转;认证结果经 `context.principal` 传给路由,删除旧的按请求取主体的辅助函数;未预期的异常只返回通用错误信息,细节写日志。
100
+ - runtime、mcp、a2a、gateway、zhin.js、calendar 插件与各适配器的 Webhook / 反向 WebSocket 路由迁移到新契约,行为不变。
101
+
102
+ - Updated dependencies [540a7f2]
103
+ - Updated dependencies [53932e5]
104
+ - Updated dependencies [57c6cdc]
105
+ - Updated dependencies [e1fda87]
106
+ - Updated dependencies [4e8ba38]
107
+ - Updated dependencies [a9c7a13]
108
+ - Updated dependencies [120e225]
109
+ - Updated dependencies [c2bbdcf]
110
+ - Updated dependencies [c2bbdcf]
111
+ - Updated dependencies [63595fc]
112
+ - Updated dependencies [5120367]
113
+ - Updated dependencies [fd055d2]
114
+ - Updated dependencies [4e8ba38]
115
+ - Updated dependencies [cc7a5f9]
116
+ - Updated dependencies [4e8ba38]
117
+ - Updated dependencies [f8bf684]
118
+ - Updated dependencies [e0bc008]
119
+ - Updated dependencies [5cd9d3d]
120
+ - Updated dependencies [5cd9d3d]
121
+ - Updated dependencies [c2bbdcf]
122
+ - Updated dependencies [f8bf684]
123
+ - Updated dependencies [663473b]
124
+ - Updated dependencies [c606d51]
125
+ - Updated dependencies [5cd9d3d]
126
+ - Updated dependencies [d655ef0]
127
+ - Updated dependencies [1e54b1e]
128
+ - @zhin.js/client@1.1.32
129
+ - @zhin.js/adapter@1.1.33
130
+ - @zhin.js/core@1.2.0
131
+ - @zhin.js/logger@1.1.3
132
+ - @zhin.js/host-http@1.2.0
133
+ - @zhin.js/feature-kit@1.1.16
134
+ - @zhin.js/console-contract@1.1.6
135
+ - @zhin.js/im-contract@1.1.14
136
+ - @zhin.js/page@1.1.18
137
+
3
138
  ## 1.1.30
4
139
 
5
140
  ### 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/README.md CHANGED
@@ -20,19 +20,19 @@ pnpm add @zhin.js/adapter-sandbox
20
20
 
21
21
  ## 前置条件
22
22
 
23
- Sandbox 不需要外部账号。只需由 `zhin runtime start` 装配 HTTP Host,并确保浏览器能访问启动日志中的 Host 地址。
23
+ Sandbox 不需要外部账号。只需用 `zhin start` 启动项目(管理网关承载 HTTP,实例的路由经网关转发),并确保浏览器能访问启动日志中的 Host 地址。
24
24
 
25
25
  ## 依赖
26
26
 
27
- ### Plugin Runtime(新,`zhin runtime start`)
27
+ ### Plugin Runtime(`zhin start`)
28
28
 
29
29
  - `@zhin.js/adapter` — 约定式 `adapters/sandbox/index.ts`
30
30
  - `@zhin.js/host-http` — Root 提供的 `httpHostToken`(WebSocket `/sandbox` + Console HTTP)
31
31
  - `@zhin.js/core` — `endpointSpec.events` 入站、`outboundMessageToken` 出站
32
32
  - `@zhin.js/page` + `pages/index/index.tsx` — ADR 0046 约定页(`definePage`;路由 `/sandbox`)
33
33
 
34
- Root 在 `zhin runtime start` 时装载 `@zhin.js/host-http`、`ConsoleRuntime` 与
35
- `ClientBuildModuleRuntime`。打开 `http://<host>:<port>/console` 可浏览页面;Sandbox 页
34
+ `zhin start` 拉起的实例装载 `@zhin.js/host-http`、`ConsoleRuntime` 与
35
+ `ClientBuildModuleRuntime`(HTTP 由管理网关监听并转发)。打开 `http://<host>:<port>/console` 可浏览页面;Sandbox 页
36
36
  (路由 `/sandbox`,与 WebSocket `/sandbox` 同 path:GET 开页、Upgrade 走 WS)内置聊天壳。
37
37
 
38
38
  旧 `client/`(`register(api)` / `pageManager.addEntry`)仅保留给 legacy Host 栈参考,
@@ -84,8 +84,8 @@ Console 原生渲染 Markdown 格式的流式回复(`markdown` 段,`data.con
84
84
  ## 使用方式
85
85
 
86
86
  1. 启动 Zhin 实例:`pnpm dev`(终端会打印 Host 地址,一般为 `http://127.0.0.1:8086`)
87
- 2. 打开 **[Remote Console](https://console.zhin.dev)**,API Base 与 Host 地址一致,Token 与 `http.token` / `HTTP_TOKEN` 一致
88
- 3. 在 Console **会话** 页连接后发送消息
87
+ 2. 打开 **[Remote Console](https://console.zhin.dev)**,API Base 与 Host 地址一致,用 Console 账号登录(首次连接用 `http.token` / `HTTP_TOKEN` 创建所有者)
88
+ 3. 连接后在 Console 侧栏「试聊一下」(`/sandbox`)发送消息
89
89
 
90
90
  浏览器客户端连接到默认 `sandbox-bot`,也可以通过多个显式 endpoint 使用不同 WebSocket 路径。
91
91
 
@@ -97,7 +97,7 @@ Console 原生渲染 Markdown 格式的流式回复(`markdown` 段,`data.con
97
97
 
98
98
  刷新后仅恢复当前进程和 generation 中仍有效的待处理交互,继续使用原发起人、会话、期限和单次处理规则。历史与浏览器缓存中的控件不提供当前审批权限;已结束或重启前的操作不会重新激活。
99
99
 
100
- 无人值守任务等产生的 Host 工具审批,可在任务中心的「Host 工具审批」中查看并逐次确认。该入口沿用 Console 操作者的权限,只显示当前有效请求,不改变 IM 审批规则。
100
+ 无人值守任务等产生的 Host 工具审批,可在「运维 → 定时任务 → 管理员任务」的「Host 工具审批」中查看并逐次确认。该入口沿用 Console 操作者的权限,只显示当前有效请求,不改变 IM 审批规则。
101
101
 
102
102
  「变更与产物」中的成功文件写入、编辑在 Host 提供项目文件引用时,可打开现有文件管理器查看当前文件。入口沿用文件管理器的项目根与读取权限;旧记录或无法映射的文件仍显示执行记录,不推测链接。该入口读取当前内容,不是执行时的历史快照。
103
103
 
@@ -110,9 +110,9 @@ Console 沙盒页和自己写的测试客户端都用这套协议。每个 WebSo
110
110
  ### 连接
111
111
 
112
112
  - **地址**:`ws://<host>:<port>/sandbox`。同一个 HTTP Host 上的第一个 Sandbox endpoint 挂在 `/sandbox`,其余 endpoint 挂在 `/sandbox/<endpoint id>`(重名时依次加 `-2`、`-3`),启动日志会打印 `ws mounted <path>`。
113
- - **鉴权**:Host 配置了 token 时,握手请求需带 `Authorization: Bearer <token>` 或查询参数 `?token=<token>`,否则返回 `401`。demo 权限的 token 只能连 `/sandbox`,而且是只读的:消息会被接收,但不会进入命令和 Agent,服务端回一条 `type: "error"`。
113
+ - **鉴权**:Host 需要凭据时(已配置 `http.token` 或已完成初始化),握手请求需带 Console 凭据:`Authorization: Bearer <会话或 API 令牌>` 或查询参数 `?token=`,并且该账号要有 `endpoint.operate` 权限(所有者、管理员、运营),否则返回 `401`。初始化令牌不能连接。
114
114
  - **多连接**:同一 endpoint 的浏览器连接可以并存,共用已配置的 `owner`;`connectionId` 只标识连接,不改变 Bot 或 Agent 会话身份。关闭一个页面只移除该连接,不取消或重跑任务;endpoint 停止时关闭全部连接(`1001`),generation 退役继续由 Host 关闭(`1012`)。
115
- - **会话投递**:每个 full 连接订阅一个 `type` + `id`;默认订阅 `private` + `owner`,发送普通消息也会更新该连接的订阅。回复只投递到同会话的 full 连接,demo 连接不能订阅或接收这些消息。无匹配连接时不确认发送,所有发送尝试失败时保留结果未知,不自动重试。
115
+ - **会话投递**:每个连接订阅一个 `type` + `id`;默认订阅 `private` + `owner`,发送普通消息也会更新该连接的订阅。回复只投递到同会话的连接。无匹配连接时不确认发送,所有发送尝试失败时保留结果未知,不自动重试。
116
116
 
117
117
  ### 客户端 → 服务端:订阅当前会话
118
118
 
@@ -182,7 +182,7 @@ Console 沙盒页和自己写的测试客户端都用这套协议。每个 WebSo
182
182
  }
183
183
  ```
184
184
 
185
- `canExecute` 表示当前连接是否为 full 权限(能运行命令和 Agent 任务);`shellIsolation` 是 Docker 隔离环境的探测结果,仅供展示。`ready` 与 `subscribed` 仅确认连接和订阅,不代表任务或审批成功。
185
+ `canExecute` 表示当前连接能否运行命令和 Agent 任务(通过鉴权的连接都可以);`shellIsolation` 是 Docker 隔离环境的探测结果,仅供展示。`ready` 与 `subscribed` 仅确认连接和订阅,不代表任务或审批成功。
186
186
 
187
187
  **回复消息**:
188
188
 
@@ -204,7 +204,7 @@ Console 沙盒页和自己写的测试客户端都用这套协议。每个 WebSo
204
204
  - `image` / `audio` / `video` / `file` 段只读 `data.media`(MediaRef):`url` 原样透传;`base64` 补上 `base64://` 前缀后内联;`path` 由服务端读取文件后转成 `base64` 内联;其他类型和缺少 `data.media` 的媒体段会被丢弃,并在日志中记录 `sandbox_outbound_media_dropped`。
205
205
  - 插件直接发送完整消息对象时,其他字段会原样保留。
206
206
 
207
- **用户消息回声**:只发给已完成新协议订阅的同会话 full 连接。
207
+ **用户消息回声**:只发给已完成新协议订阅的同会话连接。
208
208
 
209
209
  ```json
210
210
  {
@@ -222,29 +222,12 @@ Console 沙盒页和自己写的测试客户端都用这套协议。每个 WebSo
222
222
 
223
223
  客户端按会话、消息方向及 `messageId` 合并本页乐观消息、真实历史和回声。按钮操作仍由原服务端交互与审批逻辑裁决,页面显示「已提交」不代表审批通过。多连接沿用当前 Console 操作者和配置的 Sandbox owner,不增加多人账号体系。
224
224
 
225
- **只读连接的提示**:demo 权限的连接发送消息后,服务端回复:
226
-
227
- ```json
228
- {
229
- "type": "error",
230
- "id": "sandbox-user",
231
- "endpoint": "sandbox-bot",
232
- "content": [{ "type": "text", "data": { "text": "当前连接是只读演示权限,不能运行 Agent 任务。" } }],
233
- "timestamp": 1700000000000
234
- }
235
- ```
236
-
237
225
  ## 适用场景
238
226
 
239
227
  - 本地开发调试插件逻辑
240
228
  - 测试命令和 AI 工具调用
241
229
  - 不依赖外部平台的功能验证
242
230
 
243
- ## AI 工具
244
-
245
- 技能说明见 `skills/sandbox/SKILL.md`(本地沙箱调试约束)。
246
-
247
-
248
231
  ## 故障排查
249
232
 
250
233
  | 现象 | 排查 |
@@ -257,3 +240,7 @@ Console 沙盒页和自己写的测试客户端都用这套协议。每个 WebSo
257
240
  ## 许可证
258
241
 
259
242
  MIT License
243
+
244
+ ## 成员身份
245
+
246
+ 模拟器的发送者角色(`master` = 群主 / `admin` / `member`)在群聊、频道中作为 `sender.platform.standing`(`owner` / `admin` / `member`)上报,私聊不上报。它只模拟平台身份,不授予框架角色(主人等由账号配置或聊天角色决定)。能力画像:`group` / `channel` 的 `scene.platformStanding = { standing: true }`。详见 [ADR 0056 §1](https://github.com/zhinjs/zhin/blob/main/docs/adr/0056-chat-roles.md)。
@@ -24,6 +24,9 @@ export default defineAdapter({
24
24
  // The authenticated local ingress: its configured owner may turn wire metadata into agent-run authority.
25
25
  runtime: { sandbox: true },
26
26
  },
27
+ // ADR 0056 §1:模拟器的发送者角色(master = 群主 / admin / member)作为平台身份上报。
28
+ group: { scene: { platformStanding: { standing: true } } },
29
+ channel: { scene: { platformStanding: { standing: true } } },
27
30
  },
28
31
  createAdapter: context => new SandboxAdapter(context),
29
32
  });
@@ -28,6 +28,9 @@ export default defineAdapter<SandboxEndpointConfig>({
28
28
  // The authenticated local ingress: its configured owner may turn wire metadata into agent-run authority.
29
29
  runtime: { sandbox: true },
30
30
  },
31
+ // ADR 0056 §1:模拟器的发送者角色(master = 群主 / admin / member)作为平台身份上报。
32
+ group: { scene: { platformStanding: { standing: true } } },
33
+ channel: { scene: { platformStanding: { standing: true } } },
31
34
  },
32
35
  createAdapter: context => new SandboxAdapter(context),
33
36
  });
package/lib/endpoint.js CHANGED
@@ -7,7 +7,7 @@ import { randomUUID } from 'node:crypto';
7
7
  import { execFile } from 'node:child_process';
8
8
  import { formatCompact, getAdapterLogger } from '@zhin.js/logger';
9
9
  import { EndpointDeliveryError } from '@zhin.js/im-contract';
10
- import { bindSandboxWsSocket, formatSandboxOutbound, parseSandboxWsFrame, sandboxInboundConversation, whenWsOpen, } from './protocol.js';
10
+ import { bindSandboxWsSocket, sandboxSocketOf, formatSandboxOutbound, parseSandboxWsFrame, sandboxInboundConversation, whenWsOpen, } from './protocol.js';
11
11
  import { SandboxClient } from './client.js';
12
12
  const claimedWsPaths = new WeakMap();
13
13
  function claimSandboxWsPath(http, name) {
@@ -252,8 +252,9 @@ export class SandboxWsEndpoint extends SandboxClient {
252
252
  ? `sandbox-${randomUUID().slice(0, 8)}`
253
253
  : this.#options.defaults.id;
254
254
  const owner = this.#options.defaults.owner;
255
- const canExecute = connection.authScope === 'full';
256
- const socket = connection.socket;
255
+ // Every admitted host-authenticated socket carries a Console principal allowed to use it.
256
+ const canExecute = true;
257
+ const socket = sandboxSocketOf(connection);
257
258
  const connectionId = randomUUID();
258
259
  const subscription = {
259
260
  connectionId, target, owner, socket, canExecute, scoped: false,
@@ -320,16 +321,13 @@ export class SandboxWsEndpoint extends SandboxClient {
320
321
  ...(parsed.senderRole ? { senderRole: parsed.senderRole } : {}),
321
322
  messageId, endpoint: this.#options.defaults.id, content: parsed.content, timestamp: parsed.timestamp,
322
323
  }));
324
+ // ADR 0056 §1: the simulated group role is a platform standing (master = 群主). It never
325
+ // grants framework roles; those come from the runtime (account owner / chat roles).
326
+ const standing = parsed.senderRole === 'master' ? 'owner' : parsed.senderRole;
323
327
  const sender = {
324
328
  id: senderId,
325
329
  name: senderName,
326
- ...(parsed.senderRole
327
- ? {
328
- role: parsed.senderRole,
329
- roles: parsed.senderRole === 'master' ? ['master', 'admin'] : parsed.senderRole === 'admin' ? ['admin'] : ['member'],
330
- permissions: parsed.senderRole === 'master' ? ['master', 'admin'] : parsed.senderRole === 'admin' ? ['admin'] : [],
331
- }
332
- : {}),
330
+ ...(standing && conversation.kind !== 'private' ? { platform: { standing } } : {}),
333
331
  };
334
332
  void this[endpointSpec].events.message({
335
333
  event: raw,
package/lib/protocol.d.ts CHANGED
@@ -15,6 +15,13 @@ export interface SandboxWsSocket {
15
15
  addEventListener?(type: 'message' | 'close' | 'error', listener: (ev: Event | MessageEvent | CloseEvent) => void): void;
16
16
  removeEventListener?(type: 'message' | 'close' | 'error', listener: (ev: Event | MessageEvent | CloseEvent) => void): void;
17
17
  }
18
+ /** A Host {@link WsConnection} seen through the {@link SandboxWsSocket} surface. */
19
+ export declare function sandboxSocketOf(connection: {
20
+ send(data: string): void;
21
+ close(code?: number, reason?: string): void;
22
+ onMessage(listener: (data: string | Uint8Array) => void): () => void;
23
+ onClose(listener: (code: number, reason: string) => void): () => void;
24
+ }): SandboxWsSocket;
18
25
  export type ResolvedSandboxBot = {
19
26
  readonly context: 'sandbox';
20
27
  readonly id: string;
package/lib/protocol.js CHANGED
@@ -4,6 +4,33 @@ import { isMediaRef } from '@zhin.js/im-contract';
4
4
  import { formatCompact, getLogger } from '@zhin.js/logger';
5
5
  import { normalizeSandboxAgentRunConfig, } from './run-config.js';
6
6
  const logger = getLogger('sandbox');
7
+ /** A Host {@link WsConnection} seen through the {@link SandboxWsSocket} surface. */
8
+ export function sandboxSocketOf(connection) {
9
+ let open = true;
10
+ connection.onClose(() => { open = false; });
11
+ const subscriptions = new Map();
12
+ return {
13
+ get readyState() { return open ? WS_OPEN : 3; },
14
+ send: (data) => { if (open)
15
+ connection.send(data); },
16
+ close: (code, reason) => connection.close(code, reason),
17
+ on(event, listener) {
18
+ if (event === 'message') {
19
+ subscriptions.set(listener, connection.onMessage((data) => {
20
+ listener(typeof data === 'string' ? data : new TextDecoder().decode(data));
21
+ }));
22
+ }
23
+ else if (event === 'close') {
24
+ subscriptions.set(listener, connection.onClose(() => listener()));
25
+ }
26
+ // Transport errors surface as a close on a WsConnection.
27
+ },
28
+ off(_event, listener) {
29
+ subscriptions.get(listener)?.();
30
+ subscriptions.delete(listener);
31
+ },
32
+ };
33
+ }
7
34
  export function resolveSandboxEndpoint(config) {
8
35
  const id = optionalEndpointField(config.id) ?? 'sandbox-bot';
9
36
  const owner = optionalEndpointField(config.owner) ?? 'sandbox-user';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhin.js/adapter-sandbox",
3
- "version": "1.1.30",
3
+ "version": "1.1.31",
4
4
  "description": "Zhin.js Sandbox adapter for Plugin Runtime (WebSocket /sandbox)",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -18,8 +18,6 @@
18
18
  "schema.json",
19
19
  "src",
20
20
  "lib",
21
- "dist",
22
- "skills",
23
21
  "README.md",
24
22
  "CHANGELOG.md"
25
23
  ],
@@ -46,36 +44,35 @@
46
44
  },
47
45
  "dependencies": {
48
46
  "lucide-react": "^0.525.0",
49
- "react": "^19.2.8",
50
- "@zhin.js/console-contract": "1.1.5",
51
- "@zhin.js/core": "1.1.60",
52
- "@zhin.js/client": "1.1.31",
53
- "@zhin.js/adapter": "1.1.32",
54
- "@zhin.js/feature-kit": "1.1.15",
55
- "@zhin.js/host-http": "1.1.17",
56
- "@zhin.js/im-contract": "1.1.13",
57
- "@zhin.js/logger": "1.1.2",
58
- "@zhin.js/page": "1.1.17",
59
- "@zhin.js/skill": "1.1.16"
47
+ "@zhin.js/adapter": "1.1.33",
48
+ "@zhin.js/client": "1.1.32",
49
+ "@zhin.js/console-contract": "1.1.6",
50
+ "@zhin.js/core": "1.2.0",
51
+ "@zhin.js/feature-kit": "1.1.16",
52
+ "@zhin.js/host-http": "1.2.0",
53
+ "@zhin.js/im-contract": "1.1.14",
54
+ "@zhin.js/logger": "1.1.3",
55
+ "@zhin.js/page": "1.1.18"
60
56
  },
61
57
  "devDependencies": {
62
58
  "@types/react": "^19.2.18",
63
59
  "@types/ws": "^8.18.1",
60
+ "react": "^19.2.8",
64
61
  "typescript": "^6.0.3",
65
62
  "vitest": "^4.1.10",
66
63
  "ws": "^8.21.1",
67
- "@zhin.js/pagemanager": "1.1.24",
68
- "@zhin.js/runtime": "1.1.21",
69
- "zhin.js": "1.1.25"
64
+ "@zhin.js/pagemanager": "1.1.25",
65
+ "@zhin.js/runtime": "1.2.0",
66
+ "zhin.js": "1.1.26"
70
67
  },
71
68
  "peerDependencies": {
72
69
  "react": "^19.0.0",
73
- "@zhin.js/adapter": "^1.1.32",
74
- "@zhin.js/console-contract": "^1.1.5",
75
- "@zhin.js/core": "^1.1.60",
76
- "@zhin.js/host-http": "^1.1.17",
77
- "@zhin.js/page": "^1.1.17",
78
- "zhin.js": "^1.1.25"
70
+ "@zhin.js/adapter": "^1.1.33",
71
+ "@zhin.js/console-contract": "^1.1.6",
72
+ "@zhin.js/core": "^1.2.0",
73
+ "@zhin.js/host-http": "^1.2.0",
74
+ "@zhin.js/page": "^1.1.18",
75
+ "zhin.js": "^1.1.26"
79
76
  },
80
77
  "peerDependenciesMeta": {
81
78
  "react": {
@@ -103,10 +100,6 @@
103
100
  {
104
101
  "package": "@zhin.js/page",
105
102
  "api": "^1.0.0"
106
- },
107
- {
108
- "package": "@zhin.js/skill",
109
- "api": "^1.0.0"
110
103
  }
111
104
  ],
112
105
  "plugins": []
@@ -114,6 +107,6 @@
114
107
  "scripts": {
115
108
  "build": "tsc",
116
109
  "clean": "rimraf lib",
117
- "test": "NODE_OPTIONS=--experimental-strip-types vitest run --root ../../.. plugins/adapters/sandbox/tests"
110
+ "test": "vitest run --root ../../.. plugins/adapters/sandbox/tests"
118
111
  }
119
112
  }
package/schema.json CHANGED
@@ -14,34 +14,6 @@
14
14
  "default": 500,
15
15
  "description": "Minimum delay in milliseconds between reply updates; the first update is immediate."
16
16
  },
17
- "master": {
18
- "type": [
19
- "string",
20
- "number"
21
- ],
22
- "description": "框架 master(sandbox client id (distinct from endpoints[].owner);AI/工具权限、endpoint 管理)。endpoints[i].master 可逐项覆盖",
23
- "x-i18n": {
24
- "en": {
25
- "description": "Framework masters (sandbox client id, distinct from endpoints[].owner; AI/tool permissions and endpoint management). endpoints[i].master can override this value."
26
- }
27
- }
28
- },
29
- "trusted": {
30
- "type": "array",
31
- "items": {
32
- "type": [
33
- "string",
34
- "number"
35
- ],
36
- "description": "Trusted sandbox client id (distinct from endpoints[].owner)"
37
- },
38
- "description": "框架 trusted 用户列表(弱于 master)。endpoints[i].trusted 可逐项追加",
39
- "x-i18n": {
40
- "en": {
41
- "description": "Framework trusted users, below master authority. endpoints[i].trusted can add users."
42
- }
43
- }
44
- },
45
17
  "endpoints": {
46
18
  "type": "array",
47
19
  "description": "多账号:一个插件实例挂多个 endpoint。每项与顶层字段同构(id 必填,其余覆盖顶层)",
@@ -49,34 +21,6 @@
49
21
  "type": "object",
50
22
  "additionalProperties": false,
51
23
  "properties": {
52
- "master": {
53
- "type": [
54
- "string",
55
- "number"
56
- ],
57
- "description": "本 endpoint 的框架 master(sandbox client id (distinct from endpoints[].owner));覆盖顶层 master",
58
- "x-i18n": {
59
- "en": {
60
- "description": "Framework masters for this endpoint (sandbox client id, distinct from endpoints[].owner), overriding the top-level master list."
61
- }
62
- }
63
- },
64
- "trusted": {
65
- "type": "array",
66
- "items": {
67
- "type": [
68
- "string",
69
- "number"
70
- ],
71
- "description": "Trusted sandbox client id (distinct from endpoints[].owner)"
72
- },
73
- "description": "本 endpoint 的 trusted 列表",
74
- "x-i18n": {
75
- "en": {
76
- "description": "Trusted users for this endpoint."
77
- }
78
- }
79
- },
80
24
  "owner": {
81
25
  "type": "string",
82
26
  "description": "Sandbox owner user ID"
package/src/endpoint.ts CHANGED
@@ -9,9 +9,10 @@ import { execFile } from 'node:child_process';
9
9
  import type { HttpHost, WsConnection } from '@zhin.js/host-http';
10
10
  import { formatCompact, getAdapterLogger } from '@zhin.js/logger';
11
11
  import type { CapabilityId } from 'zhin.js';
12
- import { EndpointDeliveryError } from '@zhin.js/im-contract';
12
+ import { EndpointDeliveryError, type PlatformStandingLevel } from '@zhin.js/im-contract';
13
13
  import {
14
14
  bindSandboxWsSocket,
15
+ sandboxSocketOf,
15
16
  formatSandboxOutbound,
16
17
  parseSandboxWsFrame,
17
18
  sandboxInboundConversation,
@@ -320,8 +321,9 @@ export class SandboxWsEndpoint extends SandboxClient<SandboxConnection> implemen
320
321
  ? `sandbox-${randomUUID().slice(0, 8)}`
321
322
  : this.#options.defaults.id;
322
323
  const owner = this.#options.defaults.owner;
323
- const canExecute = connection.authScope === 'full';
324
- const socket = connection.socket as SandboxWsSocket;
324
+ // Every admitted host-authenticated socket carries a Console principal allowed to use it.
325
+ const canExecute = true;
326
+ const socket = sandboxSocketOf(connection);
325
327
  const connectionId = randomUUID();
326
328
  const subscription: SandboxConnection = {
327
329
  connectionId, target, owner, socket, canExecute, scoped: false,
@@ -387,16 +389,13 @@ export class SandboxWsEndpoint extends SandboxClient<SandboxConnection> implemen
387
389
  ...(parsed.senderRole ? { senderRole: parsed.senderRole } : {}),
388
390
  messageId, endpoint: this.#options.defaults.id, content: parsed.content, timestamp: parsed.timestamp,
389
391
  }));
392
+ // ADR 0056 §1: the simulated group role is a platform standing (master = 群主). It never
393
+ // grants framework roles; those come from the runtime (account owner / chat roles).
394
+ const standing: PlatformStandingLevel | undefined = parsed.senderRole === 'master' ? 'owner' : parsed.senderRole;
390
395
  const sender = {
391
396
  id: senderId,
392
397
  name: senderName,
393
- ...(parsed.senderRole
394
- ? {
395
- role: parsed.senderRole,
396
- roles: parsed.senderRole === 'master' ? ['master', 'admin'] : parsed.senderRole === 'admin' ? ['admin'] : ['member'],
397
- permissions: parsed.senderRole === 'master' ? ['master', 'admin'] : parsed.senderRole === 'admin' ? ['admin'] : [],
398
- }
399
- : {}),
398
+ ...(standing && conversation.kind !== 'private' ? { platform: { standing } } : {}),
400
399
  };
401
400
  void this[endpointSpec].events.message({
402
401
  event: raw,
package/src/protocol.ts CHANGED
@@ -37,6 +37,37 @@ export interface SandboxWsSocket {
37
37
  ): void;
38
38
  }
39
39
 
40
+ /** A Host {@link WsConnection} seen through the {@link SandboxWsSocket} surface. */
41
+ export function sandboxSocketOf(connection: {
42
+ send(data: string): void;
43
+ close(code?: number, reason?: string): void;
44
+ onMessage(listener: (data: string | Uint8Array) => void): () => void;
45
+ onClose(listener: (code: number, reason: string) => void): () => void;
46
+ }): SandboxWsSocket {
47
+ let open = true;
48
+ connection.onClose(() => { open = false; });
49
+ const subscriptions = new Map<(...args: unknown[]) => void, () => void>();
50
+ return {
51
+ get readyState() { return open ? WS_OPEN : 3; },
52
+ send: (data) => { if (open) connection.send(data); },
53
+ close: (code, reason) => connection.close(code, reason),
54
+ on(event, listener) {
55
+ if (event === 'message') {
56
+ subscriptions.set(listener, connection.onMessage((data) => {
57
+ listener(typeof data === 'string' ? data : new TextDecoder().decode(data));
58
+ }));
59
+ } else if (event === 'close') {
60
+ subscriptions.set(listener, connection.onClose(() => listener()));
61
+ }
62
+ // Transport errors surface as a close on a WsConnection.
63
+ },
64
+ off(_event, listener) {
65
+ subscriptions.get(listener)?.();
66
+ subscriptions.delete(listener);
67
+ },
68
+ };
69
+ }
70
+
40
71
  export type ResolvedSandboxBot = {
41
72
  readonly context: 'sandbox';
42
73
  readonly id: string;