@zhin.js/adapter-sandbox 1.1.34 → 1.1.36
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 +69 -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 +18 -18
- 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/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
|
|
9
|
+
import { principalAllows, type HttpHost, type WsConnection } from '@zhin.js/host-http';
|
|
10
10
|
import { formatCompact, getAdapterLogger } from '@zhin.js/logger';
|
|
11
|
-
import type
|
|
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
|
-
|
|
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, {
|
package/src/protocol.ts
CHANGED
|
@@ -178,6 +178,11 @@ export interface SandboxParsedMessage {
|
|
|
178
178
|
senderId?: string;
|
|
179
179
|
senderName?: string;
|
|
180
180
|
senderRole?: SandboxSenderRole;
|
|
181
|
+
/**
|
|
182
|
+
* ADR 0060 §5.4: speak as the chat identity linked to the authenticated Console user instead of
|
|
183
|
+
* `senderId`. The server decides; without such an identity the message is simulated.
|
|
184
|
+
*/
|
|
185
|
+
asMe?: boolean;
|
|
181
186
|
}
|
|
182
187
|
|
|
183
188
|
export type SandboxInboundEnvelope = SandboxParsedMessage;
|
|
@@ -193,6 +198,7 @@ interface SandboxWirePayload {
|
|
|
193
198
|
senderId?: unknown;
|
|
194
199
|
senderName?: unknown;
|
|
195
200
|
senderRole?: unknown;
|
|
201
|
+
asMe?: unknown;
|
|
196
202
|
}
|
|
197
203
|
|
|
198
204
|
function readSandboxWirePayload(raw: string): SandboxWirePayload & { op?: unknown; conversation?: unknown } {
|
|
@@ -361,9 +367,21 @@ function normalizeSandboxWsPayload(payload: SandboxWirePayload, raw: string, sel
|
|
|
361
367
|
...(senderId ? { senderId } : {}),
|
|
362
368
|
...(senderName ? { senderName } : {}),
|
|
363
369
|
...(senderRole ? { senderRole } : {}),
|
|
370
|
+
...(payload.asMe === true ? { asMe: true } : {}),
|
|
364
371
|
};
|
|
365
372
|
}
|
|
366
373
|
|
|
374
|
+
/**
|
|
375
|
+
* ADR 0060 §5.4: a client-chosen sender id becomes a reserved simulated id (`~sim:<id>`). Ids
|
|
376
|
+
* starting with `~` are never chat identities (`isChatIdentity`), so a simulated sender holds no
|
|
377
|
+
* zhin role whatever id it types — including the id of an owner.
|
|
378
|
+
*/
|
|
379
|
+
export const SANDBOX_SIMULATED_PREFIX = '~sim:';
|
|
380
|
+
|
|
381
|
+
export function sandboxSimulatedSenderId(clientId: string): string {
|
|
382
|
+
return clientId.startsWith(SANDBOX_SIMULATED_PREFIX) ? clientId : `${SANDBOX_SIMULATED_PREFIX}${clientId}`;
|
|
383
|
+
}
|
|
384
|
+
|
|
367
385
|
/**
|
|
368
386
|
* 入站归一化 → ConversationRef。sandbox 无平台社交图谱:
|
|
369
387
|
* `private`/`group`/`channel` 直映射;`direct`(私聊)归 'private';
|