@superbased/sdk 0.0.1-placeholder.0 → 0.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.
Files changed (118) hide show
  1. package/NOTICE +4 -0
  2. package/README.md +434 -5
  3. package/dist/cjs/admit.d.ts +139 -0
  4. package/dist/cjs/admit.js +442 -0
  5. package/dist/cjs/admit.js.map +1 -0
  6. package/dist/cjs/attrs.d.ts +113 -0
  7. package/dist/cjs/attrs.js +183 -0
  8. package/dist/cjs/attrs.js.map +1 -0
  9. package/dist/cjs/config.d.ts +202 -0
  10. package/dist/cjs/config.js +386 -0
  11. package/dist/cjs/config.js.map +1 -0
  12. package/dist/cjs/context.d.ts +102 -0
  13. package/dist/cjs/context.js +234 -0
  14. package/dist/cjs/context.js.map +1 -0
  15. package/dist/cjs/control.d.ts +99 -0
  16. package/dist/cjs/control.js +243 -0
  17. package/dist/cjs/control.js.map +1 -0
  18. package/dist/cjs/cost.d.ts +108 -0
  19. package/dist/cjs/cost.js +211 -0
  20. package/dist/cjs/cost.js.map +1 -0
  21. package/dist/cjs/destination.d.ts +125 -0
  22. package/dist/cjs/destination.js +357 -0
  23. package/dist/cjs/destination.js.map +1 -0
  24. package/dist/cjs/experiments.d.ts +237 -0
  25. package/dist/cjs/experiments.js +678 -0
  26. package/dist/cjs/experiments.js.map +1 -0
  27. package/dist/cjs/export.d.ts +84 -0
  28. package/dist/cjs/export.js +328 -0
  29. package/dist/cjs/export.js.map +1 -0
  30. package/dist/cjs/index.d.ts +168 -0
  31. package/dist/cjs/index.js +581 -0
  32. package/dist/cjs/index.js.map +1 -0
  33. package/dist/cjs/instrument.d.ts +88 -0
  34. package/dist/cjs/instrument.js +397 -0
  35. package/dist/cjs/instrument.js.map +1 -0
  36. package/dist/cjs/package.json +1 -0
  37. package/dist/cjs/policy.d.ts +77 -0
  38. package/dist/cjs/policy.js +252 -0
  39. package/dist/cjs/policy.js.map +1 -0
  40. package/dist/cjs/prompts.d.ts +175 -0
  41. package/dist/cjs/prompts.js +476 -0
  42. package/dist/cjs/prompts.js.map +1 -0
  43. package/dist/cjs/propagation.d.ts +34 -0
  44. package/dist/cjs/propagation.js +151 -0
  45. package/dist/cjs/propagation.js.map +1 -0
  46. package/dist/cjs/req.d.ts +10 -0
  47. package/dist/cjs/req.js +3 -0
  48. package/dist/cjs/req.js.map +1 -0
  49. package/dist/cjs/runtime.d.ts +44 -0
  50. package/dist/cjs/runtime.js +67 -0
  51. package/dist/cjs/runtime.js.map +1 -0
  52. package/dist/cjs/scores.d.ts +102 -0
  53. package/dist/cjs/scores.js +226 -0
  54. package/dist/cjs/scores.js.map +1 -0
  55. package/dist/cjs/spans.d.ts +193 -0
  56. package/dist/cjs/spans.js +398 -0
  57. package/dist/cjs/spans.js.map +1 -0
  58. package/dist/cjs/vendor.d.ts +33 -0
  59. package/dist/cjs/vendor.js +67 -0
  60. package/dist/cjs/vendor.js.map +1 -0
  61. package/dist/esm/admit.d.ts +139 -0
  62. package/dist/esm/admit.js +432 -0
  63. package/dist/esm/admit.js.map +1 -0
  64. package/dist/esm/attrs.d.ts +113 -0
  65. package/dist/esm/attrs.js +179 -0
  66. package/dist/esm/attrs.js.map +1 -0
  67. package/dist/esm/config.d.ts +202 -0
  68. package/dist/esm/config.js +364 -0
  69. package/dist/esm/config.js.map +1 -0
  70. package/dist/esm/context.d.ts +102 -0
  71. package/dist/esm/context.js +221 -0
  72. package/dist/esm/context.js.map +1 -0
  73. package/dist/esm/control.d.ts +99 -0
  74. package/dist/esm/control.js +230 -0
  75. package/dist/esm/control.js.map +1 -0
  76. package/dist/esm/cost.d.ts +108 -0
  77. package/dist/esm/cost.js +202 -0
  78. package/dist/esm/cost.js.map +1 -0
  79. package/dist/esm/destination.d.ts +125 -0
  80. package/dist/esm/destination.js +346 -0
  81. package/dist/esm/destination.js.map +1 -0
  82. package/dist/esm/experiments.d.ts +237 -0
  83. package/dist/esm/experiments.js +666 -0
  84. package/dist/esm/experiments.js.map +1 -0
  85. package/dist/esm/export.d.ts +84 -0
  86. package/dist/esm/export.js +314 -0
  87. package/dist/esm/export.js.map +1 -0
  88. package/dist/esm/index.d.ts +168 -0
  89. package/dist/esm/index.js +500 -0
  90. package/dist/esm/index.js.map +1 -0
  91. package/dist/esm/instrument.d.ts +88 -0
  92. package/dist/esm/instrument.js +391 -0
  93. package/dist/esm/instrument.js.map +1 -0
  94. package/dist/esm/policy.d.ts +77 -0
  95. package/dist/esm/policy.js +240 -0
  96. package/dist/esm/policy.js.map +1 -0
  97. package/dist/esm/prompts.d.ts +175 -0
  98. package/dist/esm/prompts.js +460 -0
  99. package/dist/esm/prompts.js.map +1 -0
  100. package/dist/esm/propagation.d.ts +34 -0
  101. package/dist/esm/propagation.js +145 -0
  102. package/dist/esm/propagation.js.map +1 -0
  103. package/dist/esm/req.d.ts +10 -0
  104. package/dist/esm/req.js +2 -0
  105. package/dist/esm/req.js.map +1 -0
  106. package/dist/esm/runtime.d.ts +44 -0
  107. package/dist/esm/runtime.js +59 -0
  108. package/dist/esm/runtime.js.map +1 -0
  109. package/dist/esm/scores.d.ts +102 -0
  110. package/dist/esm/scores.js +219 -0
  111. package/dist/esm/scores.js.map +1 -0
  112. package/dist/esm/spans.d.ts +193 -0
  113. package/dist/esm/spans.js +378 -0
  114. package/dist/esm/spans.js.map +1 -0
  115. package/dist/esm/vendor.d.ts +33 -0
  116. package/dist/esm/vendor.js +61 -0
  117. package/dist/esm/vendor.js.map +1 -0
  118. package/package.json +121 -4
@@ -0,0 +1,432 @@
1
+ /**
2
+ * `admit()`: the input-admission pre-flight check (admission spec §6.1).
3
+ *
4
+ * Never throws or rejects. Any failure (transport, timeout, HTTP error, a body
5
+ * that is not a JSON object, a field of the wrong type) yields a degraded
6
+ * verdict that admits (fail open, the default) or denies (`failClosed`).
7
+ */
8
+ import { trace } from "@opentelemetry/api";
9
+ import { envFlag, onlineUsable, resolveServiceName } from "./config.js";
10
+ import { getCurrentAttributes } from "./context.js";
11
+ import { isLoopbackUrl } from "./destination.js";
12
+ import { destinationKnown, runtime } from "./runtime.js";
13
+ /** Default admission-check endpoint: this machine's Observer API on the dashboard port. */
14
+ export const DEFAULT_ADMISSION_ENDPOINT = "http://127.0.0.1:8081/api/obs/admission/check";
15
+ /** The path of a machine's admission check. */
16
+ const MACHINE_ADMISSION_PATH = "/api/obs/admission/check";
17
+ /** Path of the org SDK control API's admission endpoint, under an org URL. */
18
+ export const SDK_ADMIT_PATH = "/v1/sdk/admit";
19
+ /**
20
+ * Default client timeout (ms). Longer than the server's 10 s judge budget, so
21
+ * the client does not fail open on a request the server would still decide.
22
+ * A server that advertises a recommended timeout (the
23
+ * `recommended_client_timeout_ms` body field or the
24
+ * `X-SBO-Recommended-Timeout-Ms` header, sent by both the org SDK control API
25
+ * and the local machine) overrides it for later calls.
26
+ */
27
+ export const DEFAULT_ADMIT_TIMEOUT_MS = 12_000;
28
+ /**
29
+ * The advertised-timeout names, canonical first. The second of each pair is
30
+ * the pre-release spelling, still read so an older server keeps working.
31
+ */
32
+ export const TIMEOUT_HEADERS = ["x-sbo-recommended-timeout-ms", "x-superbased-admit-timeout-ms"];
33
+ export const TIMEOUT_FIELDS = ["recommended_client_timeout_ms", "recommended_timeout_ms"];
34
+ /** Client-side degraded reasons (`Verdict.degraded`). Server values pass through. */
35
+ export const Degraded = {
36
+ /** HTTP 403/404: admission is off on the server or not permitted. */
37
+ UNAVAILABLE: "admission-unavailable",
38
+ TIMEOUT: "client-timeout",
39
+ TRANSPORT: "client-transport",
40
+ HTTP_ERROR: "client-http-error",
41
+ BAD_RESPONSE: "client-bad-response",
42
+ /**
43
+ * The organization answered mode `off`: it has no admission policy, so it
44
+ * made no decision (live finding L-05, ruling D29). Under destination `both`
45
+ * the SDK then asks this machine; otherwise the verdict is degraded.
46
+ */
47
+ ADMISSION_OFF: "admission-off",
48
+ };
49
+ const advertised = new Map();
50
+ // --- saying so when admit() could not decide (review E-39) -------------------
51
+ //
52
+ // admit() fails open (the contract), but never silently: every degraded
53
+ // verdict is counted for diagnostics(), and one console.warn per cause per
54
+ // minute names the cause and the fix. Python does the same (logging).
55
+ /** How often (ms) admit() may warn about the same cause. */
56
+ export const DEGRADED_LOG_INTERVAL_MS = 60_000;
57
+ /** [cause, lowest status, highest status, what to fix, where]: the first matching row wins; 0..999 matches any status; where is "machine" (the check went to a machine's admission path) or "" for any address. Python has the same table. */
58
+ const FIXES = [
59
+ [
60
+ Degraded.UNAVAILABLE,
61
+ 404,
62
+ 404,
63
+ "this machine has no admission check: update Observer (a current machine answers allow while no admission policy is set), or turn admission on",
64
+ "machine",
65
+ ],
66
+ [Degraded.HTTP_ERROR, 300, 399, "the address redirects, and admit() never follows a redirect (the key must not move hosts): use the final URL", ""],
67
+ [Degraded.HTTP_ERROR, 401, 401, "the SDK key was refused: check apiKey / SUPERBASED_API_KEY, or sign in again", ""],
68
+ [Degraded.UNAVAILABLE, 403, 403, "the key may not run admission checks, or admission is off for this app", ""],
69
+ [Degraded.UNAVAILABLE, 404, 404, "no admission check at this address: point orgUrl / SUPERBASED_ORG_URL at the AI Apps gateway (not the dashboard), or turn admission on", ""],
70
+ [Degraded.HTTP_ERROR, 429, 429, "the server is rate limiting admission checks", ""],
71
+ [Degraded.HTTP_ERROR, 0, 999, "the admission server answered with an error", ""],
72
+ [Degraded.TIMEOUT, 0, 999, "no answer within the timeout: raise timeoutMs, or check the server", ""],
73
+ [Degraded.TRANSPORT, 0, 999, "nothing answered at this address: check the URL and that Observer is running", ""],
74
+ [Degraded.BAD_RESPONSE, 0, 999, "the address did not answer like an admission check: check the URL", ""],
75
+ [Degraded.ADMISSION_OFF, 0, 999, "your organization has no admission policy for AI Apps (mode off): ask an admin to turn admission on, or use destination both so this machine's policy applies", ""],
76
+ ];
77
+ /** What to fix for a degraded verdict ("" for a server-side reason). */
78
+ export function degradedFix(cause, status, url = "") {
79
+ const machine = isMachineAdmission(url);
80
+ for (const [c, lo, hi, fix, at] of FIXES) {
81
+ if (c === cause && status >= lo && status <= hi && (!at || (at === "machine") === machine))
82
+ return fix;
83
+ }
84
+ return "";
85
+ }
86
+ /** Whether url is a machine's admission check (its path). */
87
+ function isMachineAdmission(url) {
88
+ try {
89
+ return new URL(url).pathname.replace(/\/+$/, "").endsWith(MACHINE_ADMISSION_PATH);
90
+ }
91
+ catch {
92
+ return false;
93
+ }
94
+ }
95
+ /** Process-wide admit() counters, read by diagnostics(). */
96
+ export const admitStats = { degraded: 0, lastError: "", lastErrorAt: 0, loggedAt: new Map() };
97
+ export function resetAdmitStats() {
98
+ admitStats.degraded = 0;
99
+ admitStats.lastError = "";
100
+ admitStats.lastErrorAt = 0;
101
+ admitStats.loggedAt.clear();
102
+ }
103
+ /** scheme://host[:port]/path of a URL: no user info, no query. */
104
+ function where(url) {
105
+ try {
106
+ const u = new URL(url);
107
+ return `${u.protocol}//${u.host}${u.pathname}`;
108
+ }
109
+ catch {
110
+ return "the admission address";
111
+ }
112
+ }
113
+ function noteDegraded(v, url) {
114
+ try {
115
+ const detail = v.httpStatus ? `HTTP ${v.httpStatus}` : v.error || v.degraded;
116
+ const fix = degradedFix(v.degraded, v.httpStatus, url);
117
+ const outcome = v.allowed ? "admitted (fail open)" : "denied (failClosed)";
118
+ const msg = `admit() got no decision${url ? ` from ${where(url)}` : ""} (${v.degraded}: ${detail}); the message was ${outcome}` +
119
+ (fix ? `. Fix: ${fix}` : "");
120
+ const now = Date.now();
121
+ admitStats.degraded += 1;
122
+ admitStats.lastError = msg.slice(0, 500);
123
+ admitStats.lastErrorAt = now;
124
+ const key = `${v.degraded}:${v.httpStatus}`;
125
+ if (!runtime.settings?.debug && now - (admitStats.loggedAt.get(key) ?? -Infinity) < DEGRADED_LOG_INTERVAL_MS)
126
+ return;
127
+ admitStats.loggedAt.set(key, now);
128
+ console.warn(`@superbased/sdk: ${msg}`);
129
+ }
130
+ catch {
131
+ // reporting never breaks admit()
132
+ }
133
+ }
134
+ /** Forget server-advertised timeouts (tests). */
135
+ export function resetAdvertisedTimeouts() {
136
+ advertised.clear();
137
+ }
138
+ /** The server-advertised timeout remembered for url, in ms (tests). */
139
+ export function advertisedTimeoutMs(url) {
140
+ return advertised.get(url);
141
+ }
142
+ /** The first of names whose get(name) is neither null nor undefined. */
143
+ function firstPresent(get, names) {
144
+ for (const n of names) {
145
+ const v = get(n);
146
+ if (v !== null && v !== undefined)
147
+ return v;
148
+ }
149
+ return undefined;
150
+ }
151
+ function str(d, k) {
152
+ const v = d[k];
153
+ return typeof v === "string" ? v : "";
154
+ }
155
+ function num(d, k) {
156
+ const v = d[k];
157
+ return typeof v === "number" && Number.isFinite(v) ? Math.trunc(v) : 0;
158
+ }
159
+ function rememberTimeout(url, raw) {
160
+ if (raw == null || typeof raw === "boolean")
161
+ return;
162
+ const ms = Number(raw);
163
+ if (Number.isFinite(ms) && ms >= 100 && ms <= 120_000)
164
+ advertised.set(url, ms);
165
+ }
166
+ /** Normalize a parsed response body into a Verdict; null when it is not one. */
167
+ export function parseVerdict(body) {
168
+ if (body === null || typeof body !== "object" || Array.isArray(body))
169
+ return null;
170
+ const d = body;
171
+ if (typeof d.allowed !== "boolean")
172
+ return null;
173
+ const vid = d.verdict_id ?? d.id;
174
+ return {
175
+ allowed: d.allowed,
176
+ decision: str(d, "decision") || (d.allowed ? "allow" : "deny"),
177
+ severity: str(d, "severity"),
178
+ criterion: str(d, "criterion"),
179
+ reason: str(d, "reason"),
180
+ mode: str(d, "mode"),
181
+ enforceDecision: str(d, "enforce_decision"),
182
+ degraded: str(d, "degraded"),
183
+ judgeUsed: d.judge_used === true,
184
+ latencyMs: num(d, "latency_ms"),
185
+ verdictId: typeof vid === "string" || (typeof vid === "number" && Number.isFinite(vid)) ? String(vid) : "",
186
+ httpStatus: 0,
187
+ error: "",
188
+ };
189
+ }
190
+ /**
191
+ * Where the check goes and whether the SDK key rides with it (contract
192
+ * destination.md section 8): an explicit `endpoint` / `orgUrl` wins, then
193
+ * SUPERBASED_ADMISSION_ENDPOINT; after init, the destination decides (`local`
194
+ * the machine, `online` / `both` with a usable gateway the org, degraded the
195
+ * machine); before init, SUPERBASED_ORG_URL, else the machine. The configured
196
+ * key is sent to the org, or to a remote endpoint you named, never to a
197
+ * loopback address (only an explicit `apiKey` goes there).
198
+ */
199
+ function resolveTarget(opts, env) {
200
+ if (opts.endpoint)
201
+ return { url: opts.endpoint, sendKey: !isLoopbackUrl(opts.endpoint), org: "" };
202
+ if (opts.orgUrl)
203
+ return { url: opts.orgUrl.replace(/\/+$/, "") + SDK_ADMIT_PATH, sendKey: true, org: "named" };
204
+ const ep = (env.SUPERBASED_ADMISSION_ENDPOINT ?? "").trim();
205
+ if (ep)
206
+ return { url: ep, sendKey: !isLoopbackUrl(ep), org: "" };
207
+ const s = runtime.settings;
208
+ const machine = machineAdmissionUrl();
209
+ if (s && runtime.destinationSource) {
210
+ if ((runtime.destination === "online" || runtime.destination === "both") && s.orgUrl && onlineUsable(s)) {
211
+ return { url: s.orgUrl + SDK_ADMIT_PATH, sendKey: true, org: "plan" };
212
+ }
213
+ if (runtime.destination)
214
+ return { url: machine, sendKey: false, org: "" };
215
+ }
216
+ const org = (env.SUPERBASED_ORG_URL ?? "").trim();
217
+ if (org)
218
+ return { url: org.replace(/\/+$/, "") + SDK_ADMIT_PATH, sendKey: true, org: "named" };
219
+ return { url: machine, sendKey: false, org: "" };
220
+ }
221
+ /** This machine's admission check: the one discovery advertised (loopback only), else the machine URL's route. */
222
+ function machineAdmissionUrl() {
223
+ const s = runtime.settings;
224
+ return runtime.admissionUrl || (s ? s.nodeUrl + MACHINE_ADMISSION_PATH : DEFAULT_ADMISSION_ENDPOINT);
225
+ }
226
+ function activeTraceId() {
227
+ try {
228
+ const ctx = trace.getActiveSpan()?.spanContext();
229
+ if (ctx && /^[0-9a-f]{32}$/.test(ctx.traceId) && !/^0+$/.test(ctx.traceId))
230
+ return ctx.traceId;
231
+ }
232
+ catch {
233
+ // ignore
234
+ }
235
+ return "";
236
+ }
237
+ function stampSpan(v) {
238
+ try {
239
+ const sp = trace.getActiveSpan();
240
+ if (!sp || !sp.isRecording())
241
+ return;
242
+ sp.setAttribute("sbo.admission.allowed", v.allowed);
243
+ sp.setAttribute("sbo.admission.decision", v.decision);
244
+ if (v.verdictId)
245
+ sp.setAttribute("sbo.admission.verdict_id", v.verdictId);
246
+ if (v.degraded)
247
+ sp.setAttribute("sbo.admission.degraded", v.degraded);
248
+ }
249
+ catch {
250
+ // ignore
251
+ }
252
+ }
253
+ function degraded(cause, failClosed, started, httpStatus = 0, error = "") {
254
+ return {
255
+ allowed: !failClosed,
256
+ decision: failClosed ? "deny" : "allow",
257
+ severity: "",
258
+ criterion: "",
259
+ reason: failClosed ? "admission check unavailable" : "",
260
+ mode: "",
261
+ enforceDecision: "",
262
+ degraded: cause,
263
+ judgeUsed: false,
264
+ latencyMs: Math.round(Date.now() - started),
265
+ verdictId: "",
266
+ httpStatus,
267
+ error: error.slice(0, 300),
268
+ };
269
+ }
270
+ /**
271
+ * The `service.name` the app's spans carry: the resource of the last span
272
+ * the SDK saw (its own provider's, or the app's when attached), else the
273
+ * configured name (serviceName, SUPERBASED_SERVICE_NAME, OTEL_SERVICE_NAME,
274
+ * OTEL_RESOURCE_ATTRIBUTES, custom-app). OpenTelemetry's `unknown_service`
275
+ * default is no name.
276
+ */
277
+ export function serviceName(env) {
278
+ const seen = runtime.resourceService.trim();
279
+ if (seen && !seen.startsWith("unknown_service"))
280
+ return seen;
281
+ return runtime.settings?.serviceName || resolveServiceName(undefined, env);
282
+ }
283
+ /**
284
+ * Check an incoming user message against the app's admission policy BEFORE
285
+ * running the agent, and get an allow/flag/ask/deny verdict.
286
+ *
287
+ * ```ts
288
+ * const v = await admit(userMessage, { user: "alice", session: "s1" });
289
+ * if (!v.allowed) return v.reason; // or route to a human on `ask`
290
+ * ```
291
+ *
292
+ * Never rejects. When no decision can be obtained it admits, unless
293
+ * `failClosed` is set; `degraded` says why.
294
+ */
295
+ export async function admit(message, opts = {}) {
296
+ const started = Date.now();
297
+ const env = (typeof process !== "undefined" ? process.env : {});
298
+ const failClosed = opts.failClosed ?? envFlag(env, ["SUPERBASED_ADMISSION_FAIL_CLOSED"], false);
299
+ let url = DEFAULT_ADMISSION_ENDPOINT;
300
+ try {
301
+ // The org or the machine is known only once discovery answered (review E-33).
302
+ await destinationKnown();
303
+ const target = resolveTarget(opts, env);
304
+ url = target.url;
305
+ // Identity: the argument, else the request scope (propagateAttributes),
306
+ // else init's process-wide value (contract section 2), as in Python.
307
+ const cur = getCurrentAttributes();
308
+ const s = runtime.settings;
309
+ const payload = JSON.stringify({
310
+ text: message == null ? "" : String(message),
311
+ tenant: opts.tenant || cur.tenant || s?.tenant || "",
312
+ user: opts.user || cur.user || s?.user || "",
313
+ session: opts.session || cur.sessionId || s?.sessionId || "",
314
+ // service.name: service-scoped budget caps bind on it, on the machine
315
+ // and on the org.
316
+ service: serviceName(env),
317
+ trace_id: opts.traceId ?? activeTraceId(),
318
+ request_id: opts.requestId ?? "",
319
+ });
320
+ const key = opts.apiKey ?? (target.sendKey ? (runtime.settings?.apiKey || env.SUPERBASED_API_KEY || "") : "");
321
+ let v = await post(url, key, payload, opts, failClosed, started);
322
+ if (target.org && !v.degraded && v.mode === "off") {
323
+ // The org has no admission policy, so it made no decision (L-05).
324
+ // Under destination both, this machine's policy decides (the key never
325
+ // goes there); otherwise the verdict says nothing decided.
326
+ if (target.org === "plan" && runtime.destination === "both") {
327
+ url = machineAdmissionUrl();
328
+ v = await post(url, "", payload, { ...opts, headers: withoutAuthorization(opts.headers) }, failClosed, started);
329
+ }
330
+ else {
331
+ v = degraded(Degraded.ADMISSION_OFF, failClosed, started, v.httpStatus, "the organization answered mode off");
332
+ noteDegraded(v, url);
333
+ }
334
+ }
335
+ stampSpan(v);
336
+ return v;
337
+ }
338
+ catch (err) {
339
+ // The last line of defence: never reject into the host.
340
+ const v = degraded(Degraded.BAD_RESPONSE, failClosed, started, 0, String(err));
341
+ stampSpan(v);
342
+ noteDegraded(v, url);
343
+ return v;
344
+ }
345
+ }
346
+ function withoutAuthorization(h) {
347
+ if (!h)
348
+ return h;
349
+ return Object.fromEntries(Object.entries(h).filter(([k]) => k.toLowerCase() !== "authorization"));
350
+ }
351
+ /** One admission request to url; a failure is a counted degraded verdict. The caller stamps the span. */
352
+ async function post(url, key, payload, opts, failClosed, started) {
353
+ const fail = (cause, status = 0, error = "") => {
354
+ const v = degraded(cause, failClosed, started, status, error);
355
+ noteDegraded(v, url);
356
+ return v;
357
+ };
358
+ let timer;
359
+ try {
360
+ const timeoutMs = opts.timeoutMs ?? advertised.get(url) ?? DEFAULT_ADMIT_TIMEOUT_MS;
361
+ const headers = { "Content-Type": "application/json", Accept: "application/json" };
362
+ if (key)
363
+ headers.Authorization = `Bearer ${key}`;
364
+ if (opts.headers)
365
+ Object.assign(headers, opts.headers);
366
+ const controller = new AbortController();
367
+ let timedOut = false;
368
+ timer = setTimeout(() => {
369
+ timedOut = true;
370
+ controller.abort();
371
+ }, timeoutMs);
372
+ let resp;
373
+ try {
374
+ resp = await fetch(url, {
375
+ method: "POST",
376
+ headers,
377
+ body: payload,
378
+ signal: controller.signal,
379
+ // Never follow a redirect: the key must not ride to a host it was not sent to (R-B26).
380
+ redirect: "manual",
381
+ });
382
+ }
383
+ catch (err) {
384
+ if (timedOut)
385
+ return fail(Degraded.TIMEOUT, 0, `timed out after ${timeoutMs}ms`);
386
+ const cause = err.cause;
387
+ return fail(Degraded.TRANSPORT, 0, cause?.code ?? cause?.message ?? String(err));
388
+ }
389
+ rememberTimeout(url, firstPresent((n) => resp.headers.get(n), TIMEOUT_HEADERS));
390
+ if (resp.status === 403 || resp.status === 404) {
391
+ void resp.body?.cancel().catch(() => undefined);
392
+ return fail(Degraded.UNAVAILABLE, resp.status, `HTTP ${resp.status}`);
393
+ }
394
+ if (!resp.ok) {
395
+ void resp.body?.cancel().catch(() => undefined);
396
+ return fail(Degraded.HTTP_ERROR, resp.status, `HTTP ${resp.status}`);
397
+ }
398
+ let text;
399
+ try {
400
+ text = await resp.text();
401
+ }
402
+ catch (err) {
403
+ if (timedOut)
404
+ return fail(Degraded.TIMEOUT, resp.status, `timed out after ${timeoutMs}ms`);
405
+ return fail(Degraded.TRANSPORT, resp.status, String(err));
406
+ }
407
+ let body;
408
+ try {
409
+ body = JSON.parse(text);
410
+ }
411
+ catch (err) {
412
+ return fail(Degraded.BAD_RESPONSE, resp.status, String(err));
413
+ }
414
+ const v = parseVerdict(body);
415
+ if (!v) {
416
+ const kind = body === null ? "null" : Array.isArray(body) ? "array" : typeof body;
417
+ return fail(Degraded.BAD_RESPONSE, resp.status, kind === "object" ? "response field 'allowed' is missing or not a boolean" : `response body is ${kind}, not an object`);
418
+ }
419
+ const fields = body;
420
+ rememberTimeout(url, firstPresent((n) => fields[n], TIMEOUT_FIELDS));
421
+ v.httpStatus = resp.status;
422
+ return v;
423
+ }
424
+ catch (err) {
425
+ return fail(Degraded.BAD_RESPONSE, 0, String(err));
426
+ }
427
+ finally {
428
+ if (timer)
429
+ clearTimeout(timer);
430
+ }
431
+ }
432
+ //# sourceMappingURL=admit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"admit.js","sourceRoot":"","sources":["../../src/admit.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAE3C,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAY,MAAM,aAAa,CAAC;AAClF,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAEzD,2FAA2F;AAC3F,MAAM,CAAC,MAAM,0BAA0B,GAAG,+CAA+C,CAAC;AAC1F,+CAA+C;AAC/C,MAAM,sBAAsB,GAAG,0BAA0B,CAAC;AAC1D,8EAA8E;AAC9E,MAAM,CAAC,MAAM,cAAc,GAAG,e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AAO,IAAI,CACT,QAAQ,CAAC,YAAY,EACrB,IAAI,CAAC,MAAM,EACX,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,sDAAsD,CAAC,CAAC,CAAC,oBAAoB,IAAI,iBAAiB,CACvH,CAAC;QACJ,CAAC;QACD,MAAM,MAAM,GAAG,IAA+B,CAAC;QAC/C,eAAe,CAAC,GAAG,EAAE,YAAY,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,cAAc,CAAC,CAAC,CAAC;QACrE,CAAC,CAAC,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC;QAC3B,OAAO,CAAC,CAAC;IACX,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,IAAI,CAAC,QAAQ,CAAC,YAAY,EAAE,CAAC,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;IACrD,CAAC;YAAS,CAAC;QACT,IAAI,KAAK;YAAE,YAAY,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;AACH,CAAC","sourcesContent":["/**\n * `admit()`: the input-admission pre-flight check (admission spec §6.1).\n *\n * Never throws or rejects. Any failure (transport, timeout, HTTP error, a body\n * that is not a JSON object, a field of the wrong type) yields a degraded\n * verdict that admits (fail open, the default) or denies (`failClosed`).\n */\n\nimport { trace } from \"@opentelemetry/api\";\n\nimport { envFlag, onlineUsable, resolveServiceName, type Env } from \"./config.js\";\nimport { getCurrentAttributes } from \"./context.js\";\nimport { isLoopbackUrl } from \"./destination.js\";\nimport { destinationKnown, runtime } from \"./runtime.js\";\n\n/** Default admission-check endpoint: this machine's Observer API on the dashboard port. */\nexport const DEFAULT_ADMISSION_ENDPOINT = \"http://127.0.0.1:8081/api/obs/admission/check\";\n/** The path of a machine's admission check. */\nconst MACHINE_ADMISSION_PATH = \"/api/obs/admission/check\";\n/** Path of the org SDK control API's admission endpoint, under an org URL. */\nexport const SDK_ADMIT_PATH = \"/v1/sdk/admit\";\n/**\n * Default client timeout (ms). Longer than the server's 10 s judge budget, so\n * the client does not fail open on a request the server would still decide.\n * A server that advertises a recommended timeout (the\n * `recommended_client_timeout_ms` body field or the\n * `X-SBO-Recommended-Timeout-Ms` header, sent by both the org SDK control API\n * and the local machine) overrides it for later calls.\n */\nexport const DEFAULT_ADMIT_TIMEOUT_MS = 12_000;\n\n/**\n * The advertised-timeout names, canonical first. The second of each pair is\n * the pre-release spelling, still read so an older server keeps working.\n */\nexport const TIMEOUT_HEADERS = [\"x-sbo-recommended-timeout-ms\", \"x-superbased-admit-timeout-ms\"] as const;\nexport const TIMEOUT_FIELDS = [\"recommended_client_timeout_ms\", \"recommended_timeout_ms\"] as const;\n\n/** Client-side degraded reasons (`Verdict.degraded`). Server values pass through. */\nexport const Degraded = {\n /** HTTP 403/404: admission is off on the server or not permitted. */\n UNAVAILABLE: \"admission-unavailable\",\n TIMEOUT: \"client-timeout\",\n TRANSPORT: \"client-transport\",\n HTTP_ERROR: \"client-http-error\",\n BAD_RESPONSE: \"client-bad-response\",\n /**\n * The organization answered mode `off`: it has no admission policy, so it\n * made no decision (live finding L-05, ruling D29). Under destination `both`\n * the SDK then asks this machine; otherwise the verdict is degraded.\n */\n ADMISSION_OFF: \"admission-off\",\n} as const;\n\n/** The result of an {@link admit} check. */\nexport interface Verdict {\n /**\n * What the app should honour. In `observe` mode the server always returns\n * `true` and records the shadow verdict; in `enforce` mode it returns the\n * real decision (`ask`/`deny` → `false`, `flag` still admits).\n */\n allowed: boolean;\n /** The raw decision, one of: allow / flag / ask / deny. */\n decision: string;\n severity: string;\n /** The criterion id that fired, if any. */\n criterion: string;\n /** A short string to surface to the user on a block. */\n reason: string;\n mode: string;\n /** What enforce mode WOULD decide, so you can measure before flipping. */\n enforceDecision: string;\n /** Empty for a clean decision; otherwise why it is not one (see {@link Degraded}). */\n degraded: string;\n /** Whether the server consulted its LLM judge (server field `judge_used`). */\n judgeUsed: boolean;\n /** Server-side decision latency; for a client-degraded verdict, the client's elapsed time (`latency_ms`). */\n latencyMs: number;\n /** The server's id for the recorded verdict, when it returns one. */\n verdictId: string;\n /** HTTP status of the response (0 when none arrived). */\n httpStatus: number;\n /** Detail for a client-degraded verdict. */\n error: string;\n}\n\nexport interface AdmitOptions {\n /** The app's tenant. Defaults to the request scope's (`propagateAttributes`), then `init`'s. */\n tenant?: string;\n /** The app's end user. Defaults to the request scope's, then `init`'s. */\n user?: string;\n /** The app's session. Defaults to the request scope's `sessionId`, then `init`'s. */\n session?: string;\n /** Defaults to the active span's trace id. */\n traceId?: string;\n requestId?: string;\n /** Full admission URL. Defaults to $SUPERBASED_ADMISSION_ENDPOINT, then the destination (see resolveTarget), then this machine. */\n endpoint?: string;\n /** Org base URL; the check goes to `<orgUrl>/v1/sdk/admit`. Env: SUPERBASED_ORG_URL. */\n orgUrl?: string;\n /**\n * SDK credential, sent as `Authorization: Bearer`. Env: SUPERBASED_API_KEY.\n * Only an explicit `apiKey` goes to a loopback endpoint; the configured key\n * rides only to an org URL or an explicit remote endpoint.\n */\n apiKey?: string;\n /** Extra or overriding request headers. */\n headers?: Record<string, string>;\n /** Per-call timeout in ms. Default: the server-advertised timeout, else 12000. */\n timeoutMs?: number;\n /** Deny when no decision could be obtained. Env: SUPERBASED_ADMISSION_FAIL_CLOSED. Default false. */\n failClosed?: boolean;\n}\n\nconst advertised = new Map<string, number>();\n\n// --- saying so when admit() could not decide (review E-39) -------------------\n//\n// admit() fails open (the contract), but never silently: every degraded\n// verdict is counted for diagnostics(), and one console.warn per cause per\n// minute names the cause and the fix. Python does the same (logging).\n\n/** How often (ms) admit() may warn about the same cause. */\nexport const DEGRADED_LOG_INTERVAL_MS = 60_000;\n\n/** [cause, lowest status, highest status, what to fix, where]: the first matching row wins; 0..999 matches any status; where is \"machine\" (the check went to a machine's admission path) or \"\" for any address. Python has the same table. */\nconst FIXES: ReadonlyArray<[string, number, number, string, string]> = [\n [\n Degraded.UNAVAILABLE,\n 404,\n 404,\n \"this machine has no admission check: update Observer (a current machine answers allow while no admission policy is set), or turn admission on\",\n \"machine\",\n ],\n [Degraded.HTTP_ERROR, 300, 399, \"the address redirects, and admit() never follows a redirect (the key must not move hosts): use the final URL\", \"\"],\n [Degraded.HTTP_ERROR, 401, 401, \"the SDK key was refused: check apiKey / SUPERBASED_API_KEY, or sign in again\", \"\"],\n [Degraded.UNAVAILABLE, 403, 403, \"the key may not run admission checks, or admission is off for this app\", \"\"],\n [Degraded.UNAVAILABLE, 404, 404, \"no admission check at this address: point orgUrl / SUPERBASED_ORG_URL at the AI Apps gateway (not the dashboard), or turn admission on\", \"\"],\n [Degraded.HTTP_ERROR, 429, 429, \"the server is rate limiting admission checks\", \"\"],\n [Degraded.HTTP_ERROR, 0, 999, \"the admission server answered with an error\", \"\"],\n [Degraded.TIMEOUT, 0, 999, \"no answer within the timeout: raise timeoutMs, or check the server\", \"\"],\n [Degraded.TRANSPORT, 0, 999, \"nothing answered at this address: check the URL and that Observer is running\", \"\"],\n [Degraded.BAD_RESPONSE, 0, 999, \"the address did not answer like an admission check: check the URL\", \"\"],\n [Degraded.ADMISSION_OFF, 0, 999, \"your organization has no admission policy for AI Apps (mode off): ask an admin to turn admission on, or use destination both so this machine's policy applies\", \"\"],\n];\n\n/** What to fix for a degraded verdict (\"\" for a server-side reason). */\nexport function degradedFix(cause: string, status: number, url = \"\"): string {\n const machine = isMachineAdmission(url);\n for (const [c, lo, hi, fix, at] of FIXES) {\n if (c === cause && status >= lo && status <= hi && (!at || (at === \"machine\") === machine)) return fix;\n }\n return \"\";\n}\n\n/** Whether url is a machine's admission check (its path). */\nfunction isMachineAdmission(url: string): boolean {\n try {\n return new URL(url).pathname.replace(/\\/+$/, \"\").endsWith(MACHINE_ADMISSION_PATH);\n } catch {\n return false;\n }\n}\n\n/** Process-wide admit() counters, read by diagnostics(). */\nexport const admitStats = { degraded: 0, lastError: \"\", lastErrorAt: 0, loggedAt: new Map<string, number>() };\n\nexport function resetAdmitStats(): void {\n admitStats.degraded = 0;\n admitStats.lastError = \"\";\n admitStats.lastErrorAt = 0;\n admitStats.loggedAt.clear();\n}\n\n/** scheme://host[:port]/path of a URL: no user info, no query. */\nfunction where(url: string): string {\n try {\n const u = new URL(url);\n return `${u.protocol}//${u.host}${u.pathname}`;\n } catch {\n return \"the admission address\";\n }\n}\n\nfunction noteDegraded(v: Verdict, url: string): void {\n try {\n const detail = v.httpStatus ? `HTTP ${v.httpStatus}` : v.error || v.degraded;\n const fix = degradedFix(v.degraded, v.httpStatus, url);\n const outcome = v.allowed ? \"admitted (fail open)\" : \"denied (failClosed)\";\n const msg =\n `admit() got no decision${url ? ` from ${where(url)}` : \"\"} (${v.degraded}: ${detail}); the message was ${outcome}` +\n (fix ? `. Fix: ${fix}` : \"\");\n const now = Date.now();\n admitStats.degraded += 1;\n admitStats.lastError = msg.slice(0, 500);\n admitStats.lastErrorAt = now;\n const key = `${v.degraded}:${v.httpStatus}`;\n if (!runtime.settings?.debug && now - (admitStats.loggedAt.get(key) ?? -Infinity) < DEGRADED_LOG_INTERVAL_MS) return;\n admitStats.loggedAt.set(key, now);\n console.warn(`@superbased/sdk: ${msg}`);\n } catch {\n // reporting never breaks admit()\n }\n}\n\n/** Forget server-advertised timeouts (tests). */\nexport function resetAdvertisedTimeouts(): void {\n advertised.clear();\n}\n\n/** The server-advertised timeout remembered for url, in ms (tests). */\nexport function advertisedTimeoutMs(url: string): number | undefined {\n return advertised.get(url);\n}\n\n/** The first of names whose get(name) is neither null nor undefined. */\nfunction firstPresent(get: (name: string) => unknown, names: readonly string[]): unknown {\n for (const n of names) {\n const v = get(n);\n if (v !== null && v !== undefined) return v;\n }\n return undefined;\n}\n\nfunction str(d: Record<string, unknown>, k: string): string {\n const v = d[k];\n return typeof v === \"string\" ? v : \"\";\n}\n\nfunction num(d: Record<string, unknown>, k: string): number {\n const v = d[k];\n return typeof v === \"number\" && Number.isFinite(v) ? Math.trunc(v) : 0;\n}\n\nfunction rememberTimeout(url: string, raw: unknown): void {\n if (raw == null || typeof raw === \"boolean\") return;\n const ms = Number(raw);\n if (Number.isFinite(ms) && ms >= 100 && ms <= 120_000) advertised.set(url, ms);\n}\n\n/** Normalize a parsed response body into a Verdict; null when it is not one. */\nexport function parseVerdict(body: unknown): Verdict | null {\n if (body === null || typeof body !== \"object\" || Array.isArray(body)) return null;\n const d = body as Record<string, unknown>;\n if (typeof d.allowed !== \"boolean\") return null;\n const vid = d.verdict_id ?? d.id;\n return {\n allowed: d.allowed,\n decision: str(d, \"decision\") || (d.allowed ? \"allow\" : \"deny\"),\n severity: str(d, \"severity\"),\n criterion: str(d, \"criterion\"),\n reason: str(d, \"reason\"),\n mode: str(d, \"mode\"),\n enforceDecision: str(d, \"enforce_decision\"),\n degraded: str(d, \"degraded\"),\n judgeUsed: d.judge_used === true,\n latencyMs: num(d, \"latency_ms\"),\n verdictId: typeof vid === \"string\" || (typeof vid === \"number\" && Number.isFinite(vid)) ? String(vid) : \"\",\n httpStatus: 0,\n error: \"\",\n };\n}\n\n/**\n * Where the check goes and whether the SDK key rides with it (contract\n * destination.md section 8): an explicit `endpoint` / `orgUrl` wins, then\n * SUPERBASED_ADMISSION_ENDPOINT; after init, the destination decides (`local`\n * the machine, `online` / `both` with a usable gateway the org, degraded the\n * machine); before init, SUPERBASED_ORG_URL, else the machine. The configured\n * key is sent to the org, or to a remote endpoint you named, never to a\n * loopback address (only an explicit `apiKey` goes there).\n */\nfunction resolveTarget(opts: AdmitOptions, env: Env): Target {\n if (opts.endpoint) return { url: opts.endpoint, sendKey: !isLoopbackUrl(opts.endpoint), org: \"\" };\n if (opts.orgUrl) return { url: opts.orgUrl.replace(/\\/+$/, \"\") + SDK_ADMIT_PATH, sendKey: true, org: \"named\" };\n const ep = (env.SUPERBASED_ADMISSION_ENDPOINT ?? \"\").trim();\n if (ep) return { url: ep, sendKey: !isLoopbackUrl(ep), org: \"\" };\n const s = runtime.settings;\n const machine = machineAdmissionUrl();\n if (s && runtime.destinationSource) {\n if ((runtime.destination === \"online\" || runtime.destination === \"both\") && s.orgUrl && onlineUsable(s)) {\n return { url: s.orgUrl + SDK_ADMIT_PATH, sendKey: true, org: \"plan\" };\n }\n if (runtime.destination) return { url: machine, sendKey: false, org: \"\" };\n }\n const org = (env.SUPERBASED_ORG_URL ?? \"\").trim();\n if (org) return { url: org.replace(/\\/+$/, \"\") + SDK_ADMIT_PATH, sendKey: true, org: \"named\" };\n return { url: machine, sendKey: false, org: \"\" };\n}\n\n/** Where the check goes; `org` says whether it is the org init's destination chose (plan) or one the caller named. */\ninterface Target {\n url: string;\n sendKey: boolean;\n org: \"\" | \"plan\" | \"named\";\n}\n\n/** This machine's admission check: the one discovery advertised (loopback only), else the machine URL's route. */\nfunction machineAdmissionUrl(): string {\n const s = runtime.settings;\n return runtime.admissionUrl || (s ? s.nodeUrl + MACHINE_ADMISSION_PATH : DEFAULT_ADMISSION_ENDPOINT);\n}\n\nfunction activeTraceId(): string {\n try {\n const ctx = trace.getActiveSpan()?.spanContext();\n if (ctx && /^[0-9a-f]{32}$/.test(ctx.traceId) && !/^0+$/.test(ctx.traceId)) return ctx.traceId;\n } catch {\n // ignore\n }\n return \"\";\n}\n\nfunction stampSpan(v: Verdict): void {\n try {\n const sp = trace.getActiveSpan();\n if (!sp || !sp.isRecording()) return;\n sp.setAttribute(\"sbo.admission.allowed\", v.allowed);\n sp.setAttribute(\"sbo.admission.decision\", v.decision);\n if (v.verdictId) sp.setAttribute(\"sbo.admission.verdict_id\", v.verdictId);\n if (v.degraded) sp.setAttribute(\"sbo.admission.degraded\", v.degraded);\n } catch {\n // ignore\n }\n}\n\nfunction degraded(cause: string, failClosed: boolean, started: number, httpStatus = 0, error = \"\"): Verdict {\n return {\n allowed: !failClosed,\n decision: failClosed ? \"deny\" : \"allow\",\n severity: \"\",\n criterion: \"\",\n reason: failClosed ? \"admission check unavailable\" : \"\",\n mode: \"\",\n enforceDecision: \"\",\n degraded: cause,\n judgeUsed: false,\n latencyMs: Math.round(Date.now() - started),\n verdictId: \"\",\n httpStatus,\n error: error.slice(0, 300),\n };\n}\n\n/**\n * The `service.name` the app's spans carry: the resource of the last span\n * the SDK saw (its own provider's, or the app's when attached), else the\n * configured name (serviceName, SUPERBASED_SERVICE_NAME, OTEL_SERVICE_NAME,\n * OTEL_RESOURCE_ATTRIBUTES, custom-app). OpenTelemetry's `unknown_service`\n * default is no name.\n */\nexport function serviceName(env: Env): string {\n const seen = runtime.resourceService.trim();\n if (seen && !seen.startsWith(\"unknown_service\")) return seen;\n return runtime.settings?.serviceName || resolveServiceName(undefined, env);\n}\n\n/**\n * Check an incoming user message against the app's admission policy BEFORE\n * running the agent, and get an allow/flag/ask/deny verdict.\n *\n * ```ts\n * const v = await admit(userMessage, { user: \"alice\", session: \"s1\" });\n * if (!v.allowed) return v.reason; // or route to a human on `ask`\n * ```\n *\n * Never rejects. When no decision can be obtained it admits, unless\n * `failClosed` is set; `degraded` says why.\n */\nexport async function admit(message: string, opts: AdmitOptions = {}): Promise<Verdict> {\n const started = Date.now();\n const env = (typeof process !== \"undefined\" ? process.env : {}) as Env;\n const failClosed = opts.failClosed ?? envFlag(env, [\"SUPERBASED_ADMISSION_FAIL_CLOSED\"], false);\n let url = DEFAULT_ADMISSION_ENDPOINT;\n try {\n // The org or the machine is known only once discovery answered (review E-33).\n await destinationKnown();\n const target = resolveTarget(opts, env);\n url = target.url;\n // Identity: the argument, else the request scope (propagateAttributes),\n // else init's process-wide value (contract section 2), as in Python.\n const cur = getCurrentAttributes();\n const s = runtime.settings;\n const payload = JSON.stringify({\n text: message == null ? \"\" : String(message),\n tenant: opts.tenant || cur.tenant || s?.tenant || \"\",\n user: opts.user || cur.user || s?.user || \"\",\n session: opts.session || cur.sessionId || s?.sessionId || \"\",\n // service.name: service-scoped budget caps bind on it, on the machine\n // and on the org.\n service: serviceName(env),\n trace_id: opts.traceId ?? activeTraceId(),\n request_id: opts.requestId ?? \"\",\n });\n const key = opts.apiKey ?? (target.sendKey ? (runtime.settings?.apiKey || env.SUPERBASED_API_KEY || \"\") : \"\");\n let v = await post(url, key, payload, opts, failClosed, started);\n if (target.org && !v.degraded && v.mode === \"off\") {\n // The org has no admission policy, so it made no decision (L-05).\n // Under destination both, this machine's policy decides (the key never\n // goes there); otherwise the verdict says nothing decided.\n if (target.org === \"plan\" && runtime.destination === \"both\") {\n url = machineAdmissionUrl();\n v = await post(url, \"\", payload, { ...opts, headers: withoutAuthorization(opts.headers) }, failClosed, started);\n } else {\n v = degraded(Degraded.ADMISSION_OFF, failClosed, started, v.httpStatus, \"the organization answered mode off\");\n noteDegraded(v, url);\n }\n }\n stampSpan(v);\n return v;\n } catch (err) {\n // The last line of defence: never reject into the host.\n const v = degraded(Degraded.BAD_RESPONSE, failClosed, started, 0, String(err));\n stampSpan(v);\n noteDegraded(v, url);\n return v;\n }\n}\n\nfunction withoutAuthorization(h: Record<string, string> | undefined): Record<string, string> | undefined {\n if (!h) return h;\n return Object.fromEntries(Object.entries(h).filter(([k]) => k.toLowerCase() !== \"authorization\"));\n}\n\n/** One admission request to url; a failure is a counted degraded verdict. The caller stamps the span. */\nasync function post(url: string, key: string, payload: string, opts: AdmitOptions, failClosed: boolean, started: number): Promise<Verdict> {\n const fail = (cause: string, status = 0, error = \"\"): Verdict => {\n const v = degraded(cause, failClosed, started, status, error);\n noteDegraded(v, url);\n return v;\n };\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const timeoutMs = opts.timeoutMs ?? advertised.get(url) ?? DEFAULT_ADMIT_TIMEOUT_MS;\n const headers: Record<string, string> = { \"Content-Type\": \"application/json\", Accept: \"application/json\" };\n if (key) headers.Authorization = `Bearer ${key}`;\n if (opts.headers) Object.assign(headers, opts.headers);\n const controller = new AbortController();\n let timedOut = false;\n timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeoutMs);\n let resp: Response;\n try {\n resp = await fetch(url, {\n method: \"POST\",\n headers,\n body: payload,\n signal: controller.signal,\n // Never follow a redirect: the key must not ride to a host it was not sent to (R-B26).\n redirect: \"manual\",\n });\n } catch (err) {\n if (timedOut) return fail(Degraded.TIMEOUT, 0, `timed out after ${timeoutMs}ms`);\n const cause = (err as { cause?: { code?: string; message?: string } }).cause;\n return fail(Degraded.TRANSPORT, 0, cause?.code ?? cause?.message ?? String(err));\n }\n rememberTimeout(url, firstPresent((n) => resp.headers.get(n), TIMEOUT_HEADERS));\n if (resp.status === 403 || resp.status === 404) {\n void resp.body?.cancel().catch(() => undefined);\n return fail(Degraded.UNAVAILABLE, resp.status, `HTTP ${resp.status}`);\n }\n if (!resp.ok) {\n void resp.body?.cancel().catch(() => undefined);\n return fail(Degraded.HTTP_ERROR, resp.status, `HTTP ${resp.status}`);\n }\n let text: string;\n try {\n text = await resp.text();\n } catch (err) {\n if (timedOut) return fail(Degraded.TIMEOUT, resp.status, `timed out after ${timeoutMs}ms`);\n return fail(Degraded.TRANSPORT, resp.status, String(err));\n }\n let body: unknown;\n try {\n body = JSON.parse(text);\n } catch (err) {\n return fail(Degraded.BAD_RESPONSE, resp.status, String(err));\n }\n const v = parseVerdict(body);\n if (!v) {\n const kind = body === null ? \"null\" : Array.isArray(body) ? \"array\" : typeof body;\n return fail(\n Degraded.BAD_RESPONSE,\n resp.status,\n kind === \"object\" ? \"response field 'allowed' is missing or not a boolean\" : `response body is ${kind}, not an object`,\n );\n }\n const fields = body as Record<string, unknown>;\n rememberTimeout(url, firstPresent((n) => fields[n], TIMEOUT_FIELDS));\n v.httpStatus = resp.status;\n return v;\n } catch (err) {\n return fail(Degraded.BAD_RESPONSE, 0, String(err));\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n"]}
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Every span-attribute key the SDK writes, in one place.
3
+ *
4
+ * The keys come from the Observer vocabulary: `internal/genaiattr` (GenAI
5
+ * semconv pinned to open-telemetry/semantic-conventions-genai at
6
+ * `SEMCONV_COMMIT`, plus the OpenInference names Observer reads) and
7
+ * `internal/otelident` (identity), plus the SDK-owned `sbo.*` keys of
8
+ * contract sdk-api-surface.md section 9. The SDK never invents a key:
9
+ * `vocabulary.test.mjs` checks each one against those Go files and against
10
+ * `sdk/contract/sdk-attribute-keys.json`.
11
+ */
12
+ /** The pinned GenAI semconv state (`internal/genaiattr.SemconvCommit`). */
13
+ export declare const SEMCONV_COMMIT = "76e0c19e7fe11dc693fe258642363a438af4d3aa";
14
+ export declare const SEMCONV_SCHEMA_URL = "https://opentelemetry.io/schemas/gen-ai-dev/1.42.0-dev";
15
+ export declare const K: {
16
+ readonly spanKind: "openinference.span.kind";
17
+ readonly operation: "gen_ai.operation.name";
18
+ readonly provider: "gen_ai.provider.name";
19
+ readonly systemLegacy: "gen_ai.system";
20
+ readonly requestModel: "gen_ai.request.model";
21
+ readonly responseModel: "gen_ai.response.model";
22
+ readonly responseId: "gen_ai.response.id";
23
+ readonly finishReasons: "gen_ai.response.finish_reasons";
24
+ readonly inputTokens: "gen_ai.usage.input_tokens";
25
+ readonly totalTokens: "gen_ai.usage.total_tokens";
26
+ readonly outputTokens: "gen_ai.usage.output_tokens";
27
+ readonly cacheReadTokens: "gen_ai.usage.cache_read.input_tokens";
28
+ readonly cacheWriteTokens: "gen_ai.usage.cache_write.input_tokens";
29
+ readonly reasoningTokens: "gen_ai.usage.reasoning.output_tokens";
30
+ readonly cost: "gen_ai.usage.cost";
31
+ readonly toolName: "gen_ai.tool.name";
32
+ readonly toolCallId: "gen_ai.tool.call.id";
33
+ readonly toolArguments: "gen_ai.tool.call.arguments";
34
+ readonly toolResult: "gen_ai.tool.call.result";
35
+ readonly agentName: "gen_ai.agent.name";
36
+ readonly agentId: "gen_ai.agent.id";
37
+ readonly retrievalQuery: "gen_ai.retrieval.query.text";
38
+ readonly retrievalDocuments: "gen_ai.retrieval.documents";
39
+ readonly inputMessages: "gen_ai.input.messages";
40
+ readonly outputMessages: "gen_ai.output.messages";
41
+ readonly systemInstructions: "gen_ai.system_instructions";
42
+ readonly errorType: "error.type";
43
+ readonly oiModel: "llm.model_name";
44
+ readonly oiProvider: "llm.provider";
45
+ readonly oiToolName: "tool.name";
46
+ readonly oiAgentName: "agent.name";
47
+ readonly inputValue: "input.value";
48
+ readonly outputValue: "output.value";
49
+ readonly requestId: "request_id";
50
+ readonly tenant: "sbo.tenant";
51
+ readonly user: "sbo.user";
52
+ readonly session: "session.id";
53
+ readonly environment: "sbo.environment";
54
+ readonly release: "sbo.release";
55
+ readonly tags: "sbo.tags";
56
+ readonly metadataPrefix: "sbo.metadata.";
57
+ readonly serviceVersion: "service.version";
58
+ readonly deploymentEnvironment: "deployment.environment.name";
59
+ readonly sdk: "sbo.sdk";
60
+ readonly experimentRunId: "sbo.experiment.run_id";
61
+ readonly experimentItemId: "sbo.experiment.item_id";
62
+ readonly promptName: "sbo.prompt.name";
63
+ readonly promptVersion: "sbo.prompt.version";
64
+ readonly promptLabel: "sbo.prompt.label";
65
+ /** Which side of a staged rollout served the prompt (prompts.md v2 section 9.4; genaiattr field prompt_cohort, lane C8). */
66
+ readonly promptCohort: "sbo.prompt.cohort";
67
+ readonly admissionAllowed: "sbo.admission.allowed";
68
+ readonly admissionDecision: "sbo.admission.decision";
69
+ readonly admissionVerdictId: "sbo.admission.verdict_id";
70
+ readonly admissionDegraded: "sbo.admission.degraded";
71
+ };
72
+ /**
73
+ * Content-bearing keys and prefixes: the ones `captureContent`, the
74
+ * `maxContentChars` clip and the `mask` hook apply to at export, whichever
75
+ * instrumentation wrote them (genaiattr content fields, every dialect).
76
+ */
77
+ export declare const CONTENT_KEYS: ReadonlySet<string>;
78
+ export declare const CONTENT_PREFIXES: readonly string[];
79
+ /**
80
+ * Content an instrumentation emits under keys the Go vocabulary does not map
81
+ * (yet): the contract's `extra_content_prefixes`, exactly as Python's
82
+ * EXTRA_CONTENT_PREFIXES. The SDK never writes them, but an instrumentation
83
+ * does, so they are masked, clipped and dropped like the rest: content never
84
+ * leaves unmasked because Observer does not read it. Each is a prefix (an
85
+ * exact key is its own prefix: OpenInference's `llm.prompts` is one key).
86
+ */
87
+ export declare const EXTRA_CONTENT_PREFIXES: readonly string[];
88
+ /** Indexed-list members that are structure, not content (`gen_ai.prompt.0.role`). */
89
+ export declare const CONTENT_PREFIX_EXEMPT_SUFFIXES: readonly string[];
90
+ /** True when `key` carries prompt, response or tool I/O content (Python's is_content_key). */
91
+ export declare function isContentKey(key: string): boolean;
92
+ /** `setRequestParams` option -> `gen_ai.request.*` key (the genaiattr Params names). */
93
+ export declare const REQUEST_PARAMS: {
94
+ readonly maxTokens: "gen_ai.request.max_tokens";
95
+ readonly temperature: "gen_ai.request.temperature";
96
+ readonly topP: "gen_ai.request.top_p";
97
+ readonly topK: "gen_ai.request.top_k";
98
+ readonly stopSequences: "gen_ai.request.stop_sequences";
99
+ readonly frequencyPenalty: "gen_ai.request.frequency_penalty";
100
+ readonly presencePenalty: "gen_ai.request.presence_penalty";
101
+ readonly seed: "gen_ai.request.seed";
102
+ readonly stream: "gen_ai.request.stream";
103
+ readonly reasoningLevel: "gen_ai.request.reasoning.level";
104
+ };
105
+ /** Bounds of the identity contract (`internal/otelident`): ingest clamps with the same numbers. */
106
+ export declare const LIMITS: {
107
+ readonly valueLen: 256;
108
+ readonly tags: 32;
109
+ readonly tagLen: 128;
110
+ readonly metadataKeys: 32;
111
+ readonly metadataKeyLen: 128;
112
+ readonly metadataValueLen: 512;
113
+ };