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