gogcli-mcp-contacts 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/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",
@@ -31572,7 +31598,7 @@ function registerRunTool(server, options) {
31572
31598
  function errorText(err) {
31573
31599
  return err instanceof Error ? `Error: ${err.message}` : String(err);
31574
31600
  }
31575
- var DEFINITE_AUTH_PATTERN = /\b(401|unauthorized|invalid_grant)\b/i;
31601
+ var DEFINITE_AUTH_PATTERN = /\b(?:unauthorized|invalid_grant)\b|\b(?:error|status|code|http|responded|response)["']?[\s:=(,]{0,4}401\b/i;
31576
31602
  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;
31577
31603
  var AUTH_ERROR_PATTERN = new RegExp(`${DEFINITE_AUTH_PATTERN.source}|${STALE_TOKEN_PATTERN.source}`, "i");
31578
31604
  var INVALID_GRANT_PATTERN = /invalid_grant|token has been expired or revoked/i;
@@ -31582,6 +31608,14 @@ var AUTH_HINT = "\n\nAuthentication may have expired. Use gog_auth_add to re-aut
31582
31608
  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.';
31583
31609
  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).";
31584
31610
  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.";
31611
+ 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.";
31612
+ var RUNNER_TRANSPORT_HINTS = {
31613
+ "transport-auth": RUNNER_TRANSPORT_AUTH_HINT,
31614
+ // The request itself was malformed, so the runner will refuse it identically
31615
+ // every time. Nothing to advise beyond the message the runner already gave.
31616
+ "transport-request": "",
31617
+ "transport-retryable": TRANSIENT_HINT
31618
+ };
31585
31619
  function formatAccountList(raw) {
31586
31620
  try {
31587
31621
  const parsed = JSON.parse(raw);
@@ -31594,11 +31628,12 @@ function formatAccountList(raw) {
31594
31628
  }
31595
31629
  async function diagnose(err) {
31596
31630
  const errText = errorText(err);
31631
+ const transportHint = isRunnerTransportError(err) ? RUNNER_TRANSPORT_HINTS[err.kind] : void 0;
31597
31632
  const isInvalidGrant = INVALID_GRANT_PATTERN.test(errText);
31598
31633
  const isTransientError = !DEFINITE_AUTH_PATTERN.test(errText) && TRANSIENT_ERROR_PATTERN.test(errText);
31599
31634
  const isAuthError = !isTransientError && AUTH_ERROR_PATTERN.test(errText);
31600
31635
  const isGridLimitError = GRID_LIMIT_ERROR_PATTERN.test(errText);
31601
- const hint = isInvalidGrant ? INVALID_GRANT_HINT : isAuthError ? AUTH_HINT : isTransientError ? TRANSIENT_HINT : isGridLimitError ? GRID_LIMIT_HINT : "";
31636
+ const hint = transportHint ?? (isInvalidGrant ? INVALID_GRANT_HINT : isAuthError ? AUTH_HINT : isTransientError ? TRANSIENT_HINT : isGridLimitError ? GRID_LIMIT_HINT : "");
31602
31637
  try {
31603
31638
  const accounts = formatAccountList(await run(["auth", "list"]));
31604
31639
  return errorResult(`${errText}
@@ -31631,8 +31666,8 @@ function formatOneAccountHealth(a, now) {
31631
31666
  const age = ageInDays(a.created_at, now);
31632
31667
  const ageStr = age === null ? "" : ` Authorized ${age.toFixed(1)} day(s) ago.`;
31633
31668
  if (a.valid === false) {
31634
- 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";
31635
- 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).`;
31669
+ 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";
31670
+ 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).`;
31636
31671
  }
31637
31672
  if (a.valid === true) {
31638
31673
  let line = `\u2713 ${email3}: token valid.${ageStr}`;
@@ -31674,7 +31709,7 @@ function registerAuthToolsWith(server, defaultServices) {
31674
31709
  }
31675
31710
  });
31676
31711
  server.registerTool("gog_auth_status", {
31677
- description: "Show gogcli auth configuration: keyring backend, credential files, and auth setup.",
31712
+ 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.",
31678
31713
  annotations: { readOnlyHint: true },
31679
31714
  inputSchema: {}
31680
31715
  }, async () => {
@@ -31685,7 +31720,7 @@ function registerAuthToolsWith(server, defaultServices) {
31685
31720
  }
31686
31721
  });
31687
31722
  server.registerTool("gog_auth_health", {
31688
- 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.',
31723
+ 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.',
31689
31724
  annotations: { readOnlyHint: true },
31690
31725
  inputSchema: {}
31691
31726
  }, async () => {
@@ -31848,7 +31883,40 @@ var failIfNotEmptyParam = external_exports.boolean().optional().describe(
31848
31883
  );
31849
31884
 
31850
31885
  // ../gogcli-mcp/src/server.ts
31851
- var VERSION = true ? "2.21.0" : "0.0.0";
31886
+ var VERSION = true ? "2.22.0" : "0.0.0";
31887
+
31888
+ // ../gogcli-mcp/src/auth-log.ts
31889
+ var FAILURES = /* @__PURE__ */ new Set([
31890
+ "token.mint-failed",
31891
+ "grant.dead",
31892
+ "replay.failed",
31893
+ "runner.auth-failed",
31894
+ "connect.key-rejected",
31895
+ // An enrolment that could not proceed is a failure even though nobody is at
31896
+ // fault: it is the only trace a half-enrolled connector leaves behind, and
31897
+ // the absence of exactly this record is why DEFECT 4 could not be explained.
31898
+ "connect.runner-unreachable",
31899
+ "connect.google-unhealthy",
31900
+ "refusal.google-unhealthy",
31901
+ // The loudest record on this branch, and the only one that means "we cannot
31902
+ // explain this". Google refused a real call while a live check of the same
31903
+ // credential, taken seconds later, succeeded — so neither the 7-day cliff nor
31904
+ // a revoked grant accounts for it. It is filed as a failure precisely because
31905
+ // it is the record nobody may scroll past: it is the only evidence that could
31906
+ // ever justify building something on the hosted path, and its absence over
31907
+ // time is what retires that theory for good.
31908
+ "refusal.google-ok"
31909
+ ]);
31910
+ var PREFIX = "gog-auth ";
31911
+ var TAG_CHARS = 12;
31912
+ function credentialTag(cacheKeyHash) {
31913
+ return cacheKeyHash.slice(0, TAG_CHARS);
31914
+ }
31915
+ function logAuthTransition(event, context) {
31916
+ const record2 = JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), event, ...context });
31917
+ const write = FAILURES.has(event) ? console.error : console.warn;
31918
+ write(PREFIX + redactSecrets2(record2));
31919
+ }
31852
31920
 
31853
31921
  // ../gogcli-mcp/src/google-token.ts
31854
31922
  var TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token";
@@ -31875,22 +31943,73 @@ function makeAccessTokenSource(env) {
31875
31943
  );
31876
31944
  };
31877
31945
  }
31878
- return async () => {
31879
- const key = await cacheKey(refreshToken, clientId);
31880
- const hit = cache.get(key);
31881
- if (hit && hit.expiresAt - EXPIRY_MARGIN_MS > Date.now()) return hit.accessToken;
31882
- let pending = inFlight.get(key);
31946
+ let keyPromise;
31947
+ const key = () => keyPromise ??= cacheKey(refreshToken, clientId);
31948
+ const logCacheHits = parseBoolEnv("GOG_AUTH_LOG_CACHE_HITS", { env });
31949
+ const read = async () => {
31950
+ const k = await key();
31951
+ const hit = cache.get(k);
31952
+ if (hit && hit.expiresAt - EXPIRY_MARGIN_MS > Date.now()) {
31953
+ if (logCacheHits) logAuthTransition("token.cache-hit", { credential: credentialTag(k) });
31954
+ return hit.accessToken;
31955
+ }
31956
+ let pending = inFlight.get(k);
31883
31957
  if (!pending) {
31884
31958
  pending = exchange(refreshToken, clientId, clientSecret).then((minted2) => {
31885
- cache.set(key, minted2);
31959
+ cache.set(k, minted2);
31960
+ logAuthTransition("token.minted", {
31961
+ credential: credentialTag(k),
31962
+ reason: `valid for ${Math.round((minted2.expiresAt - Date.now()) / 1e3)}s`
31963
+ });
31886
31964
  return minted2;
31887
- }).finally(() => inFlight.delete(key));
31888
- inFlight.set(key, pending);
31965
+ }).catch((err) => {
31966
+ logAuthTransition(err.grantDead ? "grant.dead" : "token.mint-failed", {
31967
+ credential: credentialTag(k),
31968
+ reason: err.message
31969
+ });
31970
+ throw err;
31971
+ }).finally(() => inFlight.delete(k));
31972
+ inFlight.set(k, pending);
31889
31973
  }
31890
31974
  const minted = await pending;
31891
31975
  return minted.accessToken;
31892
31976
  };
31977
+ const invalidate = async (rejected) => {
31978
+ const k = await key();
31979
+ const hit = cache.get(k);
31980
+ if (!hit || hit.accessToken !== rejected) {
31981
+ logAuthTransition("token.evict-noop", {
31982
+ credential: credentialTag(k),
31983
+ reason: hit ? "a concurrent caller had already replaced this credential\u2019s token" : "no token was cached for this credential"
31984
+ });
31985
+ return false;
31986
+ }
31987
+ cache.delete(k);
31988
+ logAuthTransition("token.evicted", {
31989
+ credential: credentialTag(k),
31990
+ reason: "Google rejected this access token; the next read will mint a new one"
31991
+ });
31992
+ return true;
31993
+ };
31994
+ return Object.assign(read, {
31995
+ invalidate,
31996
+ credentialId: async () => credentialTag(await key())
31997
+ });
31893
31998
  }
31999
+ var TokenExchangeError = class extends Error {
32000
+ /**
32001
+ * The REFRESH token is dead (Google's `invalid_grant`), not merely the access
32002
+ * token. Carried as a flag rather than re-read from the message, because
32003
+ * inferring the author of a failure from prose several authors can produce is
32004
+ * precisely the mistake this branch exists to undo. `instanceof` is safe: the
32005
+ * class is thrown and caught inside this one module.
32006
+ */
32007
+ grantDead;
32008
+ constructor(message, grantDead) {
32009
+ super(message);
32010
+ this.grantDead = grantDead;
32011
+ }
32012
+ };
31894
32013
  async function exchange(refreshToken, clientId, clientSecret) {
31895
32014
  let res;
31896
32015
  try {
@@ -31905,79 +32024,338 @@ async function exchange(refreshToken, clientId, clientSecret) {
31905
32024
  }).toString()
31906
32025
  });
31907
32026
  } catch (err) {
31908
- throw new Error(
31909
- `the Google token exchange could not be reached: ${err instanceof Error ? err.message : String(err)}`
32027
+ throw new TokenExchangeError(
32028
+ `the Google token exchange could not be reached: ${err instanceof Error ? err.message : String(err)}`,
32029
+ false
31910
32030
  );
31911
32031
  }
31912
32032
  const body = await res.json().catch(() => ({}));
31913
32033
  if (!res.ok) {
31914
32034
  if (body.error === "invalid_grant") {
31915
- throw new Error(
31916
- '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.'
32035
+ throw new TokenExchangeError(
32036
+ '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.',
32037
+ true
31917
32038
  );
31918
32039
  }
31919
- throw new Error(
31920
- `the access token could not be refreshed (HTTP ${res.status}${body.error ? `, ${body.error}` : ""})`
32040
+ throw new TokenExchangeError(
32041
+ `the access token could not be refreshed (HTTP ${res.status}${body.error ? `, ${body.error}` : ""})`,
32042
+ false
31921
32043
  );
31922
32044
  }
31923
32045
  if (!body.access_token) {
31924
- throw new Error("the access token could not be refreshed: Google returned no access_token");
32046
+ throw new TokenExchangeError(
32047
+ "the access token could not be refreshed: Google returned no access_token",
32048
+ false
32049
+ );
31925
32050
  }
31926
32051
  const expiresInMs = (body.expires_in ?? 3600) * 1e3;
31927
32052
  return { accessToken: body.access_token, expiresAt: Date.now() + expiresInMs };
31928
32053
  }
31929
32054
 
32055
+ // ../gogcli-mcp/src/google-probe.ts
32056
+ var bool = (value) => typeof value === "boolean" ? value : void 0;
32057
+ var cause = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
32058
+ function readGoogleProbe(body) {
32059
+ const record2 = typeof body === "object" && body !== null ? body : {};
32060
+ const measured = bool(record2.measured);
32061
+ const reported = cause(record2.error);
32062
+ if (measured === false) {
32063
+ return {
32064
+ kind: "unmeasured",
32065
+ reason: reported ?? "the runner reported it could not measure the Google layer"
32066
+ };
32067
+ }
32068
+ if (measured === true) {
32069
+ if (bool(record2.ok) === true) return { kind: "ok" };
32070
+ return {
32071
+ kind: "unhealthy",
32072
+ reason: reported ?? "the runner reported the Google layer unhealthy with no cause"
32073
+ };
32074
+ }
32075
+ return {
32076
+ kind: "unmeasured",
32077
+ 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"
32078
+ };
32079
+ }
32080
+
31930
32081
  // ../gogcli-mcp/src/connector-runtime.ts
31931
32082
  var DEFAULT_TIMEOUT_MS = 3e4;
31932
32083
  var DEADLINE_GRACE_MS = 5e3;
32084
+ var MIN_REPLAY_BUDGET_MS = 1e3;
32085
+ var REFUSAL_PROBE_TIMEOUT_MS = 4e3;
32086
+ var MIN_PROBE_BUDGET_MS = 1e3;
32087
+ var PROBE_INTERVAL_MS = 6e4;
31933
32088
  var RUNNER_GOG_FAILED = 422;
31934
32089
  var RUNNER_DRAINING = 503;
32090
+ var RUNNER_BAD_REQUEST = 400;
32091
+ var RUNNER_BAD_KEY = 401;
32092
+ var GogFailedError = class extends Error {
32093
+ /** gog's stderr alone, with no echoed argv mixed in. */
32094
+ stderr;
32095
+ constructor(message, stderr) {
32096
+ super(message);
32097
+ this.stderr = stderr;
32098
+ }
32099
+ };
32100
+ var GOOGLE_TOKEN_REJECTED_PATTERN = /Google API error \(401\b|invalid[ _]authentication[ _]credentials|\bACCESS_TOKEN_EXPIRED\b|\binvalid_token\b/i;
32101
+ var REFRESH_TOKEN_DEAD_PATTERN = /\binvalid_grant\b/i;
32102
+ var READ_ONLY_SUBCOMMANDS = /* @__PURE__ */ new Set([
32103
+ "cat",
32104
+ "describe",
32105
+ "get",
32106
+ "info",
32107
+ "list",
32108
+ "list-slides",
32109
+ "ls",
32110
+ "metadata",
32111
+ "read-slide",
32112
+ "search",
32113
+ "services",
32114
+ "status",
32115
+ "structure"
32116
+ ]);
32117
+ function gogTarget(args) {
32118
+ const words = args.filter((arg) => typeof arg === "string");
32119
+ let service;
32120
+ for (let i = 0; i < words.length; i += 1) {
32121
+ const word = words[i];
32122
+ if (word.startsWith("-")) {
32123
+ if (word === "--account") i += 1;
32124
+ continue;
32125
+ }
32126
+ if (service === void 0) {
32127
+ service = word;
32128
+ continue;
32129
+ }
32130
+ return { service, subcommand: word };
32131
+ }
32132
+ return { service };
32133
+ }
32134
+ async function remintAfterGoogleRejection(err, used, args, readAccessToken, deadlineAt, probeGoogle) {
32135
+ if (!(err instanceof GogFailedError)) return void 0;
32136
+ const grantDead = REFRESH_TOKEN_DEAD_PATTERN.test(err.stderr);
32137
+ if (!grantDead && !GOOGLE_TOKEN_REJECTED_PATTERN.test(err.stderr)) return void 0;
32138
+ const { service, subcommand } = gogTarget(args);
32139
+ const credential = await readAccessToken?.credentialId?.();
32140
+ const where = { credential, service };
32141
+ if (grantDead) {
32142
+ logAuthTransition("grant.dead", {
32143
+ ...where,
32144
+ reason: "gog reported invalid_grant: the stored refresh token is dead, so no token can be minted and this account must be re-authorized"
32145
+ });
32146
+ return void 0;
32147
+ }
32148
+ if (!used) {
32149
+ await probeGoogle(where);
32150
+ logAuthTransition("replay.declined", {
32151
+ ...where,
32152
+ reason: "no access token was supplied with the call, so gog acted as the backend volume\u2019s own identity"
32153
+ });
32154
+ return void 0;
32155
+ }
32156
+ if (!readAccessToken?.invalidate) {
32157
+ logAuthTransition("replay.declined", {
32158
+ ...where,
32159
+ reason: "this token source cannot mint a replacement, so a replay would resend the rejected token"
32160
+ });
32161
+ return void 0;
32162
+ }
32163
+ const evicted = await readAccessToken.invalidate(used);
32164
+ if (subcommand === void 0 || !READ_ONLY_SUBCOMMANDS.has(subcommand)) {
32165
+ logAuthTransition("replay.declined", {
32166
+ ...where,
32167
+ reason: `not replayable: '${subcommand ?? "(none)"}' is not a known read-only subcommand and a write could double-apply`
32168
+ });
32169
+ return void 0;
32170
+ }
32171
+ if (!evicted) {
32172
+ logAuthTransition("replay.declined", {
32173
+ ...where,
32174
+ reason: "the rejected token was already superseded, so the cache holds the token a replay would send"
32175
+ });
32176
+ return void 0;
32177
+ }
32178
+ const fresh = await readAccessToken();
32179
+ if (!fresh) {
32180
+ logAuthTransition("replay.declined", {
32181
+ ...where,
32182
+ reason: "the token source produced no token after eviction; replaying without one would act as the backend"
32183
+ });
32184
+ return void 0;
32185
+ }
32186
+ const budgetMs = deadlineAt - Date.now();
32187
+ if (budgetMs < MIN_REPLAY_BUDGET_MS) {
32188
+ logAuthTransition("replay.declined", {
32189
+ ...where,
32190
+ 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`
32191
+ });
32192
+ return void 0;
32193
+ }
32194
+ return { token: fresh, budgetMs, invalidate: readAccessToken.invalidate, ...where };
32195
+ }
31935
32196
  function makeFlyExecutor(endpoint, key, readAccessToken) {
32197
+ let lastProbeAt = Number.NEGATIVE_INFINITY;
32198
+ const probeGoogleAfterRefusal = async (where, deadlineAt) => {
32199
+ const record2 = { ...where, endpoint };
32200
+ const now = Date.now();
32201
+ const remainingMs = deadlineAt - now;
32202
+ if (remainingMs < MIN_PROBE_BUDGET_MS) {
32203
+ logAuthTransition("refusal.google-unmeasured", {
32204
+ ...record2,
32205
+ 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`
32206
+ });
32207
+ return;
32208
+ }
32209
+ if (now - lastProbeAt < PROBE_INTERVAL_MS) {
32210
+ logAuthTransition("refusal.google-unmeasured", {
32211
+ ...record2,
32212
+ // "attempted", not "measured". `lastProbeAt` is stamped before the
32213
+ // fetch and is deliberately NOT reset when the probe comes back with no
32214
+ // verdict (a 404 from a runner too old to have the endpoint, a timeout,
32215
+ // a dead socket) — the backend cost this throttle exists to bound was
32216
+ // paid either way, and resetting it would let a retry loop storm a
32217
+ // runner that is already unwell. So the timestamp stays and the sentence
32218
+ // has to be the true one: on this branch a log line may not assert a
32219
+ // measurement that never happened, and the previous probe may well have
32220
+ // measured nothing at all.
32221
+ 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"
32222
+ });
32223
+ return;
32224
+ }
32225
+ lastProbeAt = now;
32226
+ let event;
32227
+ let reason;
32228
+ try {
32229
+ const res = await fetch(`${endpoint}/health/google`, {
32230
+ headers: { Authorization: `Bearer ${key}` },
32231
+ // Never more than the probe's own budget, never more than the call has
32232
+ // left. `Math.min` rather than a plain constant because the second
32233
+ // bound is the caller's, and it outranks ours.
32234
+ signal: AbortSignal.timeout(Math.min(REFUSAL_PROBE_TIMEOUT_MS, remainingMs))
32235
+ });
32236
+ if (!res.ok) {
32237
+ event = "refusal.google-unmeasured";
32238
+ reason = `the runner did not answer the Google probe (HTTP ${res.status})`;
32239
+ } else {
32240
+ const verdict = readGoogleProbe(await res.json());
32241
+ if (verdict.kind === "ok") {
32242
+ event = "refusal.google-ok";
32243
+ 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";
32244
+ } else {
32245
+ event = verdict.kind === "unhealthy" ? "refusal.google-unhealthy" : "refusal.google-unmeasured";
32246
+ reason = verdict.reason;
32247
+ }
32248
+ }
32249
+ } catch (err) {
32250
+ event = "refusal.google-unmeasured";
32251
+ reason = err instanceof Error ? err.message : String(err);
32252
+ }
32253
+ logAuthTransition(event, { ...record2, reason });
32254
+ };
31936
32255
  return async (args, opts) => {
31937
32256
  const deadlineMs = (opts?.timeout ?? DEFAULT_TIMEOUT_MS) + DEADLINE_GRACE_MS;
31938
32257
  const accessToken = await readAccessToken?.();
31939
- let res;
32258
+ const deadlineAt = Date.now() + deadlineMs;
31940
32259
  try {
31941
- res = await fetch(endpoint + "/run", {
31942
- method: "POST",
31943
- headers: {
31944
- Authorization: "Bearer " + key,
31945
- "Content-Type": "application/json"
31946
- },
31947
- body: JSON.stringify(accessToken ? { args, accessToken } : { args }),
31948
- signal: AbortSignal.timeout(deadlineMs)
31949
- });
32260
+ return await attempt(endpoint, key, args, accessToken, deadlineMs);
31950
32261
  } catch (err) {
31951
- const name = err instanceof Error ? err.name : "";
31952
- if (name === "TimeoutError" || name === "AbortError") {
31953
- throw new Error(
31954
- `gog-runner did not respond within ${deadlineMs}ms (${endpoint}) \u2014 the Fly backend may be cold or wedged`
31955
- );
32262
+ const replay = await remintAfterGoogleRejection(
32263
+ err,
32264
+ accessToken,
32265
+ args,
32266
+ readAccessToken,
32267
+ deadlineAt,
32268
+ (where2) => probeGoogleAfterRefusal(where2, deadlineAt)
32269
+ );
32270
+ if (replay === void 0) throw err;
32271
+ const where = { credential: replay.credential, service: replay.service, endpoint };
32272
+ logAuthTransition("replay.attempted", {
32273
+ ...where,
32274
+ reason: "Google rejected the access token; replaying this read once with a freshly minted one"
32275
+ });
32276
+ try {
32277
+ const stdout = await attempt(endpoint, key, args, replay.token, replay.budgetMs);
32278
+ logAuthTransition("replay.succeeded", where);
32279
+ return stdout;
32280
+ } catch (replayErr) {
32281
+ logAuthTransition("replay.failed", { ...where, reason: String(replayErr) });
32282
+ if (replayErr instanceof GogFailedError && GOOGLE_TOKEN_REJECTED_PATTERN.test(replayErr.stderr)) {
32283
+ await replay.invalidate(replay.token);
32284
+ }
32285
+ throw replayErr;
31956
32286
  }
31957
- throw err;
31958
32287
  }
31959
- if (!res.ok) {
31960
- const body = await res.json().catch(() => null);
31961
- const detail = body && typeof body.error === "string" ? body.stderr && body.stderr.trim() && body.stderr.trim() !== body.error.trim() ? `${body.error}
32288
+ };
32289
+ }
32290
+ async function attempt(endpoint, key, args, accessToken, deadlineMs) {
32291
+ let res;
32292
+ try {
32293
+ res = await fetch(endpoint + "/run", {
32294
+ method: "POST",
32295
+ headers: {
32296
+ Authorization: "Bearer " + key,
32297
+ "Content-Type": "application/json"
32298
+ },
32299
+ body: JSON.stringify(accessToken ? { args, accessToken } : { args }),
32300
+ signal: AbortSignal.timeout(deadlineMs)
32301
+ });
32302
+ } catch (err) {
32303
+ const name = err instanceof Error ? err.name : "";
32304
+ if (name === "TimeoutError" || name === "AbortError") {
32305
+ throw new RunnerTransportError(
32306
+ `gog-runner did not respond within ${deadlineMs}ms (${endpoint}) \u2014 the Fly backend may be cold or wedged`,
32307
+ "transport-retryable"
32308
+ );
32309
+ }
32310
+ throw err;
32311
+ }
32312
+ if (!res.ok) {
32313
+ const body = await res.json().catch(() => null);
32314
+ const detail = body && typeof body.error === "string" ? body.stderr && body.stderr.trim() && body.stderr.trim() !== body.error.trim() ? `${body.error}
31962
32315
  ${body.stderr}` : body.error : "";
31963
- if (res.status === RUNNER_GOG_FAILED) {
31964
- throw new Error(detail || "gog failed on the runner (no detail supplied)");
31965
- }
31966
- if (res.status === RUNNER_DRAINING || body?.retryable === true) {
31967
- throw new Error(
31968
- `gog-runner is restarting; retry this call.${detail ? ` ${detail}` : ""}`
31969
- );
31970
- }
31971
- if (detail) {
31972
- throw new Error(detail);
31973
- }
31974
- throw new Error(
31975
- `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.`
32316
+ if (res.status === RUNNER_GOG_FAILED) {
32317
+ throw new GogFailedError(
32318
+ detail || "gog failed on the runner (no detail supplied)",
32319
+ typeof body?.stderr === "string" ? body.stderr : ""
31976
32320
  );
31977
32321
  }
31978
- const { stdout } = await res.json();
31979
- return stdout;
31980
- };
32322
+ if (res.status === RUNNER_BAD_KEY) {
32323
+ logAuthTransition("runner.auth-failed", {
32324
+ service: gogTarget(args).service,
32325
+ endpoint,
32326
+ 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"
32327
+ });
32328
+ throw new RunnerTransportError(
32329
+ "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.",
32330
+ "transport-auth",
32331
+ res.status
32332
+ );
32333
+ }
32334
+ if (res.status === RUNNER_BAD_REQUEST) {
32335
+ throw new RunnerTransportError(
32336
+ detail || "gog-runner rejected the request (no detail supplied)",
32337
+ "transport-request",
32338
+ res.status
32339
+ );
32340
+ }
32341
+ if (res.status === RUNNER_DRAINING || body?.retryable === true) {
32342
+ throw new RunnerTransportError(
32343
+ `gog-runner is restarting; retry this call.${detail ? ` ${detail}` : ""}`,
32344
+ "transport-retryable",
32345
+ res.status
32346
+ );
32347
+ }
32348
+ if (detail) {
32349
+ throw new Error(detail);
32350
+ }
32351
+ throw new RunnerTransportError(
32352
+ `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.`,
32353
+ "transport-retryable",
32354
+ res.status
32355
+ );
32356
+ }
32357
+ const { stdout } = await res.json();
32358
+ return stdout;
31981
32359
  }
31982
32360
 
31983
32361
  // ../gogcli-mcp/src/remote-runner.ts
package/manifest.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "manifest_version": "0.3",
4
4
  "name": "gogcli-mcp-contacts",
5
5
  "display_name": "gogcli (Contacts)",
6
- "version": "2.21.0",
6
+ "version": "2.22.0",
7
7
  "description": "Extended Google Contacts for Claude via gogcli — auth + Contacts + Workspace directory (People API)",
8
8
  "author": {
9
9
  "name": "Chris Hall",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gogcli-mcp-contacts",
3
- "version": "2.21.0",
3
+ "version": "2.22.0",
4
4
  "mcpName": "io.github.chrischall/gogcli-mcp-contacts",
5
5
  "description": "Extended Google Contacts + People MCP server via gogcli — auth + Contacts + Workspace directory (People API)",
6
6
  "author": "Claude Code (AI) <https://www.anthropic.com/claude>",