@egdesk/next-api-plugin 1.5.55 → 1.5.57

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 CHANGED
@@ -116,7 +116,21 @@ export const VISITOR_AUTH = {
116
116
  };
117
117
  ```
118
118
 
119
- `NEXT_PUBLIC_EGDESK_VISITOR_SCOPES=basic|workspace` overrides that file. EGDesk allowlists scopes server-side; unknown Google APIs are dropped. Older helpers that send no scopes still get workspace (previous default).
119
+ `NEXT_PUBLIC_EGDESK_VISITOR_SCOPES=basic|workspace` overrides that file. You can also pass any Google scopes to `startVisitorGoogleLogin({ scopes })`. Identity scopes are always included. Older helpers that send no scopes still get workspace (previous default).
120
+
121
+ To use those visitor credentials on Workspace MCP (Sheets / Drive / Docs / Slides / Gmail / Apps Script), pass `{ asVisitor: true }` to the helper. Owner credentials stay the default.
122
+
123
+ ```typescript
124
+ import { callSheetsTool, getSheetRange } from './egdesk-helpers';
125
+
126
+ // Owner EGDesk credentials (default)
127
+ await getSheetRange(spreadsheetId, 'Sheet1!A1:B2');
128
+
129
+ // Website visitor from startVisitorGoogleLogin()
130
+ await callSheetsTool('sheets_get_range', { spreadsheetId, range: 'Sheet1!A1:B2' }, { asVisitor: true });
131
+ ```
132
+
133
+ Watch / sync / `drive_auth_login` stay owner-only even with `asVisitor`.
120
134
 
121
135
  ### Custom Setup
122
136
 
@@ -214,10 +228,10 @@ getVisitorSheetRange(spreadsheetId, range)
214
228
 
215
229
  | Who | Helper | Identity |
216
230
  |-----|--------|----------|
217
- | EGDesk owner | `startDriveAuthLogin()` | Owner token for this machine’s MCP (Drive watch, sync) |
218
- | Website visitor | `startVisitorGoogleLogin()` from `egdesk-visitor-google.ts` | EGDesk Auth user (login brokered by EGDesk; opaque session bound to this site origin) |
231
+ | EGDesk owner | `startDriveAuthLogin()` / `callSheetsTool()` (default) | Owner token for this machine’s MCP (Drive watch, sync) |
232
+ | Website visitor | `startVisitorGoogleLogin()` then `callSheetsTool(..., { asVisitor: true })` | Opaque visitor session (brokered by EGDesk; bound to this site origin) |
219
233
 
220
- Visitors **are** EGDesk Auth users. They are not the MCP owner. The published site never holds Supabase credentials; RLS still limits each user to their own token row on EGDesk.
234
+ Visitors **are** EGDesk Auth users. They are not the MCP owner unless you opt in with `asVisitor`. The published site never holds Supabase credentials or Google tokens.
221
235
 
222
236
  ### Configuration Types
223
237
 
@@ -211,6 +211,76 @@ function buildServerEgdeskHeaders(): Record<string, string> {
211
211
  return headers;
212
212
  }
213
213
 
214
+ const VISITOR_SESSION_KEY = 'egdesk_visitor_session';
215
+
216
+ export type WorkspaceVisitorCallOptions = {
217
+ asVisitor?: boolean;
218
+ visitorSessionId?: string;
219
+ };
220
+
221
+ function getBrowserVisitorSessionId(): string | null {
222
+ if (typeof window === 'undefined') return null;
223
+ return window.localStorage.getItem(VISITOR_SESSION_KEY);
224
+ }
225
+
226
+ function buildWorkspaceVisitorHeaders(options: WorkspaceVisitorCallOptions = {}): Record<string, string> {
227
+ const headers: Record<string, string> = {};
228
+ if (!options.asVisitor) return headers;
229
+ const sessionId = options.visitorSessionId || getBrowserVisitorSessionId();
230
+ if (!sessionId) {
231
+ throw new Error(
232
+ 'asVisitor is set but no visitor session is available. Call startVisitorGoogleLogin() first, or pass visitorSessionId on the server.',
233
+ );
234
+ }
235
+ headers['Authorization'] = \`Bearer \${sessionId}\`;
236
+ headers['X-EGDesk-As-Visitor'] = 'true';
237
+ if (typeof window !== 'undefined') {
238
+ headers['X-Visitor-Origin'] = window.location.origin;
239
+ }
240
+ return headers;
241
+ }
242
+
243
+ function withVisitorToolArgs(
244
+ args: Record<string, any>,
245
+ options: WorkspaceVisitorCallOptions = {},
246
+ ): Record<string, any> {
247
+ if (!options.asVisitor) return args;
248
+ return { ...args, asVisitor: true };
249
+ }
250
+
251
+ async function callWorkspaceMcpTool(
252
+ path: string,
253
+ proxyPath: string,
254
+ toolName: string,
255
+ args: Record<string, any> = {},
256
+ options: WorkspaceVisitorCallOptions = {},
257
+ ): Promise<any> {
258
+ const body = JSON.stringify({
259
+ tool: toolName,
260
+ arguments: withVisitorToolArgs(args, options),
261
+ });
262
+ const isServer = typeof window === 'undefined';
263
+ const visitorHeaders = buildWorkspaceVisitorHeaders(options);
264
+ let response: Response;
265
+ if (isServer) {
266
+ const apiUrl =
267
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
268
+ EGDESK_CONFIG.apiUrl;
269
+ response = await fetch(\`\${apiUrl}\${path}\`, {
270
+ method: 'POST',
271
+ headers: { ...buildServerEgdeskHeaders(), ...visitorHeaders },
272
+ body,
273
+ });
274
+ } else {
275
+ response = await apiFetch(proxyPath, {
276
+ method: 'POST',
277
+ headers: { 'Content-Type': 'application/json', ...visitorHeaders },
278
+ body,
279
+ });
280
+ }
281
+ return parseEgdeskMcpToolResponse(response);
282
+ }
283
+
214
284
  /**
215
285
  * Parse EGDesk MCP \`/tools/call\` JSON so \`error\` is shown even when HTTP status is 500.
216
286
  */
@@ -2842,6 +2912,10 @@ export type AiCallerCallOptions = {
2842
2912
  keyName?: ${(options.apiKeyNames ?? []).length > 0
2843
2913
  ? (options.apiKeyNames.map(n => `'${n}'`).join(' | ') + ' | (string & {})')
2844
2914
  : 'string'};
2915
+ /** standard = default. flex = 50% cheaper, slower/sheddable. priority = more expensive. */
2916
+ serviceTier?: 'standard' | 'flex' | 'priority';
2917
+ /** Explicit cache name from createAiCallerCache (cachedContents/...). */
2918
+ cachedContent?: string;
2845
2919
  };
2846
2920
 
2847
2921
  export type AiCallerModelDetails = {
@@ -2888,6 +2962,8 @@ export type AiCallerCallResult = {
2888
2962
  apiKey: { name: string; id: string | null } | null;
2889
2963
  attachments: AiCallerAttachmentsSummary;
2890
2964
  logId: string;
2965
+ serviceTier: 'standard' | 'flex' | 'priority';
2966
+ cachedContent: string | null;
2891
2967
  };
2892
2968
 
2893
2969
  /**
@@ -2924,6 +3000,8 @@ export type AiCallerGenerateImageOptions = {
2924
3000
  keyName?: ${(options.apiKeyNames ?? []).length > 0
2925
3001
  ? (options.apiKeyNames.map(n => `'${n}'`).join(' | ') + ' | (string & {})')
2926
3002
  : 'string'};
3003
+ /** standard = default. flex = 50% cheaper, slower/sheddable. */
3004
+ serviceTier?: 'standard' | 'flex' | 'priority';
2927
3005
  };
2928
3006
 
2929
3007
  export type AiCallerGeneratedImage = {
@@ -3001,6 +3079,86 @@ export async function listAiCallerModels(): Promise<AiCallerModelsResult> {
3001
3079
  return callAiCallerTool('ai_caller_list_models', {});
3002
3080
  }
3003
3081
 
3082
+ export type AiCallerBatchRequest = {
3083
+ key?: string;
3084
+ prompt?: string;
3085
+ systemPrompt?: string;
3086
+ temperature?: number;
3087
+ maxOutputTokens?: number;
3088
+ responseSchema?: Record<string, any>;
3089
+ tools?: Array<Record<string, any>>;
3090
+ toolConfig?: AiCallerCallOptions['toolConfig'];
3091
+ cachedContent?: string;
3092
+ images?: string[];
3093
+ filePaths?: string[];
3094
+ files?: AiCallerCallOptions['files'];
3095
+ };
3096
+
3097
+ export type AiCallerBatchSubmitOptions = {
3098
+ model?: string;
3099
+ displayName?: string;
3100
+ caller?: string;
3101
+ keyName?: ${(options.apiKeyNames ?? []).length > 0
3102
+ ? (options.apiKeyNames.map(n => `'${n}'`).join(' | ') + ' | (string & {})')
3103
+ : 'string'};
3104
+ };
3105
+
3106
+ /** Submit an async Gemini Batch job (50% of standard price). Poll with getAiCallerBatch. */
3107
+ export async function submitAiCallerBatch(
3108
+ requests: AiCallerBatchRequest[],
3109
+ options: AiCallerBatchSubmitOptions = {}
3110
+ ) {
3111
+ return callAiCallerTool('ai_caller_batch_submit', { requests, ...options });
3112
+ }
3113
+
3114
+ /** Get a Gemini Batch job. Set waitMs to poll up to 120s per call. */
3115
+ export async function getAiCallerBatch(
3116
+ name: string,
3117
+ options: { includeResults?: boolean; waitMs?: number; pollIntervalMs?: number; keyName?: string } = {}
3118
+ ) {
3119
+ return callAiCallerTool('ai_caller_batch_get', { name, ...options });
3120
+ }
3121
+
3122
+ export async function listAiCallerBatches(options: { pageSize?: number; pageToken?: string; keyName?: string } = {}) {
3123
+ return callAiCallerTool('ai_caller_batch_list', options);
3124
+ }
3125
+
3126
+ export async function cancelAiCallerBatch(name: string, options: { keyName?: string } = {}) {
3127
+ return callAiCallerTool('ai_caller_batch_cancel', { name, ...options });
3128
+ }
3129
+
3130
+ export type AiCallerCacheCreateOptions = {
3131
+ prompt?: string;
3132
+ systemPrompt?: string;
3133
+ model?: string;
3134
+ displayName?: string;
3135
+ ttl?: string | number;
3136
+ images?: string[];
3137
+ filePaths?: string[];
3138
+ files?: AiCallerCallOptions['files'];
3139
+ caller?: string;
3140
+ keyName?: ${(options.apiKeyNames ?? []).length > 0
3141
+ ? (options.apiKeyNames.map(n => `'${n}'`).join(' | ') + ' | (string & {})')
3142
+ : 'string'};
3143
+ };
3144
+
3145
+ /** Create an explicit Gemini context cache. Pass the returned name as cachedContent on later calls. */
3146
+ export async function createAiCallerCache(options: AiCallerCacheCreateOptions = {}) {
3147
+ return callAiCallerTool('ai_caller_cache_create', options);
3148
+ }
3149
+
3150
+ export async function listAiCallerCaches(options: { pageSize?: number; pageToken?: string; keyName?: string } = {}) {
3151
+ return callAiCallerTool('ai_caller_cache_list', options);
3152
+ }
3153
+
3154
+ export async function getAiCallerCache(name: string, options: { keyName?: string } = {}) {
3155
+ return callAiCallerTool('ai_caller_cache_get', { name, ...options });
3156
+ }
3157
+
3158
+ export async function deleteAiCallerCache(name: string, options: { keyName?: string } = {}) {
3159
+ return callAiCallerTool('ai_caller_cache_delete', { name, ...options });
3160
+ }
3161
+
3004
3162
  // ==========================================
3005
3163
  // PageIndex (MCP) — PDF RAG
3006
3164
  // ==========================================
@@ -3080,10 +3238,9 @@ export async function deletePageIndexDocument(docId: string) {
3080
3238
  * Call EGDesk Drive MCP tool (Google Drive change notifications + poll).
3081
3239
  *
3082
3240
  * Owner MCP auth on EGDesk: GOOGLE_SERVICE_ACCOUNT_JSON or Google Workspace sign-in
3083
- * via startDriveAuthLogin() — configures THIS EGDesk instance, not website visitors.
3084
- * Website visitors should use startVisitorGoogleLogin({ scopes }) from egdesk-visitor-google.ts
3085
- * (EGDesk brokers Auth; the site never receives Supabase keys).
3086
- * Share target folders with the service account when using SA credentials.
3241
+ * via startDriveAuthLogin() — configures THIS EGDesk instance.
3242
+ * Pass { asVisitor: true } to act as the website visitor from startVisitorGoogleLogin().
3243
+ * Watch / sync / drive_auth_login stay owner-only even with asVisitor.
3087
3244
  *
3088
3245
  * - Server: \`POST {apiUrl}/drive/tools/call\`
3089
3246
  * - Client: \`POST /__drive_proxy\` (see proxy.ts / middleware)
@@ -3091,31 +3248,10 @@ export async function deletePageIndexDocument(docId: string) {
3091
3248
  */
3092
3249
  export async function callDriveTool(
3093
3250
  toolName: string,
3094
- args: Record<string, any> = {}
3251
+ args: Record<string, any> = {},
3252
+ options: WorkspaceVisitorCallOptions = {},
3095
3253
  ): Promise<any> {
3096
- const body = JSON.stringify({ tool: toolName, arguments: args });
3097
-
3098
- const isServer = typeof window === 'undefined';
3099
-
3100
- let response: Response;
3101
- if (isServer) {
3102
- const apiUrl =
3103
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
3104
- EGDESK_CONFIG.apiUrl;
3105
- response = await fetch(\`\${apiUrl}/drive/tools/call\`, {
3106
- method: 'POST',
3107
- headers: buildServerEgdeskHeaders(),
3108
- body
3109
- });
3110
- } else {
3111
- response = await apiFetch('/__drive_proxy', {
3112
- method: 'POST',
3113
- headers: { 'Content-Type': 'application/json' },
3114
- body
3115
- });
3116
- }
3117
-
3118
- return parseEgdeskMcpToolResponse(response);
3254
+ return callWorkspaceMcpTool('/drive/tools/call', '/__drive_proxy', toolName, args, options);
3119
3255
  }
3120
3256
 
3121
3257
  /** Check owner Drive auth on this EGDesk instance (service account / Google OAuth) */
@@ -3315,36 +3451,16 @@ export async function syncDrive(options: {
3315
3451
  * Call EGDesk Sheets MCP tool.
3316
3452
  *
3317
3453
  * Auth: personal OAuth, service account, or domain-wide delegation (call getSheetsAuthStatus() first).
3454
+ * Pass { asVisitor: true } to act as the website visitor from startVisitorGoogleLogin().
3318
3455
  * - Server: \`POST {apiUrl}/sheets/tools/call\`
3319
3456
  * - Client: \`POST /__sheets_proxy\`
3320
3457
  */
3321
3458
  export async function callSheetsTool(
3322
3459
  toolName: string,
3323
- args: Record<string, any> = {}
3460
+ args: Record<string, any> = {},
3461
+ options: WorkspaceVisitorCallOptions = {},
3324
3462
  ): Promise<any> {
3325
- const body = JSON.stringify({ tool: toolName, arguments: args });
3326
-
3327
- const isServer = typeof window === 'undefined';
3328
-
3329
- let response: Response;
3330
- if (isServer) {
3331
- const apiUrl =
3332
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
3333
- EGDESK_CONFIG.apiUrl;
3334
- response = await fetch(\`\${apiUrl}/sheets/tools/call\`, {
3335
- method: 'POST',
3336
- headers: buildServerEgdeskHeaders(),
3337
- body
3338
- });
3339
- } else {
3340
- response = await apiFetch('/__sheets_proxy', {
3341
- method: 'POST',
3342
- headers: { 'Content-Type': 'application/json' },
3343
- body
3344
- });
3345
- }
3346
-
3347
- return parseEgdeskMcpToolResponse(response);
3463
+ return callWorkspaceMcpTool('/sheets/tools/call', '/__sheets_proxy', toolName, args, options);
3348
3464
  }
3349
3465
 
3350
3466
  /** Who Sheets/Docs/Slides/Drive calls act as: personal_oauth, service_account, or domain_wide_delegation */
@@ -3427,28 +3543,10 @@ export async function tintSheetDataTab(spreadsheetId: string, sheetName: string)
3427
3543
 
3428
3544
  export async function callDocsTool(
3429
3545
  toolName: string,
3430
- args: Record<string, any> = {}
3546
+ args: Record<string, any> = {},
3547
+ options: WorkspaceVisitorCallOptions = {},
3431
3548
  ): Promise<any> {
3432
- const body = JSON.stringify({ tool: toolName, arguments: args });
3433
- const isServer = typeof window === 'undefined';
3434
- let response: Response;
3435
- if (isServer) {
3436
- const apiUrl =
3437
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
3438
- EGDESK_CONFIG.apiUrl;
3439
- response = await fetch(\`\${apiUrl}/docs/tools/call\`, {
3440
- method: 'POST',
3441
- headers: buildServerEgdeskHeaders(),
3442
- body
3443
- });
3444
- } else {
3445
- response = await apiFetch('/__docs_proxy', {
3446
- method: 'POST',
3447
- headers: { 'Content-Type': 'application/json' },
3448
- body
3449
- });
3450
- }
3451
- return parseEgdeskMcpToolResponse(response);
3549
+ return callWorkspaceMcpTool('/docs/tools/call', '/__docs_proxy', toolName, args, options);
3452
3550
  }
3453
3551
 
3454
3552
  export async function getGoogleDocsAuthStatus() {
@@ -3486,28 +3584,10 @@ export async function replaceGoogleDocText(
3486
3584
 
3487
3585
  export async function callSlidesTool(
3488
3586
  toolName: string,
3489
- args: Record<string, any> = {}
3587
+ args: Record<string, any> = {},
3588
+ options: WorkspaceVisitorCallOptions = {},
3490
3589
  ): Promise<any> {
3491
- const body = JSON.stringify({ tool: toolName, arguments: args });
3492
- const isServer = typeof window === 'undefined';
3493
- let response: Response;
3494
- if (isServer) {
3495
- const apiUrl =
3496
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
3497
- EGDESK_CONFIG.apiUrl;
3498
- response = await fetch(\`\${apiUrl}/slides/tools/call\`, {
3499
- method: 'POST',
3500
- headers: buildServerEgdeskHeaders(),
3501
- body
3502
- });
3503
- } else {
3504
- response = await apiFetch('/__slides_proxy', {
3505
- method: 'POST',
3506
- headers: { 'Content-Type': 'application/json' },
3507
- body
3508
- });
3509
- }
3510
- return parseEgdeskMcpToolResponse(response);
3590
+ return callWorkspaceMcpTool('/slides/tools/call', '/__slides_proxy', toolName, args, options);
3511
3591
  }
3512
3592
 
3513
3593
  export async function getGoogleSlidesAuthStatus() {
@@ -3605,28 +3685,10 @@ export async function syncSheets(options: {
3605
3685
  */
3606
3686
  export async function callGmailTool(
3607
3687
  toolName: string,
3608
- args: Record<string, any> = {}
3688
+ args: Record<string, any> = {},
3689
+ options: WorkspaceVisitorCallOptions = {},
3609
3690
  ): Promise<any> {
3610
- const body = JSON.stringify({ tool: toolName, arguments: args });
3611
- const isServer = typeof window === 'undefined';
3612
- let response: Response;
3613
- if (isServer) {
3614
- const apiUrl =
3615
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
3616
- EGDESK_CONFIG.apiUrl;
3617
- response = await fetch(\`\${apiUrl}/gmail/tools/call\`, {
3618
- method: 'POST',
3619
- headers: buildServerEgdeskHeaders(),
3620
- body
3621
- });
3622
- } else {
3623
- response = await apiFetch('/__gmail_proxy', {
3624
- method: 'POST',
3625
- headers: { 'Content-Type': 'application/json' },
3626
- body
3627
- });
3628
- }
3629
- return parseEgdeskMcpToolResponse(response);
3691
+ return callWorkspaceMcpTool('/gmail/tools/call', '/__gmail_proxy', toolName, args, options);
3630
3692
  }
3631
3693
 
3632
3694
  /** Who Gmail calls act as: personal_oauth, service_account, or domain_wide_delegation */
@@ -3677,28 +3739,10 @@ export async function sendGmailMessage(options: {
3677
3739
  */
3678
3740
  export async function callAppsScriptTool(
3679
3741
  toolName: string,
3680
- args: Record<string, any> = {}
3742
+ args: Record<string, any> = {},
3743
+ options: WorkspaceVisitorCallOptions = {},
3681
3744
  ): Promise<any> {
3682
- const body = JSON.stringify({ tool: toolName, arguments: args });
3683
- const isServer = typeof window === 'undefined';
3684
- let response: Response;
3685
- if (isServer) {
3686
- const apiUrl =
3687
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
3688
- EGDESK_CONFIG.apiUrl;
3689
- response = await fetch(\`\${apiUrl}/apps-script/tools/call\`, {
3690
- method: 'POST',
3691
- headers: buildServerEgdeskHeaders(),
3692
- body
3693
- });
3694
- } else {
3695
- response = await apiFetch('/__apps_script_proxy', {
3696
- method: 'POST',
3697
- headers: { 'Content-Type': 'application/json' },
3698
- body
3699
- });
3700
- }
3701
- return parseEgdeskMcpToolResponse(response);
3745
+ return callWorkspaceMcpTool('/apps-script/tools/call', '/__apps_script_proxy', toolName, args, options);
3702
3746
  }
3703
3747
 
3704
3748
  /** Apps Script auth mode and identity (OAuth or service account / DWD — call before create/push/run) */
@@ -93,6 +93,25 @@ function visitorUpstreamHeaders(request: NextRequest): Record<string, string> {
93
93
  return headers;
94
94
  }
95
95
 
96
+ function workspaceUpstreamHeaders(request: NextRequest): Record<string, string> {
97
+ const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
98
+ const headers: Record<string, string> = { 'Content-Type': 'application/json' };
99
+ if (apiKey) headers['X-Api-Key'] = apiKey;
100
+ const authorization = request.headers.get('authorization');
101
+ const asVisitor = request.headers.get('x-egdesk-as-visitor');
102
+ if (authorization) headers['Authorization'] = authorization;
103
+ if (asVisitor) headers['X-EGDesk-As-Visitor'] = asVisitor;
104
+ if (asVisitor === 'true' || authorization) {
105
+ const origin =
106
+ request.headers.get('x-visitor-origin') ||
107
+ request.headers.get('origin') ||
108
+ request.nextUrl.origin;
109
+ headers['Origin'] = origin;
110
+ headers['X-Visitor-Origin'] = origin;
111
+ }
112
+ return headers;
113
+ }
114
+
96
115
  export async function middleware(request: NextRequest) {
97
116
  const { pathname } = request.nextUrl;
98
117
 
@@ -262,14 +281,11 @@ export async function middleware(request: NextRequest) {
262
281
  if (pathname.includes('__drive_proxy')) {
263
282
  try {
264
283
  const body = await request.text();
265
- const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
266
284
  const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
267
- const headers: HeadersInit = { 'Content-Type': 'application/json' };
268
- if (apiKey) headers['X-Api-Key'] = apiKey;
269
285
 
270
286
  const response = await fetch(\`\${apiUrl}/drive/tools/call\`, {
271
287
  method: 'POST',
272
- headers,
288
+ headers: workspaceUpstreamHeaders(request),
273
289
  body,
274
290
  });
275
291
  const result = await response.json();
@@ -285,14 +301,11 @@ export async function middleware(request: NextRequest) {
285
301
  if (pathname.includes('__docs_proxy')) {
286
302
  try {
287
303
  const body = await request.text();
288
- const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
289
304
  const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
290
- const headers: HeadersInit = { 'Content-Type': 'application/json' };
291
- if (apiKey) headers['X-Api-Key'] = apiKey;
292
305
 
293
306
  const response = await fetch(\`\${apiUrl}/docs/tools/call\`, {
294
307
  method: 'POST',
295
- headers,
308
+ headers: workspaceUpstreamHeaders(request),
296
309
  body,
297
310
  });
298
311
  const result = await response.json();
@@ -308,14 +321,11 @@ export async function middleware(request: NextRequest) {
308
321
  if (pathname.includes('__slides_proxy')) {
309
322
  try {
310
323
  const body = await request.text();
311
- const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
312
324
  const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
313
- const headers: HeadersInit = { 'Content-Type': 'application/json' };
314
- if (apiKey) headers['X-Api-Key'] = apiKey;
315
325
 
316
326
  const response = await fetch(\`\${apiUrl}/slides/tools/call\`, {
317
327
  method: 'POST',
318
- headers,
328
+ headers: workspaceUpstreamHeaders(request),
319
329
  body,
320
330
  });
321
331
  const result = await response.json();
@@ -331,14 +341,11 @@ export async function middleware(request: NextRequest) {
331
341
  if (pathname.includes('__sheets_proxy')) {
332
342
  try {
333
343
  const body = await request.text();
334
- const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
335
344
  const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
336
- const headers: HeadersInit = { 'Content-Type': 'application/json' };
337
- if (apiKey) headers['X-Api-Key'] = apiKey;
338
345
 
339
346
  const response = await fetch(\`\${apiUrl}/sheets/tools/call\`, {
340
347
  method: 'POST',
341
- headers,
348
+ headers: workspaceUpstreamHeaders(request),
342
349
  body,
343
350
  });
344
351
  const result = await response.json();
@@ -392,13 +399,10 @@ export async function middleware(request: NextRequest) {
392
399
  if (pathname.includes('__gmail_proxy')) {
393
400
  try {
394
401
  const body = await request.text();
395
- const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
396
402
  const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
397
- const headers: HeadersInit = { 'Content-Type': 'application/json' };
398
- if (apiKey) headers['X-Api-Key'] = apiKey;
399
403
  const response = await fetch(\`\${apiUrl}/gmail/tools/call\`, {
400
404
  method: 'POST',
401
- headers,
405
+ headers: workspaceUpstreamHeaders(request),
402
406
  body,
403
407
  });
404
408
  const result = await response.json();
@@ -414,13 +418,10 @@ export async function middleware(request: NextRequest) {
414
418
  if (pathname.includes('__apps_script_proxy')) {
415
419
  try {
416
420
  const body = await request.text();
417
- const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
418
421
  const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
419
- const headers: HeadersInit = { 'Content-Type': 'application/json' };
420
- if (apiKey) headers['X-Api-Key'] = apiKey;
421
422
  const response = await fetch(\`\${apiUrl}/apps-script/tools/call\`, {
422
423
  method: 'POST',
423
- headers,
424
+ headers: workspaceUpstreamHeaders(request),
424
425
  body,
425
426
  });
426
427
  const result = await response.json();
@@ -102,6 +102,24 @@ function visitorForwardHeaders(request: NextRequest): Record<string, string> {
102
102
  return headers;
103
103
  }
104
104
 
105
+ /** Forward opt-in visitor session headers to Workspace MCP tool calls. */
106
+ function workspaceForwardHeaders(request: NextRequest): Record<string, string> {
107
+ const headers = buildEgdeskHeaders();
108
+ const authorization = request.headers.get('authorization');
109
+ const asVisitor = request.headers.get('x-egdesk-as-visitor');
110
+ if (authorization) headers['Authorization'] = authorization;
111
+ if (asVisitor) headers['X-EGDesk-As-Visitor'] = asVisitor;
112
+ if (asVisitor === 'true' || authorization) {
113
+ const origin =
114
+ request.headers.get('x-visitor-origin') ||
115
+ request.headers.get('origin') ||
116
+ request.nextUrl.origin;
117
+ headers['Origin'] = origin;
118
+ headers['X-Visitor-Origin'] = origin;
119
+ }
120
+ return headers;
121
+ }
122
+
105
123
  export async function proxy(request: NextRequest) {
106
124
  const { pathname } = request.nextUrl;
107
125
 
@@ -422,7 +440,7 @@ export async function proxy(request: NextRequest) {
422
440
 
423
441
  const response = await fetch(\`\${apiUrl}/drive/tools/call\`, {
424
442
  method: 'POST',
425
- headers: buildEgdeskHeaders(),
443
+ headers: workspaceForwardHeaders(request),
426
444
  body,
427
445
  });
428
446
 
@@ -444,7 +462,7 @@ export async function proxy(request: NextRequest) {
444
462
 
445
463
  const response = await fetch(\`\${apiUrl}/docs/tools/call\`, {
446
464
  method: 'POST',
447
- headers: buildEgdeskHeaders(),
465
+ headers: workspaceForwardHeaders(request),
448
466
  body,
449
467
  });
450
468
 
@@ -466,7 +484,7 @@ export async function proxy(request: NextRequest) {
466
484
 
467
485
  const response = await fetch(\`\${apiUrl}/slides/tools/call\`, {
468
486
  method: 'POST',
469
- headers: buildEgdeskHeaders(),
487
+ headers: workspaceForwardHeaders(request),
470
488
  body,
471
489
  });
472
490
 
@@ -488,7 +506,7 @@ export async function proxy(request: NextRequest) {
488
506
 
489
507
  const response = await fetch(\`\${apiUrl}/sheets/tools/call\`, {
490
508
  method: 'POST',
491
- headers: buildEgdeskHeaders(),
509
+ headers: workspaceForwardHeaders(request),
492
510
  body,
493
511
  });
494
512
 
@@ -540,7 +558,7 @@ export async function proxy(request: NextRequest) {
540
558
  const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
541
559
  const response = await fetch(\`\${apiUrl}/gmail/tools/call\`, {
542
560
  method: 'POST',
543
- headers: buildEgdeskHeaders(),
561
+ headers: workspaceForwardHeaders(request),
544
562
  body,
545
563
  });
546
564
  const result = await response.json();
@@ -559,7 +577,7 @@ export async function proxy(request: NextRequest) {
559
577
  const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
560
578
  const response = await fetch(\`\${apiUrl}/apps-script/tools/call\`, {
561
579
  method: 'POST',
562
- headers: buildEgdeskHeaders(),
580
+ headers: workspaceForwardHeaders(request),
563
581
  body,
564
582
  });
565
583
  const result = await response.json();
package/dist/index.d.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  * The minimum EGDesk app version this plugin version is compatible with.
9
9
  * The app checks this at setup time and warns on mismatch.
10
10
  */
11
- export declare const COMPATIBLE_APP_VERSION = "1.4.63";
11
+ export declare const COMPATIBLE_APP_VERSION = "1.4.65";
12
12
  export interface SetupOptions {
13
13
  egdeskUrl?: string;
14
14
  /** Production EGDesk server URL — written to .env.production.local. Falls back to egdeskUrl. */
package/dist/index.js CHANGED
@@ -46,7 +46,7 @@ exports.setupNextApiPlugin = setupNextApiPlugin;
46
46
  * The minimum EGDesk app version this plugin version is compatible with.
47
47
  * The app checks this at setup time and warns on mismatch.
48
48
  */
49
- exports.COMPATIBLE_APP_VERSION = '1.4.63';
49
+ exports.COMPATIBLE_APP_VERSION = '1.4.65';
50
50
  const fs = __importStar(require("fs"));
51
51
  const path = __importStar(require("path"));
52
52
  const setup_userdata_1 = require("./setup-userdata");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@egdesk/next-api-plugin",
3
- "version": "1.5.55",
3
+ "version": "1.5.57",
4
4
  "description": "Next.js plugin for EGDesk database proxy integration",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",