Repository navigation
Expand file tree
/
Copy pathloop.go
More file actions
1856 lines (1699 loc) · 75 KB
/
Copy pathloop.go
File metadata and controls
1856 lines (1699 loc) · 75 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
package runtime
import (
"context"
"errors"
"fmt"
"log/slog"
"path/filepath"
"reflect"
"regexp"
"slices"
"strings"
"time"
"uuid"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"github.com/docker/docker-agent/pkg/agent"
"github.com/docker/docker-agent/pkg/chat"
"github.com/docker/docker-agent/pkg/httpclient"
"github.com/docker/docker-agent/pkg/model/provider"
"github.com/docker/docker-agent/pkg/modelsdev"
"github.com/docker/docker-agent/pkg/runtime/pricing"
"github.com/docker/docker-agent/pkg/runtime/toolexec"
"github.com/docker/docker-agent/pkg/session"
"github.com/docker/docker-agent/pkg/telemetry/genai"
"github.com/docker/docker-agent/pkg/tools"
bgagent "github.com/docker/docker-agent/pkg/tools/builtin/agent"
"github.com/docker/docker-agent/pkg/tools/builtin/backgroundjobs"
"github.com/docker/docker-agent/pkg/tools/builtin/plan"
"github.com/docker/docker-agent/pkg/tools/builtin/sessioncontext"
"github.com/docker/docker-agent/pkg/userconfig"
)
// registerDefaultTools wires up the built-in tool handlers (session context,
// background agents) into the runtime's tool dispatch map. Caller-bound
// handlers (transfer_task, handoff, change_model, ...) are bound per call in
// processToolCalls.
func (r *LocalRuntime) registerDefaultTools() {
r.toolMap[sessioncontext.ToolNameListSessions] = r.handleListSessions
r.toolMap[sessioncontext.ToolNameReadSession] = r.handleReadSession
r.bgAgents.RegisterHandlers(func(name string, fn func(context.Context, *session.Session, tools.ToolCall) (*tools.ToolCallResult, error)) {
r.toolMap[name] = func(ctx context.Context, sess *session.Session, tc tools.ToolCall, _ EventSink, _ tools.Runtime) (*tools.ToolCallResult, error) {
return fn(ctx, sess, tc)
}
})
}
// emitHookDrivenShutdown fans out the standard Error /
// notification(level=error) / on_error stanzas when a blocking hook
// (e.g. post_tool_use or before_llm_call) signals run termination.
func (r *LocalRuntime) emitHookDrivenShutdown(
ctx context.Context,
a *agent.Agent,
sess *session.Session,
message string,
events EventSink,
) {
if message == "" {
// aggregate() may leave Result.Message empty on a deny
// verdict (e.g. exit 2 without stderr, or block without a
// reason).
message = "Agent terminated by a hook."
}
events.Emit(ErrorWithCodeForSession(sess.ID, ErrorCodeHookBlocked, message))
r.notifyError(ctx, a, sess.ID, message)
}
// finalizeEventChannel performs cleanup at the end of a RunStream goroutine:
// emits the StreamStopped event, fires hooks, records telemetry, restores the
// previous elicitation channel, and closes the events channel.
//
// reason is one of the turnEndReason* constants (or
// StreamStopReasonMaxIterations), or empty when the stream exits before any
// turn classifies it (e.g. tool setup failure), and classifies how the
// stream ended (e.g. "normal", "error", "canceled"). It is surfaced in
// the StreamStoppedEvent so external consumers (boards, dashboards) can
// distinguish between successful completion, crashes, and user-initiated
// stops without reverse-engineering reconnect failures.
//
// Ordering (decided in #3074): StreamStopped is emitted before the session-end
// hooks and telemetry run, not after, so consumers react immediately (the TUI
// stops its spinner and drains its queued messages) instead of waiting behind
// potentially slow user-configured session_end hooks. This is safe because
// those hooks dispatch with a nil event sink and never emit onto this channel,
// so StreamStopped stays the last event a consumer observes. The authoritative
// "all cleanup done" signal is the channel close (done last, in
// restoreAndClose) that terminates a `for range`, not the StreamStopped event.
//
// Delivery: StreamStopped is delivered with a bounded blocking send (see
// [boundedChannelSink]) rather than a plain non-blocking one. A consumer
// still draining the channel — including one that already got Esc or
// otherwise cancelled its context, since the TUI keeps draining until close —
// reliably receives it. It is dropped only if nothing accepts it within
// streamStoppedTimeout, i.e. the consumer has genuinely abandoned the channel
// (#4136 fixed the non-blocking drop that caused this; #3070 is why the send
// is bounded rather than unbounded). Consumers must still rely on the channel
// close, not on receiving StreamStopped, as the one guaranteed terminal
// signal.
func (r *LocalRuntime) finalizeEventChannel(ctx context.Context, sess *session.Session, reason string, finishReason chat.FinishReason, prevElicitationCh chan Event, events chan<- Event) {
a := r.resolveSessionAgent(sess)
if ctx.Err() != nil && reason == "" {
reason = turnEndReasonCanceled
}
// Bounded, not unbounded: an abandoned consumer must not hang teardown
// forever (#3070), but a live one draining past cancellation must still
// get this event (#4136) — so this never selects on ctx.Done().
stopped := StreamStopped(sess.ID, a.Name(), reason).(*StreamStoppedEvent)
stopped.FinishReason = finishReason
bounded(&channelSink{ch: events}, r.streamStoppedTimeout()).Emit(stopped)
// Execute session end hooks with a context that won't be cancelled so
// cleanup hooks run even when the stream was interrupted (e.g. Ctrl+C).
r.executeSessionEndHooks(context.WithoutCancel(ctx), sess, a)
// on_user_input means "the agent is now waiting for the user". Only a
// root interactive stream hands control back to a user when it ends;
// sub-session and non-interactive teardowns (background agents, MCP
// serve, A2A, evals) have nobody to wait for and must not fire it (#4004).
if !sess.IsSubSession() && !sess.NonInteractive {
r.executeOnUserInputHooks(ctx, a, sess.ID, "stream stopped")
}
r.telemetry.RecordSessionEnd(ctx)
r.elicitation.restoreAndClose(events, prevElicitationCh)
}
// streamStoppedTimeout returns the bounded-delivery deadline for the
// StreamStopped emit in finalizeEventChannel, falling back to
// defaultStreamStoppedDeliveryTimeout when unset (e.g. a *LocalRuntime built
// directly as a struct literal in tests, bypassing NewLocalRuntime).
func (r *LocalRuntime) streamStoppedTimeout() time.Duration {
if r.streamStoppedDeliveryTimeout > 0 {
return r.streamStoppedDeliveryTimeout
}
return defaultStreamStoppedDeliveryTimeout
}
// RunStream starts the agent's interaction loop and returns a channel of events.
// The returned channel is closed when the loop terminates (success, error, or
// context cancellation). Each iteration: sends messages to the model, streams
// the response, executes any tool calls, and loops until the model signals stop
// or the iteration limit is reached.
func (r *LocalRuntime) RunStream(ctx context.Context, sess *session.Session) <-chan Event {
return r.runStream(ctx, sess, defaultIdleStreamRetryPolicy(), nil)
}
func (r *LocalRuntime) streamStartAgentName(sess *session.Session) string {
// Routed root sessions restart at the shared entry agent in beginRouting;
// ignore any RouteAgent left over from the previous request.
if sess.Routed() && sess.AgentName == "" {
return r.currentAgentName()
}
return r.sessionAgentName(sess)
}
// runStream starts the run loop for sess. resume is the checkpoint the run is
// taken up from; it is nil for a new run.
func (r *LocalRuntime) runStream(ctx context.Context, sess *session.Session, idleRetryPolicy idleStreamRetryPolicy, resume *checkpoint) <-chan Event {
slog.DebugContext(ctx, "Starting runtime stream", "agent", r.streamStartAgentName(sess), "session_id", sess.ID)
events := make(chan Event, defaultEventChannelCapacity)
rootStream := !sess.IsSubSession()
if rootStream {
r.activeRootStreams.Add(1)
// Install a fresh budget for this run. Sub-sessions deliberately
// skip this: they share the root's tracker so a fan-out spends
// against one wallet rather than one allowance per child.
r.ensureBudget()
}
// Register before the run goroutine starts so the session is listed in
// the /context team view (and targetable for explicit compaction) for
// the whole lifetime of its stream.
entry := r.registerLiveSessionWithIdleRetry(sess, idleRetryPolicy)
// Persist the root before tools can append root-owned state.
out := r.observe(ctx, sess, events)
go func() {
if rootStream {
defer r.activeRootStreams.Add(-1)
}
r.runStreamLoop(withObserverFlush(ctx, events), sess, entry, resume, events)
}()
return out
}
// runStreamLoop is the body of RunStream. Pulled out of the anonymous
// goroutine so it has a real name in stack traces and is easier to navigate
// in editors.
func (r *LocalRuntime) runStreamLoop(ctx context.Context, sess *session.Session, liveEntry *liveSessionEntry, resume *checkpoint, events chan Event) {
sink := &channelSink{ch: events}
ctx = context.WithValue(ctx, scratchpadRootKey{}, liveEntry.treeRootID)
// Seed the cagent session ID at the run-loop boundary so any
// gateway-bound HTTP call originating from this loop can correlate
// back to the originating session. Plumbing happens in
// pkg/httpclient/userAgentTransport, gated on `X-Cagent-Forward`.
initialAgent := r.streamStartAgentName(sess)
ctx = httpclient.ContextWithSessionID(ctx, sess.ID)
r.telemetry.RecordSessionStart(ctx, initialAgent, sess.ID)
// Seed `gen_ai.conversation.id` into baggage at the session
// boundary. Every span the runtime, providers, MCP client, RAG,
// sandbox, evaluation, hooks, and (downstream) any subprocess
// or remote service create from here on will pick it up
// automatically without per-helper plumbing — and the value
// rides over W3C `baggage` so it crosses MCP / sandbox /
// HTTP boundaries too.
ctx = genai.WithConversationID(ctx, sess.ID)
// A non-interactive session (background_agents via runCollecting, MCP
// serve, A2A, evals) has no live UI that can answer an OAuth elicitation,
// and runCollecting drops events rather than forwarding them. If a remote
// MCP toolset needs first-time OAuth, blocking on an elicitation that
// nobody can answer hangs the sub-agent forever (issue #3200): the
// connection context is detached with context.WithoutCancel, so not even
// cancellation can unblock it. Mark the context so toolset Start() fails
// fast with an AuthorizationRequiredError — the same fast-fail the startup
// tool probe uses (see EmitStartupInfo) — instead of eliciting. A real user
// authorizes such servers from an interactive turn (or transfer_task, which
// keeps NonInteractive=false and forwards the dialog to the TUI).
if sess.NonInteractive {
ctx = tools.WithoutInteractivePrompts(ctx)
}
// runtime.session is the root span for one stream. gen_ai.* keys
// are emitted alongside the legacy `agent` / `session.id` keys
// so existing dashboards keep matching while spec-aware tooling
// can filter by `gen_ai.conversation.id` and
// `cagent.agent.name`. Legacy keys drop out under
// OTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_latest_experimental.
sessionAttrs := []attribute.KeyValue{
attribute.String(genai.AttrConversationID, sess.ID),
attribute.String(genai.AttrAgentNameRuntime, initialAgent),
}
if genai.EmitLegacyAttributes() {
sessionAttrs = append(sessionAttrs,
attribute.String("agent", initialAgent),
attribute.String("session.id", sess.ID),
)
}
ctx, sessionSpan := r.startSpan(ctx, "runtime.session", trace.WithAttributes(sessionAttrs...))
defer sessionSpan.End()
// Swap in this stream's events channel for elicitation and save the
// previous one so it can be restored on teardown. This allows nested
// RunStream calls to temporarily own elicitation without losing the
// parent's channel.
prevElicitationCh := r.elicitation.swap(events)
// streamReason records the exit reason from the final turn so
// finalizeEventChannel can surface it in the StreamStoppedEvent.
// It is copied from ls.exitReason after each runTurn.
//
// Register the cleanup defer immediately after the swap so every exit
// path finalizes, including the early returns below (tool setup
// failure, a user_prompt_submit hook signalling termination). Without
// this, those early returns leak the events channel: observe's
// forwarder goroutine never exits, a `for range RunStream(...)`
// consumer hangs forever, and the elicitation bridge is left pointing
// at this dead stream's channel.
var streamReason string
var streamFinishReason chat.FinishReason
// rec is the record a durable runtime keeps of the run; it is nil, and
// does nothing, on any other.
rec := r.newRunRecord(sess, events, resume)
ctx = withRunRecord(ctx, rec)
defer func() {
// A panic is a crash: the record stays, so the run is found again
// and the crash counted. The stream is still closed before the
// panic goes on.
crash := recover()
if crash == nil {
if err := rec.settle(ctx); err != nil {
// The run got to its end and its record is still there: it
// did not end as far as the store knows.
streamReason = r.stopUnrecorded(ctx, sess, r.resolveSessionAgent(sess), err, sink)
}
}
r.finalizeEventChannel(ctx, sess, streamReason, streamFinishReason, prevElicitationCh, events)
if crash != nil {
panic(crash)
}
}()
// Unregister from the live-session registry and execute any accepted
// explicit-compaction request before the stream lifecycle closes.
// Registered after the finalize defer so it runs first (LIFO): an
// accepted request is processed before StreamStopped is emitted and
// the events channel closes, so it can never be stranded.
defer r.finishLiveSession(ctx, liveEntry)
// Subscribe this stream to shared-plan change notifications for its
// whole lifecycle. Registered once here rather than per iteration, and
// the deferred release runs (LIFO) before finalizeEventChannel closes
// the events channel — on every exit path, including errors and
// cancellation — so no subscription outlives its sink.
defer r.subscribePlanChanges(sess, sink)()
defer r.subscribeToolsetEvents(sess, sink)()
// A run does some things once, when it starts: it announces its prompt,
// fires the hooks of a new run and looks for a cached answer. A run taken
// up past that point has its state back instead.
starting := resume == nil || resume.Phase == phaseStarting
// Routed conversations restart at the entry agent and let before_agent_run
// pick the agent that actually runs, before anything is prepared for it.
var route *routeState
if starting {
route = r.beginRouting(sess)
} else {
route = resume.State.Route
}
a := r.turnAgent(sess, resume)
// The prompt is what the user last wrote, when a run that is starting
// has that to answer. A new run announces it; one taken up again has
// announced it already.
var prompt chat.Message
var promptEvent *UserMessageEvent
if starting && sess.SendUserMessage {
if msg, position, ok := sess.Prompt(); ok {
prompt = msg
if resume == nil {
promptEvent = userMessageEvent(prompt, sess.ID, position).(*UserMessageEvent)
}
}
}
if resume == nil {
if err := rec.begin(ctx, promptEvent); err != nil {
streamReason = r.stopUnrecorded(ctx, sess, a, err, sink)
return
}
}
emitPrompt := func() {
if promptEvent != nil {
sink.Emit(promptEvent)
}
}
var stop *routeStop
switch {
case route == nil:
stop = r.routingUnsupported(route, a)
case starting:
// The prompt precedes any route taken by a before_agent_run hook.
emitPrompt()
a, stop = r.activateAgent(ctx, sess, a, route, sink)
}
if stop != nil {
streamReason = r.stopRouting(ctx, sess, a, stop, sink)
return
}
ls := &loopState{
idleRetry: liveEntry.idleRetry,
compaction: newCompactionController(r, sess, sink, userconfig.Get()),
}
defer ls.compaction.Close(ctx)
if starting {
// session_start fires once per run. Its AdditionalContext
// (typically the AddEnvironmentInfo env block) is held as transient
// extras and threaded into every model call below — never added to
// the visible transcript (with cache_stable_prompts it is persisted
// only in the instruction-context snapshot), to keep the transcript
// clean and the user message tail stable.
sessionStart := r.executeSessionStartHooks(ctx, sess, a, sink)
ls.runState = runState{
MaxIterations: sess.MaxIterations,
SessionStartMsgs: sessionStart.messages,
SessionStartLegacyMsgs: sessionStart.legacyMessages(),
SessionStartSources: sessionStart.sources,
Route: route,
}
} else {
ls.runState = resume.State
}
// Emit team information
sink.Emit(TeamInfo(r.agentDetailsFromTeam(ctx), a.Name()))
// Surface the run budget from the first frame, before any model call,
// so the configured ceilings are visible immediately rather than only
// after the first priced turn. A run that fails on its very first call
// (e.g. a bad API key) still shows its budget was active.
if b := r.currentBudget(); b != nil {
sink.Emit(BudgetUsage(sess.ID, a.Name(), b.snapshot()))
}
ctx = tools.WithHandlerScope(ctx, tools.HandlerScope{
Elicitation: r.elicitationHandler,
OAuthSuccess: func() {
sink.Emit(Authorization(tools.ElicitationActionAccept, r.resolveSessionAgent(sess).Name()))
},
})
r.emitAgentWarnings(a, sink)
for _, name := range r.team.AgentNames() {
if configured, err := r.team.Agent(name); err == nil {
r.configureToolsetHandlers(configured)
}
}
agentTools, err := r.getTools(ctx, sess, a, sessionSpan, sink, true)
if err != nil {
sink.Emit(ErrorWithCodeForSession(sess.ID, ErrorCodeToolFailed, fmt.Sprintf("failed to get tools: %v", err)))
return
}
// Record the catalogue size on the session span — answers "how
// many tools could this turn actually use?" without having to
// walk into per-toolset spans. Stamped after exclusion filters
// so the count matches what was offered to the model.
sessionSpan.SetAttributes(attribute.Int("cagent.agent.tools.count", len(agentTools)))
sink.Emit(ToolsetInfo(len(agentTools), false, a.Name()))
if route == nil {
emitPrompt()
}
if prompt.Role == chat.MessageRoleUser {
stop, msg, ctxMsgs := r.executeUserPromptSubmitHooks(ctx, sess, a, prompt.Content, sink)
if stop {
slog.WarnContext(ctx, "user_prompt_submit hook signalled run termination",
"agent", a.Name(), "session_id", sess.ID, "reason", msg)
r.emitHookDrivenShutdown(ctx, a, sess, msg, sink)
return
}
ls.UserPromptMsgs = ctxMsgs
}
sink.Emit(StreamStarted(sess.ID, a.Name()))
if starting && a.HasHarness() && rec == nil {
streamReason = r.runHarnessAgent(ctx, sess, a, sink)
return
}
// Response cache lookup. On a hit, replay the stored answer and
// skip the model entirely. The matching storage half is
// implemented as the cache_response stop-hook builtin (see
// runtime/cache.go and getHooksExecutor).
if starting && r.tryReplayCachedResponse(ctx, sess, a, sink) {
if ls.Route == nil {
return
}
// A replayed answer is a completion like any other: it may still route onward.
outcome, stop := r.routeCompletion(ctx, sess, a, sess.GetLastAssistantMessageContent(), ls, sink)
switch outcome {
case routeStopped:
streamReason = r.stopRouting(ctx, sess, a, stop, sink)
return
case routeFinished:
return
case routeContinued:
}
}
// Polling and waiting legitimately repeat identical arguments.
loopThreshold := sess.MaxConsecutiveToolCalls
if loopThreshold == 0 {
loopThreshold = 5 // default: always active
}
ls.loopDetector = toolexec.NewLoopDetector(loopThreshold,
bgagent.ToolNameViewBackgroundAgent,
bgagent.ToolNameListBackgroundAgents,
bgagent.ToolNameWaitBackgroundAgents,
backgroundjobs.ToolNameViewBackgroundJob,
)
ls.loopDetector.Restore(ls.Loop)
// A run taken up again enters its first turn at the step it was cut off
// in, with the answer that turn's model step had left.
from, answer := phaseModel, (*modelAnswer)(nil)
if !starting {
from, answer = resume.Phase, resume.Answer
}
// recorded says the record already stands where the run is: at the step
// it is taken up at. Saving it again would pass for progress.
recorded := !starting
for {
// A turn is prepared for its model step unless the run is taken up
// past it: what comes before the model is asked has no place between
// a model's tool calls and their results.
entering := from == phaseModel
// Pause the loop here if /pause has been toggled on. Any in-flight
// LLM request and its tool calls have already completed. Emit a
// RuntimePaused event right before blocking so the TUI can flip its
// indicator from "Pausing…" to "Paused".
if r.isPaused() {
sink.Emit(Paused(sess.ID, a.Name()))
if err := r.waitIfPaused(ctx); err != nil {
return
}
}
// Execute any explicitly requested (/context) compaction for this
// session now, at the iteration boundary: no model turn is in flight,
// so the compaction snapshot cannot race with messages being appended
// between the snapshot and ApplyCompaction.
if entering {
r.runQueuedCompaction(ctx, liveEntry)
}
a = r.resolveSessionAgent(sess)
switch {
case !entering:
a = r.turnAgent(sess, resume)
case ls.Route != nil:
a, stop = r.activateAgent(ctx, sess, a, ls.Route, sink)
default:
stop = r.routingUnsupported(ls.Route, a)
}
if stop != nil {
streamReason = r.stopRouting(ctx, sess, a, stop, sink)
return
}
if rec != nil && a.HasHarness() {
// A harness does its work outside the conversation: there
// would be no step to take the run up at. This holds for the
// agent a run starts with and for any it is handed to.
sink.Emit(ErrorForSession(sess.ID, fmt.Sprintf("Agent %q runs in an external harness, which a durable runtime cannot run.", a.Name())))
streamReason = turnEndReasonError
return
}
// Reset tool-derived state on agent switch so warnings and model
// overrides do not inherit the previous agent's tool activity.
if a.Name() != ls.PrevAgentName {
ls.ToolModelOverride = ""
ls.PrevTurnMadeToolCalls = false
ls.StructuredOutputReminders = 0
ls.PrevAgentName = a.Name()
}
r.emitAgentWarnings(a, sink)
agentTools, err := r.getTools(ctx, sess, a, sessionSpan, sink, true)
if err != nil {
sink.Emit(ErrorWithCodeForSession(sess.ID, ErrorCodeToolFailed, fmt.Sprintf("failed to get tools: %v", err)))
return
}
// Emit updated tool count. After a ToolListChanged MCP notification
// the cache is invalidated, so getTools above re-fetches from the
// server and may return a different count.
sink.Emit(ToolsetInfo(len(agentTools), false, a.Name()))
// A turn entered past its model step was let through before the run
// was cut off.
if entering {
// Check iteration limit
newMax, decision := r.enforceMaxIterations(ctx, sess, a, ls.Iteration, ls.MaxIterations, sink)
if decision == iterationStop {
streamReason = StreamStopReasonMaxIterations
if ctx.Err() != nil {
streamReason = turnEndReasonCanceled
}
return
}
ls.MaxIterations = newMax
// Check the run budget. Placed next to the iteration cap because
// both are "should this run keep going" questions answered at the
// turn boundary, before a model call is paid for.
if r.enforceBudget(ctx, sess, a, sink) == iterationStop {
streamReason = turnEndReasonBudgetExceeded
return
}
}
// Exit immediately if the stream context has been cancelled (e.g., Ctrl+C)
if err := ctx.Err(); err != nil {
slog.DebugContext(ctx, "Runtime stream context cancelled, stopping loop", "agent", a.Name(), "session_id", sess.ID)
return
}
slog.DebugContext(ctx, "Starting conversation loop iteration", "agent", a.Name())
model := a.Model(ctx)
// Per-tool model routing: use a cheaper model for this turn
// if the previous tool calls specified one, then reset.
if ls.ToolModelOverride != "" {
if overrideModel, err := r.resolveModelRef(ctx, ls.ToolModelOverride); err != nil {
slog.WarnContext(ctx, "Failed to resolve per-tool model override; using agent default",
"model_override", ls.ToolModelOverride, "error", err)
} else {
slog.InfoContext(ctx, "Using per-tool model override for this turn",
"agent", a.Name(), "override", overrideModel.ID().String(), "primary", model.ID().String())
model = overrideModel
}
}
modelID := model.ID()
// Notify sidebar of the model for this turn. For rule-based
// routing, the actual routed model is emitted from within the
// stream once the first chunk arrives.
info := AgentInfo(a.Name(), modelID.String(), a.Description(), a.WelcomeMessage()).(*AgentInfoEvent)
info.SessionID = sess.ID
sink.Emit(info)
slog.DebugContext(ctx, "Using agent", "agent", a.Name(), "model", modelID.String())
slog.DebugContext(ctx, "Getting model definition", "model_id", modelID.String())
m, err := r.modelsStore.GetModel(ctx, modelID)
if err != nil {
slog.DebugContext(ctx, "Failed to get model definition", "error", err)
}
// We can only compact if we know the context limit.
// resolveContextLimit prefers the declared context_window (or
// provider_opts.context_size), then tries provider discovery and
// the models.dev catalogue. The lookup above is reused inside resolveContextLimit
// only when no window is declared; we keep the explicit call
// here because m is also passed to [pricing.ComputeMessageCost] for
// per-turn cost computation.
// resolveContextLimit yields the primary model's window; effectiveContextLimit
// caps it to the dedicated compaction model's (smaller) window when one is
// configured, so the session operates within a budget the summary call can
// always ingest. The capped value drives both the proactive compaction
// trigger and the UI context gauge (issue #3241); it equals the primary
// window unless a smaller compaction model is configured.
contextLimit := r.effectiveContextLimit(ctx, a, r.resolveContextLimit(ctx, model, modelID))
if entering {
ls.compaction.BeforeTurn(ctx, a, contextLimit)
// Drain steer messages queued while idle or before the first model call
// (covers idle-window and first-turn-miss races).
if sr := r.drainAndEmitSteered(ctx, sess, a, sink); sr.drained {
if r.applySteering(ctx, sess, a, ls, sr, sink) {
return
}
ls.compaction.AfterMessages(ctx, a, contextLimit, sr.messageCountBefore)
// The run has new input: where it stands is no longer what
// is on record.
recorded = false
}
// Proactive compaction may have exhausted the budget since the first check.
if r.enforceBudget(ctx, sess, a, sink) == iterationStop {
streamReason = turnEndReasonBudgetExceeded
return
}
// All that comes before the model is asked is done, and is in
// the record with the run's state as the turn found it: taken up
// from here, the turn is prepared again and comes out the same.
if !recorded {
if err := rec.commit(ctx, phaseModel, ls, nil); err != nil {
streamReason = r.stopUnrecorded(ctx, sess, a, err, sink)
return
}
}
// The turn is counted, and the model its tools asked for is
// used up, once it is on record.
ls.Iteration++
ls.ToolModelOverride = ""
}
recorded = false
// Everything from turn_start onwards is extracted into runTurn so a
// single deferred turn_end hook fires on every exit path: a normal
// stop, a follow-up continue, an error, a hook-driven shutdown, the
// loop-detector tripping, ctx cancellation, even a panic. runTurn
// returns the loop control directive and records the reason reported
// via [hooks.Input.Reason] in ls.exitReason; the deferred dispatch
// runs AFTER both are set, so callers see the same reason the
// runtime took. ctrl drives the outer for-loop's
// continue-or-exit decision.
ctrl := r.runTurn(ctx, &turn{
sess: sess, a: a, m: m, model: model, modelID: modelID, contextLimit: contextLimit,
sessionSpan: sessionSpan, agentTools: agentTools, ls: ls, events: sink, rec: rec,
}, from, answer)
from, answer = phaseModel, nil
streamReason = ls.exitReason
switch ctrl {
case turnContinue:
continue
case turnExit:
streamFinishReason = ls.finishReason
return
}
}
}
// turnControl is what [LocalRuntime.runTurn] reports back to the outer
// run-stream loop: continue to the next iteration, or exit the loop
// entirely. break and return are equivalent here because the loop is
// the last statement in runStreamLoop, so we collapse them into one.
type turnControl int
const (
// turnContinue — outer loop should re-iterate (e.g. follow-up,
// drained steered, retry after stream error, more tool calls).
turnContinue turnControl = iota
// turnExit — outer loop should stop and let runStreamLoop’s
// deferred cleanup run (normal stop, error, hook-blocked,
// loop-detected, ctx cancelled).
turnExit
)
// runState is what a run carries from one step to the next: everything the
// loop needs to pick the run up where a step left it. It holds data only, so
// it can be kept as it is. What the loop works with but cannot keep, such as
// the compaction controller, lives on [loopState].
type runState struct {
Iteration int `json:"iteration,omitempty"`
MaxIterations int `json:"max_iterations,omitempty"`
OverflowCompactions int `json:"overflow_compactions,omitempty"`
ToolModelOverride string `json:"tool_model_override,omitempty"`
PrevAgentName string `json:"prev_agent_name,omitempty"`
// Context that session_start and user_prompt_submit hooks added to the
// run. It rides with every model call and never enters the transcript.
SessionStartMsgs []chat.Message `json:"session_start_msgs,omitempty"`
SessionStartLegacyMsgs []chat.Message `json:"session_start_legacy_msgs,omitempty"`
SessionStartSources []session.InstructionSource `json:"session_start_sources,omitempty"`
UserPromptMsgs []chat.Message `json:"user_prompt_msgs,omitempty"`
// StructuredOutputReminders counts the transient reminders injected
// after a tool-mode turn stopped without calling the internal output
// tool. Bounded by maxStructuredOutputReminders; reset on agent switch
// so it never carries across agents.
StructuredOutputReminders int `json:"structured_output_reminders,omitempty"`
// PrevTurnMadeToolCalls gives empty-reply warnings context from this agent's previous turn.
PrevTurnMadeToolCalls bool `json:"prev_turn_made_tool_calls,omitempty"`
// Route is non-nil only for hook-routed conversations.
Route *routeState `json:"route,omitempty"`
// Loop is what the loop detector has counted.
Loop toolexec.LoopState `json:"loop"`
}
// loopState is the per-RunStream state that persists across iterations: the
// run's state, and the working parts of this stream that serve it. Grouping
// them keeps the function signatures small and makes it trivial to add new
// per-stream tracking without touching any signature.
type loopState struct {
runState
compaction *compactionController
loopDetector *toolexec.LoopDetector
exitReason string
finishReason chat.FinishReason
// idleRetry is shared by every turn and fallback attempt in this child run.
idleRetry *idleStreamRetryAllowance
}
// recordToolCalls counts a batch of tool calls and reports whether the model
// is repeating itself without making progress.
func (ls *loopState) recordToolCalls(calls []tools.ToolCall, exemptCallIDs ...string) bool {
looping := ls.loopDetector.Record(calls, exemptCallIDs...)
ls.Loop = ls.loopDetector.State()
return looping
}
// resetToolCallCount starts counting repeated tool calls afresh.
func (ls *loopState) resetToolCallCount() {
ls.loopDetector.Reset()
ls.Loop = ls.loopDetector.State()
}
// emptyTurnWarning explains a terminal turn without a user-facing reply.
// Tool execution alone does not establish that the user's task is complete.
func emptyTurnWarning(res streamResult, prevTurnMadeToolCalls bool, modelID string, reason chat.FinishReason) string {
switch {
case strings.TrimSpace(res.ReasoningContent) != "":
return fmt.Sprintf(
"Model %s produced only reasoning and no reply (stop reason: %s). "+
"Thinking-mode models can emit reasoning tokens without a final answer; "+
"the reasoning is not used as the response. Send a follow-up to continue if the task is unfinished.",
modelID, reason,
)
case reason == chat.FinishReasonStop && prevTurnMadeToolCalls:
return fmt.Sprintf(
"Model %s stopped without a final reply after using tools (stop reason: %s). "+
"Send a follow-up to continue if the task is unfinished.",
modelID, reason,
)
default:
return fmt.Sprintf(
"Model %s returned an empty response (stop reason: %s). "+
"Send a follow-up to continue if the task is unfinished.",
modelID, reason,
)
}
}
// runPhase names the step a run takes next. A run starts once, then takes
// turns of three steps each: the model is asked, the tool calls it made are
// run, and what follows an answer is done. The run loop enters every turn at
// the first of them, except the turn a run is taken up again in.
type runPhase string
const (
phaseStarting runPhase = "starting"
phaseModel runPhase = "model"
phaseTools runPhase = "tools"
phaseAnswered runPhase = "answered"
)
// turn is what one pass of the loop works with: the agent it runs, what that
// agent runs with, and where its events go.
type turn struct {
sess *session.Session
a *agent.Agent
m *modelsdev.Model
model provider.Provider
modelID modelsdev.ID
contextLimit int64
sessionSpan trace.Span
agentTools []tools.Tool
ls *loopState
events EventSink
// rec is the record kept of the run, if one is.
rec *runRecord
// takenUp says the turn is entered past its model step, by a run that
// was cut off in it.
takenUp bool
}
// modelAnswer is what the model step of a turn leaves for the steps after
// it: the tool calls to run, and the answer the model stopped on, if it did.
type modelAnswer struct {
// Agent is the agent whose turn it is.
Agent string `json:"agent,omitempty"`
Calls []tools.ToolCall `json:"calls,omitempty"`
Content string `json:"content,omitempty"`
HasMedia bool `json:"has_media,omitempty"`
FinishReason chat.FinishReason `json:"finish_reason,omitempty"`
Stopped bool `json:"stopped,omitempty"`
// Model is the model that answered, which a fallback or a routing rule
// may have chosen over the agent's own.
Model modelsdev.ID `json:"model"`
// Validated is set when the answer is a tool-mode structured output
// that passed validation.
Validated bool `json:"validated,omitempty"`
// Messages is how many messages the session held once the answer was
// in it. What the turn adds to them are its tool results, whose size
// decides whether the context is compacted before the next model call.
Messages int `json:"messages,omitempty"`
}
// runTurn performs one iteration of the run-stream loop, from
// turn_start onwards. Wrapping the body in its own function exists for
// one reason: a deferred call can fire turn_end on every exit path — a
// normal stop, an error from handleStreamError, a hook-driven
// shutdown, the loop detector, context cancellation, even a panic —
// without sprinkling explicit dispatch calls at every return / break /
// continue. endReason is captured by reference so each branch can set
// it before falling out; the deferred call reads it AFTER the body has
// assigned the final value.
//
// A turn is three steps: [LocalRuntime.callModel], [LocalRuntime.runTools] and
// [LocalRuntime.afterAnswer]. from names the one it is entered at; a turn
// entered past the first is given the answer the model step had left.
//
// The outer loop owns persistent per-stream state via ls ([loopState]);
// per-turn state that needs to survive into the next iteration
// (overflowCompactions, toolModelOverride) is mutated through the
// shared loopState pointer.
func (r *LocalRuntime) runTurn(ctx context.Context, t *turn, from runPhase, answer *modelAnswer) turnControl {
sess, a, ls, events := t.sess, t.a, t.ls, t.events
ls.finishReason = ""
t.takenUp = from != phaseModel
// endReason is set by every exit branch below and read by the
// deferred turn_end dispatch. Default = normal so a clean fall-
// through (model produced output, more tool calls, no hook
// blocked) reports "continue" or "normal" depending on which
// branch ran last. Branches overwrite this before returning.
endReason := turnEndReasonNormal
defer func() {
if ctxErr := ctx.Err(); ctxErr != nil && endReason == turnEndReasonNormal {
// Context cancellation is detected after the fact: a
// branch that returned early because of ctx.Err overrides
// the default, but a panic-recovered branch may not have
// had the chance, so re-check here.
endReason = turnEndReasonCanceled
}
// Use a non-cancellable context so turn_end runs even when
// the stream was interrupted (Ctrl+C, parent cancellation),
// matching the same guarantee session_end has at the
// finalizeEventChannel level.
r.executeTurnEndHooks(context.WithoutCancel(ctx), sess, a, endReason, events)
ls.exitReason = endReason
}()
if from == phaseModel {
var ctrl turnControl
if answer, ctrl, endReason = r.callModel(ctx, t); answer == nil {
return ctrl
}
answer.Messages = sess.OwnMessageCount()
if err := t.rec.commit(ctx, phaseTools, ls, answer); err != nil {
endReason = r.stopUnrecorded(ctx, sess, a, err, events)
return turnExit
}
} else {
// A turn taken up past its model step starts again as far as its
// hooks can tell: the turn_end that fires however it ends has a
// turn_start of this stream's before it. What turn_start has to
// say is for a model call, and this turn makes none.
r.executeTurnStartHooks(ctx, sess, a, events)
}
// The message count before tool calls measures how much content was
// added by tool results.
messageCountBeforeTools := answer.Messages
if from != phaseAnswered {
if ctrl, reason, done := r.runTools(ctx, t, answer, messageCountBeforeTools); done {
endReason = reason
return ctrl
}
}
if answer.Stopped {
if from != phaseAnswered {
if err := t.rec.commit(ctx, phaseAnswered, ls, answer); err != nil {
endReason = r.stopUnrecorded(ctx, sess, a, err, events)
return turnExit
}
}
ctrl, reason := r.afterAnswer(ctx, t, answer, messageCountBeforeTools)
endReason = reason
return ctrl
}
ls.compaction.AfterMessages(ctx, a, t.contextLimit, messageCountBeforeTools)
endReason = turnEndReasonContinue
return turnContinue
}
// callModel is the first step of a turn: it asks the model and records its
// answer. It returns nil when the turn ends there, along with what the loop
// does next and the reason the turn ended with.
func (r *LocalRuntime) callModel(ctx context.Context, t *turn) (*modelAnswer, turnControl, string) {
sess, a, ls, events := t.sess, t.a, t.ls, t.events
m, model, modelID, contextLimit, agentTools := t.m, t.model, t.modelID, t.contextLimit, t.agentTools
// turnStart bounds this turn's active time, attributed to the agent
// below so the run budget can show how long each agent spent working.
turnStart := r.now()
streamAttrs := []attribute.KeyValue{
attribute.String(genai.AttrConversationID, sess.ID),
attribute.String(genai.AttrAgentNameRuntime, a.Name()),
}
if genai.EmitLegacyAttributes() {
streamAttrs = append(streamAttrs,
attribute.String("agent", a.Name()),
attribute.String("session.id", sess.ID),
)
}
streamCtx, streamSpan := r.startSpan(ctx, "runtime.stream", trace.WithAttributes(streamAttrs...))
// streamSpan ends inline at the natural points (success path before
// recordAssistantMessage, error path after handleStreamError) so its
// duration tracks the model call only, not the whole iteration. The
// boolean prevents a double-End on paths that already closed it.
spanEnded := false
endStreamSpan := func() {
if !spanEnded {
streamSpan.End()
spanEnded = true
}
}
defer endStreamSpan()
// Run turn_start hooks before assembly so dynamic context can be diffed
// against what the model already knows. Changes extend the conversation;
// they never rewrite the frozen instruction prefix.
turnStartMsgs := r.executeTurnStartHooks(ctx, sess, a, events)
// Pending tool-mode structured-output reminder rides with the transient
// system extras: threaded per call, never persisted as a user message.
reminderMsgs := ls.structuredOutputReminderMessages()
legacyExtras := slices.Concat(ls.SessionStartLegacyMsgs, ls.UserPromptMsgs, turnStartMsgs.legacyMessages(), reminderMsgs)
sources := instructionSources(ls.SessionStartMsgs, ls.UserPromptMsgs, turnStartMsgs, ls.SessionStartSources...)
sources = append(sources, instructionSource("runtime/structured-output", "structured-output reminder", reminderMsgs))
messages, err := r.messagesWithDynamicContext(ctx, sess, a, sources, legacyExtras)
if err != nil {
if ctx.Err() != nil {
return nil, turnExit, turnEndReasonCanceled
}
r.emitHookDrivenShutdown(ctx, a, sess, err.Error(), events)
return nil, turnExit, turnEndReasonHookBlocked
}
slog.DebugContext(ctx, "Retrieved messages for processing", "agent", a.Name(), "message_count", len(messages))
// before_llm_call hooks fire just before the model is invoked.
// A terminating verdict (e.g. from the max_iterations builtin)
// stops the run loop here, before any tokens are spent. Hooks
// may also rewrite the outgoing messages by returning
// HookSpecificOutput.UpdatedMessages — the redact_secrets
// builtin uses this to scrub secrets from chat content before
// the LLM ever sees it. The rewrite happens BEFORE the
// runtime's Go-only message transforms so a hook that drops a
// message (e.g. a custom "strip system reminders") doesn't get