@shashu-ai/sdk 1.1.1 → 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/dist/index.cjs DELETED
@@ -1,2567 +0,0 @@
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/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- Audit: () => Audit,
24
- BLOCK_ENCODING_HEADER: () => BLOCK_ENCODING_HEADER,
25
- BODY_KEY: () => BODY_KEY,
26
- CONTRACT_VERSION_HEADER: () => CONTRACT_VERSION_HEADER,
27
- DECISIONS: () => DECISIONS,
28
- DECISION_ALLOW: () => DECISION_ALLOW,
29
- DECISION_ALLOW_ALTERED: () => DECISION_ALLOW_ALTERED,
30
- DECISION_BLOCK: () => DECISION_BLOCK,
31
- DECISION_FAIL: () => DECISION_FAIL,
32
- DECISION_NOT_CHECKED: () => DECISION_NOT_CHECKED,
33
- DECISION_REFUSE: () => DECISION_REFUSE,
34
- DEFAULT_BLOCK_ENCODING: () => DEFAULT_BLOCK_ENCODING,
35
- DEFAULT_CONTRACT_VERSION: () => DEFAULT_CONTRACT_VERSION,
36
- DEFAULT_RETRY_POLICY: () => DEFAULT_RETRY_POLICY,
37
- DELIVERED_DECISIONS: () => DELIVERED_DECISIONS,
38
- HEADER_ATTACHMENTS: () => HEADER_ATTACHMENTS,
39
- HEADER_CODE: () => HEADER_CODE,
40
- HEADER_DECISION: () => HEADER_DECISION,
41
- HEADER_INSPECTION: () => HEADER_INSPECTION,
42
- HEADER_MEMORY: () => HEADER_MEMORY,
43
- HEADER_PREFIX: () => HEADER_PREFIX,
44
- HEADER_REQUEST_ID: () => HEADER_REQUEST_ID,
45
- HEADER_SHASHU_REQUEST_ID: () => HEADER_SHASHU_REQUEST_ID,
46
- HEADER_SHOULD_RETRY: () => HEADER_SHOULD_RETRY,
47
- HEADER_TRACE_ID: () => HEADER_TRACE_ID,
48
- MemoryWriteBlocked: () => MemoryWriteBlocked,
49
- PASS_CODES: () => PASS_CODES,
50
- PASS_EXPIRED: () => PASS_EXPIRED,
51
- PASS_NOT_LICENSED: () => PASS_NOT_LICENSED,
52
- PASS_PROVIDER_NOT_SET_UP: () => PASS_PROVIDER_NOT_SET_UP,
53
- PASS_UNKNOWN_AGENT: () => PASS_UNKNOWN_AGENT,
54
- PASS_WRONG_AUDIENCE: () => PASS_WRONG_AUDIENCE,
55
- PASS_WRONG_ISSUER: () => PASS_WRONG_ISSUER,
56
- SOURCES: () => SOURCES,
57
- SOURCE_TOOL_HEADER: () => SOURCE_TOOL_HEADER,
58
- Shashu: () => Shashu,
59
- ShashuAuthenticationError: () => ShashuAuthenticationError,
60
- ShashuBadRequestError: () => ShashuBadRequestError,
61
- ShashuBudgetExceededError: () => ShashuBudgetExceededError,
62
- ShashuConfigError: () => ShashuConfigError,
63
- ShashuContentFilterError: () => ShashuContentFilterError,
64
- ShashuContextWindowExceeded: () => ShashuContextWindowExceeded,
65
- ShashuError: () => ShashuError,
66
- ShashuPermissionError: () => ShashuPermissionError,
67
- ShashuPolicyViolation: () => ShashuPolicyViolation,
68
- ShashuProviderError: () => ShashuProviderError,
69
- ShashuRateLimitError: () => ShashuRateLimitError,
70
- TRUSTLOG_HEADER_PREFIX: () => TRUSTLOG_HEADER_PREFIX,
71
- attachRagContext: () => attachRagContext,
72
- buildContextHeaders: () => buildContextHeaders,
73
- buildInvocationHeaders: () => buildInvocationHeaders,
74
- buildRagContext: () => buildRagContext,
75
- buildSourceToolJson: () => buildSourceToolJson,
76
- captureIncoming: () => captureIncoming,
77
- createShashuAnthropicConfig: () => createShashuAnthropicConfig,
78
- createShashuGeminiConfig: () => createShashuGeminiConfig,
79
- createShashuLangChainConfig: () => createShashuLangChainConfig,
80
- createShashuOpenAIOptions: () => createShashuOpenAIOptions,
81
- decisionFrom: () => decisionFrom,
82
- declareMemory: () => declareMemory,
83
- declareRetrieval: () => declareRetrieval,
84
- executeWithRetry: () => executeWithRetry,
85
- gatewayRetryAfter: () => gatewayRetryAfter,
86
- getAnthropicHeaders: () => getAnthropicHeaders,
87
- getGeminiHeaders: () => getGeminiHeaders,
88
- getN8nHeaderSnippet: () => getN8nHeaderSnippet,
89
- getShashuHeaders: () => getShashuHeaders,
90
- getWorkflowContextFromEnv: () => getWorkflowContextFromEnv,
91
- isShashuBlock: () => isShashuBlock,
92
- makeRagContext: () => makeRagContext,
93
- memoryScope: () => memoryScope,
94
- parseRetryAfter: () => parseRetryAfter,
95
- raiseForResponse: () => raiseForResponse,
96
- raiseIfContentFiltered: () => raiseIfContentFiltered,
97
- resolveRetryPolicy: () => resolveRetryPolicy,
98
- retrievalScope: () => retrievalScope,
99
- shashuDecision: () => shashuDecision,
100
- shashuFetch: () => shashuFetch,
101
- tracer: () => tracer,
102
- withRetrievalJoiner: () => withRetrievalJoiner
103
- });
104
- module.exports = __toCommonJS(index_exports);
105
-
106
- // src/client.ts
107
- var import_node_crypto3 = require("crypto");
108
-
109
- // src/types.ts
110
- var ShashuError = class _ShashuError extends Error {
111
- /**
112
- * Why a route was refused for the data in the request, off the decision.
113
- * Set on a `route_data_policy` refusal, so an app can say which route is not
114
- * approved for which category without parsing the message.
115
- */
116
- get routePolicy() {
117
- return this.decision?.routePolicy;
118
- }
119
- constructor(message, status, body, details) {
120
- super(message);
121
- this.name = "ShashuError";
122
- this.status = status;
123
- this.body = body;
124
- this.type = details?.type;
125
- this.code = details?.code;
126
- this.decision = details?.decision;
127
- this.responseHeaders = details?.responseHeaders;
128
- Object.setPrototypeOf(this, _ShashuError.prototype);
129
- }
130
- };
131
-
132
- // src/exceptions.ts
133
- var PROVIDER_ERROR_PREFIX = "TrustGate Provider Error:";
134
- var ShashuConfigError = class _ShashuConfigError extends ShashuError {
135
- constructor(message) {
136
- super(message, 0);
137
- this.name = "ShashuConfigError";
138
- Object.setPrototypeOf(this, _ShashuConfigError.prototype);
139
- }
140
- };
141
- var ShashuAuthenticationError = class _ShashuAuthenticationError extends ShashuError {
142
- constructor(message, status, body, details) {
143
- super(message, status, body, details);
144
- this.name = "ShashuAuthenticationError";
145
- Object.setPrototypeOf(this, _ShashuAuthenticationError.prototype);
146
- }
147
- /**
148
- * True when the upstream provider rejected the gateway's credential.
149
- *
150
- * Reads `error.type`, the one field the gateway populates differently for
151
- * pass-throughs, and falls back to the message prefix it stamps on every
152
- * pass-through when the body carried no type.
153
- */
154
- get isProviderPassthrough() {
155
- if (this.type === "authentication_error") return true;
156
- return this.message.startsWith(PROVIDER_ERROR_PREFIX);
157
- }
158
- };
159
- var ShashuBadRequestError = class _ShashuBadRequestError extends ShashuError {
160
- constructor(message, status, body, details) {
161
- super(message, status, body, details);
162
- this.name = "ShashuBadRequestError";
163
- Object.setPrototypeOf(this, _ShashuBadRequestError.prototype);
164
- }
165
- };
166
- var ShashuContextWindowExceeded = class _ShashuContextWindowExceeded extends ShashuBadRequestError {
167
- constructor(message, status, body, details) {
168
- super(message, status, body, details);
169
- this.name = "ShashuContextWindowExceeded";
170
- Object.setPrototypeOf(this, _ShashuContextWindowExceeded.prototype);
171
- }
172
- };
173
- var ShashuRateLimitError = class _ShashuRateLimitError extends ShashuError {
174
- constructor(message, status, body, details) {
175
- super(message, status, body, details);
176
- this.name = "ShashuRateLimitError";
177
- this.scope = details?.scope;
178
- this.retryAfterSeconds = details?.retryAfterSeconds;
179
- Object.setPrototypeOf(this, _ShashuRateLimitError.prototype);
180
- }
181
- };
182
- var ShashuPermissionError = class _ShashuPermissionError extends ShashuError {
183
- constructor(message, status, body, details) {
184
- super(message, status, body, details);
185
- this.name = "ShashuPermissionError";
186
- Object.setPrototypeOf(this, _ShashuPermissionError.prototype);
187
- }
188
- };
189
- var ShashuBudgetExceededError = class _ShashuBudgetExceededError extends ShashuPermissionError {
190
- constructor(message, status, body, details) {
191
- super(message, status, body, details);
192
- this.name = "ShashuBudgetExceededError";
193
- Object.setPrototypeOf(this, _ShashuBudgetExceededError.prototype);
194
- }
195
- };
196
- var ShashuPolicyViolation = class _ShashuPolicyViolation extends ShashuPermissionError {
197
- constructor(message, status, body, details) {
198
- super(message, status, body, details);
199
- this.name = "ShashuPolicyViolation";
200
- Object.setPrototypeOf(this, _ShashuPolicyViolation.prototype);
201
- }
202
- };
203
- var MemoryWriteBlocked = class _MemoryWriteBlocked extends ShashuPolicyViolation {
204
- constructor(message, status, body, details) {
205
- super(message, status, body, details);
206
- this.name = "MemoryWriteBlocked";
207
- Object.setPrototypeOf(this, _MemoryWriteBlocked.prototype);
208
- }
209
- /** The decision's memory block. */
210
- get memory() {
211
- return this.decision?.memory;
212
- }
213
- };
214
- var ShashuProviderError = class _ShashuProviderError extends ShashuError {
215
- constructor(message, status, body, details) {
216
- super(message, status, body, details);
217
- this.name = "ShashuProviderError";
218
- Object.setPrototypeOf(this, _ShashuProviderError.prototype);
219
- }
220
- };
221
- var ShashuContentFilterError = class _ShashuContentFilterError extends ShashuError {
222
- constructor(message, body, finishReason = null, status = 200, details) {
223
- super(message, status, body, details);
224
- this.name = "ShashuContentFilterError";
225
- this.finishReason = finishReason;
226
- Object.setPrototypeOf(this, _ShashuContentFilterError.prototype);
227
- }
228
- };
229
- function rateLimitDetail(err) {
230
- const inner = err?.details?.error;
231
- return inner && typeof inner === "object" ? inner : {};
232
- }
233
- function gatewayRetryAfter(res, parsedBody) {
234
- const fromHeader = parseRetryAfter(res.headers.get("retry-after"));
235
- if (fromHeader !== void 0) return fromHeader;
236
- if (!parsedBody || typeof parsedBody !== "object") return void 0;
237
- const err = parsedBody.error;
238
- const seconds = rateLimitDetail(err).retry_after_seconds;
239
- return typeof seconds === "number" ? seconds : void 0;
240
- }
241
- var HTTP_SHAPED_CODE = /^[0-9]{3}$/;
242
- function dispatchCode(code, status) {
243
- if (typeof code !== "string" || !HTTP_SHAPED_CODE.test(code)) return status;
244
- const parsed = Number.parseInt(code, 10);
245
- return parsed >= 100 && parsed < 600 ? parsed : status;
246
- }
247
- function parseRetryAfter(value) {
248
- if (!value) return void 0;
249
- const trimmed = value.trim();
250
- const asInt = Number(trimmed);
251
- if (Number.isFinite(asInt)) return asInt;
252
- const asDate = Date.parse(trimmed);
253
- if (!Number.isNaN(asDate)) {
254
- return Math.max(0, (asDate - Date.now()) / 1e3);
255
- }
256
- return void 0;
257
- }
258
- async function raiseForResponse(res, decision) {
259
- if (res.ok) return;
260
- const status = res.status;
261
- let body;
262
- let parsed = {};
263
- try {
264
- const text = await res.text();
265
- body = text;
266
- parsed = JSON.parse(text);
267
- body = parsed;
268
- } catch {
269
- }
270
- const err = parsed?.error ?? {};
271
- const message = typeof err.message === "string" && err.message || typeof parsed?.message === "string" && parsed.message || `SHASHU gateway error (HTTP ${status}).`;
272
- const type = err.type;
273
- const code = err.code;
274
- const details = { type, code, decision, responseHeaders: res.headers };
275
- const kind = dispatchCode(code, status);
276
- if (kind === 401) throw new ShashuAuthenticationError(message, status, body, details);
277
- if (kind === 429) {
278
- const detail = rateLimitDetail(err);
279
- const retryAfterSeconds = detail.retry_after_seconds ?? parseRetryAfter(res.headers.get("retry-after"));
280
- throw new ShashuRateLimitError(detail.message ?? message, status, body, {
281
- ...details,
282
- scope: detail.scope,
283
- retryAfterSeconds
284
- });
285
- }
286
- if (kind === 403) {
287
- if (decision !== void 0 && decision.memoryBlocked > 0) {
288
- throw new MemoryWriteBlocked(message, status, body, details);
289
- }
290
- throw new ShashuPolicyViolation(message, status, body, details);
291
- }
292
- if (kind === 400) {
293
- if (type === "context_window_exceeded") {
294
- throw new ShashuContextWindowExceeded(message, status, body, details);
295
- }
296
- if (type === "content_filter") {
297
- throw new ShashuContentFilterError(message, body, null, status, details);
298
- }
299
- throw new ShashuBadRequestError(message, status, body, details);
300
- }
301
- if (kind === 502 || kind === 503 || kind === 504) {
302
- throw new ShashuProviderError(message, status, body, details);
303
- }
304
- throw new ShashuError(message, status, body, details);
305
- }
306
- function raiseIfContentFiltered(json, decision, headers) {
307
- if (!json || typeof json !== "object") return;
308
- const choices = json.choices;
309
- if (!Array.isArray(choices) || choices.length === 0) return;
310
- const first = choices[0];
311
- if (first?.finish_reason === "content_filter") {
312
- throw new ShashuContentFilterError(
313
- "Response was blocked by the gateway content filter (finish_reason='content_filter').",
314
- json,
315
- "content_filter",
316
- 200,
317
- { decision, responseHeaders: headers }
318
- );
319
- }
320
- }
321
-
322
- // src/config.ts
323
- var BASE_URL_ENV = "SHASHU_BASE_URL";
324
- var API_KEY_ENV = "SHASHU_API_KEY";
325
- var DISABLE_ENV = "SHASHU_DISABLE";
326
- var TRUTHY = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);
327
- function env() {
328
- return typeof process !== "undefined" && process.env ? process.env : {};
329
- }
330
- function envGet(current2, _legacy) {
331
- const now = (env()[current2] ?? "").trim();
332
- return now || void 0;
333
- }
334
- function isDisabled() {
335
- return TRUTHY.has((envGet(DISABLE_ENV) ?? "").trim().toLowerCase());
336
- }
337
- function firstConfigured(baseUrl, envVars) {
338
- if (baseUrl && baseUrl.trim()) return baseUrl.trim().replace(/\/+$/, "");
339
- for (const name of envVars) {
340
- const value = env()[name]?.trim();
341
- if (value) return value.replace(/\/+$/, "");
342
- }
343
- return void 0;
344
- }
345
- function optionalBaseUrl(baseUrl, envVars = [BASE_URL_ENV]) {
346
- return firstConfigured(baseUrl, envVars);
347
- }
348
- function requireBaseUrl(baseUrl, opts) {
349
- const envVars = opts.envVars ?? [BASE_URL_ENV];
350
- const resolved = firstConfigured(baseUrl, envVars);
351
- if (resolved) return resolved;
352
- const option = opts.option ?? "baseUrl";
353
- const envHint = envVars.length === 1 ? `set the ${envVars[0]} environment variable` : `set one of the ${envVars.join(" or ")} environment variables`;
354
- throw new ShashuConfigError(
355
- `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.`
356
- );
357
- }
358
-
359
- // src/context.ts
360
- var import_node_crypto2 = require("crypto");
361
-
362
- // src/version.ts
363
- var SDK_VERSION = "1.1.1";
364
-
365
- // src/tracer.ts
366
- var import_node_async_hooks = require("async_hooks");
367
- var import_node_crypto = require("crypto");
368
- var spanStorage = new import_node_async_hooks.AsyncLocalStorage();
369
- var a2aStorage = new import_node_async_hooks.AsyncLocalStorage();
370
- function coerceHeaderMap(headers) {
371
- const out = {};
372
- if (!headers) return out;
373
- try {
374
- if (Array.isArray(headers)) {
375
- for (const pair of headers) {
376
- if (Array.isArray(pair) && pair.length >= 2 && pair[0] != null) {
377
- out[String(pair[0]).toLowerCase()] = String(pair[1]);
378
- }
379
- }
380
- return out;
381
- }
382
- if (headers instanceof Map) {
383
- for (const [k, v] of headers) out[String(k).toLowerCase()] = String(v);
384
- return out;
385
- }
386
- if (typeof headers.forEach === "function") {
387
- headers.forEach((v, k) => {
388
- if (k != null) out[String(k).toLowerCase()] = String(v);
389
- });
390
- return out;
391
- }
392
- if (typeof headers === "object") {
393
- for (const [k, v] of Object.entries(headers)) {
394
- if (v !== void 0 && v !== null) out[k.toLowerCase()] = String(v);
395
- }
396
- }
397
- } catch {
398
- return out;
399
- }
400
- return out;
401
- }
402
- function parseHopDepth(raw) {
403
- const n = parseInt(String(raw ?? "").trim(), 10);
404
- return Number.isFinite(n) && n > 0 ? n : 0;
405
- }
406
- function captureFromHeaders(h) {
407
- const trace = (h["x-shashu-trace-id"] ?? "").trim();
408
- if (!trace) return void 0;
409
- const session = (h["x-shashu-session-id"] ?? "").trim();
410
- const caller = (h["x-shashu-caller-agent-id"] ?? "").trim();
411
- return {
412
- traceId: trace,
413
- sessionId: session || void 0,
414
- inboundHopDepth: parseHopDepth(h["x-shashu-hop-depth"]),
415
- inboundCallerAgentId: caller || void 0
416
- };
417
- }
418
- var Tracer = class {
419
- /**
420
- * Resolves the address OPTIONALLY, unlike every other entry point.
421
- *
422
- * The module exports a singleton (`export const tracer = new Tracer()`), so
423
- * this constructor runs on `import "@shashu-ai/sdk"`. Throwing here would
424
- * make importing the SDK fail for anyone who has not set the variable, which
425
- * is a far worse failure than the one this is fixing. Instead the address
426
- * stays undefined and {@link flush} posts nothing — the same shape as the
427
- * Python SDK's telemetry path, which resolves with optional_base_url and
428
- * no-ops the flush.
429
- */
430
- constructor() {
431
- this.buffer = [];
432
- this.flushTimer = null;
433
- this._gatewayUrl = optionalBaseUrl();
434
- this._apiKey = envGet(API_KEY_ENV);
435
- }
436
- /**
437
- * Current gateway base URL (respects configure()), or undefined when none is
438
- * configured. Undefined means telemetry is not sent — never a default host.
439
- */
440
- get gatewayUrl() {
441
- return this._gatewayUrl;
442
- }
443
- /** Current API key (respects configure()). */
444
- get apiKey() {
445
- return this._apiKey;
446
- }
447
- /**
448
- * Update gateway URL and/or API key at runtime (e.g. for scripts switching agents).
449
- * baseUrl has its trailing slash stripped to match constructor behavior.
450
- */
451
- configure(opts) {
452
- if (opts.baseUrl !== void 0) {
453
- this._gatewayUrl = opts.baseUrl.replace(/\/$/, "");
454
- }
455
- if (opts.apiKey !== void 0) {
456
- this._apiKey = opts.apiKey;
457
- }
458
- }
459
- // --- Context Accessors ---
460
- get traceId() {
461
- return spanStorage.getStore()?.traceId ?? a2aStorage.getStore()?.traceId;
462
- }
463
- get currentSpanId() {
464
- const store = spanStorage.getStore();
465
- return store?.spanId;
466
- }
467
- /** The current span's PARENT span id; undefined at origin or for a root span. */
468
- get parentSpanId() {
469
- const store = spanStorage.getStore();
470
- return store?.parentId;
471
- }
472
- get isActive() {
473
- return !!spanStorage.getStore();
474
- }
475
- // --- A2A inbound-capture + outbound propagation (ADR-007 §0, §4.1 locked) ---
476
- /** True when this context CAPTURED an inbound flow — so a downstream gateway call
477
- * PROPAGATES the trace and attaches caller/session/hop lineage rather than originate
478
- * a new flow. False = origin (header set unchanged). */
479
- get isA2aHop() {
480
- const s = a2aStorage.getStore();
481
- return !!(s && s.traceId);
482
- }
483
- /** The captured inbound session id, or undefined when none was propagated. */
484
- get sessionId() {
485
- return a2aStorage.getStore()?.sessionId || void 0;
486
- }
487
- /** Advisory inbound hop depth captured from x-shashu-hop-depth (0 if absent). */
488
- get inboundHopDepth() {
489
- return a2aStorage.getStore()?.inboundHopDepth ?? 0;
490
- }
491
- /** Hop depth to advertise on the next downstream call = inbound + 1 (advisory; the
492
- * gateway recounts authoritatively). */
493
- get outboundHopDepth() {
494
- return this.inboundHopDepth + 1;
495
- }
496
- /** The captured inbound x-shashu-caller-agent-id — the upstream agent that INVOKED
497
- * this hop. The SDK FORWARDS this on the outbound gateway call so the gateway records
498
- * the real (invoker -> this agent) edge, NEVER this agent's own id (§4.1). undefined at
499
- * origin / caller-stripped. */
500
- get inboundCallerAgentId() {
501
- return a2aStorage.getStore()?.inboundCallerAgentId || void 0;
502
- }
503
- /**
504
- * Capture an inbound flow from the headers of a request this agent is SERVING into the
505
- * AsyncLocalStorage store, so a downstream call made through the SDK propagates the SAME
506
- * flow (WP-A2A-4 / ADR-007 §0). Reads (case-insensitively) x-shashu-trace-id (the flow
507
- * id), -session-id, -hop-depth, and -caller-agent-id (the upstream INVOKER). The captured
508
- * trace is PROPAGATED on the next outbound call (never re-minted); the session, inbound hop
509
- * depth, and inbound caller ride along — the caller is FORWARDED on the gateway call (§4.1),
510
- * never replaced by self.
511
- *
512
- * Uses enterWith, so the capture persists for the remainder of the current async execution
513
- * (one-shot, for a script serving a single inbound call). Servers handling many requests
514
- * should prefer {@link incoming} so one flow's lineage never leaks into the next. No inbound
515
- * trace ⇒ origin: the ambient capture is cleared and false is returned (non-A2A unaffected).
516
- * Never throws — telemetry must not break a request.
517
- */
518
- captureIncoming(headers) {
519
- const capture = captureFromHeaders(coerceHeaderMap(headers));
520
- a2aStorage.enterWith(capture);
521
- return capture !== void 0;
522
- }
523
- /**
524
- * Scoped inbound capture: capture for the duration of serving ONE request, then restore
525
- * the prior context on exit — so a long-lived worker does not leak one flow's lineage into
526
- * the next. Prefer this in servers; {@link captureIncoming} is the one-shot for scripts.
527
- *
528
- * @example
529
- * await tracer.incoming(req.headers, async () => {
530
- * await tg.fetch("/v1/chat/completions", { ... }); // propagates the captured flow
531
- * });
532
- */
533
- incoming(headers, callback) {
534
- const capture = captureFromHeaders(coerceHeaderMap(headers));
535
- return a2aStorage.run(capture, callback);
536
- }
537
- // --- Main Logic ---
538
- /**
539
- * Wraps a callback in a new Span Context.
540
- * Automatically handles Header injection for any internal calls.
541
- */
542
- async span(name, callback, metadata) {
543
- const parent = spanStorage.getStore();
544
- const traceId = parent?.traceId ?? a2aStorage.getStore()?.traceId ?? (0, import_node_crypto.randomUUID)();
545
- const spanId = (0, import_node_crypto.randomUUID)();
546
- const parentId = parent?.spanId;
547
- const context = { traceId, spanId, parentId };
548
- const startTime = Date.now() / 1e3;
549
- try {
550
- return await spanStorage.run(context, async () => {
551
- return await callback(spanId);
552
- });
553
- } finally {
554
- const endTime = Date.now() / 1e3;
555
- this.record({
556
- trace_id: traceId,
557
- span_id: spanId,
558
- parent_span_id: parentId,
559
- name,
560
- start_time: startTime,
561
- end_time: endTime,
562
- duration: endTime - startTime,
563
- metadata
564
- });
565
- }
566
- }
567
- // --- Telemetry Transport ---
568
- record(span) {
569
- if (isDisabled()) return;
570
- this.buffer.push(span);
571
- if (this.buffer.length >= 10) {
572
- this.flush();
573
- } else if (!this.flushTimer) {
574
- this.flushTimer = setTimeout(() => this.flush(), 1e3);
575
- this.flushTimer.unref();
576
- }
577
- }
578
- async flush() {
579
- if (this.flushTimer) {
580
- clearTimeout(this.flushTimer);
581
- this.flushTimer = null;
582
- }
583
- if (isDisabled()) return;
584
- if (this.buffer.length === 0 || !this._apiKey || !this._gatewayUrl) return;
585
- const batch = [...this.buffer];
586
- this.buffer = [];
587
- try {
588
- await fetch(`${this._gatewayUrl}/api/telemetry/spans`, {
589
- method: "POST",
590
- headers: {
591
- "Content-Type": "application/json",
592
- Authorization: `Bearer ${this._apiKey}`
593
- },
594
- body: JSON.stringify(batch)
595
- });
596
- } catch {
597
- }
598
- }
599
- };
600
- var tracer = new Tracer();
601
- function captureIncoming(headers) {
602
- return tracer.captureIncoming(headers);
603
- }
604
-
605
- // src/context.ts
606
- var HEADER_PREFIX = "x-shashu";
607
- var SOURCE_TOOL_HEADER = "x-shashu-source-tool";
608
- var DEFAULT_CONTRACT_VERSION = "2026-09-01";
609
- var CONTRACT_VERSION_HEADER = "shashu-version";
610
- function applyContractVersion(headers, contractVersion) {
611
- if (contractVersion === null) return headers;
612
- const named = Object.keys(headers).some((k) => k.toLowerCase() === CONTRACT_VERSION_HEADER);
613
- if (!named) headers[CONTRACT_VERSION_HEADER] = contractVersion ?? DEFAULT_CONTRACT_VERSION;
614
- return headers;
615
- }
616
- var N8N_KEYS = [
617
- "N8N_WORKFLOW_ID",
618
- "N8N_EXECUTION_ID",
619
- "N8N_WORKFLOW_NAME",
620
- "N8N_EXECUTION_MODE"
621
- ];
622
- var VERCEL_KEYS = [
623
- "VERCEL",
624
- "VERCEL_ENV",
625
- "VERCEL_URL",
626
- "VERCEL_GIT_COMMIT_REF",
627
- "VERCEL_GIT_REPO_ID",
628
- "VERCEL_GIT_COMMIT_SHA"
629
- ];
630
- var GITHUB_KEYS = [
631
- "GITHUB_ACTION",
632
- "GITHUB_ACTIONS",
633
- "GITHUB_WORKFLOW",
634
- "GITHUB_RUN_ID",
635
- "GITHUB_RUN_NUMBER",
636
- "GITHUB_REPOSITORY",
637
- "GITHUB_SHA"
638
- ];
639
- function pickEnv(keys) {
640
- const out = {};
641
- for (const key of keys) {
642
- const v = process.env[key];
643
- if (v !== void 0 && v !== "") out[key] = v;
644
- }
645
- return out;
646
- }
647
- function getBaseMetadata() {
648
- return {
649
- sdk_version: SDK_VERSION,
650
- node_version: process.version,
651
- os: process.platform,
652
- arch: process.arch
653
- };
654
- }
655
- function getWorkflowContextFromEnv() {
656
- const baseMeta = getBaseMetadata();
657
- const n8n = pickEnv(N8N_KEYS);
658
- if (Object.keys(n8n).length > 0) {
659
- return {
660
- source: "n8n",
661
- workflow_id: n8n.N8N_WORKFLOW_ID,
662
- execution_id: n8n.N8N_EXECUTION_ID,
663
- metadata: { ...baseMeta, ...n8n }
664
- };
665
- }
666
- const vercel = pickEnv(VERCEL_KEYS);
667
- if (Object.keys(vercel).length > 0) {
668
- return {
669
- source: "vercel",
670
- workflow_id: vercel.VERCEL_GIT_REPO_ID || vercel.VERCEL_URL,
671
- execution_id: vercel.VERCEL_GIT_COMMIT_SHA,
672
- metadata: { ...baseMeta, ...vercel }
673
- };
674
- }
675
- const github = pickEnv(GITHUB_KEYS);
676
- if (Object.keys(github).length > 0) {
677
- return {
678
- source: "github",
679
- workflow_id: github.GITHUB_WORKFLOW || github.GITHUB_REPOSITORY,
680
- execution_id: github.GITHUB_RUN_ID || github.GITHUB_RUN_NUMBER,
681
- metadata: { ...baseMeta, ...github }
682
- };
683
- }
684
- return {
685
- source: "local_script",
686
- metadata: baseMeta
687
- };
688
- }
689
- function buildSourceToolJson(ctx) {
690
- const meta = ctx.metadata ?? getBaseMetadata();
691
- const payload = {
692
- source: ctx.source,
693
- metadata: meta
694
- };
695
- if (ctx.workflow_id !== void 0) payload.workflow_id = ctx.workflow_id;
696
- if (ctx.execution_id !== void 0) payload.execution_id = ctx.execution_id;
697
- if (ctx.workflow_step !== void 0) payload.workflow_step = ctx.workflow_step;
698
- return JSON.stringify(payload);
699
- }
700
- var TRUSTLOG_HEADER_PREFIX = "x-trustlog-";
701
- function resolveOriginTraceId() {
702
- const n8n = process.env.N8N_EXECUTION_ID;
703
- if (n8n) return n8n;
704
- const github = process.env.GITHUB_RUN_ID;
705
- if (github) return github;
706
- const gitlab = process.env.CI_PIPELINE_ID;
707
- if (process.env.GITLAB_CI && gitlab) return gitlab;
708
- return (0, import_node_crypto2.randomUUID)();
709
- }
710
- function lowercaseHeaderKeys(h) {
711
- const out = {};
712
- for (const [k, v] of Object.entries(h)) out[k.toLowerCase()] = v;
713
- return out;
714
- }
715
- function buildContextHeaders(ctx, session) {
716
- const meta = ctx.metadata ?? getBaseMetadata();
717
- const h = {
718
- [SOURCE_TOOL_HEADER]: buildSourceToolJson({ ...ctx, metadata: meta }),
719
- [`${HEADER_PREFIX}-source`]: ctx.source
720
- };
721
- if (ctx.workflow_id) h[`${HEADER_PREFIX}-workflow-id`] = ctx.workflow_id;
722
- if (ctx.execution_id) h[`${HEADER_PREFIX}-execution-id`] = ctx.execution_id;
723
- if (ctx.workflow_step) h[`${HEADER_PREFIX}-workflow-step`] = ctx.workflow_step;
724
- for (const [k, v] of Object.entries(meta)) {
725
- if (v) h[`${TRUSTLOG_HEADER_PREFIX}${k.replace(/_/g, "-")}`] = String(v);
726
- }
727
- if (tracer.isActive) {
728
- if (tracer.traceId) h["x-shashu-trace-id"] = tracer.traceId;
729
- h["x-shashu-span-id"] = tracer.currentSpanId ?? "";
730
- h["x-shashu-parent-id"] = tracer.parentSpanId ?? "";
731
- } else if (tracer.isA2aHop) {
732
- if (tracer.traceId) h["x-shashu-trace-id"] = tracer.traceId;
733
- } else if (!h["x-shashu-trace-id"]) {
734
- h["x-shashu-trace-id"] = resolveOriginTraceId();
735
- }
736
- const sessionId = resolveSessionId(session);
737
- if (sessionId) h["x-shashu-session-id"] = sessionId;
738
- if (tracer.isA2aHop) {
739
- const inboundCaller = tracer.inboundCallerAgentId;
740
- if (inboundCaller) h["x-shashu-caller-agent-id"] = inboundCaller;
741
- h["x-shashu-hop-depth"] = String(tracer.outboundHopDepth);
742
- }
743
- return lowercaseHeaderKeys(h);
744
- }
745
- function resolveSessionId(opts) {
746
- if (opts?.requestSessionId != null && String(opts.requestSessionId) !== "") {
747
- return String(opts.requestSessionId);
748
- }
749
- const captured = tracer.sessionId;
750
- if (captured) return captured;
751
- if (opts?.defaultSessionId != null && String(opts.defaultSessionId) !== "") {
752
- return String(opts.defaultSessionId);
753
- }
754
- return void 0;
755
- }
756
- function buildInvocationHeaders(opts) {
757
- const trace = opts.traceId ?? tracer.traceId ?? (0, import_node_crypto2.randomUUID)();
758
- const hop = opts.hopDepth ?? tracer.outboundHopDepth;
759
- const session = resolveSessionId({ requestSessionId: opts.sessionId });
760
- const h = {
761
- "x-shashu-trace-id": String(trace),
762
- "x-shashu-caller-agent-id": String(opts.callerAgentId),
763
- "x-shashu-hop-depth": String(hop)
764
- };
765
- if (session) h["x-shashu-session-id"] = String(session);
766
- return lowercaseHeaderKeys(h);
767
- }
768
-
769
- // src/audit.ts
770
- var Audit = class {
771
- constructor(client) {
772
- this.client = client;
773
- }
774
- /**
775
- * POST a post-hoc audit event for scanning + audit-only logging.
776
- *
777
- * Non-2xx responses throw the typed exception hierarchy (e.g.
778
- * ShashuPolicyViolation on 403 when the connector key is invalid),
779
- * raised by `client.fetch`.
780
- */
781
- async events(input, options) {
782
- const body = {
783
- source: input.source,
784
- conversation: input.conversation
785
- };
786
- if (input.externalEventId !== void 0) {
787
- body.external_event_id = input.externalEventId;
788
- }
789
- if (input.occurredAt !== void 0) {
790
- body.occurred_at = input.occurredAt;
791
- }
792
- if (input.userContext !== void 0) {
793
- body.user_context = input.userContext;
794
- }
795
- if (input.traceId !== void 0) {
796
- body.trace_id = input.traceId;
797
- }
798
- if (input.parentSpanId !== void 0) {
799
- body.parent_span_id = input.parentSpanId;
800
- }
801
- if (input.sessionId !== void 0) {
802
- body.session_id = input.sessionId;
803
- }
804
- const res = await this.client.fetch(
805
- "/v1/audit/events",
806
- {
807
- method: "POST",
808
- body: JSON.stringify(body)
809
- },
810
- options
811
- );
812
- return await res.json();
813
- }
814
- };
815
-
816
- // src/retry.ts
817
- var DEFAULT_RETRY_POLICY = {
818
- maxRetries: 2,
819
- backoffBaseSeconds: 0.5,
820
- backoffMaxSeconds: 30,
821
- retryOnConnectionErrors: true,
822
- retryOn429: true,
823
- retryOn5xx: false,
824
- neverRetryStatus: [400, 401, 403, 404],
825
- ignoreRetryAfter: false,
826
- jitterFraction: 0.2
827
- };
828
- function resolveRetryPolicy(policy) {
829
- if (policy === null) return null;
830
- if (policy === void 0) return { ...DEFAULT_RETRY_POLICY };
831
- return { ...DEFAULT_RETRY_POLICY, ...policy };
832
- }
833
- function shouldRetryStatus(policy, status) {
834
- if (policy.neverRetryStatus.includes(status)) return false;
835
- if (status === 429) return policy.retryOn429;
836
- if (status === 503) return true;
837
- if (status >= 500 && status <= 599) return policy.retryOn5xx;
838
- return false;
839
- }
840
- function truthyHeader(value) {
841
- return ["1", "true", "yes", "on"].includes((value ?? "").trim().toLowerCase());
842
- }
843
- function gatewaySaysBusyRetry(res, retryAfter) {
844
- if (res.status !== 429 && res.status !== 503) return false;
845
- if (truthyHeader(res.headers.get("x-should-retry"))) return true;
846
- return retryAfter !== void 0;
847
- }
848
- function shouldRetryResponse(policy, res, retryAfter) {
849
- if (policy.neverRetryStatus.includes(res.status)) return false;
850
- if (res.status === 429 || res.status === 503) {
851
- if (res.status === 429 && !policy.retryOn429) return false;
852
- return gatewaySaysBusyRetry(res, retryAfter);
853
- }
854
- if (!shouldRetryStatus(policy, res.status)) return false;
855
- return true;
856
- }
857
- function delayFor(policy, attempt, res, retryAfter) {
858
- const jitter = (seconds) => {
859
- const frac = policy.jitterFraction ?? 0.2;
860
- const capped = Math.min(policy.backoffMaxSeconds, seconds);
861
- if (frac <= 0) return capped;
862
- return Math.min(policy.backoffMaxSeconds, capped * (1 + Math.random() * frac));
863
- };
864
- if (res !== null && (res.status === 429 || res.status === 503) && !policy.ignoreRetryAfter && retryAfter !== void 0) {
865
- return jitter(retryAfter);
866
- }
867
- return jitter(policy.backoffBaseSeconds * 2 ** attempt);
868
- }
869
- function isConnectionError(err) {
870
- return err instanceof TypeError;
871
- }
872
- var defaultSleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1e3));
873
- async function peekJson(res) {
874
- try {
875
- return await res.clone().json();
876
- } catch {
877
- return void 0;
878
- }
879
- }
880
- async function executeWithRetry(send, policy, sleep = defaultSleep) {
881
- if (policy === null) return send();
882
- let attempt = 0;
883
- for (; ; ) {
884
- let res;
885
- try {
886
- res = await send();
887
- } catch (err) {
888
- if (policy.retryOnConnectionErrors && isConnectionError(err) && attempt < policy.maxRetries) {
889
- await sleep(delayFor(policy, attempt, null, void 0));
890
- attempt += 1;
891
- continue;
892
- }
893
- throw err;
894
- }
895
- const retryAfter = res.status === 429 || res.status === 503 ? gatewayRetryAfter(res, await peekJson(res)) : void 0;
896
- if (attempt < policy.maxRetries && shouldRetryResponse(policy, res, retryAfter)) {
897
- await sleep(delayFor(policy, attempt, res, retryAfter));
898
- attempt += 1;
899
- continue;
900
- }
901
- return res;
902
- }
903
- }
904
-
905
- // src/_bus.ts
906
- var import_node_async_hooks2 = require("async_hooks");
907
- var MAX_EVENTS = 8;
908
- var MAX_DOCS = 64;
909
- var MAX_PREVIEW_CHARS = 2048;
910
- var MAX_CORPUS_CHARS = 256;
911
- var MAX_QUERY_CHARS = 4096;
912
- var EMPTY = Object.freeze([]);
913
- var BUS = new import_node_async_hooks2.AsyncLocalStorage();
914
- function current() {
915
- return BUS.getStore()?.events ?? EMPTY;
916
- }
917
- function push(event) {
918
- if (!event.docs || event.docs.length === 0) return;
919
- const store = BUS.getStore();
920
- const next = trim([...store?.events ?? EMPTY, event]);
921
- if (store?.shared) {
922
- store.events = next;
923
- return;
924
- }
925
- BUS.enterWith({ events: next, shared: false });
926
- }
927
- function snapshot() {
928
- return current();
929
- }
930
- function clear() {
931
- const store = BUS.getStore();
932
- if (store) {
933
- store.events = EMPTY;
934
- return;
935
- }
936
- BUS.enterWith({ events: EMPTY, shared: false });
937
- }
938
- function hasEvents() {
939
- return current().length > 0;
940
- }
941
- function runWith(state, fn) {
942
- return BUS.run({ events: state, shared: true }, fn);
943
- }
944
- function trim(events) {
945
- const recent = events.slice(-MAX_EVENTS);
946
- let budget = MAX_DOCS;
947
- const kept = [];
948
- for (let i = recent.length - 1; i >= 0; i -= 1) {
949
- if (budget <= 0) break;
950
- const event = recent[i];
951
- if (event.docs.length > budget) {
952
- kept.push({ ...event, docs: event.docs.slice(-budget) });
953
- budget = 0;
954
- } else {
955
- budget -= event.docs.length;
956
- kept.push(event);
957
- }
958
- }
959
- kept.reverse();
960
- return Object.freeze(kept);
961
- }
962
-
963
- // src/rag.ts
964
- function makeRagContext(input) {
965
- const out = {};
966
- if (input.corpus !== void 0) out.corpus = input.corpus;
967
- if (input.query !== void 0) out.query = input.query;
968
- if (input.docs !== void 0) out.docs = input.docs;
969
- return out;
970
- }
971
- function attachRagContext(body, ragContext) {
972
- if (body === null || typeof body !== "object") {
973
- throw new TypeError("body must be an object");
974
- }
975
- if (ragContext === null || typeof ragContext !== "object") {
976
- throw new TypeError("ragContext must be an object");
977
- }
978
- const existing = body.shashu_metadata;
979
- const meta = existing !== null && typeof existing === "object" ? existing : {};
980
- meta.rag_context = ragContext;
981
- body.shashu_metadata = meta;
982
- return body;
983
- }
984
- var SOURCES = [
985
- "manual",
986
- "langchain",
987
- "llamaindex",
988
- "tool",
989
- "otel",
990
- "n8n",
991
- "provider",
992
- "other"
993
- ];
994
- var HEX = /^[0-9a-fA-F]{8,64}$/;
995
- var SCORE_MIN = -1;
996
- var SCORE_MAX = 1e6;
997
- var MAX_ID_CHARS = 512;
998
- var MAX_SOURCE_URI_CHARS = 2048;
999
- var PREVIEW_KEYS = ["preview", "text", "content", "pageContent", "page_content", "body"];
1000
- var ID_KEYS = [
1001
- "id",
1002
- "doc_id",
1003
- "docId",
1004
- "documentId",
1005
- "document_id",
1006
- "nodeId",
1007
- "node_id",
1008
- "id_",
1009
- "_id"
1010
- ];
1011
- var SCORE_KEYS = ["score", "similarity", "relevance"];
1012
- var SOURCE_URI_KEYS = [
1013
- "source_uri",
1014
- "sourceUri",
1015
- "url",
1016
- "uri",
1017
- "source",
1018
- "file_path",
1019
- "filePath",
1020
- "file_name",
1021
- "fileName"
1022
- ];
1023
- var HASH_KEYS = ["hash", "sha256", "digest"];
1024
- var FIELD_KEYS = [
1025
- ["preview", PREVIEW_KEYS],
1026
- ["id", ID_KEYS],
1027
- ["score", SCORE_KEYS],
1028
- ["source_uri", SOURCE_URI_KEYS],
1029
- ["hash", HASH_KEYS]
1030
- ];
1031
- function has(...props) {
1032
- return (doc) => typeof doc === "object" && doc !== null && props.every((p) => doc[p] !== void 0);
1033
- }
1034
- var isObject = (doc) => typeof doc === "object" && doc !== null;
1035
- function gather(doc) {
1036
- const found = {};
1037
- for (const [field, keys] of FIELD_KEYS) {
1038
- for (const key of keys) {
1039
- const value = doc[key];
1040
- if (value !== void 0 && value !== null) {
1041
- found[field] = value;
1042
- break;
1043
- }
1044
- }
1045
- }
1046
- const metadata = doc.metadata;
1047
- if (isObject(metadata)) {
1048
- for (const [field, keys] of FIELD_KEYS) {
1049
- if (found[field] !== void 0 || field === "preview") continue;
1050
- for (const key of keys) {
1051
- const value = metadata[key];
1052
- if (value !== void 0 && value !== null) {
1053
- found[field] = value;
1054
- break;
1055
- }
1056
- }
1057
- }
1058
- }
1059
- return found;
1060
- }
1061
- function fromScoredNode(doc) {
1062
- const inner = readDocument(doc.node);
1063
- return doc.score !== void 0 && doc.score !== null ? { ...inner, score: doc.score } : inner;
1064
- }
1065
- var COERCIONS = [
1066
- { name: "string", matches: (d) => typeof d === "string", read: (d) => ({ preview: d }) },
1067
- { name: "scored_node", matches: has("node"), read: fromScoredNode },
1068
- { name: "langchain_document", matches: has("pageContent"), read: gather },
1069
- { name: "preview_object", matches: has("preview"), read: gather },
1070
- { name: "text_node", matches: has("text"), read: gather },
1071
- { name: "object", matches: isObject, read: gather }
1072
- ];
1073
- function readDocument(doc) {
1074
- for (const rule of COERCIONS) {
1075
- if (rule.matches(doc)) return rule.read(doc);
1076
- }
1077
- return {};
1078
- }
1079
- function asText(value, limit) {
1080
- if (typeof value !== "string") return void 0;
1081
- return value.slice(0, limit) || void 0;
1082
- }
1083
- function asId(value, position) {
1084
- if (typeof value === "string") {
1085
- const cleaned = value.trim().slice(0, MAX_ID_CHARS);
1086
- if (cleaned) return cleaned;
1087
- }
1088
- if (typeof value === "number" && Number.isFinite(value)) return String(value);
1089
- return `doc-${position}`;
1090
- }
1091
- function asScore(value) {
1092
- let candidate = value;
1093
- if (typeof candidate === "string") {
1094
- if (!candidate.trim()) return void 0;
1095
- const parsed = Number(candidate);
1096
- if (Number.isNaN(parsed)) return void 0;
1097
- candidate = parsed;
1098
- }
1099
- if (typeof candidate !== "number") return void 0;
1100
- if (!Number.isFinite(candidate) || candidate < SCORE_MIN || candidate > SCORE_MAX) {
1101
- return void 0;
1102
- }
1103
- return candidate;
1104
- }
1105
- function normalise(raw, position) {
1106
- const preview = asText(raw.preview, MAX_PREVIEW_CHARS);
1107
- if (preview === void 0) return void 0;
1108
- const out = { id: asId(raw.id, position), preview };
1109
- const score = asScore(raw.score);
1110
- if (score !== void 0) out.score = score;
1111
- const sourceUri = asText(raw.source_uri, MAX_SOURCE_URI_CHARS);
1112
- if (sourceUri !== void 0) out.source_uri = sourceUri;
1113
- if (typeof raw.hash === "string" && HEX.test(raw.hash)) out.hash = raw.hash;
1114
- return out;
1115
- }
1116
- function asDocumentList(docs) {
1117
- if (typeof docs === "string") return [docs];
1118
- if (Array.isArray(docs)) return docs;
1119
- if (isObject(docs) && typeof docs[Symbol.iterator] === "function") {
1120
- return Array.from(docs);
1121
- }
1122
- return [docs];
1123
- }
1124
- function coerceDocs(docs) {
1125
- const out = [];
1126
- let position = 0;
1127
- for (const doc of asDocumentList(docs)) {
1128
- position += 1;
1129
- const normalised = normalise(readDocument(doc), position);
1130
- if (normalised !== void 0) out.push(normalised);
1131
- }
1132
- return out;
1133
- }
1134
- function requireCorpus(corpus) {
1135
- if (typeof corpus !== "string" || !corpus.trim()) {
1136
- throw new TypeError(
1137
- "declareRetrieval() needs a non-empty corpus: it is what the gateway records the documents as having come from, and rag_context.v1 requires it."
1138
- );
1139
- }
1140
- return corpus.trim().slice(0, MAX_CORPUS_CHARS);
1141
- }
1142
- function requireSource(source) {
1143
- if (!SOURCES.includes(source)) {
1144
- throw new TypeError(
1145
- `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.`
1146
- );
1147
- }
1148
- return source;
1149
- }
1150
- function declareRetrieval(docs, options) {
1151
- if (isDisabled()) return;
1152
- const corpus = requireCorpus(options.corpus);
1153
- const source = requireSource(options.source ?? "manual");
1154
- push({
1155
- corpus,
1156
- query: asText(options.query, MAX_QUERY_CHARS),
1157
- source,
1158
- docs: coerceDocs(docs)
1159
- });
1160
- }
1161
- async function retrievalScope(docs, options, fn) {
1162
- if (isDisabled()) return await fn();
1163
- const before = snapshot();
1164
- return await runWith(before, async () => {
1165
- declareRetrieval(docs, options);
1166
- return await fn();
1167
- });
1168
- }
1169
- function dedupe(docs) {
1170
- const seen = /* @__PURE__ */ new Set();
1171
- const out = [];
1172
- for (const doc of docs) {
1173
- const key = `${doc.id}\0${doc.preview}`;
1174
- if (seen.has(key)) continue;
1175
- seen.add(key);
1176
- out.push(doc);
1177
- }
1178
- return out;
1179
- }
1180
- function buildRagContext(events) {
1181
- events = events.filter((event) => event.kind !== "memory");
1182
- const docs = dedupe(events.flatMap((event) => event.docs)).slice(-MAX_DOCS);
1183
- if (docs.length === 0) return void 0;
1184
- const corpora = [...new Set(events.map((event) => event.corpus))];
1185
- const corpus = corpora.length === 1 ? corpora[0] : corpora.join("+").slice(0, MAX_CORPUS_CHARS).replace(/\++$/, "");
1186
- const sources = new Set(events.map((event) => event.source));
1187
- const queries = events.map((event) => event.query).filter((q) => !!q);
1188
- const context = {
1189
- v: 1,
1190
- corpus,
1191
- source: sources.size === 1 ? [...sources][0] : "other",
1192
- docs
1193
- };
1194
- if (queries.length) context.query = queries[queries.length - 1];
1195
- return context;
1196
- }
1197
-
1198
- // src/memory.ts
1199
- var MEMORY_SOURCES = [
1200
- "sdk",
1201
- "manual",
1202
- "langchain",
1203
- "llamaindex",
1204
- "tool",
1205
- "otel",
1206
- "n8n",
1207
- "provider",
1208
- "hosted",
1209
- "other"
1210
- ];
1211
- var MEMORY_SCOPES = ["agent", "crew", "tenant"];
1212
- function requireStore(store) {
1213
- if (!store || !store.trim()) {
1214
- throw new TypeError(
1215
- "declareMemory needs a non-empty store: it is what the gateway records the items as having come from, and memory_context.v1 requires it."
1216
- );
1217
- }
1218
- return store.trim().slice(0, MAX_CORPUS_CHARS);
1219
- }
1220
- function requireScope(scope) {
1221
- const value = scope || "agent";
1222
- if (!MEMORY_SCOPES.includes(value)) {
1223
- throw new TypeError(`declareMemory scope='${scope}' is not a memory_context.v1 value.`);
1224
- }
1225
- return value;
1226
- }
1227
- function requireSource2(source) {
1228
- const value = source || "sdk";
1229
- if (!MEMORY_SOURCES.includes(value)) {
1230
- throw new TypeError(`declareMemory source='${source}' is not a memory_context.v1 value.`);
1231
- }
1232
- return value;
1233
- }
1234
- function declareMemory(items, options) {
1235
- if (isDisabled()) return;
1236
- const docs = coerceDocs(items);
1237
- if (docs.length === 0) return;
1238
- push({
1239
- kind: "memory",
1240
- corpus: requireStore(options.store),
1241
- query: requireScope(options.scope),
1242
- source: requireSource2(options.source),
1243
- docs
1244
- });
1245
- }
1246
- async function memoryScope(items, options, fn) {
1247
- if (isDisabled()) return await fn();
1248
- const before = snapshot();
1249
- return await runWith(before, async () => {
1250
- declareMemory(items, options);
1251
- return await fn();
1252
- });
1253
- }
1254
- function buildMemoryContext(events) {
1255
- const mem = events.filter((e) => e.kind === "memory");
1256
- const items = mem.flatMap((e) => e.docs.map((d) => ({ id: d.id, preview: d.preview }))).slice(-MAX_DOCS);
1257
- if (items.length === 0) return void 0;
1258
- const stores = [...new Set(mem.map((e) => e.corpus))];
1259
- const sources = new Set(mem.map((e) => e.source));
1260
- const scope = mem[mem.length - 1]?.query || "agent";
1261
- return {
1262
- v: 1,
1263
- store: stores.length === 1 ? stores[0] : stores.join("+").slice(0, MAX_CORPUS_CHARS),
1264
- scope,
1265
- source: sources.size === 1 ? [...sources][0] : "other",
1266
- items
1267
- };
1268
- }
1269
- function attachMemoryContext(body, memoryContext) {
1270
- const bag = body;
1271
- const existing = bag.shashu_metadata;
1272
- const metadata = existing !== null && typeof existing === "object" ? existing : {};
1273
- bag.shashu_metadata = { ...metadata, memory_context: memoryContext };
1274
- return body;
1275
- }
1276
-
1277
- // src/_joiner.ts
1278
- var globalFetch = (input, init) => globalThis.fetch(input, init);
1279
- function parseJsonObject(body) {
1280
- if (typeof body !== "string") return void 0;
1281
- if (!/^[\s]*\{/.test(body)) return void 0;
1282
- try {
1283
- const parsed = JSON.parse(body);
1284
- return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
1285
- } catch {
1286
- return void 0;
1287
- }
1288
- }
1289
- function metadataBag(body) {
1290
- const metadata = body.shashu_metadata;
1291
- if (metadata !== null && typeof metadata === "object") {
1292
- return metadata;
1293
- }
1294
- return void 0;
1295
- }
1296
- function hasExplicitRagContext(body) {
1297
- const metadata = metadataBag(body);
1298
- return metadata?.rag_context !== void 0 && metadata?.rag_context !== null;
1299
- }
1300
- function hasExplicitMemoryContext(body) {
1301
- const metadata = metadataBag(body);
1302
- return metadata?.memory_context !== void 0 && metadata?.memory_context !== null;
1303
- }
1304
- function fixContentLength(headers, byteLength2) {
1305
- const value = String(byteLength2);
1306
- if (headers instanceof Headers) {
1307
- if (headers.has("content-length")) headers.set("content-length", value);
1308
- return headers;
1309
- }
1310
- if (Array.isArray(headers)) {
1311
- return headers.map(
1312
- (pair) => Array.isArray(pair) && String(pair[0]).toLowerCase() === "content-length" ? [pair[0], value] : pair
1313
- );
1314
- }
1315
- if (headers !== null && typeof headers === "object") {
1316
- const out = { ...headers };
1317
- for (const key of Object.keys(out)) {
1318
- if (key.toLowerCase() === "content-length") out[key] = value;
1319
- }
1320
- return out;
1321
- }
1322
- return headers;
1323
- }
1324
- function hasConflictingCorpora(events) {
1325
- if (events.length <= 1) return false;
1326
- const first = events[0].corpus;
1327
- for (let i = 1; i < events.length; i += 1) {
1328
- if (events[i].corpus !== first) return true;
1329
- }
1330
- return false;
1331
- }
1332
- function takeContextFor(body) {
1333
- const events = snapshot();
1334
- const ragEvents = events.filter((e) => e.kind !== "memory");
1335
- const memEvents = events.filter((e) => e.kind === "memory");
1336
- const explicitRag = hasExplicitRagContext(body);
1337
- const explicitMem = hasExplicitMemoryContext(body);
1338
- clear();
1339
- let mutated = false;
1340
- if (!explicitRag) {
1341
- if (hasConflictingCorpora(ragEvents)) {
1342
- } else {
1343
- const context = buildRagContext(ragEvents);
1344
- if (context !== void 0) {
1345
- attachRagContext(body, context);
1346
- mutated = true;
1347
- }
1348
- }
1349
- }
1350
- if (!explicitMem) {
1351
- const memoryContext = buildMemoryContext(memEvents);
1352
- if (memoryContext !== void 0) {
1353
- attachMemoryContext(body, memoryContext);
1354
- mutated = true;
1355
- }
1356
- }
1357
- return mutated ? body : void 0;
1358
- }
1359
- function pinOutgoing(input, init) {
1360
- if (!hasEvents()) return { input, init };
1361
- if (isDisabled()) {
1362
- clear();
1363
- return { input, init };
1364
- }
1365
- const body = parseJsonObject(init?.body);
1366
- if (body === void 0) return { input, init };
1367
- const merged = takeContextFor(body);
1368
- if (merged === void 0) return { input, init };
1369
- const encoded = JSON.stringify(merged);
1370
- return {
1371
- input,
1372
- init: {
1373
- ...init,
1374
- body: encoded,
1375
- headers: fixContentLength(init?.headers, byteLength(encoded))
1376
- }
1377
- };
1378
- }
1379
- function withRetrievalJoiner(underlying = globalFetch) {
1380
- return async function trustgateJoiningFetch(input, init) {
1381
- if (!hasEvents()) return underlying(input, init);
1382
- if (isDisabled()) {
1383
- clear();
1384
- return underlying(input, init);
1385
- }
1386
- try {
1387
- if (typeof Request !== "undefined" && input instanceof Request) {
1388
- const body2 = parseJsonObject(await input.clone().text());
1389
- if (body2 === void 0) return underlying(input, init);
1390
- const merged2 = takeContextFor(body2);
1391
- if (merged2 === void 0) return underlying(input, init);
1392
- const encoded2 = JSON.stringify(merged2);
1393
- const replacement = new Request(input, { body: encoded2 });
1394
- if (replacement.headers.has("content-length")) {
1395
- replacement.headers.set("content-length", String(byteLength(encoded2)));
1396
- }
1397
- return underlying(replacement, init);
1398
- }
1399
- const body = parseJsonObject(init?.body);
1400
- if (body === void 0) return underlying(input, init);
1401
- const merged = takeContextFor(body);
1402
- if (merged === void 0) return underlying(input, init);
1403
- const encoded = JSON.stringify(merged);
1404
- return underlying(input, {
1405
- ...init,
1406
- body: encoded,
1407
- headers: fixContentLength(init?.headers, byteLength(encoded))
1408
- });
1409
- } catch {
1410
- return underlying(input, init);
1411
- }
1412
- };
1413
- }
1414
- function byteLength(text) {
1415
- return new TextEncoder().encode(text).length;
1416
- }
1417
-
1418
- // src/decision.ts
1419
- var DECISION_ALLOW = "allow";
1420
- var DECISION_ALLOW_ALTERED = "allow_altered";
1421
- var DECISION_NOT_CHECKED = "not_checked";
1422
- var DECISION_BLOCK = "block";
1423
- var DECISION_REFUSE = "refuse";
1424
- var DECISION_FAIL = "fail";
1425
- var DECISIONS = [
1426
- DECISION_ALLOW,
1427
- DECISION_ALLOW_ALTERED,
1428
- DECISION_NOT_CHECKED,
1429
- DECISION_BLOCK,
1430
- DECISION_REFUSE,
1431
- DECISION_FAIL
1432
- ];
1433
- var DELIVERED_DECISIONS = /* @__PURE__ */ new Set([
1434
- DECISION_ALLOW,
1435
- DECISION_ALLOW_ALTERED,
1436
- DECISION_NOT_CHECKED
1437
- ]);
1438
- var BODY_KEY = "shashu";
1439
- var HEADER_DECISION = "x-shashu-decision";
1440
- var HEADER_CODE = "x-shashu-code";
1441
- var HEADER_INSPECTION = "x-shashu-inspection";
1442
- var HEADER_SHOULD_RETRY = "x-should-retry";
1443
- var HEADER_REQUEST_ID = "x-request-id";
1444
- var HEADER_SHASHU_REQUEST_ID = "x-shashu-request-id";
1445
- var HEADER_TRACE_ID = "x-shashu-trace-id";
1446
- var HEADER_ATTACHMENTS = "x-shashu-attachments";
1447
- var HEADER_MEMORY = "x-shashu-memory";
1448
- var ATTACHMENT_STATES = /* @__PURE__ */ new Set([
1449
- "scanned",
1450
- "scanned_partial",
1451
- "not_inspected",
1452
- "blocked"
1453
- ]);
1454
- var carried = /* @__PURE__ */ new WeakMap();
1455
- function rememberDecision(obj, decision) {
1456
- carried.set(obj, decision);
1457
- }
1458
- function coerceDecision(raw) {
1459
- if (typeof raw === "string" && DECISIONS.includes(raw)) {
1460
- return raw;
1461
- }
1462
- return DECISION_BLOCK;
1463
- }
1464
- function parseInspectionHeader(value) {
1465
- if (typeof value !== "string" || !value.trim()) return void 0;
1466
- const out = {};
1467
- const detectors = {};
1468
- for (const part of value.split(";")) {
1469
- if (!part.includes("=")) continue;
1470
- const eq = part.indexOf("=");
1471
- const name = part.slice(0, eq).trim();
1472
- const state = part.slice(eq + 1).trim();
1473
- if (name === "input" || name === "output" || name === "reason") out[name] = state;
1474
- else if (name) detectors[name] = state;
1475
- }
1476
- if (Object.keys(detectors).length) out.detectors = detectors;
1477
- return Object.keys(out).length ? out : void 0;
1478
- }
1479
- function headerGet(headers, name) {
1480
- if (headers == null) return void 0;
1481
- try {
1482
- if (typeof headers.get === "function") {
1483
- const v = headers.get(name);
1484
- return v == null ? void 0 : v;
1485
- }
1486
- const rec = headers;
1487
- const direct = rec[name];
1488
- if (typeof direct === "string") return direct;
1489
- const lower = name.toLowerCase();
1490
- for (const [k, v] of Object.entries(rec)) {
1491
- if (k.toLowerCase() === lower && typeof v === "string") return v;
1492
- }
1493
- } catch {
1494
- return void 0;
1495
- }
1496
- return void 0;
1497
- }
1498
- function fromBody(body) {
1499
- if (body == null || typeof body !== "object" || Array.isArray(body)) return void 0;
1500
- const rec = body;
1501
- const top = rec[BODY_KEY];
1502
- if (top != null && typeof top === "object" && !Array.isArray(top)) {
1503
- return top;
1504
- }
1505
- const err = rec.error;
1506
- if (err != null && typeof err === "object" && !Array.isArray(err)) {
1507
- const nested = err[BODY_KEY];
1508
- if (nested != null && typeof nested === "object" && !Array.isArray(nested)) {
1509
- return nested;
1510
- }
1511
- }
1512
- return void 0;
1513
- }
1514
- function fromHeaders(headers) {
1515
- const raw = headerGet(headers, HEADER_DECISION);
1516
- if (typeof raw !== "string" || !raw.trim()) return void 0;
1517
- const env2 = { decision: raw.trim() };
1518
- const code = headerGet(headers, HEADER_CODE);
1519
- if (typeof code === "string" && code.trim()) env2.code = code.trim();
1520
- const recordId = headerGet(headers, HEADER_REQUEST_ID);
1521
- if (typeof recordId === "string" && recordId.trim()) env2.id = recordId.trim();
1522
- const hopId = headerGet(headers, HEADER_SHASHU_REQUEST_ID);
1523
- if (typeof hopId === "string" && hopId.trim()) env2.request_id = hopId.trim();
1524
- const trace = headerGet(headers, HEADER_TRACE_ID);
1525
- if (typeof trace === "string" && trace.trim()) env2.trace_id = trace.trim();
1526
- const shouldRetry = headerGet(headers, HEADER_SHOULD_RETRY);
1527
- if (typeof shouldRetry === "string") env2.retryable = shouldRetry.trim().toLowerCase() === "true";
1528
- const inspection = parseInspectionHeader(headerGet(headers, HEADER_INSPECTION));
1529
- if (inspection) env2.inspection = inspection;
1530
- return env2;
1531
- }
1532
- var SHARED_FIELDS = ["decision", "code", "id", "retryable"];
1533
- var str = (v) => typeof v === "string" ? v : void 0;
1534
- var int = (v) => typeof v === "number" && Number.isInteger(v) ? v : void 0;
1535
- var count = (v) => typeof v === "number" && Number.isInteger(v) && v > 0 ? v : 0;
1536
- var isRecord = (v) => v != null && typeof v === "object" && !Array.isArray(v);
1537
- var records = (v) => Array.isArray(v) ? v.filter(isRecord) : [];
1538
- function readAttachment(item) {
1539
- const rawState = str(item.state);
1540
- return Object.freeze({
1541
- state: rawState !== void 0 && ATTACHMENT_STATES.has(rawState) ? rawState : "unknown",
1542
- rawState,
1543
- reason: str(item.reason),
1544
- filename: str(item.filename),
1545
- declaredType: str(item.declared_type),
1546
- sniffedType: str(item.sniffed_type),
1547
- sha256: str(item.sha256),
1548
- bytes: int(item.bytes),
1549
- source: str(item.source),
1550
- index: int(item.index),
1551
- path: str(item.path),
1552
- findings: Object.freeze(
1553
- records(item.findings).map(
1554
- (f) => Object.freeze({
1555
- detector: str(f.detector),
1556
- category: str(f.category),
1557
- code: str(f.code),
1558
- severity: str(f.severity),
1559
- locator: str(f.locator)
1560
- })
1561
- )
1562
- )
1563
- });
1564
- }
1565
- function attachmentsFromBody(block) {
1566
- if (!isRecord(block)) return void 0;
1567
- return Object.freeze({
1568
- total: count(block.total),
1569
- scanned: count(block.scanned),
1570
- scannedPartial: count(block.scanned_partial),
1571
- notInspected: count(block.not_inspected),
1572
- blocked: count(block.blocked),
1573
- items: Object.freeze(records(block.items).map(readAttachment)),
1574
- carrier: "body"
1575
- });
1576
- }
1577
- function memoryFromBody(block) {
1578
- if (!isRecord(block)) return void 0;
1579
- return Object.freeze({
1580
- writes: count(block.writes),
1581
- writesBlocked: count(block.writes_blocked),
1582
- recalls: count(block.recalls),
1583
- recallsFlagged: count(block.recalls_flagged),
1584
- coverage: str(block.coverage),
1585
- items: Object.freeze(
1586
- records(block.items).map(
1587
- (i) => Object.freeze({
1588
- kind: str(i.kind),
1589
- state: str(i.state),
1590
- reason: str(i.reason),
1591
- tool: str(i.tool),
1592
- store: str(i.store),
1593
- scope: str(i.scope),
1594
- source: str(i.source),
1595
- enforcement: str(i.enforcement),
1596
- memoryRef: str(i.memory_ref),
1597
- writeRef: str(i.write_ref),
1598
- seenBefore: typeof i.seen_before === "boolean" ? i.seen_before : void 0
1599
- })
1600
- )
1601
- ),
1602
- carrier: "body"
1603
- });
1604
- }
1605
- function routePolicyFromBody(block) {
1606
- if (!isRecord(block)) return void 0;
1607
- return Object.freeze({
1608
- route: str(block.route),
1609
- category: str(block.category),
1610
- reason: str(block.reason),
1611
- requestedRoute: str(block.requested_route),
1612
- degradedRoute: str(block.degraded_route)
1613
- });
1614
- }
1615
- function countsHeader(value) {
1616
- if (value === void 0) return void 0;
1617
- const out = {};
1618
- let any = false;
1619
- for (const part of value.split(";")) {
1620
- const eq = part.indexOf("=");
1621
- if (eq < 0) continue;
1622
- const name = part.slice(0, eq).trim();
1623
- const n = part.slice(eq + 1).trim();
1624
- if (name && /^[0-9]+$/.test(n)) {
1625
- out[name] = Number(n);
1626
- any = true;
1627
- }
1628
- }
1629
- return any ? out : void 0;
1630
- }
1631
- function attachmentsFromHeader(value) {
1632
- const c = countsHeader(value);
1633
- if (!c) return void 0;
1634
- const total = c.total ?? 0;
1635
- const scanned = c.scanned ?? 0;
1636
- const notInspected = c.not_inspected ?? 0;
1637
- const blocked = c.blocked ?? 0;
1638
- return Object.freeze({
1639
- total,
1640
- scanned,
1641
- // The header does not carry it. The four states partition `total`, so the
1642
- // remainder is scanned_partial — which errs, if the header is ever wrong,
1643
- // toward counting a file as unverified rather than as checked.
1644
- scannedPartial: Math.max(0, total - scanned - notInspected - blocked),
1645
- notInspected,
1646
- blocked,
1647
- items: Object.freeze([]),
1648
- carrier: "header"
1649
- });
1650
- }
1651
- function memoryFromHeader(value) {
1652
- const c = countsHeader(value);
1653
- if (!c) return void 0;
1654
- return Object.freeze({
1655
- writes: c.writes ?? 0,
1656
- writesBlocked: c.blocked ?? 0,
1657
- recalls: c.recalls ?? 0,
1658
- recallsFlagged: c.flagged ?? 0,
1659
- coverage: void 0,
1660
- items: Object.freeze([]),
1661
- carrier: "header"
1662
- });
1663
- }
1664
- function blockSource(bodyEnv, headers) {
1665
- if (bodyEnv != null) {
1666
- return "attachments" in bodyEnv || "memory" in bodyEnv || "route_policy" in bodyEnv ? { body: bodyEnv } : void 0;
1667
- }
1668
- return headers != null ? { headers } : void 0;
1669
- }
1670
- var SOURCE = /* @__PURE__ */ Symbol("trustgate.decision.blocks");
1671
- var ATTACHMENTS = /* @__PURE__ */ Symbol("trustgate.decision.attachments");
1672
- var MEMORY = /* @__PURE__ */ Symbol("trustgate.decision.memory");
1673
- var UNREAD = /* @__PURE__ */ Symbol("trustgate.decision.unread");
1674
- var _a, _b;
1675
- SOURCE, _b = ATTACHMENTS, _a = MEMORY;
1676
- var DecisionRecord = class {
1677
- constructor(f, source) {
1678
- this[_b] = UNREAD;
1679
- this[_a] = UNREAD;
1680
- this.decision = f.decision;
1681
- this.rawDecision = f.rawDecision;
1682
- this.code = f.code;
1683
- this.retryable = f.retryable;
1684
- this.id = f.id;
1685
- this.requestId = f.requestId;
1686
- this.traceId = f.traceId;
1687
- this.inspection = f.inspection;
1688
- this.versions = f.versions;
1689
- this.message = f.message;
1690
- this.retryAfterMs = f.retryAfterMs;
1691
- this.altered = f.altered;
1692
- this.carriers = f.carriers;
1693
- this.carrierDisagreement = f.carrierDisagreement;
1694
- this.delivered = DELIVERED_DECISIONS.has(f.decision);
1695
- this.isBlock = f.decision === DECISION_BLOCK;
1696
- this.isAltered = f.decision === DECISION_ALLOW_ALTERED;
1697
- this.unverified = f.decision === DECISION_NOT_CHECKED;
1698
- this[SOURCE] = source;
1699
- }
1700
- get attachments() {
1701
- if (this[ATTACHMENTS] === UNREAD) {
1702
- const src = this[SOURCE];
1703
- this[ATTACHMENTS] = src === void 0 ? void 0 : "body" in src ? attachmentsFromBody(src.body.attachments) : attachmentsFromHeader(headerGet(src.headers, HEADER_ATTACHMENTS));
1704
- }
1705
- return this[ATTACHMENTS];
1706
- }
1707
- get memory() {
1708
- if (this[MEMORY] === UNREAD) {
1709
- const src = this[SOURCE];
1710
- this[MEMORY] = src === void 0 ? void 0 : "body" in src ? memoryFromBody(src.body.memory) : memoryFromHeader(headerGet(src.headers, HEADER_MEMORY));
1711
- }
1712
- return this[MEMORY];
1713
- }
1714
- get routePolicy() {
1715
- const src = this[SOURCE];
1716
- return src !== void 0 && "body" in src ? routePolicyFromBody(src.body.route_policy) : void 0;
1717
- }
1718
- get filesUnverified() {
1719
- const a = this.attachments;
1720
- return a ? a.notInspected + a.scannedPartial : 0;
1721
- }
1722
- get filesBlocked() {
1723
- return this.attachments?.blocked ?? 0;
1724
- }
1725
- get memoryBlocked() {
1726
- return this.memory?.writesBlocked ?? 0;
1727
- }
1728
- get memoryRecallsFlagged() {
1729
- return this.memory?.recallsFlagged ?? 0;
1730
- }
1731
- get memoryCoverage() {
1732
- return this.memory?.coverage;
1733
- }
1734
- };
1735
- function makeDecision(fields, source) {
1736
- return new DecisionRecord(fields, source);
1737
- }
1738
- function build(bodyEnv, headerEnv, headers) {
1739
- if (bodyEnv == null && headerEnv == null) return void 0;
1740
- const carriers = [
1741
- ...bodyEnv != null ? ["body"] : [],
1742
- ...headerEnv != null ? ["headers"] : []
1743
- ];
1744
- const merged = { ...headerEnv ?? {}, ...bodyEnv ?? {} };
1745
- const disagreement = {};
1746
- if (bodyEnv != null && headerEnv != null) {
1747
- for (const name of SHARED_FIELDS) {
1748
- if (name in bodyEnv && name in headerEnv && bodyEnv[name] !== headerEnv[name]) {
1749
- disagreement[name] = [bodyEnv[name], headerEnv[name]];
1750
- }
1751
- }
1752
- }
1753
- const raw = merged.decision;
1754
- const retryAfterMs = merged.retry_after_ms;
1755
- const versions = merged.versions;
1756
- return makeDecision(
1757
- {
1758
- decision: coerceDecision(raw),
1759
- rawDecision: typeof raw === "string" ? raw : void 0,
1760
- code: typeof merged.code === "string" ? merged.code : void 0,
1761
- retryable: Boolean(merged.retryable),
1762
- id: typeof merged.id === "string" ? merged.id : void 0,
1763
- requestId: typeof merged.request_id === "string" ? merged.request_id : void 0,
1764
- traceId: typeof merged.trace_id === "string" ? merged.trace_id : typeof merged.id === "string" ? merged.id : void 0,
1765
- inspection: merged.inspection != null && typeof merged.inspection === "object" && !Array.isArray(merged.inspection) ? merged.inspection : void 0,
1766
- versions: versions != null && typeof versions === "object" && !Array.isArray(versions) ? versions : void 0,
1767
- message: typeof merged.message === "string" ? merged.message : void 0,
1768
- retryAfterMs: typeof retryAfterMs === "number" ? retryAfterMs : void 0,
1769
- altered: merged.altered != null && typeof merged.altered === "object" && !Array.isArray(merged.altered) ? merged.altered : void 0,
1770
- carriers,
1771
- carrierDisagreement: disagreement
1772
- },
1773
- blockSource(bodyEnv, headers)
1774
- );
1775
- }
1776
- function decisionFrom(body, headers) {
1777
- return build(fromBody(body), fromHeaders(headers), headers);
1778
- }
1779
- async function decisionFromResponse(response) {
1780
- let body;
1781
- try {
1782
- const ct = response.headers.get("content-type") ?? "";
1783
- if (ct.includes("application/json")) body = await response.clone().json();
1784
- } catch {
1785
- body = void 0;
1786
- }
1787
- return decisionFrom(body, response.headers);
1788
- }
1789
- var BODY_ATTRIBUTES = ["response_body", "body"];
1790
- function parsedBodyEnvelope(obj) {
1791
- if (obj == null || typeof obj !== "object") return void 0;
1792
- const rec = obj;
1793
- for (const attribute of BODY_ATTRIBUTES) {
1794
- const found = fromBody(rec[attribute]);
1795
- if (found) return found;
1796
- }
1797
- return void 0;
1798
- }
1799
- function shashuDecision(obj) {
1800
- try {
1801
- if (obj == null) return void 0;
1802
- if (typeof obj === "object") {
1803
- const remembered = carried.get(obj);
1804
- if (remembered) return remembered;
1805
- const cached = obj.decision;
1806
- if (cached && typeof cached === "object" && cached !== null && "decision" in cached) {
1807
- return cached;
1808
- }
1809
- if (obj instanceof Response) {
1810
- return build(void 0, fromHeaders(obj.headers), obj.headers);
1811
- }
1812
- if (!Array.isArray(obj)) {
1813
- const bodyEnv = fromBody(obj) ?? parsedBodyEnvelope(obj);
1814
- const headers = obj.responseHeaders ?? obj.headers ?? (obj.response ?? {}).headers;
1815
- return build(bodyEnv, fromHeaders(headers), headers);
1816
- }
1817
- }
1818
- } catch {
1819
- return void 0;
1820
- }
1821
- return void 0;
1822
- }
1823
- function isShashuBlock(err) {
1824
- try {
1825
- const found = shashuDecision(err);
1826
- if (found != null) return found.isBlock;
1827
- if (err instanceof ShashuContentFilterError) return true;
1828
- if (err != null && typeof err === "object") {
1829
- for (const attribute of BODY_ATTRIBUTES) {
1830
- const body = err[attribute];
1831
- if (body == null || typeof body !== "object") continue;
1832
- const rec = body;
1833
- for (const candidate of [rec, rec.error]) {
1834
- if (candidate != null && typeof candidate === "object" && candidate.type === "content_filter") {
1835
- return true;
1836
- }
1837
- }
1838
- const choices = rec.choices;
1839
- if (Array.isArray(choices) && choices[0] && typeof choices[0] === "object") {
1840
- if (choices[0].finish_reason === "content_filter") {
1841
- return true;
1842
- }
1843
- }
1844
- }
1845
- }
1846
- } catch {
1847
- return false;
1848
- }
1849
- return false;
1850
- }
1851
-
1852
- // src/credential.ts
1853
- var BOTH_OR_NEITHER = "Give either a SHASHU key or a token provider, not both.";
1854
- var KEY_ONLY_FOR_NOW = "{name} is key only for now: pass a SHASHU key, not a token provider.";
1855
- var REFRESH_SKEW_SECONDS = 60;
1856
- var PASS_PROVIDER_NOT_SET_UP = "pass_provider_not_set_up";
1857
- var PASS_NOT_LICENSED = "pass_not_licensed";
1858
- var PASS_EXPIRED = "pass_expired";
1859
- var PASS_WRONG_AUDIENCE = "pass_wrong_audience";
1860
- var PASS_WRONG_ISSUER = "pass_wrong_issuer";
1861
- var PASS_UNKNOWN_AGENT = "pass_unknown_agent";
1862
- var PASS_CODES = [
1863
- PASS_PROVIDER_NOT_SET_UP,
1864
- PASS_NOT_LICENSED,
1865
- PASS_EXPIRED,
1866
- PASS_WRONG_AUDIENCE,
1867
- PASS_WRONG_ISSUER,
1868
- PASS_UNKNOWN_AGENT
1869
- ];
1870
- var RETRY_CODES = /* @__PURE__ */ new Set([PASS_EXPIRED]);
1871
- function rejectKeyOnly(name, tokenProvider) {
1872
- if (tokenProvider != null) {
1873
- throw new ShashuConfigError(KEY_ONLY_FOR_NOW.replace("{name}", name));
1874
- }
1875
- }
1876
- function jwtExpUnverified(token) {
1877
- const parts = token.split(".");
1878
- if (parts.length !== 3) return null;
1879
- const payload = parts[1];
1880
- const pad = "=".repeat((4 - payload.length % 4) % 4);
1881
- try {
1882
- const json = Buffer.from(payload + pad, "base64url").toString("utf8");
1883
- const data = JSON.parse(json);
1884
- if (data.exp == null) return null;
1885
- const exp = Number(data.exp);
1886
- return Number.isFinite(exp) ? exp : null;
1887
- } catch {
1888
- return null;
1889
- }
1890
- }
1891
- function passRefusalCodeFromText(text) {
1892
- try {
1893
- const parsed = JSON.parse(text);
1894
- const code = parsed?.error?.code;
1895
- return typeof code === "string" && PASS_CODES.includes(code) ? code : null;
1896
- } catch {
1897
- return null;
1898
- }
1899
- }
1900
- function shouldRetryPassRefused(opts) {
1901
- if (!opts.usesProvider || opts.bytesDelivered || opts.status !== 401) return false;
1902
- return opts.code != null && RETRY_CODES.has(opts.code);
1903
- }
1904
- var CredentialResolver = class {
1905
- constructor(opts) {
1906
- const envKey = envGet(API_KEY_ENV) ?? void 0;
1907
- const hasKeyArg = opts.apiKey !== void 0;
1908
- const hasProvider = opts.tokenProvider !== void 0;
1909
- if (hasKeyArg && hasProvider) throw new ShashuConfigError(BOTH_OR_NEITHER);
1910
- if (hasProvider && envKey && !hasKeyArg) throw new ShashuConfigError(BOTH_OR_NEITHER);
1911
- if (opts.requireOne && !hasProvider && !hasKeyArg && !envKey) {
1912
- throw new ShashuConfigError(BOTH_OR_NEITHER);
1913
- }
1914
- this.provider = opts.tokenProvider;
1915
- this.staticKey = hasProvider ? void 0 : hasKeyArg ? opts.apiKey : envKey;
1916
- }
1917
- get usesProvider() {
1918
- return this.provider !== void 0;
1919
- }
1920
- async get() {
1921
- if (!this.provider) return this.staticKey;
1922
- if (this.cached && !this.needsRefresh(this.cached)) return this.cached;
1923
- if (this.inflight) return this.inflight;
1924
- this.inflight = (async () => {
1925
- const token = await this.provider();
1926
- this.cached = String(token);
1927
- this.inflight = void 0;
1928
- return this.cached;
1929
- })().catch((err) => {
1930
- this.inflight = void 0;
1931
- throw err;
1932
- });
1933
- return this.inflight;
1934
- }
1935
- invalidate() {
1936
- this.cached = void 0;
1937
- }
1938
- needsRefresh(token) {
1939
- const exp = jwtExpUnverified(token);
1940
- if (exp == null) return true;
1941
- return Date.now() / 1e3 >= exp - REFRESH_SKEW_SECONDS;
1942
- }
1943
- };
1944
-
1945
- // src/client.ts
1946
- var USER_AGENT = `trustgate-node/${SDK_VERSION}`;
1947
- var joiningFetch = withRetrievalJoiner();
1948
- var streamingInertWarningEmitted = false;
1949
- function warnStreamingInert() {
1950
- if (streamingInertWarningEmitted) return;
1951
- streamingInertWarningEmitted = true;
1952
- console.warn(
1953
- "[trustgate] Streaming is not yet supported end-to-end: the gateway buffers /v1/chat/completions and returns full JSON regardless of the `stream` flag, so no incremental tokens are produced. fetchStream() will fall back to the buffered response. (warned once per process)"
1954
- );
1955
- }
1956
- function resolveContext(config, options) {
1957
- return options?.workflowContext ?? config.workflowContext ?? getWorkflowContextFromEnv();
1958
- }
1959
- function resolveBaseUrl(config) {
1960
- return requireBaseUrl(config.baseUrl, { entryPoint: "new Shashu()" });
1961
- }
1962
- function mergeHeaders(config, options, context, session, token) {
1963
- const out = {
1964
- "content-type": "application/json",
1965
- "user-agent": USER_AGENT,
1966
- ...config.headers,
1967
- ...options?.headers
1968
- };
1969
- const credential = token ?? config.apiKey;
1970
- if (credential) {
1971
- out["authorization"] = `Bearer ${credential}`;
1972
- }
1973
- if (context) {
1974
- Object.assign(out, buildContextHeaders(context, session));
1975
- }
1976
- return out;
1977
- }
1978
- var Shashu = class {
1979
- constructor(config) {
1980
- this.resolvedBaseUrl = resolveBaseUrl(config);
1981
- this.config = { ...config, baseUrl: this.resolvedBaseUrl };
1982
- this.resolver = new CredentialResolver({
1983
- apiKey: config.apiKey,
1984
- tokenProvider: config.tokenProvider,
1985
- requireOne: true
1986
- });
1987
- this._agentId = config.agentId;
1988
- this._sessionId = config.sessionId ?? (0, import_node_crypto3.randomUUID)();
1989
- this.retryPolicy = resolveRetryPolicy(config.retryPolicy);
1990
- this.audit = new Audit(this);
1991
- }
1992
- /** Base URL of the Shashu gateway. */
1993
- get baseUrl() {
1994
- return this.resolvedBaseUrl;
1995
- }
1996
- /** This agent's own id, as known so far (seed option or cached response header). */
1997
- get agentId() {
1998
- return this._agentId;
1999
- }
2000
- /**
2001
- * The session this client joins. Minted once at construction when the caller
2002
- * did not pass `sessionId`. A captured A2A session overrides it; a
2003
- * per-request `sessionId` overrides both.
2004
- */
2005
- get sessionId() {
2006
- return this._sessionId;
2007
- }
2008
- /**
2009
- * Cache this agent's own id from the gateway's `x-shashu-agent-id` response header
2010
- * (delivered by WP-A2A-1). Used by {@link buildInvocationHeaders} to stamp caller = self
2011
- * on a downstream invocation. Read on EVERY response — including non-2xx — so even a
2012
- * blocked response seeds the self-id. NEVER an auth credential. Fail-soft: never throws.
2013
- */
2014
- captureAgentId(res) {
2015
- try {
2016
- const aid = res.headers.get("x-shashu-agent-id");
2017
- if (aid) this._agentId = aid;
2018
- } catch {
2019
- }
2020
- }
2021
- /**
2022
- * Lineage headers to stamp on a message THIS agent sends to a DOWNSTREAM agent (the
2023
- * invoking side, ADR-007 §4.1). caller-agent-id = this client's own id (`agentId` option,
2024
- * refreshed from gateway responses); trace / hop / session default from the tracer so the
2025
- * served flow is propagated. The downstream agent calls `captureIncoming()` on these
2026
- * headers. Throws if self-id is not known yet — set the `agentId` option or make one
2027
- * gateway call first so the `x-shashu-agent-id` response header can seed it.
2028
- */
2029
- buildInvocationHeaders(opts) {
2030
- if (!this._agentId) {
2031
- throw new Error(
2032
- "self agent id is unknown \u2014 set the agentId option or make one gateway call first so the x-shashu-agent-id response header can seed it."
2033
- );
2034
- }
2035
- return buildInvocationHeaders({ callerAgentId: this._agentId, ...opts });
2036
- }
2037
- /**
2038
- * Get the current effective workflow context (from config override or process.env).
2039
- */
2040
- getWorkflowContext(options) {
2041
- return resolveContext(this.config, options);
2042
- }
2043
- /**
2044
- * Perform a non-streaming JSON request through Shashu. Request body is
2045
- * sent unchanged; the gateway routes by the `model` field.
2046
- *
2047
- * Non-2xx responses throw the typed exception hierarchy (auth / bad-request /
2048
- * context-window / rate-limit / permission / policy-violation / provider).
2049
- * A 200 whose body has finish_reason="content_filter" throws
2050
- * ShashuContentFilterError.
2051
- *
2052
- * Connection errors are retried per the client's retry policy. A 429 is
2053
- * retried only when the gateway named a time to come back -- the
2054
- * identical-request breaker names none, and retrying it refreshes the
2055
- * window that is blocking you. See ./retry.js.
2056
- */
2057
- async fetch(path, init = {}, options) {
2058
- const context = resolveContext(this.config, options);
2059
- const url = path.startsWith("http") ? path : `${this.resolvedBaseUrl}/${path.replace(/^\//, "")}`;
2060
- const timeout = options?.timeout ?? 6e4;
2061
- const headersOnce = applyContractVersion(
2062
- {
2063
- ...mergeHeaders(this.config, options, context, {
2064
- defaultSessionId: this._sessionId,
2065
- requestSessionId: options?.sessionId
2066
- }),
2067
- ...init.headers
2068
- },
2069
- this.config.contractVersion
2070
- );
2071
- const frozenHeaders = { ...headersOnce };
2072
- delete frozenHeaders["authorization"];
2073
- delete frozenHeaders["Authorization"];
2074
- const pinned = pinOutgoing(url, { ...init, headers: frozenHeaders });
2075
- const send = async () => {
2076
- const token = await this.resolver.get();
2077
- const controller = new AbortController();
2078
- const id = setTimeout(() => controller.abort(), timeout);
2079
- try {
2080
- const headers = { ...pinned.init?.headers };
2081
- if (token) headers["authorization"] = `Bearer ${token}`;
2082
- return await joiningFetch(pinned.input, {
2083
- ...pinned.init,
2084
- headers,
2085
- signal: init.signal ?? controller.signal
2086
- });
2087
- } finally {
2088
- clearTimeout(id);
2089
- }
2090
- };
2091
- let res = await executeWithRetry(send, this.retryPolicy);
2092
- if (this.resolver.usesProvider && res.status === 401) {
2093
- const code = passRefusalCodeFromText(await res.clone().text());
2094
- if (shouldRetryPassRefused({
2095
- usesProvider: true,
2096
- status: res.status,
2097
- code,
2098
- bytesDelivered: false
2099
- })) {
2100
- this.resolver.invalidate();
2101
- res = await send();
2102
- }
2103
- }
2104
- this.captureAgentId(res);
2105
- const decision = await decisionFromResponse(res);
2106
- if (decision) rememberDecision(res, decision);
2107
- await raiseForResponse(res, decision);
2108
- if (res.headers.get("content-type")?.includes("application/json")) {
2109
- try {
2110
- const json = await res.clone().json();
2111
- raiseIfContentFiltered(json, decision, res.headers);
2112
- } catch (err) {
2113
- if (err instanceof ShashuContentFilterError) throw err;
2114
- }
2115
- }
2116
- return res;
2117
- }
2118
- /**
2119
- * Perform a streaming request (SSE). Forwards the response stream; gateway
2120
- * attributes the request using workflow context. 403 throws ShashuError.
2121
- *
2122
- * NOTICE — streaming is INERT against a Shashu gateway today. The proxy
2123
- * always calls the provider in non-streaming mode and buffers the full
2124
- * response so its deferred-deanonymize / egress-scan step can run on the
2125
- * complete body; it emits no chat SSE regardless of the `stream` flag or
2126
- * DLP settings. This method consequently does not yield incremental tokens
2127
- * — when the response is not `text/event-stream` it returns the buffered
2128
- * JSON response unchanged. The method is kept (not removed) for forward
2129
- * compatibility once gateway streaming lands. A one-time warning is logged
2130
- * on first use.
2131
- */
2132
- async fetchStream(path, init = {}, options) {
2133
- warnStreamingInert();
2134
- const context = resolveContext(this.config, options);
2135
- const url = path.startsWith("http") ? path : `${this.resolvedBaseUrl}/${path.replace(/^\//, "")}`;
2136
- const send = async () => {
2137
- const token = await this.resolver.get();
2138
- const headers = mergeHeaders(
2139
- this.config,
2140
- options,
2141
- context,
2142
- {
2143
- defaultSessionId: this._sessionId,
2144
- requestSessionId: options?.sessionId
2145
- },
2146
- token
2147
- );
2148
- const mergedHeaders = applyContractVersion(
2149
- {
2150
- accept: "text/event-stream",
2151
- ...headers,
2152
- ...init.headers
2153
- },
2154
- this.config.contractVersion
2155
- );
2156
- return joiningFetch(url, {
2157
- ...init,
2158
- headers: mergedHeaders,
2159
- signal: init.signal
2160
- });
2161
- };
2162
- let res = await send();
2163
- if (this.resolver.usesProvider && res.status === 401) {
2164
- const code = passRefusalCodeFromText(await res.clone().text());
2165
- if (shouldRetryPassRefused({
2166
- usesProvider: true,
2167
- status: res.status,
2168
- code,
2169
- bytesDelivered: false
2170
- })) {
2171
- this.resolver.invalidate();
2172
- res = await send();
2173
- }
2174
- }
2175
- this.captureAgentId(res);
2176
- const decision = await decisionFromResponse(res);
2177
- if (decision) rememberDecision(res, decision);
2178
- if (!res.ok) {
2179
- await raiseForResponse(res, decision);
2180
- }
2181
- if (!res.body) {
2182
- return res;
2183
- }
2184
- if (!res.headers.get("content-type")?.includes("text/event-stream")) {
2185
- return res;
2186
- }
2187
- return new Response(res.body, {
2188
- status: res.status,
2189
- statusText: res.statusText,
2190
- headers: res.headers
2191
- });
2192
- }
2193
- };
2194
-
2195
- // src/fetch.ts
2196
- var import_node_crypto4 = require("crypto");
2197
- var DEFAULT_BLOCK_ENCODING = "explicit";
2198
- var BLOCK_ENCODING_HEADER = "shashu-block-encoding";
2199
- function shashuFetch(options = {}) {
2200
- const resolver = new CredentialResolver({
2201
- apiKey: options.apiKey,
2202
- tokenProvider: options.tokenProvider
2203
- });
2204
- const defaultSessionId = options.sessionId ?? (0, import_node_crypto4.randomUUID)();
2205
- const underlying = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
2206
- const joining = withRetrievalJoiner(underlying);
2207
- const baked = buildContextHeaders(options.workflowContext ?? getWorkflowContextFromEnv(), {
2208
- defaultSessionId
2209
- });
2210
- if (options.blockEncoding !== null) {
2211
- baked[BLOCK_ENCODING_HEADER] = options.blockEncoding ?? DEFAULT_BLOCK_ENCODING;
2212
- }
2213
- if (options.headers) {
2214
- for (const [k, v] of Object.entries(options.headers)) baked[k.toLowerCase()] = v;
2215
- }
2216
- return async function trustgateFetching(input, init) {
2217
- const send = async () => {
2218
- const headers = { ...baked };
2219
- const extra = init?.headers;
2220
- if (extra instanceof Headers) extra.forEach((v, k) => headers[k.toLowerCase()] = v);
2221
- else if (Array.isArray(extra)) {
2222
- for (const [k, v] of extra) headers[String(k).toLowerCase()] = String(v);
2223
- } else if (extra && typeof extra === "object") {
2224
- for (const [k, v] of Object.entries(extra)) headers[k.toLowerCase()] = String(v);
2225
- }
2226
- const token = await resolver.get();
2227
- if (token) headers.authorization = `Bearer ${token}`;
2228
- return joining(input, {
2229
- ...init,
2230
- headers: applyContractVersion(headers, options.contractVersion)
2231
- });
2232
- };
2233
- const res = await send();
2234
- if (!resolver.usesProvider || res.status !== 401) return res;
2235
- const text = await res.clone().text();
2236
- const code = passRefusalCodeFromText(text);
2237
- if (!shouldRetryPassRefused({
2238
- usesProvider: true,
2239
- status: res.status,
2240
- code,
2241
- bytesDelivered: false
2242
- })) {
2243
- return res;
2244
- }
2245
- resolver.invalidate();
2246
- return send();
2247
- };
2248
- }
2249
-
2250
- // src/n8n.ts
2251
- function getN8nHeaderSnippet(apiKey, baseUrl) {
2252
- const key = apiKey ?? tracer.apiKey ?? envGet(API_KEY_ENV) ?? "";
2253
- const url = baseUrl ?? tracer.gatewayUrl ?? envGet(BASE_URL_ENV) ?? "";
2254
- const ctx = getWorkflowContextFromEnv();
2255
- const contextHeaders = buildContextHeaders(ctx);
2256
- const headers = [];
2257
- if (url) {
2258
- headers.push({ name: `${HEADER_PREFIX}-gateway-url`, value: url });
2259
- }
2260
- if (key) {
2261
- headers.push({ name: "authorization", value: `Bearer ${key}` });
2262
- headers.push({ name: "x-api-key", value: key });
2263
- }
2264
- for (const [name, value] of Object.entries(contextHeaders)) {
2265
- headers.push({ name, value });
2266
- }
2267
- const json = JSON.stringify(
2268
- headers.reduce((acc, { name, value }) => {
2269
- acc[name] = value;
2270
- return acc;
2271
- }, {}),
2272
- null,
2273
- 2
2274
- );
2275
- return { headers, json };
2276
- }
2277
-
2278
- // src/middleware/vercel-ai.ts
2279
- var import_node_crypto5 = require("crypto");
2280
- function getShashuHeaders(workflowContext, sessionId, contractVersion) {
2281
- const ctx = workflowContext ?? getWorkflowContextFromEnv();
2282
- return applyContractVersion(
2283
- buildContextHeaders(ctx, sessionId ? { defaultSessionId: sessionId } : void 0),
2284
- contractVersion
2285
- );
2286
- }
2287
- function createShashuOpenAIOptions(options) {
2288
- if (isDisabled()) return {};
2289
- const baseUrl = requireBaseUrl(options.baseUrl, {
2290
- entryPoint: "createShashuOpenAIOptions()"
2291
- });
2292
- const resolver = new CredentialResolver({
2293
- apiKey: options.apiKey,
2294
- tokenProvider: options.tokenProvider
2295
- });
2296
- const headers = {
2297
- ...options.headers,
2298
- ...getShashuHeaders(options.workflowContext, options.sessionId ?? (0, import_node_crypto5.randomUUID)(), null)
2299
- };
2300
- applyContractVersion(headers, options.contractVersion);
2301
- const joining = withRetrievalJoiner();
2302
- const fetch2 = async (input, init) => {
2303
- const token = await resolver.get();
2304
- const next = new Headers(init?.headers);
2305
- if (token) next.set("authorization", `Bearer ${token}`);
2306
- const send = () => joining(input, { ...init, headers: next });
2307
- const res = await send();
2308
- if (!resolver.usesProvider || res.status !== 401) return res;
2309
- const code = passRefusalCodeFromText(await res.clone().text());
2310
- if (!shouldRetryPassRefused({
2311
- usesProvider: true,
2312
- status: res.status,
2313
- code,
2314
- bytesDelivered: false
2315
- })) {
2316
- return res;
2317
- }
2318
- resolver.invalidate();
2319
- const retryToken = await resolver.get();
2320
- if (retryToken) next.set("authorization", `Bearer ${retryToken}`);
2321
- return joining(input, { ...init, headers: next });
2322
- };
2323
- return {
2324
- baseURL: baseUrl,
2325
- apiKey: resolver.usesProvider ? void 0 : options.openaiApiKey ?? options.apiKey,
2326
- headers: Object.keys(headers).length ? headers : void 0,
2327
- fetch: fetch2
2328
- };
2329
- }
2330
-
2331
- // src/middleware/langchain.ts
2332
- var import_node_crypto6 = require("crypto");
2333
- function createShashuLangChainConfig(config) {
2334
- if (isDisabled()) return {};
2335
- const baseUrl = requireBaseUrl(config.baseUrl, {
2336
- entryPoint: "createShashuLangChainConfig()"
2337
- });
2338
- const ctx = config.workflowContext ?? getWorkflowContextFromEnv();
2339
- const resolver = new CredentialResolver({
2340
- apiKey: config.apiKey,
2341
- tokenProvider: config.tokenProvider
2342
- });
2343
- const headers = {
2344
- ...config.headers,
2345
- ...buildContextHeaders(ctx, { defaultSessionId: config.sessionId ?? (0, import_node_crypto6.randomUUID)() })
2346
- };
2347
- applyContractVersion(headers, config.contractVersion);
2348
- const fetch2 = async (input, init) => {
2349
- const baseHeaders = new Headers(init?.headers);
2350
- baseHeaders.delete("authorization");
2351
- const headerObj = {};
2352
- baseHeaders.forEach((v, k) => {
2353
- headerObj[k] = v;
2354
- });
2355
- const pinned = pinOutgoing(input, { ...init, headers: headerObj });
2356
- const send = async () => {
2357
- const token = await resolver.get();
2358
- const headers2 = { ...pinned.init?.headers || {} };
2359
- if (token) headers2.authorization = `Bearer ${token}`;
2360
- return globalThis.fetch(pinned.input, { ...pinned.init, headers: headers2 });
2361
- };
2362
- const res = await executeWithRetry(send, resolveRetryPolicy(config.retryPolicy));
2363
- if (!resolver.usesProvider || res.status !== 401) return res;
2364
- const code = passRefusalCodeFromText(await res.clone().text());
2365
- if (!shouldRetryPassRefused({
2366
- usesProvider: true,
2367
- status: res.status,
2368
- code,
2369
- bytesDelivered: false
2370
- })) {
2371
- return res;
2372
- }
2373
- resolver.invalidate();
2374
- return send();
2375
- };
2376
- return {
2377
- baseURL: baseUrl,
2378
- defaultHeaders: Object.keys(headers).length ? headers : void 0,
2379
- configuration: {
2380
- baseURL: baseUrl,
2381
- defaultHeaders: Object.keys(headers).length ? headers : void 0,
2382
- fetch: fetch2
2383
- }
2384
- };
2385
- }
2386
- var ShashuLangChainCallback = class {
2387
- constructor() {
2388
- this.name = "ShashuLangChainCallback";
2389
- this.raiseError = false;
2390
- this.awaitHandlers = false;
2391
- this.ignoreLLM = false;
2392
- this.ignoreChain = false;
2393
- this.ignoreAgent = false;
2394
- this.ignoreRetriever = false;
2395
- this.ignoreCustomEvent = false;
2396
- }
2397
- copy() {
2398
- return this;
2399
- }
2400
- };
2401
- var PRESENCE = new ShashuLangChainCallback();
2402
-
2403
- // src/middleware/anthropic.ts
2404
- var import_node_crypto7 = require("crypto");
2405
- function getAnthropicHeaders(config) {
2406
- const ctx = config.workflowContext ?? getWorkflowContextFromEnv();
2407
- const headers = {
2408
- ...config.headers,
2409
- ...buildContextHeaders(ctx, { defaultSessionId: config.sessionId })
2410
- };
2411
- if (config.apiKey) {
2412
- headers["x-api-key"] = config.apiKey;
2413
- }
2414
- return applyContractVersion(headers, config.contractVersion);
2415
- }
2416
- function createShashuAnthropicConfig(config) {
2417
- if (isDisabled()) return {};
2418
- const baseURL = requireBaseUrl(config.baseUrl, {
2419
- entryPoint: "createShashuAnthropicConfig()"
2420
- });
2421
- const resolver = new CredentialResolver({
2422
- apiKey: config.apiKey ?? void 0,
2423
- tokenProvider: config.tokenProvider
2424
- });
2425
- const headers = getAnthropicHeaders({
2426
- ...config,
2427
- sessionId: config.sessionId ?? (0, import_node_crypto7.randomUUID)(),
2428
- apiKey: resolver.usesProvider ? void 0 : config.apiKey
2429
- });
2430
- const joining = withRetrievalJoiner();
2431
- const fetch2 = async (input, init) => {
2432
- const token = await resolver.get();
2433
- const next = new Headers(init?.headers);
2434
- if (token) next.set("x-api-key", token);
2435
- const res = await joining(input, { ...init, headers: next });
2436
- if (!resolver.usesProvider || res.status !== 401) return res;
2437
- const code = passRefusalCodeFromText(await res.clone().text());
2438
- if (!shouldRetryPassRefused({
2439
- usesProvider: true,
2440
- status: res.status,
2441
- code,
2442
- bytesDelivered: false
2443
- })) {
2444
- return res;
2445
- }
2446
- resolver.invalidate();
2447
- const retryToken = await resolver.get();
2448
- if (retryToken) next.set("x-api-key", retryToken);
2449
- return joining(input, { ...init, headers: next });
2450
- };
2451
- return {
2452
- baseURL,
2453
- apiKey: resolver.usesProvider ? null : config.apiKey ?? null,
2454
- defaultHeaders: Object.keys(headers).length ? headers : void 0,
2455
- fetch: fetch2
2456
- };
2457
- }
2458
-
2459
- // src/middleware/google.ts
2460
- var import_node_crypto8 = require("crypto");
2461
- function getGeminiHeaders(config) {
2462
- const ctx = config.workflowContext ?? getWorkflowContextFromEnv();
2463
- const headers = {
2464
- ...config.headers,
2465
- ...buildContextHeaders(ctx, { defaultSessionId: config.sessionId })
2466
- };
2467
- if (config.apiKey) {
2468
- headers["x-api-key"] = config.apiKey;
2469
- }
2470
- return applyContractVersion(headers, config.contractVersion);
2471
- }
2472
- function createShashuGeminiConfig(config) {
2473
- if (isDisabled()) return {};
2474
- rejectKeyOnly("createShashuGeminiConfig", config.tokenProvider);
2475
- const baseUrl = requireBaseUrl(config.baseUrl, {
2476
- entryPoint: "createShashuGeminiConfig()"
2477
- });
2478
- const headers = getGeminiHeaders({ ...config, sessionId: config.sessionId ?? (0, import_node_crypto8.randomUUID)() });
2479
- return {
2480
- baseUrl,
2481
- apiKey: config.apiKey ?? null,
2482
- headers: Object.keys(headers).length ? headers : void 0
2483
- };
2484
- }
2485
- // Annotate the CommonJS export names for ESM import in node:
2486
- 0 && (module.exports = {
2487
- Audit,
2488
- BLOCK_ENCODING_HEADER,
2489
- BODY_KEY,
2490
- CONTRACT_VERSION_HEADER,
2491
- DECISIONS,
2492
- DECISION_ALLOW,
2493
- DECISION_ALLOW_ALTERED,
2494
- DECISION_BLOCK,
2495
- DECISION_FAIL,
2496
- DECISION_NOT_CHECKED,
2497
- DECISION_REFUSE,
2498
- DEFAULT_BLOCK_ENCODING,
2499
- DEFAULT_CONTRACT_VERSION,
2500
- DEFAULT_RETRY_POLICY,
2501
- DELIVERED_DECISIONS,
2502
- HEADER_ATTACHMENTS,
2503
- HEADER_CODE,
2504
- HEADER_DECISION,
2505
- HEADER_INSPECTION,
2506
- HEADER_MEMORY,
2507
- HEADER_PREFIX,
2508
- HEADER_REQUEST_ID,
2509
- HEADER_SHASHU_REQUEST_ID,
2510
- HEADER_SHOULD_RETRY,
2511
- HEADER_TRACE_ID,
2512
- MemoryWriteBlocked,
2513
- PASS_CODES,
2514
- PASS_EXPIRED,
2515
- PASS_NOT_LICENSED,
2516
- PASS_PROVIDER_NOT_SET_UP,
2517
- PASS_UNKNOWN_AGENT,
2518
- PASS_WRONG_AUDIENCE,
2519
- PASS_WRONG_ISSUER,
2520
- SOURCES,
2521
- SOURCE_TOOL_HEADER,
2522
- Shashu,
2523
- ShashuAuthenticationError,
2524
- ShashuBadRequestError,
2525
- ShashuBudgetExceededError,
2526
- ShashuConfigError,
2527
- ShashuContentFilterError,
2528
- ShashuContextWindowExceeded,
2529
- ShashuError,
2530
- ShashuPermissionError,
2531
- ShashuPolicyViolation,
2532
- ShashuProviderError,
2533
- ShashuRateLimitError,
2534
- TRUSTLOG_HEADER_PREFIX,
2535
- attachRagContext,
2536
- buildContextHeaders,
2537
- buildInvocationHeaders,
2538
- buildRagContext,
2539
- buildSourceToolJson,
2540
- captureIncoming,
2541
- createShashuAnthropicConfig,
2542
- createShashuGeminiConfig,
2543
- createShashuLangChainConfig,
2544
- createShashuOpenAIOptions,
2545
- decisionFrom,
2546
- declareMemory,
2547
- declareRetrieval,
2548
- executeWithRetry,
2549
- gatewayRetryAfter,
2550
- getAnthropicHeaders,
2551
- getGeminiHeaders,
2552
- getN8nHeaderSnippet,
2553
- getShashuHeaders,
2554
- getWorkflowContextFromEnv,
2555
- isShashuBlock,
2556
- makeRagContext,
2557
- memoryScope,
2558
- parseRetryAfter,
2559
- raiseForResponse,
2560
- raiseIfContentFiltered,
2561
- resolveRetryPolicy,
2562
- retrievalScope,
2563
- shashuDecision,
2564
- shashuFetch,
2565
- tracer,
2566
- withRetrievalJoiner
2567
- });