@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.
@@ -0,0 +1,56 @@
1
+ import type { MessageSegment } from '@zhin.js/client';
2
+ import { getSandboxApiBase, getSandboxAuthHeaders, type SandboxRequestContext } from './sandboxTransport.js';
3
+ import type { SandboxScope } from './agentTrace.js';
4
+ import type { PlaygroundMessage } from './playgroundState.js';
5
+
6
+ /**
7
+ * Host marker of a human approval prompt (#1250): `UserInteractionRequest.purpose = 'approval'`
8
+ * is rendered by Core as keyboard `data.purpose`. Any segment carrying it marks the message, so a
9
+ * text-only approval card that sets the same field on its body is recognised too.
10
+ */
11
+ export const APPROVAL_PURPOSE = 'approval';
12
+
13
+ /** Only real approval prompts get the "needs your confirmation" label, not game cards or menu pages. */
14
+ export function isApprovalPrompt(message: Pick<PlaygroundMessage, 'type' | 'interactionReadOnly' | 'content'>): boolean {
15
+ return message.type === 'received' && message.interactionReadOnly !== true
16
+ && message.content.some((segment: MessageSegment) => {
17
+ const data = segment.data as Record<string, unknown> | undefined;
18
+ return data !== null && typeof data === 'object' && data.purpose === APPROVAL_PURPOSE;
19
+ });
20
+ }
21
+
22
+ /** What `GET /api/conversations/workspaces/commands` returns for the live Sandbox binding. */
23
+ export interface SandboxCommandHints {
24
+ readonly prefix: string;
25
+ readonly menu?: string;
26
+ readonly quick: readonly string[];
27
+ }
28
+
29
+ /** Quick commands of the Host's command index; null when the Host cannot tell (older Host, no binding). */
30
+ export async function readSandboxCommandHints(
31
+ connectionId: string,
32
+ scene: Readonly<{ type: SandboxScope; id: string }>,
33
+ locale: string,
34
+ signal?: AbortSignal,
35
+ context?: SandboxRequestContext,
36
+ ): Promise<SandboxCommandHints | null> {
37
+ const url = new URL('/api/conversations/workspaces/commands', `${(context ? context.apiBase : getSandboxApiBase()) || window.location.origin}/`);
38
+ url.searchParams.set('connectionId', connectionId);
39
+ url.searchParams.set('type', scene.type);
40
+ url.searchParams.set('id', scene.id);
41
+ url.searchParams.set('locale', locale);
42
+ try {
43
+ const response = await fetch(url, { headers: context?.headers ?? getSandboxAuthHeaders(), signal });
44
+ if (!response.ok) return null;
45
+ const body = await response.json() as { success?: boolean; data?: Partial<SandboxCommandHints> };
46
+ const data = body?.data;
47
+ if (!body?.success || !data || typeof data.prefix !== 'string' || !Array.isArray(data.quick)) return null;
48
+ return Object.freeze({
49
+ prefix: data.prefix,
50
+ ...(typeof data.menu === 'string' ? { menu: data.menu } : {}),
51
+ quick: Object.freeze(data.quick.filter((item): item is string => typeof item === 'string' && item.trim().length > 0).slice(0, 6)),
52
+ });
53
+ } catch {
54
+ return null;
55
+ }
56
+ }
@@ -2,6 +2,18 @@
2
2
  /** Authored interface copy only; unknown/user text is returned unchanged. */
3
3
  export const sandboxEnglish = {
4
4
  "刷新会话目录": "Refresh conversations",
5
+ "我的聊天身份": "My chat identity",
6
+ "客户端自填的发送者不解析 zhin 角色": "A sender id typed by the client never resolves a zhin role",
7
+ "模拟身份,无角色": "Simulated, no role",
8
+ "以我的聊天身份发言": "Speak as my chat identity",
9
+ "当前连接没有 Console 用户(未登录或 --standalone),所有消息都按模拟身份处理,不解析 zhin 角色。": "This connection has no Console user (not signed in, or --standalone): every message is simulated and resolves no zhin role.",
10
+ "以链接到你 Console 账号的聊天身份发言,角色按你的聊天角色解析。": "Messages use the chat identity linked to your Console account; roles resolve from your chat roles.",
11
+ "模拟身份,无角色:自填的发送者 ID 只用于模拟别人,不解析 zhin 角色。": "Simulated, no role: a typed sender id only simulates someone else and resolves no zhin role.",
12
+ "你在 Sandbox 上还没有聊天身份,上一条消息按模拟身份发送。": "You have no chat identity on the Sandbox yet; the last message was sent as a simulated sender.",
13
+ "链接到你的聊天身份持有全局角色,以它发言需要全局 iam.manage 权限;上一条消息按模拟身份(无角色)发送。": "The chat identity linked to you holds a global role; speaking as it needs global iam.manage, so the last message was sent as a simulated sender without roles.",
14
+ "在 Sandbox 上创建我的聊天身份": "Create my chat identity on the Sandbox",
15
+ "已创建,下一条消息生效。": "Created; it applies from the next message.",
16
+ "当前 Host 不支持,请升级。": "This Host does not support it; please upgrade.",
5
17
  "正在读取会话目录": "Loading conversations",
6
18
  "Host 会话目录": "Host conversations",
7
19
  "会话目录": "Conversations",
@@ -123,6 +135,7 @@ export const sandboxEnglish = {
123
135
  "编写": "Write",
124
136
  "预览": "Preview",
125
137
  "清空输入": "Clear input",
138
+ "正在加载会话记录…": "Loading conversation history…",
126
139
  "搜索表情...": "Search emoji…",
127
140
  "未找到匹配的表情": "No matching emoji",
128
141
  "支持 http(s) 图片链接或 data URL": "Supports HTTP(S) image links or data URLs",
@@ -136,7 +149,15 @@ export const sandboxEnglish = {
136
149
  "输入 Markdown 后可在这里检查最终效果": "Enter Markdown to preview the final result here",
137
150
  "未找到匹配的用户": "No matching users",
138
151
  "发送": "Send",
139
- "快捷操作:": "Shortcuts:",
152
+ "快捷操作与语法": "Shortcuts and syntax",
153
+ "媒体": "Media",
154
+ "命令以 {0} 开头": "Commands start with {0}",
155
+ "命令无需前缀": "Commands need no prefix",
156
+ "更多操作": "More actions",
157
+ "@ 机器人": "@ the bot",
158
+ "@ 机器人(插入 [@{0}])": "@ the bot (inserts [@{0}])",
159
+ "@机器人(群聊里唤起机器人,也可点 @ 按钮插入)": "@ the bot (wakes it in group chats; or use the @ button)",
160
+ "模拟发送者": "Simulated sender",
140
161
  "换行": "New line",
141
162
  "代码块": "Code block",
142
163
  "**文本**": "**text**",
@@ -3,6 +3,18 @@ export type SandboxLocale = 'zh-CN' | 'en';
3
3
  /** Authored interface copy only; unknown/user text is returned unchanged. */
4
4
  export const sandboxEnglish: Readonly<Record<string, string>> = {
5
5
  "刷新会话目录": "Refresh conversations",
6
+ "我的聊天身份": "My chat identity",
7
+ "客户端自填的发送者不解析 zhin 角色": "A sender id typed by the client never resolves a zhin role",
8
+ "模拟身份,无角色": "Simulated, no role",
9
+ "以我的聊天身份发言": "Speak as my chat identity",
10
+ "当前连接没有 Console 用户(未登录或 --standalone),所有消息都按模拟身份处理,不解析 zhin 角色。": "This connection has no Console user (not signed in, or --standalone): every message is simulated and resolves no zhin role.",
11
+ "以链接到你 Console 账号的聊天身份发言,角色按你的聊天角色解析。": "Messages use the chat identity linked to your Console account; roles resolve from your chat roles.",
12
+ "模拟身份,无角色:自填的发送者 ID 只用于模拟别人,不解析 zhin 角色。": "Simulated, no role: a typed sender id only simulates someone else and resolves no zhin role.",
13
+ "你在 Sandbox 上还没有聊天身份,上一条消息按模拟身份发送。": "You have no chat identity on the Sandbox yet; the last message was sent as a simulated sender.",
14
+ "链接到你的聊天身份持有全局角色,以它发言需要全局 iam.manage 权限;上一条消息按模拟身份(无角色)发送。": "The chat identity linked to you holds a global role; speaking as it needs global iam.manage, so the last message was sent as a simulated sender without roles.",
15
+ "在 Sandbox 上创建我的聊天身份": "Create my chat identity on the Sandbox",
16
+ "已创建,下一条消息生效。": "Created; it applies from the next message.",
17
+ "当前 Host 不支持,请升级。": "This Host does not support it; please upgrade.",
6
18
  "正在读取会话目录": "Loading conversations",
7
19
  "Host 会话目录": "Host conversations",
8
20
  "会话目录": "Conversations",
@@ -124,6 +136,7 @@ export const sandboxEnglish: Readonly<Record<string, string>> = {
124
136
  "编写": "Write",
125
137
  "预览": "Preview",
126
138
  "清空输入": "Clear input",
139
+ "正在加载会话记录…": "Loading conversation history…",
127
140
  "搜索表情...": "Search emoji…",
128
141
  "未找到匹配的表情": "No matching emoji",
129
142
  "支持 http(s) 图片链接或 data URL": "Supports HTTP(S) image links or data URLs",
@@ -137,7 +150,15 @@ export const sandboxEnglish: Readonly<Record<string, string>> = {
137
150
  "输入 Markdown 后可在这里检查最终效果": "Enter Markdown to preview the final result here",
138
151
  "未找到匹配的用户": "No matching users",
139
152
  "发送": "Send",
140
- "快捷操作:": "Shortcuts:",
153
+ "快捷操作与语法": "Shortcuts and syntax",
154
+ "媒体": "Media",
155
+ "命令以 {0} 开头": "Commands start with {0}",
156
+ "命令无需前缀": "Commands need no prefix",
157
+ "更多操作": "More actions",
158
+ "@ 机器人": "@ the bot",
159
+ "@ 机器人(插入 [@{0}])": "@ the bot (inserts [@{0}])",
160
+ "@机器人(群聊里唤起机器人,也可点 @ 按钮插入)": "@ the bot (wakes it in group chats; or use the @ button)",
161
+ "模拟发送者": "Simulated sender",
141
162
  "换行": "New line",
142
163
  "代码块": "Code block",
143
164
  "**文本**": "**text**",
@@ -0,0 +1,83 @@
1
+ // Generated by build-plugin-runtime-entries.mjs. Do not edit.
2
+ /**
3
+ * Page-side fallback for segments the Sandbox page has no dedicated renderer for (#1250).
4
+ * Core already flattens outbound history; this is the last guard so a reply never shows a raw
5
+ * `{"$jsx":…}` object or a bare `[markdown]`: Markdown keeps its source, buttons (keyboard rows and
6
+ * JSX `<button>`) become `[label]`, unrendered JSX is read through its children.
7
+ */
8
+ const MAX_DEPTH = 32;
9
+ export function isJsxNode(value) {
10
+ if (!value || typeof value !== 'object' || Array.isArray(value))
11
+ return false;
12
+ const node = value;
13
+ return node.$jsx === 'zhin.jsx/1' && !!node.props && typeof node.props === 'object' && !Array.isArray(node.props);
14
+ }
15
+ function keyboardLabels(rows) {
16
+ if (!Array.isArray(rows))
17
+ return '';
18
+ return rows.flatMap(row => Array.isArray(row) ? row : [])
19
+ .map(button => button && typeof button === 'object' ? button.label : undefined)
20
+ .filter((label) => typeof label === 'string' && label.length > 0)
21
+ .map(label => `[${label}]`).join(' ');
22
+ }
23
+ function flatten(node, depth) {
24
+ if (typeof node === 'string')
25
+ return node;
26
+ if (node == null || typeof node === 'boolean')
27
+ return '';
28
+ if (typeof node === 'number' || typeof node === 'bigint')
29
+ return String(node);
30
+ if (depth > MAX_DEPTH || typeof node !== 'object')
31
+ return '';
32
+ if (Array.isArray(node))
33
+ return node.map(item => flatten(item, depth + 1)).join('');
34
+ if (isJsxNode(node)) {
35
+ const props = node.props;
36
+ if (node.type === 'button') {
37
+ const label = typeof props.label === 'string' ? props.label : flatten(props.children, depth + 1);
38
+ return label ? `[${label}]` : '';
39
+ }
40
+ if (typeof props.text === 'string')
41
+ return props.text;
42
+ if (node.type === 'keyboard' && Array.isArray(props.rows))
43
+ return keyboardLabels(props.rows);
44
+ return flatten(props.children ?? props.content, depth + 1);
45
+ }
46
+ const record = node;
47
+ if (typeof record.type === 'string')
48
+ return segmentFallbackText(record, depth + 1) ?? `[${record.type}]`;
49
+ return typeof record.text === 'string' ? record.text : '';
50
+ }
51
+ /**
52
+ * Display text (Markdown) for a segment, or undefined when nothing better than `[type]` exists.
53
+ * Accepts canonical segments (`{ type, data }`) and unrendered JSX nodes.
54
+ */
55
+ export function segmentFallbackText(segment, depth = 0) {
56
+ if (!segment || typeof segment !== 'object' || depth > MAX_DEPTH)
57
+ return undefined;
58
+ if (isJsxNode(segment)) {
59
+ const text = flatten(segment, depth);
60
+ return text || undefined;
61
+ }
62
+ const record = segment;
63
+ const data = record.data && typeof record.data === 'object' && !Array.isArray(record.data)
64
+ ? record.data : undefined;
65
+ if (!data)
66
+ return undefined;
67
+ if (record.type === 'keyboard')
68
+ return keyboardLabels(data.rows) || undefined;
69
+ for (const field of ['text', 'content', 'markdown', 'children']) {
70
+ const value = data[field];
71
+ if (value === undefined || value === null)
72
+ continue;
73
+ const text = flatten(value, depth + 1);
74
+ if (text)
75
+ return text;
76
+ }
77
+ return undefined;
78
+ }
79
+ /** Plain text of a segment's body for previews; `[type]` only when nothing readable exists. */
80
+ export function segmentPreviewText(segment) {
81
+ const type = segment && typeof segment === 'object' ? segment.type : undefined;
82
+ return segmentFallbackText(segment) ?? (typeof type === 'string' ? `[${type}]` : '');
83
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Page-side fallback for segments the Sandbox page has no dedicated renderer for (#1250).
3
+ * Core already flattens outbound history; this is the last guard so a reply never shows a raw
4
+ * `{"$jsx":…}` object or a bare `[markdown]`: Markdown keeps its source, buttons (keyboard rows and
5
+ * JSX `<button>`) become `[label]`, unrendered JSX is read through its children.
6
+ */
7
+ const MAX_DEPTH = 32;
8
+
9
+ interface JsxLike {
10
+ readonly $jsx: 'zhin.jsx/1';
11
+ readonly type: unknown;
12
+ readonly props: Readonly<Record<string, unknown>>;
13
+ }
14
+
15
+ export function isJsxNode(value: unknown): value is JsxLike {
16
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
17
+ const node = value as Partial<JsxLike>;
18
+ return node.$jsx === 'zhin.jsx/1' && !!node.props && typeof node.props === 'object' && !Array.isArray(node.props);
19
+ }
20
+
21
+ function keyboardLabels(rows: unknown): string {
22
+ if (!Array.isArray(rows)) return '';
23
+ return rows.flatMap(row => Array.isArray(row) ? row : [])
24
+ .map(button => button && typeof button === 'object' ? (button as { label?: unknown }).label : undefined)
25
+ .filter((label): label is string => typeof label === 'string' && label.length > 0)
26
+ .map(label => `[${label}]`).join(' ');
27
+ }
28
+
29
+ function flatten(node: unknown, depth: number): string {
30
+ if (typeof node === 'string') return node;
31
+ if (node == null || typeof node === 'boolean') return '';
32
+ if (typeof node === 'number' || typeof node === 'bigint') return String(node);
33
+ if (depth > MAX_DEPTH || typeof node !== 'object') return '';
34
+ if (Array.isArray(node)) return node.map(item => flatten(item, depth + 1)).join('');
35
+ if (isJsxNode(node)) {
36
+ const props = node.props;
37
+ if (node.type === 'button') {
38
+ const label = typeof props.label === 'string' ? props.label : flatten(props.children, depth + 1);
39
+ return label ? `[${label}]` : '';
40
+ }
41
+ if (typeof props.text === 'string') return props.text;
42
+ if (node.type === 'keyboard' && Array.isArray(props.rows)) return keyboardLabels(props.rows);
43
+ return flatten(props.children ?? props.content, depth + 1);
44
+ }
45
+ const record = node as Record<string, unknown>;
46
+ if (typeof record.type === 'string') return segmentFallbackText(record, depth + 1) ?? `[${record.type}]`;
47
+ return typeof record.text === 'string' ? record.text : '';
48
+ }
49
+
50
+ /**
51
+ * Display text (Markdown) for a segment, or undefined when nothing better than `[type]` exists.
52
+ * Accepts canonical segments (`{ type, data }`) and unrendered JSX nodes.
53
+ */
54
+ export function segmentFallbackText(segment: unknown, depth = 0): string | undefined {
55
+ if (!segment || typeof segment !== 'object' || depth > MAX_DEPTH) return undefined;
56
+ if (isJsxNode(segment)) {
57
+ const text = flatten(segment, depth);
58
+ return text || undefined;
59
+ }
60
+ const record = segment as { type?: unknown; data?: unknown };
61
+ const data = record.data && typeof record.data === 'object' && !Array.isArray(record.data)
62
+ ? record.data as Record<string, unknown> : undefined;
63
+ if (!data) return undefined;
64
+ if (record.type === 'keyboard') return keyboardLabels(data.rows) || undefined;
65
+ for (const field of ['text', 'content', 'markdown', 'children'] as const) {
66
+ const value = data[field];
67
+ if (value === undefined || value === null) continue;
68
+ const text = flatten(value, depth + 1);
69
+ if (text) return text;
70
+ }
71
+ return undefined;
72
+ }
73
+
74
+ /** Plain text of a segment's body for previews; `[type]` only when nothing readable exists. */
75
+ export function segmentPreviewText(segment: unknown): string {
76
+ const type = segment && typeof segment === 'object' ? (segment as { type?: unknown }).type : undefined;
77
+ return segmentFallbackText(segment) ?? (typeof type === 'string' ? `[${type}]` : '');
78
+ }
@@ -346,8 +346,29 @@ export const sandboxStyles = `
346
346
  .zhin-sandbox .sandbox-at-item > svg { flex-shrink: 0; color: var(--sb-muted-fg); }
347
347
  .zhin-sandbox .sandbox-at-name { font-size: 13px; font-weight: 600; }
348
348
  .zhin-sandbox .sandbox-at-id { font-size: 12px; color: var(--sb-muted-fg); }
349
- .zhin-sandbox .sandbox-hints { display: flex; align-items: center; flex-wrap: wrap; gap: 4px 8px; font-size: 12px; line-height: 1.8; color: var(--sb-muted-fg); }
350
- .zhin-sandbox .sandbox-hints > svg { flex-shrink: 0; }
349
+ .zhin-sandbox .sandbox-hints { font-size: 12px; line-height: 1.8; color: var(--sb-muted-fg); }
350
+ .zhin-sandbox .sandbox-hints > summary { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; user-select: none; list-style: none; }
351
+ .zhin-sandbox .sandbox-hints > summary::-webkit-details-marker { display: none; }
352
+ .zhin-sandbox .sandbox-hints > summary:hover { color: var(--sb-fg); }
353
+ .zhin-sandbox .sandbox-hints > ul { display: flex; flex-wrap: wrap; gap: 4px 12px; margin: 4px 0 0; padding: 0; list-style: none; }
354
+ .zhin-sandbox .sandbox-hints li { display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; }
355
+ .zhin-sandbox .sandbox-more { position: relative; display: inline-flex; }
356
+ .zhin-sandbox .sandbox-more-trigger { color: var(--sb-muted-fg); }
357
+ .zhin-sandbox .sandbox-more-trigger.active { border-color: var(--sb-primary-line); background: var(--sb-primary-soft); color: var(--sb-primary); }
358
+ .zhin-sandbox .sandbox-more-backdrop { position: fixed; inset: 0; z-index: 40; }
359
+ .zhin-sandbox .sandbox-more-menu { position: absolute; top: calc(100% + 6px); right: 0; z-index: 41; display: grid; min-width: 220px; padding: 4px; border: 1px solid var(--sb-border); border-radius: var(--sb-radius-sm); background: var(--sb-bg); box-shadow: 0 8px 24px rgb(0 0 0 / 0.12); }
360
+ .zhin-sandbox .sandbox-more-menu > button { display: flex; align-items: center; gap: 8px; justify-content: flex-start; width: 100%; padding: 8px 10px; border: 0; background: transparent; color: var(--sb-fg); font-size: 13px; text-align: left; }
361
+ .zhin-sandbox .sandbox-more-menu > button:hover { background: var(--sb-accent); }
362
+ .zhin-sandbox .sandbox-more-menu > button[aria-checked="true"] { color: var(--sb-primary); }
363
+ .zhin-sandbox .sandbox-more-menu > button.is-danger { color: var(--sb-danger); }
364
+ .zhin-sandbox .sandbox-more-menu > button > em { margin-left: auto; font-style: normal; }
365
+ .zhin-sandbox .sandbox-more-menu > button > em + em { margin-left: 4px; }
366
+ .zhin-sandbox .sandbox-role-badge.is-simulated { color: var(--sb-muted-fg); }
367
+ .zhin-sandbox .sandbox-speaker-mode { display: grid; gap: 6px; grid-column: 1 / -1; }
368
+ .zhin-sandbox .sandbox-speaker-toggle { display: inline-flex; align-items: center; gap: 8px; font-weight: 600; }
369
+ .zhin-sandbox .sandbox-speaker-mode > p { margin: 0; color: var(--sb-muted-fg); font-size: 12px; }
370
+ .zhin-sandbox .sandbox-speaker-setup { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; font-size: 12px; }
371
+ .zhin-sandbox .sandbox-speaker-setup > em { font-style: normal; color: var(--sb-muted-fg); }
351
372
  .zhin-sandbox .sandbox-hint-key { padding: 1px 6px; border: 1px solid var(--sb-border); border-radius: var(--sb-radius-sm); background: var(--sb-muted); color: var(--sb-fg); font-family: var(--sb-mono); font-size: 12px; line-height: 1.4; }
352
373
  .zhin-sandbox .sandbox-hint-text { margin-right: 6px; }
353
374
 
@@ -471,8 +492,8 @@ export const sandboxStyles = `
471
492
  .zhin-sandbox .agent-playground-runbar { flex-direction: column; align-items: flex-start; gap: 10px; min-height: 0; padding: 12px; }
472
493
  /* In a column the 14rem flex-basis would become the identity row height. */
473
494
  .zhin-sandbox .agent-playground-run-identity { flex: 0 0 auto; width: 100%; }
474
- .zhin-sandbox .agent-playground-run-actions { flex-wrap: nowrap; justify-content: flex-start; margin-left: 0; overflow-x: auto; max-width: 100%; }
475
- .zhin-sandbox .agent-playground-run-actions > button[aria-controls="sandbox-run-inspector"] { display: none; }
495
+ .zhin-sandbox .agent-playground-run-actions { flex-wrap: wrap; justify-content: flex-start; margin-left: 0; max-width: 100%; }
496
+ .zhin-sandbox .sandbox-more-menu { right: auto; left: 0; }
476
497
  .zhin-sandbox .agent-playground-run-actions > a, .zhin-sandbox .agent-playground-run-actions > button { flex-shrink: 0; white-space: nowrap; width: auto; font-size: 13px; }
477
498
  .zhin-sandbox .agent-playground-run-title span { display: none; }
478
499
  .zhin-sandbox .agent-playground-message-scroll { padding: 16px 10px; }
@@ -345,8 +345,29 @@ export const sandboxStyles = `
345
345
  .zhin-sandbox .sandbox-at-item > svg { flex-shrink: 0; color: var(--sb-muted-fg); }
346
346
  .zhin-sandbox .sandbox-at-name { font-size: 13px; font-weight: 600; }
347
347
  .zhin-sandbox .sandbox-at-id { font-size: 12px; color: var(--sb-muted-fg); }
348
- .zhin-sandbox .sandbox-hints { display: flex; align-items: center; flex-wrap: wrap; gap: 4px 8px; font-size: 12px; line-height: 1.8; color: var(--sb-muted-fg); }
349
- .zhin-sandbox .sandbox-hints > svg { flex-shrink: 0; }
348
+ .zhin-sandbox .sandbox-hints { font-size: 12px; line-height: 1.8; color: var(--sb-muted-fg); }
349
+ .zhin-sandbox .sandbox-hints > summary { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; user-select: none; list-style: none; }
350
+ .zhin-sandbox .sandbox-hints > summary::-webkit-details-marker { display: none; }
351
+ .zhin-sandbox .sandbox-hints > summary:hover { color: var(--sb-fg); }
352
+ .zhin-sandbox .sandbox-hints > ul { display: flex; flex-wrap: wrap; gap: 4px 12px; margin: 4px 0 0; padding: 0; list-style: none; }
353
+ .zhin-sandbox .sandbox-hints li { display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; }
354
+ .zhin-sandbox .sandbox-more { position: relative; display: inline-flex; }
355
+ .zhin-sandbox .sandbox-more-trigger { color: var(--sb-muted-fg); }
356
+ .zhin-sandbox .sandbox-more-trigger.active { border-color: var(--sb-primary-line); background: var(--sb-primary-soft); color: var(--sb-primary); }
357
+ .zhin-sandbox .sandbox-more-backdrop { position: fixed; inset: 0; z-index: 40; }
358
+ .zhin-sandbox .sandbox-more-menu { position: absolute; top: calc(100% + 6px); right: 0; z-index: 41; display: grid; min-width: 220px; padding: 4px; border: 1px solid var(--sb-border); border-radius: var(--sb-radius-sm); background: var(--sb-bg); box-shadow: 0 8px 24px rgb(0 0 0 / 0.12); }
359
+ .zhin-sandbox .sandbox-more-menu > button { display: flex; align-items: center; gap: 8px; justify-content: flex-start; width: 100%; padding: 8px 10px; border: 0; background: transparent; color: var(--sb-fg); font-size: 13px; text-align: left; }
360
+ .zhin-sandbox .sandbox-more-menu > button:hover { background: var(--sb-accent); }
361
+ .zhin-sandbox .sandbox-more-menu > button[aria-checked="true"] { color: var(--sb-primary); }
362
+ .zhin-sandbox .sandbox-more-menu > button.is-danger { color: var(--sb-danger); }
363
+ .zhin-sandbox .sandbox-more-menu > button > em { margin-left: auto; font-style: normal; }
364
+ .zhin-sandbox .sandbox-more-menu > button > em + em { margin-left: 4px; }
365
+ .zhin-sandbox .sandbox-role-badge.is-simulated { color: var(--sb-muted-fg); }
366
+ .zhin-sandbox .sandbox-speaker-mode { display: grid; gap: 6px; grid-column: 1 / -1; }
367
+ .zhin-sandbox .sandbox-speaker-toggle { display: inline-flex; align-items: center; gap: 8px; font-weight: 600; }
368
+ .zhin-sandbox .sandbox-speaker-mode > p { margin: 0; color: var(--sb-muted-fg); font-size: 12px; }
369
+ .zhin-sandbox .sandbox-speaker-setup { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; font-size: 12px; }
370
+ .zhin-sandbox .sandbox-speaker-setup > em { font-style: normal; color: var(--sb-muted-fg); }
350
371
  .zhin-sandbox .sandbox-hint-key { padding: 1px 6px; border: 1px solid var(--sb-border); border-radius: var(--sb-radius-sm); background: var(--sb-muted); color: var(--sb-fg); font-family: var(--sb-mono); font-size: 12px; line-height: 1.4; }
351
372
  .zhin-sandbox .sandbox-hint-text { margin-right: 6px; }
352
373
 
@@ -470,8 +491,8 @@ export const sandboxStyles = `
470
491
  .zhin-sandbox .agent-playground-runbar { flex-direction: column; align-items: flex-start; gap: 10px; min-height: 0; padding: 12px; }
471
492
  /* In a column the 14rem flex-basis would become the identity row height. */
472
493
  .zhin-sandbox .agent-playground-run-identity { flex: 0 0 auto; width: 100%; }
473
- .zhin-sandbox .agent-playground-run-actions { flex-wrap: nowrap; justify-content: flex-start; margin-left: 0; overflow-x: auto; max-width: 100%; }
474
- .zhin-sandbox .agent-playground-run-actions > button[aria-controls="sandbox-run-inspector"] { display: none; }
494
+ .zhin-sandbox .agent-playground-run-actions { flex-wrap: wrap; justify-content: flex-start; margin-left: 0; max-width: 100%; }
495
+ .zhin-sandbox .sandbox-more-menu { right: auto; left: 0; }
475
496
  .zhin-sandbox .agent-playground-run-actions > a, .zhin-sandbox .agent-playground-run-actions > button { flex-shrink: 0; white-space: nowrap; width: auto; font-size: 13px; }
476
497
  .zhin-sandbox .agent-playground-run-title span { display: none; }
477
498
  .zhin-sandbox .agent-playground-message-scroll { padding: 16px 10px; }
package/plugin.js CHANGED
@@ -1,9 +1,13 @@
1
1
  // Generated by build-plugin-runtime-entries.mjs. Do not edit.
2
2
  import { definePlugin } from 'zhin.js';
3
+ import { createSandboxConsoleRpc } from "./lib/console.js";
3
4
  export default definePlugin({
4
5
  name: 'sandbox',
5
6
  configUpdate: { featurePaths: [['nickname'], ['profile'], ['endpoints']] },
6
- metadata: {
7
- displayName: 'Sandbox Adapter',
7
+ setup(context) {
8
+ // Account management in the Console (status, add / start / stop / remove), as for other adapters.
9
+ return {
10
+ consoleRpc: createSandboxConsoleRpc(() => context.config.get()),
11
+ };
8
12
  },
9
13
  });
package/src/adapter.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Adapter, type AdapterContext, type EndpointCreationContext } 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, type ChatRoleReader } from 'zhin.js';
4
5
  import { resolveSandboxEndpoint, type SandboxEndpointConfig } from './protocol.js';
5
6
  import { SandboxWsEndpoint } from './endpoint.js';
6
7
  import type { SandboxClientEventMap } from './client.js';
@@ -14,9 +15,14 @@ export class SandboxAdapter extends Adapter<SandboxWsEndpoint, SandboxEndpointCo
14
15
  protected override validateConfiguration(config: SandboxEndpointConfig): void { resolveSandboxEndpoint(config); }
15
16
  protected createEndpoint(input: SandboxEndpointConfig, execution: EndpointCreationContext): SandboxWsEndpoint {
16
17
  return new SandboxWsEndpoint({ id: execution.canonicalId, defaults: resolveSandboxEndpoint(input),
17
- http: this.#context.use(httpHostToken), locale: resolveLocale(this.#context.use(projectLocaleToken)) });
18
+ http: this.#context.use(httpHostToken), locale: resolveLocale(this.#context.use(projectLocaleToken)),
19
+ ...optionalChatRoles(() => this.#context.use(chatRolesToken)) });
18
20
  }
19
21
  }
22
+ /** The instance provides chat roles (ADR 0060 §6); hosts without them (tests, other roots) show no zhin role. */
23
+ function optionalChatRoles(read: () => ChatRoleReader): { chatRoles?: ChatRoleReader } {
24
+ try { return { chatRoles: read() }; } catch { return {}; }
25
+ }
20
26
  declare module '@zhin.js/feature-kit' {
21
27
  interface AdapterRegistry { readonly sandbox: SandboxAdapter; }
22
28
  }
package/src/console.ts ADDED
@@ -0,0 +1,50 @@
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, type AdapterConsoleField } from 'zhin.js/adapter';
9
+ import type { PluginConsoleRpc } from 'zhin.js';
10
+
11
+ export const sandboxConsoleFields: readonly AdapterConsoleField[] = Object.freeze([
12
+ {
13
+ key: 'owner',
14
+ label: '所有者用户 ID',
15
+ labelI18n: { en: 'Owner user ID' },
16
+ placeholder: 'sandbox-user',
17
+ description: 'Console 里以这个用户身份发消息;不填时使用适配器的默认值',
18
+ descriptionI18n: { en: 'The Console chats as this user; the adapter default is used when empty' },
19
+ },
20
+ {
21
+ key: 'nickname',
22
+ label: '机器人昵称',
23
+ labelI18n: { en: 'Bot nickname' },
24
+ description: '会话里显示的机器人名字(可选)',
25
+ descriptionI18n: { en: 'Bot name shown in conversations (optional)' },
26
+ },
27
+ {
28
+ key: 'commandPrefix',
29
+ label: '命令前缀',
30
+ labelI18n: { en: 'Command prefix' },
31
+ placeholder: '/',
32
+ description: '只把以它开头的消息当作命令;留空时任意文本都按命令匹配',
33
+ descriptionI18n: { en: 'Only messages starting with it are commands; empty matches any text' },
34
+ },
35
+ ]);
36
+
37
+ export const sandboxConsoleSpec = Object.freeze({
38
+ adapterKey: 'sandbox',
39
+ adapterDisplayName: 'Sandbox',
40
+ fields: sandboxConsoleFields,
41
+ docsUrl: 'https://zhin.js.org/adapters/sandbox',
42
+ readPermission: 'sandbox:read',
43
+ writePermission: 'sandbox:write',
44
+ idHint: '账号名,例如 sandbox-bot',
45
+ idHintI18n: { en: 'Account name, e.g. sandbox-bot' },
46
+ });
47
+
48
+ export function createSandboxConsoleRpc(getConfig: () => unknown): PluginConsoleRpc {
49
+ return createAdapterConsoleRpc({ ...sandboxConsoleSpec, getConfig });
50
+ }
package/src/endpoint.ts CHANGED
@@ -6,9 +6,9 @@ import { createEndpointSpecification, endpointSpec, type Endpoint, type Endpoint
6
6
  */
7
7
  import { randomUUID } from 'node:crypto';
8
8
  import { execFile } from 'node:child_process';
9
- import type { HttpHost, WsConnection } from '@zhin.js/host-http';
9
+ import { principalAllows, type HttpHost, type WsConnection } from '@zhin.js/host-http';
10
10
  import { formatCompact, getAdapterLogger } from '@zhin.js/logger';
11
- import type { CapabilityId } from 'zhin.js';
11
+ import { hostChatRole, type CapabilityId, type ChatRoleReader } from 'zhin.js';
12
12
  import { EndpointDeliveryError, type PlatformStandingLevel } from '@zhin.js/im-contract';
13
13
  import {
14
14
  bindSandboxWsSocket,
@@ -16,6 +16,7 @@ import {
16
16
  formatSandboxOutbound,
17
17
  parseSandboxWsFrame,
18
18
  sandboxInboundConversation,
19
+ sandboxSimulatedSenderId,
19
20
  whenWsOpen,
20
21
  type ResolvedSandboxBot,
21
22
  type SandboxWsSocket,
@@ -134,6 +135,44 @@ export interface SandboxEndpointOptions {
134
135
  readonly id: CapabilityId;
135
136
  readonly http: HttpHost;
136
137
  readonly defaults: ResolvedSandboxBot;
138
+ /** Chat roles (`chatRolesToken`, ADR 0060 §6): the sender's zhin role shown on the page. */
139
+ readonly chatRoles?: ChatRoleReader;
140
+ }
141
+
142
+ /**
143
+ * ADR 0060 §5.4 (P0): what the Runtime resolves for this sender — zhin role and the Agent trust
144
+ * tier it implies (`resolveTurnTrustLevel`: a global owner → `owner`, admin / trusted or a
145
+ * lower-level owner → `trusted_member`, anyone else over IM → `group_member`). The page shows it
146
+ * next to the simulated platform standing so 群主 is never mistaken for a zhin role.
147
+ */
148
+ export function sandboxSenderRoleFacts(reader: ChatRoleReader | undefined, conversation: Parameters<ChatRoleReader['factsOf']>[0], senderId: string):
149
+ { senderChatRole?: string; senderTrustLevel: 'owner' | 'trusted_member' | 'group_member' } {
150
+ let facts: ReturnType<ChatRoleReader['factsOf']>;
151
+ try { facts = reader?.factsOf(conversation, senderId); } catch { facts = undefined; }
152
+ const host = hostChatRole(facts);
153
+ return {
154
+ ...(facts?.chatRole ? { senderChatRole: facts.chatRole } : {}),
155
+ senderTrustLevel: host === 'owner' ? 'owner' : host ? 'trusted_member' : 'group_member',
156
+ };
157
+ }
158
+
159
+ /** Why 「以我的聊天身份发言」 was not used for a message (`asMeUnavailable` on the echo). */
160
+ export type SandboxAsMeUnavailableReason = 'no-console-user' | 'no-identity' | 'needs-global-iam';
161
+
162
+ interface SandboxConsoleUser {
163
+ readonly userId: string;
164
+ readonly displayName?: string;
165
+ /** Holds global `iam.manage`: may speak as a linked person who holds a global grant (ADR 0060 §5.4). */
166
+ readonly canManageGlobal: boolean;
167
+ }
168
+
169
+ /** The signed-in Console user behind a socket (sessions and API tokens); none for the bootstrap principal or standalone. */
170
+ export function sandboxConsoleUser(principal: WsConnection['principal']): SandboxConsoleUser | undefined {
171
+ if (!principal || (principal.kind !== 'user' && principal.kind !== 'api-token')) return undefined;
172
+ if (typeof principal.userId !== 'string' || !principal.userId) return undefined;
173
+ let canManageGlobal = false;
174
+ try { canManageGlobal = principalAllows(principal, 'iam.manage'); } catch { canManageGlobal = false; }
175
+ return Object.freeze({ userId: principal.userId, ...(principal.displayName ? { displayName: principal.displayName } : {}), canManageGlobal });
137
176
  }
138
177
 
139
178
  /**
@@ -323,6 +362,9 @@ export class SandboxWsEndpoint extends SandboxClient<SandboxConnection> implemen
323
362
  const owner = this.#options.defaults.owner;
324
363
  // Every admitted host-authenticated socket carries a Console principal allowed to use it.
325
364
  const canExecute = true;
365
+ // ADR 0060 §5.4: a signed-in Console user may speak as their linked chat identity. The bootstrap
366
+ // principal and `--standalone` (no gateway) have no user: everything is simulated there.
367
+ const consoleUser = sandboxConsoleUser(connection.principal);
326
368
  const socket = sandboxSocketOf(connection);
327
369
  const connectionId = randomUUID();
328
370
  const subscription: SandboxConnection = {
@@ -345,7 +387,10 @@ export class SandboxWsEndpoint extends SandboxClient<SandboxConnection> implemen
345
387
  }));
346
388
  return;
347
389
  }
348
- const frame = parseSandboxWsFrame(raw);
390
+ const frame = parseSandboxWsFrame(raw, {
391
+ id: this.#options.defaults.id,
392
+ ...(this.#options.defaults.nickname ? { names: [this.#options.defaults.nickname] } : {}),
393
+ });
349
394
  if (frame.kind === 'invalid') {
350
395
  socket.send(JSON.stringify({
351
396
  type: 'error', endpoint: target, connectionId,
@@ -365,13 +410,17 @@ export class SandboxWsEndpoint extends SandboxClient<SandboxConnection> implemen
365
410
  }
366
411
  const parsed = frame.message;
367
412
  void this.#emitPlatformEvent('message', raw);
368
- const senderId = parsed.senderId || owner;
369
- const senderName = parsed.senderName || senderId;
370
413
  const sceneId = parsed.id || owner;
371
414
  const conversation = { ...sandboxInboundConversation(String(this.#options.id), {
372
415
  type: parsed.type,
373
416
  id: sceneId,
374
417
  }), endpoint: this[endpointSpec].identity };
418
+ const speaker = this.#speaker(parsed.asMe === true, consoleUser, conversation);
419
+ // The id the page chose (shown as typed); the Runtime only ever sees the speaker's real
420
+ // identity or the reserved simulated id, never a client-chosen id that could hold a role.
421
+ const clientSenderId = parsed.senderId || owner;
422
+ const senderId = speaker.identity ? speaker.identity.userId : sandboxSimulatedSenderId(clientSenderId);
423
+ const senderName = speaker.identity ? (consoleUser?.displayName || speaker.identity.userId) : (parsed.senderName || clientSenderId);
375
424
  this.#logger.debug(formatCompact({
376
425
  op: 'sandbox_recv',
377
426
  target,
@@ -385,8 +434,12 @@ export class SandboxWsEndpoint extends SandboxClient<SandboxConnection> implemen
385
434
  const messageId = parsed.messageId ?? randomUUID();
386
435
  this.#broadcast(this.#subscribers(scene, true), JSON.stringify({
387
436
  ...scene, conversation: scene, direction: 'inbound', senderId,
388
- ...(parsed.senderName ? { senderName: parsed.senderName } : {}),
437
+ displaySenderId: speaker.identity ? speaker.identity.userId : clientSenderId,
438
+ simulated: !speaker.identity,
439
+ ...(speaker.unavailable ? { asMeUnavailable: speaker.unavailable } : {}),
440
+ ...(speaker.identity || parsed.senderName ? { senderName } : {}),
389
441
  ...(parsed.senderRole ? { senderRole: parsed.senderRole } : {}),
442
+ ...sandboxSenderRoleFacts(this.#options.chatRoles, conversation, senderId),
390
443
  messageId, endpoint: this.#options.defaults.id, content: parsed.content, timestamp: parsed.timestamp,
391
444
  }));
392
445
  // ADR 0056 §1: the simulated group role is a platform standing (master = 群主). It never
@@ -461,6 +514,8 @@ export class SandboxWsEndpoint extends SandboxClient<SandboxConnection> implemen
461
514
  endpoint: target,
462
515
  workingDirectory: process.cwd(),
463
516
  canExecute,
517
+ // Whether 「以我的聊天身份发言」 can work on this socket (a signed-in Console user).
518
+ consoleUser: consoleUser !== undefined,
464
519
  shellIsolation,
465
520
  content: [{
466
521
  type: 'text',
@@ -478,6 +533,26 @@ export class SandboxWsEndpoint extends SandboxClient<SandboxConnection> implemen
478
533
  });
479
534
  }
480
535
 
536
+ /**
537
+ * ADR 0060 §5.4: the identity a message speaks as. Only on request, only for a signed-in Console
538
+ * user, and only an identity of the person linked to that user on this adapter (`consoleSpeaker`).
539
+ * A person who holds a global grant is spoken as only by a caller with global `iam.manage`;
540
+ * otherwise the message goes out as a simulated, role-less sender (`needs-global-iam`), the
541
+ * same rule `chat-identities.simulated.ensure` applies when it creates the identity.
542
+ */
543
+ #speaker(asMe: boolean, user: SandboxConsoleUser | undefined, conversation: Parameters<ChatRoleReader['factsOf']>[0]):
544
+ { readonly identity?: { readonly adapter: string; readonly userId: string }; readonly unavailable?: SandboxAsMeUnavailableReason } {
545
+ if (!asMe) return {};
546
+ if (!user) return { unavailable: 'no-console-user' };
547
+ const speaker = (canManageGlobal: boolean) => {
548
+ try { return this.#options.chatRoles?.consoleSpeaker?.(conversation, user.userId, { canManageGlobal }); } catch { return undefined; }
549
+ };
550
+ const identity = speaker(user.canManageGlobal);
551
+ if (identity) return { identity };
552
+ // Tell 「no identity yet」 apart from 「the person holds global grants」.
553
+ return { unavailable: !user.canManageGlobal && speaker(true) ? 'needs-global-iam' : 'no-identity' };
554
+ }
555
+
481
556
  #ensurePlaceholder(name: string, owner: string): void {
482
557
  if (this.connectionRecords.has(name)) return;
483
558
  this.connectionRecords.set(name, {