@zhin.js/adapter-sandbox 1.1.20 → 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.
- package/CHANGELOG.md +57 -0
- package/README.md +55 -7
- package/adapters/sandbox/index.js +3 -12
- package/adapters/sandbox/index.ts +2 -12
- package/lib/adapter.d.ts +17 -0
- package/lib/adapter.js +17 -0
- package/lib/client.d.ts +7 -14
- package/lib/client.js +12 -11
- package/lib/endpoint.d.ts +16 -13
- package/lib/endpoint.js +171 -138
- package/lib/index.d.ts +2 -1
- package/lib/index.js +2 -1
- package/lib/protocol.d.ts +22 -1
- package/lib/protocol.js +34 -4
- package/package.json +17 -17
- package/pages/index/ConversationRecoveryPanel.js +131 -0
- package/pages/index/ConversationRecoveryPanel.tsx +134 -0
- package/pages/index/SandboxChat.js +319 -111
- package/pages/index/SandboxChat.tsx +356 -126
- package/pages/index/agentTrace.js +21 -10
- package/pages/index/agentTrace.ts +24 -10
- package/pages/index/conversationRecovery.js +40 -0
- package/pages/index/conversationRecovery.ts +68 -0
- package/pages/index/index.js +5 -5
- package/pages/index/index.tsx +5 -5
- package/pages/index/messages.js +24 -6
- package/pages/index/messages.ts +24 -6
- package/pages/index/playgroundState.js +51 -1
- package/pages/index/playgroundState.ts +61 -1
- package/pages/index/sandboxTransport.js +25 -0
- package/pages/index/sandboxTransport.ts +35 -0
- package/pages/index/useSandboxHistory.js +161 -0
- package/pages/index/useSandboxHistory.ts +164 -0
- package/pages/index/workspaceDirectory.js +49 -0
- package/pages/index/workspaceDirectory.ts +74 -0
- package/pages/index/workspaceDirectoryState.js +120 -0
- package/pages/index/workspaceDirectoryState.ts +124 -0
- package/src/adapter.ts +22 -0
- package/src/client.ts +16 -18
- package/src/endpoint.ts +179 -140
- package/src/index.ts +1 -1
- package/src/protocol.ts +59 -13
package/src/endpoint.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createMessages, resolveLocale, type Locale } from 'zhin.js/i18n';
|
|
2
|
-
import { Endpoint, type EndpointSendRequest } from 'zhin.js/adapter';
|
|
2
|
+
import { createEndpointSpecification, endpointSpec, type Endpoint, type EndpointSpecification, type EndpointSendRequest } from 'zhin.js/adapter';
|
|
3
3
|
/**
|
|
4
4
|
* SandboxWsEndpoint — WebSocket lifecycle and OutboundMessageService bridge for /sandbox.
|
|
5
5
|
*/
|
|
@@ -8,16 +8,18 @@ import { execFile } from 'node:child_process';
|
|
|
8
8
|
import type { HttpHost, WsConnection } from '@zhin.js/host-http';
|
|
9
9
|
import { formatCompact, getAdapterLogger } from '@zhin.js/logger';
|
|
10
10
|
import type { CapabilityId } from 'zhin.js';
|
|
11
|
+
import { EndpointDeliveryError } from '@zhin.js/im-contract';
|
|
11
12
|
import {
|
|
12
13
|
bindSandboxWsSocket,
|
|
13
14
|
formatSandboxOutbound,
|
|
14
|
-
|
|
15
|
+
parseSandboxWsFrame,
|
|
15
16
|
sandboxInboundConversation,
|
|
16
17
|
whenWsOpen,
|
|
17
18
|
type ResolvedSandboxBot,
|
|
18
19
|
type SandboxWsSocket,
|
|
20
|
+
type SandboxConversation,
|
|
19
21
|
} from './protocol.js';
|
|
20
|
-
import { SandboxClient
|
|
22
|
+
import { SandboxClient } from './client.js';
|
|
21
23
|
|
|
22
24
|
/**
|
|
23
25
|
* 多 sandbox endpoint 共用同一个 HttpHost 时,同 path 的所有 WS listener
|
|
@@ -71,10 +73,14 @@ function claimSandboxWsPath(
|
|
|
71
73
|
}
|
|
72
74
|
|
|
73
75
|
interface SandboxConnection {
|
|
76
|
+
readonly connectionId: string;
|
|
74
77
|
readonly target: string;
|
|
75
78
|
readonly owner: string;
|
|
76
79
|
readonly socket: SandboxWsSocket;
|
|
77
80
|
readonly release: () => void;
|
|
81
|
+
readonly canExecute: boolean;
|
|
82
|
+
conversation: SandboxConversation;
|
|
83
|
+
scoped: boolean;
|
|
78
84
|
/** true = 占位连接(尚无真实 WS 客户端),send 命中时按 miss 处理。 */
|
|
79
85
|
readonly placeholder?: boolean;
|
|
80
86
|
}
|
|
@@ -116,7 +122,8 @@ const messages = createMessages({
|
|
|
116
122
|
readOnly: { 'zh-CN': '当前连接是只读演示权限,不能运行 Agent 任务。', en: 'This connection is a read-only demo and cannot run Agent tasks.' },
|
|
117
123
|
connected: { 'zh-CN': '已连接 Sandbox「{target}」', en: 'Connected to Sandbox “{target}”' },
|
|
118
124
|
protocol: { 'zh-CN': '与 Node Host 控制台沙盒协议一致({path})', en: 'Using the Node Host Console sandbox protocol ({path})' },
|
|
119
|
-
profile: { 'zh-CN': '
|
|
125
|
+
profile: { 'zh-CN': '会话已启用持久化运行配置。', en: 'The conversation uses a persistent runtime profile.' },
|
|
126
|
+
invalidFrame: { 'zh-CN': '会话订阅或消息格式无效。', en: 'The conversation subscription or message format is invalid.' },
|
|
120
127
|
});
|
|
121
128
|
|
|
122
129
|
export interface SandboxEndpointOptions {
|
|
@@ -131,17 +138,15 @@ export interface SandboxEndpointOptions {
|
|
|
131
138
|
* Sandbox 是本地开发/测试面,无平台社交图谱(好友/群/频道),
|
|
132
139
|
* 不适用 EndpointManagement 语义端口;本 endpoint 不暴露该端口。
|
|
133
140
|
*/
|
|
134
|
-
export class SandboxWsEndpoint extends
|
|
135
|
-
readonly
|
|
141
|
+
export class SandboxWsEndpoint extends SandboxClient<SandboxConnection> implements Endpoint {
|
|
142
|
+
readonly [endpointSpec]: EndpointSpecification;
|
|
136
143
|
readonly #logger!: ReturnType<typeof getAdapterLogger>;
|
|
137
144
|
|
|
138
145
|
readonly #options: SandboxEndpointOptions;
|
|
139
146
|
readonly #locale: Locale;
|
|
140
|
-
readonly #connections = new Map<string, SandboxConnection>();
|
|
141
147
|
readonly #readiness = createSandboxReadinessGate(probeShellIsolation);
|
|
142
148
|
#wsHandleRelease?: () => void;
|
|
143
149
|
#wsPathRelease?: () => void;
|
|
144
|
-
#wsPath = '/sandbox';
|
|
145
150
|
#open = false;
|
|
146
151
|
#started = false;
|
|
147
152
|
|
|
@@ -150,34 +155,28 @@ export class SandboxWsEndpoint extends Endpoint<SandboxClient> {
|
|
|
150
155
|
this.#logger = getAdapterLogger('sandbox', options.defaults.id);
|
|
151
156
|
this.#options = options;
|
|
152
157
|
this.#locale = resolveLocale(options.locale);
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
);
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
/** Live endpoint id (config `id`) — Console endpoint.list/resolve uses it. */
|
|
165
|
-
get name(): string {
|
|
166
|
-
return this.#options.defaults.id;
|
|
158
|
+
const readTransportState = () => this.#transportState;
|
|
159
|
+
this[endpointSpec] = createEndpointSpecification(this, {
|
|
160
|
+
name: options.defaults.id,
|
|
161
|
+
start: () => this.#start(), open: () => this.#openEndpoint(),
|
|
162
|
+
close: () => this.#close(), stop: () => this.#stop(),
|
|
163
|
+
send: request => this.#send(request),
|
|
164
|
+
get transportState() { return readTransportState(); },
|
|
165
|
+
});
|
|
167
166
|
}
|
|
168
167
|
|
|
169
168
|
/** The Sandbox transport is the mounted local listener, not a remote account. */
|
|
170
|
-
get transportState(): 'open' | 'idle' {
|
|
169
|
+
get #transportState(): 'open' | 'idle' {
|
|
171
170
|
return this.#started && this.#wsHandleRelease ? 'open' : 'idle';
|
|
172
171
|
}
|
|
173
172
|
|
|
174
|
-
start(): void {
|
|
173
|
+
#start(): void {
|
|
175
174
|
if (this.#started) return;
|
|
176
175
|
this.#started = true;
|
|
177
176
|
// 多 endpoint 同 path 会被全部回调(入站重复、出站互窜),按名隔离。
|
|
178
177
|
const claim = claimSandboxWsPath(this.#options.http, this.#options.defaults.id);
|
|
179
178
|
this.#wsPathRelease = claim.release;
|
|
180
|
-
this
|
|
179
|
+
this.wsPathValue = claim.path;
|
|
181
180
|
const handle = this.#options.http.ws(claim.path);
|
|
182
181
|
this.#wsHandleRelease = handle.onConnection((connection) => {
|
|
183
182
|
this.#acceptConnection(connection);
|
|
@@ -188,25 +187,25 @@ export class SandboxWsEndpoint extends Endpoint<SandboxClient> {
|
|
|
188
187
|
this.#logger.info(`ws mounted ${claim.path}`);
|
|
189
188
|
}
|
|
190
189
|
|
|
191
|
-
|
|
190
|
+
#openEndpoint(): void {
|
|
192
191
|
this.#open = true;
|
|
193
192
|
// Synthetic account: Sandbox has no platform login, so its Bot identity is the
|
|
194
193
|
// configured bot id. Per-connection random names are not Bot accounts.
|
|
195
|
-
this.reportSelfUserId(this.#options.defaults.id);
|
|
194
|
+
this[endpointSpec].reportSelfUserId(this.#options.defaults.id);
|
|
196
195
|
}
|
|
197
196
|
|
|
198
|
-
close(): void {
|
|
197
|
+
#close(): void {
|
|
199
198
|
this.#open = false;
|
|
200
199
|
}
|
|
201
200
|
|
|
202
|
-
stop(): void {
|
|
201
|
+
#stop(): void {
|
|
203
202
|
this.#open = false;
|
|
204
|
-
this.reportSelfUserId(undefined);
|
|
203
|
+
this[endpointSpec].reportSelfUserId(undefined);
|
|
205
204
|
this.#wsHandleRelease?.();
|
|
206
205
|
this.#wsHandleRelease = undefined;
|
|
207
206
|
this.#wsPathRelease?.();
|
|
208
207
|
this.#wsPathRelease = undefined;
|
|
209
|
-
for (const connection of this
|
|
208
|
+
for (const connection of this.connectionRecords.values()) {
|
|
210
209
|
connection.release();
|
|
211
210
|
if (!connection.placeholder) {
|
|
212
211
|
try {
|
|
@@ -216,53 +215,64 @@ export class SandboxWsEndpoint extends Endpoint<SandboxClient> {
|
|
|
216
215
|
}
|
|
217
216
|
}
|
|
218
217
|
}
|
|
219
|
-
this
|
|
218
|
+
this.connectionRecords.clear();
|
|
220
219
|
this.#started = false;
|
|
221
220
|
this.#logger.debug(formatCompact({ op: 'sandbox_stopped' }));
|
|
222
221
|
}
|
|
223
222
|
|
|
224
|
-
send({ conversation, payload }: EndpointSendRequest): string {
|
|
223
|
+
#send({ conversation, payload }: EndpointSendRequest): string {
|
|
225
224
|
if (!this.#open) throw new Error('Sandbox Endpoint is not open');
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
if (!connection) {
|
|
231
|
-
this.#logger.debug(formatCompact({
|
|
232
|
-
op: 'sandbox_send_miss',
|
|
233
|
-
target: `${conversation.kind}:${conversation.id}`,
|
|
234
|
-
}));
|
|
235
|
-
throw new Error('Sandbox Endpoint has no live connection');
|
|
225
|
+
const scene = { type: conversation.kind, id: conversation.id };
|
|
226
|
+
const subscribers = this.#subscribers(scene);
|
|
227
|
+
if (!subscribers.length) {
|
|
228
|
+
throw new EndpointDeliveryError('sandbox_delivery_unavailable', 'Sandbox Endpoint has no live connection', 'not_sent');
|
|
236
229
|
}
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
type: conversation.kind,
|
|
247
|
-
id: conversation.id,
|
|
230
|
+
// Use the same identity for live messages and the canonical delivery receipt.
|
|
231
|
+
const explicitMessageId = payload && typeof payload === 'object' && !Array.isArray(payload)
|
|
232
|
+
? (payload as { readonly messageId?: unknown }).messageId
|
|
233
|
+
: undefined;
|
|
234
|
+
const messageId = typeof explicitMessageId === 'string' && explicitMessageId.trim()
|
|
235
|
+
? explicitMessageId
|
|
236
|
+
: randomUUID();
|
|
237
|
+
const wire = formatSandboxOutbound(payload, {
|
|
238
|
+
...scene,
|
|
248
239
|
bot: this.#options.defaults.id,
|
|
249
|
-
endpoint:
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
240
|
+
endpoint: this.#options.defaults.id,
|
|
241
|
+
messageId,
|
|
242
|
+
conversation: scene,
|
|
243
|
+
});
|
|
244
|
+
if (this.#broadcast(subscribers, wire) === 0) {
|
|
245
|
+
throw new EndpointDeliveryError(
|
|
246
|
+
'sandbox_delivery_unavailable',
|
|
247
|
+
'Sandbox Endpoint has no live connection',
|
|
248
|
+
'unknown',
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
return messageId;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
#subscribers(scene: { readonly type: string; readonly id: string }, echo = false): SandboxConnection[] {
|
|
255
|
+
return [...this.connectionRecords.values()].filter(connection => !connection.placeholder && connection.canExecute
|
|
256
|
+
&& (!echo || connection.scoped)
|
|
257
|
+
&& connection.conversation.type === scene.type && connection.conversation.id === scene.id
|
|
258
|
+
&& (connection.socket.readyState === undefined || connection.socket.readyState === 1));
|
|
258
259
|
}
|
|
259
260
|
|
|
260
|
-
/**
|
|
261
|
-
#
|
|
262
|
-
|
|
263
|
-
|
|
261
|
+
/** A failing page must not prevent delivery to another subscriber or admit another turn. */
|
|
262
|
+
#broadcast(subscribers: readonly SandboxConnection[], wire: string): number {
|
|
263
|
+
let delivered = 0;
|
|
264
|
+
for (const connection of subscribers) {
|
|
265
|
+
try {
|
|
266
|
+
connection.socket.send(wire);
|
|
267
|
+
delivered += 1;
|
|
268
|
+
} catch (error) {
|
|
269
|
+
this.#logger.warn(formatCompact({
|
|
270
|
+
op: 'sandbox_send_failed', connectionId: connection.connectionId,
|
|
271
|
+
error: error instanceof Error ? error.message : String(error),
|
|
272
|
+
}));
|
|
273
|
+
}
|
|
264
274
|
}
|
|
265
|
-
return
|
|
275
|
+
return delivered;
|
|
266
276
|
}
|
|
267
277
|
|
|
268
278
|
#acceptConnection(connection: WsConnection): void {
|
|
@@ -272,81 +282,103 @@ export class SandboxWsEndpoint extends Endpoint<SandboxClient> {
|
|
|
272
282
|
const owner = this.#options.defaults.owner;
|
|
273
283
|
const canExecute = connection.authScope === 'full';
|
|
274
284
|
const socket = connection.socket as SandboxWsSocket;
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
previous.socket.close(4000, 'replaced by new sandbox client');
|
|
284
|
-
} catch {
|
|
285
|
-
/* already closed */
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
this.#connections.delete(target);
|
|
289
|
-
}
|
|
285
|
+
const connectionId = randomUUID();
|
|
286
|
+
const subscription: SandboxConnection = {
|
|
287
|
+
connectionId, target, owner, socket, canExecute, scoped: false,
|
|
288
|
+
conversation: { type: 'private', id: owner },
|
|
289
|
+
release: () => release(),
|
|
290
|
+
};
|
|
291
|
+
const placeholder = this.connectionRecords.get(this.#options.defaults.id);
|
|
292
|
+
if (placeholder?.placeholder) this.connectionRecords.delete(this.#options.defaults.id);
|
|
290
293
|
const release = bindSandboxWsSocket(socket, {
|
|
291
294
|
onMessage: (raw) => {
|
|
292
|
-
void this
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
metadata: Object.freeze({
|
|
295
|
+
void this[endpointSpec].events.run(() => {
|
|
296
|
+
if (!canExecute) {
|
|
297
|
+
socket.send(JSON.stringify({
|
|
298
|
+
type: 'error',
|
|
299
|
+
id: owner,
|
|
300
|
+
endpoint: target,
|
|
301
|
+
content: [{ type: 'text', data: { text: messages(this.#locale, 'readOnly') } }],
|
|
302
|
+
timestamp: Date.now(),
|
|
303
|
+
}));
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
const frame = parseSandboxWsFrame(raw);
|
|
307
|
+
if (frame.kind === 'invalid') {
|
|
308
|
+
socket.send(JSON.stringify({
|
|
309
|
+
type: 'error', endpoint: target, connectionId,
|
|
310
|
+
content: [{ type: 'text', data: { text: messages(this.#locale, 'invalidFrame') } }],
|
|
311
|
+
timestamp: Date.now(),
|
|
312
|
+
}));
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
if (frame.kind === 'subscribe') {
|
|
316
|
+
subscription.conversation = frame.conversation;
|
|
317
|
+
subscription.scoped = true;
|
|
318
|
+
socket.send(JSON.stringify({
|
|
319
|
+
type: 'subscribed', id: frame.conversation.id, conversation: frame.conversation,
|
|
320
|
+
endpoint: target, connectionId, timestamp: Date.now(),
|
|
321
|
+
}));
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
const parsed = frame.message;
|
|
325
|
+
void this.#emitPlatformEvent('message', raw);
|
|
326
|
+
const sceneId = parsed.id || owner;
|
|
327
|
+
const conversation = { ...sandboxInboundConversation(String(this.#options.id), {
|
|
326
328
|
type: parsed.type,
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
...(parsed.action ? { action: parsed.action } : {}),
|
|
332
|
-
...(parsed.agentRun ? { sandboxAgentRun: parsed.agentRun } : {}),
|
|
333
|
-
}),
|
|
334
|
-
}).catch((err) => {
|
|
335
|
-
this.#logger.warn(formatCompact({
|
|
336
|
-
op: 'sandbox_gateway_receive_failed',
|
|
329
|
+
id: sceneId,
|
|
330
|
+
}), endpoint: this[endpointSpec].identity };
|
|
331
|
+
this.#logger.debug(formatCompact({
|
|
332
|
+
op: 'sandbox_recv',
|
|
337
333
|
target,
|
|
338
|
-
|
|
334
|
+
sender: owner,
|
|
335
|
+
channelType: parsed.type,
|
|
336
|
+
channelId: sceneId,
|
|
337
|
+
text: parsed.text.slice(0, 80),
|
|
338
|
+
}));
|
|
339
|
+
const scene: SandboxConversation = { type: conversation.kind as SandboxConversation['type'], id: sceneId };
|
|
340
|
+
subscription.conversation = scene;
|
|
341
|
+
const messageId = parsed.messageId ?? randomUUID();
|
|
342
|
+
this.#broadcast(this.#subscribers(scene, true), JSON.stringify({
|
|
343
|
+
...scene, conversation: scene, direction: 'inbound', senderId: owner,
|
|
344
|
+
messageId, endpoint: this.#options.defaults.id, content: parsed.content, timestamp: parsed.timestamp,
|
|
339
345
|
}));
|
|
346
|
+
void this[endpointSpec].events.message({
|
|
347
|
+
event: raw,
|
|
348
|
+
...(typeof parsed.timestamp === 'number' ? { platformSentAt: parsed.timestamp } : {}),
|
|
349
|
+
conversation,
|
|
350
|
+
message: { conversation, id: messageId },
|
|
351
|
+
content: parsed.text,
|
|
352
|
+
segments: parsed.content,
|
|
353
|
+
sender: { id: owner },
|
|
354
|
+
endpointId: target,
|
|
355
|
+
metadata: Object.freeze({
|
|
356
|
+
type: parsed.type,
|
|
357
|
+
channelType: parsed.type,
|
|
358
|
+
channelId: parsed.id || owner,
|
|
359
|
+
elements: parsed.content,
|
|
360
|
+
timestamp: parsed.timestamp,
|
|
361
|
+
...(parsed.action ? { action: parsed.action } : {}),
|
|
362
|
+
...(parsed.agentRun ? { sandboxAgentRun: parsed.agentRun } : {}),
|
|
363
|
+
}),
|
|
364
|
+
}).catch((err) => {
|
|
365
|
+
this.#logger.warn(formatCompact({
|
|
366
|
+
op: 'sandbox_gateway_receive_failed',
|
|
367
|
+
target,
|
|
368
|
+
error: err instanceof Error ? err.message : String(err),
|
|
369
|
+
}));
|
|
370
|
+
});
|
|
371
|
+
}).catch((error: unknown) => {
|
|
372
|
+
this.#logger.debug(formatCompact({ op: 'sandbox_receive_failed', error: error instanceof Error ? error.message : String(error) }));
|
|
340
373
|
});
|
|
341
374
|
},
|
|
342
375
|
onClose: () => {
|
|
343
376
|
void this.#emitPlatformEvent('connection.close', { target, owner });
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
this.#
|
|
349
|
-
this.#logger.debug(formatCompact({ op: 'sandbox_ws_closed', target }));
|
|
377
|
+
const current = this.connectionRecords.get(connectionId);
|
|
378
|
+
if (current === subscription) {
|
|
379
|
+
current.release();
|
|
380
|
+
this.connectionRecords.delete(connectionId);
|
|
381
|
+
this.#logger.debug(formatCompact({ op: 'sandbox_ws_closed', target, connectionId }));
|
|
350
382
|
}
|
|
351
383
|
},
|
|
352
384
|
onError: (err) => {
|
|
@@ -358,14 +390,17 @@ export class SandboxWsEndpoint extends Endpoint<SandboxClient> {
|
|
|
358
390
|
}));
|
|
359
391
|
},
|
|
360
392
|
});
|
|
361
|
-
this
|
|
393
|
+
this.connectionRecords.set(connectionId, subscription);
|
|
362
394
|
void this.#emitPlatformEvent('connection.open', { target, owner, socket });
|
|
363
395
|
this.#logger.debug(formatCompact({ op: 'sandbox_ws_connected', target, owner }));
|
|
364
396
|
this.#readiness.afterProbe((shellIsolation) => {
|
|
365
|
-
const current = this
|
|
397
|
+
const current = this.connectionRecords.get(connectionId);
|
|
366
398
|
if (!current || current.socket !== socket) return;
|
|
367
399
|
const readyPayload = JSON.stringify({
|
|
368
400
|
type: 'ready',
|
|
401
|
+
protocol: 'scoped-conversations-v1',
|
|
402
|
+
connectionId,
|
|
403
|
+
conversation: subscription.conversation,
|
|
369
404
|
locale: this.#locale,
|
|
370
405
|
id: owner,
|
|
371
406
|
endpoint: target,
|
|
@@ -377,7 +412,7 @@ export class SandboxWsEndpoint extends Endpoint<SandboxClient> {
|
|
|
377
412
|
data: {
|
|
378
413
|
text: [
|
|
379
414
|
messages(this.#locale, 'connected', { target }),
|
|
380
|
-
messages(this.#locale, 'protocol', { path: this
|
|
415
|
+
messages(this.#locale, 'protocol', { path: this.wsPathValue }),
|
|
381
416
|
messages(this.#locale, 'profile'),
|
|
382
417
|
].join('\n'),
|
|
383
418
|
},
|
|
@@ -389,8 +424,12 @@ export class SandboxWsEndpoint extends Endpoint<SandboxClient> {
|
|
|
389
424
|
}
|
|
390
425
|
|
|
391
426
|
#ensurePlaceholder(name: string, owner: string): void {
|
|
392
|
-
if (this
|
|
393
|
-
this
|
|
427
|
+
if (this.connectionRecords.has(name)) return;
|
|
428
|
+
this.connectionRecords.set(name, {
|
|
429
|
+
connectionId: name,
|
|
430
|
+
canExecute: false,
|
|
431
|
+
scoped: false,
|
|
432
|
+
conversation: { type: 'private', id: owner },
|
|
394
433
|
target: name,
|
|
395
434
|
owner,
|
|
396
435
|
socket: { send: () => undefined, close: () => undefined },
|
|
@@ -400,7 +439,7 @@ export class SandboxWsEndpoint extends Endpoint<SandboxClient> {
|
|
|
400
439
|
}
|
|
401
440
|
|
|
402
441
|
async #emitPlatformEvent(name: string, event: unknown): Promise<void> {
|
|
403
|
-
await this.
|
|
442
|
+
await this[endpointSpec].events.platform(name, event).catch((error) => {
|
|
404
443
|
this.#logger.warn(formatCompact({
|
|
405
444
|
op: 'sandbox_platform_event_failed',
|
|
406
445
|
event: name,
|
package/src/index.ts
CHANGED
|
@@ -15,7 +15,6 @@ export {
|
|
|
15
15
|
|
|
16
16
|
export {
|
|
17
17
|
SandboxClient,
|
|
18
|
-
sandboxClient,
|
|
19
18
|
type SandboxClientEventMap,
|
|
20
19
|
type SandboxClientConnection,
|
|
21
20
|
} from './client.js';
|
|
@@ -24,3 +23,4 @@ export {
|
|
|
24
23
|
SandboxWsEndpoint,
|
|
25
24
|
type SandboxEndpointOptions,
|
|
26
25
|
} from './endpoint.js';
|
|
26
|
+
export { SandboxAdapter } from './adapter.js';
|
package/src/protocol.ts
CHANGED
|
@@ -18,6 +18,7 @@ export interface MessageElement {
|
|
|
18
18
|
}
|
|
19
19
|
|
|
20
20
|
export interface SandboxWsSocket {
|
|
21
|
+
readonly readyState?: number;
|
|
21
22
|
send(data: string): void;
|
|
22
23
|
close(code?: number, reason?: string): void;
|
|
23
24
|
on?(event: 'message' | 'close' | 'error', listener: (...args: unknown[]) => void): void;
|
|
@@ -115,7 +116,12 @@ export function bindSandboxWsSocket(
|
|
|
115
116
|
};
|
|
116
117
|
}
|
|
117
118
|
|
|
118
|
-
export
|
|
119
|
+
export interface SandboxConversation {
|
|
120
|
+
readonly type: 'private' | 'group' | 'channel';
|
|
121
|
+
readonly id: string;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export interface SandboxParsedMessage {
|
|
119
125
|
type: MessageType;
|
|
120
126
|
id: string;
|
|
121
127
|
messageId?: string;
|
|
@@ -124,21 +130,55 @@ export function parseSandboxWsPayload(raw: string): {
|
|
|
124
130
|
text: string;
|
|
125
131
|
action?: { id: string; payload: string };
|
|
126
132
|
agentRun?: SandboxAgentRunConfig;
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
interface SandboxWirePayload {
|
|
136
|
+
type?: MessageType;
|
|
137
|
+
id?: string;
|
|
138
|
+
content?: MessageElement[] | string;
|
|
139
|
+
text?: string;
|
|
140
|
+
timestamp?: number;
|
|
141
|
+
messageId?: unknown;
|
|
142
|
+
agentRun?: unknown;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function readSandboxWirePayload(raw: string): SandboxWirePayload & { op?: unknown; conversation?: unknown } {
|
|
137
146
|
try {
|
|
138
|
-
payload = JSON.parse(raw)
|
|
147
|
+
const payload: unknown = JSON.parse(raw);
|
|
148
|
+
return payload && typeof payload === 'object' && !Array.isArray(payload)
|
|
149
|
+
? payload as SandboxWirePayload
|
|
150
|
+
: { text: raw };
|
|
139
151
|
} catch {
|
|
140
|
-
|
|
152
|
+
return { text: raw };
|
|
141
153
|
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export type SandboxWsFrame =
|
|
157
|
+
| { readonly kind: 'subscribe'; readonly conversation: SandboxConversation }
|
|
158
|
+
| { readonly kind: 'message'; readonly message: SandboxParsedMessage }
|
|
159
|
+
| { readonly kind: 'invalid' };
|
|
160
|
+
|
|
161
|
+
/** Control frames never fall through into chat or platform message hooks. */
|
|
162
|
+
export function parseSandboxWsFrame(raw: string): SandboxWsFrame {
|
|
163
|
+
const payload = readSandboxWirePayload(raw);
|
|
164
|
+
if ('op' in payload) {
|
|
165
|
+
const conversation = payload.conversation as Partial<SandboxConversation> | null;
|
|
166
|
+
if (payload.op !== 'subscribe' || !conversation || typeof conversation !== 'object'
|
|
167
|
+
|| (conversation.type !== 'private' && conversation.type !== 'group' && conversation.type !== 'channel')
|
|
168
|
+
|| typeof conversation.id !== 'string' || !conversation.id.trim()) return { kind: 'invalid' };
|
|
169
|
+
return { kind: 'subscribe', conversation: { type: conversation.type, id: conversation.id } };
|
|
170
|
+
}
|
|
171
|
+
const message = normalizeSandboxWsPayload(payload, raw);
|
|
172
|
+
if (!['private', 'direct', 'group', 'channel', 'guild'].includes(message.type)
|
|
173
|
+
|| typeof message.id !== 'string') return { kind: 'invalid' };
|
|
174
|
+
return { kind: 'message', message };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function parseSandboxWsPayload(raw: string): SandboxParsedMessage {
|
|
178
|
+
return normalizeSandboxWsPayload(readSandboxWirePayload(raw), raw);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function normalizeSandboxWsPayload(payload: SandboxWirePayload, raw: string): SandboxParsedMessage {
|
|
142
182
|
const type = payload.type ?? 'private';
|
|
143
183
|
const id = payload.id ?? 'sandbox-user';
|
|
144
184
|
const content: MessageElement[] = typeof payload.content === 'string'
|
|
@@ -215,6 +255,7 @@ export type SandboxOutboundChannel = {
|
|
|
215
255
|
readonly bot?: string;
|
|
216
256
|
readonly endpoint?: string;
|
|
217
257
|
readonly messageId?: string;
|
|
258
|
+
readonly conversation?: { readonly type: string; readonly id: string };
|
|
218
259
|
};
|
|
219
260
|
|
|
220
261
|
const MEDIA_SEGMENT_TYPES = new Set(['image', 'audio', 'video', 'file']);
|
|
@@ -326,6 +367,7 @@ export function formatSandboxOutbound(
|
|
|
326
367
|
if (channel.bot) stamp.bot = channel.bot;
|
|
327
368
|
if (channel.endpoint) stamp.endpoint = channel.endpoint;
|
|
328
369
|
if (channel.messageId) stamp.messageId = channel.messageId;
|
|
370
|
+
if (channel.conversation) stamp.conversation = channel.conversation;
|
|
329
371
|
|
|
330
372
|
if (typeof payload === 'string') {
|
|
331
373
|
return JSON.stringify({
|
|
@@ -362,6 +404,10 @@ export function formatSandboxOutbound(
|
|
|
362
404
|
: {}),
|
|
363
405
|
type: envelope.type ?? stamp.type,
|
|
364
406
|
id: envelope.id ?? stamp.id,
|
|
407
|
+
conversation: stamp.conversation ?? envelope.conversation,
|
|
408
|
+
messageId: typeof envelope.messageId === 'string' && envelope.messageId.trim()
|
|
409
|
+
? envelope.messageId
|
|
410
|
+
: stamp.messageId,
|
|
365
411
|
timestamp: typeof envelope.timestamp === 'number' ? envelope.timestamp : Date.now(),
|
|
366
412
|
});
|
|
367
413
|
}
|