sarvam-agents-client 0.2.3 → 0.3.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 (178) hide show
  1. package/README.md +16 -1
  2. package/dist/apis/AgentsApi.d.ts +4 -4
  3. package/dist/apis/AgentsApi.js +4 -4
  4. package/dist/apis/AppsApi.d.ts +1 -0
  5. package/dist/apis/AppsApi.js +3 -0
  6. package/dist/apis/FunctionToolsApi.d.ts +33 -0
  7. package/dist/apis/FunctionToolsApi.js +65 -0
  8. package/dist/apis/QueueApi.d.ts +1 -0
  9. package/dist/apis/QueueApi.js +3 -0
  10. package/dist/apis/ResponsesApi.d.ts +2 -0
  11. package/dist/apis/ResponsesApi.js +6 -0
  12. package/dist/apis/index.d.ts +1 -0
  13. package/dist/apis/index.js +1 -0
  14. package/dist/compose/agent.d.ts +26 -6
  15. package/dist/compose/agent.js +84 -7
  16. package/dist/compose/deploy.d.ts +3 -2
  17. package/dist/compose/errors.d.ts +22 -1
  18. package/dist/compose/errors.js +21 -1
  19. package/dist/compose/events.d.ts +38 -0
  20. package/dist/compose/events.js +59 -2
  21. package/dist/compose/functionTool.d.ts +101 -0
  22. package/dist/compose/functionTool.js +420 -0
  23. package/dist/compose/index.d.ts +7 -3
  24. package/dist/compose/index.js +3 -1
  25. package/dist/compose/output.d.ts +40 -0
  26. package/dist/compose/output.js +476 -0
  27. package/dist/compose/run.d.ts +44 -15
  28. package/dist/compose/run.js +164 -21
  29. package/dist/compose/runState.d.ts +28 -2
  30. package/dist/compose/runState.js +30 -0
  31. package/dist/compose/settingsTransport.d.ts +23 -3
  32. package/dist/compose/settingsTransport.js +295 -3
  33. package/dist/compose/transport.d.ts +21 -3
  34. package/dist/esm/apis/AgentsApi.d.ts +4 -4
  35. package/dist/esm/apis/AgentsApi.js +4 -4
  36. package/dist/esm/apis/AppsApi.d.ts +1 -0
  37. package/dist/esm/apis/AppsApi.js +3 -0
  38. package/dist/esm/apis/FunctionToolsApi.d.ts +33 -0
  39. package/dist/esm/apis/FunctionToolsApi.js +61 -0
  40. package/dist/esm/apis/QueueApi.d.ts +1 -0
  41. package/dist/esm/apis/QueueApi.js +3 -0
  42. package/dist/esm/apis/ResponsesApi.d.ts +2 -0
  43. package/dist/esm/apis/ResponsesApi.js +6 -0
  44. package/dist/esm/apis/index.d.ts +1 -0
  45. package/dist/esm/apis/index.js +1 -0
  46. package/dist/esm/compose/agent.d.ts +26 -6
  47. package/dist/esm/compose/agent.js +84 -7
  48. package/dist/esm/compose/deploy.d.ts +3 -2
  49. package/dist/esm/compose/errors.d.ts +22 -1
  50. package/dist/esm/compose/errors.js +21 -1
  51. package/dist/esm/compose/events.d.ts +38 -0
  52. package/dist/esm/compose/events.js +58 -2
  53. package/dist/esm/compose/functionTool.d.ts +101 -0
  54. package/dist/esm/compose/functionTool.js +406 -0
  55. package/dist/esm/compose/index.d.ts +7 -3
  56. package/dist/esm/compose/index.js +1 -0
  57. package/dist/esm/compose/output.d.ts +40 -0
  58. package/dist/esm/compose/output.js +466 -0
  59. package/dist/esm/compose/run.d.ts +44 -15
  60. package/dist/esm/compose/run.js +165 -22
  61. package/dist/esm/compose/runState.d.ts +28 -2
  62. package/dist/esm/compose/runState.js +31 -1
  63. package/dist/esm/compose/settingsTransport.d.ts +23 -3
  64. package/dist/esm/compose/settingsTransport.js +298 -7
  65. package/dist/esm/compose/transport.d.ts +21 -3
  66. package/dist/esm/models/AgentConversationDetail.d.ts +7 -0
  67. package/dist/esm/models/AgentConversationDetail.js +3 -0
  68. package/dist/esm/models/AppResource.d.ts +29 -0
  69. package/dist/esm/models/AppResource.js +16 -0
  70. package/dist/esm/models/AppToolsResponse.d.ts +3 -4
  71. package/dist/esm/models/AppToolsResponse.js +3 -2
  72. package/dist/esm/models/AppView.d.ts +48 -0
  73. package/dist/esm/models/AppView.js +23 -0
  74. package/dist/esm/models/ClarifyBody.d.ts +6 -0
  75. package/dist/esm/models/ClarifyBody.js +2 -0
  76. package/dist/esm/models/ConversationDetail.d.ts +7 -0
  77. package/dist/esm/models/ConversationDetail.js +3 -0
  78. package/dist/esm/models/ErrorDetail.d.ts +1 -0
  79. package/dist/esm/models/ErrorDetail.js +2 -1
  80. package/dist/esm/models/FunctionResultBody.d.ts +44 -0
  81. package/dist/esm/models/FunctionResultBody.js +49 -0
  82. package/dist/esm/models/McpSecurityAppealView.d.ts +50 -0
  83. package/dist/esm/models/McpSecurityAppealView.js +47 -0
  84. package/dist/esm/models/McpSecurityView.d.ts +105 -0
  85. package/dist/esm/models/McpSecurityView.js +66 -0
  86. package/dist/esm/models/MessagesResponse.d.ts +6 -0
  87. package/dist/esm/models/MessagesResponse.js +2 -0
  88. package/dist/esm/models/QueueMessageInput.d.ts +23 -0
  89. package/dist/esm/models/QueueMessageInput.js +14 -0
  90. package/dist/esm/models/RequiredAction.d.ts +77 -0
  91. package/dist/esm/models/RequiredAction.js +69 -0
  92. package/dist/esm/models/ResponseDetail.d.ts +40 -0
  93. package/dist/esm/models/ResponseDetail.js +12 -0
  94. package/dist/esm/models/ResponseInput.d.ts +23 -0
  95. package/dist/esm/models/ResponseInput.js +14 -0
  96. package/dist/esm/models/ToolResults200Response.d.ts +38 -0
  97. package/dist/esm/models/ToolResults200Response.js +47 -0
  98. package/dist/esm/models/ToolResultsBody.d.ts +39 -0
  99. package/dist/esm/models/ToolResultsBody.js +48 -0
  100. package/dist/esm/models/index.d.ts +6 -0
  101. package/dist/esm/models/index.js +6 -0
  102. package/dist/esm/streaming.d.ts +14 -2
  103. package/dist/esm/streaming.js +26 -4
  104. package/dist/models/AgentConversationDetail.d.ts +7 -0
  105. package/dist/models/AgentConversationDetail.js +3 -0
  106. package/dist/models/AppResource.d.ts +29 -0
  107. package/dist/models/AppResource.js +17 -1
  108. package/dist/models/AppToolsResponse.d.ts +3 -4
  109. package/dist/models/AppToolsResponse.js +3 -2
  110. package/dist/models/AppView.d.ts +48 -0
  111. package/dist/models/AppView.js +24 -1
  112. package/dist/models/ClarifyBody.d.ts +6 -0
  113. package/dist/models/ClarifyBody.js +2 -0
  114. package/dist/models/ConversationDetail.d.ts +7 -0
  115. package/dist/models/ConversationDetail.js +3 -0
  116. package/dist/models/ErrorDetail.d.ts +1 -0
  117. package/dist/models/ErrorDetail.js +2 -1
  118. package/dist/models/FunctionResultBody.d.ts +44 -0
  119. package/dist/models/FunctionResultBody.js +56 -0
  120. package/dist/models/McpSecurityAppealView.d.ts +50 -0
  121. package/dist/models/McpSecurityAppealView.js +54 -0
  122. package/dist/models/McpSecurityView.d.ts +105 -0
  123. package/dist/models/McpSecurityView.js +73 -0
  124. package/dist/models/MessagesResponse.d.ts +6 -0
  125. package/dist/models/MessagesResponse.js +2 -0
  126. package/dist/models/QueueMessageInput.d.ts +23 -0
  127. package/dist/models/QueueMessageInput.js +15 -1
  128. package/dist/models/RequiredAction.d.ts +77 -0
  129. package/dist/models/RequiredAction.js +77 -0
  130. package/dist/models/ResponseDetail.d.ts +40 -0
  131. package/dist/models/ResponseDetail.js +12 -0
  132. package/dist/models/ResponseInput.d.ts +23 -0
  133. package/dist/models/ResponseInput.js +15 -0
  134. package/dist/models/ToolResults200Response.d.ts +38 -0
  135. package/dist/models/ToolResults200Response.js +54 -0
  136. package/dist/models/ToolResultsBody.d.ts +39 -0
  137. package/dist/models/ToolResultsBody.js +55 -0
  138. package/dist/models/index.d.ts +6 -0
  139. package/dist/models/index.js +6 -0
  140. package/dist/streaming.d.ts +14 -2
  141. package/dist/streaming.js +27 -4
  142. package/package.json +4 -3
  143. package/src/apis/AgentsApi.ts +4 -4
  144. package/src/apis/AppsApi.ts +5 -0
  145. package/src/apis/FunctionToolsApi.ts +102 -0
  146. package/src/apis/QueueApi.ts +5 -0
  147. package/src/apis/ResponsesApi.ts +10 -0
  148. package/src/apis/index.ts +1 -0
  149. package/src/compose/agent.ts +108 -15
  150. package/src/compose/deploy.ts +6 -5
  151. package/src/compose/errors.ts +35 -2
  152. package/src/compose/events.ts +79 -1
  153. package/src/compose/functionTool.ts +441 -0
  154. package/src/compose/index.ts +7 -3
  155. package/src/compose/output.ts +436 -0
  156. package/src/compose/run.ts +208 -39
  157. package/src/compose/runState.ts +46 -6
  158. package/src/compose/settingsTransport.ts +297 -10
  159. package/src/compose/transport.ts +27 -3
  160. package/src/models/AgentConversationDetail.ts +15 -0
  161. package/src/models/AppResource.ts +42 -0
  162. package/src/models/AppToolsResponse.ts +11 -4
  163. package/src/models/AppView.ts +73 -0
  164. package/src/models/ClarifyBody.ts +8 -0
  165. package/src/models/ConversationDetail.ts +15 -0
  166. package/src/models/ErrorDetail.ts +2 -1
  167. package/src/models/FunctionResultBody.ts +83 -0
  168. package/src/models/McpSecurityAppealView.ts +89 -0
  169. package/src/models/McpSecurityView.ts +169 -0
  170. package/src/models/MessagesResponse.ts +8 -0
  171. package/src/models/QueueMessageInput.ts +28 -0
  172. package/src/models/RequiredAction.ts +128 -0
  173. package/src/models/ResponseDetail.ts +48 -0
  174. package/src/models/ResponseInput.ts +30 -0
  175. package/src/models/ToolResults200Response.ts +75 -0
  176. package/src/models/ToolResultsBody.ts +83 -0
  177. package/src/models/index.ts +6 -0
  178. package/src/streaming.ts +39 -3
@@ -1,19 +1,171 @@
1
1
  /** SettingsTransport: the compose transport on the generated API (agent settings file + responses stream). */
2
- import { randomUUID } from "node:crypto";
2
+ import { createHash, randomUUID } from "node:crypto";
3
3
  import { AgentsApi } from "../apis/AgentsApi.js";
4
4
  import { ConversationsApi } from "../apis/ConversationsApi.js";
5
5
  import { ResponsesApi } from "../apis/ResponsesApi.js";
6
- import { ResponseError } from "../runtime.js";
6
+ import { FetchError, ResponseError } from "../runtime.js";
7
7
  import type { Configuration } from "../runtime.js";
8
- import { answerClarify, reconnect, streamResponse } from "../streaming.js";
8
+ import { answerClarify, postToolResults, reconnect, streamResponse } from "../streaming.js";
9
9
  import type { ResponseStream } from "../streaming.js";
10
10
  import type { Agent } from "./agent.js";
11
- import { NotSupportedByServerError, UserError } from "./errors.js";
12
- import { fromUiChunk } from "./events.js";
11
+ import type { OutputType } from "./output.js";
12
+ import { NotSupportedByServerError, RunError, UserError } from "./errors.js";
13
+ import { chunksFromUiMessage, fromUiChunk } from "./events.js";
13
14
  import type { Event } from "./events.js";
14
- import type { RemoteAgent, SettingsWarning, Transport, TurnStream } from "./transport.js";
15
+ import type { FunctionResult } from "./functionTool.js";
16
+ import type { PendingFunctionCalls, RemoteAgent, SettingsWarning, Transport, TurnStream } from "./transport.js";
15
17
 
16
18
  const PAGE = 100;
19
+ /** A post the server is still delivering (409 in_progress) is retried this many times, Retry-After apart. */
20
+ const IN_PROGRESS_RETRIES = 5;
21
+ /** A post the server could not deliver to the agent (503; nothing was kept) is re-posted this many times,
22
+ * Retry-After apart, with the same Idempotency-Key and results: the agent takes them once. */
23
+ const UNAVAILABLE_RETRIES = 5;
24
+ /** The longest wait one Retry-After can ask for, in seconds. */
25
+ const RETRY_AFTER_MAX = 30;
26
+ /** After a 409 expired or already_answered the server goes on with the turn; chat_service may still be picking that
27
+ * continuation up. The conversation is read again every `followPollMs.value` ms, at most FOLLOW_POLLS times. Mutable
28
+ * for tests; not exported from the compose root. */
29
+ export const followPollMs = { value: 1000 };
30
+ const FOLLOW_POLLS = 30;
31
+ /** 409 reasons after which the server went on with the turn without this post: the run follows it. */
32
+ const WENT_ON: Record<string, string> = {
33
+ expired: "the results arrived too late: the request expired, and the agent got a failed result for each call and " +
34
+ "went on without them",
35
+ already_answered: "another poster answered the request first; the agent went on with those results",
36
+ };
37
+ /** Why POST .../tool-results refused a post, by reason (`error.details[0].reason`); the run cannot go on from here. */
38
+ const REFUSALS: Record<string, string> = {
39
+ expired: "the request expired before its results arrived; the agent went on without them",
40
+ stopped: "the user stopped the turn before these results arrived; the server answered every call with an error " +
41
+ "and stopped the turn",
42
+ ended: "the turn waiting on these results has ended",
43
+ already_answered: "these function calls were already answered",
44
+ idempotency_key_reused: "the request was answered with other results under the same Idempotency-Key",
45
+ no_active_run: "no agent run is waiting on these results (the session has ended)",
46
+ results_too_large: "the outputs together are over the server's limit",
47
+ unknown_request: "the server has no function-call request with this id",
48
+ missing_tool_call_ids: "the results do not answer every call of the request",
49
+ unknown_tool_call_ids: "the results answer calls that are not part of the request",
50
+ duplicate_tool_call_ids: "the results answer a call more than once",
51
+ };
52
+ /** A post that got no answer (the connection broke or timed out) is retried this many times, with the same key. */
53
+ const LOST_POST_RETRIES = 3;
54
+
55
+ /** No answer from the server: fetch failed (a TypeError from undici, wrapped in FetchError by the runtime). */
56
+ function isLostPost(err: unknown, signal?: AbortSignal): boolean {
57
+ if (signal?.aborted) return false;
58
+ return err instanceof FetchError || err instanceof TypeError;
59
+ }
60
+
61
+ /** `error.details[0].reason` of a chat_service error response, else null. */
62
+ async function reason(err: unknown, status: number): Promise<string | null> {
63
+ if (!(err instanceof ResponseError) || err.response.status !== status) return null;
64
+ try {
65
+ const value = (await err.response.clone().json()).error.details[0].reason;
66
+ return typeof value === "string" ? value : null;
67
+ } catch {
68
+ return null;
69
+ }
70
+ }
71
+
72
+ /** Whether a stored reply still ends on `requestId`: nothing after its `data-function-call-request` part but the
73
+ * paused segment's `data-output` (`skipped: "paused"`), so the turn has not gone on from it yet. */
74
+ function waitsOn(message: unknown, requestId: string): boolean {
75
+ const parts = message !== null && typeof message === "object" ? (message as Record<string, unknown>)["parts"] : null;
76
+ const list = Array.isArray(parts) ? (parts as Record<string, unknown>[]) : [];
77
+ const at = list.findIndex((p) => p !== null && typeof p === "object" && p["type"] === "data-function-call-request"
78
+ && ((p["data"] as Record<string, unknown> | undefined)?.["requestId"] ?? p["id"]) === requestId);
79
+ if (at === -1) return false;
80
+ return list.slice(at + 1).every((p) => {
81
+ const kind = p !== null && typeof p === "object" ? p["type"] : undefined;
82
+ if (kind === "reasoning" || kind === "step-start") return true;
83
+ return kind === "data-output" && (p["data"] as Record<string, unknown> | undefined)?.["skipped"] === "paused";
84
+ });
85
+ }
86
+
87
+ /** The `error` object of a chat_service error response, else null (not a chat_service error). */
88
+ async function chatError(err: ResponseError): Promise<Record<string, unknown> | null> {
89
+ try {
90
+ const error = (await err.response.clone().json()).error;
91
+ return error !== null && typeof error === "object" && !Array.isArray(error) ? error : null;
92
+ } catch {
93
+ return null;
94
+ }
95
+ }
96
+
97
+ /** `error.details[0]` of a chat_service error, else {}. */
98
+ function firstDetail(error: Record<string, unknown> | null): Record<string, unknown> {
99
+ const details = error?.["details"];
100
+ const first = Array.isArray(details) ? details[0] : undefined;
101
+ return first !== null && typeof first === "object" && !Array.isArray(first) ? { ...first } : {};
102
+ }
103
+
104
+ function retryAfterMs(err: ResponseError): number {
105
+ const seconds = Number(err.response.headers.get("retry-after") ?? 2);
106
+ if (!Number.isFinite(seconds) || seconds < 0) return 2000;
107
+ return Math.min(seconds, RETRY_AFTER_MAX) * 1000;
108
+ }
109
+
110
+ /** A refused POST .../tool-results as the SDK's error: RunError with the server's reason as `code`,
111
+ * NotSupportedByServerError(["functions"]) for a server without the route, else the ResponseError itself. */
112
+ async function refused(err: ResponseError, requestId: string): Promise<Error> {
113
+ const status = err.response.status;
114
+ const error = await chatError(err);
115
+ const detail = firstDetail(error);
116
+ const why = typeof detail["reason"] === "string" ? (detail["reason"] as string) : null;
117
+ if (why !== null && Object.prototype.hasOwnProperty.call(REFUSALS, why)) {
118
+ let message = `function results for request ${requestId}: ${REFUSALS[why]}`;
119
+ if (why === "results_too_large" && detail["maxBytes"] !== undefined) message += ` (${String(detail["maxBytes"])} bytes)`;
120
+ const ids = detail["toolCallIds"];
121
+ if (Array.isArray(ids) && ids.length > 0) message += `: ${ids.map(String).join(", ")}`;
122
+ return new RunError(why, message, status, detail);
123
+ }
124
+ if (status === 404) {
125
+ if (error === null) return new NotSupportedByServerError(["functions"]); // the framework's own 404: no route
126
+ return new RunError("not_found", `function results for request ${requestId}: no such conversation for this caller`,
127
+ 404, detail);
128
+ }
129
+ return err;
130
+ }
131
+
132
+ /** The `Idempotency-Key` for answering `requestId`: the same for every post of it, from any process. */
133
+ export function idempotencyKey(requestId: string): string {
134
+ return createHash("sha256").update(requestId, "utf8").digest("hex");
135
+ }
136
+
137
+ function sleep(ms: number, signal?: AbortSignal): Promise<void> {
138
+ return new Promise((resolve, reject) => {
139
+ if (signal?.aborted) return reject(signal.reason);
140
+ const timer = setTimeout(() => {
141
+ signal?.removeEventListener("abort", onAbort);
142
+ resolve();
143
+ }, ms);
144
+ const onAbort = () => {
145
+ clearTimeout(timer);
146
+ reject(signal?.reason);
147
+ };
148
+ signal?.addEventListener("abort", onAbort, { once: true });
149
+ });
150
+ }
151
+
152
+ /** A turn that has already ended, read back from its stored reply (`chunksFromUiMessage`). A replay: it holds the
153
+ * whole turn, the requests this run answered too. */
154
+ class Finished implements TurnStream {
155
+ readonly responseId = null;
156
+ readonly lastEventId = null;
157
+ readonly replay = true;
158
+ constructor(readonly conversationId: string, private readonly chunks: Record<string, unknown>[]) {}
159
+
160
+ async *[Symbol.asyncIterator](): AsyncGenerator<Event> {
161
+ for (const chunk of this.chunks) {
162
+ const event = fromUiChunk(chunk);
163
+ if (event !== null) yield event;
164
+ }
165
+ }
166
+
167
+ close(): void {}
168
+ }
17
169
 
18
170
  interface Envelope {
19
171
  settings?: { [key: string]: any } | null;
@@ -29,6 +181,8 @@ class Stream implements TurnStream {
29
181
  constructor(
30
182
  private readonly inner: ResponseStream,
31
183
  readonly conversationId: string | null,
184
+ /** Read without a cursor after a duplicate post: the server replays the turn from its start. */
185
+ readonly replay = false,
32
186
  ) {}
33
187
 
34
188
  get responseId(): string | null {
@@ -89,7 +243,7 @@ export class SettingsTransport implements Transport {
89
243
  return this.remote(resource, await this.instructions(agentId));
90
244
  }
91
245
 
92
- async createAgent(agent: Agent): Promise<RemoteAgent> {
246
+ async createAgent(agent: Agent<OutputType | undefined>): Promise<RemoteAgent> {
93
247
  const settings = agent.toSettings();
94
248
  let resource;
95
249
  try {
@@ -132,7 +286,7 @@ export class SettingsTransport implements Transport {
132
286
  };
133
287
  }
134
288
 
135
- async updateAgent(agentId: string, agent: Agent): Promise<RemoteAgent> {
289
+ async updateAgent(agentId: string, agent: Agent<OutputType | undefined>): Promise<RemoteAgent> {
136
290
  const settings = agent.toSettings();
137
291
  // findAgents searches by display name, so an adopted (or dashboard-renamed) agent must carry sdk_name.
138
292
  if ((await this.agents.getAgent({ agentId })).name !== agent.name) {
@@ -204,7 +358,17 @@ export class SettingsTransport implements Transport {
204
358
  agentId,
205
359
  message: { id: randomUUID(), role: "user", parts: [{ type: "text", text }] },
206
360
  };
207
- return new Stream(await streamResponse(this.config, body, { signal }), conversationId);
361
+ let inner: ResponseStream;
362
+ try {
363
+ inner = await streamResponse(this.config, body, { signal });
364
+ } catch (err) {
365
+ if ((await reason(err, 409)) === "function_call_pending") {
366
+ throw new RunError("function_call_pending", "the conversation is waiting on function results from an earlier " +
367
+ "run; continue it with run(agent, await RunState.fromSession(conversationId))");
368
+ }
369
+ throw err;
370
+ }
371
+ return new Stream(inner, conversationId);
208
372
  }
209
373
 
210
374
  async answerClarify(
@@ -231,6 +395,129 @@ export class SettingsTransport implements Transport {
231
395
  await this.responses.stopResponse({ conversationId });
232
396
  }
233
397
 
398
+ async postFunctionResults(
399
+ conversationId: string,
400
+ requestId: string,
401
+ results: FunctionResult[],
402
+ signal?: AbortSignal,
403
+ ): Promise<TurnStream> {
404
+ const body = {
405
+ requestId,
406
+ results: results.map((r) => ({ toolCallId: r.callId, output: r.output, isError: r.isError })),
407
+ };
408
+ const key = idempotencyKey(requestId);
409
+ let inner: ResponseStream;
410
+ let busy = 0;
411
+ let unavailable = 0;
412
+ let lost = 0;
413
+ for (;;) {
414
+ try {
415
+ inner = await postToolResults(this.config, conversationId, body, { signal, idempotencyKey: key });
416
+ break;
417
+ } catch (err) {
418
+ if (isLostPost(err, signal)) {
419
+ // The server may have stored the results before the connection broke: the same key makes a retry safe,
420
+ // and a stored post comes back as a duplicate.
421
+ if (lost >= LOST_POST_RETRIES) {
422
+ const why = err instanceof Error ? `${err.name}: ${err.message}` : String(err);
423
+ throw new RunError("stream_lost",
424
+ `function results for request ${requestId} got no answer after ${lost + 1} tries (${why})`);
425
+ }
426
+ await sleep(250 * 2 ** lost, signal);
427
+ lost += 1;
428
+ continue;
429
+ }
430
+ if (!(err instanceof ResponseError)) throw err;
431
+ const status = err.response.status;
432
+ const why = status === 409 ? firstDetail(await chatError(err))["reason"] : undefined;
433
+ if (why === "in_progress") {
434
+ // The first post with this key is still being delivered; answered only while the request is the open
435
+ // pause, so the same post is safe to repeat.
436
+ if (busy >= IN_PROGRESS_RETRIES) {
437
+ throw new RunError(why, `function results for request ${requestId} were still being delivered after ` +
438
+ `${busy + 1} tries`, 409, firstDetail(await chatError(err)));
439
+ }
440
+ await sleep(retryAfterMs(err), signal);
441
+ busy += 1;
442
+ continue;
443
+ }
444
+ if (status === 503) {
445
+ // Not delivered and nothing kept, but the agent may have them: the same key and results again.
446
+ if (unavailable >= UNAVAILABLE_RETRIES) {
447
+ throw new RunError("unavailable", `function results for request ${requestId} could not be delivered to ` +
448
+ `the agent after ${unavailable + 1} tries`, 503, firstDetail(await chatError(err)));
449
+ }
450
+ await sleep(retryAfterMs(err), signal);
451
+ unavailable += 1;
452
+ continue;
453
+ }
454
+ if (status === 409 && typeof why === "string" && Object.prototype.hasOwnProperty.call(WENT_ON, why)) {
455
+ console.warn(`function results for request ${requestId} were not taken (409 ${why}): ${WENT_ON[why]}; ` +
456
+ "following the turn");
457
+ return this.followAfter(conversationId, requestId, why, signal);
458
+ }
459
+ throw await refused(err, requestId);
460
+ }
461
+ }
462
+ if (!inner.duplicate) return new Stream(inner, conversationId);
463
+ // The server already had these results (an earlier post, ours or another process's, got through).
464
+ return this.follow(conversationId, signal);
465
+ }
466
+
467
+ /** The turn after a request someone already answered, as a replay of it from its start (the run skips up to the
468
+ * answered request): the running response by reconnecting without a cursor, else the conversation's last reply
469
+ * as stored. A turn that paused again ends on its new request, unanswered. */
470
+ async follow(conversationId: string, signal?: AbortSignal): Promise<TurnStream> {
471
+ return this.followAfter(conversationId, null, null, signal);
472
+ }
473
+
474
+ /** `follow`, after a 409 expired / already_answered for `requestId`: a turn not yet picked up again (no active
475
+ * response, and the last reply still ends on that request) is read again every second, up to 30 times; then
476
+ * RunError(reason). An abort ends the wait. */
477
+ private async followAfter(conversationId: string, requestId: string | null, why: string | null,
478
+ signal?: AbortSignal): Promise<TurnStream> {
479
+ for (let polls = 0; ; polls++) {
480
+ // Read raw: the stored parts are passed through as they are, not through the generated models.
481
+ const raw = await this.conversations.getConversationRaw({ conversationId }, { signal });
482
+ const detail: unknown = await raw.raw.json();
483
+ const body = (detail !== null && typeof detail === "object" ? detail : {}) as Record<string, unknown>;
484
+ const responseId = body["activeResponseId"];
485
+ if (typeof responseId === "string" && responseId) {
486
+ return new Stream(await reconnect(this.config, conversationId, responseId, null, { signal }), conversationId, true);
487
+ }
488
+ const messages = Array.isArray(body["messages"]) ? body["messages"] : [];
489
+ const last = [...messages].reverse().find((m) => m !== null && typeof m === "object"
490
+ && (m as Record<string, unknown>)["role"] === "assistant");
491
+ if (requestId === null || !waitsOn(last, requestId)) {
492
+ return new Finished(conversationId, chunksFromUiMessage(last ?? null));
493
+ }
494
+ if (polls >= FOLLOW_POLLS) {
495
+ const code = why ?? "expired";
496
+ throw new RunError(code, `function results for request ${requestId}: ${WENT_ON[code] ?? code}, but the turn ` +
497
+ `has not gone on after ${polls} reads; read the conversation later`, 409, { reason: code });
498
+ }
499
+ await sleep(followPollMs.value, signal);
500
+ }
501
+ }
502
+
503
+ async pending(conversationId: string): Promise<PendingFunctionCalls[]> {
504
+ const detail = await this.conversations.getConversation({ conversationId });
505
+ const grouped = new Map<string, PendingFunctionCalls>();
506
+ for (const action of detail.requiredActions ?? []) {
507
+ if ((action.type ?? "function_call") !== "function_call") continue;
508
+ let request = grouped.get(action.requestId);
509
+ if (request === undefined) {
510
+ request = { requestId: action.requestId, calls: [] };
511
+ const expires = action.expiresAt as unknown;
512
+ if (expires instanceof Date) request.expiresAt = expires.toISOString();
513
+ else if (typeof expires === "string") request.expiresAt = expires;
514
+ grouped.set(action.requestId, request);
515
+ }
516
+ request.calls.push({ callId: action.toolCallId, name: action.name, arguments: { ...(action.arguments ?? {}) } });
517
+ }
518
+ return Array.from(grouped.values());
519
+ }
520
+
234
521
  // -- helpers --------------------------------------------------------------------------------------------
235
522
 
236
523
  /** Put back what updateAgent overwrote; a failing restore must not mask the original error. */
@@ -271,7 +558,7 @@ async function invalidSettings(err: unknown): Promise<UserError | null> {
271
558
  }
272
559
 
273
560
  /** findAgents() matches on metadata.sdk_name; a server that drops it would get a new agent per deploy. */
274
- function checkMetadata(envelope: Envelope, agent: Agent): void {
561
+ function checkMetadata(envelope: Envelope, agent: Agent<OutputType | undefined>): void {
275
562
  const metadata = (envelope.settings ?? {})["metadata"];
276
563
  if (typeof metadata !== "object" || metadata === null || Array.isArray(metadata) || metadata["sdk_name"] !== agent.name) {
277
564
  throw new NotSupportedByServerError(["metadata"]);
@@ -1,6 +1,8 @@
1
1
  /** Transport interface: the seam between the compose layer and the server. */
2
2
  import type { Agent } from "./agent.js";
3
- import type { Event } from "./events.js";
3
+ import type { OutputType } from "./output.js";
4
+ import type { Event, FunctionCallRequest } from "./events.js";
5
+ import type { FunctionResult } from "./functionTool.js";
4
6
 
5
7
  export interface SettingsWarning {
6
8
  code: string;
@@ -21,15 +23,24 @@ export interface TurnStream extends AsyncIterable<Event> {
21
23
  readonly conversationId: string | null;
22
24
  readonly responseId: string | null;
23
25
  readonly lastEventId: string | null;
26
+ /** Read without a cursor after a duplicate post: the server replays the turn from its start. */
27
+ readonly replay?: boolean;
24
28
  close(): void;
25
29
  }
26
30
 
31
+ /** A function-call request the conversation is waiting on (`requiredActions`, grouped by request). */
32
+ export interface PendingFunctionCalls {
33
+ requestId: string;
34
+ calls: FunctionCallRequest[];
35
+ expiresAt?: string;
36
+ }
37
+
27
38
  export interface Transport {
28
39
  readonly kind: "settings";
29
40
  findAgents(sdkName: string): Promise<RemoteAgent[]>;
30
41
  readAgent(agentId: string): Promise<RemoteAgent>;
31
- createAgent(agent: Agent): Promise<RemoteAgent>;
32
- updateAgent(agentId: string, agent: Agent): Promise<RemoteAgent>;
42
+ createAgent(agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
43
+ updateAgent(agentId: string, agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
33
44
  deleteAgent(agentId: string): Promise<void>;
34
45
  startTurn(agentId: string, conversationId: string | null, text: string, signal?: AbortSignal): Promise<TurnStream>;
35
46
  answerClarify(
@@ -45,4 +56,17 @@ export interface Transport {
45
56
  signal?: AbortSignal,
46
57
  ): Promise<TurnStream>;
47
58
  stop(conversationId: string): Promise<void>;
59
+ /** Post the results of a function-call request and stream the rest of the turn. Optional so a transport written
60
+ * before function tools still type-checks; run() needs it only when the model calls a function. */
61
+ postFunctionResults?(
62
+ conversationId: string,
63
+ requestId: string,
64
+ results: FunctionResult[],
65
+ signal?: AbortSignal,
66
+ ): Promise<TurnStream>;
67
+ /** The function-call requests the conversation is waiting on; used by `RunState.fromSession`. */
68
+ pending?(conversationId: string): Promise<PendingFunctionCalls[]>;
69
+ /** The turn after a request answered elsewhere, replayed from its start (`replay`); resuming a stale RunState
70
+ * follows it instead of running the calls again. */
71
+ follow?(conversationId: string, signal?: AbortSignal): Promise<TurnStream>;
48
72
  }
@@ -27,6 +27,13 @@ import {
27
27
  FieldHighlightToJSON,
28
28
  FieldHighlightToJSONTyped,
29
29
  } from './FieldHighlight.js';
30
+ import type { RequiredAction } from './RequiredAction.js';
31
+ import {
32
+ RequiredActionFromJSON,
33
+ RequiredActionFromJSONTyped,
34
+ RequiredActionToJSON,
35
+ RequiredActionToJSONTyped,
36
+ } from './RequiredAction.js';
30
37
  import type { QueuedTurnView } from './QueuedTurnView.js';
31
38
  import {
32
39
  QueuedTurnViewFromJSON,
@@ -155,6 +162,12 @@ export interface AgentConversationDetail {
155
162
  * @memberof AgentConversationDetail
156
163
  */
157
164
  queuedTurns?: Array<QueuedTurnView>;
165
+ /**
166
+ *
167
+ * @type {Array<RequiredAction>}
168
+ * @memberof AgentConversationDetail
169
+ */
170
+ requiredActions?: Array<RequiredAction>;
158
171
  /**
159
172
  *
160
173
  * @type {boolean}
@@ -234,6 +247,7 @@ export function AgentConversationDetailFromJSONTyped(json: any, ignoreDiscrimina
234
247
  'hasMore': json['hasMore'] == null ? undefined : json['hasMore'],
235
248
  'nextBeforeCursor': json['nextBeforeCursor'] == null ? undefined : json['nextBeforeCursor'],
236
249
  'queuedTurns': json['queuedTurns'] == null ? undefined : ((json['queuedTurns'] as Array<any>).map(QueuedTurnViewFromJSON)),
250
+ 'requiredActions': json['requiredActions'] == null ? undefined : ((json['requiredActions'] as Array<any>).map(RequiredActionFromJSON)),
237
251
  'isMine': json['isMine'] == null ? undefined : json['isMine'],
238
252
  'panjaWsId': json['panjaWsId'],
239
253
  'readOnly': json['readOnly'] == null ? undefined : json['readOnly'],
@@ -271,6 +285,7 @@ export function AgentConversationDetailToJSONTyped(value?: AgentConversationDeta
271
285
  'hasMore': value['hasMore'],
272
286
  'nextBeforeCursor': value['nextBeforeCursor'],
273
287
  'queuedTurns': value['queuedTurns'] == null ? undefined : ((value['queuedTurns'] as Array<any>).map(QueuedTurnViewToJSON)),
288
+ 'requiredActions': value['requiredActions'] == null ? undefined : ((value['requiredActions'] as Array<any>).map(RequiredActionToJSON)),
274
289
  'isMine': value['isMine'],
275
290
  'panjaWsId': value['panjaWsId'],
276
291
  'readOnly': value['readOnly'],
@@ -13,6 +13,13 @@
13
13
  */
14
14
 
15
15
  import { mapValues } from '../runtime.js';
16
+ import type { McpSecurityView } from './McpSecurityView.js';
17
+ import {
18
+ McpSecurityViewFromJSON,
19
+ McpSecurityViewFromJSONTyped,
20
+ McpSecurityViewToJSON,
21
+ McpSecurityViewToJSONTyped,
22
+ } from './McpSecurityView.js';
16
23
  import type { Scope } from './Scope.js';
17
24
  import {
18
25
  ScopeFromJSON,
@@ -194,6 +201,24 @@ export interface AppResource {
194
201
  * @memberof AppResource
195
202
  */
196
203
  connectorMode?: string | null;
204
+ /**
205
+ *
206
+ * @type {boolean}
207
+ * @memberof AppResource
208
+ */
209
+ isCustom?: boolean;
210
+ /**
211
+ *
212
+ * @type {string}
213
+ * @memberof AppResource
214
+ */
215
+ authKind?: AppResourceAuthKindEnum | null;
216
+ /**
217
+ *
218
+ * @type {McpSecurityView}
219
+ * @memberof AppResource
220
+ */
221
+ security?: McpSecurityView | null;
197
222
  }
198
223
 
199
224
 
@@ -215,6 +240,17 @@ export const AppResourceAuthTypeEnum = {
215
240
  } as const;
216
241
  export type AppResourceAuthTypeEnum = typeof AppResourceAuthTypeEnum[keyof typeof AppResourceAuthTypeEnum];
217
242
 
243
+ /**
244
+ * @export
245
+ */
246
+ export const AppResourceAuthKindEnum = {
247
+ Oauth: 'oauth',
248
+ ApiKey: 'api_key',
249
+ SharedKey: 'shared_key',
250
+ None: 'none'
251
+ } as const;
252
+ export type AppResourceAuthKindEnum = typeof AppResourceAuthKindEnum[keyof typeof AppResourceAuthKindEnum];
253
+
218
254
 
219
255
  /**
220
256
  * Check if a given object implements the AppResource interface.
@@ -264,6 +300,9 @@ export function AppResourceFromJSONTyped(json: any, ignoreDiscriminator: boolean
264
300
  'orgName': json['orgName'] == null ? undefined : json['orgName'],
265
301
  'isManagedConnector': json['isManagedConnector'] == null ? undefined : json['isManagedConnector'],
266
302
  'connectorMode': json['connectorMode'] == null ? undefined : json['connectorMode'],
303
+ 'isCustom': json['isCustom'] == null ? undefined : json['isCustom'],
304
+ 'authKind': json['authKind'] == null ? undefined : json['authKind'],
305
+ 'security': json['security'] == null ? undefined : McpSecurityViewFromJSON(json['security']),
267
306
  };
268
307
  }
269
308
 
@@ -302,6 +341,9 @@ export function AppResourceToJSONTyped(value?: AppResource | null, ignoreDiscrim
302
341
  'orgName': value['orgName'],
303
342
  'isManagedConnector': value['isManagedConnector'],
304
343
  'connectorMode': value['connectorMode'],
344
+ 'isCustom': value['isCustom'],
345
+ 'authKind': value['authKind'],
346
+ 'security': McpSecurityViewToJSON(value['security']),
305
347
  };
306
348
  }
307
349
 
@@ -20,6 +20,13 @@ import {
20
20
  AppToolViewToJSON,
21
21
  AppToolViewToJSONTyped,
22
22
  } from './AppToolView.js';
23
+ import type { McpSecurityView } from './McpSecurityView.js';
24
+ import {
25
+ McpSecurityViewFromJSON,
26
+ McpSecurityViewFromJSONTyped,
27
+ McpSecurityViewToJSON,
28
+ McpSecurityViewToJSONTyped,
29
+ } from './McpSecurityView.js';
23
30
 
24
31
  /**
25
32
  * FE dialog payload for ``GET /v1/apps/{integration_id}/tools``.
@@ -53,10 +60,10 @@ export interface AppToolsResponse {
53
60
  tools: Array<AppToolView>;
54
61
  /**
55
62
  *
56
- * @type {{ [key: string]: any; }}
63
+ * @type {McpSecurityView}
57
64
  * @memberof AppToolsResponse
58
65
  */
59
- security?: { [key: string]: any; } | null;
66
+ security?: McpSecurityView | null;
60
67
  /**
61
68
  *
62
69
  * @type {string}
@@ -102,7 +109,7 @@ export function AppToolsResponseFromJSONTyped(json: any, ignoreDiscriminator: bo
102
109
  'name': json['name'],
103
110
  'authStatus': json['authStatus'],
104
111
  'tools': ((json['tools'] as Array<any>).map(AppToolViewFromJSON)),
105
- 'security': json['security'] == null ? undefined : json['security'],
112
+ 'security': json['security'] == null ? undefined : McpSecurityViewFromJSON(json['security']),
106
113
  'trust': json['trust'] == null ? undefined : json['trust'],
107
114
  };
108
115
  }
@@ -122,7 +129,7 @@ export function AppToolsResponseToJSONTyped(value?: AppToolsResponse | null, ign
122
129
  'name': value['name'],
123
130
  'authStatus': value['authStatus'],
124
131
  'tools': ((value['tools'] as Array<any>).map(AppToolViewToJSON)),
125
- 'security': value['security'],
132
+ 'security': McpSecurityViewToJSON(value['security']),
126
133
  'trust': value['trust'],
127
134
  };
128
135
  }