HC / FIELD BRIEF
Field notes Coding-agent mod for BQAA
Sources 19

A build note, prepared 13 October 2026, updated 15 October 2026

A coding-agent mod that writes BigQuery Agent Analytics rows without blocking

A mod runs as code inside the host coding-agent CLI. This one turns each turn, model request, tool call and subagent into a BQAA agent_events row, and sends them to BigQuery from timers, so no hook waits on the network.

Built and tested on 13 October 2026 against v2.1.296 of the host CLI, and tested again on 14 October against v2.1.299, using only methods its mod documentation and type declarations describe. The code, plugins/bigquery-agent-analytics-mod, came in through pull request #7 to bigquery_agent_analytics_skill, merged on 15 October 2026 as commit 5566d7f on main. The sample rows and queries shown here are linked at commit 4e8951c of the pull request’s branch; the fixes that followed it left both files unchanged. Sample rows are output of the mod’s own test fixture, not production data; the demo below is real sessions writing to a test dataset. Section 11, on an admin-managed deployment, was checked on 15 October against the merged mod and v2.1.299, and corrected the same day after review.

Citation key: “mod docs” is the host CLI’s mod documentation (first entry under Sources); “ADK” is the BigQuery Agent Analytics plugin for ADK page; “Repo” is pull request #7, which holds the mod. Single-quoted names are page or section names in the cited source. What could not be checked is listed under NOT VERIFIED.

A demo recording, eleven numbered sections, a list of what was not verified, and 19 linked sources.

Demo: real sessions

A terminal recording of two real sessions, made on 15 October 2026 with v2.1.299 of the host CLI and the mod in live mode, writing to a test dataset. a) Fail open: with a token command that always fails, the prompt is still answered. The mod’s toast and transcript notice say no working credentials and name the fix. /bqaa-status shows the notice with the rows waiting, and at exit the rows go to a spill file on disk. b) With working credentials, the agent runs ls (allowed by a settings rule) and reads a file. Fifteen seconds in, the session replays the 8 rows that a) parked, and its /bqaa-status reports them sent. c) bq reads b)’s 15 rows back. Both TOOL_COMPLETED rows carry the recorded permission decision, accept from the configuration, and a count by event type follows. d) setup.sh checks the table and makes the usage views. The two views report the day’s requests, sessions and tokens by model and by user. Every query is capped at 100 MB billed. This copy is re-rendered from the recording’s text with two substitutions: the project id reads PROJECT wherever it appears, and the model name in the by-model view reads example-model. Waits are shortened in playback.

1. What it does

A mod is a plugin made of JavaScript or TypeScript event handlers that the host coding-agent CLI calls when an event happens — a tool call, a submitted prompt, a part of the interface being drawn — and each handler can watch the event, change it, or take it over (mod docs, ‘Mods overview’). Mods need v2.1.287 or later of the CLI (mod docs, ‘Turn mods on or off’). Every handler, called a hook, receives the mods API as $, the event as e, and next, which passes the event on to the other mods and then to the host’s own behaviour, and returns the result (mod docs, ‘Create a mod’).

bigquery-agent-analytics-mod uses that to record an agent session in the BigQuery Agent Analytics schema. It hooks twelve events and adds three commands:

  • Session: start (classic.SessionStart, which also follows /clear and resume) and end (session.end), each a STATE_DELTA row.
  • Prompt and turn: USER_MESSAGE_RECEIVED for each prompt that enters, INVOCATION_STARTING and INVOCATION_COMPLETED (or INVOCATION_ERROR) around each turn, and AGENT_RESPONSE for its answer.
  • Every model request: LLM_REQUEST and LLM_RESPONSE from the streaming turn.step event, with the token counts the engine reports and the request’s latency and time to first token (LLM_ERROR when no response arrived).
  • Every tool call: TOOL_STARTING and TOOL_COMPLETED with arguments, result, latency, tool errors and hook denials, and a flag when a permission prompt held the call up.
  • Subagents: AGENT_STARTING and AGENT_COMPLETED with their own span, their type in the agent column and their token totals.
  • Permission answers: the host’s own tool_decision records, which reach a mod’s telemetry.log hook as collector records, give each TOOL_COMPLETED row how its permission check answered: accept or reject, and where the answer came from (the configuration, a hook, or the person).
  • When rows cannot be written: while no credentials work or the identity lacks permission, a line in the band above the prompt (ui.render on AbovePrompt) says what is wrong, the fix for the token source in use, and how many rows wait. A toast, a transcript line and the status line say it too, and the next successful send clears it. No prompt waits on it.
  • Commands: /bqaa-status (queue depth, sent, dead-lettered, refused, dropped, last error, dead-letter files), /bqaa-flush and /bqaa-backfill.

The rows follow the ADK schema reference, including event_id from schema version 2 (ADK, ‘Schema Reference’), so they can share a table with ADK agents and with this repository’s settings-hook plugin, and the repository’s analysis skill reads them with its existing queries (Repo).

What came from the upstream reference mod

The upstream reference mod is another mod that copies the host’s own telemetry records into BigQuery. A side-by-side reading of it led to five additions, reimplemented in this mod’s own structure:

  • A credential-failure notice in the band above the prompt, as above. It comes with faster recovery: retries at least every 30 seconds while credentials fail, a retry as soon as a prompt is sent, and one immediate retry with a fresh token after a 401.
  • Opt-in identity, off by default because both settings add personal data. userIdFromCredentials sets user_id to the verified account of the access token each row is sent with; recordHostname adds the machine’s name to session_metadata.
  • Recorded permission decisions, as above.
  • A setup script, setup.sh. It creates the dataset, the table from the DDL, a separate views dataset and the views. It is safe to run again, and it has a --dry-run.
  • Usage views, daily_usage_by_model and daily_usage_by_user. They report requests, sessions and token counts per day. They count only this mod’s LLM_RESPONSE rows, since other writers can share the table and name their token counts differently. Rows are deduplicated on (timestamp, event_id), so a filter on the day still reaches the table’s day partitions.

Not adopted: a mode that refuses prompts while no credentials work. Every prompt is passed on as it came, whatever the credentials do. The notice says what to fix, and the rows wait in the queue or on disk.

2. Why a mod, not settings hooks

The repository already has a capture path: bigquery-agent-analytics-tracing, a plugin of settings hooks (tracing plugin). Settings hooks run “a shell command, HTTP request, or prompt” on a lifecycle event (mod docs, ‘Compare mods, settings hooks, skills, and MCP servers’); that plugin starts a Python process per event, and pull request #6, ‘Make tracing hooks non-blocking and fail-open’, open as of this note, reworks those foreground hooks because they could hang the CLI (PR #6). A mod runs inside the host CLI, and its API makes the non-blocking shape the natural one:

  • A hook that only observes returns next(e), and time spent waiting on next or a mods API call “doesn’t count” against the hook’s time limit (mod docs, ‘Run work in the background’).
  • Work that outlives one event “runs on a timer you start from session.start”, with $.clock.every and $.clock.after in place of setInterval and setTimeout (mod docs, ‘Run work in the background’).
  • A hook that throws is skipped and “the next handler runs in its place” (mod docs, ‘Handle a hook that fails’), so an observer fails open by default.

The mod holds itself to three rules. Each capture hook (prompt, turn, model request, tool and subagent events) calls next(e), records what it saw into an in-memory queue with synchronous, bounded work, and returns what next gave it unchanged; the one other call it waits on is the host’s $.session.id(), read for each event. No hook waits on the network or a process; two lifecycle hooks do bounded work of their own before passing their event on: session.start sets the writer up and registers the three commands, and session.end writes what is still queued to a spill file, waiting at most 800 ms inside the host’s end-of-session bound, the one wait on the disk. And the mod’s bookkeeping cannot throw into an event: the six observers the plugin validator lists as gating hooks with a catch (classic.SessionStart, classic.SubagentStart, classic.PermissionRequest, prompt.submit, telemetry.log, tool.call) carry a .catch(($, e, next) => next(e)) handler whose answer is “go on as if the mod were not here”, and the other hooks run their bookkeeping inside try blocks. No setting changes any of this: every prompt is passed on first, and no option makes a hook wait on credentials or on BigQuery.

The tests make the rules checkable. One makes BigQuery never answer, then sends 25 tool calls through the mod and expects each to return. Another checks that no hook, session.end included, called $.http.fetch or $.process.run. Four more send prompts while the token command fails, while BigQuery refuses the credentials, and while either never answers; each expects the prompt passed on with no request and no process run while the hook runs. As a check on the checks, awaiting the flush inside the tool.call hook made the never-answer test hit the test kit’s 5-second limit and fail: the same failure, in a test, that a person sees as the CLI hanging.

Judgement: the mods API does not make blocking impossible (a hook can still await a fetch), but it gives the right primitives a name — next, timers, a per-hook time limit — so the rule can be stated in code review and enforced by a test. The cost moves elsewhere: an in-memory queue can lose rows that a disk spool would not, which section 10 bounds.

3. Architecture

Architecture of the BigQuery Agent Analytics mod The host coding-agent CLI raises session, prompt, turn, model-request, tool and subagent events. The mod's hooks call next, build a BQAA row synchronously and put it in a bounded in-memory queue; that is the whole hot path. A background writer on a timer takes batches from the queue, gets an access token from a cached gcloud command, and posts them to BigQuery's insertAll with a timeout. Retryable failures back off and retry three times; rows that still fail, rows BigQuery refuses, and rows left at session end go to JSONL files in a dead-letter directory, one subdirectory per table, which /bqaa-backfill, the next session or recovery send again, each line only to the table it records. Host CLI (engine) events the mod hooks classic.SessionStart prompt.submit turn.start turn.step (streams) tool.call classic.SubagentStart turn.complete session.end Mod hooks (hot path) 1. call next(e) 2. build the BQAA row, synchronously: ids, spans, redaction, cut to budget 3. enqueue; return next’s result Bounded queue (memory) 5,000 rows / 8 MiB by default full: drops oldest, counts them Background writer $.clock.every(5 s) and after each main-loop turn token: $.process.run(gcloud …), cached in memory, refreshed on 401 batch ≤ 500 rows / 3 MiB insertId = event_id 10 s timeout ($.clock.after), 30 s host cap per fetch one request at a time take BigQuery POST …/tables/{t}/insertAll agent_events (BQAA schema v2) $.http.fetch Dead-letter dir, one per table retry-*.jsonlretries ran out rejected-*.jsonlrefused spill-*.jsonlexit, pressure after retries, or refused session.end: no request; what is queued goes to a spill file /bqaa-backfill, next session start, or once BigQuery answers again queue past 80% while failing: oldest half spilled, not dropped
The hot path (shaded) ends at the queue. Everything to its right and below runs from timers or commands, outside any hook’s dispatch, except the spill write at session end, which that hook waits for within its budget. Dashed lines are failure and recovery paths.
  1. Hot path. A hook calls next(e), then builds the row synchronously: ids and spans, secrets redacted (every value under a key that is not on the mod’s allowlist, at any depth and in JSON inside text, and any such key’s name that holds a credential; JSON-looking text too long or broken to parse dropped whole; credential shapes, URL credentials and credential-named lines in free text, best effort), payloads cut to maxPayloadChars within a character budget (a 2,760,000-character Write is copied in under 100 ms in a unit test), is_truncated set when anything was cut.
  2. Queue. In memory, bounded at 5,000 rows and 8 MiB of UTF-8 by default; when full it drops its oldest rows and counts them. While BigQuery is failing and the queue passes 80%, the writer moves the oldest half to disk instead.
  3. Writer. A $.clock.every timer (5 s by default), plus a send after each main-loop turn, runs one request at a time: a cached access token from $.process.run (default gcloud auth application-default print-access-token), batches of at most 500 rows and 3 MiB of UTF-8, under the 4 MiB that $.http.fetch takes in a request body (counted in characters, which never outnumber the bytes), and a 10-second client timeout raced with $.clock.after under the host’s own 30-second cap per fetch (mod docs, ‘Mods reference’, limits).
  4. Retries and refusals. 408, 429, 5xx, quota 403s, network errors and timeouts back off exponentially (1 s to 60 s) for up to three retries with the same insertIds. A 401 gets one immediate retry with a fresh token; while no credentials work, retries come at least every 30 seconds and the notice shows above the prompt; a 404 for the table creates it with the BQAA DDL’s partitioning and clustering; 400, access-denied 403s, a missing dataset and rows insertAll reports as invalid are refused. A 2xx answer counts as delivered only when it is a valid insertAll response: a body cut off at the response limit, or one of another shape, leaves the outcome unknown, so the rows are retried the same way and parked if the retries run out.
  5. Dead letter and backfill. $.fs has read, write, list, exists, stat and ancestors and nothing else, write “isn’t atomic”, and a read or write takes at most 4 MiB of one file (mod docs, ‘Mods reference’, API methods and limits), whose text is UTF-8. So each failure writes a new JSONL file (retry-, rejected- or spill-) that no writer touches again, of at most 3 MiB of UTF-8, in a subdirectory named after the table the rows were meant for; a row too large for a file on its own has its payload columns cut to fit. Each file ends with a completion record written after its rows (their count and a checksum), and a replay reads a file only when that record is there and matches: a file another session is still writing, or one left by a writer that stopped part-way, is kept as it is, never read or emptied, and /bqaa-status lists it. A replay reads only the configured table’s subdirectory and checks each line’s recorded table before sending it, so a line for another table is kept as written. A backfill that lands a file’s rows truncates it to zero bytes; what it leaves (rows that fail again, other tables’ lines) goes to new files first, each with its completion record, and only then is the file truncated, so with no rename in $.fs a write that fails leaves the file as it was. A file over 4 MiB is reported rather than passed over, and a per-file lease in $.store keeps two sessions off the same file.
  6. Session end. “All session.end hooks together” get 1.5 seconds by default (mod docs, ‘Mods reference’, limits). The mod starts no request there: the rows still queued, and any whose request has not answered, go to a spill file in the table’s subdirectory, and the hook waits at most 800 ms for that write before passing the event on. The next session sends the file 15 seconds after it starts, or /bqaa-backfill does; a row whose request was in flight at exit can arrive twice, and event_id dedups it.

Why tabledata.insertAll: the ADK plugin writes through the Storage Write API in Python and Java (ADK), which is gRPC, while $.http.fetch makes http or https requests with a string body (mod docs, ‘Use the mods API’). The ADK docs note that their Kotlin plugin also uses tabledata.insertAll, inserting rows “one at a time … synchronously on the invocation path” (ADK, ‘Kotlin support’); the mod uses the same API batched and off the hot path. Each row’s event_id doubles as its insertId, and a row sent twice (an ambiguous timeout, a backfill) keeps it, so the ADK docs’ dedup applies: QUALIFY event_id IS NULL OR ROW_NUMBER() OVER (PARTITION BY event_id ORDER BY timestamp) = 1 (ADK, ‘Delivery and deduplication’). QUALIFY is evaluated after GROUP BY, so a query that aggregates dedups in a CTE first, as the queries in section 8 do.

4. Install

You need the host CLI at v2.1.287 or later, a BigQuery dataset, and an identity with roles/bigquery.dataEditor on it that gcloud can mint a token for. The mod creates the table on first write if it is missing.

For one session, from a checkout

export BQAA_PROJECT_ID=my-gcp-project BQAA_DATASET=agent_analytics
claude --plugin-dir ./plugins/bigquery-agent-analytics-mod

--plugin-dir “loads a plugin directory for one session without installing it” (mod docs, ‘Create a mod’).

From the repository’s marketplace

The repository’s .claude-plugin/marketplace.json lists the mod beside the settings-hook plugin. From a clone of the repository:

claude plugin marketplace add ./
claude plugin install bigquery-agent-analytics-mod@bigquery-agent-analytics-plugin \
  --config project=my-gcp-project --config dataset=agent_analytics

Or one command adds the marketplace from GitHub and installs (--marketplace needs v2.1.292 or later). After the merge, it installed the mod as bigquery-agent-analytics-mod@bigquery-agent-analytics-plugin in an isolated configuration directory and saved both options:

claude plugin install bigquery-agent-analytics-mod \
  --marketplace haiyuan-eng-google/bigquery_agent_analytics_skill \
  --config project=my-gcp-project --config dataset=agent_analytics

A mod installs as a plugin, and a session that is already open needs /reload-plugins to load it (mod docs, ‘Install or update a mod’). Install this mod or the settings-hook tracing plugin for a given table, not both, or every event is written twice.

5. Configure

Options are the plugin’s userConfig, which the CLI shows in the install dialog and as /config rows; a string option left empty falls back to the BQAA_* environment variable the tracing plugin already reads, then to a default. An administrator can set them for every user and lock them: see section 11.

Options and their environment fallbacks. Numbers are held to the bounds shown.
OptionFallback, default, effect
project, datasetBQAA_PROJECT_ID (or GCP_PROJECT_ID, GOOGLE_CLOUD_PROJECT), BQAA_DATASET (or BQ_DATASET). Required; without them nothing is captured and /bqaa-status says why.
table, locationBQAA_TABLE, then agent_events; BQAA_LOCATION, then US (shown by /bqaa-status; insertAll is addressed by table).
enabled, dryRunOn, off. BQAA_TRACE_ENABLED=false turns capture off; BQAA_DRY_RUN=true writes rows as JSONL beside the dead-letter directory instead of sending.
maxPayloadChars16,384 (1,024 to 500,000). Cap per JSON payload column; past it the value is cut and is_truncated set.
flushIntervalMs5,000 (1,000 to 300,000). How often the writer sends.
deadLetterDirBQAA_DEAD_LETTER_DIR, then ~/.bqaa-mod/dead-letter; one subdirectory per table.
agentName, accessTokenCommandcoding-agent; gcloud auth application-default print-access-token (argv, no shell). BQAA_ACCESS_TOKEN skips the command.
userIdFromCredentials, recordHostnameOff, off; each adds personal data to the rows. With the first on, user_id is the verified email of the account of the access token each row is sent with. The account is looked up at Google’s token information endpoint, with the token in a POST body; until it is known, rows keep the configured user_id. With the second on, session_metadata.host_name carries the machine’s host name.
Environment onlyBQAA_USER_ID, BQAA_REQUEST_TIMEOUT_MS (10,000), BQAA_MAX_QUEUE_ROWS (5,000), BQAA_EXIT_FLUSH_MS (800: how long session end may wait for its spill file), BQAA_AUTO_CREATE_TABLE, BQAA_AUTO_BACKFILL.

Authentication

$.http.fetch is plain HTTPS, so the mod cannot use a Google client library; it needs an OAuth access token. The background writer, never a hook, runs the token command with $.process.run, which takes an argument list and “uses no shell” (mod docs, ‘Use the mods API’). With the default command that is Application Default Credentials (gcloud auth application-default login, or service-account impersonation configured for it). The token stays in memory and is reused for 45 minutes. On a 401 the writer gets a fresh one and retries at once. The token goes only to bigquery.googleapis.com, and, with userIdFromCredentials on, to Google’s token information endpoint in a POST body; $.http.fetch drops headers such as Authorization on a redirect to another origin (mod docs, ‘Use the mods API’). A service-account key file cannot be used directly, because the mods environment offers crypto.subtle.digest but no signing. While no credentials work, the notice above the prompt names the fix, for example gcloud auth application-default login; prompts are not held up.

6. Schema mapping

Each mod hook, the BQAA event_type it writes, and what the row carries.
Mod hookevent_typeContent and attributes
classic.SessionStartSTATE_DELTA{"session_start": true}; state_delta.start_source (startup, resume, clear, compact, fork), model, session_metadata (project, cwd, host_version); the host can raise the event before session.start has read the environment, so the row waits until it has, keeping the event’s time
prompt.submitUSER_MESSAGE_RECEIVED{"text_summary": prompt} once the prompt entered; prompt_origin, submitted_during_turn
turn.start (main loop)INVOCATION_STARTINGThe turn’s root span; turn_number. A subagent’s run starts with a turn.start of its own that names its loop (agentId): no row, no turn counted, and the main turn goes on.
turn.stepLLM_REQUEST, LLM_RESPONSE or LLM_ERRORRequest: model, effort, step index, message count, the user’s prompt on a turn’s first request. Response: requested tool names and text; usage_metadata; finish_reason; latency_ms.total_ms and time_to_first_token_ms
tool.callTOOL_STARTING, TOOL_COMPLETED{"tool", "tool_origin", "args" | "result"} (LOCAL, MCP, SUB_AGENT; small fields first, so a cut falls on the payload); latency_ms.total_ms; status ERROR with error_message for a tool error or a hook’s deny; permission_requested; permission_decision and permission_decision_source
telemetry.log (collector records)No row of its ownA tool_decision record sets permission_decision (accept, reject) and permission_decision_source on its call’s TOOL_COMPLETED, matched by tool_use_id. An accept arrives while the call runs; a rejection arrives just after the call returned, so a finished call waits up to 2 seconds for its decision and keeps the time it ended. Every record is passed on unchanged.
classic.SubagentStart, turn.complete (subagent)AGENT_STARTING, AGENT_COMPLETED or AGENT_ERRORagent = subagent type; its own span under the turn; token totals and duration
turn.complete (main loop)AGENT_RESPONSE, INVOCATION_COMPLETED or INVOCATION_ERRORThe answer; finish_reason, is_aborted, step count, the turn’s token totals, latency_ms.total_ms
session.endSTATE_DELTA{"session_end": true}; reason, turn count, duration

usage_metadata holds the names the repository’s tracing plugin and analysis skill read (prompt_tokens, counting cache reads and writes, completion_tokens, total_tokens) beside the four counts as the API reports them; the engine passes those counts on each turn.step result and the turn’s totals on turn.complete (mod docs, ‘Follow a turn’). A failed tool is a TOOL_COMPLETED row with status ERROR, as in the tracing plugin and the skill’s failure-rate query, where ADK writes TOOL_ERROR (ADK, ‘Tool usage (plugin lifecycle)’). Every row also carries root_agent_name, source: "coding_agent" and a writer block naming the mod and its version.

Ids and spans

  • session_id is the host CLI’s session id, read again for each event, so the rows after /clear, /resume or /branch carry the new one even where the classic hooks do not run (if the host refuses that read after such a change, rows carry none rather than the old one); invocation_id is the engine’s turn id; trace_id is a fresh 32-hex id per main-loop turn, shared by the subagents it starts.
  • The turn’s span is the root. Each model request is a span under it (its request and response rows share the span); each tool call is a span under the model request that asked for it; a subagent is a span under the turn, with its own requests and tools beneath it.
  • event_id is 32-hex, unique per row, and is insertAll’s insertId.

7. Sample rows

Sample output. These rows are the insertAll payload the mod built when its own fixture test, tests/sample-rows.test.ts, ran in the plugin test runner: a prompt, four model requests, Read, an Agent call that runs an Explore subagent, Edit, and Bash after a permission prompt. All but the last went to a stubbed insertAll; the last, the session-end row, is the one session end writes to a spill file for the next session to send. The model id example-model, the token counts and the turn’s 48,211 ms are fixture inputs; the other latency_ms values are what the run measured, a few milliseconds, because nothing really ran. Ids are random per run.

The fixture session, one line per row, in the order the mod queued them. Span ids shortened to 8 characters.
#event_typeagentspan_idparent_span_idlatency_msDetail
1STATE_DELTAcoding-agent02f1c31f——session start
2INVOCATION_STARTINGcoding-agentf5ceed92——
3USER_MESSAGE_RECEIVEDcoding-agentf5ceed92——prompt
4LLM_REQUESTcoding-agent014ed661f5ceed92—example-model step 0
5LLM_RESPONSEcoding-agent014ed661f5ceed92total 1, ttft 1example-model, 20,854 in / 96 out tokens, asks for Read
6TOOL_STARTINGcoding-agent1e90ac8c014ed661—Read
7TOOL_COMPLETEDcoding-agent1e90ac8c014ed661total 0Read
8LLM_REQUESTcoding-agent750abddef5ceed92—example-model step 1
9LLM_RESPONSEcoding-agent750abddef5ceed92total 0example-model, 19,758 in / 0 out tokens, asks for Agent
10TOOL_STARTINGcoding-agentebae5c8d750abdde—Agent
11AGENT_STARTINGExplorebcf3870cf5ceed92—subagent Explore
12LLM_REQUESTExplore5dfe0cbebcf3870c—example-model step 0
13LLM_RESPONSEExplore5dfe0cbebcf3870ctotal 0example-model, 5,279 in / 141 out tokens
14AGENT_COMPLETEDExplorebcf3870cf5ceed92total 6,4805,420 tokens
15TOOL_COMPLETEDcoding-agentebae5c8d750abddetotal 1Agent
16LLM_REQUESTcoding-agentb569e2cff5ceed92—example-model step 2
17LLM_RESPONSEcoding-agentb569e2cff5ceed92total 0example-model, 21,791 in / 388 out tokens, asks for Edit, Bash
18TOOL_STARTINGcoding-agent5b5f3b52b569e2cf—Edit
19TOOL_COMPLETEDcoding-agent5b5f3b52b569e2cftotal 0Edit
20TOOL_STARTINGcoding-agentbab87003b569e2cf—Bash
21TOOL_COMPLETEDcoding-agentbab87003b569e2cftotal 0Bash (permission prompt)
22LLM_REQUESTcoding-agentd42145f8f5ceed92—example-model step 3
23LLM_RESPONSEcoding-agentd42145f8f5ceed92total 0, ttft 0example-model, 22,430 in / 61 out tokens
24AGENT_RESPONSEcoding-agentf5ceed92——final answer
25INVOCATION_COMPLETEDcoding-agentf5ceed92—total 48,21185,168 tokens, 4 steps
26STATE_DELTAcoding-agentcfdb21a1——session end

One LLM_RESPONSE row, JSON columns expanded

{
  "timestamp": "2026-10-14T02:54:21.137Z",
  "event_id": "d0529c41b9e2e1968859a1305b4a165f",
  "event_type": "LLM_RESPONSE",
  "agent": "coding-agent",
  "session_id": "5c4b1d2e-8f7a-4c3b-9d1e-2a6f0b7c8d9e",
  "invocation_id": "3f0e2a71-9c4d-4b8e-a1f6-52d7c0e9b134",
  "user_id": "dev",
  "trace_id": "a4db76890e3b711d381938f9c05e0935",
  "span_id": "014ed66196c9a931",
  "parent_span_id": "f5ceed92dfb61a76",
  "content": {
    "tool_uses": [
      "Read"
    ],
    "response": "I'll look at the flush loop first."
  },
  "content_parts": [],
  "attributes": {
    "root_agent_name": "coding-agent",
    "source": "coding_agent",
    "model": "example-model",
    "model_version": "example-model",
    "usage_metadata": {
      "prompt_tokens": 20854,
      "completion_tokens": 96,
      "total_tokens": 20950,
      "input_tokens": 2310,
      "output_tokens": 96,
      "cache_read_input_tokens": 0,
      "cache_creation_input_tokens": 18544
    },
    "finish_reason": "tool_use",
    "step_index": 0,
    "writer": {
      "plugin": "bigquery-agent-analytics-mod",
      "version": "0.1.0",
      "label": "bigquery-agent-analytics-mod/0.1.0",
      "agent": "coding-agent",
      "mode": "insert_all"
    }
  },
  "latency_ms": {
    "total_ms": 1,
    "time_to_first_token_ms": 1
  },
  "status": "OK",
  "error_message": null,
  "is_truncated": false
}

One TOOL_COMPLETED row, as the insertAll payload carries it

The JSON columns travel as JSON text inside the row, which is how tabledata.insertAll takes BigQuery JSON values:

{"timestamp": "2026-10-14T02:54:21.142Z", "event_id": "12d434849fd84d98541e1e7436c55b97", "event_type": "TOOL_COMPLETED", "agent": "coding-agent", "session_id": "5c4b1d2e-8f7a-4c3b-9d1e-2a6f0b7c8d9e", "invocation_id": "3f0e2a71-9c4d-4b8e-a1f6-52d7c0e9b134", "user_id": "dev", "trace_id": "a4db76890e3b711d381938f9c05e0935", "span_id": "bab87003630f5369", "parent_span_id": "b569e2cf4f1bf6ab", "content": "{\"tool\":\"Bash\",\"tool_origin\":\"LOCAL\",\"result\":\"12 pass\\n0 fail\"}", "content_parts": [], "attributes": "{\"root_agent_name\":\"coding-agent\",\"source\":\"coding_agent\",\"tool_use_id\":\"toolu_c4d39d1a1c094555ae72affc428e50ac\",\"permission_requested\":true,\"writer\":{\"plugin\":\"bigquery-agent-analytics-mod\",\"version\":\"0.1.0\",\"label\":\"bigquery-agent-analytics-mod/0.1.0\",\"agent\":\"coding-agent\",\"mode\":\"insert_all\"}}", "latency_ms": "{\"total_ms\":0}", "status": "OK", "error_message": null, "is_truncated": false}

All 26 rows are in examples/sample-rows.jsonl (at commit 4e8951c).

8. Queries

sql/sample_queries.sql holds eight queries written with the analysis skill’s {PROJECT}.{DATASET}.{TABLE} placeholders and @start/@end/@trace_id parameters, so the skill’s run_bq.py can run them (the file at commit 4e8951c). Three of them, as the file has them:

Tokens and prompt-cache share per session and model

WITH responses AS (
  SELECT *
  FROM `{PROJECT}.{DATASET}.{TABLE}`
  WHERE event_type = 'LLM_RESPONSE'
    AND timestamp BETWEEN @start AND @end
  QUALIFY event_id IS NULL OR ROW_NUMBER() OVER (PARTITION BY event_id ORDER BY timestamp) = 1
)
SELECT
  session_id,
  JSON_VALUE(attributes, '$.model') AS model,
  COUNT(*) AS model_requests,
  SUM(CAST(JSON_VALUE(attributes, '$.usage_metadata.input_tokens') AS INT64)) AS input_tokens,
  SUM(CAST(JSON_VALUE(attributes, '$.usage_metadata.cache_read_input_tokens') AS INT64)) AS cache_read_tokens,
  SUM(CAST(JSON_VALUE(attributes, '$.usage_metadata.cache_creation_input_tokens') AS INT64)) AS cache_write_tokens,
  SUM(CAST(JSON_VALUE(attributes, '$.usage_metadata.output_tokens') AS INT64)) AS output_tokens,
  ROUND(SAFE_DIVIDE(
    SUM(CAST(JSON_VALUE(attributes, '$.usage_metadata.cache_read_input_tokens') AS INT64)),
    SUM(CAST(JSON_VALUE(attributes, '$.usage_metadata.prompt_tokens') AS INT64))), 3) AS cache_read_share
FROM responses
GROUP BY session_id, model
ORDER BY output_tokens DESC;

Tool failure rate and latency

WITH tools AS (
  SELECT *
  FROM `{PROJECT}.{DATASET}.{TABLE}`
  WHERE event_type = 'TOOL_COMPLETED'
    AND timestamp BETWEEN @start AND @end
  QUALIFY event_id IS NULL OR ROW_NUMBER() OVER (PARTITION BY event_id ORDER BY timestamp) = 1
)
SELECT
  JSON_VALUE(content, '$.tool') AS tool_name,
  JSON_VALUE(content, '$.tool_origin') AS tool_origin,
  COUNT(*) AS calls,
  COUNTIF(status = 'ERROR') AS failures,
  ROUND(COUNTIF(status = 'ERROR') / COUNT(*) * 100, 2) AS fail_rate_pct,
  COUNTIF(JSON_VALUE(attributes, '$.denied') = 'true') AS denied_by_hook,
  COUNTIF(JSON_VALUE(attributes, '$.permission_requested') = 'true') AS asked_permission,
  APPROX_QUANTILES(CAST(JSON_VALUE(latency_ms, '$.total_ms') AS INT64), 100)[OFFSET(50)] AS p50_ms,
  APPROX_QUANTILES(CAST(JSON_VALUE(latency_ms, '$.total_ms') AS INT64), 100)[OFFSET(95)] AS p95_ms
FROM tools
GROUP BY tool_name, tool_origin
ORDER BY failures DESC, calls DESC;

The span tree of one turn

SELECT
  child.timestamp,
  child.event_type,
  child.agent,
  child.span_id,
  child.parent_span_id,
  parent.event_type AS parent_event_type,
  COALESCE(JSON_VALUE(child.content, '$.tool'), JSON_VALUE(child.attributes, '$.model')) AS detail,
  CAST(JSON_VALUE(child.latency_ms, '$.total_ms') AS INT64) AS total_ms,
  child.status
FROM `{PROJECT}.{DATASET}.{TABLE}` AS child
LEFT JOIN (
  SELECT span_id, trace_id, ANY_VALUE(event_type) AS event_type
  FROM `{PROJECT}.{DATASET}.{TABLE}`
  WHERE timestamp BETWEEN @start AND @end
    AND trace_id = @trace_id
    AND event_type IN ('INVOCATION_STARTING', 'LLM_REQUEST', 'AGENT_STARTING')
  GROUP BY span_id, trace_id
) AS parent
  ON child.parent_span_id = parent.span_id AND child.trace_id = parent.trace_id
WHERE child.timestamp BETWEEN @start AND @end
  AND child.trace_id = @trace_id
QUALIFY child.event_id IS NULL OR ROW_NUMBER() OVER (PARTITION BY child.event_id ORDER BY child.timestamp) = 1
ORDER BY child.timestamp;

The other five deduplicate rows, show model latency by model (p50/p95 total, time to first token), give one line per turn, rank subagent types, and track the mod’s own health per day. setup.sh also makes two usage views over this mod’s rows (section 1). All eight parse as BigQuery SQL and ran over the 26 sample rows in DuckDB after a dialect translation, and so did the three above as extracted from this page (section 9); none has been run in BigQuery.

9. How it was checked

  • claude plugin validate passes on the mod and on the repository’s marketplace file. It lists the twelve hooked events and three commands, “answers its own command” for each command, “gating hook with .catch” for the six observers that carry one (classic.SessionStart, classic.SubagentStart, classic.PermissionRequest, prompt.submit, telemetry.log, tool.call), and the calls the module makes: $.clock.after, $.clock.every, $.command.register, $.env.get, $.fs.*, $.http.fetch, $.process.run, $.session.id, $.session.version, $.store.*, $.ui.invalidate, $.ui.log, $.ui.resolve, $.ui.status, $.ui.toast. Of those, $.ui.resolve and $.ui.invalidate draw and redraw the band, and $.ui.toast shows the notice’s toast. The validator is how the mod docs suggest you “list what a mod does” before installing it (mod docs, ‘Mods overview’).
  • claude plugin test: 176 tests pass, run with no session, sign-in, GCP or network; $.http.fetch, $.process.run, $.fs and $.store are stubbed and mock.clock drives the timers (mod docs, ‘Test a mod’), and the $.fs stubs measure files in UTF-8 bytes and refuse one over 4 MiB, as the host does. They cover the rows and spans, subagent runs in the order the host raises them (one invocation and one trace for the turn, a span per run, a SubagentStart that comes late or never), the session-start row raised before or during session.start’s setup, the non-blocking rules with session.end included, the queue bound, retries with stable insertIds, timeouts, token refresh, table creation, partial inserts, 2xx answers that are not valid insertAll responses, dead-letter files, replay that keeps two tables’ rows apart and writes what it leaves before emptying a file (a failed write included), completion records (a file part written, cut short or changed is not complete; a writer and a replayer interleaved lose no row; a file without its record is kept and reported), backfill, leases, the exit spill and its time bound, multibyte rows held to the file limit in bytes, /clear and resume with no classic hooks (a refused session-id read included), dry run, redaction (the allowlist at any depth and in JSON inside text, whole values of any type, JSON nested in strings to any encoding depth, JSON-looking text too long or broken to parse however it opens, key names that hold a credential (in nested objects, JSON text and tool arguments), credential names in text with their plural and numbered forms, URLs and webhook URLs, credential-named lines whatever they hold, values past 5,000 characters and past the scanned window, credentials that straddle a length cap, every place a diagnostic goes, and each reviewer’s probe run through capture, delivery and the dead-letter file), truncation that keeps a row’s identifying fields, refused environment reads, a re-fired session.start, and configuration. They also cover the additions:
    • the credential notice: the band, drawn through the test kit, keeping what other mods draw and giving way to a survey; one toast and one transcript line; the status line; its clearing; the fix for each token source;
    • recovery after signing in;
    • prompts passed on with no request or process while credentials fail, are refused or never answer;
    • the opt-in identity through a credential change, an expired token and a replay that keeps each row’s stored user;
    • permission decisions that arrive during a call, just after it, or never.
    Breaking a rule on purpose made the relevant tests fail: awaiting the flush inside tool.call, breaking the span parenting, and undoing, one at a time, the per-table replay directory, the per-line table check, diagnostic redaction, byte-based file sizes, the request-free session end, the token-variable fallback, stem matching of credential names, the oversized-file report, redaction before cutting (in the writer and where BigQuery’s error text is first cut), the check that a 2xx answer is a valid insertAll response, the redaction of values that already hold a marker, scanning past 4,096 characters, decoding JSON inside strings, pass and pwd as credential names, webhook URLs, URL user-info, dropping JSON text that cannot be parsed (rather than scrubbing it line by line), reading the session id only at start, keeping the old id after a session change, reading it in tool.call after the tool has started, emptying a replayed file before what it leaves is written elsewhere, keeping every key (no allowlist), redacting only credential names instead of everything not listed, dropping the plural and numbered forms of credential names, exempting no listed name from the text rule, treating lists that open with a scalar or JSON-encoded strings as plain text, scrubbing unparseable JSON-looking text instead of dropping it, leaving a key the mod writes off the list, reading every file as complete, skipping the record’s checksum, writing dead-letter or replacement files without a completion record, not reporting incomplete files, taking a subagent’s turn.start as a main-loop turn, writing its start row before SubagentStart names it, opening a second span when SubagentStart comes late, reusing an ended run’s span, nesting a run under a fresh trace, writing the session-start row with the defaults the module starts with, never writing a session-start row that waited, stamping it when written rather than when its event came, copying key names as they came, keeping a name past the scan budget, numbering placeholders over an object’s own names, not counting a replaced name, and checking names only in a payload’s own objects. The same was done for the additions: making the prompt hook wait for a token, dropping the notice or its clearing, stamping an account looked up for another token or for an expired one, and writing a call’s row without waiting for a late rejection.
  • TypeScript: the hooks module type-checks under tsc --strict against the type declarations the CLI wrote for v2.1.296 and against those for v2.1.299; the tests type-check against those for v2.1.299, as they use turn.start’s loop id, which the v2.1.296 declarations lack.
  • Real sessions: headless (-p) runs of the CLI with --plugin-dir on v2.1.296. Two runs with BQAA_DRY_RUN=true and a one-tool prompt (echo through Bash, on a small model), made before the session-end and dead-letter changes, wrote 12 rows each: a STATE_DELTA at each end, INVOCATION_STARTING, USER_MESSAGE_RECEIVED, two LLM_REQUEST/LLM_RESPONSE pairs, TOOL_STARTING/TOOL_COMPLETED, AGENT_RESPONSE and INVOCATION_COMPLETED, with the engine’s token counts and measured latencies (including time to first token) filled in, the tool span under the request that asked for it, and the session-end row written at exit. The engine starts a tool while the response that asked for it is still streaming, so the tool’s start row came before that response’s row, and the exact order differed between the runs. After those changes, /bqaa-status ran with no model call in a dry run, and once against a destination with a token command that always fails, so nothing could be sent: at exit its two STATE_DELTA rows went to a spill file in the destination’s subdirectory, each line naming its table, and the status named the token program without its arguments. On v2.1.299, a dry run whose prompt delegated a search to an Explore subagent wrote 25 rows: one INVOCATION_STARTING; one AGENT_STARTING, typed Explore, under the turn’s span; the turn’s 23 rows, the subagent’s and its handed-back answer included, in one trace and one invocation with no parent span missing; a session-end trace_count of 1; and a session-start row with the loaded user, writer mode and host version, as on the rows after it. Live, on v2.1.299:
    • A first recording, on 14 October, wrote one session’s 14 rows to a test table created from the DDL, the session-end row through a spill file that the next session sent 15 seconds in, and bq read all 14 back.
    • The demo above, recorded on 15 October, adds the failure path. Session a), whose token command always fails, answered its prompt and parked its 8 rows. Session b) sent them 15 seconds in, sent its own 15 rows while open (both TOOL_COMPLETED rows with an accept decision from the configuration), and spilled its session-end row at exit.
    • bq read b)’s 15 rows back, and the views counted 4 requests over 2 sessions for the day. Every query was capped at 100 MB billed, and each billed 0 bytes.
    A headless probe on v2.1.299 had three findings:
    • the host’s collector records reach a mod with no telemetry settings;
    • an accepted tool decision arrives before its call returns;
    • a rejected one arrives just after.
    That order is why a finished call waits for its decision. Runs on one machine are not a benchmark, so no timings are quoted here.
  • Install path: claude plugin marketplace add ./ and claude plugin install bigquery-agent-analytics-mod@bigquery-agent-analytics-plugin --config … succeeded in an isolated configuration directory, storing the options under pluginConfigs.
  • Setup script and views:
    • setup.sh passes 38 offline checks against a stand-in bq that logs its calls. Plain names are required before any call, and a dry run calls nothing.
    • Both views ran in DuckDB over a fixture that several writers share, and in BigQuery over the same fixture as literal rows. Each time they counted only this mod’s requests, sessions and tokens.
    • A BigQuery dry run with one day’s filter reads 0 bytes of the other days.
    • In the demo, setup.sh ran against the test project, where both datasets and the table already existed, and made the two views.
  • Admin-managed deployment (section 11):
    • 26 scenarios ran on the Linux build of v2.1.299, in an offline container. The managed-settings file and a marketplace directory, holding the merged mod and a probe mod, were writable only by root, and sessions ran as an ordinary user.
    • They checked where options and environment variables come from, and which lower settings lose to the policy. They also covered the guard’s options, the sideload and marketplace locks, safe mode and --bare, and a user’s mod hooking the mod’s reads.
    • The real mod’s /bqaa-status ran under the policy.
    • After review, the mod’s token command ran with a repository’s CLOUDSDK_PYTHON and PATH, against an administrator-owned stand-in for the credential tool. A repository’s settings also set the four delivery variables, with and without the policy’s pins.
    • On the macOS build, the credential tool’s own launcher ran a stand-in interpreter named by CLOUDSDK_PYTHON and a stand-in helper found through PATH. It also read a credentials file and a configuration directory named by variables. None of these printed a token.
    • Two checks ran on the macOS build: a post-merge install from GitHub, and the order of a user’s own settings with no policy.
    • One read-only check, printing only true or false, found that a per-user default-credentials token carries a verified email.
  • SQL: the DDL and the eight queries parse with sqlglot’s BigQuery dialect; translated to DuckDB, all eight ran over the 26 sample rows with the expected results (one turn, 48,211 ms, five model requests, four tool calls, one subagent). The three queries in section 8 and the README’s example were also checked as extracted from this page and the README, and ran the same way.

10. Limitations

  • Mods are early access: “this surface may change between releases without notice”, in the header of the type declarations the CLI (v2.1.296) writes beside a mod. Tested with 2.1.296 and 2.1.299.
  • A subagent’s run is told from a main-loop turn by the loop id its turn.start carries (agentId, in the type declarations from v2.1.299); a host that raised turn.start for a subagent without it would have that run recorded as a main-loop turn.
  • Writes use tabledata.insertAll, the legacy streaming API, not the Storage Write API the ADK Python and Java plugins use; its quotas and pricing apply, and its insertId dedup is best effort, so queries should dedup on event_id.
  • LLM_REQUEST rows carry the user’s prompt on a turn’s first request and no conversation history or system prompt; reading them per request would put $.session.messages() on the hot path. content_parts is empty.
  • A tool’s total_ms covers the whole tool.call chain, including a permission prompt (flagged) and PreToolUse hooks. A model request’s time to first token is measured at the first text, thinking or tool chunk that reaches the mod’s hook.
  • A subagent’s span sits under its turn, not under the Agent tool call that started it: the events seen carry no reliable link between the two.
  • No HITL_* rows. The answer to a permission prompt is recorded on the call’s TOOL_COMPLETED row (permission_decision, permission_decision_source), from the host’s tool_decision record. A rejection that arrives more than 2 seconds after its call returned is not recorded.
  • The usage views report token counts, not prices, and count only this mod’s rows; other writers sharing the table are left out.
  • The in-memory queue is lost when the hooks module reloads or its worker crashes — at most one flush interval of rows plus any batch in backoff. A disk spool would avoid that at the cost of disk work per event.
  • Rows queued at exit reach BigQuery when a later session starts (15 seconds in) or /bqaa-backfill runs; until then they wait in a spill file.
  • Rows parked for a table are sent only by a session configured for that table; after switching tables, the old table’s rows wait until a session runs with its settings again.
  • $.fs cannot append, rename or delete: one file per failure, truncated rather than removed after a backfill.
  • A dead-letter file without a matching completion record is never replayed: one left by a writer that stopped part-way, or written by an earlier version of the mod, stays on disk, listed by /bqaa-status, for a person to look at.
  • The type declarations mark $.process.run as “CLI only”; where the token command cannot run, set BQAA_ACCESS_TOKEN.
  • Where an organization manages the host CLI, classic.SessionStart, classic.SubagentStart and classic.PermissionRequest pass over a plugin a person installs, as claude plugin validate reports. Installed that way, the mod records no session-start row, records each subagent with an inferred AGENT_STARTING row typed subagent, and flags no permission prompts; rows still carry the current session id. Installed as the organization’s mod (section 11), it received classic.SessionStart even under a policy that keeps users’ hooks out; the other two were not exercised there.
  • Redaction is by allowlist: in content and attributes, at any depth and in JSON inside their text, a value is kept only under a key on the mod’s list (the fields it writes, such as ids, token counts, timings, model and tool names; and free-text fields: the prompt, the answer, a tool’s arguments and result, error text and the built-in tools’ text arguments). Under any other key the value becomes [REDACTED], whatever it holds, so an MCP tool’s own arguments and JSON output are mostly redacted. A name that is not on the list and itself holds a credential shape, a URL with user-info or a credential-named parameter, or a credential-named value becomes [REDACTED_KEY:n], numbered within its object. Text that looks like JSON (an object, a list opening with any value, or a JSON-encoded object or list) is parsed and held to the same list; when it cannot be parsed whole (too long to scan, or not valid JSON) it is dropped and marked, never scrubbed line by line. Other text is scanned for known credential shapes, URL credentials and credential-named values (plural and numbered names included), best effort: JSON that follows other text (a file view with line numbers, a log line) is free text, where a value nested on a later line than its credential name is missed, and a credential-named line can also lose a little more than the credential (a type name in code). The table holds prompts, answers, tool arguments and results, cut to maxPayloadChars.

11. Admin-managed deployment

Can one administrator configure the mod so that every user’s sessions trace into one BigQuery dataset? Yes, and most of it works today with no change to the mod. It goes through the host CLI’s managed settings: a policy an organization deploys to every machine, which no user, project or command-line setting overrides (mod docs, ‘Deploy managed settings’). The setup is about half a day to a day per platform. Anything that needs mod code is marked Proposed, not yet implemented.

Everything under ‘Works today’ was observed on 15 October 2026 with v2.1.299 of the host CLI and the mod as merged. The host’s Linux build ran in an offline container, with a managed-settings file only root could write, and the sessions ran as an ordinary user.

Works today, with no code change

  • Install it for everyone. The administrator copies the mod into a marketplace directory that users cannot write, and the policy names that directory and enables the mod. The mod then counts as the organization’s (mod docs, ‘Manage mods for your organization’). It loaded ahead of users’ own mods, and a user who disabled it in their own settings, or turned all hooks off, did not unload it.
  • Pin the options. The policy’s pluginConfigs entry sets the mod’s options key by key, and nothing lower changed a pinned key. A user’s settings, --settings, a repository’s settings and exported variables all lost. claude plugin configure still printed “Configuration saved”, and the session kept the policy’s value. A key the policy leaves unset still takes the user’s value.
  • Pin what environment variables can change. Each of these works even when the matching option is pinned:
    • BQAA_TRACE_ENABLED=false turns capture off;
    • BQAA_DRY_RUN=true turns a dry run on;
    • an exported BQAA_ACCESS_TOKEN replaces the token command.
    Four delivery settings exist only as variables, and a repository’s settings can set them too:
    • BQAA_AUTO_BACKFILL=false stops parked rows from being replayed;
    • a small BQAA_MAX_QUEUE_ROWS drops the oldest queued rows;
    • BQAA_EXIT_FLUSH_MS=0 can cut off the last rows at exit;
    • BQAA_REQUEST_TIMEOUT_MS sets every request’s time limit.
    The policy’s env block replaces what a user exports or a repository sets, so pin all of these there too, the four delivery settings at their defaults. With both pins, a user’s BQAA_TRACE_ENABLED=false left capture on; with only the option pinned, it turned capture off. Without the four pins, a repository’s settings changed all four for the organization’s copy; with them, it read the defaults.
  • Mark unverified identities. With userIdFromCredentials pinned on, user_id is the verified email of the token’s account. A policy value BQAA_USER_ID=unverified makes every row whose account is not known say so, rather than carry a name the user picked. Rows parked without a token carried unverified, not the user’s exported name. This holds for rows the session captures. Rows replayed from the local spool keep the user_id stored in their file, and the person can edit those files. So a file written before the rollout, or changed, can still send another name.
  • Keep other copies out (optional, and fleet-wide: these apply to every plugin, not just this one). Each did what it says:
    • the host’s built-in guard can refuse every mod that is not the organization’s (allowManagedModsOnly);
    • disableSideloadFlags refuses --plugin-dir;
    • strictKnownMarketplaces allows only the listed marketplace sources.
  • Other mods cannot feed it false values. A user’s mod hooked environment and settings reads to return false values. The guard bypassed it, and the organization’s mod read the true values. Under allowManagedHooksOnly, the organization’s copy still loaded and still received classic.SessionStart.
  • Fixed behaviour needs no pin. Redaction is always on; only the payload cap, maxPayloadChars, is an option. A credential failure always fails open with the notice, since the mod has no setting that blocks prompts. Under the policy, a pinned token command that failed gave the usual notice, naming that command.

A policy that does all of this. The names are placeholders; the file’s path on each system is in the host docs.

{
  "extraKnownMarketplaces": {
    "org-tools": { "source": { "source": "directory", "path": "/opt/org/agent-plugins" } }
  },
  "enabledPlugins": { "bigquery-agent-analytics-mod@org-tools": true },
  "pluginConfigs": {
    "bigquery-agent-analytics-mod@org-tools": {
      "options": {
        "project": "my-gcp-project",
        "dataset": "agent_analytics",
        "table": "agent_events",
        "location": "US",
        "enabled": true,
        "dryRun": false,
        "accessTokenCommand": "/opt/google-cloud-sdk/bin/gcloud auth application-default print-access-token",
        "userIdFromCredentials": true,
        "recordHostname": false,
        "maxPayloadChars": 16384,
        "flushIntervalMs": 5000,
        "agentName": "coding-agent"
      }
    }
  },
  "env": {
    "BQAA_TRACE_ENABLED": "true",
    "BQAA_DRY_RUN": "false",
    "BQAA_ACCESS_TOKEN": "",
    "BQAA_USER_ID": "unverified",
    "BQAA_AUTO_CREATE_TABLE": "false",
    "BQAA_AUTO_BACKFILL": "true",
    "BQAA_MAX_QUEUE_ROWS": "5000",
    "BQAA_EXIT_FLUSH_MS": "800",
    "BQAA_REQUEST_TIMEOUT_MS": "10000"
  }
}

Optional and fleet-wide, in the same file (the two pluginConfigs entries merge):

{
  "pluginConfigs": { "cc-plugin-sec-default@builtin": { "options": { "allowManagedModsOnly": true } } },
  "disableSideloadFlags": true,
  "strictKnownMarketplaces": [ { "source": "directory", "path": "/opt/org/agent-plugins" } ]
}
What each policy entry pins, and what the checks saw.
EntryPins, and what was seen
project, dataset, table, locationThe destination. /bqaa-status showed the pinned target over a user option, a user variable and an exported project.
enabled and BQAA_TRACE_ENABLEDCapture on. Without the variable pin, an exported BQAA_TRACE_ENABLED=false turned capture off.
dryRun and BQAA_DRY_RUNLive writes. A user’s dryRun: true was ignored.
accessTokenCommand, and BQAA_ACCESS_TOKEN set emptyThe token command’s program and arguments. An exported token was ignored and the pinned command ran. The command’s environment is not pinned; see below.
userIdFromCredentials and BQAA_USER_IDThe identity of rows the session captures: the verified email of the token’s account, else unverified. Replayed rows keep what their file says.
BQAA_AUTO_BACKFILL, BQAA_MAX_QUEUE_ROWS, BQAA_EXIT_FLUSH_MS, BQAA_REQUEST_TIMEOUT_MS at their defaultsReplay on, and the queue, exit and request limits at their defaults. Without these pins, a repository’s settings changed all four for the organization’s copy.
BQAA_AUTO_CREATE_TABLE set to falseUsers’ credentials never create the table; the administrator makes it once, with setup.sh.
recordHostname, maxPayloadCharsThe host name stays out, and the payload cap is fixed, pinned like the other options. These two were not read back one by one.

To check one machine, claude -p /bqaa-status prints the pinned target with no model call, and the debug log says the mod loaded ahead of users’ mods.

What no setting can enforce

  • A person can start a session without the mod. The host’s safe mode (a flag or an environment variable) and --bare both skip installed plugins, the organization’s included, and managed settings bind only the host CLI.
  • A local administrator can edit the managed settings.
  • The token command’s environment. The policy pins the command’s program and arguments, but the command inherits the session’s environment, a repository’s settings included.
    • In the checks, a repository’s CLOUDSDK_PYTHON made the pinned credential tool run the repository’s own interpreter, and a repository’s PATH ran its own helper inside the same command. The real tool’s launcher behaves the same way.
    • The policy’s env block can pin a named variable such as CLOUDSDK_PYTHON, which stopped the first case. But every tool in the session then gets that value, and PATH cannot be pinned that way.
    • The fix is proposed below.
  • Replayed rows keep their stored identity. Rows parked in a spill or retry file are sent as the file holds them. The file sits in the person’s own directory, protected by a checksum, not a signature, so a file written before the rollout, or edited, can send another user_id.
  • Row content is what the writer sends. Whoever holds the insert permission can write rows through the API with any user_id. BigQuery does not record who streamed which row: insertAll is among the methods that write no audit log (BigQuery audit logs).
  • BigQuery has no per-person cap on streaming inserts; its custom quotas cover query bytes only (custom quotas).

Credentials, access and cost

  • Credentials. Each person’s own default credentials are the default and the recommended model.
    • The token of a person signed in with gcloud’s default scopes carried a verified email. The check printed only true or false.
    • Impersonating one writer service account gives every row the same identity at best: that account’s email, and only when its token carries the email scope.
    • Workforce and workload identity federation tokens cannot be introspected, so the mod finds no email for them (token types).
    • A key file on every machine is not recommended.
  • Writers. insertAll needs bigquery.tables.updateData and bigquery.tables.get on the table, and bigquery.datasets.get on the dataset (insertAll permissions).
    • An insert-only grant: roles/bigquery.metadataViewer on the dataset, plus a custom role holding only bigquery.tables.updateData, granted on the table alone (table-level access).
    • Not roles/bigquery.dataEditor: it can also read every row, and with them every person’s prompts.
  • Readers. Analysts query the views, which sit in the separate dataset setup.sh makes. Authorized on the events dataset, they need no access to the table (authorized views).
    • For raw rows, a row access policy with FILTER USING (user_id = SESSION_USER()) shows each person their own rows (row access policies).
    • It needs user_id from credentials, and it filters reads: it does not stop a writer from naming someone else.
  • Administrators. Setting up needs more than running.
    • Once, to set up:
      • setup.sh runs its DDL as query jobs, which need bigquery.jobs.create on the project they run from (running queries).
      • Making the two datasets needs bigquery.datasets.create on the project (creating datasets); a grant on a dataset cannot give it before the dataset exists.
      • Making the custom writer role needs Role Administrator on the project (custom roles).
      • Grant these to whoever sets up, or have a project owner make the datasets and the role first.
    • After that, roles/bigquery.dataOwner on the two datasets covers the grants, the view authorization, row access policies and retention. Add roles/bigquery.jobUser on one project, for the DDL those changes run as.
  • Cost and retention.
    • insertAll costs $0.01 per 200 MiB, each row counted as at least 1 KB (pricing). The demo’s rows were about 1 KB each.
    • Throughput limits are per project, 1 GB/s in the US and EU multi-regions, and at most 500 rows per request are recommended: the mod’s own batch cap (quotas).
    • Set a partition expiration on the table (partition expiration). Neither setup.sh nor the mod sets one.

Proposed, not yet implemented

Proposed, not yet implemented. These need mod code, and none is written. The estimate is six to seven days, plus review.

  • The policy decides, and the mod says so.
    • The mod reads the managed policy itself: the mods API’s $.settings.read({ source: 'policy' }) returned it in the checks.
    • It resolves each setting in this order: the policy, then the user’s settings and environment, then a repository’s.
    • A pinned option then holds on its own. No variable can flip enabled or dryRun, or replace a pinned token command.
    • Under a policy, a repository’s settings no longer pick the destination, the token command, or the replay, queue, exit and request settings.
  • The token command runs in an environment the administrator controls. The mods API can set a child process’s variables but not remove them, so this has two parts:
    • The mod sets every variable that steers the command’s interpreter, executable search, loaders, or credential and configuration files to the policy’s value or to empty, before it runs the command. This covers, for example, CLOUDSDK_PYTHON, PATH and GOOGLE_APPLICATION_CREDENTIALS.
    • The policy pins a launcher in the administrator’s own directory. The launcher clears its environment before it starts the credential tool.
    • An acceptance test replays this section’s counterexample. With the change, a repository’s interpreter and PATH leave no trace, and the token still comes back.
  • A locked marker. /bqaa-status shows each setting’s value and its source, such as dataset agent_analytics (policy, locked). The host itself shows no lock.
  • Where user_id came from. Each row records whether its user_id came from the credential, the configuration or the administrator’s marker, and the views can split verified rows from the rest.
    • Replayed rows are marked unverifiable, whatever their file says. They take the replaying session’s verified account, or unverified, or a policy can keep them from being sent at all.
    • A regression test replays a completed file that names someone else.
  • Messages for managed users. A refused write tells the person to ask their administrator, instead of naming roles/bigquery.dataEditor. A missing table, with auto-create off, raises the notice instead of only parking rows.
  • Tests:
    • unit tests of the resolution over policy snapshots, where no policy means today’s behaviour;
    • plugin tests with $.settings.read stubbed;
    • mutation checks;
    • regression tests for this section’s two counterexamples, the repository’s interpreter and PATH and the replayed file;
    • this section’s container check, as a script;
    • one live session.
  • Further out. An ingestion endpoint that stamps user_id on the server: the only way to make it unforgeable, at two to three weeks.

Rollout

Pilot with one group, then widen. A policy reaches everyone it is delivered to, so a group needs its own file or profile.

  1. Whoever holds the setup permissions above makes the datasets, table and views with setup.sh, and the custom writer role. The administrators then set retention, and grant writers and readers.
  2. Each person signs in once with gcloud auth application-default login.
  3. Device management places the marketplace directory, the policy, and gcloud at a fixed path.

Updates replace the directory. To roll back, set the plugin to false in the policy’s enabledPlugins. Without device management, the same keys in users’ own settings work but lock nothing. The host’s server-managed settings can carry the policy, but they cannot place the directory. The mod would then install from GitHub and count as a user’s.

NOT VERIFIED

  • NOT VERIFIED: BigQuery’s other answers. The demo’s live session landed its rows with tabledata.insertAll in a table created from the DDL, JSON-typed columns sent as JSON text included; every other answer the writer handles (partial insert errors, 401, 403, 404, 429, 5xx, timeouts) is a scripted stub in the tests, and the mod’s own table creation and BigQuery’s insertId dedup were not exercised against the service.
  • NOT VERIFIED: the 401 refresh path against a real expired token; the demo’s working-credentials session, b), used the default token command with a real identity.
  • NOT VERIFIED: behaviour in the host’s desktop app and editor extension, and on Windows; the real-session check ran headless on macOS.
  • NOT VERIFIED: the per-file backfill lease and the completion records under many concurrent sessions on a real file system (a test shows a write’s first line before the rest, as a write that is not atomic can), and memory and timing over long sessions.
  • NOT VERIFIED: BigQuery cost for this write pattern.
  • NOT VERIFIED: the eight sample queries in BigQuery itself (they were parsed and run in DuckDB only).
  • NOT VERIFIED: the credential notice in a real terminal session. The drawing tests check the band’s tree, not how a terminal paints it; the demo shows the toast and the transcript line as a headless session receives them.
  • NOT VERIFIED: setup.sh creating a missing dataset or table against a project. In the demo it ran where both datasets and the table existed, and made the views.
  • NOT VERIFIED: the opt-in identity in a real session, and a token running out in one. A per-user default-credentials token was checked to carry a verified email; the mod’s use of it ran in tests only.
  • NOT VERIFIED: managed settings delivered by a device-management profile, a registry value or the host’s server, and on macOS or Windows; the section 11 checks used a managed-settings file on the Linux build. That the classic hooks pass over a person-installed plugin under such a policy is still the validator’s report, and the session id after /clear or resume without them is covered by the tests only.
  • NOT VERIFIED: section 11’s grants, row access policy and view authorization against a project (only the documentation and gcloud’s role listings were read), its cost figures beyond the documented prices, and everything it marks as proposed. Section 11’s token-environment checks ran the mod with a stand-in for the credential tool, and the real tool’s launcher with stand-in interpreters and helpers, never together.

Sources