@mindstone/mcp-server-google-workspace 0.5.12 → 0.5.13

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.
Files changed (35) hide show
  1. package/README.md +28 -3
  2. package/dist/connectorRenewalClient.d.ts +162 -0
  3. package/dist/connectorRenewalClient.js +212 -0
  4. package/dist/modules/accounts/manager.js +24 -4
  5. package/dist/modules/accounts/oauth.js +5 -2
  6. package/dist/modules/accounts/token.d.ts +1 -0
  7. package/dist/modules/accounts/token.js +18 -8
  8. package/dist/modules/accounts/unauthorized.d.ts +4 -0
  9. package/dist/modules/accounts/unauthorized.js +46 -0
  10. package/dist/modules/calendar/service.js +2 -2
  11. package/dist/modules/docs/service.d.ts +1 -1
  12. package/dist/modules/docs/service.js +16 -8
  13. package/dist/modules/docs/types.d.ts +0 -1
  14. package/dist/oauth/coordinatedClient.d.ts +14 -0
  15. package/dist/oauth/coordinatedClient.js +103 -0
  16. package/dist/tools/definitions/chat.js +1 -2
  17. package/dist/tools/definitions/docs.js +4 -8
  18. package/dist/tools/definitions/drive.js +0 -1
  19. package/dist/tools/docs-handlers.d.ts +0 -2
  20. package/dist/tools/docs-handlers.js +0 -2
  21. package/dist/tools/param-normalizer.js +0 -1
  22. package/dist/tools/server.js +8 -23
  23. package/dist/tools/type-guards.d.ts +0 -1
  24. package/dist/tools/type-guards.js +1 -3
  25. package/dist/utils/apiError.d.ts +4 -4
  26. package/dist/utils/apiError.js +7 -6
  27. package/dist/utils/google-retry.d.ts +6 -0
  28. package/dist/utils/google-retry.js +18 -1
  29. package/node_modules/cross-spawn/README.md +19 -3
  30. package/node_modules/cross-spawn/lib/parse.js +38 -10
  31. package/node_modules/cross-spawn/lib/util/escape.js +84 -25
  32. package/node_modules/cross-spawn/lib/util/readShebang.js +8 -2
  33. package/node_modules/cross-spawn/lib/util/resolveCommand.js +8 -1
  34. package/node_modules/cross-spawn/package.json +21 -24
  35. package/package.json +1 -1
@@ -4,7 +4,7 @@ import { getAccountManager } from '../accounts/index.js';
4
4
  import { CalendarError } from './types.js';
5
5
  import { DriveService } from '../drive/service.js';
6
6
  import { AccountError } from '../accounts/types.js';
7
- import { isUnauthorizedError } from '../accounts/unauthorized.js';
7
+ import { isGoogleAuthFailure } from '../accounts/unauthorized.js';
8
8
  import { isPassthroughGoogleError } from '../../utils/apiError.js';
9
9
  import { wrapUntrustedContent } from '../../utils/untrusted-controls.js';
10
10
  function toAttachmentReferences(attachments) {
@@ -371,7 +371,7 @@ export class CalendarService {
371
371
  throw error;
372
372
  if (isShortWindowRateLimit(error))
373
373
  throw error;
374
- if (isUnauthorizedError(error)) {
374
+ if (isGoogleAuthFailure(error)) {
375
375
  if (process.env.GOOGLE_WORKSPACE_DISABLE_REFRESH === '1') {
376
376
  throw new AccountError('Calendar authentication required', 'AUTH_REQUIRED', 'Connect Google Workspace to continue');
377
377
  }
@@ -114,7 +114,7 @@ export declare class DocsService extends BaseGoogleService<docs_v1.Docs> {
114
114
  /**
115
115
  * Copy one tab's content into another tab of the same document: into a new
116
116
  * tab (`newTabTitle`) or into an existing tab, which is cleared first
117
- * (`targetTabId` + `overwriteExisting`). Every input check, the source read
117
+ * (`targetTabId`). Every input check, the source read
118
118
  * and the per-chip access checks happen before the first write. On a failure
119
119
  * after that, a tab this call created is deleted again (best effort); an
120
120
  * existing target is left as it is and the error says so. A copy that
@@ -4,7 +4,7 @@ import { TabCopyError, copyTabContent } from './tabCopy.js';
4
4
  import { computeMoveApiIndex } from '../../utils/tabPosition.js';
5
5
  import { DOCS_SCOPES } from './scopes.js';
6
6
  import { describeApiError, describeApiErrorUntrusted, extractHttpStatus, failedResult, isAuthHandoffError, isPassthroughGoogleError, withCause } from '../../utils/apiError.js';
7
- import { preserveGoogleRetryDecision } from '../../utils/google-retry.js';
7
+ import { markMayHaveWritten, preserveGoogleRetryDecision } from '../../utils/google-retry.js';
8
8
  import { wrapUntrustedJsonValues } from '../../utils/untrusted-content.js';
9
9
  import { ALL_TEXT_KEYS, DocsInputError, quoteTabId, TAB_READ_TEXT_OPTIONS, TAB_TREE_FIELDS, TRUNCATION_MARKER, assertUniqueTitle, buildAllTabsText, bodyEndIndex, countWords, descendantsOf, extractBodyText, findAnchor, flatParagraphs, flattenTabs, nextParagraphInContainer, normalizeInsertText, paragraphSearchText, requireTabs, resolveTab, siblingsOf, } from './tabs.js';
10
10
  const DEFAULT_MAX_CHARS = 50000;
@@ -223,6 +223,7 @@ export class DocsService extends BaseGoogleService {
223
223
  * Create a new document with optional initial content
224
224
  */
225
225
  async createDocument(email, options) {
226
+ let documentId;
226
227
  try {
227
228
  await this.ensureInitialized();
228
229
  this.checkInitialized();
@@ -234,7 +235,7 @@ export class DocsService extends BaseGoogleService {
234
235
  title: options.title,
235
236
  },
236
237
  });
237
- const documentId = createResponse.data.documentId;
238
+ documentId = createResponse.data.documentId;
238
239
  if (!documentId) {
239
240
  return {
240
241
  success: false,
@@ -270,8 +271,13 @@ export class DocsService extends BaseGoogleService {
270
271
  catch (error) {
271
272
  // An expired/revoked grant must keep its reconnect signal — folding it
272
273
  // into a plain error string would skip the host's auth_required handoff.
273
- if (isPassthroughGoogleError(error))
274
+ if (isPassthroughGoogleError(error)) {
275
+ // The document already exists: a replay would create a second one.
276
+ if (documentId) {
277
+ throw markMayHaveWritten(withCause(new Error(`Created document ${documentId}, but adding its content failed.`), error));
278
+ }
274
279
  throw error;
280
+ }
275
281
  return failedResult(error, describeApiError(error));
276
282
  }
277
283
  }
@@ -889,7 +895,7 @@ export class DocsService extends BaseGoogleService {
889
895
  /**
890
896
  * Copy one tab's content into another tab of the same document: into a new
891
897
  * tab (`newTabTitle`) or into an existing tab, which is cleared first
892
- * (`targetTabId` + `overwriteExisting`). Every input check, the source read
898
+ * (`targetTabId`). Every input check, the source read
893
899
  * and the per-chip access checks happen before the first write. On a failure
894
900
  * after that, a tab this call created is deleted again (best effort); an
895
901
  * existing target is left as it is and the error says so. A copy that
@@ -911,9 +917,6 @@ export class DocsService extends BaseGoogleService {
911
917
  if (hasTarget && (options.newTabParentId !== undefined || options.newTabPosition !== undefined)) {
912
918
  throw new DocsInputError('new_tab_parent_id and new_tab_position only apply with new_tab_title.');
913
919
  }
914
- if (hasTarget && options.overwriteExisting !== true) {
915
- throw new DocsInputError('Copying into an existing tab clears it first. Pass overwrite_existing: true to confirm, or use new_tab_title to copy into a new tab.');
916
- }
917
920
  const newTitle = hasNewTitle ? requireTabTitle(options.newTabTitle) : undefined;
918
921
  client = await this.getWriteClient(email);
919
922
  const docsClient = client;
@@ -1033,8 +1036,10 @@ export class DocsService extends BaseGoogleService {
1033
1036
  }
1034
1037
  const cause = error.cause;
1035
1038
  let outcome = '';
1039
+ let mayHaveWritten = true;
1036
1040
  if (createdTabId && client) {
1037
1041
  const cleaned = await this.deleteHalfWrittenTab(client, options.documentId, createdTabId);
1042
+ mayHaveWritten = !cleaned;
1038
1043
  outcome = cleaned
1039
1044
  ? ` The new tab ${createdTabId} was deleted again, so nothing changed.`
1040
1045
  : ` The new tab ${createdTabId} could not be deleted and may be partly written; delete it with delete_workspace_document_tab before trying again.`;
@@ -1051,6 +1056,7 @@ export class DocsService extends BaseGoogleService {
1051
1056
  }
1052
1057
  else {
1053
1058
  outcome = ' Nothing was written to the document.';
1059
+ mayHaveWritten = false;
1054
1060
  }
1055
1061
  // Auth handoffs keep their reconnect signal (after the cleanup attempt).
1056
1062
  if (isAuthHandoffError(cause))
@@ -1058,11 +1064,13 @@ export class DocsService extends BaseGoogleService {
1058
1064
  if (cause instanceof DocsInputError)
1059
1065
  throw cause;
1060
1066
  const status = extractHttpStatus(cause);
1061
- return preserveGoogleRetryDecision(withCause({
1067
+ const failure = preserveGoogleRetryDecision(withCause({
1062
1068
  success: false,
1063
1069
  error: `Copy failed during "${error.phase}": ${describeApiErrorUntrusted(cause, DOCS_API_ERROR_SOURCE)}.${outcome}`,
1064
1070
  ...(status === 429 ? { status } : {}),
1065
1071
  }, cause), cause);
1072
+ // Re-running a copy that may have written would write it twice.
1073
+ return mayHaveWritten ? markMayHaveWritten(failure) : failure;
1066
1074
  }
1067
1075
  }
1068
1076
  /** Best-effort removal of a tab a failed copy created. True when it is gone. */
@@ -151,7 +151,6 @@ export interface CopyTabOptions {
151
151
  documentId: string;
152
152
  sourceTabId: string;
153
153
  targetTabId?: string;
154
- overwriteExisting?: boolean;
155
154
  newTabTitle?: string;
156
155
  newTabParentId?: string;
157
156
  newTabPosition?: number;
@@ -0,0 +1,14 @@
1
+ import { OAuth2Client, type Credentials } from 'google-auth-library';
2
+ type Credential = {
3
+ relativePath: string;
4
+ read: () => Promise<unknown>;
5
+ save: (tokens: Credentials) => Promise<void>;
6
+ };
7
+ /** Register only a token already read from its account's credential file; never search other accounts. */
8
+ export declare function registerGoogleCredential(file: string, token: unknown, read: Credential['read'], save: Credential['save']): void;
9
+ /** The SDK's explicit refresh and API-request automatic refresh both enter this protected seam (10.6.2). */
10
+ export declare class CoordinatedOAuth2Client extends OAuth2Client {
11
+ protected refreshTokenNoCache(refreshToken?: string | null): Promise<import("google-auth-library/build/src/auth/oauth2client.js").GetTokenResponse>;
12
+ }
13
+ export {};
14
+ //# sourceMappingURL=coordinatedClient.d.ts.map
@@ -0,0 +1,103 @@
1
+ import path from 'node:path';
2
+ import { OAuth2Client } from 'google-auth-library';
3
+ import { z } from 'zod';
4
+ import { ConnectorRenewal, RenewalAttemptError, RenewalWaitError } from '../connectorRenewalClient.js';
5
+ const SavedToken = z.object({
6
+ access_token: z.string().min(1), refresh_token: z.string().min(1),
7
+ expiry_date: z.number().finite().optional(), scope: z.string().optional(), token_type: z.string().optional(),
8
+ }).passthrough();
9
+ const credentials = new Map();
10
+ const credentialKeys = new Map();
11
+ let coordinator;
12
+ /** Register only a token already read from its account's credential file; never search other accounts. */
13
+ export function registerGoogleCredential(file, token, read, save) {
14
+ if (!process.env.GOOGLE_WORKSPACE_RENEWAL_COORDINATOR_STATE)
15
+ return;
16
+ const parsed = SavedToken.safeParse(token);
17
+ const oldKey = credentialKeys.get(file);
18
+ if (oldKey)
19
+ credentials.delete(oldKey);
20
+ credentialKeys.delete(file);
21
+ if (!parsed.success)
22
+ return;
23
+ // CREDENTIALS_PATH is <provider folder>/<instance>/credentials (or the standalone credentials folder).
24
+ const instance = path.dirname(path.dirname(file));
25
+ const relativePath = path.basename(instance) === 'google-workspace-mcp'
26
+ ? `credentials/${path.basename(file)}`
27
+ : `${path.basename(instance)}/credentials/${path.basename(file)}`;
28
+ credentials.set(parsed.data.refresh_token, { relativePath, read, save });
29
+ credentialKeys.set(file, parsed.data.refresh_token);
30
+ }
31
+ function normalized(token) {
32
+ return { accessToken: token.access_token, refreshToken: token.refresh_token, expiresAt: token.expiry_date ?? null };
33
+ }
34
+ const RefreshResponse = z.object({
35
+ access_token: z.string().min(1), refresh_token: z.string().min(1).optional(),
36
+ expires_in: z.number().positive().finite(), scope: z.string().optional(), token_type: z.string().optional(),
37
+ });
38
+ /** The SDK's explicit refresh and API-request automatic refresh both enter this protected seam (10.6.2). */
39
+ export class CoordinatedOAuth2Client extends OAuth2Client {
40
+ async refreshTokenNoCache(refreshToken) {
41
+ const statePath = process.env.GOOGLE_WORKSPACE_RENEWAL_COORDINATOR_STATE;
42
+ if (!statePath)
43
+ return super.refreshTokenNoCache(refreshToken);
44
+ const disabled = process.env.GOOGLE_WORKSPACE_DISABLE_REFRESH;
45
+ if (disabled && disabled !== '0' && disabled.toLowerCase() !== 'false')
46
+ throw new RenewalWaitError();
47
+ const credential = refreshToken ? credentials.get(refreshToken) : undefined;
48
+ if (!credential)
49
+ throw new RenewalWaitError();
50
+ const original = SavedToken.parse(await credential.read());
51
+ if (original.refresh_token !== refreshToken)
52
+ throw new RenewalWaitError();
53
+ if (coordinator?.path !== statePath)
54
+ coordinator = { path: statePath, client: new ConnectorRenewal(statePath) };
55
+ let saved = original;
56
+ const result = await coordinator.client.refresh({ provider: 'google-workspace', relativePath: credential.relativePath }, normalized(original), async (permitted, dispatched) => {
57
+ const latest = SavedToken.safeParse(await credential.read());
58
+ if (!latest.success || latest.data.refresh_token !== refreshToken)
59
+ throw new RenewalWaitError();
60
+ const body = new URLSearchParams({ client_id: this._clientId ?? '', client_secret: this._clientSecret ?? '',
61
+ grant_type: 'refresh_token', refresh_token: permitted.refreshToken });
62
+ if (!this._clientId || !this._clientSecret)
63
+ throw new RenewalWaitError();
64
+ const signal = AbortSignal.timeout(30000);
65
+ dispatched();
66
+ const response = await globalThis.fetch(this.endpoints.oauth2TokenUrl, {
67
+ method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body, signal,
68
+ });
69
+ const data = await response.json();
70
+ if (!response.ok) {
71
+ const failure = z.object({ error: z.string() }).safeParse(data);
72
+ throw new RenewalAttemptError(response.status < 500 && failure.success &&
73
+ failure.data.error === 'invalid_grant'
74
+ ? 'rejected' : response.status >= 400 && response.status < 500 ? 'not_dispatched' : 'uncertain');
75
+ }
76
+ const fresh = RefreshResponse.parse(data);
77
+ saved = { ...original, ...fresh, refresh_token: fresh.refresh_token ?? permitted.refreshToken,
78
+ expiry_date: Date.now() + fresh.expires_in * 1000 };
79
+ return normalized(SavedToken.parse(saved));
80
+ }, async (tokens) => {
81
+ const latest = SavedToken.safeParse(await credential.read());
82
+ if (!latest.success || !(latest.data.access_token === original.access_token
83
+ && latest.data.refresh_token === original.refresh_token
84
+ || latest.data.access_token === tokens.accessToken && latest.data.refresh_token === tokens.refreshToken)) {
85
+ throw new RenewalAttemptError('uncertain');
86
+ }
87
+ saved = { ...original, ...saved, access_token: tokens.accessToken,
88
+ refresh_token: tokens.refreshToken ?? original.refresh_token, expiry_date: tokens.expiresAt ?? undefined };
89
+ await credential.save(saved);
90
+ }, async () => {
91
+ const legacy = await super.refreshTokenNoCache(refreshToken);
92
+ saved = { ...original, ...legacy.tokens, refresh_token: legacy.tokens.refresh_token ?? refreshToken };
93
+ return normalized(SavedToken.parse(saved));
94
+ });
95
+ const tokens = { ...saved, access_token: result.accessToken, refresh_token: result.refreshToken,
96
+ expiry_date: result.expiresAt ?? undefined };
97
+ // The SDK restores this field after refreshTokenNoCache; keep that restoration on the new rotation.
98
+ if (this.credentials.refresh_token === refreshToken)
99
+ this.credentials.refresh_token = tokens.refresh_token;
100
+ return { tokens, res: null };
101
+ }
102
+ }
103
+ //# sourceMappingURL=coordinatedClient.js.map
@@ -100,8 +100,7 @@ export const chatTools = [
100
100
  category: "Chat",
101
101
  description: `Post a plain-text message to a Google Chat space as the authenticated user.
102
102
 
103
- This sends a real message visible to everyone in the space. Confirm the space
104
- and the message content with the user before sending.
103
+ This sends a real message visible to everyone in the space.
105
104
 
106
105
  Use list_chat_spaces first to find the space resource name (e.g. "spaces/AAAA...").
107
106
 
@@ -730,8 +730,8 @@ export const docsTools = [
730
730
  apply with new_tab_title.
731
731
 
732
732
  Which target: to archive or duplicate a tab, use new_tab_title. To reset a tab in place from a
733
- template (keeping its id, position and sub-tabs), use target_tab_id with overwrite_existing:
734
- true, which clears the tab first. Never delete a tab in order to replace it: deleting also
733
+ template (keeping its id, position and sub-tabs), use target_tab_id, which clears the tab
734
+ first. Never delete a tab in order to replace it: deleting also
735
735
  deletes its sub-tabs. target_tab_id needs a real tab id ("default" is refused);
736
736
  source_tab_id and new_tab_parent_id accept "default" for the first tab.
737
737
 
@@ -756,7 +756,7 @@ export const docsTools = [
756
756
  { "email": "user@example.com", "document_id": "1ABC123xyz", "source_tab_id": "t.live01", "new_tab_title": "2031-10-13", "new_tab_parent_id": "t.live01", "new_tab_position": 0 }
757
757
 
758
758
  2. Reset the live tab from the Template tab (clears it first):
759
- { "email": "user@example.com", "document_id": "1ABC123xyz", "source_tab_id": "t.tmpl02", "target_tab_id": "t.live01", "overwrite_existing": true }`,
759
+ { "email": "user@example.com", "document_id": "1ABC123xyz", "source_tab_id": "t.tmpl02", "target_tab_id": "t.live01" }`,
760
760
  aliases: ['copy_doc_tab', 'duplicate_document_tab', 'clone_document_tab'],
761
761
  annotations: { readOnlyHint: false, destructiveHint: true },
762
762
  inputSchema: {
@@ -776,11 +776,7 @@ export const docsTools = [
776
776
  },
777
777
  target_tab_id: {
778
778
  type: 'string',
779
- description: 'Existing tab to copy into; it is cleared first and needs overwrite_existing: true ("default" is not accepted). Not with new_tab_title.'
780
- },
781
- overwrite_existing: {
782
- type: 'boolean',
783
- description: 'Confirms that target_tab_id will be cleared and overwritten (required with target_tab_id).'
779
+ description: 'Existing tab to copy into; it is cleared first ("default" is not accepted). Not with new_tab_title.'
784
780
  },
785
781
  new_tab_title: {
786
782
  type: 'string',
@@ -443,7 +443,6 @@ COMMON MISTAKES:
443
443
  1. Verify account access with list_workspace_accounts
444
444
  2. Confirm account if multiple exist
445
445
  3. Check Drive write permissions
446
- 4. Confirm deletion is intended
447
446
 
448
447
  Example Flow:
449
448
  1. Check account access
@@ -125,8 +125,6 @@ interface CopyDocumentTabArgs {
125
125
  sourceTabId?: string;
126
126
  target_tab_id?: string;
127
127
  targetTabId?: string;
128
- overwrite_existing?: boolean;
129
- overwriteExisting?: boolean;
130
128
  new_tab_title?: string;
131
129
  newTabTitle?: string;
132
130
  new_tab_parent_id?: string;
@@ -602,7 +602,6 @@ export async function handleCopyDocumentTab(args) {
602
602
  const documentId = readAliasedString(rawArgs, 'document_id', 'documentId');
603
603
  const sourceTabId = readAliasedString(rawArgs, 'source_tab_id', 'sourceTabId');
604
604
  const targetTabId = readAliasedString(rawArgs, 'target_tab_id', 'targetTabId');
605
- const overwriteExisting = readAliasedBoolean(rawArgs, 'overwrite_existing', 'overwriteExisting');
606
605
  const newTabTitle = readAliasedString(rawArgs, 'new_tab_title', 'newTabTitle');
607
606
  const newTabParentId = readAliasedString(rawArgs, 'new_tab_parent_id', 'newTabParentId');
608
607
  const newTabPosition = readAliasedNumber(rawArgs, 'new_tab_position', 'newTabPosition');
@@ -618,7 +617,6 @@ export async function handleCopyDocumentTab(args) {
618
617
  documentId: documentId,
619
618
  sourceTabId: sourceTabId,
620
619
  ...(targetTabId !== undefined ? { targetTabId } : {}),
621
- ...(overwriteExisting !== undefined ? { overwriteExisting } : {}),
622
620
  ...(newTabTitle !== undefined ? { newTabTitle } : {}),
623
621
  ...(newTabParentId !== undefined ? { newTabParentId } : {}),
624
622
  ...(newTabPosition !== undefined ? { newTabPosition } : {}),
@@ -43,7 +43,6 @@ const LEGACY_ALIASES = {
43
43
  deleteSubTabs: 'delete_sub_tabs',
44
44
  sourceTabId: 'source_tab_id',
45
45
  targetTabId: 'target_tab_id',
46
- overwriteExisting: 'overwrite_existing',
47
46
  newTabTitle: 'new_tab_title',
48
47
  newTabParentId: 'new_tab_parent_id',
49
48
  newTabPosition: 'new_tab_position',
@@ -3,8 +3,9 @@ import { createRequire } from 'node:module';
3
3
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
4
4
  import { createStdioTransport } from "./stdio-transport.js";
5
5
  import logger, { renderLogArg } from '../utils/logger.js';
6
- import { isGoogleRecoveryExhausted } from '../utils/google-retry.js';
6
+ import { isGoogleRecoveryExhausted, mayHaveWritten } from '../utils/google-retry.js';
7
7
  import { GENERIC_NEXT_STEP, classifyGoogleFailure, envelopeErrorDetail, googleFailureNextStep, hasErrorDetails, summariseGoogleError, } from '../utils/apiError.js';
8
+ import { isGoogleAuthFailure } from '../modules/accounts/unauthorized.js';
8
9
  import { CallToolRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
9
10
  const require = createRequire(import.meta.url);
10
11
  const pkg = require('../../package.json');
@@ -757,34 +758,18 @@ export class GSuiteServer {
757
758
  // the string auth codes checked below).
758
759
  const rawCode = error?.code;
759
760
  const code = typeof rawCode === 'string' ? rawCode : undefined;
760
- const status = typeof error === 'object' && error !== null
761
- ? error.response?.status
762
- ?? error.status
763
- ?? error.code
764
- : undefined;
765
- const numericStatus = typeof status === 'number'
766
- ? status
767
- : typeof status === 'string' && /^\d+$/.test(status)
768
- ? Number(status)
769
- : undefined;
770
- if (code === 'AUTH_REQUIRED' || code === 'HOST_ORCHESTRATED_AUTH_REQUIRED') {
761
+ if (code === 'AUTH_REQUIRED' || code === 'HOST_ORCHESTRATED_AUTH_REQUIRED' || isGoogleAuthFailure(error)) {
771
762
  return {
772
763
  status: 'auth_required',
773
764
  user_action: { id: 'google.connect_account' },
774
765
  agent_action: {
775
766
  instruction: "Connect Google Workspace to continue. The user will be redirected to Google's sign-in."
776
767
  },
777
- setupToolName: 'authenticate_workspace_account'
778
- };
779
- }
780
- if (numericStatus === 401) {
781
- return {
782
- status: 'auth_required',
783
- user_action: { id: 'google.connect_account' },
784
- agent_action: {
785
- instruction: "Connect Google Workspace to continue. The user will be redirected to Google's sign-in."
786
- },
787
- setupToolName: 'authenticate_workspace_account'
768
+ setupToolName: 'authenticate_workspace_account',
769
+ // The request may already have partly run: say what happened so it is checked, not repeated.
770
+ ...(mayHaveWritten(error)
771
+ ? errorDetailField(`${errorDetailText(error)} This request may already have partly run; check the result before trying it again.`)
772
+ : {})
788
773
  };
789
774
  }
790
775
  // Connector input checks: the connector's own guidance about the caller's input.
@@ -178,7 +178,6 @@ interface CopyDocumentTabArgs {
178
178
  documentId: string;
179
179
  sourceTabId: string;
180
180
  targetTabId?: string;
181
- overwriteExisting?: boolean;
182
181
  newTabTitle?: string;
183
182
  newTabParentId?: string;
184
183
  newTabPosition?: number;
@@ -654,7 +654,6 @@ export function isCopyDocumentTabArgs(args) {
654
654
  const documentId = readAliasedArg(rawParams, 'document_id', 'documentId');
655
655
  const sourceTabId = readAliasedArg(rawParams, 'source_tab_id', 'sourceTabId');
656
656
  const targetTabId = readAliasedArg(rawParams, 'target_tab_id', 'targetTabId');
657
- const overwriteExisting = readAliasedArg(rawParams, 'overwrite_existing', 'overwriteExisting');
658
657
  const newTabTitle = readAliasedArg(rawParams, 'new_tab_title', 'newTabTitle');
659
658
  const newTabParentId = readAliasedArg(rawParams, 'new_tab_parent_id', 'newTabParentId');
660
659
  const newTabPosition = readAliasedArg(rawParams, 'new_tab_position', 'newTabPosition');
@@ -663,14 +662,13 @@ export function isCopyDocumentTabArgs(args) {
663
662
  typeof documentId === 'string' &&
664
663
  typeof sourceTabId === 'string' &&
665
664
  isOptional(targetTabId, 'string') &&
666
- isOptional(overwriteExisting, 'boolean') &&
667
665
  isOptional(newTabTitle, 'string') &&
668
666
  isOptional(newTabParentId, 'string') &&
669
667
  isOptional(newTabPosition, 'number');
670
668
  }
671
669
  export function assertCopyDocumentTabArgs(args) {
672
670
  if (!isCopyDocumentTabArgs(args)) {
673
- throw new Error('Invalid copy document tab parameters. Required: document_id, source_tab_id, and either target_tab_id (with overwrite_existing: true) or new_tab_title. Optional with new_tab_title: new_tab_parent_id (string), new_tab_position (number)');
671
+ throw new Error('Invalid copy document tab parameters. Required: document_id, source_tab_id, and either target_tab_id or new_tab_title. Optional with new_tab_title: new_tab_parent_id (string), new_tab_position (number)');
674
672
  }
675
673
  }
676
674
  export function isBatchUpdateDocumentArgs(args) {
@@ -90,10 +90,10 @@ export declare function hasErrorDetails(error: unknown): error is {
90
90
  */
91
91
  export declare function isAuthHandoffError(error: unknown): boolean;
92
92
  /**
93
- * True when the server's `formatErrorResponse` owns this error's tool result: an
94
- * auth hand-off code (the `auth_required` reconnect, or a pass-through such as
95
- * `CREDENTIAL_FILE_REFUSED`) or any `AccountError`, whose `resolution` is connector
96
- * text. A handler's own result builder rethrows these instead of summarising them,
93
+ * True when the server's `formatErrorResponse` owns this error's tool result: a
94
+ * wrapped Google auth failure, an auth hand-off code (the `auth_required` reconnect,
95
+ * or a pass-through such as `CREDENTIAL_FILE_REFUSED`) or any `AccountError`, whose
96
+ * `resolution` is connector text. A handler's result builder rethrows these instead of summarising them,
97
97
  * so the resolution and the hand-off are written in one place.
98
98
  */
99
99
  export declare function isServerFormattedError(error: unknown): boolean;
@@ -3,6 +3,7 @@ import { wrapUntrustedContent } from './untrusted-controls.js';
3
3
  import { unwrapUntrusted } from './untrusted-content.js';
4
4
  import { GOOGLE_RATE_LIMIT_NEXT_STEP, LONG_WINDOW_QUOTA, errorText, isGoogleRecoveryExhausted, isShortWindowRateLimit, preserveGoogleRetryDecision, } from './google-retry.js';
5
5
  import { AccountError } from '../modules/accounts/types.js';
6
+ import { isGoogleAuthFailure } from '../modules/accounts/unauthorized.js';
6
7
  /**
7
8
  * Links `target` to the original thrown value as a non-enumerable `cause`, so
8
9
  * status and reason stay reachable (cause-walking readers) without the original
@@ -267,18 +268,18 @@ export function isAuthHandoffError(error) {
267
268
  return typeof code === 'string' && AUTH_HANDOFF_CODES.has(code);
268
269
  }
269
270
  /**
270
- * True when the server's `formatErrorResponse` owns this error's tool result: an
271
- * auth hand-off code (the `auth_required` reconnect, or a pass-through such as
272
- * `CREDENTIAL_FILE_REFUSED`) or any `AccountError`, whose `resolution` is connector
273
- * text. A handler's own result builder rethrows these instead of summarising them,
271
+ * True when the server's `formatErrorResponse` owns this error's tool result: a
272
+ * wrapped Google auth failure, an auth hand-off code (the `auth_required` reconnect,
273
+ * or a pass-through such as `CREDENTIAL_FILE_REFUSED`) or any `AccountError`, whose
274
+ * `resolution` is connector text. A handler's result builder rethrows these instead of summarising them,
274
275
  * so the resolution and the hand-off are written in one place.
275
276
  */
276
277
  export function isServerFormattedError(error) {
277
- return isAuthHandoffError(error) || error instanceof AccountError;
278
+ return isAuthHandoffError(error) || error instanceof AccountError || isGoogleAuthFailure(error);
278
279
  }
279
280
  /** Keep structured recovery decisions out of lossy string-only error results. */
280
281
  export function isPassthroughGoogleError(error) {
281
- return isAuthHandoffError(error) || isGoogleRecoveryExhausted(error) || extractHttpStatus(error) === 429 || isShortWindowRateLimit(error);
282
+ return isAuthHandoffError(error) || isGoogleAuthFailure(error) || isGoogleRecoveryExhausted(error) || extractHttpStatus(error) === 429 || isShortWindowRateLimit(error);
282
283
  }
283
284
  /**
284
285
  * Normalizes any thrown value into an error suitable for a tool handler's outer
@@ -8,6 +8,12 @@ export declare function rateLimitReason(error: unknown, status: number | undefin
8
8
  export declare function isShortWindowRateLimit(error: unknown): boolean;
9
9
  /** Only this request policy can declare a terminal retry decision. */
10
10
  export declare function isGoogleRecoveryExhausted(error: unknown): boolean;
11
+ /**
12
+ * Marks a failure from an operation that may already have changed the user's data,
13
+ * so a token renewal never re-runs it (the retry would repeat those writes).
14
+ */
15
+ export declare function markMayHaveWritten<T extends object>(target: T): T;
16
+ export declare function mayHaveWritten(error: unknown): boolean;
11
17
  export declare function preserveGoogleRetryDecision<T extends object>(target: T, cause: unknown): T;
12
18
  export declare function createGoogleRetryConfig({ sleep, random, }?: {
13
19
  sleep?: (ms: number) => Promise<void>;
@@ -1,5 +1,6 @@
1
1
  import { extractHttpStatus } from './apiError.js';
2
2
  const TERMINAL_RETRY_DECISION = Symbol.for('google-workspace.terminal-retry-decision');
3
+ const MAY_HAVE_WRITTEN = Symbol.for('google-workspace.may-have-written');
3
4
  const RETRY_METHODS = new Set(['GET', 'HEAD', 'PUT', 'OPTIONS', 'DELETE']);
4
5
  const EXTENDED_RATE_LIMIT_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
5
6
  // Google's documented exponential backoff caps at 32–64 seconds. Our 32-second
@@ -44,18 +45,34 @@ export function isShortWindowRateLimit(error) {
44
45
  }
45
46
  /** Only this request policy can declare a terminal retry decision. */
46
47
  export function isGoogleRecoveryExhausted(error) {
48
+ return hasMark(error, TERMINAL_RETRY_DECISION);
49
+ }
50
+ function hasMark(error, mark) {
47
51
  const seen = new Set();
48
52
  while (typeof error === 'object' && error !== null && !seen.has(error)) {
49
- if (error[TERMINAL_RETRY_DECISION] === true)
53
+ if (error[mark] === true)
50
54
  return true;
51
55
  seen.add(error);
52
56
  error = error.cause;
53
57
  }
54
58
  return false;
55
59
  }
60
+ /**
61
+ * Marks a failure from an operation that may already have changed the user's data,
62
+ * so a token renewal never re-runs it (the retry would repeat those writes).
63
+ */
64
+ export function markMayHaveWritten(target) {
65
+ Object.defineProperty(target, MAY_HAVE_WRITTEN, { value: true });
66
+ return target;
67
+ }
68
+ export function mayHaveWritten(error) {
69
+ return hasMark(error, MAY_HAVE_WRITTEN);
70
+ }
56
71
  export function preserveGoogleRetryDecision(target, cause) {
57
72
  if (isGoogleRecoveryExhausted(cause))
58
73
  Object.defineProperty(target, TERMINAL_RETRY_DECISION, { value: true });
74
+ if (mayHaveWritten(cause))
75
+ markMayHaveWritten(target);
59
76
  return target;
60
77
  }
61
78
  function retryAfterMs(error) {
@@ -1,14 +1,12 @@
1
1
  # cross-spawn
2
2
 
3
- [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][ci-image]][ci-url] [![Build status][appveyor-image]][appveyor-url]
3
+ [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][ci-image]][ci-url]
4
4
 
5
5
  [npm-url]:https://npmjs.org/package/cross-spawn
6
6
  [downloads-image]:https://img.shields.io/npm/dm/cross-spawn.svg
7
7
  [npm-image]:https://img.shields.io/npm/v/cross-spawn.svg
8
8
  [ci-url]:https://github.com/moxystudio/node-cross-spawn/actions/workflows/ci.yaml
9
9
  [ci-image]:https://github.com/moxystudio/node-cross-spawn/actions/workflows/ci.yaml/badge.svg
10
- [appveyor-url]:https://ci.appveyor.com/project/satazor/node-cross-spawn
11
- [appveyor-image]:https://img.shields.io/appveyor/ci/satazor/node-cross-spawn/master.svg
12
10
 
13
11
  A cross platform solution to node's spawn and spawnSync.
14
12
 
@@ -70,6 +68,24 @@ While `cross-spawn` adds support for `options.shell` in node `<v4.8`, all of its
70
68
 
71
69
  This mimics the Node.js behavior. More specifically, the command and its arguments will not be automatically escaped nor shebang support will be offered. This is by design because if you are using `options.shell` you are probably targeting a specific platform anyway and you don't want things to get into your way.
72
70
 
71
+ ### Windows argument escaping
72
+
73
+ On Unix systems arguments are passed to a new process as an array of strings, but on Windows they are passed as a single command line string and it is up to the child process to parse it back into an array. Therefore `cross-spawn` and the child process must agree on how the command line is encoded.
74
+
75
+ `cross-spawn` escapes arguments according to the conventions of the Microsoft C runtime, which most programs use, including Node.js, Python, Java and .NET. However, some programs have their own way of parsing the command line, in which case they may see a different array of arguments than the one you passed.
76
+
77
+ Commands that are not executables, such as batch files (`.bat` and `.cmd`), are run through `cmd.exe`, which uses non-standard parsing and is especially vulnerable to malicious input, as it may be used to run arbitrary commands. `cross-spawn` escapes the command and its arguments according to `cmd.exe` rules, similarly to other runtimes such as [Rust](https://doc.rust-lang.org/std/process/index.html#windows-argument-splitting). Still, due to the complexity of `cmd.exe`, there are limitations that no escaping can overcome:
78
+
79
+ - Some characters can't be escaped at all. Line breaks (`\r` and `\n`) can't be escaped and passing them results in an error being thrown.
80
+ - The command must be the name or path of a single program, with its arguments passed in `args`. The command is quoted, so `spawn('npm install')` fails with `ENOENT`, like it does on other platforms, and double quotes in it are ignored, since Windows file names can't contain them.
81
+ - Shell built-ins that run other commands, such as `call` and `start`, pass their arguments to those commands unescaped. Call the program directly instead, e.g. `spawn('tool.bat', args)` instead of `spawn('call', ['tool.bat', ...args])`.
82
+ - Batch files are assumed to forward arguments as received, e.g. with `%*`, `%1` or `"%~1"`. Batch files that use `%~1` unquoted, `call` or enable delayed expansion re-parse their arguments and may be vulnerable to malicious input.
83
+ - Programs called by batch files must follow the Microsoft C runtime conventions. Programs that don't, such as those written in Go or that use `CommandLineToArgvW`, may split arguments containing double quotes differently.
84
+
85
+ Additionally, programs that read their arguments with the legacy ANSI code page instead of Unicode may convert certain Unicode characters into others, such as `"` (U+FF02) into `"`, which changes how arguments are split. This is known as [WorstFit](https://worst.fit) and can't be mitigated by `cross-spawn`.
86
+
87
+ When passing untrusted input on Windows, validate it so that only a safe subset is allowed, and prefer calling executables directly rather than through batch files.
88
+
73
89
  ### Shebangs support
74
90
 
75
91
  While `cross-spawn` handles shebangs on Windows, its support is limited. More specifically, it just supports `#!/usr/bin/env <program>` where `<program>` must not contain any arguments.