-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMalibuAgent.swift
More file actions
1501 lines (1431 loc) · 67.3 KB
/
Copy pathMalibuAgent.swift
File metadata and controls
1501 lines (1431 loc) · 67.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
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 Combine
import Foundation
// AUDIT R1 + R2 fixes wired into this file:
// - H1 (R1): crash reconnect used to re-enter start() while `child` was still
// non-nil, so the guard returned immediately and the daemon never
// restarted. We now nil `child` before scheduling reconnect.
// - H2 (R1): intentional stop paths must NOT fire onUnexpectedExit; a flag on
// CLIChildProcess suppresses the callback and MalibuAgent cancels
// any pending reconnect task before setting child = nil.
// - H3 (R2): reconnect task could complete `start()` AFTER shutdown() returned.
// We now gate `start()` on an isShuttingDown flag and re-check it after
// every suspension.
// - H4 (R2): `start()` refuses to launch when ProviderConfig.isConfigured
// is false. Onboarding "Start earning" no longer bypasses the deep-
// link + Keychain gate.
// - A1 (R1+R2): pause/resume no longer optimistically flip snapshot.state.
// A legacy all-zero metrics tuple is treated as unavailable so older
// supported CLI peers cannot misreport "no earnings" as authoritative.
@MainActor
final class MalibuAgent: ObservableObject {
@Published private(set) var snapshot: AgentSnapshot = .empty
@Published private(set) var logLines: [String] = []
@Published private(set) var providerStartFailure: String?
private var child: CLIChildProcess?
private var control: ControlSocketClient?
private var metricsPoller: Task<Void, Never>?
private var eventStreamTask: Task<Void, Never>?
private var reconnectTask: Task<Void, Never>?
private var providerLogTail: ProviderLogTail?
private var providerLogTailCancellable: AnyCancellable?
private var watchdogLogTailCancellable: AnyCancellable?
private var watchdogLogLines: [String] = []
private var reconnect = ReconnectPolicy()
private let thermalMonitor = ThermalMonitor()
private var cancellables: Set<AnyCancellable> = []
// AUDIT R2 CODE H3 fix: once shutdown begins, refuse any subsequent start()
// — including a reconnect Task that already slept past its cancellation
// check but hadn't yet re-entered the MainActor.
private var isShuttingDown: Bool = false
private var healthPollTask: Task<Void, Never>?
private var monitorsLaunchdProvider = false
/// Reward projections may become fresh only after the current provider
/// passes both the local readiness and service-identity checks.
private var providerProjectionEligible = false
private var lastRequestsRateSample: (total: Int, date: Date)?
private var latestReleaseFetchedAt: Date?
private var cliUpdateTask: Task<Void, Never>?
private var hardwareVerificationRetryTask: Task<Void, Never>?
/// Set while corrective `--recover-hardware-admission` may have drained
/// launchd and therefore owes a restore/bootstrap. Cleared on success.
private var hardwareRecoveryOwnsLaunchdRestore = false
private var credentialRepairTask: Task<Void, Never>?
private var admissionIdentityRecoveryTask: Task<Void, Never>?
private var referralStatusExpiryTask: Task<Void, Never>?
private let referralActionWatchdog = ReferralActionWatchdog()
private var lastReferralRefreshRequestedAt: Date?
private let latestReleaseTTL: TimeInterval = 3600
init(
initialSnapshot: AgentSnapshot = .empty,
projectionEligibleForMetrics: Bool = false
) {
snapshot = initialSnapshot
providerProjectionEligible = projectionEligibleForMetrics
thermalMonitor.$state
.sink { [weak self] state in
self?.snapshot.thermalState = state
}
.store(in: &cancellables)
snapshot.thermalState = thermalMonitor.state
}
// MARK: - Lifecycle
func start() async {
guard !isShuttingDown else { return }
invalidateProviderProjectionFreshness()
guard ProviderConfig.readProviderID() != nil else {
snapshot.state = .error
snapshot.lastError = "Not set up yet. Click Launch Provider to activate."
return
}
guard StartupState.launchdInstallEvidenceExists() else {
snapshot.state = .error
snapshot.lastError = "Not set up yet. Click Launch Provider to run the installer."
return
}
guard await ProviderConfig.isConfigured else {
snapshot.state = .error
snapshot.lastError = "Not set up yet. Click Launch Provider to activate."
return
}
// Release any Malibu-spawned CLI from older builds before attaching to launchd.
await releaseSpawnedChildForLaunchdMonitor()
snapshot.state = .starting
startProviderLogTail()
if await monitorInstalledProviderIfPresent() {
return
}
if let failure = providerStartFailure {
snapshot.state = .error
snapshot.lastError = failure
return
}
guard !isShuttingDown else { return }
if let failure = diagnosedProviderFailure(includingLaunchdState: true) {
providerStartFailure = failure
snapshot.state = .error
snapshot.lastError = failure
return
}
snapshot.state = .reconnecting
snapshot.lastError = ProviderLogDiagnostics.timeoutMessage(
logHint: ProviderLogDiagnostics.logHint()
)
await scheduleReconnect()
}
// Do not flip state until the CLI persists and acknowledges the lifecycle
// transition. Malibu requests the transaction but never owns pause state.
func pause() async {
guard let control else {
snapshot.lastError = "Provider control is unavailable. Malibu will retry the local connection."
return
}
snapshot.pauseAcknowledged = false
do {
try await control.send(.pauseRequest)
} catch {
snapshot.lastError = "Could not request provider pause: \(error.localizedDescription)"
}
}
func resume() async {
guard let control else {
snapshot.lastError = "Provider control is unavailable. Malibu will retry the local connection."
return
}
do {
try await control.send(.resumeRequest)
} catch {
snapshot.lastError = "Could not request provider resume: \(error.localizedDescription)"
}
}
func refreshReferralStatus() async {
guard snapshot.hasTrustedReferralBoundary() else {
snapshot.referralAvailability = .unsupported
snapshot.referralStatus = nil
snapshot.referralLastError = nil
return
}
guard control != nil else {
snapshot.referralAvailability = .unavailable
snapshot.referralLastError = "The provider control connection is unavailable."
return
}
snapshot.referralLastError = nil
_ = await requestReferralStatusIfDue()
}
func startReferralChallenge() async {
guard snapshot.hasTrustedReferralBoundary(),
snapshot.localStatusCapabilities.contains("referral_advocacy_v1"),
snapshot.referralStatus?.isCurrent() == true,
snapshot.referralStatus?.canStartSocialChallenge == true,
let control else { return }
beginReferralAction()
snapshot.referralLastError = nil
do {
try await control.send(.referralChallengeRequest)
} catch {
finishReferralAction()
resumeReferralStatusExpiryOrRefresh()
snapshot.referralLastError = "The X verification request could not reach the provider."
}
}
func reopenReferralChallenge() async {
guard snapshot.hasTrustedReferralBoundary(),
snapshot.localStatusCapabilities.contains("referral_advocacy_v1"),
let pending = snapshot.referralStatus?.pendingChallenge,
pending.expiresAt > Date(),
let control else { return }
beginReferralAction()
snapshot.referralLastError = nil
do {
try await control.send(.referralChallengeReopenRequest)
} catch {
finishReferralAction()
resumeReferralStatusExpiryOrRefresh()
snapshot.referralLastError = "The X composer could not be reopened by the provider."
}
}
func verifyReferralPost(_ postURL: String) async {
guard snapshot.hasTrustedReferralBoundary(),
snapshot.localStatusCapabilities.contains("referral_advocacy_v1"),
snapshot.referralStatus?.isCurrent() == true,
snapshot.referralStatus?.pendingChallenge != nil,
let control else { return }
beginReferralAction()
snapshot.referralLastError = nil
do {
try await control.send(.referralVerifyRequest(postURL: postURL))
} catch {
finishReferralAction()
resumeReferralStatusExpiryOrRefresh()
snapshot.referralLastError = "The X post could not be submitted to the provider."
}
}
func cancelReferralChallenge() async {
guard snapshot.hasTrustedReferralBoundary(),
snapshot.localStatusCapabilities.contains("referral_advocacy_v1"),
snapshot.referralStatus?.isCurrent() == true,
let control else { return }
beginReferralAction()
snapshot.referralLastError = nil
do {
try await control.send(.referralChallengeCancelRequest)
} catch {
finishReferralAction()
resumeReferralStatusExpiryOrRefresh()
snapshot.referralLastError = "The pending X verification could not be cleared."
}
}
/// Online #582 recovery without reinstalling provider identity.
/// Pending trust resubmits stored evidence; corrective paths use the CLI
/// `--recover-hardware-admission` drain/recommend/restore transaction.
func retryHardwareVerification() async {
guard !isShuttingDown else { return }
guard AgentSnapshotPresenter.publicStatus(snapshot).executableAction == .retryHardwareVerification else {
return
}
guard !snapshot.hardwareVerificationRetryInProgress else { return }
if let previous = hardwareVerificationRetryTask {
previous.cancel()
await previous.value
}
guard !isShuttingDown, !Task.isCancelled else { return }
let pendingTrust = snapshot.lifecycleReason == "autotune_evidence_required"
snapshot.hardwareVerificationRetryInProgress = true
snapshot.hardwareVerificationRetryLastError = nil
hardwareVerificationRetryTask = Task { [weak self] in
guard let self else { return }
defer {
if !self.isShuttingDown {
self.snapshot.hardwareVerificationRetryInProgress = false
}
}
var attemptedCorrectiveRecovery = !pendingTrust
do {
let cliURL = URL(fileURLWithPath: CLIUpdateRunner.installedCLIPath())
if pendingTrust {
do {
try await AutotuneRecommendationRunner.runPendingEvidenceResubmit(cliURL: cliURL)
} catch let AutotuneRecommendationError.nonZeroExit(code, _) where code == 10 {
// Stored recommendation/evidence missing or stale —
// fall through to corrective drain/restore recovery.
attemptedCorrectiveRecovery = true
self.hardwareRecoveryOwnsLaunchdRestore = true
try await AutotuneRecommendationRunner.runHardwareAdmissionRecovery(cliURL: cliURL)
}
} else {
self.hardwareRecoveryOwnsLaunchdRestore = true
try await AutotuneRecommendationRunner.runHardwareAdmissionRecovery(cliURL: cliURL)
}
guard !Task.isCancelled, !self.isShuttingDown else {
self.restoreLaunchdIfCorrectiveRecoveryOwned(attemptedCorrectiveRecovery)
return
}
self.hardwareRecoveryOwnsLaunchdRestore = false
self.snapshot.hardwareVerificationRetryLastError = nil
if let port = ProviderConfig.readHTTPPort() {
try? await Task.sleep(nanoseconds: 3_000_000_000)
await self.applyProviderSnapshot(port: port)
}
} catch is CancellationError {
self.restoreLaunchdIfCorrectiveRecoveryOwned(attemptedCorrectiveRecovery)
return
} catch {
self.restoreLaunchdIfCorrectiveRecoveryOwned(attemptedCorrectiveRecovery)
guard !Task.isCancelled, !self.isShuttingDown else { return }
self.snapshot.hardwareVerificationRetryLastError =
AgentSnapshotPresenter.publicErrorDetail(error.localizedDescription)
?? "Provider setup could not be completed. Export diagnostics for support."
}
}
await hardwareVerificationRetryTask?.value
}
private func restoreLaunchdIfCorrectiveRecoveryOwned(_ attemptedCorrectiveRecovery: Bool) {
guard AutotuneRecommendationRunner.shouldBestEffortBootstrapLaunchd(
attemptedCorrectiveRecovery: attemptedCorrectiveRecovery
) || hardwareRecoveryOwnsLaunchdRestore else {
return
}
AutotuneRecommendationRunner.bestEffortBootstrapLaunchdProvider()
hardwareRecoveryOwnsLaunchdRestore = false
}
func updateCLINow() async {
guard !snapshot.cliUpdateInProgress else { return }
guard AgentSnapshotPresenter.updateAvailable(snapshot) else { return }
cliUpdateTask?.cancel()
snapshot.cliUpdateInProgress = true
let installedVersion = snapshot.cliVersion
let compatibilitySetID = snapshot.compatibilitySetID
cliUpdateTask = Task { [weak self] in
guard let self else { return }
do {
try await CLIUpdateRunner.run(
installedVersion: installedVersion,
compatibilitySetID: compatibilitySetID
) { line in
self.logLines.append(LogTailBuffer.redacted(line))
if self.logLines.count > 400 {
self.logLines.removeFirst(self.logLines.count - 400)
}
}
self.snapshot.cliUpdateLastError = nil
if let port = ProviderConfig.readHTTPPort() {
try? await Task.sleep(nanoseconds: 3_000_000_000)
await self.applyProviderSnapshot(port: port)
}
} catch {
self.snapshot.cliUpdateLastError = error.localizedDescription
}
self.snapshot.cliUpdateInProgress = false
}
await cliUpdateTask?.value
}
func repairProviderCredential() async {
guard !isShuttingDown,
AgentSnapshotPresenter.canRepairCredential(snapshot),
let expectedProviderID = snapshot.localProviderID,
ProviderConfig.readProviderID() == expectedProviderID else { return }
if let previous = credentialRepairTask {
previous.cancel()
await previous.value
}
guard !isShuttingDown, !Task.isCancelled else { return }
snapshot.credentialRepairInProgress = true
snapshot.credentialRepairLastError = nil
credentialRepairTask = Task { [weak self] in
guard let self else { return }
do {
let result = try await ProviderCredentialHandoffRunner.repairCredential(
configURL: ProviderPaths.current.configFile,
expectedProviderID: expectedProviderID,
previousServiceInstanceID: self.snapshot.serviceInstanceID
)
guard !Task.isCancelled, !self.isShuttingDown else { return }
self.applyCredentialSnapshot(result)
if let port = ProviderConfig.readHTTPPort() {
await self.applyProviderSnapshot(port: port)
}
} catch is CancellationError {
return
} catch {
guard !Task.isCancelled, !self.isShuttingDown else { return }
self.snapshot.credentialRepairLastError = error.localizedDescription
await self.refreshCredentialDiagnosis()
}
if !self.isShuttingDown {
self.snapshot.credentialRepairInProgress = false
}
}
await credentialRepairTask?.value
}
func repairAdmissionIdentity() async {
guard !isShuttingDown,
AgentSnapshotPresenter.canRepairAdmissionIdentity(snapshot) else { return }
let expectedProviderID = snapshot.localProviderID
if let configError = AgentSnapshotPresenter.admissionIdentityRecoveryConfigError(
expectedProviderID: expectedProviderID,
configuredProviderID: ProviderConfig.readProviderID()
) {
snapshot.admissionIdentityRecoveryLastError = configError
return
}
guard let expectedProviderID else { return }
if let previous = admissionIdentityRecoveryTask {
previous.cancel()
await previous.value
}
guard !isShuttingDown, !Task.isCancelled else { return }
let activate = ["approval_required", "committed_cleanup"]
.contains(snapshot.admissionIdentityRecoveryJournalState)
|| snapshot.admissionIdentityState == "recovery_pending"
snapshot.admissionIdentityRecoveryInProgress = true
snapshot.admissionIdentityRecoveryLastError = nil
admissionIdentityRecoveryTask = Task { [weak self] in
guard let self else { return }
do {
if activate {
let result = try await ProviderCredentialHandoffRunner.activateAdmissionIdentityRecovery(
configURL: ProviderPaths.current.configFile,
expectedProviderID: expectedProviderID,
previousServiceInstanceID: self.snapshot.serviceInstanceID
)
guard !Task.isCancelled, !self.isShuttingDown else { return }
self.snapshot.applyAdmissionIdentityRecoveryJournal(result)
self.snapshot.admissionIdentityState = "ready"
self.snapshot.admissionIdentityPublicKeySHA256 = result.publicKeySHA256
self.snapshot.admissionIdentityPendingPublicKeySHA256 = nil
self.snapshot.admissionIdentityTransitionError = nil
self.snapshot.admissionIdentityRecoveryAction = "none"
if let port = ProviderConfig.readHTTPPort() {
await self.applyProviderSnapshot(port: port)
}
} else {
let incidentID = "malibu-\(UUID().uuidString.lowercased())"
let result = try await ProviderCredentialHandoffRunner.stageAdmissionIdentityRecovery(
configURL: ProviderPaths.current.configFile,
expectedProviderID: expectedProviderID,
incidentID: incidentID,
reason: "Malibu network verification repair"
)
guard !Task.isCancelled, !self.isShuttingDown else { return }
self.snapshot.applyAdmissionIdentityRecoveryJournal(result)
}
} catch is CancellationError {
return
} catch {
guard !Task.isCancelled, !self.isShuttingDown else { return }
self.snapshot.admissionIdentityRecoveryLastError = error.localizedDescription
}
if !self.isShuttingDown {
self.snapshot.admissionIdentityRecoveryInProgress = false
}
}
await admissionIdentityRecoveryTask?.value
}
// Detach Malibu from the standalone launchd provider. Option 2 makes the
// CLI the lifecycle owner, so quitting or updating the read-only app must
// never drain, stop, or restart a healthy provider. Explicit uninstall is
// performed separately by the CLI-owned teardown transaction.
func shutdown(gracefulSeconds: Int) async {
_ = gracefulSeconds
isShuttingDown = true
reconnectTask?.cancel(); reconnectTask = nil
healthPollTask?.cancel(); healthPollTask = nil
cliUpdateTask?.cancel(); cliUpdateTask = nil
referralStatusExpiryTask?.cancel(); referralStatusExpiryTask = nil
let hardwareRetryTask = hardwareVerificationRetryTask
hardwareVerificationRetryTask = nil
hardwareRetryTask?.cancel()
await hardwareRetryTask?.value
// Only restore when corrective recovery may have drained launchd.
// Ordinary quit must not re-bootstrap an intentionally unloaded job.
if hardwareRecoveryOwnsLaunchdRestore {
AutotuneRecommendationRunner.bestEffortBootstrapLaunchdProvider()
hardwareRecoveryOwnsLaunchdRestore = false
}
let admissionRecoveryTask = admissionIdentityRecoveryTask
admissionIdentityRecoveryTask = nil
admissionRecoveryTask?.cancel()
await admissionRecoveryTask?.value
let repairTask = credentialRepairTask
credentialRepairTask = nil
repairTask?.cancel()
await repairTask?.value
monitorsLaunchdProvider = false
lastRequestsRateSample = nil
await control?.close()
metricsPoller?.cancel(); metricsPoller = nil
eventStreamTask?.cancel(); eventStreamTask = nil
stopProviderLogTail()
logLines = []
child = nil
control = nil
snapshot = .empty
snapshot.thermalState = thermalMonitor.state
}
// MARK: - Private
/// Attach to an existing launchd-managed provider (CLI install track).
/// Returns true when local /v1/health is reachable on the configured port.
@discardableResult
func monitorInstalledProviderIfPresent(
timeout: TimeInterval = MalibuOnboardingTimeouts.firstServingFrameSec
) async -> Bool {
guard let port = ProviderConfig.readHTTPPort(),
ProviderConfig.readProviderID() != nil else {
return false
}
providerStartFailure = nil
await releaseSpawnedChildForLaunchdMonitor()
startProviderLogTail()
let deadline = Date().addingTimeInterval(max(1, timeout))
let pollInterval: TimeInterval = 2
while Date() < deadline {
if await InstalledProviderMonitor.isHealthy(port: port) {
monitorsLaunchdProvider = true
providerStartFailure = nil
await applyProviderSnapshot(port: port)
await refreshAdmissionIdentityRecoveryDiagnosis()
await attachInstalledProviderControlIfAvailable()
startHealthPolling(port: port)
return snapshot.state == .serving
}
if let failure = diagnosedProviderFailure() {
providerStartFailure = failure
snapshot.state = .error
snapshot.lastError = failure
await refreshCredentialDiagnosis()
return false
}
let remaining = deadline.timeIntervalSinceNow
guard remaining > 0 else { break }
let sleep = min(pollInterval, remaining)
try? await Task.sleep(nanoseconds: UInt64(sleep * 1_000_000_000))
}
let failure = diagnosedProviderFailure(includingLaunchdState: true)
?? ProviderLogDiagnostics.timeoutMessage(logHint: ProviderLogDiagnostics.logHint())
providerStartFailure = failure
snapshot.state = .error
snapshot.lastError = failure
await refreshCredentialDiagnosis()
return false
}
/// Stop a Malibu-spawned CLI child before attaching to launchd. Without
/// this, onboarding can leave two macprovider-cli processes (different
/// ports, same provider_id) running concurrently.
private func releaseSpawnedChildForLaunchdMonitor() async {
invalidateProviderProjectionFreshness()
reconnectTask?.cancel()
reconnectTask = nil
let oldControl = control
metricsPoller?.cancel()
metricsPoller = nil
eventStreamTask?.cancel()
eventStreamTask = nil
control = nil
if child != nil {
child?.markStopping()
try? await oldControl?.send(.shutdownRequest(graceSeconds: 5))
await child?.stop(gracePeriod: 5)
}
await oldControl?.close()
child = nil
invalidateProviderProjectionFreshness()
}
private func applyProviderSnapshot(port: Int) async {
let localReady = await applyHealthSnapshot(port: port)
if !localReady {
invalidateProviderProjectionFreshness()
}
if let status = await InstalledProviderMonitor.fetchStatus(port: port),
let expectedProviderID = ProviderConfig.readProviderID(),
InstalledProviderMonitor.serviceIdentityMatches(
status,
expectedProviderID: expectedProviderID,
launchdPID: InstalledProviderMonitor.launchdServicePID(),
liveCodeMatches: ProviderCredentialHandoffRunner.validatedInstalledProcessMatches(pid:)
) {
snapshot.localProviderID = expectedProviderID
snapshot.localStatusContractVersion = status.contractVersion
snapshot.localStatusMinimumReaderVersion = status.minimumReaderVersion
snapshot.localStatusContractCompatible = status.contractCompatible
snapshot.localStatusLifecycleOwner = status.lifecycleOwner
snapshot.localStatusCapabilities = status.capabilities
snapshot.statusObservationID = status.observationID
snapshot.statusObservedAt = status.observedAt
snapshot.statusObservationValidForMS = status.observationValidForMS
snapshot.statusObservationFresh = status.observationFresh
snapshot.serviceInstanceID = status.serviceInstanceID
snapshot.servicePID = status.servicePID
snapshot.serviceBootSession = status.serviceBootSession
snapshot.serviceStartedAt = status.serviceStartedAt
snapshot.serviceRole = status.serviceRole
snapshot.lifecycleRecordState = status.transitionRecordState
snapshot.lifecycleSequence = status.transitionSequence
snapshot.lifecycleTransitionID = status.transitionID
snapshot.lifecycleTransitionAt = status.transitionAt
snapshot.lifecycleState = status.transitionState
snapshot.lifecycleReason = status.transitionReason
snapshot.lifecycleAuthority = status.transitionAuthority
snapshot.lifecycleWriter = status.transitionWriter
snapshot.lifecycleOperationID = status.transitionOperationID
snapshot.lifecycleOperatorPaused = status.operatorPaused
snapshot.lifecycleLastRestart = status.lastRestart
snapshot.lifecycleLastRejection = status.lastRejection
snapshot.lifecycleLastUpdate = status.lastUpdate
snapshot.lifecycleLastWatchdog = status.lastWatchdog
snapshot.lifecycleLeaseState = status.lifecycleLeaseState
snapshot.lifecycleLeaseKind = status.lifecycleLeaseKind
snapshot.lifecycleLeaseOperationID = status.lifecycleLeaseOperationID
snapshot.lifecycleLeaseExpiresWallMS = status.lifecycleLeaseExpiresWallMS
snapshot.credentialSource = status.credentialSource
snapshot.credentialState = status.credentialState
snapshot.credentialRestartSafe = status.credentialRestartSafe
snapshot.credentialMigrationPending = status.credentialMigrationPending
snapshot.credentialRecoveryAction = status.credentialRecoveryAction
snapshot.credentialStatusObservedAt = status.observedAt
snapshot.credentialStatusFromDiagnostic = false
snapshot.admissionIdentitySource = status.admissionIdentitySource
snapshot.admissionIdentityState = status.admissionIdentityState
snapshot.admissionIdentityPublicKeySHA256 = status.admissionIdentityPublicKeySHA256
snapshot.admissionIdentityPendingPublicKeySHA256 = status.admissionIdentityPendingPublicKeySHA256
snapshot.admissionIdentityPreviousPublicKeySHA256 = status.admissionIdentityPreviousPublicKeySHA256
snapshot.admissionIdentityPreviousValidUntil = status.admissionIdentityPreviousValidUntil
snapshot.admissionIdentityCoordinatorGeneration = status.admissionIdentityCoordinatorGeneration
snapshot.admissionIdentityCoordinatorPublicKeySHA256 = status.admissionIdentityCoordinatorPublicKeySHA256
snapshot.admissionIdentityCoordinatorKeyRole = status.admissionIdentityCoordinatorKeyRole
snapshot.admissionIdentityTransitionError = status.admissionIdentityTransitionError
snapshot.admissionIdentityRecoveryAction = status.admissionIdentityRecoveryAction
snapshot.coordinatorIdentityAdmissionMode = status.coordinatorIdentityAdmissionMode
snapshot.coordinatorConnected = status.coordinatorConnected
snapshot.networkState = status.networkState
providerProjectionEligible = localReady
snapshot.advertisedMaxConcurrency = status.advertisedMaxConcurrency
snapshot.catalogState = status.catalogState
snapshot.catalogReleaseID = status.catalogReleaseID
snapshot.catalogDigest = status.catalogDigest
snapshot.catalogSignerKeyID = status.catalogSignerKeyID
snapshot.catalogSource = status.catalogSource
snapshot.compatibilitySetID = status.compatibilitySetID
snapshot.compatibilitySetSHA256 = status.compatibilitySetSHA256
if let version = status.binaryVersion {
snapshot.cliVersion = ProviderCLIVersion.normalize(version)
}
if let recommended = status.recommendedVersion {
snapshot.coordinatorRecommendedVersion = ProviderCLIVersion.normalize(recommended)
}
if snapshot.hasTrustedReferralBoundary() {
if snapshot.referralAvailability == .unsupported {
snapshot.referralAvailability = .unavailable
}
} else {
referralStatusExpiryTask?.cancel()
referralStatusExpiryTask = nil
snapshot.referralAvailability = .unsupported
snapshot.referralStatus = nil
snapshot.referralLastError = nil
finishReferralAction()
}
} else {
// Never carry a prior authoritative serving verdict across a
// failed status/readiness refresh.
snapshot.invalidateLocalStatusObservation()
invalidateProviderProjectionFreshness()
}
reconcileNetworkState(localReady: localReady)
await refreshLatestReleaseIfNeeded()
}
private func refreshCredentialDiagnosis() async {
guard FileManager.default.fileExists(atPath: ProviderPaths.current.configFile.path),
let expectedProviderID = ProviderConfig.readProviderID() else { return }
do {
let result = try await ProviderCredentialHandoffRunner.credentialStatus(
configURL: ProviderPaths.current.configFile,
expectedProviderID: expectedProviderID
)
applyCredentialSnapshot(result)
} catch {
snapshot.credentialRepairLastError = snapshot.credentialRepairLastError
?? error.localizedDescription
}
await refreshAdmissionIdentityRecoveryDiagnosis()
}
private func refreshAdmissionIdentityRecoveryDiagnosis() async {
guard FileManager.default.fileExists(atPath: ProviderPaths.current.configFile.path),
let expectedProviderID = ProviderConfig.readProviderID() else {
if snapshot.admissionIdentityRecoveryJournalState != nil {
snapshot.admissionIdentityRecoveryLastError =
"Network verification repair requires the current provider setup."
}
return
}
do {
let result = try await ProviderCredentialHandoffRunner.admissionIdentityRecoveryStatus(
configURL: ProviderPaths.current.configFile,
expectedProviderID: expectedProviderID
)
snapshot.applyAdmissionIdentityRecoveryJournal(result)
} catch {
snapshot.admissionIdentityRecoveryLastError = error.localizedDescription
}
}
private func applyCredentialSnapshot(_ credential: ProviderCredentialHandoffRunner.CredentialSnapshot) {
snapshot.localProviderID = credential.providerID
snapshot.credentialSource = credential.source
snapshot.credentialState = credential.condition
snapshot.credentialRestartSafe = credential.restartSafe
snapshot.credentialMigrationPending = credential.migrationPending
snapshot.credentialRecoveryAction = credential.action
snapshot.credentialStatusObservedAt = Date()
snapshot.credentialStatusFromDiagnostic = true
}
/// Local /v1/health readiness only — coordinator session is reconciled separately.
@discardableResult
private func applyHealthSnapshot(port: Int) async -> Bool {
guard let health = await InstalledProviderMonitor.fetchHealth(port: port) else { return false }
if let model = health.model, !model.isEmpty {
snapshot.currentModelID = model
}
if let total = health.requestsTotal {
snapshot.requestsServedAllTime = total
updateRequestsPerMinute(from: total)
}
if let today = health.requestsToday {
snapshot.requestsServedToday = today
}
if let inputToday = health.inputTokensToday {
snapshot.inputTokensToday = inputToday
}
if let outputToday = health.outputTokensToday {
snapshot.outputTokensToday = outputToday
}
if let inputAllTime = health.inputTokensAllTime {
snapshot.inputTokensAllTime = inputAllTime
}
if let outputAllTime = health.outputTokensAllTime {
snapshot.outputTokensAllTime = outputAllTime
}
if let uptime = health.uptimeSeconds {
snapshot.uptimeSec = uptime
}
if let restarts = health.restartCount {
snapshot.restartCount = restarts
}
return health.ready
}
/// Serving requires the CLI's coordinator-authoritative buyer-serving
/// state. A WebSocket connection proves transport only, not admission.
private func reconcileNetworkState(localReady: Bool) {
if snapshot.lifecycleRecordState == "valid",
(snapshot.lifecycleState == "paused_by_operator" || snapshot.lifecycleOperatorPaused == true) {
snapshot.state = .paused
snapshot.pauseAcknowledged = true
snapshot.lastError = nil
return
}
if snapshot.state == .paused {
// The persisted CLI transition, not an old UI acknowledgement, is
// authoritative. Once it advances, clear the local paused view.
snapshot.state = localReady ? .reconnecting : .starting
snapshot.pauseAcknowledged = false
}
let observationCurrent = snapshot.isLocalStatusObservationCurrent()
let buyerServing = observationCurrent && snapshot.networkState == "buyer_serving"
if localReady && buyerServing {
snapshot.state = .serving
snapshot.lastError = nil
return
}
if localReady {
snapshot.state = .reconnecting
snapshot.lastError = coordinatorDisconnectMessage()
return
}
}
private func coordinatorDisconnectMessage() -> String {
if snapshot.localStatusContractCompatible == false {
return "Provider running · Malibu needs an update to read its status"
}
if !snapshot.isLocalStatusObservationCurrent() {
return "Provider running · checking status again"
}
switch snapshot.networkState {
case "safe_offline_fallback":
return "Model loaded locally · provider software is using an offline fallback"
case "catalog_update_required":
return "Model loaded locally · provider software update required"
case "catalog_integrity_failure":
return "Model loaded locally · provider software check failed"
case "local_donor":
return "Model loaded locally · this mode does not receive customer work"
case "not_buyer_serving":
return "Model loaded locally · this Mac is not currently eligible for customer work"
case "buyer_serving_unknown":
return "Model loaded locally · checking customer availability"
case "live_verified":
return snapshot.coordinatorConnected == true
? "Model loaded locally · waiting for network approval"
: "Model loaded locally · provider software verified; reconnecting to the network"
default:
break
}
switch snapshot.coordinatorConnected {
case .some(false):
return "Model loaded locally · not connected to the network"
case .none:
return "Model loaded locally · checking network connection…"
case .some(true):
return snapshot.networkState == nil
? "Model loaded locally · checking customer availability"
: "Checking background provider…"
}
}
private func refreshLatestReleaseIfNeeded() async {
if let fetchedAt = latestReleaseFetchedAt,
Date().timeIntervalSince(fetchedAt) < latestReleaseTTL,
snapshot.latestReleaseVersion != nil {
return
}
if let tag = await GitHubLatestReleaseClient.fetchTag() {
latestReleaseFetchedAt = Date()
snapshot.latestReleaseVersion = tag
}
}
private func updateRequestsPerMinute(from total: Int) {
let now = Date()
if let last = lastRequestsRateSample {
let elapsedMinutes = now.timeIntervalSince(last.date) / 60.0
if elapsedMinutes > 0 {
let delta = max(0, total - last.total)
snapshot.requestsPerMinute = Double(delta) / elapsedMinutes
}
}
lastRequestsRateSample = (total, now)
}
private func startHealthPolling(port: Int) {
lastRequestsRateSample = nil
healthPollTask?.cancel()
healthPollTask = Task { [weak self] in
while !Task.isCancelled {
try? await Task.sleep(nanoseconds: LocalStatusObservationPolicy.pollIntervalNanoseconds)
guard let self else { return }
if await InstalledProviderMonitor.isHealthy(port: port) {
await self.applyProviderSnapshot(port: port)
await self.attachInstalledProviderControlIfAvailable()
try? await self.control?.send(.metricsRequest)
try? await self.control?.send(.statusRequest)
await self.requestReferralStatusIfDue()
} else if self.monitorsLaunchdProvider {
await MainActor.run {
self.snapshot.invalidateLocalStatusObservation()
self.invalidateProviderProjectionFreshness()
if let failure = self.diagnosedProviderFailure(includingLaunchdState: true) {
self.providerStartFailure = failure
self.snapshot.state = .error
self.snapshot.lastError = failure
} else {
self.snapshot.state = .reconnecting
self.snapshot.lastError = ProviderLogDiagnostics.timeoutMessage(
logHint: ProviderLogDiagnostics.logHint()
)
}
}
}
}
}
}
private func connectControl(socketPath: String) async {
metricsPoller?.cancel(); metricsPoller = nil
eventStreamTask?.cancel(); eventStreamTask = nil
if let control {
await control.close()
self.control = nil
}
let client = ControlSocketClient(socketPath: socketPath)
do {
try await client.connect(timeout: MalibuOnboardingTimeouts.controlSocketConnectSec)
} catch {
// AUDIT R6 CODE M-connect fix: previously we set .error and returned,
// leaving `self.child` pointing at a running CLI. `start()`'s
// `guard child == nil` then blocked every subsequent restart, and
// the orphan kept holding the model in memory. Stop the child
// cleanly and route through the same reconnect backoff as an
// unexpected exit so the user (or model-load recovery) can retry.
snapshot.state = .error
snapshot.lastError = "Control socket: \(error)"
invalidateProviderProjectionFreshness()
child?.markStopping()
await child?.stop(gracePeriod: 5)
child = nil
guard !isShuttingDown else { return }
snapshot.state = .reconnecting
await scheduleReconnect()
return
}
guard !isShuttingDown else { await client.close(); return }
self.control = client
reconnect.reset()
snapshot.state = .starting
eventStreamTask = Task { [weak self] in
for await frame in client.stream {
guard let self, !Task.isCancelled, self.control === client else { return }
self.consume(frame)
}
await client.close()
guard let self, self.control === client else { return }
if self.monitorsLaunchdProvider { self.control = nil }
self.markReferralControlDisconnected()
}
metricsPoller = Task { [weak self] in
while !Task.isCancelled {
try? await Task.sleep(nanoseconds: LocalStatusObservationPolicy.pollIntervalNanoseconds)
try? await client.send(.metricsRequest)
try? await client.send(.statusRequest)
if let port = ProviderConfig.readHTTPPort() {
await self?.applyProviderSnapshot(port: port)
}
await self?.requestReferralStatusIfDue()
}
}
try? await client.send(.statusRequest)
try? await client.send(.metricsRequest)
await requestReferralStatusIfDue()
}
/// Attach a strictly read-only Malibu client to the launchd-owned CLI.
/// Failure is non-fatal because HTTP health/status remains the lifecycle
/// source; the control socket adds the CLI-authenticated earnings view.
private func attachInstalledProviderControlIfAvailable() async {
guard monitorsLaunchdProvider, control == nil else { return }
let client = ControlSocketClient(socketPath: ProviderPaths.current.controlSocket.path)
do {
try await client.connect(timeout: 2)
} catch {
await client.close()
return
}
guard monitorsLaunchdProvider, !isShuttingDown else {
await client.close()
return
}
control = client
eventStreamTask?.cancel()
eventStreamTask = Task { [weak self] in
for await frame in client.stream {
guard let self, !Task.isCancelled, self.control === client else { return }
self.consume(frame)
}
await client.close()
guard let self, self.control === client else { return }
if self.monitorsLaunchdProvider { self.control = nil }
self.markReferralControlDisconnected()
}
try? await client.send(.statusRequest)
try? await client.send(.metricsRequest)
await requestReferralStatusIfDue()
}
@discardableResult
private func requestReferralStatusIfDue() async -> Bool {
guard snapshot.hasTrustedReferralBoundary(), let control else { return false }
let now = Date()
guard ReferralRefreshPolicy.shouldRequest(
now: now,
lastRequestedAt: lastReferralRefreshRequestedAt
) else { return false }
lastReferralRefreshRequestedAt = now
beginReferralAction()
do {
try await control.send(.referralStatusRequest)
return true
} catch {
markReferralControlDisconnected()
return false
}
}
func beginReferralAction() {
referralStatusExpiryTask?.cancel()
referralStatusExpiryTask = nil
snapshot.referralActionInProgress = true
referralActionWatchdog.arm { [weak self] in
guard let self else { return }
self.snapshot.referralActionInProgress = false
self.referralStatusExpiryTask?.cancel()
self.referralStatusExpiryTask = nil
self.snapshot.referralStatus = nil
self.snapshot.referralAvailability = self.snapshot.hasTrustedReferralBoundary()
? .unavailable
: .unsupported