@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
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ superbased SDK for TypeScript (@superbased/sdk)
2
+ Copyright 2026 Gaja AI
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
package/README.md CHANGED
@@ -1,10 +1,439 @@
1
- # @superbased/sdk (placeholder)
1
+ # superbased SDK for TypeScript / Node
2
2
 
3
- This version only reserves the name so the package can be published by
4
- superbased's release workflow. It contains no code.
3
+ Send your LLM app's and agents' traces to superbased over OpenTelemetry: to
4
+ the Observer on your machine while you build, to your organization's (or
5
+ superbased's hosted) gateway in production, or to both.
5
6
 
6
- Install the real package, version 0.1.0 or later:
7
+ - Package `@superbased/sdk`, ESM and CommonJS, typed. Apache-2.0.
8
+ - Node `>=20.6.0` (the `vercel-ai` instrumentation needs Node 22).
9
+ - A thin layer over OpenTelemetry JS 2.x: anything it sends, a plain OTel
10
+ exporter pointed at superbased could send too, and it attaches to an
11
+ OpenTelemetry setup you already have.
7
12
 
8
- ```
13
+ Full reference: [superbased.app/docs/sdk/typescript](https://superbased.app/docs/sdk/typescript).
14
+
15
+ ## Install
16
+
17
+ ```bash
9
18
  npm install @superbased/sdk
10
19
  ```
20
+
21
+ To use this machine's Observer, turn on Settings > Your apps in its
22
+ dashboard (or `[observability] enabled = true`). The SDK sends spans to
23
+ `http://127.0.0.1:4318/v1/traces` unless you point it elsewhere.
24
+
25
+ ## Quick start
26
+
27
+ ```ts
28
+ import { init, propagateAttributes, setUsage, shutdown, withAgentSpan, withLlmSpan } from "@superbased/sdk";
29
+
30
+ init({ serviceName: "support-bot", release: "1.4.0" }); // once at startup; idempotent
31
+
32
+ app.post("/chat", (req, res) =>
33
+ propagateAttributes({ user: req.user.id, sessionId: req.body.thread }, () =>
34
+ withAgentSpan("answer", {}, async () => {
35
+ await withLlmSpan("chat", { model: "gpt-4o", provider: "openai", prompt: req.body.messages }, async (span) => {
36
+ const r = await openai.chat.completions.create(/* ... */);
37
+ setUsage(span, {
38
+ inputTokens: r.usage?.prompt_tokens,
39
+ outputTokens: r.usage?.completion_tokens,
40
+ cacheReadTokens: r.usage?.prompt_tokens_details?.cached_tokens,
41
+ responseId: r.id,
42
+ response: r.choices[0].message.content ?? "",
43
+ });
44
+ });
45
+ }),
46
+ ),
47
+ );
48
+
49
+ await shutdown(); // in a short-lived process: flush before exit (bounded, never rejects)
50
+ ```
51
+
52
+ Or let `instrument()` create the LLM spans for you (see below).
53
+
54
+ ## Per-request attributes
55
+
56
+ ```ts
57
+ propagateAttributes({ user, sessionId, tenant, tags: ["beta"], metadata: { plan: "pro" }, release, environment }, () => handle(req));
58
+ const scope = identify({ user: req.user.id }); // the rest of this request; scope.reset() undoes it
59
+ getCurrentAttributes(); // what is in effect here
60
+ ```
61
+
62
+ - Every span started inside gets the values (the SDK's, an instrumentation's,
63
+ or your own OTel spans), carried through async work by AsyncLocalStorage.
64
+ The span already active gets the values you just set too.
65
+ - Inner values win; tags are unioned; metadata merges per key (`null` removes
66
+ a key). `undefined` leaves an outer value and `""` clears it.
67
+ - Keys: `sbo.user` (your app's end user; personal data), `session.id`,
68
+ `sbo.tenant` (your own customer), `sbo.tags`, `sbo.metadata.<key>`,
69
+ `sbo.release`, `sbo.environment`. Bounds: 256 chars a value, 32 tags of
70
+ 128, 32 metadata keys (key 128, value 512).
71
+ - `init()` takes the same seven as process-wide defaults, on the resource
72
+ (release as `service.version`, environment as
73
+ `deployment.environment.name`).
74
+
75
+ ## Spans
76
+
77
+ | Helper | Kind | Writes |
78
+ |---|---|---|
79
+ | `withSpan(name, fn)`, `withSpan(name, { kind, attributes }, fn)` | any (default CHAIN) | `openinference.span.kind` |
80
+ | `observe(fn, { name, kind, attributes, captureIo })` | any | wraps a function; `captureIo` records arguments and result |
81
+ | `withLlmSpan(name, { model, provider, operation, prompt, system, attributes }, fn)` | LLM | `gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.provider.name` (+ legacy `gen_ai.system`, `llm.*`); `prompt` string to `input.value`, message list to `gen_ai.input.messages`, a `Prompt` from `getPrompt()` to the `sbo.prompt.*` stamp; `system` to `gen_ai.system_instructions` |
82
+ | `withToolSpan(name, { toolName, callId, arguments }, fn)` | TOOL | `execute_tool`, `gen_ai.tool.name`, `gen_ai.tool.call.id`, `gen_ai.tool.call.arguments` |
83
+ | `withRetrieverSpan(name, { query }, fn)` | RETRIEVER | `retrieval`, `gen_ai.retrieval.query.text` |
84
+ | `withAgentSpan(name, { agentName, agentId }, fn)` | AGENT | `invoke_agent`, `gen_ai.agent.name`, `gen_ai.agent.id` |
85
+ | `withEmbeddingSpan(name, { model, provider }, fn)` | EMBEDDING | `embeddings`, model and provider |
86
+
87
+ A sync callback's value is returned synchronously; an async one returns a
88
+ promise. A failure records the exception once, sets ERROR and `error.type`;
89
+ success sets OK unless you set a status yourself.
90
+
91
+ Setters (no-ops on a span that is not recording):
92
+
93
+ - `setUsage(span, { inputTokens, outputTokens, totalTokens, cacheReadTokens, cacheWriteTokens, reasoningTokens, responseId, requestId, responseModel, finishReasons, costUsd, prompt, response })`.
94
+ `inputTokens` is GROSS (it includes cache reads and writes, which are
95
+ subsets of it); `outputTokens` includes `reasoningTokens`. `totalTokens` is
96
+ optional (Observer derives input + output). A negative count is a
97
+ RangeError. A reported `costUsd` is kept, but Observer's own price wins when
98
+ it knows the model.
99
+ - `setContent(span, { prompt, response, toolArgs, toolResult })`,
100
+ `setInput(span, v)`, `setOutput(span, v)` (on a RETRIEVER span: the
101
+ documents), `setToolResult(span, r)`, `setDocuments(span, docs)`,
102
+ `setRequestParams(span, { temperature, maxTokens, topP, ... })`.
103
+ - `getCurrentTraceId()`, `getCurrentSpanId()`.
104
+
105
+ The SDK writes only keys from Observer's vocabulary (the GenAI semantic
106
+ conventions pinned at `SEMCONV_COMMIT`, plus OpenInference names Observer
107
+ reads); `Attr` lists them.
108
+
109
+ ## Auto-instrumentation: `instrument()`
110
+
111
+ ```ts
112
+ init();
113
+ instrument(["openai", "anthropic", "langchain", "mcp", "vercel-ai", "gemini", "bedrock", "llama-index", "openai-agents"]); // or instrument() for every installed one
114
+ ```
115
+
116
+ | Target | Install next to the framework | Notes |
117
+ |---|---|---|
118
+ | `openai` | `@arizeai/openinference-instrumentation-openai` | chat, completions, embeddings, responses |
119
+ | `anthropic` | `@arizeai/openinference-instrumentation-anthropic` | messages, with cache usage |
120
+ | `langchain` (also `langgraph`) | `@arizeai/openinference-instrumentation-langchain` | LangGraph runs are LangChain runs |
121
+ | `mcp` | `@arizeai/openinference-instrumentation-mcp` | carries the trace across MCP stdio / SSE / streamable HTTP, so a server's spans join the caller's trace |
122
+ | `vercel-ai` | `@ai-sdk/otel` | AI SDK v7 (Node 22+): registers its telemetry integration, which already emits the GenAI semconv |
123
+ | `gemini` (also `google-genai`) | `@traceloop/instrumentation-google-generativeai` | `@google/genai` (Node 22+), clients built after `instrument()`; ESM: hand over `{ ...(await import("@google/genai")) }` and build the client from that copy |
124
+ | `bedrock` | `@arizeai/openinference-instrumentation-bedrock` | `@aws-sdk/client-bedrock-runtime`: InvokeModel, Converse and their streams |
125
+ | `llama-index` (also `llamaindex`) | `@traceloop/instrumentation-llamaindex` | LlamaIndex.TS engines, retrievers, synthesizers and LLM `chat` |
126
+ | `openai-agents` (also `agents`) | `@arizeai/openinference-instrumentation-openai-agents` | `@openai/agents`: a tracing processor added beside yours |
127
+
128
+ CrewAI and Pydantic AI are Python-only frameworks; asking for them here is a
129
+ TypeError that says so (use the Python SDK).
130
+
131
+ - Returns `{ target: status }`: `instrumented`, `already`, `not-installed`
132
+ (install the package above and the framework) or `error: ...`. It never
133
+ throws, except a TypeError for an unknown target name.
134
+ - CommonJS apps: call it before or after `require("openai")`.
135
+ - ESM apps import their own copy of the framework, so hand it over:
136
+ `instrument(["openai"], { modules: { openai: await import("openai") } })`
137
+ (`anthropic`: `await import("@anthropic-ai/sdk")`; `langchain`:
138
+ `@langchain/core/callbacks/manager`; `vercel-ai`: `{ ai, otel }`).
139
+ - The spans go through the SDK, so per-request attributes, sampling, masking
140
+ and the destination apply to them. `uninstrument()` undoes it.
141
+
142
+ ## Where your data goes: `destination`
143
+
144
+ | Value | The SDK exports to |
145
+ |---|---|
146
+ | `local` | this machine's Observer only |
147
+ | `online` | your organization's (or superbased's hosted) gateway only |
148
+ | `both` | each of them, through its own exporter: one being down never delays or drops the other |
149
+
150
+ The choice: `init({ destination })`, then `SUPERBASED_DESTINATION`, then the
151
+ default this machine's Observer advertises (`both` when you have signed in,
152
+ `local` otherwise, or what you chose in its Settings), then `local`. While the
153
+ SDK asks the machine (at most 500 ms, loopback only), finished spans wait;
154
+ `await ready()` resolves once it knows.
155
+
156
+ - The gateway URL: `orgUrl`, `SUPERBASED_ORG_URL`, then the one the machine
157
+ learned when you signed in. Spans go to `<orgUrl>/v1/traces`.
158
+ - The credential: `apiKey`, `SUPERBASED_API_KEY`, then the file the machine
159
+ wrote at sign-in (read only when it is yours alone: not a symlink, mode
160
+ 0600). It is sent only to the gateway, never to the machine.
161
+ - `online` without a gateway URL or a credential exports nothing; `both`
162
+ exports to the machine only. Either way the SDK says so once and in
163
+ `diagnostics().destinationProblems`. Fix: `observer sdk sign-in`, or
164
+ set `SUPERBASED_ORG_URL` and `SUPERBASED_API_KEY`.
165
+ - An explicit `destination` of `online` or `both` still takes the gateway URL
166
+ and the credential file from the machine when you did not give them.
167
+ - No destination chosen, no machine answering, and a gateway URL plus a
168
+ credential given: `online` (`destinationSource: "inferred"`).
169
+ - An explicit `endpoint` only sets where the local destination sends.
170
+ - Your app's `OTEL_EXPORTER_OTLP_*` variables configure the local exporter,
171
+ and only when the destination is `local`; they never redirect or add
172
+ headers to the online one, and the key never rides to their endpoint.
173
+ - Control calls and `admit()` follow no redirect.
174
+
175
+ ## Scores and feedback
176
+
177
+ ```ts
178
+ const traceId = getCurrentTraceId(); // keep it with your answer
179
+ await score("faithfulness", 0.92, { traceId, scorer: "judge", scorerVersion: "3" });
180
+ await feedback(false, { traceId, comment: "wrong city" }); // an end user's thumbs-down
181
+ ```
182
+
183
+ - `score(name, value, { traceId, spanId, comment, kind, scorer, scorerVersion, runId, scoreId, timestamp })`:
184
+ the value is a number, a boolean or a label; `traceId` defaults to the
185
+ active trace and the score is trace-level unless you pass `spanId` (the
186
+ same as Python).
187
+ - Written to every destination (`both`: to each, with the same id, so a
188
+ retry or the second copy never doubles it). Resolves
189
+ `{ ok, id, clientId, destinations, errors }`: `ok` only when every
190
+ destination accepted it, `id` the stored `sc_...` id. It never throws: a
191
+ score the rules refuse (a bad name, a `kind` that disagrees with the value,
192
+ no trace) resolves `ok: false` with an error naming the rule's code
193
+ (`invalid_name`, `kind_mismatch`, `invalid_trace_id`, ...) before any call.
194
+ - `flush()` waits for pending score writes.
195
+
196
+ ## Where a trace's cost came from: `getTraceCost`
197
+
198
+ ```ts
199
+ const cost = await getTraceCost(traceId); // null when no destination has the trace
200
+ for (const s of cost?.spans ?? []) console.log(s.model, s.costUsd, s.costSource, s.costDeltaUsd);
201
+
202
+ // Calls through your organization's AI gateway: let the SDK carry the join key
203
+ const openai = new OpenAI({ baseURL: "https://gw.example/v1", fetch: gatewayFetch() });
204
+ ```
205
+
206
+ - `costSource`: `gateway_exact` (the org AI
207
+ gateway observed the provider's tokens), `proxy_exact` (this machine's
208
+ proxy did), `computed` (priced from the span's tokens), `reported` (the
209
+ instrumentation's own number, used only for an unpriced model) or `""`:
210
+ unpriced, `costUsd: null`, never $0. `costDeltaUsd` is exact minus
211
+ reported. `costProvenance` labels the trace (`mixed`, and `complete:
212
+ false` when a span is unpriced).
213
+ - Reads the org (`GET /v1/sdk/traces/{id}/cost`, scope `sdk:read`) under
214
+ `online`, the machine's trace detail under `local`, the org then the
215
+ machine under `both`.
216
+ - `gatewayFetch()` sends an `X-SBO-Request-Id` when the call carries none and
217
+ stamps the id the gateway answers with on the active span as `request_id`,
218
+ the exact join key. `stampGatewayRequestId(response)` does the stamp for a
219
+ response you got another way. It also names the end user and the service
220
+ for the gateway's app budgets (`X-Superbased-User`: the per-request user,
221
+ else `init`'s; `X-Superbased-Service`: the spans' `service.name`), keeping
222
+ any such header the call already sets. Pass `gatewayFetch()` only to a
223
+ client pointed at the gateway: the end user is PII.
224
+
225
+ ## Experiments
226
+
227
+ ```ts
228
+ const res = await runExperiment({
229
+ name: "prompt-v7",
230
+ dataset: "golden-qa", // a dataset name or id, or inline items with datasetName
231
+ task: async (input) => answer(input),
232
+ evaluators: [function exact_match({ output, expectedOutput }) { return output === expectedOutput; }],
233
+ failUnder: 0.9, // CI gate
234
+ });
235
+ console.log(res.passRate, res.summary);
236
+ ```
237
+
238
+ - Creates a run on each destination (freezing a dataset snapshot unless
239
+ `snapshotVersion` pins one), runs `task` on each item in its own trace, runs
240
+ the evaluators in-process and posts each result as it finishes, then
241
+ finishes the run. Under `both` the task runs once and each result goes to
242
+ both sides.
243
+ - Evaluators return a number, a boolean, a label, `{ name, value, comment }`
244
+ or a list of those; `{ name, version, evaluate }` names and versions the
245
+ scorer.
246
+ - Inline items: pass `datasetName` to record them as a snapshot of that
247
+ dataset; without it they run in-process only.
248
+ - A dataset found nowhere, or a run that cannot be created, rejects with
249
+ `ExperimentError`; below `failUnder` it rejects with `ExperimentGateFailed`
250
+ and sets `process.exitCode = 1`. The gate is strict by default: a run that
251
+ scored nothing, a skipped destination or a result that was not accepted
252
+ also fails it (`strict: false` gates on the pass rate alone). A CI key
253
+ needs the `sdk:eval` scope.
254
+ - The key `observer sdk sign-in` stores has no `sdk:eval`, so the org answers
255
+ 403 `insufficient_scope`: that destination is skipped with an entry in
256
+ `errors` and the run goes on with this machine under `both` (never a
257
+ rejection; under `online` alone the result is empty).
258
+ - `getDataset(nameOrId, { version })` reads a snapshot's items; a dataset
259
+ found nowhere rejects with `ExperimentError`.
260
+
261
+ ## Prompts
262
+
263
+ ```ts
264
+ const p = await getPrompt("support-reply", { label: "production", fallback: "Answer: {{question}}" });
265
+ const text = p.compile({ question }); // also stamps sbo.prompt.name / version / label on the active span
266
+ withLlmSpan("chat", { model: "gpt-4o", prompt: p }, () => /* ... */);
267
+ ```
268
+
269
+ - By `label` (`production`, the default, or `staging`) or `version`, not both.
270
+ - Cached for `promptCacheTtlMs` (60 s); after that the cached copy is returned
271
+ at once and revalidated in the background (stale-while-revalidate, ETag). A
272
+ failed refresh keeps serving the cached copy; a 404 drops it.
273
+ - Staged rollout: when a label serves a candidate to a
274
+ percentage of users, the SDK sends the SHA-256 of the current trace's user
275
+ (else its session; or pass `user` / `sessionId`), never the id itself, and
276
+ gets that key's side. It caches at most one copy per side (`candidate`,
277
+ `base`, `unkeyed`) and buckets other keys itself with the rollout's salt,
278
+ so a million users cost three fetches. `p.version` is the version served,
279
+ `p.cohort` the side; both are stamped (`sbo.prompt.version`,
280
+ `sbo.prompt.cohort`).
281
+ - Each destination keeps its own cached copy and revalidates against itself,
282
+ so under `both` one side failing never drops a copy the other served.
283
+ - With nothing cached, a failed fetch throws `PromptNotFound` (no destination
284
+ has it) or `PromptFetchError` (a transport or server failure), both
285
+ `PromptError`s, unless you pass
286
+ a `fallback` (returned with `isFallback: true`, never cached, stamps
287
+ nothing).
288
+ - `compile()` fills `{{name}}` in one pass and throws `PromptCompileError`
289
+ naming every missing variable. `p.text`, `p.messages`, `p.variables`,
290
+ `p.config`, `p.version`, `p.label`.
291
+
292
+ ## Trace context across services
293
+
294
+ ```ts
295
+ await queue.send({ body, headers: inject() }); // traceparent (+ baggage)
296
+ continueTrace(message.headers, () => withSpan("consume", work)); // join the caller's trace
297
+ ```
298
+
299
+ `extract(headers)` returns the context; `getTraceparent()` the header value.
300
+ They always use W3C trace context, whatever propagator your app set. Values
301
+ set with `propagateAttributes({ ..., asBaggage: true })` travel as W3C
302
+ baggage and are restored by `continueTrace` (only use it for values the next
303
+ service may see).
304
+
305
+ ## Sampling, filtering, masking
306
+
307
+ - `sampleRate` (0..1, `SUPERBASED_SAMPLE_RATE`, or `OTEL_TRACES_SAMPLER` +
308
+ `_ARG`): keeps or drops whole traces by trace id, parent-based. The same
309
+ trace id gets the same answer in every service and in both superbased SDKs.
310
+ - `shouldExport(span) => boolean`: return false to drop a finished span. A
311
+ hook that throws keeps the span and is counted.
312
+ - `mask(value, key) => value`: rewrites every content value (prompts,
313
+ responses, messages, tool arguments and results, documents; on spans and
314
+ span events, from any instrumentation) before export. Return `null` to drop
315
+ it. A hook that throws drops that value, never the span, and is counted:
316
+ content is never sent unmasked by accident.
317
+ - Content is captured by default. `captureContent: false` removes it from
318
+ every exported span, an instrumentation's included; `maxContentChars`
319
+ clips each value.
320
+
321
+ These apply to what the SDK exports; a provider's other processors see the
322
+ original span.
323
+
324
+ ## Pre-flight check: `admit()`
325
+
326
+ ```ts
327
+ const v = await admit(userMessage, { user: "alice", session: "s1" });
328
+ if (!v.allowed) return v.reason;
329
+ ```
330
+
331
+ - Goes where your destination points: this machine for `local`, your
332
+ organization's gateway (`<orgUrl>/v1/sdk/admit`, with the key) for `online`
333
+ or `both`, the machine when the gateway is not configured. An explicit
334
+ `endpoint` or `orgUrl` wins.
335
+ - Never rejects. With no decision it admits, unless `failClosed: true`
336
+ (`SUPERBASED_ADMISSION_FAIL_CLOSED=1`). `v.degraded` says why:
337
+ `admission-unavailable` (403/404), `client-timeout`, `client-transport`,
338
+ `client-http-error`, `client-bad-response`.
339
+ - Timeout 12 s, or what the server advertises. Inside a span the verdict is
340
+ recorded on it (`sbo.admission.*`).
341
+
342
+ ## An app that already uses OpenTelemetry
343
+
344
+ - No provider registered: `init()` registers its own (`diagnostics().mode` is `owned`).
345
+ - OTel JS 2.x providers take processors only at construction. Add the SDK's
346
+ and `init()` exports through yours (`attached`):
347
+
348
+ ```ts
349
+ const provider = new NodeTracerProvider({ spanProcessors: [spanProcessor(), ...yourProcessors] });
350
+ provider.register();
351
+ init({ serviceName: "my-app" });
352
+ ```
353
+ - An OTel JS 1.x provider (has `addSpanProcessor`): the SDK adds its processor (`attached`).
354
+ - Any other provider: the SDK keeps a private one for its own spans
355
+ (`standalone`); they still join the active trace.
356
+
357
+ `shutdown()` stops only the SDK's exporters; your provider keeps running.
358
+ Calling `init()` again with the same settings does nothing; with different
359
+ settings it replaces the exporters in place.
360
+
361
+ ## Flush, shutdown, diagnostics
362
+
363
+ - `await flush(timeoutMs?)`: export now and wait for pending score writes
364
+ (await it at the end of a serverless handler). `await shutdown(timeoutMs?)`:
365
+ flush and stop. Both are bounded by `shutdownTimeoutMs` and never reject.
366
+ - On `beforeExit` the SDK flushes by itself (`exitHook`). Call `shutdown()`
367
+ before `process.exit()`. With an endpoint down, its in-flight request can
368
+ keep the process alive up to `exportTimeoutMs` after the flush gives up.
369
+ - Failures are summarised in at most one `console.warn` line a minute
370
+ (`debug: true` logs each).
371
+ - `diagnostics()`: `mode`, `destination`, `destinationSource`,
372
+ `destinations`, `destinationProblems`, `pendingSpans`, `exportedSpans`,
373
+ `failedExports`, `droppedSpans`, `sampledOutSpans`, `filteredSpans`,
374
+ `shouldExportErrors`, `maskErrors`, `lastError`, `controlCalls`,
375
+ `controlFailures`.
376
+
377
+ ## Settings
378
+
379
+ Every option has an environment variable. An explicit option wins, then the
380
+ `SUPERBASED_*` variable, then the standard OpenTelemetry one, then (for the
381
+ destination, gateway URL and credential) what this machine advertises, then
382
+ the default. `settings()` returns what was resolved. Durations are
383
+ milliseconds.
384
+
385
+ | `init()` option | Environment | Default |
386
+ |---|---|---|
387
+ | `destination` | `SUPERBASED_DESTINATION` | the machine's default, else `local` |
388
+ | `orgUrl` | `SUPERBASED_ORG_URL` | the machine's, else none |
389
+ | `apiKey` | `SUPERBASED_API_KEY` | the machine's credential file, else none |
390
+ | `endpoint` (the local destination's URL) | `SUPERBASED_OTLP_ENDPOINT`; for destination `local` only also `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`, `OTEL_EXPORTER_OTLP_ENDPOINT` (+ `/v1/traces`) | the machine's advertised receiver, else `http://127.0.0.1:4318/v1/traces` |
391
+ | `headers` | `SUPERBASED_OTLP_HEADERS`; for destination `local` only also `OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_EXPORTER_OTLP_TRACES_HEADERS` (merged; option on top) | none |
392
+ | `nodeUrl` | `SUPERBASED_NODE_URL` | `http://127.0.0.1:8081` |
393
+ | `discover` | `SUPERBASED_DISCOVER` | on |
394
+ | `discoverTimeoutMs` | `SUPERBASED_DISCOVER_TIMEOUT_MS` | 500 |
395
+ | `serviceName` | `SUPERBASED_SERVICE_NAME`, `OTEL_SERVICE_NAME`, `service.name` in `OTEL_RESOURCE_ATTRIBUTES` | `custom-app` |
396
+ | `resourceAttributes` | `OTEL_RESOURCE_ATTRIBUTES` | none |
397
+ | `user` | `SUPERBASED_USER` | none |
398
+ | `sessionId` | `SUPERBASED_SESSION_ID` | none |
399
+ | `tenant` | `SUPERBASED_TENANT` | none |
400
+ | `tags` | `SUPERBASED_TAGS` (comma list) | none |
401
+ | `metadata` | `SUPERBASED_METADATA` (`k=v,k2=v2`) | none |
402
+ | `release` | `SUPERBASED_RELEASE` | none |
403
+ | `environment` | `SUPERBASED_ENVIRONMENT` | none |
404
+ | `captureContent` | `SUPERBASED_CAPTURE_CONTENT` (legacy `OBSERVER_CAPTURE_CONTENT`) | on |
405
+ | `maxContentChars` | `SUPERBASED_MAX_CONTENT_CHARS` | 8000 (0 = no clip) |
406
+ | `sampleRate` | `SUPERBASED_SAMPLE_RATE`, `OTEL_TRACES_SAMPLER` + `OTEL_TRACES_SAMPLER_ARG` | 1 |
407
+ | `mask`, `shouldExport` | code only | none |
408
+ | `exportTimeoutMs` | `SUPERBASED_EXPORT_TIMEOUT_MS`, `OTEL_EXPORTER_OTLP_TRACES_TIMEOUT`, `OTEL_EXPORTER_OTLP_TIMEOUT` | 5000 |
409
+ | `shutdownTimeoutMs` | `SUPERBASED_SHUTDOWN_TIMEOUT_MS` | 2000 |
410
+ | `apiTimeoutMs` (scores, prompts, datasets, experiments) | `SUPERBASED_API_TIMEOUT_MS` | 5000 |
411
+ | `promptCacheTtlMs` | `SUPERBASED_PROMPT_CACHE_TTL_MS` | 60000 |
412
+ | `exitHook` | `SUPERBASED_EXIT_HOOK` | on |
413
+ | `debug` | `SUPERBASED_DEBUG` | off |
414
+ | `console` (also print spans) | `SUPERBASED_CONSOLE` | off |
415
+ | `exporter`, `tracerProvider` | code only | OTLP/HTTP; the global provider |
416
+
417
+ `admit()` options: `endpoint` (`SUPERBASED_ADMISSION_ENDPOINT`), `orgUrl`
418
+ (`SUPERBASED_ORG_URL`), `apiKey` (`SUPERBASED_API_KEY`), `timeoutMs` (the
419
+ server's advertised timeout, else 12000), `failClosed`
420
+ (`SUPERBASED_ADMISSION_FAIL_CLOSED`, off).
421
+
422
+ ## Echo-guard caveat
423
+
424
+ Never set the resource attribute `sbo.emitted_by=observer`: it marks
425
+ Observer's own telemetry, and a resource carrying it is dropped at ingestion.
426
+ The SDK sets `sbo.sdk="superbased-typescript"`.
427
+
428
+ ## Development
429
+
430
+ ```bash
431
+ npm ci # from the committed lockfile
432
+ npm test # build (ESM + CJS) and run every node --test suite, offline
433
+ npm run typecheck
434
+ npm run example # compile and run examples/quickstart.ts
435
+ ```
436
+
437
+ `SUPERBASED_RECORD_FIXTURES=1 npm test` re-records the instrumentation
438
+ fixtures (`sdk/contract/fixtures/instrument/*-ts.json`) after an upgrade;
439
+ review the diff.
@@ -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>;