sarvam-agents-client 0.5.1 → 0.5.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/dist/compat/core/data.js +5 -14
- package/dist/compat/core/events.d.ts +6 -0
- package/dist/compat/core/files.d.ts +65 -0
- package/dist/compat/core/files.js +851 -0
- package/dist/compat/core/history.js +32 -7
- package/dist/compat/core/http.d.ts +52 -0
- package/dist/compat/core/http.js +309 -0
- package/dist/compat/core/turns.d.ts +29 -0
- package/dist/compat/core/turns.js +163 -12
- package/dist/compat/openai/client.d.ts +5 -0
- package/dist/compat/openai/client.js +10 -2
- package/dist/compat/openai/resources/events.js +218 -21
- package/dist/compat/openai/resources/sessions.js +33 -4
- package/dist/esm/compat/core/data.js +5 -14
- package/dist/esm/compat/core/events.d.ts +6 -0
- package/dist/esm/compat/core/files.d.ts +65 -0
- package/dist/esm/compat/core/files.js +829 -0
- package/dist/esm/compat/core/history.js +32 -7
- package/dist/esm/compat/core/http.d.ts +52 -0
- package/dist/esm/compat/core/http.js +307 -0
- package/dist/esm/compat/core/turns.d.ts +29 -0
- package/dist/esm/compat/core/turns.js +162 -12
- package/dist/esm/compat/openai/client.d.ts +5 -0
- package/dist/esm/compat/openai/client.js +10 -2
- package/dist/esm/compat/openai/resources/events.js +209 -12
- package/dist/esm/compat/openai/resources/sessions.js +33 -4
- package/package.json +1 -1
- package/src/compat/core/data.ts +5 -14
- package/src/compat/core/events.ts +7 -1
- package/src/compat/core/files.ts +913 -0
- package/src/compat/core/history.ts +32 -7
- package/src/compat/core/http.ts +338 -1
- package/src/compat/core/turns.ts +214 -13
- package/src/compat/openai/client.ts +13 -1
- package/src/compat/openai/resources/events.ts +239 -12
- package/src/compat/openai/resources/sessions.ts +39 -4
|
@@ -4,17 +4,37 @@ import { MessagesApi } from "../../apis/MessagesApi.js";
|
|
|
4
4
|
import { chunksFromUiMessage } from "../../compose/events.js";
|
|
5
5
|
import { TurnEvents } from "./events.js";
|
|
6
6
|
import { itemId as makeItemId } from "./ids.js";
|
|
7
|
-
function
|
|
8
|
-
var _a;
|
|
7
|
+
function userTextAndAttachments(parts) {
|
|
8
|
+
var _a, _b, _c, _d;
|
|
9
9
|
if (!Array.isArray(parts))
|
|
10
|
-
return "";
|
|
10
|
+
return { text: "", attachments: [] };
|
|
11
11
|
let out = "";
|
|
12
|
+
const attachments = [];
|
|
12
13
|
for (const p of parts) {
|
|
13
|
-
if (p
|
|
14
|
-
|
|
14
|
+
if (!p || typeof p !== "object")
|
|
15
|
+
continue;
|
|
16
|
+
const obj = p;
|
|
17
|
+
const ptype = obj["type"];
|
|
18
|
+
if (ptype === "text") {
|
|
19
|
+
out += String((_a = obj["text"]) !== null && _a !== void 0 ? _a : "");
|
|
20
|
+
}
|
|
21
|
+
else if (ptype === "file") {
|
|
22
|
+
const meta = ((_b = obj["providerMetadata"]) !== null && _b !== void 0 ? _b : obj["provider_metadata"]);
|
|
23
|
+
const custom = meta && typeof meta === "object" ? meta["custom"] : undefined;
|
|
24
|
+
let aid = custom && typeof custom === "object" && typeof custom["artifactId"] === "string"
|
|
25
|
+
? custom["artifactId"]
|
|
26
|
+
: "";
|
|
27
|
+
if (!aid && typeof obj["url"] === "string" && obj["url"].startsWith("artifact://")) {
|
|
28
|
+
aid = obj["url"].slice("artifact://".length);
|
|
29
|
+
}
|
|
30
|
+
if (aid) {
|
|
31
|
+
const fname = String((custom && typeof custom === "object" && custom["filename"]) || obj["filename"] || aid);
|
|
32
|
+
const mtype = String((_d = (_c = obj["mediaType"]) !== null && _c !== void 0 ? _c : obj["media_type"]) !== null && _d !== void 0 ? _d : "application/octet-stream");
|
|
33
|
+
attachments.push({ fileId: aid, filename: fname, mediaType: mtype });
|
|
34
|
+
}
|
|
15
35
|
}
|
|
16
36
|
}
|
|
17
|
-
return out;
|
|
37
|
+
return { text: out, attachments };
|
|
18
38
|
}
|
|
19
39
|
function msgTimestamp(msg, fallback) {
|
|
20
40
|
var _a, _b;
|
|
@@ -64,10 +84,15 @@ export async function history(http, sessionId) {
|
|
|
64
84
|
const role = String((_g = msg["role"]) !== null && _g !== void 0 ? _g : "assistant");
|
|
65
85
|
const msgTs = msgTimestamp(msg, ts);
|
|
66
86
|
if (role === "user") {
|
|
87
|
+
const { text, attachments } = userTextAndAttachments(msg["parts"]);
|
|
67
88
|
records.push({
|
|
68
89
|
responseId: msgId,
|
|
69
90
|
role: "user",
|
|
70
|
-
events: [
|
|
91
|
+
events: [
|
|
92
|
+
attachments.length > 0
|
|
93
|
+
? { kind: "text_done", itemId: makeItemId(msgId, 0), text, attachments }
|
|
94
|
+
: { kind: "text_done", itemId: makeItemId(msgId, 0), text },
|
|
95
|
+
],
|
|
71
96
|
createdAt: msgTs,
|
|
72
97
|
});
|
|
73
98
|
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import * as httpMod from "node:http";
|
|
2
|
+
import * as httpsMod from "node:https";
|
|
1
3
|
import { Configuration, type FetchAPI } from "../../runtime.js";
|
|
2
4
|
export declare const DEFAULT_BASE_URL = "https://chat.sarvamclaw.sarvam.ai";
|
|
3
5
|
export declare const DEFAULT_TIMEOUT_MS = 600000;
|
|
@@ -11,6 +13,7 @@ export interface ClientConfigInput {
|
|
|
11
13
|
defaultQuery?: Record<string, string>;
|
|
12
14
|
fetch?: FetchAPI;
|
|
13
15
|
provider?: string;
|
|
16
|
+
allowPrivateRemoteUrls?: boolean;
|
|
14
17
|
}
|
|
15
18
|
export interface ResolvedClientConfig {
|
|
16
19
|
apiKey: string;
|
|
@@ -21,6 +24,7 @@ export interface ResolvedClientConfig {
|
|
|
21
24
|
defaultQuery: Record<string, string>;
|
|
22
25
|
fetch?: FetchAPI;
|
|
23
26
|
provider: string;
|
|
27
|
+
allowPrivateRemoteUrls: boolean;
|
|
24
28
|
}
|
|
25
29
|
export interface PerCallRequestOptions {
|
|
26
30
|
timeout?: number;
|
|
@@ -35,17 +39,65 @@ export interface RawResponseSnapshot {
|
|
|
35
39
|
headers: Record<string, string>;
|
|
36
40
|
}
|
|
37
41
|
export declare function resolveClientConfig(input?: ClientConfigInput): ResolvedClientConfig;
|
|
42
|
+
export interface PinnedNodeTransport {
|
|
43
|
+
httpRequest?: typeof httpMod.request;
|
|
44
|
+
httpsRequest?: typeof httpsMod.request;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Create a Node `net.LookupFunction` that always resolves directly to ``pinnedIp`` without
|
|
48
|
+
* issuing a second DNS lookup, supporting both `{ all: true }` (Node 20+ autoSelectFamily)
|
|
49
|
+
* and single-address callback forms.
|
|
50
|
+
*/
|
|
51
|
+
export declare function createPinnedLookup(pinnedIp: string): (_hostname: string, options: number | {
|
|
52
|
+
all?: boolean;
|
|
53
|
+
} | ((err: NodeJS.ErrnoException | null, address: string | Array<{
|
|
54
|
+
address: string;
|
|
55
|
+
family: number;
|
|
56
|
+
}>, family?: number) => void), callback?: (err: NodeJS.ErrnoException | null, address: string | Array<{
|
|
57
|
+
address: string;
|
|
58
|
+
family: number;
|
|
59
|
+
}>, family?: number) => void) => void;
|
|
60
|
+
/**
|
|
61
|
+
* Issue an HTTP/HTTPS request pinned to ``pinnedIp`` via Node's stdlib ``node:http`` / ``node:https``
|
|
62
|
+
* while preserving the original ``Host`` header, TLS SNI (``servername``), and certificate hostname
|
|
63
|
+
* verification (closing the DNS rebinding TOCTOU gap).
|
|
64
|
+
*/
|
|
65
|
+
export declare function pinnedNodeFetch(url: string, init: RequestInit, pinnedIp: string, signal?: AbortSignal, transport?: PinnedNodeTransport): Promise<Response>;
|
|
38
66
|
export declare class Http {
|
|
39
67
|
readonly config: ResolvedClientConfig;
|
|
40
68
|
readonly sdkConfig: Configuration;
|
|
69
|
+
private readonly baseFetch;
|
|
41
70
|
private readonly sleepFn;
|
|
42
71
|
private readonly jitterFn;
|
|
72
|
+
private readonly resolveHostFn?;
|
|
43
73
|
private readonly reqStore;
|
|
44
74
|
constructor(input: ClientConfigInput, opts?: {
|
|
45
75
|
sleep?: (ms: number) => Promise<void>;
|
|
46
76
|
jitter?: (ms: number) => number;
|
|
77
|
+
resolveHost?: (host: string) => Promise<string[]>;
|
|
47
78
|
});
|
|
48
79
|
newIdempotencyKey(): string;
|
|
80
|
+
resolveHost(host: string): Promise<string[]>;
|
|
81
|
+
effectiveRemoteTimeoutMs(maxMs: number): number;
|
|
82
|
+
/**
|
|
83
|
+
* Issue a raw HTTP request WITHOUT Sarvam Authorization, X-Panja-Origin, defaultHeaders, defaultQuery,
|
|
84
|
+
* or Idempotency-Key. Honors per-call AbortSignal and timeout (optionally capped by maxTimeoutMs or
|
|
85
|
+
* pinned by timeoutOverrideMs), and returns the raw unbuffered Response plus a cleanup handle and
|
|
86
|
+
* deadline race promise so callers can stream and cap response bodies safely.
|
|
87
|
+
*
|
|
88
|
+
* When ``opts.pinnedIp`` is supplied and no custom ``fetch`` override was provided, connects
|
|
89
|
+
* directly to ``opts.pinnedIp`` via ``node:http``/``node:https`` with original ``Host`` and TLS
|
|
90
|
+
* ``servername`` to eliminate the DNS rebinding TOCTOU window.
|
|
91
|
+
*/
|
|
92
|
+
externalFetch(url: string, init?: RequestInit, opts?: {
|
|
93
|
+
maxTimeoutMs?: number;
|
|
94
|
+
timeoutOverrideMs?: number;
|
|
95
|
+
pinnedIp?: string | null;
|
|
96
|
+
}): Promise<{
|
|
97
|
+
response: Response;
|
|
98
|
+
racePromise: Promise<never> | null;
|
|
99
|
+
cleanup: () => void;
|
|
100
|
+
}>;
|
|
49
101
|
withRequestOptions<T>(opts: PerCallRequestOptions | undefined, fn: () => Promise<T>): Promise<T>;
|
|
50
102
|
captureRawResponse<T>(fn: () => Promise<T>): Promise<{
|
|
51
103
|
data: T;
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
/** HTTP config, key/URL resolution, retry loop, timeouts, default/per-call options, and Configuration wrapper. */
|
|
2
2
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { lookup as dnsLookup } from "node:dns/promises";
|
|
5
|
+
import * as httpMod from "node:http";
|
|
6
|
+
import * as httpsMod from "node:https";
|
|
7
|
+
import { isIP } from "node:net";
|
|
8
|
+
import { Readable } from "node:stream";
|
|
4
9
|
import { Configuration, ResponseError, FetchError } from "../../runtime.js";
|
|
5
10
|
import { NotSupportedByServerError, UserError } from "../../compose/errors.js";
|
|
6
11
|
import { CoreAPIError, CoreConnectionError, CoreTimeoutError, CoreUserAbortError, mapPanjaError, } from "./errors.js";
|
|
@@ -38,6 +43,7 @@ export function resolveClientConfig(input = {}) {
|
|
|
38
43
|
defaultQuery: { ...((_d = input.defaultQuery) !== null && _d !== void 0 ? _d : {}) },
|
|
39
44
|
fetch: input.fetch,
|
|
40
45
|
provider: (_e = input.provider) !== null && _e !== void 0 ? _e : "openai",
|
|
46
|
+
allowPrivateRemoteUrls: Boolean(input.allowPrivateRemoteUrls),
|
|
41
47
|
};
|
|
42
48
|
}
|
|
43
49
|
function getHeader(headers, name) {
|
|
@@ -106,12 +112,185 @@ function mergeUrlQuery(urlStr, extra) {
|
|
|
106
112
|
}
|
|
107
113
|
return u.toString();
|
|
108
114
|
}
|
|
115
|
+
/**
|
|
116
|
+
* Create a Node `net.LookupFunction` that always resolves directly to ``pinnedIp`` without
|
|
117
|
+
* issuing a second DNS lookup, supporting both `{ all: true }` (Node 20+ autoSelectFamily)
|
|
118
|
+
* and single-address callback forms.
|
|
119
|
+
*/
|
|
120
|
+
export function createPinnedLookup(pinnedIp) {
|
|
121
|
+
const family = isIP(pinnedIp);
|
|
122
|
+
if (family !== 4 && family !== 6) {
|
|
123
|
+
throw new Error(`Invalid pinned IP address: ${pinnedIp}`);
|
|
124
|
+
}
|
|
125
|
+
return (_hostname, options, callback) => {
|
|
126
|
+
const cb = typeof options === "function" ? options : callback;
|
|
127
|
+
if (!cb)
|
|
128
|
+
return;
|
|
129
|
+
const wantAll = typeof options === "object" && options !== null && Boolean(options.all);
|
|
130
|
+
if (wantAll) {
|
|
131
|
+
cb(null, [{ address: pinnedIp, family }]);
|
|
132
|
+
}
|
|
133
|
+
else {
|
|
134
|
+
cb(null, pinnedIp, family);
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
function normalizeInitHeaders(raw) {
|
|
139
|
+
const out = {};
|
|
140
|
+
if (!raw)
|
|
141
|
+
return out;
|
|
142
|
+
if (raw instanceof Headers) {
|
|
143
|
+
raw.forEach((v, k) => {
|
|
144
|
+
out[k] = v;
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
else if (Array.isArray(raw)) {
|
|
148
|
+
for (const [k, v] of raw) {
|
|
149
|
+
out[k] = v;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
else {
|
|
153
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
154
|
+
if (v !== undefined)
|
|
155
|
+
out[k] = String(v);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return out;
|
|
159
|
+
}
|
|
160
|
+
function incomingHeadersToWeb(res) {
|
|
161
|
+
var _a;
|
|
162
|
+
const headers = new Headers();
|
|
163
|
+
if (Array.isArray(res.rawHeaders) && res.rawHeaders.length >= 2) {
|
|
164
|
+
for (let i = 0; i + 1 < res.rawHeaders.length; i += 2) {
|
|
165
|
+
const k = res.rawHeaders[i];
|
|
166
|
+
const v = res.rawHeaders[i + 1];
|
|
167
|
+
if (k)
|
|
168
|
+
headers.append(k, v);
|
|
169
|
+
}
|
|
170
|
+
return headers;
|
|
171
|
+
}
|
|
172
|
+
for (const [k, v] of Object.entries((_a = res.headers) !== null && _a !== void 0 ? _a : {})) {
|
|
173
|
+
if (v === undefined)
|
|
174
|
+
continue;
|
|
175
|
+
if (Array.isArray(v)) {
|
|
176
|
+
for (const item of v)
|
|
177
|
+
headers.append(k, item);
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
headers.append(k, v);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return headers;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Issue an HTTP/HTTPS request pinned to ``pinnedIp`` via Node's stdlib ``node:http`` / ``node:https``
|
|
187
|
+
* while preserving the original ``Host`` header, TLS SNI (``servername``), and certificate hostname
|
|
188
|
+
* verification (closing the DNS rebinding TOCTOU gap).
|
|
189
|
+
*/
|
|
190
|
+
export function pinnedNodeFetch(url, init, pinnedIp, signal, transport) {
|
|
191
|
+
var _a, _b, _c;
|
|
192
|
+
const parsed = new URL(url);
|
|
193
|
+
const isHttps = parsed.protocol === "https:";
|
|
194
|
+
const unbracketedHost = parsed.hostname.startsWith("[") && parsed.hostname.endsWith("]")
|
|
195
|
+
? parsed.hostname.slice(1, -1)
|
|
196
|
+
: parsed.hostname;
|
|
197
|
+
const hostIsIp = isIP(unbracketedHost) !== 0;
|
|
198
|
+
const method = ((_a = init.method) !== null && _a !== void 0 ? _a : "GET").toUpperCase();
|
|
199
|
+
const reqHeaders = normalizeInitHeaders(init.headers);
|
|
200
|
+
const hasHost = Object.keys(reqHeaders).some((k) => k.toLowerCase() === "host");
|
|
201
|
+
if (!hasHost) {
|
|
202
|
+
reqHeaders["Host"] = parsed.host;
|
|
203
|
+
}
|
|
204
|
+
const reqOpts = {
|
|
205
|
+
protocol: parsed.protocol,
|
|
206
|
+
hostname: unbracketedHost,
|
|
207
|
+
port: parsed.port || undefined,
|
|
208
|
+
path: `${parsed.pathname || "/"}${parsed.search}`,
|
|
209
|
+
method,
|
|
210
|
+
headers: reqHeaders,
|
|
211
|
+
lookup: createPinnedLookup(pinnedIp),
|
|
212
|
+
signal,
|
|
213
|
+
...(isHttps && !hostIsIp ? { servername: unbracketedHost } : {}),
|
|
214
|
+
};
|
|
215
|
+
const requestFn = isHttps
|
|
216
|
+
? ((_b = transport === null || transport === void 0 ? void 0 : transport.httpsRequest) !== null && _b !== void 0 ? _b : httpsMod.request)
|
|
217
|
+
: ((_c = transport === null || transport === void 0 ? void 0 : transport.httpRequest) !== null && _c !== void 0 ? _c : httpMod.request);
|
|
218
|
+
return new Promise((resolve, reject) => {
|
|
219
|
+
let settled = false;
|
|
220
|
+
const finishResolve = (r) => {
|
|
221
|
+
if (settled)
|
|
222
|
+
return;
|
|
223
|
+
settled = true;
|
|
224
|
+
resolve(r);
|
|
225
|
+
};
|
|
226
|
+
const finishReject = (err) => {
|
|
227
|
+
if (settled)
|
|
228
|
+
return;
|
|
229
|
+
settled = true;
|
|
230
|
+
reject(err);
|
|
231
|
+
};
|
|
232
|
+
const req = requestFn(reqOpts, (res) => {
|
|
233
|
+
var _a, _b;
|
|
234
|
+
const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 500;
|
|
235
|
+
const respHeaders = incomingHeadersToWeb(res);
|
|
236
|
+
const statusText = (_b = res.statusMessage) !== null && _b !== void 0 ? _b : "";
|
|
237
|
+
if (NULL_BODY_STATUSES.has(status) || method === "HEAD") {
|
|
238
|
+
res.resume();
|
|
239
|
+
finishResolve(new Response(null, { status, statusText, headers: respHeaders }));
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
if (signal) {
|
|
243
|
+
const onAbort = () => {
|
|
244
|
+
const reason = signal.reason instanceof Error
|
|
245
|
+
? signal.reason
|
|
246
|
+
: Object.assign(new Error("Request was aborted."), { name: "AbortError" });
|
|
247
|
+
res.destroy(reason);
|
|
248
|
+
req.destroy(reason);
|
|
249
|
+
};
|
|
250
|
+
if (signal.aborted) {
|
|
251
|
+
onAbort();
|
|
252
|
+
}
|
|
253
|
+
else {
|
|
254
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
255
|
+
const detach = () => {
|
|
256
|
+
signal.removeEventListener("abort", onAbort);
|
|
257
|
+
};
|
|
258
|
+
res.once("end", detach);
|
|
259
|
+
res.once("close", detach);
|
|
260
|
+
res.once("error", detach);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
const webStream = Readable.toWeb(res);
|
|
264
|
+
finishResolve(new Response(webStream, { status, statusText, headers: respHeaders }));
|
|
265
|
+
});
|
|
266
|
+
req.on("error", (err) => {
|
|
267
|
+
finishReject(err);
|
|
268
|
+
});
|
|
269
|
+
const body = init.body;
|
|
270
|
+
if (body === undefined || body === null) {
|
|
271
|
+
req.end();
|
|
272
|
+
}
|
|
273
|
+
else if (typeof body === "string") {
|
|
274
|
+
req.end(body);
|
|
275
|
+
}
|
|
276
|
+
else if (body instanceof Uint8Array) {
|
|
277
|
+
req.end(Buffer.from(body.buffer, body.byteOffset, body.byteLength));
|
|
278
|
+
}
|
|
279
|
+
else if (body instanceof ArrayBuffer) {
|
|
280
|
+
req.end(Buffer.from(body));
|
|
281
|
+
}
|
|
282
|
+
else {
|
|
283
|
+
req.end(String(body));
|
|
284
|
+
}
|
|
285
|
+
});
|
|
286
|
+
}
|
|
109
287
|
export class Http {
|
|
110
288
|
constructor(input, opts = {}) {
|
|
111
289
|
var _a, _b;
|
|
112
290
|
this.reqStore = new AsyncLocalStorage();
|
|
113
291
|
this.config = resolveClientConfig(input);
|
|
114
292
|
this.sleepFn = (_a = opts.sleep) !== null && _a !== void 0 ? _a : ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
293
|
+
this.resolveHostFn = opts.resolveHost;
|
|
115
294
|
if (opts.jitter) {
|
|
116
295
|
this.jitterFn = opts.jitter;
|
|
117
296
|
}
|
|
@@ -131,6 +310,7 @@ export class Http {
|
|
|
131
310
|
headers[k] = v;
|
|
132
311
|
}
|
|
133
312
|
const baseFetch = (_b = this.config.fetch) !== null && _b !== void 0 ? _b : globalThis.fetch.bind(globalThis);
|
|
313
|
+
this.baseFetch = baseFetch;
|
|
134
314
|
const httpSelf = this;
|
|
135
315
|
const wrappedFetch = async (reqInput, init) => {
|
|
136
316
|
var _a, _b, _c, _d;
|
|
@@ -332,6 +512,133 @@ export class Http {
|
|
|
332
512
|
newIdempotencyKey() {
|
|
333
513
|
return randomUUID();
|
|
334
514
|
}
|
|
515
|
+
async resolveHost(host) {
|
|
516
|
+
if (this.resolveHostFn) {
|
|
517
|
+
return [...(await this.resolveHostFn(host))];
|
|
518
|
+
}
|
|
519
|
+
const entries = await dnsLookup(host, { all: true });
|
|
520
|
+
const ips = [];
|
|
521
|
+
for (const entry of entries) {
|
|
522
|
+
if (entry.address && !ips.includes(entry.address)) {
|
|
523
|
+
ips.push(entry.address);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
return ips;
|
|
527
|
+
}
|
|
528
|
+
effectiveRemoteTimeoutMs(maxMs) {
|
|
529
|
+
var _a;
|
|
530
|
+
const ov = this.reqStore.getStore();
|
|
531
|
+
const configured = (_a = ov === null || ov === void 0 ? void 0 : ov.timeout) !== null && _a !== void 0 ? _a : this.config.timeout;
|
|
532
|
+
if (configured > 0 && Number.isFinite(configured)) {
|
|
533
|
+
return Math.min(configured, maxMs);
|
|
534
|
+
}
|
|
535
|
+
return maxMs;
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* Issue a raw HTTP request WITHOUT Sarvam Authorization, X-Panja-Origin, defaultHeaders, defaultQuery,
|
|
539
|
+
* or Idempotency-Key. Honors per-call AbortSignal and timeout (optionally capped by maxTimeoutMs or
|
|
540
|
+
* pinned by timeoutOverrideMs), and returns the raw unbuffered Response plus a cleanup handle and
|
|
541
|
+
* deadline race promise so callers can stream and cap response bodies safely.
|
|
542
|
+
*
|
|
543
|
+
* When ``opts.pinnedIp`` is supplied and no custom ``fetch`` override was provided, connects
|
|
544
|
+
* directly to ``opts.pinnedIp`` via ``node:http``/``node:https`` with original ``Host`` and TLS
|
|
545
|
+
* ``servername`` to eliminate the DNS rebinding TOCTOU window.
|
|
546
|
+
*/
|
|
547
|
+
async externalFetch(url, init = {}, opts = {}) {
|
|
548
|
+
var _a, _b;
|
|
549
|
+
const ov = this.reqStore.getStore();
|
|
550
|
+
const ovSignal = ov === null || ov === void 0 ? void 0 : ov.signal;
|
|
551
|
+
if (ovSignal === null || ovSignal === void 0 ? void 0 : ovSignal.aborted) {
|
|
552
|
+
throw new CoreUserAbortError("Request was aborted.");
|
|
553
|
+
}
|
|
554
|
+
const configuredTimeout = (_a = ov === null || ov === void 0 ? void 0 : ov.timeout) !== null && _a !== void 0 ? _a : this.config.timeout;
|
|
555
|
+
let timeoutMs = (_b = opts.timeoutOverrideMs) !== null && _b !== void 0 ? _b : configuredTimeout;
|
|
556
|
+
if (opts.timeoutOverrideMs === undefined && opts.maxTimeoutMs !== undefined) {
|
|
557
|
+
timeoutMs = timeoutMs > 0 && Number.isFinite(timeoutMs)
|
|
558
|
+
? Math.min(timeoutMs, opts.maxTimeoutMs)
|
|
559
|
+
: opts.maxTimeoutMs;
|
|
560
|
+
}
|
|
561
|
+
const hasTimeout = timeoutMs > 0 && Number.isFinite(timeoutMs);
|
|
562
|
+
let controller = null;
|
|
563
|
+
let timer = null;
|
|
564
|
+
let onOvAbort = null;
|
|
565
|
+
let timedOut = false;
|
|
566
|
+
let userAborted = false;
|
|
567
|
+
let settled = false;
|
|
568
|
+
let rejectRace = null;
|
|
569
|
+
let racePromise = null;
|
|
570
|
+
if (hasTimeout || ovSignal) {
|
|
571
|
+
controller = new AbortController();
|
|
572
|
+
racePromise = new Promise((_resolve, reject) => {
|
|
573
|
+
rejectRace = reject;
|
|
574
|
+
});
|
|
575
|
+
racePromise.catch(() => { });
|
|
576
|
+
if (ovSignal) {
|
|
577
|
+
onOvAbort = () => {
|
|
578
|
+
userAborted = true;
|
|
579
|
+
const abortErr = new CoreUserAbortError("Request was aborted.");
|
|
580
|
+
controller === null || controller === void 0 ? void 0 : controller.abort(abortErr);
|
|
581
|
+
if (!settled && rejectRace)
|
|
582
|
+
rejectRace(abortErr);
|
|
583
|
+
};
|
|
584
|
+
ovSignal.addEventListener("abort", onOvAbort, { once: true });
|
|
585
|
+
}
|
|
586
|
+
if (hasTimeout) {
|
|
587
|
+
timer = setTimeout(() => {
|
|
588
|
+
timedOut = true;
|
|
589
|
+
const err = new Error(`Request timed out after ${timeoutMs}ms`);
|
|
590
|
+
err.name = "TimeoutError";
|
|
591
|
+
controller === null || controller === void 0 ? void 0 : controller.abort(err);
|
|
592
|
+
if (!settled && rejectRace) {
|
|
593
|
+
rejectRace(new CoreTimeoutError(`Request timed out after ${timeoutMs}ms.`));
|
|
594
|
+
}
|
|
595
|
+
}, timeoutMs);
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
const cleanup = () => {
|
|
599
|
+
settled = true;
|
|
600
|
+
if (timer !== null) {
|
|
601
|
+
clearTimeout(timer);
|
|
602
|
+
timer = null;
|
|
603
|
+
}
|
|
604
|
+
if (ovSignal && onOvAbort) {
|
|
605
|
+
ovSignal.removeEventListener("abort", onOvAbort);
|
|
606
|
+
onOvAbort = null;
|
|
607
|
+
}
|
|
608
|
+
};
|
|
609
|
+
try {
|
|
610
|
+
const fetchPromise = opts.pinnedIp && !this.config.fetch
|
|
611
|
+
? pinnedNodeFetch(url, init, opts.pinnedIp, controller === null || controller === void 0 ? void 0 : controller.signal)
|
|
612
|
+
: this.baseFetch(url, {
|
|
613
|
+
...init,
|
|
614
|
+
redirect: "manual",
|
|
615
|
+
signal: controller === null || controller === void 0 ? void 0 : controller.signal,
|
|
616
|
+
});
|
|
617
|
+
fetchPromise.then((lateResp) => {
|
|
618
|
+
var _a;
|
|
619
|
+
if (timedOut || userAborted) {
|
|
620
|
+
try {
|
|
621
|
+
void ((_a = lateResp.body) === null || _a === void 0 ? void 0 : _a.cancel().catch(() => { }));
|
|
622
|
+
}
|
|
623
|
+
catch (_b) {
|
|
624
|
+
// ignore
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
}, () => { });
|
|
628
|
+
const response = await (racePromise ? Promise.race([fetchPromise, racePromise]) : fetchPromise);
|
|
629
|
+
return { response, racePromise, cleanup };
|
|
630
|
+
}
|
|
631
|
+
catch (err) {
|
|
632
|
+
cleanup();
|
|
633
|
+
if (userAborted || (ovSignal === null || ovSignal === void 0 ? void 0 : ovSignal.aborted)) {
|
|
634
|
+
throw new CoreUserAbortError("Request was aborted.");
|
|
635
|
+
}
|
|
636
|
+
if (timedOut) {
|
|
637
|
+
throw new CoreTimeoutError(`Request timed out after ${timeoutMs}ms.`);
|
|
638
|
+
}
|
|
639
|
+
throw err;
|
|
640
|
+
}
|
|
641
|
+
}
|
|
335
642
|
withRequestOptions(opts, fn) {
|
|
336
643
|
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
337
644
|
if (!opts)
|
|
@@ -1,16 +1,36 @@
|
|
|
1
|
+
import type { MessagePart } from "../../models/MessagePart.js";
|
|
1
2
|
import { type ResponseStream } from "../../streaming.js";
|
|
2
3
|
import { type TurnEvent } from "./events.js";
|
|
4
|
+
import { AttachmentUploadCache } from "./files.js";
|
|
3
5
|
import { Http, type PerCallRequestOptions } from "./http.js";
|
|
4
6
|
import { Sessions } from "./sessions.js";
|
|
5
7
|
export type Part = {
|
|
6
8
|
type: "text";
|
|
7
9
|
text: string;
|
|
10
|
+
} | {
|
|
11
|
+
type: "inline_file";
|
|
12
|
+
data: Uint8Array;
|
|
13
|
+
mediaType: string;
|
|
14
|
+
filename: string;
|
|
15
|
+
kind: "image" | "file";
|
|
16
|
+
param?: string;
|
|
17
|
+
} | {
|
|
18
|
+
type: "remote_file";
|
|
19
|
+
url: string;
|
|
20
|
+
kind: "image" | "file";
|
|
21
|
+
filename?: string;
|
|
22
|
+
mediaType?: string;
|
|
23
|
+
param?: string;
|
|
8
24
|
} | {
|
|
9
25
|
type: "file_ref";
|
|
10
26
|
fileId: string;
|
|
11
27
|
mediaType?: string;
|
|
28
|
+
filename?: string;
|
|
29
|
+
kind: "image" | "file";
|
|
30
|
+
param?: string;
|
|
12
31
|
};
|
|
13
32
|
export declare const DEFAULT_POLL_TIMEOUT_MS = 300000;
|
|
33
|
+
export declare function prefetchRemoteParts(http: Http, parts: Part[]): Promise<Part[]>;
|
|
14
34
|
export declare class ListenerRegistry {
|
|
15
35
|
private readonly listeners;
|
|
16
36
|
register(sessionId: string, listener: Listener): void;
|
|
@@ -50,10 +70,12 @@ export declare class Turns {
|
|
|
50
70
|
private readonly responsesApi;
|
|
51
71
|
private readonly pollIntervalMs;
|
|
52
72
|
private readonly provider;
|
|
73
|
+
private readonly uploadCache;
|
|
53
74
|
constructor(_http: Http, _sessions: Sessions, opts?: {
|
|
54
75
|
pollIntervalMs?: number;
|
|
55
76
|
provider?: string;
|
|
56
77
|
registry?: ListenerRegistry;
|
|
78
|
+
uploadCache?: AttachmentUploadCache;
|
|
57
79
|
});
|
|
58
80
|
handoffOrClose(sessionId: string, stream: ResponseStream): boolean;
|
|
59
81
|
listen(sessionId: string, opts?: {
|
|
@@ -62,6 +84,13 @@ export declare class Turns {
|
|
|
62
84
|
initialStream?: ResponseStream;
|
|
63
85
|
reqOpts?: PerCallRequestOptions;
|
|
64
86
|
}): Listener;
|
|
87
|
+
resolveParts(sessionId: string, parts: Part[], opts?: {
|
|
88
|
+
key?: string;
|
|
89
|
+
}): Promise<MessagePart[]>;
|
|
90
|
+
sendMessageParts(sessionId: string, agentId: string | null, msgParts: MessagePart[], opts: {
|
|
91
|
+
msgId: string;
|
|
92
|
+
returnStream?: boolean;
|
|
93
|
+
}): Promise<ResponseStream | null>;
|
|
65
94
|
send(sessionId: string, agentId: string | null, parts: Part[], opts?: {
|
|
66
95
|
key?: string;
|
|
67
96
|
returnStream?: boolean;
|