@zhin.js/adapter-sandbox 1.1.22 → 1.1.24

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 CHANGED
@@ -1,5 +1,83 @@
1
1
  # @zhin.js/adapter-process
2
2
 
3
+ ## 1.1.24
4
+
5
+ ### Patch Changes
6
+
7
+ - 41ff1a5: ADR 0044 C5: every official adapter now declares a capability `profile` (its `segments` moved into `profile.default.messaging.segments`). icqq declares the complete profile (per conversation kind: scene, all 14 actions with real limits, events, feedback, delivery) and implements the seven new management ports (`pokeUser`, `unmuteGroupMember`, `muteAllGroupMembers`, `setGroupCard`, `setGroupTitle`, `setGroupEssence`, `inviteGroupMember`) with fresh bot-role reads. qq official declares its passive reply windows; undeclared capabilities stay unsupported.
8
+ - 299863a: ADR 0044 C3: runtime consumers read capabilities instead of platform names. Scene facts (group info, member profile) are queried where the profile declares `scene.groupInfo` / `scene.memberProfile`; activity feedback (reaction, typing, status message, refresh interval, quote-only delivery) follows `feedback`, `actions.reaction` and `delivery.proactive` and the per-platform table is gone; large inline media is spooled only where `delivery.spool` is declared; the sandbox ingress and its console shell follow a new additive `runtime.sandbox` capability. `defineAgentTool` and Skill frontmatter accept `requiresCapabilities` (for example `actions.mute`), evaluated against the per-turn `TurnCapabilities`, so moderation tools disappear when the Bot is not an administrator and return when it is; the icqq/qq keyword boost in tool selection is removed and the icqq group-admin tools are tagged. The `icqq` command-line special case in the exec policy is now a generic `registerSensitiveExecCommand` rule registered by the icqq plugin. `EndpointCapabilities` gains a serializable per-kind `kinds` view. Adapters without a profile keep their previous behaviour (their derived profile also reads the management ports they implement).
9
+ - 4fe49b5: 支持配置按需生效:分离保存与有效版本,独立变更先应用,账号资料更新保留连接,模型按回合使用确定版本;Console 返回结构化应用结果。监听改为仅显式 --watch 启用,开发模板显式选择源码和配置监听。
10
+
11
+ 自变更消费配置应用回执,避免已处理配置被二次重载;持久化本次写入修订和应用结果,未知结果或修订冲突时停止自动续作并保留现场,恢复不会覆盖未经本次变更确认的配置。
12
+
13
+ - cce07db: Refresh adapter Console pages with lightweight black/white/gray surfaces, clearer account and login workflows, responsive layouts, accessible focus states, and self-contained light/dark styling. Apply the shared visual language to Sandbox conversations and Bilibili comment review while preserving runtime authority and platform send paths.
14
+ - Updated dependencies [b249e5e]
15
+ - Updated dependencies [57661f6]
16
+ - Updated dependencies [cbd3f14]
17
+ - Updated dependencies [299863a]
18
+ - Updated dependencies [aaa93d7]
19
+ - Updated dependencies [bd524d1]
20
+ - Updated dependencies [126ae99]
21
+ - Updated dependencies [4fe49b5]
22
+ - Updated dependencies [cce07db]
23
+ - Updated dependencies [b652db3]
24
+ - Updated dependencies [0315ba0]
25
+ - @zhin.js/core@1.1.56
26
+ - @zhin.js/adapter@1.1.28
27
+ - @zhin.js/im-contract@1.1.11
28
+ - @zhin.js/skill@1.1.13
29
+ - @zhin.js/host-http@1.1.14
30
+ - @zhin.js/feature-kit@1.1.12
31
+ - @zhin.js/client@1.1.24
32
+ - @zhin.js/page@1.1.14
33
+
34
+ ## 1.1.23
35
+
36
+ ### Patch Changes
37
+
38
+ - 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.
39
+
40
+ 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.
41
+
42
+ 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.
43
+
44
+ - 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.
45
+
46
+ 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.
47
+
48
+ 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.
49
+
50
+ - 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.
51
+
52
+ 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.
53
+
54
+ 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.
55
+
56
+ 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.
57
+
58
+ - 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.
59
+
60
+ Seek past completed conversation-history backfill batches instead of re-scanning the migrated prefix. Preserve original event data, retention and compatible older writers.
61
+
62
+ Report terminal provider quota and billing failures after publication without regeneration, and isolate synchronous diagnostic failures from provider outcomes and retry/fallback decisions.
63
+
64
+ - Updated dependencies [b88e988]
65
+ - Updated dependencies [f78eb84]
66
+ - Updated dependencies [c15cef9]
67
+ - Updated dependencies [b0c02a2]
68
+ - Updated dependencies [af8f803]
69
+ - Updated dependencies [26fda97]
70
+ - Updated dependencies [976886c]
71
+ - Updated dependencies [032dc96]
72
+ - @zhin.js/adapter@1.1.27
73
+ - @zhin.js/client@1.1.23
74
+ - @zhin.js/im-contract@1.1.10
75
+ - @zhin.js/core@1.1.55
76
+ - @zhin.js/page@1.1.13
77
+ - @zhin.js/host-http@1.1.13
78
+ - @zhin.js/feature-kit@1.1.11
79
+ - @zhin.js/skill@1.1.12
80
+
3
81
  ## 1.1.22
4
82
 
5
83
  ### 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
- - `content` 是消息段数组。文本、`html`(JSX 卡片,见上文 `html: direct`)、按钮等段原样透传。
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
 
@@ -8,12 +8,22 @@ import {} from "../../lib/protocol.js";
8
8
  export { SandboxWsEndpoint } from "../../lib/endpoint.js";
9
9
  export default defineAdapter({
10
10
  capabilities: ['inbound', 'outbound'],
11
- // Console UI 直连 URL 媒体、直接渲染 base64 内联媒体;path 由端点读盘
12
- // 物化为 base64 内联(sandbox 无平台上传通道)。交互段由 Console 原生承载。
13
- segments: {
14
- html: 'direct',
15
- outboundMedia: ['url', 'base64', 'path'],
16
- interactive: 'native',
11
+ profile: {
12
+ default: {
13
+ messaging: {
14
+ // Console UI 直连 URL 媒体、直接渲染 base64 内联媒体;path 由端点读盘
15
+ // 物化为 base64 内联(sandbox 无平台上传通道)。交互段由 Console 原生承载。
16
+ segments: {
17
+ html: 'direct',
18
+ markdown: 'native',
19
+ outboundMedia: ['url', 'base64', 'path'],
20
+ interactive: 'native',
21
+ },
22
+ },
23
+ delivery: { send: true, proactive: true, spool: true },
24
+ // The authenticated local ingress: its configured owner may turn wire metadata into agent-run authority.
25
+ runtime: { sandbox: true },
26
+ },
17
27
  },
18
28
  createAdapter: context => new SandboxAdapter(context),
19
29
  });
@@ -12,12 +12,22 @@ export type { SandboxEndpointOptions } from '../../src/endpoint.js';
12
12
 
13
13
  export default defineAdapter<SandboxEndpointConfig>({
14
14
  capabilities: ['inbound', 'outbound'],
15
- // Console UI 直连 URL 媒体、直接渲染 base64 内联媒体;path 由端点读盘
16
- // 物化为 base64 内联(sandbox 无平台上传通道)。交互段由 Console 原生承载。
17
- segments: {
18
- html: 'direct',
19
- outboundMedia: ['url', 'base64', 'path'],
20
- interactive: 'native',
15
+ profile: {
16
+ default: {
17
+ messaging: {
18
+ // Console UI 直连 URL 媒体、直接渲染 base64 内联媒体;path 由端点读盘
19
+ // 物化为 base64 内联(sandbox 无平台上传通道)。交互段由 Console 原生承载。
20
+ segments: {
21
+ html: 'direct',
22
+ markdown: 'native',
23
+ outboundMedia: ['url', 'base64', 'path'],
24
+ interactive: 'native',
25
+ },
26
+ },
27
+ delivery: { send: true, proactive: true, spool: true },
28
+ // The authenticated local ingress: its configured owner may turn wire metadata into agent-run authority.
29
+ runtime: { sandbox: true },
30
+ },
21
31
  },
22
32
  createAdapter: context => new SandboxAdapter(context),
23
33
  });
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
- /** Sandbox WebSocket wire protocol helpers (no legacy Adapter/Endpoint). */
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.22",
3
+ "version": "1.1.24",
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.26",
51
- "@zhin.js/client": "1.1.22",
50
+ "@zhin.js/adapter": "1.1.28",
51
+ "@zhin.js/client": "1.1.24",
52
52
  "@zhin.js/console-contract": "1.1.3",
53
- "@zhin.js/core": "1.1.54",
54
- "@zhin.js/feature-kit": "1.1.10",
55
- "@zhin.js/host-http": "1.1.12",
56
- "@zhin.js/im-contract": "1.1.9",
53
+ "@zhin.js/core": "1.1.56",
54
+ "@zhin.js/feature-kit": "1.1.12",
55
+ "@zhin.js/host-http": "1.1.14",
56
+ "@zhin.js/im-contract": "1.1.11",
57
57
  "@zhin.js/logger": "1.1.2",
58
- "@zhin.js/page": "1.1.12",
59
- "@zhin.js/skill": "1.1.11"
58
+ "@zhin.js/page": "1.1.14",
59
+ "@zhin.js/skill": "1.1.13"
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.19",
68
- "@zhin.js/runtime": "1.1.16",
69
- "zhin.js": "1.1.19"
67
+ "@zhin.js/pagemanager": "1.1.21",
68
+ "@zhin.js/runtime": "1.1.18",
69
+ "zhin.js": "1.1.21"
70
70
  },
71
71
  "peerDependencies": {
72
72
  "react": "^19.0.0",
73
- "@zhin.js/adapter": "^1.1.26",
73
+ "@zhin.js/adapter": "^1.1.28",
74
74
  "@zhin.js/console-contract": "^1.1.3",
75
- "@zhin.js/core": "^1.1.54",
76
- "@zhin.js/host-http": "^1.1.12",
77
- "@zhin.js/page": "^1.1.12",
78
- "zhin.js": "^1.1.19"
75
+ "@zhin.js/core": "^1.1.56",
76
+ "@zhin.js/host-http": "^1.1.14",
77
+ "@zhin.js/page": "^1.1.14",
78
+ "zhin.js": "^1.1.21"
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.0.0"
101
+ "api": "^2.1.0"
102
102
  },
103
103
  {
104
104
  "package": "@zhin.js/page",
@@ -347,21 +347,7 @@ const RichTextEditor = forwardRef(({ locale = 'zh-CN', placeholder = sandboxText
347
347
  replaceAtTrigger,
348
348
  getContent
349
349
  }));
350
- return (_jsx("div", { ref: editorRef, contentEditable: true, suppressContentEditableWarning: true, onInput: handleChange, onKeyDown: handleKeyDown, onPaste: handlePaste, "data-placeholder": placeholder, className: "rich-text-editor", style: {
351
- width: '100%',
352
- minHeight,
353
- maxHeight,
354
- padding: '0.5rem 0.75rem',
355
- border: '1px solid var(--gray-6)',
356
- borderRadius: '6px',
357
- backgroundColor: 'var(--gray-1)',
358
- fontSize: 'var(--font-size-2)',
359
- outline: 'none',
360
- overflowY: 'auto',
361
- lineHeight: '1.5',
362
- wordWrap: 'break-word',
363
- color: 'var(--gray-12)'
364
- } }));
350
+ return (_jsx("div", { ref: editorRef, contentEditable: true, role: "textbox", "aria-label": placeholder, "aria-multiline": "true", suppressContentEditableWarning: true, onInput: handleChange, onKeyDown: handleKeyDown, onPaste: handlePaste, "data-placeholder": placeholder, className: "rich-text-editor", style: { width: '100%', minHeight, maxHeight } }));
365
351
  });
366
352
  RichTextEditor.displayName = 'RichTextEditor';
367
353
  export default RichTextEditor;
@@ -412,27 +412,16 @@ const RichTextEditor = forwardRef<RichTextEditorRef, RichTextEditorProps>(
412
412
  <div
413
413
  ref={editorRef}
414
414
  contentEditable
415
+ role="textbox"
416
+ aria-label={placeholder}
417
+ aria-multiline="true"
415
418
  suppressContentEditableWarning
416
419
  onInput={handleChange}
417
420
  onKeyDown={handleKeyDown}
418
421
  onPaste={handlePaste}
419
422
  data-placeholder={placeholder}
420
423
  className="rich-text-editor"
421
- style={{
422
- width: '100%',
423
- minHeight,
424
- maxHeight,
425
- padding: '0.5rem 0.75rem',
426
- border: '1px solid var(--gray-6)',
427
- borderRadius: '6px',
428
- backgroundColor: 'var(--gray-1)',
429
- fontSize: 'var(--font-size-2)',
430
- outline: 'none',
431
- overflowY: 'auto',
432
- lineHeight: '1.5',
433
- wordWrap: 'break-word',
434
- color: 'var(--gray-12)'
435
- }}
424
+ style={{ width: '100%', minHeight, maxHeight }}
436
425
  />
437
426
  )
438
427
  }
@@ -2,12 +2,13 @@
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
3
  import { sandboxText } from './messages.js';
4
4
  import React, { useState, useEffect, useRef, useMemo, useCallback } from 'react';
5
- import { cn, CodeBlock, MarkdownContent, resolveMediaSrc, pickMediaRawUrl, } from '@zhin.js/client';
5
+ import { cn, adapterConsoleStyles, CodeBlock, MarkdownContent, resolveMediaSrc, pickMediaRawUrl, } from '@zhin.js/client';
6
6
  import { buildSandboxWebSocketUrl, captureSandboxRequestContext, createSandboxMessageId, submitSandboxFrame, SANDBOX_SCOPED_PROTOCOL } from './sandboxTransport';
7
7
  import { createWorkspaceDirectoryController } from './workspaceDirectoryState.js';
8
8
  import { User, Bot, Users, Trash2, Send, Hash, MessageSquare, Wifi, WifiOff, Smile, Image, X, Check, Info, Search, Video, Music, Plus, PanelRight, ExternalLink, RefreshCw, Sparkles, Activity, Wrench, Coins, CircleAlert, Gauge, SlidersHorizontal, FolderOpen, ShieldCheck, Network, Square, RotateCcw, FileDiff, Terminal, FlaskConical, ChevronDown, FileDown, ListChecks, } from 'lucide-react';
9
9
  import RichTextEditor, {} from './RichTextEditor';
10
10
  import HtmlMessage from './HtmlMessage.js';
11
+ import { sandboxStyles } from './styles.js';
11
12
  import ConversationRecoveryPanel from './ConversationRecoveryPanel.js';
12
13
  import { useSandboxHistory } from './useSandboxHistory.js';
13
14
  import { agentSessionsPath, buildAgentRunReport, buildSandboxSessionKey, cancelAgentTask, deriveAgentRunSteps, deriveTaskRuns, deriveWorkbenchArtifacts, fetchAgentTrace, loadCachedAgentTrace, mergeTraceSnapshot, presentTraceEvent, summarizeTrace, saveCachedAgentTrace, } from './agentTrace.js';
@@ -266,6 +267,8 @@ export default function Sandbox(props = {}) {
266
267
  interactionReadOnly: false,
267
268
  channelId: sceneId, channelName, senderId: isInput ? data.senderId || connectionRef.current.ownerId || 'owner' : 'endpoint',
268
269
  senderName: isInput ? sandboxText(locale, "当前用户") : data.bot || endpointIdRef.current, content, timestamp: data.timestamp,
270
+ ...(Number.isSafeInteger(data.revision) && data.revision > 0 ? { revision: data.revision } : {}),
271
+ ...(typeof data.streaming === 'boolean' ? { streaming: data.streaming } : {}),
269
272
  }));
270
273
  };
271
274
  const sendInteractiveAction = (payload, messageId) => {
@@ -752,7 +755,7 @@ export default function Sandbox(props = {}) {
752
755
  };
753
756
  const inlineRunCard = currentTask ? (_jsxs("article", { className: cn('agent-playground-inline-run', `is-${currentTask.status}`), "aria-live": currentTask.status === 'running' ? 'polite' : undefined, children: [_jsx("span", { className: "agent-playground-inline-run-rail", "aria-hidden": "true" }), _jsxs("div", { className: "agent-playground-inline-run-head", children: [_jsx("span", { className: "agent-playground-inline-run-icon", children: _jsx(ListChecks, { size: 17 }) }), _jsxs("div", { className: "agent-playground-inline-run-copy", children: [_jsx("span", { children: currentTask.status === 'running' ? 'Live agent run' : 'Agent run summary' }), _jsx("h3", { children: taskStatusLabel(currentTask.status, locale) }), currentTaskMessage && _jsx("p", { children: messageText(currentTaskMessage.content) })] }), _jsxs("div", { className: "agent-playground-inline-run-actions", children: [currentTask.status === 'running' ? (_jsxs("button", { type: "button", className: "is-stop", onClick: () => void stopActiveTask(), disabled: stoppingTask, children: [_jsx(Square, { size: 12 }), stoppingTask ? sandboxText(locale, "停止中") : sandboxText(locale, "停止")] })) : currentTaskMessage ? (_jsxs("button", { type: "button", onClick: retryCurrentTask, children: [_jsx(RotateCcw, { size: 13 }), sandboxText(locale, "重试")] })) : null, _jsxs("button", { type: "button", onClick: exportCurrentRun, title: sandboxText(locale, "导出 Markdown 运行报告"), children: [_jsx(FileDown, { size: 13 }), sandboxText(locale, "导出")] })] })] }), _jsxs("dl", { className: "agent-playground-inline-run-metrics", children: [_jsxs("div", { children: [_jsx("dt", { children: sandboxText(locale, "耗时") }), _jsx("dd", { children: currentTask.durationMs === undefined ? sandboxText(locale, "进行中") : formatDuration(currentTask.durationMs, locale) })] }), _jsxs("div", { children: [_jsx("dt", { children: sandboxText(locale, "步骤") }), _jsx("dd", { children: currentRunSteps.length })] }), _jsxs("div", { children: [_jsx("dt", { children: sandboxText(locale, "工具") }), _jsx("dd", { children: currentTask.toolCount })] }), _jsxs("div", { children: [_jsx("dt", { children: "Token" }), _jsx("dd", { children: currentTask.tokenCount.toLocaleString(locale) })] }), _jsxs("div", { className: cn(currentTask.problemCount > 0 && 'has-problem'), children: [_jsx("dt", { children: sandboxText(locale, "异常") }), _jsx("dd", { children: currentTask.problemCount })] })] }), inlineRunExpanded && (currentRunSteps.length > 0 ? (_jsx("ol", { className: "agent-playground-inline-run-steps", children: currentRunSteps.map((step) => (_jsxs("li", { className: cn(`is-${step.status}`), children: [_jsx("i", { "aria-hidden": "true" }), _jsxs("div", { children: [_jsx("strong", { children: step.title }), step.detail && _jsx("small", { children: step.detail })] }), _jsx("span", { children: step.durationMs === undefined ? runStepStatusLabel(step.status, locale) : formatDuration(step.durationMs, locale) })] }, step.id))) })) : _jsx("div", { className: "agent-playground-inline-run-empty", children: sandboxText(locale, "正在等待第一条运行事件…") })), _jsxs("footer", { children: [_jsxs("button", { type: "button", "aria-expanded": inlineRunExpanded, onClick: () => setInlineRunExpanded((expanded) => !expanded), children: [_jsx(ChevronDown, { size: 13 }), inlineRunExpanded ? sandboxText(locale, "收起步骤") : sandboxText(locale, "查看 {0} 个步骤", [currentRunSteps.length])] }), _jsxs("button", { type: "button", onClick: () => { setInspectorView(currentRunArtifacts.length > 0 ? 'artifacts' : 'runs'); setShowInspector(true); }, children: [currentRunArtifacts.length > 0 ? sandboxText(locale, "{0} 个变更与产物", [currentRunArtifacts.length]) : sandboxText(locale, "打开运行检查器"), _jsx(PanelRight, { size: 13 })] })] })] })) : null;
754
757
  const recoveryConnectionId = connectionRef.current.connectionId;
755
- return (_jsxs("section", { className: cn("agent-playground-shell", showInspector && "has-inspector"), children: [_jsxs("div", { className: "agent-playground-mobilebar", children: [_jsxs("button", { type: "button", "aria-expanded": showChannelList, onClick: () => setShowChannelList(!showChannelList), children: [_jsx(MessageSquare, { size: 17 }), sandboxText(locale, "会话列表")] }), _jsx("strong", { children: sandboxText(locale, "会话") }), _jsxs("button", { type: "button", "aria-expanded": showInspector, "aria-controls": "sandbox-run-inspector", onClick: () => setShowInspector(!showInspector), children: [_jsx(PanelRight, { size: 17 }), sandboxText(locale, "检查器")] })] }), _jsxs("nav", { className: cn("channel-sidebar agent-playground-sessions", showChannelList && "show"), "aria-label": sandboxText(locale, "会话列表"), children: [_jsx("div", { className: "agent-playground-brand", children: _jsxs("div", { className: "flex justify-between items-center", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("span", { className: "agent-playground-mark", children: _jsx(Sparkles, { size: 16 }) }), _jsxs("div", { children: [_jsx("h2", { children: sandboxText(locale, "会话") }), _jsx("small", { children: "Conversations" })] })] }), _jsx("span", { className: cn("agent-playground-connection", connected && "is-online"), title: connected ? sandboxText(locale, "Sandbox WebSocket 已连接") : sandboxText(locale, "正在重连 Sandbox WebSocket"), children: connected ? _jsx(Wifi, { size: 12 }) : _jsx(WifiOff, { size: 12 }) })] }) }), _jsxs("div", { className: "agent-playground-section-label", children: [_jsx("span", { children: sandboxText(locale, "会话列表") }), _jsx("span", { children: channels.length }), _jsx("button", { type: "button", disabled: directoryStatus.mode === 'loading', "aria-label": sandboxText(locale, "刷新会话目录"), onClick: () => void directoryControllerRef.current?.refresh(), children: _jsx(RefreshCw, { size: 13 }) })] }), _jsx("div", { className: "agent-playground-session-list", children: channels.map((channel) => {
758
+ return (_jsxs("section", { className: cn("zhin-console-surface zhin-sandbox agent-playground-shell", showInspector && "has-inspector"), children: [_jsxs("style", { children: [adapterConsoleStyles, sandboxStyles] }), _jsxs("div", { className: "agent-playground-mobilebar", children: [_jsxs("button", { type: "button", "aria-expanded": showChannelList, onClick: () => setShowChannelList(!showChannelList), children: [_jsx(MessageSquare, { size: 17 }), sandboxText(locale, "会话列表")] }), _jsx("strong", { children: sandboxText(locale, "会话") }), _jsxs("button", { type: "button", "aria-expanded": showInspector, "aria-controls": "sandbox-run-inspector", onClick: () => setShowInspector(!showInspector), children: [_jsx(PanelRight, { size: 17 }), sandboxText(locale, "检查器")] })] }), _jsxs("nav", { className: cn("channel-sidebar agent-playground-sessions", showChannelList && "show"), "aria-label": sandboxText(locale, "会话列表"), children: [_jsx("div", { className: "agent-playground-brand", children: _jsxs("div", { className: "flex justify-between items-center", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("span", { className: "agent-playground-mark", children: _jsx(Sparkles, { size: 16 }) }), _jsxs("div", { children: [_jsx("h2", { children: sandboxText(locale, "会话") }), _jsx("small", { children: "Conversations" })] })] }), _jsx("span", { className: cn("agent-playground-connection", connected && "is-online"), title: connected ? sandboxText(locale, "Sandbox WebSocket 已连接") : sandboxText(locale, "正在重连 Sandbox WebSocket"), children: connected ? _jsx(Wifi, { size: 12 }) : _jsx(WifiOff, { size: 12 }) })] }) }), _jsxs("div", { className: "agent-playground-section-label", children: [_jsx("span", { children: sandboxText(locale, "会话列表") }), _jsx("span", { children: channels.length }), _jsx("button", { type: "button", disabled: directoryStatus.mode === 'loading', "aria-label": sandboxText(locale, "刷新会话目录"), onClick: () => void directoryControllerRef.current?.refresh(), children: _jsx(RefreshCw, { size: 13 }) })] }), _jsx("div", { className: "agent-playground-session-list", children: channels.map((channel) => {
756
759
  const isActive = activeChannel.id === channel.id && activeChannel.type === channel.type;
757
760
  return (_jsxs("button", { type: "button", disabled: directoryStatus.mode === 'loading', "aria-current": isActive ? 'page' : undefined, className: cn("agent-playground-session", isActive && "active"), onClick: () => switchChannel(channel), children: [_jsx("span", { className: "agent-playground-session-icon", children: getChannelIcon(channel.type) }), _jsxs("div", { className: "flex-1 min-w-0", children: [_jsx("div", { className: "text-sm font-medium truncate", children: channel.name }), _jsx("div", { className: "text-xs text-muted-foreground", children: channel.type === 'private' ? sandboxText(locale, "单用户作用域") : channel.type === 'group' ? sandboxText(locale, "群组作用域") : sandboxText(locale, "频道作用域") })] }), channel.unread > 0 && _jsx("span", { className: "inline-flex items-center justify-center h-5 min-w-5 rounded-full bg-destructive text-destructive-foreground text-[10px] font-medium px-1", children: channel.unread })] }, `${channel.type}:${channel.id}`));
758
761
  }) }), _jsx("div", { className: "agent-playground-new-session", children: showNewSession ? (_jsxs("div", { className: "agent-playground-new-form", children: [_jsx("input", { value: newSessionName, onChange: (event) => setNewSessionName(event.target.value), onKeyDown: (event) => { if (event.key === 'Enter')
@@ -2,6 +2,7 @@ import { sandboxText, type SandboxLocale } from './messages.js';
2
2
  import React, { useState, useEffect, useRef, useMemo, useCallback } from 'react';
3
3
  import {
4
4
  cn,
5
+ adapterConsoleStyles,
5
6
  CodeBlock,
6
7
  MarkdownContent,
7
8
  resolveMediaSrc,
@@ -22,6 +23,7 @@ import {
22
23
  } from 'lucide-react';
23
24
  import RichTextEditor, { type RichTextEditorRef } from './RichTextEditor';
24
25
  import HtmlMessage from './HtmlMessage.js';
26
+ import { sandboxStyles } from './styles.js';
25
27
  import ConversationRecoveryPanel from './ConversationRecoveryPanel.js';
26
28
  import { useSandboxHistory } from './useSandboxHistory.js';
27
29
  import {
@@ -238,6 +240,7 @@ export default function Sandbox(props: SandboxPageProps = {}) {
238
240
  type: string; id: string; locale?: unknown; content?: unknown; endpoint?: string; workingDirectory?: string; canExecute?: boolean;
239
241
  shellIsolation?: { available?: boolean; provider?: string; message?: string }; timestamp: number;
240
242
  messageId?: string; bot?: string; protocol?: string; connectionId?: string; direction?: string; senderId?: string;
243
+ revision?: number; streaming?: boolean;
241
244
  conversation?: { type: Channel['type']; id: string };
242
245
  }) => {
243
246
  const locale = data.type === 'ready' && data.locale === 'en' ? 'en' : data.type === 'ready' ? 'zh-CN' : localeRef.current
@@ -326,6 +329,8 @@ export default function Sandbox(props: SandboxPageProps = {}) {
326
329
  interactionReadOnly: false,
327
330
  channelId: sceneId, channelName, senderId: isInput ? data.senderId || connectionRef.current.ownerId || 'owner' : 'endpoint',
328
331
  senderName: isInput ? sandboxText(locale, "当前用户") : data.bot || endpointIdRef.current, content, timestamp: data.timestamp,
332
+ ...(Number.isSafeInteger(data.revision) && data.revision! > 0 ? { revision: data.revision } : {}),
333
+ ...(typeof data.streaming === 'boolean' ? { streaming: data.streaming } : {}),
329
334
  }))
330
335
  }
331
336
 
@@ -886,7 +891,8 @@ export default function Sandbox(props: SandboxPageProps = {}) {
886
891
 
887
892
  const recoveryConnectionId = connectionRef.current.connectionId
888
893
  return (
889
- <section className={cn("agent-playground-shell", showInspector && "has-inspector")}>
894
+ <section className={cn("zhin-console-surface zhin-sandbox agent-playground-shell", showInspector && "has-inspector")}>
895
+ <style>{adapterConsoleStyles}{sandboxStyles}</style>
890
896
  <div className="agent-playground-mobilebar">
891
897
  <button type="button" aria-expanded={showChannelList} onClick={() => setShowChannelList(!showChannelList)}><MessageSquare size={17} />{sandboxText(locale, "会话列表")}</button>
892
898
  <strong>{sandboxText(locale, "会话")}</strong>
@@ -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
- return index < 0 ? [...messages, incoming]
175
- : messages.map((message, offset) => offset === index ? { ...message, ...incoming } : message);
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
- return index < 0 ? [...messages, incoming]
231
- : messages.map((message, offset) => offset === index ? { ...message, ...incoming } : message);
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
  }