@egdesk/next-api-plugin 1.5.3 → 1.5.5

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.
@@ -38,10 +38,100 @@ var __importStar = (this && this.__importStar) || (function () {
38
38
  };
39
39
  })();
40
40
  Object.defineProperty(exports, "__esModule", { value: true });
41
+ exports.formatEgdeskSchemaFileContent = formatEgdeskSchemaFileContent;
42
+ exports.generateSchemaFile = generateSchemaFile;
43
+ exports.ensureSchemaFile = ensureSchemaFile;
41
44
  exports.generateHelpers = generateHelpers;
42
45
  const fs = __importStar(require("fs"));
43
46
  const path = __importStar(require("path"));
44
47
  const os = __importStar(require("os"));
48
+ /** Columns auto-managed by EGDesk — omit from committed seed schema. */
49
+ const SYSTEM_SCHEMA_COLUMNS = new Set(['id', 'imported_at']);
50
+ function escapeTsString(value) {
51
+ return value.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
52
+ }
53
+ function schemaKeyForTable(tableName) {
54
+ const key = tableName.replace(/[^a-zA-Z0-9_]/g, '_');
55
+ return /^[a-zA-Z_]/.test(key) ? key : `_${key}`;
56
+ }
57
+ /**
58
+ * Format egdesk.schema.ts content — the committed, portable seed schema.
59
+ */
60
+ function formatEgdeskSchemaFileContent(tables) {
61
+ const tableEntries = tables.length === 0
62
+ ? ` // example_table: {
63
+ // name: 'example_table',
64
+ // displayName: 'Example Table',
65
+ // columns: ['name', 'created_at'],
66
+ // columnCount: 2,
67
+ // rowCount: 0,
68
+ // },`
69
+ : tables
70
+ .map((table) => {
71
+ const key = schemaKeyForTable(table.tableName);
72
+ const userColumns = table.columns.filter((col) => !SYSTEM_SCHEMA_COLUMNS.has(col));
73
+ const columns = userColumns.map((col) => `'${escapeTsString(col)}'`).join(', ');
74
+ return ` ${key}: {
75
+ name: '${escapeTsString(table.tableName)}',
76
+ displayName: '${escapeTsString(table.displayName)}',
77
+ columns: [${columns}],
78
+ columnCount: ${userColumns.length},
79
+ rowCount: 0,
80
+ }`;
81
+ })
82
+ .join(',\n');
83
+ return `/**
84
+ * egdesk.schema.ts — committed seed schema
85
+ *
86
+ * COMMIT THIS FILE TO GIT.
87
+ *
88
+ * When someone opens this project in their EGDesk, these tables are created
89
+ * automatically in their dev database on first server start.
90
+ *
91
+ * Unlike egdesk.config.ts (auto-generated, gitignored), this file is the
92
+ * portable source of truth for your app's database structure.
93
+ *
94
+ * Edit this file when you add/remove tables or columns. Do NOT edit
95
+ * egdesk.config.ts — EGDesk regenerates it from the live database.
96
+ */
97
+
98
+ export const TABLES = {
99
+ ${tableEntries}
100
+ } as const;
101
+
102
+ export type TableName = keyof typeof TABLES;
103
+ export const TABLE_NAMES = Object.keys(TABLES) as TableName[];
104
+ `;
105
+ }
106
+ /**
107
+ * Write egdesk.schema.ts to the project root.
108
+ */
109
+ function generateSchemaFile(projectPath, tables) {
110
+ const schemaPath = path.join(projectPath, 'egdesk.schema.ts');
111
+ fs.writeFileSync(schemaPath, formatEgdeskSchemaFileContent(tables).replace(/\r?\n/g, os.EOL), 'utf-8');
112
+ console.log(`✅ Generated ${schemaPath}`);
113
+ }
114
+ /**
115
+ * Create egdesk.schema.ts only when missing. Never overwrites an existing file.
116
+ */
117
+ function ensureSchemaFile(projectPath, tables) {
118
+ const schemaPath = path.join(projectPath, 'egdesk.schema.ts');
119
+ if (fs.existsSync(schemaPath)) {
120
+ return { created: false, source: 'existing', tableCount: tables.length };
121
+ }
122
+ const userTables = tables
123
+ .map((table) => ({
124
+ ...table,
125
+ columns: table.columns.filter((col) => !SYSTEM_SCHEMA_COLUMNS.has(col)),
126
+ }))
127
+ .filter((table) => table.columns.length > 0);
128
+ generateSchemaFile(projectPath, userTables);
129
+ return {
130
+ created: true,
131
+ source: userTables.length > 0 ? 'database' : 'template',
132
+ tableCount: userTables.length,
133
+ };
134
+ }
45
135
  /**
46
136
  * Generate egdesk-helpers.ts file
47
137
  */
@@ -51,14 +141,70 @@ function generateHelpers(projectPath) {
51
141
  * EGDesk Helper Functions for Next.js
52
142
  *
53
143
  * Type-safe helpers for EGDesk user data, FinanceHub (banks, cards, Hometax, promissory notes),
54
- * internal knowledge / business identity / company research (MCP), and browser recorder replay.
144
+ * internal knowledge / business identity / company research (MCP), Korean law (MCP), and browser recorder replay.
55
145
  * Works in both client and server components.
56
146
  *
57
- * Generated by @egdesk/next-api-plugin
147
+ * Generated by @egdesk/next-api-plugin — do not edit by hand.
148
+ *
149
+ * Schema files:
150
+ * - egdesk.schema.ts — committed seed schema (edit this; commit to git)
151
+ * - egdesk.config.ts — auto-generated runtime snapshot (gitignored; do not edit)
58
152
  */
59
153
 
60
154
  import { EGDESK_CONFIG } from './egdesk.config';
61
155
 
156
+ /**
157
+ * Resolve EGDesk tunnel basePath for client-side fetch.
158
+ * Next.js basePath does NOT apply to raw fetch() — prepend manually in production.
159
+ */
160
+ export function getEgdeskBasePath(): string {
161
+ if (typeof window === 'undefined') {
162
+ return (
163
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_BASE_PATH) ||
164
+ (typeof process !== 'undefined' && process.env?.EGDESK_BASE_PATH) ||
165
+ ''
166
+ );
167
+ }
168
+
169
+ const fromEnv =
170
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_BASE_PATH) || '';
171
+ if (fromEnv) return fromEnv;
172
+
173
+ // Fallback: detect /t/{tunnelId}/p/{projectName} from the current URL
174
+ const parts = window.location.pathname.split('/').filter(Boolean);
175
+ if (parts[0] === 't' && parts.length >= 4 && parts[2] === 'p') {
176
+ return \`/\${parts.slice(0, 4).join('/')}\`;
177
+ }
178
+ return '';
179
+ }
180
+
181
+ /**
182
+ * Fetch wrapper that prepends EGDesk basePath to relative URLs.
183
+ * Use for /api/* routes and /__*_proxy paths in client components.
184
+ */
185
+ export async function apiFetch(path: string, options?: RequestInit): Promise<Response> {
186
+ const basePath = getEgdeskBasePath();
187
+ const url =
188
+ path.startsWith('/') && !path.startsWith('//') ? \`\${basePath}\${path}\` : path;
189
+ return fetch(url, options);
190
+ }
191
+
192
+ /** Build EGDesk routing headers (project-id + env) for server-side direct calls. */
193
+ function buildServerEgdeskHeaders(): Record<string, string> {
194
+ const headers: Record<string, string> = { 'Content-Type': 'application/json' };
195
+ const apiKey =
196
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_KEY) ||
197
+ EGDESK_CONFIG.apiKey;
198
+ const projectId =
199
+ typeof process !== 'undefined' ? process.env?.NEXT_PUBLIC_EGDESK_PROJECT_ID : undefined;
200
+ const egdeskEnv =
201
+ typeof process !== 'undefined' ? process.env?.NEXT_PUBLIC_EGDESK_ENV : undefined;
202
+ if (apiKey) headers['X-Api-Key'] = apiKey;
203
+ if (projectId) headers['X-EGDesk-Project-Id'] = projectId;
204
+ if (egdeskEnv) headers['X-EGDesk-Env'] = egdeskEnv;
205
+ return headers;
206
+ }
207
+
62
208
  /**
63
209
  * Parse EGDesk MCP \`/tools/call\` JSON so \`error\` is shown even when HTTP status is 500.
64
210
  */
@@ -111,9 +257,6 @@ export async function callUserDataTool(
111
257
  args: Record<string, any> = {}
112
258
  ): Promise<any> {
113
259
  const body = JSON.stringify({ tool: toolName, arguments: args });
114
- const headers: Record<string, string> = {
115
- 'Content-Type': 'application/json'
116
- };
117
260
 
118
261
  const isServer = typeof window === 'undefined';
119
262
 
@@ -123,22 +266,16 @@ export async function callUserDataTool(
123
266
  const apiUrl =
124
267
  (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
125
268
  EGDESK_CONFIG.apiUrl;
126
- const apiKey =
127
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_KEY) ||
128
- EGDESK_CONFIG.apiKey;
129
- if (apiKey) {
130
- headers['X-Api-Key'] = apiKey;
131
- }
132
269
  response = await fetch(\`\${apiUrl}/user-data/tools/call\`, {
133
270
  method: 'POST',
134
- headers,
271
+ headers: buildServerEgdeskHeaders(),
135
272
  body
136
273
  });
137
274
  } else {
138
- // Browser: use proxy for CORS and tunnel base path
139
- response = await fetch('/__user_data_proxy', {
275
+ // Browser: use proxy for CORS and tunnel base path (proxy.ts injects routing headers)
276
+ response = await apiFetch('/__user_data_proxy', {
140
277
  method: 'POST',
141
- headers,
278
+ headers: { 'Content-Type': 'application/json' },
142
279
  body
143
280
  });
144
281
  }
@@ -201,12 +338,49 @@ export async function aggregateTable(
201
338
  }
202
339
 
203
340
  /**
204
- * Execute raw SQL query (read-only, SELECT only)
341
+ * Execute raw SQL query (read-only, SELECT only).
342
+ * Supports JOINs — use listTables() and getTableSchema() to discover tables/columns first.
343
+ * For structured multi-table joins, prefer joinTables().
205
344
  */
206
345
  export async function executeSQL(query: string) {
207
346
  return callUserDataTool('user_data_sql_query', { query });
208
347
  }
209
348
 
349
+ /**
350
+ * Join one or more tables and query combined rows.
351
+ * Use listTables() and getTableSchema() first to discover table names and columns.
352
+ *
353
+ * @example
354
+ * await joinTables('orders', [
355
+ * { table: 'customers', on: { leftColumn: 'customer_id', rightColumn: 'id' } },
356
+ * { table: 'products', on: { leftColumn: 'orders.product_id', rightColumn: 'id' }, joinType: 'LEFT' },
357
+ * ]);
358
+ */
359
+ export async function joinTables(
360
+ fromTable: string,
361
+ joins: Array<{
362
+ table: string;
363
+ on:
364
+ | { leftColumn: string; rightColumn: string }
365
+ | Array<{ leftColumn: string; rightColumn: string }>;
366
+ joinType?: 'INNER' | 'LEFT' | 'RIGHT';
367
+ }>,
368
+ options: {
369
+ select?: string[];
370
+ filters?: Record<string, string>;
371
+ limit?: number;
372
+ offset?: number;
373
+ orderBy?: string;
374
+ orderDirection?: 'ASC' | 'DESC';
375
+ } = {}
376
+ ) {
377
+ return callUserDataTool('user_data_join', {
378
+ fromTable,
379
+ joins,
380
+ ...options
381
+ });
382
+ }
383
+
210
384
  /**
211
385
  * List all available tables
212
386
  */
@@ -327,9 +501,6 @@ export async function callFinanceHubTool(
327
501
  args: Record<string, any> = {}
328
502
  ): Promise<any> {
329
503
  const body = JSON.stringify({ tool: toolName, arguments: args });
330
- const headers: Record<string, string> = {
331
- 'Content-Type': 'application/json'
332
- };
333
504
 
334
505
  const isServer = typeof window === 'undefined';
335
506
 
@@ -338,21 +509,15 @@ export async function callFinanceHubTool(
338
509
  const apiUrl =
339
510
  (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
340
511
  EGDESK_CONFIG.apiUrl;
341
- const apiKey =
342
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_KEY) ||
343
- EGDESK_CONFIG.apiKey;
344
- if (apiKey) {
345
- headers['X-Api-Key'] = apiKey;
346
- }
347
512
  response = await fetch(\`\${apiUrl}/financehub/tools/call\`, {
348
513
  method: 'POST',
349
- headers,
514
+ headers: buildServerEgdeskHeaders(),
350
515
  body
351
516
  });
352
517
  } else {
353
- response = await fetch('/__financehub_proxy', {
518
+ response = await apiFetch('/__financehub_proxy', {
354
519
  method: 'POST',
355
- headers,
520
+ headers: { 'Content-Type': 'application/json' },
356
521
  body
357
522
  });
358
523
  }
@@ -665,9 +830,6 @@ export async function callInternalKnowledgeTool(
665
830
  args: Record<string, any> = {}
666
831
  ): Promise<any> {
667
832
  const body = JSON.stringify({ tool: toolName, arguments: args });
668
- const headers: Record<string, string> = {
669
- 'Content-Type': 'application/json'
670
- };
671
833
 
672
834
  const isServer = typeof window === 'undefined';
673
835
 
@@ -676,21 +838,15 @@ export async function callInternalKnowledgeTool(
676
838
  const apiUrl =
677
839
  (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
678
840
  EGDESK_CONFIG.apiUrl;
679
- const apiKey =
680
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_KEY) ||
681
- EGDESK_CONFIG.apiKey;
682
- if (apiKey) {
683
- headers['X-Api-Key'] = apiKey;
684
- }
685
841
  response = await fetch(\`\${apiUrl}/internal-knowledge/tools/call\`, {
686
842
  method: 'POST',
687
- headers,
843
+ headers: buildServerEgdeskHeaders(),
688
844
  body
689
845
  });
690
846
  } else {
691
- response = await fetch('/__internal_knowledge_proxy', {
847
+ response = await apiFetch('/__internal_knowledge_proxy', {
692
848
  method: 'POST',
693
- headers,
849
+ headers: { 'Content-Type': 'application/json' },
694
850
  body
695
851
  });
696
852
  }
@@ -785,28 +941,76 @@ export async function getBusinessIdentityServicesProducts(snapshotId: string) {
785
941
  return callInternalKnowledgeTool('businessidentity_get_services_products', { snapshotId });
786
942
  }
787
943
 
944
+ /**
945
+ * Call EGDesk Company Research MCP tool (run workflows and query saved research).
946
+ *
947
+ * - Server: \`POST {apiUrl}/company-research/tools/call\`
948
+ * - Client: \`POST /__company_research_proxy\` (see proxy.ts / middleware)
949
+ */
950
+ export async function callCompanyResearchTool(
951
+ toolName: string,
952
+ args: Record<string, any> = {}
953
+ ): Promise<any> {
954
+ const body = JSON.stringify({ tool: toolName, arguments: args });
955
+
956
+ const isServer = typeof window === 'undefined';
957
+
958
+ let response: Response;
959
+ if (isServer) {
960
+ const apiUrl =
961
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
962
+ EGDESK_CONFIG.apiUrl;
963
+ response = await fetch(\`\${apiUrl}/company-research/tools/call\`, {
964
+ method: 'POST',
965
+ headers: buildServerEgdeskHeaders(),
966
+ body
967
+ });
968
+ } else {
969
+ response = await apiFetch('/__company_research_proxy', {
970
+ method: 'POST',
971
+ headers: { 'Content-Type': 'application/json' },
972
+ body
973
+ });
974
+ }
975
+
976
+ return parseEgdeskMcpToolResponse(response);
977
+ }
978
+
979
+ /** Run full company research workflow for a domain (several minutes) */
980
+ export async function runCompanyResearch(
981
+ domain: string,
982
+ options: { bypassCache?: boolean; inquiryData?: Record<string, any> } = {}
983
+ ) {
984
+ return callCompanyResearchTool('companyresearch_run', { domain, ...options });
985
+ }
986
+
788
987
  /** List company research records */
789
988
  export async function listCompanyResearch(
790
989
  status?: 'completed' | 'failed' | 'in_progress'
791
990
  ) {
792
- return callInternalKnowledgeTool('companyresearch_list_all', {
991
+ return callCompanyResearchTool('companyresearch_list_all', {
793
992
  ...(status != null ? { status } : {})
794
993
  });
795
994
  }
796
995
 
797
996
  /** One company research record by ID */
798
997
  export async function getCompanyResearchById(researchId: string) {
799
- return callInternalKnowledgeTool('companyresearch_get_by_id', { researchId });
998
+ return callCompanyResearchTool('companyresearch_get_by_id', { researchId });
800
999
  }
801
1000
 
802
1001
  /** Research records for a domain */
803
1002
  export async function getCompanyResearchByDomain(domain: string) {
804
- return callInternalKnowledgeTool('companyresearch_get_by_domain', { domain });
1003
+ return callCompanyResearchTool('companyresearch_get_by_domain', { domain });
1004
+ }
1005
+
1006
+ /** Most recent completed research for a domain */
1007
+ export async function getLatestCompletedCompanyResearch(domain: string) {
1008
+ return callCompanyResearchTool('companyresearch_get_latest_completed', { domain });
805
1009
  }
806
1010
 
807
1011
  /** Search company research by company name or domain */
808
1012
  export async function searchCompanyResearch(searchText: string) {
809
- return callInternalKnowledgeTool('companyresearch_search', { searchText });
1013
+ return callCompanyResearchTool('companyresearch_search', { searchText });
810
1014
  }
811
1015
 
812
1016
  // ==========================================
@@ -824,9 +1028,6 @@ export async function callBrowserRecordingTool(
824
1028
  args: Record<string, any> = {}
825
1029
  ): Promise<any> {
826
1030
  const body = JSON.stringify({ tool: toolName, arguments: args });
827
- const headers: Record<string, string> = {
828
- 'Content-Type': 'application/json'
829
- };
830
1031
 
831
1032
  const isServer = typeof window === 'undefined';
832
1033
 
@@ -835,21 +1036,15 @@ export async function callBrowserRecordingTool(
835
1036
  const apiUrl =
836
1037
  (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
837
1038
  EGDESK_CONFIG.apiUrl;
838
- const apiKey =
839
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_KEY) ||
840
- EGDESK_CONFIG.apiKey;
841
- if (apiKey) {
842
- headers['X-Api-Key'] = apiKey;
843
- }
844
1039
  response = await fetch(\`\${apiUrl}/browser-recording/tools/call\`, {
845
1040
  method: 'POST',
846
- headers,
1041
+ headers: buildServerEgdeskHeaders(),
847
1042
  body
848
1043
  });
849
1044
  } else {
850
- response = await fetch('/__browser_recording_proxy', {
1045
+ response = await apiFetch('/__browser_recording_proxy', {
851
1046
  method: 'POST',
852
- headers,
1047
+ headers: { 'Content-Type': 'application/json' },
853
1048
  body
854
1049
  });
855
1050
  }
@@ -926,6 +1121,16 @@ export async function removeBrowserRecordingSchedule(testFile: string) {
926
1121
  return callBrowserRecordingTool('browser_recording_remove_schedule', { testFile });
927
1122
  }
928
1123
 
1124
+ /** Pause a recurring schedule without deleting it */
1125
+ export async function pauseBrowserRecordingSchedule(testFile: string) {
1126
+ return callBrowserRecordingTool('browser_recording_pause_schedule', { testFile });
1127
+ }
1128
+
1129
+ /** Resume a paused recurring schedule */
1130
+ export async function resumeBrowserRecordingSchedule(testFile: string) {
1131
+ return callBrowserRecordingTool('browser_recording_resume_schedule', { testFile });
1132
+ }
1133
+
929
1134
  export type BrowserRecordingSyncConfigOptions = {
930
1135
  testFile?: string;
931
1136
  scriptFolderPath?: string;
@@ -992,9 +1197,6 @@ export async function callAICenterTool(
992
1197
  args: Record<string, any> = {}
993
1198
  ): Promise<any> {
994
1199
  const body = JSON.stringify({ tool: toolName, arguments: args });
995
- const headers: Record<string, string> = {
996
- 'Content-Type': 'application/json'
997
- };
998
1200
 
999
1201
  const isServer = typeof window === 'undefined';
1000
1202
 
@@ -1003,21 +1205,15 @@ export async function callAICenterTool(
1003
1205
  const apiUrl =
1004
1206
  (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1005
1207
  EGDESK_CONFIG.apiUrl;
1006
- const apiKey =
1007
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_KEY) ||
1008
- EGDESK_CONFIG.apiKey;
1009
- if (apiKey) {
1010
- headers['X-Api-Key'] = apiKey;
1011
- }
1012
1208
  response = await fetch(\`\${apiUrl}/ai-center/tools/call\`, {
1013
1209
  method: 'POST',
1014
- headers,
1210
+ headers: buildServerEgdeskHeaders(),
1015
1211
  body
1016
1212
  });
1017
1213
  } else {
1018
- response = await fetch('/__ai_center_proxy', {
1214
+ response = await apiFetch('/__ai_center_proxy', {
1019
1215
  method: 'POST',
1020
- headers,
1216
+ headers: { 'Content-Type': 'application/json' },
1021
1217
  body
1022
1218
  });
1023
1219
  }
@@ -1261,6 +1457,382 @@ export async function getCalendarEventsFromAICenter() {
1261
1457
  export async function completeTask(taskId: string, status: 'completed' | 'approved' | 'rejected') {
1262
1458
  return callAICenterTool('ai_center_complete_task', { taskId, status });
1263
1459
  }
1460
+
1461
+ // ==========================================
1462
+ // KOREAN LAW / LAWYER (MCP)
1463
+ // ==========================================
1464
+
1465
+ /**
1466
+ * Call EGDesk Korean Law MCP tool (법제처 API — laws, precedents, admin rules, municipal ordinances).
1467
+ *
1468
+ * - Server: \`POST {apiUrl}/korean-law/tools/call\`
1469
+ * - Client: \`POST /__korean_law_proxy\` (see proxy.ts / middleware)
1470
+ */
1471
+ export async function callKoreanLawTool(
1472
+ toolName: string,
1473
+ args: Record<string, any> = {}
1474
+ ): Promise<any> {
1475
+ const body = JSON.stringify({ tool: toolName, arguments: args });
1476
+
1477
+ const isServer = typeof window === 'undefined';
1478
+
1479
+ let response: Response;
1480
+ if (isServer) {
1481
+ const apiUrl =
1482
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1483
+ EGDESK_CONFIG.apiUrl;
1484
+ response = await fetch(\`\${apiUrl}/korean-law/tools/call\`, {
1485
+ method: 'POST',
1486
+ headers: buildServerEgdeskHeaders(),
1487
+ body
1488
+ });
1489
+ } else {
1490
+ response = await apiFetch('/__korean_law_proxy', {
1491
+ method: 'POST',
1492
+ headers: { 'Content-Type': 'application/json' },
1493
+ body
1494
+ });
1495
+ }
1496
+
1497
+ return parseEgdeskMcpToolResponse(response);
1498
+ }
1499
+
1500
+ /** Search laws, precedents, administrative rules, or municipal ordinances */
1501
+ export async function searchKoreanLaw(
1502
+ query: string,
1503
+ options: {
1504
+ target?: 'law' | 'prec' | 'admrul' | 'ordin';
1505
+ display?: number;
1506
+ page?: number;
1507
+ } = {}
1508
+ ) {
1509
+ return callKoreanLawTool('korean_law_search', { query, ...options });
1510
+ }
1511
+
1512
+ /** Get full text of a law, administrative rule, or municipal ordinance */
1513
+ export async function getKoreanLawText(
1514
+ id: string,
1515
+ target: 'law' | 'admrul' | 'ordin' = 'law'
1516
+ ) {
1517
+ return callKoreanLawTool('korean_law_get_text', { id, target });
1518
+ }
1519
+
1520
+ /** Get full text of a court precedent (판례) */
1521
+ export async function getKoreanLawDecision(id: string) {
1522
+ return callKoreanLawTool('korean_law_get_decision', { id });
1523
+ }
1524
+
1525
+ // ==========================================
1526
+ // SEO (MCP)
1527
+ // ==========================================
1528
+
1529
+ /**
1530
+ * Call EGDesk SEO MCP tool (Lighthouse audits and report history).
1531
+ *
1532
+ * - Server: \`POST {apiUrl}/seo/tools/call\`
1533
+ * - Client: \`POST /__seo_proxy\` (see proxy.ts / middleware)
1534
+ */
1535
+ export async function callSeoTool(
1536
+ toolName: string,
1537
+ args: Record<string, any> = {}
1538
+ ): Promise<any> {
1539
+ const body = JSON.stringify({ tool: toolName, arguments: args });
1540
+
1541
+ const isServer = typeof window === 'undefined';
1542
+
1543
+ let response: Response;
1544
+ if (isServer) {
1545
+ const apiUrl =
1546
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1547
+ EGDESK_CONFIG.apiUrl;
1548
+ response = await fetch(\`\${apiUrl}/seo/tools/call\`, {
1549
+ method: 'POST',
1550
+ headers: buildServerEgdeskHeaders(),
1551
+ body
1552
+ });
1553
+ } else {
1554
+ response = await apiFetch('/__seo_proxy', {
1555
+ method: 'POST',
1556
+ headers: { 'Content-Type': 'application/json' },
1557
+ body
1558
+ });
1559
+ }
1560
+
1561
+ return parseEgdeskMcpToolResponse(response);
1562
+ }
1563
+
1564
+ /** Run Lighthouse audits on one or more URLs (max 5; ~30–60s per URL) */
1565
+ export async function runLighthouse(
1566
+ urls: string[],
1567
+ options: {
1568
+ proxy?: string;
1569
+ includeAiExplanation?: boolean;
1570
+ } = {}
1571
+ ) {
1572
+ return callSeoTool('seo_run_lighthouse', { urls, ...options });
1573
+ }
1574
+
1575
+ /** List saved SEO Lighthouse report summaries */
1576
+ export async function listSeoReports(options: { url?: string; limit?: number } = {}) {
1577
+ return callSeoTool('seo_list_reports', options);
1578
+ }
1579
+
1580
+ /** Get a saved SEO report by ID */
1581
+ export async function getSeoReport(id: string) {
1582
+ return callSeoTool('seo_get_report', { id });
1583
+ }
1584
+
1585
+ /** Get Lighthouse issues grouped by category for a saved report */
1586
+ export async function getSeoIssuesSummary(reportId: string) {
1587
+ return callSeoTool('seo_get_issues_summary', { reportId });
1588
+ }
1589
+
1590
+ // ==========================================
1591
+ // SSL (MCP)
1592
+ // ==========================================
1593
+
1594
+ /**
1595
+ * Call EGDesk SSL MCP tool (TLS/security analysis and certificate management).
1596
+ *
1597
+ * - Server: \`POST {apiUrl}/ssl/tools/call\`
1598
+ * - Client: \`POST /__ssl_proxy\` (see proxy.ts / middleware)
1599
+ */
1600
+ export async function callSslTool(
1601
+ toolName: string,
1602
+ args: Record<string, any> = {}
1603
+ ): Promise<any> {
1604
+ const body = JSON.stringify({ tool: toolName, arguments: args });
1605
+
1606
+ const isServer = typeof window === 'undefined';
1607
+
1608
+ let response: Response;
1609
+ if (isServer) {
1610
+ const apiUrl =
1611
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1612
+ EGDESK_CONFIG.apiUrl;
1613
+ response = await fetch(\`\${apiUrl}/ssl/tools/call\`, {
1614
+ method: 'POST',
1615
+ headers: buildServerEgdeskHeaders(),
1616
+ body
1617
+ });
1618
+ } else {
1619
+ response = await apiFetch('/__ssl_proxy', {
1620
+ method: 'POST',
1621
+ headers: { 'Content-Type': 'application/json' },
1622
+ body
1623
+ });
1624
+ }
1625
+
1626
+ return parseEgdeskMcpToolResponse(response);
1627
+ }
1628
+
1629
+ /** Full SSL/security audit: cert, headers, and letter grade (A+ to F) */
1630
+ export async function analyzeSslSite(url: string, save: boolean = true) {
1631
+ return callSslTool('ssl_analyze_site', { url, save });
1632
+ }
1633
+
1634
+ /** Inspect TLS certificate for a URL (expiry, issuer, SANs) */
1635
+ export async function checkSslCertificate(url: string) {
1636
+ return callSslTool('ssl_check_certificate', { url });
1637
+ }
1638
+
1639
+ /** Check security headers (HSTS, CSP, X-Frame-Options, etc.) */
1640
+ export async function checkSecurityHeaders(url: string) {
1641
+ return callSslTool('ssl_check_security_headers', { url });
1642
+ }
1643
+
1644
+ /** List saved SSL analysis history entries */
1645
+ export async function listSslAnalyses(options: { websiteUrl?: string; limit?: number } = {}) {
1646
+ return callSslTool('ssl_list_analyses', options);
1647
+ }
1648
+
1649
+ /** Get a saved SSL analysis by ID */
1650
+ export async function getSslAnalysis(id: string) {
1651
+ return callSslTool('ssl_get_analysis', { id });
1652
+ }
1653
+
1654
+ /** List stored SSL certificates (metadata only, no private keys) */
1655
+ export async function listSslCertificates() {
1656
+ return callSslTool('ssl_list_certificates', {});
1657
+ }
1658
+
1659
+ /** Get stored certificate metadata by ID */
1660
+ export async function getSslCertificate(id: string) {
1661
+ return callSslTool('ssl_get_certificate', { id });
1662
+ }
1663
+
1664
+ /** Generate a self-signed certificate for local development */
1665
+ export async function generateSelfSignedCertificate(domain: string) {
1666
+ return callSslTool('ssl_generate_self_signed', { domain });
1667
+ }
1668
+
1669
+ /** Generate a mkcert-trusted local development certificate (macOS) */
1670
+ export async function generateTrustedLocalCertificate(domain: string = 'egdesk.local') {
1671
+ return callSslTool('ssl_generate_trusted_local', { domain });
1672
+ }
1673
+
1674
+ /** Request a Let's Encrypt certificate via ACME HTTP-01 */
1675
+ export async function generateLetsEncryptCertificate(domain: string, email?: string) {
1676
+ return callSslTool('ssl_generate_lets_encrypt', { domain, email });
1677
+ }
1678
+
1679
+ /** Set the active certificate used by EGDesk dev servers */
1680
+ export async function setActiveSslCertificate(certificateId: string | null) {
1681
+ return callSslTool('ssl_set_active_certificate', { certificateId });
1682
+ }
1683
+
1684
+ /** Delete a stored certificate by ID */
1685
+ export async function deleteSslCertificate(id: string) {
1686
+ return callSslTool('ssl_delete_certificate', { id });
1687
+ }
1688
+
1689
+ // ==========================================
1690
+ // Local Agent AI (MCP)
1691
+ // ==========================================
1692
+
1693
+ /**
1694
+ * Call EGDesk Local Agent MCP tool (Ollama + Gemma 4 QAT offline inference).
1695
+ *
1696
+ * Pairs with filesystem MCP (discover/read files) and file-conversion MCP (format changes).
1697
+ *
1698
+ * - Server: \`POST {apiUrl}/local-agent/tools/call\`
1699
+ * - Client: \`POST /__local_agent_proxy\` (see proxy.ts / middleware)
1700
+ */
1701
+ export async function callLocalAgentTool(
1702
+ toolName: string,
1703
+ args: Record<string, any> = {}
1704
+ ): Promise<any> {
1705
+ const body = JSON.stringify({ tool: toolName, arguments: args });
1706
+
1707
+ const isServer = typeof window === 'undefined';
1708
+
1709
+ let response: Response;
1710
+ if (isServer) {
1711
+ const apiUrl =
1712
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1713
+ EGDESK_CONFIG.apiUrl;
1714
+ response = await fetch(\`\${apiUrl}/local-agent/tools/call\`, {
1715
+ method: 'POST',
1716
+ headers: buildServerEgdeskHeaders(),
1717
+ body
1718
+ });
1719
+ } else {
1720
+ response = await apiFetch('/__local_agent_proxy', {
1721
+ method: 'POST',
1722
+ headers: { 'Content-Type': 'application/json' },
1723
+ body
1724
+ });
1725
+ }
1726
+
1727
+ return parseEgdeskMcpToolResponse(response);
1728
+ }
1729
+
1730
+ /** Check Ollama status, default model install state, and attachment capabilities */
1731
+ export async function getLocalAgentStatus() {
1732
+ return callLocalAgentTool('local_agent_status', {});
1733
+ }
1734
+
1735
+ /**
1736
+ * Pull the default local agent model (Gemma 4 E4B QAT).
1737
+ * Optional \`model\` overrides the Ollama tag.
1738
+ */
1739
+ export async function pullLocalAgentModel(model?: string) {
1740
+ return callLocalAgentTool('local_agent_pull', model ? { model } : {});
1741
+ }
1742
+
1743
+ export type LocalAgentChatMessage = {
1744
+ role: 'system' | 'user' | 'assistant';
1745
+ content: string;
1746
+ };
1747
+
1748
+ export type LocalAgentCallOptions = {
1749
+ messages?: LocalAgentChatMessage[];
1750
+ /** Base64 strings (raw or data URLs) */
1751
+ images?: string[];
1752
+ /** Absolute paths — images, text files, .pdf, .docx (same rules as filesystem MCP) */
1753
+ filePaths?: string[];
1754
+ systemPrompt?: string;
1755
+ model?: string;
1756
+ };
1757
+
1758
+ /**
1759
+ * Run offline chat with the local agent.
1760
+ * Use filesystem MCP (fs_search_files, fs_read_image) to discover files first when needed.
1761
+ */
1762
+ export async function callLocalAgent(prompt: string, options: LocalAgentCallOptions = {}) {
1763
+ return callLocalAgentTool('local_agent_call', { prompt, ...options });
1764
+ }
1765
+
1766
+ // ==========================================
1767
+ // PageIndex (MCP) — PDF RAG
1768
+ // ==========================================
1769
+
1770
+ /**
1771
+ * Call EGDesk PageIndex MCP tool (vectorless PDF indexing and retrieval).
1772
+ *
1773
+ * PDF only. Use filesystem MCP to find files; file-conversion MCP to produce PDFs from other formats.
1774
+ *
1775
+ * - Server: \`POST {apiUrl}/pageindex/tools/call\`
1776
+ * - Client: \`POST /__pageindex_proxy\` (see proxy.ts / middleware)
1777
+ */
1778
+ export async function callPageIndexTool(
1779
+ toolName: string,
1780
+ args: Record<string, any> = {}
1781
+ ): Promise<any> {
1782
+ const body = JSON.stringify({ tool: toolName, arguments: args });
1783
+
1784
+ const isServer = typeof window === 'undefined';
1785
+
1786
+ let response: Response;
1787
+ if (isServer) {
1788
+ const apiUrl =
1789
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1790
+ EGDESK_CONFIG.apiUrl;
1791
+ response = await fetch(\`\${apiUrl}/pageindex/tools/call\`, {
1792
+ method: 'POST',
1793
+ headers: buildServerEgdeskHeaders(),
1794
+ body
1795
+ });
1796
+ } else {
1797
+ response = await apiFetch('/__pageindex_proxy', {
1798
+ method: 'POST',
1799
+ headers: { 'Content-Type': 'application/json' },
1800
+ body
1801
+ });
1802
+ }
1803
+
1804
+ return parseEgdeskMcpToolResponse(response);
1805
+ }
1806
+
1807
+ /** Index a PDF and build a hierarchical PageIndex tree (30–60s; requires Gemini API key) */
1808
+ export async function indexPageIndexPdf(filePath: string) {
1809
+ return callPageIndexTool('pageindex_index_document', { file_path: filePath });
1810
+ }
1811
+
1812
+ /** List indexed PDF documents */
1813
+ export async function listPageIndexDocuments() {
1814
+ return callPageIndexTool('pageindex_list_documents', {});
1815
+ }
1816
+
1817
+ /** Get metadata for an indexed document */
1818
+ export async function getPageIndexDocument(docId: string) {
1819
+ return callPageIndexTool('pageindex_get_document', { doc_id: docId });
1820
+ }
1821
+
1822
+ /** Get hierarchical structure (titles, page ranges, summaries — no full text) */
1823
+ export async function getPageIndexStructure(docId: string) {
1824
+ return callPageIndexTool('pageindex_get_structure', { doc_id: docId });
1825
+ }
1826
+
1827
+ /** Get raw text for specific pages (e.g. pages: "5", "3,8", "5-7") */
1828
+ export async function getPageIndexPages(docId: string, pages: string) {
1829
+ return callPageIndexTool('pageindex_get_pages', { doc_id: docId, pages });
1830
+ }
1831
+
1832
+ /** Delete an indexed document */
1833
+ export async function deletePageIndexDocument(docId: string) {
1834
+ return callPageIndexTool('pageindex_delete_document', { doc_id: docId });
1835
+ }
1264
1836
  `;
1265
1837
  fs.writeFileSync(helperPath, helperContent.replace(/\r?\n/g, os.EOL), 'utf-8');
1266
1838
  console.log(`✅ Generated ${helperPath}`);