@superbased/sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +438 -2
  4. package/dist/cjs/admit.d.ts +139 -0
  5. package/dist/cjs/admit.js +442 -0
  6. package/dist/cjs/admit.js.map +1 -0
  7. package/dist/cjs/attrs.d.ts +113 -0
  8. package/dist/cjs/attrs.js +183 -0
  9. package/dist/cjs/attrs.js.map +1 -0
  10. package/dist/cjs/config.d.ts +202 -0
  11. package/dist/cjs/config.js +386 -0
  12. package/dist/cjs/config.js.map +1 -0
  13. package/dist/cjs/context.d.ts +102 -0
  14. package/dist/cjs/context.js +234 -0
  15. package/dist/cjs/context.js.map +1 -0
  16. package/dist/cjs/control.d.ts +99 -0
  17. package/dist/cjs/control.js +243 -0
  18. package/dist/cjs/control.js.map +1 -0
  19. package/dist/cjs/cost.d.ts +108 -0
  20. package/dist/cjs/cost.js +211 -0
  21. package/dist/cjs/cost.js.map +1 -0
  22. package/dist/cjs/destination.d.ts +125 -0
  23. package/dist/cjs/destination.js +357 -0
  24. package/dist/cjs/destination.js.map +1 -0
  25. package/dist/cjs/experiments.d.ts +237 -0
  26. package/dist/cjs/experiments.js +678 -0
  27. package/dist/cjs/experiments.js.map +1 -0
  28. package/dist/cjs/export.d.ts +84 -0
  29. package/dist/cjs/export.js +328 -0
  30. package/dist/cjs/export.js.map +1 -0
  31. package/dist/cjs/index.d.ts +168 -0
  32. package/dist/cjs/index.js +581 -0
  33. package/dist/cjs/index.js.map +1 -0
  34. package/dist/cjs/instrument.d.ts +88 -0
  35. package/dist/cjs/instrument.js +397 -0
  36. package/dist/cjs/instrument.js.map +1 -0
  37. package/dist/cjs/package.json +1 -0
  38. package/dist/cjs/policy.d.ts +77 -0
  39. package/dist/cjs/policy.js +252 -0
  40. package/dist/cjs/policy.js.map +1 -0
  41. package/dist/cjs/prompts.d.ts +175 -0
  42. package/dist/cjs/prompts.js +476 -0
  43. package/dist/cjs/prompts.js.map +1 -0
  44. package/dist/cjs/propagation.d.ts +34 -0
  45. package/dist/cjs/propagation.js +151 -0
  46. package/dist/cjs/propagation.js.map +1 -0
  47. package/dist/cjs/req.d.ts +10 -0
  48. package/dist/cjs/req.js +3 -0
  49. package/dist/cjs/req.js.map +1 -0
  50. package/dist/cjs/runtime.d.ts +44 -0
  51. package/dist/cjs/runtime.js +67 -0
  52. package/dist/cjs/runtime.js.map +1 -0
  53. package/dist/cjs/scores.d.ts +102 -0
  54. package/dist/cjs/scores.js +226 -0
  55. package/dist/cjs/scores.js.map +1 -0
  56. package/dist/cjs/spans.d.ts +193 -0
  57. package/dist/cjs/spans.js +398 -0
  58. package/dist/cjs/spans.js.map +1 -0
  59. package/dist/cjs/vendor.d.ts +33 -0
  60. package/dist/cjs/vendor.js +67 -0
  61. package/dist/cjs/vendor.js.map +1 -0
  62. package/dist/esm/admit.d.ts +139 -0
  63. package/dist/esm/admit.js +432 -0
  64. package/dist/esm/admit.js.map +1 -0
  65. package/dist/esm/attrs.d.ts +113 -0
  66. package/dist/esm/attrs.js +179 -0
  67. package/dist/esm/attrs.js.map +1 -0
  68. package/dist/esm/config.d.ts +202 -0
  69. package/dist/esm/config.js +364 -0
  70. package/dist/esm/config.js.map +1 -0
  71. package/dist/esm/context.d.ts +102 -0
  72. package/dist/esm/context.js +221 -0
  73. package/dist/esm/context.js.map +1 -0
  74. package/dist/esm/control.d.ts +99 -0
  75. package/dist/esm/control.js +230 -0
  76. package/dist/esm/control.js.map +1 -0
  77. package/dist/esm/cost.d.ts +108 -0
  78. package/dist/esm/cost.js +202 -0
  79. package/dist/esm/cost.js.map +1 -0
  80. package/dist/esm/destination.d.ts +125 -0
  81. package/dist/esm/destination.js +346 -0
  82. package/dist/esm/destination.js.map +1 -0
  83. package/dist/esm/experiments.d.ts +237 -0
  84. package/dist/esm/experiments.js +666 -0
  85. package/dist/esm/experiments.js.map +1 -0
  86. package/dist/esm/export.d.ts +84 -0
  87. package/dist/esm/export.js +314 -0
  88. package/dist/esm/export.js.map +1 -0
  89. package/dist/esm/index.d.ts +168 -0
  90. package/dist/esm/index.js +500 -0
  91. package/dist/esm/index.js.map +1 -0
  92. package/dist/esm/instrument.d.ts +88 -0
  93. package/dist/esm/instrument.js +391 -0
  94. package/dist/esm/instrument.js.map +1 -0
  95. package/dist/esm/policy.d.ts +77 -0
  96. package/dist/esm/policy.js +240 -0
  97. package/dist/esm/policy.js.map +1 -0
  98. package/dist/esm/prompts.d.ts +175 -0
  99. package/dist/esm/prompts.js +460 -0
  100. package/dist/esm/prompts.js.map +1 -0
  101. package/dist/esm/propagation.d.ts +34 -0
  102. package/dist/esm/propagation.js +145 -0
  103. package/dist/esm/propagation.js.map +1 -0
  104. package/dist/esm/req.d.ts +10 -0
  105. package/dist/esm/req.js +2 -0
  106. package/dist/esm/req.js.map +1 -0
  107. package/dist/esm/runtime.d.ts +44 -0
  108. package/dist/esm/runtime.js +59 -0
  109. package/dist/esm/runtime.js.map +1 -0
  110. package/dist/esm/scores.d.ts +102 -0
  111. package/dist/esm/scores.js +219 -0
  112. package/dist/esm/scores.js.map +1 -0
  113. package/dist/esm/spans.d.ts +193 -0
  114. package/dist/esm/spans.js +378 -0
  115. package/dist/esm/spans.js.map +1 -0
  116. package/dist/esm/vendor.d.ts +33 -0
  117. package/dist/esm/vendor.js +61 -0
  118. package/dist/esm/vendor.js.map +1 -0
  119. package/package.json +130 -4
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instrument.js","sourceRoot":"","sources":["../../src/instrument.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,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AAC;QAC3B,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;gBACjB,GAAG,CAAC,IAAI,CAAC,GAAG,aAAa,CAAC;gBAC1B,SAAS;YACX,CAAC;YACD,MAAM,CAAC,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,IAAI,KAAK,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YAC7E,GAAG,CAAC,IAAI,CAAC,GAAG,UAAU,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;QAC1C,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,8HAA8H;AAC9H,MAAM,UAAU,YAAY,CAAC,OAA2B;IACtD,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;IAC3D,KAAK,MAAM,IAAI,IAAI,IAAI,EAAE,CAAC;QACxB,MAAM,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC3B,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QACpB,IAAI,CAAC;YACH,CAAC,EAAE,IAAI,EAAE,CAAC;QACZ,CAAC;QAAC,MAAM,CAAC;YACP,SAAS;QACX,CAAC;IACH,CAAC;AACH,CAAC;AAED,oCAAoC;AACpC,MAAM,UAAU,YAAY;IAC1B,OAAO,CAAC,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;AAC5B,CAAC","sourcesContent":["/**\n * `instrument([...])`: framework auto-instrumentation over the upstream\n * OpenInference JS instrumentations, or OpenLLMetry's (Traceloop) where\n * OpenInference has no JS one (Gemini's `@google/genai`, LlamaIndex.TS)\n * (plan D10: depend on them, own only the wiring and the conformance\n * fixtures; contract sdk-api-surface.md section 10). CrewAI and Pydantic AI\n * are Python-only, so they have no row ({@link PYTHON_ONLY}).\n *\n * Each target is a row of {@link TARGETS}. The instrumentation packages are\n * optional peer dependencies: install the one you need next to the framework\n * (`npm i @arizeai/openinference-instrumentation-openai`). A missing package\n * or framework is reported, never thrown. The spans go through the SDK's\n * provider, so identity, sampling, masking and the destination apply to them\n * like to the SDK's own spans.\n *\n * CommonJS apps: `instrument()` patches the framework module `require`\n * returns, before or after your own `require`. ESM apps import their own\n * copy of the framework, so hand it over: `instrument([\"openai\"], { modules:\n * { openai: await import(\"openai\") } })`. `vercel-ai` is an AI SDK v7\n * telemetry integration (Node 22+, ESM), registered with `registerTelemetry`;\n * the AI SDK's own spans already use the pinned GenAI semconv, so no\n * OpenInference layer is needed there.\n */\n\nimport { realpathSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { join } from \"node:path\";\n\nimport { trace, type TracerProvider } from \"@opentelemetry/api\";\n\nimport { req } from \"./req.js\";\nimport { runtime } from \"./runtime.js\";\n\nexport const INSTRUMENTED = \"instrumented\";\nexport const ALREADY = \"already\";\nexport const NOT_INSTALLED = \"not-installed\";\n\nexport type InstrumentTarget =\n | \"openai\"\n | \"anthropic\"\n | \"langchain\"\n | \"mcp\"\n | \"vercel-ai\"\n | \"gemini\"\n | \"bedrock\"\n | \"llama-index\"\n | \"openai-agents\";\n\ninterface Ctx {\n provider: TracerProvider;\n /** The framework module(s) the caller handed over, if any. */\n module: unknown;\n}\n\ninterface Active {\n undo(): void;\n}\n\n/** One instrumentable framework. */\ninterface Target {\n name: InstrumentTarget;\n /** The instrumentation package (an optional peer dependency). */\n package: string;\n /** The framework module that must load. */\n library: string;\n note: string;\n /** Instrument; throws on failure. `null` = the host already did. */\n install(ctx: Ctx): Active | null;\n}\n\ntype Loaded = Record<string, unknown>;\n\n/**\n * Load an optional peer (an instrumentation package, or a framework not\n * handed over): from this package's location first, then from the app's.\n *\n * The second look matters when the app installed the SDK from a folder\n * (`npm install ./sdk/typescript`): npm links the folder, Node resolves from\n * its real path, and the peers the app installed beside the framework are\n * not on that path. The app is found from its entry script, then the\n * working directory.\n */\nfunction load(spec: string): Loaded {\n try {\n return req(spec) as Loaded;\n } catch (err) {\n if ((err as { code?: string }).code !== \"MODULE_NOT_FOUND\") throw err;\n for (const app of appRequires()) {\n try {\n return app(spec) as Loaded;\n } catch {\n // not there either; the original error says what is missing\n }\n }\n throw err;\n }\n}\n\n/** `require`s anchored at the app: its entry script's folder, then the working directory. */\nfunction appRequires(): NodeJS.Require[] {\n const anchors: string[] = [];\n const entry = typeof process !== \"undefined\" ? process.argv?.[1] : undefined;\n if (entry) {\n try {\n anchors.push(realpathSync(entry));\n } catch {\n anchors.push(entry);\n }\n }\n if (typeof process !== \"undefined\" && typeof process.cwd === \"function\") anchors.push(join(process.cwd(), \"noop.js\"));\n const out: NodeJS.Require[] = [];\n for (const a of anchors) {\n try {\n out.push(createRequire(a));\n } catch {\n // an anchor that is not a path\n }\n }\n return out;\n}\n\n/** An OpenInference class instrumentation patched onto one framework module. */\nfunction oiClass(name: InstrumentTarget, pkg: string, cls: string, library: string, note = \"\"): Target {\n return {\n name,\n package: pkg,\n library,\n note,\n install({ provider, module }) {\n const mod = load(pkg);\n if (typeof mod.isPatched === \"function\" && (mod.isPatched as () => boolean)()) return null;\n const Cls = mod[cls] as new (o: object) => {\n manuallyInstrument(m: unknown): void;\n disable(): void;\n unpatch?(m: unknown): void;\n setTracerProvider?(p: TracerProvider): void;\n };\n const inst = new Cls({ tracerProvider: provider, instrumentationConfig: { enabled: false } });\n inst.setTracerProvider?.(provider);\n const target = module ?? load(library);\n inst.manuallyInstrument(target);\n return {\n undo() {\n inst.disable();\n // Some instrumentations' disable() leaves a manual patch in place (LangChain): unpatch it.\n if (typeof mod.isPatched === \"function\" && (mod.isPatched as () => boolean)()) inst.unpatch?.(target);\n },\n };\n },\n };\n}\n\n/**\n * An ESM module namespace is sealed: an instrumentation that replaces an\n * export (rather than patching a prototype) cannot write to it. Refuse with\n * the fix instead of a TypeError from deep inside the instrumentation.\n */\nfunction writable(mod: unknown, what: string, spread: string): void {\n if (mod && typeof mod === \"object\" && (Object.prototype.toString.call(mod) === \"[object Module]\" || !Object.isExtensible(mod))) {\n throw new TypeError(\n `${what} is an ESM module namespace, which cannot be patched; hand over a copy and build the client from it: const m = { ...(await import(\"${spread}\")) }; instrument([...], { modules: { ... m } }); new m.<Client>(...)`,\n );\n }\n}\n\n/** Call a method of an instrumentation that its types keep private (the unpatch half of a manual patch). */\nfunction callPrivate(inst: object, method: string, ...args: unknown[]): void {\n const fn = (inst as Record<string, unknown>)[method];\n if (typeof fn === \"function\") (fn as (...a: unknown[]) => unknown).apply(inst, args);\n}\n\n/**\n * An OpenLLMetry (Traceloop) instrumentation: its constructor takes the plain\n * OTel InstrumentationConfig (no `tracerProvider` field), so the provider is\n * set afterwards. `enabled: false` keeps it from installing a require hook of\n * its own; the SDK patches the module it was handed (or `require` returns).\n */\ninterface Traceloop {\n setTracerProvider(p: TracerProvider): void;\n manuallyInstrument(...m: unknown[]): void;\n disable(): void;\n}\n\nfunction traceloop(pkg: string, cls: string, provider: TracerProvider): Traceloop {\n const Cls = load(pkg)[cls] as new (o: object) => Traceloop;\n const inst = new Cls({ enabled: false });\n inst.setTracerProvider(provider);\n return inst;\n}\n\nconst MCP_MODULES = {\n clientStdioModule: \"@modelcontextprotocol/sdk/client/stdio.js\",\n serverStdioModule: \"@modelcontextprotocol/sdk/server/stdio.js\",\n clientSSEModule: \"@modelcontextprotocol/sdk/client/sse.js\",\n serverSSEModule: \"@modelcontextprotocol/sdk/server/sse.js\",\n clientStreamableHTTPModule: \"@modelcontextprotocol/sdk/client/streamableHttp.js\",\n serverStreamableHTTPModule: \"@modelcontextprotocol/sdk/server/streamableHttp.js\",\n} as const;\n\ninterface TelemetryHolder {\n AI_SDK_TELEMETRY_INTEGRATIONS?: unknown[];\n}\n\n/** The table: one row per target, walked in order. */\nexport const TARGETS: readonly Target[] = [\n oiClass(\"openai\", \"@arizeai/openinference-instrumentation-openai\", \"OpenAIInstrumentation\", \"openai\"),\n oiClass(\"anthropic\", \"@arizeai/openinference-instrumentation-anthropic\", \"AnthropicInstrumentation\", \"@anthropic-ai/sdk\"),\n oiClass(\n \"langchain\",\n \"@arizeai/openinference-instrumentation-langchain\",\n \"LangChainInstrumentation\",\n \"@langchain/core/callbacks/manager\",\n \"covers LangGraph (its runs are LangChain runs)\",\n ),\n {\n name: \"mcp\",\n package: \"@arizeai/openinference-instrumentation-mcp\",\n library: \"@modelcontextprotocol/sdk/client/index.js\",\n note: \"carries trace context across MCP client and server transports, so server-side spans join the caller's trace\",\n install({ module }) {\n const mod = load(\"@arizeai/openinference-instrumentation-mcp\");\n const Cls = mod.MCPInstrumentation as new (o: object) => { manuallyInstrument(m: object): void; disable(): void };\n const inst = new Cls({ instrumentationConfig: { enabled: false } });\n const given = (module ?? {}) as Record<string, unknown>;\n const mods: Record<string, unknown> = {};\n for (const [k, spec] of Object.entries(MCP_MODULES)) {\n if (given[k]) mods[k] = given[k];\n else if (!module) {\n try {\n mods[k] = load(spec);\n } catch {\n // a transport this SDK version lacks\n }\n }\n }\n inst.manuallyInstrument(mods);\n return { undo: () => inst.disable() };\n },\n },\n {\n name: \"vercel-ai\",\n package: \"@ai-sdk/otel\",\n library: \"ai\",\n note: \"AI SDK v7 (Node 22+): registers an @ai-sdk/otel telemetry integration, which emits the pinned GenAI semconv spans Observer reads natively\",\n install({ provider, module }) {\n const given = (module ?? {}) as { ai?: Loaded; otel?: Loaded };\n const ai = given.ai ?? load(\"ai\");\n const otel = given.otel ?? load(\"@ai-sdk/otel\");\n const OpenTelemetry = otel.OpenTelemetry as new (o: object) => object;\n const integration = new OpenTelemetry({ tracer: provider.getTracer(\"ai\"), usage: true, embedding: true, toolChoice: true });\n (ai.registerTelemetry as (i: object) => void)(integration);\n return {\n undo() {\n const list = (globalThis as TelemetryHolder).AI_SDK_TELEMETRY_INTEGRATIONS;\n const i = list?.indexOf(integration) ?? -1;\n if (list && i >= 0) list.splice(i, 1);\n },\n };\n },\n },\n {\n name: \"gemini\",\n package: \"@traceloop/instrumentation-google-generativeai\",\n library: \"@google/genai\",\n note: \"Google Gen AI SDK (@google/genai, Node 22+) over OpenLLMetry's instrumentation: generateContent and generateContentStream on clients built after instrument()\",\n install({ provider, module }) {\n const genai = (module ?? load(\"@google/genai\")) as Loaded;\n writable(genai, \"the @google/genai module\", \"@google/genai\");\n const inst = traceloop(\"@traceloop/instrumentation-google-generativeai\", \"GenAIInstrumentation\", provider);\n inst.manuallyInstrument(genai);\n return {\n undo() {\n callPrivate(inst, \"unwrap\", genai);\n inst.disable();\n },\n };\n },\n },\n {\n name: \"bedrock\",\n package: \"@arizeai/openinference-instrumentation-bedrock\",\n library: \"@aws-sdk/client-bedrock-runtime\",\n note: \"AWS Bedrock Runtime (@aws-sdk/client-bedrock-runtime): InvokeModel, Converse and their streaming forms, patched on BedrockRuntimeClient.prototype.send\",\n install({ provider, module }) {\n const mod = load(\"@arizeai/openinference-instrumentation-bedrock\");\n if (typeof mod.isPatched === \"function\" && (mod.isPatched as () => boolean)()) return null;\n const Cls = mod.BedrockInstrumentation as new (o: object) => { manuallyInstrument(m: unknown): void; disable(): void; setTracerProvider?(p: TracerProvider): void };\n const inst = new Cls({ tracerProvider: provider, instrumentationConfig: { enabled: false } });\n inst.setTracerProvider?.(provider);\n const target = module ?? load(\"@aws-sdk/client-bedrock-runtime\");\n inst.manuallyInstrument(target);\n return {\n undo() {\n inst.disable();\n if (typeof mod.isPatched === \"function\" && (mod.isPatched as () => boolean)()) callPrivate(inst, \"unpatch\", target);\n },\n };\n },\n },\n {\n name: \"llama-index\",\n package: \"@traceloop/instrumentation-llamaindex\",\n library: \"llamaindex\",\n note: \"LlamaIndex.TS over OpenLLMetry's instrumentation: query and chat engines, retrievers, synthesizers, embeddings and every LLM class the module exports (and @llamaindex/openai's OpenAI when handed over as { llamaindex, openai })\",\n install({ provider, module }) {\n const given = module as { llamaindex?: Loaded; openai?: Loaded } | undefined;\n const li = given?.llamaindex ?? (given && !(\"llamaindex\" in given) && !(\"openai\" in given) ? (given as Loaded) : load(\"llamaindex\"));\n let oa = given?.openai;\n if (!oa && !given) {\n try {\n oa = load(\"@llamaindex/openai\");\n } catch {\n // the OpenAI provider package is optional\n }\n }\n const inst = traceloop(\"@traceloop/instrumentation-llamaindex\", \"LlamaIndexInstrumentation\", provider);\n inst.manuallyInstrument(li, oa);\n return {\n undo() {\n callPrivate(inst, \"unpatch\", li);\n if (oa) callPrivate(inst, \"unpatchOpenAI\", oa);\n inst.disable();\n },\n };\n },\n },\n {\n name: \"openai-agents\",\n package: \"@arizeai/openinference-instrumentation-openai-agents\",\n library: \"@openai/agents\",\n note: \"OpenAI Agents SDK (@openai/agents): an OpenInference tracing processor added beside the SDK's own processors (agent, generation, function-tool and handoff spans); the app's existing trace processors keep running\",\n install({ provider, module }) {\n const mod = load(\"@arizeai/openinference-instrumentation-openai-agents\");\n if (typeof mod.isPatched === \"function\" && (mod.isPatched as () => boolean)()) return null;\n const Cls = mod.OpenAIAgentsInstrumentation as new (o: object) => {\n manuallyInstrument(m: unknown, o?: object): void;\n uninstrument(): void;\n disable(): void;\n };\n const inst = new Cls({ tracerProvider: provider, exclusiveProcessor: false, instrumentationConfig: { enabled: false } });\n inst.manuallyInstrument(module ?? load(\"@openai/agents\"), { exclusiveProcessor: false });\n return {\n undo() {\n inst.uninstrument();\n inst.disable();\n },\n };\n },\n },\n];\n\n/** Other names for a target. */\nexport const ALIASES: Readonly<Record<string, InstrumentTarget>> = {\n langgraph: \"langchain\",\n vercel: \"vercel-ai\",\n ai: \"vercel-ai\",\n google: \"gemini\",\n \"google-genai\": \"gemini\",\n \"aws-bedrock\": \"bedrock\",\n llamaindex: \"llama-index\",\n llama_index: \"llama-index\",\n agents: \"openai-agents\",\n \"openai_agents\": \"openai-agents\",\n};\n\n/**\n * Frameworks that exist only for Python, so this SDK has no row for them.\n * Asking for one is a TypeError naming the reason (not \"unknown target\").\n */\nexport const PYTHON_ONLY: Readonly<Record<string, string>> = {\n crewai: \"CrewAI is a Python framework; there is no JavaScript CrewAI to instrument (use the Python SDK, superbased-sdk[crewai])\",\n \"pydantic-ai\": \"Pydantic AI is a Python framework; there is no JavaScript Pydantic AI to instrument (use the Python SDK)\",\n pydantic_ai: \"Pydantic AI is a Python framework; there is no JavaScript Pydantic AI to instrument (use the Python SDK)\",\n};\n\nconst byName = new Map(TARGETS.map((t) => [t.name, t]));\nconst active = new Map<InstrumentTarget, Active>();\n\nfunction names(targets: readonly string[] | undefined): InstrumentTarget[] {\n if (!targets) return TARGETS.map((t) => t.name);\n const out: InstrumentTarget[] = [];\n for (const raw of targets) {\n const n = String(raw).trim().toLowerCase();\n const name = (ALIASES[n] ?? n) as InstrumentTarget;\n if (PYTHON_ONLY[n]) throw new TypeError(`@superbased/sdk: ${PYTHON_ONLY[n]}`);\n if (!byName.has(name)) {\n const known = [...byName.keys(), ...Object.keys(ALIASES)].sort().join(\", \");\n throw new TypeError(`@superbased/sdk: unknown instrument target ${JSON.stringify(raw)}; known: ${known}`);\n }\n if (!out.includes(name)) out.push(name);\n }\n return out;\n}\n\nfunction missing(err: unknown): boolean {\n const code = (err as { code?: string }).code;\n return code === \"MODULE_NOT_FOUND\" || code === \"ERR_MODULE_NOT_FOUND\" || code === \"ERR_PACKAGE_PATH_NOT_EXPORTED\";\n}\n\nexport interface InstrumentOptions {\n /**\n * The framework modules, for an ESM app (or to patch a specific copy):\n * `openai` (the namespace, `await import(\"openai\")`), `anthropic`\n * (`@anthropic-ai/sdk`), `langchain` (`@langchain/core/callbacks/manager`),\n * `mcp` (`{ clientStreamableHTTPModule, serverStreamableHTTPModule, ... }`),\n * `vercel-ai` (`{ ai, otel }`: the `ai` and `@ai-sdk/otel` modules),\n * `gemini` (a COPY of `@google/genai`: `{ ...(await import(\"@google/genai\")) }`,\n * then build `new copy.GoogleGenAI(...)` from it, because the instrumentation\n * replaces the class export), `bedrock` (`@aws-sdk/client-bedrock-runtime`),\n * `llama-index` (`{ llamaindex, openai }`: the `llamaindex` module and,\n * optionally, `@llamaindex/openai`), `openai-agents` (`@openai/agents`).\n */\n modules?: Partial<Record<InstrumentTarget, unknown>>;\n /** The provider the instrumentations write to (default: the SDK's, else the global one). */\n tracerProvider?: TracerProvider;\n}\n\n/**\n * Turn on auto-instrumentation for `targets` (`openai`, `anthropic`,\n * `langchain` (also `langgraph`), `mcp`, `vercel-ai`, `gemini`, `bedrock`,\n * `llama-index`, `openai-agents`); none given\n * instruments every installed one. Returns `{ target: status }`, status one\n * of `instrumented`, `already`, `not-installed` (install the\n * instrumentation package and the framework) or `error: <message>`. An\n * unknown target is a TypeError. Call after `init()`; idempotent.\n */\nexport function instrument(targets?: readonly string[], opts: InstrumentOptions = {}): Record<string, string> {\n const list = names(targets ?? (opts.modules ? (Object.keys(opts.modules) as InstrumentTarget[]) : undefined));\n const provider = opts.tracerProvider ?? runtime.provider ?? trace.getTracerProvider();\n const out: Record<string, string> = {};\n for (const name of list) {\n if (active.has(name)) {\n out[name] = ALREADY;\n continue;\n }\n const t = byName.get(name)!;\n try {\n const got = t.install({ provider, module: opts.modules?.[name] });\n if (got === null) {\n out[name] = ALREADY; // the host instrumented it first\n continue;\n }\n active.set(name, got);\n out[name] = INSTRUMENTED;\n } catch (err) {\n if (missing(err)) {\n out[name] = NOT_INSTALLED;\n continue;\n }\n const e = err instanceof Error ? `${err.name}: ${err.message}` : String(err);\n out[name] = `error: ${e}`.slice(0, 300);\n }\n }\n return out;\n}\n\n/** Undo `instrument()` for `targets` (none given: every instrumented one). Never throws for one that was not instrumented. */\nexport function uninstrument(targets?: readonly string[]): void {\n const list = targets ? names(targets) : [...active.keys()];\n for (const name of list) {\n const a = active.get(name);\n active.delete(name);\n try {\n a?.undo();\n } catch {\n // ignore\n }\n }\n}\n\n/** The targets instrumented now. */\nexport function instrumented(): InstrumentTarget[] {\n return [...active.keys()];\n}\n"]}
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Export-time policy, applied by the SDK's span processor to every span it
3
+ * exports (the SDK's own and any instrumentation's), in this order
4
+ * (contract sdk-api-surface.md section 5):
5
+ *
6
+ * 1. Head sampling by trace id (`sampleRate`). When the SDK owns the
7
+ * provider this is the provider's sampler (`SwitchableSampler`,
8
+ * parent-based by default); when the SDK is attached to a host provider
9
+ * the host's sampler stays in charge and the same trace-id ratio is
10
+ * applied to what the SDK exports. A trace is kept when the low 64 bits of
11
+ * its id are below `round(rate * 2^64)` (the OTel TraceIdRatioBased rule
12
+ * as the Python SDK applies it), so every service and both SDKs agree.
13
+ * 2. `shouldExport(span)`: false drops the span (`filteredSpans`). A hook
14
+ * that throws keeps the span (no silent loss) and counts
15
+ * `shouldExportErrors`.
16
+ * 3. Content rules on every content attribute, on the span and its events:
17
+ * `captureContent` off removes it; otherwise `mask(value, key)` rewrites
18
+ * it (null / undefined drops it; a hook that throws drops it and counts
19
+ * `maskErrors`, never exporting the value unmasked), then the value is
20
+ * clipped to `maxContentChars`.
21
+ *
22
+ * The original span is never changed: the SDK exports a copy when a content
23
+ * rule changes something, so a host's other processors see the original.
24
+ */
25
+ import { type Attributes, type AttributeValue, type Context, type Link, type SpanKind } from "@opentelemetry/api";
26
+ import { type ReadableSpan, type Sampler, type SamplingResult } from "@opentelemetry/sdk-trace-base";
27
+ /** Rewrite one content value before export. Return null / undefined to drop it. */
28
+ export type MaskFn = (value: AttributeValue, key: string) => unknown;
29
+ /** Decide whether a finished span is exported. */
30
+ export type ShouldExportFn = (span: ReadableSpan) => boolean;
31
+ export declare const TRUNCATED_MARK = "\u2026[truncated]";
32
+ export interface ExportPolicy {
33
+ captureContent: boolean;
34
+ maxContentChars: number;
35
+ mask?: MaskFn;
36
+ shouldExport?: ShouldExportFn;
37
+ /** Applied only when a host's sampler made the decision (attached mode); undefined = export every recorded span. */
38
+ exportRatio?: number;
39
+ /** Tracer scopes of model client libraries whose own spans are dropped (vendor.ts). */
40
+ dropScopePrefixes?: string[];
41
+ }
42
+ export declare const policyStats: {
43
+ sampledOut: number;
44
+ filtered: number;
45
+ shouldExportErrors: number;
46
+ maskErrors: number;
47
+ vendorSpansDropped: number;
48
+ usageNetInputCorrected: number;
49
+ lastHookError: string;
50
+ };
51
+ export declare function resetPolicyStats(): void;
52
+ /** The trace-id ratio bound: kept when the low 64 bits are below it. */
53
+ export declare function ratioBound(rate: number): bigint;
54
+ /** Whether the trace with this id is kept at `rate` (deterministic, the same in both SDKs). */
55
+ export declare function keepTrace(traceId: string, rate: number): boolean;
56
+ /** The trace-id ratio root sampler, with the cross-SDK rule above. */
57
+ export declare class RatioSampler implements Sampler {
58
+ readonly rate: number;
59
+ constructor(rate: number);
60
+ shouldSample(_ctx: Context, traceId: string): SamplingResult;
61
+ toString(): string;
62
+ }
63
+ /** The sampler of a provider the SDK owns; a later `init()` swaps the rate in place. */
64
+ export declare class SwitchableSampler implements Sampler {
65
+ private inner;
66
+ rate: number;
67
+ set(rate: number, parentBased: boolean): void;
68
+ shouldSample(ctx: Context, traceId: string, name: string, kind: SpanKind, attrs: Attributes, links: Link[]): SamplingResult;
69
+ toString(): string;
70
+ }
71
+ export declare function clipContent(value: AttributeValue, max: number): AttributeValue;
72
+ /** New attributes when a content rule changes `attrs`; null when none does. */
73
+ export declare function rewriteAttributes(attrs: Attributes | undefined, p: ExportPolicy): Attributes | null;
74
+ /** The span to export: `span` itself, or a copy with rewritten content. */
75
+ export declare function applyContentRules(span: ReadableSpan, p: ExportPolicy): ReadableSpan;
76
+ /** The whole policy: the span to export, or null to drop it (counted). */
77
+ export declare function applyPolicy(span: ReadableSpan, p: ExportPolicy): ReadableSpan | null;
@@ -0,0 +1,240 @@
1
+ /**
2
+ * Export-time policy, applied by the SDK's span processor to every span it
3
+ * exports (the SDK's own and any instrumentation's), in this order
4
+ * (contract sdk-api-surface.md section 5):
5
+ *
6
+ * 1. Head sampling by trace id (`sampleRate`). When the SDK owns the
7
+ * provider this is the provider's sampler (`SwitchableSampler`,
8
+ * parent-based by default); when the SDK is attached to a host provider
9
+ * the host's sampler stays in charge and the same trace-id ratio is
10
+ * applied to what the SDK exports. A trace is kept when the low 64 bits of
11
+ * its id are below `round(rate * 2^64)` (the OTel TraceIdRatioBased rule
12
+ * as the Python SDK applies it), so every service and both SDKs agree.
13
+ * 2. `shouldExport(span)`: false drops the span (`filteredSpans`). A hook
14
+ * that throws keeps the span (no silent loss) and counts
15
+ * `shouldExportErrors`.
16
+ * 3. Content rules on every content attribute, on the span and its events:
17
+ * `captureContent` off removes it; otherwise `mask(value, key)` rewrites
18
+ * it (null / undefined drops it; a hook that throws drops it and counts
19
+ * `maskErrors`, never exporting the value unmasked), then the value is
20
+ * clipped to `maxContentChars`.
21
+ *
22
+ * The original span is never changed: the SDK exports a copy when a content
23
+ * rule changes something, so a host's other processors see the original.
24
+ */
25
+ import { SamplingDecision } from "@opentelemetry/api";
26
+ import { AlwaysOffSampler, AlwaysOnSampler, ParentBasedSampler } from "@opentelemetry/sdk-trace-base";
27
+ import { isContentKey } from "./attrs.js";
28
+ export const TRUNCATED_MARK = "…[truncated]";
29
+ export const policyStats = {
30
+ sampledOut: 0,
31
+ filtered: 0,
32
+ shouldExportErrors: 0,
33
+ maskErrors: 0,
34
+ vendorSpansDropped: 0,
35
+ usageNetInputCorrected: 0,
36
+ lastHookError: "",
37
+ };
38
+ export function resetPolicyStats() {
39
+ Object.assign(policyStats, {
40
+ sampledOut: 0,
41
+ filtered: 0,
42
+ shouldExportErrors: 0,
43
+ maskErrors: 0,
44
+ vendorSpansDropped: 0,
45
+ usageNetInputCorrected: 0,
46
+ lastHookError: "",
47
+ });
48
+ }
49
+ function hookError(counter, what, err) {
50
+ policyStats[counter] += 1;
51
+ const e = err instanceof Error ? `${err.name}: ${err.message}` : String(err);
52
+ policyStats.lastHookError = `${what}: ${e}`.slice(0, 500);
53
+ }
54
+ const TWO_64 = 2n ** 64n;
55
+ /** The trace-id ratio bound: kept when the low 64 bits are below it. */
56
+ export function ratioBound(rate) {
57
+ const r = Math.max(0, Math.min(1, rate));
58
+ if (r >= 1)
59
+ return TWO_64;
60
+ return BigInt(Math.round(r * Number(TWO_64)));
61
+ }
62
+ /** Whether the trace with this id is kept at `rate` (deterministic, the same in both SDKs). */
63
+ export function keepTrace(traceId, rate) {
64
+ if (!(rate < 1))
65
+ return true;
66
+ if (!(rate > 0))
67
+ return false;
68
+ const low = traceId.length >= 16 ? traceId.slice(-16) : traceId;
69
+ let n;
70
+ try {
71
+ n = BigInt("0x" + (low || "0"));
72
+ }
73
+ catch {
74
+ return true;
75
+ }
76
+ return n < ratioBound(rate);
77
+ }
78
+ /** The trace-id ratio root sampler, with the cross-SDK rule above. */
79
+ export class RatioSampler {
80
+ rate;
81
+ constructor(rate) {
82
+ this.rate = rate;
83
+ }
84
+ shouldSample(_ctx, traceId) {
85
+ return { decision: keepTrace(traceId, this.rate) ? SamplingDecision.RECORD_AND_SAMPLED : SamplingDecision.NOT_RECORD };
86
+ }
87
+ toString() {
88
+ return `SuperbasedRatio{${this.rate}}`;
89
+ }
90
+ }
91
+ /** The sampler of a provider the SDK owns; a later `init()` swaps the rate in place. */
92
+ export class SwitchableSampler {
93
+ inner = new AlwaysOnSampler();
94
+ rate = 1;
95
+ set(rate, parentBased) {
96
+ this.rate = rate;
97
+ const root = rate >= 1 ? new AlwaysOnSampler() : rate <= 0 ? new AlwaysOffSampler() : new RatioSampler(rate);
98
+ this.inner = parentBased ? new ParentBasedSampler({ root }) : root;
99
+ }
100
+ shouldSample(ctx, traceId, name, kind, attrs, links) {
101
+ const r = this.inner.shouldSample(ctx, traceId, name, kind, attrs, links);
102
+ if (r.decision === SamplingDecision.NOT_RECORD)
103
+ policyStats.sampledOut += 1;
104
+ return r;
105
+ }
106
+ toString() {
107
+ return `SuperbasedSampler{${this.inner.toString()}}`;
108
+ }
109
+ }
110
+ export function clipContent(value, max) {
111
+ if (max > 0 && typeof value === "string" && value.length > max)
112
+ return value.slice(0, max) + TRUNCATED_MARK;
113
+ return value;
114
+ }
115
+ function isAttrValue(v) {
116
+ if (typeof v === "string" || typeof v === "number" || typeof v === "boolean")
117
+ return true;
118
+ return Array.isArray(v) && v.every((x) => x == null || ["string", "number", "boolean"].includes(typeof x));
119
+ }
120
+ /** One content attribute: [keep, new value]. */
121
+ function contentValue(key, value, p) {
122
+ if (!p.captureContent)
123
+ return [false, undefined];
124
+ let v = value;
125
+ if (p.mask) {
126
+ let out;
127
+ try {
128
+ out = p.mask(value, key);
129
+ }
130
+ catch (err) {
131
+ hookError("maskErrors", `mask(${key})`, err);
132
+ return [false, undefined];
133
+ }
134
+ if (out === null || out === undefined)
135
+ return [false, undefined];
136
+ v = isAttrValue(out) ? out : String(out);
137
+ }
138
+ return [true, clipContent(v, p.maxContentChars)];
139
+ }
140
+ /** New attributes when a content rule changes `attrs`; null when none does. */
141
+ export function rewriteAttributes(attrs, p) {
142
+ if (!attrs)
143
+ return null;
144
+ let out = null;
145
+ for (const [key, value] of Object.entries(attrs)) {
146
+ if (value === undefined || !isContentKey(key))
147
+ continue;
148
+ const [keep, next] = contentValue(key, value, p);
149
+ if (keep && next === value)
150
+ continue;
151
+ out ??= { ...attrs };
152
+ if (keep)
153
+ out[key] = next;
154
+ else
155
+ delete out[key];
156
+ }
157
+ return out;
158
+ }
159
+ function needsContentRules(p) {
160
+ return !p.captureContent || !!p.mask || p.maxContentChars > 0;
161
+ }
162
+ function copySpan(span, attributes, events) {
163
+ return {
164
+ name: span.name,
165
+ kind: span.kind,
166
+ spanContext: () => span.spanContext(),
167
+ parentSpanContext: span.parentSpanContext,
168
+ startTime: span.startTime,
169
+ endTime: span.endTime,
170
+ status: span.status,
171
+ attributes,
172
+ links: span.links,
173
+ events,
174
+ duration: span.duration,
175
+ ended: span.ended,
176
+ resource: span.resource,
177
+ instrumentationScope: span.instrumentationScope,
178
+ droppedAttributesCount: span.droppedAttributesCount,
179
+ droppedEventsCount: span.droppedEventsCount,
180
+ droppedLinksCount: span.droppedLinksCount,
181
+ };
182
+ }
183
+ /** The span to export: `span` itself, or a copy with rewritten content. */
184
+ export function applyContentRules(span, p) {
185
+ if (!needsContentRules(p))
186
+ return span;
187
+ try {
188
+ const attrs = rewriteAttributes(span.attributes, p);
189
+ let events = span.events;
190
+ let changed = false;
191
+ if (span.events?.length) {
192
+ events = span.events.map((ev) => {
193
+ const a = rewriteAttributes(ev.attributes, p);
194
+ if (!a)
195
+ return ev;
196
+ changed = true;
197
+ return { ...ev, attributes: a };
198
+ });
199
+ }
200
+ if (!attrs && !changed)
201
+ return span;
202
+ return copySpan(span, attrs ?? span.attributes, changed ? events : span.events);
203
+ }
204
+ catch (err) {
205
+ // A span the rules cannot process is exported without its content, never with it unmasked.
206
+ hookError("maskErrors", "content rules", err);
207
+ const strip = (a) => Object.fromEntries(Object.entries(a ?? {}).filter(([k]) => !isContentKey(k)));
208
+ return copySpan(span, strip(span.attributes), (span.events ?? []).map((ev) => ({ ...ev, attributes: strip(ev.attributes) })));
209
+ }
210
+ }
211
+ /** The whole policy: the span to export, or null to drop it (counted). */
212
+ export function applyPolicy(span, p) {
213
+ if (p.dropScopePrefixes?.length) {
214
+ const scope = span.instrumentationScope?.name ?? "";
215
+ if (scope && p.dropScopePrefixes.some((pre) => scope.startsWith(pre))) {
216
+ policyStats.vendorSpansDropped += 1;
217
+ return null;
218
+ }
219
+ }
220
+ if (p.exportRatio !== undefined && p.exportRatio < 1 && !keepTrace(span.spanContext().traceId, p.exportRatio)) {
221
+ policyStats.sampledOut += 1;
222
+ return null;
223
+ }
224
+ if (p.shouldExport) {
225
+ let keep = true;
226
+ try {
227
+ keep = p.shouldExport(span) !== false;
228
+ }
229
+ catch (err) {
230
+ hookError("shouldExportErrors", "shouldExport", err);
231
+ keep = true;
232
+ }
233
+ if (!keep) {
234
+ policyStats.filtered += 1;
235
+ return null;
236
+ }
237
+ }
238
+ return applyContentRules(span, p);
239
+ }
240
+ //# sourceMappingURL=policy.js.map
@@ -0,0 +1 @@
1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WAAW,CAAC,kBAAkB,IAAI,CAAC,CAAC;YACpC,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IACD,IAAI,CAAC,CAAC,WAAW,KAAK,SAAS,IAAI,CAAC,CAAC,WAAW,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,WAAW,CAAC,EAAE,CAAC;QAC9G,WAAW,CAAC,UAAU,IAAI,CAAC,CAAC;QAC5B,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,CAAC,CAAC,YAAY,EAAE,CAAC;QACnB,IAAI,IAAI,GAAG,IAAI,CAAC;QAChB,IAAI,CAAC;YACH,IAAI,GAAG,CAAC,CAAC,YAAY,CAAC,IAAI,CAAC,KAAK,KAAK,CAAC;QACxC,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,SAAS,CAAC,oBAAoB,EAAE,cAAc,EAAE,GAAG,CAAC,CAAC;YACrD,IAAI,GAAG,IAAI,CAAC;QACd,CAAC;QACD,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,WAAW,CAAC,QAAQ,IAAI,CAAC,CAAC;YAC1B,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,iBAAiB,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;AACpC,CAAC","sourcesContent":["/**\n * Export-time policy, applied by the SDK's span processor to every span it\n * exports (the SDK's own and any instrumentation's), in this order\n * (contract sdk-api-surface.md section 5):\n *\n * 1. Head sampling by trace id (`sampleRate`). When the SDK owns the\n * provider this is the provider's sampler (`SwitchableSampler`,\n * parent-based by default); when the SDK is attached to a host provider\n * the host's sampler stays in charge and the same trace-id ratio is\n * applied to what the SDK exports. A trace is kept when the low 64 bits of\n * its id are below `round(rate * 2^64)` (the OTel TraceIdRatioBased rule\n * as the Python SDK applies it), so every service and both SDKs agree.\n * 2. `shouldExport(span)`: false drops the span (`filteredSpans`). A hook\n * that throws keeps the span (no silent loss) and counts\n * `shouldExportErrors`.\n * 3. Content rules on every content attribute, on the span and its events:\n * `captureContent` off removes it; otherwise `mask(value, key)` rewrites\n * it (null / undefined drops it; a hook that throws drops it and counts\n * `maskErrors`, never exporting the value unmasked), then the value is\n * clipped to `maxContentChars`.\n *\n * The original span is never changed: the SDK exports a copy when a content\n * rule changes something, so a host's other processors see the original.\n */\n\nimport { SamplingDecision, type Attributes, type AttributeValue, type Context, type Link, type SpanKind } from \"@opentelemetry/api\";\nimport { AlwaysOffSampler, AlwaysOnSampler, ParentBasedSampler, type ReadableSpan, type Sampler, type SamplingResult } from \"@opentelemetry/sdk-trace-base\";\n\nimport { isContentKey } from \"./attrs.js\";\n\n/** Rewrite one content value before export. Return null / undefined to drop it. */\nexport type MaskFn = (value: AttributeValue, key: string) => unknown;\n\n/** Decide whether a finished span is exported. */\nexport type ShouldExportFn = (span: ReadableSpan) => boolean;\n\nexport const TRUNCATED_MARK = \"…[truncated]\";\n\nexport interface ExportPolicy {\n captureContent: boolean;\n maxContentChars: number;\n mask?: MaskFn;\n shouldExport?: ShouldExportFn;\n /** Applied only when a host's sampler made the decision (attached mode); undefined = export every recorded span. */\n exportRatio?: number;\n /** Tracer scopes of model client libraries whose own spans are dropped (vendor.ts). */\n dropScopePrefixes?: string[];\n}\n\nexport const policyStats = {\n sampledOut: 0,\n filtered: 0,\n shouldExportErrors: 0,\n maskErrors: 0,\n vendorSpansDropped: 0,\n usageNetInputCorrected: 0,\n lastHookError: \"\",\n};\n\nexport function resetPolicyStats(): void {\n Object.assign(policyStats, {\n sampledOut: 0,\n filtered: 0,\n shouldExportErrors: 0,\n maskErrors: 0,\n vendorSpansDropped: 0,\n usageNetInputCorrected: 0,\n lastHookError: \"\",\n });\n}\n\nfunction hookError(counter: \"shouldExportErrors\" | \"maskErrors\", what: string, err: unknown): void {\n policyStats[counter] += 1;\n const e = err instanceof Error ? `${err.name}: ${err.message}` : String(err);\n policyStats.lastHookError = `${what}: ${e}`.slice(0, 500);\n}\n\nconst TWO_64 = 2n ** 64n;\n\n/** The trace-id ratio bound: kept when the low 64 bits are below it. */\nexport function ratioBound(rate: number): bigint {\n const r = Math.max(0, Math.min(1, rate));\n if (r >= 1) return TWO_64;\n return BigInt(Math.round(r * Number(TWO_64)));\n}\n\n/** Whether the trace with this id is kept at `rate` (deterministic, the same in both SDKs). */\nexport function keepTrace(traceId: string, rate: number): boolean {\n if (!(rate < 1)) return true;\n if (!(rate > 0)) return false;\n const low = traceId.length >= 16 ? traceId.slice(-16) : traceId;\n let n: bigint;\n try {\n n = BigInt(\"0x\" + (low || \"0\"));\n } catch {\n return true;\n }\n return n < ratioBound(rate);\n}\n\n/** The trace-id ratio root sampler, with the cross-SDK rule above. */\nexport class RatioSampler implements Sampler {\n constructor(readonly rate: number) {}\n shouldSample(_ctx: Context, traceId: string): SamplingResult {\n return { decision: keepTrace(traceId, this.rate) ? SamplingDecision.RECORD_AND_SAMPLED : SamplingDecision.NOT_RECORD };\n }\n toString(): string {\n return `SuperbasedRatio{${this.rate}}`;\n }\n}\n\n/** The sampler of a provider the SDK owns; a later `init()` swaps the rate in place. */\nexport class SwitchableSampler implements Sampler {\n private inner: Sampler = new AlwaysOnSampler();\n rate = 1;\n set(rate: number, parentBased: boolean): void {\n this.rate = rate;\n const root: Sampler = rate >= 1 ? new AlwaysOnSampler() : rate <= 0 ? new AlwaysOffSampler() : new RatioSampler(rate);\n this.inner = parentBased ? new ParentBasedSampler({ root }) : root;\n }\n shouldSample(ctx: Context, traceId: string, name: string, kind: SpanKind, attrs: Attributes, links: Link[]): SamplingResult {\n const r = this.inner.shouldSample(ctx, traceId, name, kind, attrs, links);\n if (r.decision === SamplingDecision.NOT_RECORD) policyStats.sampledOut += 1;\n return r;\n }\n toString(): string {\n return `SuperbasedSampler{${this.inner.toString()}}`;\n }\n}\n\nexport function clipContent(value: AttributeValue, max: number): AttributeValue {\n if (max > 0 && typeof value === \"string\" && value.length > max) return value.slice(0, max) + TRUNCATED_MARK;\n return value;\n}\n\nfunction isAttrValue(v: unknown): v is AttributeValue {\n if (typeof v === \"string\" || typeof v === \"number\" || typeof v === \"boolean\") return true;\n return Array.isArray(v) && v.every((x) => x == null || [\"string\", \"number\", \"boolean\"].includes(typeof x));\n}\n\n/** One content attribute: [keep, new value]. */\nfunction contentValue(key: string, value: AttributeValue, p: ExportPolicy): [boolean, AttributeValue | undefined] {\n if (!p.captureContent) return [false, undefined];\n let v: AttributeValue = value;\n if (p.mask) {\n let out: unknown;\n try {\n out = p.mask(value, key);\n } catch (err) {\n hookError(\"maskErrors\", `mask(${key})`, err);\n return [false, undefined];\n }\n if (out === null || out === undefined) return [false, undefined];\n v = isAttrValue(out) ? out : String(out);\n }\n return [true, clipContent(v, p.maxContentChars)];\n}\n\n/** New attributes when a content rule changes `attrs`; null when none does. */\nexport function rewriteAttributes(attrs: Attributes | undefined, p: ExportPolicy): Attributes | null {\n if (!attrs) return null;\n let out: Attributes | null = null;\n for (const [key, value] of Object.entries(attrs)) {\n if (value === undefined || !isContentKey(key)) continue;\n const [keep, next] = contentValue(key, value, p);\n if (keep && next === value) continue;\n out ??= { ...attrs };\n if (keep) out[key] = next;\n else delete out[key];\n }\n return out;\n}\n\nfunction needsContentRules(p: ExportPolicy): boolean {\n return !p.captureContent || !!p.mask || p.maxContentChars > 0;\n}\n\nfunction copySpan(span: ReadableSpan, attributes: Attributes, events: ReadableSpan[\"events\"]): ReadableSpan {\n return {\n name: span.name,\n kind: span.kind,\n spanContext: () => span.spanContext(),\n parentSpanContext: span.parentSpanContext,\n startTime: span.startTime,\n endTime: span.endTime,\n status: span.status,\n attributes,\n links: span.links,\n events,\n duration: span.duration,\n ended: span.ended,\n resource: span.resource,\n instrumentationScope: span.instrumentationScope,\n droppedAttributesCount: span.droppedAttributesCount,\n droppedEventsCount: span.droppedEventsCount,\n droppedLinksCount: span.droppedLinksCount,\n };\n}\n\n/** The span to export: `span` itself, or a copy with rewritten content. */\nexport function applyContentRules(span: ReadableSpan, p: ExportPolicy): ReadableSpan {\n if (!needsContentRules(p)) return span;\n try {\n const attrs = rewriteAttributes(span.attributes, p);\n let events = span.events;\n let changed = false;\n if (span.events?.length) {\n events = span.events.map((ev) => {\n const a = rewriteAttributes(ev.attributes, p);\n if (!a) return ev;\n changed = true;\n return { ...ev, attributes: a };\n });\n }\n if (!attrs && !changed) return span;\n return copySpan(span, attrs ?? span.attributes, changed ? events : span.events);\n } catch (err) {\n // A span the rules cannot process is exported without its content, never with it unmasked.\n hookError(\"maskErrors\", \"content rules\", err);\n const strip = (a: Attributes | undefined): Attributes =>\n Object.fromEntries(Object.entries(a ?? {}).filter(([k]) => !isContentKey(k))) as Attributes;\n return copySpan(span, strip(span.attributes), (span.events ?? []).map((ev) => ({ ...ev, attributes: strip(ev.attributes) })));\n }\n}\n\n/** The whole policy: the span to export, or null to drop it (counted). */\nexport function applyPolicy(span: ReadableSpan, p: ExportPolicy): ReadableSpan | null {\n if (p.dropScopePrefixes?.length) {\n const scope = span.instrumentationScope?.name ?? \"\";\n if (scope && p.dropScopePrefixes.some((pre) => scope.startsWith(pre))) {\n policyStats.vendorSpansDropped += 1;\n return null;\n }\n }\n if (p.exportRatio !== undefined && p.exportRatio < 1 && !keepTrace(span.spanContext().traceId, p.exportRatio)) {\n policyStats.sampledOut += 1;\n return null;\n }\n if (p.shouldExport) {\n let keep = true;\n try {\n keep = p.shouldExport(span) !== false;\n } catch (err) {\n hookError(\"shouldExportErrors\", \"shouldExport\", err);\n keep = true;\n }\n if (!keep) {\n policyStats.filtered += 1;\n return null;\n }\n }\n return applyContentRules(span, p);\n}\n"]}
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Prompt registry client (W3-3; contract `contracts/prompts.md`, lane B8).
3
+ *
4
+ * - Fetch: online `GET <org>/v1/sdk/prompts/{name}` (scope `sdk:read`),
5
+ * local `GET <machine>/api/obs/sdk/prompts/{name}`; `both` prefers online
6
+ * and falls back to local. `?label=` or `?version=`, never both; neither is
7
+ * `label=production`.
8
+ * - Cache per (endpoint, name, selector): fresh for `cacheTtlMs` (default
9
+ * 60 s, `SUPERBASED_PROMPT_CACHE_TTL_MS`). After that the cached prompt is
10
+ * returned at once and revalidated in the background with `If-None-Match`
11
+ * (stale-while-revalidate); a 304 renews it, a 404 drops it, any other
12
+ * failure keeps serving it.
13
+ * - A first fetch that fails throws {@link PromptNotFound}, unless you pass a
14
+ * `fallback`, which is returned marked `isFallback` and never cached.
15
+ * - `compile(values)` fills `{{name}}` placeholders in one pass (a value is
16
+ * never re-scanned) and throws {@link PromptCompileError} naming every
17
+ * missing variable. `prompt.compile()`, `getPrompt()` inside a span and
18
+ * `withLlmSpan(..., { promptRef })` stamp `sbo.prompt.name`,
19
+ * `sbo.prompt.version` and (for a label fetch) `sbo.prompt.label` on the
20
+ * span. A fallback stamps nothing.
21
+ */
22
+ import { type Span } from "@opentelemetry/api";
23
+ import { type ControlOptions } from "./control.js";
24
+ export declare const DEFAULT_PROMPT_LABEL = "production";
25
+ export declare const PROMPT_LABELS: readonly ["production", "staging"];
26
+ export interface ChatMessage {
27
+ role: string;
28
+ content: string;
29
+ }
30
+ export type PromptBody = string | ChatMessage[];
31
+ export interface GetPromptOptions extends ControlOptions {
32
+ /** `production` (default) or `staging`. Exclusive with `version`. */
33
+ label?: string;
34
+ /** An exact version number. Exclusive with `label`. */
35
+ version?: number;
36
+ /** Cache freshness in ms (default: the promptCacheTtlMs setting, 60 000). 0 revalidates on every call. */
37
+ cacheTtlMs?: number;
38
+ /** Returned (marked isFallback, never cached) when the prompt cannot be fetched and nothing is cached. */
39
+ fallback?: PromptBody;
40
+ /**
41
+ * The end user that picks the side of a staged rollout (prompts.md v2
42
+ * section 9.2). Default: the current trace's user (`propagateAttributes`
43
+ * / `identify`). Only its SHA-256 is sent.
44
+ */
45
+ user?: string;
46
+ /** The session that picks the side when there is no user. Default: the current trace's session. */
47
+ sessionId?: string;
48
+ }
49
+ /** A label's staged rollout as the server reported it (prompts.md v2 section 9.3). */
50
+ export interface PromptRollout {
51
+ baseVersion: number;
52
+ candidateVersion: number;
53
+ percent: number;
54
+ /** Which side this key was served: `candidate`, `base` or `unkeyed`. */
55
+ cohort: "candidate" | "base" | "unkeyed";
56
+ /** Which key decided: `user`, `session` or "". */
57
+ key: "user" | "session" | "";
58
+ salt: string;
59
+ }
60
+ /** The base of every prompt error (contract sdk-api-surface.md section 7.3). */
61
+ export declare class PromptError extends Error {
62
+ readonly status: number;
63
+ readonly code: string;
64
+ constructor(message: string, status?: number, code?: string);
65
+ }
66
+ /** Thrown when no destination has the prompt (404 / not implemented everywhere) and there is no fallback. */
67
+ export declare class PromptNotFound extends PromptError {
68
+ constructor(message: string, status?: number, code?: string);
69
+ }
70
+ /** Thrown when a destination failed otherwise (transport, timeout, 5xx, a bad body) and there is no fallback. */
71
+ export declare class PromptFetchError extends PromptError {
72
+ constructor(message: string, status?: number, code?: string);
73
+ }
74
+ /** Thrown by compile() when a placeholder has no value; `missing` is sorted. */
75
+ export declare class PromptCompileError extends PromptError {
76
+ readonly missing: string[];
77
+ constructor(missing: string[]);
78
+ }
79
+ /** The distinct placeholder names in a body, sorted by byte order. */
80
+ export declare function promptVariables(body: PromptBody): string[];
81
+ /** Fill placeholders in one left-to-right pass; throws PromptCompileError naming every missing name. */
82
+ export declare function compilePrompt(body: PromptBody, values: Record<string, unknown>): PromptBody;
83
+ /** Registry fields Python's Prompt also carries (contract prompts.md). */
84
+ export interface PromptDetails {
85
+ /** How the registry resolved it: `label:<name>` or `version:<n>` ("" for a fallback). */
86
+ resolvedBy?: string;
87
+ /** The version's commit message ("" when none). */
88
+ commitMessage?: string;
89
+ /** When the version was created (RFC 3339 UTC; "" for a fallback). */
90
+ createdAt?: string;
91
+ /** Where this copy came from: `online`, `local` or `fallback`. */
92
+ source?: string;
93
+ }
94
+ /** A fetched (or fallback) prompt. */
95
+ export declare class Prompt {
96
+ readonly name: string;
97
+ readonly version: number;
98
+ /** The label it was resolved by ("" for a version fetch or a fallback). */
99
+ readonly label: string;
100
+ readonly type: "text" | "chat";
101
+ readonly prompt: PromptBody;
102
+ /** Model parameters or other config stored with the version (`{}` when none). */
103
+ readonly config: Record<string, unknown>;
104
+ /** The labels that point at this version now. */
105
+ readonly labels: string[];
106
+ /** `sha256:<hex>` of the version's canonical content. */
107
+ readonly digest: string;
108
+ /** True when this is the caller's fallback, not a registry copy. */
109
+ readonly isFallback: boolean;
110
+ /** The label's staged rollout, when it has one (the version above is the one SERVED). */
111
+ readonly rollout: PromptRollout | null;
112
+ /** How the registry resolved it: `label:<name>` or `version:<n>` ("" for a fallback). */
113
+ readonly resolvedBy: string;
114
+ /** The version's commit message ("" when none). */
115
+ readonly commitMessage: string;
116
+ /** When the version was created (RFC 3339 UTC; "" for a fallback). */
117
+ readonly createdAt: string;
118
+ /** Where this copy came from: `online`, `local` or `fallback` ("" when built by hand). */
119
+ readonly source: string;
120
+ constructor(name: string, version: number,
121
+ /** The label it was resolved by ("" for a version fetch or a fallback). */
122
+ label: string, type: "text" | "chat", prompt: PromptBody,
123
+ /** Model parameters or other config stored with the version (`{}` when none). */
124
+ config?: Record<string, unknown>,
125
+ /** The labels that point at this version now. */
126
+ labels?: string[],
127
+ /** `sha256:<hex>` of the version's canonical content. */
128
+ digest?: string,
129
+ /** True when this is the caller's fallback, not a registry copy. */
130
+ isFallback?: boolean,
131
+ /** The label's staged rollout, when it has one (the version above is the one SERVED). */
132
+ rollout?: PromptRollout | null, details?: PromptDetails);
133
+ /** Which rollout side served this copy (`candidate`, `base`, `unkeyed`), "" when the label has no rollout. */
134
+ get cohort(): string;
135
+ /** The body of a text prompt ("" for a chat prompt). */
136
+ get text(): string;
137
+ /** The messages of a chat prompt ([] for a text prompt). */
138
+ get messages(): ChatMessage[];
139
+ /** The placeholder names, sorted. */
140
+ get variables(): string[];
141
+ /** Fill the variables and stamp the active span. A text prompt gives a string, a chat prompt a message list. */
142
+ compile(values?: Record<string, unknown>): PromptBody;
143
+ /** Stamp this prompt's identity on `span` (default: the active span). Fallbacks stamp nothing. */
144
+ stamp(span?: Span | undefined): void;
145
+ }
146
+ /** Parse a registry 200 body into a Prompt; null when it is not one. `source`: the destination that answered. */
147
+ export declare function parsePrompt(body: unknown, fallbackName?: string, source?: string): Prompt | null;
148
+ /** Lowercase hex SHA-256 of a string's UTF-8 bytes (what the SDK sends as user_hash / session_hash). */
149
+ export declare function cohortHash(id: string): string;
150
+ /**
151
+ * The rollout bucket of a subject (`user:<hash>` / `session:<hash>`):
152
+ * uint32 big-endian of the first 4 bytes of SHA-256(salt + "|" + subject),
153
+ * mod 100 (rolloutcore.HashBucket; pinned by sdk/contract/prompt-rollout-cases.json).
154
+ */
155
+ export declare function rolloutBucket(salt: string, subject: string): number;
156
+ export declare function clearPromptCache(): void;
157
+ /** How many entries the prompt cache holds (tests and diagnostics). */
158
+ export declare function promptCacheSize(): number;
159
+ /**
160
+ * Get a prompt from the registry.
161
+ *
162
+ * ```ts
163
+ * const p = await getPrompt("support-reply", { fallback: "Answer: {{question}}" });
164
+ * const text = p.compile({ question }); // also stamps the active span
165
+ * ```
166
+ *
167
+ * The destinations are asked in order (`both`: the gateway, then the
168
+ * machine); the first one holding a cached copy serves it, else the first
169
+ * one that answers 200. Fresh for `cacheTtlMs`; stale, the cached copy is
170
+ * returned at once and revalidated in the background against the same
171
+ * destination (`cacheTtlMs: 0` revalidates before returning). With nothing
172
+ * cached and no destination answering: `fallback` when given, else
173
+ * `PromptNotFound` (every destination said not found) or `PromptFetchError`.
174
+ */
175
+ export declare function getPrompt(name: string, opts?: GetPromptOptions): Promise<Prompt>;