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.
package/dist/lib.js CHANGED
@@ -23018,6 +23018,21 @@ import { delimiter, join } from "node:path";
23018
23018
  function isGogFileArg(arg) {
23019
23019
  return typeof arg !== "string";
23020
23020
  }
23021
+ var RUNNER_TRANSPORT_BRAND = /* @__PURE__ */ Symbol.for("gogcli.RunnerTransportError");
23022
+ var RunnerTransportError = class extends Error {
23023
+ kind;
23024
+ status;
23025
+ constructor(message, kind, status) {
23026
+ super(message);
23027
+ this.name = "RunnerTransportError";
23028
+ this.kind = kind;
23029
+ this.status = status;
23030
+ Object.defineProperty(this, RUNNER_TRANSPORT_BRAND, { value: true });
23031
+ }
23032
+ };
23033
+ function isRunnerTransportError(err) {
23034
+ return err instanceof Error && err[RUNNER_TRANSPORT_BRAND] === true;
23035
+ }
23021
23036
  var runExecutor = new AsyncLocalStorage();
23022
23037
  var defaultExecutor;
23023
23038
  function setDefaultGogExecutor(executor) {
@@ -23027,7 +23042,7 @@ function activeExecutor() {
23027
23042
  return runExecutor.getStore() ?? defaultExecutor;
23028
23043
  }
23029
23044
  var TIMEOUT_MS = 3e4;
23030
- var MIN_GOG_VERSION = "0.34.1";
23045
+ var MIN_GOG_VERSION = "0.35.0";
23031
23046
  function readonlyEnvEnabled() {
23032
23047
  return readEnvVar("GOG_READONLY") !== void 0 && parseBoolEnv("GOG_READONLY", { default: true });
23033
23048
  }
@@ -23199,7 +23214,11 @@ async function run(args, options = {}) {
23199
23214
  }
23200
23215
  return redact(output);
23201
23216
  } catch (err) {
23202
- throw new Error(redact(err instanceof Error ? err.message : String(err)));
23217
+ const message = redact(err instanceof Error ? err.message : String(err));
23218
+ if (isRunnerTransportError(err)) {
23219
+ throw new RunnerTransportError(message, err.kind, err.status);
23220
+ }
23221
+ throw new Error(message);
23203
23222
  }
23204
23223
  }
23205
23224
  async function runBinary(args, options = {}) {
@@ -23300,6 +23319,13 @@ var TIMESTAMP_KEYS = /* @__PURE__ */ new Set([
23300
23319
  // Calendar event start/end
23301
23320
  "internalDate",
23302
23321
  // Gmail, epoch milliseconds (authoritative)
23322
+ // gog >= 0.35.0 Gmail message AND thread listings. Already offset-bearing
23323
+ // (RFC3339 from internalDate), so it needs no offset repair — it is
23324
+ // allowlisted purely to gain a Display sibling, and to be re-rendered in
23325
+ // DISPLAY_TZ like every other instant. Separately sourced from the sibling
23326
+ // `date`, which is a naive re-format of the sender's Date header; the two may
23327
+ // legitimately disagree. See docs/timestamps.md.
23328
+ "internalDateIso",
23303
23329
  "modifiedTime",
23304
23330
  // Drive
23305
23331
  "createdTime",
@@ -23473,7 +23499,7 @@ function registerRunTool(server, options) {
23473
23499
  function errorText(err) {
23474
23500
  return err instanceof Error ? `Error: ${err.message}` : String(err);
23475
23501
  }
23476
- var DEFINITE_AUTH_PATTERN = /\b(401|unauthorized|invalid_grant)\b/i;
23502
+ var DEFINITE_AUTH_PATTERN = /\b(?:unauthorized|invalid_grant)\b|\b(?:error|status|code|http|responded|response)["']?[\s:=(,]{0,4}401\b/i;
23477
23503
  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;
23478
23504
  var AUTH_ERROR_PATTERN = new RegExp(`${DEFINITE_AUTH_PATTERN.source}|${STALE_TOKEN_PATTERN.source}`, "i");
23479
23505
  var INVALID_GRANT_PATTERN = /invalid_grant|token has been expired or revoked/i;
@@ -23483,6 +23509,14 @@ var AUTH_HINT = "\n\nAuthentication may have expired. Use gog_auth_add to re-aut
23483
23509
  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.';
23484
23510
  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).";
23485
23511
  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.";
23512
+ 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.";
23513
+ var RUNNER_TRANSPORT_HINTS = {
23514
+ "transport-auth": RUNNER_TRANSPORT_AUTH_HINT,
23515
+ // The request itself was malformed, so the runner will refuse it identically
23516
+ // every time. Nothing to advise beyond the message the runner already gave.
23517
+ "transport-request": "",
23518
+ "transport-retryable": TRANSIENT_HINT
23519
+ };
23486
23520
  function formatAccountList(raw) {
23487
23521
  try {
23488
23522
  const parsed = JSON.parse(raw);
@@ -23495,11 +23529,12 @@ function formatAccountList(raw) {
23495
23529
  }
23496
23530
  async function diagnose(err) {
23497
23531
  const errText = errorText(err);
23532
+ const transportHint = isRunnerTransportError(err) ? RUNNER_TRANSPORT_HINTS[err.kind] : void 0;
23498
23533
  const isInvalidGrant = INVALID_GRANT_PATTERN.test(errText);
23499
23534
  const isTransientError = !DEFINITE_AUTH_PATTERN.test(errText) && TRANSIENT_ERROR_PATTERN.test(errText);
23500
23535
  const isAuthError = !isTransientError && AUTH_ERROR_PATTERN.test(errText);
23501
23536
  const isGridLimitError = GRID_LIMIT_ERROR_PATTERN.test(errText);
23502
- const hint = isInvalidGrant ? INVALID_GRANT_HINT : isAuthError ? AUTH_HINT : isTransientError ? TRANSIENT_HINT : isGridLimitError ? GRID_LIMIT_HINT : "";
23537
+ const hint = transportHint ?? (isInvalidGrant ? INVALID_GRANT_HINT : isAuthError ? AUTH_HINT : isTransientError ? TRANSIENT_HINT : isGridLimitError ? GRID_LIMIT_HINT : "");
23503
23538
  try {
23504
23539
  const accounts = formatAccountList(await run(["auth", "list"]));
23505
23540
  return errorResult(`${errText}
@@ -23532,8 +23567,8 @@ function formatOneAccountHealth(a, now) {
23532
23567
  const age = ageInDays(a.created_at, now);
23533
23568
  const ageStr = age === null ? "" : ` Authorized ${age.toFixed(1)} day(s) ago.`;
23534
23569
  if (a.valid === false) {
23535
- 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";
23536
- 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).`;
23570
+ 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";
23571
+ 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).`;
23537
23572
  }
23538
23573
  if (a.valid === true) {
23539
23574
  let line = `\u2713 ${email3}: token valid.${ageStr}`;
@@ -23629,7 +23664,7 @@ function registerAuthToolsWith(server, defaultServices) {
23629
23664
  }
23630
23665
  });
23631
23666
  server.registerTool("gog_auth_status", {
23632
- description: "Show gogcli auth configuration: keyring backend, credential files, and auth setup.",
23667
+ 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.",
23633
23668
  annotations: { readOnlyHint: true },
23634
23669
  inputSchema: {}
23635
23670
  }, async () => {
@@ -23640,7 +23675,7 @@ function registerAuthToolsWith(server, defaultServices) {
23640
23675
  }
23641
23676
  });
23642
23677
  server.registerTool("gog_auth_health", {
23643
- 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.',
23678
+ 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.',
23644
23679
  annotations: { readOnlyHint: true },
23645
23680
  inputSchema: {}
23646
23681
  }, async () => {
@@ -24990,7 +25025,7 @@ function registerTasksTools(server) {
24990
25025
  }
24991
25026
 
24992
25027
  // src/server.ts
24993
- var VERSION = true ? "2.21.0" : "0.0.0";
25028
+ var VERSION = true ? "2.22.0" : "0.0.0";
24994
25029
  var BASE_TOOL_REGISTRARS = [
24995
25030
  registerApiTools,
24996
25031
  registerAuthTools,
@@ -25005,6 +25040,39 @@ var BASE_TOOL_REGISTRARS = [
25005
25040
  registerTasksTools
25006
25041
  ];
25007
25042
 
25043
+ // src/auth-log.ts
25044
+ var FAILURES = /* @__PURE__ */ new Set([
25045
+ "token.mint-failed",
25046
+ "grant.dead",
25047
+ "replay.failed",
25048
+ "runner.auth-failed",
25049
+ "connect.key-rejected",
25050
+ // An enrolment that could not proceed is a failure even though nobody is at
25051
+ // fault: it is the only trace a half-enrolled connector leaves behind, and
25052
+ // the absence of exactly this record is why DEFECT 4 could not be explained.
25053
+ "connect.runner-unreachable",
25054
+ "connect.google-unhealthy",
25055
+ "refusal.google-unhealthy",
25056
+ // The loudest record on this branch, and the only one that means "we cannot
25057
+ // explain this". Google refused a real call while a live check of the same
25058
+ // credential, taken seconds later, succeeded — so neither the 7-day cliff nor
25059
+ // a revoked grant accounts for it. It is filed as a failure precisely because
25060
+ // it is the record nobody may scroll past: it is the only evidence that could
25061
+ // ever justify building something on the hosted path, and its absence over
25062
+ // time is what retires that theory for good.
25063
+ "refusal.google-ok"
25064
+ ]);
25065
+ var PREFIX = "gog-auth ";
25066
+ var TAG_CHARS = 12;
25067
+ function credentialTag(cacheKeyHash) {
25068
+ return cacheKeyHash.slice(0, TAG_CHARS);
25069
+ }
25070
+ function logAuthTransition(event, context) {
25071
+ const record2 = JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), event, ...context });
25072
+ const write = FAILURES.has(event) ? console.error : console.warn;
25073
+ write(PREFIX + redactSecrets2(record2));
25074
+ }
25075
+
25008
25076
  // src/google-token.ts
25009
25077
  var TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token";
25010
25078
  var EXPIRY_MARGIN_MS = 12e4;
@@ -25030,22 +25098,73 @@ function makeAccessTokenSource(env) {
25030
25098
  );
25031
25099
  };
25032
25100
  }
25033
- return async () => {
25034
- const key = await cacheKey(refreshToken, clientId);
25035
- const hit = cache.get(key);
25036
- if (hit && hit.expiresAt - EXPIRY_MARGIN_MS > Date.now()) return hit.accessToken;
25037
- let pending = inFlight.get(key);
25101
+ let keyPromise;
25102
+ const key = () => keyPromise ??= cacheKey(refreshToken, clientId);
25103
+ const logCacheHits = parseBoolEnv("GOG_AUTH_LOG_CACHE_HITS", { env });
25104
+ const read = async () => {
25105
+ const k = await key();
25106
+ const hit = cache.get(k);
25107
+ if (hit && hit.expiresAt - EXPIRY_MARGIN_MS > Date.now()) {
25108
+ if (logCacheHits) logAuthTransition("token.cache-hit", { credential: credentialTag(k) });
25109
+ return hit.accessToken;
25110
+ }
25111
+ let pending = inFlight.get(k);
25038
25112
  if (!pending) {
25039
25113
  pending = exchange(refreshToken, clientId, clientSecret).then((minted2) => {
25040
- cache.set(key, minted2);
25114
+ cache.set(k, minted2);
25115
+ logAuthTransition("token.minted", {
25116
+ credential: credentialTag(k),
25117
+ reason: `valid for ${Math.round((minted2.expiresAt - Date.now()) / 1e3)}s`
25118
+ });
25041
25119
  return minted2;
25042
- }).finally(() => inFlight.delete(key));
25043
- inFlight.set(key, pending);
25120
+ }).catch((err) => {
25121
+ logAuthTransition(err.grantDead ? "grant.dead" : "token.mint-failed", {
25122
+ credential: credentialTag(k),
25123
+ reason: err.message
25124
+ });
25125
+ throw err;
25126
+ }).finally(() => inFlight.delete(k));
25127
+ inFlight.set(k, pending);
25044
25128
  }
25045
25129
  const minted = await pending;
25046
25130
  return minted.accessToken;
25047
25131
  };
25132
+ const invalidate = async (rejected) => {
25133
+ const k = await key();
25134
+ const hit = cache.get(k);
25135
+ if (!hit || hit.accessToken !== rejected) {
25136
+ logAuthTransition("token.evict-noop", {
25137
+ credential: credentialTag(k),
25138
+ reason: hit ? "a concurrent caller had already replaced this credential\u2019s token" : "no token was cached for this credential"
25139
+ });
25140
+ return false;
25141
+ }
25142
+ cache.delete(k);
25143
+ logAuthTransition("token.evicted", {
25144
+ credential: credentialTag(k),
25145
+ reason: "Google rejected this access token; the next read will mint a new one"
25146
+ });
25147
+ return true;
25148
+ };
25149
+ return Object.assign(read, {
25150
+ invalidate,
25151
+ credentialId: async () => credentialTag(await key())
25152
+ });
25048
25153
  }
25154
+ var TokenExchangeError = class extends Error {
25155
+ /**
25156
+ * The REFRESH token is dead (Google's `invalid_grant`), not merely the access
25157
+ * token. Carried as a flag rather than re-read from the message, because
25158
+ * inferring the author of a failure from prose several authors can produce is
25159
+ * precisely the mistake this branch exists to undo. `instanceof` is safe: the
25160
+ * class is thrown and caught inside this one module.
25161
+ */
25162
+ grantDead;
25163
+ constructor(message, grantDead) {
25164
+ super(message);
25165
+ this.grantDead = grantDead;
25166
+ }
25167
+ };
25049
25168
  async function exchange(refreshToken, clientId, clientSecret) {
25050
25169
  let res;
25051
25170
  try {
@@ -25060,79 +25179,338 @@ async function exchange(refreshToken, clientId, clientSecret) {
25060
25179
  }).toString()
25061
25180
  });
25062
25181
  } catch (err) {
25063
- throw new Error(
25064
- `the Google token exchange could not be reached: ${err instanceof Error ? err.message : String(err)}`
25182
+ throw new TokenExchangeError(
25183
+ `the Google token exchange could not be reached: ${err instanceof Error ? err.message : String(err)}`,
25184
+ false
25065
25185
  );
25066
25186
  }
25067
25187
  const body = await res.json().catch(() => ({}));
25068
25188
  if (!res.ok) {
25069
25189
  if (body.error === "invalid_grant") {
25070
- throw new Error(
25071
- '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.'
25190
+ throw new TokenExchangeError(
25191
+ '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.',
25192
+ true
25072
25193
  );
25073
25194
  }
25074
- throw new Error(
25075
- `the access token could not be refreshed (HTTP ${res.status}${body.error ? `, ${body.error}` : ""})`
25195
+ throw new TokenExchangeError(
25196
+ `the access token could not be refreshed (HTTP ${res.status}${body.error ? `, ${body.error}` : ""})`,
25197
+ false
25076
25198
  );
25077
25199
  }
25078
25200
  if (!body.access_token) {
25079
- throw new Error("the access token could not be refreshed: Google returned no access_token");
25201
+ throw new TokenExchangeError(
25202
+ "the access token could not be refreshed: Google returned no access_token",
25203
+ false
25204
+ );
25080
25205
  }
25081
25206
  const expiresInMs = (body.expires_in ?? 3600) * 1e3;
25082
25207
  return { accessToken: body.access_token, expiresAt: Date.now() + expiresInMs };
25083
25208
  }
25084
25209
 
25210
+ // src/google-probe.ts
25211
+ var bool = (value) => typeof value === "boolean" ? value : void 0;
25212
+ var cause = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
25213
+ function readGoogleProbe(body) {
25214
+ const record2 = typeof body === "object" && body !== null ? body : {};
25215
+ const measured = bool(record2.measured);
25216
+ const reported = cause(record2.error);
25217
+ if (measured === false) {
25218
+ return {
25219
+ kind: "unmeasured",
25220
+ reason: reported ?? "the runner reported it could not measure the Google layer"
25221
+ };
25222
+ }
25223
+ if (measured === true) {
25224
+ if (bool(record2.ok) === true) return { kind: "ok" };
25225
+ return {
25226
+ kind: "unhealthy",
25227
+ reason: reported ?? "the runner reported the Google layer unhealthy with no cause"
25228
+ };
25229
+ }
25230
+ return {
25231
+ kind: "unmeasured",
25232
+ 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"
25233
+ };
25234
+ }
25235
+
25085
25236
  // src/connector-runtime.ts
25086
25237
  var DEFAULT_TIMEOUT_MS = 3e4;
25087
25238
  var DEADLINE_GRACE_MS = 5e3;
25239
+ var MIN_REPLAY_BUDGET_MS = 1e3;
25240
+ var REFUSAL_PROBE_TIMEOUT_MS = 4e3;
25241
+ var MIN_PROBE_BUDGET_MS = 1e3;
25242
+ var PROBE_INTERVAL_MS = 6e4;
25088
25243
  var RUNNER_GOG_FAILED = 422;
25089
25244
  var RUNNER_DRAINING = 503;
25245
+ var RUNNER_BAD_REQUEST = 400;
25246
+ var RUNNER_BAD_KEY = 401;
25247
+ var GogFailedError = class extends Error {
25248
+ /** gog's stderr alone, with no echoed argv mixed in. */
25249
+ stderr;
25250
+ constructor(message, stderr) {
25251
+ super(message);
25252
+ this.stderr = stderr;
25253
+ }
25254
+ };
25255
+ var GOOGLE_TOKEN_REJECTED_PATTERN = /Google API error \(401\b|invalid[ _]authentication[ _]credentials|\bACCESS_TOKEN_EXPIRED\b|\binvalid_token\b/i;
25256
+ var REFRESH_TOKEN_DEAD_PATTERN = /\binvalid_grant\b/i;
25257
+ var READ_ONLY_SUBCOMMANDS = /* @__PURE__ */ new Set([
25258
+ "cat",
25259
+ "describe",
25260
+ "get",
25261
+ "info",
25262
+ "list",
25263
+ "list-slides",
25264
+ "ls",
25265
+ "metadata",
25266
+ "read-slide",
25267
+ "search",
25268
+ "services",
25269
+ "status",
25270
+ "structure"
25271
+ ]);
25272
+ function gogTarget(args) {
25273
+ const words = args.filter((arg) => typeof arg === "string");
25274
+ let service;
25275
+ for (let i = 0; i < words.length; i += 1) {
25276
+ const word = words[i];
25277
+ if (word.startsWith("-")) {
25278
+ if (word === "--account") i += 1;
25279
+ continue;
25280
+ }
25281
+ if (service === void 0) {
25282
+ service = word;
25283
+ continue;
25284
+ }
25285
+ return { service, subcommand: word };
25286
+ }
25287
+ return { service };
25288
+ }
25289
+ async function remintAfterGoogleRejection(err, used, args, readAccessToken, deadlineAt, probeGoogle) {
25290
+ if (!(err instanceof GogFailedError)) return void 0;
25291
+ const grantDead = REFRESH_TOKEN_DEAD_PATTERN.test(err.stderr);
25292
+ if (!grantDead && !GOOGLE_TOKEN_REJECTED_PATTERN.test(err.stderr)) return void 0;
25293
+ const { service, subcommand } = gogTarget(args);
25294
+ const credential = await readAccessToken?.credentialId?.();
25295
+ const where = { credential, service };
25296
+ if (grantDead) {
25297
+ logAuthTransition("grant.dead", {
25298
+ ...where,
25299
+ reason: "gog reported invalid_grant: the stored refresh token is dead, so no token can be minted and this account must be re-authorized"
25300
+ });
25301
+ return void 0;
25302
+ }
25303
+ if (!used) {
25304
+ await probeGoogle(where);
25305
+ logAuthTransition("replay.declined", {
25306
+ ...where,
25307
+ reason: "no access token was supplied with the call, so gog acted as the backend volume\u2019s own identity"
25308
+ });
25309
+ return void 0;
25310
+ }
25311
+ if (!readAccessToken?.invalidate) {
25312
+ logAuthTransition("replay.declined", {
25313
+ ...where,
25314
+ reason: "this token source cannot mint a replacement, so a replay would resend the rejected token"
25315
+ });
25316
+ return void 0;
25317
+ }
25318
+ const evicted = await readAccessToken.invalidate(used);
25319
+ if (subcommand === void 0 || !READ_ONLY_SUBCOMMANDS.has(subcommand)) {
25320
+ logAuthTransition("replay.declined", {
25321
+ ...where,
25322
+ reason: `not replayable: '${subcommand ?? "(none)"}' is not a known read-only subcommand and a write could double-apply`
25323
+ });
25324
+ return void 0;
25325
+ }
25326
+ if (!evicted) {
25327
+ logAuthTransition("replay.declined", {
25328
+ ...where,
25329
+ reason: "the rejected token was already superseded, so the cache holds the token a replay would send"
25330
+ });
25331
+ return void 0;
25332
+ }
25333
+ const fresh = await readAccessToken();
25334
+ if (!fresh) {
25335
+ logAuthTransition("replay.declined", {
25336
+ ...where,
25337
+ reason: "the token source produced no token after eviction; replaying without one would act as the backend"
25338
+ });
25339
+ return void 0;
25340
+ }
25341
+ const budgetMs = deadlineAt - Date.now();
25342
+ if (budgetMs < MIN_REPLAY_BUDGET_MS) {
25343
+ logAuthTransition("replay.declined", {
25344
+ ...where,
25345
+ 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`
25346
+ });
25347
+ return void 0;
25348
+ }
25349
+ return { token: fresh, budgetMs, invalidate: readAccessToken.invalidate, ...where };
25350
+ }
25090
25351
  function makeFlyExecutor(endpoint, key, readAccessToken) {
25352
+ let lastProbeAt = Number.NEGATIVE_INFINITY;
25353
+ const probeGoogleAfterRefusal = async (where, deadlineAt) => {
25354
+ const record2 = { ...where, endpoint };
25355
+ const now = Date.now();
25356
+ const remainingMs = deadlineAt - now;
25357
+ if (remainingMs < MIN_PROBE_BUDGET_MS) {
25358
+ logAuthTransition("refusal.google-unmeasured", {
25359
+ ...record2,
25360
+ 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`
25361
+ });
25362
+ return;
25363
+ }
25364
+ if (now - lastProbeAt < PROBE_INTERVAL_MS) {
25365
+ logAuthTransition("refusal.google-unmeasured", {
25366
+ ...record2,
25367
+ // "attempted", not "measured". `lastProbeAt` is stamped before the
25368
+ // fetch and is deliberately NOT reset when the probe comes back with no
25369
+ // verdict (a 404 from a runner too old to have the endpoint, a timeout,
25370
+ // a dead socket) — the backend cost this throttle exists to bound was
25371
+ // paid either way, and resetting it would let a retry loop storm a
25372
+ // runner that is already unwell. So the timestamp stays and the sentence
25373
+ // has to be the true one: on this branch a log line may not assert a
25374
+ // measurement that never happened, and the previous probe may well have
25375
+ // measured nothing at all.
25376
+ 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"
25377
+ });
25378
+ return;
25379
+ }
25380
+ lastProbeAt = now;
25381
+ let event;
25382
+ let reason;
25383
+ try {
25384
+ const res = await fetch(`${endpoint}/health/google`, {
25385
+ headers: { Authorization: `Bearer ${key}` },
25386
+ // Never more than the probe's own budget, never more than the call has
25387
+ // left. `Math.min` rather than a plain constant because the second
25388
+ // bound is the caller's, and it outranks ours.
25389
+ signal: AbortSignal.timeout(Math.min(REFUSAL_PROBE_TIMEOUT_MS, remainingMs))
25390
+ });
25391
+ if (!res.ok) {
25392
+ event = "refusal.google-unmeasured";
25393
+ reason = `the runner did not answer the Google probe (HTTP ${res.status})`;
25394
+ } else {
25395
+ const verdict = readGoogleProbe(await res.json());
25396
+ if (verdict.kind === "ok") {
25397
+ event = "refusal.google-ok";
25398
+ 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";
25399
+ } else {
25400
+ event = verdict.kind === "unhealthy" ? "refusal.google-unhealthy" : "refusal.google-unmeasured";
25401
+ reason = verdict.reason;
25402
+ }
25403
+ }
25404
+ } catch (err) {
25405
+ event = "refusal.google-unmeasured";
25406
+ reason = err instanceof Error ? err.message : String(err);
25407
+ }
25408
+ logAuthTransition(event, { ...record2, reason });
25409
+ };
25091
25410
  return async (args, opts) => {
25092
25411
  const deadlineMs = (opts?.timeout ?? DEFAULT_TIMEOUT_MS) + DEADLINE_GRACE_MS;
25093
25412
  const accessToken = await readAccessToken?.();
25094
- let res;
25413
+ const deadlineAt = Date.now() + deadlineMs;
25095
25414
  try {
25096
- res = await fetch(endpoint + "/run", {
25097
- method: "POST",
25098
- headers: {
25099
- Authorization: "Bearer " + key,
25100
- "Content-Type": "application/json"
25101
- },
25102
- body: JSON.stringify(accessToken ? { args, accessToken } : { args }),
25103
- signal: AbortSignal.timeout(deadlineMs)
25104
- });
25415
+ return await attempt(endpoint, key, args, accessToken, deadlineMs);
25105
25416
  } catch (err) {
25106
- const name = err instanceof Error ? err.name : "";
25107
- if (name === "TimeoutError" || name === "AbortError") {
25108
- throw new Error(
25109
- `gog-runner did not respond within ${deadlineMs}ms (${endpoint}) \u2014 the Fly backend may be cold or wedged`
25110
- );
25417
+ const replay = await remintAfterGoogleRejection(
25418
+ err,
25419
+ accessToken,
25420
+ args,
25421
+ readAccessToken,
25422
+ deadlineAt,
25423
+ (where2) => probeGoogleAfterRefusal(where2, deadlineAt)
25424
+ );
25425
+ if (replay === void 0) throw err;
25426
+ const where = { credential: replay.credential, service: replay.service, endpoint };
25427
+ logAuthTransition("replay.attempted", {
25428
+ ...where,
25429
+ reason: "Google rejected the access token; replaying this read once with a freshly minted one"
25430
+ });
25431
+ try {
25432
+ const stdout = await attempt(endpoint, key, args, replay.token, replay.budgetMs);
25433
+ logAuthTransition("replay.succeeded", where);
25434
+ return stdout;
25435
+ } catch (replayErr) {
25436
+ logAuthTransition("replay.failed", { ...where, reason: String(replayErr) });
25437
+ if (replayErr instanceof GogFailedError && GOOGLE_TOKEN_REJECTED_PATTERN.test(replayErr.stderr)) {
25438
+ await replay.invalidate(replay.token);
25439
+ }
25440
+ throw replayErr;
25111
25441
  }
25112
- throw err;
25113
25442
  }
25114
- if (!res.ok) {
25115
- const body = await res.json().catch(() => null);
25116
- const detail = body && typeof body.error === "string" ? body.stderr && body.stderr.trim() && body.stderr.trim() !== body.error.trim() ? `${body.error}
25443
+ };
25444
+ }
25445
+ async function attempt(endpoint, key, args, accessToken, deadlineMs) {
25446
+ let res;
25447
+ try {
25448
+ res = await fetch(endpoint + "/run", {
25449
+ method: "POST",
25450
+ headers: {
25451
+ Authorization: "Bearer " + key,
25452
+ "Content-Type": "application/json"
25453
+ },
25454
+ body: JSON.stringify(accessToken ? { args, accessToken } : { args }),
25455
+ signal: AbortSignal.timeout(deadlineMs)
25456
+ });
25457
+ } catch (err) {
25458
+ const name = err instanceof Error ? err.name : "";
25459
+ if (name === "TimeoutError" || name === "AbortError") {
25460
+ throw new RunnerTransportError(
25461
+ `gog-runner did not respond within ${deadlineMs}ms (${endpoint}) \u2014 the Fly backend may be cold or wedged`,
25462
+ "transport-retryable"
25463
+ );
25464
+ }
25465
+ throw err;
25466
+ }
25467
+ if (!res.ok) {
25468
+ const body = await res.json().catch(() => null);
25469
+ const detail = body && typeof body.error === "string" ? body.stderr && body.stderr.trim() && body.stderr.trim() !== body.error.trim() ? `${body.error}
25117
25470
  ${body.stderr}` : body.error : "";
25118
- if (res.status === RUNNER_GOG_FAILED) {
25119
- throw new Error(detail || "gog failed on the runner (no detail supplied)");
25120
- }
25121
- if (res.status === RUNNER_DRAINING || body?.retryable === true) {
25122
- throw new Error(
25123
- `gog-runner is restarting; retry this call.${detail ? ` ${detail}` : ""}`
25124
- );
25125
- }
25126
- if (detail) {
25127
- throw new Error(detail);
25128
- }
25129
- throw new Error(
25130
- `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.`
25471
+ if (res.status === RUNNER_GOG_FAILED) {
25472
+ throw new GogFailedError(
25473
+ detail || "gog failed on the runner (no detail supplied)",
25474
+ typeof body?.stderr === "string" ? body.stderr : ""
25131
25475
  );
25132
25476
  }
25133
- const { stdout } = await res.json();
25134
- return stdout;
25135
- };
25477
+ if (res.status === RUNNER_BAD_KEY) {
25478
+ logAuthTransition("runner.auth-failed", {
25479
+ service: gogTarget(args).service,
25480
+ endpoint,
25481
+ 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"
25482
+ });
25483
+ throw new RunnerTransportError(
25484
+ "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.",
25485
+ "transport-auth",
25486
+ res.status
25487
+ );
25488
+ }
25489
+ if (res.status === RUNNER_BAD_REQUEST) {
25490
+ throw new RunnerTransportError(
25491
+ detail || "gog-runner rejected the request (no detail supplied)",
25492
+ "transport-request",
25493
+ res.status
25494
+ );
25495
+ }
25496
+ if (res.status === RUNNER_DRAINING || body?.retryable === true) {
25497
+ throw new RunnerTransportError(
25498
+ `gog-runner is restarting; retry this call.${detail ? ` ${detail}` : ""}`,
25499
+ "transport-retryable",
25500
+ res.status
25501
+ );
25502
+ }
25503
+ if (detail) {
25504
+ throw new Error(detail);
25505
+ }
25506
+ throw new RunnerTransportError(
25507
+ `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.`,
25508
+ "transport-retryable",
25509
+ res.status
25510
+ );
25511
+ }
25512
+ const { stdout } = await res.json();
25513
+ return stdout;
25136
25514
  }
25137
25515
 
25138
25516
  // src/remote-runner.ts
package/manifest.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "manifest_version": "0.3",
4
4
  "name": "gogcli-mcp",
5
5
  "display_name": "gogcli",
6
- "version": "2.21.0",
6
+ "version": "2.22.0",
7
7
  "description": "Google Sheets (and more) for Claude via gogcli — read, write, and manage spreadsheets",
8
8
  "author": {
9
9
  "name": "Chris Hall",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gogcli-mcp",
3
- "version": "2.21.0",
3
+ "version": "2.22.0",
4
4
  "mcpName": "io.github.chrischall/gogcli-mcp",
5
5
  "description": "MCP server wrapping gogcli for Google service access",
6
6
  "author": "Claude Code (AI) <https://www.anthropic.com/claude>",
package/server.json CHANGED
@@ -7,12 +7,12 @@
7
7
  "source": "github",
8
8
  "subfolder": "packages/gogcli-mcp"
9
9
  },
10
- "version": "2.21.0",
10
+ "version": "2.22.0",
11
11
  "packages": [
12
12
  {
13
13
  "registryType": "npm",
14
14
  "identifier": "gogcli-mcp",
15
- "version": "2.21.0",
15
+ "version": "2.22.0",
16
16
  "transport": {
17
17
  "type": "stdio"
18
18
  },