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