gogcli-mcp 2.21.0 → 2.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,7 +7,7 @@
7
7
  },
8
8
  "metadata": {
9
9
  "description": "Google Sheets (and more) for Claude via gogcli — read, write, and manage spreadsheets",
10
- "version": "2.21.0"
10
+ "version": "2.22.0"
11
11
  },
12
12
  "plugins": [
13
13
  {
@@ -15,7 +15,7 @@
15
15
  "displayName": "gogcli",
16
16
  "source": "./",
17
17
  "description": "Google Sheets (and more) for Claude via gogcli — read, write, and manage spreadsheets",
18
- "version": "2.21.0",
18
+ "version": "2.22.0",
19
19
  "author": {
20
20
  "name": "Chris Hall"
21
21
  },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "gogcli-mcp",
3
3
  "displayName": "gogcli",
4
- "version": "2.21.0",
4
+ "version": "2.22.0",
5
5
  "description": "Google Sheets (and more) for Claude via gogcli — read, write, and manage spreadsheets",
6
6
  "author": {
7
7
  "name": "Chris Hall",
package/dist/index.js CHANGED
@@ -31140,6 +31140,21 @@ import { delimiter, join } from "node:path";
31140
31140
  function isGogFileArg(arg) {
31141
31141
  return typeof arg !== "string";
31142
31142
  }
31143
+ var RUNNER_TRANSPORT_BRAND = /* @__PURE__ */ Symbol.for("gogcli.RunnerTransportError");
31144
+ var RunnerTransportError = class extends Error {
31145
+ kind;
31146
+ status;
31147
+ constructor(message, kind, status) {
31148
+ super(message);
31149
+ this.name = "RunnerTransportError";
31150
+ this.kind = kind;
31151
+ this.status = status;
31152
+ Object.defineProperty(this, RUNNER_TRANSPORT_BRAND, { value: true });
31153
+ }
31154
+ };
31155
+ function isRunnerTransportError(err) {
31156
+ return err instanceof Error && err[RUNNER_TRANSPORT_BRAND] === true;
31157
+ }
31143
31158
  var runExecutor = new AsyncLocalStorage();
31144
31159
  var defaultExecutor;
31145
31160
  function setDefaultGogExecutor(executor) {
@@ -31320,7 +31335,11 @@ async function run(args, options = {}) {
31320
31335
  }
31321
31336
  return redact(output);
31322
31337
  } catch (err) {
31323
- throw new Error(redact(err instanceof Error ? err.message : String(err)));
31338
+ const message = redact(err instanceof Error ? err.message : String(err));
31339
+ if (isRunnerTransportError(err)) {
31340
+ throw new RunnerTransportError(message, err.kind, err.status);
31341
+ }
31342
+ throw new Error(message);
31324
31343
  }
31325
31344
  }
31326
31345
  async function runBinary(args, options = {}) {
@@ -31421,6 +31440,13 @@ var TIMESTAMP_KEYS = /* @__PURE__ */ new Set([
31421
31440
  // Calendar event start/end
31422
31441
  "internalDate",
31423
31442
  // Gmail, epoch milliseconds (authoritative)
31443
+ // gog >= 0.35.0 Gmail message AND thread listings. Already offset-bearing
31444
+ // (RFC3339 from internalDate), so it needs no offset repair — it is
31445
+ // allowlisted purely to gain a Display sibling, and to be re-rendered in
31446
+ // DISPLAY_TZ like every other instant. Separately sourced from the sibling
31447
+ // `date`, which is a naive re-format of the sender's Date header; the two may
31448
+ // legitimately disagree. See docs/timestamps.md.
31449
+ "internalDateIso",
31424
31450
  "modifiedTime",
31425
31451
  // Drive
31426
31452
  "createdTime",
@@ -31589,7 +31615,7 @@ function registerRunTool(server, options) {
31589
31615
  function errorText(err) {
31590
31616
  return err instanceof Error ? `Error: ${err.message}` : String(err);
31591
31617
  }
31592
- var DEFINITE_AUTH_PATTERN = /\b(401|unauthorized|invalid_grant)\b/i;
31618
+ var DEFINITE_AUTH_PATTERN = /\b(?:unauthorized|invalid_grant)\b|\b(?:error|status|code|http|responded|response)["']?[\s:=(,]{0,4}401\b/i;
31593
31619
  var STALE_TOKEN_PATTERN = /\b(?:access[ _-]?)?token\b[^.;\n]{0,40}\b(?:has\s+)?(?:been\s+)?(?:expired|revoked)\b|\b(?:expired|revoked)\s+(?:access[ _-]?)?token\b/i;
31594
31620
  var AUTH_ERROR_PATTERN = new RegExp(`${DEFINITE_AUTH_PATTERN.source}|${STALE_TOKEN_PATTERN.source}`, "i");
31595
31621
  var INVALID_GRANT_PATTERN = /invalid_grant|token has been expired or revoked/i;
@@ -31599,6 +31625,14 @@ var AUTH_HINT = "\n\nAuthentication may have expired. Use gog_auth_add to re-aut
31599
31625
  var INVALID_GRANT_HINT = '\n\nThe stored refresh token was rejected (invalid_grant): it has expired or been revoked, so the whole account is signed out and re-authorization is required. The most common cause is the 7-day refresh-token limit Google applies to OAuth apps whose consent screen is still in "Testing" mode. Re-authorize with gog_auth_add (opens a browser) or gog_auth_add_url + gog_auth_add_complete (remote/headless). To stop this recurring, publish the OAuth consent screen to "In production" in the Google Cloud project that owns the OAuth client. Ask the user if they would like to re-authenticate.';
31600
31626
  var TRANSIENT_HINT = "\n\nThis error is often transient. Retry the same call before trying a different approach (do not fall back to smaller writes or row-by-row operations).";
31601
31627
  var GRID_LIMIT_HINT = "\n\nThe target range is outside the sheet's current grid. Add the missing rows or columns first with gog_sheets_insert (dimension: rows or cols), then retry the write.";
31628
+ var RUNNER_TRANSPORT_AUTH_HINT = "\n\nThis is the CONNECTOR's own transport auth failing, not your Google sign-in. The gog-runner backend rejected the bearer token this server sent, so the request never reached gog and no Google credential was checked \u2014 the Google account is not the problem and re-authorizing it cannot fix this. An operator must make the Worker secret GOG_RUNNER_KEY equal RUNNER_KEY on the Fly app (wrangler secret put GOG_RUNNER_KEY / fly secrets set RUNNER_KEY), then retry.";
31629
+ var RUNNER_TRANSPORT_HINTS = {
31630
+ "transport-auth": RUNNER_TRANSPORT_AUTH_HINT,
31631
+ // The request itself was malformed, so the runner will refuse it identically
31632
+ // every time. Nothing to advise beyond the message the runner already gave.
31633
+ "transport-request": "",
31634
+ "transport-retryable": TRANSIENT_HINT
31635
+ };
31602
31636
  function formatAccountList(raw) {
31603
31637
  try {
31604
31638
  const parsed = JSON.parse(raw);
@@ -31611,11 +31645,12 @@ function formatAccountList(raw) {
31611
31645
  }
31612
31646
  async function diagnose(err) {
31613
31647
  const errText = errorText(err);
31648
+ const transportHint = isRunnerTransportError(err) ? RUNNER_TRANSPORT_HINTS[err.kind] : void 0;
31614
31649
  const isInvalidGrant = INVALID_GRANT_PATTERN.test(errText);
31615
31650
  const isTransientError = !DEFINITE_AUTH_PATTERN.test(errText) && TRANSIENT_ERROR_PATTERN.test(errText);
31616
31651
  const isAuthError = !isTransientError && AUTH_ERROR_PATTERN.test(errText);
31617
31652
  const isGridLimitError = GRID_LIMIT_ERROR_PATTERN.test(errText);
31618
- const hint = isInvalidGrant ? INVALID_GRANT_HINT : isAuthError ? AUTH_HINT : isTransientError ? TRANSIENT_HINT : isGridLimitError ? GRID_LIMIT_HINT : "";
31653
+ const hint = transportHint ?? (isInvalidGrant ? INVALID_GRANT_HINT : isAuthError ? AUTH_HINT : isTransientError ? TRANSIENT_HINT : isGridLimitError ? GRID_LIMIT_HINT : "");
31619
31654
  try {
31620
31655
  const accounts = formatAccountList(await run(["auth", "list"]));
31621
31656
  return errorResult(`${errText}
@@ -31648,8 +31683,8 @@ function formatOneAccountHealth(a, now) {
31648
31683
  const age = ageInDays(a.created_at, now);
31649
31684
  const ageStr = age === null ? "" : ` Authorized ${age.toFixed(1)} day(s) ago.`;
31650
31685
  if (a.valid === false) {
31651
- const cause = INVALID_GRANT_PATTERN.test(a.error ?? "") ? 'refresh token expired or revoked \u2014 commonly the 7-day limit on OAuth consent screens still in "Testing" mode' : a.error?.trim() || "unknown error";
31652
- return `\u2717 ${email3}: NEEDS RE-AUTH \u2014 ${cause}.${ageStr} Re-authorize with gog_auth_add (browser) or gog_auth_add_url + gog_auth_add_complete (remote/headless).`;
31686
+ const cause2 = INVALID_GRANT_PATTERN.test(a.error ?? "") ? 'refresh token expired or revoked \u2014 commonly the 7-day limit on OAuth consent screens still in "Testing" mode' : a.error?.trim() || "unknown error";
31687
+ return `\u2717 ${email3}: NEEDS RE-AUTH \u2014 ${cause2}.${ageStr} Re-authorize with gog_auth_add (browser) or gog_auth_add_url + gog_auth_add_complete (remote/headless).`;
31653
31688
  }
31654
31689
  if (a.valid === true) {
31655
31690
  let line = `\u2713 ${email3}: token valid.${ageStr}`;
@@ -31745,7 +31780,7 @@ function registerAuthToolsWith(server, defaultServices) {
31745
31780
  }
31746
31781
  });
31747
31782
  server.registerTool("gog_auth_status", {
31748
- description: "Show gogcli auth configuration: keyring backend, credential files, and auth setup.",
31783
+ description: "Show gogcli auth CONFIGURATION: keyring backend, credential files, and auth setup. Despite the name this is not a health check \u2014 it reads local setup and does not contact Google, so it says nothing about whether an account can still authenticate. Use gog_auth_health for that.",
31749
31784
  annotations: { readOnlyHint: true },
31750
31785
  inputSchema: {}
31751
31786
  }, async () => {
@@ -31756,7 +31791,7 @@ function registerAuthToolsWith(server, defaultServices) {
31756
31791
  }
31757
31792
  });
31758
31793
  server.registerTool("gog_auth_health", {
31759
- description: 'Check the LIVE health of each stored Google account. Unlike gog_auth_status (which only reports keyring/config setup), this performs a real token refresh against Google, so it detects expired or revoked (invalid_grant) refresh tokens \u2014 the account-wide sign-out that blocks every service. Reports per account: whether the token is currently valid, the mapped cause when it is not, how long ago it was authorized, and a warning as it approaches the 7-day refresh-token limit that applies to OAuth apps whose consent screen is still in "Testing" mode. Run it proactively to re-authorize on your own schedule instead of mid-task.',
31794
+ description: 'Check the LIVE health of each stored Google account. Unlike gog_auth_status (which only reports keyring/config setup), this performs a real token refresh against Google, so it detects expired or revoked (invalid_grant) refresh tokens \u2014 the account-wide sign-out that blocks every service. Reports per account: whether the token is currently valid, the mapped cause when it is not, how long ago it was authorized, and a warning as it approaches the 7-day refresh-token limit that applies to OAuth apps whose consent screen is still in "Testing" mode. Run it proactively to re-authorize on your own schedule instead of mid-task. On the hosted connector this is the ONLY check that measures Google: a connector showing "connected" or "refreshed" has verified the connector key that reaches the gog machine, and nothing else \u2014 the Google credential lives on that machine and can be dead while the connection looks perfectly healthy.',
31760
31795
  annotations: { readOnlyHint: true },
31761
31796
  inputSchema: {}
31762
31797
  }, async () => {
@@ -33103,7 +33138,7 @@ function registerTasksTools(server) {
33103
33138
  }
33104
33139
 
33105
33140
  // src/server.ts
33106
- var VERSION = true ? "2.21.0" : "0.0.0";
33141
+ var VERSION = true ? "2.22.0" : "0.0.0";
33107
33142
  var BASE_TOOL_REGISTRARS = [
33108
33143
  registerApiTools,
33109
33144
  registerAuthTools,
@@ -33118,6 +33153,39 @@ var BASE_TOOL_REGISTRARS = [
33118
33153
  registerTasksTools
33119
33154
  ];
33120
33155
 
33156
+ // src/auth-log.ts
33157
+ var FAILURES = /* @__PURE__ */ new Set([
33158
+ "token.mint-failed",
33159
+ "grant.dead",
33160
+ "replay.failed",
33161
+ "runner.auth-failed",
33162
+ "connect.key-rejected",
33163
+ // An enrolment that could not proceed is a failure even though nobody is at
33164
+ // fault: it is the only trace a half-enrolled connector leaves behind, and
33165
+ // the absence of exactly this record is why DEFECT 4 could not be explained.
33166
+ "connect.runner-unreachable",
33167
+ "connect.google-unhealthy",
33168
+ "refusal.google-unhealthy",
33169
+ // The loudest record on this branch, and the only one that means "we cannot
33170
+ // explain this". Google refused a real call while a live check of the same
33171
+ // credential, taken seconds later, succeeded — so neither the 7-day cliff nor
33172
+ // a revoked grant accounts for it. It is filed as a failure precisely because
33173
+ // it is the record nobody may scroll past: it is the only evidence that could
33174
+ // ever justify building something on the hosted path, and its absence over
33175
+ // time is what retires that theory for good.
33176
+ "refusal.google-ok"
33177
+ ]);
33178
+ var PREFIX = "gog-auth ";
33179
+ var TAG_CHARS = 12;
33180
+ function credentialTag(cacheKeyHash) {
33181
+ return cacheKeyHash.slice(0, TAG_CHARS);
33182
+ }
33183
+ function logAuthTransition(event, context) {
33184
+ const record2 = JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), event, ...context });
33185
+ const write = FAILURES.has(event) ? console.error : console.warn;
33186
+ write(PREFIX + redactSecrets2(record2));
33187
+ }
33188
+
33121
33189
  // src/google-token.ts
33122
33190
  var TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token";
33123
33191
  var EXPIRY_MARGIN_MS = 12e4;
@@ -33143,22 +33211,73 @@ function makeAccessTokenSource(env) {
33143
33211
  );
33144
33212
  };
33145
33213
  }
33146
- return async () => {
33147
- const key = await cacheKey(refreshToken, clientId);
33148
- const hit = cache.get(key);
33149
- if (hit && hit.expiresAt - EXPIRY_MARGIN_MS > Date.now()) return hit.accessToken;
33150
- let pending = inFlight.get(key);
33214
+ let keyPromise;
33215
+ const key = () => keyPromise ??= cacheKey(refreshToken, clientId);
33216
+ const logCacheHits = parseBoolEnv("GOG_AUTH_LOG_CACHE_HITS", { env });
33217
+ const read = async () => {
33218
+ const k = await key();
33219
+ const hit = cache.get(k);
33220
+ if (hit && hit.expiresAt - EXPIRY_MARGIN_MS > Date.now()) {
33221
+ if (logCacheHits) logAuthTransition("token.cache-hit", { credential: credentialTag(k) });
33222
+ return hit.accessToken;
33223
+ }
33224
+ let pending = inFlight.get(k);
33151
33225
  if (!pending) {
33152
33226
  pending = exchange(refreshToken, clientId, clientSecret).then((minted2) => {
33153
- cache.set(key, minted2);
33227
+ cache.set(k, minted2);
33228
+ logAuthTransition("token.minted", {
33229
+ credential: credentialTag(k),
33230
+ reason: `valid for ${Math.round((minted2.expiresAt - Date.now()) / 1e3)}s`
33231
+ });
33154
33232
  return minted2;
33155
- }).finally(() => inFlight.delete(key));
33156
- inFlight.set(key, pending);
33233
+ }).catch((err) => {
33234
+ logAuthTransition(err.grantDead ? "grant.dead" : "token.mint-failed", {
33235
+ credential: credentialTag(k),
33236
+ reason: err.message
33237
+ });
33238
+ throw err;
33239
+ }).finally(() => inFlight.delete(k));
33240
+ inFlight.set(k, pending);
33157
33241
  }
33158
33242
  const minted = await pending;
33159
33243
  return minted.accessToken;
33160
33244
  };
33245
+ const invalidate = async (rejected) => {
33246
+ const k = await key();
33247
+ const hit = cache.get(k);
33248
+ if (!hit || hit.accessToken !== rejected) {
33249
+ logAuthTransition("token.evict-noop", {
33250
+ credential: credentialTag(k),
33251
+ reason: hit ? "a concurrent caller had already replaced this credential\u2019s token" : "no token was cached for this credential"
33252
+ });
33253
+ return false;
33254
+ }
33255
+ cache.delete(k);
33256
+ logAuthTransition("token.evicted", {
33257
+ credential: credentialTag(k),
33258
+ reason: "Google rejected this access token; the next read will mint a new one"
33259
+ });
33260
+ return true;
33261
+ };
33262
+ return Object.assign(read, {
33263
+ invalidate,
33264
+ credentialId: async () => credentialTag(await key())
33265
+ });
33161
33266
  }
33267
+ var TokenExchangeError = class extends Error {
33268
+ /**
33269
+ * The REFRESH token is dead (Google's `invalid_grant`), not merely the access
33270
+ * token. Carried as a flag rather than re-read from the message, because
33271
+ * inferring the author of a failure from prose several authors can produce is
33272
+ * precisely the mistake this branch exists to undo. `instanceof` is safe: the
33273
+ * class is thrown and caught inside this one module.
33274
+ */
33275
+ grantDead;
33276
+ constructor(message, grantDead) {
33277
+ super(message);
33278
+ this.grantDead = grantDead;
33279
+ }
33280
+ };
33162
33281
  async function exchange(refreshToken, clientId, clientSecret) {
33163
33282
  let res;
33164
33283
  try {
@@ -33173,79 +33292,338 @@ async function exchange(refreshToken, clientId, clientSecret) {
33173
33292
  }).toString()
33174
33293
  });
33175
33294
  } catch (err) {
33176
- throw new Error(
33177
- `the Google token exchange could not be reached: ${err instanceof Error ? err.message : String(err)}`
33295
+ throw new TokenExchangeError(
33296
+ `the Google token exchange could not be reached: ${err instanceof Error ? err.message : String(err)}`,
33297
+ false
33178
33298
  );
33179
33299
  }
33180
33300
  const body = await res.json().catch(() => ({}));
33181
33301
  if (!res.ok) {
33182
33302
  if (body.error === "invalid_grant") {
33183
- throw new Error(
33184
- 'the stored refresh token has expired or been revoked, so this account must be re-authorized (commonly the 7-day limit on OAuth consent screens still in "Testing" mode). Re-enrol with gog_auth_add_url + gog_auth_add_complete and store the new refresh token.'
33303
+ throw new TokenExchangeError(
33304
+ 'the stored refresh token was rejected (invalid_grant): it has expired or been revoked, so this account must be re-authorized (commonly the 7-day limit on OAuth consent screens still in "Testing" mode). Re-enrol with gog_auth_add_url + gog_auth_add_complete and store the new refresh token.',
33305
+ true
33185
33306
  );
33186
33307
  }
33187
- throw new Error(
33188
- `the access token could not be refreshed (HTTP ${res.status}${body.error ? `, ${body.error}` : ""})`
33308
+ throw new TokenExchangeError(
33309
+ `the access token could not be refreshed (HTTP ${res.status}${body.error ? `, ${body.error}` : ""})`,
33310
+ false
33189
33311
  );
33190
33312
  }
33191
33313
  if (!body.access_token) {
33192
- throw new Error("the access token could not be refreshed: Google returned no access_token");
33314
+ throw new TokenExchangeError(
33315
+ "the access token could not be refreshed: Google returned no access_token",
33316
+ false
33317
+ );
33193
33318
  }
33194
33319
  const expiresInMs = (body.expires_in ?? 3600) * 1e3;
33195
33320
  return { accessToken: body.access_token, expiresAt: Date.now() + expiresInMs };
33196
33321
  }
33197
33322
 
33323
+ // src/google-probe.ts
33324
+ var bool = (value) => typeof value === "boolean" ? value : void 0;
33325
+ var cause = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
33326
+ function readGoogleProbe(body) {
33327
+ const record2 = typeof body === "object" && body !== null ? body : {};
33328
+ const measured = bool(record2.measured);
33329
+ const reported = cause(record2.error);
33330
+ if (measured === false) {
33331
+ return {
33332
+ kind: "unmeasured",
33333
+ reason: reported ?? "the runner reported it could not measure the Google layer"
33334
+ };
33335
+ }
33336
+ if (measured === true) {
33337
+ if (bool(record2.ok) === true) return { kind: "ok" };
33338
+ return {
33339
+ kind: "unhealthy",
33340
+ reason: reported ?? "the runner reported the Google layer unhealthy with no cause"
33341
+ };
33342
+ }
33343
+ return {
33344
+ kind: "unmeasured",
33345
+ reason: reported ? `the runner did not report whether it measured the Google layer; it said: ${reported}` : "the runner did not report whether it measured the Google layer"
33346
+ };
33347
+ }
33348
+
33198
33349
  // src/connector-runtime.ts
33199
33350
  var DEFAULT_TIMEOUT_MS = 3e4;
33200
33351
  var DEADLINE_GRACE_MS = 5e3;
33352
+ var MIN_REPLAY_BUDGET_MS = 1e3;
33353
+ var REFUSAL_PROBE_TIMEOUT_MS = 4e3;
33354
+ var MIN_PROBE_BUDGET_MS = 1e3;
33355
+ var PROBE_INTERVAL_MS = 6e4;
33201
33356
  var RUNNER_GOG_FAILED = 422;
33202
33357
  var RUNNER_DRAINING = 503;
33358
+ var RUNNER_BAD_REQUEST = 400;
33359
+ var RUNNER_BAD_KEY = 401;
33360
+ var GogFailedError = class extends Error {
33361
+ /** gog's stderr alone, with no echoed argv mixed in. */
33362
+ stderr;
33363
+ constructor(message, stderr) {
33364
+ super(message);
33365
+ this.stderr = stderr;
33366
+ }
33367
+ };
33368
+ var GOOGLE_TOKEN_REJECTED_PATTERN = /Google API error \(401\b|invalid[ _]authentication[ _]credentials|\bACCESS_TOKEN_EXPIRED\b|\binvalid_token\b/i;
33369
+ var REFRESH_TOKEN_DEAD_PATTERN = /\binvalid_grant\b/i;
33370
+ var READ_ONLY_SUBCOMMANDS = /* @__PURE__ */ new Set([
33371
+ "cat",
33372
+ "describe",
33373
+ "get",
33374
+ "info",
33375
+ "list",
33376
+ "list-slides",
33377
+ "ls",
33378
+ "metadata",
33379
+ "read-slide",
33380
+ "search",
33381
+ "services",
33382
+ "status",
33383
+ "structure"
33384
+ ]);
33385
+ function gogTarget(args) {
33386
+ const words = args.filter((arg) => typeof arg === "string");
33387
+ let service;
33388
+ for (let i = 0; i < words.length; i += 1) {
33389
+ const word = words[i];
33390
+ if (word.startsWith("-")) {
33391
+ if (word === "--account") i += 1;
33392
+ continue;
33393
+ }
33394
+ if (service === void 0) {
33395
+ service = word;
33396
+ continue;
33397
+ }
33398
+ return { service, subcommand: word };
33399
+ }
33400
+ return { service };
33401
+ }
33402
+ async function remintAfterGoogleRejection(err, used, args, readAccessToken, deadlineAt, probeGoogle) {
33403
+ if (!(err instanceof GogFailedError)) return void 0;
33404
+ const grantDead = REFRESH_TOKEN_DEAD_PATTERN.test(err.stderr);
33405
+ if (!grantDead && !GOOGLE_TOKEN_REJECTED_PATTERN.test(err.stderr)) return void 0;
33406
+ const { service, subcommand } = gogTarget(args);
33407
+ const credential = await readAccessToken?.credentialId?.();
33408
+ const where = { credential, service };
33409
+ if (grantDead) {
33410
+ logAuthTransition("grant.dead", {
33411
+ ...where,
33412
+ reason: "gog reported invalid_grant: the stored refresh token is dead, so no token can be minted and this account must be re-authorized"
33413
+ });
33414
+ return void 0;
33415
+ }
33416
+ if (!used) {
33417
+ await probeGoogle(where);
33418
+ logAuthTransition("replay.declined", {
33419
+ ...where,
33420
+ reason: "no access token was supplied with the call, so gog acted as the backend volume\u2019s own identity"
33421
+ });
33422
+ return void 0;
33423
+ }
33424
+ if (!readAccessToken?.invalidate) {
33425
+ logAuthTransition("replay.declined", {
33426
+ ...where,
33427
+ reason: "this token source cannot mint a replacement, so a replay would resend the rejected token"
33428
+ });
33429
+ return void 0;
33430
+ }
33431
+ const evicted = await readAccessToken.invalidate(used);
33432
+ if (subcommand === void 0 || !READ_ONLY_SUBCOMMANDS.has(subcommand)) {
33433
+ logAuthTransition("replay.declined", {
33434
+ ...where,
33435
+ reason: `not replayable: '${subcommand ?? "(none)"}' is not a known read-only subcommand and a write could double-apply`
33436
+ });
33437
+ return void 0;
33438
+ }
33439
+ if (!evicted) {
33440
+ logAuthTransition("replay.declined", {
33441
+ ...where,
33442
+ reason: "the rejected token was already superseded, so the cache holds the token a replay would send"
33443
+ });
33444
+ return void 0;
33445
+ }
33446
+ const fresh = await readAccessToken();
33447
+ if (!fresh) {
33448
+ logAuthTransition("replay.declined", {
33449
+ ...where,
33450
+ reason: "the token source produced no token after eviction; replaying without one would act as the backend"
33451
+ });
33452
+ return void 0;
33453
+ }
33454
+ const budgetMs = deadlineAt - Date.now();
33455
+ if (budgetMs < MIN_REPLAY_BUDGET_MS) {
33456
+ logAuthTransition("replay.declined", {
33457
+ ...where,
33458
+ reason: `only ${budgetMs}ms of the call\u2019s deadline remained, so a replay could only time out; the rejected token was evicted, so the next call mints a fresh one`
33459
+ });
33460
+ return void 0;
33461
+ }
33462
+ return { token: fresh, budgetMs, invalidate: readAccessToken.invalidate, ...where };
33463
+ }
33203
33464
  function makeFlyExecutor(endpoint, key, readAccessToken) {
33465
+ let lastProbeAt = Number.NEGATIVE_INFINITY;
33466
+ const probeGoogleAfterRefusal = async (where, deadlineAt) => {
33467
+ const record2 = { ...where, endpoint };
33468
+ const now = Date.now();
33469
+ const remainingMs = deadlineAt - now;
33470
+ if (remainingMs < MIN_PROBE_BUDGET_MS) {
33471
+ logAuthTransition("refusal.google-unmeasured", {
33472
+ ...record2,
33473
+ reason: `only ${remainingMs}ms of the call\u2019s deadline remained, so the Google layer was not measured rather than delay the caller\u2019s own error`
33474
+ });
33475
+ return;
33476
+ }
33477
+ if (now - lastProbeAt < PROBE_INTERVAL_MS) {
33478
+ logAuthTransition("refusal.google-unmeasured", {
33479
+ ...record2,
33480
+ // "attempted", not "measured". `lastProbeAt` is stamped before the
33481
+ // fetch and is deliberately NOT reset when the probe comes back with no
33482
+ // verdict (a 404 from a runner too old to have the endpoint, a timeout,
33483
+ // a dead socket) — the backend cost this throttle exists to bound was
33484
+ // paid either way, and resetting it would let a retry loop storm a
33485
+ // runner that is already unwell. So the timestamp stays and the sentence
33486
+ // has to be the true one: on this branch a log line may not assert a
33487
+ // measurement that never happened, and the previous probe may well have
33488
+ // measured nothing at all.
33489
+ reason: "a Google probe was attempted recently, so another was not sent: this probe spawns gog on the backend and takes the keyring\u2019s exclusive lock"
33490
+ });
33491
+ return;
33492
+ }
33493
+ lastProbeAt = now;
33494
+ let event;
33495
+ let reason;
33496
+ try {
33497
+ const res = await fetch(`${endpoint}/health/google`, {
33498
+ headers: { Authorization: `Bearer ${key}` },
33499
+ // Never more than the probe's own budget, never more than the call has
33500
+ // left. `Math.min` rather than a plain constant because the second
33501
+ // bound is the caller's, and it outranks ours.
33502
+ signal: AbortSignal.timeout(Math.min(REFUSAL_PROBE_TIMEOUT_MS, remainingMs))
33503
+ });
33504
+ if (!res.ok) {
33505
+ event = "refusal.google-unmeasured";
33506
+ reason = `the runner did not answer the Google probe (HTTP ${res.status})`;
33507
+ } else {
33508
+ const verdict = readGoogleProbe(await res.json());
33509
+ if (verdict.kind === "ok") {
33510
+ event = "refusal.google-ok";
33511
+ reason = "Google refused this call, yet a live token check on the same volume succeeded \u2014 so a dead or expired refresh token does not explain this refusal";
33512
+ } else {
33513
+ event = verdict.kind === "unhealthy" ? "refusal.google-unhealthy" : "refusal.google-unmeasured";
33514
+ reason = verdict.reason;
33515
+ }
33516
+ }
33517
+ } catch (err) {
33518
+ event = "refusal.google-unmeasured";
33519
+ reason = err instanceof Error ? err.message : String(err);
33520
+ }
33521
+ logAuthTransition(event, { ...record2, reason });
33522
+ };
33204
33523
  return async (args, opts) => {
33205
33524
  const deadlineMs = (opts?.timeout ?? DEFAULT_TIMEOUT_MS) + DEADLINE_GRACE_MS;
33206
33525
  const accessToken = await readAccessToken?.();
33207
- let res;
33526
+ const deadlineAt = Date.now() + deadlineMs;
33208
33527
  try {
33209
- res = await fetch(endpoint + "/run", {
33210
- method: "POST",
33211
- headers: {
33212
- Authorization: "Bearer " + key,
33213
- "Content-Type": "application/json"
33214
- },
33215
- body: JSON.stringify(accessToken ? { args, accessToken } : { args }),
33216
- signal: AbortSignal.timeout(deadlineMs)
33217
- });
33528
+ return await attempt(endpoint, key, args, accessToken, deadlineMs);
33218
33529
  } catch (err) {
33219
- const name = err instanceof Error ? err.name : "";
33220
- if (name === "TimeoutError" || name === "AbortError") {
33221
- throw new Error(
33222
- `gog-runner did not respond within ${deadlineMs}ms (${endpoint}) \u2014 the Fly backend may be cold or wedged`
33223
- );
33530
+ const replay = await remintAfterGoogleRejection(
33531
+ err,
33532
+ accessToken,
33533
+ args,
33534
+ readAccessToken,
33535
+ deadlineAt,
33536
+ (where2) => probeGoogleAfterRefusal(where2, deadlineAt)
33537
+ );
33538
+ if (replay === void 0) throw err;
33539
+ const where = { credential: replay.credential, service: replay.service, endpoint };
33540
+ logAuthTransition("replay.attempted", {
33541
+ ...where,
33542
+ reason: "Google rejected the access token; replaying this read once with a freshly minted one"
33543
+ });
33544
+ try {
33545
+ const stdout = await attempt(endpoint, key, args, replay.token, replay.budgetMs);
33546
+ logAuthTransition("replay.succeeded", where);
33547
+ return stdout;
33548
+ } catch (replayErr) {
33549
+ logAuthTransition("replay.failed", { ...where, reason: String(replayErr) });
33550
+ if (replayErr instanceof GogFailedError && GOOGLE_TOKEN_REJECTED_PATTERN.test(replayErr.stderr)) {
33551
+ await replay.invalidate(replay.token);
33552
+ }
33553
+ throw replayErr;
33224
33554
  }
33225
- throw err;
33226
33555
  }
33227
- if (!res.ok) {
33228
- const body = await res.json().catch(() => null);
33229
- const detail = body && typeof body.error === "string" ? body.stderr && body.stderr.trim() && body.stderr.trim() !== body.error.trim() ? `${body.error}
33556
+ };
33557
+ }
33558
+ async function attempt(endpoint, key, args, accessToken, deadlineMs) {
33559
+ let res;
33560
+ try {
33561
+ res = await fetch(endpoint + "/run", {
33562
+ method: "POST",
33563
+ headers: {
33564
+ Authorization: "Bearer " + key,
33565
+ "Content-Type": "application/json"
33566
+ },
33567
+ body: JSON.stringify(accessToken ? { args, accessToken } : { args }),
33568
+ signal: AbortSignal.timeout(deadlineMs)
33569
+ });
33570
+ } catch (err) {
33571
+ const name = err instanceof Error ? err.name : "";
33572
+ if (name === "TimeoutError" || name === "AbortError") {
33573
+ throw new RunnerTransportError(
33574
+ `gog-runner did not respond within ${deadlineMs}ms (${endpoint}) \u2014 the Fly backend may be cold or wedged`,
33575
+ "transport-retryable"
33576
+ );
33577
+ }
33578
+ throw err;
33579
+ }
33580
+ if (!res.ok) {
33581
+ const body = await res.json().catch(() => null);
33582
+ const detail = body && typeof body.error === "string" ? body.stderr && body.stderr.trim() && body.stderr.trim() !== body.error.trim() ? `${body.error}
33230
33583
  ${body.stderr}` : body.error : "";
33231
- if (res.status === RUNNER_GOG_FAILED) {
33232
- throw new Error(detail || "gog failed on the runner (no detail supplied)");
33233
- }
33234
- if (res.status === RUNNER_DRAINING || body?.retryable === true) {
33235
- throw new Error(
33236
- `gog-runner is restarting; retry this call.${detail ? ` ${detail}` : ""}`
33237
- );
33238
- }
33239
- if (detail) {
33240
- throw new Error(detail);
33241
- }
33242
- throw new Error(
33243
- `gog-runner HTTP ${res.status}: the response did not come from the runner, so the request never reached gog. The backend Machine was most likely starting or shutting down \u2014 this is transient, retry the same call.`
33584
+ if (res.status === RUNNER_GOG_FAILED) {
33585
+ throw new GogFailedError(
33586
+ detail || "gog failed on the runner (no detail supplied)",
33587
+ typeof body?.stderr === "string" ? body.stderr : ""
33244
33588
  );
33245
33589
  }
33246
- const { stdout } = await res.json();
33247
- return stdout;
33248
- };
33590
+ if (res.status === RUNNER_BAD_KEY) {
33591
+ logAuthTransition("runner.auth-failed", {
33592
+ service: gogTarget(args).service,
33593
+ endpoint,
33594
+ reason: "the gog-runner rejected the connector\u2019s bearer token, so gog never ran and no Google credential was read; GOG_RUNNER_KEY does not match the Fly app\u2019s RUNNER_KEY"
33595
+ });
33596
+ throw new RunnerTransportError(
33597
+ "gog-runner rejected the connector's bearer token, so the request never reached gog and no Google credential was involved. The Worker secret GOG_RUNNER_KEY no longer matches RUNNER_KEY on the Fly app; set them to the same value (wrangler secret put GOG_RUNNER_KEY / fly secrets set RUNNER_KEY) and retry.",
33598
+ "transport-auth",
33599
+ res.status
33600
+ );
33601
+ }
33602
+ if (res.status === RUNNER_BAD_REQUEST) {
33603
+ throw new RunnerTransportError(
33604
+ detail || "gog-runner rejected the request (no detail supplied)",
33605
+ "transport-request",
33606
+ res.status
33607
+ );
33608
+ }
33609
+ if (res.status === RUNNER_DRAINING || body?.retryable === true) {
33610
+ throw new RunnerTransportError(
33611
+ `gog-runner is restarting; retry this call.${detail ? ` ${detail}` : ""}`,
33612
+ "transport-retryable",
33613
+ res.status
33614
+ );
33615
+ }
33616
+ if (detail) {
33617
+ throw new Error(detail);
33618
+ }
33619
+ throw new RunnerTransportError(
33620
+ `gog-runner HTTP ${res.status}: the response did not come from the runner, so the request never reached gog. The backend Machine was most likely starting or shutting down \u2014 this is transient, retry the same call.`,
33621
+ "transport-retryable",
33622
+ res.status
33623
+ );
33624
+ }
33625
+ const { stdout } = await res.json();
33626
+ return stdout;
33249
33627
  }
33250
33628
 
33251
33629
  // src/remote-runner.ts