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,21 +1,181 @@
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";
7
- import { answerClarify, reconnect, streamResponse } from "../streaming.js";
8
- import { NotSupportedByServerError, UserError } from "./errors.js";
9
- import { fromUiChunk } from "./events.js";
6
+ import { FetchError, ResponseError } from "../runtime.js";
7
+ import { answerClarify, postToolResults, reconnect, streamResponse } from "../streaming.js";
8
+ import { NotSupportedByServerError, RunError, UserError } from "./errors.js";
9
+ import { chunksFromUiMessage, fromUiChunk } from "./events.js";
10
10
  const PAGE = 100;
11
+ /** A post the server is still delivering (409 in_progress) is retried this many times, Retry-After apart. */
12
+ const IN_PROGRESS_RETRIES = 5;
13
+ /** A post the server could not deliver to the agent (503; nothing was kept) is re-posted this many times,
14
+ * Retry-After apart, with the same Idempotency-Key and results: the agent takes them once. */
15
+ const UNAVAILABLE_RETRIES = 5;
16
+ /** The longest wait one Retry-After can ask for, in seconds. */
17
+ const RETRY_AFTER_MAX = 30;
18
+ /** After a 409 expired or already_answered the server goes on with the turn; chat_service may still be picking that
19
+ * continuation up. The conversation is read again every `followPollMs.value` ms, at most FOLLOW_POLLS times. Mutable
20
+ * for tests; not exported from the compose root. */
21
+ export const followPollMs = { value: 1000 };
22
+ const FOLLOW_POLLS = 30;
23
+ /** 409 reasons after which the server went on with the turn without this post: the run follows it. */
24
+ const WENT_ON = {
25
+ expired: "the results arrived too late: the request expired, and the agent got a failed result for each call and " +
26
+ "went on without them",
27
+ already_answered: "another poster answered the request first; the agent went on with those results",
28
+ };
29
+ /** Why POST .../tool-results refused a post, by reason (`error.details[0].reason`); the run cannot go on from here. */
30
+ const REFUSALS = {
31
+ expired: "the request expired before its results arrived; the agent went on without them",
32
+ stopped: "the user stopped the turn before these results arrived; the server answered every call with an error " +
33
+ "and stopped the turn",
34
+ ended: "the turn waiting on these results has ended",
35
+ already_answered: "these function calls were already answered",
36
+ idempotency_key_reused: "the request was answered with other results under the same Idempotency-Key",
37
+ no_active_run: "no agent run is waiting on these results (the session has ended)",
38
+ results_too_large: "the outputs together are over the server's limit",
39
+ unknown_request: "the server has no function-call request with this id",
40
+ missing_tool_call_ids: "the results do not answer every call of the request",
41
+ unknown_tool_call_ids: "the results answer calls that are not part of the request",
42
+ duplicate_tool_call_ids: "the results answer a call more than once",
43
+ };
44
+ /** A post that got no answer (the connection broke or timed out) is retried this many times, with the same key. */
45
+ const LOST_POST_RETRIES = 3;
46
+ /** No answer from the server: fetch failed (a TypeError from undici, wrapped in FetchError by the runtime). */
47
+ function isLostPost(err, signal) {
48
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted)
49
+ return false;
50
+ return err instanceof FetchError || err instanceof TypeError;
51
+ }
52
+ /** `error.details[0].reason` of a chat_service error response, else null. */
53
+ async function reason(err, status) {
54
+ if (!(err instanceof ResponseError) || err.response.status !== status)
55
+ return null;
56
+ try {
57
+ const value = (await err.response.clone().json()).error.details[0].reason;
58
+ return typeof value === "string" ? value : null;
59
+ }
60
+ catch (_a) {
61
+ return null;
62
+ }
63
+ }
64
+ /** Whether a stored reply still ends on `requestId`: nothing after its `data-function-call-request` part but the
65
+ * paused segment's `data-output` (`skipped: "paused"`), so the turn has not gone on from it yet. */
66
+ function waitsOn(message, requestId) {
67
+ const parts = message !== null && typeof message === "object" ? message["parts"] : null;
68
+ const list = Array.isArray(parts) ? parts : [];
69
+ const at = list.findIndex((p) => {
70
+ var _a, _b;
71
+ return p !== null && typeof p === "object" && p["type"] === "data-function-call-request"
72
+ && ((_b = (_a = p["data"]) === null || _a === void 0 ? void 0 : _a["requestId"]) !== null && _b !== void 0 ? _b : p["id"]) === requestId;
73
+ });
74
+ if (at === -1)
75
+ return false;
76
+ return list.slice(at + 1).every((p) => {
77
+ var _a;
78
+ const kind = p !== null && typeof p === "object" ? p["type"] : undefined;
79
+ if (kind === "reasoning" || kind === "step-start")
80
+ return true;
81
+ return kind === "data-output" && ((_a = p["data"]) === null || _a === void 0 ? void 0 : _a["skipped"]) === "paused";
82
+ });
83
+ }
84
+ /** The `error` object of a chat_service error response, else null (not a chat_service error). */
85
+ async function chatError(err) {
86
+ try {
87
+ const error = (await err.response.clone().json()).error;
88
+ return error !== null && typeof error === "object" && !Array.isArray(error) ? error : null;
89
+ }
90
+ catch (_a) {
91
+ return null;
92
+ }
93
+ }
94
+ /** `error.details[0]` of a chat_service error, else {}. */
95
+ function firstDetail(error) {
96
+ const details = error === null || error === void 0 ? void 0 : error["details"];
97
+ const first = Array.isArray(details) ? details[0] : undefined;
98
+ return first !== null && typeof first === "object" && !Array.isArray(first) ? { ...first } : {};
99
+ }
100
+ function retryAfterMs(err) {
101
+ var _a;
102
+ const seconds = Number((_a = err.response.headers.get("retry-after")) !== null && _a !== void 0 ? _a : 2);
103
+ if (!Number.isFinite(seconds) || seconds < 0)
104
+ return 2000;
105
+ return Math.min(seconds, RETRY_AFTER_MAX) * 1000;
106
+ }
107
+ /** A refused POST .../tool-results as the SDK's error: RunError with the server's reason as `code`,
108
+ * NotSupportedByServerError(["functions"]) for a server without the route, else the ResponseError itself. */
109
+ async function refused(err, requestId) {
110
+ const status = err.response.status;
111
+ const error = await chatError(err);
112
+ const detail = firstDetail(error);
113
+ const why = typeof detail["reason"] === "string" ? detail["reason"] : null;
114
+ if (why !== null && Object.prototype.hasOwnProperty.call(REFUSALS, why)) {
115
+ let message = `function results for request ${requestId}: ${REFUSALS[why]}`;
116
+ if (why === "results_too_large" && detail["maxBytes"] !== undefined)
117
+ message += ` (${String(detail["maxBytes"])} bytes)`;
118
+ const ids = detail["toolCallIds"];
119
+ if (Array.isArray(ids) && ids.length > 0)
120
+ message += `: ${ids.map(String).join(", ")}`;
121
+ return new RunError(why, message, status, detail);
122
+ }
123
+ if (status === 404) {
124
+ if (error === null)
125
+ 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`, 404, detail);
127
+ }
128
+ return err;
129
+ }
130
+ /** The `Idempotency-Key` for answering `requestId`: the same for every post of it, from any process. */
131
+ export function idempotencyKey(requestId) {
132
+ return createHash("sha256").update(requestId, "utf8").digest("hex");
133
+ }
134
+ function sleep(ms, signal) {
135
+ return new Promise((resolve, reject) => {
136
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted)
137
+ return reject(signal.reason);
138
+ const timer = setTimeout(() => {
139
+ signal === null || signal === void 0 ? void 0 : signal.removeEventListener("abort", onAbort);
140
+ resolve();
141
+ }, ms);
142
+ const onAbort = () => {
143
+ clearTimeout(timer);
144
+ reject(signal === null || signal === void 0 ? void 0 : signal.reason);
145
+ };
146
+ signal === null || signal === void 0 ? void 0 : signal.addEventListener("abort", onAbort, { once: true });
147
+ });
148
+ }
149
+ /** A turn that has already ended, read back from its stored reply (`chunksFromUiMessage`). A replay: it holds the
150
+ * whole turn, the requests this run answered too. */
151
+ class Finished {
152
+ constructor(conversationId, chunks) {
153
+ this.conversationId = conversationId;
154
+ this.chunks = chunks;
155
+ this.responseId = null;
156
+ this.lastEventId = null;
157
+ this.replay = true;
158
+ }
159
+ async *[Symbol.asyncIterator]() {
160
+ for (const chunk of this.chunks) {
161
+ const event = fromUiChunk(chunk);
162
+ if (event !== null)
163
+ yield event;
164
+ }
165
+ }
166
+ close() { }
167
+ }
11
168
  function isNotFound(err) {
12
169
  return err instanceof ResponseError && err.response.status === 404;
13
170
  }
14
171
  /** TurnStream over a streaming ResponseStream; ids are read live from the underlying stream. */
15
172
  class Stream {
16
- constructor(inner, conversationId) {
173
+ constructor(inner, conversationId,
174
+ /** Read without a cursor after a duplicate post: the server replays the turn from its start. */
175
+ replay = false) {
17
176
  this.inner = inner;
18
177
  this.conversationId = conversationId;
178
+ this.replay = replay;
19
179
  }
20
180
  get responseId() {
21
181
  return this.inner.responseId;
@@ -188,7 +348,18 @@ export class SettingsTransport {
188
348
  agentId,
189
349
  message: { id: randomUUID(), role: "user", parts: [{ type: "text", text }] },
190
350
  };
191
- return new Stream(await streamResponse(this.config, body, { signal }), conversationId);
351
+ let inner;
352
+ try {
353
+ inner = await streamResponse(this.config, body, { signal });
354
+ }
355
+ catch (err) {
356
+ if ((await reason(err, 409)) === "function_call_pending") {
357
+ throw new RunError("function_call_pending", "the conversation is waiting on function results from an earlier " +
358
+ "run; continue it with run(agent, await RunState.fromSession(conversationId))");
359
+ }
360
+ throw err;
361
+ }
362
+ return new Stream(inner, conversationId);
192
363
  }
193
364
  async answerClarify(conversationId, requestId, answers, signal) {
194
365
  const inner = await answerClarify(this.config, conversationId, { requestId, answers }, { signal });
@@ -201,6 +372,126 @@ export class SettingsTransport {
201
372
  async stop(conversationId) {
202
373
  await this.responses.stopResponse({ conversationId });
203
374
  }
375
+ async postFunctionResults(conversationId, requestId, results, signal) {
376
+ const body = {
377
+ requestId,
378
+ results: results.map((r) => ({ toolCallId: r.callId, output: r.output, isError: r.isError })),
379
+ };
380
+ const key = idempotencyKey(requestId);
381
+ let inner;
382
+ let busy = 0;
383
+ let unavailable = 0;
384
+ let lost = 0;
385
+ for (;;) {
386
+ try {
387
+ inner = await postToolResults(this.config, conversationId, body, { signal, idempotencyKey: key });
388
+ break;
389
+ }
390
+ catch (err) {
391
+ if (isLostPost(err, signal)) {
392
+ // The server may have stored the results before the connection broke: the same key makes a retry safe,
393
+ // and a stored post comes back as a duplicate.
394
+ if (lost >= LOST_POST_RETRIES) {
395
+ const why = err instanceof Error ? `${err.name}: ${err.message}` : String(err);
396
+ throw new RunError("stream_lost", `function results for request ${requestId} got no answer after ${lost + 1} tries (${why})`);
397
+ }
398
+ await sleep(250 * 2 ** lost, signal);
399
+ lost += 1;
400
+ continue;
401
+ }
402
+ if (!(err instanceof ResponseError))
403
+ throw err;
404
+ const status = err.response.status;
405
+ const why = status === 409 ? firstDetail(await chatError(err))["reason"] : undefined;
406
+ if (why === "in_progress") {
407
+ // The first post with this key is still being delivered; answered only while the request is the open
408
+ // pause, so the same post is safe to repeat.
409
+ if (busy >= IN_PROGRESS_RETRIES) {
410
+ throw new RunError(why, `function results for request ${requestId} were still being delivered after ` +
411
+ `${busy + 1} tries`, 409, firstDetail(await chatError(err)));
412
+ }
413
+ await sleep(retryAfterMs(err), signal);
414
+ busy += 1;
415
+ continue;
416
+ }
417
+ if (status === 503) {
418
+ // Not delivered and nothing kept, but the agent may have them: the same key and results again.
419
+ if (unavailable >= UNAVAILABLE_RETRIES) {
420
+ throw new RunError("unavailable", `function results for request ${requestId} could not be delivered to ` +
421
+ `the agent after ${unavailable + 1} tries`, 503, firstDetail(await chatError(err)));
422
+ }
423
+ await sleep(retryAfterMs(err), signal);
424
+ unavailable += 1;
425
+ continue;
426
+ }
427
+ if (status === 409 && typeof why === "string" && Object.prototype.hasOwnProperty.call(WENT_ON, why)) {
428
+ console.warn(`function results for request ${requestId} were not taken (409 ${why}): ${WENT_ON[why]}; ` +
429
+ "following the turn");
430
+ return this.followAfter(conversationId, requestId, why, signal);
431
+ }
432
+ throw await refused(err, requestId);
433
+ }
434
+ }
435
+ if (!inner.duplicate)
436
+ return new Stream(inner, conversationId);
437
+ // The server already had these results (an earlier post, ours or another process's, got through).
438
+ return this.follow(conversationId, signal);
439
+ }
440
+ /** The turn after a request someone already answered, as a replay of it from its start (the run skips up to the
441
+ * answered request): the running response by reconnecting without a cursor, else the conversation's last reply
442
+ * as stored. A turn that paused again ends on its new request, unanswered. */
443
+ async follow(conversationId, signal) {
444
+ return this.followAfter(conversationId, null, null, signal);
445
+ }
446
+ /** `follow`, after a 409 expired / already_answered for `requestId`: a turn not yet picked up again (no active
447
+ * response, and the last reply still ends on that request) is read again every second, up to 30 times; then
448
+ * RunError(reason). An abort ends the wait. */
449
+ async followAfter(conversationId, requestId, why, signal) {
450
+ var _a;
451
+ for (let polls = 0;; polls++) {
452
+ // Read raw: the stored parts are passed through as they are, not through the generated models.
453
+ const raw = await this.conversations.getConversationRaw({ conversationId }, { signal });
454
+ const detail = await raw.raw.json();
455
+ const body = (detail !== null && typeof detail === "object" ? detail : {});
456
+ const responseId = body["activeResponseId"];
457
+ if (typeof responseId === "string" && responseId) {
458
+ return new Stream(await reconnect(this.config, conversationId, responseId, null, { signal }), conversationId, true);
459
+ }
460
+ const messages = Array.isArray(body["messages"]) ? body["messages"] : [];
461
+ const last = [...messages].reverse().find((m) => m !== null && typeof m === "object"
462
+ && m["role"] === "assistant");
463
+ if (requestId === null || !waitsOn(last, requestId)) {
464
+ return new Finished(conversationId, chunksFromUiMessage(last !== null && last !== void 0 ? last : null));
465
+ }
466
+ if (polls >= FOLLOW_POLLS) {
467
+ const code = why !== null && why !== void 0 ? why : "expired";
468
+ throw new RunError(code, `function results for request ${requestId}: ${(_a = WENT_ON[code]) !== null && _a !== void 0 ? _a : code}, but the turn ` +
469
+ `has not gone on after ${polls} reads; read the conversation later`, 409, { reason: code });
470
+ }
471
+ await sleep(followPollMs.value, signal);
472
+ }
473
+ }
474
+ async pending(conversationId) {
475
+ var _a, _b, _c;
476
+ const detail = await this.conversations.getConversation({ conversationId });
477
+ const grouped = new Map();
478
+ for (const action of (_a = detail.requiredActions) !== null && _a !== void 0 ? _a : []) {
479
+ if (((_b = action.type) !== null && _b !== void 0 ? _b : "function_call") !== "function_call")
480
+ continue;
481
+ let request = grouped.get(action.requestId);
482
+ if (request === undefined) {
483
+ request = { requestId: action.requestId, calls: [] };
484
+ const expires = action.expiresAt;
485
+ if (expires instanceof Date)
486
+ request.expiresAt = expires.toISOString();
487
+ else if (typeof expires === "string")
488
+ request.expiresAt = expires;
489
+ grouped.set(action.requestId, request);
490
+ }
491
+ request.calls.push({ callId: action.toolCallId, name: action.name, arguments: { ...((_c = action.arguments) !== null && _c !== void 0 ? _c : {}) } });
492
+ }
493
+ return Array.from(grouped.values());
494
+ }
204
495
  // -- helpers --------------------------------------------------------------------------------------------
205
496
  /** Put back what updateAgent overwrote; a failing restore must not mask the original error. */
206
497
  async restore(agentId, settings, instructions) {
@@ -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
  export interface SettingsWarning {
5
7
  code: string;
6
8
  path: string;
@@ -18,17 +20,33 @@ export interface TurnStream extends AsyncIterable<Event> {
18
20
  readonly conversationId: string | null;
19
21
  readonly responseId: string | null;
20
22
  readonly lastEventId: string | null;
23
+ /** Read without a cursor after a duplicate post: the server replays the turn from its start. */
24
+ readonly replay?: boolean;
21
25
  close(): void;
22
26
  }
27
+ /** A function-call request the conversation is waiting on (`requiredActions`, grouped by request). */
28
+ export interface PendingFunctionCalls {
29
+ requestId: string;
30
+ calls: FunctionCallRequest[];
31
+ expiresAt?: string;
32
+ }
23
33
  export interface Transport {
24
34
  readonly kind: "settings";
25
35
  findAgents(sdkName: string): Promise<RemoteAgent[]>;
26
36
  readAgent(agentId: string): Promise<RemoteAgent>;
27
- createAgent(agent: Agent): Promise<RemoteAgent>;
28
- updateAgent(agentId: string, agent: Agent): Promise<RemoteAgent>;
37
+ createAgent(agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
38
+ updateAgent(agentId: string, agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
29
39
  deleteAgent(agentId: string): Promise<void>;
30
40
  startTurn(agentId: string, conversationId: string | null, text: string, signal?: AbortSignal): Promise<TurnStream>;
31
41
  answerClarify(conversationId: string, requestId: string, answers: Record<string, unknown>, signal?: AbortSignal): Promise<TurnStream>;
32
42
  resume(conversationId: string, responseId: string, lastEventId: string | null, signal?: AbortSignal): Promise<TurnStream>;
33
43
  stop(conversationId: string): Promise<void>;
44
+ /** Post the results of a function-call request and stream the rest of the turn. Optional so a transport written
45
+ * before function tools still type-checks; run() needs it only when the model calls a function. */
46
+ postFunctionResults?(conversationId: string, requestId: string, results: FunctionResult[], signal?: AbortSignal): Promise<TurnStream>;
47
+ /** The function-call requests the conversation is waiting on; used by `RunState.fromSession`. */
48
+ pending?(conversationId: string): Promise<PendingFunctionCalls[]>;
49
+ /** The turn after a request answered elsewhere, replayed from its start (`replay`); resuming a stale RunState
50
+ * follows it instead of running the calls again. */
51
+ follow?(conversationId: string, signal?: AbortSignal): Promise<TurnStream>;
34
52
  }
@@ -11,6 +11,7 @@
11
11
  */
12
12
  import type { UIMessage } from './UIMessage.js';
13
13
  import type { FieldHighlight } from './FieldHighlight.js';
14
+ import type { RequiredAction } from './RequiredAction.js';
14
15
  import type { QueuedTurnView } from './QueuedTurnView.js';
15
16
  /**
16
17
  *
@@ -134,6 +135,12 @@ export interface AgentConversationDetail {
134
135
  * @memberof AgentConversationDetail
135
136
  */
136
137
  queuedTurns?: Array<QueuedTurnView>;
138
+ /**
139
+ *
140
+ * @type {Array<RequiredAction>}
141
+ * @memberof AgentConversationDetail
142
+ */
143
+ requiredActions?: Array<RequiredAction>;
137
144
  /**
138
145
  *
139
146
  * @type {boolean}
@@ -13,6 +13,7 @@
13
13
  */
14
14
  import { UIMessageFromJSON, UIMessageToJSON, } from './UIMessage.js';
15
15
  import { FieldHighlightFromJSON, FieldHighlightToJSON, } from './FieldHighlight.js';
16
+ import { RequiredActionFromJSON, RequiredActionToJSON, } from './RequiredAction.js';
16
17
  import { QueuedTurnViewFromJSON, QueuedTurnViewToJSON, } from './QueuedTurnView.js';
17
18
  /**
18
19
  * Check if a given object implements the AgentConversationDetail interface.
@@ -79,6 +80,7 @@ export function AgentConversationDetailFromJSONTyped(json, ignoreDiscriminator)
79
80
  'hasMore': json['hasMore'] == null ? undefined : json['hasMore'],
80
81
  'nextBeforeCursor': json['nextBeforeCursor'] == null ? undefined : json['nextBeforeCursor'],
81
82
  'queuedTurns': json['queuedTurns'] == null ? undefined : (json['queuedTurns'].map(QueuedTurnViewFromJSON)),
83
+ 'requiredActions': json['requiredActions'] == null ? undefined : (json['requiredActions'].map(RequiredActionFromJSON)),
82
84
  'isMine': json['isMine'] == null ? undefined : json['isMine'],
83
85
  'panjaWsId': json['panjaWsId'],
84
86
  'readOnly': json['readOnly'] == null ? undefined : json['readOnly'],
@@ -112,6 +114,7 @@ export function AgentConversationDetailToJSONTyped(value, ignoreDiscriminator =
112
114
  'hasMore': value['hasMore'],
113
115
  'nextBeforeCursor': value['nextBeforeCursor'],
114
116
  'queuedTurns': value['queuedTurns'] == null ? undefined : (value['queuedTurns'].map(QueuedTurnViewToJSON)),
117
+ 'requiredActions': value['requiredActions'] == null ? undefined : (value['requiredActions'].map(RequiredActionToJSON)),
115
118
  'isMine': value['isMine'],
116
119
  'panjaWsId': value['panjaWsId'],
117
120
  'readOnly': value['readOnly'],
@@ -9,6 +9,7 @@
9
9
  * https://openapi-generator.tech
10
10
  * Do not edit the class manually.
11
11
  */
12
+ import type { McpSecurityView } from './McpSecurityView.js';
12
13
  import type { Scope } from './Scope.js';
13
14
  import type { Capabilities } from './Capabilities.js';
14
15
  import type { FieldHighlight } from './FieldHighlight.js';
@@ -165,6 +166,24 @@ export interface AppResource {
165
166
  * @memberof AppResource
166
167
  */
167
168
  connectorMode?: string | null;
169
+ /**
170
+ *
171
+ * @type {boolean}
172
+ * @memberof AppResource
173
+ */
174
+ isCustom?: boolean;
175
+ /**
176
+ *
177
+ * @type {string}
178
+ * @memberof AppResource
179
+ */
180
+ authKind?: AppResourceAuthKindEnum | null;
181
+ /**
182
+ *
183
+ * @type {McpSecurityView}
184
+ * @memberof AppResource
185
+ */
186
+ security?: McpSecurityView | null;
168
187
  }
169
188
  /**
170
189
  * @export
@@ -182,6 +201,16 @@ export declare const AppResourceAuthTypeEnum: {
182
201
  readonly None: "none";
183
202
  };
184
203
  export type AppResourceAuthTypeEnum = typeof AppResourceAuthTypeEnum[keyof typeof AppResourceAuthTypeEnum];
204
+ /**
205
+ * @export
206
+ */
207
+ export declare const AppResourceAuthKindEnum: {
208
+ readonly Oauth: "oauth";
209
+ readonly ApiKey: "api_key";
210
+ readonly SharedKey: "shared_key";
211
+ readonly None: "none";
212
+ };
213
+ export type AppResourceAuthKindEnum = typeof AppResourceAuthKindEnum[keyof typeof AppResourceAuthKindEnum];
185
214
  /**
186
215
  * Check if a given object implements the AppResource interface.
187
216
  */
@@ -11,6 +11,7 @@
11
11
  * https://openapi-generator.tech
12
12
  * Do not edit the class manually.
13
13
  */
14
+ import { McpSecurityViewFromJSON, McpSecurityViewToJSON, } from './McpSecurityView.js';
14
15
  import { ScopeFromJSON, ScopeToJSON, } from './Scope.js';
15
16
  import { CapabilitiesFromJSON, CapabilitiesToJSON, } from './Capabilities.js';
16
17
  import { FieldHighlightFromJSON, FieldHighlightToJSON, } from './FieldHighlight.js';
@@ -29,6 +30,15 @@ export const AppResourceAuthTypeEnum = {
29
30
  ApiKey: 'api_key',
30
31
  None: 'none'
31
32
  };
33
+ /**
34
+ * @export
35
+ */
36
+ export const AppResourceAuthKindEnum = {
37
+ Oauth: 'oauth',
38
+ ApiKey: 'api_key',
39
+ SharedKey: 'shared_key',
40
+ None: 'none'
41
+ };
32
42
  /**
33
43
  * Check if a given object implements the AppResource interface.
34
44
  */
@@ -81,6 +91,9 @@ export function AppResourceFromJSONTyped(json, ignoreDiscriminator) {
81
91
  'orgName': json['orgName'] == null ? undefined : json['orgName'],
82
92
  'isManagedConnector': json['isManagedConnector'] == null ? undefined : json['isManagedConnector'],
83
93
  'connectorMode': json['connectorMode'] == null ? undefined : json['connectorMode'],
94
+ 'isCustom': json['isCustom'] == null ? undefined : json['isCustom'],
95
+ 'authKind': json['authKind'] == null ? undefined : json['authKind'],
96
+ 'security': json['security'] == null ? undefined : McpSecurityViewFromJSON(json['security']),
84
97
  };
85
98
  }
86
99
  export function AppResourceToJSON(json) {
@@ -115,5 +128,8 @@ export function AppResourceToJSONTyped(value, ignoreDiscriminator = false) {
115
128
  'orgName': value['orgName'],
116
129
  'isManagedConnector': value['isManagedConnector'],
117
130
  'connectorMode': value['connectorMode'],
131
+ 'isCustom': value['isCustom'],
132
+ 'authKind': value['authKind'],
133
+ 'security': McpSecurityViewToJSON(value['security']),
118
134
  };
119
135
  }
@@ -10,6 +10,7 @@
10
10
  * Do not edit the class manually.
11
11
  */
12
12
  import type { AppToolView } from './AppToolView.js';
13
+ import type { McpSecurityView } from './McpSecurityView.js';
13
14
  /**
14
15
  * FE dialog payload for ``GET /v1/apps/{integration_id}/tools``.
15
16
  * @export
@@ -42,12 +43,10 @@ export interface AppToolsResponse {
42
43
  tools: Array<AppToolView>;
43
44
  /**
44
45
  *
45
- * @type {{ [key: string]: any; }}
46
+ * @type {McpSecurityView}
46
47
  * @memberof AppToolsResponse
47
48
  */
48
- security?: {
49
- [key: string]: any;
50
- } | null;
49
+ security?: McpSecurityView | null;
51
50
  /**
52
51
  *
53
52
  * @type {string}
@@ -12,6 +12,7 @@
12
12
  * Do not edit the class manually.
13
13
  */
14
14
  import { AppToolViewFromJSON, AppToolViewToJSON, } from './AppToolView.js';
15
+ import { McpSecurityViewFromJSON, McpSecurityViewToJSON, } from './McpSecurityView.js';
15
16
  /**
16
17
  * @export
17
18
  */
@@ -46,7 +47,7 @@ export function AppToolsResponseFromJSONTyped(json, ignoreDiscriminator) {
46
47
  'name': json['name'],
47
48
  'authStatus': json['authStatus'],
48
49
  'tools': (json['tools'].map(AppToolViewFromJSON)),
49
- 'security': json['security'] == null ? undefined : json['security'],
50
+ 'security': json['security'] == null ? undefined : McpSecurityViewFromJSON(json['security']),
50
51
  'trust': json['trust'] == null ? undefined : json['trust'],
51
52
  };
52
53
  }
@@ -62,7 +63,7 @@ export function AppToolsResponseToJSONTyped(value, ignoreDiscriminator = false)
62
63
  'name': value['name'],
63
64
  'authStatus': value['authStatus'],
64
65
  'tools': (value['tools'].map(AppToolViewToJSON)),
65
- 'security': value['security'],
66
+ 'security': McpSecurityViewToJSON(value['security']),
66
67
  'trust': value['trust'],
67
68
  };
68
69
  }
@@ -9,6 +9,8 @@
9
9
  * https://openapi-generator.tech
10
10
  * Do not edit the class manually.
11
11
  */
12
+ import type { McpSecurityView } from './McpSecurityView.js';
13
+ import type { Scope } from './Scope.js';
12
14
  import type { AppCategory } from './AppCategory.js';
13
15
  /**
14
16
  *
@@ -124,6 +126,42 @@ export interface AppView {
124
126
  * @memberof AppView
125
127
  */
126
128
  connectorMode?: string | null;
129
+ /**
130
+ *
131
+ * @type {boolean}
132
+ * @memberof AppView
133
+ */
134
+ isCustom?: boolean;
135
+ /**
136
+ *
137
+ * @type {boolean}
138
+ * @memberof AppView
139
+ */
140
+ isOwnedByMe?: boolean;
141
+ /**
142
+ *
143
+ * @type {Scope}
144
+ * @memberof AppView
145
+ */
146
+ scope?: Scope | null;
147
+ /**
148
+ *
149
+ * @type {string}
150
+ * @memberof AppView
151
+ */
152
+ createdByName?: string | null;
153
+ /**
154
+ *
155
+ * @type {string}
156
+ * @memberof AppView
157
+ */
158
+ authKind?: AppViewAuthKindEnum | null;
159
+ /**
160
+ *
161
+ * @type {McpSecurityView}
162
+ * @memberof AppView
163
+ */
164
+ security?: McpSecurityView | null;
127
165
  }
128
166
  /**
129
167
  * @export
@@ -134,6 +172,16 @@ export declare const AppViewAuthTypeEnum: {
134
172
  readonly None: "none";
135
173
  };
136
174
  export type AppViewAuthTypeEnum = typeof AppViewAuthTypeEnum[keyof typeof AppViewAuthTypeEnum];
175
+ /**
176
+ * @export
177
+ */
178
+ export declare const AppViewAuthKindEnum: {
179
+ readonly Oauth: "oauth";
180
+ readonly ApiKey: "api_key";
181
+ readonly SharedKey: "shared_key";
182
+ readonly None: "none";
183
+ };
184
+ export type AppViewAuthKindEnum = typeof AppViewAuthKindEnum[keyof typeof AppViewAuthKindEnum];
137
185
  /**
138
186
  * Check if a given object implements the AppView interface.
139
187
  */