@superbased/sdk 0.0.0-stage → 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 (119) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +438 -2
  4. package/dist/cjs/admit.d.ts +139 -0
  5. package/dist/cjs/admit.js +442 -0
  6. package/dist/cjs/admit.js.map +1 -0
  7. package/dist/cjs/attrs.d.ts +113 -0
  8. package/dist/cjs/attrs.js +183 -0
  9. package/dist/cjs/attrs.js.map +1 -0
  10. package/dist/cjs/config.d.ts +202 -0
  11. package/dist/cjs/config.js +386 -0
  12. package/dist/cjs/config.js.map +1 -0
  13. package/dist/cjs/context.d.ts +102 -0
  14. package/dist/cjs/context.js +234 -0
  15. package/dist/cjs/context.js.map +1 -0
  16. package/dist/cjs/control.d.ts +99 -0
  17. package/dist/cjs/control.js +243 -0
  18. package/dist/cjs/control.js.map +1 -0
  19. package/dist/cjs/cost.d.ts +108 -0
  20. package/dist/cjs/cost.js +211 -0
  21. package/dist/cjs/cost.js.map +1 -0
  22. package/dist/cjs/destination.d.ts +125 -0
  23. package/dist/cjs/destination.js +357 -0
  24. package/dist/cjs/destination.js.map +1 -0
  25. package/dist/cjs/experiments.d.ts +237 -0
  26. package/dist/cjs/experiments.js +678 -0
  27. package/dist/cjs/experiments.js.map +1 -0
  28. package/dist/cjs/export.d.ts +84 -0
  29. package/dist/cjs/export.js +328 -0
  30. package/dist/cjs/export.js.map +1 -0
  31. package/dist/cjs/index.d.ts +168 -0
  32. package/dist/cjs/index.js +581 -0
  33. package/dist/cjs/index.js.map +1 -0
  34. package/dist/cjs/instrument.d.ts +88 -0
  35. package/dist/cjs/instrument.js +397 -0
  36. package/dist/cjs/instrument.js.map +1 -0
  37. package/dist/cjs/package.json +1 -0
  38. package/dist/cjs/policy.d.ts +77 -0
  39. package/dist/cjs/policy.js +252 -0
  40. package/dist/cjs/policy.js.map +1 -0
  41. package/dist/cjs/prompts.d.ts +175 -0
  42. package/dist/cjs/prompts.js +476 -0
  43. package/dist/cjs/prompts.js.map +1 -0
  44. package/dist/cjs/propagation.d.ts +34 -0
  45. package/dist/cjs/propagation.js +151 -0
  46. package/dist/cjs/propagation.js.map +1 -0
  47. package/dist/cjs/req.d.ts +10 -0
  48. package/dist/cjs/req.js +3 -0
  49. package/dist/cjs/req.js.map +1 -0
  50. package/dist/cjs/runtime.d.ts +44 -0
  51. package/dist/cjs/runtime.js +67 -0
  52. package/dist/cjs/runtime.js.map +1 -0
  53. package/dist/cjs/scores.d.ts +102 -0
  54. package/dist/cjs/scores.js +226 -0
  55. package/dist/cjs/scores.js.map +1 -0
  56. package/dist/cjs/spans.d.ts +193 -0
  57. package/dist/cjs/spans.js +398 -0
  58. package/dist/cjs/spans.js.map +1 -0
  59. package/dist/cjs/vendor.d.ts +33 -0
  60. package/dist/cjs/vendor.js +67 -0
  61. package/dist/cjs/vendor.js.map +1 -0
  62. package/dist/esm/admit.d.ts +139 -0
  63. package/dist/esm/admit.js +432 -0
  64. package/dist/esm/admit.js.map +1 -0
  65. package/dist/esm/attrs.d.ts +113 -0
  66. package/dist/esm/attrs.js +179 -0
  67. package/dist/esm/attrs.js.map +1 -0
  68. package/dist/esm/config.d.ts +202 -0
  69. package/dist/esm/config.js +364 -0
  70. package/dist/esm/config.js.map +1 -0
  71. package/dist/esm/context.d.ts +102 -0
  72. package/dist/esm/context.js +221 -0
  73. package/dist/esm/context.js.map +1 -0
  74. package/dist/esm/control.d.ts +99 -0
  75. package/dist/esm/control.js +230 -0
  76. package/dist/esm/control.js.map +1 -0
  77. package/dist/esm/cost.d.ts +108 -0
  78. package/dist/esm/cost.js +202 -0
  79. package/dist/esm/cost.js.map +1 -0
  80. package/dist/esm/destination.d.ts +125 -0
  81. package/dist/esm/destination.js +346 -0
  82. package/dist/esm/destination.js.map +1 -0
  83. package/dist/esm/experiments.d.ts +237 -0
  84. package/dist/esm/experiments.js +666 -0
  85. package/dist/esm/experiments.js.map +1 -0
  86. package/dist/esm/export.d.ts +84 -0
  87. package/dist/esm/export.js +314 -0
  88. package/dist/esm/export.js.map +1 -0
  89. package/dist/esm/index.d.ts +168 -0
  90. package/dist/esm/index.js +500 -0
  91. package/dist/esm/index.js.map +1 -0
  92. package/dist/esm/instrument.d.ts +88 -0
  93. package/dist/esm/instrument.js +391 -0
  94. package/dist/esm/instrument.js.map +1 -0
  95. package/dist/esm/policy.d.ts +77 -0
  96. package/dist/esm/policy.js +240 -0
  97. package/dist/esm/policy.js.map +1 -0
  98. package/dist/esm/prompts.d.ts +175 -0
  99. package/dist/esm/prompts.js +460 -0
  100. package/dist/esm/prompts.js.map +1 -0
  101. package/dist/esm/propagation.d.ts +34 -0
  102. package/dist/esm/propagation.js +145 -0
  103. package/dist/esm/propagation.js.map +1 -0
  104. package/dist/esm/req.d.ts +10 -0
  105. package/dist/esm/req.js +2 -0
  106. package/dist/esm/req.js.map +1 -0
  107. package/dist/esm/runtime.d.ts +44 -0
  108. package/dist/esm/runtime.js +59 -0
  109. package/dist/esm/runtime.js.map +1 -0
  110. package/dist/esm/scores.d.ts +102 -0
  111. package/dist/esm/scores.js +219 -0
  112. package/dist/esm/scores.js.map +1 -0
  113. package/dist/esm/spans.d.ts +193 -0
  114. package/dist/esm/spans.js +378 -0
  115. package/dist/esm/spans.js.map +1 -0
  116. package/dist/esm/vendor.d.ts +33 -0
  117. package/dist/esm/vendor.js +61 -0
  118. package/dist/esm/vendor.js.map +1 -0
  119. package/package.json +130 -4
@@ -0,0 +1,139 @@
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 { type Env } from "./config.js";
9
+ /** Default admission-check endpoint: this machine's Observer API on the dashboard port. */
10
+ export declare const DEFAULT_ADMISSION_ENDPOINT = "http://127.0.0.1:8081/api/obs/admission/check";
11
+ /** Path of the org SDK control API's admission endpoint, under an org URL. */
12
+ export declare const SDK_ADMIT_PATH = "/v1/sdk/admit";
13
+ /**
14
+ * Default client timeout (ms). Longer than the server's 10 s judge budget, so
15
+ * the client does not fail open on a request the server would still decide.
16
+ * A server that advertises a recommended timeout (the
17
+ * `recommended_client_timeout_ms` body field or the
18
+ * `X-SBO-Recommended-Timeout-Ms` header, sent by both the org SDK control API
19
+ * and the local machine) overrides it for later calls.
20
+ */
21
+ export declare const DEFAULT_ADMIT_TIMEOUT_MS = 12000;
22
+ /**
23
+ * The advertised-timeout names, canonical first. The second of each pair is
24
+ * the pre-release spelling, still read so an older server keeps working.
25
+ */
26
+ export declare const TIMEOUT_HEADERS: readonly ["x-sbo-recommended-timeout-ms", "x-superbased-admit-timeout-ms"];
27
+ export declare const TIMEOUT_FIELDS: readonly ["recommended_client_timeout_ms", "recommended_timeout_ms"];
28
+ /** Client-side degraded reasons (`Verdict.degraded`). Server values pass through. */
29
+ export declare const Degraded: {
30
+ /** HTTP 403/404: admission is off on the server or not permitted. */
31
+ readonly UNAVAILABLE: "admission-unavailable";
32
+ readonly TIMEOUT: "client-timeout";
33
+ readonly TRANSPORT: "client-transport";
34
+ readonly HTTP_ERROR: "client-http-error";
35
+ readonly BAD_RESPONSE: "client-bad-response";
36
+ /**
37
+ * The organization answered mode `off`: it has no admission policy, so it
38
+ * made no decision (live finding L-05, ruling D29). Under destination `both`
39
+ * the SDK then asks this machine; otherwise the verdict is degraded.
40
+ */
41
+ readonly ADMISSION_OFF: "admission-off";
42
+ };
43
+ /** The result of an {@link admit} check. */
44
+ export interface Verdict {
45
+ /**
46
+ * What the app should honour. In `observe` mode the server always returns
47
+ * `true` and records the shadow verdict; in `enforce` mode it returns the
48
+ * real decision (`ask`/`deny` → `false`, `flag` still admits).
49
+ */
50
+ allowed: boolean;
51
+ /** The raw decision, one of: allow / flag / ask / deny. */
52
+ decision: string;
53
+ severity: string;
54
+ /** The criterion id that fired, if any. */
55
+ criterion: string;
56
+ /** A short string to surface to the user on a block. */
57
+ reason: string;
58
+ mode: string;
59
+ /** What enforce mode WOULD decide, so you can measure before flipping. */
60
+ enforceDecision: string;
61
+ /** Empty for a clean decision; otherwise why it is not one (see {@link Degraded}). */
62
+ degraded: string;
63
+ /** Whether the server consulted its LLM judge (server field `judge_used`). */
64
+ judgeUsed: boolean;
65
+ /** Server-side decision latency; for a client-degraded verdict, the client's elapsed time (`latency_ms`). */
66
+ latencyMs: number;
67
+ /** The server's id for the recorded verdict, when it returns one. */
68
+ verdictId: string;
69
+ /** HTTP status of the response (0 when none arrived). */
70
+ httpStatus: number;
71
+ /** Detail for a client-degraded verdict. */
72
+ error: string;
73
+ }
74
+ export interface AdmitOptions {
75
+ /** The app's tenant. Defaults to the request scope's (`propagateAttributes`), then `init`'s. */
76
+ tenant?: string;
77
+ /** The app's end user. Defaults to the request scope's, then `init`'s. */
78
+ user?: string;
79
+ /** The app's session. Defaults to the request scope's `sessionId`, then `init`'s. */
80
+ session?: string;
81
+ /** Defaults to the active span's trace id. */
82
+ traceId?: string;
83
+ requestId?: string;
84
+ /** Full admission URL. Defaults to $SUPERBASED_ADMISSION_ENDPOINT, then the destination (see resolveTarget), then this machine. */
85
+ endpoint?: string;
86
+ /** Org base URL; the check goes to `<orgUrl>/v1/sdk/admit`. Env: SUPERBASED_ORG_URL. */
87
+ orgUrl?: string;
88
+ /**
89
+ * SDK credential, sent as `Authorization: Bearer`. Env: SUPERBASED_API_KEY.
90
+ * Only an explicit `apiKey` goes to a loopback endpoint; the configured key
91
+ * rides only to an org URL or an explicit remote endpoint.
92
+ */
93
+ apiKey?: string;
94
+ /** Extra or overriding request headers. */
95
+ headers?: Record<string, string>;
96
+ /** Per-call timeout in ms. Default: the server-advertised timeout, else 12000. */
97
+ timeoutMs?: number;
98
+ /** Deny when no decision could be obtained. Env: SUPERBASED_ADMISSION_FAIL_CLOSED. Default false. */
99
+ failClosed?: boolean;
100
+ }
101
+ /** How often (ms) admit() may warn about the same cause. */
102
+ export declare const DEGRADED_LOG_INTERVAL_MS = 60000;
103
+ /** What to fix for a degraded verdict ("" for a server-side reason). */
104
+ export declare function degradedFix(cause: string, status: number, url?: string): string;
105
+ /** Process-wide admit() counters, read by diagnostics(). */
106
+ export declare const admitStats: {
107
+ degraded: number;
108
+ lastError: string;
109
+ lastErrorAt: number;
110
+ loggedAt: Map<string, number>;
111
+ };
112
+ export declare function resetAdmitStats(): void;
113
+ /** Forget server-advertised timeouts (tests). */
114
+ export declare function resetAdvertisedTimeouts(): void;
115
+ /** The server-advertised timeout remembered for url, in ms (tests). */
116
+ export declare function advertisedTimeoutMs(url: string): number | undefined;
117
+ /** Normalize a parsed response body into a Verdict; null when it is not one. */
118
+ export declare function parseVerdict(body: unknown): Verdict | null;
119
+ /**
120
+ * The `service.name` the app's spans carry: the resource of the last span
121
+ * the SDK saw (its own provider's, or the app's when attached), else the
122
+ * configured name (serviceName, SUPERBASED_SERVICE_NAME, OTEL_SERVICE_NAME,
123
+ * OTEL_RESOURCE_ATTRIBUTES, custom-app). OpenTelemetry's `unknown_service`
124
+ * default is no name.
125
+ */
126
+ export declare function serviceName(env: Env): string;
127
+ /**
128
+ * Check an incoming user message against the app's admission policy BEFORE
129
+ * running the agent, and get an allow/flag/ask/deny verdict.
130
+ *
131
+ * ```ts
132
+ * const v = await admit(userMessage, { user: "alice", session: "s1" });
133
+ * if (!v.allowed) return v.reason; // or route to a human on `ask`
134
+ * ```
135
+ *
136
+ * Never rejects. When no decision can be obtained it admits, unless
137
+ * `failClosed` is set; `degraded` says why.
138
+ */
139
+ export declare function admit(message: string, opts?: AdmitOptions): Promise<Verdict>;
@@ -0,0 +1,442 @@
1
+ "use strict";
2
+ /**
3
+ * `admit()`: the input-admission pre-flight check (admission spec §6.1).
4
+ *
5
+ * Never throws or rejects. Any failure (transport, timeout, HTTP error, a body
6
+ * that is not a JSON object, a field of the wrong type) yields a degraded
7
+ * verdict that admits (fail open, the default) or denies (`failClosed`).
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.admitStats = exports.DEGRADED_LOG_INTERVAL_MS = exports.Degraded = exports.TIMEOUT_FIELDS = exports.TIMEOUT_HEADERS = exports.DEFAULT_ADMIT_TIMEOUT_MS = exports.SDK_ADMIT_PATH = exports.DEFAULT_ADMISSION_ENDPOINT = void 0;
11
+ exports.degradedFix = degradedFix;
12
+ exports.resetAdmitStats = resetAdmitStats;
13
+ exports.resetAdvertisedTimeouts = resetAdvertisedTimeouts;
14
+ exports.advertisedTimeoutMs = advertisedTimeoutMs;
15
+ exports.parseVerdict = parseVerdict;
16
+ exports.serviceName = serviceName;
17
+ exports.admit = admit;
18
+ const api_1 = require("@opentelemetry/api");
19
+ const config_js_1 = require("./config.js");
20
+ const context_js_1 = require("./context.js");
21
+ const destination_js_1 = require("./destination.js");
22
+ const runtime_js_1 = require("./runtime.js");
23
+ /** Default admission-check endpoint: this machine's Observer API on the dashboard port. */
24
+ exports.DEFAULT_ADMISSION_ENDPOINT = "http://127.0.0.1:8081/api/obs/admission/check";
25
+ /** The path of a machine's admission check. */
26
+ const MACHINE_ADMISSION_PATH = "/api/obs/admission/check";
27
+ /** Path of the org SDK control API's admission endpoint, under an org URL. */
28
+ exports.SDK_ADMIT_PATH = "/v1/sdk/admit";
29
+ /**
30
+ * Default client timeout (ms). Longer than the server's 10 s judge budget, so
31
+ * the client does not fail open on a request the server would still decide.
32
+ * A server that advertises a recommended timeout (the
33
+ * `recommended_client_timeout_ms` body field or the
34
+ * `X-SBO-Recommended-Timeout-Ms` header, sent by both the org SDK control API
35
+ * and the local machine) overrides it for later calls.
36
+ */
37
+ exports.DEFAULT_ADMIT_TIMEOUT_MS = 12_000;
38
+ /**
39
+ * The advertised-timeout names, canonical first. The second of each pair is
40
+ * the pre-release spelling, still read so an older server keeps working.
41
+ */
42
+ exports.TIMEOUT_HEADERS = ["x-sbo-recommended-timeout-ms", "x-superbased-admit-timeout-ms"];
43
+ exports.TIMEOUT_FIELDS = ["recommended_client_timeout_ms", "recommended_timeout_ms"];
44
+ /** Client-side degraded reasons (`Verdict.degraded`). Server values pass through. */
45
+ exports.Degraded = {
46
+ /** HTTP 403/404: admission is off on the server or not permitted. */
47
+ UNAVAILABLE: "admission-unavailable",
48
+ TIMEOUT: "client-timeout",
49
+ TRANSPORT: "client-transport",
50
+ HTTP_ERROR: "client-http-error",
51
+ BAD_RESPONSE: "client-bad-response",
52
+ /**
53
+ * The organization answered mode `off`: it has no admission policy, so it
54
+ * made no decision (live finding L-05, ruling D29). Under destination `both`
55
+ * the SDK then asks this machine; otherwise the verdict is degraded.
56
+ */
57
+ ADMISSION_OFF: "admission-off",
58
+ };
59
+ const advertised = new Map();
60
+ // --- saying so when admit() could not decide (review E-39) -------------------
61
+ //
62
+ // admit() fails open (the contract), but never silently: every degraded
63
+ // verdict is counted for diagnostics(), and one console.warn per cause per
64
+ // minute names the cause and the fix. Python does the same (logging).
65
+ /** How often (ms) admit() may warn about the same cause. */
66
+ exports.DEGRADED_LOG_INTERVAL_MS = 60_000;
67
+ /** [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. */
68
+ const FIXES = [
69
+ [
70
+ exports.Degraded.UNAVAILABLE,
71
+ 404,
72
+ 404,
73
+ "this machine has no admission check: update Observer (a current machine answers allow while no admission policy is set), or turn admission on",
74
+ "machine",
75
+ ],
76
+ [exports.Degraded.HTTP_ERROR, 300, 399, "the address redirects, and admit() never follows a redirect (the key must not move hosts): use the final URL", ""],
77
+ [exports.Degraded.HTTP_ERROR, 401, 401, "the SDK key was refused: check apiKey / SUPERBASED_API_KEY, or sign in again", ""],
78
+ [exports.Degraded.UNAVAILABLE, 403, 403, "the key may not run admission checks, or admission is off for this app", ""],
79
+ [exports.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", ""],
80
+ [exports.Degraded.HTTP_ERROR, 429, 429, "the server is rate limiting admission checks", ""],
81
+ [exports.Degraded.HTTP_ERROR, 0, 999, "the admission server answered with an error", ""],
82
+ [exports.Degraded.TIMEOUT, 0, 999, "no answer within the timeout: raise timeoutMs, or check the server", ""],
83
+ [exports.Degraded.TRANSPORT, 0, 999, "nothing answered at this address: check the URL and that Observer is running", ""],
84
+ [exports.Degraded.BAD_RESPONSE, 0, 999, "the address did not answer like an admission check: check the URL", ""],
85
+ [exports.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", ""],
86
+ ];
87
+ /** What to fix for a degraded verdict ("" for a server-side reason). */
88
+ function degradedFix(cause, status, url = "") {
89
+ const machine = isMachineAdmission(url);
90
+ for (const [c, lo, hi, fix, at] of FIXES) {
91
+ if (c === cause && status >= lo && status <= hi && (!at || (at === "machine") === machine))
92
+ return fix;
93
+ }
94
+ return "";
95
+ }
96
+ /** Whether url is a machine's admission check (its path). */
97
+ function isMachineAdmission(url) {
98
+ try {
99
+ return new URL(url).pathname.replace(/\/+$/, "").endsWith(MACHINE_ADMISSION_PATH);
100
+ }
101
+ catch {
102
+ return false;
103
+ }
104
+ }
105
+ /** Process-wide admit() counters, read by diagnostics(). */
106
+ exports.admitStats = { degraded: 0, lastError: "", lastErrorAt: 0, loggedAt: new Map() };
107
+ function resetAdmitStats() {
108
+ exports.admitStats.degraded = 0;
109
+ exports.admitStats.lastError = "";
110
+ exports.admitStats.lastErrorAt = 0;
111
+ exports.admitStats.loggedAt.clear();
112
+ }
113
+ /** scheme://host[:port]/path of a URL: no user info, no query. */
114
+ function where(url) {
115
+ try {
116
+ const u = new URL(url);
117
+ return `${u.protocol}//${u.host}${u.pathname}`;
118
+ }
119
+ catch {
120
+ return "the admission address";
121
+ }
122
+ }
123
+ function noteDegraded(v, url) {
124
+ try {
125
+ const detail = v.httpStatus ? `HTTP ${v.httpStatus}` : v.error || v.degraded;
126
+ const fix = degradedFix(v.degraded, v.httpStatus, url);
127
+ const outcome = v.allowed ? "admitted (fail open)" : "denied (failClosed)";
128
+ const msg = `admit() got no decision${url ? ` from ${where(url)}` : ""} (${v.degraded}: ${detail}); the message was ${outcome}` +
129
+ (fix ? `. Fix: ${fix}` : "");
130
+ const now = Date.now();
131
+ exports.admitStats.degraded += 1;
132
+ exports.admitStats.lastError = msg.slice(0, 500);
133
+ exports.admitStats.lastErrorAt = now;
134
+ const key = `${v.degraded}:${v.httpStatus}`;
135
+ if (!runtime_js_1.runtime.settings?.debug && now - (exports.admitStats.loggedAt.get(key) ?? -Infinity) < exports.DEGRADED_LOG_INTERVAL_MS)
136
+ return;
137
+ exports.admitStats.loggedAt.set(key, now);
138
+ console.warn(`@superbased/sdk: ${msg}`);
139
+ }
140
+ catch {
141
+ // reporting never breaks admit()
142
+ }
143
+ }
144
+ /** Forget server-advertised timeouts (tests). */
145
+ function resetAdvertisedTimeouts() {
146
+ advertised.clear();
147
+ }
148
+ /** The server-advertised timeout remembered for url, in ms (tests). */
149
+ function advertisedTimeoutMs(url) {
150
+ return advertised.get(url);
151
+ }
152
+ /** The first of names whose get(name) is neither null nor undefined. */
153
+ function firstPresent(get, names) {
154
+ for (const n of names) {
155
+ const v = get(n);
156
+ if (v !== null && v !== undefined)
157
+ return v;
158
+ }
159
+ return undefined;
160
+ }
161
+ function str(d, k) {
162
+ const v = d[k];
163
+ return typeof v === "string" ? v : "";
164
+ }
165
+ function num(d, k) {
166
+ const v = d[k];
167
+ return typeof v === "number" && Number.isFinite(v) ? Math.trunc(v) : 0;
168
+ }
169
+ function rememberTimeout(url, raw) {
170
+ if (raw == null || typeof raw === "boolean")
171
+ return;
172
+ const ms = Number(raw);
173
+ if (Number.isFinite(ms) && ms >= 100 && ms <= 120_000)
174
+ advertised.set(url, ms);
175
+ }
176
+ /** Normalize a parsed response body into a Verdict; null when it is not one. */
177
+ function parseVerdict(body) {
178
+ if (body === null || typeof body !== "object" || Array.isArray(body))
179
+ return null;
180
+ const d = body;
181
+ if (typeof d.allowed !== "boolean")
182
+ return null;
183
+ const vid = d.verdict_id ?? d.id;
184
+ return {
185
+ allowed: d.allowed,
186
+ decision: str(d, "decision") || (d.allowed ? "allow" : "deny"),
187
+ severity: str(d, "severity"),
188
+ criterion: str(d, "criterion"),
189
+ reason: str(d, "reason"),
190
+ mode: str(d, "mode"),
191
+ enforceDecision: str(d, "enforce_decision"),
192
+ degraded: str(d, "degraded"),
193
+ judgeUsed: d.judge_used === true,
194
+ latencyMs: num(d, "latency_ms"),
195
+ verdictId: typeof vid === "string" || (typeof vid === "number" && Number.isFinite(vid)) ? String(vid) : "",
196
+ httpStatus: 0,
197
+ error: "",
198
+ };
199
+ }
200
+ /**
201
+ * Where the check goes and whether the SDK key rides with it (contract
202
+ * destination.md section 8): an explicit `endpoint` / `orgUrl` wins, then
203
+ * SUPERBASED_ADMISSION_ENDPOINT; after init, the destination decides (`local`
204
+ * the machine, `online` / `both` with a usable gateway the org, degraded the
205
+ * machine); before init, SUPERBASED_ORG_URL, else the machine. The configured
206
+ * key is sent to the org, or to a remote endpoint you named, never to a
207
+ * loopback address (only an explicit `apiKey` goes there).
208
+ */
209
+ function resolveTarget(opts, env) {
210
+ if (opts.endpoint)
211
+ return { url: opts.endpoint, sendKey: !(0, destination_js_1.isLoopbackUrl)(opts.endpoint), org: "" };
212
+ if (opts.orgUrl)
213
+ return { url: opts.orgUrl.replace(/\/+$/, "") + exports.SDK_ADMIT_PATH, sendKey: true, org: "named" };
214
+ const ep = (env.SUPERBASED_ADMISSION_ENDPOINT ?? "").trim();
215
+ if (ep)
216
+ return { url: ep, sendKey: !(0, destination_js_1.isLoopbackUrl)(ep), org: "" };
217
+ const s = runtime_js_1.runtime.settings;
218
+ const machine = machineAdmissionUrl();
219
+ if (s && runtime_js_1.runtime.destinationSource) {
220
+ if ((runtime_js_1.runtime.destination === "online" || runtime_js_1.runtime.destination === "both") && s.orgUrl && (0, config_js_1.onlineUsable)(s)) {
221
+ return { url: s.orgUrl + exports.SDK_ADMIT_PATH, sendKey: true, org: "plan" };
222
+ }
223
+ if (runtime_js_1.runtime.destination)
224
+ return { url: machine, sendKey: false, org: "" };
225
+ }
226
+ const org = (env.SUPERBASED_ORG_URL ?? "").trim();
227
+ if (org)
228
+ return { url: org.replace(/\/+$/, "") + exports.SDK_ADMIT_PATH, sendKey: true, org: "named" };
229
+ return { url: machine, sendKey: false, org: "" };
230
+ }
231
+ /** This machine's admission check: the one discovery advertised (loopback only), else the machine URL's route. */
232
+ function machineAdmissionUrl() {
233
+ const s = runtime_js_1.runtime.settings;
234
+ return runtime_js_1.runtime.admissionUrl || (s ? s.nodeUrl + MACHINE_ADMISSION_PATH : exports.DEFAULT_ADMISSION_ENDPOINT);
235
+ }
236
+ function activeTraceId() {
237
+ try {
238
+ const ctx = api_1.trace.getActiveSpan()?.spanContext();
239
+ if (ctx && /^[0-9a-f]{32}$/.test(ctx.traceId) && !/^0+$/.test(ctx.traceId))
240
+ return ctx.traceId;
241
+ }
242
+ catch {
243
+ // ignore
244
+ }
245
+ return "";
246
+ }
247
+ function stampSpan(v) {
248
+ try {
249
+ const sp = api_1.trace.getActiveSpan();
250
+ if (!sp || !sp.isRecording())
251
+ return;
252
+ sp.setAttribute("sbo.admission.allowed", v.allowed);
253
+ sp.setAttribute("sbo.admission.decision", v.decision);
254
+ if (v.verdictId)
255
+ sp.setAttribute("sbo.admission.verdict_id", v.verdictId);
256
+ if (v.degraded)
257
+ sp.setAttribute("sbo.admission.degraded", v.degraded);
258
+ }
259
+ catch {
260
+ // ignore
261
+ }
262
+ }
263
+ function degraded(cause, failClosed, started, httpStatus = 0, error = "") {
264
+ return {
265
+ allowed: !failClosed,
266
+ decision: failClosed ? "deny" : "allow",
267
+ severity: "",
268
+ criterion: "",
269
+ reason: failClosed ? "admission check unavailable" : "",
270
+ mode: "",
271
+ enforceDecision: "",
272
+ degraded: cause,
273
+ judgeUsed: false,
274
+ latencyMs: Math.round(Date.now() - started),
275
+ verdictId: "",
276
+ httpStatus,
277
+ error: error.slice(0, 300),
278
+ };
279
+ }
280
+ /**
281
+ * The `service.name` the app's spans carry: the resource of the last span
282
+ * the SDK saw (its own provider's, or the app's when attached), else the
283
+ * configured name (serviceName, SUPERBASED_SERVICE_NAME, OTEL_SERVICE_NAME,
284
+ * OTEL_RESOURCE_ATTRIBUTES, custom-app). OpenTelemetry's `unknown_service`
285
+ * default is no name.
286
+ */
287
+ function serviceName(env) {
288
+ const seen = runtime_js_1.runtime.resourceService.trim();
289
+ if (seen && !seen.startsWith("unknown_service"))
290
+ return seen;
291
+ return runtime_js_1.runtime.settings?.serviceName || (0, config_js_1.resolveServiceName)(undefined, env);
292
+ }
293
+ /**
294
+ * Check an incoming user message against the app's admission policy BEFORE
295
+ * running the agent, and get an allow/flag/ask/deny verdict.
296
+ *
297
+ * ```ts
298
+ * const v = await admit(userMessage, { user: "alice", session: "s1" });
299
+ * if (!v.allowed) return v.reason; // or route to a human on `ask`
300
+ * ```
301
+ *
302
+ * Never rejects. When no decision can be obtained it admits, unless
303
+ * `failClosed` is set; `degraded` says why.
304
+ */
305
+ async function admit(message, opts = {}) {
306
+ const started = Date.now();
307
+ const env = (typeof process !== "undefined" ? process.env : {});
308
+ const failClosed = opts.failClosed ?? (0, config_js_1.envFlag)(env, ["SUPERBASED_ADMISSION_FAIL_CLOSED"], false);
309
+ let url = exports.DEFAULT_ADMISSION_ENDPOINT;
310
+ try {
311
+ // The org or the machine is known only once discovery answered (review E-33).
312
+ await (0, runtime_js_1.destinationKnown)();
313
+ const target = resolveTarget(opts, env);
314
+ url = target.url;
315
+ // Identity: the argument, else the request scope (propagateAttributes),
316
+ // else init's process-wide value (contract section 2), as in Python.
317
+ const cur = (0, context_js_1.getCurrentAttributes)();
318
+ const s = runtime_js_1.runtime.settings;
319
+ const payload = JSON.stringify({
320
+ text: message == null ? "" : String(message),
321
+ tenant: opts.tenant || cur.tenant || s?.tenant || "",
322
+ user: opts.user || cur.user || s?.user || "",
323
+ session: opts.session || cur.sessionId || s?.sessionId || "",
324
+ // service.name: service-scoped budget caps bind on it, on the machine
325
+ // and on the org.
326
+ service: serviceName(env),
327
+ trace_id: opts.traceId ?? activeTraceId(),
328
+ request_id: opts.requestId ?? "",
329
+ });
330
+ const key = opts.apiKey ?? (target.sendKey ? (runtime_js_1.runtime.settings?.apiKey || env.SUPERBASED_API_KEY || "") : "");
331
+ let v = await post(url, key, payload, opts, failClosed, started);
332
+ if (target.org && !v.degraded && v.mode === "off") {
333
+ // The org has no admission policy, so it made no decision (L-05).
334
+ // Under destination both, this machine's policy decides (the key never
335
+ // goes there); otherwise the verdict says nothing decided.
336
+ if (target.org === "plan" && runtime_js_1.runtime.destination === "both") {
337
+ url = machineAdmissionUrl();
338
+ v = await post(url, "", payload, { ...opts, headers: withoutAuthorization(opts.headers) }, failClosed, started);
339
+ }
340
+ else {
341
+ v = degraded(exports.Degraded.ADMISSION_OFF, failClosed, started, v.httpStatus, "the organization answered mode off");
342
+ noteDegraded(v, url);
343
+ }
344
+ }
345
+ stampSpan(v);
346
+ return v;
347
+ }
348
+ catch (err) {
349
+ // The last line of defence: never reject into the host.
350
+ const v = degraded(exports.Degraded.BAD_RESPONSE, failClosed, started, 0, String(err));
351
+ stampSpan(v);
352
+ noteDegraded(v, url);
353
+ return v;
354
+ }
355
+ }
356
+ function withoutAuthorization(h) {
357
+ if (!h)
358
+ return h;
359
+ return Object.fromEntries(Object.entries(h).filter(([k]) => k.toLowerCase() !== "authorization"));
360
+ }
361
+ /** One admission request to url; a failure is a counted degraded verdict. The caller stamps the span. */
362
+ async function post(url, key, payload, opts, failClosed, started) {
363
+ const fail = (cause, status = 0, error = "") => {
364
+ const v = degraded(cause, failClosed, started, status, error);
365
+ noteDegraded(v, url);
366
+ return v;
367
+ };
368
+ let timer;
369
+ try {
370
+ const timeoutMs = opts.timeoutMs ?? advertised.get(url) ?? exports.DEFAULT_ADMIT_TIMEOUT_MS;
371
+ const headers = { "Content-Type": "application/json", Accept: "application/json" };
372
+ if (key)
373
+ headers.Authorization = `Bearer ${key}`;
374
+ if (opts.headers)
375
+ Object.assign(headers, opts.headers);
376
+ const controller = new AbortController();
377
+ let timedOut = false;
378
+ timer = setTimeout(() => {
379
+ timedOut = true;
380
+ controller.abort();
381
+ }, timeoutMs);
382
+ let resp;
383
+ try {
384
+ resp = await fetch(url, {
385
+ method: "POST",
386
+ headers,
387
+ body: payload,
388
+ signal: controller.signal,
389
+ // Never follow a redirect: the key must not ride to a host it was not sent to (R-B26).
390
+ redirect: "manual",
391
+ });
392
+ }
393
+ catch (err) {
394
+ if (timedOut)
395
+ return fail(exports.Degraded.TIMEOUT, 0, `timed out after ${timeoutMs}ms`);
396
+ const cause = err.cause;
397
+ return fail(exports.Degraded.TRANSPORT, 0, cause?.code ?? cause?.message ?? String(err));
398
+ }
399
+ rememberTimeout(url, firstPresent((n) => resp.headers.get(n), exports.TIMEOUT_HEADERS));
400
+ if (resp.status === 403 || resp.status === 404) {
401
+ void resp.body?.cancel().catch(() => undefined);
402
+ return fail(exports.Degraded.UNAVAILABLE, resp.status, `HTTP ${resp.status}`);
403
+ }
404
+ if (!resp.ok) {
405
+ void resp.body?.cancel().catch(() => undefined);
406
+ return fail(exports.Degraded.HTTP_ERROR, resp.status, `HTTP ${resp.status}`);
407
+ }
408
+ let text;
409
+ try {
410
+ text = await resp.text();
411
+ }
412
+ catch (err) {
413
+ if (timedOut)
414
+ return fail(exports.Degraded.TIMEOUT, resp.status, `timed out after ${timeoutMs}ms`);
415
+ return fail(exports.Degraded.TRANSPORT, resp.status, String(err));
416
+ }
417
+ let body;
418
+ try {
419
+ body = JSON.parse(text);
420
+ }
421
+ catch (err) {
422
+ return fail(exports.Degraded.BAD_RESPONSE, resp.status, String(err));
423
+ }
424
+ const v = parseVerdict(body);
425
+ if (!v) {
426
+ const kind = body === null ? "null" : Array.isArray(body) ? "array" : typeof body;
427
+ return fail(exports.Degraded.BAD_RESPONSE, resp.status, kind === "object" ? "response field 'allowed' is missing or not a boolean" : `response body is ${kind}, not an object`);
428
+ }
429
+ const fields = body;
430
+ rememberTimeout(url, firstPresent((n) => fields[n], exports.TIMEOUT_FIELDS));
431
+ v.httpStatus = resp.status;
432
+ return v;
433
+ }
434
+ catch (err) {
435
+ return fail(exports.Degraded.BAD_RESPONSE, 0, String(err));
436
+ }
437
+ finally {
438
+ if (timer)
439
+ clearTimeout(timer);
440
+ }
441
+ }
442
+ //# sourceMappingURL=admit.js.map