@zhin.js/adapter-sandbox 1.1.19 → 1.1.21

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.
Files changed (42) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +55 -7
  3. package/adapters/sandbox/index.js +3 -12
  4. package/adapters/sandbox/index.ts +2 -12
  5. package/lib/adapter.d.ts +17 -0
  6. package/lib/adapter.js +17 -0
  7. package/lib/client.d.ts +7 -14
  8. package/lib/client.js +12 -11
  9. package/lib/endpoint.d.ts +16 -13
  10. package/lib/endpoint.js +171 -138
  11. package/lib/index.d.ts +2 -1
  12. package/lib/index.js +2 -1
  13. package/lib/protocol.d.ts +22 -1
  14. package/lib/protocol.js +34 -4
  15. package/package.json +18 -18
  16. package/pages/index/ConversationRecoveryPanel.js +131 -0
  17. package/pages/index/ConversationRecoveryPanel.tsx +134 -0
  18. package/pages/index/SandboxChat.js +319 -111
  19. package/pages/index/SandboxChat.tsx +356 -126
  20. package/pages/index/agentTrace.js +21 -10
  21. package/pages/index/agentTrace.ts +24 -10
  22. package/pages/index/conversationRecovery.js +40 -0
  23. package/pages/index/conversationRecovery.ts +68 -0
  24. package/pages/index/index.js +5 -5
  25. package/pages/index/index.tsx +5 -5
  26. package/pages/index/messages.js +24 -6
  27. package/pages/index/messages.ts +24 -6
  28. package/pages/index/playgroundState.js +51 -1
  29. package/pages/index/playgroundState.ts +61 -1
  30. package/pages/index/sandboxTransport.js +25 -0
  31. package/pages/index/sandboxTransport.ts +35 -0
  32. package/pages/index/useSandboxHistory.js +161 -0
  33. package/pages/index/useSandboxHistory.ts +164 -0
  34. package/pages/index/workspaceDirectory.js +49 -0
  35. package/pages/index/workspaceDirectory.ts +74 -0
  36. package/pages/index/workspaceDirectoryState.js +120 -0
  37. package/pages/index/workspaceDirectoryState.ts +124 -0
  38. package/src/adapter.ts +22 -0
  39. package/src/client.ts +16 -18
  40. package/src/endpoint.ts +179 -140
  41. package/src/index.ts +1 -1
  42. package/src/protocol.ts +59 -13
package/lib/endpoint.js CHANGED
@@ -1,12 +1,13 @@
1
1
  import { createMessages, resolveLocale } from 'zhin.js/i18n';
2
- import { Endpoint } from 'zhin.js/adapter';
2
+ import { createEndpointSpecification, endpointSpec } from 'zhin.js/adapter';
3
3
  /**
4
4
  * SandboxWsEndpoint — WebSocket lifecycle and OutboundMessageService bridge for /sandbox.
5
5
  */
6
6
  import { randomUUID } from 'node:crypto';
7
7
  import { execFile } from 'node:child_process';
8
8
  import { formatCompact, getAdapterLogger } from '@zhin.js/logger';
9
- import { bindSandboxWsSocket, formatSandboxOutbound, parseSandboxWsPayload, sandboxInboundConversation, whenWsOpen, } from './protocol.js';
9
+ import { EndpointDeliveryError } from '@zhin.js/im-contract';
10
+ import { bindSandboxWsSocket, formatSandboxOutbound, parseSandboxWsFrame, sandboxInboundConversation, whenWsOpen, } from './protocol.js';
10
11
  import { SandboxClient } from './client.js';
11
12
  const claimedWsPaths = new WeakMap();
12
13
  function claimSandboxWsPath(http, name) {
@@ -69,22 +70,21 @@ const messages = createMessages({
69
70
  readOnly: { 'zh-CN': '当前连接是只读演示权限,不能运行 Agent 任务。', en: 'This connection is a read-only demo and cannot run Agent tasks.' },
70
71
  connected: { 'zh-CN': '已连接 Sandbox「{target}」', en: 'Connected to Sandbox “{target}”' },
71
72
  protocol: { 'zh-CN': '与 Node Host 控制台沙盒协议一致({path})', en: 'Using the Node Host Console sandbox protocol ({path})' },
72
- profile: { 'zh-CN': '「试聊一下」会话已启用持久化运行配置。', en: 'The “Try a chat” session uses a persistent runtime profile.' },
73
+ profile: { 'zh-CN': '会话已启用持久化运行配置。', en: 'The conversation uses a persistent runtime profile.' },
74
+ invalidFrame: { 'zh-CN': '会话订阅或消息格式无效。', en: 'The conversation subscription or message format is invalid.' },
73
75
  });
74
76
  /**
75
77
  * Sandbox 是本地开发/测试面,无平台社交图谱(好友/群/频道),
76
78
  * 不适用 EndpointManagement 语义端口;本 endpoint 不暴露该端口。
77
79
  */
78
- export class SandboxWsEndpoint extends Endpoint {
79
- client;
80
+ export class SandboxWsEndpoint extends SandboxClient {
81
+ [endpointSpec];
80
82
  #logger;
81
83
  #options;
82
84
  #locale;
83
- #connections = new Map();
84
85
  #readiness = createSandboxReadinessGate(probeShellIsolation);
85
86
  #wsHandleRelease;
86
87
  #wsPathRelease;
87
- #wsPath = '/sandbox';
88
88
  #open = false;
89
89
  #started = false;
90
90
  constructor(options) {
@@ -92,29 +92,27 @@ export class SandboxWsEndpoint extends Endpoint {
92
92
  this.#logger = getAdapterLogger('sandbox', options.defaults.id);
93
93
  this.#options = options;
94
94
  this.#locale = resolveLocale(options.locale);
95
- this.client = new SandboxClient(() => this.#wsPath, () => [...this.#connections.values()].map((connection) => ({
96
- target: connection.target,
97
- owner: connection.owner,
98
- socket: connection.socket,
99
- placeholder: connection.placeholder === true,
100
- })));
101
- }
102
- /** Live endpoint id (config `id`) — Console endpoint.list/resolve uses it. */
103
- get name() {
104
- return this.#options.defaults.id;
95
+ const readTransportState = () => this.#transportState;
96
+ this[endpointSpec] = createEndpointSpecification(this, {
97
+ name: options.defaults.id,
98
+ start: () => this.#start(), open: () => this.#openEndpoint(),
99
+ close: () => this.#close(), stop: () => this.#stop(),
100
+ send: request => this.#send(request),
101
+ get transportState() { return readTransportState(); },
102
+ });
105
103
  }
106
104
  /** The Sandbox transport is the mounted local listener, not a remote account. */
107
- get transportState() {
105
+ get #transportState() {
108
106
  return this.#started && this.#wsHandleRelease ? 'open' : 'idle';
109
107
  }
110
- start() {
108
+ #start() {
111
109
  if (this.#started)
112
110
  return;
113
111
  this.#started = true;
114
112
  // 多 endpoint 同 path 会被全部回调(入站重复、出站互窜),按名隔离。
115
113
  const claim = claimSandboxWsPath(this.#options.http, this.#options.defaults.id);
116
114
  this.#wsPathRelease = claim.release;
117
- this.#wsPath = claim.path;
115
+ this.wsPathValue = claim.path;
118
116
  const handle = this.#options.http.ws(claim.path);
119
117
  this.#wsHandleRelease = handle.onConnection((connection) => {
120
118
  this.#acceptConnection(connection);
@@ -124,23 +122,23 @@ export class SandboxWsEndpoint extends Endpoint {
124
122
  }
125
123
  this.#logger.info(`ws mounted ${claim.path}`);
126
124
  }
127
- open() {
125
+ #openEndpoint() {
128
126
  this.#open = true;
129
127
  // Synthetic account: Sandbox has no platform login, so its Bot identity is the
130
128
  // configured bot id. Per-connection random names are not Bot accounts.
131
- this.reportSelfUserId(this.#options.defaults.id);
129
+ this[endpointSpec].reportSelfUserId(this.#options.defaults.id);
132
130
  }
133
- close() {
131
+ #close() {
134
132
  this.#open = false;
135
133
  }
136
- stop() {
134
+ #stop() {
137
135
  this.#open = false;
138
- this.reportSelfUserId(undefined);
136
+ this[endpointSpec].reportSelfUserId(undefined);
139
137
  this.#wsHandleRelease?.();
140
138
  this.#wsHandleRelease = undefined;
141
139
  this.#wsPathRelease?.();
142
140
  this.#wsPathRelease = undefined;
143
- for (const connection of this.#connections.values()) {
141
+ for (const connection of this.connectionRecords.values()) {
144
142
  connection.release();
145
143
  if (!connection.placeholder) {
146
144
  try {
@@ -151,53 +149,59 @@ export class SandboxWsEndpoint extends Endpoint {
151
149
  }
152
150
  }
153
151
  }
154
- this.#connections.clear();
152
+ this.connectionRecords.clear();
155
153
  this.#started = false;
156
154
  this.#logger.debug(formatCompact({ op: 'sandbox_stopped' }));
157
155
  }
158
- send({ conversation, payload }) {
156
+ #send({ conversation, payload }) {
159
157
  if (!this.#open)
160
158
  throw new Error('Sandbox Endpoint is not open');
161
- // Reply targets this endpoint's own live socket (fixed bot name, or the
162
- // only live random-name connection); conversation carries kind/id stamp.
163
- const connection = this.#connections.get(this.#options.defaults.id)
164
- ?? this.#findLiveConnection();
165
- if (!connection) {
166
- this.#logger.debug(formatCompact({
167
- op: 'sandbox_send_miss',
168
- target: `${conversation.kind}:${conversation.id}`,
169
- }));
170
- throw new Error('Sandbox Endpoint has no live connection');
159
+ const scene = { type: conversation.kind, id: conversation.id };
160
+ const subscribers = this.#subscribers(scene);
161
+ if (!subscribers.length) {
162
+ throw new EndpointDeliveryError('sandbox_delivery_unavailable', 'Sandbox Endpoint has no live connection', 'not_sent');
171
163
  }
172
- if (connection.placeholder) {
173
- this.#logger.debug(formatCompact({
174
- op: 'sandbox_send_placeholder',
175
- target: `${conversation.kind}:${conversation.id}`,
176
- }));
177
- throw new Error('Sandbox Endpoint has no live connection');
178
- }
179
- // Console UI filters by type+id; stamp the conversation onto outbound wire.
180
- connection.socket.send(formatSandboxOutbound(payload, {
181
- type: conversation.kind,
182
- id: conversation.id,
164
+ // Use the same identity for live messages and the canonical delivery receipt.
165
+ const explicitMessageId = payload && typeof payload === 'object' && !Array.isArray(payload)
166
+ ? payload.messageId
167
+ : undefined;
168
+ const messageId = typeof explicitMessageId === 'string' && explicitMessageId.trim()
169
+ ? explicitMessageId
170
+ : randomUUID();
171
+ const wire = formatSandboxOutbound(payload, {
172
+ ...scene,
183
173
  bot: this.#options.defaults.id,
184
- endpoint: connection.target,
185
- }));
186
- this.#logger.debug(formatCompact({
187
- op: 'sandbox_send',
188
- target: connection.target,
189
- channelType: conversation.kind,
190
- channelId: conversation.id,
191
- }));
192
- return randomUUID();
174
+ endpoint: this.#options.defaults.id,
175
+ messageId,
176
+ conversation: scene,
177
+ });
178
+ if (this.#broadcast(subscribers, wire) === 0) {
179
+ throw new EndpointDeliveryError('sandbox_delivery_unavailable', 'Sandbox Endpoint has no live connection', 'unknown');
180
+ }
181
+ return messageId;
193
182
  }
194
- /** Prefer a real (non-placeholder) socket when reply target key is wrong/stale. */
195
- #findLiveConnection() {
196
- for (const connection of this.#connections.values()) {
197
- if (!connection.placeholder)
198
- return connection;
183
+ #subscribers(scene, echo = false) {
184
+ return [...this.connectionRecords.values()].filter(connection => !connection.placeholder && connection.canExecute
185
+ && (!echo || connection.scoped)
186
+ && connection.conversation.type === scene.type && connection.conversation.id === scene.id
187
+ && (connection.socket.readyState === undefined || connection.socket.readyState === 1));
188
+ }
189
+ /** A failing page must not prevent delivery to another subscriber or admit another turn. */
190
+ #broadcast(subscribers, wire) {
191
+ let delivered = 0;
192
+ for (const connection of subscribers) {
193
+ try {
194
+ connection.socket.send(wire);
195
+ delivered += 1;
196
+ }
197
+ catch (error) {
198
+ this.#logger.warn(formatCompact({
199
+ op: 'sandbox_send_failed', connectionId: connection.connectionId,
200
+ error: error instanceof Error ? error.message : String(error),
201
+ }));
202
+ }
199
203
  }
200
- return undefined;
204
+ return delivered;
201
205
  }
202
206
  #acceptConnection(connection) {
203
207
  const target = this.#options.defaults.randomNamePerConnection
@@ -206,82 +210,104 @@ export class SandboxWsEndpoint extends Endpoint {
206
210
  const owner = this.#options.defaults.owner;
207
211
  const canExecute = connection.authScope === 'full';
208
212
  const socket = connection.socket;
209
- // Fixed-name mode reuses `target`; dropping the prior entry without
210
- // closing its socket leaves a zombie browser tab that still looks
211
- // connected but never receives outbound traffic.
212
- const previous = this.#connections.get(target);
213
- if (previous) {
214
- previous.release();
215
- if (!previous.placeholder) {
216
- try {
217
- previous.socket.close(4000, 'replaced by new sandbox client');
218
- }
219
- catch {
220
- /* already closed */
221
- }
222
- }
223
- this.#connections.delete(target);
224
- }
213
+ const connectionId = randomUUID();
214
+ const subscription = {
215
+ connectionId, target, owner, socket, canExecute, scoped: false,
216
+ conversation: { type: 'private', id: owner },
217
+ release: () => release(),
218
+ };
219
+ const placeholder = this.connectionRecords.get(this.#options.defaults.id);
220
+ if (placeholder?.placeholder)
221
+ this.connectionRecords.delete(this.#options.defaults.id);
225
222
  const release = bindSandboxWsSocket(socket, {
226
223
  onMessage: (raw) => {
227
- void this.#emitPlatformEvent('message', raw);
228
- if (!canExecute) {
229
- socket.send(JSON.stringify({
230
- type: 'error',
231
- id: owner,
232
- endpoint: target,
233
- content: [{ type: 'text', data: { text: messages(this.#locale, 'readOnly') } }],
234
- timestamp: Date.now(),
235
- }));
236
- return;
237
- }
238
- const parsed = parseSandboxWsPayload(raw);
239
- const sceneId = parsed.id || owner;
240
- const conversation = sandboxInboundConversation(String(this.#options.id), {
241
- type: parsed.type,
242
- id: sceneId,
243
- });
244
- this.#logger.debug(formatCompact({
245
- op: 'sandbox_recv',
246
- target,
247
- sender: owner,
248
- channelType: parsed.type,
249
- channelId: sceneId,
250
- text: parsed.text.slice(0, 80),
251
- }));
252
- // Don't gate on #open — inbound must always reach the gateway so
253
- // Command/AI dispatch and outbound replies work.
254
- void this.emit('message.receive', {
255
- conversation,
256
- ...(parsed.messageId ? { message: { conversation, id: parsed.messageId } } : {}),
257
- content: parsed.text,
258
- sender: { id: owner },
259
- endpointId: target,
260
- metadata: Object.freeze({
261
- type: parsed.type,
262
- channelType: parsed.type,
263
- channelId: parsed.id || owner,
264
- elements: parsed.content,
265
- timestamp: parsed.timestamp,
266
- ...(parsed.action ? { action: parsed.action } : {}),
267
- ...(parsed.agentRun ? { sandboxAgentRun: parsed.agentRun } : {}),
268
- }),
269
- }).catch((err) => {
270
- this.#logger.warn(formatCompact({
271
- op: 'sandbox_gateway_receive_failed',
224
+ void this[endpointSpec].events.run(() => {
225
+ if (!canExecute) {
226
+ socket.send(JSON.stringify({
227
+ type: 'error',
228
+ id: owner,
229
+ endpoint: target,
230
+ content: [{ type: 'text', data: { text: messages(this.#locale, 'readOnly') } }],
231
+ timestamp: Date.now(),
232
+ }));
233
+ return;
234
+ }
235
+ const frame = parseSandboxWsFrame(raw);
236
+ if (frame.kind === 'invalid') {
237
+ socket.send(JSON.stringify({
238
+ type: 'error', endpoint: target, connectionId,
239
+ content: [{ type: 'text', data: { text: messages(this.#locale, 'invalidFrame') } }],
240
+ timestamp: Date.now(),
241
+ }));
242
+ return;
243
+ }
244
+ if (frame.kind === 'subscribe') {
245
+ subscription.conversation = frame.conversation;
246
+ subscription.scoped = true;
247
+ socket.send(JSON.stringify({
248
+ type: 'subscribed', id: frame.conversation.id, conversation: frame.conversation,
249
+ endpoint: target, connectionId, timestamp: Date.now(),
250
+ }));
251
+ return;
252
+ }
253
+ const parsed = frame.message;
254
+ void this.#emitPlatformEvent('message', raw);
255
+ const sceneId = parsed.id || owner;
256
+ const conversation = { ...sandboxInboundConversation(String(this.#options.id), {
257
+ type: parsed.type,
258
+ id: sceneId,
259
+ }), endpoint: this[endpointSpec].identity };
260
+ this.#logger.debug(formatCompact({
261
+ op: 'sandbox_recv',
272
262
  target,
273
- error: err instanceof Error ? err.message : String(err),
263
+ sender: owner,
264
+ channelType: parsed.type,
265
+ channelId: sceneId,
266
+ text: parsed.text.slice(0, 80),
267
+ }));
268
+ const scene = { type: conversation.kind, id: sceneId };
269
+ subscription.conversation = scene;
270
+ const messageId = parsed.messageId ?? randomUUID();
271
+ this.#broadcast(this.#subscribers(scene, true), JSON.stringify({
272
+ ...scene, conversation: scene, direction: 'inbound', senderId: owner,
273
+ messageId, endpoint: this.#options.defaults.id, content: parsed.content, timestamp: parsed.timestamp,
274
274
  }));
275
+ void this[endpointSpec].events.message({
276
+ event: raw,
277
+ ...(typeof parsed.timestamp === 'number' ? { platformSentAt: parsed.timestamp } : {}),
278
+ conversation,
279
+ message: { conversation, id: messageId },
280
+ content: parsed.text,
281
+ segments: parsed.content,
282
+ sender: { id: owner },
283
+ endpointId: target,
284
+ metadata: Object.freeze({
285
+ type: parsed.type,
286
+ channelType: parsed.type,
287
+ channelId: parsed.id || owner,
288
+ elements: parsed.content,
289
+ timestamp: parsed.timestamp,
290
+ ...(parsed.action ? { action: parsed.action } : {}),
291
+ ...(parsed.agentRun ? { sandboxAgentRun: parsed.agentRun } : {}),
292
+ }),
293
+ }).catch((err) => {
294
+ this.#logger.warn(formatCompact({
295
+ op: 'sandbox_gateway_receive_failed',
296
+ target,
297
+ error: err instanceof Error ? err.message : String(err),
298
+ }));
299
+ });
300
+ }).catch((error) => {
301
+ this.#logger.debug(formatCompact({ op: 'sandbox_receive_failed', error: error instanceof Error ? error.message : String(error) }));
275
302
  });
276
303
  },
277
304
  onClose: () => {
278
305
  void this.#emitPlatformEvent('connection.close', { target, owner });
279
- // Only drop the map entry if we still own this socket — a replace
280
- // may have already swapped in a newer connection for the same target.
281
- const current = this.#connections.get(target);
282
- if (current && current.socket === socket) {
283
- this.#connections.delete(target);
284
- this.#logger.debug(formatCompact({ op: 'sandbox_ws_closed', target }));
306
+ const current = this.connectionRecords.get(connectionId);
307
+ if (current === subscription) {
308
+ current.release();
309
+ this.connectionRecords.delete(connectionId);
310
+ this.#logger.debug(formatCompact({ op: 'sandbox_ws_closed', target, connectionId }));
285
311
  }
286
312
  },
287
313
  onError: (err) => {
@@ -293,15 +319,18 @@ export class SandboxWsEndpoint extends Endpoint {
293
319
  }));
294
320
  },
295
321
  });
296
- this.#connections.set(target, { target, owner, socket, release });
322
+ this.connectionRecords.set(connectionId, subscription);
297
323
  void this.#emitPlatformEvent('connection.open', { target, owner, socket });
298
324
  this.#logger.debug(formatCompact({ op: 'sandbox_ws_connected', target, owner }));
299
325
  this.#readiness.afterProbe((shellIsolation) => {
300
- const current = this.#connections.get(target);
326
+ const current = this.connectionRecords.get(connectionId);
301
327
  if (!current || current.socket !== socket)
302
328
  return;
303
329
  const readyPayload = JSON.stringify({
304
330
  type: 'ready',
331
+ protocol: 'scoped-conversations-v1',
332
+ connectionId,
333
+ conversation: subscription.conversation,
305
334
  locale: this.#locale,
306
335
  id: owner,
307
336
  endpoint: target,
@@ -313,7 +342,7 @@ export class SandboxWsEndpoint extends Endpoint {
313
342
  data: {
314
343
  text: [
315
344
  messages(this.#locale, 'connected', { target }),
316
- messages(this.#locale, 'protocol', { path: this.#wsPath }),
345
+ messages(this.#locale, 'protocol', { path: this.wsPathValue }),
317
346
  messages(this.#locale, 'profile'),
318
347
  ].join('\n'),
319
348
  },
@@ -324,9 +353,13 @@ export class SandboxWsEndpoint extends Endpoint {
324
353
  });
325
354
  }
326
355
  #ensurePlaceholder(name, owner) {
327
- if (this.#connections.has(name))
356
+ if (this.connectionRecords.has(name))
328
357
  return;
329
- this.#connections.set(name, {
358
+ this.connectionRecords.set(name, {
359
+ connectionId: name,
360
+ canExecute: false,
361
+ scoped: false,
362
+ conversation: { type: 'private', id: owner },
330
363
  target: name,
331
364
  owner,
332
365
  socket: { send: () => undefined, close: () => undefined },
@@ -335,7 +368,7 @@ export class SandboxWsEndpoint extends Endpoint {
335
368
  });
336
369
  }
337
370
  async #emitPlatformEvent(name, event) {
338
- await this.emitPlatform(name, event).catch((error) => {
371
+ await this[endpointSpec].events.platform(name, event).catch((error) => {
339
372
  this.#logger.warn(formatCompact({
340
373
  op: 'sandbox_platform_event_failed',
341
374
  event: name,
package/lib/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export { bindSandboxWsSocket, formatSandboxOutbound, normalizeSandboxOutboundSegments, parseSandboxWsPayload, resolveSandboxEndpoint, sandboxInboundConversation, whenWsOpen, type MessageElement, type MessageType, type ResolvedSandboxBot, type SandboxEndpointConfig, type SandboxWsSocket, } from './protocol.js';
2
- export { SandboxClient, sandboxClient, type SandboxClientEventMap, type SandboxClientConnection, } from './client.js';
2
+ export { SandboxClient, type SandboxClientEventMap, type SandboxClientConnection, } from './client.js';
3
3
  export { SandboxWsEndpoint, type SandboxEndpointOptions, } from './endpoint.js';
4
+ export { SandboxAdapter } from './adapter.js';
package/lib/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export { bindSandboxWsSocket, formatSandboxOutbound, normalizeSandboxOutboundSegments, parseSandboxWsPayload, resolveSandboxEndpoint, sandboxInboundConversation, whenWsOpen, } from './protocol.js';
2
- export { SandboxClient, sandboxClient, } from './client.js';
2
+ export { SandboxClient, } from './client.js';
3
3
  export { SandboxWsEndpoint, } from './endpoint.js';
4
+ export { SandboxAdapter } from './adapter.js';
package/lib/protocol.d.ts CHANGED
@@ -7,6 +7,7 @@ export interface MessageElement {
7
7
  readonly data?: Record<string, unknown>;
8
8
  }
9
9
  export interface SandboxWsSocket {
10
+ readonly readyState?: number;
10
11
  send(data: string): void;
11
12
  close(code?: number, reason?: string): void;
12
13
  on?(event: 'message' | 'close' | 'error', listener: (...args: unknown[]) => void): void;
@@ -31,7 +32,11 @@ export declare function bindSandboxWsSocket(ws: SandboxWsSocket, handlers: {
31
32
  onClose: () => void;
32
33
  onError?: (err: unknown) => void;
33
34
  }): () => void;
34
- export declare function parseSandboxWsPayload(raw: string): {
35
+ export interface SandboxConversation {
36
+ readonly type: 'private' | 'group' | 'channel';
37
+ readonly id: string;
38
+ }
39
+ export interface SandboxParsedMessage {
35
40
  type: MessageType;
36
41
  id: string;
37
42
  messageId?: string;
@@ -43,7 +48,19 @@ export declare function parseSandboxWsPayload(raw: string): {
43
48
  payload: string;
44
49
  };
45
50
  agentRun?: SandboxAgentRunConfig;
51
+ }
52
+ export type SandboxWsFrame = {
53
+ readonly kind: 'subscribe';
54
+ readonly conversation: SandboxConversation;
55
+ } | {
56
+ readonly kind: 'message';
57
+ readonly message: SandboxParsedMessage;
58
+ } | {
59
+ readonly kind: 'invalid';
46
60
  };
61
+ /** Control frames never fall through into chat or platform message hooks. */
62
+ export declare function parseSandboxWsFrame(raw: string): SandboxWsFrame;
63
+ export declare function parseSandboxWsPayload(raw: string): SandboxParsedMessage;
47
64
  /**
48
65
  * 入站归一化 → ConversationRef。sandbox 无平台社交图谱:
49
66
  * `private`/`group`/`channel` 直映射;`direct`(私聊)归 'private';
@@ -59,6 +76,10 @@ export type SandboxOutboundChannel = {
59
76
  readonly bot?: string;
60
77
  readonly endpoint?: string;
61
78
  readonly messageId?: string;
79
+ readonly conversation?: {
80
+ readonly type: string;
81
+ readonly id: string;
82
+ };
62
83
  };
63
84
  /** 出站段数组归一:媒体段走 MediaRef-only 归一,其余段原样透传。 */
64
85
  export declare function normalizeSandboxOutboundSegments(segments: readonly unknown[]): unknown[];
package/lib/protocol.js CHANGED
@@ -63,14 +63,38 @@ export function bindSandboxWsSocket(ws, handlers) {
63
63
  ws.removeEventListener('error', onError);
64
64
  };
65
65
  }
66
- export function parseSandboxWsPayload(raw) {
67
- let payload;
66
+ function readSandboxWirePayload(raw) {
68
67
  try {
69
- payload = JSON.parse(raw);
68
+ const payload = JSON.parse(raw);
69
+ return payload && typeof payload === 'object' && !Array.isArray(payload)
70
+ ? payload
71
+ : { text: raw };
70
72
  }
71
73
  catch {
72
- payload = { text: raw };
74
+ return { text: raw };
75
+ }
76
+ }
77
+ /** Control frames never fall through into chat or platform message hooks. */
78
+ export function parseSandboxWsFrame(raw) {
79
+ const payload = readSandboxWirePayload(raw);
80
+ if ('op' in payload) {
81
+ const conversation = payload.conversation;
82
+ if (payload.op !== 'subscribe' || !conversation || typeof conversation !== 'object'
83
+ || (conversation.type !== 'private' && conversation.type !== 'group' && conversation.type !== 'channel')
84
+ || typeof conversation.id !== 'string' || !conversation.id.trim())
85
+ return { kind: 'invalid' };
86
+ return { kind: 'subscribe', conversation: { type: conversation.type, id: conversation.id } };
73
87
  }
88
+ const message = normalizeSandboxWsPayload(payload, raw);
89
+ if (!['private', 'direct', 'group', 'channel', 'guild'].includes(message.type)
90
+ || typeof message.id !== 'string')
91
+ return { kind: 'invalid' };
92
+ return { kind: 'message', message };
93
+ }
94
+ export function parseSandboxWsPayload(raw) {
95
+ return normalizeSandboxWsPayload(readSandboxWirePayload(raw), raw);
96
+ }
97
+ function normalizeSandboxWsPayload(payload, raw) {
74
98
  const type = payload.type ?? 'private';
75
99
  const id = payload.id ?? 'sandbox-user';
76
100
  const content = typeof payload.content === 'string'
@@ -243,6 +267,8 @@ export function formatSandboxOutbound(payload, channel = {}) {
243
267
  stamp.endpoint = channel.endpoint;
244
268
  if (channel.messageId)
245
269
  stamp.messageId = channel.messageId;
270
+ if (channel.conversation)
271
+ stamp.conversation = channel.conversation;
246
272
  if (typeof payload === 'string') {
247
273
  return JSON.stringify({
248
274
  ...stamp,
@@ -274,6 +300,10 @@ export function formatSandboxOutbound(payload, channel = {}) {
274
300
  : {}),
275
301
  type: envelope.type ?? stamp.type,
276
302
  id: envelope.id ?? stamp.id,
303
+ conversation: stamp.conversation ?? envelope.conversation,
304
+ messageId: typeof envelope.messageId === 'string' && envelope.messageId.trim()
305
+ ? envelope.messageId
306
+ : stamp.messageId,
277
307
  timestamp: typeof envelope.timestamp === 'number' ? envelope.timestamp : Date.now(),
278
308
  });
279
309
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhin.js/adapter-sandbox",
3
- "version": "1.1.19",
3
+ "version": "1.1.21",
4
4
  "description": "Zhin.js Sandbox adapter for Plugin Runtime (WebSocket /sandbox)",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -47,16 +47,16 @@
47
47
  "dependencies": {
48
48
  "lucide-react": "^0.525.0",
49
49
  "react": "^19.2.8",
50
- "@zhin.js/adapter": "1.1.24",
51
- "@zhin.js/client": "1.1.20",
50
+ "@zhin.js/adapter": "1.1.26",
51
+ "@zhin.js/client": "1.1.22",
52
52
  "@zhin.js/console-contract": "1.1.3",
53
- "@zhin.js/core": "1.1.52",
54
- "@zhin.js/feature-kit": "1.1.9",
55
- "@zhin.js/host-http": "1.1.11",
56
- "@zhin.js/im-contract": "1.1.8",
53
+ "@zhin.js/core": "1.1.54",
54
+ "@zhin.js/feature-kit": "1.1.10",
55
+ "@zhin.js/host-http": "1.1.12",
56
+ "@zhin.js/im-contract": "1.1.9",
57
57
  "@zhin.js/logger": "1.1.2",
58
- "@zhin.js/page": "1.1.10",
59
- "@zhin.js/skill": "1.1.10"
58
+ "@zhin.js/page": "1.1.11",
59
+ "@zhin.js/skill": "1.1.11"
60
60
  },
61
61
  "devDependencies": {
62
62
  "@types/react": "^19.2.18",
@@ -64,18 +64,18 @@
64
64
  "typescript": "^6.0.3",
65
65
  "vitest": "^4.1.10",
66
66
  "ws": "^8.21.1",
67
- "@zhin.js/pagemanager": "1.1.16",
68
- "@zhin.js/runtime": "1.1.15",
69
- "zhin.js": "1.1.17"
67
+ "@zhin.js/pagemanager": "1.1.18",
68
+ "@zhin.js/runtime": "1.1.16",
69
+ "zhin.js": "1.1.19"
70
70
  },
71
71
  "peerDependencies": {
72
72
  "react": "^19.0.0",
73
- "@zhin.js/adapter": "^1.1.24",
73
+ "@zhin.js/adapter": "^1.1.26",
74
74
  "@zhin.js/console-contract": "^1.1.3",
75
- "@zhin.js/core": "^1.1.52",
76
- "@zhin.js/host-http": "^1.1.11",
77
- "@zhin.js/page": "^1.1.10",
78
- "zhin.js": "^1.1.17"
75
+ "@zhin.js/core": "^1.1.54",
76
+ "@zhin.js/host-http": "^1.1.12",
77
+ "@zhin.js/page": "^1.1.11",
78
+ "zhin.js": "^1.1.19"
79
79
  },
80
80
  "peerDependenciesMeta": {
81
81
  "react": {
@@ -98,7 +98,7 @@
98
98
  "features": [
99
99
  {
100
100
  "package": "@zhin.js/adapter",
101
- "api": "^1.0.0"
101
+ "api": "^2.0.0"
102
102
  },
103
103
  {
104
104
  "package": "@zhin.js/page",