forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAgentRuntimeProcess+ChatFirstJournal.swift
More file actions
582 lines (562 loc) · 21.6 KB
/
Copy pathAgentRuntimeProcess+ChatFirstJournal.swift
File metadata and controls
582 lines (562 loc) · 21.6 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
import Foundation
/// Capability-scoped main-Chat journal operations. The kernel remains the sole
/// journal writer; this extension validates the Swift boundary and projects the
/// kernel receipts through the existing runtime actor.
extension AgentRuntimeProcess {
/// Shape-only receipt from the local/offline E2E path that dispatches the
/// actual Chat-first block tool through the normal authorized-tool channel.
struct ChatFirstHarnessExecutorReceipt: Equatable, Sendable {
let executorInvoked: Bool
let validated: Bool
let journalBlockRendered: Bool
}
/// Local/offline-only E2E seam for the real Swift Chat-first block executor.
/// The caller supplies an already-resolved main-Chat session and immutable
/// server projection; Node derives and rechecks that projection from the
/// mounted session rather than accepting it from this message.
func invokeChatFirstFixtureTaskCard(
clientId: String,
ownerID: String,
sessionID: String,
producingTurnID: String,
controlGeneration: Int,
authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot
) async throws -> ChatFirstHarnessExecutorReceipt {
let stage = ProcessInfo.processInfo.environment["OMI_ENV_STAGE"]
let isLocalOrOfflineStage = stage == "local" || stage == "offline"
guard AppBuild.allowsLocalAutomation, isLocalOrOfflineStage else {
throw BridgeError.agentError("Chat-first executor fixture is unavailable outside local/offline builds")
}
guard controlGeneration >= 0 else {
throw BridgeError.agentError("Chat-first executor fixture requires a valid control generation")
}
try assertAuthorization(authorizationSnapshot, expectedOwnerID: ownerID)
let requestID = UUID().uuidString
let result = try await kernelContractRequest(
payload: Self.chatFirstHarnessExecutorBeginWireMessage(
clientId: clientId,
requestId: requestID,
ownerID: ownerID,
sessionID: sessionID,
producingTurnID: producingTurnID,
controlGeneration: controlGeneration
),
expectedKind: .chatFirstHarnessExecutorResult,
authorizationSnapshot: authorizationSnapshot
)
guard
result["ownerId"] as? String == ownerID,
result["sessionId"] as? String == sessionID,
let runID = result["runId"] as? String, !runID.isEmpty,
let attemptID = result["attemptId"] as? String, !attemptID.isEmpty,
let ok = result["ok"] as? Bool,
let executorInvoked = result["executorInvoked"] as? Bool,
let validated = result["validated"] as? Bool,
let journalBlockRendered = result["journalBlockRendered"] as? Bool
else {
throw BridgeError.agentError("Kernel returned an invalid Chat-first executor fixture receipt")
}
guard ok == (executorInvoked && validated && journalBlockRendered) else {
throw BridgeError.agentError("Kernel returned an inconsistent Chat-first executor fixture receipt")
}
return ChatFirstHarnessExecutorReceipt(
executorInvoked: executorInvoked,
validated: validated,
journalBlockRendered: journalBlockRendered
)
}
static func chatFirstHarnessExecutorBeginWireMessage(
clientId: String,
requestId: String,
ownerID: String,
sessionID: String,
producingTurnID: String,
controlGeneration: Int
) -> [String: Any] {
var message = protocolEnvelope(
type: "chat_first_harness_executor_begin",
clientId: clientId,
requestId: requestId,
ownerId: ownerID
)
message["sessionId"] = sessionID
message["producingTurnId"] = producingTurnID
message["controlGeneration"] = controlGeneration
// This is deliberately the sole fixture payload accepted by Node. It is
// server-validated before the normal journal append can happen.
message["input"] = ["blocks": [["type": "taskCard", "taskId": "chat-first-e2e-task-v1"]]]
return message
}
struct JournalOperationResult: Sendable {
let operation: String
let conversationId: String
let turn: KernelJournalTurn?
let turns: [KernelJournalTurn]
let clearedCount: Int
let highWaterTurnSeq: Int
let conversationGeneration: Int
let generationBaseTurnSeq: Int
let accepted: Bool?
let duplicate: Bool?
let continuityKey: String?
let suppressedByTailQuestion: Bool
let suppressedByStreamingTail: Bool
let materializationStoppedByTail: Bool
let materializationReceipts: [ChatFirstMaterializationReceipt]
let materializationRejections: [ChatFirstMaterializationRejection]
let materializationDeferrals: [ChatFirstMaterializationDeferral]
let coldStartSequenceTerminalReceipts: [ChatFirstColdStartSequenceTerminalReceipt]
let acknowledgedReceiptCount: Int
init(
operation: String,
conversationId: String,
turn: KernelJournalTurn?,
turns: [KernelJournalTurn],
clearedCount: Int,
highWaterTurnSeq: Int,
conversationGeneration: Int,
generationBaseTurnSeq: Int,
accepted: Bool? = nil,
duplicate: Bool? = nil,
continuityKey: String? = nil,
suppressedByTailQuestion: Bool = false,
suppressedByStreamingTail: Bool = false,
materializationStoppedByTail: Bool = false,
materializationReceipts: [ChatFirstMaterializationReceipt] = [],
materializationRejections: [ChatFirstMaterializationRejection] = [],
materializationDeferrals: [ChatFirstMaterializationDeferral] = [],
coldStartSequenceTerminalReceipts: [ChatFirstColdStartSequenceTerminalReceipt] = [],
acknowledgedReceiptCount: Int = 0
) {
self.operation = operation
self.conversationId = conversationId
self.turn = turn
self.turns = turns
self.clearedCount = clearedCount
self.highWaterTurnSeq = highWaterTurnSeq
self.conversationGeneration = conversationGeneration
self.generationBaseTurnSeq = generationBaseTurnSeq
self.accepted = accepted
self.duplicate = duplicate
self.continuityKey = continuityKey
self.suppressedByTailQuestion = suppressedByTailQuestion
self.suppressedByStreamingTail = suppressedByStreamingTail
self.materializationStoppedByTail = materializationStoppedByTail
self.materializationReceipts = materializationReceipts
self.materializationRejections = materializationRejections
self.materializationDeferrals = materializationDeferrals
self.coldStartSequenceTerminalReceipts = coldStartSequenceTerminalReceipts
self.acknowledgedReceiptCount = acknowledgedReceiptCount
}
}
struct QuestionInteractionReply: Sendable {
let accepted: Bool
let duplicate: Bool
let continuityKey: String
let parentTurn: KernelJournalTurn?
let userTurn: KernelJournalTurn
let assistantTurn: KernelJournalTurn
}
struct ChatFirstIntentsMaterialization: Sendable {
let accepted: Bool
let stoppedByTail: Bool
let receipts: [ChatFirstMaterializationReceipt]
let rejections: [ChatFirstMaterializationRejection]
let deferrals: [ChatFirstMaterializationDeferral]
}
/// Append server-validated structured blocks to exactly the assistant turn
/// produced by this capability's run/attempt. The Node kernel re-checks the
/// live capability and performs the sole journal mutation.
func appendChatFirstBlocks(
clientId: String,
surface: AgentSurfaceReference,
ownerID: String,
sessionID: String,
runID: String,
attemptID: String,
capabilityRef: String,
controlGeneration: Int,
blocksJSON: String,
authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot
) async throws -> KernelJournalTurn {
guard let blocksData = blocksJSON.data(using: .utf8),
let blocks = try? JSONSerialization.jsonObject(with: blocksData) as? [[String: Any]],
surface.surfaceKind == "main_chat",
controlGeneration >= 0,
!blocks.isEmpty,
blocks.count <= 8
else {
throw BridgeError.agentError("Invalid chat-first journal append")
}
let result = try await journalOperation(
type: "append_chat_first_blocks",
operation: "append_chat_first_blocks",
clientId: clientId,
surface: surface,
ownerID: ownerID,
payload: [
"sessionId": sessionID,
"runId": runID,
"attemptId": attemptID,
"capabilityRef": capabilityRef,
"controlGeneration": controlGeneration,
"blocks": blocks,
],
authorizationSnapshot: authorizationSnapshot
)
guard let turn = result.turn else {
throw BridgeError.agentError("Chat-first journal append returned no turn")
}
recordLifecycleJournalMutation(turn)
return turn
}
/// Attach one locally stored Rewind image to precisely the assistant turn
/// produced by the authorized Chat-first run. The local kernel owns the
/// turn selection and durability; Swift supplies only the evidence metadata.
func appendChatFirstEvidence(
clientId: String,
surface: AgentSurfaceReference,
ownerID: String,
sessionID: String,
runID: String,
attemptID: String,
capabilityRef: String,
controlGeneration: Int,
resource: ChatResource,
authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot
) async throws -> KernelJournalTurn {
guard surface.surfaceKind == "main_chat", controlGeneration >= 0, resource.isImage,
let resourceJSON =
ChatResource.encodeResourcesForPersistence([resource]),
let resourceData = resourceJSON.data(using: .utf8),
let resources = try JSONSerialization.jsonObject(with: resourceData) as? [[String: Any]],
let wireResource = resources.first
else {
throw BridgeError.agentError("Invalid chat-first evidence append")
}
let result = try await journalOperation(
type: "append_chat_first_evidence",
operation: "append_chat_first_evidence",
clientId: clientId,
surface: surface,
ownerID: ownerID,
payload: [
"sessionId": sessionID,
"runId": runID,
"attemptId": attemptID,
"capabilityRef": capabilityRef,
"controlGeneration": controlGeneration,
"resource": wireResource,
],
authorizationSnapshot: authorizationSnapshot
)
guard let turn = result.turn else {
throw BridgeError.agentError("Chat-first evidence append returned no turn")
}
recordLifecycleJournalMutation(turn)
return turn
}
/// The journal derives the stored question payload and only accepts the
/// current main-Chat tail. Swift cannot send an answer string or select an
/// arbitrary parent row through this operation.
func recordQuestionInteractionReply(
clientId: String,
surface: AgentSurfaceReference,
ownerID: String,
sessionID: String,
questionID: String,
optionID: String,
controlGeneration: Int,
authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot
) async throws -> QuestionInteractionReply {
guard surface.surfaceKind == "main_chat",
controlGeneration >= 0,
!sessionID.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
!questionID.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
!optionID.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
else {
throw BridgeError.agentError("Invalid question interaction")
}
let result = try await journalOperation(
type: "record_question_interaction_reply",
operation: "record_question_interaction_reply",
clientId: clientId,
surface: surface,
ownerID: ownerID,
payload: [
"sessionId": sessionID,
"questionId": questionID,
"optionId": optionID,
"controlGeneration": controlGeneration,
],
authorizationSnapshot: authorizationSnapshot
)
guard result.accepted == true,
let continuityKey = result.continuityKey,
let userTurn = result.turns.first(where: { $0.role == "user" }),
let assistantTurn = result.turns.first(where: { $0.role == "assistant" })
else {
throw BridgeError.agentError("Question is no longer actionable")
}
for turn in [result.turn, userTurn, assistantTurn] {
if let turn { recordLifecycleJournalMutation(turn) }
}
return QuestionInteractionReply(
accepted: true,
duplicate: result.duplicate == true,
continuityKey: continuityKey,
parentTurn: result.turn,
userTurn: userTurn,
assistantTurn: assistantTurn
)
}
/// Materialize one ordered server batch through the kernel, which owns the
/// canonical assistant rows, tail suppression, and receipt identities.
func materializeChatFirstIntents(
clientId: String,
surface: AgentSurfaceReference,
ownerID: String,
sessionID: String,
controlGeneration: Int,
intentsJSON: String,
authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot
) async throws -> ChatFirstIntentsMaterialization {
guard let intentsData = intentsJSON.data(using: .utf8),
let intents = try? JSONDecoder().decode([ChatFirstPromptIntent].self, from: intentsData),
surface.surfaceKind == "main_chat",
controlGeneration >= 0,
!intents.isEmpty,
intents.count <= 8,
intents.allSatisfy({ $0.accountGeneration == controlGeneration && $0.kernelBlocks != nil }),
!sessionID.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
else {
throw BridgeError.agentError("Invalid chat-first materialization")
}
let result = try await journalOperation(
type: "materialize_chat_first_intents",
operation: "materialize_chat_first_intents",
clientId: clientId,
surface: surface,
ownerID: ownerID,
payload: [
"sessionId": sessionID,
"controlGeneration": controlGeneration,
"intents": intents.compactMap { intent -> [String: Any]? in
guard let blocks = intent.kernelBlocks else { return nil }
return [
"intentId": intent.intentID,
"continuityKey": intent.continuityKey,
"source": intent.source.rawValue,
"blocks": blocks,
] as [String: Any]
},
],
authorizationSnapshot: authorizationSnapshot
)
for turn in result.turns {
recordLifecycleJournalMutation(turn)
}
return ChatFirstIntentsMaterialization(
accepted: result.accepted == true,
stoppedByTail: result.materializationStoppedByTail,
receipts: result.materializationReceipts,
rejections: result.materializationRejections,
deferrals: result.materializationDeferrals
)
}
func listChatFirstMaterializationReceipts(
clientId: String,
surface: AgentSurfaceReference,
ownerID: String,
sessionID: String,
controlGeneration: Int,
authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot
) async throws -> ChatFirstPromptReceiptBatch {
guard surface.surfaceKind == "main_chat", controlGeneration >= 0 else {
throw BridgeError.agentError("Invalid chat-first receipt listing")
}
let result = try await journalOperation(
type: "list_chat_first_materialization_receipts",
operation: "list_chat_first_materialization_receipts",
clientId: clientId,
surface: surface,
ownerID: ownerID,
payload: ["sessionId": sessionID, "controlGeneration": controlGeneration, "limit": 16],
authorizationSnapshot: authorizationSnapshot
)
return ChatFirstPromptReceiptBatch(
materializationReceipts: result.materializationReceipts,
coldStartSequenceTerminalReceipts: result.coldStartSequenceTerminalReceipts
)
}
@discardableResult
func acknowledgeChatFirstMaterializationReceipts(
clientId: String,
surface: AgentSurfaceReference,
ownerID: String,
sessionID: String,
controlGeneration: Int,
receipts: ChatFirstPromptReceiptBatch,
authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot
) async throws -> Int {
guard surface.surfaceKind == "main_chat",
controlGeneration >= 0,
receipts.materializationReceipts.count <= 16,
receipts.coldStartSequenceTerminalReceipts.count <= 16
else {
throw BridgeError.agentError("Invalid chat-first receipt acknowledgement")
}
let result = try await journalOperation(
type: "acknowledge_chat_first_materialization_receipts",
operation: "acknowledge_chat_first_materialization_receipts",
clientId: clientId,
surface: surface,
ownerID: ownerID,
payload: [
"sessionId": sessionID,
"controlGeneration": controlGeneration,
"receipts": receipts.materializationReceipts.map {
["intentId": $0.intentID, "receiptId": $0.receiptID]
},
"coldStartSequenceTerminalReceipts": receipts.coldStartSequenceTerminalReceipts.map {
[
"sequenceId": $0.sequenceID,
"receiptId": $0.receiptID,
"terminalState": $0.terminalState.rawValue,
]
},
],
authorizationSnapshot: authorizationSnapshot
)
return result.acknowledgedReceiptCount
}
nonisolated static func chatFirstMaterializationReceipts(
from payload: Any?
) -> [ChatFirstMaterializationReceipt] {
guard let values = payload as? [[String: Any]] else { return [] }
return values.compactMap { value in
guard let intentID = value["intentId"] as? String,
!intentID.isEmpty,
let receiptID = value["receiptId"] as? String,
!receiptID.isEmpty
else { return nil }
return ChatFirstMaterializationReceipt(intentID: intentID, receiptID: receiptID)
}
}
nonisolated static func chatFirstRejections(
from payload: Any?
) -> [ChatFirstMaterializationRejection] {
guard let values = payload as? [[String: Any]] else { return [] }
return values.compactMap { value in
guard let intentID = value["intentId"] as? String,
!intentID.isEmpty,
let code = value["code"] as? String,
!code.isEmpty
else { return nil }
return ChatFirstMaterializationRejection(
intentID: intentID,
code: code,
message: value["message"] as? String
)
}
}
nonisolated static func chatFirstDeferrals(from payload: Any?) -> [ChatFirstMaterializationDeferral] {
guard let values = payload as? [[String: Any]] else { return [] }
return values.compactMap { value in
guard let intentID = value["intentId"] as? String, !intentID.isEmpty,
let code = value["code"] as? String, ["tail_question", "streaming_tail"].contains(code)
else { return nil }
return ChatFirstMaterializationDeferral(intentID: intentID, code: code)
}
}
nonisolated static func chatFirstJournalFailureLog(
failure: AgentRuntimeFailure?, payload: [String: Any], raw: String
) -> String {
let code = failure?.code ?? payload["errorCode"] as? String ?? "journal_operation_failed"
return "AgentRuntimeProcess: journal operation failed code=\(code) message=\(raw)"
}
nonisolated static func chatFirstColdStartSequenceTerminalReceipts(
from payload: Any?
) -> [ChatFirstColdStartSequenceTerminalReceipt] {
guard let values = payload as? [[String: Any]] else { return [] }
return values.compactMap { value in
guard let sequenceID = value["sequenceId"] as? String,
!sequenceID.isEmpty,
let receiptID = value["receiptId"] as? String,
!receiptID.isEmpty,
let rawState = value["terminalState"] as? String,
let terminalState = ChatFirstColdStartSequenceTerminalReceipt.TerminalState(rawValue: rawState)
else { return nil }
return ChatFirstColdStartSequenceTerminalReceipt(
sequenceID: sequenceID,
receiptID: receiptID,
terminalState: terminalState
)
}
}
func handleChatFirstDeferralDelivery(_ message: RuntimeMessage) {
guard let request = ChatFirstDeferralDeliveryRequest(payload: message.payload) else {
sendChatFirstDeferralDeliveryResult(
requestId: message.requestId,
clientId: message.clientId,
ownerID: message.payload["ownerId"] as? String,
continuityKey: message.payload["continuityKey"] as? String ?? "",
deliveryGeneration: message.payload["deliveryGeneration"] as? Int ?? 0,
payloadHash: message.payload["payloadHash"] as? String ?? "",
ok: false,
errorCode: "chat_first_deferral_malformed"
)
return
}
Task { [weak self] in
do {
try await APIClient.shared.recordChatFirstDeferral(request)
await self?.sendChatFirstDeferralDeliveryResult(
requestId: message.requestId,
clientId: message.clientId,
ownerID: request.ownerID,
continuityKey: request.continuityKey,
deliveryGeneration: request.deliveryGeneration,
payloadHash: request.payloadHash,
ok: true,
errorCode: nil
)
} catch {
await self?.sendChatFirstDeferralDeliveryResult(
requestId: message.requestId,
clientId: message.clientId,
ownerID: request.ownerID,
continuityKey: request.continuityKey,
deliveryGeneration: request.deliveryGeneration,
payloadHash: request.payloadHash,
ok: false,
errorCode: Self.boundedChatFirstDeferralErrorCode(for: error)
)
}
}
}
func sendChatFirstDeferralDeliveryResult(
requestId: String?,
clientId: String?,
ownerID: String?,
continuityKey: String,
deliveryGeneration: Int,
payloadHash: String,
ok: Bool,
errorCode: String?
) {
var payload: [String: Any] = [
"type": "chat_first_deferral_delivery_result",
"protocolVersion": 2,
"continuityKey": continuityKey,
"deliveryGeneration": deliveryGeneration,
"payloadHash": payloadHash,
"ok": ok,
]
if let requestId { payload["requestId"] = requestId }
if let clientId { payload["clientId"] = clientId }
if let ownerID { payload["ownerId"] = ownerID }
if let errorCode { payload["errorCode"] = errorCode }
sendJson(payload)
}
}