@zhin.js/adapter-sandbox 1.1.34 → 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 +51 -0
- package/README.md +5 -1
- package/lib/adapter.js +12 -1
- package/lib/console.d.ts +23 -0
- package/lib/console.js +46 -0
- package/lib/endpoint.d.ts +24 -2
- package/lib/endpoint.js +80 -4
- package/lib/protocol.d.ts +12 -0
- package/lib/protocol.js +10 -0
- package/package.json +13 -13
- package/pages/index/SandboxChat.js +34 -4
- package/pages/index/SandboxChat.tsx +69 -9
- package/pages/index/chatIdentity.js +47 -0
- package/pages/index/chatIdentity.ts +66 -0
- package/pages/index/messages.js +12 -0
- package/pages/index/messages.ts +12 -0
- package/pages/index/styles.js +7 -0
- package/pages/index/styles.ts +7 -0
- package/plugin.js +7 -0
- package/src/adapter.ts +7 -1
- package/src/console.ts +50 -0
- package/src/endpoint.ts +77 -5
- package/src/protocol.ts +18 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,56 @@
|
|
|
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
|
+
|
|
3
54
|
## 1.1.34
|
|
4
55
|
|
|
5
56
|
### 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:
|
|
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 对象。
|
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
|
}
|
package/lib/console.d.ts
ADDED
|
@@ -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
|
|
4
|
-
import type
|
|
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 = {
|
|
@@ -300,13 +340,17 @@ export class SandboxWsEndpoint extends SandboxClient {
|
|
|
300
340
|
}
|
|
301
341
|
const parsed = frame.message;
|
|
302
342
|
void this.#emitPlatformEvent('message', raw);
|
|
303
|
-
const senderId = parsed.senderId || owner;
|
|
304
|
-
const senderName = parsed.senderName || senderId;
|
|
305
343
|
const sceneId = parsed.id || owner;
|
|
306
344
|
const conversation = { ...sandboxInboundConversation(String(this.#options.id), {
|
|
307
345
|
type: parsed.type,
|
|
308
346
|
id: sceneId,
|
|
309
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);
|
|
310
354
|
this.#logger.debug(formatCompact({
|
|
311
355
|
op: 'sandbox_recv',
|
|
312
356
|
target,
|
|
@@ -320,8 +364,12 @@ export class SandboxWsEndpoint extends SandboxClient {
|
|
|
320
364
|
const messageId = parsed.messageId ?? randomUUID();
|
|
321
365
|
this.#broadcast(this.#subscribers(scene, true), JSON.stringify({
|
|
322
366
|
...scene, conversation: scene, direction: 'inbound', senderId,
|
|
323
|
-
|
|
367
|
+
displaySenderId: speaker.identity ? speaker.identity.userId : clientSenderId,
|
|
368
|
+
simulated: !speaker.identity,
|
|
369
|
+
...(speaker.unavailable ? { asMeUnavailable: speaker.unavailable } : {}),
|
|
370
|
+
...(speaker.identity || parsed.senderName ? { senderName } : {}),
|
|
324
371
|
...(parsed.senderRole ? { senderRole: parsed.senderRole } : {}),
|
|
372
|
+
...sandboxSenderRoleFacts(this.#options.chatRoles, conversation, senderId),
|
|
325
373
|
messageId, endpoint: this.#options.defaults.id, content: parsed.content, timestamp: parsed.timestamp,
|
|
326
374
|
}));
|
|
327
375
|
// ADR 0056 §1: the simulated group role is a platform standing (master = 群主). It never
|
|
@@ -397,6 +445,8 @@ export class SandboxWsEndpoint extends SandboxClient {
|
|
|
397
445
|
endpoint: target,
|
|
398
446
|
workingDirectory: process.cwd(),
|
|
399
447
|
canExecute,
|
|
448
|
+
// Whether 「以我的聊天身份发言」 can work on this socket (a signed-in Console user).
|
|
449
|
+
consoleUser: consoleUser !== undefined,
|
|
400
450
|
shellIsolation,
|
|
401
451
|
content: [{
|
|
402
452
|
type: 'text',
|
|
@@ -413,6 +463,32 @@ export class SandboxWsEndpoint extends SandboxClient {
|
|
|
413
463
|
whenWsOpen(socket, () => socket.send(readyPayload));
|
|
414
464
|
});
|
|
415
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
|
+
}
|
|
416
492
|
#ensurePlaceholder(name, owner) {
|
|
417
493
|
if (this.connectionRecords.has(name))
|
|
418
494
|
return;
|
package/lib/protocol.d.ts
CHANGED
|
@@ -65,6 +65,11 @@ export interface SandboxParsedMessage {
|
|
|
65
65
|
senderId?: string;
|
|
66
66
|
senderName?: string;
|
|
67
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;
|
|
68
73
|
}
|
|
69
74
|
export type SandboxInboundEnvelope = SandboxParsedMessage;
|
|
70
75
|
export type SandboxWsFrame = {
|
|
@@ -89,6 +94,13 @@ export interface SandboxSelfMention {
|
|
|
89
94
|
export declare function parseSandboxWsFrame(raw: string, self?: SandboxSelfMention): SandboxWsFrame;
|
|
90
95
|
export declare function parseSandboxWsPayload(raw: string, self?: SandboxSelfMention): SandboxParsedMessage;
|
|
91
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;
|
|
92
104
|
/**
|
|
93
105
|
* 入站归一化 → ConversationRef。sandbox 无平台社交图谱:
|
|
94
106
|
* `private`/`group`/`channel` 直映射;`direct`(私聊)归 'private';
|
package/lib/protocol.js
CHANGED
|
@@ -247,8 +247,18 @@ function normalizeSandboxWsPayload(payload, raw, self) {
|
|
|
247
247
|
...(senderId ? { senderId } : {}),
|
|
248
248
|
...(senderName ? { senderName } : {}),
|
|
249
249
|
...(senderRole ? { senderRole } : {}),
|
|
250
|
+
...(payload.asMe === true ? { asMe: true } : {}),
|
|
250
251
|
};
|
|
251
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
|
+
}
|
|
252
262
|
/**
|
|
253
263
|
* 入站归一化 → ConversationRef。sandbox 无平台社交图谱:
|
|
254
264
|
* `private`/`group`/`channel` 直映射;`direct`(私聊)归 'private';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zhin.js/adapter-sandbox",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.35",
|
|
4
4
|
"description": "Sandbox adapter: a local chat workspace for the Remote Console, for development and testing without a real platform.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"zhin.js",
|
|
@@ -39,14 +39,14 @@
|
|
|
39
39
|
},
|
|
40
40
|
"dependencies": {
|
|
41
41
|
"lucide-react": "^0.525.0",
|
|
42
|
-
"@zhin.js/adapter": "1.3.
|
|
43
|
-
"@zhin.js/client": "1.2.
|
|
42
|
+
"@zhin.js/adapter": "1.3.1",
|
|
43
|
+
"@zhin.js/client": "1.2.1",
|
|
44
44
|
"@zhin.js/console-contract": "1.2.0",
|
|
45
|
-
"@zhin.js/core": "1.
|
|
45
|
+
"@zhin.js/core": "1.9.0",
|
|
46
46
|
"@zhin.js/feature-kit": "1.1.18",
|
|
47
|
-
"@zhin.js/host-http": "1.
|
|
47
|
+
"@zhin.js/host-http": "1.4.0",
|
|
48
48
|
"@zhin.js/im-contract": "1.2.0",
|
|
49
|
-
"@zhin.js/logger": "1.
|
|
49
|
+
"@zhin.js/logger": "1.2.0",
|
|
50
50
|
"@zhin.js/page": "1.1.20"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
@@ -56,18 +56,18 @@
|
|
|
56
56
|
"typescript": "^6.0.3",
|
|
57
57
|
"vitest": "^4.1.10",
|
|
58
58
|
"ws": "^8.21.1",
|
|
59
|
-
"@zhin.js/pagemanager": "1.1.
|
|
60
|
-
"@zhin.js/runtime": "1.
|
|
61
|
-
"zhin.js": "1.
|
|
59
|
+
"@zhin.js/pagemanager": "1.1.29",
|
|
60
|
+
"@zhin.js/runtime": "1.4.0",
|
|
61
|
+
"zhin.js": "1.4.0"
|
|
62
62
|
},
|
|
63
63
|
"peerDependencies": {
|
|
64
64
|
"react": "^19.0.0",
|
|
65
|
-
"@zhin.js/adapter": "^1.3.
|
|
65
|
+
"@zhin.js/adapter": "^1.3.1",
|
|
66
66
|
"@zhin.js/console-contract": "^1.2.0",
|
|
67
|
-
"@zhin.js/core": "^1.
|
|
68
|
-
"@zhin.js/host-http": "^1.
|
|
67
|
+
"@zhin.js/core": "^1.9.0",
|
|
68
|
+
"@zhin.js/host-http": "^1.4.0",
|
|
69
69
|
"@zhin.js/page": "^1.1.20",
|
|
70
|
-
"zhin.js": "^1.
|
|
70
|
+
"zhin.js": "^1.4.0"
|
|
71
71
|
},
|
|
72
72
|
"peerDependenciesMeta": {
|
|
73
73
|
"react": {
|
|
@@ -6,6 +6,7 @@ import { cn, CodeBlock, MarkdownContent, resolveMediaSrc, pickMediaRawUrl, } fro
|
|
|
6
6
|
import { buildSandboxWebSocketUrl, captureSandboxRequestContext, createSandboxMessageId, submitSandboxFrame, SANDBOX_SCOPED_PROTOCOL } from './sandboxTransport.js';
|
|
7
7
|
import { createWorkspaceDirectoryController } from './workspaceDirectoryState.js';
|
|
8
8
|
import { isApprovalPrompt, readSandboxCommandHints } from './composerCommands.js';
|
|
9
|
+
import { ensureSandboxChatIdentity, readServerSpeaker, wantsAsMe } from './chatIdentity.js';
|
|
9
10
|
import { isJsxNode, segmentFallbackText, segmentPreviewText } from './segmentFallback.js';
|
|
10
11
|
import { User, Bot, Users, Trash2, Send, Hash, MessageSquare, Wifi, WifiOff, Smile, Image, X, Check, Search, Video, Music, Plus, PanelRight, ExternalLink, RefreshCw, Sparkles, Activity, Wrench, Coins, CircleAlert, Gauge, SlidersHorizontal, FolderOpen, ShieldCheck, Network, Square, RotateCcw, FileDiff, Terminal, FlaskConical, ChevronDown, FileDown, ListChecks, MoreHorizontal, Keyboard, AtSign, } from 'lucide-react';
|
|
11
12
|
import RichTextEditor, {} from './RichTextEditor.js';
|
|
@@ -15,6 +16,12 @@ import ConversationRecoveryPanel from './ConversationRecoveryPanel.js';
|
|
|
15
16
|
import { useSandboxHistory } from './useSandboxHistory.js';
|
|
16
17
|
import { agentSessionsPath, buildAgentRunReport, buildSandboxSessionKey, cancelAgentTask, deriveAgentRunSteps, deriveTaskRuns, deriveWorkbenchArtifacts, fetchAgentTrace, loadCachedAgentTrace, mergeTraceSnapshot, presentTraceEvent, summarizeTrace, saveCachedAgentTrace, } from './agentTrace.js';
|
|
17
18
|
import { createDefaultPlaygroundState, loadPlaygroundState, savePlaygroundState, mergePlaygroundMessage, retirePlaygroundInteractions, } from './playgroundState.js';
|
|
19
|
+
/** ADR 0060 §5.4: the simulated role is a platform standing (群主 / 管理员 / 成员), never a zhin role. */
|
|
20
|
+
function platformStandingLabel(role, locale) {
|
|
21
|
+
if (locale === 'en')
|
|
22
|
+
return role === 'master' ? 'group owner' : role === 'admin' ? 'group admin' : 'member';
|
|
23
|
+
return role === 'master' ? '群主' : role === 'admin' ? '群管理员' : '成员';
|
|
24
|
+
}
|
|
18
25
|
export default function Sandbox(props = {}) {
|
|
19
26
|
const [locale, setLocale] = useState('zh-CN');
|
|
20
27
|
const localeRef = useRef('zh-CN');
|
|
@@ -59,6 +66,13 @@ export default function Sandbox(props = {}) {
|
|
|
59
66
|
const [senderId, setSenderId] = useState('dev-user');
|
|
60
67
|
const [senderName, setSenderName] = useState('Developer');
|
|
61
68
|
const [senderRole, setSenderRole] = useState('master');
|
|
69
|
+
// ADR 0060 §5.4: what the server resolved for the last message sent (speaker, zhin role, Agent trust tier).
|
|
70
|
+
const [serverRole, setServerRole] = useState(null);
|
|
71
|
+
// 「以我的聊天身份发言」 (default) vs a simulated sender; only a signed-in Console user can speak as themselves.
|
|
72
|
+
const [speakerMode, setSpeakerMode] = useState('me');
|
|
73
|
+
const [consoleUser, setConsoleUser] = useState(false);
|
|
74
|
+
const [identitySetup, setIdentitySetup] = useState({ status: 'idle' });
|
|
75
|
+
const asMe = wantsAsMe(speakerMode, consoleUser);
|
|
62
76
|
const [showSenderSettings, setShowSenderSettings] = useState(false);
|
|
63
77
|
/** Runbar overflow: identity, run settings, inspector and clear live here (#1250). */
|
|
64
78
|
const [showMoreActions, setShowMoreActions] = useState(false);
|
|
@@ -227,6 +241,7 @@ export default function Sandbox(props = {}) {
|
|
|
227
241
|
connectionRef.current = { protocol: data.protocol, connectionId: data.connectionId, ownerId: data.id, canExecute: data.canExecute !== false };
|
|
228
242
|
setReadyConnectionId(data.connectionId);
|
|
229
243
|
setCanExecute(data.canExecute !== false);
|
|
244
|
+
setConsoleUser(data.consoleUser === true);
|
|
230
245
|
setTransportNotice(data.canExecute === false ? sandboxText(locale, "当前 Token 只有演示权限,任务运行已禁用。") : null);
|
|
231
246
|
if (data.shellIsolation) {
|
|
232
247
|
setShellIsolation({
|
|
@@ -270,6 +285,9 @@ export default function Sandbox(props = {}) {
|
|
|
270
285
|
const channelType = data.conversation?.type ?? (data.type === 'group' || data.type === 'channel' ? data.type : 'private');
|
|
271
286
|
const sceneId = data.conversation?.id ?? data.id;
|
|
272
287
|
const isInput = data.direction === 'inbound';
|
|
288
|
+
const speaker = isInput ? readServerSpeaker(data) : null;
|
|
289
|
+
if (speaker)
|
|
290
|
+
setServerRole(speaker);
|
|
273
291
|
// Interactive choices are transport inputs, not another chat turn or an approval result.
|
|
274
292
|
if (isInput && content.every((segment) => segment.type === 'action'))
|
|
275
293
|
return;
|
|
@@ -292,7 +310,7 @@ export default function Sandbox(props = {}) {
|
|
|
292
310
|
setMessages((prev) => mergePlaygroundMessage(prev, {
|
|
293
311
|
id: data.messageId ?? createSandboxMessageId(), type: isInput ? 'sent' : 'received', channelType,
|
|
294
312
|
interactionReadOnly: false,
|
|
295
|
-
channelId: sceneId, channelName, senderId: isInput ? data.senderId || connectionRef.current.ownerId || 'owner' : 'endpoint',
|
|
313
|
+
channelId: sceneId, channelName, senderId: isInput ? data.displaySenderId || data.senderId || connectionRef.current.ownerId || 'owner' : 'endpoint',
|
|
296
314
|
senderName: isInput ? (typeof data.senderName === 'string' && data.senderName.trim() ? data.senderName.trim() : sandboxText(locale, "当前用户")) : data.bot || endpointIdRef.current, content, timestamp: data.timestamp,
|
|
297
315
|
...(Number.isSafeInteger(data.revision) && data.revision > 0 ? { revision: data.revision } : {}),
|
|
298
316
|
...(typeof data.streaming === 'boolean' ? { streaming: data.streaming } : {}),
|
|
@@ -307,7 +325,7 @@ export default function Sandbox(props = {}) {
|
|
|
307
325
|
const resolvedSenderName = senderName.trim() || sandboxText(localeRef.current, "测试用户");
|
|
308
326
|
if (!submitSandboxFrame(wsRef.current, {
|
|
309
327
|
type: scene.type, id: scene.id, messageId: createSandboxMessageId(), content: segments,
|
|
310
|
-
senderId: resolvedSenderId, senderName: resolvedSenderName, senderRole,
|
|
328
|
+
senderId: resolvedSenderId, senderName: resolvedSenderName, senderRole, ...(asMe ? { asMe: true } : {}),
|
|
311
329
|
agentRun: scene.runConfig, timestamp: Date.now(),
|
|
312
330
|
})) {
|
|
313
331
|
setTransportNotice(sandboxText(localeRef.current, "Sandbox 连接尚未就绪,审批选择未发送。"));
|
|
@@ -692,7 +710,7 @@ export default function Sandbox(props = {}) {
|
|
|
692
710
|
};
|
|
693
711
|
if (!submitSandboxFrame(wsRef.current, {
|
|
694
712
|
type: scene.type, id: scene.id, messageId: newMessage.id, content: segments,
|
|
695
|
-
senderId: resolvedSenderId, senderName: resolvedSenderName, senderRole,
|
|
713
|
+
senderId: resolvedSenderId, senderName: resolvedSenderName, senderRole, ...(asMe ? { asMe: true } : {}),
|
|
696
714
|
agentRun: scene.runConfig, timestamp: newMessage.timestamp,
|
|
697
715
|
})) {
|
|
698
716
|
setTransportNotice(sandboxText(localeRef.current, "Sandbox 连接尚未就绪,消息未发送。"));
|
|
@@ -860,6 +878,7 @@ export default function Sandbox(props = {}) {
|
|
|
860
878
|
.sandbox-role-badge.is-master { background: rgba(245,158,11,0.18); color: #d97706; }
|
|
861
879
|
.sandbox-role-badge.is-admin { background: rgba(59,130,246,0.18); color: #2563eb; }
|
|
862
880
|
.sandbox-role-badge.is-member { background: rgba(16,185,129,0.16); color: #059669; }
|
|
881
|
+
.sandbox-role-badge.is-zhin { text-transform: none; background: rgba(139,92,246,0.16); color: #7c3aed; }
|
|
863
882
|
.sandbox-role-switcher { display: inline-flex; gap: 4px; }
|
|
864
883
|
.sandbox-role-option { padding: 4px 10px; border-radius: 6px; border: 1px solid rgba(148,163,184,0.3); font-size: 12px; cursor: pointer; background: transparent; color: inherit; text-transform: capitalize; }
|
|
865
884
|
.sandbox-role-option.active { font-weight: 600; border-color: currentColor; background: rgba(59,130,246,0.12); }
|
|
@@ -893,7 +912,18 @@ export default function Sandbox(props = {}) {
|
|
|
893
912
|
}) }), _jsx("div", { className: "agent-playground-new-session", children: showNewSession ? (_jsxs("div", { className: "agent-playground-new-form", children: [_jsx("input", { value: newSessionName, onChange: (event) => setNewSessionName(event.target.value), onKeyDown: (event) => { if (event.key === 'Enter')
|
|
894
913
|
addSession(); }, placeholder: sandboxText(locale, "会话名称"), autoFocus: true }), _jsx("div", { className: "agent-playground-scope-picker", role: "group", "aria-label": sandboxText(locale, "消息作用域"), children: ['private', 'group', 'channel'].map((scope) => (_jsx("button", { type: "button", "aria-pressed": newSessionScope === scope, className: cn(newSessionScope === scope && 'active'), onClick: () => setNewSessionScope(scope), children: scope === 'private' ? sandboxText(locale, "单用户") : scope === 'group' ? sandboxText(locale, "群组") : sandboxText(locale, "频道") }, scope))) }), _jsxs("div", { className: "agent-playground-new-actions", children: [_jsx("button", { type: "button", onClick: () => setShowNewSession(false), children: sandboxText(locale, "取消") }), _jsx("button", { type: "button", className: "primary", onClick: addSession, children: sandboxText(locale, "创建") })] })] })) : (_jsxs("button", { type: "button", disabled: directoryStatus.mode === 'loading', className: "agent-playground-add", onClick: () => setShowNewSession(true), children: [_jsx(Plus, { size: 15 }), sandboxText(locale, "新建会话")] })) }), _jsxs("div", { className: "agent-playground-endpoint", children: [_jsx("span", { children: directoryStatus.mode === 'loading' ? sandboxText(locale, "正在读取会话目录") : directoryStatus.mode === 'server' && !directoryStatus.error ? sandboxText(locale, "Host 会话目录") : persistenceStatus === 'saved' ? sandboxText(locale, "会话已持久化") : sandboxText(locale, "会话保存失败") }), _jsx("strong", { children: endpointId })] })] }), showChannelList && _jsx("div", { className: "channel-overlay", onClick: () => setShowChannelList(false) }), _jsxs("main", { className: "chat-area agent-playground-main", children: [_jsxs("header", { className: "agent-playground-runbar", children: [_jsxs("div", { className: "agent-playground-run-identity", children: [_jsx("span", { className: "agent-playground-run-icon", children: getChannelIcon(activeChannel.type) }), _jsx("div", { title: sessionKey, children: _jsxs("div", { className: "agent-playground-run-title", children: [_jsx("h1", { title: activeChannel.name, children: activeChannel.name }), _jsx("span", { children: scopeLabel })] }) })] }), _jsxs("div", { className: "agent-playground-run-actions", children: [_jsxs("span", { className: cn("agent-playground-run-state", currentTask?.status === 'running' && "is-running", currentTask?.status === 'failed' && 'has-problem'), children: [currentTask?.status === 'running' ? _jsx(Activity, { size: 14 }) : _jsx(Gauge, { size: 14 }), currentTask ? taskStatusLabel(currentTask.status, locale) : sandboxText(locale, "{0} 条消息", [channelMessages.length])] }), currentTask?.status === 'running' ? (_jsxs("button", { type: "button", className: "agent-playground-stop", onClick: () => void stopActiveTask(), disabled: stoppingTask, "aria-label": sandboxText(locale, "停止当前任务"), children: [_jsx(Square, { size: 13 }), stoppingTask ? sandboxText(locale, "停止中") : sandboxText(locale, "停止")] })) : lastUserMessage ? (_jsxs("button", { type: "button", onClick: retryLastTask, "aria-label": sandboxText(locale, "重新运行上一个任务"), children: [_jsx(RotateCcw, { size: 14 }), sandboxText(locale, "重试")] })) : null, props.renderConversationDetails
|
|
895
914
|
? _jsxs("button", { type: "button", disabled: !canExecute, "aria-expanded": showConversationDetails, "aria-controls": "sandbox-conversation-details", onClick: () => setShowConversationDetails((visible) => !visible), children: [_jsx(ListChecks, { size: 14 }), sandboxText(locale, "对话与轨迹")] })
|
|
896
|
-
: _jsxs("a", { href: agentSessionsPath(sessionKey), children: [_jsx(ExternalLink, { size: 14 }), sandboxText(locale, "对话与轨迹")] }), _jsxs("div", { className: "sandbox-more", children: [_jsx("button", { type: "button", className: cn("sandbox-more-trigger", (showMoreActions || showSenderSettings || showRunSettings) && 'active'), "aria-haspopup": "menu", "aria-expanded": showMoreActions, onClick: () => setShowMoreActions((visible) => !visible), "aria-label": sandboxText(locale, "更多操作"), title: sandboxText(locale, "更多操作"), children: _jsx(MoreHorizontal, { size: 16 }) }), showMoreActions && (_jsxs(_Fragment, { children: [_jsx("div", { className: "sandbox-more-backdrop", onClick: () => setShowMoreActions(false) }), _jsxs("div", { className: "sandbox-more-menu", role: "menu", "aria-label": sandboxText(locale, "更多操作"), children: [_jsxs("button", { type: "button", role: "menuitemcheckbox", "aria-checked": showSenderSettings, onClick: () => { setShowSenderSettings((visible) => !visible); setShowMoreActions(false); }, children: [_jsx(User, { size: 14 }), _jsx("span", { children: sandboxText(locale, "模拟发送者") }), _jsxs("em", { className: cn("sandbox-role-badge", `is-${senderRole}`),
|
|
915
|
+
: _jsxs("a", { href: agentSessionsPath(sessionKey), children: [_jsx(ExternalLink, { size: 14 }), sandboxText(locale, "对话与轨迹")] }), _jsxs("div", { className: "sandbox-more", children: [_jsx("button", { type: "button", className: cn("sandbox-more-trigger", (showMoreActions || showSenderSettings || showRunSettings) && 'active'), "aria-haspopup": "menu", "aria-expanded": showMoreActions, onClick: () => setShowMoreActions((visible) => !visible), "aria-label": sandboxText(locale, "更多操作"), title: sandboxText(locale, "更多操作"), children: _jsx(MoreHorizontal, { size: 16 }) }), showMoreActions && (_jsxs(_Fragment, { children: [_jsx("div", { className: "sandbox-more-backdrop", onClick: () => setShowMoreActions(false) }), _jsxs("div", { className: "sandbox-more-menu", role: "menu", "aria-label": sandboxText(locale, "更多操作"), children: [_jsxs("button", { type: "button", role: "menuitemcheckbox", "aria-checked": showSenderSettings, onClick: () => { setShowSenderSettings((visible) => !visible); setShowMoreActions(false); }, children: [_jsx(User, { size: 14 }), _jsx("span", { children: sandboxText(locale, "模拟发送者") }), _jsxs("em", { className: cn("sandbox-role-badge", `is-${senderRole}`), title: locale === 'en' ? 'Simulated platform standing (not a zhin role)' : '模拟的平台身份(不是 zhin 角色)', children: [asMe ? sandboxText(locale, "我的聊天身份") : (senderName.trim() || senderId.trim() || 'dev-user'), " \u00B7 ", platformStandingLabel(senderRole, locale)] }), serverRole && (serverRole.simulated
|
|
916
|
+
? _jsx("em", { className: "sandbox-role-badge is-simulated", title: sandboxText(locale, "客户端自填的发送者不解析 zhin 角色"), children: sandboxText(locale, "模拟身份,无角色") })
|
|
917
|
+
: _jsx("em", { className: "sandbox-role-badge is-zhin", title: locale === 'en' ? 'Resolved by the server: zhin role · Agent trust tier' : '服务端解析:zhin 角色 · Agent 信任档位', children: `zhin: ${serverRole.chatRole ?? (locale === 'en' ? 'none' : '无')} · ${serverRole.trustLevel}` }))] }), _jsxs("button", { type: "button", role: "menuitemcheckbox", "aria-checked": showRunSettings, onClick: () => { setShowRunSettings((visible) => !visible); setShowMoreActions(false); }, children: [_jsx(SlidersHorizontal, { size: 14 }), _jsx("span", { children: sandboxText(locale, "配置运行环境") })] }), _jsxs("button", { type: "button", role: "menuitemcheckbox", "aria-checked": showInspector, "aria-controls": "sandbox-run-inspector", onClick: () => { setShowInspector(!showInspector); setShowMoreActions(false); }, children: [_jsx(PanelRight, { size: 14 }), _jsx("span", { children: sandboxText(locale, "切换运行检查器") })] }), _jsxs("button", { type: "button", role: "menuitem", className: "is-danger", onClick: () => { setConfirmClear(true); setShowMoreActions(false); }, children: [_jsx(Trash2, { size: 14 }), _jsx("span", { children: sandboxText(locale, "清空当前会话") })] })] })] }))] })] })] }), showSenderSettings && (_jsxs("section", { className: "agent-playground-run-settings sandbox-sender-settings", "aria-label": locale === 'en' ? 'Simulated sender' : '模拟发送者配置', children: [_jsxs("div", { className: "sandbox-speaker-mode", children: [_jsxs("label", { className: "sandbox-speaker-toggle", children: [_jsx("input", { type: "checkbox", checked: speakerMode === 'me', disabled: !consoleUser, onChange: (event) => setSpeakerMode(event.target.checked ? 'me' : 'simulated') }), _jsx("span", { children: sandboxText(locale, "以我的聊天身份发言") })] }), _jsx("p", { children: !consoleUser
|
|
918
|
+
? sandboxText(locale, "当前连接没有 Console 用户(未登录或 --standalone),所有消息都按模拟身份处理,不解析 zhin 角色。")
|
|
919
|
+
: asMe
|
|
920
|
+
? sandboxText(locale, "以链接到你 Console 账号的聊天身份发言,角色按你的聊天角色解析。")
|
|
921
|
+
: sandboxText(locale, "模拟身份,无角色:自填的发送者 ID 只用于模拟别人,不解析 zhin 角色。") }), asMe && serverRole?.asMeUnavailable === 'needs-global-iam' && (_jsx("div", { className: "sandbox-speaker-setup", role: "status", children: _jsx("span", { children: sandboxText(locale, "链接到你的聊天身份持有全局角色,以它发言需要全局 iam.manage 权限;上一条消息按模拟身份(无角色)发送。") }) })), asMe && serverRole?.asMeUnavailable === 'no-identity' && (_jsxs("div", { className: "sandbox-speaker-setup", role: "status", children: [_jsx("span", { children: sandboxText(locale, "你在 Sandbox 上还没有聊天身份,上一条消息按模拟身份发送。") }), _jsx("button", { type: "button", disabled: identitySetup.status === 'busy', onClick: () => {
|
|
922
|
+
setIdentitySetup({ status: 'busy' });
|
|
923
|
+
void ensureSandboxChatIdentity(socketRequestContextRef.current ?? undefined).then((result) => {
|
|
924
|
+
setIdentitySetup(result.status === 'ok' ? { status: 'done' } : result);
|
|
925
|
+
});
|
|
926
|
+
}, children: sandboxText(locale, "在 Sandbox 上创建我的聊天身份") }), identitySetup.status === 'done' && _jsx("em", { children: sandboxText(locale, "已创建,下一条消息生效。") }), identitySetup.status === 'unsupported' && _jsx("em", { children: sandboxText(locale, "当前 Host 不支持,请升级。") }), identitySetup.status === 'failed' && _jsx("em", { children: identitySetup.message })] }))] }), _jsxs("label", { children: [_jsxs("span", { children: [_jsx(User, { size: 14 }), locale === 'en' ? 'Sender ID (simulated, no role)' : '发送者 ID(模拟身份,无角色)'] }), _jsx("input", { value: senderId, disabled: asMe, onChange: (event) => setSenderId(event.target.value), placeholder: "dev-user", spellCheck: false })] }), _jsxs("label", { children: [_jsx("span", { children: locale === 'en' ? 'Sender Name' : '发送者昵称' }), _jsx("input", { value: senderName, disabled: asMe, onChange: (event) => setSenderName(event.target.value), placeholder: "Developer", spellCheck: false })] }), _jsxs("label", { children: [_jsxs("span", { children: [_jsx(ShieldCheck, { size: 14 }), locale === 'en' ? 'Platform standing (not a zhin role)' : '平台身份(不是 zhin 角色)'] }), _jsx("div", { className: "sandbox-role-switcher", role: "group", "aria-label": locale === 'en' ? 'Platform standing' : '平台身份', children: ['member', 'admin', 'master'].map((role) => (_jsx("button", { type: "button", "aria-pressed": senderRole === role, className: cn("sandbox-role-option", `is-${role}`, senderRole === role && "active"), onClick: () => setSenderRole(role), children: platformStandingLabel(role, locale) }, role))) })] }), _jsxs("div", { className: "sandbox-sender-presets", children: [_jsx("button", { type: "button", onClick: () => { setSenderId('dev-user'); setSenderName('Developer'); setSenderRole('master'); }, children: locale === 'en' ? 'Group owner (platform standing, dev-user)' : '群主(平台身份,dev-user)' }), _jsx("button", { type: "button", onClick: () => { setSenderId('admin-user'); setSenderName('Admin'); setSenderRole('admin'); }, children: "Admin (admin-user)" }), _jsx("button", { type: "button", onClick: () => { setSenderId('member-user'); setSenderName('Member'); setSenderRole('member'); }, children: "Member (member-user)" })] })] })), cancellationFeedback && _jsxs("div", { className: "agent-playground-confirm", role: cancellationFeedback.kind === 'error' ? 'alert' : 'status', children: [_jsx("div", { children: _jsx("span", { children: cancellationFeedback.message }) }), _jsx("button", { type: "button", onClick: () => setCancellationFeedback(null), children: sandboxText(locale, "知道了") })] }), confirmClear && (_jsxs("div", { className: "agent-playground-confirm", role: "alert", children: [_jsxs("div", { children: [_jsx("strong", { children: sandboxText(locale, "清空当前测试记录?") }), _jsxs("span", { children: [sandboxText(locale, "只移除“"), activeChannel.name, sandboxText(locale, "”在浏览器中的消息,不影响 Agent 会话存储。")] })] }), _jsx("button", { type: "button", onClick: () => setConfirmClear(false), children: sandboxText(locale, "取消") }), _jsx("button", { type: "button", className: "danger", onClick: clearMessages, children: sandboxText(locale, "确认清空") })] })), ['emoji', 'parse'].filter((kind) => inlineNotices[kind]).map((kind) => (_jsxs("div", { className: "sandbox-notice", role: "status", children: [_jsx(CircleAlert, { size: 14 }), _jsx("span", { children: kind === 'emoji' ? sandboxText(locale, "表情列表加载失败,表情选择器暂不可用。") : sandboxText(locale, "收到一条无法解析的消息,已忽略。") }), _jsx("button", { type: "button", onClick: () => setInlineNotices((n) => ({ ...n, [kind]: false })), children: sandboxText(locale, "知道了") })] }, kind))), transportNotice && (_jsxs("div", { className: "agent-playground-confirm", role: "status", children: [_jsxs("div", { children: [_jsx("strong", { children: sandboxText(locale, "运行暂不可用") }), _jsx("span", { children: transportNotice })] }), _jsx("button", { type: "button", onClick: () => setTransportNotice(null), children: sandboxText(locale, "知道了") })] })), directoryStatus.error && _jsxs("div", { className: "agent-playground-confirm", role: "alert", children: [_jsxs("div", { children: [_jsx("strong", { children: sandboxText(locale, "会话目录") }), _jsx("span", { children: directoryStatus.error })] }), _jsx("button", { type: "button", onClick: () => void directoryControllerRef.current?.refresh(), children: sandboxText(locale, "重新读取") })] }), showRunSettings && (_jsxs("section", { className: "agent-playground-run-settings", "aria-label": sandboxText(locale, "运行配置"), children: [_jsxs("label", { className: "agent-playground-directory-field", children: [_jsxs("span", { children: [_jsx(FolderOpen, { size: 14 }), sandboxText(locale, "工作目录")] }), _jsx("input", { disabled: directoryStatus.mode === 'loading', value: activeChannel.runConfig.workingDirectory, onChange: (event) => updateRunConfig({ workingDirectory: event.target.value }), placeholder: sandboxText(locale, "使用 Host 项目目录"), spellCheck: false })] }), _jsxs("label", { children: [_jsxs("span", { children: [_jsx(ShieldCheck, { size: 14 }), sandboxText(locale, "安全策略")] }), _jsxs("select", { disabled: directoryStatus.mode === 'loading', value: activeChannel.runConfig.safetyMode, onChange: (event) => {
|
|
897
927
|
const safetyMode = event.target.value;
|
|
898
928
|
updateRunConfig({ safetyMode, ...(safetyMode === 'danger-full-access' ? { networkAccess: true } : {}) });
|
|
899
929
|
}, children: [_jsx("option", { value: "read-only", children: sandboxText(locale, "只读") }), _jsx("option", { value: "workspace-write", children: sandboxText(locale, "工作区写入") }), _jsx("option", { value: "danger-full-access", children: sandboxText(locale, "完全访问") })] })] }), _jsxs("label", { children: [_jsx("span", { children: sandboxText(locale, "审批策略") }), _jsxs("select", { value: activeChannel.runConfig.safetyMode === 'read-only' ? 'auto' : activeChannel.runConfig.safetyMode === 'danger-full-access' ? 'bypass' : activeChannel.runConfig.approvalMode, disabled: activeChannel.runConfig.safetyMode !== 'workspace-write', onChange: (event) => updateRunConfig({ approvalMode: event.target.value }), children: [_jsx("option", { value: "ask", children: sandboxText(locale, "按需确认") }), _jsx("option", { value: "auto", children: sandboxText(locale, "审核 Agent 自动判断") }), _jsx("option", { value: "bypass", children: sandboxText(locale, "绕过审批") })] })] }), _jsxs("label", { className: "agent-playground-network-toggle", children: [_jsxs("span", { children: [_jsx(Network, { size: 14 }), sandboxText(locale, "网络访问")] }), _jsx("input", { type: "checkbox", checked: activeChannel.runConfig.safetyMode === 'danger-full-access' || activeChannel.runConfig.networkAccess, disabled: activeChannel.runConfig.safetyMode === 'danger-full-access', onChange: (event) => updateRunConfig({ networkAccess: event.target.checked }) }), _jsx("i", { "aria-hidden": "true" })] }), activeChannel.runConfig.safetyMode === 'danger-full-access' && (_jsxs("p", { children: [_jsx(CircleAlert, { size: 14 }), sandboxText(locale, "完全访问允许 Agent 操作工作目录之外的文件并访问网络,请仅用于可信任务。")] })), activeChannel.runConfig.safetyMode !== 'danger-full-access' && shellIsolation?.available === false && (_jsxs("p", { children: [_jsx(CircleAlert, { size: 14 }), sandboxText(locale, "安全 Shell 需要可用的 Docker daemon;当前仅文件工具可运行。"), shellIsolation.message] }))] })), canExecute && recoveryConnectionId && (_jsx(ConversationRecoveryPanel, { connectionId: recoveryConnectionId, sessionKey: sessionKey, locale: locale, hidden: showConversationDetails, pendingRefreshEpoch: pendingRefreshEpoch, onRetiredInteractions: (retired) => {
|