Repository navigation
Expand file tree
/
Copy pathgroups.js
More file actions
8328 lines (8104 loc) · 420 KB
/
Copy pathgroups.js
File metadata and controls
8328 lines (8104 loc) · 420 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Group chats: the room ledger, members' group Sessions, 3-way message protocol
// (`visible` / `invite` / `call`), SQLite-backed Bot-to-Bot delegations (`room_work`
// + `calls` + `waits`), group report-back, and group tools (`group_relay`,
// `read_own_chat`, `read_group_chat`).
//
// 3-way protocol:
// - `visible` (`note`): written to `ledger/group-*.jsonl`, 0 model wakes. Body `@Name`
// written by a Bot is strictly display-only and never creates calls or wakes.
// - `invite`: user message (`admin` mode / `everyone` ordered / user `@Name` or `@all`),
// kickoff, or goal cue — grants 1 speaking opportunity (may `[PASS]`), no owed deliverable.
// - `call`: explicit Bot-to-Bot delegation (`delegate_work` / `post_to_group(intent='request')`)
// persisted in `coordination.sqlite` (`works(kind='room_work') + calls + waits`), with
// directed wait-cycle detection, single-settlement barrier back to the fixed caller,
// and hard-signal no-progress pause (no fixed round/text heuristics).
import { createHash, randomUUID } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { rm } from 'node:fs/promises'
import { join } from 'node:path'
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import { defineTool } from '@deepseek-ai/dsh-tools'
import { claimsFor } from './claims.js'
import {
GROUP_LINE_READ,
HISTORY_PAGE,
HISTORY_TIMEOUT_MS,
INSTANT_WORK_TOOLS,
MESSAGE_INLINE_MAX,
ROOM_REPLY_TIMEOUT_MS,
ROOM_STEP_GAP_MS,
ROOM_WORK_GRACE_MS,
SOURCE_KIND,
TEXT_KEPT,
isWorkTool,
} from './constants.js'
import { searchGroupBook } from './group-search.js'
import { extractClaimKeys, mergeDuplicateRevision, normalizeGoalKey, stripLeadingMentions } from './handoffs.js'
import { parseBook } from './ledger.js'
import {
addressedMembers,
classifyBotGroupSpeech,
explicitCallees,
isCallRoute,
isInviteRoute,
isResultRoute,
isVisibleRoute,
resolveUserInvite,
roomCall,
roomResult,
roomVisible,
waitsOnMember,
} from './room-message.js'
import { createRoomReports } from './room-reports.js'
import { redactDeep } from './secrets.js'
import { escapeRegExp, excerpt, headOf, reminderPrompts, splitRef, stripReasoning, textOf } from './text.js'
import { foregroundAddress, roomMemberAddress } from './threads.js'
import { GROUP_REF, output } from './tools.js'
import { failureLine } from './turns.js'
import { REPLY_ELISION, parseReplies, presentedFiles, relayRange } from '../shared/group-replies.js'
import { viaIsIm, viaOf } from '../shared/im-platforms.js'
import { captureMentionRefs, mentionSpans, referenceSpans, speakerOf } from '../shared/mentions.js'
import { stripToolCallTags } from '../shared/assistant-text.js'
const ROOM_LOG_MAX = 60
const ROOM_FIRST_LOOK = 12
const ROOM_DELTA_MAX = 24
const ROOM_EARLIER_MAX = 8
const ROOM_READ_MAX = 30
const BACKFILL_WINDOW = 5
const CALLER_WORK_KIND = 'room_caller'
const CALL_WORK_KIND = 'room_call'
const CHAIN_WORK_KIND = 'room_chain'
const REPORT_WORK_KIND = 'room_report'
const TERMINAL_STATUSES = new Set(['done', 'failed', 'stopped'])
const isPrivateBot = bot => bot?.private === true || bot?.privacy === true
const roomChainWorkId = roomId => `rw_chain:${roomId}`
const SHOWN_ONLY = new Set(['working', 'approval'])
// Kind rows that stay visible after a refused write (a notice carries its own kind).
const KIND_RESIDUE = new Set(['done', 'stopped', 'cut', 'resumed', 'lookup'])
const memberLine = record => record !== undefined && !SHOWN_ONLY.has(record.kind)
const unseenWindow = (room, memberId) => {
const since = room.seen[memberId]
if (since === undefined) {
return { all: room.log, lines: room.log.slice(-ROOM_FIRST_LOOK) }
}
const all = room.log.filter(line => line.seq > since && line.botId !== memberId)
return { all, lines: all.slice(-ROOM_DELTA_MAX) }
}
const unseenLines = (room, memberId) => unseenWindow(room, memberId).lines
const goalNotice = (line) => {
switch (line.event) {
case 'draft': return 'The user asked for a goal for this group; the admin is aligning it with them.'
case 'start': return `Goal "${line.title}" started with ${line.count} stages; stage 1 "${line.next ?? ''}" is current.`
case 'pass': return line.next !== undefined
? `Goal "${line.title}": stage ${line.stage} of ${line.count} passed; stage ${line.stage + 1} "${line.next}" is current.`
: `Goal "${line.title}": stage ${line.stage} of ${line.count} passed; every stage passed.`
case 'rework': return `Goal "${line.title}": stage ${line.stage} was sent back: ${line.text ?? ''}`
case 'revise': return `Goal "${line.title}" was changed: ${line.text ?? ''}`
case 'pause': return line.text ? `Goal "${line.title}" is paused (${line.text}). Start no new stage work.` : `Goal "${line.title}" is paused. Start no new stage work.`
case 'resume': return `Goal "${line.title}" is resumed.`
case 'complete': return `Goal "${line.title}" is complete.`
case 'stop': return `Goal "${line.title}" was stopped: ${line.text ?? ''}`
default: return line.text ?? ''
}
}
const noticeText = (line) => {
if (line.reason === 'missed') return `${(line.names ?? []).join(' and ')} did not answer within ${line.minutes} minutes, so this round moved on without it. If it is still working, it posts its result later as a late reply; if it is urgent, the user can write here or the admin can follow up.`
if (line.reason === 'paused' && line.cause === 'no_progress') return `Paused: ${[line.from, ...(line.names ?? [])].filter(Boolean).join(' and ')} made no measurable progress across ${line.count ?? line.limit ?? 3} attempts. Waiting for the user to continue or adjust.`
if (line.reason === 'paused' && line.idle && (line.names ?? []).length === 0) return `Paused: Bots here posted ${line.limit} status updates with no new work, the last from ${line.from ?? 'a member'}. Waiting for the user to continue.`
if (line.reason === 'paused' && line.idle && line.cause === 'cycle') return `Paused: ${[line.from, ...(line.names ?? [])].filter(Boolean).join(' and ')} formed a wait cycle. Waiting for the user.`
if (line.reason === 'paused') return `Paused: Bots waited on the same unresolved step without measurable progress. Waiting for the user to continue or stop.`
if (line.reason === 'admin-passed') return `${(line.names ?? []).join(' and ') || 'The admin'} did not answer or delegate to anyone. The user can address a member with @Name.`
if (line.reason === 'folder') return `The group's folder ${line.path} is gone, so its members work in the team workspace; set the group's folder again in the group's settings.`
if (line.reason === 'goal') return goalNotice(line)
if (line.reason === 'failed') return `${(line.names ?? []).join(' and ')} stopped: its model call failed (${line.detail}). What it was doing here is not finished; the user can switch its model in its settings or ask it to go on.`
if (line.reason === 'helper-failed') return `${(line.names ?? []).join(' and ')}'s background helper did not finish: ${line.detail}. The work it was doing here is not finished; ask it to go on if it still matters.`
return line.text ?? ''
}
const presentedLine = file => `[Presented file ${file.path}${file.description ? `: ${file.description}` : ''}]`
// `text` is what to show of a message line, by default what the log keeps of it.
export const lineText = (line, text = line.text) => {
if (line.kind === 'lookup') return `[${speakerOf(line)} looked up its own chat${line.text ? ` for "${line.text}"` : ''}]`
if (line.kind === 'resumed') return `[${speakerOf(line)}'s work here was cut off when DeepSeek Harness restarted; it is picking it back up and posts when done]`
if (line.kind === 'cut') return `[${speakerOf(line)}'s work here was cut off by a restart again, so it stopped; ask it to go on if it still matters]`
if (line.kind === 'stopped') return `[The user stopped ${speakerOf(line)}'s work here]`
if (line.kind === 'done') return `[${speakerOf(line)} finished the work it was asked for]`
if (line.kind === 'notice') return `[${noticeText(line)}]`
const body = [text, ...(line.presented ?? []).map(presentedLine)].filter(Boolean).join('\n')
return `${speakerOf(line)}: ${body}`
}
const transcript = (lines, textOfLine = line => line.text, project = line => line) => lines.map(line => lineText(project(line), textOfLine(line))).join('\n')
// Models often echo the transcript format ("Name: …") despite the instruction.
export const stripOwnName = (name, text) => text.replace(new RegExp(`^\\s*\\**${escapeRegExp(name)}\\**\\s*[::]\\s*`), '').trim()
export const isPass = text => text === '' || /^\s*[[【((]\s*pass\s*[\]】))]|^\s*pass\s*[.。!!]?\s*$/i.test(text)
// The write a drawn line queued is remembered per book AND seq: `room.seq` counts from 1 in
// every room, so a bare seq would make two rooms share one entry in this host-wide table.
export const lineWriteKeyOf = (roomId, seq) => `group-${roomId}:${seq}`
// Who "@" names in order, using the same span rules as the chat bubbles.
export const mentionsIn = (text, members, references = []) => {
const found = []
let all = false
for (const span of mentionSpans(text, members, { references: references.flatMap(reference => reference.labels) })) {
if (span.all) all = true
else if (!found.includes(span.bot)) found.push(span.bot)
}
return { all, found }
}
function mentionsOf(opener, everyone) {
if (opener.route) {
if (isVisibleRoute(opener.route)) return { all: false, found: [] }
if (isCallRoute(opener.route) && !opener.mentions) {
return { all: false, found: explicitCallees(opener.route, everyone, opener.botId) }
}
if (isResultRoute(opener.route) || isInviteRoute(opener.route)) {
return { all: false, found: addressedMembers(opener.route, everyone, opener.botId) }
}
}
const saved = opener?.mentions
if (saved === undefined || !Array.isArray(saved.ids)) return undefined
const byId = new Map(everyone.map(bot => [bot.id, bot]))
const found = []
for (const id of saved.ids) {
const bot = byId.get(id)
if (bot !== undefined && !found.includes(bot)) found.push(bot)
}
return { all: saved.all === true, found }
}
export const referenceNote = references => (references?.length
? `Conversations the user referenced in this round:\n\n${references.map(reference => reference.text).join('\n\n')}`
: '')
const ROOM_REPLY = 'Reply with your message for the group, no name prefix: in a discussion, one or two short messages. When you are asked to do something, call your first tool in the same step as your opening note — if you stop without a tool call, your turn ends and no work runs. The group does not wait for you and sees what you write while you work: say what you will do, write again only when something matters, and end with the result, never a promise to do it later. Reply [PASS] to stay silent when you have nothing new to add or the message is for someone else.'
const ROOM_REPLY_COMPACT = 'Reply for the group (no name prefix; [PASS] to stay silent).'
const ROOM_CALLS = 'Use delegate_work to assign tasks to group members; their results return to you automatically once finished. Plain "@Name" in your message text is display-only and never wakes or delegates to other members.'
const slotLabel = (slot, self) => {
if (slot.status === 'speaking') return slot === self ? `${slot.name} (you, now)` : `${slot.name} (answering now)`
if (slot.status === 'posted') return `${slot.name} (posted)`
if (slot.status === 'passed') return `${slot.name} (passed)`
if (slot.status === 'missed') return `${slot.name} (no answer)`
if (slot.status === 'working') return `${slot.name} (working on it; posts when done)`
if (slot.status === 'waiting-approval') return `${slot.name} (waiting for the user's approval; posts when done)`
if (slot.status === 'waiting-answer') return `${slot.name} (waiting for the user's answer; posts when answered)`
if (slot.status === 'failed') return `${slot.name} (could not answer: error)`
if (slot.status === 'left') return `${slot.name} (left the group)`
return slot.name
}
const adminNote = room => [
'You are this group\'s admin.',
room.mode === 'admin' ? 'Plain messages come to you first: answer them, or assign tasks to members with delegate_work.' : '',
'When the user asks, change the group with update_group.',
'When the user wants this group to reach a goal, set it with group_goal: align with the user first (goal-grill skill), then start it.',
].filter(Boolean).join(' ')
const roomKickoff = language => `The user just created this group and has not written yet. Greet the user in one short message and ask what they want this group to work on. Do not delegate to members yet, and do not reply [PASS]. No name prefix. Write in ${language ?? 'the user\'s language if known; otherwise Chinese'}.`
const lostSession = error => error?.code === 'session/not-found' || /\bis corrupt\b|\bcorrupt session log\b/i.test(String(error?.message ?? ''))
const fileLine = file => `[File "${file.name}" (${file.bytes} bytes) attached]`
const lineOverflow = line => {
if (line?.files?.length !== 1 || typeof line.botId !== 'string' || line.kind !== undefined) return undefined
const [file] = line.files
if (line.overflow === true || /^\[A long message: \d+ characters\. Its start is below; all of it is in the attached file\. Read the file before you act on it\./.test(line.text)) return file
// Legacy Bot posts can lose the preview marker; their linked file still has the overflow writer's name and size.
if (file.bytes > MESSAGE_INLINE_MAX && /^Post from .*\.txt$/su.test(file.name)) return file
}
const POST_HEADER = /^\[Group post from (?:[^\r\n]*\]\r?\n|[^\]\r\n]*\])/
const digestOf = text => createHash('sha256').update(String(text ?? '')).digest('hex').slice(0, 16)
function legacyNoticeRecord(reply, time) {
const botId = reply.botId
if (reply.kind === 'goal') {
const { who: _who, kind: _kind, seq: _seq, time: _time, about: _about, botId: _botId, name: _name, color: _color, ...fields } = reply
return { who: 'DS Bot', kind: 'notice', reason: 'goal', ...fields, ...time }
}
if (reply.kind === 'paused') {
return {
who: 'DS Bot', kind: 'notice', reason: 'paused',
...(reply.idle !== undefined ? { idle: reply.idle } : {}),
...(reply.name ? { from: reply.name } : {}),
...(botId ? { about: botId } : {}),
...(reply.count !== undefined ? { count: reply.count } : {}),
...(reply.limit !== undefined ? { limit: reply.limit } : {}),
...(Array.isArray(reply.names) ? { names: reply.names } : {}),
...time,
}
}
if (reply.kind === 'failed') {
return {
who: 'DS Bot', kind: 'notice', reason: 'failed',
...(reply.name ? { names: [reply.name] } : {}),
...(botId ? { about: botId } : {}),
...(reply.code !== undefined ? { code: reply.code } : {}),
...(reply.status !== undefined ? { status: reply.status } : {}),
...(reply.text !== undefined ? { message: reply.text, detail: reply.text } : {}),
...time,
}
}
if (reply.kind === 'helper-failed') {
return {
who: 'DS Bot', kind: 'notice', reason: 'helper-failed',
...(reply.name ? { names: [reply.name] } : {}),
...(botId ? { about: botId } : {}),
...(reply.stopReason ? { stopReason: reply.stopReason } : {}),
...(reply.helper ? { helper: reply.helper } : {}),
...(reply.text !== undefined ? { detail: reply.text } : {}),
...time,
}
}
if (reply.kind === 'missed' || reply.kind === 'admin-passed') {
return {
who: 'DS Bot', kind: 'notice', reason: reply.kind,
...(reply.name ? { names: [reply.name] } : {}),
...(botId ? { about: botId } : {}),
...(reply.kind === 'missed' ? { minutes: reply.minutes ?? Math.round(ROOM_REPLY_TIMEOUT_MS / 60000) } : {}),
...time,
}
}
if (reply.kind === 'folder') {
return {
who: 'DS Bot', kind: 'notice', reason: 'folder',
...(reply.path ? { path: reply.path } : {}),
...(reply.text !== undefined ? { text: reply.text } : {}),
...time,
}
}
return {
who: 'DS Bot', kind: 'notice', reason: reply.kind,
...(reply.name ? { names: [reply.name] } : {}),
...(botId ? { about: botId } : {}),
...(reply.text !== undefined ? { text: reply.text } : {}),
...time,
}
}
export function extractGroupSessionLines(events, botNameOf = () => undefined) {
const lines = []
const relayCalls = new Set()
for (const event of events) {
if (event?.type === 'user/message') {
const source = event.data?.source
const content = Array.isArray(event.data?.content) ? event.data.content : []
const files = content.filter(block => block?.type === 'file' && block.attachment !== undefined).map(block => block.attachment)
const time = Number.isFinite(event.time) ? { time: event.time } : {}
if (source?.kind === 'user') {
const text = [textOf(content), ...files.map(fileLine)].filter(Boolean).join('\n')
const via = viaOf(source)
const rpcId = typeof source.rpcId === 'string' && source.rpcId.trim() !== '' ? source.rpcId.trim() : undefined
lines.push({ who: 'User', text, ...(files.length > 0 ? { files } : {}), ...(via === undefined ? {} : { via }), ...(rpcId === undefined ? {} : { rpcId }), ...time, ...(Number.isInteger(event.seq) ? { eventSeq: event.seq } : {}), ...(typeof event.data?.id === 'string' ? { messageId: event.data.id } : {}) })
} else if (source?.kind === 'schedule') {
const prompts = reminderPrompts(textOf(content))
const text = prompts.length > 0 ? prompts.join('\n') : textOf(content)
lines.push({ who: 'User', schedule: true, text, ...time, ...(Number.isInteger(event.seq) ? { eventSeq: event.seq } : {}), ...(typeof event.data?.id === 'string' ? { messageId: event.data.id } : {}) })
} else if (source?.kind === SOURCE_KIND && source.role === 'post') {
if (source.logged !== undefined || source.failed !== undefined || source.resumed === true || source.stopped === true || source.done === true || source.resumedPause === true) continue
const raw = textOf(content).replace(POST_HEADER, '')
const text = [raw, ...files.map(fileLine)].filter(Boolean).join('\n')
const presented = presentedFiles(source.presented)
const botId = source.senderSessionId
const who = source.senderName ?? botNameOf(botId) ?? 'Bot'
lines.push({ who, ...(botId ? { botId } : {}), text, ...(files.length > 0 ? { files } : {}), ...(source.externalPost === true && Number.isInteger(source.length) ? { overflow: true } : {}), ...(presented.length > 0 ? { presented } : {}), ...(source.duration === undefined ? {} : { duration: source.duration }), ...time })
}
continue
}
if (event?.type === 'tool/call') {
const name = event.data?.name
if (name === 'group_relay' || (name === 'run_code' && String(event.data?.arguments ?? '').includes('group_relay'))) {
if (event.data?.callId !== undefined) relayCalls.add(event.data.callId)
}
continue
}
if (event?.type !== 'tool/result') continue
const callId = event.data?.message?.toolCallId
if (!relayCalls.has(callId)) continue
relayCalls.delete(callId)
const raw = textOf(event.data?.message?.content)
if (relayRange(raw) !== undefined) continue
const parsed = parseReplies(raw)
if (parsed.broken) lines.push({ gap: true })
for (const reply of parsed.replies) {
if (!reply || typeof reply !== 'object' || reply.kind === 'working' || reply.kind === 'approval') continue
const time = Number.isFinite(reply.time) ? { time: reply.time } : {}
if (reply.kind === 'user') {
const rpcId = typeof reply.requestId === 'string' && reply.requestId.trim() !== ''
? reply.requestId.trim()
: (typeof reply.rpcId === 'string' && reply.rpcId.trim() !== '' ? reply.rpcId.trim() : undefined)
lines.push({ who: 'User', text: reply.text ?? '', ...(reply.via ? { via: reply.via } : {}), ...(rpcId === undefined ? {} : { rpcId }), ...time })
} else if (reply.kind === undefined) {
const botId = reply.botId
const who = reply.name ?? botNameOf(botId) ?? 'Bot'
const presented = presentedFiles(reply.presented)
lines.push({ who, ...(botId ? { botId } : {}), text: reply.text ?? '', ...(presented.length > 0 ? { presented } : {}), ...time })
} else if (reply.kind === 'lookup' || reply.kind === 'done' || reply.kind === 'stopped' || reply.kind === 'cut' || reply.kind === 'resumed') {
const botId = reply.botId
const who = reply.name ?? botNameOf(botId) ?? 'Bot'
lines.push({ who, ...(botId ? { botId } : {}), kind: reply.kind, text: reply.text ?? '', ...time })
} else {
lines.push(legacyNoticeRecord(reply, time))
}
}
if (parsed.broken) lines.push({ gap: true })
}
return lines
}
function sameSessionLine(a, b) {
if (a?.gap === true || b?.gap === true) return false
if ((a.kind ?? undefined) !== (b.kind ?? undefined)) return false
if (a.kind !== undefined) {
if (a.kind === 'notice' && a.reason !== b.reason) return false
return a.botId === undefined || b.botId === undefined || a.botId === b.botId
}
const userA = a.botId === undefined && a.who === 'User'
const userB = b.botId === undefined && b.who === 'User'
if (userA !== userB) return false
if (!userA && a.botId !== undefined && b.botId !== undefined && a.botId !== b.botId) return false
if (!userA && (a.botId === undefined || b.botId === undefined) && a.who !== b.who) return false
const textA = String(a.text ?? '')
const textB = String(b.text ?? '')
if (textA === textB) return true
if (textA !== '' && textB !== '') return textA.startsWith(textB) || textB.startsWith(textA)
return userA && textA === '' && b.images !== undefined
}
export function alignGroupSessionLines(sessionLines, kept) {
if (sessionLines.length === 0) return []
const sorted = [...kept].filter(record => Number.isInteger(record?.seq)).sort((a, b) => a.seq - b.seq)
if (sorted.length === 0) {
const end = sessionLines.findIndex(line => line.gap === true)
const prefix = end === -1 ? sessionLines : sessionLines.slice(0, end)
return prefix.map((line, index) => ({ ...line, seq: index + 1 }))
}
const oldestSeq = sorted[0].seq
const anchors = [0]
const firstMessage = sorted.findIndex(line => line.kind === undefined)
if (firstMessage > 0) anchors.push(firstMessage)
for (const anchor of anchors) {
const win = Math.min(BACKFILL_WINDOW, sorted.length - anchor)
if (win <= 0) continue
const candidates = []
for (let idx = 0; idx <= sessionLines.length - win; idx += 1) {
let ok = true
for (let offset = 0; offset < win; offset += 1) {
if (!sameSessionLine(sessionLines[idx + offset], sorted[anchor + offset])) { ok = false; break }
}
if (ok) candidates.push(idx)
}
if (candidates.length === 0) continue
const target = sorted[anchor]
const best = candidates.reduce((pick, idx) => {
const dist = Math.abs(idx - (target.seq - 1))
const pickDist = Math.abs(pick - (target.seq - 1))
if (dist !== pickDist) return dist < pickDist ? idx : pick
const gap = Math.abs((sessionLines[idx].time ?? 0) - (target.time ?? 0))
const pickGap = Math.abs((sessionLines[pick].time ?? 0) - (target.time ?? 0))
return gap < pickGap ? idx : pick
})
const recovered = []
for (let i = best - 1; i >= 0; i -= 1) {
if (sessionLines[i]?.gap === true) break
const seq = target.seq - (best - i)
if (seq >= 1 && seq < oldestSeq) recovered.push({ ...sessionLines[i], seq })
}
return recovered.reverse()
}
return undefined
}
export function install(rt) {
const { ctx } = rt
const bookOf = roomId => `group-${roomId}`
const writes = () => rt.readOnly?.() === undefined
const db = () => rt.coordDb ?? null
const existingDb = () => (typeof rt.existingCoordDb === 'function' ? rt.existingCoordDb() : db())
const writableDb = () => {
const handle = db()
if (handle === null || handle.isClosed?.() || handle.readonly || !writes()) return null
return handle
}
const existingWritableDb = () => {
const handle = existingDb()
if (handle === null || handle.isClosed?.() || handle.readonly || !writes()) return null
return handle
}
const saveSoon = () => void rt.save().catch(() => {})
const oldLogName = id => (/^[\w-]{1,128}$/.test(id) ? id : createHash('sha256').update(String(id)).digest('hex').slice(0, 32))
rt.ledger.importer('group-', (book) => {
const roomId = book.slice('group-'.length)
const lines = new Map()
const keep = (line, text = line.text) => lines.set(line.seq, typeof text === 'string'
? { ...line, text, length: line.length ?? text.length }
: line)
for (const line of rt.roomOf(roomId)?.log ?? []) {
if (!Number.isInteger(line?.seq)) continue
let text = line.text
if (line.length !== undefined) {
try { text = readFileSync(join(rt.home, 'group-lines', roomId, `${line.seq}.txt`), 'utf8') } catch { /* only its start was kept */ }
}
keep(line, text)
}
try {
for (const line of parseBook(readFileSync(join(rt.home, 'group-logs', `${oldLogName(roomId)}.jsonl`), 'utf8'))) {
if (Number.isInteger(line.seq)) keep(line)
}
} catch { /* no log of its own yet */ }
return [...lines.values()].sort((a, b) => a.seq - b.seq)
})
const reconciled = new WeakSet()
const ensureRoomLog = (room) => {
if (typeof room.seq !== 'number') {
room.log = (room.log ?? []).map((line, index) => ({ ...line, seq: index + 1 }))
room.seq = room.log.length
}
room.seen ??= {}
if (!reconciled.has(room)) {
reconciled.add(room)
const book = bookOf(room.id)
const superseded = supersededSeqsOf(rt.ledger?.records?.(book) ?? [])
const ahead = rt.ledger.after(book, room.seq)
if (ahead.length > 0) {
room.seq = Math.max(room.seq, ...ahead.map(record => record.seq))
room.log = [...room.log, ...ahead.filter(record => !superseded?.has(record.seq) && memberLine(record)).map(record => cutLine(record))].slice(-ROOM_LOG_MAX)
}
}
}
const memberText = room => (line) => {
const source = line.length === undefined ? line : rt.ledger.record(bookOf(room.id), line.seq)
const whole = source === undefined ? undefined : projectRoomLine(room, source).text
if (whole === undefined) return `${projectRoomLine(room, line).text}… (cut; ${line.length} characters in all, the rest was not kept)`
const shown = headOf(whole, GROUP_LINE_READ)
return whole.length > shown.length ? `${shown}… (cut; ${whole.length} characters in all)` : shown
}
const cutLine = (line, text = line.text ?? '') => {
const kept = headOf(text, TEXT_KEPT)
return kept.length === text.length ? line : { ...line, text: kept, length: text.length }
}
function keepGroupLine(roomId, line, text) {
rt.ledger.open(bookOf(roomId))
return cutLine(line, text)
}
function dropGroupLines(roomId) {
clearPresented(roomId)
backfilled.delete(roomId)
// Deleting the key being visited is safe: Map iteration only skips entries removed before
// it reaches them.
for (const key of atHintAt.keys()) {
if (key.startsWith(`${roomId}:`)) atHintAt.delete(key)
}
laterPosts.delete(roomId)
stoppedFinishing.delete(roomId)
inFlightRoomDrains.delete(roomId)
pendingSessionHandovers.delete(roomId)
sessionClaimedSeqs.delete(roomId)
sessionClaimedGen.delete(roomId)
inFlightRecoveredDispatches.delete(roomId)
clearPendingRoomLedgerRetry(roomId)
activeRoomLedgerRecoveries.delete(roomId)
const handle = existingWritableDb()
if (handle !== null) {
const works = handle.listWorks({ kind: 'room_work', roomId, activeOnly: true, limit: 500 })
for (const work of works) {
if (work.meta?.kind === REPORT_WORK_KIND) continue
handle.stopWork(work.workId, { reason: 'Group deleted' })
}
}
rt.ledger.drop(bookOf(roomId))
if (!writes()) return
void rm(join(rt.home, 'group-lines', roomId), { recursive: true, force: true }).catch(() => {})
void rm(join(rt.home, 'group-logs', `${oldLogName(roomId)}.jsonl`), { force: true }).catch(() => {})
}
const backfilled = new Set()
const backfilling = new Map()
async function sessionEvents(sessionId, signal) {
const agent = await rt.resolveAgent(sessionId).catch(() => undefined)
const throughSeq = agent?.session?.seq !== undefined ? Number(agent.session.seq) - 1 : undefined
if (throughSeq !== undefined && throughSeq < 0) return []
const pages = []
let beforeSeq
for (;;) {
const page = await ctx.sessionController.page({
address: { kind: 'session', sessionId },
...(throughSeq === undefined ? {} : { throughSeq }),
...(beforeSeq === undefined ? {} : { beforeSeq }),
maxMessages: HISTORY_PAGE,
}, signal)
const events = (page.records ?? []).map(record => record.event).filter(Boolean)
if (events.length > 0) pages.push(events)
if (!page.hasMore || events.length === 0) break
beforeSeq = events[0].seq
}
return pages.reverse().flat()
}
async function backfillGroupLog(roomId, since) {
if (since === undefined || backfilled.has(roomId)) return
const pending = backfilling.get(roomId)
if (pending !== undefined) return pending
const run = (async () => {
const room = rt.roomOf(roomId)
if (room === undefined) return
ensureRoomLog(room)
const book = bookOf(roomId)
const records = rt.ledger.records(book)
let oldestSeq
for (const record of records) {
if (Number.isInteger(record.seq) && (oldestSeq === undefined || record.seq < oldestSeq)) oldestSeq = record.seq
}
if (oldestSeq !== undefined && oldestSeq <= since + 1) return
if (oldestSeq === undefined && room.seq <= since) return
if (typeof ctx.sessionController?.page !== 'function') return
const partIds = [...(room.parts ?? []).map(segment => segment.sessionId), rt.sessionOfRoom(room)].filter(Boolean)
const signal = AbortSignal.timeout(HISTORY_TIMEOUT_MS)
const botNameOf = botId => rt.botOf(botId)?.name
const partLines = []
let lostError
for (let i = partIds.length - 1; i >= 0; i -= 1) {
try {
partLines.unshift(extractGroupSessionLines(await sessionEvents(partIds[i], signal), botNameOf))
} catch (error) {
if (lostSession(error)) {
lostError ??= error
partLines.unshift([{ gap: true }])
continue
}
throw new Error(`its Session history could not be read: ${error?.message ?? error}`, { cause: error })
}
}
const sessionLines = partLines.flat()
const kept = records.filter(record => Number.isInteger(record.seq))
const recovered = alignGroupSessionLines(sessionLines, kept)
// The room counts as backfilled only once the recovered lines are on disk. A failed
// write takes them out of the book again, so the caller hears of it, and the room
// stays unmarked for the next call to retry. That throw also skips the warning on
// missing lines below: the lines were in the Session, and the caller warns instead.
// A read-only host keeps the recovered lines in its cache for the lookup at hand but
// writes nothing, so it leaves the room unmarked: once it takes over as the writer it
// reads the book from disk again, and the next call recovers the lines and saves them.
const writable = rt.readOnly?.() === undefined
const added = recovered !== undefined && recovered.length > 0 ? rt.ledger.prepend(book, recovered) : 0
if (!writable) return
if (added > 0) {
let unsaved
await rt.ledger.written(book).catch((error) => { unsaved = { error } })
if (unsaved !== undefined) throw new Error(`the lines recovered from its Session could not be saved: ${unsaved.error?.message ?? unsaved.error}`)
}
let earliestSeq = oldestSeq
for (const record of rt.ledger.records(book)) {
if (Number.isInteger(record.seq) && (earliestSeq === undefined || record.seq < earliestSeq)) earliestSeq = record.seq
}
const missing = (earliestSeq ?? (room.seq + 1)) - since - 1
if (missing > 0) {
if (lostError !== undefined) {
rt.warn('ds-bot: %d lines of group "%s" left its log before they were reviewed and could not be recovered from its Session: %s', missing, room.name, lostError.message ?? lostError)
} else {
rt.warn('ds-bot: %d lines of group "%s" left its log before they were reviewed and were not in its Session', missing, room.name)
}
}
backfilled.add(roomId)
})().finally(() => {
if (backfilling.get(roomId) === run) backfilling.delete(roomId)
})
backfilling.set(roomId, run)
return run
}
const roomLineListeners = new Set()
// Invariant: every visible group row written to `bookOf(room.id)` MUST go through `say()`
// so `room.seq` advances monotonically. `host/mobile.js` relies on `room.seq` to invalidate
// `room-chat` incremental fast-path tips whenever a visible row lands (including zero-wake
// posts, notices, and `rt.logRoom` cards).
// Invariant: room.seq only ever moves here, once per line; drawLine never numbers.
// The write each drawn seq queued, so a caller can name it instead of guessing from the
// book's tail. Dropped as soon as its outcome is known.
const lineWrites = new Map()
// `room.seq` starts at 1 in every room, so a key of the seq alone would collide across rooms.
// Exported so a test can pin the key space without pretending to drive the whole round.
const lineWriteKey = (room, seq) => lineWriteKeyOf(room.id, seq)
const maskRoomLine = (line, mask, fileMask = mask) => {
let projected = line
for (const field of ['text', 'message', 'detail', 'helper', 'path', 'title', 'next', 'changes']) {
if (line[field] === undefined) continue
const value = mask(line[field])
if (value !== line[field]) projected = { ...projected, [field]: value }
}
for (const field of ['presented', 'files', 'images']) {
if (!Array.isArray(line[field])) continue
const files = line[field].map(fileMask)
if (files.some((file, index) => file !== line[field][index])) projected = { ...projected, [field]: files }
}
return projected.text === line.text ? projected : { ...projected, mentionRefs: undefined }
}
const projectRoomLine = (room, line, options) => {
const id = rt.sessionOfRoom(room)
return maskRoomLine(line, value => rt.redactGroupVault?.(id, value, options) ?? value, file =>
rt.projectGroupFile?.(id, file, options) ?? file)
}
// Read-only observation point for tests: it only reads the keys already in the table, never
// takes part in a write, and scopes itself to one room through the `bookOf` prefix above.
rt.lineWriteKeysOf = roomId => [...lineWrites.keys()].filter(key => String(key).startsWith(`${bookOf(roomId)}:`))
const appendLine = (room, line, references, options) => {
ensureRoomLog(room)
if (lineOverflow(line) !== undefined) line = { ...line, overflow: true }
const projected = projectRoomLine(room, line, { storage: true })
if (projected !== line) line = { ...projected, eventSeq: undefined }
room.seq += 1
const record = { ...line, seq: room.seq, time: line.time ?? Date.now() }
// #2659: every visible line passes through here — in-round speech, external posts, late
// replies and recovered progress text — so this is the one place that can tell a Bot its
// body @Name woke nobody. A notice carries a `kind` and is not a dropped @.
if (line.kind === undefined && line.botId !== undefined && isVisibleRoute(line.route)) {
const sender = rt.botOf(line.botId)
if (sender !== undefined) {
hintUnwokenMentions(room, sender, line.text, { route: line.route, externalPost: options?.externalPost }, { called: options?.called })
}
}
if (line.kind === undefined && typeof line.text === 'string') {
const stored = rt.sessionMentionRefs?.(line.eventSession ?? rt.sessionOfRoom(room), line.eventSeq)
const bots = line.botId === undefined ? room.members.map(rt.botOf).filter(Boolean) : Object.values(rt.state.bots)
const text = line.botId === undefined ? line.text : stripToolCallTags(line.text)
const labels = references?.flatMap(reference => reference.labels)
const skips = referenceSpans(text, labels)
record.mentionRefs = stored?.filter(ref => !skips.some(span => ref.start < span.end && span.start < ref.end))
?? captureMentionRefs(text, bots, { references: labels })
}
rt.ledger.append(bookOf(room.id), record)
// The write this record queued is the last one of the book right now: `append` returned
// after pushing it, and nothing else can have appended to this book in between (no await).
// A caller that must undo its result when the line never lands takes this, never the tail
// it would read later, which by then may belong to an unrelated line. Kept beside the
// record so nothing about the write reaches the book itself.
const write = rt.ledger.written?.(bookOf(room.id))
if (write !== undefined) {
// Keyed by book AND seq: room.seq counts from 1 in every room, so a bare seq would let
// two rooms overwrite each other's entry in this host-wide map.
const key = lineWriteKey(room, record.seq)
lineWrites.set(key, write)
if (lineWrites.size > ROOM_LOG_MAX) lineWrites.delete(lineWrites.keys().next().value)
void write.then(() => lineWrites.delete(key), () => lineWrites.delete(key))
}
return record
}
const drawLine = (room, record) => {
const projected = projectRoomLine(room, record)
rt.roomLineAdded?.(room, projected)
if (!memberLine(record)) return record
// Insert in seq order, not plain append: a ledger-gated line draws after its write
// resolves while an ungated line with a higher seq may already be in the window — the
// transcript the members read must still follow the book.
const line = cutLine(record)
const at = Number.isInteger(line.seq) ? room.log.findIndex(other => Number.isInteger(other.seq) && other.seq > line.seq) : -1
room.log = (at === -1 ? [...room.log, line] : [...room.log.slice(0, at), line, ...room.log.slice(at)]).slice(-ROOM_LOG_MAX)
for (const listener of roomLineListeners) {
try { listener(room, projected) } catch (error) { rt.warn('ds-bot: room line listener failed: %s', error) }
}
return record
}
const unsavedNotice = error => `The last line may not have been saved: ${error?.message ?? error}`
// Whether the room was already told this exact thing by the line just before. Only the
// trailing line counts: a notice anywhere in the window means a failure that has since been
// recovered from, and a new one after it must be told again.
const toldUnsaved = (room, text) => {
const tail = room.log.at(-1)
return tail !== undefined && tail.kind === 'notice' && tail.reason === 'unsaved' && tail.text === text
}
// One way to tell the room a line it wrote did not reach the book, so every path dedupes
// the same way and none of them can flood the room on a retry loop.
const sayUnsaved = (room, error) => {
const text = unsavedNotice(error)
if (toldUnsaved(room, text)) return
try {
say(room, { who: 'DS Bot', kind: 'notice', reason: 'unsaved', text })
} catch {}
}
// A line the book did not keep calls nobody: the caller hears the rejection (and closes its
// batch), the room hears a warning of its own. This one draws synchronously; a refusal leaves
// the line in `room.log` (members' prompts read it) while `rowsView` keeps it out of the rows
// a client fetches. Only the gated paths await `written` before drawing.
const say = (room, line, references, options) => {
const record = appendLine(room, line, references, options)
// `written` is part of the ledger contract; only a partial test facade can lack it.
if (record.reason !== 'unsaved') {
rt.ledger.written?.(bookOf(room.id)).catch((error) => {
rt.warn('ds-bot: a line said in %s was not saved: %s', room.name, error?.message ?? error)
sayUnsaved(room, error)
})
}
return drawLine(room, record)
}
function rowOf(record, { persisted } = {}) {
const botId = record.botId ?? record.about
const bot = botId === undefined ? undefined : rt.botOf(botId)
const who = { botId, name: bot?.name ?? (record.kind === 'notice' ? record.names?.[0] : record.who), color: bot?.color }
const time = record.time
if (record.kind === undefined) {
const mentions = record.mentionRefs === undefined ? {} : { mentionRefs: record.mentionRefs }
if (record.botId === undefined) {
const requestId = typeof record.rpcId === 'string' && record.rpcId.trim() !== '' ? record.rpcId.trim() : undefined
return {
kind: 'user',
text: record.text,
time,
...mentions,
...(record.via ? { via: record.via } : {}),
...(requestId === undefined ? {} : { requestId }),
...(requestId !== undefined && persisted === true ? { durable: true } : {}),
}
}
return {
...who, text: record.text, time,
...mentions,
roomSeq: record.seq,
...(record.duration === undefined ? {} : { duration: record.duration }),
...(record.claims === undefined ? {} : { claims: record.claims }),
...(record.changes === undefined ? {} : { changes: record.changes }),
...(record.presented?.length ? { presented: record.presented } : {}),
}
}
if (record.kind === 'lookup') return { kind: 'lookup', ...who, text: record.text, time }
if (record.kind !== 'notice') return { kind: record.kind, ...who, time, ...(record.changes === undefined ? {} : { changes: record.changes }) }
switch (record.reason) {
case 'failed': return { kind: 'failed', ...who, code: record.code, ...(record.status ? { status: record.status } : {}), ...(record.requestId ? { requestId: record.requestId } : {}), text: record.message ?? record.detail, time }
case 'helper-failed': return { kind: 'helper-failed', ...who, ...(record.stopReason ? { stopReason: record.stopReason } : {}), ...(record.helper ? { helper: record.helper } : {}), text: record.detail, time }
case 'missed': return { kind: 'missed', ...who, time }
case 'admin-passed': return { kind: 'admin-passed', ...who, time }
case 'paused': return { kind: 'paused', idle: record.idle, ...(record.cause !== undefined ? { cause: record.cause } : {}), ...who, name: bot?.name ?? record.from, count: record.count ?? record.limit, limit: record.limit, names: record.names, time }
case 'folder': return { kind: 'folder', text: noticeText(record), time }
// A line the book refused is said in the room; the history draws it as plain text.
case 'unsaved': return { kind: 'folder', text: noticeText(record), time }
case 'goal': {
const { who: _who, kind: _kind, reason: _reason, seq: _seq, time: _time, about: _about, ...fields } = record
return { kind: 'goal', ...fields, time }
}
default: return undefined
}
}
// In-flight write-ahead drains per room, pending handovers whose round aborted while
// DSH was still running its claimed turn, seq numbers whose write-ahead ledger row
// lost the ownership handover to DSH's native session turn, and per-room recovery/rewake guards.
const inFlightRoomDrains = new Map()
const pendingSessionHandovers = new Map()
const sessionClaimedSeqs = new Map()
const sessionClaimedGen = new Map()
const sessionTurnWaiters = new Map()
const inFlightRecoveredDispatches = new Map()
const rewakeAfterStrippedPreStep = new Map()
const ROOM_LEDGER_RETRY_DELAYS_MS = [200, 400, 800, 1_600, 3_000, 5_000, 10_000, 30_000]
const pendingRoomLedgerRetries = new Map()
const activeRoomLedgerRecoveries = new Map()
const clearPendingRoomLedgerRetry = (roomId) => {
const entry = pendingRoomLedgerRetries.get(roomId)
if (entry === undefined) return
if (entry.timer !== undefined) clearTimeout(entry.timer)
pendingRoomLedgerRetries.delete(roomId)
}
const schedulePendingRoomLedgerRetry = (roomId, { resetBackoff = false } = {}) => {
if (
typeof roomId !== 'string'
|| roomId === ''
|| disposed
|| rt.deletingRooms?.has(roomId)
|| rt.readOnly?.() !== undefined
|| rt.roomOf(roomId) === undefined
) {
clearPendingRoomLedgerRetry(roomId)
return
}
let entry = pendingRoomLedgerRetries.get(roomId)
if (entry === undefined) {
entry = { timer: undefined, attempts: 0, inFlight: false, pendingReschedule: false }
pendingRoomLedgerRetries.set(roomId, entry)
}
if (resetBackoff) entry.attempts = 0
if (entry.inFlight) {
entry.pendingReschedule = true
return
}
if (entry.timer !== undefined) return
const delayMs = ROOM_LEDGER_RETRY_DELAYS_MS[Math.min(entry.attempts, ROOM_LEDGER_RETRY_DELAYS_MS.length - 1)]
entry.attempts += 1
if (entry.attempts === 5 || (entry.attempts > 5 && entry.attempts % 10 === 0)) {
rt.warn?.('ds-bot: room %s still has pending ledger dispatches awaiting readable member receipt evidence after %d retries; retrying in %dms', roomId, entry.attempts, delayMs)
}
entry.timer = setTimeout(() => {
const current = pendingRoomLedgerRetries.get(roomId)
if (current !== entry) return
current.timer = undefined
if (disposed || rt.deletingRooms?.has(roomId) || rt.readOnly?.() !== undefined || rt.roomOf(roomId) === undefined) {
clearPendingRoomLedgerRetry(roomId)
return
}
if ((activeRoomLedgerRecoveries.get(roomId) ?? 0) > 0) {
schedulePendingRoomLedgerRetry(roomId)
return
}
current.inFlight = true
current.pendingReschedule = false
void recoverPendingRoomLedgerDispatches(roomId)
.catch((error) => {
rt.warn?.('ds-bot: scheduled room ledger recovery retry for %s failed: %s', roomId, error?.message ?? error)
if (pendingRoomLedgerRetries.get(roomId) === current) current.pendingReschedule = true
})
.finally(() => {
if (pendingRoomLedgerRetries.get(roomId) !== current) return
current.inFlight = false
if (disposed || rt.deletingRooms?.has(roomId) || rt.readOnly?.() !== undefined || rt.roomOf(roomId) === undefined) {
clearPendingRoomLedgerRetry(roomId)
return
}
if (current.pendingReschedule) {
current.pendingReschedule = false
schedulePendingRoomLedgerRetry(roomId)
} else {
const room = rt.roomOf(roomId)
if (room === undefined || (pendingRoomLedgerDispatches(room).length === 0 && !inFlightRecoveredDispatches.has(roomId))) {
clearPendingRoomLedgerRetry(roomId)
}
}
})
}, delayMs)
entry.timer.unref?.()
}
const supersededSeqsOf = (records) => {
let set
for (const record of records ?? []) {
if (record?.event === 'supersede' && Number.isInteger(record.targetSeq)) {
set ??= new Set()
set.add(record.targetSeq)
}
}
return set
}
const dispatchedStateOf = (records) => {
let dispatchedAll
let dispatchedBots
let cancelledAll
let cancelledBots
for (const record of records ?? []) {
if (record?.event !== 'dispatched' || !Number.isInteger(record.targetSeq)) continue
if (record.all === true) {
dispatchedAll ??= new Set()
dispatchedAll.add(record.targetSeq)
if (record.cancelled === true) {
cancelledAll ??= new Set()
cancelledAll.add(record.targetSeq)
}
}
if (typeof record.botId === 'string' && record.botId !== '') {
dispatchedBots ??= new Map()
let set = dispatchedBots.get(record.targetSeq)
if (set === undefined) {
set = new Set()
dispatchedBots.set(record.targetSeq, set)
}
set.add(record.botId)
if (record.cancelled === true) {
cancelledBots ??= new Map()
let cset = cancelledBots.get(record.targetSeq)
if (cset === undefined) {
cset = new Set()
cancelledBots.set(record.targetSeq, cset)
}
cset.add(record.botId)
}
}
}
return { dispatchedAll, dispatchedBots, cancelledAll, cancelledBots }
}
const isRoomLedgerSeqCancelled = (roomOrId, seq, botId) => {
const roomId = typeof roomOrId === 'string' ? roomOrId : roomOrId?.id
if (typeof roomId !== 'string' || roomId === '' || !Number.isInteger(seq)) return false
const book = bookOf(roomId)
if (typeof rt.ledger?.hasBook === 'function' && !rt.ledger.hasBook(book)) return false
const { cancelledAll, cancelledBots } = dispatchedStateOf(rt.ledger?.records?.(book))
if (cancelledAll?.has(seq) === true) return true
if (typeof botId === 'string' && botId !== '' && cancelledBots?.get(seq)?.has(botId) === true) return true
return false
}
const isRoomLedgerSeqClosed = (roomOrId, seq, botId) => {
const roomId = typeof roomOrId === 'string' ? roomOrId : roomOrId?.id
if (typeof roomId !== 'string' || roomId === '' || !Number.isInteger(seq)) return false
const book = bookOf(roomId)
if (typeof rt.ledger?.hasBook === 'function' && !rt.ledger.hasBook(book)) return false
const records = rt.ledger?.records?.(book)
const superseded = supersededSeqsOf(records)
if (isSeqSuperseded(roomId, seq, superseded)) return true
const { dispatchedAll, dispatchedBots } = dispatchedStateOf(records)
if (dispatchedAll?.has(seq) === true) return true
if (typeof botId === 'string' && botId !== '' && dispatchedBots?.get(seq)?.has(botId) === true) return true
return false
}
const isParkedMessageFullyCancelled = (roomOrId, botId, parkedMessage, fallbackSeq) => {
const seqs = Array.isArray(parkedMessage?.source?.ledgerDispatchSeqs)
? parkedMessage.source.ledgerDispatchSeqs.filter(Number.isInteger)
: []
if (seqs.length > 0) return seqs.every(seq => isRoomLedgerSeqCancelled(roomOrId, seq, botId))
return Number.isInteger(fallbackSeq) && isRoomLedgerSeqCancelled(roomOrId, fallbackSeq, botId)
}
const pruneCancelledMemberRoomInbox = (roomOrId, botId, agent) => {
const roomId = typeof roomOrId === 'string' ? roomOrId : roomOrId?.id
if (typeof roomId !== 'string' || roomId === '' || typeof agent?.inbox?.remove !== 'function') return 0
const book = bookOf(roomId)
if (typeof rt.ledger?.hasBook === 'function' && !rt.ledger.hasBook(book)) return 0
const { cancelledAll, cancelledBots } = dispatchedStateOf(rt.ledger?.records?.(book))
if (cancelledAll === undefined && cancelledBots === undefined) return 0
let removed = 0
for (const lane of [agent.inbox.nextStep, agent.inbox.nextTurn]) {
for (const message of Array.from(lane ?? [])) {
const src = message?.source
if (src?.kind !== SOURCE_KIND || src.role !== 'room' || src.roomId !== roomId) continue
const seqs = Array.isArray(src.ledgerDispatchSeqs) ? src.ledgerDispatchSeqs.filter(Number.isInteger) : []
if (seqs.length === 0) continue
const allCancelled = seqs.every(seq => (
cancelledAll?.has(seq) === true
|| (typeof botId === 'string' && botId !== '' && cancelledBots?.get(seq)?.has(botId) === true)
))
if (!allCancelled) continue
if (agent.inbox.remove(message.id) === true) removed += 1
}
}
return removed
}
const bumpSessionClaimedGen = (roomId) => {
if (typeof roomId !== 'string' || roomId === '') return
sessionClaimedGen.set(roomId, (sessionClaimedGen.get(roomId) ?? 0) + 1)
}
const noteSessionClaimedSeq = (roomId, seq) => {
if (typeof roomId !== 'string' || roomId === '' || !Number.isInteger(seq)) return
let set = sessionClaimedSeqs.get(roomId)
if (set === undefined) {
set = new Set()
sessionClaimedSeqs.set(roomId, set)
}
if (!set.has(seq)) {
set.add(seq)
bumpSessionClaimedGen(roomId)
}
}
const clearSessionClaimedSeq = (roomId, seq) => {
const set = sessionClaimedSeqs.get(roomId)