SLOPSHOPPER

bigquery-telemetry

Copies Claude Code's OpenTelemetry event records into BigQuery, one table per event type, in the layout a Cloud Logging sink writes for records sent through…

bandtoastpromptprocessnetworktimer
A shopper browsing a rack in a slop shop
README

Claude Code mod: telemetry straight to BigQuery

A Claude Code plugin whose mod copies each OpenTelemetry event record that reaches mods (user_prompt, api_request, tool_decision, tool_result, and so on) straight into BigQuery. There is no collector to deploy.

A developer asks Claude Code on Vertex AI to summarize a README; each event (user_prompt, api_request, tool_decision, tool_result, assistant_response) moves into BigQuery, where a query over the event tables returns the prompt's nine rows

Exporting OpenTelemetry to BigQuery usually runs through Google's Telemetry API or a collector, Cloud Logging and a Log Router sink. The mod runs inside Claude Code and writes the same rows directly:

<img alt="The usual OpenTelemetry export goes from Claude Code through the Telemetry API or an OTel collector, Cloud Logging and a Log Router sink to BigQuery. With the mod, Claude Code writes the same tables to BigQuery directly with tabledata.insertAll." src="assets/one-hop.svg">

The tables look like the ones a Cloud Logging sink writes to a BigQuery dataset with partitioned tables, when Claude Code's OpenTelemetry export reaches Cloud Logging through Google's Telemetry API (telemetry.googleapis.com). There is one table per kind of event, named for the bare event (api_request), partitioned by day on timestamp. Columns have the sink's camelCase names (logName, textPayload, resource.labels.task_id), and labels is a RECORD of STRING fields, so numbers need SAFE_CAST. See What a row contains. setup.sh creates the tables, a view of each that leaves out repeated rows, and two spend views, daily_spend and spend_by_model, with the columns of the otlp-to-collector quickstart's views of those names.

How this compares with OpenTelemetry export to Cloud Logging

This modOpenTelemetry export
What runsA plugin on each developer's machineClaude Code's OTLP exporter, sending to the Telemetry API directly or through a collector
Where events landBigQuery tables you own, one per kind of eventCloud Logging; a Log Router sink can copy them to BigQuery tables like these
Metrics (Cloud Monitoring) and tracesNo. Token and cost totals come from api_request events.Yes
Claude Code settingsNone, beyond installing the pluginCLAUDE_CODE_ENABLE_TELEMETRY, exporter endpoint, headers helper; OTEL_RESOURCE_ATTRIBUTES recommended
Claude Code version2.1.287 or later (mods)Any version with OpenTelemetry support
DeliveryBest effort: rows can arrive twice or be lost (see Limitations)The OpenTelemetry SDK's batching, and the collector's if there is one

Both can run at once: the mod passes every record on unchanged, so an OpenTelemetry export you already have keeps working.

Claude Code ──telemetry.log──> mod (queue, batch every 5 s) ──insertAll over HTTPS──> one BigQuery table per event
     │                                                                                 (api_request, tool_result, …,
     │                                                                                  other_events for the rest)
     └── the same record, unchanged, to your own OpenTelemetry export (if any)                │
                                                                                               ├── a deduplicated view of each table
                                                                                               ├── daily_spend
                                                                                               └── spend_by_model

Requirements

  • Claude Code 2.1.287 or later. Tested in the terminal CLI with claude -p; the Agent SDK runs the same CLI and should behave the same, but wasn't tested.
  • A Google Cloud project with the BigQuery API and billing enabled (streaming inserts aren't in BigQuery's free tier).
  • For setup, the bq CLI and jq. On each developer machine, gcloud signed in (see Authentication).

1. Create the tables and views

PROJECT=your-project-id ./setup.sh

This creates, in PROJECT:

  • the dataset claude_code_telemetry (change with BQ_DATASET), holding one table per kind of event that Claude Code's monitoring documentation lists. Each table has the columns in schema.json, plus one labels field for each attribute that documentation lists for that event or for every event (and a few Claude Code is known to send anyway), as kept in event-labels.json, and for each EXTRA_LABELS key. Tables are partitioned by day on timestamp. A further table, other_events, has only the fields every event has, and holds events that have no table of their own (see Events with no table).
  • the dataset claude_code_telemetry_reporting (change with VIEWS_DATASET), holding the views daily_spend and spend_by_model (sql/), which read the api_request table (see The spend views).
  • the dataset claude_code_telemetry_deduped (change with DEDUPED_DATASET), holding a view of each table, named like it, that keeps one row per insertId and timestamp (see The deduplicated views).

Other settings:

  • BQ_LOCATION sets the location (default US).
  • TABLE_PREFIX is added to the front of every table name. Set the mod's table_prefix option to the same value.
  • EXTRA_LABELS is a comma-separated list of attribute names to give their own field in every table, for example EXTRA_LABELS=cloud.region,team.id. Attributes without their own field still arrive, in labels.extra_labels (see Labels with no field); a field of its own just makes one easier to query.

The script is safe to re-run. It creates what is missing, adds label fields an existing table lacks, and replaces the views; it never removes anything. Re-run it after adding an EXTRA_LABELS key or a kind of event to event-labels.json. BigQuery's streaming inserts can take a few minutes to see fields added to an existing table, and until then they drop values for those fields without an error.

2. Let developers write rows

The mod reads each table's columns with tables.get, then streams rows with the Storage Write API (REST), which Google previously called the legacy tabledata.insertAll method. Google recommends the gRPC Storage Write API for new projects, but a mod can only make HTTPS requests, and the REST API is still fully supported. Writers need bigquery.tables.get and bigquery.tables.updateData on every table. Google's page also lists bigquery.datasets.get, but inserting works without it. The mod never creates or changes a table.

BigQuery Data Editor on the dataset would work, but it also lets every developer read and delete everyone's rows, and change or delete the tables. A narrower choice is a custom role with just the two table permissions, granted on the dataset to a group. bq add-iam-policy-binding can't grant a role on a dataset (it answers "This feature requires allowlisting"), so add the group to the dataset's access list instead:

gcloud iam roles create claudeCodeTelemetryWriter --project=your-project-id \
  --title="Claude Code telemetry writer" \
  --permissions=bigquery.tables.updateData,bigquery.tables.get

bq show --format=prettyjson your-project-id:claude_code_telemetry > dataset.json
jq '{access: (.access + [{
      role: "projects/your-project-id/roles/claudeCodeTelemetryWriter",
      groupByEmail: "claude-code-users@example.com"}])}' dataset.json > access.json
bq update --source access.json your-project-id:claude_code_telemetry

With this role writers can add rows and read table schemas, and can't remove or change a row once it is written. A test in October 2026, with a service account that had only this role on the dataset and BigQuery Job User on the project, could insert rows, but every one of these failed:

AttemptFails for lack of
Read rows (SELECT, tabledata.list)bigquery.tables.getData
DELETE, UPDATE or TRUNCATE TABLE, even of the writer's own rowsbigquery.tables.getData
Overwrite the table, or one day's partition, with a query job or a copy jobbigquery.tables.create
Delete the table, or give it an expiration timebigquery.tables.delete, bigquery.tables.update

Rows are written by the developer's own machine, so anyone who can write can also write rows with made-up values, such as another person's user.email or a wrong cost_usd. The same is true of OpenTelemetry export, where each machine sets OTEL_RESOURCE_ATTRIBUTES.

People who read the views need BigQuery Data Viewer on the views' dataset and BigQuery Job User on a project. Views read the tables, so readers also need BigQuery Data Viewer on the tables' dataset, unless the views' dataset is an authorized dataset of the tables' dataset, which lets its current and future views read the tables for them. Don't give writers read access to the tables: with bigquery.tables.getData, which Data Viewer includes, the same test service account deleted rows with DELETE. So to show developers the spend views, authorize claude_code_telemetry_reporting. Don't authorize claude_code_telemetry_deduped: its views return every row of the tables, so readers of that dataset should be the people who may read the tables.

3. Install and configure the plugin

The plugin's options go under pluginConfigs in user or managed settings. Claude Code does not read them from a repository's project settings.

Try it on one machine

Load the folder directly and put the options in ~/.claude/settings.json, under the id bigquery-telemetry@inline:

{
  "pluginConfigs": {
    "bigquery-telemetry@inline": {
      "options": { "project": "your-project-id" }
    }
  }
}
claude --plugin-dir ./01-quickstart/bigquery-mod

Roll it out with managed settings

Add the folder to a plugin marketplace your organization controls, for example by copying it to plugins/bigquery-telemetry in your marketplace repository and listing it in .claude-plugin/marketplace.json:

{ "name": "bigquery-telemetry", "source": "./plugins/bigquery-telemetry", "description": "Claude Code telemetry to BigQuery" }

Then install it and set its options for everyone in managed settings:

{
  "extraKnownMarketplaces": {
    "your-marketplace": { "source": { "source": "github", "repo": "your-org/your-marketplace" } }
  },
  "enabledPlugins": { "bigquery-telemetry@your-marketplace": true },
  "pluginConfigs": {
    "bigquery-telemetry@your-marketplace": { "options": { "project": "your-project-id" } }
  }
}

Things to know:

  • What it calls: claude plugin validate ./01-quickstart/bigquery-mod lists every call the mod makes and every environment variable it reads. The calls that reach outside Claude Code are $.http.fetch (to BigQuery, to Google's tokeninfo endpoint for the email address, and to the metadata server with auth: metadata) and $.process.run (only gcloud, and hostname unless hostname_task_id is off or OTEL_RESOURCE_ATTRIBUTES sets service.instance.id).
  • claude -p and CI: marketplace plugins install in the background, so the first run can start without the mod. Set CLAUDE_CODE_SYNC_PLUGIN_INSTALL=1 to make the run wait for the install.
  • Developers can't turn the plugin off, but they can change the copy Claude Code installs, or load another. Set "disableSideloadFlags": true in managed settings so that no one can load a plugin for a session with --plugin-dir or --plugin-url. To stop users' own mods from running and to install yours so that only an administrator can change it, see Claude Code's mods admin guide.

Who and where each row comes from

Developers set nothing beyond the plugin. Each row gets:

  • The developer's email address in labels.user_email: the account they signed in to (see The email address).
  • The project in logName and resource.labels.project_id: the project option.
  • The machine in resource.labels.task_id: its hostname, in a generic_task resource with job claude-code. See The resource.

OTEL_RESOURCE_ATTRIBUTES is optional. Claude Code copies its keys onto every record, so they become labels, and a few keys fill resource labels (see The resource).

Options

OptionDefaultWhat it does
project(none; required)Project that holds the dataset
datasetclaude_code_telemetryDataset that holds the tables, one per kind of event
table_prefix(none)Added to the front of every table name, for example to keep these tables apart from others in a shared dataset. Use the same value as TABLE_PREFIX in setup.sh. A Cloud Logging sink adds no prefix, so queries written for sink tables need it added.
email_from_credentialstrueFill labels.user_email with the credentials' email address when Claude Code sets none (see The email address). Set to false to leave it empty then.
hostname_task_idtruePut the machine's hostname in resource.labels.task_id (see The resource). Set to false to leave task_id empty and never look up the hostname. A service.instance.id you set in OTEL_RESOURCE_ATTRIBUTES is still used.
authadcHow the mod gets a Google access token; see Authentication
on_auth_failurewarnwarn shows a warning above the prompt while rows can't be written for lack of credentials or permission; block also refuses prompts while there are no working credentials. See When credentials fail
quota_project(none)Sent as the x-goog-user-project header, for user credentials that need a quota project
flush_interval_seconds5How often queued rows are sent (1 to 300)
api_basehttps://bigquery.googleapis.comChange only to point the mod at a test server, with auth: none

4. Check that rows arrive

Start a session, send a prompt, and within a few seconds:

SELECT logName, resource.type, resource.labels.task_id, COUNT(*) AS n
FROM `your-project-id.claude_code_telemetry.api_request`
WHERE timestamp > TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 HOUR)
GROUP BY 1, 2, 3;

If nothing arrives, start Claude Code with --debug and search the debug log for bigquery-telemetry. Every problem the mod hits (no project set, a failed token command, a refused row, a missing table, a label with no field) is logged there, and in an interactive session the first occurrence of most of them also shows as a dim line in the transcript.

Authentication

Claude Code gives mods no Google credential, so the mod gets its own access token, and sends it only to https://*.googleapis.com:

  • adc (default): runs gcloud auth application-default print-access-token. Works on a laptop after gcloud auth application-default login, which Vertex AI users of Claude Code usually have done.
  • gcloud: runs gcloud auth print-access-token, the account gcloud itself is signed in as.
  • metadata: asks the metadata server for the attached service account's token. Use it on Compute Engine, Cloud Workstations, GKE with Workload Identity, or Cloud Run.
  • none: sends no token, for a local test server only.

The mod gets a token when the session starts, so that one is at hand at exit, reuses a gcloud token for up to 10 minutes, and gets a new one when BigQuery answers 401. If BigQuery rejects the new token too, the rows wait and are retried with backoff; they aren't dropped.

When credentials fail

Access tokens last about an hour and gcloud renews them on its own, so nothing happens day to day. Rows stop being written when the developer has never signed in, the sign-in was revoked or expired under the organization's re-authentication policy, BigQuery rejects the credentials (401), or the writer lacks permission (403). The mod then keeps the rows and retries (see Limitations), and:

  • warn (default): a line above the prompt says what's wrong and how to fix it, for example run: gcloud auth application-default login, with the number of rows waiting; a toast announces it once. It clears itself once a send succeeds: after signing in, including from the same session (for example ! gcloud auth application-default login), that's with the next prompt, or within 30 seconds. With claude -p and the Agent SDK there is no band; the message goes to the debug log.
  • block: as warn, and while there are no working credentials each prompt is refused with that message before it reaches the model, in interactive sessions and claude -p alike. Each prompt checks again, so signing in unblocks the next one. A missing permission (403) only warns, so that one wrong IAM grant can't stop every developer. If the mod can't send at all (bad options, outbound requests refused), prompts are refused too. The check fails closed: if it crashes, or BigQuery rejected the credentials earlier and can't be reached to check them again, the prompt is refused. A network failure alone, with credentials that work, doesn't block.

With auth: gcloud and no signed-in account, Claude Code shows the warning band above the prompt, with 15 rows waiting, and a toast in the top-right corner

block is only enforcement if developers can't remove or change the mod (see Roll it out with managed settings). It guarantees that rows are being written, not what they contain. Unattended runs need credentials that don't expire, such as auth: metadata.

The email address

With email_from_credentials on (the default), the mod looks up, once per session, the email address of the account its token belongs to:

  • adc and gcloud: it asks Google's tokeninfo endpoint, which returns the verified email of the token's account. gcloud tokens carry the email scope this needs by default; without it there is no address, and the debug log says so.
  • metadata: it asks the metadata server for the attached service account's email address, so rows name the service account, not a person.
  • none: no address.

labels.user_email always names an account someone signed in to. For users signed in to an Anthropic account, Claude Code sets user.email itself, and that stays. Otherwise (on Vertex AI, for example) the mod fills it with the credentials' address. A user.email or user_email key in OTEL_RESOURCE_ATTRIBUTES never fills it, since any developer can set that variable to any address: it goes into labels.extra_labels under its own key. The credentials' address is never saved to disk with unsent rows, so rows a later session sends on an earlier one's behalf go without it rather than with the wrong account's.

What a row contains

Each row is a Cloud Logging log entry, mapped from the OpenTelemetry record as the Telemetry API maps it, in the table layout of a Cloud Logging sink that routes logs to BigQuery with partitioned tables. Queries written for such sink tables should run on these, apart from the known differences.

There is one table per kind of event, named for the event (api_request, tool_result, …), with table_prefix in front if set.

ColumnValue
timestampWhen the event was logged. Tables are partitioned by day on it, so filter on it.
receiveTimestampWhen the mod received the event
logNameprojects/PROJECT/logs/EVENT, for example projects/my-project/logs/api_request
resource.type, resource.labels.*The monitored resource that wrote the entry: always generic_task, naming the project and the machine. See The resource.
textPayloadclaude_code.EVENT
labels.*The record's attributes as strings, one field each, named as a sink names fields: session.id becomes labels.session_id. Numbers are text, so use SAFE_CAST. Attributes without a field of their own are in the JSON field labels.extra_labels.
severityDEFAULT
trace, spanId, traceSampledThe trace the record belongs to, if any (see LogEntry)
insertIdA random ID per record, the same when a send is retried

The resource

Every row's resource is a generic_task, the monitored resource type Cloud Logging uses for a process that isn't a VM or a container, with these labels:

LabelValue
project_idThe project option
jobclaude-code, or the value of OTEL_SERVICE_NAME
task_idThe machine's hostname, from the hostname command or else the HOSTNAME or COMPUTERNAME variable. A service.instance.id in OTEL_RESOURCE_ATTRIBUTES replaces it, and the mod then doesn't run hostname. Empty with hostname_task_id off.
locationA location, cloud.availability_zone or cloud.region key in OTEL_RESOURCE_ATTRIBUTES (the first one set), else empty
namespaceA namespace or service.namespace key in OTEL_RESOURCE_ATTRIBUTES, else empty

A hostname can identify a person: on macOS the default hostname usually includes the owner's name, such as Adas-MacBook-Pro. If it shouldn't reach the tables, turn hostname_task_id off, or set service.instance.id in OTEL_RESOURCE_ATTRIBUTES to something else.

Labels with no field

Each table has a field for every attribute Claude Code's documentation lists for that event, plus a few it's known to send anyway such as ttft_ms on api_request (all kept in event-labels.json), and for each EXTRA_LABELS key. Any other attribute goes into labels.extra_labels, a JSON field holding one object per row: keys from OTEL_RESOURCE_ATTRIBUTES, attributes a newer Claude Code adds, and attributes it sends but doesn't document for that event. Nothing needs listing in advance:

SELECT SAFE_CAST(STRING(labels.extra_labels.history_entries_pruned) AS INT64) AS history_entries_pruned
FROM `your-project-id.claude_code_telemetry.retention_sweep`

Field access (labels.extra_labels.team_id) returns JSON; STRING(...) or JSON_VALUE(labels.extra_labels, '$.team_id') gives text. Keys are the field names a sink would use (team.id becomes team_id). When two attributes would get the same field (team.id and team_id), one that Claude Code set wins over one from OTEL_RESOURCE_ATTRIBUTES, or else the first; the other keeps its own key here. Tables made by an earlier setup.sh may hav

Source 2 files
hooks/register.mjs 960 lines
1// Copyright 2026 The "Anthropic on Google Cloud" Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// A Claude Code mod that copies each OpenTelemetry event record into
16// BigQuery, one table per event type, in the layout a Cloud Logging sink
17// writes. README.md describes the options, the row format and the limits.
18
19import {
20  MAX_BATCH_BYTES,
21  MAX_BATCH_ROWS,
22  MAX_ROW_BYTES,
23  MAX_VALUE_BYTES,
24  backoffMs,
25  fitToTable,
26  insertAllBody,
27  jsonBytes,
28  outcomeOf,
29  resourceAttributesOf,
30  rowOf,
31  sessionFieldsOf,
32  tableNameOf,
33  takeBatch,
34  truncated,
35  wantsHostname,
36} from './rows.mjs'
37
38const LOG_PREFIX = 'bigquery-telemetry: '
39const METADATA_TOKEN_URL =
40  'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token'
41const METADATA_EMAIL_URL =
42  'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/email'
43const TOKENINFO_URL = 'https://oauth2.googleapis.com/tokeninfo'
44// How long a failed lookup of the credentials' email address is kept before
45// it is tried again.
46const EMAIL_RETRY_MS = 10 * 60 * 1000
47// With on_auth_failure "block", how long a prompt waits for a token before
48// it is refused.
49const AUTH_CHECK_TIMEOUT_MS = 25_000
50// While credentials are the problem, retries come at least this often, so the
51// warning clears soon after the developer signs in.
52const AUTH_RETRY_MAX_MS = 30_000
53// gcloud doesn't say when its token expires and may print one it cached
54// earlier, so reuse it for 10 minutes at most, and get a new one on a 401.
55const GCLOUD_TOKEN_REUSE_MS = 10 * 60 * 1000
56// How long a table's columns, read with tables.get, are trusted before
57// they are read again (setup.sh may have added some).
58const TABLE_FIELDS_REUSE_MS = 10 * 60 * 1000
59// Batches sent at once, usually each for its own table.
60const MAX_PARALLEL_SENDS = 8
61// Cap on rows held in memory while BigQuery can't be reached.
62const MAX_QUEUE_BYTES = 16 * 1024 * 1024
63// Cap on the rows one session keeps in the store. All sessions share the
64// mod's store, which holds 4 MiB in total.
65const MAX_SPOOL_BYTES = 1024 * 1024
66const SPOOL_PREFIX = 'unsent:'
67// A session that just ended may still be sending the rows it saved, so
68// other sessions leave saved rows alone until they are this old. A running
69// session waiting to retry can own older ones; taking those can duplicate rows.
70const SPOOL_MIN_AGE_MS = 30_000
71// The table, made by setup.sh, for events that have no table of their own.
72const OTHER_EVENTS = 'other_events'
73
74let config
75const state = {
76  queue: [], // items { table, insertId, json, bytes } waiting to be sent
77  queuedBytes: 0,
78  inFlight: [], // the rows being sent now
79  context: undefined, // promise of what every row needs from the session
80  token: undefined, // { value, expiresAt }
81  tokenRequest: undefined, // promise of the token being fetched now, shared by every caller
82  email: undefined, // { value, readAt }: the credentials' email address, '' if unknown
83  emailRequest: undefined, // promise of the lookup running now, shared by every caller
84  tables: new Map(), // table name -> { fields, readAt }: its columns, from tables.get
85  tableReads: new Map(), // table name -> promise of the tables.get running now
86  prefetched: new Set(), // tables whose columns enqueue() has already asked for
87  failures: 0, // failed attempts in a row
88  retryAt: 0, // no attempt before this time (ms since the epoch)
89  flushing: undefined, // promise of the running drain
90  timerStarted: false, // whether the flush timer runs; it outlives a session id
91  disabled: '', // why the mod stopped sending, when it did
92  ended: false, // the process is exiting
93  spoolKey: SPOOL_PREFIX + crypto.randomUUID(), // this process's key in the store
94  spooled: false, // whether the store holds rows under spoolKey
95  spoolWrites: Promise.resolve(true), // the latest write of saved rows; they run one at a time
96  taken: [], // [{ key, ids }]: other sessions' keys to delete once these rows are sent
97  warned: new Set(),
98  // Why rows can't be written: { kind: 'credentials' | 'permission', reason },
99  // shown above the prompt until a send succeeds.
100  authProblem: undefined,
101  toasted: new Set(), // kinds of authProblem already announced with a toast
102}
103
104export function register(on, options) {
105  config = configOf(options)
106  state.disabled = problemOf(config)
107
108  on('session.start', async ($, e, next) => {
109    if (state.disabled) await warnOnce($, 'disabled', 'no rows will be sent to BigQuery: ' + state.disabled)
110    try {
111      await contextOf($)
112    } catch (error) {
113      await warnOnce($, 'start', "could not read the session's settings; trying again with the next record: " + messageOf(error))
114    }
115    if (!state.disabled) {
116      // session.start can fire again in the same process (after /clear or a
117      // resume), and the first timer still runs then.
118      if (!state.timerStarted) {
119        state.timerStarted = true
120        $.clock.every(config.intervalMs, () => {
121          void flush($)
122        })
123      }
124      // Get a token now, so that one is at hand at exit, and the email
125      // address it belongs to.
126      void tokenOf($)
127        .then(() => emailOf($))
128        .catch(() => {})
129      await replaySpool($)
130    }
131    return next(e)
132  })
133
134  // Always pass the record on with next(e), and first: refusing or holding
135  // it would also affect the OpenTelemetry export the organization may run.
136  on('telemetry.log', { to: 'collector' }, async ($, e, next) => {
137    const result = await next(e)
138    // If a later hook refused the record, the export doesn't get it, so neither does BigQuery.
139    if (result?.deny !== undefined) return result
140    try {
141      await enqueue($, e)
142    } catch (error) {
143      await warnOnce($, 'enqueue', 'could not queue a record, so it will not be sent: ' + messageOf(error))
144    }
145    return result
146  })
147
148  // While rows can't be written for lack of credentials or permission, a
149  // line above the prompt says why and how to fix it.
150  on('ui.render', { component: 'AbovePrompt' }, ($, e, next) => {
151    if (!state.authProblem || e.hasSurvey) return next(e)
152    const { Box, Text } = $.ui.resolve(e)
153    return authBand(Box, Text)
154  })
155
156  // With on_auth_failure "block", a prompt is refused while there are no
157  // working Google credentials, so that no session runs unrecorded. A crash
158  // here refuses the prompt too.
159  on('prompt.submit', async ($, e, next) => {
160    // A prompt while rows can't be written is a good moment to try again: the
161    // developer may have just signed in.
162    if (state.authProblem && !state.disabled) {
163      state.retryAt = 0
164      void flush($)
165    }
166    if (config.onAuthFailure !== 'block') return next(e)
167    const problem = await blockingProblem($)
168    if (problem) return { drop: problem }
169    return next(e)
170  }).catch(($, e, next) =>
171    next.called ? next(e) : { drop: 'bigquery-telemetry could not check the Google credentials, so the prompt was not sent.' },
172  )
173
174  on('session.end', async ($, e, next) => {
175    try {
176      if (e.reason === 'clear' || e.reason === 'resume') {
177        // The process goes on under a new session id, and the timer keeps
178        // sending; this just sends what is queued now.
179        void flush($)
180      } else {
181        await finish($, next.budget)
182      }
183    } catch (error) {
184      console.warn(LOG_PREFIX + 'could not save or send rows at exit: ' + messageOf(error))
185    }
186    return next(e)
187  })
188}
189
190function configOf(options) {
191  const o = options ?? {}
192  const text = (value, fallback) => {
193    const s = typeof value === 'string' ? value.trim() : ''
194    return s === '' ? fallback : s
195  }
196  const project = text(o.project, '')
197  const seconds = Number(o.flush_interval_seconds)
198  return {
199    project,
200    dataset: text(o.dataset, 'claude_code_telemetry'),
201    tablePrefix: text(o.table_prefix, ''),
202    hostnameTaskId: o.hostname_task_id !== false && o.hostname_task_id !== 'false',
203    emailFromCredentials: o.email_from_credentials !== false && o.email_from_credentials !== 'false',
204    auth: text(o.auth, 'adc'),
205    onAuthFailure: text(o.on_auth_failure, 'warn').toLowerCase(),
206    quotaProject: text(o.quota_project, ''),
207    intervalMs: (Number.isFinite(seconds) && seconds >= 1 ? Math.min(seconds, 300) : 5) * 1000,
208    apiBase: text(o.api_base, 'https://bigquery.googleapis.com').replace(/\/+$/, ''),
209  }
210}
211
212// Why the options can't work, or '' if they can. Checked before anything is
213// sent, so that a token never goes anywhere but Google.
214function problemOf(c) {
215  if (!c.project) {
216    return 'the "project" option is not set. Set it in pluginConfigs in your user or managed ' +
217      'settings; Claude Code does not read plugin options from project settings.'
218  }
219  if (!['warn', 'block'].includes(c.onAuthFailure)) {
220    return 'the "on_auth_failure" option is "' + c.onAuthFailure + '", but it must be warn or block.'
221  }
222  if (!['adc', 'gcloud', 'metadata', 'none'].includes(c.auth)) {
223    return 'the "auth" option is "' + c.auth + '", but it must be adc, gcloud, metadata or none.'
224  }
225  if (c.auth !== 'none' && !isGoogleApi(c.apiBase)) {
226    return 'the "api_base" option must be an https://*.googleapis.com URL unless "auth" is none, ' +
227      'so that a Google token is never sent anywhere else.'
228  }
229  if (!isUrl(c.apiBase)) return 'the "api_base" option is not an http or https URL.'
230  if (!/^[A-Za-z0-9_]*$/.test(c.tablePrefix)) {
231    return 'the "table_prefix" option may contain only letters, digits and underscores, as in setup.sh.'
232  }
233  return ''
234}
235
236// What every row needs from the session, read once.
237function contextOf($) {
238  if (!state.context) {
239    state.context = loadContext($).catch((error) => {
240      state.context = undefined
241      throw error
242    })
243  }
244  return state.context
245}
246
247async function loadContext($) {
248  const resourceAttributes = await $.env.get('OTEL_RESOURCE_ATTRIBUTES')
249  const serviceName = await $.env.get('OTEL_SERVICE_NAME')
250  // CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC no longer stops a mod's requests
251  // (Claude Code 2.1.288 and later); where Claude Code still refuses them,
252  // sendOrFail sees the refusal and the mod stops then.
253  const attributes = resourceAttributesOf(resourceAttributes, serviceName)
254  const hostname = config.hostnameTaskId && !state.disabled && wantsHostname(attributes) ? await hostnameOf($) : ''
255  return sessionFieldsOf(attributes, config.project, hostname)
256}
257
258// The machine's hostname, for the resource's task_id, or '' if it can't be found.
259async function hostnameOf($) {
260  try {
261    const run = await $.process.run(['hostname'], { timeoutMs: 5_000 })
262    const name = run.exitCode === 0 ? run.stdout.trim() : ''
263    if (name) return name
264  } catch {
265    // Fall back to the environment below.
266  }
267  return ((await $.env.get('HOSTNAME')) || (await $.env.get('COMPUTERNAME')) || '').trim()
268}
269
270async function enqueue($, e) {
271  if (state.disabled) return
272  const context = await contextOf($)
273  if (state.disabled) return
274  const { table, json } = rowOf(e, context, crypto.randomUUID(), new Date().toISOString(), config.tablePrefix)
275  const bytes = jsonBytes(json)
276  if (bytes > MAX_ROW_BYTES) {
277    await warnOnce(
278      $,
279      'too-big:' + e.event,
280      'a record of type ' + e.event + ' (about ' + Math.ceil(bytes / 1024) + ' KiB) was not sent: the mod drops records over ' +
281        MAX_ROW_BYTES / 1024 + " KiB, Cloud Logging's limit for one log entry. Records this large usually come from " +
282        'OTEL_LOG_USER_PROMPTS, OTEL_LOG_ASSISTANT_RESPONSES, OTEL_LOG_TOOL_DETAILS or OTEL_LOG_RAW_API_BODIES; ' +
283        "unset them if that content doesn't need to reach BigQuery.",
284    )
285    return
286  }
287  // Only this process's rows get its credentials' email address, and only
288  // when the record carries none of its own.
289  const wantsEmail = config.emailFromCredentials && !json.labels.user_email
290  pushBack([{ table, insertId: json.insertId, json, bytes, wantsEmail }])
291  // Read a new table's columns now, once, so that sending at exit needn't wait for it.
292  if (!state.prefetched.has(table)) {
293    state.prefetched.add(table)
294    void fieldsOf($, table).catch(() => {})
295  }
296  while (state.queuedBytes > MAX_QUEUE_BYTES && state.queue.length > 1) {
297    const oldest = state.queue.shift()
298    state.queuedBytes -= oldest.bytes
299    await warnOnce(
300      $,
301      'full',
302      "over 16 MiB of rows is waiting because BigQuery hasn't accepted any for a while, so the oldest rows are being dropped.",
303    )
304  }
305  if (state.ended) {
306    // A record that arrives after session.end: save it with the rest.
307    await spool($)
308  } else if (state.queue.length >= MAX_BATCH_ROWS || state.queuedBytes >= MAX_BATCH_BYTES) {
309    void flush($)
310  }
311}
312
313function pushBack(items) {
314  for (const item of items) {
315    state.queue.push(item)
316    state.queuedBytes += item.bytes
317  }
318}
319
320function pushFront(items) {
321  state.queue.unshift(...items)
322  for (const item of items) state.queuedBytes += item.bytes
323}
324
325// Starts sending what is queued, unless a send is already running. The
326// returned promise never rejects.
327function flush($) {
328  if (!state.flushing) {
329    state.flushing = drain($)
330      .catch((error) =>
331        console.warn(LOG_PREFIX + 'sending stopped on an unexpected error and resumes at the next interval: ' + messageOf(error)),
332      )
333      .finally(() => {
334        state.flushing = undefined
335      })
336  }
337  return state.flushing
338}
339
340async function drain($) {
341  while (state.queue.length > 0 && !state.disabled && (await $.clock.now()) >= state.retryAt) {
342    // Each kind of event has its own table, so batches go out together, up
343    // to 8 at once: at exit, one round trip covers that many tables.
344    const batches = []
345    while (state.queue.length > 0 && batches.length < MAX_PARALLEL_SENDS) batches.push(takeBatch(state.queue))
346    for (const item of batches.flat()) state.queuedBytes -= item.bytes
347    state.inFlight = batches.flat()
348    const outcomes = await Promise.all(
349      batches.map(async (batch) => {
350        const outcome = await sendOrFail($, batch)
351        // Settle each batch as soon as it is answered, so that the saved copies
352        // stay in step with what is still unsent even if the process exits now.
353        state.inFlight = state.inFlight.filter((item) => !batch.includes(item))
354        pushFront(outcome.retry)
355        if (state.ended || state.spooled) await spool($)
356        if (state.taken.length > 0) {
357          try {
358            await releaseTaken($, [...outcome.sent, ...outcome.dropped])
359          } catch (error) {
360            // The other session's key stays; its rows may be sent again later.
361            console.warn(LOG_PREFIX + 'could not remove rows another session saved: ' + messageOf(error))
362          }
363        }
364        return outcome
365      }),
366    )
367    const egress = outcomes.find((o) => o.egressRefused)
368    if (egress) {
369      await disable($, 'Claude Code refused the request to BigQuery: ' + egress.reason + '.')
370      return
371    }
372    const failed = outcomes.some(isFailure)
373    let waitMs = failed ? backoffMs(state.failures + 1) : 0
374    if (state.authProblem?.kind === 'credentials') waitMs = Math.min(waitMs, AUTH_RETRY_MAX_MS)
375    for (const outcome of outcomes) await report($, outcome, waitMs)
376    state.failures = failed ? state.failures + 1 : 0
377    state.retryAt = failed ? (await $.clock.now()) + waitMs : 0
378    if (state.failures > 0) return
379  }
380}
381
382// send(), with a failure before BigQuery answered turned into an outcome.
383async function sendOrFail($, batch) {
384  try {
385    return await send($, batch)
386  } catch (error) {
387    const message = messageOf(error)
388    // Claude Code refuses every request from the mod.
389    const egress = message.match(/\$\.http\.fetch: refused: (.*)$/)
390    if (egress) return { sent: [], retry: batch, dropped: [], reason: egress[1], egressRefused: true }
391    // Claude Code refused this one request, for example for its size.
392    if (/\$\.http\.fetch: \S+ refused: /.test(message)) {
393      return { sent: [], retry: [], dropped: batch, reason: message, retryLater: false, refusedByClaudeCode: true }
394    }
395    // The token or the request failed before BigQuery answered.
396    return { sent: [], retry: batch, dropped: [], reason: message, retryLater: true }
397  }
398}
399
400// Whether an outcome calls for a backoff before the next attempt.
401function isFailure(outcome) {
402  return outcome.retryLater || (outcome.sent.length === 0 && outcome.dropped.length === 0)
403}
404
405// Warns about rows an outcome dropped, or will send again after waitMs.
406async function report($, outcome, waitMs) {
407  if (outcome.dropped.length > 0) {
408    await warnOnce(
409      $,
410      'dropped:' + outcome.reason,
411      (outcome.refusedByClaudeCode
412        ? 'Claude Code refused the request for ' + outcome.dropped.length + " row(s), so they won't be sent: "
413        : outcome.missingTable
414          ? outcome.dropped.length + " row(s) won't be sent: "
415          : 'BigQuery refused ' + outcome.dropped.length + " row(s), so they won't be sent: ") + outcome.reason,
416    )
417  }
418  if (isFailure(outcome)) {
419    await warnOnce(
420      $,
421      'retry:' + outcome.reason,
422      'could not send rows to BigQuery; trying again in about ' + Math.ceil(waitMs / 1000) + ' s: ' + outcome.reason,
423    )
424  }
425}
426
427// Sends a batch, all for one table, after removing the labels that table
428// has no column for. A batch whose table doesn't exist goes to other_events.
429async function send($, batch) {
430  let table = batch[0].table
431  let fields = await fieldsOf($, table)
432  if (fields === 'missing') {
433    const other = tableNameOf(OTHER_EVENTS, config.tablePrefix)
434    const otherFields = table === other ? 'missing' : await fieldsOf($, other)
435    if (otherFields === 'missing') {
436      return {
437        sent: [], retry: [], dropped: batch, retryLater: false, missingTable: true,
438        reason: 'the table ' + config.project + ':' + config.dataset + '.' + table + " doesn't exist. Check the " +
439          'project, dataset and table_prefix options. If they are right, this is a kind of event setup.sh made no ' +
440          'table for, and there is no ' + other + ' table to hold it: run setup.sh again.',
441      }
442    }
443    // Debug log only: no row is lost, and other_events shows which events need a table.
444    if (!state.warned.has('other:' + table)) {
445      state.warned.add('other:' + table)
446      console.warn(
447        LOG_PREFIX + 'the table ' + table + " doesn't exist, so its rows go to " + other +
448          '. To give it a table, add the event to event-labels.json and run setup.sh again.',
449      )
450    }
451    // Retried rows then go straight to other_events.
452    for (const item of batch) item.table = other
453    table = other
454    fields = otherFields
455  }
456  if (fields) {
457    for (const item of batch) {
458      const fitted = fitToTable(item.json, fields)
459      item.json = fitted.json
460      for (const name of fitted.dropped) {
461        // Debug log only: this can happen in every session until setup.sh is run again.
462        if (!state.warned.has('column:' + table + '.' + name)) {
463          state.warned.add('column:' + table + '.' + name)
464          console.warn(
465            LOG_PREFIX + 'the table ' + table + ' has no column ' + name +
466              (name.startsWith('labels.') ? ' and no labels.extra_labels' : '') +
467              ", so that value isn't sent. Run setup.sh again to add the missing columns.",
468          )
469        }
470      }
471    }
472  }
473  // The credentials' email address goes only into the request, never into
474  // item.json, so it is never written to the store with unsent rows.
475  const email = batch.some((item) => item.wantsEmail) ? await emailOf($) : ''
476  const toSend = batch.map((item) => withEmail(item, email, fields))
477  const response = await call($, 'POST', tableUrlOf(table) + '/insertAll', insertAllBody(toSend))
478  if (response.status === 403) {
479    await noteAuthProblem($, 'permission', outcomeOf(batch, response.status, response.text).reason)
480  } else if (response.ok) {
481    await clearAuthProblem($)
482  }
483  return outcomeOf(batch, response.status, response.text)
484}
485
486// The item to send: with labels.user_email set to email when the item wants
487// it, has none, and its table has that column (or its columns are unknown).
488function withEmail(item, email, fields) {
489  if (!email || !item.wantsEmail || item.json.labels?.user_email) return item
490  const labelFields = fields?.find?.((f) => f.name === 'labels')?.fields
491  if (labelFields && !labelFields.some((f) => f.name === 'user_email')) return item
492  return { ...item, json: { ...item.json, labels: { ...item.json.labels, user_email: truncated(email, MAX_VALUE_BYTES) } } }
493}
494
495function tableUrlOf(table) {
496  return (
497    config.apiBase +
498    '/bigquery/v2/projects/' + encodeURIComponent(config.project) +
499    '/datasets/' + encodeURIComponent(config.dataset) +
500    '/tables/' + encodeURIComponent(table)
501  )
502}
503
504// The table's columns from tables.get, read at most every 10 minutes:
505// 'missing' if the table doesn't exist, or undefined if BigQuery refused to
506// show them (BigQuery then drops the values that have no column). Throws when
507// the read should be tried again later (401, 408, 429, 5xx, network).
508async function fieldsOf($, table) {
509  const now = await $.clock.now()
510  const known = state.tables.get(table)
511  if (known && now - known.readAt < TABLE_FIELDS_REUSE_MS) return known.fields
512  if (!state.tableReads.has(table)) {
513    state.tableReads.set(table, readFields($, table, now).finally(() => state.tableReads.delete(table)))
514  }
515  return state.tableReads.get(table)
516}
517
518async function readFields($, table, now) {
519  const response = await call($, 'GET', tableUrlOf(table) + '?fields=schema')
520  if (response.status === 404) {
521    state.tables.set(table, { fields: 'missing', readAt: now })
522    return 'missing'
523  }
524  if (response.status === 401 || response.status === 408 || response.status === 429 || response.status >= 500) {
525    throw new Error('could not read the columns of ' + table + ': HTTP ' + response.status)
526  }
527  let fields
528  try {
529    fields = response.ok ? JSON.parse(response.text).schema?.fields : undefined
530  } catch {
531    fields = undefined
532  }
533  if (!Array.isArray(fields)) {
534    state.tables.set(table, { fields: undefined, readAt: now })
535    await warnOnce(
536      $,
537      'fields',
538      'could not read the columns of ' + table + ' (HTTP ' + response.status + '), so values the table has no column for ' +
539        'are dropped by BigQuery without a warning. Writers need bigquery.tables.get as well as bigquery.tables.updateData.',
540    )
541    return undefined
542  }
543  state.tables.set(table, { fields, readAt: now })
544  return fields
545}
546
547// A request to BigQuery with the token, sent once more with a new token after a 401.
548async function call($, method, url, body) {
549  let { response, token } = await fetchWithToken($, method, url, body)
550  if (response.status === 401 && config.auth !== 'none') {
551    // The token may have expired early: get a new one and try once more. Only
552    // the token this request used is thrown away, so that requests answered
553    // 401 at the same time share one new token.
554    if (state.token?.value === token) state.token = undefined
555    ;({ response } = await fetchWithToken($, method, url, body))
556    if (response.status === 401) {
557      await noteAuthProblem($, 'credentials', 'BigQuery rejected the credentials (HTTP 401) even after getting a new token')
558    }
559  }
560  if (response.ok && state.authProblem?.kind === 'credentials') await clearAuthProblem($)
561  return response
562}
563
564async function fetchWithToken($, method, url, body) {
565  const headers = {}
566  if (body !== undefined) headers['Content-Type'] = 'application/json'
567  const token = await tokenOf($)
568  if (token) {
569    // problemOf() already refused such an api_base; this is a second check.
570    if (!isGoogleApi(url)) throw new Error('refusing to send a Google token to ' + new URL(url).origin)
571    headers.Authorization = 'Bearer ' + token
572  }
573  if (config.quotaProject) headers['x-goog-user-project'] = config.quotaProject
574  const response = await $.http.fetch(url, body === undefined ? { method, headers } : { method, headers, body })
575  return { response, token }
576}
577
578// An OAuth access token for BigQuery, or '' when auth is "none". Callers
579// share one fetch while it runs, so gcloud never runs twice at once.
580async function tokenOf($) {
581  if (config.auth === 'none') return ''
582  const now = await $.clock.now()
583  if (state.token && state.token.expiresAt > now) return state.token.value
584  if (!state.tokenRequest) {
585    state.tokenRequest = newToken($, now)
586      .catch(async (error) => {
587        await noteAuthProblem($, 'credentials', messageOf(error))
588        throw error
589      })
590      .finally(() => {
591        state.tokenRequest = undefined
592      })
593  }
594  return state.tokenRequest
595}
596
597async function newToken($, now) {
598  let value
599  let lifetimeMs = GCLOUD_TOKEN_REUSE_MS
600  if (config.auth === 'metadata') {
601    const response = await $.http.fetch(METADATA_TOKEN_URL, { headers: { 'Metadata-Flavor': 'Google' } })
602    if (!response.ok) throw new Error('the metadata server answered HTTP ' + response.status + ' when asked for an access token')
603    const body = JSON.parse(response.text)
604    value = body.access_token
605    const expiresIn = Number(body.expires_in)
606    // Reuse it until a minute before it expires; if the answer doesn't say, for 5 minutes.
607    lifetimeMs = Number.isFinite(expiresIn) ? Math.max(0, (expiresIn - 60) * 1000) : 5 * 60 * 1000
608  } else {
609    const run =
610      config.auth === 'gcloud'
611        ? await $.process.run(['gcloud', 'auth', 'print-access-token'], { timeoutMs: 20_000 })
612        : await $.process.run(['gcloud', 'auth', 'application-default', 'print-access-token'], { timeoutMs: 20_000 })
613    if (run.exitCode !== 0) {
614      throw new Error('gcloud could not print an access token (exit ' + run.exitCode + '): ' + errorLine(run.stderr))
615    }
616    value = run.stdout.trim()
617  }
618  if (!value) throw new Error('the ' + (config.auth === 'metadata' ? 'metadata server' : 'gcloud command') + ' returned no access token')
619  state.token = { value, expiresAt: now + lifetimeMs }
620  return value
621}
622
623// The email address of the account the credentials belong to, or '' when it
624// is off, unknown, or can't be found. Looked up once per process; a failed
625// lookup is tried again after 10 minutes, and one that failed only because
626// there was no token, with the next send. Never throws.
627async function emailOf($) {
628  if (!config.emailFromCredentials || config.auth === 'none') return ''
629  const now = await $.clock.now()
630  if (state.email && (state.email.value || now - state.email.readAt < EMAIL_RETRY_MS)) return state.email.value
631  if (!state.emailRequest) {
632    state.emailRequest = lookUpEmail($)
633      .then((value) => {
634        state.email = { value, readAt: now }
635        return value
636      })
637      .catch(async (error) => {
638        // No token, or Claude Code refuses the mod's requests: send() reports
639        // that already, and the lookup can run again.
640        if (error?.noToken || /\$\.http\.fetch: refused: /.test(messageOf(error))) return ''
641        state.email = { value: '', readAt: now }
642        await warnOnce($, 'email', "could not find the credentials' email address, so rows without a user.email " +
643          'attribute are sent without one: ' + messageOf(error))
644        return ''
645      })
646      .finally(() => {
647        state.emailRequest = undefined
648      })
649  }
650  return state.emailRequest
651}
652
653async function lookUpEmail($) {
654  if (config.auth === 'metadata') {
655    const response = await $.http.fetch(METADATA_EMAIL_URL, { headers: { 'Metadata-Flavor': 'Google' } })
656    if (!response.ok) throw new Error('the metadata server answered HTTP ' + response.status)
657    return response.text.trim()
658  }
659  // Google's tokeninfo endpoint names the account a token was issued to, when
660  // it has the email scope (gcloud's tokens have it by default). The token
661  // goes in the body, not the URL.
662  const token = await tokenOf($).catch((error) => {
663    throw Object.assign(new Error(messageOf(error)), { noToken: true })
664  })
665  if (!isGoogleApi(TOKENINFO_URL)) throw new Error('refusing to send a Google token to ' + new URL(TOKENINFO_URL).origin)
666  const response = await $.http.fetch(TOKENINFO_URL, {
667    method: 'POST',
668    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
669    body: 'access_token=' + encodeURIComponent(token),
670  })
671  if (!response.ok) throw new Error('tokeninfo answered HTTP ' + response.status)
672  const info = JSON.parse(response.text)
673  if (!info.email) throw new Error("the token has no email scope, so tokeninfo doesn't name its account")
674  if (String(info.email_verified) !== 'true') throw new Error('tokeninfo says the email address is not verified')
675  return String(info.email)
676}
677
678// Called at exit. Saves unsent rows first, because Claude Code may stop
679// the mod at any moment now, then sends them if a token is at hand, taking
680// at most half of what is left of the shared exit budget, and at most 1 s.
681async function finish($, budget) {
682  state.ended = true
683  if (state.disabled) return
684  await spool($)
685  if (state.queue.length === 0 && state.inFlight.length === 0) return
686  const waitMs = Math.min((budget?.remainingMs ?? 0) / 2, 1000)
687  const hasToken = config.auth === 'none' || (state.token && state.token.expiresAt > (await $.clock.now()))
688  if (!hasToken || waitMs < 200) return
689  state.retryAt = 0
690  await Promise.race([flush($), $.clock.sleep(waitMs)])
691}
692
693// Writes the unsent rows (the batches being sent and the queue) under this
694// process's key, or removes the key when nothing is left. Returns true only
695// if every unsent row is now saved. Writes run one at a time, each saving
696// what is unsent when it runs, so the last one always reflects the latest state.
697function spool($) {
698  const write = state.spoolWrites.then(() => writeSpool($))
699  state.spoolWrites = write
700  return write
701}
702
703async function writeSpool($) {
704  const rows = []
705  let bytes = 0
706  let lost = 0
707  for (const item of [...state.inFlight, ...state.queue]) {
708    if (bytes + item.bytes > MAX_SPOOL_BYTES) {
709      lost += 1
710      continue
711    }
712    rows.push({ table: item.table, insertId: item.insertId, json: item.json })
713    bytes += item.bytes
714  }
715  try {
716    if (rows.length === 0) {
717      if (state.spooled) await $.store.delete(state.spoolKey)
718    } else {
719      await $.store.set(state.spoolKey, { writtenAt: await $.clock.now(), rows })
720    }
721    state.spooled = rows.length > 0
722  } catch (error) {
723    console.warn(LOG_PREFIX + 'could not save unsent rows; they are lost if Claude Code exits before sending them: ' + messageOf(error))
724    return false
725  }
726  if (lost > 0) {
727    console.warn(
728      LOG_PREFIX + lost + ' unsent row(s) were not saved because a session may save only 1 MiB; ' +
729        'they are lost if Claude Code exits before sending them',
730    )
731  }
732  return lost === 0
733}
734
735// Takes over rows that other sessions saved, whole keys at a time while
736// they fit in this session's 1 MiB: queues them and saves them under this
737// process's key, then removes the old keys; if that save fails, it removes
738// each old key once its rows are sent. A key can belong to a running session
739// waiting to retry; taking it can duplicate rows, which the views setup.sh
740// makes remove.
741async function replaySpool($) {
742  try {
743    const now = await $.clock.now()
744    const taken = []
745    const rows = []
746    let bytes = state.queuedBytes
747    for (const key of await $.store.keys()) {
748      if (!key.startsWith(SPOOL_PREFIX) || key === state.spoolKey) continue
749      const saved = await $.store.get(key)
750      if (saved && now - Number(saved.writtenAt ?? 0) < SPOOL_MIN_AGE_MS) continue
751      const keyRows = []
752      for (const r of Array.isArray(saved?.rows) ? saved.rows : []) {
753        // A saved row goes to its event's table under the current table_prefix,
754        // which may differ from the one it was saved with, so r.table is only
755        // checked for being there. Anything else is dropped.
756        const table = typeof r?.table === 'string' && r.json && typeof r.json === 'object' ? savedTableOf(r.json) : ''
757        if (table && typeof r.insertId === 'string') {
758          keyRows.push({ table, insertId: r.insertId, json: r.json, bytes: jsonBytes(r.json) })
759        }
760      }
761      const keyBytes = keyRows.reduce((sum, r) => sum + r.bytes, 0)
762      if (bytes + keyBytes > MAX_SPOOL_BYTES) continue
763      bytes += keyBytes
764      taken.push({ key, ids: new Set(keyRows.map((r) => r.insertId)) })
765      rows.push(...keyRows)
766    }
767    if (taken.length === 0) return
768    pushFront(rows)
769    if (await spool($)) {
770      for (const { key } of taken) await $.store.delete(key)
771    } else {
772      state.taken.push(...taken)
773    }
774  } catch (error) {
775    await warnOnce($, 'replay', 'could not pick up rows that earlier sessions saved; they stay saved for a later session: ' + messageOf(error))
776  }
777}
778
779// The table for a saved row, from the event name at the end of its logName.
780function savedTableOf(json) {
781  const match = typeof json.logName === 'string' ? json.logName.match(/\/logs\/([^/]+)$/) : null
782  if (!match) return ''
783  try {
784    return tableNameOf(decodeURIComponent(match[1]), config.tablePrefix)
785  } catch {
786    return ''
787  }
788}
789
790// Removes other sessions' keys whose rows have all been sent or dropped.
791async function releaseTaken($, done) {
792  for (const item of done) for (const t of state.taken) t.ids.delete(item.insertId)
793  const finished = state.taken.filter((t) => t.ids.size === 0)
794  state.taken = state.taken.filter((t) => t.ids.size > 0)
795  for (const { key } of finished) await $.store.delete(key)
796}
797
798async function disable($, reason) {
799  state.disabled = reason
800  // Saves what is unsent, including rows taken over from other sessions,
801  // for a later session that may be able to send it. Once that is saved,
802  // the other sessions' keys holding the taken rows can go.
803  if ((await spool($)) && state.taken.length > 0) {
804    try {
805      for (const { key } of state.taken) await $.store.delete(key)
806      state.taken = []
807    } catch (error) {
808      console.warn(LOG_PREFIX + 'could not remove rows another session saved: ' + messageOf(error))
809    }
810  }
811  state.queue = []
812  state.queuedBytes = 0
813  state.inFlight = []
814  await warnOnce($, 'disabled', 'no rows will be sent to BigQuery: ' + reason)
815}
816
817// Records why rows can't be written, and redraws the band. The first time
818// each kind of problem appears in this process, a toast says so too.
819async function noteAuthProblem($, kind, reason) {
820  if (config.auth === 'none') return
821  const changed = state.authProblem?.kind !== kind || state.authProblem?.reason !== reason
822  state.authProblem = { kind, reason }
823  if (!changed) return
824  redraw($)
825  if (!state.toasted.has(kind)) {
826    state.toasted.add(kind)
827    try {
828      await $.ui.toast('BigQuery telemetry. ' + problemSummary(), { timeoutMs: 15_000 })
829    } catch {
830      // Not every surface shows toasts; the band and the log still say it.
831    }
832  }
833  await warnOnce($, 'auth:' + kind + ':' + reason, problemSummary() + ' (' + reason + ')')
834}
835
836async function clearAuthProblem($) {
837  if (!state.authProblem) return
838  state.authProblem = undefined
839  redraw($)
840}
841
842function redraw($) {
843  try {
844    $.ui.invalidate('ui.render')
845  } catch {
846    // No drawing surface (claude -p, the SDK).
847  }
848}
849
850// One sentence: what's wrong and how to fix it.
851function problemSummary() {
852  const p = state.authProblem
853  if (!p) return ''
854  if (p.kind === 'permission') {
855    return 'Rows are not being written: missing BigQuery permission. Ask an admin to grant ' +
856      'bigquery.tables.updateData on ' + config.project + ':' + config.dataset + '.'
857  }
858  const fix = {
859    adc: 'run: gcloud auth application-default login',
860    gcloud: 'run: gcloud auth login',
861    metadata: "check this machine's attached service account",
862  }[config.auth]
863  return 'Rows are not being written: no working Google credentials. To fix, ' + fix + '.'
864}
865
866function authBand(Box, Text) {
867  const waiting = state.queue.length + state.inFlight.length
868  const blocking = config.onAuthFailure === 'block' && state.authProblem.kind === 'credentials'
869  const parts = [
870    Text({ color: blocking ? 'red' : 'yellow', bold: true, children: '⚠ BigQuery telemetry: ' }),
871    Text({ children: problemSummary().replace(/^Rows are not being written: /, '') }),
872  ]
873  if (waiting > 0) parts.push(Text({ dimColor: true, children: '  ' + waiting + ' row(s) waiting' }))
874  if (blocking) parts.push(Text({ color: 'red', children: '  Prompts are blocked until this is fixed.' }))
875  return Box({ flexDirection: 'row', flexWrap: 'wrap', paddingX: 1, children: parts })
876}
877
878// With on_auth_failure "block": why a prompt can't go ahead, or '' if it can.
879async function blockingProblem($) {
880  if (state.disabled) return 'bigquery-telemetry: prompts are blocked because no rows can be sent to BigQuery: ' + state.disabled
881  if (config.auth === 'none') return ''
882  // Neither side of the race rejects, so whichever loses is simply ignored.
883  const outcome = await Promise.race([
884    tokenOf($).then(() => ({ ok: true }), (error) => ({ error })),
885    $.clock.sleep(AUTH_CHECK_TIMEOUT_MS).then(() => ({ error: new Error('timed out getting a Google token') })),
886  ])
887  if (outcome.error) {
888    if (!state.authProblem) await noteAuthProblem($, 'credentials', messageOf(outcome.error))
889    return 'bigquery-telemetry: prompts are blocked until telemetry can be recorded. ' + problemSummary()
890  }
891  // A token was found. If BigQuery rejected the last one, check again before
892  // letting the prompt through: a 401 here means the credentials are still bad.
893  if (state.authProblem?.kind === 'credentials') {
894    try {
895      const response = await call($, 'GET', tableUrlOf(tableNameOf('user_prompt', config.tablePrefix)) + '?fields=schema')
896      if (response.status === 401) {
897        return 'bigquery-telemetry: prompts are blocked until telemetry can be recorded. ' + problemSummary()
898      }
899      await clearAuthProblem($)
900    } catch (error) {
901      // BigQuery rejected these credentials before and couldn't be reached to
902      // check again: fail closed, as the gate is meant to.
903      return 'bigquery-telemetry: prompts are blocked: BigQuery rejected the credentials earlier, and checking ' +
904        'them again failed (' + messageOf(error) + '). ' + problemSummary()
905    }
906  }
907  return ''
908}
909
910async function warn($, text) {
911  console.warn(LOG_PREFIX + text)
912  try {
913    await $.ui.log(text) // Claude Code adds the mod's name
914  } catch {
915    // Some surfaces have no transcript to write to; the debug log has it.
916  }
917}
918
919async function warnOnce($, key, text) {
920  if (state.warned.has(key)) {
921    console.warn(LOG_PREFIX + text)
922    return
923  }
924  state.warned.add(key)
925  await warn($, text)
926}
927
928function isUrl(text) {
929  try {
930    const url = new URL(text)
931    return url.protocol === 'https:' || url.protocol === 'http:'
932  } catch {
933    return false
934  }
935}
936
937function isGoogleApi(text) {
938  try {
939    const url = new URL(text)
940    return url.protocol === 'https:' && (url.hostname === 'googleapis.com' || url.hostname.endsWith('.googleapis.com'))
941  } catch {
942    return false
943  }
944}
945
946// One line from a command's error output, without control characters and at
947// most 200 characters: gcloud's ERROR: line if there is one (it can follow
948// WARNING: lines), else the first line. The rest (instructions, URLs) would
949// garble a one-line warning.
950function errorLine(text) {
951  const lines = String(text ?? '').split(/\r?\n/).map((l) => l.trim()).filter((l) => l)
952  const line = lines.find((l) => l.startsWith('ERROR:')) ?? lines[0] ?? ''
953  const clean = line.replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ')
954  return clean.length > 200 ? clean.slice(0, 199) + '…' : clean
955}
956
957function messageOf(error) {
958  return error instanceof Error ? error.message : String(error)
959}
960
hooks/rows.mjs 365 lines
1// Copyright 2026 The "Anthropic on Google Cloud" Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// Helpers for the mod that make no mods API calls, so tests can call
16// them directly: record to row, batching, and reading BigQuery's answers.
17
18// Each record becomes a row in the layout a Cloud Logging sink writes to
19// BigQuery when Claude Code's OpenTelemetry export goes through Google's
20// Telemetry API: one table per event type, camelCase LogEntry columns, and
21// labels as a RECORD of STRING fields. See "What a row contains" in README.md.
22// https://docs.cloud.google.com/logging/docs/export/bigquery
23// https://docs.cloud.google.com/stackdriver/docs/reference/telemetry/otlp-log-record-to-log-entry
24// https://docs.cloud.google.com/stackdriver/docs/reference/telemetry/otlp-attribute-to-logging-resource
25
26// Cloud Logging's limits for an entry made from an OTLP record: 256 KiB per
27// entry (the mod drops a bigger row), 512 B per attribute key and 64 KiB per value.
28export const MAX_ROW_BYTES = 256 * 1024
29const MAX_KEY_BYTES = 512
30export const MAX_VALUE_BYTES = 64 * 1024
31// A BigQuery field name that a sink writes is at most 128 characters.
32const MAX_FIELD_NAME = 128
33
34// insertAll takes at most 50,000 rows and 10 MB in one request. A batch is at
35// most 500 rows and 3 MiB, or one row of at most 256 KiB, well under both.
36export const MAX_BATCH_ROWS = 500
37export const MAX_BATCH_BYTES = 3 * 1024 * 1024
38
39// Attributes each resource label is read from, first non-empty wins; else ''.
40// The names are those Google's OTLP-to-resource mapping uses for generic_task.
41const RESOURCE_LABEL_KEYS = {
42  location: ['location', 'cloud.availability_zone', 'cloud.region'],
43  namespace: ['namespace', 'service.namespace'],
44  job: ['job', 'service.name'],
45  task_id: ['task_id', 'service.instance.id'],
46}
47
48const encoder = new TextEncoder()
49
50/** Size of a value's JSON text in bytes (UTF-8). */
51export function jsonBytes(value) {
52  return encoder.encode(JSON.stringify(value)).length
53}
54
55/**
56 * The resource attributes Claude Code sends that a mod can know. Later ones
57 * win: service.name "claude-code", then OTEL_RESOURCE_ATTRIBUTES, then
58 * OTEL_SERVICE_NAME.
59 */
60export function resourceAttributesOf(otelResourceAttributes, otelServiceName) {
61  const attributes = Object.create(null) // no prototype, so a __proto__ key is kept
62  attributes['service.name'] = 'claude-code'
63  Object.assign(attributes, envAttributesOf(otelResourceAttributes ?? ''))
64  if (otelServiceName) attributes['service.name'] = otelServiceName
65  return attributes
66}
67
68// OTEL_RESOURCE_ATTRIBUTES ("k1=v1,k2=v2"): pairs without a key are skipped,
69// quotes around a value are dropped, and percent-encoding is decoded where valid.
70function envAttributesOf(text) {
71  const attributes = Object.create(null)
72  for (const pair of text.split(',')) {
73    const at = pair.indexOf('=')
74    const key = at < 0 ? '' : pair.slice(0, at).trim()
75    if (!key) continue
76    const value = pair.slice(at + 1).trim().replace(/^"|"$/g, '')
77    try {
78      attributes[key] = decodeURIComponent(value)
79    } catch {
80      attributes[key] = value
81    }
82  }
83  return attributes
84}
85
86/**
87 * Whether the mod needs the machine's hostname for task_id: no attribute
88 * names the task.
89 */
90export function wantsHostname(attributes) {
91  return !RESOURCE_LABEL_KEYS.task_id.some((key) => attributes[key])
92}
93
94/**
95 * The monitored resource { type, labels }: always generic_task, with
96 * project_id the given project, job the service name (claude-code unless
97 * OTEL_SERVICE_NAME says otherwise), task_id the service.instance.id
98 * attribute or else hostname, and location and namespace from their
99 * attributes. A label with no value is ''. See "The resource" in README.md.
100 */
101export function resourceOf(attributes, project, hostname = '') {
102  const first = (keys) => keys.map((key) => attributes[key]).find((value) => value) ?? ''
103  const labels = { project_id: project }
104  for (const [name, keys] of Object.entries(RESOURCE_LABEL_KEYS)) labels[name] = first(keys)
105  if (!labels.task_id) labels.task_id = hostname
106  return { type: 'generic_task', labels }
107}
108
109/**
110 * A label value: lists (and any other object) as compact JSON text, as
111 * Google documents for lists. Numbers
112 * and booleans as JavaScript writes them ("34", "0.000188", "1e-7", "true"):
113 * not confirmed against a real Telemetry API export.
114 */
115export function labelValueOf(value) {
116  if (typeof value === 'string') return value
117  if (typeof value === 'object' && value !== null) return JSON.stringify(value)
118  return String(value)
119}
120
121/**
122 * text cut to at most maxBytes of UTF-8, ending in "…" when cut, as Cloud
123 * Logging marks a truncated label. Whether the ellipsis counts toward the
124 * limit is not confirmed against a real Telemetry API export.
125 */
126export function truncated(text, maxBytes) {
127  const bytes = encoder.encode(text)
128  if (bytes.length <= maxBytes) return text
129  const kept = new TextDecoder().decode(bytes.subarray(0, maxBytes - 3)) // "…" is 3 bytes
130  return kept.replace(/\uFFFD$/, '') + '…' // drop a character cut in half
131}
132
133/**
134 * The BigQuery field name a sink gives a label key: each character other
135 * than a letter, digit or underscore becomes "_", leading underscores are
136 * removed, and the name is lowercased and cut to 128 characters
137 * ("session.id" becomes session_id). '' when nothing is left.
138 */
139export function fieldNameOf(key) {
140  return key.replace(/[^A-Za-z0-9_]/gu, '_').replace(/^_+/, '').toLowerCase().slice(0, MAX_FIELD_NAME)
141}
142
143/**
144 * The table a sink writes a log to: the prefix, then the log ID with every
145 * character other than a letter, digit or underscore turned into "_" (Google
146 * shows "-", "." and "/" becoming "_").
147 */
148export function tableNameOf(logId, prefix = '') {
149  return prefix + logId.replace(/[^A-Za-z0-9_]/gu, '_')
150}
151
152/**
153 * Fields every row of a session shares: logProject (the project option, used
154 * in logName and resource.labels.project_id) and resource. Also the resource
155 * attributes, which rowOf uses to tell a record's own attributes from those
156 * Claude Code copied from OTEL_RESOURCE_ATTRIBUTES.
157 */
158export function sessionFieldsOf(resourceAttributes, project, hostname = '') {
159  return { logProject: project, resource: resourceOf(resourceAttributes, project, hostname), resourceAttributes }
160}
161
162/**
163 * { table, json } for a telemetry.log event { event, attributes, loggedAt,
164 * span? }. The log ID is always the event name. context is what
165 * sessionFieldsOf returns; insertId must stay the same when the row is sent
166 * again. trace, spanId and traceSampled are left out when not set.
167 */
168export function rowOf(entry, context, insertId, receivedAt, tablePrefix = '') {
169  // The record's attributes and nothing else, as strings under their sink
170  // field names. The record's own attributes pick first, then those Claude
171  // Code copied from OTEL_RESOURCE_ATTRIBUTES, so that variable can't replace
172  // what Claude Code sets; within each, when two keys get the same name
173  // ("team.id" and "team_id") the first stays. labels.user_email names an
174  // account someone signed in to, so a copied one never fills it: the
175  // credentials' email does, when the row is sent. Attributes that get no
176  // field this way, and any named extra_labels, go into labels.extra_labels
177  // under their own keys.
178  const labels = Object.create(null)
179  const setAside = Object.create(null)
180  const resourceAttributes = context.resourceAttributes ?? {}
181  const own = []
182  const copied = []
183  for (const [key, value] of Object.entries(entry.attributes ?? {})) {
184    const fromResource = Object.hasOwn(resourceAttributes, key) && resourceAttributes[key] === labelValueOf(value)
185    ;(fromResource ? copied : own).push([key, value])
186  }
187  for (const [i, [key, value]] of [...own, ...copied].entries()) {
188    const cutKey = truncated(key, MAX_KEY_BYTES)
189    const name = fieldNameOf(cutKey)
190    if (!name) continue
191    const text = truncated(labelValueOf(value), MAX_VALUE_BYTES)
192    if (name in labels || name === EXTRA_LABELS_FIELD || (name === USER_EMAIL_FIELD && i >= own.length)) {
193      setAside[cutKey] = text
194    } else {
195      labels[name] = text
196    }
197  }
198  if (Object.keys(setAside).length > 0) labels[EXTRA_LABELS_FIELD] = JSON.stringify(setAside)
199  const logId = entry.event
200  const span = entry.span
201  const json = {
202    timestamp: entry.loggedAt,
203    receiveTimestamp: receivedAt,
204    logName: 'projects/' + context.logProject + '/logs/' + encodeURIComponent(logId),
205    resource: context.resource,
206    severity: 'DEFAULT',
207    textPayload: 'claude_code.' + entry.event,
208    labels: { ...labels },
209    insertId,
210  }
211  if (span) {
212    // The bare 32-hex-digit trace ID: Google says "the value from the log
213    // record's traceId field", with no example.
214    json.trace = span.traceId
215    json.spanId = span.spanId
216    // Set only when the sampled bit is 1; "otherwise, it remains unset".
217    if ((span.traceFlags & 1) === 1) json.traceSampled = true
218  }
219  return { table: tableNameOf(logId, tablePrefix), json }
220}
221
222// The labels field that holds, as one JSON object, every label the table
223// has no field of its own for. setup.sh adds it to every table as a JSON
224// field; insertAll takes a JSON field's value as JSON text.
225export const EXTRA_LABELS_FIELD = 'extra_labels'
226// The labels field that names the user ("user.email" as a sink names it).
227export const USER_EMAIL_FIELD = 'user_email'
228
229/**
230 * json fitted to the table's columns (fields, from tables.get): labels the
231 * table has no field for go into labels.extra_labels as JSON text, or are
232 * dropped when the table lacks that field too; resource labels it lacks are
233 * dropped. Also returns the names of the fields it dropped.
234 */
235export function fitToTable(json, fields) {
236  const subfields = (record, name) => record?.find((f) => f.name === name)?.fields ?? []
237  const labelNames = new Set(subfields(fields, 'labels').map((f) => f.name))
238  const resourceNames = new Set(subfields(subfields(fields, 'resource'), 'labels').map((f) => f.name))
239  const hasExtra = labelNames.delete(EXTRA_LABELS_FIELD)
240  const dropped = []
241  const labels = {}
242  // What rowOf already set aside in labels.extra_labels, under the attributes' own keys.
243  const { [EXTRA_LABELS_FIELD]: setAside, ...fieldLabels } = json.labels ?? {}
244  const extra = setAside ? JSON.parse(setAside) : {}
245  if (setAside && !hasExtra) dropped.push('labels.' + EXTRA_LABELS_FIELD)
246  for (const [name, value] of Object.entries(fieldLabels)) {
247    if (labelNames.has(name)) labels[name] = value
248    else if (hasExtra) extra[name] = value
249    else dropped.push('labels.' + name)
250  }
251  if (hasExtra && Object.keys(extra).length > 0) labels[EXTRA_LABELS_FIELD] = JSON.stringify(extra)
252  const resourceLabels = {}
253  for (const [name, value] of Object.entries(json.resource?.labels ?? {})) {
254    if (resourceNames.has(name)) resourceLabels[name] = value
255    else dropped.push('resource.labels.' + name)
256  }
257  return { json: { ...json, labels, resource: { ...json.resource, labels: resourceLabels } }, dropped }
258}
259
260/**
261 * Removes and returns items { table, insertId, json, bytes } from the queue:
262 * those for the first item's table, at most maxRows and maxBytes, but always
263 * at least one.
264 */
265export function takeBatch(queue, maxRows = MAX_BATCH_ROWS, maxBytes = MAX_BATCH_BYTES) {
266  if (queue.length === 0) return []
267  const table = queue[0].table
268  const taken = []
269  let bytes = 0
270  for (let i = 0; i < queue.length && taken.length < maxRows; ) {
271    const item = queue[i]
272    if (item.table !== table) {
273      i++
274      continue
275    }
276    if (bytes + item.bytes > maxBytes && taken.length > 0) break
277    bytes += item.bytes
278    taken.push(item)
279    queue.splice(i, 1)
280  }
281  return taken
282}
283
284/** The insertAll request body for a batch. */
285export function insertAllBody(batch) {
286  return JSON.stringify({
287    kind: 'bigquery#tableDataInsertAllRequest',
288    skipInvalidRows: false,
289    // A backstop: fields the table lacks are dropped rather than refusing
290    // the row. The mod normally removes them first, and says which.
291    ignoreUnknownValues: true,
292    rows: batch.map((item) => ({ insertId: item.insertId, json: item.json })),
293  })
294}
295
296// BigQuery error reasons that mean "try the same request again later".
297// https://cloud.google.com/bigquery/docs/error-messages
298const RETRYABLE_REASONS = new Set([
299  'backendError',
300  'internalError',
301  'rateLimitExceeded',
302  'quotaExceeded',
303  'timeout',
304  'stopped',
305])
306
307/**
308 * Sorts a sent batch by BigQuery's answer into { sent, retry, dropped },
309 * with the reason for any failure. retryLater is true when the retried
310 * rows should wait for a backoff before the next attempt.
311 */
312export function outcomeOf(batch, status, text) {
313  let body
314  try {
315    body = JSON.parse(text)
316  } catch {
317    body = undefined
318  }
319
320  if (status >= 200 && status < 300) {
321    const errors = Array.isArray(body?.insertErrors) ? body.insertErrors : []
322    if (errors.length === 0) return { sent: batch, retry: [], dropped: [], reason: '', retryLater: false }
323    const failed = new Map()
324    for (const error of errors) failed.set(error.index, error.errors ?? [])
325    const sent = []
326    const retry = []
327    const dropped = []
328    const reasons = new Set()
329    batch.forEach((item, index) => {
330      const rowErrors = failed.get(index)
331      if (rowErrors === undefined) sent.push(item)
332      else if (rowErrors.length > 0 && rowErrors.every((e) => RETRYABLE_REASONS.has(e.reason))) retry.push(item)
333      else {
334        dropped.push(item)
335        for (const e of rowErrors) reasons.add(describeError(e))
336      }
337    })
338    return { sent, retry, dropped, reason: [...reasons].join('; '), retryLater: false }
339  }
340
341  const error = body?.error
342  const reasons = (error?.errors ?? []).map((e) => e.reason)
343  const message = error?.message ?? (typeof text === 'string' ? text.slice(0, 200) : '')
344  // 403 too: a missing permission can be granted later, so the rows wait
345  // (with backoff, up to the in-memory limit) instead of being dropped.
346  const isRetryable =
347    status === 401 || status === 403 || status === 408 || status === 429 || status >= 500 ||
348    reasons.some((r) => RETRYABLE_REASONS.has(r))
349  if (isRetryable) {
350    return { sent: [], retry: batch, dropped: [], reason: 'HTTP ' + status + ': ' + message, retryLater: true }
351  }
352  return { sent: [], retry: [], dropped: batch, reason: 'HTTP ' + status + ': ' + message, retryLater: false }
353}
354
355function describeError(error) {
356  const where = error.location ? ' (' + error.location + ')' : ''
357  return (error.reason ?? 'error') + where + ': ' + (error.message ?? '')
358}
359
360/** How long to wait before the next attempt after `failures` failures in a row. */
361export function backoffMs(failures, random = Math.random()) {
362  const base = Math.min(300_000, 2_000 * 2 ** Math.max(0, failures - 1))
363  return Math.round(base * (0.5 + random / 2))
364}
365