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