@egdesk/next-api-plugin 1.5.6 → 1.5.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/generate-helpers.d.ts +5 -1
- package/dist/generate-helpers.js +559 -4
- package/dist/generate-middleware.js +33 -1
- package/dist/generate-proxy.js +68 -2
- package/dist/index.d.ts +8 -1
- package/dist/index.js +104 -7
- package/dist/setup-userdata.js +30 -31
- package/package.json +8 -1
- package/src/cli.ts +0 -63
- package/src/generate-api-wrapper.ts +0 -69
- package/src/generate-helpers.ts +0 -1829
- package/src/generate-middleware.ts +0 -206
- package/src/generate-proxy.ts +0 -308
- package/src/index.ts +0 -144
- package/src/setup-userdata.ts +0 -373
- package/tsconfig.json +0 -18
|
@@ -28,4 +28,8 @@ export declare function ensureSchemaFile(projectPath: string, tables: SchemaTabl
|
|
|
28
28
|
/**
|
|
29
29
|
* Generate egdesk-helpers.ts file
|
|
30
30
|
*/
|
|
31
|
-
export
|
|
31
|
+
export interface GenerateHelpersOptions {
|
|
32
|
+
/** Google/Gemini API key names saved in EGDesk AI Keys Manager */
|
|
33
|
+
apiKeyNames?: string[];
|
|
34
|
+
}
|
|
35
|
+
export declare function generateHelpers(projectPath: string, options?: GenerateHelpersOptions): void;
|
package/dist/generate-helpers.js
CHANGED
|
@@ -132,10 +132,7 @@ function ensureSchemaFile(projectPath, tables) {
|
|
|
132
132
|
tableCount: userTables.length,
|
|
133
133
|
};
|
|
134
134
|
}
|
|
135
|
-
|
|
136
|
-
* Generate egdesk-helpers.ts file
|
|
137
|
-
*/
|
|
138
|
-
function generateHelpers(projectPath) {
|
|
135
|
+
function generateHelpers(projectPath, options = {}) {
|
|
139
136
|
const helperPath = path.join(projectPath, 'egdesk-helpers.ts');
|
|
140
137
|
const helperContent = `/**
|
|
141
138
|
* EGDesk Helper Functions for Next.js
|
|
@@ -489,6 +486,351 @@ export async function renameTable(
|
|
|
489
486
|
});
|
|
490
487
|
}
|
|
491
488
|
|
|
489
|
+
// ==========================================
|
|
490
|
+
// FILE STORAGE HELPERS
|
|
491
|
+
// ==========================================
|
|
492
|
+
|
|
493
|
+
/**
|
|
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.
|
|
497
|
+
*/
|
|
498
|
+
export async function uploadFile(
|
|
499
|
+
tableName: string,
|
|
500
|
+
rowId: number,
|
|
501
|
+
columnName: string,
|
|
502
|
+
filename: string,
|
|
503
|
+
data: string,
|
|
504
|
+
options: {
|
|
505
|
+
mimeType?: string;
|
|
506
|
+
forceStorageType?: 'blob' | 'file';
|
|
507
|
+
compress?: boolean;
|
|
508
|
+
} = {}
|
|
509
|
+
) {
|
|
510
|
+
return callUserDataTool('user_data_upload_file', {
|
|
511
|
+
tableName,
|
|
512
|
+
rowId,
|
|
513
|
+
columnName,
|
|
514
|
+
filename,
|
|
515
|
+
data,
|
|
516
|
+
...options
|
|
517
|
+
});
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/**
|
|
521
|
+
* Download a file from a user data table row.
|
|
522
|
+
* Look up by fileId, or by (tableName, rowId, columnName).
|
|
523
|
+
*/
|
|
524
|
+
export async function downloadFile(options: {
|
|
525
|
+
fileId?: string;
|
|
526
|
+
tableName?: string;
|
|
527
|
+
rowId?: number;
|
|
528
|
+
columnName?: string;
|
|
529
|
+
}) {
|
|
530
|
+
return callUserDataTool('user_data_download_file', options);
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/**
|
|
534
|
+
* Delete a file from a user data table row.
|
|
535
|
+
* Look up by fileId, or by (tableName, rowId, columnName).
|
|
536
|
+
*/
|
|
537
|
+
export async function deleteFile(options: {
|
|
538
|
+
fileId?: string;
|
|
539
|
+
tableName?: string;
|
|
540
|
+
rowId?: number;
|
|
541
|
+
columnName?: string;
|
|
542
|
+
}) {
|
|
543
|
+
return callUserDataTool('user_data_delete_file', options);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/**
|
|
547
|
+
* List all files attached to a specific table row.
|
|
548
|
+
*/
|
|
549
|
+
export async function listFiles(tableName: string, rowId: number) {
|
|
550
|
+
return callUserDataTool('user_data_list_files', { tableName, rowId });
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/**
|
|
554
|
+
* Get file storage statistics for all tables or a specific table.
|
|
555
|
+
*/
|
|
556
|
+
export async function getFileStats(tableName?: string) {
|
|
557
|
+
return callUserDataTool('user_data_get_file_stats', {
|
|
558
|
+
...(tableName != null ? { tableName } : {})
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
// ==========================================
|
|
563
|
+
// USER DATA REAL-TIME SUBSCRIPTIONS
|
|
564
|
+
// ==========================================
|
|
565
|
+
|
|
566
|
+
export interface UserDataChangeEvent {
|
|
567
|
+
kind: 'schema' | 'data';
|
|
568
|
+
action: 'create_table' | 'delete_table' | 'rename_table' | 'insert' | 'update' | 'delete';
|
|
569
|
+
tableName?: string;
|
|
570
|
+
tableId?: string;
|
|
571
|
+
source?: 'mcp' | 'ipc' | 'sync' | 'import';
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* Subscribe to real-time user-data change events via SSE.
|
|
576
|
+
* Works in browser only (uses EventSource).
|
|
577
|
+
*
|
|
578
|
+
* @param callback Called whenever a user-data mutation occurs (insert, update, delete, schema change).
|
|
579
|
+
* @param options Optional filter: only fire for a specific table or event kind.
|
|
580
|
+
* @returns An unsubscribe function that closes the SSE connection.
|
|
581
|
+
*
|
|
582
|
+
* @example
|
|
583
|
+
* // Listen for all changes
|
|
584
|
+
* const unsub = onUserDataChanged((event) => {
|
|
585
|
+
* console.log(\`\${event.action} on \${event.tableName}\`);
|
|
586
|
+
* });
|
|
587
|
+
*
|
|
588
|
+
* // Listen only for changes to "orders" table
|
|
589
|
+
* const unsub = onUserDataChanged(
|
|
590
|
+
* (event) => { refreshOrders(); },
|
|
591
|
+
* { tableName: 'orders' }
|
|
592
|
+
* );
|
|
593
|
+
*
|
|
594
|
+
* // Cleanup
|
|
595
|
+
* unsub();
|
|
596
|
+
*/
|
|
597
|
+
export function onUserDataChanged(
|
|
598
|
+
callback: (event: UserDataChangeEvent) => void,
|
|
599
|
+
options?: { tableName?: string; kind?: 'schema' | 'data' }
|
|
600
|
+
): () => void {
|
|
601
|
+
if (typeof window === 'undefined' || typeof EventSource === 'undefined') {
|
|
602
|
+
console.warn('onUserDataChanged() is only available in the browser.');
|
|
603
|
+
return () => {};
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
const apiUrl = EGDESK_CONFIG.apiUrl || '';
|
|
607
|
+
const apiKey = EGDESK_CONFIG.apiKey || '';
|
|
608
|
+
const sseUrl = apiKey ? \`\${apiUrl}/user-data/sse?key=\${encodeURIComponent(apiKey)}\` : \`\${apiUrl}/user-data/sse\`;
|
|
609
|
+
const es = new EventSource(sseUrl);
|
|
610
|
+
|
|
611
|
+
es.addEventListener('message', (e: MessageEvent) => {
|
|
612
|
+
try {
|
|
613
|
+
const msg = JSON.parse(e.data);
|
|
614
|
+
if (msg.method !== 'egdesk/user-data-changed') return;
|
|
615
|
+
|
|
616
|
+
const event: UserDataChangeEvent = msg.params;
|
|
617
|
+
if (options?.tableName && event.tableName !== options.tableName) return;
|
|
618
|
+
if (options?.kind && event.kind !== options.kind) return;
|
|
619
|
+
|
|
620
|
+
callback(event);
|
|
621
|
+
} catch {
|
|
622
|
+
// ignore malformed messages
|
|
623
|
+
}
|
|
624
|
+
});
|
|
625
|
+
|
|
626
|
+
es.addEventListener('error', () => {
|
|
627
|
+
console.warn('[EGDesk] User-data SSE connection error — will auto-reconnect.');
|
|
628
|
+
});
|
|
629
|
+
|
|
630
|
+
return () => { es.close(); };
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// ==========================================
|
|
634
|
+
// KAKAO CHANNEL / CHATBOT HELPERS
|
|
635
|
+
// ==========================================
|
|
636
|
+
//
|
|
637
|
+
// Login model (read this before using \`service\`):
|
|
638
|
+
// - One Kakao account (KakaoTalk QR). EGDesk stores cookies in a persistent Chrome
|
|
639
|
+
// profile per \`profileName\`.
|
|
640
|
+
// - business.kakao.com and chatbot.kakao.com share that profile — scan QR once.
|
|
641
|
+
// - \`service\` on beginKakaoLogin only picks which admin site opens first for the QR
|
|
642
|
+
// flow; it is NOT a separate login type.
|
|
643
|
+
// - list/create tools reuse the profile and skip QR when already logged in.
|
|
644
|
+
|
|
645
|
+
/**
|
|
646
|
+
* Call EGDesk Kakao MCP tool.
|
|
647
|
+
*
|
|
648
|
+
* Kakao tools drive browser automation for Kakao Business and chatbot admin,
|
|
649
|
+
* so the \`kakao\` MCP service must be enabled in EGDesk before use.
|
|
650
|
+
*
|
|
651
|
+
* All tools for a given \`profileName\` share one Chrome profile and one Kakao login.
|
|
652
|
+
*/
|
|
653
|
+
export async function callKakaoTool(
|
|
654
|
+
toolName: string,
|
|
655
|
+
args: Record<string, any> = {}
|
|
656
|
+
): Promise<any> {
|
|
657
|
+
const body = JSON.stringify({ tool: toolName, arguments: args });
|
|
658
|
+
|
|
659
|
+
const isServer = typeof window === 'undefined';
|
|
660
|
+
|
|
661
|
+
let response: Response;
|
|
662
|
+
if (isServer) {
|
|
663
|
+
const apiUrl =
|
|
664
|
+
(typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
|
|
665
|
+
EGDESK_CONFIG.apiUrl;
|
|
666
|
+
response = await fetch(\`\${apiUrl}/kakao/tools/call\`, {
|
|
667
|
+
method: 'POST',
|
|
668
|
+
headers: buildServerEgdeskHeaders(),
|
|
669
|
+
body
|
|
670
|
+
});
|
|
671
|
+
} else {
|
|
672
|
+
response = await apiFetch('/__kakao_proxy', {
|
|
673
|
+
method: 'POST',
|
|
674
|
+
headers: { 'Content-Type': 'application/json' },
|
|
675
|
+
body
|
|
676
|
+
});
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
return parseEgdeskMcpToolResponse(response);
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
export type KakaoLoginSession = {
|
|
683
|
+
success: boolean;
|
|
684
|
+
loginId: string;
|
|
685
|
+
/** Admin site opened for this QR flow (\`chatbot\` or \`business\`) — same Kakao account either way. */
|
|
686
|
+
service: 'business' | 'chatbot';
|
|
687
|
+
profileName: string;
|
|
688
|
+
profileDir: string;
|
|
689
|
+
status: 'starting' | 'waiting_for_qr' | 'logged_in' | 'expired' | 'failed' | 'closed';
|
|
690
|
+
message?: string;
|
|
691
|
+
error?: string;
|
|
692
|
+
qrImageDataUrl?: string;
|
|
693
|
+
createdAt: string;
|
|
694
|
+
updatedAt: string;
|
|
695
|
+
expiresAt: string;
|
|
696
|
+
};
|
|
697
|
+
|
|
698
|
+
/**
|
|
699
|
+
* Start Kakao QR login in a persistent EGDesk Chrome profile.
|
|
700
|
+
*
|
|
701
|
+
* One Kakao account, one session: scanning the QR logs into KakaoTalk/accounts.kakao.com.
|
|
702
|
+
* Cookies are saved under \`profileName\` and shared by business.kakao.com and
|
|
703
|
+
* chatbot.kakao.com — you do not need separate logins for channels vs bots.
|
|
704
|
+
*
|
|
705
|
+
* \`options.service\` only chooses which admin site EGDesk navigates to before showing
|
|
706
|
+
* the QR code (\`'chatbot'\` → chatbot.kakao.com, \`'business'\` → business.kakao.com).
|
|
707
|
+
*
|
|
708
|
+
* Returns \`loginId\` and \`qrImageDataUrl\`. Poll with \`kakaoLoginStatus()\` until
|
|
709
|
+
* \`status\` is \`'logged_in'\`, or call \`closeKakaoLogin()\` to cancel.
|
|
710
|
+
*/
|
|
711
|
+
export async function beginKakaoLogin(
|
|
712
|
+
profileName: string,
|
|
713
|
+
options: {
|
|
714
|
+
/** Entry URL for the QR flow. Defaults to \`'chatbot'\`. Same Kakao login either way. */
|
|
715
|
+
service?: 'business' | 'chatbot';
|
|
716
|
+
/** Run browser headless. Defaults to true; pass false to show Chrome. */
|
|
717
|
+
headless?: boolean;
|
|
718
|
+
waitMs?: number;
|
|
719
|
+
} = {}
|
|
720
|
+
): Promise<KakaoLoginSession> {
|
|
721
|
+
return callKakaoTool('kakao_begin_login', { profileName, ...options });
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
/** Poll Kakao QR login status by loginId. */
|
|
725
|
+
export async function kakaoLoginStatus(
|
|
726
|
+
profileName: string,
|
|
727
|
+
loginId: string
|
|
728
|
+
): Promise<KakaoLoginSession> {
|
|
729
|
+
return callKakaoTool('kakao_login_status', { profileName, loginId });
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/** Close a pending Kakao login browser session. */
|
|
733
|
+
export async function closeKakaoLogin(
|
|
734
|
+
profileName: string,
|
|
735
|
+
loginId: string
|
|
736
|
+
): Promise<{ success: boolean; loginId: string; message?: string; error?: string }> {
|
|
737
|
+
return callKakaoTool('kakao_close_login', { profileName, loginId });
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
export type KakaoChannel = {
|
|
741
|
+
id: string;
|
|
742
|
+
name: string;
|
|
743
|
+
searchId: string;
|
|
744
|
+
adminUrl: string;
|
|
745
|
+
channelUrl: string;
|
|
746
|
+
chatUrl?: string;
|
|
747
|
+
isPublic?: boolean;
|
|
748
|
+
searchEnabled?: boolean;
|
|
749
|
+
connectedBotName?: string;
|
|
750
|
+
connectedBotId?: string;
|
|
751
|
+
connectedChatbots?: Array<{ name: string; id?: string }>;
|
|
752
|
+
status?: string;
|
|
753
|
+
detailError?: string;
|
|
754
|
+
};
|
|
755
|
+
|
|
756
|
+
export type KakaoBot = {
|
|
757
|
+
id: string;
|
|
758
|
+
name: string;
|
|
759
|
+
status?: string;
|
|
760
|
+
isInactive?: boolean;
|
|
761
|
+
page: number;
|
|
762
|
+
index: number;
|
|
763
|
+
callbackStatus?: Record<string, any>;
|
|
764
|
+
};
|
|
765
|
+
|
|
766
|
+
/** List Kakao Business channels. Reuses the profile session; shows QR only if not logged in. */
|
|
767
|
+
export async function listKakaoChannels(
|
|
768
|
+
profileName: string,
|
|
769
|
+
options: { enrichDetails?: boolean } = {}
|
|
770
|
+
) {
|
|
771
|
+
return callKakaoTool('kakao_list_channels', { profileName, ...options });
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/** List Kakao chatbot admin bots. Reuses the profile session; shows QR only if not logged in. */
|
|
775
|
+
export async function listKakaoBots(profileName: string) {
|
|
776
|
+
return callKakaoTool('kakao_list_bots', { profileName });
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
/** List both Kakao Business channels and chatbot admin bots. */
|
|
780
|
+
export async function listKakaoResources(
|
|
781
|
+
profileName: string,
|
|
782
|
+
options: { enrichDetails?: boolean } = {}
|
|
783
|
+
) {
|
|
784
|
+
return callKakaoTool('kakao_list_resources', { profileName, ...options });
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
/** Persist a selected Kakao channel into the EGDesk profile metadata. */
|
|
788
|
+
export async function selectKakaoChannel(profileName: string, channel: KakaoChannel) {
|
|
789
|
+
return callKakaoTool('kakao_select_channel', { profileName, channel });
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
/** Webhook URLs, API key, identity fields, and setup modes for BYO AI chatbots. */
|
|
793
|
+
export async function getKakaoWebhookInfo(profileName: string) {
|
|
794
|
+
return callKakaoTool('kakao_get_webhook_info', { profileName });
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/** Check whether Kakao bot skill/callback URLs match the current EGDesk tunnel. */
|
|
798
|
+
export async function checkKakaoCallbackStatuses(
|
|
799
|
+
profileName: string,
|
|
800
|
+
options: { bots?: KakaoBot[]; channels?: KakaoChannel[] } = {}
|
|
801
|
+
) {
|
|
802
|
+
return callKakaoTool('kakao_check_callback_statuses', { profileName, ...options });
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
/** Repair Kakao bot skill URL, headers, fallback link, and deploy the bot. */
|
|
806
|
+
export async function repairKakaoCallbackSetup(
|
|
807
|
+
profileName: string,
|
|
808
|
+
options: { bots?: KakaoBot[]; channels?: KakaoChannel[] } = {}
|
|
809
|
+
) {
|
|
810
|
+
return callKakaoTool('kakao_repair_callback_setup', { profileName, ...options });
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
/** Create or reuse a Kakao Business channel. Reuses profile login; may show QR if needed. */
|
|
814
|
+
export async function createKakaoChannel(options: {
|
|
815
|
+
profileName: string;
|
|
816
|
+
channelName: string;
|
|
817
|
+
searchId: string;
|
|
818
|
+
reuseExisting?: boolean;
|
|
819
|
+
}) {
|
|
820
|
+
return callKakaoTool('kakao_create_channel', options);
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
/** Create or reuse a Kakao chatbot, configure skill/callback, link fallback block, and deploy. Reuses profile login. */
|
|
824
|
+
export async function createKakaoBot(options: {
|
|
825
|
+
profileName: string;
|
|
826
|
+
botName: string;
|
|
827
|
+
channelSearchId: string;
|
|
828
|
+
skillUrl?: string;
|
|
829
|
+
reuseExisting?: boolean;
|
|
830
|
+
}) {
|
|
831
|
+
return callKakaoTool('kakao_create_bot', options);
|
|
832
|
+
}
|
|
833
|
+
|
|
492
834
|
// ==========================================
|
|
493
835
|
// FINANCEHUB HELPERS
|
|
494
836
|
// ==========================================
|
|
@@ -629,6 +971,15 @@ export async function listHometaxConnections() {
|
|
|
629
971
|
return callFinanceHubTool('financehub_list_hometax_connections', {});
|
|
630
972
|
}
|
|
631
973
|
|
|
974
|
+
/**
|
|
975
|
+
* List registered Hometax client companies for a business, including sales stats and saved risk data.
|
|
976
|
+
*/
|
|
977
|
+
export async function listHometaxClients(options: {
|
|
978
|
+
businessNumber?: string;
|
|
979
|
+
} = {}) {
|
|
980
|
+
return callFinanceHubTool('financehub_list_hometax_clients', options);
|
|
981
|
+
}
|
|
982
|
+
|
|
632
983
|
/**
|
|
633
984
|
* Query electronic tax invoices synced from Hometax (tax_invoices table)
|
|
634
985
|
*/
|
|
@@ -1763,6 +2114,123 @@ export async function callLocalAgent(prompt: string, options: LocalAgentCallOpti
|
|
|
1763
2114
|
return callLocalAgentTool('local_agent_call', { prompt, ...options });
|
|
1764
2115
|
}
|
|
1765
2116
|
|
|
2117
|
+
// ==========================================
|
|
2118
|
+
// AI Caller (MCP) — Gemini with token tracking
|
|
2119
|
+
// ==========================================
|
|
2120
|
+
|
|
2121
|
+
/**
|
|
2122
|
+
* Call EGDesk AI Caller MCP tool (Gemini API with token usage tracking).
|
|
2123
|
+
*
|
|
2124
|
+
* Every call is logged to SQLite for rate/cost tracking.
|
|
2125
|
+
*
|
|
2126
|
+
* - Server: \`POST {apiUrl}/ai-caller/tools/call\`
|
|
2127
|
+
* - Client: \`POST /api/ai-caller\` via apiFetch (see app/api/ai-caller/route.ts)
|
|
2128
|
+
*/
|
|
2129
|
+
export async function callAiCallerTool(
|
|
2130
|
+
toolName: string,
|
|
2131
|
+
args: Record<string, any> = {}
|
|
2132
|
+
): Promise<any> {
|
|
2133
|
+
const body = JSON.stringify({ tool: toolName, arguments: args });
|
|
2134
|
+
|
|
2135
|
+
const isServer = typeof window === 'undefined';
|
|
2136
|
+
|
|
2137
|
+
let response: Response;
|
|
2138
|
+
if (isServer) {
|
|
2139
|
+
const apiUrl =
|
|
2140
|
+
(typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
|
|
2141
|
+
EGDESK_CONFIG.apiUrl;
|
|
2142
|
+
response = await fetch(\`\${apiUrl}/ai-caller/tools/call\`, {
|
|
2143
|
+
method: 'POST',
|
|
2144
|
+
headers: buildServerEgdeskHeaders(),
|
|
2145
|
+
body
|
|
2146
|
+
});
|
|
2147
|
+
} else {
|
|
2148
|
+
response = await apiFetch('/api/ai-caller', {
|
|
2149
|
+
method: 'POST',
|
|
2150
|
+
headers: { 'Content-Type': 'application/json' },
|
|
2151
|
+
body
|
|
2152
|
+
});
|
|
2153
|
+
}
|
|
2154
|
+
|
|
2155
|
+
return parseEgdeskMcpToolResponse(response);
|
|
2156
|
+
}
|
|
2157
|
+
|
|
2158
|
+
/** Known API key names discovered at setup time from EGDesk AI Keys Manager */
|
|
2159
|
+
export const AI_KEY_NAMES = [${(options.apiKeyNames ?? []).map(n => `'${n}'`).join(', ')}] as const;
|
|
2160
|
+
|
|
2161
|
+
export type AiCallerCallOptions = {
|
|
2162
|
+
systemPrompt?: string;
|
|
2163
|
+
model?: string;
|
|
2164
|
+
temperature?: number;
|
|
2165
|
+
maxOutputTokens?: number;
|
|
2166
|
+
caller?: string;
|
|
2167
|
+
responseSchema?: Record<string, any>;
|
|
2168
|
+
/** Base64 strings (raw or data URLs) */
|
|
2169
|
+
images?: string[];
|
|
2170
|
+
/** Absolute paths — images, text files, .pdf, .docx, video (same rules as filesystem MCP) */
|
|
2171
|
+
filePaths?: string[];
|
|
2172
|
+
/** Inline file uploads when callers cannot use filePaths */
|
|
2173
|
+
files?: Array<{
|
|
2174
|
+
name: string;
|
|
2175
|
+
content: string;
|
|
2176
|
+
encoding?: 'utf8' | 'base64';
|
|
2177
|
+
mimeType?: string;
|
|
2178
|
+
}>;
|
|
2179
|
+
/** Select a specific Google API key by name (as saved in EGDesk AI Keys Manager). Leave empty to use the default key. */
|
|
2180
|
+
keyName?: ${(options.apiKeyNames ?? []).length > 0
|
|
2181
|
+
? (options.apiKeyNames.map(n => `'${n}'`).join(' | ') + ' | (string & {})')
|
|
2182
|
+
: 'string'};
|
|
2183
|
+
};
|
|
2184
|
+
|
|
2185
|
+
/**
|
|
2186
|
+
* Call Gemini and log token usage. Returns the AI response plus a usage summary.
|
|
2187
|
+
* Supports images, filePaths, and inline files (documents, text, video frames).
|
|
2188
|
+
*/
|
|
2189
|
+
export async function callAiCaller(prompt: string, options: AiCallerCallOptions = {}) {
|
|
2190
|
+
return callAiCallerTool('ai_caller_call', { prompt, ...options });
|
|
2191
|
+
}
|
|
2192
|
+
|
|
2193
|
+
export type AiCallerUsageOptions = {
|
|
2194
|
+
caller?: string;
|
|
2195
|
+
model?: string;
|
|
2196
|
+
since?: string;
|
|
2197
|
+
until?: string;
|
|
2198
|
+
groupBy?: 'caller' | 'model' | 'day' | 'hour';
|
|
2199
|
+
};
|
|
2200
|
+
|
|
2201
|
+
/**
|
|
2202
|
+
* Get aggregated token usage stats. Supports filtering and grouping.
|
|
2203
|
+
*/
|
|
2204
|
+
export async function getAiCallerUsage(options: AiCallerUsageOptions = {}) {
|
|
2205
|
+
return callAiCallerTool('ai_caller_get_usage', options);
|
|
2206
|
+
}
|
|
2207
|
+
|
|
2208
|
+
export type AiCallerLogsOptions = {
|
|
2209
|
+
caller?: string;
|
|
2210
|
+
model?: string;
|
|
2211
|
+
since?: string;
|
|
2212
|
+
limit?: number;
|
|
2213
|
+
};
|
|
2214
|
+
|
|
2215
|
+
/**
|
|
2216
|
+
* Get raw AI call log entries, newest first.
|
|
2217
|
+
*/
|
|
2218
|
+
export async function getAiCallerLogs(options: AiCallerLogsOptions = {}) {
|
|
2219
|
+
return callAiCallerTool('ai_caller_get_logs', options);
|
|
2220
|
+
}
|
|
2221
|
+
|
|
2222
|
+
export type AiCallerModelsResult = {
|
|
2223
|
+
models: string[];
|
|
2224
|
+
defaultModel: string;
|
|
2225
|
+
};
|
|
2226
|
+
|
|
2227
|
+
/**
|
|
2228
|
+
* List Gemini models available for text generation, fetched live from the Google API via EGDesk.
|
|
2229
|
+
*/
|
|
2230
|
+
export async function listAiCallerModels(): Promise<AiCallerModelsResult> {
|
|
2231
|
+
return callAiCallerTool('ai_caller_list_models', {});
|
|
2232
|
+
}
|
|
2233
|
+
|
|
1766
2234
|
// ==========================================
|
|
1767
2235
|
// PageIndex (MCP) — PDF RAG
|
|
1768
2236
|
// ==========================================
|
|
@@ -1833,6 +2301,93 @@ export async function getPageIndexPages(docId: string, pages: string) {
|
|
|
1833
2301
|
export async function deletePageIndexDocument(docId: string) {
|
|
1834
2302
|
return callPageIndexTool('pageindex_delete_document', { doc_id: docId });
|
|
1835
2303
|
}
|
|
2304
|
+
|
|
2305
|
+
// ==========================================
|
|
2306
|
+
// EGDesk Config (MCP) — Gemini / Google API keys
|
|
2307
|
+
// ==========================================
|
|
2308
|
+
|
|
2309
|
+
/**
|
|
2310
|
+
* Call EGDesk Config MCP tool (Gemini keys from AI Keys Manager).
|
|
2311
|
+
*
|
|
2312
|
+
* - Server: \`POST {apiUrl}/egdesk-config/tools/call\`
|
|
2313
|
+
* - Client: \`POST /__egdesk_config_proxy\` (see proxy.ts / middleware)
|
|
2314
|
+
*/
|
|
2315
|
+
export async function callEgdeskConfigTool(
|
|
2316
|
+
toolName: string,
|
|
2317
|
+
args: Record<string, any> = {}
|
|
2318
|
+
): Promise<any> {
|
|
2319
|
+
const body = JSON.stringify({ tool: toolName, arguments: args });
|
|
2320
|
+
|
|
2321
|
+
const isServer = typeof window === 'undefined';
|
|
2322
|
+
|
|
2323
|
+
let response: Response;
|
|
2324
|
+
if (isServer) {
|
|
2325
|
+
const apiUrl =
|
|
2326
|
+
(typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
|
|
2327
|
+
EGDESK_CONFIG.apiUrl;
|
|
2328
|
+
response = await fetch(\`\${apiUrl}/egdesk-config/tools/call\`, {
|
|
2329
|
+
method: 'POST',
|
|
2330
|
+
headers: buildServerEgdeskHeaders(),
|
|
2331
|
+
body
|
|
2332
|
+
});
|
|
2333
|
+
} else {
|
|
2334
|
+
response = await apiFetch('/__egdesk_config_proxy', {
|
|
2335
|
+
method: 'POST',
|
|
2336
|
+
headers: { 'Content-Type': 'application/json' },
|
|
2337
|
+
body
|
|
2338
|
+
});
|
|
2339
|
+
}
|
|
2340
|
+
|
|
2341
|
+
return parseEgdeskMcpToolResponse(response);
|
|
2342
|
+
}
|
|
2343
|
+
|
|
2344
|
+
/** Get the preferred API key EGDesk would use for an AI provider */
|
|
2345
|
+
export async function getApiKey(options: {
|
|
2346
|
+
provider?: 'google' | 'openai' | 'anthropic' | 'azure' | 'custom';
|
|
2347
|
+
keyId?: string;
|
|
2348
|
+
name?: string;
|
|
2349
|
+
apiKey?: string;
|
|
2350
|
+
} = {}) {
|
|
2351
|
+
return callEgdeskConfigTool('egdesk_get_api_key', options);
|
|
2352
|
+
}
|
|
2353
|
+
|
|
2354
|
+
/** Save an API key into EGDesk AI Keys Manager for a given provider */
|
|
2355
|
+
export async function setApiKey(options: {
|
|
2356
|
+
provider?: 'google' | 'openai' | 'anthropic' | 'azure' | 'custom';
|
|
2357
|
+
apiKey: string;
|
|
2358
|
+
name?: string;
|
|
2359
|
+
keyId?: string;
|
|
2360
|
+
setActive?: boolean;
|
|
2361
|
+
}) {
|
|
2362
|
+
return callEgdeskConfigTool('egdesk_set_api_key', options);
|
|
2363
|
+
}
|
|
2364
|
+
|
|
2365
|
+
/** List API keys in AI Keys Manager, optionally filtered by provider */
|
|
2366
|
+
export async function listApiKeys(options: {
|
|
2367
|
+
provider?: 'google' | 'openai' | 'anthropic' | 'azure' | 'custom';
|
|
2368
|
+
} = {}) {
|
|
2369
|
+
return callEgdeskConfigTool('egdesk_list_api_keys', options);
|
|
2370
|
+
}
|
|
2371
|
+
|
|
2372
|
+
/** Get the preferred Google/Gemini API key EGDesk would use */
|
|
2373
|
+
export async function getGeminiApiKey(options: { keyId?: string; name?: string; apiKey?: string } = {}) {
|
|
2374
|
+
return getApiKey({ provider: 'google', ...options });
|
|
2375
|
+
}
|
|
2376
|
+
|
|
2377
|
+
/** Save a Google/Gemini API key into EGDesk AI Keys Manager */
|
|
2378
|
+
export async function setGeminiApiKey(options: {
|
|
2379
|
+
apiKey: string;
|
|
2380
|
+
name?: string;
|
|
2381
|
+
keyId?: string;
|
|
2382
|
+
setActive?: boolean;
|
|
2383
|
+
}) {
|
|
2384
|
+
return setApiKey({ provider: 'google', ...options });
|
|
2385
|
+
}
|
|
2386
|
+
|
|
2387
|
+
/** List all Google/Gemini keys in AI Keys Manager */
|
|
2388
|
+
export async function listGeminiApiKeys() {
|
|
2389
|
+
return listApiKeys({ provider: 'google' });
|
|
2390
|
+
}
|
|
1836
2391
|
`;
|
|
1837
2392
|
fs.writeFileSync(helperPath, helperContent.replace(/\r?\n/g, os.EOL), 'utf-8');
|
|
1838
2393
|
console.log(`✅ Generated ${helperPath}`);
|
|
@@ -73,7 +73,7 @@ import type { NextRequest } from 'next/server';
|
|
|
73
73
|
/**
|
|
74
74
|
* EGDesk Database Proxy Middleware
|
|
75
75
|
*
|
|
76
|
-
* Intercepts __user_data_proxy, __browser_recording_proxy, __internal_knowledge_proxy, and
|
|
76
|
+
* Intercepts __user_data_proxy, __browser_recording_proxy, __internal_knowledge_proxy, __company_research_proxy, and __kakao_proxy requests
|
|
77
77
|
* and forwards them to the EGDesk MCP HTTP server.
|
|
78
78
|
* This allows CORS-free database access in both local and tunneled environments.
|
|
79
79
|
*
|
|
@@ -213,6 +213,38 @@ export async function middleware(request: NextRequest) {
|
|
|
213
213
|
}
|
|
214
214
|
}
|
|
215
215
|
|
|
216
|
+
if (pathname.includes('__kakao_proxy')) {
|
|
217
|
+
try {
|
|
218
|
+
const body = await request.text();
|
|
219
|
+
|
|
220
|
+
const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
|
|
221
|
+
const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
|
|
222
|
+
|
|
223
|
+
const headers: HeadersInit = {
|
|
224
|
+
'Content-Type': 'application/json',
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
if (apiKey) {
|
|
228
|
+
headers['X-Api-Key'] = apiKey;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const response = await fetch(\`\${apiUrl}/kakao/tools/call\`, {
|
|
232
|
+
method: 'POST',
|
|
233
|
+
headers,
|
|
234
|
+
body,
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
const result = await response.json();
|
|
238
|
+
|
|
239
|
+
return NextResponse.json(result, { status: response.status });
|
|
240
|
+
} catch (error: any) {
|
|
241
|
+
return NextResponse.json(
|
|
242
|
+
{ error: 'Proxy error', message: error.message },
|
|
243
|
+
{ status: 500 }
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
216
248
|
// Continue to next middleware or route
|
|
217
249
|
return NextResponse.next();
|
|
218
250
|
}
|