forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDesktopCoordinatorService.swift
More file actions
1163 lines (1074 loc) · 42.2 KB
/
Copy pathDesktopCoordinatorService.swift
File metadata and controls
1163 lines (1074 loc) · 42.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Foundation
protocol DesktopCoordinatorRuntimeControlling: Sendable {
func directControlTool(
clientId: String,
harnessMode: String,
name: String,
input: RuntimeJSONPayloadBox
) async throws -> String
}
extension AgentRuntimeProcess: DesktopCoordinatorRuntimeControlling {
func directControlTool(
clientId: String,
harnessMode: String,
name: String,
input: RuntimeJSONPayloadBox
) async throws -> String {
try await directControlTool(
clientId: clientId,
harnessMode: harnessMode,
name: name,
input: input,
authorizationSnapshot: nil)
}
}
enum DesktopCoordinatorOriginSurface: String, CaseIterable, Sendable {
case mainChat = "main_chat"
case floatingBar = "floating_bar"
case realtime = "realtime"
case taskChat = "task_chat"
init(surfaceKind: String?) {
switch surfaceKind {
case "floating_bar": self = .floatingBar
case "realtime", "realtime_voice": self = .realtime
case "task_chat", "workstream": self = .taskChat
default: self = .mainChat
}
}
}
struct DesktopCoordinatorAwarenessSnapshot: Codable {
let generatedAt: String
let source: String
let runtimeControlTools: [String]
let automation: DesktopCoordinatorAutomationProjection
let sessions: [DesktopCoordinatorSessionProjection]
let debugDispatches: [DesktopCoordinatorDispatchProjection]
let runtimeError: String?
}
struct DesktopCoordinatorAutomationProjection: Codable {
let bridgeEnabled: Bool
let bridgePort: UInt16
let bundleIdentifier: String
let appState: String
let selectedTab: String?
let askOmiOpen: Bool
let floatingBarVisible: Bool
}
struct DesktopCoordinatorSessionProjection: Codable {
let sessionId: String?
let title: String
let surfaceKind: String?
let externalRefKind: String?
let externalRefId: String?
let status: String
let runId: String?
let runStatus: String?
let runMode: String?
let attemptId: String?
let provider: String?
let updatedAt: String?
let source: String
}
struct DesktopCoordinatorActionQueueItem: Codable {
let id: String
let rank: Int
let kind: String
let title: String
let status: String
let sessionId: String?
let runId: String?
let dispatchId: String?
let source: String
}
struct DesktopCoordinatorOpenLoops: Codable {
let generatedAt: String
let items: [DesktopCoordinatorActionQueueItem]
}
enum DesktopCoordinatorIntentProposal: Equatable {
case answerInline
case spawnAgent
case continueRun
case clarify(missing: [String])
var payload: [String: Any] {
switch self {
case .answerInline:
return ["intent": "answer_inline"]
case .spawnAgent:
return ["intent": "spawn_agent"]
case .continueRun:
return ["intent": "continue_run"]
case .clarify(let missing):
return ["intent": "clarify", "missing": missing]
}
}
}
struct DesktopCoordinatorIntentSyntaxFacts: Equatable {
var delegationNegated: Bool?
var explicitSessionId: String?
var explicitRunId: String?
var parentRunId: String?
var explicitProvider: String?
var requestedAgentCount: Int?
var payload: [String: Any] {
var result: [String: Any] = [:]
if let delegationNegated { result["delegationNegated"] = delegationNegated }
if let explicitSessionId { result["explicitSessionId"] = explicitSessionId }
if let explicitRunId { result["explicitRunId"] = explicitRunId }
if let parentRunId { result["parentRunId"] = parentRunId }
if let explicitProvider { result["explicitProvider"] = explicitProvider }
if let requestedAgentCount { result["requestedAgentCount"] = requestedAgentCount }
return result
}
}
struct DesktopCoordinatorRouteDecision: Equatable {
let decisionId: String
let intent: String
let surfaceKind: String
let snapshotVersion: String
let reasonCode: String
let explanation: String
let sessionId: String?
let runId: String?
let requestedProvider: String?
let requestedAgentCount: Int?
let parentRunId: String?
let missing: [String]
let rejectionCode: String?
}
struct DesktopCoordinatorDispatchProjection: Codable {
let dispatchId: String
let kind: String
let status: String
let title: String
let decisionPrompt: String
let recommendedDefault: String?
let sourceSessionId: String?
let sourceRunId: String?
let createdAt: String
let resolvedAt: String?
let resolution: String?
let source: String
}
struct DesktopCoordinatorCompletionDeltaItem: Codable {
let id: String
let title: String
let surfaceKind: String?
let externalRefKind: String?
let externalRefId: String?
let status: String
let sessionId: String?
let runId: String?
let completedAtMs: Int?
let finalText: String
/// The prompt that spawned the run, when the kernel payload carries it. A
/// completion is meaningless to the model without the question it answers.
let inputPrompt: String?
init(
id: String,
title: String,
surfaceKind: String?,
externalRefKind: String?,
externalRefId: String?,
status: String,
sessionId: String?,
runId: String?,
completedAtMs: Int?,
finalText: String,
inputPrompt: String? = nil
) {
self.id = id
self.title = title
self.surfaceKind = surfaceKind
self.externalRefKind = externalRefKind
self.externalRefId = externalRefId
self.status = status
self.sessionId = sessionId
self.runId = runId
self.completedAtMs = completedAtMs
self.finalText = finalText
self.inputPrompt = inputPrompt
}
}
struct DesktopCoordinatorCompletionDelta: Codable {
let ids: [String]
let prompt: String
let completedAtHighWaterMs: Int?
// Artifacts produced by the newly-completed sub-agents in this delta, so the
// consuming surface (main chat / notch) can render them as resource cards on
// the parent's response.
var artifacts: [AgentArtifactProjection] = []
}
struct DesktopCoordinatorSpawnedAgent: Codable {
let sessionId: String
let runId: String
let attemptId: String?
let title: String
let externalRefId: String?
}
struct DesktopCoordinatorSpawnBatch: Codable {
let requestedAgentCount: Int
let agents: [DesktopCoordinatorSpawnedAgent]
}
struct DesktopCoordinatorProducerJournalDescriptor: Sendable {
static let schemaVersion = 1
let surface: AgentSurfaceReference
let continuityKey: String
let pillId: UUID
let userText: String
let assistantText: String
let objective: String
let title: String
var dictionary: [String: Any] {
[
"schemaVersion": Self.schemaVersion,
"surface": [
"surfaceKind": surface.surfaceKind,
"externalRefKind": surface.externalRefKind,
"externalRefId": surface.externalRefId,
],
"continuityKey": continuityKey,
"pillId": pillId.uuidString,
"userText": userText,
"assistantText": assistantText,
"objective": objective,
"title": title,
]
}
}
struct DesktopCoordinatorAgentRunInspection: Codable {
let sessionId: String?
let runId: String?
let attemptId: String?
let provider: String?
let status: String
let finalText: String?
let errorMessage: String?
let artifacts: [AgentArtifactProjection]
}
@MainActor
final class DesktopCoordinatorService {
static let shared = DesktopCoordinatorService()
private enum ToolName {
static let listAgentSessions = "list_agent_sessions"
static let getAgentRun = "get_agent_run"
static let buildAwarenessSnapshot = "build_desktop_awareness_snapshot"
static let listActionQueue = "list_desktop_action_queue"
static let getOpenLoops = "get_desktop_open_loops"
static let routeIntent = "route_desktop_intent"
static let createDispatch = "create_desktop_dispatch"
static let resolveDispatch = "resolve_desktop_dispatch"
static let cancelAgentRun = "cancel_agent_run"
static let inspectAgentArtifacts = "inspect_agent_artifacts"
static let sendAgentMessage = "send_agent_message"
static let spawnAgent = "spawn_agent"
static let runAgentAndWait = "run_agent_and_wait"
static let setDesktopAttentionOverride = "set_desktop_attention_override"
}
private let runtime: DesktopCoordinatorRuntimeControlling
private let clientId: String
private let harnessModeProvider: @MainActor () -> String
private let formatter = ISO8601DateFormatter()
private let checkpointDefaults: UserDefaults
private let completionCheckpointPrefix = "desktopCoordinator.completedAgentDelta.seenRunIds"
private let completionHighWaterPrefix = "desktopCoordinator.completedAgentDelta.highWaterMs"
init(
runtime: DesktopCoordinatorRuntimeControlling = AgentRuntimeProcess.shared,
clientId: String = "desktop-coordinator",
harnessModeProvider: @escaping @MainActor () -> String = AgentControlService.currentHarnessMode,
checkpointDefaults: UserDefaults = .standard
) {
self.runtime = runtime
self.clientId = clientId
self.harnessModeProvider = harnessModeProvider
self.checkpointDefaults = checkpointDefaults
}
func awarenessSnapshot() async -> DesktopCoordinatorAwarenessSnapshot {
let automationSnapshot = DesktopAutomationStateStore.shared.current()
do {
let raw = try await callRuntimeControlTool(ToolName.listAgentSessions, input: [:])
return DesktopCoordinatorAwarenessSnapshot(
generatedAt: nowString(),
source: "swift_projection",
runtimeControlTools: [ToolName.listAgentSessions],
automation: DesktopCoordinatorAutomationProjection(snapshot: automationSnapshot),
sessions: parseSessions(from: raw),
debugDispatches: [],
runtimeError: nil
)
} catch {
return DesktopCoordinatorAwarenessSnapshot(
generatedAt: nowString(),
source: "swift_projection",
runtimeControlTools: [ToolName.listAgentSessions],
automation: DesktopCoordinatorAutomationProjection(snapshot: automationSnapshot),
sessions: [],
debugDispatches: [],
runtimeError: error.localizedDescription
)
}
}
func awarenessSnapshotJSON(limit: Int = 50) async throws -> String {
try await callRuntimeControlTool(ToolName.buildAwarenessSnapshot, input: ["limit": limit])
}
func actionQueueJSON(limit: Int = 50) async throws -> String {
try await callRuntimeControlTool(ToolName.listActionQueue, input: ["limit": limit])
}
func openLoopsJSON(limit: Int = 50) async throws -> String {
try await callRuntimeControlTool(ToolName.getOpenLoops, input: ["limit": limit])
}
func routeIntent(
intent: String,
surfaceKind: String,
taskId: String? = nil,
snapshotVersion: String? = nil,
proposal: DesktopCoordinatorIntentProposal,
syntaxFacts: DesktopCoordinatorIntentSyntaxFacts? = nil
) async throws -> DesktopCoordinatorRouteDecision {
var input: [String: Any] = [
"utterance": intent,
"surfaceKind": surfaceKind.isEmpty ? "main_chat" : surfaceKind,
"proposal": proposal.payload,
]
if let taskId, !taskId.isEmpty {
input["taskId"] = taskId
}
if let snapshotVersion, !snapshotVersion.isEmpty {
input["snapshotVersion"] = snapshotVersion
}
if let syntaxFacts, !syntaxFacts.payload.isEmpty {
input["syntaxFacts"] = syntaxFacts.payload
}
let raw = try await callRuntimeControlTool(ToolName.routeIntent, input: input)
return try parseRouteDecision(from: raw)
}
func routeIntentJSON(
intent: String,
surfaceKind: String? = nil,
taskId: String? = nil,
snapshotVersion: String? = nil,
proposal: DesktopCoordinatorIntentProposal,
syntaxFacts: DesktopCoordinatorIntentSyntaxFacts? = nil
) async throws -> String {
var input: [String: Any] = [
"utterance": intent,
"surfaceKind": surfaceKind?.isEmpty == false ? surfaceKind! : "main_chat",
"proposal": proposal.payload,
]
if let taskId, !taskId.isEmpty { input["taskId"] = taskId }
if let snapshotVersion, !snapshotVersion.isEmpty { input["snapshotVersion"] = snapshotVersion }
if let syntaxFacts, !syntaxFacts.payload.isEmpty { input["syntaxFacts"] = syntaxFacts.payload }
return try await callRuntimeControlTool(ToolName.routeIntent, input: input)
}
func createDispatchJSON(
kind: String,
title: String,
decisionPrompt: String,
recommendedDefault: String? = nil,
sourceSessionId: String? = nil,
sourceRunId: String? = nil
) async throws -> String {
var input: [String: Any] = [
"kind": kind.isEmpty ? "routing_choice" : kind,
"priority": 50,
"title": title.isEmpty ? "Coordinator attention" : title,
"decisionPrompt": decisionPrompt.isEmpty ? "Review this coordinator attention item." : decisionPrompt,
]
if let recommendedDefault, !recommendedDefault.isEmpty { input["recommendedDefault"] = recommendedDefault }
if let sourceSessionId, !sourceSessionId.isEmpty { input["sourceSessionId"] = sourceSessionId }
if let sourceRunId, !sourceRunId.isEmpty { input["sourceRunId"] = sourceRunId }
return try await callRuntimeControlTool(ToolName.createDispatch, input: input)
}
func resolveDispatchJSON(dispatchId: String, resolution: String) async throws -> String {
try await callRuntimeControlTool(
ToolName.resolveDispatch,
input: [
"dispatchId": dispatchId,
"status": resolution == "cancelled" ? "cancelled" : "resolved",
"resolution": ["decision": resolution.isEmpty ? "resolved" : resolution],
]
)
}
func actionQueue() async -> [DesktopCoordinatorActionQueueItem] {
let snapshot = await awarenessSnapshot()
return deriveActionQueue(from: snapshot)
}
func openLoops() async -> DesktopCoordinatorOpenLoops {
let queue = await actionQueue()
let items = queue.filter { item in
["approval", "failed_run", "stale_or_active_run", "debug_dispatch"].contains(item.kind)
}
return DesktopCoordinatorOpenLoops(generatedAt: nowString(), items: items)
}
func inspectRun(runId: String) async throws -> String {
let trimmedRunId = runId.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmedRunId.isEmpty else {
throw NSError(
domain: "DesktopCoordinatorService",
code: 3,
userInfo: [NSLocalizedDescriptionKey: "runId is required to inspect an agent run"]
)
}
return try await callRuntimeControlTool(ToolName.getAgentRun, input: ["runId": trimmedRunId])
}
func cancelAgentRun(runId: String, reason: String = "Stopped by user") async throws -> String {
try await callRuntimeControlTool(
ToolName.cancelAgentRun,
input: ["runId": runId]
)
}
func spawnAgent(
objective: String,
title: String?,
pillId: UUID,
originSurface: DesktopCoordinatorOriginSurface,
provider: String?,
parentRunId: String?,
visible: Bool,
model: String?,
harnessMode: AgentHarnessMode?,
cwd: String?,
producerJournal: DesktopCoordinatorProducerJournalDescriptor? = nil
) async throws -> DesktopCoordinatorSpawnedAgent {
let batch = try await spawnAgents(
objective: objective,
title: title,
pillId: pillId,
requestedAgentCount: 1,
originSurface: originSurface,
provider: provider,
parentRunId: parentRunId,
visible: visible,
model: model,
harnessMode: harnessMode,
cwd: cwd,
producerJournal: producerJournal
)
guard let first = batch.agents.first else {
throw NSError(
domain: "DesktopCoordinatorService",
code: 2,
userInfo: [NSLocalizedDescriptionKey: "Background-agent spawn returned no agents"])
}
return first
}
func spawnAgents(
objective: String,
title: String?,
pillId: UUID?,
requestedAgentCount: Int,
originSurface: DesktopCoordinatorOriginSurface,
provider: String?,
parentRunId: String?,
visible: Bool,
model: String?,
harnessMode: AgentHarnessMode?,
cwd: String?,
producerJournal: DesktopCoordinatorProducerJournalDescriptor? = nil
) async throws -> DesktopCoordinatorSpawnBatch {
let boundedCount = max(1, min(requestedAgentCount, 8))
var metadata: [String: Any] = [
"uiProjection": visible ? "floating_bar" : "delegated_agent"
]
if let pillId {
metadata["pillId"] = pillId.uuidString
metadata["siblingGroupExternalRefId"] = pillId.uuidString
}
if let producerJournal {
metadata["producerJournal"] = producerJournal.dictionary
}
var input: [String: Any] = [
"objective": objective,
"visible": visible,
"requestedAgentCount": boundedCount,
"clientId": "desktop-floating-pill",
"originSurfaceKind": originSurface.rawValue,
"metadata": metadata,
]
if let pillId {
input["externalRefId"] = pillId.uuidString
}
if let title, !title.isEmpty { input["title"] = title }
if let provider, !provider.isEmpty { input["provider"] = provider }
if let parentRunId, !parentRunId.isEmpty { input["parentRunId"] = parentRunId }
if let model, !model.isEmpty { input["model"] = model }
if let harnessMode { input["adapterId"] = AgentRuntimeRouting.adapterId(for: harnessMode).rawValue }
if let cwd, !cwd.isEmpty { input["cwd"] = cwd }
let raw = try await callRuntimeControlTool(ToolName.spawnAgent, input: input)
return try parseSpawnedAgents(from: raw)
}
func dismissFloatingRunAttention(runId: String, reason: String = "Dismissed by user") async throws {
_ = try await callRuntimeControlTool(
ToolName.setDesktopAttentionOverride,
input: [
"subjectKind": "run",
"subjectId": runId,
"dismissed": true,
"reason": reason,
]
)
}
func continueAgent(
sessionId: String,
prompt: String,
originSurface: DesktopCoordinatorOriginSurface,
model: String?,
cwd: String?
) async throws -> DesktopCoordinatorAgentRunInspection {
var input: [String: Any] = [
"sessionId": sessionId,
"prompt": prompt,
"mode": "act",
"clientId": "desktop-floating-pill",
"originSurfaceKind": originSurface.rawValue,
"metadata": ["uiProjection": "floating_bar"],
]
if let model, !model.isEmpty { input["model"] = model }
if let cwd, !cwd.isEmpty { input["cwd"] = cwd }
let raw = try await callRuntimeControlTool(ToolName.sendAgentMessage, input: input)
return parseInspectedRun(from: raw)
}
func inspectAgentRun(runId: String) async throws -> DesktopCoordinatorAgentRunInspection {
parseInspectedRun(from: try await inspectRun(runId: runId))
}
func inspectArtifactsForRun(runId: String) async throws -> [AgentArtifactProjection] {
let trimmedRunId = runId.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmedRunId.isEmpty else {
throw NSError(
domain: "DesktopCoordinatorService",
code: 4,
userInfo: [NSLocalizedDescriptionKey: "runId is required to inspect agent artifacts"]
)
}
let raw = try await callRuntimeControlTool(
ToolName.inspectAgentArtifacts, input: ["runId": trimmedRunId, "limit": 100])
return try AgentArtifactProjection.parseList(fromToolResult: raw)
}
func peekCompletedAgentDelta(surfaceKind: String, limit: Int = 5) async -> DesktopCoordinatorCompletionDelta? {
await peekCompletedAgentDelta(surfaceKey: surfaceKind, surfaceLabel: surfaceKind, limit: limit)
}
func peekCompletedAgentDelta(surface: AgentSurfaceReference, limit: Int = 5) async
-> DesktopCoordinatorCompletionDelta?
{
await peekCompletedAgentDelta(surfaceKey: surface.key, surfaceLabel: surface.surfaceKind, limit: limit)
}
private func peekCompletedAgentDelta(surfaceKey: String, surfaceLabel: String, limit: Int) async
-> DesktopCoordinatorCompletionDelta?
{
do {
let raw = try await callRuntimeControlTool(ToolName.listAgentSessions, input: ["limit": 50])
let seen = Set(checkpointDefaults.stringArray(forKey: completionCheckpointKey(surfaceKey: surfaceKey)) ?? [])
let nowMs = currentTimeMs()
let highWaterKey = completionHighWaterKey(surfaceKey: surfaceKey)
let minCompletedAtMs = nowMs - CompletionDeltaPolicy.maxAgeMs(forSurfaceKind: surfaceLabel)
let highWaterMs: Int
if checkpointDefaults.object(forKey: highWaterKey) != nil {
highWaterMs = checkpointDefaults.integer(forKey: highWaterKey)
} else {
// First use starts at the bounded recent-window floor, not now. A parent
// chat may not ask for deltas until after its sub-agent finishes, and that
// first check still needs to surface the completed agent's resources.
highWaterMs = minCompletedAtMs
checkpointDefaults.set(minCompletedAtMs, forKey: highWaterKey)
}
let items = parseCompletionDeltaItems(from: raw)
.filter {
guard let completedAtMs = $0.completedAtMs else { return false }
return completedAtMs > highWaterMs
&& completedAtMs >= minCompletedAtMs
&& !seen.contains($0.id)
}
.sorted { ($0.completedAtMs ?? 0) < ($1.completedAtMs ?? 0) }
.prefix(limit)
.map { $0 }
guard !items.isEmpty else { return nil }
return DesktopCoordinatorCompletionDelta(
ids: items.map(\.id),
prompt: CompletionDeltaPolicy.format(surfaceKind: surfaceLabel, items: items, nowMs: nowMs),
completedAtHighWaterMs: items.compactMap(\.completedAtMs).max(),
artifacts: await collectDeltaArtifacts(for: items)
)
} catch {
logError("DesktopCoordinatorService: completed agent delta unavailable", error: error)
return nil
}
}
func acknowledgeCompletedAgentDelta(surfaceKind: String, ids: [String]) {
guard !ids.isEmpty else { return }
checkpointCompletionDelta(surfaceKind: surfaceKind, ids: ids, completedAtHighWaterMs: nil)
}
func acknowledgeCompletedAgentDelta(surfaceKind: String, ids: [String], completedAtHighWaterMs: Int?) {
guard !ids.isEmpty else { return }
checkpointCompletionDelta(surfaceKind: surfaceKind, ids: ids, completedAtHighWaterMs: completedAtHighWaterMs)
}
func acknowledgeCompletedAgentDelta(surface: AgentSurfaceReference, ids: [String]) {
guard !ids.isEmpty else { return }
checkpointCompletionDelta(surfaceKey: surface.key, ids: ids, completedAtHighWaterMs: nil)
}
func acknowledgeCompletedAgentDelta(surface: AgentSurfaceReference, ids: [String], completedAtHighWaterMs: Int?) {
guard !ids.isEmpty else { return }
checkpointCompletionDelta(surfaceKey: surface.key, ids: ids, completedAtHighWaterMs: completedAtHighWaterMs)
}
func runtimeControlManifest() -> [String] {
[
ToolName.listAgentSessions,
ToolName.getAgentRun,
ToolName.buildAwarenessSnapshot,
ToolName.listActionQueue,
ToolName.getOpenLoops,
ToolName.routeIntent,
ToolName.createDispatch,
ToolName.resolveDispatch,
ToolName.cancelAgentRun,
ToolName.inspectAgentArtifacts,
ToolName.sendAgentMessage,
ToolName.spawnAgent,
ToolName.runAgentAndWait,
ToolName.setDesktopAttentionOverride,
]
}
func listFloatingAgentPills(limit: Int = 50) async throws -> [[String: Any]] {
let raw = try await callRuntimeControlTool(
ToolName.listAgentSessions,
input: ["limit": limit, "surfaceKind": "floating_bar"]
)
guard let data = raw.data(using: .utf8),
let object = try JSONSerialization.jsonObject(with: data) as? [String: Any],
object["ok"] as? Bool == true
else {
return []
}
return object["floating_agent_pills"] as? [[String: Any]] ?? []
}
func floatingAgentStatusSummary(limit: Int = 8) async -> String {
do {
let pills = try await listFloatingAgentPills(limit: limit)
guard !pills.isEmpty else {
return "No floating agent pills are running or recently finished."
}
let lines = pills.map { entry -> String in
let title = stringValue(entry["title"]) ?? "Background agent"
let id = (stringValue(entry["id"]) ?? "").prefix(8)
let status = stringValue(entry["status"]) ?? "unknown"
let activity = stringValue(entry["latestActivity"]) ?? ""
return "- \(title) [\(id)]: \(status); \(activity)"
}
return "Floating agent pills:\n" + lines.joined(separator: "\n")
} catch {
logError("DesktopCoordinatorService: floating agent status unavailable", error: error)
return ""
}
}
private func callRuntimeControlTool(_ name: String, input: [String: Any]) async throws -> String {
try await runtime.directControlTool(
clientId: clientId,
harnessMode: harnessModeProvider(),
name: name,
input: RuntimeJSONPayloadBox(input)
)
}
private func deriveActionQueue(from snapshot: DesktopCoordinatorAwarenessSnapshot)
-> [DesktopCoordinatorActionQueueItem]
{
var items: [DesktopCoordinatorActionQueueItem] = []
for dispatch in snapshot.debugDispatches {
items.append(
DesktopCoordinatorActionQueueItem(
id: dispatch.dispatchId,
rank: 1,
kind: "debug_dispatch",
title: dispatch.title,
status: dispatch.status,
sessionId: dispatch.sourceSessionId,
runId: dispatch.sourceRunId,
dispatchId: dispatch.dispatchId,
source: dispatch.source
)
)
}
for session in snapshot.sessions {
let status = session.runStatus ?? session.status
let id = session.runId ?? session.sessionId ?? "\(session.title)_\(session.status)"
if status == "waiting_approval" {
items.append(queueItem(id: id, rank: 1, kind: "approval", session: session, status: status))
} else if ["failed", "orphaned", "timed_out"].contains(status) {
items.append(queueItem(id: id, rank: 2, kind: "failed_run", session: session, status: status))
} else if isActive(status) {
items.append(queueItem(id: id, rank: 4, kind: "stale_or_active_run", session: session, status: status))
} else if ["succeeded", "completed"].contains(status) {
items.append(queueItem(id: id, rank: 5, kind: "completed_run_review", session: session, status: status))
}
}
return items.sorted {
if $0.rank == $1.rank { return $0.id < $1.id }
return $0.rank < $1.rank
}
}
private func queueItem(
id: String,
rank: Int,
kind: String,
session: DesktopCoordinatorSessionProjection,
status: String
) -> DesktopCoordinatorActionQueueItem {
DesktopCoordinatorActionQueueItem(
id: id,
rank: rank,
kind: kind,
title: session.title,
status: status,
sessionId: session.sessionId,
runId: session.runId,
dispatchId: nil,
source: session.source
)
}
private func parseSessions(from raw: String) -> [DesktopCoordinatorSessionProjection] {
guard let object = jsonObject(from: raw), object["ok"] as? Bool != false else {
return []
}
let sessions = object["sessions"] as? [[String: Any]] ?? []
return sessions.map { summary in
let session = summary["session"] as? [String: Any] ?? [:]
let latestRun = summary["latestRun"] as? [String: Any] ?? [:]
let activeRun = summary["activeRun"] as? [String: Any] ?? [:]
let selectedRun = activeRun.isEmpty ? latestRun : activeRun
let latestAttempt = summary["latestAttempt"] as? [String: Any] ?? [:]
let activeAttempt = summary["activeAttempt"] as? [String: Any] ?? [:]
let selectedAttempt = activeRun.isEmpty ? latestAttempt : activeAttempt
let sessionStatus = stringValue(session["status"]) ?? "unknown"
let title =
stringValue(session["title"])
?? stringValue(session["surfaceKind"])
?? "Untitled agent"
return DesktopCoordinatorSessionProjection(
sessionId: stringValue(session["sessionId"]),
title: title,
surfaceKind: stringValue(session["surfaceKind"]),
externalRefKind: stringValue(session["externalRefKind"]),
externalRefId: stringValue(session["externalRefId"]),
status: sessionStatus,
runId: stringValue(selectedRun["runId"]),
runStatus: stringValue(selectedRun["status"]),
runMode: stringValue(selectedRun["mode"]),
attemptId: stringValue(selectedAttempt["attemptId"]),
provider: stringValue((session["metadata"] as? [String: Any])?["provider"]),
updatedAt: stringValue(session["updatedAt"]) ?? stringValue(selectedRun["updatedAt"]),
source: "runtime_control_tool:list_agent_sessions"
)
}
}
private func parseCompletionDeltaItems(from raw: String) -> [DesktopCoordinatorCompletionDeltaItem] {
guard let object = jsonObject(from: raw), object["ok"] as? Bool != false else {
return []
}
let sessions = object["sessions"] as? [[String: Any]] ?? []
return sessions.compactMap { summary in
let session = summary["session"] as? [String: Any] ?? [:]
let latestRun = summary["latestRun"] as? [String: Any] ?? [:]
guard !latestRun.isEmpty else { return nil }
let status = stringValue(latestRun["status"]) ?? stringValue(session["status"]) ?? "unknown"
// Only runs that actually completed carry deliverable work. Terminal-but-
// not-succeeded statuses (cancelled, timed_out, orphaned, failed) used to
// pass here and were injected as "newly completed work" with a synthetic
// placeholder body — noise that pushed the model to weave dead threads
// into the live answer.
guard CompletionDeltaPolicy.eligibleStatuses.contains(status) else { return nil }
let runId = stringValue(latestRun["runId"])
let sessionId = stringValue(session["sessionId"])
let completedAtMs = intValue(latestRun["completedAtMs"])
// When runId is absent, include completedAtMs so that each distinct
// terminal run completion carries a unique id even if the same session
// produces multiple completions over time.
let id = runId ?? (sessionId.map { "\($0)_\(completedAtMs ?? 0)" })
guard let id else { return nil }
let surfaceKind = stringValue(session["surfaceKind"])
guard surfaceKind != "main_chat" else { return nil }
let title =
stringValue(session["title"])
?? surfaceKind
?? "Completed agent"
let sanitizedTitle = sanitizePromptLine(title, maxLength: 120)
let finalText =
stringValue(latestRun["finalText"])
?? stringValue(latestRun["errorMessage"])
?? stringValue((latestRun["result"] as? [String: Any])?["text"])
?? "\(sanitizedTitle) finished with status \(status). Inspect the agentRef for details if the user asks."
let inputPrompt = sanitizePromptLine(
stringValue((latestRun["input"] as? [String: Any])?["prompt"]) ?? "",
maxLength: 200)
return DesktopCoordinatorCompletionDeltaItem(
id: id,
title: sanitizedTitle,
surfaceKind: surfaceKind,
externalRefKind: stringValue(session["externalRefKind"]),
externalRefId: stringValue(session["externalRefId"]),
status: status,
sessionId: sessionId,
runId: runId,
completedAtMs: completedAtMs,
finalText: sanitizePromptLine(finalText, maxLength: 1_200),
inputPrompt: inputPrompt.isEmpty ? nil : inputPrompt
)
}
}
private func checkpointCompletionDelta(surfaceKind: String, ids: [String], completedAtHighWaterMs: Int?) {
checkpointCompletionDelta(surfaceKey: surfaceKind, ids: ids, completedAtHighWaterMs: completedAtHighWaterMs)
}
private func checkpointCompletionDelta(surfaceKey: String, ids: [String], completedAtHighWaterMs: Int?) {
let key = completionCheckpointKey(surfaceKey: surfaceKey)
var seen = checkpointDefaults.stringArray(forKey: key) ?? []
seen.append(contentsOf: ids)
checkpointDefaults.set(Array(seen.suffix(100)), forKey: key)
if let completedAtHighWaterMs {
let highWaterKey = completionHighWaterKey(surfaceKey: surfaceKey)
checkpointDefaults.set(
max(checkpointDefaults.integer(forKey: highWaterKey), completedAtHighWaterMs), forKey: highWaterKey)
}
}
private func completionCheckpointKey(surfaceKind: String) -> String {
completionCheckpointKey(surfaceKey: surfaceKind)
}
private func completionCheckpointKey(surfaceKey: String) -> String {
"\(completionCheckpointPrefix).\(surfaceKey.isEmpty ? "unknown" : surfaceKey)"
}
private func completionHighWaterKey(surfaceKey: String) -> String {
"\(completionHighWaterPrefix).\(surfaceKey.isEmpty ? "unknown" : surfaceKey)"
}
/// Fetches the artifacts produced by each successfully-completed sub-agent in
/// the delta so the consuming surface can render them as resource cards.
/// Bounded by the delta `limit`; failed runs are skipped (no artifacts to show).
private func collectDeltaArtifacts(for items: [DesktopCoordinatorCompletionDeltaItem]) async
-> [AgentArtifactProjection]
{
let inspectable = items.filter { item in
guard let runId = item.runId, !runId.isEmpty else { return false }
return ["succeeded", "completed"].contains(item.status)
}
guard !inspectable.isEmpty else { return [] }
var collected: [AgentArtifactProjection] = []
var seenIds = Set<String>()
for item in inspectable {
guard let runId = item.runId else { continue }
let inspection: DesktopCoordinatorAgentRunInspection
do {
inspection = try await inspectAgentRun(runId: runId)
} catch {
let fallbackArtifacts = (try? await inspectArtifactsForRun(runId: runId)) ?? []
for artifact in fallbackArtifacts where artifact.isUserFacingResult {
guard seenIds.insert(artifact.artifactId).inserted else { continue }
collected.append(artifact)
}
continue
}
if inspection.status == "failed", inspection.artifacts.isEmpty {
let fallbackArtifacts = (try? await inspectArtifactsForRun(runId: runId)) ?? []
for artifact in fallbackArtifacts where artifact.isUserFacingResult {
guard seenIds.insert(artifact.artifactId).inserted else { continue }
collected.append(artifact)
}
continue
}
for artifact in inspection.artifacts where artifact.isUserFacingResult {
guard seenIds.insert(artifact.artifactId).inserted else { continue }
collected.append(artifact)
}
}
return collected
}
private func isActive(_ status: String) -> Bool {
["queued", "starting", "running", "waiting_input", "waiting_approval", "cancelling"].contains(status)
}
private func nowString() -> String {
formatter.string(from: Date())
}
private func jsonObject(from raw: String) -> [String: Any]? {
guard let data = raw.data(using: .utf8) else { return nil }
return try? JSONSerialization.jsonObject(with: data) as? [String: Any]
}
private func parseRouteDecision(from raw: String) throws -> DesktopCoordinatorRouteDecision {
guard let object = jsonObject(from: raw) else {
throw NSError(
domain: "DesktopCoordinatorService",
code: 5,
userInfo: [NSLocalizedDescriptionKey: "Invalid kernel route response"])
}
if object["ok"] as? Bool == false {
throw NSError(
domain: "DesktopCoordinatorService",
code: 5,
userInfo: [
NSLocalizedDescriptionKey: runtimeErrorMessage(from: object)
?? "Kernel route request was rejected"
])
}
let route = object["route"] as? [String: Any] ?? [:]
guard
let decisionId = stringValue(route["decisionId"]),
let intent = stringValue(route["intent"]),
let surfaceKind = stringValue(route["surfaceKind"]),
let snapshotVersion = stringValue(route["snapshotVersion"]),
let reasonCode = stringValue(route["reasonCode"]),
let explanation = stringValue(route["explanation"])
else {
throw NSError(
domain: "DesktopCoordinatorService",
code: 5,
userInfo: [NSLocalizedDescriptionKey: "Kernel route response omitted typed decision fields"])
}
return DesktopCoordinatorRouteDecision(
decisionId: decisionId,
intent: intent,