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): trace only async iterators through consumption (#976)
kyle-elliott-asymptoteeb3bb54d6f20
diff --git a/docs/changelog/sdk.mdx b/docs/changelog/sdk.mdxindex 44d01e60..7e02ce7f 100644--- a/docs/changelog/sdk.mdx+++ b/docs/changelog/sdk.mdx@@ -11,6 +11,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.- **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/src/index.test.ts b/packages/asymptote-sdk-js/src/index.test.tsindex ee31437f..77910a92 100644--- a/packages/asymptote-sdk-js/src/index.test.ts+++ b/packages/asymptote-sdk-js/src/index.test.ts@@ -2,6 +2,8 @@ import { SpanStatusCode } from "@opentelemetry/api";import { InMemorySpanExporter } from "@opentelemetry/sdk-trace-base";import { readFileSync } from "node:fs";import { createServer, type IncomingMessage } from "node:http";+import { Readable, Writable } from "node:stream";+import { pipeline } from "node:stream/promises";import { afterEach, beforeEach, describe, expect, it } from "vitest";import {@@ -377,9 +379,15 @@ describe("Asymptote Observe SDK", () => {initialize({ spanExporter: exporter, disableDefaultExporter: true, disableBatch: true });class Stream {#interrupted = false;+ #sent = false;async interrupt() { this.#interrupted = true; }get interrupted() { return this.#interrupted; }- async *[Symbol.asyncIterator]() { if (!this.#interrupted) yield "message"; }+ async next(): Promise<IteratorResult<string>> {+ if (this.#interrupted || this.#sent) return { value: undefined, done: true };+ this.#sent = true;+ return { value: "message", done: false };+ }+ [Symbol.asyncIterator]() { return this; }}const original = new Stream();const query = wrapClaudeAgentQuery(() => original);@@ -445,6 +453,30 @@ describe("Asymptote Observe SDK", () => {expect(cleaned).toBe(true);expect(exporter.getFinishedSpans()).toHaveLength(1);});++ // An iterable with its own reading API is returned untouched: a wrapper would see only for-await,+ // so reading it any other way would leave the span open and never export it.+ it.each([+ ["ReadableStream.getReader()", () => new ReadableStream({ start(c) { c.enqueue("x"); c.close(); } }), async (s: ReadableStream) => {+ expect(s).toBeInstanceOf(ReadableStream);+ await s.getReader().read();+ }],+ ["Readable.pipe()", () => Readable.from(["x"]), async (s: Readable) => {+ expect(s).toBeInstanceOf(Readable);+ await pipeline(s, new Writable({ write(_chunk, _encoding, done) { done(); } }));+ }],+ ])("returns an async iterable that is not an iterator as a value (%s)", async (_name, make, consume) => {+ const exporter = new InMemorySpanExporter();+ initialize({ spanExporter: exporter, disableDefaultExporter: true, disableBatch: true });+ const original = make();+ const sync = observe({ name: "sync" }, () => original)();+ const promised = await observe({ name: "promised" }, async () => make())();+ expect(sync).toBe(original);+ await consume(sync as never);+ await consume(promised as never);+ await flush();+ expect(exporter.getFinishedSpans().map(span => span.name).sort()).toEqual(["promised", "sync"]);+ });it("provides a tracer compatible with Vercel-style telemetry hooks", async () => {const exporter = new InMemorySpanExporter();initialize({ spanExporter: exporter, disableDefaultExporter: true, disableBatch: true });diff --git a/packages/asymptote-sdk-js/src/index.ts b/packages/asymptote-sdk-js/src/index.tsindex 28e556ef..a67b30e4 100644--- a/packages/asymptote-sdk-js/src/index.ts+++ b/packages/asymptote-sdk-js/src/index.ts@@ -562,7 +562,7 @@ function finishResult<T>(result: T, span: Span, options?: ObserveOptions): unkno},);}- if (isAsyncIterable(result)) {+ if (isAsyncIterator(result)) {// A stream such as the Claude Agent SDK's Query carries controls (interrupt(), setModel(), ...)// beside its iterator. Iteration goes through the traced iterator; every other read goes to// the original stream, with functions bound to it so private-field methods keep working, and@@ -629,8 +629,17 @@ function isPromiseLike(value: unknown): value is Promise<unknown> {return Boolean(value && typeof (value as Promise<unknown>).then === "function");}-function isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {- return Boolean(value && typeof (value as AsyncIterable<unknown>)[Symbol.asyncIterator] === "function");+// Only an async iterator, such as an async generator or the Claude Agent SDK's Query, is traced+// through consumption: its next() is the only way to read it. Other async iterables, such as the+// Anthropic SDK's Stream, ReadableStream or a Node Readable, can also be read through their own+// APIs (toReadableStream(), getReader(), pipe(), events), which a wrapper never sees, so wrapping+// them would leave the span open forever and break instanceof. Those are returned as values.+function isAsyncIterator(value: unknown): value is AsyncIterable<unknown> & AsyncIterator<unknown> {+ return Boolean(+ value &&+ typeof (value as AsyncIterable<unknown>)[Symbol.asyncIterator] === "function" &&+ typeof (value as AsyncIterator<unknown>).next === "function",+ );}function firstStringArg(args: unknown[]): string {