chatluna-plugin-onebot-sandbox 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +1 -0
  2. package/client/chat/composer.tsx +4 -2
  3. package/client/environment/entity-dialog.css +4 -0
  4. package/client/environment/entity-dialog.tsx +72 -3
  5. package/client/locales/en.yml +11 -0
  6. package/client/locales/zh.yml +11 -0
  7. package/client/workspace/media-cache.ts +38 -0
  8. package/client/workspace/store.ts +28 -9
  9. package/dist/.vite/manifest.json +1 -1
  10. package/dist/app-SGdVOART.js +85 -0
  11. package/dist/client.css +1 -1
  12. package/dist/client.js +1 -1
  13. package/lib/bot.d.ts +4 -1
  14. package/lib/bot.d.ts.map +1 -1
  15. package/lib/channel-assignee.d.ts +4 -3
  16. package/lib/channel-assignee.d.ts.map +1 -1
  17. package/lib/chatluna/conversation-lines.d.ts +41 -27
  18. package/lib/chatluna/conversation-lines.d.ts.map +1 -1
  19. package/lib/chatluna/model-calls.d.ts +68 -0
  20. package/lib/chatluna/model-calls.d.ts.map +1 -0
  21. package/lib/chatluna/presets.d.ts +142 -0
  22. package/lib/chatluna/presets.d.ts.map +1 -0
  23. package/lib/chatluna/runtime.d.ts +14 -0
  24. package/lib/chatluna/runtime.d.ts.map +1 -1
  25. package/lib/chatluna/state.d.ts +13 -4
  26. package/lib/chatluna/state.d.ts.map +1 -1
  27. package/lib/chatluna/wakeup.d.ts +2 -2
  28. package/lib/chatluna/wakeup.d.ts.map +1 -1
  29. package/lib/console-contract.d.ts +21 -1
  30. package/lib/console-contract.d.ts.map +1 -1
  31. package/lib/console.d.ts +2 -1
  32. package/lib/console.d.ts.map +1 -1
  33. package/lib/control-service.d.ts +10 -0
  34. package/lib/control-service.d.ts.map +1 -1
  35. package/lib/conversation-resolution.d.ts +17 -0
  36. package/lib/conversation-resolution.d.ts.map +1 -1
  37. package/lib/inbound-delivery.d.ts +17 -8
  38. package/lib/inbound-delivery.d.ts.map +1 -1
  39. package/lib/index.d.ts +4 -0
  40. package/lib/index.d.ts.map +1 -1
  41. package/lib/index.js +1244 -212
  42. package/lib/index.js.map +1 -1
  43. package/lib/mcp/http-api.d.ts.map +1 -1
  44. package/lib/mcp/service.d.ts +11 -1
  45. package/lib/mcp/service.d.ts.map +1 -1
  46. package/lib/mcp/tool-registry.d.ts +6 -0
  47. package/lib/mcp/tool-registry.d.ts.map +1 -1
  48. package/lib/onebot-profiles.d.ts +8 -0
  49. package/lib/onebot-profiles.d.ts.map +1 -1
  50. package/lib/test-spaces.d.ts.map +1 -1
  51. package/lib/webui.d.ts.map +1 -1
  52. package/package.json +5 -1
  53. package/dist/app-sK3yIFCF.js +0 -85
package/lib/index.js CHANGED
@@ -1,17 +1,18 @@
1
1
  import Schema from "schemastery";
2
+ import { schemaDocument, schemaFromJsonSchema } from "@chatluna/schema";
2
3
  import { fileURLToPath } from "node:url";
3
4
  import { ApiError } from "@chatluna/server";
4
5
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
5
6
  import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
6
7
  import { basename, join, resolve } from "node:path";
7
8
  import { Bot, h } from "@satorijs/core";
8
- import { schemaDocument, schemaFromJsonSchema } from "@chatluna/schema";
9
9
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
10
10
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
11
11
  import { CallToolRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, McpError, ReadResourceRequestSchema } from "@modelcontextprotocol/sdk/types.js";
12
12
  import { createServer } from "node:http";
13
13
  import { createServer as createServer$1 } from "node:https";
14
14
  import { BlockList, isIP } from "node:net";
15
+ import { requestAt } from "@chatluna/session";
15
16
  // external/onebot-sandbox/src/error-detail.ts
16
17
  /** 日志里的异常详情:Cordis 4 的 Logger 会把 Error 参数格式化成 `{}`,必须显式取堆栈。 */
17
18
  function errorDetail(error) {
@@ -50,6 +51,63 @@ function onDispose(ctx, task) {
50
51
  function resolveBaseDir(ctx) {
51
52
  return ctx.baseUrl ? fileURLToPath(new URL(".", ctx.baseUrl)) : process.cwd();
52
53
  }
54
+ // external/onebot-sandbox/src/chatluna/runtime.ts
55
+ /**
56
+ * 被测 ChatLuna 插件运行时的解析口。
57
+ *
58
+ * 沙盒要读的东西——唤醒规则用的 `chat`、`routing`、`presets`,对话线切换时重置会话用的 `chat`——都挂在
59
+ * ChatLuna v2 各自插件的服务实例上。这些插件都可以随时重载,因此这里只提供「现取一次」的函数,不缓存实例。
60
+ *
61
+ * 两条形态是这个模块存在的理由,不是防御性写法:
62
+ *
63
+ * 1. 走 `get(name)` 而不是属性访问。本插件不把这些服务写进 `inject`——声明了它们会让被测插件每次
64
+ * 重载都连带重建沙盒,内存模式下整份场景会跟着丢——而未声明的属性访问会被 Cordis 记一条注入告警。
65
+ * 2. 自己的上下文取不到时,遍历插件注册表用提供方自己的上下文再取一次。被测插件可能装在隔离了服务
66
+ * 映射的 loader group 里,此时只有提供方那份上下文能解析到实例。
67
+ *
68
+ * 形状按运行时读:服务来自仓库外的包,类型不在编译期可见。因此解析口收一个「接受判定」而不是直接把
69
+ * 服务交出去——调用方各自只要服务上的一小块能力,判定不通过就当作没装,而不是等到真的调用那一小块
70
+ * 能力时才在调用点上炸掉。
71
+ */
72
+ function readRecord$3(value) {
73
+ return value !== null && typeof value === "object" ? value : void 0;
74
+ }
75
+ function readServiceFrom(host, serviceName, accept) {
76
+ const get = readRecord$3(host)?.get;
77
+ if (typeof get !== "function") return void 0;
78
+ const service = readRecord$3(get.call(host, serviceName));
79
+ return service ? accept(service) : void 0;
80
+ }
81
+ function listRegistryContexts(value) {
82
+ const registry = readRecord$3(readRecord$3(value)?.registry);
83
+ const values = registry?.values;
84
+ if (typeof values !== "function") return [];
85
+ return [...values.call(registry)].flatMap((runtime) => {
86
+ const ctx = readRecord$3(runtime)?.ctx;
87
+ return ctx ? [ctx] : [];
88
+ });
89
+ }
90
+ /**
91
+ * 按服务名解析被测 ChatLuna 插件的服务,并收窄成调用方真正用到的那一小块。
92
+ *
93
+ * 先在自己的上下文里取;取不到再遍历插件注册表用提供方自己的上下文取一次。第二步不是保险措施,
94
+ * 理由见模块注释第 2 条。
95
+ */
96
+ function findChatLunaRuntime(host, serviceName, accept) {
97
+ const direct = readServiceFrom(host, serviceName, accept);
98
+ if (direct) return direct;
99
+ for (const ctx of listRegistryContexts(host)) {
100
+ const resolved = readServiceFrom(ctx, serviceName, accept);
101
+ if (resolved) return resolved;
102
+ }
103
+ }
104
+ var SandboxChatLunaError = class extends Error {
105
+ reason;
106
+ constructor(reason, message) {
107
+ super(message);
108
+ this.reason = reason;
109
+ }
110
+ };
53
111
  // external/onebot-sandbox/src/types.ts
54
112
  function isSandboxUser(participant) {
55
113
  return participant.kind === "user";
@@ -120,9 +178,17 @@ var SandboxOneBotDebugCursorExpiredError = class extends SandboxDomainError {
120
178
  };
121
179
  // external/onebot-sandbox/src/webui.ts
122
180
  const SIGNAL_STATE = "onebot-sandbox.signal";
181
+ const CHATLUNA_ERROR_CODES = {
182
+ unavailable: "UNAVAILABLE",
183
+ not_found: "NOT_FOUND",
184
+ forbidden: "FORBIDDEN",
185
+ conflict: "CONFLICT",
186
+ invalid: "INVALID_ARGUMENT"
187
+ };
123
188
  /** 领域错误是调用方可以修正的输入问题,映射成 400;其余异常保持 500 并由服务端记录堆栈。 */
124
189
  function toApiError(error) {
125
190
  if (error instanceof ApiError) return error;
191
+ if (error instanceof SandboxChatLunaError) return new ApiError(CHATLUNA_ERROR_CODES[error.reason], error.message);
126
192
  if (error instanceof SandboxDomainError || error instanceof Error && error.constructor === Error) return new ApiError("INVALID_ARGUMENT", error.message);
127
193
  return error;
128
194
  }
@@ -387,6 +453,35 @@ function resolveDirectConversationId(scene, firstId, secondId) {
387
453
  function resolveGroupConversationId(scene, groupId) {
388
454
  return findGroupRootConversation(scene, groupId)?.id ?? createGroupConversationId(groupId);
389
455
  }
456
+ /** adapter-onebot 给私聊事件的 channelId:`private:` 加对方账号(从接收的机器人一侧看)。 */
457
+ function toOneBotDirectChannelId(peerId) {
458
+ return `private:${peerId}`;
459
+ }
460
+ /**
461
+ * 会话在 Koishi 一侧的 channelId,与 adapter-onebot 一致:群聊是裸群号,私聊是 `private:<对方账号>`。
462
+ *
463
+ * 被测插件会按真实格式拼 channelId(例如按群号唤醒、按 `private:<QQ号>` 发私聊),沙盒给出别的
464
+ * 格式,ChatLuna 就会把同一个群当成两条路由、各有一份历史。会话实例在真实平台上没有对应物,
465
+ * 沿用实例自己的 ID,v2 因此把它当作独立的频道。
466
+ */
467
+ function toOneBotChannelId(conversation, botId) {
468
+ if (conversation.kind === "instance") return conversation.id;
469
+ if (conversation.type === "group") return conversation.groupId;
470
+ return toOneBotDirectChannelId(resolveConversationPeerId(conversation, botId) ?? botId);
471
+ }
472
+ /**
473
+ * 把 Koishi 一侧的 channelId 解析回沙盒会话 ID,是 {@link toOneBotChannelId} 的反向。
474
+ *
475
+ * 沙盒自己的会话 ID(`group:*`、`private:*:*`、实例 ID)原样认;`private:<账号>` 按这个机器人与该账号
476
+ * 的私聊解析,裸群号按该群的群聊解析。解析不出时原样返回,交给调用方的可见性校验报错。
477
+ */
478
+ function resolveOneBotChannelId(scene, channelId, botId) {
479
+ if (findConversationRow(scene, channelId)) return channelId;
480
+ const direct = /^private:([^:]+)$/.exec(channelId);
481
+ if (direct) return resolveDirectConversationId(scene, direct[1], botId);
482
+ if (scene.groups.some(({ id }) => id === channelId)) return resolveGroupConversationId(scene, channelId);
483
+ return channelId;
484
+ }
390
485
  /** 确保一对参与者的私聊根会话存在,就地写入场景。 */
391
486
  function ensureDirectRootConversation(scene, firstId, secondId) {
392
487
  const existing = findDirectRootConversation(scene, firstId, secondId);
@@ -595,10 +690,7 @@ function toOneBotMessageSegments(content, media) {
595
690
  }
596
691
  }));
597
692
  const generatedLabel = media.length === 1 ? `[${getMediaLabel(media[0])}] ${media[0].name}` : "";
598
- if (content && content !== generatedLabel) segments.push({
599
- type: "text",
600
- data: { text: content }
601
- });
693
+ if (content && content !== generatedLabel) segments.push(...h.parse(content).flatMap(toOneBotElementSegments));
602
694
  return segments;
603
695
  }
604
696
  return h.parse(content).flatMap(toOneBotElementSegments);
@@ -1151,6 +1243,15 @@ const baselines = {
1151
1243
  appName: "NapCat.Onebot",
1152
1244
  appVersion: "sandbox-2026.07.24",
1153
1245
  capabilities: createCapabilities([
1246
+ {
1247
+ id: "group.member.shut-list",
1248
+ action: "get_group_shut_list",
1249
+ handler: "get_group_shut_list",
1250
+ description: "获取指定群当前处于禁言状态的成员列表;原样返回 QQ 内核的 ShutUpGroupMember:uin 是字符串 QQ 号,昵称 nick、群名片 cardName、禁言到期时间 shutUpTime,role 是内核编号(2 成员、3 管理员、4 群主),uid 是与 QQ 号无关的内核 ID",
1251
+ aliases: ["getGroupShutList"],
1252
+ surface: "native",
1253
+ supported: true
1254
+ },
1154
1255
  {
1155
1256
  id: "contact.recent.list",
1156
1257
  action: "get_recent_contact",
@@ -1203,6 +1304,15 @@ const baselines = {
1203
1304
  appName: "LLOneBot",
1204
1305
  appVersion: "sandbox-2026.07.24",
1205
1306
  capabilities: createCapabilities([
1307
+ {
1308
+ id: "group.member.shut-list",
1309
+ action: "get_group_shut_list",
1310
+ handler: "get_group_shut_list",
1311
+ description: "获取指定群当前处于禁言状态的成员列表;每项是 uid、uin(字符串 QQ 号)、nick、cardName、role(2 成员、3 管理员、4 群主)、禁言到期时间 shutUpTime、memberRealLevel、memberSpecialTitle、joinTime、lastSpeakTime",
1312
+ aliases: ["getGroupShutList"],
1313
+ surface: "native",
1314
+ supported: true
1315
+ },
1206
1316
  {
1207
1317
  id: "group.notice.delete",
1208
1318
  action: "_delete_group_notice",
@@ -1403,6 +1513,16 @@ function getOneBotMessageId(profile, messageId) {
1403
1513
  return profile === "snowluma" ? hashOneBotMessageId(messageId) : getOneBotMessageSequence(messageId);
1404
1514
  }
1405
1515
  /**
1516
+ * Satori 一侧的消息 ID(`session.messageId`、`Universal.Message.id`、`sendMessage` 的返回值)。
1517
+ *
1518
+ * adapter-onebot 写的是 `'' + message_id`,十进制字符串,口径与该实现的 message_id 相同。沙盒自身的消息
1519
+ * ID 不外露:插件拿它调原始 action 在沙盒里查得到({@link resolveOneBotMessageId} 两种都认),换到真实
1520
+ * 实现上就查不到了。
1521
+ */
1522
+ function getSatoriMessageId(profile, messageId) {
1523
+ return String(getOneBotMessageId(profile, messageId));
1524
+ }
1525
+ /**
1406
1526
  * 把插件传来的 message_id 解析回沙盒消息 ID:沙盒自身的消息 ID 原样认,数字按该实现的 message_id 口径匹配。
1407
1527
  *
1408
1528
  * SnowLuma 下只认哈希 ID、不认消息序号,这正是要暴露的差异。
@@ -2070,6 +2190,16 @@ function readNestedForwardId(segment) {
2070
2190
  function getGroupMemberMuteTimestamp(member) {
2071
2191
  return isSandboxGroupMemberMuted(member) ? Math.floor(new Date(member.mutedUntil).getTime() / 1e3) : 0;
2072
2192
  }
2193
+ /** QQ 内核的群角色编号(NapCat `NTGroupMemberRole`):成员 2、管理员 3、群主 4。 */
2194
+ const KERNEL_GROUP_ROLE = {
2195
+ member: 2,
2196
+ admin: 3,
2197
+ owner: 4
2198
+ };
2199
+ /** 内核 uid 是与 QQ 号无关的不透明字符串;沙盒没有这一层,按账号派生一个形似的值。 */
2200
+ function toKernelUid(participantId) {
2201
+ return `u_sandbox_${participantId}`;
2202
+ }
2073
2203
  var SandboxBot = class extends Bot {
2074
2204
  control;
2075
2205
  inboundEventConversations;
@@ -2500,26 +2630,77 @@ var SandboxBot = class extends Bot {
2500
2630
  if (action === "get_group_shut_list") {
2501
2631
  const groupId = this.normalizeOneBotGroupId(params.group_id);
2502
2632
  await this.getGuild(groupId);
2503
- const group = this.control.getSnapshot().groups.find(({ id }) => id === groupId);
2633
+ const snapshot = this.control.getSnapshot();
2634
+ const muted = snapshot.groups.find(({ id }) => id === groupId).members.filter((member) => isSandboxGroupMemberMuted(member));
2635
+ const participantOf = (id) => snapshot.participants.find((participant) => participant.id === id);
2504
2636
  if (this.implementation === "snowluma") return {
2505
2637
  status: "ok",
2506
2638
  retcode: 0,
2507
- data: group.members.filter((member) => isSandboxGroupMemberMuted(member)).map((member) => ({
2639
+ data: muted.map((member) => ({
2508
2640
  user_id: Number(member.participantId),
2509
- nickname: this.control.getSnapshot().participants.find(({ id }) => id === member.participantId)?.name ?? member.participantId,
2641
+ nickname: participantOf(member.participantId)?.name ?? member.participantId,
2510
2642
  shut_up_time: getGroupMemberMuteTimestamp(member)
2511
2643
  }))
2512
2644
  };
2645
+ const members = muted.map((member) => ({
2646
+ uid: toKernelUid(member.participantId),
2647
+ uin: member.participantId,
2648
+ nick: participantOf(member.participantId)?.name ?? member.participantId,
2649
+ cardName: member.card ?? "",
2650
+ role: KERNEL_GROUP_ROLE[member.role],
2651
+ shutUpTime: getGroupMemberMuteTimestamp(member),
2652
+ memberRealLevel: Number.parseInt(member.level ?? "", 10) || 0,
2653
+ memberSpecialTitle: member.title ?? "",
2654
+ joinTime: member.joinTime ?? 0,
2655
+ lastSpeakTime: member.lastSentTime ?? 0
2656
+ }));
2657
+ if (this.implementation === "llbot") return {
2658
+ status: "ok",
2659
+ retcode: 0,
2660
+ data: members
2661
+ };
2513
2662
  return {
2514
2663
  status: "ok",
2515
2664
  retcode: 0,
2516
- data: group.members.filter((member) => isSandboxGroupMemberMuted(member)).map((member) => ({
2517
- group_id: Number(groupId),
2518
- user_id: Number(member.participantId),
2519
- nickname: this.control.getSnapshot().participants.find(({ id }) => id === member.participantId)?.name ?? member.participantId,
2520
- card: member.card ?? "",
2665
+ data: members.map((member) => ({
2666
+ uid: member.uid,
2667
+ qid: "",
2668
+ uin: member.uin,
2669
+ nick: member.nick,
2670
+ remark: "",
2671
+ cardType: 0,
2672
+ cardName: member.cardName,
2521
2673
  role: member.role,
2522
- shut_up_timestamp: getGroupMemberMuteTimestamp(member)
2674
+ avatarPath: "",
2675
+ shutUpTime: member.shutUpTime,
2676
+ isDelete: false,
2677
+ isSpecialConcerned: false,
2678
+ isSpecialShield: false,
2679
+ isRobot: participantOf(member.uin)?.kind === "bot",
2680
+ groupHonor: {},
2681
+ memberRealLevel: member.memberRealLevel,
2682
+ memberLevel: member.memberRealLevel,
2683
+ globalGroupLevel: 0,
2684
+ globalGroupPoint: 0,
2685
+ memberTitleId: 0,
2686
+ memberSpecialTitle: member.memberSpecialTitle,
2687
+ specialTitleExpireTime: "0",
2688
+ userShowFlag: 0,
2689
+ userShowFlagNew: 0,
2690
+ richFlag: 0,
2691
+ mssVipType: 0,
2692
+ bigClubLevel: 0,
2693
+ bigClubFlag: 0,
2694
+ autoRemark: "",
2695
+ creditLevel: 0,
2696
+ joinTime: member.joinTime,
2697
+ lastSpeakTime: member.lastSpeakTime,
2698
+ memberFlag: 0,
2699
+ memberFlagExt: 0,
2700
+ memberMobileFlag: 0,
2701
+ memberFlagExt2: 0,
2702
+ isSpecialShielded: false,
2703
+ cardNameId: 0
2523
2704
  }))
2524
2705
  };
2525
2706
  }
@@ -2683,7 +2864,7 @@ var SandboxBot = class extends Bot {
2683
2864
  }
2684
2865
  async createDirectChannel(userId) {
2685
2866
  return {
2686
- id: this.resolveDirectConversationId(userId),
2867
+ id: toOneBotDirectChannelId(userId),
2687
2868
  type: 1
2688
2869
  };
2689
2870
  }
@@ -2744,19 +2925,20 @@ var SandboxBot = class extends Bot {
2744
2925
  return { data: await Promise.all(group.members.map(({ participantId }) => this.getGuildMember(guildId, participantId))) };
2745
2926
  }
2746
2927
  async getMessage(channelId, messageId) {
2747
- const message = this.requireReadableMessage(messageId, channelId);
2928
+ const message = this.requireReadableMessage(messageId, this.resolveChannelId(channelId));
2748
2929
  return this.toUniversalMessage(message);
2749
2930
  }
2750
2931
  async getMessageList(channelId) {
2751
2932
  const snapshot = this.control.getSnapshot();
2752
- const conversation = this.getVisibleConversation(channelId, snapshot);
2933
+ const conversation = this.getVisibleConversation(resolveOneBotChannelId(snapshot, channelId, this.selfId), snapshot);
2753
2934
  const conversationMessageIds = new Set(readConversationMessageIds(snapshot, conversation.id));
2754
2935
  const messages = snapshot.messages.filter(({ id }) => conversationMessageIds.has(id)).filter((message) => !isRecalledMessage(message));
2755
2936
  return { data: await Promise.all(messages.map((message) => this.toUniversalMessage(message))) };
2756
2937
  }
2757
2938
  async deleteMessage(channelId, messageId) {
2758
- this.getVisibleConversation(channelId);
2759
- await this.control.recallBotMessage(this.selfId, messageId, channelId);
2939
+ const conversationId = this.resolveChannelId(channelId);
2940
+ this.getVisibleConversation(conversationId);
2941
+ await this.control.recallBotMessage(this.selfId, messageId, conversationId);
2760
2942
  }
2761
2943
  async deleteFriend(userId) {
2762
2944
  this.control.deleteBotFriend(this.selfId, userId);
@@ -2823,24 +3005,25 @@ var SandboxBot = class extends Bot {
2823
3005
  }
2824
3006
  async sendMessage(channelId, fragment, _referrer, options = {}) {
2825
3007
  if (this.status !== 1) throw new Error(`机器人已离线:${this.selfId}`);
3008
+ const conversationId = this.resolveChannelId(channelId);
2826
3009
  const transformed = await (options.session ?? this.session({
2827
3010
  type: "send",
2828
3011
  channel: {
2829
3012
  id: channelId,
2830
- type: resolveConversation(this.control.getSnapshot(), channelId)?.type === "group" ? 0 : 1
3013
+ type: resolveConversation(this.control.getSnapshot(), conversationId)?.type === "group" ? 0 : 1
2831
3014
  }
2832
3015
  })).transform(h.normalize(fragment));
2833
3016
  const message = parseKoishiOutboundMessage(transformed);
2834
3017
  if (!message.content && !message.mediaSources.length) return [];
2835
- const action = resolveConversation(this.control.getSnapshot(), channelId)?.type === "group" ? "send_group_msg" : "send_private_msg";
3018
+ const action = resolveConversation(this.control.getSnapshot(), conversationId)?.type === "group" ? "send_group_msg" : "send_private_msg";
2836
3019
  const payload = {
2837
3020
  channel_id: channelId,
2838
3021
  message: transformed.join("")
2839
3022
  };
2840
3023
  const startedAt = Date.now();
2841
3024
  try {
2842
- const messageId = await this.deliverOutboundMessage(channelId, message);
2843
- const conversationObservation = this.observeConversation({ conversationId: channelId });
3025
+ const messageId = await this.deliverOutboundMessage(conversationId, message);
3026
+ const conversationObservation = this.observeConversation({ conversationId });
2844
3027
  this.control.recordOneBotDebug({
2845
3028
  botId: this.selfId,
2846
3029
  implementation: this.implementation,
@@ -2857,7 +3040,7 @@ var SandboxBot = class extends Bot {
2857
3040
  },
2858
3041
  ...conversationObservation ? { conversationObservation } : {}
2859
3042
  });
2860
- return [messageId];
3043
+ return [getSatoriMessageId(this.implementation, messageId)];
2861
3044
  } catch (error) {
2862
3045
  this.control.recordOneBotDebug({
2863
3046
  botId: this.selfId,
@@ -3111,7 +3294,8 @@ var SandboxBot = class extends Bot {
3111
3294
  return emojiId;
3112
3295
  }
3113
3296
  /**
3114
- * Koishi 的 channelId 在群聊中是沙盒逻辑会话 ID;OneBot action 只接受真实群号。
3297
+ * 群实例的 channelId 是实例 ID,插件把它当群号传进 OneBot action 时换回真实群号;也认沙盒的
3298
+ * `group:*` 会话 ID。根会话的 channelId 已经是裸群号。
3115
3299
  *
3116
3300
  * 群号从解析出的会话读,不按 `group:` 前缀推断:会话实例 ID 沿用随机 ID 命名空间、没有群前缀,
3117
3301
  * 剥前缀会把群实例的 channelId 原样当成群号。解析不出会话时原样返回,插件直接传真实群号仍然可用。
@@ -3172,6 +3356,10 @@ var SandboxBot = class extends Bot {
3172
3356
  * 快照可选:`getSnapshot` 每次克隆整份场景,需要顺带读消息列表的调用方传入自己那一份,
3173
3357
  * 一次 action 因此只克隆一遍。
3174
3358
  */
3359
+ /** Satori 接口收到的 channelId 可能是 adapter-onebot 格式,也可能是沙盒会话 ID,见 {@link resolveOneBotChannelId}。 */
3360
+ resolveChannelId(channelId) {
3361
+ return resolveOneBotChannelId(this.control.getSnapshot(), channelId, this.selfId);
3362
+ }
3175
3363
  getVisibleConversation(channelId, snapshot = this.control.getSnapshot()) {
3176
3364
  try {
3177
3365
  return requireVisibleConversation(snapshot, this.selfId, channelId);
@@ -3283,10 +3471,10 @@ var SandboxBot = class extends Bot {
3283
3471
  const reply = message.replyToMessageId ? snapshot.messages.find(({ id }) => id === message.replyToMessageId) : void 0;
3284
3472
  const readableReply = reply && !isRecalledMessage(reply) ? reply : void 0;
3285
3473
  return {
3286
- id: message.id,
3287
- messageId: message.id,
3474
+ id: getSatoriMessageId(this.implementation, message.id),
3475
+ messageId: getSatoriMessageId(this.implementation, message.id),
3288
3476
  channel: conversation ? {
3289
- id: conversation.id,
3477
+ id: toOneBotChannelId(conversation, this.selfId),
3290
3478
  type: conversation.type === "group" ? 0 : 1
3291
3479
  } : void 0,
3292
3480
  guild: conversation?.groupId ? {
@@ -3297,8 +3485,8 @@ var SandboxBot = class extends Bot {
3297
3485
  content: message.content,
3298
3486
  elements: h.parse(message.content),
3299
3487
  quote: readableReply ? {
3300
- id: readableReply.id,
3301
- messageId: readableReply.id,
3488
+ id: getSatoriMessageId(this.implementation, readableReply.id),
3489
+ messageId: getSatoriMessageId(this.implementation, readableReply.id),
3302
3490
  content: readableReply.content,
3303
3491
  user: await this.getUser(readableReply.authorId)
3304
3492
  } : void 0,
@@ -3533,7 +3721,7 @@ var SandboxChannelAssignee = class {
3533
3721
  // external/onebot-sandbox/src/chatluna/thinking.ts
3534
3722
  /** `reply` 工具(`render.reply = tool`)的名字,与 v2 `packages/chat/core/src/render/reply-tool.ts` 同步。 */
3535
3723
  const REPLY_TOOL = "reply";
3536
- function readRecord$3(value) {
3724
+ function readRecord$2(value) {
3537
3725
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3538
3726
  }
3539
3727
  /**
@@ -3544,11 +3732,11 @@ function readRecord$3(value) {
3544
3732
  * 「生成内心活动」有没有生效。
3545
3733
  */
3546
3734
  function readStepThought(step) {
3547
- const record = readRecord$3(step);
3735
+ const record = readRecord$2(step);
3548
3736
  return [...Array.isArray(record?.content) ? record.content : [], ...Array.isArray(record?.toolCalls) ? record.toolCalls : []].map((value) => {
3549
- const block = readRecord$3(value);
3737
+ const block = readRecord$2(value);
3550
3738
  if (block?.type === "text" && typeof block.text === "string") return parseThinkContent(block.text);
3551
- const content = readRecord$3(block?.input)?.content;
3739
+ const content = readRecord$2(block?.input)?.content;
3552
3740
  if (block?.type === "tool-call" && block.toolName === REPLY_TOOL && typeof content === "string") return parseThinkContent(content);
3553
3741
  return "";
3554
3742
  }).filter(Boolean).join("\n\n");
@@ -3557,7 +3745,7 @@ function parseThinkContent(text) {
3557
3745
  return Array.from(text.matchAll(/<think\b[^>]*>([\s\S]*?)<\/think\s*>/gi)).map((match) => (match[1] ?? "").trim()).filter(Boolean).join("\n\n");
3558
3746
  }
3559
3747
  // external/onebot-sandbox/src/chatluna/state.ts
3560
- function readRecord$2(value) {
3748
+ function readRecord$1(value) {
3561
3749
  return value !== null && typeof value === "object" ? value : void 0;
3562
3750
  }
3563
3751
  function readString$1(value) {
@@ -3567,15 +3755,15 @@ function readNumber$1(value) {
3567
3755
  return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
3568
3756
  }
3569
3757
  function readSessionTarget(session) {
3570
- const value = readRecord$2(session);
3571
- const bot = readRecord$2(value?.bot);
3572
- const channel = readRecord$2(value?.channel);
3758
+ const value = readRecord$1(session);
3759
+ const bot = readRecord$1(value?.bot);
3760
+ const channel = readRecord$1(value?.channel);
3573
3761
  const botParticipantId = readString$1(value?.selfId) ?? readString$1(bot?.selfId);
3574
- const conversationId = readString$1(value?.channelId) ?? readString$1(channel?.id);
3575
- if (!botParticipantId || !conversationId) return;
3762
+ const channelId = readString$1(value?.channelId) ?? readString$1(channel?.id);
3763
+ if (!botParticipantId || !channelId) return;
3576
3764
  return {
3577
3765
  botParticipantId,
3578
- conversationId
3766
+ channelId
3579
3767
  };
3580
3768
  }
3581
3769
  function readAgentSessionId(agent) {
@@ -3589,12 +3777,12 @@ function createStateKey(botParticipantId, conversationId) {
3589
3777
  * 机器人的等待态、用量、思考与回复出处,全部由 ChatLuna v2 的三个事件推动。
3590
3778
  *
3591
3779
  * `chat/receive` 给出「agent 会话 ID → 机器人 + 会话」映射,之后的 `agent-status`(busy / idle)与
3592
- * `agent-step` 只带会话 ID。v2 的会话键含机器人 selfId,因此一个 agent 会话只对应一个机器人会话,
3780
+ * `agent-step` 只带会话 ID;唤醒的回合没有 `chat/receive`,映射改由 agent 自己的路由位置补上。v2 的会话键含机器人 selfId,因此一个 agent 会话只对应一个机器人会话,
3593
3781
  * 并发的机器人与会话各自按会话 ID 收尾,互不串联。
3594
3782
  */
3595
3783
  var SandboxChatLunaStateStore = class {
3596
3784
  ctx;
3597
- validateTarget;
3785
+ resolveTarget;
3598
3786
  onChange;
3599
3787
  archiveResult;
3600
3788
  states = /* @__PURE__ */ new Map();
@@ -3611,16 +3799,21 @@ var SandboxChatLunaStateStore = class {
3611
3799
  /** 机器人会话 → 已结束回合还没落到回复上的结果。 */
3612
3800
  pendingResults = /* @__PURE__ */ new Map();
3613
3801
  disposers = [];
3614
- constructor(ctx, validateTarget, onChange = () => {}, archiveResult = () => {}) {
3802
+ constructor(ctx, resolveTarget, onChange = () => {}, archiveResult = () => {}) {
3615
3803
  this.ctx = ctx;
3616
- this.validateTarget = validateTarget;
3804
+ this.resolveTarget = resolveTarget;
3617
3805
  this.onChange = onChange;
3618
3806
  this.archiveResult = archiveResult;
3619
3807
  const on = this.ctx.on.bind(this.ctx);
3620
3808
  this.disposers.push(on("chat/receive", (session, result) => {
3621
- const target = readSessionTarget(session);
3809
+ const source = readSessionTarget(session);
3622
3810
  const sessionId = readString$1(result?.sessionId);
3623
- if (!target || !sessionId || !this.validateTarget(target.botParticipantId, target.conversationId)) return;
3811
+ const conversationId = source && this.resolveTarget(source.botParticipantId, source.channelId);
3812
+ if (!source || !sessionId || !conversationId) return;
3813
+ const target = {
3814
+ botParticipantId: source.botParticipantId,
3815
+ conversationId
3816
+ };
3624
3817
  this.agentTargets.set(sessionId, target);
3625
3818
  if (this.busySessions.has(sessionId) && !this.turns.has(sessionId)) this.begin(sessionId, target);
3626
3819
  }));
@@ -3629,14 +3822,14 @@ var SandboxChatLunaStateStore = class {
3629
3822
  if (!sessionId) return;
3630
3823
  if (status === "busy") this.busySessions.add(sessionId);
3631
3824
  else this.busySessions.delete(sessionId);
3632
- const target = this.agentTargets.get(sessionId);
3825
+ const target = this.targetOf(sessionId, agent);
3633
3826
  if (!target) return;
3634
3827
  if (status === "busy") this.begin(sessionId, target);
3635
3828
  else this.finish(sessionId);
3636
3829
  }));
3637
3830
  this.disposers.push(on("chatluna/agent-step", ({ agent, step }) => {
3638
3831
  const sessionId = readAgentSessionId(agent);
3639
- const target = sessionId ? this.agentTargets.get(sessionId) : void 0;
3832
+ const target = sessionId ? this.targetOf(sessionId, agent) : void 0;
3640
3833
  if (!sessionId || !target) return;
3641
3834
  this.recordStep(sessionId, target, step);
3642
3835
  }));
@@ -3652,6 +3845,25 @@ var SandboxChatLunaStateStore = class {
3652
3845
  this.latestTraces.set(located.key, located.trace);
3653
3846
  }));
3654
3847
  }
3848
+ /**
3849
+ * agent 会话对应的机器人会话。`chat.wake` 唤醒的回合不经过 `chat/receive`,会话第一次被唤醒时还没有
3850
+ * 映射,这时按 agent 打开时记下的路由位置补上,否则唤醒发出的回复没有出处。
3851
+ */
3852
+ targetOf(sessionId, agent) {
3853
+ const known = this.agentTargets.get(sessionId);
3854
+ if (known) return known;
3855
+ const location = readRecord$1(readRecord$1(agent?.options)?.location);
3856
+ const botParticipantId = readString$1(location?.selfId);
3857
+ const channelId = readString$1(location?.channel);
3858
+ const conversationId = botParticipantId && channelId ? this.resolveTarget(botParticipantId, channelId) : void 0;
3859
+ if (!botParticipantId || !conversationId) return;
3860
+ const target = {
3861
+ botParticipantId,
3862
+ conversationId
3863
+ };
3864
+ this.agentTargets.set(sessionId, target);
3865
+ return target;
3866
+ }
3655
3867
  locateStepSpan(span) {
3656
3868
  if (span?.spanKind !== "step") return;
3657
3869
  const sessionId = readString$1(span.session);
@@ -3810,95 +4022,89 @@ var SandboxChatLunaStateStore = class {
3810
4022
  }
3811
4023
  }
3812
4024
  };
3813
- // external/onebot-sandbox/src/chatluna/runtime.ts
3814
- /**
3815
- * 被测 ChatLuna 插件运行时的解析口。
3816
- *
3817
- * 沙盒要读的东西——唤醒规则用的 `chat`、`routing`、`presets`,对话线切换时重置会话用的 `chat`——都挂在
3818
- * ChatLuna v2 各自插件的服务实例上。这些插件都可以随时重载,因此这里只提供「现取一次」的函数,不缓存实例。
3819
- *
3820
- * 两条形态是这个模块存在的理由,不是防御性写法:
3821
- *
3822
- * 1. 走 `get(name)` 而不是属性访问。本插件不把这些服务写进 `inject`——声明了它们会让被测插件每次
3823
- * 重载都连带重建沙盒,内存模式下整份场景会跟着丢——而未声明的属性访问会被 Cordis 记一条注入告警。
3824
- * 2. 自己的上下文取不到时,遍历插件注册表用提供方自己的上下文再取一次。被测插件可能装在隔离了服务
3825
- * 映射的 loader group 里,此时只有提供方那份上下文能解析到实例。
3826
- *
3827
- * 形状按运行时读:服务来自仓库外的包,类型不在编译期可见。因此解析口收一个「接受判定」而不是直接把
3828
- * 服务交出去——调用方各自只要服务上的一小块能力,判定不通过就当作没装,而不是等到真的调用那一小块
3829
- * 能力时才在调用点上炸掉。
3830
- */
3831
- function readRecord$1(value) {
3832
- return value !== null && typeof value === "object" ? value : void 0;
3833
- }
3834
- function readServiceFrom(host, serviceName, accept) {
3835
- const get = readRecord$1(host)?.get;
3836
- if (typeof get !== "function") return void 0;
3837
- const service = readRecord$1(get.call(host, serviceName));
3838
- return service ? accept(service) : void 0;
3839
- }
3840
- function listRegistryContexts(value) {
3841
- const registry = readRecord$1(readRecord$1(value)?.registry);
3842
- const values = registry?.values;
3843
- if (typeof values !== "function") return [];
3844
- return [...values.call(registry)].flatMap((runtime) => {
3845
- const ctx = readRecord$1(runtime)?.ctx;
3846
- return ctx ? [ctx] : [];
3847
- });
4025
+ // external/onebot-sandbox/src/chatluna/conversation-lines.ts
4026
+ /** 与 `@chatluna/satori` 的 `sessionIdFor` 一致:会话键第一次建立时的头会话。 */
4027
+ function defaultChatSessionId(conversationKey) {
4028
+ return `route:${conversationKey}`;
4029
+ }
4030
+ const LINE_TAG = "sandbox-";
4031
+ /** 对话线自己的 ChatLuna 会话 ID:主场景根会话是 v2 默认值,其余带固定后缀。 */
4032
+ function chatSessionIdOf(conversationKey, line) {
4033
+ return [
4034
+ defaultChatSessionId(conversationKey),
4035
+ ...line.scopeId ? [`${LINE_TAG}space-${line.scopeId}`] : [],
4036
+ ...line.instanceId ? [`${LINE_TAG}line-${line.instanceId}`] : []
4037
+ ].join(":");
3848
4038
  }
3849
4039
  /**
3850
- * 按服务名解析被测 ChatLuna 插件的服务,并收窄成调用方真正用到的那一小块。
3851
- *
3852
- * 先在自己的上下文里取;取不到再遍历插件注册表用提供方自己的上下文取一次。第二步不是保险措施,
3853
- * 理由见模块注释第 2 条。
4040
+ * 解析 v2 的 `chat` 与 `conversations` 服务,理由同 {@link findChatLunaRuntime}:按名称现取,不写进 inject。
4041
+ * 两者形状都对才算解析成功。
3854
4042
  */
3855
- function findChatLunaRuntime(host, serviceName, accept) {
3856
- const direct = readServiceFrom(host, serviceName, accept);
3857
- if (direct) return direct;
3858
- for (const ctx of listRegistryContexts(host)) {
3859
- const resolved = readServiceFrom(ctx, serviceName, accept);
3860
- if (resolved) return resolved;
3861
- }
4043
+ function findChatConversationHeads(host) {
4044
+ const chat = findChatLunaRuntime(host, "chat", (service) => typeof service.binding === "function" ? service : void 0);
4045
+ const conversations = findChatLunaRuntime(host, "conversations", (service) => typeof service.current === "function" && typeof service.switch === "function" ? service : void 0);
4046
+ if (!chat || !conversations) return;
4047
+ const call = (name, ...args) => conversations[name].call(conversations, ...args);
4048
+ return {
4049
+ conversationKeyOf: (session) => {
4050
+ const key = readRecord$3(chat.binding.call(chat, session))?.conversationKey;
4051
+ return typeof key === "string" && key ? key : void 0;
4052
+ },
4053
+ head: async (conversationKey) => {
4054
+ const sessionId = readRecord$3(await call("current", conversationKey))?.sessionId;
4055
+ return typeof sessionId === "string" && sessionId ? sessionId : void 0;
4056
+ },
4057
+ switch: async (conversationKey, sessionId) => {
4058
+ await call("switch", conversationKey, sessionId);
4059
+ if (typeof conversations.live !== "function" || typeof conversations.release !== "function") return;
4060
+ const liveSessionId = readRecord$3(readRecord$3(call("live", conversationKey))?.record)?.sessionId;
4061
+ if (liveSessionId !== void 0 && String(liveSessionId) !== sessionId) await call("release", String(liveSessionId));
4062
+ }
4063
+ };
3862
4064
  }
3863
- // external/onebot-sandbox/src/chatluna/conversation-lines.ts
3864
- /**
3865
- * 解析 v2 的 `chat` 服务,理由同 {@link findChatLunaRuntime}:按名称现取,不写进 inject。
3866
- * 同时有 `binding` 与 `reset` 才算解析成功。
3867
- */
3868
- function findChatConversationReset(host) {
3869
- return findChatLunaRuntime(host, "chat", (chat) => {
3870
- const { binding, reset } = chat;
3871
- if (typeof binding !== "function" || typeof reset !== "function") return void 0;
3872
- return {
3873
- conversationKeyOf: (session) => {
3874
- const key = readRecord$1(binding.call(chat, session))?.conversationKey;
3875
- return typeof key === "string" && key ? key : void 0;
3876
- },
3877
- reset: async (conversationKey) => reset.call(chat, conversationKey)
3878
- };
3879
- });
4065
+ function lineKeyOf(line) {
4066
+ return `${line.scopeId ?? ""}\u0000${line.instanceId ?? ""}`;
3880
4067
  }
4068
+ const MAIN_ROOT_LINE = lineKeyOf({});
3881
4069
  var SandboxChatConversationLines = class {
3882
4070
  resolveChat;
3883
- /** 每个(机器人,v2 会话键)上一次派发的对话线。 */
3884
- lastConversationIds = /* @__PURE__ */ new Map();
4071
+ /** v2 会话键 → 当前占着它的对话线。 */
4072
+ owners = /* @__PURE__ */ new Map();
4073
+ /** (对话线,v2 会话键)→ 这条对话线上次停留的会话;v2 自己重置过时与固定 ID 不同。 */
4074
+ sessions = /* @__PURE__ */ new Map();
4075
+ /** 同一个会话键上的切换串行执行,连发的消息不会交错读写头会话。 */
4076
+ pending = /* @__PURE__ */ new Map();
3885
4077
  constructor(resolveChat) {
3886
4078
  this.resolveChat = resolveChat;
3887
4079
  }
3888
- /**
3889
- * 记下这次入站事件属于哪条对话线,并在它与上一次不同时重置 v2 那份会话。返回是否真的重置过。
3890
- *
3891
- * 第一次为某个键派发时不重置:那份会话可能正是这条对话线攒下的历史。
3892
- */
4080
+ /** 在派发前把 v2 会话切到这次入站事件所属的对话线上。返回是否真的切换过。 */
3893
4081
  async followInboundConversation(input) {
3894
4082
  const chat = this.resolveChat();
3895
4083
  const conversationKey = chat?.conversationKeyOf(input.session);
3896
4084
  if (!chat || !conversationKey) return false;
3897
- const key = `${input.botId}\u0000${conversationKey}`;
3898
- const previous = this.lastConversationIds.get(key);
3899
- this.lastConversationIds.set(key, input.conversationId);
3900
- if (previous === void 0 || previous === input.conversationId) return false;
3901
- await chat.reset(conversationKey);
4085
+ const run = (this.pending.get(conversationKey) ?? Promise.resolve()).catch(() => void 0).then(() => this.follow(chat, conversationKey, input));
4086
+ this.pending.set(conversationKey, run);
4087
+ try {
4088
+ return await run;
4089
+ } finally {
4090
+ if (this.pending.get(conversationKey) === run) this.pending.delete(conversationKey);
4091
+ }
4092
+ }
4093
+ async follow(chat, conversationKey, line) {
4094
+ const lineKey = lineKeyOf(line);
4095
+ const slot = (key) => `${key}\u0000${conversationKey}`;
4096
+ const head = await chat.head(conversationKey);
4097
+ const owner = this.owners.get(conversationKey);
4098
+ if (owner === lineKey) {
4099
+ if (head) this.sessions.set(slot(lineKey), head);
4100
+ return false;
4101
+ }
4102
+ if (head && owner !== void 0) this.sessions.set(slot(owner), head);
4103
+ else if (head && !head.startsWith(`${defaultChatSessionId(conversationKey)}:${LINE_TAG}`)) this.sessions.set(slot(MAIN_ROOT_LINE), head);
4104
+ this.owners.set(conversationKey, lineKey);
4105
+ const target = this.sessions.get(slot(lineKey)) ?? chatSessionIdOf(conversationKey, line);
4106
+ if (head === target || head === void 0 && target === defaultChatSessionId(conversationKey)) return false;
4107
+ await chat.switch(conversationKey, target);
3902
4108
  return true;
3903
4109
  }
3904
4110
  };
@@ -3958,7 +4164,8 @@ function createInboundDelivery({ getRuntimeBot, getBotProfile, onMiddlewareFinis
3958
4164
  if (context.conversation.type === "direct") return context.peer?.kind === "bot" && context.peer.enabled ? [context.peer] : [];
3959
4165
  return (context.group?.members ?? []).map(({ participantId }) => getBotProfile(participantId)).filter((profile) => !!profile && profile.enabled && profile.id !== context.operator.id);
3960
4166
  };
3961
- const dispatchEvent = async (bot, session) => {
4167
+ /** 派发并记一条调试记录;ChatLuna 会话由调用方先切好。 */
4168
+ const dispatchRecorded = async (bot, session) => {
3962
4169
  const startedAt = Date.now();
3963
4170
  const payload = Reflect.get(session, "onebot");
3964
4171
  const profile = getBotProfile(bot.selfId);
@@ -3997,20 +4204,24 @@ function createInboundDelivery({ getRuntimeBot, getBotProfile, onMiddlewareFinis
3997
4204
  /**
3998
4205
  * 让 ChatLuna v2 的会话跟上这次入站事件所属的对话线。
3999
4206
  *
4000
- * 失败只写日志:重置不成功最坏是这一轮带上另一条对话线的历史,而中断投递会让被测插件
4207
+ * 失败只写日志:切换不成功最坏是这一轮带上另一条对话线(或另一个测试空间)的历史,而中断投递会让被测插件
4001
4208
  * 根本收不到消息,那比上下文不干净严重得多。
4002
4209
  */
4003
- const followChatConversation = async (botId, context, session) => {
4210
+ const followChatConversation = async (botId, target, session) => {
4004
4211
  try {
4005
4212
  await followInboundConversation({
4006
4213
  botId,
4007
- conversationId: context.conversation.id,
4214
+ ...target,
4008
4215
  session
4009
4216
  });
4010
4217
  } catch (error) {
4011
- logger.warn("重置 ChatLuna 会话失败;这一轮可能带上另一条对话线的历史。", error);
4218
+ logger.warn("切换 ChatLuna 会话失败;这一轮可能带上另一条对话线或另一个测试空间的历史。", error);
4012
4219
  }
4013
4220
  };
4221
+ const dispatchEvent = async (bot, session) => {
4222
+ await followChatConversation(bot.selfId, { channelId: session.channelId }, session);
4223
+ await dispatchRecorded(bot, session);
4224
+ };
4014
4225
  /**
4015
4226
  * 让这条群聊会话的 Koishi channel 受理人对齐到收件机器人。
4016
4227
  *
@@ -4023,7 +4234,7 @@ function createInboundDelivery({ getRuntimeBot, getBotProfile, onMiddlewareFinis
4023
4234
  try {
4024
4235
  await alignChannelAssignee({
4025
4236
  botId,
4026
- channelId: context.conversation.id,
4237
+ channelId: toOneBotChannelId(context.conversation, botId),
4027
4238
  groupId: context.group.id
4028
4239
  });
4029
4240
  } catch (error) {
@@ -4096,7 +4307,7 @@ function createInboundDelivery({ getRuntimeBot, getBotProfile, onMiddlewareFinis
4096
4307
  name: context.operator.name
4097
4308
  },
4098
4309
  channel: {
4099
- id: context.conversation.id,
4310
+ id: toOneBotChannelId(context.conversation, recipientBot.id),
4100
4311
  type: context.conversation.type === "group" ? 0 : 1
4101
4312
  },
4102
4313
  guild: context.group ? {
@@ -4104,15 +4315,19 @@ function createInboundDelivery({ getRuntimeBot, getBotProfile, onMiddlewareFinis
4104
4315
  name: context.group.name
4105
4316
  } : void 0,
4106
4317
  message: {
4107
- id: messageId,
4108
- messageId,
4318
+ id: getSatoriMessageId(recipientBot.implementation, messageId),
4319
+ messageId: getSatoriMessageId(recipientBot.implementation, messageId),
4109
4320
  content: elements.join(""),
4110
4321
  elements,
4111
- quote
4322
+ quote: quote && {
4323
+ ...quote,
4324
+ id: getSatoriMessageId(recipientBot.implementation, quote.id),
4325
+ messageId: getSatoriMessageId(recipientBot.implementation, quote.id)
4326
+ }
4112
4327
  }
4113
4328
  });
4114
4329
  Object.assign(session, { onebot: payload });
4115
- await followChatConversation(recipientBot.id, context, session);
4330
+ await followChatConversation(recipientBot.id, { conversationId: context.conversation.id }, session);
4116
4331
  const middlewareFinished = new Promise((resolve) => {
4117
4332
  const timer = setTimeout(() => {
4118
4333
  disposeMiddlewareWait?.();
@@ -4129,7 +4344,7 @@ function createInboundDelivery({ getRuntimeBot, getBotProfile, onMiddlewareFinis
4129
4344
  });
4130
4345
  await eventConversations.run(recipientBot.id, context.conversation.id, async () => {
4131
4346
  dispatched = true;
4132
- await dispatchEvent(runtimeBot, session);
4347
+ await dispatchRecorded(runtimeBot, session);
4133
4348
  await middlewareFinished;
4134
4349
  });
4135
4350
  } catch (error) {
@@ -4380,6 +4595,14 @@ function createRelationshipActions({ commitSceneMutation, dispatchGroupNotice, r
4380
4595
  // external/onebot-sandbox/src/control-service.ts
4381
4596
  var SandboxRuntimeBotRegistry = class {
4382
4597
  owners = /* @__PURE__ */ new Map();
4598
+ conversationLines;
4599
+ /**
4600
+ * ChatLuna 的会话键由机器人号与群号、账号组成,和机器人 ID 一样是各场景共用的资源,对话线归属因此
4601
+ * 挂在这个共享对象上:主场景与各测试空间必须看到同一份「这个键此刻属于谁」。
4602
+ */
4603
+ chatConversationLines(resolveChat) {
4604
+ return this.conversationLines ??= new SandboxChatConversationLines(resolveChat);
4605
+ }
4383
4606
  assertAvailable(botId, owner) {
4384
4607
  const currentOwner = this.owners.get(botId);
4385
4608
  if (currentOwner && currentOwner !== owner) throw new SandboxDomainError(`机器人 ID 已被活动场景占用:${botId}`);
@@ -4612,6 +4835,7 @@ var SandboxControlService = class {
4612
4835
  * 由它负责在对话线切换时重置那份会话。
4613
4836
  */
4614
4837
  chatConversationLines;
4838
+ scopeId;
4615
4839
  /**
4616
4840
  * Koishi 的 channel 受理人与虚拟机器人对不上时,非 @ 的群消息会在中间件之前被静默丢弃;
4617
4841
  * 由它在投递前把受理人对齐,见 {@link SandboxChannelAssignee}。
@@ -4660,12 +4884,14 @@ var SandboxControlService = class {
4660
4884
  this.ensureStableAvatars();
4661
4885
  this.reclaimSceneMessages();
4662
4886
  this.initialScene = structuredClone(this.scene);
4663
- this.chatLunaState = new SandboxChatLunaStateStore(ctx, (botParticipantId, conversationId) => {
4664
- return this.scene.participants.find(({ id }) => id === botParticipantId)?.kind === "bot" && !!findVisibleConversation(this.scene, botParticipantId, conversationId);
4887
+ this.chatLunaState = new SandboxChatLunaStateStore(ctx, (botParticipantId, channelId) => {
4888
+ if (!this.runtimeBots.has(botParticipantId)) return void 0;
4889
+ return findVisibleConversation(this.scene, botParticipantId, resolveOneBotChannelId(this.scene, channelId, botParticipantId))?.id;
4665
4890
  }, () => this.notifySceneMutation(), (botParticipantId, conversationId, result, messageIds) => {
4666
4891
  this.archiveChatLunaResult(botParticipantId, conversationId, result, messageIds);
4667
4892
  });
4668
- this.chatConversationLines = new SandboxChatConversationLines(() => findChatConversationReset(ctx));
4893
+ this.chatConversationLines = this.runtimeBotRegistry.chatConversationLines(() => findChatConversationHeads(ctx));
4894
+ this.scopeId = options.scopeId;
4669
4895
  this.channelAssignee = new SandboxChannelAssignee(async (rows) => {
4670
4896
  const database = ctx.get("database");
4671
4897
  if (!database) return false;
@@ -4678,7 +4904,15 @@ var SandboxControlService = class {
4678
4904
  onMiddlewareFinished: (listener) => ctx.on("middleware", listener),
4679
4905
  recordDebug: (input) => this.recordOneBotDebug(input),
4680
4906
  recordDelivery: (delivery) => this.botDeliveries.push(delivery),
4681
- followInboundConversation: (input) => this.chatConversationLines.followInboundConversation(input),
4907
+ followInboundConversation: ({ conversationId, channelId, botId, session }) => {
4908
+ const conversation = resolveConversation(this.scene, conversationId ?? resolveOneBotChannelId(this.scene, channelId ?? "", botId));
4909
+ const instanceId = conversation?.kind === "instance" && conversation.type === "direct" ? conversation.id : void 0;
4910
+ return this.chatConversationLines.followInboundConversation({
4911
+ scopeId: this.scopeId,
4912
+ instanceId,
4913
+ session
4914
+ });
4915
+ },
4682
4916
  alignChannelAssignee: (input) => this.channelAssignee.align(input),
4683
4917
  logger: {
4684
4918
  warn: (message, error) => ctx.logger.warn("%s\n%s", message, errorDetail(error)),
@@ -4786,7 +5020,7 @@ var SandboxControlService = class {
4786
5020
  try {
4787
5021
  url = new URL(value);
4788
5022
  } catch {
4789
- throw new SandboxDomainError("头像必须是受管媒体引用、Data URL、base64:// 或 HTTP(S) URL");
5023
+ throw new SandboxDomainError("头像来源不受支持:只接受 HTTP(S) URL、base64://、Data URL 或 sandbox-media:// 媒体引用,不读取本地文件路径");
4790
5024
  }
4791
5025
  if (url.protocol !== "http:" && url.protocol !== "https:") throw new SandboxDomainError("头像 URL 仅支持 HTTP(S)");
4792
5026
  const response = await fetch(url, { signal: AbortSignal.timeout(1e4) });
@@ -4869,21 +5103,19 @@ var SandboxControlService = class {
4869
5103
  size: media.size
4870
5104
  });
4871
5105
  });
4872
- if (text) elements.push(h.text(text));
4873
- const onebotMessage = input.media.map((media) => ({
4874
- type: media.type === "audio" ? "record" : media.type,
4875
- data: { file: media.reference }
4876
- }));
4877
- if (context.reply) onebotMessage.unshift({
4878
- type: "reply",
4879
- data: { id: String(getOneBotMessageSequence(context.reply.id)) }
4880
- });
4881
- if (text) onebotMessage.push({
4882
- type: "text",
4883
- data: { text }
4884
- });
4885
- const rawMessage = `${context.reply ? `[CQ:reply,id=${getOneBotMessageSequence(context.reply.id)}]` : ""}${input.media.map((media) => `[CQ:${media.type === "audio" ? "record" : media.type},file=${media.reference}]`).join("")}${text}`;
4886
- await this.dispatchMessageToBots(context, message, elements, onebotMessage, rawMessage);
5106
+ if (text) elements.push(...h.parse(text));
5107
+ const onebotMessage = [
5108
+ ...context.reply ? [{
5109
+ type: "reply",
5110
+ data: { id: String(getOneBotMessageSequence(context.reply.id)) }
5111
+ }] : [],
5112
+ ...input.media.map((media) => ({
5113
+ type: media.type === "audio" ? "record" : media.type,
5114
+ data: { file: media.reference }
5115
+ })),
5116
+ ...text ? toOneBotMessageSegments(text) : []
5117
+ ];
5118
+ await this.dispatchMessageToBots(context, message, elements, onebotMessage, toOneBotRawMessage(onebotMessage));
4887
5119
  return {
4888
5120
  messageId: message.id,
4889
5121
  revision: this.scene.revision
@@ -6027,7 +6259,7 @@ var SandboxControlService = class {
6027
6259
  size: item.size
6028
6260
  });
6029
6261
  });
6030
- if (text) elements.push(h.text(text));
6262
+ if (text) elements.push(...h.parse(text));
6031
6263
  const onebotMessage = [
6032
6264
  ...context.reply ? [{
6033
6265
  type: "reply",
@@ -6037,10 +6269,7 @@ var SandboxControlService = class {
6037
6269
  type: item.type === "audio" ? "record" : item.type,
6038
6270
  data: { file: item.reference }
6039
6271
  })),
6040
- ...text ? [{
6041
- type: "text",
6042
- data: { text }
6043
- }] : []
6272
+ ...text ? toOneBotMessageSegments(text) : []
6044
6273
  ];
6045
6274
  const delivery = this.dispatchMessageToBots(context, message, elements, onebotMessage, toOneBotRawMessage(onebotMessage));
6046
6275
  return {
@@ -6285,12 +6514,12 @@ var SandboxControlService = class {
6285
6514
  name: this.getParticipant(peerId).name
6286
6515
  },
6287
6516
  channel: {
6288
- id: conversation.id,
6517
+ id: toOneBotChannelId(conversation, botId),
6289
6518
  type: 1
6290
6519
  },
6291
6520
  message: {
6292
- id: messageId,
6293
- messageId
6521
+ id: getSatoriMessageId(this.implementationOf(botId), messageId),
6522
+ messageId: getSatoriMessageId(this.implementationOf(botId), messageId)
6294
6523
  }
6295
6524
  });
6296
6525
  Object.assign(session, { onebot: {
@@ -6721,17 +6950,25 @@ var SandboxControlService = class {
6721
6950
  user: {
6722
6951
  id: userId,
6723
6952
  name: this.getUser(userId).name
6953
+ },
6954
+ channel: {
6955
+ id: toOneBotDirectChannelId(userId),
6956
+ type: 1
6957
+ }
6958
+ });
6959
+ Object.assign(session, {
6960
+ messageId: flag,
6961
+ content: comment,
6962
+ onebot: {
6963
+ time: Math.floor(Date.now() / 1e3),
6964
+ self_id: Number(botId),
6965
+ post_type: "request",
6966
+ request_type: "friend",
6967
+ user_id: Number(userId),
6968
+ comment,
6969
+ flag
6724
6970
  }
6725
6971
  });
6726
- Object.assign(session, { onebot: {
6727
- time: Math.floor(Date.now() / 1e3),
6728
- self_id: Number(botId),
6729
- post_type: "request",
6730
- request_type: "friend",
6731
- user_id: Number(userId),
6732
- comment,
6733
- flag
6734
- } });
6735
6972
  await this.inboundDelivery.dispatchEvent(bot, session);
6736
6973
  }
6737
6974
  async dispatchBotNotice(botId, userId, noticeType) {
@@ -6745,7 +6982,7 @@ var SandboxControlService = class {
6745
6982
  name: this.getUser(userId).name
6746
6983
  },
6747
6984
  channel: {
6748
- id: resolveDirectConversationId(this.scene, userId, botId),
6985
+ id: toOneBotDirectChannelId(userId),
6749
6986
  type: 1
6750
6987
  }
6751
6988
  });
@@ -6770,28 +7007,36 @@ var SandboxControlService = class {
6770
7007
  await Promise.all(botIds.map(async (botId) => {
6771
7008
  const bot = this.getRuntimeBot(botId);
6772
7009
  const session = bot.session({
6773
- type: "guild-request",
7010
+ type: subType === "add" ? "guild-member-request" : "guild-request",
6774
7011
  timestamp: Date.now(),
6775
7012
  guild: {
6776
7013
  id: group.id,
6777
7014
  name: group.name
6778
7015
  },
7016
+ channel: {
7017
+ id: group.id,
7018
+ type: 0
7019
+ },
6779
7020
  user: {
6780
7021
  id: request.requesterId,
6781
7022
  name: this.getParticipant(request.requesterId).name
6782
7023
  }
6783
7024
  });
6784
- Object.assign(session, { onebot: {
6785
- time: Math.floor(Date.now() / 1e3),
6786
- self_id: Number(botId),
6787
- post_type: "request",
6788
- request_type: "group",
6789
- sub_type: subType,
6790
- group_id: Number(group.id),
6791
- user_id: Number(request.requesterId),
6792
- comment: request.comment,
6793
- flag: request.id
6794
- } });
7025
+ Object.assign(session, {
7026
+ messageId: request.id,
7027
+ content: request.comment,
7028
+ onebot: {
7029
+ time: Math.floor(Date.now() / 1e3),
7030
+ self_id: Number(botId),
7031
+ post_type: "request",
7032
+ request_type: "group",
7033
+ sub_type: subType,
7034
+ group_id: Number(group.id),
7035
+ user_id: Number(request.requesterId),
7036
+ comment: request.comment,
7037
+ flag: request.id
7038
+ }
7039
+ });
6795
7040
  await this.inboundDelivery.dispatchEvent(bot, session);
6796
7041
  }));
6797
7042
  }
@@ -6814,7 +7059,7 @@ var SandboxControlService = class {
6814
7059
  name: group.name
6815
7060
  },
6816
7061
  channel: {
6817
- id: resolveGroupConversationId(this.scene, group.id),
7062
+ id: group.id,
6818
7063
  type: 0
6819
7064
  },
6820
7065
  user: user ? {
@@ -6841,8 +7086,8 @@ var SandboxControlService = class {
6841
7086
  roles: [{ id: member.role }]
6842
7087
  } : void 0,
6843
7088
  message: options.messageId ? {
6844
- id: options.messageId,
6845
- messageId: options.messageId
7089
+ id: getSatoriMessageId(this.implementationOf(botId), options.messageId),
7090
+ messageId: getSatoriMessageId(this.implementationOf(botId), options.messageId)
6846
7091
  } : void 0
6847
7092
  });
6848
7093
  if (noticeType === "notify" && noticeData.sub_type === "poke") Object.assign(session, {
@@ -7120,6 +7365,7 @@ var SandboxTestSpaceService = class {
7120
7365
  return new SandboxControlService(this.ctx, {
7121
7366
  initialScene: scene,
7122
7367
  runtimeActive,
7368
+ scopeId: id,
7123
7369
  runtimeBots: this.runtimeBots,
7124
7370
  mediaDirectory: resolve(this.spaceDirectory(id), "media"),
7125
7371
  debugPersistence: this.createDebugPersistence?.(id),
@@ -7338,7 +7584,7 @@ function assertEnvironmentInput(input) {
7338
7584
  assertNoLegacyRpcFields(input);
7339
7585
  return input;
7340
7586
  }
7341
- function registerConsole(console, control, appearance, endpoint, testSpaces) {
7587
+ function registerConsole(console, control, appearance, endpoint, testSpaces, presets) {
7342
7588
  console.addEntry();
7343
7589
  control.onSceneMutation(({ revision }) => {
7344
7590
  console.broadcast("onebot-sandbox.scene-mutated", { revision });
@@ -7627,6 +7873,35 @@ function registerConsole(console, control, appearance, endpoint, testSpaces) {
7627
7873
  operatorId: input.operatorId
7628
7874
  });
7629
7875
  }, { authority: 4 });
7876
+ if (presets) {
7877
+ const presetCatalog = () => {
7878
+ try {
7879
+ const { presets: records, assignments } = presets.list();
7880
+ return {
7881
+ available: true,
7882
+ presets: records.map(({ id, name, status }) => ({
7883
+ id,
7884
+ name,
7885
+ status
7886
+ })),
7887
+ assignments
7888
+ };
7889
+ } catch (error) {
7890
+ if (error instanceof SandboxChatLunaError && error.reason === "unavailable") return {
7891
+ available: false,
7892
+ presets: [],
7893
+ assignments: []
7894
+ };
7895
+ throw error;
7896
+ }
7897
+ };
7898
+ registerListener("onebot-sandbox.bot-presets", presetCatalog, { authority: 4 });
7899
+ registerListener("onebot-sandbox.set-bot-preset", async (input) => {
7900
+ if (resolveControl(input, false).getSnapshot().participants.find(({ id }) => id === input.botId)?.kind !== "bot") throw new SandboxDomainError(`机器人不存在:${input.botId}`);
7901
+ await presets.assign(input.botId, input.presetId ?? void 0);
7902
+ return presetCatalog();
7903
+ }, { authority: 4 });
7904
+ }
7630
7905
  registerListener("onebot-sandbox.debug-records", listDebugRecords, { authority: 4 });
7631
7906
  registerListener("onebot-sandbox.debug-record", getDebugRecord, { authority: 4 });
7632
7907
  registerListener("onebot-sandbox.clear-debug-records", clearDebugRecords, { authority: 4 });
@@ -8080,6 +8355,10 @@ const HTTP_API_ERROR_STATUS = {
8080
8355
  media_not_found: 404,
8081
8356
  invalid_media_url: 400,
8082
8357
  digest_mismatch: 400,
8358
+ chatluna_unavailable: 503,
8359
+ model_call_not_found: 404,
8360
+ preset_not_found: 404,
8361
+ preset_forbidden: 403,
8083
8362
  method_not_allowed: 405,
8084
8363
  payload_too_large: 413,
8085
8364
  domain_error: 422,
@@ -8556,6 +8835,335 @@ var SandboxTestEndpointServer = class {
8556
8835
  response.end(JSON.stringify(body));
8557
8836
  }
8558
8837
  };
8838
+ // external/onebot-sandbox/src/chatluna/model-calls.ts
8839
+ const PREVIEW_LENGTH = 200;
8840
+ /** 超过这个长度、且只由 Base64 字符组成的字符串按内联媒体处理,不原样返回。 */
8841
+ const INLINE_DATA_THRESHOLD = 4096;
8842
+ function isMessageEntry(entry) {
8843
+ return entry?.kind === "message";
8844
+ }
8845
+ function readBlocks(content) {
8846
+ if (!Array.isArray(content)) return [];
8847
+ return content.flatMap((block) => {
8848
+ const record = readRecord$3(block);
8849
+ return record ? [record] : [];
8850
+ });
8851
+ }
8852
+ function blocksText(content) {
8853
+ return readBlocks(content).flatMap((block) => {
8854
+ if (block.type === "text" && typeof block.text === "string") return [block.text];
8855
+ if (block.type === "envelope") return [blocksText(block.content)];
8856
+ return [];
8857
+ }).filter(Boolean).join("\n");
8858
+ }
8859
+ function toSummary(entry) {
8860
+ const meta = entry.message.meta;
8861
+ if (entry.message.role !== "assistant" || typeof meta?.turn !== "number" || typeof meta.step !== "number") return;
8862
+ const text = blocksText(entry.message.content);
8863
+ return {
8864
+ seq: entry.n,
8865
+ turn: meta.turn,
8866
+ step: meta.step,
8867
+ time: entry.time,
8868
+ text: text.length > PREVIEW_LENGTH ? `${text.slice(0, PREVIEW_LENGTH)}…` : text,
8869
+ toolCalls: readBlocks(entry.message.content).flatMap((block) => block.type === "tool-call" && typeof block.toolName === "string" ? [block.toolName] : []),
8870
+ ...meta.usage === void 0 ? {} : { usage: meta.usage },
8871
+ ...meta.finish === void 0 ? {} : { finish: meta.finish },
8872
+ ...meta.timing === void 0 ? {} : { timing: meta.timing }
8873
+ };
8874
+ }
8875
+ /**
8876
+ * 把内联媒体换成占位:一张图的 Base64 就能撑满调用方的上下文,而排查请求时只需要知道那里有一张图。
8877
+ */
8878
+ function elideInlineData(value) {
8879
+ if (typeof value === "string") return value.length > INLINE_DATA_THRESHOLD && /^[A-Za-z0-9+/=\r\n]+$/.test(value) ? `[内联数据已省略,${value.length} 字符]` : value;
8880
+ if (Array.isArray(value)) return value.map(elideInlineData);
8881
+ const record = readRecord$3(value);
8882
+ if (!record) return value;
8883
+ return Object.fromEntries(Object.entries(record).map(([key, item]) => [key, elideInlineData(item)]));
8884
+ }
8885
+ /**
8886
+ * 默认读本插件所在实例里的 v2 会话日志。
8887
+ *
8888
+ * 进行中的会话先问 agent 自己的会话句柄:它持有正在写入的那份存储;已关闭的会话读 `session_store`。
8889
+ * 两者都按名称现取,理由同 `findChatLunaRuntime`。
8890
+ */
8891
+ var SandboxChatLunaModelCalls = class {
8892
+ host;
8893
+ constructor(host) {
8894
+ this.host = host;
8895
+ }
8896
+ storeOf(sessionId) {
8897
+ const agents = findChatLunaRuntime(this.host, "agents", (service) => typeof service.get === "function" ? service : void 0);
8898
+ const session = readRecord$3(readRecord$3(agents ? agents.get.call(agents, sessionId) : void 0)?.session);
8899
+ if (typeof session?.getStore === "function") return session.getStore.call(session);
8900
+ const store = findChatLunaRuntime(this.host, "session_store", (service) => typeof service.read === "function" && typeof service.head === "function" ? service : void 0);
8901
+ if (!store) throw new SandboxChatLunaError("unavailable", "ChatLuna 的会话存储没有加载,读不到模型调用");
8902
+ return store;
8903
+ }
8904
+ async readEntries(sessionId, store) {
8905
+ const id = sessionId;
8906
+ if (!await store.head(id)) return void 0;
8907
+ return (await store.read(id, { kind: "message" })).filter(isMessageEntry);
8908
+ }
8909
+ async list(sessionId) {
8910
+ return (await this.readEntries(sessionId, this.storeOf(sessionId)))?.flatMap((entry) => toSummary(entry) ?? []);
8911
+ }
8912
+ async get(sessionId, seq, options = {}) {
8913
+ const store = this.storeOf(sessionId);
8914
+ const id = sessionId;
8915
+ if (!await store.head(id)) return void 0;
8916
+ const [entry] = await store.read(id, {
8917
+ from: seq,
8918
+ before: seq + 1
8919
+ });
8920
+ if (!isMessageEntry(entry)) return void 0;
8921
+ const summary = toSummary(entry);
8922
+ if (!summary) return void 0;
8923
+ const response = {
8924
+ content: elideInlineData(entry.message.content),
8925
+ ...entry.message.meta?.raw === void 0 ? {} : { raw: elideInlineData(entry.message.meta.raw) }
8926
+ };
8927
+ try {
8928
+ const request = await requestAt(store, id, seq);
8929
+ const messages = options.lastMessages === void 0 ? request.messages : request.messages.slice(-options.lastMessages);
8930
+ return {
8931
+ ...summary,
8932
+ request: {
8933
+ config: request.config,
8934
+ ...request.system === void 0 ? {} : { system: request.system },
8935
+ tools: (request.tools ?? []).map((tool) => options.includeToolSchemas ? tool : {
8936
+ name: tool.name,
8937
+ ...tool.description ? { description: tool.description } : {}
8938
+ }),
8939
+ messageCount: request.messages.length,
8940
+ messages: messages.map(elideInlineData)
8941
+ },
8942
+ response
8943
+ };
8944
+ } catch (error) {
8945
+ return {
8946
+ ...summary,
8947
+ requestError: error instanceof Error ? error.message : String(error),
8948
+ response
8949
+ };
8950
+ }
8951
+ }
8952
+ };
8953
+ // external/onebot-sandbox/src/chatluna/presets.ts
8954
+ /**
8955
+ * 测试预设:让测试者新建、修改 ChatLuna v2 的预设,并把沙盒机器人切到指定预设。
8956
+ *
8957
+ * 预设是 v2 的全局资源,不属于任何场景或测试空间,所以写权限由沙盒自己收窄:
8958
+ *
8959
+ * - ID 以 `sandbox-test-` 开头的是测试预设,只能经这里新建,可以随意修改与删除;
8960
+ * - 其余预设只有列在插件设置 `presetEditing.editablePresets` 里的才能修改,而且一律不能删除;
8961
+ * - v2 标成 `editable: 'none'` 的(插件贡献的预设)无论如何都只读。
8962
+ *
8963
+ * 切换预设写成 v2 的路由规则而不是会话级覆盖:规则持久、重启后仍生效,且与真实配置走同一条
8964
+ * 解析路径。每个机器人一条,ID 固定为 `onebot-sandbox-preset-<机器人 ID>`,筛选条件只命中
8965
+ * OneBot 平台上这个 selfId;更具体的用户规则(例如按频道写的)仍会盖过它。
8966
+ */
8967
+ const TEST_PRESET_PREFIX = "sandbox-test-";
8968
+ const RULE_PREFIX = "onebot-sandbox-preset-";
8969
+ const RULE_WRITER = "onebot-sandbox";
8970
+ const PLATFORM$1 = "onebot";
8971
+ function isTestPresetId(id) {
8972
+ return id.startsWith(TEST_PRESET_PREFIX);
8973
+ }
8974
+ /** v2 的错误类型不在编译期可见,冲突按错误名识别:预设是 `PresetConflictError`,路由是 code `CONFLICT`。 */
8975
+ function translateError(error) {
8976
+ if (error instanceof SandboxChatLunaError) throw error;
8977
+ const record = readRecord$3(error);
8978
+ const message = error instanceof Error ? error.message : String(error);
8979
+ if (record?.name === "PresetConflictError" || record?.code === "CONFLICT") throw new SandboxChatLunaError("conflict", `${message};重新读取后再修改`);
8980
+ throw new SandboxChatLunaError("invalid", message);
8981
+ }
8982
+ async function guarded(run) {
8983
+ try {
8984
+ return await run();
8985
+ } catch (error) {
8986
+ translateError(error);
8987
+ }
8988
+ }
8989
+ var SandboxChatLunaPresets = class {
8990
+ host;
8991
+ editablePresets;
8992
+ constructor(host, editablePresets) {
8993
+ this.host = host;
8994
+ this.editablePresets = editablePresets;
8995
+ }
8996
+ presets() {
8997
+ const service = findChatLunaRuntime(this.host, "presets", (candidate) => typeof candidate.list === "function" && typeof candidate.save === "function" ? candidate : void 0);
8998
+ if (!service) throw new SandboxChatLunaError("unavailable", "ChatLuna 的预设服务没有加载");
8999
+ return service;
9000
+ }
9001
+ routing() {
9002
+ const service = findChatLunaRuntime(this.host, "routing", (candidate) => typeof candidate.save === "function" && typeof candidate.rules === "function" ? candidate : void 0);
9003
+ if (!service) throw new SandboxChatLunaError("unavailable", "ChatLuna 的路由服务没有加载");
9004
+ return service;
9005
+ }
9006
+ writable(record) {
9007
+ if (record.editable !== "source") return false;
9008
+ return isTestPresetId(record.id) || this.editablePresets.includes(record.id);
9009
+ }
9010
+ summarize(record) {
9011
+ return {
9012
+ id: record.id,
9013
+ name: record.name,
9014
+ kind: record.kind,
9015
+ loader: record.loader,
9016
+ status: record.status,
9017
+ origin: record.origin,
9018
+ revision: record.revision,
9019
+ ...record.description ? { description: record.description } : {},
9020
+ diagnostics: record.diagnostics ?? [],
9021
+ testPreset: isTestPresetId(record.id),
9022
+ writable: this.writable(record)
9023
+ };
9024
+ }
9025
+ require(id) {
9026
+ const record = this.presets().get(id);
9027
+ if (!record) throw new SandboxChatLunaError("not_found", `预设不存在:${id}`);
9028
+ return record;
9029
+ }
9030
+ assignments() {
9031
+ const routing = findChatLunaRuntime(this.host, "routing", (candidate) => typeof candidate.rules === "function" ? candidate : void 0);
9032
+ if (!routing) return [];
9033
+ return routing.rules().flatMap((rule) => {
9034
+ if (rule.by !== RULE_WRITER || !rule.id.startsWith(RULE_PREFIX)) return [];
9035
+ const presetId = readRecord$3(rule.values?.["chat.preset"])?.preset;
9036
+ return typeof presetId === "string" ? [{
9037
+ botId: rule.id.slice(22),
9038
+ presetId,
9039
+ ruleId: rule.id
9040
+ }] : [];
9041
+ });
9042
+ }
9043
+ list() {
9044
+ const presets = this.presets();
9045
+ return {
9046
+ presets: presets.list().map((record) => this.summarize(record)),
9047
+ loaders: presets.listLoaders().map((loader) => ({
9048
+ id: loader.id,
9049
+ extensions: [...loader.extensions]
9050
+ })),
9051
+ assignments: this.assignments()
9052
+ };
9053
+ }
9054
+ async get(id) {
9055
+ const record = this.require(id);
9056
+ const source = await this.presets().source(id);
9057
+ return {
9058
+ preset: this.summarize(record),
9059
+ ...source ? { source } : { data: record.data }
9060
+ };
9061
+ }
9062
+ async create(input) {
9063
+ if (!isTestPresetId(input.id)) throw new SandboxChatLunaError("forbidden", `测试预设的 ID 必须以 ${TEST_PRESET_PREFIX} 开头:${input.id}`);
9064
+ const presets = this.presets();
9065
+ if (presets.get(input.id)) throw new SandboxChatLunaError("invalid", `预设已存在:${input.id};修改它用 save_preset,或换一个 ID`);
9066
+ if (input.copyFrom !== void 0) {
9067
+ this.require(input.copyFrom);
9068
+ return this.summarize(await guarded(() => presets.duplicate(input.copyFrom, input.id, RULE_WRITER)));
9069
+ }
9070
+ if (input.loader === void 0) throw new SandboxChatLunaError("invalid", "loader 与 copyFrom 至少需要提供一项");
9071
+ const loader = input.loader;
9072
+ return this.summarize(await guarded(() => presets.create({
9073
+ id: input.id,
9074
+ loader,
9075
+ ...input.text === void 0 ? {} : { text: input.text }
9076
+ }, RULE_WRITER)));
9077
+ }
9078
+ async save(id, text, revision) {
9079
+ const record = this.require(id);
9080
+ if (!this.writable(record)) throw new SandboxChatLunaError("forbidden", record.editable !== "source" ? `预设 ${id} 由插件提供,只读` : `预设 ${id} 不是测试预设,也不在插件设置的可编辑预设列表里`);
9081
+ return this.summarize(await guarded(() => this.presets().save(id, text, revision, RULE_WRITER)));
9082
+ }
9083
+ async remove(id, revision) {
9084
+ this.require(id);
9085
+ if (!isTestPresetId(id)) throw new SandboxChatLunaError("forbidden", `只能删除测试预设(${TEST_PRESET_PREFIX} 开头):${id}`);
9086
+ const unassignedBots = [];
9087
+ for (const assignment of this.assignments().filter((item) => item.presetId === id)) {
9088
+ await this.assign(assignment.botId, void 0);
9089
+ unassignedBots.push(assignment.botId);
9090
+ }
9091
+ await guarded(() => this.presets().remove(id, revision, RULE_WRITER));
9092
+ return {
9093
+ removed: id,
9094
+ unassignedBots
9095
+ };
9096
+ }
9097
+ async assign(botId, presetId) {
9098
+ const routing = this.routing();
9099
+ const ruleId = `${RULE_PREFIX}${botId}`;
9100
+ if (presetId === void 0) {
9101
+ if (routing.rule(ruleId)) await guarded(() => routing.remove(ruleId, { by: RULE_WRITER }));
9102
+ return {
9103
+ botId,
9104
+ presetId: null
9105
+ };
9106
+ }
9107
+ this.require(presetId);
9108
+ await guarded(() => routing.save({
9109
+ id: ruleId,
9110
+ name: `OneBot 沙盒:机器人 ${botId} 的预设`,
9111
+ filter: {
9112
+ kind: "and",
9113
+ operands: [{
9114
+ kind: "scope",
9115
+ field: "platform",
9116
+ values: [PLATFORM$1]
9117
+ }, {
9118
+ kind: "scope",
9119
+ field: "self",
9120
+ values: [botId]
9121
+ }]
9122
+ },
9123
+ values: { "chat.preset": { preset: presetId } },
9124
+ enabled: true,
9125
+ by: RULE_WRITER
9126
+ }, { by: RULE_WRITER }));
9127
+ return {
9128
+ botId,
9129
+ presetId,
9130
+ ruleId
9131
+ };
9132
+ }
9133
+ };
9134
+ /** 设置页「可编辑预设」的动态 schema 名,`src/index.ts` 的字段经 `Schema.dynamic` 引用它。 */
9135
+ const EDITABLE_PRESETS_SCHEMA = "onebot-sandbox.editable-presets";
9136
+ /**
9137
+ * 「可编辑预设」的可选项:v2 里能按源文本编辑、又不是测试预设的预设。
9138
+ *
9139
+ * 测试预设总是可写,插件提供的预设总是只读,两者列出来勾了也不改变什么,所以不进选项。已经登记、
9140
+ * 但预设已经不在的 ID 仍然列出并标明,否则多选控件会把它当成未知值悄悄丢掉,用户也无从取消。
9141
+ */
9142
+ function editablePresetChoices(presets, selected) {
9143
+ const candidates = presets.filter((preset) => preset.editable === "source" && !isTestPresetId(preset.id));
9144
+ const known = new Set(candidates.map(({ id }) => id));
9145
+ const choices = [...candidates.map((preset) => Schema.const(preset.id).description(preset.name === preset.id ? preset.id : `${preset.name}(${preset.id})`)), ...selected.filter((id) => !known.has(id)).map((id) => Schema.const(id).description(`${id}(预设已不存在)`))];
9146
+ return Schema.array(Schema.union(choices)).role("select");
9147
+ }
9148
+ function readSelected(doc) {
9149
+ const value = readRecord$3(doc.presetEditing)?.editablePresets;
9150
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
9151
+ }
9152
+ /**
9153
+ * 登记「可编辑预设」的选项来源。设置页按需向服务端解析,预设增删时让已打开的设置页重新解析。
9154
+ *
9155
+ * `schemas` 只在这一处子作用域里注入,`presets` 按名称现取,理由同 `findChatLunaRuntime`:
9156
+ * 写进插件的 `inject` 会让被测插件每次重载都连带重建沙盒。
9157
+ */
9158
+ function registerEditablePresetChoices(ctx) {
9159
+ ctx.inject(["schemas"], (inner) => {
9160
+ inner.schemas.define(EDITABLE_PRESETS_SCHEMA, ({ doc }) => {
9161
+ const presets = findChatLunaRuntime(ctx, "presets", (service) => typeof service.list === "function" ? service : void 0);
9162
+ return editablePresetChoices(presets ? presets.list.call(presets) : [], readSelected(doc));
9163
+ });
9164
+ inner.on("presets/change", () => inner.schemas.invalidate(EDITABLE_PRESETS_SCHEMA));
9165
+ });
9166
+ }
8559
9167
  // external/onebot-sandbox/src/chatluna/wakeup.ts
8560
9168
  /**
8561
9169
  * 从一个 Koishi 上下文解析 ChatLuna v2 的对话服务、路由服务与预设服务。
@@ -8570,14 +9178,14 @@ function readSandboxResponderRuntimes(host) {
8570
9178
  const presets = findChatLunaRuntime(host, "presets", (service) => typeof service.get === "function" ? service : void 0);
8571
9179
  return { chat: {
8572
9180
  resolve: (identity) => {
8573
- return readRecord$1(readRecord$1(readRecord$1(chat.binding.call(chat, identity))?.resolution)?.values) ?? {};
9181
+ return readRecord$3(readRecord$3(readRecord$3(chat.binding.call(chat, identity))?.resolution)?.values) ?? {};
8574
9182
  },
8575
9183
  deciders: () => readDeciders(chat.activationDeciders.call(chat)),
8576
9184
  rules: () => readRules(routing.rules.call(routing)),
8577
9185
  readPresetNicknames: (presetId) => {
8578
9186
  if (!presets) return [];
8579
9187
  try {
8580
- return readStrings(readRecord$1(readRecord$1(presets.get.call(presets, presetId))?.data)?.nick);
9188
+ return readStrings(readRecord$3(readRecord$3(presets.get.call(presets, presetId))?.data)?.nick);
8581
9189
  } catch {
8582
9190
  return [];
8583
9191
  }
@@ -8587,7 +9195,7 @@ function readSandboxResponderRuntimes(host) {
8587
9195
  function readDeciders(value) {
8588
9196
  if (!Array.isArray(value)) return [];
8589
9197
  return value.flatMap((item) => {
8590
- const record = readRecord$1(item);
9198
+ const record = readRecord$3(item);
8591
9199
  const id = readString(record?.id);
8592
9200
  if (!id) return [];
8593
9201
  const label = readString(record?.label);
@@ -8602,7 +9210,7 @@ function readDeciders(value) {
8602
9210
  function readRules(value) {
8603
9211
  if (!Array.isArray(value)) return [];
8604
9212
  return value.flatMap((item) => {
8605
- const record = readRecord$1(item);
9213
+ const record = readRecord$3(item);
8606
9214
  const id = readString(record?.id);
8607
9215
  if (!id) return [];
8608
9216
  const name = readString(record?.name);
@@ -8611,7 +9219,7 @@ function readRules(value) {
8611
9219
  ...name ? { name } : {},
8612
9220
  enabled: record?.enabled !== false,
8613
9221
  filter: record?.filter,
8614
- values: readRecord$1(record?.values) ?? {}
9222
+ values: readRecord$3(record?.values) ?? {}
8615
9223
  }];
8616
9224
  });
8617
9225
  }
@@ -8652,17 +9260,17 @@ const BUILTIN_RULES = /* @__PURE__ */ new Set(["global", "global-private"]);
8652
9260
  function readChatWakeup(runtime, target) {
8653
9261
  const direct = target.conversationType === "direct";
8654
9262
  const values = runtime.resolve(toRouteIdentity(target));
8655
- const engine = readRecord$1(values["chat.engine"]) ?? {};
9263
+ const engine = readRecord$3(values["chat.engine"]) ?? {};
8656
9264
  const engineId = readString(engine.id) ?? "agent";
8657
9265
  const mode = readString(engine.mode) ?? "normal";
8658
- const activation = readRecord$1(values["chat.activation"]) ?? {};
9266
+ const activation = readRecord$3(values["chat.activation"]) ?? {};
8659
9267
  const registered = new Map(runtime.deciders().map((decider) => [decider.id, decider]));
8660
9268
  const deciders = readStrings(activation.use).filter((id) => {
8661
9269
  const decider = registered.get(id);
8662
9270
  return decider && (!decider.engines || decider.engines.includes(engineId));
8663
9271
  });
8664
- const presetName = readString(readRecord$1(values["chat.preset"])?.preset);
8665
- const rule = readRecord$1(activation.rule) ?? {};
9272
+ const presetName = readString(readRecord$3(values["chat.preset"])?.preset);
9273
+ const rule = readRecord$3(activation.rule) ?? {};
8666
9274
  const nicknames = [.../* @__PURE__ */ new Set([...readStrings(rule.botNames), ...presetName ? runtime.readPresetNicknames(presetName) : []])];
8667
9275
  const base = {
8668
9276
  responder: "chatluna",
@@ -8686,13 +9294,13 @@ function readChatWakeup(runtime, target) {
8686
9294
  const caveats = [];
8687
9295
  for (const id of deciders) if (id === "rule") readRuleConditions(rule, direct, nicknames, conditions, caveats);
8688
9296
  else if (id === "activity") {
8689
- const config = readRecord$1(activation.activity) ?? {};
9297
+ const config = readRecord$3(activation.activity) ?? {};
8690
9298
  conditions.push({
8691
9299
  kind: "activity-score",
8692
9300
  detail: `按群聊热度、话题与提及自主插话(activity 判定器:基础概率 ${formatPercent(readNumber(config.chance, .3))},每小时最多 ${readNumber(config.hourlyLimit, 30)} 次,两次至少间隔 30 秒)`
8693
9301
  });
8694
9302
  } else if (id === "judge") {
8695
- const config = readRecord$1(activation.judge) ?? {};
9303
+ const config = readRecord$3(activation.judge) ?? {};
8696
9304
  conditions.push({
8697
9305
  kind: "model-judge",
8698
9306
  detail: `前面的判定都没唤醒时,由模型判断要不要接话(judge 判定器:意愿阈值 ${readNumber(config.minUrge, .55)},两次至少间隔 ${readNumber(config.minInterval, 6e4)} 毫秒,每天 ${readNumber(config.dailyBudget, 200)} 次预算)`
@@ -8784,13 +9392,13 @@ function readRuleConditions(rule, direct, nicknames, conditions, caveats) {
8784
9392
  /** 判定之后影响「多久回复、会不会自己说话」的设置:合并方式、引擎自带的沉默机制与主动发言。 */
8785
9393
  function readFlowCaveats(values, engineId, direct, deciders) {
8786
9394
  const caveats = [];
8787
- const merge = Object.hasOwn(values, "chat.merge") ? readRecord$1(values["chat.merge"]) : void 0;
9395
+ const merge = Object.hasOwn(values, "chat.merge") ? readRecord$3(values["chat.merge"]) : void 0;
8788
9396
  const mergeMode = merge ? direct ? readString(merge.directMode) ?? readString(merge.mode) : readString(merge.mode) : void 0;
8789
9397
  if (merge && mergeMode === "settle") caveats.push(`chat.merge 为「等待发送完毕」:发言者静默 ${readNumber(merge.quiet, 2500)} 毫秒后才回复,连续发送时最长等 ${readNumber(merge.max, 15e3)} 毫秒;等待超时不要短于此`);
8790
9398
  if (deciders.includes("activity") || deciders.includes("judge")) caveats.push("activity 与 judge 是自主判定:同样的消息这次唤醒、下次不唤醒都正常,回复也可能延后发出");
8791
9399
  if (engineId === "character") caveats.push("character 引擎:直接对机器人说闭嘴类的话会让它沉默一段时间,预设作息里的睡眠时段只有 @、引用、私聊与昵称能唤醒,模型也可以选择不回复");
8792
9400
  if (engineId === "setup") caveats.push("本会话路由到 setup 引擎(主人私聊、人设尚未设置完成),回复是设置向导而不是正常对话");
8793
- const proactive = Object.hasOwn(values, "chat.proactive") ? readRecord$1(values["chat.proactive"]) : void 0;
9401
+ const proactive = Object.hasOwn(values, "chat.proactive") ? readRecord$3(values["chat.proactive"]) : void 0;
8794
9402
  const initiatives = proactive ? [
8795
9403
  "silence",
8796
9404
  "followUp",
@@ -8841,7 +9449,7 @@ const PARAMETER_OF_FIELD = {
8841
9449
  };
8842
9450
  /** 谓词里引用到的作用域维度;消息内容类谓词记作 `content`。 */
8843
9451
  function collectPredicateFields(predicate, fields = /* @__PURE__ */ new Set()) {
8844
- const record = readRecord$1(predicate);
9452
+ const record = readRecord$3(predicate);
8845
9453
  if (!record) return fields;
8846
9454
  const kind = record.kind;
8847
9455
  if (kind === "scope" && typeof record.field === "string") fields.add(record.field);
@@ -9832,7 +10440,7 @@ function readCapabilityMatrix(control, implementation) {
9832
10440
  /**
9833
10441
  * 被测机器人当前的唤醒规则。
9834
10442
  *
9835
- * 传了会话就按投递时的路由身份解析(机器人、群号、会话 ID、发言者,见 `readWakeupTargets`):v2 的路由规则
10443
+ * 传了会话就按投递时的路由身份解析(机器人、群号、频道 ID、发言者,见 `readWakeupTargets`):v2 的路由规则
9836
10444
  * 可以按其中任意一维覆盖唤醒配置。会话实例用它自己的 ID,v2 把实例当作独立的频道路由,答案可能与根会话
9837
10445
  * 不同。省略会话时给出私聊与群聊两份通用规则:按会话、机器人或发言者写的覆盖会明确标成待判定。
9838
10446
  */
@@ -9854,7 +10462,8 @@ function getWakeupRules(runtime, args) {
9854
10462
  /**
9855
10463
  * 一条会话上每个被测机器人各自的路由身份。
9856
10464
  *
9857
- * 字段与 `inbound-delivery.ts` 投递时构造的 Session 一致:频道 ID 是会话 ID,群聊带群号,用户是发言者。
10465
+ * 字段与 `inbound-delivery.ts` 投递时构造的 Session 一致:频道 ID 按 adapter-onebot 的格式(`toOneBotChannelId`,
10466
+ * 私聊因此每个机器人一份),群聊带群号,用户是发言者。
9858
10467
  * 同一条群消息会投给群里每个机器人,各自按自己的 selfId 解析规则,因此一个机器人一份答案;传了 botId
9859
10468
  * 只答那一个。私聊的发言者就是会话里那位普通用户;群聊的发言者要调用方用 operatorId 指定。
9860
10469
  */
@@ -9871,7 +10480,7 @@ function readWakeupTargets(snapshot, conversation, botId, operatorId) {
9871
10480
  guildId: conversation.groupId
9872
10481
  } : {},
9873
10482
  botId: id,
9874
- channelId: conversation.id,
10483
+ channelId: toOneBotChannelId(conversation, id),
9875
10484
  ...operatorId ? { userId: operatorId } : {}
9876
10485
  }));
9877
10486
  const speaker = operatorId ?? memberIds.find((id) => !isBot(id));
@@ -9882,7 +10491,7 @@ function readWakeupTargets(snapshot, conversation, botId, operatorId) {
9882
10491
  userId: speaker
9883
10492
  } : {},
9884
10493
  botId: id,
9885
- channelId: conversation.id
10494
+ channelId: toOneBotChannelId(conversation, id)
9886
10495
  }));
9887
10496
  }
9888
10497
  function getServerInfo(runtime) {
@@ -10038,6 +10647,172 @@ function exportScene(runtime) {
10038
10647
  scene: runtime.control.getSnapshot()
10039
10648
  };
10040
10649
  }
10650
+ async function withChatLuna(run, notFound) {
10651
+ try {
10652
+ return await run();
10653
+ } catch (error) {
10654
+ if (!(error instanceof SandboxChatLunaError)) throw error;
10655
+ switch (error.reason) {
10656
+ case "unavailable": throw new SandboxMcpError("chatluna_unavailable", error.message, true, "确认 ChatLuna 对应的插件已经启用后重试。");
10657
+ case "not_found": throw notFound === "preset_not_found" ? new SandboxMcpError("preset_not_found", error.message, false, "用 list_presets 查看现有预设的 ID。") : new SandboxMcpError("model_call_not_found", error.message);
10658
+ case "forbidden": throw new SandboxMcpError("preset_forbidden", error.message, false, `新建以 ${TEST_PRESET_PREFIX} 开头的测试预设,或请用户在插件设置的可编辑预设里加入这个预设。`);
10659
+ case "conflict": throw new SandboxMcpError("revision_conflict", error.message, true, "用 get_preset 读取最新的 revision 后再保存。");
10660
+ case "invalid": throw new SandboxMcpError("invalid_arguments", error.message);
10661
+ }
10662
+ }
10663
+ }
10664
+ function tracePageUrl(sessionId) {
10665
+ return `/traces/${encodeURIComponent(sessionId)}`;
10666
+ }
10667
+ /**
10668
+ * 要读哪个 ChatLuna 会话:直接给会话 ID,或者给一条机器人回复、一条会话,按回复上记下的出处找。
10669
+ *
10670
+ * 出处由 `src/chatluna/state.ts` 在机器人发消息时写进 `message.chatLuna.trace`,所以只有经 ChatLuna
10671
+ * 生成的回复带它;命令回复与沙盒手动发出的消息没有。按回复找时同时记下它所在的那一步。
10672
+ */
10673
+ function resolveModelCallSession(runtime, args) {
10674
+ if (args.sessionId !== void 0) return { sessionId: requireString(args.sessionId, "sessionId") };
10675
+ const snapshot = runtime.control.getSnapshot();
10676
+ if (args.messageId !== void 0) {
10677
+ const messageId = requireString(args.messageId, "messageId");
10678
+ const message = snapshot.messages.find(({ id }) => id === messageId);
10679
+ if (!message) throw new SandboxMcpError("model_call_not_found", `消息不存在:${messageId}`);
10680
+ const trace = message.chatLuna?.trace;
10681
+ if (!trace) throw new SandboxMcpError("model_call_not_found", `消息 ${messageId} 没有模型调用出处:只有 ChatLuna 生成的机器人回复带出处`);
10682
+ return {
10683
+ sessionId: trace.sessionId,
10684
+ focus: {
10685
+ turn: trace.turn,
10686
+ step: trace.step
10687
+ },
10688
+ messageId
10689
+ };
10690
+ }
10691
+ if (args.conversationId !== void 0) {
10692
+ const conversationId = requireString(args.conversationId, "conversationId");
10693
+ if (!resolveConversation(snapshot, conversationId)) throw new SandboxMcpError("conversation_not_found", `会话不存在:${conversationId}`);
10694
+ const botId = args.botId === void 0 ? void 0 : requireString(args.botId, "botId");
10695
+ const ids = new Set(readConversationMessageIds(snapshot, conversationId));
10696
+ const message = snapshot.messages.filter((item) => ids.has(item.id) && item.chatLuna?.trace && (botId === void 0 || item.authorId === botId)).at(-1);
10697
+ if (!message?.chatLuna?.trace) throw new SandboxMcpError("model_call_not_found", `会话 ${conversationId} 里还没有带模型调用出处的机器人回复`);
10698
+ const { trace } = message.chatLuna;
10699
+ return {
10700
+ sessionId: trace.sessionId,
10701
+ focus: {
10702
+ turn: trace.turn,
10703
+ step: trace.step
10704
+ },
10705
+ messageId: message.id
10706
+ };
10707
+ }
10708
+ throw new SandboxMcpError("invalid_arguments", "sessionId、messageId、conversationId 至少需要提供一项");
10709
+ }
10710
+ async function readModelCalls(runtime, sessionId) {
10711
+ const calls = await withChatLuna(() => runtime.modelCalls.list(sessionId), "model_call_not_found");
10712
+ if (!calls) throw new SandboxMcpError("model_call_not_found", `ChatLuna 会话不存在:${sessionId}`);
10713
+ return calls;
10714
+ }
10715
+ async function listModelCalls(runtime, args) {
10716
+ const target = resolveModelCallSession(runtime, args);
10717
+ const limit = requireNumber(args.limit, "limit", {
10718
+ fallback: 20,
10719
+ min: 1,
10720
+ max: 200
10721
+ });
10722
+ const calls = await readModelCalls(runtime, target.sessionId);
10723
+ return {
10724
+ sessionId: target.sessionId,
10725
+ tracePage: tracePageUrl(target.sessionId),
10726
+ ...target.messageId ? {
10727
+ messageId: target.messageId,
10728
+ focus: target.focus
10729
+ } : {},
10730
+ total: calls.length,
10731
+ calls: calls.slice(-limit)
10732
+ };
10733
+ }
10734
+ async function getModelCall(runtime, args) {
10735
+ const target = resolveModelCallSession(runtime, args);
10736
+ const lastMessages = requireNumber(args.lastMessages, "lastMessages", {
10737
+ fallback: 30,
10738
+ min: 1,
10739
+ max: 1e3
10740
+ });
10741
+ const includeToolSchemas = optionalBoolean(args.includeToolSchemas, "includeToolSchemas") ?? false;
10742
+ let seq = optionalNumber(args.seq, "seq", { min: 0 });
10743
+ if (seq === void 0) {
10744
+ const turn = optionalNumber(args.turn, "turn", { min: 1 });
10745
+ const step = optionalNumber(args.step, "step", { min: 1 });
10746
+ const position = turn === void 0 ? target.focus : {
10747
+ turn,
10748
+ step
10749
+ };
10750
+ const calls = await readModelCalls(runtime, target.sessionId);
10751
+ const match = position ? calls.filter((call) => call.turn === position.turn && (position.step === void 0 || call.step === position.step)).at(-1) : calls.at(-1);
10752
+ if (!match) throw new SandboxMcpError("model_call_not_found", `会话 ${target.sessionId} 里没有这一步模型调用`);
10753
+ seq = match.seq;
10754
+ }
10755
+ const resolvedSeq = seq;
10756
+ const detail = await withChatLuna(() => runtime.modelCalls.get(target.sessionId, resolvedSeq, {
10757
+ lastMessages,
10758
+ includeToolSchemas
10759
+ }), "model_call_not_found");
10760
+ if (!detail) throw new SandboxMcpError("model_call_not_found", `会话 ${target.sessionId} 的第 ${resolvedSeq} 条记录不是模型调用`);
10761
+ return {
10762
+ sessionId: target.sessionId,
10763
+ tracePage: tracePageUrl(target.sessionId),
10764
+ ...detail
10765
+ };
10766
+ }
10767
+ function listPresets(runtime) {
10768
+ return withChatLuna(() => ({
10769
+ testPresetPrefix: TEST_PRESET_PREFIX,
10770
+ ...runtime.presets.list()
10771
+ }), "preset_not_found");
10772
+ }
10773
+ function getPreset(runtime, args) {
10774
+ const presetId = requireString(args.presetId, "presetId");
10775
+ return withChatLuna(() => runtime.presets.get(presetId), "preset_not_found");
10776
+ }
10777
+ /** 源文本已写入、解析却失败时 v2 照样返回,并沿用上一次成功解析的内容;不提示的话调用方会以为改动已经生效。 */
10778
+ function withParseWarning(preset) {
10779
+ return preset.status === "error" ? {
10780
+ preset,
10781
+ warning: "源文本已写入,但解析失败,ChatLuna 仍在使用上一次成功解析的内容;按 diagnostics 修正后重新保存"
10782
+ } : { preset };
10783
+ }
10784
+ async function createTestPreset(runtime, args) {
10785
+ const presetId = requireString(args.presetId, "presetId");
10786
+ const loader = args.loader === void 0 ? void 0 : requireString(args.loader, "loader");
10787
+ const copyFrom = args.copyFrom === void 0 ? void 0 : requireString(args.copyFrom, "copyFrom");
10788
+ if (args.text !== void 0 && typeof args.text !== "string") throw new SandboxMcpError("invalid_arguments", "text 必须是字符串");
10789
+ if (copyFrom !== void 0 && args.text !== void 0) throw new SandboxMcpError("invalid_arguments", "copyFrom 与 text 不能同时提供:复制后再用 save_preset 修改");
10790
+ const text = args.text;
10791
+ return withParseWarning(await withChatLuna(() => runtime.presets.create({
10792
+ id: presetId,
10793
+ loader,
10794
+ text,
10795
+ copyFrom
10796
+ }), "preset_not_found"));
10797
+ }
10798
+ async function savePreset(runtime, args) {
10799
+ const presetId = requireString(args.presetId, "presetId");
10800
+ if (typeof args.text !== "string") throw new SandboxMcpError("invalid_arguments", "text 必须是字符串");
10801
+ const text = args.text;
10802
+ const revision = requireString(args.revision, "revision");
10803
+ return withParseWarning(await withChatLuna(() => runtime.presets.save(presetId, text, revision), "preset_not_found"));
10804
+ }
10805
+ function deleteTestPreset(runtime, args) {
10806
+ const presetId = requireString(args.presetId, "presetId");
10807
+ const revision = args.revision === void 0 ? void 0 : requireString(args.revision, "revision");
10808
+ return withChatLuna(() => runtime.presets.remove(presetId, revision), "preset_not_found");
10809
+ }
10810
+ function setBotPreset(runtime, args) {
10811
+ const botId = requireString(args.botId, "botId");
10812
+ if (runtime.control.getSnapshot().participants.find((participant) => participant.id === botId)?.kind !== "bot") throw new SandboxMcpError("participant_not_found", `机器人不存在:${botId}`);
10813
+ const presetId = args.presetId === void 0 ? void 0 : requireString(args.presetId, "presetId");
10814
+ return withChatLuna(() => runtime.presets.assign(botId, presetId), "preset_not_found");
10815
+ }
10041
10816
  function uploadMedia(runtime, args) {
10042
10817
  const dataBase64 = requireString(args.dataBase64, "dataBase64");
10043
10818
  const digest = createHash("sha256").update(Buffer.from(dataBase64, "base64")).digest("hex");
@@ -10691,6 +11466,37 @@ const TOOL_ENTRIES = [
10691
11466
  requiresConfirmation: false,
10692
11467
  run: getWakeupRules
10693
11468
  },
11469
+ {
11470
+ name: "list_presets",
11471
+ scope: "read",
11472
+ description: "列出 ChatLuna 的预设、可用的预设格式,以及沙盒机器人当前切到的预设",
11473
+ inputSchema: {
11474
+ type: "object",
11475
+ properties: {},
11476
+ description: `writable 表示能否用 save_preset 修改:ID 以 ${TEST_PRESET_PREFIX} 开头的测试预设总是可以,其余预设要在插件设置的可编辑预设里。assignments 是 set_bot_preset 写下的切换。`
11477
+ },
11478
+ quota: "read",
11479
+ spaceResolution: "none",
11480
+ idempotent: false,
11481
+ requiresConfirmation: false,
11482
+ run: listPresets
11483
+ },
11484
+ {
11485
+ name: "get_preset",
11486
+ scope: "read",
11487
+ description: "读取一个预设的源文本、revision 与解析诊断",
11488
+ inputSchema: {
11489
+ type: "object",
11490
+ properties: { presetId: { type: "string" } },
11491
+ required: ["presetId"],
11492
+ description: "返回的 source.revision 是 save_preset 的乐观锁;插件提供的预设没有源文本,改给出解析后的 data。"
11493
+ },
11494
+ quota: "read",
11495
+ spaceResolution: "none",
11496
+ idempotent: false,
11497
+ requiresConfirmation: false,
11498
+ run: getPreset
11499
+ },
10694
11500
  {
10695
11501
  name: "upload_media",
10696
11502
  scope: "interact",
@@ -11390,6 +12196,116 @@ const TOOL_ENTRIES = [
11390
12196
  requiresConfirmation: true,
11391
12197
  run: importScene
11392
12198
  },
12199
+ {
12200
+ name: "create_test_preset",
12201
+ scope: "manage",
12202
+ description: `新建测试预设(ID 必须以 ${TEST_PRESET_PREFIX} 开头),可以复制一个已有预设`,
12203
+ inputSchema: {
12204
+ type: "object",
12205
+ properties: {
12206
+ presetId: {
12207
+ type: "string",
12208
+ description: `新预设的 ID,以 ${TEST_PRESET_PREFIX} 开头,只能含字母、数字、下划线、点与连字符`
12209
+ },
12210
+ loader: {
12211
+ type: "string",
12212
+ description: "预设格式,取 list_presets 返回的 loaders[].id;与 copyFrom 二选一"
12213
+ },
12214
+ text: {
12215
+ type: "string",
12216
+ description: "预设源文本;省略时用该格式的模板"
12217
+ },
12218
+ copyFrom: {
12219
+ type: "string",
12220
+ description: "复制这个预设的源文件,格式随源预设;不能与 text 同时提供"
12221
+ }
12222
+ },
12223
+ required: ["presetId"],
12224
+ description: "预设是 ChatLuna 的全局资源,不随测试空间删除;用完以后用 delete_test_preset 删掉。新建后用 set_bot_preset 让沙盒机器人用上它。"
12225
+ },
12226
+ quota: "mutation",
12227
+ spaceResolution: "none",
12228
+ idempotent: false,
12229
+ requiresConfirmation: false,
12230
+ run: createTestPreset
12231
+ },
12232
+ {
12233
+ name: "save_preset",
12234
+ scope: "manage",
12235
+ description: "保存预设源文本:测试预设,或插件设置里允许编辑的预设",
12236
+ inputSchema: {
12237
+ type: "object",
12238
+ properties: {
12239
+ presetId: { type: "string" },
12240
+ text: {
12241
+ type: "string",
12242
+ description: "完整的新源文本"
12243
+ },
12244
+ revision: {
12245
+ type: "string",
12246
+ description: "get_preset 返回的 source.revision;预设在此之后被改过时拒绝保存"
12247
+ }
12248
+ },
12249
+ required: [
12250
+ "presetId",
12251
+ "text",
12252
+ "revision"
12253
+ ],
12254
+ description: "保存后 ChatLuna 立即重新加载。解析失败时源文本照样写入,但 ChatLuna 沿用旧内容,返回值会带 warning 与 diagnostics。"
12255
+ },
12256
+ quota: "mutation",
12257
+ spaceResolution: "none",
12258
+ idempotent: false,
12259
+ requiresConfirmation: false,
12260
+ run: savePreset
12261
+ },
12262
+ {
12263
+ name: "delete_test_preset",
12264
+ scope: "manage",
12265
+ description: `删除测试预设(只限 ${TEST_PRESET_PREFIX} 开头的),并撤掉指向它的机器人切换`,
12266
+ inputSchema: {
12267
+ type: "object",
12268
+ properties: {
12269
+ presetId: { type: "string" },
12270
+ revision: {
12271
+ type: "string",
12272
+ description: "可选乐观锁;省略时不检查"
12273
+ }
12274
+ },
12275
+ required: ["presetId"]
12276
+ },
12277
+ quota: "mutation",
12278
+ spaceResolution: "none",
12279
+ idempotent: false,
12280
+ requiresConfirmation: false,
12281
+ run: deleteTestPreset
12282
+ },
12283
+ {
12284
+ name: "set_bot_preset",
12285
+ scope: "manage",
12286
+ description: "把沙盒机器人切到指定预设,或恢复为 ChatLuna 路由原本的预设",
12287
+ inputSchema: {
12288
+ type: "object",
12289
+ properties: {
12290
+ spaceId: SPACE_OPTIONAL,
12291
+ botId: {
12292
+ type: "string",
12293
+ description: "沙盒机器人的参与者 ID"
12294
+ },
12295
+ presetId: {
12296
+ type: "string",
12297
+ description: "要切到的预设;省略时撤掉切换,恢复路由原本的预设"
12298
+ }
12299
+ },
12300
+ required: ["botId"],
12301
+ description: "写成一条只命中这个机器人(OneBot 平台上的这个 selfId)的 ChatLuna 路由规则,持久保存,重启后仍然生效;按频道等写得更具体的用户规则仍会盖过它。切换后会话历史保留,从下一条消息起按新预设回复。"
12302
+ },
12303
+ quota: "mutation",
12304
+ spaceResolution: "read",
12305
+ idempotent: false,
12306
+ requiresConfirmation: false,
12307
+ run: setBotPreset
12308
+ },
11393
12309
  {
11394
12310
  name: "list_onebot_debug_records",
11395
12311
  scope: "debug",
@@ -11469,6 +12385,106 @@ const TOOL_ENTRIES = [
11469
12385
  requiresConfirmation: false,
11470
12386
  run: clearOneBotDebugRecords
11471
12387
  },
12388
+ {
12389
+ name: "list_model_calls",
12390
+ scope: "debug",
12391
+ description: "列出被测机器人一个 ChatLuna 会话里的模型调用(每一步的位置、回复摘要、工具调用、用量)",
12392
+ inputSchema: {
12393
+ type: "object",
12394
+ properties: {
12395
+ spaceId: SPACE_OPTIONAL,
12396
+ messageId: {
12397
+ type: "string",
12398
+ description: "机器人的一条回复:读生成它的那个 ChatLuna 会话"
12399
+ },
12400
+ conversationId: {
12401
+ type: "string",
12402
+ description: "沙盒会话:读其中最近一条机器人回复所在的 ChatLuna 会话"
12403
+ },
12404
+ botId: {
12405
+ type: "string",
12406
+ description: "与 conversationId 一起用:只看这个机器人的回复"
12407
+ },
12408
+ sessionId: {
12409
+ type: "string",
12410
+ description: "ChatLuna 会话 ID(trace 页地址里的那一段)"
12411
+ },
12412
+ limit: {
12413
+ type: "number",
12414
+ minimum: 1,
12415
+ maximum: 200,
12416
+ default: 20,
12417
+ description: "只返回最后这么多步"
12418
+ }
12419
+ },
12420
+ description: "messageId、conversationId、sessionId 三选一。返回的 seq 交给 get_model_call 读完整请求与响应。"
12421
+ },
12422
+ quota: "read",
12423
+ spaceResolution: "read",
12424
+ idempotent: false,
12425
+ requiresConfirmation: false,
12426
+ run: listModelCalls
12427
+ },
12428
+ {
12429
+ name: "get_model_call",
12430
+ scope: "debug",
12431
+ description: "读取一步模型调用的完整请求体(模型配置、系统提示词、工具、消息)与响应体",
12432
+ inputSchema: {
12433
+ type: "object",
12434
+ properties: {
12435
+ spaceId: SPACE_OPTIONAL,
12436
+ messageId: {
12437
+ type: "string",
12438
+ description: "机器人的一条回复:读生成它的那一步"
12439
+ },
12440
+ conversationId: {
12441
+ type: "string",
12442
+ description: "沙盒会话:读其中最近一条机器人回复的那一步"
12443
+ },
12444
+ botId: {
12445
+ type: "string",
12446
+ description: "与 conversationId 一起用:只看这个机器人的回复"
12447
+ },
12448
+ sessionId: {
12449
+ type: "string",
12450
+ description: "ChatLuna 会话 ID;只给它时读最近一步"
12451
+ },
12452
+ seq: {
12453
+ type: "number",
12454
+ minimum: 0,
12455
+ description: "list_model_calls 返回的 seq,优先于 turn/step"
12456
+ },
12457
+ turn: {
12458
+ type: "number",
12459
+ minimum: 1,
12460
+ description: "list_model_calls 返回的 turn;从 1 开始"
12461
+ },
12462
+ step: {
12463
+ type: "number",
12464
+ minimum: 1,
12465
+ description: "list_model_calls 返回的 step,从 1 开始;只给 turn 时读这一回合的最后一步"
12466
+ },
12467
+ lastMessages: {
12468
+ type: "number",
12469
+ minimum: 1,
12470
+ maximum: 1e3,
12471
+ default: 30,
12472
+ description: "请求里只返回最后这么多条消息;request.messageCount 是总数"
12473
+ },
12474
+ includeToolSchemas: {
12475
+ type: "boolean",
12476
+ default: false,
12477
+ description: "带上工具的完整参数 schema;默认只给名字与说明"
12478
+ }
12479
+ },
12480
+ description: "内容与 ChatLuna trace 页一致,是归一化后的请求与响应,不是供应商的原始 HTTP 报文;内联图片等 Base64 数据换成占位。"
12481
+ },
12482
+ quota: "read",
12483
+ spaceResolution: "read",
12484
+ idempotent: false,
12485
+ requiresConfirmation: false,
12486
+ run: getModelCall
12487
+ },
11472
12488
  {
11473
12489
  name: "list_test_call_records",
11474
12490
  scope: "debug",
@@ -11660,6 +12676,10 @@ const STABLE_ERROR_CODES = [
11660
12676
  "media_not_found",
11661
12677
  "invalid_media_url",
11662
12678
  "digest_mismatch",
12679
+ "chatluna_unavailable",
12680
+ "model_call_not_found",
12681
+ "preset_not_found",
12682
+ "preset_forbidden",
11663
12683
  "method_not_allowed",
11664
12684
  "payload_too_large",
11665
12685
  "domain_error",
@@ -11744,11 +12764,15 @@ var SandboxMcpService = class {
11744
12764
  testSpaces;
11745
12765
  /** 被测机器人当前的唤醒规则;工具声明、测试指南与 `get_wakeup_rules` 都问它。 */
11746
12766
  wakeup;
12767
+ modelCalls;
12768
+ presets;
11747
12769
  constructor(ctx, control, options) {
11748
12770
  this.ctx = ctx;
11749
12771
  this.control = control;
11750
12772
  this.testSpaces = options.testSpaces;
11751
12773
  this.wakeup = options.wakeup ?? new SandboxChatLunaWakeup(() => readSandboxResponderRuntimes(ctx));
12774
+ this.modelCalls = options.modelCalls ?? new SandboxChatLunaModelCalls(ctx);
12775
+ this.presets = options.presets ?? new SandboxChatLunaPresets(ctx, options.editablePresets ?? []);
11752
12776
  mkdirSync(options.dataDirectory, { recursive: true });
11753
12777
  this.credentialFile = join(options.dataDirectory, "test-credentials.json");
11754
12778
  this.eventLimit = options.eventLimit ?? 1e3;
@@ -12206,6 +13230,8 @@ var SandboxMcpService = class {
12206
13230
  appendEvent: (type, data, eventSpaceId = spaceId) => this.appendEvent(type, data, eventSpaceId),
12207
13231
  waitFor: (waitArgs, predicate) => this.waitFor(waitArgs, predicate),
12208
13232
  readWakeupRules: (targets) => this.wakeup.read(targets),
13233
+ modelCalls: this.modelCalls,
13234
+ presets: this.presets,
12209
13235
  requireTestSpaces: () => this.requireTestSpaces(),
12210
13236
  rememberUploadedMedia: (mediaId, media) => this.rememberUploadedMedia(this.mediaCacheKey(spaceId, mediaId), media),
12211
13237
  findUploadedMedia: (mediaId) => this.uploadedMedia.get(this.mediaCacheKey(spaceId, mediaId)),
@@ -12702,6 +13728,7 @@ const botToolFields = { botTools: Schema.object({
12702
13728
  Schema.const("debug").description("调试")
12703
13729
  ])).default(["read", "interact"]).role("checkbox").extra("label", "权限范围").description("只注册所选范围内的工具,含义与测试凭证的权限范围相同;修改操作同样只能作用于 AI 测试空间")
12704
13730
  }).description("工具调用") };
13731
+ const presetEditingFields = { presetEditing: Schema.object({ editablePresets: Schema.dynamic(EDITABLE_PRESETS_SCHEMA).default([]).extra("label", "可编辑预设").description("测试工具除了`sandbox-test-`前缀的测试预设,还可以修改这些预设;只能修改,不能删除") }).description("预设编辑") };
12705
13732
  /**
12706
13733
  * 插件设置的完整 schema,由沙盒工作台的「设置」页渲染(`src/settings.ts`)。
12707
13734
  *
@@ -12714,7 +13741,8 @@ const Settings = Schema.intersect([
12714
13741
  Schema.intersect([Schema.object(storageModeFields), Schema.object(sceneMessageFields).extra("i18n", "group.sceneMessages").description("场景消息")]).extra("i18n", "group.storage").extra("label", "数据存储").description("模拟环境的保存位置,以及消息的保留上限。上限按主环境与每个 AI 测试空间分别计算"),
12715
13742
  Schema.object({
12716
13743
  ...endpointFields,
12717
- ...botToolFields
13744
+ ...botToolFields,
13745
+ ...presetEditingFields
12718
13746
  }).extra("i18n", "group.endpoint").extra("label", "测试端点").description("供 AI 客户端操控沙盒的 MCP 与 HTTP 接口,同一组工具也可以交给 ChatLuna 机器人调用。两个端点共用监听器、访问限制与调用配额,配额按测试凭证分别计数,超出返回 429")
12719
13747
  ]);
12720
13748
  /**
@@ -12726,7 +13754,8 @@ const Config = Schema.object(Object.fromEntries(Object.entries({
12726
13754
  ...storageModeFields,
12727
13755
  ...sceneMessageFields,
12728
13756
  ...endpointFields,
12729
- ...botToolFields
13757
+ ...botToolFields,
13758
+ ...presetEditingFields
12730
13759
  }).map(([key, field]) => [key, field.hidden()]))).description("设置在 OneBot 沙盒工作台的「设置」页编辑");
12731
13760
  function apply(ctx, config) {
12732
13761
  const baseDir = resolveBaseDir(ctx);
@@ -12769,6 +13798,7 @@ function apply(ctx, config) {
12769
13798
  * 要么一起有要么一起没有。构造失败的唯一实际来源是建数据目录或读凭证文件,失败时沙盒工作台照常可用。
12770
13799
  */
12771
13800
  let endpoint;
13801
+ const presets = new SandboxChatLunaPresets(ctx, config.presetEditing.editablePresets);
12772
13802
  try {
12773
13803
  const mcp = new SandboxMcpService(ctx, control, {
12774
13804
  dataDirectory: resolve(baseDir, "data/chatluna/onebot-sandbox"),
@@ -12779,7 +13809,8 @@ function apply(ctx, config) {
12779
13809
  maxConcurrentMutations: config.testEndpoint.shared.maxConcurrentMutations,
12780
13810
  maxConcurrentWaits: config.testEndpoint.shared.maxConcurrentWaits,
12781
13811
  maxConcurrentUploads: config.testEndpoint.shared.maxConcurrentUploads,
12782
- testSpaces
13812
+ testSpaces,
13813
+ presets
12783
13814
  });
12784
13815
  endpoint = {
12785
13816
  mcp,
@@ -12819,8 +13850,9 @@ function apply(ctx, config) {
12819
13850
  sandboxAccentColor: config.sandboxAccentColor,
12820
13851
  sandboxMarkRecalledMessages: config.sandboxMarkRecalledMessages
12821
13852
  };
12822
- registerConsole(createWebuiRegistrar(ctx), control, appearance, endpoint, testSpaces);
13853
+ registerConsole(createWebuiRegistrar(ctx), control, appearance, endpoint, testSpaces, presets);
12823
13854
  registerSettings(ctx, Settings, "chatluna-plugin-onebot-sandbox");
13855
+ registerEditablePresetChoices(ctx);
12824
13856
  onStart(ctx, async () => {
12825
13857
  await control.waitForSceneReady();
12826
13858
  await endpoint?.server.start().catch((error) => ctx.logger.error("%s\n%s", "test endpoint listener failed to start", errorDetail(error)));