gogcli-mcp-gmail 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
@@ -31145,6 +31145,21 @@ import { delimiter, join } from "node:path";
31145
31145
  function isGogFileArg(arg) {
31146
31146
  return typeof arg !== "string";
31147
31147
  }
31148
+ var RUNNER_TRANSPORT_BRAND = /* @__PURE__ */ Symbol.for("gogcli.RunnerTransportError");
31149
+ var RunnerTransportError = class extends Error {
31150
+ kind;
31151
+ status;
31152
+ constructor(message, kind, status) {
31153
+ super(message);
31154
+ this.name = "RunnerTransportError";
31155
+ this.kind = kind;
31156
+ this.status = status;
31157
+ Object.defineProperty(this, RUNNER_TRANSPORT_BRAND, { value: true });
31158
+ }
31159
+ };
31160
+ function isRunnerTransportError(err) {
31161
+ return err instanceof Error && err[RUNNER_TRANSPORT_BRAND] === true;
31162
+ }
31148
31163
  var runExecutor = new AsyncLocalStorage();
31149
31164
  var defaultExecutor;
31150
31165
  function setDefaultGogExecutor(executor) {
@@ -31325,7 +31340,11 @@ async function run(args, options = {}) {
31325
31340
  }
31326
31341
  return redact(output);
31327
31342
  } catch (err) {
31328
- throw new Error(redact(err instanceof Error ? err.message : String(err)));
31343
+ const message = redact(err instanceof Error ? err.message : String(err));
31344
+ if (isRunnerTransportError(err)) {
31345
+ throw new RunnerTransportError(message, err.kind, err.status);
31346
+ }
31347
+ throw new Error(message);
31329
31348
  }
31330
31349
  }
31331
31350
 
@@ -31416,6 +31435,13 @@ var TIMESTAMP_KEYS = /* @__PURE__ */ new Set([
31416
31435
  // Calendar event start/end
31417
31436
  "internalDate",
31418
31437
  // Gmail, epoch milliseconds (authoritative)
31438
+ // gog >= 0.35.0 Gmail message AND thread listings. Already offset-bearing
31439
+ // (RFC3339 from internalDate), so it needs no offset repair — it is
31440
+ // allowlisted purely to gain a Display sibling, and to be re-rendered in
31441
+ // DISPLAY_TZ like every other instant. Separately sourced from the sibling
31442
+ // `date`, which is a naive re-format of the sender's Date header; the two may
31443
+ // legitimately disagree. See docs/timestamps.md.
31444
+ "internalDateIso",
31419
31445
  "modifiedTime",
31420
31446
  // Drive
31421
31447
  "createdTime",
@@ -31584,7 +31610,7 @@ function registerRunTool(server, options) {
31584
31610
  function errorText(err) {
31585
31611
  return err instanceof Error ? `Error: ${err.message}` : String(err);
31586
31612
  }
31587
- var DEFINITE_AUTH_PATTERN = /\b(401|unauthorized|invalid_grant)\b/i;
31613
+ var DEFINITE_AUTH_PATTERN = /\b(?:unauthorized|invalid_grant)\b|\b(?:error|status|code|http|responded|response)["']?[\s:=(,]{0,4}401\b/i;
31588
31614
  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;
31589
31615
  var AUTH_ERROR_PATTERN = new RegExp(`${DEFINITE_AUTH_PATTERN.source}|${STALE_TOKEN_PATTERN.source}`, "i");
31590
31616
  var INVALID_GRANT_PATTERN = /invalid_grant|token has been expired or revoked/i;
@@ -31594,6 +31620,14 @@ var AUTH_HINT = "\n\nAuthentication may have expired. Use gog_auth_add to re-aut
31594
31620
  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.';
31595
31621
  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).";
31596
31622
  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.";
31623
+ 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.";
31624
+ var RUNNER_TRANSPORT_HINTS = {
31625
+ "transport-auth": RUNNER_TRANSPORT_AUTH_HINT,
31626
+ // The request itself was malformed, so the runner will refuse it identically
31627
+ // every time. Nothing to advise beyond the message the runner already gave.
31628
+ "transport-request": "",
31629
+ "transport-retryable": TRANSIENT_HINT
31630
+ };
31597
31631
  function formatAccountList(raw) {
31598
31632
  try {
31599
31633
  const parsed = JSON.parse(raw);
@@ -31606,11 +31640,12 @@ function formatAccountList(raw) {
31606
31640
  }
31607
31641
  async function diagnose(err) {
31608
31642
  const errText = errorText(err);
31643
+ const transportHint = isRunnerTransportError(err) ? RUNNER_TRANSPORT_HINTS[err.kind] : void 0;
31609
31644
  const isInvalidGrant = INVALID_GRANT_PATTERN.test(errText);
31610
31645
  const isTransientError = !DEFINITE_AUTH_PATTERN.test(errText) && TRANSIENT_ERROR_PATTERN.test(errText);
31611
31646
  const isAuthError = !isTransientError && AUTH_ERROR_PATTERN.test(errText);
31612
31647
  const isGridLimitError = GRID_LIMIT_ERROR_PATTERN.test(errText);
31613
- const hint = isInvalidGrant ? INVALID_GRANT_HINT : isAuthError ? AUTH_HINT : isTransientError ? TRANSIENT_HINT : isGridLimitError ? GRID_LIMIT_HINT : "";
31648
+ const hint = transportHint ?? (isInvalidGrant ? INVALID_GRANT_HINT : isAuthError ? AUTH_HINT : isTransientError ? TRANSIENT_HINT : isGridLimitError ? GRID_LIMIT_HINT : "");
31614
31649
  try {
31615
31650
  const accounts = formatAccountList(await run(["auth", "list"]));
31616
31651
  return errorResult(`${errText}
@@ -31643,8 +31678,8 @@ function formatOneAccountHealth(a, now) {
31643
31678
  const age = ageInDays(a.created_at, now);
31644
31679
  const ageStr = age === null ? "" : ` Authorized ${age.toFixed(1)} day(s) ago.`;
31645
31680
  if (a.valid === false) {
31646
- 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";
31647
- 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).`;
31681
+ 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";
31682
+ 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).`;
31648
31683
  }
31649
31684
  if (a.valid === true) {
31650
31685
  let line = `\u2713 ${email3}: token valid.${ageStr}`;
@@ -31686,7 +31721,7 @@ function registerAuthToolsWith(server, defaultServices) {
31686
31721
  }
31687
31722
  });
31688
31723
  server.registerTool("gog_auth_status", {
31689
- description: "Show gogcli auth configuration: keyring backend, credential files, and auth setup.",
31724
+ 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.",
31690
31725
  annotations: { readOnlyHint: true },
31691
31726
  inputSchema: {}
31692
31727
  }, async () => {
@@ -31697,7 +31732,7 @@ function registerAuthToolsWith(server, defaultServices) {
31697
31732
  }
31698
31733
  });
31699
31734
  server.registerTool("gog_auth_health", {
31700
- 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.',
31735
+ 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.',
31701
31736
  annotations: { readOnlyHint: true },
31702
31737
  inputSchema: {}
31703
31738
  }, async () => {
@@ -31861,7 +31896,40 @@ var failIfNotEmptyParam = external_exports.boolean().optional().describe(
31861
31896
  );
31862
31897
 
31863
31898
  // ../gogcli-mcp/src/server.ts
31864
- var VERSION = true ? "2.21.0" : "0.0.0";
31899
+ var VERSION = true ? "2.22.0" : "0.0.0";
31900
+
31901
+ // ../gogcli-mcp/src/auth-log.ts
31902
+ var FAILURES = /* @__PURE__ */ new Set([
31903
+ "token.mint-failed",
31904
+ "grant.dead",
31905
+ "replay.failed",
31906
+ "runner.auth-failed",
31907
+ "connect.key-rejected",
31908
+ // An enrolment that could not proceed is a failure even though nobody is at
31909
+ // fault: it is the only trace a half-enrolled connector leaves behind, and
31910
+ // the absence of exactly this record is why DEFECT 4 could not be explained.
31911
+ "connect.runner-unreachable",
31912
+ "connect.google-unhealthy",
31913
+ "refusal.google-unhealthy",
31914
+ // The loudest record on this branch, and the only one that means "we cannot
31915
+ // explain this". Google refused a real call while a live check of the same
31916
+ // credential, taken seconds later, succeeded — so neither the 7-day cliff nor
31917
+ // a revoked grant accounts for it. It is filed as a failure precisely because
31918
+ // it is the record nobody may scroll past: it is the only evidence that could
31919
+ // ever justify building something on the hosted path, and its absence over
31920
+ // time is what retires that theory for good.
31921
+ "refusal.google-ok"
31922
+ ]);
31923
+ var PREFIX = "gog-auth ";
31924
+ var TAG_CHARS = 12;
31925
+ function credentialTag(cacheKeyHash) {
31926
+ return cacheKeyHash.slice(0, TAG_CHARS);
31927
+ }
31928
+ function logAuthTransition(event, context) {
31929
+ const record2 = JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), event, ...context });
31930
+ const write = FAILURES.has(event) ? console.error : console.warn;
31931
+ write(PREFIX + redactSecrets2(record2));
31932
+ }
31865
31933
 
31866
31934
  // ../gogcli-mcp/src/google-token.ts
31867
31935
  var TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token";
@@ -31888,22 +31956,73 @@ function makeAccessTokenSource(env) {
31888
31956
  );
31889
31957
  };
31890
31958
  }
31891
- return async () => {
31892
- const key = await cacheKey(refreshToken, clientId);
31893
- const hit = cache.get(key);
31894
- if (hit && hit.expiresAt - EXPIRY_MARGIN_MS > Date.now()) return hit.accessToken;
31895
- let pending = inFlight.get(key);
31959
+ let keyPromise;
31960
+ const key = () => keyPromise ??= cacheKey(refreshToken, clientId);
31961
+ const logCacheHits = parseBoolEnv("GOG_AUTH_LOG_CACHE_HITS", { env });
31962
+ const read = async () => {
31963
+ const k = await key();
31964
+ const hit = cache.get(k);
31965
+ if (hit && hit.expiresAt - EXPIRY_MARGIN_MS > Date.now()) {
31966
+ if (logCacheHits) logAuthTransition("token.cache-hit", { credential: credentialTag(k) });
31967
+ return hit.accessToken;
31968
+ }
31969
+ let pending = inFlight.get(k);
31896
31970
  if (!pending) {
31897
31971
  pending = exchange(refreshToken, clientId, clientSecret).then((minted2) => {
31898
- cache.set(key, minted2);
31972
+ cache.set(k, minted2);
31973
+ logAuthTransition("token.minted", {
31974
+ credential: credentialTag(k),
31975
+ reason: `valid for ${Math.round((minted2.expiresAt - Date.now()) / 1e3)}s`
31976
+ });
31899
31977
  return minted2;
31900
- }).finally(() => inFlight.delete(key));
31901
- inFlight.set(key, pending);
31978
+ }).catch((err) => {
31979
+ logAuthTransition(err.grantDead ? "grant.dead" : "token.mint-failed", {
31980
+ credential: credentialTag(k),
31981
+ reason: err.message
31982
+ });
31983
+ throw err;
31984
+ }).finally(() => inFlight.delete(k));
31985
+ inFlight.set(k, pending);
31902
31986
  }
31903
31987
  const minted = await pending;
31904
31988
  return minted.accessToken;
31905
31989
  };
31990
+ const invalidate = async (rejected) => {
31991
+ const k = await key();
31992
+ const hit = cache.get(k);
31993
+ if (!hit || hit.accessToken !== rejected) {
31994
+ logAuthTransition("token.evict-noop", {
31995
+ credential: credentialTag(k),
31996
+ reason: hit ? "a concurrent caller had already replaced this credential\u2019s token" : "no token was cached for this credential"
31997
+ });
31998
+ return false;
31999
+ }
32000
+ cache.delete(k);
32001
+ logAuthTransition("token.evicted", {
32002
+ credential: credentialTag(k),
32003
+ reason: "Google rejected this access token; the next read will mint a new one"
32004
+ });
32005
+ return true;
32006
+ };
32007
+ return Object.assign(read, {
32008
+ invalidate,
32009
+ credentialId: async () => credentialTag(await key())
32010
+ });
31906
32011
  }
32012
+ var TokenExchangeError = class extends Error {
32013
+ /**
32014
+ * The REFRESH token is dead (Google's `invalid_grant`), not merely the access
32015
+ * token. Carried as a flag rather than re-read from the message, because
32016
+ * inferring the author of a failure from prose several authors can produce is
32017
+ * precisely the mistake this branch exists to undo. `instanceof` is safe: the
32018
+ * class is thrown and caught inside this one module.
32019
+ */
32020
+ grantDead;
32021
+ constructor(message, grantDead) {
32022
+ super(message);
32023
+ this.grantDead = grantDead;
32024
+ }
32025
+ };
31907
32026
  async function exchange(refreshToken, clientId, clientSecret) {
31908
32027
  let res;
31909
32028
  try {
@@ -31918,79 +32037,338 @@ async function exchange(refreshToken, clientId, clientSecret) {
31918
32037
  }).toString()
31919
32038
  });
31920
32039
  } catch (err) {
31921
- throw new Error(
31922
- `the Google token exchange could not be reached: ${err instanceof Error ? err.message : String(err)}`
32040
+ throw new TokenExchangeError(
32041
+ `the Google token exchange could not be reached: ${err instanceof Error ? err.message : String(err)}`,
32042
+ false
31923
32043
  );
31924
32044
  }
31925
32045
  const body = await res.json().catch(() => ({}));
31926
32046
  if (!res.ok) {
31927
32047
  if (body.error === "invalid_grant") {
31928
- throw new Error(
31929
- '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.'
32048
+ throw new TokenExchangeError(
32049
+ '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.',
32050
+ true
31930
32051
  );
31931
32052
  }
31932
- throw new Error(
31933
- `the access token could not be refreshed (HTTP ${res.status}${body.error ? `, ${body.error}` : ""})`
32053
+ throw new TokenExchangeError(
32054
+ `the access token could not be refreshed (HTTP ${res.status}${body.error ? `, ${body.error}` : ""})`,
32055
+ false
31934
32056
  );
31935
32057
  }
31936
32058
  if (!body.access_token) {
31937
- throw new Error("the access token could not be refreshed: Google returned no access_token");
32059
+ throw new TokenExchangeError(
32060
+ "the access token could not be refreshed: Google returned no access_token",
32061
+ false
32062
+ );
31938
32063
  }
31939
32064
  const expiresInMs = (body.expires_in ?? 3600) * 1e3;
31940
32065
  return { accessToken: body.access_token, expiresAt: Date.now() + expiresInMs };
31941
32066
  }
31942
32067
 
32068
+ // ../gogcli-mcp/src/google-probe.ts
32069
+ var bool = (value) => typeof value === "boolean" ? value : void 0;
32070
+ var cause = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
32071
+ function readGoogleProbe(body) {
32072
+ const record2 = typeof body === "object" && body !== null ? body : {};
32073
+ const measured = bool(record2.measured);
32074
+ const reported = cause(record2.error);
32075
+ if (measured === false) {
32076
+ return {
32077
+ kind: "unmeasured",
32078
+ reason: reported ?? "the runner reported it could not measure the Google layer"
32079
+ };
32080
+ }
32081
+ if (measured === true) {
32082
+ if (bool(record2.ok) === true) return { kind: "ok" };
32083
+ return {
32084
+ kind: "unhealthy",
32085
+ reason: reported ?? "the runner reported the Google layer unhealthy with no cause"
32086
+ };
32087
+ }
32088
+ return {
32089
+ kind: "unmeasured",
32090
+ 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"
32091
+ };
32092
+ }
32093
+
31943
32094
  // ../gogcli-mcp/src/connector-runtime.ts
31944
32095
  var DEFAULT_TIMEOUT_MS = 3e4;
31945
32096
  var DEADLINE_GRACE_MS = 5e3;
32097
+ var MIN_REPLAY_BUDGET_MS = 1e3;
32098
+ var REFUSAL_PROBE_TIMEOUT_MS = 4e3;
32099
+ var MIN_PROBE_BUDGET_MS = 1e3;
32100
+ var PROBE_INTERVAL_MS = 6e4;
31946
32101
  var RUNNER_GOG_FAILED = 422;
31947
32102
  var RUNNER_DRAINING = 503;
32103
+ var RUNNER_BAD_REQUEST = 400;
32104
+ var RUNNER_BAD_KEY = 401;
32105
+ var GogFailedError = class extends Error {
32106
+ /** gog's stderr alone, with no echoed argv mixed in. */
32107
+ stderr;
32108
+ constructor(message, stderr) {
32109
+ super(message);
32110
+ this.stderr = stderr;
32111
+ }
32112
+ };
32113
+ var GOOGLE_TOKEN_REJECTED_PATTERN = /Google API error \(401\b|invalid[ _]authentication[ _]credentials|\bACCESS_TOKEN_EXPIRED\b|\binvalid_token\b/i;
32114
+ var REFRESH_TOKEN_DEAD_PATTERN = /\binvalid_grant\b/i;
32115
+ var READ_ONLY_SUBCOMMANDS = /* @__PURE__ */ new Set([
32116
+ "cat",
32117
+ "describe",
32118
+ "get",
32119
+ "info",
32120
+ "list",
32121
+ "list-slides",
32122
+ "ls",
32123
+ "metadata",
32124
+ "read-slide",
32125
+ "search",
32126
+ "services",
32127
+ "status",
32128
+ "structure"
32129
+ ]);
32130
+ function gogTarget(args) {
32131
+ const words = args.filter((arg) => typeof arg === "string");
32132
+ let service;
32133
+ for (let i = 0; i < words.length; i += 1) {
32134
+ const word = words[i];
32135
+ if (word.startsWith("-")) {
32136
+ if (word === "--account") i += 1;
32137
+ continue;
32138
+ }
32139
+ if (service === void 0) {
32140
+ service = word;
32141
+ continue;
32142
+ }
32143
+ return { service, subcommand: word };
32144
+ }
32145
+ return { service };
32146
+ }
32147
+ async function remintAfterGoogleRejection(err, used, args, readAccessToken, deadlineAt, probeGoogle) {
32148
+ if (!(err instanceof GogFailedError)) return void 0;
32149
+ const grantDead = REFRESH_TOKEN_DEAD_PATTERN.test(err.stderr);
32150
+ if (!grantDead && !GOOGLE_TOKEN_REJECTED_PATTERN.test(err.stderr)) return void 0;
32151
+ const { service, subcommand } = gogTarget(args);
32152
+ const credential = await readAccessToken?.credentialId?.();
32153
+ const where = { credential, service };
32154
+ if (grantDead) {
32155
+ logAuthTransition("grant.dead", {
32156
+ ...where,
32157
+ reason: "gog reported invalid_grant: the stored refresh token is dead, so no token can be minted and this account must be re-authorized"
32158
+ });
32159
+ return void 0;
32160
+ }
32161
+ if (!used) {
32162
+ await probeGoogle(where);
32163
+ logAuthTransition("replay.declined", {
32164
+ ...where,
32165
+ reason: "no access token was supplied with the call, so gog acted as the backend volume\u2019s own identity"
32166
+ });
32167
+ return void 0;
32168
+ }
32169
+ if (!readAccessToken?.invalidate) {
32170
+ logAuthTransition("replay.declined", {
32171
+ ...where,
32172
+ reason: "this token source cannot mint a replacement, so a replay would resend the rejected token"
32173
+ });
32174
+ return void 0;
32175
+ }
32176
+ const evicted = await readAccessToken.invalidate(used);
32177
+ if (subcommand === void 0 || !READ_ONLY_SUBCOMMANDS.has(subcommand)) {
32178
+ logAuthTransition("replay.declined", {
32179
+ ...where,
32180
+ reason: `not replayable: '${subcommand ?? "(none)"}' is not a known read-only subcommand and a write could double-apply`
32181
+ });
32182
+ return void 0;
32183
+ }
32184
+ if (!evicted) {
32185
+ logAuthTransition("replay.declined", {
32186
+ ...where,
32187
+ reason: "the rejected token was already superseded, so the cache holds the token a replay would send"
32188
+ });
32189
+ return void 0;
32190
+ }
32191
+ const fresh = await readAccessToken();
32192
+ if (!fresh) {
32193
+ logAuthTransition("replay.declined", {
32194
+ ...where,
32195
+ reason: "the token source produced no token after eviction; replaying without one would act as the backend"
32196
+ });
32197
+ return void 0;
32198
+ }
32199
+ const budgetMs = deadlineAt - Date.now();
32200
+ if (budgetMs < MIN_REPLAY_BUDGET_MS) {
32201
+ logAuthTransition("replay.declined", {
32202
+ ...where,
32203
+ 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`
32204
+ });
32205
+ return void 0;
32206
+ }
32207
+ return { token: fresh, budgetMs, invalidate: readAccessToken.invalidate, ...where };
32208
+ }
31948
32209
  function makeFlyExecutor(endpoint, key, readAccessToken) {
32210
+ let lastProbeAt = Number.NEGATIVE_INFINITY;
32211
+ const probeGoogleAfterRefusal = async (where, deadlineAt) => {
32212
+ const record2 = { ...where, endpoint };
32213
+ const now = Date.now();
32214
+ const remainingMs = deadlineAt - now;
32215
+ if (remainingMs < MIN_PROBE_BUDGET_MS) {
32216
+ logAuthTransition("refusal.google-unmeasured", {
32217
+ ...record2,
32218
+ 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`
32219
+ });
32220
+ return;
32221
+ }
32222
+ if (now - lastProbeAt < PROBE_INTERVAL_MS) {
32223
+ logAuthTransition("refusal.google-unmeasured", {
32224
+ ...record2,
32225
+ // "attempted", not "measured". `lastProbeAt` is stamped before the
32226
+ // fetch and is deliberately NOT reset when the probe comes back with no
32227
+ // verdict (a 404 from a runner too old to have the endpoint, a timeout,
32228
+ // a dead socket) — the backend cost this throttle exists to bound was
32229
+ // paid either way, and resetting it would let a retry loop storm a
32230
+ // runner that is already unwell. So the timestamp stays and the sentence
32231
+ // has to be the true one: on this branch a log line may not assert a
32232
+ // measurement that never happened, and the previous probe may well have
32233
+ // measured nothing at all.
32234
+ 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"
32235
+ });
32236
+ return;
32237
+ }
32238
+ lastProbeAt = now;
32239
+ let event;
32240
+ let reason;
32241
+ try {
32242
+ const res = await fetch(`${endpoint}/health/google`, {
32243
+ headers: { Authorization: `Bearer ${key}` },
32244
+ // Never more than the probe's own budget, never more than the call has
32245
+ // left. `Math.min` rather than a plain constant because the second
32246
+ // bound is the caller's, and it outranks ours.
32247
+ signal: AbortSignal.timeout(Math.min(REFUSAL_PROBE_TIMEOUT_MS, remainingMs))
32248
+ });
32249
+ if (!res.ok) {
32250
+ event = "refusal.google-unmeasured";
32251
+ reason = `the runner did not answer the Google probe (HTTP ${res.status})`;
32252
+ } else {
32253
+ const verdict = readGoogleProbe(await res.json());
32254
+ if (verdict.kind === "ok") {
32255
+ event = "refusal.google-ok";
32256
+ 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";
32257
+ } else {
32258
+ event = verdict.kind === "unhealthy" ? "refusal.google-unhealthy" : "refusal.google-unmeasured";
32259
+ reason = verdict.reason;
32260
+ }
32261
+ }
32262
+ } catch (err) {
32263
+ event = "refusal.google-unmeasured";
32264
+ reason = err instanceof Error ? err.message : String(err);
32265
+ }
32266
+ logAuthTransition(event, { ...record2, reason });
32267
+ };
31949
32268
  return async (args, opts) => {
31950
32269
  const deadlineMs = (opts?.timeout ?? DEFAULT_TIMEOUT_MS) + DEADLINE_GRACE_MS;
31951
32270
  const accessToken = await readAccessToken?.();
31952
- let res;
32271
+ const deadlineAt = Date.now() + deadlineMs;
31953
32272
  try {
31954
- res = await fetch(endpoint + "/run", {
31955
- method: "POST",
31956
- headers: {
31957
- Authorization: "Bearer " + key,
31958
- "Content-Type": "application/json"
31959
- },
31960
- body: JSON.stringify(accessToken ? { args, accessToken } : { args }),
31961
- signal: AbortSignal.timeout(deadlineMs)
31962
- });
32273
+ return await attempt(endpoint, key, args, accessToken, deadlineMs);
31963
32274
  } catch (err) {
31964
- const name = err instanceof Error ? err.name : "";
31965
- if (name === "TimeoutError" || name === "AbortError") {
31966
- throw new Error(
31967
- `gog-runner did not respond within ${deadlineMs}ms (${endpoint}) \u2014 the Fly backend may be cold or wedged`
31968
- );
32275
+ const replay = await remintAfterGoogleRejection(
32276
+ err,
32277
+ accessToken,
32278
+ args,
32279
+ readAccessToken,
32280
+ deadlineAt,
32281
+ (where2) => probeGoogleAfterRefusal(where2, deadlineAt)
32282
+ );
32283
+ if (replay === void 0) throw err;
32284
+ const where = { credential: replay.credential, service: replay.service, endpoint };
32285
+ logAuthTransition("replay.attempted", {
32286
+ ...where,
32287
+ reason: "Google rejected the access token; replaying this read once with a freshly minted one"
32288
+ });
32289
+ try {
32290
+ const stdout = await attempt(endpoint, key, args, replay.token, replay.budgetMs);
32291
+ logAuthTransition("replay.succeeded", where);
32292
+ return stdout;
32293
+ } catch (replayErr) {
32294
+ logAuthTransition("replay.failed", { ...where, reason: String(replayErr) });
32295
+ if (replayErr instanceof GogFailedError && GOOGLE_TOKEN_REJECTED_PATTERN.test(replayErr.stderr)) {
32296
+ await replay.invalidate(replay.token);
32297
+ }
32298
+ throw replayErr;
31969
32299
  }
31970
- throw err;
31971
32300
  }
31972
- if (!res.ok) {
31973
- const body = await res.json().catch(() => null);
31974
- const detail = body && typeof body.error === "string" ? body.stderr && body.stderr.trim() && body.stderr.trim() !== body.error.trim() ? `${body.error}
32301
+ };
32302
+ }
32303
+ async function attempt(endpoint, key, args, accessToken, deadlineMs) {
32304
+ let res;
32305
+ try {
32306
+ res = await fetch(endpoint + "/run", {
32307
+ method: "POST",
32308
+ headers: {
32309
+ Authorization: "Bearer " + key,
32310
+ "Content-Type": "application/json"
32311
+ },
32312
+ body: JSON.stringify(accessToken ? { args, accessToken } : { args }),
32313
+ signal: AbortSignal.timeout(deadlineMs)
32314
+ });
32315
+ } catch (err) {
32316
+ const name = err instanceof Error ? err.name : "";
32317
+ if (name === "TimeoutError" || name === "AbortError") {
32318
+ throw new RunnerTransportError(
32319
+ `gog-runner did not respond within ${deadlineMs}ms (${endpoint}) \u2014 the Fly backend may be cold or wedged`,
32320
+ "transport-retryable"
32321
+ );
32322
+ }
32323
+ throw err;
32324
+ }
32325
+ if (!res.ok) {
32326
+ const body = await res.json().catch(() => null);
32327
+ const detail = body && typeof body.error === "string" ? body.stderr && body.stderr.trim() && body.stderr.trim() !== body.error.trim() ? `${body.error}
31975
32328
  ${body.stderr}` : body.error : "";
31976
- if (res.status === RUNNER_GOG_FAILED) {
31977
- throw new Error(detail || "gog failed on the runner (no detail supplied)");
31978
- }
31979
- if (res.status === RUNNER_DRAINING || body?.retryable === true) {
31980
- throw new Error(
31981
- `gog-runner is restarting; retry this call.${detail ? ` ${detail}` : ""}`
31982
- );
31983
- }
31984
- if (detail) {
31985
- throw new Error(detail);
31986
- }
31987
- throw new Error(
31988
- `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.`
32329
+ if (res.status === RUNNER_GOG_FAILED) {
32330
+ throw new GogFailedError(
32331
+ detail || "gog failed on the runner (no detail supplied)",
32332
+ typeof body?.stderr === "string" ? body.stderr : ""
31989
32333
  );
31990
32334
  }
31991
- const { stdout } = await res.json();
31992
- return stdout;
31993
- };
32335
+ if (res.status === RUNNER_BAD_KEY) {
32336
+ logAuthTransition("runner.auth-failed", {
32337
+ service: gogTarget(args).service,
32338
+ endpoint,
32339
+ 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"
32340
+ });
32341
+ throw new RunnerTransportError(
32342
+ "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.",
32343
+ "transport-auth",
32344
+ res.status
32345
+ );
32346
+ }
32347
+ if (res.status === RUNNER_BAD_REQUEST) {
32348
+ throw new RunnerTransportError(
32349
+ detail || "gog-runner rejected the request (no detail supplied)",
32350
+ "transport-request",
32351
+ res.status
32352
+ );
32353
+ }
32354
+ if (res.status === RUNNER_DRAINING || body?.retryable === true) {
32355
+ throw new RunnerTransportError(
32356
+ `gog-runner is restarting; retry this call.${detail ? ` ${detail}` : ""}`,
32357
+ "transport-retryable",
32358
+ res.status
32359
+ );
32360
+ }
32361
+ if (detail) {
32362
+ throw new Error(detail);
32363
+ }
32364
+ throw new RunnerTransportError(
32365
+ `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.`,
32366
+ "transport-retryable",
32367
+ res.status
32368
+ );
32369
+ }
32370
+ const { stdout } = await res.json();
32371
+ return stdout;
31994
32372
  }
31995
32373
 
31996
32374
  // ../gogcli-mcp/src/remote-runner.ts
@@ -32047,6 +32425,7 @@ function trimThread(result, latestN, snippetsOnly) {
32047
32425
  return result;
32048
32426
  }
32049
32427
  }
32428
+ var GOG_DEFAULT_INLINE_MAX_BYTES = 3145728;
32050
32429
  var MIME_BY_EXT = {
32051
32430
  pdf: "application/pdf",
32052
32431
  png: "image/png",
@@ -32108,13 +32487,29 @@ async function resolveBySize(messageId, sizeBytes, account) {
32108
32487
  return void 0;
32109
32488
  }
32110
32489
  }
32490
+ async function resolveByIndex(messageId, index, account) {
32491
+ try {
32492
+ const parsed = JSON.parse(
32493
+ await run(["gmail", "get", messageId, "--use-indexed-attachment-ids"], { account })
32494
+ );
32495
+ const attachments = parsed.attachments;
32496
+ if (!attachments) return void 0;
32497
+ const declared = attachments.find((a) => a.attachmentIndex === index);
32498
+ if (declared) return declared;
32499
+ if (attachments.every((a) => a.attachmentIndex === void 0)) return attachments[index];
32500
+ return void 0;
32501
+ } catch {
32502
+ return void 0;
32503
+ }
32504
+ }
32111
32505
  function defaultOutPath(messageId, filename) {
32112
32506
  return `/tmp/gog-attachments/${messageId}/${filename}`;
32113
32507
  }
32114
32508
  function sanitizeAttachmentError(err, messageId, attachmentId) {
32115
32509
  let msg = err instanceof Error ? err.message : String(err);
32116
32510
  msg = msg.replace(/^Command failed:.*(\n|$)/, "");
32117
- msg = msg.split(attachmentId).join("<attachment>").split(messageId).join("<message>");
32511
+ if (attachmentId) msg = msg.split(attachmentId).join("<attachment>");
32512
+ msg = msg.split(messageId).join("<message>");
32118
32513
  return msg.trim() || "the download failed on the server";
32119
32514
  }
32120
32515
  function inlineImageResult(summary, base643, mimeType) {
@@ -32178,21 +32573,35 @@ function registerExtraGmailTools(server) {
32178
32573
  return runOrDiagnose(args, { account, lossless: true });
32179
32574
  });
32180
32575
  server.registerTool("gog_gmail_attachment", {
32181
- description: `Download a Gmail attachment and deliver its contents so you can actually read them. The real filename and MIME type are resolved from the message part metadata, so the saved file and response are named correctly (e.g. Guest_Copy.pdf), never a generic *.bin. deliver="auto" (default) is transport-aware: images always come back as a native image block; anything else is delivered by the channel that works on your transport \u2014 a readable server-side file PATH on local (stdio) clients that share the filesystem, or a Google Drive link on the remote connector (whose backend filesystem you can't read, and which rejects inline PDF/binary blobs). deliver="inline" forces the bytes inline as an image or embedded resource blob (use only if your client consumes resource blobs; errors if over gog's 3 MiB cap). deliver="drive" always uploads to Drive; deliver="off" writes the file server-side and returns {path, fileName, mimeType, bytes}. Drive delivery creates a file in your Drive (blocked when GOG_READONLY is set).`,
32576
+ description: `Download a Gmail attachment and deliver its contents so you can actually read them. Identify the attachment by attachmentIndex (preferred: the 0-based position from a listing fetched with useIndexedAttachmentIds \u2014 stable, and it resolves the real name before the download) or by the legacy opaque attachmentId. The real filename and MIME type are resolved from the message part metadata, so the saved file and response are named correctly (e.g. Guest_Copy.pdf), never a generic *.bin. deliver="auto" (default) is transport-aware: images always come back as a native image block; anything else is delivered by the channel that works on your transport \u2014 a readable server-side file PATH on local (stdio) clients that share the filesystem, or a Google Drive link on the remote connector (whose backend filesystem you can't read, and which rejects inline PDF/binary blobs). deliver="inline" forces the bytes inline as an image or embedded resource blob (use only if your client consumes resource blobs; errors if over gog's 3 MiB cap). deliver="drive" always uploads to Drive; deliver="off" writes the file server-side and returns {path, fileName, mimeType, bytes}. Drive delivery creates a file in your Drive (blocked when GOG_READONLY is set).`,
32182
32577
  inputSchema: {
32183
32578
  messageId: external_exports.string().describe("Gmail message ID"),
32184
- attachmentId: external_exports.string().describe("Attachment ID (from the message payload)"),
32579
+ attachmentId: external_exports.string().optional().describe("The opaque attachment ID from a listing. Legacy addressing: Gmail re-issues a DIFFERENT id for the same part on every API call, so an id copied from an older listing can be stale. Prefer attachmentIndex. Exactly one of attachmentId / attachmentIndex is required."),
32580
+ attachmentIndex: external_exports.number().int().nonnegative().optional().describe("The attachment's 0-based position in its message \u2014 the `attachmentIndex` field of a listing fetched with useIndexedAttachmentIds. Stable (a message's MIME structure does not change), so this is the reliable way to name an attachment. Exactly one of attachmentId / attachmentIndex is required. NOTE: it is per-MESSAGE \u2014 in gog_gmail_thread_attachments the array is flattened across the whole thread, so use each row's messageId + attachmentIndex, never its position in that flat list."),
32581
+ inlineMaxBytes: external_exports.number().int().nonnegative().optional().describe("Byte ceiling under which gog embeds the attachment bytes rather than only writing the file. Defaults to gog's own 3145728, which this server pins explicitly on every call so an ambient GOG_GMAIL_INLINE_MAX_BYTES cannot change the answer. Raise it to inline something larger, lower it to force the file/Drive path."),
32185
32582
  deliver: external_exports.enum(["auto", "inline", "drive", "off"]).optional().describe("How to return the contents: auto (image inline; else a local file path or a Drive link, per transport), inline (force bytes as image/resource blob), drive (always a Drive link), or off (server-side download only). Default: auto."),
32186
32583
  out: external_exports.string().optional().describe("Server-side path where gog writes the file. NOTE: this resolves on the CONNECTOR/gog server's filesystem, not your machine \u2014 on the remote connector it is ignored (you can't read it; you get a Drive link instead). Locally it is honored. Omit it to use an ephemeral temp path."),
32187
32584
  name: external_exports.string().optional().describe("Filename override. Defaults to the attachment's real filename from the message metadata; pass this to skip that lookup or force a name."),
32188
32585
  driveFolder: external_exports.string().optional().describe("Destination Google Drive folder ID for the uploaded copy (drive/auto delivery on the remote connector, or oversized attachments)."),
32189
32586
  account: accountParam
32190
32587
  }
32191
- }, async ({ messageId, attachmentId, deliver = "auto", out, name, driveFolder, account }) => {
32588
+ }, async ({ messageId, attachmentId, attachmentIndex, deliver = "auto", out, name, inlineMaxBytes, driveFolder, account }) => {
32589
+ if (attachmentId === void 0 === (attachmentIndex === void 0)) {
32590
+ return errorResult(
32591
+ "Pass exactly one of attachmentId or attachmentIndex. Prefer attachmentIndex \u2014 the 0-based `attachmentIndex` from a listing fetched with useIndexedAttachmentIds \u2014 because Gmail's opaque attachmentId is not stable across API calls and a copied one may no longer resolve."
32592
+ );
32593
+ }
32594
+ const indexed = attachmentIndex !== void 0;
32595
+ const attachmentRef = indexed ? String(attachmentIndex) : attachmentId;
32192
32596
  const remote = runExecutor.getStore() !== void 0;
32193
32597
  try {
32194
32598
  let filename = name ? sanitizeFilename(name) : void 0;
32195
32599
  let mimeType = filename ? MIME_BY_EXT[extOf(filename)] : void 0;
32600
+ if (indexed && !filename) {
32601
+ const meta3 = await resolveByIndex(messageId, attachmentIndex, account);
32602
+ if (meta3?.filename) filename = sanitizeFilename(meta3.filename);
32603
+ if (meta3?.mimeType) mimeType = meta3.mimeType;
32604
+ }
32196
32605
  const notes = [];
32197
32606
  let outPath = out;
32198
32607
  if (out && remote) {
@@ -32207,12 +32616,16 @@ function registerExtraGmailTools(server) {
32207
32616
  if (!mimeType && (deliver === "auto" || deliver === "inline")) {
32208
32617
  needInline = true;
32209
32618
  }
32210
- const args = ["gmail", "attachment", messageId, attachmentId];
32619
+ const args = ["gmail", "attachment", messageId, attachmentRef];
32620
+ args.push(indexed ? "--use-indexed-attachment-ids" : "--use-indexed-attachment-ids=false");
32211
32621
  if (needInline) args.push("--inline");
32622
+ args.push(`--inline-max-bytes=${inlineMaxBytes ?? GOG_DEFAULT_INLINE_MAX_BYTES}`);
32212
32623
  args.push(`--out=${outPath}`, `--name=${filename ?? "attachment"}`);
32213
32624
  const info = JSON.parse(await run(args, { account }));
32214
32625
  const path = info.path ?? outPath;
32215
- if (!filename) {
32626
+ if (!filename && info.filename) filename = sanitizeFilename(info.filename);
32627
+ if (!mimeType && info.mimeType) mimeType = info.mimeType;
32628
+ if (!filename && !indexed) {
32216
32629
  const meta3 = await resolveBySize(messageId, info.bytes, account);
32217
32630
  if (meta3?.filename) filename = sanitizeFilename(meta3.filename);
32218
32631
  if (!mimeType && meta3?.mimeType) mimeType = meta3.mimeType;
@@ -32236,7 +32649,7 @@ function registerExtraGmailTools(server) {
32236
32649
  return withNote(isImage ? inlineImageResult(summary, info.contentBase64, mimeType) : inlineResourceResult(messageId, filename, summary, info.contentBase64, mimeType), notes);
32237
32650
  }
32238
32651
  return errorResult(
32239
- `Attachment is too large to return inline (${info.reason ?? "exceeds gog's 3 MiB inline limit"}). Use deliver="auto" or deliver="drive" to receive it as a Google Drive link.`
32652
+ `Attachment is too large to return inline (${info.reason ?? "exceeds gog's inline size limit, 3 MiB by default \u2014 raise inlineMaxBytes"}). Use deliver="auto" or deliver="drive" to receive it as a Google Drive link.`
32240
32653
  );
32241
32654
  }
32242
32655
  if (isImage && info.contentBase64) {
@@ -32378,15 +32791,17 @@ function registerExtraGmailTools(server) {
32378
32791
  sanitizeContent: external_exports.boolean().optional().describe("Strip HTML, remove URLs, omit raw payloads from JSON (largest payload-size reduction)"),
32379
32792
  latestN: external_exports.number().int().positive().optional().describe("Return only the most recent N messages in the thread (wrapper-side trim; avoids overflowing context on long threads)"),
32380
32793
  snippetsOnly: external_exports.boolean().optional().describe("Reduce each message to its id, labels, snippet, and key headers (From/To/Cc/Subject/Date), dropping full bodies"),
32794
+ useIndexedAttachmentIds: external_exports.boolean().optional().describe("Report each attachment as a 0-based `attachmentIndex` within its message instead of an opaque `attachmentId`. The index is stable across calls (a message's MIME structure does not change) while the id is not, so this is what you want before calling gog_gmail_attachment."),
32381
32795
  outDir: external_exports.string().optional().describe("Directory to write attachments to (default: current directory)"),
32382
32796
  account: accountParam
32383
32797
  }
32384
- }, async ({ threadId, download, full, sanitizeContent, latestN, snippetsOnly, outDir, account }) => {
32798
+ }, async ({ threadId, download, full, sanitizeContent, latestN, snippetsOnly, useIndexedAttachmentIds, outDir, account }) => {
32385
32799
  const args = ["gmail", "thread", "get", threadId];
32386
32800
  if (download) args.push("--download");
32387
32801
  if (full) args.push("--full");
32388
32802
  if (sanitizeContent) args.push("--sanitize-content");
32389
32803
  if (outDir) args.push(`--out-dir=${outDir}`);
32804
+ args.push(useIndexedAttachmentIds ? "--use-indexed-attachment-ids" : "--use-indexed-attachment-ids=false");
32390
32805
  const result = await runOrDiagnose(args, { account });
32391
32806
  if (latestN === void 0 && !snippetsOnly) return result;
32392
32807
  return trimThread(result, latestN, snippetsOnly);
@@ -32412,13 +32827,15 @@ function registerExtraGmailTools(server) {
32412
32827
  inputSchema: {
32413
32828
  threadId: external_exports.string().describe("Gmail thread ID"),
32414
32829
  download: external_exports.boolean().optional().describe("Download all attachments to the SERVER filesystem (see the note above; on the remote connector the files aren't reachable \u2014 fetch individually with gog_gmail_attachment instead)."),
32830
+ useIndexedAttachmentIds: external_exports.boolean().optional().describe("Report each attachment as a 0-based `attachmentIndex` instead of an opaque `attachmentId`. Set this before calling gog_gmail_attachment: the index is stable across calls, the id is not. The index counts WITHIN each message, and this listing flattens every message's attachments into one array \u2014 so pair each row's `messageId` with its own `attachmentIndex`; a row's position in the flat array is NOT the index."),
32415
32831
  outDir: external_exports.string().optional().describe("Directory to write attachments to, resolved on the gog SERVER's filesystem (default: current directory). Not your local machine on the remote connector."),
32416
32832
  account: accountParam
32417
32833
  }
32418
- }, async ({ threadId, download, outDir, account }) => {
32834
+ }, async ({ threadId, download, useIndexedAttachmentIds, outDir, account }) => {
32419
32835
  const args = ["gmail", "thread", "attachments", threadId];
32420
32836
  if (download) args.push("--download");
32421
32837
  if (outDir) args.push(`--out-dir=${outDir}`);
32838
+ args.push(useIndexedAttachmentIds ? "--use-indexed-attachment-ids" : "--use-indexed-attachment-ids=false");
32422
32839
  return runOrDiagnose(args, { account });
32423
32840
  });
32424
32841
  server.registerTool("gog_gmail_labels_list", {
@@ -32507,11 +32924,13 @@ function registerExtraGmailTools(server) {
32507
32924
  inputSchema: {
32508
32925
  draftId: external_exports.string().describe("Draft ID"),
32509
32926
  download: external_exports.boolean().optional().describe("Download draft attachments"),
32927
+ useIndexedAttachmentIds: external_exports.boolean().optional().describe("Report each attachment as a 0-based `attachmentIndex` instead of an opaque `attachmentId` (stable across calls, unlike the id)."),
32510
32928
  account: accountParam
32511
32929
  }
32512
- }, async ({ draftId, download, account }) => {
32930
+ }, async ({ draftId, download, useIndexedAttachmentIds, account }) => {
32513
32931
  const args = ["gmail", "drafts", "get", draftId];
32514
32932
  if (download) args.push("--download");
32933
+ args.push(useIndexedAttachmentIds ? "--use-indexed-attachment-ids" : "--use-indexed-attachment-ids=false");
32515
32934
  return runOrDiagnose(args, { account });
32516
32935
  });
32517
32936
  const draftWriteSchema = {
@@ -32521,7 +32940,7 @@ function registerExtraGmailTools(server) {
32521
32940
  subject: external_exports.string().describe("Subject"),
32522
32941
  body: external_exports.string().describe("Body (plain text). Any size \u2014 a large body is written to a temp file on the gog server rather than inlined into the command line. Note gog strips trailing newlines from a file-delivered body."),
32523
32942
  bodyHtml: external_exports.string().optional().describe("Body (HTML; optional). Pass the HTML itself at any size \u2014 a large body is written to a temp file on the gog server rather than inlined into the command line. Mutually exclusive with bodyHtmlFile."),
32524
- bodyHtmlFile: external_exports.string().optional().describe('Path to an HTML file that ALREADY EXISTS on the gog server to use as the HTML body, or "-" to read from stdin. Mutually exclusive with bodyHtml \u2014 supplying both is rejected. You rarely need this: bodyHtml handles large bodies on its own.'),
32943
+ bodyHtmlFile: external_exports.string().optional().describe(`Path to an HTML file that ALREADY EXISTS on the gog server to use as the HTML body. gog also accepts "-" for stdin, but this server never writes to gog's stdin, so "-" would hang until the call times out. Mutually exclusive with bodyHtml \u2014 supplying both is rejected. You rarely need this: bodyHtml handles large bodies on its own.`),
32525
32944
  replyToMessageId: external_exports.string().optional().describe("Reply to a specific Gmail MESSAGE id \u2014 the short hex `id` field from gog_gmail_get / _search / _thread_get (e.g. 19e7593d77fd9636), NOT a thread id and NOT the RFC822 `<\u2026@host>` Message-Id header. Anchors In-Reply-To/References to that exact message. To reply to a thread when you don't know the latest message, use replyToThreadId instead. If both are given, replyToMessageId wins."),
32526
32945
  replyToThreadId: external_exports.string().optional().describe(`Reply to a Gmail THREAD id \u2014 passed to gog as --thread-id, which threads the draft using the thread's latest-message headers (In-Reply-To/References). This is what "reply to this thread" almost always means. Mutually exclusive with replyToMessageId (which wins if both are set). Thread ids and message ids are both 16-hex strings and easy to confuse \u2014 use this param, not replyToMessageId, when the id came from a thread.`),
32527
32946
  replyTo: external_exports.string().optional().describe("Reply-To header address"),
@@ -32529,6 +32948,7 @@ function registerExtraGmailTools(server) {
32529
32948
  replyAll: external_exports.boolean().optional().describe("Auto-populate recipients from the original message (reply-all), inferring To/Cc from it. Requires replyToMessageId or replyToThreadId. Explicit to/cc/bcc still apply on top; omitRecipients still suppresses them."),
32530
32949
  attach: external_exports.array(external_exports.string()).optional().describe("Local file paths to attach (repeatable). Read on the gog server, base64-encoded with a MIME type inferred from the extension. The JSON result echoes attached filenames and byte sizes \u2014 check it to confirm the files were found and embedded. On gog_gmail_drafts_update, supplying attach REPLACES the draft's existing attachments; omitting it preserves them (use clearAttachments to remove all)."),
32531
32950
  from: external_exports.string().optional().describe("Send from this email address (must be a verified send-as alias)"),
32951
+ autoFromAddressedAlias: external_exports.boolean().optional().describe("When from is omitted, send from the verified send-as alias the original message was addressed TO, instead of the account's primary address \u2014 so a reply to mail sent to an alias goes back out from that alias. Ignored when from is set."),
32532
32952
  omitRecipients: external_exports.boolean().optional().describe("Create the draft with no recipients even if to/cc/bcc are supplied \u2014 an accidental-send guard. Populate recipients in a later update before sending."),
32533
32953
  returnFull: external_exports.boolean().optional().describe("After writing, re-fetch and return the full stored draft (subject, body, recipients) instead of just the write acknowledgement. Costs one extra read."),
32534
32954
  account: accountParam
@@ -32551,6 +32971,7 @@ function registerExtraGmailTools(server) {
32551
32971
  if (f.quote) args.push("--quote");
32552
32972
  if (f.attach) for (const path of f.attach) args.push(`--attach=${path}`);
32553
32973
  if (f.from) args.push(`--from=${f.from}`);
32974
+ args.push(f.autoFromAddressedAlias ? "--auto-from-addressed-alias" : "--auto-from-addressed-alias=false");
32554
32975
  }
32555
32976
  async function writeDraft(args, account, returnFull, knownDraftId) {
32556
32977
  const result = await runOrDiagnose(args, { account });
@@ -32563,7 +32984,7 @@ function registerExtraGmailTools(server) {
32563
32984
  }
32564
32985
  const draftId = knownDraftId ?? parsed.draftId;
32565
32986
  if (!draftId) return result;
32566
- return runOrDiagnose(["gmail", "drafts", "get", draftId], { account });
32987
+ return runOrDiagnose(["gmail", "drafts", "get", draftId, "--use-indexed-attachment-ids=false"], { account });
32567
32988
  }
32568
32989
  server.registerTool("gog_gmail_drafts_create", {
32569
32990
  description: "Create a new Gmail draft. Recipients (to/cc/bcc) are optional; omit them (or set omitRecipients) to create a recipient-less draft as an accidental-send guard. For replies, prefer replyToThreadId (anchors to the thread's latest message) or replyToMessageId (a specific message) \u2014 don't pass a thread id into replyToMessageId, which mis-threads silently.",
@@ -32574,17 +32995,19 @@ function registerExtraGmailTools(server) {
32574
32995
  return writeDraft(args, account, returnFull);
32575
32996
  });
32576
32997
  server.registerTool("gog_gmail_drafts_update", {
32577
- description: "Update an existing Gmail draft. For replies, prefer replyToThreadId (threads off the thread's latest message) or replyToMessageId (a specific message) over passing a thread id into replyToMessageId. Attachment semantics: supplying attach REPLACES the draft's existing attachments; omitting it preserves them; set clearAttachments to remove all.",
32998
+ description: "Update an existing Gmail draft. For replies, prefer replyToThreadId (threads off the thread's latest message) or replyToMessageId (a specific message) over passing a thread id into replyToMessageId. An update preserves the draft's existing reply context (In-Reply-To/References) and its threadId; it never invents reply headers for a draft that is not a reply. The result reports the effective inReplyTo/references so you can verify threading without a raw-header fetch. Attachment semantics: supplying attach REPLACES the draft's existing attachments; omitting it preserves them; set clearAttachments to remove all.",
32578
32999
  annotations: { destructiveHint: true },
32579
33000
  inputSchema: {
32580
33001
  draftId: external_exports.string().describe("Draft ID"),
32581
33002
  ...draftWriteSchema,
32582
- clearAttachments: external_exports.boolean().optional().describe("Remove all attachments from the draft. By default, omitting attach preserves the draft's existing attachments; this intentionally clears them. Ignored if attach is also supplied (attach replaces).")
33003
+ clearAttachments: external_exports.boolean().optional().describe("Remove all attachments from the draft. By default, omitting attach preserves the draft's existing attachments; this intentionally clears them. Ignored if attach is also supplied (attach replaces)."),
33004
+ clearReplyContext: external_exports.boolean().optional().describe("Strip In-Reply-To/References from the draft, turning a reply back into a standalone message while keeping the same draft id and threadId. Use this to repair a mis-threaded draft in place instead of deleting and recreating it. Mutually exclusive with replyToMessageId, replyToThreadId and quote \u2014 gog rejects the call if any of them is combined with this.")
32583
33005
  }
32584
- }, async ({ draftId, account, returnFull, clearAttachments, ...flags }) => {
33006
+ }, async ({ draftId, account, returnFull, clearAttachments, clearReplyContext, ...flags }) => {
32585
33007
  const args = ["gmail", "drafts", "update", draftId];
32586
33008
  appendDraftFlags(args, flags);
32587
33009
  if (clearAttachments) args.push("--clear-attachments");
33010
+ if (clearReplyContext) args.push("--clear-reply-context");
32588
33011
  return writeDraft(args, account, returnFull, draftId);
32589
33012
  });
32590
33013
  server.registerTool("gog_gmail_drafts_delete", {
@@ -32610,6 +33033,24 @@ function registerExtraGmailTools(server) {
32610
33033
  }, async ({ draftId, account }) => {
32611
33034
  return runOrDiagnose(["gmail", "drafts", "send", draftId], { account });
32612
33035
  });
33036
+ server.registerTool("gog_gmail_import", {
33037
+ description: "Import an existing RFC822/EML message INTO the mailbox. This is Gmail's import path, not a send: nothing leaves the account, and the message keeps its own From/Date/Message-Id headers so it files where it belongs chronologically. Use it to restore an exported message or to file a .eml under a label; to actually send mail use gog_gmail_send, and to stage one use gog_gmail_drafts_create. The file is read on the gog SERVER, not your machine.",
33038
+ inputSchema: {
33039
+ file: external_exports.string().describe(`Path to an RFC822/EML file that ALREADY EXISTS on the gog server. gog also accepts "-" for stdin, but this server never writes to gog's stdin, so "-" would hang until the call times out.`),
33040
+ labels: external_exports.array(external_exports.string()).optional().describe(`Labels to apply to the imported message (repeatable). Each may be a label ID or a label name \u2014 names are resolved server-side. A name containing a COMMA cannot be passed here: gog declares --label as a Kong slice with no separator override, so Kong splits each value on commas and "Clients, Inc" is looked up as two labels ("Clients" and "Inc") and fails. Use that label's ID instead \u2014 ids never contain a comma; gog_gmail_labels_list gives you one.`),
33041
+ internalDateSource: external_exports.enum(["dateHeader", "receivedTime"]).optional().describe("Which clock sets Gmail's internal date: dateHeader (gog default \u2014 the message's own Date header, so it sorts into the mailbox at its original time) or receivedTime (now)."),
33042
+ neverMarkSpam: external_exports.boolean().optional().describe("Never classify the imported message as spam."),
33043
+ processForCalendar: external_exports.boolean().optional().describe("Process calendar invitations inside the imported message \u2014 this can ADD EVENTS to your calendar."),
33044
+ account: accountParam
33045
+ }
33046
+ }, async ({ file: file2, labels, internalDateSource, neverMarkSpam, processForCalendar, account }) => {
33047
+ const args = ["gmail", "import", file2];
33048
+ if (labels) for (const label of labels) args.push(`--label=${label}`);
33049
+ if (internalDateSource) args.push(`--internal-date-source=${internalDateSource}`);
33050
+ if (neverMarkSpam) args.push("--never-mark-spam");
33051
+ if (processForCalendar) args.push("--process-for-calendar");
33052
+ return runOrDiagnose(args, { account });
33053
+ });
32613
33054
  server.registerTool("gog_gmail_forward", {
32614
33055
  description: "Forward an existing Gmail message to new recipients.",
32615
33056
  annotations: { destructiveHint: true },
@@ -32636,7 +33077,7 @@ function registerExtraGmailTools(server) {
32636
33077
  messageId: external_exports.string().describe("Gmail message ID to reply to \u2014 the short hex `id` from gog_gmail_get / _search / _messages_search (NOT the threadId, NOT the RFC822 `<\u2026@host>` Message-Id header)."),
32637
33078
  body: external_exports.string().optional().describe("Reply body (plain text; required unless bodyHtml or bodyHtmlFile is set). Any size \u2014 a large body is written to a temp file on the gog server rather than inlined into the command line. Note gog strips trailing newlines from a file-delivered body."),
32638
33079
  bodyHtml: external_exports.string().optional().describe("Reply body (HTML; optional). Pass the HTML itself at any size \u2014 a large body is written to a temp file on the gog server rather than inlined into the command line. Mutually exclusive with bodyHtmlFile."),
32639
- bodyHtmlFile: external_exports.string().optional().describe('Path to an HTML file that ALREADY EXISTS on the gog server for the reply body, or "-" for stdin. Mutually exclusive with bodyHtml \u2014 supplying both is rejected. You rarely need this: bodyHtml handles large bodies on its own.'),
33080
+ bodyHtmlFile: external_exports.string().optional().describe(`Path to an HTML file that ALREADY EXISTS on the gog server for the reply body. gog also accepts "-" for stdin, but this server never writes to gog's stdin, so "-" would hang until the call times out. Mutually exclusive with bodyHtml \u2014 supplying both is rejected. You rarely need this: bodyHtml handles large bodies on its own.`),
32640
33081
  to: external_exports.array(external_exports.string()).optional().describe("Add or move recipients to To (repeatable). Added on top of the recipients inherited from the original message."),
32641
33082
  cc: external_exports.array(external_exports.string()).optional().describe("Add or move recipients to Cc (repeatable)"),
32642
33083
  bcc: external_exports.array(external_exports.string()).optional().describe("Add or move recipients to Bcc (repeatable)"),
@@ -32645,6 +33086,7 @@ function registerExtraGmailTools(server) {
32645
33086
  noQuote: external_exports.boolean().optional().describe("Do not include the original message quoted below the reply (default: the original is quoted)"),
32646
33087
  attach: external_exports.array(external_exports.string()).optional().describe("Local file paths to attach (repeatable). Read on the gog server, base64-encoded with a MIME type inferred from the extension."),
32647
33088
  from: external_exports.string().optional().describe("Send from this email address (must be a verified send-as alias)"),
33089
+ autoFromAddressedAlias: external_exports.boolean().optional().describe("When from is omitted, send from the verified send-as alias the original message was addressed TO, instead of the account's primary address \u2014 so a reply to mail sent to an alias goes back out from that alias. Ignored when from is set."),
32648
33090
  signature: external_exports.boolean().optional().describe("Append the Gmail signature from the active send-as address"),
32649
33091
  signatureFrom: external_exports.string().optional().describe("Append the Gmail signature from this send-as email address"),
32650
33092
  signatureFile: external_exports.string().optional().describe("Append a local signature file (plain text or HTML), read on the gog server"),
@@ -32666,6 +33108,7 @@ function registerExtraGmailTools(server) {
32666
33108
  if (f.signature) args.push("--signature");
32667
33109
  if (f.signatureFrom) args.push(`--signature-from=${f.signatureFrom}`);
32668
33110
  if (f.signatureFile) args.push(`--signature-file=${f.signatureFile}`);
33111
+ args.push(f.autoFromAddressedAlias ? "--auto-from-addressed-alias" : "--auto-from-addressed-alias=false");
32669
33112
  }
32670
33113
  server.registerTool("gog_gmail_reply", {
32671
33114
  description: 'Reply to a Gmail message (sends to the original sender only). Threads off the message and inherits a "Re:" subject and the quoted original by default. For replying to every participant use gog_gmail_reply_all; to reply across many messages matching a query use gog_gmail_autoreply; to stage a reply without sending use gog_gmail_drafts_create.',
@@ -32729,9 +33172,11 @@ function registerExtraGmailTools(server) {
32729
33172
  includeBody: external_exports.boolean().optional().describe("Include the decoded message body in each result"),
32730
33173
  full: external_exports.boolean().optional().describe("Show full message bodies without truncation (implies includeBody)"),
32731
33174
  bodyFormat: external_exports.enum(["text", "html"]).optional().describe("Body format preference when includeBody is set"),
33175
+ includeAttachments: external_exports.boolean().optional().describe("Include each message's attachment metadata (filename, size, mimeType, id or index). NOT a cheap add-on: like includeBody it makes gog fetch every matching message at format=full, so it costs a full per-message read \u2014 narrow the query or lower max before turning it on."),
33176
+ useIndexedAttachmentIds: external_exports.boolean().optional().describe("Report each attachment as a 0-based `attachmentIndex` within its message instead of an opaque `attachmentId` (stable across calls, unlike the id). Only has an effect alongside includeAttachments or includeBody."),
32732
33177
  account: accountParam
32733
33178
  }
32734
- }, async ({ query, max, page, all, includeBody, full, bodyFormat, account }) => {
33179
+ }, async ({ query, max, page, all, includeBody, full, bodyFormat, includeAttachments, useIndexedAttachmentIds, account }) => {
32735
33180
  const args = ["gmail", "messages", "search", query];
32736
33181
  if (max !== void 0) args.push(`--max=${max}`);
32737
33182
  if (page) args.push(`--page=${page}`);
@@ -32739,6 +33184,8 @@ function registerExtraGmailTools(server) {
32739
33184
  if (includeBody) args.push("--include-body");
32740
33185
  if (full) args.push("--full");
32741
33186
  if (bodyFormat) args.push(`--body-format=${bodyFormat}`);
33187
+ args.push(includeAttachments ? "--include-attachments" : "--include-attachments=false");
33188
+ args.push(useIndexedAttachmentIds ? "--use-indexed-attachment-ids" : "--use-indexed-attachment-ids=false");
32742
33189
  return runOrDiagnose(args, { account });
32743
33190
  });
32744
33191
  server.registerTool("gog_gmail_labels_style", {