Repository navigation
Expand file tree
/
Copy pathbot-tasks.js
More file actions
1239 lines (1191 loc) · 55.5 KB
/
Copy pathbot-tasks.js
File metadata and controls
1239 lines (1191 loc) · 55.5 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
// Retired per-Bot background task sub-sessions and live foreground handoff (#2808).
//
// DS Bot returns to the #783 principle: every Bot has one continuous conversation,
// slow shell commands continue as DSH native background jobs (`backgroundAfterSec`),
// and parallel work runs across multiple Bots (`delegate_work` queues cleanly when a
// target Bot is busy rather than spawning hidden `bot-handoff` sub-sessions).
//
// This module retains only:
// 1. Send-admission & flush-barrier idempotency helpers used by `channel.js` and `im/index.js`.
// 2. Safe startup retirement of legacy active `bot.tasks[]` and `task:*` coordination rows
// so teams upgrading from v0.3.9–v0.4.3 never stall or lose historical chat segments.
// 3. Explicit `bot/unsupported` rejections for retired endpoints (`bot-move-to-background`, etc.).
import { rmSync } from 'node:fs'
import { join } from 'node:path'
import { HISTORY_TIMEOUT_MS, SOURCE_KIND } from './constants.js'
import { threadCurrentOfPart, threadOfPart } from './threads.js'
const TERMINAL_TASK_STATUSES = new Set(['done', 'completed', 'cancelled', 'failed', 'interrupted', 'stopped'])
const MAX_INSPECTED_SESSIONS = 128
const MAX_SETTLED_TASKS = 50
const MAX_ARCHIVED_TASK_FALLBACK = 2000
const retiredError = (message = 'Per-Bot background task sessions have been retired. Queue your message or delegate to another Bot.') =>
Object.assign(new Error(message), { code: 'bot/unsupported' })
export function install(rt) {
const { ctx, state } = rt
let disposed = false
const activeAdmissionWaiters = new Set()
const admittedRpcIds = new Map() // sessionId -> Set<rpcId>
const admittedLogicalRpcIds = new Map() // ownerKey -> Map<rpcId, { sessionId, durable, durableSessionId, userMessage }>
const sessionRpcDurability = new Map() // sessionId -> Map<rpcId, { durable, userMessage }>
const inspectedSettledSessionRpcIds = new Map() // immutable sessionId -> Map<rpcId, { userMessage: boolean }>
ctx.effect?.(() => () => {
disposed = true
for (const finish of [...activeAdmissionWaiters]) finish()
stopRetiringTasks()
admittedRpcIds.clear()
admittedLogicalRpcIds.clear()
sessionRpcDurability.clear()
inspectedSettledSessionRpcIds.clear()
archivedTaskSessions.clear()
}, 'ds-bot: retired bot-tasks cleanup')
const isLocalCliBot = (bot, session) => {
const ref = bot?.model ?? bot?.appliedModel ?? rt.cachedDefault?.()
if (rt.localAgentBadge?.(ref) !== undefined || rt.isLocalAgentRef?.(ref) === true) return true
const provider = session?.requestHeader?.()?.config?.provider
return provider !== undefined && rt.isLocalAgentRoute?.(provider) === true
}
const isLocalCliSession = (sessionId) => {
if (sessionId === undefined) return false
const botId = rt.chatOwners.get(sessionId) ?? rt.groupOwners.get(sessionId)?.botId ?? rt.taskOwners?.get(sessionId)?.botId
const bot = botId === undefined ? undefined : rt.botOf(botId)
const session = ctx.get?.('agents')?.get?.(sessionId)?.session
return isLocalCliBot(bot, session)
}
const logicalOwnerOf = (ref) => {
if (ref === undefined) return undefined
const taskOwner = rt.taskOwners?.get(ref)
if (taskOwner !== undefined) return taskOwner.roomId !== undefined ? { roomId: taskOwner.roomId } : { botId: taskOwner.botId }
const botId = rt.chatOwners.get(ref)
if (botId !== undefined) return { botId }
const groupOwner = rt.groupOwners.get(ref)
if (groupOwner !== undefined) return { roomId: groupOwner.roomId }
const past = rt.pastOwners?.get(ref)
if (past !== undefined) return past.roomId !== undefined ? { roomId: past.roomId } : { botId: past.botId }
const bot = rt.botOf(ref)
if (bot !== undefined) return { botId: bot.id }
const room = rt.roomOf(ref)
if (room !== undefined) return { roomId: room.id }
return undefined
}
const ownerKeyOf = (owner) => {
if (owner === undefined) return undefined
if (owner.roomId !== undefined) return `room:${owner.roomId}`
if (owner.botId !== undefined) return `bot:${owner.botId}`
return undefined
}
const noteSessionAdmittedRpc = (sessionId, rpcId) => {
if (sessionId === undefined || rpcId === undefined) return
let set = admittedRpcIds.get(sessionId)
if (set === undefined) {
set = new Set()
admittedRpcIds.set(sessionId, set)
}
set.add(rpcId)
if (set.size > 400) set.delete(set.values().next().value)
}
const noteLogicalAdmittedRpc = (sessionId, rpcId, { durable = false, userMessage = false } = {}) => {
if (rpcId === undefined) return
const ownerKey = ownerKeyOf(logicalOwnerOf(sessionId))
if (ownerKey === undefined) return
let logical = admittedLogicalRpcIds.get(ownerKey)
if (logical === undefined) {
logical = new Map()
admittedLogicalRpcIds.set(ownerKey, logical)
}
const prev = logical.get(rpcId)
logical.delete(rpcId)
let nextDurable = prev?.durable === true
let nextDurableSessionId = prev?.durableSessionId
let nextUserMessage = prev?.userMessage === true
if (prev?.durable === true && prev?.userMessage === true) {
// An append-only user/message durability proof stays permanently valid across switches.
nextDurable = true
nextUserMessage = true
nextDurableSessionId = prev.durableSessionId ?? prev.sessionId
} else if (durable === true) {
nextDurable = true
nextDurableSessionId = sessionId ?? prev?.durableSessionId ?? prev?.sessionId
nextUserMessage = userMessage === true
}
logical.set(rpcId, {
sessionId: sessionId ?? prev?.sessionId,
durable: nextDurable,
durableSessionId: nextDurableSessionId,
userMessage: nextUserMessage,
})
if (logical.size > 400) logical.delete(logical.keys().next().value)
}
const noteSessionRpcDurability = (sessionId, rpcId, { durable = false, userMessage = false } = {}) => {
if (typeof sessionId !== 'string' || sessionId === '' || typeof rpcId !== 'string' || rpcId === '') return
let map = sessionRpcDurability.get(sessionId)
if (map === undefined) {
map = new Map()
sessionRpcDurability.set(sessionId, map)
}
const prev = map.get(rpcId)
map.delete(rpcId)
let nextDurable = prev?.durable === true
let nextUserMessage = prev?.userMessage === true
if (prev?.durable === true && prev?.userMessage === true) {
nextDurable = true
nextUserMessage = true
} else if (durable === true) {
nextDurable = true
nextUserMessage = userMessage === true || prev?.userMessage === true
}
map.set(rpcId, { durable: nextDurable, userMessage: nextUserMessage })
if (map.size > 400) {
for (const [key, entry] of map) {
if (entry.durable === true) {
map.delete(key)
break
}
}
if (map.size > 2000) map.delete(map.keys().next().value)
}
}
const noteAdmittedRpc = (sessionId, rpcId, opts) => {
noteSessionAdmittedRpc(sessionId, rpcId)
noteSessionRpcDurability(sessionId, rpcId, opts)
noteLogicalAdmittedRpc(sessionId, rpcId, opts)
}
const noteSendPrompted = (sessionId, rpcId) => {
if (sessionId === undefined || rpcId === undefined) return
noteLogicalAdmittedRpc(sessionId, rpcId)
noteSessionRpcDurability(sessionId, rpcId)
noteSessionAdmittedRpc(sessionId, rpcId)
}
const noteRoomLedgerRpcDurable = (roomId, sessionId, rpcId) => {
if (typeof rpcId !== 'string') return
const trimmed = rpcId.trim()
if (trimmed === '') return
const sid = typeof sessionId === 'string' && sessionId !== ''
? sessionId
: (typeof roomId === 'string' && roomId !== '' ? rt.sessionOfRoom?.(rt.roomOf(roomId)) : undefined)
if (typeof sid === 'string' && sid !== '') {
noteAdmittedRpc(sid, trimmed, { durable: true, userMessage: true })
}
rt.publishFeed?.('send-confirmed', {
requestId: trimmed,
...(typeof sid === 'string' && sid !== '' ? { sessionId: sid } : {}),
...(typeof roomId === 'string' && roomId !== '' ? { chatId: roomId } : {}),
})
}
const isUserMessageDurable = (sessionId, rpcId, { liveFrame = false } = {}) => {
if (typeof sessionId !== 'string' || sessionId === '' || typeof rpcId !== 'string' || rpcId === '') return false
const owner = logicalOwnerOf(sessionId)
if (owner?.roomId !== undefined && typeof rt.findRoomLedgerRpc === 'function') {
const ledgerHit = rt.findRoomLedgerRpc(owner.roomId, rpcId)
if (ledgerHit?.found === true) {
return !liveFrame && ledgerHit.persisted === true
}
}
const perSession = sessionRpcDurability.get(sessionId)?.get(rpcId)
if (perSession?.durable === true) {
if (perSession.userMessage === true || !isSupersededPart(sessionId)) return true
}
const ownerKey = ownerKeyOf(owner)
const logicalHit = ownerKey === undefined ? undefined : admittedLogicalRpcIds.get(ownerKey)?.get(rpcId)
if (logicalHit?.durable === true) {
const durableSid = logicalHit.durableSessionId ?? logicalHit.sessionId
if (logicalHit.userMessage === true || (typeof durableSid === 'string' && !isSupersededPart(durableSid))) {
return true
}
}
if (liveFrame === true) return false
if (perSession !== undefined && perSession.durable !== true) return false
if (logicalHit !== undefined && logicalHit.durable !== true) return false
if (admittedRpcIds.get(sessionId)?.has(rpcId) === true) return false
return true
}
// One pass over an event log that separates two fundamentally different kinds of
// admission evidence: ids recorded as an append-only `user/message` (a turn that
// actually started; it stays on that part's transcript forever) versus ids still
// pending in the replayed inbox (durable input, but only consumable while the part
// is live — a retired part never runs again, so a pending inbox entry stranded
// there is no proof the owning conversation durably has the message).
const classifyAdmittedEvidence = (events) => {
const admitted = new Set()
const userMessages = new Set()
if (!Array.isArray(events)) return { admitted, userMessages }
const pending = { 'next-turn': [], 'next-step': [] }
for (const ev of events) {
if (ev?.type === 'user/message') {
for (const id of [ev.data?.id, ev.data?.message?.id, ev.data?.source?.rpcId]) {
if (id !== undefined) {
admitted.add(id)
userMessages.add(id)
}
}
} else if (ev?.type === 'agent/inbox/spliced' && ev.data) {
const inbox = pending[ev.data.target]
if (inbox !== undefined) {
const start = ev.data.start
const removedCount = ev.data.removedCount ?? 0
const inserted = Array.isArray(ev.data.inserted) ? ev.data.inserted : []
if (Number.isSafeInteger(start) && start >= 0 && start <= inbox.length
&& Number.isSafeInteger(removedCount) && removedCount >= 0 && start + removedCount <= inbox.length) {
inbox.splice(start, removedCount, ...inserted)
}
}
}
}
for (const list of [pending['next-turn'], pending['next-step']]) {
for (const msg of list) {
if (msg?.id !== undefined) admitted.add(msg.id)
if (msg?.source?.rpcId !== undefined) admitted.add(msg.source.rpcId)
}
}
return { admitted, userMessages }
}
const collectAdmittedIdsFromEvents = (events, claimed) => {
if (claimed === undefined) return classifyAdmittedEvidence(events).admitted
const found = new Set()
if (!Array.isArray(events)) return found
const pending = { 'next-turn': [], 'next-step': [] }
for (const ev of events) {
if (ev?.type === 'turn/end') claimed.clear()
if (ev?.type === 'user/message') {
if (ev.data?.id !== undefined) found.add(ev.data.id)
if (ev.data?.message?.id !== undefined) found.add(ev.data.message.id)
if (ev.data?.source?.rpcId !== undefined) found.add(ev.data.source.rpcId)
} else if (ev?.type === 'agent/inbox/spliced' && ev.data) {
const inbox = pending[ev.data.target]
if (inbox !== undefined) {
const start = ev.data.start
const removedCount = ev.data.removedCount ?? 0
const inserted = Array.isArray(ev.data.inserted) ? ev.data.inserted : []
if (Number.isSafeInteger(start) && start >= 0 && start <= inbox.length
&& Number.isSafeInteger(removedCount) && removedCount >= 0 && start + removedCount <= inbox.length) {
const removed = inbox.splice(start, removedCount, ...inserted)
if (inserted.length === 0 && ev.data.outcome !== 'canceled') {
for (const msg of removed) {
claimed.add(msg?.id)
claimed.add(msg?.source?.rpcId)
}
}
}
}
}
}
for (const list of [pending['next-turn'], pending['next-step']]) {
for (const msg of list) {
if (msg?.id !== undefined) found.add(msg.id)
if (msg?.source?.rpcId !== undefined) found.add(msg.source.rpcId)
}
}
return found
}
// The session a send to `ref` would reach now, mirroring `channel.js`:
// an earlier part of a thread resolves to that thread's live part.
const sendTargetOf = (ref) => {
const past = rt.pastOwners.get(ref)
const room = rt.roomOf(ref) ?? (past?.roomId !== undefined ? rt.roomOf(past.roomId) : undefined)
const ownTarget = (() => {
if (rt.botOf(ref)) return rt.chatOf(ref)
const taskOwner = rt.taskOwners?.get(ref)
if (taskOwner !== undefined) {
if (taskOwner.roomId !== undefined) {
const ownerRoom = rt.roomOf(taskOwner.roomId)
return ownerRoom === undefined ? undefined : rt.sessionOfRoom(ownerRoom)
}
return rt.chatOf(taskOwner.botId)
}
if (past !== undefined && past.roomId === undefined) {
const bot = rt.botOf(past.botId)
if (threadOfPart(bot, ref)?.thread === 'task') return rt.chatOf(past.botId)
return threadCurrentOfPart(bot, ref) ?? rt.chatOf(past.botId)
}
return undefined
})()
return ownTarget ?? (room !== undefined ? rt.sessionOfRoom(room) : ref)
}
// A part superseded by a newer one: it is recorded as a past part of its owner
// and the owner's live target no longer is this session. Its pending inbox can
// never be consumed again, so unconsumed inbox evidence on it must be confirmed
// on the replacement part instead of being trusted as durable.
const isSupersededPart = (sid) => {
if (rt.pastOwners?.has?.(sid) !== true) return false
if (rt.isBotSession?.(sid) === true || rt.roomOwners?.has?.(sid) === true) return false
const current = sendTargetOf(sid)
return typeof current === 'string' && current !== '' && current !== sid
}
const hasSessionAdmission = (agent, ...ids) => {
const candidates = new Set(ids.filter(id => id !== undefined))
if (agent === undefined || candidates.size === 0) return false
for (const list of [agent.inbox?.nextStep ?? [], agent.inbox?.nextTurn ?? []]) {
if (list.some(msg => candidates.has(msg?.id) || candidates.has(msg?.source?.rpcId))) return true
}
const admitted = collectAdmittedIdsFromEvents(agent.session?.snapshotEvents?.())
return [...candidates].some(id => admitted.has(id))
}
const isAdmittedOn = (agent, rpcId) => {
if (rpcId === undefined || agent === undefined) return false
const sid = agent.id ?? agent.session?.id
return admittedRpcIds.get(sid)?.has(rpcId) === true || hasSessionAdmission(agent, rpcId)
}
const isClaimedInTurn = (agent, id) => {
if (id === undefined || agent?.status !== 'running') return false
const claimed = new Set()
const admitted = collectAdmittedIdsFromEvents(agent.session?.snapshotEvents?.(), claimed)
return claimed.has(id) && !admitted.has(id)
}
const waitForClaimedAdmission = (sessionId, agent, requestId, holdsRequest, timeoutMs = 5000) => {
if (holdsRequest()) return Promise.resolve(true)
if (disposed || !isClaimedInTurn(agent, requestId)) return Promise.resolve(false)
if (typeof ctx.on !== 'function') return Promise.resolve(false)
return new Promise((resolve) => {
let settled = false
let offEvent
let offDisposed
const finish = (ok) => {
if (settled) return
settled = true
activeAdmissionWaiters.delete(onHostDispose)
clearTimeout(timer)
offEvent?.()
offDisposed?.()
resolve(ok)
}
const onHostDispose = () => finish(holdsRequest())
const check = () => {
if (holdsRequest()) return finish(true)
if (disposed || !isClaimedInTurn(agent, requestId)) return finish(false)
}
activeAdmissionWaiters.add(onHostDispose)
// Keep the bounded timeout ref'd while waiting; host dispose cancels it immediately.
const timer = setTimeout(() => finish(holdsRequest()), timeoutMs)
offEvent = ctx.on('session/event', (evSession, ev) => {
if (evSession?.id !== sessionId) return
if (ev?.type === 'user/message' || ev?.type === 'turn/end' || ev?.type === 'agent/inbox/spliced') check()
})
offDisposed = ctx.on('agent/disposed', (ev) => {
const disposedAgent = ev?.agent ?? ev
if ((disposedAgent?.id ?? disposedAgent?.session?.id) === sessionId) finish(holdsRequest())
})
check()
})
}
const confirmSessionFlushed = async (sessionId, requestId) => {
if (typeof sessionId !== 'string' || sessionId === '') return false
const owner = logicalOwnerOf(sessionId)
const hasPersistedRoomLedger = () => {
if (owner?.roomId === undefined || typeof requestId !== 'string' || requestId.trim() === '') return false
if (rt.findRoomLedgerRpc?.(owner.roomId, requestId)?.persisted !== true) return false
noteAdmittedRpc(sessionId, requestId, { durable: true, userMessage: true })
return true
}
if (hasPersistedRoomLedger()) return true
if (typeof ctx.sessions?.flush !== 'function') return false
const agent = ctx.get?.('agents')?.get?.(sessionId)
const session = agent?.session ?? ctx.sessions?.get?.(sessionId)
if (session === undefined) return false
const canVerifyAdmission = requestId !== undefined && typeof session.snapshotEvents === 'function'
if (!canVerifyAdmission) {
try {
if ((await ctx.sessions.flush(session)) !== true) return hasPersistedRoomLedger()
if (requestId !== undefined) {
noteSessionRpcDurability(sessionId, requestId, { durable: true })
noteLogicalAdmittedRpc(sessionId, requestId, { durable: true })
}
return true
} catch {
return hasPersistedRoomLedger()
}
}
const hasUserMessageIn = events => events.some(
ev => ev?.type === 'user/message' && (
ev.data?.id === requestId
|| ev.data?.message?.id === requestId
|| ev.data?.source?.rpcId === requestId
),
)
const hasUserMessageNow = () => hasUserMessageIn(session.snapshotEvents?.() ?? [])
// Inbox-only evidence acks durable only while the part is still live: if a part
// switch committed while `flush()` was awaiting, this session is now a retired
// past part whose pending inbox will never be consumed again. An unconsumed
// inbox entry stranded there is being forwarded onto the replacement part by
// parts.js (or may be lost if that handoff failed), so the caller must fall
// through to replacement confirmation instead of trusting this part.
const supersededWithInboxOnlyEvidence = () => !hasUserMessageNow() && isSupersededPart(sessionId)
try {
for (let pass = 0; pass < 4; pass += 1) {
if (hasPersistedRoomLedger()) return true
let before = session.snapshotEvents?.() ?? []
let hadUserMessageBeforeFlush = hasUserMessageIn(before)
const hadDurableInboxBeforeFlush = !hadUserMessageBeforeFlush
&& collectAdmittedIdsFromEvents(before).has(requestId)
if (!hadUserMessageBeforeFlush && !hadDurableInboxBeforeFlush) {
if (hasPersistedRoomLedger()) return true
if (agent === undefined || !isClaimedInTurn(agent, requestId)) return false
if (!(await waitForClaimedAdmission(sessionId, agent, requestId, hasUserMessageNow))) {
return hasPersistedRoomLedger()
}
before = session.snapshotEvents?.() ?? []
hadUserMessageBeforeFlush = hasUserMessageIn(before)
if (!hadUserMessageBeforeFlush) return hasPersistedRoomLedger()
}
const beforeLen = before.length
if ((await ctx.sessions.flush(session)) !== true) return hasPersistedRoomLedger()
if (hadUserMessageBeforeFlush) {
noteSessionRpcDurability(sessionId, requestId, { durable: true, userMessage: true })
noteLogicalAdmittedRpc(sessionId, requestId, { durable: true, userMessage: true })
return true
}
if (hasPersistedRoomLedger()) return true
const after = session.snapshotEvents?.() ?? []
const spliceMutatedDuringFlush = after.length < beforeLen
|| after.slice(beforeLen).some(ev => ev?.type === 'agent/inbox/spliced')
if (!spliceMutatedDuringFlush && !hasUserMessageIn(after) && collectAdmittedIdsFromEvents(after).has(requestId)) {
if (supersededWithInboxOnlyEvidence()) return false
noteSessionRpcDurability(sessionId, requestId, { durable: true, userMessage: false })
noteLogicalAdmittedRpc(sessionId, requestId, { durable: true, userMessage: false })
return true
}
}
return hasPersistedRoomLedger()
} catch {
return hasPersistedRoomLedger()
}
}
const findLiveAdmittedSession = (requestId, ownerKey) => {
for (const [sid, set] of admittedRpcIds) {
if (!set.has(requestId)) continue
if (ownerKey !== undefined && ownerKeyOf(logicalOwnerOf(sid)) !== ownerKey) continue
return sid
}
return undefined
}
const findAdmittedForSend = async ({ ref, refs, sessionId, requestId, callerSupplied = true, targetOnly = false } = {}) => {
if (requestId === undefined) return { admitted: false }
const owner = logicalOwnerOf(sessionId) ?? logicalOwnerOf(ref)
const ownerKey = ownerKeyOf(owner)
const roomLedgerAdmission = (roomId) => {
if (typeof roomId !== 'string' || roomId === '' || typeof rt.findRoomLedgerRpc !== 'function') return undefined
const hit = rt.findRoomLedgerRpc(roomId, requestId)
if (hit?.found !== true) return undefined
const room = rt.roomOf(roomId)
const sid = (room !== undefined ? rt.sessionOfRoom?.(room) : undefined) ?? sessionId
if (hit.persisted === true) {
if (typeof sid === 'string' && sid !== '') {
noteAdmittedRpc(sid, requestId, { durable: true, userMessage: true })
}
return { admitted: true, sessionId: sid, durable: true, userMessage: true }
}
if (typeof sid === 'string' && sid !== '') {
noteAdmittedRpc(sid, requestId, { durable: false, userMessage: false })
}
return { admitted: true, sessionId: sid, durable: false, userMessage: false }
}
const hitResult = (hit, key) => {
const sid = hit.durableSessionId ?? hit.sessionId ?? findLiveAdmittedSession(requestId, key)
// A cached inbox-only durability proof is only valid while its owning part
// has not been superseded by a part switch; once retired, force re-confirmation
// on the replacement part instead of returning a stale `durable: true`.
const durable = hit.durable === true
&& (hit.userMessage === true || (typeof sid === 'string' && !isSupersededPart(sid)))
if (!durable) {
const hitRoomId = (typeof key === 'string' && key.startsWith('room:'))
? key.slice(5)
: (logicalOwnerOf(sid)?.roomId ?? owner?.roomId)
const ledgerHit = roomLedgerAdmission(hitRoomId)
if (ledgerHit?.durable === true) return ledgerHit
}
return {
admitted: true,
sessionId: sid,
durable,
userMessage: hit.userMessage === true,
}
}
if (ownerKey !== undefined) {
const hit = admittedLogicalRpcIds.get(ownerKey)?.get(requestId)
if (hit !== undefined) return hitResult(hit, ownerKey)
}
const isImRequest = typeof requestId === 'string' && requestId.startsWith('im:')
if (isImRequest && !targetOnly) {
for (const [key, map] of admittedLogicalRpcIds.entries()) {
const hit = map.get(requestId)
if (hit !== undefined) return hitResult(hit, key)
}
}
if (Array.isArray(refs) && refs.length > 0) {
for (const extraRef of refs) {
const extraKey = ownerKeyOf(logicalOwnerOf(extraRef))
if (extraKey === undefined) continue
const hit = admittedLogicalRpcIds.get(extraKey)?.get(requestId)
if (hit !== undefined) return hitResult(hit, extraKey)
}
}
const candidates = new Map() // sid -> { immutable: boolean }
const candidateRoomIds = new Set()
const addCandidate = (sid, immutable = false) => {
if (typeof sid !== 'string' || sid === '') return
const existing = candidates.get(sid)
if (existing === undefined) candidates.set(sid, { immutable })
else if (immutable) existing.immutable = true
}
const addBotCandidates = (bot) => {
if (bot === undefined) return
addCandidate(rt.chatOf(bot.id), false)
for (const seg of [...(bot.segments ?? [])].reverse().slice(0, 6)) {
addCandidate(seg?.sessionId, true)
}
}
const addRoomCandidates = (room) => {
if (room === undefined) return
candidateRoomIds.add(room.id)
addCandidate(rt.sessionOfRoom?.(room), false)
if (Array.isArray(room?.parts)) {
for (const part of [...room.parts].reverse().slice(0, 4)) {
addCandidate(typeof part === 'string' ? part : part?.sessionId, true)
}
}
if (room?.segments !== null && typeof room?.segments === 'object') {
const segLists = Array.isArray(room.segments) ? [room.segments] : Object.values(room.segments)
for (const list of segLists) {
if (!Array.isArray(list)) continue
for (const seg of [...list].reverse().slice(0, 4)) {
addCandidate(seg?.sessionId, true)
}
}
}
}
addCandidate(sessionId, false)
if (ref !== undefined && rt.botOf(ref) === undefined && rt.roomOf(ref) === undefined) addCandidate(ref, false)
if (owner?.botId !== undefined) addBotCandidates(rt.botOf(owner.botId))
else if (owner?.roomId !== undefined) addRoomCandidates(rt.roomOf(owner.roomId))
if (Array.isArray(refs) && refs.length > 0) {
for (const extraRef of refs) {
const extraOwner = logicalOwnerOf(extraRef)
if (extraOwner?.botId !== undefined) addBotCandidates(rt.botOf(extraOwner.botId))
else if (extraOwner?.roomId !== undefined) addRoomCandidates(rt.roomOf(extraOwner.roomId))
else addCandidate(extraRef, false)
}
}
if (isImRequest && !targetOnly) {
for (const bot of Object.values(state.bots ?? {})) addBotCandidates(bot)
for (const room of Object.values(state.rooms ?? {})) addRoomCandidates(room)
}
// Check canonical persisted room ledger evidence first (works both on the live host
// after an earlier DSH flush failure and after a host restart from disk snapshots).
let pendingLedgerHit
for (const roomId of candidateRoomIds) {
const ledgerHit = roomLedgerAdmission(roomId)
if (ledgerHit === undefined) continue
if (ledgerHit.durable === true) return ledgerHit
pendingLedgerHit ??= ledgerHit
}
const agents = ctx.get?.('agents')
const coldCandidates = []
for (const [sid, meta] of candidates) {
if (admittedRpcIds.get(sid)?.has(requestId)) {
noteLogicalAdmittedRpc(sid, requestId)
return { admitted: true, sessionId: sid, durable: false }
}
const agent = agents?.get?.(sid)
if (agent !== undefined) {
if (isAdmittedOn(agent, requestId)) {
noteAdmittedRpc(sid, requestId)
return { admitted: true, sessionId: sid, durable: false }
}
continue
}
const session = ctx.sessions?.get?.(sid)
if (session !== undefined) {
if (collectAdmittedIdsFromEvents(session.snapshotEvents?.()).has(requestId)) {
noteAdmittedRpc(sid, requestId)
return { admitted: true, sessionId: sid, durable: false }
}
continue
}
coldCandidates.push([sid, meta])
}
if (!callerSupplied || coldCandidates.length === 0) return pendingLedgerHit ?? { admitted: false }
let readFailure
// Persisted evidence on a retired past part proves durability only when it is
// an append-only `user/message`: a turn that started there is part of the
// conversation's permanent transcript. A pending inbox entry stranded on a
// superseded part is never consumed again — it counts as durable only once
// the replacement part durably holds it, so it must not ack `durable: true`.
const durableOnColdPart = (sid, hasUserMessageEvidence) => {
if (hasUserMessageEvidence) return true
return !isSupersededPart(sid)
}
for (const [sid, meta] of coldCandidates) {
const cached = inspectedSettledSessionRpcIds.get(sid)
if (cached !== undefined) {
const cachedEntry = cached.get(requestId)
if (cachedEntry !== undefined) {
const userMessage = cachedEntry.userMessage === true
const durable = durableOnColdPart(sid, userMessage)
noteAdmittedRpc(sid, requestId, { durable, userMessage })
return { admitted: true, sessionId: sid, durable, userMessage }
}
continue
}
const read = await rt.readSessionEvidence?.(sid, AbortSignal.timeout(HISTORY_TIMEOUT_MS), { preferPersisted: true })
if (!read || read.status === 'unavailable') return { admitted: false }
if (read.status === 'error') {
readFailure ??= read.error
continue
}
const classified = classifyAdmittedEvidence(read.events)
const foundIds = classified.admitted
const isPersisted = read.persisted === true
if (meta.immutable && read.status === 'ok' && isPersisted) {
const entries = new Map()
for (const id of foundIds) entries.set(id, { userMessage: classified.userMessages.has(id) })
inspectedSettledSessionRpcIds.set(sid, entries)
while (inspectedSettledSessionRpcIds.size > MAX_INSPECTED_SESSIONS) {
inspectedSettledSessionRpcIds.delete(inspectedSettledSessionRpcIds.keys().next().value)
}
}
if (foundIds.has(requestId)) {
const userMessage = classified.userMessages.has(requestId)
const durable = isPersisted && durableOnColdPart(sid, userMessage)
noteAdmittedRpc(sid, requestId, { durable, userMessage })
return { admitted: true, sessionId: sid, durable, userMessage }
}
if (!isPersisted || read.status === 'not_found') {
const attachedAgent = agents?.get?.(sid)
if (attachedAgent !== undefined && (isAdmittedOn(attachedAgent, requestId) || isClaimedInTurn(attachedAgent, requestId))) {
noteAdmittedRpc(sid, requestId)
return { admitted: true, sessionId: sid, durable: false }
}
const attachedSession = ctx.sessions?.get?.(sid)
if (attachedSession !== undefined && collectAdmittedIdsFromEvents(attachedSession.snapshotEvents?.()).has(requestId)) {
noteAdmittedRpc(sid, requestId)
return { admitted: true, sessionId: sid, durable: false }
}
}
}
if (readFailure !== undefined) throw readFailure
return pendingLedgerHit ?? { admitted: false }
}
const isDurableProofStillValid = (sid, requestId, userMessage = false) => {
if (userMessage === true) return true
if (typeof sid !== 'string' || sid === '') return false
const owner = logicalOwnerOf(sid)
if (owner?.roomId !== undefined && typeof requestId === 'string' && requestId.trim() !== '') {
if (rt.findRoomLedgerRpc?.(owner.roomId, requestId)?.persisted === true) return true
}
if (!isSupersededPart(sid)) return true
if (requestId === undefined) return false
const session = ctx.get?.('agents')?.get?.(sid)?.session ?? ctx.sessions?.get?.(sid)
const events = typeof session?.snapshotEvents === 'function' ? session.snapshotEvents() : undefined
if (!Array.isArray(events)) return false
return events.some(
ev => ev?.type === 'user/message' && (
ev.data?.id === requestId
|| ev.data?.message?.id === requestId
|| ev.data?.source?.rpcId === requestId
),
)
}
const isAdmittedForSend = async (args) => (await findAdmittedForSend(args)).admitted === true
// Read-only lookup for legacy archived `bot.tasks[]` (e.g. `read_own_chat` archive recall).
const taskById = (taskId) => {
if (typeof taskId !== 'string' || taskId === '') return undefined
for (const bot of Object.values(state.bots ?? {})) {
const task = (bot.tasks ?? []).find(item => item?.id === taskId)
if (task !== undefined) return { bot, task }
}
return undefined
}
const taskBySession = (sessionId) => {
if (typeof sessionId !== 'string' || sessionId === '') return undefined
for (const bot of Object.values(state.bots ?? {})) {
const task = (bot.tasks ?? []).find(
item => item?.sessionId === sessionId || (item?.segments ?? []).some(seg => seg?.sessionId === sessionId),
)
if (task !== undefined) return { bot, task }
}
return undefined
}
const forgetTaskSession = (sessionId) => {
if (typeof sessionId !== 'string' || sessionId === '') return
admittedRpcIds.delete(sessionId)
sessionRpcDurability.delete(sessionId)
rt.taskOwners?.delete(sessionId)
}
const forgetBotTasks = (bot) => {
// Do NOT delete `bot.tasks` here: `roster.js:deleteBot` reads `openSessions(bot)`
// immediately after to archive memory, preserve `privateArchives[].sessionIds`,
// release sessions, and await `deleteSegmentNotes`.
forgetTaskSession(bot?.id)
forgetTaskSession(rt.chatOf?.(bot?.id))
for (const task of tasksOf(bot)) {
rt.cancelApprovals?.(task.sessionId)
dropReportFile(task.reportFile)
for (const sid of taskSessionIds(task)) forgetTaskSession(sid)
}
}
// Keep send-admission RPC tracking and group-relay discard hooks alive after retiring L3/L4.
ctx.on?.('agent/inbox/inserted', ({ agent, message } = {}) => {
if (message?.source?.rpcId !== undefined) {
noteAdmittedRpc(agent?.id ?? agent?.session?.id, message.source.rpcId)
}
})
ctx.on?.('agent/inbox/discarded', ({ agent, message } = {}) => {
const src = message?.source
if (src?.kind === SOURCE_KIND && src.role === 'post') {
rt.roomRelayDiscarded?.(src, agent?.id ?? agent?.session?.id)
return
}
if (src?.kind === SOURCE_KIND && src.role === 'room' && typeof src.exchangeId === 'string' && src.exchangeId !== '' && !rt.isMovingInboxMessage?.(message.id)) {
rt.finishLateRoomExchange?.(src.exchangeId)
}
})
ctx.on?.('session/event', (session, event) => {
if (event?.type === 'user/message' && event.data?.source?.rpcId !== undefined) {
noteAdmittedRpc(session?.id, event.data.source.rpcId)
}
})
const reportsDir = join(rt.home, 'reports')
const tasksOf = bot => Array.isArray(bot?.tasks) ? bot.tasks : []
const retiredTasks = () => Array.isArray(state.retiredTasks) ? state.retiredTasks : []
const retiredTaskSessionIds = bot => Array.isArray(bot?.retiredTaskSessions) ? bot.retiredTaskSessions : []
const taskSessionIds = (task) => {
const ids = []
if (typeof task?.sessionId === 'string' && task.sessionId !== '') ids.push(task.sessionId)
for (const seg of task?.segments ?? []) {
if (typeof seg?.sessionId === 'string' && seg.sessionId !== '') ids.push(seg.sessionId)
}
return [...new Set(ids)]
}
const ownedTaskSessionIds = (task) => {
const inherited = new Set((task?.inheritedSegments ?? []).map(segment => segment?.sessionId))
return taskSessionIds(task).filter(id => id !== task?.from && !inherited.has(id))
}
const dropReportFile = (file) => {
if (typeof file !== 'string' || !/^[A-Za-z0-9_-]+\.txt$/.test(file)) return true
if (rt.readOnly?.() !== undefined) return false
try {
rmSync(join(reportsDir, file), { force: true })
return true
} catch {
return false
}
}
const archivedTaskSessions = new Set()
const hasRegistryArchiveList = () => {
try {
const archived = ctx.workspaceRegistry?.archivedSessionIds
return archived !== undefined && archived !== null
} catch {
return false
}
}
const rememberArchivedTaskSession = (id) => {
if (typeof id !== 'string' || id === '' || hasRegistryArchiveList()) return
archivedTaskSessions.delete(id)
archivedTaskSessions.add(id)
if (archivedTaskSessions.size > MAX_ARCHIVED_TASK_FALLBACK) {
const oldest = archivedTaskSessions.values().next().value
if (oldest !== undefined) archivedTaskSessions.delete(oldest)
}
}
const sessionAlreadyArchived = (id) => {
try {
const archived = ctx.workspaceRegistry?.archivedSessionIds
if (archived !== undefined && archived !== null) {
if (archived instanceof Set) return archived.has(id)
if (Array.isArray(archived)) return archived.includes(id)
if (typeof archived[Symbol.iterator] === 'function') {
for (const item of archived) if (item === id) return true
return false
}
}
} catch {}
return archivedTaskSessions.has(id)
}
const hasLiveSessionOwner = id => rt.agentOf?.(id) !== undefined
|| rt.chatOwners.has(id) || rt.groupOwners.has(id) || rt.roomOwners.has(id)
const hasSessionOwner = id => hasLiveSessionOwner(id) || rt.pastOwners.has(id)
const isInherited = id => Object.values(state.bots ?? {}).some(bot => tasksOf(bot).some(task =>
task?.from === id || task?.inheritedSegments?.some(segment => segment?.sessionId === id)))
// All legacy per-Bot background task sessions (task_start, fg-handoff, bot-handoff)
// no longer have any UI entry after #2808, so every settled legacy task session
// migrates its schedules back to the Bot/room chat and archives cleanly.
const unarchivedSettledHandoffIds = (task) => {
if (!task || !TERMINAL_TASK_STATUSES.has(task.status)) return []
return ownedTaskSessionIds(task).filter(id => !hasLiveSessionOwner(id) && !isInherited(id) && !sessionAlreadyArchived(id))
}
const retirementTarget = ({ botId, roomId }) => {
if (rt.botOf(botId) === undefined) return undefined
if (roomId === undefined) return rt.chatOf(botId)
const room = rt.roomOf(roomId)
return room?.members?.includes(botId) ? room.sessions?.[botId] : undefined
}
const cleanPrunedSession = (id) => {
for (const entries of [state.closedCards, state.closedCardSeqs, state.exchangeTurns, state.questions, state.views, state.switching]) {
if (entries !== undefined) delete entries[id]
}
admittedRpcIds.delete(id)
rt.renewMemory?.(id)
rt.forgetSessionParts?.(id)
rt.forgetSessionTurn?.(id)
rt.forgetSessionModel?.(id)
rt.releaseSession?.(id, { reason: 'task-pruned' })
return rt.deleteSegmentNotes?.([id])
}
const sessionBusy = (id) => {
const agent = ctx.get?.('agents')?.get?.(id)
return agent?.status === 'running' || rt.live?.get?.(id)?.turn !== undefined
|| rt.hasPendingRecovery?.(id) === true || rt.isSwitchingPart?.(id) === true
|| state.switching?.[id] !== undefined || (rt.runningJobs?.(id)?.length ?? 0) > 0
}
function pruneSettledTasks(bot, keepSessions = new Set()) {
const settled = tasksOf(bot).filter(task => task && TERMINAL_TASK_STATUSES.has(task.status))
const excess = settled.length - MAX_SETTLED_TASKS
if (excess <= 0) return []
const dropped = new Set()
for (const task of settled.slice(0, excess)) {
const ids = taskSessionIds(task)
if (ids.some(id => keepSessions.has(id) || sessionBusy(id))) continue
state.retiredTasks = [...retiredTasks(), { botId: bot.id, roomId: task.roomId, sessionIds: ownedTaskSessionIds(task), reportFile: task.reportFile }]
bot.retiredTaskSessions = [...new Set([...retiredTaskSessionIds(bot), ...ids])]
dropped.add(task)
}
if (dropped.size > 0) bot.tasks = tasksOf(bot).filter(task => !dropped.has(task))
return [...dropped]
}
let retirement = Promise.resolve()
let retirementStopped = false
let retirementRetryTimer
let retirementRetryDelay = 1000
const writeAccess = () => retirementStopped || rt.readOnly?.() !== undefined ? undefined : rt.teamWriteAccess?.()
const ownsRetirement = () => writeAccess() === 'locked'
const resetRetirementRetry = () => {
clearTimeout(retirementRetryTimer)
retirementRetryTimer = undefined
retirementRetryDelay = 1000
}
const retryRetirement = () => {
if (retirementRetryTimer !== undefined || !ownsRetirement()) return
retirementRetryTimer = setTimeout(() => {
retirementRetryTimer = undefined
if (ownsRetirement()) void retireTasks()
}, retirementRetryDelay)
retirementRetryTimer.unref?.()
retirementRetryDelay = Math.min(retirementRetryDelay * 2, 15_000)
}
const stopRetiringTasks = () => {
retirementStopped = true
resetRetirementRetry()
return retirement
}
async function updateRetirement(entry, next) {
const before = retiredTasks()
const after = before.flatMap(item => item === entry ? (next === undefined ? [] : [next]) : [item])
state.retiredTasks = after
try {
await rt.save({ required: true })
} catch (error) {
if (state.retiredTasks === after) state.retiredTasks = before
throw error
}
}
// Safely archives legacy pruned/settled task sessions on upgrade, moving any schedules
// attached to retired task sessions back to the Bot's foreground chat before archiving.
function retireTasks(bots = [], keepSessions = new Set()) {
retirement = retirement.then(async () => {
const access = writeAccess()
if (access === undefined) return
const pruned = bots.filter(bot => rt.botOf(bot.id) === bot)
.flatMap(bot => pruneSettledTasks(bot, keepSessions))
const pending = retiredTasks().slice()
const unarchivedHandoffs = access === 'locked'
? Object.values(state.bots ?? {}).flatMap(bot => tasksOf(bot).flatMap((task) => {
const ids = unarchivedSettledHandoffIds(task)
return ids.length > 0 ? [{ bot, task, sessionIds: ids }] : []
}))
: []
if (pruned.length === 0 && (access !== 'locked' || (pending.length === 0 && unarchivedHandoffs.length === 0))) return
await rt.save({ required: true })
if (access !== 'locked') return
let retry = false
for (const entry of pending) {
const current = () => ownsRetirement() && retiredTasks().includes(entry)
if (!current()) return
const remaining = []
for (const id of entry.sessionIds ?? []) {
if (!current()) return
if (hasSessionOwner(id)) continue
if (keepSessions.has(id) || sessionBusy(id) || isInherited(id)) {
remaining.push(id)
continue
}
try {
const target = retirementTarget(entry)
if (target !== undefined) await rt.moveSchedules?.(id, target)
if (!current()) return
if (hasSessionOwner(id)) continue
if (sessionBusy(id) || isInherited(id) || retirementTarget(entry) !== target) {
remaining.push(id)
continue
}
if (!sessionAlreadyArchived(id)) {
await ctx.workspaceRegistry?.archiveSession?.(id)
rememberArchivedTaskSession(id)
}
} catch (error) {
if (error?.name !== 'WorkspaceUnknownSessionError' || error.sessionId !== id) {
remaining.push(id)
if (error?.code !== 'schedule/pending') {
rt.warn?.('ds-bot: task Session %s not archived yet: %s', id, error)
retry = true
}
continue
}
rememberArchivedTaskSession(id)
}
if (!current()) return
if (!hasSessionOwner(id)) await cleanPrunedSession(id)
}
if (!current()) return
if (remaining.length > 0 && remaining.length === (entry.sessionIds ?? []).length) continue
let completed = entry
if ((entry.sessionIds ?? []).length > 0) {
completed = { ...entry, sessionIds: remaining }
await updateRetirement(entry, completed)
}
if (remaining.length > 0 || !ownsRetirement() || !retiredTasks().includes(completed)) continue
if (dropReportFile(completed.reportFile)) await updateRetirement(completed, undefined)
}
for (const { bot, task, sessionIds } of unarchivedHandoffs) {
if (!ownsRetirement()) return