@zhin.js/adapter-sandbox 1.0.69 → 1.1.0

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 (46) hide show
  1. package/CHANGELOG.md +961 -49
  2. package/README.md +60 -36
  3. package/adapters/sandbox.js +25 -0
  4. package/adapters/sandbox.ts +30 -0
  5. package/agent/skills/sandbox.md +33 -0
  6. package/lib/client.d.ts +27 -0
  7. package/lib/client.js +27 -0
  8. package/lib/endpoint.d.ts +42 -0
  9. package/lib/endpoint.js +357 -0
  10. package/lib/index.d.ts +3 -53
  11. package/lib/index.js +3 -173
  12. package/lib/protocol.d.ts +78 -0
  13. package/lib/protocol.js +301 -0
  14. package/lib/run-config.d.ts +10 -0
  15. package/lib/run-config.js +30 -0
  16. package/package.json +60 -24
  17. package/pages/RichTextEditor.js +366 -0
  18. package/{client → pages}/RichTextEditor.tsx +59 -13
  19. package/pages/SandboxChat.js +615 -0
  20. package/pages/SandboxChat.tsx +1186 -0
  21. package/pages/agentTrace.js +559 -0
  22. package/pages/agentTrace.test.js +235 -0
  23. package/pages/agentTrace.test.ts +265 -0
  24. package/pages/agentTrace.ts +646 -0
  25. package/pages/index.js +18 -0
  26. package/pages/index.tsx +18 -0
  27. package/pages/playgroundState.js +126 -0
  28. package/pages/playgroundState.test.js +92 -0
  29. package/pages/playgroundState.test.ts +105 -0
  30. package/pages/playgroundState.ts +172 -0
  31. package/pages/sandboxTransport.js +45 -0
  32. package/pages/sandboxTransport.ts +45 -0
  33. package/plugin.js +8 -0
  34. package/schema.json +76 -0
  35. package/src/client.ts +47 -0
  36. package/src/endpoint.ts +420 -0
  37. package/src/index.ts +26 -234
  38. package/src/protocol.ts +398 -0
  39. package/src/run-config.ts +41 -0
  40. package/LICENSE +0 -21
  41. package/client/Sandbox.tsx +0 -493
  42. package/client/index.tsx +0 -11
  43. package/client/tsconfig.json +0 -7
  44. package/dist/index.js +0 -1
  45. package/lib/index.d.ts.map +0 -1
  46. package/lib/index.js.map +0 -1
package/lib/index.d.ts CHANGED
@@ -1,53 +1,3 @@
1
- import { EventEmitter } from "events";
2
- import { Bot, Adapter, Message, SendOptions, MessageType, MessageElement, Plugin } from "zhin.js";
3
- import type { WebSocket } from "ws";
4
- import { Router } from "@zhin.js/http";
5
- export interface SandboxConfig {
6
- context: "sandbox";
7
- ws: WebSocket;
8
- name: string;
9
- }
10
- declare module "zhin.js" {
11
- namespace Plugin {
12
- interface Contexts {
13
- router: Router;
14
- web: any;
15
- }
16
- }
17
- interface Adapters {
18
- sandbox: SandboxAdapter;
19
- }
20
- }
21
- export declare class SandboxBot extends EventEmitter implements Bot<SandboxConfig, {
22
- content: MessageElement[];
23
- ts: number;
24
- }> {
25
- adapter: SandboxAdapter;
26
- $config: SandboxConfig;
27
- $connected: boolean;
28
- get $id(): string;
29
- private logger;
30
- constructor(adapter: SandboxAdapter, $config: SandboxConfig);
31
- $connect(): Promise<void>;
32
- $disconnect(): Promise<void>;
33
- $formatMessage({ content, type, id, ts }: {
34
- content: MessageElement[];
35
- id: string;
36
- type: MessageType;
37
- ts: number;
38
- }): Message<{
39
- content: MessageElement[];
40
- ts: number;
41
- }>;
42
- $sendMessage(options: SendOptions): Promise<string>;
43
- $recallMessage(id: string): Promise<void>;
44
- }
45
- declare class SandboxAdapter extends Adapter<SandboxBot> {
46
- wss?: ReturnType<Router["ws"]>;
47
- constructor(plugin: Plugin);
48
- createBot(config: SandboxConfig): SandboxBot;
49
- start(): Promise<void>;
50
- setupWebSocket(router: Router): Promise<void>;
51
- }
52
- export {};
53
- //# sourceMappingURL=index.d.ts.map
1
+ export { bindSandboxWsSocket, formatSandboxOutbound, normalizeSandboxOutboundSegments, parseSandboxWsPayload, resolveSandboxEndpoint, sandboxInboundConversation, whenWsOpen, type MessageElement, type MessageType, type ResolvedSandboxBot, type SandboxAdapterConfig, type SandboxWsSocket, } from './protocol.js';
2
+ export { SandboxClient, sandboxClient, type SandboxClientEventMap, type SandboxClientConnection, } from './client.js';
3
+ export { SandboxWsEndpoint, type SandboxEndpointOptions, } from './endpoint.js';
package/lib/index.js CHANGED
@@ -1,173 +1,3 @@
1
- import { EventEmitter } from "events";
2
- import { Adapter, usePlugin, Message, segment, } from "zhin.js";
3
- import path from "path";
4
- const plugin = usePlugin();
5
- const logger = plugin.logger;
6
- export class SandboxBot extends EventEmitter {
7
- adapter;
8
- $config;
9
- $connected = false;
10
- get $id() {
11
- return this.$config.name;
12
- }
13
- logger = logger;
14
- constructor(adapter, $config) {
15
- super();
16
- this.adapter = adapter;
17
- this.$config = $config;
18
- this.$config.ws.on("message", (data) => {
19
- const message = JSON.parse(data.toString());
20
- // 确保 content 是 MessageElement[] 格式
21
- const content = typeof message.content === 'string'
22
- ? [{ type: 'text', data: { text: message.content } }]
23
- : message.content;
24
- this.logger.debug(`${this.$config.name} recv ${message.type}(${message.id}):${segment.raw(content)}`);
25
- const formattedMessage = this.$formatMessage({ content: content, type: message.type, id: message.id, ts: message.timestamp });
26
- this.adapter.emit("message.receive", formattedMessage);
27
- });
28
- this.$config.ws.on("close", () => {
29
- this.logger.debug(`Sandbox bot ${this.$config.name} disconnected`);
30
- this.$connected = false;
31
- // 从 adapter 中移除 bot
32
- this.adapter.bots.delete(this.$id);
33
- });
34
- }
35
- async $connect() {
36
- this.$connected = true;
37
- }
38
- async $disconnect() {
39
- this.$config.ws.close();
40
- this.$connected = false;
41
- }
42
- $formatMessage({ content, type, id, ts }) {
43
- const message = Message.from({ content, ts }, {
44
- $id: `${ts}`,
45
- $adapter: "sandbox",
46
- $bot: `${this.$config.name}`,
47
- $sender: {
48
- id: `${id}`,
49
- name: `mock`,
50
- },
51
- $channel: {
52
- id: `${id}`,
53
- type: type,
54
- },
55
- $content: content,
56
- $raw: segment.raw(content),
57
- $timestamp: ts,
58
- $recall: async () => {
59
- await this.$recallMessage(message.$id);
60
- },
61
- $reply: async (content, quote) => {
62
- if (!Array.isArray(content))
63
- content = [content];
64
- if (quote)
65
- content.unshift({ type: "reply", data: { id: typeof quote === "boolean" ? message.$id : quote } });
66
- return await this.adapter.sendMessage({
67
- ...message.$channel,
68
- context: "sandbox",
69
- bot: `${this.$config.name}`,
70
- content,
71
- });
72
- },
73
- });
74
- return message;
75
- }
76
- async $sendMessage(options) {
77
- if (!this.$connected)
78
- return "";
79
- this.logger.debug(`${this.$config.name} send ${options.type}(${options.id}):${segment.raw(options.content)}`);
80
- options.bot = this.$config.name;
81
- options.context = "sandbox";
82
- this.$config.ws.send(JSON.stringify({
83
- ...options,
84
- content: options.content, // 发送消息段数组
85
- timestamp: Date.now(),
86
- }));
87
- return "";
88
- }
89
- async $recallMessage(id) {
90
- // 沙盒不支持撤回消息
91
- }
92
- }
93
- class SandboxAdapter extends Adapter {
94
- wss;
95
- constructor(plugin) {
96
- super(plugin, "sandbox", []);
97
- }
98
- createBot(config) {
99
- const bot = new SandboxBot(this, config);
100
- // 将 bot 添加到 bots Map 中
101
- this.bots.set(bot.$id, bot);
102
- return bot;
103
- }
104
- async start() {
105
- // start 方法会在 mounted 时被调用
106
- // WebSocket server 的创建在 useContext("router") 中处理
107
- }
108
- async setupWebSocket(router) {
109
- if (this.wss)
110
- return; // 已经设置过了
111
- // 创建 WebSocket server
112
- this.wss = router.ws("/sandbox");
113
- this.wss.on("connection", (ws, req) => {
114
- // 为每个连接创建一个唯一的 bot 名称
115
- const botName = `sandbox-${Math.random().toString(36).slice(2, 9)}`;
116
- logger.debug(`New sandbox connection: ${botName} from ${req.socket.remoteAddress}`);
117
- // 创建 bot 配置
118
- const config = {
119
- context: "sandbox",
120
- ws,
121
- name: botName,
122
- };
123
- // 创建并连接 bot
124
- const bot = this.createBot(config);
125
- bot.$connect();
126
- // WebSocket 关闭时清理
127
- ws.on("close", () => {
128
- logger.debug(`Sandbox connection closed: ${botName}`);
129
- this.bots.delete(bot.$id);
130
- });
131
- ws.on("error", (error) => {
132
- logger.error(`Sandbox WebSocket error for ${botName}:`, error);
133
- });
134
- });
135
- logger.debug("Sandbox WebSocket server started at /sandbox");
136
- }
137
- }
138
- const { provide } = usePlugin();
139
- provide({
140
- name: "sandbox",
141
- description: "Sandbox Adapter",
142
- mounted: async (p) => {
143
- const adapter = new SandboxAdapter(p);
144
- await adapter.start();
145
- return adapter;
146
- },
147
- dispose: async (adapter) => {
148
- // 关闭所有 bot 连接
149
- for (const bot of adapter.bots.values()) {
150
- await bot.$disconnect();
151
- }
152
- // 关闭 WebSocket server
153
- adapter.wss?.close();
154
- await adapter.stop();
155
- },
156
- });
157
- // 使用 router 上下文创建 WebSocket server
158
- plugin.useContext("router", async (router) => {
159
- // 等待 sandbox adapter 就绪
160
- plugin.useContext("sandbox", async (adapter) => {
161
- await adapter.setupWebSocket(router);
162
- });
163
- });
164
- // 使用 web 上下文注册客户端入口
165
- plugin.useContext("web", (web) => {
166
- // 注册 Sandbox 适配器的客户端入口文件
167
- const dispose = web.addEntry({
168
- production: path.resolve(import.meta.dirname, "../dist/index.js"),
169
- development: path.resolve(import.meta.dirname, "../client/index.tsx"),
170
- });
171
- return dispose;
172
- });
173
- //# sourceMappingURL=index.js.map
1
+ export { bindSandboxWsSocket, formatSandboxOutbound, normalizeSandboxOutboundSegments, parseSandboxWsPayload, resolveSandboxEndpoint, sandboxInboundConversation, whenWsOpen, } from './protocol.js';
2
+ export { SandboxClient, sandboxClient, } from './client.js';
3
+ export { SandboxWsEndpoint, } from './endpoint.js';
@@ -0,0 +1,78 @@
1
+ /** Sandbox WebSocket wire protocol helpers (no legacy Adapter/Endpoint). */
2
+ import type { ConversationRef } from '@zhin.js/im-contract';
3
+ import { type SandboxAgentRunConfig } from './run-config.js';
4
+ export type MessageType = 'private' | 'group' | 'guild' | 'direct' | 'channel';
5
+ export interface MessageElement {
6
+ readonly type: string;
7
+ readonly data?: Record<string, unknown>;
8
+ }
9
+ export interface SandboxWsSocket {
10
+ send(data: string): void;
11
+ close(code?: number, reason?: string): void;
12
+ on?(event: 'message' | 'close' | 'error', listener: (...args: unknown[]) => void): void;
13
+ off?(event: 'message' | 'close' | 'error', listener: (...args: unknown[]) => void): void;
14
+ addEventListener?(type: 'message' | 'close' | 'error', listener: (ev: Event | MessageEvent | CloseEvent) => void): void;
15
+ removeEventListener?(type: 'message' | 'close' | 'error', listener: (ev: Event | MessageEvent | CloseEvent) => void): void;
16
+ }
17
+ export type ResolvedSandboxBot = {
18
+ readonly context: 'sandbox';
19
+ readonly id: string;
20
+ readonly owner: string;
21
+ readonly randomNamePerConnection: boolean;
22
+ };
23
+ export interface SandboxAdapterConfig {
24
+ /** Runtime expands `endpoints[i]` onto the top level — prefer these. */
25
+ readonly context?: string;
26
+ readonly id?: string;
27
+ readonly owner?: string;
28
+ /** Legacy shape: endpoint entries nested under `endpoints[]`. */
29
+ readonly endpoints?: ReadonlyArray<{
30
+ readonly context?: string;
31
+ readonly id?: string;
32
+ readonly owner?: string;
33
+ }>;
34
+ }
35
+ export declare function resolveSandboxEndpoint(appConfig: SandboxAdapterConfig): ResolvedSandboxBot;
36
+ export declare function bindSandboxWsSocket(ws: SandboxWsSocket, handlers: {
37
+ onMessage: (raw: string) => void;
38
+ onClose: () => void;
39
+ onError?: (err: unknown) => void;
40
+ }): () => void;
41
+ export declare function parseSandboxWsPayload(raw: string): {
42
+ type: MessageType;
43
+ id: string;
44
+ messageId?: string;
45
+ content: MessageElement[];
46
+ timestamp: number;
47
+ text: string;
48
+ action?: {
49
+ id: string;
50
+ payload: string;
51
+ };
52
+ agentRun?: SandboxAgentRunConfig;
53
+ };
54
+ /**
55
+ * 入站归一化 → ConversationRef。sandbox 无平台社交图谱:
56
+ * `private`/`group`/`channel` 直映射;`direct`(私聊)归 'private';
57
+ * `guild`(频道容器语义)归 'channel'。无 guild/temp 容器信息,不产生 parent。
58
+ */
59
+ export declare function sandboxInboundConversation(endpointKey: string, msg: {
60
+ readonly type: MessageType;
61
+ readonly id: string;
62
+ }): ConversationRef;
63
+ export type SandboxOutboundChannel = {
64
+ readonly type?: string;
65
+ readonly id?: string;
66
+ readonly bot?: string;
67
+ readonly endpoint?: string;
68
+ readonly messageId?: string;
69
+ };
70
+ /** 出站段数组归一:媒体段走 MediaRef-only 归一,其余段原样透传。 */
71
+ export declare function normalizeSandboxOutboundSegments(segments: readonly unknown[]): unknown[];
72
+ /**
73
+ * Wire-encode an already-rendered outbound payload.
74
+ * Stamps `channel` so Console SandboxChat can filter by type+id (otherwise
75
+ * replies look like they disappeared).
76
+ */
77
+ export declare function formatSandboxOutbound(payload: unknown, channel?: SandboxOutboundChannel): string;
78
+ export declare function whenWsOpen(ws: SandboxWsSocket, fn: () => void): void;
@@ -0,0 +1,301 @@
1
+ /** Sandbox WebSocket wire protocol helpers (no legacy Adapter/Endpoint). */
2
+ import { readFileSync } from 'node:fs';
3
+ import { isMediaRef } from '@zhin.js/core';
4
+ import { formatCompact, getLogger } from '@zhin.js/logger';
5
+ import { normalizeSandboxAgentRunConfig, } from './run-config.js';
6
+ const logger = getLogger('sandbox');
7
+ export function resolveSandboxEndpoint(appConfig) {
8
+ const entry = appConfig.endpoints?.find((item) => item.context === 'sandbox');
9
+ const fixedName = typeof appConfig.id === 'string' && appConfig.id
10
+ ? appConfig.id
11
+ : typeof entry?.id === 'string' && entry.id
12
+ ? entry.id
13
+ : undefined;
14
+ const id = fixedName || process.env.SANDBOX_BOT_NAME || 'sandbox-bot';
15
+ const owner = (typeof appConfig.owner === 'string' && appConfig.owner)
16
+ || (typeof entry?.owner === 'string' && entry.owner)
17
+ || process.env.SANDBOX_BOT_OWNER
18
+ || 'sandbox-user';
19
+ return {
20
+ context: 'sandbox',
21
+ id,
22
+ owner,
23
+ // The endpoint id participates in the Agent session key. Keep it stable
24
+ // across browser reconnects and Host restarts so a persisted playground
25
+ // session resumes the same Agent context.
26
+ randomNamePerConnection: false,
27
+ };
28
+ }
29
+ export function bindSandboxWsSocket(ws, handlers) {
30
+ if (typeof ws.on === 'function') {
31
+ const onMessage = (...args) => {
32
+ const data = args[0];
33
+ const raw = typeof data === 'string'
34
+ ? data
35
+ : data instanceof ArrayBuffer
36
+ ? new TextDecoder().decode(data)
37
+ : Buffer.isBuffer(data)
38
+ ? data.toString()
39
+ : String(data ?? '');
40
+ handlers.onMessage(raw);
41
+ };
42
+ ws.on('message', onMessage);
43
+ ws.on('close', handlers.onClose);
44
+ if (handlers.onError)
45
+ ws.on('error', handlers.onError);
46
+ return () => {
47
+ ws.off?.('message', onMessage);
48
+ ws.off?.('close', handlers.onClose);
49
+ if (handlers.onError)
50
+ ws.off?.('error', handlers.onError);
51
+ };
52
+ }
53
+ const onMessage = (ev) => {
54
+ const data = ev.data;
55
+ handlers.onMessage(typeof data === 'string' ? data : '');
56
+ };
57
+ const onClose = () => handlers.onClose();
58
+ const onError = handlers.onError
59
+ ? () => handlers.onError?.(new Error('WebSocket error'))
60
+ : undefined;
61
+ ws.addEventListener('message', onMessage);
62
+ ws.addEventListener('close', onClose);
63
+ if (onError)
64
+ ws.addEventListener('error', onError);
65
+ return () => {
66
+ ws.removeEventListener('message', onMessage);
67
+ ws.removeEventListener('close', onClose);
68
+ if (onError)
69
+ ws.removeEventListener('error', onError);
70
+ };
71
+ }
72
+ export function parseSandboxWsPayload(raw) {
73
+ let payload;
74
+ try {
75
+ payload = JSON.parse(raw);
76
+ }
77
+ catch {
78
+ payload = { text: raw };
79
+ }
80
+ const type = payload.type ?? 'private';
81
+ const id = payload.id ?? 'sandbox-user';
82
+ const content = typeof payload.content === 'string'
83
+ ? [{ type: 'text', data: { text: payload.content } }]
84
+ : Array.isArray(payload.content)
85
+ ? payload.content
86
+ : [{ type: 'text', data: { text: payload.text ?? raw } }];
87
+ const actionSegment = content.find((segment) => segment.type === 'action');
88
+ let action;
89
+ if (actionSegment?.data) {
90
+ const actionPayload = typeof actionSegment.data.payload === 'string'
91
+ ? actionSegment.data.payload
92
+ : typeof actionSegment.data.id === 'string'
93
+ ? actionSegment.data.id
94
+ : '';
95
+ const actionId = typeof actionSegment.data.id === 'string'
96
+ ? actionSegment.data.id
97
+ : actionPayload;
98
+ if (actionId || actionPayload) {
99
+ action = { id: actionId || actionPayload, payload: actionPayload || actionId };
100
+ }
101
+ }
102
+ let text = content
103
+ .flatMap((segment) => (segment.type === 'text' && typeof segment.data?.text === 'string'
104
+ ? [segment.data.text]
105
+ : []))
106
+ .join('\n');
107
+ if (!text.trim()) {
108
+ text = (typeof payload.text === 'string' && payload.text.trim())
109
+ ? payload.text
110
+ : action?.payload ?? raw;
111
+ }
112
+ const agentRun = normalizeSandboxAgentRunConfig(payload.agentRun);
113
+ const rawMessageId = typeof payload.messageId === 'string' ? payload.messageId.trim() : '';
114
+ const messageId = /^[A-Za-z0-9._:-]{1,160}$/u.test(rawMessageId) ? rawMessageId : undefined;
115
+ return {
116
+ type,
117
+ id,
118
+ ...(messageId ? { messageId } : {}),
119
+ content,
120
+ timestamp: payload.timestamp ?? Date.now(),
121
+ text,
122
+ action,
123
+ ...(agentRun ? { agentRun } : {}),
124
+ };
125
+ }
126
+ /**
127
+ * 入站归一化 → ConversationRef。sandbox 无平台社交图谱:
128
+ * `private`/`group`/`channel` 直映射;`direct`(私聊)归 'private';
129
+ * `guild`(频道容器语义)归 'channel'。无 guild/temp 容器信息,不产生 parent。
130
+ */
131
+ export function sandboxInboundConversation(endpointKey, msg) {
132
+ const kind = msg.type === 'direct'
133
+ ? 'private'
134
+ : msg.type === 'guild'
135
+ ? 'channel'
136
+ : msg.type;
137
+ return {
138
+ endpoint: { id: endpointKey, adapter: endpointKey.split('\0')[0] ?? endpointKey },
139
+ kind,
140
+ id: msg.id,
141
+ };
142
+ }
143
+ const MEDIA_SEGMENT_TYPES = new Set(['image', 'audio', 'video', 'file']);
144
+ /**
145
+ * base64 内联值:Console UI 的 resolveMediaSrc 只识别 data: / base64://
146
+ * 前缀;裸 base64 补前缀(有 mime_type 时拼成可直转 data: URL 的形状)。
147
+ */
148
+ function toInlineBase64Value(value, mimeType) {
149
+ const trimmed = value.trim();
150
+ if (trimmed.startsWith('base64://') || trimmed.startsWith('data:'))
151
+ return trimmed;
152
+ return mimeType
153
+ ? `base64://${mimeType};base64,${trimmed}`
154
+ : `base64://${trimmed}`;
155
+ }
156
+ /**
157
+ * 出站媒体段归一(canonical MediaRef 唯一来源,不读 legacy url/file/base64/src):
158
+ * - kind=url → 浏览器直连 URL,原样透传;
159
+ * - kind=base64 → 内联直发(补 base64:// 前缀供 Console UI 解析);
160
+ * - kind=path → 读盘物化为 base64 内联(sandbox 无平台上传通道);
161
+ * - kind=file → sandbox 无不透明引用通道,丢弃。
162
+ * 无 canonical `data.media` 的媒体段一律 warn + 丢弃。
163
+ */
164
+ function normalizeMediaSegment(segment) {
165
+ const data = segment.data ?? {};
166
+ const media = data.media;
167
+ if (!isMediaRef(media)) {
168
+ logger.warn(formatCompact({
169
+ op: 'sandbox_outbound_media_dropped',
170
+ type: segment.type,
171
+ reason: 'missing_media_ref',
172
+ }));
173
+ return null;
174
+ }
175
+ if (media.kind === 'url')
176
+ return { type: segment.type, data };
177
+ if (media.kind === 'base64') {
178
+ return {
179
+ type: segment.type,
180
+ data: {
181
+ ...data,
182
+ media: { ...media, value: toInlineBase64Value(media.value, media.mime_type) },
183
+ },
184
+ };
185
+ }
186
+ if (media.kind === 'path') {
187
+ try {
188
+ const base64 = readFileSync(media.value).toString('base64');
189
+ return {
190
+ type: segment.type,
191
+ data: {
192
+ ...data,
193
+ media: {
194
+ ...media,
195
+ kind: 'base64',
196
+ value: toInlineBase64Value(base64, media.mime_type),
197
+ },
198
+ },
199
+ };
200
+ }
201
+ catch (err) {
202
+ logger.warn(formatCompact({
203
+ op: 'sandbox_outbound_media_dropped',
204
+ type: segment.type,
205
+ reason: 'path_read_failed',
206
+ error: err instanceof Error ? err.message : String(err),
207
+ }));
208
+ return null;
209
+ }
210
+ }
211
+ logger.warn(formatCompact({
212
+ op: 'sandbox_outbound_media_dropped',
213
+ type: segment.type,
214
+ reason: 'unsupported_media_kind',
215
+ }));
216
+ return null;
217
+ }
218
+ /** 出站段数组归一:媒体段走 MediaRef-only 归一,其余段原样透传。 */
219
+ export function normalizeSandboxOutboundSegments(segments) {
220
+ const out = [];
221
+ for (const item of segments) {
222
+ if (item
223
+ && typeof item === 'object'
224
+ && !Array.isArray(item)
225
+ && MEDIA_SEGMENT_TYPES.has(String(item.type))) {
226
+ const normalized = normalizeMediaSegment(item);
227
+ if (normalized)
228
+ out.push(normalized);
229
+ continue;
230
+ }
231
+ out.push(item);
232
+ }
233
+ return out;
234
+ }
235
+ /**
236
+ * Wire-encode an already-rendered outbound payload.
237
+ * Stamps `channel` so Console SandboxChat can filter by type+id (otherwise
238
+ * replies look like they disappeared).
239
+ */
240
+ export function formatSandboxOutbound(payload, channel = {}) {
241
+ const stamp = {};
242
+ if (channel.type)
243
+ stamp.type = channel.type;
244
+ if (channel.id)
245
+ stamp.id = channel.id;
246
+ if (channel.bot)
247
+ stamp.bot = channel.bot;
248
+ if (channel.endpoint)
249
+ stamp.endpoint = channel.endpoint;
250
+ if (channel.messageId)
251
+ stamp.messageId = channel.messageId;
252
+ if (typeof payload === 'string') {
253
+ return JSON.stringify({
254
+ ...stamp,
255
+ content: [{ type: 'text', data: { text: payload } }],
256
+ timestamp: Date.now(),
257
+ });
258
+ }
259
+ if (Array.isArray(payload)) {
260
+ return JSON.stringify({
261
+ ...stamp,
262
+ content: normalizeSandboxOutboundSegments(payload),
263
+ timestamp: Date.now(),
264
+ });
265
+ }
266
+ // Already a wire envelope ({ content, type, … }) — pass through so the
267
+ // Console UI can read `content` / `type` without an extra nesting layer.
268
+ // Bare segment objects ({ type: 'text', data: … }) still need wrapping.
269
+ if (payload
270
+ && typeof payload === 'object'
271
+ && !Array.isArray(payload)
272
+ && ('content' in payload
273
+ || 'type' in payload && 'timestamp' in payload)) {
274
+ const envelope = payload;
275
+ return JSON.stringify({
276
+ ...stamp,
277
+ ...envelope,
278
+ ...(Array.isArray(envelope.content)
279
+ ? { content: normalizeSandboxOutboundSegments(envelope.content) }
280
+ : {}),
281
+ type: envelope.type ?? stamp.type,
282
+ id: envelope.id ?? stamp.id,
283
+ timestamp: typeof envelope.timestamp === 'number' ? envelope.timestamp : Date.now(),
284
+ });
285
+ }
286
+ return JSON.stringify({ ...stamp, content: payload, timestamp: Date.now() });
287
+ }
288
+ /** WebSocket.OPEN 常量值;Node <22 无全局 WebSocket,不能用 WebSocket.OPEN。 */
289
+ const WS_OPEN = 1;
290
+ export function whenWsOpen(ws, fn) {
291
+ const std = ws;
292
+ if (typeof std.readyState === 'number') {
293
+ if (std.readyState === WS_OPEN) {
294
+ fn();
295
+ return;
296
+ }
297
+ std.addEventListener('open', fn, { once: true });
298
+ return;
299
+ }
300
+ fn();
301
+ }
@@ -0,0 +1,10 @@
1
+ export type SandboxSafetyMode = 'read-only' | 'workspace-write' | 'danger-full-access';
2
+ export type SandboxApprovalMode = 'ask' | 'deny' | 'allow';
3
+ export interface SandboxAgentRunConfig {
4
+ readonly workingDirectory: string;
5
+ readonly safetyMode: SandboxSafetyMode;
6
+ readonly approvalMode: SandboxApprovalMode;
7
+ readonly networkAccess: boolean;
8
+ }
9
+ export declare const DEFAULT_SANDBOX_AGENT_RUN_CONFIG: SandboxAgentRunConfig;
10
+ export declare function normalizeSandboxAgentRunConfig(value: unknown): SandboxAgentRunConfig | undefined;
@@ -0,0 +1,30 @@
1
+ export const DEFAULT_SANDBOX_AGENT_RUN_CONFIG = Object.freeze({
2
+ workingDirectory: '',
3
+ safetyMode: 'workspace-write',
4
+ approvalMode: 'ask',
5
+ networkAccess: false,
6
+ });
7
+ const SAFETY_MODES = new Set(['read-only', 'workspace-write', 'danger-full-access']);
8
+ const APPROVAL_MODES = new Set(['ask', 'deny', 'allow']);
9
+ export function normalizeSandboxAgentRunConfig(value) {
10
+ if (!value || typeof value !== 'object' || Array.isArray(value))
11
+ return undefined;
12
+ const input = value;
13
+ const workingDirectory = typeof input.workingDirectory === 'string'
14
+ ? input.workingDirectory.trim().slice(0, 4096)
15
+ : '';
16
+ const safetyMode = SAFETY_MODES.has(input.safetyMode)
17
+ ? input.safetyMode
18
+ : DEFAULT_SANDBOX_AGENT_RUN_CONFIG.safetyMode;
19
+ const approvalMode = APPROVAL_MODES.has(input.approvalMode)
20
+ ? input.approvalMode
21
+ : DEFAULT_SANDBOX_AGENT_RUN_CONFIG.approvalMode;
22
+ return Object.freeze({
23
+ workingDirectory,
24
+ safetyMode,
25
+ approvalMode,
26
+ // Full host access cannot be combined with a portable network namespace.
27
+ // Keep the contract honest: danger mode includes network authority.
28
+ networkAccess: safetyMode === 'danger-full-access' || input.networkAccess === true,
29
+ });
30
+ }