@zhin.js/adapter-sandbox 1.1.22 → 1.1.23
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 +47 -0
- package/README.md +10 -1
- package/adapters/sandbox/index.js +1 -0
- package/adapters/sandbox/index.ts +1 -0
- package/lib/adapter.js +1 -1
- package/lib/endpoint.js +44 -0
- package/lib/protocol.d.ts +6 -2
- package/lib/protocol.js +5 -0
- package/package.json +18 -18
- package/pages/index/SandboxChat.js +2 -0
- package/pages/index/SandboxChat.tsx +3 -0
- package/pages/index/playgroundState.js +21 -2
- package/pages/index/playgroundState.ts +23 -2
- package/pages/index/useSandboxHistory.js +41 -8
- package/pages/index/useSandboxHistory.ts +37 -8
- package/schema.json +126 -1
- package/src/adapter.ts +1 -1
- package/src/endpoint.ts +41 -1
- package/src/protocol.ts +10 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,52 @@
|
|
|
1
1
|
# @zhin.js/adapter-process
|
|
2
2
|
|
|
3
|
+
## 1.1.23
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- af8f803: Use the current Endpoint's platform profile for Agent account identity, with per-field configured fallbacks and scoped, identity-approved profile tools. Keep SOUL first-person and independent of account names. Profile ports preserve the source Client, cancellation, truthful update outcomes and private image authority.
|
|
8
|
+
|
|
9
|
+
Adapter Feature API 2.1 and Tool Feature API 1.1 describe the additive profile requirements; new Core, official adapters and generated plugins declare the corresponding floors. Existing compatible API-2.0/API-1.0 plugins remain accepted by the newer providers. npm releases remain patch.
|
|
10
|
+
|
|
11
|
+
Private IM assets now bind to the full canonical conversation and principal. Existing IM asset records that contain only the earlier lossy hash remain on disk until their original expiry, but cannot be safely rebound; recapture them. No automatic file deletion, platform profile mutation or workspace SOUL rewrite occurs during upgrade.
|
|
12
|
+
|
|
13
|
+
- 26fda97: Deliver validated final answers progressively through configured QQ C2C, Telegram drafts, Slack streams, Lark cards and Sandbox updates. Keep complete-message delivery for unsupported scenes, disabled adapters and outbound middleware that does not explicitly support revisions. Discord retains complete-message delivery.
|
|
14
|
+
|
|
15
|
+
Preserve source-account leases, media order and confirmed delivery facts across cancellation, capacity rollover and follow-up answer phases. Preview drafts and uncertain outcomes do not become sent history. Bound each reply's semantic snapshot to 1 MiB, retain confirmed prefixes on failure and avoid replaying published answers.
|
|
16
|
+
|
|
17
|
+
Project the latest confirmed message revision into paginated conversation history and synchronize Sandbox message updates across connections. Existing adapter implementations and complete-send callers remain compatible.
|
|
18
|
+
|
|
19
|
+
- 976886c: Preserve confirmed progressive reply content, routing and delivery evidence across cancellation, rollover and closing failures without replaying published text. Keep error dispositions and actual message references, and abort the owning provider request when its functional text consumer fails.
|
|
20
|
+
|
|
21
|
+
Enable native Sandbox Markdown through the real Core projection so Console updates retain formatting in one message. Preserve instance-level streaming opt-outs, recall tombstones and multi-page synchronization. The first safe content is immediate; later updates retain the configured pacing, including large valid intervals.
|
|
22
|
+
|
|
23
|
+
Keep Slack and Lark Markdown streaming within the current physical message. When continuation formatting cannot be verified, stop and retain confirmed content instead of replaying or silently changing it to plain text. Plain-text continuations retain their original reply route.
|
|
24
|
+
|
|
25
|
+
Use rebuildable revision metadata and indexes in the existing conversation event table for bounded SQL history reads. Original event JSON and retention remain unchanged; older writers and models keep their compatible read path. Supported adapter streaming remains enabled by default, with complete-message fallback for disabled settings or outbound middleware without incremental: true.
|
|
26
|
+
|
|
27
|
+
- 3c1912f: Restore legacy Sandbox streaming history updates while preserving revision precedence, creation order, recall boundaries and browser-cache provenance. Report empty QQ send plans as not sent before any platform call.
|
|
28
|
+
|
|
29
|
+
Seek past completed conversation-history backfill batches instead of re-scanning the migrated prefix. Preserve original event data, retention and compatible older writers.
|
|
30
|
+
|
|
31
|
+
Report terminal provider quota and billing failures after publication without regeneration, and isolate synchronous diagnostic failures from provider outcomes and retry/fallback decisions.
|
|
32
|
+
|
|
33
|
+
- Updated dependencies [b88e988]
|
|
34
|
+
- Updated dependencies [f78eb84]
|
|
35
|
+
- Updated dependencies [c15cef9]
|
|
36
|
+
- Updated dependencies [b0c02a2]
|
|
37
|
+
- Updated dependencies [af8f803]
|
|
38
|
+
- Updated dependencies [26fda97]
|
|
39
|
+
- Updated dependencies [976886c]
|
|
40
|
+
- Updated dependencies [032dc96]
|
|
41
|
+
- @zhin.js/adapter@1.1.27
|
|
42
|
+
- @zhin.js/client@1.1.23
|
|
43
|
+
- @zhin.js/im-contract@1.1.10
|
|
44
|
+
- @zhin.js/core@1.1.55
|
|
45
|
+
- @zhin.js/page@1.1.13
|
|
46
|
+
- @zhin.js/host-http@1.1.13
|
|
47
|
+
- @zhin.js/feature-kit@1.1.11
|
|
48
|
+
- @zhin.js/skill@1.1.12
|
|
49
|
+
|
|
3
50
|
## 1.1.22
|
|
4
51
|
|
|
5
52
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -71,8 +71,16 @@ sandbox:
|
|
|
71
71
|
endpoints:
|
|
72
72
|
- id: sandbox-bot
|
|
73
73
|
owner: sandbox-user
|
|
74
|
+
streaming: true
|
|
75
|
+
streamingIntervalMs: 500
|
|
74
76
|
```
|
|
75
77
|
|
|
78
|
+
流式回复默认开启,首次内容立即投递,后续更新默认间隔 500 ms。
|
|
79
|
+
`streaming: false` 使用完整消息发送。流式更新复用同一 `messageId` 并递增
|
|
80
|
+
`revision`,同会话的多个页面同步更新同一气泡;最终更新带 `streaming: false`。
|
|
81
|
+
Console 原生渲染 Markdown 格式的流式回复(`markdown` 段,`data.content`),保留标题、粗体和代码块;Core 不会先将其转换为纯文字。
|
|
82
|
+
没有在线订阅者时不确认已发送,取消不会补发最终内容。
|
|
83
|
+
|
|
76
84
|
## 使用方式
|
|
77
85
|
|
|
78
86
|
1. 启动 Zhin 实例:`pnpm dev`(终端会打印 Host 地址,一般为 `http://127.0.0.1:8086`)
|
|
@@ -191,7 +199,8 @@ Console 沙盒页和自己写的测试客户端都用这套协议。每个 WebSo
|
|
|
191
199
|
|
|
192
200
|
- `conversation: { type, id }` 是框架发送请求确定的真实会话;新客户端优先用它归并消息,即使 legacy envelope 的 `type` / `id` 指向别处。`bot` 和 `endpoint` 是配置的 endpoint id。旧客户端仍可读取原 `type` / `id` 字段。
|
|
193
201
|
- `messageId` 与框架记录的发送回执使用同一个消息 ID,可用于关联实时回复和已保存的聊天记录;已有 wire envelope 的非空显式字符串 ID 保持不变。
|
|
194
|
-
- `
|
|
202
|
+
- `revision` 为同一消息的递增版本;`streaming: true` 表示后续仍可更新,`false` 为该物理消息的完成更新。旧客户端可继续读取 `content`,支持版本的客户端忽略迟到的旧版本。聊天历史每页仍为 50 条消息,更新事件不额外占用页数;撤回优先于后续更新。
|
|
203
|
+
- `content` 是消息段数组。`text` 段使用 `data.text`,`markdown` 段使用 `data.content`;`html`(JSX 卡片,见上文 `html: direct`)、按钮等段原样透传。
|
|
195
204
|
- `image` / `audio` / `video` / `file` 段只读 `data.media`(MediaRef):`url` 原样透传;`base64` 补上 `base64://` 前缀后内联;`path` 由服务端读取文件后转成 `base64` 内联;其他类型和缺少 `data.media` 的媒体段会被丢弃,并在日志中记录 `sandbox_outbound_media_dropped`。
|
|
196
205
|
- 插件直接发送完整消息对象时,其他字段会原样保留。
|
|
197
206
|
|
package/lib/adapter.js
CHANGED
|
@@ -8,7 +8,7 @@ export class SandboxAdapter extends Adapter {
|
|
|
8
8
|
constructor(context) { super(); this.#context = context; }
|
|
9
9
|
get configurationIdentityFields() { return ['id']; }
|
|
10
10
|
// owner binds the synthetic sender's existing permissions and is not a runtime connection setting.
|
|
11
|
-
get configurationUpdateFields() { return []; }
|
|
11
|
+
get configurationUpdateFields() { return ['streaming', 'streamingIntervalMs']; }
|
|
12
12
|
validateConfiguration(config) { resolveSandboxEndpoint(config); }
|
|
13
13
|
createEndpoint(input, execution) {
|
|
14
14
|
return new SandboxWsEndpoint({ id: execution.canonicalId, defaults: resolveSandboxEndpoint(input),
|
package/lib/endpoint.js
CHANGED
|
@@ -98,6 +98,9 @@ export class SandboxWsEndpoint extends SandboxClient {
|
|
|
98
98
|
start: () => this.#start(), open: () => this.#openEndpoint(),
|
|
99
99
|
close: () => this.#close(), stop: () => this.#stop(),
|
|
100
100
|
send: request => this.#send(request),
|
|
101
|
+
...(options.defaults.streaming ? { streaming: Object.freeze({ mode: 'native',
|
|
102
|
+
minIntervalMs: options.defaults.streamingIntervalMs, supports: request => this.#supportsStream(request),
|
|
103
|
+
open: request => this.#openStream(request) }) } : {}),
|
|
101
104
|
get transportState() { return readTransportState(); },
|
|
102
105
|
});
|
|
103
106
|
}
|
|
@@ -180,6 +183,47 @@ export class SandboxWsEndpoint extends SandboxClient {
|
|
|
180
183
|
}
|
|
181
184
|
return messageId;
|
|
182
185
|
}
|
|
186
|
+
#supportsStream(request) {
|
|
187
|
+
return !request.conversation.parent && request.conversation.threadId === undefined
|
|
188
|
+
&& ['private', 'group', 'channel'].includes(request.conversation.kind);
|
|
189
|
+
}
|
|
190
|
+
#openStream(request) {
|
|
191
|
+
if (!this.#supportsStream(request))
|
|
192
|
+
return undefined;
|
|
193
|
+
const messageId = randomUUID();
|
|
194
|
+
let revision = 0, timestamp, acceptedText = '';
|
|
195
|
+
let state = 'active';
|
|
196
|
+
let last;
|
|
197
|
+
const submit = async (text, finish) => {
|
|
198
|
+
if (state === 'completed') {
|
|
199
|
+
if (finish && text === acceptedText)
|
|
200
|
+
return last;
|
|
201
|
+
throw new EndpointDeliveryError('stream_closed', 'Sandbox reply stream has completed', 'not_sent');
|
|
202
|
+
}
|
|
203
|
+
if (state === 'cancelled' || request.signal?.aborted || !this.#open) {
|
|
204
|
+
throw new EndpointDeliveryError('endpoint_inactive', 'Sandbox reply stream has ended', 'not_sent');
|
|
205
|
+
}
|
|
206
|
+
if (!text.startsWith(acceptedText))
|
|
207
|
+
throw new EndpointDeliveryError('invalid_payload', 'Sandbox stream text must preserve the confirmed prefix', 'not_sent');
|
|
208
|
+
const sentAt = timestamp ?? Date.now();
|
|
209
|
+
this.#send({ conversation: request.conversation, signal: request.signal, payload: {
|
|
210
|
+
messageId, revision: revision + 1, streaming: !finish, timestamp: sentAt,
|
|
211
|
+
content: [...(request.prefix ?? []), request.format === 'markdown'
|
|
212
|
+
? { type: 'markdown', data: { content: text } } : { type: 'text', data: { text } }],
|
|
213
|
+
} });
|
|
214
|
+
timestamp = sentAt;
|
|
215
|
+
revision += 1;
|
|
216
|
+
acceptedText = text;
|
|
217
|
+
last = { status: 'sent', messageId, acceptedText };
|
|
218
|
+
if (finish)
|
|
219
|
+
state = 'completed';
|
|
220
|
+
return last;
|
|
221
|
+
};
|
|
222
|
+
return Object.freeze({ write: text => submit(text, false), finish: text => submit(text, true),
|
|
223
|
+
cancel: () => { if (state === 'active')
|
|
224
|
+
state = 'cancelled'; },
|
|
225
|
+
});
|
|
226
|
+
}
|
|
183
227
|
#subscribers(scene, echo = false) {
|
|
184
228
|
return [...this.connectionRecords.values()].filter(connection => !connection.placeholder && connection.canExecute
|
|
185
229
|
&& (!echo || connection.scoped)
|
package/lib/protocol.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
import type { EndpointProfileConfiguration } from 'zhin.js/adapter';
|
|
2
2
|
import { type ConversationRef } from '@zhin.js/im-contract';
|
|
3
3
|
import { type SandboxAgentRunConfig } from './run-config.js';
|
|
4
4
|
export type MessageType = 'private' | 'group' | 'guild' | 'direct' | 'channel';
|
|
@@ -20,11 +20,15 @@ export type ResolvedSandboxBot = {
|
|
|
20
20
|
readonly id: string;
|
|
21
21
|
readonly owner: string;
|
|
22
22
|
readonly randomNamePerConnection: boolean;
|
|
23
|
+
readonly streaming: boolean;
|
|
24
|
+
readonly streamingIntervalMs: number;
|
|
23
25
|
};
|
|
24
26
|
/** One endpoint config after AdapterIndex expands `plugins.<instanceKey>.endpoints`. */
|
|
25
|
-
export interface SandboxEndpointConfig {
|
|
27
|
+
export interface SandboxEndpointConfig extends EndpointProfileConfiguration {
|
|
26
28
|
readonly id?: string;
|
|
27
29
|
readonly owner?: string;
|
|
30
|
+
readonly streaming?: boolean;
|
|
31
|
+
readonly streamingIntervalMs?: number;
|
|
28
32
|
}
|
|
29
33
|
export declare function resolveSandboxEndpoint(config: SandboxEndpointConfig): ResolvedSandboxBot;
|
|
30
34
|
export declare function bindSandboxWsSocket(ws: SandboxWsSocket, handlers: {
|
package/lib/protocol.js
CHANGED
|
@@ -7,6 +7,9 @@ const logger = getLogger('sandbox');
|
|
|
7
7
|
export function resolveSandboxEndpoint(config) {
|
|
8
8
|
const id = optionalEndpointField(config.id) ?? 'sandbox-bot';
|
|
9
9
|
const owner = optionalEndpointField(config.owner) ?? 'sandbox-user';
|
|
10
|
+
const streamingIntervalMs = config.streamingIntervalMs ?? 500;
|
|
11
|
+
if (!Number.isFinite(streamingIntervalMs) || streamingIntervalMs < 0)
|
|
12
|
+
throw new TypeError('streamingIntervalMs must be a non-negative finite number');
|
|
10
13
|
return {
|
|
11
14
|
context: 'sandbox',
|
|
12
15
|
id,
|
|
@@ -15,6 +18,8 @@ export function resolveSandboxEndpoint(config) {
|
|
|
15
18
|
// across browser reconnects and Host restarts so a persisted playground
|
|
16
19
|
// session resumes the same Agent context.
|
|
17
20
|
randomNamePerConnection: false,
|
|
21
|
+
streaming: config.streaming !== false,
|
|
22
|
+
streamingIntervalMs,
|
|
18
23
|
};
|
|
19
24
|
}
|
|
20
25
|
function optionalEndpointField(value) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zhin.js/adapter-sandbox",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.23",
|
|
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.
|
|
51
|
-
"@zhin.js/client": "1.1.
|
|
50
|
+
"@zhin.js/adapter": "1.1.27",
|
|
51
|
+
"@zhin.js/client": "1.1.23",
|
|
52
52
|
"@zhin.js/console-contract": "1.1.3",
|
|
53
|
-
"@zhin.js/core": "1.1.
|
|
54
|
-
"@zhin.js/feature-kit": "1.1.
|
|
55
|
-
"@zhin.js/host-http": "1.1.
|
|
56
|
-
"@zhin.js/im-contract": "1.1.
|
|
53
|
+
"@zhin.js/core": "1.1.55",
|
|
54
|
+
"@zhin.js/feature-kit": "1.1.11",
|
|
55
|
+
"@zhin.js/host-http": "1.1.13",
|
|
56
|
+
"@zhin.js/im-contract": "1.1.10",
|
|
57
57
|
"@zhin.js/logger": "1.1.2",
|
|
58
|
-
"@zhin.js/page": "1.1.
|
|
59
|
-
"@zhin.js/skill": "1.1.
|
|
58
|
+
"@zhin.js/page": "1.1.13",
|
|
59
|
+
"@zhin.js/skill": "1.1.12"
|
|
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.
|
|
68
|
-
"@zhin.js/runtime": "1.1.
|
|
69
|
-
"zhin.js": "1.1.
|
|
67
|
+
"@zhin.js/pagemanager": "1.1.20",
|
|
68
|
+
"@zhin.js/runtime": "1.1.17",
|
|
69
|
+
"zhin.js": "1.1.20"
|
|
70
70
|
},
|
|
71
71
|
"peerDependencies": {
|
|
72
72
|
"react": "^19.0.0",
|
|
73
|
-
"@zhin.js/adapter": "^1.1.
|
|
73
|
+
"@zhin.js/adapter": "^1.1.27",
|
|
74
74
|
"@zhin.js/console-contract": "^1.1.3",
|
|
75
|
-
"@zhin.js/core": "^1.1.
|
|
76
|
-
"@zhin.js/host-http": "^1.1.
|
|
77
|
-
"@zhin.js/page": "^1.1.
|
|
78
|
-
"zhin.js": "^1.1.
|
|
75
|
+
"@zhin.js/core": "^1.1.55",
|
|
76
|
+
"@zhin.js/host-http": "^1.1.13",
|
|
77
|
+
"@zhin.js/page": "^1.1.13",
|
|
78
|
+
"zhin.js": "^1.1.20"
|
|
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": "^2.
|
|
101
|
+
"api": "^2.1.0"
|
|
102
102
|
},
|
|
103
103
|
{
|
|
104
104
|
"package": "@zhin.js/page",
|
|
@@ -266,6 +266,8 @@ export default function Sandbox(props = {}) {
|
|
|
266
266
|
interactionReadOnly: false,
|
|
267
267
|
channelId: sceneId, channelName, senderId: isInput ? data.senderId || connectionRef.current.ownerId || 'owner' : 'endpoint',
|
|
268
268
|
senderName: isInput ? sandboxText(locale, "当前用户") : data.bot || endpointIdRef.current, content, timestamp: data.timestamp,
|
|
269
|
+
...(Number.isSafeInteger(data.revision) && data.revision > 0 ? { revision: data.revision } : {}),
|
|
270
|
+
...(typeof data.streaming === 'boolean' ? { streaming: data.streaming } : {}),
|
|
269
271
|
}));
|
|
270
272
|
};
|
|
271
273
|
const sendInteractiveAction = (payload, messageId) => {
|
|
@@ -238,6 +238,7 @@ export default function Sandbox(props: SandboxPageProps = {}) {
|
|
|
238
238
|
type: string; id: string; locale?: unknown; content?: unknown; endpoint?: string; workingDirectory?: string; canExecute?: boolean;
|
|
239
239
|
shellIsolation?: { available?: boolean; provider?: string; message?: string }; timestamp: number;
|
|
240
240
|
messageId?: string; bot?: string; protocol?: string; connectionId?: string; direction?: string; senderId?: string;
|
|
241
|
+
revision?: number; streaming?: boolean;
|
|
241
242
|
conversation?: { type: Channel['type']; id: string };
|
|
242
243
|
}) => {
|
|
243
244
|
const locale = data.type === 'ready' && data.locale === 'en' ? 'en' : data.type === 'ready' ? 'zh-CN' : localeRef.current
|
|
@@ -326,6 +327,8 @@ export default function Sandbox(props: SandboxPageProps = {}) {
|
|
|
326
327
|
interactionReadOnly: false,
|
|
327
328
|
channelId: sceneId, channelName, senderId: isInput ? data.senderId || connectionRef.current.ownerId || 'owner' : 'endpoint',
|
|
328
329
|
senderName: isInput ? sandboxText(locale, "当前用户") : data.bot || endpointIdRef.current, content, timestamp: data.timestamp,
|
|
330
|
+
...(Number.isSafeInteger(data.revision) && data.revision! > 0 ? { revision: data.revision } : {}),
|
|
331
|
+
...(typeof data.streaming === 'boolean' ? { streaming: data.streaming } : {}),
|
|
329
332
|
}))
|
|
330
333
|
}
|
|
331
334
|
|
|
@@ -105,6 +105,8 @@ function parseMessage(value) {
|
|
|
105
105
|
return undefined;
|
|
106
106
|
if (item.channelType !== 'private' && item.channelType !== 'group' && item.channelType !== 'channel')
|
|
107
107
|
return undefined;
|
|
108
|
+
const historyEvent = item.historyEvent && typeof item.historyEvent === 'object' && !Array.isArray(item.historyEvent)
|
|
109
|
+
? item.historyEvent : undefined;
|
|
108
110
|
return {
|
|
109
111
|
id: item.id.slice(0, 256),
|
|
110
112
|
type: item.type,
|
|
@@ -118,8 +120,15 @@ function parseMessage(value) {
|
|
|
118
120
|
...(item.interactionResolved === true ? { interactionResolved: true } : {}),
|
|
119
121
|
...(hasPlaygroundKeyboard(item.content) ? { interactionReadOnly: true } : {}),
|
|
120
122
|
...(Number.isSafeInteger(item.historySequence) && Number(item.historySequence) > 0 ? { historySequence: Number(item.historySequence) } : {}),
|
|
123
|
+
...(Number.isSafeInteger(item.historyCreatedSequence) && Number(item.historyCreatedSequence) > 0
|
|
124
|
+
? { historyCreatedSequence: Number(item.historyCreatedSequence) } : {}),
|
|
125
|
+
...((historyEvent?.type === 'message.created' || historyEvent?.type === 'message.updated')
|
|
126
|
+
&& Number.isSafeInteger(historyEvent.sequence) && Number(historyEvent.sequence) > 0
|
|
127
|
+
? { historyEvent: { type: historyEvent.type, sequence: Number(historyEvent.sequence) } } : {}),
|
|
121
128
|
...(item.recalled === true ? { recalled: true } : {}),
|
|
122
129
|
...(typeof item.recalledMessageId === 'string' ? { recalledMessageId: item.recalledMessageId } : {}),
|
|
130
|
+
...(Number.isSafeInteger(item.revision) && Number(item.revision) > 0 ? { revision: Number(item.revision) } : {}),
|
|
131
|
+
...(typeof item.streaming === 'boolean' ? { streaming: item.streaming } : {}),
|
|
123
132
|
};
|
|
124
133
|
}
|
|
125
134
|
export function hasPlaygroundKeyboard(content) {
|
|
@@ -168,9 +177,19 @@ function sessionIdentity(value) {
|
|
|
168
177
|
}
|
|
169
178
|
/** Socket echoes replace their local optimistic row, without crossing scenes or authors. */
|
|
170
179
|
export function mergePlaygroundMessage(messages, incoming) {
|
|
180
|
+
if (messages.some(message => message.recalledMessageId === incoming.id
|
|
181
|
+
&& message.channelType === incoming.channelType && message.channelId === incoming.channelId))
|
|
182
|
+
return [...messages];
|
|
171
183
|
const index = messages.findIndex(message => message.id === incoming.id
|
|
172
184
|
&& message.channelType === incoming.channelType && message.channelId === incoming.channelId
|
|
173
185
|
&& message.type === incoming.type);
|
|
174
|
-
|
|
175
|
-
|
|
186
|
+
if (index < 0)
|
|
187
|
+
return [...messages, incoming];
|
|
188
|
+
const existing = messages[index];
|
|
189
|
+
if (existing.recalled || existing.revision !== undefined && (incoming.revision ?? 0) <= existing.revision)
|
|
190
|
+
return [...messages];
|
|
191
|
+
return messages.map((message, offset) => offset === index ? { ...message, ...incoming,
|
|
192
|
+
historyEvent: incoming.historyEvent,
|
|
193
|
+
...(incoming.revision === undefined ? {} : { timestamp: message.timestamp }),
|
|
194
|
+
} : message);
|
|
176
195
|
}
|
|
@@ -33,8 +33,13 @@ export interface PlaygroundMessage {
|
|
|
33
33
|
/** Stored controls are display data; only the live pending authority may accept their answers. */
|
|
34
34
|
readonly interactionReadOnly?: boolean;
|
|
35
35
|
readonly historySequence?: number;
|
|
36
|
+
readonly historyCreatedSequence?: number;
|
|
37
|
+
/** Origin of the selected historical body; a live wire revision clears this provenance. */
|
|
38
|
+
readonly historyEvent?: Readonly<{ type: 'message.created' | 'message.updated'; sequence: number }>;
|
|
36
39
|
readonly recalled?: boolean;
|
|
37
40
|
readonly recalledMessageId?: string;
|
|
41
|
+
readonly revision?: number;
|
|
42
|
+
readonly streaming?: boolean;
|
|
38
43
|
}
|
|
39
44
|
|
|
40
45
|
export interface PlaygroundState {
|
|
@@ -155,6 +160,8 @@ function parseMessage(value: unknown): PlaygroundMessage | undefined {
|
|
|
155
160
|
if (typeof item.id !== 'string' || typeof item.channelId !== 'string' || !Array.isArray(item.content)) return undefined;
|
|
156
161
|
if (item.type !== 'sent' && item.type !== 'received') return undefined;
|
|
157
162
|
if (item.channelType !== 'private' && item.channelType !== 'group' && item.channelType !== 'channel') return undefined;
|
|
163
|
+
const historyEvent = item.historyEvent && typeof item.historyEvent === 'object' && !Array.isArray(item.historyEvent)
|
|
164
|
+
? item.historyEvent as Record<string, unknown> : undefined;
|
|
158
165
|
return {
|
|
159
166
|
id: item.id.slice(0, 256),
|
|
160
167
|
type: item.type,
|
|
@@ -168,8 +175,15 @@ function parseMessage(value: unknown): PlaygroundMessage | undefined {
|
|
|
168
175
|
...(item.interactionResolved === true ? { interactionResolved: true } : {}),
|
|
169
176
|
...(hasPlaygroundKeyboard(item.content as MessageSegment[]) ? { interactionReadOnly: true } : {}),
|
|
170
177
|
...(Number.isSafeInteger(item.historySequence) && Number(item.historySequence) > 0 ? { historySequence: Number(item.historySequence) } : {}),
|
|
178
|
+
...(Number.isSafeInteger(item.historyCreatedSequence) && Number(item.historyCreatedSequence) > 0
|
|
179
|
+
? { historyCreatedSequence: Number(item.historyCreatedSequence) } : {}),
|
|
180
|
+
...((historyEvent?.type === 'message.created' || historyEvent?.type === 'message.updated')
|
|
181
|
+
&& Number.isSafeInteger(historyEvent.sequence) && Number(historyEvent.sequence) > 0
|
|
182
|
+
? { historyEvent: { type: historyEvent.type, sequence: Number(historyEvent.sequence) } } : {}),
|
|
171
183
|
...(item.recalled === true ? { recalled: true } : {}),
|
|
172
184
|
...(typeof item.recalledMessageId === 'string' ? { recalledMessageId: item.recalledMessageId } : {}),
|
|
185
|
+
...(Number.isSafeInteger(item.revision) && Number(item.revision) > 0 ? { revision: Number(item.revision) } : {}),
|
|
186
|
+
...(typeof item.streaming === 'boolean' ? { streaming: item.streaming } : {}),
|
|
173
187
|
};
|
|
174
188
|
}
|
|
175
189
|
|
|
@@ -224,9 +238,16 @@ export function mergePlaygroundMessage(
|
|
|
224
238
|
messages: readonly PlaygroundMessage[],
|
|
225
239
|
incoming: PlaygroundMessage,
|
|
226
240
|
): PlaygroundMessage[] {
|
|
241
|
+
if (messages.some(message => message.recalledMessageId === incoming.id
|
|
242
|
+
&& message.channelType === incoming.channelType && message.channelId === incoming.channelId)) return [...messages];
|
|
227
243
|
const index = messages.findIndex(message => message.id === incoming.id
|
|
228
244
|
&& message.channelType === incoming.channelType && message.channelId === incoming.channelId
|
|
229
245
|
&& message.type === incoming.type);
|
|
230
|
-
|
|
231
|
-
|
|
246
|
+
if (index < 0) return [...messages, incoming];
|
|
247
|
+
const existing = messages[index]!;
|
|
248
|
+
if (existing.recalled || existing.revision !== undefined && (incoming.revision ?? 0) <= existing.revision) return [...messages];
|
|
249
|
+
return messages.map((message, offset) => offset === index ? { ...message, ...incoming,
|
|
250
|
+
historyEvent: incoming.historyEvent,
|
|
251
|
+
...(incoming.revision === undefined ? {} : { timestamp: message.timestamp }),
|
|
252
|
+
} : message);
|
|
232
253
|
}
|
|
@@ -115,19 +115,28 @@ export function readSandboxHistoryPage(body, binding, before, locale = 'zh-CN')
|
|
|
115
115
|
|| !validTime(item.timestamp) || before !== undefined && Number(item.sequence) >= before)
|
|
116
116
|
fail();
|
|
117
117
|
previous = Number(item.sequence);
|
|
118
|
-
if (item.type === 'message.created') {
|
|
118
|
+
if (item.type === 'message.created' || item.type === 'message.updated') {
|
|
119
119
|
const message = record(item.message), ref = record(message?.ref), actor = record(message?.actor);
|
|
120
120
|
if (!message || !ref || !text(ref.id) || !matches(ref.conversation) || !validTime(message.timestamp)
|
|
121
121
|
|| !Array.isArray(message.segments) || !message.segments.every(segment => text(record(segment)?.type) && record(record(segment)?.data))
|
|
122
122
|
|| message.actor !== undefined && (!actor || !text(actor.id) || actor.displayName !== undefined && typeof actor.displayName !== 'string')
|
|
123
123
|
|| message.contentStatus !== undefined && message.contentStatus !== 'unavailable')
|
|
124
124
|
fail();
|
|
125
|
+
if (message.revision !== undefined && (!Number.isSafeInteger(message.revision) || Number(message.revision) < 0)
|
|
126
|
+
|| item.type === 'message.updated' && (!Number.isSafeInteger(message.revision) || Number(message.revision) <= 0)
|
|
127
|
+
|| message.recalled !== undefined && message.recalled !== true)
|
|
128
|
+
fail();
|
|
125
129
|
const content = message.contentStatus === 'unavailable'
|
|
126
130
|
? [{ type: 'text', data: { text: sandboxText(locale, '消息正文未保存') } }] : message.segments;
|
|
127
131
|
messages.push({ id: ref.id, type: actor ? 'sent' : 'received', channelType: binding.scene.type, channelId: binding.scene.id,
|
|
128
132
|
channelName: binding.scene.name, senderId: actor ? String(actor.id) : 'endpoint',
|
|
129
133
|
senderName: actor ? String(actor.displayName || actor.id) : binding.scope.id, content, timestamp: message.timestamp,
|
|
130
|
-
historySequence: previous,
|
|
134
|
+
historySequence: previous, historyEvent: { type: item.type, sequence: previous },
|
|
135
|
+
...(item.type === 'message.created' ? { historyCreatedSequence: previous } : {}),
|
|
136
|
+
...(hasPlaygroundKeyboard(content) ? { interactionReadOnly: true } : {}),
|
|
137
|
+
...(message.revision === undefined ? {} : { revision: Number(message.revision), streaming: false }),
|
|
138
|
+
...(message.recalled === true ? { recalled: true } : {}),
|
|
139
|
+
});
|
|
131
140
|
}
|
|
132
141
|
else if (item.type === 'message.recalled') {
|
|
133
142
|
const ref = record(item.messageRef);
|
|
@@ -147,15 +156,39 @@ export function readSandboxHistoryPage(body, binding, before, locale = 'zh-CN')
|
|
|
147
156
|
/** Stable message identity joins canonical events, optimistic inputs and native wire receipts. */
|
|
148
157
|
export function mergeSandboxHistory(current, history) {
|
|
149
158
|
const key = (row) => JSON.stringify([row.channelType, row.channelId, row.type, row.id]);
|
|
150
|
-
const
|
|
159
|
+
const targetKey = (row, id = row.id) => JSON.stringify([row.channelType, row.channelId, id]);
|
|
160
|
+
const lowest = (left, right) => left === undefined ? right : right === undefined ? left : Math.min(left, right);
|
|
161
|
+
const recalled = new Set(), recallSequences = new Map();
|
|
162
|
+
for (const row of [...current, ...history]) {
|
|
163
|
+
if (!row.recalledMessageId)
|
|
164
|
+
continue;
|
|
165
|
+
const target = targetKey(row, row.recalledMessageId);
|
|
166
|
+
recalled.add(target);
|
|
167
|
+
if (row.historySequence !== undefined)
|
|
168
|
+
recallSequences.set(target, lowest(recallSequences.get(target), row.historySequence));
|
|
169
|
+
}
|
|
170
|
+
// An earlier page can reveal that a previously loaded raw update followed a recall.
|
|
171
|
+
const afterRecall = (row) => row.historyEvent?.type === 'message.updated'
|
|
172
|
+
&& recallSequences.has(targetKey(row)) && row.historyEvent.sequence >= recallSequences.get(targetKey(row));
|
|
173
|
+
const rows = new Map(current.filter(row => !afterRecall(row)).map(row => [key(row), row]));
|
|
151
174
|
for (const row of history) {
|
|
175
|
+
if (afterRecall(row))
|
|
176
|
+
continue;
|
|
152
177
|
const existing = rows.get(key(row));
|
|
153
|
-
|
|
154
|
-
|
|
178
|
+
const beforeRecall = Boolean(row.historyEvent && row.historyEvent.sequence < (recallSequences.get(targetKey(row)) ?? -1));
|
|
179
|
+
const newer = (!existing?.recalled || row.recalled || beforeRecall) && ((row.revision ?? 0) > (existing?.revision ?? 0)
|
|
180
|
+
|| (row.revision ?? 0) === (existing?.revision ?? 0) && row.historyEvent && existing?.historyEvent
|
|
181
|
+
&& row.historyEvent.sequence < existing.historyEvent.sequence);
|
|
182
|
+
const createdSequence = lowest(existing?.historyCreatedSequence, row.historyCreatedSequence);
|
|
183
|
+
rows.set(key(row), existing ? { ...(newer ? { ...existing, ...row } : { ...row, ...existing }),
|
|
184
|
+
historySequence: createdSequence ?? lowest(existing.historySequence, row.historySequence), historyCreatedSequence: createdSequence,
|
|
185
|
+
historyEvent: newer ? row.historyEvent : existing.historyEvent,
|
|
186
|
+
...(!newer && existing.interactionReadOnly === false ? { interactionReadOnly: false } : row.interactionReadOnly ? { interactionReadOnly: true } : {}),
|
|
187
|
+
...(existing.recalled || row.recalled ? { recalled: true } : {}),
|
|
188
|
+
} : row);
|
|
155
189
|
}
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
? { ...row, recalled: true, ...(hasPlaygroundKeyboard(row.content) ? { interactionReadOnly: true } : {}) } : row)
|
|
190
|
+
return [...rows.values()].map(row => row.recalled || recalled.has(targetKey(row))
|
|
191
|
+
? { ...row, recalled: true, streaming: false, ...(hasPlaygroundKeyboard(row.content) ? { interactionReadOnly: true } : {}) } : row)
|
|
159
192
|
.sort((a, b) => a.timestamp - b.timestamp || (a.channelType === b.channelType && a.channelId === b.channelId
|
|
160
193
|
? (a.historySequence ?? Number.MAX_SAFE_INTEGER) - (b.historySequence ?? Number.MAX_SAFE_INTEGER) : 0));
|
|
161
194
|
}
|
|
@@ -121,18 +121,26 @@ export function readSandboxHistoryPage(body: unknown, binding: SandboxHistoryBin
|
|
|
121
121
|
if (!item || !Number.isSafeInteger(item.sequence) || Number(item.sequence) <= previous || !text(item.type)
|
|
122
122
|
|| !validTime(item.timestamp) || before !== undefined && Number(item.sequence) >= before) fail();
|
|
123
123
|
previous = Number(item.sequence);
|
|
124
|
-
if (item.type === 'message.created') {
|
|
124
|
+
if (item.type === 'message.created' || item.type === 'message.updated') {
|
|
125
125
|
const message = record(item.message), ref = record(message?.ref), actor = record(message?.actor);
|
|
126
126
|
if (!message || !ref || !text(ref.id) || !matches(ref.conversation) || !validTime(message.timestamp)
|
|
127
127
|
|| !Array.isArray(message.segments) || !message.segments.every(segment => text(record(segment)?.type) && record(record(segment)?.data))
|
|
128
128
|
|| message.actor !== undefined && (!actor || !text(actor.id) || actor.displayName !== undefined && typeof actor.displayName !== 'string')
|
|
129
129
|
|| message.contentStatus !== undefined && message.contentStatus !== 'unavailable') fail();
|
|
130
|
+
if (message.revision !== undefined && (!Number.isSafeInteger(message.revision) || Number(message.revision) < 0)
|
|
131
|
+
|| item.type === 'message.updated' && (!Number.isSafeInteger(message.revision) || Number(message.revision) <= 0)
|
|
132
|
+
|| message.recalled !== undefined && message.recalled !== true) fail();
|
|
130
133
|
const content: MessageSegment[] = message.contentStatus === 'unavailable'
|
|
131
134
|
? [{ type: 'text', data: { text: sandboxText(locale, '消息正文未保存') } }] : message.segments as MessageSegment[];
|
|
132
135
|
messages.push({ id: ref.id, type: actor ? 'sent' : 'received', channelType: binding.scene.type, channelId: binding.scene.id,
|
|
133
136
|
channelName: binding.scene.name, senderId: actor ? String(actor.id) : 'endpoint',
|
|
134
137
|
senderName: actor ? String(actor.displayName || actor.id) : binding.scope.id, content, timestamp: message.timestamp,
|
|
135
|
-
historySequence: previous,
|
|
138
|
+
historySequence: previous, historyEvent: { type: item.type, sequence: previous },
|
|
139
|
+
...(item.type === 'message.created' ? { historyCreatedSequence: previous } : {}),
|
|
140
|
+
...(hasPlaygroundKeyboard(content) ? { interactionReadOnly: true } : {}),
|
|
141
|
+
...(message.revision === undefined ? {} : { revision: Number(message.revision), streaming: false }),
|
|
142
|
+
...(message.recalled === true ? { recalled: true } : {}),
|
|
143
|
+
});
|
|
136
144
|
} else if (item.type === 'message.recalled') {
|
|
137
145
|
const ref = record(item.messageRef);
|
|
138
146
|
if (item.messageRef !== undefined && (!ref || !text(ref.id) || !matches(ref.conversation))) fail();
|
|
@@ -150,15 +158,36 @@ export function readSandboxHistoryPage(body: unknown, binding: SandboxHistoryBin
|
|
|
150
158
|
/** Stable message identity joins canonical events, optimistic inputs and native wire receipts. */
|
|
151
159
|
export function mergeSandboxHistory(current: readonly PlaygroundMessage[], history: readonly PlaygroundMessage[]): PlaygroundMessage[] {
|
|
152
160
|
const key = (row: PlaygroundMessage) => JSON.stringify([row.channelType, row.channelId, row.type, row.id]);
|
|
153
|
-
const
|
|
161
|
+
const targetKey = (row: PlaygroundMessage, id = row.id) => JSON.stringify([row.channelType, row.channelId, id]);
|
|
162
|
+
const lowest = (left?: number, right?: number) => left === undefined ? right : right === undefined ? left : Math.min(left, right);
|
|
163
|
+
const recalled = new Set<string>(), recallSequences = new Map<string, number>();
|
|
164
|
+
for (const row of [...current, ...history]) {
|
|
165
|
+
if (!row.recalledMessageId) continue;
|
|
166
|
+
const target = targetKey(row, row.recalledMessageId);
|
|
167
|
+
recalled.add(target);
|
|
168
|
+
if (row.historySequence !== undefined) recallSequences.set(target, lowest(recallSequences.get(target), row.historySequence)!);
|
|
169
|
+
}
|
|
170
|
+
// An earlier page can reveal that a previously loaded raw update followed a recall.
|
|
171
|
+
const afterRecall = (row: PlaygroundMessage) => row.historyEvent?.type === 'message.updated'
|
|
172
|
+
&& recallSequences.has(targetKey(row)) && row.historyEvent.sequence >= recallSequences.get(targetKey(row))!;
|
|
173
|
+
const rows = new Map(current.filter(row => !afterRecall(row)).map(row => [key(row), row]));
|
|
154
174
|
for (const row of history) {
|
|
175
|
+
if (afterRecall(row)) continue;
|
|
155
176
|
const existing = rows.get(key(row));
|
|
156
|
-
|
|
157
|
-
|
|
177
|
+
const beforeRecall = Boolean(row.historyEvent && row.historyEvent.sequence < (recallSequences.get(targetKey(row)) ?? -1));
|
|
178
|
+
const newer = (!existing?.recalled || row.recalled || beforeRecall) && ((row.revision ?? 0) > (existing?.revision ?? 0)
|
|
179
|
+
|| (row.revision ?? 0) === (existing?.revision ?? 0) && row.historyEvent && existing?.historyEvent
|
|
180
|
+
&& row.historyEvent.sequence < existing.historyEvent.sequence);
|
|
181
|
+
const createdSequence = lowest(existing?.historyCreatedSequence, row.historyCreatedSequence);
|
|
182
|
+
rows.set(key(row), existing ? { ...(newer ? { ...existing, ...row } : { ...row, ...existing }),
|
|
183
|
+
historySequence: createdSequence ?? lowest(existing.historySequence, row.historySequence), historyCreatedSequence: createdSequence,
|
|
184
|
+
historyEvent: newer ? row.historyEvent : existing.historyEvent,
|
|
185
|
+
...(!newer && existing.interactionReadOnly === false ? { interactionReadOnly: false } : row.interactionReadOnly ? { interactionReadOnly: true } : {}),
|
|
186
|
+
...(existing.recalled || row.recalled ? { recalled: true } : {}),
|
|
187
|
+
} : row);
|
|
158
188
|
}
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
? { ...row, recalled: true, ...(hasPlaygroundKeyboard(row.content) ? { interactionReadOnly: true } : {}) } : row)
|
|
189
|
+
return [...rows.values()].map(row => row.recalled || recalled.has(targetKey(row))
|
|
190
|
+
? { ...row, recalled: true, streaming: false, ...(hasPlaygroundKeyboard(row.content) ? { interactionReadOnly: true } : {}) } : row)
|
|
162
191
|
.sort((a, b) => a.timestamp - b.timestamp || (a.channelType === b.channelType && a.channelId === b.channelId
|
|
163
192
|
? (a.historySequence ?? Number.MAX_SAFE_INTEGER) - (b.historySequence ?? Number.MAX_SAFE_INTEGER) : 0));
|
|
164
193
|
}
|
package/schema.json
CHANGED
|
@@ -3,6 +3,17 @@
|
|
|
3
3
|
"type": "object",
|
|
4
4
|
"additionalProperties": false,
|
|
5
5
|
"properties": {
|
|
6
|
+
"streaming": {
|
|
7
|
+
"type": "boolean",
|
|
8
|
+
"default": true,
|
|
9
|
+
"description": "Publish supported replies while generating. Set false to send only complete replies."
|
|
10
|
+
},
|
|
11
|
+
"streamingIntervalMs": {
|
|
12
|
+
"type": "number",
|
|
13
|
+
"minimum": 0,
|
|
14
|
+
"default": 500,
|
|
15
|
+
"description": "Minimum delay in milliseconds between reply updates; the first update is immediate."
|
|
16
|
+
},
|
|
6
17
|
"master": {
|
|
7
18
|
"type": [
|
|
8
19
|
"string",
|
|
@@ -70,12 +81,42 @@
|
|
|
70
81
|
"type": "string",
|
|
71
82
|
"description": "Sandbox owner user ID"
|
|
72
83
|
},
|
|
84
|
+
"streaming": {
|
|
85
|
+
"type": "boolean",
|
|
86
|
+
"description": "Publish supported replies while generating. Set false to send only complete replies."
|
|
87
|
+
},
|
|
88
|
+
"streamingIntervalMs": {
|
|
89
|
+
"type": "number",
|
|
90
|
+
"minimum": 0,
|
|
91
|
+
"description": "Minimum delay in milliseconds between reply updates; the first update is immediate."
|
|
92
|
+
},
|
|
73
93
|
"commandPrefix": {
|
|
74
94
|
"type": "string"
|
|
75
95
|
},
|
|
76
96
|
"id": {
|
|
77
97
|
"type": "string",
|
|
78
98
|
"description": "Sandbox bot name"
|
|
99
|
+
},
|
|
100
|
+
"nickname": {
|
|
101
|
+
"type": [
|
|
102
|
+
"string",
|
|
103
|
+
"null"
|
|
104
|
+
],
|
|
105
|
+
"description": "账号昵称兜底",
|
|
106
|
+
"x-i18n": {
|
|
107
|
+
"en": {
|
|
108
|
+
"description": "Fallback account nickname"
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
},
|
|
112
|
+
"profile": {
|
|
113
|
+
"$ref": "#/$defs/selfProfileFallback",
|
|
114
|
+
"description": "账号资料兜底",
|
|
115
|
+
"x-i18n": {
|
|
116
|
+
"en": {
|
|
117
|
+
"description": "Fallback account profile"
|
|
118
|
+
}
|
|
119
|
+
}
|
|
79
120
|
}
|
|
80
121
|
},
|
|
81
122
|
"required": [
|
|
@@ -97,9 +138,93 @@
|
|
|
97
138
|
"description": "Command prefix. The default empty string allows unprefixed commands; '/' requires a leading slash. Each endpoints[i] can override it."
|
|
98
139
|
}
|
|
99
140
|
}
|
|
141
|
+
},
|
|
142
|
+
"nickname": {
|
|
143
|
+
"type": [
|
|
144
|
+
"string",
|
|
145
|
+
"null"
|
|
146
|
+
],
|
|
147
|
+
"description": "账号昵称兜底",
|
|
148
|
+
"x-i18n": {
|
|
149
|
+
"en": {
|
|
150
|
+
"description": "Fallback account nickname"
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
},
|
|
154
|
+
"profile": {
|
|
155
|
+
"$ref": "#/$defs/selfProfileFallback",
|
|
156
|
+
"description": "账号资料兜底",
|
|
157
|
+
"x-i18n": {
|
|
158
|
+
"en": {
|
|
159
|
+
"description": "Fallback account profile"
|
|
160
|
+
}
|
|
161
|
+
}
|
|
100
162
|
}
|
|
101
163
|
},
|
|
102
164
|
"required": [
|
|
103
165
|
"endpoints"
|
|
104
|
-
]
|
|
166
|
+
],
|
|
167
|
+
"$defs": {
|
|
168
|
+
"selfProfileFallback": {
|
|
169
|
+
"type": "object",
|
|
170
|
+
"additionalProperties": false,
|
|
171
|
+
"properties": {
|
|
172
|
+
"gender": {
|
|
173
|
+
"type": [
|
|
174
|
+
"string",
|
|
175
|
+
"null"
|
|
176
|
+
],
|
|
177
|
+
"enum": [
|
|
178
|
+
"male",
|
|
179
|
+
"female",
|
|
180
|
+
"other",
|
|
181
|
+
"unknown",
|
|
182
|
+
null
|
|
183
|
+
]
|
|
184
|
+
},
|
|
185
|
+
"age": {
|
|
186
|
+
"type": [
|
|
187
|
+
"integer",
|
|
188
|
+
"null"
|
|
189
|
+
],
|
|
190
|
+
"minimum": 0
|
|
191
|
+
},
|
|
192
|
+
"birthday": {
|
|
193
|
+
"type": [
|
|
194
|
+
"string",
|
|
195
|
+
"null"
|
|
196
|
+
],
|
|
197
|
+
"pattern": "^\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])$"
|
|
198
|
+
},
|
|
199
|
+
"signature": {
|
|
200
|
+
"type": [
|
|
201
|
+
"string",
|
|
202
|
+
"null"
|
|
203
|
+
]
|
|
204
|
+
},
|
|
205
|
+
"avatar": {
|
|
206
|
+
"type": [
|
|
207
|
+
"string",
|
|
208
|
+
"null"
|
|
209
|
+
],
|
|
210
|
+
"pattern": "^(https?://[^\\s/?#]+(?:[/?#].*)?|)$"
|
|
211
|
+
},
|
|
212
|
+
"interests": {
|
|
213
|
+
"type": [
|
|
214
|
+
"array",
|
|
215
|
+
"null"
|
|
216
|
+
],
|
|
217
|
+
"items": {
|
|
218
|
+
"type": "string"
|
|
219
|
+
}
|
|
220
|
+
},
|
|
221
|
+
"bio": {
|
|
222
|
+
"type": [
|
|
223
|
+
"string",
|
|
224
|
+
"null"
|
|
225
|
+
]
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
105
230
|
}
|
package/src/adapter.ts
CHANGED
|
@@ -10,7 +10,7 @@ export class SandboxAdapter extends Adapter<SandboxWsEndpoint, SandboxEndpointCo
|
|
|
10
10
|
constructor(context: AdapterContext<SandboxEndpointConfig>) { super(); this.#context = context; }
|
|
11
11
|
override get configurationIdentityFields(): readonly string[] { return ['id']; }
|
|
12
12
|
// owner binds the synthetic sender's existing permissions and is not a runtime connection setting.
|
|
13
|
-
override get configurationUpdateFields(): readonly string[] { return []; }
|
|
13
|
+
override get configurationUpdateFields(): readonly string[] { return ['streaming', 'streamingIntervalMs']; }
|
|
14
14
|
protected override validateConfiguration(config: SandboxEndpointConfig): void { resolveSandboxEndpoint(config); }
|
|
15
15
|
protected createEndpoint(input: SandboxEndpointConfig, execution: EndpointCreationContext): SandboxWsEndpoint {
|
|
16
16
|
return new SandboxWsEndpoint({ id: execution.canonicalId, defaults: resolveSandboxEndpoint(input),
|
package/src/endpoint.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createMessages, resolveLocale, type Locale } from 'zhin.js/i18n';
|
|
2
|
-
import { createEndpointSpecification, endpointSpec, type Endpoint, type EndpointSpecification, type EndpointSendRequest
|
|
2
|
+
import { createEndpointSpecification, endpointSpec, type Endpoint, type EndpointSpecification, type EndpointSendRequest,
|
|
3
|
+
type EndpointStreaming, type EndpointStreamRequest, type EndpointMessageStream, type EndpointStreamAcknowledgement } from 'zhin.js/adapter';
|
|
3
4
|
/**
|
|
4
5
|
* SandboxWsEndpoint — WebSocket lifecycle and OutboundMessageService bridge for /sandbox.
|
|
5
6
|
*/
|
|
@@ -161,6 +162,9 @@ export class SandboxWsEndpoint extends SandboxClient<SandboxConnection> implemen
|
|
|
161
162
|
start: () => this.#start(), open: () => this.#openEndpoint(),
|
|
162
163
|
close: () => this.#close(), stop: () => this.#stop(),
|
|
163
164
|
send: request => this.#send(request),
|
|
165
|
+
...(options.defaults.streaming ? { streaming: Object.freeze<EndpointStreaming>({ mode: 'native',
|
|
166
|
+
minIntervalMs: options.defaults.streamingIntervalMs, supports: request => this.#supportsStream(request),
|
|
167
|
+
open: request => this.#openStream(request) }) } : {}),
|
|
164
168
|
get transportState() { return readTransportState(); },
|
|
165
169
|
});
|
|
166
170
|
}
|
|
@@ -251,6 +255,42 @@ export class SandboxWsEndpoint extends SandboxClient<SandboxConnection> implemen
|
|
|
251
255
|
return messageId;
|
|
252
256
|
}
|
|
253
257
|
|
|
258
|
+
#supportsStream(request: Pick<EndpointStreamRequest, 'conversation' | 'source'>): boolean {
|
|
259
|
+
return !request.conversation.parent && request.conversation.threadId === undefined
|
|
260
|
+
&& ['private', 'group', 'channel'].includes(request.conversation.kind);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
#openStream(request: EndpointStreamRequest): EndpointMessageStream | undefined {
|
|
264
|
+
if (!this.#supportsStream(request)) return undefined;
|
|
265
|
+
const messageId = randomUUID();
|
|
266
|
+
let revision = 0, timestamp: number | undefined, acceptedText = '';
|
|
267
|
+
let state: 'active' | 'completed' | 'cancelled' = 'active';
|
|
268
|
+
let last: EndpointStreamAcknowledgement | undefined;
|
|
269
|
+
const submit = async (text: string, finish: boolean): Promise<EndpointStreamAcknowledgement> => {
|
|
270
|
+
if (state === 'completed') {
|
|
271
|
+
if (finish && text === acceptedText) return last!;
|
|
272
|
+
throw new EndpointDeliveryError('stream_closed', 'Sandbox reply stream has completed', 'not_sent');
|
|
273
|
+
}
|
|
274
|
+
if (state === 'cancelled' || request.signal?.aborted || !this.#open) {
|
|
275
|
+
throw new EndpointDeliveryError('endpoint_inactive', 'Sandbox reply stream has ended', 'not_sent');
|
|
276
|
+
}
|
|
277
|
+
if (!text.startsWith(acceptedText)) throw new EndpointDeliveryError('invalid_payload', 'Sandbox stream text must preserve the confirmed prefix', 'not_sent');
|
|
278
|
+
const sentAt = timestamp ?? Date.now();
|
|
279
|
+
this.#send({ conversation: request.conversation, signal: request.signal, payload: {
|
|
280
|
+
messageId, revision: revision + 1, streaming: !finish, timestamp: sentAt,
|
|
281
|
+
content: [...(request.prefix ?? []), request.format === 'markdown'
|
|
282
|
+
? { type: 'markdown', data: { content: text } } : { type: 'text', data: { text } }],
|
|
283
|
+
} });
|
|
284
|
+
timestamp = sentAt; revision += 1; acceptedText = text;
|
|
285
|
+
last = { status: 'sent', messageId, acceptedText };
|
|
286
|
+
if (finish) state = 'completed';
|
|
287
|
+
return last;
|
|
288
|
+
};
|
|
289
|
+
return Object.freeze<EndpointMessageStream>({ write: text => submit(text, false), finish: text => submit(text, true),
|
|
290
|
+
cancel: () => { if (state === 'active') state = 'cancelled'; },
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
|
|
254
294
|
#subscribers(scene: { readonly type: string; readonly id: string }, echo = false): SandboxConnection[] {
|
|
255
295
|
return [...this.connectionRecords.values()].filter(connection => !connection.placeholder && connection.canExecute
|
|
256
296
|
&& (!echo || connection.scoped)
|
package/src/protocol.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { EndpointProfileConfiguration } from 'zhin.js/adapter';
|
|
1
2
|
/** Sandbox WebSocket wire protocol helpers (no legacy Adapter/Endpoint). */
|
|
2
3
|
|
|
3
4
|
import { readFileSync } from 'node:fs';
|
|
@@ -41,12 +42,16 @@ export type ResolvedSandboxBot = {
|
|
|
41
42
|
readonly id: string;
|
|
42
43
|
readonly owner: string;
|
|
43
44
|
readonly randomNamePerConnection: boolean;
|
|
45
|
+
readonly streaming: boolean;
|
|
46
|
+
readonly streamingIntervalMs: number;
|
|
44
47
|
};
|
|
45
48
|
|
|
46
49
|
/** One endpoint config after AdapterIndex expands `plugins.<instanceKey>.endpoints`. */
|
|
47
|
-
export interface SandboxEndpointConfig {
|
|
50
|
+
export interface SandboxEndpointConfig extends EndpointProfileConfiguration {
|
|
48
51
|
readonly id?: string;
|
|
49
52
|
readonly owner?: string;
|
|
53
|
+
readonly streaming?: boolean;
|
|
54
|
+
readonly streamingIntervalMs?: number;
|
|
50
55
|
}
|
|
51
56
|
|
|
52
57
|
export function resolveSandboxEndpoint(
|
|
@@ -54,6 +59,8 @@ export function resolveSandboxEndpoint(
|
|
|
54
59
|
): ResolvedSandboxBot {
|
|
55
60
|
const id = optionalEndpointField(config.id) ?? 'sandbox-bot';
|
|
56
61
|
const owner = optionalEndpointField(config.owner) ?? 'sandbox-user';
|
|
62
|
+
const streamingIntervalMs = config.streamingIntervalMs ?? 500;
|
|
63
|
+
if (!Number.isFinite(streamingIntervalMs) || streamingIntervalMs < 0) throw new TypeError('streamingIntervalMs must be a non-negative finite number');
|
|
57
64
|
return {
|
|
58
65
|
context: 'sandbox',
|
|
59
66
|
id,
|
|
@@ -62,6 +69,8 @@ export function resolveSandboxEndpoint(
|
|
|
62
69
|
// across browser reconnects and Host restarts so a persisted playground
|
|
63
70
|
// session resumes the same Agent context.
|
|
64
71
|
randomNamePerConnection: false,
|
|
72
|
+
streaming: config.streaming !== false,
|
|
73
|
+
streamingIntervalMs,
|
|
65
74
|
};
|
|
66
75
|
}
|
|
67
76
|
|