@shashu-ai/sdk 0.0.0-stage → 1.0.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/LICENSE ADDED
@@ -0,0 +1,142 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Work" shall mean the work of authorship, whether in Source or
27
+ Object form, made available under the License, as indicated by a
28
+ copyright notice that is included in or attached to the work
29
+ (an example is provided in the Appendix below).
30
+
31
+ "Derivative Works" shall mean any work, whether in Source or Object
32
+ form, that is based on (or derived from) the Work and for which the
33
+ editorial revisions, annotations, elaborations, or other modifications
34
+ represent, as a whole, an original work of authorship. For the purposes
35
+ of this License, Derivative Works shall not include works that remain
36
+ separable from, or merely link (or bind by name) to the interfaces of,
37
+ the Work and Derivative Works thereof.
38
+
39
+ "Contribution" shall mean any work of authorship, including
40
+ the original version of the Work and any modifications or additions
41
+ to that Work or Derivative Works thereof, that is intentionally
42
+ submitted to Licensor for inclusion in the Work by the copyright owner
43
+ or by an individual or Legal Entity authorized to submit on behalf of
44
+ the copyright owner.
45
+
46
+ "Contributor" shall mean Licensor and any individual or Legal Entity
47
+ on behalf of whom a Contribution has been received by Licensor and
48
+ subsequently incorporated within the Work.
49
+
50
+ 2. Grant of Copyright License. Subject to the terms and conditions of
51
+ this License, each Contributor hereby grants to You a perpetual,
52
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
53
+ copyright license to reproduce, prepare Derivative Works of,
54
+ publicly display, publicly perform, sublicense, and distribute the
55
+ Work and such Derivative Works in Source or Object form.
56
+
57
+ 3. Grant of Patent License. Subject to the terms and conditions of
58
+ this License, each Contributor hereby grants to You a perpetual,
59
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
60
+ (except as stated in this section) patent license to make, have made,
61
+ use, offer to sell, sell, import, and otherwise transfer the Work,
62
+ where such license applies only to those patent claims licensable
63
+ by such Contributor that are necessarily infringed by their
64
+ Contribution(s) alone or by combination of their Contribution(s)
65
+ with the Work to which such Contribution(s) was submitted.
66
+
67
+ 4. Redistribution. You may reproduce and distribute copies of the
68
+ Work or Derivative Works thereof in any medium, with or without
69
+ modifications, and in Source or Object form, provided that You
70
+ meet the following conditions:
71
+
72
+ (a) You must give any other recipients of the Work or
73
+ Derivative Works a copy of this License; and
74
+
75
+ (b) You must cause any modified files to carry prominent notices
76
+ stating that You changed the files; and
77
+
78
+ (c) You must retain, in the Source form of any Derivative Works
79
+ that You distribute, all copyright, patent, trademark, and
80
+ attribution notices from the Source form of the Work,
81
+ excluding those notices that do not pertain to any part of
82
+ the Derivative Works; and
83
+
84
+ (d) If the Work includes a "NOTICE" text file as part of its
85
+ distribution, then any Derivative Works that You distribute must
86
+ include a readable copy of the attribution notices contained
87
+ within such NOTICE file, excluding those notices that do not
88
+ pertain to any part of the Derivative Works, in at least one
89
+ of the following places: within a NOTICE text file distributed
90
+ as part of the Derivative Works; within the Source form or
91
+ documentation, if provided along with the Derivative Works; or,
92
+ within a display generated by the Derivative Works, if and
93
+ wherever such third-party notices normally appear.
94
+
95
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
96
+ any Contribution intentionally submitted for inclusion in the Work
97
+ by You to the Licensor shall be under the terms and conditions of
98
+ this License, without any additional terms or conditions.
99
+
100
+ 6. Trademarks. This License does not grant permission to use the trade
101
+ names, trademarks, service marks, or product names of the Licensor,
102
+ except as required for reasonable and customary use in describing the
103
+ origin of the Work and reproducing the content of the NOTICE file.
104
+
105
+ 7. Disclaimer of Warranty. Unless required by applicable law or
106
+ agreed to in writing, Licensor provides the Work (and each
107
+ Contributor provides its Contributions) on an "AS IS" BASIS,
108
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
109
+ implied, including, without limitation, any warranties or conditions
110
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
111
+ PARTICULAR PURPOSE.
112
+
113
+ 8. Limitation of Liability. In no event and under no legal theory,
114
+ whether in tort (including negligence), contract, or otherwise,
115
+ unless required by applicable law (such as deliberate and grossly
116
+ negligent acts) or agreed to in writing, shall any Contributor be
117
+ liable to You for damages, including any direct, indirect, special,
118
+ incidental, or consequential damages of any character arising as a
119
+ result of this License or out of the use or inability to use the
120
+ Work.
121
+
122
+ 9. Accepting Warranty or Additional Liability. While redistributing
123
+ the Work or Derivative Works thereof, You may choose to offer,
124
+ and charge a fee for, acceptance of support, warranty, indemnity,
125
+ or other liability obligations and/or rights consistent with this
126
+ License.
127
+
128
+ END OF TERMS AND CONDITIONS
129
+
130
+ Copyright 2026 Trustgate AI LLC
131
+
132
+ Licensed under the Apache License, Version 2.0 (the "License");
133
+ you may not use this file except in compliance with the License.
134
+ You may obtain a copy of the License at
135
+
136
+ http://www.apache.org/licenses/LICENSE-2.0
137
+
138
+ Unless required by applicable law or agreed to in writing, software
139
+ distributed under the License is distributed on an "AS IS" BASIS,
140
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
141
+ See the License for the specific language governing permissions and
142
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,8 @@
1
+ SHASHU by Trustgate AI
2
+ Copyright 2026 Trustgate AI LLC
3
+
4
+ This product includes software developed by Trustgate AI LLC.
5
+ Licensed under the Apache License, Version 2.0.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
package/README.md CHANGED
@@ -1,3 +1,392 @@
1
- # Temporary Holding Version
1
+ # @shashu-ai/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Node.js client for **SHASHU by Trustgate AI**, a self-hosted AI security gateway for
4
+ regulated industries. There is no default gateway hostname — you point the
5
+ client at your own address, and it raises a configuration error rather than
6
+ guessing. After the first mention, this document says **SHASHU**.
7
+
8
+ Wire names `x-trustgate-*`, `trustgate_metadata`, and the `tg_sk_` key prefix
9
+ are protocol names and are unchanged.
10
+
11
+ Requires Node.js 18 or later.
12
+
13
+ The library declares retrieval (explicitly or ambiently), carries session and
14
+ trace on every request, surfaces the gateway's decision (`allow`,
15
+ `allow_altered`, `not_checked`, `block`, `refuse`, `fail`), and recognises a
16
+ block. The block-recognition helper fails closed on an unknown code.
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ npm install @shashu-ai/sdk
22
+ ```
23
+
24
+ Optional peer dependencies for middleware:
25
+
26
+ ```bash
27
+ npm install ai @ai-sdk/openai # Vercel AI SDK
28
+ npm install @langchain/openai # LangChain
29
+ ```
30
+
31
+ ## Quick start
32
+
33
+ Key:
34
+
35
+ ```ts
36
+ import { Shashu } from '@shashu-ai/sdk';
37
+ const client = new Shashu({ baseUrl: 'https://your-shashu-gateway.example', apiKey: 'tg_sk_...' });
38
+ ```
39
+
40
+ Cloud pass (the function is yours; SHASHU never calls Entra, Google or AWS):
41
+
42
+ ```ts
43
+ import { Shashu } from '@shashu-ai/sdk';
44
+ const client = new Shashu({
45
+ baseUrl: 'https://your-shashu-gateway.example',
46
+ tokenProvider: getPass,
47
+ });
48
+ ```
49
+
50
+ ## Pass refusal codes
51
+
52
+ A cloud-pass 401 names the reason in `error.code`. Only `pass_expired` is retried
53
+ (once, after fetching a new pass). Every other code is raised as
54
+ `ShashuAuthenticationError` with `.code` set.
55
+
56
+ | Code | Meaning |
57
+ | -------------------------- | ------------------------------------------------------- |
58
+ | `pass_expired` | Cached pass expired; SDK retries once with a fresh pass |
59
+ | `pass_provider_not_set_up` | This gateway has no identity provider configured |
60
+ | `pass_not_licensed` | Cloud pass is not licensed on this gateway |
61
+ | `pass_wrong_audience` | Pass audience does not match this gateway |
62
+ | `pass_wrong_issuer` | Pass issuer does not match this gateway |
63
+ | `pass_unknown_agent` | The pass does not map to a known agent |
64
+
65
+ Plain OpenAI client, when that client accepts a function as the key:
66
+
67
+ ```ts
68
+ import OpenAI from 'openai';
69
+ const openai = new OpenAI({ baseURL: 'https://your-shashu-gateway.example/v1', apiKey: getPass });
70
+ ```
71
+
72
+ ## Core client
73
+
74
+ ```ts
75
+ import { Shashu, getWorkflowContextFromEnv } from '@shashu-ai/sdk';
76
+
77
+ const client = new Shashu({
78
+ baseUrl: process.env.SHASHU_BASE_URL!,
79
+ apiKey: process.env.SHASHU_API_KEY,
80
+ // workflowContext optional; otherwise read from process.env (n8n, Vercel, GitHub)
81
+ });
82
+
83
+ // Non-streaming
84
+ const res = await client.fetch('/v1/chat/completions', {
85
+ method: 'POST',
86
+ body: JSON.stringify({ model: 'gpt-4', messages: [...] }),
87
+ });
88
+
89
+ // SSE streaming (workflow_id sent in request for background attribution)
90
+ const streamRes = await client.fetchStream('/v1/chat/completions', {
91
+ method: 'POST',
92
+ body: JSON.stringify({ model: 'gpt-4', messages: [...], stream: true }),
93
+ });
94
+ // Consume streamRes.body (ReadableStream) as usual for SSE
95
+ ```
96
+
97
+ ## Configuring the gateway address
98
+
99
+ **There is no default gateway address.** SHASHU is self-hosted: your gateway
100
+ is on your network, under your name, and the SDK will not guess a host for you.
101
+ Every entry point resolves the address the same way:
102
+
103
+ 1. the explicit `baseUrl` option, then
104
+ 2. the `TRUSTGATE_BASE_URL` environment variable, then
105
+ 3. a `ShashuConfigError`.
106
+
107
+ ```ts
108
+ import { Shashu, ShashuConfigError } from '@shashu-ai/sdk';
109
+
110
+ try {
111
+ const client = new Shashu({ apiKey: process.env.TRUSTGATE_API_KEY });
112
+ } catch (e) {
113
+ if (e instanceof ShashuConfigError) {
114
+ // "SHASHU gateway address is not configured, so new Shashu() has
115
+ // nothing to route to. Pass baseUrl to new Shashu(), or set the
116
+ // TRUSTGATE_BASE_URL environment variable. ..."
117
+ }
118
+ }
119
+ ```
120
+
121
+ `ShashuConfigError` is a `ShashuError`, raised before any request is sent
122
+ (its `status` is `0`, not an HTTP status). The tracer is the one exception to
123
+ rule 3: it is constructed when the module is imported, so an unset address
124
+ leaves it with no gateway and it simply sends no span telemetry rather than
125
+ breaking `import`.
126
+
127
+ ### Turning the SDK off: `TRUSTGATE_DISABLE`
128
+
129
+ Set `TRUSTGATE_DISABLE=1` to make the SDK a no-op without a code change, so a
130
+ platform team can stop a deployed service's instrumentation from its
131
+ environment. `1`, `true`, `yes` and `on` are all accepted (any case).
132
+
133
+ ```bash
134
+ TRUSTGATE_DISABLE=1 node ./my-service.js
135
+ ```
136
+
137
+ When it is set:
138
+
139
+ - the four middleware helpers return `{}` and throw nothing, even with no
140
+ address configured — your provider client is left exactly as it was, talking
141
+ to its own endpoint with its own credential and no Shashu headers;
142
+ - the tracer records and flushes no spans, while still maintaining trace context
143
+ so an app that reads `tracer.traceId` keeps working.
144
+
145
+ It does **not** switch off `new Shashu({...})`. That client exists only to
146
+ call your gateway, so there is nothing for it to no-op into; it still requires
147
+ an address.
148
+
149
+ ## Reading the gateway's decision
150
+
151
+ The gateway answers with a **decision**, not just content. Read it with
152
+ `shashuDecision()`, which takes the returned response or an error you
153
+ caught:
154
+
155
+ ```ts
156
+ import { Shashu, shashuDecision, isShashuBlock } from '@shashu-ai/sdk';
157
+
158
+ const response = await client.fetch('/v1/chat/completions', { method: 'POST', body });
159
+ const decision = shashuDecision(response);
160
+ if (decision !== undefined && decision.isAltered) {
161
+ // Delivered, but policy edited it. Log decision.altered / decision.code.
162
+ }
163
+
164
+ try {
165
+ await client.fetch('/v1/chat/completions', { method: 'POST', body });
166
+ } catch (err) {
167
+ if (isShashuBlock(err)) {
168
+ return "That request was blocked by your organization's policy.";
169
+ }
170
+ throw err;
171
+ }
172
+ ```
173
+
174
+ Six values, and the split that matters is whether you got the model's content:
175
+ `allow`, `allow_altered`, `not_checked` (content delivered) versus `block`,
176
+ `refuse`, `fail` (no content). `shashuDecision()` returns nothing when the
177
+ gateway did not send a decision — that is not `allow`. `isShashuBlock()`
178
+ inspects; it patches nothing. An unrecognised decision fails closed (`true`).
179
+
180
+ **This SDK sends `trustgate-version: 2026-09-01` by default** (since 4.0.0), the
181
+ same value as the Trustgate AI Python SDK. The `Shashu` client,
182
+ `shashuFetch()` and the middleware configs all send it. With it, the body of
183
+ every reply carries the full `trustgate` block, so `decision.memory.items` lists
184
+ each memory save and recall and you get the inspection detail, not just header
185
+ counts. A refusal arrives as an error instead of a 200 reply: a content block is
186
+ an HTTP **400** (`ShashuContentFilterError`), a policy refusal a **403**
187
+ (`ShashuPolicyViolation`, or `MemoryWriteBlocked` for a blocked memory write),
188
+ and a provider SDK given `shashuFetch()` raises its own 400 or 403 error. To
189
+ turn it off, pass `contractVersion: null` to `new Shashu({...})`,
190
+ `shashuFetch({...})` or a middleware config. The gateway then serves your
191
+ account default, which is the `legacy` contract (a block is a 200 with
192
+ `finish_reason: "content_filter"`, and memory detail is header counts only)
193
+ unless an operator changed it.
194
+
195
+ ## Context provider
196
+
197
+ Workflow metadata is read from `process.env` so Shashu can attribute traffic
198
+ to the workflow that produced it:
199
+
200
+ | Source | Example env vars |
201
+ | ---------- | ------------------------------------------------------------------------ |
202
+ | **n8n** | `N8N_WORKFLOW_ID`, `N8N_EXECUTION_ID`, `N8N_WORKFLOW_NAME` |
203
+ | **Vercel** | `VERCEL`, `VERCEL_ENV`, `VERCEL_URL`, `VERCEL_GIT_*` |
204
+ | **GitHub** | `GITHUB_ACTION`, `GITHUB_WORKFLOW`, `GITHUB_RUN_ID`, `GITHUB_REPOSITORY` |
205
+
206
+ ```ts
207
+ import { getWorkflowContextFromEnv } from '@shashu-ai/sdk';
208
+
209
+ const ctx = getWorkflowContextFromEnv();
210
+ // { source: 'n8n', workflow_id: '...', execution_id: '...', metadata: {...} }
211
+ ```
212
+
213
+ ## Middleware: Vercel AI SDK
214
+
215
+ Point the OpenAI provider at Shashu so all calls go through the gateway with workflow context:
216
+
217
+ ```ts
218
+ import { createOpenAI } from '@ai-sdk/openai';
219
+ import { createShashuOpenAIOptions } from '@shashu-ai/sdk/middleware/vercel-ai';
220
+
221
+ const openai = createOpenAI(
222
+ createShashuOpenAIOptions({
223
+ baseUrl: process.env.TRUSTGATE_BASE_URL!,
224
+ apiKey: process.env.TRUSTGATE_API_KEY,
225
+ })
226
+ );
227
+
228
+ // Use with streamText / generateText as usual
229
+ import { streamText } from 'ai';
230
+ const result = streamText({
231
+ model: openai('gpt-4'),
232
+ messages: [{ role: 'user', content: 'Hello' }],
233
+ });
234
+ ```
235
+
236
+ ## Middleware: LangChain
237
+
238
+ Use Shashu as the OpenAI endpoint for LangChain with one config object:
239
+
240
+ ```ts
241
+ import { ChatOpenAI } from '@langchain/openai';
242
+ import { createShashuLangChainConfig } from '@shashu-ai/sdk/middleware/langchain';
243
+
244
+ const config = createShashuLangChainConfig({
245
+ baseUrl: process.env.TRUSTGATE_BASE_URL!,
246
+ apiKey: process.env.TRUSTGATE_API_KEY,
247
+ });
248
+
249
+ const llm = new ChatOpenAI({
250
+ ...config,
251
+ modelName: 'gpt-4',
252
+ temperature: 0,
253
+ });
254
+ ```
255
+
256
+ The returned `configuration` also carries a `fetch` that attaches any declared
257
+ retrieval to the outgoing body — see [Declaring retrieval](#declaring-retrieval-rag).
258
+
259
+ ## Declaring retrieval (RAG)
260
+
261
+ The gateway scans retrieved documents on a dedicated `ingress-rag` surface when
262
+ the request body carries `trustgate_metadata.rag_context` — with the corpus, the
263
+ per-document previews and the scores, rather than as an undifferentiated wall of
264
+ user text. Declare what you retrieved **where you retrieved it**; the SDK carries
265
+ the declaration to the gateway on the next model call.
266
+
267
+ ```ts
268
+ import { declareRetrieval } from '@shashu-ai/sdk';
269
+
270
+ const docs = await vectorstore.similaritySearch(question, 5);
271
+ declareRetrieval(docs, { corpus: 'policy_docs_v2', query: question });
272
+
273
+ // ...any amount of unrelated code...
274
+
275
+ await openai.chat.completions.create({ model: 'gpt-4o-mini', messages });
276
+ ```
277
+
278
+ `docs` may be plain strings, plain objects (`text` / `content` / `pageContent` /
279
+ `body`, with `id`, `score`, `source_uri`, `hash` read from the object or its
280
+ `metadata`), LangChain `Document`s or LlamaIndex nodes. The payload is capped at
281
+ the contract's limits: 64 documents, 2048-character previews, 8 declarations,
282
+ newest kept. An explicit `attachRagContext()` on the body always wins, and
283
+ `TRUSTGATE_DISABLE=1` makes the whole path inert.
284
+
285
+ ### Where the declaration reaches
286
+
287
+ The declaration rides an `AsyncLocalStorage` store, which Node binds to the
288
+ current async **frame** rather than to a task the way Python binds a
289
+ `ContextVar`. Three rules follow, and they are the ones worth knowing:
290
+
291
+ | where you declare | reaches the model call |
292
+ | -------------------------------------------------- | ---------------------- |
293
+ | the same async function, before the call | yes |
294
+ | a helper called before it has suspended | yes |
295
+ | a helper that already `await`ed, and then declared | **no** |
296
+ | anywhere inside `retrievalScope()` | yes |
297
+
298
+ `retrievalScope()` is the answer to both of the rows above that say **no** — a
299
+ helper that declares after awaiting, and a `Promise.all` fan-out where each
300
+ task declares before its first `await`. It gives the block a retrieval bus of
301
+ its own, so a declaration made anywhere inside reaches the model call and
302
+ nothing inside is seen by a sibling task or by anything after the block:
303
+
304
+ ```ts
305
+ import { retrievalScope } from '@shashu-ai/sdk';
306
+
307
+ // One declaration bound to one block:
308
+ await retrievalScope(docs, { corpus: 'policy_docs_v2', query }, () => chain.invoke(query));
309
+
310
+ // A fan-out: one scope per task, each with its own documents.
311
+ await Promise.all(
312
+ batches.map((b) =>
313
+ retrievalScope(b.docs, { corpus: 'policy_docs_v2' }, () =>
314
+ openai.chat.completions.create({ model, messages: b.messages })
315
+ )
316
+ )
317
+ );
318
+ ```
319
+
320
+ > **Removed in 3.0.0.** `isolateRetrieval()` was a third public function for
321
+ > exactly these two shapes. `retrievalScope()` covers both, so the surface now
322
+ > carries two retrieval functions and no third — see
323
+ > `contracts/sdk-surface.v1.md`. Replace
324
+ > `isolateRetrieval(() => { declareRetrieval(docs, opts); ... })` with
325
+ > `retrievalScope(docs, opts, () => ...)`.
326
+
327
+ ### Which clients carry it
328
+
329
+ The joiner rides the `fetch` the middleware hands back, so it works with any SDK
330
+ that accepts one:
331
+
332
+ | middleware | seam | automatic |
333
+ | ------------------------------- | ----------------------------------------------- | --------- |
334
+ | `new Shashu()` | the client's own `fetch` | yes |
335
+ | `createShashuLangChainConfig()` | `configuration.fetch` | yes |
336
+ | `createShashuAnthropicConfig()` | client option `fetch` | yes |
337
+ | `createShashuOpenAIOptions()` | provider option `fetch` | yes |
338
+ | `createShashuGeminiConfig()` | none — `@google/generative-ai` takes no `fetch` | **no** |
339
+
340
+ On the Gemini path, route the call through Shashu's own client or wrap your
341
+ own fetch with `withRetrievalJoiner()`. `test/conformance/seams.test.ts` asserts
342
+ every row of this table against the real SDKs.
343
+
344
+ ### LangChain: no line at all
345
+
346
+ Install the collector once and every retriever that runs inside a chain declares
347
+ what it returned:
348
+
349
+ ```ts
350
+ import { install } from '@shashu-ai/sdk/middleware/langchain';
351
+
352
+ await install({ corpus: 'policy_docs_v2' });
353
+ // LCEL, RetrievalQA-shaped chains, nested chains — nothing passed to invoke().
354
+ ```
355
+
356
+ `install()` returns `false` and does nothing at all when `@langchain/core` is not
357
+ installed. `uninstall()` turns the collecting off.
358
+
359
+ One case is **not** automatic: a retriever invoked outside any chain
360
+ (`await retriever.invoke(q)` on its own). Its run has no parent to associate a
361
+ later model call with, and LangChain dispatches callbacks through a queue that
362
+ discards the async context they would need. Call `declareRetrieval(docs, …)`
363
+ there. `test/conformance/outside-chain.test.ts` holds both halves of that.
364
+
365
+ ## n8n HTTP Request node: header snippet
366
+
367
+ Get a pre-formatted JSON object of headers for n8n “HTTP Request” nodes so each request includes Shashu auth and workflow context:
368
+
369
+ ```ts
370
+ import { getN8nHeaderSnippet } from '@shashu-ai/sdk';
371
+
372
+ const { headers, json } = getN8nHeaderSnippet();
373
+ // headers: [ { name: 'X-Trustgate-Source', value: 'n8n' }, ... ]
374
+ // json: '{"X-Trustgate-Source":"n8n","X-Trustgate-Workflow-Id":"...", ...}'
375
+ ```
376
+
377
+ In n8n, set **Send Headers** (or equivalent) to the `headers` array or paste the `json` into your node config. You can pass `apiKey` and `baseUrl` explicitly or rely on `TRUSTGATE_API_KEY` and `TRUSTGATE_BASE_URL` in the environment.
378
+
379
+ ## Streaming (SSE)
380
+
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.
383
+
384
+ ## License
385
+
386
+ MIT
387
+
388
+ ## Documentation and support
389
+
390
+ Product documentation: [https://shashu.ai/docs](https://shashu.ai/docs).
391
+
392
+ Support is through your Shashu administrator.
@@ -0,0 +1,48 @@
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
+ * `trustgate_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
+ /**
37
+ * Wrap a `fetch` so the carried declaration rides the next JSON model call.
38
+ *
39
+ * ```ts
40
+ * const openai = new OpenAI({ baseURL, fetch: withRetrievalJoiner() });
41
+ * ```
42
+ *
43
+ * Never throws on the SDK's behalf: any failure to understand a request means
44
+ * that request goes out exactly as the caller built it.
45
+ */
46
+ declare function withRetrievalJoiner(underlying?: FetchLike): FetchLike;
47
+
48
+ export { type FetchLike as F, withRetrievalJoiner as w };
@@ -0,0 +1,48 @@
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
+ * `trustgate_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
+ /**
37
+ * Wrap a `fetch` so the carried declaration rides the next JSON model call.
38
+ *
39
+ * ```ts
40
+ * const openai = new OpenAI({ baseURL, fetch: withRetrievalJoiner() });
41
+ * ```
42
+ *
43
+ * Never throws on the SDK's behalf: any failure to understand a request means
44
+ * that request goes out exactly as the caller built it.
45
+ */
46
+ declare function withRetrievalJoiner(underlying?: FetchLike): FetchLike;
47
+
48
+ export { type FetchLike as F, withRetrievalJoiner as w };