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