cortico-world-astrbot 1.3.3 → 1.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  让 Cortico 的人格 Bot 进 QQ 群说话,同时把 QQ 账号与插件能力留在 AstrBot 手里。
6
6
  *Join QQ conversations through an AstrBot bridge, keeping AstrBot's plugins while a Cortico persona drives the talking.*
7
7
 
8
- **当前版本:1.3.3**
8
+ **当前版本:1.3.4**
9
9
 
10
10
  项目地址:[as124da1231/cortico-world-astrbot](https://github.com/as124da1231/cortico-world-astrbot)。
11
11
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cortico-world-astrbot",
3
- "version": "1.3.3",
3
+ "version": "1.3.4",
4
4
  "type": "module",
5
5
  "description": "让 Cortico 人格进 QQ 群交流,AstrBot 保留插件与账号 / Join QQ conversations through an AstrBot bridge, keeping AstrBot plugins while Cortico persona chats",
6
6
  "license": "MIT",
package/src/driver.ts CHANGED
@@ -64,6 +64,8 @@ export interface SendResult {
64
64
  ok: boolean;
65
65
  /** ok 为 false 时的原因,可直接进工具回执。 */
66
66
  error?: string;
67
+ /** 失败时消息是否可能已经发出;true 表示「结果未知」,不要直接重试。 */
68
+ uncertain?: boolean;
67
69
  /** 桥是否真的把这条发成了语音(TTS 失败时会退回文字)。 */
68
70
  voice?: boolean;
69
71
  /** 成功但有需要说明的事,例如「TTS 没开,已改发文字」。 */
@@ -141,6 +143,8 @@ export interface BridgeDriverOptions {
141
143
  reconnectMaxMs?: number;
142
144
  /** 一次发送等确认的超时。 */
143
145
  sendTimeoutMs?: number;
146
+ /** WebSocket 握手(HTTP Upgrade)的超时;0 表示不设。 */
147
+ handshakeTimeoutMs?: number;
144
148
  /** 一次工具调用等回执的超时。 */
145
149
  toolTimeoutMs?: number;
146
150
  /** 心跳间隔;0 表示不做活性检测。 */
@@ -155,8 +159,20 @@ interface PendingSend {
155
159
  timer: ReturnType<typeof setTimeout>;
156
160
  }
157
161
 
158
- /** 发送确认的默认超时。 */
159
- export const DEFAULT_SEND_TIMEOUT_MS = 15_000;
162
+ /** 发送确认的默认超时。要覆盖桥侧的排队 + TTS + 平台发送。 */
163
+ export const DEFAULT_SEND_TIMEOUT_MS = 30_000;
164
+
165
+ /** 带图发送额外等待:图片要经桥转给 QQ,慢网下会久一点。 */
166
+ export const IMAGE_SEND_EXTRA_MS = 20_000;
167
+
168
+ /** 语音发送额外等待:桥侧 TTS 最多等 30 秒,再加平台发送。 */
169
+ export const VOICE_SEND_EXTRA_MS = 40_000;
170
+
171
+ /** WebSocket 握手默认超时;对端只接受 TCP、不回 Upgrade 时靠它收尾。 */
172
+ export const DEFAULT_HANDSHAKE_TIMEOUT_MS = 10_000;
173
+
174
+ /** 握手超时之外再留一点余量,防止底层没发 close。 */
175
+ const HANDSHAKE_GUARD_EXTRA_MS = 2_000;
160
176
 
161
177
  /** 工具回执的默认超时:有些工具本身会查网、生成图片,给宽一点。 */
162
178
  export const DEFAULT_TOOL_TIMEOUT_MS = 90_000;
@@ -280,7 +296,7 @@ export class AstrbotBridgeDriver implements BridgeDriver {
280
296
  clearTimeout(this.reconnectTimer);
281
297
  this.reconnectTimer = undefined;
282
298
  }
283
- this.rejectAllPending('驱动已停止');
299
+ this.rejectAllPending('驱动已停止', true);
284
300
  const ws = this.ws;
285
301
  this.ws = undefined;
286
302
  const was = this.connected;
@@ -304,11 +320,15 @@ export class AstrbotBridgeDriver implements BridgeDriver {
304
320
  // 带图/语音的帧更大、更慢,给桥多一点时间。
305
321
  const timeout =
306
322
  (this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS) +
307
- (image ? 15_000 : 0) +
308
- (voice ? 20_000 : 0);
323
+ (image ? IMAGE_SEND_EXTRA_MS : 0) +
324
+ (voice ? VOICE_SEND_EXTRA_MS : 0);
309
325
  const timer = setTimeout(() => {
310
326
  this.pending.delete(rid);
311
- resolve({ ok: false, error: `桥没有在 ${timeout}ms 内确认` });
327
+ resolve({
328
+ ok: false,
329
+ uncertain: true,
330
+ error: `桥没有在 ${timeout}ms 内确认,消息可能已经发出`,
331
+ });
312
332
  }, timeout);
313
333
  this.pending.set(rid, { resolve, timer });
314
334
  const frame: Record<string, unknown> = {
@@ -336,18 +356,23 @@ export class AstrbotBridgeDriver implements BridgeDriver {
336
356
  return;
337
357
  }
338
358
  let settled = false;
359
+ let guard: ReturnType<typeof setTimeout> | undefined;
339
360
  const settle = (): void => {
340
361
  if (!settled) {
341
362
  settled = true;
363
+ if (guard) clearTimeout(guard);
342
364
  onSettled?.();
343
365
  }
344
366
  };
345
367
 
346
368
  const token = this.opts.token;
369
+ const handshakeMs = this.opts.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS;
347
370
  let ws: WebSocket;
348
371
  try {
349
372
  ws = new WebSocket(this.opts.wsUrl, {
350
373
  headers: token ? { Authorization: `Bearer ${token}` } : undefined,
374
+ // 对端只接受 TCP、不回 101 时,ws 自己不会超时;这里必须给。
375
+ ...(handshakeMs > 0 ? { handshakeTimeout: handshakeMs } : {}),
351
376
  });
352
377
  } catch (err) {
353
378
  this.log.warn('桥地址无法解析', {
@@ -360,6 +385,22 @@ export class AstrbotBridgeDriver implements BridgeDriver {
360
385
  }
361
386
  this.ws = ws;
362
387
 
388
+ if (handshakeMs > 0) {
389
+ guard = setTimeout(() => {
390
+ if (this.stopped || this.ws !== ws || settled) return;
391
+ this.log.warn('桥连接在握手超时内没有完成,重建连接', {
392
+ wsUrl: this.opts.wsUrl,
393
+ timeoutMs: handshakeMs + HANDSHAKE_GUARD_EXTRA_MS,
394
+ });
395
+ try {
396
+ ws.terminate();
397
+ } catch {
398
+ // 已经断了就算了;close 会接手重连。
399
+ }
400
+ settle();
401
+ }, handshakeMs + HANDSHAKE_GUARD_EXTRA_MS);
402
+ }
403
+
363
404
  ws.on('open', () => {
364
405
  if (this.stopped || this.ws !== ws) {
365
406
  ws.terminate();
@@ -419,7 +460,7 @@ export class AstrbotBridgeDriver implements BridgeDriver {
419
460
  this.stopHeartbeat();
420
461
  this.ws = undefined;
421
462
  this.connected = false;
422
- this.rejectAllPending('与桥的连接已断开');
463
+ this.rejectAllPending('与桥的连接已断开', true);
423
464
  if (wasConnected) this.log.info('与 AstrBot 桥的连接已断开');
424
465
  }
425
466
  settle();
@@ -479,10 +520,20 @@ export class AstrbotBridgeDriver implements BridgeDriver {
479
520
  }
480
521
 
481
522
  private handleFrame(raw: string): void {
482
- let frame: Record<string, unknown>;
523
+ // 一帧坏数据不能把整个 Coo 带下去:事件回调里抛错会升级成
524
+ // uncaughtException,宿主通常会直接关机。
483
525
  try {
484
- frame = JSON.parse(raw) as Record<string, unknown>;
485
- } catch {
526
+ this.handleFrameUnsafe(raw);
527
+ } catch (err) {
528
+ this.log.error('处理桥帧失败,已忽略', {
529
+ error: err instanceof Error ? err.message : String(err),
530
+ });
531
+ }
532
+ }
533
+
534
+ private handleFrameUnsafe(raw: string): void {
535
+ const frame = parseFrame(raw);
536
+ if (!frame) {
486
537
  this.log.warn('收到无法解析的帧,已忽略');
487
538
  return;
488
539
  }
@@ -506,7 +557,11 @@ export class AstrbotBridgeDriver implements BridgeDriver {
506
557
  voice: frame.voice === true,
507
558
  note: typeof frame.note === 'string' ? frame.note : undefined,
508
559
  }
509
- : { ok: false, error: String(frame.error ?? '桥拒绝发送') },
560
+ : {
561
+ ok: false,
562
+ error: String(frame.error ?? '桥拒绝发送'),
563
+ uncertain: frame.uncertain === true,
564
+ },
510
565
  );
511
566
  return;
512
567
  }
@@ -632,10 +687,10 @@ export class AstrbotBridgeDriver implements BridgeDriver {
632
687
  }
633
688
  }
634
689
 
635
- private rejectAllPending(reason: string): void {
690
+ private rejectAllPending(reason: string, uncertain = false): void {
636
691
  for (const call of this.pending.values()) {
637
692
  clearTimeout(call.timer);
638
- call.resolve({ ok: false, error: reason });
693
+ call.resolve({ ok: false, error: reason, uncertain });
639
694
  }
640
695
  this.pending.clear();
641
696
  for (const call of this.pendingTools.values()) {
@@ -646,6 +701,21 @@ export class AstrbotBridgeDriver implements BridgeDriver {
646
701
  }
647
702
  }
648
703
 
704
+ /**
705
+ * 解析一帧文本。合法 JSON 不代表是对象:`null`(以及数字、字符串、数组)
706
+ * 都不能往下走,否则 `frame.t` 会在 null 上抛 TypeError。
707
+ */
708
+ export function parseFrame(raw: string): Record<string, unknown> | null {
709
+ let parsed: unknown;
710
+ try {
711
+ parsed = JSON.parse(raw);
712
+ } catch {
713
+ return null;
714
+ }
715
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
716
+ return parsed as Record<string, unknown>;
717
+ }
718
+
649
719
  /** 把一帧 `msg` 收敛成 BridgeMessage;形状不对时返回 null。 */
650
720
  export function parseMessage(frame: Record<string, unknown>): BridgeMessage | null {
651
721
  const convRaw = frame.conv as Record<string, unknown> | undefined;
package/src/history.ts CHANGED
@@ -58,7 +58,18 @@ export function readLatest(
58
58
  return picked.reverse();
59
59
  }
60
60
 
61
- /** 关键词搜索该会话,每处命中带前后若干条,按时间升序拼接。 */
61
+ /** 一次搜索最多扫多少条事件,防止历史很长时把一次工具调用拖太久。 */
62
+ const MAX_SEARCH_SCAN = 20_000;
63
+ /** 翻页大小。 */
64
+ const SEARCH_PAGE = 500;
65
+
66
+ /**
67
+ * 关键词搜索该会话,每处命中带前后若干条,按时间升序拼接。
68
+ *
69
+ * 不能直接用 store.grep:它的 limit 在「按会话过滤」之前计数,别的会话
70
+ * 命中一多,本会话就会被挤成 0 条;它的 context 也不筛会话,可能把
71
+ * 别的会话的上下文当成命中返回。这里从最新往回翻,先筛会话再匹配。
72
+ */
62
73
  export function search(
63
74
  store: EventStoreReader,
64
75
  conv: Conv,
@@ -67,16 +78,31 @@ export function search(
67
78
  context: number,
68
79
  sender?: string,
69
80
  ): EventEnvelope[][] {
70
- const hits = store.grep({
71
- keyword,
72
- context,
73
- source: 'astrbot',
74
- origin: 'external',
75
- limit,
76
- ...(sender ? { senderKey: sender } : {}),
77
- });
81
+ const needle = keyword.toLowerCase();
82
+ const hits: EventEnvelope[] = [];
83
+ let toCursor = store.latestCursor();
84
+ let scanned = 0;
85
+
86
+ while (hits.length < limit && toCursor > 0 && scanned < MAX_SEARCH_SCAN) {
87
+ const page = store.range({ ...BASE, toCursor, limit: SEARCH_PAGE });
88
+ if (page.length === 0) break;
89
+ scanned += page.length;
90
+ for (let i = page.length - 1; i >= 0 && hits.length < limit; i--) {
91
+ const e = page[i]!;
92
+ if (!inConv(e, conv)) continue;
93
+ if (sender && String(e.senderKey ?? '') !== sender) continue;
94
+ if (!String(e.text ?? '').toLowerCase().includes(needle)) continue;
95
+ hits.push(e);
96
+ }
97
+ if (page.length < SEARCH_PAGE) break;
98
+ const first = page[0]!.cursor;
99
+ if (first <= 1) break;
100
+ toCursor = first - 1;
101
+ }
102
+
78
103
  return hits
79
- .map((hit) => hit.events.filter((e) => inConv(e, conv)))
104
+ .reverse()
105
+ .map((hit) => store.around(hit.cursor, context, context).filter((e) => inConv(e, conv)))
80
106
  .filter((group) => group.length > 0);
81
107
  }
82
108
 
package/src/version.ts ADDED
@@ -0,0 +1,15 @@
1
+ /** 扩展版本:直接读包根的 package.json,避免在代码里再手写一份。 */
2
+ import { readFileSync } from 'node:fs';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ function readVersion(): string {
6
+ try {
7
+ const path = fileURLToPath(new URL('../package.json', import.meta.url));
8
+ const pkg = JSON.parse(readFileSync(path, 'utf8')) as { version?: unknown };
9
+ return typeof pkg.version === 'string' ? pkg.version : '';
10
+ } catch {
11
+ return '';
12
+ }
13
+ }
14
+
15
+ export const EXTENSION_VERSION = readVersion();
package/src/world.ts CHANGED
@@ -20,6 +20,7 @@ import {
20
20
  } from './config.ts';
21
21
  import {
22
22
  AstrbotBridgeDriver,
23
+ DEFAULT_HANDSHAKE_TIMEOUT_MS,
23
24
  type BridgeDriver,
24
25
  type BridgeMessage,
25
26
  type Conv,
@@ -27,6 +28,7 @@ import {
27
28
  type ToolInfo,
28
29
  } from './driver.ts';
29
30
  import { convOfEvent, renderLatest, renderSearch } from './history.ts';
31
+ import { EXTENSION_VERSION } from './version.ts';
30
32
 
31
33
  const ENV_PROMPT_FILE = fileURLToPath(new URL('./ENV_PROMPT.md', import.meta.url));
32
34
 
@@ -36,6 +38,12 @@ export const MAX_IMAGE_BYTES = 6 * 1024 * 1024;
36
38
  /** 收到带权限的消息后,这个会话在多久内可以发图。 */
37
39
  export const SCREENSHOT_GRANT_MS = 120_000;
38
40
 
41
+ /**
42
+ * 等桥完成首次连接的默认上限。到点先让 Coo 继续启动,驱动在后台继续重连;
43
+ * 单个 World 不该把整条启动链拖死。
44
+ */
45
+ export const DEFAULT_START_TIMEOUT_MS = 12_000;
46
+
39
47
  /** 从 ISO 时间里取 HH:MM;取不到就返回 --:--。 */
40
48
  function hhmm(iso: string | undefined): string {
41
49
  if (!iso) return '--:--';
@@ -56,6 +64,10 @@ export interface AstrbotWorldOptions {
56
64
  timezone: string;
57
65
  /** 测试用:换掉真实驱动。 */
58
66
  driver?: BridgeDriver;
67
+ /** 首次连接最多等多久;到点先继续启动,后台继续重连。 */
68
+ startTimeoutMs?: number;
69
+ /** WebSocket 握手超时;0 表示不设。 */
70
+ handshakeTimeoutMs?: number;
59
71
  }
60
72
 
61
73
  /** 全部工具的声明;`describe` 与 `tools()` 都取这一份。 */
@@ -189,8 +201,8 @@ export class AstrbotWorld implements World {
189
201
  private readonly convs = new Map<string, Conv>();
190
202
  /** 最后一条消息所在的会话;工具不指定会话时用它。 */
191
203
  private lastConv?: Conv;
192
- /** 会话 -> 可以发图的截止时刻;由桥在消息帧里给权限。 */
193
- private readonly shotGrants = new Map<string, number>();
204
+ /** 会话 -> 可发图授权;绑定到给权限的那条消息,轮次结束即失效。 */
205
+ private readonly shotGrants = new Map<string, { until: number; msgId: string }>();
194
206
  /** 发送时间戳,用于每分钟上限。 */
195
207
  private sendStamps: number[] = [];
196
208
  /** 桥那边启用的工具;只在环境提示词里列出来,不注册成原生工具。 */
@@ -275,6 +287,9 @@ export class AstrbotWorld implements World {
275
287
 
276
288
  webUi(): WorldWebUiDecl {
277
289
  return {
290
+ ...(EXTENSION_VERSION
291
+ ? { badges: [{ label: '版本', value: EXTENSION_VERSION, tone: 'plain' as const }] }
292
+ : {}),
278
293
  config: [ASTRBOT_CONFIG_GROUP],
279
294
  promptDocs: [
280
295
  {
@@ -310,6 +325,7 @@ export class AstrbotWorld implements World {
310
325
  capabilities: { images: this.acceptsImages(host) },
311
326
  reconnectBaseMs: cfg.reconnectBaseMs,
312
327
  reconnectMaxMs: cfg.reconnectMaxMs,
328
+ handshakeTimeoutMs: this.opts.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS,
313
329
  log: host.log,
314
330
  });
315
331
  this.driver = driver;
@@ -369,15 +385,38 @@ export class AstrbotWorld implements World {
369
385
  });
370
386
  });
371
387
 
372
- // 连不上不抛错:start 只承诺「尝试过」,桥没起来不该拖垮整个装配。
373
- try {
374
- await driver.start();
375
- } catch (err) {
376
- host.log.warn('连接 AstrBot 桥失败', {
377
- error: err instanceof Error ? err.message : String(err),
388
+ // 连不上不抛错,也不无限等:桥没起来或握手卡住都不该拖垮整个装配。
389
+ // 到点后驱动仍在后台重连,连上会通过 onState 把状态推回来。
390
+ await this.waitDriverStart(driver, this.opts.startTimeoutMs ?? DEFAULT_START_TIMEOUT_MS);
391
+ this.connected = driver.connected;
392
+ }
393
+
394
+ /** 等首次连接,但最多等 timeoutMs;超时只记日志,不终止后台重连。 */
395
+ private async waitDriverStart(driver: BridgeDriver, timeoutMs: number): Promise<void> {
396
+ const limit = Math.max(1, timeoutMs);
397
+ let timer: ReturnType<typeof setTimeout> | undefined;
398
+ const timedOut = new Promise<boolean>((resolve) => {
399
+ timer = setTimeout(() => resolve(false), limit);
400
+ });
401
+ const started = driver
402
+ .start()
403
+ .then(() => true)
404
+ .catch((err: unknown) => {
405
+ this.host?.log.warn('连接 AstrBot 桥失败', {
406
+ error: err instanceof Error ? err.message : String(err),
407
+ });
408
+ return true;
378
409
  });
410
+ try {
411
+ const ok = await Promise.race([started, timedOut]);
412
+ if (!ok) {
413
+ this.host?.log.warn('连接 AstrBot 桥超时,先继续启动,后台继续重连', {
414
+ timeoutMs: limit,
415
+ });
416
+ }
417
+ } finally {
418
+ if (timer) clearTimeout(timer);
379
419
  }
380
- this.connected = driver.connected;
381
420
  }
382
421
 
383
422
  async stop(): Promise<void> {
@@ -461,7 +500,7 @@ export class AstrbotWorld implements World {
461
500
  // 通知不是人说的话,不能拿它撤销授权。
462
501
  if (!isNotice) {
463
502
  if (msg.canScreenshot) {
464
- this.grantScreenshot(msg.conv);
503
+ this.grantScreenshot(msg.conv, msg.id);
465
504
  } else {
466
505
  this.shotGrants.delete(`${msg.conv.kind}:${msg.conv.id}`);
467
506
  }
@@ -729,7 +768,12 @@ export class AstrbotWorld implements World {
729
768
  const result = await driver.send(conv, text, replyTo, image, voice);
730
769
  const where = conv.kind === 'group' ? `群「${conv.name ?? conv.id}」` : '私聊';
731
770
  if (!result.ok) {
732
- return { text: `没有发出:${result.error ?? '未知原因'}`, failed: true };
771
+ const reason = result.error ?? '未知原因';
772
+ const lead = result.uncertain ? '没有确认发出' : '没有发出';
773
+ const hint = result.uncertain
774
+ ? ';这条可能已经发出,先确认再决定要不要重试,不要直接重发'
775
+ : '';
776
+ return { text: `${lead}:${reason}${hint}`, failed: true };
733
777
  }
734
778
  const what = result.voice
735
779
  ? image
@@ -758,19 +802,29 @@ export class AstrbotWorld implements World {
758
802
  return this.lastConv;
759
803
  }
760
804
 
761
- /** 记下「这个会话可以发图到什么时候」;顺手清掉过期项,免得表一直长。 */
762
- private grantScreenshot(conv: Conv): void {
805
+ /** 记下「这个会话、这条消息可以发图到什么时候」;顺手清掉过期项。 */
806
+ private grantScreenshot(conv: Conv, msgId: string): void {
807
+ if (!msgId) return;
763
808
  const now = Date.now();
764
- for (const [key, until] of this.shotGrants) {
765
- if (until <= now) this.shotGrants.delete(key);
809
+ for (const [key, grant] of this.shotGrants) {
810
+ if (grant.until <= now) this.shotGrants.delete(key);
766
811
  }
767
- this.shotGrants.set(`${conv.kind}:${conv.id}`, now + SCREENSHOT_GRANT_MS);
812
+ this.shotGrants.set(`${conv.kind}:${conv.id}`, {
813
+ until: now + SCREENSHOT_GRANT_MS,
814
+ msgId,
815
+ });
768
816
  }
769
817
 
770
- /** 这个会话现在能不能发图。 */
818
+ /**
819
+ * 这一轮能不能发图:必须是当前 QQ 轮次、必须是授权所在的会话,
820
+ * 而且授权要来自这一轮最后一条人话。桌宠轮次和只收到通知的轮次都不行。
821
+ */
771
822
  private mayScreenshot(conv: Conv): boolean {
772
- const until = this.shotGrants.get(`${conv.kind}:${conv.id}`) ?? 0;
773
- return until > Date.now();
823
+ if (!this.qqTurnActive()) return false;
824
+ if (this.turnConv?.kind !== conv.kind || this.turnConv.id !== conv.id) return false;
825
+ if (!this.turnMsgId) return false;
826
+ const grant = this.shotGrants.get(`${conv.kind}:${conv.id}`);
827
+ return !!grant && grant.until > Date.now() && grant.msgId === this.turnMsgId;
774
828
  }
775
829
 
776
830
  private historyTool(): ToolDef {
@@ -807,6 +861,7 @@ export class AstrbotWorld implements World {
807
861
  handler: async () => {
808
862
  const cfg = this.opts.cfg;
809
863
  const lines: string[] = [];
864
+ if (EXTENSION_VERSION) lines.push(`版本:${EXTENSION_VERSION}`);
810
865
  lines.push(`桥地址:${cfg.wsUrl || '(未配置)'}`);
811
866
  lines.push(`连接:${this.connected ? '已连上' : '未连上'}`);
812
867
  lines.push('渠道:QQ(经 AstrBot 桥)');