@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.
@@ -1,1829 +0,0 @@
1
- /**
2
- * Generate helper functions for EGDesk database access in Next.js
3
- *
4
- * Creates egdesk-helpers.ts with type-safe helper functions.
5
- */
6
-
7
- import * as fs from 'fs';
8
- import * as path from 'path';
9
- import * as os from 'os';
10
-
11
- /** Columns auto-managed by EGDesk — omit from committed seed schema. */
12
- const SYSTEM_SCHEMA_COLUMNS = new Set(['id', 'imported_at']);
13
-
14
- export interface SchemaTableDefinition {
15
- tableName: string;
16
- displayName: string;
17
- columns: string[];
18
- }
19
-
20
- function escapeTsString(value: string): string {
21
- return value.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
22
- }
23
-
24
- function schemaKeyForTable(tableName: string): string {
25
- const key = tableName.replace(/[^a-zA-Z0-9_]/g, '_');
26
- return /^[a-zA-Z_]/.test(key) ? key : `_${key}`;
27
- }
28
-
29
- /**
30
- * Format egdesk.schema.ts content — the committed, portable seed schema.
31
- */
32
- export function formatEgdeskSchemaFileContent(tables: SchemaTableDefinition[]): string {
33
- const tableEntries =
34
- tables.length === 0
35
- ? ` // example_table: {
36
- // name: 'example_table',
37
- // displayName: 'Example Table',
38
- // columns: ['name', 'created_at'],
39
- // columnCount: 2,
40
- // rowCount: 0,
41
- // },`
42
- : tables
43
- .map((table) => {
44
- const key = schemaKeyForTable(table.tableName);
45
- const userColumns = table.columns.filter((col) => !SYSTEM_SCHEMA_COLUMNS.has(col));
46
- const columns = userColumns.map((col) => `'${escapeTsString(col)}'`).join(', ');
47
- return ` ${key}: {
48
- name: '${escapeTsString(table.tableName)}',
49
- displayName: '${escapeTsString(table.displayName)}',
50
- columns: [${columns}],
51
- columnCount: ${userColumns.length},
52
- rowCount: 0,
53
- }`;
54
- })
55
- .join(',\n');
56
-
57
- return `/**
58
- * egdesk.schema.ts — committed seed schema
59
- *
60
- * COMMIT THIS FILE TO GIT.
61
- *
62
- * When someone opens this project in their EGDesk, these tables are created
63
- * automatically in their dev database on first server start.
64
- *
65
- * Unlike egdesk.config.ts (auto-generated, gitignored), this file is the
66
- * portable source of truth for your app's database structure.
67
- *
68
- * Edit this file when you add/remove tables or columns. Do NOT edit
69
- * egdesk.config.ts — EGDesk regenerates it from the live database.
70
- */
71
-
72
- export const TABLES = {
73
- ${tableEntries}
74
- } as const;
75
-
76
- export type TableName = keyof typeof TABLES;
77
- export const TABLE_NAMES = Object.keys(TABLES) as TableName[];
78
- `;
79
- }
80
-
81
- /**
82
- * Write egdesk.schema.ts to the project root.
83
- */
84
- export function generateSchemaFile(projectPath: string, tables: SchemaTableDefinition[]): void {
85
- const schemaPath = path.join(projectPath, 'egdesk.schema.ts');
86
- fs.writeFileSync(schemaPath, formatEgdeskSchemaFileContent(tables).replace(/\r?\n/g, os.EOL), 'utf-8');
87
- console.log(`✅ Generated ${schemaPath}`);
88
- }
89
-
90
- export type EnsureSchemaFileResult = {
91
- created: boolean;
92
- source: 'existing' | 'database' | 'template';
93
- tableCount: number;
94
- };
95
-
96
- /**
97
- * Create egdesk.schema.ts only when missing. Never overwrites an existing file.
98
- */
99
- export function ensureSchemaFile(
100
- projectPath: string,
101
- tables: SchemaTableDefinition[],
102
- ): EnsureSchemaFileResult {
103
- const schemaPath = path.join(projectPath, 'egdesk.schema.ts');
104
- if (fs.existsSync(schemaPath)) {
105
- return { created: false, source: 'existing', tableCount: tables.length };
106
- }
107
-
108
- const userTables = tables
109
- .map((table) => ({
110
- ...table,
111
- columns: table.columns.filter((col) => !SYSTEM_SCHEMA_COLUMNS.has(col)),
112
- }))
113
- .filter((table) => table.columns.length > 0);
114
-
115
- generateSchemaFile(projectPath, userTables);
116
- return {
117
- created: true,
118
- source: userTables.length > 0 ? 'database' : 'template',
119
- tableCount: userTables.length,
120
- };
121
- }
122
-
123
- /**
124
- * Generate egdesk-helpers.ts file
125
- */
126
- export function generateHelpers(projectPath: string): void {
127
- const helperPath = path.join(projectPath, 'egdesk-helpers.ts');
128
-
129
- const helperContent = `/**
130
- * EGDesk Helper Functions for Next.js
131
- *
132
- * Type-safe helpers for EGDesk user data, FinanceHub (banks, cards, Hometax, promissory notes),
133
- * internal knowledge / business identity / company research (MCP), Korean law (MCP), and browser recorder replay.
134
- * Works in both client and server components.
135
- *
136
- * Generated by @egdesk/next-api-plugin — do not edit by hand.
137
- *
138
- * Schema files:
139
- * - egdesk.schema.ts — committed seed schema (edit this; commit to git)
140
- * - egdesk.config.ts — auto-generated runtime snapshot (gitignored; do not edit)
141
- */
142
-
143
- import { EGDESK_CONFIG } from './egdesk.config';
144
-
145
- /**
146
- * Resolve EGDesk tunnel basePath for client-side fetch.
147
- * Next.js basePath does NOT apply to raw fetch() — prepend manually in production.
148
- */
149
- export function getEgdeskBasePath(): string {
150
- if (typeof window === 'undefined') {
151
- return (
152
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_BASE_PATH) ||
153
- (typeof process !== 'undefined' && process.env?.EGDESK_BASE_PATH) ||
154
- ''
155
- );
156
- }
157
-
158
- const fromEnv =
159
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_BASE_PATH) || '';
160
- if (fromEnv) return fromEnv;
161
-
162
- // Fallback: detect /t/{tunnelId}/p/{projectName} from the current URL
163
- const parts = window.location.pathname.split('/').filter(Boolean);
164
- if (parts[0] === 't' && parts.length >= 4 && parts[2] === 'p') {
165
- return \`/\${parts.slice(0, 4).join('/')}\`;
166
- }
167
- return '';
168
- }
169
-
170
- /**
171
- * Fetch wrapper that prepends EGDesk basePath to relative URLs.
172
- * Use for /api/* routes and /__*_proxy paths in client components.
173
- */
174
- export async function apiFetch(path: string, options?: RequestInit): Promise<Response> {
175
- const basePath = getEgdeskBasePath();
176
- const url =
177
- path.startsWith('/') && !path.startsWith('//') ? \`\${basePath}\${path}\` : path;
178
- return fetch(url, options);
179
- }
180
-
181
- /** Build EGDesk routing headers (project-id + env) for server-side direct calls. */
182
- function buildServerEgdeskHeaders(): Record<string, string> {
183
- const headers: Record<string, string> = { 'Content-Type': 'application/json' };
184
- const apiKey =
185
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_KEY) ||
186
- EGDESK_CONFIG.apiKey;
187
- const projectId =
188
- typeof process !== 'undefined' ? process.env?.NEXT_PUBLIC_EGDESK_PROJECT_ID : undefined;
189
- const egdeskEnv =
190
- typeof process !== 'undefined' ? process.env?.NEXT_PUBLIC_EGDESK_ENV : undefined;
191
- if (apiKey) headers['X-Api-Key'] = apiKey;
192
- if (projectId) headers['X-EGDesk-Project-Id'] = projectId;
193
- if (egdeskEnv) headers['X-EGDesk-Env'] = egdeskEnv;
194
- return headers;
195
- }
196
-
197
- /**
198
- * Parse EGDesk MCP \`/tools/call\` JSON so \`error\` is shown even when HTTP status is 500.
199
- */
200
- async function parseEgdeskMcpToolResponse(response: Response): Promise<any> {
201
- const result = await response.json().catch(() => null);
202
-
203
- if (result && typeof result === 'object' && result.success === false) {
204
- const errMsg =
205
- typeof result.error === 'string'
206
- ? result.error
207
- : result.error != null
208
- ? String(result.error)
209
- : 'Tool call failed';
210
- throw new Error(errMsg);
211
- }
212
-
213
- if (!response.ok) {
214
- let fromBody = '';
215
- if (result && typeof result === 'object') {
216
- if (typeof result.error === 'string') fromBody = result.error;
217
- else if (typeof (result as { message?: string }).message === 'string') {
218
- fromBody = (result as { message: string }).message;
219
- }
220
- }
221
- throw new Error(fromBody || \`HTTP \${response.status}: \${response.statusText}\`);
222
- }
223
-
224
- if (!result || result.success !== true) {
225
- throw new Error(
226
- result && typeof result === 'object' && typeof result.error === 'string'
227
- ? result.error
228
- : 'Tool call failed'
229
- );
230
- }
231
-
232
- const content = result.result?.content?.[0]?.text;
233
- return content ? JSON.parse(content) : null;
234
- }
235
-
236
- /**
237
- * Call EGDesk user-data MCP tool
238
- *
239
- * - Server (API routes): Calls Egdesk API directly using EGDESK_CONFIG.apiUrl and
240
- * EGDESK_CONFIG.apiKey (from env NEXT_PUBLIC_EGDESK_API_URL / NEXT_PUBLIC_EGDESK_API_KEY)
241
- * so relative URLs and tunnel base path are not an issue.
242
- * - Client (browser): Uses /__user_data_proxy so CORS and tunnel base path still work.
243
- */
244
- export async function callUserDataTool(
245
- toolName: string,
246
- args: Record<string, any> = {}
247
- ): Promise<any> {
248
- const body = JSON.stringify({ tool: toolName, arguments: args });
249
-
250
- const isServer = typeof window === 'undefined';
251
-
252
- let response: Response;
253
- if (isServer) {
254
- // API routes: call Egdesk directly (relative URL is invalid in Node)
255
- const apiUrl =
256
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
257
- EGDESK_CONFIG.apiUrl;
258
- response = await fetch(\`\${apiUrl}/user-data/tools/call\`, {
259
- method: 'POST',
260
- headers: buildServerEgdeskHeaders(),
261
- body
262
- });
263
- } else {
264
- // Browser: use proxy for CORS and tunnel base path (proxy.ts injects routing headers)
265
- response = await apiFetch('/__user_data_proxy', {
266
- method: 'POST',
267
- headers: { 'Content-Type': 'application/json' },
268
- body
269
- });
270
- }
271
-
272
- return parseEgdeskMcpToolResponse(response);
273
- }
274
-
275
- /**
276
- * Query table data
277
- */
278
- export async function queryTable(
279
- tableName: string,
280
- options: {
281
- filters?: Record<string, string>;
282
- limit?: number;
283
- offset?: number;
284
- orderBy?: string;
285
- orderDirection?: 'ASC' | 'DESC';
286
- } = {}
287
- ) {
288
- return callUserDataTool('user_data_query', {
289
- tableName,
290
- ...options
291
- });
292
- }
293
-
294
- /**
295
- * Search table
296
- */
297
- export async function searchTable(
298
- tableName: string,
299
- searchQuery: string,
300
- limit: number = 50
301
- ) {
302
- return callUserDataTool('user_data_search', {
303
- tableName,
304
- searchQuery,
305
- limit
306
- });
307
- }
308
-
309
- /**
310
- * Aggregate data
311
- */
312
- export async function aggregateTable(
313
- tableName: string,
314
- column: string,
315
- aggregateFunction: 'SUM' | 'AVG' | 'MIN' | 'MAX' | 'COUNT',
316
- options: {
317
- filters?: Record<string, string>;
318
- groupBy?: string;
319
- } = {}
320
- ) {
321
- return callUserDataTool('user_data_aggregate', {
322
- tableName,
323
- column,
324
- function: aggregateFunction,
325
- ...options
326
- });
327
- }
328
-
329
- /**
330
- * Execute raw SQL query (read-only, SELECT only).
331
- * Supports JOINs — use listTables() and getTableSchema() to discover tables/columns first.
332
- * For structured multi-table joins, prefer joinTables().
333
- */
334
- export async function executeSQL(query: string) {
335
- return callUserDataTool('user_data_sql_query', { query });
336
- }
337
-
338
- /**
339
- * Join one or more tables and query combined rows.
340
- * Use listTables() and getTableSchema() first to discover table names and columns.
341
- *
342
- * @example
343
- * await joinTables('orders', [
344
- * { table: 'customers', on: { leftColumn: 'customer_id', rightColumn: 'id' } },
345
- * { table: 'products', on: { leftColumn: 'orders.product_id', rightColumn: 'id' }, joinType: 'LEFT' },
346
- * ]);
347
- */
348
- export async function joinTables(
349
- fromTable: string,
350
- joins: Array<{
351
- table: string;
352
- on:
353
- | { leftColumn: string; rightColumn: string }
354
- | Array<{ leftColumn: string; rightColumn: string }>;
355
- joinType?: 'INNER' | 'LEFT' | 'RIGHT';
356
- }>,
357
- options: {
358
- select?: string[];
359
- filters?: Record<string, string>;
360
- limit?: number;
361
- offset?: number;
362
- orderBy?: string;
363
- orderDirection?: 'ASC' | 'DESC';
364
- } = {}
365
- ) {
366
- return callUserDataTool('user_data_join', {
367
- fromTable,
368
- joins,
369
- ...options
370
- });
371
- }
372
-
373
- /**
374
- * List all available tables
375
- */
376
- export async function listTables() {
377
- return callUserDataTool('user_data_list_tables', {});
378
- }
379
-
380
- /**
381
- * Get table schema
382
- */
383
- export async function getTableSchema(tableName: string) {
384
- return callUserDataTool('user_data_get_schema', { tableName });
385
- }
386
-
387
- /**
388
- * Create a new table
389
- */
390
- export async function createTable(
391
- displayName: string,
392
- schema: Array<{
393
- name: string;
394
- type: 'TEXT' | 'INTEGER' | 'REAL' | 'DATE';
395
- notNull?: boolean;
396
- defaultValue?: any;
397
- }>,
398
- options?: {
399
- description?: string;
400
- tableName?: string;
401
- uniqueKeyColumns?: string[];
402
- duplicateAction?: 'skip' | 'update' | 'allow' | 'replace-date-range';
403
- }
404
- ) {
405
- return callUserDataTool('user_data_create_table', {
406
- displayName,
407
- schema,
408
- ...options
409
- });
410
- }
411
-
412
- /**
413
- * Insert rows into a table
414
- */
415
- export async function insertRows(
416
- tableName: string,
417
- rows: Array<Record<string, any>>
418
- ) {
419
- return callUserDataTool('user_data_insert_rows', {
420
- tableName,
421
- rows
422
- });
423
- }
424
-
425
- /**
426
- * Update rows in a table
427
- */
428
- export async function updateRows(
429
- tableName: string,
430
- updates: Record<string, any>,
431
- options: {
432
- ids?: number[];
433
- filters?: Record<string, string>;
434
- }
435
- ) {
436
- return callUserDataTool('user_data_update_rows', {
437
- tableName,
438
- updates,
439
- ...options
440
- });
441
- }
442
-
443
- /**
444
- * Delete rows from a table
445
- */
446
- export async function deleteRows(
447
- tableName: string,
448
- options: {
449
- ids?: number[];
450
- filters?: Record<string, string>;
451
- }
452
- ) {
453
- return callUserDataTool('user_data_delete_rows', {
454
- tableName,
455
- ...options
456
- });
457
- }
458
-
459
- /**
460
- * Delete a table
461
- */
462
- export async function deleteTable(tableName: string) {
463
- return callUserDataTool('user_data_delete_table', { tableName });
464
- }
465
-
466
- /**
467
- * Rename a table
468
- */
469
- export async function renameTable(
470
- tableName: string,
471
- newTableName: string,
472
- newDisplayName?: string
473
- ) {
474
- return callUserDataTool('user_data_rename_table', {
475
- tableName,
476
- newTableName,
477
- newDisplayName
478
- });
479
- }
480
-
481
- // ==========================================
482
- // FINANCEHUB HELPERS
483
- // ==========================================
484
-
485
- /**
486
- * Call EGDesk FinanceHub MCP tool
487
- */
488
- export async function callFinanceHubTool(
489
- toolName: string,
490
- args: Record<string, any> = {}
491
- ): Promise<any> {
492
- const body = JSON.stringify({ tool: toolName, arguments: args });
493
-
494
- const isServer = typeof window === 'undefined';
495
-
496
- let response: Response;
497
- if (isServer) {
498
- const apiUrl =
499
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
500
- EGDESK_CONFIG.apiUrl;
501
- response = await fetch(\`\${apiUrl}/financehub/tools/call\`, {
502
- method: 'POST',
503
- headers: buildServerEgdeskHeaders(),
504
- body
505
- });
506
- } else {
507
- response = await apiFetch('/__financehub_proxy', {
508
- method: 'POST',
509
- headers: { 'Content-Type': 'application/json' },
510
- body
511
- });
512
- }
513
-
514
- return parseEgdeskMcpToolResponse(response);
515
- }
516
-
517
- /**
518
- * List all registered banks and card companies
519
- */
520
- export async function listBanks() {
521
- return callFinanceHubTool('financehub_list_banks', {});
522
- }
523
-
524
- /**
525
- * List bank accounts with balances
526
- */
527
- export async function listAccounts(options: {
528
- bankId?: string;
529
- isActive?: boolean;
530
- } = {}) {
531
- return callFinanceHubTool('financehub_list_accounts', options);
532
- }
533
-
534
- /**
535
- * Query bank transactions
536
- */
537
- export async function queryBankTransactions(options: {
538
- accountId?: string;
539
- bankId?: string;
540
- startDate?: string;
541
- endDate?: string;
542
- category?: string;
543
- minAmount?: number;
544
- maxAmount?: number;
545
- searchText?: string;
546
- limit?: number;
547
- offset?: number;
548
- orderBy?: 'date' | 'amount' | 'balance';
549
- orderDir?: 'asc' | 'desc';
550
- } = {}) {
551
- return callFinanceHubTool('financehub_query_transactions', options);
552
- }
553
-
554
- /**
555
- * Query card transactions (NEW)
556
- */
557
- export async function queryCardTransactions(options: {
558
- accountId?: string;
559
- cardCompanyId?: string;
560
- cardNumber?: string;
561
- merchantName?: string;
562
- startDate?: string;
563
- endDate?: string;
564
- category?: string;
565
- minAmount?: number;
566
- maxAmount?: number;
567
- includeCancelled?: boolean;
568
- limit?: number;
569
- offset?: number;
570
- orderBy?: 'date' | 'amount';
571
- orderDir?: 'asc' | 'desc';
572
- } = {}) {
573
- return callFinanceHubTool('financehub_query_card_transactions', options);
574
- }
575
-
576
- /**
577
- * Get transaction statistics
578
- */
579
- export async function getTransactionStats(options: {
580
- accountId?: string;
581
- bankId?: string;
582
- startDate?: string;
583
- endDate?: string;
584
- } = {}) {
585
- return callFinanceHubTool('financehub_get_statistics', options);
586
- }
587
-
588
- /**
589
- * Get monthly breakdown of deposits/withdrawals
590
- */
591
- export async function getMonthlySummary(options: {
592
- accountId?: string;
593
- bankId?: string;
594
- year?: number;
595
- months?: number;
596
- } = {}) {
597
- return callFinanceHubTool('financehub_get_monthly_summary', options);
598
- }
599
-
600
- /**
601
- * Get overall stats (banks, accounts, transactions, balances)
602
- */
603
- export async function getOverallStats() {
604
- return callFinanceHubTool('financehub_get_overall_stats', {});
605
- }
606
-
607
- /**
608
- * Get bank/card sync operation history (sync_operations table)
609
- */
610
- export async function getSyncHistory(limit: number = 50) {
611
- return callFinanceHubTool('financehub_get_sync_history', { limit });
612
- }
613
-
614
- /**
615
- * List Hometax business connections (hometax_connections: counts, spreadsheet URLs, status)
616
- */
617
- export async function listHometaxConnections() {
618
- return callFinanceHubTool('financehub_list_hometax_connections', {});
619
- }
620
-
621
- /**
622
- * Query electronic tax invoices synced from Hometax (tax_invoices table)
623
- */
624
- export async function queryTaxInvoices(options: {
625
- businessNumber?: string;
626
- invoiceType?: 'sales' | 'purchase';
627
- startDate?: string;
628
- endDate?: string;
629
- limit?: number;
630
- offset?: number;
631
- } = {}) {
632
- return callFinanceHubTool('financehub_query_tax_invoices', options);
633
- }
634
-
635
- /**
636
- * Query tax-exempt invoices synced from Hometax (tax_exempt_invoices table)
637
- */
638
- export async function queryTaxExemptInvoices(options: {
639
- businessNumber?: string;
640
- invoiceType?: 'sales' | 'purchase';
641
- startDate?: string;
642
- endDate?: string;
643
- limit?: number;
644
- offset?: number;
645
- } = {}) {
646
- return callFinanceHubTool('financehub_query_tax_exempt_invoices', options);
647
- }
648
-
649
- /**
650
- * Query cash receipts synced from Hometax (cash_receipts table)
651
- */
652
- export async function queryCashReceipts(options: {
653
- businessNumber?: string;
654
- startDate?: string;
655
- endDate?: string;
656
- limit?: number;
657
- offset?: number;
658
- } = {}) {
659
- return callFinanceHubTool('financehub_query_cash_receipts', options);
660
- }
661
-
662
- /**
663
- * Get Hometax Excel import sync history (hometax_sync_operations). Not the same as getSyncHistory (banks/cards).
664
- */
665
- export async function getHometaxSyncHistory(limit: number = 50) {
666
- return callFinanceHubTool('financehub_get_hometax_sync_history', { limit });
667
- }
668
-
669
- /**
670
- * List per-(bank, product) bank-product tables — bank-side product data
671
- * downloaded from bank portals that isn't core deposit/card transactions
672
- * (loans, receivables, e-bills, etc.). Returns table slugs, displayName,
673
- * column schemas, and row counts. ALWAYS call this first to discover
674
- * what tables exist before calling queryBankProductTable.
675
- */
676
- export async function listBankProductTables() {
677
- return callFinanceHubTool('financehub_list_bank_product_tables', {});
678
- }
679
-
680
- /**
681
- * Generic safe query against any per-(bank, product) table from
682
- * listBankProductTables. Filters use the table's exact column names
683
- * (snake_case). Returns rows with totalMatching, limit, offset.
684
- *
685
- * @example
686
- * queryBankProductTable({
687
- * tableSlug: 'ibk_loan_transactions',
688
- * filters: [
689
- * { column: 'account_number', op: '=', value: '306-063568-04-036' },
690
- * { column: 'transaction_amount', op: '>', value: 1000000 },
691
- * ],
692
- * orderBy: { column: 'transaction_date', direction: 'DESC' },
693
- * limit: 50,
694
- * });
695
- */
696
- export async function queryBankProductTable(options: {
697
- tableSlug: string;
698
- filters?: Array<{
699
- column: string;
700
- op: '=' | '!=' | '>' | '<' | '>=' | '<=' | 'like' | 'in';
701
- value: string | number | Array<string | number>;
702
- }>;
703
- orderBy?: { column: string; direction?: 'ASC' | 'DESC' };
704
- limit?: number;
705
- offset?: number;
706
- latestOnly?: boolean;
707
- }) {
708
- return callFinanceHubTool('financehub_query_bank_product_table', options);
709
- }
710
-
711
- /**
712
- * Create or update a bank/card account (no credentials).
713
- */
714
- export async function upsertFinanceHubAccount(account: {
715
- bankId: string;
716
- accountNumber: string;
717
- accountName?: string;
718
- customerName?: string;
719
- balance?: number;
720
- availableBalance?: number;
721
- currency?: string;
722
- accountType?: string;
723
- openDate?: string;
724
- metadata?: Record<string, unknown>;
725
- }) {
726
- return callFinanceHubTool('financehub_upsert_account', account);
727
- }
728
-
729
- /**
730
- * Import bank or card transactions (deduplicated). Max 1000 per call.
731
- */
732
- export async function importFinanceHubTransactions(options: {
733
- bankId: string;
734
- accountData: {
735
- accountNumber: string;
736
- accountName?: string;
737
- customerName?: string;
738
- balance?: number;
739
- availableBalance?: number;
740
- openDate?: string;
741
- };
742
- transactions: Array<Record<string, unknown>>;
743
- syncMetadata: {
744
- queryPeriodStart: string;
745
- queryPeriodEnd: string;
746
- filePath?: string;
747
- };
748
- isCard?: boolean;
749
- }) {
750
- return callFinanceHubTool('financehub_import_transactions', options);
751
- }
752
-
753
- /**
754
- * Upsert rows into a bank-product table (loans, receivables, etc.). Max 500 per call.
755
- */
756
- export async function upsertFinanceHubBankProductRows(options: {
757
- tableSlug: string;
758
- rows: Array<Record<string, unknown>>;
759
- }) {
760
- return callFinanceHubTool('financehub_upsert_bank_product_rows', options);
761
- }
762
-
763
- /**
764
- * Delete an account and all its transactions/sync rows (not credentials).
765
- */
766
- export async function deleteFinanceHubAccount(bankId: string, accountNumber: string) {
767
- return callFinanceHubTool('financehub_delete_account', { bankId, accountNumber });
768
- }
769
-
770
- /**
771
- * Delete all imported data for a bankId (accounts, transactions, sync ops).
772
- */
773
- export async function deleteFinanceHubImportedDataForBank(bankId: string) {
774
- return callFinanceHubTool('financehub_delete_imported_data_for_bank', { bankId });
775
- }
776
-
777
- /**
778
- * Delete transactions by account scope, date range, and/or ids (max 500 ids).
779
- */
780
- export async function deleteFinanceHubTransactions(options: {
781
- accountId?: string;
782
- bankId?: string;
783
- accountNumber?: string;
784
- startDate?: string;
785
- endDate?: string;
786
- transactionIds?: string[];
787
- isCard?: boolean;
788
- }) {
789
- return callFinanceHubTool('financehub_delete_transactions', options);
790
- }
791
-
792
- /**
793
- * Delete bank-product table rows by ids and/or filters (max 1000 rows).
794
- */
795
- export async function deleteFinanceHubBankProductRows(options: {
796
- tableSlug: string;
797
- ids?: string[];
798
- filters?: Array<{
799
- column: string;
800
- op: '=' | '!=' | '>' | '<' | '>=' | '<=' | 'like' | 'in';
801
- value: string | number | Array<string | number>;
802
- }>;
803
- }) {
804
- return callFinanceHubTool('financehub_delete_bank_product_rows', options);
805
- }
806
-
807
- // ==========================================
808
- // INTERNAL KNOWLEDGE / BUSINESS IDENTITY / COMPANY RESEARCH (MCP)
809
- // ==========================================
810
-
811
- /**
812
- * Call EGDesk Internal Knowledge MCP tool (knowledge docs, business identity snapshots, company research).
813
- *
814
- * - Server: \`POST {apiUrl}/internal-knowledge/tools/call\`
815
- * - Client: \`POST /__internal_knowledge_proxy\` (see proxy.ts / middleware)
816
- */
817
- export async function callInternalKnowledgeTool(
818
- toolName: string,
819
- args: Record<string, any> = {}
820
- ): Promise<any> {
821
- const body = JSON.stringify({ tool: toolName, arguments: args });
822
-
823
- const isServer = typeof window === 'undefined';
824
-
825
- let response: Response;
826
- if (isServer) {
827
- const apiUrl =
828
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
829
- EGDESK_CONFIG.apiUrl;
830
- response = await fetch(\`\${apiUrl}/internal-knowledge/tools/call\`, {
831
- method: 'POST',
832
- headers: buildServerEgdeskHeaders(),
833
- body
834
- });
835
- } else {
836
- response = await apiFetch('/__internal_knowledge_proxy', {
837
- method: 'POST',
838
- headers: { 'Content-Type': 'application/json' },
839
- body
840
- });
841
- }
842
-
843
- return parseEgdeskMcpToolResponse(response);
844
- }
845
-
846
- /** List internal knowledge documents for a business identity snapshot */
847
- export async function listKnowledgeDocuments(
848
- snapshotId: string,
849
- category?: 'hierarchy' | 'process' | 'policy' | 'note'
850
- ) {
851
- return callInternalKnowledgeTool('knowledge_list_documents', {
852
- snapshotId,
853
- ...(category != null ? { category } : {})
854
- });
855
- }
856
-
857
- /** Get one knowledge document by ID (full markdown content) */
858
- export async function getKnowledgeDocument(documentId: string) {
859
- return callInternalKnowledgeTool('knowledge_get_document', { documentId });
860
- }
861
-
862
- /** Search knowledge documents by text in title or content */
863
- export async function searchKnowledgeContent(
864
- snapshotId: string,
865
- searchText: string,
866
- category?: 'hierarchy' | 'process' | 'policy' | 'note'
867
- ) {
868
- return callInternalKnowledgeTool('knowledge_search_content', {
869
- snapshotId,
870
- searchText,
871
- ...(category != null ? { category } : {})
872
- });
873
- }
874
-
875
- /** Get all documents of a single category for a snapshot */
876
- export async function getKnowledgeByCategory(
877
- snapshotId: string,
878
- category: 'hierarchy' | 'process' | 'policy' | 'note'
879
- ) {
880
- return callInternalKnowledgeTool('knowledge_get_by_category', { snapshotId, category });
881
- }
882
-
883
- /** Create a new knowledge document */
884
- export async function createKnowledgeDocument(
885
- snapshotId: string,
886
- title: string,
887
- category: 'hierarchy' | 'process' | 'policy' | 'note',
888
- content?: string
889
- ) {
890
- return callInternalKnowledgeTool('knowledge_create_document', {
891
- snapshotId,
892
- title,
893
- category,
894
- ...(content != null ? { content } : {})
895
- });
896
- }
897
-
898
- /** Update an existing knowledge document */
899
- export async function updateKnowledgeDocument(
900
- documentId: string,
901
- updates: { title?: string; category?: 'hierarchy' | 'process' | 'policy' | 'note'; content?: string }
902
- ) {
903
- return callInternalKnowledgeTool('knowledge_update_document', { documentId, ...updates });
904
- }
905
-
906
- /** Delete a knowledge document */
907
- export async function deleteKnowledgeDocument(documentId: string) {
908
- return callInternalKnowledgeTool('knowledge_delete_document', { documentId });
909
- }
910
-
911
- /** List business identity snapshots (optional brand filter) */
912
- export async function listBusinessIdentitySnapshots(brandKey?: string) {
913
- return callInternalKnowledgeTool('businessidentity_list_snapshots', {
914
- ...(brandKey != null ? { brandKey } : {})
915
- });
916
- }
917
-
918
- /** Full snapshot by ID (identity JSON, SEO/SSL analysis, etc.) */
919
- export async function getBusinessIdentitySnapshot(snapshotId: string) {
920
- return callInternalKnowledgeTool('businessidentity_get_snapshot', { snapshotId });
921
- }
922
-
923
- /** Company info slice from a snapshot (contact, structure, partners, industries) */
924
- export async function getBusinessIdentityCompanyInfo(snapshotId: string) {
925
- return callInternalKnowledgeTool('businessidentity_get_company_info', { snapshotId });
926
- }
927
-
928
- /** Services and products from a snapshot */
929
- export async function getBusinessIdentityServicesProducts(snapshotId: string) {
930
- return callInternalKnowledgeTool('businessidentity_get_services_products', { snapshotId });
931
- }
932
-
933
- /**
934
- * Call EGDesk Company Research MCP tool (run workflows and query saved research).
935
- *
936
- * - Server: \`POST {apiUrl}/company-research/tools/call\`
937
- * - Client: \`POST /__company_research_proxy\` (see proxy.ts / middleware)
938
- */
939
- export async function callCompanyResearchTool(
940
- toolName: string,
941
- args: Record<string, any> = {}
942
- ): Promise<any> {
943
- const body = JSON.stringify({ tool: toolName, arguments: args });
944
-
945
- const isServer = typeof window === 'undefined';
946
-
947
- let response: Response;
948
- if (isServer) {
949
- const apiUrl =
950
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
951
- EGDESK_CONFIG.apiUrl;
952
- response = await fetch(\`\${apiUrl}/company-research/tools/call\`, {
953
- method: 'POST',
954
- headers: buildServerEgdeskHeaders(),
955
- body
956
- });
957
- } else {
958
- response = await apiFetch('/__company_research_proxy', {
959
- method: 'POST',
960
- headers: { 'Content-Type': 'application/json' },
961
- body
962
- });
963
- }
964
-
965
- return parseEgdeskMcpToolResponse(response);
966
- }
967
-
968
- /** Run full company research workflow for a domain (several minutes) */
969
- export async function runCompanyResearch(
970
- domain: string,
971
- options: { bypassCache?: boolean; inquiryData?: Record<string, any> } = {}
972
- ) {
973
- return callCompanyResearchTool('companyresearch_run', { domain, ...options });
974
- }
975
-
976
- /** List company research records */
977
- export async function listCompanyResearch(
978
- status?: 'completed' | 'failed' | 'in_progress'
979
- ) {
980
- return callCompanyResearchTool('companyresearch_list_all', {
981
- ...(status != null ? { status } : {})
982
- });
983
- }
984
-
985
- /** One company research record by ID */
986
- export async function getCompanyResearchById(researchId: string) {
987
- return callCompanyResearchTool('companyresearch_get_by_id', { researchId });
988
- }
989
-
990
- /** Research records for a domain */
991
- export async function getCompanyResearchByDomain(domain: string) {
992
- return callCompanyResearchTool('companyresearch_get_by_domain', { domain });
993
- }
994
-
995
- /** Most recent completed research for a domain */
996
- export async function getLatestCompletedCompanyResearch(domain: string) {
997
- return callCompanyResearchTool('companyresearch_get_latest_completed', { domain });
998
- }
999
-
1000
- /** Search company research by company name or domain */
1001
- export async function searchCompanyResearch(searchText: string) {
1002
- return callCompanyResearchTool('companyresearch_search', { searchText });
1003
- }
1004
-
1005
- // ==========================================
1006
- // BROWSER RECORDING HELPERS
1007
- // ==========================================
1008
-
1009
- /**
1010
- * Call EGDesk Browser Recording MCP tool (saved recorder tests, replay with optional dates).
1011
- *
1012
- * - Server: \`POST {apiUrl}/browser-recording/tools/call\`
1013
- * - Client: \`POST /__browser_recording_proxy\` (see proxy.ts / middleware)
1014
- */
1015
- export async function callBrowserRecordingTool(
1016
- toolName: string,
1017
- args: Record<string, any> = {}
1018
- ): Promise<any> {
1019
- const body = JSON.stringify({ tool: toolName, arguments: args });
1020
-
1021
- const isServer = typeof window === 'undefined';
1022
-
1023
- let response: Response;
1024
- if (isServer) {
1025
- const apiUrl =
1026
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1027
- EGDESK_CONFIG.apiUrl;
1028
- response = await fetch(\`\${apiUrl}/browser-recording/tools/call\`, {
1029
- method: 'POST',
1030
- headers: buildServerEgdeskHeaders(),
1031
- body
1032
- });
1033
- } else {
1034
- response = await apiFetch('/__browser_recording_proxy', {
1035
- method: 'POST',
1036
- headers: { 'Content-Type': 'application/json' },
1037
- body
1038
- });
1039
- }
1040
-
1041
- return parseEgdeskMcpToolResponse(response);
1042
- }
1043
-
1044
- /** List saved *.spec.js files in the EGDesk browser-recorder-tests output folder */
1045
- export async function listBrowserRecordingTests() {
1046
- return callBrowserRecordingTool('browser_recording_list_saved_tests', {});
1047
- }
1048
-
1049
- /** Inspect a spec: date UI, defaultReplayDates, labeledFieldReplayBlocks, etc. */
1050
- export async function getBrowserRecordingReplayOptions(testFile: string) {
1051
- return callBrowserRecordingTool('browser_recording_get_replay_options', { testFile });
1052
- }
1053
-
1054
- export type BrowserRecordingRunOptions = {
1055
- headless?: boolean;
1056
- /** Save headless preference for scheduled runs */
1057
- persistHeadless?: boolean;
1058
- startDate?: string;
1059
- endDate?: string;
1060
- datePickersByIndex?: string[];
1061
- /** Per captureLabeledFields step, values in field order */
1062
- labeledFieldFills?: (string | undefined)[][];
1063
- };
1064
-
1065
- export type BrowserRecordingScheduleOptions = {
1066
- testName?: string;
1067
- scheduledTime?: string;
1068
- frequencyType?: 'daily' | 'weekly' | 'monthly' | 'custom';
1069
- dayOfWeek?: number;
1070
- dayOfMonth?: number;
1071
- customIntervalDays?: number;
1072
- enabled?: boolean;
1073
- headless?: boolean;
1074
- };
1075
-
1076
- /** Replay a saved recording in Chrome (optional headless, dates + labeledFieldFills) */
1077
- export async function runBrowserRecording(
1078
- testFile: string,
1079
- options: BrowserRecordingRunOptions = {}
1080
- ) {
1081
- return callBrowserRecordingTool('browser_recording_run', {
1082
- testFile,
1083
- ...options
1084
- });
1085
- }
1086
-
1087
- /** List Playwright scheduler entries for browser recorder tests */
1088
- export async function listBrowserRecordingSchedules() {
1089
- return callBrowserRecordingTool('browser_recording_list_schedules', {});
1090
- }
1091
-
1092
- /** Get schedule for a test file, or null */
1093
- export async function getBrowserRecordingSchedule(testFile: string) {
1094
- return callBrowserRecordingTool('browser_recording_get_schedule', { testFile });
1095
- }
1096
-
1097
- /** Create or update a recurring schedule for a saved test */
1098
- export async function setBrowserRecordingSchedule(
1099
- testFile: string,
1100
- options: BrowserRecordingScheduleOptions = {}
1101
- ) {
1102
- return callBrowserRecordingTool('browser_recording_set_schedule', {
1103
- testFile,
1104
- ...options
1105
- });
1106
- }
1107
-
1108
- /** Remove scheduler entry for a test file */
1109
- export async function removeBrowserRecordingSchedule(testFile: string) {
1110
- return callBrowserRecordingTool('browser_recording_remove_schedule', { testFile });
1111
- }
1112
-
1113
- /** Pause a recurring schedule without deleting it */
1114
- export async function pauseBrowserRecordingSchedule(testFile: string) {
1115
- return callBrowserRecordingTool('browser_recording_pause_schedule', { testFile });
1116
- }
1117
-
1118
- /** Resume a paused recurring schedule */
1119
- export async function resumeBrowserRecordingSchedule(testFile: string) {
1120
- return callBrowserRecordingTool('browser_recording_resume_schedule', { testFile });
1121
- }
1122
-
1123
- export type BrowserRecordingSyncConfigOptions = {
1124
- testFile?: string;
1125
- scriptFolderPath?: string;
1126
- scriptName?: string;
1127
- targetTableId?: string;
1128
- columnMappings?: Record<string, string>;
1129
- headerRow?: number;
1130
- skipBottomRows?: number;
1131
- sheetIndex?: number;
1132
- appliedSplits?: Array<{ originalColumn: string; dateColumn: string; numberColumn: string }>;
1133
- uniqueKeyColumns?: string[];
1134
- duplicateAction?: 'skip' | 'update' | 'allow' | 'replace-date-range' | 'replace-all';
1135
- fileAction?: 'keep' | 'archive' | 'delete';
1136
- enabled?: boolean;
1137
- autoSyncEnabled?: boolean;
1138
- };
1139
-
1140
- /** List EGDesk-Browser download folders with Excel/CSV files */
1141
- export async function listBrowserRecordingDownloadFolders() {
1142
- return callBrowserRecordingTool('browser_recording_list_download_folders', {});
1143
- }
1144
-
1145
- /** List sync-to-SQL configs for browser downloads */
1146
- export async function listBrowserRecordingSyncConfigs() {
1147
- return callBrowserRecordingTool('browser_recording_list_sync_configs', {});
1148
- }
1149
-
1150
- /** Get sync config by testFile or scriptFolderPath */
1151
- export async function getBrowserRecordingSyncConfig(opts: {
1152
- testFile?: string;
1153
- scriptFolderPath?: string;
1154
- }) {
1155
- return callBrowserRecordingTool('browser_recording_get_sync_config', opts);
1156
- }
1157
-
1158
- /** Create or update sync-to-DB for a browser download folder */
1159
- export async function setBrowserRecordingSyncConfig(
1160
- opts: BrowserRecordingSyncConfigOptions
1161
- ) {
1162
- return callBrowserRecordingTool('browser_recording_set_sync_config', opts);
1163
- }
1164
-
1165
- /** Remove sync config by configId, testFile, or scriptFolderPath */
1166
- export async function removeBrowserRecordingSyncConfig(opts: {
1167
- configId?: string;
1168
- testFile?: string;
1169
- scriptFolderPath?: string;
1170
- }) {
1171
- return callBrowserRecordingTool('browser_recording_remove_sync_config', opts);
1172
- }
1173
-
1174
- // ==========================================
1175
- // AI CENTER (workflows, entities, relations, tags)
1176
- // ==========================================
1177
-
1178
- /**
1179
- * Call EGDesk AI Center MCP tool (workflows, Neuron Layer entities/relations/tags).
1180
- *
1181
- * - Server: \`POST {apiUrl}/ai-center/tools/call\`
1182
- * - Client: \`POST /__ai_center_proxy\` (see proxy.ts / middleware)
1183
- */
1184
- export async function callAICenterTool(
1185
- toolName: string,
1186
- args: Record<string, any> = {}
1187
- ): Promise<any> {
1188
- const body = JSON.stringify({ tool: toolName, arguments: args });
1189
-
1190
- const isServer = typeof window === 'undefined';
1191
-
1192
- let response: Response;
1193
- if (isServer) {
1194
- const apiUrl =
1195
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1196
- EGDESK_CONFIG.apiUrl;
1197
- response = await fetch(\`\${apiUrl}/ai-center/tools/call\`, {
1198
- method: 'POST',
1199
- headers: buildServerEgdeskHeaders(),
1200
- body
1201
- });
1202
- } else {
1203
- response = await apiFetch('/__ai_center_proxy', {
1204
- method: 'POST',
1205
- headers: { 'Content-Type': 'application/json' },
1206
- body
1207
- });
1208
- }
1209
-
1210
- return parseEgdeskMcpToolResponse(response);
1211
- }
1212
-
1213
- // ── Data Sources ─────────────────────────────────────────────────────────────
1214
-
1215
- /**
1216
- * List all data sources available for AI processing (user data tables, finance hub accounts,
1217
- * business identity snapshots, company research records) with processing state.
1218
- */
1219
- export async function listDataSources() {
1220
- return callAICenterTool('ai_center_list_data_sources', {});
1221
- }
1222
-
1223
- // ── Workflows ────────────────────────────────────────────────────────────────
1224
-
1225
- /** List all AI workflows */
1226
- export async function listWorkflows() {
1227
- return callAICenterTool('ai_center_list_workflows', {});
1228
- }
1229
-
1230
- /** Get a single workflow by ID (includes action steps) */
1231
- export async function getWorkflow(id: string) {
1232
- return callAICenterTool('ai_center_get_workflow', { id });
1233
- }
1234
-
1235
- /** Create a new AI workflow */
1236
- export async function createWorkflow(data: {
1237
- label: string;
1238
- inputTypes: string[];
1239
- hints: string[];
1240
- outputTables: string[];
1241
- actions: Array<{ actionId: string; params?: Record<string, any>; stage?: number; position?: number }>;
1242
- status?: 'active' | 'suggested' | 'draft';
1243
- suggestedBy?: string;
1244
- triggerTable?: string | null;
1245
- notify?: string[];
1246
- }) {
1247
- return callAICenterTool('ai_center_create_workflow', data);
1248
- }
1249
-
1250
- /** Update metadata fields of an existing workflow */
1251
- export async function updateWorkflow(
1252
- id: string,
1253
- data: {
1254
- label?: string;
1255
- status?: 'active' | 'suggested' | 'draft';
1256
- inputTypes?: string[];
1257
- hints?: string[];
1258
- outputTables?: string[];
1259
- triggerTable?: string | null;
1260
- }
1261
- ) {
1262
- return callAICenterTool('ai_center_update_workflow', { id, ...data });
1263
- }
1264
-
1265
- /** Change the status of a workflow */
1266
- export async function updateWorkflowStatus(
1267
- id: string,
1268
- status: 'active' | 'suggested' | 'draft'
1269
- ) {
1270
- return callAICenterTool('ai_center_update_workflow_status', { id, status });
1271
- }
1272
-
1273
- /** Delete a workflow and all its action steps */
1274
- export async function deleteWorkflow(id: string) {
1275
- return callAICenterTool('ai_center_delete_workflow', { id });
1276
- }
1277
-
1278
- // ── Workflow notify roles ─────────────────────────────────────────────────────
1279
-
1280
- /** Set which roles receive notifications for all activity on a workflow's runs */
1281
- export async function setWorkflowNotifyRoles(workflowId: string, roles: string[]) {
1282
- return callAICenterTool('ai_center_set_workflow_notify', { workflowId, roles });
1283
- }
1284
-
1285
- // ── Workflow actions ──────────────────────────────────────────────────────────
1286
-
1287
- /** Append or insert an action step into a workflow */
1288
- export async function addWorkflowAction(
1289
- workflowId: string,
1290
- actionId: string,
1291
- params: Record<string, any>,
1292
- stage: number = 0,
1293
- position: number = 0
1294
- ) {
1295
- return callAICenterTool('ai_center_add_workflow_action', { workflowId, actionId, params, stage, position });
1296
- }
1297
-
1298
- /** Remove a single action step from a workflow by its row ID */
1299
- export async function removeWorkflowAction(rowId: string) {
1300
- return callAICenterTool('ai_center_remove_workflow_action', { rowId });
1301
- }
1302
-
1303
- // ── Workflow runs ─────────────────────────────────────────────────────────────
1304
-
1305
- /** Start a new run of a workflow, optionally linked to a source data row */
1306
- export async function createRun(
1307
- workflowId: string,
1308
- inputData: Record<string, any>,
1309
- sourceTable?: string | null,
1310
- sourceRowId?: string | null
1311
- ) {
1312
- return callAICenterTool('ai_center_create_run', { workflowId, inputData, sourceTable, sourceRowId });
1313
- }
1314
-
1315
- /** Get a single workflow run by ID */
1316
- export async function getRun(runId: string) {
1317
- return callAICenterTool('ai_center_get_run', { runId });
1318
- }
1319
-
1320
- /** Get all runs for a workflow */
1321
- export async function getRuns(workflowId: string) {
1322
- return callAICenterTool('ai_center_get_runs', { workflowId });
1323
- }
1324
-
1325
- /** Update the status of a workflow run */
1326
- export async function updateRunStatus(
1327
- runId: string,
1328
- status: '정상진행중' | '반려중' | '정상완료' | '취소완료'
1329
- ) {
1330
- return callAICenterTool('ai_center_update_run_status', { runId, status });
1331
- }
1332
-
1333
- /** Advance a workflow run to a new stage */
1334
- export async function advanceRunStage(runId: string, stage: number) {
1335
- return callAICenterTool('ai_center_advance_run_stage', { runId, stage });
1336
- }
1337
-
1338
- // ── Workflow approvals ────────────────────────────────────────────────────────
1339
-
1340
- /** Create a pending approval record for a run */
1341
- export async function createApproval(
1342
- runId: string,
1343
- stage: number,
1344
- chainPosition: number,
1345
- role: string
1346
- ) {
1347
- return callAICenterTool('ai_center_create_approval', { runId, stage, chainPosition, role });
1348
- }
1349
-
1350
- /** Get all approval records for a run */
1351
- export async function getApprovals(runId: string) {
1352
- return callAICenterTool('ai_center_get_approvals', { runId });
1353
- }
1354
-
1355
- /** Record an approval decision */
1356
- export async function recordApprovalDecision(
1357
- approvalId: string,
1358
- decision: 'approved' | 'rejected' | 'cancelled'
1359
- ) {
1360
- return callAICenterTool('ai_center_record_approval_decision', { approvalId, decision });
1361
- }
1362
-
1363
- // ── Entities ──────────────────────────────────────────────────────────────────
1364
-
1365
- /** List all Neuron Layer entities, optionally filtered by type */
1366
- export async function listEntities(types?: string[]) {
1367
- return callAICenterTool('ai_center_list_entities', types ? { types } : {});
1368
- }
1369
-
1370
- /** Create a new entity in the Neuron Layer */
1371
- export async function createEntity(data: {
1372
- type: string;
1373
- name: string;
1374
- source: 'ai' | 'human';
1375
- id?: string;
1376
- raw?: string;
1377
- confidence?: number;
1378
- }) {
1379
- return callAICenterTool('ai_center_create_entity', data);
1380
- }
1381
-
1382
- /** Delete an entity from the Neuron Layer */
1383
- export async function deleteEntity(id: string) {
1384
- return callAICenterTool('ai_center_delete_entity', { id });
1385
- }
1386
-
1387
- // ── Relations ─────────────────────────────────────────────────────────────────
1388
-
1389
- /** List all relations, optionally filtered by source entity ID */
1390
- export async function listRelations(fromId?: string) {
1391
- return callAICenterTool('ai_center_list_relations', fromId ? { fromId } : {});
1392
- }
1393
-
1394
- /** Create a relation edge between two entities */
1395
- export async function createRelation(data: {
1396
- from_type: string;
1397
- from_id: string;
1398
- to_type: string;
1399
- to_id: string;
1400
- relation: string;
1401
- source: 'ai' | 'human';
1402
- id?: string;
1403
- confidence?: number;
1404
- }) {
1405
- return callAICenterTool('ai_center_create_relation', data);
1406
- }
1407
-
1408
- /** Delete a relation edge by ID */
1409
- export async function deleteRelation(id: string) {
1410
- return callAICenterTool('ai_center_delete_relation', { id });
1411
- }
1412
-
1413
- // ── Tags ──────────────────────────────────────────────────────────────────────
1414
-
1415
- /** List all tags, optionally filtered by entity ID */
1416
- export async function listTags(entityId?: string) {
1417
- return callAICenterTool('ai_center_list_tags', entityId ? { entityId } : {});
1418
- }
1419
-
1420
- /** Create a tag/property on an entity or document */
1421
- export async function createTag(data: {
1422
- doc_type: string;
1423
- doc_id: string;
1424
- namespace: string;
1425
- value: string;
1426
- source: 'ai' | 'human';
1427
- id?: string;
1428
- doc_ref?: string;
1429
- entity_id?: string;
1430
- confidence?: number;
1431
- }) {
1432
- return callAICenterTool('ai_center_create_tag', data);
1433
- }
1434
-
1435
- /** Delete a tag by ID */
1436
- export async function deleteTag(id: string) {
1437
- return callAICenterTool('ai_center_delete_tag', { id });
1438
- }
1439
-
1440
- /** List all company-wide shared business deadlines from the company calendar (company_calendar table). */
1441
- export async function getCalendarEventsFromAICenter() {
1442
- return callAICenterTool('ai_center_get_calendar_events', {});
1443
- }
1444
-
1445
- /** Update the status of an operational task. */
1446
- export async function completeTask(taskId: string, status: 'completed' | 'approved' | 'rejected') {
1447
- return callAICenterTool('ai_center_complete_task', { taskId, status });
1448
- }
1449
-
1450
- // ==========================================
1451
- // KOREAN LAW / LAWYER (MCP)
1452
- // ==========================================
1453
-
1454
- /**
1455
- * Call EGDesk Korean Law MCP tool (법제처 API — laws, precedents, admin rules, municipal ordinances).
1456
- *
1457
- * - Server: \`POST {apiUrl}/korean-law/tools/call\`
1458
- * - Client: \`POST /__korean_law_proxy\` (see proxy.ts / middleware)
1459
- */
1460
- export async function callKoreanLawTool(
1461
- toolName: string,
1462
- args: Record<string, any> = {}
1463
- ): Promise<any> {
1464
- const body = JSON.stringify({ tool: toolName, arguments: args });
1465
-
1466
- const isServer = typeof window === 'undefined';
1467
-
1468
- let response: Response;
1469
- if (isServer) {
1470
- const apiUrl =
1471
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1472
- EGDESK_CONFIG.apiUrl;
1473
- response = await fetch(\`\${apiUrl}/korean-law/tools/call\`, {
1474
- method: 'POST',
1475
- headers: buildServerEgdeskHeaders(),
1476
- body
1477
- });
1478
- } else {
1479
- response = await apiFetch('/__korean_law_proxy', {
1480
- method: 'POST',
1481
- headers: { 'Content-Type': 'application/json' },
1482
- body
1483
- });
1484
- }
1485
-
1486
- return parseEgdeskMcpToolResponse(response);
1487
- }
1488
-
1489
- /** Search laws, precedents, administrative rules, or municipal ordinances */
1490
- export async function searchKoreanLaw(
1491
- query: string,
1492
- options: {
1493
- target?: 'law' | 'prec' | 'admrul' | 'ordin';
1494
- display?: number;
1495
- page?: number;
1496
- } = {}
1497
- ) {
1498
- return callKoreanLawTool('korean_law_search', { query, ...options });
1499
- }
1500
-
1501
- /** Get full text of a law, administrative rule, or municipal ordinance */
1502
- export async function getKoreanLawText(
1503
- id: string,
1504
- target: 'law' | 'admrul' | 'ordin' = 'law'
1505
- ) {
1506
- return callKoreanLawTool('korean_law_get_text', { id, target });
1507
- }
1508
-
1509
- /** Get full text of a court precedent (판례) */
1510
- export async function getKoreanLawDecision(id: string) {
1511
- return callKoreanLawTool('korean_law_get_decision', { id });
1512
- }
1513
-
1514
- // ==========================================
1515
- // SEO (MCP)
1516
- // ==========================================
1517
-
1518
- /**
1519
- * Call EGDesk SEO MCP tool (Lighthouse audits and report history).
1520
- *
1521
- * - Server: \`POST {apiUrl}/seo/tools/call\`
1522
- * - Client: \`POST /__seo_proxy\` (see proxy.ts / middleware)
1523
- */
1524
- export async function callSeoTool(
1525
- toolName: string,
1526
- args: Record<string, any> = {}
1527
- ): Promise<any> {
1528
- const body = JSON.stringify({ tool: toolName, arguments: args });
1529
-
1530
- const isServer = typeof window === 'undefined';
1531
-
1532
- let response: Response;
1533
- if (isServer) {
1534
- const apiUrl =
1535
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1536
- EGDESK_CONFIG.apiUrl;
1537
- response = await fetch(\`\${apiUrl}/seo/tools/call\`, {
1538
- method: 'POST',
1539
- headers: buildServerEgdeskHeaders(),
1540
- body
1541
- });
1542
- } else {
1543
- response = await apiFetch('/__seo_proxy', {
1544
- method: 'POST',
1545
- headers: { 'Content-Type': 'application/json' },
1546
- body
1547
- });
1548
- }
1549
-
1550
- return parseEgdeskMcpToolResponse(response);
1551
- }
1552
-
1553
- /** Run Lighthouse audits on one or more URLs (max 5; ~30–60s per URL) */
1554
- export async function runLighthouse(
1555
- urls: string[],
1556
- options: {
1557
- proxy?: string;
1558
- includeAiExplanation?: boolean;
1559
- } = {}
1560
- ) {
1561
- return callSeoTool('seo_run_lighthouse', { urls, ...options });
1562
- }
1563
-
1564
- /** List saved SEO Lighthouse report summaries */
1565
- export async function listSeoReports(options: { url?: string; limit?: number } = {}) {
1566
- return callSeoTool('seo_list_reports', options);
1567
- }
1568
-
1569
- /** Get a saved SEO report by ID */
1570
- export async function getSeoReport(id: string) {
1571
- return callSeoTool('seo_get_report', { id });
1572
- }
1573
-
1574
- /** Get Lighthouse issues grouped by category for a saved report */
1575
- export async function getSeoIssuesSummary(reportId: string) {
1576
- return callSeoTool('seo_get_issues_summary', { reportId });
1577
- }
1578
-
1579
- // ==========================================
1580
- // SSL (MCP)
1581
- // ==========================================
1582
-
1583
- /**
1584
- * Call EGDesk SSL MCP tool (TLS/security analysis and certificate management).
1585
- *
1586
- * - Server: \`POST {apiUrl}/ssl/tools/call\`
1587
- * - Client: \`POST /__ssl_proxy\` (see proxy.ts / middleware)
1588
- */
1589
- export async function callSslTool(
1590
- toolName: string,
1591
- args: Record<string, any> = {}
1592
- ): Promise<any> {
1593
- const body = JSON.stringify({ tool: toolName, arguments: args });
1594
-
1595
- const isServer = typeof window === 'undefined';
1596
-
1597
- let response: Response;
1598
- if (isServer) {
1599
- const apiUrl =
1600
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1601
- EGDESK_CONFIG.apiUrl;
1602
- response = await fetch(\`\${apiUrl}/ssl/tools/call\`, {
1603
- method: 'POST',
1604
- headers: buildServerEgdeskHeaders(),
1605
- body
1606
- });
1607
- } else {
1608
- response = await apiFetch('/__ssl_proxy', {
1609
- method: 'POST',
1610
- headers: { 'Content-Type': 'application/json' },
1611
- body
1612
- });
1613
- }
1614
-
1615
- return parseEgdeskMcpToolResponse(response);
1616
- }
1617
-
1618
- /** Full SSL/security audit: cert, headers, and letter grade (A+ to F) */
1619
- export async function analyzeSslSite(url: string, save: boolean = true) {
1620
- return callSslTool('ssl_analyze_site', { url, save });
1621
- }
1622
-
1623
- /** Inspect TLS certificate for a URL (expiry, issuer, SANs) */
1624
- export async function checkSslCertificate(url: string) {
1625
- return callSslTool('ssl_check_certificate', { url });
1626
- }
1627
-
1628
- /** Check security headers (HSTS, CSP, X-Frame-Options, etc.) */
1629
- export async function checkSecurityHeaders(url: string) {
1630
- return callSslTool('ssl_check_security_headers', { url });
1631
- }
1632
-
1633
- /** List saved SSL analysis history entries */
1634
- export async function listSslAnalyses(options: { websiteUrl?: string; limit?: number } = {}) {
1635
- return callSslTool('ssl_list_analyses', options);
1636
- }
1637
-
1638
- /** Get a saved SSL analysis by ID */
1639
- export async function getSslAnalysis(id: string) {
1640
- return callSslTool('ssl_get_analysis', { id });
1641
- }
1642
-
1643
- /** List stored SSL certificates (metadata only, no private keys) */
1644
- export async function listSslCertificates() {
1645
- return callSslTool('ssl_list_certificates', {});
1646
- }
1647
-
1648
- /** Get stored certificate metadata by ID */
1649
- export async function getSslCertificate(id: string) {
1650
- return callSslTool('ssl_get_certificate', { id });
1651
- }
1652
-
1653
- /** Generate a self-signed certificate for local development */
1654
- export async function generateSelfSignedCertificate(domain: string) {
1655
- return callSslTool('ssl_generate_self_signed', { domain });
1656
- }
1657
-
1658
- /** Generate a mkcert-trusted local development certificate (macOS) */
1659
- export async function generateTrustedLocalCertificate(domain: string = 'egdesk.local') {
1660
- return callSslTool('ssl_generate_trusted_local', { domain });
1661
- }
1662
-
1663
- /** Request a Let's Encrypt certificate via ACME HTTP-01 */
1664
- export async function generateLetsEncryptCertificate(domain: string, email?: string) {
1665
- return callSslTool('ssl_generate_lets_encrypt', { domain, email });
1666
- }
1667
-
1668
- /** Set the active certificate used by EGDesk dev servers */
1669
- export async function setActiveSslCertificate(certificateId: string | null) {
1670
- return callSslTool('ssl_set_active_certificate', { certificateId });
1671
- }
1672
-
1673
- /** Delete a stored certificate by ID */
1674
- export async function deleteSslCertificate(id: string) {
1675
- return callSslTool('ssl_delete_certificate', { id });
1676
- }
1677
-
1678
- // ==========================================
1679
- // Local Agent AI (MCP)
1680
- // ==========================================
1681
-
1682
- /**
1683
- * Call EGDesk Local Agent MCP tool (Ollama + Gemma 4 QAT offline inference).
1684
- *
1685
- * Pairs with filesystem MCP (discover/read files) and file-conversion MCP (format changes).
1686
- *
1687
- * - Server: \`POST {apiUrl}/local-agent/tools/call\`
1688
- * - Client: \`POST /__local_agent_proxy\` (see proxy.ts / middleware)
1689
- */
1690
- export async function callLocalAgentTool(
1691
- toolName: string,
1692
- args: Record<string, any> = {}
1693
- ): Promise<any> {
1694
- const body = JSON.stringify({ tool: toolName, arguments: args });
1695
-
1696
- const isServer = typeof window === 'undefined';
1697
-
1698
- let response: Response;
1699
- if (isServer) {
1700
- const apiUrl =
1701
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1702
- EGDESK_CONFIG.apiUrl;
1703
- response = await fetch(\`\${apiUrl}/local-agent/tools/call\`, {
1704
- method: 'POST',
1705
- headers: buildServerEgdeskHeaders(),
1706
- body
1707
- });
1708
- } else {
1709
- response = await apiFetch('/__local_agent_proxy', {
1710
- method: 'POST',
1711
- headers: { 'Content-Type': 'application/json' },
1712
- body
1713
- });
1714
- }
1715
-
1716
- return parseEgdeskMcpToolResponse(response);
1717
- }
1718
-
1719
- /** Check Ollama status, default model install state, and attachment capabilities */
1720
- export async function getLocalAgentStatus() {
1721
- return callLocalAgentTool('local_agent_status', {});
1722
- }
1723
-
1724
- /**
1725
- * Pull the default local agent model (Gemma 4 E4B QAT).
1726
- * Optional \`model\` overrides the Ollama tag.
1727
- */
1728
- export async function pullLocalAgentModel(model?: string) {
1729
- return callLocalAgentTool('local_agent_pull', model ? { model } : {});
1730
- }
1731
-
1732
- export type LocalAgentChatMessage = {
1733
- role: 'system' | 'user' | 'assistant';
1734
- content: string;
1735
- };
1736
-
1737
- export type LocalAgentCallOptions = {
1738
- messages?: LocalAgentChatMessage[];
1739
- /** Base64 strings (raw or data URLs) */
1740
- images?: string[];
1741
- /** Absolute paths — images, text files, .pdf, .docx (same rules as filesystem MCP) */
1742
- filePaths?: string[];
1743
- systemPrompt?: string;
1744
- model?: string;
1745
- };
1746
-
1747
- /**
1748
- * Run offline chat with the local agent.
1749
- * Use filesystem MCP (fs_search_files, fs_read_image) to discover files first when needed.
1750
- */
1751
- export async function callLocalAgent(prompt: string, options: LocalAgentCallOptions = {}) {
1752
- return callLocalAgentTool('local_agent_call', { prompt, ...options });
1753
- }
1754
-
1755
- // ==========================================
1756
- // PageIndex (MCP) — PDF RAG
1757
- // ==========================================
1758
-
1759
- /**
1760
- * Call EGDesk PageIndex MCP tool (vectorless PDF indexing and retrieval).
1761
- *
1762
- * PDF only. Use filesystem MCP to find files; file-conversion MCP to produce PDFs from other formats.
1763
- *
1764
- * - Server: \`POST {apiUrl}/pageindex/tools/call\`
1765
- * - Client: \`POST /__pageindex_proxy\` (see proxy.ts / middleware)
1766
- */
1767
- export async function callPageIndexTool(
1768
- toolName: string,
1769
- args: Record<string, any> = {}
1770
- ): Promise<any> {
1771
- const body = JSON.stringify({ tool: toolName, arguments: args });
1772
-
1773
- const isServer = typeof window === 'undefined';
1774
-
1775
- let response: Response;
1776
- if (isServer) {
1777
- const apiUrl =
1778
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1779
- EGDESK_CONFIG.apiUrl;
1780
- response = await fetch(\`\${apiUrl}/pageindex/tools/call\`, {
1781
- method: 'POST',
1782
- headers: buildServerEgdeskHeaders(),
1783
- body
1784
- });
1785
- } else {
1786
- response = await apiFetch('/__pageindex_proxy', {
1787
- method: 'POST',
1788
- headers: { 'Content-Type': 'application/json' },
1789
- body
1790
- });
1791
- }
1792
-
1793
- return parseEgdeskMcpToolResponse(response);
1794
- }
1795
-
1796
- /** Index a PDF and build a hierarchical PageIndex tree (30–60s; requires Gemini API key) */
1797
- export async function indexPageIndexPdf(filePath: string) {
1798
- return callPageIndexTool('pageindex_index_document', { file_path: filePath });
1799
- }
1800
-
1801
- /** List indexed PDF documents */
1802
- export async function listPageIndexDocuments() {
1803
- return callPageIndexTool('pageindex_list_documents', {});
1804
- }
1805
-
1806
- /** Get metadata for an indexed document */
1807
- export async function getPageIndexDocument(docId: string) {
1808
- return callPageIndexTool('pageindex_get_document', { doc_id: docId });
1809
- }
1810
-
1811
- /** Get hierarchical structure (titles, page ranges, summaries — no full text) */
1812
- export async function getPageIndexStructure(docId: string) {
1813
- return callPageIndexTool('pageindex_get_structure', { doc_id: docId });
1814
- }
1815
-
1816
- /** Get raw text for specific pages (e.g. pages: "5", "3,8", "5-7") */
1817
- export async function getPageIndexPages(docId: string, pages: string) {
1818
- return callPageIndexTool('pageindex_get_pages', { doc_id: docId, pages });
1819
- }
1820
-
1821
- /** Delete an indexed document */
1822
- export async function deletePageIndexDocument(docId: string) {
1823
- return callPageIndexTool('pageindex_delete_document', { doc_id: docId });
1824
- }
1825
- `;
1826
-
1827
- fs.writeFileSync(helperPath, helperContent.replace(/\r?\n/g, os.EOL), 'utf-8');
1828
- console.log(`✅ Generated ${helperPath}`);
1829
- }