@egdesk/next-api-plugin 1.5.12 → 1.5.14

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.
@@ -146,6 +146,13 @@ function generateHelpers(projectPath, options = {}) {
146
146
  * Schema files:
147
147
  * - egdesk.schema.ts — committed seed schema (edit this; commit to git)
148
148
  * - egdesk.config.ts — auto-generated runtime snapshot (gitignored; do not edit)
149
+ *
150
+ * AI / external agents:
151
+ * - If egdesk-user-data MCP is connected (Claude Desktop / Antigravity / Cursor), prefer MCP tools
152
+ * for exploring My DB: user_data_list_projects → user_data_select_project → user_data_list_tables / query.
153
+ * - Check that EGDesk is running and MCP tools are actually available before relying on them.
154
+ * - For app code in this repo, keep using these helpers (queryTable, etc.) — MCP is optional for agents.
155
+ * - If MCP tools are missing/empty, fall back to helpers + EGDESK-README.md; ask the user to install MCP from EGDesk.
149
156
  */
150
157
 
151
158
  import { EGDESK_CONFIG } from './egdesk.config';
@@ -392,6 +399,16 @@ export async function getTableSchema(tableName: string) {
392
399
  return callUserDataTool('user_data_get_schema', { tableName });
393
400
  }
394
401
 
402
+ /**
403
+ * Get schemas for multiple tables in ONE call (preferred over repeated getTableSchema).
404
+ * Omit tableNames to fetch schemas for all tables.
405
+ */
406
+ export async function getTableSchemas(tableNames?: string[]) {
407
+ return callUserDataTool('user_data_get_schemas_batch', {
408
+ ...(tableNames?.length ? { tableNames } : {}),
409
+ });
410
+ }
411
+
395
412
  /**
396
413
  * Create a new table
397
414
  */
@@ -491,9 +508,11 @@ export async function renameTable(
491
508
  // ==========================================
492
509
 
493
510
  /**
494
- * Upload a file to a user data table row.
495
- * Data must be base64-encoded. Files <10KB are stored as uncompressed blobs,
496
- * 10-100KB as gzip-compressed blobs, >100KB on the filesystem via BucketManager.
511
+ * Upload a file attachment for a table row.
512
+ * Files are NOT table columns — they attach via a virtual columnName (e.g. "file").
513
+ * Workflow: insertRows(...) → uploadFile(tableName, rowId, 'file', filename, base64).
514
+ * Data must be base64 (raw or data URL). Files <10KB store as uncompressed blobs,
515
+ * 10-100KB as gzip blobs, >100KB on disk via BucketManager.
497
516
  */
498
517
  export async function uploadFile(
499
518
  tableName: string,
@@ -503,7 +522,7 @@ export async function uploadFile(
503
522
  data: string,
504
523
  options: {
505
524
  mimeType?: string;
506
- forceStorageType?: 'blob' | 'file';
525
+ forceStorageType?: 'blob' | 'filesystem';
507
526
  compress?: boolean;
508
527
  } = {}
509
528
  ) {
@@ -559,6 +578,190 @@ export async function getFileStats(tableName?: string) {
559
578
  });
560
579
  }
561
580
 
581
+ // ==========================================
582
+ // USER DATA CRON JOBS
583
+ // ==========================================
584
+
585
+ export type UserDataCronActionType = 'sync_config' | 'browser_recording' | 'backup' | 'script';
586
+ export type UserDataCronFrequencyType = 'daily' | 'weekly' | 'monthly' | 'custom' | 'cron';
587
+
588
+ export type UserDataCronActionPayload = {
589
+ syncConfigId?: string;
590
+ syncConfigName?: string;
591
+ testPath?: string;
592
+ testName?: string;
593
+ scriptPath?: string;
594
+ functionName?: string;
595
+ args?: unknown;
596
+ timeoutMs?: number;
597
+ cwd?: string;
598
+ };
599
+
600
+ export type CreateUserDataCronJobOptions = {
601
+ name: string;
602
+ actionType: UserDataCronActionType;
603
+ actionPayload?: UserDataCronActionPayload;
604
+ /** Flat alias for actionPayload.syncConfigId */
605
+ syncConfigId?: string;
606
+ syncConfigName?: string;
607
+ /** Flat alias for actionPayload.testPath */
608
+ testPath?: string;
609
+ testName?: string;
610
+ /** Flat alias for actionPayload.scriptPath (.js/.mjs/.cjs) */
611
+ scriptPath?: string;
612
+ functionName?: string;
613
+ args?: unknown;
614
+ timeoutMs?: number;
615
+ cwd?: string;
616
+ scheduledTime?: string;
617
+ /** Defaults to daily when omitted */
618
+ frequencyType?: UserDataCronFrequencyType;
619
+ dayOfWeek?: number;
620
+ dayOfMonth?: number;
621
+ customIntervalDays?: number;
622
+ cronExpression?: string;
623
+ enabled?: boolean;
624
+ };
625
+
626
+ export type UpdateUserDataCronJobOptions = Partial<CreateUserDataCronJobOptions> & {
627
+ jobId: string;
628
+ };
629
+
630
+ /** List UserData cron jobs for the active project+env */
631
+ export async function listUserDataCronJobs() {
632
+ return callUserDataTool('user_data_cron_list', {});
633
+ }
634
+
635
+ /** Get a UserData cron job by id */
636
+ export async function getUserDataCronJob(jobId: string) {
637
+ return callUserDataTool('user_data_cron_get', { jobId });
638
+ }
639
+
640
+ /** Create a UserData cron job (sync_config / browser_recording / backup) */
641
+ export async function createUserDataCronJob(options: CreateUserDataCronJobOptions) {
642
+ return callUserDataTool('user_data_cron_create', options);
643
+ }
644
+
645
+ /** Update a UserData cron job */
646
+ export async function updateUserDataCronJob(options: UpdateUserDataCronJobOptions) {
647
+ return callUserDataTool('user_data_cron_update', options);
648
+ }
649
+
650
+ /** Delete a UserData cron job */
651
+ export async function deleteUserDataCronJob(jobId: string) {
652
+ return callUserDataTool('user_data_cron_delete', { jobId });
653
+ }
654
+
655
+ /** Enable or pause a UserData cron job */
656
+ export async function toggleUserDataCronJob(jobId: string, enabled: boolean) {
657
+ return callUserDataTool('user_data_cron_toggle', { jobId, enabled });
658
+ }
659
+
660
+ /** Run a UserData cron job immediately */
661
+ export async function runUserDataCronJobNow(jobId: string) {
662
+ return callUserDataTool('user_data_cron_run_now', { jobId });
663
+ }
664
+
665
+ /** List execution history for a UserData cron job */
666
+ export async function listUserDataCronExecutions(jobId: string, limit?: number) {
667
+ return callUserDataTool('user_data_cron_executions', {
668
+ jobId,
669
+ ...(limit != null ? { limit } : {}),
670
+ });
671
+ }
672
+
673
+ /** Get UserData cron scheduler status */
674
+ export async function getUserDataCronStatus() {
675
+ return callUserDataTool('user_data_cron_status', {});
676
+ }
677
+
678
+ // ==========================================
679
+ // USER DATA QUEUE JOBS
680
+ // ==========================================
681
+
682
+ export type UserDataQueueActionType =
683
+ | 'sync_config'
684
+ | 'browser_recording'
685
+ | 'backup'
686
+ | 'script';
687
+
688
+ export type UserDataQueueActionPayload = UserDataCronActionPayload;
689
+
690
+ export type EnqueueUserDataQueueJobOptions = {
691
+ name?: string;
692
+ actionType: UserDataQueueActionType;
693
+ actionPayload?: UserDataQueueActionPayload;
694
+ syncConfigId?: string;
695
+ syncConfigName?: string;
696
+ testPath?: string;
697
+ testName?: string;
698
+ scriptPath?: string;
699
+ functionName?: string;
700
+ args?: unknown;
701
+ timeoutMs?: number;
702
+ cwd?: string;
703
+ priority?: number;
704
+ maxAttempts?: number;
705
+ runAfter?: string | null;
706
+ idempotencyKey?: string | null;
707
+ };
708
+
709
+ /** List UserData queue jobs for the active project+env */
710
+ export async function listUserDataQueueJobs(options?: {
711
+ status?: string;
712
+ limit?: number;
713
+ }) {
714
+ return callUserDataTool('user_data_queue_list', options || {});
715
+ }
716
+
717
+ /** Get a UserData queue job by id */
718
+ export async function getUserDataQueueJob(jobId: string) {
719
+ return callUserDataTool('user_data_queue_get', { jobId });
720
+ }
721
+
722
+ /** Enqueue a UserData job (sync_config / browser_recording / backup / script) */
723
+ export async function enqueueUserDataQueueJob(options: EnqueueUserDataQueueJobOptions) {
724
+ return callUserDataTool('user_data_queue_enqueue', options);
725
+ }
726
+
727
+ /** Cancel a pending UserData queue job */
728
+ export async function cancelUserDataQueueJob(jobId: string) {
729
+ return callUserDataTool('user_data_queue_cancel', { jobId });
730
+ }
731
+
732
+ /** Retry a failed/dead/cancelled UserData queue job */
733
+ export async function retryUserDataQueueJob(jobId: string) {
734
+ return callUserDataTool('user_data_queue_retry', { jobId });
735
+ }
736
+
737
+ /** Delete a UserData queue job */
738
+ export async function deleteUserDataQueueJob(jobId: string) {
739
+ return callUserDataTool('user_data_queue_delete', { jobId });
740
+ }
741
+
742
+ /** Run a UserData queue job immediately */
743
+ export async function runUserDataQueueJobNow(jobId: string) {
744
+ return callUserDataTool('user_data_queue_run_now', { jobId });
745
+ }
746
+
747
+ /** List attempt history for a UserData queue job */
748
+ export async function listUserDataQueueRuns(jobId: string, limit?: number) {
749
+ return callUserDataTool('user_data_queue_runs', {
750
+ jobId,
751
+ ...(limit != null ? { limit } : {}),
752
+ });
753
+ }
754
+
755
+ /** Get UserData queue counts by status */
756
+ export async function getUserDataQueueStats() {
757
+ return callUserDataTool('user_data_queue_stats', {});
758
+ }
759
+
760
+ /** Get UserData queue worker status */
761
+ export async function getUserDataQueueStatus() {
762
+ return callUserDataTool('user_data_queue_status', {});
763
+ }
764
+
562
765
  // ==========================================
563
766
  // USER DATA REAL-TIME SUBSCRIPTIONS
564
767
  // ==========================================
@@ -605,7 +808,16 @@ export function onUserDataChanged(
605
808
 
606
809
  const apiUrl = EGDESK_CONFIG.apiUrl || '';
607
810
  const apiKey = EGDESK_CONFIG.apiKey || '';
608
- const sseUrl = apiKey ? \`\${apiUrl}/user-data/sse?key=\${encodeURIComponent(apiKey)}\` : \`\${apiUrl}/user-data/sse\`;
811
+ const projectId =
812
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_PROJECT_ID) || '';
813
+ const egdeskEnv =
814
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_ENV) || '';
815
+ const sseParams = new URLSearchParams();
816
+ if (apiKey) sseParams.set('key', apiKey);
817
+ if (projectId) sseParams.set('egdeskId', projectId);
818
+ if (egdeskEnv) sseParams.set('environment', egdeskEnv);
819
+ const sseQuery = sseParams.toString();
820
+ const sseUrl = \`\${apiUrl}/user-data/sse\${sseQuery ? \`?\${sseQuery}\` : ''}\`;
609
821
  const es = new EventSource(sseUrl);
610
822
 
611
823
  es.addEventListener('message', (e: MessageEvent) => {
@@ -2359,6 +2571,242 @@ export async function deletePageIndexDocument(docId: string) {
2359
2571
  return callPageIndexTool('pageindex_delete_document', { doc_id: docId });
2360
2572
  }
2361
2573
 
2574
+ // ==========================================
2575
+ // Drive (MCP) — change watch / poll / events
2576
+ // ==========================================
2577
+
2578
+ /**
2579
+ * Call EGDesk Drive MCP tool (Google Drive change notifications + poll).
2580
+ *
2581
+ * Auth on EGDesk: GOOGLE_SERVICE_ACCOUNT_JSON or Google Workspace sign-in.
2582
+ * Share target folders with the service account when using SA credentials.
2583
+ *
2584
+ * - Server: \`POST {apiUrl}/drive/tools/call\`
2585
+ * - Client: \`POST /__drive_proxy\` (see proxy.ts / middleware)
2586
+ * - Webhook (Google push, not this helper): \`POST {apiUrl}/drive/webhook\`
2587
+ */
2588
+ export async function callDriveTool(
2589
+ toolName: string,
2590
+ args: Record<string, any> = {}
2591
+ ): Promise<any> {
2592
+ const body = JSON.stringify({ tool: toolName, arguments: args });
2593
+
2594
+ const isServer = typeof window === 'undefined';
2595
+
2596
+ let response: Response;
2597
+ if (isServer) {
2598
+ const apiUrl =
2599
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
2600
+ EGDESK_CONFIG.apiUrl;
2601
+ response = await fetch(\`\${apiUrl}/drive/tools/call\`, {
2602
+ method: 'POST',
2603
+ headers: buildServerEgdeskHeaders(),
2604
+ body
2605
+ });
2606
+ } else {
2607
+ response = await apiFetch('/__drive_proxy', {
2608
+ method: 'POST',
2609
+ headers: { 'Content-Type': 'application/json' },
2610
+ body
2611
+ });
2612
+ }
2613
+
2614
+ return parseEgdeskMcpToolResponse(response);
2615
+ }
2616
+
2617
+ /** Check Drive auth (service account / Google OAuth) */
2618
+ export async function getDriveAuthStatus() {
2619
+ return callDriveTool('drive_auth_status', {});
2620
+ }
2621
+
2622
+ /**
2623
+ * Start Google OAuth for Drive. Returns { status:'pending', authUrl } immediately.
2624
+ * Open authUrl in the browser, then poll getDriveAuthStatus() until connected.
2625
+ */
2626
+ export async function startDriveAuthLogin(options: {
2627
+ openWindow?: boolean;
2628
+ forceConsent?: boolean;
2629
+ } = {}) {
2630
+ return callDriveTool('drive_auth_login', options);
2631
+ }
2632
+
2633
+ /** Initialize Drive sync (page token + target folders; optional snapshot) */
2634
+ export async function initDriveSync(options: {
2635
+ folderIds: string[];
2636
+ snapshot?: boolean;
2637
+ downloadPath?: string;
2638
+ reset?: boolean;
2639
+ }) {
2640
+ return callDriveTool('drive_init', options);
2641
+ }
2642
+
2643
+ /** Start drive.changes.watch; webhook = {webhookBaseUrl}/drive/webhook */
2644
+ export async function watchDriveChanges(options: {
2645
+ webhookBaseUrl: string;
2646
+ ttlSeconds?: number;
2647
+ }) {
2648
+ return callDriveTool('drive_watch', options);
2649
+ }
2650
+
2651
+ /** Stop the active Drive watch channel */
2652
+ export async function stopDriveWatch() {
2653
+ return callDriveTool('drive_stop', {});
2654
+ }
2655
+
2656
+ /** One-shot poll via changes.list (no tunnel needed) */
2657
+ export async function pollDriveChanges(options: { download?: boolean } = {}) {
2658
+ return callDriveTool('drive_poll', options);
2659
+ }
2660
+
2661
+ /** Keep watching saved folders on an interval (persists + auto-resumes) */
2662
+ export async function startDrivePollLoop(options: {
2663
+ intervalSeconds?: number;
2664
+ download?: boolean;
2665
+ } = {}) {
2666
+ return callDriveTool('drive_start_poll_loop', options);
2667
+ }
2668
+
2669
+ /** Stop continuous poll loop (folders/page token stay saved) */
2670
+ export async function stopDrivePollLoop() {
2671
+ return callDriveTool('drive_stop_poll_loop', {});
2672
+ }
2673
+
2674
+ /** Sync state, channel expiry, and event counts */
2675
+ export async function getDriveStatus() {
2676
+ return callDriveTool('drive_status', {});
2677
+ }
2678
+
2679
+ /** List currently watched folders with names and Drive URLs */
2680
+ export async function listDriveWatchedFolders() {
2681
+ return callDriveTool('drive_list_watched_folders', {});
2682
+ }
2683
+
2684
+ /** List recent drive_file_events */
2685
+ export async function listDriveEvents(options: {
2686
+ limit?: number;
2687
+ downloadedOnly?: boolean;
2688
+ since?: string;
2689
+ } = {}) {
2690
+ return callDriveTool('drive_list_events', options);
2691
+ }
2692
+
2693
+ /** Replace monitored folder IDs without resetting the page token */
2694
+ export async function setDriveTargetFolders(folderIds: string[]) {
2695
+ return callDriveTool('drive_set_target_folders', { folderIds });
2696
+ }
2697
+
2698
+ // ==========================================
2699
+ // Knowledge Wiki (MCP) — Obsidian + wikiHow
2700
+ // ==========================================
2701
+
2702
+ /**
2703
+ * Call EGDesk Knowledge Wiki MCP tool (Obsidian vault index + wikiHow guides).
2704
+ *
2705
+ * - Server: \`POST {apiUrl}/knowledge-wiki/tools/call\`
2706
+ * - Client: \`POST /__knowledge_wiki_proxy\` (see proxy.ts / middleware)
2707
+ */
2708
+ export async function callKnowledgeWikiTool(
2709
+ toolName: string,
2710
+ args: Record<string, any> = {}
2711
+ ): Promise<any> {
2712
+ const body = JSON.stringify({ tool: toolName, arguments: args });
2713
+
2714
+ const isServer = typeof window === 'undefined';
2715
+
2716
+ let response: Response;
2717
+ if (isServer) {
2718
+ const apiUrl =
2719
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
2720
+ EGDESK_CONFIG.apiUrl;
2721
+ response = await fetch(\`\${apiUrl}/knowledge-wiki/tools/call\`, {
2722
+ method: 'POST',
2723
+ headers: buildServerEgdeskHeaders(),
2724
+ body
2725
+ });
2726
+ } else {
2727
+ response = await apiFetch('/__knowledge_wiki_proxy', {
2728
+ method: 'POST',
2729
+ headers: { 'Content-Type': 'application/json' },
2730
+ body
2731
+ });
2732
+ }
2733
+
2734
+ return parseEgdeskMcpToolResponse(response);
2735
+ }
2736
+
2737
+ export async function getKnowledgeWikiStatus() {
2738
+ return callKnowledgeWikiTool('knowledge_wiki_status', {});
2739
+ }
2740
+
2741
+ export async function searchKnowledgeWiki(
2742
+ query: string,
2743
+ options: { limit?: number; sources?: Array<'obsidian' | 'wikihow'> } = {}
2744
+ ) {
2745
+ return callKnowledgeWikiTool('knowledge_wiki_search', { query, ...options });
2746
+ }
2747
+
2748
+ export async function setObsidianVault(vaultPath: string) {
2749
+ return callKnowledgeWikiTool('obsidian_set_vault', { vaultPath });
2750
+ }
2751
+
2752
+ export async function indexObsidianVault(options: { vaultPath?: string } = {}) {
2753
+ return callKnowledgeWikiTool('obsidian_index', options);
2754
+ }
2755
+
2756
+ export async function listObsidianNotes(options: {
2757
+ limit?: number;
2758
+ offset?: number;
2759
+ tag?: string;
2760
+ } = {}) {
2761
+ return callKnowledgeWikiTool('obsidian_list_notes', options);
2762
+ }
2763
+
2764
+ export async function getObsidianNote(options: {
2765
+ path?: string;
2766
+ title?: string;
2767
+ id?: string;
2768
+ }) {
2769
+ return callKnowledgeWikiTool('obsidian_get_note', options);
2770
+ }
2771
+
2772
+ export async function searchObsidianNotes(query: string, limit?: number) {
2773
+ return callKnowledgeWikiTool('obsidian_search', { query, limit });
2774
+ }
2775
+
2776
+ export async function getObsidianBacklinks(title: string, limit?: number) {
2777
+ return callKnowledgeWikiTool('obsidian_backlinks', { title, limit });
2778
+ }
2779
+
2780
+ export async function listObsidianTags() {
2781
+ return callKnowledgeWikiTool('obsidian_list_tags', {});
2782
+ }
2783
+
2784
+ export async function searchWikiHow(
2785
+ query: string,
2786
+ options: { lang?: string; limit?: number } = {}
2787
+ ) {
2788
+ return callKnowledgeWikiTool('wikihow_search', { query, ...options });
2789
+ }
2790
+
2791
+ export async function getWikiHowGuide(
2792
+ titleOrUrl: string,
2793
+ options: { lang?: string; cache?: boolean } = {}
2794
+ ) {
2795
+ return callKnowledgeWikiTool('wikihow_get_guide', { titleOrUrl, ...options });
2796
+ }
2797
+
2798
+ export async function listCachedWikiHow(options: {
2799
+ limit?: number;
2800
+ offset?: number;
2801
+ lang?: string;
2802
+ } = {}) {
2803
+ return callKnowledgeWikiTool('wikihow_list_cached', options);
2804
+ }
2805
+
2806
+ export async function searchCachedWikiHow(query: string, limit?: number) {
2807
+ return callKnowledgeWikiTool('wikihow_search_cached', { query, limit });
2808
+ }
2809
+
2362
2810
  // ==========================================
2363
2811
  // EGDesk Config (MCP) — Gemini / Google API keys
2364
2812
  // ==========================================
@@ -2445,6 +2893,157 @@ export async function setGeminiApiKey(options: {
2445
2893
  export async function listGeminiApiKeys() {
2446
2894
  return listApiKeys({ provider: 'google' });
2447
2895
  }
2896
+
2897
+ // ==========================================
2898
+ // Phone / Google Messages (MCP)
2899
+ // ==========================================
2900
+
2901
+ /**
2902
+ * Call EGDesk Phone MCP tool (Messages Web devices, inbox, SMS queue, consent).
2903
+ *
2904
+ * - Server: \`POST {apiUrl}/phone/tools/call\`
2905
+ * - Client: \`POST /__phone_proxy\` (see proxy.ts / middleware)
2906
+ */
2907
+ export async function callPhoneTool(
2908
+ toolName: string,
2909
+ args: Record<string, any> = {}
2910
+ ): Promise<any> {
2911
+ const body = JSON.stringify({ tool: toolName, arguments: args });
2912
+ const isServer = typeof window === 'undefined';
2913
+
2914
+ let response: Response;
2915
+ if (isServer) {
2916
+ const apiUrl =
2917
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
2918
+ EGDESK_CONFIG.apiUrl;
2919
+ response = await fetch(\`\${apiUrl}/phone/tools/call\`, {
2920
+ method: 'POST',
2921
+ headers: buildServerEgdeskHeaders(),
2922
+ body
2923
+ });
2924
+ } else {
2925
+ response = await apiFetch('/__phone_proxy', {
2926
+ method: 'POST',
2927
+ headers: { 'Content-Type': 'application/json' },
2928
+ body
2929
+ });
2930
+ }
2931
+
2932
+ return parseEgdeskMcpToolResponse(response);
2933
+ }
2934
+
2935
+ export async function listPhoneDevices() {
2936
+ return callPhoneTool('phone_list_devices', {});
2937
+ }
2938
+
2939
+ export async function createPhoneDevice(options: { label: string; id?: string }) {
2940
+ return callPhoneTool('phone_create_device', options);
2941
+ }
2942
+
2943
+ export async function deletePhoneDevice(deviceId: string) {
2944
+ return callPhoneTool('phone_delete_device', { deviceId });
2945
+ }
2946
+
2947
+ export async function connectPhoneDevice(deviceId: string) {
2948
+ return callPhoneTool('phone_connect', { deviceId });
2949
+ }
2950
+
2951
+ export async function checkPhoneDevice(deviceId: string) {
2952
+ return callPhoneTool('phone_check', { deviceId });
2953
+ }
2954
+
2955
+ export async function listPhoneConversations(deviceId: string) {
2956
+ return callPhoneTool('phone_list_conversations', { deviceId });
2957
+ }
2958
+
2959
+ export async function syncPhoneConversations(deviceId: string) {
2960
+ return callPhoneTool('phone_sync_conversations', { deviceId });
2961
+ }
2962
+
2963
+ export async function listPhoneConversationMessages(options: {
2964
+ deviceId: string;
2965
+ convKey: string;
2966
+ }) {
2967
+ return callPhoneTool('phone_list_conversation_messages', options);
2968
+ }
2969
+
2970
+ export async function syncPhoneConversationThread(options: {
2971
+ deviceId: string;
2972
+ convKey: string;
2973
+ title: string;
2974
+ }) {
2975
+ return callPhoneTool('phone_sync_conversation_thread', options);
2976
+ }
2977
+
2978
+ export async function listPhoneContacts(deviceId: string) {
2979
+ return callPhoneTool('phone_list_contacts', { deviceId });
2980
+ }
2981
+
2982
+ export async function syncPhoneContacts(deviceId: string) {
2983
+ return callPhoneTool('phone_sync_contacts', { deviceId });
2984
+ }
2985
+
2986
+ export async function sendPhoneSms(options: {
2987
+ deviceId: string;
2988
+ phoneNumber: string;
2989
+ message: string;
2990
+ snapshotId?: string;
2991
+ scheduledAt?: number;
2992
+ isMarketing?: boolean;
2993
+ brandName?: string;
2994
+ }) {
2995
+ return callPhoneTool('phone_send', options);
2996
+ }
2997
+
2998
+ export async function listPhoneQueue(options: {
2999
+ deviceId?: string;
3000
+ snapshotId?: string;
3001
+ limit?: number;
3002
+ } = {}) {
3003
+ return callPhoneTool('phone_list_queue', options);
3004
+ }
3005
+
3006
+ export async function cancelPhoneSend(jobId: string) {
3007
+ return callPhoneTool('phone_cancel_send', { jobId });
3008
+ }
3009
+
3010
+ export async function retryPhoneSend(jobId: string) {
3011
+ return callPhoneTool('phone_retry_send', { jobId });
3012
+ }
3013
+
3014
+ export async function listPhoneDevicesForSnapshot(snapshotId: string) {
3015
+ return callPhoneTool('phone_list_for_snapshot', { snapshotId });
3016
+ }
3017
+
3018
+ export async function linkPhoneSnapshot(options: {
3019
+ snapshotId: string;
3020
+ deviceId: string;
3021
+ }) {
3022
+ return callPhoneTool('phone_link_snapshot', options);
3023
+ }
3024
+
3025
+ export async function unlinkPhoneSnapshot(options: {
3026
+ snapshotId: string;
3027
+ deviceId: string;
3028
+ }) {
3029
+ return callPhoneTool('phone_unlink_snapshot', options);
3030
+ }
3031
+
3032
+ export async function getPhoneConsentLink(snapshotId: string) {
3033
+ return callPhoneTool('phone_consent_link_get', { snapshotId });
3034
+ }
3035
+
3036
+ export async function createPhoneConsentLink(options: {
3037
+ snapshotId: string;
3038
+ brandName?: string;
3039
+ optOutPhone?: string;
3040
+ }) {
3041
+ return callPhoneTool('phone_consent_link_create', options);
3042
+ }
3043
+
3044
+ export async function syncPhoneConsentEvents(snapshotId: string) {
3045
+ return callPhoneTool('phone_consent_events_sync', { snapshotId });
3046
+ }
2448
3047
  `;
2449
3048
  fs.writeFileSync(helperPath, helperContent.replace(/\r?\n/g, os.EOL), 'utf-8');
2450
3049
  console.log(`✅ Generated ${helperPath}`);
@@ -264,4 +264,32 @@ export const config = {
264
264
  `;
265
265
  fs.writeFileSync(middlewarePath, middlewareContent.replace(/\r?\n/g, os.EOL), 'utf-8');
266
266
  console.log(`✅ Generated ${middlewarePath}`);
267
+ // Next.js 16+ errors if both middleware.ts and proxy.ts exist.
268
+ removeConflictingInterceptorFiles(projectPath, middlewarePath);
269
+ }
270
+ function removeFileIfExists(filePath) {
271
+ if (!fs.existsSync(filePath))
272
+ return;
273
+ try {
274
+ fs.unlinkSync(filePath);
275
+ console.log(`🗑️ Removed conflicting ${path.basename(filePath)}: ${filePath}`);
276
+ }
277
+ catch (err) {
278
+ console.warn(`⚠️ Could not remove ${filePath}:`, err);
279
+ }
280
+ }
281
+ function removeConflictingInterceptorFiles(projectPath, keepPath) {
282
+ const candidates = [
283
+ path.join(projectPath, 'proxy.ts'),
284
+ path.join(projectPath, 'src', 'proxy.ts'),
285
+ path.join(projectPath, 'proxy.js'),
286
+ path.join(projectPath, 'src', 'proxy.js'),
287
+ path.join(projectPath, 'middleware.ts'),
288
+ path.join(projectPath, 'src', 'middleware.ts'),
289
+ ];
290
+ for (const filePath of candidates) {
291
+ if (path.resolve(filePath) === path.resolve(keepPath))
292
+ continue;
293
+ removeFileIfExists(filePath);
294
+ }
267
295
  }
@@ -75,7 +75,7 @@ import type { NextRequest } from 'next/server';
75
75
  /**
76
76
  * EGDesk Database Proxy (Next.js 16+)
77
77
  *
78
- * Intercepts __user_data_proxy, __browser_recording_proxy, __internal_knowledge_proxy, __company_research_proxy, __ai_center_proxy, __korean_law_proxy, __seo_proxy, __ssl_proxy, __local_agent_proxy, __pageindex_proxy, __egdesk_config_proxy, __ai_caller_proxy, and __kakao_proxy requests
78
+ * Intercepts __user_data_proxy, __browser_recording_proxy, __internal_knowledge_proxy, __company_research_proxy, __ai_center_proxy, __korean_law_proxy, __seo_proxy, __ssl_proxy, __local_agent_proxy, __pageindex_proxy, __drive_proxy, __knowledge_wiki_proxy, __egdesk_config_proxy, __ai_caller_proxy, __kakao_proxy, and __phone_proxy requests
79
79
  * and forwards them to the EGDesk MCP HTTP server. This avoids CORS in local and tunneled environments.
80
80
  *
81
81
  * Generated by @egdesk/next-api-plugin
@@ -318,6 +318,50 @@ export async function proxy(request: NextRequest) {
318
318
  }
319
319
  }
320
320
 
321
+ if (pathname.includes('__drive_proxy')) {
322
+ try {
323
+ const body = await request.text();
324
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
325
+
326
+ const response = await fetch(\`\${apiUrl}/drive/tools/call\`, {
327
+ method: 'POST',
328
+ headers: buildEgdeskHeaders(),
329
+ body,
330
+ });
331
+
332
+ const result = await response.json();
333
+
334
+ return NextResponse.json(result, { status: response.status });
335
+ } catch (error: any) {
336
+ return NextResponse.json(
337
+ { error: 'Proxy error', message: error.message },
338
+ { status: 500 }
339
+ );
340
+ }
341
+ }
342
+
343
+ if (pathname.includes('__knowledge_wiki_proxy')) {
344
+ try {
345
+ const body = await request.text();
346
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
347
+
348
+ const response = await fetch(\`\${apiUrl}/knowledge-wiki/tools/call\`, {
349
+ method: 'POST',
350
+ headers: buildEgdeskHeaders(),
351
+ body,
352
+ });
353
+
354
+ const result = await response.json();
355
+
356
+ return NextResponse.json(result, { status: response.status });
357
+ } catch (error: any) {
358
+ return NextResponse.json(
359
+ { error: 'Proxy error', message: error.message },
360
+ { status: 500 }
361
+ );
362
+ }
363
+ }
364
+
321
365
  if (pathname.includes('__kakao_proxy')) {
322
366
  try {
323
367
  const body = await request.text();
@@ -340,6 +384,28 @@ export async function proxy(request: NextRequest) {
340
384
  }
341
385
  }
342
386
 
387
+ if (pathname.includes('__phone_proxy')) {
388
+ try {
389
+ const body = await request.text();
390
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
391
+
392
+ const response = await fetch(\`\${apiUrl}/phone/tools/call\`, {
393
+ method: 'POST',
394
+ headers: buildEgdeskHeaders(),
395
+ body,
396
+ });
397
+
398
+ const result = await response.json();
399
+
400
+ return NextResponse.json(result, { status: response.status });
401
+ } catch (error: any) {
402
+ return NextResponse.json(
403
+ { error: 'Proxy error', message: error.message },
404
+ { status: 500 }
405
+ );
406
+ }
407
+ }
408
+
343
409
  if (pathname.includes('__egdesk_config_proxy')) {
344
410
  try {
345
411
  const body = await request.text();
@@ -392,7 +458,7 @@ export const config = {
392
458
  matcher: [
393
459
  /*
394
460
  * Match all paths except static assets
395
- * The proxy function filters for __user_data_proxy / __browser_recording_proxy / __internal_knowledge_proxy / __company_research_proxy / __ai_center_proxy / __korean_law_proxy / __seo_proxy / __ssl_proxy / __local_agent_proxy / __pageindex_proxy / __egdesk_config_proxy / __ai_caller_proxy / __kakao_proxy
461
+ * The proxy function filters for __user_data_proxy / __browser_recording_proxy / __internal_knowledge_proxy / __company_research_proxy / __ai_center_proxy / __korean_law_proxy / __seo_proxy / __ssl_proxy / __local_agent_proxy / __pageindex_proxy / __drive_proxy / __knowledge_wiki_proxy / __egdesk_config_proxy / __ai_caller_proxy / __kakao_proxy / __phone_proxy
396
462
  */
397
463
  '/:path*',
398
464
  ],
@@ -400,4 +466,42 @@ export const config = {
400
466
  `;
401
467
  fs.writeFileSync(proxyPath, proxyContent.replace(/\r?\n/g, os.EOL), 'utf-8');
402
468
  console.log(`✅ Generated ${proxyPath}`);
469
+ // Next.js 16+ errors if both middleware.ts and proxy.ts exist.
470
+ removeConflictingInterceptorFiles(projectPath, 'proxy', proxyPath);
471
+ }
472
+ function removeFileIfExists(filePath, label) {
473
+ if (!fs.existsSync(filePath))
474
+ return;
475
+ try {
476
+ fs.unlinkSync(filePath);
477
+ console.log(`🗑️ Removed conflicting ${label}: ${filePath}`);
478
+ }
479
+ catch (err) {
480
+ console.warn(`⚠️ Could not remove ${filePath}:`, err);
481
+ }
482
+ }
483
+ /** Drop the other interceptor convention (and duplicates in root vs src/). */
484
+ function removeConflictingInterceptorFiles(projectPath, keep, keepPath) {
485
+ const candidates = keep === 'proxy'
486
+ ? [
487
+ path.join(projectPath, 'middleware.ts'),
488
+ path.join(projectPath, 'src', 'middleware.ts'),
489
+ path.join(projectPath, 'middleware.js'),
490
+ path.join(projectPath, 'src', 'middleware.js'),
491
+ path.join(projectPath, 'proxy.ts'),
492
+ path.join(projectPath, 'src', 'proxy.ts'),
493
+ ]
494
+ : [
495
+ path.join(projectPath, 'proxy.ts'),
496
+ path.join(projectPath, 'src', 'proxy.ts'),
497
+ path.join(projectPath, 'proxy.js'),
498
+ path.join(projectPath, 'src', 'proxy.js'),
499
+ path.join(projectPath, 'middleware.ts'),
500
+ path.join(projectPath, 'src', 'middleware.ts'),
501
+ ];
502
+ for (const filePath of candidates) {
503
+ if (path.resolve(filePath) === path.resolve(keepPath))
504
+ continue;
505
+ removeFileIfExists(filePath, path.basename(filePath));
506
+ }
403
507
  }
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.18";
11
+ export declare const COMPATIBLE_APP_VERSION = "1.4.28";
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.18';
49
+ exports.COMPATIBLE_APP_VERSION = '1.4.28';
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.12",
3
+ "version": "1.5.14",
4
4
  "description": "Next.js plugin for EGDesk database proxy integration",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",