sarvam-agents-client 0.1.2 → 0.2.1

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