@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.
@@ -1,49 +0,0 @@
1
- import { S as ShashuConfig } from '../types-BLs_TMFv.cjs';
2
- import { F as FetchLike } from '../_joiner-DGi8GsY7.cjs';
3
-
4
- /**
5
- * Anthropic middleware: use Shashu as the base URL for @anthropic-ai/sdk.
6
- *
7
- * Pass the returned config to the Anthropic client so all requests go through
8
- * Shashu with workflow context and x-api-key for Shadow AI detection.
9
- *
10
- * Example:
11
- *
12
- * import Anthropic from '@anthropic-ai/sdk';
13
- * import { createShashuAnthropicConfig } from '@shashu-ai/sdk/middleware/anthropic';
14
- *
15
- * const config = createShashuAnthropicConfig({
16
- * baseUrl: process.env.SHASHU_BASE_URL!,
17
- * apiKey: process.env.SHASHU_API_KEY,
18
- * });
19
- *
20
- * const anthropic = new Anthropic(config);
21
- * const message = await anthropic.messages.create({ model: 'claude-3-5-sonnet-20241022', ... });
22
- */
23
-
24
- /**
25
- * Returns headers compatible with @anthropic-ai/sdk. Uses x-api-key only (no
26
- * Authorization header). Use with defaultHeaders or when building requests manually.
27
- */
28
- declare function getAnthropicHeaders(config: ShashuConfig): Record<string, string>;
29
- /**
30
- * Returns a config object for the Anthropic SDK (baseURL, apiKey, defaultHeaders).
31
- * Injects Shashu context headers and x-api-key so requests go through the gateway.
32
- *
33
- * Returns `{}` when SHASHU_DISABLE is set: the provider client is then left
34
- * exactly as it was — its own endpoint, its own credential, no Shashu context
35
- * headers — which is the same no-op the Python SDK's patchers perform. The
36
- * caller's tg_sk_ key is deliberately NOT handed back, since it would be sent to
37
- * the provider directly.
38
- *
39
- * @throws {ShashuConfigError} when no address is configured and the SDK is
40
- * not disabled. There is no default host. See ../config.ts.
41
- */
42
- declare function createShashuAnthropicConfig(config: ShashuConfig): {
43
- baseURL?: string;
44
- apiKey?: string | null;
45
- defaultHeaders?: Record<string, string>;
46
- fetch?: FetchLike;
47
- };
48
-
49
- export { createShashuAnthropicConfig, getAnthropicHeaders };
@@ -1,49 +0,0 @@
1
- import { S as ShashuConfig } from '../types-BLs_TMFv.js';
2
- import { F as FetchLike } from '../_joiner-DGi8GsY7.js';
3
-
4
- /**
5
- * Anthropic middleware: use Shashu as the base URL for @anthropic-ai/sdk.
6
- *
7
- * Pass the returned config to the Anthropic client so all requests go through
8
- * Shashu with workflow context and x-api-key for Shadow AI detection.
9
- *
10
- * Example:
11
- *
12
- * import Anthropic from '@anthropic-ai/sdk';
13
- * import { createShashuAnthropicConfig } from '@shashu-ai/sdk/middleware/anthropic';
14
- *
15
- * const config = createShashuAnthropicConfig({
16
- * baseUrl: process.env.SHASHU_BASE_URL!,
17
- * apiKey: process.env.SHASHU_API_KEY,
18
- * });
19
- *
20
- * const anthropic = new Anthropic(config);
21
- * const message = await anthropic.messages.create({ model: 'claude-3-5-sonnet-20241022', ... });
22
- */
23
-
24
- /**
25
- * Returns headers compatible with @anthropic-ai/sdk. Uses x-api-key only (no
26
- * Authorization header). Use with defaultHeaders or when building requests manually.
27
- */
28
- declare function getAnthropicHeaders(config: ShashuConfig): Record<string, string>;
29
- /**
30
- * Returns a config object for the Anthropic SDK (baseURL, apiKey, defaultHeaders).
31
- * Injects Shashu context headers and x-api-key so requests go through the gateway.
32
- *
33
- * Returns `{}` when SHASHU_DISABLE is set: the provider client is then left
34
- * exactly as it was — its own endpoint, its own credential, no Shashu context
35
- * headers — which is the same no-op the Python SDK's patchers perform. The
36
- * caller's tg_sk_ key is deliberately NOT handed back, since it would be sent to
37
- * the provider directly.
38
- *
39
- * @throws {ShashuConfigError} when no address is configured and the SDK is
40
- * not disabled. There is no default host. See ../config.ts.
41
- */
42
- declare function createShashuAnthropicConfig(config: ShashuConfig): {
43
- baseURL?: string;
44
- apiKey?: string | null;
45
- defaultHeaders?: Record<string, string>;
46
- fetch?: FetchLike;
47
- };
48
-
49
- export { createShashuAnthropicConfig, getAnthropicHeaders };
@@ -1,10 +0,0 @@
1
- import {
2
- createShashuAnthropicConfig,
3
- getAnthropicHeaders
4
- } from "../chunk-3GAMCQ6R.js";
5
- import "../chunk-M7EMWSNS.js";
6
- import "../chunk-TGD6KDWT.js";
7
- export {
8
- createShashuAnthropicConfig,
9
- getAnthropicHeaders
10
- };
@@ -1,530 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/middleware/google.ts
21
- var google_exports = {};
22
- __export(google_exports, {
23
- createShashuGeminiConfig: () => createShashuGeminiConfig,
24
- getGeminiHeaders: () => getGeminiHeaders
25
- });
26
- module.exports = __toCommonJS(google_exports);
27
- var import_node_crypto3 = require("crypto");
28
-
29
- // src/types.ts
30
- var ShashuError = class _ShashuError extends Error {
31
- /**
32
- * Why a route was refused for the data in the request, off the decision.
33
- * Set on a `route_data_policy` refusal, so an app can say which route is not
34
- * approved for which category without parsing the message.
35
- */
36
- get routePolicy() {
37
- return this.decision?.routePolicy;
38
- }
39
- constructor(message, status, body, details) {
40
- super(message);
41
- this.name = "ShashuError";
42
- this.status = status;
43
- this.body = body;
44
- this.type = details?.type;
45
- this.code = details?.code;
46
- this.decision = details?.decision;
47
- this.responseHeaders = details?.responseHeaders;
48
- Object.setPrototypeOf(this, _ShashuError.prototype);
49
- }
50
- };
51
-
52
- // src/exceptions.ts
53
- var ShashuConfigError = class _ShashuConfigError extends ShashuError {
54
- constructor(message) {
55
- super(message, 0);
56
- this.name = "ShashuConfigError";
57
- Object.setPrototypeOf(this, _ShashuConfigError.prototype);
58
- }
59
- };
60
-
61
- // src/config.ts
62
- var BASE_URL_ENV = "SHASHU_BASE_URL";
63
- var API_KEY_ENV = "SHASHU_API_KEY";
64
- var DISABLE_ENV = "SHASHU_DISABLE";
65
- var TRUTHY = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);
66
- function env() {
67
- return typeof process !== "undefined" && process.env ? process.env : {};
68
- }
69
- function envGet(current, _legacy) {
70
- const now = (env()[current] ?? "").trim();
71
- return now || void 0;
72
- }
73
- function isDisabled() {
74
- return TRUTHY.has((envGet(DISABLE_ENV) ?? "").trim().toLowerCase());
75
- }
76
- function firstConfigured(baseUrl, envVars) {
77
- if (baseUrl && baseUrl.trim()) return baseUrl.trim().replace(/\/+$/, "");
78
- for (const name of envVars) {
79
- const value = env()[name]?.trim();
80
- if (value) return value.replace(/\/+$/, "");
81
- }
82
- return void 0;
83
- }
84
- function optionalBaseUrl(baseUrl, envVars = [BASE_URL_ENV]) {
85
- return firstConfigured(baseUrl, envVars);
86
- }
87
- function requireBaseUrl(baseUrl, opts) {
88
- const envVars = opts.envVars ?? [BASE_URL_ENV];
89
- const resolved = firstConfigured(baseUrl, envVars);
90
- if (resolved) return resolved;
91
- const option = opts.option ?? "baseUrl";
92
- const envHint = envVars.length === 1 ? `set the ${envVars[0]} environment variable` : `set one of the ${envVars.join(" or ")} environment variables`;
93
- throw new ShashuConfigError(
94
- `SHASHU gateway address is not configured, so ${opts.entryPoint} has nothing to route to. Pass ${option} to ${opts.entryPoint}, or ${envHint}. SHASHU is self-hosted: the SDK has no default address and will not guess one.`
95
- );
96
- }
97
-
98
- // src/credential.ts
99
- var KEY_ONLY_FOR_NOW = "{name} is key only for now: pass a SHASHU key, not a token provider.";
100
- function rejectKeyOnly(name, tokenProvider) {
101
- if (tokenProvider != null) {
102
- throw new ShashuConfigError(KEY_ONLY_FOR_NOW.replace("{name}", name));
103
- }
104
- }
105
-
106
- // src/context.ts
107
- var import_node_crypto2 = require("crypto");
108
-
109
- // src/version.ts
110
- var SDK_VERSION = "1.1.1";
111
-
112
- // src/tracer.ts
113
- var import_node_async_hooks = require("async_hooks");
114
- var import_node_crypto = require("crypto");
115
- var spanStorage = new import_node_async_hooks.AsyncLocalStorage();
116
- var a2aStorage = new import_node_async_hooks.AsyncLocalStorage();
117
- function coerceHeaderMap(headers) {
118
- const out = {};
119
- if (!headers) return out;
120
- try {
121
- if (Array.isArray(headers)) {
122
- for (const pair of headers) {
123
- if (Array.isArray(pair) && pair.length >= 2 && pair[0] != null) {
124
- out[String(pair[0]).toLowerCase()] = String(pair[1]);
125
- }
126
- }
127
- return out;
128
- }
129
- if (headers instanceof Map) {
130
- for (const [k, v] of headers) out[String(k).toLowerCase()] = String(v);
131
- return out;
132
- }
133
- if (typeof headers.forEach === "function") {
134
- headers.forEach((v, k) => {
135
- if (k != null) out[String(k).toLowerCase()] = String(v);
136
- });
137
- return out;
138
- }
139
- if (typeof headers === "object") {
140
- for (const [k, v] of Object.entries(headers)) {
141
- if (v !== void 0 && v !== null) out[k.toLowerCase()] = String(v);
142
- }
143
- }
144
- } catch {
145
- return out;
146
- }
147
- return out;
148
- }
149
- function parseHopDepth(raw) {
150
- const n = parseInt(String(raw ?? "").trim(), 10);
151
- return Number.isFinite(n) && n > 0 ? n : 0;
152
- }
153
- function captureFromHeaders(h) {
154
- const trace = (h["x-shashu-trace-id"] ?? "").trim();
155
- if (!trace) return void 0;
156
- const session = (h["x-shashu-session-id"] ?? "").trim();
157
- const caller = (h["x-shashu-caller-agent-id"] ?? "").trim();
158
- return {
159
- traceId: trace,
160
- sessionId: session || void 0,
161
- inboundHopDepth: parseHopDepth(h["x-shashu-hop-depth"]),
162
- inboundCallerAgentId: caller || void 0
163
- };
164
- }
165
- var Tracer = class {
166
- /**
167
- * Resolves the address OPTIONALLY, unlike every other entry point.
168
- *
169
- * The module exports a singleton (`export const tracer = new Tracer()`), so
170
- * this constructor runs on `import "@shashu-ai/sdk"`. Throwing here would
171
- * make importing the SDK fail for anyone who has not set the variable, which
172
- * is a far worse failure than the one this is fixing. Instead the address
173
- * stays undefined and {@link flush} posts nothing — the same shape as the
174
- * Python SDK's telemetry path, which resolves with optional_base_url and
175
- * no-ops the flush.
176
- */
177
- constructor() {
178
- this.buffer = [];
179
- this.flushTimer = null;
180
- this._gatewayUrl = optionalBaseUrl();
181
- this._apiKey = envGet(API_KEY_ENV);
182
- }
183
- /**
184
- * Current gateway base URL (respects configure()), or undefined when none is
185
- * configured. Undefined means telemetry is not sent — never a default host.
186
- */
187
- get gatewayUrl() {
188
- return this._gatewayUrl;
189
- }
190
- /** Current API key (respects configure()). */
191
- get apiKey() {
192
- return this._apiKey;
193
- }
194
- /**
195
- * Update gateway URL and/or API key at runtime (e.g. for scripts switching agents).
196
- * baseUrl has its trailing slash stripped to match constructor behavior.
197
- */
198
- configure(opts) {
199
- if (opts.baseUrl !== void 0) {
200
- this._gatewayUrl = opts.baseUrl.replace(/\/$/, "");
201
- }
202
- if (opts.apiKey !== void 0) {
203
- this._apiKey = opts.apiKey;
204
- }
205
- }
206
- // --- Context Accessors ---
207
- get traceId() {
208
- return spanStorage.getStore()?.traceId ?? a2aStorage.getStore()?.traceId;
209
- }
210
- get currentSpanId() {
211
- const store = spanStorage.getStore();
212
- return store?.spanId;
213
- }
214
- /** The current span's PARENT span id; undefined at origin or for a root span. */
215
- get parentSpanId() {
216
- const store = spanStorage.getStore();
217
- return store?.parentId;
218
- }
219
- get isActive() {
220
- return !!spanStorage.getStore();
221
- }
222
- // --- A2A inbound-capture + outbound propagation (ADR-007 §0, §4.1 locked) ---
223
- /** True when this context CAPTURED an inbound flow — so a downstream gateway call
224
- * PROPAGATES the trace and attaches caller/session/hop lineage rather than originate
225
- * a new flow. False = origin (header set unchanged). */
226
- get isA2aHop() {
227
- const s = a2aStorage.getStore();
228
- return !!(s && s.traceId);
229
- }
230
- /** The captured inbound session id, or undefined when none was propagated. */
231
- get sessionId() {
232
- return a2aStorage.getStore()?.sessionId || void 0;
233
- }
234
- /** Advisory inbound hop depth captured from x-shashu-hop-depth (0 if absent). */
235
- get inboundHopDepth() {
236
- return a2aStorage.getStore()?.inboundHopDepth ?? 0;
237
- }
238
- /** Hop depth to advertise on the next downstream call = inbound + 1 (advisory; the
239
- * gateway recounts authoritatively). */
240
- get outboundHopDepth() {
241
- return this.inboundHopDepth + 1;
242
- }
243
- /** The captured inbound x-shashu-caller-agent-id — the upstream agent that INVOKED
244
- * this hop. The SDK FORWARDS this on the outbound gateway call so the gateway records
245
- * the real (invoker -> this agent) edge, NEVER this agent's own id (§4.1). undefined at
246
- * origin / caller-stripped. */
247
- get inboundCallerAgentId() {
248
- return a2aStorage.getStore()?.inboundCallerAgentId || void 0;
249
- }
250
- /**
251
- * Capture an inbound flow from the headers of a request this agent is SERVING into the
252
- * AsyncLocalStorage store, so a downstream call made through the SDK propagates the SAME
253
- * flow (WP-A2A-4 / ADR-007 §0). Reads (case-insensitively) x-shashu-trace-id (the flow
254
- * id), -session-id, -hop-depth, and -caller-agent-id (the upstream INVOKER). The captured
255
- * trace is PROPAGATED on the next outbound call (never re-minted); the session, inbound hop
256
- * depth, and inbound caller ride along — the caller is FORWARDED on the gateway call (§4.1),
257
- * never replaced by self.
258
- *
259
- * Uses enterWith, so the capture persists for the remainder of the current async execution
260
- * (one-shot, for a script serving a single inbound call). Servers handling many requests
261
- * should prefer {@link incoming} so one flow's lineage never leaks into the next. No inbound
262
- * trace ⇒ origin: the ambient capture is cleared and false is returned (non-A2A unaffected).
263
- * Never throws — telemetry must not break a request.
264
- */
265
- captureIncoming(headers) {
266
- const capture = captureFromHeaders(coerceHeaderMap(headers));
267
- a2aStorage.enterWith(capture);
268
- return capture !== void 0;
269
- }
270
- /**
271
- * Scoped inbound capture: capture for the duration of serving ONE request, then restore
272
- * the prior context on exit — so a long-lived worker does not leak one flow's lineage into
273
- * the next. Prefer this in servers; {@link captureIncoming} is the one-shot for scripts.
274
- *
275
- * @example
276
- * await tracer.incoming(req.headers, async () => {
277
- * await tg.fetch("/v1/chat/completions", { ... }); // propagates the captured flow
278
- * });
279
- */
280
- incoming(headers, callback) {
281
- const capture = captureFromHeaders(coerceHeaderMap(headers));
282
- return a2aStorage.run(capture, callback);
283
- }
284
- // --- Main Logic ---
285
- /**
286
- * Wraps a callback in a new Span Context.
287
- * Automatically handles Header injection for any internal calls.
288
- */
289
- async span(name, callback, metadata) {
290
- const parent = spanStorage.getStore();
291
- const traceId = parent?.traceId ?? a2aStorage.getStore()?.traceId ?? (0, import_node_crypto.randomUUID)();
292
- const spanId = (0, import_node_crypto.randomUUID)();
293
- const parentId = parent?.spanId;
294
- const context = { traceId, spanId, parentId };
295
- const startTime = Date.now() / 1e3;
296
- try {
297
- return await spanStorage.run(context, async () => {
298
- return await callback(spanId);
299
- });
300
- } finally {
301
- const endTime = Date.now() / 1e3;
302
- this.record({
303
- trace_id: traceId,
304
- span_id: spanId,
305
- parent_span_id: parentId,
306
- name,
307
- start_time: startTime,
308
- end_time: endTime,
309
- duration: endTime - startTime,
310
- metadata
311
- });
312
- }
313
- }
314
- // --- Telemetry Transport ---
315
- record(span) {
316
- if (isDisabled()) return;
317
- this.buffer.push(span);
318
- if (this.buffer.length >= 10) {
319
- this.flush();
320
- } else if (!this.flushTimer) {
321
- this.flushTimer = setTimeout(() => this.flush(), 1e3);
322
- this.flushTimer.unref();
323
- }
324
- }
325
- async flush() {
326
- if (this.flushTimer) {
327
- clearTimeout(this.flushTimer);
328
- this.flushTimer = null;
329
- }
330
- if (isDisabled()) return;
331
- if (this.buffer.length === 0 || !this._apiKey || !this._gatewayUrl) return;
332
- const batch = [...this.buffer];
333
- this.buffer = [];
334
- try {
335
- await fetch(`${this._gatewayUrl}/api/telemetry/spans`, {
336
- method: "POST",
337
- headers: {
338
- "Content-Type": "application/json",
339
- Authorization: `Bearer ${this._apiKey}`
340
- },
341
- body: JSON.stringify(batch)
342
- });
343
- } catch {
344
- }
345
- }
346
- };
347
- var tracer = new Tracer();
348
-
349
- // src/context.ts
350
- var HEADER_PREFIX = "x-shashu";
351
- var SOURCE_TOOL_HEADER = "x-shashu-source-tool";
352
- var DEFAULT_CONTRACT_VERSION = "2026-09-01";
353
- var CONTRACT_VERSION_HEADER = "shashu-version";
354
- function applyContractVersion(headers, contractVersion) {
355
- if (contractVersion === null) return headers;
356
- const named = Object.keys(headers).some((k) => k.toLowerCase() === CONTRACT_VERSION_HEADER);
357
- if (!named) headers[CONTRACT_VERSION_HEADER] = contractVersion ?? DEFAULT_CONTRACT_VERSION;
358
- return headers;
359
- }
360
- var N8N_KEYS = [
361
- "N8N_WORKFLOW_ID",
362
- "N8N_EXECUTION_ID",
363
- "N8N_WORKFLOW_NAME",
364
- "N8N_EXECUTION_MODE"
365
- ];
366
- var VERCEL_KEYS = [
367
- "VERCEL",
368
- "VERCEL_ENV",
369
- "VERCEL_URL",
370
- "VERCEL_GIT_COMMIT_REF",
371
- "VERCEL_GIT_REPO_ID",
372
- "VERCEL_GIT_COMMIT_SHA"
373
- ];
374
- var GITHUB_KEYS = [
375
- "GITHUB_ACTION",
376
- "GITHUB_ACTIONS",
377
- "GITHUB_WORKFLOW",
378
- "GITHUB_RUN_ID",
379
- "GITHUB_RUN_NUMBER",
380
- "GITHUB_REPOSITORY",
381
- "GITHUB_SHA"
382
- ];
383
- function pickEnv(keys) {
384
- const out = {};
385
- for (const key of keys) {
386
- const v = process.env[key];
387
- if (v !== void 0 && v !== "") out[key] = v;
388
- }
389
- return out;
390
- }
391
- function getBaseMetadata() {
392
- return {
393
- sdk_version: SDK_VERSION,
394
- node_version: process.version,
395
- os: process.platform,
396
- arch: process.arch
397
- };
398
- }
399
- function getWorkflowContextFromEnv() {
400
- const baseMeta = getBaseMetadata();
401
- const n8n = pickEnv(N8N_KEYS);
402
- if (Object.keys(n8n).length > 0) {
403
- return {
404
- source: "n8n",
405
- workflow_id: n8n.N8N_WORKFLOW_ID,
406
- execution_id: n8n.N8N_EXECUTION_ID,
407
- metadata: { ...baseMeta, ...n8n }
408
- };
409
- }
410
- const vercel = pickEnv(VERCEL_KEYS);
411
- if (Object.keys(vercel).length > 0) {
412
- return {
413
- source: "vercel",
414
- workflow_id: vercel.VERCEL_GIT_REPO_ID || vercel.VERCEL_URL,
415
- execution_id: vercel.VERCEL_GIT_COMMIT_SHA,
416
- metadata: { ...baseMeta, ...vercel }
417
- };
418
- }
419
- const github = pickEnv(GITHUB_KEYS);
420
- if (Object.keys(github).length > 0) {
421
- return {
422
- source: "github",
423
- workflow_id: github.GITHUB_WORKFLOW || github.GITHUB_REPOSITORY,
424
- execution_id: github.GITHUB_RUN_ID || github.GITHUB_RUN_NUMBER,
425
- metadata: { ...baseMeta, ...github }
426
- };
427
- }
428
- return {
429
- source: "local_script",
430
- metadata: baseMeta
431
- };
432
- }
433
- function buildSourceToolJson(ctx) {
434
- const meta = ctx.metadata ?? getBaseMetadata();
435
- const payload = {
436
- source: ctx.source,
437
- metadata: meta
438
- };
439
- if (ctx.workflow_id !== void 0) payload.workflow_id = ctx.workflow_id;
440
- if (ctx.execution_id !== void 0) payload.execution_id = ctx.execution_id;
441
- if (ctx.workflow_step !== void 0) payload.workflow_step = ctx.workflow_step;
442
- return JSON.stringify(payload);
443
- }
444
- var TRUSTLOG_HEADER_PREFIX = "x-trustlog-";
445
- function resolveOriginTraceId() {
446
- const n8n = process.env.N8N_EXECUTION_ID;
447
- if (n8n) return n8n;
448
- const github = process.env.GITHUB_RUN_ID;
449
- if (github) return github;
450
- const gitlab = process.env.CI_PIPELINE_ID;
451
- if (process.env.GITLAB_CI && gitlab) return gitlab;
452
- return (0, import_node_crypto2.randomUUID)();
453
- }
454
- function lowercaseHeaderKeys(h) {
455
- const out = {};
456
- for (const [k, v] of Object.entries(h)) out[k.toLowerCase()] = v;
457
- return out;
458
- }
459
- function buildContextHeaders(ctx, session) {
460
- const meta = ctx.metadata ?? getBaseMetadata();
461
- const h = {
462
- [SOURCE_TOOL_HEADER]: buildSourceToolJson({ ...ctx, metadata: meta }),
463
- [`${HEADER_PREFIX}-source`]: ctx.source
464
- };
465
- if (ctx.workflow_id) h[`${HEADER_PREFIX}-workflow-id`] = ctx.workflow_id;
466
- if (ctx.execution_id) h[`${HEADER_PREFIX}-execution-id`] = ctx.execution_id;
467
- if (ctx.workflow_step) h[`${HEADER_PREFIX}-workflow-step`] = ctx.workflow_step;
468
- for (const [k, v] of Object.entries(meta)) {
469
- if (v) h[`${TRUSTLOG_HEADER_PREFIX}${k.replace(/_/g, "-")}`] = String(v);
470
- }
471
- if (tracer.isActive) {
472
- if (tracer.traceId) h["x-shashu-trace-id"] = tracer.traceId;
473
- h["x-shashu-span-id"] = tracer.currentSpanId ?? "";
474
- h["x-shashu-parent-id"] = tracer.parentSpanId ?? "";
475
- } else if (tracer.isA2aHop) {
476
- if (tracer.traceId) h["x-shashu-trace-id"] = tracer.traceId;
477
- } else if (!h["x-shashu-trace-id"]) {
478
- h["x-shashu-trace-id"] = resolveOriginTraceId();
479
- }
480
- const sessionId = resolveSessionId(session);
481
- if (sessionId) h["x-shashu-session-id"] = sessionId;
482
- if (tracer.isA2aHop) {
483
- const inboundCaller = tracer.inboundCallerAgentId;
484
- if (inboundCaller) h["x-shashu-caller-agent-id"] = inboundCaller;
485
- h["x-shashu-hop-depth"] = String(tracer.outboundHopDepth);
486
- }
487
- return lowercaseHeaderKeys(h);
488
- }
489
- function resolveSessionId(opts) {
490
- if (opts?.requestSessionId != null && String(opts.requestSessionId) !== "") {
491
- return String(opts.requestSessionId);
492
- }
493
- const captured = tracer.sessionId;
494
- if (captured) return captured;
495
- if (opts?.defaultSessionId != null && String(opts.defaultSessionId) !== "") {
496
- return String(opts.defaultSessionId);
497
- }
498
- return void 0;
499
- }
500
-
501
- // src/middleware/google.ts
502
- function getGeminiHeaders(config) {
503
- const ctx = config.workflowContext ?? getWorkflowContextFromEnv();
504
- const headers = {
505
- ...config.headers,
506
- ...buildContextHeaders(ctx, { defaultSessionId: config.sessionId })
507
- };
508
- if (config.apiKey) {
509
- headers["x-api-key"] = config.apiKey;
510
- }
511
- return applyContractVersion(headers, config.contractVersion);
512
- }
513
- function createShashuGeminiConfig(config) {
514
- if (isDisabled()) return {};
515
- rejectKeyOnly("createShashuGeminiConfig", config.tokenProvider);
516
- const baseUrl = requireBaseUrl(config.baseUrl, {
517
- entryPoint: "createShashuGeminiConfig()"
518
- });
519
- const headers = getGeminiHeaders({ ...config, sessionId: config.sessionId ?? (0, import_node_crypto3.randomUUID)() });
520
- return {
521
- baseUrl,
522
- apiKey: config.apiKey ?? null,
523
- headers: Object.keys(headers).length ? headers : void 0
524
- };
525
- }
526
- // Annotate the CommonJS export names for ESM import in node:
527
- 0 && (module.exports = {
528
- createShashuGeminiConfig,
529
- getGeminiHeaders
530
- });