diff --git a/.github/workflows/cursor-sdk-tests.yml b/.github/workflows/cursor-sdk-tests.yml new file mode 100644 index 000000000..5522275f9 --- /dev/null +++ b/.github/workflows/cursor-sdk-tests.yml @@ -0,0 +1,47 @@ +name: Cursor SDK tests + +on: + pull_request: + branches: [dev, main] + paths: + - 'typescript/packages/traceai_cursor_sdk/**' + - 'typescript/packages/fi-core/**' + - 'typescript/packages/fi-semantic-conventions/**' + - 'typescript/pnpm-lock.yaml' + - 'typescript/pnpm-workspace.yaml' + - 'typescript/package.json' + - '.github/workflows/cursor-sdk-tests.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + cursor-sdk: + name: Cursor SDK build and tests + runs-on: ubuntu-latest + timeout-minutes: 15 + defaults: + run: + working-directory: typescript + env: + FI_BASE_URL: http://127.0.0.1:9 + FI_GRPC_URL: http://127.0.0.1:9 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: '22' + - run: corepack enable + - name: Frozen filtered install + run: pnpm install --frozen-lockfile --ignore-scripts --filter '@traceai/cursor-sdk...' + - name: Build package and shared dependencies + run: pnpm --filter '@traceai/cursor-sdk...' --workspace-concurrency=1 run build + - name: Offline tests and real SDK type contract + run: | + pnpm --filter '@traceai/cursor-sdk' exec jest --runInBand + pnpm --filter '@traceai/cursor-sdk' run typecheck:contract + - name: Package tarball + run: pnpm --filter '@traceai/cursor-sdk' pack --pack-destination "$RUNNER_TEMP/cursor-package" diff --git a/typescript/packages/traceai_cursor_sdk/README.md b/typescript/packages/traceai_cursor_sdk/README.md new file mode 100644 index 000000000..2268be0cc --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/README.md @@ -0,0 +1,190 @@ +# @traceai/cursor-sdk + +OpenTelemetry tracing for the [Cursor TypeScript SDK](https://cursor.com/docs/sdk/typescript) (`@cursor/sdk`). Each `agent.send()` becomes one trace in Future AGI: an AGENT span for the run, with child spans for tool calls, thinking and assistant text, the model, token usage and the run status. Every run of one agent shares a session (the agent id), so a multi-turn conversation reads as one session. + +This package traces the SDK inside your Node process. It is not the Cursor IDE hook integration, which traces the Cursor editor through `.cursor/hooks.json`. + +**What was verified:** live runs with a signed-in Cursor account (Plus plan, `@cursor/sdk` 1.0.38, `composer-2.5`, Node 26.8, local runtime) traced into Future AGI: a streamed run with `read`, `edit` and `shell` tools and thinking, a `wait()`-only follow-up in the same session, and a run the plan rejected (see [Live vendor verification](#live-vendor-verification-2026-10-20)). Against the real package without an account (1.0.37 and 1.0.38): the `Agent.create` / `Agent.resume` / `Agent.prompt` error paths (wrong key, unknown agent) and a missing-key local run. Not run: the cloud runtime (`bc-` agents). + +## Install + +```bash +npm install @traceai/cursor-sdk @traceai/fi-core @cursor/sdk +``` + +`@cursor/sdk` is a peer dependency. Nothing in this package imports it at runtime. + +## Use + +```ts +import * as CursorSDK from "@cursor/sdk"; +import { register, ProjectType } from "@traceai/fi-core"; +import { CursorSDKInstrumentation, shutdown } from "@traceai/cursor-sdk"; + +// Not the global provider: @cursor/sdk emits its own internal OpenTelemetry spans +// (scope "context-tracer") on the global provider. Pass this one explicitly instead. +const tracerProvider = register({ + projectName: "cursor-sdk-app", + projectType: ProjectType.OBSERVE, + setGlobalTracerProvider: false, +}); +const instrumentation = new CursorSDKInstrumentation({ tracerProvider }); +instrumentation.manuallyInstrument(CursorSDK); + +let agent: CursorSDK.SDKAgent | undefined; +try { + agent = await CursorSDK.Agent.create({ + apiKey: process.env.CURSOR_API_KEY!, + // A model and its params from Cursor.models.list(); plans with fixed model + // settings (Plus: fast=false) reject the run otherwise. + model: { id: "composer-2.5", params: [{ id: "fast", value: "false" }] }, + local: { cwd: process.cwd() }, + }); + const run = await agent.send("List the files in this folder and read README.md"); + for await (const event of run.stream()) { + // your own handling; events are passed through unchanged + } + await run.wait(); +} finally { + await agent?.[Symbol.asyncDispose](); + await shutdown(tracerProvider); // also exports a failed Agent.create span +} +``` + +`register()` reads `FI_API_KEY`, `FI_SECRET_KEY` and `FI_BASE_URL`. `@cursor/sdk` is ESM first, so pass the module namespace to `manuallyInstrument()`. A CommonJS app can instead call `registerInstrumentations({ tracerProvider, instrumentations: [new CursorSDKInstrumentation()] })` before `require("@cursor/sdk")`. + +`Agent.prompt()` is traced too: it calls `Agent.create()`, `send()` and `wait()` internally. `instrumentation.wrapAgent(agent)` traces an agent you got some other way. + +### SDK-internal spans + +`@cursor/sdk` bundles `@opentelemetry/api` and starts its own spans (instrumentation scope `context-tracer`, for example `LocalGitExecutor.exec`, `LocalRequestContextExecutor.computeGlobalCache`) on the global tracer provider: 27 of them in one short local run. They are outside this package's privacy settings and carry SDK internals such as file and rule names. With `setGlobalTracerProvider: false` and the provider passed explicitly, as above, none of them reach Future AGI (checked in `contract/real_sdk_error.mjs`). If your app registers its own global provider, those spans go there. + +### What the wrapper does and does not do + +- It patches the static `Agent.create` and `Agent.resume`, and `send`, `stream` and `wait` on the agent and run objects they return. You get the SDK's own objects back, and `run.stream()` yields the SDK's own events unchanged. +- It never reads the run's event stream on its own. The local runtime's stream is a single-consumer queue, so a second reader would steal your events. In this version, tool, thinking and assistant spans exist only for events your code reads through `run.stream()`. (The SDK's per-send `onStep` / `onDelta` callbacks could feed them without the stream; this version does not use them.) +- Tracing failures are logged with `diag.debug` and never reach your code. + +## Spans + +``` +Cursor Agent run AGENT session.id = agent id, model, tokens, status +├─ Cursor thinking CHAIN one per thinking block (deltas joined), cursor.thinking.duration_ms +├─ Cursor assistant message LLM one per run of consecutive text deltas +└─ Cursor tool: TOOL one per tool_call call_id: running -> completed | error +``` + +| Attribute | Where | Source | +| --- | --- | --- | +| `session.id` | run and child spans | `agent.agentId` (`agent-` local, `bc-` cloud), unless your app set a session id through fi-core context; on a create/resume error span only when an agent id was passed | +| `gen_ai.conversation.id`, `cursor.runtime` | run | the agent id; `local` or `cloud` from the id | +| `cursor.agent.id`, `cursor.run.id` | run and child spans | `agent.agentId`, `run.id` | +| `cursor.request.id` | run | `RunResult.requestId` / `run.requestId` (a live local run sends no `request` event; one is used when present) | +| `gen_ai.request.model`, `cursor.model.params` | run, assistant | `send({ model })`, `agent.model`, `run.model`, `RunResult.model` | +| `cursor.tools` | run | `system` event, when the runtime sends one | +| `gen_ai.usage.*` | run | see Token usage | +| `cursor.run.status`, `cursor.run.last_status_event`, `cursor.run.duration_ms` | run | `RunResult` / run handle / `status` events | +| `tool.name`, `gen_ai.tool.call.id`, `cursor.tool.status` | tool | `tool_call` events (ids like `tool_`; parallel calls are kept apart by id) | +| `cursor.thinking.duration_ms` | thinking | the block's closing event (empty text, `thinking_duration_ms`): Cursor's own figure for streaming the thinking text. The span starts at the previous event, so it also covers the model's wait before the first delta. | +| `cursor.tool.args_truncated`, `cursor.tool.result_truncated` | tool | the SDK's `truncated` flags | + +Status: + +- Run `finished`: OK. +- Run `error`: ERROR, `cursor.run.error_code` from `RunResult.error.code`. No status message by default; Cursor's own error text only with content opted in (see Privacy). +- Run `cancelled`: ERROR with `cursor.run.cancelled=true` (status message omitted by default) (no Cursor message, no error code). +- `send()`, `stream()` or `wait()` throwing: ERROR on the run span, an `exception` event and the SDK error fields (`cursor.error.name`, `.code`, `.http_status`, `.retryable`, `.operation`). The caller gets the same error. +- `Agent.create()` / `Agent.resume()` throwing (for example `AuthenticationError` for a wrong API key): one ERROR span `Cursor Agent create` / `Cursor Agent resume`. A successful create emits no span. +- A `tool_call` with `status: "error"`: ERROR on the tool span, with no status message by default. + +### When the run span closes + +At the first of: `wait()` resolving or throwing, the stream throwing, the stream ending cleanly, or a terminal status from `run.onDidChangeStatus`. While your code is reading the stream, closing waits for the stream to end, so buffered tool events are not lost. + +- Stop iterating early (`break`): open tool spans end with `cursor.tool.incomplete=true`, the run span gets `cursor.run.stream_detached=true` and closes when the run ends. +- A stream read partly and never closed: once the run's end is known, the span closes after `streamDrainTimeoutMs` (default 30000), marked like an early break. +- `wait()` only, or `Agent.prompt()`: one run span with status, model and tokens, no child spans. +- Neither stream nor wait: the run span closes when the run ends (status listener), after a short grace period (`runEndGraceMs`, default 2000) in which you can still start reading the stream. + +## Token usage + +The run span carries the SDK's cumulative run usage (`RunResult.usage` or `run.usage`) when it is present, otherwise the sum of the run's `usage` events (`cursor.usage.source` says which). + +Cursor's `inputTokens` excludes cache reads and writes: its `totalTokens` is input + output + cache read + cache write (a live run: 23820 + 258 + 19172 + 0 = 43250). Following the OpenTelemetry GenAI conventions, `gen_ai.usage.input_tokens` is the whole prompt, `inputTokens + cacheReadTokens + cacheWriteTokens` (42992 there), so input + output = total. The other keys: `outputTokens` to `gen_ai.usage.output_tokens`, `totalTokens` to `gen_ai.usage.total_tokens` (as reported; it excludes reasoning tokens), `cacheReadTokens` and `cacheWriteTokens` to the cache keys, `reasoningTokens` (when the model reports them) to `gen_ai.usage.output_tokens.reasoning`. Cursor's own numbers are kept as is in `cursor.usage.input_tokens`, `.output_tokens`, `.cache_read_tokens`, `.cache_write_tokens`, `.total_tokens` and `.reasoning_tokens`. Child spans carry no tokens, so trace totals are not double counted. Dollar cost is not on the stream; `agent.getUsage()` reports it where the account has the feature (it returned `403 feature_unavailable` on the Plus plan). + +## Privacy: content is off by default + +By default no prompt, tool argument, tool result, thinking text, assistant text, task summary or error text is exported: only names, ids, sizes (`cursor.input.length`, `cursor.text.length`), status, model and tokens. The API key is never read. + +Errors are content too: messages and stack traces carry local paths and usernames, and Cursor's run-error text can quote prompt text. By default an error exports only its class and structural fields: + +- the `exception` event has `exception.type` (the class name) and no `exception.message` or `exception.stacktrace`; +- fi-core 1.1 removes the status message and `cursor.error.message`, including fixed summaries, because hiding content also enables `hideErrorDetails`; +- `cursor.error.name`, `.code`, `.http_status`, `.retryable` and `.operation` are exported as is. + +Turn content on in code: + +```ts +new CursorSDKInstrumentation({ tracerProvider, traceConfig: { hideInputs: false, hideOutputs: false } }); +``` + +or with the fi-core environment variables `FI_HIDE_INPUTS=false` (prompts, tool arguments) and `FI_HIDE_OUTPUTS=false` (results, thinking, assistant text). Only an explicit `false` turns content on. Error messages, stack traces and Cursor's run-error text are exported only when both are on and `hideErrorDetails` / `FI_HIDE_ERROR_DETAILS` is not enabled. Setting `hideErrorDetails: false` alone does not opt into raw Cursor error content; it retains fixed summaries while content remains hidden. Text values are cut at 5000 characters (error messages at 500). With content on, values are exported as the SDK reports them, including file paths inside tool arguments and results. + +## Not captured / limitations + +- **Child spans without the stream.** Tool, thinking and assistant spans need your code to read `run.stream()`; `wait()`-only runs and `Agent.prompt()` get the run span only. This version does not use the SDK's `onStep` / `onDelta` callbacks. +- **Per-model-call spans.** The SDK reports usage per turn, not per model request; tokens are on the run span only. No cost on spans (`agent.getUsage()`, where the plan has it). +- **Runs not started by a traced `send()`**: runs fetched with `Agent.getRun()` or `Agent.listRuns()` are not traced. +- **System prompt, rules, skills and Cursor's internal context**: the SDK does not expose them on the stream. +- **Subagent internals**: a subagent started through the `task` tool is one tool span. +- **Cloud runtime (`bc-` agents)**: handled by the same code, not run end to end (the live runs used the local runtime). +- **Shell exit codes**: Cursor reports a shell command that exits non-zero as a `completed` call with `status: "success"`, so its span is OK; the exit code is only in the result (content on). +- **Runs still open when the process exits** without `shutdown()` / `forceFlush()` are lost; `shutdown()` closes runs still in progress with `cursor.run.status=running` and no status. +- **SDK-internal spans** (`context-tracer` scope) are not filtered by this package; keep the Future AGI provider non-global (see above). + +## Flushing + +Call `await shutdown(tracerProvider)` before a short script exits. It closes every open run span (runs waiting for their final status, partly read streams, runs still in progress) and flushes the provider. `instrumentation.forceFlush()` closes only runs whose end is already known. + +## Troubleshooting + +- No spans: call `manuallyInstrument(CursorSDK)` before `Agent.create()`. With ESM, the automatic require hook does not see `import`. +- Only a `Cursor Agent create` span, `AuthenticationError (401)`: the API key is wrong (or revoked). Create a user API key in the Cursor dashboard ([grok.com/dashboard](https://grok.com/dashboard); new keys start with `grok_`), or use `Cursor.auth.login()`. +- A `Cursor Agent run` span with ERROR status and no error code about a second after it starts, with a working key and no tool spans: the model or its settings are not in your plan. With content on, `cursor.error.message` reads `Model unavailable on ...`. Pass a model and params that `Cursor.models.list()` returns for your key, for example `{ id: "composer-2.5", params: [{ id: "fast", value: "false" }] }` on Plus. +- A `Cursor Agent run` span with ERROR status (`cursor.run.status=error`) a few seconds after `send()`, and no tool spans: no API key at all (no `apiKey`, no `CURSOR_API_KEY`, no stored login). `Agent.create()` succeeds without a key; the run is rejected once it starts (`[unknown] Invalid User API Key` in `RunResult.error`). +- `RunResult.error.message` says `Weekly usage limit reached`: the account has exhausted its allowance. Wait for the reset or add credits in Cursor; changing the tracing settings cannot remove this limit. The example exits non-zero for failed runs. +- A `shell` tool result saying the working directory no longer exists: `local.cwd` was a relative path. Pass an absolute one. +- Run span but no tool spans on a working key: your code did not read `run.stream()`, or read it after the run span closed. Read the stream before or while you call `wait()`. +- Extra traces with names like `LocalGitExecutor.exec`: the provider was registered as the global one. Use `setGlobalTracerProvider: false`. +- Spans missing at exit: await `shutdown()`. + +## Tests + +```bash +pnpm test # jest: fake SDK with the real 1.0.37/1.0.38 shapes and control flow, plus event sequences recorded from live runs +HOME="$(mktemp -d)" pnpm run test:contract +``` + +`test:contract` builds the package, type-checks the real `@cursor/sdk` types against the structural types the wrapper reads (`contract/sdk_types.ts`), checks the CommonJS auto-instrumentation hook, and runs the real SDK without an account (network to api.cursor.com): wrong-key `Agent.create` / `Agent.prompt` and unknown-agent `Agent.resume` (identical error to the caller, no message, stack or path exported by default, full text with content on), and a missing-key local run through `send()` / `stream()` / `wait()` that asserts the exporter receives only this package's spans. + +## Live vendor verification (2026-10-20) + +Signed-in Cursor account on the Plus plan, user API key, `@cursor/sdk` 1.0.38 (the npm release), `@traceai/fi-core` 1.0.0 from npm, this package installed from a `pnpm pack` tarball, Node 26.8, local runtime, `composer-2.5` with `fast: false`, a throwaway two-file git repo, a fresh `HOME`, `register({ setGlobalTracerProvider: false })`. Traces landed in a local Future AGI (`fi_verify.py --expect-type tool`: PASS for both projects). + +| Run | Trace | Spans | +| --- | --- | --- | +| streamed, default privacy | `eec8abf8c9a94e3c86881f144403c24e` | run OK (23820 input + 19172 cache read / 258 output, total 43250) -> 3 thinking, `read`, `edit`, 1 assistant message | +| `examples/basic.mjs` (before the cwd fix below) with content on (`FI_HIDE_INPUTS=false`, `FI_HIDE_OUTPUTS=false`), run 1 streamed | `581f15b8429948b7830e387361944f5a` | run OK -> 2 thinking, `shell`, `read` (in parallel with the shell), `shell`, 1 assistant message | +| same agent, run 2 `wait()` only | `93c316ab674e4a59aa3c9f9ce9b14543` | run OK, same session as run 1 | +| `composer-2.5` without params on Plus | `9529e2dfaba046829124a4b4b427fcf3` | run ERROR `RunError` (Cursor: "Model unavailable on Plus ... with fixed settings") | + +What the real stream showed, compared with the replay this package was first tested on (jest now also replays the recorded sequences): + +- No `request`, `user`, `system` or `task` events in a local run; the request id is only on `RunResult.requestId` (already read from there). +- Thinking arrives as text deltas closed by an empty-text event with `thinking_duration_ms`, as assumed; Cursor's duration covers only the streaming of the thinking text. +- Tool calls: `running` (repeated for partial updates with the same args), then `completed`; ids `tool_`; no `truncated` field; tools can run in parallel. +- `totalTokens` includes cache reads and writes, and `inputTokens` excludes them (the replay had assumed total = input + output). Fixed: `gen_ai.usage.input_tokens` now adds the cache tokens. +- A failed run can carry `RunResult.error` with a message and no code; fi-core 1.1 omits the default status message; the ERROR status and structural fields remain. +- A relative `local.cwd` breaks the agent's `shell` tool ("working directory no longer exists"); the example now resolves it. +- `agent.getUsage()` returned `403 feature_unavailable` on Plus. +- Privacy, over every stored column: default config, prompt marker 0, README marker 0, home paths 0; content on, the prompt in `input`, the README marker in tool and run outputs, home paths in tool arguments (as documented). API key 0 in both. No SDK-internal (`context-tracer`) span reached Future AGI. diff --git a/typescript/packages/traceai_cursor_sdk/contract/auto_instrument.cjs b/typescript/packages/traceai_cursor_sdk/contract/auto_instrument.cjs new file mode 100644 index 000000000..68ef1ed1a --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/contract/auto_instrument.cjs @@ -0,0 +1,15 @@ +/** + * Auto-instrumentation check (no network): `registerInstrumentations()` then + * `require("@cursor/sdk")` patches the CJS build's Agent class through the + * OpenTelemetry require hook. + * + * node contract/auto_instrument.cjs + */ +const assert = require("node:assert/strict"); +const { registerInstrumentations } = require("@opentelemetry/instrumentation"); +const { CursorSDKInstrumentation, isPatched } = require("../dist/src/index.js"); + +registerInstrumentations({ instrumentations: [new CursorSDKInstrumentation()] }); +const { Agent } = require("@cursor/sdk"); +assert.equal(isPatched(Agent), true, "require('@cursor/sdk') was not patched"); +console.log("PASS auto-instrumentation patched require('@cursor/sdk') Agent"); diff --git a/typescript/packages/traceai_cursor_sdk/contract/real_sdk_error.mjs b/typescript/packages/traceai_cursor_sdk/contract/real_sdk_error.mjs new file mode 100644 index 000000000..99590b52d --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/contract/real_sdk_error.mjs @@ -0,0 +1,230 @@ +/** + * Contract test against the REAL @cursor/sdk (ESM, Node >= 22.13, network to + * api.cursor.com). No Cursor account is needed. + * + * Wrong key (`apiKey: ""`): the SDK fails in `Agent.create()`. + * - the caller gets exactly the error it gets without tracing; + * - one ERROR span; by default only the error class and structural fields + * (no message, no stack trace, no local path); full text only on opt-in; + * - `Agent.prompt()` is traced through the patched `Agent.create()`. + * + * Unknown agent id: `Agent.resume()` fails; same checks, one ERROR span. + * + * Missing key (no apiKey, no CURSOR_API_KEY, no stored login): `Agent.create()` + * succeeds and the REAL local runtime runs `send()` / `stream()` / `wait()` + * until the backend rejects the run. With the documented setup (provider not + * registered as the global one, passed explicitly) the exporter receives only + * this package's spans, none of the SDK's own internal OpenTelemetry spans. + * + * HOME="$(mktemp -d)" pnpm run test:contract + * + * Use a throwaway HOME: the SDK keeps a local agent store under ~/.cursor. + */ +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { trace } from "@opentelemetry/api"; +import * as CursorSDK from "@cursor/sdk"; +import { BasicTracerProvider, InMemorySpanExporter, SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base"; +import { CursorSDKInstrumentation, INSTRUMENTATION_NAME, isPatched, shutdown } from "../dist/esm/index.js"; + +const BAD_KEY = "crsr_th8263_contract_invalid_key_do_not_use"; +/** The workspace checkout: the SDK's stack frames point into it (it contains the local username). */ +const CHECKOUT = fileURLToPath(new URL("../../..", import.meta.url)).replace(/\/$/, ""); +const cwd = mkdtempSync(join(tmpdir(), "cursor-sdk-contract-")); +const options = { apiKey: BAD_KEY, model: { id: "auto" }, local: { cwd } }; +delete process.env.CURSOR_API_KEY; + +function memory() { + const exporter = new InMemorySpanExporter(); + return { exporter, provider: new BasicTracerProvider({ spanProcessors: [new SimpleSpanProcessor(exporter)] }) }; +} +// The Future AGI provider of the documented setup: NOT the global provider. +const { exporter, provider } = memory(); +// A global provider, standing in for "register() made the FI provider global": catches the SDK's own spans. +const global = memory(); +trace.setGlobalTracerProvider(global.provider); + +const results = []; +async function capture(fn) { + try { + await fn(); + } catch (error) { + return error; + } + throw new Error("expected the SDK call to throw"); +} +const describe = (error) => ({ + name: error?.name, + message: error?.message, + code: error?.code, + status: error?.status, + isAuthenticationError: error instanceof CursorSDK.AuthenticationError, + isCursorSdkError: error instanceof CursorSDK.CursorSdkError, +}); +async function check(name, fn) { + exporter.reset(); + try { + await fn(); + results.push(`PASS ${name}`); + } catch (error) { + results.push(`FAIL ${name}: ${error?.stack ?? error}`); + } +} +const scopeOf = (s) => s.instrumentationScope?.name ?? s.instrumentationLibrary?.name; +/** Everything a span exports: attributes, events and status. */ +const exported = (spans) => + JSON.stringify(spans.map((s) => ({ name: s.name, attributes: s.attributes, events: s.events.map((e) => ({ name: e.name, attributes: e.attributes })), status: s.status }))); + +function assertPrivateByDefault(spans, expected) { + const dump = exported(spans); + assert.ok(!dump.includes(BAD_KEY), "API key leaked into a span"); + assert.ok(!dump.includes(CHECKOUT), `local checkout path (${CHECKOUT}) leaked into a span`); + assert.ok(!dump.includes("file://"), "file URL leaked into a span"); + assert.ok(!dump.includes("exception.stacktrace"), "stack trace exported by default"); + assert.ok(!dump.includes("exception.message"), "exception message exported by default"); + if (expected?.message) assert.ok(!dump.includes(expected.message), "raw error message exported by default"); +} + +function assertCreateErrorSpan(span, expected) { + assert.equal(span.status.code, 2, "span status must be ERROR"); + assert.equal(span.status.message, undefined); + assert.equal(span.attributes["cursor.error.message"], undefined); + assert.equal(span.attributes["fi.span.kind"], "AGENT"); + assert.equal(span.attributes["cursor.error.name"], expected.name); + if (expected.code) assert.equal(span.attributes["cursor.error.code"], expected.code); + if (expected.status) assert.equal(span.attributes["cursor.error.http_status"], expected.status); + assert.equal(span.attributes["cursor.runtime"], "local"); + assert.equal(span.attributes["gen_ai.request.model"], "auto"); + const exception = span.events.find((e) => e.name === "exception"); + assert.ok(exception, "exception event recorded"); + assert.deepEqual(exception.attributes, { "exception.type": expected.name }); +} + +// 1. Baseline without tracing. +const baselineCreate = describe(await capture(() => CursorSDK.Agent.create(options))); +const baselinePrompt = describe(await capture(() => CursorSDK.Agent.prompt("say hi", options))); +console.log("baseline Agent.create error:", JSON.stringify(baselineCreate)); + +// 2. Instrument the real module namespace (documented setup: explicit provider). +const instrumentation = new CursorSDKInstrumentation({ tracerProvider: provider }); +assert.equal(instrumentation.manuallyInstrument(CursorSDK), true); +assert.equal(isPatched(CursorSDK.Agent), true); + +await check("wrong key, Agent.create: same error to the caller, one ERROR span, no message/stack/path by default", async () => { + const error = describe(await capture(() => CursorSDK.Agent.create(options))); + assert.deepEqual(error, baselineCreate); + const spans = exporter.getFinishedSpans(); + assert.equal(spans.length, 1, `spans: ${spans.map((s) => s.name)}`); + assert.equal(spans[0].name, "Cursor Agent create"); + assertCreateErrorSpan(spans[0], error); + assertPrivateByDefault(spans, error); + console.log("create span (default):", JSON.stringify(spans[0].status), JSON.stringify(spans[0].events.map((e) => e.attributes))); +}); + +await check("wrong key, Agent.prompt goes through the patched Agent.create", async () => { + const error = describe(await capture(() => CursorSDK.Agent.prompt("say hi", options))); + assert.deepEqual(error, baselinePrompt); + const spans = exporter.getFinishedSpans(); + assert.equal(spans.length, 1, `spans: ${spans.map((s) => s.name)}`); + assert.equal(spans[0].name, "Cursor Agent create"); + assertCreateErrorSpan(spans[0], error); + assertPrivateByDefault(spans, error); +}); + +await check("Agent.resume of a missing local agent: same error to the caller, one ERROR span, no message/stack/path by default", async () => { + const missing = "agent-00000000-0000-4000-8000-000000000000"; + instrumentation.disable(); + const baseline = describe(await capture(() => CursorSDK.Agent.resume(missing, options))); + instrumentation.enable(); + exporter.reset(); + const error = describe(await capture(() => CursorSDK.Agent.resume(missing, options))); + assert.deepEqual(error, baseline); + const spans = exporter.getFinishedSpans(); + assert.equal(spans.length, 1, `spans: ${spans.map((s) => s.name)}`); + assert.equal(spans[0].name, "Cursor Agent resume"); + assert.equal(spans[0].status.code, 2); + assert.equal(spans[0].attributes["cursor.agent.id"], missing); + assert.equal(spans[0].attributes["session.id"], missing); + assert.equal(spans[0].status.message, undefined); + assert.equal(spans[0].attributes["cursor.error.message"], undefined); + const exception = spans[0].events.find((e) => e.name === "exception"); + assert.deepEqual(exception?.attributes, { "exception.type": spans[0].attributes["cursor.error.name"] }); + assertPrivateByDefault(spans, error); + console.log("resume error:", JSON.stringify(error), "| span status:", JSON.stringify(spans[0].status)); +}); + +await check("wrong key with content opted in: full message and the stack trace (which carries the local path)", async () => { + instrumentation.unpatch(); + const optIn = new CursorSDKInstrumentation({ tracerProvider: provider, traceConfig: { hideInputs: false, hideOutputs: false } }); + optIn.manuallyInstrument(CursorSDK); + try { + const error = describe(await capture(() => CursorSDK.Agent.create(options))); + const spans = exporter.getFinishedSpans(); + assert.equal(spans.length, 1); + assert.equal(spans[0].status.message, error.message); + const exception = spans[0].events.find((e) => e.name === "exception"); + assert.equal(exception.attributes["exception.message"], error.message); + assert.ok(String(exception.attributes["exception.stacktrace"]).includes(CHECKOUT), "opt-in stack trace has the SDK path"); + assert.ok(!exported(spans).includes(BAD_KEY), "API key leaked into a span"); + } finally { + optIn.unpatch(); + optIn.disable(); + instrumentation.manuallyInstrument(CursorSDK); + } +}); + +await check("missing key (no account): the REAL local runtime runs send/stream/wait; run span ERROR; exporter gets 0 SDK-internal spans", async () => { + global.exporter.reset(); + const noKey = { model: { id: "auto" }, local: { cwd } }; + const agent = await CursorSDK.Agent.create(noKey); + assert.ok(agent.agentId.startsWith("agent-"), agent.agentId); + let streamEndStatus; + const types = []; + let result; + try { + const run = await agent.send("List the files in this folder. CONTRACT-MARKER-7713"); + for await (const event of run.stream()) types.push(event.type === "status" ? `status:${event.status}` : event.type); + streamEndStatus = run.status; + result = await run.wait(); + } finally { + await agent[Symbol.asyncDispose]?.(); + } + await shutdown(provider); + console.log("missing-key run: events", types.join(","), "| run.status at stream end:", streamEndStatus, "| wait:", JSON.stringify({ status: result.status, error: result.error })); + + const spans = exporter.getFinishedSpans(); + const foreign = spans.filter((s) => scopeOf(s) !== INSTRUMENTATION_NAME); + assert.equal(foreign.length, 0, `foreign spans in the FI exporter: ${foreign.map((s) => `${scopeOf(s)}:${s.name}`)}`); + const run = spans.find((s) => s.name === "Cursor Agent run"); + assert.ok(run, `spans: ${spans.map((s) => s.name)}`); + assert.equal(run.status.code, 2); + assert.equal(run.attributes["session.id"], agent.agentId); + assert.equal(run.attributes["cursor.run.status"], "error"); + assert.equal(run.status.message, undefined, "fi-core hides error details by default"); + const dump = exported(spans); + assert.ok(!dump.includes("CONTRACT-MARKER-7713"), "prompt exported by default"); + assert.ok(!dump.includes(CHECKOUT) && !dump.includes(cwd), "local path exported by default"); + if (result.error?.message) assert.ok(!dump.includes(result.error.message), "Cursor's run-error text exported by default"); + + const internal = global.exporter.getFinishedSpans(); + const scopes = [...new Set(internal.map(scopeOf))]; + console.log(`SDK-internal spans on the GLOBAL provider (would reach Future AGI if the FI provider were global): ${internal.length}, scopes ${JSON.stringify(scopes)}, e.g. ${JSON.stringify([...new Set(internal.map((s) => s.name))].slice(0, 6))}`); + console.log("FI exporter scopes:", JSON.stringify([...new Set(spans.map(scopeOf))]), "spans:", spans.length); +}); + +await check("unpatch restores the SDK's own Agent.create", async () => { + instrumentation.unpatch(); + assert.equal(isPatched(CursorSDK.Agent), false); + await capture(() => CursorSDK.Agent.create(options)); + assert.equal(exporter.getFinishedSpans().length, 0); +}); + +rmSync(cwd, { recursive: true, force: true }); +console.log(results.join("\n")); +const failed = results.filter((r) => r.startsWith("FAIL")).length; +const version = JSON.parse(readFileSync(new URL("../node_modules/@cursor/sdk/package.json", import.meta.url), "utf8")).version; +console.log(`${results.length - failed}/${results.length} contract checks passed against @cursor/sdk ${version}`); +process.exit(failed ? 1 : 0); diff --git a/typescript/packages/traceai_cursor_sdk/contract/sdk_types.ts b/typescript/packages/traceai_cursor_sdk/contract/sdk_types.ts new file mode 100644 index 000000000..ea75a46f7 --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/contract/sdk_types.ts @@ -0,0 +1,33 @@ +/** + * Compile-time contract: the real `@cursor/sdk` types (devDependency, 1.0.38) + * fit the structural types the wrapper reads. `pnpm run typecheck:contract` + * fails when an SDK release changes a shape this package depends on. + */ +import type { AgentOptions, Run, RunResult, SDKAgent, SDKMessage, SendOptions, TokenUsage } from "@cursor/sdk"; +import { Agent } from "@cursor/sdk"; +import type { + AgentClassLike, + AgentLike, + AgentOptionsLike, + CursorSDKModuleLike, + RunLike, + RunResultLike, + SDKMessageLike, + SendOptionsLike, + TokenUsageLike, +} from "../src/types"; + +export const agentClass: AgentClassLike = Agent; +export const sdkModule: CursorSDKModuleLike = { Agent }; +export const agent = (value: SDKAgent): AgentLike => value; +export const run = (value: Run): RunLike => value; +export const runResult = (value: RunResult): RunResultLike => value; +export const message = (value: SDKMessage): SDKMessageLike => value; +export const usage = (value: TokenUsage): TokenUsageLike => value; +export const agentOptions = (value: AgentOptions): AgentOptionsLike => value; +export const sendOptions = (value: SendOptions): SendOptionsLike => value; + +/** Every SDKMessage `type` the tracer switches on exists in the SDK union. */ +type Handled = "system" | "user" | "assistant" | "thinking" | "tool_call" | "status" | "request" | "task" | "usage"; +export const handled: Handled[] = [] as SDKMessage["type"][]; +export const known: SDKMessage["type"][] = [] as Handled[]; diff --git a/typescript/packages/traceai_cursor_sdk/contract/tsconfig.json b/typescript/packages/traceai_cursor_sdk/contract/tsconfig.json new file mode 100644 index 000000000..eb67e8376 --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/contract/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "types": [] + }, + "files": ["sdk_types.ts"] +} diff --git a/typescript/packages/traceai_cursor_sdk/examples/basic.mjs b/typescript/packages/traceai_cursor_sdk/examples/basic.mjs new file mode 100644 index 000000000..32246d754 --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/examples/basic.mjs @@ -0,0 +1,47 @@ +// One traced Cursor SDK session (local runtime): two runs on one agent, the +// first streamed (tool spans), the second wait()-only. +// +// export CURSOR_API_KEY=... # Cursor dashboard: https://grok.com/dashboard +// export FI_API_KEY=... FI_SECRET_KEY=... FI_BASE_URL=https://api.futureagi.com +// node examples/basic.mjs [project dir] +import { resolve } from "node:path"; +import * as CursorSDK from "@cursor/sdk"; +import { ProjectType, register } from "@traceai/fi-core"; +import { CursorSDKInstrumentation, shutdown } from "@traceai/cursor-sdk"; + +// Absolute: with a relative local.cwd the agent's shell tool reports that its +// working directory no longer exists (@cursor/sdk 1.0.38). +const cwd = resolve(process.argv[2] ?? process.cwd()); +// Not global: @cursor/sdk starts its own internal spans on the global provider. +const tracerProvider = register({ + projectName: process.env.FI_PROJECT_NAME ?? "cursor-sdk-example", + projectType: ProjectType.OBSERVE, + setGlobalTracerProvider: false, +}); +new CursorSDKInstrumentation({ tracerProvider }).manuallyInstrument(CursorSDK); + +let agent; +try { + agent = await CursorSDK.Agent.create({ + apiKey: process.env.CURSOR_API_KEY, + // A model and its params from Cursor.models.list(). Plans with fixed model + // settings (Plus: fast=false) fail the run with "Model unavailable" otherwise. + model: { id: process.env.CURSOR_MODEL ?? "composer-2.5", params: [{ id: "fast", value: "false" }] }, + local: { cwd }, + }); + const run = await agent.send("List the files in this folder and read README.md, then tell me its first line."); + for await (const event of run.stream()) { + if (event.type === "tool_call") console.log(`tool ${event.name}: ${event.status}`); + } + const first = await run.wait(); + console.log("run 1:", first.status, first.usage); + if (first.status !== "finished") throw new Error(`Cursor run 1 ${first.status}; inspect RunResult.error and the account allowance.`); + + const second = await (await agent.send("Now say which file is the largest.")).wait(); + console.log("run 2:", second.status, second.usage, "\nagent (session id):", agent.agentId); + if (second.status !== "finished") throw new Error(`Cursor run 2 ${second.status}; inspect RunResult.error and the account allowance.`); +} finally { + await agent?.[Symbol.asyncDispose](); + // Export the spans, including a failed Agent.create (e.g. a bad CURSOR_API_KEY). + await shutdown(tracerProvider); +} diff --git a/typescript/packages/traceai_cursor_sdk/jest.config.js b/typescript/packages/traceai_cursor_sdk/jest.config.js new file mode 100644 index 000000000..1a1a13998 --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/jest.config.js @@ -0,0 +1,22 @@ +module.exports = { + preset: 'ts-jest', + testEnvironment: 'node', + roots: ['/src'], + testMatch: ['**/__tests__/**/*.test.ts'], + testPathIgnorePatterns: ['/node_modules/'], + collectCoverageFrom: ['src/**/*.ts', '!src/**/*.d.ts', '!src/index.ts', '!src/__tests__/**'], + coverageDirectory: 'coverage', + coverageReporters: ['text', 'lcov'], + transform: { + '^.+\\.ts$': ['ts-jest', { + tsconfig: { + module: 'commonjs' + } + }] + }, + moduleNameMapper: { + '^@traceai/fi-core$': '/../fi-core/src', + '^@traceai/fi-semantic-conventions$': '/../fi-semantic-conventions/src' + }, + testTimeout: 15000 +}; diff --git a/typescript/packages/traceai_cursor_sdk/package.json b/typescript/packages/traceai_cursor_sdk/package.json new file mode 100644 index 000000000..c6adcde0f --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/package.json @@ -0,0 +1,84 @@ +{ + "name": "@traceai/cursor-sdk", + "version": "0.1.0", + "description": "OpenTelemetry tracing for the Cursor TypeScript SDK (@cursor/sdk) agent runs", + "main": "./dist/src/index.js", + "module": "./dist/esm/index.js", + "esnext": "./dist/esnext/index.js", + "types": "./dist/src/index.d.ts", + "exports": { + ".": { + "types": "./dist/src/index.d.ts", + "import": "./dist/esm/index.js", + "require": "./dist/src/index.js" + } + }, + "scripts": { + "prebuild": "rimraf dist", + "build": "tsc --build tsconfig.json tsconfig.esm.json tsconfig.esnext.json && tsc-alias -p tsconfig.esm.json && pnpm run postbuild", + "postbuild": "echo '{\"type\": \"module\"}' > ./dist/esm/package.json", + "test": "jest", + "typecheck:contract": "tsc --noEmit -p contract/tsconfig.json", + "test:contract": "pnpm run build && pnpm run typecheck:contract && node contract/auto_instrument.cjs && node contract/real_sdk_error.mjs", + "prepare": "pnpm run build" + }, + "keywords": [ + "opentelemetry", + "tracing", + "instrumentation", + "cursor", + "cursor-sdk", + "coding-agent", + "agents", + "llm", + "observability" + ], + "author": "Future AGI ", + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "git+https://github.com/future-agi/traceAI.git", + "directory": "typescript/packages/traceai_cursor_sdk" + }, + "bugs": { + "url": "https://github.com/future-agi/traceAI/issues" + }, + "homepage": "https://github.com/future-agi/traceAI/tree/main/typescript/packages/traceai_cursor_sdk#readme", + "engines": { + "node": ">=18.0.0" + }, + "dependencies": { + "@opentelemetry/api": "^1.9.0", + "@opentelemetry/instrumentation": "^0.202.0", + "@traceai/fi-core": "workspace:^", + "@traceai/fi-semantic-conventions": "workspace:^" + }, + "devDependencies": { + "@cursor/sdk": "1.0.38", + "@opentelemetry/sdk-trace-base": "^2.0.1", + "@types/jest": "^29.5.14", + "@types/node": "^22.10.10", + "jest": "^29.7.0", + "rimraf": "^6.0.1", + "ts-jest": "^29.2.5", + "tsc-alias": "^1.8.10", + "typescript": "^5.7.3" + }, + "peerDependencies": { + "@cursor/sdk": ">=1.0.0 <2" + }, + "peerDependenciesMeta": { + "@cursor/sdk": { + "optional": true + } + }, + "files": [ + "dist", + "src", + "!**/__tests__/**", + "!**/*.tsbuildinfo" + ], + "publishConfig": { + "access": "public" + } +} diff --git a/typescript/packages/traceai_cursor_sdk/src/__tests__/fixtures/events.ts b/typescript/packages/traceai_cursor_sdk/src/__tests__/fixtures/events.ts new file mode 100644 index 000000000..0d546ea17 --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/src/__tests__/fixtures/events.ts @@ -0,0 +1,235 @@ +/** + * Stream events in the shapes `@cursor/sdk` 1.0.37 emits (`messages.d.ts`), + * following the local runtime's mapping in dist/esm/index.js: + * + * user-message-appended -> { type: "user", message: { role, content: [text] } } + * text-delta -> { type: "assistant", message: { role, content: [text chunk] } } + * thinking-delta -> { type: "thinking", text: chunk } + * thinking-completed -> { type: "thinking", text: "", thinking_duration_ms } + * tool-call-started / partial-tool-call / tool-call-completed + * -> { type: "tool_call", call_id, name, status, args?, result?, truncated? } + * summary -> { type: "task", text } + * turn-ended -> { type: "usage", usage: TokenUsage } + * status changes -> { type: "status", status: "RUNNING" | "FINISHED" | "ERROR", message? } + * request -> { type: "request", request_id } + */ +import type { SDKMessageLike, TokenUsageLike } from "../../types"; +import type { Step } from "./fakeSdk"; + +export const AGENT_ID = "agent-11111111-2222-4333-8444-555555555555"; +export const RUN_ID = "run-1"; +export const MODEL = { id: "composer-2", params: [{ id: "thinking", value: "high" }] }; +export const PROMPT_MARKER = "MARKER-CURSOR-UNIT-7731"; +export const SECRET_ARG = "/home/dev/secret-project/README.md"; +export const SECRET_RESULT = "TOP-SECRET-FILE-CONTENTS"; +export const THINKING_TEXT = "I should list files first."; + +const base = (agentId = AGENT_ID, runId = RUN_ID) => ({ agent_id: agentId, run_id: runId }); + +// Cursor's totalTokens = input + output + cache read + cache write (inputTokens excludes the cache). +export const USAGE: TokenUsageLike = { + inputTokens: 1200, + outputTokens: 80, + cacheReadTokens: 900, + cacheWriteTokens: 40, + totalTokens: 2220, + reasoningTokens: 12, +}; +/** `gen_ai.usage.input_tokens` for USAGE: Cursor's input plus cache read and write. */ +export const PROMPT_TOKENS = 2140; + +export function events(agentId = AGENT_ID, runId = RUN_ID) { + const b = base(agentId, runId); + return { + request: { type: "request", ...b, request_id: "req-xyz" } as SDKMessageLike, + running: { type: "status", ...b, status: "RUNNING" } as SDKMessageLike, + user: { type: "user", ...b, message: { role: "user", content: [{ type: "text", text: `List files ${PROMPT_MARKER}` }] } } as SDKMessageLike, + system: { type: "system", subtype: "init", ...b, model: MODEL, tools: ["read", "ls", "shell"] } as SDKMessageLike, + thinkingDelta1: { type: "thinking", ...b, text: "I should list " } as SDKMessageLike, + thinkingDelta2: { type: "thinking", ...b, text: "files first." } as SDKMessageLike, + thinkingDone: { type: "thinking", ...b, text: "", thinking_duration_ms: 420 } as SDKMessageLike, + textDelta1: { type: "assistant", ...b, message: { role: "assistant", content: [{ type: "text", text: "Let me " }] } } as SDKMessageLike, + textDelta2: { type: "assistant", ...b, message: { role: "assistant", content: [{ type: "text", text: "look." }] } } as SDKMessageLike, + lsStart: { type: "tool_call", ...b, call_id: "call-ls", name: "ls", status: "running", args: { path: SECRET_ARG } } as SDKMessageLike, + lsPartial: { type: "tool_call", ...b, call_id: "call-ls", name: "ls", status: "running", args: { path: SECRET_ARG, depth: 1 } } as SDKMessageLike, + lsDone: { + type: "tool_call", + ...b, + call_id: "call-ls", + name: "ls", + status: "completed", + args: { path: SECRET_ARG, depth: 1 }, + result: { status: "success", value: { files: ["README.md", SECRET_RESULT] } }, + truncated: { args: false, result: false }, + } as SDKMessageLike, + readStart: { type: "tool_call", ...b, call_id: "call-read", name: "read", status: "running", args: { path: SECRET_ARG } } as SDKMessageLike, + readError: { + type: "tool_call", + ...b, + call_id: "call-read", + name: "read", + status: "error", + args: { path: SECRET_ARG }, + result: { status: "error", error: `ENOENT ${SECRET_RESULT}` }, + } as SDKMessageLike, + shellCompletedOnly: { + type: "tool_call", + ...b, + call_id: "call-shell", + name: "shell", + status: "completed", + args: { command: "cat README.md" }, + result: { status: "success", value: { stdout: SECRET_RESULT, exitCode: 0 } }, + } as SDKMessageLike, + answerDelta: { type: "assistant", ...b, message: { role: "assistant", content: [{ type: "text", text: `README says ${SECRET_RESULT}` }] } } as SDKMessageLike, + task: { type: "task", ...b, text: "Summarized the folder" } as SDKMessageLike, + usage: { type: "usage", ...b, usage: USAGE } as SDKMessageLike, + finished: { type: "status", ...b, status: "FINISHED" } as SDKMessageLike, + errored: { type: "status", ...b, status: "ERROR", message: "Model provider returned 500" } as SDKMessageLike, + }; +} + +/** A full successful run: thinking, text, a tool with a partial update, a failing tool, a completed-only tool, the answer, usage. */ +export function fullRun(agentId = AGENT_ID, runId = RUN_ID): Step[] { + const e = events(agentId, runId); + return [ + { event: e.request }, + { event: e.running }, + { event: e.user }, + { event: e.system }, + { event: e.thinkingDelta1, delayMs: 2 }, + { event: e.thinkingDelta2, delayMs: 2 }, + { event: e.thinkingDone, delayMs: 2 }, + { event: e.textDelta1, delayMs: 2 }, + { event: e.textDelta2, delayMs: 2 }, + { event: e.lsStart, delayMs: 2 }, + { event: e.lsPartial, delayMs: 2 }, + { event: e.lsDone, delayMs: 3 }, + { event: e.readStart, delayMs: 2 }, + { event: e.readError, delayMs: 2 }, + { event: e.shellCompletedOnly, delayMs: 2 }, + { event: e.answerDelta, delayMs: 2 }, + { event: e.task }, + { event: e.usage }, + { event: e.finished }, + { finish: "finished", result: `README says ${SECRET_RESULT}`, usage: USAGE }, + ]; +} + +/** A run whose model call fails after one tool started. */ +export function failedRun(agentId = AGENT_ID, runId = RUN_ID): Step[] { + const e = events(agentId, runId); + return [ + { event: e.running }, + { event: e.lsStart, delayMs: 2 }, + { event: e.errored, delayMs: 2 }, + { finish: "error", error: { message: "Model provider returned 500", code: "provider_error" } }, + ]; +} + +/** A run that keeps going for a while after the first events (for early-break tests). */ +export function slowRun(agentId = AGENT_ID, runId = RUN_ID): Step[] { + const e = events(agentId, runId); + return [ + { event: e.running }, + { event: e.lsStart, delayMs: 2 }, + { event: e.textDelta1, delayMs: 30 }, + { event: e.lsDone, delayMs: 2 }, + { event: e.usage, delayMs: 2 }, + { event: e.finished, delayMs: 2 }, + { finish: "finished", result: "done", usage: USAGE }, + ]; +} + +/** Usage a live local run reported (2026-10-20, @cursor/sdk 1.0.38, composer-2.5): no reasoning tokens. */ +export const LIVE_USAGE: TokenUsageLike = { + inputTokens: 23820, + outputTokens: 258, + cacheReadTokens: 19172, + cacheWriteTokens: 0, + totalTokens: 43250, +}; +export const LIVE_READ_ID = "tool_78fbe67f-22b2-46f8-b1b4-ee84232072e"; +export const LIVE_EDIT_ID = "tool_785d444b-6d2c-4c59-ae58-848acbeec51"; +export const PLAN_ERROR = `Model unavailable on Plus ${SECRET_RESULT}`; + +/** + * The event sequence a live local run emitted (2026-10-20, @cursor/sdk 1.0.38, + * composer-2.5): read README.md, write notes.txt, answer. Paths and texts are + * placeholders. Unlike the documented example above: no `request`, `user`, + * `system` or `task` events (the request id is only on `RunResult.requestId`), + * each thinking block ends with an empty-text event carrying + * `thinking_duration_ms`, a partial `running` update repeats the same args, + * completed tools carry no `truncated`, and usage has no reasoning tokens. + */ +export function liveRun(agentId = AGENT_ID, runId = RUN_ID): Step[] { + const b = base(agentId, runId); + const thinking = (text: string, thinking_duration_ms?: number): Step => ({ + event: { type: "thinking", ...b, text, ...(thinking_duration_ms !== undefined ? { thinking_duration_ms } : {}) } as SDKMessageLike, + delayMs: 1, + }); + const tool = (call_id: string, name: string, status: string, result?: unknown): Step => ({ + event: { type: "tool_call", ...b, call_id, name, status, args: { path: SECRET_ARG }, ...(result ? { result } : {}) } as SDKMessageLike, + delayMs: 2, + }); + const assistant = (text: string): Step => ({ + event: { type: "assistant", ...b, message: { role: "assistant", content: [{ type: "text", text }] } } as SDKMessageLike, + delayMs: 1, + }); + return [ + { event: { type: "status", ...b, status: "RUNNING" } as SDKMessageLike }, + thinking("Reading"), + thinking(" README.md"), + thinking("", 62), + tool(LIVE_READ_ID, "read", "running"), + tool(LIVE_READ_ID, "read", "completed", { status: "success", value: { content: SECRET_RESULT, totalLines: 3, fileSize: 31 } }), + thinking("The second line"), + thinking("", 112), + tool(LIVE_EDIT_ID, "edit", "running"), + tool(LIVE_EDIT_ID, "edit", "running"), + tool(LIVE_EDIT_ID, "edit", "completed", { status: "success", value: { linesAdded: 1, linesRemoved: 0, diffString: `+${SECRET_RESULT}` } }), + thinking("Created notes.txt"), + thinking("", 235), + assistant("Created notes.txt "), + assistant(`with ${SECRET_RESULT}`), + { event: { type: "usage", ...b, usage: LIVE_USAGE } as SDKMessageLike }, + { event: { type: "status", ...b, status: "FINISHED" } as SDKMessageLike }, + { finish: "finished", result: `Created notes.txt with ${SECRET_RESULT}`, usage: LIVE_USAGE }, + ]; +} + +/** + * Parallel tool calls from a live run (2026-10-20): `shell` starts, `read` + * starts and completes, then `shell` completes. A shell command that exits + * non-zero is still a `completed` call with `status: "success"`. + */ +export function liveParallelToolsRun(agentId = AGENT_ID, runId = RUN_ID): Step[] { + const b = base(agentId, runId); + const tool = (call_id: string, name: string, status: string, args: unknown, result?: unknown, delayMs = 2): Step => ({ + event: { type: "tool_call", ...b, call_id, name, status, args, ...(result ? { result } : {}) } as SDKMessageLike, + delayMs, + }); + return [ + { event: { type: "status", ...b, status: "RUNNING" } as SDKMessageLike }, + tool("tool_shell", "shell", "running", { command: `ls -la ${SECRET_ARG}`, timeout: 30000 }), + tool("tool_read", "read", "running", { path: SECRET_ARG }), + tool("tool_read", "read", "completed", { path: SECRET_ARG }, { status: "success", value: { content: SECRET_RESULT } }), + tool("tool_shell", "shell", "completed", { command: `ls -la ${SECRET_ARG}`, timeout: 30000 }, { status: "success", value: { exitCode: 1, stdout: "", stderr: SECRET_RESULT } }, 15), + { event: { type: "status", ...b, status: "FINISHED" } as SDKMessageLike }, + { finish: "finished", result: "done", usage: LIVE_USAGE }, + ]; +} + +/** + * A live run with a model setting the plan does not include (2026-10-20, + * composer-2.5 without `fast: false` on Plus): the run starts, then fails + * with a status message and a `RunResult.error` that has no code. + */ +export function liveModelUnavailableRun(agentId = AGENT_ID, runId = RUN_ID): Step[] { + const b = base(agentId, runId); + return [ + { event: { type: "status", ...b, status: "RUNNING" } as SDKMessageLike }, + { event: { type: "status", ...b, status: "ERROR", message: PLAN_ERROR } as SDKMessageLike, delayMs: 2 }, + { finish: "error", error: { message: PLAN_ERROR } }, + ]; +} diff --git a/typescript/packages/traceai_cursor_sdk/src/__tests__/fixtures/fakeSdk.ts b/typescript/packages/traceai_cursor_sdk/src/__tests__/fixtures/fakeSdk.ts new file mode 100644 index 000000000..3aba459b1 --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/src/__tests__/fixtures/fakeSdk.ts @@ -0,0 +1,252 @@ +/** + * A stand-in for `@cursor/sdk` 1.0.37 / 1.0.38 with the same public shapes + * (`dist/esm/stubs.d.ts`, `agent.d.ts`, `run.d.ts`, `messages.d.ts`) and the + * same control flow as the real local runtime: + * + * - `Agent.prompt()` calls `Agent.create()` through the class, then + * `send()`, `wait()` and `[Symbol.asyncDispose]()`; + * - `run.stream()` is a single-consumer queue (`async *stream()` over a + * shifted array), closed when the run ends; + * - the run's status flips through `onDidChangeStatus` listeners; + * - `wait()` resolves with a `RunResult` built from the handle once terminal. + */ +import type { RunResultLike, SDKMessageLike, TokenUsageLike } from "../../types"; + +export class FakeAuthenticationError extends Error { + readonly code = "error"; + readonly status = 401; + readonly isRetryable = false; + readonly operation: string; + constructor(message: string, operation: string) { + super(message); + this.name = "AuthenticationError"; + this.operation = operation; + } +} + +export type Step = + | { event: SDKMessageLike; delayMs?: number } + | { finish: "finished" | "error" | "cancelled"; result?: string; error?: { message: string; code?: string }; usage?: TokenUsageLike; delayMs?: number } + | { throw: Error; delayMs?: number }; + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +/** Single-consumer event queue, like the SDK's run event buffer. */ +class EventQueue { + private readonly queue: SDKMessageLike[] = []; + private readonly waiters: Array<(r: { done: boolean; value?: SDKMessageLike; error?: Error }) => void> = []; + private closed = false; + private failure?: Error; + + push(event: SDKMessageLike): void { + const waiter = this.waiters.shift(); + if (waiter) waiter({ done: false, value: event }); + else this.queue.push(event); + } + + close(error?: Error): void { + this.closed = true; + this.failure = error; + for (const waiter of this.waiters.splice(0)) waiter({ done: true, error }); + } + + async *stream(): AsyncGenerator { + for (;;) { + const next = this.queue.shift(); + if (next) { + yield next; + continue; + } + if (this.closed) { + if (this.failure) throw this.failure; + return; + } + const r = await new Promise<{ done: boolean; value?: SDKMessageLike; error?: Error }>((resolve) => this.waiters.push(resolve)); + if (r.done) { + if (r.error) throw r.error; + return; + } + yield r.value as SDKMessageLike; + } + } +} + +export interface FakeRunOptions { + /** Omit `onDidChangeStatus` (an SDK without status listeners). */ + noStatusListener?: boolean; + /** Flip the status this many ms after the queue closes (models the real ordering race). */ + statusLagMs?: number; + /** Do not set `usage` on the handle at the end (only usage events carry tokens). */ + noHandleUsage?: boolean; +} + +export class FakeRun { + readonly id: string; + readonly agentId: string; + readonly requestId = "req-1"; + readonly createdAt = Date.now(); + model?: { id: string; params?: Array<{ id: string; value: string }> }; + result?: string; + error?: { message: string; code?: string }; + durationMs?: number; + usage?: TokenUsageLike; + private currentStatus = "running"; + private readonly listeners = new Set<(status: string) => void>(); + private readonly buffer = new EventQueue(); + private readonly done: Promise; + readonly onDidChangeStatus?: (listener: (status: string) => void) => () => void; + + constructor(agentId: string, runId: string, model: FakeRun["model"], steps: Step[], private readonly options: FakeRunOptions = {}) { + this.id = runId; + this.agentId = agentId; + this.model = model; + if (!options.noStatusListener) { + this.onDidChangeStatus = (listener) => { + this.listeners.add(listener); + return () => this.listeners.delete(listener); + }; + } + this.done = this.play(steps); + this.done.catch(() => undefined); + } + + get status(): string { + return this.currentStatus; + } + + supports(): boolean { + return true; + } + + stream(): AsyncGenerator { + return this.buffer.stream(); + } + + async wait(): Promise { + await this.done.catch(() => undefined); + while (this.currentStatus === "running") await sleep(1); + return { + id: this.id, + requestId: this.requestId, + status: this.currentStatus, + ...(this.result !== undefined ? { result: this.result } : {}), + ...(this.currentStatus === "error" && this.error ? { error: this.error } : {}), + ...(this.model ? { model: this.model } : {}), + ...(this.durationMs !== undefined ? { durationMs: this.durationMs } : {}), + ...(this.usage ? { usage: this.usage } : {}), + }; + } + + async cancel(): Promise { + this.setStatus("cancelled"); + } + + async conversation(): Promise { + return []; + } + + private setStatus(status: string): void { + this.currentStatus = status; + for (const listener of [...this.listeners]) listener(status); + } + + private async play(steps: Step[]): Promise { + const started = Date.now(); + for (const step of steps) { + if (step.delayMs) await sleep(step.delayMs); + else await Promise.resolve(); + if ("event" in step) { + this.buffer.push(step.event); + } else if ("throw" in step) { + this.buffer.close(step.throw); + this.setStatus("error"); + return; + } else { + this.result = step.result; + this.error = step.error; + this.durationMs = Date.now() - started; + if (step.usage && !this.options.noHandleUsage) this.usage = step.usage; + this.buffer.close(); + if (this.options.statusLagMs) await sleep(this.options.statusLagMs); + this.setStatus(step.finish); + return; + } + } + } +} + +export interface FakeAgentScript { + /** Steps per send(), in order. */ + runs: Step[][]; + runOptions?: FakeRunOptions; + /** Make send() reject with this error. */ + sendError?: Error; +} + +let agentCounter = 0; + +export class FakeAgent { + readonly agentId: string; + model?: { id: string; params?: Array<{ id: string; value: string }> }; + private sends = 0; + disposed = false; + + constructor(agentId: string, model: FakeAgent["model"], private readonly script: FakeAgentScript) { + this.agentId = agentId; + this.model = model; + } + + async send(message: string | { text: string }, options?: { model?: { id: string } }): Promise { + void message; + if (this.script.sendError) throw this.script.sendError; + if (options?.model) this.model = options.model; + const steps = this.script.runs[this.sends] ?? this.script.runs[this.script.runs.length - 1] ?? []; + this.sends += 1; + return new FakeRun(this.agentId, `run-${this.sends}`, this.model, steps, this.script.runOptions); + } + + close(): void { + this.disposed = true; + } + + async reload(): Promise {} + + async [Symbol.asyncDispose](): Promise { + this.disposed = true; + } +} + +/** Builds a fresh `Agent` class per test, scripted like the real one. */ +export function makeFakeSdk(script: FakeAgentScript, createError?: Error) { + class Agent { + private constructor() {} + + static async create(options: { apiKey?: string; model?: FakeRun["model"]; local?: { cwd?: string }; agentId?: string }): Promise { + if (createError) throw createError; + agentCounter += 1; + const id = options.agentId ?? `agent-0000000${agentCounter}-aaaa-4bbb-8ccc-000000000000`; + return new FakeAgent(id, options.model, script); + } + + static async resume(agentId: string, options?: { model?: { id: string } }): Promise { + if (createError) throw createError; + return new FakeAgent(agentId, options?.model, script); + } + + /** Same body as 1.0.37: `const e = await De.create(r ?? {}); ... e.send(t) ... r.wait() ... asyncDispose`. */ + static async prompt(message: string, options?: { model?: { id: string } }): Promise { + const agent = await Agent.create(options ?? {}); + try { + const run = await agent.send(message); + return await run.wait(); + } finally { + await agent[Symbol.asyncDispose](); + } + } + + static async list(): Promise<{ items: unknown[] }> { + return { items: [] }; + } + } + return { Agent }; +} diff --git a/typescript/packages/traceai_cursor_sdk/src/__tests__/helpers.ts b/typescript/packages/traceai_cursor_sdk/src/__tests__/helpers.ts new file mode 100644 index 000000000..a84feb82f --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/src/__tests__/helpers.ts @@ -0,0 +1,106 @@ +import { Context, ContextManager, ROOT_CONTEXT } from "@opentelemetry/api"; +import { + BasicTracerProvider, + InMemorySpanExporter, + ReadableSpan, + SimpleSpanProcessor, +} from "@opentelemetry/sdk-trace-base"; + +export function memoryProvider(): { provider: BasicTracerProvider; exporter: InMemorySpanExporter } { + const exporter = new InMemorySpanExporter(); + const provider = new BasicTracerProvider({ spanProcessors: [new SimpleSpanProcessor(exporter)] }); + return { provider, exporter }; +} + +export async function drain(iterable: AsyncIterable): Promise { + const out: T[] = []; + for await (const item of iterable) { + out.push(item); + } + return out; +} + +export function byName(spans: ReadableSpan[], name: string): ReadableSpan[] { + return spans.filter((span) => span.name === name); +} + +export function one(spans: ReadableSpan[], name: string): ReadableSpan { + const matches = byName(spans, name); + if (matches.length !== 1) { + throw new Error(`expected one span named ${name}, got ${matches.length}: ${spans.map((s) => s.name).join(", ")}`); + } + return matches[0]; +} + +export function parentId(span: ReadableSpan): string | undefined { + // sdk-trace-base 2.x exposes parentSpanContext; 1.x exposed parentSpanId. + const anySpan = span as unknown as { parentSpanContext?: { spanId: string }; parentSpanId?: string }; + return anySpan.parentSpanContext?.spanId ?? anySpan.parentSpanId; +} + +export function allAttributeText(spans: ReadableSpan[]): string { + return JSON.stringify(spans.map((span) => span.attributes)); +} + +/** Everything a span exports: attributes, events (exception events included) and status. */ +export function exportedText(spans: ReadableSpan[]): string { + return JSON.stringify( + spans.map((span) => ({ + name: span.name, + attributes: span.attributes, + events: span.events.map((e) => ({ name: e.name, attributes: e.attributes })), + status: span.status, + })), + ); +} + +/** Minimal synchronous context manager, so `context.with()` works in tests without extra deps. */ +export class StackContextManager implements ContextManager { + private stack: Context[] = [ROOT_CONTEXT]; + + active(): Context { + return this.stack[this.stack.length - 1]; + } + + with ReturnType>( + ctx: Context, + fn: F, + thisArg?: ThisParameterType, + ...args: A + ): ReturnType { + this.stack.push(ctx); + try { + return fn.call(thisArg, ...args); + } finally { + this.stack.pop(); + } + } + + bind(_ctx: Context, target: T): T { + return target; + } + + enable(): this { + return this; + } + + disable(): this { + this.stack = [ROOT_CONTEXT]; + return this; + } +} + +export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +/** Poll until `fn` returns true (spans end asynchronously after status changes). */ +export async function until(fn: () => boolean, timeoutMs = 2000): Promise { + const deadline = Date.now() + timeoutMs; + while (!fn()) { + if (Date.now() > deadline) throw new Error("condition not met in time"); + await sleep(2); + } +} + +export function attr(span: ReadableSpan, key: string): unknown { + return span.attributes[key]; +} diff --git a/typescript/packages/traceai_cursor_sdk/src/__tests__/package.test.ts b/typescript/packages/traceai_cursor_sdk/src/__tests__/package.test.ts new file mode 100644 index 000000000..2e85dbee3 --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/src/__tests__/package.test.ts @@ -0,0 +1,36 @@ +import * as fs from "fs"; +import * as path from "path"; +import * as api from "../index"; + +const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "..", "package.json"), "utf8")); + +describe("package surface", () => { + it("exports the instrumentation API", () => { + expect(typeof api.CursorSDKInstrumentation).toBe("function"); + expect(typeof api.instrumentCursorSDK).toBe("function"); + expect(typeof api.shutdown).toBe("function"); + expect(typeof api.resolveContentPolicy).toBe("function"); + expect(typeof api.isPatched).toBe("function"); + expect(api.INSTRUMENTATION_NAME).toBe(pkg.name); + expect(api.SpanNames.RUN).toBe("Cursor Agent run"); + }); + + it("VERSION matches package.json", () => { + expect(api.VERSION).toBe(pkg.version); + }); + + it("does not depend on @cursor/sdk at runtime (peer only)", () => { + expect(pkg.dependencies["@cursor/sdk"]).toBeUndefined(); + expect(pkg.peerDependencies["@cursor/sdk"]).toBeDefined(); + expect(pkg.peerDependenciesMeta["@cursor/sdk"].optional).toBe(true); + }); + + it("instrumentCursorSDK() patches the given module", () => { + const Agent = { create: async () => ({}) }; + const instrumentation = api.instrumentCursorSDK({ Agent }); + expect(api.isPatched(Agent)).toBe(true); + instrumentation.unpatch(); + instrumentation.disable(); + expect(api.isPatched(Agent)).toBe(false); + }); +}); diff --git a/typescript/packages/traceai_cursor_sdk/src/__tests__/sdkShape.test.ts b/typescript/packages/traceai_cursor_sdk/src/__tests__/sdkShape.test.ts new file mode 100644 index 000000000..33212a7b2 --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/src/__tests__/sdkShape.test.ts @@ -0,0 +1,61 @@ +/** + * Shape guard against the installed @cursor/sdk (devDependency, CJS build). + * No network: it only inspects the class and stubs Agent.create. + */ +import { CursorSDKInstrumentation, isPatched } from "../index"; + +type Sdk = { Agent: Record & { create: (...a: unknown[]) => Promise; prompt: (...a: unknown[]) => Promise } }; + +let sdk: Sdk | undefined; +let loadError: unknown; +try { + // eslint-disable-next-line @typescript-eslint/no-var-requires + sdk = require("@cursor/sdk"); +} catch (error) { + loadError = error; +} + +const maybe = sdk ? describe : describe.skip; + +maybe("installed @cursor/sdk", () => { + it("exposes Agent.create / resume / prompt as writable, configurable statics", () => { + for (const method of ["create", "resume", "prompt"]) { + const descriptor = Object.getOwnPropertyDescriptor(sdk!.Agent, method); + expect(typeof descriptor?.value).toBe("function"); + expect(descriptor?.writable).toBe(true); + expect(descriptor?.configurable).toBe(true); + } + }); + + it("Agent.prompt() calls Agent.create() through the class (so it is traced without its own wrapper)", async () => { + const Agent = sdk!.Agent; + const original = Agent.create; + const sentinel = new Error("sentinel: prompt went through Agent.create"); + Agent.create = async () => { + throw sentinel; + }; + try { + await expect(Agent.prompt("hi", { model: { id: "auto" } })).rejects.toMatchObject({ message: sentinel.message }); + } finally { + Agent.create = original; + } + }); + + it("manuallyInstrument() patches and unpatch() restores the real class", () => { + const instrumentation = new CursorSDKInstrumentation(); + const original = sdk!.Agent.create; + expect(instrumentation.manuallyInstrument(sdk as never)).toBe(true); + expect(isPatched(sdk!.Agent)).toBe(true); + expect(sdk!.Agent.create).not.toBe(original); + instrumentation.unpatch(); + instrumentation.disable(); + expect(sdk!.Agent.create).toBe(original); + expect(isPatched(sdk!.Agent)).toBe(false); + }); +}); + +if (!sdk) { + it("skips the shape guard when @cursor/sdk cannot load here", () => { + expect(loadError).toBeDefined(); + }); +} diff --git a/typescript/packages/traceai_cursor_sdk/src/__tests__/wrapper.test.ts b/typescript/packages/traceai_cursor_sdk/src/__tests__/wrapper.test.ts new file mode 100644 index 000000000..6f322429c --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/src/__tests__/wrapper.test.ts @@ -0,0 +1,809 @@ +import { SpanStatusCode, context } from "@opentelemetry/api"; +import { ReadableSpan } from "@opentelemetry/sdk-trace-base"; +import { setSession } from "@traceai/fi-core"; +import { CursorAttributes as C, SpanNames, StandardAttributes as S } from "../attributes"; +import { CursorSDKInstrumentation, resolveContentPolicy, shutdown } from "../instrumentation"; +import { isPatched } from "../wrappers"; +import { + AGENT_ID, + LIVE_EDIT_ID, + LIVE_READ_ID, + LIVE_USAGE, + PLAN_ERROR, + PROMPT_MARKER, + PROMPT_TOKENS, + SECRET_ARG, + SECRET_RESULT, + THINKING_TEXT, + USAGE, + events, + failedRun, + fullRun, + liveModelUnavailableRun, + liveParallelToolsRun, + liveRun, + slowRun, +} from "./fixtures/events"; +import { FakeAuthenticationError, FakeRun, Step, makeFakeSdk } from "./fixtures/fakeSdk"; +import { StackContextManager, allAttributeText, attr, byName, drain, exportedText, memoryProvider, one, parentId, sleep, until } from "./helpers"; + +const { provider, exporter } = memoryProvider(); +const instrumentations: CursorSDKInstrumentation[] = []; + +function instrument( + script: Parameters[0], + options: { createError?: Error; traceConfig?: { hideInputs?: boolean; hideOutputs?: boolean }; graceMs?: number; drainMs?: number } = {}, +) { + const sdk = makeFakeSdk(script, options.createError); + const instrumentation = new CursorSDKInstrumentation({ + tracerProvider: provider, + traceConfig: options.traceConfig, + runEndGraceMs: options.graceMs ?? 30, + streamDrainTimeoutMs: options.drainMs, + }); + instrumentations.push(instrumentation); + expect(instrumentation.manuallyInstrument(sdk)).toBe(true); + return { sdk, instrumentation }; +} + +const spans = () => exporter.getFinishedSpans(); +const runSpans = () => byName(spans(), SpanNames.RUN); +const toolSpans = () => spans().filter((s) => s.name.startsWith(SpanNames.TOOL_PREFIX)); +const childrenOf = (span: ReadableSpan) => spans().filter((s) => parentId(s) === span.spanContext().spanId); + +const ENV_KEYS = ["FI_HIDE_INPUTS", "FI_HIDE_OUTPUTS", "FI_HIDE_ERROR_DETAILS"] as const; +const savedEnv: Record = {}; + +beforeEach(() => { + exporter.reset(); + for (const key of ENV_KEYS) { + savedEnv[key] = process.env[key]; + delete process.env[key]; + } +}); + +afterEach(() => { + for (const key of ENV_KEYS) { + if (savedEnv[key] === undefined) delete process.env[key]; + else process.env[key] = savedEnv[key]; + } + while (instrumentations.length) { + const instrumentation = instrumentations.pop()!; + instrumentation.unpatch(); + instrumentation.disable(); + } +}); + +describe("streamed run (documented events)", () => { + async function streamFullRun(traceConfig?: { hideInputs?: boolean; hideOutputs?: boolean }) { + const { sdk } = instrument({ runs: [fullRun()] }, { traceConfig }); + const agent = await sdk.Agent.create({ apiKey: "crsr_unit_key", model: { id: "composer-2" }, local: { cwd: "/tmp" }, agentId: AGENT_ID }); + const run = await agent.send(`List files ${PROMPT_MARKER}`); + const seen = await drain(run.stream()); + const result = await run.wait(); + await until(() => runSpans().length === 1); + return { agent, run, seen, result }; + } + + it("builds run -> thinking / assistant / tool spans with session, model, tokens and status", async () => { + const { seen, result } = await streamFullRun(); + expect(seen).toHaveLength(19); + expect(result.status).toBe("finished"); + + const run = one(spans(), SpanNames.RUN); + expect(run.status.code).toBe(SpanStatusCode.OK); + expect(attr(run, S.FI_SPAN_KIND)).toBe("AGENT"); + expect(attr(run, S.SESSION_ID)).toBe(AGENT_ID); + expect(attr(run, S.CONVERSATION_ID)).toBe(AGENT_ID); + expect(attr(run, C.AGENT_ID)).toBe(AGENT_ID); + expect(attr(run, C.RUNTIME)).toBe("local"); + expect(attr(run, C.RUN_ID)).toBe("run-1"); + expect(attr(run, C.REQUEST_ID)).toBe("req-1"); + expect(attr(run, C.RUN_STATUS)).toBe("finished"); + expect(attr(run, C.LAST_STATUS_EVENT)).toBe("FINISHED"); + expect(attr(run, S.MODEL_NAME)).toBe("composer-2"); + expect(attr(run, C.TOOLS)).toEqual(["read", "ls", "shell"]); + expect(attr(run, S.INPUT_TOKENS)).toBe(PROMPT_TOKENS); + expect(attr(run, C.USAGE_INPUT_TOKENS)).toBe(USAGE.inputTokens); + expect(attr(run, S.OUTPUT_TOKENS)).toBe(USAGE.outputTokens); + expect(attr(run, S.TOTAL_TOKENS)).toBe(USAGE.totalTokens); + expect(attr(run, S.CACHE_READ_TOKENS)).toBe(USAGE.cacheReadTokens); + expect(attr(run, S.CACHE_WRITE_TOKENS)).toBe(USAGE.cacheWriteTokens); + expect(attr(run, S.REASONING_TOKENS)).toBe(USAGE.reasoningTokens); + expect(attr(run, C.USAGE_SOURCE)).toBe("run"); + expect(typeof attr(run, C.RUN_DURATION_MS)).toBe("number"); + expect(attr(run, C.INPUT_LENGTH)).toBe(`List files ${PROMPT_MARKER}`.length); + + const children = childrenOf(run); + expect(children.map((s) => s.name).sort()).toEqual( + [ + SpanNames.ASSISTANT_MESSAGE, + SpanNames.ASSISTANT_MESSAGE, + SpanNames.THINKING, + `${SpanNames.TOOL_PREFIX}ls`, + `${SpanNames.TOOL_PREFIX}read`, + `${SpanNames.TOOL_PREFIX}shell`, + ].sort(), + ); + for (const child of children) { + expect(child.spanContext().traceId).toBe(run.spanContext().traceId); + expect(attr(child, S.SESSION_ID)).toBe(AGENT_ID); + } + + const ls = one(spans(), `${SpanNames.TOOL_PREFIX}ls`); + expect(attr(ls, S.FI_SPAN_KIND)).toBe("TOOL"); + expect(attr(ls, S.TOOL_NAME)).toBe("ls"); + expect(attr(ls, S.TOOL_CALL_ID)).toBe("call-ls"); + expect(attr(ls, C.TOOL_STATUS)).toBe("completed"); + expect(attr(ls, C.TOOL_STARTED_EVENT)).toBe(true); + expect(attr(ls, C.TOOL_RESULT_TRUNCATED)).toBe(false); + expect(ls.status.code).toBe(SpanStatusCode.OK); + + const read = one(spans(), `${SpanNames.TOOL_PREFIX}read`); + expect(read.status.code).toBe(SpanStatusCode.ERROR); + expect(read.status.message).toBeUndefined(); + + const shell = one(spans(), `${SpanNames.TOOL_PREFIX}shell`); + expect(attr(shell, C.TOOL_STARTED_EVENT)).toBe(false); + expect(shell.status.code).toBe(SpanStatusCode.OK); + + const thinking = one(spans(), SpanNames.THINKING); + expect(attr(thinking, S.FI_SPAN_KIND)).toBe("CHAIN"); + expect(attr(thinking, C.THINKING_DURATION_MS)).toBe(420); + expect(attr(thinking, C.TEXT_LENGTH)).toBe(THINKING_TEXT.length); + + const messages = byName(spans(), SpanNames.ASSISTANT_MESSAGE); + expect(messages.map((m) => attr(m, C.TEXT_LENGTH))).toEqual(["Let me look.".length, `README says ${SECRET_RESULT}`.length]); + for (const m of messages) { + expect(attr(m, S.FI_SPAN_KIND)).toBe("LLM"); + expect(attr(m, S.MODEL_NAME)).toBe("composer-2"); + } + + // Children start and end inside the run span. + const toMs = (t: [number, number]) => t[0] * 1000 + t[1] / 1e6; + for (const child of children) { + expect(toMs(child.startTime as [number, number])).toBeGreaterThanOrEqual(toMs(run.startTime as [number, number])); + expect(toMs(child.endTime as [number, number])).toBeLessThanOrEqual(toMs(run.endTime as [number, number])); + } + }); + + it("hides prompt, tool args/results, thinking and assistant text by default", async () => { + await streamFullRun(); + const text = allAttributeText(spans()); + expect(text).not.toContain(PROMPT_MARKER); + expect(text).not.toContain(SECRET_ARG); + expect(text).not.toContain(SECRET_RESULT); + expect(text).not.toContain("I should list"); + expect(text).not.toContain("Let me"); + expect(text).not.toContain("Summarized the folder"); + for (const span of spans()) { + expect(span.attributes[S.INPUT_VALUE]).toBeUndefined(); + expect(span.attributes[S.OUTPUT_VALUE]).toBeUndefined(); + } + expect(resolveContentPolicy()).toEqual({ hideInputs: true, hideOutputs: true }); + }); + + it("exports content when traceConfig opts in", async () => { + await streamFullRun({ hideInputs: false, hideOutputs: false }); + const run = one(spans(), SpanNames.RUN); + expect(attr(run, S.INPUT_VALUE)).toBe(`List files ${PROMPT_MARKER}`); + expect(attr(run, S.OUTPUT_VALUE)).toBe(`README says ${SECRET_RESULT}`); + const ls = one(spans(), `${SpanNames.TOOL_PREFIX}ls`); + expect(JSON.parse(attr(ls, S.INPUT_VALUE) as string)).toEqual({ path: SECRET_ARG, depth: 1 }); + expect(attr(ls, S.OUTPUT_VALUE)).toContain(SECRET_RESULT); + expect(attr(one(spans(), SpanNames.THINKING), S.OUTPUT_VALUE)).toBe(THINKING_TEXT); + expect(byName(spans(), SpanNames.ASSISTANT_MESSAGE).map((m) => attr(m, S.OUTPUT_VALUE))).toEqual([ + "Let me look.", + `README says ${SECRET_RESULT}`, + ]); + // A failing tool's status message can carry tool output: only with outputs visible. + expect(one(spans(), `${SpanNames.TOOL_PREFIX}read`).status.message).toContain("ENOENT"); + }); + + it("opts in through FI_HIDE_INPUTS=false / FI_HIDE_OUTPUTS=false, fail-closed on anything else", async () => { + process.env.FI_HIDE_INPUTS = " FALSE "; + process.env.FI_HIDE_OUTPUTS = "no"; + expect(resolveContentPolicy()).toEqual({ hideInputs: false, hideOutputs: true }); + await streamFullRun(); + const run = one(spans(), SpanNames.RUN); + expect(attr(run, S.INPUT_VALUE)).toBe(`List files ${PROMPT_MARKER}`); + expect(attr(run, S.OUTPUT_VALUE)).toBeUndefined(); + expect(allAttributeText(spans())).not.toContain(SECRET_RESULT); + }); + + it("never records the API key", async () => { + await streamFullRun({ hideInputs: false, hideOutputs: false }); + expect(allAttributeText(spans())).not.toContain("crsr_unit_key"); + }); + + it("yields the SDK's own event objects and returns the SDK's own agent and run", async () => { + const steps = fullRun(); + const expected = steps.filter((s): s is { event: never } => "event" in s).map((s) => s.event); + const { sdk } = instrument({ runs: [steps] }); + const agent = await sdk.Agent.create({ model: { id: "composer-2" } }); + expect(agent.constructor.name).toBe("FakeAgent"); + const run = await agent.send("hi"); + expect(run).toBeInstanceOf(FakeRun); + const seen = await drain(run.stream()); + expect(seen).toHaveLength(expected.length); + seen.forEach((event, i) => expect(event).toBe(expected[i])); + }); +}); + +describe("live-recorded run (@cursor/sdk 1.0.38, 2026-10-20)", () => { + async function streamLive(steps: Step[], traceConfig?: { hideInputs?: boolean; hideOutputs?: boolean }) { + const { sdk } = instrument({ runs: [steps] }, { traceConfig }); + const agent = await sdk.Agent.create({ model: { id: "composer-2.5", params: [{ id: "fast", value: "false" }] }, local: { cwd: "/tmp" }, agentId: AGENT_ID }); + const run = await agent.send(`Read README.md ${PROMPT_MARKER}`); + await drain(run.stream()); + const result = await run.wait(); + await until(() => runSpans().length === 1); + return result; + } + + it("maps the real event sequence: thinking blocks, read and edit tools, one answer, request id and tokens", async () => { + await streamLive(liveRun()); + const run = one(spans(), SpanNames.RUN); + expect(run.status.code).toBe(SpanStatusCode.OK); + // No `request` event in a live run: the id comes from RunResult.requestId. + expect(attr(run, C.REQUEST_ID)).toBe("req-1"); + expect(childrenOf(run).map((s) => s.name)).toEqual([ + SpanNames.THINKING, + `${SpanNames.TOOL_PREFIX}read`, + SpanNames.THINKING, + `${SpanNames.TOOL_PREFIX}edit`, + SpanNames.THINKING, + SpanNames.ASSISTANT_MESSAGE, + ]); + expect(byName(spans(), SpanNames.THINKING).map((s) => attr(s, C.THINKING_DURATION_MS))).toEqual([62, 112, 235]); + const tools = toolSpans(); + expect(tools.map((s) => attr(s, C.TOOL_CALL_ID))).toEqual([LIVE_READ_ID, LIVE_EDIT_ID]); + expect(tools.every((s) => s.status.code === SpanStatusCode.OK && attr(s, C.TOOL_STATUS) === "completed")).toBe(true); + expect(attr(one(spans(), SpanNames.ASSISTANT_MESSAGE), C.TEXT_LENGTH)).toBe(`Created notes.txt with ${SECRET_RESULT}`.length); + + // Cursor's inputTokens excludes cache reads: 23820 + 19172 + 258 = 43250. + expect(attr(run, S.INPUT_TOKENS)).toBe(42992); + expect(attr(run, S.OUTPUT_TOKENS)).toBe(258); + expect(attr(run, S.TOTAL_TOKENS)).toBe(LIVE_USAGE.totalTokens); + expect(attr(run, S.CACHE_READ_TOKENS)).toBe(19172); + expect(attr(run, C.USAGE_INPUT_TOKENS)).toBe(LIVE_USAGE.inputTokens); + expect(attr(run, S.REASONING_TOKENS)).toBeUndefined(); + + const text = exportedText(spans()); + for (const secret of [PROMPT_MARKER, SECRET_ARG, SECRET_RESULT, "Reading", "notes.txt"]) expect(text).not.toContain(secret); + }); + + it("puts the real tool args, results, thinking and answer on the spans with content on", async () => { + await streamLive(liveRun(), { hideInputs: false, hideOutputs: false }); + const run = one(spans(), SpanNames.RUN); + expect(attr(run, S.INPUT_VALUE)).toContain(PROMPT_MARKER); + expect(attr(run, S.OUTPUT_VALUE)).toBe(`Created notes.txt with ${SECRET_RESULT}`); + const [read, edit] = toolSpans(); + expect(attr(read, S.INPUT_VALUE)).toContain(SECRET_ARG); + expect(attr(read, S.OUTPUT_VALUE)).toContain(SECRET_RESULT); + expect(attr(edit, S.OUTPUT_VALUE)).toContain(SECRET_RESULT); + expect(byName(spans(), SpanNames.THINKING).map((s) => attr(s, S.OUTPUT_VALUE))).toEqual(["Reading README.md", "The second line", "Created notes.txt"]); + }); + + it("keeps parallel tool calls apart by call id; a non-zero shell exit is a completed call", async () => { + await streamLive(liveParallelToolsRun()); + const shell = one(spans(), `${SpanNames.TOOL_PREFIX}shell`); + const read = one(spans(), `${SpanNames.TOOL_PREFIX}read`); + expect(attr(shell, C.TOOL_CALL_ID)).toBe("tool_shell"); + expect(attr(read, C.TOOL_CALL_ID)).toBe("tool_read"); + expect(shell.status.code).toBe(SpanStatusCode.OK); + expect(read.status.code).toBe(SpanStatusCode.OK); + const ms = (t: [number, number]) => t[0] * 1e3 + t[1] / 1e6; + // shell opened before read and closed after it. + expect(ms(shell.startTime)).toBeLessThanOrEqual(ms(read.startTime)); + expect(ms(shell.endTime)).toBeGreaterThan(ms(read.endTime)); + expect(exportedText(spans())).not.toContain(SECRET_RESULT); + }); + + it("reports a run the plan rejects as RunError without a code, and Cursor's text only with content on", async () => { + const result = await streamLive(liveModelUnavailableRun()); + expect(result.status).toBe("error"); + const run = one(spans(), SpanNames.RUN); + expect(run.status.code).toBe(SpanStatusCode.ERROR); + expect(run.status.message).toBeUndefined(); + expect(attr(run, C.RUN_ERROR_CODE)).toBeUndefined(); + expect(exportedText(spans())).not.toContain("Model unavailable"); + + exporter.reset(); + await streamLive(liveModelUnavailableRun(), { hideInputs: false, hideOutputs: false }); + expect(exportedText(spans())).toContain(PLAN_ERROR); + }); +}); + +describe("run outcomes", () => { + it("marks a failed run ERROR with Cursor's message and code; open tools fail with it", async () => { + const { sdk } = instrument({ runs: [failedRun()] }); + const agent = await sdk.Agent.create({ model: { id: "composer-2" } }); + const run = await agent.send("hi"); + await drain(run.stream()); + const result = await run.wait(); + expect(result.status).toBe("error"); + await until(() => runSpans().length === 1); + const span = one(spans(), SpanNames.RUN); + expect(span.status.code).toBe(SpanStatusCode.ERROR); + // fi-core 1.1 also removes fixed error summaries when content is hidden. + expect(span.status.message).toBeUndefined(); + expect(attr(span, C.ERROR_MESSAGE)).toBeUndefined(); + expect(exportedText(spans())).not.toContain("Model provider returned 500"); + expect(attr(span, C.RUN_ERROR_CODE)).toBe("provider_error"); + expect(attr(span, C.RUN_STATUS)).toBe("error"); + const ls = one(spans(), `${SpanNames.TOOL_PREFIX}ls`); + expect(ls.status.code).toBe(SpanStatusCode.ERROR); + expect(attr(ls, C.TOOL_INCOMPLETE)).toBe(true); + }); + + it("marks a cancelled run ERROR (cancelled)", async () => { + const { sdk } = instrument({ runs: [[{ event: events().running }, { finish: "cancelled", delayMs: 2 }]] }); + const agent = await sdk.Agent.create({ model: { id: "composer-2" } }); + const run = await agent.send("hi"); + await run.wait(); + await until(() => runSpans().length === 1); + const span = one(spans(), SpanNames.RUN); + expect(span.status).toEqual({ code: SpanStatusCode.ERROR }); + expect(attr(span, C.RUN_CANCELLED)).toBe(true); + }); + + it("records a stream that throws as ERROR with the exception, and the caller sees the same error", async () => { + const boom = new Error("connection reset"); + const { sdk } = instrument({ runs: [[{ event: events().lsStart }, { throw: boom, delayMs: 2 }]] }); + const agent = await sdk.Agent.create({ model: { id: "composer-2" } }); + const run = await agent.send("hi"); + await expect(drain(run.stream())).rejects.toBe(boom); + const span = one(spans(), SpanNames.RUN); + expect(span.status).toEqual({ code: SpanStatusCode.ERROR }); + expect(span.events.find((e) => e.name === "exception")?.attributes).toEqual({ "exception.type": "Error" }); + const ls = one(spans(), `${SpanNames.TOOL_PREFIX}ls`); + expect(ls.status.code).toBe(SpanStatusCode.ERROR); + expect(attr(ls, C.TOOL_INCOMPLETE)).toBe(true); + }); + + it("records send() rejecting (AuthenticationError) as an ERROR run span, error unchanged", async () => { + const auth = new FakeAuthenticationError("Invalid User API Key", "agent.send"); + const { sdk } = instrument({ runs: [], sendError: auth }); + const agent = await sdk.Agent.create({ model: { id: "composer-2" } }); + await expect(agent.send("hi")).rejects.toBe(auth); + const span = one(spans(), SpanNames.RUN); + expect(span.status).toEqual({ code: SpanStatusCode.ERROR }); + expect(attr(span, C.ERROR_MESSAGE)).toBeUndefined(); + expect(attr(span, C.ERROR_NAME)).toBe("AuthenticationError"); + expect(attr(span, C.ERROR_CODE)).toBe("error"); + expect(attr(span, C.ERROR_STATUS)).toBe(401); + expect(attr(span, C.ERROR_RETRYABLE)).toBe(false); + expect(attr(span, C.ERROR_OPERATION)).toBe("agent.send"); + const exception = span.events.find((e) => e.name === "exception"); + expect(exception?.attributes).toEqual({ "exception.type": "AuthenticationError" }); + }); + + it("records Agent.create() rejecting as one ERROR 'Cursor Agent create' span, error unchanged", async () => { + const auth = new FakeAuthenticationError("Invalid User API Key", "Agent.create"); + const { sdk } = instrument({ runs: [] }, { createError: auth }); + await expect(sdk.Agent.create({ apiKey: "crsr_bad", model: { id: "auto" }, local: { cwd: "/tmp" } })).rejects.toBe(auth); + const span = one(spans(), SpanNames.CREATE); + expect(span.status.code).toBe(SpanStatusCode.ERROR); + expect(attr(span, C.RUNTIME)).toBe("local"); + expect(attr(span, S.MODEL_NAME)).toBe("auto"); + expect(allAttributeText(spans())).not.toContain("crsr_bad"); + expect(spans()).toHaveLength(1); + }); + + it("records Agent.resume() rejecting as 'Cursor Agent resume' with the agent id as session", async () => { + const err = new Error("Agent agent-x not found"); + const { sdk } = instrument({ runs: [] }, { createError: err }); + await expect(sdk.Agent.resume("bc-1234")).rejects.toBe(err); + const span = one(spans(), SpanNames.RESUME); + expect(attr(span, C.AGENT_ID)).toBe("bc-1234"); + expect(attr(span, S.SESSION_ID)).toBe("bc-1234"); + expect(attr(span, C.RUNTIME)).toBe("cloud"); + }); + + it("records wait() rejecting, and the caller sees the same error", async () => { + const err = new Error("wait unsupported"); + const { sdk } = instrument({ runs: [[{ event: events().running }]] }); + const agent = await sdk.Agent.create({ model: { id: "composer-2" } }); + const original = FakeRun.prototype.wait; + FakeRun.prototype.wait = () => Promise.reject(err); + let run: FakeRun; + try { + run = await agent.send("hi"); + } finally { + FakeRun.prototype.wait = original; + } + await expect(run.wait()).rejects.toBe(err); + const span = one(spans(), SpanNames.RUN); + expect(span.status).toEqual({ code: SpanStatusCode.ERROR }); + expect(span.events.some((e) => e.name === "exception")).toBe(true); + }); +}); + +describe("error text is content", () => { + const PATH = "/Users/alice/secret-proj/.env"; + const MARKER = "ERRMARKER-5521"; + + function pathError(): FakeAuthenticationError { + const error = new FakeAuthenticationError(`ENOENT: open '${PATH}' while handling ${MARKER}`, "agent.send"); + error.stack = `AuthenticationError: ENOENT\n at send (file://${PATH}/../node_modules/@cursor/sdk/dist/esm/index.js:1:1)`; + return error; + } + + async function failEverywhere(traceConfig?: { hideInputs?: boolean; hideOutputs?: boolean }) { + // 1) Agent.create throws an error carrying a path. + const create = instrument({ runs: [] }, { createError: pathError(), traceConfig }); + await expect(create.sdk.Agent.create({ model: { id: "auto" } })).rejects.toThrow(MARKER); + // 2) send() throws one. + const send = instrument({ runs: [], sendError: pathError() }, { traceConfig }); + const agent = await send.sdk.Agent.create({ model: { id: "auto" } }); + await expect(agent.send("hi")).rejects.toThrow(MARKER); + // 3) A run fails with a path in Cursor's run error and in the status event. + const e = events(); + const runFail = instrument( + { + runs: [ + [ + { event: e.running }, + { event: { ...e.errored, message: `tool crashed reading ${PATH} ${MARKER}` }, delayMs: 2 }, + { finish: "error", error: { message: `[unknown] ${PATH} ${MARKER}`, code: "internal" } }, + ], + ], + }, + { traceConfig }, + ); + const agent2 = await runFail.sdk.Agent.create({ model: { id: "auto" } }); + const run = await agent2.send("hi"); + await drain(run.stream()); + await run.wait(); + await until(() => runSpans().length === 2); + return exportedText(spans()); + } + + it("default: no message, no stack, no path; fi-core also suppresses status summaries", async () => { + const text = await failEverywhere(); + expect(text).not.toContain(PATH); + expect(text).not.toContain("/Users/"); + expect(text).not.toContain(MARKER); + expect(text).not.toContain("exception.message"); + expect(text).not.toContain("exception.stacktrace"); + const create = one(spans(), SpanNames.CREATE); + expect(create.status.message).toBeUndefined(); + expect(create.events[0].attributes).toEqual({ "exception.type": "AuthenticationError" }); + const [sendSpan, failedRun] = runSpans(); + expect(sendSpan.status.message).toBeUndefined(); + expect(failedRun.status.message).toBeUndefined(); + expect(attr(failedRun, C.RUN_ERROR_CODE)).toBe("internal"); + }); + + it("only hiding one side still redacts error text", async () => { + const text = await failEverywhere({ hideInputs: false, hideOutputs: true }); + expect(text).not.toContain(PATH); + expect(text).not.toContain("exception.stacktrace"); + }); + + it("opt-in (inputs and outputs visible): full message, stack trace and Cursor's run-error text", async () => { + const text = await failEverywhere({ hideInputs: false, hideOutputs: false }); + expect(text).toContain(PATH); + expect(text).toContain("exception.stacktrace"); + expect(text).toContain("exception.message"); + const create = one(spans(), SpanNames.CREATE); + expect(create.status.message).toContain(MARKER); + expect(runSpans()[1].status.message).toBe(`[unknown] ${PATH} ${MARKER}`); + }); +}); + +describe("consumption patterns", () => { + it("wait() without streaming: run span with RunResult usage and status, no tool spans", async () => { + const { sdk } = instrument({ runs: [fullRun()] }); + const agent = await sdk.Agent.create({ model: { id: "composer-2" } }); + const run = await agent.send("hi"); + const result = await run.wait(); + expect(result.usage).toEqual(USAGE); + const span = one(spans(), SpanNames.RUN); + expect(span.status.code).toBe(SpanStatusCode.OK); + expect(attr(span, S.TOTAL_TOKENS)).toBe(USAGE.totalTokens); + expect(attr(span, C.USAGE_SOURCE)).toBe("run"); + expect(toolSpans()).toHaveLength(0); + }); + + it("Agent.prompt() is traced through Agent.create -> send -> wait (one run span)", async () => { + const { sdk } = instrument({ runs: [fullRun()] }); + const result = await sdk.Agent.prompt(`one shot ${PROMPT_MARKER}`, { model: { id: "composer-2" } }); + expect(result.status).toBe("finished"); + expect(spans().map((s) => s.name)).toEqual([SpanNames.RUN]); + const span = runSpans()[0]; + expect(span.status.code).toBe(SpanStatusCode.OK); + expect(attr(span, S.MODEL_NAME)).toBe("composer-2"); + expect(attr(span, S.INPUT_TOKENS)).toBe(PROMPT_TOKENS); + }); + + it("early break: open tools end incomplete, the run span ends when the run does", async () => { + const { sdk } = instrument({ runs: [slowRun()] }); + const agent = await sdk.Agent.create({ model: { id: "composer-2" } }); + const run = await agent.send("hi"); + for await (const event of run.stream()) { + if (event.type === "tool_call") break; + } + // The ls tool span ended at the break; the run is still going. + const ls = one(spans(), `${SpanNames.TOOL_PREFIX}ls`); + expect(attr(ls, C.TOOL_INCOMPLETE)).toBe(true); + expect(ls.status.code).toBe(SpanStatusCode.UNSET); + expect(runSpans()).toHaveLength(0); + await until(() => runSpans().length === 1); + const span = runSpans()[0]; + expect(attr(span, C.RUN_STREAM_DETACHED)).toBe(true); + expect(attr(span, C.RUN_STATUS)).toBe("finished"); + expect(span.status.code).toBe(SpanStatusCode.OK); + // Tokens come from the handle once the run ends. + expect(attr(span, S.TOTAL_TOKENS)).toBe(USAGE.totalTokens); + expect(toolSpans()).toHaveLength(1); + }); + + it("early break on an SDK without status listeners ends the run span at the break", async () => { + const { sdk } = instrument({ runs: [slowRun()], runOptions: { noStatusListener: true } }); + const agent = await sdk.Agent.create({ model: { id: "composer-2" } }); + const run = await agent.send("hi"); + for await (const event of run.stream()) { + if (event.type === "tool_call") break; + } + const span = one(spans(), SpanNames.RUN); + expect(attr(span, C.RUN_STREAM_DETACHED)).toBe(true); + expect(attr(span, C.RUN_STATUS)).toBe("running"); + expect(span.status.code).toBe(SpanStatusCode.UNSET); + }); + + it("fire and forget (no stream, no wait): the span ends after the run, within the grace period", async () => { + const { sdk } = instrument({ runs: [fullRun()] }, { graceMs: 10 }); + const agent = await sdk.Agent.create({ model: { id: "composer-2" } }); + await agent.send("hi"); + await until(() => runSpans().length === 1); + const span = runSpans()[0]; + expect(span.status.code).toBe(SpanStatusCode.OK); + expect(attr(span, S.TOTAL_TOKENS)).toBe(USAGE.totalTokens); + }); + + it("streaming that starts after the run finished (within the grace period) still gets tool spans", async () => { + const { sdk } = instrument({ runs: [fullRun()] }, { graceMs: 500 }); + const agent = await sdk.Agent.create({ model: { id: "composer-2" } }); + const run = await agent.send("hi"); + await until(() => run.status === "finished"); + await drain(run.stream()); + await until(() => runSpans().length === 1); + expect(toolSpans()).toHaveLength(3); + }); + + it("stream ends before the handle flips: usage from events, closed by wait() inside the grace period", async () => { + const { sdk } = instrument({ runs: [fullRun().filter((s) => !("event" in s) || s.event.type !== "status")], runOptions: { statusLagMs: 20, noHandleUsage: true } }); + const agent = await sdk.Agent.create({ model: { id: "composer-2" } }); + const run = await agent.send("hi"); + await drain(run.stream()); + expect(runSpans()).toHaveLength(0); + await run.wait(); + await until(() => runSpans().length === 1); + const span = runSpans()[0]; + expect(attr(span, C.USAGE_SOURCE)).toBe("events"); + expect(attr(span, S.INPUT_TOKENS)).toBe(PROMPT_TOKENS); + expect(typeof attr(span, C.RUN_DURATION_MS)).toBe("number"); + }); + + it("forceFlush() closes a run waiting in its grace period", async () => { + const { sdk, instrumentation } = instrument( + { runs: [fullRun().filter((s) => !("event" in s) || s.event.type !== "status")], runOptions: { statusLagMs: 300 } }, + { graceMs: 60_000 }, + ); + const agent = await sdk.Agent.create({ model: { id: "composer-2" } }); + const run = await agent.send("hi"); + await drain(run.stream()); + expect(runSpans()).toHaveLength(0); + await instrumentation.forceFlush(); + expect(runSpans()).toHaveLength(1); + expect(runSpans()[0].status.code).toBe(SpanStatusCode.OK); + }); + + it("shutdown() closes waiting runs of every instrumentation", async () => { + const { sdk } = instrument( + { runs: [fullRun().filter((s) => !("event" in s) || s.event.type !== "status")], runOptions: { statusLagMs: 300 } }, + { graceMs: 60_000 }, + ); + const agent = await sdk.Agent.create({ model: { id: "composer-2" } }); + const run = await agent.send("hi"); + await drain(run.stream()); + await shutdown(provider); + expect(runSpans()).toHaveLength(1); + }); + + it("stream and wait() concurrently: the span waits for the stream so no tool event is lost", async () => { + const { sdk } = instrument({ runs: [fullRun()] }); + const agent = await sdk.Agent.create({ model: { id: "composer-2" } }); + const run = await agent.send("hi"); + const iterator = run.stream(); + const first = await iterator.next(); + expect(first.done).toBe(false); + const result = await run.wait(); + expect(result.status).toBe("finished"); + expect(runSpans()).toHaveLength(0); + await drain({ [Symbol.asyncIterator]: () => iterator }); + await until(() => runSpans().length === 1); + expect(toolSpans()).toHaveLength(3); + expect(attr(runSpans()[0], C.USAGE_SOURCE)).toBe("run"); + }); +}); + +describe("streams that are never finished", () => { + it("a partly read stream that is never closed: the span closes after wait() plus the drain timeout", async () => { + const { sdk } = instrument({ runs: [fullRun()] }, { drainMs: 40 }); + const agent = await sdk.Agent.create({ model: { id: "composer-2" } }); + const run = await agent.send("hi"); + const iterator = run.stream(); + await iterator.next(); + await iterator.next(); + const result = await run.wait(); + expect(result.status).toBe("finished"); + expect(runSpans()).toHaveLength(0); + await until(() => runSpans().length === 1); + const span = runSpans()[0]; + expect(span.status.code).toBe(SpanStatusCode.OK); + expect(attr(span, C.RUN_STREAM_DETACHED)).toBe(true); + expect(attr(span, S.TOTAL_TOKENS)).toBe(USAGE.totalTokens); + }); + + it("forceFlush() closes a partly read stream's run once its end is known", async () => { + const { sdk, instrumentation } = instrument({ runs: [fullRun()] }, { drainMs: 60_000 }); + const agent = await sdk.Agent.create({ model: { id: "composer-2" } }); + const run = await agent.send("hi"); + const iterator = run.stream(); + await iterator.next(); + await run.wait(); + await sleep(20); + expect(runSpans()).toHaveLength(0); + await instrumentation.forceFlush(); + expect(runSpans()).toHaveLength(1); + expect(runSpans()[0].status.code).toBe(SpanStatusCode.OK); + }); + + it("shutdown() closes a run that is still in progress (status UNSET, cursor.run.status=running)", async () => { + const { sdk } = instrument({ runs: [slowRun()] }, { drainMs: 60_000 }); + const agent = await sdk.Agent.create({ model: { id: "composer-2" } }); + const run = await agent.send("hi"); + const iterator = run.stream(); + await iterator.next(); + await shutdown(provider); + const span = one(spans(), SpanNames.RUN); + expect(attr(span, C.RUN_STATUS)).toBe("running"); + expect(span.status.code).toBe(SpanStatusCode.UNSET); + await run.wait(); + }); +}); + +describe("sessions", () => { + it("two sends on one agent: two traces, one session (the agent id)", async () => { + const { sdk } = instrument({ runs: [fullRun(AGENT_ID, "run-1"), fullRun(AGENT_ID, "run-2")] }); + const agent = await sdk.Agent.create({ model: { id: "composer-2" }, agentId: AGENT_ID }); + for (const prompt of ["first", "second"]) { + const run = await agent.send(prompt); + await drain(run.stream()); + } + await until(() => runSpans().length === 2); + const [a, b] = runSpans(); + expect(a.spanContext().traceId).not.toBe(b.spanContext().traceId); + expect(attr(a, S.SESSION_ID)).toBe(AGENT_ID); + expect(attr(b, S.SESSION_ID)).toBe(AGENT_ID); + expect([attr(a, C.RUN_ID), attr(b, C.RUN_ID)].sort()).toEqual(["run-1", "run-2"]); + }); + + it("Agent.resume() agents are traced and keep the resumed id as session", async () => { + const { sdk } = instrument({ runs: [fullRun("bc-abc", "run-9")] }); + const agent = await sdk.Agent.resume("bc-abc"); + const run = await agent.send("continue"); + await drain(run.stream()); + await until(() => runSpans().length === 1); + expect(attr(runSpans()[0], S.SESSION_ID)).toBe("bc-abc"); + expect(attr(runSpans()[0], C.RUNTIME)).toBe("cloud"); + }); + + it("an app-set fi-core session id wins over the agent id", async () => { + const manager = new StackContextManager(); + context.setGlobalContextManager(manager); + try { + const { sdk } = instrument({ runs: [fullRun()] }); + const agent = await sdk.Agent.create({ model: { id: "composer-2" }, agentId: AGENT_ID }); + const run = await context.with(setSession(context.active(), { sessionId: "app-session-1" }), () => agent.send("hi")); + await drain(run.stream()); + await until(() => runSpans().length === 1); + expect(attr(runSpans()[0], S.SESSION_ID)).toBe("app-session-1"); + expect(attr(runSpans()[0], C.AGENT_ID)).toBe(AGENT_ID); + for (const tool of toolSpans()) expect(attr(tool, S.SESSION_ID)).toBeUndefined(); + } finally { + context.disable(); + } + }); +}); + +describe("patching", () => { + it("is idempotent, reversible, and a disabled instrumentation passes through", async () => { + const { sdk, instrumentation } = instrument({ runs: [fullRun()] }); + expect(isPatched(sdk.Agent)).toBe(true); + const patchedCreate = sdk.Agent.create; + expect(instrumentation.manuallyInstrument(sdk)).toBe(true); + expect(sdk.Agent.create).toBe(patchedCreate); + + instrumentation.disable(); + const agent = await sdk.Agent.create({ model: { id: "composer-2" } }); + const run = await agent.send("hi"); + await run.wait(); + await sleep(20); + expect(spans()).toHaveLength(0); + + instrumentation.enable(); + instrumentation.unpatch(); + expect(isPatched(sdk.Agent)).toBe(false); + expect(Object.prototype.hasOwnProperty.call(sdk.Agent, "create")).toBe(true); + const plain = await sdk.Agent.create({ model: { id: "composer-2" } }); + expect(isPatched(plain)).toBe(false); + }); + + it("unpatch() also stops agents created before it, without disable()", async () => { + const { sdk, instrumentation } = instrument({ runs: [fullRun(), fullRun()] }); + const agent = await sdk.Agent.create({ model: { id: "composer-2" } }); + instrumentation.unpatch(); + const run = await agent.send("hi"); + await drain(run.stream()); + await run.wait(); + await sleep(20); + expect(spans()).toHaveLength(0); + // Instrumenting again resumes tracing for that agent. + expect(instrumentation.manuallyInstrument(sdk)).toBe(true); + const again = await agent.send("again"); + await again.wait(); + await until(() => runSpans().length === 1); + }); + + it("wrapAgent() traces an agent obtained elsewhere", async () => { + const sdk = makeFakeSdk({ runs: [fullRun()] }); + const instrumentation = new CursorSDKInstrumentation({ tracerProvider: provider, runEndGraceMs: 10 }); + instrumentations.push(instrumentation); + const agent = await sdk.Agent.create({ model: { id: "composer-2" } }); + expect(instrumentation.wrapAgent(agent)).toBe(agent); + const run = await agent.send("hi"); + await drain(run.stream()); + await until(() => runSpans().length === 1); + expect(toolSpans()).toHaveLength(3); + }); + + it("returns false for something that is not the SDK", () => { + const instrumentation = new CursorSDKInstrumentation({ tracerProvider: provider }); + instrumentations.push(instrumentation); + expect(instrumentation.manuallyInstrument({} as never)).toBe(false); + expect(instrumentation.manuallyInstrument({ Agent: {} } as never)).toBe(false); + }); +}); + +describe("robustness", () => { + it("ignores malformed events and a tool completion repeated after its span ended", async () => { + const e = events(); + const steps: Step[] = [ + { event: { type: "tool_call" } }, + { event: { type: "assistant", message: "not-an-object" } as never }, + { event: { type: "brand_new_event", foo: 1 } as never }, + { event: e.lsStart }, + { event: e.lsDone, delayMs: 2 }, + { event: e.lsDone }, + { event: { type: "usage", usage: { inputTokens: "x" } } as never }, + { event: e.finished }, + { finish: "finished" }, + ]; + const { sdk } = instrument({ runs: [steps] }); + const agent = await sdk.Agent.create({ model: { id: "composer-2" } }); + const run = await agent.send({ text: "object message", images: [{ url: "x" }] } as never); + const seen = await drain(run.stream()); + expect(seen).toHaveLength(steps.length - 1); + await until(() => runSpans().length === 1); + const span = runSpans()[0]; + expect(span.status.code).toBe(SpanStatusCode.OK); + expect(attr(span, C.INPUT_IMAGE_COUNT)).toBe(1); + expect(byName(spans(), `${SpanNames.TOOL_PREFIX}ls`)).toHaveLength(1); + expect(byName(spans(), `${SpanNames.TOOL_PREFIX}unknown`)).toHaveLength(1); + expect(attr(span, S.TOTAL_TOKENS)).toBeUndefined(); + }); +}); diff --git a/typescript/packages/traceai_cursor_sdk/src/attributes.ts b/typescript/packages/traceai_cursor_sdk/src/attributes.ts new file mode 100644 index 000000000..d24de557e --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/src/attributes.ts @@ -0,0 +1,100 @@ +/** + * Span names and attribute keys for Cursor SDK spans. + * + * Standard keys (`fi.span.kind`, `session.id`, `input.value`, token counts...) + * come from `@traceai/fi-semantic-conventions` so the Future AGI collector + * promotes them. `cursor.*` keys carry the SDK's own structural fields. + */ +import { SemanticConventions } from "@traceai/fi-semantic-conventions"; + +export const SpanNames = { + /** One `agent.send()` run (also each run inside `Agent.prompt()`). */ + RUN: "Cursor Agent run", + /** `Agent.create()` that threw (bad API key, bad model...). Successful creates emit no span. */ + CREATE: "Cursor Agent create", + /** `Agent.resume()` that threw. Successful resumes emit no span. */ + RESUME: "Cursor Agent resume", + /** Prefix of a tool span: `Cursor tool: read`. */ + TOOL_PREFIX: "Cursor tool: ", + THINKING: "Cursor thinking", + ASSISTANT_MESSAGE: "Cursor assistant message", +} as const; + +export const CursorAttributes = { + AGENT_ID: "cursor.agent.id", + RUNTIME: "cursor.runtime", + RUN_ID: "cursor.run.id", + REQUEST_ID: "cursor.request.id", + RUN_STATUS: "cursor.run.status", + RUN_DURATION_MS: "cursor.run.duration_ms", + RUN_ERROR_CODE: "cursor.run.error_code", + RUN_CANCELLED: "cursor.run.cancelled", + /** The consumer stopped iterating `run.stream()` before the run ended. */ + RUN_STREAM_DETACHED: "cursor.run.stream_detached", + /** Last `status` stream event (CREATING, RUNNING, FINISHED, ERROR, CANCELLED, EXPIRED). */ + LAST_STATUS_EVENT: "cursor.run.last_status_event", + SEND_MODE: "cursor.send.mode", + MODEL_PARAMS: "cursor.model.params", + TOOLS: "cursor.tools", + INPUT_LENGTH: "cursor.input.length", + INPUT_IMAGE_COUNT: "cursor.input.image_count", + + TOOL_CALL_ID: "cursor.tool.call_id", + TOOL_STATUS: "cursor.tool.status", + TOOL_ARGS_TRUNCATED: "cursor.tool.args_truncated", + TOOL_RESULT_TRUNCATED: "cursor.tool.result_truncated", + /** The run ended (or the consumer stopped reading) before the tool's completion event. */ + TOOL_INCOMPLETE: "cursor.tool.incomplete", + /** false when the SDK sent only the completion event; the span then starts at the previous event. */ + TOOL_STARTED_EVENT: "cursor.tool.started_event", + + THINKING_DURATION_MS: "cursor.thinking.duration_ms", + TEXT_LENGTH: "cursor.text.length", + ASSISTANT_TOOL_USE_COUNT: "cursor.assistant.tool_use_count", + + USAGE_INPUT_TOKENS: "cursor.usage.input_tokens", + USAGE_OUTPUT_TOKENS: "cursor.usage.output_tokens", + USAGE_CACHE_READ_TOKENS: "cursor.usage.cache_read_tokens", + USAGE_CACHE_WRITE_TOKENS: "cursor.usage.cache_write_tokens", + USAGE_TOTAL_TOKENS: "cursor.usage.total_tokens", + USAGE_REASONING_TOKENS: "cursor.usage.reasoning_tokens", + /** `run` when the SDK's cumulative run usage was used, `events` when summed from `usage` stream events. */ + USAGE_SOURCE: "cursor.usage.source", + + /** SDK error fields (`CursorSdkError`): never content. */ + ERROR_NAME: "cursor.error.name", + ERROR_CODE: "cursor.error.code", + ERROR_STATUS: "cursor.error.http_status", + ERROR_RETRYABLE: "cursor.error.retryable", + ERROR_OPERATION: "cursor.error.operation", + ERROR_MESSAGE: "cursor.error.message", +} as const; + +/** Standard keys used by this package, resolved from fi-semantic-conventions. */ +export const StandardAttributes = { + FI_SPAN_KIND: SemanticConventions.FI_SPAN_KIND, + /** Same value as `fi.span.kind`; the Python fi_instrumentation key the collector also reads. */ + GEN_AI_SPAN_KIND: "gen_ai.span.kind", + SESSION_ID: SemanticConventions.SESSION_ID, + CONVERSATION_ID: SemanticConventions.GEN_AI_CONVERSATION_ID, + INPUT_VALUE: SemanticConventions.INPUT_VALUE, + INPUT_MIME_TYPE: SemanticConventions.INPUT_MIME_TYPE, + OUTPUT_VALUE: SemanticConventions.OUTPUT_VALUE, + OUTPUT_MIME_TYPE: SemanticConventions.OUTPUT_MIME_TYPE, + MODEL_NAME: SemanticConventions.LLM_MODEL_NAME, + PROVIDER: SemanticConventions.LLM_PROVIDER, + TOOL_NAME: SemanticConventions.TOOL_NAME, + GEN_AI_TOOL_NAME: "gen_ai.tool.name", + TOOL_CALL_ID: "gen_ai.tool.call.id", + AGENT_NAME: "gen_ai.agent.name", + INPUT_TOKENS: SemanticConventions.LLM_TOKEN_COUNT_PROMPT, + OUTPUT_TOKENS: SemanticConventions.LLM_TOKEN_COUNT_COMPLETION, + TOTAL_TOKENS: SemanticConventions.LLM_TOKEN_COUNT_TOTAL, + CACHE_READ_TOKENS: SemanticConventions.LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_READ, + CACHE_WRITE_TOKENS: SemanticConventions.LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_WRITE, + REASONING_TOKENS: SemanticConventions.LLM_TOKEN_COUNT_COMPLETION_DETAILS_REASONING, +} as const; + +export const AGENT_NAME = "cursor"; +/** All inference goes through Cursor's hosted models, local or cloud runtime. */ +export const PROVIDER_NAME = "cursor"; diff --git a/typescript/packages/traceai_cursor_sdk/src/index.ts b/typescript/packages/traceai_cursor_sdk/src/index.ts new file mode 100644 index 000000000..e2d4b072e --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/src/index.ts @@ -0,0 +1,21 @@ +export { + CursorSDKInstrumentation, + INSTRUMENTATION_NAME, + instrumentCursorSDK, + resolveContentPolicy, + shutdown, +} from "./instrumentation"; +export type { CursorSDKInstrumentationConfig } from "./instrumentation"; +export { isPatched } from "./wrappers"; +export type { ContentPolicy } from "./spans"; +export { AGENT_NAME, CursorAttributes, PROVIDER_NAME, SpanNames, StandardAttributes } from "./attributes"; +export type { + AgentClassLike, + AgentLike, + CursorSDKModuleLike, + RunLike, + RunResultLike, + SDKMessageLike, + TokenUsageLike, +} from "./types"; +export { VERSION } from "./version"; diff --git a/typescript/packages/traceai_cursor_sdk/src/instrumentation.ts b/typescript/packages/traceai_cursor_sdk/src/instrumentation.ts new file mode 100644 index 000000000..e6d941190 --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/src/instrumentation.ts @@ -0,0 +1,275 @@ +/** + * Public entry points: an OpenTelemetry instrumentation that patches the + * `@cursor/sdk` `Agent` class (automatically for `require("@cursor/sdk")`, + * or through `manuallyInstrument()`), plus `forceFlush()` / `shutdown()` to + * close and flush spans before a short script exits. + */ +import { TracerProvider, diag, trace } from "@opentelemetry/api"; +import { + InstrumentationBase, + InstrumentationConfig, + InstrumentationNodeModuleDefinition, +} from "@opentelemetry/instrumentation"; +import { FITracer, TraceConfigOptions } from "@traceai/fi-core"; +import { ContentPolicy } from "./spans"; +import { AgentClassLike, CursorSDKModuleLike } from "./types"; +import { VERSION } from "./version"; +import { RunWatcher, TracingContext, isPatched, patchAgentClass, wrapAgent } from "./wrappers"; + +export const INSTRUMENTATION_NAME = "@traceai/cursor-sdk"; +const MODULE_NAME = "@cursor/sdk"; +const SUPPORTED_VERSIONS = [">=1.0.0 <2"]; +const DEFAULT_GRACE_MS = 2000; +const DEFAULT_DRAIN_MS = 30_000; + +/** + * fi-core env keys. Read fail-closed, unlike fi-core (`value.toLowerCase() === + * "true"`): only an explicit `false` (trimmed, any case) opts in to content. + */ +const FI_HIDE_INPUTS = "FI_HIDE_INPUTS"; +const FI_HIDE_OUTPUTS = "FI_HIDE_OUTPUTS"; + +export interface CursorSDKInstrumentationConfig { + /** OpenTelemetry instrumentation options (`enabled`...). */ + instrumentationConfig?: InstrumentationConfig; + /** Provider to create spans with. Defaults to the global provider. */ + tracerProvider?: TracerProvider; + /** + * fi-core trace config. Unlike fi-core, `hideInputs` and `hideOutputs` + * default to `true` here: prompts, tool arguments (shell commands, file + * paths, edits), tool results (file contents, command output), thinking and + * assistant text of a coding agent carry source code and secrets. Opt in + * with `false`, or with `FI_HIDE_INPUTS=false` / `FI_HIDE_OUTPUTS=false`. + */ + traceConfig?: TraceConfigOptions; + /** + * Milliseconds a run span waits, after the run's end was signalled without a + * `RunResult`, for `run.wait()` or a terminal status before it closes. + * Default 2000. `forceFlush()` / `shutdown()` close waiting runs at once. + */ + runEndGraceMs?: number; + /** + * Milliseconds a run span stays open, after the run's end is known, for a + * `run.stream()` that is still being read (or was read partly and never + * closed). Default 30000. Open tool spans then end as incomplete. + */ + streamDrainTimeoutMs?: number; +} + +function nonNegative(value: unknown, fallback: number): number { + return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : fallback; +} + +/** `false` only for an explicit `false`; any other value (or none) keeps content hidden. */ +function envHide(key: string): boolean { + const value = typeof process !== "undefined" ? process.env?.[key] : undefined; + return !(typeof value === "string" && value.trim().toLowerCase() === "false"); +} + +/** Precedence: explicit option > fi-core env var > this package's default (hidden). */ +export function resolveContentPolicy(traceConfig?: TraceConfigOptions): ContentPolicy { + return { + hideInputs: traceConfig?.hideInputs ?? envHide(FI_HIDE_INPUTS), + hideOutputs: traceConfig?.hideOutputs ?? envHide(FI_HIDE_OUTPUTS), + }; +} + +/** Instrumentations created in this process, so `shutdown()` can close their waiting runs. */ +const instances = new Set>(); + +/** + * Traces `@cursor/sdk` agent runs. + * + * ```ts + * import * as CursorSDK from "@cursor/sdk"; + * const instrumentation = new CursorSDKInstrumentation({ tracerProvider }); + * instrumentation.manuallyInstrument(CursorSDK); + * const agent = await CursorSDK.Agent.create({ model: { id: "composer-2.5" }, local: { cwd } }); + * const run = await agent.send("..."); // one "Cursor Agent run" span + * for await (const event of run.stream()) {} // tool / thinking / assistant child spans + * ``` + * + * `require("@cursor/sdk")` after `registerInstrumentations()` is patched + * automatically. ESM imports need `manuallyInstrument()` (or an + * import-in-the-middle loader). + */ +export class CursorSDKInstrumentation extends InstrumentationBase { + private readonly traceConfig?: TraceConfigOptions; + private readonly graceMs: number; + private readonly drainMs: number; + /** Set by `unpatch()`: agents created earlier pass through untraced. */ + private stopped = false; + private readonly registry = new Set(); + private readonly undo = new Map void>(); + private providerForFlush?: TracerProvider; + + constructor(config: CursorSDKInstrumentationConfig = {}) { + super(INSTRUMENTATION_NAME, VERSION, Object.assign({}, config.instrumentationConfig)); + this.traceConfig = config.traceConfig; + this.graceMs = nonNegative(config.runEndGraceMs, DEFAULT_GRACE_MS); + this.drainMs = nonNegative(config.streamDrainTimeoutMs, DEFAULT_DRAIN_MS); + if (config.tracerProvider) this.setTracerProvider(config.tracerProvider); + instances.add(new WeakRef(this)); + } + + override setTracerProvider(tracerProvider: TracerProvider): void { + super.setTracerProvider(tracerProvider); + this.providerForFlush = tracerProvider; + } + + /** The content policy this instrumentation applies. */ + get contentPolicy(): ContentPolicy { + return resolveContentPolicy(this.traceConfig); + } + + protected init() { + return new InstrumentationNodeModuleDefinition( + MODULE_NAME, + SUPPORTED_VERSIONS, + (moduleExports: CursorSDKModuleLike) => { + this.patchModule(moduleExports); + return moduleExports; + }, + (moduleExports: CursorSDKModuleLike) => { + this.unpatchModule(moduleExports); + }, + ); + } + + /** + * Patch the SDK's `Agent` class. Pass the module namespace + * (`import * as CursorSDK from "@cursor/sdk"`) or `{ Agent }`. Returns + * `true` when the class is patched after this call. + */ + manuallyInstrument(module: CursorSDKModuleLike): boolean { + return this.patchModule(module); + } + + /** Trace one existing `SDKAgent` (from any source). Returns the same instance. */ + wrapAgent(agent: T): T { + this.stopped = false; + return wrapAgent(agent, () => this.tracingContext()); + } + + /** + * Remove the class patches this instrumentation applied. Agents created + * before this call stop tracing too (their wrapped `send()` passes straight + * through) until `manuallyInstrument()` or `wrapAgent()` is called again. + */ + unpatch(): void { + this.stopped = true; + for (const [target, undo] of this.undo) { + this.undo.delete(target); + try { + undo(); + } catch (error) { + diag.debug(`${INSTRUMENTATION_NAME}: unpatch failed: ${error}`); + } + } + } + + override disable(): void { + super.disable(); + this.closeRuns(false); + } + + /** + * Close runs whose end is already known but whose span is still open + * (waiting for `wait()` / a terminal status, or for a stream that is still + * being read), then flush the provider's span processors. Does not shut + * the provider down. + */ + async forceFlush(): Promise { + this.closeRuns(false); + await flushProvider(this.providerForFlush ?? trace.getTracerProvider()); + } + + /** `all`: also close runs still in progress (process exit). */ + private closeRuns(all: boolean): void { + // disable() can run inside the base constructor, before fields exist. + if (!this.registry) return; + for (const watcher of [...this.registry]) { + if (all || watcher.inGrace || watcher.outcomeKnown) watcher.flush(); + } + } + + private patchModule(module: CursorSDKModuleLike): boolean { + const AgentClass = module?.Agent as AgentClassLike | undefined; + if (!AgentClass || typeof AgentClass.create !== "function") { + diag.warn(`${INSTRUMENTATION_NAME}: expected the @cursor/sdk module (no Agent.create found); nothing patched`); + return false; + } + this.stopped = false; + if (isPatched(AgentClass)) return true; + const undo = patchAgentClass(AgentClass, () => this.tracingContext()); + if (undo) this.undo.set(AgentClass, undo); + return !!undo; + } + + private unpatchModule(module: CursorSDKModuleLike): void { + const AgentClass = module?.Agent as object | undefined; + const undo = AgentClass ? this.undo.get(AgentClass) : undefined; + if (!AgentClass || !undo) return; + this.undo.delete(AgentClass); + undo(); + } + + private tracingContext(): TracingContext | undefined { + if (!this.isEnabled() || this.stopped) return undefined; + const policy = this.contentPolicy; + const tracer = new FITracer({ + tracer: this.tracer, + traceConfig: { ...this.traceConfig, hideInputs: policy.hideInputs, hideOutputs: policy.hideOutputs }, + }); + return { tracer, policy, graceMs: this.graceMs, drainMs: this.drainMs, registry: this.registry }; + } +} + +/** Python-style convenience constructor: create, then `manuallyInstrument(module)`. */ +export function instrumentCursorSDK( + module: CursorSDKModuleLike, + config: CursorSDKInstrumentationConfig = {}, +): CursorSDKInstrumentation { + const instrumentation = new CursorSDKInstrumentation(config); + instrumentation.manuallyInstrument(module); + return instrumentation; +} + +/** + * Before a short script exits: close every open run span of every + * instrumentation in this process (a run still in progress closes with + * `cursor.run.status=running` and no status), then flush the provider. + * Export errors are logged, never thrown: export failure does not fail the agent. + */ +export async function shutdown(tracerProvider?: TracerProvider): Promise { + for (const ref of [...instances]) { + const instrumentation = ref.deref(); + if (!instrumentation) { + instances.delete(ref); + continue; + } + (instrumentation as unknown as { closeRuns(all: boolean): void }).closeRuns(true); + } + await flushProvider(tracerProvider ?? trace.getTracerProvider()); +} + +function resolveDelegate(provider: TracerProvider): TracerProvider { + const maybeProxy = provider as TracerProvider & { + getDelegate?: () => TracerProvider; + forceFlush?: () => Promise; + }; + if (typeof maybeProxy.forceFlush !== "function" && typeof maybeProxy.getDelegate === "function") { + return maybeProxy.getDelegate(); + } + return provider; +} + +async function flushProvider(provider: TracerProvider): Promise { + const target = resolveDelegate(provider) as TracerProvider & { forceFlush?: () => Promise }; + if (typeof target.forceFlush !== "function") return; + try { + await target.forceFlush(); + } catch (error) { + diag.warn(`${INSTRUMENTATION_NAME}: forceFlush failed: ${error}`); + } +} diff --git a/typescript/packages/traceai_cursor_sdk/src/spans.ts b/typescript/packages/traceai_cursor_sdk/src/spans.ts new file mode 100644 index 000000000..2dd6101ba --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/src/spans.ts @@ -0,0 +1,847 @@ +/** + * Span model for one Cursor SDK run (one `agent.send()`, including the run + * inside `Agent.prompt()`). + * + * Cursor Agent run (AGENT) session.id = agent id, model, usage, status + * ├─ Cursor thinking (CHAIN) one per thinking block (deltas joined) + * ├─ Cursor assistant message (LLM) one per run of consecutive text deltas + * └─ Cursor tool: (TOOL) one per tool_call call_id, running -> completed | error + * + * The local runtime streams `assistant` and `thinking` events as deltas + * (`text-delta`, `thinking-delta`; `thinking-completed` carries + * `thinking_duration_ms` with empty text) and emits `tool_call` events at + * start, on partial updates and at completion. This class joins them back + * into one span per logical step. + * + * Every public method swallows its own errors: tracing never fails the agent. + */ +import { Attributes, Context, HrTime, Span, SpanKind, SpanStatusCode, Tracer, diag, trace } from "@opentelemetry/api"; +import { getAttributesFromContext } from "@traceai/fi-core"; +import { MimeType } from "@traceai/fi-semantic-conventions"; +import { + AGENT_NAME, + CursorAttributes as C, + PROVIDER_NAME, + SpanNames, + StandardAttributes as S, +} from "./attributes"; +import { + AgentLike, + ModelSelectionLike, + RunLike, + RunResultLike, + SDKMessageLike, + SendOptionsLike, + TokenUsageLike, + UserMessageLike, +} from "./types"; + +/** Which content the wrapper may copy onto spans. Both default to hidden. */ +export interface ContentPolicy { + /** Drop prompts and tool arguments. */ + hideInputs: boolean; + /** Drop assistant text, thinking text, task summaries and tool results. */ + hideOutputs: boolean; +} + +/** + * Error text is content: messages, stack traces and Cursor's run-error text + * can carry local paths, usernames and prompt fragments. Unless both inputs + * and outputs are opted in, errors are exported as their class name and + * structural fields only. + */ +export function redactsErrors(policy: ContentPolicy): boolean { + return policy.hideInputs || policy.hideOutputs; +} + +/** How a run ended, as far as the wrapper could observe it. */ +export type FinishOutcome = + /** `run.wait()` (or `Agent.prompt()`) resolved with a `RunResult`. */ + | { kind: "result"; result: RunResultLike } + /** The run handle reached a terminal status, or its stream ended cleanly. */ + | { kind: "status" } + /** `send()`, `stream()` or `wait()` threw. */ + | { kind: "error"; error: unknown } + /** The consumer stopped reading and the run's end cannot be observed. */ + | { kind: "detached" }; + +const CONTENT_MAX = 5000; +const ERROR_MESSAGE_MAX = 500; +const LOG = "@traceai/cursor-sdk"; +const TERMINAL = new Set(["finished", "error", "cancelled"]); +/** `status` stream event -> run status. */ +const STATUS_EVENT_TO_RUN: Record = { + FINISHED: "finished", + ERROR: "error", + CANCELLED: "cancelled", + EXPIRED: "error", +}; + +/** + * One clock for every start and end time the wrapper sets. OTel falls back to + * millisecond `Date.now()` for the end of a span whose start time was given, + * so mixing explicit and implicit times can order a child after its parent. + */ +export function clockMs(): number { + const perf = (globalThis as { performance?: { now?: () => number; timeOrigin?: number } }).performance; + if (perf && typeof perf.now === "function" && typeof perf.timeOrigin === "number") { + return perf.timeOrigin + perf.now(); + } + return Date.now(); +} + +export function toHrTime(ms: number): HrTime { + const seconds = Math.floor(ms / 1000); + const nanos = Math.round((ms - seconds * 1000) * 1e6); + return nanos >= 1e9 ? [seconds + 1, nanos - 1e9] : [seconds, nanos]; +} + +export function truncate(value: string, max: number): string { + return value.length > max ? `${value.slice(0, max)}...[truncated]` : value; +} + +export function safeJson(value: unknown, max = CONTENT_MAX): string { + try { + const text = typeof value === "string" ? value : JSON.stringify(value); + return truncate(text ?? String(value), max); + } catch { + return truncate(String(value), max); + } +} + +export function isTerminalStatus(status: unknown): boolean { + return typeof status === "string" && TERMINAL.has(status); +} + +/** Terminal run status implied by a `status` stream event, if any. */ +export function statusFromEvent(status: unknown): string | undefined { + return typeof status === "string" ? STATUS_EVENT_TO_RUN[status] : undefined; +} + +/** Prompt text and image count of an `agent.send()` message. */ +export function normalizeMessage(message: unknown): { prompt: string; images: number } { + if (typeof message === "string") return { prompt: message, images: 0 }; + if (message && typeof message === "object") { + const m = message as UserMessageLike; + return { + prompt: typeof m.text === "string" ? m.text : "", + images: Array.isArray(m.images) ? m.images.length : 0, + }; + } + return { prompt: "", images: 0 }; +} + +function finite(value: unknown): number | undefined { + return typeof value === "number" && Number.isFinite(value) ? value : undefined; +} + +function modelId(model: ModelSelectionLike | undefined): string | undefined { + return model && typeof model === "object" && typeof model.id === "string" && model.id ? model.id : undefined; +} + +function hasUsage(usage: TokenUsageLike | undefined): usage is TokenUsageLike { + if (!usage || typeof usage !== "object") return false; + return [usage.inputTokens, usage.outputTokens, usage.totalTokens, usage.cacheReadTokens, usage.cacheWriteTokens].some( + (v) => finite(v) !== undefined, + ); +} + +const USAGE_KEYS = ["inputTokens", "outputTokens", "cacheReadTokens", "cacheWriteTokens", "totalTokens", "reasoningTokens"] as const; + +function addUsage(sum: TokenUsageLike, usage: TokenUsageLike): void { + for (const key of USAGE_KEYS) { + const value = finite(usage[key]); + if (value !== undefined) sum[key] = (sum[key] ?? 0) + value; + } +} + +/** Fields of `CursorSdkError` (name, code, HTTP status, retryable, operation). Never content. */ +export function sdkErrorAttributes(error: unknown): Attributes { + const attributes: Attributes = {}; + if (!error || typeof error !== "object") return attributes; + const e = error as { name?: unknown; code?: unknown; status?: unknown; isRetryable?: unknown; operation?: unknown }; + attributes[C.ERROR_NAME] = errorName(error); + if (typeof e.code === "string" && e.code) attributes[C.ERROR_CODE] = e.code; + if (finite(e.status) !== undefined) attributes[C.ERROR_STATUS] = e.status as number; + if (typeof e.isRetryable === "boolean") attributes[C.ERROR_RETRYABLE] = e.isRetryable; + if (typeof e.operation === "string" && e.operation) attributes[C.ERROR_OPERATION] = e.operation; + return attributes; +} + +export function errorMessage(error: unknown): string { + if (error instanceof Error) return error.message; + if (error && typeof error === "object" && typeof (error as { message?: unknown }).message === "string") { + return (error as { message: string }).message; + } + return typeof error === "string" ? error : safeJson(error, ERROR_MESSAGE_MAX); +} + +/** `bc-` ids are cloud agents (the SDK routes on this prefix); everything else is local. */ +export function runtimeOf(agentId: string | undefined): "cloud" | "local" | undefined { + if (!agentId) return undefined; + return agentId.startsWith("bc-") ? "cloud" : "local"; +} + +/** The error's class name (`error.name`, else the constructor's name). */ +export function errorName(error: unknown): string { + if (error && typeof error === "object") { + const name = (error as { name?: unknown }).name; + if (typeof name === "string" && name && name !== "Error") return name; + const ctor = (error as { constructor?: { name?: unknown } }).constructor?.name; + if (typeof ctor === "string" && ctor.length > 1 && ctor !== "Object") return ctor; + if (typeof name === "string" && name) return name; + } + return "Error"; +} + +/** Fixed, content-free summary: ` ()`, e.g. `AuthenticationError (401)`. */ +export function errorSummary(error: unknown): string { + const name = errorName(error); + const e = (error && typeof error === "object" ? error : {}) as { status?: unknown; code?: unknown }; + const detail = finite(e.status) !== undefined ? String(e.status) : typeof e.code === "string" && e.code ? e.code : undefined; + return detail ? `${name} (${detail})` : name; +} + +/** Status / `cursor.error.message` text for a thrown error under the policy. */ +function thrownErrorMessage(error: unknown, policy: ContentPolicy): string { + return redactsErrors(policy) ? errorSummary(error) : truncate(errorMessage(error), ERROR_MESSAGE_MAX); +} + +/** + * Record the exception event. Redacted: only `exception.type` (the class + * name), no message and no stack trace. Opted in: the full error. + */ +function recordError(span: Span, error: unknown, policy: ContentPolicy): void { + if (redactsErrors(policy)) { + span.recordException({ name: errorName(error) }); + } else if (error instanceof Error) { + span.recordException(error); + } else { + span.recordException({ name: errorName(error), message: errorMessage(error) }); + } +} + +export function safeContextAttributes(ctx: Context): Attributes { + try { + return getAttributesFromContext(ctx); + } catch { + return {}; + } +} + +interface ToolState { + span: Span; + name: string; + last: SDKMessageLike; +} + +interface TextBlockState { + startMs: number; + lastMs: number; + parts: string[]; + length: number; + toolUses: number; +} + +export interface RunTracerArgs { + tracer: Tracer; + policy: ContentPolicy; + parentContext: Context; + agent?: AgentLike; + message?: unknown; + sendOptions?: SendOptionsLike; + startTimeMs?: number; +} + +export class RunTracer { + private readonly tracer: Tracer; + private readonly policy: ContentPolicy; + private readonly startTimeMs: number; + private readonly appSetSession: boolean; + + private readonly span: Span; + private readonly runContext: Context; + private finished = false; + private agentId?: string; + private runId?: string; + private modelName?: string; + private lastEventMs: number; + private lastStatusEvent?: string; + private lastStatusMessage?: string; + private readonly tools = new Map(); + private readonly endedToolIds = new Set(); + private anonymousTools = 0; + private assistant?: TextBlockState; + private thinking?: TextBlockState; + private readonly assistantText: string[] = []; + private readonly usageSum: TokenUsageLike = {}; + private usageEvents = 0; + + constructor(args: RunTracerArgs) { + this.tracer = args.tracer; + this.policy = args.policy; + this.startTimeMs = args.startTimeMs ?? clockMs(); + this.lastEventMs = this.startTimeMs; + const contextAttributes = safeContextAttributes(args.parentContext); + this.appSetSession = contextAttributes[S.SESSION_ID] != null; + + this.span = this.tracer.startSpan( + SpanNames.RUN, + { kind: SpanKind.INTERNAL, startTime: toHrTime(this.startTimeMs) }, + args.parentContext, + ); + this.runContext = trace.setSpan(args.parentContext, this.span); + try { + this.span.setAttributes(contextAttributes); + this.span.setAttributes(this.startAttributes(args)); + } catch (error) { + diag.debug(`${LOG}: failed to set run attributes: ${error}`); + } + } + + get isFinished(): boolean { + return this.finished; + } + + /** The terminal run status the stream announced (`status` event), if any. */ + get statusFromStream(): string | undefined { + return statusFromEvent(this.lastStatusEvent); + } + + /** Copy ids and model from the `Run` handle `send()` resolved with. */ + attachRun(run: RunLike): void { + if (this.finished || !run || typeof run !== "object") return; + try { + const attributes: Attributes = {}; + if (typeof run.id === "string" && run.id) { + this.runId = run.id; + attributes[C.RUN_ID] = run.id; + } + if (typeof run.requestId === "string" && run.requestId) attributes[C.REQUEST_ID] = run.requestId; + this.span.setAttributes(attributes); + if (typeof run.agentId === "string" && run.agentId) this.setAgentId(run.agentId); + this.setModel(run.model); + } catch (error) { + diag.debug(`${LOG}: failed to attach run: ${error}`); + } + } + + /** Record one stream event. Never throws and never mutates the event. */ + onEvent(event: unknown): void { + if (this.finished || !event || typeof event !== "object") return; + try { + const nowMs = clockMs(); + const e = event as SDKMessageLike; + if (typeof e.agent_id === "string" && e.agent_id && e.agent_id !== this.agentId) this.setAgentId(e.agent_id); + if (typeof e.run_id === "string" && e.run_id && !this.runId) { + this.runId = e.run_id; + this.span.setAttribute(C.RUN_ID, e.run_id); + } + if (e.type !== "assistant") this.closeAssistant(); + switch (e.type) { + case "system": + this.onSystem(e); + break; + case "assistant": + this.onAssistant(e, nowMs); + break; + case "thinking": + this.onThinking(e, nowMs); + break; + case "tool_call": + this.onToolCall(e, nowMs); + break; + case "usage": + if (e.usage && typeof e.usage === "object") { + addUsage(this.usageSum, e.usage); + this.usageEvents += 1; + } + break; + case "status": + if (typeof e.status === "string") { + this.lastStatusEvent = e.status; + this.span.addEvent("cursor.status", { [C.LAST_STATUS_EVENT]: e.status }, toHrTime(nowMs)); + // Cursor's run-error text: exported only when error text is opted in (see finish()). + if (typeof e.message === "string" && e.message) { + this.lastStatusMessage = truncate(e.message, ERROR_MESSAGE_MAX); + } + } + break; + case "request": + if (typeof e.request_id === "string" && e.request_id) this.span.setAttribute(C.REQUEST_ID, e.request_id); + break; + case "task": { + const attributes: Attributes = {}; + if (typeof e.status === "string") attributes["cursor.task.status"] = e.status; + if (typeof e.text === "string" && !this.policy.hideOutputs) { + attributes["cursor.task.text"] = truncate(e.text, CONTENT_MAX); + } + this.span.addEvent("cursor.task", attributes, toHrTime(nowMs)); + break; + } + default: + break; + } + this.lastEventMs = nowMs; + } catch (error) { + diag.debug(`${LOG}: failed to record event: ${error}`); + } + } + + /** + * The consumer stopped iterating `run.stream()` before it ended. Later + * events of this run are not seen, so open child spans end now, marked + * incomplete. The run span stays open until the run's end is observed. + */ + detach(): void { + if (this.finished) return; + try { + const endMs = clockMs(); + this.closeAssistant(); + this.closeThinking(endMs); + for (const [id, state] of this.tools) { + this.tools.delete(id); + this.endedToolIds.add(id); + this.applyToolAttributes(state.span, state.last); + state.span.setAttribute(C.TOOL_INCOMPLETE, true); + state.span.end(toHrTime(endMs)); + } + this.span.setAttribute(C.RUN_STREAM_DETACHED, true); + } catch (error) { + diag.debug(`${LOG}: failed to detach: ${error}`); + } + } + + /** End every open span for this run. Idempotent. */ + finish(outcome: FinishOutcome, run?: RunLike): void { + if (this.finished) return; + this.finished = true; + const span = this.span; + try { + const endMs = Math.max(clockMs(), this.lastEventMs); + this.closeAssistant(); + this.closeThinking(endMs); + + const result = outcome.kind === "result" && outcome.result && typeof outcome.result === "object" ? outcome.result : undefined; + const handle = run && typeof run === "object" ? run : undefined; + const read = (key: K): RunResultLike[K] | undefined => { + const fromResult = result?.[key]; + if (fromResult !== undefined) return fromResult; + try { + return handle?.[key as keyof RunLike] as RunResultLike[K] | undefined; + } catch { + return undefined; + } + }; + + const handleStatus = read("status"); + let status: string | undefined = isTerminalStatus(handleStatus) ? handleStatus : this.statusFromStream; + // A stream that ended cleanly ended with its run. + if (!isTerminalStatus(status) && outcome.kind === "status") status = "finished"; + if (outcome.kind === "error") status = "error"; + // Detached before the end: keep what the handle says ("running"), status stays UNSET. + if (!status && typeof handleStatus === "string") status = handleStatus; + + const attributes: Attributes = {}; + if (typeof status === "string") attributes[C.RUN_STATUS] = status; + if (this.lastStatusEvent) attributes[C.LAST_STATUS_EVENT] = this.lastStatusEvent; + const id = read("id"); + if (typeof id === "string" && id && !this.runId) attributes[C.RUN_ID] = id; + const requestId = read("requestId"); + if (typeof requestId === "string" && requestId) attributes[C.REQUEST_ID] = requestId; + const durationMs = finite(read("durationMs")); + if (durationMs !== undefined) attributes[C.RUN_DURATION_MS] = durationMs; + this.setModel(read("model")); + Object.assign(attributes, this.usageAttributes(read("usage"))); + + const output = read("result"); + const text = typeof output === "string" && output ? output : this.assistantText.join(""); + if (text && !this.policy.hideOutputs) { + attributes[S.OUTPUT_VALUE] = truncate(text, CONTENT_MAX); + attributes[S.OUTPUT_MIME_TYPE] = MimeType.TEXT; + } + + const failed = status === "error"; + const cancelled = status === "cancelled"; + for (const [toolId, state] of this.tools) { + this.tools.delete(toolId); + this.endedToolIds.add(toolId); + this.applyToolAttributes(state.span, state.last); + state.span.setAttribute(C.TOOL_INCOMPLETE, true); + if (cancelled) state.span.setStatus({ code: SpanStatusCode.ERROR, message: "cancelled" }); + else if (failed) state.span.setStatus({ code: SpanStatusCode.ERROR, message: "tool not completed (run failed)" }); + state.span.end(toHrTime(endMs)); + } + + span.setAttributes(attributes); + if (outcome.kind === "error") { + const message = thrownErrorMessage(outcome.error, this.policy); + span.setAttributes({ ...sdkErrorAttributes(outcome.error), [C.ERROR_MESSAGE]: message }); + recordError(span, outcome.error, this.policy); + span.setStatus({ code: SpanStatusCode.ERROR, message }); + } else if (cancelled) { + span.setAttribute(C.RUN_CANCELLED, true); + span.setStatus({ code: SpanStatusCode.ERROR, message: "cancelled" }); + } else if (failed) { + const runError = read("error"); + const code = runError && typeof runError.code === "string" ? runError.code : undefined; + if (code) span.setAttribute(C.RUN_ERROR_CODE, code); + const raw = runError && typeof runError.message === "string" && runError.message ? runError.message : this.lastStatusMessage; + // Cursor's run-error text can quote paths or prompt text: a fixed summary unless opted in. + const message = redactsErrors(this.policy) + ? code + ? `RunError (${code})` + : "RunError" + : truncate(raw ?? "run failed", ERROR_MESSAGE_MAX); + span.setAttribute(C.ERROR_MESSAGE, message); + span.setStatus({ code: SpanStatusCode.ERROR, message }); + } else if (status === "finished") { + span.setStatus({ code: SpanStatusCode.OK }); + } + span.end(toHrTime(endMs)); + } catch (error) { + diag.debug(`${LOG}: failed to finish run: ${error}`); + try { + span.end(); + } catch { + /* already ended */ + } + } + } + + private startAttributes(args: RunTracerArgs): Attributes { + const attributes: Attributes = { + [S.FI_SPAN_KIND]: "AGENT", + [S.GEN_AI_SPAN_KIND]: "AGENT", + [S.AGENT_NAME]: AGENT_NAME, + [S.PROVIDER]: PROVIDER_NAME, + }; + const options = args.sendOptions && typeof args.sendOptions === "object" ? args.sendOptions : undefined; + if (typeof options?.mode === "string") attributes[C.SEND_MODE] = options.mode; + let agentModel: ModelSelectionLike | undefined; + let agentId: string | undefined; + try { + agentModel = args.agent?.model; + agentId = args.agent?.agentId; + } catch { + /* getters that throw are ignored */ + } + const model = modelId(options?.model) ? options?.model : agentModel; + const id = modelId(model); + if (id) { + this.modelName = id; + attributes[S.MODEL_NAME] = id; + if (Array.isArray(model?.params) && model.params.length) attributes[C.MODEL_PARAMS] = safeJson(model.params, 1000); + } + const { prompt, images } = normalizeMessage(args.message); + attributes[C.INPUT_LENGTH] = prompt.length; + if (images > 0) attributes[C.INPUT_IMAGE_COUNT] = images; + if (!this.policy.hideInputs) { + attributes[S.INPUT_VALUE] = truncate(prompt, CONTENT_MAX); + attributes[S.INPUT_MIME_TYPE] = MimeType.TEXT; + } + if (typeof agentId === "string" && agentId) { + this.agentId = agentId; + Object.assign(attributes, this.agentAttributes(agentId)); + } + return attributes; + } + + private agentAttributes(agentId: string): Attributes { + const attributes: Attributes = { [C.AGENT_ID]: agentId, [S.CONVERSATION_ID]: agentId }; + const runtime = runtimeOf(agentId); + if (runtime) attributes[C.RUNTIME] = runtime; + // An app that set session.id through fi-core context keeps it. + if (!this.appSetSession) attributes[S.SESSION_ID] = agentId; + return attributes; + } + + private setAgentId(agentId: string): void { + this.agentId = agentId; + this.span.setAttributes(this.agentAttributes(agentId)); + } + + private setModel(model: ModelSelectionLike | undefined): void { + const id = modelId(model); + if (!id || id === this.modelName) return; + this.modelName = id; + this.span.setAttribute(S.MODEL_NAME, id); + if (Array.isArray(model?.params) && model.params.length) this.span.setAttribute(C.MODEL_PARAMS, safeJson(model.params, 1000)); + } + + private childAttributes(kind: string): Attributes { + const attributes: Attributes = { [S.FI_SPAN_KIND]: kind, [S.GEN_AI_SPAN_KIND]: kind }; + if (this.agentId) { + attributes[C.AGENT_ID] = this.agentId; + if (!this.appSetSession) attributes[S.SESSION_ID] = this.agentId; + } + if (this.runId) attributes[C.RUN_ID] = this.runId; + return attributes; + } + + private onSystem(e: SDKMessageLike): void { + this.setModel(e.model); + if (Array.isArray(e.tools)) { + const tools = e.tools.filter((t): t is string => typeof t === "string"); + if (tools.length) this.span.setAttribute(C.TOOLS, tools); + } + } + + private onAssistant(e: SDKMessageLike, nowMs: number): void { + const body = e.message && typeof e.message === "object" ? e.message : undefined; + const content = Array.isArray(body?.content) ? body!.content : []; + let text = ""; + let toolUses = 0; + for (const block of content) { + if (!block || typeof block !== "object") continue; + if (block.type === "text" && typeof block.text === "string") text += block.text; + else if (block.type === "tool_use") toolUses += 1; + } + if (!this.assistant) { + this.assistant = { startMs: this.lastEventMs, lastMs: nowMs, parts: [], length: 0, toolUses: 0 }; + } + const block = this.assistant; + block.lastMs = nowMs; + block.toolUses += toolUses; + if (text) { + block.length += text.length; + if (!this.policy.hideOutputs) block.parts.push(text); + this.assistantText.push(text); + } + } + + /** End the open assistant text block, if any, as one LLM span. */ + private closeAssistant(): void { + const block = this.assistant; + if (!block) return; + this.assistant = undefined; + const attributes = this.childAttributes("LLM"); + attributes[S.PROVIDER] = PROVIDER_NAME; + if (this.modelName) attributes[S.MODEL_NAME] = this.modelName; + attributes[C.TEXT_LENGTH] = block.length; + if (block.toolUses) attributes[C.ASSISTANT_TOOL_USE_COUNT] = block.toolUses; + if (!this.policy.hideOutputs && block.parts.length) { + attributes[S.OUTPUT_VALUE] = truncate(block.parts.join(""), CONTENT_MAX); + attributes[S.OUTPUT_MIME_TYPE] = MimeType.TEXT; + } + const span = this.tracer.startSpan( + SpanNames.ASSISTANT_MESSAGE, + { kind: SpanKind.INTERNAL, startTime: toHrTime(block.startMs), attributes }, + this.runContext, + ); + span.setStatus({ code: SpanStatusCode.OK }); + span.end(toHrTime(block.lastMs)); + } + + private onThinking(e: SDKMessageLike, nowMs: number): void { + const text = typeof e.text === "string" ? e.text : ""; + const duration = finite(e.thinking_duration_ms); + if (!this.thinking && (text || duration !== undefined)) { + const startMs = !text && duration !== undefined ? Math.max(this.startTimeMs, nowMs - duration) : this.lastEventMs; + this.thinking = { startMs, lastMs: nowMs, parts: [], length: 0, toolUses: 0 }; + } + const block = this.thinking; + if (!block) return; + block.lastMs = nowMs; + if (text) { + block.length += text.length; + if (!this.policy.hideOutputs) block.parts.push(text); + } + // `thinking-completed` carries the duration (and empty text): the block is done. + if (duration !== undefined) this.closeThinking(nowMs, duration); + } + + private closeThinking(endMs: number, durationMs?: number): void { + const block = this.thinking; + if (!block) return; + this.thinking = undefined; + const attributes = this.childAttributes("CHAIN"); + attributes[C.TEXT_LENGTH] = block.length; + if (durationMs !== undefined) attributes[C.THINKING_DURATION_MS] = durationMs; + if (!this.policy.hideOutputs && block.parts.length) { + attributes[S.OUTPUT_VALUE] = truncate(block.parts.join(""), CONTENT_MAX); + attributes[S.OUTPUT_MIME_TYPE] = MimeType.TEXT; + } + const span = this.tracer.startSpan( + SpanNames.THINKING, + { kind: SpanKind.INTERNAL, startTime: toHrTime(block.startMs), attributes }, + this.runContext, + ); + span.setStatus({ code: SpanStatusCode.OK }); + span.end(toHrTime(Math.max(endMs, block.startMs))); + } + + private toolKey(e: SDKMessageLike): string { + if (typeof e.call_id === "string" && e.call_id) return e.call_id; + this.anonymousTools += 1; + return `__anonymous_${this.anonymousTools}`; + } + + private onToolCall(e: SDKMessageLike, nowMs: number): void { + const key = this.toolKey(e); + // A completion event repeated after the span ended (or after detach) is ignored. + if (this.endedToolIds.has(key)) return; + let state = this.tools.get(key); + if (!state) { + const startedEvent = e.status === "running" || e.status === undefined; + state = this.startTool(e, startedEvent ? nowMs : this.lastEventMs, startedEvent); + this.tools.set(key, state); + } + state.last = e; + if (e.status === "completed" || e.status === "error") { + this.tools.delete(key); + this.endedToolIds.add(key); + this.applyToolAttributes(state.span, e); + if (e.status === "error") { + // A tool's error result can carry tool output: only with outputs visible. + const message = + !this.policy.hideOutputs && e.result !== undefined ? truncate(safeJson(e.result), ERROR_MESSAGE_MAX) : `${state.name} failed`; + state.span.setStatus({ code: SpanStatusCode.ERROR, message }); + } else { + state.span.setStatus({ code: SpanStatusCode.OK }); + } + state.span.end(toHrTime(nowMs)); + } + } + + private startTool(e: SDKMessageLike, startMs: number, startedEvent: boolean): ToolState { + const name = typeof e.name === "string" && e.name ? e.name : "unknown"; + const attributes = this.childAttributes("TOOL"); + attributes[S.TOOL_NAME] = name; + attributes[S.GEN_AI_TOOL_NAME] = name; + attributes[C.TOOL_STARTED_EVENT] = startedEvent; + if (typeof e.call_id === "string" && e.call_id) { + attributes[C.TOOL_CALL_ID] = e.call_id; + attributes[S.TOOL_CALL_ID] = e.call_id; + } + const span = this.tracer.startSpan( + `${SpanNames.TOOL_PREFIX}${name}`, + { kind: SpanKind.INTERNAL, startTime: toHrTime(startMs), attributes }, + this.runContext, + ); + return { span, name, last: e }; + } + + /** Structural fields always; arguments and results only when the policy allows them. */ + private applyToolAttributes(span: Span, e: SDKMessageLike): void { + const attributes: Attributes = {}; + if (typeof e.status === "string") attributes[C.TOOL_STATUS] = e.status; + if (e.truncated && typeof e.truncated === "object") { + if (typeof e.truncated.args === "boolean") attributes[C.TOOL_ARGS_TRUNCATED] = e.truncated.args; + if (typeof e.truncated.result === "boolean") attributes[C.TOOL_RESULT_TRUNCATED] = e.truncated.result; + } + if (e.args !== undefined && !this.policy.hideInputs) { + attributes[S.INPUT_VALUE] = safeJson(e.args); + attributes[S.INPUT_MIME_TYPE] = typeof e.args === "string" ? MimeType.TEXT : MimeType.JSON; + } + if (e.result !== undefined && !this.policy.hideOutputs) { + attributes[S.OUTPUT_VALUE] = safeJson(e.result); + attributes[S.OUTPUT_MIME_TYPE] = typeof e.result === "string" ? MimeType.TEXT : MimeType.JSON; + } + span.setAttributes(attributes); + } + + /** + * Token counts: the run's cumulative usage from the SDK (`RunResult.usage` + * / `run.usage`) when present, else the sum of this run's `usage` events. + * Cursor's `inputTokens` excludes cache reads and writes (its `totalTokens` + * is input + output + cache read + cache write, without `reasoningTokens`, + * a subset of output), so the promoted input count adds them back, as the + * GenAI semantic conventions ask; `cursor.usage.*` keeps Cursor's numbers. + */ + private usageAttributes(runUsage: TokenUsageLike | undefined): Attributes { + let usage: TokenUsageLike | undefined; + let source: "run" | "events" | undefined; + if (hasUsage(runUsage)) { + usage = runUsage; + source = "run"; + } else if (this.usageEvents > 0 && hasUsage(this.usageSum)) { + usage = this.usageSum; + source = "events"; + } + const attributes: Attributes = {}; + if (!usage || !source) return attributes; + attributes[C.USAGE_SOURCE] = source; + const input = finite(usage.inputTokens); + const output = finite(usage.outputTokens); + const total = finite(usage.totalTokens); + const cacheRead = finite(usage.cacheReadTokens); + const cacheWrite = finite(usage.cacheWriteTokens); + const reasoning = finite(usage.reasoningTokens); + const promptTokens = input === undefined ? undefined : input + (cacheRead ?? 0) + (cacheWrite ?? 0); + if (input !== undefined) { + attributes[S.INPUT_TOKENS] = promptTokens; + attributes[C.USAGE_INPUT_TOKENS] = input; + } + if (output !== undefined) { + attributes[S.OUTPUT_TOKENS] = output; + attributes[C.USAGE_OUTPUT_TOKENS] = output; + } + if (total !== undefined) { + attributes[S.TOTAL_TOKENS] = total; + attributes[C.USAGE_TOTAL_TOKENS] = total; + } else if (promptTokens !== undefined && output !== undefined) { + attributes[S.TOTAL_TOKENS] = promptTokens + output; + } + if (cacheRead !== undefined) { + attributes[S.CACHE_READ_TOKENS] = cacheRead; + attributes[C.USAGE_CACHE_READ_TOKENS] = cacheRead; + } + if (cacheWrite !== undefined) { + attributes[S.CACHE_WRITE_TOKENS] = cacheWrite; + attributes[C.USAGE_CACHE_WRITE_TOKENS] = cacheWrite; + } + if (reasoning !== undefined) { + attributes[S.REASONING_TOKENS] = reasoning; + attributes[C.USAGE_REASONING_TOKENS] = reasoning; + } + return attributes; + } +} + +/** + * One ERROR span for an `Agent.create()` / `Agent.resume()` that threw (for + * example `AuthenticationError` for a bad API key). Successful calls emit no + * span: their agent id is on every later run span. + */ +export function recordFactoryError(args: { + tracer: Tracer; + policy: ContentPolicy; + name: string; + parentContext: Context; + startTimeMs: number; + error: unknown; + agentId?: string; + model?: ModelSelectionLike; + runtime?: "local" | "cloud"; +}): void { + try { + const contextAttributes = safeContextAttributes(args.parentContext); + const attributes: Attributes = { + ...contextAttributes, + [S.FI_SPAN_KIND]: "AGENT", + [S.GEN_AI_SPAN_KIND]: "AGENT", + [S.AGENT_NAME]: AGENT_NAME, + [S.PROVIDER]: PROVIDER_NAME, + }; + const model = modelId(args.model); + if (model) attributes[S.MODEL_NAME] = model; + if (args.runtime) attributes[C.RUNTIME] = args.runtime; + if (args.agentId) { + attributes[C.AGENT_ID] = args.agentId; + if (contextAttributes[S.SESSION_ID] == null) attributes[S.SESSION_ID] = args.agentId; + } + const message = thrownErrorMessage(args.error, args.policy); + Object.assign(attributes, sdkErrorAttributes(args.error), { [C.ERROR_MESSAGE]: message }); + const span = args.tracer.startSpan( + args.name, + { kind: SpanKind.INTERNAL, startTime: toHrTime(args.startTimeMs), attributes }, + args.parentContext, + ); + recordError(span, args.error, args.policy); + span.setStatus({ code: SpanStatusCode.ERROR, message }); + span.end(toHrTime(Math.max(clockMs(), args.startTimeMs))); + } catch (error) { + diag.debug(`${LOG}: failed to record ${args.name} error: ${error}`); + } +} diff --git a/typescript/packages/traceai_cursor_sdk/src/types.ts b/typescript/packages/traceai_cursor_sdk/src/types.ts new file mode 100644 index 000000000..2ade4a2b2 --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/src/types.ts @@ -0,0 +1,155 @@ +/** + * Structural copies of the `@cursor/sdk` types this package reads + * (dist/esm/*.d.ts of 1.0.37 and 1.0.38). The SDK is a peer dependency, so nothing here + * imports it: the package type-checks and runs whether or not it is installed. + * `contract/sdk_types.ts` checks that the real SDK types fit these shapes. + * + * Fields are optional or `unknown` because the wrapper must never throw on a + * shape a newer SDK adds. + */ + +/** `ModelSelection` (`options.d.ts`). */ +export interface ModelSelectionLike { + id?: string; + params?: Array<{ id?: string; value?: string }>; +} + +/** `SDKUserMessage`: the object form `agent.send()` accepts. */ +export interface UserMessageLike { + text?: string; + images?: unknown[]; +} + +/** `SendOptions` (`agent.d.ts`). Only the fields read here. */ +export interface SendOptionsLike { + model?: ModelSelectionLike; + mode?: string; + mcpServers?: Record; +} + +/** `AgentOptions` (`options.d.ts`). Only the fields read here; `apiKey` is never read. */ +export interface AgentOptionsLike { + model?: ModelSelectionLike; + name?: string; + mode?: string; + agentId?: string; + local?: { cwd?: string | string[] }; + cloud?: object; +} + +/** `TokenUsage` (`usage-types.d.ts`). */ +export interface TokenUsageLike { + inputTokens?: number; + outputTokens?: number; + cacheReadTokens?: number; + cacheWriteTokens?: number; + totalTokens?: number; + reasoningTokens?: number; +} + +/** `RunError` (`run.d.ts`). */ +export interface RunErrorLike { + message?: string; + code?: string; +} + +/** `RunResult` (`run.d.ts`), resolved by `run.wait()` and `Agent.prompt()`. */ +export interface RunResultLike { + id?: string; + requestId?: string; + status?: string; + result?: string; + error?: RunErrorLike; + model?: ModelSelectionLike; + durationMs?: number; + usage?: TokenUsageLike; +} + +/** `RunStatus`: "running" | "finished" | "error" | "cancelled". */ +export type RunStatusLike = string; + +/** `SDKMessage` (`messages.d.ts`), flattened: every member's fields, all optional. */ +export interface SDKMessageLike { + type?: string; + agent_id?: string; + run_id?: string; + /** system */ + subtype?: string; + model?: ModelSelectionLike; + tools?: string[]; + /** user, assistant: the message body; status: Cursor's diagnostic text. */ + message?: MessageBodyLike | string; + /** tool_call */ + call_id?: string; + name?: string; + status?: string; + args?: unknown; + result?: unknown; + truncated?: { args?: boolean; result?: boolean }; + /** thinking, task */ + text?: string; + thinking_duration_ms?: number; + /** request */ + request_id?: string; + /** usage */ + usage?: TokenUsageLike; +} + +/** `message` of `user` / `assistant` events. */ +export interface MessageBodyLike { + role?: string; + content?: Array; +} + +/** `TextBlock | ToolUseBlock`. */ +export interface ContentBlockLike { + type?: string; + text?: string; + id?: string; + name?: string; + input?: unknown; +} + +/** `Run` (`run.d.ts`). The wrapper patches `stream` and `wait` on the instance. */ +export interface RunLike { + readonly id?: string; + readonly requestId?: string; + readonly agentId?: string; + readonly status?: RunStatusLike; + readonly result?: string; + readonly error?: RunErrorLike; + readonly model?: ModelSelectionLike; + readonly durationMs?: number; + readonly usage?: TokenUsageLike; + stream?(): AsyncGenerator; + wait?(): Promise; + onDidChangeStatus?(listener: (status: RunStatusLike) => void): () => void; +} + +/** `SDKAgent` (`agent.d.ts`). The wrapper patches `send` on the instance. */ +export interface AgentLike { + readonly agentId?: string; + readonly model?: ModelSelectionLike; + send?(message: string | UserMessageLike, options?: SendOptionsLike): Promise; +} + +/** + * The `Agent` class (`stubs.d.ts`). Its static factories are the patch points: + * `create` and `resume` return an `SDKAgent`; `prompt` calls `Agent.create` + * (then `send` and `wait`) internally, so it is traced through them. + */ +export interface AgentClassLike { + create?(options: AgentOptionsLike): Promise; + resume?(agentId: string, options?: Partial): Promise; + prompt?(message: string, options?: AgentOptionsLike): Promise; +} + +/** + * The SDK module namespace (`import * as CursorSDK from "@cursor/sdk"`) or + * any object exposing the `Agent` class. Typed loosely on purpose: the SDK's + * `Agent` has a private constructor, so it is not assignable to a class type. + */ +export interface CursorSDKModuleLike { + // eslint-disable-next-line @typescript-eslint/ban-types + Agent?: Function | AgentClassLike; +} diff --git a/typescript/packages/traceai_cursor_sdk/src/version.ts b/typescript/packages/traceai_cursor_sdk/src/version.ts new file mode 100644 index 000000000..52c905c11 --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/src/version.ts @@ -0,0 +1 @@ +export const VERSION = "0.1.0"; diff --git a/typescript/packages/traceai_cursor_sdk/src/wrappers.ts b/typescript/packages/traceai_cursor_sdk/src/wrappers.ts new file mode 100644 index 000000000..d72dfa1ec --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/src/wrappers.ts @@ -0,0 +1,543 @@ +/** + * Patch points. + * + * - `Agent.create` / `Agent.resume` (static, writable on the SDK's `Agent` + * class): the returned `SDKAgent` instance gets a traced `send`; a factory + * that throws is recorded as one ERROR span. `Agent.prompt()` calls + * `Agent.create()` then `send()` and `wait()` (1.0.37, 1.0.38), so it is traced + * through those without a wrapper of its own. + * - `agent.send()` (instance): opens the run span and patches the returned + * `Run` instance's `stream()` and `wait()`, and subscribes to + * `onDidChangeStatus`. + * + * Nothing is wrapped in a Proxy: callers get the SDK's own agent and run + * objects back, and `run.stream()` yields the SDK's own event objects + * unchanged, forwarding `return()` / `throw()`. The local runtime's stream is a + * single-consumer queue, so the wrapper never reads it on its own: tool spans + * exist only for events the application reads through `run.stream()`. + */ +import { Context, Tracer, context as otelContext, diag } from "@opentelemetry/api"; +import { SpanNames } from "./attributes"; +import { + ContentPolicy, + RunTracer, + clockMs, + isTerminalStatus, + recordFactoryError, + runtimeOf, +} from "./spans"; +import { AgentClassLike, AgentLike, AgentOptionsLike, RunLike, RunResultLike, SDKMessageLike, SendOptionsLike } from "./types"; + +const PATCHED = Symbol.for("@traceai/cursor-sdk/patched"); +const LOG = "@traceai/cursor-sdk"; + +export interface TracingContext { + tracer: Tracer; + policy: ContentPolicy; + /** + * How long a run whose end was signalled without a `RunResult` (stream ended + * before the status flipped, or the run finished before anyone streamed) + * waits for `wait()` / a terminal status before its span is closed. + */ + graceMs: number; + /** + * How long a run whose end is already known (wait() resolved, terminal + * status) keeps its span open for a stream that is still being read. Stops + * a partly read, never-closed stream from holding the span open forever. + */ + drainMs: number; + /** Runs whose span is still open, so `forceFlush()` / `shutdown()` can close them. */ + registry: Set; +} + +export type GetContext = () => TracingContext | undefined; + +export function isPatched(target: unknown): boolean { + try { + return !!target && (target as Record)[PATCHED] === true; + } catch { + return false; + } +} + +function markPatched(target: object): boolean { + try { + Object.defineProperty(target, PATCHED, { value: true, configurable: true, enumerable: false }); + return true; + } catch { + return false; + } +} + +function defineMethod(target: object, name: string, value: unknown): boolean { + try { + Object.defineProperty(target, name, { value, writable: true, configurable: true, enumerable: false }); + return true; + } catch (error) { + diag.debug(`${LOG}: cannot patch ${name}: ${error}`); + return false; + } +} + +function safe(fn: () => void): void { + try { + fn(); + } catch (error) { + diag.debug(`${LOG}: ${error}`); + } +} + +/** + * Patch the SDK's `Agent` class (`import { Agent } from "@cursor/sdk"`). + * Returns an undo function, or `undefined` when it was already patched or + * has nothing to patch. + */ +export function patchAgentClass(AgentClass: AgentClassLike, getContext: GetContext): (() => void) | undefined { + if (!AgentClass || (typeof AgentClass !== "function" && typeof AgentClass !== "object") || isPatched(AgentClass)) { + return undefined; + } + const target = AgentClass as unknown as Record; + const undo: Array<() => void> = []; + for (const [method, spanName] of [ + ["create", SpanNames.CREATE], + ["resume", SpanNames.RESUME], + ] as const) { + const original = target[method]; + if (typeof original !== "function") continue; + const hadOwn = Object.prototype.hasOwnProperty.call(target, method); + const traced = function tracedAgentFactory(this: unknown, ...args: unknown[]) { + const ctx = getContext(); + if (!ctx) return (original as (...a: unknown[]) => unknown).apply(this, args); + const startTimeMs = clockMs(); + const parentContext = otelContext.active(); + let pending: unknown; + try { + pending = (original as (...a: unknown[]) => unknown).apply(this, args); + } catch (error) { + factoryFailed(ctx, spanName, method, args, parentContext, startTimeMs, error); + throw error; + } + return Promise.resolve(pending).then( + (agent) => wrapAgent(agent as AgentLike, getContext), + (error) => { + factoryFailed(ctx, spanName, method, args, parentContext, startTimeMs, error); + throw error; + }, + ); + }; + if (!defineMethod(target, method, traced)) continue; + undo.push(() => { + if (hadOwn) defineMethod(target, method, original); + else delete target[method]; + }); + } + if (!undo.length) return undefined; + markPatched(target); + return () => { + while (undo.length) safe(() => undo.pop()?.()); + safe(() => delete (target as Record)[PATCHED]); + }; +} + +function factoryFailed( + ctx: TracingContext, + spanName: string, + method: "create" | "resume", + args: unknown[], + parentContext: Context, + startTimeMs: number, + error: unknown, +): void { + safe(() => { + let options: AgentOptionsLike | undefined; + let agentId: string | undefined; + if (method === "create") { + options = args[0] as AgentOptionsLike | undefined; + agentId = typeof options?.agentId === "string" ? options.agentId : undefined; + } else { + agentId = typeof args[0] === "string" ? (args[0] as string) : undefined; + options = args[1] as AgentOptionsLike | undefined; + } + const runtime = options && typeof options === "object" && options.cloud ? "cloud" : options?.local ? "local" : runtimeOf(agentId); + recordFactoryError({ + tracer: ctx.tracer, + policy: ctx.policy, + name: spanName, + parentContext, + startTimeMs, + error, + agentId, + model: options && typeof options === "object" ? options.model : undefined, + runtime, + }); + }); +} + +/** + * Patch one `SDKAgent` instance so each `send()` is traced. Returns the same + * instance. A no-op for anything without a `send` method. + */ +export function wrapAgent(agent: T, getContext: GetContext): T { + const target = agent as unknown as AgentLike; + if (!target || typeof target !== "object" || isPatched(target)) return agent; + const original = target.send; + if (typeof original !== "function") return agent; + const traced = function tracedSend(this: AgentLike, ...args: unknown[]) { + const ctx = getContext(); + if (!ctx) return original.apply(this, args as Parameters>); + let tracer: RunTracer | undefined; + try { + tracer = new RunTracer({ + tracer: ctx.tracer, + policy: ctx.policy, + parentContext: otelContext.active(), + agent: this ?? target, + message: args[0], + sendOptions: args[1] as SendOptionsLike | undefined, + startTimeMs: clockMs(), + }); + } catch (error) { + diag.debug(`${LOG}: tracing disabled for this run: ${error}`); + } + if (!tracer) return original.apply(this, args as Parameters>); + const runTracer = tracer; + let pending: Promise; + try { + pending = original.apply(this, args as Parameters>); + } catch (error) { + safe(() => runTracer.finish({ kind: "error", error })); + throw error; + } + return Promise.resolve(pending).then( + (run) => { + safe(() => watchRun(run, runTracer, ctx)); + return run; + }, + (error) => { + safe(() => runTracer.finish({ kind: "error", error })); + throw error; + }, + ); + }; + if (!defineMethod(target, "send", traced)) return agent; + markPatched(target); + return agent; +} + +/** + * Decides when a run span closes. The span closes at the first of: + * `wait()` resolving or throwing, the stream throwing, the stream ending + * cleanly (the run ended with it), or a terminal status from + * `onDidChangeStatus`. While the application is reading the stream, closing + * is deferred to the stream's end so buffered tool events are not lost. + */ +export class RunWatcher { + private activeStreams = 0; + private streamed = false; + private pendingResult?: RunResultLike; + private pendingError?: { error: unknown }; + private terminalSeen = false; + private streamEnded = false; + private graceTimer?: ReturnType; + private drainTimer?: ReturnType; + private unsubscribe?: () => void; + + constructor( + private readonly run: RunLike, + private readonly tracer: RunTracer, + private readonly ctx: TracingContext, + ) { + ctx.registry.add(this); + tracer.attachRun(run); + this.subscribe(); + } + + get finished(): boolean { + return this.tracer.isFinished; + } + + /** True while the run's end is known but the span waits for `wait()` or a status. */ + get inGrace(): boolean { + return this.graceTimer !== undefined; + } + + /** True once the run's end is known: wait() settled, a terminal status, or the stream ended cleanly. */ + get outcomeKnown(): boolean { + return ( + !!this.pendingResult || + !!this.pendingError || + this.terminalSeen || + this.streamEnded || + !!this.tracer.statusFromStream || + this.handleTerminal() + ); + } + + /** + * Close now with what is known. Used by `forceFlush()` (runs whose end is + * known) and `shutdown()` (every open run). A stream still being read is + * detached first: its open tool spans end as incomplete. + */ + flush(): void { + if (this.finished) return; + if (this.activeStreams > 0) { + this.activeStreams = 0; + this.tracer.detach(); + } + if (this.pendingError) this.finish({ kind: "error", error: this.pendingError.error }); + else if (this.pendingResult) this.finish({ kind: "result", result: this.pendingResult }); + else if (this.outcomeKnown) this.finish({ kind: "status" }); + else this.finish({ kind: "detached" }); + } + + onStreamStart(): void { + this.activeStreams += 1; + this.streamed = true; + this.clearGrace(); + // Started after the run ended (within the grace period): bound how long it may stay open. + if (this.terminalSeen || this.pendingResult || this.pendingError) this.startDrain(); + } + + onStreamEvent(event: SDKMessageLike): void { + this.tracer.onEvent(event); + } + + /** The stream ended cleanly: the run ended. */ + onStreamDone(): void { + this.activeStreams = Math.max(0, this.activeStreams - 1); + this.streamEnded = true; + if (this.activeStreams > 0) return; + if (this.pendingError || this.pendingResult || this.handleTerminal() || this.tracer.statusFromStream) { + this.terminalSeen = true; + this.tryFinish(); + } else { + // The run handle may flip to terminal a moment after the queue closes. + this.startGrace(); + } + } + + onStreamError(error: unknown): void { + this.activeStreams = Math.max(0, this.activeStreams - 1); + this.finish({ kind: "error", error }); + } + + /** The consumer stopped reading (`break`, `return()`). */ + onStreamReturn(): void { + this.activeStreams = Math.max(0, this.activeStreams - 1); + if (this.activeStreams > 0) return; + this.tracer.detach(); + if (this.pendingError || this.pendingResult || this.handleTerminal() || this.tracer.statusFromStream) { + this.terminalSeen = true; + this.tryFinish(); + } else if (!this.unsubscribe) { + // No way to observe the end: close now, status from the handle ("running"). + this.finish({ kind: "detached" }); + } + // Otherwise the status listener or wait() closes it. + } + + onWaitResult(result: RunResultLike): void { + this.pendingResult = result; + this.tryFinish(); + } + + onWaitError(error: unknown): void { + this.pendingError = { error }; + this.tryFinish(); + } + + /** + * The run's end is known but a stream is still open (read partly and never + * closed, or still draining). Close the span after `drainMs` anyway. + */ + private startDrain(): void { + if (this.drainTimer || this.finished || this.activeStreams === 0) return; + const timer = setTimeout(() => { + this.drainTimer = undefined; + if (!this.finished) this.flush(); + }, this.ctx.drainMs); + (timer as { unref?: () => void }).unref?.(); + this.drainTimer = timer; + } + + private subscribe(): void { + const subscribe = this.run.onDidChangeStatus; + if (typeof subscribe !== "function") return; + try { + const dispose = subscribe.call(this.run, (status) => { + safe(() => { + if (!isTerminalStatus(status) || this.finished) return; + this.terminalSeen = true; + if (this.activeStreams > 0) { + this.startDrain(); + return; + } + if (!this.streamed && !this.pendingResult && !this.pendingError) { + // Finished before anyone read the stream: give the app a moment to start reading it or call wait(). + this.startGrace(); + return; + } + this.tryFinish(); + }); + }); + if (typeof dispose === "function") this.unsubscribe = dispose; + else this.unsubscribe = () => undefined; + } catch (error) { + diag.debug(`${LOG}: onDidChangeStatus failed: ${error}`); + } + } + + private handleTerminal(): boolean { + try { + return isTerminalStatus(this.run.status); + } catch { + return false; + } + } + + private tryFinish(): void { + if (this.finished) return; + if (this.activeStreams > 0) { + if (this.pendingError || this.pendingResult || this.terminalSeen) this.startDrain(); + return; + } + if (this.pendingError) this.finish({ kind: "error", error: this.pendingError.error }); + else if (this.pendingResult) this.finish({ kind: "result", result: this.pendingResult }); + else if (this.terminalSeen || this.handleTerminal()) this.finish({ kind: "status" }); + } + + private startGrace(): void { + if (this.graceTimer || this.finished) return; + const timer = setTimeout(() => { + this.graceTimer = undefined; + if (this.finished) return; + if (this.activeStreams > 0) { + this.startDrain(); + return; + } + this.finish(this.pendingResult ? { kind: "result", result: this.pendingResult } : { kind: "status" }); + }, this.ctx.graceMs); + (timer as { unref?: () => void }).unref?.(); + this.graceTimer = timer; + } + + private clearGrace(): void { + if (this.graceTimer) clearTimeout(this.graceTimer); + this.graceTimer = undefined; + } + + private finish(outcome: Parameters[0]): void { + this.clearGrace(); + if (this.drainTimer) clearTimeout(this.drainTimer); + this.drainTimer = undefined; + this.tracer.finish(outcome, this.run); + this.ctx.registry.delete(this); + const unsubscribe = this.unsubscribe; + this.unsubscribe = undefined; + if (unsubscribe) safe(unsubscribe); + } +} + +/** Patch one `Run` instance's `stream()` and `wait()` and watch its status. */ +export function watchRun(run: RunLike, tracer: RunTracer, ctx: TracingContext): void { + if (!run || typeof run !== "object") { + tracer.finish({ kind: "status" }); + return; + } + const watcher = new RunWatcher(run, tracer, ctx); + const target = run as unknown as Record; + + const originalStream = run.stream; + if (typeof originalStream === "function") { + defineMethod(target, "stream", function tracedStream(this: RunLike, ...args: unknown[]) { + const source = (originalStream as (...a: unknown[]) => AsyncGenerator).apply(this, args); + return traceStream(source, watcher); + }); + } + const originalWait = run.wait; + if (typeof originalWait === "function") { + defineMethod(target, "wait", function tracedWait(this: RunLike, ...args: unknown[]) { + const pending = (originalWait as (...a: unknown[]) => Promise).apply(this, args); + return Promise.resolve(pending).then( + (result) => { + safe(() => watcher.onWaitResult(result)); + return result; + }, + (error) => { + safe(() => watcher.onWaitError(error)); + throw error; + }, + ); + }); + } + markPatched(target); +} + +/** + * Return a generator that yields exactly what `source` yields and feeds the + * watcher. A tracing failure never reaches the caller. + */ +export function traceStream( + source: AsyncGenerator, + watcher: RunWatcher, +): AsyncGenerator { + if (!source || typeof source.next !== "function") return source; + let started = false; + let ended = false; + const start = () => { + if (started) return; + started = true; + safe(() => watcher.onStreamStart()); + }; + const end = (fn: () => void) => { + if (ended || !started) return; + ended = true; + safe(fn); + }; + + const proxy = { + async next(...args: [] | [unknown]) { + start(); + let result: IteratorResult; + try { + result = await source.next(...(args as [])); + } catch (error) { + end(() => watcher.onStreamError(error)); + throw error; + } + if (result.done) end(() => watcher.onStreamDone()); + else if (!ended) safe(() => watcher.onStreamEvent(result.value)); + return result; + }, + async return(value?: unknown) { + try { + return await source.return(value as never); + } finally { + end(() => watcher.onStreamReturn()); + } + }, + async throw(error?: unknown) { + start(); + let result: IteratorResult; + try { + result = await source.throw(error); + } catch (thrown) { + end(() => watcher.onStreamError(thrown)); + throw thrown; + } + if (result.done) end(() => watcher.onStreamReturn()); + else if (!ended) safe(() => watcher.onStreamEvent(result.value)); + return result; + }, + [Symbol.asyncIterator]() { + return proxy; + }, + } as unknown as AsyncGenerator; + const asyncDispose = (Symbol as unknown as { asyncDispose?: symbol }).asyncDispose; + if (asyncDispose) { + (proxy as unknown as Record)[asyncDispose] = async () => { + await proxy.return(undefined); + }; + } + return proxy; +} diff --git a/typescript/packages/traceai_cursor_sdk/tsconfig.esm.json b/typescript/packages/traceai_cursor_sdk/tsconfig.esm.json new file mode 100644 index 000000000..e5d6f9b6c --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/tsconfig.esm.json @@ -0,0 +1,17 @@ +{ + "extends": "../../tsconfig.base.esm.json", + "compilerOptions": { + "outDir": "dist/esm", + "rootDir": "src", + "tsBuildInfoFile": "dist/esm/tsconfig.esm.tsbuildinfo", + "baseUrl": "./src" + }, + "include": [ + "src/**/*.ts" + ], + "references": [], + "exclude": [ + "src/**/*.test.ts", + "src/**/__tests__/**" + ] +} diff --git a/typescript/packages/traceai_cursor_sdk/tsconfig.esnext.json b/typescript/packages/traceai_cursor_sdk/tsconfig.esnext.json new file mode 100644 index 000000000..a99f0fe06 --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/tsconfig.esnext.json @@ -0,0 +1,17 @@ +{ + "extends": "../../tsconfig.base.esnext.json", + "compilerOptions": { + "outDir": "dist/esnext", + "rootDir": "src", + "tsBuildInfoFile": "dist/esnext/tsconfig.esnext.tsbuildinfo", + "baseUrl": "./src" + }, + "include": [ + "src/**/*.ts" + ], + "references": [], + "exclude": [ + "src/**/*.test.ts", + "src/**/__tests__/**" + ] +} diff --git a/typescript/packages/traceai_cursor_sdk/tsconfig.json b/typescript/packages/traceai_cursor_sdk/tsconfig.json new file mode 100644 index 000000000..087f63ee4 --- /dev/null +++ b/typescript/packages/traceai_cursor_sdk/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": ".", + "baseUrl": "./src" + }, + "include": ["src/**/*.ts"], + "exclude": ["src/**/*.test.ts", "src/**/__tests__/**", "test/**/*.ts"], + "references": [ + { "path": "../fi-core" }, + { "path": "../fi-semantic-conventions" } + ] +} diff --git a/typescript/pnpm-lock.yaml b/typescript/pnpm-lock.yaml index be0f04bdc..214f6d938 100644 --- a/typescript/pnpm-lock.yaml +++ b/typescript/pnpm-lock.yaml @@ -621,6 +621,49 @@ importers: specifier: ^1.8.16 version: 1.8.16 + packages/traceai_cursor_sdk: + dependencies: + '@opentelemetry/api': + specifier: ^1.9.0 + version: 1.9.1 + '@opentelemetry/instrumentation': + specifier: ^0.202.0 + version: 0.202.0(@opentelemetry/api@1.9.1) + '@traceai/fi-core': + specifier: workspace:^ + version: link:../fi-core + '@traceai/fi-semantic-conventions': + specifier: workspace:^ + version: link:../fi-semantic-conventions + devDependencies: + '@cursor/sdk': + specifier: 1.0.38 + version: 1.0.38(zod@4.3.6) + '@opentelemetry/sdk-trace-base': + specifier: ^2.0.1 + version: 2.7.1(@opentelemetry/api@1.9.1) + '@types/jest': + specifier: ^29.5.14 + version: 29.5.14 + '@types/node': + specifier: ^22.10.10 + version: 22.15.33 + jest: + specifier: ^29.7.0 + version: 29.7.0(@types/node@22.15.33)(ts-node@10.9.2(@types/node@22.15.33)(typescript@5.8.3)) + rimraf: + specifier: ^6.0.1 + version: 6.1.2 + ts-jest: + specifier: ^29.2.5 + version: 29.4.6(@babel/core@7.27.1)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.27.1))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.15.33)(ts-node@10.9.2(@types/node@22.15.33)(typescript@5.8.3)))(typescript@5.8.3) + tsc-alias: + specifier: ^1.8.10 + version: 1.8.16 + typescript: + specifier: ^5.7.3 + version: 5.8.3 + packages/traceai_deepseek: dependencies: '@opentelemetry/api': @@ -2871,6 +2914,9 @@ packages: '@bcoe/v8-coverage@0.2.3': resolution: {integrity: sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==} + '@bufbuild/protobuf@1.10.0': + resolution: {integrity: sha512-QDdVFLoN93Zjg36NoQPZfsVH9tZew7wKDKyV5qRdj8ntT4wQCOradQjRaTdwMhWUYsgKsvCINKKm87FdEk96Ag==} + '@bufbuild/protobuf@1.10.1': resolution: {integrity: sha512-wJ8ReQbHxsAfXhrf9ixl0aYbZorRuOWpBNzm8pL8ftmSxQx/wnJD5Eg861NwJU/czy2VXFIebCeZnZrI9rktIQ==} @@ -2890,10 +2936,57 @@ packages: resolution: {integrity: sha512-Ir+AOibqzrIsL6ajt3Rz3LskB7OiMVHqltZmspbW/TJuTVuyOMirVqAkjfY6JISiLHgyNqicAC8AyHHGzNd/dA==} engines: {node: '>=0.1.90'} + '@connectrpc/connect-web@1.7.0': + resolution: {integrity: sha512-qyP0YOnUPRWwCc/VfsoydMJvkb7EyUPr2q9sHgBuJzbADjiqck1gKH5V5ZPzPhTLBvmz5UvG+wiZ5sMRQHU1MQ==} + peerDependencies: + '@bufbuild/protobuf': ^1.10.0 + '@connectrpc/connect': 1.7.0 + + '@connectrpc/connect@1.7.0': + resolution: {integrity: sha512-iNKdJRi69YP3mq6AePRT8F/HrxWCewrhxnLMNm0vpqXAR8biwzRtO6Hjx80C6UvtKJ5sFmffQT7I4Baecz389w==} + peerDependencies: + '@bufbuild/protobuf': ^1.10.0 + '@cspotcode/source-map-support@0.8.1': resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==} engines: {node: '>=12'} + '@cursor/sdk-darwin-arm64@1.0.38': + resolution: {integrity: sha512-pXxj4pjbIoDo6ZjgksSf4VTD4EJz6BGDKvFjDVVUMg0PmLCVbceOnp0pqfRO8SVpdUSE45GFrXuLnSZgLag/xw==} + cpu: [arm64] + os: [darwin] + hasBin: true + + '@cursor/sdk-darwin-x64@1.0.38': + resolution: {integrity: sha512-rutfTMq1f9WZckPFH8R5bzNzHaZg7I/TijVUkfD3GbqIqqc5OKHzdTMqZf+AFAqRDQccGJn4GLWcnQ9wTwIVNA==} + cpu: [x64] + os: [darwin] + hasBin: true + + '@cursor/sdk-linux-arm64@1.0.38': + resolution: {integrity: sha512-CqmUnM8W8W2mKucSrdHO0kn4ems82siWuo7kvVJvXCtPkaziVNC++dro5h9hSh2oVgRbB91sWQ4lzsHVIDpkvA==} + cpu: [arm64] + os: [linux] + hasBin: true + + '@cursor/sdk-linux-x64@1.0.38': + resolution: {integrity: sha512-RL6OJTAF3oozMG+HNtykySQ5BOP94yJNWP65wZ2yzMLTAW9ao80++OnaWJya1lndLacHLYP+QZT4igm5TT+BWQ==} + cpu: [x64] + os: [linux] + hasBin: true + + '@cursor/sdk-win32-x64@1.0.38': + resolution: {integrity: sha512-IUfuCk/S/qzEB+tfT4yWH6iSMz56Lvakn1zNjdk+oAsZ7RJWtWkZcea6eqMSRB1WLmTeQG0uetXKX330w+xI0A==} + cpu: [x64] + os: [win32] + hasBin: true + + '@cursor/sdk@1.0.38': + resolution: {integrity: sha512-8UwPKaprIXvlVR71yHyNNTyFwZCOzfHW7W+FKjPdDS9Ym9FDZc51Jwsu9lAhxHf7n0US3t0pybkDaNFdldrQ+A==} + engines: {node: '>=22.13'} + peerDependencies: + zod: ^3.25.0 || ^4.0.0 + '@dabh/diagnostics@2.0.8': resolution: {integrity: sha512-R4MSXTVnuMzGD7bzHdW2ZhhdPC/igELENcq5IjEverBvq5hn1SXCWcsi6eSsdWP0/Ur+SItRRjAktmdoX/8R/Q==} @@ -5640,6 +5733,12 @@ packages: '@standard-schema/spec@1.1.0': resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + '@statsig/client-core@3.31.0': + resolution: {integrity: sha512-SuxQD6TmVszPG7FoMKwTk/uyBuVFk7XnxI3T/E0uyb7PL7GNjONtfsoh+NqBBVUJVse0CUeSFfgJPoZy1ZOslQ==} + + '@statsig/js-client@3.31.0': + resolution: {integrity: sha512-LFa5E0LjT6sTfZv3sNGoyRLSZ1078+agdgOA+Vm1ecjG+KbSOfBLTW7hMwimrJ29slRwbYDzbtKaPJo/R37N2g==} + '@strands-agents/sdk@0.1.6': resolution: {integrity: sha512-nQl1WlCSGYjcpo/dkZU5v/0gaLaAwNW4oPJm2N6gqvTXsaUO33COYqQb80fgdF57xw38K+a6OYmdmA4CGXqrdw==} engines: {node: '>=20.0.0'} @@ -11330,6 +11429,8 @@ snapshots: '@bcoe/v8-coverage@0.2.3': {} + '@bufbuild/protobuf@1.10.0': {} + '@bufbuild/protobuf@1.10.1': {} '@bufbuild/protobuf@2.11.0': {} @@ -11358,10 +11459,48 @@ snapshots: '@colors/colors@1.6.0': {} + '@connectrpc/connect-web@1.7.0(@bufbuild/protobuf@1.10.0)(@connectrpc/connect@1.7.0(@bufbuild/protobuf@1.10.0))': + dependencies: + '@bufbuild/protobuf': 1.10.0 + '@connectrpc/connect': 1.7.0(@bufbuild/protobuf@1.10.0) + + '@connectrpc/connect@1.7.0(@bufbuild/protobuf@1.10.0)': + dependencies: + '@bufbuild/protobuf': 1.10.0 + '@cspotcode/source-map-support@0.8.1': dependencies: '@jridgewell/trace-mapping': 0.3.9 + '@cursor/sdk-darwin-arm64@1.0.38': + optional: true + + '@cursor/sdk-darwin-x64@1.0.38': + optional: true + + '@cursor/sdk-linux-arm64@1.0.38': + optional: true + + '@cursor/sdk-linux-x64@1.0.38': + optional: true + + '@cursor/sdk-win32-x64@1.0.38': + optional: true + + '@cursor/sdk@1.0.38(zod@4.3.6)': + dependencies: + '@bufbuild/protobuf': 1.10.0 + '@connectrpc/connect': 1.7.0(@bufbuild/protobuf@1.10.0) + '@connectrpc/connect-web': 1.7.0(@bufbuild/protobuf@1.10.0)(@connectrpc/connect@1.7.0(@bufbuild/protobuf@1.10.0)) + '@statsig/js-client': 3.31.0 + zod: 4.3.6 + optionalDependencies: + '@cursor/sdk-darwin-arm64': 1.0.38 + '@cursor/sdk-darwin-x64': 1.0.38 + '@cursor/sdk-linux-arm64': 1.0.38 + '@cursor/sdk-linux-x64': 1.0.38 + '@cursor/sdk-win32-x64': 1.0.38 + '@dabh/diagnostics@2.0.8': dependencies: '@so-ric/colorspace': 1.1.6 @@ -13837,6 +13976,15 @@ snapshots: transitivePeerDependencies: - supports-color + '@opentelemetry/instrumentation@0.202.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/api-logs': 0.202.0 + import-in-the-middle: 1.14.2 + require-in-the-middle: 7.5.2 + transitivePeerDependencies: + - supports-color + '@opentelemetry/instrumentation@0.203.0(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 @@ -15177,6 +15325,12 @@ snapshots: '@standard-schema/spec@1.1.0': {} + '@statsig/client-core@3.31.0': {} + + '@statsig/js-client@3.31.0': + dependencies: + '@statsig/client-core': 3.31.0 + '@strands-agents/sdk@0.1.6(@cfworker/json-schema@4.1.1)(ws@8.21.0)': dependencies: '@aws-sdk/client-bedrock-runtime': 3.975.0