@egdesk/next-api-plugin 1.5.86 → 1.5.106

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.
@@ -211,6 +211,26 @@ function buildServerEgdeskHeaders(): Record<string, string> {
211
211
  return headers;
212
212
  }
213
213
 
214
+ /**
215
+ * Server-side MCP root for API routes / RSC.
216
+ * Prefer EGDESK_MCP_INTERNAL_URL (localhost) so hosted Next never re-enters the
217
+ * public tunnel for MCP calls (avoids double-hop upload 504s).
218
+ * Browser code must not use this — use /__*_proxy + apiFetch instead.
219
+ */
220
+ function resolveServerEgdeskApiUrl(): string {
221
+ if (typeof process !== 'undefined') {
222
+ const internal = process.env?.EGDESK_MCP_INTERNAL_URL;
223
+ if (internal && String(internal).trim()) {
224
+ return String(internal).replace(/\\/$/, '');
225
+ }
226
+ const pub = process.env?.NEXT_PUBLIC_EGDESK_API_URL;
227
+ if (pub && String(pub).trim()) {
228
+ return String(pub).replace(/\\/$/, '');
229
+ }
230
+ }
231
+ return String(EGDESK_CONFIG.apiUrl || '').replace(/\\/$/, '');
232
+ }
233
+
214
234
  const VISITOR_SESSION_KEY = 'egdesk_visitor_session';
215
235
 
216
236
  export type WorkspaceVisitorCallOptions = {
@@ -299,9 +319,7 @@ async function callWorkspaceMcpTool(
299
319
  const visitorHeaders = buildWorkspaceVisitorHeaders(options);
300
320
  let response: Response;
301
321
  if (isServer) {
302
- const apiUrl =
303
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
304
- EGDESK_CONFIG.apiUrl;
322
+ const apiUrl = resolveServerEgdeskApiUrl();
305
323
  response = await fetch(\`\${apiUrl}\${path}\`, {
306
324
  method: 'POST',
307
325
  headers: { ...buildServerEgdeskHeaders(), ...visitorHeaders },
@@ -432,9 +450,7 @@ export async function callEgdeskHttp(
432
450
  const isServer = typeof window === 'undefined';
433
451
  let response: Response;
434
452
  if (isServer) {
435
- const apiUrl =
436
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
437
- EGDESK_CONFIG.apiUrl;
453
+ const apiUrl = resolveServerEgdeskApiUrl();
438
454
  const base = apiUrl.endsWith('/') ? apiUrl : \`\${apiUrl}/\`;
439
455
  const url = new URL(pathname.startsWith('/') ? pathname.slice(1) : pathname, base);
440
456
  for (const [key, value] of Object.entries(query)) {
@@ -464,9 +480,8 @@ export async function callEgdeskHttp(
464
480
  /**
465
481
  * Call EGDesk user-data MCP tool
466
482
  *
467
- * - Server (API routes): Calls Egdesk API directly using EGDESK_CONFIG.apiUrl and
468
- * EGDESK_CONFIG.apiKey (from env NEXT_PUBLIC_EGDESK_API_URL / NEXT_PUBLIC_EGDESK_API_KEY)
469
- * so relative URLs and tunnel base path are not an issue.
483
+ * - Server (API routes): Calls Egdesk via resolveServerEgdeskApiUrl()
484
+ * (EGDESK_MCP_INTERNAL_URL localhost first, then NEXT_PUBLIC_EGDESK_API_URL) + API key.
470
485
  * - Client (browser): Uses /__user_data_proxy so CORS and tunnel base path still work.
471
486
  */
472
487
  export async function callUserDataTool(
@@ -480,9 +495,7 @@ export async function callUserDataTool(
480
495
  let response: Response;
481
496
  if (isServer) {
482
497
  // API routes: call Egdesk directly (relative URL is invalid in Node)
483
- const apiUrl =
484
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
485
- EGDESK_CONFIG.apiUrl;
498
+ const apiUrl = resolveServerEgdeskApiUrl();
486
499
  response = await fetch(\`\${apiUrl}/user-data/tools/call\`, {
487
500
  method: 'POST',
488
501
  headers: buildServerEgdeskHeaders(),
@@ -748,12 +761,535 @@ export async function renameTable(
748
761
  // FILE STORAGE HELPERS
749
762
  // ==========================================
750
763
 
764
+ /** Above this decoded size, uploadFile switches to chunked tunnel-safe uploads. */
765
+ const UPLOAD_CHUNKED_THRESHOLD_BYTES = 4 * 1024 * 1024;
766
+
767
+ function estimateBase64DecodedBytes(data: string): number {
768
+ const trimmed = String(data || '').replace(/^data:[^;]+;base64,/i, '').replace(/\\s/g, '');
769
+ return Math.floor((trimmed.length * 3) / 4);
770
+ }
771
+
772
+ function base64ToUint8Array(data: string): Uint8Array {
773
+ const trimmed = String(data || '').replace(/^data:[^;]+;base64,/i, '').replace(/\\s/g, '');
774
+ const bin = atob(trimmed);
775
+ const out = new Uint8Array(bin.length);
776
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
777
+ return out;
778
+ }
779
+
780
+ async function sha256Hex(buf: ArrayBuffer): Promise<string> {
781
+ const digest = await crypto.subtle.digest('SHA-256', buf);
782
+ return Array.from(new Uint8Array(digest))
783
+ .map((b) => b.toString(16).padStart(2, '0'))
784
+ .join('');
785
+ }
786
+
787
+ export type UploadFileChunkedOptions = {
788
+ mimeType?: string;
789
+ forceStorageType?: 'blob' | 'filesystem';
790
+ compress?: boolean;
791
+ onProgress?: (p: { sentBytes: number; totalBytes: number; sentChunks: number; totalChunks: number }) => void;
792
+ signal?: AbortSignal;
793
+ parallelism?: number;
794
+ };
795
+
796
+ /**
797
+ * Chunked upload for large files (tunnel-safe). Browser sends raw octet-stream chunks
798
+ * to /api/user/files/uploads/*; MCP assembles on disk and path-ingests.
799
+ */
800
+ export async function uploadFileChunked(
801
+ tableName: string,
802
+ rowId: number,
803
+ columnName: string,
804
+ file: Blob | File,
805
+ options: UploadFileChunkedOptions = {},
806
+ ): Promise<any> {
807
+ if (typeof window === 'undefined') {
808
+ throw new Error('uploadFileChunked() is browser-only. On the server, stream to MCP /user-data/uploads directly.');
809
+ }
810
+ const filename =
811
+ (file as File).name ||
812
+ \`upload-\${Date.now()}.bin\`;
813
+ const mimeType = options.mimeType || file.type || 'application/octet-stream';
814
+ const totalBytes = file.size;
815
+ const lastModified = Number((file as File).lastModified) || 0;
816
+ const resumeKey = \`egdesk_chunked_upload:\${tableName}|\${rowId}|\${columnName}|\${filename}|\${totalBytes}|\${lastModified}\`;
817
+ const readResume = (): string => {
818
+ try {
819
+ return localStorage.getItem(resumeKey) || '';
820
+ } catch {
821
+ return '';
822
+ }
823
+ };
824
+ const writeResume = (id: string) => {
825
+ try {
826
+ localStorage.setItem(resumeKey, id);
827
+ } catch {
828
+ // ignore quota / private mode
829
+ }
830
+ };
831
+ const clearResume = () => {
832
+ try {
833
+ localStorage.removeItem(resumeKey);
834
+ } catch {
835
+ // ignore
836
+ }
837
+ };
838
+
839
+ let uploadId = readResume();
840
+ let chunkSize = 0;
841
+ let totalChunks = 0;
842
+
843
+ if (uploadId) {
844
+ const statusRes = await apiFetch(\`/api/user/files/uploads/\${uploadId}\`, { signal: options.signal });
845
+ const statusJson = await statusRes.json().catch(() => ({}));
846
+ if (
847
+ statusRes.ok &&
848
+ statusJson.success !== false &&
849
+ (statusJson.state === 'receiving' || statusJson.state === 'finalizing') &&
850
+ Number(statusJson.size) === totalBytes
851
+ ) {
852
+ chunkSize = Number(statusJson.chunkSize);
853
+ totalChunks = Number(statusJson.totalChunks || Math.ceil(totalBytes / chunkSize));
854
+ } else if (statusRes.ok && statusJson.state === 'done' && statusJson.file) {
855
+ clearResume();
856
+ return {
857
+ success: true,
858
+ uploadId,
859
+ file: statusJson.file,
860
+ state: 'done',
861
+ sha256: statusJson.sha256,
862
+ resumed: true,
863
+ };
864
+ } else {
865
+ clearResume();
866
+ uploadId = '';
867
+ }
868
+ }
869
+
870
+ if (!uploadId) {
871
+ const initRes = await apiFetch('/api/user/files/uploads', {
872
+ method: 'POST',
873
+ headers: { 'Content-Type': 'application/json' },
874
+ body: JSON.stringify({
875
+ filename,
876
+ size: totalBytes,
877
+ mimeType,
878
+ tableName,
879
+ rowId,
880
+ columnName,
881
+ forceStorageType: options.forceStorageType,
882
+ compress: options.compress,
883
+ }),
884
+ signal: options.signal,
885
+ });
886
+ const initJson = await initRes.json();
887
+ if (!initRes.ok || initJson.success === false) {
888
+ throw new Error(initJson.error || initJson.message || \`Init upload failed (HTTP \${initRes.status})\`);
889
+ }
890
+ uploadId = String(initJson.uploadId);
891
+ chunkSize = Number(initJson.chunkSize);
892
+ totalChunks = Number(initJson.totalChunks || Math.ceil(totalBytes / chunkSize));
893
+ writeResume(uploadId);
894
+ }
895
+
896
+ const parallelism = Math.max(1, Math.min(options.parallelism ?? 3, 3));
897
+
898
+ const statusRes = await apiFetch(\`/api/user/files/uploads/\${uploadId}\`, { signal: options.signal });
899
+ const statusJson = await statusRes.json().catch(() => ({}));
900
+ const already = new Set<number>(Array.isArray(statusJson.received) ? statusJson.received : []);
901
+
902
+ let sentBytes = Math.min(totalBytes, already.size * chunkSize);
903
+ let sentChunks = already.size;
904
+ options.onProgress?.({ sentBytes, totalBytes, sentChunks, totalChunks });
905
+
906
+ const pending: number[] = [];
907
+ for (let i = 0; i < totalChunks; i++) {
908
+ if (!already.has(i)) pending.push(i);
909
+ }
910
+
911
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
912
+ const backoffs = [500, 1500, 4000];
913
+
914
+ async function putOne(index: number): Promise<void> {
915
+ const start = index * chunkSize;
916
+ const end = Math.min(start + chunkSize, totalBytes);
917
+ const slice = file.slice(start, end);
918
+ const buf = await slice.arrayBuffer();
919
+ const sha = await sha256Hex(buf);
920
+ let lastErr: Error | null = null;
921
+ for (let attempt = 0; attempt < 3; attempt++) {
922
+ if (options.signal?.aborted) throw new Error('Upload aborted');
923
+ try {
924
+ const res = await apiFetch(\`/api/user/files/uploads/\${uploadId}/chunks/\${index}\`, {
925
+ method: 'PUT',
926
+ headers: {
927
+ 'Content-Type': 'application/octet-stream',
928
+ 'x-chunk-sha256': sha,
929
+ },
930
+ body: buf,
931
+ signal: options.signal,
932
+ });
933
+ const json = await res.json().catch(() => ({}));
934
+ if (res.status === 401 && attempt < 2) {
935
+ await sleep(backoffs[attempt]);
936
+ continue;
937
+ }
938
+ if (!res.ok || json.success === false) {
939
+ throw new Error(json.error || json.message || \`Chunk \${index} failed (HTTP \${res.status})\`);
940
+ }
941
+ sentChunks += 1;
942
+ sentBytes = Math.min(totalBytes, sentBytes + (end - start));
943
+ options.onProgress?.({ sentBytes, totalBytes, sentChunks, totalChunks });
944
+ return;
945
+ } catch (e: any) {
946
+ lastErr = e instanceof Error ? e : new Error(String(e));
947
+ if (attempt < 2) await sleep(backoffs[attempt]);
948
+ }
949
+ }
950
+ throw lastErr || new Error(\`Chunk \${index} failed\`);
951
+ }
952
+
953
+ let cursor = 0;
954
+ async function worker() {
955
+ while (cursor < pending.length) {
956
+ const idx = pending[cursor++];
957
+ await putOne(idx);
958
+ }
959
+ }
960
+ await Promise.all(Array.from({ length: Math.min(parallelism, pending.length || 1) }, () => worker()));
961
+
962
+ const completeRes = await apiFetch(\`/api/user/files/uploads/\${uploadId}/complete\`, {
963
+ method: 'POST',
964
+ headers: { 'Content-Type': 'application/json' },
965
+ body: '{}',
966
+ signal: options.signal,
967
+ });
968
+ let completeJson = await completeRes.json();
969
+ if (!completeRes.ok && completeRes.status !== 202) {
970
+ throw new Error(completeJson.error || completeJson.message || \`Complete failed (HTTP \${completeRes.status})\`);
971
+ }
972
+
973
+ // Poll when finalizing in background
974
+ if (completeJson.state === 'finalizing' || completeRes.status === 202) {
975
+ for (let i = 0; i < 600; i++) {
976
+ if (options.signal?.aborted) throw new Error('Upload aborted');
977
+ await sleep(500);
978
+ const st = await apiFetch(\`/api/user/files/uploads/\${uploadId}\`, { signal: options.signal });
979
+ const sj = await st.json();
980
+ if (sj.state === 'done') {
981
+ completeJson = sj;
982
+ break;
983
+ }
984
+ if (sj.state === 'failed') {
985
+ throw new Error(sj.error || 'Upload finalization failed');
986
+ }
987
+ }
988
+ if (completeJson.state !== 'done') {
989
+ throw new Error('Timed out waiting for upload finalization');
990
+ }
991
+ }
992
+
993
+ clearResume();
994
+ return {
995
+ success: true,
996
+ uploadId,
997
+ file: completeJson.file,
998
+ state: completeJson.state || 'done',
999
+ sha256: completeJson.sha256,
1000
+ };
1001
+ }
1002
+
1003
+ // ==========================================
1004
+ // VOICE TRANSCRIPT CHUNKED AUDIO UPLOAD
1005
+ // ==========================================
1006
+
1007
+ /** EGDesk Voice Transcript MCP allowlist max (must match desktop audio-path.ts). */
1008
+ const VOICE_TRANSCRIPT_MAX_AUDIO_BYTES = 80 * 1024 * 1024;
1009
+
1010
+ const VOICE_TRANSCRIPT_AUDIO_EXTENSIONS = [
1011
+ '.wav',
1012
+ '.mp3',
1013
+ '.m4a',
1014
+ '.aac',
1015
+ '.ogg',
1016
+ '.webm',
1017
+ '.flac',
1018
+ ];
1019
+
1020
+ export type UploadVoiceTranscriptAudioOptions = {
1021
+ mimeType?: string;
1022
+ onProgress?: (p: { sentBytes: number; totalBytes: number; sentChunks: number; totalChunks: number }) => void;
1023
+ signal?: AbortSignal;
1024
+ parallelism?: number;
1025
+ };
1026
+
1027
+ export type VoiceTranscriptAudioUploadResult = {
1028
+ success: true;
1029
+ uploadId: string;
1030
+ filePath: string;
1031
+ state: string;
1032
+ sha256?: string;
1033
+ filename: string;
1034
+ resumed?: boolean;
1035
+ };
1036
+
1037
+ function assertVoiceTranscriptFilename(filename: string): void {
1038
+ const lower = filename.toLowerCase();
1039
+ const ok = VOICE_TRANSCRIPT_AUDIO_EXTENSIONS.some((ext) => lower.endsWith(ext));
1040
+ if (!ok) {
1041
+ throw new Error(
1042
+ \`Unsupported audio extension for "\${filename}". Allowed: \${VOICE_TRANSCRIPT_AUDIO_EXTENSIONS.join(', ')}\`,
1043
+ );
1044
+ }
1045
+ }
1046
+
1047
+ /**
1048
+ * Chunked upload for call/meeting audio (tunnel-safe). Proxies to /api/voice-transcript/uploads/*
1049
+ * and returns an absolute file_path on the EGDesk machine for voice_transcript_transcribe.
1050
+ */
1051
+ export async function uploadVoiceTranscriptAudioChunked(
1052
+ file: Blob | File,
1053
+ options: UploadVoiceTranscriptAudioOptions = {},
1054
+ ): Promise<VoiceTranscriptAudioUploadResult> {
1055
+ if (typeof window === 'undefined') {
1056
+ throw new Error(
1057
+ 'uploadVoiceTranscriptAudioChunked() is browser-only. On the server, POST to MCP /voice-transcript/uploads directly.',
1058
+ );
1059
+ }
1060
+ const filename = (file as File).name || \`recording-\${Date.now()}.m4a\`;
1061
+ assertVoiceTranscriptFilename(filename);
1062
+ const mimeType = options.mimeType || file.type || 'application/octet-stream';
1063
+ const totalBytes = file.size;
1064
+ if (totalBytes <= 0) throw new Error('Audio file is empty.');
1065
+ if (totalBytes > VOICE_TRANSCRIPT_MAX_AUDIO_BYTES) {
1066
+ throw new Error(
1067
+ \`Audio is too large (\${totalBytes} bytes). Max \${VOICE_TRANSCRIPT_MAX_AUDIO_BYTES} bytes (80 MB).\`,
1068
+ );
1069
+ }
1070
+
1071
+ const lastModified = Number((file as File).lastModified) || 0;
1072
+ const resumeKey = \`egdesk_voice_chunked_upload:\${filename}|\${totalBytes}|\${lastModified}\`;
1073
+ const readResume = (): string => {
1074
+ try {
1075
+ return localStorage.getItem(resumeKey) || '';
1076
+ } catch {
1077
+ return '';
1078
+ }
1079
+ };
1080
+ const writeResume = (id: string) => {
1081
+ try {
1082
+ localStorage.setItem(resumeKey, id);
1083
+ } catch {
1084
+ // ignore
1085
+ }
1086
+ };
1087
+ const clearResume = () => {
1088
+ try {
1089
+ localStorage.removeItem(resumeKey);
1090
+ } catch {
1091
+ // ignore
1092
+ }
1093
+ };
1094
+
1095
+ const apiBase = '/api/voice-transcript/uploads';
1096
+
1097
+ let uploadId = readResume();
1098
+ let chunkSize = 0;
1099
+ let totalChunks = 0;
1100
+
1101
+ if (uploadId) {
1102
+ const statusRes = await apiFetch(\`\${apiBase}/\${uploadId}\`, { signal: options.signal });
1103
+ const statusJson = await statusRes.json().catch(() => ({}));
1104
+ if (
1105
+ statusRes.ok &&
1106
+ statusJson.success !== false &&
1107
+ (statusJson.state === 'receiving' || statusJson.state === 'finalizing') &&
1108
+ Number(statusJson.size) === totalBytes
1109
+ ) {
1110
+ chunkSize = Number(statusJson.chunkSize);
1111
+ totalChunks = Number(statusJson.totalChunks || Math.ceil(totalBytes / chunkSize));
1112
+ } else if (statusRes.ok && statusJson.state === 'done' && (statusJson.filePath || statusJson.file?.filePath)) {
1113
+ clearResume();
1114
+ const filePath = String(statusJson.filePath || statusJson.file?.filePath);
1115
+ return {
1116
+ success: true,
1117
+ uploadId,
1118
+ filePath,
1119
+ state: 'done',
1120
+ sha256: statusJson.sha256,
1121
+ filename,
1122
+ resumed: true,
1123
+ };
1124
+ } else {
1125
+ clearResume();
1126
+ uploadId = '';
1127
+ }
1128
+ }
1129
+
1130
+ if (!uploadId) {
1131
+ const initRes = await apiFetch(apiBase, {
1132
+ method: 'POST',
1133
+ headers: { 'Content-Type': 'application/json' },
1134
+ body: JSON.stringify({ filename, size: totalBytes, mimeType }),
1135
+ signal: options.signal,
1136
+ });
1137
+ const initJson = await initRes.json();
1138
+ if (!initRes.ok || initJson.success === false) {
1139
+ throw new Error(initJson.error || initJson.message || \`Init upload failed (HTTP \${initRes.status})\`);
1140
+ }
1141
+ uploadId = String(initJson.uploadId);
1142
+ chunkSize = Number(initJson.chunkSize);
1143
+ totalChunks = Number(initJson.totalChunks || Math.ceil(totalBytes / chunkSize));
1144
+ writeResume(uploadId);
1145
+ }
1146
+
1147
+ const parallelism = Math.max(1, Math.min(options.parallelism ?? 3, 3));
1148
+ const statusRes = await apiFetch(\`\${apiBase}/\${uploadId}\`, { signal: options.signal });
1149
+ const statusJson = await statusRes.json().catch(() => ({}));
1150
+ const already = new Set<number>(Array.isArray(statusJson.received) ? statusJson.received : []);
1151
+
1152
+ let sentBytes = Math.min(totalBytes, already.size * chunkSize);
1153
+ let sentChunks = already.size;
1154
+ options.onProgress?.({ sentBytes, totalBytes, sentChunks, totalChunks });
1155
+
1156
+ const pending: number[] = [];
1157
+ for (let i = 0; i < totalChunks; i++) {
1158
+ if (!already.has(i)) pending.push(i);
1159
+ }
1160
+
1161
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
1162
+ const backoffs = [500, 1500, 4000];
1163
+
1164
+ async function putOne(index: number): Promise<void> {
1165
+ const start = index * chunkSize;
1166
+ const end = Math.min(start + chunkSize, totalBytes);
1167
+ const slice = file.slice(start, end);
1168
+ const buf = await slice.arrayBuffer();
1169
+ const sha = await sha256Hex(buf);
1170
+ let lastErr: Error | null = null;
1171
+ for (let attempt = 0; attempt < 3; attempt++) {
1172
+ if (options.signal?.aborted) throw new Error('Upload aborted');
1173
+ try {
1174
+ const res = await apiFetch(\`\${apiBase}/\${uploadId}/chunks/\${index}\`, {
1175
+ method: 'PUT',
1176
+ headers: {
1177
+ 'Content-Type': 'application/octet-stream',
1178
+ 'x-chunk-sha256': sha,
1179
+ },
1180
+ body: buf,
1181
+ signal: options.signal,
1182
+ });
1183
+ const json = await res.json().catch(() => ({}));
1184
+ if (res.status === 401 && attempt < 2) {
1185
+ await sleep(backoffs[attempt]);
1186
+ continue;
1187
+ }
1188
+ if (!res.ok || json.success === false) {
1189
+ throw new Error(json.error || json.message || \`Chunk \${index} failed (HTTP \${res.status})\`);
1190
+ }
1191
+ sentChunks += 1;
1192
+ sentBytes = Math.min(totalBytes, sentBytes + (end - start));
1193
+ options.onProgress?.({ sentBytes, totalBytes, sentChunks, totalChunks });
1194
+ return;
1195
+ } catch (e: any) {
1196
+ lastErr = e instanceof Error ? e : new Error(String(e));
1197
+ if (attempt < 2) await sleep(backoffs[attempt]);
1198
+ }
1199
+ }
1200
+ throw lastErr || new Error(\`Chunk \${index} failed\`);
1201
+ }
1202
+
1203
+ let cursor = 0;
1204
+ async function worker() {
1205
+ while (cursor < pending.length) {
1206
+ const idx = pending[cursor++];
1207
+ await putOne(idx);
1208
+ }
1209
+ }
1210
+ await Promise.all(Array.from({ length: Math.min(parallelism, pending.length || 1) }, () => worker()));
1211
+
1212
+ const completeRes = await apiFetch(\`\${apiBase}/\${uploadId}/complete\`, {
1213
+ method: 'POST',
1214
+ headers: { 'Content-Type': 'application/json' },
1215
+ body: '{}',
1216
+ signal: options.signal,
1217
+ });
1218
+ let completeJson = await completeRes.json();
1219
+ if (!completeRes.ok && completeRes.status !== 202) {
1220
+ throw new Error(completeJson.error || completeJson.message || \`Complete failed (HTTP \${completeRes.status})\`);
1221
+ }
1222
+
1223
+ if (completeJson.state === 'finalizing' || completeRes.status === 202) {
1224
+ for (let i = 0; i < 600; i++) {
1225
+ if (options.signal?.aborted) throw new Error('Upload aborted');
1226
+ await sleep(500);
1227
+ const st = await apiFetch(\`\${apiBase}/\${uploadId}\`, { signal: options.signal });
1228
+ const sj = await st.json();
1229
+ if (sj.state === 'done') {
1230
+ completeJson = sj;
1231
+ break;
1232
+ }
1233
+ if (sj.state === 'failed') {
1234
+ throw new Error(sj.error || 'Upload finalization failed');
1235
+ }
1236
+ }
1237
+ if (completeJson.state !== 'done') {
1238
+ throw new Error('Timed out waiting for voice upload finalization');
1239
+ }
1240
+ }
1241
+
1242
+ const filePath = String(
1243
+ completeJson.filePath || completeJson.file?.filePath || '',
1244
+ );
1245
+ if (!filePath) {
1246
+ throw new Error('Upload completed but filePath was missing from the response.');
1247
+ }
1248
+
1249
+ clearResume();
1250
+ return {
1251
+ success: true,
1252
+ uploadId,
1253
+ filePath,
1254
+ state: completeJson.state || 'done',
1255
+ sha256: completeJson.sha256,
1256
+ filename,
1257
+ };
1258
+ }
1259
+
1260
+ /**
1261
+ * Upload audio for Voice Transcript (browser). Uses chunked upload for tunnel safety.
1262
+ * Pass a File from a file picker (accept audio/*) or a Blob with a name.
1263
+ */
1264
+ export async function uploadVoiceTranscriptAudio(
1265
+ file: Blob | File,
1266
+ options: UploadVoiceTranscriptAudioOptions = {},
1267
+ ): Promise<VoiceTranscriptAudioUploadResult> {
1268
+ return uploadVoiceTranscriptAudioChunked(file, options);
1269
+ }
1270
+
1271
+ /**
1272
+ * Upload audio from a Base64 or data-URL string (browser). Files larger than 4 MiB decoded
1273
+ * use the chunked path automatically.
1274
+ */
1275
+ export async function uploadVoiceTranscriptAudioFromBase64(
1276
+ filename: string,
1277
+ data: string,
1278
+ options: UploadVoiceTranscriptAudioOptions = {},
1279
+ ): Promise<VoiceTranscriptAudioUploadResult> {
1280
+ assertVoiceTranscriptFilename(filename);
1281
+ const bytes = base64ToUint8Array(data);
1282
+ const blob = new Blob([bytes], { type: options.mimeType || 'application/octet-stream' });
1283
+ const file = new File([blob], filename, { type: options.mimeType || blob.type });
1284
+ return uploadVoiceTranscriptAudioChunked(file, options);
1285
+ }
1286
+
751
1287
  /**
752
1288
  * Upload a file attachment for a table row.
753
1289
  * Files are NOT table columns — they attach via a virtual columnName (e.g. "file").
754
1290
  * Workflow: insertRows(...) → uploadFile(tableName, rowId, 'file', filename, base64).
755
- * Data must be base64 (raw or data URL). Files <10KB store as uncompressed blobs,
756
- * 10-100KB as gzip blobs, >100KB on disk via BucketManager.
1291
+ * Data must be base64 (raw or data URL). Files >4 MiB automatically use chunked upload
1292
+ * in the browser (tunnel-safe). Small files still use a single Base64 MCP call.
757
1293
  */
758
1294
  export async function uploadFile(
759
1295
  tableName: string,
@@ -767,6 +1303,13 @@ export async function uploadFile(
767
1303
  compress?: boolean;
768
1304
  } = {}
769
1305
  ) {
1306
+ const decodedBytes = estimateBase64DecodedBytes(data);
1307
+ if (typeof window !== 'undefined' && decodedBytes > UPLOAD_CHUNKED_THRESHOLD_BYTES) {
1308
+ const bytes = base64ToUint8Array(data);
1309
+ const blob = new Blob([bytes], { type: options.mimeType || 'application/octet-stream' });
1310
+ const file = new File([blob], filename, { type: options.mimeType || blob.type });
1311
+ return uploadFileChunked(tableName, rowId, columnName, file, options);
1312
+ }
770
1313
  return callUserDataTool('user_data_upload_file', {
771
1314
  tableName,
772
1315
  rowId,
@@ -1113,9 +1656,7 @@ export async function callKakaoTool(
1113
1656
 
1114
1657
  let response: Response;
1115
1658
  if (isServer) {
1116
- const apiUrl =
1117
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1118
- EGDESK_CONFIG.apiUrl;
1659
+ const apiUrl = resolveServerEgdeskApiUrl();
1119
1660
  response = await fetch(\`\${apiUrl}/kakao/tools/call\`, {
1120
1661
  method: 'POST',
1121
1662
  headers: buildServerEgdeskHeaders(),
@@ -1301,9 +1842,7 @@ export async function callFinanceHubTool(
1301
1842
 
1302
1843
  let response: Response;
1303
1844
  if (isServer) {
1304
- const apiUrl =
1305
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1306
- EGDESK_CONFIG.apiUrl;
1845
+ const apiUrl = resolveServerEgdeskApiUrl();
1307
1846
  response = await fetch(\`\${apiUrl}/financehub/tools/call\`, {
1308
1847
  method: 'POST',
1309
1848
  headers: buildServerEgdeskHeaders(),
@@ -1639,9 +2178,7 @@ export async function callBusinessIdentityTool(
1639
2178
 
1640
2179
  let response: Response;
1641
2180
  if (isServer) {
1642
- const apiUrl =
1643
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1644
- EGDESK_CONFIG.apiUrl;
2181
+ const apiUrl = resolveServerEgdeskApiUrl();
1645
2182
  response = await fetch(\`\${apiUrl}/business-identity/tools/call\`, {
1646
2183
  method: 'POST',
1647
2184
  headers: buildServerEgdeskHeaders(),
@@ -1725,9 +2262,7 @@ export async function callCompanyResearchTool(
1725
2262
 
1726
2263
  let response: Response;
1727
2264
  if (isServer) {
1728
- const apiUrl =
1729
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1730
- EGDESK_CONFIG.apiUrl;
2265
+ const apiUrl = resolveServerEgdeskApiUrl();
1731
2266
  response = await fetch(\`\${apiUrl}/company-research/tools/call\`, {
1732
2267
  method: 'POST',
1733
2268
  headers: buildServerEgdeskHeaders(),
@@ -1873,9 +2408,7 @@ export async function callBrowserRecordingTool(
1873
2408
 
1874
2409
  let response: Response;
1875
2410
  if (isServer) {
1876
- const apiUrl =
1877
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
1878
- EGDESK_CONFIG.apiUrl;
2411
+ const apiUrl = resolveServerEgdeskApiUrl();
1879
2412
  response = await fetch(\`\${apiUrl}/browser-recording/tools/call\`, {
1880
2413
  method: 'POST',
1881
2414
  headers: buildServerEgdeskHeaders(),
@@ -2284,9 +2817,7 @@ export async function callAICenterTool(
2284
2817
 
2285
2818
  let response: Response;
2286
2819
  if (isServer) {
2287
- const apiUrl =
2288
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
2289
- EGDESK_CONFIG.apiUrl;
2820
+ const apiUrl = resolveServerEgdeskApiUrl();
2290
2821
  response = await fetch(\`\${apiUrl}/ai-center/tools/call\`, {
2291
2822
  method: 'POST',
2292
2823
  headers: buildServerEgdeskHeaders(),
@@ -2560,9 +3091,7 @@ export async function callKoreanLawTool(
2560
3091
 
2561
3092
  let response: Response;
2562
3093
  if (isServer) {
2563
- const apiUrl =
2564
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
2565
- EGDESK_CONFIG.apiUrl;
3094
+ const apiUrl = resolveServerEgdeskApiUrl();
2566
3095
  response = await fetch(\`\${apiUrl}/korean-law/tools/call\`, {
2567
3096
  method: 'POST',
2568
3097
  headers: buildServerEgdeskHeaders(),
@@ -2786,9 +3315,7 @@ export async function callSeoTool(
2786
3315
 
2787
3316
  let response: Response;
2788
3317
  if (isServer) {
2789
- const apiUrl =
2790
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
2791
- EGDESK_CONFIG.apiUrl;
3318
+ const apiUrl = resolveServerEgdeskApiUrl();
2792
3319
  response = await fetch(\`\${apiUrl}/seo/tools/call\`, {
2793
3320
  method: 'POST',
2794
3321
  headers: buildServerEgdeskHeaders(),
@@ -2851,9 +3378,7 @@ export async function callHostingCodingTool(
2851
3378
 
2852
3379
  let response: Response;
2853
3380
  if (isServer) {
2854
- const apiUrl =
2855
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
2856
- EGDESK_CONFIG.apiUrl;
3381
+ const apiUrl = resolveServerEgdeskApiUrl();
2857
3382
  response = await fetch(\`\${apiUrl}/hosting-coding/tools/call\`, {
2858
3383
  method: 'POST',
2859
3384
  headers: buildServerEgdeskHeaders(),
@@ -2992,9 +3517,7 @@ export async function callLocalAgentTool(
2992
3517
 
2993
3518
  let response: Response;
2994
3519
  if (isServer) {
2995
- const apiUrl =
2996
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
2997
- EGDESK_CONFIG.apiUrl;
3520
+ const apiUrl = resolveServerEgdeskApiUrl();
2998
3521
  response = await fetch(\`\${apiUrl}/local-agent/tools/call\`, {
2999
3522
  method: 'POST',
3000
3523
  headers: buildServerEgdeskHeaders(),
@@ -3069,9 +3592,7 @@ export async function callAiCallerTool(
3069
3592
 
3070
3593
  let response: Response;
3071
3594
  if (isServer) {
3072
- const apiUrl =
3073
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
3074
- EGDESK_CONFIG.apiUrl;
3595
+ const apiUrl = resolveServerEgdeskApiUrl();
3075
3596
  response = await fetch(\`\${apiUrl}/ai-caller/tools/call\`, {
3076
3597
  method: 'POST',
3077
3598
  headers: buildServerEgdeskHeaders(),
@@ -3390,9 +3911,7 @@ export async function callPageIndexTool(
3390
3911
 
3391
3912
  let response: Response;
3392
3913
  if (isServer) {
3393
- const apiUrl =
3394
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
3395
- EGDESK_CONFIG.apiUrl;
3914
+ const apiUrl = resolveServerEgdeskApiUrl();
3396
3915
  response = await fetch(\`\${apiUrl}/pageindex/tools/call\`, {
3397
3916
  method: 'POST',
3398
3917
  headers: buildServerEgdeskHeaders(),
@@ -3618,6 +4137,43 @@ export async function renameDriveFile(fileId: string, name: string, preferOAuth?
3618
4137
  return callDriveTool('drive_rename', { fileId, name, preferOAuth });
3619
4138
  }
3620
4139
 
4140
+ /** Invite a Google user to a Drive file or folder. Default preferOAuth: true. */
4141
+ export async function shareDriveFile(options: {
4142
+ fileId: string;
4143
+ shareType?: 'user' | 'anyone' | 'domain';
4144
+ email?: string;
4145
+ domain?: string;
4146
+ role?: 'reader' | 'writer' | 'commenter';
4147
+ allowFileDiscovery?: boolean;
4148
+ sendNotificationEmail?: boolean;
4149
+ preferOAuth?: boolean;
4150
+ }) {
4151
+ const preferOAuth = options.preferOAuth ?? true;
4152
+ return callDriveTool('drive_share_file', { ...options, preferOAuth }, { preferOAuth });
4153
+ }
4154
+
4155
+ /** List non-owner permissions on a Drive file or folder. Default preferOAuth: true. */
4156
+ export async function listDriveFilePermissions(
4157
+ fileId: string,
4158
+ options: WorkspaceVisitorCallOptions = {},
4159
+ ) {
4160
+ const preferOAuth = options.preferOAuth ?? true;
4161
+ return callDriveTool('drive_list_file_permissions', { fileId, preferOAuth }, { ...options, preferOAuth });
4162
+ }
4163
+
4164
+ /** Remove a collaborator by permissionId or email. Default preferOAuth: true. */
4165
+ export async function revokeDriveFileAccess(options: {
4166
+ fileId: string;
4167
+ permissionId?: string;
4168
+ email?: string;
4169
+ shareType?: 'anyone' | 'domain';
4170
+ domain?: string;
4171
+ preferOAuth?: boolean;
4172
+ }) {
4173
+ const preferOAuth = options.preferOAuth ?? true;
4174
+ return callDriveTool('drive_revoke_file_access', { ...options, preferOAuth }, { preferOAuth });
4175
+ }
4176
+
3621
4177
  /** Move a Drive file or folder to trash. Pass preferOAuth: true to act as the signed-in Google user. */
3622
4178
  export async function trashDriveFile(fileId: string, preferOAuth?: boolean) {
3623
4179
  return callDriveTool('drive_trash', { fileId, preferOAuth });
@@ -4173,9 +4729,7 @@ export async function callKnowledgeWikiTool(
4173
4729
 
4174
4730
  let response: Response;
4175
4731
  if (isServer) {
4176
- const apiUrl =
4177
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
4178
- EGDESK_CONFIG.apiUrl;
4732
+ const apiUrl = resolveServerEgdeskApiUrl();
4179
4733
  response = await fetch(\`\${apiUrl}/knowledge-wiki/tools/call\`, {
4180
4734
  method: 'POST',
4181
4735
  headers: buildServerEgdeskHeaders(),
@@ -4285,9 +4839,7 @@ export async function callEgdeskConfigTool(
4285
4839
 
4286
4840
  let response: Response;
4287
4841
  if (isServer) {
4288
- const apiUrl =
4289
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
4290
- EGDESK_CONFIG.apiUrl;
4842
+ const apiUrl = resolveServerEgdeskApiUrl();
4291
4843
  response = await fetch(\`\${apiUrl}/egdesk-config/tools/call\`, {
4292
4844
  method: 'POST',
4293
4845
  headers: buildServerEgdeskHeaders(),
@@ -4403,9 +4955,7 @@ export async function callPhoneTool(
4403
4955
 
4404
4956
  let response: Response;
4405
4957
  if (isServer) {
4406
- const apiUrl =
4407
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
4408
- EGDESK_CONFIG.apiUrl;
4958
+ const apiUrl = resolveServerEgdeskApiUrl();
4409
4959
  response = await fetch(\`\${apiUrl}/phone/tools/call\`, {
4410
4960
  method: 'POST',
4411
4961
  headers: buildServerEgdeskHeaders(),
@@ -4666,9 +5216,7 @@ export async function callInstagramTool(
4666
5216
 
4667
5217
  let response: Response;
4668
5218
  if (isServer) {
4669
- const apiUrl =
4670
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
4671
- EGDESK_CONFIG.apiUrl;
5219
+ const apiUrl = resolveServerEgdeskApiUrl();
4672
5220
  response = await fetch(\`\${apiUrl}/instagram/tools/call\`, {
4673
5221
  method: 'POST',
4674
5222
  headers: buildServerEgdeskHeaders(),
@@ -5001,9 +5549,7 @@ export async function callBlogTool(
5001
5549
 
5002
5550
  let response: Response;
5003
5551
  if (isServer) {
5004
- const apiUrl =
5005
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
5006
- EGDESK_CONFIG.apiUrl;
5552
+ const apiUrl = resolveServerEgdeskApiUrl();
5007
5553
  response = await fetch(\`\${apiUrl}/blog/tools/call\`, {
5008
5554
  method: 'POST',
5009
5555
  headers: buildServerEgdeskHeaders(),
@@ -5285,9 +5831,7 @@ export async function callYouTubeTool(
5285
5831
 
5286
5832
  let response: Response;
5287
5833
  if (isServer) {
5288
- const apiUrl =
5289
- (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
5290
- EGDESK_CONFIG.apiUrl;
5834
+ const apiUrl = resolveServerEgdeskApiUrl();
5291
5835
  response = await fetch(\`\${apiUrl}/youtube/tools/call\`, {
5292
5836
  method: 'POST',
5293
5837
  headers: buildServerEgdeskHeaders(),