sarvam-agents-client 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -0
- package/dist/apis/AgentConversationsApi.d.ts +44 -1
- package/dist/apis/AgentConversationsApi.js +104 -1
- package/dist/apis/AgentsApi.d.ts +77 -5
- package/dist/apis/AgentsApi.js +163 -5
- package/dist/apis/AppsApi.d.ts +43 -1
- package/dist/apis/AppsApi.js +108 -0
- package/dist/apis/ArtifactsApi.d.ts +31 -1
- package/dist/apis/ArtifactsApi.js +82 -0
- package/dist/apis/CustomAPIsApi.d.ts +124 -0
- package/dist/apis/CustomAPIsApi.js +305 -0
- package/dist/apis/ModelsApi.d.ts +26 -0
- package/dist/apis/ModelsApi.js +52 -0
- package/dist/apis/index.d.ts +2 -0
- package/dist/apis/index.js +2 -0
- package/dist/compose/agent.d.ts +40 -0
- package/dist/compose/agent.js +191 -0
- package/dist/compose/deploy.d.ts +30 -0
- package/dist/compose/deploy.js +146 -0
- package/dist/compose/errors.d.ts +48 -0
- package/dist/compose/errors.js +68 -0
- package/dist/compose/events.d.ts +63 -0
- package/dist/compose/events.js +100 -0
- package/dist/compose/fingerprint.d.ts +6 -0
- package/dist/compose/fingerprint.js +83 -0
- package/dist/compose/index.d.ts +13 -0
- package/dist/compose/index.js +33 -0
- package/dist/compose/run.d.ts +100 -0
- package/dist/compose/run.js +536 -0
- package/dist/compose/runState.d.ts +26 -0
- package/dist/compose/runState.js +79 -0
- package/dist/compose/settingsTransport.d.ts +24 -0
- package/dist/compose/settingsTransport.js +280 -0
- package/dist/compose/tools.d.ts +17 -0
- package/dist/compose/tools.js +29 -0
- package/dist/compose/transport.d.ts +34 -0
- package/dist/compose/transport.js +2 -0
- package/dist/esm/apis/AgentConversationsApi.d.ts +44 -1
- package/dist/esm/apis/AgentConversationsApi.js +104 -1
- package/dist/esm/apis/AgentsApi.d.ts +77 -5
- package/dist/esm/apis/AgentsApi.js +163 -5
- package/dist/esm/apis/AppsApi.d.ts +43 -1
- package/dist/esm/apis/AppsApi.js +109 -1
- package/dist/esm/apis/ArtifactsApi.d.ts +31 -1
- package/dist/esm/apis/ArtifactsApi.js +83 -1
- package/dist/esm/apis/CustomAPIsApi.d.ts +124 -0
- package/dist/esm/apis/CustomAPIsApi.js +301 -0
- package/dist/esm/apis/ModelsApi.d.ts +26 -0
- package/dist/esm/apis/ModelsApi.js +48 -0
- package/dist/esm/apis/index.d.ts +2 -0
- package/dist/esm/apis/index.js +2 -0
- package/dist/esm/compose/agent.d.ts +40 -0
- package/dist/esm/compose/agent.js +187 -0
- package/dist/esm/compose/deploy.d.ts +30 -0
- package/dist/esm/compose/deploy.js +137 -0
- package/dist/esm/compose/errors.d.ts +48 -0
- package/dist/esm/compose/errors.js +53 -0
- package/dist/esm/compose/events.d.ts +63 -0
- package/dist/esm/compose/events.js +97 -0
- package/dist/esm/compose/fingerprint.d.ts +6 -0
- package/dist/esm/compose/fingerprint.js +78 -0
- package/dist/esm/compose/index.d.ts +13 -0
- package/dist/esm/compose/index.js +8 -0
- package/dist/esm/compose/run.d.ts +100 -0
- package/dist/esm/compose/run.js +530 -0
- package/dist/esm/compose/runState.d.ts +26 -0
- package/dist/esm/compose/runState.js +75 -0
- package/dist/esm/compose/settingsTransport.d.ts +24 -0
- package/dist/esm/compose/settingsTransport.js +276 -0
- package/dist/esm/compose/tools.d.ts +17 -0
- package/dist/esm/compose/tools.js +19 -0
- package/dist/esm/compose/transport.d.ts +34 -0
- package/dist/esm/compose/transport.js +1 -0
- package/dist/esm/models/AgentChannelRef.d.ts +1 -0
- package/dist/esm/models/AgentChannelRef.js +2 -1
- package/dist/esm/models/AgentConversationDetail.d.ts +15 -2
- package/dist/esm/models/AgentConversationDetail.js +6 -4
- package/dist/esm/models/AgentConversationView.d.ts +11 -5
- package/dist/esm/models/AgentConversationView.js +4 -4
- package/dist/esm/models/AgentCreate.d.ts +8 -0
- package/dist/esm/models/AgentCreate.js +2 -0
- package/dist/esm/models/AgentCustomApiList.d.ts +33 -0
- package/dist/esm/models/AgentCustomApiList.js +44 -0
- package/dist/esm/models/AgentResource.d.ts +14 -0
- package/dist/esm/models/AgentResource.js +4 -0
- package/dist/esm/models/AgentSettingsResponse.d.ts +53 -0
- package/dist/esm/models/AgentSettingsResponse.js +52 -0
- package/dist/esm/models/AgentUpdate.d.ts +8 -0
- package/dist/esm/models/AgentUpdate.js +2 -0
- package/dist/esm/models/AppAccountView.d.ts +88 -0
- package/dist/esm/models/AppAccountView.js +79 -0
- package/dist/esm/models/AppAccountsView.d.ts +66 -0
- package/dist/esm/models/AppAccountsView.js +60 -0
- package/dist/esm/models/AppResource.d.ts +36 -0
- package/dist/esm/models/AppResource.js +12 -0
- package/dist/esm/models/AppResourceCheckView.d.ts +74 -0
- package/dist/esm/models/AppResourceCheckView.js +63 -0
- package/dist/esm/models/AppResourceView.d.ts +68 -0
- package/dist/esm/models/AppResourceView.js +67 -0
- package/dist/esm/models/AppResourcesView.d.ts +54 -0
- package/dist/esm/models/AppResourcesView.js +56 -0
- package/dist/esm/models/AppToolsResponse.d.ts +14 -0
- package/dist/esm/models/AppToolsResponse.js +4 -0
- package/dist/esm/models/AppView.d.ts +42 -0
- package/dist/esm/models/AppView.js +14 -0
- package/dist/esm/models/ArtifactVersionResponse.d.ts +94 -0
- package/dist/esm/models/ArtifactVersionResponse.js +80 -0
- package/dist/esm/models/AttachedAgent.d.ts +44 -0
- package/dist/esm/models/AttachedAgent.js +49 -0
- package/dist/esm/models/Auth.d.ts +30 -0
- package/dist/esm/models/Auth.js +52 -0
- package/dist/esm/models/BindCustomApiBody.d.ts +32 -0
- package/dist/esm/models/BindCustomApiBody.js +43 -0
- package/dist/esm/models/ConversationArtifact.d.ts +14 -0
- package/dist/esm/models/ConversationArtifact.js +9 -0
- package/dist/esm/models/CustomApi.d.ts +102 -0
- package/dist/esm/models/CustomApi.js +90 -0
- package/dist/esm/models/CustomApiBasicAuth.d.ts +51 -0
- package/dist/esm/models/CustomApiBasicAuth.js +57 -0
- package/dist/esm/models/CustomApiBearerAuth.d.ts +45 -0
- package/dist/esm/models/CustomApiBearerAuth.js +53 -0
- package/dist/esm/models/CustomApiCreate.d.ts +57 -0
- package/dist/esm/models/CustomApiCreate.js +56 -0
- package/dist/esm/models/CustomApiHeader.d.ts +44 -0
- package/dist/esm/models/CustomApiHeader.js +47 -0
- package/dist/esm/models/CustomApiHeadersAuth.d.ts +46 -0
- package/dist/esm/models/CustomApiHeadersAuth.js +54 -0
- package/dist/esm/models/CustomApiList.d.ts +64 -0
- package/dist/esm/models/CustomApiList.js +64 -0
- package/dist/esm/models/CustomApiName.d.ts +44 -0
- package/dist/esm/models/CustomApiName.js +49 -0
- package/dist/esm/models/CustomApiUpdate.d.ts +58 -0
- package/dist/esm/models/CustomApiUpdate.js +50 -0
- package/dist/esm/models/CustomApiUpdateAuth.d.ts +30 -0
- package/dist/esm/models/CustomApiUpdateAuth.js +52 -0
- package/dist/esm/models/ErrorDetailItem.d.ts +5 -0
- package/dist/esm/models/ListModels403Response.d.ts +23 -0
- package/dist/esm/models/ListModels403Response.js +45 -0
- package/dist/esm/models/ModelEndpointView.d.ts +38 -0
- package/dist/esm/models/ModelEndpointView.js +45 -0
- package/dist/esm/models/ModelView.d.ts +69 -0
- package/dist/esm/models/ModelView.js +56 -0
- package/dist/esm/models/ModelsResponse.d.ts +33 -0
- package/dist/esm/models/ModelsResponse.js +44 -0
- package/dist/esm/models/SettingsIssueView.d.ts +44 -0
- package/dist/esm/models/SettingsIssueView.js +51 -0
- package/dist/esm/models/VersionCommitBody.d.ts +44 -0
- package/dist/esm/models/VersionCommitBody.js +51 -0
- package/dist/esm/models/VersionUploadUrlBody.d.ts +32 -0
- package/dist/esm/models/VersionUploadUrlBody.js +43 -0
- package/dist/esm/models/index.d.ts +28 -0
- package/dist/esm/models/index.js +28 -0
- package/dist/models/AgentChannelRef.d.ts +1 -0
- package/dist/models/AgentChannelRef.js +2 -1
- package/dist/models/AgentConversationDetail.d.ts +15 -2
- package/dist/models/AgentConversationDetail.js +6 -4
- package/dist/models/AgentConversationView.d.ts +11 -5
- package/dist/models/AgentConversationView.js +4 -4
- package/dist/models/AgentCreate.d.ts +8 -0
- package/dist/models/AgentCreate.js +2 -0
- package/dist/models/AgentCustomApiList.d.ts +33 -0
- package/dist/models/AgentCustomApiList.js +51 -0
- package/dist/models/AgentResource.d.ts +14 -0
- package/dist/models/AgentResource.js +4 -0
- package/dist/models/AgentSettingsResponse.d.ts +53 -0
- package/dist/models/AgentSettingsResponse.js +59 -0
- package/dist/models/AgentUpdate.d.ts +8 -0
- package/dist/models/AgentUpdate.js +2 -0
- package/dist/models/AppAccountView.d.ts +88 -0
- package/dist/models/AppAccountView.js +87 -0
- package/dist/models/AppAccountsView.d.ts +66 -0
- package/dist/models/AppAccountsView.js +68 -0
- package/dist/models/AppResource.d.ts +36 -0
- package/dist/models/AppResource.js +12 -0
- package/dist/models/AppResourceCheckView.d.ts +74 -0
- package/dist/models/AppResourceCheckView.js +71 -0
- package/dist/models/AppResourceView.d.ts +68 -0
- package/dist/models/AppResourceView.js +74 -0
- package/dist/models/AppResourcesView.d.ts +54 -0
- package/dist/models/AppResourcesView.js +64 -0
- package/dist/models/AppToolsResponse.d.ts +14 -0
- package/dist/models/AppToolsResponse.js +4 -0
- package/dist/models/AppView.d.ts +42 -0
- package/dist/models/AppView.js +14 -0
- package/dist/models/ArtifactVersionResponse.d.ts +94 -0
- package/dist/models/ArtifactVersionResponse.js +88 -0
- package/dist/models/AttachedAgent.d.ts +44 -0
- package/dist/models/AttachedAgent.js +56 -0
- package/dist/models/Auth.d.ts +30 -0
- package/dist/models/Auth.js +58 -0
- package/dist/models/BindCustomApiBody.d.ts +32 -0
- package/dist/models/BindCustomApiBody.js +50 -0
- package/dist/models/ConversationArtifact.d.ts +14 -0
- package/dist/models/ConversationArtifact.js +10 -0
- package/dist/models/CustomApi.d.ts +102 -0
- package/dist/models/CustomApi.js +98 -0
- package/dist/models/CustomApiBasicAuth.d.ts +51 -0
- package/dist/models/CustomApiBasicAuth.js +65 -0
- package/dist/models/CustomApiBearerAuth.d.ts +45 -0
- package/dist/models/CustomApiBearerAuth.js +61 -0
- package/dist/models/CustomApiCreate.d.ts +57 -0
- package/dist/models/CustomApiCreate.js +63 -0
- package/dist/models/CustomApiHeader.d.ts +44 -0
- package/dist/models/CustomApiHeader.js +54 -0
- package/dist/models/CustomApiHeadersAuth.d.ts +46 -0
- package/dist/models/CustomApiHeadersAuth.js +62 -0
- package/dist/models/CustomApiList.d.ts +64 -0
- package/dist/models/CustomApiList.js +71 -0
- package/dist/models/CustomApiName.d.ts +44 -0
- package/dist/models/CustomApiName.js +56 -0
- package/dist/models/CustomApiUpdate.d.ts +58 -0
- package/dist/models/CustomApiUpdate.js +57 -0
- package/dist/models/CustomApiUpdateAuth.d.ts +30 -0
- package/dist/models/CustomApiUpdateAuth.js +58 -0
- package/dist/models/ErrorDetailItem.d.ts +5 -0
- package/dist/models/ListModels403Response.d.ts +23 -0
- package/dist/models/ListModels403Response.js +51 -0
- package/dist/models/ModelEndpointView.d.ts +38 -0
- package/dist/models/ModelEndpointView.js +52 -0
- package/dist/models/ModelView.d.ts +69 -0
- package/dist/models/ModelView.js +63 -0
- package/dist/models/ModelsResponse.d.ts +33 -0
- package/dist/models/ModelsResponse.js +51 -0
- package/dist/models/SettingsIssueView.d.ts +44 -0
- package/dist/models/SettingsIssueView.js +58 -0
- package/dist/models/VersionCommitBody.d.ts +44 -0
- package/dist/models/VersionCommitBody.js +58 -0
- package/dist/models/VersionUploadUrlBody.d.ts +32 -0
- package/dist/models/VersionUploadUrlBody.js +50 -0
- package/dist/models/index.d.ts +28 -0
- package/dist/models/index.js +28 -0
- package/package.json +15 -2
- package/src/apis/AgentConversationsApi.ts +172 -3
- package/src/apis/AgentsApi.ts +242 -7
- package/src/apis/AppsApi.ts +174 -3
- package/src/apis/ArtifactsApi.ts +144 -0
- package/src/apis/ClarifyApi.ts +3 -3
- package/src/apis/CollectionsApi.ts +3 -3
- package/src/apis/ConversationsApi.ts +3 -3
- package/src/apis/CronsApi.ts +3 -3
- package/src/apis/CustomAPIsApi.ts +471 -0
- package/src/apis/MessagesApi.ts +3 -3
- package/src/apis/ModelsApi.ts +70 -0
- package/src/apis/QueueApi.ts +3 -3
- package/src/apis/ResponsesApi.ts +3 -3
- package/src/apis/SkillsApi.ts +3 -3
- package/src/apis/index.ts +2 -0
- package/src/compose/agent.ts +223 -0
- package/src/compose/deploy.ts +168 -0
- package/src/compose/errors.ts +66 -0
- package/src/compose/events.ts +122 -0
- package/src/compose/fingerprint.ts +74 -0
- package/src/compose/index.ts +13 -0
- package/src/compose/run.ts +601 -0
- package/src/compose/runState.ts +95 -0
- package/src/compose/settingsTransport.ts +299 -0
- package/src/compose/tools.ts +27 -0
- package/src/compose/transport.ts +48 -0
- package/src/models/AgentChannelRef.ts +2 -1
- package/src/models/AgentConversationDetail.ts +21 -5
- package/src/models/AgentConversationView.ts +15 -8
- package/src/models/AgentCreate.ts +8 -0
- package/src/models/AgentCustomApiList.ts +74 -0
- package/src/models/AgentResource.ts +16 -0
- package/src/models/AgentSettingsResponse.ts +99 -0
- package/src/models/AgentUpdate.ts +8 -0
- package/src/models/AppAccountView.ts +143 -0
- package/src/models/AppAccountsView.ts +118 -0
- package/src/models/AppResource.ts +48 -0
- package/src/models/AppResourceCheckView.ts +117 -0
- package/src/models/AppResourceView.ts +120 -0
- package/src/models/AppResourcesView.ts +102 -0
- package/src/models/AppToolsResponse.ts +16 -0
- package/src/models/AppView.ts +56 -0
- package/src/models/ArtifactVersionResponse.ts +155 -0
- package/src/models/AttachedAgent.ts +83 -0
- package/src/models/Auth.ts +84 -0
- package/src/models/BindCustomApiBody.ts +66 -0
- package/src/models/ConversationArtifact.ts +19 -0
- package/src/models/CustomApi.ts +175 -0
- package/src/models/CustomApiBasicAuth.ts +94 -0
- package/src/models/CustomApiBearerAuth.ts +85 -0
- package/src/models/CustomApiCreate.ts +108 -0
- package/src/models/CustomApiHeader.ts +82 -0
- package/src/models/CustomApiHeadersAuth.ts +93 -0
- package/src/models/CustomApiList.ts +120 -0
- package/src/models/CustomApiName.ts +83 -0
- package/src/models/CustomApiUpdate.ts +106 -0
- package/src/models/CustomApiUpdateAuth.ts +84 -0
- package/src/models/ErrorDetailItem.ts +5 -0
- package/src/models/ListModels403Response.ts +73 -0
- package/src/models/ModelEndpointView.ts +74 -0
- package/src/models/ModelView.ts +122 -0
- package/src/models/ModelsResponse.ts +74 -0
- package/src/models/SettingsIssueView.ts +84 -0
- package/src/models/VersionCommitBody.ts +84 -0
- package/src/models/VersionUploadUrlBody.ts +66 -0
- package/src/models/index.ts +28 -0
|
@@ -0,0 +1,601 @@
|
|
|
1
|
+
/** run(): deploy the agent, drive one turn through a Transport, handle clarify questions, dropped streams and cancel. */
|
|
2
|
+
import type { Configuration } from "../runtime.js";
|
|
3
|
+
import { FetchError } from "../runtime.js";
|
|
4
|
+
import type { Agent } from "./agent.js";
|
|
5
|
+
import { agentIdFor, getDefaultClient, resolveTransport } from "./deploy.js";
|
|
6
|
+
import { NotSupportedError, RunError, UserError } from "./errors.js";
|
|
7
|
+
import type { ClarifyQuestion, Event } from "./events.js";
|
|
8
|
+
import { RunState } from "./runState.js";
|
|
9
|
+
import type { Interruption } from "./runState.js";
|
|
10
|
+
import type { Transport, TurnStream } from "./transport.js";
|
|
11
|
+
|
|
12
|
+
const MAX_RECONNECTS = 3;
|
|
13
|
+
/** The abort reason ResponseStream (src/streaming.ts) uses when a stream goes quiet. */
|
|
14
|
+
const IDLE_TIMEOUT_MESSAGE = "stream idle timeout";
|
|
15
|
+
|
|
16
|
+
export type ClarifyHandler = (
|
|
17
|
+
questions: ClarifyQuestion[],
|
|
18
|
+
) => Record<string, unknown> | Promise<Record<string, unknown>>;
|
|
19
|
+
|
|
20
|
+
export interface RunOptions {
|
|
21
|
+
client?: Configuration;
|
|
22
|
+
transport?: Transport;
|
|
23
|
+
/** Continue this conversation (a previous `result.conversationId`). */
|
|
24
|
+
conversationId?: string;
|
|
25
|
+
/** Aborting stops reading, tells the server to stop the turn, and resolves with `finalOutput` undefined. */
|
|
26
|
+
signal?: AbortSignal;
|
|
27
|
+
/** Answers clarify questions; without it a question ends the run with an interruption. */
|
|
28
|
+
onClarify?: ClarifyHandler;
|
|
29
|
+
/** Not supported: the server caps turns per agent; set `new Agent({ limits: { maxTurns } })`. */
|
|
30
|
+
maxTurns?: never;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type RunStreamEvent =
|
|
34
|
+
| { type: "raw_model_stream_event"; data: { type: "output_text_delta" | "reasoning_delta"; delta: string } }
|
|
35
|
+
| { type: "run_item_stream_event"; name: "tool_called" | "tool_output" | "message_output_created"; item: unknown };
|
|
36
|
+
|
|
37
|
+
type ClarifyEvent = Extract<Event, { kind: "clarify_requested" }>;
|
|
38
|
+
type Emit = (event: RunStreamEvent) => void;
|
|
39
|
+
|
|
40
|
+
interface Outcome {
|
|
41
|
+
finalOutput: string | undefined;
|
|
42
|
+
outputText: string;
|
|
43
|
+
newItems: Event[];
|
|
44
|
+
interruptions: Interruption[];
|
|
45
|
+
conversationId: string | undefined;
|
|
46
|
+
cancelled: boolean;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function stateOf(conversationId: string | undefined, interruptions: Interruption[]): RunState {
|
|
50
|
+
if (conversationId === undefined) throw new UserError("this run has no conversation to resume");
|
|
51
|
+
return new RunState(conversationId, interruptions.slice(), {});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export class RunResult {
|
|
55
|
+
readonly finalOutput: string | undefined;
|
|
56
|
+
readonly outputText: string;
|
|
57
|
+
readonly newItems: Event[];
|
|
58
|
+
readonly interruptions: Interruption[];
|
|
59
|
+
readonly conversationId: string | undefined;
|
|
60
|
+
|
|
61
|
+
/** @internal */
|
|
62
|
+
constructor(outcome: Outcome) {
|
|
63
|
+
this.finalOutput = outcome.finalOutput;
|
|
64
|
+
this.outputText = outcome.outputText;
|
|
65
|
+
this.newItems = outcome.newItems;
|
|
66
|
+
this.interruptions = outcome.interruptions;
|
|
67
|
+
this.conversationId = outcome.conversationId;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** A RunState to answer the interruptions and continue; throws UserError when the run has no conversation. */
|
|
71
|
+
get state(): RunState {
|
|
72
|
+
return stateOf(this.conversationId, this.interruptions);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// -- the run loop ------------------------------------------------------------------------------------------------
|
|
77
|
+
|
|
78
|
+
/** Thrown inside the loop when the caller's signal aborted; turned into a cancelled result. */
|
|
79
|
+
class Cancelled extends Error {}
|
|
80
|
+
|
|
81
|
+
/** Errors from a stream whose connection dropped (Python's _DROP_ERRORS); anything else propagates unchanged. */
|
|
82
|
+
function isDrop(err: unknown): boolean {
|
|
83
|
+
// Every TypeError counts as a drop: undici reports a dropped response body as `TypeError: terminated` (and a failed
|
|
84
|
+
// connect as `TypeError: fetch failed`), with no stable code to match on. The cost: an SDK bug that throws a
|
|
85
|
+
// TypeError surfaces as a stream_lost error after 3 retries instead of propagating immediately.
|
|
86
|
+
if (err instanceof FetchError || err instanceof TypeError) return true;
|
|
87
|
+
if (!(err instanceof Error)) return false;
|
|
88
|
+
return err.name === "AbortError" || err.name === "TimeoutError" || err.message === IDLE_TIMEOUT_MESSAGE;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Settle with `p`, or reject with Cancelled as soon as `signal` aborts. */
|
|
92
|
+
function raceAbort<T>(p: Promise<T>, signal: AbortSignal): Promise<T> {
|
|
93
|
+
return new Promise<T>((resolve, reject) => {
|
|
94
|
+
if (signal.aborted) {
|
|
95
|
+
p.catch(() => undefined);
|
|
96
|
+
reject(new Cancelled());
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
const onAbort = () => reject(new Cancelled());
|
|
100
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
101
|
+
p.then(
|
|
102
|
+
(v) => {
|
|
103
|
+
signal.removeEventListener("abort", onAbort);
|
|
104
|
+
resolve(v);
|
|
105
|
+
},
|
|
106
|
+
(e) => {
|
|
107
|
+
signal.removeEventListener("abort", onAbort);
|
|
108
|
+
reject(e);
|
|
109
|
+
},
|
|
110
|
+
);
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Sends the stop request once: after the abort, once a conversation exists, never after the run completed. */
|
|
115
|
+
class Stopper {
|
|
116
|
+
private conversationId: string | null = null;
|
|
117
|
+
private sent = false;
|
|
118
|
+
complete = false;
|
|
119
|
+
|
|
120
|
+
constructor(
|
|
121
|
+
private readonly transport: Transport,
|
|
122
|
+
private readonly signal: AbortSignal,
|
|
123
|
+
) {}
|
|
124
|
+
|
|
125
|
+
onConversation(conversationId: string): void {
|
|
126
|
+
this.conversationId = conversationId;
|
|
127
|
+
if (this.signal.aborted) this.send();
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
send(): void {
|
|
131
|
+
if (this.sent || this.complete || this.conversationId === null) return;
|
|
132
|
+
this.sent = true;
|
|
133
|
+
const conversationId = this.conversationId;
|
|
134
|
+
// No signal: the caller's is already aborted. Nobody awaits this; log a failure instead of losing it.
|
|
135
|
+
let request: Promise<void>;
|
|
136
|
+
try {
|
|
137
|
+
request = this.transport.stop(conversationId);
|
|
138
|
+
} catch (err) {
|
|
139
|
+
request = Promise.reject(err);
|
|
140
|
+
}
|
|
141
|
+
request.catch((err) => console.warn(`stopping conversation ${conversationId} failed: ${err}`));
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
class Loop {
|
|
146
|
+
conversationId: string | null = null;
|
|
147
|
+
readonly items: Event[] = [];
|
|
148
|
+
// Text of the current segment, per text block. Kept per block so a resumed stream, which replays from the start
|
|
149
|
+
// of the block it dropped in, doesn't repeat text.
|
|
150
|
+
private blocks: [string | null, string[]][] = [];
|
|
151
|
+
private openBlock: string | null = null;
|
|
152
|
+
|
|
153
|
+
constructor(
|
|
154
|
+
private readonly transport: Transport,
|
|
155
|
+
private readonly onClarify: ClarifyHandler | undefined,
|
|
156
|
+
private readonly emit: Emit,
|
|
157
|
+
private readonly signal: AbortSignal,
|
|
158
|
+
private readonly onConversation: (conversationId: string) => void,
|
|
159
|
+
) {}
|
|
160
|
+
|
|
161
|
+
get text(): string {
|
|
162
|
+
return this.blocks.map(([, parts]) => parts.join("")).join("");
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
private resetText(): void {
|
|
166
|
+
this.blocks = [];
|
|
167
|
+
this.openBlock = null;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
private block(blockId: string | null): string[] {
|
|
171
|
+
if (blockId === null && this.openBlock !== null) blockId = this.openBlock;
|
|
172
|
+
for (const [bid, parts] of this.blocks) if (bid !== null && bid === blockId) return parts;
|
|
173
|
+
const last = this.blocks[this.blocks.length - 1];
|
|
174
|
+
if (blockId === null && last && last[0] === null) return last[1];
|
|
175
|
+
const parts: string[] = [];
|
|
176
|
+
this.blocks.push([blockId, parts]);
|
|
177
|
+
return parts;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
private onText(event: Event): void {
|
|
181
|
+
if (event.kind === "text_start") {
|
|
182
|
+
this.block(event.id).length = 0; // a replayed block starts over
|
|
183
|
+
this.openBlock = event.id;
|
|
184
|
+
} else if (event.kind === "text_end") {
|
|
185
|
+
if (this.openBlock === event.id) this.openBlock = null;
|
|
186
|
+
} else if (event.kind === "text_delta") {
|
|
187
|
+
this.block(event.id ?? null).push(event.delta);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Prepare for a resumed stream: it restarts at a block boundary, or from the start without a cursor. */
|
|
192
|
+
private rewind(lastEventId: string | null, itemsAtStart: number): void {
|
|
193
|
+
if (lastEventId === null) {
|
|
194
|
+
this.resetText();
|
|
195
|
+
this.items.length = itemsAtStart;
|
|
196
|
+
} else if (this.openBlock !== null) {
|
|
197
|
+
const open = this.openBlock;
|
|
198
|
+
this.blocks = this.blocks.filter(([bid]) => bid !== open);
|
|
199
|
+
this.openBlock = null;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
private note(stream: TurnStream): void {
|
|
204
|
+
const conversationId = stream.conversationId;
|
|
205
|
+
if (conversationId && conversationId !== this.conversationId) {
|
|
206
|
+
this.conversationId = conversationId;
|
|
207
|
+
this.onConversation(conversationId);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Open a stream through the transport; an abort before, during or after the request cancels the run. */
|
|
212
|
+
private async open(call: () => Promise<TurnStream>): Promise<TurnStream> {
|
|
213
|
+
if (this.signal.aborted) throw new Cancelled();
|
|
214
|
+
let stream: TurnStream;
|
|
215
|
+
try {
|
|
216
|
+
stream = await call();
|
|
217
|
+
} catch (err) {
|
|
218
|
+
if (this.signal.aborted) throw new Cancelled();
|
|
219
|
+
throw err;
|
|
220
|
+
}
|
|
221
|
+
if (this.signal.aborted) {
|
|
222
|
+
this.note(stream); // the turn exists on the server: let the stop reach it
|
|
223
|
+
stream.close();
|
|
224
|
+
throw new Cancelled();
|
|
225
|
+
}
|
|
226
|
+
return stream;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
start(agentId: string, conversationId: string | null, input: string): Promise<TurnStream> {
|
|
230
|
+
return this.open(() => this.transport.startTurn(agentId, conversationId, input, this.signal));
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Read one turn segment to turn_finished, resuming dropped streams; return an unanswered question. */
|
|
234
|
+
private async consume(stream: TurnStream): Promise<ClarifyEvent | null> {
|
|
235
|
+
let clarify: ClarifyEvent | null = null;
|
|
236
|
+
let reconnects = 0;
|
|
237
|
+
const itemsAtStart = this.items.length;
|
|
238
|
+
for (;;) {
|
|
239
|
+
let finished = false;
|
|
240
|
+
const current = stream;
|
|
241
|
+
const onAbort = () => current.close();
|
|
242
|
+
this.signal.addEventListener("abort", onAbort, { once: true });
|
|
243
|
+
try {
|
|
244
|
+
this.note(current);
|
|
245
|
+
try {
|
|
246
|
+
for await (const event of current) {
|
|
247
|
+
// A buffered body can still yield after the abort; none of it counts as progress.
|
|
248
|
+
if (this.signal.aborted) throw new Cancelled();
|
|
249
|
+
if (event.kind === "turn_finished") {
|
|
250
|
+
finished = true;
|
|
251
|
+
break;
|
|
252
|
+
}
|
|
253
|
+
if (this.handle(event)) clarify = event as ClarifyEvent;
|
|
254
|
+
}
|
|
255
|
+
} catch (err) {
|
|
256
|
+
if (err instanceof Cancelled || this.signal.aborted) throw new Cancelled();
|
|
257
|
+
if (!isDrop(err)) throw err; // a drop is handled like a clean end without turn_finished
|
|
258
|
+
}
|
|
259
|
+
} finally {
|
|
260
|
+
this.signal.removeEventListener("abort", onAbort);
|
|
261
|
+
current.close();
|
|
262
|
+
}
|
|
263
|
+
if (this.signal.aborted) throw new Cancelled();
|
|
264
|
+
if (finished) return clarify;
|
|
265
|
+
const responseId = current.responseId;
|
|
266
|
+
const lastEventId = current.lastEventId;
|
|
267
|
+
if (reconnects >= MAX_RECONNECTS || this.conversationId === null) {
|
|
268
|
+
throw new RunError("stream_lost", `stream ended without finishing after ${reconnects} reconnects`);
|
|
269
|
+
}
|
|
270
|
+
if (responseId === null) {
|
|
271
|
+
throw new RunError("stream_lost", "stream ended before the server sent a response id; cannot reconnect");
|
|
272
|
+
}
|
|
273
|
+
reconnects += 1;
|
|
274
|
+
this.rewind(lastEventId, itemsAtStart);
|
|
275
|
+
const conversationId = this.conversationId;
|
|
276
|
+
stream = await this.open(() => this.transport.resume(conversationId, responseId, lastEventId, this.signal));
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Handle one event other than turn_finished; returns true for a clarify request. */
|
|
281
|
+
private handle(event: Event): boolean {
|
|
282
|
+
switch (event.kind) {
|
|
283
|
+
case "turn_failed":
|
|
284
|
+
throw new RunError(event.code, event.message);
|
|
285
|
+
case "stopped":
|
|
286
|
+
if (this.signal.aborted) throw new Cancelled();
|
|
287
|
+
throw new RunError("stopped", `the turn was stopped on the server (${event.reason})`);
|
|
288
|
+
case "text_start":
|
|
289
|
+
case "text_end":
|
|
290
|
+
this.onText(event);
|
|
291
|
+
return false;
|
|
292
|
+
case "text_delta":
|
|
293
|
+
this.onText(event);
|
|
294
|
+
this.emit({ type: "raw_model_stream_event", data: { type: "output_text_delta", delta: event.delta } });
|
|
295
|
+
return false;
|
|
296
|
+
case "reasoning_delta":
|
|
297
|
+
this.emit({ type: "raw_model_stream_event", data: { type: "reasoning_delta", delta: event.delta } });
|
|
298
|
+
return false;
|
|
299
|
+
default:
|
|
300
|
+
break;
|
|
301
|
+
}
|
|
302
|
+
this.items.push(event);
|
|
303
|
+
if (event.kind === "tool_called" || event.kind === "tool_output") {
|
|
304
|
+
this.emit({ type: "run_item_stream_event", name: event.kind, item: event });
|
|
305
|
+
} else if (event.kind === "function_calls_requested") {
|
|
306
|
+
throw new NotSupportedError("function tools are not supported yet");
|
|
307
|
+
}
|
|
308
|
+
return event.kind === "clarify_requested";
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
private async ask(questions: ClarifyQuestion[]): Promise<Record<string, unknown>> {
|
|
312
|
+
const handler = this.onClarify as ClarifyHandler;
|
|
313
|
+
// Raced against the signal: a handler that never settles must not keep a cancelled run alive.
|
|
314
|
+
const answers: unknown = await raceAbort(Promise.resolve().then(() => handler(questions.slice())), this.signal);
|
|
315
|
+
if (typeof answers !== "object" || answers === null || Array.isArray(answers)) {
|
|
316
|
+
throw new UserError(`onClarify must return an object of answers, got ${Array.isArray(answers) ? "array" : typeof answers}`);
|
|
317
|
+
}
|
|
318
|
+
return answers as Record<string, unknown>;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
private answer(requestId: string, answers: Record<string, unknown>): Promise<TurnStream> {
|
|
322
|
+
const conversationId = this.conversationId;
|
|
323
|
+
if (conversationId === null) throw new RunError("stream_lost", "no conversation to answer the question in");
|
|
324
|
+
return this.open(() => this.transport.answerClarify(conversationId, requestId, answers, this.signal));
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** Run to completion, answering questions with onClarify; return an Interruption if there is no handler. */
|
|
328
|
+
async drive(stream: TurnStream): Promise<Interruption | null> {
|
|
329
|
+
for (;;) {
|
|
330
|
+
const clarify = await this.consume(stream);
|
|
331
|
+
if (clarify === null) {
|
|
332
|
+
this.emit({ type: "run_item_stream_event", name: "message_output_created", item: this.text });
|
|
333
|
+
return null;
|
|
334
|
+
}
|
|
335
|
+
if (this.onClarify === undefined) {
|
|
336
|
+
return { kind: "clarify", requestId: clarify.requestId, payload: { questions: clarify.questions.slice() } };
|
|
337
|
+
}
|
|
338
|
+
if (this.signal.aborted) throw new Cancelled();
|
|
339
|
+
const answers = await this.ask(clarify.questions);
|
|
340
|
+
if (this.signal.aborted) throw new Cancelled();
|
|
341
|
+
this.resetText();
|
|
342
|
+
stream = await this.answer(clarify.requestId, answers);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** Post the answers held in a RunState and continue; return what is still pending. */
|
|
347
|
+
async answerPending(state: RunState): Promise<Interruption[]> {
|
|
348
|
+
this.conversationId = state.conversationId;
|
|
349
|
+
this.onConversation(state.conversationId);
|
|
350
|
+
for (let n = 0; n < state.pending.length; n++) {
|
|
351
|
+
const item = state.pending[n];
|
|
352
|
+
const interruption = await this.drive(await this.answer(item.requestId, state.answers[item.requestId]));
|
|
353
|
+
if (interruption !== null) return [interruption, ...state.pending.slice(n + 1)];
|
|
354
|
+
}
|
|
355
|
+
return [];
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// -- run() -------------------------------------------------------------------------------------------------------
|
|
360
|
+
|
|
361
|
+
function checkMaxTurns(opts: { maxTurns?: unknown }): void {
|
|
362
|
+
if (opts.maxTurns !== undefined) {
|
|
363
|
+
throw new NotSupportedError(
|
|
364
|
+
"per-run maxTurns is not supported yet: the server caps turns per agent; " +
|
|
365
|
+
"set new Agent({ limits: { maxTurns } }) (limits.maxTurns)",
|
|
366
|
+
);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function checkInput(input: unknown): void {
|
|
371
|
+
if (input instanceof RunState) {
|
|
372
|
+
for (const item of input.pending) {
|
|
373
|
+
if (item.kind !== "clarify") {
|
|
374
|
+
throw new NotSupportedError(`resuming "${item.kind}" interruptions is not supported yet`);
|
|
375
|
+
}
|
|
376
|
+
if (!Object.prototype.hasOwnProperty.call(input.answers, item.requestId)) {
|
|
377
|
+
throw new UserError(`pending clarify "${item.requestId}" has no answer: call state.answer(item, {...})`);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
} else if (typeof input !== "string") {
|
|
381
|
+
throw new UserError(`input must be a string or a RunState, got ${typeof input}`);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
interface Prepared {
|
|
386
|
+
agent: Agent;
|
|
387
|
+
input: string | RunState;
|
|
388
|
+
opts: RunOptions;
|
|
389
|
+
transport: Transport;
|
|
390
|
+
owner: object;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
function prepare(agent: Agent, input: string | RunState, opts: RunOptions): Prepared {
|
|
394
|
+
checkMaxTurns(opts);
|
|
395
|
+
checkInput(input);
|
|
396
|
+
const transport = resolveTransport(opts.client, opts.transport);
|
|
397
|
+
// resolveTransport succeeded, so one of these is set.
|
|
398
|
+
const owner = (opts.transport ?? opts.client ?? getDefaultClient()) as object;
|
|
399
|
+
return { agent, input, opts, transport, owner };
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** Link the caller's signal into `controller`; returns the cleanup. */
|
|
403
|
+
function link(signal: AbortSignal | undefined, controller: AbortController): () => void {
|
|
404
|
+
if (!signal) return () => undefined;
|
|
405
|
+
if (signal.aborted) {
|
|
406
|
+
controller.abort();
|
|
407
|
+
return () => undefined;
|
|
408
|
+
}
|
|
409
|
+
const onAbort = () => controller.abort();
|
|
410
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
411
|
+
return () => signal.removeEventListener("abort", onAbort);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
async function execute(p: Prepared, controller: AbortController, emit: Emit): Promise<Outcome> {
|
|
415
|
+
const signal = controller.signal;
|
|
416
|
+
const unlink = link(p.opts.signal, controller);
|
|
417
|
+
const stopper = new Stopper(p.transport, signal);
|
|
418
|
+
const onAbort = () => stopper.send();
|
|
419
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
420
|
+
const loop = new Loop(p.transport, p.opts.onClarify, emit, signal, (c) => stopper.onConversation(c));
|
|
421
|
+
let interruptions: Interruption[] = [];
|
|
422
|
+
let cancelled = false;
|
|
423
|
+
const fallbackConversation = p.input instanceof RunState ? p.input.conversationId : p.opts.conversationId;
|
|
424
|
+
try {
|
|
425
|
+
if (signal.aborted) throw new Cancelled(); // nothing to deploy, answer or stop
|
|
426
|
+
if (p.input instanceof RunState) {
|
|
427
|
+
interruptions = await loop.answerPending(p.input);
|
|
428
|
+
} else {
|
|
429
|
+
const agentId = await raceAbort(agentIdFor(p.agent, p.transport, p.owner), signal);
|
|
430
|
+
const stream = await loop.start(agentId, p.opts.conversationId ?? null, p.input);
|
|
431
|
+
const interruption = await loop.drive(stream);
|
|
432
|
+
interruptions = interruption ? [interruption] : [];
|
|
433
|
+
}
|
|
434
|
+
} catch (err) {
|
|
435
|
+
if (!(err instanceof Cancelled)) throw err;
|
|
436
|
+
interruptions = [];
|
|
437
|
+
cancelled = true;
|
|
438
|
+
} finally {
|
|
439
|
+
stopper.complete = true;
|
|
440
|
+
signal.removeEventListener("abort", onAbort);
|
|
441
|
+
unlink();
|
|
442
|
+
}
|
|
443
|
+
cancelled = cancelled || signal.aborted;
|
|
444
|
+
const text = loop.text;
|
|
445
|
+
return {
|
|
446
|
+
finalOutput: interruptions.length || cancelled ? undefined : text,
|
|
447
|
+
outputText: text,
|
|
448
|
+
newItems: loop.items,
|
|
449
|
+
interruptions,
|
|
450
|
+
conversationId: loop.conversationId ?? fallbackConversation,
|
|
451
|
+
cancelled,
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// -- streaming ---------------------------------------------------------------------------------------------------
|
|
456
|
+
|
|
457
|
+
/** Returned by `run(..., { stream: true })`. Iterate it once (or use `toTextStream()`); leaving early cancels. */
|
|
458
|
+
export class StreamedRunResult implements AsyncIterable<RunStreamEvent> {
|
|
459
|
+
/** Settles when the run ends; rejects with the run's error. */
|
|
460
|
+
readonly completed: Promise<void>;
|
|
461
|
+
finalOutput: string | undefined = undefined;
|
|
462
|
+
outputText = "";
|
|
463
|
+
newItems: Event[] = [];
|
|
464
|
+
interruptions: Interruption[] = [];
|
|
465
|
+
conversationId: string | undefined = undefined;
|
|
466
|
+
cancelled = false;
|
|
467
|
+
|
|
468
|
+
private readonly queue: RunStreamEvent[] = [];
|
|
469
|
+
private waiters: (() => void)[] = [];
|
|
470
|
+
private done = false;
|
|
471
|
+
private failure: { error: unknown } | null = null;
|
|
472
|
+
private consumed = false;
|
|
473
|
+
private readonly controller: AbortController;
|
|
474
|
+
|
|
475
|
+
/** @internal */
|
|
476
|
+
constructor(prepared: Prepared) {
|
|
477
|
+
this.controller = new AbortController();
|
|
478
|
+
this.conversationId = prepared.input instanceof RunState ? prepared.input.conversationId : prepared.opts.conversationId;
|
|
479
|
+
this.completed = execute(prepared, this.controller, (e) => this.push(e)).then(
|
|
480
|
+
(outcome) => {
|
|
481
|
+
this.finalOutput = outcome.finalOutput;
|
|
482
|
+
this.outputText = outcome.outputText;
|
|
483
|
+
this.newItems = outcome.newItems;
|
|
484
|
+
this.interruptions = outcome.interruptions;
|
|
485
|
+
this.conversationId = outcome.conversationId;
|
|
486
|
+
this.cancelled = outcome.cancelled;
|
|
487
|
+
this.end();
|
|
488
|
+
},
|
|
489
|
+
(error) => {
|
|
490
|
+
this.failure = { error };
|
|
491
|
+
this.end();
|
|
492
|
+
throw error;
|
|
493
|
+
},
|
|
494
|
+
);
|
|
495
|
+
this.completed.catch(() => undefined); // reported through iteration or `await completed`, never unhandled
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
get state(): RunState {
|
|
499
|
+
return stateOf(this.conversationId, this.interruptions);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
private push(event: RunStreamEvent): void {
|
|
503
|
+
this.queue.push(event);
|
|
504
|
+
this.notify();
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
private end(): void {
|
|
508
|
+
this.done = true;
|
|
509
|
+
this.notify();
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
private notify(): void {
|
|
513
|
+
const waiters = this.waiters;
|
|
514
|
+
this.waiters = [];
|
|
515
|
+
for (const wake of waiters) wake();
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
private claim(): void {
|
|
519
|
+
if (this.consumed) throw new UserError("a streamed run can only be consumed once");
|
|
520
|
+
this.consumed = true;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* The event iterator. Hand-written rather than an async generator: a generator's return() queues behind a pending
|
|
525
|
+
* next(), so leaving while the server is quiet would neither settle nor cancel the run until another event came.
|
|
526
|
+
*/
|
|
527
|
+
private events(): AsyncIterator<RunStreamEvent> {
|
|
528
|
+
let closed = false;
|
|
529
|
+
const finished = (): IteratorResult<RunStreamEvent> => ({ done: true, value: undefined });
|
|
530
|
+
return {
|
|
531
|
+
next: async (): Promise<IteratorResult<RunStreamEvent>> => {
|
|
532
|
+
for (;;) {
|
|
533
|
+
if (closed) return finished();
|
|
534
|
+
const next = this.queue.shift();
|
|
535
|
+
if (next !== undefined) return { done: false, value: next };
|
|
536
|
+
if (this.done) {
|
|
537
|
+
closed = true;
|
|
538
|
+
if (this.failure) throw this.failure.error;
|
|
539
|
+
return finished();
|
|
540
|
+
}
|
|
541
|
+
await new Promise<void>((resolve) => this.waiters.push(resolve));
|
|
542
|
+
}
|
|
543
|
+
},
|
|
544
|
+
// Left early (break, return, a throwing loop body, a cancelled text stream): cancel the run, wake pending reads.
|
|
545
|
+
return: async (): Promise<IteratorResult<RunStreamEvent>> => {
|
|
546
|
+
if (!closed) {
|
|
547
|
+
closed = true;
|
|
548
|
+
if (!this.done) this.controller.abort();
|
|
549
|
+
this.notify();
|
|
550
|
+
}
|
|
551
|
+
return finished();
|
|
552
|
+
},
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
[Symbol.asyncIterator](): AsyncIterator<RunStreamEvent> {
|
|
557
|
+
this.claim();
|
|
558
|
+
return this.events();
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/** The output text deltas as a ReadableStream; consumes this result's events. */
|
|
562
|
+
toTextStream(): ReadableStream<string> {
|
|
563
|
+
this.claim();
|
|
564
|
+
const it = this.events();
|
|
565
|
+
return new ReadableStream<string>({
|
|
566
|
+
async pull(controller) {
|
|
567
|
+
for (;;) {
|
|
568
|
+
const r = await it.next();
|
|
569
|
+
if (r.done) {
|
|
570
|
+
controller.close();
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
const e = r.value;
|
|
574
|
+
if (e.type === "raw_model_stream_event" && e.data.type === "output_text_delta") {
|
|
575
|
+
controller.enqueue(e.data.delta);
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
},
|
|
580
|
+
async cancel() {
|
|
581
|
+
if (it.return) await it.return(); // settles at once and cancels the run, even with a pull pending
|
|
582
|
+
},
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/**
|
|
588
|
+
* Run `agent` on `input` (a message, or a RunState holding answers), deploying it first if this owner has not
|
|
589
|
+
* deployed this exact definition. With `stream: true`, resolves at once with a StreamedRunResult.
|
|
590
|
+
*/
|
|
591
|
+
export function run(agent: Agent, input: string | RunState, opts: RunOptions & { stream: true }): Promise<StreamedRunResult>;
|
|
592
|
+
export function run(agent: Agent, input: string | RunState, opts?: RunOptions & { stream?: false }): Promise<RunResult>;
|
|
593
|
+
export async function run(
|
|
594
|
+
agent: Agent,
|
|
595
|
+
input: string | RunState,
|
|
596
|
+
opts: RunOptions & { stream?: boolean } = {},
|
|
597
|
+
): Promise<RunResult | StreamedRunResult> {
|
|
598
|
+
const prepared = prepare(agent, input, opts);
|
|
599
|
+
if (opts.stream) return new StreamedRunResult(prepared);
|
|
600
|
+
return new RunResult(await execute(prepared, new AbortController(), () => undefined));
|
|
601
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/** RunState: what a paused run needs to continue (conversation, pending interruptions and the caller's answers). */
|
|
2
|
+
import type { Agent } from "./agent.js";
|
|
3
|
+
import { UserError } from "./errors.js";
|
|
4
|
+
import type { ClarifyQuestion } from "./events.js";
|
|
5
|
+
|
|
6
|
+
const STATE_VERSION = 1;
|
|
7
|
+
|
|
8
|
+
export interface Interruption {
|
|
9
|
+
kind: "clarify";
|
|
10
|
+
requestId: string;
|
|
11
|
+
payload: { questions: ClarifyQuestion[] };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function isObject(v: unknown): v is Record<string, unknown> {
|
|
15
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export class RunState {
|
|
19
|
+
readonly conversationId: string;
|
|
20
|
+
readonly pending: Interruption[];
|
|
21
|
+
/** @internal */
|
|
22
|
+
readonly answers: Record<string, Record<string, unknown>>;
|
|
23
|
+
/** @internal */
|
|
24
|
+
readonly transportKind: string;
|
|
25
|
+
|
|
26
|
+
/** @internal Use `result.state` or `RunState.fromString`. */
|
|
27
|
+
constructor(
|
|
28
|
+
conversationId: string,
|
|
29
|
+
pending: Interruption[],
|
|
30
|
+
answers: Record<string, Record<string, unknown>> = {},
|
|
31
|
+
transportKind = "settings",
|
|
32
|
+
) {
|
|
33
|
+
this.conversationId = conversationId;
|
|
34
|
+
this.pending = pending;
|
|
35
|
+
this.answers = answers;
|
|
36
|
+
this.transportKind = transportKind;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Record the answers to a pending interruption; `run(agent, state)` sends them. */
|
|
40
|
+
answer(item: Interruption, answers: Record<string, unknown>): void {
|
|
41
|
+
if (!this.pending.some((p) => p.requestId === item.requestId)) {
|
|
42
|
+
throw new UserError(`no pending item with request id "${item.requestId}"`);
|
|
43
|
+
}
|
|
44
|
+
this.answers[item.requestId] = { ...answers };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** JSON in the format Python's `RunState.to_json()` writes. */
|
|
48
|
+
toString(): string {
|
|
49
|
+
return JSON.stringify({
|
|
50
|
+
version: STATE_VERSION,
|
|
51
|
+
transport_kind: this.transportKind,
|
|
52
|
+
conversation_id: this.conversationId,
|
|
53
|
+
pending: this.pending.map((p) => ({ kind: p.kind, request_id: p.requestId, payload: p.payload })),
|
|
54
|
+
answers: this.answers,
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Read a state written by `toString()` (or by Python's `to_json()`). */
|
|
59
|
+
static async fromString(agent: Agent, s: string): Promise<RunState> {
|
|
60
|
+
void agent; // accepted for @openai/agents parity; the state holds no agent definition
|
|
61
|
+
let data: unknown;
|
|
62
|
+
try {
|
|
63
|
+
data = JSON.parse(s);
|
|
64
|
+
} catch (err) {
|
|
65
|
+
throw new UserError(`run state is not valid JSON: ${(err as Error).message}`);
|
|
66
|
+
}
|
|
67
|
+
if (!isObject(data) || data["version"] !== STATE_VERSION) {
|
|
68
|
+
const version = isObject(data) ? JSON.stringify(data["version"]) : "none";
|
|
69
|
+
throw new UserError(`unsupported run state version: ${version}`);
|
|
70
|
+
}
|
|
71
|
+
const conversationId = data["conversation_id"];
|
|
72
|
+
if (typeof conversationId !== "string" || conversationId === "") {
|
|
73
|
+
throw new UserError("run state is missing conversation_id");
|
|
74
|
+
}
|
|
75
|
+
const rawPending = data["pending"] ?? [];
|
|
76
|
+
if (!Array.isArray(rawPending)) throw new UserError("run state pending must be a list");
|
|
77
|
+
const pending = rawPending.map((p): Interruption => {
|
|
78
|
+
if (!isObject(p) || typeof p["kind"] !== "string") throw new UserError("run state pending item is missing kind");
|
|
79
|
+
if (typeof p["request_id"] !== "string") throw new UserError("run state pending item is missing request_id");
|
|
80
|
+
const payload = isObject(p["payload"]) ? p["payload"] : {};
|
|
81
|
+
// Other kinds are kept as read; run() refuses them with NotSupportedError, as Python does.
|
|
82
|
+
return { kind: p["kind"], requestId: p["request_id"], payload } as unknown as Interruption;
|
|
83
|
+
});
|
|
84
|
+
const rawAnswers = data["answers"] ?? {};
|
|
85
|
+
if (!isObject(rawAnswers)) throw new UserError("run state answers must be an object");
|
|
86
|
+
const answers: Record<string, Record<string, unknown>> = {};
|
|
87
|
+
for (const key of Object.keys(rawAnswers)) {
|
|
88
|
+
const value = rawAnswers[key];
|
|
89
|
+
if (!isObject(value)) throw new UserError(`run state answers for "${key}" must be an object`);
|
|
90
|
+
answers[key] = { ...value };
|
|
91
|
+
}
|
|
92
|
+
const transportKind = typeof data["transport_kind"] === "string" ? data["transport_kind"] : "settings";
|
|
93
|
+
return new RunState(conversationId, pending, answers, transportKind);
|
|
94
|
+
}
|
|
95
|
+
}
|