@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
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
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,3 +1,439 @@
1
- # Temporary Holding Version
1
+ # superbased SDK for TypeScript / Node
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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.
6
+
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.
12
+
13
+ Full reference: [superbased.app/docs/sdk/typescript](https://superbased.app/docs/sdk/typescript).
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ npm install @superbased/sdk
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.