Skip to content

feat(server-utils): Add first-party Flue instrumentation - #24265

Draft
RulaKhaled wants to merge 2 commits into
developfrom
feat/flue-instrumentation-base
Draft

feat(server-utils): Add first-party Flue instrumentation#24265
RulaKhaled wants to merge 2 commits into
developfrom
feat/flue-instrumentation-base

Conversation

@RulaKhaled

@RulaKhaled RulaKhaled commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator

Instruments the Flue agent framework (@flue/runtime) through its own instrument() hook. Enabled by default on Node, no app code required. Verified against a scaffolded flue init app driven over HTTP against a real provider, on both injection paths:

http.server  POST
  └─ gen_ai.invoke_agent  invoke_agent Hello   (auto.ai.flue)
     ├─ gen_ai.chat  chat anthropic/claude-haiku-4.5  [988 in / 125 out / $0.001613]
     ├─ gen_ai.execute_tool  execute_tool get_weather
     └─ gen_ai.chat  chat anthropic/claude-haiku-4.5  [1035 in / 30 out / $0.001185]

Message content is gated on recordInputs/recordOutputs, falling back to dataCollection.genAI. Flue reaches providers through pi-ai, which bundles the openai/@anthropic-ai/sdk/@google/genai clients, so those are skipped while Flue is instrumented — otherwise every call gets a second gen_ai.chat.

Root cause: Flue publishes no diagnostics channels, only an { observe, interceptor } registration. The interceptor owns the agent span and the active context; observe owns the turn and tool spans, since turn_start/turn are the only signal one-to-one with a model call. Getting at the app's own instrument() needs both injection paths, because neither records what the other uses: the bundler snippet passes the binding out, while the runtime hook imports the module by its recorded URL.

Cloudflare needs manual registration — agents run in per-Durable-Object isolates an integration registered off Sentry.init() never sees — so createFlueInstrumentation is exported from @sentry/cloudflare and skips providers itself.

Tests stacked in #24266.

Known gaps: Cloudflare untested end to end; Flue's own Sentry blueprint targets @sentry/node@^10.64.0 and our docs point at it, so on v11 both would register and double-report (needs a docs update, same shape as the @mastra/sentry migration).

Fixes #24017

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

size-limit report 📦

Path Size % Change Change
@sentry/browser 28.91 kB +0.39% +110 B 🔺
@sentry/browser - with treeshaking flags 27.21 kB +0.37% +100 B 🔺
@sentry/browser - with treeshaking flags tracing without tracing 27.1 kB +0.35% +93 B 🔺
@sentry/browser (incl. Tracing) 50.27 kB +2.15% +1.05 kB 🔺
@sentry/browser (incl. Tracing + Span Streaming) 50.28 kB +2.15% +1.06 kB 🔺
@sentry/browser (incl. Tracing, Profiling) 53.26 kB +2.18% +1.13 kB 🔺
@sentry/browser (incl. Tracing, Replay) 89.76 kB +1.13% +998 B 🔺
@sentry/browser (incl. Tracing, Replay) - with treeshaking flags 78.86 kB +1.16% +901 B 🔺
@sentry/browser (incl. Tracing, Replay with Canvas) 94.45 kB +1.08% +1.01 kB 🔺
@sentry/browser (incl. Tracing, Replay, Feedback) 107.46 kB +1.02% +1.08 kB 🔺
@sentry/browser (incl. Feedback) 46.4 kB +0.23% +106 B 🔺
@sentry/browser (incl. sendFeedback) 33.96 kB +0.29% +96 B 🔺
@sentry/browser (incl. FeedbackAsync) 39.07 kB +0.24% +93 B 🔺
@sentry/browser (incl. Metrics) 29.93 kB +0.36% +105 B 🔺
@sentry/browser (incl. Logs) 30.19 kB +0.34% +101 B 🔺
@sentry/browser (incl. Metrics & Logs) 30.86 kB +0.37% +112 B 🔺
@sentry/react 30.66 kB +0.37% +113 B 🔺
@sentry/react (incl. Tracing) 52.59 kB +2.01% +1.03 kB 🔺
@sentry/vue 36.15 kB +0.28% +99 B 🔺
@sentry/vue (incl. Tracing) 52.53 kB +2.05% +1.05 kB 🔺
@sentry/svelte 28.93 kB +0.32% +91 B 🔺
CDN Bundle 30.64 kB +0.32% +95 B 🔺
CDN Bundle (incl. Tracing) 50.78 kB +2.1% +1.04 kB 🔺
CDN Bundle (incl. Logs, Metrics) 32.92 kB +0.32% +102 B 🔺
CDN Bundle (incl. Tracing, Logs, Metrics) 52.73 kB +2% +1.03 kB 🔺
CDN Bundle (incl. Replay, Logs, Metrics) 73.61 kB +0.19% +135 B 🔺
CDN Bundle (incl. Tracing, Replay) 88.32 kB +1.19% +1.03 kB 🔺
CDN Bundle (incl. Tracing, Replay, Logs, Metrics) 90.29 kB +1.24% +1.1 kB 🔺
CDN Bundle (incl. Tracing, Replay, Feedback) 94.36 kB +1.23% +1.15 kB 🔺
CDN Bundle (incl. Tracing, Replay, Feedback, Logs, Metrics) 96.38 kB +1.23% +1.17 kB 🔺
CDN Bundle - uncompressed 90.72 kB +0.29% +257 B 🔺
CDN Bundle (incl. Tracing) - uncompressed 151.68 kB +2.37% +3.51 kB 🔺
CDN Bundle (incl. Logs, Metrics) - uncompressed 97.3 kB +0.28% +266 B 🔺
CDN Bundle (incl. Tracing, Logs, Metrics) - uncompressed 157.64 kB +2.28% +3.51 kB 🔺
CDN Bundle (incl. Replay, Logs, Metrics) - uncompressed 226.71 kB +0.19% +417 B 🔺
CDN Bundle (incl. Tracing, Replay) - uncompressed 271.25 kB +1.31% +3.49 kB 🔺
CDN Bundle (incl. Tracing, Replay, Logs, Metrics) - uncompressed 277.2 kB +1.28% +3.49 kB 🔺
CDN Bundle (incl. Tracing, Replay, Feedback) - uncompressed 284.95 kB +1.24% +3.49 kB 🔺
CDN Bundle (incl. Tracing, Replay, Feedback, Logs, Metrics) - uncompressed 290.89 kB +1.22% +3.49 kB 🔺
@sentry/nextjs (client) 54.91 kB +1.7% +913 B 🔺
@sentry/sveltekit (client) 50.69 kB +2.1% +1.04 kB 🔺
@sentry/core/server 37.1 kB +0.31% +114 B 🔺
@sentry/core/browser 13.66 kB +0.82% +110 B 🔺
@sentry/node 129.74 kB +1.53% +1.95 kB 🔺
@sentry/node/import (ESM hook with diagnostics-channel injection) 81.86 kB +0.3% +243 B 🔺
@sentry/node - without tracing 89.07 kB +0.41% +356 B 🔺
@sentry/node - without channel injection 108.85 kB +1.7% +1.82 kB 🔺
@sentry/aws-serverless 97.47 kB +0.39% +370 B 🔺
@sentry/cloudflare (withSentry) - minified 202.48 kB +0.25% +500 B 🔺
@sentry/cloudflare (withSentry) 504.19 kB +0.31% +1.51 kB 🔺

View base workflow run

RulaKhaled and others added 2 commits September 10, 2026 09:39
Instruments the Flue agent framework (`@flue/runtime`) through the runtime's own
`instrument()` hook, producing the `invoke_agent` -> `chat` / `execute_tool`
hierarchy with token usage and Flue-computed cost.

Flue exposes no diagnostics channels; it takes an `{ observe, interceptor }`
registration. The interceptor owns the agent span and the active context, so
spans opened underneath parent correctly. `observe` owns the turn and tool spans,
because `turn_start`/`turn` are the only signal one-to-one with a model call and
`turn` carries usage.

Reaching the app's own `instrument()` is the awkward part: it closes over a
module-scope registry, so registering into a second evaluated copy fails
silently, and `createRequire` — how `mastraIntegration` finds the app's copy —
cannot resolve an ESM-only package with no `require` export condition. Each
injection path therefore supplies it differently, and neither records what the
other uses: under a bundler plugin the injected snippet passes the binding out
(new optional `bindings` on the channel-integration definitions), and under the
runtime hook the module is imported by the resolved URL the hook records, which
ESM guarantees resolves to the same instance.

Also skips the raw provider integrations while Flue is instrumented: Flue calls
the providers through `@earendil-works/pi-ai`, which bundles the `openai`,
`@anthropic-ai/sdk` and `@google/genai` clients, so those would emit a second
`gen_ai.chat` beside ours.

Cloudflare needs manual registration — agents run in per-Durable-Object isolates
that an integration registered off `Sentry.init()` never sees — so
`createFlueInstrumentation` is exported from `@sentry/cloudflare` and performs
the provider skip itself.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Flue exposes the content on its event stream — `turn_request` carries the full
`ModelRequest` (system prompt, messages, tool definitions), the settled `turn`
carries `response.output`, and the tool events carry arguments and results — so
there is no reason to omit it.

Recorded as `gen_ai.input.messages`, `gen_ai.output.messages`,
`gen_ai.system_instructions`, `gen_ai.tool.definitions`,
`gen_ai.tool.call.arguments` and `gen_ai.tool.call.result`, gated on
`recordInputs`/`recordOutputs` via `resolveAIRecordingOptions`, which falls back
to the client's `dataCollection.genAI` settings. `FlueOptions` is threaded back
through `flueIntegration` and now does something.

Note the request content is only on `turn_request`; the settled `turn` reports
request metadata alone.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

@isaacs isaacs left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is on a good path, but there are still some gaps. It surfaced an interesting shortcoming of @apm-js-collab/tracing-hooks that could save around some lines on this side. apm-js-collab/tracing-hooks#52

// A submission's agent operation re-enters once, and the two carry different halves of the
// agent's identity: the outer context names the agent, the inner one names the conversation.
// Only the outer becomes a span, so the conversation id is lifted onto it from the re-entry.
if (agentDepth++ > 0) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This approach is not parallel-safe.

agentDepth and agentSpan are single closure variables, and this treats any re-entry as a re-entry of the same submission. However, if an HTTP server or some other concurrency-heavy application had two parallel operations, those could clobber each other.

This can probably be fixed by using the operationId and submissionId to link the operations together. Keep agent spans in a Map keyed by operation.operationId, and resolve the parent in observe from observation.operationId. That also removes the depth counter and the re-entry special case entirely.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, I'm not sure this is actually guaranteed to enter exactly twice? Looking at the flue code, the two dispatch sites I found are the coordinator and the session's runOperation (for operationKind of 'prompt' and 'skill').

runOperation is behind runExclusive, so it can't nest within one session. But subagent delegation runs in a separate session (DelegationDepthExceededError and defineSubagent are both exported), and a nested session's own runOperation('prompt') would be a third-level agent operation. Under the current code every subagent invocation is swallowed into the parent's single invoke_agent span.

I had the clanker clank up a test, written to packages/server-utils/test/ai/flue/nested-agent-operations.test.ts that seems to demonstrate this, if I'm understanding the behavior here properly: https://gist.github.com/isaacs/8f703ebae6adc26696b54c5d4f76b50e

}
},
);
},

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FlueExecutionContext.traceCarrier is { traceparent, tracestate }, populated by extractTraceCarrier from the incoming request headers and passed on the outer agent operation.

But, the code here never reads it, so it seems like dispatched submissions will start orphan traces? For a durable or dispatched submission the coordinator runs the work later, possibly in another isolate, Durable Object, or process. Without traceCarrier, the invoke_agent span starts a brand new trace with no link to the request that enqueued it.

We could do this with a small helper, like:

function sentryTraceFromTraceparent(traceparent: string): string | undefined {
  const [version, traceId, spanId, flags] = traceparent.split('-');
  if (version !== '00' || !traceId || !spanId || !flags) {
    return undefined;
  }
  return `${traceId}-${spanId}-${parseInt(flags, 16) & 0x01 ? '1' : '0'}`;
}

(This could perhaps be reasonable to put in @sentry/core somewhere, near generateTraceparentHeader? I didn't see any w3c traceparent parser there already, and it's tiny, so we could also wait until there's a second use for it before abstracting.)

And then apply it only when nothing already continued the trace:

const sentryTrace = ctx.traceCarrier?.traceparent
  ? sentryTraceFromTraceparent(ctx.traceCarrier.traceparent)
  : undefined;

return sentryTrace && !getActiveSpan()
  ? continueTrace({ sentryTrace, baggage: undefined }, openAgentSpan)
  : openAgentSpan();

// reports as a turn, emitting a second `gen_ai.chat` beside ours. Done here rather than in
// `flueIntegration` so registering by hand — the only option on Cloudflare, where agents run in
// per-Durable-Object isolates — gets it too.
_INTERNAL_skipAiProviderWrapping(SKIPPED_PROVIDERS);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This calls _INTERNAL_skipAiProviderWrapping once, when createFlueInstrumentation is constructed. On Cloudflare the documented usage is a manual call in module or Durable Object scope, so it runs once per isolate.

But, packages/cloudflare/src/client.ts line 188 calls _INTERNAL_clearAiProviderSkips() in _setupIntegrations(), and its comment states that Cloudflare calls init() per request. So the skip registered at isolate load is wiped by the first init() and never re-registered. Every request after the first in that isolate would double report gen_ai.chat for any provider client that is channel-instrumented, which is what the skip is there to prevent.

I think the skip needs to be re-applied per client, not once per instrumentation object. Registering it from an integration setup(client) would do that.

Also, the skip is a side effect of building the object, but the object is only useful once instrument() accepts it.

packages/server-utils/src/integrations/flue.ts lines 59-67 catch any throw from instrument() and log it.

So on the failure path the SDK has suppressed the other AI instrumentations and installed nothing in its place: the user gets no gen_ai.chat spans at all, only a debug log. Reading Flue's instrument function shows it throws InstrumentationAlreadyInstalledError when the key is taken and isDevMode() is false, and can also rethrow from registerExecutionInterceptor.

Recommendation: Move the skip to after a successful instrument() call, or restore the previous state on failure.

// the app's copy — the only copy whose module-scope state the running app reads.
const args = [
JSON.stringify(moduleName),
...(exportName ? [exportName] : []),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
...(exportName ? [exportName] : []),
(exportName ? exportName : undefined),

If a binding has moduleBindings but no exportName, then we'd get something like orchestrionModuleInjected("x", { instrument }), and the bindings object lands in the integrationFn slot. packages/server-utils/src/utils/moduleInjected.ts line 44-46 would then store that object as a factory, and packages/cloudflare/src/baseSdk.ts line 41 would call it as a function and throw.

If we put an explicit undefined here, it'll guarantee it's always a consistent argument position.

(Another option would be to make this an options object or something. Passing undefined is a little bit gross, to be fair.)

// (Flue's `instrument()`) rather than through channels at its call sites: that API closes over
// module-scope state, so it only works on the copy the app itself loaded. This covers the bundler
// path, where the module is inlined and no resolved file is recorded to import instead.
{ exportName: 'flueIntegration', modules: ['@flue/runtime'], bindings: ['instrument'] },

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This sets both exportName and bindings for @flue/runtime. exportName is there so a bundler-only SDK can auto-install the subscriber: packages/cloudflare/src/baseSdk.ts line 38 and lines 150-155 read marker.integrations and call each factory, at init() and on orchestrion.module-injected.

Cloudflare would then instantiate and install flueIntegration on the live client, which contradicts the intention that Cloudflare needs manual registration because an integration registered off init() never sees the per-Durable-Object isolates.

For Flue, exportName looks unnecessary: Node registers the integration statically, and Cloudflare is meant to register by hand. Only bindings is needed.

We should check whether the Cloudflare Vite plugin transforms @flue/runtime at all, and if it does, drop the exportName for this entry.

(Note: if we do drop exportName here, then this walks right into the issue commented in packages/server-utils/src/orchestrion/bundler/moduleInjectedTransform.ts, which is otherwise only theoretical.)

// per-Durable-Object isolates — gets it too.
_INTERNAL_skipAiProviderWrapping(SKIPPED_PROVIDERS);

const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Every other AI integration resolves these values at span time (see packages/server-utils/src/integrations/openai.ts line 82 and 124), because resolveAIRecordingOptions reads getClient()?.getDataCollectionOptions() (packages/server-utils/src/ai/core/utils.ts line 72).

On Cloudflare the client is replaced per request, so the values captured at isolate load are the wrong ones for every later request. On Node it happens to work because the client is stable. Resolving lazily would remove the divergence.

}

const open = (): Span =>
startInactiveSpan({

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

startToolSpan uses startInactiveSpan and parents off the agent span. Anything the tool does (database query, HTTP call, a nested call etc), then lands under invoke_agent as a sibling of execute_tool rather than inside it.

The interceptor already receives type: 'tool' with toolCallId and toolName, and type: 'model' with turnId. Wrapping next() in withActiveSpan(existingSpan, next) for those operation types would fix the nesting without creating extra spans, and would reuse the span the observe path already opened.

The comment at packages/server-utils/src/ai/flue/index.ts lines 173-174 says the
active span during observe "is whatever the provider SDK last opened". With the providers skipped, that is worth re-checking; if it no longer holds, the whole agentSpan plumbing could be replaced by the current active span.

return;
}

import(url).then(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We usually try to avoid computed dynamic imports, but like you said, the ESM registry is the only way in, so it's probably fine.

Two practical consequences though:

  • It works in the CJS build only because rollup 4 defaults output.dynamicImportInCjs to true, so the import() survives instead of being rewritten to require(). That default is load-bearing and undocumented here. packages/server-utils/rollup.npm.config.mjs does not pin it.
  • Bundlers that statically analyze this file will emit a critical-dependency warning for the expression import, even though the bundler path never executes it (the binding is preferred above, on lines 34-38).

The moduleBindings mechanism already exists; consider recording the module URL for the runtime path through the same channel so this branch can go away.

The root cause is upstream: registerDiagnosticsChannelInjection passes no customTransforms (packages/server-runtime-injection/src/register.ts line 167), so registrationOnly cannot be used on the --import path. That is the layer where a fix would remove both the dynamic import and the init anchor.

*/
export const flueConfig: InstrumentationConfig[] = [
{
channelName: 'flueInit',

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't need to be prefixed, since it's already going to be prefixed by orchestrion, as orchestrion:@flue/runtime:<value>.

Suggested change
channelName: 'flueInit',
channelName: 'init',

span.setAttribute(GEN_AI_RESPONSE_MODEL, responseModel);
}

const provider = observation.request?.providerId ?? observation.request?.providerName;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both fields are required strings on ModelRequestInfo, so the fallback seems like it's not doing any work? I think just providerId is the correct value here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add first-party Flue instrumentation

2 participants