@shashu-ai/sdk 1.2.0 → 1.3.0

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.
@@ -1,40 +0,0 @@
1
- import {
2
- applyContractVersion,
3
- buildContextHeaders,
4
- getWorkflowContextFromEnv,
5
- isDisabled,
6
- rejectKeyOnly,
7
- requireBaseUrl
8
- } from "./chunk-CWC6GQTL.js";
9
-
10
- // src/middleware/google.ts
11
- import { randomUUID } from "crypto";
12
- function getGeminiHeaders(config) {
13
- const ctx = config.workflowContext ?? getWorkflowContextFromEnv();
14
- const headers = {
15
- ...config.headers,
16
- ...buildContextHeaders(ctx, { defaultSessionId: config.sessionId })
17
- };
18
- if (config.apiKey) {
19
- headers["x-api-key"] = config.apiKey;
20
- }
21
- return applyContractVersion(headers, config.contractVersion);
22
- }
23
- function createShashuGeminiConfig(config) {
24
- if (isDisabled()) return {};
25
- rejectKeyOnly("createShashuGeminiConfig", config.tokenProvider);
26
- const baseUrl = requireBaseUrl(config.baseUrl, {
27
- entryPoint: "createShashuGeminiConfig()"
28
- });
29
- const headers = getGeminiHeaders({ ...config, sessionId: config.sessionId ?? randomUUID() });
30
- return {
31
- baseUrl,
32
- apiKey: config.apiKey ?? null,
33
- headers: Object.keys(headers).length ? headers : void 0
34
- };
35
- }
36
-
37
- export {
38
- getGeminiHeaders,
39
- createShashuGeminiConfig
40
- };
@@ -1,74 +0,0 @@
1
- import {
2
- withRetrievalJoiner
3
- } from "./chunk-MZGHCDWX.js";
4
- import {
5
- CredentialResolver,
6
- applyContractVersion,
7
- buildContextHeaders,
8
- getWorkflowContextFromEnv,
9
- isDisabled,
10
- passRefusalCodeFromText,
11
- requireBaseUrl,
12
- shouldRetryPassRefused
13
- } from "./chunk-CWC6GQTL.js";
14
-
15
- // src/middleware/anthropic.ts
16
- import { randomUUID } from "crypto";
17
- function getAnthropicHeaders(config) {
18
- const ctx = config.workflowContext ?? getWorkflowContextFromEnv();
19
- const headers = {
20
- ...config.headers,
21
- ...buildContextHeaders(ctx, { defaultSessionId: config.sessionId })
22
- };
23
- if (config.apiKey) {
24
- headers["x-api-key"] = config.apiKey;
25
- }
26
- return applyContractVersion(headers, config.contractVersion);
27
- }
28
- function createShashuAnthropicConfig(config) {
29
- if (isDisabled()) return {};
30
- const baseURL = requireBaseUrl(config.baseUrl, {
31
- entryPoint: "createShashuAnthropicConfig()"
32
- });
33
- const resolver = new CredentialResolver({
34
- apiKey: config.apiKey ?? void 0,
35
- tokenProvider: config.tokenProvider
36
- });
37
- const headers = getAnthropicHeaders({
38
- ...config,
39
- sessionId: config.sessionId ?? randomUUID(),
40
- apiKey: resolver.usesProvider ? void 0 : config.apiKey
41
- });
42
- const joining = withRetrievalJoiner();
43
- const fetch = async (input, init) => {
44
- const token = await resolver.get();
45
- const next = new Headers(init?.headers);
46
- if (token) next.set("x-api-key", token);
47
- const res = await joining(input, { ...init, headers: next });
48
- if (!resolver.usesProvider || res.status !== 401) return res;
49
- const code = passRefusalCodeFromText(await res.clone().text());
50
- if (!shouldRetryPassRefused({
51
- usesProvider: true,
52
- status: res.status,
53
- code,
54
- bytesDelivered: false
55
- })) {
56
- return res;
57
- }
58
- resolver.invalidate();
59
- const retryToken = await resolver.get();
60
- if (retryToken) next.set("x-api-key", retryToken);
61
- return joining(input, { ...init, headers: next });
62
- };
63
- return {
64
- baseURL,
65
- apiKey: resolver.usesProvider ? null : config.apiKey ?? null,
66
- defaultHeaders: Object.keys(headers).length ? headers : void 0,
67
- fetch
68
- };
69
- }
70
-
71
- export {
72
- getAnthropicHeaders,
73
- createShashuAnthropicConfig
74
- };
@@ -1,530 +0,0 @@
1
- import {
2
- isDisabled
3
- } from "./chunk-CWC6GQTL.js";
4
-
5
- // src/_bus.ts
6
- import { AsyncLocalStorage } from "async_hooks";
7
- var MAX_EVENTS = 8;
8
- var MAX_DOCS = 64;
9
- var MAX_PREVIEW_CHARS = 2048;
10
- var MAX_CORPUS_CHARS = 256;
11
- var MAX_QUERY_CHARS = 4096;
12
- var EMPTY = Object.freeze([]);
13
- var BUS = new AsyncLocalStorage();
14
- function current() {
15
- return BUS.getStore()?.events ?? EMPTY;
16
- }
17
- function push(event) {
18
- if (!event.docs || event.docs.length === 0) return;
19
- const store = BUS.getStore();
20
- const next = trim([...store?.events ?? EMPTY, event]);
21
- if (store?.shared) {
22
- store.events = next;
23
- return;
24
- }
25
- BUS.enterWith({ events: next, shared: false });
26
- }
27
- function snapshot() {
28
- return current();
29
- }
30
- function clear() {
31
- const store = BUS.getStore();
32
- if (store) {
33
- store.events = EMPTY;
34
- return;
35
- }
36
- BUS.enterWith({ events: EMPTY, shared: false });
37
- }
38
- function hasEvents() {
39
- return current().length > 0;
40
- }
41
- function runWith(state, fn) {
42
- return BUS.run({ events: state, shared: true }, fn);
43
- }
44
- function trim(events) {
45
- const recent = events.slice(-MAX_EVENTS);
46
- let budget = MAX_DOCS;
47
- const kept = [];
48
- for (let i = recent.length - 1; i >= 0; i -= 1) {
49
- if (budget <= 0) break;
50
- const event = recent[i];
51
- if (event.docs.length > budget) {
52
- kept.push({ ...event, docs: event.docs.slice(-budget) });
53
- budget = 0;
54
- } else {
55
- budget -= event.docs.length;
56
- kept.push(event);
57
- }
58
- }
59
- kept.reverse();
60
- return Object.freeze(kept);
61
- }
62
-
63
- // src/rag.ts
64
- function makeRagContext(input) {
65
- const out = {};
66
- if (input.corpus !== void 0) out.corpus = input.corpus;
67
- if (input.query !== void 0) out.query = input.query;
68
- if (input.docs !== void 0) out.docs = input.docs;
69
- return out;
70
- }
71
- function attachRagContext(body, ragContext) {
72
- if (body === null || typeof body !== "object") {
73
- throw new TypeError("body must be an object");
74
- }
75
- if (ragContext === null || typeof ragContext !== "object") {
76
- throw new TypeError("ragContext must be an object");
77
- }
78
- const existing = body.shashu_metadata;
79
- const meta = existing !== null && typeof existing === "object" ? existing : {};
80
- meta.rag_context = ragContext;
81
- body.shashu_metadata = meta;
82
- return body;
83
- }
84
- var SOURCES = [
85
- "manual",
86
- "langchain",
87
- "llamaindex",
88
- "tool",
89
- "otel",
90
- "n8n",
91
- "provider",
92
- "other"
93
- ];
94
- var HEX = /^[0-9a-fA-F]{8,64}$/;
95
- var SCORE_MIN = -1;
96
- var SCORE_MAX = 1e6;
97
- var MAX_ID_CHARS = 512;
98
- var MAX_SOURCE_URI_CHARS = 2048;
99
- var PREVIEW_KEYS = ["preview", "text", "content", "pageContent", "page_content", "body"];
100
- var ID_KEYS = [
101
- "id",
102
- "doc_id",
103
- "docId",
104
- "documentId",
105
- "document_id",
106
- "nodeId",
107
- "node_id",
108
- "id_",
109
- "_id"
110
- ];
111
- var SCORE_KEYS = ["score", "similarity", "relevance"];
112
- var SOURCE_URI_KEYS = [
113
- "source_uri",
114
- "sourceUri",
115
- "url",
116
- "uri",
117
- "source",
118
- "file_path",
119
- "filePath",
120
- "file_name",
121
- "fileName"
122
- ];
123
- var HASH_KEYS = ["hash", "sha256", "digest"];
124
- var FIELD_KEYS = [
125
- ["preview", PREVIEW_KEYS],
126
- ["id", ID_KEYS],
127
- ["score", SCORE_KEYS],
128
- ["source_uri", SOURCE_URI_KEYS],
129
- ["hash", HASH_KEYS]
130
- ];
131
- function has(...props) {
132
- return (doc) => typeof doc === "object" && doc !== null && props.every((p) => doc[p] !== void 0);
133
- }
134
- var isObject = (doc) => typeof doc === "object" && doc !== null;
135
- function gather(doc) {
136
- const found = {};
137
- for (const [field, keys] of FIELD_KEYS) {
138
- for (const key of keys) {
139
- const value = doc[key];
140
- if (value !== void 0 && value !== null) {
141
- found[field] = value;
142
- break;
143
- }
144
- }
145
- }
146
- const metadata = doc.metadata;
147
- if (isObject(metadata)) {
148
- for (const [field, keys] of FIELD_KEYS) {
149
- if (found[field] !== void 0 || field === "preview") continue;
150
- for (const key of keys) {
151
- const value = metadata[key];
152
- if (value !== void 0 && value !== null) {
153
- found[field] = value;
154
- break;
155
- }
156
- }
157
- }
158
- }
159
- return found;
160
- }
161
- function fromScoredNode(doc) {
162
- const inner = readDocument(doc.node);
163
- return doc.score !== void 0 && doc.score !== null ? { ...inner, score: doc.score } : inner;
164
- }
165
- var COERCIONS = [
166
- { name: "string", matches: (d) => typeof d === "string", read: (d) => ({ preview: d }) },
167
- { name: "scored_node", matches: has("node"), read: fromScoredNode },
168
- { name: "langchain_document", matches: has("pageContent"), read: gather },
169
- { name: "preview_object", matches: has("preview"), read: gather },
170
- { name: "text_node", matches: has("text"), read: gather },
171
- { name: "object", matches: isObject, read: gather }
172
- ];
173
- function readDocument(doc) {
174
- for (const rule of COERCIONS) {
175
- if (rule.matches(doc)) return rule.read(doc);
176
- }
177
- return {};
178
- }
179
- function asText(value, limit) {
180
- if (typeof value !== "string") return void 0;
181
- return value.slice(0, limit) || void 0;
182
- }
183
- function asId(value, position) {
184
- if (typeof value === "string") {
185
- const cleaned = value.trim().slice(0, MAX_ID_CHARS);
186
- if (cleaned) return cleaned;
187
- }
188
- if (typeof value === "number" && Number.isFinite(value)) return String(value);
189
- return `doc-${position}`;
190
- }
191
- function asScore(value) {
192
- let candidate = value;
193
- if (typeof candidate === "string") {
194
- if (!candidate.trim()) return void 0;
195
- const parsed = Number(candidate);
196
- if (Number.isNaN(parsed)) return void 0;
197
- candidate = parsed;
198
- }
199
- if (typeof candidate !== "number") return void 0;
200
- if (!Number.isFinite(candidate) || candidate < SCORE_MIN || candidate > SCORE_MAX) {
201
- return void 0;
202
- }
203
- return candidate;
204
- }
205
- function normalise(raw, position) {
206
- const preview = asText(raw.preview, MAX_PREVIEW_CHARS);
207
- if (preview === void 0) return void 0;
208
- const out = { id: asId(raw.id, position), preview };
209
- const score = asScore(raw.score);
210
- if (score !== void 0) out.score = score;
211
- const sourceUri = asText(raw.source_uri, MAX_SOURCE_URI_CHARS);
212
- if (sourceUri !== void 0) out.source_uri = sourceUri;
213
- if (typeof raw.hash === "string" && HEX.test(raw.hash)) out.hash = raw.hash;
214
- return out;
215
- }
216
- function asDocumentList(docs) {
217
- if (typeof docs === "string") return [docs];
218
- if (Array.isArray(docs)) return docs;
219
- if (isObject(docs) && typeof docs[Symbol.iterator] === "function") {
220
- return Array.from(docs);
221
- }
222
- return [docs];
223
- }
224
- function coerceDocs(docs) {
225
- const out = [];
226
- let position = 0;
227
- for (const doc of asDocumentList(docs)) {
228
- position += 1;
229
- const normalised = normalise(readDocument(doc), position);
230
- if (normalised !== void 0) out.push(normalised);
231
- }
232
- return out;
233
- }
234
- function requireCorpus(corpus) {
235
- if (typeof corpus !== "string" || !corpus.trim()) {
236
- throw new TypeError(
237
- "declareRetrieval() needs a non-empty corpus: it is what the gateway records the documents as having come from, and rag_context.v1 requires it."
238
- );
239
- }
240
- return corpus.trim().slice(0, MAX_CORPUS_CHARS);
241
- }
242
- function requireSource(source) {
243
- if (!SOURCES.includes(source)) {
244
- throw new TypeError(
245
- `declareRetrieval() source=${JSON.stringify(source)} is not a rag_context.v1 value. Use one of: ${SOURCES.join(", ")}. A new integration adds its value to the contract first.`
246
- );
247
- }
248
- return source;
249
- }
250
- function declareRetrieval(docs, options) {
251
- if (isDisabled()) return;
252
- const corpus = requireCorpus(options.corpus);
253
- const source = requireSource(options.source ?? "manual");
254
- push({
255
- corpus,
256
- query: asText(options.query, MAX_QUERY_CHARS),
257
- source,
258
- docs: coerceDocs(docs)
259
- });
260
- }
261
- async function retrievalScope(docs, options, fn) {
262
- if (isDisabled()) return await fn();
263
- const before = snapshot();
264
- return await runWith(before, async () => {
265
- declareRetrieval(docs, options);
266
- return await fn();
267
- });
268
- }
269
- function dedupe(docs) {
270
- const seen = /* @__PURE__ */ new Set();
271
- const out = [];
272
- for (const doc of docs) {
273
- const key = `${doc.id}\0${doc.preview}`;
274
- if (seen.has(key)) continue;
275
- seen.add(key);
276
- out.push(doc);
277
- }
278
- return out;
279
- }
280
- function buildRagContext(events) {
281
- events = events.filter((event) => event.kind !== "memory");
282
- const docs = dedupe(events.flatMap((event) => event.docs)).slice(-MAX_DOCS);
283
- if (docs.length === 0) return void 0;
284
- const corpora = [...new Set(events.map((event) => event.corpus))];
285
- const corpus = corpora.length === 1 ? corpora[0] : corpora.join("+").slice(0, MAX_CORPUS_CHARS).replace(/\++$/, "");
286
- const sources = new Set(events.map((event) => event.source));
287
- const queries = events.map((event) => event.query).filter((q) => !!q);
288
- const context = {
289
- v: 1,
290
- corpus,
291
- source: sources.size === 1 ? [...sources][0] : "other",
292
- docs
293
- };
294
- if (queries.length) context.query = queries[queries.length - 1];
295
- return context;
296
- }
297
-
298
- // src/memory.ts
299
- var MEMORY_SOURCES = [
300
- "sdk",
301
- "manual",
302
- "langchain",
303
- "llamaindex",
304
- "tool",
305
- "otel",
306
- "n8n",
307
- "provider",
308
- "hosted",
309
- "other"
310
- ];
311
- var MEMORY_SCOPES = ["agent", "crew", "tenant"];
312
- function requireStore(store) {
313
- if (!store || !store.trim()) {
314
- throw new TypeError(
315
- "declareMemory needs a non-empty store: it is what the gateway records the items as having come from, and memory_context.v1 requires it."
316
- );
317
- }
318
- return store.trim().slice(0, MAX_CORPUS_CHARS);
319
- }
320
- function requireScope(scope) {
321
- const value = scope || "agent";
322
- if (!MEMORY_SCOPES.includes(value)) {
323
- throw new TypeError(`declareMemory scope='${scope}' is not a memory_context.v1 value.`);
324
- }
325
- return value;
326
- }
327
- function requireSource2(source) {
328
- const value = source || "sdk";
329
- if (!MEMORY_SOURCES.includes(value)) {
330
- throw new TypeError(`declareMemory source='${source}' is not a memory_context.v1 value.`);
331
- }
332
- return value;
333
- }
334
- function declareMemory(items, options) {
335
- if (isDisabled()) return;
336
- const docs = coerceDocs(items);
337
- if (docs.length === 0) return;
338
- push({
339
- kind: "memory",
340
- corpus: requireStore(options.store),
341
- query: requireScope(options.scope),
342
- source: requireSource2(options.source),
343
- docs
344
- });
345
- }
346
- async function memoryScope(items, options, fn) {
347
- if (isDisabled()) return await fn();
348
- const before = snapshot();
349
- return await runWith(before, async () => {
350
- declareMemory(items, options);
351
- return await fn();
352
- });
353
- }
354
- function buildMemoryContext(events) {
355
- const mem = events.filter((e) => e.kind === "memory");
356
- const items = mem.flatMap((e) => e.docs.map((d) => ({ id: d.id, preview: d.preview }))).slice(-MAX_DOCS);
357
- if (items.length === 0) return void 0;
358
- const stores = [...new Set(mem.map((e) => e.corpus))];
359
- const sources = new Set(mem.map((e) => e.source));
360
- const scope = mem[mem.length - 1]?.query || "agent";
361
- return {
362
- v: 1,
363
- store: stores.length === 1 ? stores[0] : stores.join("+").slice(0, MAX_CORPUS_CHARS),
364
- scope,
365
- source: sources.size === 1 ? [...sources][0] : "other",
366
- items
367
- };
368
- }
369
- function attachMemoryContext(body, memoryContext) {
370
- const bag = body;
371
- const existing = bag.shashu_metadata;
372
- const metadata = existing !== null && typeof existing === "object" ? existing : {};
373
- bag.shashu_metadata = { ...metadata, memory_context: memoryContext };
374
- return body;
375
- }
376
-
377
- // src/_joiner.ts
378
- var globalFetch = (input, init) => globalThis.fetch(input, init);
379
- function parseJsonObject(body) {
380
- if (typeof body !== "string") return void 0;
381
- if (!/^[\s]*\{/.test(body)) return void 0;
382
- try {
383
- const parsed = JSON.parse(body);
384
- return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
385
- } catch {
386
- return void 0;
387
- }
388
- }
389
- function metadataBag(body) {
390
- const metadata = body.shashu_metadata;
391
- if (metadata !== null && typeof metadata === "object") {
392
- return metadata;
393
- }
394
- return void 0;
395
- }
396
- function hasExplicitRagContext(body) {
397
- const metadata = metadataBag(body);
398
- return metadata?.rag_context !== void 0 && metadata?.rag_context !== null;
399
- }
400
- function hasExplicitMemoryContext(body) {
401
- const metadata = metadataBag(body);
402
- return metadata?.memory_context !== void 0 && metadata?.memory_context !== null;
403
- }
404
- function fixContentLength(headers, byteLength2) {
405
- const value = String(byteLength2);
406
- if (headers instanceof Headers) {
407
- if (headers.has("content-length")) headers.set("content-length", value);
408
- return headers;
409
- }
410
- if (Array.isArray(headers)) {
411
- return headers.map(
412
- (pair) => Array.isArray(pair) && String(pair[0]).toLowerCase() === "content-length" ? [pair[0], value] : pair
413
- );
414
- }
415
- if (headers !== null && typeof headers === "object") {
416
- const out = { ...headers };
417
- for (const key of Object.keys(out)) {
418
- if (key.toLowerCase() === "content-length") out[key] = value;
419
- }
420
- return out;
421
- }
422
- return headers;
423
- }
424
- function hasConflictingCorpora(events) {
425
- if (events.length <= 1) return false;
426
- const first = events[0].corpus;
427
- for (let i = 1; i < events.length; i += 1) {
428
- if (events[i].corpus !== first) return true;
429
- }
430
- return false;
431
- }
432
- function takeContextFor(body) {
433
- const events = snapshot();
434
- const ragEvents = events.filter((e) => e.kind !== "memory");
435
- const memEvents = events.filter((e) => e.kind === "memory");
436
- const explicitRag = hasExplicitRagContext(body);
437
- const explicitMem = hasExplicitMemoryContext(body);
438
- clear();
439
- let mutated = false;
440
- if (!explicitRag) {
441
- if (hasConflictingCorpora(ragEvents)) {
442
- } else {
443
- const context = buildRagContext(ragEvents);
444
- if (context !== void 0) {
445
- attachRagContext(body, context);
446
- mutated = true;
447
- }
448
- }
449
- }
450
- if (!explicitMem) {
451
- const memoryContext = buildMemoryContext(memEvents);
452
- if (memoryContext !== void 0) {
453
- attachMemoryContext(body, memoryContext);
454
- mutated = true;
455
- }
456
- }
457
- return mutated ? body : void 0;
458
- }
459
- function pinOutgoing(input, init) {
460
- if (!hasEvents()) return { input, init };
461
- if (isDisabled()) {
462
- clear();
463
- return { input, init };
464
- }
465
- const body = parseJsonObject(init?.body);
466
- if (body === void 0) return { input, init };
467
- const merged = takeContextFor(body);
468
- if (merged === void 0) return { input, init };
469
- const encoded = JSON.stringify(merged);
470
- return {
471
- input,
472
- init: {
473
- ...init,
474
- body: encoded,
475
- headers: fixContentLength(init?.headers, byteLength(encoded))
476
- }
477
- };
478
- }
479
- function withRetrievalJoiner(underlying = globalFetch) {
480
- return async function shashuJoiningFetch(input, init) {
481
- if (!hasEvents()) return underlying(input, init);
482
- if (isDisabled()) {
483
- clear();
484
- return underlying(input, init);
485
- }
486
- try {
487
- if (typeof Request !== "undefined" && input instanceof Request) {
488
- const body2 = parseJsonObject(await input.clone().text());
489
- if (body2 === void 0) return underlying(input, init);
490
- const merged2 = takeContextFor(body2);
491
- if (merged2 === void 0) return underlying(input, init);
492
- const encoded2 = JSON.stringify(merged2);
493
- const replacement = new Request(input, { body: encoded2 });
494
- if (replacement.headers.has("content-length")) {
495
- replacement.headers.set("content-length", String(byteLength(encoded2)));
496
- }
497
- return underlying(replacement, init);
498
- }
499
- const body = parseJsonObject(init?.body);
500
- if (body === void 0) return underlying(input, init);
501
- const merged = takeContextFor(body);
502
- if (merged === void 0) return underlying(input, init);
503
- const encoded = JSON.stringify(merged);
504
- return underlying(input, {
505
- ...init,
506
- body: encoded,
507
- headers: fixContentLength(init?.headers, byteLength(encoded))
508
- });
509
- } catch {
510
- return underlying(input, init);
511
- }
512
- };
513
- }
514
- function byteLength(text) {
515
- return new TextEncoder().encode(text).length;
516
- }
517
-
518
- export {
519
- MAX_EVENTS,
520
- makeRagContext,
521
- attachRagContext,
522
- SOURCES,
523
- declareRetrieval,
524
- retrievalScope,
525
- buildRagContext,
526
- declareMemory,
527
- memoryScope,
528
- pinOutgoing,
529
- withRetrievalJoiner
530
- };
@@ -1,71 +0,0 @@
1
- import {
2
- withRetrievalJoiner
3
- } from "./chunk-MZGHCDWX.js";
4
- import {
5
- CredentialResolver,
6
- applyContractVersion,
7
- buildContextHeaders,
8
- getWorkflowContextFromEnv,
9
- isDisabled,
10
- passRefusalCodeFromText,
11
- requireBaseUrl,
12
- shouldRetryPassRefused
13
- } from "./chunk-CWC6GQTL.js";
14
-
15
- // src/middleware/vercel-ai.ts
16
- import { randomUUID } from "crypto";
17
- function getShashuHeaders(workflowContext, sessionId, contractVersion) {
18
- const ctx = workflowContext ?? getWorkflowContextFromEnv();
19
- return applyContractVersion(
20
- buildContextHeaders(ctx, sessionId ? { defaultSessionId: sessionId } : void 0),
21
- contractVersion
22
- );
23
- }
24
- function createShashuOpenAIOptions(options) {
25
- if (isDisabled()) return {};
26
- const baseUrl = requireBaseUrl(options.baseUrl, {
27
- entryPoint: "createShashuOpenAIOptions()"
28
- });
29
- const resolver = new CredentialResolver({
30
- apiKey: options.apiKey,
31
- tokenProvider: options.tokenProvider
32
- });
33
- const headers = {
34
- ...options.headers,
35
- ...getShashuHeaders(options.workflowContext, options.sessionId ?? randomUUID(), null)
36
- };
37
- applyContractVersion(headers, options.contractVersion);
38
- const joining = withRetrievalJoiner();
39
- const fetch = async (input, init) => {
40
- const token = await resolver.get();
41
- const next = new Headers(init?.headers);
42
- if (token) next.set("authorization", `Bearer ${token}`);
43
- const send = () => joining(input, { ...init, headers: next });
44
- const res = await send();
45
- if (!resolver.usesProvider || res.status !== 401) return res;
46
- const code = passRefusalCodeFromText(await res.clone().text());
47
- if (!shouldRetryPassRefused({
48
- usesProvider: true,
49
- status: res.status,
50
- code,
51
- bytesDelivered: false
52
- })) {
53
- return res;
54
- }
55
- resolver.invalidate();
56
- const retryToken = await resolver.get();
57
- if (retryToken) next.set("authorization", `Bearer ${retryToken}`);
58
- return joining(input, { ...init, headers: next });
59
- };
60
- return {
61
- baseURL: baseUrl,
62
- apiKey: resolver.usesProvider ? void 0 : options.openaiApiKey ?? options.apiKey,
63
- headers: Object.keys(headers).length ? headers : void 0,
64
- fetch
65
- };
66
- }
67
-
68
- export {
69
- getShashuHeaders,
70
- createShashuOpenAIOptions
71
- };