gogcli-mcp-sheets 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": "Extended Google Sheets for Claude via gogcli — auth + full Sheets support",
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 (Sheets)",
16
16
  "source": "./",
17
17
  "description": "Extended Google Sheets for Claude via gogcli — auth + full Sheets support",
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-sheets",
3
3
  "displayName": "gogcli (Sheets)",
4
- "version": "2.21.0",
4
+ "version": "2.22.0",
5
5
  "description": "Extended Google Sheets for Claude via gogcli — auth + full Sheets support",
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
 
@@ -31411,6 +31430,13 @@ var TIMESTAMP_KEYS = /* @__PURE__ */ new Set([
31411
31430
  // Calendar event start/end
31412
31431
  "internalDate",
31413
31432
  // Gmail, epoch milliseconds (authoritative)
31433
+ // gog >= 0.35.0 Gmail message AND thread listings. Already offset-bearing
31434
+ // (RFC3339 from internalDate), so it needs no offset repair — it is
31435
+ // allowlisted purely to gain a Display sibling, and to be re-rendered in
31436
+ // DISPLAY_TZ like every other instant. Separately sourced from the sibling
31437
+ // `date`, which is a naive re-format of the sender's Date header; the two may
31438
+ // legitimately disagree. See docs/timestamps.md.
31439
+ "internalDateIso",
31414
31440
  "modifiedTime",
31415
31441
  // Drive
31416
31442
  "createdTime",
@@ -31579,7 +31605,7 @@ function registerRunTool(server, options) {
31579
31605
  function errorText(err) {
31580
31606
  return err instanceof Error ? `Error: ${err.message}` : String(err);
31581
31607
  }
31582
- var DEFINITE_AUTH_PATTERN = /\b(401|unauthorized|invalid_grant)\b/i;
31608
+ var DEFINITE_AUTH_PATTERN = /\b(?:unauthorized|invalid_grant)\b|\b(?:error|status|code|http|responded|response)["']?[\s:=(,]{0,4}401\b/i;
31583
31609
  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;
31584
31610
  var AUTH_ERROR_PATTERN = new RegExp(`${DEFINITE_AUTH_PATTERN.source}|${STALE_TOKEN_PATTERN.source}`, "i");
31585
31611
  var INVALID_GRANT_PATTERN = /invalid_grant|token has been expired or revoked/i;
@@ -31589,6 +31615,14 @@ var AUTH_HINT = "\n\nAuthentication may have expired. Use gog_auth_add to re-aut
31589
31615
  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.';
31590
31616
  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).";
31591
31617
  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.";
31618
+ 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.";
31619
+ var RUNNER_TRANSPORT_HINTS = {
31620
+ "transport-auth": RUNNER_TRANSPORT_AUTH_HINT,
31621
+ // The request itself was malformed, so the runner will refuse it identically
31622
+ // every time. Nothing to advise beyond the message the runner already gave.
31623
+ "transport-request": "",
31624
+ "transport-retryable": TRANSIENT_HINT
31625
+ };
31592
31626
  function formatAccountList(raw) {
31593
31627
  try {
31594
31628
  const parsed = JSON.parse(raw);
@@ -31601,11 +31635,12 @@ function formatAccountList(raw) {
31601
31635
  }
31602
31636
  async function diagnose(err) {
31603
31637
  const errText = errorText(err);
31638
+ const transportHint = isRunnerTransportError(err) ? RUNNER_TRANSPORT_HINTS[err.kind] : void 0;
31604
31639
  const isInvalidGrant = INVALID_GRANT_PATTERN.test(errText);
31605
31640
  const isTransientError = !DEFINITE_AUTH_PATTERN.test(errText) && TRANSIENT_ERROR_PATTERN.test(errText);
31606
31641
  const isAuthError = !isTransientError && AUTH_ERROR_PATTERN.test(errText);
31607
31642
  const isGridLimitError = GRID_LIMIT_ERROR_PATTERN.test(errText);
31608
- const hint = isInvalidGrant ? INVALID_GRANT_HINT : isAuthError ? AUTH_HINT : isTransientError ? TRANSIENT_HINT : isGridLimitError ? GRID_LIMIT_HINT : "";
31643
+ const hint = transportHint ?? (isInvalidGrant ? INVALID_GRANT_HINT : isAuthError ? AUTH_HINT : isTransientError ? TRANSIENT_HINT : isGridLimitError ? GRID_LIMIT_HINT : "");
31609
31644
  try {
31610
31645
  const accounts = formatAccountList(await run(["auth", "list"]));
31611
31646
  return errorResult(`${errText}
@@ -31638,8 +31673,8 @@ function formatOneAccountHealth(a, now) {
31638
31673
  const age = ageInDays(a.created_at, now);
31639
31674
  const ageStr = age === null ? "" : ` Authorized ${age.toFixed(1)} day(s) ago.`;
31640
31675
  if (a.valid === false) {
31641
- 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";
31642
- 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).`;
31676
+ 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";
31677
+ 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).`;
31643
31678
  }
31644
31679
  if (a.valid === true) {
31645
31680
  let line = `\u2713 ${email3}: token valid.${ageStr}`;
@@ -31681,7 +31716,7 @@ function registerAuthToolsWith(server, defaultServices) {
31681
31716
  }
31682
31717
  });
31683
31718
  server.registerTool("gog_auth_status", {
31684
- description: "Show gogcli auth configuration: keyring backend, credential files, and auth setup.",
31719
+ 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.",
31685
31720
  annotations: { readOnlyHint: true },
31686
31721
  inputSchema: {}
31687
31722
  }, async () => {
@@ -31692,7 +31727,7 @@ function registerAuthToolsWith(server, defaultServices) {
31692
31727
  }
31693
31728
  });
31694
31729
  server.registerTool("gog_auth_health", {
31695
- 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.',
31730
+ 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.',
31696
31731
  annotations: { readOnlyHint: true },
31697
31732
  inputSchema: {}
31698
31733
  }, async () => {
@@ -31958,7 +31993,40 @@ function registerSheetsTools(server) {
31958
31993
  }
31959
31994
 
31960
31995
  // ../gogcli-mcp/src/server.ts
31961
- var VERSION = true ? "2.21.0" : "0.0.0";
31996
+ var VERSION = true ? "2.22.0" : "0.0.0";
31997
+
31998
+ // ../gogcli-mcp/src/auth-log.ts
31999
+ var FAILURES = /* @__PURE__ */ new Set([
32000
+ "token.mint-failed",
32001
+ "grant.dead",
32002
+ "replay.failed",
32003
+ "runner.auth-failed",
32004
+ "connect.key-rejected",
32005
+ // An enrolment that could not proceed is a failure even though nobody is at
32006
+ // fault: it is the only trace a half-enrolled connector leaves behind, and
32007
+ // the absence of exactly this record is why DEFECT 4 could not be explained.
32008
+ "connect.runner-unreachable",
32009
+ "connect.google-unhealthy",
32010
+ "refusal.google-unhealthy",
32011
+ // The loudest record on this branch, and the only one that means "we cannot
32012
+ // explain this". Google refused a real call while a live check of the same
32013
+ // credential, taken seconds later, succeeded — so neither the 7-day cliff nor
32014
+ // a revoked grant accounts for it. It is filed as a failure precisely because
32015
+ // it is the record nobody may scroll past: it is the only evidence that could
32016
+ // ever justify building something on the hosted path, and its absence over
32017
+ // time is what retires that theory for good.
32018
+ "refusal.google-ok"
32019
+ ]);
32020
+ var PREFIX = "gog-auth ";
32021
+ var TAG_CHARS = 12;
32022
+ function credentialTag(cacheKeyHash) {
32023
+ return cacheKeyHash.slice(0, TAG_CHARS);
32024
+ }
32025
+ function logAuthTransition(event, context) {
32026
+ const record2 = JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), event, ...context });
32027
+ const write = FAILURES.has(event) ? console.error : console.warn;
32028
+ write(PREFIX + redactSecrets2(record2));
32029
+ }
31962
32030
 
31963
32031
  // ../gogcli-mcp/src/google-token.ts
31964
32032
  var TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token";
@@ -31985,22 +32053,73 @@ function makeAccessTokenSource(env) {
31985
32053
  );
31986
32054
  };
31987
32055
  }
31988
- return async () => {
31989
- const key = await cacheKey(refreshToken, clientId);
31990
- const hit = cache.get(key);
31991
- if (hit && hit.expiresAt - EXPIRY_MARGIN_MS > Date.now()) return hit.accessToken;
31992
- let pending = inFlight.get(key);
32056
+ let keyPromise;
32057
+ const key = () => keyPromise ??= cacheKey(refreshToken, clientId);
32058
+ const logCacheHits = parseBoolEnv("GOG_AUTH_LOG_CACHE_HITS", { env });
32059
+ const read = async () => {
32060
+ const k = await key();
32061
+ const hit = cache.get(k);
32062
+ if (hit && hit.expiresAt - EXPIRY_MARGIN_MS > Date.now()) {
32063
+ if (logCacheHits) logAuthTransition("token.cache-hit", { credential: credentialTag(k) });
32064
+ return hit.accessToken;
32065
+ }
32066
+ let pending = inFlight.get(k);
31993
32067
  if (!pending) {
31994
32068
  pending = exchange(refreshToken, clientId, clientSecret).then((minted2) => {
31995
- cache.set(key, minted2);
32069
+ cache.set(k, minted2);
32070
+ logAuthTransition("token.minted", {
32071
+ credential: credentialTag(k),
32072
+ reason: `valid for ${Math.round((minted2.expiresAt - Date.now()) / 1e3)}s`
32073
+ });
31996
32074
  return minted2;
31997
- }).finally(() => inFlight.delete(key));
31998
- inFlight.set(key, pending);
32075
+ }).catch((err) => {
32076
+ logAuthTransition(err.grantDead ? "grant.dead" : "token.mint-failed", {
32077
+ credential: credentialTag(k),
32078
+ reason: err.message
32079
+ });
32080
+ throw err;
32081
+ }).finally(() => inFlight.delete(k));
32082
+ inFlight.set(k, pending);
31999
32083
  }
32000
32084
  const minted = await pending;
32001
32085
  return minted.accessToken;
32002
32086
  };
32087
+ const invalidate = async (rejected) => {
32088
+ const k = await key();
32089
+ const hit = cache.get(k);
32090
+ if (!hit || hit.accessToken !== rejected) {
32091
+ logAuthTransition("token.evict-noop", {
32092
+ credential: credentialTag(k),
32093
+ reason: hit ? "a concurrent caller had already replaced this credential\u2019s token" : "no token was cached for this credential"
32094
+ });
32095
+ return false;
32096
+ }
32097
+ cache.delete(k);
32098
+ logAuthTransition("token.evicted", {
32099
+ credential: credentialTag(k),
32100
+ reason: "Google rejected this access token; the next read will mint a new one"
32101
+ });
32102
+ return true;
32103
+ };
32104
+ return Object.assign(read, {
32105
+ invalidate,
32106
+ credentialId: async () => credentialTag(await key())
32107
+ });
32003
32108
  }
32109
+ var TokenExchangeError = class extends Error {
32110
+ /**
32111
+ * The REFRESH token is dead (Google's `invalid_grant`), not merely the access
32112
+ * token. Carried as a flag rather than re-read from the message, because
32113
+ * inferring the author of a failure from prose several authors can produce is
32114
+ * precisely the mistake this branch exists to undo. `instanceof` is safe: the
32115
+ * class is thrown and caught inside this one module.
32116
+ */
32117
+ grantDead;
32118
+ constructor(message, grantDead) {
32119
+ super(message);
32120
+ this.grantDead = grantDead;
32121
+ }
32122
+ };
32004
32123
  async function exchange(refreshToken, clientId, clientSecret) {
32005
32124
  let res;
32006
32125
  try {
@@ -32015,79 +32134,338 @@ async function exchange(refreshToken, clientId, clientSecret) {
32015
32134
  }).toString()
32016
32135
  });
32017
32136
  } catch (err) {
32018
- throw new Error(
32019
- `the Google token exchange could not be reached: ${err instanceof Error ? err.message : String(err)}`
32137
+ throw new TokenExchangeError(
32138
+ `the Google token exchange could not be reached: ${err instanceof Error ? err.message : String(err)}`,
32139
+ false
32020
32140
  );
32021
32141
  }
32022
32142
  const body = await res.json().catch(() => ({}));
32023
32143
  if (!res.ok) {
32024
32144
  if (body.error === "invalid_grant") {
32025
- throw new Error(
32026
- '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.'
32145
+ throw new TokenExchangeError(
32146
+ '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.',
32147
+ true
32027
32148
  );
32028
32149
  }
32029
- throw new Error(
32030
- `the access token could not be refreshed (HTTP ${res.status}${body.error ? `, ${body.error}` : ""})`
32150
+ throw new TokenExchangeError(
32151
+ `the access token could not be refreshed (HTTP ${res.status}${body.error ? `, ${body.error}` : ""})`,
32152
+ false
32031
32153
  );
32032
32154
  }
32033
32155
  if (!body.access_token) {
32034
- throw new Error("the access token could not be refreshed: Google returned no access_token");
32156
+ throw new TokenExchangeError(
32157
+ "the access token could not be refreshed: Google returned no access_token",
32158
+ false
32159
+ );
32035
32160
  }
32036
32161
  const expiresInMs = (body.expires_in ?? 3600) * 1e3;
32037
32162
  return { accessToken: body.access_token, expiresAt: Date.now() + expiresInMs };
32038
32163
  }
32039
32164
 
32165
+ // ../gogcli-mcp/src/google-probe.ts
32166
+ var bool = (value) => typeof value === "boolean" ? value : void 0;
32167
+ var cause = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
32168
+ function readGoogleProbe(body) {
32169
+ const record2 = typeof body === "object" && body !== null ? body : {};
32170
+ const measured = bool(record2.measured);
32171
+ const reported = cause(record2.error);
32172
+ if (measured === false) {
32173
+ return {
32174
+ kind: "unmeasured",
32175
+ reason: reported ?? "the runner reported it could not measure the Google layer"
32176
+ };
32177
+ }
32178
+ if (measured === true) {
32179
+ if (bool(record2.ok) === true) return { kind: "ok" };
32180
+ return {
32181
+ kind: "unhealthy",
32182
+ reason: reported ?? "the runner reported the Google layer unhealthy with no cause"
32183
+ };
32184
+ }
32185
+ return {
32186
+ kind: "unmeasured",
32187
+ 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"
32188
+ };
32189
+ }
32190
+
32040
32191
  // ../gogcli-mcp/src/connector-runtime.ts
32041
32192
  var DEFAULT_TIMEOUT_MS = 3e4;
32042
32193
  var DEADLINE_GRACE_MS = 5e3;
32194
+ var MIN_REPLAY_BUDGET_MS = 1e3;
32195
+ var REFUSAL_PROBE_TIMEOUT_MS = 4e3;
32196
+ var MIN_PROBE_BUDGET_MS = 1e3;
32197
+ var PROBE_INTERVAL_MS = 6e4;
32043
32198
  var RUNNER_GOG_FAILED = 422;
32044
32199
  var RUNNER_DRAINING = 503;
32200
+ var RUNNER_BAD_REQUEST = 400;
32201
+ var RUNNER_BAD_KEY = 401;
32202
+ var GogFailedError = class extends Error {
32203
+ /** gog's stderr alone, with no echoed argv mixed in. */
32204
+ stderr;
32205
+ constructor(message, stderr) {
32206
+ super(message);
32207
+ this.stderr = stderr;
32208
+ }
32209
+ };
32210
+ var GOOGLE_TOKEN_REJECTED_PATTERN = /Google API error \(401\b|invalid[ _]authentication[ _]credentials|\bACCESS_TOKEN_EXPIRED\b|\binvalid_token\b/i;
32211
+ var REFRESH_TOKEN_DEAD_PATTERN = /\binvalid_grant\b/i;
32212
+ var READ_ONLY_SUBCOMMANDS = /* @__PURE__ */ new Set([
32213
+ "cat",
32214
+ "describe",
32215
+ "get",
32216
+ "info",
32217
+ "list",
32218
+ "list-slides",
32219
+ "ls",
32220
+ "metadata",
32221
+ "read-slide",
32222
+ "search",
32223
+ "services",
32224
+ "status",
32225
+ "structure"
32226
+ ]);
32227
+ function gogTarget(args) {
32228
+ const words = args.filter((arg) => typeof arg === "string");
32229
+ let service;
32230
+ for (let i = 0; i < words.length; i += 1) {
32231
+ const word = words[i];
32232
+ if (word.startsWith("-")) {
32233
+ if (word === "--account") i += 1;
32234
+ continue;
32235
+ }
32236
+ if (service === void 0) {
32237
+ service = word;
32238
+ continue;
32239
+ }
32240
+ return { service, subcommand: word };
32241
+ }
32242
+ return { service };
32243
+ }
32244
+ async function remintAfterGoogleRejection(err, used, args, readAccessToken, deadlineAt, probeGoogle) {
32245
+ if (!(err instanceof GogFailedError)) return void 0;
32246
+ const grantDead = REFRESH_TOKEN_DEAD_PATTERN.test(err.stderr);
32247
+ if (!grantDead && !GOOGLE_TOKEN_REJECTED_PATTERN.test(err.stderr)) return void 0;
32248
+ const { service, subcommand } = gogTarget(args);
32249
+ const credential = await readAccessToken?.credentialId?.();
32250
+ const where = { credential, service };
32251
+ if (grantDead) {
32252
+ logAuthTransition("grant.dead", {
32253
+ ...where,
32254
+ reason: "gog reported invalid_grant: the stored refresh token is dead, so no token can be minted and this account must be re-authorized"
32255
+ });
32256
+ return void 0;
32257
+ }
32258
+ if (!used) {
32259
+ await probeGoogle(where);
32260
+ logAuthTransition("replay.declined", {
32261
+ ...where,
32262
+ reason: "no access token was supplied with the call, so gog acted as the backend volume\u2019s own identity"
32263
+ });
32264
+ return void 0;
32265
+ }
32266
+ if (!readAccessToken?.invalidate) {
32267
+ logAuthTransition("replay.declined", {
32268
+ ...where,
32269
+ reason: "this token source cannot mint a replacement, so a replay would resend the rejected token"
32270
+ });
32271
+ return void 0;
32272
+ }
32273
+ const evicted = await readAccessToken.invalidate(used);
32274
+ if (subcommand === void 0 || !READ_ONLY_SUBCOMMANDS.has(subcommand)) {
32275
+ logAuthTransition("replay.declined", {
32276
+ ...where,
32277
+ reason: `not replayable: '${subcommand ?? "(none)"}' is not a known read-only subcommand and a write could double-apply`
32278
+ });
32279
+ return void 0;
32280
+ }
32281
+ if (!evicted) {
32282
+ logAuthTransition("replay.declined", {
32283
+ ...where,
32284
+ reason: "the rejected token was already superseded, so the cache holds the token a replay would send"
32285
+ });
32286
+ return void 0;
32287
+ }
32288
+ const fresh = await readAccessToken();
32289
+ if (!fresh) {
32290
+ logAuthTransition("replay.declined", {
32291
+ ...where,
32292
+ reason: "the token source produced no token after eviction; replaying without one would act as the backend"
32293
+ });
32294
+ return void 0;
32295
+ }
32296
+ const budgetMs = deadlineAt - Date.now();
32297
+ if (budgetMs < MIN_REPLAY_BUDGET_MS) {
32298
+ logAuthTransition("replay.declined", {
32299
+ ...where,
32300
+ 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`
32301
+ });
32302
+ return void 0;
32303
+ }
32304
+ return { token: fresh, budgetMs, invalidate: readAccessToken.invalidate, ...where };
32305
+ }
32045
32306
  function makeFlyExecutor(endpoint, key, readAccessToken) {
32307
+ let lastProbeAt = Number.NEGATIVE_INFINITY;
32308
+ const probeGoogleAfterRefusal = async (where, deadlineAt) => {
32309
+ const record2 = { ...where, endpoint };
32310
+ const now = Date.now();
32311
+ const remainingMs = deadlineAt - now;
32312
+ if (remainingMs < MIN_PROBE_BUDGET_MS) {
32313
+ logAuthTransition("refusal.google-unmeasured", {
32314
+ ...record2,
32315
+ 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`
32316
+ });
32317
+ return;
32318
+ }
32319
+ if (now - lastProbeAt < PROBE_INTERVAL_MS) {
32320
+ logAuthTransition("refusal.google-unmeasured", {
32321
+ ...record2,
32322
+ // "attempted", not "measured". `lastProbeAt` is stamped before the
32323
+ // fetch and is deliberately NOT reset when the probe comes back with no
32324
+ // verdict (a 404 from a runner too old to have the endpoint, a timeout,
32325
+ // a dead socket) — the backend cost this throttle exists to bound was
32326
+ // paid either way, and resetting it would let a retry loop storm a
32327
+ // runner that is already unwell. So the timestamp stays and the sentence
32328
+ // has to be the true one: on this branch a log line may not assert a
32329
+ // measurement that never happened, and the previous probe may well have
32330
+ // measured nothing at all.
32331
+ 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"
32332
+ });
32333
+ return;
32334
+ }
32335
+ lastProbeAt = now;
32336
+ let event;
32337
+ let reason;
32338
+ try {
32339
+ const res = await fetch(`${endpoint}/health/google`, {
32340
+ headers: { Authorization: `Bearer ${key}` },
32341
+ // Never more than the probe's own budget, never more than the call has
32342
+ // left. `Math.min` rather than a plain constant because the second
32343
+ // bound is the caller's, and it outranks ours.
32344
+ signal: AbortSignal.timeout(Math.min(REFUSAL_PROBE_TIMEOUT_MS, remainingMs))
32345
+ });
32346
+ if (!res.ok) {
32347
+ event = "refusal.google-unmeasured";
32348
+ reason = `the runner did not answer the Google probe (HTTP ${res.status})`;
32349
+ } else {
32350
+ const verdict = readGoogleProbe(await res.json());
32351
+ if (verdict.kind === "ok") {
32352
+ event = "refusal.google-ok";
32353
+ 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";
32354
+ } else {
32355
+ event = verdict.kind === "unhealthy" ? "refusal.google-unhealthy" : "refusal.google-unmeasured";
32356
+ reason = verdict.reason;
32357
+ }
32358
+ }
32359
+ } catch (err) {
32360
+ event = "refusal.google-unmeasured";
32361
+ reason = err instanceof Error ? err.message : String(err);
32362
+ }
32363
+ logAuthTransition(event, { ...record2, reason });
32364
+ };
32046
32365
  return async (args, opts) => {
32047
32366
  const deadlineMs = (opts?.timeout ?? DEFAULT_TIMEOUT_MS) + DEADLINE_GRACE_MS;
32048
32367
  const accessToken = await readAccessToken?.();
32049
- let res;
32368
+ const deadlineAt = Date.now() + deadlineMs;
32050
32369
  try {
32051
- res = await fetch(endpoint + "/run", {
32052
- method: "POST",
32053
- headers: {
32054
- Authorization: "Bearer " + key,
32055
- "Content-Type": "application/json"
32056
- },
32057
- body: JSON.stringify(accessToken ? { args, accessToken } : { args }),
32058
- signal: AbortSignal.timeout(deadlineMs)
32059
- });
32370
+ return await attempt(endpoint, key, args, accessToken, deadlineMs);
32060
32371
  } catch (err) {
32061
- const name = err instanceof Error ? err.name : "";
32062
- if (name === "TimeoutError" || name === "AbortError") {
32063
- throw new Error(
32064
- `gog-runner did not respond within ${deadlineMs}ms (${endpoint}) \u2014 the Fly backend may be cold or wedged`
32065
- );
32372
+ const replay = await remintAfterGoogleRejection(
32373
+ err,
32374
+ accessToken,
32375
+ args,
32376
+ readAccessToken,
32377
+ deadlineAt,
32378
+ (where2) => probeGoogleAfterRefusal(where2, deadlineAt)
32379
+ );
32380
+ if (replay === void 0) throw err;
32381
+ const where = { credential: replay.credential, service: replay.service, endpoint };
32382
+ logAuthTransition("replay.attempted", {
32383
+ ...where,
32384
+ reason: "Google rejected the access token; replaying this read once with a freshly minted one"
32385
+ });
32386
+ try {
32387
+ const stdout = await attempt(endpoint, key, args, replay.token, replay.budgetMs);
32388
+ logAuthTransition("replay.succeeded", where);
32389
+ return stdout;
32390
+ } catch (replayErr) {
32391
+ logAuthTransition("replay.failed", { ...where, reason: String(replayErr) });
32392
+ if (replayErr instanceof GogFailedError && GOOGLE_TOKEN_REJECTED_PATTERN.test(replayErr.stderr)) {
32393
+ await replay.invalidate(replay.token);
32394
+ }
32395
+ throw replayErr;
32066
32396
  }
32067
- throw err;
32068
32397
  }
32069
- if (!res.ok) {
32070
- const body = await res.json().catch(() => null);
32071
- const detail = body && typeof body.error === "string" ? body.stderr && body.stderr.trim() && body.stderr.trim() !== body.error.trim() ? `${body.error}
32398
+ };
32399
+ }
32400
+ async function attempt(endpoint, key, args, accessToken, deadlineMs) {
32401
+ let res;
32402
+ try {
32403
+ res = await fetch(endpoint + "/run", {
32404
+ method: "POST",
32405
+ headers: {
32406
+ Authorization: "Bearer " + key,
32407
+ "Content-Type": "application/json"
32408
+ },
32409
+ body: JSON.stringify(accessToken ? { args, accessToken } : { args }),
32410
+ signal: AbortSignal.timeout(deadlineMs)
32411
+ });
32412
+ } catch (err) {
32413
+ const name = err instanceof Error ? err.name : "";
32414
+ if (name === "TimeoutError" || name === "AbortError") {
32415
+ throw new RunnerTransportError(
32416
+ `gog-runner did not respond within ${deadlineMs}ms (${endpoint}) \u2014 the Fly backend may be cold or wedged`,
32417
+ "transport-retryable"
32418
+ );
32419
+ }
32420
+ throw err;
32421
+ }
32422
+ if (!res.ok) {
32423
+ const body = await res.json().catch(() => null);
32424
+ const detail = body && typeof body.error === "string" ? body.stderr && body.stderr.trim() && body.stderr.trim() !== body.error.trim() ? `${body.error}
32072
32425
  ${body.stderr}` : body.error : "";
32073
- if (res.status === RUNNER_GOG_FAILED) {
32074
- throw new Error(detail || "gog failed on the runner (no detail supplied)");
32075
- }
32076
- if (res.status === RUNNER_DRAINING || body?.retryable === true) {
32077
- throw new Error(
32078
- `gog-runner is restarting; retry this call.${detail ? ` ${detail}` : ""}`
32079
- );
32080
- }
32081
- if (detail) {
32082
- throw new Error(detail);
32083
- }
32084
- throw new Error(
32085
- `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.`
32426
+ if (res.status === RUNNER_GOG_FAILED) {
32427
+ throw new GogFailedError(
32428
+ detail || "gog failed on the runner (no detail supplied)",
32429
+ typeof body?.stderr === "string" ? body.stderr : ""
32086
32430
  );
32087
32431
  }
32088
- const { stdout } = await res.json();
32089
- return stdout;
32090
- };
32432
+ if (res.status === RUNNER_BAD_KEY) {
32433
+ logAuthTransition("runner.auth-failed", {
32434
+ service: gogTarget(args).service,
32435
+ endpoint,
32436
+ 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"
32437
+ });
32438
+ throw new RunnerTransportError(
32439
+ "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.",
32440
+ "transport-auth",
32441
+ res.status
32442
+ );
32443
+ }
32444
+ if (res.status === RUNNER_BAD_REQUEST) {
32445
+ throw new RunnerTransportError(
32446
+ detail || "gog-runner rejected the request (no detail supplied)",
32447
+ "transport-request",
32448
+ res.status
32449
+ );
32450
+ }
32451
+ if (res.status === RUNNER_DRAINING || body?.retryable === true) {
32452
+ throw new RunnerTransportError(
32453
+ `gog-runner is restarting; retry this call.${detail ? ` ${detail}` : ""}`,
32454
+ "transport-retryable",
32455
+ res.status
32456
+ );
32457
+ }
32458
+ if (detail) {
32459
+ throw new Error(detail);
32460
+ }
32461
+ throw new RunnerTransportError(
32462
+ `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.`,
32463
+ "transport-retryable",
32464
+ res.status
32465
+ );
32466
+ }
32467
+ const { stdout } = await res.json();
32468
+ return stdout;
32091
32469
  }
32092
32470
 
32093
32471
  // ../gogcli-mcp/src/remote-runner.ts
@@ -32506,7 +32884,7 @@ ${resultText(result) ?? ""}` }] };
32506
32884
  url: external_exports.string().optional().describe("Hyperlink URL for single-link mode"),
32507
32885
  text: external_exports.string().optional().describe("Display text for single-link mode (defaults to the URL when omitted)"),
32508
32886
  runsJson: external_exports.string().optional().describe('Multi-link cell: JSON array of runs, e.g. [{"text":"Act A","uri":"https://a"},{"text":" / "},{"text":"Act B","uri":"https://b"}]. A run with an empty uri is plain text.'),
32509
- cellsJson: external_exports.string().optional().describe("Batch: JSON array of {cell,url,text} or {cell,runs:[{text,uri}]} objects, written in one request."),
32887
+ cellsJson: external_exports.string().optional().describe("Batch: JSON array of {cell,url,text} or {cell,runs:[{text,uri}]} objects, written in one request. Inline JSON or @file (a path gog reads itself \u2014 cheaper than inlining a large batch). gog also accepts @- for stdin, but this server never writes to gog's stdin, so @- would hang until the call times out."),
32510
32888
  account: accountParam
32511
32889
  }
32512
32890
  }, async ({ spreadsheetId, cell, url: url2, text, runsJson, cellsJson, account }) => {
package/manifest.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "manifest_version": "0.3",
4
4
  "name": "gogcli-mcp-sheets",
5
5
  "display_name": "gogcli (Sheets)",
6
- "version": "2.21.0",
6
+ "version": "2.22.0",
7
7
  "description": "Extended Google Sheets for Claude via gogcli — auth + full Sheets support",
8
8
  "author": {
9
9
  "name": "Chris Hall",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gogcli-mcp-sheets",
3
- "version": "2.21.0",
3
+ "version": "2.22.0",
4
4
  "mcpName": "io.github.chrischall/gogcli-mcp-sheets",
5
5
  "description": "Extended Google Sheets MCP server via gogcli — all base tools plus full Sheets support",
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-sheets"
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-sheets",
15
- "version": "2.21.0",
15
+ "version": "2.22.0",
16
16
  "transport": {
17
17
  "type": "stdio"
18
18
  },
@@ -471,7 +471,7 @@ export function registerExtraSheetsTools(server: McpServer): void {
471
471
  url: z.string().optional().describe('Hyperlink URL for single-link mode'),
472
472
  text: z.string().optional().describe('Display text for single-link mode (defaults to the URL when omitted)'),
473
473
  runsJson: z.string().optional().describe('Multi-link cell: JSON array of runs, e.g. [{"text":"Act A","uri":"https://a"},{"text":" / "},{"text":"Act B","uri":"https://b"}]. A run with an empty uri is plain text.'),
474
- cellsJson: z.string().optional().describe('Batch: JSON array of {cell,url,text} or {cell,runs:[{text,uri}]} objects, written in one request.'),
474
+ cellsJson: z.string().optional().describe('Batch: JSON array of {cell,url,text} or {cell,runs:[{text,uri}]} objects, written in one request. Inline JSON or @file (a path gog reads itself — cheaper than inlining a large batch). gog also accepts @- for stdin, but this server never writes to gog\'s stdin, so @- would hang until the call times out.'),
475
475
  account: accountParam,
476
476
  },
477
477
  }, async ({ spreadsheetId, cell, url, text, runsJson, cellsJson, account }) => {
@@ -753,6 +753,38 @@ describe('gog_sheets_links_set', () => {
753
753
  { account: undefined },
754
754
  );
755
755
  });
756
+
757
+ // gog 0.35.0 (openclaw/gogcli#941) routes --cells-json through
758
+ // resolveInlineOrFileBytes, so it now also accepts @file and @- (stdin).
759
+ // The value is already passed through verbatim, so @file needs no code
760
+ // change — only the param description, which currently tells the model it
761
+ // must inline the whole array.
762
+ it('forwards an @file --cells-json reference verbatim', async () => {
763
+ vi.mocked(lib.runOrDiagnose).mockResolvedValue(rawTextResult('{}'));
764
+ const harness = await setupHandlers();
765
+ await harness.callTool('gog_sheets_links_set', { spreadsheetId: 'sid', cellsJson: '@/tmp/cells.json' });
766
+ expect(lib.runOrDiagnose).toHaveBeenCalledWith(
767
+ ['sheets', 'links', 'set', 'sid', '--cells-json=@/tmp/cells.json'],
768
+ { account: undefined },
769
+ );
770
+ });
771
+
772
+ // runner.ts spawns gog without ever writing to or closing the child's stdin,
773
+ // so `@-` blocks until the 30 s timeout rather than reading anything. The
774
+ // description must steer callers away from it.
775
+ it('cellsJson description documents @file and rules out @- stdin', async () => {
776
+ const { McpServer } = await import('@modelcontextprotocol/sdk/server/mcp.js');
777
+ const server = new McpServer({ name: 'test', version: '0.0.0' });
778
+ const configs = new Map<string, { inputSchema?: Record<string, { description?: string }> }>();
779
+ vi.spyOn(server, 'registerTool').mockImplementation((name, config) => {
780
+ configs.set(name, config as { inputSchema?: Record<string, { description?: string }> });
781
+ return undefined as never;
782
+ });
783
+ registerExtraSheetsTools(server);
784
+ const desc = configs.get('gog_sheets_links_set')?.inputSchema?.cellsJson?.description ?? '';
785
+ expect(desc).toMatch(/@file/);
786
+ expect(desc).toMatch(/@-/);
787
+ });
756
788
  });
757
789
 
758
790
  // 18. named-ranges list