Files
vscode/extensions/copilot/docs/monitoring/agent_monitoring.md
T
Zhichao Li ddb6f98ce6 feat(otel): Add OpenTelemetry GenAI instrumentation to Copilot Chat (#3917)
* feat: add OTel GenAI instrumentation foundation

Phase 0 complete:
- spec.md: Full spec with decisions, GenAI semconv, dual-write, eval signals,
  lessons from Gemini CLI + Claude Code
- plan.md: E2E demo plan (chat ext + eval repo + Azure backend)
- src/platform/otel/: IOTelService, config, attributes, metrics, events,
  message formatters, NodeOTelService, file exporters
- package.json: Added @opentelemetry/* dependencies

OTel opt-in behind OTEL_EXPORTER_OTLP_ENDPOINT env var.

* refactor: reorder OTel type imports for consistency

* refactor: reorder OTel type imports for consistency

* feat(otel): wire OTel spans into chat extension — Phase 1 core

- Register IOTelService in DI (NodeOTelService when enabled, NoopOTelService when disabled)
- Add OTelContrib lifecycle contribution for OTel init/shutdown
- Add `chat {model}` inference span in ChatMLFetcherImpl._doFetchAndStreamChat()
- Add `execute_tool {name}` span in ToolsService.invokeTool()
- Add `invoke_agent {participant}` parent span in ToolCallingLoop.run()
- Record gen_ai.client.operation.duration, tool call count/duration, agent metrics
- Thread IOTelService through all ToolCallingLoop subclasses
- Update test files with NoopOTelService
- Zero overhead when OTel is disabled (noop providers, no dynamic imports)

* feat(otel): add embeddings span, config UI settings, and unit tests

- Add `embeddings {model}` span in RemoteEmbeddingsComputer.computeEmbeddings()
- Add VS Code settings under github.copilot.chat.otel.* in package.json
  (enabled, exporterType, otlpEndpoint, captureContent, outfile)
- Wire VS Code settings into resolveOTelConfig in services.ts
- Add unit tests for:
  - resolveOTelConfig: env precedence, kill switch, all config paths (16 tests)
  - NoopOTelService: zero-overhead noop behavior (8 tests)
  - GenAiMetrics: metric recording with correct attributes (7 tests)

* test(otel): add unit tests for messageFormatters, genAiEvents, fileExporters

- messageFormatters: 18 tests covering toInputMessages, toOutputMessages,
  toSystemInstructions, toToolDefinitions (edge cases, empty inputs, invalid JSON)
- genAiEvents: 9 tests covering all 4 event emitters, content capture on/off
- fileExporters: 5 tests covering write/read round-trip for span, log, metric
  exporters plus aggregation temporality

Total OTel test suite: 63 tests across 6 files

* feat(otel): record token usage and time-to-first-token metrics

Add gen_ai.client.token.usage (input/output) and copilot_chat.time_to_first_token
histogram metrics at the fetchMany success path where token counts and TTFT
are available from the processSuccessfulResponse result.

* docs: finalize sprint plan with completion status

* style: apply formatter changes to OTel files

* feat(otel): emit gen_ai.client.inference.operation.details event with token usage

Wire emitInferenceDetailsEvent into fetchMany success path where full
token usage (prompt_tokens, completion_tokens), resolved model, request ID,
and finish reasons are available from processSuccessfulResponse.

This follows the OTel GenAI spec pattern:
- Spans: timing + hierarchy + error tracking
- Events: full request/response details including token counts

The data mirrors what RequestLogger captures for chat-export-logs.json.

* feat(otel): add aggregated token usage to invoke_agent span

Per the OTel GenAI agent spans spec, add gen_ai.usage.input_tokens and
gen_ai.usage.output_tokens as Recommended attributes on the invoke_agent span.

Tokens are accumulated across all LLM turns by listening to onDidReceiveResponse
events during the agent loop, then set on the span before it ends.

Ref: https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-agent-spans/

* feat(otel): add token usage attributes to chat inference span

Defer the `chat {model}` span completion from _doFetchAndStreamChat to
fetchMany where processSuccessfulResponse has extracted token counts.

The chat span now carries:
- gen_ai.usage.input_tokens (prompt_tokens)
- gen_ai.usage.output_tokens (completion_tokens)
- gen_ai.response.model (resolved model)

The span handle is returned from _doFetchAndStreamChat via the result
object so fetchMany can set attributes and end it after tokens are known.

This matches the chat-export-logs.json pattern where each request entry
carries full usage data alongside the response.

* style: apply formatter changes

* fix: correct import paths in otelContrib and add IOTelService to test

* feat: add diagnostic span exporter to log first successful export and failures

* feat: add content capture to OTel spans (messages, responses, tool args/results)

- Chat spans: add copilot.debug_name attribute for identifying orphan spans
- Chat spans: capture gen_ai.input.messages and gen_ai.output.messages when captureContent enabled
- Tool spans: capture gen_ai.tool.call.arguments and gen_ai.tool.call.result when captureContent enabled
- Extension chat endpoint: capture input/output messages when captureContent enabled
- Add CopilotAttr.DEBUG_NAME constant

* fix: register IOTelService in chatLib setupServices for NES test

* fix: register OTel ConfigKey settings in Advanced namespace for configurations test

* fix: register IOTelService in shared test services (createExtensionUnitTestingServices)

* fix: register IOTelService in platform test services

* feat(otel): enhance GenAI span attributes per OTel semantic conventions

- Change gen_ai.provider.name from 'openai' to 'github' for CAPI models
- Rename CopilotAttr to CopilotChatAttr, prefix values with copilot_chat.*
- Add GITHUB to GenAiProviderName enum
- Replace copilot.debug_name with gen_ai.agent.name on chat spans
- Add gen_ai.request.temperature, gen_ai.request.top_p to chat spans
- Add gen_ai.response.id, gen_ai.response.finish_reasons on success
- Add gen_ai.usage.cache_read.input_tokens from cached_tokens
- Add copilot_chat.request.max_prompt_tokens and copilot_chat.time_to_first_token
- Add gen_ai.tool.description to execute_tool spans
- Fix gen_ai.tool.call.id to read chatStreamToolCallId (was reading nonexistent prop)
- Fix tool result capture to handle PromptTsxPart and DataPart (not just TextPart)
- Add gen_ai.input.messages and gen_ai.output.messages to invoke_agent span (opt-in)
- Move gen_ai.tool.definitions from chat spans to invoke_agent span (opt-in)
- Add gen_ai.system_instructions to chat spans (opt-in)
- Fix error.type raw strings to use StdAttr.ERROR_TYPE constant
- Centralize hardcoded copilot.turn_count and copilot.endpoint_type into CopilotChatAttr
- Add COPILOT_OTEL_CAPTURE_CONTENT=true to launch.json for testing
- Document span hierarchy fixes needed in plan.md

* feat(otel): connect subagent spans to parent trace via context propagation

- Add TraceContext type and getActiveTraceContext() to IOTelService
- Add storeTraceContext/getStoredTraceContext for cross-boundary propagation
- Add parentTraceContext option to SpanOptions for explicit parent linking
- Implement in NodeOTelService using OTel remote span context
- Capture trace context when execute_tool runSubagent fires (keyed by toolCallId)
- Restore parent context in subagent invoke_agent span (via subAgentInvocationId)
- Auto-cleanup stored contexts after 5 minutes to prevent memory leaks
- Update test mocks with new IOTelService methods
- Update plan.md with investigation findings

* fix(otel): fix subagent trace context key to use parentRequestId

The previous implementation stored trace context keyed by chatStreamToolCallId
(model-assigned tool call ID), but looked it up by subAgentInvocationId
(VS Code internal invocation.callId UUID). These are different IDs that don't
match across the IPC boundary.

Fix: key by chatRequestId on store side (available on invocation options),
and look up by parentRequestId on subagent side (same value, available on
ChatRequest). Both reference the parent agent's request ID.

Verified: 21-span trace with subagent correctly nested under parent agent.

* fix(otel): add model attrs to invoke_agent and max_prompt_tokens to BYOK chat

- Set gen_ai.request.model on invoke_agent span from endpoint
- Track gen_ai.response.model from last LLM response resolvedModel
- Add copilot_chat.request.max_prompt_tokens to BYOK chat spans
- Document upstream gaps in plan.md (BYOK token usage, programmatic tool IDs)

* test(otel): add trace context propagation tests for subagent linkage

Tests verify:
- storeTraceContext/getStoredTraceContext round-trip and single-use semantics
- getActiveTraceContext returns context inside startActiveSpan
- parentTraceContext makes child span inherit traceId from parent
- Independent spans get different traceIds without parentTraceContext
- Full subagent flow: store context in tool call, retrieve in subagent

* fix(otel): add finish_reasons and ttft to BYOK chat spans, document orphan spans

- Set gen_ai.response.finish_reasons on BYOK chat success
- Set copilot_chat.time_to_first_token on BYOK chat success
- Document Gap 4: duplicate orphan spans from CopilotLanguageModelWrapper
- Identify all orphan span categories (title, progressMessages, promptCategorization, wrapper)

* docs(otel): update Gap 4 analysis — wrapper spans have actual token usage data

The copilotLanguageModelWrapper orphan spans are the actual CAPI HTTP
handlers, not duplicates. They contain real token usage, cache read tokens,
resolved model names, and temperature — all missing from the consumer-side
extChatEndpoint spans due to VS Code LM API limitations.

Updated plan.md with:
- Side-by-side attribute comparison table
- Three fix approaches (context propagation, span suppression, enrichment)
- Recommendation: Option 1 (propagate trace context through IPC)

* feat(otel): propagate trace context through BYOK IPC to link wrapper spans

- Pass _otelTraceContext through modelOptions alongside _capturingTokenCorrelationId
- Inject IOTelService into CopilotLanguageModelWrapper
- Wrap makeRequest in startActiveSpan with parentTraceContext when available
- This creates a byok-provider bridge span that makes chatMLFetcher's chat span
  a child of the original invoke_agent trace, bringing real token usage data
  into the agent trace hierarchy

* debug(otel): add debug attribute to verify trace context capture in BYOK path

* fix(otel): remove debug attribute, BYOK trace context propagation verified working

Verified: 63-span trace with Azure BYOK (gpt-5) correctly shows:
- byok-provider bridge spans linking wrapper chat spans into agent trace
- Real token usage (in:21458 out:1730 cache:19072) visible on wrapper chat spans
- hasCtx:true on all extChatEndpoint spans confirming context capture
- Two subagent invoke_agent spans correctly nested under main agent
- Zero orphan copilotLanguageModelWrapper spans

* refactor(otel): replace byok-provider bridge span with invisible context propagation

Add runWithTraceContext() to IOTelService — sets parent trace context
without creating a visible span. The wrapper's chat spans now appear
directly as children of invoke_agent, eliminating the noisy
byok-provider intermediary span.

Before: invoke_agent → byok-provider → chat (wrapper)
After:  invoke_agent → chat (wrapper)

* refactor(otel): remove duplicate BYOK consumer-side chat span

The extChatEndpoint no longer creates its own chat span. The wrapper's
chatMLFetcher span (via CopilotLanguageModelWrapper) is the single source
of truth with full token usage, cache data, and resolved model.

Before: invoke_agent → chat (empty, extChatEndpoint) + chat (rich, wrapper)
After:  invoke_agent → chat (rich, wrapper only)

* fix(otel): restore chat span for non-wrapper BYOK providers (Anthropic, Gemini)

The previous commit removed the extChatEndpoint chat span, which was correct
for Azure/OpenAI BYOK (served by CopilotLanguageModelWrapper via chatMLFetcher).
But Anthropic and Gemini BYOK providers call their native SDKs directly,
bypassing CopilotLanguageModelWrapper — so they need the consumer-side span.

Now: always create a chat span in extChatEndpoint with basic metadata
(model, provider, response.id, finish_reasons). For wrapper-based providers,
the chatMLFetcher also creates a richer sibling span with token usage.

* fix(otel): skip consumer chat span for wrapper-based BYOK providers

Only create the extChatEndpoint chat span for non-wrapper providers
(Anthropic, Gemini) that need it as their only span. Wrapper-based
providers (Azure, OpenAI, OpenRouter, Ollama, xAI) get a single rich
span from chatMLFetcher via CopilotLanguageModelWrapper.

Result: 1 chat span per LLM call for all provider types.

* fix: remove unnecessary 'google' from non-wrapper vendor set

* feat(otel): add rich chat span with usage data for Anthropic BYOK provider

Move chat span creation into AnthropicLMProvider where actual API response
data (token usage, cache reads) is available. The span is linked to the
agent trace via runWithTraceContext and enriched with:
- gen_ai.usage.input_tokens / output_tokens
- gen_ai.usage.cache_read.input_tokens
- gen_ai.response.model / response.id / finish_reasons

Remove consumer-side extChatEndpoint span for all vendors (nonWrapperVendors
now empty) since both wrapper-based and Anthropic providers create their
own spans with full data.

Next: apply same pattern to Gemini provider.

* feat(otel): add rich chat span for Gemini BYOK, clean up extChatEndpoint

- Add OTel chat span with full usage data to GeminiNativeBYOKLMProvider
- Remove all consumer-side span code from extChatEndpoint (dead code)
- Each provider now owns its chat span with real API response data:
  * CAPI: chatMLFetcher
  * OpenAI-compat BYOK: CopilotLanguageModelWrapper → chatMLFetcher
  * Anthropic: AnthropicLMProvider
  * Gemini: GeminiNativeBYOKLMProvider
- Fix Gemini test to pass IOTelService

* feat(otel): enrich Anthropic/Gemini chat spans with full metadata

Add to both providers:
- copilot_chat.request.max_prompt_tokens (model.maxInputTokens)
- server.address (api.anthropic.com / generativelanguage.googleapis.com)
- gen_ai.conversation.id (requestId)
- copilot_chat.time_to_first_token (result.ttft)

Now matches CAPI chat span attribute parity.

* feat(otel): add server.address to CAPI/Azure BYOK chat spans

Extract hostname from urlOrRequestMetadata when it's a URL string
and set as server.address on the chat span. Works for both CAPI
and CopilotLanguageModelWrapper (Azure BYOK) paths.

* feat(otel): add max_tokens and output_messages to Anthropic/Gemini chat spans

- gen_ai.request.max_tokens from model.maxOutputTokens
- gen_ai.output.messages (opt-in) from response text
- Closes remaining attribute gaps vs CAPI/Azure BYOK spans

* fix(otel): capture tool calls in output_messages for chat spans

When model responds with tool calls instead of text, the output_messages
attribute was empty. Now captures both text parts and tool call parts
in the output_messages, matching the OTel GenAI output messages schema.

Also: Azure BYOK invoke_agent zero tokens is a known upstream gap —
extChatEndpoint returns hardcoded usage:0 since VS Code LM API doesn't
expose actual usage from the provider side.

* fix(otel): capture tool calls in output_messages for Anthropic/Gemini BYOK spans

Same fix as CAPI — when model responds with tool calls, include them
in gen_ai.output.messages alongside text parts. All three provider
paths (CAPI, Anthropic, Gemini) now consistently capture both text
and tool call parts in output messages.

* fix(otel): add input_messages and agent_name to Anthropic/Gemini chat spans

- gen_ai.input.messages (opt-in) captured from provider messages parameter
- gen_ai.agent.name set to AnthropicBYOK / GeminiBYOK for identification

Closes the last attribute gaps vs CAPI/Azure BYOK chat spans.

* fix(otel): fix input_messages serialization for Anthropic/Gemini BYOK

- Map enum role values to names (1→user, 2→assistant, 3→system)
- Extract text from LanguageModelTextPart content arrays instead of
  showing '[complex]' for all messages
- Use OTel GenAI input messages schema with role + parts format

* docs(otel): add remaining metrics/events work to plan.md

Coverage matrix showing:
- Anthropic/Gemini BYOK missing: operation.duration, token.usage,
  time_to_first_token metrics, and inference.details event
- CAPI and Azure BYOK (via wrapper) fully covered
- Tool/agent/session metrics covered across all providers
- 4 tasks (M1-M4) to close the gap

* feat(otel): add metrics and inference events to Anthropic/Gemini BYOK providers

Both providers now record:
- gen_ai.client.operation.duration histogram
- gen_ai.client.token.usage histograms (input + output)
- copilot_chat.time_to_first_token histogram
- gen_ai.client.inference.operation.details log event

All metrics/events now have full parity across CAPI, Azure BYOK,
Anthropic BYOK, and Gemini BYOK.

* fix(otel): fix LoggerProvider constructor — use 'processors' key (SDK v2)

The OTel SDK v2 changed the LoggerProvider constructor option from
'logRecordProcessors' to 'processors'. The old key was silently
ignored, causing all log records to be dropped.

This is why logs never appeared in Loki despite traces working fine.

* docs: add agent monitoring guide with OTel usage and Claude/Gemini comparison

* docs: remove Claude/Gemini comparison from monitoring guide

* docs: add OTel comparison with Claude Code and Gemini CLI

* docs: reorganize monitoring docs — user guide + dev architecture

- agent_monitoring.md: polished user-facing guide (for VS Code website)
- agent_monitoring_arch.md: developer-facing architecture & instrumentation guide
- Removed internal plan/spec/comparison files from repo (moved to ~/Documents)

* fix(otel): restore _doFetchViaHttp body and _fetchWithInstrumentation after rebase

* fix(otel): propagate otelSpan through WebSocket/HTTP routing paths

The otelSpan was created in _doFetchAndStreamChat but not included
in returns from _doFetchViaWebSocket and _doFetchViaHttp, causing
the caller (fetchMany) to always receive undefined for otelSpan.

Fix: await both routing paths and spread otelSpan into the result.

* docs(otel): improve monitoring docs, add collector setup, fix trace context

- Expand agent_monitoring.md with detailed span/metric/event attribute tables
- Add BYOK provider coverage, subagent trace propagation docs
- Add Backend Considerations: Azure App Insights (via collector), Langfuse, Grafana
- Add End-to-End Setup & Verification section with KQL examples
- Add OTel Collector config + docker-compose for Azure App Insights
- Fix: emit inference details event before span.end() in chatMLFetcher
  (fixes 'No trace ID' log records in App Insights)
- Fix: pass active context in emitLogRecord for trace correlation
- Update launch.json to point at OTel Collector (localhost:4328)

* docs(otel): merge Backend Considerations and E2E sections to remove redundancy

* docs(otel): remove internal dev debug reference from user-facing guide

* docs(otel): remove Grafana section and Jaeger refs from App Insights section

* docs(otel): trim Backend section to factual setup guides, remove claims

* docs(otel): final accuracy audit — fix false claims against code

- Mark copilot_chat.session.start event as 'not yet emitted' (defined but no call site)
- Mark copilot_chat.agent.turn event as 'not yet emitted' (defined but no call site)
- Mark copilot_chat.session.count metric as 'not yet wired up'
- Fix OTEL_EXPORTER_OTLP_PROTOCOL desc: only 'grpc' changes behavior
- Fix telemetry kill switch claim: vscodeTelemetryLevel not wired in services.ts
- Remove false toolCalling.tsx instrumentation point from arch doc
- Fix docker-compose comments: wrong port numbers (16686→16687, 4318→4328)
- Add reference to full collector config file from inline snippet

* docs(otel): remove telemetry.telemetryLevel references — OTel is independent

* feat(otel): wire up session.start event, agent.turn event, and session.count metric

- emitSessionStartEvent + incrementSessionCount at invoke_agent start (top-level only)
- emitAgentTurnEvent per LLM response in onDidReceiveResponse listener
- Remove 'not yet wired' markers from docs

* chore: untrack .playwright-mcp/ and add to .gitignore

* chore: remove otel spec reference files

* chore(otel): remove OpenTelemetry environment variables from launch configurations

* fix(otel): add 64KB truncation limit for content capture attributes

Prevents OTLP batch export failures when large prompts/responses are
captured. Aligned with gemini-cli's limitTotalLength pattern.

Applied truncateForOTel() to all JSON.stringify calls feeding span
attributes across chatMLFetcher, toolCallingLoop, toolsService,
anthropicProvider, geminiNativeProvider, and genAiEvents.

* refactor(otel): make GenAiMetrics methods static to avoid per-call allocations

Aligned with gemini-cli pattern of module-level metric functions.
Eliminates 17+ throwaway GenAiMetrics instances per agent run.

* fix(otel): fix timer leak, cap buffered ops, rate-limit export logs

- storeTraceContext: track timers for clearTimeout on retrieval/shutdown,
  add 100-entry max with LRU eviction
- BufferedSpanHandle: cap _ops at 200 to prevent unbounded growth
- DiagnosticSpanExporter: rate-limit failure logs to once per 60s

* docs(otel): fix Jaeger UI port to match docker-compose (16687)

* chore(otel): update sprint plan — mark P0/P1 tasks done

* fix(otel): remove as any casts in BYOK provider content capture

Use proper Array.isArray + instanceof checks instead of as any[]
casts for LanguageModelChatMessage.content iteration.

* refactor(otel): extract OTelModelOptions shared interface

Replaces 3 duplicated inline type assertions for _otelTraceContext
and _capturingTokenCorrelationId with a single shared interface.

* refactor(otel): route OTel logs through ILogService output channel

Replace console.info/error/warn in NodeOTelService with a log callback.
OTelContrib logs essential status to the Copilot Chat output channel
for user troubleshooting (enabled/disabled, exporter config, shutdown).

* fix(otel): remove orphaned OTel ConfigKey definitions

OTel config is read via workspace.getConfiguration in services.ts,
not through IConfigurationService.get(ConfigKey). These constants
were unused dead code.

* test(otel): add comprehensive OTel instrumentation tests

- Agent trace hierarchy (invoke_agent → chat → execute_tool, subagent
  propagation, error states, metrics, events)
- BYOK provider span emission (CLIENT kind, token usage, error.type,
  content capture gating, parentTraceContext linking)
- chatMLFetcher two-phase span lifecycle (create → enrich → end,
  error path, operation duration metric)
- Service robustness (runWithTraceContext, startActiveSpan error
  lifecycle, storeTraceContext overwrite)
- CapturingOTelService reusable test mock for all OTel assertions

* chore: apply formatter import sorting

* chore: remove outdated sprint plan document

* feat(otel): add OTel configuration settings for tracing and logging

* fix(otel): ensure metric reader is flushed and shutdown properly
2026-03-02 20:46:30 +00:00

20 KiB

Monitoring Agent Usage with OpenTelemetry

Copilot Chat can export traces, metrics, and events via OpenTelemetry (OTel) — giving you real-time visibility into agent interactions, LLM calls, tool executions, and token usage.

All signal names and attributes follow the OTel GenAI Semantic Conventions, so the data works with any OTel-compatible backend: Jaeger, Grafana, Azure Monitor, Datadog, Honeycomb, and more.

Quick Start

Set these environment variables before launching VS Code:

# Enable OTel and point to a local collector
export COPILOT_OTEL_ENABLED=true
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318

# Launch VS Code
code .

That's it. Traces, metrics, and events start flowing to your collector.

Tip: To get started quickly with a local trace viewer, run Jaeger in Docker:

docker run -d --name jaeger -p 16686:16686 -p 4318:4318 jaegertracing/jaeger:latest

Then open http://localhost:16687 and look for service copilot-chat.


Configuration

VS Code Settings

Open Settings (Ctrl+,) and search for copilot otel:

Setting Type Default Description
github.copilot.chat.otel.enabled boolean false Enable OTel emission
github.copilot.chat.otel.exporterType string "otlp-http" otlp-http, otlp-grpc, console, or file
github.copilot.chat.otel.otlpEndpoint string "http://localhost:4318" OTLP collector endpoint
github.copilot.chat.otel.captureContent boolean false Capture full prompt/response content
github.copilot.chat.otel.outfile string "" File path for JSON-lines output

Environment Variables

Environment variables always take precedence over VS Code settings.

Variable Default Description
COPILOT_OTEL_ENABLED false Enable OTel. Also enabled when OTEL_EXPORTER_OTLP_ENDPOINT is set.
COPILOT_OTEL_ENDPOINT OTLP endpoint URL (takes precedence over OTEL_EXPORTER_OTLP_ENDPOINT)
OTEL_EXPORTER_OTLP_ENDPOINT Standard OTel OTLP endpoint URL
OTEL_EXPORTER_OTLP_PROTOCOL http/protobuf OTLP protocol. Only grpc changes behavior; all other values use HTTP.
COPILOT_OTEL_PROTOCOL Override OTLP protocol (grpc or http). Falls back to OTEL_EXPORTER_OTLP_PROTOCOL.
OTEL_SERVICE_NAME copilot-chat Service name in resource attributes
OTEL_RESOURCE_ATTRIBUTES Extra resource attributes (key1=val1,key2=val2)
COPILOT_OTEL_CAPTURE_CONTENT false Capture full prompt/response content
COPILOT_OTEL_LOG_LEVEL info Min log level: trace, debug, info, warn, error
COPILOT_OTEL_FILE_EXPORTER_PATH Write all signals to this file (JSON-lines)
COPILOT_OTEL_HTTP_INSTRUMENTATION false Enable HTTP-level OTel instrumentation
OTEL_EXPORTER_OTLP_HEADERS Auth headers (e.g., Authorization=Bearer token)

Activation

OTel is off by default with zero overhead. It activates when:

  • COPILOT_OTEL_ENABLED=true, or
  • OTEL_EXPORTER_OTLP_ENDPOINT is set, or
  • github.copilot.chat.otel.enabled is true

What Gets Exported

Traces

Copilot Chat emits a hierarchical span tree for each agent interaction:

invoke_agent copilot                           [~15s]
  ├── chat gpt-4o                              [~3s]  (LLM requests tool calls)
  ├── execute_tool readFile                    [~50ms]
  ├── execute_tool runCommand                  [~2s]
  ├── chat gpt-4o                              [~4s]  (LLM generates final response)
  └── (span ends)

invoke_agent — wraps the entire agent orchestration (all LLM calls + tool executions).

Attribute Requirement Example
gen_ai.operation.name Required invoke_agent
gen_ai.provider.name Required github
gen_ai.agent.name Required copilot
gen_ai.conversation.id Required a1b2c3d4-...
gen_ai.request.model Recommended gpt-4o
gen_ai.response.model Recommended gpt-4o-2024-08-06
gen_ai.usage.input_tokens Recommended 12500
gen_ai.usage.output_tokens Recommended 3200
copilot_chat.turn_count Always 4
error.type On error Error
gen_ai.input.messages Opt-in (captureContent) [{"role":"user",...}]
gen_ai.output.messages Opt-in (captureContent) [{"role":"assistant",...}]
gen_ai.tool.definitions Opt-in (captureContent) [{"type":"function",...}]

chat — one span per LLM API call (span kind: CLIENT).

Attribute Requirement Example
gen_ai.operation.name Required chat
gen_ai.provider.name Required github
gen_ai.request.model Required gpt-4o
gen_ai.conversation.id Required a1b2c3d4-...
gen_ai.request.max_tokens Always 2048
gen_ai.request.temperature When set 0.1
gen_ai.request.top_p When set 0.95
copilot_chat.request.max_prompt_tokens Always 128000
gen_ai.response.id On response chatcmpl-abc123
gen_ai.response.model On response gpt-4o-2024-08-06
gen_ai.response.finish_reasons On response ["stop"]
gen_ai.usage.input_tokens On response 1500
gen_ai.usage.output_tokens On response 250
copilot_chat.time_to_first_token On response 450
server.address When available api.github.com
copilot_chat.debug_name When available agentMode
error.type On error TimeoutError
gen_ai.input.messages Opt-in (captureContent) [{"role":"system",...}]
gen_ai.system_instructions Opt-in (captureContent) [{"type":"text",...}]

execute_tool — one span per tool invocation (span kind: INTERNAL).

Attribute Requirement Example
gen_ai.operation.name Required execute_tool
gen_ai.tool.name Required readFile
gen_ai.tool.type Required function or extension (MCP tools)
gen_ai.tool.call.id Recommended call_abc123
gen_ai.tool.description When available Read the contents of a file
error.type On error FileNotFoundError
gen_ai.tool.call.arguments Opt-in (captureContent) {"filePath":"/src/index.ts"}
gen_ai.tool.call.result Opt-in (captureContent) (file contents or summary)

Metrics

GenAI Convention Metrics

Metric Type Unit Description
gen_ai.client.operation.duration Histogram s LLM API call duration
gen_ai.client.token.usage Histogram tokens Token counts (input/output)

gen_ai.client.operation.duration attributes:

Attribute Description
gen_ai.operation.name Operation type (e.g., chat)
gen_ai.provider.name Provider (e.g., github, anthropic)
gen_ai.request.model Requested model
gen_ai.response.model Resolved model (if different)
server.address Server hostname
server.port Server port
error.type Error class (if failed)

gen_ai.client.token.usage attributes:

Attribute Description
gen_ai.operation.name Operation type
gen_ai.provider.name Provider name
gen_ai.token.type input or output
gen_ai.request.model Requested model
gen_ai.response.model Resolved model
server.address Server hostname

Extension-Specific Metrics

Metric Type Unit Description
copilot_chat.tool.call.count Counter calls Tool invocations by name and success
copilot_chat.tool.call.duration Histogram ms Tool execution latency
copilot_chat.agent.invocation.duration Histogram s Agent mode end-to-end duration
copilot_chat.agent.turn.count Histogram turns LLM round-trips per agent invocation
copilot_chat.session.count Counter sessions Chat sessions started
copilot_chat.time_to_first_token Histogram s Time to first SSE token

copilot_chat.tool.call.count attributes: gen_ai.tool.name, success (boolean)

copilot_chat.tool.call.duration attributes: gen_ai.tool.name

copilot_chat.agent.invocation.duration attributes: gen_ai.agent.name

copilot_chat.agent.turn.count attributes: gen_ai.agent.name

copilot_chat.time_to_first_token attributes: gen_ai.request.model

Events

gen_ai.client.inference.operation.details

Emitted after each LLM API call with full inference metadata.

Attribute Description
gen_ai.operation.name Always chat
gen_ai.request.model Requested model
gen_ai.response.model Resolved model
gen_ai.response.id Response ID
gen_ai.response.finish_reasons Stop reasons (e.g., ["stop"])
gen_ai.usage.input_tokens Input token count
gen_ai.usage.output_tokens Output token count
gen_ai.request.temperature Temperature (if set)
gen_ai.request.max_tokens Max tokens (if set)
error.type Error class (if failed)
gen_ai.input.messages Full prompt messages (captureContent only)
gen_ai.system_instructions System prompt (captureContent only)
gen_ai.tool.definitions Tool schemas (captureContent only)

copilot_chat.session.start

Emitted when a new chat session begins (top-level agent invocations only, not subagents).

Attribute Description
session.id Session identifier
gen_ai.request.model Initial model
gen_ai.agent.name Chat participant name

copilot_chat.tool.call

Emitted when a tool invocation completes.

Attribute Description
gen_ai.tool.name Tool name
duration_ms Execution time in milliseconds
success true or false
error.type Error class (if failed)

copilot_chat.agent.turn

Emitted for each LLM round-trip within an agent invocation.

Attribute Description
turn.index Turn number (0-indexed)
gen_ai.usage.input_tokens Input tokens this turn
gen_ai.usage.output_tokens Output tokens this turn
tool_call_count Number of tool calls this turn

Resource Attributes

All signals carry:

Attribute Value
service.name copilot-chat (configurable via OTEL_SERVICE_NAME)
service.version Extension version
session.id Unique per VS Code window

Add custom resource attributes with OTEL_RESOURCE_ATTRIBUTES:

export OTEL_RESOURCE_ATTRIBUTES="team.id=platform,department=engineering"

These custom attributes are included in all traces, metrics, and events, allowing you to:

  • Filter metrics by team or department
  • Create team-specific dashboards and alerts
  • Track usage across organizational boundaries

Note: OTEL_RESOURCE_ATTRIBUTES uses comma-separated key=value pairs. Values cannot contain spaces, commas, or semicolons. Use percent-encoding for special characters (e.g., org.name=John%27s%20Org).


Content Capture

By default, no prompt content, responses, or tool arguments are captured — only metadata like model names, token counts, and durations.

To capture full content:

export COPILOT_OTEL_CAPTURE_CONTENT=true

This populates these span attributes:

Attribute Content
gen_ai.input.messages Full prompt messages (JSON)
gen_ai.output.messages Full response messages (JSON)
gen_ai.system_instructions System prompt
gen_ai.tool.definitions Tool schemas
gen_ai.tool.call.arguments Tool input arguments
gen_ai.tool.call.result Tool output

Content is captured in full with no truncation.

Warning: Content capture may include sensitive information such as code, file contents, and user prompts. Only enable in trusted environments.


Example Configurations

OTLP/gRPC:

export COPILOT_OTEL_ENABLED=true
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
export OTEL_EXPORTER_OTLP_PROTOCOL=grpc

Remote collector with authentication:

export COPILOT_OTEL_ENABLED=true
export OTEL_EXPORTER_OTLP_ENDPOINT=https://collector.example.com:4318
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-token"

File-based output (offline / CI):

export COPILOT_OTEL_ENABLED=true
export COPILOT_OTEL_FILE_EXPORTER_PATH=/tmp/copilot-otel.jsonl

Console output (quick debugging):

{
  "github.copilot.chat.otel.enabled": true,
  "github.copilot.chat.otel.exporterType": "console"
}

Subagent Trace Propagation

When an agent invokes a subagent (e.g., via the runSubagent tool), Copilot Chat automatically propagates the trace context so the subagent's invoke_agent span is parented to the calling agent's execute_tool span. This produces a connected trace tree:

invoke_agent copilot                           [~30s]
  ├── chat gpt-4o                              [~3s]
  ├── execute_tool runSubagent                 [~20s]
  │   └── invoke_agent Explore                 [~18s]   ← child via trace context
  │       ├── chat gpt-4o                      [~2s]
  │       ├── execute_tool searchFiles         [~200ms]
  │       ├── execute_tool readFile            [~50ms]
  │       └── chat gpt-4o                      [~3s]
  ├── chat gpt-4o                              [~4s]
  └── (span ends)

This propagation works across async boundaries — the parent's trace context is stored when runSubagent starts and retrieved when the subagent begins its invoke_agent span.


Interpreting the Data

Traces — Visualize the full agent execution in Jaeger or Grafana Tempo. Each invoke_agent span contains child chat and execute_tool spans, making it easy to identify bottlenecks and debug failures. Subagent invocations appear as nested invoke_agent spans under execute_tool runSubagent.

Metrics — Track token usage trends by model and provider, monitor tool success rates via copilot_chat.tool.call.count, and watch perceived latency with copilot_chat.time_to_first_token. All metrics carry the same resource attributes (service.name, service.version, session.id) for consistent filtering.

Eventscopilot_chat.session.start tracks session creation. copilot_chat.tool.call events provide per-invocation timing and error details. gen_ai.client.inference.operation.details gives the full LLM call record including token usage and, when content capture is enabled, the complete prompt/response messages. Use gen_ai.conversation.id to correlate all signals belonging to the same session.


Initialization & Buffering

The OTel SDK is loaded asynchronously via dynamic imports to avoid blocking extension startup. Events emitted before initialization completes are buffered (up to 1,000 items) and replayed once the SDK is ready. If initialization fails, buffered events are discarded and all subsequent calls become no-ops — the extension continues to function normally.

First successful span export is logged to the console ([OTel] First span batch exported successfully via ...) to confirm end-to-end connectivity.


Backend Setup & Verification

Copilot Chat's OTel data works with any OTLP-compatible backend. This section covers setup and verification for recommended backends.

OTel Collector + Azure Application Insights

Azure Application Insights ingests OTel traces, metrics, and logs through an OTel Collector with the azuremonitor exporter. This repo includes a ready-to-use collector setup in docs/monitoring/.

1. Start the collector:

# Set your App Insights connection string (from Azure Portal → App Insights → Overview)
export APPLICATIONINSIGHTS_CONNECTION_STRING="InstrumentationKey=...;IngestionEndpoint=..."

# Start the OTel Collector
cd docs/monitoring
docker compose up -d

2. Verify the collector is healthy:

# Should return 200
curl -s -o /dev/null -w "%{http_code}" http://localhost:4328/v1/traces \
  -X POST -H "Content-Type: application/json" -d '{"resourceSpans":[]}'

3. Launch VS Code:

COPILOT_OTEL_ENABLED=true \
COPILOT_OTEL_CAPTURE_CONTENT=true \
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4328 \
code .

4. Generate telemetry — Send a chat message in Copilot Chat (e.g., "explain this file" in agent mode).

5. Verify in App Insights:

  • Traces: Application Insights → Transaction search → filter by "Trace" or "Request".

  • Logs: Application Insights → Logs:

    traces
    | where timestamp > ago(1h)
    | where message contains "GenAI" or message contains "copilot_chat"
    | project timestamp, message, customDimensions
    | order by timestamp desc
    
  • Metrics: Application Insights → Metrics → "Custom" namespace, or via Logs:

    customMetrics
    | where timestamp > ago(1h)
    | where name startswith "gen_ai" or name startswith "copilot_chat"
    | summarize avg(value), count() by name
    

Note: Traces typically appear within 1-2 minutes. Metrics may take 5-10 minutes.

Collector config (docs/monitoring/otel-collector-config.yaml):

receivers:
  otlp:
    protocols:
      http:
        endpoint: 0.0.0.0:4318
      grpc:
        endpoint: 0.0.0.0:4317

exporters:
  azuremonitor:
    connection_string: "${APPLICATIONINSIGHTS_CONNECTION_STRING}"
  debug:
    verbosity: basic

service:
  pipelines:
    traces:
      receivers: [otlp]
      exporters: [azuremonitor, debug]
    metrics:
      receivers: [otlp]
      exporters: [azuremonitor, debug]

Note: The docker-compose maps ports to 4328/4327 on the host to avoid conflicts. Adjust in docker-compose.yaml if needed. Add additional exporters (e.g., otlphttp/jaeger) to fan out to multiple backends. See docs/monitoring/otel-collector-config.yaml for the full config including batch processor and logs pipeline.

Langfuse

Langfuse is an open-source LLM observability platform with native OTLP ingestion and support for OTel GenAI Semantic Conventions. See the Langfuse docs for full details on capabilities and limitations.

Setup:

export COPILOT_OTEL_ENABLED=true
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:3000/api/public/otel
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Basic $(echo -n '<public-key>:<secret-key>' | base64)"
export COPILOT_OTEL_CAPTURE_CONTENT=true

Replace <public-key> and <secret-key> with your Langfuse API keys from Settings → API Keys.

Verify: Open Langfuse → Traces. You should see invoke_agent traces with nested chat and execute_tool spans.

Other Backends

Any OTLP-compatible backend works with Copilot Chat's OTel output. Some options:

Backend Description
Jaeger Open-source distributed tracing platform
Grafana Tempo + Prometheus Open-source traces + metrics stack

Refer to each backend's documentation for OTLP ingestion setup.


Security & Privacy

  • Off by default. No OTel data is emitted unless explicitly enabled. When disabled, the OTel SDK is not loaded at all — zero runtime overhead.
  • No content by default. Prompts, responses, and tool arguments require opt-in via captureContent.
  • No PII in default attributes. Session IDs, model names, and token counts are not personally identifiable.
  • User-configured endpoints. Data goes only where you point it — no phone-home behavior.
  • Dynamic imports only. OTel SDK packages are loaded on-demand, ensuring zero bundle impact when disabled.