forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKernelTurnJournal.swift
More file actions
487 lines (462 loc) · 17.3 KB
/
Copy pathKernelTurnJournal.swift
File metadata and controls
487 lines (462 loc) · 17.3 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
import Foundation
enum KernelJournalTurnStatus: String, Sendable {
case pending
case streaming
case completed
case failed
}
/// Sendable wire projection of one kernel-owned journal row. Structured UI
/// payloads stay encoded while crossing the runtime actor boundary and are
/// decoded only on MainActor.
struct KernelJournalTurn: Sendable, Equatable {
let conversationId: String
let turnId: String
let turnSeq: Int
let conversationGeneration: Int
let generationBaseTurnSeq: Int
let producerId: String
let payloadHash: String
let role: String
let surfaceKind: String
let externalRefKind: String
let externalRefId: String
let content: String
let origin: String
let status: KernelJournalTurnStatus
let contentBlocksJSON: String
let resourcesJSON: String
let producingRunId: String?
let producingAttemptId: String?
let remoteId: String?
let metadataJSON: String
let createdAtMs: Int
let updatedAtMs: Int
let completedAtMs: Int?
init?(
dictionary: [String: Any],
surfaceFallback: AgentSurfaceReference? = nil,
conversationGenerationFallback: Int = 1,
generationBaseTurnSeqFallback: Int = 0
) {
guard
let turnId = dictionary["turnId"] as? String,
!turnId.isEmpty,
let role = dictionary["role"] as? String,
let content = dictionary["content"] as? String,
let rawStatus = dictionary["status"] as? String,
let status = KernelJournalTurnStatus(rawValue: rawStatus)
else { return nil }
self.conversationId = dictionary["conversationId"] as? String ?? ""
self.turnId = turnId
self.turnSeq = Self.int(dictionary["turnSeq"]) ?? 0
self.conversationGeneration =
Self.int(dictionary["conversationGeneration"])
?? conversationGenerationFallback
self.generationBaseTurnSeq =
Self.int(dictionary["generationBaseTurnSeq"])
?? generationBaseTurnSeqFallback
self.producerId = dictionary["producerId"] as? String ?? ""
self.payloadHash = dictionary["payloadHash"] as? String ?? ""
self.role = role
self.surfaceKind = dictionary["surfaceKind"] as? String ?? surfaceFallback?.surfaceKind ?? ""
self.externalRefKind =
dictionary["externalRefKind"] as? String
?? surfaceFallback?.externalRefKind ?? ""
self.externalRefId =
dictionary["externalRefId"] as? String
?? surfaceFallback?.externalRefId ?? ""
self.content = content
self.origin = dictionary["origin"] as? String ?? "legacy"
self.status = status
self.contentBlocksJSON = Self.jsonArrayString(dictionary["contentBlocks"])
self.resourcesJSON = Self.jsonArrayString(dictionary["resources"])
self.producingRunId = dictionary["producingRunId"] as? String
self.producingAttemptId = dictionary["producingAttemptId"] as? String
self.remoteId = dictionary["remoteId"] as? String
self.metadataJSON = dictionary["metadataJson"] as? String ?? "{}"
self.createdAtMs = Self.int(dictionary["createdAtMs"]) ?? 0
self.updatedAtMs = Self.int(dictionary["updatedAtMs"]) ?? self.createdAtMs
self.completedAtMs = Self.int(dictionary["completedAtMs"])
}
private static func int(_ value: Any?) -> Int? {
if let value = value as? Int { return value }
if let value = value as? NSNumber { return value.intValue }
return nil
}
private static func jsonArrayString(_ value: Any?) -> String {
guard let array = value as? [Any],
JSONSerialization.isValidJSONObject(array),
let data = try? JSONSerialization.data(withJSONObject: array),
let encoded = String(data: data, encoding: .utf8)
else { return "[]" }
return encoded
}
}
/// Deterministic replay gate shared by every Swift journal projection. Runtime
/// notifications can be duplicated or reordered; only a contiguous range may
/// advance a projection checkpoint.
enum KernelJournalReplay {
static func contiguousTurns(
from candidates: [KernelJournalTurn],
after checkpoint: Int
) -> [KernelJournalTurn] {
var expected = checkpoint + 1
var accepted: [KernelJournalTurn] = []
for turn in candidates.sorted(by: {
$0.turnSeq == $1.turnSeq ? $0.turnId < $1.turnId : $0.turnSeq < $1.turnSeq
}) where turn.turnSeq > checkpoint {
guard turn.turnSeq == expected else { break }
accepted.append(turn)
expected += 1
}
return accepted
}
}
struct KernelJournalTurnWrite: Sendable {
let turnId: String
let role: String
let origin: String
let status: KernelJournalTurnStatus
let content: String
let contentBlocksJSON: String
let resourcesJSON: String
let metadataJSON: String
let createdAtMs: Int
var dictionary: [String: Any] {
[
"turnId": turnId,
"role": role,
"origin": origin,
"status": status.rawValue,
"content": content,
"contentBlocks": Self.jsonArray(contentBlocksJSON),
"resources": Self.jsonArray(resourcesJSON),
"metadataJson": metadataJSON,
"createdAtMs": createdAtMs,
]
}
static func jsonArray(_ raw: String) -> [Any] {
guard let data = raw.data(using: .utf8),
let value = try? JSONSerialization.jsonObject(with: data) as? [Any]
else { return [] }
return value
}
}
struct KernelJournalTurnUpdate: Sendable {
let turnId: String
let status: KernelJournalTurnStatus?
let content: String?
let contentBlocksJSON: String?
let appendContentBlocksJSON: String?
let resourcesJSON: String?
let appendResourcesJSON: String?
/// One evidence object to atomically append to the row's `evidence` metadata
/// namespace. The runtime owns merge/idempotency; Swift never replaces the
/// full metadata blob for a late OCR result.
let appendEvidenceJSON: String?
let metadataJSON: String?
/// Narrow authority flag for revising an optimistically sealed terminal row:
/// the same desktop client that sealed a row `.completed` before delivery
/// resolved may downgrade it to `.failed` when the answer never reached the
/// user (#12743). The kernel accepts this only as a payload-free downgrade
/// and merges — never replaces — the row's existing metadata.
let terminalRevision: Bool
/// A terminal lifecycle update that deliberately carries no response
/// payload. This is used after stop/supersession when the visible projection
/// may already have removed its empty placeholder: the existing journal row
/// still becomes terminal, but a late adapter result cannot be copied into it.
static func statusOnly(
turnId: String,
status: KernelJournalTurnStatus
) -> KernelJournalTurnUpdate {
KernelJournalTurnUpdate(
turnId: turnId,
status: status,
content: nil,
contentBlocksJSON: nil,
appendContentBlocksJSON: nil,
resourcesJSON: nil,
appendResourcesJSON: nil,
appendEvidenceJSON: nil,
metadataJSON: nil,
terminalRevision: false
)
}
/// Downgrades an optimistically sealed `.completed` row to `.failed` with
/// its truncation cause, carrying no payload: content, content blocks,
/// resources, and existing metadata (model attribution, continuity) stay
/// untouched while `terminalReason` (and, when the answer text completed
/// before delivery was cut, `answerTextCompleted`) merges into the row's
/// metadata.
static func sealedTerminalRevision(
turnId: String,
terminalReason: String,
answerTextCompleted: Bool = false
) -> KernelJournalTurnUpdate {
var revisionMetadata: [String: Any] = ["terminalReason": terminalReason]
if answerTextCompleted {
revisionMetadata["answerTextCompleted"] = true
}
let encodedReason: String
if let data = try? JSONSerialization.data(withJSONObject: revisionMetadata),
let encoded = String(data: data, encoding: .utf8)
{
encodedReason = encoded
} else {
encodedReason = "{}"
}
return KernelJournalTurnUpdate(
turnId: turnId,
status: .failed,
content: nil,
contentBlocksJSON: nil,
appendContentBlocksJSON: nil,
resourcesJSON: nil,
appendResourcesJSON: nil,
appendEvidenceJSON: nil,
metadataJSON: encodedReason,
terminalRevision: true
)
}
var dictionary: [String: Any] {
var value: [String: Any] = ["turnId": turnId]
if let status { value["status"] = status.rawValue }
if let content { value["content"] = content }
if let contentBlocksJSON {
value["replaceContentBlocks"] = KernelJournalTurnWrite.jsonArray(contentBlocksJSON)
}
if let appendContentBlocksJSON {
value["appendContentBlocks"] = KernelJournalTurnWrite.jsonArray(appendContentBlocksJSON)
}
if let resourcesJSON {
value["replaceResources"] = KernelJournalTurnWrite.jsonArray(resourcesJSON)
}
if let appendResourcesJSON {
value["appendResources"] = KernelJournalTurnWrite.jsonArray(appendResourcesJSON)
}
if let appendEvidenceJSON {
// The wire contract mirrors appendResources: one late evidence item is
// carried as a one-element array so the kernel can merge each item by
// stable ID in one transaction.
value["appendEvidence"] = [Self.jsonObject(appendEvidenceJSON)]
}
if let metadataJSON { value["metadataJson"] = metadataJSON }
if terminalRevision { value["terminalRevision"] = true }
return value
}
private static func jsonObject(_ raw: String) -> [String: Any] {
guard let data = raw.data(using: .utf8),
let value = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
else { return [:] }
return value
}
}
enum KernelJournalTerminalDisposition: String, Sendable {
case accept
case discard
}
struct KernelJournalTurnTerminalization: Sendable {
let turnId: String
let producingRunId: String
let producingAttemptId: String
let disposition: KernelJournalTerminalDisposition
let content: String?
let contentBlocksJSON: String?
let resourcesJSON: String?
var dictionary: [String: Any] {
var value: [String: Any] = [
"turnId": turnId,
"producingRunId": producingRunId,
"producingAttemptId": producingAttemptId,
"disposition": disposition.rawValue,
]
if let content { value["content"] = content }
if let contentBlocksJSON {
value["replaceContentBlocks"] = KernelJournalTurnWrite.jsonArray(contentBlocksJSON)
}
if let resourcesJSON {
value["replaceResources"] = KernelJournalTurnWrite.jsonArray(resourcesJSON)
}
return value
}
}
struct KernelJournalRemoteTurn: Sendable {
let remoteId: String
let canonicalTurnId: String?
let role: String
let content: String
let contentBlocksJSON: String
let resourcesJSON: String
let metadataJSON: String
let createdAtMs: Int
var dictionary: [String: Any] {
var value: [String: Any] = [
"remoteId": remoteId,
"role": role,
"content": content,
"contentBlocks": KernelJournalTurnWrite.jsonArray(contentBlocksJSON),
"resources": KernelJournalTurnWrite.jsonArray(resourcesJSON),
"metadataJson": Self.normalizedMetadataObject(metadataJSON),
"createdAtMs": createdAtMs,
]
if let canonicalTurnId { value["canonicalTurnId"] = canonicalTurnId }
return value
}
private static func normalizedMetadataObject(_ raw: String) -> String {
guard let data = raw.data(using: .utf8),
let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
JSONSerialization.isValidJSONObject(object),
let normalized = try? JSONSerialization.data(withJSONObject: object),
let encoded = String(data: normalized, encoding: .utf8)
else { return "{}" }
return encoded
}
}
@MainActor
extension KernelJournalTurn {
func chatMessage() -> ChatMessage {
let metadata = Self.metadataObject(metadataJSON)
let continuityKey =
(metadata["continuityKey"] as? String)
?? (metadata["idempotencyKey"] as? String)
let owner: ChatTurnOwner?
switch origin {
case "realtime_voice": owner = .floatingVoice
case "floating_chat": owner = .floatingDefault
case "task_chat", "workstream": owner = .taskChat(externalRefId)
default: owner = .mainChat
}
var message = ChatMessage(
id: turnId,
clientTurnId: continuityKey,
text: content,
createdAt: Date(timeIntervalSince1970: TimeInterval(createdAtMs) / 1_000),
sender: role == "user" ? .user : .ai,
isStreaming: status == .pending || status == .streaming,
isSynced: remoteId != nil,
contentBlocks: ChatContentBlockCodec.mergingCitationBackup(
ChatContentBlockCodec.decode(contentBlocksJSON) ?? [],
backup: ChatContentBlockCodec.decodeFromMessageMetadata(metadataJSON)
),
notificationContext: metadata["notificationContext"] as? String,
resources: ChatResource.hydrateFileStates(
ChatResource.decodeResourcesFromPersistence(resourcesJSON)
),
turnOwner: owner,
journalStatus: status,
hidesEmptyStreamingPlaceholder: metadata["hiddenUntilOutput"] as? Bool ?? false
)
if message.sender == .user {
let evidence = ConversationEvidenceMetadataCodec.envelope(from: metadataJSON)?.items ?? []
if !evidence.isEmpty || metadata["screen_context"] as? String != nil {
message.metadata = MessageMetadata(
screenContext: metadata["screen_context"] as? String,
evidence: evidence
)
}
}
// Persisted served-model attribution: lets a journaled voice turn (or a
// restored one) show the Response Context Model row that in-memory
// metadata would otherwise lose.
if message.sender == .ai, let models = metadata["modelsUsed"] as? [String], !models.isEmpty {
message.metadata = MessageMetadata(
adapterId: origin == "realtime_voice" ? "realtime" : "",
modelsUsed: models
)
}
return message
}
private static func metadataObject(_ raw: String) -> [String: Any] {
guard let data = raw.data(using: .utf8),
let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
else { return [:] }
return object
}
}
@MainActor
extension ChatMessage {
func journalWrite(
origin: String,
status: KernelJournalTurnStatus,
continuityKey: String? = nil,
appId: String? = nil,
sessionId: String? = nil,
messageSource: String? = nil,
terminalReason: String? = nil,
answerTextCompleted: Bool? = nil
) -> KernelJournalTurnWrite {
var metadata: [String: Any] = [:]
if let continuityKey, !continuityKey.isEmpty { metadata["continuityKey"] = continuityKey }
if let models = self.metadata?.modelsUsed, !models.isEmpty { metadata["modelsUsed"] = models }
if let notificationContext { metadata["notificationContext"] = notificationContext }
if let screenContext = self.metadata?.screenContext, !screenContext.isEmpty {
metadata["screen_context"] = String(screenContext.prefix(1_200))
}
if let evidence = self.metadata?.evidence, !evidence.isEmpty {
let envelope = ConversationEvidenceEnvelope(items: evidence)
if let encoded = ConversationEvidenceMetadataCodec.encodeEnvelope(envelope) {
metadata[ConversationEvidenceMetadataCodec.metadataKey] = encoded
}
}
// These rollback-compatible fields are consumed only by the kernel outbox
// renderer for the existing /v2/desktop/messages POST shape.
if let appId { metadata["appId"] = appId }
if let sessionId { metadata["sessionId"] = sessionId }
if let messageSource { metadata["messageSource"] = messageSource }
if let terminalReason { metadata["terminalReason"] = terminalReason }
if answerTextCompleted == true { metadata["answerTextCompleted"] = true }
let metadataJSON: String
let encodedMetadata: String
if let data = try? JSONSerialization.data(withJSONObject: metadata),
let encoded = String(data: data, encoding: .utf8)
{
encodedMetadata = encoded
} else {
encodedMetadata = "{}"
}
metadataJSON =
ChatContentBlockCodec.mergeIntoMessageMetadata(
encodedMetadata,
contentBlocks: ChatContentBlockCodec.citationBlocks(in: contentBlocks)
) ?? encodedMetadata
return KernelJournalTurnWrite(
turnId: id,
role: sender == .user ? "user" : "assistant",
origin: origin,
status: status,
content: text,
contentBlocksJSON: ChatContentBlockCodec.encode(contentBlocks) ?? "[]",
resourcesJSON: ChatResource.encodeResourcesForPersistence(displayResources) ?? "[]",
metadataJSON: metadataJSON,
createdAtMs: Int(createdAt.timeIntervalSince1970 * 1_000)
)
}
func journalUpdate(
status: KernelJournalTurnStatus? = nil,
terminalReason: String? = nil,
answerTextCompleted: Bool? = nil
) -> KernelJournalTurnUpdate {
var updateMetadata: [String: Any] = [:]
if let terminalReason { updateMetadata["terminalReason"] = terminalReason }
if answerTextCompleted == true { updateMetadata["answerTextCompleted"] = true }
var metadataJSON: String?
if !updateMetadata.isEmpty,
let data = try? JSONSerialization.data(withJSONObject: updateMetadata),
let encoded = String(data: data, encoding: .utf8)
{
metadataJSON = encoded
}
return KernelJournalTurnUpdate(
turnId: id,
status: status,
content: text,
contentBlocksJSON: ChatContentBlockCodec.encode(contentBlocks) ?? "[]",
appendContentBlocksJSON: nil,
resourcesJSON: ChatResource.encodeResourcesForPersistence(displayResources) ?? "[]",
appendResourcesJSON: nil,
appendEvidenceJSON: nil,
metadataJSON: metadataJSON,
terminalRevision: false
)
}
}