@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.
@@ -12,6 +12,7 @@ import { buildSandboxWebSocketUrl, captureSandboxRequestContext, createSandboxMe
12
12
  import { createWorkspaceDirectoryController, type DirectoryStatus } from './workspaceDirectoryState.js';
13
13
  import type { SandboxWorkspaceScope } from './workspaceDirectory.js';
14
14
  import { isApprovalPrompt, readSandboxCommandHints, type SandboxCommandHints } from './composerCommands.js';
15
+ import { ensureSandboxChatIdentity, readServerSpeaker, wantsAsMe, type SandboxServerSpeaker, type SandboxSpeakerMode } from './chatIdentity.js';
15
16
  import { isJsxNode, segmentFallbackText, segmentPreviewText } from './segmentFallback.js';
16
17
  import {
17
18
  User, Bot, Users, Trash2, Send, Hash, MessageSquare,
@@ -63,6 +64,12 @@ export interface SandboxPageProps {
63
64
  readonly renderConversationDetails?: (context: { readonly sessionKey: string; readonly canExecute: boolean; readonly connectionId?: string }) => React.ReactNode
64
65
  }
65
66
 
67
+ /** ADR 0060 §5.4: the simulated role is a platform standing (群主 / 管理员 / 成员), never a zhin role. */
68
+ function platformStandingLabel(role: 'master' | 'admin' | 'member', locale: string): string {
69
+ if (locale === 'en') return role === 'master' ? 'group owner' : role === 'admin' ? 'group admin' : 'member'
70
+ return role === 'master' ? '群主' : role === 'admin' ? '群管理员' : '成员'
71
+ }
72
+
66
73
  export default function Sandbox(props: SandboxPageProps = {}) {
67
74
  const [locale, setLocale] = useState<SandboxLocale>('zh-CN')
68
75
  const localeRef = useRef<SandboxLocale>('zh-CN')
@@ -111,6 +118,13 @@ export default function Sandbox(props: SandboxPageProps = {}) {
111
118
  const [senderId, setSenderId] = useState('dev-user')
112
119
  const [senderName, setSenderName] = useState('Developer')
113
120
  const [senderRole, setSenderRole] = useState<'master' | 'admin' | 'member'>('master')
121
+ // ADR 0060 §5.4: what the server resolved for the last message sent (speaker, zhin role, Agent trust tier).
122
+ const [serverRole, setServerRole] = useState<SandboxServerSpeaker | null>(null)
123
+ // 「以我的聊天身份发言」 (default) vs a simulated sender; only a signed-in Console user can speak as themselves.
124
+ const [speakerMode, setSpeakerMode] = useState<SandboxSpeakerMode>('me')
125
+ const [consoleUser, setConsoleUser] = useState(false)
126
+ const [identitySetup, setIdentitySetup] = useState<{ status: 'idle' | 'busy' | 'done' | 'unsupported' } | { status: 'failed'; message: string }>({ status: 'idle' })
127
+ const asMe = wantsAsMe(speakerMode, consoleUser)
114
128
  const [showSenderSettings, setShowSenderSettings] = useState(false)
115
129
  /** Runbar overflow: identity, run settings, inspector and clear live here (#1250). */
116
130
  const [showMoreActions, setShowMoreActions] = useState(false)
@@ -265,6 +279,8 @@ export default function Sandbox(props: SandboxPageProps = {}) {
265
279
  shellIsolation?: { available?: boolean; provider?: string; message?: string }; timestamp: number;
266
280
  messageId?: string; bot?: string; protocol?: string; connectionId?: string; direction?: string; senderId?: string;
267
281
  senderName?: string; senderRole?: 'master' | 'admin' | 'member';
282
+ senderChatRole?: string; senderTrustLevel?: string; consoleUser?: boolean;
283
+ simulated?: boolean; displaySenderId?: string; asMeUnavailable?: string;
268
284
  revision?: number; streaming?: boolean;
269
285
  conversation?: { type: Channel['type']; id: string };
270
286
  }) => {
@@ -288,6 +304,7 @@ export default function Sandbox(props: SandboxPageProps = {}) {
288
304
  connectionRef.current = { protocol: data.protocol, connectionId: data.connectionId, ownerId: data.id, canExecute: data.canExecute !== false }
289
305
  setReadyConnectionId(data.connectionId)
290
306
  setCanExecute(data.canExecute !== false)
307
+ setConsoleUser(data.consoleUser === true)
291
308
  setTransportNotice(data.canExecute === false ? sandboxText(locale, "当前 Token 只有演示权限,任务运行已禁用。") : null)
292
309
  if (data.shellIsolation) {
293
310
  setShellIsolation({
@@ -331,6 +348,8 @@ export default function Sandbox(props: SandboxPageProps = {}) {
331
348
  const channelType: Channel['type'] = data.conversation?.type ?? (data.type === 'group' || data.type === 'channel' ? data.type : 'private')
332
349
  const sceneId = data.conversation?.id ?? data.id
333
350
  const isInput = data.direction === 'inbound'
351
+ const speaker = isInput ? readServerSpeaker(data as Record<string, unknown>) : null
352
+ if (speaker) setServerRole(speaker)
334
353
  // Interactive choices are transport inputs, not another chat turn or an approval result.
335
354
  if (isInput && content.every((segment) => segment.type === 'action')) return
336
355
  const channelName = channelType === 'private'
@@ -353,7 +372,7 @@ export default function Sandbox(props: SandboxPageProps = {}) {
353
372
  setMessages((prev) => mergePlaygroundMessage(prev, {
354
373
  id: data.messageId ?? createSandboxMessageId(), type: isInput ? 'sent' : 'received', channelType,
355
374
  interactionReadOnly: false,
356
- channelId: sceneId, channelName, senderId: isInput ? data.senderId || connectionRef.current.ownerId || 'owner' : 'endpoint',
375
+ channelId: sceneId, channelName, senderId: isInput ? data.displaySenderId || data.senderId || connectionRef.current.ownerId || 'owner' : 'endpoint',
357
376
  senderName: isInput ? (typeof data.senderName === 'string' && data.senderName.trim() ? data.senderName.trim() : sandboxText(locale, "当前用户")) : data.bot || endpointIdRef.current, content, timestamp: data.timestamp,
358
377
  ...(Number.isSafeInteger(data.revision) && data.revision! > 0 ? { revision: data.revision } : {}),
359
378
  ...(typeof data.streaming === 'boolean' ? { streaming: data.streaming } : {}),
@@ -368,7 +387,7 @@ export default function Sandbox(props: SandboxPageProps = {}) {
368
387
  const resolvedSenderName = senderName.trim() || sandboxText(localeRef.current, "测试用户")
369
388
  if (!submitSandboxFrame(wsRef.current, {
370
389
  type: scene.type, id: scene.id, messageId: createSandboxMessageId(), content: segments,
371
- senderId: resolvedSenderId, senderName: resolvedSenderName, senderRole,
390
+ senderId: resolvedSenderId, senderName: resolvedSenderName, senderRole, ...(asMe ? { asMe: true } : {}),
372
391
  agentRun: scene.runConfig, timestamp: Date.now(),
373
392
  })) {
374
393
  setTransportNotice(sandboxText(localeRef.current, "Sandbox 连接尚未就绪,审批选择未发送。"))
@@ -881,7 +900,7 @@ export default function Sandbox(props: SandboxPageProps = {}) {
881
900
  }
882
901
  if (!submitSandboxFrame(wsRef.current, {
883
902
  type: scene.type, id: scene.id, messageId: newMessage.id, content: segments,
884
- senderId: resolvedSenderId, senderName: resolvedSenderName, senderRole,
903
+ senderId: resolvedSenderId, senderName: resolvedSenderName, senderRole, ...(asMe ? { asMe: true } : {}),
885
904
  agentRun: scene.runConfig, timestamp: newMessage.timestamp,
886
905
  })) {
887
906
  setTransportNotice(sandboxText(localeRef.current, "Sandbox 连接尚未就绪,消息未发送。"))
@@ -1068,6 +1087,7 @@ export default function Sandbox(props: SandboxPageProps = {}) {
1068
1087
  .sandbox-role-badge.is-master { background: rgba(245,158,11,0.18); color: #d97706; }
1069
1088
  .sandbox-role-badge.is-admin { background: rgba(59,130,246,0.18); color: #2563eb; }
1070
1089
  .sandbox-role-badge.is-member { background: rgba(16,185,129,0.16); color: #059669; }
1090
+ .sandbox-role-badge.is-zhin { text-transform: none; background: rgba(139,92,246,0.16); color: #7c3aed; }
1071
1091
  .sandbox-role-switcher { display: inline-flex; gap: 4px; }
1072
1092
  .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; }
1073
1093
  .sandbox-role-option.active { font-weight: 600; border-color: currentColor; background: rgba(59,130,246,0.12); }
@@ -1201,7 +1221,12 @@ export default function Sandbox(props: SandboxPageProps = {}) {
1201
1221
  onClick={() => { setShowSenderSettings((visible) => !visible); setShowMoreActions(false) }}>
1202
1222
  <User size={14} />
1203
1223
  <span>{sandboxText(locale, "模拟发送者")}</span>
1204
- <em className={cn("sandbox-role-badge", `is-${senderRole}`)}>{senderName.trim() || senderId.trim() || 'dev-user'} · {senderRole}</em>
1224
+ <em className={cn("sandbox-role-badge", `is-${senderRole}`)} title={locale === 'en' ? 'Simulated platform standing (not a zhin role)' : '模拟的平台身份(不是 zhin 角色)'}>{asMe ? sandboxText(locale, "我的聊天身份") : (senderName.trim() || senderId.trim() || 'dev-user')} · {platformStandingLabel(senderRole, locale)}</em>
1225
+ {serverRole && (serverRole.simulated
1226
+ ? <em className="sandbox-role-badge is-simulated" title={sandboxText(locale, "客户端自填的发送者不解析 zhin 角色")}>{sandboxText(locale, "模拟身份,无角色")}</em>
1227
+ : <em className="sandbox-role-badge is-zhin" title={locale === 'en' ? 'Resolved by the server: zhin role · Agent trust tier' : '服务端解析:zhin 角色 · Agent 信任档位'}>
1228
+ {`zhin: ${serverRole.chatRole ?? (locale === 'en' ? 'none' : '无')} · ${serverRole.trustLevel}`}
1229
+ </em>)}
1205
1230
  </button>
1206
1231
  <button type="button" role="menuitemcheckbox" aria-checked={showRunSettings}
1207
1232
  onClick={() => { setShowRunSettings((visible) => !visible); setShowMoreActions(false) }}>
@@ -1224,10 +1249,44 @@ export default function Sandbox(props: SandboxPageProps = {}) {
1224
1249
 
1225
1250
  {showSenderSettings && (
1226
1251
  <section className="agent-playground-run-settings sandbox-sender-settings" aria-label={locale === 'en' ? 'Simulated sender' : '模拟发送者配置'}>
1252
+ <div className="sandbox-speaker-mode">
1253
+ <label className="sandbox-speaker-toggle">
1254
+ <input type="checkbox" checked={speakerMode === 'me'} disabled={!consoleUser}
1255
+ onChange={(event) => setSpeakerMode(event.target.checked ? 'me' : 'simulated')} />
1256
+ <span>{sandboxText(locale, "以我的聊天身份发言")}</span>
1257
+ </label>
1258
+ <p>
1259
+ {!consoleUser
1260
+ ? sandboxText(locale, "当前连接没有 Console 用户(未登录或 --standalone),所有消息都按模拟身份处理,不解析 zhin 角色。")
1261
+ : asMe
1262
+ ? sandboxText(locale, "以链接到你 Console 账号的聊天身份发言,角色按你的聊天角色解析。")
1263
+ : sandboxText(locale, "模拟身份,无角色:自填的发送者 ID 只用于模拟别人,不解析 zhin 角色。")}
1264
+ </p>
1265
+ {asMe && serverRole?.asMeUnavailable === 'needs-global-iam' && (
1266
+ <div className="sandbox-speaker-setup" role="status">
1267
+ <span>{sandboxText(locale, "链接到你的聊天身份持有全局角色,以它发言需要全局 iam.manage 权限;上一条消息按模拟身份(无角色)发送。")}</span>
1268
+ </div>
1269
+ )}
1270
+ {asMe && serverRole?.asMeUnavailable === 'no-identity' && (
1271
+ <div className="sandbox-speaker-setup" role="status">
1272
+ <span>{sandboxText(locale, "你在 Sandbox 上还没有聊天身份,上一条消息按模拟身份发送。")}</span>
1273
+ <button type="button" disabled={identitySetup.status === 'busy'} onClick={() => {
1274
+ setIdentitySetup({ status: 'busy' })
1275
+ void ensureSandboxChatIdentity(socketRequestContextRef.current ?? undefined).then((result) => {
1276
+ setIdentitySetup(result.status === 'ok' ? { status: 'done' } : result)
1277
+ })
1278
+ }}>{sandboxText(locale, "在 Sandbox 上创建我的聊天身份")}</button>
1279
+ {identitySetup.status === 'done' && <em>{sandboxText(locale, "已创建,下一条消息生效。")}</em>}
1280
+ {identitySetup.status === 'unsupported' && <em>{sandboxText(locale, "当前 Host 不支持,请升级。")}</em>}
1281
+ {identitySetup.status === 'failed' && <em>{identitySetup.message}</em>}
1282
+ </div>
1283
+ )}
1284
+ </div>
1227
1285
  <label>
1228
- <span><User size={14} />{locale === 'en' ? 'Sender ID' : '发送者 ID'}</span>
1286
+ <span><User size={14} />{locale === 'en' ? 'Sender ID (simulated, no role)' : '发送者 ID(模拟身份,无角色)'}</span>
1229
1287
  <input
1230
1288
  value={senderId}
1289
+ disabled={asMe}
1231
1290
  onChange={(event) => setSenderId(event.target.value)}
1232
1291
  placeholder="dev-user"
1233
1292
  spellCheck={false}
@@ -1237,14 +1296,15 @@ export default function Sandbox(props: SandboxPageProps = {}) {
1237
1296
  <span>{locale === 'en' ? 'Sender Name' : '发送者昵称'}</span>
1238
1297
  <input
1239
1298
  value={senderName}
1299
+ disabled={asMe}
1240
1300
  onChange={(event) => setSenderName(event.target.value)}
1241
1301
  placeholder="Developer"
1242
1302
  spellCheck={false}
1243
1303
  />
1244
1304
  </label>
1245
1305
  <label>
1246
- <span><ShieldCheck size={14} />{locale === 'en' ? 'Sender Role' : '角色权限'}</span>
1247
- <div className="sandbox-role-switcher" role="group" aria-label={locale === 'en' ? 'Sender role' : '角色权限'}>
1306
+ <span><ShieldCheck size={14} />{locale === 'en' ? 'Platform standing (not a zhin role)' : '平台身份(不是 zhin 角色)'}</span>
1307
+ <div className="sandbox-role-switcher" role="group" aria-label={locale === 'en' ? 'Platform standing' : '平台身份'}>
1248
1308
  {(['member', 'admin', 'master'] as const).map((role) => (
1249
1309
  <button
1250
1310
  key={role}
@@ -1253,13 +1313,13 @@ export default function Sandbox(props: SandboxPageProps = {}) {
1253
1313
  className={cn("sandbox-role-option", `is-${role}`, senderRole === role && "active")}
1254
1314
  onClick={() => setSenderRole(role)}
1255
1315
  >
1256
- {role}
1316
+ {platformStandingLabel(role, locale)}
1257
1317
  </button>
1258
1318
  ))}
1259
1319
  </div>
1260
1320
  </label>
1261
1321
  <div className="sandbox-sender-presets">
1262
- <button type="button" onClick={() => { setSenderId('dev-user'); setSenderName('Developer'); setSenderRole('master') }}>Master (dev-user)</button>
1322
+ <button type="button" onClick={() => { setSenderId('dev-user'); setSenderName('Developer'); setSenderRole('master') }}>{locale === 'en' ? 'Group owner (platform standing, dev-user)' : '群主(平台身份,dev-user)'}</button>
1263
1323
  <button type="button" onClick={() => { setSenderId('admin-user'); setSenderName('Admin'); setSenderRole('admin') }}>Admin (admin-user)</button>
1264
1324
  <button type="button" onClick={() => { setSenderId('member-user'); setSenderName('Member'); setSenderRole('member') }}>Member (member-user)</button>
1265
1325
  </div>
@@ -0,0 +1,47 @@
1
+ // Generated by build-plugin-runtime-entries.mjs. Do not edit.
2
+ import { getSandboxApiBase, getSandboxAuthHeaders } from './sandboxTransport.js';
3
+ /** Reads the speaker fields of an inbound echo; null on frames from an older Host without them. */
4
+ export function readServerSpeaker(frame) {
5
+ if (typeof frame.senderId !== 'string' || typeof frame.senderTrustLevel !== 'string')
6
+ return null;
7
+ const simulated = frame.simulated === true;
8
+ const unavailable = frame.asMeUnavailable === 'no-console-user' || frame.asMeUnavailable === 'no-identity' || frame.asMeUnavailable === 'needs-global-iam'
9
+ ? frame.asMeUnavailable : undefined;
10
+ return Object.freeze({
11
+ senderId: frame.senderId,
12
+ displaySenderId: typeof frame.displaySenderId === 'string' && frame.displaySenderId ? frame.displaySenderId : frame.senderId,
13
+ simulated,
14
+ trustLevel: frame.senderTrustLevel,
15
+ ...(typeof frame.senderChatRole === 'string' && frame.senderChatRole ? { chatRole: frame.senderChatRole } : {}),
16
+ ...(unavailable ? { asMeUnavailable: unavailable } : {}),
17
+ });
18
+ }
19
+ /** Whether a send should ask to speak as the linked identity (only when the socket has a Console user). */
20
+ export function wantsAsMe(mode, consoleUser) {
21
+ return mode === 'me' && consoleUser;
22
+ }
23
+ /**
24
+ * `chat-identities.simulated.ensure`: gives the caller's person an identity on the Sandbox (and
25
+ * links a new person to the caller when there is none). `unsupported` on a Host without the RPC.
26
+ */
27
+ export async function ensureSandboxChatIdentity(context, signal) {
28
+ const url = new URL('/api/console/request', `${(context ? context.apiBase : getSandboxApiBase()) || window.location.origin}/`);
29
+ try {
30
+ const response = await fetch(url, {
31
+ method: 'POST',
32
+ headers: { ...(context?.headers ?? getSandboxAuthHeaders()), 'content-type': 'application/json' },
33
+ body: JSON.stringify({ type: 'chat-identities.simulated.ensure', data: {}, requestId: `sandbox-identity-${Date.now()}` }),
34
+ ...(signal ? { signal } : {}),
35
+ });
36
+ const body = await response.json().catch(() => null);
37
+ if (response.ok && body?.success)
38
+ return { status: 'ok' };
39
+ // Older Hosts refuse an RPC they do not list (`unmapped`) or answer 未知请求.
40
+ if (response.status === 404 || body?.code === 'unmapped' || body?.code === 'unknown_rpc' || body?.error === '未知请求')
41
+ return { status: 'unsupported' };
42
+ return { status: 'failed', message: typeof body?.error === 'string' && body.error ? body.error : `HTTP ${response.status}` };
43
+ }
44
+ catch (error) {
45
+ return { status: 'failed', message: error instanceof Error ? error.message : String(error) };
46
+ }
47
+ }
@@ -0,0 +1,66 @@
1
+ import { getSandboxApiBase, getSandboxAuthHeaders, type SandboxRequestContext } from './sandboxTransport.js';
2
+
3
+ /**
4
+ * ADR 0060 §5.4: who a Sandbox message speaks as. The server decides from the authenticated
5
+ * Console principal; the page only asks (`asMe`) and shows what the server answered.
6
+ */
7
+ export type SandboxSpeakerMode = 'me' | 'simulated';
8
+
9
+ /** Why 「以我的聊天身份发言」 could not be used for a message (`asMeUnavailable` on the echo). */
10
+ export type SandboxAsMeUnavailable = 'no-console-user' | 'no-identity' | 'needs-global-iam';
11
+
12
+ /** The server's answer for the last message this page sent. */
13
+ export interface SandboxServerSpeaker {
14
+ readonly senderId: string;
15
+ /** The id as typed (simulated) or the linked identity (me). */
16
+ readonly displaySenderId: string;
17
+ readonly simulated: boolean;
18
+ readonly chatRole?: string;
19
+ readonly trustLevel: string;
20
+ readonly asMeUnavailable?: SandboxAsMeUnavailable;
21
+ }
22
+
23
+ /** Reads the speaker fields of an inbound echo; null on frames from an older Host without them. */
24
+ export function readServerSpeaker(frame: Readonly<Record<string, unknown>>): SandboxServerSpeaker | null {
25
+ if (typeof frame.senderId !== 'string' || typeof frame.senderTrustLevel !== 'string') return null;
26
+ const simulated = frame.simulated === true;
27
+ const unavailable = frame.asMeUnavailable === 'no-console-user' || frame.asMeUnavailable === 'no-identity' || frame.asMeUnavailable === 'needs-global-iam'
28
+ ? frame.asMeUnavailable : undefined;
29
+ return Object.freeze({
30
+ senderId: frame.senderId,
31
+ displaySenderId: typeof frame.displaySenderId === 'string' && frame.displaySenderId ? frame.displaySenderId : frame.senderId,
32
+ simulated,
33
+ trustLevel: frame.senderTrustLevel,
34
+ ...(typeof frame.senderChatRole === 'string' && frame.senderChatRole ? { chatRole: frame.senderChatRole } : {}),
35
+ ...(unavailable ? { asMeUnavailable: unavailable } : {}),
36
+ });
37
+ }
38
+
39
+ /** Whether a send should ask to speak as the linked identity (only when the socket has a Console user). */
40
+ export function wantsAsMe(mode: SandboxSpeakerMode, consoleUser: boolean): boolean {
41
+ return mode === 'me' && consoleUser;
42
+ }
43
+
44
+ /**
45
+ * `chat-identities.simulated.ensure`: gives the caller's person an identity on the Sandbox (and
46
+ * links a new person to the caller when there is none). `unsupported` on a Host without the RPC.
47
+ */
48
+ export async function ensureSandboxChatIdentity(context?: SandboxRequestContext, signal?: AbortSignal):
49
+ Promise<{ readonly status: 'ok' } | { readonly status: 'unsupported' } | { readonly status: 'failed'; readonly message: string }> {
50
+ const url = new URL('/api/console/request', `${(context ? context.apiBase : getSandboxApiBase()) || window.location.origin}/`);
51
+ try {
52
+ const response = await fetch(url, {
53
+ method: 'POST',
54
+ headers: { ...(context?.headers ?? getSandboxAuthHeaders()), 'content-type': 'application/json' },
55
+ body: JSON.stringify({ type: 'chat-identities.simulated.ensure', data: {}, requestId: `sandbox-identity-${Date.now()}` }),
56
+ ...(signal ? { signal } : {}),
57
+ });
58
+ const body = await response.json().catch(() => null) as { success?: boolean; error?: unknown; code?: unknown } | null;
59
+ if (response.ok && body?.success) return { status: 'ok' };
60
+ // Older Hosts refuse an RPC they do not list (`unmapped`) or answer 未知请求.
61
+ if (response.status === 404 || body?.code === 'unmapped' || body?.code === 'unknown_rpc' || body?.error === '未知请求') return { status: 'unsupported' };
62
+ return { status: 'failed', message: typeof body?.error === 'string' && body.error ? body.error : `HTTP ${response.status}` };
63
+ } catch (error) {
64
+ return { status: 'failed', message: error instanceof Error ? error.message : String(error) };
65
+ }
66
+ }
@@ -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",
@@ -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",
@@ -362,6 +362,13 @@ export const sandboxStyles = `
362
362
  .zhin-sandbox .sandbox-more-menu > button[aria-checked="true"] { color: var(--sb-primary); }
363
363
  .zhin-sandbox .sandbox-more-menu > button.is-danger { color: var(--sb-danger); }
364
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); }
365
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; }
366
373
  .zhin-sandbox .sandbox-hint-text { margin-right: 6px; }
367
374
 
@@ -361,6 +361,13 @@ export const sandboxStyles = `
361
361
  .zhin-sandbox .sandbox-more-menu > button[aria-checked="true"] { color: var(--sb-primary); }
362
362
  .zhin-sandbox .sandbox-more-menu > button.is-danger { color: var(--sb-danger); }
363
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); }
364
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; }
365
372
  .zhin-sandbox .sandbox-hint-text { margin-right: 6px; }
366
373
 
package/plugin.js CHANGED
@@ -1,6 +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']] },
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
+ };
12
+ },
6
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 = {
@@ -368,13 +410,17 @@ export class SandboxWsEndpoint extends SandboxClient<SandboxConnection> implemen
368
410
  }
369
411
  const parsed = frame.message;
370
412
  void this.#emitPlatformEvent('message', raw);
371
- const senderId = parsed.senderId || owner;
372
- const senderName = parsed.senderName || senderId;
373
413
  const sceneId = parsed.id || owner;
374
414
  const conversation = { ...sandboxInboundConversation(String(this.#options.id), {
375
415
  type: parsed.type,
376
416
  id: sceneId,
377
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);
378
424
  this.#logger.debug(formatCompact({
379
425
  op: 'sandbox_recv',
380
426
  target,
@@ -388,8 +434,12 @@ export class SandboxWsEndpoint extends SandboxClient<SandboxConnection> implemen
388
434
  const messageId = parsed.messageId ?? randomUUID();
389
435
  this.#broadcast(this.#subscribers(scene, true), JSON.stringify({
390
436
  ...scene, conversation: scene, direction: 'inbound', senderId,
391
- ...(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 } : {}),
392
441
  ...(parsed.senderRole ? { senderRole: parsed.senderRole } : {}),
442
+ ...sandboxSenderRoleFacts(this.#options.chatRoles, conversation, senderId),
393
443
  messageId, endpoint: this.#options.defaults.id, content: parsed.content, timestamp: parsed.timestamp,
394
444
  }));
395
445
  // ADR 0056 §1: the simulated group role is a platform standing (master = 群主). It never
@@ -464,6 +514,8 @@ export class SandboxWsEndpoint extends SandboxClient<SandboxConnection> implemen
464
514
  endpoint: target,
465
515
  workingDirectory: process.cwd(),
466
516
  canExecute,
517
+ // Whether 「以我的聊天身份发言」 can work on this socket (a signed-in Console user).
518
+ consoleUser: consoleUser !== undefined,
467
519
  shellIsolation,
468
520
  content: [{
469
521
  type: 'text',
@@ -481,6 +533,26 @@ export class SandboxWsEndpoint extends SandboxClient<SandboxConnection> implemen
481
533
  });
482
534
  }
483
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
+
484
556
  #ensurePlaceholder(name: string, owner: string): void {
485
557
  if (this.connectionRecords.has(name)) return;
486
558
  this.connectionRecords.set(name, {