@datagol/pi-lens-extension
v0.6.0
Published
Pi coding-agent extension that traces agent runs to DataGOL Lens.
Readme
@datagol/pi-lens-extension
Traces Pi coding-agent
runs to DataGOL Lens. Maps Pi's event stream onto one Lens trace per agent run —
an llm span per model turn, a tool span per tool call — from inside the
pi --mode rpc subprocess.
Nothing is sent unless it is configured, and a tracing failure can never break the agent.
Install
pi install npm:@datagol/pi-lens-extension # global (~/.pi/settings.json)
pi install npm:@datagol/pi-lens-extension -l # project-local (.pi/settings.json)Pi reads the entry point from this package's pi.extensions manifest field, and
installs the runtime dependency (@datagol/lens-js) itself.
A host that spawns Pi programmatically and wants a pinned, offline-safe copy can
instead depend on this package and copy dist/index.js into
~/.pi/agent/extensions/lens/index.js at boot — Pi loads every directory under
extensions/ independently. That is what DataGOL AppX does, so the version that
runs is the one its lockfile pins.
Configure
All via environment variables on the Pi process.
| Variable | Required | Notes |
|---|---|---|
| DATAGOL_LENS_TRACING | yes | true to enable; anything else and the extension is fully inert |
| DATAGOL_LENS_API_KEY | yes | project (dgl_…) or platform (dglp_…) key. Not a user JWT — the JS SDK rejects those |
| DATAGOL_LENS_PROJECT_ID | yes | see below — this is part of the gate, not optional |
| DATAGOL_LENS_API_URL | no | defaults to http://localhost:8000 |
| DATAGOL_LENS_HIDE_INPUTS | no | true sends run shape and token counts only, no prompt or tool text |
DATAGOL_LENS_PROJECT_ID is enforced at startup because Lens's postTrace
throws without one and the SDK swallows that throw — so a missing project id
would otherwise give you a tracer that looks enabled and silently emits nothing.
The extension refuses to start instead, and says so in its log.
Attribution is picked up from the environment when the host provides it, and needs no extra configuration:
| Variable | Becomes |
|---|---|
| DATAGOL_SESSION_ID | trace session_id |
| DATAGOL_USER_ID | trace external_user_id |
| DATAGOL_COMPANY_ID | trace company_id — what drives Lens budgets and spend attribution |
| DATAGOL_ENV, DATAGOL_WORKSPACE_ID | trace tags |
What a trace looks like
One trace per agent run (agent_start → agent_end), named AppX:
llmspans (llm-turn-N), one per model call — the assistantmessage_start→message_endpair — carrying prompt / completion / total / cache-read / cache-write / reasoning tokens, the model id, and Pi's own cost figure. Lens re-prices server-side when it can resolve the model and keeps this figure when it cannot. The output holds the text, the tool calls the model asked for, and the stop reason.toolspans (tool: <name>), one per tool call, with the arguments, the text of the result the model saw, and the error status. Deliberately not nested under the model call: it ends before the tools it asked for start, so nesting would produce a child whose time range escapes its parent.metadata.llm_span_id,turn_indexandtool_call_idkeep the link queryable instead. A call that another tool made (parentToolCallId) is nested, under that tool, because it runs inside it.- The status is
errorwhen the run ended on a model error or an abort.
Hosting many sessions in one process
The default export reads everything from the environment once, which fits a Pi
process per session. A host that runs many sessions, users and companies in one
process builds the extension with createLensExtension and passes it to Pi as
an extension factory:
import { createLensExtension, createProjectResolver } from '@datagol/pi-lens-extension';
const lens = createLensExtension({
client, // anything with the SDK's postTrace
context: (ctx) => ({ // read when each trace opens
sessionId, companyId, externalUserId,
agentKey: 'DataVisualizationAgent', agentName: 'Dave', traceName: 'dave-agent',
tags: { mode }, metadata: { correlation_id },
}),
resolveProject: createProjectResolver({ apiUrl, apiKey, routing: 'per_company', fallbackProjectId }),
bracket: 'prompt', // one trace per prompt, closed on agent_settled
delivery: 'background', // do not hold the end of the run for the POST
onPending: (sent) => drain.add(sent),
log: (line) => console.log(`[lens] ${line}`),
fieldCap: 16_000,
});| Option | Default | Notes |
|---|---|---|
| context | — | Return undefined to skip a run. |
| resolveProject | — | Called when the trace is sent, with its company. createProjectResolver caches per company, is single-flight, caches a failure for 30 s, and never rejects. |
| bracket | 'run' | 'prompt' keeps one trace across the agent runs of one prompt (the overflow retry, a queued follow-up). |
| delivery | 'await' | 'background' hands each send to onPending instead of returning it to Pi. |
| log | none | The default export logs to the diag file. |
| hideInputs | false | |
| fieldCap | 4096 | |
The client is the host's, so the host sets its own POST timeout. The default export uses 10 s.
Operational notes
- The trace arrives when the run ends, not during it. The SDK's
TraceBuilderis one-shot and Lens never promotes arunningtrace tosuccess, so incremental publishing is not available to a client. For a long run, nothing is visible in Lens until it finishes. - It never writes to stdout or stderr. Pi's RPC JSON protocol lives there, so
a stray write corrupts the session. Diagnostics go to
~/.pi/agent/lens-tracer.log, which also records the resolved config at startup and the reason when tracing is disabled. - Every handler is wrapped. A bug in the tracer is logged and swallowed rather than propagated into Pi's event dispatch, where it would surface as an agent error.
- Large runs are capped. Because everything buffers until the end, the tracer stops recording span payloads past a span count or byte budget, keeping timings and token counts and noting the truncation once.
Development
npm install
npm test # bundles with esbuild, then drives dist/index.js through a fake PiThe tests import the built bundle on purpose: that is what npm ships and what
Pi loads. They cover the event→span mapping, token extraction, the disabled and
misconfigured gates, network failure isolation, aborts, and HIDE_INPUTS.
Released with the Lens SDKs on a single sdk-vX.Y.Z tag — all three package
versions must match. Its dependency range on @datagol/lens-js is widened by
hand, not on every release; see .github/workflows/publish-sdk.yml.
