-
Notifications
You must be signed in to change notification settings - Fork 434
Expand file tree
/
Copy pathAgentLoop.ts
More file actions
1643 lines (1547 loc) · 60.3 KB
/
Copy pathAgentLoop.ts
File metadata and controls
1643 lines (1547 loc) · 60.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { setTimeout as sleep } from "node:timers/promises";
import {
applyModelEventToAssembler,
assembleAssistantMessage,
cloneMessages,
createModelMessageAssemblerState,
type CanonicalToolCall,
type CanonicalToolSchema,
PROMPT_TOO_LONG_ANTHROPIC_PATTERN,
PROMPT_TOO_LONG_OPENAI_PATTERN,
REQUEST_TOO_LARGE_PATTERN,
type CanonicalMessage,
type CanonicalModelError,
type CanonicalModelRequest,
type CanonicalUsage,
} from "../../model/index.js";
import type {
PilotDeckReadFileStateMap,
PilotDeckSubagentForkApi,
PilotDeckToolResult,
PilotDeckToolRuntimeContext,
PilotDeckWriteSnapshotMap,
} from "../../tool/index.js";
import {
SUBAGENT_DEFINITIONS,
getSubagentDefinition,
} from "../sub/builtinSubagentTypes.js";
import { buildPlanModeAgentToolSchema } from "../../tool/builtin/agent.js";
import { agentError } from "../protocol/errors.js";
import type { AgentEvent } from "../protocol/events.js";
import type { AgentPermissionDenial, AgentTurnResult } from "../protocol/result.js";
import type { AgentRuntimeConfig } from "../runtime/AgentRuntimeConfig.js";
import type { AgentRuntimeDependencies } from "../runtime/AgentRuntimeDependencies.js";
import type { LifecycleDispatchResult } from "../../lifecycle/index.js";
import type { PilotDeckHookEvent } from "../../extension/hooks/protocol/events.js";
import { NullContextRuntime } from "../../context/NullContextRuntime.js";
import type { AgentContextRuntime } from "../../context/ContextRuntime.js";
import type { ContextRecoveryDecision } from "../../context/index.js";
import type { PermissionMode, PermissionRule, PermissionRuleSet } from "../../permission/index.js";
import { collectToolCalls } from "./collectToolCalls.js";
import { createMissingToolResult, ensureToolResultPairing } from "./ensureToolResultPairing.js";
import { LargeFileRepair, type LargeFileRepairDecision } from "./LargeFileRepair.js";
import { projectToolResults } from "./projectToolResults.js";
const TOOL_EVENT_PUMP_INTERVAL_MS = 500;
const SUBAGENT_STATUS_HEARTBEAT_MS = 2_000;
type ActiveSubagentStatus = {
subagentId: string;
subagentType?: string;
startedAtMs: number;
lastHeartbeatMs: number;
currentToolCallId?: string;
currentToolName?: string;
};
export type AgentLoopInput = {
sessionId: string;
turnId: string;
messages: CanonicalMessage[];
maxTurns?: number;
permissionMode?: PermissionMode;
/** The user's actual permission preference before plan-mode override. */
basePermissionMode?: PermissionMode;
permissionRules?: Partial<PermissionRuleSet>;
abortSignal?: AbortSignal;
onDurableMessage?: (message: CanonicalMessage) => void | Promise<void>;
};
export type AgentLoopRunResult = {
result: AgentTurnResult;
messages: CanonicalMessage[];
};
export type AgentLoopSeedState = {
readFileState?: PilotDeckReadFileStateMap;
writeSnapshots?: PilotDeckWriteSnapshotMap;
};
export class AgentLoop {
private readonly readFileState: PilotDeckReadFileStateMap;
private readonly writeSnapshots: PilotDeckWriteSnapshotMap;
constructor(
private readonly config: AgentRuntimeConfig,
private readonly dependencies: AgentRuntimeDependencies,
seedState?: AgentLoopSeedState,
) {
this.readFileState = cloneReadFileStateMap(seedState?.readFileState);
this.writeSnapshots = cloneWriteSnapshotMap(seedState?.writeSnapshots);
}
snapshotFileState(): AgentLoopSeedState {
return {
readFileState: cloneReadFileStateMap(this.readFileState),
writeSnapshots: cloneWriteSnapshotMap(this.writeSnapshots),
};
}
async *run(input: AgentLoopInput): AsyncGenerator<AgentEvent, AgentLoopRunResult, unknown> {
this.applyPermissionOverrides(input.permissionMode, input.permissionRules, input.basePermissionMode);
const startedAt = this.now().toISOString();
let messages = [...input.messages];
let turnCount = 1;
let usage: CanonicalUsage = {};
let permissionDenials: AgentPermissionDenial[] = [];
let structuredOutput: unknown;
let finalMessage: CanonicalMessage | undefined;
const captureTurn = async (errored: boolean): Promise<void> => {
const hook = this.dependencies.context?.captureTurn;
if (!hook) return;
try {
await hook.call(this.dependencies.context, {
sessionId: input.sessionId,
turnId: input.turnId,
messages,
errored,
});
} catch {
// captureTurn must never break a turn — context impl already
// swallows; this catch is defensive.
}
};
/**
* Single-shot reactive truncate-and-retry guard. Set true after the loop
* already truncated for a `prompt_too_long` once; subsequent PTL errors
* fall through to fallback / fail (legacy single-shot semantics).
*/
let hasAttemptedCompact = false;
/**
* Single-shot guard for `max_output_reached` retries. The loop bumps
* `config.maxOutputTokens` (capped at `OUTPUT_TOKEN_RETRY_CEILING`) once
* and retries; a second hit falls through to the continuation recovery.
*/
let hasAttemptedOutputRetry = false;
/**
* Multi-turn continuation recovery counter for `max_output_reached`.
* After the single-shot token bump, the loop injects a continuation
* prompt and preserves the truncated assistant message so the model can
* resume from where it was cut off — up to MAX_OUTPUT_RECOVERY_LIMIT
* times.
*/
const MAX_OUTPUT_RECOVERY_LIMIT = 3;
let maxOutputRecoveryCount = 0;
const MAX_JSON_SELF_CORRECT_RETRIES = 3;
let jsonSelfCorrectCount = 0;
const largeFileRepair = new LargeFileRepair();
/**
* Circuit breaker: consecutive turns where ALL tool calls are
* `invalid_tool_input` errors. When the model is stuck in a loop
* (e.g. qwen repeatedly emitting empty-param bash calls), terminate
* early instead of burning tokens. Resets on any turn with at least
* one successful tool call.
*/
const MAX_CONSECUTIVE_ALL_INVALID_TURNS = 3;
let consecutiveAllInvalidTurns = 0;
const stickyInfo = this.dependencies.router.invalidateSticky?.(input.sessionId);
let previousTier: string | undefined = stickyInfo?.previousTier;
const continueWithSyntheticPrompt = async (decision: LargeFileRepairDecision): Promise<{
type: "continue";
event: AgentEvent;
} | {
type: "completed";
result: AgentTurnResult;
}> => {
if (decision.type === "stop") {
const result = this.createTurnResult(input, {
type: "error",
stopReason: "tool_error",
usage,
permissionDenials,
turns: turnCount,
startedAt,
finalMessage,
structuredOutput,
errors: [agentError("agent_tool_error_loop", decision.reason)],
});
return { type: "completed", result };
}
if (decision.strip === "error_pair") {
messages = stripTrailingErrorPair(messages);
} else if (decision.strip === "assistant") {
const last = messages[messages.length - 1];
if (last?.role === "assistant") {
messages = messages.slice(0, -1);
}
}
messages.push({
role: "user",
content: [{ type: "text", text: decision.prompt }],
metadata: { synthetic: true, purpose: decision.purpose },
});
if (this.config.maxOutputTokens !== undefined
&& this.config.maxOutputTokens < largeFileRepair.recommendedMaxOutputTokens) {
this.config.maxOutputTokens = largeFileRepair.recommendedMaxOutputTokens;
}
return {
type: "continue",
event: {
type: "turn_continued",
sessionId: input.sessionId,
turnId: input.turnId,
reason: "model_error",
},
};
};
while (true) {
if (input.abortSignal?.aborted) {
const result = this.createTurnResult(input, {
type: "aborted",
stopReason: "aborted_streaming",
usage,
permissionDenials,
turns: turnCount,
startedAt,
finalMessage,
});
await captureTurn(result.type === "error");
yield { type: "turn_completed", sessionId: input.sessionId, turnId: input.turnId, result };
return { result, messages };
}
const ctx = this.dependencies.context;
if (ctx?.tryAutoCompact) {
try {
const compact = await ctx.tryAutoCompact({
messages,
abortSignal: input.abortSignal,
});
if (compact.type === "compacted") {
messages = compact.messages;
yield {
type: "turn_continued",
sessionId: input.sessionId,
turnId: input.turnId,
reason: "auto_compact",
};
}
yield {
type: "context_budget",
sessionId: input.sessionId,
turnId: input.turnId,
snapshot: compact.snapshot,
};
} catch {
// Auto-compaction must never block the model call — proceed with
// the original messages if evaluation or summarization fails.
}
yield* this.drainEventBuffer();
}
let request = await this.createModelRequest(messages, input);
if (input.abortSignal?.aborted) {
const result = this.createTurnResult(input, {
type: "aborted",
stopReason: "aborted_streaming",
usage,
permissionDenials,
turns: turnCount,
startedAt,
finalMessage,
});
await captureTurn(result.type === "error");
yield { type: "turn_completed", sessionId: input.sessionId, turnId: input.turnId, result };
return { result, messages };
}
this.dispatchLifecycle(input, "PreModelRequest", {
provider: request.provider,
model: request.model,
}).catch(() => {});
yield {
type: "model_request_started",
sessionId: input.sessionId,
turnId: input.turnId,
model: request.model,
provider: request.provider,
};
// Split decide + execute so we can insert a post-routing compact pass
// when the routed model's context window is smaller than the agent's
// default model (the window used by the first tryAutoCompact above).
const decision = await this.dependencies.router.decide({
request,
sessionId: input.sessionId,
isMainAgent: !this.config.isSubagent,
metadata: previousTier ? { previousTier } : undefined,
});
const getMaxCtx = this.dependencies.getModelMaxContextTokens;
const agentMaxCtx = this.config.maxContextTokens;
if (ctx?.tryAutoCompact && getMaxCtx && agentMaxCtx) {
const routedMaxCtx = getMaxCtx(decision.provider, decision.model);
if (routedMaxCtx !== undefined && routedMaxCtx < agentMaxCtx) {
try {
const recompact = await ctx.tryAutoCompact({
messages,
abortSignal: input.abortSignal,
maxContextTokens: routedMaxCtx,
});
if (recompact.type === "compacted") {
messages = recompact.messages;
request = await this.createModelRequest(messages, input);
yield {
type: "turn_continued",
sessionId: input.sessionId,
turnId: input.turnId,
reason: "auto_compact",
};
}
yield {
type: "context_budget",
sessionId: input.sessionId,
turnId: input.turnId,
snapshot: recompact.snapshot,
};
} catch {
// Post-routing compaction must never block the model call.
}
}
}
const assembler = createModelMessageAssemblerState();
try {
for await (const event of this.dependencies.router.execute(decision, request, {
sessionId: input.sessionId,
turnId: input.turnId,
projectPath: this.config.cwd,
abortSignal: input.abortSignal,
})) {
yield { type: "model_event", sessionId: input.sessionId, turnId: input.turnId, event };
applyModelEventToAssembler(assembler, event);
if (event.type === "error") {
break;
}
}
if (!stickyInfo?.orchestrating) previousTier = undefined;
} catch (error) {
if (input.abortSignal?.aborted) {
const result = this.createTurnResult(input, {
type: "aborted",
stopReason: "aborted_streaming",
usage,
permissionDenials,
turns: turnCount,
startedAt,
finalMessage,
});
await captureTurn(result.type === "error");
yield { type: "turn_completed", sessionId: input.sessionId, turnId: input.turnId, result };
return { result, messages };
}
const stopFailureMsg = error instanceof Error ? error.message : String(error);
await this.dispatchLifecycle(input, "StopFailure", { error: stopFailureMsg });
yield { type: "stop_failure", sessionId: input.sessionId, turnId: input.turnId, error: stopFailureMsg };
const result = this.createTurnResult(input, {
type: "error",
stopReason: "model_error",
usage,
permissionDenials,
turns: turnCount,
startedAt,
finalMessage,
errors: [agentError("agent_model_error", stopFailureMsg)],
});
yield { type: "turn_failed", sessionId: input.sessionId, turnId: input.turnId, error: result.errors![0]! };
await captureTurn(result.type === "error");
yield { type: "turn_completed", sessionId: input.sessionId, turnId: input.turnId, result };
return { result, messages };
}
if (input.abortSignal?.aborted) {
const result = this.createTurnResult(input, {
type: "aborted",
stopReason: "aborted_streaming",
usage,
permissionDenials,
turns: turnCount,
startedAt,
finalMessage,
});
await captureTurn(result.type === "error");
yield { type: "turn_completed", sessionId: input.sessionId, turnId: input.turnId, result };
return { result, messages };
}
const assembled = assembleAssistantMessage(assembler);
usage = mergeUsage(usage, assembled.usage);
finalMessage = assembled.message;
messages.push(assembled.message);
yield { type: "assistant_message", sessionId: input.sessionId, turnId: input.turnId, message: assembled.message };
await input.onDurableMessage?.(assembled.message);
const toolCalls = collectToolCalls(assembled.message);
if (assembled.error) {
if (toolCalls.length > 0) {
const projected = projectToolResults(
toolCalls.map((call) => createMissingToolResult(call, this.now, "Model error interrupted tool execution.")),
);
messages.push(...projected);
yield { type: "tool_results_projected", sessionId: input.sessionId, turnId: input.turnId, message: projected[0]! };
for (const msg of projected) {
await input.onDurableMessage?.(msg);
}
}
if (
this.config.jsonSelfCorrect &&
assembled.error.code === "invalid_tool_arguments" &&
jsonSelfCorrectCount < MAX_JSON_SELF_CORRECT_RETRIES
) {
jsonSelfCorrectCount++;
messages.push({
role: "user",
content: [{
type: "text",
text: "Your previous tool call contained invalid JSON in the arguments and could not be parsed. "
+ "Please retry with valid JSON. Common issues: missing quotes around keys/values, "
+ "trailing commas, unescaped special characters in strings.",
}],
metadata: { synthetic: true, purpose: "json_self_correct" },
});
yield {
type: "turn_continued",
sessionId: input.sessionId,
turnId: input.turnId,
reason: "model_error",
};
continue;
}
// Reactive recovery: ask context runtime if it can recover from the
// model error (e.g. `prompt_too_long` → truncate head and retry).
// Single-shot per turn — see legacy parity §3.1 #8.
const reactive = await this.tryReactiveRecover(input, assembled.error, messages, hasAttemptedCompact);
if (reactive && reactive.type === "truncate_head_and_retry") {
// Drop the failed assistant message + any synthetic tool_result we just
// pushed so the retry doesn't carry a half-baked tool_call. Then apply
// keepRatio so the cap is computed against valid history only.
messages = stripTrailingErrorPair(messages);
messages = truncateHeadKeepRatio(messages, reactive.keepRatio);
hasAttemptedCompact = true;
yield {
type: "turn_continued",
sessionId: input.sessionId,
turnId: input.turnId,
reason: "model_error",
};
continue;
}
if (reactive && reactive.type === "strip_images_and_retry") {
messages = stripTrailingErrorPair(messages);
messages = stripImagesFromMessages(messages);
yield {
type: "turn_continued",
sessionId: input.sessionId,
turnId: input.turnId,
reason: "model_error",
};
continue;
}
// `max_output_reached`: output token limit hit (or truncated JSON
// reclassified from invalid_tool_arguments when finishReason=length).
//
// Phase A — single-shot token doubling: strip the partial response
// and retry with 2x maxOutputTokens (capped at CEILING).
// Phase B — multi-turn continuation: keep the truncated assistant
// message in context and inject a "resume" prompt so the model can
// pick up where it was cut off (up to MAX_OUTPUT_RECOVERY_LIMIT).
// Phase C — exhausted: fall through to error surfacing.
if (assembled.error.code === "max_output_reached") {
// Phase A
if (!hasAttemptedOutputRetry) {
messages = stripTrailingErrorPair(messages);
const previous = this.config.maxOutputTokens ?? OUTPUT_TOKEN_RETRY_DEFAULT;
this.config.maxOutputTokens = Math.min(previous * 2, OUTPUT_TOKEN_RETRY_CEILING);
hasAttemptedOutputRetry = true;
yield {
type: "turn_continued",
sessionId: input.sessionId,
turnId: input.turnId,
reason: "model_error",
};
continue;
}
// Phase B
if (maxOutputRecoveryCount < MAX_OUTPUT_RECOVERY_LIMIT) {
maxOutputRecoveryCount++;
messages.push({
role: "user",
content: [{
type: "text",
text: "Output token limit hit. Resume directly — no apology, no recap of what you were doing. "
+ "Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces.",
}],
metadata: { synthetic: true, purpose: "max_output_recovery" },
});
yield {
type: "turn_continued",
sessionId: input.sessionId,
turnId: input.turnId,
reason: "model_error",
};
continue;
}
// Phase C: fall through to error surfacing
}
// Cross-provider fallback decisions are now owned by RouterRuntime
// (see `runFallbackChain` + `zeroUsageRetry`); the loop only
// classifies the surfaced error and falls through.
const classified = classifyModelError(assembled.error);
await this.dispatchLifecycle(input, "StopFailure", { error: assembled.error });
yield { type: "stop_failure", sessionId: input.sessionId, turnId: input.turnId, error: typeof assembled.error === "string" ? assembled.error : JSON.stringify(assembled.error) };
const result = this.createTurnResult(input, {
type: "error",
stopReason: classified.stopReason,
usage,
permissionDenials,
turns: turnCount,
startedAt,
finalMessage,
errors: [classified.error],
});
yield { type: "turn_failed", sessionId: input.sessionId, turnId: input.turnId, error: result.errors![0]! };
await captureTurn(result.type === "error");
yield { type: "turn_completed", sessionId: input.sessionId, turnId: input.turnId, result };
return { result, messages };
}
if (toolCalls.length === 0) {
const largeFileDecision = largeFileRepair.onNoToolCalls();
if (largeFileDecision) {
const continued = await continueWithSyntheticPrompt(largeFileDecision);
if (continued.type === "completed") {
yield { type: "turn_failed", sessionId: input.sessionId, turnId: input.turnId, error: continued.result.errors![0]! };
await captureTurn(continued.result.type === "error");
yield { type: "turn_completed", sessionId: input.sessionId, turnId: input.turnId, result: continued.result };
return { result: continued.result, messages };
}
yield continued.event;
continue;
}
const stopHooks = await this.dispatchLifecycle(input, "Stop", {
stopHookActive: false,
lastAssistantMessage: textFromMessage(assembled.message),
});
yield { type: "stop_requested", sessionId: input.sessionId, turnId: input.turnId };
messages.push(...stopHooks.messages);
const stopBlock = findLifecycleBlock(stopHooks);
if (stopBlock) {
const result = this.createTurnResult(input, {
type: "error",
stopReason: "tool_error",
usage,
permissionDenials,
turns: turnCount,
startedAt,
finalMessage,
structuredOutput,
errors: [agentError("agent_unsupported_feature", stopBlock.reason)],
});
yield { type: "turn_failed", sessionId: input.sessionId, turnId: input.turnId, error: result.errors![0]! };
await captureTurn(result.type === "error");
yield { type: "turn_completed", sessionId: input.sessionId, turnId: input.turnId, result };
return { result, messages };
}
const result = this.createTurnResult(input, {
type: "success",
stopReason: "completed",
usage,
permissionDenials,
turns: turnCount,
startedAt,
finalMessage,
structuredOutput,
});
await captureTurn(result.type === "error");
yield { type: "turn_completed", sessionId: input.sessionId, turnId: input.turnId, result };
return { result, messages };
}
yield { type: "tool_calls_detected", sessionId: input.sessionId, turnId: input.turnId, calls: toolCalls };
if (input.abortSignal?.aborted) {
const result = this.createTurnResult(input, {
type: "aborted",
stopReason: "aborted_streaming",
usage,
permissionDenials,
turns: turnCount,
startedAt,
finalMessage,
});
await captureTurn(result.type === "error");
yield { type: "turn_completed", sessionId: input.sessionId, turnId: input.turnId, result };
return { result, messages };
}
// When jsonrepair silently "fixed" truncated JSON and the response
// was cut by max_tokens, the tool call arguments are likely incomplete
// (e.g. half-written file content). Apply the same recovery as
// max_output_reached: token doubling → continuation prompt → give up.
if (assembled.hasRepairedToolCalls && (assembled.finishReason === "length" || assembled.finishReason === "tool_call" || assembled.finishReason === "stop")) {
console.warn(
`[AgentLoop] Blocking ${toolCalls.length} repaired-but-truncated tool call(s) — entering max_output recovery`,
);
const largeFileDecision = largeFileRepair.recoverFromRepairedTruncation(toolCalls);
if (largeFileDecision) {
const continued = await continueWithSyntheticPrompt(largeFileDecision);
if (continued.type === "completed") {
yield { type: "turn_failed", sessionId: input.sessionId, turnId: input.turnId, error: continued.result.errors![0]! };
await captureTurn(continued.result.type === "error");
yield { type: "turn_completed", sessionId: input.sessionId, turnId: input.turnId, result: continued.result };
return { result: continued.result, messages };
}
yield continued.event;
continue;
}
// Phase A: token doubling (if not yet attempted)
if (!hasAttemptedOutputRetry) {
messages = stripTrailingErrorPair(messages);
const previous = this.config.maxOutputTokens ?? OUTPUT_TOKEN_RETRY_DEFAULT;
this.config.maxOutputTokens = Math.min(previous * 2, OUTPUT_TOKEN_RETRY_CEILING);
hasAttemptedOutputRetry = true;
yield {
type: "turn_continued",
sessionId: input.sessionId,
turnId: input.turnId,
reason: "model_error",
};
continue;
}
// Phase B: continuation recovery
if (maxOutputRecoveryCount < MAX_OUTPUT_RECOVERY_LIMIT) {
maxOutputRecoveryCount++;
messages.push({
role: "user",
content: [{
type: "text",
text: "Output token limit hit. Resume directly — no apology, no recap of what you were doing. "
+ "Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces.",
}],
metadata: { synthetic: true, purpose: "max_output_recovery" },
});
yield {
type: "turn_continued",
sessionId: input.sessionId,
turnId: input.turnId,
reason: "model_error",
};
continue;
}
// Phase C: exhausted — let tool execution proceed with
// outputTruncated=true so formatValidationError can provide hints.
}
let results: PilotDeckToolResult[];
try {
const toolContext = this.createToolContext(input, messages);
if (assembled.finishReason === "length" || assembled.hasRepairedToolCalls) {
toolContext.outputTruncated = true;
}
results = yield* this.executeToolsWithEventPump(
toolCalls,
toolContext,
input,
);
} catch (error) {
results = toolCalls.map((call) =>
createMissingToolResult(call, this.now, error instanceof Error ? error.message : String(error)),
);
}
if (input.abortSignal?.aborted) {
const result = this.createTurnResult(input, {
type: "aborted",
stopReason: "aborted_streaming",
usage,
permissionDenials,
turns: turnCount,
startedAt,
finalMessage,
});
await captureTurn(result.type === "error");
yield { type: "turn_completed", sessionId: input.sessionId, turnId: input.turnId, result };
return { result, messages };
}
yield* this.drainEventBuffer();
const pairedResults = ensureToolResultPairing(toolCalls, results, this.now);
const toolResultRepair = largeFileRepair.analyzeToolResults(pairedResults, {
outputTruncated: assembled.finishReason === "length" || assembled.hasRepairedToolCalls === true,
repairedToolCalls: assembled.hasRepairedToolCalls === true,
finishReason: assembled.finishReason,
});
permissionDenials = [...permissionDenials, ...collectPermissionDenials(pairedResults)];
for (const result of pairedResults) {
if (result.type === "success" && result.metadata?.structuredOutput) {
structuredOutput = result.data;
}
const requestedMode = readRequestedMode(result.type === "success" ? result.data : undefined);
if (requestedMode) {
let effectiveMode = requestedMode;
if (requestedMode === "plan" && this.config.permissionMode !== "plan") {
this.config.permissionModeBeforePlan = this.config.permissionMode;
} else if (this.config.permissionMode === "plan" && requestedMode !== "plan") {
if (this.config.permissionModeBeforePlan) {
effectiveMode = this.config.permissionModeBeforePlan;
this.config.permissionModeBeforePlan = undefined;
}
}
this.config.permissionMode = effectiveMode;
this.config.permissionContext.mode = effectiveMode;
yield { type: "mode_change_requested", sessionId: input.sessionId, turnId: input.turnId, mode: effectiveMode };
}
yield { type: "tool_result", sessionId: input.sessionId, turnId: input.turnId, result };
}
const projected = projectToolResults(pairedResults);
// Route the freshly projected tool_result message through the context
// runtime so large payloads land on disk via `ToolResultBudget`. When
// the runtime doesn't implement `applyToolResults` (e.g. NullContext),
// we simply append the raw projection (legacy behaviour).
// Only the first message (containing tool_result blocks) goes through
// budget processing; supplemental messages (PDF/image data) are appended directly.
const [toolResultMsg, ...supplementalMsgs] = projected;
const ctxApply = this.dependencies.context?.applyToolResults;
if (ctxApply) {
try {
const applied = await ctxApply.call(this.dependencies.context, {
sessionId: input.sessionId,
turnId: input.turnId,
toolResultMessage: toolResultMsg,
messages,
});
messages = applied.messages;
} catch {
messages.push(toolResultMsg);
}
} else {
messages.push(toolResultMsg);
}
for (const supplemental of supplementalMsgs) {
messages.push(supplemental);
}
yield { type: "tool_results_projected", sessionId: input.sessionId, turnId: input.turnId, message: toolResultMsg };
await input.onDurableMessage?.(toolResultMsg);
for (const supplemental of supplementalMsgs) {
await input.onDurableMessage?.(supplemental);
}
if (toolResultRepair) {
const continued = await continueWithSyntheticPrompt(toolResultRepair);
if (continued.type === "completed") {
yield { type: "turn_failed", sessionId: input.sessionId, turnId: input.turnId, error: continued.result.errors![0]! };
await captureTurn(continued.result.type === "error");
yield { type: "turn_completed", sessionId: input.sessionId, turnId: input.turnId, result: continued.result };
return { result: continued.result, messages };
}
yield continued.event;
continue;
}
const lifecycleBlock = findToolLifecycleBlock(pairedResults);
if (lifecycleBlock) {
const result = this.createTurnResult(input, {
type: "error",
stopReason: "tool_error",
usage,
permissionDenials,
turns: turnCount,
startedAt,
finalMessage,
structuredOutput,
errors: [agentError("agent_unsupported_feature", lifecycleBlock.reason)],
});
yield { type: "turn_failed", sessionId: input.sessionId, turnId: input.turnId, error: result.errors![0]! };
await captureTurn(result.type === "error");
yield { type: "turn_completed", sessionId: input.sessionId, turnId: input.turnId, result };
return { result, messages };
}
// Circuit breaker: detect turns where ALL tool calls returned
// invalid_tool_input. If the model is stuck (e.g. repeatedly emitting
// empty-param bash), terminate early after MAX_CONSECUTIVE_ALL_INVALID_TURNS.
// When LargeFileRepair is actively managing recovery, defer to its own
// attempt limits instead of terminating here.
const allInvalid = pairedResults.length > 0 && pairedResults.every(
(r) => r.type === "error" && r.error.code === "invalid_tool_input",
);
if (allInvalid && largeFileRepair.hasPendingRepair) {
const fallbackRepair = largeFileRepair.onInvalidToolInput();
if (fallbackRepair) {
const continued = await continueWithSyntheticPrompt(fallbackRepair);
if (continued.type === "completed") {
yield { type: "turn_failed", sessionId: input.sessionId, turnId: input.turnId, error: continued.result.errors![0]! };
await captureTurn(continued.result.type === "error");
yield { type: "turn_completed", sessionId: input.sessionId, turnId: input.turnId, result: continued.result };
return { result: continued.result, messages };
}
yield continued.event;
continue;
}
}
if (allInvalid) {
consecutiveAllInvalidTurns++;
if (consecutiveAllInvalidTurns >= MAX_CONSECUTIVE_ALL_INVALID_TURNS) {
const result = this.createTurnResult(input, {
type: "error",
stopReason: "tool_error",
usage,
permissionDenials,
turns: turnCount,
startedAt,
finalMessage,
structuredOutput,
errors: [agentError(
"agent_tool_error_loop",
`Terminated: ${consecutiveAllInvalidTurns} consecutive turns with all tool calls failing input validation. The model appears stuck in a loop.`,
undefined,
"The model is repeatedly producing invalid tool calls. Consider switching to a more capable model via settings.",
)],
});
yield { type: "turn_failed", sessionId: input.sessionId, turnId: input.turnId, error: result.errors![0]! };
await captureTurn(result.type === "error");
yield { type: "turn_completed", sessionId: input.sessionId, turnId: input.turnId, result };
return { result, messages };
}
} else {
consecutiveAllInvalidTurns = 0;
maxOutputRecoveryCount = 0;
hasAttemptedOutputRetry = false;
}
if (this.config.stopOnStructuredOutput && structuredOutput !== undefined) {
const result = this.createTurnResult(input, {
type: "success",
stopReason: "completed",
usage,
permissionDenials,
turns: turnCount,
startedAt,
finalMessage,
structuredOutput,
});
await captureTurn(result.type === "error");
yield { type: "turn_completed", sessionId: input.sessionId, turnId: input.turnId, result };
return { result, messages };
}
const nextTurnCount = turnCount + 1;
if (input.maxTurns && nextTurnCount > input.maxTurns) {
const result = this.createTurnResult(input, {
type: "max_turns",
stopReason: "max_turns",
usage,
permissionDenials,
turns: nextTurnCount,
startedAt,
finalMessage,
structuredOutput,
errors: [agentError(
"agent_max_turns_reached",
`Reached maximum number of turns (${input.maxTurns}).`,
undefined,
"Max turn limit reached. Increase maxTurns in config or break the task into smaller steps.",
)],
});
await captureTurn(result.type === "error");
yield { type: "turn_completed", sessionId: input.sessionId, turnId: input.turnId, result };
return { result, messages };
}
turnCount = nextTurnCount;
yield { type: "turn_continued", sessionId: input.sessionId, turnId: input.turnId, reason: "next_turn" };
}
}
private async tryReactiveRecover(
input: AgentLoopInput,
error: CanonicalModelError,
messages: CanonicalMessage[],
hasAttemptedCompact: boolean,
): Promise<ContextRecoveryDecision | undefined> {
const ctx: AgentContextRuntime | undefined = this.dependencies.context;
if (!ctx?.recoverFromModelError) {
return undefined;
}
try {
return await ctx.recoverFromModelError({
sessionId: input.sessionId,
turnId: input.turnId,
error,
messages,
hasAttemptedCompact,
});
} catch {
// Recovery probe should never block fallback. Pretend the runtime gave up.
return undefined;
}
}
private async createModelRequest(
messages: CanonicalMessage[],
input: AgentLoopInput,
): Promise<CanonicalModelRequest> {
const contextRuntime = this.dependencies.context ?? new NullContextRuntime();
const planTodo = this.dependencies.planTodoManager?.forSession(input.sessionId);
let tools = this.dependencies.tools.registry.toCanonicalSchemas();
if (this.config.permissionMode === "plan") {
tools = applyPlanModeToolOverrides(tools);
}
const prepared = await contextRuntime.prepareForModel({
sessionId: input.sessionId,
turnId: input.turnId,
cwd: this.config.cwd,
provider: this.config.provider,
model: this.config.model,
permissionMode: this.config.permissionMode,
additionalWorkingDirectories: this.config.permissionContext.additionalWorkingDirectories,
messages: cloneMessages(messages),
tools,
maxMessages: this.config.maxContextMessages,
customSystemPrompt: this.config.systemPrompt,
appendSystemPrompt: planTodo?.buildPromptAddendum(),
abortSignal: input.abortSignal,
});
this.dispatchLifecycle(input, "InstructionsLoaded", {
hasSystemPrompt: !!prepared.systemPrompt,
}).catch(() => {});
this.dependencies.eventEmitter?.({
type: "instructions_loaded",
sessionId: input.sessionId,
turnId: input.turnId,
hasSystemPrompt: !!prepared.systemPrompt,
});
return {
provider: this.config.provider,
model: this.config.model,
messages: prepared.messages,
systemPrompt: prepared.systemPrompt ?? this.config.systemPrompt,
tools: prepared.tools,
toolChoice: this.config.toolChoice,
maxOutputTokens: this.config.maxOutputTokens,
temperature: this.config.temperature,
thinking: this.config.thinking,
stream: true,
metadata: this.config.metadata,
cacheBreakpoints: prepared.cacheBreakpoints,
};
}
private createToolContext(
input: AgentLoopInput,
messages: CanonicalMessage[],
): PilotDeckToolRuntimeContext {
const planDirectoryPath = this.dependencies.planFileManager?.getPlanDirectoryPath();
const planTodo = this.dependencies.planTodoManager?.forSession(input.sessionId);
const permissionContext = {
...this.config.permissionContext,
cwd: this.config.cwd,
...(planDirectoryPath ? { planDirectoryPath } : {}),
};
return {
sessionId: input.sessionId,
turnId: input.turnId,
// Group key for `FileHistoryStore.trackEdit` (C4). Our canonical
// assistant messages don't carry an id, so the turn id is the closest
// stable scope: every edit/write produced inside this turn rewinds as
// a single batch — semantic match to legacy "rewind by messageId".
messageId: input.turnId,
cwd: this.config.cwd,
abortSignal: input.abortSignal,
subagentTimeoutMs: this.config.subagentTimeoutMs,
permissionMode: this.config.permissionMode,
permissionContext,
auditRecorder: this.dependencies.auditRecorder,
now: this.now,
env: this.config.env,
maxResultBytes: this.config.maxResultBytes,
// Tools that need a secondary model call (e.g. `agent` subagents in
// fallback mode, `web_fetch` extraction) get a thin adapter that
// funnels into the router's stream so subagents inherit fallback /
// zero-usage retry.
model: {
stream: (request, signal) =>