-
Notifications
You must be signed in to change notification settings - Fork 730
Expand file tree
/
Copy pathrun.ts
More file actions
1624 lines (1518 loc) · 57.7 KB
/
run.ts
File metadata and controls
1624 lines (1518 loc) · 57.7 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 { Agent, AgentOutputType } from './agent';
import { RunAgentUpdatedStreamEvent, RunRawModelStreamEvent } from './events';
import { ModelBehaviorError, UserError } from './errors';
import {
defineInputGuardrail,
defineOutputGuardrail,
InputGuardrail,
OutputGuardrail,
} from './guardrail';
import type {
InputGuardrailDefinition,
InputGuardrailResult,
OutputGuardrailDefinition,
OutputGuardrailMetadata,
} from './guardrail';
import { Handoff, HandoffInputFilter } from './handoff';
import { RunHooks } from './lifecycle';
import logger from './logger';
import { Model, ModelProvider, ModelResponse, ModelSettings } from './model';
import { getDefaultModelProvider } from './providers';
import { RunContext } from './runContext';
import { RunResult, StreamedRunResult } from './result';
import { RunState } from './runState';
import { RunItem } from './items';
import { disposeResolvedComputers } from './tool';
import {
getOrCreateTrace,
resetCurrentSpan,
setCurrentSpan,
withNewSpanContext,
withTrace,
} from './tracing/context';
import type { TracingConfig } from './tracing';
import { Usage } from './usage';
import { convertAgentOutputTypeToSerializable } from './utils/tools';
import { DEFAULT_MAX_TURNS } from './runner/constants';
import { StreamEventResponseCompleted } from './types/protocol';
import type { Session, SessionInputCallback } from './memory/session';
import type { AgentInputItem } from './types';
import {
ServerConversationTracker,
applyCallModelInputFilter,
} from './runner/conversation';
import {
createGuardrailTracker,
runOutputGuardrails,
} from './runner/guardrails';
import {
adjustModelSettingsForNonGPT5RunnerModel,
mergeModelSettings,
maybeResetToolChoice,
selectModel,
} from './runner/modelSettings';
import {
getResponseWithRetry,
getStreamedResponseWithRetry,
} from './runner/modelRetry';
import { processModelResponseAsync } from './runner/modelOutputs';
import {
addStepToRunResult,
streamStepItemsToRunResult,
getUsageSnapshotFromStreamEvent,
isAbortError,
} from './runner/streaming';
import {
createSessionPersistenceTracker,
prepareInputItemsWithSession,
saveStreamInputToSession,
saveStreamResultToSession,
saveToSession,
} from './runner/sessionPersistence';
import { resolveTurnAfterModelResponse } from './runner/turnResolution';
import { prepareTurn } from './runner/turnPreparation';
import {
applyTurnResult,
handleInterruptedOutcome,
resumeInterruptedTurn,
} from './runner/runLoop';
import { applyTraceOverrides, getTracing } from './runner/tracing';
import type { ReasoningItemIdPolicy } from './runner/items';
import type {
AgentArtifacts,
CallModelInputFilter,
PreparedModelCall,
} from './runner/types';
import { tryHandleRunError } from './runner/errorHandlers';
import type { RunErrorHandlers } from './runner/errorHandlers';
export type {
CallModelInputFilter,
CallModelInputFilterArgs,
ModelInputData,
} from './runner/types';
export type {
RunErrorData,
RunErrorHandler,
RunErrorHandlerInput,
RunErrorHandlerResult,
RunErrorHandlers,
RunErrorKind,
} from './runner/errorHandlers';
export { getTracing } from './runner/tracing';
export { selectModel } from './runner/modelSettings';
export { getTurnInput } from './runner/items';
export type { ReasoningItemIdPolicy } from './runner/items';
// Maintenance: keep helper utilities (e.g., GuardrailTracker) in runner/* modules so run.ts stays orchestration-only.
// --------------------------------------------------------------
// Configuration
// --------------------------------------------------------------
export type ToolErrorFormatterArgs<
TContext = unknown,
TKind extends 'approval_rejected' = 'approval_rejected',
> = {
/**
* The category of tool error being formatted.
*/
kind: TKind;
/**
* The tool runtime that produced the error.
*/
toolType: 'function' | 'computer' | 'shell' | 'apply_patch';
/**
* The name of the tool that produced the error.
*/
toolName: string;
/**
* The unique tool call identifier.
*/
callId: string;
/**
* The SDK's default message for this error kind.
*/
defaultMessage: string;
/**
* The active run context for the current execution.
*/
runContext: RunContext<TContext>;
};
export type ToolErrorFormatter<TContext = unknown> = (
args: ToolErrorFormatterArgs<TContext>,
) => Promise<string | undefined> | string | undefined;
/**
* Configures settings for the entire agent run.
*/
export type RunConfig = {
/**
* The model to use for the entire agent run. If set, will override the model set on every
* agent. The modelProvider passed in below must be able to resolve this model name.
*/
model?: string | Model;
/**
* The model provider to use when looking up string model names. Defaults to OpenAI.
*/
modelProvider: ModelProvider;
/**
* Configure global model settings. Any non-null values will override the agent-specific model
* settings.
*/
modelSettings?: ModelSettings;
/**
* A global input filter to apply to all handoffs. If `Handoff.inputFilter` is set, then that
* will take precedence. The input filter allows you to edit the inputs that are sent to the new
* agent. See the documentation in `Handoff.inputFilter` for more details.
*/
handoffInputFilter?: HandoffInputFilter;
/**
* A list of input guardrails to run on the initial run input.
*/
inputGuardrails?: InputGuardrail[];
/**
* A list of output guardrails to run on the final output of the run.
*/
outputGuardrails?: OutputGuardrail<AgentOutputType<unknown>>[];
/**
* Whether tracing is disabled for the agent run. If disabled, we will not trace the agent run.
*/
tracingDisabled: boolean;
/**
* Whether we include potentially sensitive data (for example: inputs/outputs of tool calls or
* LLM generations) in traces. If false, we'll still create spans for these events, but the
* sensitive data will not be included.
*/
traceIncludeSensitiveData: boolean;
/**
* The name of the run, used for tracing. Should be a logical name for the run, like
* "Code generation workflow" or "Customer support agent".
*/
workflowName?: string;
/**
* A custom trace ID to use for tracing. If not provided, we will generate a new trace ID.
*/
traceId?: string;
/**
* A grouping identifier to use for tracing, to link multiple traces from the same conversation
* or process. For example, you might use a chat thread ID.
*/
groupId?: string;
/**
* An optional dictionary of additional metadata to include with the trace.
*/
traceMetadata?: Record<string, string>;
/**
* Tracing configuration for this run. Use this to override the API key used when exporting traces.
*/
tracing?: TracingConfig;
/**
* Customizes how session history is combined with the current turn's input.
* When omitted, history items are appended before the new input.
*/
sessionInputCallback?: SessionInputCallback;
/**
* Invoked immediately before calling the model, allowing callers to edit the
* system instructions or input items that will be sent to the model.
*/
callModelInputFilter?: CallModelInputFilter;
/**
* Formats tool error messages that are returned to the model.
* Returning `undefined` falls back to the SDK default message.
*/
toolErrorFormatter?: ToolErrorFormatter;
/**
* Controls how run items are converted into model input for subsequent turns.
*/
reasoningItemIdPolicy?: ReasoningItemIdPolicy;
};
/**
* Common run options shared between streaming and non-streaming execution pathways.
*/
type SharedRunOptions<
TContext = undefined,
TAgent extends Agent<any, any> = Agent<any, any>,
> = {
context?: TContext | RunContext<TContext>;
maxTurns?: number;
signal?: AbortSignal;
previousResponseId?: string;
conversationId?: string;
session?: Session;
sessionInputCallback?: SessionInputCallback;
callModelInputFilter?: CallModelInputFilter;
toolErrorFormatter?: ToolErrorFormatter;
reasoningItemIdPolicy?: ReasoningItemIdPolicy;
tracing?: TracingConfig;
/**
* Error handlers keyed by error kind. Currently only maxTurns errors are supported.
*/
errorHandlers?: RunErrorHandlers<TContext, TAgent>;
};
/**
* Options for runs that stream incremental events as the model responds.
*/
export type StreamRunOptions<
TContext = undefined,
TAgent extends Agent<any, any> = Agent<any, any>,
> = SharedRunOptions<TContext, TAgent> & {
/**
* Whether to stream the run. If true, the run will emit events as the model responds.
*/
stream: true;
};
/**
* Options for runs that collect the full model response before returning.
*/
export type NonStreamRunOptions<
TContext = undefined,
TAgent extends Agent<any, any> = Agent<any, any>,
> = SharedRunOptions<TContext, TAgent> & {
/**
* Run to completion without streaming incremental events; leave undefined or set to `false`.
*/
stream?: false;
};
/**
* Options polymorphic over streaming or non-streaming execution modes.
*/
export type IndividualRunOptions<
TContext = undefined,
TAgent extends Agent<any, any> = Agent<any, any>,
> = StreamRunOptions<TContext, TAgent> | NonStreamRunOptions<TContext, TAgent>;
// --------------------------------------------------------------
// Runner
// --------------------------------------------------------------
/**
* Executes an agent workflow with the shared default `Runner` instance.
*
* @param agent - The entry agent to invoke.
* @param input - A string utterance, structured input items, or a resumed `RunState`.
* @param options - Controls streaming mode, context, session handling, and turn limits.
* @returns A `RunResult` when `stream` is false, otherwise a `StreamedRunResult`.
*/
export async function run<TAgent extends Agent<any, any>, TContext = undefined>(
agent: TAgent,
input: string | AgentInputItem[] | RunState<TContext, TAgent>,
options?: NonStreamRunOptions<TContext, TAgent>,
): Promise<RunResult<TContext, TAgent>>;
export async function run<TAgent extends Agent<any, any>, TContext = undefined>(
agent: TAgent,
input: string | AgentInputItem[] | RunState<TContext, TAgent>,
options?: StreamRunOptions<TContext, TAgent>,
): Promise<StreamedRunResult<TContext, TAgent>>;
export async function run<TAgent extends Agent<any, any>, TContext = undefined>(
agent: TAgent,
input: string | AgentInputItem[] | RunState<TContext, TAgent>,
options?:
| StreamRunOptions<TContext, TAgent>
| NonStreamRunOptions<TContext, TAgent>,
): Promise<RunResult<TContext, TAgent> | StreamedRunResult<TContext, TAgent>> {
const runner = getDefaultRunner();
if (options?.stream) {
return await runner.run(agent, input, options);
} else {
return await runner.run(agent, input, options);
}
}
/**
* Orchestrates agent execution, including guardrails, tool calls, session persistence, and
* tracing. Reuse a `Runner` instance when you want consistent configuration across multiple runs.
*/
export class Runner extends RunHooks<any, AgentOutputType<unknown>> {
public readonly config: RunConfig;
private readonly traceOverrides: {
traceId?: string;
workflowName?: string;
groupId?: string;
traceMetadata?: Record<string, string>;
tracingApiKey?: string;
};
/**
* Creates a runner with optional defaults that apply to every subsequent run invocation.
*
* @param config - Overrides for models, guardrails, tracing, or session behavior.
*/
constructor(config: Partial<RunConfig> = {}) {
super();
this.config = {
modelProvider: config.modelProvider ?? getDefaultModelProvider(),
model: config.model,
modelSettings: config.modelSettings,
handoffInputFilter: config.handoffInputFilter,
inputGuardrails: config.inputGuardrails,
outputGuardrails: config.outputGuardrails,
tracingDisabled: config.tracingDisabled ?? false,
traceIncludeSensitiveData: config.traceIncludeSensitiveData ?? true,
workflowName: config.workflowName ?? 'Agent workflow',
traceId: config.traceId,
groupId: config.groupId,
traceMetadata: config.traceMetadata,
tracing: config.tracing,
sessionInputCallback: config.sessionInputCallback,
callModelInputFilter: config.callModelInputFilter,
toolErrorFormatter: config.toolErrorFormatter,
reasoningItemIdPolicy: config.reasoningItemIdPolicy,
};
this.traceOverrides = {
...(config.traceId !== undefined ? { traceId: config.traceId } : {}),
...(config.workflowName !== undefined
? { workflowName: config.workflowName }
: {}),
...(config.groupId !== undefined ? { groupId: config.groupId } : {}),
...(config.traceMetadata !== undefined
? { traceMetadata: config.traceMetadata }
: {}),
...(config.tracing?.apiKey !== undefined
? { tracingApiKey: config.tracing.apiKey }
: {}),
};
this.inputGuardrailDefs = (config.inputGuardrails ?? []).map(
defineInputGuardrail,
);
this.outputGuardrailDefs = (config.outputGuardrails ?? []).map(
defineOutputGuardrail,
);
}
/**
* Run a workflow starting at the given agent. The agent will run in a loop until a final
* output is generated. The loop runs like so:
* 1. The agent is invoked with the given input.
* 2. If there is a final output (i.e. the agent produces something of type
* `agent.outputType`, the loop terminates.
* 3. If there's a handoff, we run the loop again, with the new agent.
* 4. Else, we run tool calls (if any), and re-run the loop.
*
* In two cases, the agent may raise an exception:
* 1. If the maxTurns is exceeded, a MaxTurnsExceeded exception is raised unless handled.
* 2. If a guardrail tripwire is triggered, a GuardrailTripwireTriggered exception is raised.
*
* Note that only the first agent's input guardrails are run.
*
* @param agent - The starting agent to run.
* @param input - The initial input to the agent. You can pass a string or an array of
* `AgentInputItem`.
* @param options - Options for the run, including streaming behavior, execution context, and the
* maximum number of turns.
* @returns The result of the run.
*/
run<TAgent extends Agent<any, any>, TContext = undefined>(
agent: TAgent,
input: string | AgentInputItem[] | RunState<TContext, TAgent>,
options?: NonStreamRunOptions<TContext, TAgent>,
): Promise<RunResult<TContext, TAgent>>;
run<TAgent extends Agent<any, any>, TContext = undefined>(
agent: TAgent,
input: string | AgentInputItem[] | RunState<TContext, TAgent>,
options?: StreamRunOptions<TContext, TAgent>,
): Promise<StreamedRunResult<TContext, TAgent>>;
async run<TAgent extends Agent<any, any>, TContext = undefined>(
agent: TAgent,
input: string | AgentInputItem[] | RunState<TContext, TAgent>,
options: IndividualRunOptions<TContext, TAgent> = {
stream: false,
context: undefined,
} as IndividualRunOptions<TContext, TAgent>,
): Promise<
RunResult<TContext, TAgent> | StreamedRunResult<TContext, TAgent>
> {
const resolvedOptions = options ?? { stream: false, context: undefined };
// Per-run options take precedence over runner defaults for session memory behavior.
const sessionInputCallback =
resolvedOptions.sessionInputCallback ?? this.config.sessionInputCallback;
// Likewise allow callers to override callModelInputFilter on individual runs.
const callModelInputFilter =
resolvedOptions.callModelInputFilter ?? this.config.callModelInputFilter;
// Per-run callback can override runner-level tool error formatting defaults.
const toolErrorFormatter =
resolvedOptions.toolErrorFormatter ?? this.config.toolErrorFormatter;
const reasoningItemIdPolicy = resolvedOptions.reasoningItemIdPolicy;
const hasCallModelInputFilter = Boolean(callModelInputFilter);
const tracingConfig = resolvedOptions.tracing ?? this.config.tracing;
const traceOverrides = {
...this.traceOverrides,
...(resolvedOptions.tracing?.apiKey !== undefined
? { tracingApiKey: resolvedOptions.tracing.apiKey }
: {}),
};
const effectiveOptions = {
...resolvedOptions,
sessionInputCallback,
callModelInputFilter,
toolErrorFormatter,
reasoningItemIdPolicy,
};
const resumingFromState = input instanceof RunState;
const preserveTurnPersistenceOnResume =
resumingFromState &&
(input as RunState<TContext, TAgent>)._currentTurnInProgress === true;
const resumedConversationId = resumingFromState
? (input as RunState<TContext, TAgent>)._conversationId
: undefined;
const resumedPreviousResponseId = resumingFromState
? (input as RunState<TContext, TAgent>)._previousResponseId
: undefined;
const serverManagesConversation =
Boolean(effectiveOptions.conversationId ?? resumedConversationId) ||
Boolean(effectiveOptions.previousResponseId ?? resumedPreviousResponseId);
// When the server tracks conversation history we defer to it for previous turns so local session
// persistence can focus solely on the new delta being generated in this process.
const session = effectiveOptions.session;
const sessionPersistence = createSessionPersistenceTracker({
session,
hasCallModelInputFilter,
persistInput: saveStreamInputToSession,
resumingFromState,
});
let preparedInput: typeof input = input;
if (!(preparedInput instanceof RunState)) {
const prepared = await prepareInputItemsWithSession(
preparedInput,
session,
sessionInputCallback,
{
// When the server tracks conversation state we only send the new turn inputs;
// previous messages are recovered via conversationId/previousResponseId.
includeHistoryInPreparedInput: !serverManagesConversation,
preserveDroppedNewItems: serverManagesConversation,
},
);
if (serverManagesConversation && session) {
// When the server manages memory we only persist the new turn inputs locally so the
// conversation service stays the single source of truth for prior exchanges.
const sessionItems = prepared.sessionItems;
if (sessionItems && sessionItems.length > 0) {
preparedInput = sessionItems;
} else {
preparedInput = prepared.preparedInput;
}
} else {
preparedInput = prepared.preparedInput;
}
sessionPersistence?.setPreparedItems(prepared.sessionItems);
}
// Streaming runs persist the input asynchronously, so track a one-shot helper
// that can be awaited from multiple branches without double-writing.
const ensureStreamInputPersisted =
sessionPersistence?.buildPersistInputOnce(serverManagesConversation);
const executeRun = async () => {
if (effectiveOptions.stream) {
const streamResult = await this.#runIndividualStream(
agent,
preparedInput,
effectiveOptions,
ensureStreamInputPersisted,
sessionPersistence?.recordTurnItems,
preserveTurnPersistenceOnResume,
);
return streamResult;
}
const runResult = await this.#runIndividualNonStream(
agent,
preparedInput,
effectiveOptions,
sessionPersistence?.recordTurnItems,
preserveTurnPersistenceOnResume,
);
// See note above: allow sessions to run for callbacks/state but skip writes when the server
// is the source of truth for transcript history.
if (sessionPersistence && !serverManagesConversation) {
await saveToSession(
session,
sessionPersistence.getItemsForPersistence(),
runResult,
);
}
return runResult;
};
if (preparedInput instanceof RunState && preparedInput._trace) {
const applied = applyTraceOverrides(
preparedInput._trace,
preparedInput._currentAgentSpan,
traceOverrides,
);
preparedInput._trace = applied.trace;
preparedInput._currentAgentSpan = applied.currentSpan;
return withTrace(preparedInput._trace, async () => {
if (preparedInput._currentAgentSpan) {
setCurrentSpan(preparedInput._currentAgentSpan);
}
return executeRun();
});
}
return getOrCreateTrace(async () => executeRun(), {
traceId: this.config.traceId,
name: this.config.workflowName,
groupId: this.config.groupId,
metadata: this.config.traceMetadata,
// Per-run tracing config overrides exporter defaults such as environment API key.
tracingApiKey: tracingConfig?.apiKey,
});
}
// --------------------------------------------------------------
// Internals
// --------------------------------------------------------------
private readonly inputGuardrailDefs: InputGuardrailDefinition[];
private readonly outputGuardrailDefs: OutputGuardrailDefinition<
OutputGuardrailMetadata,
AgentOutputType<unknown>
>[];
/**
* @internal
* Resolves the effective model once so both run loops obey the same precedence rules.
*/
async #resolveModelForAgent<TContext>(
agent: Agent<TContext, AgentOutputType>,
): Promise<{
model: Model;
explictlyModelSet: boolean;
resolvedModelName?: string;
}> {
const explictlyModelSet =
(agent.model !== undefined &&
agent.model !== Agent.DEFAULT_MODEL_PLACEHOLDER) ||
(this.config.model !== undefined &&
this.config.model !== Agent.DEFAULT_MODEL_PLACEHOLDER);
const selectedModel = selectModel(agent.model, this.config.model);
const resolvedModelName =
typeof selectedModel === 'string' ? selectedModel : undefined;
const resolvedModel =
typeof selectedModel === 'string'
? await this.config.modelProvider.getModel(selectedModel)
: selectedModel;
return { model: resolvedModel, explictlyModelSet, resolvedModelName };
}
/**
* @internal
*/
async #runIndividualNonStream<
TContext,
TAgent extends Agent<TContext, AgentOutputType>,
_THandoffs extends (Agent<any, any> | Handoff<any>)[] = any[],
>(
startingAgent: TAgent,
input: string | AgentInputItem[] | RunState<TContext, TAgent>,
options: NonStreamRunOptions<TContext, TAgent>,
// sessionInputUpdate lets the caller adjust queued session items after filters run so we
// persist exactly what we send to the model (e.g., after redactions or truncation).
sessionInputUpdate?: (
sourceItems: (AgentInputItem | undefined)[],
filteredItems?: AgentInputItem[],
) => void,
preserveTurnPersistenceOnResume?: boolean,
): Promise<RunResult<TContext, TAgent>> {
return withNewSpanContext(async () => {
// if we have a saved state we use that one, otherwise we create a new one
const isResumedState = input instanceof RunState;
const state = isResumedState
? input
: new RunState(
options.context instanceof RunContext
? options.context
: new RunContext(options.context),
input,
startingAgent,
options.maxTurns ?? DEFAULT_MAX_TURNS,
);
if (isResumedState) {
state._agentToolInvocation = undefined;
}
const resolvedReasoningItemIdPolicy =
options.reasoningItemIdPolicy ??
(isResumedState ? state._reasoningItemIdPolicy : undefined) ??
this.config.reasoningItemIdPolicy;
state.setReasoningItemIdPolicy(resolvedReasoningItemIdPolicy);
const resolvedConversationId =
options.conversationId ??
(isResumedState ? state._conversationId : undefined);
const resolvedPreviousResponseId =
options.previousResponseId ??
(isResumedState ? state._previousResponseId : undefined);
if (!isResumedState) {
state.setConversationContext(
resolvedConversationId,
resolvedPreviousResponseId,
);
}
const serverConversationTracker =
resolvedConversationId || resolvedPreviousResponseId
? new ServerConversationTracker({
conversationId: resolvedConversationId,
previousResponseId: resolvedPreviousResponseId,
reasoningItemIdPolicy: resolvedReasoningItemIdPolicy,
})
: undefined;
if (serverConversationTracker && isResumedState) {
serverConversationTracker.primeFromState({
originalInput: state._originalInput,
generatedItems: state._generatedItems,
modelResponses: state._modelResponses,
});
state.setConversationContext(
serverConversationTracker.conversationId,
serverConversationTracker.previousResponseId,
);
}
const toolErrorFormatter =
options.toolErrorFormatter ?? this.config.toolErrorFormatter;
// Tracks when we resume an approval interruption so the next run-again step stays in the same turn.
let continuingInterruptedTurn = false;
try {
while (true) {
// if we don't have a current step, we treat this as a new run
state._currentStep = state._currentStep ?? {
type: 'next_step_run_again',
};
if (state._currentStep.type === 'next_step_interruption') {
logger.debug('Continuing from interruption');
if (!state._lastTurnResponse || !state._lastProcessedResponse) {
throw new UserError(
'No model response found in previous state',
state,
);
}
const interruptedOutcome = await resumeInterruptedTurn({
state,
runner: this,
toolErrorFormatter,
});
// Don't reset counter here - resolveInterruptedTurn already adjusted it via rewind logic
// The counter will be reset when _currentTurn is incremented (starting a new turn)
const { shouldReturn, shouldContinue } = handleInterruptedOutcome({
state,
outcome: interruptedOutcome,
setContinuingInterruptedTurn: (value) => {
continuingInterruptedTurn = value;
},
});
if (shouldReturn) {
// we are still in an interruption, so we need to avoid an infinite loop
return new RunResult<TContext, TAgent>(state);
}
if (shouldContinue) {
continue;
}
}
if (state._currentStep.type === 'next_step_run_again') {
const wasContinuingInterruptedTurn = continuingInterruptedTurn;
continuingInterruptedTurn = false;
const guardrailTracker = createGuardrailTracker();
const previousTurn = state._currentTurn;
const previousPersistedCount = state._currentTurnPersistedItemCount;
const previousGeneratedCount = state._generatedItems.length;
const { artifacts, turnInput, parallelGuardrailPromise } =
await prepareTurn({
state,
input: state._originalInput,
generatedItems: state._generatedItems,
isResumedState,
preserveTurnPersistenceOnResume,
continuingInterruptedTurn: wasContinuingInterruptedTurn,
serverConversationTracker,
inputGuardrailDefs: this.inputGuardrailDefs,
guardrailHandlers: {
onParallelStart: guardrailTracker.markPending,
onParallelError: guardrailTracker.setError,
},
emitAgentStart: (context, agent, inputItems) => {
this.emit('agent_start', context, agent, inputItems);
},
});
if (
preserveTurnPersistenceOnResume &&
state._currentTurn > previousTurn &&
previousPersistedCount <= previousGeneratedCount
) {
// Preserve persisted offsets from a resumed run to avoid re-saving prior items.
state._currentTurnPersistedItemCount = previousPersistedCount;
}
guardrailTracker.setPromise(parallelGuardrailPromise);
const preparedCall = await this.#prepareModelCall(
state,
options,
artifacts,
turnInput,
serverConversationTracker,
sessionInputUpdate,
);
guardrailTracker.throwIfError();
state._lastTurnResponse = await getResponseWithRetry(
preparedCall.model,
{
systemInstructions: preparedCall.modelInput.instructions,
prompt: preparedCall.prompt,
// Explicit agent/run config models should take precedence over prompt defaults.
...(preparedCall.explictlyModelSet
? { overridePromptModel: true }
: {}),
input: preparedCall.modelInput.input,
previousResponseId: preparedCall.previousResponseId,
conversationId: preparedCall.conversationId,
modelSettings: preparedCall.modelSettings,
tools: preparedCall.serializedTools,
toolsExplicitlyProvided: preparedCall.toolsExplicitlyProvided,
outputType: convertAgentOutputTypeToSerializable(
state._currentAgent.outputType,
),
handoffs: preparedCall.serializedHandoffs,
tracing: getTracing(
this.config.tracingDisabled,
this.config.traceIncludeSensitiveData,
),
signal: options.signal,
},
);
if (serverConversationTracker) {
serverConversationTracker.markInputAsSent(
preparedCall.sourceItems,
{
filterApplied: preparedCall.filterApplied,
allTurnItems: preparedCall.turnInput,
},
);
}
state._modelResponses.push(state._lastTurnResponse);
state._context.usage.add(state._lastTurnResponse.usage);
state._noActiveAgentRun = false;
// After each turn record the items echoed by the server so future requests only
// include the incremental inputs that have not yet been acknowledged.
serverConversationTracker?.trackServerItems(
state._lastTurnResponse,
);
if (serverConversationTracker) {
state.setConversationContext(
serverConversationTracker.conversationId,
serverConversationTracker.previousResponseId,
);
}
const processedResponse = await processModelResponseAsync(
state._lastTurnResponse,
state._currentAgent,
preparedCall.tools,
preparedCall.handoffs,
state,
[...preparedCall.turnInput, ...state._generatedItems],
);
state._lastProcessedResponse = processedResponse;
await guardrailTracker.awaitCompletion();
const turnResult = await resolveTurnAfterModelResponse<TContext>(
state._currentAgent,
state._originalInput,
state._generatedItems,
state._lastTurnResponse,
state._lastProcessedResponse!,
this,
state,
toolErrorFormatter,
);
applyTurnResult({
state,
turnResult,
agent: state._currentAgent,
toolsUsed: state._lastProcessedResponse?.toolsUsed ?? [],
resetTurnPersistence: !isResumedState,
});
}
const currentStep = state._currentStep;
if (!currentStep) {
logger.debug('Running next loop');
continue;
}
switch (currentStep.type) {
case 'next_step_final_output':
await runOutputGuardrails(
state,
this.outputGuardrailDefs,
currentStep.output,
);
state._currentTurnInProgress = false;
this.emit(
'agent_end',
state._context,
state._currentAgent,
currentStep.output,
);
state._currentAgent.emit(
'agent_end',
state._context,
currentStep.output,
);
return new RunResult<TContext, TAgent>(state);
case 'next_step_handoff':
state.setCurrentAgent(currentStep.newAgent as TAgent);
if (state._currentAgentSpan) {
state._currentAgentSpan.end();
resetCurrentSpan();
state.setCurrentAgentSpan(undefined);
}
state._noActiveAgentRun = true;
state._currentTurnInProgress = false;
// We've processed the handoff, so we need to run the loop again.
state._currentStep = { type: 'next_step_run_again' };
break;
case 'next_step_interruption':
// Interrupted. Don't run any guardrails.
return new RunResult<TContext, TAgent>(state);
case 'next_step_run_again':
state._currentTurnInProgress = false;
logger.debug('Running next loop');
break;
default:
logger.debug('Running next loop');
}
}
} catch (err) {
state._currentTurnInProgress = false;
const handledResult = await tryHandleRunError({
error: err,
state,
errorHandlers: options.errorHandlers,
outputGuardrailDefs: this.outputGuardrailDefs,
emitAgentEnd: (context, agent, outputText) => {
this.emit('agent_end', context, agent, outputText);
agent.emit('agent_end', context, outputText);
},
});
if (handledResult) {
return handledResult;
}
if (state._currentAgentSpan) {
state._currentAgentSpan.setError({
message: 'Error in agent run',
data: { error: String(err) },
});
}
throw err;
} finally {
if (state._currentStep?.type !== 'next_step_interruption') {
try {
await disposeResolvedComputers({ runContext: state._context });
} catch (error) {
logger.warn(`Failed to dispose computers after run: ${error}`);
}
}
if (state._currentAgentSpan) {
if (state._currentStep?.type !== 'next_step_interruption') {
// don't end the span if the run was interrupted
state._currentAgentSpan.end();
}
resetCurrentSpan();
}
}
});
}
/**
* @internal
*/
async #runStreamLoop<
TContext,
TAgent extends Agent<TContext, AgentOutputType>,
>(
result: StreamedRunResult<TContext, TAgent>,
options: StreamRunOptions<TContext, TAgent>,
isResumedState: boolean,
ensureStreamInputPersisted?: () => Promise<void>,
sessionInputUpdate?: (
sourceItems: (AgentInputItem | undefined)[],
filteredItems?: AgentInputItem[],
) => void,
preserveTurnPersistenceOnResume?: boolean,
): Promise<void> {
const resolvedReasoningItemIdPolicy =
options.reasoningItemIdPolicy ??
(isResumedState ? result.state._reasoningItemIdPolicy : undefined) ??
this.config.reasoningItemIdPolicy;
result.state.setReasoningItemIdPolicy(resolvedReasoningItemIdPolicy);
const resolvedConversationId =
options.conversationId ?? result.state._conversationId;
const resolvedPreviousResponseId =
options.previousResponseId ?? result.state._previousResponseId;
const serverManagesConversation =
Boolean(resolvedConversationId) || Boolean(resolvedPreviousResponseId);
const serverConversationTracker = serverManagesConversation
? new ServerConversationTracker({
conversationId: resolvedConversationId,
previousResponseId: resolvedPreviousResponseId,
reasoningItemIdPolicy: resolvedReasoningItemIdPolicy,
})
: undefined;
if (serverConversationTracker) {
result.state.setConversationContext(
serverConversationTracker.conversationId,