@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.d.cts DELETED
@@ -1,748 +0,0 @@
1
- import { R as RequestOptions, S as ShashuConfig, W as WorkflowContext, a as ShashuError, D as Decision, M as MemoryActivity, N as N8nHeaderSnippet } from './types-BLs_TMFv.cjs';
2
- export { A as Attachment, b as AttachmentFinding, c as AttachmentState, d as Attachments, B as BODY_KEY, e as DECISIONS, f as DECISION_ALLOW, g as DECISION_ALLOW_ALTERED, h as DECISION_BLOCK, i as DECISION_FAIL, j as DECISION_NOT_CHECKED, k as DECISION_REFUSE, l as DEFAULT_RETRY_POLICY, m as DELIVERED_DECISIONS, H as HEADER_ATTACHMENTS, n as HEADER_CODE, o as HEADER_DECISION, p as HEADER_INSPECTION, q as HEADER_MEMORY, r as HEADER_REQUEST_ID, s as HEADER_SHASHU_REQUEST_ID, t as HEADER_SHOULD_RETRY, u as HEADER_TRACE_ID, v as MemoryItem, P as Provider, w as RetryPolicy, x as RoutePolicy, y as RuntimeMetadata, z as decisionFrom, C as executeWithRetry, E as isShashuBlock, F as resolveRetryPolicy, G as shashuDecision } from './types-BLs_TMFv.cjs';
3
- import { F as FetchLike } from './_joiner-DGi8GsY7.cjs';
4
- export { w as withRetrievalJoiner } from './_joiner-DGi8GsY7.cjs';
5
- export { D as DeclareRetrievalOptions, R as RagContext, a as RagDoc, b as RagSource, S as SOURCES, c as attachRagContext, d as buildRagContext, e as createShashuLangChainConfig, f as declareRetrieval, m as makeRagContext, r as retrievalScope } from './langchain-DKyrUjk4.cjs';
6
- export { ShashuOpenAIOptions, createShashuOpenAIOptions, getShashuHeaders } from './middleware/vercel-ai.cjs';
7
- export { createShashuAnthropicConfig, getAnthropicHeaders } from './middleware/anthropic.cjs';
8
- export { createShashuGeminiConfig, getGeminiHeaders } from './middleware/google.cjs';
9
-
10
- /**
11
- * Audit-event ingestion for vendor-controlled SaaS chokepoints.
12
- *
13
- * Mirrors the gateway's `POST /v1/audit/events` endpoint. Use this when you
14
- * have a connector (Microsoft Purview, Salesforce Event Bus, custom webhook)
15
- * that consumes vendor LLM events and needs to push them through Shashu's
16
- * scanner pipeline for audit-only logging — verdicts feed the audit log and
17
- * alerting but never block the originating request (the user already saw the
18
- * vendor's response).
19
- *
20
- * @example
21
- * const tg = new Shashu({ baseUrl, apiKey });
22
- * const result = await tg.audit.events({
23
- * source: "ms_copilot",
24
- * externalEventId: "evt_abc123",
25
- * occurredAt: "2026-05-02T14:00:00Z",
26
- * conversation: {
27
- * messages: [{ role: "user", content: "summarize Q3 board minutes" }],
28
- * response: "Q3 minutes summary: ...",
29
- * },
30
- * userContext: { user_id: "alice@example.com" },
31
- * });
32
- * if (result.is_threat) myAlertPipeline(result);
33
- */
34
-
35
- interface AuditConversation {
36
- messages?: Record<string, unknown>[];
37
- response?: string;
38
- shashu_metadata?: Record<string, unknown>;
39
- /** Free-form passthrough preserved alongside the canonical conversation. */
40
- extra?: Record<string, unknown>;
41
- }
42
- interface AuditEventInput {
43
- /** Connector identifier, e.g. "salesforce_einstein", "ms_copilot", "purview_dlp". */
44
- source: string;
45
- /** Vendor's event/transaction ID for cross-system correlation. */
46
- externalEventId?: string;
47
- /** ISO-8601 timestamp of the original LLM interaction. */
48
- occurredAt?: string;
49
- conversation: AuditConversation;
50
- /** Optional vendor-side user/tenant attribution for RBAC reporting. */
51
- userContext?: Record<string, unknown>;
52
- /**
53
- * Distributed trace ID linking related connector events. If absent, the
54
- * gateway falls back to the x-shashu-trace-id header (auto-detected
55
- * from env or tracer context); without either, the AuditLog row will only
56
- * have transaction_id.
57
- */
58
- traceId?: string;
59
- /** Optional parent span ID for hierarchy reconstruction. */
60
- parentSpanId?: string;
61
- /**
62
- * Vendor session/conversation ID grouping multi-turn events. Connectors
63
- * should pass the vendor's session ID here so multi-turn flows cluster
64
- * correctly in the dashboard.
65
- */
66
- sessionId?: string;
67
- }
68
- interface AuditVerdict {
69
- action?: string;
70
- severity?: string;
71
- pillars?: unknown;
72
- reason?: string;
73
- adapter?: string;
74
- }
75
- interface AuditEventResult {
76
- transaction_id: string;
77
- mode: string;
78
- audit_action: string;
79
- severity: string;
80
- is_threat: boolean;
81
- ingress_verdict: AuditVerdict | null;
82
- egress_verdict: AuditVerdict | null;
83
- surface_verdicts: Record<string, unknown> | null;
84
- }
85
- declare class Audit {
86
- private readonly client;
87
- constructor(client: Shashu);
88
- /**
89
- * POST a post-hoc audit event for scanning + audit-only logging.
90
- *
91
- * Non-2xx responses throw the typed exception hierarchy (e.g.
92
- * ShashuPolicyViolation on 403 when the connector key is invalid),
93
- * raised by `client.fetch`.
94
- */
95
- events(input: AuditEventInput, options?: RequestOptions): Promise<AuditEventResult>;
96
- }
97
-
98
- /**
99
- * Shashu Node.js client. All traffic is sent to the Shashu gateway with
100
- * Bearer auth (tg_sk_...). The gateway routes to OpenAI/Anthropic based on
101
- * the `model` field in the request body.
102
- */
103
- declare class Shashu {
104
- private readonly config;
105
- private readonly resolvedBaseUrl;
106
- private readonly retryPolicy;
107
- private readonly resolver;
108
- /** One session for this client. See `contracts/sdk-surface.v1.md`. */
109
- private readonly _sessionId;
110
- /**
111
- * This agent's OWN id (ADR-007 §4.1). Seeded by the `agentId` option and refreshed from
112
- * each gateway response's `x-shashu-agent-id` header (read on EVERY response, incl.
113
- * 4xx). Used by {@link buildInvocationHeaders} to stamp caller = self when invoking a
114
- * downstream agent — never sent as the gateway call's caller. Advisory lineage, never auth.
115
- */
116
- private _agentId?;
117
- /** Audit-event ingestion for vendor-controlled SaaS chokepoints. */
118
- readonly audit: Audit;
119
- constructor(config: ShashuConfig);
120
- /** Base URL of the Shashu gateway. */
121
- get baseUrl(): string;
122
- /** This agent's own id, as known so far (seed option or cached response header). */
123
- get agentId(): string | undefined;
124
- /**
125
- * The session this client joins. Minted once at construction when the caller
126
- * did not pass `sessionId`. A captured A2A session overrides it; a
127
- * per-request `sessionId` overrides both.
128
- */
129
- get sessionId(): string;
130
- /**
131
- * Cache this agent's own id from the gateway's `x-shashu-agent-id` response header
132
- * (delivered by WP-A2A-1). Used by {@link buildInvocationHeaders} to stamp caller = self
133
- * on a downstream invocation. Read on EVERY response — including non-2xx — so even a
134
- * blocked response seeds the self-id. NEVER an auth credential. Fail-soft: never throws.
135
- */
136
- private captureAgentId;
137
- /**
138
- * Lineage headers to stamp on a message THIS agent sends to a DOWNSTREAM agent (the
139
- * invoking side, ADR-007 §4.1). caller-agent-id = this client's own id (`agentId` option,
140
- * refreshed from gateway responses); trace / hop / session default from the tracer so the
141
- * served flow is propagated. The downstream agent calls `captureIncoming()` on these
142
- * headers. Throws if self-id is not known yet — set the `agentId` option or make one
143
- * gateway call first so the `x-shashu-agent-id` response header can seed it.
144
- */
145
- buildInvocationHeaders(opts?: {
146
- traceId?: string;
147
- sessionId?: string;
148
- hopDepth?: number;
149
- }): Record<string, string>;
150
- /**
151
- * Get the current effective workflow context (from config override or process.env).
152
- */
153
- getWorkflowContext(options?: RequestOptions): WorkflowContext;
154
- /**
155
- * Perform a non-streaming JSON request through Shashu. Request body is
156
- * sent unchanged; the gateway routes by the `model` field.
157
- *
158
- * Non-2xx responses throw the typed exception hierarchy (auth / bad-request /
159
- * context-window / rate-limit / permission / policy-violation / provider).
160
- * A 200 whose body has finish_reason="content_filter" throws
161
- * ShashuContentFilterError.
162
- *
163
- * Connection errors are retried per the client's retry policy. A 429 is
164
- * retried only when the gateway named a time to come back -- the
165
- * identical-request breaker names none, and retrying it refreshes the
166
- * window that is blocking you. See ./retry.js.
167
- */
168
- fetch(path: string, init?: RequestInit, options?: RequestOptions): Promise<Response>;
169
- /**
170
- * Perform a streaming request (SSE). Forwards the response stream; gateway
171
- * attributes the request using workflow context. 403 throws ShashuError.
172
- *
173
- * NOTICE — streaming is INERT against a Shashu gateway today. The proxy
174
- * always calls the provider in non-streaming mode and buffers the full
175
- * response so its deferred-deanonymize / egress-scan step can run on the
176
- * complete body; it emits no chat SSE regardless of the `stream` flag or
177
- * DLP settings. This method consequently does not yield incremental tokens
178
- * — when the response is not `text/event-stream` it returns the buffered
179
- * JSON response unchanged. The method is kept (not removed) for forward
180
- * compatibility once gateway streaming lands. A one-time warning is logged
181
- * on first use.
182
- */
183
- fetchStream(path: string, init?: RequestInit, options?: RequestOptions): Promise<Response>;
184
- }
185
-
186
- /**
187
- * A `fetch` carrying Shashu's joiner and headers, for a provider SDK we
188
- * do not own.
189
- *
190
- * The seam every OpenAI-compatible SDK already offers is a caller-supplied
191
- * `fetch`. This is that: no patching, no wrapper class.
192
- *
193
- * import { shashuFetch } from "@shashu-ai/sdk";
194
- * const openai = new OpenAI({ baseURL, apiKey, fetch: shashuFetch({ apiKey }) });
195
- *
196
- * Two things ride on it:
197
- *
198
- * 1. **The joiner** — the same `withRetrievalJoiner` `Shashu` mounts,
199
- * imported, not reimplemented. A caller-supplied `fetch` is the underlying
200
- * transport (never replaced); when omitted, `globalThis.fetch` is the
201
- * default.
202
- * 2. **The headers** — whatever `buildContextHeaders` builds, including a
203
- * session minted ONCE at construction, so every hop of a tool loop lands
204
- * in one session.
205
- */
206
-
207
- /** How the gateway should encode a block. A default, not a hardcode. */
208
- declare const DEFAULT_BLOCK_ENCODING = "explicit";
209
- /** The header `DEFAULT_BLOCK_ENCODING` is sent under. Lowercase. */
210
- declare const BLOCK_ENCODING_HEADER = "shashu-block-encoding";
211
- interface ShashuFetchOptions {
212
- /** Session every request this fetch makes joins. Minted once when omitted. */
213
- sessionId?: string;
214
- /**
215
- * Underlying `fetch`. Never replaced: the joiner wraps it. Omit to default
216
- * to `globalThis.fetch` at call time.
217
- */
218
- fetch?: FetchLike;
219
- workflowContext?: WorkflowContext;
220
- headers?: Record<string, string>;
221
- apiKey?: string;
222
- /** Callable returning the current cloud pass. Mutually exclusive with apiKey. */
223
- tokenProvider?: () => string | Promise<string>;
224
- /**
225
- * `Shashu-Block-Encoding`. Default `explicit`. Pass `null` to send no
226
- * such header.
227
- */
228
- blockEncoding?: string | null;
229
- /**
230
- * `shashu-version`. Default `DEFAULT_CONTRACT_VERSION` (`"2026-09-01"`).
231
- * Without it the gateway serves its legacy contract and discards the block
232
- * encoding above. Pass `null` to send no such header.
233
- */
234
- contractVersion?: string | null;
235
- }
236
- /**
237
- * A `fetch` to hand to a provider SDK's `fetch` option.
238
- *
239
- * Carries the retrieval joiner and the `x-shashu-*` header set, so a
240
- * LangChain / Vercel AI / raw-`openai` call made through it is attributed,
241
- * traced and able to declare its retrieval — with nothing patched.
242
- */
243
- declare function shashuFetch(options?: ShashuFetchOptions): FetchLike;
244
-
245
- /**
246
- * The gateway's pass refusal codes (`contracts/sdk-surface.v1.md`, "Signing in
247
- * with a cloud pass — the six refusal codes"). Arrive in `error.code` on an
248
- * HTTP 401, on the legacy body and every contract version.
249
- */
250
- declare const PASS_PROVIDER_NOT_SET_UP = "pass_provider_not_set_up";
251
- declare const PASS_NOT_LICENSED = "pass_not_licensed";
252
- declare const PASS_EXPIRED = "pass_expired";
253
- declare const PASS_WRONG_AUDIENCE = "pass_wrong_audience";
254
- declare const PASS_WRONG_ISSUER = "pass_wrong_issuer";
255
- declare const PASS_UNKNOWN_AGENT = "pass_unknown_agent";
256
- declare const PASS_CODES: readonly ["pass_provider_not_set_up", "pass_not_licensed", "pass_expired", "pass_wrong_audience", "pass_wrong_issuer", "pass_unknown_agent"];
257
- type PassRefusalCode = (typeof PASS_CODES)[number];
258
-
259
- /** Lowercase header prefix for proxy/gateway parity with Python SDK. */
260
- declare const HEADER_PREFIX = "x-shashu";
261
- /** Header carrying the full context JSON (structurally identical to Python SDK). */
262
- declare const SOURCE_TOOL_HEADER = "x-shashu-source-tool";
263
- /**
264
- * The contract generation this SDK speaks, declared on every request — the
265
- * same value the Python SDK sends (`trustgate.context.DEFAULT_CONTRACT_VERSION`).
266
- *
267
- * The gateway resolves an ABSENT `shashu-version` header to its legacy
268
- * contract: a refusal is a 200 with prose in `message.content`, the body
269
- * carries no envelope (so memory and file items reach a caller as header
270
- * counts only), and the `shashu-block-encoding` header `shashuFetch`
271
- * sends is read and discarded.
272
- *
273
- * A documented default, not a hardcode: pass `contractVersion` to pin another,
274
- * or `contractVersion: null` to send no such header and take whatever the
275
- * account default already does.
276
- */
277
- declare const DEFAULT_CONTRACT_VERSION = "2026-09-01";
278
- /** The header {@link DEFAULT_CONTRACT_VERSION} is sent under. Lowercase. */
279
- declare const CONTRACT_VERSION_HEADER = "shashu-version";
280
- /**
281
- * Searches process.env for workflow metadata from n8n, Vercel, or GitHub.
282
- * If no managed environment is detected, returns context with source "local_script"
283
- * so local developer usage is correctly tagged as Shadow AI in the dashboard.
284
- * Never returns null.
285
- */
286
- declare function getWorkflowContextFromEnv(): WorkflowContext;
287
- /**
288
- * JSON payload for x-shashu-source-tool header (structurally identical to Python SDK).
289
- */
290
- declare function buildSourceToolJson(ctx: WorkflowContext): string;
291
- /** Prefix for runtime/metadata headers (e.g. x-trustlog-node-version). */
292
- declare const TRUSTLOG_HEADER_PREFIX = "x-trustlog-";
293
- declare function buildContextHeaders(ctx: WorkflowContext, session?: SessionHeaderOptions): Record<string, string>;
294
- /**
295
- * How {@link buildContextHeaders} picks the session. One place, not a second
296
- * copy on the client. Rank, from the contract:
297
- *
298
- * 1. `requestSessionId` — a per-request INSTRUCTION. Wins.
299
- * 2. a captured inbound A2A session — overrides the construction-time default.
300
- * 3. `defaultSessionId` — the client's own session, minted once at construction.
301
- */
302
- interface SessionHeaderOptions {
303
- /** Construction-time default. A captured A2A session overrides this. */
304
- defaultSessionId?: string;
305
- /** Per-request instruction. Wins over the captured session and the default. */
306
- requestSessionId?: string;
307
- }
308
- /** Options for {@link buildInvocationHeaders}. */
309
- interface InvocationHeaderOptions {
310
- /** THIS agent's own id — the invoker stamps itself. Advisory lineage, never auth. */
311
- callerAgentId: string;
312
- /** Flow id; defaults to the served flow (tracer.traceId) or a fresh root at origin. */
313
- traceId?: string;
314
- /** Session id; defaults to the captured session, if any. */
315
- sessionId?: string;
316
- /** Hop depth to advertise; defaults to tracer.outboundHopDepth (inbound + 1). */
317
- hopDepth?: number;
318
- }
319
- /**
320
- * Build the Shashu lineage headers to stamp on an INTER-AGENT INVOCATION — the message
321
- * THIS agent sends to a DOWNSTREAM agent it is calling (the invoking side, ADR-007 §4.1
322
- * locked). The downstream agent then calls {@link captureIncoming} on these headers and
323
- * FORWARDS this caller on its own gateway call — forming the (this agent -> downstream
324
- * agent) edge.
325
- *
326
- * `callerAgentId` is THIS agent's own id (the invoker stamps itself) — the one case where
327
- * the SDK sets caller = self. It is advisory lineage, NEVER an auth credential; authenticate
328
- * to the downstream service by its own means.
329
- *
330
- * Defaults pull from the tracer so the flow this agent is serving is propagated: `traceId`
331
- * -> tracer.traceId (a fresh root is minted at origin, the captured flow is propagated
332
- * mid-flow); `hopDepth` -> tracer.outboundHopDepth; `sessionId` -> the captured session.
333
- */
334
- declare function buildInvocationHeaders(opts: InvocationHeaderOptions): Record<string, string>;
335
-
336
- /**
337
- * Shashu SDK exception hierarchy (mirrors the Python SDK).
338
- *
339
- * Every shape named below is a verbatim capture from a running gateway, taken
340
- * with `sdks/e2e/capture_error_contract.py` in the trustgate-ai repo. That
341
- * harness is the source of truth for this module; a claim that cannot be
342
- * reproduced with it does not belong here. The previous version of this header
343
- * was derived from an investigation write-up and got three things wrong — see
344
- * CHANGELOG 1.8.0.
345
- *
346
- * 401 -> ShashuAuthenticationError type="invalid_request_error"
347
- * 400 -> ShashuBadRequestError type="ProviderInvalidRequestError"
348
- * 400 -> ShashuContextWindowExceeded type="context_window_exceeded"
349
- * 400 -> ShashuContentFilterError type="content_filter"
350
- * 429 -> ShashuRateLimitError see "The two 429s" below
351
- * 403 -> ShashuPermissionError
352
- * └─ ShashuPolicyViolation (every 403; concrete back-compat type)
353
- * └─ MemoryWriteBlocked (a 403 whose decision refused a memory write)
354
- * 404 -> ShashuError type="ProviderModelNotFoundError"
355
- * 502/503/504 -> ShashuProviderError
356
- * 2xx + finish_reason="content_filter" -> ShashuContentFilterError
357
- *
358
- * **A security block has two encodings and ONE exception type.** The gateway
359
- * serialises the same block either as 200 + `finish_reason "content_filter"`
360
- * (`compatible` / legacy) or as 400 + `error.type "content_filter"`
361
- * (`explicit`, the default at contract `2026-09-01`). Which one a caller sees
362
- * is chosen by a request header or an account default, so the two must not
363
- * throw different types — see {@link ShashuContentFilterError}.
364
- *
365
- * **`error.type` is a discriminator on exactly one value.** Every OTHER 4xx the
366
- * gateway raises itself carries `"invalid_request_error"` — a 401, a 403 and a
367
- * 422 are identical in that field — and under contract `2026-09-01` a refusal
368
- * carries `authentication_error` / `permission_error` / `rate_limit_error` by
369
- * status, which restates the status rather than refining it. The two values
370
- * worth branching on are `content_filter` and `context_window_exceeded`, both
371
- * on a 400, and both are read below. Everything else is dispatched on the
372
- * status: see `dispatchCode` for what `error.code` actually holds and why it is
373
- * not the discriminator this module once called it.
374
- *
375
- * **A 401 is not always about your key.** The gateway's own auth failure sends
376
- * `type="invalid_request_error"` with message `"Invalid TrustGate API Key"` or
377
- * `"Not authenticated"` (the latter with a `WWW-Authenticate: Bearer` header).
378
- * A 401 carrying `type="authentication_error"` and a message prefixed
379
- * `"TrustGate Provider Error: "` is a **pass-through**: the gateway's own stored
380
- * provider credential was rejected upstream. Your `tg_sk_` key is fine and
381
- * rotating it changes nothing — a gateway operator has to fix the provider
382
- * secret. The same is true of 403 (`ProviderPermissionError`), 404, 429 and the
383
- * 5xx family. This module used to attribute `authentication_error` to the
384
- * gateway's own 401, which pointed every reader at the wrong credential.
385
- *
386
- * **The two 429s.** They are different responses and only one is retryable:
387
- *
388
- * - the token bucket sends `Retry-After` and nests its structured detail at
389
- * `error.details.error` — `type="rate_limit_exceeded"`, `scope`,
390
- * `retry_after_seconds` and the readable `message`. The OUTER
391
- * `error.message` on that body is the literal string `"error"`, so this
392
- * module reads the inner one.
393
- * - the identical-request breaker sends **no** `Retry-After`, no `details`,
394
- * and puts `"Infinite Loop Detected"` at `error.message`. Retrying it
395
- * re-trips the breaker and refreshes its window — see `./retry.js`.
396
- *
397
- * **Budget-vs-policy is NOT detectable.** It used to be guessed by testing
398
- * `/budget/i` against the message. That is gone (1.8.0): a message is prose, it
399
- * gets reworded, and it is not a contract. `ShashuBudgetExceededError` is
400
- * still exported so existing `catch` clauses type-check, but nothing throws it —
401
- * every 403 is a `ShashuPolicyViolation`. Catch `ShashuPermissionError` to
402
- * cover both. It becomes reachable again if the gateway ships a real
403
- * discriminator (ticket TRUSTGATE-403-DISCRIMINATOR).
404
- *
405
- * `ShashuError` remains the base (re-exported from "./types.js" for
406
- * backward compatibility), so existing `catch (e) { e instanceof ShashuError }`
407
- * code keeps working — every typed error is a subclass. Pillar/severity are not
408
- * in caller-facing bodies (they live in the audit log) and are absent here.
409
- */
410
-
411
- type ErrorDetails = {
412
- type?: string;
413
- code?: string;
414
- decision?: Decision;
415
- responseHeaders?: Headers;
416
- };
417
- /**
418
- * The SDK was asked to instrument or address a process it cannot address.
419
- *
420
- * The odd one out in this module: every other class here is HTTP-status shaped
421
- * and describes a response. This one is raised BEFORE any request, at
422
- * construction or configuration time, and only for configuration the caller can
423
- * fix. `status` is therefore `0` — not an HTTP status, but the honest statement
424
- * that nothing was sent. (The field is non-optional on the base class and
425
- * widening it to `number | undefined` would break every consumer that compares
426
- * it, so 0 carries the meaning instead.)
427
- *
428
- * SHASHU is self-hosted, so there is no address the SDK could fall back to —
429
- * a fallback would send the operator's prompts to a host they never named.
430
- * Resolution is: explicit `baseUrl` option, then the environment, then this
431
- * error. The message names the environment variable and the option; it
432
- * deliberately suggests no hostname. See ./config.ts.
433
- */
434
- declare class ShashuConfigError extends ShashuError {
435
- constructor(message: string);
436
- }
437
- /**
438
- * 401 — an authentication failure. NOT necessarily yours.
439
- *
440
- * Two different producers land here and they need opposite fixes:
441
- *
442
- * - the **gateway's own** agent-key check — missing, unknown, deactivated or
443
- * rotated `tg_sk_` key. `type="invalid_request_error"`, message
444
- * `"Invalid TrustGate API Key"` or `"Not authenticated"`. Fix: your key.
445
- * - a **provider pass-through** — the gateway's stored provider credential was
446
- * rejected upstream. `type="authentication_error"`, message prefixed
447
- * `"TrustGate Provider Error: "`. Your key is fine; rotating it changes
448
- * nothing. Fix: a gateway operator replaces the provider secret.
449
- *
450
- * {@link isProviderPassthrough} tells them apart.
451
- */
452
- declare class ShashuAuthenticationError extends ShashuError {
453
- constructor(message: string, status: number, body?: unknown, details?: ErrorDetails);
454
- /**
455
- * True when the upstream provider rejected the gateway's credential.
456
- *
457
- * Reads `error.type`, the one field the gateway populates differently for
458
- * pass-throughs, and falls back to the message prefix it stamps on every
459
- * pass-through when the body carried no type.
460
- */
461
- get isProviderPassthrough(): boolean;
462
- }
463
- declare class ShashuBadRequestError extends ShashuError {
464
- constructor(message: string, status: number, body?: unknown, details?: ErrorDetails);
465
- }
466
- declare class ShashuContextWindowExceeded extends ShashuBadRequestError {
467
- constructor(message: string, status: number, body?: unknown, details?: ErrorDetails);
468
- }
469
- declare class ShashuRateLimitError extends ShashuError {
470
- /** Limiter scope ("tenant" | "agent" | "tpm") when provided by the gateway. */
471
- readonly scope?: string;
472
- /** Seconds to wait before retrying, from the body or the Retry-After header. */
473
- readonly retryAfterSeconds?: number;
474
- constructor(message: string, status: number, body?: unknown, details?: ErrorDetails & {
475
- scope?: string;
476
- retryAfterSeconds?: number;
477
- });
478
- }
479
- declare class ShashuPermissionError extends ShashuError {
480
- constructor(message: string, status: number, body?: unknown, details?: ErrorDetails);
481
- }
482
- /**
483
- * 403 — the agent's monthly budget is exhausted.
484
- *
485
- * **Never thrown today.** It used to be thrown when `/budget/i` matched the 403
486
- * message, which is guessing from prose: it misfired on any policy denial whose
487
- * wording mentioned a budget, and missed a real budget denial the moment someone
488
- * reworded the message. The gateway sends no discriminator — every 403 carries
489
- * an identical `{type: "invalid_request_error", code: "403"}` envelope — so the
490
- * honest answer is that this cannot be detected.
491
- *
492
- * Kept exported so existing `catch` clauses still type-check. Catch
493
- * {@link ShashuPermissionError} to cover budget and policy together. This
494
- * class becomes reachable again if the gateway ships a real discriminator
495
- * (ticket TRUSTGATE-403-DISCRIMINATOR,
496
- * https://github.com/aisquad001/trustgate-ai/issues/736).
497
- */
498
- declare class ShashuBudgetExceededError extends ShashuPermissionError {
499
- constructor(message: string, status: number, body?: unknown, details?: ErrorDetails);
500
- }
501
- declare class ShashuPolicyViolation extends ShashuPermissionError {
502
- constructor(message: string, status: number, body?: unknown, details?: ErrorDetails);
503
- }
504
- /**
505
- * 403 — the gateway refused to store a memory write.
506
- *
507
- * A {@link ShashuPolicyViolation}, so every existing `catch` for that type
508
- * still catches it. Thrown when the decision's `memory` block reports a
509
- * blocked write; which write, and why, is on {@link MemoryWriteBlocked.memory}.
510
- * The type is chosen from that block, never from a copy of the `code` or
511
- * reason vocabulary.
512
- */
513
- declare class MemoryWriteBlocked extends ShashuPolicyViolation {
514
- constructor(message: string, status: number, body?: unknown, details?: ErrorDetails);
515
- /** The decision's memory block. */
516
- get memory(): MemoryActivity | undefined;
517
- }
518
- /**
519
- * 502/503/504 — an upstream LLM provider error surfaced by the gateway.
520
- *
521
- * `error.type` on these is the gateway's own provider-error class name
522
- * (`ProviderServerError`, `ProviderConnectionError`, `ProviderTimeoutError`, …).
523
- * There is no `"provider_error"` type; this module used to claim there was.
524
- */
525
- declare class ShashuProviderError extends ShashuError {
526
- constructor(message: string, status: number, body?: unknown, details?: ErrorDetails);
527
- }
528
- /**
529
- * The gateway blocked the content. ONE type, both encodings.
530
- *
531
- * A security block reaches the caller in one of two shapes, and which one
532
- * depends on request headers (`shashu-version`, `shashu-block-encoding`)
533
- * or an account default the caller may not control. Since 4.0.0 this SDK
534
- * sends `shashu-version: 2026-09-01` by default, so the 400 is what a
535
- * caller sees unless they pass `contractVersion: null`:
536
- *
537
- * - `compatible` / legacy — **HTTP 200**, `finish_reason "content_filter"`.
538
- * {@link finishReason} is that string and `status` is 200.
539
- * - `explicit` (the default at contract `2026-09-01`) — **HTTP 400**,
540
- * `error.type "content_filter"` and `error.code` naming the finding
541
- * (`jailbreak`, `dlp`, `pii_output`, `secret`, `prompt_injection`).
542
- * {@link finishReason} is `null`; the finding is on `code`.
543
- *
544
- * They are the same event, so they throw the same type. Splitting them would
545
- * mean an `instanceof ShashuContentFilterError` check silently stopped
546
- * working on the day an operator moved the account default — a client-side
547
- * break with no client-side change, which is the failure the gateway's own
548
- * versioning exists to prevent. Callers that must tell the encodings apart
549
- * read `status` or {@link finishReason}.
550
- */
551
- declare class ShashuContentFilterError extends ShashuError {
552
- /**
553
- * `"content_filter"` on the 200 encoding; `null` on the 400 one, where there
554
- * is no `choices` array to carry a finish reason.
555
- */
556
- readonly finishReason: string | null;
557
- constructor(message: string, body: unknown, finishReason?: string | null, status?: number, details?: ErrorDetails);
558
- }
559
- /**
560
- * Seconds the gateway asked the caller to wait, or `undefined` if it did not ask.
561
- *
562
- * **`undefined` is a decision, not a missing value.** The gateway names a retry
563
- * time when it is throttling you and stays silent when the refusal will not
564
- * clear on its own — see `./retry.js`, which uses exactly this to decide whether
565
- * a 429 may be retried at all.
566
- *
567
- * Header first: `Retry-After` is present on every token-bucket rejection and
568
- * costs nothing to read. `error.details.error.retry_after_seconds` is the same
569
- * number, consulted only when the header is absent, and read from an
570
- * already-parsed body so the response stream is never touched.
571
- */
572
- declare function gatewayRetryAfter(res: Pick<Response, 'headers'>, parsedBody?: unknown): number | undefined;
573
- /** Parse an integer-seconds or HTTP-date Retry-After header into seconds, or undefined. */
574
- declare function parseRetryAfter(value: string | null | undefined): number | undefined;
575
- /**
576
- * Throw the appropriate Shashu error for a non-2xx gateway Response.
577
- * No-op for 2xx (use {@link raiseIfContentFiltered} for the 200 block path).
578
- * Reads the body, so call only when you will not also consume `res`.
579
- *
580
- * **This function FAILS OPEN as to block-ness, deliberately, and that is the
581
- * opposite direction to {@link isShashuBlock}. Both are correct because
582
- * they answer different questions.** This one decides whether to REPLACE a
583
- * provider's own error with a Shashu type: turning a genuine provider 400
584
- * into a fake block would break `catch` clauses a customer already has, so it
585
- * needs a positive signal (a 403, or a 400 whose `error.type` is
586
- * `content_filter`) before it acts, and anything unreadable stays a generic
587
- * ShashuError / ShashuBadRequestError. `isShashuBlock` is called on
588
- * an error the customer already holds, replaces nothing, and therefore fails
589
- * CLOSED — an unparseable Shashu block signal answers true there. See the
590
- * docstring on that function for the full argument.
591
- *
592
- * @see isShashuBlock
593
- */
594
- declare function raiseForResponse(res: Response, decision?: Decision): Promise<void>;
595
- /** Throw ShashuContentFilterError if a parsed 200 body was content-filtered. */
596
- declare function raiseIfContentFiltered(json: unknown, decision?: Decision, headers?: Headers): void;
597
-
598
- /**
599
- * Captured inbound A2A flow (WP-A2A-4 / ADR-007 §0, §4.1). When this agent is SERVING
600
- * a request, captureIncoming() stores the inbound flow here so a downstream gateway call
601
- * made through the SDK PROPAGATES the same flow (trace + session + hop + caller lineage)
602
- * instead of minting a fresh one. Held in its own AsyncLocalStorage so it composes with —
603
- * but is independent of — span context. Absent store ⇒ origin (non-A2A behavior unchanged).
604
- */
605
- interface A2ACapture {
606
- /** The flow id, propagated unchanged on the outbound gateway call. */
607
- traceId: string;
608
- /** The captured inbound session id, if any. */
609
- sessionId?: string;
610
- /** Advisory inbound hop depth from x-shashu-hop-depth (0 if absent). */
611
- inboundHopDepth: number;
612
- /** The upstream agent that INVOKED this hop (x-shashu-caller-agent-id), FORWARDED
613
- * on the outbound gateway call — never this agent's own id (§4.1). */
614
- inboundCallerAgentId?: string;
615
- }
616
- declare class Tracer {
617
- private buffer;
618
- private flushTimer;
619
- private _gatewayUrl?;
620
- private _apiKey?;
621
- /**
622
- * Resolves the address OPTIONALLY, unlike every other entry point.
623
- *
624
- * The module exports a singleton (`export const tracer = new Tracer()`), so
625
- * this constructor runs on `import "@shashu-ai/sdk"`. Throwing here would
626
- * make importing the SDK fail for anyone who has not set the variable, which
627
- * is a far worse failure than the one this is fixing. Instead the address
628
- * stays undefined and {@link flush} posts nothing — the same shape as the
629
- * Python SDK's telemetry path, which resolves with optional_base_url and
630
- * no-ops the flush.
631
- */
632
- constructor();
633
- /**
634
- * Current gateway base URL (respects configure()), or undefined when none is
635
- * configured. Undefined means telemetry is not sent — never a default host.
636
- */
637
- get gatewayUrl(): string | undefined;
638
- /** Current API key (respects configure()). */
639
- get apiKey(): string | undefined;
640
- /**
641
- * Update gateway URL and/or API key at runtime (e.g. for scripts switching agents).
642
- * baseUrl has its trailing slash stripped to match constructor behavior.
643
- */
644
- configure(opts: {
645
- baseUrl?: string;
646
- apiKey?: string;
647
- }): void;
648
- get traceId(): string | undefined;
649
- get currentSpanId(): string | undefined;
650
- /** The current span's PARENT span id; undefined at origin or for a root span. */
651
- get parentSpanId(): string | undefined;
652
- get isActive(): boolean;
653
- /** True when this context CAPTURED an inbound flow — so a downstream gateway call
654
- * PROPAGATES the trace and attaches caller/session/hop lineage rather than originate
655
- * a new flow. False = origin (header set unchanged). */
656
- get isA2aHop(): boolean;
657
- /** The captured inbound session id, or undefined when none was propagated. */
658
- get sessionId(): string | undefined;
659
- /** Advisory inbound hop depth captured from x-shashu-hop-depth (0 if absent). */
660
- get inboundHopDepth(): number;
661
- /** Hop depth to advertise on the next downstream call = inbound + 1 (advisory; the
662
- * gateway recounts authoritatively). */
663
- get outboundHopDepth(): number;
664
- /** The captured inbound x-shashu-caller-agent-id — the upstream agent that INVOKED
665
- * this hop. The SDK FORWARDS this on the outbound gateway call so the gateway records
666
- * the real (invoker -> this agent) edge, NEVER this agent's own id (§4.1). undefined at
667
- * origin / caller-stripped. */
668
- get inboundCallerAgentId(): string | undefined;
669
- /**
670
- * Capture an inbound flow from the headers of a request this agent is SERVING into the
671
- * AsyncLocalStorage store, so a downstream call made through the SDK propagates the SAME
672
- * flow (WP-A2A-4 / ADR-007 §0). Reads (case-insensitively) x-shashu-trace-id (the flow
673
- * id), -session-id, -hop-depth, and -caller-agent-id (the upstream INVOKER). The captured
674
- * trace is PROPAGATED on the next outbound call (never re-minted); the session, inbound hop
675
- * depth, and inbound caller ride along — the caller is FORWARDED on the gateway call (§4.1),
676
- * never replaced by self.
677
- *
678
- * Uses enterWith, so the capture persists for the remainder of the current async execution
679
- * (one-shot, for a script serving a single inbound call). Servers handling many requests
680
- * should prefer {@link incoming} so one flow's lineage never leaks into the next. No inbound
681
- * trace ⇒ origin: the ambient capture is cleared and false is returned (non-A2A unaffected).
682
- * Never throws — telemetry must not break a request.
683
- */
684
- captureIncoming(headers: unknown): boolean;
685
- /**
686
- * Scoped inbound capture: capture for the duration of serving ONE request, then restore
687
- * the prior context on exit — so a long-lived worker does not leak one flow's lineage into
688
- * the next. Prefer this in servers; {@link captureIncoming} is the one-shot for scripts.
689
- *
690
- * @example
691
- * await tracer.incoming(req.headers, async () => {
692
- * await tg.fetch("/v1/chat/completions", { ... }); // propagates the captured flow
693
- * });
694
- */
695
- incoming<T>(headers: unknown, callback: () => T): T;
696
- /**
697
- * Wraps a callback in a new Span Context.
698
- * Automatically handles Header injection for any internal calls.
699
- */
700
- span<T>(name: string, callback: (spanId: string) => Promise<T>, metadata?: Record<string, unknown>): Promise<T>;
701
- private record;
702
- flush(): Promise<void>;
703
- }
704
- declare const tracer: Tracer;
705
- /**
706
- * Module-level convenience for {@link Tracer.captureIncoming} on the global tracer
707
- * (WP-A2A-4 / ADR-007 §0). Call at the start of serving an inbound request so a
708
- * downstream call made through the SDK propagates the same flow:
709
- *
710
- * import { captureIncoming } from "@shashu-ai/sdk";
711
- * captureIncoming(req.headers); // this agent is now mid-flow
712
- * await tg.fetch("/v1/chat/completions", { ... }); // propagates trace + lineage
713
- *
714
- * Returns true if a trace was captured (mid-flow hop), false at origin.
715
- */
716
- declare function captureIncoming(headers: unknown): boolean;
717
-
718
- /**
719
- * Returns a pre-formatted JSON object of headers for use in n8n "HTTP Request" nodes.
720
- * Header keys are lowercase for gateway parity. Includes Shashu auth and workflow
721
- * context (workflow_id, execution_id, source, x-shashu-source-tool JSON).
722
- *
723
- * Resolution order: (1) arguments apiKey/baseUrl, (2) tracer.configure() values, (3) process.env.
724
- * When tracer.isActive, context headers include x-shashu-trace-id, x-shashu-span-id,
725
- * and x-shashu-parent-id so the n8n workflow appears as a child of the current span.
726
- *
727
- * Use in n8n:
728
- * 1. Add an "HTTP Request" node.
729
- * 2. In "Send Headers" (or equivalent), use the returned `headers` array
730
- * or paste the `json` string into a "JSON" header configuration.
731
- *
732
- * @param apiKey - Optional Shashu API key (Priority 1; else tracer.apiKey, else env).
733
- * @param baseUrl - Optional gateway base URL (Priority 1; else tracer.gatewayUrl, else env).
734
- * @returns Headers as name/value list and as a JSON string for n8n.
735
- */
736
- declare function getN8nHeaderSnippet(apiKey?: string, baseUrl?: string): N8nHeaderSnippet;
737
-
738
- declare const MEMORY_SOURCES: readonly ["sdk", "manual", "langchain", "llamaindex", "tool", "otel", "n8n", "provider", "hosted", "other"];
739
- declare const MEMORY_SCOPES: readonly ["agent", "crew", "tenant"];
740
- interface DeclareMemoryOptions {
741
- store: string;
742
- scope?: (typeof MEMORY_SCOPES)[number];
743
- source?: (typeof MEMORY_SOURCES)[number];
744
- }
745
- declare function declareMemory(items: unknown, options: DeclareMemoryOptions): void;
746
- declare function memoryScope<T>(items: unknown, options: DeclareMemoryOptions, fn: () => T | Promise<T>): Promise<T>;
747
-
748
- export { type A2ACapture, Audit, type AuditConversation, type AuditEventInput, type AuditEventResult, type AuditVerdict, BLOCK_ENCODING_HEADER, CONTRACT_VERSION_HEADER, DEFAULT_BLOCK_ENCODING, DEFAULT_CONTRACT_VERSION, Decision, type DeclareMemoryOptions, FetchLike, HEADER_PREFIX, type InvocationHeaderOptions, MemoryActivity, MemoryWriteBlocked, N8nHeaderSnippet, PASS_CODES, PASS_EXPIRED, PASS_NOT_LICENSED, PASS_PROVIDER_NOT_SET_UP, PASS_UNKNOWN_AGENT, PASS_WRONG_AUDIENCE, PASS_WRONG_ISSUER, type PassRefusalCode, RequestOptions, SOURCE_TOOL_HEADER, Shashu, ShashuAuthenticationError, ShashuBadRequestError, ShashuBudgetExceededError, ShashuConfig, ShashuConfigError, ShashuContentFilterError, ShashuContextWindowExceeded, ShashuError, ShashuPermissionError, ShashuPolicyViolation, ShashuProviderError, ShashuRateLimitError, TRUSTLOG_HEADER_PREFIX, WorkflowContext, buildContextHeaders, buildInvocationHeaders, buildSourceToolJson, captureIncoming, declareMemory, gatewayRetryAfter, getN8nHeaderSnippet, getWorkflowContextFromEnv, memoryScope, parseRetryAfter, raiseForResponse, raiseIfContentFiltered, shashuFetch, tracer };