sarvam-agents-client 0.3.0 → 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 (125) hide show
  1. package/README.md +16 -1
  2. package/dist/apis/FunctionToolsApi.d.ts +33 -0
  3. package/dist/apis/FunctionToolsApi.js +65 -0
  4. package/dist/apis/index.d.ts +1 -0
  5. package/dist/apis/index.js +1 -0
  6. package/dist/compose/agent.d.ts +16 -3
  7. package/dist/compose/agent.js +76 -7
  8. package/dist/compose/errors.d.ts +5 -1
  9. package/dist/compose/errors.js +4 -1
  10. package/dist/compose/events.d.ts +4 -0
  11. package/dist/compose/events.js +34 -0
  12. package/dist/compose/functionTool.d.ts +101 -0
  13. package/dist/compose/functionTool.js +420 -0
  14. package/dist/compose/index.d.ts +5 -2
  15. package/dist/compose/index.js +3 -1
  16. package/dist/compose/output.d.ts +11 -0
  17. package/dist/compose/output.js +32 -7
  18. package/dist/compose/run.d.ts +5 -1
  19. package/dist/compose/run.js +118 -25
  20. package/dist/compose/runState.d.ts +26 -1
  21. package/dist/compose/runState.js +30 -0
  22. package/dist/compose/settingsTransport.d.ts +20 -1
  23. package/dist/compose/settingsTransport.js +295 -3
  24. package/dist/compose/transport.d.ts +18 -1
  25. package/dist/esm/apis/FunctionToolsApi.d.ts +33 -0
  26. package/dist/esm/apis/FunctionToolsApi.js +61 -0
  27. package/dist/esm/apis/index.d.ts +1 -0
  28. package/dist/esm/apis/index.js +1 -0
  29. package/dist/esm/compose/agent.d.ts +16 -3
  30. package/dist/esm/compose/agent.js +76 -7
  31. package/dist/esm/compose/errors.d.ts +5 -1
  32. package/dist/esm/compose/errors.js +4 -1
  33. package/dist/esm/compose/events.d.ts +4 -0
  34. package/dist/esm/compose/events.js +33 -0
  35. package/dist/esm/compose/functionTool.d.ts +101 -0
  36. package/dist/esm/compose/functionTool.js +406 -0
  37. package/dist/esm/compose/index.d.ts +5 -2
  38. package/dist/esm/compose/index.js +1 -0
  39. package/dist/esm/compose/output.d.ts +11 -0
  40. package/dist/esm/compose/output.js +30 -9
  41. package/dist/esm/compose/run.d.ts +5 -1
  42. package/dist/esm/compose/run.js +118 -25
  43. package/dist/esm/compose/runState.d.ts +26 -1
  44. package/dist/esm/compose/runState.js +31 -1
  45. package/dist/esm/compose/settingsTransport.d.ts +20 -1
  46. package/dist/esm/compose/settingsTransport.js +298 -7
  47. package/dist/esm/compose/transport.d.ts +18 -1
  48. package/dist/esm/models/AgentConversationDetail.d.ts +7 -0
  49. package/dist/esm/models/AgentConversationDetail.js +3 -0
  50. package/dist/esm/models/ClarifyBody.d.ts +6 -0
  51. package/dist/esm/models/ClarifyBody.js +2 -0
  52. package/dist/esm/models/ConversationDetail.d.ts +7 -0
  53. package/dist/esm/models/ConversationDetail.js +3 -0
  54. package/dist/esm/models/ErrorDetail.d.ts +1 -0
  55. package/dist/esm/models/ErrorDetail.js +2 -1
  56. package/dist/esm/models/FunctionResultBody.d.ts +44 -0
  57. package/dist/esm/models/FunctionResultBody.js +49 -0
  58. package/dist/esm/models/QueueMessageInput.d.ts +23 -0
  59. package/dist/esm/models/QueueMessageInput.js +14 -0
  60. package/dist/esm/models/RequiredAction.d.ts +77 -0
  61. package/dist/esm/models/RequiredAction.js +69 -0
  62. package/dist/esm/models/ResponseDetail.d.ts +8 -0
  63. package/dist/esm/models/ResponseDetail.js +2 -0
  64. package/dist/esm/models/ResponseInput.d.ts +23 -0
  65. package/dist/esm/models/ResponseInput.js +14 -0
  66. package/dist/esm/models/ToolResults200Response.d.ts +38 -0
  67. package/dist/esm/models/ToolResults200Response.js +47 -0
  68. package/dist/esm/models/ToolResultsBody.d.ts +39 -0
  69. package/dist/esm/models/ToolResultsBody.js +48 -0
  70. package/dist/esm/models/index.d.ts +4 -0
  71. package/dist/esm/models/index.js +4 -0
  72. package/dist/esm/streaming.d.ts +14 -2
  73. package/dist/esm/streaming.js +26 -4
  74. package/dist/models/AgentConversationDetail.d.ts +7 -0
  75. package/dist/models/AgentConversationDetail.js +3 -0
  76. package/dist/models/ClarifyBody.d.ts +6 -0
  77. package/dist/models/ClarifyBody.js +2 -0
  78. package/dist/models/ConversationDetail.d.ts +7 -0
  79. package/dist/models/ConversationDetail.js +3 -0
  80. package/dist/models/ErrorDetail.d.ts +1 -0
  81. package/dist/models/ErrorDetail.js +2 -1
  82. package/dist/models/FunctionResultBody.d.ts +44 -0
  83. package/dist/models/FunctionResultBody.js +56 -0
  84. package/dist/models/QueueMessageInput.d.ts +23 -0
  85. package/dist/models/QueueMessageInput.js +15 -1
  86. package/dist/models/RequiredAction.d.ts +77 -0
  87. package/dist/models/RequiredAction.js +77 -0
  88. package/dist/models/ResponseDetail.d.ts +8 -0
  89. package/dist/models/ResponseDetail.js +2 -0
  90. package/dist/models/ResponseInput.d.ts +23 -0
  91. package/dist/models/ResponseInput.js +15 -0
  92. package/dist/models/ToolResults200Response.d.ts +38 -0
  93. package/dist/models/ToolResults200Response.js +54 -0
  94. package/dist/models/ToolResultsBody.d.ts +39 -0
  95. package/dist/models/ToolResultsBody.js +55 -0
  96. package/dist/models/index.d.ts +4 -0
  97. package/dist/models/index.js +4 -0
  98. package/dist/streaming.d.ts +14 -2
  99. package/dist/streaming.js +27 -4
  100. package/package.json +1 -1
  101. package/src/apis/FunctionToolsApi.ts +102 -0
  102. package/src/apis/index.ts +1 -0
  103. package/src/compose/agent.ts +87 -9
  104. package/src/compose/errors.ts +7 -1
  105. package/src/compose/events.ts +30 -0
  106. package/src/compose/functionTool.ts +441 -0
  107. package/src/compose/index.ts +5 -2
  108. package/src/compose/output.ts +30 -9
  109. package/src/compose/run.ts +115 -18
  110. package/src/compose/runState.ts +44 -5
  111. package/src/compose/settingsTransport.ts +293 -7
  112. package/src/compose/transport.ts +24 -1
  113. package/src/models/AgentConversationDetail.ts +15 -0
  114. package/src/models/ClarifyBody.ts +8 -0
  115. package/src/models/ConversationDetail.ts +15 -0
  116. package/src/models/ErrorDetail.ts +2 -1
  117. package/src/models/FunctionResultBody.ts +83 -0
  118. package/src/models/QueueMessageInput.ts +28 -0
  119. package/src/models/RequiredAction.ts +128 -0
  120. package/src/models/ResponseDetail.ts +8 -0
  121. package/src/models/ResponseInput.ts +30 -0
  122. package/src/models/ToolResults200Response.ts +75 -0
  123. package/src/models/ToolResultsBody.ts +83 -0
  124. package/src/models/index.ts +4 -0
  125. 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,7 +1,8 @@
1
1
  /** Transport interface: the seam between the compose layer and the server. */
2
2
  import type { Agent } from "./agent.js";
3
3
  import type { OutputType } from "./output.js";
4
- import type { Event } from "./events.js";
4
+ import type { Event, FunctionCallRequest } from "./events.js";
5
+ import type { FunctionResult } from "./functionTool.js";
5
6
  export interface SettingsWarning {
6
7
  code: string;
7
8
  path: string;
@@ -19,8 +20,16 @@ export interface TurnStream extends AsyncIterable<Event> {
19
20
  readonly conversationId: string | null;
20
21
  readonly responseId: string | null;
21
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;
22
25
  close(): void;
23
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
+ }
24
33
  export interface Transport {
25
34
  readonly kind: "settings";
26
35
  findAgents(sdkName: string): Promise<RemoteAgent[]>;
@@ -32,4 +41,12 @@ export interface Transport {
32
41
  answerClarify(conversationId: string, requestId: string, answers: Record<string, unknown>, signal?: AbortSignal): Promise<TurnStream>;
33
42
  resume(conversationId: string, responseId: string, lastEventId: string | null, signal?: AbortSignal): Promise<TurnStream>;
34
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>;
35
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'],
@@ -35,6 +35,12 @@ export interface ClarifyBody {
35
35
  answers?: {
36
36
  [key: string]: any;
37
37
  };
38
+ /**
39
+ *
40
+ * @type {string}
41
+ * @memberof ClarifyBody
42
+ */
43
+ endUserId?: string | null;
38
44
  }
39
45
  /**
40
46
  * Check if a given object implements the ClarifyBody interface.
@@ -30,6 +30,7 @@ export function ClarifyBodyFromJSONTyped(json, ignoreDiscriminator) {
30
30
  'requestId': json['requestId'],
31
31
  'action': json['action'] == null ? undefined : json['action'],
32
32
  'answers': json['answers'] == null ? undefined : json['answers'],
33
+ 'endUserId': json['endUserId'] == null ? undefined : json['endUserId'],
33
34
  };
34
35
  }
35
36
  export function ClarifyBodyToJSON(json) {
@@ -43,5 +44,6 @@ export function ClarifyBodyToJSONTyped(value, ignoreDiscriminator = false) {
43
44
  'requestId': value['requestId'],
44
45
  'action': value['action'],
45
46
  'answers': value['answers'],
47
+ 'endUserId': value['endUserId'],
46
48
  };
47
49
  }
@@ -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
  * GET /conversations/{id} — the list view plus the projected history and
@@ -135,6 +136,12 @@ export interface ConversationDetail {
135
136
  * @memberof ConversationDetail
136
137
  */
137
138
  queuedTurns?: Array<QueuedTurnView>;
139
+ /**
140
+ *
141
+ * @type {Array<RequiredAction>}
142
+ * @memberof ConversationDetail
143
+ */
144
+ requiredActions?: Array<RequiredAction>;
138
145
  }
139
146
  /**
140
147
  * Check if a given object implements the ConversationDetail interface.
@@ -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 ConversationDetail interface.
@@ -77,6 +78,7 @@ export function ConversationDetailFromJSONTyped(json, ignoreDiscriminator) {
77
78
  'hasMore': json['hasMore'] == null ? undefined : json['hasMore'],
78
79
  'nextBeforeCursor': json['nextBeforeCursor'] == null ? undefined : json['nextBeforeCursor'],
79
80
  'queuedTurns': json['queuedTurns'] == null ? undefined : (json['queuedTurns'].map(QueuedTurnViewFromJSON)),
81
+ 'requiredActions': json['requiredActions'] == null ? undefined : (json['requiredActions'].map(RequiredActionFromJSON)),
80
82
  };
81
83
  }
82
84
  export function ConversationDetailToJSON(json) {
@@ -106,5 +108,6 @@ export function ConversationDetailToJSONTyped(value, ignoreDiscriminator = false
106
108
  'hasMore': value['hasMore'],
107
109
  'nextBeforeCursor': value['nextBeforeCursor'],
108
110
  'queuedTurns': value['queuedTurns'] == null ? undefined : (value['queuedTurns'].map(QueuedTurnViewToJSON)),
111
+ 'requiredActions': value['requiredActions'] == null ? undefined : (value['requiredActions'].map(RequiredActionToJSON)),
109
112
  };
110
113
  }
@@ -58,6 +58,7 @@ export declare const ErrorDetailCodeEnum: {
58
58
  readonly Unavailable: "CHAT_UNAVAILABLE";
59
59
  readonly Upstream: "CHAT_UPSTREAM";
60
60
  readonly Internal: "CHAT_INTERNAL";
61
+ readonly BalanceExhausted: "CHAT_BALANCE_EXHAUSTED";
61
62
  };
62
63
  export type ErrorDetailCodeEnum = typeof ErrorDetailCodeEnum[keyof typeof ErrorDetailCodeEnum];
63
64
  /**
@@ -25,7 +25,8 @@ export const ErrorDetailCodeEnum = {
25
25
  RateLimit: 'CHAT_RATE_LIMIT',
26
26
  Unavailable: 'CHAT_UNAVAILABLE',
27
27
  Upstream: 'CHAT_UPSTREAM',
28
- Internal: 'CHAT_INTERNAL'
28
+ Internal: 'CHAT_INTERNAL',
29
+ BalanceExhausted: 'CHAT_BALANCE_EXHAUSTED'
29
30
  };
30
31
  /**
31
32
  * Check if a given object implements the ErrorDetail interface.
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Sarvam Agents API
3
+ * Chat with a Sarvam agent, exchange files with it, and set it up (instructions, skills, knowledge bases, connectors, deploy) from your own code. Authenticate with a service token sent as a Bearer token, and send the header X-Panja-Origin: managed_agents on every request.
4
+ *
5
+ * The version of the OpenAPI document: 0.1.0
6
+ * Contact: support@sarvam.ai
7
+ *
8
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
9
+ * https://openapi-generator.tech
10
+ * Do not edit the class manually.
11
+ */
12
+ /**
13
+ * One call's result, as the app ran it.
14
+ * @export
15
+ * @interface FunctionResultBody
16
+ */
17
+ export interface FunctionResultBody {
18
+ /**
19
+ *
20
+ * @type {string}
21
+ * @memberof FunctionResultBody
22
+ */
23
+ toolCallId: string;
24
+ /**
25
+ *
26
+ * @type {string}
27
+ * @memberof FunctionResultBody
28
+ */
29
+ output: string;
30
+ /**
31
+ *
32
+ * @type {boolean}
33
+ * @memberof FunctionResultBody
34
+ */
35
+ isError?: boolean;
36
+ }
37
+ /**
38
+ * Check if a given object implements the FunctionResultBody interface.
39
+ */
40
+ export declare function instanceOfFunctionResultBody(value: object): value is FunctionResultBody;
41
+ export declare function FunctionResultBodyFromJSON(json: any): FunctionResultBody;
42
+ export declare function FunctionResultBodyFromJSONTyped(json: any, ignoreDiscriminator: boolean): FunctionResultBody;
43
+ export declare function FunctionResultBodyToJSON(json: any): FunctionResultBody;
44
+ export declare function FunctionResultBodyToJSONTyped(value?: FunctionResultBody | null, ignoreDiscriminator?: boolean): any;
@@ -0,0 +1,49 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+ /**
4
+ * Sarvam Agents API
5
+ * Chat with a Sarvam agent, exchange files with it, and set it up (instructions, skills, knowledge bases, connectors, deploy) from your own code. Authenticate with a service token sent as a Bearer token, and send the header X-Panja-Origin: managed_agents on every request.
6
+ *
7
+ * The version of the OpenAPI document: 0.1.0
8
+ * Contact: support@sarvam.ai
9
+ *
10
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
11
+ * https://openapi-generator.tech
12
+ * Do not edit the class manually.
13
+ */
14
+ /**
15
+ * Check if a given object implements the FunctionResultBody interface.
16
+ */
17
+ export function instanceOfFunctionResultBody(value) {
18
+ if (!('toolCallId' in value) || value['toolCallId'] === undefined)
19
+ return false;
20
+ if (!('output' in value) || value['output'] === undefined)
21
+ return false;
22
+ return true;
23
+ }
24
+ export function FunctionResultBodyFromJSON(json) {
25
+ return FunctionResultBodyFromJSONTyped(json, false);
26
+ }
27
+ export function FunctionResultBodyFromJSONTyped(json, ignoreDiscriminator) {
28
+ if (json == null) {
29
+ return json;
30
+ }
31
+ return {
32
+ 'toolCallId': json['toolCallId'],
33
+ 'output': json['output'],
34
+ 'isError': json['isError'] == null ? undefined : json['isError'],
35
+ };
36
+ }
37
+ export function FunctionResultBodyToJSON(json) {
38
+ return FunctionResultBodyToJSONTyped(json, false);
39
+ }
40
+ export function FunctionResultBodyToJSONTyped(value, ignoreDiscriminator = false) {
41
+ if (value == null) {
42
+ return value;
43
+ }
44
+ return {
45
+ 'toolCallId': value['toolCallId'],
46
+ 'output': value['output'],
47
+ 'isError': value['isError'],
48
+ };
49
+ }
@@ -40,6 +40,18 @@ export interface QueueMessageInput {
40
40
  * @memberof QueueMessageInput
41
41
  */
42
42
  retryOf?: string | null;
43
+ /**
44
+ *
45
+ * @type {string}
46
+ * @memberof QueueMessageInput
47
+ */
48
+ surface?: QueueMessageInputSurfaceEnum | null;
49
+ /**
50
+ *
51
+ * @type {string}
52
+ * @memberof QueueMessageInput
53
+ */
54
+ endUserId?: string | null;
43
55
  }
44
56
  /**
45
57
  * @export
@@ -49,6 +61,17 @@ export declare const QueueMessageInputDeliveryEnum: {
49
61
  readonly Now: "now";
50
62
  };
51
63
  export type QueueMessageInputDeliveryEnum = typeof QueueMessageInputDeliveryEnum[keyof typeof QueueMessageInputDeliveryEnum];
64
+ /**
65
+ * @export
66
+ */
67
+ export declare const QueueMessageInputSurfaceEnum: {
68
+ readonly Builder: "builder";
69
+ readonly Playground: "playground";
70
+ readonly Tests: "tests";
71
+ readonly Evals: "evals";
72
+ readonly Cowork: "cowork";
73
+ };
74
+ export type QueueMessageInputSurfaceEnum = typeof QueueMessageInputSurfaceEnum[keyof typeof QueueMessageInputSurfaceEnum];
52
75
  /**
53
76
  * Check if a given object implements the QueueMessageInput interface.
54
77
  */