@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.
- package/CHANGELOG.md +16 -0
- package/README.md +36 -5
- package/package.json +2 -2
- package/dist/_joiner-D_FGAaoc.d.cts +0 -38
- package/dist/_joiner-D_FGAaoc.d.ts +0 -38
- package/dist/chunk-CWC6GQTL.js +0 -800
- package/dist/chunk-K4ZIXS2U.js +0 -40
- package/dist/chunk-MLFWJAEH.js +0 -74
- package/dist/chunk-MZGHCDWX.js +0 -530
- package/dist/chunk-TI45NK2R.js +0 -71
- package/dist/chunk-YSAQRZFP.js +0 -343
- package/dist/index.cjs +0 -2580
- package/dist/index.d.cts +0 -748
- package/dist/index.d.ts +0 -748
- package/dist/index.js +0 -974
- package/dist/langchain-CoNoZ_vQ.d.cts +0 -322
- package/dist/langchain-D9Xo9IMm.d.ts +0 -322
- package/dist/middleware/anthropic.cjs +0 -930
- package/dist/middleware/anthropic.d.cts +0 -49
- package/dist/middleware/anthropic.d.ts +0 -49
- package/dist/middleware/anthropic.js +0 -10
- package/dist/middleware/google.cjs +0 -530
- package/dist/middleware/google.d.cts +0 -71
- package/dist/middleware/google.d.ts +0 -71
- package/dist/middleware/google.js +0 -9
- package/dist/middleware/langchain.cjs +0 -1342
- package/dist/middleware/langchain.d.cts +0 -3
- package/dist/middleware/langchain.d.ts +0 -3
- package/dist/middleware/langchain.js +0 -22
- package/dist/middleware/vercel-ai.cjs +0 -927
- package/dist/middleware/vercel-ai.d.cts +0 -70
- package/dist/middleware/vercel-ai.d.ts +0 -70
- package/dist/middleware/vercel-ai.js +0 -10
- package/dist/types-BQVfxZJP.d.cts +0 -448
- package/dist/types-BQVfxZJP.d.ts +0 -448
|
@@ -1,1342 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __create = Object.create;
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __export = (target, all) => {
|
|
9
|
-
for (var name in all)
|
|
10
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
-
};
|
|
12
|
-
var __copyProps = (to, from, except, desc) => {
|
|
13
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
-
for (let key of __getOwnPropNames(from))
|
|
15
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
-
}
|
|
18
|
-
return to;
|
|
19
|
-
};
|
|
20
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
-
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
-
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
-
mod
|
|
27
|
-
));
|
|
28
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
-
|
|
30
|
-
// src/middleware/langchain.ts
|
|
31
|
-
var langchain_exports = {};
|
|
32
|
-
__export(langchain_exports, {
|
|
33
|
-
DEFAULT_CORPUS: () => DEFAULT_CORPUS,
|
|
34
|
-
SOURCE: () => SOURCE,
|
|
35
|
-
ShashuLangChainCallback: () => ShashuLangChainCallback,
|
|
36
|
-
createShashuLangChainConfig: () => createShashuLangChainConfig,
|
|
37
|
-
install: () => install,
|
|
38
|
-
isInstalled: () => isInstalled,
|
|
39
|
-
lcDocumentsToRagContext: () => lcDocumentsToRagContext,
|
|
40
|
-
uninstall: () => uninstall
|
|
41
|
-
});
|
|
42
|
-
module.exports = __toCommonJS(langchain_exports);
|
|
43
|
-
var import_node_crypto3 = require("crypto");
|
|
44
|
-
|
|
45
|
-
// src/types.ts
|
|
46
|
-
var ShashuError = class _ShashuError extends Error {
|
|
47
|
-
/**
|
|
48
|
-
* Why a route was refused for the data in the request, off the decision.
|
|
49
|
-
* Set on a `route_data_policy` refusal, so an app can say which route is not
|
|
50
|
-
* approved for which category without parsing the message.
|
|
51
|
-
*/
|
|
52
|
-
get routePolicy() {
|
|
53
|
-
return this.decision?.routePolicy;
|
|
54
|
-
}
|
|
55
|
-
constructor(message, status, body, details) {
|
|
56
|
-
super(message);
|
|
57
|
-
this.name = "ShashuError";
|
|
58
|
-
this.status = status;
|
|
59
|
-
this.body = body;
|
|
60
|
-
this.type = details?.type;
|
|
61
|
-
this.code = details?.code;
|
|
62
|
-
this.decision = details?.decision;
|
|
63
|
-
this.responseHeaders = details?.responseHeaders;
|
|
64
|
-
Object.setPrototypeOf(this, _ShashuError.prototype);
|
|
65
|
-
}
|
|
66
|
-
};
|
|
67
|
-
|
|
68
|
-
// src/exceptions.ts
|
|
69
|
-
var ShashuConfigError = class _ShashuConfigError extends ShashuError {
|
|
70
|
-
constructor(message) {
|
|
71
|
-
super(message, 0);
|
|
72
|
-
this.name = "ShashuConfigError";
|
|
73
|
-
Object.setPrototypeOf(this, _ShashuConfigError.prototype);
|
|
74
|
-
}
|
|
75
|
-
};
|
|
76
|
-
function rateLimitDetail(err) {
|
|
77
|
-
const inner = err?.details?.error;
|
|
78
|
-
return inner && typeof inner === "object" ? inner : {};
|
|
79
|
-
}
|
|
80
|
-
function gatewayRetryAfter(res, parsedBody) {
|
|
81
|
-
const fromHeader = parseRetryAfter(res.headers.get("retry-after"));
|
|
82
|
-
if (fromHeader !== void 0) return fromHeader;
|
|
83
|
-
if (!parsedBody || typeof parsedBody !== "object") return void 0;
|
|
84
|
-
const err = parsedBody.error;
|
|
85
|
-
const seconds = rateLimitDetail(err).retry_after_seconds;
|
|
86
|
-
return typeof seconds === "number" ? seconds : void 0;
|
|
87
|
-
}
|
|
88
|
-
function parseRetryAfter(value) {
|
|
89
|
-
if (!value) return void 0;
|
|
90
|
-
const trimmed = value.trim();
|
|
91
|
-
const asInt = Number(trimmed);
|
|
92
|
-
if (Number.isFinite(asInt)) return asInt;
|
|
93
|
-
const asDate = Date.parse(trimmed);
|
|
94
|
-
if (!Number.isNaN(asDate)) {
|
|
95
|
-
return Math.max(0, (asDate - Date.now()) / 1e3);
|
|
96
|
-
}
|
|
97
|
-
return void 0;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
// src/config.ts
|
|
101
|
-
var BASE_URL_ENV = "SHASHU_BASE_URL";
|
|
102
|
-
var API_KEY_ENV = "SHASHU_API_KEY";
|
|
103
|
-
var DISABLE_ENV = "SHASHU_DISABLE";
|
|
104
|
-
var TRUTHY = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);
|
|
105
|
-
function env() {
|
|
106
|
-
return typeof process !== "undefined" && process.env ? process.env : {};
|
|
107
|
-
}
|
|
108
|
-
function envGet(current2, _legacy) {
|
|
109
|
-
const now = (env()[current2] ?? "").trim();
|
|
110
|
-
return now || void 0;
|
|
111
|
-
}
|
|
112
|
-
function isDisabled() {
|
|
113
|
-
return TRUTHY.has((envGet(DISABLE_ENV) ?? "").trim().toLowerCase());
|
|
114
|
-
}
|
|
115
|
-
function firstConfigured(baseUrl, envVars) {
|
|
116
|
-
if (baseUrl && baseUrl.trim()) return baseUrl.trim().replace(/\/+$/, "");
|
|
117
|
-
for (const name of envVars) {
|
|
118
|
-
const value = env()[name]?.trim();
|
|
119
|
-
if (value) return value.replace(/\/+$/, "");
|
|
120
|
-
}
|
|
121
|
-
return void 0;
|
|
122
|
-
}
|
|
123
|
-
function optionalBaseUrl(baseUrl, envVars = [BASE_URL_ENV]) {
|
|
124
|
-
return firstConfigured(baseUrl, envVars);
|
|
125
|
-
}
|
|
126
|
-
function requireBaseUrl(baseUrl, opts) {
|
|
127
|
-
const envVars = opts.envVars ?? [BASE_URL_ENV];
|
|
128
|
-
const resolved = firstConfigured(baseUrl, envVars);
|
|
129
|
-
if (resolved) return resolved;
|
|
130
|
-
const option = opts.option ?? "baseUrl";
|
|
131
|
-
const envHint = envVars.length === 1 ? `set the ${envVars[0]} environment variable` : `set one of the ${envVars.join(" or ")} environment variables`;
|
|
132
|
-
throw new ShashuConfigError(
|
|
133
|
-
`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.`
|
|
134
|
-
);
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
// src/context.ts
|
|
138
|
-
var import_node_crypto2 = require("crypto");
|
|
139
|
-
|
|
140
|
-
// src/version.ts
|
|
141
|
-
var SDK_VERSION = "1.2.0";
|
|
142
|
-
|
|
143
|
-
// src/tracer.ts
|
|
144
|
-
var import_node_async_hooks = require("async_hooks");
|
|
145
|
-
var import_node_crypto = require("crypto");
|
|
146
|
-
var spanStorage = new import_node_async_hooks.AsyncLocalStorage();
|
|
147
|
-
var a2aStorage = new import_node_async_hooks.AsyncLocalStorage();
|
|
148
|
-
function coerceHeaderMap(headers) {
|
|
149
|
-
const out = {};
|
|
150
|
-
if (!headers) return out;
|
|
151
|
-
try {
|
|
152
|
-
if (Array.isArray(headers)) {
|
|
153
|
-
for (const pair of headers) {
|
|
154
|
-
if (Array.isArray(pair) && pair.length >= 2 && pair[0] != null) {
|
|
155
|
-
out[String(pair[0]).toLowerCase()] = String(pair[1]);
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
return out;
|
|
159
|
-
}
|
|
160
|
-
if (headers instanceof Map) {
|
|
161
|
-
for (const [k, v] of headers) out[String(k).toLowerCase()] = String(v);
|
|
162
|
-
return out;
|
|
163
|
-
}
|
|
164
|
-
if (typeof headers.forEach === "function") {
|
|
165
|
-
headers.forEach((v, k) => {
|
|
166
|
-
if (k != null) out[String(k).toLowerCase()] = String(v);
|
|
167
|
-
});
|
|
168
|
-
return out;
|
|
169
|
-
}
|
|
170
|
-
if (typeof headers === "object") {
|
|
171
|
-
for (const [k, v] of Object.entries(headers)) {
|
|
172
|
-
if (v !== void 0 && v !== null) out[k.toLowerCase()] = String(v);
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
} catch {
|
|
176
|
-
return out;
|
|
177
|
-
}
|
|
178
|
-
return out;
|
|
179
|
-
}
|
|
180
|
-
function parseHopDepth(raw) {
|
|
181
|
-
const n = parseInt(String(raw ?? "").trim(), 10);
|
|
182
|
-
return Number.isFinite(n) && n > 0 ? n : 0;
|
|
183
|
-
}
|
|
184
|
-
function captureFromHeaders(h) {
|
|
185
|
-
const trace = (h["x-shashu-trace-id"] ?? "").trim();
|
|
186
|
-
if (!trace) return void 0;
|
|
187
|
-
const session = (h["x-shashu-session-id"] ?? "").trim();
|
|
188
|
-
const caller = (h["x-shashu-caller-agent-id"] ?? "").trim();
|
|
189
|
-
return {
|
|
190
|
-
traceId: trace,
|
|
191
|
-
sessionId: session || void 0,
|
|
192
|
-
inboundHopDepth: parseHopDepth(h["x-shashu-hop-depth"]),
|
|
193
|
-
inboundCallerAgentId: caller || void 0
|
|
194
|
-
};
|
|
195
|
-
}
|
|
196
|
-
var Tracer = class {
|
|
197
|
-
/**
|
|
198
|
-
* Resolves the address OPTIONALLY, unlike every other entry point.
|
|
199
|
-
*
|
|
200
|
-
* The module exports a singleton (`export const tracer = new Tracer()`), so
|
|
201
|
-
* this constructor runs on `import "@shashu-ai/sdk"`. Throwing here would
|
|
202
|
-
* make importing the SDK fail for anyone who has not set the variable, which
|
|
203
|
-
* is a far worse failure than the one this is fixing. Instead the address
|
|
204
|
-
* stays undefined and {@link flush} posts nothing — the same shape as the
|
|
205
|
-
* Python SDK's telemetry path, which resolves with optional_base_url and
|
|
206
|
-
* no-ops the flush.
|
|
207
|
-
*/
|
|
208
|
-
constructor() {
|
|
209
|
-
this.buffer = [];
|
|
210
|
-
this.flushTimer = null;
|
|
211
|
-
this._gatewayUrl = optionalBaseUrl();
|
|
212
|
-
this._apiKey = envGet(API_KEY_ENV);
|
|
213
|
-
}
|
|
214
|
-
/**
|
|
215
|
-
* Current gateway base URL (respects configure()), or undefined when none is
|
|
216
|
-
* configured. Undefined means telemetry is not sent — never a default host.
|
|
217
|
-
*/
|
|
218
|
-
get gatewayUrl() {
|
|
219
|
-
return this._gatewayUrl;
|
|
220
|
-
}
|
|
221
|
-
/** Current API key (respects configure()). */
|
|
222
|
-
get apiKey() {
|
|
223
|
-
return this._apiKey;
|
|
224
|
-
}
|
|
225
|
-
/**
|
|
226
|
-
* Update gateway URL and/or API key at runtime (e.g. for scripts switching agents).
|
|
227
|
-
* baseUrl has its trailing slash stripped to match constructor behavior.
|
|
228
|
-
*/
|
|
229
|
-
configure(opts) {
|
|
230
|
-
if (opts.baseUrl !== void 0) {
|
|
231
|
-
this._gatewayUrl = opts.baseUrl.replace(/\/$/, "");
|
|
232
|
-
}
|
|
233
|
-
if (opts.apiKey !== void 0) {
|
|
234
|
-
this._apiKey = opts.apiKey;
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
// --- Context Accessors ---
|
|
238
|
-
get traceId() {
|
|
239
|
-
return spanStorage.getStore()?.traceId ?? a2aStorage.getStore()?.traceId;
|
|
240
|
-
}
|
|
241
|
-
get currentSpanId() {
|
|
242
|
-
const store = spanStorage.getStore();
|
|
243
|
-
return store?.spanId;
|
|
244
|
-
}
|
|
245
|
-
/** The current span's PARENT span id; undefined at origin or for a root span. */
|
|
246
|
-
get parentSpanId() {
|
|
247
|
-
const store = spanStorage.getStore();
|
|
248
|
-
return store?.parentId;
|
|
249
|
-
}
|
|
250
|
-
get isActive() {
|
|
251
|
-
return !!spanStorage.getStore();
|
|
252
|
-
}
|
|
253
|
-
// --- A2A inbound-capture + outbound propagation (ADR-007 §0, §4.1 locked) ---
|
|
254
|
-
/** True when this context CAPTURED an inbound flow — so a downstream gateway call
|
|
255
|
-
* PROPAGATES the trace and attaches caller/session/hop lineage rather than originate
|
|
256
|
-
* a new flow. False = origin (header set unchanged). */
|
|
257
|
-
get isA2aHop() {
|
|
258
|
-
const s = a2aStorage.getStore();
|
|
259
|
-
return !!(s && s.traceId);
|
|
260
|
-
}
|
|
261
|
-
/** The captured inbound session id, or undefined when none was propagated. */
|
|
262
|
-
get sessionId() {
|
|
263
|
-
return a2aStorage.getStore()?.sessionId || void 0;
|
|
264
|
-
}
|
|
265
|
-
/** Advisory inbound hop depth captured from x-shashu-hop-depth (0 if absent). */
|
|
266
|
-
get inboundHopDepth() {
|
|
267
|
-
return a2aStorage.getStore()?.inboundHopDepth ?? 0;
|
|
268
|
-
}
|
|
269
|
-
/** Hop depth to advertise on the next downstream call = inbound + 1 (advisory; the
|
|
270
|
-
* gateway recounts authoritatively). */
|
|
271
|
-
get outboundHopDepth() {
|
|
272
|
-
return this.inboundHopDepth + 1;
|
|
273
|
-
}
|
|
274
|
-
/** The captured inbound x-shashu-caller-agent-id — the upstream agent that INVOKED
|
|
275
|
-
* this hop. The SDK FORWARDS this on the outbound gateway call so the gateway records
|
|
276
|
-
* the real (invoker -> this agent) edge, NEVER this agent's own id (§4.1). undefined at
|
|
277
|
-
* origin / caller-stripped. */
|
|
278
|
-
get inboundCallerAgentId() {
|
|
279
|
-
return a2aStorage.getStore()?.inboundCallerAgentId || void 0;
|
|
280
|
-
}
|
|
281
|
-
/**
|
|
282
|
-
* Capture an inbound flow from the headers of a request this agent is SERVING into the
|
|
283
|
-
* AsyncLocalStorage store, so a downstream call made through the SDK propagates the SAME
|
|
284
|
-
* flow (WP-A2A-4 / ADR-007 §0). Reads (case-insensitively) x-shashu-trace-id (the flow
|
|
285
|
-
* id), -session-id, -hop-depth, and -caller-agent-id (the upstream INVOKER). The captured
|
|
286
|
-
* trace is PROPAGATED on the next outbound call (never re-minted); the session, inbound hop
|
|
287
|
-
* depth, and inbound caller ride along — the caller is FORWARDED on the gateway call (§4.1),
|
|
288
|
-
* never replaced by self.
|
|
289
|
-
*
|
|
290
|
-
* Uses enterWith, so the capture persists for the remainder of the current async execution
|
|
291
|
-
* (one-shot, for a script serving a single inbound call). Servers handling many requests
|
|
292
|
-
* should prefer {@link incoming} so one flow's lineage never leaks into the next. No inbound
|
|
293
|
-
* trace ⇒ origin: the ambient capture is cleared and false is returned (non-A2A unaffected).
|
|
294
|
-
* Never throws — telemetry must not break a request.
|
|
295
|
-
*/
|
|
296
|
-
captureIncoming(headers) {
|
|
297
|
-
const capture = captureFromHeaders(coerceHeaderMap(headers));
|
|
298
|
-
a2aStorage.enterWith(capture);
|
|
299
|
-
return capture !== void 0;
|
|
300
|
-
}
|
|
301
|
-
/**
|
|
302
|
-
* Scoped inbound capture: capture for the duration of serving ONE request, then restore
|
|
303
|
-
* the prior context on exit — so a long-lived worker does not leak one flow's lineage into
|
|
304
|
-
* the next. Prefer this in servers; {@link captureIncoming} is the one-shot for scripts.
|
|
305
|
-
*
|
|
306
|
-
* @example
|
|
307
|
-
* await tracer.incoming(req.headers, async () => {
|
|
308
|
-
* await tg.fetch("/v1/chat/completions", { ... }); // propagates the captured flow
|
|
309
|
-
* });
|
|
310
|
-
*/
|
|
311
|
-
incoming(headers, callback) {
|
|
312
|
-
const capture = captureFromHeaders(coerceHeaderMap(headers));
|
|
313
|
-
return a2aStorage.run(capture, callback);
|
|
314
|
-
}
|
|
315
|
-
// --- Main Logic ---
|
|
316
|
-
/**
|
|
317
|
-
* Wraps a callback in a new Span Context.
|
|
318
|
-
* Automatically handles Header injection for any internal calls.
|
|
319
|
-
*/
|
|
320
|
-
async span(name, callback, metadata) {
|
|
321
|
-
const parent = spanStorage.getStore();
|
|
322
|
-
const traceId = parent?.traceId ?? a2aStorage.getStore()?.traceId ?? (0, import_node_crypto.randomUUID)();
|
|
323
|
-
const spanId = (0, import_node_crypto.randomUUID)();
|
|
324
|
-
const parentId = parent?.spanId;
|
|
325
|
-
const context = { traceId, spanId, parentId };
|
|
326
|
-
const startTime = Date.now() / 1e3;
|
|
327
|
-
try {
|
|
328
|
-
return await spanStorage.run(context, async () => {
|
|
329
|
-
return await callback(spanId);
|
|
330
|
-
});
|
|
331
|
-
} finally {
|
|
332
|
-
const endTime = Date.now() / 1e3;
|
|
333
|
-
this.record({
|
|
334
|
-
trace_id: traceId,
|
|
335
|
-
span_id: spanId,
|
|
336
|
-
parent_span_id: parentId,
|
|
337
|
-
name,
|
|
338
|
-
start_time: startTime,
|
|
339
|
-
end_time: endTime,
|
|
340
|
-
duration: endTime - startTime,
|
|
341
|
-
metadata
|
|
342
|
-
});
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
// --- Telemetry Transport ---
|
|
346
|
-
record(span) {
|
|
347
|
-
if (isDisabled()) return;
|
|
348
|
-
this.buffer.push(span);
|
|
349
|
-
if (this.buffer.length >= 10) {
|
|
350
|
-
this.flush();
|
|
351
|
-
} else if (!this.flushTimer) {
|
|
352
|
-
this.flushTimer = setTimeout(() => this.flush(), 1e3);
|
|
353
|
-
this.flushTimer.unref();
|
|
354
|
-
}
|
|
355
|
-
}
|
|
356
|
-
async flush() {
|
|
357
|
-
if (this.flushTimer) {
|
|
358
|
-
clearTimeout(this.flushTimer);
|
|
359
|
-
this.flushTimer = null;
|
|
360
|
-
}
|
|
361
|
-
if (isDisabled()) return;
|
|
362
|
-
if (this.buffer.length === 0 || !this._apiKey || !this._gatewayUrl) return;
|
|
363
|
-
const batch = [...this.buffer];
|
|
364
|
-
this.buffer = [];
|
|
365
|
-
try {
|
|
366
|
-
await fetch(`${this._gatewayUrl}/api/telemetry/spans`, {
|
|
367
|
-
method: "POST",
|
|
368
|
-
headers: {
|
|
369
|
-
"Content-Type": "application/json",
|
|
370
|
-
Authorization: `Bearer ${this._apiKey}`
|
|
371
|
-
},
|
|
372
|
-
body: JSON.stringify(batch)
|
|
373
|
-
});
|
|
374
|
-
} catch {
|
|
375
|
-
}
|
|
376
|
-
}
|
|
377
|
-
};
|
|
378
|
-
var tracer = new Tracer();
|
|
379
|
-
|
|
380
|
-
// src/context.ts
|
|
381
|
-
var HEADER_PREFIX = "x-shashu";
|
|
382
|
-
var SOURCE_TOOL_HEADER = "x-shashu-source-tool";
|
|
383
|
-
var DEFAULT_CONTRACT_VERSION = "2026-09-01";
|
|
384
|
-
var CONTRACT_VERSION_HEADER = "shashu-version";
|
|
385
|
-
function applyContractVersion(headers, contractVersion) {
|
|
386
|
-
if (contractVersion === null) return headers;
|
|
387
|
-
const named = Object.keys(headers).some((k) => k.toLowerCase() === CONTRACT_VERSION_HEADER);
|
|
388
|
-
if (!named) headers[CONTRACT_VERSION_HEADER] = contractVersion ?? DEFAULT_CONTRACT_VERSION;
|
|
389
|
-
return headers;
|
|
390
|
-
}
|
|
391
|
-
var N8N_KEYS = [
|
|
392
|
-
"N8N_WORKFLOW_ID",
|
|
393
|
-
"N8N_EXECUTION_ID",
|
|
394
|
-
"N8N_WORKFLOW_NAME",
|
|
395
|
-
"N8N_EXECUTION_MODE"
|
|
396
|
-
];
|
|
397
|
-
var VERCEL_KEYS = [
|
|
398
|
-
"VERCEL",
|
|
399
|
-
"VERCEL_ENV",
|
|
400
|
-
"VERCEL_URL",
|
|
401
|
-
"VERCEL_GIT_COMMIT_REF",
|
|
402
|
-
"VERCEL_GIT_REPO_ID",
|
|
403
|
-
"VERCEL_GIT_COMMIT_SHA"
|
|
404
|
-
];
|
|
405
|
-
var GITHUB_KEYS = [
|
|
406
|
-
"GITHUB_ACTION",
|
|
407
|
-
"GITHUB_ACTIONS",
|
|
408
|
-
"GITHUB_WORKFLOW",
|
|
409
|
-
"GITHUB_RUN_ID",
|
|
410
|
-
"GITHUB_RUN_NUMBER",
|
|
411
|
-
"GITHUB_REPOSITORY",
|
|
412
|
-
"GITHUB_SHA"
|
|
413
|
-
];
|
|
414
|
-
function pickEnv(keys) {
|
|
415
|
-
const out = {};
|
|
416
|
-
for (const key of keys) {
|
|
417
|
-
const v = process.env[key];
|
|
418
|
-
if (v !== void 0 && v !== "") out[key] = v;
|
|
419
|
-
}
|
|
420
|
-
return out;
|
|
421
|
-
}
|
|
422
|
-
function getBaseMetadata() {
|
|
423
|
-
return {
|
|
424
|
-
sdk_version: SDK_VERSION,
|
|
425
|
-
node_version: process.version,
|
|
426
|
-
os: process.platform,
|
|
427
|
-
arch: process.arch
|
|
428
|
-
};
|
|
429
|
-
}
|
|
430
|
-
function getWorkflowContextFromEnv() {
|
|
431
|
-
const baseMeta = getBaseMetadata();
|
|
432
|
-
const n8n = pickEnv(N8N_KEYS);
|
|
433
|
-
if (Object.keys(n8n).length > 0) {
|
|
434
|
-
return {
|
|
435
|
-
source: "n8n",
|
|
436
|
-
workflow_id: n8n.N8N_WORKFLOW_ID,
|
|
437
|
-
execution_id: n8n.N8N_EXECUTION_ID,
|
|
438
|
-
metadata: { ...baseMeta, ...n8n }
|
|
439
|
-
};
|
|
440
|
-
}
|
|
441
|
-
const vercel = pickEnv(VERCEL_KEYS);
|
|
442
|
-
if (Object.keys(vercel).length > 0) {
|
|
443
|
-
return {
|
|
444
|
-
source: "vercel",
|
|
445
|
-
workflow_id: vercel.VERCEL_GIT_REPO_ID || vercel.VERCEL_URL,
|
|
446
|
-
execution_id: vercel.VERCEL_GIT_COMMIT_SHA,
|
|
447
|
-
metadata: { ...baseMeta, ...vercel }
|
|
448
|
-
};
|
|
449
|
-
}
|
|
450
|
-
const github = pickEnv(GITHUB_KEYS);
|
|
451
|
-
if (Object.keys(github).length > 0) {
|
|
452
|
-
return {
|
|
453
|
-
source: "github",
|
|
454
|
-
workflow_id: github.GITHUB_WORKFLOW || github.GITHUB_REPOSITORY,
|
|
455
|
-
execution_id: github.GITHUB_RUN_ID || github.GITHUB_RUN_NUMBER,
|
|
456
|
-
metadata: { ...baseMeta, ...github }
|
|
457
|
-
};
|
|
458
|
-
}
|
|
459
|
-
return {
|
|
460
|
-
source: "local_script",
|
|
461
|
-
metadata: baseMeta
|
|
462
|
-
};
|
|
463
|
-
}
|
|
464
|
-
function buildSourceToolJson(ctx) {
|
|
465
|
-
const meta = ctx.metadata ?? getBaseMetadata();
|
|
466
|
-
const payload = {
|
|
467
|
-
source: ctx.source,
|
|
468
|
-
metadata: meta
|
|
469
|
-
};
|
|
470
|
-
if (ctx.workflow_id !== void 0) payload.workflow_id = ctx.workflow_id;
|
|
471
|
-
if (ctx.execution_id !== void 0) payload.execution_id = ctx.execution_id;
|
|
472
|
-
if (ctx.workflow_step !== void 0) payload.workflow_step = ctx.workflow_step;
|
|
473
|
-
return JSON.stringify(payload);
|
|
474
|
-
}
|
|
475
|
-
var TRUSTLOG_HEADER_PREFIX = "x-trustlog-";
|
|
476
|
-
function resolveOriginTraceId() {
|
|
477
|
-
const n8n = process.env.N8N_EXECUTION_ID;
|
|
478
|
-
if (n8n) return n8n;
|
|
479
|
-
const github = process.env.GITHUB_RUN_ID;
|
|
480
|
-
if (github) return github;
|
|
481
|
-
const gitlab = process.env.CI_PIPELINE_ID;
|
|
482
|
-
if (process.env.GITLAB_CI && gitlab) return gitlab;
|
|
483
|
-
return (0, import_node_crypto2.randomUUID)();
|
|
484
|
-
}
|
|
485
|
-
function lowercaseHeaderKeys(h) {
|
|
486
|
-
const out = {};
|
|
487
|
-
for (const [k, v] of Object.entries(h)) out[k.toLowerCase()] = v;
|
|
488
|
-
return out;
|
|
489
|
-
}
|
|
490
|
-
function buildContextHeaders(ctx, session) {
|
|
491
|
-
const meta = ctx.metadata ?? getBaseMetadata();
|
|
492
|
-
const h = {
|
|
493
|
-
[SOURCE_TOOL_HEADER]: buildSourceToolJson({ ...ctx, metadata: meta }),
|
|
494
|
-
[`${HEADER_PREFIX}-source`]: ctx.source
|
|
495
|
-
};
|
|
496
|
-
if (ctx.workflow_id) h[`${HEADER_PREFIX}-workflow-id`] = ctx.workflow_id;
|
|
497
|
-
if (ctx.execution_id) h[`${HEADER_PREFIX}-execution-id`] = ctx.execution_id;
|
|
498
|
-
if (ctx.workflow_step) h[`${HEADER_PREFIX}-workflow-step`] = ctx.workflow_step;
|
|
499
|
-
for (const [k, v] of Object.entries(meta)) {
|
|
500
|
-
if (v) h[`${TRUSTLOG_HEADER_PREFIX}${k.replace(/_/g, "-")}`] = String(v);
|
|
501
|
-
}
|
|
502
|
-
if (tracer.isActive) {
|
|
503
|
-
if (tracer.traceId) h["x-shashu-trace-id"] = tracer.traceId;
|
|
504
|
-
h["x-shashu-span-id"] = tracer.currentSpanId ?? "";
|
|
505
|
-
h["x-shashu-parent-id"] = tracer.parentSpanId ?? "";
|
|
506
|
-
} else if (tracer.isA2aHop) {
|
|
507
|
-
if (tracer.traceId) h["x-shashu-trace-id"] = tracer.traceId;
|
|
508
|
-
} else if (!h["x-shashu-trace-id"]) {
|
|
509
|
-
h["x-shashu-trace-id"] = resolveOriginTraceId();
|
|
510
|
-
}
|
|
511
|
-
const sessionId = resolveSessionId(session);
|
|
512
|
-
if (sessionId) h["x-shashu-session-id"] = sessionId;
|
|
513
|
-
if (tracer.isA2aHop) {
|
|
514
|
-
const inboundCaller = tracer.inboundCallerAgentId;
|
|
515
|
-
if (inboundCaller) h["x-shashu-caller-agent-id"] = inboundCaller;
|
|
516
|
-
h["x-shashu-hop-depth"] = String(tracer.outboundHopDepth);
|
|
517
|
-
}
|
|
518
|
-
return lowercaseHeaderKeys(h);
|
|
519
|
-
}
|
|
520
|
-
function resolveSessionId(opts) {
|
|
521
|
-
if (opts?.requestSessionId != null && String(opts.requestSessionId) !== "") {
|
|
522
|
-
return String(opts.requestSessionId);
|
|
523
|
-
}
|
|
524
|
-
const captured2 = tracer.sessionId;
|
|
525
|
-
if (captured2) return captured2;
|
|
526
|
-
if (opts?.defaultSessionId != null && String(opts.defaultSessionId) !== "") {
|
|
527
|
-
return String(opts.defaultSessionId);
|
|
528
|
-
}
|
|
529
|
-
return void 0;
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
// src/_bus.ts
|
|
533
|
-
var import_node_async_hooks2 = require("async_hooks");
|
|
534
|
-
var MAX_EVENTS = 8;
|
|
535
|
-
var MAX_DOCS = 64;
|
|
536
|
-
var MAX_PREVIEW_CHARS = 2048;
|
|
537
|
-
var MAX_CORPUS_CHARS = 256;
|
|
538
|
-
var MAX_QUERY_CHARS = 4096;
|
|
539
|
-
var EMPTY = Object.freeze([]);
|
|
540
|
-
var BUS = new import_node_async_hooks2.AsyncLocalStorage();
|
|
541
|
-
function current() {
|
|
542
|
-
return BUS.getStore()?.events ?? EMPTY;
|
|
543
|
-
}
|
|
544
|
-
function push(event) {
|
|
545
|
-
if (!event.docs || event.docs.length === 0) return;
|
|
546
|
-
const store = BUS.getStore();
|
|
547
|
-
const next = trim([...store?.events ?? EMPTY, event]);
|
|
548
|
-
if (store?.shared) {
|
|
549
|
-
store.events = next;
|
|
550
|
-
return;
|
|
551
|
-
}
|
|
552
|
-
BUS.enterWith({ events: next, shared: false });
|
|
553
|
-
}
|
|
554
|
-
function snapshot() {
|
|
555
|
-
return current();
|
|
556
|
-
}
|
|
557
|
-
function clear() {
|
|
558
|
-
const store = BUS.getStore();
|
|
559
|
-
if (store) {
|
|
560
|
-
store.events = EMPTY;
|
|
561
|
-
return;
|
|
562
|
-
}
|
|
563
|
-
BUS.enterWith({ events: EMPTY, shared: false });
|
|
564
|
-
}
|
|
565
|
-
function hasEvents() {
|
|
566
|
-
return current().length > 0;
|
|
567
|
-
}
|
|
568
|
-
function trim(events) {
|
|
569
|
-
const recent = events.slice(-MAX_EVENTS);
|
|
570
|
-
let budget = MAX_DOCS;
|
|
571
|
-
const kept = [];
|
|
572
|
-
for (let i = recent.length - 1; i >= 0; i -= 1) {
|
|
573
|
-
if (budget <= 0) break;
|
|
574
|
-
const event = recent[i];
|
|
575
|
-
if (event.docs.length > budget) {
|
|
576
|
-
kept.push({ ...event, docs: event.docs.slice(-budget) });
|
|
577
|
-
budget = 0;
|
|
578
|
-
} else {
|
|
579
|
-
budget -= event.docs.length;
|
|
580
|
-
kept.push(event);
|
|
581
|
-
}
|
|
582
|
-
}
|
|
583
|
-
kept.reverse();
|
|
584
|
-
return Object.freeze(kept);
|
|
585
|
-
}
|
|
586
|
-
|
|
587
|
-
// src/rag.ts
|
|
588
|
-
function attachRagContext(body, ragContext) {
|
|
589
|
-
if (body === null || typeof body !== "object") {
|
|
590
|
-
throw new TypeError("body must be an object");
|
|
591
|
-
}
|
|
592
|
-
if (ragContext === null || typeof ragContext !== "object") {
|
|
593
|
-
throw new TypeError("ragContext must be an object");
|
|
594
|
-
}
|
|
595
|
-
const existing = body.shashu_metadata;
|
|
596
|
-
const meta = existing !== null && typeof existing === "object" ? existing : {};
|
|
597
|
-
meta.rag_context = ragContext;
|
|
598
|
-
body.shashu_metadata = meta;
|
|
599
|
-
return body;
|
|
600
|
-
}
|
|
601
|
-
var SOURCES = [
|
|
602
|
-
"manual",
|
|
603
|
-
"langchain",
|
|
604
|
-
"llamaindex",
|
|
605
|
-
"tool",
|
|
606
|
-
"otel",
|
|
607
|
-
"n8n",
|
|
608
|
-
"provider",
|
|
609
|
-
"other"
|
|
610
|
-
];
|
|
611
|
-
var HEX = /^[0-9a-fA-F]{8,64}$/;
|
|
612
|
-
var SCORE_MIN = -1;
|
|
613
|
-
var SCORE_MAX = 1e6;
|
|
614
|
-
var MAX_ID_CHARS = 512;
|
|
615
|
-
var MAX_SOURCE_URI_CHARS = 2048;
|
|
616
|
-
var PREVIEW_KEYS = ["preview", "text", "content", "pageContent", "page_content", "body"];
|
|
617
|
-
var ID_KEYS = [
|
|
618
|
-
"id",
|
|
619
|
-
"doc_id",
|
|
620
|
-
"docId",
|
|
621
|
-
"documentId",
|
|
622
|
-
"document_id",
|
|
623
|
-
"nodeId",
|
|
624
|
-
"node_id",
|
|
625
|
-
"id_",
|
|
626
|
-
"_id"
|
|
627
|
-
];
|
|
628
|
-
var SCORE_KEYS = ["score", "similarity", "relevance"];
|
|
629
|
-
var SOURCE_URI_KEYS = [
|
|
630
|
-
"source_uri",
|
|
631
|
-
"sourceUri",
|
|
632
|
-
"url",
|
|
633
|
-
"uri",
|
|
634
|
-
"source",
|
|
635
|
-
"file_path",
|
|
636
|
-
"filePath",
|
|
637
|
-
"file_name",
|
|
638
|
-
"fileName"
|
|
639
|
-
];
|
|
640
|
-
var HASH_KEYS = ["hash", "sha256", "digest"];
|
|
641
|
-
var FIELD_KEYS = [
|
|
642
|
-
["preview", PREVIEW_KEYS],
|
|
643
|
-
["id", ID_KEYS],
|
|
644
|
-
["score", SCORE_KEYS],
|
|
645
|
-
["source_uri", SOURCE_URI_KEYS],
|
|
646
|
-
["hash", HASH_KEYS]
|
|
647
|
-
];
|
|
648
|
-
function has(...props) {
|
|
649
|
-
return (doc) => typeof doc === "object" && doc !== null && props.every((p) => doc[p] !== void 0);
|
|
650
|
-
}
|
|
651
|
-
var isObject = (doc) => typeof doc === "object" && doc !== null;
|
|
652
|
-
function gather(doc) {
|
|
653
|
-
const found = {};
|
|
654
|
-
for (const [field, keys] of FIELD_KEYS) {
|
|
655
|
-
for (const key of keys) {
|
|
656
|
-
const value = doc[key];
|
|
657
|
-
if (value !== void 0 && value !== null) {
|
|
658
|
-
found[field] = value;
|
|
659
|
-
break;
|
|
660
|
-
}
|
|
661
|
-
}
|
|
662
|
-
}
|
|
663
|
-
const metadata = doc.metadata;
|
|
664
|
-
if (isObject(metadata)) {
|
|
665
|
-
for (const [field, keys] of FIELD_KEYS) {
|
|
666
|
-
if (found[field] !== void 0 || field === "preview") continue;
|
|
667
|
-
for (const key of keys) {
|
|
668
|
-
const value = metadata[key];
|
|
669
|
-
if (value !== void 0 && value !== null) {
|
|
670
|
-
found[field] = value;
|
|
671
|
-
break;
|
|
672
|
-
}
|
|
673
|
-
}
|
|
674
|
-
}
|
|
675
|
-
}
|
|
676
|
-
return found;
|
|
677
|
-
}
|
|
678
|
-
function fromScoredNode(doc) {
|
|
679
|
-
const inner = readDocument(doc.node);
|
|
680
|
-
return doc.score !== void 0 && doc.score !== null ? { ...inner, score: doc.score } : inner;
|
|
681
|
-
}
|
|
682
|
-
var COERCIONS = [
|
|
683
|
-
{ name: "string", matches: (d) => typeof d === "string", read: (d) => ({ preview: d }) },
|
|
684
|
-
{ name: "scored_node", matches: has("node"), read: fromScoredNode },
|
|
685
|
-
{ name: "langchain_document", matches: has("pageContent"), read: gather },
|
|
686
|
-
{ name: "preview_object", matches: has("preview"), read: gather },
|
|
687
|
-
{ name: "text_node", matches: has("text"), read: gather },
|
|
688
|
-
{ name: "object", matches: isObject, read: gather }
|
|
689
|
-
];
|
|
690
|
-
function readDocument(doc) {
|
|
691
|
-
for (const rule of COERCIONS) {
|
|
692
|
-
if (rule.matches(doc)) return rule.read(doc);
|
|
693
|
-
}
|
|
694
|
-
return {};
|
|
695
|
-
}
|
|
696
|
-
function asText(value, limit) {
|
|
697
|
-
if (typeof value !== "string") return void 0;
|
|
698
|
-
return value.slice(0, limit) || void 0;
|
|
699
|
-
}
|
|
700
|
-
function asId(value, position) {
|
|
701
|
-
if (typeof value === "string") {
|
|
702
|
-
const cleaned = value.trim().slice(0, MAX_ID_CHARS);
|
|
703
|
-
if (cleaned) return cleaned;
|
|
704
|
-
}
|
|
705
|
-
if (typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
706
|
-
return `doc-${position}`;
|
|
707
|
-
}
|
|
708
|
-
function asScore(value) {
|
|
709
|
-
let candidate = value;
|
|
710
|
-
if (typeof candidate === "string") {
|
|
711
|
-
if (!candidate.trim()) return void 0;
|
|
712
|
-
const parsed = Number(candidate);
|
|
713
|
-
if (Number.isNaN(parsed)) return void 0;
|
|
714
|
-
candidate = parsed;
|
|
715
|
-
}
|
|
716
|
-
if (typeof candidate !== "number") return void 0;
|
|
717
|
-
if (!Number.isFinite(candidate) || candidate < SCORE_MIN || candidate > SCORE_MAX) {
|
|
718
|
-
return void 0;
|
|
719
|
-
}
|
|
720
|
-
return candidate;
|
|
721
|
-
}
|
|
722
|
-
function normalise(raw, position) {
|
|
723
|
-
const preview = asText(raw.preview, MAX_PREVIEW_CHARS);
|
|
724
|
-
if (preview === void 0) return void 0;
|
|
725
|
-
const out = { id: asId(raw.id, position), preview };
|
|
726
|
-
const score = asScore(raw.score);
|
|
727
|
-
if (score !== void 0) out.score = score;
|
|
728
|
-
const sourceUri = asText(raw.source_uri, MAX_SOURCE_URI_CHARS);
|
|
729
|
-
if (sourceUri !== void 0) out.source_uri = sourceUri;
|
|
730
|
-
if (typeof raw.hash === "string" && HEX.test(raw.hash)) out.hash = raw.hash;
|
|
731
|
-
return out;
|
|
732
|
-
}
|
|
733
|
-
function asDocumentList(docs) {
|
|
734
|
-
if (typeof docs === "string") return [docs];
|
|
735
|
-
if (Array.isArray(docs)) return docs;
|
|
736
|
-
if (isObject(docs) && typeof docs[Symbol.iterator] === "function") {
|
|
737
|
-
return Array.from(docs);
|
|
738
|
-
}
|
|
739
|
-
return [docs];
|
|
740
|
-
}
|
|
741
|
-
function coerceDocs(docs) {
|
|
742
|
-
const out = [];
|
|
743
|
-
let position = 0;
|
|
744
|
-
for (const doc of asDocumentList(docs)) {
|
|
745
|
-
position += 1;
|
|
746
|
-
const normalised = normalise(readDocument(doc), position);
|
|
747
|
-
if (normalised !== void 0) out.push(normalised);
|
|
748
|
-
}
|
|
749
|
-
return out;
|
|
750
|
-
}
|
|
751
|
-
function requireCorpus(corpus) {
|
|
752
|
-
if (typeof corpus !== "string" || !corpus.trim()) {
|
|
753
|
-
throw new TypeError(
|
|
754
|
-
"declareRetrieval() needs a non-empty corpus: it is what the gateway records the documents as having come from, and rag_context.v1 requires it."
|
|
755
|
-
);
|
|
756
|
-
}
|
|
757
|
-
return corpus.trim().slice(0, MAX_CORPUS_CHARS);
|
|
758
|
-
}
|
|
759
|
-
function requireSource(source) {
|
|
760
|
-
if (!SOURCES.includes(source)) {
|
|
761
|
-
throw new TypeError(
|
|
762
|
-
`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.`
|
|
763
|
-
);
|
|
764
|
-
}
|
|
765
|
-
return source;
|
|
766
|
-
}
|
|
767
|
-
function declareRetrieval(docs, options) {
|
|
768
|
-
if (isDisabled()) return;
|
|
769
|
-
const corpus = requireCorpus(options.corpus);
|
|
770
|
-
const source = requireSource(options.source ?? "manual");
|
|
771
|
-
push({
|
|
772
|
-
corpus,
|
|
773
|
-
query: asText(options.query, MAX_QUERY_CHARS),
|
|
774
|
-
source,
|
|
775
|
-
docs: coerceDocs(docs)
|
|
776
|
-
});
|
|
777
|
-
}
|
|
778
|
-
function dedupe(docs) {
|
|
779
|
-
const seen = /* @__PURE__ */ new Set();
|
|
780
|
-
const out = [];
|
|
781
|
-
for (const doc of docs) {
|
|
782
|
-
const key = `${doc.id}\0${doc.preview}`;
|
|
783
|
-
if (seen.has(key)) continue;
|
|
784
|
-
seen.add(key);
|
|
785
|
-
out.push(doc);
|
|
786
|
-
}
|
|
787
|
-
return out;
|
|
788
|
-
}
|
|
789
|
-
function buildRagContext(events) {
|
|
790
|
-
events = events.filter((event) => event.kind !== "memory");
|
|
791
|
-
const docs = dedupe(events.flatMap((event) => event.docs)).slice(-MAX_DOCS);
|
|
792
|
-
if (docs.length === 0) return void 0;
|
|
793
|
-
const corpora = [...new Set(events.map((event) => event.corpus))];
|
|
794
|
-
const corpus = corpora.length === 1 ? corpora[0] : corpora.join("+").slice(0, MAX_CORPUS_CHARS).replace(/\++$/, "");
|
|
795
|
-
const sources = new Set(events.map((event) => event.source));
|
|
796
|
-
const queries = events.map((event) => event.query).filter((q) => !!q);
|
|
797
|
-
const context = {
|
|
798
|
-
v: 1,
|
|
799
|
-
corpus,
|
|
800
|
-
source: sources.size === 1 ? [...sources][0] : "other",
|
|
801
|
-
docs
|
|
802
|
-
};
|
|
803
|
-
if (queries.length) context.query = queries[queries.length - 1];
|
|
804
|
-
return context;
|
|
805
|
-
}
|
|
806
|
-
|
|
807
|
-
// src/memory.ts
|
|
808
|
-
function buildMemoryContext(events) {
|
|
809
|
-
const mem = events.filter((e) => e.kind === "memory");
|
|
810
|
-
const items = mem.flatMap((e) => e.docs.map((d) => ({ id: d.id, preview: d.preview }))).slice(-MAX_DOCS);
|
|
811
|
-
if (items.length === 0) return void 0;
|
|
812
|
-
const stores = [...new Set(mem.map((e) => e.corpus))];
|
|
813
|
-
const sources = new Set(mem.map((e) => e.source));
|
|
814
|
-
const scope = mem[mem.length - 1]?.query || "agent";
|
|
815
|
-
return {
|
|
816
|
-
v: 1,
|
|
817
|
-
store: stores.length === 1 ? stores[0] : stores.join("+").slice(0, MAX_CORPUS_CHARS),
|
|
818
|
-
scope,
|
|
819
|
-
source: sources.size === 1 ? [...sources][0] : "other",
|
|
820
|
-
items
|
|
821
|
-
};
|
|
822
|
-
}
|
|
823
|
-
function attachMemoryContext(body, memoryContext) {
|
|
824
|
-
const bag = body;
|
|
825
|
-
const existing = bag.shashu_metadata;
|
|
826
|
-
const metadata = existing !== null && typeof existing === "object" ? existing : {};
|
|
827
|
-
bag.shashu_metadata = { ...metadata, memory_context: memoryContext };
|
|
828
|
-
return body;
|
|
829
|
-
}
|
|
830
|
-
|
|
831
|
-
// src/_joiner.ts
|
|
832
|
-
function parseJsonObject(body) {
|
|
833
|
-
if (typeof body !== "string") return void 0;
|
|
834
|
-
if (!/^[\s]*\{/.test(body)) return void 0;
|
|
835
|
-
try {
|
|
836
|
-
const parsed = JSON.parse(body);
|
|
837
|
-
return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
838
|
-
} catch {
|
|
839
|
-
return void 0;
|
|
840
|
-
}
|
|
841
|
-
}
|
|
842
|
-
function metadataBag(body) {
|
|
843
|
-
const metadata = body.shashu_metadata;
|
|
844
|
-
if (metadata !== null && typeof metadata === "object") {
|
|
845
|
-
return metadata;
|
|
846
|
-
}
|
|
847
|
-
return void 0;
|
|
848
|
-
}
|
|
849
|
-
function hasExplicitRagContext(body) {
|
|
850
|
-
const metadata = metadataBag(body);
|
|
851
|
-
return metadata?.rag_context !== void 0 && metadata?.rag_context !== null;
|
|
852
|
-
}
|
|
853
|
-
function hasExplicitMemoryContext(body) {
|
|
854
|
-
const metadata = metadataBag(body);
|
|
855
|
-
return metadata?.memory_context !== void 0 && metadata?.memory_context !== null;
|
|
856
|
-
}
|
|
857
|
-
function fixContentLength(headers, byteLength2) {
|
|
858
|
-
const value = String(byteLength2);
|
|
859
|
-
if (headers instanceof Headers) {
|
|
860
|
-
if (headers.has("content-length")) headers.set("content-length", value);
|
|
861
|
-
return headers;
|
|
862
|
-
}
|
|
863
|
-
if (Array.isArray(headers)) {
|
|
864
|
-
return headers.map(
|
|
865
|
-
(pair) => Array.isArray(pair) && String(pair[0]).toLowerCase() === "content-length" ? [pair[0], value] : pair
|
|
866
|
-
);
|
|
867
|
-
}
|
|
868
|
-
if (headers !== null && typeof headers === "object") {
|
|
869
|
-
const out = { ...headers };
|
|
870
|
-
for (const key of Object.keys(out)) {
|
|
871
|
-
if (key.toLowerCase() === "content-length") out[key] = value;
|
|
872
|
-
}
|
|
873
|
-
return out;
|
|
874
|
-
}
|
|
875
|
-
return headers;
|
|
876
|
-
}
|
|
877
|
-
function hasConflictingCorpora(events) {
|
|
878
|
-
if (events.length <= 1) return false;
|
|
879
|
-
const first = events[0].corpus;
|
|
880
|
-
for (let i = 1; i < events.length; i += 1) {
|
|
881
|
-
if (events[i].corpus !== first) return true;
|
|
882
|
-
}
|
|
883
|
-
return false;
|
|
884
|
-
}
|
|
885
|
-
function takeContextFor(body) {
|
|
886
|
-
const events = snapshot();
|
|
887
|
-
const ragEvents = events.filter((e) => e.kind !== "memory");
|
|
888
|
-
const memEvents = events.filter((e) => e.kind === "memory");
|
|
889
|
-
const explicitRag = hasExplicitRagContext(body);
|
|
890
|
-
const explicitMem = hasExplicitMemoryContext(body);
|
|
891
|
-
clear();
|
|
892
|
-
let mutated = false;
|
|
893
|
-
if (!explicitRag) {
|
|
894
|
-
if (hasConflictingCorpora(ragEvents)) {
|
|
895
|
-
} else {
|
|
896
|
-
const context = buildRagContext(ragEvents);
|
|
897
|
-
if (context !== void 0) {
|
|
898
|
-
attachRagContext(body, context);
|
|
899
|
-
mutated = true;
|
|
900
|
-
}
|
|
901
|
-
}
|
|
902
|
-
}
|
|
903
|
-
if (!explicitMem) {
|
|
904
|
-
const memoryContext = buildMemoryContext(memEvents);
|
|
905
|
-
if (memoryContext !== void 0) {
|
|
906
|
-
attachMemoryContext(body, memoryContext);
|
|
907
|
-
mutated = true;
|
|
908
|
-
}
|
|
909
|
-
}
|
|
910
|
-
return mutated ? body : void 0;
|
|
911
|
-
}
|
|
912
|
-
function pinOutgoing(input, init) {
|
|
913
|
-
if (!hasEvents()) return { input, init };
|
|
914
|
-
if (isDisabled()) {
|
|
915
|
-
clear();
|
|
916
|
-
return { input, init };
|
|
917
|
-
}
|
|
918
|
-
const body = parseJsonObject(init?.body);
|
|
919
|
-
if (body === void 0) return { input, init };
|
|
920
|
-
const merged = takeContextFor(body);
|
|
921
|
-
if (merged === void 0) return { input, init };
|
|
922
|
-
const encoded = JSON.stringify(merged);
|
|
923
|
-
return {
|
|
924
|
-
input,
|
|
925
|
-
init: {
|
|
926
|
-
...init,
|
|
927
|
-
body: encoded,
|
|
928
|
-
headers: fixContentLength(init?.headers, byteLength(encoded))
|
|
929
|
-
}
|
|
930
|
-
};
|
|
931
|
-
}
|
|
932
|
-
function byteLength(text) {
|
|
933
|
-
return new TextEncoder().encode(text).length;
|
|
934
|
-
}
|
|
935
|
-
|
|
936
|
-
// src/retry.ts
|
|
937
|
-
var DEFAULT_RETRY_POLICY = {
|
|
938
|
-
maxRetries: 2,
|
|
939
|
-
backoffBaseSeconds: 0.5,
|
|
940
|
-
backoffMaxSeconds: 30,
|
|
941
|
-
retryOnConnectionErrors: true,
|
|
942
|
-
retryOn429: true,
|
|
943
|
-
retryOn5xx: false,
|
|
944
|
-
neverRetryStatus: [400, 401, 403, 404],
|
|
945
|
-
ignoreRetryAfter: false,
|
|
946
|
-
jitterFraction: 0.2
|
|
947
|
-
};
|
|
948
|
-
function resolveRetryPolicy(policy) {
|
|
949
|
-
if (policy === null) return null;
|
|
950
|
-
if (policy === void 0) return { ...DEFAULT_RETRY_POLICY };
|
|
951
|
-
return { ...DEFAULT_RETRY_POLICY, ...policy };
|
|
952
|
-
}
|
|
953
|
-
function shouldRetryStatus(policy, status) {
|
|
954
|
-
if (policy.neverRetryStatus.includes(status)) return false;
|
|
955
|
-
if (status === 429) return policy.retryOn429;
|
|
956
|
-
if (status === 503) return true;
|
|
957
|
-
if (status >= 500 && status <= 599) return policy.retryOn5xx;
|
|
958
|
-
return false;
|
|
959
|
-
}
|
|
960
|
-
function truthyHeader(value) {
|
|
961
|
-
return ["1", "true", "yes", "on"].includes((value ?? "").trim().toLowerCase());
|
|
962
|
-
}
|
|
963
|
-
function gatewaySaysBusyRetry(res, retryAfter) {
|
|
964
|
-
if (res.status !== 429 && res.status !== 503) return false;
|
|
965
|
-
if (truthyHeader(res.headers.get("x-should-retry"))) return true;
|
|
966
|
-
return retryAfter !== void 0;
|
|
967
|
-
}
|
|
968
|
-
function shouldRetryResponse(policy, res, retryAfter) {
|
|
969
|
-
if (policy.neverRetryStatus.includes(res.status)) return false;
|
|
970
|
-
if (res.status === 429 || res.status === 503) {
|
|
971
|
-
if (res.status === 429 && !policy.retryOn429) return false;
|
|
972
|
-
return gatewaySaysBusyRetry(res, retryAfter);
|
|
973
|
-
}
|
|
974
|
-
if (!shouldRetryStatus(policy, res.status)) return false;
|
|
975
|
-
return true;
|
|
976
|
-
}
|
|
977
|
-
function delayFor(policy, attempt, res, retryAfter) {
|
|
978
|
-
const jitter = (seconds) => {
|
|
979
|
-
const frac = policy.jitterFraction ?? 0.2;
|
|
980
|
-
const capped = Math.min(policy.backoffMaxSeconds, seconds);
|
|
981
|
-
if (frac <= 0) return capped;
|
|
982
|
-
return Math.min(policy.backoffMaxSeconds, capped * (1 + Math.random() * frac));
|
|
983
|
-
};
|
|
984
|
-
if (res !== null && (res.status === 429 || res.status === 503) && !policy.ignoreRetryAfter && retryAfter !== void 0) {
|
|
985
|
-
return jitter(retryAfter);
|
|
986
|
-
}
|
|
987
|
-
return jitter(policy.backoffBaseSeconds * 2 ** attempt);
|
|
988
|
-
}
|
|
989
|
-
var UNSENT_CODES = /* @__PURE__ */ new Set([
|
|
990
|
-
"ECONNREFUSED",
|
|
991
|
-
"ENOTFOUND",
|
|
992
|
-
"EAI_AGAIN",
|
|
993
|
-
"ENETUNREACH",
|
|
994
|
-
"EHOSTUNREACH",
|
|
995
|
-
"UND_ERR_CONNECT",
|
|
996
|
-
"UND_ERR_CONNECT_TIMEOUT"
|
|
997
|
-
]);
|
|
998
|
-
function requestNeverLeft(err) {
|
|
999
|
-
if (!(err instanceof TypeError)) return false;
|
|
1000
|
-
const cause = err.cause;
|
|
1001
|
-
const code = cause?.code ?? "";
|
|
1002
|
-
if (UNSENT_CODES.has(code)) return true;
|
|
1003
|
-
return cause?.name === "ConnectTimeoutError" || cause?.name === "ConnectError";
|
|
1004
|
-
}
|
|
1005
|
-
var defaultSleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1e3));
|
|
1006
|
-
async function peekJson(res) {
|
|
1007
|
-
try {
|
|
1008
|
-
return await res.clone().json();
|
|
1009
|
-
} catch {
|
|
1010
|
-
return void 0;
|
|
1011
|
-
}
|
|
1012
|
-
}
|
|
1013
|
-
async function executeWithRetry(send, policy, sleep = defaultSleep) {
|
|
1014
|
-
if (policy === null) return send();
|
|
1015
|
-
let attempt = 0;
|
|
1016
|
-
for (; ; ) {
|
|
1017
|
-
let res;
|
|
1018
|
-
try {
|
|
1019
|
-
res = await send();
|
|
1020
|
-
} catch (err) {
|
|
1021
|
-
if (policy.retryOnConnectionErrors && requestNeverLeft(err) && attempt < policy.maxRetries) {
|
|
1022
|
-
await sleep(delayFor(policy, attempt, null, void 0));
|
|
1023
|
-
attempt += 1;
|
|
1024
|
-
continue;
|
|
1025
|
-
}
|
|
1026
|
-
throw err;
|
|
1027
|
-
}
|
|
1028
|
-
const retryAfter = res.status === 429 || res.status === 503 ? gatewayRetryAfter(res, await peekJson(res)) : void 0;
|
|
1029
|
-
if (attempt < policy.maxRetries && shouldRetryResponse(policy, res, retryAfter)) {
|
|
1030
|
-
await sleep(delayFor(policy, attempt, res, retryAfter));
|
|
1031
|
-
attempt += 1;
|
|
1032
|
-
continue;
|
|
1033
|
-
}
|
|
1034
|
-
return res;
|
|
1035
|
-
}
|
|
1036
|
-
}
|
|
1037
|
-
|
|
1038
|
-
// src/credential.ts
|
|
1039
|
-
var BOTH_OR_NEITHER = "Give either a SHASHU key or a token provider, not both.";
|
|
1040
|
-
var REFRESH_SKEW_SECONDS = 60;
|
|
1041
|
-
var PASS_PROVIDER_NOT_SET_UP = "pass_provider_not_set_up";
|
|
1042
|
-
var PASS_NOT_LICENSED = "pass_not_licensed";
|
|
1043
|
-
var PASS_EXPIRED = "pass_expired";
|
|
1044
|
-
var PASS_WRONG_AUDIENCE = "pass_wrong_audience";
|
|
1045
|
-
var PASS_WRONG_ISSUER = "pass_wrong_issuer";
|
|
1046
|
-
var PASS_UNKNOWN_AGENT = "pass_unknown_agent";
|
|
1047
|
-
var PASS_CODES = [
|
|
1048
|
-
PASS_PROVIDER_NOT_SET_UP,
|
|
1049
|
-
PASS_NOT_LICENSED,
|
|
1050
|
-
PASS_EXPIRED,
|
|
1051
|
-
PASS_WRONG_AUDIENCE,
|
|
1052
|
-
PASS_WRONG_ISSUER,
|
|
1053
|
-
PASS_UNKNOWN_AGENT
|
|
1054
|
-
];
|
|
1055
|
-
var RETRY_CODES = /* @__PURE__ */ new Set([PASS_EXPIRED]);
|
|
1056
|
-
function jwtExpUnverified(token) {
|
|
1057
|
-
const parts = token.split(".");
|
|
1058
|
-
if (parts.length !== 3) return null;
|
|
1059
|
-
const payload = parts[1];
|
|
1060
|
-
const pad = "=".repeat((4 - payload.length % 4) % 4);
|
|
1061
|
-
try {
|
|
1062
|
-
const json = Buffer.from(payload + pad, "base64url").toString("utf8");
|
|
1063
|
-
const data = JSON.parse(json);
|
|
1064
|
-
if (data.exp == null) return null;
|
|
1065
|
-
const exp = Number(data.exp);
|
|
1066
|
-
return Number.isFinite(exp) ? exp : null;
|
|
1067
|
-
} catch {
|
|
1068
|
-
return null;
|
|
1069
|
-
}
|
|
1070
|
-
}
|
|
1071
|
-
function passRefusalCodeFromText(text) {
|
|
1072
|
-
try {
|
|
1073
|
-
const parsed = JSON.parse(text);
|
|
1074
|
-
const code = parsed?.error?.code;
|
|
1075
|
-
return typeof code === "string" && PASS_CODES.includes(code) ? code : null;
|
|
1076
|
-
} catch {
|
|
1077
|
-
return null;
|
|
1078
|
-
}
|
|
1079
|
-
}
|
|
1080
|
-
function shouldRetryPassRefused(opts) {
|
|
1081
|
-
if (!opts.usesProvider || opts.bytesDelivered || opts.status !== 401) return false;
|
|
1082
|
-
return opts.code != null && RETRY_CODES.has(opts.code);
|
|
1083
|
-
}
|
|
1084
|
-
var CredentialResolver = class {
|
|
1085
|
-
constructor(opts) {
|
|
1086
|
-
const envKey = envGet(API_KEY_ENV) ?? void 0;
|
|
1087
|
-
const hasKeyArg = opts.apiKey !== void 0;
|
|
1088
|
-
const hasProvider = opts.tokenProvider !== void 0;
|
|
1089
|
-
if (hasKeyArg && hasProvider) throw new ShashuConfigError(BOTH_OR_NEITHER);
|
|
1090
|
-
if (hasProvider && envKey && !hasKeyArg) throw new ShashuConfigError(BOTH_OR_NEITHER);
|
|
1091
|
-
if (opts.requireOne && !hasProvider && !hasKeyArg && !envKey) {
|
|
1092
|
-
throw new ShashuConfigError(BOTH_OR_NEITHER);
|
|
1093
|
-
}
|
|
1094
|
-
this.provider = opts.tokenProvider;
|
|
1095
|
-
this.staticKey = hasProvider ? void 0 : hasKeyArg ? opts.apiKey : envKey;
|
|
1096
|
-
}
|
|
1097
|
-
get usesProvider() {
|
|
1098
|
-
return this.provider !== void 0;
|
|
1099
|
-
}
|
|
1100
|
-
async get() {
|
|
1101
|
-
if (!this.provider) return this.staticKey;
|
|
1102
|
-
if (this.cached && !this.needsRefresh(this.cached)) return this.cached;
|
|
1103
|
-
if (this.inflight) return this.inflight;
|
|
1104
|
-
this.inflight = (async () => {
|
|
1105
|
-
const token = await this.provider();
|
|
1106
|
-
this.cached = String(token);
|
|
1107
|
-
this.inflight = void 0;
|
|
1108
|
-
return this.cached;
|
|
1109
|
-
})().catch((err) => {
|
|
1110
|
-
this.inflight = void 0;
|
|
1111
|
-
throw err;
|
|
1112
|
-
});
|
|
1113
|
-
return this.inflight;
|
|
1114
|
-
}
|
|
1115
|
-
invalidate() {
|
|
1116
|
-
this.cached = void 0;
|
|
1117
|
-
}
|
|
1118
|
-
needsRefresh(token) {
|
|
1119
|
-
const exp = jwtExpUnverified(token);
|
|
1120
|
-
if (exp == null) return true;
|
|
1121
|
-
return Date.now() / 1e3 >= exp - REFRESH_SKEW_SECONDS;
|
|
1122
|
-
}
|
|
1123
|
-
};
|
|
1124
|
-
|
|
1125
|
-
// src/middleware/langchain.ts
|
|
1126
|
-
function createShashuLangChainConfig(config) {
|
|
1127
|
-
if (isDisabled()) return {};
|
|
1128
|
-
const baseUrl = requireBaseUrl(config.baseUrl, {
|
|
1129
|
-
entryPoint: "createShashuLangChainConfig()"
|
|
1130
|
-
});
|
|
1131
|
-
const ctx = config.workflowContext ?? getWorkflowContextFromEnv();
|
|
1132
|
-
const resolver = new CredentialResolver({
|
|
1133
|
-
apiKey: config.apiKey,
|
|
1134
|
-
tokenProvider: config.tokenProvider
|
|
1135
|
-
});
|
|
1136
|
-
const headers = {
|
|
1137
|
-
...config.headers,
|
|
1138
|
-
...buildContextHeaders(ctx, { defaultSessionId: config.sessionId ?? (0, import_node_crypto3.randomUUID)() })
|
|
1139
|
-
};
|
|
1140
|
-
applyContractVersion(headers, config.contractVersion);
|
|
1141
|
-
const fetch2 = async (input, init) => {
|
|
1142
|
-
const baseHeaders = new Headers(init?.headers);
|
|
1143
|
-
baseHeaders.delete("authorization");
|
|
1144
|
-
const headerObj = {};
|
|
1145
|
-
baseHeaders.forEach((v, k) => {
|
|
1146
|
-
headerObj[k] = v;
|
|
1147
|
-
});
|
|
1148
|
-
const pinned = pinOutgoing(input, { ...init, headers: headerObj });
|
|
1149
|
-
const send = async () => {
|
|
1150
|
-
const token = await resolver.get();
|
|
1151
|
-
const headers2 = { ...pinned.init?.headers || {} };
|
|
1152
|
-
if (token) headers2.authorization = `Bearer ${token}`;
|
|
1153
|
-
return globalThis.fetch(pinned.input, { ...pinned.init, headers: headers2 });
|
|
1154
|
-
};
|
|
1155
|
-
const res = await executeWithRetry(send, resolveRetryPolicy(config.retryPolicy));
|
|
1156
|
-
if (!resolver.usesProvider || res.status !== 401) return res;
|
|
1157
|
-
const code = passRefusalCodeFromText(await res.clone().text());
|
|
1158
|
-
if (!shouldRetryPassRefused({
|
|
1159
|
-
usesProvider: true,
|
|
1160
|
-
status: res.status,
|
|
1161
|
-
code,
|
|
1162
|
-
bytesDelivered: false
|
|
1163
|
-
})) {
|
|
1164
|
-
return res;
|
|
1165
|
-
}
|
|
1166
|
-
resolver.invalidate();
|
|
1167
|
-
return send();
|
|
1168
|
-
};
|
|
1169
|
-
return {
|
|
1170
|
-
baseURL: baseUrl,
|
|
1171
|
-
defaultHeaders: Object.keys(headers).length ? headers : void 0,
|
|
1172
|
-
configuration: {
|
|
1173
|
-
baseURL: baseUrl,
|
|
1174
|
-
defaultHeaders: Object.keys(headers).length ? headers : void 0,
|
|
1175
|
-
fetch: fetch2
|
|
1176
|
-
}
|
|
1177
|
-
};
|
|
1178
|
-
}
|
|
1179
|
-
function lcDocumentsToRagContext(documents, options = {}) {
|
|
1180
|
-
const maxDocs = options.maxDocs ?? 32;
|
|
1181
|
-
const previewChars = options.previewChars ?? 600;
|
|
1182
|
-
const docs = [];
|
|
1183
|
-
for (const doc of documents.slice(0, maxDocs)) {
|
|
1184
|
-
const page = doc.pageContent ?? String(doc);
|
|
1185
|
-
const entry = { preview: String(page).slice(0, previewChars) };
|
|
1186
|
-
const metadata = doc.metadata ?? {};
|
|
1187
|
-
if (metadata && typeof metadata === "object") {
|
|
1188
|
-
const docId = metadata.source ?? metadata.id;
|
|
1189
|
-
if (docId) entry.id = String(docId);
|
|
1190
|
-
const score = metadata.score ?? metadata.relevance;
|
|
1191
|
-
if (typeof score === "number") entry.score = score;
|
|
1192
|
-
}
|
|
1193
|
-
docs.push(entry);
|
|
1194
|
-
}
|
|
1195
|
-
const out = { docs };
|
|
1196
|
-
if (options.corpus !== void 0) out.corpus = options.corpus;
|
|
1197
|
-
if (options.query !== void 0) out.query = options.query;
|
|
1198
|
-
return out;
|
|
1199
|
-
}
|
|
1200
|
-
var SOURCE = "langchain";
|
|
1201
|
-
var DEFAULT_CORPUS = "langchain-retriever";
|
|
1202
|
-
var MAX_TRACKED_RUNS = 64;
|
|
1203
|
-
var captured = /* @__PURE__ */ new Map();
|
|
1204
|
-
var QUERY = /* @__PURE__ */ Symbol.for("shashu.langchain.query");
|
|
1205
|
-
var enabled = false;
|
|
1206
|
-
var patched = false;
|
|
1207
|
-
var corpusName = DEFAULT_CORPUS;
|
|
1208
|
-
function active() {
|
|
1209
|
-
return enabled && !isDisabled();
|
|
1210
|
-
}
|
|
1211
|
-
function record(key, capture) {
|
|
1212
|
-
const list = captured.get(key) ?? [];
|
|
1213
|
-
list.push(capture);
|
|
1214
|
-
if (list.length > MAX_EVENTS) list.splice(0, list.length - MAX_EVENTS);
|
|
1215
|
-
captured.set(key, list);
|
|
1216
|
-
if (captured.size > MAX_TRACKED_RUNS) {
|
|
1217
|
-
const oldest = captured.keys().next();
|
|
1218
|
-
if (!oldest.done) captured.delete(oldest.value);
|
|
1219
|
-
}
|
|
1220
|
-
}
|
|
1221
|
-
function deliver(key) {
|
|
1222
|
-
if (!active() || typeof key !== "string") return;
|
|
1223
|
-
const captures = captured.get(key);
|
|
1224
|
-
if (!captures || captures.length === 0) return;
|
|
1225
|
-
for (const capture of captures) {
|
|
1226
|
-
try {
|
|
1227
|
-
declareRetrieval(capture.documents, {
|
|
1228
|
-
corpus: corpusName,
|
|
1229
|
-
query: capture.query,
|
|
1230
|
-
source: SOURCE
|
|
1231
|
-
});
|
|
1232
|
-
} catch (err) {
|
|
1233
|
-
console.warn(
|
|
1234
|
-
`SHASHU LangChain collector dropped a retrieval: ${err instanceof Error ? err.name : typeof err}`
|
|
1235
|
-
);
|
|
1236
|
-
}
|
|
1237
|
-
}
|
|
1238
|
-
}
|
|
1239
|
-
var ShashuLangChainCallback = class {
|
|
1240
|
-
constructor() {
|
|
1241
|
-
this.name = "ShashuLangChainCallback";
|
|
1242
|
-
this.raiseError = false;
|
|
1243
|
-
this.awaitHandlers = false;
|
|
1244
|
-
this.ignoreLLM = false;
|
|
1245
|
-
this.ignoreChain = false;
|
|
1246
|
-
this.ignoreAgent = false;
|
|
1247
|
-
this.ignoreRetriever = false;
|
|
1248
|
-
this.ignoreCustomEvent = false;
|
|
1249
|
-
}
|
|
1250
|
-
copy() {
|
|
1251
|
-
return this;
|
|
1252
|
-
}
|
|
1253
|
-
};
|
|
1254
|
-
var PRESENCE = new ShashuLangChainCallback();
|
|
1255
|
-
function patchConfigure(CallbackManager) {
|
|
1256
|
-
for (const name of ["configure", "_configureSync"]) {
|
|
1257
|
-
const original = CallbackManager[name];
|
|
1258
|
-
if (typeof original !== "function") continue;
|
|
1259
|
-
CallbackManager[name] = function(inheritable, ...rest) {
|
|
1260
|
-
if (!active()) return original.call(this, inheritable, ...rest);
|
|
1261
|
-
let next = inheritable;
|
|
1262
|
-
if (next === void 0 || next === null) next = [PRESENCE];
|
|
1263
|
-
else if (Array.isArray(next)) next = next.includes(PRESENCE) ? next : [...next, PRESENCE];
|
|
1264
|
-
const manager = original.call(this, next, ...rest);
|
|
1265
|
-
if (manager && !Array.isArray(inheritable) && inheritable && typeof inheritable.addHandler === "function" && !manager.handlers.includes(PRESENCE)) {
|
|
1266
|
-
manager.addHandler(PRESENCE, true);
|
|
1267
|
-
}
|
|
1268
|
-
return manager;
|
|
1269
|
-
};
|
|
1270
|
-
}
|
|
1271
|
-
}
|
|
1272
|
-
function patchCapture(CallbackManager, CallbackManagerForRetrieverRun) {
|
|
1273
|
-
const originalStart = CallbackManager.prototype.handleRetrieverStart;
|
|
1274
|
-
CallbackManager.prototype.handleRetrieverStart = async function(retriever, query, ...rest) {
|
|
1275
|
-
const runManager = await originalStart.call(this, retriever, query, ...rest);
|
|
1276
|
-
if (active() && runManager && typeof query === "string") runManager[QUERY] = query;
|
|
1277
|
-
return runManager;
|
|
1278
|
-
};
|
|
1279
|
-
const originalEnd = CallbackManagerForRetrieverRun.prototype.handleRetrieverEnd;
|
|
1280
|
-
CallbackManagerForRetrieverRun.prototype.handleRetrieverEnd = function(documents, ...rest) {
|
|
1281
|
-
if (active() && Array.isArray(documents) && documents.length > 0) {
|
|
1282
|
-
record(this._parentRunId, { documents, query: this[QUERY] });
|
|
1283
|
-
}
|
|
1284
|
-
return originalEnd.call(this, documents, ...rest);
|
|
1285
|
-
};
|
|
1286
|
-
}
|
|
1287
|
-
function patchDelivery(CallbackManager) {
|
|
1288
|
-
for (const name of ["handleChatModelStart", "handleLLMStart"]) {
|
|
1289
|
-
const original = CallbackManager.prototype[name];
|
|
1290
|
-
if (typeof original !== "function") continue;
|
|
1291
|
-
CallbackManager.prototype[name] = function(...args) {
|
|
1292
|
-
deliver(this._parentRunId);
|
|
1293
|
-
return original.apply(this, args);
|
|
1294
|
-
};
|
|
1295
|
-
}
|
|
1296
|
-
}
|
|
1297
|
-
function patchCleanup(CallbackManagerForChainRun) {
|
|
1298
|
-
for (const name of ["handleChainEnd", "handleChainError"]) {
|
|
1299
|
-
const original = CallbackManagerForChainRun.prototype[name];
|
|
1300
|
-
if (typeof original !== "function") continue;
|
|
1301
|
-
CallbackManagerForChainRun.prototype[name] = function(...args) {
|
|
1302
|
-
if (this._parentRunId === void 0) captured.delete(this.runId);
|
|
1303
|
-
return original.apply(this, args);
|
|
1304
|
-
};
|
|
1305
|
-
}
|
|
1306
|
-
}
|
|
1307
|
-
async function install(options = {}) {
|
|
1308
|
-
if (options.corpus !== void 0) corpusName = options.corpus || DEFAULT_CORPUS;
|
|
1309
|
-
if (!patched) {
|
|
1310
|
-
let manager;
|
|
1311
|
-
try {
|
|
1312
|
-
manager = await import("@langchain/core/callbacks/manager");
|
|
1313
|
-
} catch {
|
|
1314
|
-
return false;
|
|
1315
|
-
}
|
|
1316
|
-
patchConfigure(manager.CallbackManager);
|
|
1317
|
-
patchCapture(manager.CallbackManager, manager.CallbackManagerForRetrieverRun);
|
|
1318
|
-
patchDelivery(manager.CallbackManager);
|
|
1319
|
-
patchCleanup(manager.CallbackManagerForChainRun);
|
|
1320
|
-
patched = true;
|
|
1321
|
-
}
|
|
1322
|
-
enabled = true;
|
|
1323
|
-
return true;
|
|
1324
|
-
}
|
|
1325
|
-
function uninstall() {
|
|
1326
|
-
enabled = false;
|
|
1327
|
-
captured.clear();
|
|
1328
|
-
}
|
|
1329
|
-
function isInstalled() {
|
|
1330
|
-
return active();
|
|
1331
|
-
}
|
|
1332
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
1333
|
-
0 && (module.exports = {
|
|
1334
|
-
DEFAULT_CORPUS,
|
|
1335
|
-
SOURCE,
|
|
1336
|
-
ShashuLangChainCallback,
|
|
1337
|
-
createShashuLangChainConfig,
|
|
1338
|
-
install,
|
|
1339
|
-
isInstalled,
|
|
1340
|
-
lcDocumentsToRagContext,
|
|
1341
|
-
uninstall
|
|
1342
|
-
});
|