sarvam-agents-client 0.3.0 → 0.3.2

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 (135) hide show
  1. package/README.md +98 -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 +20 -3
  7. package/dist/compose/agent.js +84 -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 +6 -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 +28 -1
  23. package/dist/compose/settingsTransport.js +389 -7
  24. package/dist/compose/transport.d.ts +18 -1
  25. package/dist/compose/webhook.d.ts +19 -0
  26. package/dist/compose/webhook.js +184 -0
  27. package/dist/esm/apis/FunctionToolsApi.d.ts +33 -0
  28. package/dist/esm/apis/FunctionToolsApi.js +61 -0
  29. package/dist/esm/apis/index.d.ts +1 -0
  30. package/dist/esm/apis/index.js +1 -0
  31. package/dist/esm/compose/agent.d.ts +20 -3
  32. package/dist/esm/compose/agent.js +84 -7
  33. package/dist/esm/compose/errors.d.ts +5 -1
  34. package/dist/esm/compose/errors.js +4 -1
  35. package/dist/esm/compose/events.d.ts +4 -0
  36. package/dist/esm/compose/events.js +33 -0
  37. package/dist/esm/compose/functionTool.d.ts +101 -0
  38. package/dist/esm/compose/functionTool.js +406 -0
  39. package/dist/esm/compose/index.d.ts +6 -2
  40. package/dist/esm/compose/index.js +1 -0
  41. package/dist/esm/compose/output.d.ts +11 -0
  42. package/dist/esm/compose/output.js +30 -9
  43. package/dist/esm/compose/run.d.ts +5 -1
  44. package/dist/esm/compose/run.js +118 -25
  45. package/dist/esm/compose/runState.d.ts +26 -1
  46. package/dist/esm/compose/runState.js +31 -1
  47. package/dist/esm/compose/settingsTransport.d.ts +28 -1
  48. package/dist/esm/compose/settingsTransport.js +392 -11
  49. package/dist/esm/compose/transport.d.ts +18 -1
  50. package/dist/esm/compose/webhook.d.ts +19 -0
  51. package/dist/esm/compose/webhook.js +177 -0
  52. package/dist/esm/models/AgentConversationDetail.d.ts +7 -0
  53. package/dist/esm/models/AgentConversationDetail.js +3 -0
  54. package/dist/esm/models/ClarifyBody.d.ts +6 -0
  55. package/dist/esm/models/ClarifyBody.js +2 -0
  56. package/dist/esm/models/ConversationDetail.d.ts +7 -0
  57. package/dist/esm/models/ConversationDetail.js +3 -0
  58. package/dist/esm/models/ErrorDetail.d.ts +1 -0
  59. package/dist/esm/models/ErrorDetail.js +2 -1
  60. package/dist/esm/models/FunctionResultBody.d.ts +44 -0
  61. package/dist/esm/models/FunctionResultBody.js +49 -0
  62. package/dist/esm/models/QueueMessageInput.d.ts +23 -0
  63. package/dist/esm/models/QueueMessageInput.js +14 -0
  64. package/dist/esm/models/RequiredAction.d.ts +77 -0
  65. package/dist/esm/models/RequiredAction.js +69 -0
  66. package/dist/esm/models/ResponseDetail.d.ts +8 -0
  67. package/dist/esm/models/ResponseDetail.js +2 -0
  68. package/dist/esm/models/ResponseInput.d.ts +23 -0
  69. package/dist/esm/models/ResponseInput.js +14 -0
  70. package/dist/esm/models/ToolResults200Response.d.ts +38 -0
  71. package/dist/esm/models/ToolResults200Response.js +47 -0
  72. package/dist/esm/models/ToolResultsBody.d.ts +39 -0
  73. package/dist/esm/models/ToolResultsBody.js +48 -0
  74. package/dist/esm/models/index.d.ts +4 -0
  75. package/dist/esm/models/index.js +4 -0
  76. package/dist/esm/streaming.d.ts +14 -2
  77. package/dist/esm/streaming.js +26 -4
  78. package/dist/esm/webhooks.d.ts +203 -0
  79. package/dist/esm/webhooks.js +215 -0
  80. package/dist/models/AgentConversationDetail.d.ts +7 -0
  81. package/dist/models/AgentConversationDetail.js +3 -0
  82. package/dist/models/ClarifyBody.d.ts +6 -0
  83. package/dist/models/ClarifyBody.js +2 -0
  84. package/dist/models/ConversationDetail.d.ts +7 -0
  85. package/dist/models/ConversationDetail.js +3 -0
  86. package/dist/models/ErrorDetail.d.ts +1 -0
  87. package/dist/models/ErrorDetail.js +2 -1
  88. package/dist/models/FunctionResultBody.d.ts +44 -0
  89. package/dist/models/FunctionResultBody.js +56 -0
  90. package/dist/models/QueueMessageInput.d.ts +23 -0
  91. package/dist/models/QueueMessageInput.js +15 -1
  92. package/dist/models/RequiredAction.d.ts +77 -0
  93. package/dist/models/RequiredAction.js +77 -0
  94. package/dist/models/ResponseDetail.d.ts +8 -0
  95. package/dist/models/ResponseDetail.js +2 -0
  96. package/dist/models/ResponseInput.d.ts +23 -0
  97. package/dist/models/ResponseInput.js +15 -0
  98. package/dist/models/ToolResults200Response.d.ts +38 -0
  99. package/dist/models/ToolResults200Response.js +54 -0
  100. package/dist/models/ToolResultsBody.d.ts +39 -0
  101. package/dist/models/ToolResultsBody.js +55 -0
  102. package/dist/models/index.d.ts +4 -0
  103. package/dist/models/index.js +4 -0
  104. package/dist/streaming.d.ts +14 -2
  105. package/dist/streaming.js +27 -4
  106. package/dist/webhooks.d.ts +203 -0
  107. package/dist/webhooks.js +224 -0
  108. package/package.json +9 -1
  109. package/src/apis/FunctionToolsApi.ts +102 -0
  110. package/src/apis/index.ts +1 -0
  111. package/src/compose/agent.ts +96 -9
  112. package/src/compose/errors.ts +7 -1
  113. package/src/compose/events.ts +30 -0
  114. package/src/compose/functionTool.ts +441 -0
  115. package/src/compose/index.ts +6 -2
  116. package/src/compose/output.ts +30 -9
  117. package/src/compose/run.ts +115 -18
  118. package/src/compose/runState.ts +44 -5
  119. package/src/compose/settingsTransport.ts +379 -8
  120. package/src/compose/transport.ts +24 -1
  121. package/src/compose/webhook.ts +181 -0
  122. package/src/models/AgentConversationDetail.ts +15 -0
  123. package/src/models/ClarifyBody.ts +8 -0
  124. package/src/models/ConversationDetail.ts +15 -0
  125. package/src/models/ErrorDetail.ts +2 -1
  126. package/src/models/FunctionResultBody.ts +83 -0
  127. package/src/models/QueueMessageInput.ts +28 -0
  128. package/src/models/RequiredAction.ts +128 -0
  129. package/src/models/ResponseDetail.ts +8 -0
  130. package/src/models/ResponseInput.ts +30 -0
  131. package/src/models/ToolResults200Response.ts +75 -0
  132. package/src/models/ToolResultsBody.ts +83 -0
  133. package/src/models/index.ts +4 -0
  134. package/src/streaming.ts +39 -3
  135. package/src/webhooks.ts +390 -0
@@ -1,21 +1,190 @@
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
+ import { CustomAPIsApi } from "../apis/CustomAPIsApi.js";
5
6
  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";
7
+ import { FetchError, ResponseError } from "../runtime.js";
8
+ import { answerClarify, postToolResults, reconnect, streamResponse } from "../streaming.js";
9
+ import { NotSupportedByServerError, RunError, UserError } from "./errors.js";
10
+ import { chunksFromUiMessage, fromUiChunk } from "./events.js";
10
11
  const PAGE = 100;
12
+ /** A post the server is still delivering (409 in_progress) is retried this many times, Retry-After apart. */
13
+ const IN_PROGRESS_RETRIES = 5;
14
+ /** A post the server could not deliver to the agent (503; nothing was kept) is re-posted this many times,
15
+ * Retry-After apart, with the same Idempotency-Key and results: the agent takes them once. */
16
+ const UNAVAILABLE_RETRIES = 5;
17
+ /** The longest wait one Retry-After can ask for, in seconds. */
18
+ const RETRY_AFTER_MAX = 30;
19
+ /** After a 409 expired or already_answered the server goes on with the turn; chat_service may still be picking that
20
+ * continuation up. The conversation is read again every `followPollMs.value` ms, at most FOLLOW_POLLS times. Mutable
21
+ * for tests; not exported from the compose root. */
22
+ export const followPollMs = { value: 1000 };
23
+ const FOLLOW_POLLS = 30;
24
+ /** 409 reasons after which the server went on with the turn without this post: the run follows it. */
25
+ const WENT_ON = {
26
+ expired: "the results arrived too late: the request expired, and the agent got a failed result for each call and " +
27
+ "went on without them",
28
+ already_answered: "another poster answered the request first; the agent went on with those results",
29
+ };
30
+ /** Why POST .../tool-results refused a post, by reason (`error.details[0].reason`); the run cannot go on from here. */
31
+ const REFUSALS = {
32
+ expired: "the request expired before its results arrived; the agent went on without them",
33
+ stopped: "the user stopped the turn before these results arrived; the server answered every call with an error " +
34
+ "and stopped the turn",
35
+ ended: "the turn waiting on these results has ended",
36
+ already_answered: "these function calls were already answered",
37
+ idempotency_key_reused: "the request was answered with other results under the same Idempotency-Key",
38
+ no_active_run: "no agent run is waiting on these results (the session has ended)",
39
+ results_too_large: "the outputs together are over the server's limit",
40
+ unknown_request: "the server has no function-call request with this id",
41
+ missing_tool_call_ids: "the results do not answer every call of the request",
42
+ unknown_tool_call_ids: "the results answer calls that are not part of the request",
43
+ duplicate_tool_call_ids: "the results answer a call more than once",
44
+ };
45
+ /** A post that got no answer (the connection broke or timed out) is retried this many times, with the same key. */
46
+ const LOST_POST_RETRIES = 3;
47
+ /** No answer from the server: fetch failed (a TypeError from undici, wrapped in FetchError by the runtime). */
48
+ function isLostPost(err, signal) {
49
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted)
50
+ return false;
51
+ return err instanceof FetchError || err instanceof TypeError;
52
+ }
53
+ /** `error.details[0].reason` of a chat_service error response, else null. */
54
+ async function reason(err, status) {
55
+ if (!(err instanceof ResponseError) || err.response.status !== status)
56
+ return null;
57
+ try {
58
+ const value = (await err.response.clone().json()).error.details[0].reason;
59
+ return typeof value === "string" ? value : null;
60
+ }
61
+ catch (_a) {
62
+ return null;
63
+ }
64
+ }
65
+ /** Whether a stored reply still ends on `requestId`: nothing after its `data-function-call-request` part but the
66
+ * paused segment's `data-output` (`skipped: "paused"`), so the turn has not gone on from it yet. */
67
+ function waitsOn(message, requestId) {
68
+ const parts = message !== null && typeof message === "object" ? message["parts"] : null;
69
+ const list = Array.isArray(parts) ? parts : [];
70
+ const at = list.findIndex((p) => {
71
+ var _a, _b;
72
+ return p !== null && typeof p === "object" && p["type"] === "data-function-call-request"
73
+ && ((_b = (_a = p["data"]) === null || _a === void 0 ? void 0 : _a["requestId"]) !== null && _b !== void 0 ? _b : p["id"]) === requestId;
74
+ });
75
+ if (at === -1)
76
+ return false;
77
+ return list.slice(at + 1).every((p) => {
78
+ var _a;
79
+ const kind = p !== null && typeof p === "object" ? p["type"] : undefined;
80
+ if (kind === "reasoning" || kind === "step-start")
81
+ return true;
82
+ return kind === "data-output" && ((_a = p["data"]) === null || _a === void 0 ? void 0 : _a["skipped"]) === "paused";
83
+ });
84
+ }
85
+ /** The `error` object of a chat_service error response, else null (not a chat_service error). */
86
+ async function chatError(err) {
87
+ try {
88
+ const error = (await err.response.clone().json()).error;
89
+ return error !== null && typeof error === "object" && !Array.isArray(error) ? error : null;
90
+ }
91
+ catch (_a) {
92
+ return null;
93
+ }
94
+ }
95
+ /** `error.details[0]` of a chat_service error, else {}. */
96
+ function firstDetail(error) {
97
+ const details = error === null || error === void 0 ? void 0 : error["details"];
98
+ const first = Array.isArray(details) ? details[0] : undefined;
99
+ return first !== null && typeof first === "object" && !Array.isArray(first) ? { ...first } : {};
100
+ }
101
+ function retryAfterMs(err) {
102
+ var _a;
103
+ const seconds = Number((_a = err.response.headers.get("retry-after")) !== null && _a !== void 0 ? _a : 2);
104
+ if (!Number.isFinite(seconds) || seconds < 0)
105
+ return 2000;
106
+ return Math.min(seconds, RETRY_AFTER_MAX) * 1000;
107
+ }
108
+ /** A refused POST .../tool-results as the SDK's error: RunError with the server's reason as `code`,
109
+ * NotSupportedByServerError(["functions"]) for a server without the route, else the ResponseError itself. */
110
+ async function refused(err, requestId) {
111
+ const status = err.response.status;
112
+ const error = await chatError(err);
113
+ const detail = firstDetail(error);
114
+ const why = typeof detail["reason"] === "string" ? detail["reason"] : null;
115
+ if (why !== null && Object.prototype.hasOwnProperty.call(REFUSALS, why)) {
116
+ let message = `function results for request ${requestId}: ${REFUSALS[why]}`;
117
+ if (why === "results_too_large" && detail["maxBytes"] !== undefined)
118
+ message += ` (${String(detail["maxBytes"])} bytes)`;
119
+ const ids = detail["toolCallIds"];
120
+ if (Array.isArray(ids) && ids.length > 0)
121
+ message += `: ${ids.map(String).join(", ")}`;
122
+ return new RunError(why, message, status, detail);
123
+ }
124
+ if (status === 404) {
125
+ if (error === null)
126
+ return new NotSupportedByServerError(["functions"]); // the framework's own 404: no route
127
+ return new RunError("not_found", `function results for request ${requestId}: no such conversation for this caller`, 404, detail);
128
+ }
129
+ return err;
130
+ }
131
+ /** The `Idempotency-Key` for answering `requestId`: the same for every post of it, from any process. */
132
+ export function idempotencyKey(requestId) {
133
+ return createHash("sha256").update(requestId, "utf8").digest("hex");
134
+ }
135
+ function sleep(ms, signal) {
136
+ return new Promise((resolve, reject) => {
137
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted)
138
+ return reject(signal.reason);
139
+ const timer = setTimeout(() => {
140
+ signal === null || signal === void 0 ? void 0 : signal.removeEventListener("abort", onAbort);
141
+ resolve();
142
+ }, ms);
143
+ const onAbort = () => {
144
+ clearTimeout(timer);
145
+ reject(signal === null || signal === void 0 ? void 0 : signal.reason);
146
+ };
147
+ signal === null || signal === void 0 ? void 0 : signal.addEventListener("abort", onAbort, { once: true });
148
+ });
149
+ }
150
+ /** A turn that has already ended, read back from its stored reply (`chunksFromUiMessage`). A replay: it holds the
151
+ * whole turn, the requests this run answered too. */
152
+ class Finished {
153
+ constructor(conversationId, chunks) {
154
+ this.conversationId = conversationId;
155
+ this.chunks = chunks;
156
+ this.responseId = null;
157
+ this.lastEventId = null;
158
+ this.replay = true;
159
+ }
160
+ async *[Symbol.asyncIterator]() {
161
+ for (const chunk of this.chunks) {
162
+ const event = fromUiChunk(chunk);
163
+ if (event !== null)
164
+ yield event;
165
+ }
166
+ }
167
+ close() { }
168
+ }
169
+ /** `settings` for a new agent's first write: no `webhooks` (the server checks them against the agent's bound
170
+ * credentials, and a new agent has none yet) and no `sdk_hash` (it covers the webhooks, so an agent left in this
171
+ * state would otherwise read as deployed and never get them). */
172
+ function withoutWebhooks(settings) {
173
+ const { webhooks: _webhooks, ...out } = settings;
174
+ const { sdk_hash: _hash, ...metadata } = settings["metadata"];
175
+ return { ...out, metadata };
176
+ }
11
177
  function isNotFound(err) {
12
178
  return err instanceof ResponseError && err.response.status === 404;
13
179
  }
14
180
  /** TurnStream over a streaming ResponseStream; ids are read live from the underlying stream. */
15
181
  class Stream {
16
- constructor(inner, conversationId) {
182
+ constructor(inner, conversationId,
183
+ /** Read without a cursor after a duplicate post: the server replays the turn from its start. */
184
+ replay = false) {
17
185
  this.inner = inner;
18
186
  this.conversationId = conversationId;
187
+ this.replay = replay;
19
188
  }
20
189
  get responseId() {
21
190
  return this.inner.responseId;
@@ -41,6 +210,7 @@ export class SettingsTransport {
41
210
  this.agents = new AgentsApi(config);
42
211
  this.conversations = new ConversationsApi(config);
43
212
  this.responses = new ResponsesApi(config);
213
+ this.customApis = new CustomAPIsApi(config);
44
214
  }
45
215
  // -- agents ---------------------------------------------------------------------------------------------
46
216
  async findAgents(sdkName) {
@@ -69,17 +239,24 @@ export class SettingsTransport {
69
239
  return this.remote(resource, await this.instructions(agentId));
70
240
  }
71
241
  async createAgent(agent) {
72
- var _a, _b;
242
+ var _a, _b, _c;
73
243
  const settings = agent.toSettings();
244
+ const webhooks = ((_a = settings["webhooks"]) !== null && _a !== void 0 ? _a : []);
245
+ // The server checks webhooks against the credentials bound to the agent, and a new agent has none: create it
246
+ // without them, bind the Custom APIs they name, then write the settings in full.
247
+ const { bind, unbound } = await this.webhookCredentials(webhooks);
74
248
  let resource;
75
249
  try {
76
250
  resource = await this.agents.createAgent({
77
- agentCreate: { name: agent.name, instructions: agent.instructions, settings },
251
+ agentCreate: {
252
+ name: agent.name, instructions: agent.instructions,
253
+ settings: webhooks.length > 0 ? withoutWebhooks(settings) : settings,
254
+ },
78
255
  });
79
256
  }
80
257
  catch (err) {
81
258
  // A 422 stored nothing, so there is no agent to delete.
82
- throw (_a = (await invalidSettings(err))) !== null && _a !== void 0 ? _a : err;
259
+ throw (_b = (await invalidSettings(err))) !== null && _b !== void 0 ? _b : err;
83
260
  }
84
261
  let envelope;
85
262
  let warnings;
@@ -94,7 +271,23 @@ export class SettingsTransport {
94
271
  throw new NotSupportedByServerError(["settings"]);
95
272
  throw err;
96
273
  }
274
+ if (webhooks.length > 0) {
275
+ for (const { path, name, customApiId } of bind)
276
+ await this.bind(resource.id, path, name, customApiId);
277
+ try {
278
+ envelope = await this.agents.putAgentSettings({ agentId: resource.id, body: settings });
279
+ }
280
+ catch (err) {
281
+ const invalid = await invalidSettings(err);
282
+ if (invalid === null)
283
+ throw err;
284
+ throw new UserError([invalid.message, ...unbound].join("; "), invalid.issues);
285
+ }
286
+ }
97
287
  warnings = checkWarnings(envelope, settings);
288
+ // Accepted unchecked (webhooks switched off): refused once they are on.
289
+ for (const sentence of unbound)
290
+ console.warn(`agent ${resource.id}: ${sentence}`);
98
291
  checkMetadata(envelope, agent);
99
292
  await this.agents.deployAgent({ agentId: resource.id });
100
293
  }
@@ -112,10 +305,67 @@ export class SettingsTransport {
112
305
  agentId: resource.id,
113
306
  name: agent.name,
114
307
  instructions: agent.instructions,
115
- settings: { ...((_b = envelope.settings) !== null && _b !== void 0 ? _b : {}) },
308
+ settings: { ...((_c = envelope.settings) !== null && _c !== void 0 ? _c : {}) },
116
309
  warnings,
117
310
  };
118
311
  }
312
+ /** The caller's Custom APIs the webhooks name, to bind to a new agent: one entry per name that matches exactly
313
+ * one, and a sentence per name that matches none or several (left to the server, which refuses it only when it
314
+ * checks credentials). */
315
+ async webhookCredentials(webhooks) {
316
+ const bind = [];
317
+ const unbound = [];
318
+ const seen = new Set();
319
+ for (const [i, hook] of webhooks.entries()) {
320
+ const name = hook.secret_credential;
321
+ if (seen.has(name))
322
+ continue;
323
+ seen.add(name);
324
+ const path = `webhooks.${i}.secret_credential`;
325
+ const ids = await this.customApiIds(name);
326
+ if (ids.length === 1) {
327
+ bind.push({ path, name, customApiId: ids[0] });
328
+ }
329
+ else if (ids.length === 0) {
330
+ unbound.push(`${path}: you have no Custom API named '${name}' to bind to the new agent; create it, then ` +
331
+ "deploy again");
332
+ }
333
+ else {
334
+ unbound.push(`${path}: ${ids.length} of your Custom APIs are named '${name}', so none was bound to the new ` +
335
+ "agent; rename or delete all but one, then deploy again");
336
+ }
337
+ }
338
+ return { bind, unbound };
339
+ }
340
+ /** The ids of the caller's own Custom APIs named exactly `name` (`q` also matches substrings and hosts). */
341
+ async customApiIds(name) {
342
+ const ids = [];
343
+ let offset = 0;
344
+ for (;;) {
345
+ const result = await this.customApis.listCustomApis({ q: name, limit: PAGE, offset });
346
+ const items = result.data;
347
+ for (const item of items)
348
+ if (item.name === name)
349
+ ids.push(item.id);
350
+ offset += items.length;
351
+ if (items.length === 0 || !result.hasMore)
352
+ return ids;
353
+ }
354
+ }
355
+ async bind(agentId, path, name, customApiId) {
356
+ var _a;
357
+ try {
358
+ await this.customApis.bindCustomApi({ agentId, bindCustomApiBody: { customApiId } });
359
+ }
360
+ catch (err) {
361
+ const status = err instanceof ResponseError ? err.response.status : 0;
362
+ if (!(err instanceof ResponseError) || status < 400 || status >= 500)
363
+ throw err;
364
+ const message = (_a = (await chatError(err))) === null || _a === void 0 ? void 0 : _a["message"];
365
+ throw new UserError(`${path}: could not bind the Custom API '${name}' to the new agent: ` +
366
+ (typeof message === "string" && message ? message : `HTTP ${status}`));
367
+ }
368
+ }
119
369
  async updateAgent(agentId, agent) {
120
370
  var _a, _b;
121
371
  const settings = agent.toSettings();
@@ -188,7 +438,18 @@ export class SettingsTransport {
188
438
  agentId,
189
439
  message: { id: randomUUID(), role: "user", parts: [{ type: "text", text }] },
190
440
  };
191
- return new Stream(await streamResponse(this.config, body, { signal }), conversationId);
441
+ let inner;
442
+ try {
443
+ inner = await streamResponse(this.config, body, { signal });
444
+ }
445
+ catch (err) {
446
+ if ((await reason(err, 409)) === "function_call_pending") {
447
+ throw new RunError("function_call_pending", "the conversation is waiting on function results from an earlier " +
448
+ "run; continue it with run(agent, await RunState.fromSession(conversationId))");
449
+ }
450
+ throw err;
451
+ }
452
+ return new Stream(inner, conversationId);
192
453
  }
193
454
  async answerClarify(conversationId, requestId, answers, signal) {
194
455
  const inner = await answerClarify(this.config, conversationId, { requestId, answers }, { signal });
@@ -201,6 +462,126 @@ export class SettingsTransport {
201
462
  async stop(conversationId) {
202
463
  await this.responses.stopResponse({ conversationId });
203
464
  }
465
+ async postFunctionResults(conversationId, requestId, results, signal) {
466
+ const body = {
467
+ requestId,
468
+ results: results.map((r) => ({ toolCallId: r.callId, output: r.output, isError: r.isError })),
469
+ };
470
+ const key = idempotencyKey(requestId);
471
+ let inner;
472
+ let busy = 0;
473
+ let unavailable = 0;
474
+ let lost = 0;
475
+ for (;;) {
476
+ try {
477
+ inner = await postToolResults(this.config, conversationId, body, { signal, idempotencyKey: key });
478
+ break;
479
+ }
480
+ catch (err) {
481
+ if (isLostPost(err, signal)) {
482
+ // The server may have stored the results before the connection broke: the same key makes a retry safe,
483
+ // and a stored post comes back as a duplicate.
484
+ if (lost >= LOST_POST_RETRIES) {
485
+ const why = err instanceof Error ? `${err.name}: ${err.message}` : String(err);
486
+ throw new RunError("stream_lost", `function results for request ${requestId} got no answer after ${lost + 1} tries (${why})`);
487
+ }
488
+ await sleep(250 * 2 ** lost, signal);
489
+ lost += 1;
490
+ continue;
491
+ }
492
+ if (!(err instanceof ResponseError))
493
+ throw err;
494
+ const status = err.response.status;
495
+ const why = status === 409 ? firstDetail(await chatError(err))["reason"] : undefined;
496
+ if (why === "in_progress") {
497
+ // The first post with this key is still being delivered; answered only while the request is the open
498
+ // pause, so the same post is safe to repeat.
499
+ if (busy >= IN_PROGRESS_RETRIES) {
500
+ throw new RunError(why, `function results for request ${requestId} were still being delivered after ` +
501
+ `${busy + 1} tries`, 409, firstDetail(await chatError(err)));
502
+ }
503
+ await sleep(retryAfterMs(err), signal);
504
+ busy += 1;
505
+ continue;
506
+ }
507
+ if (status === 503) {
508
+ // Not delivered and nothing kept, but the agent may have them: the same key and results again.
509
+ if (unavailable >= UNAVAILABLE_RETRIES) {
510
+ throw new RunError("unavailable", `function results for request ${requestId} could not be delivered to ` +
511
+ `the agent after ${unavailable + 1} tries`, 503, firstDetail(await chatError(err)));
512
+ }
513
+ await sleep(retryAfterMs(err), signal);
514
+ unavailable += 1;
515
+ continue;
516
+ }
517
+ if (status === 409 && typeof why === "string" && Object.prototype.hasOwnProperty.call(WENT_ON, why)) {
518
+ console.warn(`function results for request ${requestId} were not taken (409 ${why}): ${WENT_ON[why]}; ` +
519
+ "following the turn");
520
+ return this.followAfter(conversationId, requestId, why, signal);
521
+ }
522
+ throw await refused(err, requestId);
523
+ }
524
+ }
525
+ if (!inner.duplicate)
526
+ return new Stream(inner, conversationId);
527
+ // The server already had these results (an earlier post, ours or another process's, got through).
528
+ return this.follow(conversationId, signal);
529
+ }
530
+ /** The turn after a request someone already answered, as a replay of it from its start (the run skips up to the
531
+ * answered request): the running response by reconnecting without a cursor, else the conversation's last reply
532
+ * as stored. A turn that paused again ends on its new request, unanswered. */
533
+ async follow(conversationId, signal) {
534
+ return this.followAfter(conversationId, null, null, signal);
535
+ }
536
+ /** `follow`, after a 409 expired / already_answered for `requestId`: a turn not yet picked up again (no active
537
+ * response, and the last reply still ends on that request) is read again every second, up to 30 times; then
538
+ * RunError(reason). An abort ends the wait. */
539
+ async followAfter(conversationId, requestId, why, signal) {
540
+ var _a;
541
+ for (let polls = 0;; polls++) {
542
+ // Read raw: the stored parts are passed through as they are, not through the generated models.
543
+ const raw = await this.conversations.getConversationRaw({ conversationId }, { signal });
544
+ const detail = await raw.raw.json();
545
+ const body = (detail !== null && typeof detail === "object" ? detail : {});
546
+ const responseId = body["activeResponseId"];
547
+ if (typeof responseId === "string" && responseId) {
548
+ return new Stream(await reconnect(this.config, conversationId, responseId, null, { signal }), conversationId, true);
549
+ }
550
+ const messages = Array.isArray(body["messages"]) ? body["messages"] : [];
551
+ const last = [...messages].reverse().find((m) => m !== null && typeof m === "object"
552
+ && m["role"] === "assistant");
553
+ if (requestId === null || !waitsOn(last, requestId)) {
554
+ return new Finished(conversationId, chunksFromUiMessage(last !== null && last !== void 0 ? last : null));
555
+ }
556
+ if (polls >= FOLLOW_POLLS) {
557
+ const code = why !== null && why !== void 0 ? why : "expired";
558
+ throw new RunError(code, `function results for request ${requestId}: ${(_a = WENT_ON[code]) !== null && _a !== void 0 ? _a : code}, but the turn ` +
559
+ `has not gone on after ${polls} reads; read the conversation later`, 409, { reason: code });
560
+ }
561
+ await sleep(followPollMs.value, signal);
562
+ }
563
+ }
564
+ async pending(conversationId) {
565
+ var _a, _b, _c;
566
+ const detail = await this.conversations.getConversation({ conversationId });
567
+ const grouped = new Map();
568
+ for (const action of (_a = detail.requiredActions) !== null && _a !== void 0 ? _a : []) {
569
+ if (((_b = action.type) !== null && _b !== void 0 ? _b : "function_call") !== "function_call")
570
+ continue;
571
+ let request = grouped.get(action.requestId);
572
+ if (request === undefined) {
573
+ request = { requestId: action.requestId, calls: [] };
574
+ const expires = action.expiresAt;
575
+ if (expires instanceof Date)
576
+ request.expiresAt = expires.toISOString();
577
+ else if (typeof expires === "string")
578
+ request.expiresAt = expires;
579
+ grouped.set(action.requestId, request);
580
+ }
581
+ request.calls.push({ callId: action.toolCallId, name: action.name, arguments: { ...((_c = action.arguments) !== null && _c !== void 0 ? _c : {}) } });
582
+ }
583
+ return Array.from(grouped.values());
584
+ }
204
585
  // -- helpers --------------------------------------------------------------------------------------------
205
586
  /** Put back what updateAgent overwrote; a failing restore must not mask the original error. */
206
587
  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
  }
@@ -0,0 +1,19 @@
1
+ import type { WebhookEventType } from "../webhooks.js";
2
+ /** Where the agent reports a finished, failed or paused turn (agent.json `webhooks[]`). */
3
+ export interface Webhook {
4
+ /** An `https://` URL on port 443 with a DNS host; a query string is allowed. */
5
+ url: string;
6
+ /** 1 to 4 distinct events. `approval.requested` is reserved: accepted, not sent yet. */
7
+ events: WebhookEventType[];
8
+ /** The vault credential holding the `whsec_` signing secret (agent.json `secret_credential`). */
9
+ secretCredential: string;
10
+ }
11
+ export declare const WEBHOOKS_MAX = 5;
12
+ /** Why `url` is not an allowed webhook URL, or null. Every URL the server refuses is refused, with the server's
13
+ * sentence for every URL Python's `urlsplit` parses; for a netloc its NFKC check refuses, the sentence may differ. */
14
+ export declare function urlProblem(url: string): string | null;
15
+ /** The server's pure `webhooks` rules (types first); throws `UserError` naming the agent.json path. */
16
+ export declare function checkWebhooks(webhooks: unknown): void;
17
+ /** Only the three fields, in agent.json's names (a copy). */
18
+ export declare function copyWebhooks(webhooks: readonly Webhook[]): Webhook[];
19
+ export declare function webhooksJson(webhooks: readonly Webhook[]): Record<string, unknown>[];