-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathagent.ts
More file actions
1425 lines (1264 loc) · 45.4 KB
/
Copy pathagent.ts
File metadata and controls
1425 lines (1264 loc) · 45.4 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
/** Agent class that uses the agent-loop directly.
* No transport abstraction - calls streamSimple via the loop.
*/
import { isPromise } from "node:util/types";
import {
type ApiKey,
type AssistantMessage,
type AssistantMessageEvent,
type Context,
type CursorExecHandlers,
type CursorToolResultHandler,
type Effort,
type ImageContent,
type Message,
type Model,
type ProviderSessionState,
type ServiceTier,
type SimpleStreamOptions,
streamSimple,
type TextContent,
type ThinkingBudgets,
type ToolChoice,
type ToolResultMessage,
} from "@oh-my-pi/pi-ai";
import type { Dialect } from "@oh-my-pi/pi-ai/dialect";
import type { HarmonyAuditEvent } from "@oh-my-pi/pi-ai/utils/harmony-leak";
import { preferredDialect } from "@oh-my-pi/pi-catalog/identity";
import { getBundledModel } from "@oh-my-pi/pi-catalog/models";
import { logger } from "@oh-my-pi/pi-utils";
import {
abortReasonText,
agentLoop,
agentLoopContinue,
normalizeMessagesForProvider,
normalizeTools,
resolveOwnedDialectFromEnv,
} from "./agent-loop";
import type { AppendOnlyContextManager } from "./append-only-context";
import type {
AgentContext,
AgentEvent,
AgentLoopConfig,
AgentMessage,
AgentState,
AgentTool,
AgentToolContext,
AsideMessage,
StreamFn,
ToolCallContext,
ToolChoiceDirective,
} from "./types";
import { isSoftToolRequirement } from "./types";
import { EventLoopKeepalive } from "./utils/yield";
/**
* Default convertToLlm: Keep only LLM-compatible messages, convert attachments.
*/
function defaultConvertToLlm(messages: AgentMessage[]): Message[] {
return messages.filter((m): m is Message => m.role === "user" || m.role === "assistant" || m.role === "toolResult");
}
const ANTHROPIC_OUTPUT_BLOCKED_PREFIX = "Output blocked by conten";
function isAnthropicOutputBlockedError(message: string): boolean {
return message.includes(ANTHROPIC_OUTPUT_BLOCKED_PREFIX);
}
function refreshToolChoiceForActiveTools(
toolChoice: ToolChoice | undefined,
tools: AgentContext["tools"] = [],
): ToolChoice | undefined {
if (!toolChoice || typeof toolChoice === "string") {
return toolChoice;
}
const toolName =
toolChoice.type === "tool"
? toolChoice.name
: "function" in toolChoice
? toolChoice.function.name
: toolChoice.name;
return tools.some(tool => tool.name === toolName) ? toolChoice : undefined;
}
export class AgentBusyError extends Error {
constructor(
message: string = "Agent is already processing. Use steer() or followUp() to queue messages, or wait for completion.",
) {
super(message);
this.name = "AgentBusyError";
}
}
export interface AgentOptions {
initialState?: Partial<AgentState>;
/**
* Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.
* Default filters to user/assistant/toolResult and converts attachments.
*/
convertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
/**
* Optional transform applied to context before convertToLlm.
* Use for context pruning, injecting external context, etc.
*/
transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
/**
* Optional transform applied after provider context assembly and before
* telemetry capture/provider send.
*/
transformProviderContext?: (context: Context, model: Model) => Context | Promise<Context>;
/**
* Steering mode: "all" = send all steering messages at once, "one-at-a-time" = one per turn
*/
steeringMode?: "all" | "one-at-a-time";
/**
* Follow-up mode: "all" = send all follow-up messages at once, "one-at-a-time" = one per turn
*/
followUpMode?: "all" | "one-at-a-time";
/**
* When to interrupt tool execution for steering messages.
* - "immediate": check after each tool call (default)
* - "wait": defer steering until the current turn completes
*/
interruptMode?: "immediate" | "wait";
/**
* API format for Kimi Code provider: "openai" or "anthropic" (default: "anthropic")
*/
kimiApiFormat?: "openai" | "anthropic";
/** Hint that websocket transport should be preferred when supported by the provider implementation. */
preferWebsockets?: boolean;
/**
* Custom stream function (for proxy backends, etc.). Default uses streamSimple.
*/
streamFn?: StreamFn;
/** Absolute wall-clock deadline in Unix epoch milliseconds. */
deadline?: number;
/**
* Optional session identifier forwarded to LLM providers.
* Used by providers that support session-based caching (e.g., OpenAI Codex).
*/
sessionId?: string;
/**
* Optional prompt cache key forwarded to LLM providers.
* When omitted, providers may fall back to sessionId.
*/
promptCacheKey?: string;
/**
* Shared provider state map for session-scoped transport/session caches.
*/
providerSessionState?: Map<string, ProviderSessionState>;
/**
* Resolves an API key or resolver dynamically for each LLM call.
* Useful for expiring tokens and model-scoped credential routing.
*/
getApiKey?: (model: Model) => Promise<ApiKey | undefined> | ApiKey | undefined;
/**
* Inspect or replace provider payloads before they are sent.
*/
onPayload?: SimpleStreamOptions["onPayload"];
/**
* Inspect provider response metadata after headers arrive and before streaming body consumption.
*/
onResponse?: SimpleStreamOptions["onResponse"];
/**
* Inspect raw Server-Sent Events from HTTP streaming providers.
*/
onSseEvent?: SimpleStreamOptions["onSseEvent"];
/**
* Inspect assistant streaming events before they are emitted to subscribers.
* Use this when abort decisions must happen before buffered events continue flowing.
*/
onAssistantMessageEvent?: (message: AssistantMessage, event: AssistantMessageEvent) => void;
/**
* Called when GPT-5 Harmony protocol leakage is detected and mitigated.
*/
onHarmonyLeak?: (event: HarmonyAuditEvent) => void | Promise<void>;
/**
* Custom token budgets for thinking levels (token-based providers only).
*/
thinkingBudgets?: ThinkingBudgets;
/**
* Sampling temperature for LLM calls. `undefined` uses provider default.
*/
temperature?: number;
/** Additional sampling controls for providers that support them. */
topP?: number;
topK?: number;
minP?: number;
presencePenalty?: number;
repetitionPenalty?: number;
serviceTier?: ServiceTier;
/**
* Per-call effective service-tier resolver. When set, it authoritatively
* supplies the request's tier (replacing the static `serviceTier` and its
* telemetry) per model — used to scope a provider/model into a priority
* serving path without mutating the shared session `serviceTier`.
*/
serviceTierResolver?: (model: Model) => ServiceTier | undefined;
/**
* If true, request that the underlying provider omit reasoning/thinking summaries
* from the response. The model still reasons internally; only the human-readable
* summary stream is suppressed. Useful when the UI hides thinking blocks anyway.
*/
hideThinkingSummary?: boolean;
/**
* Maximum delay in milliseconds to wait for a retry when the server requests a long wait.
* If the server's requested delay exceeds this value, the request fails immediately,
* allowing higher-level retry logic to handle it with user visibility.
* Default: 60000 (60 seconds). Set to 0 to disable the cap.
*/
maxRetryDelayMs?: number;
/**
* Provides tool execution context, resolved per tool call.
* Use for late-bound UI or session state access.
*/
getToolContext?: (toolCall?: ToolCallContext) => AgentToolContext | undefined;
/**
* Optional transform applied to tool call arguments before execution.
* Use for deobfuscating secrets or rewriting arguments.
*/
transformToolCallArguments?: (args: Record<string, unknown>, toolName: string) => Record<string, unknown>;
/** Enable intent tracing schema injection/stripping in the harness. */
intentTracing?: boolean;
/**
* Strip tool descriptions from provider-bound tool specs (top-level + nested
* schema annotations). Use when the full catalog is rendered into the system
* prompt so descriptions are not duplicated on the wire. Native tool calling only.
*/
pruneToolDescriptions?: boolean;
/** Owned tool-calling dialect. Undefined keeps provider-native tool calling. */
dialect?: Dialect;
/**
* When owned tool calling is active and the model fabricates a tool result
* mid-turn: `true` (default) aborts the provider request immediately; `false`
* drains the request and discards the fabricated continuation. Forwarded to
* the loop's {@link AgentLoopConfig.abortOnFabricatedToolResult}.
*/
abortOnFabricatedToolResult?: boolean;
/** Dynamic tool-choice directive (hard {@link ToolChoice} or {@link SoftToolRequirement}), resolved once per turn. */
getToolChoice?: () => ToolChoiceDirective | undefined;
/**
* Cursor exec handlers for local tool execution.
*/
cursorExecHandlers?: CursorExecHandlers;
/**
* Cursor tool result callback for exec tool responses.
*/
cursorOnToolResult?: CursorToolResultHandler;
/**
* Called after a tool call has been validated and is about to execute.
* See {@link AgentLoopConfig.beforeToolCall} for full semantics.
*/
beforeToolCall?: AgentLoopConfig["beforeToolCall"];
/**
* Called after a tool finishes executing, before `tool_execution_end` and the tool-result
* message are emitted. See {@link AgentLoopConfig.afterToolCall} for full semantics.
*/
afterToolCall?: AgentLoopConfig["afterToolCall"];
/**
* Called once an assistant message is finalized, before it reaches the
* context, the UI, or tool dispatch. May mutate the message in place (text +
* tool-call arguments). See {@link AgentLoopConfig.transformAssistantMessage}.
*/
transformAssistantMessage?: AgentLoopConfig["transformAssistantMessage"];
/**
* Opt-in OpenTelemetry instrumentation. Passing `{}` enables the loop's
* GenAI-semantic-convention spans using the global tracer provider. See
* {@link AgentLoopConfig.telemetry} for the full surface.
*/
telemetry?: AgentLoopConfig["telemetry"];
/**
* Immutable context mode — stabilizes system prompt + tool spec bytes
* across turns so DeepSeek/Anthropic prefix caches hit at maximum rate.
*/
appendOnlyContext?: AppendOnlyContextManager;
}
export interface AgentPromptOptions {
toolChoice?: ToolChoice;
}
/** Buffered Cursor tool result with text position at time of call */
interface CursorToolResultEntry {
toolResult: ToolResultMessage;
textLengthAtCall: number;
}
export class Agent {
#state: AgentState = {
systemPrompt: [],
model: getBundledModel("google", "gemini-2.5-flash-lite-preview-06-17"),
thinkingLevel: undefined,
disableReasoning: false,
tools: [],
messages: [],
isStreaming: false,
streamMessage: null,
pendingToolCalls: new Set<string>(),
error: undefined,
};
#listeners = new Set<(e: AgentEvent) => void>();
#abortController?: AbortController;
#convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
#transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
#transformProviderContext?: (context: Context, model: Model) => Context | Promise<Context>;
#steeringQueue: AgentMessage[] = [];
#followUpQueue: AgentMessage[] = [];
#steeringMode: "all" | "one-at-a-time";
#followUpMode: "all" | "one-at-a-time";
#interruptMode: "immediate" | "wait";
#sessionId?: string;
#deadline?: number;
#promptCacheKey?: string;
#metadata?: Record<string, unknown>;
#metadataResolver?: (provider: string) => Record<string, unknown> | undefined;
#providerSessionState?: Map<string, ProviderSessionState>;
#thinkingBudgets?: ThinkingBudgets;
#temperature?: number;
#topP?: number;
#topK?: number;
#minP?: number;
#presencePenalty?: number;
#repetitionPenalty?: number;
#serviceTier?: ServiceTier;
#serviceTierResolver?: (model: Model) => ServiceTier | undefined;
#hideThinkingSummary?: boolean;
#maxRetryDelayMs?: number;
#getToolContext?: (toolCall?: ToolCallContext) => AgentToolContext | undefined;
#cursorExecHandlers?: CursorExecHandlers;
#cursorOnToolResult?: CursorToolResultHandler;
#runningPrompt?: Promise<void>;
#resolveRunningPrompt?: () => void;
#kimiApiFormat?: "openai" | "anthropic";
#preferWebsockets?: boolean;
#transformToolCallArguments?: (args: Record<string, unknown>, toolName: string) => Record<string, unknown>;
#intentTracing: boolean;
#pruneToolDescriptions: boolean;
#dialect?: Dialect;
#abortOnFabricatedToolResult?: boolean;
#getToolChoice?: () => ToolChoiceDirective | undefined;
#onPayload?: SimpleStreamOptions["onPayload"];
#onResponse?: SimpleStreamOptions["onResponse"];
#onSseEvent?: SimpleStreamOptions["onSseEvent"];
#onAssistantMessageEvent?: (message: AssistantMessage, event: AssistantMessageEvent) => void;
#onHarmonyLeak?: (event: HarmonyAuditEvent) => void | Promise<void>;
#onBeforeYield?: () => Promise<void> | void;
#onTurnEnd?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<void> | void;
#asideMessageProvider?: () => AsideMessage[] | Promise<AsideMessage[]>;
#telemetry?: AgentLoopConfig["telemetry"];
#appendOnlyContext?: AppendOnlyContextManager;
/** Buffered Cursor tool results with text length at time of call (for correct ordering) */
#cursorToolResultBuffer: CursorToolResultEntry[] = [];
streamFn: StreamFn;
getApiKey?: (model: Model) => Promise<ApiKey | undefined> | ApiKey | undefined;
/**
* Hook invoked after tool arguments are validated and before execution.
* Reassign at any time to swap the implementation (e.g. on extension reload).
*/
beforeToolCall?: AgentLoopConfig["beforeToolCall"];
/**
* Hook invoked after tool execution and before `tool_execution_end` / tool-result
* message emission. Reassign at any time to swap the implementation.
*/
afterToolCall?: AgentLoopConfig["afterToolCall"];
/**
* Hook invoked once an assistant message is finalized, before context append,
* UI emission, and tool dispatch. Reassign at any time to swap the implementation.
*/
transformAssistantMessage?: AgentLoopConfig["transformAssistantMessage"];
constructor(opts: AgentOptions = {}) {
this.#state = { ...this.#state, ...opts.initialState };
if (opts.initialState?.messages) this.#state.messages = opts.initialState.messages.slice();
if (opts.initialState?.pendingToolCalls)
this.#state.pendingToolCalls = new Set(opts.initialState.pendingToolCalls);
this.#convertToLlm = opts.convertToLlm || defaultConvertToLlm;
this.#transformContext = opts.transformContext;
this.#steeringMode = opts.steeringMode || "one-at-a-time";
this.#followUpMode = opts.followUpMode || "one-at-a-time";
this.#interruptMode = opts.interruptMode || "immediate";
this.streamFn = opts.streamFn || streamSimple;
this.#sessionId = opts.sessionId;
this.#deadline = opts.deadline;
this.#promptCacheKey = opts.promptCacheKey;
this.#providerSessionState = opts.providerSessionState;
this.#thinkingBudgets = opts.thinkingBudgets;
this.#temperature = opts.temperature;
this.#topP = opts.topP;
this.#topK = opts.topK;
this.#minP = opts.minP;
this.#presencePenalty = opts.presencePenalty;
this.#repetitionPenalty = opts.repetitionPenalty;
this.#serviceTier = opts.serviceTier;
this.#serviceTierResolver = opts.serviceTierResolver;
this.#hideThinkingSummary = opts.hideThinkingSummary;
this.#maxRetryDelayMs = opts.maxRetryDelayMs;
this.getApiKey = opts.getApiKey;
this.#onPayload = opts.onPayload;
this.#onResponse = opts.onResponse;
this.#onSseEvent = opts.onSseEvent;
this.#getToolContext = opts.getToolContext;
this.#cursorExecHandlers = opts.cursorExecHandlers;
this.#cursorOnToolResult = opts.cursorOnToolResult;
this.#kimiApiFormat = opts.kimiApiFormat;
this.#preferWebsockets = opts.preferWebsockets;
this.#transformToolCallArguments = opts.transformToolCallArguments;
this.#intentTracing = opts.intentTracing === true;
this.#pruneToolDescriptions = opts.pruneToolDescriptions === true;
this.#dialect = opts.dialect;
this.#abortOnFabricatedToolResult = opts.abortOnFabricatedToolResult;
this.#getToolChoice = opts.getToolChoice;
this.#onAssistantMessageEvent = opts.onAssistantMessageEvent;
this.#onHarmonyLeak = opts.onHarmonyLeak;
this.beforeToolCall = opts.beforeToolCall;
this.afterToolCall = opts.afterToolCall;
this.transformAssistantMessage = opts.transformAssistantMessage;
this.#telemetry = opts.telemetry;
this.#appendOnlyContext = opts.appendOnlyContext;
this.#transformProviderContext = opts.transformProviderContext;
}
/**
* Get the current session ID used for provider caching.
*/
get sessionId(): string | undefined {
return this.#sessionId;
}
/**
* Set the session ID for provider caching.
* Call this when switching sessions (new session, branch, resume).
*/
set sessionId(value: string | undefined) {
this.#sessionId = value;
}
/**
* Get the prompt cache key forwarded to providers.
*/
get promptCacheKey(): string | undefined {
return this.#promptCacheKey;
}
/**
* Set the prompt cache key forwarded to providers.
*/
set promptCacheKey(value: string | undefined) {
this.#promptCacheKey = value;
}
/**
* Static metadata forwarded to every API request when no resolver is installed
* (e.g. `metadata.user_id` for Anthropic session attribution). Setting this
* clears any installed resolver.
*
* For live/provider-aware metadata (e.g. Anthropic OAuth `account_uuid` that
* must reflect the credential selected per-request), use
* {@link setMetadataResolver} and read via {@link metadataForProvider}.
*/
get metadata(): Record<string, unknown> | undefined {
return this.#metadata;
}
set metadata(value: Record<string, unknown> | undefined) {
this.#metadata = value;
this.#metadataResolver = undefined;
}
/**
* Resolve request metadata for the given provider at call time. When a
* resolver is installed via {@link setMetadataResolver}, it is invoked with
* the provider string so the result can be scoped (e.g. `account_uuid` is
* only included for `"anthropic"` requests). Falls back to the static
* {@link metadata} value when no resolver is set.
*/
metadataForProvider(provider: string): Record<string, unknown> | undefined {
if (this.#metadataResolver) return this.#metadataResolver(provider);
return this.#metadata;
}
/**
* Install a function that resolves request metadata at call time. The
* resolver receives the target provider string and can gate provider-specific
* fields (e.g. `account_uuid` only for `"anthropic"`). Invoked per LLM
* request by `agent-loop` after `getApiKey` selects the session-sticky
* credential. Pass `undefined` to clear and revert to the static
* {@link metadata} value.
*/
setMetadataResolver(resolver: ((provider: string) => Record<string, unknown> | undefined) | undefined): void {
this.#metadataResolver = resolver;
}
/**
* Read the active OpenTelemetry configuration. Returns `undefined` when
* instrumentation is disabled. Callers spawning child runs (e.g. subagent
* dispatch) forward this to the child's loop so its spans appear under the
* parent's active context with the subagent's own identity stamped.
*/
get telemetry(): AgentLoopConfig["telemetry"] | undefined {
return this.#telemetry;
}
/**
* Replace the active OpenTelemetry configuration. Pass `undefined` to
* disable instrumentation. Applies to the *next* `agentLoop` invocation —
* in-flight loops keep the configuration they started with.
*/
setTelemetry(telemetry: AgentLoopConfig["telemetry"] | undefined): void {
this.#telemetry = telemetry;
}
/**
* Get provider-scoped mutable session state store.
*/
get providerSessionState(): Map<string, ProviderSessionState> | undefined {
return this.#providerSessionState;
}
/**
* Set provider-scoped mutable session state store.
*/
set providerSessionState(value: Map<string, ProviderSessionState> | undefined) {
this.#providerSessionState = value;
}
/**
* Get the current thinking budgets.
*/
get thinkingBudgets(): ThinkingBudgets | undefined {
return this.#thinkingBudgets;
}
/**
* Set custom thinking budgets for token-based providers.
*/
set thinkingBudgets(value: ThinkingBudgets | undefined) {
this.#thinkingBudgets = value;
}
/**
* Get the current sampling temperature.
*/
get temperature(): number | undefined {
return this.#temperature;
}
/**
* Set sampling temperature for LLM calls. `undefined` uses provider default.
*/
set temperature(value: number | undefined) {
this.#temperature = value;
}
get topP(): number | undefined {
return this.#topP;
}
set topP(value: number | undefined) {
this.#topP = value;
}
get topK(): number | undefined {
return this.#topK;
}
set topK(value: number | undefined) {
this.#topK = value;
}
get minP(): number | undefined {
return this.#minP;
}
set minP(value: number | undefined) {
this.#minP = value;
}
get presencePenalty(): number | undefined {
return this.#presencePenalty;
}
set presencePenalty(value: number | undefined) {
this.#presencePenalty = value;
}
get repetitionPenalty(): number | undefined {
return this.#repetitionPenalty;
}
set repetitionPenalty(value: number | undefined) {
this.#repetitionPenalty = value;
}
get serviceTier(): ServiceTier | undefined {
return this.#serviceTier;
}
set serviceTier(value: ServiceTier | undefined) {
this.#serviceTier = value;
}
get serviceTierResolver(): ((model: Model) => ServiceTier | undefined) | undefined {
return this.#serviceTierResolver;
}
set serviceTierResolver(value: ((model: Model) => ServiceTier | undefined) | undefined) {
this.#serviceTierResolver = value;
}
get hideThinkingSummary(): boolean | undefined {
return this.#hideThinkingSummary;
}
set hideThinkingSummary(value: boolean | undefined) {
this.#hideThinkingSummary = value;
}
/**
* Get the current max retry delay in milliseconds.
*/
get maxRetryDelayMs(): number | undefined {
return this.#maxRetryDelayMs;
}
/**
* Set the maximum delay to wait for server-requested retries.
* Set to 0 to disable the cap.
*/
set maxRetryDelayMs(value: number | undefined) {
this.#maxRetryDelayMs = value;
}
get state(): AgentState {
return this.#state;
}
get appendOnlyContext(): AppendOnlyContextManager | undefined {
return this.#appendOnlyContext;
}
setAppendOnlyContext(manager?: AppendOnlyContextManager): void {
this.#appendOnlyContext = manager;
}
/**
* Assemble the provider Context for a side-channel (no-loop) request, mirroring
* the main loop's prefix (system + normalized tools) so it shares the prompt
* cache. Never touches the append-only log or the tool-choice queue. Owned/
* in-band dialect sessions stay tools-less (matching their no-native-tools wire
* shape and avoiding tool-markup leakage). `llmMessages` is already converted
* (and, in production, obfuscated) by the caller.
*
* `systemPrompt` defaults to the live agent prompt so the side request hits the
* same cached prefix as the main loop. Callers that must pin a different prompt
* (e.g. handoff generation, which uses the base prompt rather than a per-turn
* `before_agent_start` hook override) pass it explicitly.
*/
async buildSideRequestContext(
llmMessages: Message[],
systemPrompt: string[] = this.#state.systemPrompt,
): Promise<Context> {
const model = this.#state.model;
if (!model) throw new Error("No active model on agent");
const ownedDialect = this.#dialect ?? resolveOwnedDialectFromEnv(Bun.env.PI_DIALECT);
const messages = normalizeMessagesForProvider(llmMessages, model);
const tools = ownedDialect
? []
: (normalizeTools(
this.#state.tools,
this.#intentTracing,
preferredDialect(model.id),
this.#pruneToolDescriptions,
) ?? []);
let context: Context = { systemPrompt, messages, tools };
if (this.#transformProviderContext) context = await this.#transformProviderContext(context, model);
return context;
}
subscribe(fn: (e: AgentEvent) => void): () => void {
this.#listeners.add(fn);
return () => this.#listeners.delete(fn);
}
setProviderResponseInterceptor(fn: SimpleStreamOptions["onResponse"] | undefined): void {
this.#onResponse = fn;
}
setRawSseEventInterceptor(fn: SimpleStreamOptions["onSseEvent"] | undefined): void {
this.#onSseEvent = fn;
}
setAssistantMessageEventInterceptor(
fn: ((message: AssistantMessage, event: AssistantMessageEvent) => void) | undefined,
): void {
this.#onAssistantMessageEvent = fn;
}
setOnBeforeYield(fn: (() => Promise<void> | void) | undefined): void {
this.#onBeforeYield = fn;
}
setOnTurnEnd(fn: ((messages: AgentMessage[], signal?: AbortSignal) => Promise<void> | void) | undefined): void {
this.#onTurnEnd = fn;
}
/**
* Provide a source of non-interrupting "aside" messages (e.g. background-job
* completions, late LSP diagnostics) drained at each step boundary. Never
* aborts in-flight tools. See `AgentLoopConfig.getAsideMessages`.
*/
setAsideMessageProvider(fn: (() => AsideMessage[] | Promise<AsideMessage[]>) | undefined): void {
this.#asideMessageProvider = fn;
}
emitExternalEvent(event: AgentEvent) {
switch (event.type) {
case "message_start":
case "message_update":
this.#state.streamMessage = event.message;
break;
case "message_end":
this.#state.streamMessage = null;
this.appendMessage(event.message);
break;
case "tool_execution_start":
this.#state.pendingToolCalls.add(event.toolCallId);
break;
case "tool_execution_end":
this.#state.pendingToolCalls.delete(event.toolCallId);
break;
}
this.#emit(event);
}
// State mutators
setSystemPrompt(v: string[] | string) {
this.#state.systemPrompt = typeof v === "string" ? [v] : v;
}
setModel(m: Model) {
this.#state.model = m;
}
setThinkingLevel(l: Effort | undefined) {
this.#state.thinkingLevel = l;
}
setDisableReasoning(disabled: boolean) {
this.#state.disableReasoning = disabled;
}
setSteeringMode(mode: "all" | "one-at-a-time") {
this.#steeringMode = mode;
}
getSteeringMode(): "all" | "one-at-a-time" {
return this.#steeringMode;
}
setFollowUpMode(mode: "all" | "one-at-a-time") {
this.#followUpMode = mode;
}
getFollowUpMode(): "all" | "one-at-a-time" {
return this.#followUpMode;
}
setInterruptMode(mode: "immediate" | "wait") {
this.#interruptMode = mode;
}
getInterruptMode(): "immediate" | "wait" {
return this.#interruptMode;
}
setTools(t: AgentTool<any>[]) {
this.#state.tools = t;
}
replaceMessages(ms: AgentMessage[]) {
// New array assignment is intentional: caller-owned `ms` may be mutated
// after handoff; snapshot it so external mutations cannot leak in.
this.#state.messages = ms.slice();
}
replaceQueues(steering: AgentMessage[], followUp: AgentMessage[]) {
this.#steeringQueue = steering.slice();
this.#followUpQueue = followUp.slice();
}
appendMessage(m: AgentMessage) {
this.#state.messages.push(m);
}
popMessage(): AgentMessage | undefined {
const removed = this.#state.messages.pop();
if (removed && this.#state.streamMessage === removed) {
this.#state.streamMessage = null;
}
return removed;
}
/**
* Queue a steering message to interrupt the agent mid-run.
* Delivered after current tool execution, skips remaining tools.
*/
steer(m: AgentMessage) {
this.#steeringQueue.push(m);
}
/**
* Queue a follow-up message to be processed after the agent finishes.
* Delivered only when agent has no more tool calls or steering messages.
*/
followUp(m: AgentMessage) {
this.#followUpQueue.push(m);
}
clearSteeringQueue() {
this.#steeringQueue = [];
}
clearFollowUpQueue() {
this.#followUpQueue = [];
}
clearAllQueues() {
this.#steeringQueue = [];
this.#followUpQueue = [];
}
hasQueuedMessages(): boolean {
return this.#steeringQueue.length > 0 || this.#followUpQueue.length > 0;
}
/** Non-consuming view of the pending steering queue (insertion order, newest
* last). The session layer derives its queued-message display/count from
* this live view instead of a mirror, so the agent-core queue stays the
* single source of truth. */
peekSteeringQueue(): readonly AgentMessage[] {
return this.#steeringQueue;
}
/** Non-consuming view of the pending follow-up queue. See
* {@link peekSteeringQueue}. */
peekFollowUpQueue(): readonly AgentMessage[] {
return this.#followUpQueue;
}
get isAborting(): boolean {
return this.#abortController?.signal.aborted === true && this.#state.isStreaming;
}
#dequeueSteeringMessages(): AgentMessage[] {
if (this.#steeringMode === "one-at-a-time") {
if (this.#steeringQueue.length > 0) {
const first = this.#steeringQueue[0];
this.#steeringQueue = this.#steeringQueue.slice(1);
return [first];
}
return [];
}
const steering = this.#steeringQueue.slice();
this.#steeringQueue = [];
return steering;
}
#dequeueFollowUpMessages(): AgentMessage[] {
if (this.#followUpMode === "one-at-a-time") {
if (this.#followUpQueue.length > 0) {
const first = this.#followUpQueue[0];
this.#followUpQueue = this.#followUpQueue.slice(1);
return [first];
}
return [];
}
const followUp = this.#followUpQueue.slice();
this.#followUpQueue = [];
return followUp;
}
/**
* Remove and return the last steering message from the queue (LIFO).
* Used by dequeue keybinding.
*/
popLastSteer(): AgentMessage | undefined {
return this.#steeringQueue.pop();
}
/**
* Remove and return the last follow-up message from the queue (LIFO).
* Used by dequeue keybinding.
*/
popLastFollowUp(): AgentMessage | undefined {
return this.#followUpQueue.pop();
}
clearMessages() {
this.#state.messages.length = 0;
}
abort(reason?: unknown) {
this.#abortController?.abort(reason);
}
waitForIdle(): Promise<void> {
return this.#runningPrompt ?? Promise.resolve();
}
reset() {
this.#state.messages.length = 0;
this.#state.isStreaming = false;
this.#state.streamMessage = null;
this.#state.pendingToolCalls.clear();
this.#state.error = undefined;
this.#steeringQueue = [];
this.#followUpQueue = [];
}
/** Send a prompt with an AgentMessage */
async prompt(message: AgentMessage | AgentMessage[], options?: AgentPromptOptions): Promise<void>;
async prompt(input: string, options?: AgentPromptOptions): Promise<void>;
async prompt(input: string, images?: ImageContent[], options?: AgentPromptOptions): Promise<void>;
async prompt(
input: string | AgentMessage | AgentMessage[],
imagesOrOptions?: ImageContent[] | AgentPromptOptions,
options?: AgentPromptOptions,
) {
if (this.#state.isStreaming) {
throw new AgentBusyError();
}
const model = this.#state.model;
if (!model) throw new Error("No model configured");
let msgs: AgentMessage[];
let promptOptions: AgentPromptOptions | undefined;
let images: ImageContent[] | undefined;
if (Array.isArray(input)) {
msgs = input;
promptOptions = imagesOrOptions as AgentPromptOptions | undefined;
} else if (typeof input === "string") {
if (Array.isArray(imagesOrOptions)) {
images = imagesOrOptions;
promptOptions = options;
} else {
promptOptions = imagesOrOptions;
}
const content: Array<TextContent | ImageContent> = [{ type: "text", text: input }];
if (images && images.length > 0) {
content.push(...images);
}
msgs = [
{
role: "user",
content,
timestamp: Date.now(),
},
];
} else {
msgs = [input];
promptOptions = imagesOrOptions as AgentPromptOptions | undefined;
}
await this.#runLoop(msgs, promptOptions);
}
/**
* Continue from current context (used for retries and resuming queued messages).
*/
async continue() {