@shashu-ai/sdk 0.0.0-stage → 1.1.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.
@@ -0,0 +1,927 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/middleware/vercel-ai.ts
21
+ var vercel_ai_exports = {};
22
+ __export(vercel_ai_exports, {
23
+ createShashuOpenAIOptions: () => createShashuOpenAIOptions,
24
+ getShashuHeaders: () => getShashuHeaders
25
+ });
26
+ module.exports = __toCommonJS(vercel_ai_exports);
27
+ var import_node_crypto3 = require("crypto");
28
+
29
+ // src/types.ts
30
+ var ShashuError = class _ShashuError extends Error {
31
+ /**
32
+ * Why a route was refused for the data in the request, off the decision.
33
+ * Set on a `route_data_policy` refusal, so an app can say which route is not
34
+ * approved for which category without parsing the message.
35
+ */
36
+ get routePolicy() {
37
+ return this.decision?.routePolicy;
38
+ }
39
+ constructor(message, status, body, details) {
40
+ super(message);
41
+ this.name = "ShashuError";
42
+ this.status = status;
43
+ this.body = body;
44
+ this.type = details?.type;
45
+ this.code = details?.code;
46
+ this.decision = details?.decision;
47
+ this.responseHeaders = details?.responseHeaders;
48
+ Object.setPrototypeOf(this, _ShashuError.prototype);
49
+ }
50
+ };
51
+
52
+ // src/exceptions.ts
53
+ var ShashuConfigError = class _ShashuConfigError extends ShashuError {
54
+ constructor(message) {
55
+ super(message, 0);
56
+ this.name = "ShashuConfigError";
57
+ Object.setPrototypeOf(this, _ShashuConfigError.prototype);
58
+ }
59
+ };
60
+
61
+ // src/config.ts
62
+ var BASE_URL_ENV = "SHASHU_BASE_URL";
63
+ var API_KEY_ENV = "SHASHU_API_KEY";
64
+ var DISABLE_ENV = "SHASHU_DISABLE";
65
+ var TRUTHY = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);
66
+ function env() {
67
+ return typeof process !== "undefined" && process.env ? process.env : {};
68
+ }
69
+ function envGet(current2, _legacy) {
70
+ const now = (env()[current2] ?? "").trim();
71
+ return now || void 0;
72
+ }
73
+ function isDisabled() {
74
+ return TRUTHY.has((envGet(DISABLE_ENV) ?? "").trim().toLowerCase());
75
+ }
76
+ function firstConfigured(baseUrl, envVars) {
77
+ if (baseUrl && baseUrl.trim()) return baseUrl.trim().replace(/\/+$/, "");
78
+ for (const name of envVars) {
79
+ const value = env()[name]?.trim();
80
+ if (value) return value.replace(/\/+$/, "");
81
+ }
82
+ return void 0;
83
+ }
84
+ function optionalBaseUrl(baseUrl, envVars = [BASE_URL_ENV]) {
85
+ return firstConfigured(baseUrl, envVars);
86
+ }
87
+ function requireBaseUrl(baseUrl, opts) {
88
+ const envVars = opts.envVars ?? [BASE_URL_ENV];
89
+ const resolved = firstConfigured(baseUrl, envVars);
90
+ if (resolved) return resolved;
91
+ const option = opts.option ?? "baseUrl";
92
+ const envHint = envVars.length === 1 ? `set the ${envVars[0]} environment variable` : `set one of the ${envVars.join(" or ")} environment variables`;
93
+ throw new ShashuConfigError(
94
+ `SHASHU gateway address is not configured, so ${opts.entryPoint} has nothing to route to. Pass ${option} to ${opts.entryPoint}, or ${envHint}. SHASHU is self-hosted: the SDK has no default address and will not guess one.`
95
+ );
96
+ }
97
+
98
+ // src/context.ts
99
+ var import_node_crypto2 = require("crypto");
100
+
101
+ // src/version.ts
102
+ var SDK_VERSION = "1.1.0";
103
+
104
+ // src/tracer.ts
105
+ var import_node_async_hooks = require("async_hooks");
106
+ var import_node_crypto = require("crypto");
107
+ var spanStorage = new import_node_async_hooks.AsyncLocalStorage();
108
+ var a2aStorage = new import_node_async_hooks.AsyncLocalStorage();
109
+ function coerceHeaderMap(headers) {
110
+ const out = {};
111
+ if (!headers) return out;
112
+ try {
113
+ if (Array.isArray(headers)) {
114
+ for (const pair of headers) {
115
+ if (Array.isArray(pair) && pair.length >= 2 && pair[0] != null) {
116
+ out[String(pair[0]).toLowerCase()] = String(pair[1]);
117
+ }
118
+ }
119
+ return out;
120
+ }
121
+ if (headers instanceof Map) {
122
+ for (const [k, v] of headers) out[String(k).toLowerCase()] = String(v);
123
+ return out;
124
+ }
125
+ if (typeof headers.forEach === "function") {
126
+ headers.forEach((v, k) => {
127
+ if (k != null) out[String(k).toLowerCase()] = String(v);
128
+ });
129
+ return out;
130
+ }
131
+ if (typeof headers === "object") {
132
+ for (const [k, v] of Object.entries(headers)) {
133
+ if (v !== void 0 && v !== null) out[k.toLowerCase()] = String(v);
134
+ }
135
+ }
136
+ } catch {
137
+ return out;
138
+ }
139
+ return out;
140
+ }
141
+ function parseHopDepth(raw) {
142
+ const n = parseInt(String(raw ?? "").trim(), 10);
143
+ return Number.isFinite(n) && n > 0 ? n : 0;
144
+ }
145
+ function captureFromHeaders(h) {
146
+ const trace = (h["x-shashu-trace-id"] ?? "").trim();
147
+ if (!trace) return void 0;
148
+ const session = (h["x-shashu-session-id"] ?? "").trim();
149
+ const caller = (h["x-shashu-caller-agent-id"] ?? "").trim();
150
+ return {
151
+ traceId: trace,
152
+ sessionId: session || void 0,
153
+ inboundHopDepth: parseHopDepth(h["x-shashu-hop-depth"]),
154
+ inboundCallerAgentId: caller || void 0
155
+ };
156
+ }
157
+ var Tracer = class {
158
+ /**
159
+ * Resolves the address OPTIONALLY, unlike every other entry point.
160
+ *
161
+ * The module exports a singleton (`export const tracer = new Tracer()`), so
162
+ * this constructor runs on `import "@shashu-ai/sdk"`. Throwing here would
163
+ * make importing the SDK fail for anyone who has not set the variable, which
164
+ * is a far worse failure than the one this is fixing. Instead the address
165
+ * stays undefined and {@link flush} posts nothing — the same shape as the
166
+ * Python SDK's telemetry path, which resolves with optional_base_url and
167
+ * no-ops the flush.
168
+ */
169
+ constructor() {
170
+ this.buffer = [];
171
+ this.flushTimer = null;
172
+ this._gatewayUrl = optionalBaseUrl();
173
+ this._apiKey = envGet(API_KEY_ENV);
174
+ }
175
+ /**
176
+ * Current gateway base URL (respects configure()), or undefined when none is
177
+ * configured. Undefined means telemetry is not sent — never a default host.
178
+ */
179
+ get gatewayUrl() {
180
+ return this._gatewayUrl;
181
+ }
182
+ /** Current API key (respects configure()). */
183
+ get apiKey() {
184
+ return this._apiKey;
185
+ }
186
+ /**
187
+ * Update gateway URL and/or API key at runtime (e.g. for scripts switching agents).
188
+ * baseUrl has its trailing slash stripped to match constructor behavior.
189
+ */
190
+ configure(opts) {
191
+ if (opts.baseUrl !== void 0) {
192
+ this._gatewayUrl = opts.baseUrl.replace(/\/$/, "");
193
+ }
194
+ if (opts.apiKey !== void 0) {
195
+ this._apiKey = opts.apiKey;
196
+ }
197
+ }
198
+ // --- Context Accessors ---
199
+ get traceId() {
200
+ return spanStorage.getStore()?.traceId ?? a2aStorage.getStore()?.traceId;
201
+ }
202
+ get currentSpanId() {
203
+ const store = spanStorage.getStore();
204
+ return store?.spanId;
205
+ }
206
+ /** The current span's PARENT span id; undefined at origin or for a root span. */
207
+ get parentSpanId() {
208
+ const store = spanStorage.getStore();
209
+ return store?.parentId;
210
+ }
211
+ get isActive() {
212
+ return !!spanStorage.getStore();
213
+ }
214
+ // --- A2A inbound-capture + outbound propagation (ADR-007 §0, §4.1 locked) ---
215
+ /** True when this context CAPTURED an inbound flow — so a downstream gateway call
216
+ * PROPAGATES the trace and attaches caller/session/hop lineage rather than originate
217
+ * a new flow. False = origin (header set unchanged). */
218
+ get isA2aHop() {
219
+ const s = a2aStorage.getStore();
220
+ return !!(s && s.traceId);
221
+ }
222
+ /** The captured inbound session id, or undefined when none was propagated. */
223
+ get sessionId() {
224
+ return a2aStorage.getStore()?.sessionId || void 0;
225
+ }
226
+ /** Advisory inbound hop depth captured from x-shashu-hop-depth (0 if absent). */
227
+ get inboundHopDepth() {
228
+ return a2aStorage.getStore()?.inboundHopDepth ?? 0;
229
+ }
230
+ /** Hop depth to advertise on the next downstream call = inbound + 1 (advisory; the
231
+ * gateway recounts authoritatively). */
232
+ get outboundHopDepth() {
233
+ return this.inboundHopDepth + 1;
234
+ }
235
+ /** The captured inbound x-shashu-caller-agent-id — the upstream agent that INVOKED
236
+ * this hop. The SDK FORWARDS this on the outbound gateway call so the gateway records
237
+ * the real (invoker -> this agent) edge, NEVER this agent's own id (§4.1). undefined at
238
+ * origin / caller-stripped. */
239
+ get inboundCallerAgentId() {
240
+ return a2aStorage.getStore()?.inboundCallerAgentId || void 0;
241
+ }
242
+ /**
243
+ * Capture an inbound flow from the headers of a request this agent is SERVING into the
244
+ * AsyncLocalStorage store, so a downstream call made through the SDK propagates the SAME
245
+ * flow (WP-A2A-4 / ADR-007 §0). Reads (case-insensitively) x-shashu-trace-id (the flow
246
+ * id), -session-id, -hop-depth, and -caller-agent-id (the upstream INVOKER). The captured
247
+ * trace is PROPAGATED on the next outbound call (never re-minted); the session, inbound hop
248
+ * depth, and inbound caller ride along — the caller is FORWARDED on the gateway call (§4.1),
249
+ * never replaced by self.
250
+ *
251
+ * Uses enterWith, so the capture persists for the remainder of the current async execution
252
+ * (one-shot, for a script serving a single inbound call). Servers handling many requests
253
+ * should prefer {@link incoming} so one flow's lineage never leaks into the next. No inbound
254
+ * trace ⇒ origin: the ambient capture is cleared and false is returned (non-A2A unaffected).
255
+ * Never throws — telemetry must not break a request.
256
+ */
257
+ captureIncoming(headers) {
258
+ const capture = captureFromHeaders(coerceHeaderMap(headers));
259
+ a2aStorage.enterWith(capture);
260
+ return capture !== void 0;
261
+ }
262
+ /**
263
+ * Scoped inbound capture: capture for the duration of serving ONE request, then restore
264
+ * the prior context on exit — so a long-lived worker does not leak one flow's lineage into
265
+ * the next. Prefer this in servers; {@link captureIncoming} is the one-shot for scripts.
266
+ *
267
+ * @example
268
+ * await tracer.incoming(req.headers, async () => {
269
+ * await tg.fetch("/v1/chat/completions", { ... }); // propagates the captured flow
270
+ * });
271
+ */
272
+ incoming(headers, callback) {
273
+ const capture = captureFromHeaders(coerceHeaderMap(headers));
274
+ return a2aStorage.run(capture, callback);
275
+ }
276
+ // --- Main Logic ---
277
+ /**
278
+ * Wraps a callback in a new Span Context.
279
+ * Automatically handles Header injection for any internal calls.
280
+ */
281
+ async span(name, callback, metadata) {
282
+ const parent = spanStorage.getStore();
283
+ const traceId = parent?.traceId ?? a2aStorage.getStore()?.traceId ?? (0, import_node_crypto.randomUUID)();
284
+ const spanId = (0, import_node_crypto.randomUUID)();
285
+ const parentId = parent?.spanId;
286
+ const context = { traceId, spanId, parentId };
287
+ const startTime = Date.now() / 1e3;
288
+ try {
289
+ return await spanStorage.run(context, async () => {
290
+ return await callback(spanId);
291
+ });
292
+ } finally {
293
+ const endTime = Date.now() / 1e3;
294
+ this.record({
295
+ trace_id: traceId,
296
+ span_id: spanId,
297
+ parent_span_id: parentId,
298
+ name,
299
+ start_time: startTime,
300
+ end_time: endTime,
301
+ duration: endTime - startTime,
302
+ metadata
303
+ });
304
+ }
305
+ }
306
+ // --- Telemetry Transport ---
307
+ record(span) {
308
+ if (isDisabled()) return;
309
+ this.buffer.push(span);
310
+ if (this.buffer.length >= 10) {
311
+ this.flush();
312
+ } else if (!this.flushTimer) {
313
+ this.flushTimer = setTimeout(() => this.flush(), 1e3);
314
+ this.flushTimer.unref();
315
+ }
316
+ }
317
+ async flush() {
318
+ if (this.flushTimer) {
319
+ clearTimeout(this.flushTimer);
320
+ this.flushTimer = null;
321
+ }
322
+ if (isDisabled()) return;
323
+ if (this.buffer.length === 0 || !this._apiKey || !this._gatewayUrl) return;
324
+ const batch = [...this.buffer];
325
+ this.buffer = [];
326
+ try {
327
+ await fetch(`${this._gatewayUrl}/api/telemetry/spans`, {
328
+ method: "POST",
329
+ headers: {
330
+ "Content-Type": "application/json",
331
+ Authorization: `Bearer ${this._apiKey}`
332
+ },
333
+ body: JSON.stringify(batch)
334
+ });
335
+ } catch {
336
+ }
337
+ }
338
+ };
339
+ var tracer = new Tracer();
340
+
341
+ // src/context.ts
342
+ var HEADER_PREFIX = "x-shashu";
343
+ var SOURCE_TOOL_HEADER = "x-shashu-source-tool";
344
+ var DEFAULT_CONTRACT_VERSION = "2026-09-01";
345
+ var CONTRACT_VERSION_HEADER = "shashu-version";
346
+ function applyContractVersion(headers, contractVersion) {
347
+ if (contractVersion === null) return headers;
348
+ const named = Object.keys(headers).some((k) => k.toLowerCase() === CONTRACT_VERSION_HEADER);
349
+ if (!named) headers[CONTRACT_VERSION_HEADER] = contractVersion ?? DEFAULT_CONTRACT_VERSION;
350
+ return headers;
351
+ }
352
+ var N8N_KEYS = [
353
+ "N8N_WORKFLOW_ID",
354
+ "N8N_EXECUTION_ID",
355
+ "N8N_WORKFLOW_NAME",
356
+ "N8N_EXECUTION_MODE"
357
+ ];
358
+ var VERCEL_KEYS = [
359
+ "VERCEL",
360
+ "VERCEL_ENV",
361
+ "VERCEL_URL",
362
+ "VERCEL_GIT_COMMIT_REF",
363
+ "VERCEL_GIT_REPO_ID",
364
+ "VERCEL_GIT_COMMIT_SHA"
365
+ ];
366
+ var GITHUB_KEYS = [
367
+ "GITHUB_ACTION",
368
+ "GITHUB_ACTIONS",
369
+ "GITHUB_WORKFLOW",
370
+ "GITHUB_RUN_ID",
371
+ "GITHUB_RUN_NUMBER",
372
+ "GITHUB_REPOSITORY",
373
+ "GITHUB_SHA"
374
+ ];
375
+ function pickEnv(keys) {
376
+ const out = {};
377
+ for (const key of keys) {
378
+ const v = process.env[key];
379
+ if (v !== void 0 && v !== "") out[key] = v;
380
+ }
381
+ return out;
382
+ }
383
+ function getBaseMetadata() {
384
+ return {
385
+ sdk_version: SDK_VERSION,
386
+ node_version: process.version,
387
+ os: process.platform,
388
+ arch: process.arch
389
+ };
390
+ }
391
+ function getWorkflowContextFromEnv() {
392
+ const baseMeta = getBaseMetadata();
393
+ const n8n = pickEnv(N8N_KEYS);
394
+ if (Object.keys(n8n).length > 0) {
395
+ return {
396
+ source: "n8n",
397
+ workflow_id: n8n.N8N_WORKFLOW_ID,
398
+ execution_id: n8n.N8N_EXECUTION_ID,
399
+ metadata: { ...baseMeta, ...n8n }
400
+ };
401
+ }
402
+ const vercel = pickEnv(VERCEL_KEYS);
403
+ if (Object.keys(vercel).length > 0) {
404
+ return {
405
+ source: "vercel",
406
+ workflow_id: vercel.VERCEL_GIT_REPO_ID || vercel.VERCEL_URL,
407
+ execution_id: vercel.VERCEL_GIT_COMMIT_SHA,
408
+ metadata: { ...baseMeta, ...vercel }
409
+ };
410
+ }
411
+ const github = pickEnv(GITHUB_KEYS);
412
+ if (Object.keys(github).length > 0) {
413
+ return {
414
+ source: "github",
415
+ workflow_id: github.GITHUB_WORKFLOW || github.GITHUB_REPOSITORY,
416
+ execution_id: github.GITHUB_RUN_ID || github.GITHUB_RUN_NUMBER,
417
+ metadata: { ...baseMeta, ...github }
418
+ };
419
+ }
420
+ return {
421
+ source: "local_script",
422
+ metadata: baseMeta
423
+ };
424
+ }
425
+ function buildSourceToolJson(ctx) {
426
+ const meta = ctx.metadata ?? getBaseMetadata();
427
+ const payload = {
428
+ source: ctx.source,
429
+ metadata: meta
430
+ };
431
+ if (ctx.workflow_id !== void 0) payload.workflow_id = ctx.workflow_id;
432
+ if (ctx.execution_id !== void 0) payload.execution_id = ctx.execution_id;
433
+ if (ctx.workflow_step !== void 0) payload.workflow_step = ctx.workflow_step;
434
+ return JSON.stringify(payload);
435
+ }
436
+ var TRUSTLOG_HEADER_PREFIX = "x-trustlog-";
437
+ function resolveOriginTraceId() {
438
+ const n8n = process.env.N8N_EXECUTION_ID;
439
+ if (n8n) return n8n;
440
+ const github = process.env.GITHUB_RUN_ID;
441
+ if (github) return github;
442
+ const gitlab = process.env.CI_PIPELINE_ID;
443
+ if (process.env.GITLAB_CI && gitlab) return gitlab;
444
+ return (0, import_node_crypto2.randomUUID)();
445
+ }
446
+ function lowercaseHeaderKeys(h) {
447
+ const out = {};
448
+ for (const [k, v] of Object.entries(h)) out[k.toLowerCase()] = v;
449
+ return out;
450
+ }
451
+ function buildContextHeaders(ctx, session) {
452
+ const meta = ctx.metadata ?? getBaseMetadata();
453
+ const h = {
454
+ [SOURCE_TOOL_HEADER]: buildSourceToolJson({ ...ctx, metadata: meta }),
455
+ [`${HEADER_PREFIX}-source`]: ctx.source
456
+ };
457
+ if (ctx.workflow_id) h[`${HEADER_PREFIX}-workflow-id`] = ctx.workflow_id;
458
+ if (ctx.execution_id) h[`${HEADER_PREFIX}-execution-id`] = ctx.execution_id;
459
+ if (ctx.workflow_step) h[`${HEADER_PREFIX}-workflow-step`] = ctx.workflow_step;
460
+ for (const [k, v] of Object.entries(meta)) {
461
+ if (v) h[`${TRUSTLOG_HEADER_PREFIX}${k.replace(/_/g, "-")}`] = String(v);
462
+ }
463
+ if (tracer.isActive) {
464
+ if (tracer.traceId) h["x-shashu-trace-id"] = tracer.traceId;
465
+ h["x-shashu-span-id"] = tracer.currentSpanId ?? "";
466
+ h["x-shashu-parent-id"] = tracer.parentSpanId ?? "";
467
+ } else if (tracer.isA2aHop) {
468
+ if (tracer.traceId) h["x-shashu-trace-id"] = tracer.traceId;
469
+ } else if (!h["x-shashu-trace-id"]) {
470
+ h["x-shashu-trace-id"] = resolveOriginTraceId();
471
+ }
472
+ const sessionId = resolveSessionId(session);
473
+ if (sessionId) h["x-shashu-session-id"] = sessionId;
474
+ if (tracer.isA2aHop) {
475
+ const inboundCaller = tracer.inboundCallerAgentId;
476
+ if (inboundCaller) h["x-shashu-caller-agent-id"] = inboundCaller;
477
+ h["x-shashu-hop-depth"] = String(tracer.outboundHopDepth);
478
+ }
479
+ return lowercaseHeaderKeys(h);
480
+ }
481
+ function resolveSessionId(opts) {
482
+ if (opts?.requestSessionId != null && String(opts.requestSessionId) !== "") {
483
+ return String(opts.requestSessionId);
484
+ }
485
+ const captured = tracer.sessionId;
486
+ if (captured) return captured;
487
+ if (opts?.defaultSessionId != null && String(opts.defaultSessionId) !== "") {
488
+ return String(opts.defaultSessionId);
489
+ }
490
+ return void 0;
491
+ }
492
+
493
+ // src/_bus.ts
494
+ var import_node_async_hooks2 = require("async_hooks");
495
+ var MAX_DOCS = 64;
496
+ var MAX_CORPUS_CHARS = 256;
497
+ var EMPTY = Object.freeze([]);
498
+ var BUS = new import_node_async_hooks2.AsyncLocalStorage();
499
+ function current() {
500
+ return BUS.getStore()?.events ?? EMPTY;
501
+ }
502
+ function snapshot() {
503
+ return current();
504
+ }
505
+ function clear() {
506
+ const store = BUS.getStore();
507
+ if (store) {
508
+ store.events = EMPTY;
509
+ return;
510
+ }
511
+ BUS.enterWith({ events: EMPTY, shared: false });
512
+ }
513
+ function hasEvents() {
514
+ return current().length > 0;
515
+ }
516
+
517
+ // src/rag.ts
518
+ function attachRagContext(body, ragContext) {
519
+ if (body === null || typeof body !== "object") {
520
+ throw new TypeError("body must be an object");
521
+ }
522
+ if (ragContext === null || typeof ragContext !== "object") {
523
+ throw new TypeError("ragContext must be an object");
524
+ }
525
+ const existing = body.shashu_metadata;
526
+ const meta = existing !== null && typeof existing === "object" ? existing : {};
527
+ meta.rag_context = ragContext;
528
+ body.shashu_metadata = meta;
529
+ return body;
530
+ }
531
+ var PREVIEW_KEYS = ["preview", "text", "content", "pageContent", "page_content", "body"];
532
+ var ID_KEYS = [
533
+ "id",
534
+ "doc_id",
535
+ "docId",
536
+ "documentId",
537
+ "document_id",
538
+ "nodeId",
539
+ "node_id",
540
+ "id_",
541
+ "_id"
542
+ ];
543
+ var SCORE_KEYS = ["score", "similarity", "relevance"];
544
+ var SOURCE_URI_KEYS = [
545
+ "source_uri",
546
+ "sourceUri",
547
+ "url",
548
+ "uri",
549
+ "source",
550
+ "file_path",
551
+ "filePath",
552
+ "file_name",
553
+ "fileName"
554
+ ];
555
+ var HASH_KEYS = ["hash", "sha256", "digest"];
556
+ var FIELD_KEYS = [
557
+ ["preview", PREVIEW_KEYS],
558
+ ["id", ID_KEYS],
559
+ ["score", SCORE_KEYS],
560
+ ["source_uri", SOURCE_URI_KEYS],
561
+ ["hash", HASH_KEYS]
562
+ ];
563
+ function has(...props) {
564
+ return (doc) => typeof doc === "object" && doc !== null && props.every((p) => doc[p] !== void 0);
565
+ }
566
+ var isObject = (doc) => typeof doc === "object" && doc !== null;
567
+ function gather(doc) {
568
+ const found = {};
569
+ for (const [field, keys] of FIELD_KEYS) {
570
+ for (const key of keys) {
571
+ const value = doc[key];
572
+ if (value !== void 0 && value !== null) {
573
+ found[field] = value;
574
+ break;
575
+ }
576
+ }
577
+ }
578
+ const metadata = doc.metadata;
579
+ if (isObject(metadata)) {
580
+ for (const [field, keys] of FIELD_KEYS) {
581
+ if (found[field] !== void 0 || field === "preview") continue;
582
+ for (const key of keys) {
583
+ const value = metadata[key];
584
+ if (value !== void 0 && value !== null) {
585
+ found[field] = value;
586
+ break;
587
+ }
588
+ }
589
+ }
590
+ }
591
+ return found;
592
+ }
593
+ function fromScoredNode(doc) {
594
+ const inner = readDocument(doc.node);
595
+ return doc.score !== void 0 && doc.score !== null ? { ...inner, score: doc.score } : inner;
596
+ }
597
+ var COERCIONS = [
598
+ { name: "string", matches: (d) => typeof d === "string", read: (d) => ({ preview: d }) },
599
+ { name: "scored_node", matches: has("node"), read: fromScoredNode },
600
+ { name: "langchain_document", matches: has("pageContent"), read: gather },
601
+ { name: "preview_object", matches: has("preview"), read: gather },
602
+ { name: "text_node", matches: has("text"), read: gather },
603
+ { name: "object", matches: isObject, read: gather }
604
+ ];
605
+ function readDocument(doc) {
606
+ for (const rule of COERCIONS) {
607
+ if (rule.matches(doc)) return rule.read(doc);
608
+ }
609
+ return {};
610
+ }
611
+ function dedupe(docs) {
612
+ const seen = /* @__PURE__ */ new Set();
613
+ const out = [];
614
+ for (const doc of docs) {
615
+ const key = `${doc.id}\0${doc.preview}`;
616
+ if (seen.has(key)) continue;
617
+ seen.add(key);
618
+ out.push(doc);
619
+ }
620
+ return out;
621
+ }
622
+ function buildRagContext(events) {
623
+ events = events.filter((event) => event.kind !== "memory");
624
+ const docs = dedupe(events.flatMap((event) => event.docs)).slice(-MAX_DOCS);
625
+ if (docs.length === 0) return void 0;
626
+ const corpora = [...new Set(events.map((event) => event.corpus))];
627
+ const corpus = corpora.length === 1 ? corpora[0] : corpora.join("+").slice(0, MAX_CORPUS_CHARS).replace(/\++$/, "");
628
+ const sources = new Set(events.map((event) => event.source));
629
+ const queries = events.map((event) => event.query).filter((q) => !!q);
630
+ const context = {
631
+ v: 1,
632
+ corpus,
633
+ source: sources.size === 1 ? [...sources][0] : "other",
634
+ docs
635
+ };
636
+ if (queries.length) context.query = queries[queries.length - 1];
637
+ return context;
638
+ }
639
+
640
+ // src/memory.ts
641
+ function buildMemoryContext(events) {
642
+ const mem = events.filter((e) => e.kind === "memory");
643
+ const items = mem.flatMap((e) => e.docs.map((d) => ({ id: d.id, preview: d.preview }))).slice(-MAX_DOCS);
644
+ if (items.length === 0) return void 0;
645
+ const stores = [...new Set(mem.map((e) => e.corpus))];
646
+ const sources = new Set(mem.map((e) => e.source));
647
+ const scope = mem[mem.length - 1]?.query || "agent";
648
+ return {
649
+ v: 1,
650
+ store: stores.length === 1 ? stores[0] : stores.join("+").slice(0, MAX_CORPUS_CHARS),
651
+ scope,
652
+ source: sources.size === 1 ? [...sources][0] : "other",
653
+ items
654
+ };
655
+ }
656
+ function attachMemoryContext(body, memoryContext) {
657
+ const bag = body;
658
+ const existing = bag.shashu_metadata;
659
+ const metadata = existing !== null && typeof existing === "object" ? existing : {};
660
+ bag.shashu_metadata = { ...metadata, memory_context: memoryContext };
661
+ return body;
662
+ }
663
+
664
+ // src/_joiner.ts
665
+ var globalFetch = (input, init) => globalThis.fetch(input, init);
666
+ function parseJsonObject(body) {
667
+ if (typeof body !== "string") return void 0;
668
+ if (!/^[\s]*\{/.test(body)) return void 0;
669
+ try {
670
+ const parsed = JSON.parse(body);
671
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
672
+ } catch {
673
+ return void 0;
674
+ }
675
+ }
676
+ function metadataBag(body) {
677
+ const metadata = body.shashu_metadata;
678
+ if (metadata !== null && typeof metadata === "object") {
679
+ return metadata;
680
+ }
681
+ return void 0;
682
+ }
683
+ function hasExplicitRagContext(body) {
684
+ const metadata = metadataBag(body);
685
+ return metadata?.rag_context !== void 0 && metadata?.rag_context !== null;
686
+ }
687
+ function hasExplicitMemoryContext(body) {
688
+ const metadata = metadataBag(body);
689
+ return metadata?.memory_context !== void 0 && metadata?.memory_context !== null;
690
+ }
691
+ function fixContentLength(headers, byteLength2) {
692
+ const value = String(byteLength2);
693
+ if (headers instanceof Headers) {
694
+ if (headers.has("content-length")) headers.set("content-length", value);
695
+ return headers;
696
+ }
697
+ if (Array.isArray(headers)) {
698
+ return headers.map(
699
+ (pair) => Array.isArray(pair) && String(pair[0]).toLowerCase() === "content-length" ? [pair[0], value] : pair
700
+ );
701
+ }
702
+ if (headers !== null && typeof headers === "object") {
703
+ const out = { ...headers };
704
+ for (const key of Object.keys(out)) {
705
+ if (key.toLowerCase() === "content-length") out[key] = value;
706
+ }
707
+ return out;
708
+ }
709
+ return headers;
710
+ }
711
+ function hasConflictingCorpora(events) {
712
+ if (events.length <= 1) return false;
713
+ const first = events[0].corpus;
714
+ for (let i = 1; i < events.length; i += 1) {
715
+ if (events[i].corpus !== first) return true;
716
+ }
717
+ return false;
718
+ }
719
+ function takeContextFor(body) {
720
+ const events = snapshot();
721
+ const ragEvents = events.filter((e) => e.kind !== "memory");
722
+ const memEvents = events.filter((e) => e.kind === "memory");
723
+ const explicitRag = hasExplicitRagContext(body);
724
+ const explicitMem = hasExplicitMemoryContext(body);
725
+ clear();
726
+ let mutated = false;
727
+ if (!explicitRag) {
728
+ if (hasConflictingCorpora(ragEvents)) {
729
+ } else {
730
+ const context = buildRagContext(ragEvents);
731
+ if (context !== void 0) {
732
+ attachRagContext(body, context);
733
+ mutated = true;
734
+ }
735
+ }
736
+ }
737
+ if (!explicitMem) {
738
+ const memoryContext = buildMemoryContext(memEvents);
739
+ if (memoryContext !== void 0) {
740
+ attachMemoryContext(body, memoryContext);
741
+ mutated = true;
742
+ }
743
+ }
744
+ return mutated ? body : void 0;
745
+ }
746
+ function withRetrievalJoiner(underlying = globalFetch) {
747
+ return async function trustgateJoiningFetch(input, init) {
748
+ if (!hasEvents()) return underlying(input, init);
749
+ if (isDisabled()) {
750
+ clear();
751
+ return underlying(input, init);
752
+ }
753
+ try {
754
+ if (typeof Request !== "undefined" && input instanceof Request) {
755
+ const body2 = parseJsonObject(await input.clone().text());
756
+ if (body2 === void 0) return underlying(input, init);
757
+ const merged2 = takeContextFor(body2);
758
+ if (merged2 === void 0) return underlying(input, init);
759
+ const encoded2 = JSON.stringify(merged2);
760
+ const replacement = new Request(input, { body: encoded2 });
761
+ if (replacement.headers.has("content-length")) {
762
+ replacement.headers.set("content-length", String(byteLength(encoded2)));
763
+ }
764
+ return underlying(replacement, init);
765
+ }
766
+ const body = parseJsonObject(init?.body);
767
+ if (body === void 0) return underlying(input, init);
768
+ const merged = takeContextFor(body);
769
+ if (merged === void 0) return underlying(input, init);
770
+ const encoded = JSON.stringify(merged);
771
+ return underlying(input, {
772
+ ...init,
773
+ body: encoded,
774
+ headers: fixContentLength(init?.headers, byteLength(encoded))
775
+ });
776
+ } catch {
777
+ return underlying(input, init);
778
+ }
779
+ };
780
+ }
781
+ function byteLength(text) {
782
+ return new TextEncoder().encode(text).length;
783
+ }
784
+
785
+ // src/credential.ts
786
+ var BOTH_OR_NEITHER = "Give either a SHASHU key or a token provider, not both.";
787
+ var REFRESH_SKEW_SECONDS = 60;
788
+ var PASS_PROVIDER_NOT_SET_UP = "pass_provider_not_set_up";
789
+ var PASS_NOT_LICENSED = "pass_not_licensed";
790
+ var PASS_EXPIRED = "pass_expired";
791
+ var PASS_WRONG_AUDIENCE = "pass_wrong_audience";
792
+ var PASS_WRONG_ISSUER = "pass_wrong_issuer";
793
+ var PASS_UNKNOWN_AGENT = "pass_unknown_agent";
794
+ var PASS_CODES = [
795
+ PASS_PROVIDER_NOT_SET_UP,
796
+ PASS_NOT_LICENSED,
797
+ PASS_EXPIRED,
798
+ PASS_WRONG_AUDIENCE,
799
+ PASS_WRONG_ISSUER,
800
+ PASS_UNKNOWN_AGENT
801
+ ];
802
+ var RETRY_CODES = /* @__PURE__ */ new Set([PASS_EXPIRED]);
803
+ function jwtExpUnverified(token) {
804
+ const parts = token.split(".");
805
+ if (parts.length !== 3) return null;
806
+ const payload = parts[1];
807
+ const pad = "=".repeat((4 - payload.length % 4) % 4);
808
+ try {
809
+ const json = Buffer.from(payload + pad, "base64url").toString("utf8");
810
+ const data = JSON.parse(json);
811
+ if (data.exp == null) return null;
812
+ const exp = Number(data.exp);
813
+ return Number.isFinite(exp) ? exp : null;
814
+ } catch {
815
+ return null;
816
+ }
817
+ }
818
+ function passRefusalCodeFromText(text) {
819
+ try {
820
+ const parsed = JSON.parse(text);
821
+ const code = parsed?.error?.code;
822
+ return typeof code === "string" && PASS_CODES.includes(code) ? code : null;
823
+ } catch {
824
+ return null;
825
+ }
826
+ }
827
+ function shouldRetryPassRefused(opts) {
828
+ if (!opts.usesProvider || opts.bytesDelivered || opts.status !== 401) return false;
829
+ return opts.code != null && RETRY_CODES.has(opts.code);
830
+ }
831
+ var CredentialResolver = class {
832
+ constructor(opts) {
833
+ const envKey = envGet(API_KEY_ENV) ?? void 0;
834
+ const hasKeyArg = opts.apiKey !== void 0;
835
+ const hasProvider = opts.tokenProvider !== void 0;
836
+ if (hasKeyArg && hasProvider) throw new ShashuConfigError(BOTH_OR_NEITHER);
837
+ if (hasProvider && envKey && !hasKeyArg) throw new ShashuConfigError(BOTH_OR_NEITHER);
838
+ if (opts.requireOne && !hasProvider && !hasKeyArg && !envKey) {
839
+ throw new ShashuConfigError(BOTH_OR_NEITHER);
840
+ }
841
+ this.provider = opts.tokenProvider;
842
+ this.staticKey = hasProvider ? void 0 : hasKeyArg ? opts.apiKey : envKey;
843
+ }
844
+ get usesProvider() {
845
+ return this.provider !== void 0;
846
+ }
847
+ async get() {
848
+ if (!this.provider) return this.staticKey;
849
+ if (this.cached && !this.needsRefresh(this.cached)) return this.cached;
850
+ if (this.inflight) return this.inflight;
851
+ this.inflight = (async () => {
852
+ const token = await this.provider();
853
+ this.cached = String(token);
854
+ this.inflight = void 0;
855
+ return this.cached;
856
+ })().catch((err) => {
857
+ this.inflight = void 0;
858
+ throw err;
859
+ });
860
+ return this.inflight;
861
+ }
862
+ invalidate() {
863
+ this.cached = void 0;
864
+ }
865
+ needsRefresh(token) {
866
+ const exp = jwtExpUnverified(token);
867
+ if (exp == null) return true;
868
+ return Date.now() / 1e3 >= exp - REFRESH_SKEW_SECONDS;
869
+ }
870
+ };
871
+
872
+ // src/middleware/vercel-ai.ts
873
+ function getShashuHeaders(workflowContext, sessionId, contractVersion) {
874
+ const ctx = workflowContext ?? getWorkflowContextFromEnv();
875
+ return applyContractVersion(
876
+ buildContextHeaders(ctx, sessionId ? { defaultSessionId: sessionId } : void 0),
877
+ contractVersion
878
+ );
879
+ }
880
+ function createShashuOpenAIOptions(options) {
881
+ if (isDisabled()) return {};
882
+ const baseUrl = requireBaseUrl(options.baseUrl, {
883
+ entryPoint: "createShashuOpenAIOptions()"
884
+ });
885
+ const resolver = new CredentialResolver({
886
+ apiKey: options.apiKey,
887
+ tokenProvider: options.tokenProvider
888
+ });
889
+ const headers = {
890
+ ...options.headers,
891
+ ...getShashuHeaders(options.workflowContext, options.sessionId ?? (0, import_node_crypto3.randomUUID)(), null)
892
+ };
893
+ applyContractVersion(headers, options.contractVersion);
894
+ const joining = withRetrievalJoiner();
895
+ const fetch2 = async (input, init) => {
896
+ const token = await resolver.get();
897
+ const next = new Headers(init?.headers);
898
+ if (token) next.set("authorization", `Bearer ${token}`);
899
+ const send = () => joining(input, { ...init, headers: next });
900
+ const res = await send();
901
+ if (!resolver.usesProvider || res.status !== 401) return res;
902
+ const code = passRefusalCodeFromText(await res.clone().text());
903
+ if (!shouldRetryPassRefused({
904
+ usesProvider: true,
905
+ status: res.status,
906
+ code,
907
+ bytesDelivered: false
908
+ })) {
909
+ return res;
910
+ }
911
+ resolver.invalidate();
912
+ const retryToken = await resolver.get();
913
+ if (retryToken) next.set("authorization", `Bearer ${retryToken}`);
914
+ return joining(input, { ...init, headers: next });
915
+ };
916
+ return {
917
+ baseURL: baseUrl,
918
+ apiKey: resolver.usesProvider ? void 0 : options.openaiApiKey ?? options.apiKey,
919
+ headers: Object.keys(headers).length ? headers : void 0,
920
+ fetch: fetch2
921
+ };
922
+ }
923
+ // Annotate the CommonJS export names for ESM import in node:
924
+ 0 && (module.exports = {
925
+ createShashuOpenAIOptions,
926
+ getShashuHeaders
927
+ });