@zhin.js/adapter-sandbox 1.1.33 → 1.1.35

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,114 @@
1
1
  # @zhin.js/adapter-process
2
2
 
3
+ ## 1.1.35
4
+
5
+ ### Patch Changes
6
+
7
+ - da9dc8a: 聊天角色引导文案(ADR 0060 P0):需要 zhin 角色的命令被拒绝时,回复说明去哪里获得角色(联系主人 / Console「聊天角色」页),不点名缺哪个角色或谁持有;发言者是群主 / 群管理员时另说明平台身份不等于 zhin 角色。`功能` / `角色` 的拒绝回复同样指向 Console,尚无全局 owner 时提示认领码;Agent 信任档位的限制说明改为「联系主人授予 trusted 角色」。Sandbox 页把模拟的「Master」改称「群主(平台身份)」,并显示服务端解析的 zhin 角色与 Agent 信任档位(入站回显帧新增 `senderChatRole` / `senderTrustLevel`)。ICQQ README 去掉已不读取的 `master`「必填」写法。
8
+ - 5d90159: 聊天身份 P3(ADR 0060):Sandbox 以我发言、`ai.personalPrincipals` 改读链接。
9
+
10
+ - **Sandbox 安全修复**:Console Sandbox 客户端自填的发送者 ID 一律是模拟身份——服务端写成保留 id `~sim:<id>`,不解析任何 zhin 角色,信任档位最低;填 owner 的 id 不再能冒充 owner。以 `~` 开头的发送者 id 不是聊天身份(`isChatIdentity` 为 false),不能持有、被授予或解析角色,也不记入最近发言人。
11
+ - Sandbox 新增「以我的聊天身份发言」(默认开启):已登录的 Console 用户按其链接的人在 Sandbox 上的身份发言,角色按该人的授予解析;未登录(引导令牌)与 `--standalone` 一律按模拟身份。新 RPC `chat-identities.simulated.ensure`(`self.chat-identity`)为调用者的人(没有则新建并链接)在模拟适配器上建立身份,不触及真实平台。`ChatRoleReader` 新增可选方法 `consoleSpeaker`。
12
+ - `ai.personalPrincipals` 首次启动导入为「人 ↔ Console 账号」链接(不授予角色);`rootId` 与当前目录不一致不再导致启动失败(按别名 + subjectId 导入并告警);之后个人推理主体只读链接表。`@zhin.js/agent`:`HostInferenceOptions.personalOwners` 可为函数(每次管理租约读取),`resolveInferenceManagementPrincipal` 的 `bindings` 可为函数,且 `full` 范围允许切换到调用者自己的个人推理主体;新增 `personalOwnersOfIdentities` / `chatIdentityOfPersonalOwner`。
13
+ - 「需要你处理」`chat-roles.imported` 列出 `ai.personalPrincipals` 导入的链接;若被链接的 Console 用户就是当前查看者且尚无全局 owner,提示「是否同时设为全局 owner」。确认已读同时标记该导入。
14
+ - 聊天 `角色 授予 / 撤销` 可用 `#<人 id 前缀>` 引用一个人(前缀唯一时)。
15
+
16
+ - 73475bd: 聊天身份安全复核(ADR 0060):链接一个人等于拿到这个人的全局授予,因此凡是建立或扩大链接的路径,只要目标人持有角色,就必须由全局 `iam.manage` 持有者完成。
17
+
18
+ - **绑定码**:
19
+ - Console 用户未链接、而身份所属的人持有角色时,非全局 `iam.manage` 生成的码不再建立链接(`needs-admin`)。
20
+ - 机器人回复写明码来自哪个 Console 账号。
21
+ - 码在兑换时复核创建者当前的全局 `iam.manage`;网关发出任何 `principal-revoked` 时作废该用户未用的码。网关在自定义角色的权限被修改或角色被删除时,也会通知持有该角色的用户。
22
+ - **`chat-identities.simulated.ensure`**:调用者链接的人持有全局角色时需要全局 `iam.manage`,否则拒绝(403)。
23
+ - **`ai.personalPrincipals`**:永不自动链接到持有角色的人;首次导入之后新增或修改的条目进入「需要你处理」,经 `chat-roles.imports.resolve` 导入或忽略。`chat-roles.imports.list` 新增 `personalPending`。
24
+ - **认领码**:
25
+ - 日志只记哈希前缀,码只由 `zhin status` 给出。
26
+ - 同一发送者 10 分钟内最多计 2 次错误,之后拒绝且不计数,不能反复让码轮换。
27
+ - **归并**:任一方带 Console 链接时需要全局 `iam.manage`。
28
+ - **非全局管理者**:看不到链接、暗示链接的 `linkMethod`、指向 Console 用户的 `createdBy` 与从链接得出的授予者名。
29
+ - **`chat-principals.import`**:导入的授予记为导入者授予,忽略文件里的 `grantedBy`。
30
+ - **Sandbox 发言复核**:「以我的聊天身份发言」时,若链接的人持有全局角色而 Console 用户没有全局 `iam.manage`,按模拟身份(无角色)发送,回显 `asMeUnavailable: 'needs-global-iam'`;`ChatRoleReader.consoleSpeaker` 新增可选参数 `{ canManageGlobal }`。
31
+ - **`ai.personalPrincipals` 首次导入**:没有任何条目的项目也记录首次导入,之后加入的条目等待确认;对待确认链接的「导入」「忽略」「确认已读」均写入审计。
32
+
33
+ - e95550b: Sandbox 账号可以在 Console 管理了(#1250):插件现在提供与其他适配器相同的 Console RPC(`createAdapterConsoleRpc`)——`status` 与 `endpoint-add` / `endpoint-update` / `endpoint-start` / `endpoint-stop` / `endpoint-remove`,不再返回 404「插件未提供该操作」;账号「接入」页可新增、停用、启用和删除 Sandbox 账号(字段 `owner`、`nickname`、`commandPrefix`)。新增插件权限 `sandbox:read`(read)与 `sandbox:write`(operate)。
34
+ - Updated dependencies [39db402]
35
+ - Updated dependencies [8bf8dfa]
36
+ - Updated dependencies [603b892]
37
+ - Updated dependencies [da9dc8a]
38
+ - Updated dependencies [bc31cd3]
39
+ - Updated dependencies [760e9f5]
40
+ - Updated dependencies [5d90159]
41
+ - Updated dependencies [73475bd]
42
+ - Updated dependencies [9d3f50b]
43
+ - Updated dependencies [35e5d89]
44
+ - Updated dependencies [809c6ee]
45
+ - Updated dependencies [817b2bf]
46
+ - Updated dependencies [9cd764a]
47
+ - Updated dependencies [b2ed753]
48
+ - @zhin.js/host-http@1.4.0
49
+ - @zhin.js/logger@1.2.0
50
+ - @zhin.js/core@1.9.0
51
+ - @zhin.js/client@1.2.1
52
+ - @zhin.js/adapter@1.3.1
53
+
54
+ ## 1.1.34
55
+
56
+ ### Patch Changes
57
+
58
+ - e6d7cc1: 配置表单与插件显示名的多语言约定(#1250):Schema 节点沿用已有的 `x-i18n`(`Schema#i18n()`),按 `zh-CN` / `en` 分别声明字段的 `title`、`description` 与 `enumLabels`;插件 `metadata`(`definePlugin` 或 `package.json#zhin.metadata`)新增可选的 `displayNameI18n: { 'zh-CN'?, en? }`,与 `displayName` 一样只能在一处声明,清单只接受这两个键且值必须是非空字符串。Console 插件列表(`/api/plugins`、插件详情)和 `feature.list` / `feature.matrix` 原样带出 `displayNameI18n`,由 Console 按界面语言选择(当前语言 → `en` → `displayName` → 实例 key)。没有这些字段时行为不变。
59
+
60
+ 官方插件补齐中英文配置字段标题与说明(group-suite、repeater、roulette、answers、calendar、ledger、reminder、rss、earthquake、bilibili、content-moderation、lottery、nettools、60s、process-monitor、activity-feedback)以及全部官方插件的中英文显示名。
61
+
62
+ - 70ddaf4: 插件市场元数据(#1250 marketplace-metadata):`package.json#zhin.metadata` 新增可选的 `descriptionI18n: { 'zh-CN'?, en? }`(本地化描述)与 `category`(`adapter`、`ai`、`admin`、`community`、`entertainment`、`game`、`information`、`moderation`、`service`、`utility` 之一),校验方式与 `displayNameI18n` 相同:只接受这两个语言键、值为非空字符串、分类必须在枚举内。这两个字段只能写在清单里,插件市场才能从发布的 `package.json` 读到。`@zhin.js/plugin-runtime` 导出 `PLUGIN_CATEGORIES`、`PLUGIN_CATEGORY_LABELS`、`informativeKeywords`、`packageAuthorName`、`readPluginMarketplaceMetadata` 等读取工具。
63
+
64
+ 市场读取侧:`/pub/marketplace/search` 带出 `displayNameI18n` / `descriptionI18n`,分类读声明的 `category`(旧索引的 `util` 等按别名映射),可选 `locale=zh-CN|en` 按语言解析显示名与描述,并按两种语言的名称与描述搜索;`/pub/marketplace/detail/*` 带出发布清单的显示名、描述翻译与分类。作者一律取 `author`(没有时取 `maintainers`),不再显示发布账号——此前 `plugins.json` 生成脚本优先读 `_npmUser`,CI 可信发布的包因此都显示为「GitHub Actions」。keywords 去掉 `zhin`、`zhin.js`、`bot` 等通用词后展示与参与搜索。`zhin search` / `zhin info` 同样显示中文描述、分类和维护者,`zhin info` 不再读不存在的 `zhin.displayName` / `zhin.category`。
65
+
66
+ 官方插件与适配器:显示名移到 `package.json#zhin.metadata`,补齐中英文描述、分类、3–6 个有信息量的 keywords,author 统一为 `{ name: "lc-cn", url: "https://github.com/zhinjs/zhin" }`(不再发布邮箱);npm `description` 与英文描述一致。
67
+
68
+ - 704c7a4: Sandbox 会话页与功能自助反馈(#1250):
69
+
70
+ - 审批标记:`UserInteractionRequest` 新增可选 `purpose: 'approval'`,Core 渲染为 keyboard 段 `data.purpose`(经正常出站链);IM 审批端口(`createRuntimeApprovalPort`)发出的「操作确认」带此标记。Sandbox 页面只给带 `data.purpose === 'approval'` 的收到消息标「需要你的确认」,游戏卡片的「放弃」、菜单分页等普通按钮消息不再被误标。
71
+ - Sandbox 输入区:顶栏只保留状态、停止 / 重试、对话与轨迹,其余(模拟发送者、运行环境、运行检查器、清空会话)收进「更多」菜单;底部快捷键提示改为可折叠;快捷命令不再写死 `/help`、`ping`、`/status`,改由新接口 `GET /api/conversations/workspaces/commands`(权限 `endpoint.view`)按该会话的命令索引与 endpoint 实际 `commandPrefix` 生成(菜单的真实命令名优先,无前缀不带 `/`,未注册的命令不出现)。
72
+ - 功能覆盖记录操作者:`feature_overrides.updated_by` 在同一文本列内记录结构化写入者(来源 `chat` / `console` / `cli`、聊天身份 adapter + 平台用户 ID + 显示名,或 Console 用户 principal id + 显示名),旧记录照常读取(`chat:…` / `user:…` 推出身份)。`feature.get` 与 `feature.conversations` 返回可选 `operator`:只有对该层级有 `feature.configure` 的调用方看到完整写入者(Console 用户 id 与显示名、聊天身份与名字),仅有 `feature.view` 的只看到来源(`{ source }`)。能解析时返回会话显示名(Sandbox 会话名),只按该会话所属的 Sandbox Endpoint(适配器 + Endpoint)及其当前 owner 匹配,且只返回给同时有 `endpoint.view` 的调用方(与工作区目录同一权限)。**降级注意**:写入过结构化写入者的行,在旧版本里 `updatedBy` 会原样显示为 JSON 字符串(`{"f":1,"by":…,"op":…}`),不影响读取与覆盖生效。
73
+ - Sandbox 输入区新增「@ 机器人」按钮:插入对当前机器人(ready 帧的 endpoint id)的 mention,文本形式为 `[@<机器人 id>]`,与入站 `[@机器人名]` 解析一致;@ 候选列表里的机器人条目改为真实 id;快捷操作帮助同步说明。
74
+ - 页面兜底渲染:不认识的段不再只显示 `[type]`——`markdown` 显示原文,keyboard 与未渲染的 JSX(`{"$jsx":…}`)读出文本、按钮降级为 `[按钮标签]`,不再出现原始 JSX 对象。
75
+
76
+ 已知限制:Sandbox 页面的「需要你的确认」标记只用于展示,依据收到消息里 keyboard 段的 `data.purpose`;能自行构造该段的插件可以让普通按钮也显示这个标记(不影响审批本身的鉴权)。
77
+
78
+ - 4922472: 沙盒(#1250):会话记录加载期间消息区保持与空状态相同的高度并显示「正在加载会话记录…」;快捷命令按钮可用键盘到达(Tab),鼠标点击不会把焦点留在按钮上;点击后只预填输入框并把焦点移到输入框,由回车或「发送」发出,避免布局变化后一次点击加一次回车连发两条。输入框为空时直接填入命令;已有草稿(文字、图片、表情、@)时把命令插入到光标处(光标不在输入框内则插到开头),不删除草稿,并保留撤销记录。
79
+ - 713853a: Sandbox:群聊里输入的 `[@<机器人 id 或 nickname>]` 现在解析为对机器人的 mention(此前只是普通文本,消息被静默忽略);其他 `[@名称]` 解析为普通 mention 段。(#1250)
80
+ - Updated dependencies [ab14f22]
81
+ - Updated dependencies [b3ba941]
82
+ - Updated dependencies [7cd299e]
83
+ - Updated dependencies [7cd299e]
84
+ - Updated dependencies [7126d03]
85
+ - Updated dependencies [9026329]
86
+ - Updated dependencies [1d1746e]
87
+ - Updated dependencies [252d5dc]
88
+ - Updated dependencies [71aa159]
89
+ - Updated dependencies [ccab2c1]
90
+ - Updated dependencies [b00725c]
91
+ - Updated dependencies [c6b5563]
92
+ - Updated dependencies [f1a9745]
93
+ - Updated dependencies [e0b4e51]
94
+ - Updated dependencies [cca4427]
95
+ - Updated dependencies [627fb5e]
96
+ - Updated dependencies [70ddaf4]
97
+ - Updated dependencies [b08cff2]
98
+ - Updated dependencies [dbdfca3]
99
+ - Updated dependencies [704c7a4]
100
+ - Updated dependencies [b56cca9]
101
+ - Updated dependencies [f3910f1]
102
+ - Updated dependencies [07bd3dc]
103
+ - @zhin.js/client@1.2.0
104
+ - @zhin.js/host-http@1.3.0
105
+ - @zhin.js/core@1.8.0
106
+ - @zhin.js/adapter@1.3.0
107
+ - @zhin.js/im-contract@1.2.0
108
+ - @zhin.js/console-contract@1.2.0
109
+ - @zhin.js/page@1.1.20
110
+ - @zhin.js/feature-kit@1.1.18
111
+
3
112
  ## 1.1.33
4
113
 
5
114
  ### Patch Changes
package/README.md CHANGED
@@ -83,7 +83,7 @@ Console 原生渲染 Markdown 格式的流式回复(`markdown` 段,`data.con
83
83
 
84
84
  ## 使用方式
85
85
 
86
- 1. 启动 Zhin 实例:`pnpm dev`(终端会打印 Host 地址,一般为 `http://127.0.0.1:8086`)
86
+ 1. 启动 Zhin 实例:`pnpm dev`(终端会打印 Host 地址,一般为 `http://127.0.0.1:8068`)
87
87
  2. 打开 **[Remote Console](https://console.zhin.dev)**,API Base 与 Host 地址一致,用 Console 账号登录(首次连接用 `http.token` / `HTTP_TOKEN` 创建所有者)
88
88
  3. 连接后在 Console 侧栏「试聊一下」(`/sandbox`)发送消息
89
89
 
@@ -103,6 +103,10 @@ Console 原生渲染 Markdown 格式的流式回复(`markdown` 段,`data.con
103
103
 
104
104
  每个 endpoint 通过 Root 提供的 HTTP Host(`httpHostToken`)挂载一个 WebSocket 路径,协议见下文「消息格式(wire 协议)」。
105
105
 
106
+ ## 在 Console 管理账号
107
+
108
+ Sandbox 与其他适配器一样提供账号管理(`status`、`endpoint-add` / `endpoint-start` / `endpoint-stop` / `endpoint-remove`):在 Console 的账号「接入」页可以新增、停用、启用和删除 Sandbox 账号,字段为所有者用户 ID(`owner`)、机器人昵称(`nickname`)与命令前缀(`commandPrefix`)。新增的账号保存后处于停用状态,需要手动启用。查看需要 `sandbox:read`(`read` 级别),增删与启停需要 `sandbox:write`(`operate` 级别)。
109
+
106
110
  ## 消息格式(wire 协议)
107
111
 
108
112
  Console 沙盒页和自己写的测试客户端都用这套协议。每个 WebSocket 文本帧是一个 UTF-8 JSON 对象。
@@ -150,6 +154,7 @@ Console 沙盒页和自己写的测试客户端都用这套协议。每个 WebSo
150
154
 
151
155
  - 帧内容不是 JSON 时,整段文本按一条纯文本消息处理。
152
156
  - 消息的发送者固定为 endpoint 的 `owner`。
157
+ - **@ 提及**:文本里的 `[@名称]` 解析为 `mention` 段。名称等于 endpoint 的 `id`(如 `sandbox-bot`)或配置的 `nickname`(不区分大小写)时视为 @ 机器人:群聊里 `[@sandbox-bot] /help` 会被识别为对机器人说话,且命令文本去掉这段提及(`/help`);其他名称保留为 `@名称`。从输入框 @ 选择器插入的 `mention` 段若带的是机器人名称,也会改写成机器人 `id`。
153
158
  - **按钮回传**:`content` 中的 `{ "type": "action", "data": { "id": "...", "payload": "..." } }` 段会作为交互动作交给命令或 Agent;只填 `id` 或 `payload` 时,另一个取相同的值。消息里没有文本时,`payload` 作为消息文本。
154
159
 
155
160
  `agentRun` 字段:
package/lib/adapter.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Adapter } from 'zhin.js/adapter';
2
2
  import { httpHostToken } from '@zhin.js/host-http';
3
3
  import { projectLocaleToken, resolveLocale } from 'zhin.js/i18n';
4
+ import { chatRolesToken } from 'zhin.js';
4
5
  import { resolveSandboxEndpoint } from './protocol.js';
5
6
  import { SandboxWsEndpoint } from './endpoint.js';
6
7
  export class SandboxAdapter extends Adapter {
@@ -12,6 +13,16 @@ export class SandboxAdapter extends Adapter {
12
13
  validateConfiguration(config) { resolveSandboxEndpoint(config); }
13
14
  createEndpoint(input, execution) {
14
15
  return new SandboxWsEndpoint({ id: execution.canonicalId, defaults: resolveSandboxEndpoint(input),
15
- http: this.#context.use(httpHostToken), locale: resolveLocale(this.#context.use(projectLocaleToken)) });
16
+ http: this.#context.use(httpHostToken), locale: resolveLocale(this.#context.use(projectLocaleToken)),
17
+ ...optionalChatRoles(() => this.#context.use(chatRolesToken)) });
18
+ }
19
+ }
20
+ /** The instance provides chat roles (ADR 0060 §6); hosts without them (tests, other roots) show no zhin role. */
21
+ function optionalChatRoles(read) {
22
+ try {
23
+ return { chatRoles: read() };
24
+ }
25
+ catch {
26
+ return {};
16
27
  }
17
28
  }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Sandbox Console RPC (#1250): status plus the shared endpoint management — add, start, stop and
3
+ * remove Sandbox accounts from the Console like every other adapter (`createAdapterConsoleRpc`).
4
+ *
5
+ * The plugin's own page (`pages/index`, the conversation workbench) carries the RPC; the Console's
6
+ * account view renders the shared adapter account panel from `status`.
7
+ */
8
+ import { type AdapterConsoleField } from 'zhin.js/adapter';
9
+ import type { PluginConsoleRpc } from 'zhin.js';
10
+ export declare const sandboxConsoleFields: readonly AdapterConsoleField[];
11
+ export declare const sandboxConsoleSpec: Readonly<{
12
+ adapterKey: "sandbox";
13
+ adapterDisplayName: "Sandbox";
14
+ fields: readonly AdapterConsoleField[];
15
+ docsUrl: "https://zhin.js.org/adapters/sandbox";
16
+ readPermission: "sandbox:read";
17
+ writePermission: "sandbox:write";
18
+ idHint: "账号名,例如 sandbox-bot";
19
+ idHintI18n: {
20
+ en: string;
21
+ };
22
+ }>;
23
+ export declare function createSandboxConsoleRpc(getConfig: () => unknown): PluginConsoleRpc;
package/lib/console.js ADDED
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Sandbox Console RPC (#1250): status plus the shared endpoint management — add, start, stop and
3
+ * remove Sandbox accounts from the Console like every other adapter (`createAdapterConsoleRpc`).
4
+ *
5
+ * The plugin's own page (`pages/index`, the conversation workbench) carries the RPC; the Console's
6
+ * account view renders the shared adapter account panel from `status`.
7
+ */
8
+ import { createAdapterConsoleRpc } from 'zhin.js/adapter';
9
+ export const sandboxConsoleFields = Object.freeze([
10
+ {
11
+ key: 'owner',
12
+ label: '所有者用户 ID',
13
+ labelI18n: { en: 'Owner user ID' },
14
+ placeholder: 'sandbox-user',
15
+ description: 'Console 里以这个用户身份发消息;不填时使用适配器的默认值',
16
+ descriptionI18n: { en: 'The Console chats as this user; the adapter default is used when empty' },
17
+ },
18
+ {
19
+ key: 'nickname',
20
+ label: '机器人昵称',
21
+ labelI18n: { en: 'Bot nickname' },
22
+ description: '会话里显示的机器人名字(可选)',
23
+ descriptionI18n: { en: 'Bot name shown in conversations (optional)' },
24
+ },
25
+ {
26
+ key: 'commandPrefix',
27
+ label: '命令前缀',
28
+ labelI18n: { en: 'Command prefix' },
29
+ placeholder: '/',
30
+ description: '只把以它开头的消息当作命令;留空时任意文本都按命令匹配',
31
+ descriptionI18n: { en: 'Only messages starting with it are commands; empty matches any text' },
32
+ },
33
+ ]);
34
+ export const sandboxConsoleSpec = Object.freeze({
35
+ adapterKey: 'sandbox',
36
+ adapterDisplayName: 'Sandbox',
37
+ fields: sandboxConsoleFields,
38
+ docsUrl: 'https://zhin.js.org/adapters/sandbox',
39
+ readPermission: 'sandbox:read',
40
+ writePermission: 'sandbox:write',
41
+ idHint: '账号名,例如 sandbox-bot',
42
+ idHintI18n: { en: 'Account name, e.g. sandbox-bot' },
43
+ });
44
+ export function createSandboxConsoleRpc(getConfig) {
45
+ return createAdapterConsoleRpc({ ...sandboxConsoleSpec, getConfig });
46
+ }
package/lib/endpoint.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { type Locale } from 'zhin.js/i18n';
2
2
  import { endpointSpec, type Endpoint, type EndpointSpecification } from 'zhin.js/adapter';
3
- import type { HttpHost } from '@zhin.js/host-http';
4
- import type { CapabilityId } from 'zhin.js';
3
+ import { type HttpHost, type WsConnection } from '@zhin.js/host-http';
4
+ import { type CapabilityId, type ChatRoleReader } from 'zhin.js';
5
5
  import { type ResolvedSandboxBot, type SandboxWsSocket, type SandboxConversation } from './protocol.js';
6
6
  import { SandboxClient } from './client.js';
7
7
  interface SandboxConnection {
@@ -36,7 +36,29 @@ export interface SandboxEndpointOptions {
36
36
  readonly id: CapabilityId;
37
37
  readonly http: HttpHost;
38
38
  readonly defaults: ResolvedSandboxBot;
39
+ /** Chat roles (`chatRolesToken`, ADR 0060 §6): the sender's zhin role shown on the page. */
40
+ readonly chatRoles?: ChatRoleReader;
39
41
  }
42
+ /**
43
+ * ADR 0060 §5.4 (P0): what the Runtime resolves for this sender — zhin role and the Agent trust
44
+ * tier it implies (`resolveTurnTrustLevel`: a global owner → `owner`, admin / trusted or a
45
+ * lower-level owner → `trusted_member`, anyone else over IM → `group_member`). The page shows it
46
+ * next to the simulated platform standing so 群主 is never mistaken for a zhin role.
47
+ */
48
+ export declare function sandboxSenderRoleFacts(reader: ChatRoleReader | undefined, conversation: Parameters<ChatRoleReader['factsOf']>[0], senderId: string): {
49
+ senderChatRole?: string;
50
+ senderTrustLevel: 'owner' | 'trusted_member' | 'group_member';
51
+ };
52
+ /** Why 「以我的聊天身份发言」 was not used for a message (`asMeUnavailable` on the echo). */
53
+ export type SandboxAsMeUnavailableReason = 'no-console-user' | 'no-identity' | 'needs-global-iam';
54
+ interface SandboxConsoleUser {
55
+ readonly userId: string;
56
+ readonly displayName?: string;
57
+ /** Holds global `iam.manage`: may speak as a linked person who holds a global grant (ADR 0060 §5.4). */
58
+ readonly canManageGlobal: boolean;
59
+ }
60
+ /** The signed-in Console user behind a socket (sessions and API tokens); none for the bootstrap principal or standalone. */
61
+ export declare function sandboxConsoleUser(principal: WsConnection['principal']): SandboxConsoleUser | undefined;
40
62
  /**
41
63
  * Sandbox 是本地开发/测试面,无平台社交图谱(好友/群/频道),
42
64
  * 不适用 EndpointManagement 语义端口;本 endpoint 不暴露该端口。
package/lib/endpoint.js CHANGED
@@ -5,9 +5,11 @@ import { createEndpointSpecification, endpointSpec } from 'zhin.js/adapter';
5
5
  */
6
6
  import { randomUUID } from 'node:crypto';
7
7
  import { execFile } from 'node:child_process';
8
+ import { principalAllows } from '@zhin.js/host-http';
8
9
  import { formatCompact, getAdapterLogger } from '@zhin.js/logger';
10
+ import { hostChatRole } from 'zhin.js';
9
11
  import { EndpointDeliveryError } from '@zhin.js/im-contract';
10
- import { bindSandboxWsSocket, sandboxSocketOf, formatSandboxOutbound, parseSandboxWsFrame, sandboxInboundConversation, whenWsOpen, } from './protocol.js';
12
+ import { bindSandboxWsSocket, sandboxSocketOf, formatSandboxOutbound, parseSandboxWsFrame, sandboxInboundConversation, sandboxSimulatedSenderId, whenWsOpen, } from './protocol.js';
11
13
  import { SandboxClient } from './client.js';
12
14
  const claimedWsPaths = new WeakMap();
13
15
  function claimSandboxWsPath(http, name) {
@@ -73,6 +75,41 @@ const messages = createMessages({
73
75
  profile: { 'zh-CN': '会话已启用持久化运行配置。', en: 'The conversation uses a persistent runtime profile.' },
74
76
  invalidFrame: { 'zh-CN': '会话订阅或消息格式无效。', en: 'The conversation subscription or message format is invalid.' },
75
77
  });
78
+ /**
79
+ * ADR 0060 §5.4 (P0): what the Runtime resolves for this sender — zhin role and the Agent trust
80
+ * tier it implies (`resolveTurnTrustLevel`: a global owner → `owner`, admin / trusted or a
81
+ * lower-level owner → `trusted_member`, anyone else over IM → `group_member`). The page shows it
82
+ * next to the simulated platform standing so 群主 is never mistaken for a zhin role.
83
+ */
84
+ export function sandboxSenderRoleFacts(reader, conversation, senderId) {
85
+ let facts;
86
+ try {
87
+ facts = reader?.factsOf(conversation, senderId);
88
+ }
89
+ catch {
90
+ facts = undefined;
91
+ }
92
+ const host = hostChatRole(facts);
93
+ return {
94
+ ...(facts?.chatRole ? { senderChatRole: facts.chatRole } : {}),
95
+ senderTrustLevel: host === 'owner' ? 'owner' : host ? 'trusted_member' : 'group_member',
96
+ };
97
+ }
98
+ /** The signed-in Console user behind a socket (sessions and API tokens); none for the bootstrap principal or standalone. */
99
+ export function sandboxConsoleUser(principal) {
100
+ if (!principal || (principal.kind !== 'user' && principal.kind !== 'api-token'))
101
+ return undefined;
102
+ if (typeof principal.userId !== 'string' || !principal.userId)
103
+ return undefined;
104
+ let canManageGlobal = false;
105
+ try {
106
+ canManageGlobal = principalAllows(principal, 'iam.manage');
107
+ }
108
+ catch {
109
+ canManageGlobal = false;
110
+ }
111
+ return Object.freeze({ userId: principal.userId, ...(principal.displayName ? { displayName: principal.displayName } : {}), canManageGlobal });
112
+ }
76
113
  /**
77
114
  * Sandbox 是本地开发/测试面,无平台社交图谱(好友/群/频道),
78
115
  * 不适用 EndpointManagement 语义端口;本 endpoint 不暴露该端口。
@@ -254,6 +291,9 @@ export class SandboxWsEndpoint extends SandboxClient {
254
291
  const owner = this.#options.defaults.owner;
255
292
  // Every admitted host-authenticated socket carries a Console principal allowed to use it.
256
293
  const canExecute = true;
294
+ // ADR 0060 §5.4: a signed-in Console user may speak as their linked chat identity. The bootstrap
295
+ // principal and `--standalone` (no gateway) have no user: everything is simulated there.
296
+ const consoleUser = sandboxConsoleUser(connection.principal);
257
297
  const socket = sandboxSocketOf(connection);
258
298
  const connectionId = randomUUID();
259
299
  const subscription = {
@@ -277,7 +317,10 @@ export class SandboxWsEndpoint extends SandboxClient {
277
317
  }));
278
318
  return;
279
319
  }
280
- const frame = parseSandboxWsFrame(raw);
320
+ const frame = parseSandboxWsFrame(raw, {
321
+ id: this.#options.defaults.id,
322
+ ...(this.#options.defaults.nickname ? { names: [this.#options.defaults.nickname] } : {}),
323
+ });
281
324
  if (frame.kind === 'invalid') {
282
325
  socket.send(JSON.stringify({
283
326
  type: 'error', endpoint: target, connectionId,
@@ -297,13 +340,17 @@ export class SandboxWsEndpoint extends SandboxClient {
297
340
  }
298
341
  const parsed = frame.message;
299
342
  void this.#emitPlatformEvent('message', raw);
300
- const senderId = parsed.senderId || owner;
301
- const senderName = parsed.senderName || senderId;
302
343
  const sceneId = parsed.id || owner;
303
344
  const conversation = { ...sandboxInboundConversation(String(this.#options.id), {
304
345
  type: parsed.type,
305
346
  id: sceneId,
306
347
  }), endpoint: this[endpointSpec].identity };
348
+ const speaker = this.#speaker(parsed.asMe === true, consoleUser, conversation);
349
+ // The id the page chose (shown as typed); the Runtime only ever sees the speaker's real
350
+ // identity or the reserved simulated id, never a client-chosen id that could hold a role.
351
+ const clientSenderId = parsed.senderId || owner;
352
+ const senderId = speaker.identity ? speaker.identity.userId : sandboxSimulatedSenderId(clientSenderId);
353
+ const senderName = speaker.identity ? (consoleUser?.displayName || speaker.identity.userId) : (parsed.senderName || clientSenderId);
307
354
  this.#logger.debug(formatCompact({
308
355
  op: 'sandbox_recv',
309
356
  target,
@@ -317,8 +364,12 @@ export class SandboxWsEndpoint extends SandboxClient {
317
364
  const messageId = parsed.messageId ?? randomUUID();
318
365
  this.#broadcast(this.#subscribers(scene, true), JSON.stringify({
319
366
  ...scene, conversation: scene, direction: 'inbound', senderId,
320
- ...(parsed.senderName ? { senderName: parsed.senderName } : {}),
367
+ displaySenderId: speaker.identity ? speaker.identity.userId : clientSenderId,
368
+ simulated: !speaker.identity,
369
+ ...(speaker.unavailable ? { asMeUnavailable: speaker.unavailable } : {}),
370
+ ...(speaker.identity || parsed.senderName ? { senderName } : {}),
321
371
  ...(parsed.senderRole ? { senderRole: parsed.senderRole } : {}),
372
+ ...sandboxSenderRoleFacts(this.#options.chatRoles, conversation, senderId),
322
373
  messageId, endpoint: this.#options.defaults.id, content: parsed.content, timestamp: parsed.timestamp,
323
374
  }));
324
375
  // ADR 0056 §1: the simulated group role is a platform standing (master = 群主). It never
@@ -394,6 +445,8 @@ export class SandboxWsEndpoint extends SandboxClient {
394
445
  endpoint: target,
395
446
  workingDirectory: process.cwd(),
396
447
  canExecute,
448
+ // Whether 「以我的聊天身份发言」 can work on this socket (a signed-in Console user).
449
+ consoleUser: consoleUser !== undefined,
397
450
  shellIsolation,
398
451
  content: [{
399
452
  type: 'text',
@@ -410,6 +463,32 @@ export class SandboxWsEndpoint extends SandboxClient {
410
463
  whenWsOpen(socket, () => socket.send(readyPayload));
411
464
  });
412
465
  }
466
+ /**
467
+ * ADR 0060 §5.4: the identity a message speaks as. Only on request, only for a signed-in Console
468
+ * user, and only an identity of the person linked to that user on this adapter (`consoleSpeaker`).
469
+ * A person who holds a global grant is spoken as only by a caller with global `iam.manage`;
470
+ * otherwise the message goes out as a simulated, role-less sender (`needs-global-iam`), the
471
+ * same rule `chat-identities.simulated.ensure` applies when it creates the identity.
472
+ */
473
+ #speaker(asMe, user, conversation) {
474
+ if (!asMe)
475
+ return {};
476
+ if (!user)
477
+ return { unavailable: 'no-console-user' };
478
+ const speaker = (canManageGlobal) => {
479
+ try {
480
+ return this.#options.chatRoles?.consoleSpeaker?.(conversation, user.userId, { canManageGlobal });
481
+ }
482
+ catch {
483
+ return undefined;
484
+ }
485
+ };
486
+ const identity = speaker(user.canManageGlobal);
487
+ if (identity)
488
+ return { identity };
489
+ // Tell 「no identity yet」 apart from 「the person holds global grants」.
490
+ return { unavailable: !user.canManageGlobal && speaker(true) ? 'needs-global-iam' : 'no-identity' };
491
+ }
413
492
  #ensurePlaceholder(name, owner) {
414
493
  if (this.connectionRecords.has(name))
415
494
  return;
package/lib/protocol.d.ts CHANGED
@@ -29,6 +29,8 @@ export type ResolvedSandboxBot = {
29
29
  readonly randomNamePerConnection: boolean;
30
30
  readonly streaming: boolean;
31
31
  readonly streamingIntervalMs: number;
32
+ /** Configured `nickname`; `[@nickname]` also mentions this bot. */
33
+ readonly nickname?: string;
32
34
  };
33
35
  /** One endpoint config after AdapterIndex expands `plugins.<instanceKey>.endpoints`. */
34
36
  export interface SandboxEndpointConfig extends EndpointProfileConfiguration {
@@ -63,6 +65,11 @@ export interface SandboxParsedMessage {
63
65
  senderId?: string;
64
66
  senderName?: string;
65
67
  senderRole?: SandboxSenderRole;
68
+ /**
69
+ * ADR 0060 §5.4: speak as the chat identity linked to the authenticated Console user instead of
70
+ * `senderId`. The server decides; without such an identity the message is simulated.
71
+ */
72
+ asMe?: boolean;
66
73
  }
67
74
  export type SandboxInboundEnvelope = SandboxParsedMessage;
68
75
  export type SandboxWsFrame = {
@@ -74,10 +81,26 @@ export type SandboxWsFrame = {
74
81
  } | {
75
82
  readonly kind: 'invalid';
76
83
  };
84
+ /**
85
+ * The bot this socket talks to. Typed `[@<id or name>]` text (the input hint the Sandbox page shows)
86
+ * becomes a mention segment; a match on `id` or one of `names` (case-insensitive) targets `id`,
87
+ * so the IM layer recognises it as a mention of the bot.
88
+ */
89
+ export interface SandboxSelfMention {
90
+ readonly id: string;
91
+ readonly names?: readonly string[];
92
+ }
77
93
  /** Control frames never fall through into chat or platform message hooks. */
78
- export declare function parseSandboxWsFrame(raw: string): SandboxWsFrame;
79
- export declare function parseSandboxWsPayload(raw: string): SandboxParsedMessage;
94
+ export declare function parseSandboxWsFrame(raw: string, self?: SandboxSelfMention): SandboxWsFrame;
95
+ export declare function parseSandboxWsPayload(raw: string, self?: SandboxSelfMention): SandboxParsedMessage;
80
96
  export declare const parseSandboxInboundPayload: typeof parseSandboxWsPayload;
97
+ /**
98
+ * ADR 0060 §5.4: a client-chosen sender id becomes a reserved simulated id (`~sim:<id>`). Ids
99
+ * starting with `~` are never chat identities (`isChatIdentity`), so a simulated sender holds no
100
+ * zhin role whatever id it types — including the id of an owner.
101
+ */
102
+ export declare const SANDBOX_SIMULATED_PREFIX = "~sim:";
103
+ export declare function sandboxSimulatedSenderId(clientId: string): string;
81
104
  /**
82
105
  * 入站归一化 → ConversationRef。sandbox 无平台社交图谱:
83
106
  * `private`/`group`/`channel` 直映射;`direct`(私聊)归 'private';
package/lib/protocol.js CHANGED
@@ -47,6 +47,7 @@ export function resolveSandboxEndpoint(config) {
47
47
  randomNamePerConnection: false,
48
48
  streaming: config.streaming !== false,
49
49
  streamingIntervalMs,
50
+ ...(optionalEndpointField(config.nickname) ? { nickname: optionalEndpointField(config.nickname) } : {}),
50
51
  };
51
52
  }
52
53
  function optionalEndpointField(value) {
@@ -106,8 +107,65 @@ function readSandboxWirePayload(raw) {
106
107
  return { text: raw };
107
108
  }
108
109
  }
110
+ const TYPED_MENTION = /\[@([^\[\]\n]{1,64})\]/gu;
111
+ function expandTypedMentions(content, text, self) {
112
+ const selfKeys = new Set([self?.id, ...(self?.names ?? [])]
113
+ .flatMap(value => typeof value === 'string' && value.trim() ? [value.trim().toLowerCase()] : []));
114
+ const resolve = (name) => {
115
+ const trimmed = name.trim();
116
+ return self && selfKeys.has(trimmed.toLowerCase()) ? { target: self.id, self: true } : { target: trimmed, self: false };
117
+ };
118
+ let expanded = false;
119
+ const next = [];
120
+ for (const segment of content) {
121
+ // A picked mention (`mention` segment) may carry the bot's name instead of its id.
122
+ if ((segment.type === 'mention' || segment.type === 'at') && self && typeof segment.data?.target === 'string'
123
+ && segment.data.target !== self.id && selfKeys.has(segment.data.target.trim().toLowerCase())) {
124
+ expanded = true;
125
+ next.push({ ...segment, data: { ...segment.data, target: self.id } });
126
+ continue;
127
+ }
128
+ const value = segment.type === 'text' ? segment.data?.text : undefined;
129
+ if (typeof value !== 'string' || !value.includes('[@')) {
130
+ next.push(segment);
131
+ continue;
132
+ }
133
+ let last = 0;
134
+ for (const match of value.matchAll(TYPED_MENTION)) {
135
+ const name = match[1];
136
+ if (!name.trim())
137
+ continue;
138
+ expanded = true;
139
+ if (match.index > last)
140
+ next.push({ type: 'text', data: { text: value.slice(last, match.index) } });
141
+ const { target } = resolve(name);
142
+ next.push({ type: 'mention', data: { target, name: name.trim() } });
143
+ last = match.index + match[0].length;
144
+ }
145
+ if (last === 0)
146
+ next.push(segment);
147
+ else if (last < value.length)
148
+ next.push({ type: 'text', data: { text: value.slice(last) } });
149
+ }
150
+ if (!expanded)
151
+ return { content, text };
152
+ // Plain-text view: drop mentions of the bot (like other platforms strip the at-self prefix),
153
+ // keep `@name` for anyone else so commands and the Agent still see who was addressed.
154
+ let removedSelf = false;
155
+ const plain = text.replace(TYPED_MENTION, (whole, name) => {
156
+ if (!name.trim())
157
+ return whole;
158
+ const resolved = resolve(name);
159
+ if (resolved.self) {
160
+ removedSelf = true;
161
+ return '';
162
+ }
163
+ return `@${resolved.target}`;
164
+ });
165
+ return { content: next, text: removedSelf ? plain.replace(/[ \t]{2,}/gu, ' ').trim() : plain };
166
+ }
109
167
  /** Control frames never fall through into chat or platform message hooks. */
110
- export function parseSandboxWsFrame(raw) {
168
+ export function parseSandboxWsFrame(raw, self) {
111
169
  const payload = readSandboxWirePayload(raw);
112
170
  if ('op' in payload) {
113
171
  const conversation = payload.conversation;
@@ -117,25 +175,25 @@ export function parseSandboxWsFrame(raw) {
117
175
  return { kind: 'invalid' };
118
176
  return { kind: 'subscribe', conversation: { type: conversation.type, id: conversation.id } };
119
177
  }
120
- const message = normalizeSandboxWsPayload(payload, raw);
178
+ const message = normalizeSandboxWsPayload(payload, raw, self);
121
179
  if (!['private', 'direct', 'group', 'channel', 'guild'].includes(message.type)
122
180
  || typeof message.id !== 'string')
123
181
  return { kind: 'invalid' };
124
182
  return { kind: 'message', message };
125
183
  }
126
- export function parseSandboxWsPayload(raw) {
127
- return normalizeSandboxWsPayload(readSandboxWirePayload(raw), raw);
184
+ export function parseSandboxWsPayload(raw, self) {
185
+ return normalizeSandboxWsPayload(readSandboxWirePayload(raw), raw, self);
128
186
  }
129
187
  export const parseSandboxInboundPayload = parseSandboxWsPayload;
130
- function normalizeSandboxWsPayload(payload, raw) {
188
+ function normalizeSandboxWsPayload(payload, raw, self) {
131
189
  const type = payload.type ?? 'private';
132
190
  const id = payload.id ?? 'sandbox-user';
133
- const content = typeof payload.content === 'string'
191
+ const wireContent = typeof payload.content === 'string'
134
192
  ? [{ type: 'text', data: { text: payload.content } }]
135
193
  : Array.isArray(payload.content)
136
194
  ? payload.content
137
195
  : [{ type: 'text', data: { text: payload.text ?? raw } }];
138
- const actionSegment = content.find((segment) => segment.type === 'action');
196
+ const actionSegment = wireContent.find((segment) => segment.type === 'action');
139
197
  let action;
140
198
  if (actionSegment?.data) {
141
199
  const actionPayload = typeof actionSegment.data.payload === 'string'
@@ -150,7 +208,7 @@ function normalizeSandboxWsPayload(payload, raw) {
150
208
  action = { id: actionId || actionPayload, payload: actionPayload || actionId };
151
209
  }
152
210
  }
153
- let text = content
211
+ let text = wireContent
154
212
  .flatMap((segment) => (segment.type === 'text' && typeof segment.data?.text === 'string'
155
213
  ? [segment.data.text]
156
214
  : []))
@@ -160,6 +218,9 @@ function normalizeSandboxWsPayload(payload, raw) {
160
218
  ? payload.text
161
219
  : action?.payload ?? raw;
162
220
  }
221
+ const typed = expandTypedMentions(wireContent, text, self);
222
+ const content = typed.content;
223
+ text = typed.text;
163
224
  const agentRun = normalizeSandboxAgentRunConfig(payload.agentRun);
164
225
  const rawMessageId = typeof payload.messageId === 'string' ? payload.messageId.trim() : '';
165
226
  const messageId = /^[A-Za-z0-9._:-]{1,160}$/u.test(rawMessageId) ? rawMessageId : undefined;
@@ -186,8 +247,18 @@ function normalizeSandboxWsPayload(payload, raw) {
186
247
  ...(senderId ? { senderId } : {}),
187
248
  ...(senderName ? { senderName } : {}),
188
249
  ...(senderRole ? { senderRole } : {}),
250
+ ...(payload.asMe === true ? { asMe: true } : {}),
189
251
  };
190
252
  }
253
+ /**
254
+ * ADR 0060 §5.4: a client-chosen sender id becomes a reserved simulated id (`~sim:<id>`). Ids
255
+ * starting with `~` are never chat identities (`isChatIdentity`), so a simulated sender holds no
256
+ * zhin role whatever id it types — including the id of an owner.
257
+ */
258
+ export const SANDBOX_SIMULATED_PREFIX = '~sim:';
259
+ export function sandboxSimulatedSenderId(clientId) {
260
+ return clientId.startsWith(SANDBOX_SIMULATED_PREFIX) ? clientId : `${SANDBOX_SIMULATED_PREFIX}${clientId}`;
261
+ }
191
262
  /**
192
263
  * 入站归一化 → ConversationRef。sandbox 无平台社交图谱:
193
264
  * `private`/`group`/`channel` 直映射;`direct`(私聊)归 'private';