@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,108 @@
1
+ /**
2
+ * Exact cost, the SDK side (W4-2; contract `contracts/cost-source.md`, lane
3
+ * C2; the Python twin is `get_trace_cost`, lane C5).
4
+ *
5
+ * - `getTraceCost(traceId)`: where a trace's cost came from, span by span:
6
+ * `costSource` (`gateway_exact`, `proxy_exact`, `computed`, `reported`, or
7
+ * `""` = unpriced), every number kept, and the exact-minus-reported
8
+ * delta. Online: `GET <org>/v1/sdk/traces/{id}/cost` (scope `sdk:read`);
9
+ * local: `GET <machine>/api/obs/trace/{id}` (its `cost` object); `both`:
10
+ * the org first, then the machine. `null` when no destination has the
11
+ * trace (or none answered).
12
+ * - The join key: the org AI gateway answers every inference with
13
+ * `X-SBO-Request-Id` and honours one the client sends. `gatewayFetch()`
14
+ * wraps `fetch` for a client pointed at the gateway: it sends an id when
15
+ * the caller set none and stamps the id the gateway answered with on the
16
+ * active span as `request_id` (contract section 4 rule 1), so the span
17
+ * joins the gateway's exact record. `stampGatewayRequestId` does the
18
+ * stamp for a response you got some other way.
19
+ *
20
+ * Never throws for a transport or server failure (resolves null, counted in
21
+ * `diagnostics()`); a bad trace id is a TypeError.
22
+ */
23
+ import { type Span } from "@opentelemetry/api";
24
+ import { type ControlOptions } from "./control.js";
25
+ /** Where a span's cost came from (contract section 1); `""` is unpriced. */
26
+ export type CostSource = "gateway_exact" | "proxy_exact" | "computed" | "reported" | "";
27
+ /** Every value, in precedence order (contract section 2), then unpriced. */
28
+ export declare const COST_SOURCES: readonly CostSource[];
29
+ /** The display label every cost cell prints (contract section 1). */
30
+ export declare const COST_SOURCE_LABELS: Readonly<Record<string, string>>;
31
+ /** Whether a source is one of the exact family (`gateway_exact`, `proxy_exact`). */
32
+ export declare function isExactCost(source: string): boolean;
33
+ /** The response header that carries (and accepts) the gateway's request id. */
34
+ export declare const GATEWAY_REQUEST_ID_HEADER = "X-SBO-Request-Id";
35
+ /** A trace's cost label (contract section 5). */
36
+ export interface CostProvenance {
37
+ /** `gateway_exact`, `proxy_exact`, `computed`, `reported`, `mixed` or `unpriced`. */
38
+ label: string;
39
+ /** False when a cost-bearing span is unpriced, so the total leaves something out ("partial"). */
40
+ complete: boolean;
41
+ sources: {
42
+ gatewayExact: number;
43
+ proxyExact: number;
44
+ computed: number;
45
+ reported: number;
46
+ unpriced: number;
47
+ };
48
+ }
49
+ /** One cost-bearing span (contract section 6); a number is null where it is absent. */
50
+ export interface SpanCost {
51
+ spanId: string;
52
+ model: string;
53
+ /** null when `costSource` is "" (unpriced): never show it as $0. */
54
+ costUsd: number | null;
55
+ costSource: CostSource;
56
+ reportedUsd: number | null;
57
+ computedUsd: number | null;
58
+ exactUsd: number | null;
59
+ /** Exact minus reported; set only when the source is exact and the span reported a cost. */
60
+ costDeltaUsd: number | null;
61
+ gatewayRequestId: string;
62
+ }
63
+ /** A trace's cost, span by span (contract section 6, camelCased). */
64
+ export interface TraceCost {
65
+ traceId: string;
66
+ /** The sum of the priced spans; null when nothing is priced. */
67
+ costUsd: number | null;
68
+ costProvenance: CostProvenance;
69
+ /** Cost-bearing spans only, in start order. */
70
+ spans: SpanCost[];
71
+ /** Which destination answered: `online` (the org) or `local` (this machine). */
72
+ destination: "online" | "local";
73
+ }
74
+ /** Parse a TraceCost body (org response or the machine's `cost` object); null when it is not one. */
75
+ export declare function parseTraceCost(body: unknown, destination: "online" | "local", wantTrace?: string): TraceCost | null;
76
+ /**
77
+ * Where a trace's cost came from, span by span. `traceId` defaults to the
78
+ * current trace; with no trace it resolves null without a call. Resolves
79
+ * null when no destination has the trace or none answered; rejects only
80
+ * with a RangeError for a trace id that is not 32 hex characters (or all
81
+ * zero), as Python raises ValueError.
82
+ */
83
+ export declare function getTraceCost(traceId?: string, opts?: ControlOptions): Promise<TraceCost | null>;
84
+ /** The gateway's request id from a Response, a Headers object or a plain header record ("" when absent). */
85
+ export declare function gatewayRequestId(from: unknown): string;
86
+ /**
87
+ * Stamp the gateway's request id (from a response or its headers) on `span`
88
+ * (default: the active span) as `request_id`, the exact join key. A no-op
89
+ * when there is no id or no recording span. Returns the id.
90
+ */
91
+ export declare function stampGatewayRequestId(from: unknown, span?: Span): string;
92
+ type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
93
+ /**
94
+ * A `fetch` for a client that calls the org AI gateway (`new OpenAI({
95
+ * baseURL: <gateway>, fetch: gatewayFetch() })`): it sends an
96
+ * `X-SBO-Request-Id` when the request carries none, and stamps the id the
97
+ * gateway answered with on the span that is active when the call is made
98
+ * (an instrumentation's LLM span), so the span joins the gateway's exact
99
+ * cost record. It also names the app's end user and service
100
+ * (`X-Superbased-User`, `X-Superbased-Service`), which the gateway's app
101
+ * budget caps reserve against: the per-request user (propagateAttributes /
102
+ * identify, else init's user) and the service name admit() sends. A header
103
+ * the request already carries is kept. Pass it only to a client pointed at
104
+ * the gateway: the end user is PII, and the gateway never forwards these
105
+ * headers upstream.
106
+ */
107
+ export declare function gatewayFetch(base?: FetchLike): FetchLike;
108
+ export {};
@@ -0,0 +1,211 @@
1
+ "use strict";
2
+ /**
3
+ * Exact cost, the SDK side (W4-2; contract `contracts/cost-source.md`, lane
4
+ * C2; the Python twin is `get_trace_cost`, lane C5).
5
+ *
6
+ * - `getTraceCost(traceId)`: where a trace's cost came from, span by span:
7
+ * `costSource` (`gateway_exact`, `proxy_exact`, `computed`, `reported`, or
8
+ * `""` = unpriced), every number kept, and the exact-minus-reported
9
+ * delta. Online: `GET <org>/v1/sdk/traces/{id}/cost` (scope `sdk:read`);
10
+ * local: `GET <machine>/api/obs/trace/{id}` (its `cost` object); `both`:
11
+ * the org first, then the machine. `null` when no destination has the
12
+ * trace (or none answered).
13
+ * - The join key: the org AI gateway answers every inference with
14
+ * `X-SBO-Request-Id` and honours one the client sends. `gatewayFetch()`
15
+ * wraps `fetch` for a client pointed at the gateway: it sends an id when
16
+ * the caller set none and stamps the id the gateway answered with on the
17
+ * active span as `request_id` (contract section 4 rule 1), so the span
18
+ * joins the gateway's exact record. `stampGatewayRequestId` does the
19
+ * stamp for a response you got some other way.
20
+ *
21
+ * Never throws for a transport or server failure (resolves null, counted in
22
+ * `diagnostics()`); a bad trace id is a TypeError.
23
+ */
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.GATEWAY_REQUEST_ID_HEADER = exports.COST_SOURCE_LABELS = exports.COST_SOURCES = void 0;
26
+ exports.isExactCost = isExactCost;
27
+ exports.parseTraceCost = parseTraceCost;
28
+ exports.getTraceCost = getTraceCost;
29
+ exports.gatewayRequestId = gatewayRequestId;
30
+ exports.stampGatewayRequestId = stampGatewayRequestId;
31
+ exports.gatewayFetch = gatewayFetch;
32
+ const api_1 = require("@opentelemetry/api");
33
+ const attrs_js_1 = require("./attrs.js");
34
+ const admit_js_1 = require("./admit.js");
35
+ const context_js_1 = require("./context.js");
36
+ const control_js_1 = require("./control.js");
37
+ const runtime_js_1 = require("./runtime.js");
38
+ /** Every value, in precedence order (contract section 2), then unpriced. */
39
+ exports.COST_SOURCES = ["gateway_exact", "proxy_exact", "computed", "reported", ""];
40
+ /** The display label every cost cell prints (contract section 1). */
41
+ exports.COST_SOURCE_LABELS = {
42
+ gateway_exact: "Gateway exact",
43
+ proxy_exact: "Proxy exact",
44
+ computed: "Computed",
45
+ reported: "Reported",
46
+ "": "Unpriced",
47
+ };
48
+ /** Whether a source is one of the exact family (`gateway_exact`, `proxy_exact`). */
49
+ function isExactCost(source) {
50
+ return source === "gateway_exact" || source === "proxy_exact";
51
+ }
52
+ /** The response header that carries (and accepts) the gateway's request id. */
53
+ exports.GATEWAY_REQUEST_ID_HEADER = "X-SBO-Request-Id";
54
+ const TRACE = /^[0-9a-f]{32}$/;
55
+ function obj(v) {
56
+ return v !== null && typeof v === "object" && !Array.isArray(v) ? v : {};
57
+ }
58
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
59
+ const str = (v) => (typeof v === "string" ? v : "");
60
+ const count = (v) => (typeof v === "number" && Number.isFinite(v) ? v : 0);
61
+ function source(v) {
62
+ const s = str(v);
63
+ return exports.COST_SOURCES.includes(s) ? s : "";
64
+ }
65
+ /** Parse a TraceCost body (org response or the machine's `cost` object); null when it is not one. */
66
+ function parseTraceCost(body, destination, wantTrace = "") {
67
+ const b = obj(body);
68
+ if (!("trace_id" in b) && !("spans" in b) && !("cost_provenance" in b))
69
+ return null;
70
+ const p = obj(b.cost_provenance);
71
+ const src = obj(p.sources);
72
+ const spans = Array.isArray(b.spans) ? b.spans : [];
73
+ return {
74
+ traceId: str(b.trace_id) || wantTrace,
75
+ costUsd: num(b.cost_usd),
76
+ costProvenance: {
77
+ label: str(p.label) || "unpriced",
78
+ complete: p.complete !== false,
79
+ sources: {
80
+ gatewayExact: count(src.gateway_exact),
81
+ proxyExact: count(src.proxy_exact),
82
+ computed: count(src.computed),
83
+ reported: count(src.reported),
84
+ unpriced: count(src.unpriced),
85
+ },
86
+ },
87
+ spans: spans.map((raw) => {
88
+ const s = obj(raw);
89
+ const cs = source(s.cost_source);
90
+ return {
91
+ spanId: str(s.span_id),
92
+ model: str(s.model),
93
+ costUsd: cs ? num(s.cost_usd) : null,
94
+ costSource: cs,
95
+ reportedUsd: num(s.reported_usd),
96
+ computedUsd: num(s.computed_usd),
97
+ exactUsd: num(s.exact_usd),
98
+ costDeltaUsd: num(s.cost_delta_usd),
99
+ gatewayRequestId: str(s.gateway_request_id),
100
+ };
101
+ }),
102
+ destination,
103
+ };
104
+ }
105
+ /**
106
+ * Where a trace's cost came from, span by span. `traceId` defaults to the
107
+ * current trace; with no trace it resolves null without a call. Resolves
108
+ * null when no destination has the trace or none answered; rejects only
109
+ * with a RangeError for a trace id that is not 32 hex characters (or all
110
+ * zero), as Python raises ValueError.
111
+ */
112
+ async function getTraceCost(traceId, opts = {}) {
113
+ let id;
114
+ if (traceId === undefined || traceId === null) {
115
+ const ctx = api_1.trace.getActiveSpan()?.spanContext();
116
+ id = ctx && TRACE.test(ctx.traceId) && !/^0+$/.test(ctx.traceId) ? ctx.traceId : "";
117
+ if (!id)
118
+ return null;
119
+ }
120
+ else {
121
+ id = String(traceId).trim().toLowerCase();
122
+ if (!TRACE.test(id) || /^0+$/.test(id))
123
+ throw new RangeError(`@superbased/sdk: trace id ${JSON.stringify(traceId)} must be 32 hex characters, not all zero`);
124
+ }
125
+ const route = { online: `/traces/${id}/cost`, local: `/api/obs/trace/${id}` };
126
+ await (0, runtime_js_1.destinationKnown)();
127
+ for (const t of (0, control_js_1.targets)("read", opts)) {
128
+ const r = await (0, control_js_1.call)(t, "GET", route, { timeoutMs: (0, control_js_1.apiTimeout)(opts), quiet404: true });
129
+ if (!r.ok || r.status === 304)
130
+ continue;
131
+ const body = t.name === "local" ? obj(r.body).cost : r.body;
132
+ const parsed = parseTraceCost(body, t.name, id);
133
+ if (parsed)
134
+ return parsed;
135
+ }
136
+ return null;
137
+ }
138
+ /** The gateway's request id from a Response, a Headers object or a plain header record ("" when absent). */
139
+ function gatewayRequestId(from) {
140
+ if (!from || typeof from !== "object")
141
+ return "";
142
+ const h = from.headers ?? from;
143
+ if (h && typeof h.get === "function")
144
+ return (h.get(exports.GATEWAY_REQUEST_ID_HEADER) ?? "").trim();
145
+ for (const [k, v] of Object.entries(h)) {
146
+ if (k.toLowerCase() === exports.GATEWAY_REQUEST_ID_HEADER.toLowerCase())
147
+ return String(Array.isArray(v) ? v[0] : v).trim();
148
+ }
149
+ return "";
150
+ }
151
+ /**
152
+ * Stamp the gateway's request id (from a response or its headers) on `span`
153
+ * (default: the active span) as `request_id`, the exact join key. A no-op
154
+ * when there is no id or no recording span. Returns the id.
155
+ */
156
+ function stampGatewayRequestId(from, span) {
157
+ const id = gatewayRequestId(from);
158
+ const sp = span ?? api_1.trace.getActiveSpan();
159
+ if (id && sp?.isRecording())
160
+ sp.setAttribute(attrs_js_1.K.requestId, id);
161
+ return id;
162
+ }
163
+ /** The headers the org AI gateway reads a hosted app's end user and service from (its app budget scopes). */
164
+ const GATEWAY_USER_HEADER = "X-Superbased-User";
165
+ const GATEWAY_SERVICE_HEADER = "X-Superbased-Service";
166
+ /** The gateway ignores a longer value (internal/aigateway/gwhttp maxAppIDLen). */
167
+ const MAX_APP_ID_LEN = 512;
168
+ /** Set an app identity header unless the request has one; skip an empty, too long or non-header-safe value. Never throws. */
169
+ function setAppHeader(headers, name, value) {
170
+ const v = value.trim();
171
+ if (!v || headers.has(name) || new TextEncoder().encode(v).length > MAX_APP_ID_LEN)
172
+ return;
173
+ try {
174
+ headers.set(name, v);
175
+ }
176
+ catch {
177
+ // a value fetch cannot send as a header (non-Latin-1): leave it out
178
+ }
179
+ }
180
+ /**
181
+ * A `fetch` for a client that calls the org AI gateway (`new OpenAI({
182
+ * baseURL: <gateway>, fetch: gatewayFetch() })`): it sends an
183
+ * `X-SBO-Request-Id` when the request carries none, and stamps the id the
184
+ * gateway answered with on the span that is active when the call is made
185
+ * (an instrumentation's LLM span), so the span joins the gateway's exact
186
+ * cost record. It also names the app's end user and service
187
+ * (`X-Superbased-User`, `X-Superbased-Service`), which the gateway's app
188
+ * budget caps reserve against: the per-request user (propagateAttributes /
189
+ * identify, else init's user) and the service name admit() sends. A header
190
+ * the request already carries is kept. Pass it only to a client pointed at
191
+ * the gateway: the end user is PII, and the gateway never forwards these
192
+ * headers upstream.
193
+ */
194
+ function gatewayFetch(base) {
195
+ const f = base ?? ((i, n) => fetch(i, n));
196
+ return async (input, init) => {
197
+ const span = api_1.trace.getActiveSpan();
198
+ const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
199
+ if (!headers.has(exports.GATEWAY_REQUEST_ID_HEADER))
200
+ headers.set(exports.GATEWAY_REQUEST_ID_HEADER, `sdk-${(0, control_js_1.newId)()}`);
201
+ setAppHeader(headers, GATEWAY_USER_HEADER, (0, context_js_1.getCurrentAttributes)().user || runtime_js_1.runtime.settings?.user || "");
202
+ setAppHeader(headers, GATEWAY_SERVICE_HEADER, (0, admit_js_1.serviceName)((typeof process !== "undefined" ? process.env : {})));
203
+ const sent = headers.get(exports.GATEWAY_REQUEST_ID_HEADER) ?? "";
204
+ const resp = await f(input, { ...(init ?? {}), headers });
205
+ const got = gatewayRequestId(resp) || sent;
206
+ if (got && span?.isRecording())
207
+ span.setAttribute(attrs_js_1.K.requestId, got);
208
+ return resp;
209
+ };
210
+ }
211
+ //# sourceMappingURL=cost.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cost.js","sourceRoot":"","sources":["../../src/cost.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;;;AA2BH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AyB,EAAE,OAAO,IAAA,kBAAK,GAAE,EAAE,CAAC,CAAC;QACtG,YAAY,CAAC,OAAO,EAAE,mBAAmB,EAAE,IAAA,iCAAoB,GAAE,CAAC,IAAI,IAAI,oBAAO,CAAC,QAAQ,EAAE,IAAI,IAAI,EAAE,CAAC,CAAC;QACxG,YAAY,CAAC,OAAO,EAAE,sBAAsB,EAAE,IAAA,sBAAW,EAAC,CAAC,OAAO,OAAO,KAAK,WAAW,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAQ,CAAC,CAAC,CAAC;QACvH,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,iCAAyB,CAAC,IAAI,EAAE,CAAC;QAC1D,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,GAAG,CAAC,IAAI,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC;QAC1D,MAAM,GAAG,GAAG,gBAAgB,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC;QAC3C,IAAI,GAAG,IAAI,IAAI,EAAE,WAAW,EAAE;YAAE,IAAI,CAAC,YAAY,CAAC,YAAC,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC;QACpE,OAAO,IAAI,CAAC;IACd,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Exact cost, the SDK side (W4-2; contract `contracts/cost-source.md`, lane\n * C2; the Python twin is `get_trace_cost`, lane C5).\n *\n * - `getTraceCost(traceId)`: where a trace's cost came from, span by span:\n * `costSource` (`gateway_exact`, `proxy_exact`, `computed`, `reported`, or\n * `\"\"` = unpriced), every number kept, and the exact-minus-reported\n * delta. Online: `GET <org>/v1/sdk/traces/{id}/cost` (scope `sdk:read`);\n * local: `GET <machine>/api/obs/trace/{id}` (its `cost` object); `both`:\n * the org first, then the machine. `null` when no destination has the\n * trace (or none answered).\n * - The join key: the org AI gateway answers every inference with\n * `X-SBO-Request-Id` and honours one the client sends. `gatewayFetch()`\n * wraps `fetch` for a client pointed at the gateway: it sends an id when\n * the caller set none and stamps the id the gateway answered with on the\n * active span as `request_id` (contract section 4 rule 1), so the span\n * joins the gateway's exact record. `stampGatewayRequestId` does the\n * stamp for a response you got some other way.\n *\n * Never throws for a transport or server failure (resolves null, counted in\n * `diagnostics()`); a bad trace id is a TypeError.\n */\n\nimport { trace, type Span } from \"@opentelemetry/api\";\n\nimport { K } from \"./attrs.js\";\nimport { serviceName } from \"./admit.js\";\nimport type { Env } from \"./config.js\";\nimport { getCurrentAttributes } from \"./context.js\";\nimport { apiTimeout, call, newId, targets, type ControlOptions } from \"./control.js\";\nimport { destinationKnown, runtime } from \"./runtime.js\";\n\n/** Where a span's cost came from (contract section 1); `\"\"` is unpriced. */\nexport type CostSource = \"gateway_exact\" | \"proxy_exact\" | \"computed\" | \"reported\" | \"\";\n\n/** Every value, in precedence order (contract section 2), then unpriced. */\nexport const COST_SOURCES: readonly CostSource[] = [\"gateway_exact\", \"proxy_exact\", \"computed\", \"reported\", \"\"];\n\n/** The display label every cost cell prints (contract section 1). */\nexport const COST_SOURCE_LABELS: Readonly<Record<string, string>> = {\n gateway_exact: \"Gateway exact\",\n proxy_exact: \"Proxy exact\",\n computed: \"Computed\",\n reported: \"Reported\",\n \"\": \"Unpriced\",\n};\n\n/** Whether a source is one of the exact family (`gateway_exact`, `proxy_exact`). */\nexport function isExactCost(source: string): boolean {\n return source === \"gateway_exact\" || source === \"proxy_exact\";\n}\n\n/** The response header that carries (and accepts) the gateway's request id. */\nexport const GATEWAY_REQUEST_ID_HEADER = \"X-SBO-Request-Id\";\n\n/** A trace's cost label (contract section 5). */\nexport interface CostProvenance {\n /** `gateway_exact`, `proxy_exact`, `computed`, `reported`, `mixed` or `unpriced`. */\n label: string;\n /** False when a cost-bearing span is unpriced, so the total leaves something out (\"partial\"). */\n complete: boolean;\n sources: { gatewayExact: number; proxyExact: number; computed: number; reported: number; unpriced: number };\n}\n\n/** One cost-bearing span (contract section 6); a number is null where it is absent. */\nexport interface SpanCost {\n spanId: string;\n model: string;\n /** null when `costSource` is \"\" (unpriced): never show it as $0. */\n costUsd: number | null;\n costSource: CostSource;\n reportedUsd: number | null;\n computedUsd: number | null;\n exactUsd: number | null;\n /** Exact minus reported; set only when the source is exact and the span reported a cost. */\n costDeltaUsd: number | null;\n gatewayRequestId: string;\n}\n\n/** A trace's cost, span by span (contract section 6, camelCased). */\nexport interface TraceCost {\n traceId: string;\n /** The sum of the priced spans; null when nothing is priced. */\n costUsd: number | null;\n costProvenance: CostProvenance;\n /** Cost-bearing spans only, in start order. */\n spans: SpanCost[];\n /** Which destination answered: `online` (the org) or `local` (this machine). */\n destination: \"online\" | \"local\";\n}\n\nconst TRACE = /^[0-9a-f]{32}$/;\n\nfunction obj(v: unknown): Record<string, unknown> {\n return v !== null && typeof v === \"object\" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};\n}\nconst num = (v: unknown): number | null => (typeof v === \"number\" && Number.isFinite(v) ? v : null);\nconst str = (v: unknown): string => (typeof v === \"string\" ? v : \"\");\nconst count = (v: unknown): number => (typeof v === \"number\" && Number.isFinite(v) ? v : 0);\n\nfunction source(v: unknown): CostSource {\n const s = str(v);\n return (COST_SOURCES as readonly string[]).includes(s) ? (s as CostSource) : \"\";\n}\n\n/** Parse a TraceCost body (org response or the machine's `cost` object); null when it is not one. */\nexport function parseTraceCost(body: unknown, destination: \"online\" | \"local\", wantTrace = \"\"): TraceCost | null {\n const b = obj(body);\n if (!(\"trace_id\" in b) && !(\"spans\" in b) && !(\"cost_provenance\" in b)) return null;\n const p = obj(b.cost_provenance);\n const src = obj(p.sources);\n const spans = Array.isArray(b.spans) ? b.spans : [];\n return {\n traceId: str(b.trace_id) || wantTrace,\n costUsd: num(b.cost_usd),\n costProvenance: {\n label: str(p.label) || \"unpriced\",\n complete: p.complete !== false,\n sources: {\n gatewayExact: count(src.gateway_exact),\n proxyExact: count(src.proxy_exact),\n computed: count(src.computed),\n reported: count(src.reported),\n unpriced: count(src.unpriced),\n },\n },\n spans: spans.map((raw) => {\n const s = obj(raw);\n const cs = source(s.cost_source);\n return {\n spanId: str(s.span_id),\n model: str(s.model),\n costUsd: cs ? num(s.cost_usd) : null,\n costSource: cs,\n reportedUsd: num(s.reported_usd),\n computedUsd: num(s.computed_usd),\n exactUsd: num(s.exact_usd),\n costDeltaUsd: num(s.cost_delta_usd),\n gatewayRequestId: str(s.gateway_request_id),\n };\n }),\n destination,\n };\n}\n\n/**\n * Where a trace's cost came from, span by span. `traceId` defaults to the\n * current trace; with no trace it resolves null without a call. Resolves\n * null when no destination has the trace or none answered; rejects only\n * with a RangeError for a trace id that is not 32 hex characters (or all\n * zero), as Python raises ValueError.\n */\nexport async function getTraceCost(traceId?: string, opts: ControlOptions = {}): Promise<TraceCost | null> {\n let id: string;\n if (traceId === undefined || traceId === null) {\n const ctx = trace.getActiveSpan()?.spanContext();\n id = ctx && TRACE.test(ctx.traceId) && !/^0+$/.test(ctx.traceId) ? ctx.traceId : \"\";\n if (!id) return null;\n } else {\n id = String(traceId).trim().toLowerCase();\n if (!TRACE.test(id) || /^0+$/.test(id)) throw new RangeError(`@superbased/sdk: trace id ${JSON.stringify(traceId)} must be 32 hex characters, not all zero`);\n }\n const route = { online: `/traces/${id}/cost`, local: `/api/obs/trace/${id}` };\n await destinationKnown();\n for (const t of targets(\"read\", opts)) {\n const r = await call(t, \"GET\", route, { timeoutMs: apiTimeout(opts), quiet404: true });\n if (!r.ok || r.status === 304) continue;\n const body = t.name === \"local\" ? obj(r.body).cost : r.body;\n const parsed = parseTraceCost(body, t.name, id);\n if (parsed) return parsed;\n }\n return null;\n}\n\n/** The gateway's request id from a Response, a Headers object or a plain header record (\"\" when absent). */\nexport function gatewayRequestId(from: unknown): string {\n if (!from || typeof from !== \"object\") return \"\";\n const h = (from as { headers?: unknown }).headers ?? from;\n if (h && typeof (h as { get?: unknown }).get === \"function\") return ((h as Headers).get(GATEWAY_REQUEST_ID_HEADER) ?? \"\").trim();\n for (const [k, v] of Object.entries(h as Record<string, unknown>)) {\n if (k.toLowerCase() === GATEWAY_REQUEST_ID_HEADER.toLowerCase()) return String(Array.isArray(v) ? v[0] : v).trim();\n }\n return \"\";\n}\n\n/**\n * Stamp the gateway's request id (from a response or its headers) on `span`\n * (default: the active span) as `request_id`, the exact join key. A no-op\n * when there is no id or no recording span. Returns the id.\n */\nexport function stampGatewayRequestId(from: unknown, span?: Span): string {\n const id = gatewayRequestId(from);\n const sp = span ?? trace.getActiveSpan();\n if (id && sp?.isRecording()) sp.setAttribute(K.requestId, id);\n return id;\n}\n\ntype FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;\n\n/** The headers the org AI gateway reads a hosted app's end user and service from (its app budget scopes). */\nconst GATEWAY_USER_HEADER = \"X-Superbased-User\";\nconst GATEWAY_SERVICE_HEADER = \"X-Superbased-Service\";\n/** The gateway ignores a longer value (internal/aigateway/gwhttp maxAppIDLen). */\nconst MAX_APP_ID_LEN = 512;\n\n/** Set an app identity header unless the request has one; skip an empty, too long or non-header-safe value. Never throws. */\nfunction setAppHeader(headers: Headers, name: string, value: string): void {\n const v = value.trim();\n if (!v || headers.has(name) || new TextEncoder().encode(v).length > MAX_APP_ID_LEN) return;\n try {\n headers.set(name, v);\n } catch {\n // a value fetch cannot send as a header (non-Latin-1): leave it out\n }\n}\n\n/**\n * A `fetch` for a client that calls the org AI gateway (`new OpenAI({\n * baseURL: <gateway>, fetch: gatewayFetch() })`): it sends an\n * `X-SBO-Request-Id` when the request carries none, and stamps the id the\n * gateway answered with on the span that is active when the call is made\n * (an instrumentation's LLM span), so the span joins the gateway's exact\n * cost record. It also names the app's end user and service\n * (`X-Superbased-User`, `X-Superbased-Service`), which the gateway's app\n * budget caps reserve against: the per-request user (propagateAttributes /\n * identify, else init's user) and the service name admit() sends. A header\n * the request already carries is kept. Pass it only to a client pointed at\n * the gateway: the end user is PII, and the gateway never forwards these\n * headers upstream.\n */\nexport function gatewayFetch(base?: FetchLike): FetchLike {\n const f: FetchLike = base ?? ((i, n) => fetch(i, n));\n return async (input, init) => {\n const span = trace.getActiveSpan();\n const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));\n if (!headers.has(GATEWAY_REQUEST_ID_HEADER)) headers.set(GATEWAY_REQUEST_ID_HEADER, `sdk-${newId()}`);\n setAppHeader(headers, GATEWAY_USER_HEADER, getCurrentAttributes().user || runtime.settings?.user || \"\");\n setAppHeader(headers, GATEWAY_SERVICE_HEADER, serviceName((typeof process !== \"undefined\" ? process.env : {}) as Env));\n const sent = headers.get(GATEWAY_REQUEST_ID_HEADER) ?? \"\";\n const resp = await f(input, { ...(init ?? {}), headers });\n const got = gatewayRequestId(resp) || sent;\n if (got && span?.isRecording()) span.setAttribute(K.requestId, got);\n return resp;\n };\n}\n"]}
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Data destination (D18; contract `contracts/destination.md`, lane B6).
3
+ *
4
+ * - `local`: this machine's Observer only.
5
+ * - `online`: the org or SaaS gateway only.
6
+ * - `both`: the SDK exports to each itself, through its own exporter, so one
7
+ * failing destination never blocks the other and `both` never depends on
8
+ * the machine's push tiers.
9
+ *
10
+ * The choice, first set wins: the `destination` option, then
11
+ * `SUPERBASED_DESTINATION`, then the default this machine advertises at
12
+ * `GET <nodeUrl>/api/sdk/destination` (loopback only, 500 ms, one attempt),
13
+ * then `online` when no machine answered and the app was given a gateway and
14
+ * a credential (`inferred`, a production app), then `local`. Discovery also
15
+ * runs for an explicit `online` / `both` that still lacks a gateway URL or a
16
+ * credential, which the machine supplies (review finding R-B09), and for an
17
+ * explicit `local` / `both` with no endpoint the app named for the local
18
+ * destination: the machine advertises its own receiver (live finding L-01).
19
+ * An explicit `endpoint` only sets where the local destination sends.
20
+ *
21
+ * The gateway URL: `orgUrl`, `SUPERBASED_ORG_URL`, then the `gateway_url`
22
+ * line of the machine's credential file. The credential: `apiKey`,
23
+ * `SUPERBASED_API_KEY`, then that file's key line. The file is read only
24
+ * after the owner, mode and symlink checks of contract section 6. The
25
+ * discovery answer never decides where the key goes (review E-04): it only
26
+ * names the file, and its local URLs are used only when they are loopback.
27
+ * The machine never sends the credential itself.
28
+ *
29
+ * While discovery runs, finished spans wait in a bounded queue and then go
30
+ * to the chosen destination; none are sent to a guess.
31
+ */
32
+ import type { Context } from "@opentelemetry/api";
33
+ import type { ReadableSpan, Span, SpanProcessor } from "@opentelemetry/sdk-trace-base";
34
+ import { type DestinationChoice, type Settings } from "./config.js";
35
+ /** The machine's discovery route (contract section 4). */
36
+ export declare const DISCOVERY_PATH = "/api/sdk/destination";
37
+ export declare const DISCOVERY_API_VERSION = 1;
38
+ /** Most spans held while the destination is being discovered. */
39
+ export declare const DISCOVERY_QUEUE_MAX = 2048;
40
+ /** What the machine advertises (api_version 1), reduced to what the SDK uses. */
41
+ export interface Discovered {
42
+ destination: DestinationChoice;
43
+ source: string;
44
+ signedIn: boolean;
45
+ localEnabled: boolean;
46
+ localTracesUrl: string;
47
+ admissionUrl: string;
48
+ gatewayUrl: string;
49
+ credentialPresent: boolean;
50
+ credentialFile: string;
51
+ warnings: string[];
52
+ /** Local URLs the answer named that were not loopback, and so were ignored (review E-04). */
53
+ refused: string[];
54
+ }
55
+ /** Parse the discovery body; null when it is not a usable api_version 1 answer. */
56
+ export declare function parseDiscovery(body: unknown): Discovered | null;
57
+ /** Whether a URL's host is loopback (the only hosts discovery is sent to). */
58
+ export declare function isLoopbackUrl(url: string): boolean;
59
+ /**
60
+ * The longest discovery waits on a busy event loop (see discoverDestination),
61
+ * or ten windows when the window is longer.
62
+ */
63
+ export declare const DISCOVERY_WALL_CAP_MS = 5000;
64
+ /**
65
+ * What a discovery window's timer does when it fires at `now` (it was due at
66
+ * `due`): "rearm" when it fired late (the event loop was busy, so the
67
+ * machine's answer may be waiting behind it) and the wall cap `giveUpAt` is
68
+ * not reached; otherwise "abort".
69
+ */
70
+ export declare function discoveryTimerStep(now: number, due: number, giveUpAt: number, timeoutMs: number): "rearm" | "abort";
71
+ /** Ask the machine for its destination default. Never rejects; `error` says why on failure. */
72
+ export declare function discoverDestination(nodeUrl: string, timeoutMs: number): Promise<{
73
+ found: Discovered | null;
74
+ error: string;
75
+ }>;
76
+ /** The credential file's gateway line (contract destination.md section 6). */
77
+ export declare const CREDENTIAL_GATEWAY_FIELD = "gateway_url";
78
+ /**
79
+ * Why `url` is not a usable gateway base for the key ("" when it is): https
80
+ * (or http to a loopback host), a host, no user info, query, fragment or path.
81
+ */
82
+ export declare function gatewayProblem(url: string): string;
83
+ /**
84
+ * Read the machine's SDK credential file under the contract's rules (unix):
85
+ * not a symlink, no group or other permission bits, owned by this user. The
86
+ * first line is `<key_id>.<secret>`; each further line is `name=value`, where
87
+ * `gateway_url` names the only address the key is sent to (review E-04: the
88
+ * address comes from this owner-only file, never from the discovery answer).
89
+ * Unknown names are ignored; a gateway that is not https (or http to this
90
+ * machine) is ignored with an error. Returns the compound and the gateway,
91
+ * or `error` saying why it was refused. On Windows the file is never read:
92
+ * there is no owner check to make, so SUPERBASED_API_KEY is the way (as
93
+ * Python; review R-C33).
94
+ */
95
+ export declare function readCredentialFile(path: string): {
96
+ key: string;
97
+ gateway: string;
98
+ error: string;
99
+ };
100
+ /** Settings with what the machine supplied filled in; explicit settings win. Also returns problems. */
101
+ export declare function withDiscovered(s: Settings, d: Discovered, choice: DestinationChoice): {
102
+ settings: Settings;
103
+ problems: string[];
104
+ };
105
+ /**
106
+ * The delegate the SDK runs while discovery is in flight: holds finished
107
+ * spans (up to DISCOVERY_QUEUE_MAX; beyond that they are counted as dropped)
108
+ * and hands them to the real delegate once it is known.
109
+ */
110
+ export declare class PendingProcessor implements SpanProcessor {
111
+ private queue;
112
+ private target;
113
+ private settled;
114
+ readonly ready: Promise<void>;
115
+ private resolveReady;
116
+ constructor();
117
+ /** Counted destinations per span: one while held, then the target's (review E-31). */
118
+ get legs(): number;
119
+ /** Install the real delegate (null: drop) and replay what was held. */
120
+ resolve(target: SpanProcessor | null): void;
121
+ onStart(span: Span, ctx: Context): void;
122
+ onEnd(span: ReadableSpan): void;
123
+ forceFlush(): Promise<void>;
124
+ shutdown(): Promise<void>;
125
+ }