-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathplanner-loop.ts
More file actions
2629 lines (2513 loc) · 85 KB
/
planner-loop.ts
File metadata and controls
2629 lines (2513 loc) · 85 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 { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";
import { logger } from "../logger";
import { plannerSchema, plannerTemplate } from "../prompts/planner";
import { resolveOptimizedPromptForRuntime } from "../services/optimized-prompt-resolver";
import { emitStreamingHook, getStreamingContext } from "../streaming-context";
import type { ActionResult, ProviderDataRecord } from "../types/components";
import type { ContextEvent, ContextObjectTool } from "../types/context-object";
import {
type ChatMessage,
type GenerateTextResult,
ModelType,
type PromptSegment,
type ResponseSkeleton,
type SpanSamplerPlan,
type TextGenerationModelType,
type ToolCall,
type ToolChoice,
type ToolDefinition,
} from "../types/model";
import { resolveStateDir } from "../utils/state-dir";
import { computePrefixHashes } from "./context-hash";
import { appendContextEvent } from "./context-object";
import {
buildStageChatMessages,
cachePrefixSegments,
normalizePromptSegments,
renderContextObject,
} from "./context-renderer";
import { computeCallCostUsd } from "./cost-table";
import { runEvaluator } from "./evaluator";
import {
extractJsonObjects,
parseJsonObject,
stringifyForModel,
} from "./json-output";
import {
assertRepeatedFailureLimit,
assertTrajectoryLimit,
type ChainingLoopConfig,
type FailureLike,
mergeChainingLoopConfig,
TrajectoryLimitExceeded,
} from "./limits";
import {
buildModelInputBudget,
type ModelInputBudget,
withModelInputBudgetProviderOptions,
} from "./model-input-budget";
import { extractPlanActionsFromContent } from "./plan-actions-extractor";
import {
cacheProviderOptions,
toolMessageContent,
trajectoryStepsToMessages,
} from "./planner-rendering";
import type {
ContextObject,
EvaluatorOutput,
PlannerLoopParams,
PlannerLoopResult,
PlannerRuntime,
PlannerStep,
PlannerToolCall,
PlannerToolResult,
PlannerTrajectory,
} from "./planner-types";
import {
buildPlannerActionGrammarStrict,
buildSpanSamplerPlan,
withGuidedDecodeProviderOptions,
} from "./response-grammar";
import type {
RecordedStage,
RecordedToolCall,
RecordedUsage,
TrajectoryRecorder,
} from "./trajectory-recorder";
import { captureToolStageIO } from "./trajectory-recorder";
export {
cacheProviderOptions,
trajectoryStepsToMessages,
} from "./planner-rendering";
// Test-only re-exports for the rendering memoization unit tests.
// Underscore-prefixed so they're impossible to mistake for production API.
export function __renderRoutingHintsBlockForTests(
context: ContextObject,
): string | null {
return renderRoutingHintsBlock(context);
}
export type {
ContextObject,
EvaluatorEffects,
EvaluatorOutput,
PlannerLoopParams,
PlannerLoopResult,
PlannerRuntime,
PlannerStep,
PlannerToolCall,
PlannerToolResult,
PlannerTrajectory,
} from "./planner-types";
interface RawPlannerOutput {
action?: unknown;
parameters?: unknown;
thought?: unknown;
toolCalls?: unknown;
messageToUser?: unknown;
text?: unknown;
// Optional explicit completion signal. When emitted as a boolean,
// `tryGateEvaluator` honors `completed=false` to fall through to the
// full evaluator instead of synthesizing a FINISH. See gate
// preconditions in `tryGateEvaluator`.
completed?: unknown;
}
export async function runPlannerLoop(
params: PlannerLoopParams,
): Promise<PlannerLoopResult> {
const plannerContext = normalizePlannerContext(params.context);
const config = mergeChainingLoopConfig(params.config);
const trajectory: PlannerTrajectory = {
context: plannerContext,
steps: [],
archivedSteps: [],
plannedQueue: [],
evaluatorOutputs: [],
};
const failures: FailureLike[] = [];
let terminalOnlyContinuations = 0;
let requiredToolMisses = 0;
let unavailableToolCallRetries = 0;
let silentFailedFinishRecoveries = 0;
const requireNonTerminalToolCall =
params.requireNonTerminalToolCall === true &&
hasExposedNonTerminalTool(params.tools);
// Cumulative gross prompt-token counter, summed across every planner
// stage in this user turn. Tracked alongside the existing per-iter
// counters (terminalOnlyContinuations, requiredToolMisses) so the
// `maxTrajectoryPromptTokens` guard fires on the very call that crosses
// the threshold rather than at the next-iteration check-in.
let cumulativePromptTokens = 0;
const observePlannerUsage = (usage: {
promptTokens: number;
completionTokens: number;
}): void => {
cumulativePromptTokens += usage.promptTokens;
if (cumulativePromptTokens > config.maxTrajectoryPromptTokens) {
throw new TrajectoryLimitExceeded({
kind: "trajectory_token_budget",
max: config.maxTrajectoryPromptTokens,
observed: cumulativePromptTokens,
message:
`Trajectory prompt-token budget exceeded ` +
`(${cumulativePromptTokens}/${config.maxTrajectoryPromptTokens}) — ` +
`this turn is most likely stuck in a replan loop; aborting to bound cost.`,
});
}
};
// Tracks the most recent planner output's *explicit* `messageToUser` so the
// post-tool evaluator gate can use it as the final response when the
// trajectory ends cleanly. EXPLICIT means the planner's structured output
// carried a `messageToUser` field — not a fallback inferred from a stray
// `text` field on a native tool-call return (which can be a pre-tool thought
// rather than a final answer). The gate refuses ambiguous signals to avoid
// surfacing a thought as the user-facing reply.
let lastPlannerExplicitMessageToUser: string | undefined;
// Tracks the most recent planner output's explicit `completed` flag, when
// emitted as a boolean. The gate (`tryGateEvaluator`) treats
// `completed === false` as a hard veto on synthesizing a FINISH — the
// planner is explicitly signaling that this turn's tool calls do not yet
// achieve the goal (e.g. read-then-act, multi-step deploy). When the
// field is absent the gate's other preconditions are honored as before.
let lastPlannerExplicitCompleted: boolean | undefined;
for (let iteration = 1; ; iteration++) {
if (trajectory.plannedQueue.length === 0) {
const plannerOutput = await callPlanner({
runtime: params.runtime,
context: trajectory.context,
trajectory,
config,
modelType: params.modelType,
provider: params.provider,
tools: params.tools,
toolChoice: requireNonTerminalToolCall ? "required" : params.toolChoice,
recorder: params.recorder,
trajectoryId: params.trajectoryId,
parentStageId: params.parentStageId,
iteration,
onUsage: observePlannerUsage,
});
// Treat `messageToUser` as authoritative ONLY when the planner's structured
// output carried it as an explicit field. The native-tool-call code path
// in `parsePlannerOutput` falls back to `raw.text`, but in native mode
// `text` can be a pre-tool thought rather than a final answer — too
// ambiguous to drive the gate. We therefore probe `raw.messageToUser`
// directly here; native-mode returns won't have that key, so the gate
// stays inert in that path.
const explicit = plannerOutput.raw.messageToUser;
lastPlannerExplicitMessageToUser =
typeof explicit === "string" && explicit.trim().length > 0
? explicit
: undefined;
// Capture the planner's explicit `completed` boolean when present.
// Any non-boolean (string "false", number, null, missing) is treated
// as "unspecified" and does not influence the gate — only an actual
// `false` boolean blocks. This keeps backward compat with planner
// outputs that don't carry the field.
const completedRaw = plannerOutput.raw.completed;
lastPlannerExplicitCompleted =
typeof completedRaw === "boolean" ? completedRaw : undefined;
if (plannerOutput.toolCalls.length === 0) {
if (
requireNonTerminalToolCall &&
!hasExecutedNonTerminalTool(trajectory)
) {
requiredToolMisses++;
assertTrajectoryLimit({
kind: "required_tool_misses",
max: config.maxRequiredToolMisses,
observed: requiredToolMisses,
});
handleRequiredToolPlannerMiss({
trajectory,
iteration,
plannerOutput,
reason: "no_tool_calls",
logger: params.runtime.logger,
});
continue;
}
trajectory.steps.push({
iteration,
thought: plannerOutput.thought,
terminalMessage: plannerOutput.messageToUser,
terminalOnly: true,
});
trajectory.context = appendTerminalPlannerOutputEvent({
context: trajectory.context,
iteration,
message: plannerOutput.messageToUser,
});
if (trajectory.steps.some((step) => step.toolCall)) {
const evaluator = await evaluateTrajectory(
params,
trajectory,
iteration,
);
trajectory.evaluatorOutputs.push(evaluator);
trajectory.context = appendEvaluationEvent({
context: trajectory.context,
iteration,
evaluator,
});
if (evaluator.decision === "FINISH") {
return {
status: "finished",
trajectory,
evaluator,
finalMessage: userSafeFinalMessage(
preferredFinalMessageFromToolOrModel(
trajectory,
evaluator.messageToUser ?? plannerOutput.messageToUser,
),
trajectory,
),
};
}
if (evaluator.decision === "NEXT_RECOMMENDED") {
const selected = preferRecommendedToolCall(trajectory, evaluator);
if (!selected) {
params.runtime.logger?.warn?.(
{
recommendedToolCallId: evaluator.recommendedToolCallId,
queuedToolCallIds: trajectory.plannedQueue.map(
(call) => call.id,
),
},
"Evaluator requested NEXT_RECOMMENDED without a valid queued tool after terminal planner output; replanning",
);
trajectory.plannedQueue.length = 0;
}
continue;
}
terminalOnlyContinuations++;
assertTrajectoryLimit({
kind: "terminal_only_continuations",
max: config.maxTerminalOnlyContinuations,
observed: terminalOnlyContinuations,
});
trajectory.plannedQueue.length = 0;
trajectory.context = appendTerminalContinuationEvent({
context: trajectory.context,
iteration,
terminalOnlyContinuations,
message: plannerOutput.messageToUser,
});
continue;
}
return {
status: "finished",
trajectory,
finalMessage: userSafeFinalMessage(
plannerOutput.messageToUser,
trajectory,
),
};
}
if (plannerOutput.toolCalls.every(isTerminalToolCall)) {
if (
requireNonTerminalToolCall &&
!hasExecutedNonTerminalTool(trajectory)
) {
requiredToolMisses++;
assertTrajectoryLimit({
kind: "required_tool_misses",
max: config.maxRequiredToolMisses,
observed: requiredToolMisses,
});
handleRequiredToolPlannerMiss({
trajectory,
iteration,
plannerOutput,
reason: "terminal_only_tool_calls",
logger: params.runtime.logger,
});
continue;
}
const finalMessage = terminalMessageFromToolCalls(
plannerOutput.toolCalls,
plannerOutput.messageToUser,
);
trajectory.steps.push({
iteration,
thought: plannerOutput.thought,
terminalMessage: finalMessage,
terminalOnly: true,
});
const terminalEvaluator = terminalToolCallFinish(finalMessage);
// Only record an evaluation stage when the trajectory already has
// prior evaluator outputs. A terminal-only iteration on the very
// first planner turn (e.g. REPLY) is purely terminal and should
// not surface an `evaluation` stage in the recorded trajectory
// — the happy path tests assert this.
const shouldRecordTerminalEvaluation =
trajectory.evaluatorOutputs.length > 0;
trajectory.evaluatorOutputs.push(terminalEvaluator);
trajectory.context = appendEvaluationEvent({
context: trajectory.context,
iteration,
evaluator: terminalEvaluator,
});
if (shouldRecordTerminalEvaluation) {
const terminalEvalStartedAt = Date.now();
await recordGatedEvaluationStage({
recorder: params.recorder,
trajectoryId: params.trajectoryId,
parentStageId: params.parentStageId,
iteration,
startedAt: terminalEvalStartedAt,
endedAt: Date.now(),
output: terminalEvaluator,
reason: "terminal_tool_call",
logger: params.runtime.logger,
});
}
return {
status: "finished",
trajectory,
evaluator: terminalEvaluator,
finalMessage,
};
}
const nonTerminalCalls = plannerOutput.toolCalls
.filter((toolCall) => !isTerminalToolCall(toolCall))
.map((toolCall, index) => ensureToolCallId(toolCall, iteration, index));
const unavailable = splitUnavailableToolCalls(
nonTerminalCalls,
params.tools,
);
if (unavailable.invalid.length > 0) {
params.runtime.logger?.warn?.(
{
iteration,
invalidToolCalls: unavailable.invalid.map(
(toolCall) => toolCall.name,
),
},
"Planner called unavailable tools; retrying without executing them",
);
trajectory.context = appendUnavailableToolCallEvent({
context: trajectory.context,
iteration,
invalidToolCalls: unavailable.invalid,
tools: params.tools,
});
if (unavailable.valid.length === 0) {
unavailableToolCallRetries++;
assertTrajectoryLimit({
kind: "unavailable_tool_calls",
max: config.maxUnavailableToolCallRetries,
observed: unavailableToolCallRetries,
});
continue;
}
}
const validNonTerminalCalls = unavailable.valid;
trajectory.plannedQueue.push(...validNonTerminalCalls);
trajectory.context = {
...trajectory.context,
plannedQueue: [
...(trajectory.context.plannedQueue ?? []),
...validNonTerminalCalls.map((toolCall) => ({
id: toolCall.id,
name: toolCall.name,
args: stringifyForModel(toolCall.params ?? {}),
status: "queued" as const,
sourceStageId: `planner:${iteration}`,
})),
],
};
for (const toolCall of validNonTerminalCalls) {
trajectory.context = appendContextEvent(trajectory.context, {
id: `queue:${toolCall.id ?? toolCall.name}:${iteration}`,
type: "planned_tool_call",
source: "planner-loop",
createdAt: Date.now(),
metadata: {
iteration,
toolCallId: toolCall.id,
name: toolCall.name,
params: stringifyForModel(toolCall.params ?? {}),
status: "queued",
},
});
}
}
const toolCall = trajectory.plannedQueue.shift();
if (!toolCall) {
continue;
}
await executeQueuedToolCall({
params,
trajectory,
toolCall,
iteration,
config,
failures,
});
const latestResult = trajectory.steps[trajectory.steps.length - 1]?.result;
if (latestResult?.continueChain === false) {
// `suppressPlannerReply` from terminal actions blanks finalMessage so a
// same-turn hallucinated `messageToUser` cannot leak past the transient
// filter (which only masks it on the *next* turn).
const suppressReply =
(latestResult.data as { suppressPlannerReply?: unknown } | undefined)
?.suppressPlannerReply === true;
return {
status: "finished",
trajectory,
finalMessage: suppressReply ? "" : latestResult.text,
};
}
await maybeCompactBeforeNextModelCall({
trajectory,
config,
tools: params.tools,
recorder: params.recorder,
trajectoryId: params.trajectoryId,
parentStageId: params.parentStageId,
iteration,
logger: params.runtime.logger,
});
// Conservative gate (PR #7514): when a successful tool drained the queue
// and the just-completed planner call gave us a clean explicit
// `messageToUser`, synthesize a FINISH and skip the in-loop evaluator.
// Falls through on any ambiguity. See `tryGateEvaluator` doc-comment.
const gateStartedAt = Date.now();
const gated = tryGateEvaluator({
trajectory,
failures,
lastPlannerExplicitMessageToUser,
lastPlannerExplicitCompleted,
});
if (gated) {
trajectory.evaluatorOutputs.push(gated);
trajectory.context = appendEvaluationEvent({
context: trajectory.context,
iteration,
evaluator: gated,
});
await recordGatedEvaluationStage({
recorder: params.recorder,
trajectoryId: params.trajectoryId,
parentStageId: params.parentStageId,
iteration,
startedAt: gateStartedAt,
endedAt: Date.now(),
output: gated,
logger: params.runtime.logger,
});
return {
status: "finished",
trajectory,
evaluator: gated,
finalMessage: userSafeFinalMessage(
preferredFinalMessageFromToolOrModel(trajectory, gated.messageToUser),
trajectory,
),
};
}
const evaluator = await evaluateTrajectory(params, trajectory, iteration);
trajectory.evaluatorOutputs.push(evaluator);
appendEvaluatorContextEvent(trajectory, evaluator, iteration);
if (evaluator.decision === "FINISH") {
if (
shouldRecoverSilentFailedFinish({
evaluator,
trajectory,
recoveryCount: silentFailedFinishRecoveries,
})
) {
silentFailedFinishRecoveries++;
trajectory.context = appendSilentFailedFinishRecoveryEvent({
context: trajectory.context,
iteration,
evaluator,
trajectory,
});
continue;
}
return {
status: "finished",
trajectory,
evaluator,
finalMessage: userSafeFinalMessage(
preferredFinalMessageFromToolOrModel(
trajectory,
evaluator.messageToUser,
evaluator.success === false
? failedToolFallbackMessage(trajectory)
: undefined,
),
trajectory,
),
};
}
if (evaluator.decision === "NEXT_RECOMMENDED") {
const selected = preferRecommendedToolCall(trajectory, evaluator);
if (!selected) {
params.runtime.logger?.warn?.(
{
recommendedToolCallId: evaluator.recommendedToolCallId,
queuedToolCallIds: trajectory.plannedQueue.map((call) => call.id),
},
"Evaluator requested NEXT_RECOMMENDED without a valid queued tool; replanning",
);
trajectory.plannedQueue.length = 0;
}
continue;
}
trajectory.plannedQueue.length = 0;
}
}
function normalizePlannerContext(context: ContextObject): ContextObject {
return Array.isArray(context.events)
? context
: {
...context,
events: [],
};
}
function renderPlannerModelInput(params: {
context: ContextObject;
trajectory: PlannerTrajectory;
template?: string;
runtime?: PlannerRuntime;
/**
* Optional per-tool-result character cap. Forwarded directly to
* `trajectoryStepsToMessages` — caps the rendered tool-result
* string for each kept-verbatim step without mutating the
* trajectory itself.
*/
maxToolResultChars?: number;
}): {
messages: ChatMessage[];
promptSegments: PromptSegment[];
} {
const renderedContext = renderContextObject(params.context);
const template = params.template ?? plannerTemplate;
const instructions = (
template.split("context_object:")[0] ?? template
).trim();
const stepMessages = trajectoryStepsToMessages(params.trajectory.steps, {
maxToolResultChars: params.maxToolResultChars,
});
// Action names + parameter schemas now ride directly on the tools array
// (each Action is exposed as its own native tool), so there is no separate
// available_actions block rendered into the prompt. Routing hints stay as a
// dedicated section since they layer business advice on top of the bare
// action descriptions.
const routingHintsBlock = renderRoutingHintsBlock(params.context);
const extraSegments: PromptSegment[] = [];
if (routingHintsBlock) {
extraSegments.push({ content: routingHintsBlock, stable: false });
}
const contextSegments =
extraSegments.length > 0
? [...renderedContext.promptSegments, ...extraSegments]
: renderedContext.promptSegments;
// The planner stage instructions are template-derived (`plannerTemplate`)
// and structurally identical across iterations and across user turns, so they
// belong in the cached prefix. Marking the segment `stable: true` lets the
// Anthropic provider stamp `cache_control` on this block and lets the
// cache-key prefix extend through these instructions.
const promptSegments = normalizePromptSegments([
...contextSegments,
{ content: `planner_stage:\n${instructions}`, stable: true },
]);
// Native tool-call messages: assistant (with toolCalls) + tool (result) per
// completed step. This grows append-only across planner iterations so the
// base prefix remains byte-identical and Cerebras's prompt cache can hit.
// The trajectory JSON is NOT included in dynamicBlocks here — it is conveyed
// through stepMessages (proper assistant/tool pairs). Including it as a
// dynamic block would re-introduce the JSON-dump anti-pattern in the user
// message and invalidate the cache prefix on every iteration.
const messages = buildStageChatMessages({
contextSegments,
stageLabel: "planner_stage",
instructions,
dynamicBlocks: [],
stepMessages,
});
return { messages, promptSegments };
}
function compactionReserveForBudget(
config: ChainingLoopConfig,
): number | undefined {
if (
config.contextWindowModelName &&
config.compactionReserveTokensExplicit !== true
) {
return undefined;
}
return config.compactionReserveTokens;
}
function normalizePlannerToolName(name: string): string {
return name
.trim()
.toUpperCase()
.replace(/[^A-Z0-9]/g, "");
}
/**
* Build a "Routing hints" block from each available action's
* {@link Action.routingHint}. Replaces the hand-written domain-routing prose
* that used to live inline in `plannerTemplate` — each action now carries
* its own one-line hint as metadata, and the planner sees them only when the
* action is actually exposed for this turn.
*
* Returns `null` when no exposed action has a `routingHint` set, so the
* planner prompt simply omits the section.
*
* When `ELIZA_PROMPT_COMPRESS=1` is set, skip routing-hint rendering
* entirely — the Cerebras compress-mode escape hatch trades these hints for a
* tighter token budget. Memoized on `context.events` identity; the events
* array is immutable per planner iteration (`appendContextEvent` returns a
* new array each time).
*/
const ROUTING_HINTS_MEMO = new WeakMap<
NonNullable<ContextObject["events"]>,
string | null
>();
function renderRoutingHintsBlock(context: ContextObject): string | null {
if (process.env.ELIZA_PROMPT_COMPRESS === "1") return null;
const events = context.events;
if (events && ROUTING_HINTS_MEMO.has(events)) {
return ROUTING_HINTS_MEMO.get(events) ?? null;
}
const seen = new Set<string>();
const lines: string[] = [];
for (const event of events ?? []) {
if (event.type !== "tool" || !("tool" in event)) continue;
const tool = event.tool as ContextObjectTool;
const hint = tool.action?.routingHint?.trim();
if (!hint) continue;
const key = normalizePlannerToolName(tool.name);
if (seen.has(key)) continue;
seen.add(key);
lines.push(`- ${hint}`);
}
const result =
lines.length === 0 ? null : ["# Routing hints", ...lines].join("\n");
if (events) {
ROUTING_HINTS_MEMO.set(events, result);
}
return result;
}
/**
* Collect the tool/action events exposed for the current planner scope. Used
* to drive the per-turn planner-action grammar emitter (response-grammar.ts)
* and for sub-planner scoping (parent-action narrowing).
*/
function collectExposedTools(context: ContextObject): ContextObjectTool[] {
const parentAction =
typeof context.metadata?.subPlannerParentAction === "string"
? context.metadata.subPlannerParentAction
: "";
const inSubPlanner = parentAction.length > 0;
const tools: ContextObjectTool[] = [];
const seen = new Set<string>();
for (const event of context.events ?? []) {
if (event.type !== "tool" || !("tool" in event)) {
continue;
}
const tool = event.tool as ContextObjectTool;
if (!tool.name) {
continue;
}
const parentMatches =
typeof tool.metadata?.parentAction === "string" &&
tool.metadata.parentAction === parentAction;
if (inSubPlanner) {
if (event.source !== "sub-planner" && !parentMatches) {
continue;
}
} else if (event.source === "sub-planner" || parentMatches) {
continue;
}
const key = normalizePlannerToolName(tool.name);
if (seen.has(key)) {
continue;
}
seen.add(key);
tools.push(tool);
}
return tools;
}
export function parsePlannerOutput(raw: string | GenerateTextResult): {
thought?: string;
toolCalls: PlannerToolCall[];
messageToUser?: string;
raw: Record<string, unknown>;
} {
if (typeof raw === "string") {
return parseJsonPlannerOutput(raw);
}
const nativeToolCalls = normalizeToolCalls(raw.toolCalls);
const text = getNonEmptyString(raw.text);
// gpt-oss-class models narrate planner calls in the text channel. There
// are two observed shapes:
// 1. PLAN_ACTIONS({...}) or bare `{action,parameters}` text when native
// extraction returns nothing; recover one planner call from that text.
// 2. concatenated `{type,args}` JSON objects where native extraction
// captures only the first call; merge the missing calls back in.
let textRecoveredCalls: PlannerToolCall[] = [];
let recoverySource: string | undefined;
let recoveredThought: string | undefined;
if (nativeToolCalls.length === 0 && typeof text === "string") {
const extracted = extractPlanActionsFromContent(text);
if (extracted) {
textRecoveredCalls = [
{
name: extracted.action,
params: extracted.parameters,
},
];
recoverySource = extracted.recoverySource;
recoveredThought = extracted.thought;
}
}
const embeddedToolCalls = parseEmbeddedToolCalls(raw.text);
const embeddedObjectCount =
typeof raw.text === "string" ? extractJsonObjects(raw.text).length : 0;
if (
embeddedToolCalls.length > 0 &&
(nativeToolCalls.length === 0 || embeddedObjectCount > 1)
) {
textRecoveredCalls = mergeToolCalls(textRecoveredCalls, embeddedToolCalls);
}
const toolCalls = mergeToolCalls(nativeToolCalls, textRecoveredCalls);
return {
thought: recoveredThought,
toolCalls,
// When `raw.text` was itself tool-call JSON it is not a user-facing
// message — take the reply from a REPLY call rather than leaking the
// raw JSON blob into the channel.
messageToUser:
textRecoveredCalls.length > 0
? terminalMessageFromToolCalls(toolCalls)
: text,
raw: {
text: raw.text,
toolCalls: raw.toolCalls,
...(recoverySource ? { textRecoverySource: recoverySource } : {}),
} as Record<string, unknown>,
};
}
function parseJsonPlannerOutput(raw: string): {
thought?: string;
toolCalls: PlannerToolCall[];
messageToUser?: string;
raw: Record<string, unknown>;
} {
const trimmed = raw.trim();
const parsed = parseJsonObject<RawPlannerOutput>(trimmed);
if (!parsed) {
// Tolerant in-text fallback (elizaOS/eliza#7620): the raw output isn't
// JSON, but it might contain a `PLAN_ACTIONS({...})` envelope as text.
const extracted = extractPlanActionsFromContent(trimmed);
if (extracted) {
return {
thought: extracted.thought,
toolCalls: [{ name: extracted.action, params: extracted.parameters }],
raw: {
text: trimmed,
textRecoverySource: extracted.recoverySource,
},
};
}
return {
toolCalls: [],
messageToUser: getNonEmptyString(trimmed),
raw: { text: trimmed },
};
}
const messageToUser = getNonEmptyString(parsed.messageToUser ?? parsed.text);
const toolCalls = normalizeToolCalls(parsed.toolCalls);
const bareActionCalls =
toolCalls.length === 0 ? normalizeBarePlannerAction(parsed) : [];
let resolvedCalls = toolCalls.length > 0 ? toolCalls : bareActionCalls;
// `parseJsonObject` only returns the FIRST top-level object, so a weak
// model that concatenated bare `{type, args}` calls would lose every one
// after the first. Recover the full set from the raw string.
if (resolvedCalls.length === 0) {
resolvedCalls = parseEmbeddedToolCalls(trimmed);
}
return {
thought: typeof parsed.thought === "string" ? parsed.thought : undefined,
toolCalls: resolvedCalls,
messageToUser,
raw: parsed as Record<string, unknown>,
};
}
async function callPlanner(params: {
runtime: PlannerRuntime;
context: ContextObject;
trajectory: PlannerTrajectory;
config: ChainingLoopConfig;
modelType?: TextGenerationModelType;
provider?: string;
tools?: ToolDefinition[];
toolChoice?: ToolChoice;
recorder?: TrajectoryRecorder;
trajectoryId?: string;
parentStageId?: string;
iteration?: number;
/**
* Side-channel observer called once per model call with the gross
* `promptTokens` reported by the provider. Used by `runPlannerLoop`
* to enforce `ChainingLoopConfig.maxTrajectoryPromptTokens` without
* changing this function's return type. Errors thrown from the
* callback (e.g. `TrajectoryLimitExceeded`) propagate to the loop.
*/
onUsage?: (usage: { promptTokens: number; completionTokens: number }) => void;
}): Promise<ReturnType<typeof parsePlannerOutput>> {
let renderedInput = renderPlannerModelInput({
context: params.context,
trajectory: params.trajectory,
template: resolveOptimizedPlannerTemplate(params.runtime),
runtime: params.runtime,
maxToolResultChars: params.config.compactionMaxKeptStepChars,
});
let modelInputBudget = buildModelInputBudget({
messages: renderedInput.messages,
promptSegments: renderedInput.promptSegments,
tools: params.tools,
// `modelName` lets the per-model context-window lookup fire.
// The lookup result wins over contextWindowTokens (see buildModelInputBudget
// resolution order). Note: contextWindowTokens defaults to 128_000 so the
// spread is always non-empty; the lookup will still override it when
// contextWindowModelName resolves.
modelName: params.config.contextWindowModelName,
...(params.config.contextWindowTokens
? { contextWindowTokens: params.config.contextWindowTokens }
: {}),
reserveTokens: compactionReserveForBudget(params.config),
});
if (modelInputBudget.shouldCompact && params.config.compactionEnabled) {
const compacted = await maybeCompactPlannerTrajectory({
trajectory: params.trajectory,
budget: modelInputBudget,
config: params.config,
recorder: params.recorder,
trajectoryId: params.trajectoryId,
parentStageId: params.parentStageId,
iteration: params.iteration ?? 1,
logger: params.runtime.logger,
});
if (compacted) {
renderedInput = renderPlannerModelInput({
context: params.trajectory.context,
trajectory: params.trajectory,
template: resolveOptimizedPlannerTemplate(params.runtime),
runtime: params.runtime,
maxToolResultChars: params.config.compactionMaxKeptStepChars,
});
modelInputBudget = buildModelInputBudget({
messages: renderedInput.messages,
promptSegments: renderedInput.promptSegments,
tools: params.tools,
modelName: params.config.contextWindowModelName,
...(params.config.contextWindowTokens
? { contextWindowTokens: params.config.contextWindowTokens }
: {}),
reserveTokens: compactionReserveForBudget(params.config),
});
}
}
const prefixHashes = computePrefixHashes(renderedInput.promptSegments);
const cachePrefixHashes = computePrefixHashes(
cachePrefixSegments(renderedInput.promptSegments),
);
const prefixHash =
cachePrefixHashes[cachePrefixHashes.length - 1]?.hash ??
"no-context-segments";
const hasTools = Array.isArray(params.tools) && params.tools.length > 0;
const modelParams: {
messages: ChatMessage[];
responseSchema?: unknown;
promptSegments: PromptSegment[];
providerOptions: Record<string, unknown>;
tools?: ToolDefinition[];
toolChoice?: ToolChoice;
responseSkeleton?: ResponseSkeleton;
grammar?: string;
spanSamplerPlan?: SpanSamplerPlan;
} = {
messages: renderedInput.messages,
promptSegments: renderedInput.promptSegments,
providerOptions: withModelInputBudgetProviderOptions(
cacheProviderOptions({
prefixHash,
segmentHashes: prefixHashes.map((entry) => entry.segmentHash),
promptSegments: renderedInput.promptSegments,
provider: params.provider,
hasTools,
conversationId: params.trajectoryId,
}),
modelInputBudget,
),
};
if (hasTools) {
modelParams.tools = params.tools;
// Force a native tool call. With actions exposed directly as tools
// (post-PLAN_ACTIONS-wrapper refactor), every viable planner outcome —
// invoking an action, calling REPLY for a final message, or terminating
// via IGNORE / STOP — corresponds to a tool. There is no "the model
// shouldn't tool-call" case left, so `"required"` is the contract.
// Models that can't comply fail loudly; we don't degrade to text mode.
modelParams.toolChoice = params.toolChoice ?? "required";
// Per-turn structure forcing for the PLAN_ACTIONS args: pin `action` to
// the exact enum of actions exposed this turn and carry each action's
// normalized parameter schema so the local engine (W4) can do the
// second constrained pass (`parameters` against the chosen action's
// schema). Cloud adapters may ignore local structured-output hints like
// `responseSkeleton`, `grammar`, and
// `providerOptions.eliza.plannerActionSchemas`; `tools` carries the
// equivalent portable contract for them.