@ragable/sdk 0.7.6 → 0.7.8
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/index.d.mts +397 -523
- package/dist/index.d.ts +397 -523
- package/dist/index.js +902 -516
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +890 -507
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -22,8 +22,8 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
|
|
|
22
22
|
// src/index.ts
|
|
23
23
|
var index_exports = {};
|
|
24
24
|
__export(index_exports, {
|
|
25
|
-
AgentsClient: () => AgentsClient,
|
|
26
25
|
AuthBroadcastChannel: () => AuthBroadcastChannel,
|
|
26
|
+
BrowserStorageBucketClient: () => BrowserStorageBucketClient,
|
|
27
27
|
CookieStorageAdapter: () => CookieStorageAdapter,
|
|
28
28
|
DEFAULT_RAGABLE_API_BASE: () => DEFAULT_RAGABLE_API_BASE,
|
|
29
29
|
LocalStorageAdapter: () => LocalStorageAdapter,
|
|
@@ -40,43 +40,43 @@ __export(index_exports, {
|
|
|
40
40
|
PostgrestUpdateRootBuilder: () => PostgrestUpdateRootBuilder,
|
|
41
41
|
PostgrestUpsertReturningBuilder: () => PostgrestUpsertReturningBuilder,
|
|
42
42
|
PostgrestUpsertRootBuilder: () => PostgrestUpsertRootBuilder,
|
|
43
|
-
Ragable: () => Ragable,
|
|
44
43
|
RagableAbortError: () => RagableAbortError,
|
|
45
44
|
RagableAuth: () => RagableAuth,
|
|
46
45
|
RagableBrowser: () => RagableBrowser,
|
|
47
46
|
RagableBrowserAgentsClient: () => RagableBrowserAgentsClient,
|
|
47
|
+
RagableBrowserAiClient: () => RagableBrowserAiClient,
|
|
48
48
|
RagableBrowserAuthClient: () => RagableBrowserAuthClient,
|
|
49
49
|
RagableBrowserDatabaseClient: () => RagableBrowserDatabaseClient,
|
|
50
|
+
RagableBrowserStorageClient: () => RagableBrowserStorageClient,
|
|
50
51
|
RagableError: () => RagableError,
|
|
51
52
|
RagableNetworkError: () => RagableNetworkError,
|
|
52
|
-
RagableRequestClient: () => RagableRequestClient,
|
|
53
53
|
RagableSdkError: () => RagableSdkError,
|
|
54
54
|
RagableTimeoutError: () => RagableTimeoutError,
|
|
55
55
|
SessionStorageAdapter: () => SessionStorageAdapter,
|
|
56
|
-
ShiftClient: () => ShiftClient,
|
|
57
|
-
StorageClient: () => StorageClient,
|
|
58
56
|
Transport: () => Transport,
|
|
59
57
|
asPostgrestResponse: () => asPostgrestResponse,
|
|
60
58
|
assertPostgrestSuccess: () => assertPostgrestSuccess,
|
|
61
59
|
bindFetch: () => bindFetch,
|
|
60
|
+
buildInferenceRequestBody: () => buildInferenceRequestBody,
|
|
61
|
+
buildResponseFormat: () => buildResponseFormat,
|
|
62
62
|
collectAssistantTextFromUiSegments: () => collectAssistantTextFromUiSegments,
|
|
63
63
|
collectionRecordToRowWithMeta: () => collectionRecordToRowWithMeta,
|
|
64
64
|
collectionRecordsToRowWithMeta: () => collectionRecordsToRowWithMeta,
|
|
65
65
|
createBrowserClient: () => createBrowserClient,
|
|
66
66
|
createClient: () => createClient,
|
|
67
|
-
createRagPipeline: () => createRagPipeline,
|
|
68
67
|
createRagableBrowserClient: () => createRagableBrowserClient,
|
|
69
|
-
|
|
68
|
+
createStreamResultFromParts: () => createStreamResultFromParts,
|
|
70
69
|
detectStorage: () => detectStorage,
|
|
71
70
|
effectiveDataAuth: () => effectiveDataAuth,
|
|
72
71
|
extractErrorMessage: () => extractErrorMessage,
|
|
73
72
|
finalizeAgentChatUiTurn: () => finalizeAgentChatUiTurn,
|
|
74
73
|
foldAgentStreamIntoUiSegments: () => foldAgentStreamIntoUiSegments,
|
|
75
74
|
formatPostgrestError: () => formatPostgrestError,
|
|
76
|
-
formatRetrievalContext: () => formatRetrievalContext,
|
|
77
75
|
formatSdkError: () => formatSdkError,
|
|
78
76
|
generateIdempotencyKey: () => generateIdempotencyKey,
|
|
79
77
|
isIncompleteAgentStreamError: () => isIncompleteAgentStreamError,
|
|
78
|
+
mapAgentEvent: () => mapAgentEvent,
|
|
79
|
+
mapFireworksChunk: () => mapFireworksChunk,
|
|
80
80
|
normalizeBrowserApiBase: () => normalizeBrowserApiBase,
|
|
81
81
|
parseAgentStreamAgentInfo: () => parseAgentStreamAgentInfo,
|
|
82
82
|
parseAgentStreamDone: () => parseAgentStreamDone,
|
|
@@ -86,8 +86,11 @@ __export(index_exports, {
|
|
|
86
86
|
runAgentChatStream: () => runAgentChatStream,
|
|
87
87
|
runAgentChatStreamForUi: () => runAgentChatStreamForUi,
|
|
88
88
|
runAgentChatStreamLenient: () => runAgentChatStreamLenient,
|
|
89
|
+
streamObjectFromContext: () => streamObjectFromContext,
|
|
89
90
|
toRagableResult: () => toRagableResult,
|
|
90
|
-
|
|
91
|
+
tryParsePartialJson: () => tryParsePartialJson,
|
|
92
|
+
unwrapPostgrest: () => unwrapPostgrest,
|
|
93
|
+
wrapStreamTextAsObject: () => wrapStreamTextAsObject
|
|
91
94
|
});
|
|
92
95
|
module.exports = __toCommonJS(index_exports);
|
|
93
96
|
|
|
@@ -220,201 +223,6 @@ function extractErrorMessage(payload, fallback) {
|
|
|
220
223
|
}
|
|
221
224
|
return fallback || "Request failed";
|
|
222
225
|
}
|
|
223
|
-
var RagableRequestClient = class {
|
|
224
|
-
constructor(options) {
|
|
225
|
-
__publicField(this, "apiKey");
|
|
226
|
-
__publicField(this, "baseUrl");
|
|
227
|
-
__publicField(this, "fetchImpl");
|
|
228
|
-
__publicField(this, "defaultHeaders");
|
|
229
|
-
this.apiKey = options.apiKey;
|
|
230
|
-
this.baseUrl = DEFAULT_RAGABLE_API_BASE.replace(/\/+$/, "");
|
|
231
|
-
this.fetchImpl = bindFetch(options.fetch);
|
|
232
|
-
this.defaultHeaders = options.headers;
|
|
233
|
-
}
|
|
234
|
-
toUrl(path) {
|
|
235
|
-
const normalizedBase = this.baseUrl.replace(/\/+$/, "");
|
|
236
|
-
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
|
|
237
|
-
return `${normalizedBase}${normalizedPath}`;
|
|
238
|
-
}
|
|
239
|
-
async request(path, options = {}) {
|
|
240
|
-
const response = await this.rawFetch(path, options);
|
|
241
|
-
const payload = await this.parseResponseBody(response);
|
|
242
|
-
if (!response.ok) {
|
|
243
|
-
const message = extractErrorMessage(payload, response.statusText);
|
|
244
|
-
throw new RagableError(message, response.status, payload);
|
|
245
|
-
}
|
|
246
|
-
return payload;
|
|
247
|
-
}
|
|
248
|
-
/**
|
|
249
|
-
* Low-level fetch with API key and JSON body encoding. Caller handles status and body.
|
|
250
|
-
*/
|
|
251
|
-
async rawFetch(path, options = {}) {
|
|
252
|
-
const headers = new Headers(this.defaultHeaders);
|
|
253
|
-
headers.set("Authorization", `Bearer ${this.apiKey}`);
|
|
254
|
-
let body = options.body;
|
|
255
|
-
if (body !== void 0 && !isBodyInit(body)) {
|
|
256
|
-
headers.set("Content-Type", "application/json");
|
|
257
|
-
body = JSON.stringify(body);
|
|
258
|
-
}
|
|
259
|
-
return this.fetchImpl(this.toUrl(path), {
|
|
260
|
-
...options,
|
|
261
|
-
headers,
|
|
262
|
-
body
|
|
263
|
-
});
|
|
264
|
-
}
|
|
265
|
-
async parseResponseBody(response) {
|
|
266
|
-
if (response.status === 204) {
|
|
267
|
-
return null;
|
|
268
|
-
}
|
|
269
|
-
const contentType = response.headers.get("content-type") ?? "";
|
|
270
|
-
if (contentType.includes("application/json")) {
|
|
271
|
-
return response.json();
|
|
272
|
-
}
|
|
273
|
-
return response.text();
|
|
274
|
-
}
|
|
275
|
-
};
|
|
276
|
-
function isBodyInit(value) {
|
|
277
|
-
return typeof value === "string" || value instanceof Blob || value instanceof FormData || value instanceof URLSearchParams || value instanceof ArrayBuffer || ArrayBuffer.isView(value);
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
// src/shift.ts
|
|
281
|
-
var ShiftClient = class {
|
|
282
|
-
constructor(client) {
|
|
283
|
-
this.client = client;
|
|
284
|
-
__publicField(this, "indexes");
|
|
285
|
-
__publicField(this, "documents");
|
|
286
|
-
__publicField(this, "entries");
|
|
287
|
-
this.indexes = {
|
|
288
|
-
list: async () => {
|
|
289
|
-
return this.client.request("/v1/shift/indexes");
|
|
290
|
-
},
|
|
291
|
-
create: async (params) => {
|
|
292
|
-
return this.client.request("/v1/shift/indexes", {
|
|
293
|
-
method: "POST",
|
|
294
|
-
body: params
|
|
295
|
-
});
|
|
296
|
-
},
|
|
297
|
-
get: async (indexId) => {
|
|
298
|
-
return this.client.request(`/v1/shift/indexes/${indexId}`);
|
|
299
|
-
},
|
|
300
|
-
update: async (indexId, params) => {
|
|
301
|
-
return this.client.request(`/v1/shift/indexes/${indexId}`, {
|
|
302
|
-
method: "PUT",
|
|
303
|
-
body: params
|
|
304
|
-
});
|
|
305
|
-
},
|
|
306
|
-
delete: async (indexId) => {
|
|
307
|
-
return this.client.request(
|
|
308
|
-
`/v1/shift/indexes/${indexId}`,
|
|
309
|
-
{
|
|
310
|
-
method: "DELETE"
|
|
311
|
-
}
|
|
312
|
-
);
|
|
313
|
-
}
|
|
314
|
-
};
|
|
315
|
-
this.documents = {
|
|
316
|
-
create: async (indexId, params) => {
|
|
317
|
-
return this.client.request(
|
|
318
|
-
`/v1/shift/indexes/${indexId}/documents`,
|
|
319
|
-
{
|
|
320
|
-
method: "POST",
|
|
321
|
-
body: params
|
|
322
|
-
}
|
|
323
|
-
);
|
|
324
|
-
},
|
|
325
|
-
upload: async (indexId, params) => {
|
|
326
|
-
const formData = new FormData();
|
|
327
|
-
const fileName = resolveUploadFileName(params);
|
|
328
|
-
const contentType = resolveUploadContentType(params);
|
|
329
|
-
const file = normalizeUploadFile(params.file, contentType);
|
|
330
|
-
formData.set("file", file, fileName);
|
|
331
|
-
if (params.metadata) {
|
|
332
|
-
formData.set("metadata", JSON.stringify(params.metadata));
|
|
333
|
-
}
|
|
334
|
-
if (typeof params.chunkSize === "number") {
|
|
335
|
-
formData.set("chunkSize", String(params.chunkSize));
|
|
336
|
-
}
|
|
337
|
-
if (typeof params.chunkOverlap === "number") {
|
|
338
|
-
formData.set("chunkOverlap", String(params.chunkOverlap));
|
|
339
|
-
}
|
|
340
|
-
return this.client.request(
|
|
341
|
-
`/v1/shift/indexes/${indexId}/files`,
|
|
342
|
-
{
|
|
343
|
-
method: "POST",
|
|
344
|
-
body: formData
|
|
345
|
-
}
|
|
346
|
-
);
|
|
347
|
-
}
|
|
348
|
-
};
|
|
349
|
-
this.entries = {
|
|
350
|
-
list: async (indexId, params = {}) => {
|
|
351
|
-
const search = new URLSearchParams();
|
|
352
|
-
if (typeof params.take === "number") {
|
|
353
|
-
search.set("take", String(params.take));
|
|
354
|
-
}
|
|
355
|
-
if (typeof params.skip === "number") {
|
|
356
|
-
search.set("skip", String(params.skip));
|
|
357
|
-
}
|
|
358
|
-
const suffix = search.size > 0 ? `?${search.toString()}` : "";
|
|
359
|
-
return this.client.request(
|
|
360
|
-
`/v1/shift/indexes/${indexId}/entries${suffix}`
|
|
361
|
-
);
|
|
362
|
-
},
|
|
363
|
-
delete: async (indexId, entryId) => {
|
|
364
|
-
return this.client.request(
|
|
365
|
-
`/v1/shift/indexes/${indexId}/entries/${entryId}`,
|
|
366
|
-
{
|
|
367
|
-
method: "DELETE"
|
|
368
|
-
}
|
|
369
|
-
);
|
|
370
|
-
}
|
|
371
|
-
};
|
|
372
|
-
}
|
|
373
|
-
async search(indexId, params) {
|
|
374
|
-
return this.client.request(
|
|
375
|
-
`/v1/shift/indexes/${indexId}/search`,
|
|
376
|
-
{
|
|
377
|
-
method: "POST",
|
|
378
|
-
body: params
|
|
379
|
-
}
|
|
380
|
-
);
|
|
381
|
-
}
|
|
382
|
-
};
|
|
383
|
-
function resolveUploadFileName(params) {
|
|
384
|
-
if (params.fileName) {
|
|
385
|
-
return params.fileName;
|
|
386
|
-
}
|
|
387
|
-
if (isNamedBlob(params.file)) {
|
|
388
|
-
return params.file.name;
|
|
389
|
-
}
|
|
390
|
-
return "upload.bin";
|
|
391
|
-
}
|
|
392
|
-
function resolveUploadContentType(params) {
|
|
393
|
-
if (params.contentType) {
|
|
394
|
-
return params.contentType;
|
|
395
|
-
}
|
|
396
|
-
if (params.file instanceof Blob && params.file.type) {
|
|
397
|
-
return params.file.type;
|
|
398
|
-
}
|
|
399
|
-
return "application/octet-stream";
|
|
400
|
-
}
|
|
401
|
-
function normalizeUploadFile(file, contentType) {
|
|
402
|
-
if (file instanceof Blob) {
|
|
403
|
-
return file;
|
|
404
|
-
}
|
|
405
|
-
if (file instanceof Uint8Array) {
|
|
406
|
-
return new Blob([toArrayBuffer(file)], { type: contentType });
|
|
407
|
-
}
|
|
408
|
-
return new Blob([file], { type: contentType });
|
|
409
|
-
}
|
|
410
|
-
function isNamedBlob(value) {
|
|
411
|
-
return value instanceof Blob && "name" in value && typeof value.name === "string";
|
|
412
|
-
}
|
|
413
|
-
function toArrayBuffer(value) {
|
|
414
|
-
const copy = new Uint8Array(value.byteLength);
|
|
415
|
-
copy.set(value);
|
|
416
|
-
return copy.buffer;
|
|
417
|
-
}
|
|
418
226
|
|
|
419
227
|
// src/agent-stream.ts
|
|
420
228
|
function assertAborted(signal) {
|
|
@@ -920,72 +728,6 @@ async function* readSseStream(body) {
|
|
|
920
728
|
}
|
|
921
729
|
}
|
|
922
730
|
|
|
923
|
-
// src/agents.ts
|
|
924
|
-
var AgentsClient = class {
|
|
925
|
-
constructor(client) {
|
|
926
|
-
this.client = client;
|
|
927
|
-
}
|
|
928
|
-
async list() {
|
|
929
|
-
return this.client.request("/v1/agents");
|
|
930
|
-
}
|
|
931
|
-
async get(agentId) {
|
|
932
|
-
return this.client.request(`/v1/agents/${agentId}`);
|
|
933
|
-
}
|
|
934
|
-
async chat(agentId, params) {
|
|
935
|
-
return this.client.request(`/v1/agents/${agentId}/chat`, {
|
|
936
|
-
method: "POST",
|
|
937
|
-
body: {
|
|
938
|
-
message: params.message,
|
|
939
|
-
...params.history !== void 0 ? { history: params.history } : {}
|
|
940
|
-
}
|
|
941
|
-
});
|
|
942
|
-
}
|
|
943
|
-
/**
|
|
944
|
-
* Stream agent execution as SSE (`data: {json}` lines). Yields parsed JSON objects.
|
|
945
|
-
*/
|
|
946
|
-
async *chatStream(agentId, params) {
|
|
947
|
-
const response = await this.client.rawFetch(
|
|
948
|
-
`/v1/agents/${agentId}/chat/stream`,
|
|
949
|
-
{
|
|
950
|
-
method: "POST",
|
|
951
|
-
body: {
|
|
952
|
-
message: params.message,
|
|
953
|
-
...params.history !== void 0 ? { history: params.history } : {}
|
|
954
|
-
},
|
|
955
|
-
...params.signal !== void 0 ? { signal: params.signal } : {}
|
|
956
|
-
}
|
|
957
|
-
);
|
|
958
|
-
if (!response.ok) {
|
|
959
|
-
const payload = await parseMaybeJsonBody(response);
|
|
960
|
-
const message = extractErrorMessage(payload, response.statusText);
|
|
961
|
-
throw new RagableError(message, response.status, payload);
|
|
962
|
-
}
|
|
963
|
-
const body = response.body;
|
|
964
|
-
if (!body) {
|
|
965
|
-
return;
|
|
966
|
-
}
|
|
967
|
-
yield* readSseStream(body);
|
|
968
|
-
}
|
|
969
|
-
/**
|
|
970
|
-
* Stream an agent turn with callbacks; returns the final `done` payload plus streamed text.
|
|
971
|
-
* Prefer this over manual iteration when building chat UIs against the server API key client.
|
|
972
|
-
*/
|
|
973
|
-
async runChatStream(agentId, params, handlers = {}) {
|
|
974
|
-
return runAgentChatStream(this.chatStream(agentId, params), handlers, {
|
|
975
|
-
signal: params.signal
|
|
976
|
-
});
|
|
977
|
-
}
|
|
978
|
-
/**
|
|
979
|
-
* Stream with dashboard-style `AgentChat` ergonomics: {@link AgentChatStreamUiHandlers.onSegments}
|
|
980
|
-
* / `onStreamingText` for live UI; returns a persisted-shaped assistant message on `done`.
|
|
981
|
-
*/
|
|
982
|
-
async runChatUi(agentId, params, handlers = {}) {
|
|
983
|
-
return runAgentChatStreamForUi(this.chatStream(agentId, params), handlers, {
|
|
984
|
-
signal: params.signal
|
|
985
|
-
});
|
|
986
|
-
}
|
|
987
|
-
};
|
|
988
|
-
|
|
989
731
|
// src/transport.ts
|
|
990
732
|
var DEFAULT_RETRY = {
|
|
991
733
|
maxRetries: 3,
|
|
@@ -2214,8 +1956,8 @@ function parseExpiresInSeconds(raw) {
|
|
|
2214
1956
|
const mult = u === "s" ? 1 : u === "m" ? 60 : u === "h" ? 3600 : u === "d" ? 86400 : 1;
|
|
2215
1957
|
return n * mult;
|
|
2216
1958
|
}
|
|
2217
|
-
const
|
|
2218
|
-
return Number.isFinite(
|
|
1959
|
+
const asNum2 = Number(s);
|
|
1960
|
+
return Number.isFinite(asNum2) ? asNum2 : 0;
|
|
2219
1961
|
}
|
|
2220
1962
|
async function parseJsonOrThrow(response) {
|
|
2221
1963
|
const text = await response.text();
|
|
@@ -2619,6 +2361,740 @@ function decodeJwtExpiry(jwt) {
|
|
|
2619
2361
|
}
|
|
2620
2362
|
}
|
|
2621
2363
|
|
|
2364
|
+
// src/partial-json.ts
|
|
2365
|
+
function tryParsePartialJson(text) {
|
|
2366
|
+
const trimmed = text.trim();
|
|
2367
|
+
if (!trimmed) return void 0;
|
|
2368
|
+
try {
|
|
2369
|
+
return JSON.parse(trimmed);
|
|
2370
|
+
} catch {
|
|
2371
|
+
}
|
|
2372
|
+
const repaired = repairOpenStructures(trimmed);
|
|
2373
|
+
if (!repaired) return void 0;
|
|
2374
|
+
try {
|
|
2375
|
+
return JSON.parse(repaired);
|
|
2376
|
+
} catch {
|
|
2377
|
+
const noTrailingComma = stripTrailingCommas(trimmed);
|
|
2378
|
+
const repaired2 = repairOpenStructures(noTrailingComma);
|
|
2379
|
+
if (!repaired2) return void 0;
|
|
2380
|
+
try {
|
|
2381
|
+
return JSON.parse(repaired2);
|
|
2382
|
+
} catch {
|
|
2383
|
+
return void 0;
|
|
2384
|
+
}
|
|
2385
|
+
}
|
|
2386
|
+
}
|
|
2387
|
+
function repairOpenStructures(text) {
|
|
2388
|
+
const first = text[0];
|
|
2389
|
+
if (first !== "{" && first !== "[") {
|
|
2390
|
+
return text;
|
|
2391
|
+
}
|
|
2392
|
+
const stack = [];
|
|
2393
|
+
let inString = false;
|
|
2394
|
+
let escaped = false;
|
|
2395
|
+
for (let i = 0; i < text.length; i++) {
|
|
2396
|
+
const ch = text[i];
|
|
2397
|
+
if (escaped) {
|
|
2398
|
+
escaped = false;
|
|
2399
|
+
continue;
|
|
2400
|
+
}
|
|
2401
|
+
if (ch === "\\") {
|
|
2402
|
+
escaped = true;
|
|
2403
|
+
continue;
|
|
2404
|
+
}
|
|
2405
|
+
if (ch === '"') {
|
|
2406
|
+
inString = !inString;
|
|
2407
|
+
continue;
|
|
2408
|
+
}
|
|
2409
|
+
if (inString) continue;
|
|
2410
|
+
if (ch === "{") stack.push("}");
|
|
2411
|
+
else if (ch === "[") stack.push("]");
|
|
2412
|
+
else if (ch === "}" || ch === "]") {
|
|
2413
|
+
if (stack.length === 0) return null;
|
|
2414
|
+
stack.pop();
|
|
2415
|
+
}
|
|
2416
|
+
}
|
|
2417
|
+
let safe = text;
|
|
2418
|
+
if (inString) {
|
|
2419
|
+
safe += '"';
|
|
2420
|
+
}
|
|
2421
|
+
safe = safe.replace(/,\s*$/, "").replace(/:\s*$/, ": null");
|
|
2422
|
+
let suffix = "";
|
|
2423
|
+
for (let i = stack.length - 1; i >= 0; i--) suffix += stack[i];
|
|
2424
|
+
return safe + suffix;
|
|
2425
|
+
}
|
|
2426
|
+
function stripTrailingCommas(text) {
|
|
2427
|
+
return text.replace(/,(\s*[}\]])/g, "$1").replace(/,\s*$/, "");
|
|
2428
|
+
}
|
|
2429
|
+
|
|
2430
|
+
// src/stream-parts.ts
|
|
2431
|
+
function normalizeFinishReason(raw) {
|
|
2432
|
+
switch (raw) {
|
|
2433
|
+
case "stop":
|
|
2434
|
+
case "length":
|
|
2435
|
+
case "content-filter":
|
|
2436
|
+
case "error":
|
|
2437
|
+
return raw;
|
|
2438
|
+
case "tool_calls":
|
|
2439
|
+
return "tool-calls";
|
|
2440
|
+
case null:
|
|
2441
|
+
case void 0:
|
|
2442
|
+
case "":
|
|
2443
|
+
return "unknown";
|
|
2444
|
+
default:
|
|
2445
|
+
return "unknown";
|
|
2446
|
+
}
|
|
2447
|
+
}
|
|
2448
|
+
function chunkUsage(chunk) {
|
|
2449
|
+
const u = chunk.usage ?? {};
|
|
2450
|
+
const cached = u.prompt_tokens_details?.cached_tokens ?? u.cache_read_input_tokens;
|
|
2451
|
+
return {
|
|
2452
|
+
promptTokens: typeof u.prompt_tokens === "number" ? u.prompt_tokens : 0,
|
|
2453
|
+
completionTokens: typeof u.completion_tokens === "number" ? u.completion_tokens : 0,
|
|
2454
|
+
totalTokens: typeof u.total_tokens === "number" ? u.total_tokens : 0,
|
|
2455
|
+
...typeof cached === "number" ? { cachedPromptTokens: cached } : {}
|
|
2456
|
+
};
|
|
2457
|
+
}
|
|
2458
|
+
function createToolCallAccumulator() {
|
|
2459
|
+
return { byIndex: /* @__PURE__ */ new Map() };
|
|
2460
|
+
}
|
|
2461
|
+
function parseJsonOrRaw(raw) {
|
|
2462
|
+
try {
|
|
2463
|
+
return JSON.parse(raw);
|
|
2464
|
+
} catch {
|
|
2465
|
+
return raw;
|
|
2466
|
+
}
|
|
2467
|
+
}
|
|
2468
|
+
function mapFireworksChunk(chunk, acc) {
|
|
2469
|
+
const out = [];
|
|
2470
|
+
if (chunk.error?.message) {
|
|
2471
|
+
out.push({ type: "error", error: chunk.error.message });
|
|
2472
|
+
return out;
|
|
2473
|
+
}
|
|
2474
|
+
const choice = chunk.choices?.[0];
|
|
2475
|
+
const delta = choice?.delta;
|
|
2476
|
+
if (delta?.content) {
|
|
2477
|
+
out.push({ type: "text-delta", textDelta: delta.content });
|
|
2478
|
+
}
|
|
2479
|
+
const reasoning = delta?.reasoning_content ?? delta?.reasoning;
|
|
2480
|
+
if (typeof reasoning === "string" && reasoning.length > 0) {
|
|
2481
|
+
out.push({ type: "reasoning", textDelta: reasoning });
|
|
2482
|
+
}
|
|
2483
|
+
if (Array.isArray(delta?.tool_calls)) {
|
|
2484
|
+
for (const tc of delta.tool_calls) {
|
|
2485
|
+
const idx = typeof tc.index === "number" ? tc.index : 0;
|
|
2486
|
+
let entry = acc.byIndex.get(idx);
|
|
2487
|
+
if (!entry) {
|
|
2488
|
+
entry = { id: "", name: "", argsBuffer: "", emitted: false };
|
|
2489
|
+
acc.byIndex.set(idx, entry);
|
|
2490
|
+
}
|
|
2491
|
+
if (tc.id) entry.id = tc.id;
|
|
2492
|
+
if (tc.function?.name) entry.name = tc.function.name;
|
|
2493
|
+
if (typeof tc.function?.arguments === "string") {
|
|
2494
|
+
entry.argsBuffer += tc.function.arguments;
|
|
2495
|
+
}
|
|
2496
|
+
}
|
|
2497
|
+
}
|
|
2498
|
+
if (choice?.finish_reason) {
|
|
2499
|
+
for (const entry of acc.byIndex.values()) {
|
|
2500
|
+
if (entry.emitted || !entry.name) continue;
|
|
2501
|
+
entry.emitted = true;
|
|
2502
|
+
out.push({
|
|
2503
|
+
type: "tool-call",
|
|
2504
|
+
toolCallId: entry.id || `call_${entry.name}_${Date.now()}`,
|
|
2505
|
+
toolName: entry.name,
|
|
2506
|
+
args: entry.argsBuffer ? parseJsonOrRaw(entry.argsBuffer) : {}
|
|
2507
|
+
});
|
|
2508
|
+
}
|
|
2509
|
+
out.push({
|
|
2510
|
+
type: "finish",
|
|
2511
|
+
finishReason: normalizeFinishReason(choice.finish_reason),
|
|
2512
|
+
usage: chunkUsage(chunk)
|
|
2513
|
+
});
|
|
2514
|
+
} else if (chunk.usage) {
|
|
2515
|
+
out.push({
|
|
2516
|
+
type: "finish",
|
|
2517
|
+
finishReason: "unknown",
|
|
2518
|
+
usage: chunkUsage(chunk)
|
|
2519
|
+
});
|
|
2520
|
+
}
|
|
2521
|
+
return out;
|
|
2522
|
+
}
|
|
2523
|
+
function asStr(v, fallback = "") {
|
|
2524
|
+
return typeof v === "string" ? v : fallback;
|
|
2525
|
+
}
|
|
2526
|
+
function asNum(v, fallback = 0) {
|
|
2527
|
+
return typeof v === "number" && Number.isFinite(v) ? v : fallback;
|
|
2528
|
+
}
|
|
2529
|
+
function mapAgentEvent(event) {
|
|
2530
|
+
switch (event.type) {
|
|
2531
|
+
case "token":
|
|
2532
|
+
return { type: "text-delta", textDelta: asStr(event.token) };
|
|
2533
|
+
case "reasoning_token":
|
|
2534
|
+
return { type: "reasoning", textDelta: asStr(event.token) };
|
|
2535
|
+
case "tool:call":
|
|
2536
|
+
return {
|
|
2537
|
+
type: "tool-call",
|
|
2538
|
+
toolCallId: asStr(event.nodeId),
|
|
2539
|
+
toolName: asStr(event.toolName),
|
|
2540
|
+
args: event.args
|
|
2541
|
+
};
|
|
2542
|
+
case "tool:result":
|
|
2543
|
+
return {
|
|
2544
|
+
type: "tool-result",
|
|
2545
|
+
toolCallId: asStr(event.nodeId),
|
|
2546
|
+
toolName: asStr(event.toolName),
|
|
2547
|
+
result: event.result,
|
|
2548
|
+
...typeof event.durationMs === "number" ? { durationMs: event.durationMs } : {}
|
|
2549
|
+
};
|
|
2550
|
+
case "done": {
|
|
2551
|
+
const usage = {
|
|
2552
|
+
promptTokens: asNum(event.inputTokens),
|
|
2553
|
+
completionTokens: asNum(event.outputTokens),
|
|
2554
|
+
totalTokens: asNum(event.inputTokens) + asNum(event.outputTokens),
|
|
2555
|
+
...typeof event.cachedPromptTokens === "number" ? { cachedPromptTokens: event.cachedPromptTokens } : {}
|
|
2556
|
+
};
|
|
2557
|
+
return {
|
|
2558
|
+
type: "finish",
|
|
2559
|
+
finishReason: normalizeFinishReason(
|
|
2560
|
+
asStr(event.finishReason) || asStr(event.stopReason) || null
|
|
2561
|
+
),
|
|
2562
|
+
usage
|
|
2563
|
+
};
|
|
2564
|
+
}
|
|
2565
|
+
default:
|
|
2566
|
+
return null;
|
|
2567
|
+
}
|
|
2568
|
+
}
|
|
2569
|
+
|
|
2570
|
+
// src/ai.ts
|
|
2571
|
+
var PartBroadcast = class {
|
|
2572
|
+
constructor() {
|
|
2573
|
+
__publicField(this, "state", {
|
|
2574
|
+
parts: [],
|
|
2575
|
+
resolved: false,
|
|
2576
|
+
error: null,
|
|
2577
|
+
waiters: []
|
|
2578
|
+
});
|
|
2579
|
+
}
|
|
2580
|
+
push(part) {
|
|
2581
|
+
this.state.parts.push(part);
|
|
2582
|
+
this.notify();
|
|
2583
|
+
}
|
|
2584
|
+
end() {
|
|
2585
|
+
if (this.state.resolved) return;
|
|
2586
|
+
this.state.resolved = true;
|
|
2587
|
+
this.notify();
|
|
2588
|
+
}
|
|
2589
|
+
fail(error) {
|
|
2590
|
+
if (this.state.resolved) return;
|
|
2591
|
+
this.state.error = error;
|
|
2592
|
+
this.state.resolved = true;
|
|
2593
|
+
this.notify();
|
|
2594
|
+
}
|
|
2595
|
+
notify() {
|
|
2596
|
+
const waiters = this.state.waiters;
|
|
2597
|
+
this.state.waiters = [];
|
|
2598
|
+
for (const w of waiters) w();
|
|
2599
|
+
}
|
|
2600
|
+
consume() {
|
|
2601
|
+
const state = this.state;
|
|
2602
|
+
return {
|
|
2603
|
+
[Symbol.asyncIterator]: () => {
|
|
2604
|
+
let idx = 0;
|
|
2605
|
+
return {
|
|
2606
|
+
next: async () => {
|
|
2607
|
+
while (true) {
|
|
2608
|
+
if (idx < state.parts.length) {
|
|
2609
|
+
return { value: state.parts[idx++], done: false };
|
|
2610
|
+
}
|
|
2611
|
+
if (state.resolved) {
|
|
2612
|
+
if (state.error) throw state.error;
|
|
2613
|
+
return { value: void 0, done: true };
|
|
2614
|
+
}
|
|
2615
|
+
await new Promise((resolve) => {
|
|
2616
|
+
state.waiters.push(resolve);
|
|
2617
|
+
});
|
|
2618
|
+
}
|
|
2619
|
+
}
|
|
2620
|
+
};
|
|
2621
|
+
}
|
|
2622
|
+
};
|
|
2623
|
+
}
|
|
2624
|
+
};
|
|
2625
|
+
function defer() {
|
|
2626
|
+
let resolve;
|
|
2627
|
+
let reject;
|
|
2628
|
+
const promise = new Promise((res, rej) => {
|
|
2629
|
+
resolve = res;
|
|
2630
|
+
reject = rej;
|
|
2631
|
+
});
|
|
2632
|
+
return { promise, resolve, reject };
|
|
2633
|
+
}
|
|
2634
|
+
var ZERO_USAGE = {
|
|
2635
|
+
promptTokens: 0,
|
|
2636
|
+
completionTokens: 0,
|
|
2637
|
+
totalTokens: 0
|
|
2638
|
+
};
|
|
2639
|
+
function buildInferenceRequestBody(params, responseFormat) {
|
|
2640
|
+
const body = {
|
|
2641
|
+
model: params.model,
|
|
2642
|
+
messages: params.messages
|
|
2643
|
+
};
|
|
2644
|
+
if (params.system !== void 0) body.system = params.system;
|
|
2645
|
+
if (typeof params.temperature === "number")
|
|
2646
|
+
body.temperature = params.temperature;
|
|
2647
|
+
if (typeof params.maxTokens === "number") body.max_tokens = params.maxTokens;
|
|
2648
|
+
if (typeof params.topP === "number") body.top_p = params.topP;
|
|
2649
|
+
if (params.reasoningEffort) body.reasoning_effort = params.reasoningEffort;
|
|
2650
|
+
if (responseFormat) body.response_format = responseFormat;
|
|
2651
|
+
return body;
|
|
2652
|
+
}
|
|
2653
|
+
function buildResponseFormat(params) {
|
|
2654
|
+
const json_schema = {
|
|
2655
|
+
name: params.name ?? "Output",
|
|
2656
|
+
schema: params.schema,
|
|
2657
|
+
strict: params.strict ?? true
|
|
2658
|
+
};
|
|
2659
|
+
if (params.description) json_schema.description = params.description;
|
|
2660
|
+
return { type: "json_schema", json_schema };
|
|
2661
|
+
}
|
|
2662
|
+
async function consumeInferenceStream(body, broadcast, deferreds) {
|
|
2663
|
+
const reader = body.getReader();
|
|
2664
|
+
const decoder = new TextDecoder();
|
|
2665
|
+
const acc = createToolCallAccumulator();
|
|
2666
|
+
let textBuffer = "";
|
|
2667
|
+
let reasoningBuffer = "";
|
|
2668
|
+
let lastUsage = ZERO_USAGE;
|
|
2669
|
+
let lastFinish = "unknown";
|
|
2670
|
+
const toolCallsArr = [];
|
|
2671
|
+
let buffer = "";
|
|
2672
|
+
const dispatch = (rawLine) => {
|
|
2673
|
+
const parsed = parseSseDataLine(rawLine);
|
|
2674
|
+
if (!parsed) return;
|
|
2675
|
+
const chunk = parsed;
|
|
2676
|
+
const parts = mapFireworksChunk(chunk, acc);
|
|
2677
|
+
for (const part of parts) {
|
|
2678
|
+
if (part.type === "text-delta") textBuffer += part.textDelta;
|
|
2679
|
+
else if (part.type === "reasoning") reasoningBuffer += part.textDelta;
|
|
2680
|
+
else if (part.type === "tool-call") {
|
|
2681
|
+
toolCallsArr.push({
|
|
2682
|
+
toolCallId: part.toolCallId,
|
|
2683
|
+
toolName: part.toolName,
|
|
2684
|
+
args: part.args
|
|
2685
|
+
});
|
|
2686
|
+
} else if (part.type === "finish") {
|
|
2687
|
+
lastFinish = part.finishReason;
|
|
2688
|
+
lastUsage = part.usage;
|
|
2689
|
+
}
|
|
2690
|
+
broadcast.push(part);
|
|
2691
|
+
}
|
|
2692
|
+
};
|
|
2693
|
+
try {
|
|
2694
|
+
while (true) {
|
|
2695
|
+
const { done, value } = await reader.read();
|
|
2696
|
+
if (done) break;
|
|
2697
|
+
buffer += decoder.decode(value, { stream: true });
|
|
2698
|
+
let boundary = buffer.indexOf("\n\n");
|
|
2699
|
+
while (boundary !== -1) {
|
|
2700
|
+
const block = buffer.slice(0, boundary);
|
|
2701
|
+
buffer = buffer.slice(boundary + 2);
|
|
2702
|
+
for (const line of block.split("\n")) dispatch(line);
|
|
2703
|
+
boundary = buffer.indexOf("\n\n");
|
|
2704
|
+
}
|
|
2705
|
+
}
|
|
2706
|
+
if (buffer.trim().length > 0) {
|
|
2707
|
+
for (const line of buffer.split("\n")) dispatch(line);
|
|
2708
|
+
}
|
|
2709
|
+
broadcast.end();
|
|
2710
|
+
deferreds.text.resolve(textBuffer);
|
|
2711
|
+
deferreds.reasoning.resolve(reasoningBuffer);
|
|
2712
|
+
deferreds.usage.resolve(lastUsage);
|
|
2713
|
+
deferreds.finishReason.resolve(lastFinish);
|
|
2714
|
+
deferreds.toolCalls.resolve(toolCallsArr);
|
|
2715
|
+
} catch (error) {
|
|
2716
|
+
broadcast.fail(error);
|
|
2717
|
+
deferreds.text.reject(error);
|
|
2718
|
+
deferreds.reasoning.reject(error);
|
|
2719
|
+
deferreds.usage.reject(error);
|
|
2720
|
+
deferreds.finishReason.reject(error);
|
|
2721
|
+
deferreds.toolCalls.reject(error);
|
|
2722
|
+
} finally {
|
|
2723
|
+
try {
|
|
2724
|
+
reader.releaseLock();
|
|
2725
|
+
} catch {
|
|
2726
|
+
}
|
|
2727
|
+
}
|
|
2728
|
+
}
|
|
2729
|
+
function createStreamResultFromParts(source) {
|
|
2730
|
+
const broadcast = new PartBroadcast();
|
|
2731
|
+
const text = defer();
|
|
2732
|
+
const reasoning = defer();
|
|
2733
|
+
const usage = defer();
|
|
2734
|
+
const finishReason = defer();
|
|
2735
|
+
const toolCalls = defer();
|
|
2736
|
+
void (async () => {
|
|
2737
|
+
let textBuffer = "";
|
|
2738
|
+
let reasoningBuffer = "";
|
|
2739
|
+
let lastUsage = ZERO_USAGE;
|
|
2740
|
+
let lastFinish = "unknown";
|
|
2741
|
+
const toolCallsArr = [];
|
|
2742
|
+
try {
|
|
2743
|
+
for await (const part of source) {
|
|
2744
|
+
if (part.type === "text-delta") textBuffer += part.textDelta;
|
|
2745
|
+
else if (part.type === "reasoning")
|
|
2746
|
+
reasoningBuffer += part.textDelta;
|
|
2747
|
+
else if (part.type === "tool-call") {
|
|
2748
|
+
toolCallsArr.push({
|
|
2749
|
+
toolCallId: part.toolCallId,
|
|
2750
|
+
toolName: part.toolName,
|
|
2751
|
+
args: part.args
|
|
2752
|
+
});
|
|
2753
|
+
} else if (part.type === "finish") {
|
|
2754
|
+
lastFinish = part.finishReason;
|
|
2755
|
+
lastUsage = part.usage;
|
|
2756
|
+
}
|
|
2757
|
+
broadcast.push(part);
|
|
2758
|
+
}
|
|
2759
|
+
broadcast.end();
|
|
2760
|
+
text.resolve(textBuffer);
|
|
2761
|
+
reasoning.resolve(reasoningBuffer);
|
|
2762
|
+
usage.resolve(lastUsage);
|
|
2763
|
+
finishReason.resolve(lastFinish);
|
|
2764
|
+
toolCalls.resolve(toolCallsArr);
|
|
2765
|
+
} catch (error) {
|
|
2766
|
+
broadcast.fail(error);
|
|
2767
|
+
text.reject(error);
|
|
2768
|
+
reasoning.reject(error);
|
|
2769
|
+
usage.reject(error);
|
|
2770
|
+
finishReason.reject(error);
|
|
2771
|
+
toolCalls.reject(error);
|
|
2772
|
+
}
|
|
2773
|
+
})();
|
|
2774
|
+
return {
|
|
2775
|
+
fullStream: broadcast.consume(),
|
|
2776
|
+
textStream: {
|
|
2777
|
+
[Symbol.asyncIterator]: () => {
|
|
2778
|
+
const inner = broadcast.consume()[Symbol.asyncIterator]();
|
|
2779
|
+
return {
|
|
2780
|
+
next: async () => {
|
|
2781
|
+
while (true) {
|
|
2782
|
+
const r = await inner.next();
|
|
2783
|
+
if (r.done)
|
|
2784
|
+
return { value: void 0, done: true };
|
|
2785
|
+
if (r.value.type === "text-delta") {
|
|
2786
|
+
return { value: r.value.textDelta, done: false };
|
|
2787
|
+
}
|
|
2788
|
+
}
|
|
2789
|
+
}
|
|
2790
|
+
};
|
|
2791
|
+
}
|
|
2792
|
+
},
|
|
2793
|
+
text: text.promise,
|
|
2794
|
+
reasoning: reasoning.promise,
|
|
2795
|
+
usage: usage.promise,
|
|
2796
|
+
finishReason: finishReason.promise,
|
|
2797
|
+
toolCalls: toolCalls.promise
|
|
2798
|
+
};
|
|
2799
|
+
}
|
|
2800
|
+
function streamInferenceFromContext(ctx, params) {
|
|
2801
|
+
const broadcast = new PartBroadcast();
|
|
2802
|
+
const text = defer();
|
|
2803
|
+
const reasoning = defer();
|
|
2804
|
+
const usage = defer();
|
|
2805
|
+
const finishReason = defer();
|
|
2806
|
+
const toolCalls = defer();
|
|
2807
|
+
const start = async () => {
|
|
2808
|
+
const response = await ctx.fetch(ctx.url, {
|
|
2809
|
+
method: "POST",
|
|
2810
|
+
headers: ctx.headers,
|
|
2811
|
+
body: JSON.stringify(buildInferenceRequestBody(params)),
|
|
2812
|
+
...params.signal !== void 0 ? { signal: params.signal } : {}
|
|
2813
|
+
});
|
|
2814
|
+
if (!response.ok) {
|
|
2815
|
+
const payload = await parseMaybeJsonBody(response);
|
|
2816
|
+
const message = extractErrorMessage(payload, response.statusText);
|
|
2817
|
+
throw new RagableError(message, response.status, payload);
|
|
2818
|
+
}
|
|
2819
|
+
if (!response.body) {
|
|
2820
|
+
throw new RagableError("Inference stream has no body", 502, {
|
|
2821
|
+
code: "SDK_INFERENCE_STREAM_NO_BODY"
|
|
2822
|
+
});
|
|
2823
|
+
}
|
|
2824
|
+
await consumeInferenceStream(response.body, broadcast, {
|
|
2825
|
+
text,
|
|
2826
|
+
reasoning,
|
|
2827
|
+
usage,
|
|
2828
|
+
finishReason,
|
|
2829
|
+
toolCalls
|
|
2830
|
+
});
|
|
2831
|
+
};
|
|
2832
|
+
start().catch((err) => {
|
|
2833
|
+
broadcast.fail(err);
|
|
2834
|
+
text.reject(err);
|
|
2835
|
+
reasoning.reject(err);
|
|
2836
|
+
usage.reject(err);
|
|
2837
|
+
finishReason.reject(err);
|
|
2838
|
+
toolCalls.reject(err);
|
|
2839
|
+
});
|
|
2840
|
+
return {
|
|
2841
|
+
fullStream: broadcast.consume(),
|
|
2842
|
+
textStream: {
|
|
2843
|
+
[Symbol.asyncIterator]: () => {
|
|
2844
|
+
const inner = broadcast.consume()[Symbol.asyncIterator]();
|
|
2845
|
+
return {
|
|
2846
|
+
next: async () => {
|
|
2847
|
+
while (true) {
|
|
2848
|
+
const r = await inner.next();
|
|
2849
|
+
if (r.done) return { value: void 0, done: true };
|
|
2850
|
+
if (r.value.type === "text-delta") {
|
|
2851
|
+
return { value: r.value.textDelta, done: false };
|
|
2852
|
+
}
|
|
2853
|
+
}
|
|
2854
|
+
}
|
|
2855
|
+
};
|
|
2856
|
+
}
|
|
2857
|
+
},
|
|
2858
|
+
text: text.promise,
|
|
2859
|
+
reasoning: reasoning.promise,
|
|
2860
|
+
usage: usage.promise,
|
|
2861
|
+
finishReason: finishReason.promise,
|
|
2862
|
+
toolCalls: toolCalls.promise
|
|
2863
|
+
};
|
|
2864
|
+
}
|
|
2865
|
+
var RagableBrowserAiClient = class {
|
|
2866
|
+
constructor(options) {
|
|
2867
|
+
this.options = options;
|
|
2868
|
+
__publicField(this, "fetchImpl");
|
|
2869
|
+
this.fetchImpl = bindFetch(options.fetch);
|
|
2870
|
+
}
|
|
2871
|
+
requireWebsiteId() {
|
|
2872
|
+
const id = this.options.websiteId?.trim();
|
|
2873
|
+
if (!id) {
|
|
2874
|
+
throw new RagableError(
|
|
2875
|
+
"client.ai.streamText requires websiteId on the client. Pass createBrowserClient({ websiteId, organizationId, ... }).",
|
|
2876
|
+
400,
|
|
2877
|
+
{ code: "SDK_MISSING_WEBSITE_ID" }
|
|
2878
|
+
);
|
|
2879
|
+
}
|
|
2880
|
+
return id;
|
|
2881
|
+
}
|
|
2882
|
+
buildContext() {
|
|
2883
|
+
const url = `${this.options.apiBase}/public/organizations/${encodeURIComponent(
|
|
2884
|
+
this.options.organizationId
|
|
2885
|
+
)}/websites/${encodeURIComponent(
|
|
2886
|
+
this.requireWebsiteId()
|
|
2887
|
+
)}/inference/stream`;
|
|
2888
|
+
const headers = new Headers(this.options.headers);
|
|
2889
|
+
headers.set("Content-Type", "application/json");
|
|
2890
|
+
headers.set("Accept", "text/event-stream");
|
|
2891
|
+
return { url, headers, fetch: this.fetchImpl };
|
|
2892
|
+
}
|
|
2893
|
+
streamText(params) {
|
|
2894
|
+
return streamInferenceFromContext(this.buildContext(), params);
|
|
2895
|
+
}
|
|
2896
|
+
async generateText(params) {
|
|
2897
|
+
const result = this.streamText(params);
|
|
2898
|
+
for await (const _ of result.fullStream) {
|
|
2899
|
+
void _;
|
|
2900
|
+
}
|
|
2901
|
+
const [text, reasoning, usage, finishReason, toolCalls] = await Promise.all(
|
|
2902
|
+
[
|
|
2903
|
+
result.text,
|
|
2904
|
+
result.reasoning,
|
|
2905
|
+
result.usage,
|
|
2906
|
+
result.finishReason,
|
|
2907
|
+
result.toolCalls
|
|
2908
|
+
]
|
|
2909
|
+
);
|
|
2910
|
+
return { text, reasoning, usage, finishReason, toolCalls };
|
|
2911
|
+
}
|
|
2912
|
+
/**
|
|
2913
|
+
* Stream a JSON-Schema-constrained response. Matches Vercel AI SDK's
|
|
2914
|
+
* `streamObject` shape — returns a synchronous result with `partialObjectStream`
|
|
2915
|
+
* (best-effort incremental parses) and `object` (the final parsed JSON).
|
|
2916
|
+
*
|
|
2917
|
+
* ```ts
|
|
2918
|
+
* const { partialObjectStream, object } = client.ai.streamObject({
|
|
2919
|
+
* model: "accounts/fireworks/models/kimi-k2p5",
|
|
2920
|
+
* schema: {
|
|
2921
|
+
* type: "object",
|
|
2922
|
+
* properties: {
|
|
2923
|
+
* title: { type: "string" },
|
|
2924
|
+
* tags: { type: "array", items: { type: "string" } },
|
|
2925
|
+
* },
|
|
2926
|
+
* required: ["title", "tags"],
|
|
2927
|
+
* },
|
|
2928
|
+
* messages: [{ role: "user", content: "Give me a blog post idea about AI." }],
|
|
2929
|
+
* });
|
|
2930
|
+
* for await (const partial of partialObjectStream) renderPreview(partial);
|
|
2931
|
+
* const final = await object;
|
|
2932
|
+
* ```
|
|
2933
|
+
*/
|
|
2934
|
+
streamObject(params) {
|
|
2935
|
+
return streamObjectFromContext(this.buildContext(), params);
|
|
2936
|
+
}
|
|
2937
|
+
/**
|
|
2938
|
+
* Non-streaming variant of {@link streamObject}. Resolves once the model
|
|
2939
|
+
* finishes; rejects if the final text isn't valid JSON for the schema.
|
|
2940
|
+
*/
|
|
2941
|
+
async generateObject(params) {
|
|
2942
|
+
const result = this.streamObject(params);
|
|
2943
|
+
for await (const _ of result.partialObjectStream) {
|
|
2944
|
+
void _;
|
|
2945
|
+
}
|
|
2946
|
+
const [object, usage, finishReason, toolCalls] = await Promise.all([
|
|
2947
|
+
result.object,
|
|
2948
|
+
result.usage,
|
|
2949
|
+
result.finishReason,
|
|
2950
|
+
result.toolCalls
|
|
2951
|
+
]);
|
|
2952
|
+
return { object, usage, finishReason, toolCalls };
|
|
2953
|
+
}
|
|
2954
|
+
};
|
|
2955
|
+
function streamObjectFromContext(ctx, params) {
|
|
2956
|
+
const textParams = {
|
|
2957
|
+
model: params.model,
|
|
2958
|
+
messages: params.messages,
|
|
2959
|
+
...params.system !== void 0 ? { system: params.system } : {},
|
|
2960
|
+
...typeof params.temperature === "number" ? { temperature: params.temperature } : {},
|
|
2961
|
+
...typeof params.maxTokens === "number" ? { maxTokens: params.maxTokens } : {},
|
|
2962
|
+
...typeof params.topP === "number" ? { topP: params.topP } : {},
|
|
2963
|
+
...params.signal !== void 0 ? { signal: params.signal } : {}
|
|
2964
|
+
};
|
|
2965
|
+
const responseFormat = buildResponseFormat({
|
|
2966
|
+
schema: params.schema,
|
|
2967
|
+
...params.schemaName !== void 0 ? { name: params.schemaName } : {},
|
|
2968
|
+
...params.schemaDescription !== void 0 ? { description: params.schemaDescription } : {}
|
|
2969
|
+
});
|
|
2970
|
+
const overrideCtx = {
|
|
2971
|
+
...ctx,
|
|
2972
|
+
// Wrap fetch to substitute the body. We can't change buildInferenceRequestBody
|
|
2973
|
+
// signature on the call site cleanly, so intercept here.
|
|
2974
|
+
fetch: ((input, init) => {
|
|
2975
|
+
if (init && typeof init.body === "string") {
|
|
2976
|
+
const parsed = JSON.parse(init.body);
|
|
2977
|
+
parsed.response_format = responseFormat;
|
|
2978
|
+
const newInit = { ...init, body: JSON.stringify(parsed) };
|
|
2979
|
+
return ctx.fetch(input, newInit);
|
|
2980
|
+
}
|
|
2981
|
+
return ctx.fetch(input, init);
|
|
2982
|
+
})
|
|
2983
|
+
};
|
|
2984
|
+
const inner = streamInferenceFromContext(overrideCtx, textParams);
|
|
2985
|
+
return wrapStreamTextAsObject(inner);
|
|
2986
|
+
}
|
|
2987
|
+
function wrapStreamTextAsObject(inner) {
|
|
2988
|
+
const partialBroadcast = new PartialObjectBroadcast();
|
|
2989
|
+
const objectDeferred = defer();
|
|
2990
|
+
void (async () => {
|
|
2991
|
+
let acc = "";
|
|
2992
|
+
let lastEmitted = /* @__PURE__ */ Symbol("none");
|
|
2993
|
+
try {
|
|
2994
|
+
for await (const delta of inner.textStream) {
|
|
2995
|
+
acc += delta;
|
|
2996
|
+
const candidate = tryParsePartialJson(acc);
|
|
2997
|
+
if (candidate !== void 0 && !sameSnapshot(candidate, lastEmitted)) {
|
|
2998
|
+
lastEmitted = candidate;
|
|
2999
|
+
partialBroadcast.push(candidate);
|
|
3000
|
+
}
|
|
3001
|
+
}
|
|
3002
|
+
const finalText = await inner.text;
|
|
3003
|
+
let finalObj;
|
|
3004
|
+
try {
|
|
3005
|
+
finalObj = JSON.parse(finalText);
|
|
3006
|
+
} catch (e) {
|
|
3007
|
+
const err = new RagableError(
|
|
3008
|
+
`Model output is not valid JSON: ${e.message}`,
|
|
3009
|
+
502,
|
|
3010
|
+
{
|
|
3011
|
+
code: "SDK_OBJECT_PARSE_FAILED",
|
|
3012
|
+
raw: finalText.slice(0, 1e3)
|
|
3013
|
+
}
|
|
3014
|
+
);
|
|
3015
|
+
partialBroadcast.fail(err);
|
|
3016
|
+
objectDeferred.reject(err);
|
|
3017
|
+
return;
|
|
3018
|
+
}
|
|
3019
|
+
if (!sameSnapshot(finalObj, lastEmitted)) {
|
|
3020
|
+
partialBroadcast.push(finalObj);
|
|
3021
|
+
}
|
|
3022
|
+
partialBroadcast.end();
|
|
3023
|
+
objectDeferred.resolve(finalObj);
|
|
3024
|
+
} catch (err) {
|
|
3025
|
+
partialBroadcast.fail(err);
|
|
3026
|
+
objectDeferred.reject(err);
|
|
3027
|
+
}
|
|
3028
|
+
})();
|
|
3029
|
+
return {
|
|
3030
|
+
textStream: inner.textStream,
|
|
3031
|
+
partialObjectStream: partialBroadcast.consume(),
|
|
3032
|
+
object: objectDeferred.promise,
|
|
3033
|
+
text: inner.text,
|
|
3034
|
+
usage: inner.usage,
|
|
3035
|
+
finishReason: inner.finishReason,
|
|
3036
|
+
toolCalls: inner.toolCalls
|
|
3037
|
+
};
|
|
3038
|
+
}
|
|
3039
|
+
function sameSnapshot(a, b) {
|
|
3040
|
+
if (a === b) return true;
|
|
3041
|
+
try {
|
|
3042
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
3043
|
+
} catch {
|
|
3044
|
+
return false;
|
|
3045
|
+
}
|
|
3046
|
+
}
|
|
3047
|
+
var PartialObjectBroadcast = class {
|
|
3048
|
+
constructor() {
|
|
3049
|
+
__publicField(this, "items", []);
|
|
3050
|
+
__publicField(this, "resolved", false);
|
|
3051
|
+
__publicField(this, "error", null);
|
|
3052
|
+
__publicField(this, "waiters", []);
|
|
3053
|
+
}
|
|
3054
|
+
push(item) {
|
|
3055
|
+
this.items.push(item);
|
|
3056
|
+
this.notify();
|
|
3057
|
+
}
|
|
3058
|
+
end() {
|
|
3059
|
+
if (this.resolved) return;
|
|
3060
|
+
this.resolved = true;
|
|
3061
|
+
this.notify();
|
|
3062
|
+
}
|
|
3063
|
+
fail(error) {
|
|
3064
|
+
if (this.resolved) return;
|
|
3065
|
+
this.error = error;
|
|
3066
|
+
this.resolved = true;
|
|
3067
|
+
this.notify();
|
|
3068
|
+
}
|
|
3069
|
+
notify() {
|
|
3070
|
+
const w = this.waiters;
|
|
3071
|
+
this.waiters = [];
|
|
3072
|
+
for (const fn of w) fn();
|
|
3073
|
+
}
|
|
3074
|
+
consume() {
|
|
3075
|
+
const self = this;
|
|
3076
|
+
return {
|
|
3077
|
+
[Symbol.asyncIterator]: () => {
|
|
3078
|
+
let idx = 0;
|
|
3079
|
+
return {
|
|
3080
|
+
next: async () => {
|
|
3081
|
+
while (true) {
|
|
3082
|
+
if (idx < self.items.length) {
|
|
3083
|
+
return { value: self.items[idx++], done: false };
|
|
3084
|
+
}
|
|
3085
|
+
if (self.resolved) {
|
|
3086
|
+
if (self.error) throw self.error;
|
|
3087
|
+
return { value: void 0, done: true };
|
|
3088
|
+
}
|
|
3089
|
+
await new Promise((res) => self.waiters.push(res));
|
|
3090
|
+
}
|
|
3091
|
+
}
|
|
3092
|
+
};
|
|
3093
|
+
}
|
|
3094
|
+
};
|
|
3095
|
+
}
|
|
3096
|
+
};
|
|
3097
|
+
|
|
2622
3098
|
// src/browser.ts
|
|
2623
3099
|
function normalizeBrowserApiBase() {
|
|
2624
3100
|
return DEFAULT_RAGABLE_API_BASE.replace(/\/+$/, "");
|
|
@@ -3462,6 +3938,136 @@ var RagableBrowserAgentsClient = class {
|
|
|
3462
3938
|
}
|
|
3463
3939
|
yield* readSseStream(streamBody);
|
|
3464
3940
|
}
|
|
3941
|
+
/**
|
|
3942
|
+
* Stream a project agent defined in `agents/*.json` using the same result
|
|
3943
|
+
* shape as `client.ai.streamText`. Preferred over {@link chatStreamByName}
|
|
3944
|
+
* and {@link runChatStreamByName} — those remain for back-compat only.
|
|
3945
|
+
*
|
|
3946
|
+
* ```ts
|
|
3947
|
+
* const { textStream, text } = client.agents.run("support", {
|
|
3948
|
+
* messages: [{ role: "user", content: "I can't log in" }],
|
|
3949
|
+
* });
|
|
3950
|
+
* for await (const delta of textStream) process.stdout.write(delta);
|
|
3951
|
+
* console.log(await text);
|
|
3952
|
+
* ```
|
|
3953
|
+
*/
|
|
3954
|
+
run(agentName, params) {
|
|
3955
|
+
const source = this.runStreamParts(agentName, params);
|
|
3956
|
+
return createStreamResultFromParts(source);
|
|
3957
|
+
}
|
|
3958
|
+
/**
|
|
3959
|
+
* Same agent, same tools/instructions/RAG — but constrain the final output
|
|
3960
|
+
* to a JSON Schema. Matches `client.ai.streamObject` exactly so callers can
|
|
3961
|
+
* swap between raw inference and an agent without changing call shape.
|
|
3962
|
+
*
|
|
3963
|
+
* Tool calling and structured output are **compatible**: the model may call
|
|
3964
|
+
* the agent's tools as usual; the final assistant message is the schema-
|
|
3965
|
+
* conformant JSON. The agent's `agents/<name>.json` is unchanged — whether
|
|
3966
|
+
* the run is conversational or structured is decided by the call site.
|
|
3967
|
+
*
|
|
3968
|
+
* ```ts
|
|
3969
|
+
* const { partialObjectStream, object } = client.agents.runObject<Plan>(
|
|
3970
|
+
* "planner",
|
|
3971
|
+
* {
|
|
3972
|
+
* messages: [{ role: "user", content: "Plan a 3-day trip to Kyoto." }],
|
|
3973
|
+
* schema: {
|
|
3974
|
+
* type: "object",
|
|
3975
|
+
* properties: {
|
|
3976
|
+
* days: {
|
|
3977
|
+
* type: "array",
|
|
3978
|
+
* items: { type: "object", properties: { date: { type: "string" }, activities: { type: "array", items: { type: "string" } } } },
|
|
3979
|
+
* },
|
|
3980
|
+
* },
|
|
3981
|
+
* required: ["days"],
|
|
3982
|
+
* },
|
|
3983
|
+
* },
|
|
3984
|
+
* );
|
|
3985
|
+
* for await (const p of partialObjectStream) renderPreview(p);
|
|
3986
|
+
* console.log(await object);
|
|
3987
|
+
* ```
|
|
3988
|
+
*/
|
|
3989
|
+
runObject(agentName, params) {
|
|
3990
|
+
const responseFormat = buildResponseFormat({
|
|
3991
|
+
schema: params.schema,
|
|
3992
|
+
...params.schemaName !== void 0 ? { name: params.schemaName } : {},
|
|
3993
|
+
...params.schemaDescription !== void 0 ? { description: params.schemaDescription } : {}
|
|
3994
|
+
});
|
|
3995
|
+
const sourceParts = this.runStreamParts(agentName, {
|
|
3996
|
+
messages: params.messages,
|
|
3997
|
+
...params.signal !== void 0 ? { signal: params.signal } : {},
|
|
3998
|
+
responseFormat
|
|
3999
|
+
});
|
|
4000
|
+
const inner = createStreamResultFromParts(sourceParts);
|
|
4001
|
+
return wrapStreamTextAsObject(inner);
|
|
4002
|
+
}
|
|
4003
|
+
/** Non-streaming variant of {@link runObject}. */
|
|
4004
|
+
async generateObject(agentName, params) {
|
|
4005
|
+
const result = this.runObject(agentName, params);
|
|
4006
|
+
for await (const _ of result.partialObjectStream) void _;
|
|
4007
|
+
const [object, usage, finishReason, toolCalls] = await Promise.all([
|
|
4008
|
+
result.object,
|
|
4009
|
+
result.usage,
|
|
4010
|
+
result.finishReason,
|
|
4011
|
+
result.toolCalls
|
|
4012
|
+
]);
|
|
4013
|
+
return { object, usage, finishReason, toolCalls };
|
|
4014
|
+
}
|
|
4015
|
+
async *runStreamParts(agentName, params) {
|
|
4016
|
+
const { messages } = params;
|
|
4017
|
+
if (!Array.isArray(messages) || messages.length === 0) {
|
|
4018
|
+
throw new RagableError(
|
|
4019
|
+
"agents.run requires at least one message",
|
|
4020
|
+
400,
|
|
4021
|
+
{ code: "SDK_AGENTS_RUN_EMPTY_MESSAGES" }
|
|
4022
|
+
);
|
|
4023
|
+
}
|
|
4024
|
+
const last = messages[messages.length - 1];
|
|
4025
|
+
if (!last || last.role !== "user") {
|
|
4026
|
+
throw new RagableError(
|
|
4027
|
+
'agents.run: the final message must have role "user"',
|
|
4028
|
+
400,
|
|
4029
|
+
{ code: "SDK_AGENTS_RUN_INVALID_LAST_MESSAGE" }
|
|
4030
|
+
);
|
|
4031
|
+
}
|
|
4032
|
+
const history = messages.slice(0, -1).filter((m) => m.role === "user" || m.role === "assistant").map((m) => ({
|
|
4033
|
+
role: m.role,
|
|
4034
|
+
content: m.content
|
|
4035
|
+
}));
|
|
4036
|
+
const headers = new Headers(this.options.headers);
|
|
4037
|
+
headers.set("Content-Type", "application/json");
|
|
4038
|
+
const body = {
|
|
4039
|
+
message: last.content,
|
|
4040
|
+
...history.length > 0 ? { history } : {},
|
|
4041
|
+
...params.responseFormat ? { response_format: params.responseFormat } : {}
|
|
4042
|
+
};
|
|
4043
|
+
const response = await this.fetchImpl(
|
|
4044
|
+
this.toUrl(
|
|
4045
|
+
this.websiteAgentPath(
|
|
4046
|
+
`/agents/${encodeURIComponent(agentName)}/chat/stream`
|
|
4047
|
+
)
|
|
4048
|
+
),
|
|
4049
|
+
{
|
|
4050
|
+
method: "POST",
|
|
4051
|
+
headers,
|
|
4052
|
+
body: JSON.stringify(body),
|
|
4053
|
+
...params.signal !== void 0 ? { signal: params.signal } : {}
|
|
4054
|
+
}
|
|
4055
|
+
);
|
|
4056
|
+
if (!response.ok) {
|
|
4057
|
+
const payload = await parseMaybeJsonBody(response);
|
|
4058
|
+
const message = extractErrorMessage(payload, response.statusText);
|
|
4059
|
+
throw new RagableError(message, response.status, payload);
|
|
4060
|
+
}
|
|
4061
|
+
if (!response.body) return;
|
|
4062
|
+
for await (const event of readSseStream(response.body)) {
|
|
4063
|
+
const mapped = mapAgentEvent(event);
|
|
4064
|
+
if (mapped) yield mapped;
|
|
4065
|
+
}
|
|
4066
|
+
}
|
|
4067
|
+
/**
|
|
4068
|
+
* @deprecated Use {@link run} for new code. This method is kept for
|
|
4069
|
+
* back-compat with the original chat-stream DX.
|
|
4070
|
+
*/
|
|
3465
4071
|
async *chatStreamByName(agentName, params) {
|
|
3466
4072
|
const headers = new Headers(this.options.headers);
|
|
3467
4073
|
headers.set("Content-Type", "application/json");
|
|
@@ -3490,8 +4096,9 @@ var RagableBrowserAgentsClient = class {
|
|
|
3490
4096
|
yield* readSseStream(response.body);
|
|
3491
4097
|
}
|
|
3492
4098
|
/**
|
|
3493
|
-
*
|
|
3494
|
-
*
|
|
4099
|
+
* @deprecated Use {@link run} for new code. Returns the legacy callback-based
|
|
4100
|
+
* result type leaking server internals; the new Vercel-style API exposes
|
|
4101
|
+
* `textStream` / `fullStream` / promises for `text`, `usage`, `finishReason`.
|
|
3495
4102
|
*/
|
|
3496
4103
|
async runChatStreamByName(agentName, params, handlers = {}) {
|
|
3497
4104
|
return runAgentChatStream(this.chatStreamByName(agentName, params), handlers, {
|
|
@@ -3588,6 +4195,7 @@ var RagableBrowserAgentsClient = class {
|
|
|
3588
4195
|
var RagableBrowser = class {
|
|
3589
4196
|
constructor(options) {
|
|
3590
4197
|
__publicField(this, "agents");
|
|
4198
|
+
__publicField(this, "ai");
|
|
3591
4199
|
__publicField(this, "auth");
|
|
3592
4200
|
__publicField(this, "database");
|
|
3593
4201
|
__publicField(this, "db");
|
|
@@ -3622,6 +4230,13 @@ var RagableBrowser = class {
|
|
|
3622
4230
|
this._ragableAuth = null;
|
|
3623
4231
|
}
|
|
3624
4232
|
this.agents = new RagableBrowserAgentsClient(options);
|
|
4233
|
+
this.ai = new RagableBrowserAiClient({
|
|
4234
|
+
organizationId: options.organizationId,
|
|
4235
|
+
...options.websiteId !== void 0 ? { websiteId: options.websiteId } : {},
|
|
4236
|
+
...options.fetch !== void 0 ? { fetch: options.fetch } : {},
|
|
4237
|
+
...options.headers !== void 0 ? { headers: options.headers } : {},
|
|
4238
|
+
apiBase: normalizeBrowserApiBase()
|
|
4239
|
+
});
|
|
3625
4240
|
this.auth = new RagableBrowserAuthClient(options, this._ragableAuth);
|
|
3626
4241
|
this.database = new RagableBrowserDatabaseClient(
|
|
3627
4242
|
options,
|
|
@@ -3640,246 +4255,14 @@ function createBrowserClient(options) {
|
|
|
3640
4255
|
}
|
|
3641
4256
|
var createRagableBrowserClient = createBrowserClient;
|
|
3642
4257
|
|
|
3643
|
-
// src/rag.ts
|
|
3644
|
-
function formatRetrievalContext(results, options = {}) {
|
|
3645
|
-
const header = options.header ?? "Relevant passages:\n";
|
|
3646
|
-
const separator = options.separator ?? "\n\n";
|
|
3647
|
-
const minScore = options.minScore;
|
|
3648
|
-
let filtered = results;
|
|
3649
|
-
if (typeof minScore === "number") {
|
|
3650
|
-
filtered = results.filter((r) => r.score >= minScore);
|
|
3651
|
-
}
|
|
3652
|
-
const blocks = filtered.map((r, i) => {
|
|
3653
|
-
const scoreSuffix = options.includeScores === true ? ` (score: ${r.score.toFixed(4)})` : "";
|
|
3654
|
-
return `[${i + 1}]${scoreSuffix}
|
|
3655
|
-
${r.content.trim()}`;
|
|
3656
|
-
});
|
|
3657
|
-
let text = (blocks.length > 0 ? header : "") + blocks.join(separator);
|
|
3658
|
-
if (typeof options.maxChars === "number" && text.length > options.maxChars) {
|
|
3659
|
-
text = text.slice(0, options.maxChars).trimEnd() + "\n\u2026";
|
|
3660
|
-
}
|
|
3661
|
-
return text;
|
|
3662
|
-
}
|
|
3663
|
-
function createRagPipeline(client, options) {
|
|
3664
|
-
const { indexId } = options;
|
|
3665
|
-
return {
|
|
3666
|
-
indexId,
|
|
3667
|
-
ingestText(params) {
|
|
3668
|
-
return client.shift.documents.create(indexId, params);
|
|
3669
|
-
},
|
|
3670
|
-
ingestFile(params) {
|
|
3671
|
-
return client.shift.documents.upload(indexId, params);
|
|
3672
|
-
},
|
|
3673
|
-
search(params) {
|
|
3674
|
-
return client.shift.search(indexId, params);
|
|
3675
|
-
},
|
|
3676
|
-
async retrieve(params) {
|
|
3677
|
-
const { format: formatOpts, ...searchParams } = params;
|
|
3678
|
-
const { results } = await client.shift.search(indexId, searchParams);
|
|
3679
|
-
const context = formatRetrievalContext(results, formatOpts ?? {});
|
|
3680
|
-
return { results, context };
|
|
3681
|
-
}
|
|
3682
|
-
};
|
|
3683
|
-
}
|
|
3684
|
-
|
|
3685
|
-
// src/storage.ts
|
|
3686
|
-
function normalizeUploadFile2(file, contentType) {
|
|
3687
|
-
if (file instanceof Blob) return file;
|
|
3688
|
-
const u8 = file instanceof ArrayBuffer ? new Uint8Array(file) : new Uint8Array(file);
|
|
3689
|
-
return new Blob([u8.buffer], contentType ? { type: contentType } : {});
|
|
3690
|
-
}
|
|
3691
|
-
var StorageClient = class {
|
|
3692
|
-
constructor(client) {
|
|
3693
|
-
this.client = client;
|
|
3694
|
-
/**
|
|
3695
|
-
* Bucket-level CRUD — list, create and delete buckets for this organisation.
|
|
3696
|
-
*/
|
|
3697
|
-
__publicField(this, "buckets");
|
|
3698
|
-
this.buckets = {
|
|
3699
|
-
list: async (params) => {
|
|
3700
|
-
const qs = new URLSearchParams();
|
|
3701
|
-
if (params?.q) qs.set("q", params.q);
|
|
3702
|
-
if (params?.status) qs.set("status", params.status);
|
|
3703
|
-
if (params?.sort) qs.set("sort", params.sort);
|
|
3704
|
-
const query = qs.toString();
|
|
3705
|
-
return this.client.request(
|
|
3706
|
-
`/v1/storage/buckets${query ? `?${query}` : ""}`
|
|
3707
|
-
);
|
|
3708
|
-
},
|
|
3709
|
-
create: async (name) => {
|
|
3710
|
-
return this.client.request("/v1/storage/buckets", {
|
|
3711
|
-
method: "POST",
|
|
3712
|
-
body: { name }
|
|
3713
|
-
});
|
|
3714
|
-
},
|
|
3715
|
-
delete: async (bucketId) => {
|
|
3716
|
-
return this.client.request(
|
|
3717
|
-
`/v1/storage/buckets/${encodeURIComponent(bucketId)}`,
|
|
3718
|
-
{ method: "DELETE" }
|
|
3719
|
-
);
|
|
3720
|
-
}
|
|
3721
|
-
};
|
|
3722
|
-
}
|
|
3723
|
-
/**
|
|
3724
|
-
* Returns a {@link StorageBucketClient} scoped to the given bucket ID.
|
|
3725
|
-
*
|
|
3726
|
-
* All object operations (upload, download, list, copy, move, signed URLs, …)
|
|
3727
|
-
* are performed through the returned client.
|
|
3728
|
-
*
|
|
3729
|
-
* @param bucketId The Ragable bucket ID obtained from `buckets.list()` or `buckets.create()`.
|
|
3730
|
-
*/
|
|
3731
|
-
from(bucketId) {
|
|
3732
|
-
const { client } = this;
|
|
3733
|
-
const base = `/v1/storage/buckets/${encodeURIComponent(bucketId)}`;
|
|
3734
|
-
return {
|
|
3735
|
-
list: async (params) => {
|
|
3736
|
-
const qs = new URLSearchParams();
|
|
3737
|
-
if (params?.prefix) qs.set("prefix", params.prefix);
|
|
3738
|
-
if (params?.delimiter) qs.set("delimiter", params.delimiter);
|
|
3739
|
-
if (params?.maxResults != null)
|
|
3740
|
-
qs.set("maxResults", String(params.maxResults));
|
|
3741
|
-
if (params?.pageToken) qs.set("pageToken", params.pageToken);
|
|
3742
|
-
const query = qs.toString();
|
|
3743
|
-
return client.request(
|
|
3744
|
-
`${base}/contents${query ? `?${query}` : ""}`
|
|
3745
|
-
);
|
|
3746
|
-
},
|
|
3747
|
-
createFolder: async (folderPath) => {
|
|
3748
|
-
return client.request(
|
|
3749
|
-
`${base}/folders`,
|
|
3750
|
-
{ method: "POST", body: { folderPath } }
|
|
3751
|
-
);
|
|
3752
|
-
},
|
|
3753
|
-
deleteFolder: async (folderPath) => {
|
|
3754
|
-
return client.request(
|
|
3755
|
-
`${base}/folders`,
|
|
3756
|
-
{ method: "DELETE", body: { folderPath } }
|
|
3757
|
-
);
|
|
3758
|
-
},
|
|
3759
|
-
upload: async (params) => {
|
|
3760
|
-
const formData = new FormData();
|
|
3761
|
-
const blob = normalizeUploadFile2(params.file, params.contentType);
|
|
3762
|
-
const fileName = params.fileName ?? "upload";
|
|
3763
|
-
formData.set("file", blob, fileName);
|
|
3764
|
-
formData.set("objectPath", params.objectPath);
|
|
3765
|
-
if (params.cacheControl) {
|
|
3766
|
-
formData.set("cacheControl", params.cacheControl);
|
|
3767
|
-
}
|
|
3768
|
-
return client.request(`${base}/upload`, {
|
|
3769
|
-
method: "POST",
|
|
3770
|
-
body: formData
|
|
3771
|
-
});
|
|
3772
|
-
},
|
|
3773
|
-
delete: async (objectPath) => {
|
|
3774
|
-
return client.request(
|
|
3775
|
-
`${base}/objects`,
|
|
3776
|
-
{ method: "DELETE", body: { objectPath } }
|
|
3777
|
-
);
|
|
3778
|
-
},
|
|
3779
|
-
bulkDelete: async (objectPaths) => {
|
|
3780
|
-
return client.request(
|
|
3781
|
-
`${base}/objects/delete-bulk`,
|
|
3782
|
-
{ method: "POST", body: { objectPaths } }
|
|
3783
|
-
);
|
|
3784
|
-
},
|
|
3785
|
-
getMetadata: async (objectPath) => {
|
|
3786
|
-
const qs = new URLSearchParams({ objectPath });
|
|
3787
|
-
return client.request(
|
|
3788
|
-
`${base}/objects/metadata?${qs}`
|
|
3789
|
-
);
|
|
3790
|
-
},
|
|
3791
|
-
updateMetadata: async (params) => {
|
|
3792
|
-
return client.request(
|
|
3793
|
-
`${base}/objects/metadata`,
|
|
3794
|
-
{ method: "PATCH", body: params }
|
|
3795
|
-
);
|
|
3796
|
-
},
|
|
3797
|
-
download: async (params) => {
|
|
3798
|
-
const qs = new URLSearchParams({ objectPath: params.objectPath });
|
|
3799
|
-
if (params.asText != null) qs.set("asText", String(params.asText));
|
|
3800
|
-
if (params.maxTextBytes != null)
|
|
3801
|
-
qs.set("maxTextBytes", String(params.maxTextBytes));
|
|
3802
|
-
return client.request(
|
|
3803
|
-
`${base}/objects/download?${qs}`
|
|
3804
|
-
);
|
|
3805
|
-
},
|
|
3806
|
-
copy: async (params) => {
|
|
3807
|
-
return client.request(`${base}/objects/copy`, { method: "POST", body: params });
|
|
3808
|
-
},
|
|
3809
|
-
move: async (params) => {
|
|
3810
|
-
return client.request(`${base}/objects/move`, { method: "POST", body: params });
|
|
3811
|
-
},
|
|
3812
|
-
getSignedUploadUrl: async (params) => {
|
|
3813
|
-
return client.request(
|
|
3814
|
-
`${base}/signed-upload-url`,
|
|
3815
|
-
{ method: "POST", body: params }
|
|
3816
|
-
);
|
|
3817
|
-
},
|
|
3818
|
-
getSignedDownloadUrl: async (params) => {
|
|
3819
|
-
const qs = new URLSearchParams({ objectPath: params.objectPath });
|
|
3820
|
-
if (params.expiresInSeconds != null)
|
|
3821
|
-
qs.set("expiresInSeconds", String(params.expiresInSeconds));
|
|
3822
|
-
return client.request(
|
|
3823
|
-
`${base}/signed-download-url?${qs}`
|
|
3824
|
-
);
|
|
3825
|
-
},
|
|
3826
|
-
getSettings: async () => {
|
|
3827
|
-
return client.request(`${base}/settings`);
|
|
3828
|
-
},
|
|
3829
|
-
updateSettings: async (params) => {
|
|
3830
|
-
return client.request(`${base}/settings`, {
|
|
3831
|
-
method: "PATCH",
|
|
3832
|
-
body: params
|
|
3833
|
-
});
|
|
3834
|
-
}
|
|
3835
|
-
};
|
|
3836
|
-
}
|
|
3837
|
-
};
|
|
3838
|
-
|
|
3839
4258
|
// src/index.ts
|
|
3840
|
-
var Ragable = class {
|
|
3841
|
-
constructor(options) {
|
|
3842
|
-
__publicField(this, "shift");
|
|
3843
|
-
__publicField(this, "agents");
|
|
3844
|
-
__publicField(this, "storage");
|
|
3845
|
-
__publicField(this, "infrastructure");
|
|
3846
|
-
const client = new RagableRequestClient(options);
|
|
3847
|
-
this.shift = new ShiftClient(client);
|
|
3848
|
-
this.agents = new AgentsClient(client);
|
|
3849
|
-
this.storage = new StorageClient(client);
|
|
3850
|
-
this.infrastructure = {
|
|
3851
|
-
shift: this.shift
|
|
3852
|
-
};
|
|
3853
|
-
}
|
|
3854
|
-
};
|
|
3855
|
-
function isServerClientOptions(o) {
|
|
3856
|
-
return typeof o === "object" && o !== null && "apiKey" in o && typeof o.apiKey === "string" && o.apiKey.length > 0;
|
|
3857
|
-
}
|
|
3858
4259
|
function createClient(options) {
|
|
3859
|
-
|
|
3860
|
-
if (typeof options === "object" && options !== null && "organizationId" in options && typeof options.organizationId === "string") {
|
|
3861
|
-
console.warn(
|
|
3862
|
-
"[@ragable/sdk] createClient: `apiKey` is set, so the server client is returned. It has no `database` or `auth` \u2014 only `agents` and `shift`. For `db.collections.<name>` / `database.from()` / `auth.*`, use the browser client without `apiKey` (e.g. createClient({ organizationId, authGroupId, databaseInstanceId, ... }))."
|
|
3863
|
-
);
|
|
3864
|
-
}
|
|
3865
|
-
return new Ragable(options);
|
|
3866
|
-
}
|
|
3867
|
-
if (typeof options === "object" && options !== null && "organizationId" in options && typeof options.organizationId === "string") {
|
|
3868
|
-
return createBrowserClient(
|
|
3869
|
-
options
|
|
3870
|
-
);
|
|
3871
|
-
}
|
|
3872
|
-
throw new Error(
|
|
3873
|
-
"createClient(options) requires apiKey (server) or organizationId (browser)"
|
|
3874
|
-
);
|
|
3875
|
-
}
|
|
3876
|
-
function createRagableServerClient(options) {
|
|
3877
|
-
return new Ragable(options);
|
|
4260
|
+
return createBrowserClient(options);
|
|
3878
4261
|
}
|
|
3879
4262
|
// Annotate the CommonJS export names for ESM import in node:
|
|
3880
4263
|
0 && (module.exports = {
|
|
3881
|
-
AgentsClient,
|
|
3882
4264
|
AuthBroadcastChannel,
|
|
4265
|
+
BrowserStorageBucketClient,
|
|
3883
4266
|
CookieStorageAdapter,
|
|
3884
4267
|
DEFAULT_RAGABLE_API_BASE,
|
|
3885
4268
|
LocalStorageAdapter,
|
|
@@ -3896,43 +4279,43 @@ function createRagableServerClient(options) {
|
|
|
3896
4279
|
PostgrestUpdateRootBuilder,
|
|
3897
4280
|
PostgrestUpsertReturningBuilder,
|
|
3898
4281
|
PostgrestUpsertRootBuilder,
|
|
3899
|
-
Ragable,
|
|
3900
4282
|
RagableAbortError,
|
|
3901
4283
|
RagableAuth,
|
|
3902
4284
|
RagableBrowser,
|
|
3903
4285
|
RagableBrowserAgentsClient,
|
|
4286
|
+
RagableBrowserAiClient,
|
|
3904
4287
|
RagableBrowserAuthClient,
|
|
3905
4288
|
RagableBrowserDatabaseClient,
|
|
4289
|
+
RagableBrowserStorageClient,
|
|
3906
4290
|
RagableError,
|
|
3907
4291
|
RagableNetworkError,
|
|
3908
|
-
RagableRequestClient,
|
|
3909
4292
|
RagableSdkError,
|
|
3910
4293
|
RagableTimeoutError,
|
|
3911
4294
|
SessionStorageAdapter,
|
|
3912
|
-
ShiftClient,
|
|
3913
|
-
StorageClient,
|
|
3914
4295
|
Transport,
|
|
3915
4296
|
asPostgrestResponse,
|
|
3916
4297
|
assertPostgrestSuccess,
|
|
3917
4298
|
bindFetch,
|
|
4299
|
+
buildInferenceRequestBody,
|
|
4300
|
+
buildResponseFormat,
|
|
3918
4301
|
collectAssistantTextFromUiSegments,
|
|
3919
4302
|
collectionRecordToRowWithMeta,
|
|
3920
4303
|
collectionRecordsToRowWithMeta,
|
|
3921
4304
|
createBrowserClient,
|
|
3922
4305
|
createClient,
|
|
3923
|
-
createRagPipeline,
|
|
3924
4306
|
createRagableBrowserClient,
|
|
3925
|
-
|
|
4307
|
+
createStreamResultFromParts,
|
|
3926
4308
|
detectStorage,
|
|
3927
4309
|
effectiveDataAuth,
|
|
3928
4310
|
extractErrorMessage,
|
|
3929
4311
|
finalizeAgentChatUiTurn,
|
|
3930
4312
|
foldAgentStreamIntoUiSegments,
|
|
3931
4313
|
formatPostgrestError,
|
|
3932
|
-
formatRetrievalContext,
|
|
3933
4314
|
formatSdkError,
|
|
3934
4315
|
generateIdempotencyKey,
|
|
3935
4316
|
isIncompleteAgentStreamError,
|
|
4317
|
+
mapAgentEvent,
|
|
4318
|
+
mapFireworksChunk,
|
|
3936
4319
|
normalizeBrowserApiBase,
|
|
3937
4320
|
parseAgentStreamAgentInfo,
|
|
3938
4321
|
parseAgentStreamDone,
|
|
@@ -3942,7 +4325,10 @@ function createRagableServerClient(options) {
|
|
|
3942
4325
|
runAgentChatStream,
|
|
3943
4326
|
runAgentChatStreamForUi,
|
|
3944
4327
|
runAgentChatStreamLenient,
|
|
4328
|
+
streamObjectFromContext,
|
|
3945
4329
|
toRagableResult,
|
|
3946
|
-
|
|
4330
|
+
tryParsePartialJson,
|
|
4331
|
+
unwrapPostgrest,
|
|
4332
|
+
wrapStreamTextAsObject
|
|
3947
4333
|
});
|
|
3948
4334
|
//# sourceMappingURL=index.js.map
|