The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
fix(sdk): preserve query parameters in Observe endpoints (#923)
Rudy Mizrahi Celeklie932deb79652
diff --git a/docs/changelog/sdk.mdx b/docs/changelog/sdk.mdxindex 7e02ce7f..5081d9dc 100644--- a/docs/changelog/sdk.mdx+++ b/docs/changelog/sdk.mdx@@ -12,6 +12,7 @@ Stay up to date with the latest changes to the Beacon Observe SDK.## Unreleased- **Observed streams read through their own API keep their span** · An observed function returning a stream that has its own reading API, such as the Anthropic SDK's `client.messages.stream()` read with `finalMessage()` or events, a `ReadableStream` read with `getReader()`, or a Node stream sent through `pipe()`, never exported its span: the SDK replaced the stream with a wrapper that only `for await` went through, which also made `instanceof` checks on it fail. Such streams are now returned unchanged and their span ends when the function returns. Async generators and the Claude Agent SDK's `query()` are still traced until they are read to the end.+- **Observe endpoints keep their query string** · An endpoint with query parameters, such as a gateway URL carrying a tenant or routing parameter, had `/v1/observe` appended after its query, so spans went to the wrong route without any error. The path is now added to the URL's path, and the query and fragment are kept. `Observe.initialize()` now throws for an endpoint that is not an absolute URL, instead of exporting to an unusable address.- **API key scoped to Beacon Cloud** · `ASYMPTOTE_API_KEY` is now sent only to Beacon Cloud: in hosted mode, or to an explicit OTLP endpoint on the same origin as the base URL. Previously a service with both `ASYMPTOTE_API_KEY` and a generic `OTEL_EXPORTER_OTLP_ENDPOINT` sent the key to that collector on every export. Caller-supplied `headers` are unchanged.- **HTTPS required for the API key** · `Observe.initialize()` now throws when the key would be sent to a non-loopback `http://` base URL. `http://localhost`, `http://127.0.0.1` and `http://[::1]` remain allowed for local stubs.diff --git a/packages/asymptote-sdk-js/README.md b/packages/asymptote-sdk-js/README.mdindex 91c2eb1c..86b2cd42 100644--- a/packages/asymptote-sdk-js/README.md+++ b/packages/asymptote-sdk-js/README.md@@ -44,7 +44,9 @@ Observe.initialize({});```-The SDK appends `/v1/observe` when the endpoint does not already include it.+The SDK appends `/v1/observe` to the URL pathname when it is not already present,+preserving query parameters and fragments. Supply an absolute URL; invalid or+relative endpoints are rejected during configuration.Cloud spans carry `beacon.origin=cloud` and the compatibilityattributes documented in `docs/asymptote-observe-sdk.md`.diff --git a/packages/asymptote-sdk-js/src/endpoint-url.test.ts b/packages/asymptote-sdk-js/src/endpoint-url.test.tsnew file mode 100644index 00000000..3ccf6dd2--- /dev/null+++ b/packages/asymptote-sdk-js/src/endpoint-url.test.ts@@ -0,0 +1,57 @@+import { createServer } from "node:http";+import { afterEach, expect, it } from "vitest";+import { initialize, observe, flush, shutdown, resolveExporterConfig } from "./index.js";++afterEach(async () => { await shutdown(); });++for (const [name, suffix, expected] of [+ ["base trailing slash", "/", "/v1/observe"],+ ["complete path", "/v1/observe/", "/v1/observe"],+ ["complete path with query", "/v1/observe?project=fixture", "/v1/observe?project=fixture"],+ ["base path with query", "/collector/?project=fixture", "/collector/v1/observe?project=fixture"],+]) {+ it(`exports to the expected loopback route for ${name}`, async () => {+ const requests: { url: string | undefined; authorization: string | undefined; status: number; body: string }[] = [];+ const server = createServer((req, res) => {+ const chunks: Buffer[] = [];+ req.on("data", chunk => chunks.push(Buffer.from(chunk)));+ req.on("end", () => {+ const status = req.url === expected ? 200 : 404;+ requests.push({ url: req.url, authorization: req.headers.authorization, status, body: Buffer.concat(chunks).toString() });+ res.writeHead(status, { "Content-Type": "application/json" });+ res.end(status === 200 ? "{}" : '{"error":"unknown route"}');+ });+ });+ await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));+ const address = server.address();+ if (!address || typeof address === "string") throw new Error("missing owned listener");+ const endpoint = `http://127.0.0.1:${address.port}${suffix}`;+ try {+ initialize({ otlpEndpoint: endpoint, disableBatch: true, disableInstrumentations: true });+ observe({ name: "owned-export-fixture" }, () => "fixture")();+ await flush();+ expect(requests).toHaveLength(1);+ expect(requests[0].url).toBe(expected);+ expect(requests[0].status).toBe(200);+ expect(requests[0].authorization).toBeUndefined();+ expect(JSON.parse(requests[0].body).resourceSpans).toHaveLength(1);+ } finally {+ await shutdown();+ server.closeAllConnections();+ await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));+ }+ });+}++it("normalizes only the pathname, preserving encoded query values and fragment", () => {+ expect(resolveExporterConfig({ otlpEndpoint: "https://collector.example/base///?project=a%2Fb&tag=x&tag=y#local" }).observeUrl)+ .toBe("https://collector.example/base/v1/observe?project=a%2Fb&tag=x&tag=y#local");+ expect(resolveExporterConfig({ otlpEndpoint: "https://collector.example/v1/observe///?project=fixture#local" }).observeUrl)+ .toBe("https://collector.example/v1/observe?project=fixture#local");+});++it("rejects invalid or relative endpoints instead of constructing an unusable exporter URL", () => {+ for (const otlpEndpoint of ["/collector", "not a URL"]) {+ expect(() => resolveExporterConfig({ otlpEndpoint })).toThrow(TypeError);+ }+});diff --git a/packages/asymptote-sdk-js/src/index.ts b/packages/asymptote-sdk-js/src/index.tsindex a67b30e4..530e2941 100644--- a/packages/asymptote-sdk-js/src/index.ts+++ b/packages/asymptote-sdk-js/src/index.ts@@ -481,15 +481,14 @@ function makeSpanProcessor(exporter: SpanExporter, options: InitializeOptions):}function observeURL(endpoint: string): string {- let end = endpoint.length;- while (end > 0 && endpoint.charCodeAt(end - 1) === 47) {+ const url = new URL(endpoint);+ let end = url.pathname.length;+ while (end > 0 && url.pathname.charCodeAt(end - 1) === 47) {end -= 1;}- const trimmed = endpoint.slice(0, end);- if (trimmed.endsWith(DEFAULT_OBSERVE_PATH)) {- return trimmed;- }- return `${trimmed}${DEFAULT_OBSERVE_PATH}`;+ const trimmed = url.pathname.slice(0, end);+ url.pathname = trimmed.endsWith(DEFAULT_OBSERVE_PATH) ? trimmed : `${trimmed}${DEFAULT_OBSERVE_PATH}`;+ return url.toString();}function readSDKVersion(): string {