forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAgentRuntimeProcess.swift
More file actions
4403 lines (4130 loc) · 162 KB
/
Copy pathAgentRuntimeProcess.swift
File metadata and controls
4403 lines (4130 loc) · 162 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 Foundation
import OmiSupport
extension Notification.Name {
/// Posted on MainActor after the runtime handshake makes direct control tools admissible.
static let agentRuntimeDidBecomeReady = Notification.Name("com.omi.desktop.agentRuntimeDidBecomeReady")
}
/// Shares one asynchronous runtime launch across every client admitted while
/// that launch is suspended. The key is deliberately exact (owner-session
/// authorization plus authority epoch), so work admitted under a newer owner
/// generation never joins an older credential-bearing launch.
actor AgentRuntimeStartupSingleFlight<Key: Equatable & Sendable, Output: Sendable> {
private struct Attempt {
let id: UUID
let key: Key
let task: Task<Output, Error>
}
private var attempt: Attempt?
private var participantCount = 0
func run(
key: Key,
operation: @escaping @Sendable () async throws -> Output
) async throws -> Output {
participantCount += 1
defer { participantCount -= 1 }
if let attempt {
guard attempt.key == key else { throw BridgeError.restarting }
return try await attempt.task.value
}
let id = UUID()
let task = Task { try await operation() }
attempt = Attempt(id: id, key: key, task: task)
do {
let output = try await task.value
clearAttempt(id: id)
return output
} catch {
clearAttempt(id: id)
throw error
}
}
func participantCountForTesting() -> Int {
participantCount
}
/// A reducer can enter `.starting` just before the owning task reaches this
/// actor. Callers must distinguish that short launch-admission window from a
/// real in-flight launch; treating both as "wait for init" strands the first
/// launch forever.
func hasActiveAttempt() -> Bool {
attempt != nil
}
private func clearAttempt(id: UUID) {
guard attempt?.id == id else { return }
attempt = nil
}
}
/// Decides whether a caller joins an existing launch. `.starting` alone is not
/// sufficient evidence: the reducer records admission before the single-flight
/// actor has installed its attempt, and the first launcher must proceed.
enum AgentRuntimeStartupAdmission {
static func shouldJoin(
lifecycleState: AgentRuntimeBridgeLifecycle.State,
hasActiveStartupAttempt: Bool
) -> Bool {
lifecycleState == .running || (lifecycleState == .starting && hasActiveStartupAttempt)
}
}
/// Serializes the pipe read and sequence assignment performed by Foundation's
/// readability callback. The callback may be re-entered on different threads;
/// sequencing only after `availableData` would still allow a later read to be
/// delivered first if the earlier callback were preempted between those steps.
final class AgentRuntimeStdoutChunkReader: @unchecked Sendable {
private let lock = NSLock()
private var nextSequence: UInt64 = 0
func read(from handle: FileHandle) -> (sequence: UInt64, data: Data) {
lock.lock()
defer { lock.unlock() }
let data = handle.availableData
let sequence = nextSequence
if !data.isEmpty {
nextSequence &+= 1
}
return (sequence, data)
}
}
/// Kernel context needs a bounded but startup-tolerant readiness budget. These
/// requests only establish the pinned session and rendered context; they never
/// run the user's model query, which is tracked on its own request path.
enum AgentRuntimeKernelContractTimeoutPolicy {
static let defaultDeadlineNanoseconds: UInt64 = 5_000_000_000
static let contextReadinessDeadlineNanoseconds: UInt64 = 15_000_000_000
static func deadlineNanoseconds(for operation: String) -> UInt64 {
switch operation {
case "resolve_surface_session", "context_source_update", "get_context_snapshot":
return contextReadinessDeadlineNanoseconds
default:
return defaultDeadlineNanoseconds
}
}
}
/// Actor-owned reorder and framing buffer for the runtime's JSONL stdout.
/// Tasks created by a readability callback are not scheduling-ordered, so an
/// N+1 chunk can reach the actor before N. Hold later chunks until every prior
/// sequence is present, then extract complete lines from the canonical order.
struct AgentRuntimeOrderedStdoutBuffer {
private var nextSequence: UInt64 = 0
private var pendingChunks: [UInt64: Data] = [:]
private var lineBuffer = Data()
mutating func ingest(_ data: Data, sequence: UInt64) -> [Data] {
guard !data.isEmpty, sequence >= nextSequence else { return [] }
guard pendingChunks[sequence] == nil else { return [] }
pendingChunks[sequence] = data
var lines: [Data] = []
while let chunk = pendingChunks.removeValue(forKey: nextSequence) {
nextSequence &+= 1
lineBuffer.append(chunk)
while let newlineIndex = lineBuffer.firstIndex(of: UInt8(ascii: "\n")) {
lines.append(Data(lineBuffer[lineBuffer.startIndex..<newlineIndex]))
lineBuffer = Data(lineBuffer[lineBuffer.index(after: newlineIndex)...])
}
}
return lines
}
mutating func reset() {
nextSequence = 0
pendingChunks.removeAll(keepingCapacity: false)
lineBuffer.removeAll(keepingCapacity: false)
}
}
/// Thread-safe, actor-independent holder for the debug suspend/resume (SIGSTOP /
/// SIGCONT) state used by the non-prod stall harness.
///
/// `AgentRuntimeProcess.sendJson()` does a *blocking* stdin write. If the agent is
/// frozen (SIGSTOP) and a query fills the ~64KB pipe buffer, that write blocks the
/// actor — so if the resume (SIGCONT) were also actor-isolated it could never run,
/// deadlocking the agent permanently. Routing the SIGCONT through this lock-guarded
/// holder keeps it off the actor, so resume/auto-resume always fire even while the
/// actor is stuck writing to the frozen process. Generation-guarded so a stale
/// auto-resume can't SIGCONT after an explicit resume or a newer suspend.
final class DebugSuspendControl: @unchecked Sendable {
private let lock = NSLock()
private var pid: pid_t?
private var generation: UInt64 = 0
/// Sends SIGCONT and reports success. Injectable so the generation-guard logic
/// is unit-testable without real signals; defaults to `kill(pid, SIGCONT) == 0`.
private let sendContinue: (pid_t) -> Bool
init(sendContinue: @escaping (pid_t) -> Bool = { kill($0, SIGCONT) == 0 }) {
self.sendContinue = sendContinue
}
/// Record a SIGSTOP; returns the generation for its safety auto-resume timer.
func arm(pid: pid_t) -> UInt64 {
lock.lock()
defer { lock.unlock() }
self.pid = pid
generation &+= 1
return generation
}
/// Explicit resume: SIGCONT the armed pid and, on success, advance the
/// generation (cancelling the pending auto-resume). Returns the resumed pid, or
/// nil if nothing was armed or the SIGCONT failed. On failure the state stays
/// armed so the safety auto-resume can still recover the process. The signal is
/// sent OUTSIDE the lock — never invoke the injectable closure while holding it.
func resume() -> pid_t? {
lock.lock()
let armed = pid
lock.unlock()
guard let armed, sendContinue(armed) else { return nil }
lock.lock()
defer { lock.unlock() }
// A newer suspend/disarm may have moved on; only clear the pid we resumed.
if pid == armed {
pid = nil
generation &+= 1
}
return armed
}
/// Safety auto-resume: SIGCONT only if this generation is still the armed one.
/// Signal sent outside the lock; state cleared only on a successful send.
func autoResume(generation: UInt64) -> pid_t? {
lock.lock()
let armed = (generation == self.generation) ? pid : nil
lock.unlock()
guard let armed, sendContinue(armed) else { return nil }
lock.lock()
defer { lock.unlock() }
if pid == armed, self.generation == generation {
pid = nil
}
return armed
}
/// Clear on process teardown so a later resume can't SIGCONT a reused pid.
/// `closePipes()` calls this on every teardown/relaunch path; the only residual
/// window (OS reaping the pid before teardown runs) is benign — SIGCONT to a
/// process that isn't stopped is a no-op — and the whole flow is non-prod only.
func disarm() {
lock.lock()
defer { lock.unlock() }
pid = nil
generation &+= 1
}
}
actor AgentRuntimeProcess {
static let shared = AgentRuntimeProcess()
nonisolated static let expectedProtocolVersion = 2
nonisolated static let requiredRuntimeCapabilities: Set<String> = [
"journal_import_remote_turn",
"runtime_adapter_availability",
"chat_first_capability_projection",
]
private static let ownerTransitionClientID = "runtime-owner-transition"
struct RuntimeHandshake: Equatable, Sendable {
let protocolVersion: Int
let runtimeVersion: String
let capabilities: Set<String>
}
struct DiagnosticsSnapshot: Equatable, Sendable {
let running: Bool
let protocolVersion: Int?
let runtimeVersion: String?
}
struct RuntimeOwnerAuthorityStatus: Equatable, Sendable {
let epoch: UInt64
let ownerID: String?
let credentialOwnerID: String?
let processRunning: Bool
func isSynchronized(ownerID: String, requiresCredentials: Bool) -> Bool {
processRunning && self.ownerID == ownerID
&& (!requiresCredentials || credentialOwnerID == ownerID)
}
}
nonisolated static func shouldEnablePlaywrightExtension(
useExtension: Bool,
token: String,
targetHasExtension: Bool
) -> Bool {
useExtension && !token.isEmpty && targetHasExtension
}
nonisolated static func startupAuthHeader(
requiresCredentials: Bool,
fetchAuthHeader: () async throws -> String?
) async throws -> String? {
guard requiresCredentials else { return nil }
return try await fetchAuthHeader()
}
nonisolated static func validateRuntimeHandshake(
_ message: RuntimeMessage
) throws -> RuntimeHandshake {
guard message.kind == .initMessage,
let protocolVersion = message.protocolVersion,
protocolVersion == expectedProtocolVersion
else {
throw BridgeError.agentError("Agent runtime protocol is incompatible")
}
let runtimeVersion =
(message.payload["runtimeVersion"] as? String)?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard !runtimeVersion.isEmpty else {
throw BridgeError.agentError("Agent runtime did not identify its version")
}
let capabilities = Set(message.payload["runtimeCapabilities"] as? [String] ?? [])
guard requiredRuntimeCapabilities.isSubset(of: capabilities) else {
throw BridgeError.agentError("Agent runtime is missing required capabilities")
}
return RuntimeHandshake(
protocolVersion: protocolVersion,
runtimeVersion: runtimeVersion,
capabilities: capabilities
)
}
nonisolated static func isConfirmedOutOfMemoryDiagnostic(_ text: String) -> Bool {
let lower = text.lowercased()
return lower.contains("fatalprocessoutofmemory")
|| lower.contains("javascript heap out of memory")
|| lower.contains("failed to reserve virtual memory")
}
struct RuntimeMessage: @unchecked Sendable {
struct RequestKey: Hashable, Equatable, Sendable {
let clientId: String
let requestId: String
}
let kind: Kind
let requestId: String?
let clientId: String?
let protocolVersion: Int?
let payload: [String: Any]
var requestKey: RequestKey? {
guard let clientId, let requestId else { return nil }
return RequestKey(clientId: clientId, requestId: requestId)
}
static func parse(_ json: String) -> RuntimeMessage? {
guard let data = json.data(using: .utf8),
let dict = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let type = dict["type"] as? String
else {
return nil
}
return RuntimeMessage(
kind: kind(for: type),
requestId: dict["requestId"] as? String,
clientId: dict["clientId"] as? String,
protocolVersion: dict["protocolVersion"] as? Int,
payload: dict
)
}
private static func kind(for type: String) -> Kind {
switch type {
case "init": return .initMessage
case "text_delta": return .textDelta
case "thinking_delta": return .thinkingDelta
case "tool_use": return .toolUse
case "authorized_tool_execution": return .authorizedToolExecution
case "tool_activity": return .toolActivity
case "turn_activity": return .turnActivity
case "tool_result_display": return .toolResultDisplay
case "result": return .result
case "error": return .error
case "auth_required": return .authRequired
case "auth_success": return .authSuccess
case "cancel_ack": return .cancelAck
case "control_tool_result": return .controlToolResult
case "journal_operation_result": return .journalOperationResult
case "journal_turn_changed": return .journalTurnChanged
case "journal_backend_sync": return .journalBackendSync
case "journal_backend_delete": return .journalBackendDelete
case "journal_backend_reconcile": return .journalBackendReconcile
case "chat_first_deferral_delivery": return .chatFirstDeferralDelivery
case "default_execution_profile_configured": return .defaultExecutionProfileConfigured
case "surface_session_resolved": return .surfaceSessionResolved
case "session_execution_profile_migrated": return .sessionExecutionProfileMigrated
case "context_source_updated": return .contextSourceUpdated
case "context_snapshot": return .contextSnapshot
case "legacy_main_chat_sessions_imported": return .legacyMainChatSessionsImported
case "external_surface_run_begin_result": return .externalSurfaceRunBeginResult
case "external_surface_tool_result": return .externalSurfaceToolResult
case "external_surface_run_complete_result": return .externalSurfaceRunCompleteResult
case "chat_first_harness_executor_result": return .chatFirstHarnessExecutorResult
case "owner_runtime_revoked": return .ownerRuntimeRevoked
default: return .unknown(type)
}
}
}
private struct ClientRegistration {
var registrationID: UUID
var harnessMode: String
var authAuthorizationSnapshot: RuntimeOwnerAuthorizationSnapshot?
var onAuthRequired: AgentBridge.AuthRequiredHandler?
var onAuthSuccess: AgentBridge.AuthSuccessHandler?
init(
registrationID: UUID = UUID(),
harnessMode: String,
authAuthorizationSnapshot: RuntimeOwnerAuthorizationSnapshot? = nil,
onAuthRequired: AgentBridge.AuthRequiredHandler? = nil,
onAuthSuccess: AgentBridge.AuthSuccessHandler? = nil
) {
self.registrationID = registrationID
self.harnessMode = harnessMode
self.authAuthorizationSnapshot = authAuthorizationSnapshot
self.onAuthRequired = onAuthRequired
self.onAuthSuccess = onAuthSuccess
}
}
private struct StartupKey: Equatable, Sendable {
let authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot
let admissionAuthorityEpoch: UInt64
}
private struct StartupReceipt: Equatable, Sendable {
let authorityEpoch: UInt64
let processGeneration: UInt64
}
private struct StopFlight {
let id: UUID
var waiters: [CheckedContinuation<Void, Never>] = []
}
private struct ActiveRequest {
let clientId: String
let requestId: String
let surfaceRef: AgentSurfaceReference?
let originatingUserText: String?
let onTextDelta: AgentBridge.TextDeltaHandler
let onToolActivity: AgentBridge.ToolActivityHandler
let onTurnActivity: AgentBridge.TurnActivityHandler
let onThinkingDelta: AgentBridge.ThinkingDeltaHandler
let onToolResultDisplay: AgentBridge.ToolResultDisplayHandler
let onAuthRequired: AgentBridge.AuthRequiredHandler
let onAuthSuccess: AgentBridge.AuthSuccessHandler
let authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot
let continuation: CheckedContinuation<AgentBridge.QueryResult, Error>
var isInterrupted = false
var cancelAck: RuntimeMessage?
}
private struct ActiveControlRequest {
let clientId: String
let requestId: String
let expectedOwnerId: String
let expectedOwnerEpoch: UInt64
let authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot
let continuation: CheckedContinuation<String, Error>
}
private struct ActiveJournalRequest {
let clientId: String
let requestId: String
let authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot
let continuation: CheckedContinuation<JournalOperationResult, Error>
}
private struct ActiveKernelContractRequest {
let clientId: String
let requestId: String
let operation: String
let expectedKind: RuntimeMessage.Kind
let authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot?
let sentAtUptime: TimeInterval
let continuation: CheckedContinuation<RuntimeJSONPayloadBox, Error>
}
private struct TimedOutKernelContractRequest {
let operation: String
let expectedKind: RuntimeMessage.Kind
let timedOutAtUptime: TimeInterval
}
typealias JournalTurnChangedHandler = @Sendable (KernelJournalTurn) -> Void
typealias AuthorizedRealtimeToolHandler =
@Sendable (AuthorizedToolExecution) async -> AuthorizedRealtimeToolExecutionResult
private var process: Process?
private var stdinPipe: Pipe?
private var stdoutPipe: Pipe?
private var stderrPipe: Pipe?
private var stdoutBuffer = AgentRuntimeOrderedStdoutBuffer()
private var processGeneration: UInt64 = 0
private var runtimeOwnerAuthorityEpoch: UInt64 = 0
private var synchronizedRuntimeOwnerID: String?
private var synchronizedRuntimeCredentialOwnerID: String?
private var directControlOwnerEpoch: UInt64 = 0
private var observedDirectControlOwnerId: String?
/// Debug suspend/resume state, held off-actor so SIGCONT never deadlocks behind
/// an actor blocked writing to the frozen process. See DebugSuspendControl.
private nonisolated let debugSuspend = DebugSuspendControl()
private var lastExitWasOOM = false
private var startupBeganAt: Date?
private var startupBinaryPresent = false
private var startupBinaryPresentChecked = false
private var startupPermissionGrantedChecked = false
private var pendingStartFailureDiagnostics: DesktopErrorDiagnosticContext?
private var startupPermissionGranted = false
private var startupExitCode: Int32?
private var clients: [String: ClientRegistration] = [:]
private var activeRequests: [RuntimeMessage.RequestKey: ActiveRequest] = [:]
private var activeControlRequests: [RuntimeMessage.RequestKey: ActiveControlRequest] = [:]
private var activeControlTimeoutTasks: [RuntimeMessage.RequestKey: Task<Void, Never>] = [:]
private var activeJournalRequests: [RuntimeMessage.RequestKey: ActiveJournalRequest] = [:]
private var activeKernelContractRequests: [RuntimeMessage.RequestKey: ActiveKernelContractRequest] = [:]
private var timedOutKernelContractRequests: [RuntimeMessage.RequestKey: TimedOutKernelContractRequest] = [:]
private var activeAuthorizedToolExecutionTasks: [UUID: Task<Void, Never>] = [:]
private var journalTurnChangedHandler: JournalTurnChangedHandler?
private var authorizedRealtimeToolHandler: AuthorizedRealtimeToolHandler?
private var initContinuations: [CheckedContinuation<Void, Error>] = []
private let oomDiagnosticLatch = AgentRuntimeOOMDiagnosticLatch()
private var advertisedAgentControlTools: Set<String> = []
private var runtimeAdapterIDs: Set<String> = []
private var negotiatedProtocolVersion: Int?
private var negotiatedRuntimeVersion: String?
private var stopFlight: StopFlight?
private var expectedCancelledRequests: Set<RuntimeMessage.RequestKey> = []
// Lifecycle facts are reduced by the pure state machine; process/pipe handles
// remain local implementation resources rather than a second lifecycle truth.
private var bridgeLifecycle = AgentRuntimeBridgeLifecycle()
private let startupSingleFlight =
AgentRuntimeStartupSingleFlight<StartupKey, StartupReceipt>()
// `bridgeLifecycle` is the semantic source of truth. Process handles are
// intentionally only physical resources: they can be live before the JSONL
// handshake, but no request is admitted until the reducer reaches running.
private var isBridgeReady: Bool {
bridgeLifecycle.state == .running && process?.isRunning == true
}
private var isRestarting: Bool {
[.modeSwitching, .draining, .restarting].contains(bridgeLifecycle.state)
}
private var isStopping: Bool {
bridgeLifecycle.state == .draining
}
var isAlive: Bool {
let processRunning = process?.isRunning ?? false
if process != nil && !processRunning {
log(
"AgentRuntimeProcess: stale alive latch — process no longer running "
+ "(failure_class=stale_alive_latch recovery_action=route_to_termination recovery_result=degraded)")
DesktopDiagnosticsManager.shared.recordAgentRuntimeStaleAliveCheck()
// Route through handleTermination so in-flight continuations are resumed
// and the old terminationHandler is properly superseded. Only clearing the
// latch here would leave active requests dangling if the terminationHandler
// hasn't fired (or is about to be ignored by generation mismatch).
handleTermination(reason: .exit)
}
return processRunning
}
func diagnosticsSnapshot() -> DiagnosticsSnapshot {
DiagnosticsSnapshot(
running: isBridgeReady,
protocolVersion: negotiatedProtocolVersion,
runtimeVersion: negotiatedRuntimeVersion
)
}
/// Read-only admission probe for UI recovery loops. A process handle alone
/// is not enough: direct control is valid only after the JSONL handshake.
func isReadyForDirectControl() -> Bool {
isBridgeReady
}
func runtimeOwnerAuthorityStatus() -> RuntimeOwnerAuthorityStatus {
RuntimeOwnerAuthorityStatus(
epoch: runtimeOwnerAuthorityEpoch,
ownerID: synchronizedRuntimeOwnerID,
credentialOwnerID: synchronizedRuntimeCredentialOwnerID,
processRunning: process?.isRunning ?? false
)
}
/// The Node registry is the authority for adapter activation. Swift must not
/// re-run local executable detection before advertising a realtime provider.
func registeredDirectedProviderIDs() -> [String] {
runtimeAdapterIDs.intersection(["hermes", "openclaw"]).sorted()
}
static func adapterId(forHarnessMode harnessMode: String) -> String? {
guard let harness = AgentRuntimeRouting.harnessMode(from: harnessMode) else {
return nil
}
return AgentRuntimeRouting.adapterId(for: harness).rawValue
}
func registerClient(
clientId: String,
harnessMode: String,
authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot? = nil,
requiresCredentials: Bool = true
) async throws {
guard !isRestarting else {
throw BridgeError.restarting
}
guard
let authorizationSnapshot = authorizationSnapshot
?? RuntimeOwnerIdentity.captureAuthorizationSnapshot()
else {
throw BridgeError.authMissing
}
let admissionAuthorityEpoch = runtimeOwnerAuthorityEpoch
try assertStartupAuthority(
authorizationSnapshot,
expectedAuthorityEpoch: admissionAuthorityEpoch)
let previousRegistration = clients[clientId]
let registrationID = UUID()
var registration = previousRegistration ?? ClientRegistration(harnessMode: harnessMode)
registration.registrationID = registrationID
registration.harnessMode = harnessMode
clients[clientId] = registration
do {
let startupIsInFlight: Bool
if bridgeLifecycle.state == .starting {
startupIsInFlight = await startupSingleFlight.hasActiveAttempt()
} else {
startupIsInFlight = false
}
if AgentRuntimeStartupAdmission.shouldJoin(
lifecycleState: bridgeLifecycle.state,
hasActiveStartupAttempt: startupIsInFlight
) {
try await waitForInit(timeout: 30.0)
try assertStartupAuthority(
authorizationSnapshot,
expectedAuthorityEpoch: admissionAuthorityEpoch)
try assertClientRegistration(clientId: clientId, registrationID: registrationID)
return
}
try await startProcess(
preferredHarnessMode: harnessMode,
authorizationSnapshot: authorizationSnapshot,
admissionAuthorityEpoch: admissionAuthorityEpoch,
requiresCredentials: requiresCredentials)
try assertAuthorization(authorizationSnapshot)
try assertClientRegistration(clientId: clientId, registrationID: registrationID)
} catch {
if clients[clientId]?.registrationID == registrationID {
if let previousRegistration {
clients[clientId] = previousRegistration
} else {
clients.removeValue(forKey: clientId)
}
}
throw error
}
}
func unregisterClient(clientId: String) async {
clients.removeValue(forKey: clientId)
for (requestKey, request) in activeRequests where request.clientId == clientId {
activeRequests.removeValue(forKey: requestKey)
request.continuation.resume(throwing: BridgeError.stopped)
}
for (requestKey, request) in activeControlRequests where request.clientId == clientId {
if let activeRequest = takeActiveControlRequest(requestKey) {
activeRequest.continuation.resume(throwing: BridgeError.stopped)
}
}
for (requestKey, request) in activeJournalRequests where request.clientId == clientId {
activeJournalRequests.removeValue(forKey: requestKey)
request.continuation.resume(throwing: BridgeError.stopped)
}
for (requestKey, request) in activeKernelContractRequests where request.clientId == clientId {
activeKernelContractRequests.removeValue(forKey: requestKey)
request.continuation.resume(throwing: BridgeError.stopped)
}
if clients.isEmpty {
await stopProcessSingleFlight(resumeRequestsWith: BridgeError.stopped)
}
}
func setGlobalAuthHandlers(
clientId: String,
authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot?,
onAuthRequired: AgentBridge.AuthRequiredHandler?,
onAuthSuccess: AgentBridge.AuthSuccessHandler?
) -> Bool {
// Handler configuration is not registration. Creating a client here lets a
// handler-before-start call survive a failed/cancelled admission and keep
// the shared daemon alive as a ghost client.
guard var registration = clients[clientId] else { return false }
registration.authAuthorizationSnapshot = authorizationSnapshot
registration.onAuthRequired = onAuthRequired
registration.onAuthSuccess = onAuthSuccess
clients[clientId] = registration
return true
}
func restart(
clientId: String,
harnessMode: String,
authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot? = nil
) async throws {
guard !isRestarting else { throw BridgeError.restarting }
guard activeRequests.isEmpty, activeControlRequests.isEmpty else {
log(
"AgentRuntimeProcess: shared restart blocked while \(activeRequests.count) request(s) and \(activeControlRequests.count) control request(s) are active"
)
throw BridgeError.requestAlreadyActive
}
// Validate before mutating the reducer. A caller can be unregistered
// between a UI restart action and this actor turn; that must leave the
// bridge usable for a later registration, not stranded in `.draining`.
guard let registrationID = clients[clientId]?.registrationID else {
throw BridgeError.stopped
}
_ = bridgeLifecycle.reduce(.modeSwitchRequested)
_ = bridgeLifecycle.reduce(.drainRequested)
do {
await stopProcessSingleFlight(resumeRequestsWith: BridgeError.stopped)
_ = bridgeLifecycle.reduce(.restart)
try Task.checkCancellation()
try assertClientRegistration(clientId: clientId, registrationID: registrationID)
guard
let authorizationSnapshot = authorizationSnapshot
?? RuntimeOwnerIdentity.captureAuthorizationSnapshot()
else {
throw BridgeError.authMissing
}
try await startProcess(
preferredHarnessMode: harnessMode,
authorizationSnapshot: authorizationSnapshot,
admissionAuthorityEpoch: runtimeOwnerAuthorityEpoch,
requiresCredentials: true)
try assertAuthorization(authorizationSnapshot)
try assertClientRegistration(clientId: clientId, registrationID: registrationID)
} catch {
// A cancelled or unregistered caller cannot own a pending restart. Keep
// typed start failures intact, but return abandoned drain/restart paths
// to stopped so a subsequent registration can launch normally.
if [.draining, .restarting].contains(bridgeLifecycle.state) {
_ = bridgeLifecycle.reduce(.kill)
}
throw error
}
}
private func assertStartupAuthority(
_ snapshot: RuntimeOwnerAuthorizationSnapshot,
expectedAuthorityEpoch: UInt64
) throws {
guard !isStopping,
runtimeOwnerAuthorityEpoch == expectedAuthorityEpoch,
RuntimeOwnerIdentity.isAuthorizationCurrent(snapshot)
else {
throw BridgeError.authMissing
}
}
private func stopProcessSingleFlight(resumeRequestsWith error: BridgeError) async {
if let flight = stopFlight {
await waitForStopFlight(id: flight.id)
return
}
let id = UUID()
stopFlight = StopFlight(id: id)
await stopProcess(resumeRequestsWith: error)
finishStopFlight(id: id)
}
private func waitForStopFlight(id: UUID) async {
await withCheckedContinuation { continuation in
guard var flight = stopFlight, flight.id == id else {
continuation.resume()
return
}
flight.waiters.append(continuation)
stopFlight = flight
}
}
private func finishStopFlight(id: UUID) {
guard let flight = stopFlight, flight.id == id else { return }
stopFlight = nil
for waiter in flight.waiters {
waiter.resume()
}
}
private func assertClientRegistration(
clientId: String,
registrationID: UUID
) throws {
guard clients[clientId]?.registrationID == registrationID else {
throw BridgeError.stopped
}
}
func assertAuthorization(
_ snapshot: RuntimeOwnerAuthorizationSnapshot,
expectedOwnerID: String? = nil
) throws {
guard RuntimeOwnerIdentity.isAuthorizationCurrent(snapshot) else {
throw BridgeError.authMissing
}
if let expectedOwnerID {
let normalized = expectedOwnerID.trimmingCharacters(in: .whitespacesAndNewlines)
guard normalized == snapshot.ownerID else { throw BridgeError.authMissing }
}
}
func warmupSession(
clientId: String,
sessionId: String,
profileGeneration: Int,
authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot
) {
guard RuntimeOwnerIdentity.isAuthorizationCurrent(authorizationSnapshot) else { return }
sendJson(
Self.warmupWireMessage(
clientId: clientId,
requestId: UUID().uuidString,
ownerId: authorizationSnapshot.ownerID,
sessionId: sessionId,
profileGeneration: profileGeneration
))
}
func configureDefaultExecutionProfile(
clientId: String,
adapterId: String,
modelProfile: String?,
workingDirectory: String,
expectedPreferenceGeneration: Int?,
authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot
) async throws -> AgentDefaultExecutionProfile {
try assertAuthorization(authorizationSnapshot)
let payload = Self.configureDefaultExecutionProfileWireMessage(
clientId: clientId,
requestId: UUID().uuidString,
ownerId: authorizationSnapshot.ownerID,
adapterId: adapterId,
modelProfile: modelProfile,
workingDirectory: workingDirectory,
expectedPreferenceGeneration: expectedPreferenceGeneration
)
let result = try await kernelContractRequest(
payload: payload,
expectedKind: .defaultExecutionProfileConfigured,
authorizationSnapshot: authorizationSnapshot
)
guard let profile = AgentDefaultExecutionProfile(dictionary: result) else {
throw BridgeError.agentError("Kernel returned an invalid default execution profile")
}
return profile
}
func resolveSurfaceSession(
clientId: String,
surface: AgentSurfaceReference,
title: String?,
creationProfile: AgentSessionCreationProfile?,
chatFirstCapability: ChatFirstCapabilityProjection? = nil,
authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot
) async throws -> AgentSurfaceSession {
try assertAuthorization(authorizationSnapshot)
let payload = Self.resolveSurfaceSessionWireMessage(
clientId: clientId,
requestId: UUID().uuidString,
ownerId: authorizationSnapshot.ownerID,
surface: surface,
title: title,
creationProfile: creationProfile,
chatFirstCapability: chatFirstCapability
)
let result = try await kernelContractRequest(
payload: payload,
expectedKind: .surfaceSessionResolved,
authorizationSnapshot: authorizationSnapshot)
guard let session = AgentSurfaceSession(dictionary: result) else {
throw BridgeError.agentError("Kernel returned an invalid surface session")
}
return session
}
func migrateSessionExecutionProfile(
clientId: String,
sessionId: String,
expectedProfileGeneration: Int,
adapterId: String,
modelProfile: String?,
workingDirectory: String,
authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot
) async throws -> AgentSessionProfileMigration {
try assertAuthorization(authorizationSnapshot)
let payload = Self.migrateSessionExecutionProfileWireMessage(
clientId: clientId,
requestId: UUID().uuidString,
ownerId: authorizationSnapshot.ownerID,
sessionId: sessionId,
expectedProfileGeneration: expectedProfileGeneration,
adapterId: adapterId,
modelProfile: modelProfile,
workingDirectory: workingDirectory
)
let result = try await kernelContractRequest(
payload: payload,
expectedKind: .sessionExecutionProfileMigrated,
authorizationSnapshot: authorizationSnapshot
)
guard let migration = AgentSessionProfileMigration(dictionary: result) else {
throw BridgeError.agentError("Kernel returned an invalid session execution profile migration")
}
return migration
}
func updateContextSource(
clientId: String,
sessionId: String,
surfaceKind: String,
source: AgentContextSource,
sourceRevision: String,
outcome: AgentContextSourceOutcome,
capturedAtMs: Int,
expiresAtMs: Int?,
payload: RuntimeJSONPayloadBox,
authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot
) async throws -> AgentContextSourceUpdateReceipt {
try assertAuthorization(authorizationSnapshot)
let message = Self.contextSourceUpdateWireMessage(
clientId: clientId,
requestId: UUID().uuidString,
ownerId: authorizationSnapshot.ownerID,
sessionId: sessionId,
surfaceKind: surfaceKind,
source: source,
sourceRevision: sourceRevision,
outcome: outcome,
capturedAtMs: capturedAtMs,
expiresAtMs: expiresAtMs,
payload: payload.value
)
let result = try await kernelContractRequest(
payload: message,
expectedKind: .contextSourceUpdated,
authorizationSnapshot: authorizationSnapshot)
guard let receipt = AgentContextSourceUpdateReceipt(dictionary: result) else {
throw BridgeError.agentError("Kernel returned an invalid context source receipt")
}
return receipt
}
func getContextSnapshot(
clientId: String,
sessionId: String,
surfaceKind: String,
authorizationSnapshot: RuntimeOwnerAuthorizationSnapshot
) async throws -> AgentContextSnapshot {
try assertAuthorization(authorizationSnapshot)
let message = Self.getContextSnapshotWireMessage(
clientId: clientId,
requestId: UUID().uuidString,
ownerId: authorizationSnapshot.ownerID,
sessionId: sessionId,
surfaceKind: surfaceKind
)
let result = try await kernelContractRequest(
payload: message,
expectedKind: .contextSnapshot,
authorizationSnapshot: authorizationSnapshot)
guard
let dictionary = result["snapshot"] as? [String: Any],
let snapshot = AgentContextSnapshot(dictionary: dictionary)
else {
throw BridgeError.agentError("Kernel returned an invalid context snapshot")
}
return snapshot
}
func setAuthorizedRealtimeToolHandler(_ handler: AuthorizedRealtimeToolHandler?) {
authorizedRealtimeToolHandler = handler
}
/// Correlated pre-visibility owner barrier. This method never registers a
/// client or starts Node: an absent child already proves no process-local work
/// can survive. Any malformed/nack/timeout path kills and confirms exit before
/// returning to the owner transition.
func revokeOwnerRuntime(
previousOwnerID: String,
cleanupCapability: RuntimeOwnerTransitionCleanupCapability
) async {
let ownerID = previousOwnerID.trimmingCharacters(in: .whitespacesAndNewlines)
do {
try assertTransitionCleanupAuthority(
cleanupCapability,
previousOwnerID: ownerID)
} catch {
log("AgentRuntimeProcess: owner revoke rejected invalid cleanup capability")
if process?.isRunning == true {
await stopProcessSingleFlight(resumeRequestsWith: .stopped)
} else {
markRuntimeOwnerAuthorityDirty()
}
return
}
await cancelAndDrainAuthorizedToolExecutionTasks()
guard !ownerID.isEmpty else {
if process?.isRunning == true { await stopProcessSingleFlight(resumeRequestsWith: .stopped) }