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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
import Foundation

enum AgentRunCheckpointUpdate: Sendable, Equatable {
  case phase(AgentRunPhase)
  case activeCall(AgentToolCall, phase: AgentRunPhase)
  case counters(toolCallsUsed: Int, modelTurns: Int)
  case completedReceipt(
    AgentToolReceipt,
    toolCallsUsed: Int,
    modelTurns: Int
  )
}

struct AgentLoopCallbacks: Sendable {
  let normalizeTool: @Sendable (AgentToolCall) async throws -> AgentToolCall
  let executeTool: @Sendable (AgentToolCall) async throws -> AgentToolResult
  let requestApproval:
    @MainActor @Sendable (ToolApprovalRequest) async -> Bool
  let emit: @MainActor @Sendable (AgentEvent) -> Void
  let modelProgress:
    @MainActor @Sendable (DolphinGenerationProgress) -> Void
  let checkpoint:
    @MainActor @Sendable (AgentRunCheckpointUpdate) async throws -> Void

  init(
    normalizeTool: @escaping @Sendable (AgentToolCall) async throws -> AgentToolCall,
    executeTool: @escaping @Sendable (AgentToolCall) async throws -> AgentToolResult,
    requestApproval: @escaping @MainActor @Sendable (
      ToolApprovalRequest
    ) async -> Bool,
    emit: @escaping @MainActor @Sendable (AgentEvent) -> Void,
    modelProgress: @escaping @MainActor @Sendable (
      DolphinGenerationProgress
    ) -> Void,
    checkpoint: @escaping @MainActor @Sendable (
      AgentRunCheckpointUpdate
    ) async throws -> Void = { _ in }
  ) {
    self.normalizeTool = normalizeTool
    self.executeTool = executeTool
    self.requestApproval = requestApproval
    self.emit = emit
    self.modelProgress = modelProgress
    self.checkpoint = checkpoint
  }
}

enum AgentRunOutcome: Sendable, Equatable {
  case succeeded
  case failed
}

struct AgentRunResult: Sendable, Equatable {
  let finalText: String
  let outcome: AgentRunOutcome
  let modelTurns: Int
  let toolCalls: Int
  let trustedToolResults: Int
  let failedToolCalls: Int
}

private struct AgentFinalPresentation: Sendable {
  let text: String
  let outcome: AgentRunOutcome
  let status: AgentEventStatus
  let title: String
  let detail: String
}

enum AgentLoopError: LocalizedError, Sendable, Equatable {
  case timeLimitReached
  case emptyFinalResponse

  var errorDescription: String? {
    switch self {
    case .timeLimitReached:
      "The assistant reached its time limit."
    case .emptyFinalResponse:
      "The model returned an empty final response."
    }
  }
}

actor AgentLoop {
  private let runtime: any DolphinModelRuntimeProtocol
  private let dateProvider: any DateProviding

  init(
    runtime: any DolphinModelRuntimeProtocol,
    dateProvider: any DateProviding = SystemDateProvider()
  ) {
    self.runtime = runtime
    self.dateProvider = dateProvider
  }

  func run(
    runID: UUID,
    conversation: [AssistantMessage],
    memoryContext: [MemoryItem] = [],
    settings: AgentSettings,
    toolDefinitions: [AgentToolDefinition],
    callbacks: AgentLoopCallbacks
  ) async throws -> AgentRunResult {
    try Task.checkCancellation()
    let limits = sanitized(settings)
    let clock = ContinuousClock()
    let deadline = clock.now.advanced(
      by: .seconds(limits.maxRunSeconds)
    )
    let networkEligibleTools = toolDefinitions.filter {
      $0.risk != .networkRead || limits.networkAccessEnabled
    }
    let latestUserText = conversation.last(where: { $0.role == .user })?.content ?? ""
    var requestPlan = AgentRequestRouter.plan(for: latestUserText)
    let availableToolIDs = Set(networkEligibleTools.map(\.id))
    let canonicalAvailableIDs = availableToolIDs.intersection(
      AgentRequestRouter.canonicalToolIDs
    )
    // Protocol-test and embedding clients may supply a wholly custom registry.
    // The production registry always has canonical IDs, so only the custom-only
    // surface bypasses production deterministic routing.
    if canonicalAvailableIDs.isEmpty, !availableToolIDs.isEmpty {
      requestPlan = AgentRequestPlan(
        initialToolCall: nil,
        eligibleToolIDs: availableToolIDs
      )
    }
    var selectedToolIDs = requestPlan.eligibleToolIDs
    selectedToolIDs.formUnion(requestPlan.plannedToolCalls.map(\.name))
    // Custom definitions used by embedders and protocol tests remain available.
    // The production canonical surface is intent-scoped.
    if canonicalAvailableIDs.isEmpty {
      selectedToolIDs = availableToolIDs
    } else {
      selectedToolIDs.formUnion(
        availableToolIDs.subtracting(AgentRequestRouter.canonicalToolIDs)
      )
    }
    let tools = networkEligibleTools.filter {
      selectedToolIDs.contains($0.id)
    }
    let definitionsByID = Dictionary(
      uniqueKeysWithValues: tools.map { ($0.id, $0) }
    )
    var plannedToolCalls = requestPlan.plannedToolCalls
    let plannedToolIDs = Set(plannedToolCalls.map(\.name))
    let modelTools = tools.filter { definition in
      !plannedToolIDs.contains(definition.id)
    }
    let emitter = AgentEventEmitter(runID: runID, sink: callbacks.emit)
    var scratchpad: [DolphinPromptMessage] = []
    var signatures: Set<String> = []
    var modelTurns = 0
    var toolCalls = 0
    var trustedToolResults = 0
    var failedToolCalls = 0
    var receipts: [AgentToolReceipt] = []
    var attemptedToolAction = false

    await emitter.emit(
      kind: .run,
      status: .running,
      title: "Run started",
      detail: "Bounded to \(limits.maxToolSteps) tool steps and \(limits.maxNewTokens) output tokens per turn. Cancellation is requested at the \(limits.maxRunSeconds)-second deadline."
    )
    try await callbacks.checkpoint(.phase(.routing))
    try Task.checkCancellation()

    await emitter.emit(
      kind: .run,
      status: .information,
      title: "Plan prepared",
      detail: requestPlan.auditSummary
    )

    if requestPlan.mode == .deterministic,
      plannedToolCalls.count > limits.maxToolSteps
    {
      try await callbacks.checkpoint(.phase(.finalizing))
      await emitter.emit(
        kind: .run,
        status: .failed,
        title: "Plan exceeds action limit",
        detail: "The deterministic plan requires \(plannedToolCalls.count) steps, but this run allows \(limits.maxToolSteps). No action was executed."
      )
      return AgentRunResult(
        finalText: "This request needs \(plannedToolCalls.count) verified actions, but the current limit is \(limits.maxToolSteps). Increase the tool-step limit or split the request.",
        outcome: .failed,
        modelTurns: 0,
        toolCalls: 0,
        trustedToolResults: 0,
        failedToolCalls: 0
      )
    }

    for _ in 0..<limits.maxToolSteps {
      try Task.checkCancellation()
      try checkDeadline(deadline)

      if requestPlan.mode == .deterministic, plannedToolCalls.isEmpty {
        return try await finishDeterministicPlan(
          requestPlan,
          receipts: receipts,
          modelTurns: modelTurns,
          toolCalls: toolCalls,
          trustedToolResults: trustedToolResults,
          failedToolCalls: failedToolCalls,
          emitter: emitter,
          callbacks: callbacks
        )
      }

      let call: AgentToolCall
      if !plannedToolCalls.isEmpty {
        let routedCall = plannedToolCalls.removeFirst()
        call = routedCall
        await emitter.emit(
          kind: .run,
          status: .information,
          title: "Request routed",
          detail: definitionsByID[routedCall.name]?.displayName
            ?? "Unavailable required tool: \(routedCall.name)"
        )
        try await callbacks.checkpoint(
          .activeCall(routedCall, phase: .routing)
        )
        try Task.checkCancellation()
      } else {
        try await callbacks.checkpoint(.phase(.modelGeneration))
        try Task.checkCancellation()
        let turn = try await generateTurn(
          conversation: conversation,
          memoryContext: memoryContext,
          scratchpad: scratchpad,
          systemPrompt: limits.systemPrompt,
          tools: modelTools,
          maxNewTokens: limits.maxNewTokens,
          emitter: emitter,
          progress: callbacks.modelProgress
        )
        modelTurns += 1
        try await callbacks.checkpoint(
          .counters(toolCallsUsed: toolCalls, modelTurns: modelTurns)
        )
        try Task.checkCancellation()
        try checkDeadline(deadline)

        let parsedCall: AgentToolCall?
        do {
          parsedCall = try ToolCallParser.parse(turn.text)
        } catch {
          attemptedToolAction = true
          toolCalls += 1
          failedToolCalls += 1
          try await callbacks.checkpoint(
            .counters(toolCallsUsed: toolCalls, modelTurns: modelTurns)
          )
          await emitter.emit(
            kind: .tool,
            status: .failed,
            title: "Invalid tool request",
            detail: error.localizedDescription
          )
          scratchpad.append(.assistant(turn.text))
          scratchpad.append(
            .user(
              "Tool protocol error: \(error.localizedDescription) Return either one valid tool call or a final answer."
            )
          )
          continue
        }

        guard let parsedCall else {
          if attemptedToolAction && failedToolCalls > 0 {
            try await callbacks.checkpoint(.phase(.finalizing))
            let safeFailure = partialFailureText(
              "I couldn’t complete every requested action safely. Review Activity for the denied or invalid step, then adjust permissions or try again.",
              receipts: receipts
            )
            await emitter.emit(
              kind: .run,
              status: .failed,
              title: "Run stopped safely",
              detail: "At least one requested action did not produce a trusted result."
            )
            return AgentRunResult(
              finalText: safeFailure,
              outcome: .failed,
              modelTurns: modelTurns,
              toolCalls: toolCalls,
              trustedToolResults: trustedToolResults,
              failedToolCalls: failedToolCalls
            )
          }
          let finalText = try presentationModelText(
            from: turn.text,
            receipts: receipts
          )
          let presentation = finalPresentation(
            modelText: finalText,
            receipts: receipts
          )
          try await callbacks.checkpoint(.phase(.finalizing))
          await emitter.emit(
            kind: .run,
            status: presentation.status,
            title: presentation.title,
            detail: presentation.detail + " · " + completionDetail(
              modelTurns: modelTurns,
              toolCalls: toolCalls,
              trustedToolResults: trustedToolResults,
              failedToolCalls: failedToolCalls
            )
          )
          return AgentRunResult(
            finalText: presentation.text,
            outcome: presentation.outcome,
            modelTurns: modelTurns,
            toolCalls: toolCalls,
            trustedToolResults: trustedToolResults,
            failedToolCalls: failedToolCalls
          )
        }
        call = parsedCall
      }

      attemptedToolAction = true
      toolCalls += 1
      try await callbacks.checkpoint(
        .counters(toolCallsUsed: toolCalls, modelTurns: modelTurns)
      )
      try Task.checkCancellation()
      guard let definition = definitionsByID[call.name] else {
        failedToolCalls += 1
        scratchpad.append(.assistantToolCall(call))
        await emitter.emit(
          kind: .tool,
          status: .denied,
          title: "Unknown tool blocked",
          detail: call.name
        )
        scratchpad.append(
          .toolResponse(errorObservation("Unknown tool: \(call.name)"))
        )
        continue
      }

      let normalizedCall: AgentToolCall
      do {
        normalizedCall = try await callbacks.normalizeTool(call)
      } catch {
        failedToolCalls += 1
        scratchpad.append(.assistantToolCall(call))
        await emitter.emit(
          kind: .tool,
          status: .failed,
          title: "Invalid arguments",
          detail: "\(definition.displayName): \(error.localizedDescription)"
        )
        scratchpad.append(
          .toolResponse(errorObservation(error.localizedDescription))
        )
        continue
      }
      scratchpad.append(.assistantToolCall(normalizedCall))
      try await callbacks.checkpoint(
        .activeCall(normalizedCall, phase: .routing)
      )
      try Task.checkCancellation()

      guard signatures.insert(normalizedCall.signature).inserted else {
        failedToolCalls += 1
        await emitter.emit(
          kind: .tool,
          status: .denied,
          title: "Duplicate action blocked",
          detail: definition.displayName
        )
        scratchpad.append(
          .toolResponse(errorObservation("Duplicate tool call blocked."))
        )
        continue
      }

      switch AgentPolicy.decision(for: definition, settings: limits) {
      case .deny(let reason):
        failedToolCalls += 1
        await emitter.emit(
          kind: .tool,
          status: .denied,
          title: "Action denied by policy",
          detail: "\(definition.displayName): \(reason)"
        )
        scratchpad.append(.toolResponse(errorObservation(reason)))
        continue

      case .requireApproval(let reason):
        let createdAt = dateProvider.now()
        let request = ToolApprovalRequest(
          runID: runID,
          call: normalizedCall,
          toolName: definition.displayName,
          reason: reason,
          createdAt: createdAt,
          expiresAt: min(
            createdAt.addingTimeInterval(10 * 60),
            createdAt.addingTimeInterval(
              remainingSeconds(until: deadline, clock: clock)
            )
          )
        )
        await emitter.emit(
          kind: .approval,
          status: .awaitingApproval,
          title: "Approval requested",
          detail: definition.displayName
        )
        try await callbacks.checkpoint(
          .activeCall(normalizedCall, phase: .awaitingApproval)
        )
        try Task.checkCancellation()
        let approved = await callbacks.requestApproval(request)
        try Task.checkCancellation()
        guard approved, !request.isExpired(at: dateProvider.now()) else {
          failedToolCalls += 1
          await emitter.emit(
            kind: .approval,
            status: .denied,
            title: approved ? "Approval expired" : "Action denied",
            detail: definition.displayName
          )
          scratchpad.append(
            .toolResponse(
              errorObservation(
                approved ? "Approval expired." : "The user denied this action."
              )
            )
          )
          continue
        }
        await emitter.emit(
          kind: .approval,
          status: .succeeded,
          title: "Approved once",
          detail: definition.displayName
        )

      case .allow:
        break
      }

      try checkDeadline(deadline)
      try await callbacks.checkpoint(
        .activeCall(normalizedCall, phase: .toolExecution)
      )
      try Task.checkCancellation()
      await emitter.emit(
        kind: .tool,
        status: .running,
        title: "Running tool",
        detail: definition.displayName
      )
      do {
        let rawResult = try await callbacks.executeTool(normalizedCall)
        // Reads do not create side effects, so a background/stop cancellation
        // must be observed before their result becomes trusted evidence. Local
        // writes retain the existing atomic mutation-plus-receipt boundary.
        switch definition.risk {
        case .readOnly, .sensitiveRead, .networkRead:
          try Task.checkCancellation()
        case .localWrite:
          break
        }
        let result = rawResult.bounded(
          toMaximumCharacters: definition.maxOutputCharacters
        )
        if result.succeeded {
          guard
            let receipt = AgentToolReceipt(
              runID: runID,
              call: normalizedCall,
              definition: definition,
              result: result,
              completedAt: dateProvider.now()
            )
          else {
            failedToolCalls += 1
            await emitter.emit(
              kind: .tool,
              status: .failed,
              title: "Tool result rejected",
              detail: "The successful result could not be recorded safely."
            )
            scratchpad.append(
              .toolResponse(
                errorObservation(
                  "The tool result could not be recorded safely."
                )
              )
            )
            try Task.checkCancellation()
            continue
          }
          guard AgentVerifiedAnswerRenderer.acceptsAsTrustedReceipt(receipt)
          else {
            failedToolCalls += 1
            await emitter.emit(
              kind: .tool,
              status: .failed,
              title: "Tool result rejected",
              detail: "The canonical observation did not match the normalized call and expected schema."
            )
            scratchpad.append(
              .toolResponse(
                errorObservation(
                  "The tool observation failed canonical schema or call-correlation validation."
                )
              )
            )
            try Task.checkCancellation()
            continue
          }
          trustedToolResults += 1
          receipts.append(receipt)
          await emitter.emit(
            kind: .tool,
            status: .succeeded,
            title: "Tool completed",
            detail: receipt.evidenceJSON,
            receipt: receipt
          )
          try await callbacks.checkpoint(
            .completedReceipt(
              receipt,
              toolCallsUsed: toolCalls,
              modelTurns: modelTurns
            )
          )
        } else {
          failedToolCalls += 1
          await emitter.emit(
            kind: .tool,
            status: .failed,
            title: "Tool failed",
            detail: result.displayText
          )
        }
        scratchpad.append(.toolResponse(result.modelText))
        // A completed call is receipted before cancellation is observed. Local
        // writes commit this same receipt atomically with their mutation.
        try Task.checkCancellation()
      } catch is CancellationError {
        throw CancellationError()
      } catch {
        failedToolCalls += 1
        await emitter.emit(
          kind: .tool,
          status: .failed,
          title: "Tool failed",
          detail: error.localizedDescription
        )
        scratchpad.append(
          .toolResponse(errorObservation(error.localizedDescription))
        )
      }
    }

    if requestPlan.mode == .deterministic {
      return try await finishDeterministicPlan(
        requestPlan,
        receipts: receipts,
        modelTurns: modelTurns,
        toolCalls: toolCalls,
        trustedToolResults: trustedToolResults,
        failedToolCalls: failedToolCalls,
        emitter: emitter,
        callbacks: callbacks
      )
    }

    try checkDeadline(deadline)
    await emitter.emit(
      kind: .run,
      status: .information,
      title: "Action limit reached",
      detail: "Generating a final answer without additional tools."
    )
    try await callbacks.checkpoint(.phase(.modelGeneration))
    try Task.checkCancellation()
    let finalTurn = try await generateTurn(
      conversation: conversation,
      memoryContext: memoryContext,
      scratchpad: scratchpad,
      systemPrompt: limits.systemPrompt,
      tools: [],
      maxNewTokens: limits.maxNewTokens,
      emitter: emitter,
      progress: callbacks.modelProgress
    )
    modelTurns += 1
    try await callbacks.checkpoint(
      .counters(toolCallsUsed: toolCalls, modelTurns: modelTurns)
    )
    try Task.checkCancellation()
    try checkDeadline(deadline)

    let finalRequestedAnotherTool: Bool
    do {
      finalRequestedAnotherTool = try ToolCallParser.parse(finalTurn.text) != nil
    } catch {
      finalRequestedAnotherTool = true
    }
    if finalRequestedAnotherTool {
      failedToolCalls += 1
      try await callbacks.checkpoint(.phase(.finalizing))
      let safeFailure = partialFailureText(
        "I reached the action limit before I could finish. Review Activity and try a narrower request.",
        receipts: receipts
      )
      await emitter.emit(
        kind: .run,
        status: .failed,
        title: "Run limit reached",
        detail: "A further tool request was blocked."
      )
      return AgentRunResult(
        finalText: safeFailure,
        outcome: .failed,
        modelTurns: modelTurns,
        toolCalls: toolCalls,
        trustedToolResults: trustedToolResults,
        failedToolCalls: failedToolCalls
      )
    }

    if attemptedToolAction && failedToolCalls > 0 {
      try await callbacks.checkpoint(.phase(.finalizing))
      let safeFailure = partialFailureText(
        "I couldn’t complete every requested action safely. Review Activity for the denied or invalid step, then adjust permissions or try again.",
        receipts: receipts
      )
      await emitter.emit(
        kind: .run,
        status: .failed,
        title: "Run stopped safely",
        detail: "At least one requested action did not produce a trusted result."
      )
      return AgentRunResult(
        finalText: safeFailure,
        outcome: .failed,
        modelTurns: modelTurns,
        toolCalls: toolCalls,
        trustedToolResults: trustedToolResults,
        failedToolCalls: failedToolCalls
      )
    }

    let finalText = try presentationModelText(
      from: finalTurn.text,
      receipts: receipts
    )
    let presentation = finalPresentation(modelText: finalText, receipts: receipts)
    try await callbacks.checkpoint(.phase(.finalizing))
    await emitter.emit(
      kind: .run,
      status: presentation.status,
      title: presentation.title,
      detail: presentation.detail + " · " + completionDetail(
        modelTurns: modelTurns,
        toolCalls: toolCalls,
        trustedToolResults: trustedToolResults,
        failedToolCalls: failedToolCalls
      )
    )
    return AgentRunResult(
      finalText: presentation.text,
      outcome: presentation.outcome,
      modelTurns: modelTurns,
      toolCalls: toolCalls,
      trustedToolResults: trustedToolResults,
      failedToolCalls: failedToolCalls
    )
  }

  private func finishDeterministicPlan(
    _ plan: AgentRequestPlan,
    receipts: [AgentToolReceipt],
    modelTurns: Int,
    toolCalls: Int,
    trustedToolResults: Int,
    failedToolCalls: Int,
    emitter: AgentEventEmitter,
    callbacks: AgentLoopCallbacks
  ) async throws -> AgentRunResult {
    let receivedCallIDs = Set(receipts.map { $0.call.id })
    let missingCalls = plan.plannedToolCalls.filter {
      !receivedCallIDs.contains($0.id)
    }
    guard failedToolCalls == 0, missingCalls.isEmpty else {
      try await callbacks.checkpoint(.phase(.finalizing))
      let missingNames = missingCalls.map(\.name).joined(separator: ", ")
      let reason = missingNames.isEmpty
        ? "At least one deterministic action failed or was denied."
        : "Missing verified receipt(s) for: \(missingNames)."
      let text = partialFailureText(
        "I couldn’t complete the full verified plan. \(reason) Review Activity for the failed or denied step.",
        receipts: receipts
      )
      await emitter.emit(
        kind: .run,
        status: .failed,
        title: "Verified plan incomplete",
        detail: reason
      )
      return AgentRunResult(
        finalText: text,
        outcome: .failed,
        modelTurns: modelTurns,
        toolCalls: toolCalls,
        trustedToolResults: trustedToolResults,
        failedToolCalls: max(failedToolCalls, missingCalls.count)
      )
    }

    let presentation = finalPresentation(modelText: "", receipts: receipts)
    try await callbacks.checkpoint(.phase(.finalizing))
    await emitter.emit(
      kind: .run,
      status: presentation.status,
      title: presentation.title,
      detail: presentation.detail + " · " + completionDetail(
        modelTurns: modelTurns,
        toolCalls: toolCalls,
        trustedToolResults: trustedToolResults,
        failedToolCalls: failedToolCalls
      )
    )
    return AgentRunResult(
      finalText: presentation.text,
      outcome: presentation.outcome,
      modelTurns: modelTurns,
      toolCalls: toolCalls,
      trustedToolResults: trustedToolResults,
      failedToolCalls: failedToolCalls
    )
  }

  private func generateTurn(
    conversation: [AssistantMessage],
    memoryContext: [MemoryItem],
    scratchpad: [DolphinPromptMessage],
    systemPrompt: String,
    tools: [AgentToolDefinition],
    maxNewTokens: Int,
    emitter: AgentEventEmitter,
    progress: @MainActor @Sendable (DolphinGenerationProgress) -> Void
  ) async throws -> DolphinGenerationResult {
    let prompt = try await AgentContextWindowBuilder.build(
      systemPrompt: systemPrompt,
      conversation: conversation,
      memoryContext: memoryContext,
      scratchpad: scratchpad,
      tools: tools,
      maxNewTokens: maxNewTokens,
      runtime: runtime
    )
    var detail =
      "Prompt \(prompt.promptTokens) tokens · output budget \(maxNewTokens) tokens"
    if prompt.droppedMessages > 0 {
      detail += " · dropped \(prompt.droppedMessages) older messages"
    }
    if prompt.droppedScratchpadMessages > 0 {
      detail += " · dropped \(prompt.droppedScratchpadMessages) older action messages"
    }
    if prompt.droppedMemoryItems > 0 {
      detail += " · dropped \(prompt.droppedMemoryItems) older memories"
    }
    await emitter.emit(
      kind: .model,
      status: .running,
      title: "Model turn",
      detail: detail
    )
    let result = try await runtime.generate(
      renderedPrompt: prompt.renderedPrompt,
      maxNewTokens: maxNewTokens,
      progress: progress
    )
    let information = await runtime.information()
    await emitter.emit(
      kind: .model,
      status: .succeeded,
      title: "Model response",
      detail:
        "\(result.generatedTokens) tokens · first token \(format(result.timeToFirstTokenSeconds)) s · \(format(result.tokensPerSecond)) tok/s · \(information.modelIdentifier)"
    )
    return result
  }

  private func checkDeadline(_ deadline: ContinuousClock.Instant) throws {
    try Task.checkCancellation()
    guard ContinuousClock.now < deadline else {
      throw AgentLoopError.timeLimitReached
    }
  }

  private func remainingSeconds(
    until deadline: ContinuousClock.Instant,
    clock: ContinuousClock
  ) -> TimeInterval {
    let duration = clock.now.duration(to: deadline)
    let seconds = Double(duration.components.seconds)
      + Double(duration.components.attoseconds)
        / 1_000_000_000_000_000_000
    return min(max(seconds, 0), 10 * 60)
  }

  private func sanitized(_ settings: AgentSettings) -> AgentSettings {
    settings.sanitized()
  }

  /// Canonical receipts can produce a complete verified presentation even if
  /// the small model emits an empty or copied-receipt follow-up. Custom tool
  /// results still require nonempty model prose because there is no trusted
  /// renderer for their schema.
  private func presentationModelText(
    from rawText: String,
    receipts: [AgentToolReceipt]
  ) throws -> String {
    let value = AssistantChatText.cleaned(rawText)
    if !value.isEmpty { return value }
    if AgentVerifiedAnswerRenderer.requiresDeterministicAnswer(for: receipts)
      || verifiedWriteText(receipts) != nil
    {
      return ""
    }
    throw AgentLoopError.emptyFinalResponse
  }

  private func errorObservation(_ message: String) -> String {
    JSONValue.object([
      "error": .string(String(message.prefix(500))),
      "ok": .bool(false),
    ]).canonicalJSON
  }

  private func finalPresentation(
    modelText: String,
    receipts: [AgentToolReceipt]
  ) -> AgentFinalPresentation {
    guard !receipts.isEmpty else {
      return AgentFinalPresentation(
        text: modelText,
        outcome: .succeeded,
        status: .succeeded,
        title: "Answer completed",
        detail: "No tool was needed"
      )
    }

    let localWriteCount = receipts.count { $0.risk == .localWrite }
    let canonicalReadRequired =
      AgentVerifiedAnswerRenderer.requiresDeterministicAnswer(for: receipts)
    let canonicalReadText = canonicalReadRequired
      ? AgentVerifiedAnswerRenderer.readAnswer(for: receipts)
      : nil
    if canonicalReadRequired, canonicalReadText == nil {
      return AgentFinalPresentation(
        text: partialFailureText(
          "A verified result couldn’t be displayed safely.",
          receipts: receipts
        ),
        outcome: .failed,
        status: .failed,
        title: "Verified result rejected",
        detail: "A canonical tool observation did not match its trusted schema"
      )
    }

    let writeText = verifiedWriteText(receipts)
    if localWriteCount > 0, writeText == nil {
      return AgentFinalPresentation(
        text: partialFailureText(
          "A completed local change couldn’t be summarized safely.",
          receipts: receipts
        ),
        outcome: .failed,
        status: .failed,
        title: "Verified action summary unavailable",
        detail: "The local change remains receipted in Activity"
      )
    }

    let authoritativeText = groundedReceiptText(receipts) ?? modelText
    let readOnlyCount = receipts.count - localWriteCount
    return AgentFinalPresentation(
      text: authoritativeText,
      outcome: .succeeded,
      status: .succeeded,
      title: localWriteCount > 0
        ? "Verified actions completed"
        : "Verified read completed",
      detail: "\(receipts.count) trusted result(s): \(localWriteCount) local change(s), \(readOnlyCount) read-only"
    )
  }

  private func partialFailureText(
    _ message: String,
    receipts: [AgentToolReceipt]
  ) -> String {
    guard !receipts.isEmpty else { return message }
    if let groundedText = groundedReceiptText(receipts) {
      return "\(message)\n\nVerified before the stop:\n\(groundedText)"
    }
    let hasLocalWrites = receipts.contains { $0.risk == .localWrite }
    let completed = hasLocalWrites
      ? "Some local changes completed before the stop."
      : "Some read-only steps completed before the stop."
    return "\(message)\n\n\(completed) Review Activity for the verified details."
  }

  private func groundedReceiptText(
    _ receipts: [AgentToolReceipt]
  ) -> String? {
    var parts: [String] = []
    if let writeText = verifiedWriteText(receipts) {
      parts.append(writeText)
    }
    if let readText = AgentVerifiedAnswerRenderer.readAnswer(for: receipts) {
      parts.append(readText)
    }
    return parts.isEmpty ? nil : parts.joined(separator: "\n")
  }

  private func verifiedWriteText(
    _ receipts: [AgentToolReceipt]
  ) -> String? {
    let lines = receipts.compactMap { receipt -> String? in
      guard receipt.risk == .localWrite else { return nil }
      switch receipt.call.name {
      case "memory_save":
        guard let content = receipt.call.arguments["content"]?.stringValue else {
          return "Memory saved."
        }
        return "Got it — I’ll remember: “\(content)”."
      case "task_add":
        guard let title = receipt.call.arguments["title"]?.stringValue else {
          return "Task added."
        }
        return "Added “\(title)” to your tasks."
      case "task_complete":
        return "Task marked complete."
      default:
        let text = receipt.displayText.trimmingCharacters(
          in: .whitespacesAndNewlines
        )
        return text.isEmpty ? nil : text + (text.hasSuffix(".") ? "" : ".")
      }
    }
    return lines.isEmpty ? nil : lines.joined(separator: "\n")
  }

  private func completionDetail(
    modelTurns: Int,
    toolCalls: Int,
    trustedToolResults: Int,
    failedToolCalls: Int
  ) -> String {
    "\(modelTurns) model turns · \(toolCalls) tool calls · \(trustedToolResults) trusted results · \(failedToolCalls) failed or denied"
  }

  private func format(_ value: Double) -> String {
    String(format: "%.2f", value)
  }
}

private actor AgentEventEmitter {
  private let runID: UUID
  private let sink: @MainActor @Sendable (AgentEvent) -> Void
  private var sequence = 0

  init(
    runID: UUID,
    sink: @escaping @MainActor @Sendable (AgentEvent) -> Void
  ) {
    self.runID = runID
    self.sink = sink
  }

  func emit(
    kind: AgentEventKind,
    status: AgentEventStatus,
    title: String,
    detail: String,
    receipt: AgentToolReceipt? = nil
  ) async {
    sequence += 1
    let event = AgentEvent(
      runID: runID,
      sequence: sequence,
      kind: kind,
      status: status,
      title: title,
      detail: detail,
      receipt: receipt
    )
    await sink(event)
  }
}