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
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ /* tslint:disable */
3
+ /* eslint-disable */
4
+ /**
5
+ * Sarvam Agents API
6
+ * 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.
7
+ *
8
+ * The version of the OpenAPI document: 0.1.0
9
+ * Contact: support@sarvam.ai
10
+ *
11
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
12
+ * https://openapi-generator.tech
13
+ * Do not edit the class manually.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.instanceOfToolResultsBody = instanceOfToolResultsBody;
17
+ exports.ToolResultsBodyFromJSON = ToolResultsBodyFromJSON;
18
+ exports.ToolResultsBodyFromJSONTyped = ToolResultsBodyFromJSONTyped;
19
+ exports.ToolResultsBodyToJSON = ToolResultsBodyToJSON;
20
+ exports.ToolResultsBodyToJSONTyped = ToolResultsBodyToJSONTyped;
21
+ const FunctionResultBody_js_1 = require("./FunctionResultBody.js");
22
+ /**
23
+ * Check if a given object implements the ToolResultsBody interface.
24
+ */
25
+ function instanceOfToolResultsBody(value) {
26
+ if (!('requestId' in value) || value['requestId'] === undefined)
27
+ return false;
28
+ if (!('results' in value) || value['results'] === undefined)
29
+ return false;
30
+ return true;
31
+ }
32
+ function ToolResultsBodyFromJSON(json) {
33
+ return ToolResultsBodyFromJSONTyped(json, false);
34
+ }
35
+ function ToolResultsBodyFromJSONTyped(json, ignoreDiscriminator) {
36
+ if (json == null) {
37
+ return json;
38
+ }
39
+ return {
40
+ 'requestId': json['requestId'],
41
+ 'results': (json['results'].map(FunctionResultBody_js_1.FunctionResultBodyFromJSON)),
42
+ };
43
+ }
44
+ function ToolResultsBodyToJSON(json) {
45
+ return ToolResultsBodyToJSONTyped(json, false);
46
+ }
47
+ function ToolResultsBodyToJSONTyped(value, ignoreDiscriminator = false) {
48
+ if (value == null) {
49
+ return value;
50
+ }
51
+ return {
52
+ 'requestId': value['requestId'],
53
+ 'results': (value['results'].map(FunctionResultBody_js_1.FunctionResultBodyToJSON)),
54
+ };
55
+ }
@@ -99,6 +99,7 @@ export * from './FileQueuedResponse.js';
99
99
  export * from './FileRawResponse.js';
100
100
  export * from './FileRead.js';
101
101
  export * from './FileWriteBody.js';
102
+ export * from './FunctionResultBody.js';
102
103
  export * from './HTTPValidationError.js';
103
104
  export * from './HighlightRange.js';
104
105
  export * from './InlineCreateSkillBody.js';
@@ -129,6 +130,7 @@ export * from './QueueMessageInput.js';
129
130
  export * from './QueueMessageResult.js';
130
131
  export * from './QueuedTurnView.js';
131
132
  export * from './Reason.js';
133
+ export * from './RequiredAction.js';
132
134
  export * from './Requiredscope.js';
133
135
  export * from './Resourcetype.js';
134
136
  export * from './ResponseCompleteFileUpload.js';
@@ -152,6 +154,8 @@ export * from './StopResponse.js';
152
154
  export * from './TemplateConnectorTag.js';
153
155
  export * from './TemplateWorksWith.js';
154
156
  export * from './TextPart.js';
157
+ export * from './ToolResults200Response.js';
158
+ export * from './ToolResultsBody.js';
155
159
  export * from './TriggerCronBody.js';
156
160
  export * from './TriggerResponse.js';
157
161
  export * from './UIMessage.js';
@@ -117,6 +117,7 @@ __exportStar(require("./FileQueuedResponse.js"), exports);
117
117
  __exportStar(require("./FileRawResponse.js"), exports);
118
118
  __exportStar(require("./FileRead.js"), exports);
119
119
  __exportStar(require("./FileWriteBody.js"), exports);
120
+ __exportStar(require("./FunctionResultBody.js"), exports);
120
121
  __exportStar(require("./HTTPValidationError.js"), exports);
121
122
  __exportStar(require("./HighlightRange.js"), exports);
122
123
  __exportStar(require("./InlineCreateSkillBody.js"), exports);
@@ -147,6 +148,7 @@ __exportStar(require("./QueueMessageInput.js"), exports);
147
148
  __exportStar(require("./QueueMessageResult.js"), exports);
148
149
  __exportStar(require("./QueuedTurnView.js"), exports);
149
150
  __exportStar(require("./Reason.js"), exports);
151
+ __exportStar(require("./RequiredAction.js"), exports);
150
152
  __exportStar(require("./Requiredscope.js"), exports);
151
153
  __exportStar(require("./Resourcetype.js"), exports);
152
154
  __exportStar(require("./ResponseCompleteFileUpload.js"), exports);
@@ -170,6 +172,8 @@ __exportStar(require("./StopResponse.js"), exports);
170
172
  __exportStar(require("./TemplateConnectorTag.js"), exports);
171
173
  __exportStar(require("./TemplateWorksWith.js"), exports);
172
174
  __exportStar(require("./TextPart.js"), exports);
175
+ __exportStar(require("./ToolResults200Response.js"), exports);
176
+ __exportStar(require("./ToolResultsBody.js"), exports);
173
177
  __exportStar(require("./TriggerCronBody.js"), exports);
174
178
  __exportStar(require("./TriggerResponse.js"), exports);
175
179
  __exportStar(require("./UIMessage.js"), exports);
@@ -14,10 +14,10 @@
14
14
  * const again = await reconnect(config, conversationId, stream.responseId!, stream.lastEventId);
15
15
  *
16
16
  * Each item is the event's JSON payload (`type` is `start`, `text-delta`, `data-file-shared`,
17
- * `data-clarify-request`, `data-stopped`, `error`, `finish`, ...). The stream keeps `lastEventId` and `responseId`
17
+ * `data-clarify-request`, `data-function-call-request`, `data-stopped`, `error`, `finish`, ...). The stream keeps `lastEventId` and `responseId`
18
18
  * up to date, the two values `reconnect` needs.
19
19
  */
20
- import type { ClarifyBody, ResponseInput } from "./models/index.js";
20
+ import type { ClarifyBody, ResponseInput, ToolResultsBody } from "./models/index.js";
21
21
  import type { Configuration } from "./runtime.js";
22
22
  /** One event's JSON payload. */
23
23
  export interface StreamEvent {
@@ -40,6 +40,9 @@ export declare function iterSse(chunks: AsyncIterable<Uint8Array>): AsyncGenerat
40
40
  export declare class ResponseStream implements AsyncIterable<StreamEvent> {
41
41
  responseId: string | null;
42
42
  lastEventId: string | null;
43
+ /** `postToolResults` only: the server already had these results (a repeat with the same idempotency key), so
44
+ * this stream is empty; follow the turn with `reconnect`. */
45
+ duplicate: boolean;
43
46
  private readonly body;
44
47
  private readonly controller;
45
48
  private readonly idleTimeoutMs;
@@ -66,3 +69,12 @@ export declare function reconnect(config: Configuration, conversationId: string,
66
69
  * `body.requestId` comes from that event; put your answers in `body.answers`.
67
70
  */
68
71
  export declare function answerClarify(config: Configuration, conversationId: string, body: ClarifyBody, options?: StreamOptions): Promise<ResponseStream>;
72
+ /**
73
+ * Answer the agent's function calls (a `data-function-call-request` event) and stream the rest of the reply.
74
+ * `body.requestId` comes from that event, with one result per call. Send the same `idempotencyKey` when you retry a
75
+ * post: a repeat the server already has resolves to an empty stream with `duplicate` set, and the turn can be followed
76
+ * with `reconnect`.
77
+ */
78
+ export declare function postToolResults(config: Configuration, conversationId: string, body: ToolResultsBody, options?: StreamOptions & {
79
+ idempotencyKey?: string;
80
+ }): Promise<ResponseStream>;
package/dist/streaming.js CHANGED
@@ -15,7 +15,7 @@
15
15
  * const again = await reconnect(config, conversationId, stream.responseId!, stream.lastEventId);
16
16
  *
17
17
  * Each item is the event's JSON payload (`type` is `start`, `text-delta`, `data-file-shared`,
18
- * `data-clarify-request`, `data-stopped`, `error`, `finish`, ...). The stream keeps `lastEventId` and `responseId`
18
+ * `data-clarify-request`, `data-function-call-request`, `data-stopped`, `error`, `finish`, ...). The stream keeps `lastEventId` and `responseId`
19
19
  * up to date, the two values `reconnect` needs.
20
20
  */
21
21
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -24,7 +24,9 @@ exports.iterSse = iterSse;
24
24
  exports.streamResponse = streamResponse;
25
25
  exports.reconnect = reconnect;
26
26
  exports.answerClarify = answerClarify;
27
+ exports.postToolResults = postToolResults;
27
28
  const ClarifyApi_js_1 = require("./apis/ClarifyApi.js");
29
+ const FunctionToolsApi_js_1 = require("./apis/FunctionToolsApi.js");
28
30
  const ResponsesApi_js_1 = require("./apis/ResponsesApi.js");
29
31
  exports.DEFAULT_IDLE_TIMEOUT_MS = 60000;
30
32
  /** Parse a server-sent-events body into [last event id, payload] pairs. */
@@ -84,6 +86,9 @@ async function* iterSse(chunks) {
84
86
  /** Async iterator over a reply's events. Call `close()` if you stop early. */
85
87
  class ResponseStream {
86
88
  constructor(body, controller, idleTimeoutMs, responseId = null, lastEventId = null) {
89
+ /** `postToolResults` only: the server already had these results (a repeat with the same idempotency key), so
90
+ * this stream is empty; follow the turn with `reconnect`. */
91
+ this.duplicate = false;
87
92
  this.body = body;
88
93
  this.controller = controller;
89
94
  this.idleTimeoutMs = idleTimeoutMs;
@@ -146,15 +151,24 @@ class ResponseStream {
146
151
  }
147
152
  }
148
153
  exports.ResponseStream = ResponseStream;
149
- async function open(call, options, responseId = null, lastEventId = null) {
150
- var _a, _b;
154
+ async function open(call, options, responseId = null, lastEventId = null, jsonIsDuplicate = false) {
155
+ var _a, _b, _c, _d, _e;
151
156
  const controller = new AbortController();
152
157
  (_a = options.signal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", () => controller.abort(options.signal.reason), { once: true });
153
158
  // Non-2xx responses throw ResponseError here, like every other generated method.
154
159
  const response = await call({ signal: controller.signal });
160
+ const contentType = ((_b = response.raw.headers.get("content-type")) !== null && _b !== void 0 ? _b : "").split(";")[0].trim().toLowerCase();
161
+ if (jsonIsDuplicate && contentType === "application/json") {
162
+ await ((_c = response.raw.body) === null || _c === void 0 ? void 0 : _c.cancel().catch(() => undefined));
163
+ const empty = new ReadableStream({ start: (c) => c.close() });
164
+ const stream = new ResponseStream(empty, controller, (_d = options.idleTimeoutMs) !== null && _d !== void 0 ? _d : exports.DEFAULT_IDLE_TIMEOUT_MS);
165
+ stream.duplicate = true;
166
+ stream.close();
167
+ return stream;
168
+ }
155
169
  if (!response.raw.body)
156
170
  throw new Error("response has no body to stream");
157
- return new ResponseStream(response.raw.body, controller, (_b = options.idleTimeoutMs) !== null && _b !== void 0 ? _b : exports.DEFAULT_IDLE_TIMEOUT_MS, responseId, lastEventId);
171
+ return new ResponseStream(response.raw.body, controller, (_e = options.idleTimeoutMs) !== null && _e !== void 0 ? _e : exports.DEFAULT_IDLE_TIMEOUT_MS, responseId, lastEventId);
158
172
  }
159
173
  /** Send a message (POST /v1/responses) and stream the reply. Same body as `ResponsesApi.createResponse`. */
160
174
  function streamResponse(config, body, options = {}) {
@@ -177,3 +191,12 @@ function reconnect(config, conversationId, responseId, lastEventId = null, optio
177
191
  function answerClarify(config, conversationId, body, options = {}) {
178
192
  return open((init) => new ClarifyApi_js_1.ClarifyApi(config).clarifyRaw({ conversationId, clarifyBody: body }, init), options);
179
193
  }
194
+ /**
195
+ * Answer the agent's function calls (a `data-function-call-request` event) and stream the rest of the reply.
196
+ * `body.requestId` comes from that event, with one result per call. Send the same `idempotencyKey` when you retry a
197
+ * post: a repeat the server already has resolves to an empty stream with `duplicate` set, and the turn can be followed
198
+ * with `reconnect`.
199
+ */
200
+ function postToolResults(config, conversationId, body, options = {}) {
201
+ return open((init) => new FunctionToolsApi_js_1.FunctionToolsApi(config).toolResultsRaw({ conversationId, toolResultsBody: body, idempotencyKey: options.idempotencyKey }, init), options, null, null, true);
202
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sarvam-agents-client",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Client for the Sarvam Agents API: chat with an agent, exchange files with it, and set it up from your own code.",
5
5
  "author": "Sarvam AI <support@sarvam.ai>",
6
6
  "license": "MIT",
@@ -0,0 +1,102 @@
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
+
16
+ import * as runtime from '../runtime.js';
17
+ import type {
18
+ ChatError,
19
+ ListModels403Response,
20
+ ToolResults200Response,
21
+ ToolResultsBody,
22
+ } from '../models/index.js';
23
+ import {
24
+ ChatErrorFromJSON,
25
+ ChatErrorToJSON,
26
+ ListModels403ResponseFromJSON,
27
+ ListModels403ResponseToJSON,
28
+ ToolResults200ResponseFromJSON,
29
+ ToolResults200ResponseToJSON,
30
+ ToolResultsBodyFromJSON,
31
+ ToolResultsBodyToJSON,
32
+ } from '../models/index.js';
33
+
34
+ export interface ToolResultsRequest {
35
+ conversationId: string;
36
+ toolResultsBody: ToolResultsBody;
37
+ idempotencyKey?: string | null;
38
+ }
39
+
40
+ /**
41
+ *
42
+ */
43
+ export class FunctionToolsApi extends runtime.BaseAPI {
44
+
45
+ /**
46
+ * Answer a paused turn\'s function calls and stream its continuation.
47
+ * Tool Results Route
48
+ */
49
+ async toolResultsRaw(requestParameters: ToolResultsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<ToolResults200Response>> {
50
+ if (requestParameters['conversationId'] == null) {
51
+ throw new runtime.RequiredError(
52
+ 'conversationId',
53
+ 'Required parameter "conversationId" was null or undefined when calling toolResults().'
54
+ );
55
+ }
56
+
57
+ if (requestParameters['toolResultsBody'] == null) {
58
+ throw new runtime.RequiredError(
59
+ 'toolResultsBody',
60
+ 'Required parameter "toolResultsBody" was null or undefined when calling toolResults().'
61
+ );
62
+ }
63
+
64
+ const queryParameters: any = {};
65
+
66
+ const headerParameters: runtime.HTTPHeaders = {};
67
+
68
+ headerParameters['Content-Type'] = 'application/json';
69
+
70
+ if (requestParameters['idempotencyKey'] != null) {
71
+ headerParameters['Idempotency-Key'] = String(requestParameters['idempotencyKey']);
72
+ }
73
+
74
+ if (this.configuration && this.configuration.accessToken) {
75
+ const token = this.configuration.accessToken;
76
+ const tokenString = await token("bearerAuth", []);
77
+
78
+ if (tokenString) {
79
+ headerParameters["Authorization"] = `Bearer ${tokenString}`;
80
+ }
81
+ }
82
+ const response = await this.request({
83
+ path: `/v1/conversations/{conversationId}/tool-results`.replace(`{${"conversationId"}}`, runtime.encodePathParam('conversationId', requestParameters['conversationId'])),
84
+ method: 'POST',
85
+ headers: headerParameters,
86
+ query: queryParameters,
87
+ body: ToolResultsBodyToJSON(requestParameters['toolResultsBody']),
88
+ }, initOverrides);
89
+
90
+ return new runtime.JSONApiResponse(response, (jsonValue) => ToolResults200ResponseFromJSON(jsonValue));
91
+ }
92
+
93
+ /**
94
+ * Answer a paused turn\'s function calls and stream its continuation.
95
+ * Tool Results Route
96
+ */
97
+ async toolResults(requestParameters: ToolResultsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<ToolResults200Response> {
98
+ const response = await this.toolResultsRaw(requestParameters, initOverrides);
99
+ return await response.value();
100
+ }
101
+
102
+ }
package/src/apis/index.ts CHANGED
@@ -9,6 +9,7 @@ export * from './CollectionsApi.js';
9
9
  export * from './ConversationsApi.js';
10
10
  export * from './CronsApi.js';
11
11
  export * from './CustomAPIsApi.js';
12
+ export * from './FunctionToolsApi.js';
12
13
  export * from './MessagesApi.js';
13
14
  export * from './ModelsApi.js';
14
15
  export * from './QueueApi.js';
@@ -2,6 +2,11 @@ import { NotSupportedError, UserError } from "./errors.js";
2
2
  import { settingsFingerprint } from "./fingerprint.js";
3
3
  import { BUILTIN_NAMES, checkWebSearchOptions } from "./builtins.js";
4
4
  import { BuiltinTool } from "./tools.js";
5
+ import {
6
+ DEFAULT_FUNCTION_TIMEOUT_SECONDS, FUNCTION_TIMEOUT_RANGE, FUNCTIONS_MAX, FUNCTIONS_TOTAL_MAX_BYTES, compactBytes,
7
+ functionToolSettings, isBuiltFunctionTool, isFunctionTool, tool,
8
+ } from "./functionTool.js";
9
+ import type { FunctionTool, FunctionToolOptions } from "./functionTool.js";
5
10
  import { checkOutputType, outputSchema } from "./output.js";
6
11
  import type { OutputType } from "./output.js";
7
12
 
@@ -23,6 +28,9 @@ export interface Limits {
23
28
  maxTokensPerTurn?: number;
24
29
  }
25
30
 
31
+ /** An entry of `Agent` `tools`: a built-in (`sandbox()`, `webSearchTool()`, ...) or a function tool (`tool()`). */
32
+ export type AgentTool = BuiltinTool | FunctionTool;
33
+
26
34
  export interface AgentOptions<TOutput extends OutputType | undefined = undefined> {
27
35
  name: string;
28
36
  instructions?: string;
@@ -31,8 +39,11 @@ export interface AgentOptions<TOutput extends OutputType | undefined = undefined
31
39
  endpoint?: string;
32
40
  modelSettings?: ModelSettings;
33
41
  fallbackModels?: string[];
34
- /** Exact list of built-ins to keep on; omit to keep the server default (all on). */
35
- tools?: BuiltinTool[];
42
+ /** Exact list of what the agent may use: built-ins (the unlisted ones are turned off) and function tools (agent.json
43
+ * `functions`). Omit to keep the server default (every built-in on, no functions). */
44
+ tools?: AgentTool[];
45
+ /** Seconds (10 to 3000, default 600) the server waits for this process to answer a function call (`function_timeout_seconds`). */
46
+ functionTimeoutSeconds?: number;
36
47
  limits?: Limits;
37
48
  metadata?: Record<string, string>;
38
49
  /** The shape of the final answer: `{ type: "json_schema", schema }` or a zod schema. `finalOutput` follows it. */
@@ -118,7 +129,9 @@ export class Agent<TOutput extends OutputType | undefined = undefined> {
118
129
  readonly endpoint?: string;
119
130
  readonly modelSettings?: ModelSettings;
120
131
  readonly fallbackModels?: string[];
121
- readonly tools?: readonly BuiltinTool[];
132
+ /** Built-ins and function tools, in the order given. */
133
+ readonly tools?: readonly AgentTool[];
134
+ readonly functionTimeoutSeconds?: number;
122
135
  readonly limits?: Limits;
123
136
  readonly metadata?: Record<string, string>;
124
137
  /** Kept by reference and not frozen: a zod schema must stay usable. Non-enumerable, so deepFreeze skips it. */
@@ -126,10 +139,18 @@ export class Agent<TOutput extends OutputType | undefined = undefined> {
126
139
 
127
140
  constructor(rawOpts: AgentOptions<TOutput>) {
128
141
  const opts = normalize(rawOpts);
129
- for (const tool of opts.tools ?? []) {
142
+ for (const tool of (opts.tools ?? []) as unknown[]) {
130
143
  if (tool instanceof Agent) {
131
144
  throw new NotSupportedError("sub-agents in tools are not supported yet (field: tools)");
132
145
  }
146
+ if (typeof tool === "function") {
147
+ throw new UserError(`tools: ${tool.name || "a function"} is not a tool; wrap it with tool({ name, description, ` +
148
+ "parameters, execute })");
149
+ }
150
+ if (tool === null || typeof tool !== "object" || Array.isArray(tool)) {
151
+ throw new UserError(`tools: ${JSON.stringify(tool)} is not a tool; list built-ins (sandbox(), webSearchTool(), ...) ` +
152
+ "and tool() function tools");
153
+ }
133
154
  }
134
155
  checkNumbers(opts);
135
156
  this.name = opts.name;
@@ -138,7 +159,15 @@ export class Agent<TOutput extends OutputType | undefined = undefined> {
138
159
  this.endpoint = opts.endpoint;
139
160
  this.modelSettings = clone(opts.modelSettings);
140
161
  this.fallbackModels = clone(opts.fallbackModels);
141
- this.tools = clone(opts.tools);
162
+ // A function tool is kept by reference (it holds execute and maybe a zod schema); an object literal of that shape
163
+ // goes through tool().
164
+ this.tools = opts.tools === undefined ? undefined
165
+ : opts.tools.map((t): AgentTool => {
166
+ if (isBuiltFunctionTool(t)) return t;
167
+ if (isFunctionTool(t)) return tool(t as unknown as FunctionToolOptions);
168
+ return clone(t);
169
+ });
170
+ this.functionTimeoutSeconds = opts.functionTimeoutSeconds;
142
171
  this.limits = clone(opts.limits);
143
172
  this.metadata = clone(opts.metadata);
144
173
  Object.defineProperty(this, "outputType", { value: opts.outputType, enumerable: false, writable: false });
@@ -196,7 +225,7 @@ export class Agent<TOutput extends OutputType | undefined = undefined> {
196
225
  throw new UserError(`metadata: keys starting with 'sdk_' are reserved (${bad.join(", ")})`);
197
226
  }
198
227
  }
199
- const names = (this.tools ?? []).map((t) => t.name);
228
+ const names = this.builtinTools.map((t) => t.name);
200
229
  for (const n of names) {
201
230
  if ((BUILTIN_NAMES as readonly string[]).indexOf(n) === -1) {
202
231
  throw new UserError(`tools: unknown built-in tool ${JSON.stringify(n)} (known: ${BUILTIN_NAMES.join(", ")})`);
@@ -206,7 +235,7 @@ export class Agent<TOutput extends OutputType | undefined = undefined> {
206
235
  if (dupes.length > 0) {
207
236
  throw new UserError(`tools: duplicate built-in tool(s): ${dupes.join(", ")}`);
208
237
  }
209
- for (const t of this.tools ?? []) {
238
+ for (const t of this.builtinTools) {
210
239
  if (t.options === undefined || Object.keys(t.options).length === 0) continue;
211
240
  if (t.name !== "web_search") throw new UserError(`tools: ${t.name} takes no options`);
212
241
  checkWebSearchOptions(t.options);
@@ -214,6 +243,49 @@ export class Agent<TOutput extends OutputType | undefined = undefined> {
214
243
  if (names.indexOf("code_mode") !== -1 && names.indexOf("sandbox") === -1) {
215
244
  throw new UserError("tools: codeMode needs sandbox; add sandbox() to tools");
216
245
  }
246
+ this.checkFunctions();
247
+ }
248
+
249
+ private checkFunctions(): void {
250
+ const functions = this.functionTools;
251
+ if (functions.length > FUNCTIONS_MAX) {
252
+ throw new UserError(`tools: at most ${FUNCTIONS_MAX} function tools (got ${functions.length})`);
253
+ }
254
+ const names = functions.map((t) => t.name);
255
+ const dupes = Array.from(new Set(names.filter((n, i) => names.indexOf(n) !== i))).sort();
256
+ if (dupes.length > 0) throw new UserError(`tools: duplicate function tool(s): ${dupes.join(", ")}`);
257
+ const total = functions.reduce((sum, t) => sum + compactBytes(functionToolSettings(t)), 0);
258
+ if (total > FUNCTIONS_TOTAL_MAX_BYTES) {
259
+ throw new UserError(`tools: function tools are ${Math.ceil(total / 1024)} KB together (names, descriptions and ` +
260
+ "parameters); the server allows 64 KB, because every model call carries them");
261
+ }
262
+ const timeout = this.functionTimeoutSeconds;
263
+ if (timeout !== undefined) {
264
+ const [low, high] = FUNCTION_TIMEOUT_RANGE;
265
+ if (typeof timeout !== "number" || !Number.isInteger(timeout) || timeout < low || timeout > high) {
266
+ throw new UserError(`functionTimeoutSeconds: must be a whole number of seconds from ${low} to ${high}`);
267
+ }
268
+ }
269
+ // A call still running when the server's deadline passes is answered too late (409 expired) and the run fails;
270
+ // one that times out here first goes to the model as a failed result in time.
271
+ const deadline = timeout ?? DEFAULT_FUNCTION_TIMEOUT_SECONDS;
272
+ for (const t of functions) {
273
+ if (t.timeoutMs >= deadline * 1000) {
274
+ throw new UserError(`${t.name}: timeoutMs=${t.timeoutMs} (${t.timeoutMs / 1000}s) must be shorter than the ` +
275
+ `agent's functionTimeoutSeconds (${deadline}s${timeout === undefined ? ", the server default" : ""}); ` +
276
+ "lower the tool's timeoutMs or raise functionTimeoutSeconds");
277
+ }
278
+ }
279
+ }
280
+
281
+ /** The built-in tools in `tools`, in order. */
282
+ get builtinTools(): readonly BuiltinTool[] {
283
+ return (this.tools ?? []).filter((t) => !isFunctionTool(t)) as BuiltinTool[];
284
+ }
285
+
286
+ /** The function tools in `tools`, in order. */
287
+ get functionTools(): readonly FunctionTool[] {
288
+ return (this.tools ?? []).filter(isFunctionTool);
217
289
  }
218
290
 
219
291
  private baseSettings(): Record<string, unknown> {
@@ -240,15 +312,21 @@ export class Agent<TOutput extends OutputType | undefined = undefined> {
240
312
  if (Object.keys(limits).length > 0) out["limits"] = limits;
241
313
  }
242
314
  if (this.tools !== undefined) {
243
- // Built-ins are on by default, so an exact list writes every unlisted one as off.
315
+ // Built-ins are on by default, so an exact list writes every unlisted one as off (function tools included:
316
+ // tools: [tool(...)] means that function and no built-in).
317
+ const builtins = this.builtinTools;
244
318
  const tools: Record<string, unknown> = {};
245
319
  for (const n of BUILTIN_NAMES) {
246
- const t = this.tools.find((x) => x.name === n);
320
+ const t = builtins.find((x) => x.name === n);
247
321
  tools[n] = t === undefined ? false
248
322
  : t.options !== undefined && Object.keys(t.options).length > 0 ? clone(t.options) : true;
249
323
  }
250
324
  out["builtin_tools"] = tools;
325
+ // Never an empty list: that would change every existing agent's fingerprint.
326
+ const functions = this.functionTools;
327
+ if (functions.length > 0) out["functions"] = functions.map(functionToolSettings);
251
328
  }
329
+ if (this.functionTimeoutSeconds !== undefined) out["function_timeout_seconds"] = this.functionTimeoutSeconds;
252
330
  if (this.outputType !== undefined) out["output_schema"] = outputSchema(this.outputType as OutputType);
253
331
  return out;
254
332
  }
@@ -62,9 +62,15 @@ export class NotSupportedError extends AgentsError {}
62
62
 
63
63
  export class RunError extends AgentsError {
64
64
  readonly code: string;
65
- constructor(code: string, message: string) {
65
+ /** The HTTP status when a request was refused (for example 409 on a function-results post). */
66
+ readonly status?: number;
67
+ /** The server's `error.details[0]` (for example `toolCallIds` or `maxBytes`); `{}` when none. */
68
+ readonly details: Record<string, unknown>;
69
+ constructor(code: string, message: string, status?: number, details?: Record<string, unknown>) {
66
70
  super(`${code}: ${message}`);
67
71
  this.code = code;
72
+ if (status !== undefined) this.status = status;
73
+ this.details = { ...(details ?? {}) };
68
74
  }
69
75
  }
70
76
 
@@ -180,3 +180,33 @@ function map(chunk: Record<string, unknown>): Event | null {
180
180
  return { kind: "unknown", chunk };
181
181
  }
182
182
  }
183
+
184
+ /** A stored UIMessage (`GET /v1/conversations/{id}` `messages`) as the stream chunks that would have produced it,
185
+ * ending with `finish`, so a finished turn can be read like a live one. Text parts become one text block each, tool
186
+ * parts a call and (when they have one) its output, `data-*` parts pass through; reasoning is dropped. */
187
+ export function chunksFromUiMessage(message: unknown): Record<string, unknown>[] {
188
+ const chunks: Record<string, unknown>[] = [];
189
+ const parts = isObject(message) && Array.isArray(message["parts"]) ? message["parts"] : [];
190
+ parts.forEach((part: unknown, n: number) => {
191
+ if (!isObject(part)) return;
192
+ const kind = typeof part["type"] === "string" ? part["type"] : "";
193
+ if (kind === "text") {
194
+ const id = `msg-text-${n}`;
195
+ chunks.push({ type: "text-start", id }, { type: "text-delta", id, delta: String(part["text"] ?? "") },
196
+ { type: "text-end", id });
197
+ } else if (kind === "dynamic-tool" || kind.startsWith("tool-")) {
198
+ const name = part["toolName"] ?? (kind.startsWith("tool-") ? kind.slice("tool-".length) : "");
199
+ const toolCallId = part["toolCallId"] ?? "";
200
+ chunks.push({ type: "tool-input-available", toolCallId, toolName: name, input: part["input"] });
201
+ if (part["state"] === "output-available") {
202
+ chunks.push({ type: "tool-output-available", toolCallId, output: part["output"] });
203
+ } else if (part["state"] === "output-error") {
204
+ chunks.push({ type: "tool-output-available", toolCallId, output: { error: part["errorText"] ?? "" } });
205
+ }
206
+ } else if (kind.startsWith("data-")) {
207
+ chunks.push({ type: kind, id: part["id"], data: part["data"] });
208
+ }
209
+ });
210
+ chunks.push({ type: "finish", finishReason: "stop" });
211
+ return chunks;
212
+ }