@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.js DELETED
@@ -1,974 +0,0 @@
1
- import {
2
- createShashuAnthropicConfig,
3
- getAnthropicHeaders
4
- } from "./chunk-3GAMCQ6R.js";
5
- import {
6
- createShashuGeminiConfig,
7
- getGeminiHeaders
8
- } from "./chunk-3JZXUKNA.js";
9
- import {
10
- DEFAULT_RETRY_POLICY,
11
- createShashuLangChainConfig,
12
- executeWithRetry,
13
- resolveRetryPolicy
14
- } from "./chunk-F4CXDZQB.js";
15
- import {
16
- createShashuOpenAIOptions,
17
- getShashuHeaders
18
- } from "./chunk-3X5IUBIA.js";
19
- import {
20
- SOURCES,
21
- attachRagContext,
22
- buildRagContext,
23
- declareMemory,
24
- declareRetrieval,
25
- makeRagContext,
26
- memoryScope,
27
- pinOutgoing,
28
- retrievalScope,
29
- withRetrievalJoiner
30
- } from "./chunk-M7EMWSNS.js";
31
- import {
32
- API_KEY_ENV,
33
- BASE_URL_ENV,
34
- CONTRACT_VERSION_HEADER,
35
- CredentialResolver,
36
- DEFAULT_CONTRACT_VERSION,
37
- HEADER_PREFIX,
38
- MemoryWriteBlocked,
39
- PASS_CODES,
40
- PASS_EXPIRED,
41
- PASS_NOT_LICENSED,
42
- PASS_PROVIDER_NOT_SET_UP,
43
- PASS_UNKNOWN_AGENT,
44
- PASS_WRONG_AUDIENCE,
45
- PASS_WRONG_ISSUER,
46
- SDK_VERSION,
47
- SOURCE_TOOL_HEADER,
48
- ShashuAuthenticationError,
49
- ShashuBadRequestError,
50
- ShashuBudgetExceededError,
51
- ShashuConfigError,
52
- ShashuContentFilterError,
53
- ShashuContextWindowExceeded,
54
- ShashuError,
55
- ShashuPermissionError,
56
- ShashuPolicyViolation,
57
- ShashuProviderError,
58
- ShashuRateLimitError,
59
- TRUSTLOG_HEADER_PREFIX,
60
- applyContractVersion,
61
- buildContextHeaders,
62
- buildInvocationHeaders,
63
- buildSourceToolJson,
64
- captureIncoming,
65
- envGet,
66
- gatewayRetryAfter,
67
- getWorkflowContextFromEnv,
68
- parseRetryAfter,
69
- passRefusalCodeFromText,
70
- raiseForResponse,
71
- raiseIfContentFiltered,
72
- requireBaseUrl,
73
- shouldRetryPassRefused,
74
- tracer
75
- } from "./chunk-TGD6KDWT.js";
76
-
77
- // src/client.ts
78
- import { randomUUID } from "crypto";
79
-
80
- // src/audit.ts
81
- var Audit = class {
82
- constructor(client) {
83
- this.client = client;
84
- }
85
- /**
86
- * POST a post-hoc audit event for scanning + audit-only logging.
87
- *
88
- * Non-2xx responses throw the typed exception hierarchy (e.g.
89
- * ShashuPolicyViolation on 403 when the connector key is invalid),
90
- * raised by `client.fetch`.
91
- */
92
- async events(input, options) {
93
- const body = {
94
- source: input.source,
95
- conversation: input.conversation
96
- };
97
- if (input.externalEventId !== void 0) {
98
- body.external_event_id = input.externalEventId;
99
- }
100
- if (input.occurredAt !== void 0) {
101
- body.occurred_at = input.occurredAt;
102
- }
103
- if (input.userContext !== void 0) {
104
- body.user_context = input.userContext;
105
- }
106
- if (input.traceId !== void 0) {
107
- body.trace_id = input.traceId;
108
- }
109
- if (input.parentSpanId !== void 0) {
110
- body.parent_span_id = input.parentSpanId;
111
- }
112
- if (input.sessionId !== void 0) {
113
- body.session_id = input.sessionId;
114
- }
115
- const res = await this.client.fetch(
116
- "/v1/audit/events",
117
- {
118
- method: "POST",
119
- body: JSON.stringify(body)
120
- },
121
- options
122
- );
123
- return await res.json();
124
- }
125
- };
126
-
127
- // src/decision.ts
128
- var DECISION_ALLOW = "allow";
129
- var DECISION_ALLOW_ALTERED = "allow_altered";
130
- var DECISION_NOT_CHECKED = "not_checked";
131
- var DECISION_BLOCK = "block";
132
- var DECISION_REFUSE = "refuse";
133
- var DECISION_FAIL = "fail";
134
- var DECISIONS = [
135
- DECISION_ALLOW,
136
- DECISION_ALLOW_ALTERED,
137
- DECISION_NOT_CHECKED,
138
- DECISION_BLOCK,
139
- DECISION_REFUSE,
140
- DECISION_FAIL
141
- ];
142
- var DELIVERED_DECISIONS = /* @__PURE__ */ new Set([
143
- DECISION_ALLOW,
144
- DECISION_ALLOW_ALTERED,
145
- DECISION_NOT_CHECKED
146
- ]);
147
- var BODY_KEY = "shashu";
148
- var HEADER_DECISION = "x-shashu-decision";
149
- var HEADER_CODE = "x-shashu-code";
150
- var HEADER_INSPECTION = "x-shashu-inspection";
151
- var HEADER_SHOULD_RETRY = "x-should-retry";
152
- var HEADER_REQUEST_ID = "x-request-id";
153
- var HEADER_SHASHU_REQUEST_ID = "x-shashu-request-id";
154
- var HEADER_TRACE_ID = "x-shashu-trace-id";
155
- var HEADER_ATTACHMENTS = "x-shashu-attachments";
156
- var HEADER_MEMORY = "x-shashu-memory";
157
- var ATTACHMENT_STATES = /* @__PURE__ */ new Set([
158
- "scanned",
159
- "scanned_partial",
160
- "not_inspected",
161
- "blocked"
162
- ]);
163
- var carried = /* @__PURE__ */ new WeakMap();
164
- function rememberDecision(obj, decision) {
165
- carried.set(obj, decision);
166
- }
167
- function coerceDecision(raw) {
168
- if (typeof raw === "string" && DECISIONS.includes(raw)) {
169
- return raw;
170
- }
171
- return DECISION_BLOCK;
172
- }
173
- function parseInspectionHeader(value) {
174
- if (typeof value !== "string" || !value.trim()) return void 0;
175
- const out = {};
176
- const detectors = {};
177
- for (const part of value.split(";")) {
178
- if (!part.includes("=")) continue;
179
- const eq = part.indexOf("=");
180
- const name = part.slice(0, eq).trim();
181
- const state = part.slice(eq + 1).trim();
182
- if (name === "input" || name === "output" || name === "reason") out[name] = state;
183
- else if (name) detectors[name] = state;
184
- }
185
- if (Object.keys(detectors).length) out.detectors = detectors;
186
- return Object.keys(out).length ? out : void 0;
187
- }
188
- function headerGet(headers, name) {
189
- if (headers == null) return void 0;
190
- try {
191
- if (typeof headers.get === "function") {
192
- const v = headers.get(name);
193
- return v == null ? void 0 : v;
194
- }
195
- const rec = headers;
196
- const direct = rec[name];
197
- if (typeof direct === "string") return direct;
198
- const lower = name.toLowerCase();
199
- for (const [k, v] of Object.entries(rec)) {
200
- if (k.toLowerCase() === lower && typeof v === "string") return v;
201
- }
202
- } catch {
203
- return void 0;
204
- }
205
- return void 0;
206
- }
207
- function fromBody(body) {
208
- if (body == null || typeof body !== "object" || Array.isArray(body)) return void 0;
209
- const rec = body;
210
- const top = rec[BODY_KEY];
211
- if (top != null && typeof top === "object" && !Array.isArray(top)) {
212
- return top;
213
- }
214
- const err = rec.error;
215
- if (err != null && typeof err === "object" && !Array.isArray(err)) {
216
- const nested = err[BODY_KEY];
217
- if (nested != null && typeof nested === "object" && !Array.isArray(nested)) {
218
- return nested;
219
- }
220
- }
221
- return void 0;
222
- }
223
- function fromHeaders(headers) {
224
- const raw = headerGet(headers, HEADER_DECISION);
225
- if (typeof raw !== "string" || !raw.trim()) return void 0;
226
- const env = { decision: raw.trim() };
227
- const code = headerGet(headers, HEADER_CODE);
228
- if (typeof code === "string" && code.trim()) env.code = code.trim();
229
- const recordId = headerGet(headers, HEADER_REQUEST_ID);
230
- if (typeof recordId === "string" && recordId.trim()) env.id = recordId.trim();
231
- const hopId = headerGet(headers, HEADER_SHASHU_REQUEST_ID);
232
- if (typeof hopId === "string" && hopId.trim()) env.request_id = hopId.trim();
233
- const trace = headerGet(headers, HEADER_TRACE_ID);
234
- if (typeof trace === "string" && trace.trim()) env.trace_id = trace.trim();
235
- const shouldRetry = headerGet(headers, HEADER_SHOULD_RETRY);
236
- if (typeof shouldRetry === "string") env.retryable = shouldRetry.trim().toLowerCase() === "true";
237
- const inspection = parseInspectionHeader(headerGet(headers, HEADER_INSPECTION));
238
- if (inspection) env.inspection = inspection;
239
- return env;
240
- }
241
- var SHARED_FIELDS = ["decision", "code", "id", "retryable"];
242
- var str = (v) => typeof v === "string" ? v : void 0;
243
- var int = (v) => typeof v === "number" && Number.isInteger(v) ? v : void 0;
244
- var count = (v) => typeof v === "number" && Number.isInteger(v) && v > 0 ? v : 0;
245
- var isRecord = (v) => v != null && typeof v === "object" && !Array.isArray(v);
246
- var records = (v) => Array.isArray(v) ? v.filter(isRecord) : [];
247
- function readAttachment(item) {
248
- const rawState = str(item.state);
249
- return Object.freeze({
250
- state: rawState !== void 0 && ATTACHMENT_STATES.has(rawState) ? rawState : "unknown",
251
- rawState,
252
- reason: str(item.reason),
253
- filename: str(item.filename),
254
- declaredType: str(item.declared_type),
255
- sniffedType: str(item.sniffed_type),
256
- sha256: str(item.sha256),
257
- bytes: int(item.bytes),
258
- source: str(item.source),
259
- index: int(item.index),
260
- path: str(item.path),
261
- findings: Object.freeze(
262
- records(item.findings).map(
263
- (f) => Object.freeze({
264
- detector: str(f.detector),
265
- category: str(f.category),
266
- code: str(f.code),
267
- severity: str(f.severity),
268
- locator: str(f.locator)
269
- })
270
- )
271
- )
272
- });
273
- }
274
- function attachmentsFromBody(block) {
275
- if (!isRecord(block)) return void 0;
276
- return Object.freeze({
277
- total: count(block.total),
278
- scanned: count(block.scanned),
279
- scannedPartial: count(block.scanned_partial),
280
- notInspected: count(block.not_inspected),
281
- blocked: count(block.blocked),
282
- items: Object.freeze(records(block.items).map(readAttachment)),
283
- carrier: "body"
284
- });
285
- }
286
- function memoryFromBody(block) {
287
- if (!isRecord(block)) return void 0;
288
- return Object.freeze({
289
- writes: count(block.writes),
290
- writesBlocked: count(block.writes_blocked),
291
- recalls: count(block.recalls),
292
- recallsFlagged: count(block.recalls_flagged),
293
- coverage: str(block.coverage),
294
- items: Object.freeze(
295
- records(block.items).map(
296
- (i) => Object.freeze({
297
- kind: str(i.kind),
298
- state: str(i.state),
299
- reason: str(i.reason),
300
- tool: str(i.tool),
301
- store: str(i.store),
302
- scope: str(i.scope),
303
- source: str(i.source),
304
- enforcement: str(i.enforcement),
305
- memoryRef: str(i.memory_ref),
306
- writeRef: str(i.write_ref),
307
- seenBefore: typeof i.seen_before === "boolean" ? i.seen_before : void 0
308
- })
309
- )
310
- ),
311
- carrier: "body"
312
- });
313
- }
314
- function routePolicyFromBody(block) {
315
- if (!isRecord(block)) return void 0;
316
- return Object.freeze({
317
- route: str(block.route),
318
- category: str(block.category),
319
- reason: str(block.reason),
320
- requestedRoute: str(block.requested_route),
321
- degradedRoute: str(block.degraded_route)
322
- });
323
- }
324
- function countsHeader(value) {
325
- if (value === void 0) return void 0;
326
- const out = {};
327
- let any = false;
328
- for (const part of value.split(";")) {
329
- const eq = part.indexOf("=");
330
- if (eq < 0) continue;
331
- const name = part.slice(0, eq).trim();
332
- const n = part.slice(eq + 1).trim();
333
- if (name && /^[0-9]+$/.test(n)) {
334
- out[name] = Number(n);
335
- any = true;
336
- }
337
- }
338
- return any ? out : void 0;
339
- }
340
- function attachmentsFromHeader(value) {
341
- const c = countsHeader(value);
342
- if (!c) return void 0;
343
- const total = c.total ?? 0;
344
- const scanned = c.scanned ?? 0;
345
- const notInspected = c.not_inspected ?? 0;
346
- const blocked = c.blocked ?? 0;
347
- return Object.freeze({
348
- total,
349
- scanned,
350
- // The header does not carry it. The four states partition `total`, so the
351
- // remainder is scanned_partial — which errs, if the header is ever wrong,
352
- // toward counting a file as unverified rather than as checked.
353
- scannedPartial: Math.max(0, total - scanned - notInspected - blocked),
354
- notInspected,
355
- blocked,
356
- items: Object.freeze([]),
357
- carrier: "header"
358
- });
359
- }
360
- function memoryFromHeader(value) {
361
- const c = countsHeader(value);
362
- if (!c) return void 0;
363
- return Object.freeze({
364
- writes: c.writes ?? 0,
365
- writesBlocked: c.blocked ?? 0,
366
- recalls: c.recalls ?? 0,
367
- recallsFlagged: c.flagged ?? 0,
368
- coverage: void 0,
369
- items: Object.freeze([]),
370
- carrier: "header"
371
- });
372
- }
373
- function blockSource(bodyEnv, headers) {
374
- if (bodyEnv != null) {
375
- return "attachments" in bodyEnv || "memory" in bodyEnv || "route_policy" in bodyEnv ? { body: bodyEnv } : void 0;
376
- }
377
- return headers != null ? { headers } : void 0;
378
- }
379
- var SOURCE = /* @__PURE__ */ Symbol("trustgate.decision.blocks");
380
- var ATTACHMENTS = /* @__PURE__ */ Symbol("trustgate.decision.attachments");
381
- var MEMORY = /* @__PURE__ */ Symbol("trustgate.decision.memory");
382
- var UNREAD = /* @__PURE__ */ Symbol("trustgate.decision.unread");
383
- var _a, _b;
384
- SOURCE, _b = ATTACHMENTS, _a = MEMORY;
385
- var DecisionRecord = class {
386
- constructor(f, source) {
387
- this[_b] = UNREAD;
388
- this[_a] = UNREAD;
389
- this.decision = f.decision;
390
- this.rawDecision = f.rawDecision;
391
- this.code = f.code;
392
- this.retryable = f.retryable;
393
- this.id = f.id;
394
- this.requestId = f.requestId;
395
- this.traceId = f.traceId;
396
- this.inspection = f.inspection;
397
- this.versions = f.versions;
398
- this.message = f.message;
399
- this.retryAfterMs = f.retryAfterMs;
400
- this.altered = f.altered;
401
- this.carriers = f.carriers;
402
- this.carrierDisagreement = f.carrierDisagreement;
403
- this.delivered = DELIVERED_DECISIONS.has(f.decision);
404
- this.isBlock = f.decision === DECISION_BLOCK;
405
- this.isAltered = f.decision === DECISION_ALLOW_ALTERED;
406
- this.unverified = f.decision === DECISION_NOT_CHECKED;
407
- this[SOURCE] = source;
408
- }
409
- get attachments() {
410
- if (this[ATTACHMENTS] === UNREAD) {
411
- const src = this[SOURCE];
412
- this[ATTACHMENTS] = src === void 0 ? void 0 : "body" in src ? attachmentsFromBody(src.body.attachments) : attachmentsFromHeader(headerGet(src.headers, HEADER_ATTACHMENTS));
413
- }
414
- return this[ATTACHMENTS];
415
- }
416
- get memory() {
417
- if (this[MEMORY] === UNREAD) {
418
- const src = this[SOURCE];
419
- this[MEMORY] = src === void 0 ? void 0 : "body" in src ? memoryFromBody(src.body.memory) : memoryFromHeader(headerGet(src.headers, HEADER_MEMORY));
420
- }
421
- return this[MEMORY];
422
- }
423
- get routePolicy() {
424
- const src = this[SOURCE];
425
- return src !== void 0 && "body" in src ? routePolicyFromBody(src.body.route_policy) : void 0;
426
- }
427
- get filesUnverified() {
428
- const a = this.attachments;
429
- return a ? a.notInspected + a.scannedPartial : 0;
430
- }
431
- get filesBlocked() {
432
- return this.attachments?.blocked ?? 0;
433
- }
434
- get memoryBlocked() {
435
- return this.memory?.writesBlocked ?? 0;
436
- }
437
- get memoryRecallsFlagged() {
438
- return this.memory?.recallsFlagged ?? 0;
439
- }
440
- get memoryCoverage() {
441
- return this.memory?.coverage;
442
- }
443
- };
444
- function makeDecision(fields, source) {
445
- return new DecisionRecord(fields, source);
446
- }
447
- function build(bodyEnv, headerEnv, headers) {
448
- if (bodyEnv == null && headerEnv == null) return void 0;
449
- const carriers = [
450
- ...bodyEnv != null ? ["body"] : [],
451
- ...headerEnv != null ? ["headers"] : []
452
- ];
453
- const merged = { ...headerEnv ?? {}, ...bodyEnv ?? {} };
454
- const disagreement = {};
455
- if (bodyEnv != null && headerEnv != null) {
456
- for (const name of SHARED_FIELDS) {
457
- if (name in bodyEnv && name in headerEnv && bodyEnv[name] !== headerEnv[name]) {
458
- disagreement[name] = [bodyEnv[name], headerEnv[name]];
459
- }
460
- }
461
- }
462
- const raw = merged.decision;
463
- const retryAfterMs = merged.retry_after_ms;
464
- const versions = merged.versions;
465
- return makeDecision(
466
- {
467
- decision: coerceDecision(raw),
468
- rawDecision: typeof raw === "string" ? raw : void 0,
469
- code: typeof merged.code === "string" ? merged.code : void 0,
470
- retryable: Boolean(merged.retryable),
471
- id: typeof merged.id === "string" ? merged.id : void 0,
472
- requestId: typeof merged.request_id === "string" ? merged.request_id : void 0,
473
- traceId: typeof merged.trace_id === "string" ? merged.trace_id : typeof merged.id === "string" ? merged.id : void 0,
474
- inspection: merged.inspection != null && typeof merged.inspection === "object" && !Array.isArray(merged.inspection) ? merged.inspection : void 0,
475
- versions: versions != null && typeof versions === "object" && !Array.isArray(versions) ? versions : void 0,
476
- message: typeof merged.message === "string" ? merged.message : void 0,
477
- retryAfterMs: typeof retryAfterMs === "number" ? retryAfterMs : void 0,
478
- altered: merged.altered != null && typeof merged.altered === "object" && !Array.isArray(merged.altered) ? merged.altered : void 0,
479
- carriers,
480
- carrierDisagreement: disagreement
481
- },
482
- blockSource(bodyEnv, headers)
483
- );
484
- }
485
- function decisionFrom(body, headers) {
486
- return build(fromBody(body), fromHeaders(headers), headers);
487
- }
488
- async function decisionFromResponse(response) {
489
- let body;
490
- try {
491
- const ct = response.headers.get("content-type") ?? "";
492
- if (ct.includes("application/json")) body = await response.clone().json();
493
- } catch {
494
- body = void 0;
495
- }
496
- return decisionFrom(body, response.headers);
497
- }
498
- var BODY_ATTRIBUTES = ["response_body", "body"];
499
- function parsedBodyEnvelope(obj) {
500
- if (obj == null || typeof obj !== "object") return void 0;
501
- const rec = obj;
502
- for (const attribute of BODY_ATTRIBUTES) {
503
- const found = fromBody(rec[attribute]);
504
- if (found) return found;
505
- }
506
- return void 0;
507
- }
508
- function shashuDecision(obj) {
509
- try {
510
- if (obj == null) return void 0;
511
- if (typeof obj === "object") {
512
- const remembered = carried.get(obj);
513
- if (remembered) return remembered;
514
- const cached = obj.decision;
515
- if (cached && typeof cached === "object" && cached !== null && "decision" in cached) {
516
- return cached;
517
- }
518
- if (obj instanceof Response) {
519
- return build(void 0, fromHeaders(obj.headers), obj.headers);
520
- }
521
- if (!Array.isArray(obj)) {
522
- const bodyEnv = fromBody(obj) ?? parsedBodyEnvelope(obj);
523
- const headers = obj.responseHeaders ?? obj.headers ?? (obj.response ?? {}).headers;
524
- return build(bodyEnv, fromHeaders(headers), headers);
525
- }
526
- }
527
- } catch {
528
- return void 0;
529
- }
530
- return void 0;
531
- }
532
- function isShashuBlock(err) {
533
- try {
534
- const found = shashuDecision(err);
535
- if (found != null) return found.isBlock;
536
- if (err instanceof ShashuContentFilterError) return true;
537
- if (err != null && typeof err === "object") {
538
- for (const attribute of BODY_ATTRIBUTES) {
539
- const body = err[attribute];
540
- if (body == null || typeof body !== "object") continue;
541
- const rec = body;
542
- for (const candidate of [rec, rec.error]) {
543
- if (candidate != null && typeof candidate === "object" && candidate.type === "content_filter") {
544
- return true;
545
- }
546
- }
547
- const choices = rec.choices;
548
- if (Array.isArray(choices) && choices[0] && typeof choices[0] === "object") {
549
- if (choices[0].finish_reason === "content_filter") {
550
- return true;
551
- }
552
- }
553
- }
554
- }
555
- } catch {
556
- return false;
557
- }
558
- return false;
559
- }
560
-
561
- // src/client.ts
562
- var USER_AGENT = `trustgate-node/${SDK_VERSION}`;
563
- var joiningFetch = withRetrievalJoiner();
564
- var streamingInertWarningEmitted = false;
565
- function warnStreamingInert() {
566
- if (streamingInertWarningEmitted) return;
567
- streamingInertWarningEmitted = true;
568
- console.warn(
569
- "[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)"
570
- );
571
- }
572
- function resolveContext(config, options) {
573
- return options?.workflowContext ?? config.workflowContext ?? getWorkflowContextFromEnv();
574
- }
575
- function resolveBaseUrl(config) {
576
- return requireBaseUrl(config.baseUrl, { entryPoint: "new Shashu()" });
577
- }
578
- function mergeHeaders(config, options, context, session, token) {
579
- const out = {
580
- "content-type": "application/json",
581
- "user-agent": USER_AGENT,
582
- ...config.headers,
583
- ...options?.headers
584
- };
585
- const credential = token ?? config.apiKey;
586
- if (credential) {
587
- out["authorization"] = `Bearer ${credential}`;
588
- }
589
- if (context) {
590
- Object.assign(out, buildContextHeaders(context, session));
591
- }
592
- return out;
593
- }
594
- var Shashu = class {
595
- constructor(config) {
596
- this.resolvedBaseUrl = resolveBaseUrl(config);
597
- this.config = { ...config, baseUrl: this.resolvedBaseUrl };
598
- this.resolver = new CredentialResolver({
599
- apiKey: config.apiKey,
600
- tokenProvider: config.tokenProvider,
601
- requireOne: true
602
- });
603
- this._agentId = config.agentId;
604
- this._sessionId = config.sessionId ?? randomUUID();
605
- this.retryPolicy = resolveRetryPolicy(config.retryPolicy);
606
- this.audit = new Audit(this);
607
- }
608
- /** Base URL of the Shashu gateway. */
609
- get baseUrl() {
610
- return this.resolvedBaseUrl;
611
- }
612
- /** This agent's own id, as known so far (seed option or cached response header). */
613
- get agentId() {
614
- return this._agentId;
615
- }
616
- /**
617
- * The session this client joins. Minted once at construction when the caller
618
- * did not pass `sessionId`. A captured A2A session overrides it; a
619
- * per-request `sessionId` overrides both.
620
- */
621
- get sessionId() {
622
- return this._sessionId;
623
- }
624
- /**
625
- * Cache this agent's own id from the gateway's `x-shashu-agent-id` response header
626
- * (delivered by WP-A2A-1). Used by {@link buildInvocationHeaders} to stamp caller = self
627
- * on a downstream invocation. Read on EVERY response — including non-2xx — so even a
628
- * blocked response seeds the self-id. NEVER an auth credential. Fail-soft: never throws.
629
- */
630
- captureAgentId(res) {
631
- try {
632
- const aid = res.headers.get("x-shashu-agent-id");
633
- if (aid) this._agentId = aid;
634
- } catch {
635
- }
636
- }
637
- /**
638
- * Lineage headers to stamp on a message THIS agent sends to a DOWNSTREAM agent (the
639
- * invoking side, ADR-007 §4.1). caller-agent-id = this client's own id (`agentId` option,
640
- * refreshed from gateway responses); trace / hop / session default from the tracer so the
641
- * served flow is propagated. The downstream agent calls `captureIncoming()` on these
642
- * headers. Throws if self-id is not known yet — set the `agentId` option or make one
643
- * gateway call first so the `x-shashu-agent-id` response header can seed it.
644
- */
645
- buildInvocationHeaders(opts) {
646
- if (!this._agentId) {
647
- throw new Error(
648
- "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."
649
- );
650
- }
651
- return buildInvocationHeaders({ callerAgentId: this._agentId, ...opts });
652
- }
653
- /**
654
- * Get the current effective workflow context (from config override or process.env).
655
- */
656
- getWorkflowContext(options) {
657
- return resolveContext(this.config, options);
658
- }
659
- /**
660
- * Perform a non-streaming JSON request through Shashu. Request body is
661
- * sent unchanged; the gateway routes by the `model` field.
662
- *
663
- * Non-2xx responses throw the typed exception hierarchy (auth / bad-request /
664
- * context-window / rate-limit / permission / policy-violation / provider).
665
- * A 200 whose body has finish_reason="content_filter" throws
666
- * ShashuContentFilterError.
667
- *
668
- * Connection errors are retried per the client's retry policy. A 429 is
669
- * retried only when the gateway named a time to come back -- the
670
- * identical-request breaker names none, and retrying it refreshes the
671
- * window that is blocking you. See ./retry.js.
672
- */
673
- async fetch(path, init = {}, options) {
674
- const context = resolveContext(this.config, options);
675
- const url = path.startsWith("http") ? path : `${this.resolvedBaseUrl}/${path.replace(/^\//, "")}`;
676
- const timeout = options?.timeout ?? 6e4;
677
- const headersOnce = applyContractVersion(
678
- {
679
- ...mergeHeaders(this.config, options, context, {
680
- defaultSessionId: this._sessionId,
681
- requestSessionId: options?.sessionId
682
- }),
683
- ...init.headers
684
- },
685
- this.config.contractVersion
686
- );
687
- const frozenHeaders = { ...headersOnce };
688
- delete frozenHeaders["authorization"];
689
- delete frozenHeaders["Authorization"];
690
- const pinned = pinOutgoing(url, { ...init, headers: frozenHeaders });
691
- const send = async () => {
692
- const token = await this.resolver.get();
693
- const controller = new AbortController();
694
- const id = setTimeout(() => controller.abort(), timeout);
695
- try {
696
- const headers = { ...pinned.init?.headers };
697
- if (token) headers["authorization"] = `Bearer ${token}`;
698
- return await joiningFetch(pinned.input, {
699
- ...pinned.init,
700
- headers,
701
- signal: init.signal ?? controller.signal
702
- });
703
- } finally {
704
- clearTimeout(id);
705
- }
706
- };
707
- let res = await executeWithRetry(send, this.retryPolicy);
708
- if (this.resolver.usesProvider && res.status === 401) {
709
- const code = passRefusalCodeFromText(await res.clone().text());
710
- if (shouldRetryPassRefused({
711
- usesProvider: true,
712
- status: res.status,
713
- code,
714
- bytesDelivered: false
715
- })) {
716
- this.resolver.invalidate();
717
- res = await send();
718
- }
719
- }
720
- this.captureAgentId(res);
721
- const decision = await decisionFromResponse(res);
722
- if (decision) rememberDecision(res, decision);
723
- await raiseForResponse(res, decision);
724
- if (res.headers.get("content-type")?.includes("application/json")) {
725
- try {
726
- const json = await res.clone().json();
727
- raiseIfContentFiltered(json, decision, res.headers);
728
- } catch (err) {
729
- if (err instanceof ShashuContentFilterError) throw err;
730
- }
731
- }
732
- return res;
733
- }
734
- /**
735
- * Perform a streaming request (SSE). Forwards the response stream; gateway
736
- * attributes the request using workflow context. 403 throws ShashuError.
737
- *
738
- * NOTICE — streaming is INERT against a Shashu gateway today. The proxy
739
- * always calls the provider in non-streaming mode and buffers the full
740
- * response so its deferred-deanonymize / egress-scan step can run on the
741
- * complete body; it emits no chat SSE regardless of the `stream` flag or
742
- * DLP settings. This method consequently does not yield incremental tokens
743
- * — when the response is not `text/event-stream` it returns the buffered
744
- * JSON response unchanged. The method is kept (not removed) for forward
745
- * compatibility once gateway streaming lands. A one-time warning is logged
746
- * on first use.
747
- */
748
- async fetchStream(path, init = {}, options) {
749
- warnStreamingInert();
750
- const context = resolveContext(this.config, options);
751
- const url = path.startsWith("http") ? path : `${this.resolvedBaseUrl}/${path.replace(/^\//, "")}`;
752
- const send = async () => {
753
- const token = await this.resolver.get();
754
- const headers = mergeHeaders(
755
- this.config,
756
- options,
757
- context,
758
- {
759
- defaultSessionId: this._sessionId,
760
- requestSessionId: options?.sessionId
761
- },
762
- token
763
- );
764
- const mergedHeaders = applyContractVersion(
765
- {
766
- accept: "text/event-stream",
767
- ...headers,
768
- ...init.headers
769
- },
770
- this.config.contractVersion
771
- );
772
- return joiningFetch(url, {
773
- ...init,
774
- headers: mergedHeaders,
775
- signal: init.signal
776
- });
777
- };
778
- let res = await send();
779
- if (this.resolver.usesProvider && res.status === 401) {
780
- const code = passRefusalCodeFromText(await res.clone().text());
781
- if (shouldRetryPassRefused({
782
- usesProvider: true,
783
- status: res.status,
784
- code,
785
- bytesDelivered: false
786
- })) {
787
- this.resolver.invalidate();
788
- res = await send();
789
- }
790
- }
791
- this.captureAgentId(res);
792
- const decision = await decisionFromResponse(res);
793
- if (decision) rememberDecision(res, decision);
794
- if (!res.ok) {
795
- await raiseForResponse(res, decision);
796
- }
797
- if (!res.body) {
798
- return res;
799
- }
800
- if (!res.headers.get("content-type")?.includes("text/event-stream")) {
801
- return res;
802
- }
803
- return new Response(res.body, {
804
- status: res.status,
805
- statusText: res.statusText,
806
- headers: res.headers
807
- });
808
- }
809
- };
810
-
811
- // src/fetch.ts
812
- import { randomUUID as randomUUID2 } from "crypto";
813
- var DEFAULT_BLOCK_ENCODING = "explicit";
814
- var BLOCK_ENCODING_HEADER = "shashu-block-encoding";
815
- function shashuFetch(options = {}) {
816
- const resolver = new CredentialResolver({
817
- apiKey: options.apiKey,
818
- tokenProvider: options.tokenProvider
819
- });
820
- const defaultSessionId = options.sessionId ?? randomUUID2();
821
- const underlying = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
822
- const joining = withRetrievalJoiner(underlying);
823
- const baked = buildContextHeaders(options.workflowContext ?? getWorkflowContextFromEnv(), {
824
- defaultSessionId
825
- });
826
- if (options.blockEncoding !== null) {
827
- baked[BLOCK_ENCODING_HEADER] = options.blockEncoding ?? DEFAULT_BLOCK_ENCODING;
828
- }
829
- if (options.headers) {
830
- for (const [k, v] of Object.entries(options.headers)) baked[k.toLowerCase()] = v;
831
- }
832
- return async function trustgateFetching(input, init) {
833
- const send = async () => {
834
- const headers = { ...baked };
835
- const extra = init?.headers;
836
- if (extra instanceof Headers) extra.forEach((v, k) => headers[k.toLowerCase()] = v);
837
- else if (Array.isArray(extra)) {
838
- for (const [k, v] of extra) headers[String(k).toLowerCase()] = String(v);
839
- } else if (extra && typeof extra === "object") {
840
- for (const [k, v] of Object.entries(extra)) headers[k.toLowerCase()] = String(v);
841
- }
842
- const token = await resolver.get();
843
- if (token) headers.authorization = `Bearer ${token}`;
844
- return joining(input, {
845
- ...init,
846
- headers: applyContractVersion(headers, options.contractVersion)
847
- });
848
- };
849
- const res = await send();
850
- if (!resolver.usesProvider || res.status !== 401) return res;
851
- const text = await res.clone().text();
852
- const code = passRefusalCodeFromText(text);
853
- if (!shouldRetryPassRefused({
854
- usesProvider: true,
855
- status: res.status,
856
- code,
857
- bytesDelivered: false
858
- })) {
859
- return res;
860
- }
861
- resolver.invalidate();
862
- return send();
863
- };
864
- }
865
-
866
- // src/n8n.ts
867
- function getN8nHeaderSnippet(apiKey, baseUrl) {
868
- const key = apiKey ?? tracer.apiKey ?? envGet(API_KEY_ENV) ?? "";
869
- const url = baseUrl ?? tracer.gatewayUrl ?? envGet(BASE_URL_ENV) ?? "";
870
- const ctx = getWorkflowContextFromEnv();
871
- const contextHeaders = buildContextHeaders(ctx);
872
- const headers = [];
873
- if (url) {
874
- headers.push({ name: `${HEADER_PREFIX}-gateway-url`, value: url });
875
- }
876
- if (key) {
877
- headers.push({ name: "authorization", value: `Bearer ${key}` });
878
- headers.push({ name: "x-api-key", value: key });
879
- }
880
- for (const [name, value] of Object.entries(contextHeaders)) {
881
- headers.push({ name, value });
882
- }
883
- const json = JSON.stringify(
884
- headers.reduce((acc, { name, value }) => {
885
- acc[name] = value;
886
- return acc;
887
- }, {}),
888
- null,
889
- 2
890
- );
891
- return { headers, json };
892
- }
893
- export {
894
- Audit,
895
- BLOCK_ENCODING_HEADER,
896
- BODY_KEY,
897
- CONTRACT_VERSION_HEADER,
898
- DECISIONS,
899
- DECISION_ALLOW,
900
- DECISION_ALLOW_ALTERED,
901
- DECISION_BLOCK,
902
- DECISION_FAIL,
903
- DECISION_NOT_CHECKED,
904
- DECISION_REFUSE,
905
- DEFAULT_BLOCK_ENCODING,
906
- DEFAULT_CONTRACT_VERSION,
907
- DEFAULT_RETRY_POLICY,
908
- DELIVERED_DECISIONS,
909
- HEADER_ATTACHMENTS,
910
- HEADER_CODE,
911
- HEADER_DECISION,
912
- HEADER_INSPECTION,
913
- HEADER_MEMORY,
914
- HEADER_PREFIX,
915
- HEADER_REQUEST_ID,
916
- HEADER_SHASHU_REQUEST_ID,
917
- HEADER_SHOULD_RETRY,
918
- HEADER_TRACE_ID,
919
- MemoryWriteBlocked,
920
- PASS_CODES,
921
- PASS_EXPIRED,
922
- PASS_NOT_LICENSED,
923
- PASS_PROVIDER_NOT_SET_UP,
924
- PASS_UNKNOWN_AGENT,
925
- PASS_WRONG_AUDIENCE,
926
- PASS_WRONG_ISSUER,
927
- SOURCES,
928
- SOURCE_TOOL_HEADER,
929
- Shashu,
930
- ShashuAuthenticationError,
931
- ShashuBadRequestError,
932
- ShashuBudgetExceededError,
933
- ShashuConfigError,
934
- ShashuContentFilterError,
935
- ShashuContextWindowExceeded,
936
- ShashuError,
937
- ShashuPermissionError,
938
- ShashuPolicyViolation,
939
- ShashuProviderError,
940
- ShashuRateLimitError,
941
- TRUSTLOG_HEADER_PREFIX,
942
- attachRagContext,
943
- buildContextHeaders,
944
- buildInvocationHeaders,
945
- buildRagContext,
946
- buildSourceToolJson,
947
- captureIncoming,
948
- createShashuAnthropicConfig,
949
- createShashuGeminiConfig,
950
- createShashuLangChainConfig,
951
- createShashuOpenAIOptions,
952
- decisionFrom,
953
- declareMemory,
954
- declareRetrieval,
955
- executeWithRetry,
956
- gatewayRetryAfter,
957
- getAnthropicHeaders,
958
- getGeminiHeaders,
959
- getN8nHeaderSnippet,
960
- getShashuHeaders,
961
- getWorkflowContextFromEnv,
962
- isShashuBlock,
963
- makeRagContext,
964
- memoryScope,
965
- parseRetryAfter,
966
- raiseForResponse,
967
- raiseIfContentFiltered,
968
- resolveRetryPolicy,
969
- retrievalScope,
970
- shashuDecision,
971
- shashuFetch,
972
- tracer,
973
- withRetrievalJoiner
974
- };