@mindstone/mcp-server-google-workspace 0.5.11 → 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.
- package/README.md +28 -3
- package/dist/connectorRenewalClient.d.ts +162 -0
- package/dist/connectorRenewalClient.js +212 -0
- package/dist/modules/accounts/manager.js +24 -4
- package/dist/modules/accounts/oauth.js +5 -2
- package/dist/modules/accounts/token.d.ts +1 -0
- package/dist/modules/accounts/token.js +18 -8
- package/dist/modules/accounts/unauthorized.d.ts +4 -0
- package/dist/modules/accounts/unauthorized.js +46 -0
- package/dist/modules/calendar/service.js +2 -2
- package/dist/modules/docs/service.d.ts +1 -1
- package/dist/modules/docs/service.js +16 -8
- package/dist/modules/docs/types.d.ts +0 -1
- package/dist/oauth/coordinatedClient.d.ts +14 -0
- package/dist/oauth/coordinatedClient.js +103 -0
- package/dist/resources/compose-email-template.d.ts +1 -1
- package/dist/resources/compose-email-template.js +4 -0
- package/dist/tools/definitions/chat.js +1 -2
- package/dist/tools/definitions/docs.js +4 -8
- package/dist/tools/definitions/drive.js +0 -1
- package/dist/tools/docs-handlers.d.ts +0 -2
- package/dist/tools/docs-handlers.js +0 -2
- package/dist/tools/param-normalizer.js +0 -1
- package/dist/tools/server.js +8 -23
- package/dist/tools/type-guards.d.ts +0 -1
- package/dist/tools/type-guards.js +1 -3
- package/dist/utils/apiError.d.ts +4 -4
- package/dist/utils/apiError.js +7 -6
- package/dist/utils/google-retry.d.ts +6 -0
- package/dist/utils/google-retry.js +18 -1
- package/node_modules/cross-spawn/README.md +19 -3
- package/node_modules/cross-spawn/lib/parse.js +38 -10
- package/node_modules/cross-spawn/lib/util/escape.js +84 -25
- package/node_modules/cross-spawn/lib/util/readShebang.js +8 -2
- package/node_modules/cross-spawn/lib/util/resolveCommand.js +8 -1
- package/node_modules/cross-spawn/package.json +21 -24
- 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 {
|
|
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 (
|
|
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`
|
|
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
|
-
|
|
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`
|
|
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
|
-
|
|
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. */
|
|
@@ -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
|
|
@@ -13,5 +13,5 @@ export declare function buildComposeSend(draft: Record<string, unknown>): {
|
|
|
13
13
|
tool: string;
|
|
14
14
|
arguments: Record<string, unknown>;
|
|
15
15
|
};
|
|
16
|
-
export declare const COMPOSE_EMAIL_HTML = "\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <title>Compose Email</title>\n <style>\n :root {\n --bg: #ffffff;\n --panel: #ffffff;\n --border: #d9dde5;\n --text: #1f2937;\n --muted: #6b7280;\n --input-bg: #ffffff;\n --button-bg: #1f6feb;\n --button-text: #ffffff;\n --button-bg-hover: #1b63d3;\n --secondary-bg: #f3f4f6;\n --secondary-text: #1f2937;\n --secondary-border: #d1d5db;\n --error-bg: #fef2f2;\n --error-border: #fecaca;\n --error-text: #991b1b;\n --success-bg: #ecfdf5;\n --success-border: #bbf7d0;\n --success-text: #166534;\n --warning-bg: #fffbeb;\n --warning-border: #fde68a;\n --warning-text: #92400e;\n }\n\n @media (prefers-color-scheme: dark) {\n :root {\n --bg: #0f172a;\n --panel: #111827;\n --border: #334155;\n --text: #e5e7eb;\n --muted: #9ca3af;\n --input-bg: #0b1220;\n --button-bg: #3b82f6;\n --button-text: #eff6ff;\n --button-bg-hover: #2563eb;\n --secondary-bg: #1f2937;\n --secondary-text: #e5e7eb;\n --secondary-border: #374151;\n --error-bg: #2b1011;\n --error-border: #7f1d1d;\n --error-text: #fca5a5;\n --success-bg: #052e1b;\n --success-border: #166534;\n --success-text: #86efac;\n --warning-bg: #2a2106;\n --warning-border: #854d0e;\n --warning-text: #fcd34d;\n }\n }\n\n html[data-theme=\"light\"] {\n color-scheme: light;\n }\n\n html[data-theme=\"dark\"] {\n color-scheme: dark;\n --bg: #0f172a;\n --panel: #111827;\n --border: #334155;\n --text: #e5e7eb;\n --muted: #9ca3af;\n --input-bg: #0b1220;\n --button-bg: #3b82f6;\n --button-text: #eff6ff;\n --button-bg-hover: #2563eb;\n --secondary-bg: #1f2937;\n --secondary-text: #e5e7eb;\n --secondary-border: #374151;\n --error-bg: #2b1011;\n --error-border: #7f1d1d;\n --error-text: #fca5a5;\n --success-bg: #052e1b;\n --success-border: #166534;\n --success-text: #86efac;\n --warning-bg: #2a2106;\n --warning-border: #854d0e;\n --warning-text: #fcd34d;\n }\n\n * {\n box-sizing: border-box;\n }\n\n body {\n margin: 0;\n padding: 16px;\n background: var(--bg);\n color: var(--text);\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif;\n line-height: 1.4;\n }\n\n .wrapper {\n width: 100%;\n max-width: 720px;\n margin: 0 auto;\n }\n\n .card {\n background: var(--panel);\n border: 1px solid var(--border);\n border-radius: 12px;\n padding: 14px;\n display: flex;\n flex-direction: column;\n gap: 12px;\n }\n\n .field {\n display: flex;\n flex-direction: column;\n gap: 6px;\n }\n\n .field label {\n font-size: 12px;\n font-weight: 600;\n color: var(--muted);\n text-transform: uppercase;\n letter-spacing: 0.04em;\n }\n\n .from-value {\n color: var(--text);\n font-size: 14px;\n padding: 2px 0;\n word-break: break-word;\n }\n\n .from-helper {\n font-size: 12px;\n color: var(--muted);\n margin-top: 2px;\n }\n\n .input,\n .textarea {\n width: 100%;\n background: var(--input-bg);\n color: var(--text);\n border: 1px solid var(--border);\n border-radius: 8px;\n padding: 10px 12px;\n font-size: 14px;\n font-family: inherit;\n }\n\n .input:focus,\n .textarea:focus {\n outline: 2px solid rgba(59, 130, 246, 0.35);\n outline-offset: 1px;\n }\n\n .textarea {\n min-height: 180px;\n resize: vertical;\n white-space: pre-wrap;\n }\n\n .toggles {\n display: flex;\n gap: 12px;\n align-items: center;\n flex-wrap: wrap;\n }\n\n .link-button {\n border: none;\n padding: 0;\n background: none;\n color: var(--muted);\n text-decoration: underline;\n font-size: 12px;\n cursor: pointer;\n }\n\n .link-button:hover {\n color: var(--text);\n }\n\n .actions {\n display: flex;\n justify-content: flex-end;\n gap: 10px;\n margin-top: 2px;\n flex-wrap: wrap;\n }\n\n .button {\n border-radius: 8px;\n border: 1px solid transparent;\n min-height: 36px;\n padding: 0 14px;\n font-size: 13px;\n font-weight: 600;\n font-family: inherit;\n cursor: pointer;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n transition: background 120ms ease, opacity 120ms ease, border-color 120ms ease;\n }\n\n .button:disabled {\n cursor: not-allowed;\n opacity: 0.75;\n }\n\n .button-primary {\n background: var(--button-bg);\n color: var(--button-text);\n }\n\n .button-primary:hover:enabled {\n background: var(--button-bg-hover);\n }\n\n .button-secondary {\n background: var(--secondary-bg);\n color: var(--secondary-text);\n border-color: var(--secondary-border);\n }\n\n .spinner {\n width: 14px;\n height: 14px;\n border: 2px solid currentColor;\n border-right-color: transparent;\n border-radius: 50%;\n display: inline-block;\n animation: spin 700ms linear infinite;\n }\n\n @keyframes spin {\n to { transform: rotate(360deg); }\n }\n\n .status {\n border-radius: 8px;\n border: 1px solid transparent;\n padding: 8px 10px;\n font-size: 13px;\n }\n\n .error {\n background: var(--error-bg);\n border-color: var(--error-border);\n color: var(--error-text);\n display: flex;\n justify-content: space-between;\n align-items: center;\n gap: 8px;\n flex-wrap: wrap;\n }\n\n .success {\n background: var(--success-bg);\n border-color: var(--success-border);\n color: var(--success-text);\n }\n\n .warning {\n background: var(--warning-bg);\n border-color: var(--warning-border);\n color: var(--warning-text);\n display: block;\n }\n\n .warning strong {\n display: block;\n margin-bottom: 2px;\n }\n\n .warning .warning-detail {\n opacity: 0.85;\n }\n\n .blocked-actions {\n margin-top: 8px;\n }\n\n .collapsed {\n border: 1px solid var(--border);\n border-radius: 10px;\n background: var(--panel);\n padding: 10px 12px;\n display: flex;\n justify-content: space-between;\n align-items: center;\n gap: 8px;\n font-size: 13px;\n }\n\n .hidden {\n display: none !important;\n }\n\n .sent-header {\n display: flex;\n align-items: center;\n gap: 8px;\n flex-wrap: wrap;\n }\n\n .sent-badge {\n display: inline-flex;\n align-items: center;\n background: var(--success-bg);\n color: var(--success-text);\n border: 1px solid var(--success-border);\n border-radius: 999px;\n padding: 2px 10px;\n font-size: 12px;\n font-weight: 600;\n }\n\n .sent-timestamp {\n color: var(--muted);\n font-size: 12px;\n }\n\n .sent-value {\n color: var(--text);\n font-size: 14px;\n word-break: break-word;\n }\n\n .sent-body {\n color: var(--text);\n font-size: 14px;\n white-space: pre-wrap;\n word-break: break-word;\n max-height: 260px;\n overflow: auto;\n border: 1px solid var(--border);\n border-radius: 8px;\n padding: 10px 12px;\n background: var(--input-bg);\n }\n </style>\n</head>\n<body>\n <div class=\"wrapper\">\n <div id=\"collapsedState\" class=\"collapsed hidden\">\n <span id=\"collapsedMessage\">Draft collapsed.</span>\n <button id=\"reopenButton\" type=\"button\" class=\"button button-secondary\">Reopen</button>\n </div>\n\n <form id=\"composeForm\" class=\"card\" novalidate aria-label=\"Compose email\">\n <div class=\"field from-field\">\n <label>From</label>\n <span id=\"fromValue\" class=\"from-value\"></span>\n <span id=\"fromHelper\" class=\"from-helper hidden\"></span>\n </div>\n\n <div class=\"field\">\n <label for=\"toInput\">To</label>\n <input id=\"toInput\" class=\"input\" type=\"text\" autocomplete=\"off\" placeholder=\"name@example.com, team@example.com\">\n </div>\n\n <div class=\"toggles\">\n <button id=\"toggleCcButton\" type=\"button\" class=\"link-button\" aria-expanded=\"false\" aria-controls=\"ccRow\">Add CC</button>\n <button id=\"toggleBccButton\" type=\"button\" class=\"link-button\" aria-expanded=\"false\" aria-controls=\"bccRow\">Add BCC</button>\n </div>\n\n <div id=\"ccRow\" class=\"field hidden\">\n <label for=\"ccInput\">CC</label>\n <input id=\"ccInput\" class=\"input\" type=\"text\" autocomplete=\"off\" placeholder=\"cc@example.com\">\n </div>\n\n <div id=\"bccRow\" class=\"field hidden\">\n <label for=\"bccInput\">BCC</label>\n <input id=\"bccInput\" class=\"input\" type=\"text\" autocomplete=\"off\" placeholder=\"bcc@example.com\">\n </div>\n\n <div class=\"field\">\n <label for=\"subjectInput\">Subject</label>\n <input id=\"subjectInput\" class=\"input\" type=\"text\" autocomplete=\"off\" placeholder=\"Email subject\">\n </div>\n\n <div class=\"field\">\n <label for=\"bodyInput\">Body</label>\n <textarea id=\"bodyInput\" class=\"textarea\" placeholder=\"Write your email\"></textarea>\n </div>\n\n <div id=\"errorBox\" class=\"status error hidden\" role=\"alert\">\n <span id=\"errorText\"></span>\n <button id=\"retryButton\" type=\"button\" class=\"link-button\">Retry</button>\n </div>\n\n <div id=\"blockedBox\" class=\"status warning hidden\" role=\"status\" aria-live=\"polite\">\n <span id=\"blockedText\"></span>\n <div class=\"blocked-actions\">\n <button id=\"openComposeButton\" type=\"button\" class=\"button button-secondary\">Open in Gmail</button>\n </div>\n </div>\n\n <div id=\"successBox\" class=\"status success hidden\" role=\"status\" aria-live=\"polite\"></div>\n\n <div id=\"unknownBox\" class=\"status warning hidden\" role=\"status\" aria-live=\"polite\">\n <strong id=\"unknownTitle\"></strong>\n <span id=\"unknownText\" class=\"warning-detail\"></span>\n </div>\n\n <div class=\"actions\">\n <button id=\"cancelButton\" type=\"button\" class=\"button button-secondary\">Cancel</button>\n <button id=\"draftButton\" type=\"button\" class=\"button button-secondary\">\n <span id=\"draftSpinner\" class=\"spinner hidden\" aria-hidden=\"true\"></span>\n <span id=\"draftLabel\">Save draft</span>\n </button>\n <button id=\"sendButton\" type=\"button\" class=\"button button-primary\">\n <span id=\"sendSpinner\" class=\"spinner hidden\" aria-hidden=\"true\"></span>\n <span id=\"sendLabel\">Send email</span>\n </button>\n </div>\n </form>\n\n <div id=\"sentView\" class=\"card hidden\" role=\"status\" aria-live=\"polite\">\n <div class=\"sent-header\">\n <span class=\"sent-badge\">Sent</span>\n <span id=\"sentTimestamp\" class=\"sent-timestamp\"></span>\n </div>\n\n <div class=\"field\">\n <label>From</label>\n <span id=\"sentFrom\" class=\"sent-value\"></span>\n </div>\n\n <div class=\"field\">\n <label>To</label>\n <span id=\"sentTo\" class=\"sent-value\"></span>\n </div>\n\n <div id=\"sentCcField\" class=\"field hidden\">\n <label>CC</label>\n <span id=\"sentCc\" class=\"sent-value\"></span>\n </div>\n\n <div id=\"sentBccField\" class=\"field hidden\">\n <label>BCC</label>\n <span id=\"sentBcc\" class=\"sent-value\"></span>\n </div>\n\n <div class=\"field\">\n <label>Subject</label>\n <span id=\"sentSubject\" class=\"sent-value\"></span>\n </div>\n\n <div class=\"field\">\n <label>Message</label>\n <div id=\"sentBody\" class=\"sent-body\"></div>\n </div>\n\n <div class=\"actions\">\n <button id=\"openGmailButton\" type=\"button\" class=\"button button-secondary hidden\">Open in Gmail</button>\n <button id=\"sentCollapseButton\" type=\"button\" class=\"button button-secondary\">Collapse</button>\n </div>\n </div>\n </div>\n\n <script>\n (function () {\n 'use strict';\n\n var RESOURCE_URI = 'ui://google-workspace/compose-email';\n var SEND_OPTIONS = {\"sendToolName\":\"send_workspace_email\",\"fields\":{\"cc\":true,\"bcc\":true}};\n function buildSendArguments(mode, draft, options) {\n // Match input/textarea value sanitization, including an unedited prefill.\n const target = String(draft.target || '').replace(/[\\r\\n]/g, '').trim();\n const text = String(draft.text || '').replace(/\\r\\n?/g, '\\n');\n if (mode === 'slack') return { tool: options.sendToolName, arguments: {\n channel: target, text,\n } };\n if (mode === 'teams') return { tool: options.sendToolName, arguments: {\n chatId: target, content: text,\n } };\n const addresses = [draft.to, draft.cc, draft.bcc].map(value => {\n const input = Array.isArray(value) ? value.map(item => {\n if (!item || typeof item !== 'object') return String(item || '').trim();\n const email = String(item.email || item.address || item.value || '').trim();\n const name = String(item.name || item.displayName || '').trim();\n return email && name ? name + ' <' + email + '>' : email;\n }).filter(Boolean).join(', ') : typeof value === 'string' ? value : '';\n return input.replace(/[\\r\\n]/g, '').split(',').map(item => item.trim()).filter(Boolean);\n });\n const email = draft.sendEmail === undefined ? draft.email : draft.sendEmail;\n return { tool: options.sendToolName, arguments: {\n to: addresses[0],\n ...(options.fields.cc ? { cc: addresses[1] } : {}),\n ...(options.fields.bcc ? { bcc: addresses[2] } : {}),\n subject: String(draft.subject || '').replace(/[\\r\\n]/g, ''),\n body: String(draft.body || '').replace(/\\r\\n?/g, '\\n'),\n ...(options.includeAccount !== false && email ? { email } : {}),\n } };\n}\n var currentEmail = '';\n var currentSendEmail = '';\n // The host prefills the draft exactly once via ui/notifications/tool-result\n // on ready. We apply only the FIRST prefill and ignore any later ones, so a\n // stray or hostile re-post can't silently rewrite a draft the user has\n // already reviewed before clicking Send.\n var draftApplied = false;\n var baselineForm = null;\n var deferredHostOutcome = null;\n var pendingRequestId = null;\n var pendingSendPayload = null;\n // Retain across the local timeout so even a late reply clears its payload.\n var pendingSendRequestId = null;\n var sending = false;\n var hostSending = false;\n var collapsed = false;\n var sendMayHaveGone = false;\n var sent = false;\n // Which action the in-flight request belongs to ('send' | 'draft').\n // Captured before clearing on reply/timeout so the response handler can\n // route error/success correctly. retryAction survives the reply so a\n // later Retry click still knows which tool to re-invoke.\n var pendingAction = null;\n var retryAction = null;\n var sendBlocked = false;\n var persistentBlockMessage = '';\n var gmailUrl = null;\n var sendTimeoutId = null;\n // Just beyond the host-side tool-call timeout (60s) so a legitimately slow\n // send resolves to its real result first; this only fires when the reply\n // is genuinely lost, so the button can never stay stuck-silent.\n var SEND_TIMEOUT_MS = 75000;\n\n var composeForm = document.getElementById('composeForm');\n var collapsedState = document.getElementById('collapsedState');\n var collapsedMessage = document.getElementById('collapsedMessage');\n var reopenButton = document.getElementById('reopenButton');\n\n var sentView = document.getElementById('sentView');\n var sentTimestamp = document.getElementById('sentTimestamp');\n var sentFrom = document.getElementById('sentFrom');\n var sentTo = document.getElementById('sentTo');\n var sentCcField = document.getElementById('sentCcField');\n var sentCc = document.getElementById('sentCc');\n var sentBccField = document.getElementById('sentBccField');\n var sentBcc = document.getElementById('sentBcc');\n var sentSubject = document.getElementById('sentSubject');\n var sentBody = document.getElementById('sentBody');\n var openGmailButton = document.getElementById('openGmailButton');\n var sentCollapseButton = document.getElementById('sentCollapseButton');\n\n var toInput = document.getElementById('toInput');\n var ccInput = document.getElementById('ccInput');\n var bccInput = document.getElementById('bccInput');\n var subjectInput = document.getElementById('subjectInput');\n var bodyInput = document.getElementById('bodyInput');\n var fromValue = document.getElementById('fromValue');\n var fromHelper = document.getElementById('fromHelper');\n var ccRow = document.getElementById('ccRow');\n var bccRow = document.getElementById('bccRow');\n var toggleCcButton = document.getElementById('toggleCcButton');\n var toggleBccButton = document.getElementById('toggleBccButton');\n\n var sendButton = document.getElementById('sendButton');\n var sendLabel = document.getElementById('sendLabel');\n var sendSpinner = document.getElementById('sendSpinner');\n var draftButton = document.getElementById('draftButton');\n var draftLabel = document.getElementById('draftLabel');\n var draftSpinner = document.getElementById('draftSpinner');\n var cancelButton = document.getElementById('cancelButton');\n var retryButton = document.getElementById('retryButton');\n\n var errorBox = document.getElementById('errorBox');\n var errorText = document.getElementById('errorText');\n var successBox = document.getElementById('successBox');\n var unknownBox = document.getElementById('unknownBox');\n var unknownTitle = document.getElementById('unknownTitle');\n var unknownText = document.getElementById('unknownText');\n var blockedBox = document.getElementById('blockedBox');\n var blockedText = document.getElementById('blockedText');\n var openComposeButton = document.getElementById('openComposeButton');\n\n function applyThemeFromHostContext() {\n try {\n var context = window.__MCP_HOST_CONTEXT__;\n if (!context || (context.theme !== 'light' && context.theme !== 'dark')) {\n return;\n }\n document.documentElement.setAttribute('data-theme', context.theme);\n } catch (_) {\n // Ignore theme extraction errors\n }\n }\n\n function trimString(value) {\n return String(value || '').trim();\n }\n\n function applyFromValue(email) {\n var trimmed = trimString(email);\n if (trimmed) {\n fromValue.textContent = trimmed;\n fromValue.style.color = '';\n fromHelper.textContent = '';\n fromHelper.classList.add('hidden');\n } else {\n fromValue.textContent = 'Account not shown';\n fromValue.style.color = 'var(--muted)';\n fromHelper.textContent = 'Couldn\\'t confirm which email account to send from. Cancel, then ask your assistant to recreate this draft.';\n fromHelper.classList.remove('hidden');\n }\n }\n\n function formatAddressItem(item) {\n if (item && typeof item === 'object') {\n var email = trimString(item.email || item.address || item.value);\n var name = trimString(item.name || item.displayName);\n if (email && name) {\n return name + ' <' + email + '>';\n }\n return email;\n }\n return trimString(item);\n }\n\n function normalizeAddressList(value) {\n if (Array.isArray(value)) {\n return value.map(formatAddressItem).filter(Boolean);\n }\n if (typeof value === 'string') {\n return value\n .split(',')\n .map(function (item) { return trimString(item); })\n .filter(Boolean);\n }\n return [];\n }\n\n function listToInputValue(list) {\n return normalizeAddressList(list).join(', ');\n }\n\n var resizeQueued = false;\n function postResize() {\n if (resizeQueued) return;\n resizeQueued = true;\n requestAnimationFrame(function () {\n resizeQueued = false;\n var height = Math.max(\n document.documentElement.scrollHeight,\n document.body ? document.body.scrollHeight : 0\n );\n window.parent.postMessage(\n { jsonrpc: '2.0', method: 'ui/resize', params: { height: height } },\n '*'\n );\n });\n }\n\n function postReady() {\n window.parent.postMessage(\n {\n method: 'mcp-app:ready',\n params: { resourceUri: RESOURCE_URI }\n },\n '*'\n );\n }\n\n // Exactly one of the three panels is visible at a time: the editable form,\n // the read-only sent view, or the collapsed summary bar.\n function showView(view) {\n composeForm.classList.toggle('hidden', view !== 'form');\n sentView.classList.toggle('hidden', view !== 'sent');\n collapsedState.classList.toggle('hidden', view !== 'collapsed');\n postResize();\n }\n\n function setCollapsed(nextCollapsed, message) {\n collapsed = nextCollapsed;\n if (nextCollapsed) {\n collapsedMessage.textContent = message || 'Draft collapsed.';\n showView('collapsed');\n } else {\n // Expanding after a send restores the read-only sent view (never the\n // editable form) so the user can re-read what went out without any risk\n // of a duplicate send; before sending, it restores the editable form.\n showView(sent ? 'sent' : 'form');\n }\n }\n\n function setSending(nextSending) {\n // Only a host outcome can release another copy's in-flight send.\n nextSending = nextSending || hostSending;\n sending = nextSending;\n sendButton.disabled = nextSending || sendBlocked;\n retryButton.disabled = nextSending;\n draftButton.disabled = nextSending;\n cancelButton.disabled = nextSending;\n toInput.disabled = nextSending;\n ccInput.disabled = nextSending;\n bccInput.disabled = nextSending;\n subjectInput.disabled = nextSending;\n bodyInput.disabled = nextSending;\n sendSpinner.classList.toggle('hidden', !nextSending);\n sendLabel.textContent = nextSending ? 'Sending\u2026' : 'Send email';\n sendButton.setAttribute('aria-busy', nextSending ? 'true' : 'false');\n postResize();\n }\n\n // One local request is in flight at a time, but a send in another\n // copy can overlap this draft save and must keep the controls locked.\n function setSavingDraft(nextSaving) {\n sending = nextSaving;\n sendButton.disabled = nextSaving || sendBlocked;\n draftButton.disabled = nextSaving;\n cancelButton.disabled = nextSaving;\n toInput.disabled = nextSaving;\n ccInput.disabled = nextSaving;\n bccInput.disabled = nextSaving;\n subjectInput.disabled = nextSaving;\n bodyInput.disabled = nextSaving;\n sendSpinner.classList.add('hidden');\n sendLabel.textContent = 'Send email';\n sendButton.setAttribute('aria-busy', 'false');\n draftSpinner.classList.toggle('hidden', !nextSaving);\n draftLabel.textContent = nextSaving ? 'Saving\u2026' : 'Save draft';\n draftButton.setAttribute('aria-busy', nextSaving ? 'true' : 'false');\n if (hostSending) setSending(true);\n postResize();\n }\n\n function clearError() {\n if (persistentBlockMessage) {\n errorText.textContent = persistentBlockMessage;\n retryButton.classList.toggle('hidden', sendBlocked && retryAction !== 'draft');\n errorBox.classList.remove('hidden');\n postResize();\n return;\n }\n errorText.textContent = '';\n errorBox.classList.add('hidden');\n }\n\n function showError(message) {\n retryButton.classList.toggle('hidden', sendBlocked && retryAction !== 'draft');\n errorText.textContent = message || 'Failed to send email.';\n errorBox.classList.remove('hidden');\n postResize();\n }\n\n function clearSuccess() {\n successBox.textContent = '';\n successBox.classList.add('hidden');\n }\n\n function showSuccess(message) {\n successBox.textContent = message;\n successBox.classList.remove('hidden');\n postResize();\n }\n\n function clearSendTimeout() {\n if (sendTimeoutId !== null) {\n clearTimeout(sendTimeoutId);\n sendTimeoutId = null;\n }\n }\n\n function clearUnknown() {\n unknownTitle.textContent = '';\n unknownText.textContent = '';\n unknownBox.classList.add('hidden');\n errorBox.appendChild(retryButton);\n }\n\n // No reply ever came back for the send (e.g. the host's response was lost\n // before reaching this iframe). We genuinely don't know whether the email\n // went out, so we must NOT claim success or failure: re-enable the form and\n // tell the user to verify before resending (the send is not idempotent, so\n // a blind retry could send a duplicate).\n function showSendUnknown() {\n sendMayHaveGone = true;\n retryAction = null;\n clearSuccess();\n unknownTitle.textContent = 'Not sure if this sent.';\n unknownText.textContent = \"Check your Sent folder before sending again, so it doesn't go out twice.\";\n unknownBox.classList.remove('hidden');\n retryButton.classList.toggle('hidden', sendBlocked);\n if (!sendBlocked) unknownBox.appendChild(retryButton);\n postResize();\n }\n\n function handleSendTimeout() {\n sendTimeoutId = null;\n if (!pendingRequestId || sent) {\n return;\n }\n pendingRequestId = null;\n if (pendingAction === 'draft') {\n pendingAction = null;\n setSavingDraft(false);\n if (sendMayHaveGone) showSendUnknown();\n else showDraftSaveUnknown();\n return;\n }\n pendingAction = null;\n setSending(false);\n showSendUnknown();\n }\n\n // Same lost-reply honesty as a send, lower stakes: a blind retry here\n // could create a duplicate draft, so we say we're not sure and point at\n // the Drafts folder instead of offering Retry.\n function showDraftSaveUnknown() {\n clearError();\n clearSuccess();\n unknownTitle.textContent = 'Not sure if the draft was saved.';\n unknownText.textContent =\n \"Check your Drafts folder before trying again, so you don't create a duplicate.\";\n unknownBox.classList.remove('hidden');\n postResize();\n }\n\n function setCcVisible(visible) {\n ccRow.classList.toggle('hidden', !visible);\n toggleCcButton.textContent = visible ? 'Hide CC' : 'Add CC';\n toggleCcButton.setAttribute('aria-expanded', visible ? 'true' : 'false');\n }\n\n function setBccVisible(visible) {\n bccRow.classList.toggle('hidden', !visible);\n toggleBccButton.textContent = visible ? 'Hide BCC' : 'Add BCC';\n toggleBccButton.setAttribute('aria-expanded', visible ? 'true' : 'false');\n }\n\n function readFormPayload() {\n return buildSendArguments('email', {\n to: toInput.value,\n cc: ccInput.value,\n bcc: bccInput.value,\n subject: String(subjectInput.value || ''),\n body: String(bodyInput.value || ''),\n email: currentEmail, sendEmail: currentSendEmail\n }, SEND_OPTIONS).arguments;\n }\n\n function validatePayload(payload) {\n if (!payload.to || payload.to.length === 0) {\n return 'Add at least one recipient in To.';\n }\n if (!trimString(payload.subject)) {\n return 'Add a subject before sending.';\n }\n if (!trimString(payload.body)) {\n return 'Add an email body before sending.';\n }\n return null;\n }\n\n // Same provider-compatible minimum as sending (the draft tools require\n // To, Subject, and Body too) with save-specific copy. Draft is\n // email-mode only, so this body is the email shape unconditionally.\n function validateDraftPayload(payload) {\n if (!payload.to || payload.to.length === 0) {\n return 'Add at least one recipient in To.';\n }\n if (!trimString(payload.subject)) {\n return 'Add a subject before saving.';\n }\n if (!trimString(payload.body)) {\n return 'Add an email body before saving.';\n }\n return null;\n }\n\n function sendPayload(payload) {\n pendingSendPayload = payload;\n pendingRequestId = 'send-' + Date.now() + '-' + Math.random().toString(16).slice(2);\n pendingSendRequestId = pendingRequestId;\n pendingAction = 'send';\n retryAction = null;\n setSending(true);\n clearError();\n clearSuccess();\n clearUnknown();\n clearSendTimeout();\n sendTimeoutId = setTimeout(handleSendTimeout, SEND_TIMEOUT_MS);\n\n window.parent.postMessage(\n {\n jsonrpc: '2.0',\n method: 'tools/call',\n params: {\n name: 'send_workspace_email',\n _meta: { 'mcp-app/cardOutcome': 'sent' },\n arguments: payload\n },\n id: pendingRequestId\n },\n '*'\n );\n }\n\n function saveDraftPayload(payload) {\n pendingRequestId = 'draft-' + Date.now() + '-' + Math.random().toString(16).slice(2);\n pendingAction = 'draft';\n retryAction = null;\n setSavingDraft(true);\n clearError();\n clearSuccess();\n clearUnknown();\n clearSendTimeout();\n sendTimeoutId = setTimeout(handleSendTimeout, SEND_TIMEOUT_MS);\n\n window.parent.postMessage(\n {\n jsonrpc: '2.0',\n method: 'tools/call',\n params: {\n name: 'create_workspace_draft',\n arguments: payload\n },\n id: pendingRequestId\n },\n '*'\n );\n }\n\n function applyDraftData(rawDraft) {\n var draft = rawDraft && typeof rawDraft === 'object' ? rawDraft : {};\n toInput.value = listToInputValue(draft.to);\n ccInput.value = listToInputValue(draft.cc);\n bccInput.value = listToInputValue(draft.bcc);\n subjectInput.value = typeof draft.subject === 'string' ? draft.subject : '';\n bodyInput.value = typeof draft.body === 'string' ? draft.body : '';\n currentEmail = typeof draft.email === 'string' ? draft.email : '';\n currentSendEmail = draft.sendEmail === undefined ? currentEmail : draft.sendEmail;\n applyFromValue(currentEmail);\n setCcVisible(normalizeAddressList(draft.cc).length > 0);\n setBccVisible(normalizeAddressList(draft.bcc).length > 0);\n clearError();\n clearSuccess();\n postResize();\n }\n\n function getDraftFromToolResult(payload) {\n if (!payload || typeof payload !== 'object') {\n return null;\n }\n // CANONICAL: post-A0 super-mcp hoists structuredContent onto the\n // outer block; the host posts it through `params.structuredContent`.\n if (payload.structuredContent && typeof payload.structuredContent === 'object') {\n return payload.structuredContent;\n }\n // MIGRATION SHIM: pre-A0 stored sessions replayed through the\n // current iframe lack `params.structuredContent` because the outer\n // block had no hoist at capture time. Read inner envelope text \u2192\n // JSON.parse \u2192 result.structuredContent. NOT regex-based.\n //\n // Lifetime: PERMANENT defensive read-side helper. Pre-A0 sessions\n // are persisted on disk and may be replayed indefinitely; there is\n // no time-based sunset. Removing this fallback would silently break\n // pre-A0 conversation replay.\n var text = typeof payload.text === 'string' ? payload.text :\n (Array.isArray(payload.content)\n ? (payload.content.find(function (c) { return c && c.type === 'text' && typeof c.text === 'string'; }) || {}).text\n : null);\n if (typeof text !== 'string') return null;\n try {\n var parsed = JSON.parse(text);\n if (parsed && typeof parsed === 'object' && parsed.result && typeof parsed.result === 'object') {\n var inner = parsed.result;\n if (inner.structuredContent && typeof inner.structuredContent === 'object') {\n return inner.structuredContent;\n }\n }\n } catch (_) {\n // Likely-envelope heuristic: text starts with `{` and contains\n // `\"package_id\"` in the first 64 chars. If JSON.parse failed on a\n // likely-envelope, surface a warning so the developer chasing\n // \"compose form is empty on replay\" sees a signal. For non-envelope\n // text (the dominant case), no log fires.\n var prefix = text.length > 64 ? text.slice(0, 64) : text;\n var likelyEnvelope = prefix.charAt(0) === '{' && prefix.indexOf('\"package_id\"') !== -1;\n if (likelyEnvelope && typeof console !== 'undefined' && typeof console.warn === 'function') {\n console.warn('[compose-email] Migration shim: JSON.parse failed on likely super-mcp envelope; pre-fill skipped');\n }\n }\n return null;\n }\n\n function findTextBlock(blocks) {\n if (!Array.isArray(blocks)) return null;\n var block = blocks.find(function (c) {\n return c && c.type === 'text' && typeof c.text === 'string';\n });\n return block ? block.text : null;\n }\n\n // Extract the send result identifiers ({ messageId, threadId, labelIds })\n // from the tool-call reply. The connector attaches structuredContent, which\n // super-mcp hoists onto the outer block, so the fast path is a single read.\n // The envelope-unwrapping fallback keeps this robust for hosts (or replayed\n // sessions) that forward only the serialized super-mcp text envelope.\n function getSendMetaFromResult(result) {\n if (!result || typeof result !== 'object') return null;\n if (result.structuredContent && typeof result.structuredContent === 'object') {\n return result.structuredContent;\n }\n try {\n var outerText = findTextBlock(result.content);\n if (typeof outerText !== 'string' && typeof result.text === 'string') {\n outerText = result.text;\n }\n if (typeof outerText !== 'string') return null;\n var envelope = JSON.parse(outerText);\n if (!envelope || typeof envelope !== 'object') return null;\n // outerText was the connector payload directly (no super-mcp envelope).\n if (envelope.messageId || envelope.threadId) return envelope;\n var inner = envelope.result;\n if (!inner || typeof inner !== 'object') return null;\n if (inner.structuredContent && typeof inner.structuredContent === 'object') {\n return inner.structuredContent;\n }\n var innerText = findTextBlock(inner.content);\n if (typeof innerText !== 'string') return null;\n var payload = JSON.parse(innerText);\n return (payload && typeof payload === 'object') ? payload : null;\n } catch (_) {\n return null;\n }\n }\n\n // ---- Blocked-send Gmail escape hatch ----\n // Shown ONLY when the user's own choice blocks sending (the host's\n // closed 'user-disabled' reason). We\n // never call the disabled tool; instead we open a prefilled Gmail compose\n // window so the user finishes the send in Gmail (no copy-paste). This is\n // deliberately narrow: admin-disabled (\"disabled by your organization\u2026\")\n // and generic security-policy blocks show the reason without Retry,\n // because offering a Gmail bypass there would route around a control\n // the user did not set.\n //\n // Gmail compose URLs that get too long can silently fail to open, so we cap\n // the length and degrade visibly (recipients + subject only, paste the body)\n // rather than truncating without telling the user.\n var GMAIL_COMPOSE_MAX_URL = 8000;\n var BLOCKED_SEND_MESSAGE =\n \"You've blocked sending this email, so this card can't send it. You can finish and send it in Gmail instead.\";\n\n // Base URL + path are constant (code-reviewed here, never config-provided);\n // only the field VALUES vary and go through URLSearchParams, so query\n // delimiters, newlines, and reserved characters become encoded data \u2014 no\n // query injection or header splitting. The host ui/open-external-link\n // bridge re-validates the mail.google.com host before opening.\n function buildGmailComposeUrl(payload, includeBody) {\n var url = new URL('https://mail.google.com/mail/');\n var params = new URLSearchParams();\n params.set('view', 'cm');\n params.set('fs', '1');\n var to = normalizeAddressList(payload.to).join(',');\n if (to) params.set('to', to);\n var cc = normalizeAddressList(payload.cc).join(',');\n if (cc) params.set('cc', cc);\n var bcc = normalizeAddressList(payload.bcc).join(',');\n if (bcc) params.set('bcc', bcc);\n var subject = trimString(payload.subject);\n if (subject) params.set('su', subject);\n if (includeBody) {\n var body = String(payload.body || '');\n if (body) params.set('body', body);\n }\n url.search = params.toString();\n return url.toString();\n }\n\n function showBlockedSend() {\n clearError();\n clearSuccess();\n clearUnknown();\n if (sendMayHaveGone) showSendUnknown();\n sendButton.disabled = true;\n sendButton.title =\n \"You've blocked sending this email. Open it in Gmail to send it there.\";\n blockedText.textContent = BLOCKED_SEND_MESSAGE;\n blockedBox.classList.remove('hidden');\n postResize();\n }\n\n openComposeButton.addEventListener('click', function () {\n // Reset any prior \"too long\" note, then rebuild from the live form so\n // edits made after the block are reflected.\n blockedText.textContent = BLOCKED_SEND_MESSAGE;\n var payload = readFormPayload();\n var composeUrl = buildGmailComposeUrl(payload, true);\n if (composeUrl.length > GMAIL_COMPOSE_MAX_URL) {\n composeUrl = buildGmailComposeUrl(payload, false);\n if (composeUrl.length > GMAIL_COMPOSE_MAX_URL) {\n // Even without the body the link is too long (many recipients, or a\n // very long subject). Gmail would silently refuse to open it, so\n // don't pretend \u2014 tell the user and post nothing.\n blockedText.textContent =\n 'This draft is too large to open in Gmail. Use fewer recipients or a shorter subject, then click Open in Gmail.';\n postResize();\n return;\n }\n blockedText.textContent =\n 'This email is long, so Gmail will open with just the recipients and subject. Copy the message text above into Gmail before sending.';\n postResize();\n }\n window.parent.postMessage(\n { jsonrpc: '2.0', method: 'ui/open-external-link', params: { url: composeUrl } },\n '*'\n );\n });\n\n function looksLikeEmail(value) {\n var at = value.indexOf('@');\n return at > 0 && at === value.lastIndexOf('@') && value.indexOf(' ') === -1;\n }\n\n // Build a Gmail deep link to the just-sent message. The /u/<account> segment\n // targets the right inbox when the user is signed into several Google\n // accounts; #all/<id> opens the thread (falling back to the message id).\n function buildGmailUrl(meta, email) {\n if (!meta || typeof meta !== 'object') return null;\n var id = trimString(meta.threadId) || trimString(meta.messageId);\n if (!id || !/^[A-Za-z0-9_-]+$/.test(id)) return null;\n var account = trimString(email);\n var userPart = looksLikeEmail(account) ? encodeURIComponent(account) : '0';\n return 'https://mail.google.com/mail/u/' + userPart + '/#all/' + encodeURIComponent(id);\n }\n\n function formatSentTime(at) {\n if (typeof at !== 'number' || !Number.isFinite(at)) return '';\n var date = new Date(at);\n if (!Number.isFinite(date.getTime())) return '';\n try {\n return date.toLocaleString(undefined, {\n month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit'\n });\n } catch (_) {\n return '';\n }\n }\n\n function readFormState() {\n return JSON.stringify([toInput, ccInput, bccInput, subjectInput, bodyInput].map(function (element) { return element.value; }));\n }\n\n function assistantSentOriginal() {\n return !sent && draftApplied && !!deferredHostOutcome && deferredHostOutcome.by === 'agent';\n }\n\n function applyCardOutcome(o) {\n if (!draftApplied) {\n deferredHostOutcome = o && o.by === 'agent' ? o : null;\n if (deferredHostOutcome) return;\n }\n if (sent) return;\n if (pendingRequestId && pendingRequestId === pendingSendRequestId &&\n (!o || o.outcome === 'sending' || o.outcome === 'maybe-sent')) return;\n if (hostSending) {\n hostSending = false;\n setSending(false);\n if (sendMayHaveGone) showSendUnknown();\n }\n if (!o || typeof o !== 'object') return;\n if (o.outcome === 'sending') {\n hostSending = true;\n setCollapsed(false);\n setSending(true);\n clearUnknown();\n return;\n }\n if (o.outcome === 'maybe-sent') {\n showSendUnknown();\n setCollapsed(false);\n return;\n }\n if (o.outcome !== 'sent' && o.outcome !== 'submitted') return;\n if (o.by === 'agent' && readFormState() !== baselineForm) {\n deferredHostOutcome = o;\n showSuccess('Your assistant sent the original version');\n setCollapsed(false);\n return;\n }\n sent = true;\n sendMayHaveGone = false;\n clearSendTimeout();\n clearError();\n clearSuccess();\n clearUnknown();\n var stamp = formatSentTime(o.at);\n var message = o.by === 'agent' ? 'Sent by your assistant' : 'Email sent.';\n if (stamp) message = o.by === 'agent' ? message + ' \u00B7 ' + stamp : 'Email sent \u00B7 ' + stamp;\n setCollapsed(true, message);\n if (pendingSendPayload) renderSentView(pendingSendPayload, null, stamp);\n reopenButton.classList.toggle('hidden', !pendingSendPayload);\n }\n\n function renderSentView(payload, meta, stamp) {\n payload = payload && typeof payload === 'object' ? payload : {};\n sentTimestamp.textContent = stamp ? 'Sent ' + stamp : 'Sent';\n sentFrom.textContent = trimString(payload.email || currentEmail) || 'Account not shown';\n sentTo.textContent = normalizeAddressList(payload.to).join(', ');\n var ccList = normalizeAddressList(payload.cc);\n sentCc.textContent = ccList.join(', ');\n sentCcField.classList.toggle('hidden', ccList.length === 0);\n var bccList = normalizeAddressList(payload.bcc);\n sentBcc.textContent = bccList.join(', ');\n sentBccField.classList.toggle('hidden', bccList.length === 0);\n sentSubject.textContent = String(payload.subject || '');\n sentBody.textContent = String(payload.body || '');\n gmailUrl = buildGmailUrl(meta, payload.email || currentEmail);\n openGmailButton.classList.toggle('hidden', !gmailUrl);\n }\n\n function handleSendRequest() {\n if (sent) return;\n if (sending) return;\n if (sendBlocked) return;\n var payload = readFormPayload();\n var validationError = validatePayload(payload);\n if (validationError) {\n showError(validationError);\n return;\n }\n\n sendPayload(payload);\n }\n\n // The Send button is type=\"button\" with an explicit click handler rather\n // than a form submit button. The host renders this iframe with a\n // sandbox of \"allow-scripts\" only \u2014 no \"allow-forms\" \u2014 so native form\n // submission is blocked by the browser BEFORE the submit event fires\n // (\"Blocked form submission ... the form's frame is sandboxed and the\n // allow-forms permission is not set\"). A submit-driven Send therefore\n // silently did nothing: no postMessage, no spinner, no telemetry.\n // A click handler needs no sandbox permission and is the same path\n // Cancel/Retry already use. The submit listener below stays only as a\n // defensive fallback for hosts that DO grant allow-forms; in this sandbox\n // it never fires (neither the button click nor Enter routes through it).\n // The sending guard keeps any double-fire (in an allow-forms host) a no-op.\n sendButton.addEventListener('click', function () {\n handleSendRequest();\n });\n\n draftButton.addEventListener('click', function () {\n if (sending) return;\n var payload = readFormPayload();\n var validationError = validateDraftPayload(payload);\n if (validationError) {\n showError(validationError);\n return;\n }\n saveDraftPayload(payload);\n });\n\n composeForm.addEventListener('submit', function (event) {\n event.preventDefault();\n handleSendRequest();\n });\n\n retryButton.addEventListener('click', function () {\n if (sent) return;\n if (sending) return;\n if (sendBlocked && retryAction !== 'draft') return;\n var payload = readFormPayload();\n if (retryAction === 'draft') {\n var draftValidationError = validateDraftPayload(payload);\n if (draftValidationError) {\n showError(draftValidationError);\n return;\n }\n retryAction = null;\n saveDraftPayload(payload);\n return;\n }\n var validationError = validatePayload(payload);\n if (validationError) {\n showError(validationError);\n return;\n }\n sendPayload(payload);\n });\n\n cancelButton.addEventListener('click', function () {\n if (sending) return;\n // Hiding the notice does not resolve whether an earlier send went out.\n // After the assistant sent the original, \"Nothing sent\" would be untrue.\n var collapseMessage = sendMayHaveGone\n ? 'Collapsed. Check your Sent folder if you are not sure.'\n : assistantSentOriginal()\n ? 'Your assistant sent the original version. Your edits were not sent.'\n : 'Draft collapsed. Nothing sent.';\n if (!sendMayHaveGone) clearError();\n clearSuccess();\n clearUnknown();\n setCollapsed(true, collapseMessage);\n });\n\n reopenButton.addEventListener('click', function () {\n setCollapsed(false);\n if (!sent && sendMayHaveGone) showSendUnknown();\n else if (assistantSentOriginal()) showSuccess('Your assistant sent the original version');\n });\n\n sentCollapseButton.addEventListener('click', function () {\n setCollapsed(true, collapsedMessage.textContent || 'Email sent.');\n });\n\n // The iframe sandbox is \"allow-scripts\" only (no allow-popups / allow-forms),\n // so it cannot open a URL itself. Ask the host to open the Gmail link in the\n // user's browser via the ui/open-external-link bridge, which re-validates the\n // URL against its own allowlist before handing it to the OS.\n openGmailButton.addEventListener('click', function () {\n if (!gmailUrl) return;\n window.parent.postMessage(\n { jsonrpc: '2.0', method: 'ui/open-external-link', params: { url: gmailUrl } },\n '*'\n );\n });\n\n toggleCcButton.addEventListener('click', function () {\n setCcVisible(ccRow.classList.contains('hidden'));\n postResize();\n });\n\n toggleBccButton.addEventListener('click', function () {\n setBccVisible(bccRow.classList.contains('hidden'));\n postResize();\n });\n\n [toInput, ccInput, bccInput, subjectInput, bodyInput].forEach(function (element) {\n element.addEventListener('input', function () {\n if (!sendBlocked || persistentBlockMessage) clearError();\n clearSuccess();\n if (!sendMayHaveGone) clearUnknown();\n if (deferredHostOutcome && draftApplied) applyCardOutcome(deferredHostOutcome);\n postResize();\n });\n });\n\n window.addEventListener('message', function (event) {\n // Honest scope (origin-independent): the iframe sandbox origin is 'null',\n // so validating event.origin is unreliable across dev/prod/custom-scheme\n // hosts. Instead reject any *identified* sender that isn't our host frame\n // (window.parent). A real cross-frame postMessage always stamps\n // event.source with the sending window, so a hostile sibling frame is\n // rejected here; a null source only occurs for same-context synthetic\n // dispatch (our own code) and cannot be forged from outside, so we\n // tolerate it. This does not authenticate the host's identity \u2014 the host\n // separately authenticates this iframe by origin+source.\n if (event.source && event.source !== window.parent) {\n return;\n }\n\n var data = event.data;\n if (!data || typeof data !== 'object') {\n return;\n }\n\n if (data.method === 'mcp-app:card-outcome') {\n if (event.source === window.parent) applyCardOutcome(data.params);\n return;\n }\n\n if (data.method === 'ui/notifications/tool-result') {\n // Always parse (so the migration-shim's malformed-envelope warning\n // still fires), but apply only the first successful prefill: a stray\n // or hostile re-post can't silently rewrite a draft the user has\n // already reviewed.\n var draft = getDraftFromToolResult(data.params);\n if (draft && !draftApplied) {\n draftApplied = true;\n applyDraftData(draft);\n baselineForm = readFormState();\n if (deferredHostOutcome) applyCardOutcome(deferredHostOutcome);\n }\n return;\n }\n\n if (data.jsonrpc !== '2.0') return;\n var completedSendPayload = null;\n if (pendingSendRequestId && data.id === pendingSendRequestId) {\n completedSendPayload = pendingSendPayload;\n pendingSendPayload = null;\n pendingSendRequestId = null;\n }\n if (!pendingRequestId || data.id !== pendingRequestId) {\n return;\n }\n\n pendingRequestId = null;\n clearSendTimeout();\n clearUnknown();\n var completedAction = pendingAction;\n pendingAction = null;\n if (completedAction === 'draft') {\n setSavingDraft(false);\n } else {\n setSending(false);\n }\n\n if (data.error) {\n var errorMessage = data.error && typeof data.error.message === 'string'\n ? data.error.message\n : (completedAction === 'draft' ? 'Failed to save draft.' : 'Failed to send email.');\n if (completedAction === 'draft') {\n // Retry re-invokes the draft tool, not the send tool \u2014 pendingAction\n // is already cleared, so this is what the Retry handler routes on.\n retryAction = 'draft';\n }\n var blockedReason = data.error.data && data.error.data.reason;\n var retryCannotChangeBlock = blockedReason === 'user-disabled' || blockedReason === 'admin-disabled' || blockedReason === 'security-policy';\n var blockedBeforeSend = retryCannotChangeBlock || blockedReason === 'not-dispatched';\n if (completedAction !== 'draft' && retryCannotChangeBlock) {\n sendBlocked = true;\n if (blockedReason !== 'user-disabled') {\n persistentBlockMessage = errorMessage;\n }\n sendButton.disabled = true;\n }\n if (completedAction === 'draft' && sendMayHaveGone) {\n // A draft save is undeclared, so it cannot resolve an earlier send\n // uncertainty. Retry must remain a Send, never a silent draft save.\n retryAction = null;\n showSendUnknown();\n } else if (completedAction !== 'draft' && (!blockedBeforeSend || sendMayHaveGone)) {\n showSendUnknown();\n }\n\n // Only the host's closed user-disabled reason permits the Gmail\n // escape hatch; message text cannot establish why a call failed.\n // Draft failures must never open the send-only escape hatch.\n if (completedAction !== 'draft' && blockedReason === 'user-disabled') {\n showBlockedSend();\n return;\n }\n showError(errorMessage);\n return;\n }\n\n clearError();\n clearSuccess();\n if (completedAction === 'draft') {\n // Terminal: the draft now lives in the mailbox's Drafts folder.\n // Collapse to a stamped confirmation and retire the form \u2014 Reopen\n // would resurrect an editable copy whose next Save/Send silently\n // diverges from (or duplicates) the saved draft.\n var draftStamp = formatSentTime(Date.now());\n setCollapsed(true, draftStamp ? 'Draft saved \u00B7 ' + draftStamp : 'Draft saved.');\n reopenButton.classList.add('hidden');\n return;\n }\n // Preserve what was sent (and how to reach it) instead of discarding the\n // draft. completedSendPayload is the exact payload we posted; the reply carries\n // the Gmail message/thread ids. We default to the collapsed summary, but\n // Reopen now restores a read-only view of the sent message.\n var sentPayload = completedSendPayload || readFormPayload();\n var stamp = formatSentTime(Date.now());\n renderSentView(sentPayload, getSendMetaFromResult(data.result), stamp);\n sent = true;\n sendMayHaveGone = false;\n reopenButton.classList.remove('hidden');\n setCollapsed(true, stamp ? 'Email sent \u00B7 ' + stamp : 'Email sent.');\n });\n\n if (typeof ResizeObserver === 'function' && document.body) {\n var observer = new ResizeObserver(postResize);\n observer.observe(document.body);\n }\n\n applyThemeFromHostContext();\n setCcVisible(false);\n setBccVisible(false);\n var hostOutcome = (window.__MCP_HOST_CONTEXT__ || {}).cardOutcome;\n if (hostOutcome) applyCardOutcome(hostOutcome);\n else setCollapsed(false);\n postResize();\n postReady();\n\n window.parent.postMessage(\n {\n jsonrpc: '2.0',\n method: 'ui/initialize',\n params: { resourceUri: RESOURCE_URI },\n id: 'compose-email-init'\n },\n '*'\n );\n })();\n </script>\n</body>\n</html>\n";
|
|
16
|
+
export declare const COMPOSE_EMAIL_HTML = "\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <title>Compose Email</title>\n <style>\n :root {\n --bg: #ffffff;\n --panel: #ffffff;\n --border: #d9dde5;\n --text: #1f2937;\n --muted: #6b7280;\n --input-bg: #ffffff;\n --button-bg: #1f6feb;\n --button-text: #ffffff;\n --button-bg-hover: #1b63d3;\n --secondary-bg: #f3f4f6;\n --secondary-text: #1f2937;\n --secondary-border: #d1d5db;\n --error-bg: #fef2f2;\n --error-border: #fecaca;\n --error-text: #991b1b;\n --success-bg: #ecfdf5;\n --success-border: #bbf7d0;\n --success-text: #166534;\n --warning-bg: #fffbeb;\n --warning-border: #fde68a;\n --warning-text: #92400e;\n }\n\n @media (prefers-color-scheme: dark) {\n :root {\n --bg: #0f172a;\n --panel: #111827;\n --border: #334155;\n --text: #e5e7eb;\n --muted: #9ca3af;\n --input-bg: #0b1220;\n --button-bg: #3b82f6;\n --button-text: #eff6ff;\n --button-bg-hover: #2563eb;\n --secondary-bg: #1f2937;\n --secondary-text: #e5e7eb;\n --secondary-border: #374151;\n --error-bg: #2b1011;\n --error-border: #7f1d1d;\n --error-text: #fca5a5;\n --success-bg: #052e1b;\n --success-border: #166534;\n --success-text: #86efac;\n --warning-bg: #2a2106;\n --warning-border: #854d0e;\n --warning-text: #fcd34d;\n }\n }\n\n html[data-theme=\"light\"] {\n color-scheme: light;\n }\n\n html[data-theme=\"dark\"] {\n color-scheme: dark;\n --bg: #0f172a;\n --panel: #111827;\n --border: #334155;\n --text: #e5e7eb;\n --muted: #9ca3af;\n --input-bg: #0b1220;\n --button-bg: #3b82f6;\n --button-text: #eff6ff;\n --button-bg-hover: #2563eb;\n --secondary-bg: #1f2937;\n --secondary-text: #e5e7eb;\n --secondary-border: #374151;\n --error-bg: #2b1011;\n --error-border: #7f1d1d;\n --error-text: #fca5a5;\n --success-bg: #052e1b;\n --success-border: #166534;\n --success-text: #86efac;\n --warning-bg: #2a2106;\n --warning-border: #854d0e;\n --warning-text: #fcd34d;\n }\n\n * {\n box-sizing: border-box;\n }\n\n body {\n margin: 0;\n padding: 16px;\n background: var(--bg);\n color: var(--text);\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif;\n line-height: 1.4;\n }\n\n .wrapper {\n width: 100%;\n max-width: 720px;\n margin: 0 auto;\n }\n\n .card {\n background: var(--panel);\n border: 1px solid var(--border);\n border-radius: 12px;\n padding: 14px;\n display: flex;\n flex-direction: column;\n gap: 12px;\n }\n\n .field {\n display: flex;\n flex-direction: column;\n gap: 6px;\n }\n\n .field label {\n font-size: 12px;\n font-weight: 600;\n color: var(--muted);\n text-transform: uppercase;\n letter-spacing: 0.04em;\n }\n\n .from-value {\n color: var(--text);\n font-size: 14px;\n padding: 2px 0;\n word-break: break-word;\n }\n\n .from-helper {\n font-size: 12px;\n color: var(--muted);\n margin-top: 2px;\n }\n\n .input,\n .textarea {\n width: 100%;\n background: var(--input-bg);\n color: var(--text);\n border: 1px solid var(--border);\n border-radius: 8px;\n padding: 10px 12px;\n font-size: 14px;\n font-family: inherit;\n }\n\n .input:focus,\n .textarea:focus {\n outline: 2px solid rgba(59, 130, 246, 0.35);\n outline-offset: 1px;\n }\n\n .textarea {\n min-height: 180px;\n resize: vertical;\n white-space: pre-wrap;\n }\n\n .toggles {\n display: flex;\n gap: 12px;\n align-items: center;\n flex-wrap: wrap;\n }\n\n .link-button {\n border: none;\n padding: 0;\n background: none;\n color: var(--muted);\n text-decoration: underline;\n font-size: 12px;\n cursor: pointer;\n }\n\n .link-button:hover {\n color: var(--text);\n }\n\n .actions {\n display: flex;\n justify-content: flex-end;\n gap: 10px;\n margin-top: 2px;\n flex-wrap: wrap;\n }\n\n .button {\n border-radius: 8px;\n border: 1px solid transparent;\n min-height: 36px;\n padding: 0 14px;\n font-size: 13px;\n font-weight: 600;\n font-family: inherit;\n cursor: pointer;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n transition: background 120ms ease, opacity 120ms ease, border-color 120ms ease;\n }\n\n .button:disabled {\n cursor: not-allowed;\n opacity: 0.75;\n }\n\n .button-primary {\n background: var(--button-bg);\n color: var(--button-text);\n }\n\n .button-primary:hover:enabled {\n background: var(--button-bg-hover);\n }\n\n .button-secondary {\n background: var(--secondary-bg);\n color: var(--secondary-text);\n border-color: var(--secondary-border);\n }\n\n .spinner {\n width: 14px;\n height: 14px;\n border: 2px solid currentColor;\n border-right-color: transparent;\n border-radius: 50%;\n display: inline-block;\n animation: spin 700ms linear infinite;\n }\n\n @keyframes spin {\n to { transform: rotate(360deg); }\n }\n\n .status {\n border-radius: 8px;\n border: 1px solid transparent;\n padding: 8px 10px;\n font-size: 13px;\n }\n\n .error {\n background: var(--error-bg);\n border-color: var(--error-border);\n color: var(--error-text);\n display: flex;\n justify-content: space-between;\n align-items: center;\n gap: 8px;\n flex-wrap: wrap;\n }\n\n .success {\n background: var(--success-bg);\n border-color: var(--success-border);\n color: var(--success-text);\n }\n\n .warning {\n background: var(--warning-bg);\n border-color: var(--warning-border);\n color: var(--warning-text);\n display: block;\n }\n\n .warning strong {\n display: block;\n margin-bottom: 2px;\n }\n\n .warning .warning-detail {\n opacity: 0.85;\n }\n\n .blocked-actions {\n margin-top: 8px;\n }\n\n .collapsed {\n border: 1px solid var(--border);\n border-radius: 10px;\n background: var(--panel);\n padding: 10px 12px;\n display: flex;\n justify-content: space-between;\n align-items: center;\n gap: 8px;\n font-size: 13px;\n }\n\n .hidden {\n display: none !important;\n }\n\n .sent-header {\n display: flex;\n align-items: center;\n gap: 8px;\n flex-wrap: wrap;\n }\n\n .sent-badge {\n display: inline-flex;\n align-items: center;\n background: var(--success-bg);\n color: var(--success-text);\n border: 1px solid var(--success-border);\n border-radius: 999px;\n padding: 2px 10px;\n font-size: 12px;\n font-weight: 600;\n }\n\n .sent-timestamp {\n color: var(--muted);\n font-size: 12px;\n }\n\n .sent-value {\n color: var(--text);\n font-size: 14px;\n word-break: break-word;\n }\n\n .sent-body {\n color: var(--text);\n font-size: 14px;\n white-space: pre-wrap;\n word-break: break-word;\n max-height: 260px;\n overflow: auto;\n border: 1px solid var(--border);\n border-radius: 8px;\n padding: 10px 12px;\n background: var(--input-bg);\n }\n </style>\n</head>\n<body>\n <div class=\"wrapper\">\n <div id=\"collapsedState\" class=\"collapsed hidden\">\n <span id=\"collapsedMessage\">Draft collapsed.</span>\n <button id=\"reopenButton\" type=\"button\" class=\"button button-secondary\">Reopen</button>\n </div>\n\n <form id=\"composeForm\" class=\"card\" novalidate aria-label=\"Compose email\">\n <div class=\"field from-field\">\n <label>From</label>\n <span id=\"fromValue\" class=\"from-value\"></span>\n <span id=\"fromHelper\" class=\"from-helper hidden\"></span>\n </div>\n\n <div class=\"field\">\n <label for=\"toInput\">To</label>\n <input id=\"toInput\" class=\"input\" type=\"text\" autocomplete=\"off\" placeholder=\"name@example.com, team@example.com\">\n </div>\n\n <div class=\"toggles\">\n <button id=\"toggleCcButton\" type=\"button\" class=\"link-button\" aria-expanded=\"false\" aria-controls=\"ccRow\">Add CC</button>\n <button id=\"toggleBccButton\" type=\"button\" class=\"link-button\" aria-expanded=\"false\" aria-controls=\"bccRow\">Add BCC</button>\n </div>\n\n <div id=\"ccRow\" class=\"field hidden\">\n <label for=\"ccInput\">CC</label>\n <input id=\"ccInput\" class=\"input\" type=\"text\" autocomplete=\"off\" placeholder=\"cc@example.com\">\n </div>\n\n <div id=\"bccRow\" class=\"field hidden\">\n <label for=\"bccInput\">BCC</label>\n <input id=\"bccInput\" class=\"input\" type=\"text\" autocomplete=\"off\" placeholder=\"bcc@example.com\">\n </div>\n\n <div class=\"field\">\n <label for=\"subjectInput\">Subject</label>\n <input id=\"subjectInput\" class=\"input\" type=\"text\" autocomplete=\"off\" placeholder=\"Email subject\">\n </div>\n\n <div class=\"field\">\n <label for=\"bodyInput\">Body</label>\n <textarea id=\"bodyInput\" class=\"textarea\" placeholder=\"Write your email\"></textarea>\n </div>\n\n <div id=\"errorBox\" class=\"status error hidden\" role=\"alert\">\n <span id=\"errorText\"></span>\n <button id=\"retryButton\" type=\"button\" class=\"link-button\">Retry</button>\n </div>\n\n <div id=\"blockedBox\" class=\"status warning hidden\" role=\"status\" aria-live=\"polite\">\n <span id=\"blockedText\"></span>\n <div class=\"blocked-actions\">\n <button id=\"openComposeButton\" type=\"button\" class=\"button button-secondary\">Open in Gmail</button>\n </div>\n </div>\n\n <div id=\"successBox\" class=\"status success hidden\" role=\"status\" aria-live=\"polite\"></div>\n\n <div id=\"unknownBox\" class=\"status warning hidden\" role=\"status\" aria-live=\"polite\">\n <strong id=\"unknownTitle\"></strong>\n <span id=\"unknownText\" class=\"warning-detail\"></span>\n </div>\n\n <div class=\"actions\">\n <button id=\"cancelButton\" type=\"button\" class=\"button button-secondary\">Cancel</button>\n <button id=\"draftButton\" type=\"button\" class=\"button button-secondary\">\n <span id=\"draftSpinner\" class=\"spinner hidden\" aria-hidden=\"true\"></span>\n <span id=\"draftLabel\">Save draft</span>\n </button>\n <button id=\"sendButton\" type=\"button\" class=\"button button-primary\">\n <span id=\"sendSpinner\" class=\"spinner hidden\" aria-hidden=\"true\"></span>\n <span id=\"sendLabel\">Send email</span>\n </button>\n </div>\n </form>\n\n <div id=\"sentView\" class=\"card hidden\" role=\"status\" aria-live=\"polite\">\n <div class=\"sent-header\">\n <span class=\"sent-badge\">Sent</span>\n <span id=\"sentTimestamp\" class=\"sent-timestamp\"></span>\n </div>\n\n <div class=\"field\">\n <label>From</label>\n <span id=\"sentFrom\" class=\"sent-value\"></span>\n </div>\n\n <div class=\"field\">\n <label>To</label>\n <span id=\"sentTo\" class=\"sent-value\"></span>\n </div>\n\n <div id=\"sentCcField\" class=\"field hidden\">\n <label>CC</label>\n <span id=\"sentCc\" class=\"sent-value\"></span>\n </div>\n\n <div id=\"sentBccField\" class=\"field hidden\">\n <label>BCC</label>\n <span id=\"sentBcc\" class=\"sent-value\"></span>\n </div>\n\n <div class=\"field\">\n <label>Subject</label>\n <span id=\"sentSubject\" class=\"sent-value\"></span>\n </div>\n\n <div class=\"field\">\n <label>Message</label>\n <div id=\"sentBody\" class=\"sent-body\"></div>\n </div>\n\n <div class=\"actions\">\n <button id=\"openGmailButton\" type=\"button\" class=\"button button-secondary hidden\">Open in Gmail</button>\n <button id=\"sentCollapseButton\" type=\"button\" class=\"button button-secondary\">Collapse</button>\n </div>\n </div>\n </div>\n\n <script>\n (function () {\n 'use strict';\n\n var RESOURCE_URI = 'ui://google-workspace/compose-email';\n var SEND_OPTIONS = {\"sendToolName\":\"send_workspace_email\",\"fields\":{\"cc\":true,\"bcc\":true}};\n function buildSendArguments(mode, draft, options) {\n // Match input/textarea value sanitization, including an unedited prefill.\n const target = String(draft.target || '').replace(/[\\r\\n]/g, '').trim();\n const text = String(draft.text || '').replace(/\\r\\n?/g, '\\n');\n if (mode === 'slack') return { tool: options.sendToolName, arguments: {\n channel: target, text,\n } };\n if (mode === 'teams') return { tool: options.sendToolName, arguments: {\n chatId: target, content: text,\n } };\n const addresses = [draft.to, draft.cc, draft.bcc].map(value => {\n const input = Array.isArray(value) ? value.map(item => {\n if (!item || typeof item !== 'object') return String(item || '').trim();\n const email = String(item.email || item.address || item.value || '').trim();\n const name = String(item.name || item.displayName || '').trim();\n return email && name ? name + ' <' + email + '>' : email;\n }).filter(Boolean).join(', ') : typeof value === 'string' ? value : '';\n return input.replace(/[\\r\\n]/g, '').split(',').map(item => item.trim()).filter(Boolean);\n });\n const email = draft.sendEmail === undefined ? draft.email : draft.sendEmail;\n return { tool: options.sendToolName, arguments: {\n to: addresses[0],\n ...(options.fields.cc ? { cc: addresses[1] } : {}),\n ...(options.fields.bcc ? { bcc: addresses[2] } : {}),\n subject: String(draft.subject || '').replace(/[\\r\\n]/g, ''),\n body: String(draft.body || '').replace(/\\r\\n?/g, '\\n'),\n ...(options.includeAccount !== false && email ? { email } : {}),\n } };\n}\n var currentEmail = '';\n var currentSendEmail = '';\n // The host prefills the draft exactly once via ui/notifications/tool-result\n // on ready. We apply only the FIRST prefill and ignore any later ones, so a\n // stray or hostile re-post can't silently rewrite a draft the user has\n // already reviewed before clicking Send.\n var draftApplied = false;\n var baselineForm = null;\n var deferredHostOutcome = null;\n var pendingRequestId = null;\n var pendingSendPayload = null;\n // Retain across the local timeout so even a late reply clears its payload.\n var pendingSendRequestId = null;\n var sending = false;\n var hostSending = false;\n var collapsed = false;\n var sendMayHaveGone = false;\n var sent = false;\n // Which action the in-flight request belongs to ('send' | 'draft').\n // Captured before clearing on reply/timeout so the response handler can\n // route error/success correctly. retryAction survives the reply so a\n // later Retry click still knows which tool to re-invoke.\n var pendingAction = null;\n var retryAction = null;\n var sendBlocked = false;\n var persistentBlockMessage = '';\n var gmailUrl = null;\n var sendTimeoutId = null;\n // Just beyond the host-side tool-call timeout (60s) so a legitimately slow\n // send resolves to its real result first; this only fires when the reply\n // is genuinely lost, so the button can never stay stuck-silent.\n var SEND_TIMEOUT_MS = 75000;\n\n var composeForm = document.getElementById('composeForm');\n var collapsedState = document.getElementById('collapsedState');\n var collapsedMessage = document.getElementById('collapsedMessage');\n var reopenButton = document.getElementById('reopenButton');\n\n var sentView = document.getElementById('sentView');\n var sentTimestamp = document.getElementById('sentTimestamp');\n var sentFrom = document.getElementById('sentFrom');\n var sentTo = document.getElementById('sentTo');\n var sentCcField = document.getElementById('sentCcField');\n var sentCc = document.getElementById('sentCc');\n var sentBccField = document.getElementById('sentBccField');\n var sentBcc = document.getElementById('sentBcc');\n var sentSubject = document.getElementById('sentSubject');\n var sentBody = document.getElementById('sentBody');\n var openGmailButton = document.getElementById('openGmailButton');\n var sentCollapseButton = document.getElementById('sentCollapseButton');\n\n var toInput = document.getElementById('toInput');\n var ccInput = document.getElementById('ccInput');\n var bccInput = document.getElementById('bccInput');\n var subjectInput = document.getElementById('subjectInput');\n var bodyInput = document.getElementById('bodyInput');\n var fromValue = document.getElementById('fromValue');\n var fromHelper = document.getElementById('fromHelper');\n var ccRow = document.getElementById('ccRow');\n var bccRow = document.getElementById('bccRow');\n var toggleCcButton = document.getElementById('toggleCcButton');\n var toggleBccButton = document.getElementById('toggleBccButton');\n\n var sendButton = document.getElementById('sendButton');\n var sendLabel = document.getElementById('sendLabel');\n var sendSpinner = document.getElementById('sendSpinner');\n var draftButton = document.getElementById('draftButton');\n var draftLabel = document.getElementById('draftLabel');\n var draftSpinner = document.getElementById('draftSpinner');\n var cancelButton = document.getElementById('cancelButton');\n var retryButton = document.getElementById('retryButton');\n\n var errorBox = document.getElementById('errorBox');\n var errorText = document.getElementById('errorText');\n var successBox = document.getElementById('successBox');\n var unknownBox = document.getElementById('unknownBox');\n var unknownTitle = document.getElementById('unknownTitle');\n var unknownText = document.getElementById('unknownText');\n var blockedBox = document.getElementById('blockedBox');\n var blockedText = document.getElementById('blockedText');\n var openComposeButton = document.getElementById('openComposeButton');\n\n function applyThemeFromHostContext() {\n try {\n var context = window.__MCP_HOST_CONTEXT__;\n if (!context || (context.theme !== 'light' && context.theme !== 'dark')) {\n return;\n }\n document.documentElement.setAttribute('data-theme', context.theme);\n } catch (_) {\n // Ignore theme extraction errors\n }\n }\n\n function trimString(value) {\n return String(value || '').trim();\n }\n\n function applyFromValue(email) {\n var trimmed = trimString(email);\n if (trimmed) {\n fromValue.textContent = trimmed;\n fromValue.style.color = '';\n fromHelper.textContent = '';\n fromHelper.classList.add('hidden');\n } else {\n fromValue.textContent = 'Account not shown';\n fromValue.style.color = 'var(--muted)';\n fromHelper.textContent = 'Couldn\\'t confirm which email account to send from. Cancel, then ask your assistant to recreate this draft.';\n fromHelper.classList.remove('hidden');\n }\n }\n\n function formatAddressItem(item) {\n if (item && typeof item === 'object') {\n var email = trimString(item.email || item.address || item.value);\n var name = trimString(item.name || item.displayName);\n if (email && name) {\n return name + ' <' + email + '>';\n }\n return email;\n }\n return trimString(item);\n }\n\n function normalizeAddressList(value) {\n if (Array.isArray(value)) {\n return value.map(formatAddressItem).filter(Boolean);\n }\n if (typeof value === 'string') {\n return value\n .split(',')\n .map(function (item) { return trimString(item); })\n .filter(Boolean);\n }\n return [];\n }\n\n function listToInputValue(list) {\n return normalizeAddressList(list).join(', ');\n }\n\n var resizeQueued = false;\n function postResize() {\n if (resizeQueued) return;\n resizeQueued = true;\n requestAnimationFrame(function () {\n resizeQueued = false;\n var height = Math.max(\n document.documentElement.scrollHeight,\n document.body ? document.body.scrollHeight : 0\n );\n window.parent.postMessage(\n { jsonrpc: '2.0', method: 'ui/resize', params: { height: height } },\n '*'\n );\n });\n }\n\n function postReady() {\n window.parent.postMessage(\n {\n method: 'mcp-app:ready',\n params: { resourceUri: RESOURCE_URI }\n },\n '*'\n );\n }\n\n // Exactly one of the three panels is visible at a time: the editable form,\n // the read-only sent view, or the collapsed summary bar.\n function showView(view) {\n composeForm.classList.toggle('hidden', view !== 'form');\n sentView.classList.toggle('hidden', view !== 'sent');\n collapsedState.classList.toggle('hidden', view !== 'collapsed');\n postResize();\n }\n\n function setCollapsed(nextCollapsed, message) {\n collapsed = nextCollapsed;\n if (nextCollapsed) {\n collapsedMessage.textContent = message || 'Draft collapsed.';\n showView('collapsed');\n } else {\n // Expanding after a send restores the read-only sent view (never the\n // editable form) so the user can re-read what went out without any risk\n // of a duplicate send; before sending, it restores the editable form.\n showView(sent ? 'sent' : 'form');\n }\n }\n\n function setSending(nextSending) {\n // Only a host outcome can release another copy's in-flight send.\n nextSending = nextSending || hostSending;\n sending = nextSending;\n sendButton.disabled = nextSending || sendBlocked;\n retryButton.disabled = nextSending;\n draftButton.disabled = nextSending;\n cancelButton.disabled = nextSending;\n toInput.disabled = nextSending;\n ccInput.disabled = nextSending;\n bccInput.disabled = nextSending;\n subjectInput.disabled = nextSending;\n bodyInput.disabled = nextSending;\n sendSpinner.classList.toggle('hidden', !nextSending);\n sendLabel.textContent = nextSending ? 'Sending\u2026' : 'Send email';\n sendButton.setAttribute('aria-busy', nextSending ? 'true' : 'false');\n postResize();\n }\n\n // One local request is in flight at a time, but a send in another\n // copy can overlap this draft save and must keep the controls locked.\n function setSavingDraft(nextSaving) {\n sending = nextSaving;\n sendButton.disabled = nextSaving || sendBlocked;\n draftButton.disabled = nextSaving;\n cancelButton.disabled = nextSaving;\n toInput.disabled = nextSaving;\n ccInput.disabled = nextSaving;\n bccInput.disabled = nextSaving;\n subjectInput.disabled = nextSaving;\n bodyInput.disabled = nextSaving;\n sendSpinner.classList.add('hidden');\n sendLabel.textContent = 'Send email';\n sendButton.setAttribute('aria-busy', 'false');\n draftSpinner.classList.toggle('hidden', !nextSaving);\n draftLabel.textContent = nextSaving ? 'Saving\u2026' : 'Save draft';\n draftButton.setAttribute('aria-busy', nextSaving ? 'true' : 'false');\n if (hostSending) setSending(true);\n postResize();\n }\n\n function clearError() {\n if (persistentBlockMessage) {\n errorText.textContent = persistentBlockMessage;\n retryButton.classList.toggle('hidden', sendBlocked && retryAction !== 'draft');\n errorBox.classList.remove('hidden');\n postResize();\n return;\n }\n errorText.textContent = '';\n errorBox.classList.add('hidden');\n }\n\n function showError(message) {\n retryButton.classList.toggle('hidden', sendBlocked && retryAction !== 'draft');\n errorText.textContent = message || 'Failed to send email.';\n errorBox.classList.remove('hidden');\n postResize();\n }\n\n function clearSuccess() {\n successBox.textContent = '';\n successBox.classList.add('hidden');\n }\n\n function showSuccess(message) {\n successBox.textContent = message;\n successBox.classList.remove('hidden');\n postResize();\n }\n\n function clearSendTimeout() {\n if (sendTimeoutId !== null) {\n clearTimeout(sendTimeoutId);\n sendTimeoutId = null;\n }\n }\n\n function clearUnknown() {\n unknownTitle.textContent = '';\n unknownText.textContent = '';\n unknownBox.classList.add('hidden');\n errorBox.appendChild(retryButton);\n }\n\n // No reply ever came back for the send (e.g. the host's response was lost\n // before reaching this iframe). We genuinely don't know whether the email\n // went out, so we must NOT claim success or failure: re-enable the form and\n // tell the user to verify before resending (the send is not idempotent, so\n // a blind retry could send a duplicate).\n function showSendUnknown() {\n sendMayHaveGone = true;\n retryAction = null;\n clearSuccess();\n unknownTitle.textContent = 'Not sure if this sent.';\n unknownText.textContent = \"Check your Sent folder before sending again, so it doesn't go out twice.\";\n unknownBox.classList.remove('hidden');\n retryButton.classList.toggle('hidden', sendBlocked);\n if (!sendBlocked) unknownBox.appendChild(retryButton);\n postResize();\n }\n\n function handleSendTimeout() {\n sendTimeoutId = null;\n if (!pendingRequestId || sent) {\n return;\n }\n pendingRequestId = null;\n if (pendingAction === 'draft') {\n pendingAction = null;\n setSavingDraft(false);\n if (sendMayHaveGone) showSendUnknown();\n else showDraftSaveUnknown();\n return;\n }\n pendingAction = null;\n setSending(false);\n showSendUnknown();\n }\n\n // Same lost-reply honesty as a send, lower stakes: a blind retry here\n // could create a duplicate draft, so we say we're not sure and point at\n // the Drafts folder instead of offering Retry.\n function showDraftSaveUnknown() {\n clearError();\n clearSuccess();\n unknownTitle.textContent = 'Not sure if the draft was saved.';\n unknownText.textContent =\n \"Check your Drafts folder before trying again, so you don't create a duplicate.\";\n unknownBox.classList.remove('hidden');\n postResize();\n }\n\n function setCcVisible(visible) {\n ccRow.classList.toggle('hidden', !visible);\n toggleCcButton.textContent = visible ? 'Hide CC' : 'Add CC';\n toggleCcButton.setAttribute('aria-expanded', visible ? 'true' : 'false');\n }\n\n function setBccVisible(visible) {\n bccRow.classList.toggle('hidden', !visible);\n toggleBccButton.textContent = visible ? 'Hide BCC' : 'Add BCC';\n toggleBccButton.setAttribute('aria-expanded', visible ? 'true' : 'false');\n }\n\n function readFormPayload() {\n return buildSendArguments('email', {\n to: toInput.value,\n cc: ccInput.value,\n bcc: bccInput.value,\n subject: String(subjectInput.value || ''),\n body: String(bodyInput.value || ''),\n email: currentEmail, sendEmail: currentSendEmail\n }, SEND_OPTIONS).arguments;\n }\n\n function validatePayload(payload) {\n if (!payload.to || payload.to.length === 0) {\n return 'Add at least one recipient in To.';\n }\n if (!trimString(payload.subject)) {\n return 'Add a subject before sending.';\n }\n if (!trimString(payload.body)) {\n return 'Add an email body before sending.';\n }\n return null;\n }\n\n // Same provider-compatible minimum as sending (the draft tools require\n // To, Subject, and Body too) with save-specific copy. Draft is\n // email-mode only, so this body is the email shape unconditionally.\n function validateDraftPayload(payload) {\n if (!payload.to || payload.to.length === 0) {\n return 'Add at least one recipient in To.';\n }\n if (!trimString(payload.subject)) {\n return 'Add a subject before saving.';\n }\n if (!trimString(payload.body)) {\n return 'Add an email body before saving.';\n }\n return null;\n }\n\n function sendPayload(payload) {\n pendingSendPayload = payload;\n pendingRequestId = 'send-' + Date.now() + '-' + Math.random().toString(16).slice(2);\n pendingSendRequestId = pendingRequestId;\n pendingAction = 'send';\n retryAction = null;\n setSending(true);\n clearError();\n clearSuccess();\n clearUnknown();\n clearSendTimeout();\n sendTimeoutId = setTimeout(handleSendTimeout, SEND_TIMEOUT_MS);\n\n window.parent.postMessage(\n {\n jsonrpc: '2.0',\n method: 'tools/call',\n params: {\n name: 'send_workspace_email',\n _meta: { 'mcp-app/cardOutcome': 'sent' },\n arguments: payload\n },\n id: pendingRequestId\n },\n '*'\n );\n }\n\n function saveDraftPayload(payload) {\n pendingRequestId = 'draft-' + Date.now() + '-' + Math.random().toString(16).slice(2);\n pendingAction = 'draft';\n retryAction = null;\n setSavingDraft(true);\n clearError();\n clearSuccess();\n clearUnknown();\n clearSendTimeout();\n sendTimeoutId = setTimeout(handleSendTimeout, SEND_TIMEOUT_MS);\n\n window.parent.postMessage(\n {\n jsonrpc: '2.0',\n method: 'tools/call',\n params: {\n name: 'create_workspace_draft',\n arguments: payload\n },\n id: pendingRequestId\n },\n '*'\n );\n }\n\n function applyDraftData(rawDraft) {\n var draft = rawDraft && typeof rawDraft === 'object' ? rawDraft : {};\n toInput.value = listToInputValue(draft.to);\n ccInput.value = listToInputValue(draft.cc);\n bccInput.value = listToInputValue(draft.bcc);\n subjectInput.value = typeof draft.subject === 'string' ? draft.subject : '';\n bodyInput.value = typeof draft.body === 'string' ? draft.body : '';\n currentEmail = typeof draft.email === 'string' ? draft.email : '';\n currentSendEmail = draft.sendEmail === undefined ? currentEmail : draft.sendEmail;\n applyFromValue(currentEmail);\n setCcVisible(normalizeAddressList(draft.cc).length > 0);\n setBccVisible(normalizeAddressList(draft.bcc).length > 0);\n clearError();\n clearSuccess();\n postResize();\n }\n\n function getDraftFromToolResult(payload) {\n if (!payload || typeof payload !== 'object') {\n return null;\n }\n // CANONICAL: post-A0 super-mcp hoists structuredContent onto the\n // outer block; the host posts it through `params.structuredContent`.\n if (payload.structuredContent && typeof payload.structuredContent === 'object') {\n return payload.structuredContent;\n }\n // MIGRATION SHIM: pre-A0 stored sessions replayed through the\n // current iframe lack `params.structuredContent` because the outer\n // block had no hoist at capture time. Read inner envelope text \u2192\n // JSON.parse \u2192 result.structuredContent. NOT regex-based.\n //\n // Lifetime: PERMANENT defensive read-side helper. Pre-A0 sessions\n // are persisted on disk and may be replayed indefinitely; there is\n // no time-based sunset. Removing this fallback would silently break\n // pre-A0 conversation replay.\n var text = typeof payload.text === 'string' ? payload.text :\n (Array.isArray(payload.content)\n ? (payload.content.find(function (c) { return c && c.type === 'text' && typeof c.text === 'string'; }) || {}).text\n : null);\n if (typeof text !== 'string') return null;\n try {\n var parsed = JSON.parse(text);\n if (parsed && typeof parsed === 'object' && parsed.result && typeof parsed.result === 'object') {\n var inner = parsed.result;\n if (inner.structuredContent && typeof inner.structuredContent === 'object') {\n return inner.structuredContent;\n }\n }\n } catch (_) {\n // Likely-envelope heuristic: text starts with `{` and contains\n // `\"package_id\"` in the first 64 chars. If JSON.parse failed on a\n // likely-envelope, surface a warning so the developer chasing\n // \"compose form is empty on replay\" sees a signal. For non-envelope\n // text (the dominant case), no log fires.\n var prefix = text.length > 64 ? text.slice(0, 64) : text;\n var likelyEnvelope = prefix.charAt(0) === '{' && prefix.indexOf('\"package_id\"') !== -1;\n if (likelyEnvelope && typeof console !== 'undefined' && typeof console.warn === 'function') {\n console.warn('[compose-email] Migration shim: JSON.parse failed on likely super-mcp envelope; pre-fill skipped');\n }\n }\n return null;\n }\n\n function findTextBlock(blocks) {\n if (!Array.isArray(blocks)) return null;\n var block = blocks.find(function (c) {\n return c && c.type === 'text' && typeof c.text === 'string';\n });\n return block ? block.text : null;\n }\n\n // Extract the send result identifiers ({ messageId, threadId, labelIds })\n // from the tool-call reply. The connector attaches structuredContent, which\n // super-mcp hoists onto the outer block, so the fast path is a single read.\n // The envelope-unwrapping fallback keeps this robust for hosts (or replayed\n // sessions) that forward only the serialized super-mcp text envelope.\n function getSendMetaFromResult(result) {\n if (!result || typeof result !== 'object') return null;\n if (result.structuredContent && typeof result.structuredContent === 'object') {\n return result.structuredContent;\n }\n try {\n var outerText = findTextBlock(result.content);\n if (typeof outerText !== 'string' && typeof result.text === 'string') {\n outerText = result.text;\n }\n if (typeof outerText !== 'string') return null;\n var envelope = JSON.parse(outerText);\n if (!envelope || typeof envelope !== 'object') return null;\n // outerText was the connector payload directly (no super-mcp envelope).\n if (envelope.messageId || envelope.threadId) return envelope;\n var inner = envelope.result;\n if (!inner || typeof inner !== 'object') return null;\n if (inner.structuredContent && typeof inner.structuredContent === 'object') {\n return inner.structuredContent;\n }\n var innerText = findTextBlock(inner.content);\n if (typeof innerText !== 'string') return null;\n var payload = JSON.parse(innerText);\n return (payload && typeof payload === 'object') ? payload : null;\n } catch (_) {\n return null;\n }\n }\n\n // ---- Blocked-send Gmail escape hatch ----\n // Shown ONLY when the user's own choice blocks sending (the host's\n // closed 'user-disabled' reason). We\n // never call the disabled tool; instead we open a prefilled Gmail compose\n // window so the user finishes the send in Gmail (no copy-paste). This is\n // deliberately narrow: admin-disabled (\"disabled by your organization\u2026\")\n // and generic security-policy blocks show the reason without Retry,\n // because offering a Gmail bypass there would route around a control\n // the user did not set.\n //\n // Gmail compose URLs that get too long can silently fail to open, so we cap\n // the length and degrade visibly (recipients + subject only, paste the body)\n // rather than truncating without telling the user.\n var GMAIL_COMPOSE_MAX_URL = 8000;\n var BLOCKED_SEND_MESSAGE =\n \"You've blocked sending this email, so this card can't send it. You can finish and send it in Gmail instead.\";\n\n // Base URL + path are constant (code-reviewed here, never config-provided);\n // only the field VALUES vary and go through URLSearchParams, so query\n // delimiters, newlines, and reserved characters become encoded data \u2014 no\n // query injection or header splitting. The host ui/open-external-link\n // bridge re-validates the mail.google.com host before opening.\n function buildGmailComposeUrl(payload, includeBody) {\n var url = new URL('https://mail.google.com/mail/');\n var params = new URLSearchParams();\n params.set('view', 'cm');\n params.set('fs', '1');\n var to = normalizeAddressList(payload.to).join(',');\n if (to) params.set('to', to);\n var cc = normalizeAddressList(payload.cc).join(',');\n if (cc) params.set('cc', cc);\n var bcc = normalizeAddressList(payload.bcc).join(',');\n if (bcc) params.set('bcc', bcc);\n var subject = trimString(payload.subject);\n if (subject) params.set('su', subject);\n if (includeBody) {\n var body = String(payload.body || '');\n if (body) params.set('body', body);\n }\n url.search = params.toString();\n return url.toString();\n }\n\n function showBlockedSend() {\n clearError();\n clearSuccess();\n clearUnknown();\n if (sendMayHaveGone) showSendUnknown();\n sendButton.disabled = true;\n sendButton.title =\n \"You've blocked sending this email. Open it in Gmail to send it there.\";\n blockedText.textContent = BLOCKED_SEND_MESSAGE;\n blockedBox.classList.remove('hidden');\n postResize();\n }\n\n openComposeButton.addEventListener('click', function () {\n // Reset any prior \"too long\" note, then rebuild from the live form so\n // edits made after the block are reflected.\n blockedText.textContent = BLOCKED_SEND_MESSAGE;\n var payload = readFormPayload();\n var composeUrl = buildGmailComposeUrl(payload, true);\n if (composeUrl.length > GMAIL_COMPOSE_MAX_URL) {\n composeUrl = buildGmailComposeUrl(payload, false);\n if (composeUrl.length > GMAIL_COMPOSE_MAX_URL) {\n // Even without the body the link is too long (many recipients, or a\n // very long subject). Gmail would silently refuse to open it, so\n // don't pretend \u2014 tell the user and post nothing.\n blockedText.textContent =\n 'This draft is too large to open in Gmail. Use fewer recipients or a shorter subject, then click Open in Gmail.';\n postResize();\n return;\n }\n blockedText.textContent =\n 'This email is long, so Gmail will open with just the recipients and subject. Copy the message text above into Gmail before sending.';\n postResize();\n }\n window.parent.postMessage(\n { jsonrpc: '2.0', method: 'ui/open-external-link', params: { url: composeUrl } },\n '*'\n );\n });\n\n function looksLikeEmail(value) {\n var at = value.indexOf('@');\n return at > 0 && at === value.lastIndexOf('@') && value.indexOf(' ') === -1;\n }\n\n // Build a Gmail deep link to the just-sent message. The /u/<account> segment\n // targets the right inbox when the user is signed into several Google\n // accounts; #all/<id> opens the thread (falling back to the message id).\n function buildGmailUrl(meta, email) {\n if (!meta || typeof meta !== 'object') return null;\n var id = trimString(meta.threadId) || trimString(meta.messageId);\n if (!id || !/^[A-Za-z0-9_-]+$/.test(id)) return null;\n var account = trimString(email);\n var userPart = looksLikeEmail(account) ? encodeURIComponent(account) : '0';\n return 'https://mail.google.com/mail/u/' + userPart + '/#all/' + encodeURIComponent(id);\n }\n\n function formatSentTime(at) {\n if (typeof at !== 'number' || !Number.isFinite(at)) return '';\n var date = new Date(at);\n if (!Number.isFinite(date.getTime())) return '';\n try {\n return date.toLocaleString(undefined, {\n month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit'\n });\n } catch (_) {\n return '';\n }\n }\n\n function readFormState() {\n return JSON.stringify([toInput, ccInput, bccInput, subjectInput, bodyInput].map(function (element) { return element.value; }));\n }\n\n function assistantSentOriginal() {\n return !sent && draftApplied && !!deferredHostOutcome && deferredHostOutcome.by === 'agent';\n }\n\n function applyCardOutcome(o) {\n if (!draftApplied) {\n deferredHostOutcome = o && o.by === 'agent' ? o : null;\n if (deferredHostOutcome) return;\n }\n if (sent) return;\n if (pendingRequestId && pendingRequestId === pendingSendRequestId &&\n (!o || o.outcome === 'sending' || o.outcome === 'maybe-sent')) return;\n if (hostSending) {\n hostSending = false;\n setSending(false);\n if (sendMayHaveGone) showSendUnknown();\n }\n if (!o || typeof o !== 'object') return;\n if (o.outcome === 'sending') {\n hostSending = true;\n setCollapsed(false);\n setSending(true);\n clearUnknown();\n return;\n }\n if (o.outcome === 'maybe-sent') {\n showSendUnknown();\n setCollapsed(false);\n return;\n }\n if (o.outcome !== 'sent' && o.outcome !== 'submitted') return;\n if (o.by === 'agent' && readFormState() !== baselineForm) {\n deferredHostOutcome = o;\n showSuccess('Your assistant sent the original version');\n setCollapsed(false);\n return;\n }\n sent = true;\n sendMayHaveGone = false;\n clearSendTimeout();\n clearError();\n clearSuccess();\n clearUnknown();\n var stamp = formatSentTime(o.at);\n var message = o.by === 'agent' ? 'Sent by your assistant' : 'Email sent.';\n if (stamp) message = o.by === 'agent' ? message + ' \u00B7 ' + stamp : 'Email sent \u00B7 ' + stamp;\n setCollapsed(true, message);\n if (pendingSendPayload) renderSentView(pendingSendPayload, null, stamp);\n reopenButton.classList.toggle('hidden', !pendingSendPayload);\n }\n\n function renderSentView(payload, meta, stamp) {\n payload = payload && typeof payload === 'object' ? payload : {};\n sentTimestamp.textContent = stamp ? 'Sent ' + stamp : 'Sent';\n sentFrom.textContent = trimString(payload.email || currentEmail) || 'Account not shown';\n sentTo.textContent = normalizeAddressList(payload.to).join(', ');\n var ccList = normalizeAddressList(payload.cc);\n sentCc.textContent = ccList.join(', ');\n sentCcField.classList.toggle('hidden', ccList.length === 0);\n var bccList = normalizeAddressList(payload.bcc);\n sentBcc.textContent = bccList.join(', ');\n sentBccField.classList.toggle('hidden', bccList.length === 0);\n sentSubject.textContent = String(payload.subject || '');\n sentBody.textContent = String(payload.body || '');\n gmailUrl = buildGmailUrl(meta, payload.email || currentEmail);\n openGmailButton.classList.toggle('hidden', !gmailUrl);\n }\n\n function handleSendRequest() {\n if (sent) return;\n if (sending) return;\n if (sendBlocked) return;\n var payload = readFormPayload();\n var validationError = validatePayload(payload);\n if (validationError) {\n showError(validationError);\n return;\n }\n\n sendPayload(payload);\n }\n\n // The Send button is type=\"button\" with an explicit click handler rather\n // than a form submit button. The host renders this iframe with a\n // sandbox of \"allow-scripts\" only \u2014 no \"allow-forms\" \u2014 so native form\n // submission is blocked by the browser BEFORE the submit event fires\n // (\"Blocked form submission ... the form's frame is sandboxed and the\n // allow-forms permission is not set\"). A submit-driven Send therefore\n // silently did nothing: no postMessage, no spinner, no telemetry.\n // A click handler needs no sandbox permission and is the same path\n // Cancel/Retry already use. The submit listener below stays only as a\n // defensive fallback for hosts that DO grant allow-forms; in this sandbox\n // it never fires (neither the button click nor Enter routes through it).\n // The sending guard keeps any double-fire (in an allow-forms host) a no-op.\n sendButton.addEventListener('click', function () {\n handleSendRequest();\n });\n\n draftButton.addEventListener('click', function () {\n if (sending) return;\n var payload = readFormPayload();\n var validationError = validateDraftPayload(payload);\n if (validationError) {\n showError(validationError);\n return;\n }\n saveDraftPayload(payload);\n });\n\n composeForm.addEventListener('submit', function (event) {\n event.preventDefault();\n handleSendRequest();\n });\n\n retryButton.addEventListener('click', function () {\n if (sent) return;\n if (sending) return;\n if (sendBlocked && retryAction !== 'draft') return;\n var payload = readFormPayload();\n if (retryAction === 'draft') {\n var draftValidationError = validateDraftPayload(payload);\n if (draftValidationError) {\n showError(draftValidationError);\n return;\n }\n retryAction = null;\n saveDraftPayload(payload);\n return;\n }\n var validationError = validatePayload(payload);\n if (validationError) {\n showError(validationError);\n return;\n }\n sendPayload(payload);\n });\n\n cancelButton.addEventListener('click', function () {\n if (sending) return;\n // Hiding the notice does not resolve whether an earlier send went out.\n // After the assistant sent the original, \"Nothing sent\" would be untrue.\n var collapseMessage = sendMayHaveGone\n ? 'Collapsed. Check your Sent folder if you are not sure.'\n : assistantSentOriginal()\n ? 'Your assistant sent the original version. Your edits were not sent.'\n : 'Draft collapsed. Nothing sent.';\n if (!sendMayHaveGone) clearError();\n clearSuccess();\n clearUnknown();\n setCollapsed(true, collapseMessage);\n });\n\n reopenButton.addEventListener('click', function () {\n setCollapsed(false);\n if (!sent && sendMayHaveGone) showSendUnknown();\n else if (assistantSentOriginal()) showSuccess('Your assistant sent the original version');\n });\n\n sentCollapseButton.addEventListener('click', function () {\n setCollapsed(true, collapsedMessage.textContent || 'Email sent.');\n });\n\n // The iframe sandbox is \"allow-scripts\" only (no allow-popups / allow-forms),\n // so it cannot open a URL itself. Ask the host to open the Gmail link in the\n // user's browser via the ui/open-external-link bridge, which re-validates the\n // URL against its own allowlist before handing it to the OS.\n openGmailButton.addEventListener('click', function () {\n if (!gmailUrl) return;\n window.parent.postMessage(\n { jsonrpc: '2.0', method: 'ui/open-external-link', params: { url: gmailUrl } },\n '*'\n );\n });\n\n toggleCcButton.addEventListener('click', function () {\n setCcVisible(ccRow.classList.contains('hidden'));\n postResize();\n });\n\n toggleBccButton.addEventListener('click', function () {\n setBccVisible(bccRow.classList.contains('hidden'));\n postResize();\n });\n\n [toInput, ccInput, bccInput, subjectInput, bodyInput].forEach(function (element) {\n element.addEventListener('input', function () {\n if (!sendBlocked || persistentBlockMessage) clearError();\n clearSuccess();\n if (!sendMayHaveGone) clearUnknown();\n if (deferredHostOutcome && draftApplied) applyCardOutcome(deferredHostOutcome);\n var edit = readFormPayload();\n window.parent.postMessage({ method: 'mcp-app:compose-edit', params: {\n to: edit.to, cc: edit.cc || [], bcc: edit.bcc || [], subject: edit.subject, body: edit.body\n } }, '*');\n postResize();\n });\n });\n\n window.addEventListener('message', function (event) {\n // Honest scope (origin-independent): the iframe sandbox origin is 'null',\n // so validating event.origin is unreliable across dev/prod/custom-scheme\n // hosts. Instead reject any *identified* sender that isn't our host frame\n // (window.parent). A real cross-frame postMessage always stamps\n // event.source with the sending window, so a hostile sibling frame is\n // rejected here; a null source only occurs for same-context synthetic\n // dispatch (our own code) and cannot be forged from outside, so we\n // tolerate it. This does not authenticate the host's identity \u2014 the host\n // separately authenticates this iframe by origin+source.\n if (event.source && event.source !== window.parent) {\n return;\n }\n\n var data = event.data;\n if (!data || typeof data !== 'object') {\n return;\n }\n\n if (data.method === 'mcp-app:card-outcome') {\n if (event.source === window.parent) applyCardOutcome(data.params);\n return;\n }\n\n if (data.method === 'ui/notifications/tool-result') {\n // Always parse (so the migration-shim's malformed-envelope warning\n // still fires), but apply only the first successful prefill: a stray\n // or hostile re-post can't silently rewrite a draft the user has\n // already reviewed.\n var draft = getDraftFromToolResult(data.params);\n if (draft && !draftApplied) {\n draftApplied = true;\n applyDraftData(draft);\n baselineForm = readFormState();\n if (deferredHostOutcome) applyCardOutcome(deferredHostOutcome);\n }\n return;\n }\n\n if (data.jsonrpc !== '2.0') return;\n var completedSendPayload = null;\n if (pendingSendRequestId && data.id === pendingSendRequestId) {\n completedSendPayload = pendingSendPayload;\n pendingSendPayload = null;\n pendingSendRequestId = null;\n }\n if (!pendingRequestId || data.id !== pendingRequestId) {\n return;\n }\n\n pendingRequestId = null;\n clearSendTimeout();\n clearUnknown();\n var completedAction = pendingAction;\n pendingAction = null;\n if (completedAction === 'draft') {\n setSavingDraft(false);\n } else {\n setSending(false);\n }\n\n if (data.error) {\n var errorMessage = data.error && typeof data.error.message === 'string'\n ? data.error.message\n : (completedAction === 'draft' ? 'Failed to save draft.' : 'Failed to send email.');\n if (completedAction === 'draft') {\n // Retry re-invokes the draft tool, not the send tool \u2014 pendingAction\n // is already cleared, so this is what the Retry handler routes on.\n retryAction = 'draft';\n }\n var blockedReason = data.error.data && data.error.data.reason;\n var retryCannotChangeBlock = blockedReason === 'user-disabled' || blockedReason === 'admin-disabled' || blockedReason === 'security-policy';\n var blockedBeforeSend = retryCannotChangeBlock || blockedReason === 'not-dispatched';\n if (completedAction !== 'draft' && retryCannotChangeBlock) {\n sendBlocked = true;\n if (blockedReason !== 'user-disabled') {\n persistentBlockMessage = errorMessage;\n }\n sendButton.disabled = true;\n }\n if (completedAction === 'draft' && sendMayHaveGone) {\n // A draft save is undeclared, so it cannot resolve an earlier send\n // uncertainty. Retry must remain a Send, never a silent draft save.\n retryAction = null;\n showSendUnknown();\n } else if (completedAction !== 'draft' && (!blockedBeforeSend || sendMayHaveGone)) {\n showSendUnknown();\n }\n\n // Only the host's closed user-disabled reason permits the Gmail\n // escape hatch; message text cannot establish why a call failed.\n // Draft failures must never open the send-only escape hatch.\n if (completedAction !== 'draft' && blockedReason === 'user-disabled') {\n showBlockedSend();\n return;\n }\n showError(errorMessage);\n return;\n }\n\n clearError();\n clearSuccess();\n if (completedAction === 'draft') {\n // Terminal: the draft now lives in the mailbox's Drafts folder.\n // Collapse to a stamped confirmation and retire the form \u2014 Reopen\n // would resurrect an editable copy whose next Save/Send silently\n // diverges from (or duplicates) the saved draft.\n var draftStamp = formatSentTime(Date.now());\n setCollapsed(true, draftStamp ? 'Draft saved \u00B7 ' + draftStamp : 'Draft saved.');\n reopenButton.classList.add('hidden');\n return;\n }\n // Preserve what was sent (and how to reach it) instead of discarding the\n // draft. completedSendPayload is the exact payload we posted; the reply carries\n // the Gmail message/thread ids. We default to the collapsed summary, but\n // Reopen now restores a read-only view of the sent message.\n var sentPayload = completedSendPayload || readFormPayload();\n var stamp = formatSentTime(Date.now());\n renderSentView(sentPayload, getSendMetaFromResult(data.result), stamp);\n sent = true;\n sendMayHaveGone = false;\n reopenButton.classList.remove('hidden');\n setCollapsed(true, stamp ? 'Email sent \u00B7 ' + stamp : 'Email sent.');\n });\n\n if (typeof ResizeObserver === 'function' && document.body) {\n var observer = new ResizeObserver(postResize);\n observer.observe(document.body);\n }\n\n applyThemeFromHostContext();\n setCcVisible(false);\n setBccVisible(false);\n var hostOutcome = (window.__MCP_HOST_CONTEXT__ || {}).cardOutcome;\n if (hostOutcome) applyCardOutcome(hostOutcome);\n else setCollapsed(false);\n postResize();\n postReady();\n\n window.parent.postMessage(\n {\n jsonrpc: '2.0',\n method: 'ui/initialize',\n params: { resourceUri: RESOURCE_URI },\n id: 'compose-email-init'\n },\n '*'\n );\n })();\n </script>\n</body>\n</html>\n";
|
|
17
17
|
//# sourceMappingURL=compose-email-template.d.ts.map
|
|
@@ -1381,6 +1381,10 @@ export const COMPOSE_EMAIL_HTML = `
|
|
|
1381
1381
|
clearSuccess();
|
|
1382
1382
|
if (!sendMayHaveGone) clearUnknown();
|
|
1383
1383
|
if (deferredHostOutcome && draftApplied) applyCardOutcome(deferredHostOutcome);
|
|
1384
|
+
var edit = readFormPayload();
|
|
1385
|
+
window.parent.postMessage({ method: 'mcp-app:compose-edit', params: {
|
|
1386
|
+
to: edit.to, cc: edit.cc || [], bcc: edit.bcc || [], subject: edit.subject, body: edit.body
|
|
1387
|
+
} }, '*');
|
|
1384
1388
|
postResize();
|
|
1385
1389
|
});
|
|
1386
1390
|
});
|
|
@@ -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.
|
|
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
|
|
734
|
-
|
|
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"
|
|
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
|
|
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',
|