forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKernelTurnProjection.swift
More file actions
1302 lines (1237 loc) · 47.2 KB
/
Copy pathKernelTurnProjection.swift
File metadata and controls
1302 lines (1237 loc) · 47.2 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
import CryptoKit
import Foundation
struct KernelVoiceContextSnapshot: Equatable, Sendable {
static let empty = KernelVoiceContextSnapshot(
sessionId: "",
conversationId: "",
context: "",
freshnessIdentity: "",
contextPlanID: "",
stableCacheIdentity: "",
dynamicContextIdentity: "",
semanticGuidance: "",
turnIDs: []
)
let sessionId: String
let conversationId: String
let context: String
let freshnessIdentity: String
let contextPlanID: String
/// Opaque cache identities are safe to include in diagnostics.
let stableCacheIdentity: String
let dynamicContextIdentity: String
let semanticGuidance: String
let turnIDs: Set<String>
/// `.empty` is a transport/bridge failure sentinel, not a valid blank
/// conversation. A valid new conversation may render no text, but it still
/// has a kernel session and a deterministic freshness identity.
var isResolved: Bool {
!sessionId.isEmpty && !freshnessIdentity.isEmpty
}
}
struct KernelAutomationTurnRange: Equatable, Sendable {
let conversationId: String
let turns: [KernelJournalTurn]
}
/// Pure lifecycle mutation used by the journal writer and its behavioral
/// tests. A terminal agent fact enriches the assistant row that originally
/// produced the matching `agentSpawn`; it never creates a second chat turn.
@MainActor
enum KernelAgentLifecycleMutation {
struct Result {
let sourceTurn: KernelJournalTurn
let message: ChatMessage
let completionBlock: ChatContentBlock
let resources: [ChatResource]
}
static func completion(
in revisions: [KernelJournalTurn],
pillID: UUID,
sessionID: String?,
runID: String?,
title: String,
promptSnippet: String,
output: String,
status: String,
resources: [ChatResource]
) -> Result? {
var latestByTurnID: [String: KernelJournalTurn] = [:]
for revision in revisions {
if let current = latestByTurnID[revision.turnId], current.turnSeq >= revision.turnSeq {
continue
}
latestByTurnID[revision.turnId] = revision
}
let normalizedRunID = normalized(runID)
guard
let sourceTurn = latestByTurnID.values
.filter({ $0.role == "assistant" })
.filter({ turn in
let blocks = ChatContentBlockCodec.decode(turn.contentBlocksJSON) ?? []
return blocks.contains { block in
guard case .agentSpawn(_, let spawnPillID, _, let spawnRunID, _, _, _) = block else {
return false
}
if spawnPillID == pillID { return true }
guard let normalizedRunID else { return false }
return normalized(spawnRunID) == normalizedRunID
}
})
.max(by: { $0.turnSeq < $1.turnSeq })
else { return nil }
var message = sourceTurn.chatMessage()
let completionID = stableCompletionBlockID(pillID: pillID, runID: normalizedRunID)
let completion = ChatContentBlock.agentCompletion(
id: completionID,
pillId: pillID,
sessionId: normalized(sessionID),
runId: normalizedRunID,
title: normalized(title) ?? "Background agent",
promptSnippet: normalized(promptSnippet) ?? "Background agent",
output: output.trimmingCharacters(in: .whitespacesAndNewlines),
status: normalized(status) ?? "completed"
)
if let index = message.contentBlocks.firstIndex(where: {
guard case .agentCompletion(let id, let existingPillID, _, let existingRunID, _, _, _, _) = $0
else { return false }
if id == completionID { return true }
if let normalizedRunID { return normalized(existingRunID) == normalizedRunID }
return existingPillID == pillID && normalized(existingRunID) == nil
}) {
message.contentBlocks[index] = completion
} else {
message.contentBlocks.append(completion)
}
for resource in resources {
if let index = message.resources.firstIndex(where: { $0.id == resource.id }) {
message.resources[index] = resource
} else {
message.resources.append(resource)
}
}
return Result(
sourceTurn: sourceTurn,
message: message,
completionBlock: completion,
resources: resources
)
}
static func atomicAppendUpdate(_ result: Result) -> KernelJournalTurnUpdate {
KernelJournalTurnUpdate(
turnId: result.sourceTurn.turnId,
status: nil,
content: nil,
contentBlocksJSON: nil,
appendContentBlocksJSON: ChatContentBlockCodec.encode([
result.completionBlock
]) ?? "[]",
resourcesJSON: nil,
appendResourcesJSON: ChatResource.encodeResourcesForPersistence(
result.resources
) ?? "[]",
appendEvidenceJSON: nil,
metadataJSON: nil,
terminalRevision: false
)
}
nonisolated static func stableSpawnBlockID(pillID: UUID) -> String {
stableDigest(prefix: "agent_spawn", identity: pillID.uuidString.lowercased())
}
nonisolated static func stableCompletionBlockID(pillID: UUID, runID: String?) -> String {
stableDigest(
prefix: "agent_completion",
identity: normalized(runID) ?? pillID.uuidString.lowercased()
)
}
nonisolated private static func stableDigest(prefix: String, identity: String) -> String {
let digest = SHA256.hash(data: Data("\(prefix)\u{0}\(identity)".utf8))
return prefix + "_" + digest.prefix(12).map { String(format: "%02x", $0) }.joined()
}
nonisolated private static func normalized(_ value: String?) -> String? {
guard let value else { return nil }
let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? nil : trimmed
}
}
/// Main-chat projection over the kernel-owned journal. Runtime notifications
/// are wakeups only; every mutation is replayed in contiguous turnSeq order.
@MainActor
final class KernelTurnProjection {
private struct OwnerLease: Equatable {
let ownerID: String
let epoch: UInt64
}
struct ExchangeTurn {
let message: ChatMessage
let status: KernelJournalTurnStatus
}
typealias JournalListOperation = (
_ client: AgentClient.Session,
_ surface: AgentSurfaceReference,
_ ownerID: String,
_ afterTurnSeq: Int,
_ limit: Int
) async throws -> AgentRuntimeProcess.JournalOperationResult
typealias JournalClearOperation = (
_ client: AgentClient.Session,
_ surface: AgentSurfaceReference,
_ ownerID: String,
_ expectedGeneration: Int,
_ deleteBackend: Bool
) async throws -> Int
typealias KernelReadyOperation = () async -> Bool
private weak var host: ChatProvider?
private var client: AgentClient.Session?
private var eventToken: UUID?
private let ownerIDProvider: () -> String?
private let journalListOperation: JournalListOperation?
private let journalClearOperation: JournalClearOperation?
private let kernelReadyOperation: KernelReadyOperation?
private var projectionEpoch: UInt64 = 0
private var boundOwnerID: String?
private var highWaterByConversation: [String: Int] = [:]
private var generationByConversation: [String: Int] = [:]
private var conversationBySurface: [String: String] = [:]
private var refreshingSurfaceEpochs: [String: UInt64] = [:]
private var refreshRequestedSurfaceEpochs: [String: UInt64] = [:]
init(
host: ChatProvider,
client: AgentClient.Session? = nil,
ownerIDProvider: @escaping () -> String? = { RuntimeOwnerIdentity.currentOwnerId() },
journalListOperation: JournalListOperation? = nil,
journalClearOperation: JournalClearOperation? = nil,
kernelReadyOperation: KernelReadyOperation? = nil
) {
self.host = host
self.client = client
self.ownerIDProvider = ownerIDProvider
self.journalListOperation = journalListOperation
self.journalClearOperation = journalClearOperation
self.kernelReadyOperation = kernelReadyOperation
}
func attachClient(_ client: AgentClient.Session) async {
self.client = client
guard let lease = captureOwnerLease() else { return }
KernelJournalEventHub.shared.unsubscribe(eventToken)
await KernelJournalEventHub.shared.attach(client: client)
guard isCurrent(lease) else { return }
eventToken = KernelJournalEventHub.shared.subscribe(surface: nil) { [weak self] in
Task { @MainActor [weak self] in
guard let self, let surface = self.host?.mainChatSurfaceReference() else { return }
await self.refresh(surface: surface)
}
}
// The visible-chat loader owns the first replay so it can keep the
// transcript in its loading state until the complete snapshot is ready.
// Event notifications above still refresh an already-mounted surface.
}
/// Attach the owner-bound client for a non-production journal control action
/// without starting a model session or scheduling projection refresh work.
func attachControlClient(_ client: AgentClient.Session) {
self.client = client
}
/// Synchronous owner teardown. Suspended work retains its old epoch and can
/// neither mutate checkpoints nor project owner A rows after owner B starts.
func invalidateOwnerState() {
projectionEpoch &+= 1
boundOwnerID = nil
highWaterByConversation.removeAll()
generationByConversation.removeAll()
conversationBySurface.removeAll()
refreshingSurfaceEpochs.removeAll()
refreshRequestedSurfaceEpochs.removeAll()
if let host {
host.resetJournalProjection(surface: host.mainChatSurfaceReference())
}
}
/// Ordered replay. A gap never advances the checkpoint: the next page starts
/// from the last contiguous turnSeq, so out-of-order wakeups cannot drop data.
@discardableResult
func refresh(surface: AgentSurfaceReference) async -> Bool {
guard let lease = captureOwnerLease() else { return false }
return await refresh(surface: surface, lease: lease, publishPartialResults: true)
}
private func refresh(
surface: AgentSurfaceReference,
lease: OwnerLease,
publishPartialResults: Bool
) async -> Bool {
guard isCurrent(lease), let client else { return false }
let surfaceKey = surface.key
if refreshingSurfaceEpochs[surfaceKey] == lease.epoch {
refreshRequestedSurfaceEpochs[surfaceKey] = lease.epoch
return true
}
refreshingSurfaceEpochs[surfaceKey] = lease.epoch
defer {
if refreshingSurfaceEpochs[surfaceKey] == lease.epoch {
refreshingSurfaceEpochs.removeValue(forKey: surfaceKey)
}
}
// A restored conversation is not live streaming. Collect all contiguous
// turns fetched by this refresh, then publish one coherent transcript
// snapshot after the journal range is settled. Publishing each durable row
// independently makes first launch look like the user is watching old
// history arrive in real time, and causes the chat viewport to chase it.
var pendingProjectionTurns: [KernelJournalTurn] = []
var shouldResetProjection = false
var refreshSucceeded = true
repeat {
guard isCurrent(lease) else { return false }
// A queued request is a fresh attempt. Its outcome supersedes an earlier
// failed pass once the accumulated replacement snapshot is complete.
refreshSucceeded = true
if refreshRequestedSurfaceEpochs[surfaceKey] == lease.epoch {
refreshRequestedSurfaceEpochs.removeValue(forKey: surfaceKey)
}
var shouldContinue = true
while shouldContinue {
guard isCurrent(lease) else { return false }
let knownConversation = conversationBySurface[surfaceKey]
let knownCheckpoint = knownConversation.map {
checkpointKeyFor(conversationId: $0, surface: surface)
}
let after = knownCheckpoint.flatMap { highWaterByConversation[$0] } ?? 0
do {
let page = try await listJournalTurns(
client: client,
surface: surface,
ownerID: lease.ownerID,
afterTurnSeq: after,
limit: 100
)
guard isCurrent(lease) else { return false }
let conversationId = page.conversationId
guard !conversationId.isEmpty else {
shouldContinue = false
break
}
conversationBySurface[surfaceKey] = conversationId
let checkpointKey = checkpointKeyFor(conversationId: conversationId, surface: surface)
let currentGeneration = generationByConversation[checkpointKey]
if currentGeneration != page.conversationGeneration {
highWaterByConversation[checkpointKey] = page.generationBaseTurnSeq
generationByConversation[checkpointKey] = page.conversationGeneration
guard isCurrent(lease) else { return false }
// A newer generation invalidates every accumulated row from the
// prior one. Keep the reset and its replacement snapshot atomic.
pendingProjectionTurns.removeAll()
shouldResetProjection = true
}
generationByConversation[checkpointKey] = page.conversationGeneration
var contiguous = highWaterByConversation[checkpointKey] ?? 0
let contiguousPage = KernelJournalReplay.contiguousTurns(
from: page.turns,
after: contiguous
)
for turn in contiguousPage {
guard isCurrent(lease) else { return false }
pendingProjectionTurns.append(turn)
contiguous = turn.turnSeq
highWaterByConversation[checkpointKey] = contiguous
}
let firstUnapplied = page.turns
.filter { $0.turnSeq > contiguous }
.min { $0.turnSeq < $1.turnSeq }
if let firstUnapplied {
log(
"KernelTurnProjection: journal gap detected "
+ "(conversation=\(conversationId), expected=\(contiguous + 1), got=\(firstUnapplied.turnSeq))"
)
shouldContinue = false
} else if contiguousPage.isEmpty || contiguous >= page.highWaterTurnSeq {
shouldContinue = false
} else if !shouldContinue {
// Leave the checkpoint at the last contiguous sequence. A later
// wakeup or explicit refresh requests the missing range again.
break
}
} catch {
if isCurrent(lease) {
log("KernelTurnProjection: journal replay failed (code=journal_range_fetch_failed)")
}
refreshSucceeded = false
shouldContinue = false
}
}
} while isCurrent(lease) && refreshRequestedSurfaceEpochs[surfaceKey] == lease.epoch
guard isCurrent(lease) else { return false }
if !refreshSucceeded, !publishPartialResults {
return false
}
if shouldResetProjection {
host?.resetJournalProjection(surface: surface)
}
host?.projectJournalTurns(pendingProjectionTurns)
return refreshSucceeded
}
@discardableResult
func reload(surface: AgentSurfaceReference) async -> Bool {
guard let lease = captureOwnerLease(), isCurrent(lease) else { return false }
let surfaceKey = surface.key
if refreshingSurfaceEpochs[surfaceKey] == lease.epoch {
refreshRequestedSurfaceEpochs[surfaceKey] = lease.epoch
return false
}
let previousConversationId = conversationBySurface.removeValue(forKey: surfaceKey)
let previousCheckpointKey = previousConversationId.map {
checkpointKeyFor(conversationId: $0, surface: surface)
}
let previousHighWater = previousCheckpointKey.flatMap { highWaterByConversation[$0] }
let previousGeneration = previousCheckpointKey.flatMap { generationByConversation[$0] }
if let conversationId = previousConversationId {
let key = checkpointKeyFor(conversationId: conversationId, surface: surface)
highWaterByConversation.removeValue(forKey: key)
generationByConversation.removeValue(forKey: key)
}
guard isCurrent(lease) else { return false }
// The refresh builds a complete replacement snapshot and publishes it
// atomically. Keep the current projection visible if fetching fails.
let reloaded = await refresh(
surface: surface,
lease: lease,
publishPartialResults: false
)
guard !reloaded, isCurrent(lease) else { return reloaded }
if let failedConversationId = conversationBySurface.removeValue(forKey: surfaceKey) {
let failedKey = checkpointKeyFor(conversationId: failedConversationId, surface: surface)
highWaterByConversation.removeValue(forKey: failedKey)
generationByConversation.removeValue(forKey: failedKey)
}
if let previousConversationId, let previousCheckpointKey {
conversationBySurface[surfaceKey] = previousConversationId
if let previousHighWater {
highWaterByConversation[previousCheckpointKey] = previousHighWater
}
if let previousGeneration {
generationByConversation[previousCheckpointKey] = previousGeneration
}
}
return false
}
@discardableResult
func recordTurn(
surface: AgentSurfaceReference,
message: ChatMessage,
origin: String,
status: KernelJournalTurnStatus,
continuityKey: String? = nil,
appId: String? = nil,
sessionId: String? = nil,
messageSource: String? = nil,
ownerID: String? = nil
) async -> KernelJournalTurn? {
guard let lease = captureOwnerLease(ownerID: ownerID), let host else { return nil }
guard await host.ensureBridgeStartedForKernel(), isCurrent(lease), let client else { return nil }
do {
let turn = try await client.recordJournalTurn(
surface: surface,
ownerID: lease.ownerID,
turn: message.journalWrite(
origin: origin,
status: status,
continuityKey: continuityKey,
appId: appId,
sessionId: sessionId,
messageSource: messageSource
)
)
guard isCurrent(lease) else { return nil }
_ = await refresh(surface: surface, lease: lease, publishPartialResults: true)
guard isCurrent(lease) else { return nil }
return turn
} catch {
log("KernelTurnProjection: journal record failed (code=journal_record_failed)")
return nil
}
}
@discardableResult
func updateTurn(
surface: AgentSurfaceReference,
message: ChatMessage,
status: KernelJournalTurnStatus? = nil,
terminalReason: String? = nil,
answerTextCompleted: Bool? = nil,
ownerID: String? = nil
) async -> KernelJournalTurn? {
guard let lease = captureOwnerLease(ownerID: ownerID), let host else { return nil }
guard await host.ensureBridgeStartedForKernel(), isCurrent(lease), let client else { return nil }
do {
let turn = try await client.updateJournalTurn(
surface: surface,
ownerID: lease.ownerID,
update: message.journalUpdate(
status: status, terminalReason: terminalReason, answerTextCompleted: answerTextCompleted)
)
guard isCurrent(lease) else { return nil }
_ = await refresh(surface: surface, lease: lease, publishPartialResults: true)
guard isCurrent(lease) else { return nil }
return turn
} catch {
log("KernelTurnProjection: journal update failed (code=journal_update_failed)")
return nil
}
}
/// Adds one stable-ID evidence item to an already-admitted user row. The
/// runtime atomically merges the object into the owned row, preserving
/// unrelated metadata even when a streaming update races this late OCR.
@discardableResult
func appendEvidence(
surface: AgentSurfaceReference,
turnID: String,
evidence: ConversationEvidence,
ownerID: String? = nil
) async -> KernelJournalTurn? {
guard !turnID.isEmpty,
let lease = captureOwnerLease(ownerID: ownerID),
let host
else { return nil }
guard await host.ensureBridgeStartedForKernel(), isCurrent(lease), let client else { return nil }
do {
guard let evidenceData = try? JSONEncoder().encode(evidence),
let evidenceJSON = String(data: evidenceData, encoding: .utf8)
else { return nil }
let updated = try await client.updateJournalTurn(
surface: surface,
ownerID: lease.ownerID,
update: KernelJournalTurnUpdate(
turnId: turnID,
status: nil,
content: nil,
contentBlocksJSON: nil,
appendContentBlocksJSON: nil,
resourcesJSON: nil,
appendResourcesJSON: nil,
appendEvidenceJSON: evidenceJSON,
metadataJSON: nil,
terminalRevision: false))
guard isCurrent(lease) else { return nil }
_ = await refresh(surface: surface, lease: lease, publishPartialResults: true)
guard isCurrent(lease) else { return nil }
return updated
} catch {
if isCurrent(lease) {
log("KernelTurnProjection: journal evidence append failed (code=journal_evidence_append_failed)")
}
return nil
}
}
@discardableResult
func terminalizeTurn(
surface: AgentSurfaceReference,
turnId: String,
message: ChatMessage?,
producingRunId: String,
producingAttemptId: String,
disposition: KernelJournalTerminalDisposition,
acceptedContent: String? = nil,
acceptedResources: [ChatResource]? = nil,
ownerID: String
) async -> KernelJournalTurn? {
guard let lease = captureOwnerLease(ownerID: ownerID), let host else { return nil }
guard await host.ensureBridgeStartedForKernel(), isCurrent(lease), let client else { return nil }
let acceptedText = Self.acceptedTerminalContent(message: message, acceptedContent: acceptedContent)
let acceptedBlocks = Self.acceptedTerminalContentBlocks(message: message, acceptedContent: acceptedContent)
let terminalization = KernelJournalTurnTerminalization(
turnId: turnId,
producingRunId: producingRunId,
producingAttemptId: producingAttemptId,
disposition: disposition,
content: disposition == .accept ? acceptedText : nil,
contentBlocksJSON: disposition == .accept ? ChatContentBlockCodec.encode(acceptedBlocks) : nil,
resourcesJSON: disposition == .accept
? message.flatMap { ChatResource.encodeResourcesForPersistence($0.displayResources) }
?? acceptedResources.flatMap { resources in
resources.isEmpty ? nil : ChatResource.encodeResourcesForPersistence(resources)
}
: nil
)
do {
let turn = try await client.terminalizeJournalTurn(
surface: surface,
ownerID: lease.ownerID,
terminalization: terminalization
)
guard isCurrent(lease) else { return nil }
_ = await refresh(surface: surface, lease: lease, publishPartialResults: true)
return isCurrent(lease) ? turn : nil
} catch {
log("KernelTurnProjection: journal terminalization failed (code=journal_terminalize_failed)")
return nil
}
}
@discardableResult
func repairNonterminalTurns(
surface: AgentSurfaceReference,
turnIDs: [String],
ownerID: String
) async -> Int {
guard !turnIDs.isEmpty,
let lease = captureOwnerLease(ownerID: ownerID),
let host
else { return 0 }
guard await host.ensureBridgeStartedForKernel(), isCurrent(lease), let client else { return 0 }
do {
let repaired = try await client.repairJournalTurns(
surface: surface,
ownerID: lease.ownerID,
turnIDs: turnIDs
)
guard isCurrent(lease) else { return 0 }
_ = await refresh(surface: surface, lease: lease, publishPartialResults: true)
return isCurrent(lease) ? repaired.count : 0
} catch {
log("KernelTurnProjection: journal repair failed (code=journal_repair_failed)")
return 0
}
}
/// The query result is the authoritative final material. The streaming row is
/// an optimistic projection and can lag its terminal callback; use it only
/// when the final result intentionally contains no text.
static func acceptedTerminalContent(message: ChatMessage?, acceptedContent: String?) -> String? {
if let acceptedContent, !acceptedContent.isEmpty { return acceptedContent }
return message.flatMap { $0.text.isEmpty ? nil : $0.text }
}
static func acceptedTerminalContentBlocks(
message: ChatMessage?,
acceptedContent: String?
) -> [ChatContentBlock] {
guard let acceptedContent, !acceptedContent.isEmpty else { return message?.contentBlocks ?? [] }
let nonTextBlocks =
message?.contentBlocks.filter {
if case .text = $0 { return false }
return true
} ?? []
let messageID = message?.id ?? "terminal"
return [.text(id: "\(messageID):terminal", text: acceptedContent)] + nonTextBlocks
}
/// Terminalize an existing turn without sourcing payload from the current UI
/// projection. Stopped turns can legitimately have no visible placeholder;
/// lifecycle durability must not depend on one being present.
@discardableResult
func updateTurnStatus(
surface: AgentSurfaceReference,
turnId: String,
status: KernelJournalTurnStatus,
ownerID: String? = nil
) async -> KernelJournalTurn? {
guard let lease = captureOwnerLease(ownerID: ownerID), let host else { return nil }
guard await host.ensureBridgeStartedForKernel(), isCurrent(lease), let client else { return nil }
do {
let turn = try await client.updateJournalTurn(
surface: surface,
ownerID: lease.ownerID,
update: .statusOnly(turnId: turnId, status: status)
)
guard isCurrent(lease) else { return nil }
_ = await refresh(surface: surface, lease: lease, publishPartialResults: true)
guard isCurrent(lease) else { return nil }
return turn
} catch {
log("KernelTurnProjection: journal status update failed (code=journal_status_update_failed)")
return nil
}
}
/// Revises a row this client sealed `.completed` before delivery resolved,
/// downgrading it to `.failed` with its truncation cause when the answer
/// never reached the user (#12743). Payload-free by construction: the row's
/// content, blocks, resources, and existing metadata (model attribution,
/// continuity) are preserved; the kernel merges the terminal reason into
/// the row's metadata rather than replacing it.
@discardableResult
func reviseSealedTerminalTurn(
surface: AgentSurfaceReference,
turnId: String,
terminalReason: String,
answerTextCompleted: Bool = false,
ownerID: String? = nil
) async -> KernelJournalTurn? {
guard let lease = captureOwnerLease(ownerID: ownerID), let host else { return nil }
guard await host.ensureBridgeStartedForKernel(), isCurrent(lease), let client else { return nil }
do {
let turn = try await client.updateJournalTurn(
surface: surface,
ownerID: lease.ownerID,
update: .sealedTerminalRevision(
turnId: turnId,
terminalReason: terminalReason,
answerTextCompleted: answerTextCompleted)
)
guard isCurrent(lease) else { return nil }
_ = await refresh(surface: surface, lease: lease, publishPartialResults: true)
guard isCurrent(lease) else { return nil }
return turn
} catch {
log("KernelTurnProjection: journal terminal revision failed (code=journal_terminal_revision_failed)")
return nil
}
}
/// Convenience for a logical exchange. IDs derive from the opaque continuity
/// key, so retries cannot create a second user/assistant row.
@discardableResult
func recordExchange(
surface: AgentSurfaceReference,
userText: String,
assistantText: String,
origin: String,
continuityKey: String,
assistantContentBlocks: [ChatContentBlock] = [],
resources: [ChatResource] = [],
assistantStatus: KernelJournalTurnStatus = .completed,
terminalReason: String? = nil,
answerTextCompleted: Bool? = nil,
userScreenContext: String? = nil,
userEvidence: [ConversationEvidence] = [],
ownerID: String? = nil
) async -> Bool {
let baseDate = Date()
var writes: [KernelJournalTurnWrite] = []
if !userText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
var user = ChatMessage(
id: Self.stableTurnID(continuityKey: continuityKey, role: "user"),
clientTurnId: continuityKey,
text: userText,
createdAt: baseDate,
sender: .user
)
if !userEvidence.isEmpty || !(userScreenContext?.isEmpty ?? true) {
user.metadata = MessageMetadata(
screenContext: userScreenContext,
evidence: userEvidence)
}
writes.append(
user.journalWrite(
origin: origin,
status: .completed,
continuityKey: continuityKey,
messageSource: origin
))
}
if !assistantText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|| !assistantContentBlocks.isEmpty || !resources.isEmpty
{
let assistant = ChatMessage(
id: Self.stableTurnID(continuityKey: continuityKey, role: "assistant"),
clientTurnId: continuityKey,
text: assistantText.isEmpty ? "Done." : assistantText,
createdAt: baseDate.addingTimeInterval(0.001),
sender: .ai,
contentBlocks: assistantContentBlocks,
resources: resources
)
writes.append(
assistant.journalWrite(
origin: origin,
status: assistantStatus,
continuityKey: continuityKey,
messageSource: origin,
terminalReason: terminalReason,
answerTextCompleted: answerTextCompleted
))
}
return await recordExchange(
surface: surface,
writes: writes,
ownerID: ownerID
) != nil
}
/// Admit prebuilt visible turns under one journal transaction. This is the
/// canonical typed/task-chat entry point because it preserves caller-owned
/// message IDs, attachments, and a deliberately empty streaming placeholder.
@discardableResult
func recordExchange(
surface: AgentSurfaceReference,
turns: [ExchangeTurn],
origin: String,
continuityKey: String,
appId: String? = nil,
sessionId: String? = nil,
messageSource: String,
ownerID: String? = nil
) async -> [KernelJournalTurn]? {
let writes = turns.map { entry in
entry.message.journalWrite(
origin: origin,
status: entry.status,
continuityKey: continuityKey,
appId: appId,
sessionId: sessionId,
messageSource: messageSource
)
}
return await recordExchange(surface: surface, writes: writes, ownerID: ownerID)
}
@discardableResult
private func recordExchange(
surface: AgentSurfaceReference,
writes: [KernelJournalTurnWrite],
ownerID: String?
) async -> [KernelJournalTurn]? {
guard !writes.isEmpty, writes.count <= 2 else { return nil }
let roles = writes.map(\.role)
guard
roles == ["user"] || roles == ["assistant"]
|| roles == ["user", "assistant"]
else { return nil }
guard let lease = captureOwnerLease(ownerID: ownerID), let host else { return nil }
guard await host.ensureBridgeStartedForKernel(), isCurrent(lease), let client else { return nil }
do {
let result = try await client.recordJournalExchange(
surface: surface,
ownerID: lease.ownerID,
turns: writes
)
guard isCurrent(lease), result.operation == "record_exchange" else { return nil }
let expectedTurnIDs = Set(writes.map(\.turnId))
guard
result.turns.count == writes.count,
Set(result.turns.map(\.turnId)) == expectedTurnIDs,
!result.conversationId.isEmpty
else {
log("KernelTurnProjection: journal exchange returned an invalid receipt")
return nil
}
applyAcceptedExchange(result, surface: surface, lease: lease)
return isCurrent(lease) ? result.turns : nil
} catch {
if isCurrent(lease) {
log("KernelTurnProjection: journal exchange failed (code=journal_exchange_failed)")
}
return nil
}
}
/// Append one deterministic terminal block to the assistant turn that
/// produced the matching agent spawn. The bounded retry closes the race where
/// a fast child finishes before the parent spawn projection reaches SQLite.
@discardableResult
func appendAgentCompletion(
surface: AgentSurfaceReference,
ownerID: String? = nil,
pillID: UUID,
sessionID: String?,
runID: String?,
title: String,
promptSnippet: String,
output: String,
status: String,
resources: [ChatResource] = [],
maxLookupAttempts: Int = 8,
retryDelayNanoseconds: UInt64 = 150_000_000
) async -> KernelJournalTurn? {
guard let lease = captureOwnerLease(ownerID: ownerID), let host else { return nil }
guard await host.ensureBridgeStartedForKernel(), isCurrent(lease), let client else { return nil }
let attempts = max(1, min(maxLookupAttempts, 8))
for attempt in 0..<attempts {
guard isCurrent(lease) else { return nil }
do {
let revisions = try await journalRevisions(
client: client,
surface: surface,
lease: lease
)
guard isCurrent(lease) else { return nil }
if let mutation = KernelAgentLifecycleMutation.completion(
in: revisions,
pillID: pillID,
sessionID: sessionID,
runID: runID,
title: title,
promptSnippet: promptSnippet,
output: output,
status: status,
resources: resources
) {
let turn = try await client.updateJournalTurn(
surface: surface,
ownerID: lease.ownerID,
update: KernelAgentLifecycleMutation.atomicAppendUpdate(mutation)
)
guard isCurrent(lease) else { return nil }
_ = await refresh(surface: surface, lease: lease, publishPartialResults: true)
guard isCurrent(lease) else { return nil }
return turn
}
} catch {
if isCurrent(lease) {
log("KernelTurnProjection: agent completion update failed (code=journal_agent_completion_failed)")
}
}
if attempt + 1 < attempts, retryDelayNanoseconds > 0 {
try? await Task.sleep(nanoseconds: retryDelayNanoseconds)
guard isCurrent(lease) else { return nil }
}
}
log("KernelTurnProjection: matching agent spawn unavailable (code=journal_agent_spawn_missing)")
return nil
}
func clear(
surface: AgentSurfaceReference,
ownerID: String? = nil,
requiresModelReadiness: Bool = true,
deleteBackend: Bool = true
) async -> Bool {
guard let lease = captureOwnerLease(ownerID: ownerID), let host else { return false }
let kernelReady =
if !requiresModelReadiness {
client != nil
} else if let kernelReadyOperation {
await kernelReadyOperation()
} else {
await host.ensureBridgeStartedForKernel()
}
guard kernelReady, isCurrent(lease), let client else { return false }
do {
let surfaceKey = surface.key
let checkpointKey = conversationBySurface[surfaceKey].map {
checkpointKeyFor(conversationId: $0, surface: surface)
}
var expectedGeneration = checkpointKey.flatMap { generationByConversation[$0] }
if expectedGeneration.map({ $0 <= 0 }) ?? true {
let page: AgentRuntimeProcess.JournalOperationResult
if let journalListOperation {
page = try await journalListOperation(client, surface, lease.ownerID, 0, 1)
} else if requiresModelReadiness {
page = try await client.listJournalTurns(
surface: surface,
ownerID: lease.ownerID,
afterTurnSeq: 0,
limit: 1
)
} else {
page = try await client.listJournalTurnsForControl(
surface: surface,
ownerID: lease.ownerID,
afterTurnSeq: 0,
limit: 1
)
}
guard isCurrent(lease),
!page.conversationId.isEmpty,
page.conversationGeneration > 0
else { return false }
let bootstrapCheckpointKey = checkpointKeyFor(
conversationId: page.conversationId,
surface: surface
)
conversationBySurface[surfaceKey] = page.conversationId
generationByConversation[bootstrapCheckpointKey] = page.conversationGeneration
expectedGeneration = page.conversationGeneration
}
guard isCurrent(lease), let expectedGeneration, expectedGeneration > 0 else { return false }
if let journalClearOperation {
_ = try await journalClearOperation(
client,
surface,
lease.ownerID,
expectedGeneration,
deleteBackend
)
} else if requiresModelReadiness {
_ = try await client.clearJournalTurns(
surface: surface,
ownerID: lease.ownerID,
expectedGeneration: expectedGeneration,
deleteBackend: deleteBackend
)
} else {
_ = try await client.clearJournalTurnsForControl(
surface: surface,
ownerID: lease.ownerID,
expectedGeneration: expectedGeneration,
deleteBackend: deleteBackend
)
}
guard isCurrent(lease) else { return false }
for key in highWaterByConversation.keys where key.hasSuffix("|\(surface.key)") {
highWaterByConversation.removeValue(forKey: key)
generationByConversation.removeValue(forKey: key)
}
conversationBySurface.removeValue(forKey: surfaceKey)
host.resetJournalProjection(surface: surface)
return true
} catch {