@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/CHANGELOG.md CHANGED
@@ -1,10 +1,40 @@
1
1
  # Changelog
2
2
 
3
- All notable changes to SHASHU by Trustgate AI (Node.js SDK, `@shashu-ai/sdk`) are
3
+ All notable changes to SHASHU (Node.js SDK, `@shashu-ai/sdk`) are
4
4
  documented here. This project adheres to [Semantic Versioning](https://semver.org/).
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [1.3.0] — 2026-11-27
9
+
10
+ Changed: trace ids the SDK creates are now the 32-character standard form
11
+ (lowercase hex, no dashes), the form the gateway stores, so an id you read from
12
+ the SDK finds the same trace in SHASHU. A trace id you pass in is still sent
13
+ unchanged.
14
+
15
+ Fixed: the SDK installs next to the Vercel AI SDK (`ai`) 6 and 7. It still works
16
+ with 3, 4 and 5.
17
+
18
+ Fixed: `fetchStream` no longer warns that streaming is unsupported. The gateway
19
+ streams; the README's "Streaming (SSE)" section says how.
20
+
21
+ Docs: "One trace for a run of calls" explains how to keep several calls in one
22
+ trace with `tracer.span()`. Calls outside a span still get a trace each.
23
+
24
+ ## [1.2.0] — 2026-11-26
25
+
26
+ BREAKING: framework state keys are now `shashu_session_id` / `shashu_trace_id`.
27
+ The previous names are not read.
28
+
29
+ Provider pass-through errors are recognised by `SHASHU Provider Error:` (needs a
30
+ gateway that sends it). There is no fallback to the previous prefix.
31
+
32
+ SHASHU keys start `shashu_sk_`. Metadata, docs, and package URLs no longer
33
+ carry the previous product name.
34
+
35
+ Fixed: after a request has been sent, a dropped connection is
36
+ no longer retried automatically (avoids running the same request twice).
37
+
8
38
  ## [1.1.1] — 2026-11-25
9
39
 
10
40
  Fixed: when the gateway was busy and the SDK retried, the retry could be sent
@@ -22,8 +52,8 @@ The one-shot `pass_expired` retry is unchanged and does not stack with busy-retr
22
52
 
23
53
  ### Breaking
24
54
 
25
- - Environment variables are `SHASHU_API_KEY` / `SHASHU_BASE_URL` / `SHASHU_DISABLE` only. The `TRUSTGATE_*` fallbacks are removed.
26
- - Wire names are SHASHU only (`x-shashu-*`, `Shashu-Version`, `shashu_metadata`, body `shashu` / `error.shashu`). Old TrustGate names are neither sent nor read.
55
+ - Environment variables are `SHASHU_API_KEY` / `SHASHU_BASE_URL` / `SHASHU_DISABLE` only. The old environment-variable names are no longer read.
56
+ - Wire names are SHASHU only (`x-shashu-*`, `Shashu-Version`, `shashu_metadata`, body `shashu` / `error.shashu`). Old wire names are neither sent nor read.
27
57
 
28
58
  ## [1.0.0] — 2026-11-14
29
59
 
@@ -63,20 +93,20 @@ paste-once header list (key only).
63
93
  ### Changed: package name, licence, env, public names
64
94
 
65
95
  Package is `@shashu-ai/sdk`, version `1.0.0`, Apache-2.0.
66
- Environment variables are `SHASHU_*` first, then `TRUSTGATE_*` (warn once).
96
+ Environment variables are `SHASHU_*` first, then `shashu_*` (warn once).
67
97
  Public type, function and exception names are SHASHU (`Shashu`, `ShashuError`,
68
- `shashuFetch`, `createShashuLangChainConfig`, …). Wire names (`x-trustgate-*`,
69
- `trustgate_metadata`, `tg_sk_`) are unchanged.
98
+ `shashuFetch`, `createShashuLangChainConfig`, …). Wire names (`x-shashu-*`,
99
+ `shashu_metadata`, `tg_sk_`) are unchanged.
70
100
 
71
101
  ## [4.0.0] — unreleased
72
102
 
73
103
  One behaviour change, plus everything merged since `3.0.1`. Read the first
74
104
  section before upgrading.
75
105
 
76
- ### Behaviour change: `trustgate-version: 2026-09-01` is sent by default
106
+ ### Behaviour change: `shashu-version: 2026-09-01` is sent by default
77
107
 
78
- Every request this SDK makes now carries `trustgate-version: 2026-09-01`, the
79
- same value the Trustgate AI Python SDK has sent since `0.15.2`. That covers the
108
+ Every request this SDK makes now carries `shashu-version: 2026-09-01`, the
109
+ same value the shashu AI Python SDK has sent since `0.15.2`. That covers the
80
110
  `Shashu` client (`fetch` and `fetchStream`), `shashuFetch()`, and the
81
111
  headers built by the Anthropic, Gemini, LangChain and Vercel AI middleware.
82
112
 
@@ -106,12 +136,12 @@ it:
106
136
  LangChain, Anthropic, Gemini) now raises its own 400 or 403 error on a
107
137
  refusal (`BadRequestError`, `PermissionDeniedError`, …). Under `legacy` it
108
138
  returned the refusal as an ordinary 200 reply. The
109
- `trustgate-block-encoding: explicit` header `shashuFetch()` already sent
139
+ `shashu-block-encoding: explicit` header `shashuFetch()` already sent
110
140
  now takes effect, because the gateway ignores it without a version.
111
141
  - **Full memory and inspection details are in the body.** A reply carries the
112
- `trustgate` block, so `decision.memory.items` lists each memory save and
142
+ `shashu` block, so `decision.memory.items` lists each memory save and
113
143
  recall (`kind`, `state`, `reason`, `tool`, `store`, …). Before, a flagged
114
- save under Monitor was counted in `x-trustgate-memory` but not listed.
144
+ save under Monitor was counted in `x-shashu-memory` but not listed.
115
145
  `decision.memory.carrier` is now `"body"`.
116
146
  - **Unchanged by design:** under Block mode, a memory save the gateway strips
117
147
  from a reply is still a normal delivered reply, with `memoryBlocked === 1`
@@ -119,9 +149,9 @@ it:
119
149
 
120
150
  **To turn it off**, pass `contractVersion: null` to `new Shashu({...})`,
121
151
  `shashuFetch({...})` or any middleware config. The SDK then sends no
122
- `trustgate-version` header and the gateway serves the account default,
152
+ `shashu-version` header and the gateway serves the account default,
123
153
  `legacy` unless an operator changed it. Pass `contractVersion: "<date>"` to pin
124
- another version. A `trustgate-version` entry you put in `headers` yourself
154
+ another version. A `shashu-version` entry you put in `headers` yourself
125
155
  always wins.
126
156
 
127
157
  New public names: `DEFAULT_CONTRACT_VERSION`, `CONTRACT_VERSION_HEADER`, and
@@ -142,7 +172,7 @@ memory checks can run on them.
142
172
  - `store` is required. `scope` is `agent` (default), `crew` or `tenant`.
143
173
  `source` is one of the `memory_context.v1` values (default `sdk`). Anything
144
174
  else throws `TypeError`.
145
- - A no-op under `TRUSTGATE_DISABLE`. No collectors are included: a framework's
175
+ - A no-op under `shashu_DISABLE`. No collectors are included: a framework's
146
176
  memory is not captured automatically.
147
177
 
148
178
  ### Added: reading file, memory and route-policy results (FILE-06)
@@ -152,7 +182,7 @@ route-policy block (`contracts/decision-envelope.v1.md`, contract
152
182
  `2026-10-01`). They are readable, read-only, off the decision:
153
183
 
154
184
  - **Files** — `d.attachments`, `d.filesUnverified`, `d.filesBlocked`. Body first; on a header-only (streaming) response the
155
- counts come from `x-trustgate-attachments` and `attachments.carrier` says
185
+ counts come from `x-shashu-attachments` and `attachments.carrier` says
156
186
  `"header"`. `files_unverified` is `not_inspected + scanned_partial`.
157
187
  - **Memory** — `d.memory`, `d.memoryBlocked`, `d.memoryRecallsFlagged`, `d.memoryCoverage`.
158
188
  - **Route policy** — `d.routePolicy`, and `err.routePolicy` on the refusal, so an app can
@@ -213,7 +243,7 @@ the middleware path.
213
243
 
214
244
  ### Upgrading from 1.8.0: session limits can start firing, with no change on your side
215
245
 
216
- **`new Shashu()` traffic now carries a client-sent `x-trustgate-session-id`.**
246
+ **`new Shashu()` traffic now carries a client-sent `x-shashu-session-id`.**
217
247
  Until now it carried none, and the gateway filled in a derived id for display
218
248
  only. The gateway's session-window scan and per-session scan budget act only
219
249
  on a client-sent session id. From `3.0.0` they do. An application you have not
@@ -224,7 +254,7 @@ session. A long-lived client shared across users must pass a per-request
224
254
 
225
255
  ### Added — session at origin, the gateway's decision, `isShashuBlock`
226
256
 
227
- The constructed client now sends `x-trustgate-session-id` on every request,
257
+ The constructed client now sends `x-shashu-session-id` on every request,
228
258
  including at origin. One client is one session; a captured A2A session
229
259
  overrides the construction-time default; a per-request `sessionId` is an
230
260
  instruction that wins. Without this header the gateway synthesises
@@ -233,7 +263,7 @@ first message is a static system prompt collapses into one Sessions row.
233
263
 
234
264
  `shashuDecision` / `decisionFrom` read all six outcomes (`allow`,
235
265
  `allow_altered`, `not_checked`, `block`, `refuse`, `fail`) from both
236
- carriers (`body.trustgate` and the `x-trustgate-*` headers). Absence is
266
+ carriers (`body.shashu` and the `x-shashu-*` headers). Absence is
237
267
  today's behaviour: a response with neither carrier is unchanged.
238
268
  `isShashuBlock(err)` inspects an error and answers yes or no. It
239
269
  replaces nothing and fails closed; `raiseForResponse` still fails open as
@@ -314,7 +344,7 @@ the gateway on 2026-09-07 it is one of four:
314
344
  - a §3 **reason** — `jailbreak`, `dlp`, `egress_denied`, `auth_expired`, … — on
315
345
  every path served under contract `2026-09-01`;
316
346
  - the **HTTP status as a string** — still live, and still the default: an
317
- account that sets no `TrustGate-Version` is served `legacy`, and every refusal
347
+ account that sets no `SHASHU-Version` is served `legacy`, and every refusal
318
348
  the gateway's `HTTPException` handler renders carries `str(status_code)`
319
349
  whatever the version;
320
350
  - the literal `"invalid_request"`, on a schema-invalid body on the LLM wire;
@@ -390,7 +420,7 @@ awaited.
390
420
 
391
421
  `declareRetrieval(docs, { corpus, query })` records what a retrieval returned
392
422
  wherever it happened, and the SDK attaches it to the next model call as
393
- `trustgate_metadata.rag_context`. `retrievalScope()` bounds one declaration to a
423
+ `shashu_metadata.rag_context`. `retrievalScope()` bounds one declaration to a
394
424
  block, including a `Promise.all` fan-out where each task declares before its
395
425
  first `await`. The contract
396
426
  (`contracts/rag_context.v1.schema.json`) is vendored byte-for-byte from the
@@ -458,7 +488,7 @@ adding protection is a separate change.
458
488
  > `DEFAULT_GATEWAY_URL` export that held that host is gone.
459
489
 
460
490
  Sibling of the Python SDK's `b3a92fb`, which made the same change there. The
461
- Python `trustgate/_config.py` is the reference this implementation matches,
491
+ Python `shashu/_config.py` is the reference this implementation matches,
462
492
  down to the error wording.
463
493
 
464
494
  ### Removed — the default gateway host, at all seven sites
@@ -483,7 +513,7 @@ than six copies of the same expression that had already drifted — only the
483
513
  client guarded `typeof process !== "undefined"`; the other five would throw in
484
514
  an edge runtime. Resolution is now, everywhere:
485
515
 
486
- **explicit `baseUrl` option → `TRUSTGATE_BASE_URL` → `ShashuConfigError`.**
516
+ **explicit `baseUrl` option → `shashu_BASE_URL` → `ShashuConfigError`.**
487
517
 
488
518
  A blank or whitespace-only env var counts as unset. Trailing slashes are still
489
519
  stripped.
@@ -501,12 +531,12 @@ dead code. The behaviour change above is breaking on its own, so removing the
501
531
  export costs no additional version increment.
502
532
 
503
533
  If you were importing it, replace it with your own gateway address — passed as
504
- `baseUrl` or set as `TRUSTGATE_BASE_URL`.
534
+ `baseUrl` or set as `shashu_BASE_URL`.
505
535
 
506
536
  ### Added — `ShashuConfigError`
507
537
 
508
538
  ```ts
509
- import { ShashuConfigError } from '@trustgateai/sdk';
539
+ import { ShashuConfigError } from '@shashu-ai/sdk';
510
540
  ```
511
541
 
512
542
  A `ShashuError` subclass, so existing `catch (e) { e instanceof ShashuError }`
@@ -518,9 +548,9 @@ statement that nothing was sent.
518
548
  Its message names the environment variable, the option and the entry point, and
519
549
  deliberately names **no hostname**: there is no address to suggest.
520
550
 
521
- ### Added — `TRUSTGATE_DISABLE`
551
+ ### Added — `shashu_DISABLE`
522
552
 
523
- Set `TRUSTGATE_DISABLE=1` (or `true` / `yes` / `on`, any case) to make the SDK a
553
+ Set `shashu_DISABLE=1` (or `true` / `yes` / `on`, any case) to make the SDK a
524
554
  no-op without a code change, matching the Python SDK. The four middleware
525
555
  helpers then return `{}` and throw nothing even with no address configured —
526
556
  your provider client keeps its own endpoint, its own credential and no Shashu
@@ -541,7 +571,7 @@ return types, because `{}` is what a disabled SDK returns. Code that read
541
571
 
542
572
  The tracer resolves its address **optionally**, unlike every other entry point.
543
573
  It is constructed when the module is imported (`export const tracer = new Tracer()`),
544
- so throwing there would make `import '@trustgateai/sdk'` fail for anyone who has
574
+ so throwing there would make `import '@shashu-ai/sdk'` fail for anyone who has
545
575
  not set the variable — a far worse failure than the one being fixed. Unconfigured,
546
576
  it holds no address and posts no span telemetry. Same shape as the Python SDK's
547
577
  telemetry path.
@@ -576,7 +606,7 @@ _[If you built against the old behaviour](#if-you-built-against-the-old-behaviou
576
606
  below.
577
607
 
578
608
  Error-contract corrections. Everything below was verified against
579
- `sdks/e2e/capture_error_contract.py` in the trustgate-ai repo, which drives a
609
+ `sdks/e2e/capture_error_contract.py` in the gateway repo, which drives a
580
610
  live gateway and records what it actually sends. Nothing here is asserted from
581
611
  reading gateway source. Sibling of the Python SDK 0.10.0 change.
582
612
 
@@ -642,18 +672,18 @@ exported and still extends `ShashuPermissionError`, so imports and
642
672
  nothing throws it any more. Code that checks _only_ for the budget subclass will
643
673
  now see `ShashuPolicyViolation`. Check the parent to cover both. The class
644
674
  becomes reachable again if the gateway ships a real discriminator (ticket
645
- [`TRUSTGATE-403-DISCRIMINATOR`](https://github.com/aisquad001/trustgate-ai/issues/736)).
675
+ [`the 403 discriminator ticket`](https://the gateway repository/issues/736)).
646
676
 
647
677
  ### Fixed — a 401 was documented as the gateway's own auth failure
648
678
 
649
679
  The module header mapped `401 -> type="authentication_error"`. That is backwards.
650
680
  The gateway's own agent-key failure sends `type="invalid_request_error"` with
651
- message `"Invalid TrustGate API Key"` (or `"Not authenticated"`, plus a
681
+ message `"Invalid SHASHU API Key"` (or `"Not authenticated"`, plus a
652
682
  `WWW-Authenticate: Bearer` header). Both captured.
653
683
 
654
684
  `authentication_error` is what a **provider pass-through** carries: the gateway's
655
685
  own stored provider credential was rejected upstream, and the message is prefixed
656
- `TrustGate Provider Error:`. The caller's `tg_sk_` key is fine in that case and
686
+ `SHASHU Provider Error:`. The caller's `tg_sk_` key is fine in that case and
657
687
  rotating it fixes nothing — a gateway operator has to replace the provider
658
688
  secret. The old header pointed every reader at the wrong credential. The same
659
689
  applies to 403 (`ProviderPermissionError`), 404, 429 and the 5xx family.
@@ -771,7 +801,7 @@ happens only when the gateway named a time to come back, via the newly exported
771
801
 
772
802
  **5. A 401 does not mean your API key is wrong.** The module header mapped
773
803
  `401 -> type="authentication_error"`; backwards. Your own key failing sends
774
- `type="invalid_request_error"` with `"Invalid TrustGate API Key"`.
804
+ `type="invalid_request_error"` with `"Invalid SHASHU API Key"`.
775
805
  `authentication_error` means the **gateway's stored provider credential** was
776
806
  rejected upstream — rotating your `tg_sk_` key fixes nothing, an operator has to
777
807
  replace the provider secret. Use the new
@@ -784,17 +814,17 @@ receives is unconsumed. Covered by a test.
784
814
 
785
815
  ## [1.7.2] — 2026-07-30
786
816
 
787
- Wire-parity fixes vs the Python SDK reference (`trustgate` `context.py`).
817
+ Wire-parity fixes vs the Python SDK reference (`shashu` `context.py`).
788
818
 
789
819
  ### Fixed
790
820
 
791
- - **`x-trustgate-parent-id` no longer equals `x-trustgate-span-id`.** The header
821
+ - **`x-shashu-parent-id` no longer equals `x-shashu-span-id`.** The header
792
822
  block set both to the current span's id, so every span reported itself as its
793
- own parent on the wire. `x-trustgate-parent-id` now carries the REAL parent
823
+ own parent on the wire. `x-shashu-parent-id` now carries the REAL parent
794
824
  span id via the new `tracer.parentSpanId` getter — `""` for a root span
795
825
  (Python parity).
796
826
  - **A trace id is now ALWAYS emitted at origin.** With no active span and no
797
- captured A2A flow, no `x-trustgate-trace-id` was emitted at all. Origin now
827
+ captured A2A flow, no `x-shashu-trace-id` was emitted at all. Origin now
798
828
  resolves one mirroring Python `_get_trace_id()`: `N8N_EXECUTION_ID` →
799
829
  `GITHUB_RUN_ID` → `CI_PIPELINE_ID` (when `GITLAB_CI` is set) → a fresh UUID.
800
830
  The mid-flow (`isA2aHop`) and in-span branches are unchanged.
@@ -827,19 +857,19 @@ locked ADR-007 §4.1 caller semantics.
827
857
  request, capture the inbound flow so a downstream call through the SDK PROPAGATES
828
858
  it (one lineage / one session across hops) instead of minting a fresh trace per process.
829
859
  - `captureIncoming(headers)` and the scoped `tracer.incoming(headers, fn)` read
830
- `x-trustgate-trace-id` / `-session-id` / `-hop-depth` **and `-caller-agent-id`**
860
+ `x-shashu-trace-id` / `-session-id` / `-hop-depth` **and `-caller-agent-id`**
831
861
  (the upstream invoker) into the `AsyncLocalStorage` tracer (case-insensitive;
832
862
  plain objects, `Headers`, `Map`, or pair-arrays).
833
863
  - The outbound **gateway** call propagates the captured trace (minted only at
834
- origin), and attaches `x-trustgate-session-id`, `x-trustgate-hop-depth` (inbound+1),
835
- and `x-trustgate-caller-agent-id` = **the FORWARDED inbound caller** — the upstream
864
+ origin), and attaches `x-shashu-session-id`, `x-shashu-hop-depth` (inbound+1),
865
+ and `x-shashu-caller-agent-id` = **the FORWARDED inbound caller** — the upstream
836
866
  invoker, NEVER this agent's own id (so the gateway records the real invoker→callee
837
867
  edge, not a self-edge). Origin / caller-stripped ⇒ the caller header is omitted.
838
868
  - `buildInvocationHeaders({ callerAgentId })` (and `Shashu.buildInvocationHeaders()`,
839
869
  which uses the client's cached self-id) build the lineage headers for the **invoking**
840
870
  side — the one place caller = self: the message this agent sends to a downstream agent.
841
871
  - `Shashu` gained an `agentId` option; the client caches this agent's id from each
842
- gateway response's `x-trustgate-agent-id` header (incl. 4xx) for use as the invocation caller.
872
+ gateway response's `x-shashu-agent-id` header (incl. 4xx) for use as the invocation caller.
843
873
 
844
874
  ### Notes
845
875
 
@@ -887,7 +917,7 @@ Mirrors the Python SDK v0.8.0 (typed exceptions + conservative retries).
887
917
  - **403 budget-vs-policy split is best-effort** (matches `/budget/i` in the
888
918
  message) because every soft-block 403 shares
889
919
  `{type:"invalid_request_error", code:"403"}`. Replaced once the gateway emits a
890
- stable discriminator (ticket `TRUSTGATE-403-DISCRIMINATOR`).
920
+ stable discriminator (ticket `the 403 discriminator ticket`).
891
921
  - Streaming (`fetchStream`) remains inert against the current gateway (it
892
922
  force-buffers chat responses and emits no chat SSE regardless of the `stream`
893
923
  flag or DLP settings). `fetchStream` now carries a NOTICE in its docstring and
package/NOTICE CHANGED
@@ -1,4 +1,4 @@
1
- SHASHU by Trustgate AI
1
+ SHASHU
2
2
  Copyright 2026 Trustgate AI LLC
3
3
 
4
4
  This product includes software developed by Trustgate AI LLC.
package/README.md CHANGED
@@ -1,11 +1,11 @@
1
1
  # @shashu-ai/sdk
2
2
 
3
- Node.js client for **SHASHU by Trustgate AI**, a self-hosted AI security gateway for
3
+ Node.js client for **SHASHU**, a self-hosted AI security gateway for
4
4
  regulated industries. There is no default gateway hostname — you point the
5
5
  client at your own address, and it raises a configuration error rather than
6
6
  guessing. After the first mention, this document says **SHASHU**.
7
7
 
8
- Wire names `x-shashu-*`, `shashu_metadata`, and the `tg_sk_` key prefix
8
+ Wire names `x-shashu-*`, `shashu_metadata`, and the `shashu_sk_` key prefix
9
9
  are protocol names and are unchanged.
10
10
 
11
11
  Requires Node.js 18 or later.
@@ -34,7 +34,10 @@ Key:
34
34
 
35
35
  ```ts
36
36
  import { Shashu } from '@shashu-ai/sdk';
37
- const client = new Shashu({ baseUrl: 'https://your-shashu-gateway.example', apiKey: 'tg_sk_...' });
37
+ const client = new Shashu({
38
+ baseUrl: 'https://your-shashu-gateway.example',
39
+ apiKey: 'shashu_sk_...',
40
+ });
38
41
  ```
39
42
 
40
43
  Cloud pass (the function is yours; SHASHU never calls Entra, Google or AWS):
@@ -86,12 +89,12 @@ const res = await client.fetch('/v1/chat/completions', {
86
89
  body: JSON.stringify({ model: 'gpt-4', messages: [...] }),
87
90
  });
88
91
 
89
- // SSE streaming (workflow_id sent in request for background attribution)
92
+ // Streaming (server-sent events)
90
93
  const streamRes = await client.fetchStream('/v1/chat/completions', {
91
94
  method: 'POST',
92
95
  body: JSON.stringify({ model: 'gpt-4', messages: [...], stream: true }),
93
96
  });
94
- // Consume streamRes.body (ReadableStream) as usual for SSE
97
+ // Read streamRes.body (a ReadableStream of SSE events) as usual
95
98
  ```
96
99
 
97
100
  ## Configuring the gateway address
@@ -178,7 +181,7 @@ gateway did not send a decision — that is not `allow`. `isShashuBlock()`
178
181
  inspects; it patches nothing. An unrecognised decision fails closed (`true`).
179
182
 
180
183
  **This SDK sends `shashu-version: 2026-09-01` by default** (since 4.0.0), the
181
- same value as the Trustgate AI Python SDK. The `Shashu` client,
184
+ same value as the shashu AI Python SDK. The `Shashu` client,
182
185
  `shashuFetch()` and the middleware configs all send it. With it, the body of
183
186
  every reply carries the full `shashu` block, so `decision.memory.items` lists
184
187
  each memory save and recall and you get the inspection detail, not just header
@@ -210,9 +213,28 @@ const ctx = getWorkflowContextFromEnv();
210
213
  // { source: 'n8n', workflow_id: '...', execution_id: '...', metadata: {...} }
211
214
  ```
212
215
 
216
+ ## One trace for a run of calls
217
+
218
+ Each call made outside a span starts its own trace. To keep a run of calls (a
219
+ conversation, an agent run) in one trace, make them inside `tracer.span()`:
220
+
221
+ ```ts
222
+ import { tracer } from '@shashu-ai/sdk';
223
+
224
+ await tracer.span('support-conversation', async () => {
225
+ await client.fetch('/v1/chat/completions', { method: 'POST', body: turn1 });
226
+ await client.fetch('/v1/chat/completions', { method: 'POST', body: turn2 });
227
+ });
228
+ ```
229
+
230
+ Every call inside the callback sends the same `x-shashu-trace-id`. Trace ids the
231
+ SDK creates are 32 lowercase hex characters. A trace id you bring in, for
232
+ example from an incoming request with `tracer.incoming(headers, () => ...)`, is
233
+ sent unchanged.
234
+
213
235
  ## Middleware: Vercel AI SDK
214
236
 
215
- Point the OpenAI provider at Shashu so all calls go through the gateway with workflow context:
237
+ Works with the Vercel AI SDK (`ai`) 3 to 7. Point the OpenAI provider at Shashu so all calls go through the gateway with workflow context:
216
238
 
217
239
  ```ts
218
240
  import { createOpenAI } from '@ai-sdk/openai';
@@ -378,8 +400,20 @@ In n8n, set **Send Headers** (or equivalent) to the `headers` array or paste the
378
400
 
379
401
  ## Streaming (SSE)
380
402
 
381
- - Use `client.fetchStream(path, init, options)` for SSE endpoints. The client sets `Accept: text/event-stream` and sends workflow context (e.g. `workflow_id`) in the **initial request**, so the gateway can attribute the background stream.
382
- - The returned `Response` body is the raw stream; consume it with `response.body.getReader()` or pass through to your framework’s SSE handling.
403
+ Send `stream: true` in the body and call `client.fetchStream(path, init, options)`.
404
+ The gateway streams the answer back as server-sent events in the chat streaming
405
+ format; read `response.body` with `getReader()` or hand it to your framework.
406
+
407
+ - **Checked first, then streamed.** The gateway inspects the whole answer before
408
+ any of it reaches you, then sends it as a stream of events. The events arrive
409
+ one by one, but the first one arrives only after the model has finished.
410
+ - **A security block is an error, not a broken stream.** Whether the gateway
411
+ blocks the request (for example an injected prompt) or the answer (for
412
+ example a leaked secret), it answers with an error before any event, and
413
+ `fetchStream` throws the typed exception, as `fetch` does:
414
+ `ShashuContentFilterError` (400) or `ShashuPolicyViolation` (403).
415
+ - A refused pass is retried once, before anything is read. A stream is never
416
+ re-sent once it has started.
383
417
 
384
418
  ## License
385
419
 
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@shashu-ai/sdk",
3
3
  "type": "module",
4
- "version": "1.1.1",
5
- "description": "Node.js client for SHASHU by Trustgate AI, a self-hosted AI security gateway. Point it at your own gateway; there is no default endpoint.",
4
+ "version": "1.3.0",
5
+ "description": "Node.js client for SHASHU, a self-hosted AI security gateway. Point it at your own gateway; there is no default endpoint.",
6
6
  "main": "dist/index.cjs",
7
7
  "module": "dist/index.js",
8
8
  "types": "dist/index.d.ts",
@@ -51,7 +51,6 @@
51
51
  },
52
52
  "keywords": [
53
53
  "shashu",
54
- "trustgate",
55
54
  "self-hosted",
56
55
  "ai-gateway",
57
56
  "security",
@@ -65,7 +64,7 @@
65
64
  "homepage": "https://shashu.ai",
66
65
  "repository": {
67
66
  "type": "git",
68
- "url": "https://github.com/trustgateai-io/shashu-node.git"
67
+ "url": "https://github.com/shashu-sec/shashu-node.git"
69
68
  },
70
69
  "devDependencies": {
71
70
  "@ai-sdk/openai": "2.0.66",
@@ -89,7 +88,7 @@
89
88
  "peerDependencies": {
90
89
  "@langchain/core": "^0.3.0 || ^1.0.0",
91
90
  "@langchain/openai": "^0.2.0 || ^1.0.0",
92
- "ai": "^3.0.0 || ^4.0.0 || ^5.0.0"
91
+ "ai": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"
93
92
  },
94
93
  "peerDependenciesMeta": {
95
94
  "ai": {
@@ -1,38 +0,0 @@
1
- /**
2
- * Join the carried retrieval declaration onto the outgoing request.
3
- *
4
- * The Python SDK patches its own httpx transport, so it sees every outgoing
5
- * request whoever made it. Node has no such chokepoint: our own client owns its
6
- * `fetch`, and the middlewares only RETURN a config object the customer hands to
7
- * THEIR SDK. What makes this work is that the OpenAI, Anthropic, LangChain and
8
- * Vercel AI SDKs all accept a `fetch` in exactly that config, so the joiner is
9
- * supplied there and runs inside the provider client. `@google/generative-ai`
10
- * does not (its `RequestOptions` carries `timeout`, `apiVersion`, `apiClient`,
11
- * `baseUrl` and `customHeaders`, and nothing else), so the Gemini path is
12
- * declaration-only -- see `src/middleware/google.ts`.
13
- *
14
- * Four properties it has to hold, in this order:
15
- *
16
- * 1. **Zero cost when nothing was retrieved.** The first thing it does is a
17
- * single `AsyncLocalStorage.getStore()`. With an empty bus it forwards the
18
- * caller's own `input` and `init` OBJECT REFERENCES untouched, so the bytes
19
- * on the wire are the bytes the unwrapped client produced -- asserted by
20
- * reference identity in `test/joiner.test.ts`.
21
- * 2. **Explicit always wins.** A body already carrying
22
- * `shashu_metadata.rag_context` is left exactly as the caller built it.
23
- * The ambient declaration is consumed and discarded, not deferred: a
24
- * declaration that lost this call must not turn up on the next one.
25
- * 3. **Snapshot and clear.** The bus is emptied the moment it is written to a
26
- * request. Retrieval declared for request N never reaches request N+1.
27
- * 4. **Never corrupt a body it does not understand.** A non-JSON body, a
28
- * non-object JSON body, or a stream upload is passed through untouched and
29
- * does NOT consume the bus -- the next real model call still carries the
30
- * declaration, and a multi-gigabyte file upload does not eat it.
31
- *
32
- * Sibling of the Python SDK's `trustgate/_joiner.py`.
33
- */
34
- /** The `fetch` shape every provider SDK's option accepts. */
35
- type FetchLike = (input: any, init?: any) => Promise<Response>;
36
- declare function withRetrievalJoiner(underlying?: FetchLike): FetchLike;
37
-
38
- export { type FetchLike as F, withRetrievalJoiner as w };
@@ -1,38 +0,0 @@
1
- /**
2
- * Join the carried retrieval declaration onto the outgoing request.
3
- *
4
- * The Python SDK patches its own httpx transport, so it sees every outgoing
5
- * request whoever made it. Node has no such chokepoint: our own client owns its
6
- * `fetch`, and the middlewares only RETURN a config object the customer hands to
7
- * THEIR SDK. What makes this work is that the OpenAI, Anthropic, LangChain and
8
- * Vercel AI SDKs all accept a `fetch` in exactly that config, so the joiner is
9
- * supplied there and runs inside the provider client. `@google/generative-ai`
10
- * does not (its `RequestOptions` carries `timeout`, `apiVersion`, `apiClient`,
11
- * `baseUrl` and `customHeaders`, and nothing else), so the Gemini path is
12
- * declaration-only -- see `src/middleware/google.ts`.
13
- *
14
- * Four properties it has to hold, in this order:
15
- *
16
- * 1. **Zero cost when nothing was retrieved.** The first thing it does is a
17
- * single `AsyncLocalStorage.getStore()`. With an empty bus it forwards the
18
- * caller's own `input` and `init` OBJECT REFERENCES untouched, so the bytes
19
- * on the wire are the bytes the unwrapped client produced -- asserted by
20
- * reference identity in `test/joiner.test.ts`.
21
- * 2. **Explicit always wins.** A body already carrying
22
- * `shashu_metadata.rag_context` is left exactly as the caller built it.
23
- * The ambient declaration is consumed and discarded, not deferred: a
24
- * declaration that lost this call must not turn up on the next one.
25
- * 3. **Snapshot and clear.** The bus is emptied the moment it is written to a
26
- * request. Retrieval declared for request N never reaches request N+1.
27
- * 4. **Never corrupt a body it does not understand.** A non-JSON body, a
28
- * non-object JSON body, or a stream upload is passed through untouched and
29
- * does NOT consume the bus -- the next real model call still carries the
30
- * declaration, and a multi-gigabyte file upload does not eat it.
31
- *
32
- * Sibling of the Python SDK's `trustgate/_joiner.py`.
33
- */
34
- /** The `fetch` shape every provider SDK's option accepts. */
35
- type FetchLike = (input: any, init?: any) => Promise<Response>;
36
- declare function withRetrievalJoiner(underlying?: FetchLike): FetchLike;
37
-
38
- export { type FetchLike as F, withRetrievalJoiner as w };
@@ -1,74 +0,0 @@
1
- import {
2
- withRetrievalJoiner
3
- } from "./chunk-M7EMWSNS.js";
4
- import {
5
- CredentialResolver,
6
- applyContractVersion,
7
- buildContextHeaders,
8
- getWorkflowContextFromEnv,
9
- isDisabled,
10
- passRefusalCodeFromText,
11
- requireBaseUrl,
12
- shouldRetryPassRefused
13
- } from "./chunk-TGD6KDWT.js";
14
-
15
- // src/middleware/anthropic.ts
16
- import { randomUUID } from "crypto";
17
- function getAnthropicHeaders(config) {
18
- const ctx = config.workflowContext ?? getWorkflowContextFromEnv();
19
- const headers = {
20
- ...config.headers,
21
- ...buildContextHeaders(ctx, { defaultSessionId: config.sessionId })
22
- };
23
- if (config.apiKey) {
24
- headers["x-api-key"] = config.apiKey;
25
- }
26
- return applyContractVersion(headers, config.contractVersion);
27
- }
28
- function createShashuAnthropicConfig(config) {
29
- if (isDisabled()) return {};
30
- const baseURL = requireBaseUrl(config.baseUrl, {
31
- entryPoint: "createShashuAnthropicConfig()"
32
- });
33
- const resolver = new CredentialResolver({
34
- apiKey: config.apiKey ?? void 0,
35
- tokenProvider: config.tokenProvider
36
- });
37
- const headers = getAnthropicHeaders({
38
- ...config,
39
- sessionId: config.sessionId ?? randomUUID(),
40
- apiKey: resolver.usesProvider ? void 0 : config.apiKey
41
- });
42
- const joining = withRetrievalJoiner();
43
- const fetch = async (input, init) => {
44
- const token = await resolver.get();
45
- const next = new Headers(init?.headers);
46
- if (token) next.set("x-api-key", token);
47
- const res = await joining(input, { ...init, headers: next });
48
- if (!resolver.usesProvider || res.status !== 401) return res;
49
- const code = passRefusalCodeFromText(await res.clone().text());
50
- if (!shouldRetryPassRefused({
51
- usesProvider: true,
52
- status: res.status,
53
- code,
54
- bytesDelivered: false
55
- })) {
56
- return res;
57
- }
58
- resolver.invalidate();
59
- const retryToken = await resolver.get();
60
- if (retryToken) next.set("x-api-key", retryToken);
61
- return joining(input, { ...init, headers: next });
62
- };
63
- return {
64
- baseURL,
65
- apiKey: resolver.usesProvider ? null : config.apiKey ?? null,
66
- defaultHeaders: Object.keys(headers).length ? headers : void 0,
67
- fetch
68
- };
69
- }
70
-
71
- export {
72
- getAnthropicHeaders,
73
- createShashuAnthropicConfig
74
- };
@@ -1,40 +0,0 @@
1
- import {
2
- applyContractVersion,
3
- buildContextHeaders,
4
- getWorkflowContextFromEnv,
5
- isDisabled,
6
- rejectKeyOnly,
7
- requireBaseUrl
8
- } from "./chunk-TGD6KDWT.js";
9
-
10
- // src/middleware/google.ts
11
- import { randomUUID } from "crypto";
12
- function getGeminiHeaders(config) {
13
- const ctx = config.workflowContext ?? getWorkflowContextFromEnv();
14
- const headers = {
15
- ...config.headers,
16
- ...buildContextHeaders(ctx, { defaultSessionId: config.sessionId })
17
- };
18
- if (config.apiKey) {
19
- headers["x-api-key"] = config.apiKey;
20
- }
21
- return applyContractVersion(headers, config.contractVersion);
22
- }
23
- function createShashuGeminiConfig(config) {
24
- if (isDisabled()) return {};
25
- rejectKeyOnly("createShashuGeminiConfig", config.tokenProvider);
26
- const baseUrl = requireBaseUrl(config.baseUrl, {
27
- entryPoint: "createShashuGeminiConfig()"
28
- });
29
- const headers = getGeminiHeaders({ ...config, sessionId: config.sessionId ?? randomUUID() });
30
- return {
31
- baseUrl,
32
- apiKey: config.apiKey ?? null,
33
- headers: Object.keys(headers).length ? headers : void 0
34
- };
35
- }
36
-
37
- export {
38
- getGeminiHeaders,
39
- createShashuGeminiConfig
40
- };