@cydm/pie 4.5.1 → 4.6.0

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.
@@ -0,0 +1,3178 @@
1
+ import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
+ import {
3
+ createReadFileUnderstandingHandler,
4
+ modalityForReadFileUnderstandingKind
5
+ } from "./chunk-BLDI2GRF.js";
6
+ import {
7
+ getLogger
8
+ } from "./chunk-3W3SXVPB.js";
9
+ import {
10
+ readImageFormat
11
+ } from "./chunk-F7EBZTZO.js";
12
+
13
+ // src/capabilities/read-file-understanding.ts
14
+ import * as path9 from "node:path";
15
+ import * as fs8 from "node:fs/promises";
16
+
17
+ // src/core/provider-capabilities.ts
18
+ var PLATFORM_DISPLAY_NAMES = {
19
+ kimi: "Kimi",
20
+ gemini: "Gemini",
21
+ "openai-compatible-files": "OpenAI-compatible Files"
22
+ };
23
+ function getFileManagerAdapterKind(platform) {
24
+ const normalized = normalizeFileManagerPlatform(platform);
25
+ if (normalized === "kimi") return "kimi";
26
+ if (normalized === "gemini") return "gemini";
27
+ if (normalized === "openai-compatible-files") return "openai-compatible-files";
28
+ return "none";
29
+ }
30
+ function normalizeFileManagerPlatform(platform) {
31
+ if (!platform) return "unknown";
32
+ return platform;
33
+ }
34
+ function getProviderDisplayName(platform) {
35
+ if (!platform) return "Current platform";
36
+ const normalized = normalizeFileManagerPlatform(platform);
37
+ return PLATFORM_DISPLAY_NAMES[normalized] || normalized;
38
+ }
39
+
40
+ // src/files/adapters/kimi-adapter.ts
41
+ import * as fs from "node:fs";
42
+ import * as path from "node:path";
43
+
44
+ // src/files/errors.ts
45
+ var FileErrorMessages = {
46
+ ["UPLOAD_FAILED" /* UPLOAD_FAILED */]: {
47
+ en: "Failed to upload file. Please check your network connection and try again.",
48
+ zh: "\u6587\u4EF6\u4E0A\u4F20\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u540E\u91CD\u8BD5\u3002"
49
+ },
50
+ ["PROCESSING_TIMEOUT" /* PROCESSING_TIMEOUT */]: {
51
+ en: "File processing timed out. The file may be too large or the server is busy.",
52
+ zh: "\u6587\u4EF6\u5904\u7406\u8D85\u65F6\uFF0C\u6587\u4EF6\u53EF\u80FD\u8FC7\u5927\u6216\u670D\u52A1\u5668\u7E41\u5FD9\u3002"
53
+ },
54
+ ["FILE_EXPIRED" /* FILE_EXPIRED */]: {
55
+ en: "File has expired and been removed from the server.",
56
+ zh: "\u6587\u4EF6\u5DF2\u8FC7\u671F\uFF0C\u5DF2\u4ECE\u670D\u52A1\u5668\u79FB\u9664\u3002"
57
+ },
58
+ ["LOCAL_FILE_MISSING" /* LOCAL_FILE_MISSING */]: {
59
+ en: "Local file not found. It may have been deleted or moved.",
60
+ zh: "\u672C\u5730\u6587\u4EF6\u672A\u627E\u5230\uFF0C\u53EF\u80FD\u5DF2\u88AB\u5220\u9664\u6216\u79FB\u52A8\u3002"
61
+ },
62
+ ["PLATFORM_NOT_SUPPORTED" /* PLATFORM_NOT_SUPPORTED */]: {
63
+ en: "Platform not supported or no adapter available.",
64
+ zh: "\u4E0D\u652F\u6301\u7684\u5E73\u53F0\u6216\u7F3A\u5C11\u9002\u914D\u5668\u3002"
65
+ },
66
+ ["DISK_FULL" /* DISK_FULL */]: {
67
+ en: "Disk space is full. Please free up some space and try again.",
68
+ zh: "\u78C1\u76D8\u7A7A\u95F4\u5DF2\u6EE1\uFF0C\u8BF7\u91CA\u653E\u7A7A\u95F4\u540E\u91CD\u8BD5\u3002"
69
+ },
70
+ ["INVALID_FILE_TYPE" /* INVALID_FILE_TYPE */]: {
71
+ en: "Invalid or unsupported file type.",
72
+ zh: "\u65E0\u6548\u6216\u4E0D\u652F\u6301\u7684\u6587\u4EF6\u7C7B\u578B\u3002"
73
+ },
74
+ ["FILE_TOO_LARGE" /* FILE_TOO_LARGE */]: {
75
+ en: "File size exceeds the maximum limit. Please compress the file or use a smaller file.",
76
+ zh: "\u6587\u4EF6\u5927\u5C0F\u8D85\u8FC7\u9650\u5236\uFF0C\u8BF7\u538B\u7F29\u6587\u4EF6\u6216\u4F7F\u7528\u8F83\u5C0F\u7684\u6587\u4EF6\u3002"
77
+ },
78
+ ["FFMPEG_NOT_FOUND" /* FFMPEG_NOT_FOUND */]: {
79
+ en: "FFmpeg not found. Please install FFmpeg to process video files.",
80
+ zh: "\u672A\u627E\u5230 FFmpeg\uFF0C\u8BF7\u5B89\u88C5 FFmpeg \u4EE5\u5904\u7406\u89C6\u9891\u6587\u4EF6\u3002"
81
+ },
82
+ ["FFMPEG_ERROR" /* FFMPEG_ERROR */]: {
83
+ en: "FFmpeg processing error. The file may be corrupted or in an unsupported format.",
84
+ zh: "FFmpeg \u5904\u7406\u9519\u8BEF\uFF0C\u6587\u4EF6\u53EF\u80FD\u5DF2\u635F\u574F\u6216\u683C\u5F0F\u4E0D\u652F\u6301\u3002"
85
+ },
86
+ ["INVALID_PATH" /* INVALID_PATH */]: {
87
+ en: "Invalid file path. Path traversal is not allowed.",
88
+ zh: "\u65E0\u6548\u7684\u6587\u4EF6\u8DEF\u5F84\uFF0C\u4E0D\u5141\u8BB8\u8DEF\u5F84\u904D\u5386\u3002"
89
+ },
90
+ ["FILE_NOT_FOUND" /* FILE_NOT_FOUND */]: {
91
+ en: "File not found at the specified path.",
92
+ zh: "\u5728\u6307\u5B9A\u8DEF\u5F84\u672A\u627E\u5230\u6587\u4EF6\u3002"
93
+ },
94
+ ["NETWORK_ERROR" /* NETWORK_ERROR */]: {
95
+ en: "Network error. Please check your connection and try again.",
96
+ zh: "\u7F51\u7EDC\u9519\u8BEF\uFF0C\u8BF7\u68C0\u67E5\u8FDE\u63A5\u540E\u91CD\u8BD5\u3002"
97
+ },
98
+ ["API_ERROR" /* API_ERROR */]: {
99
+ en: "API error. The service may be temporarily unavailable.",
100
+ zh: "API \u9519\u8BEF\uFF0C\u670D\u52A1\u53EF\u80FD\u6682\u65F6\u4E0D\u53EF\u7528\u3002"
101
+ },
102
+ ["RATE_LIMITED" /* RATE_LIMITED */]: {
103
+ en: "Rate limit exceeded. Please wait a moment and try again.",
104
+ zh: "\u8BF7\u6C42\u9891\u7387\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002"
105
+ },
106
+ ["UNKNOWN_ERROR" /* UNKNOWN_ERROR */]: {
107
+ en: "An unknown error occurred. Please try again later.",
108
+ zh: "\u53D1\u751F\u672A\u77E5\u9519\u8BEF\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002"
109
+ }
110
+ };
111
+ var FileManagerError = class extends Error {
112
+ code;
113
+ details;
114
+ locale;
115
+ constructor(code, details, locale = "en") {
116
+ const messages = FileErrorMessages[code];
117
+ super(messages[locale]);
118
+ this.name = "FileManagerError";
119
+ this.code = code;
120
+ this.details = details;
121
+ this.locale = locale;
122
+ }
123
+ /**
124
+ * Get error message in specified locale
125
+ */
126
+ getMessage(locale) {
127
+ const targetLocale = locale || this.locale;
128
+ return FileErrorMessages[this.code][targetLocale];
129
+ }
130
+ /**
131
+ * Convert to JSON for serialization
132
+ */
133
+ toJSON() {
134
+ return {
135
+ name: this.name,
136
+ code: this.code,
137
+ message: this.message,
138
+ details: this.details,
139
+ locale: this.locale
140
+ };
141
+ }
142
+ };
143
+
144
+ // src/files/adapters/kimi-adapter.ts
145
+ var KimiFileAdapter = class {
146
+ platform = "kimi";
147
+ capabilities = {
148
+ supportsNativeVideo: true,
149
+ supportsFileReference: true,
150
+ maxFileSize: 100 * 1024 * 1024,
151
+ // 100MB
152
+ supportedMimeTypes: [
153
+ "image/jpeg",
154
+ "image/png",
155
+ "image/webp",
156
+ "image/gif",
157
+ "video/mp4",
158
+ "video/quicktime",
159
+ "video/x-msvideo",
160
+ "video/webm",
161
+ "application/pdf",
162
+ "text/plain",
163
+ "text/markdown"
164
+ ]
165
+ };
166
+ apiKey;
167
+ baseUrl;
168
+ constructor(apiKey, baseUrl) {
169
+ if (!baseUrl) {
170
+ throw new Error("KimiFileAdapter requires an explicit baseUrl from models.json.");
171
+ }
172
+ this.apiKey = apiKey;
173
+ this.baseUrl = baseUrl;
174
+ }
175
+ // ============================================================================
176
+ // Upload
177
+ // ============================================================================
178
+ async upload(filePath, options = {}) {
179
+ const fileName = options.sourceName || path.basename(filePath);
180
+ const mimeType = options.mimeType || this.guessMimeType(fileName);
181
+ const purpose = this.detectPurpose(filePath, options.purpose, mimeType);
182
+ const stats = fs.statSync(filePath);
183
+ if (stats.size > this.capabilities.maxFileSize) {
184
+ throw new FileManagerError(
185
+ "FILE_TOO_LARGE" /* FILE_TOO_LARGE */,
186
+ `File size ${(stats.size / 1024 / 1024).toFixed(1)}MB exceeds Kimi limit of 100MB`
187
+ );
188
+ }
189
+ const fileBuffer = fs.readFileSync(filePath);
190
+ const file = new File([fileBuffer], fileName, { type: mimeType });
191
+ const formData = new FormData();
192
+ formData.append("file", file);
193
+ formData.append("purpose", purpose);
194
+ const response = await fetch(`${this.baseUrl}/files`, {
195
+ method: "POST",
196
+ headers: {
197
+ Authorization: `Bearer ${this.apiKey}`
198
+ },
199
+ body: formData
200
+ });
201
+ if (!response.ok) {
202
+ const error = await response.text();
203
+ throw new FileManagerError(
204
+ "UPLOAD_FAILED" /* UPLOAD_FAILED */,
205
+ `Kimi upload failed: ${error}`
206
+ );
207
+ }
208
+ const result = await response.json();
209
+ return {
210
+ fileId: result.id,
211
+ name: result.filename,
212
+ size: result.bytes,
213
+ mimeType: this.guessMimeType(result.filename),
214
+ createdAt: result.created_at * 1e3,
215
+ status: result.status === "ok" ? "active" : "processing"
216
+ };
217
+ }
218
+ detectPurpose(filePath, purpose, mimeType) {
219
+ if (purpose && purpose !== "auto") {
220
+ return purpose;
221
+ }
222
+ if (mimeType) {
223
+ if (mimeType.startsWith("video/")) {
224
+ return "video";
225
+ }
226
+ if (mimeType.startsWith("image/")) {
227
+ return "image";
228
+ }
229
+ return "file-extract";
230
+ }
231
+ const ext = filePath.toLowerCase();
232
+ if (ext.match(/\.(mp4|mov|avi|webm|mkv)$/)) {
233
+ return "video";
234
+ }
235
+ if (ext.match(/\.(jpg|jpeg|png|webp|gif)$/)) {
236
+ return "image";
237
+ }
238
+ return "file-extract";
239
+ }
240
+ guessMimeType(filename) {
241
+ const ext = path.extname(filename).toLowerCase();
242
+ switch (ext) {
243
+ case ".jpg":
244
+ case ".jpeg":
245
+ return "image/jpeg";
246
+ case ".png":
247
+ return "image/png";
248
+ case ".webp":
249
+ return "image/webp";
250
+ case ".gif":
251
+ return "image/gif";
252
+ case ".mp4":
253
+ return "video/mp4";
254
+ case ".mov":
255
+ return "video/quicktime";
256
+ case ".avi":
257
+ return "video/x-msvideo";
258
+ case ".webm":
259
+ return "video/webm";
260
+ case ".pdf":
261
+ return "application/pdf";
262
+ case ".txt":
263
+ return "text/plain";
264
+ case ".md":
265
+ return "text/markdown";
266
+ default:
267
+ return "application/octet-stream";
268
+ }
269
+ }
270
+ // ============================================================================
271
+ // Status Check
272
+ // ============================================================================
273
+ async getStatus(fileId) {
274
+ const response = await fetch(`${this.baseUrl}/files/${fileId}`, {
275
+ headers: {
276
+ Authorization: `Bearer ${this.apiKey}`
277
+ }
278
+ });
279
+ if (response.status === 404) {
280
+ return {
281
+ fileId,
282
+ status: "not_found"
283
+ };
284
+ }
285
+ if (!response.ok) {
286
+ const error = await response.text();
287
+ return {
288
+ fileId,
289
+ status: "error",
290
+ error
291
+ };
292
+ }
293
+ const result = await response.json();
294
+ return {
295
+ fileId,
296
+ status: this.mapStatus(result.status),
297
+ createdAt: result.created_at * 1e3,
298
+ error: result.status_details
299
+ };
300
+ }
301
+ mapStatus(kimiStatus) {
302
+ switch (kimiStatus) {
303
+ case "ok":
304
+ return "active";
305
+ case "created":
306
+ case "processing":
307
+ return "processing";
308
+ case "error":
309
+ return "error";
310
+ default:
311
+ console.warn(`[KimiAdapter] Unknown status: ${kimiStatus}, treating as processing`);
312
+ return "processing";
313
+ }
314
+ }
315
+ // ============================================================================
316
+ // Delete
317
+ // ============================================================================
318
+ async delete(fileId) {
319
+ const response = await fetch(`${this.baseUrl}/files/${fileId}`, {
320
+ method: "DELETE",
321
+ headers: {
322
+ Authorization: `Bearer ${this.apiKey}`
323
+ }
324
+ });
325
+ if (!response.ok && response.status !== 404) {
326
+ const error = await response.text();
327
+ throw new FileManagerError(
328
+ "UPLOAD_FAILED" /* UPLOAD_FAILED */,
329
+ `Kimi delete failed: ${error}`
330
+ );
331
+ }
332
+ }
333
+ async getContent(fileId) {
334
+ const response = await fetch(`${this.baseUrl}/files/${fileId}/content`, {
335
+ headers: {
336
+ Authorization: `Bearer ${this.apiKey}`
337
+ }
338
+ });
339
+ if (!response.ok) {
340
+ const error = await response.text();
341
+ throw new FileManagerError(
342
+ "UPLOAD_FAILED" /* UPLOAD_FAILED */,
343
+ `Kimi content extraction failed: ${error}`
344
+ );
345
+ }
346
+ return response.text();
347
+ }
348
+ // ============================================================================
349
+ // List Files
350
+ // ============================================================================
351
+ async list(options = {}) {
352
+ const limit = options.limit || 100;
353
+ const url = `${this.baseUrl}/files?limit=${limit}`;
354
+ const response = await fetch(url, {
355
+ headers: {
356
+ Authorization: `Bearer ${this.apiKey}`
357
+ }
358
+ });
359
+ if (!response.ok) {
360
+ const error = await response.text();
361
+ throw new FileManagerError(
362
+ "UPLOAD_FAILED" /* UPLOAD_FAILED */,
363
+ `Kimi list failed: ${error}`
364
+ );
365
+ }
366
+ const result = await response.json();
367
+ return result.data.map((file) => ({
368
+ hash: "",
369
+ // We don't have hash from API
370
+ name: file.filename,
371
+ size: file.bytes,
372
+ type: this.guessFileType(file.filename),
373
+ mimeType: this.guessMimeType(file.filename),
374
+ createdAt: file.created_at * 1e3,
375
+ platforms: ["kimi"],
376
+ status: file.status === "ok" ? "ready" : "uploading"
377
+ }));
378
+ }
379
+ guessFileType(filename) {
380
+ const mimeType = this.guessMimeType(filename);
381
+ if (mimeType.startsWith("image/")) return "image";
382
+ if (mimeType.startsWith("video/")) return "video";
383
+ return "document";
384
+ }
385
+ // ============================================================================
386
+ // Build Reference
387
+ // ============================================================================
388
+ /**
389
+ * Build platform-specific content reference
390
+ */
391
+ buildReference(fileId, mimeType) {
392
+ const modality = mimeType.startsWith("image/") ? "image" : mimeType.startsWith("video/") ? "video" : "file";
393
+ return {
394
+ type: "fileRef",
395
+ url: `ms://${fileId}`,
396
+ mimeType,
397
+ modality
398
+ };
399
+ }
400
+ };
401
+
402
+ // src/files/adapters/gemini-adapter.ts
403
+ import * as fs2 from "node:fs";
404
+ import * as path2 from "node:path";
405
+ import { Readable } from "node:stream";
406
+ var GeminiFileAdapter = class {
407
+ platform = "gemini";
408
+ capabilities = {
409
+ supportsNativeVideo: true,
410
+ supportsFileReference: true,
411
+ maxFileSize: 2 * 1024 * 1024 * 1024,
412
+ // 2GB for files API
413
+ supportedMimeTypes: [
414
+ "image/jpeg",
415
+ "image/png",
416
+ "image/webp",
417
+ "image/heic",
418
+ "image/heif",
419
+ "video/mp4",
420
+ "video/mpeg",
421
+ "video/mov",
422
+ "video/avi",
423
+ "video/x-flv",
424
+ "video/mpg",
425
+ "video/webm",
426
+ "video/wmv",
427
+ "video/3gpp",
428
+ "application/pdf",
429
+ "text/plain",
430
+ "text/html",
431
+ "text/css",
432
+ "text/javascript",
433
+ "application/json",
434
+ "text/markdown",
435
+ "text/x-python",
436
+ "text/java",
437
+ "text/x-c",
438
+ "text/x-c++",
439
+ "text/x-csharp",
440
+ "text/x-php",
441
+ "text/x-ruby",
442
+ "text/x-go",
443
+ "text/x-rust",
444
+ "text/x-swift",
445
+ "text/x-kotlin",
446
+ "text/x-sql",
447
+ "text/xml",
448
+ "application/rtf"
449
+ ]
450
+ };
451
+ apiKey;
452
+ baseUrl;
453
+ constructor(apiKey, baseUrl = "https://generativelanguage.googleapis.com/v1beta") {
454
+ this.apiKey = apiKey;
455
+ this.baseUrl = baseUrl;
456
+ }
457
+ // ============================================================================
458
+ // Upload
459
+ // ============================================================================
460
+ async upload(filePath, options = {}) {
461
+ const stats = fs2.statSync(filePath);
462
+ if (stats.size > this.capabilities.maxFileSize) {
463
+ throw new FileManagerError(
464
+ "FILE_TOO_LARGE" /* FILE_TOO_LARGE */,
465
+ `File size ${(stats.size / 1024 / 1024 / 1024).toFixed(1)}GB exceeds Gemini limit of 2GB`
466
+ );
467
+ }
468
+ const mimeType = options.mimeType || this.guessMimeType(filePath);
469
+ const displayName = options.sourceName || path2.basename(filePath);
470
+ const startResponse = await fetch(
471
+ `${this.baseUrl}/upload/v1beta/files?key=${this.apiKey}`,
472
+ {
473
+ method: "POST",
474
+ headers: {
475
+ "X-Goog-Upload-Protocol": "resumable",
476
+ "X-Goog-Upload-Command": "start",
477
+ "X-Goog-Upload-Header-Content-Length": String(stats.size),
478
+ "X-Goog-Upload-Header-Content-Type": mimeType,
479
+ "Content-Type": "application/json"
480
+ },
481
+ body: JSON.stringify({
482
+ file: { displayName }
483
+ })
484
+ }
485
+ );
486
+ if (!startResponse.ok) {
487
+ const error = await startResponse.text();
488
+ throw new FileManagerError(
489
+ "UPLOAD_FAILED" /* UPLOAD_FAILED */,
490
+ `Gemini upload start failed: ${error}`
491
+ );
492
+ }
493
+ const uploadUrl = startResponse.headers.get("x-goog-upload-url");
494
+ if (!uploadUrl) {
495
+ throw new FileManagerError(
496
+ "UPLOAD_FAILED" /* UPLOAD_FAILED */,
497
+ "No upload URL received"
498
+ );
499
+ }
500
+ const fileStream = Readable.toWeb(fs2.createReadStream(filePath));
501
+ const uploadResponse = await fetch(uploadUrl, {
502
+ method: "POST",
503
+ headers: {
504
+ "Content-Length": String(stats.size),
505
+ "X-Goog-Upload-Offset": "0",
506
+ "X-Goog-Upload-Command": "upload, finalize"
507
+ },
508
+ body: fileStream,
509
+ // @ts-ignore - duplex option required for streaming request body in Node.js
510
+ duplex: "half"
511
+ });
512
+ if (!uploadResponse.ok) {
513
+ const error = await uploadResponse.text();
514
+ throw new FileManagerError(
515
+ "UPLOAD_FAILED" /* UPLOAD_FAILED */,
516
+ `Gemini upload failed: ${error}`
517
+ );
518
+ }
519
+ const result = await uploadResponse.json();
520
+ return {
521
+ fileId: result.file.uri,
522
+ name: result.file.displayName || displayName,
523
+ size: stats.size,
524
+ mimeType: result.file.mimeType || mimeType,
525
+ createdAt: new Date(result.file.createTime).getTime(),
526
+ expiresAt: result.file.expirationTime ? new Date(result.file.expirationTime).getTime() : void 0,
527
+ status: result.file.state === "ACTIVE" ? "active" : "processing"
528
+ };
529
+ }
530
+ // ============================================================================
531
+ // Status Check
532
+ // ============================================================================
533
+ async getStatus(fileId) {
534
+ const url = fileId.includes("/") ? fileId : `${this.baseUrl}/files/${fileId}`;
535
+ const response = await fetch(`${url}?key=${this.apiKey}`);
536
+ if (response.status === 404) {
537
+ return {
538
+ fileId,
539
+ status: "not_found"
540
+ };
541
+ }
542
+ if (!response.ok) {
543
+ const error = await response.text();
544
+ return {
545
+ fileId,
546
+ status: "error",
547
+ error
548
+ };
549
+ }
550
+ const result = await response.json();
551
+ return {
552
+ fileId,
553
+ status: this.mapStatus(result.file.state),
554
+ createdAt: new Date(result.file.createTime).getTime(),
555
+ expiresAt: result.file.expirationTime ? new Date(result.file.expirationTime).getTime() : void 0
556
+ };
557
+ }
558
+ mapStatus(geminiState) {
559
+ switch (geminiState) {
560
+ case "ACTIVE":
561
+ return "active";
562
+ case "PROCESSING":
563
+ return "processing";
564
+ case "FAILED":
565
+ return "error";
566
+ default:
567
+ return "error";
568
+ }
569
+ }
570
+ // ============================================================================
571
+ // Delete
572
+ // ============================================================================
573
+ async delete(fileId) {
574
+ const url = fileId.includes("/") ? fileId : `${this.baseUrl}/files/${fileId}`;
575
+ const response = await fetch(`${url}?key=${this.apiKey}`, {
576
+ method: "DELETE"
577
+ });
578
+ if (!response.ok && response.status !== 404) {
579
+ const error = await response.text();
580
+ throw new FileManagerError(
581
+ "UPLOAD_FAILED" /* UPLOAD_FAILED */,
582
+ `Gemini delete failed: ${error}`
583
+ );
584
+ }
585
+ }
586
+ // ============================================================================
587
+ // List Files
588
+ // ============================================================================
589
+ async list(options = {}) {
590
+ const pageSize = options.limit || 100;
591
+ const url = `${this.baseUrl}/files?key=${this.apiKey}&pageSize=${pageSize}`;
592
+ const response = await fetch(url);
593
+ if (!response.ok) {
594
+ const error = await response.text();
595
+ throw new FileManagerError(
596
+ "UPLOAD_FAILED" /* UPLOAD_FAILED */,
597
+ `Gemini list failed: ${error}`
598
+ );
599
+ }
600
+ const result = await response.json();
601
+ return result.files.map((file) => ({
602
+ hash: "",
603
+ // We don't have hash from API
604
+ name: file.displayName || "unnamed",
605
+ size: 0,
606
+ // Not provided by API
607
+ type: this.guessFileType(file.mimeType),
608
+ mimeType: file.mimeType,
609
+ createdAt: new Date(file.createTime).getTime(),
610
+ platforms: ["gemini"],
611
+ status: file.state === "ACTIVE" ? "ready" : "uploading"
612
+ }));
613
+ }
614
+ guessFileType(mimeType) {
615
+ if (mimeType?.startsWith("image/")) return "image";
616
+ if (mimeType?.startsWith("video/")) return "video";
617
+ return "document";
618
+ }
619
+ guessMimeType(filePath) {
620
+ const ext = filePath.toLowerCase().split(".").pop();
621
+ switch (ext) {
622
+ case "jpg":
623
+ case "jpeg":
624
+ return "image/jpeg";
625
+ case "png":
626
+ return "image/png";
627
+ case "webp":
628
+ return "image/webp";
629
+ case "heic":
630
+ return "image/heic";
631
+ case "heif":
632
+ return "image/heif";
633
+ case "mp4":
634
+ return "video/mp4";
635
+ case "mov":
636
+ return "video/quicktime";
637
+ case "avi":
638
+ return "video/x-msvideo";
639
+ case "webm":
640
+ return "video/webm";
641
+ case "pdf":
642
+ return "application/pdf";
643
+ case "txt":
644
+ return "text/plain";
645
+ case "md":
646
+ return "text/markdown";
647
+ case "json":
648
+ return "application/json";
649
+ case "html":
650
+ return "text/html";
651
+ case "js":
652
+ return "text/javascript";
653
+ case "py":
654
+ return "text/x-python";
655
+ case "java":
656
+ return "text/java";
657
+ case "c":
658
+ return "text/x-c";
659
+ case "cpp":
660
+ case "cc":
661
+ return "text/x-c++";
662
+ case "cs":
663
+ return "text/x-csharp";
664
+ case "php":
665
+ return "text/x-php";
666
+ case "rb":
667
+ return "text/x-ruby";
668
+ case "go":
669
+ return "text/x-go";
670
+ case "rs":
671
+ return "text/x-rust";
672
+ case "swift":
673
+ return "text/x-swift";
674
+ case "kt":
675
+ return "text/x-kotlin";
676
+ case "sql":
677
+ return "text/x-sql";
678
+ case "xml":
679
+ return "text/xml";
680
+ case "rtf":
681
+ return "application/rtf";
682
+ default:
683
+ return "application/octet-stream";
684
+ }
685
+ }
686
+ // ============================================================================
687
+ // Build Reference
688
+ // ============================================================================
689
+ /**
690
+ * Build platform-specific content reference
691
+ */
692
+ buildReference(fileId, mimeType) {
693
+ const modality = mimeType.startsWith("image/") ? "image" : mimeType.startsWith("video/") ? "video" : "file";
694
+ return {
695
+ type: "fileRef",
696
+ url: fileId,
697
+ mimeType,
698
+ modality
699
+ };
700
+ }
701
+ };
702
+
703
+ // src/files/adapters/openai-compatible-files-adapter.ts
704
+ import * as fs3 from "node:fs";
705
+ import * as path3 from "node:path";
706
+ var OpenAICompatibleFilesAdapter = class {
707
+ constructor(apiKey, baseUrl, extraHeaders = {}) {
708
+ this.apiKey = apiKey;
709
+ this.baseUrl = baseUrl;
710
+ this.extraHeaders = extraHeaders;
711
+ if (!baseUrl) {
712
+ throw new Error("OpenAICompatibleFilesAdapter requires an explicit baseUrl from models.json.");
713
+ }
714
+ }
715
+ apiKey;
716
+ baseUrl;
717
+ extraHeaders;
718
+ platform = "openai-compatible-files";
719
+ capabilities = {
720
+ supportsNativeVideo: false,
721
+ supportsFileReference: true,
722
+ maxFileSize: 100 * 1024 * 1024,
723
+ supportedMimeTypes: [
724
+ "application/pdf",
725
+ "text/plain",
726
+ "text/markdown",
727
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
728
+ ]
729
+ };
730
+ async upload(filePath, options = {}) {
731
+ const fileName = options.sourceName || path3.basename(filePath);
732
+ const mimeType = options.mimeType || guessMimeType(fileName);
733
+ const stats = fs3.statSync(filePath);
734
+ if (stats.size > this.capabilities.maxFileSize) {
735
+ throw new FileManagerError(
736
+ "FILE_TOO_LARGE" /* FILE_TOO_LARGE */,
737
+ `File size ${(stats.size / 1024 / 1024).toFixed(1)}MB exceeds OpenAI-compatible Files limit of ${this.capabilities.maxFileSize / 1024 / 1024}MB`
738
+ );
739
+ }
740
+ const file = new File([fs3.readFileSync(filePath)], fileName, { type: mimeType });
741
+ const formData = new FormData();
742
+ formData.append("file", file);
743
+ formData.append("purpose", options.purpose && options.purpose !== "auto" ? options.purpose : "file-extract");
744
+ const response = await fetch(`${trimBaseUrl(this.baseUrl)}/files`, {
745
+ method: "POST",
746
+ headers: this.authHeaders(),
747
+ body: formData
748
+ });
749
+ if (!response.ok) {
750
+ throw new FileManagerError(
751
+ "UPLOAD_FAILED" /* UPLOAD_FAILED */,
752
+ `OpenAI-compatible file upload failed: ${await response.text()}`
753
+ );
754
+ }
755
+ const result = await response.json();
756
+ const fileId = result.id || result.fileId;
757
+ if (!fileId) {
758
+ throw new FileManagerError(
759
+ "UPLOAD_FAILED" /* UPLOAD_FAILED */,
760
+ `OpenAI-compatible file upload did not return a file id.`
761
+ );
762
+ }
763
+ return {
764
+ fileId,
765
+ name: result.filename || fileName,
766
+ size: result.bytes || stats.size,
767
+ mimeType,
768
+ createdAt: result.created_at ? result.created_at * 1e3 : Date.now(),
769
+ status: statusIsReady(result.status) ? "active" : "processing"
770
+ };
771
+ }
772
+ async getStatus(fileId) {
773
+ const response = await fetch(`${trimBaseUrl(this.baseUrl)}/files/${fileId}`, {
774
+ headers: this.authHeaders()
775
+ });
776
+ if (response.status === 404) {
777
+ return { fileId, status: "not_found" };
778
+ }
779
+ if (!response.ok) {
780
+ return { fileId, status: "error", error: await response.text() };
781
+ }
782
+ const result = await response.json();
783
+ const status = result.status ? mapStatus(result.status) : "active";
784
+ return {
785
+ fileId,
786
+ status,
787
+ createdAt: result.created_at ? result.created_at * 1e3 : void 0,
788
+ error: result.status_details
789
+ };
790
+ }
791
+ async delete(fileId) {
792
+ const response = await fetch(`${trimBaseUrl(this.baseUrl)}/files/${fileId}`, {
793
+ method: "DELETE",
794
+ headers: this.authHeaders()
795
+ });
796
+ if (!response.ok && response.status !== 404) {
797
+ throw new FileManagerError(
798
+ "UPLOAD_FAILED" /* UPLOAD_FAILED */,
799
+ `OpenAI-compatible file delete failed: ${await response.text()}`
800
+ );
801
+ }
802
+ }
803
+ async getContent(fileId) {
804
+ const response = await fetch(`${trimBaseUrl(this.baseUrl)}/files/${fileId}/content`, {
805
+ headers: this.authHeaders()
806
+ });
807
+ if (!response.ok) {
808
+ throw new FileManagerError(
809
+ "UPLOAD_FAILED" /* UPLOAD_FAILED */,
810
+ `OpenAI-compatible file content extraction failed: ${await response.text()}`
811
+ );
812
+ }
813
+ return extractContentText(await response.text());
814
+ }
815
+ async list(_options = {}) {
816
+ return [];
817
+ }
818
+ buildReference(fileId, mimeType) {
819
+ return {
820
+ type: "fileRef",
821
+ url: `ms://${fileId}`,
822
+ mimeType,
823
+ modality: mimeType.startsWith("image/") ? "image" : mimeType.startsWith("video/") ? "video" : "file"
824
+ };
825
+ }
826
+ authHeaders() {
827
+ return {
828
+ Authorization: `Bearer ${this.apiKey}`,
829
+ ...this.extraHeaders
830
+ };
831
+ }
832
+ };
833
+ function trimBaseUrl(baseUrl) {
834
+ return baseUrl.replace(/\/+$/, "");
835
+ }
836
+ function statusIsReady(status) {
837
+ return !status || ["ok", "active", "ready", "completed", "success"].includes(status.toLowerCase());
838
+ }
839
+ function mapStatus(status) {
840
+ const lower = status.toLowerCase();
841
+ if (["ok", "active", "ready", "completed", "success"].includes(lower)) return "active";
842
+ if (["created", "processing", "queued", "pending"].includes(lower)) return "processing";
843
+ if (lower === "expired") return "expired";
844
+ if (lower === "not_found") return "not_found";
845
+ return "error";
846
+ }
847
+ function extractContentText(raw) {
848
+ try {
849
+ const parsed = JSON.parse(raw);
850
+ if (typeof parsed.content === "string") return parsed.content;
851
+ if (typeof parsed.text === "string") return parsed.text;
852
+ } catch {
853
+ }
854
+ return raw;
855
+ }
856
+ function guessMimeType(filename) {
857
+ const ext = path3.extname(filename).toLowerCase();
858
+ switch (ext) {
859
+ case ".pdf":
860
+ return "application/pdf";
861
+ case ".docx":
862
+ return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
863
+ case ".md":
864
+ return "text/markdown";
865
+ case ".txt":
866
+ return "text/plain";
867
+ default:
868
+ return "application/octet-stream";
869
+ }
870
+ }
871
+
872
+ // src/files/file-manager.ts
873
+ import * as fs7 from "node:fs";
874
+ import * as path8 from "node:path";
875
+ import * as crypto2 from "node:crypto";
876
+
877
+ // src/files/file-cache.ts
878
+ import * as fs4 from "node:fs";
879
+ import * as path5 from "node:path";
880
+ import * as crypto from "node:crypto";
881
+
882
+ // src/files/logger.ts
883
+ function verboseEnabled() {
884
+ return process.env.PIE_VERBOSE_FILES === "true" || process.env.PIE_VERBOSE === "true";
885
+ }
886
+ var Logger = class _Logger {
887
+ prefix;
888
+ enabled;
889
+ constructor(options = {}) {
890
+ this.prefix = options.prefix || "files";
891
+ this.enabled = options.enabled ?? verboseEnabled();
892
+ }
893
+ write(level, message, data) {
894
+ if ((level === "debug" || level === "info") && !this.enabled) {
895
+ return;
896
+ }
897
+ const logger2 = getLogger().child({ module: this.prefix });
898
+ const context = data === void 0 ? void 0 : { data };
899
+ switch (level) {
900
+ case "debug":
901
+ logger2.debug(message, context);
902
+ break;
903
+ case "info":
904
+ logger2.info(message, context);
905
+ break;
906
+ case "warn":
907
+ logger2.warn(message, context);
908
+ break;
909
+ case "error":
910
+ logger2.error(message, context);
911
+ break;
912
+ }
913
+ }
914
+ debug(message, data) {
915
+ this.write("debug", message, data);
916
+ }
917
+ info(message, data) {
918
+ this.write("info", message, data);
919
+ }
920
+ warn(message, data) {
921
+ this.write("warn", message, data);
922
+ }
923
+ error(message, err) {
924
+ const data = err instanceof Error ? { error: err.message, stack: err.stack } : err;
925
+ this.write("error", message, data);
926
+ }
927
+ child(subPrefix) {
928
+ return new _Logger({
929
+ prefix: `${this.prefix}${subPrefix}`,
930
+ enabled: this.enabled
931
+ });
932
+ }
933
+ };
934
+ var logger = new Logger({ prefix: "files" });
935
+ var cacheLogger = logger.child(".cache");
936
+ var sessionLogger = logger.child(".session");
937
+ var adapterLogger = logger.child(".adapter");
938
+ var monitorLogger = logger.child(".monitor");
939
+ var ffmpegLogger = logger.child(".ffmpeg");
940
+
941
+ // src/files/types.ts
942
+ var MIME_TYPES = {
943
+ ".jpg": "image/jpeg",
944
+ ".jpeg": "image/jpeg",
945
+ ".png": "image/png",
946
+ ".gif": "image/gif",
947
+ ".webp": "image/webp",
948
+ ".mp4": "video/mp4",
949
+ ".mov": "video/quicktime",
950
+ ".avi": "video/x-msvideo",
951
+ ".webm": "video/webm",
952
+ ".mkv": "video/x-matroska",
953
+ ".pdf": "application/pdf",
954
+ ".html": "text/html",
955
+ ".htm": "text/html",
956
+ ".txt": "text/plain",
957
+ ".md": "text/markdown",
958
+ ".json": "application/json"
959
+ };
960
+ var DEFAULT_VIDEO_OPTIONS = {
961
+ maxResolution: 720,
962
+ fps: 10,
963
+ targetSizeMB: 50,
964
+ keyframeCount: 20,
965
+ crf: 28
966
+ };
967
+ var DEFAULT_PIC_OPTIONS = {
968
+ maxWidth: 2048,
969
+ quality: 85,
970
+ format: "jpeg"
971
+ };
972
+
973
+ // src/files/utils.ts
974
+ import * as path4 from "node:path";
975
+ import { homedir } from "node:os";
976
+ var WINDOWS_ABSOLUTE_PATH_RE = /^(?:[a-zA-Z]:[\\/]|[\\/]{2}[^\\/]+[\\/][^\\/]+)/;
977
+ function isWindowsAbsolutePath(filePath) {
978
+ return WINDOWS_ABSOLUTE_PATH_RE.test(filePath);
979
+ }
980
+ function getHomeDirectory() {
981
+ return homedir() || process.env.USERPROFILE || process.env.HOME || ".";
982
+ }
983
+ function looksLikeFilePath(inputPath) {
984
+ return inputPath.startsWith("/") || inputPath.startsWith("~") || inputPath.startsWith("./") || inputPath.startsWith("../") || inputPath.startsWith(".\\") || inputPath.startsWith("..\\") || isWindowsAbsolutePath(inputPath);
985
+ }
986
+ function formatBytes(bytes) {
987
+ if (bytes < 1024) return `${bytes}B`;
988
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
989
+ if (bytes < 1024 * 1024 * 1024)
990
+ return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
991
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)}GB`;
992
+ }
993
+ function resolvePath(inputPath) {
994
+ if (inputPath.startsWith("~")) {
995
+ return path4.join(getHomeDirectory(), inputPath.slice(1));
996
+ }
997
+ if (isWindowsAbsolutePath(inputPath)) {
998
+ return inputPath;
999
+ }
1000
+ if (!path4.isAbsolute(inputPath)) {
1001
+ return path4.resolve(process.cwd(), inputPath);
1002
+ }
1003
+ return inputPath;
1004
+ }
1005
+ function getFileTypeIcon(type) {
1006
+ switch (type) {
1007
+ case "image":
1008
+ return "\u{1F5BC}\uFE0F";
1009
+ case "video":
1010
+ return "\u{1F3AC}";
1011
+ case "document":
1012
+ return "\u{1F4C4}";
1013
+ default:
1014
+ return "\u{1F4CE}";
1015
+ }
1016
+ }
1017
+
1018
+ // src/files/file-cache.ts
1019
+ var CACHE_VERSION = "1.0.0";
1020
+ var DEFAULT_MAX_CACHE_ENTRIES = 500;
1021
+ var FileCache = class _FileCache {
1022
+ baseDir;
1023
+ dataDir;
1024
+ indexPath;
1025
+ index;
1026
+ maxEntries;
1027
+ constructor(baseDir, maxEntries = DEFAULT_MAX_CACHE_ENTRIES) {
1028
+ this.baseDir = baseDir;
1029
+ this.dataDir = path5.join(baseDir, "data");
1030
+ this.indexPath = path5.join(baseDir, "index.json");
1031
+ this.maxEntries = maxEntries;
1032
+ this.index = this.loadIndex();
1033
+ this.ensureDirectories();
1034
+ }
1035
+ // ============================================================================
1036
+ // Directory Management
1037
+ // ============================================================================
1038
+ ensureDirectories() {
1039
+ if (!fs4.existsSync(this.baseDir)) {
1040
+ fs4.mkdirSync(this.baseDir, { recursive: true });
1041
+ }
1042
+ if (!fs4.existsSync(this.dataDir)) {
1043
+ fs4.mkdirSync(this.dataDir, { recursive: true });
1044
+ }
1045
+ }
1046
+ // ============================================================================
1047
+ // Index Management
1048
+ // ============================================================================
1049
+ loadIndex() {
1050
+ if (!fs4.existsSync(this.indexPath)) {
1051
+ return { version: CACHE_VERSION, files: {}, pathHints: {} };
1052
+ }
1053
+ try {
1054
+ const data = JSON.parse(fs4.readFileSync(this.indexPath, "utf-8"));
1055
+ if (data.version !== CACHE_VERSION) {
1056
+ cacheLogger.warn(`Index version mismatch: ${data.version} vs ${CACHE_VERSION}`);
1057
+ }
1058
+ return {
1059
+ version: data.version || CACHE_VERSION,
1060
+ files: data.files || {},
1061
+ pathHints: data.pathHints || {}
1062
+ };
1063
+ } catch (err) {
1064
+ cacheLogger.error(" Failed to load index, creating new:", err);
1065
+ return { version: CACHE_VERSION, files: {}, pathHints: {} };
1066
+ }
1067
+ }
1068
+ saveIndex() {
1069
+ try {
1070
+ fs4.writeFileSync(this.indexPath, JSON.stringify(this.index, null, 2));
1071
+ } catch (err) {
1072
+ cacheLogger.error(" Failed to save index:", err);
1073
+ throw err;
1074
+ }
1075
+ }
1076
+ // ============================================================================
1077
+ // Hash Computation
1078
+ // ============================================================================
1079
+ async computeHash(filePath) {
1080
+ return new Promise((resolve2, reject) => {
1081
+ const hash = crypto.createHash("sha256");
1082
+ const stream = fs4.createReadStream(filePath);
1083
+ stream.on("data", (chunk) => hash.update(chunk));
1084
+ stream.on("end", () => resolve2(hash.digest("hex")));
1085
+ stream.on("error", reject);
1086
+ });
1087
+ }
1088
+ computeHashSync(data) {
1089
+ return crypto.createHash("sha256").update(data).digest("hex");
1090
+ }
1091
+ // ============================================================================
1092
+ // File Storage
1093
+ // ============================================================================
1094
+ getStoragePath(hash) {
1095
+ const subdir = hash.slice(0, 2);
1096
+ const fullDir = path5.join(this.dataDir, subdir);
1097
+ if (!fs4.existsSync(fullDir)) {
1098
+ fs4.mkdirSync(fullDir, { recursive: true });
1099
+ }
1100
+ return path5.join(fullDir, hash);
1101
+ }
1102
+ getStorageRelativePath(hash) {
1103
+ const subdir = hash.slice(0, 2);
1104
+ return path5.join(subdir, hash);
1105
+ }
1106
+ async storeFile(sourcePath, name, mimeType) {
1107
+ const hash = await this.computeHash(sourcePath);
1108
+ const storagePath = this.getStoragePath(hash);
1109
+ this.rememberPathHint(sourcePath, hash, name);
1110
+ if (fs4.existsSync(storagePath)) {
1111
+ return { hash, localPath: storagePath };
1112
+ }
1113
+ fs4.copyFileSync(sourcePath, storagePath);
1114
+ const stat2 = fs4.statSync(storagePath);
1115
+ this.index.files[hash] = {
1116
+ hash,
1117
+ name,
1118
+ size: stat2.size,
1119
+ mimeType,
1120
+ createdAt: Date.now(),
1121
+ localPath: this.getStorageRelativePath(hash),
1122
+ platforms: {}
1123
+ };
1124
+ this.saveIndex();
1125
+ this.evictIfNeeded();
1126
+ return { hash, localPath: storagePath };
1127
+ }
1128
+ async storeBuffer(data, name, mimeType) {
1129
+ const hash = this.computeHashSync(data);
1130
+ const storagePath = this.getStoragePath(hash);
1131
+ if (fs4.existsSync(storagePath)) {
1132
+ return { hash, localPath: storagePath };
1133
+ }
1134
+ fs4.writeFileSync(storagePath, data);
1135
+ this.index.files[hash] = {
1136
+ hash,
1137
+ name,
1138
+ size: data.length,
1139
+ mimeType,
1140
+ createdAt: Date.now(),
1141
+ localPath: this.getStorageRelativePath(hash),
1142
+ platforms: {}
1143
+ };
1144
+ this.saveIndex();
1145
+ this.evictIfNeeded();
1146
+ return { hash, localPath: storagePath };
1147
+ }
1148
+ // ============================================================================
1149
+ // File Retrieval
1150
+ // ============================================================================
1151
+ getByHash(hash) {
1152
+ return this.index.files[hash];
1153
+ }
1154
+ /** Repair historical image MIME labels using the cached bytes. Content
1155
+ * deduplication must not keep an old .png-derived label when the same
1156
+ * Feishu JPEG is staged again with the corrected .jpg name. The hash,
1157
+ * bytes and platform upload records stay unchanged. */
1158
+ refreshImageMimeType(hash) {
1159
+ const entry = this.index.files[hash];
1160
+ if (!entry || !entry.mimeType.startsWith("image/")) return;
1161
+ const localPath = this.getLocalPath(hash);
1162
+ if (!localPath) return;
1163
+ const detected = readImageFormat(localPath);
1164
+ if (detected.ext === ".bin" || detected.mime === entry.mimeType) return;
1165
+ entry.mimeType = detected.mime;
1166
+ this.saveIndex();
1167
+ }
1168
+ getByFileId(fileId, platform) {
1169
+ for (const entry of Object.values(this.index.files)) {
1170
+ const platformRecord = entry.platforms[platform];
1171
+ if (platformRecord?.fileId === fileId) {
1172
+ return entry;
1173
+ }
1174
+ }
1175
+ return void 0;
1176
+ }
1177
+ getLocalPath(hash) {
1178
+ const entry = this.index.files[hash];
1179
+ if (!entry) return void 0;
1180
+ return path5.join(this.dataDir, entry.localPath);
1181
+ }
1182
+ exists(hash) {
1183
+ return hash in this.index.files;
1184
+ }
1185
+ // ============================================================================
1186
+ // Platform Records
1187
+ // ============================================================================
1188
+ addPlatformRecord(hash, platform, record) {
1189
+ const entry = this.index.files[hash];
1190
+ if (!entry) {
1191
+ throw new Error(`File with hash ${hash} not found in cache`);
1192
+ }
1193
+ entry.platforms[platform] = record;
1194
+ if (this.index.pathHints) {
1195
+ for (const hint of Object.values(this.index.pathHints)) {
1196
+ if (hint.hash !== hash) continue;
1197
+ hint.uploadedPlatforms = Array.from(/* @__PURE__ */ new Set([...hint.uploadedPlatforms || [], platform]));
1198
+ hint.updatedAt = Date.now();
1199
+ if (!hint.name) {
1200
+ hint.name = entry.name;
1201
+ }
1202
+ }
1203
+ }
1204
+ this.saveIndex();
1205
+ }
1206
+ updatePlatformStatus(hash, platform, status) {
1207
+ const entry = this.index.files[hash];
1208
+ if (!entry?.platforms[platform]) return;
1209
+ const mappedStatus = status === "not_found" ? "error" : status;
1210
+ entry.platforms[platform].status = mappedStatus;
1211
+ entry.platforms[platform].lastCheckedAt = Date.now();
1212
+ this.saveIndex();
1213
+ }
1214
+ getPlatformRecord(hash, platform) {
1215
+ return this.index.files[hash]?.platforms[platform];
1216
+ }
1217
+ getPathHint(filePath) {
1218
+ try {
1219
+ const resolvedPath = this.getResolvedHintPath(filePath);
1220
+ const stat2 = fs4.statSync(resolvedPath);
1221
+ if (!stat2.isFile()) return void 0;
1222
+ const normalizedMtimeMs = this.normalizeHintMtimeMs(stat2.mtimeMs);
1223
+ const key = this.getPathHintKey(resolvedPath);
1224
+ let hint = this.index.pathHints?.[key];
1225
+ if (!hint && this.index.pathHints) {
1226
+ const legacyEntry = Object.entries(this.index.pathHints).find(
1227
+ ([legacyKey, candidate]) => (candidate.path === resolvedPath || legacyKey.startsWith(`${resolvedPath}::`)) && candidate.size === stat2.size && this.normalizeHintMtimeMs(candidate.mtimeMs) === normalizedMtimeMs
1228
+ );
1229
+ if (legacyEntry) {
1230
+ hint = legacyEntry[1];
1231
+ this.index.pathHints[key] = {
1232
+ ...hint,
1233
+ path: resolvedPath
1234
+ };
1235
+ this.saveIndex();
1236
+ }
1237
+ }
1238
+ if (!hint) return void 0;
1239
+ if (hint.size !== stat2.size || this.normalizeHintMtimeMs(hint.mtimeMs) !== normalizedMtimeMs) {
1240
+ return void 0;
1241
+ }
1242
+ return hint;
1243
+ } catch {
1244
+ return void 0;
1245
+ }
1246
+ }
1247
+ rememberPathHint(filePath, hash, name) {
1248
+ try {
1249
+ const resolvedPath = this.getResolvedHintPath(filePath);
1250
+ const stat2 = fs4.statSync(resolvedPath);
1251
+ if (!stat2.isFile()) return;
1252
+ const entry = this.index.files[hash];
1253
+ const normalizedMtimeMs = this.normalizeHintMtimeMs(stat2.mtimeMs);
1254
+ if (!this.index.pathHints) {
1255
+ this.index.pathHints = {};
1256
+ }
1257
+ this.index.pathHints[this.getPathHintKey(resolvedPath)] = {
1258
+ path: resolvedPath,
1259
+ hash,
1260
+ name: name || entry?.name || path5.basename(resolvedPath),
1261
+ size: stat2.size,
1262
+ mtimeMs: normalizedMtimeMs,
1263
+ lastSeenAt: Date.now(),
1264
+ updatedAt: Date.now(),
1265
+ uploadedPlatforms: this.getUploadedPlatformsForHash(hash)
1266
+ };
1267
+ this.saveIndex();
1268
+ } catch {
1269
+ }
1270
+ }
1271
+ // ============================================================================
1272
+ // Search
1273
+ // ============================================================================
1274
+ search(query) {
1275
+ const lowerQuery = query.toLowerCase();
1276
+ return Object.values(this.index.files).filter(
1277
+ (entry) => entry.name.toLowerCase().includes(lowerQuery)
1278
+ );
1279
+ }
1280
+ list(options) {
1281
+ let entries = Object.values(this.index.files);
1282
+ if (options?.filter) {
1283
+ entries = entries.filter(
1284
+ (e) => this.getFileType(e.mimeType) === options.filter
1285
+ );
1286
+ }
1287
+ entries.sort((a, b) => b.createdAt - a.createdAt);
1288
+ if (options?.limit) {
1289
+ entries = entries.slice(0, options.limit);
1290
+ }
1291
+ return entries.map((e) => this.toFileInfo(e));
1292
+ }
1293
+ // ============================================================================
1294
+ // Cache Management
1295
+ // ============================================================================
1296
+ evictIfNeeded() {
1297
+ const entries = Object.entries(this.index.files);
1298
+ if (entries.length <= this.maxEntries) return;
1299
+ entries.sort((a, b) => a[1].createdAt - b[1].createdAt);
1300
+ const toEvict = entries.slice(0, entries.length - this.maxEntries);
1301
+ for (const [hash, entry] of toEvict) {
1302
+ this.deleteEntry(hash, entry);
1303
+ }
1304
+ }
1305
+ deleteEntry(hash, entry) {
1306
+ entry = entry || this.index.files[hash];
1307
+ if (!entry) return;
1308
+ const localPath = path5.join(this.dataDir, entry.localPath);
1309
+ if (fs4.existsSync(localPath)) {
1310
+ fs4.unlinkSync(localPath);
1311
+ }
1312
+ delete this.index.files[hash];
1313
+ if (this.index.pathHints) {
1314
+ for (const [hintPath, hint] of Object.entries(this.index.pathHints)) {
1315
+ if (hint.hash === hash) {
1316
+ delete this.index.pathHints[hintPath];
1317
+ }
1318
+ }
1319
+ }
1320
+ this.saveIndex();
1321
+ }
1322
+ clear() {
1323
+ for (const entry of Object.values(this.index.files)) {
1324
+ const localPath = path5.join(this.dataDir, entry.localPath);
1325
+ if (fs4.existsSync(localPath)) {
1326
+ fs4.unlinkSync(localPath);
1327
+ }
1328
+ }
1329
+ this.index = { version: CACHE_VERSION, files: {}, pathHints: {} };
1330
+ this.saveIndex();
1331
+ }
1332
+ // ============================================================================
1333
+ // Statistics
1334
+ // ============================================================================
1335
+ getStats() {
1336
+ const stats = {
1337
+ totalFiles: 0,
1338
+ totalSize: 0,
1339
+ byType: { image: 0, video: 0, document: 0 }
1340
+ };
1341
+ for (const entry of Object.values(this.index.files)) {
1342
+ stats.totalFiles++;
1343
+ stats.totalSize += entry.size;
1344
+ const type = this.getFileType(entry.mimeType);
1345
+ stats.byType[type]++;
1346
+ }
1347
+ return stats;
1348
+ }
1349
+ // ============================================================================
1350
+ // Helpers
1351
+ // ============================================================================
1352
+ getFileType(mimeType) {
1353
+ if (mimeType.startsWith("image/")) return "image";
1354
+ if (mimeType.startsWith("video/")) return "video";
1355
+ return "document";
1356
+ }
1357
+ toFileInfo(entry) {
1358
+ let status = "local";
1359
+ const platformStatuses = Object.values(entry.platforms).map((p) => p.status);
1360
+ if (platformStatuses.some((s) => s === "processing")) {
1361
+ status = "uploading";
1362
+ } else if (platformStatuses.some((s) => s === "active")) {
1363
+ status = "ready";
1364
+ } else if (platformStatuses.every((s) => s === "expired")) {
1365
+ status = "expired";
1366
+ }
1367
+ return {
1368
+ hash: entry.hash,
1369
+ name: entry.name,
1370
+ size: entry.size,
1371
+ type: this.getFileType(entry.mimeType),
1372
+ mimeType: entry.mimeType,
1373
+ createdAt: entry.createdAt,
1374
+ platforms: Object.keys(entry.platforms),
1375
+ status
1376
+ };
1377
+ }
1378
+ static getMimeType(fileName) {
1379
+ const ext = path5.extname(fileName).toLowerCase();
1380
+ return MIME_TYPES[ext] || "application/octet-stream";
1381
+ }
1382
+ static getFileTypeFromName(fileName) {
1383
+ const baseName = path5.basename(fileName);
1384
+ if (!baseName || baseName.startsWith(".")) {
1385
+ return void 0;
1386
+ }
1387
+ const mimeType = _FileCache.getMimeType(fileName);
1388
+ if (mimeType === "application/octet-stream") {
1389
+ return void 0;
1390
+ }
1391
+ if (mimeType.startsWith("image/")) return "image";
1392
+ if (mimeType.startsWith("video/")) return "video";
1393
+ return "document";
1394
+ }
1395
+ getPathHintKey(filePath) {
1396
+ return this.getResolvedHintPath(filePath);
1397
+ }
1398
+ getUploadedPlatformsForHash(hash) {
1399
+ const uploadedPlatforms = /* @__PURE__ */ new Set();
1400
+ for (const hint of Object.values(this.index.pathHints || {})) {
1401
+ if (hint.hash !== hash) continue;
1402
+ for (const platform of hint.uploadedPlatforms || []) {
1403
+ uploadedPlatforms.add(platform);
1404
+ }
1405
+ }
1406
+ return Array.from(uploadedPlatforms);
1407
+ }
1408
+ normalizeHintMtimeMs(value) {
1409
+ return Math.round(value);
1410
+ }
1411
+ getResolvedHintPath(filePath) {
1412
+ const resolvedPath = resolvePath(filePath);
1413
+ try {
1414
+ return fs4.realpathSync.native ? fs4.realpathSync.native(resolvedPath) : fs4.realpathSync(resolvedPath);
1415
+ } catch {
1416
+ return resolvedPath;
1417
+ }
1418
+ }
1419
+ };
1420
+
1421
+ // src/files/session-file-manager.ts
1422
+ import * as fs5 from "node:fs";
1423
+ import * as path6 from "node:path";
1424
+ var INITIAL_REFRESH_BACKOFF_MS = 6e4;
1425
+ var MAX_REFRESH_BACKOFF_MS = 60 * 60 * 1e3;
1426
+ var SessionFileManager = class {
1427
+ sessionId;
1428
+ sessionsDir;
1429
+ statePath;
1430
+ state;
1431
+ fileCache;
1432
+ adapters = /* @__PURE__ */ new Map();
1433
+ authFingerprint;
1434
+ constructor(sessionId, sessionsDir, fileCache, authFingerprint) {
1435
+ this.sessionId = sessionId;
1436
+ this.sessionsDir = sessionsDir;
1437
+ this.statePath = path6.join(this.sessionsDir, `${sessionId}-files.json`);
1438
+ this.fileCache = fileCache;
1439
+ this.authFingerprint = authFingerprint;
1440
+ this.state = this.loadState();
1441
+ this.ensureDirectories();
1442
+ }
1443
+ // ============================================================================
1444
+ // Directory Management
1445
+ // ============================================================================
1446
+ ensureDirectories() {
1447
+ if (!fs5.existsSync(this.sessionsDir)) {
1448
+ fs5.mkdirSync(this.sessionsDir, { recursive: true });
1449
+ }
1450
+ }
1451
+ // ============================================================================
1452
+ // State Management
1453
+ // ============================================================================
1454
+ loadState() {
1455
+ if (!fs5.existsSync(this.statePath)) {
1456
+ return {
1457
+ sessionId: this.sessionId,
1458
+ lastSyncedAt: 0,
1459
+ files: {}
1460
+ };
1461
+ }
1462
+ try {
1463
+ return JSON.parse(fs5.readFileSync(this.statePath, "utf-8"));
1464
+ } catch (err) {
1465
+ sessionLogger.error(" Failed to load state:", err);
1466
+ return {
1467
+ sessionId: this.sessionId,
1468
+ lastSyncedAt: 0,
1469
+ files: {}
1470
+ };
1471
+ }
1472
+ }
1473
+ saveState() {
1474
+ try {
1475
+ if (Object.keys(this.state.files).length === 0) {
1476
+ if (fs5.existsSync(this.statePath)) {
1477
+ fs5.unlinkSync(this.statePath);
1478
+ }
1479
+ return;
1480
+ }
1481
+ fs5.writeFileSync(this.statePath, JSON.stringify(this.state, null, 2));
1482
+ } catch (err) {
1483
+ sessionLogger.error(" Failed to save state:", err);
1484
+ }
1485
+ }
1486
+ // ============================================================================
1487
+ // Adapter Registration
1488
+ // ============================================================================
1489
+ registerAdapter(adapter) {
1490
+ this.adapters.set(adapter.platform, adapter);
1491
+ }
1492
+ getAdapter(platform) {
1493
+ return this.adapters.get(platform);
1494
+ }
1495
+ // ============================================================================
1496
+ // File Tracking
1497
+ // ============================================================================
1498
+ trackFile(fileId, hash, platform, status = "pending") {
1499
+ this.state.files[fileId] = {
1500
+ hash,
1501
+ platform,
1502
+ status
1503
+ };
1504
+ this.saveState();
1505
+ }
1506
+ updateFileStatus(fileId, status, progress, error) {
1507
+ const entry = this.state.files[fileId];
1508
+ if (!entry) return;
1509
+ entry.status = status;
1510
+ if (progress !== void 0) entry.progress = progress;
1511
+ if (error !== void 0) entry.error = error;
1512
+ this.saveState();
1513
+ }
1514
+ isRefreshCoolingDown(fileId) {
1515
+ const entry = this.state.files[fileId];
1516
+ return entry ? this.isRefreshCoolingDownForEntry(entry) : false;
1517
+ }
1518
+ getFileStatus(fileId) {
1519
+ return this.state.files[fileId];
1520
+ }
1521
+ getAllFiles() {
1522
+ return Object.entries(this.state.files).map(([fileId, entry]) => ({
1523
+ fileId,
1524
+ entry
1525
+ }));
1526
+ }
1527
+ getFilesByStatus(status) {
1528
+ return Object.entries(this.state.files).filter(([, entry]) => entry.status === status).map(([fileId, entry]) => ({ fileId, entry }));
1529
+ }
1530
+ // ============================================================================
1531
+ // Session Sync
1532
+ // ============================================================================
1533
+ /**
1534
+ * Sync file status with platform APIs
1535
+ * Called when session resumes
1536
+ */
1537
+ async syncWithPlatforms() {
1538
+ const result = {
1539
+ refreshed: 0,
1540
+ expired: 0,
1541
+ errors: 0,
1542
+ unchanged: 0
1543
+ };
1544
+ const filesByPlatform = /* @__PURE__ */ new Map();
1545
+ for (const [fileId, entry] of Object.entries(this.state.files)) {
1546
+ const list = filesByPlatform.get(entry.platform) || [];
1547
+ list.push({ fileId, entry });
1548
+ filesByPlatform.set(entry.platform, list);
1549
+ }
1550
+ for (const [platform, files] of Array.from(filesByPlatform.entries())) {
1551
+ const adapter = this.adapters.get(platform);
1552
+ if (!adapter) {
1553
+ sessionLogger.warn(`No adapter for platform: ${platform}`);
1554
+ continue;
1555
+ }
1556
+ for (const { fileId, entry } of files) {
1557
+ if (entry.status === "expired" && this.isRefreshCoolingDownForEntry(entry)) {
1558
+ result.unchanged++;
1559
+ continue;
1560
+ }
1561
+ try {
1562
+ const status = await adapter.getStatus(fileId);
1563
+ const syncResult = await this.handleStatusUpdate(
1564
+ fileId,
1565
+ entry,
1566
+ status,
1567
+ adapter
1568
+ );
1569
+ result[syncResult]++;
1570
+ } catch (err) {
1571
+ sessionLogger.error(`Failed to sync ${fileId}`, err);
1572
+ entry.status = "error";
1573
+ entry.error = err instanceof Error ? err.message : String(err);
1574
+ result.errors++;
1575
+ }
1576
+ }
1577
+ }
1578
+ this.state.lastSyncedAt = Date.now();
1579
+ this.saveState();
1580
+ sessionLogger.debug(`Sync complete: ${result.refreshed} refreshed, ${result.expired} expired, ${result.errors} errors, ${result.unchanged} unchanged`);
1581
+ return result;
1582
+ }
1583
+ async handleStatusUpdate(fileId, entry, status, adapter) {
1584
+ this.fileCache.updatePlatformStatus(entry.hash, entry.platform, status.status);
1585
+ switch (status.status) {
1586
+ case "active":
1587
+ if (entry.status !== "ready") {
1588
+ entry.status = "ready";
1589
+ this.clearRefreshBackoff(entry);
1590
+ return "unchanged";
1591
+ }
1592
+ this.clearRefreshBackoff(entry);
1593
+ return "unchanged";
1594
+ case "processing":
1595
+ entry.status = "uploading";
1596
+ this.clearRefreshBackoff(entry);
1597
+ return "unchanged";
1598
+ case "expired":
1599
+ case "not_found":
1600
+ if (this.isRefreshCoolingDownForEntry(entry)) {
1601
+ entry.status = "expired";
1602
+ return "unchanged";
1603
+ }
1604
+ const refreshed = await this.refreshFile(fileId, entry, adapter);
1605
+ if (refreshed.success) {
1606
+ return "refreshed";
1607
+ }
1608
+ return refreshed.coolingDown ? "unchanged" : "expired";
1609
+ case "error":
1610
+ entry.status = "error";
1611
+ entry.error = status.error || "Unknown error";
1612
+ return "errors";
1613
+ default:
1614
+ return "unchanged";
1615
+ }
1616
+ }
1617
+ /**
1618
+ * Refresh an expired file by re-uploading from local cache
1619
+ */
1620
+ async refreshFile(fileId, entry, adapter) {
1621
+ entry = entry || this.state.files[fileId];
1622
+ if (!entry) return { success: false };
1623
+ if (this.isRefreshCoolingDownForEntry(entry)) {
1624
+ return { success: false, coolingDown: true };
1625
+ }
1626
+ const localPath = this.fileCache.getLocalPath(entry.hash);
1627
+ if (!localPath || !fs5.existsSync(localPath)) {
1628
+ sessionLogger.warn(`Local file not found for ${fileId}`);
1629
+ entry.status = "expired";
1630
+ entry.error = "Local file missing";
1631
+ this.recordRefreshAttempt(entry);
1632
+ this.scheduleNextRefresh(entry);
1633
+ this.saveState();
1634
+ return { success: false };
1635
+ }
1636
+ adapter = adapter || this.adapters.get(entry.platform);
1637
+ if (!adapter) {
1638
+ sessionLogger.warn(`No adapter for ${entry.platform}`);
1639
+ return { success: false };
1640
+ }
1641
+ const cacheEntry = this.fileCache.getByHash(entry.hash);
1642
+ if (!cacheEntry) {
1643
+ sessionLogger.warn(`Cache entry not found for ${fileId}`);
1644
+ entry.status = "expired";
1645
+ entry.error = "Local cache entry missing";
1646
+ this.recordRefreshAttempt(entry);
1647
+ this.scheduleNextRefresh(entry);
1648
+ this.saveState();
1649
+ return { success: false };
1650
+ }
1651
+ try {
1652
+ sessionLogger.debug(`Refreshing file ${fileId} from local cache...`);
1653
+ this.recordRefreshAttempt(entry);
1654
+ entry.status = "uploading";
1655
+ this.saveState();
1656
+ const result = await adapter.upload(localPath, this.buildRefreshUploadOptions(cacheEntry));
1657
+ const refreshedStatus = result.status === "active" ? "ready" : "uploading";
1658
+ delete this.state.files[fileId];
1659
+ this.trackFile(result.fileId, entry.hash, entry.platform, refreshedStatus);
1660
+ this.fileCache.addPlatformRecord(entry.hash, entry.platform, {
1661
+ fileId: result.fileId,
1662
+ uploadedAt: Date.now(),
1663
+ expiresAt: result.expiresAt,
1664
+ status: result.status === "active" ? "active" : "processing",
1665
+ lastCheckedAt: Date.now(),
1666
+ authFingerprint: this.authFingerprint
1667
+ });
1668
+ const refreshedEntry = this.state.files[result.fileId];
1669
+ if (refreshedEntry) {
1670
+ this.clearRefreshBackoff(refreshedEntry);
1671
+ this.saveState();
1672
+ }
1673
+ sessionLogger.debug(`File refreshed: ${fileId} -> ${result.fileId}`);
1674
+ return { success: true, fileId: result.fileId };
1675
+ } catch (err) {
1676
+ sessionLogger.error(`Failed to refresh file ${fileId}`, err);
1677
+ entry.status = "expired";
1678
+ entry.error = err instanceof Error ? err.message : String(err);
1679
+ this.scheduleNextRefresh(entry);
1680
+ this.saveState();
1681
+ return { success: false };
1682
+ }
1683
+ }
1684
+ buildRefreshUploadOptions(cacheEntry) {
1685
+ return {
1686
+ sourceName: cacheEntry.name,
1687
+ mimeType: cacheEntry.mimeType,
1688
+ purpose: this.inferPurposeFromMimeType(cacheEntry.mimeType)
1689
+ };
1690
+ }
1691
+ inferPurposeFromMimeType(mimeType) {
1692
+ if (mimeType.startsWith("video/")) {
1693
+ return "video";
1694
+ }
1695
+ if (mimeType.startsWith("image/")) {
1696
+ return "image";
1697
+ }
1698
+ return "file-extract";
1699
+ }
1700
+ isRefreshCoolingDownForEntry(entry) {
1701
+ return typeof entry.nextRefreshAt === "number" && Date.now() < entry.nextRefreshAt;
1702
+ }
1703
+ recordRefreshAttempt(entry) {
1704
+ entry.lastRefreshAttemptAt = Date.now();
1705
+ entry.refreshAttempts = (entry.refreshAttempts || 0) + 1;
1706
+ delete entry.nextRefreshAt;
1707
+ }
1708
+ scheduleNextRefresh(entry) {
1709
+ const attempts = entry.refreshAttempts || 1;
1710
+ const backoffMs = Math.min(
1711
+ INITIAL_REFRESH_BACKOFF_MS * 2 ** Math.max(0, attempts - 1),
1712
+ MAX_REFRESH_BACKOFF_MS
1713
+ );
1714
+ entry.nextRefreshAt = Date.now() + backoffMs;
1715
+ }
1716
+ clearRefreshBackoff(entry) {
1717
+ delete entry.refreshAttempts;
1718
+ delete entry.lastRefreshAttemptAt;
1719
+ delete entry.nextRefreshAt;
1720
+ }
1721
+ // ============================================================================
1722
+ // Batch Operations
1723
+ // ============================================================================
1724
+ /**
1725
+ * Refresh all expired files
1726
+ */
1727
+ async refreshAllExpired() {
1728
+ const expired = this.getFilesByStatus("expired");
1729
+ let success = 0;
1730
+ let failed = 0;
1731
+ for (const { fileId, entry } of expired) {
1732
+ const refreshed = await this.refreshFile(fileId, entry);
1733
+ if (refreshed.success) success++;
1734
+ else failed++;
1735
+ }
1736
+ return { success, failed };
1737
+ }
1738
+ /**
1739
+ * Clean up session state
1740
+ */
1741
+ cleanup() {
1742
+ const maxAge = 7 * 24 * 60 * 60 * 1e3;
1743
+ const now = Date.now();
1744
+ for (const [fileId, entry] of Object.entries(this.state.files)) {
1745
+ const cacheEntry = this.fileCache.getByHash(entry.hash);
1746
+ if ((entry.status === "error" || entry.status === "expired") && cacheEntry && now - cacheEntry.createdAt > maxAge) {
1747
+ delete this.state.files[fileId];
1748
+ }
1749
+ }
1750
+ this.saveState();
1751
+ }
1752
+ // ============================================================================
1753
+ // Statistics
1754
+ // ============================================================================
1755
+ getStats() {
1756
+ const stats = {
1757
+ total: 0,
1758
+ byStatus: {
1759
+ pending: 0,
1760
+ uploading: 0,
1761
+ ready: 0,
1762
+ expired: 0,
1763
+ error: 0
1764
+ },
1765
+ byPlatform: {}
1766
+ };
1767
+ for (const entry of Object.values(this.state.files)) {
1768
+ stats.total++;
1769
+ stats.byStatus[entry.status]++;
1770
+ stats.byPlatform[entry.platform] = (stats.byPlatform[entry.platform] || 0) + 1;
1771
+ }
1772
+ return stats;
1773
+ }
1774
+ // ============================================================================
1775
+ // Static Utilities
1776
+ // ============================================================================
1777
+ static cleanupOldSessions(sessionsDir, maxAge = 30 * 24 * 60 * 60 * 1e3) {
1778
+ if (!fs5.existsSync(sessionsDir)) return;
1779
+ const now = Date.now();
1780
+ const files = fs5.readdirSync(sessionsDir);
1781
+ for (const file of files) {
1782
+ if (!file.endsWith(".json")) continue;
1783
+ const filePath = path6.join(sessionsDir, file);
1784
+ const stat2 = fs5.statSync(filePath);
1785
+ if (now - stat2.mtime.getTime() > maxAge) {
1786
+ fs5.unlinkSync(filePath);
1787
+ sessionLogger.debug(`Cleaned up old session: ${file}`);
1788
+ }
1789
+ }
1790
+ }
1791
+ };
1792
+
1793
+ // src/files/ffmpeg-processor.ts
1794
+ import * as fs6 from "node:fs";
1795
+ import * as path7 from "node:path";
1796
+ import { spawn } from "node:child_process";
1797
+ var FFmpegProcessor = class {
1798
+ ffmpegPath = "ffmpeg";
1799
+ ffprobePath = "ffprobe";
1800
+ constructor(ffmpegPath, ffprobePath) {
1801
+ if (ffmpegPath) this.ffmpegPath = ffmpegPath;
1802
+ if (ffprobePath) this.ffprobePath = ffprobePath;
1803
+ }
1804
+ // ============================================================================
1805
+ // Detection
1806
+ // ============================================================================
1807
+ async checkAvailability() {
1808
+ return new Promise((resolve2) => {
1809
+ const proc = spawn(this.ffmpegPath, ["-version"], { windowsHide: true });
1810
+ proc.on("error", () => resolve2(false));
1811
+ proc.on("exit", (code) => resolve2(code === 0));
1812
+ });
1813
+ }
1814
+ // ============================================================================
1815
+ // Video Analysis
1816
+ // ============================================================================
1817
+ async analyzeVideo(videoPath) {
1818
+ return new Promise((resolve2, reject) => {
1819
+ const args = [
1820
+ "-v",
1821
+ "error",
1822
+ "-show_entries",
1823
+ "format=duration,size,bit_rate",
1824
+ "-show_entries",
1825
+ "stream=width,height,r_frame_rate,pix_fmt",
1826
+ "-of",
1827
+ "json",
1828
+ videoPath
1829
+ ];
1830
+ const proc = spawn(this.ffprobePath, args, { windowsHide: true });
1831
+ let stdout = "";
1832
+ let stderr = "";
1833
+ proc.stdout.on("data", (data) => stdout += data);
1834
+ proc.stderr.on("data", (data) => stderr += data);
1835
+ proc.on("close", (code) => {
1836
+ if (code !== 0) {
1837
+ reject(
1838
+ new FileManagerError(
1839
+ "FFMPEG_ERROR" /* FFMPEG_ERROR */,
1840
+ `ffprobe failed: ${stderr}`
1841
+ )
1842
+ );
1843
+ return;
1844
+ }
1845
+ try {
1846
+ const info = this.parseProbeOutput(stdout, videoPath);
1847
+ resolve2(info);
1848
+ } catch (err) {
1849
+ reject(err);
1850
+ }
1851
+ });
1852
+ });
1853
+ }
1854
+ parseProbeOutput(output, videoPath) {
1855
+ const data = JSON.parse(output);
1856
+ const format = data.format || {};
1857
+ const streams = data.streams || [];
1858
+ const videoStream = streams.find((stream) => {
1859
+ if (!stream || typeof stream !== "object") return false;
1860
+ const candidate = stream;
1861
+ return Boolean(candidate.width && candidate.height);
1862
+ });
1863
+ if (!videoStream) {
1864
+ throw new FileManagerError(
1865
+ "FFMPEG_ERROR" /* FFMPEG_ERROR */,
1866
+ "No video stream found"
1867
+ );
1868
+ }
1869
+ return {
1870
+ duration: parseFloat(format.duration) || 0,
1871
+ width: videoStream.width,
1872
+ height: videoStream.height,
1873
+ fps: this.parseFrameRate(videoStream.r_frame_rate ?? "") || 30,
1874
+ bitrate: parseInt(format.bit_rate) || 0,
1875
+ format: format.format_name || "unknown",
1876
+ size: parseInt(format.size) || 0
1877
+ };
1878
+ }
1879
+ // ============================================================================
1880
+ // Video Preprocessing
1881
+ // ============================================================================
1882
+ async preprocessVideo(inputPath, outputDir, strategy, options = {}, onProgress) {
1883
+ const opts = { ...DEFAULT_VIDEO_OPTIONS, ...options };
1884
+ const info = await this.analyzeVideo(inputPath);
1885
+ switch (strategy) {
1886
+ case "compress":
1887
+ return this.compressVideo(inputPath, outputDir, info, opts, onProgress);
1888
+ case "keyframes":
1889
+ return this.extractKeyframes(inputPath, outputDir, info, opts, onProgress);
1890
+ default:
1891
+ throw new FileManagerError(
1892
+ "INVALID_FILE_TYPE" /* INVALID_FILE_TYPE */,
1893
+ `Unknown strategy: ${strategy}`
1894
+ );
1895
+ }
1896
+ }
1897
+ async compressVideo(inputPath, outputDir, info, opts, onProgress) {
1898
+ const outputName = `compressed_${Date.now()}.mp4`;
1899
+ const outputPath = path7.join(outputDir, outputName);
1900
+ const adaptiveParams = this.calculateAdaptiveParams(info.duration, opts);
1901
+ const args = [
1902
+ "-i",
1903
+ inputPath,
1904
+ "-c:v",
1905
+ "libx264",
1906
+ "-preset",
1907
+ adaptiveParams.preset,
1908
+ "-crf",
1909
+ String(adaptiveParams.crf),
1910
+ "-vf",
1911
+ `scale=-2:${adaptiveParams.maxResolution}`,
1912
+ "-r",
1913
+ String(adaptiveParams.fps),
1914
+ "-c:a",
1915
+ "aac",
1916
+ "-b:a",
1917
+ "96k",
1918
+ // Lower audio bitrate for space
1919
+ "-movflags",
1920
+ "+faststart",
1921
+ "-y",
1922
+ outputPath
1923
+ ];
1924
+ await this.runWithProgress(args, (progress) => {
1925
+ const percent = this.getVideoProgressPercent(progress, info.duration);
1926
+ if (percent !== null) {
1927
+ onProgress?.(percent);
1928
+ }
1929
+ });
1930
+ const outputStat = fs6.statSync(outputPath);
1931
+ return {
1932
+ type: "video",
1933
+ output: outputPath,
1934
+ metadata: {
1935
+ originalDuration: info.duration,
1936
+ originalSize: info.size,
1937
+ outputSize: outputStat.size,
1938
+ compressionRatio: info.size / outputStat.size
1939
+ }
1940
+ };
1941
+ }
1942
+ /**
1943
+ * Calculate adaptive compression parameters based on video duration
1944
+ * Goal: Maximize AI understanding while keeping file under 100MB
1945
+ */
1946
+ calculateAdaptiveParams(duration, _opts) {
1947
+ if (duration < 30) {
1948
+ return { preset: "medium", crf: 23, maxResolution: 720, fps: 10 };
1949
+ } else if (duration < 120) {
1950
+ return { preset: "fast", crf: 26, maxResolution: 720, fps: 10 };
1951
+ } else if (duration < 300) {
1952
+ return { preset: "fast", crf: 26, maxResolution: 720, fps: 10 };
1953
+ } else if (duration < 600) {
1954
+ return { preset: "slow", crf: 26, maxResolution: 720, fps: 10 };
1955
+ } else {
1956
+ return { preset: "slow", crf: 26, maxResolution: 480, fps: 8 };
1957
+ }
1958
+ }
1959
+ async extractKeyframes(inputPath, outputDir, info, opts, onProgress) {
1960
+ const interval = Math.floor(info.duration / opts.keyframeCount);
1961
+ const framesDir = path7.join(outputDir, `keyframes_${Date.now()}`);
1962
+ fs6.mkdirSync(framesDir, { recursive: true });
1963
+ const outputPattern = path7.join(framesDir, "frame_%03d.jpg");
1964
+ const args = [
1965
+ "-i",
1966
+ inputPath,
1967
+ "-vf",
1968
+ `select='gt(scene,0.3)',scale=480:-1:flags=lanczos`,
1969
+ "-vsync",
1970
+ "vfr",
1971
+ "-q:v",
1972
+ "2",
1973
+ outputPattern
1974
+ ];
1975
+ await this.runWithProgress(args, (progress) => {
1976
+ const percent = this.getVideoProgressPercent(progress, info.duration);
1977
+ if (percent !== null) {
1978
+ onProgress?.(percent);
1979
+ }
1980
+ });
1981
+ let frames = fs6.readdirSync(framesDir).filter((f) => f.endsWith(".jpg")).sort().map((f) => path7.join(framesDir, f));
1982
+ if (frames.length < opts.keyframeCount / 2) {
1983
+ fs6.rmSync(framesDir, { recursive: true, force: true });
1984
+ fs6.mkdirSync(framesDir, { recursive: true });
1985
+ const uniformArgs = [
1986
+ "-i",
1987
+ inputPath,
1988
+ "-vf",
1989
+ `fps=1/${interval},scale=480:-1:flags=lanczos`,
1990
+ "-q:v",
1991
+ "2",
1992
+ outputPattern
1993
+ ];
1994
+ await this.runWithProgress(uniformArgs, (progress) => {
1995
+ const percent = this.getVideoProgressPercent(progress, info.duration);
1996
+ if (percent !== null) {
1997
+ onProgress?.(percent);
1998
+ }
1999
+ });
2000
+ frames = fs6.readdirSync(framesDir).filter((f) => f.endsWith(".jpg")).sort().map((f) => path7.join(framesDir, f));
2001
+ }
2002
+ const totalOutputSize = frames.reduce(
2003
+ (sum, f) => sum + fs6.statSync(f).size,
2004
+ 0
2005
+ );
2006
+ return {
2007
+ type: "keyframes",
2008
+ output: frames,
2009
+ metadata: {
2010
+ originalDuration: info.duration,
2011
+ originalSize: info.size,
2012
+ outputSize: totalOutputSize,
2013
+ compressionRatio: info.size / totalOutputSize
2014
+ }
2015
+ };
2016
+ }
2017
+ // ============================================================================
2018
+ // Image Optimization
2019
+ // ============================================================================
2020
+ async optimizeImage(inputPath, outputDir, options = {}) {
2021
+ const opts = { ...DEFAULT_PIC_OPTIONS, ...options };
2022
+ const ext = opts.format === "webp" ? ".webp" : ".jpg";
2023
+ const outputName = `optimized_${Date.now()}${ext}`;
2024
+ const outputPath = path7.join(outputDir, outputName);
2025
+ const args = [
2026
+ "-i",
2027
+ inputPath,
2028
+ "-vf",
2029
+ `scale='min(${opts.maxWidth},iw)':-1:flags=lanczos`,
2030
+ "-q:v",
2031
+ String(opts.quality),
2032
+ "-y",
2033
+ outputPath
2034
+ ];
2035
+ await this.runFFmpeg(args);
2036
+ return outputPath;
2037
+ }
2038
+ // ============================================================================
2039
+ // FFmpeg Execution
2040
+ // ============================================================================
2041
+ runFFmpeg(args) {
2042
+ return new Promise((resolve2, reject) => {
2043
+ const proc = spawn(this.ffmpegPath, args, { windowsHide: true });
2044
+ let stderr = "";
2045
+ proc.stderr.on("data", (data) => {
2046
+ stderr += data;
2047
+ });
2048
+ proc.on("close", (code) => {
2049
+ if (code !== 0) {
2050
+ reject(
2051
+ new FileManagerError(
2052
+ "FFMPEG_ERROR" /* FFMPEG_ERROR */,
2053
+ `FFmpeg failed (code ${code}): ${stderr}`
2054
+ )
2055
+ );
2056
+ } else {
2057
+ resolve2();
2058
+ }
2059
+ });
2060
+ proc.on("error", (err) => {
2061
+ reject(
2062
+ new FileManagerError(
2063
+ "FFMPEG_NOT_FOUND" /* FFMPEG_NOT_FOUND */,
2064
+ `FFmpeg not found: ${err.message}`
2065
+ )
2066
+ );
2067
+ });
2068
+ });
2069
+ }
2070
+ // ============================================================================
2071
+ // Progress Monitoring (for future use)
2072
+ // ============================================================================
2073
+ async runWithProgress(args, onProgress) {
2074
+ return new Promise((resolve2, reject) => {
2075
+ const progressArgs = [
2076
+ ...args,
2077
+ "-progress",
2078
+ "pipe:1"
2079
+ ];
2080
+ const proc = spawn(this.ffmpegPath, progressArgs, { windowsHide: true });
2081
+ let stderr = "";
2082
+ let progressData = "";
2083
+ proc.stdout.on("data", (data) => {
2084
+ progressData += data;
2085
+ const lines = progressData.split("\n");
2086
+ progressData = lines.pop() || "";
2087
+ const progress = this.parseProgress(lines);
2088
+ if (progress && onProgress) {
2089
+ onProgress(progress);
2090
+ }
2091
+ });
2092
+ proc.stderr.on("data", (data) => {
2093
+ stderr += data;
2094
+ });
2095
+ proc.on("close", (code) => {
2096
+ if (code !== 0) {
2097
+ reject(
2098
+ new FileManagerError(
2099
+ "FFMPEG_ERROR" /* FFMPEG_ERROR */,
2100
+ `FFmpeg failed: ${stderr}`
2101
+ )
2102
+ );
2103
+ } else {
2104
+ resolve2();
2105
+ }
2106
+ });
2107
+ });
2108
+ }
2109
+ parseFrameRate(rFrameRate) {
2110
+ const parts = rFrameRate.split("/");
2111
+ if (parts.length === 2) {
2112
+ const numerator = parseInt(parts[0], 10);
2113
+ const denominator = parseInt(parts[1], 10);
2114
+ if (denominator !== 0) {
2115
+ return numerator / denominator;
2116
+ }
2117
+ }
2118
+ return parseFloat(rFrameRate) || 30;
2119
+ }
2120
+ parseProgress(lines) {
2121
+ const progress = {};
2122
+ for (const line of lines) {
2123
+ const [key, value] = line.split("=");
2124
+ switch (key) {
2125
+ case "frame":
2126
+ progress.frame = parseInt(value);
2127
+ break;
2128
+ case "fps":
2129
+ progress.fps = parseFloat(value);
2130
+ break;
2131
+ case "bitrate":
2132
+ progress.bitrate = value;
2133
+ break;
2134
+ case "total_size":
2135
+ progress.size = value;
2136
+ break;
2137
+ case "out_time":
2138
+ progress.time = value;
2139
+ break;
2140
+ case "speed":
2141
+ progress.speed = value;
2142
+ break;
2143
+ }
2144
+ }
2145
+ return Object.keys(progress).length > 0 ? progress : null;
2146
+ }
2147
+ getVideoProgressPercent(progress, durationSeconds) {
2148
+ if (!progress.time || durationSeconds <= 0) {
2149
+ return null;
2150
+ }
2151
+ const processedSeconds = this.parseTimestamp(progress.time);
2152
+ if (!Number.isFinite(processedSeconds)) {
2153
+ return null;
2154
+ }
2155
+ return Math.max(0, Math.min(100, Math.round(processedSeconds / durationSeconds * 100)));
2156
+ }
2157
+ parseTimestamp(value) {
2158
+ const parts = value.trim().split(":");
2159
+ if (parts.length !== 3) {
2160
+ return Number.NaN;
2161
+ }
2162
+ const [hours, minutes, seconds] = parts.map((part) => Number.parseFloat(part));
2163
+ if ([hours, minutes, seconds].some((part) => !Number.isFinite(part))) {
2164
+ return Number.NaN;
2165
+ }
2166
+ return hours * 3600 + minutes * 60 + seconds;
2167
+ }
2168
+ // ============================================================================
2169
+ // Strategy Selection
2170
+ // ============================================================================
2171
+ /**
2172
+ * Smart strategy selection based on video length and content
2173
+ * Goal: Maximize AI understanding while managing file size
2174
+ *
2175
+ * Note: Kimi supports native video upload, so we use compress for all videos
2176
+ * and adjust compression parameters based on length. Keyframes strategy is
2177
+ * reserved for platforms that don't support video.
2178
+ */
2179
+ static selectStrategy(videoInfo, targetSizeMB = 50) {
2180
+ const duration = videoInfo.duration;
2181
+ const size = videoInfo.size;
2182
+ return "compress";
2183
+ }
2184
+ /**
2185
+ * Calculate optimal keyframe count based on video duration
2186
+ * Ensures AI sees enough frames to understand the full content
2187
+ */
2188
+ static calculateKeyframeCount(duration) {
2189
+ const targetCount = Math.floor(duration / 2);
2190
+ return Math.max(10, Math.min(100, targetCount));
2191
+ }
2192
+ };
2193
+
2194
+ // src/files/file-manager.ts
2195
+ var DIRECTORY_LISTING_TTL_MS = 1500;
2196
+ var FileManager = class {
2197
+ constructor(options) {
2198
+ this.options = options;
2199
+ const baseDir = options.baseDir || path8.join(process.env.HOME || ".", ".pie", "files");
2200
+ const sessionsDir = options.sessionsDir || path8.join(process.env.HOME || ".", ".pie", "sessions");
2201
+ this.fileCache = new FileCache(baseDir);
2202
+ this.authFingerprint = options.apiKey ? this.buildAuthFingerprint(options.apiKey) : void 0;
2203
+ this.sessionManager = new SessionFileManager(
2204
+ options.sessionId,
2205
+ sessionsDir,
2206
+ this.fileCache,
2207
+ this.authFingerprint
2208
+ );
2209
+ this.ffmpeg = new FFmpegProcessor(options.ffmpegPath);
2210
+ this.platform = normalizeFileManagerPlatform(options.platform);
2211
+ this.tempDir = path8.join(baseDir, "temp");
2212
+ this.ensureDirectories();
2213
+ }
2214
+ options;
2215
+ fileCache;
2216
+ sessionManager;
2217
+ ffmpeg;
2218
+ platform;
2219
+ tempDir;
2220
+ directoryListingCache = /* @__PURE__ */ new Map();
2221
+ authFingerprint;
2222
+ ensureDirectories() {
2223
+ if (!fs7.existsSync(this.tempDir)) {
2224
+ fs7.mkdirSync(this.tempDir, { recursive: true });
2225
+ }
2226
+ }
2227
+ // ============================================================================
2228
+ // Adapter Registration
2229
+ // ============================================================================
2230
+ registerAdapter(adapter) {
2231
+ this.sessionManager.registerAdapter(adapter);
2232
+ }
2233
+ getPlatformName() {
2234
+ return this.platform;
2235
+ }
2236
+ /** Whether the active platform has a registered upload adapter. */
2237
+ hasAdapter() {
2238
+ return this.sessionManager.getAdapter(this.platform) !== void 0;
2239
+ }
2240
+ getPlatformDisplayName() {
2241
+ return getProviderDisplayName(this.platform);
2242
+ }
2243
+ getAdapter() {
2244
+ const adapter = this.sessionManager.getAdapter(this.platform);
2245
+ if (!adapter) {
2246
+ throw new FileManagerError(
2247
+ "PLATFORM_NOT_SUPPORTED" /* PLATFORM_NOT_SUPPORTED */,
2248
+ `No adapter registered for platform: ${this.platform}`
2249
+ );
2250
+ }
2251
+ return adapter;
2252
+ }
2253
+ // ============================================================================
2254
+ // Generic Upload
2255
+ // ============================================================================
2256
+ async stageLocal(filePath, options = {}) {
2257
+ const resolvedPath = resolvePath(filePath);
2258
+ const sourceName = options.sourceName || path8.basename(resolvedPath);
2259
+ if (!fs7.existsSync(resolvedPath)) {
2260
+ throw new FileManagerError(
2261
+ "LOCAL_FILE_MISSING" /* LOCAL_FILE_MISSING */,
2262
+ `File not found: ${filePath}`
2263
+ );
2264
+ }
2265
+ const hash = await this.fileCache.computeHash(resolvedPath);
2266
+ const cached = this.fileCache.getByHash(hash);
2267
+ const mimeType = FileCache.getMimeType(resolvedPath);
2268
+ if (!cached) {
2269
+ await this.fileCache.storeFile(resolvedPath, sourceName, mimeType);
2270
+ }
2271
+ this.fileCache.refreshImageMimeType(hash);
2272
+ this.fileCache.rememberPathHint(resolvedPath, hash, sourceName);
2273
+ this.invalidateDirectoryListingCacheForPath(resolvedPath);
2274
+ const entry = this.fileCache.getByHash(hash);
2275
+ const size = entry?.size ?? fs7.statSync(resolvedPath).size;
2276
+ return {
2277
+ success: true,
2278
+ hash,
2279
+ fileId: `local:${hash}`,
2280
+ name: sourceName,
2281
+ size,
2282
+ type: this.getFileType(mimeType),
2283
+ status: "ready",
2284
+ platform: "local"
2285
+ };
2286
+ }
2287
+ async upload(filePath, options = {}) {
2288
+ const resolvedPath = resolvePath(filePath);
2289
+ const sourceName = options.sourceName || path8.basename(resolvedPath);
2290
+ if (!fs7.existsSync(resolvedPath)) {
2291
+ throw new FileManagerError(
2292
+ "LOCAL_FILE_MISSING" /* LOCAL_FILE_MISSING */,
2293
+ `File not found: ${filePath}`
2294
+ );
2295
+ }
2296
+ const hash = await this.fileCache.computeHash(resolvedPath);
2297
+ const cached = this.fileCache.getByHash(hash);
2298
+ const platform = options.platform || this.platform;
2299
+ this.fileCache.rememberPathHint(resolvedPath, hash, sourceName);
2300
+ if (cached?.platforms[platform] && this.canReusePlatformRecord(cached.platforms[platform])) {
2301
+ const record = cached.platforms[platform];
2302
+ this.sessionManager.trackFile(
2303
+ record.fileId,
2304
+ hash,
2305
+ platform,
2306
+ record.status === "active" ? "ready" : "uploading"
2307
+ );
2308
+ return {
2309
+ success: true,
2310
+ hash,
2311
+ fileId: record.fileId,
2312
+ name: sourceName,
2313
+ size: cached.size,
2314
+ type: this.getFileType(cached.mimeType),
2315
+ status: record.status === "active" ? "ready" : "processing",
2316
+ platform,
2317
+ expiresAt: record.expiresAt
2318
+ };
2319
+ }
2320
+ const mimeType = FileCache.getMimeType(resolvedPath);
2321
+ const { localPath } = await this.fileCache.storeFile(
2322
+ resolvedPath,
2323
+ sourceName,
2324
+ mimeType
2325
+ );
2326
+ const adapter = this.getAdapter();
2327
+ if (options.onProgress) {
2328
+ options.onProgress(0, "uploading");
2329
+ }
2330
+ const uploadOptions = { ...options };
2331
+ if (!uploadOptions.purpose || uploadOptions.purpose === "auto") {
2332
+ uploadOptions.purpose = this.detectPurpose(resolvedPath);
2333
+ }
2334
+ const response = await adapter.upload(localPath, uploadOptions);
2335
+ const sessionStatus = response.status === "active" ? "ready" : "uploading";
2336
+ this.sessionManager.trackFile(response.fileId, hash, platform, sessionStatus);
2337
+ this.fileCache.addPlatformRecord(hash, platform, {
2338
+ fileId: response.fileId,
2339
+ uploadedAt: Date.now(),
2340
+ expiresAt: response.expiresAt,
2341
+ status: response.status === "active" ? "active" : "processing",
2342
+ lastCheckedAt: Date.now(),
2343
+ authFingerprint: this.authFingerprint
2344
+ });
2345
+ this.invalidateDirectoryListingCacheForPath(resolvedPath);
2346
+ if (options.onProgress) {
2347
+ if (response.status === "active") {
2348
+ options.onProgress(100, "complete");
2349
+ } else {
2350
+ options.onProgress(95, "processing");
2351
+ }
2352
+ }
2353
+ return {
2354
+ success: true,
2355
+ hash,
2356
+ fileId: response.fileId,
2357
+ name: sourceName,
2358
+ size: response.size,
2359
+ type: this.getFileType(mimeType),
2360
+ // Use original file's MIME type
2361
+ status: response.status === "active" ? "ready" : "processing",
2362
+ platform,
2363
+ expiresAt: response.expiresAt
2364
+ };
2365
+ }
2366
+ // ============================================================================
2367
+ // Image Upload with Optimization
2368
+ // ============================================================================
2369
+ async uploadPic(filePath, options = {}) {
2370
+ const resolvedPath = resolvePath(filePath);
2371
+ if (!fs7.existsSync(resolvedPath)) {
2372
+ throw new FileManagerError(
2373
+ "LOCAL_FILE_MISSING" /* LOCAL_FILE_MISSING */,
2374
+ `File not found: ${filePath}`
2375
+ );
2376
+ }
2377
+ const cachedResult = await this.tryReuseCachedSourceUpload(
2378
+ resolvedPath,
2379
+ options.sourceName || path8.basename(resolvedPath),
2380
+ options.platform || this.platform
2381
+ );
2382
+ if (cachedResult) {
2383
+ return cachedResult;
2384
+ }
2385
+ if (options.onProgress) {
2386
+ options.onProgress(0, "preprocessing");
2387
+ }
2388
+ const optimizedPath = await this.ffmpeg.optimizeImage(
2389
+ resolvedPath,
2390
+ this.tempDir,
2391
+ options.optimize
2392
+ );
2393
+ const result = await this.upload(optimizedPath, {
2394
+ ...options,
2395
+ purpose: "image",
2396
+ sourceName: path8.basename(resolvedPath)
2397
+ });
2398
+ this.fileCache.rememberPathHint(resolvedPath, result.hash, path8.basename(resolvedPath));
2399
+ this.invalidateDirectoryListingCacheForPath(resolvedPath);
2400
+ try {
2401
+ fs7.unlinkSync(optimizedPath);
2402
+ } catch {
2403
+ }
2404
+ return result;
2405
+ }
2406
+ // ============================================================================
2407
+ // Video Upload with Preprocessing
2408
+ // ============================================================================
2409
+ async uploadVideo(filePath, options = {}) {
2410
+ const resolvedPath = resolvePath(filePath);
2411
+ if (!fs7.existsSync(resolvedPath)) {
2412
+ throw new FileManagerError(
2413
+ "LOCAL_FILE_MISSING" /* LOCAL_FILE_MISSING */,
2414
+ `File not found: ${filePath}`
2415
+ );
2416
+ }
2417
+ const cachedResult = await this.tryReuseCachedSourceUpload(
2418
+ resolvedPath,
2419
+ options.sourceName || path8.basename(resolvedPath),
2420
+ options.platform || this.platform
2421
+ );
2422
+ if (cachedResult) {
2423
+ return cachedResult;
2424
+ }
2425
+ const ffmpegAvailable = await this.ffmpeg.checkAvailability();
2426
+ if (!ffmpegAvailable) {
2427
+ throw new FileManagerError(
2428
+ "FFMPEG_NOT_FOUND" /* FFMPEG_NOT_FOUND */,
2429
+ "FFmpeg not found. Please install FFmpeg to process videos."
2430
+ );
2431
+ }
2432
+ if (options.onProgress) {
2433
+ options.onProgress(0, "analyzing");
2434
+ }
2435
+ const videoInfo = await this.ffmpeg.analyzeVideo(resolvedPath);
2436
+ let strategy = options.strategy || "auto";
2437
+ if (strategy === "auto") {
2438
+ strategy = FFmpegProcessor.selectStrategy(videoInfo, options.optimize?.targetSizeMB);
2439
+ }
2440
+ if (strategy === "keyframes" && !options.optimize?.keyframeCount) {
2441
+ options.optimize = {
2442
+ ...options.optimize,
2443
+ keyframeCount: FFmpegProcessor.calculateKeyframeCount(videoInfo.duration)
2444
+ };
2445
+ }
2446
+ if (options.onProgress) {
2447
+ options.onProgress(10, "preprocessing");
2448
+ }
2449
+ const preprocessResult = await this.ffmpeg.preprocessVideo(
2450
+ resolvedPath,
2451
+ this.tempDir,
2452
+ strategy,
2453
+ options.optimize,
2454
+ (progress) => {
2455
+ if (options.onProgress) {
2456
+ const mapped = 10 + Math.round(progress * 0.4);
2457
+ options.onProgress(Math.max(10, Math.min(50, mapped)), "preprocessing");
2458
+ }
2459
+ }
2460
+ );
2461
+ if (options.onProgress) {
2462
+ options.onProgress(50, "uploading");
2463
+ }
2464
+ let result;
2465
+ if (preprocessResult.type === "video") {
2466
+ result = await this.upload(preprocessResult.output, {
2467
+ ...options,
2468
+ purpose: "video",
2469
+ sourceName: path8.basename(resolvedPath)
2470
+ });
2471
+ this.fileCache.rememberPathHint(resolvedPath, result.hash, path8.basename(resolvedPath));
2472
+ this.invalidateDirectoryListingCacheForPath(resolvedPath);
2473
+ } else {
2474
+ throw new FileManagerError(
2475
+ "PLATFORM_NOT_SUPPORTED" /* PLATFORM_NOT_SUPPORTED */,
2476
+ "Keyframe upload not yet implemented. Use compress strategy."
2477
+ );
2478
+ }
2479
+ this.cleanupTempFiles(preprocessResult.output);
2480
+ return {
2481
+ ...result,
2482
+ metadata: preprocessResult.metadata
2483
+ };
2484
+ }
2485
+ // ============================================================================
2486
+ // File Operations
2487
+ // ============================================================================
2488
+ async getFileStatus(fileId) {
2489
+ const sessionEntry = this.sessionManager.getFileStatus(fileId);
2490
+ if (!sessionEntry) {
2491
+ return void 0;
2492
+ }
2493
+ const cacheEntry = this.fileCache.getByHash(sessionEntry.hash);
2494
+ if (cacheEntry && sessionEntry.platform === this.platform) {
2495
+ const currentRecord = cacheEntry.platforms[this.platform];
2496
+ if (!this.isAccessiblePlatformRecord(currentRecord)) {
2497
+ return {
2498
+ status: "expired",
2499
+ platform: sessionEntry.platform
2500
+ };
2501
+ }
2502
+ }
2503
+ const adapter = this.sessionManager.getAdapter(sessionEntry.platform);
2504
+ if (!adapter) {
2505
+ return {
2506
+ status: sessionEntry.status,
2507
+ platform: sessionEntry.platform,
2508
+ error: sessionEntry.error,
2509
+ unsupportedPlatform: true
2510
+ };
2511
+ }
2512
+ const platformStatus = await adapter.getStatus(fileId);
2513
+ return {
2514
+ status: platformStatus.status,
2515
+ platform: sessionEntry.platform,
2516
+ error: platformStatus.error
2517
+ };
2518
+ }
2519
+ async getExtractedContent(fileId) {
2520
+ const sessionEntry = this.sessionManager.getFileStatus(fileId);
2521
+ const platform = sessionEntry?.platform || this.platform;
2522
+ const adapter = this.sessionManager.getAdapter(platform);
2523
+ if (!adapter?.getContent) {
2524
+ throw new FileManagerError(
2525
+ "PLATFORM_NOT_SUPPORTED" /* PLATFORM_NOT_SUPPORTED */,
2526
+ `Platform ${platform} does not support extracted file content retrieval.`
2527
+ );
2528
+ }
2529
+ return adapter.getContent(fileId);
2530
+ }
2531
+ list(options) {
2532
+ return this.fileCache.list(options);
2533
+ }
2534
+ async refresh(fileId) {
2535
+ const refreshed = await this.sessionManager.refreshFile(fileId);
2536
+ return refreshed.success;
2537
+ }
2538
+ async refreshWithResult(fileId) {
2539
+ return this.sessionManager.refreshFile(fileId);
2540
+ }
2541
+ markFileReferenceError(fileId, error) {
2542
+ if (!fileId || fileId.startsWith("local:")) {
2543
+ return false;
2544
+ }
2545
+ const sessionEntry = this.sessionManager.getFileStatus(fileId);
2546
+ let hash = sessionEntry?.hash;
2547
+ let platform = sessionEntry?.platform;
2548
+ if (!hash || !platform) {
2549
+ const entry = this.fileCache.getByFileId(fileId, this.platform);
2550
+ if (!entry) {
2551
+ return false;
2552
+ }
2553
+ hash = entry.hash;
2554
+ platform = this.platform;
2555
+ }
2556
+ if (!hash || !platform) {
2557
+ return false;
2558
+ }
2559
+ this.fileCache.updatePlatformStatus(hash, platform, "error");
2560
+ if (sessionEntry) {
2561
+ this.sessionManager.updateFileStatus(fileId, "error", void 0, error);
2562
+ }
2563
+ this.directoryListingCache.clear();
2564
+ return true;
2565
+ }
2566
+ async sync() {
2567
+ return this.sessionManager.syncWithPlatforms();
2568
+ }
2569
+ async delete(fileId, remote = true) {
2570
+ const entry = this.fileCache.getByFileId(fileId, this.platform);
2571
+ if (remote) {
2572
+ const adapter = this.getAdapter();
2573
+ await adapter.delete(fileId);
2574
+ }
2575
+ if (entry?.platforms[this.platform]) {
2576
+ delete entry.platforms[this.platform];
2577
+ if (Object.keys(entry.platforms).length === 0) {
2578
+ }
2579
+ }
2580
+ this.directoryListingCache.clear();
2581
+ }
2582
+ // ============================================================================
2583
+ // Mention Support
2584
+ // ============================================================================
2585
+ search(query) {
2586
+ const entries = this.fileCache.search(query);
2587
+ return entries.map((e) => ({
2588
+ hash: e.hash,
2589
+ name: e.name,
2590
+ size: e.size,
2591
+ type: this.getFileType(e.mimeType),
2592
+ mimeType: e.mimeType,
2593
+ createdAt: e.createdAt,
2594
+ platforms: Object.entries(e.platforms).filter(([, record]) => this.canReusePlatformRecord(record)).map(([platform]) => platform),
2595
+ status: this.getEntryStatus(e)
2596
+ }));
2597
+ }
2598
+ getByHash(hash) {
2599
+ const entry = this.fileCache.getByHash(hash);
2600
+ if (!entry) return void 0;
2601
+ return {
2602
+ hash: entry.hash,
2603
+ name: entry.name,
2604
+ size: entry.size,
2605
+ type: this.getFileType(entry.mimeType),
2606
+ mimeType: entry.mimeType,
2607
+ createdAt: entry.createdAt,
2608
+ platforms: Object.keys(entry.platforms),
2609
+ status: this.getEntryStatus(entry)
2610
+ };
2611
+ }
2612
+ getByFileId(fileId) {
2613
+ const sessionEntry = this.sessionManager.getFileStatus(fileId);
2614
+ const entry = sessionEntry ? this.fileCache.getByHash(sessionEntry.hash) : this.fileCache.getByFileId(fileId, this.platform);
2615
+ if (!entry) return void 0;
2616
+ return {
2617
+ hash: entry.hash,
2618
+ name: entry.name,
2619
+ size: entry.size,
2620
+ type: this.getFileType(entry.mimeType),
2621
+ mimeType: entry.mimeType,
2622
+ createdAt: entry.createdAt,
2623
+ platforms: Object.keys(entry.platforms),
2624
+ status: sessionEntry ? this.mapSessionStatusToFileInfoStatus(sessionEntry.status) : this.getEntryStatus(entry)
2625
+ };
2626
+ }
2627
+ getTrackedFile(fileId) {
2628
+ if (fileId.startsWith("local:")) {
2629
+ const hash = fileId.slice("local:".length);
2630
+ const entry2 = this.fileCache.getByHash(hash);
2631
+ if (!entry2) return void 0;
2632
+ return {
2633
+ fileId,
2634
+ hash: entry2.hash,
2635
+ name: entry2.name,
2636
+ size: entry2.size,
2637
+ type: this.getFileType(entry2.mimeType),
2638
+ mimeType: entry2.mimeType,
2639
+ platforms: Object.keys(entry2.platforms),
2640
+ status: "local",
2641
+ platform: "local"
2642
+ };
2643
+ }
2644
+ const sessionEntry = this.sessionManager.getFileStatus(fileId);
2645
+ if (!sessionEntry) {
2646
+ const entry2 = this.fileCache.getByFileId(fileId, this.platform);
2647
+ if (!entry2) {
2648
+ return void 0;
2649
+ }
2650
+ return {
2651
+ fileId,
2652
+ hash: entry2.hash,
2653
+ name: entry2.name,
2654
+ size: entry2.size,
2655
+ type: this.getFileType(entry2.mimeType),
2656
+ mimeType: entry2.mimeType,
2657
+ platforms: Object.keys(entry2.platforms),
2658
+ status: this.getEntryStatus(entry2),
2659
+ platform: this.platform
2660
+ };
2661
+ }
2662
+ const entry = this.fileCache.getByHash(sessionEntry.hash);
2663
+ if (!entry) {
2664
+ return void 0;
2665
+ }
2666
+ return {
2667
+ fileId,
2668
+ hash: entry.hash,
2669
+ name: entry.name,
2670
+ size: entry.size,
2671
+ type: this.getFileType(entry.mimeType),
2672
+ mimeType: entry.mimeType,
2673
+ platforms: Object.keys(entry.platforms),
2674
+ status: sessionEntry.status,
2675
+ platform: sessionEntry.platform
2676
+ };
2677
+ }
2678
+ ensureSessionTracking(fileId, platform = this.platform) {
2679
+ if (!fileId || fileId.startsWith("local:") || this.sessionManager.getFileStatus(fileId)) {
2680
+ return true;
2681
+ }
2682
+ const entry = this.fileCache.getByFileId(fileId, platform);
2683
+ if (!entry) {
2684
+ return false;
2685
+ }
2686
+ const record = entry.platforms[platform];
2687
+ if (!this.canReusePlatformRecord(record)) {
2688
+ return false;
2689
+ }
2690
+ this.sessionManager.trackFile(
2691
+ fileId,
2692
+ entry.hash,
2693
+ platform,
2694
+ record.status === "active" ? "ready" : "uploading"
2695
+ );
2696
+ return true;
2697
+ }
2698
+ getLocalPath(hash) {
2699
+ return this.fileCache.getLocalPath(hash);
2700
+ }
2701
+ // ============================================================================
2702
+ // Platform Reference
2703
+ // ============================================================================
2704
+ buildReference(fileId, mimeType) {
2705
+ const adapter = this.getAdapter();
2706
+ return adapter.buildReference(fileId, mimeType);
2707
+ }
2708
+ // ============================================================================
2709
+ // Utilities
2710
+ // ============================================================================
2711
+ getFileType(mimeType) {
2712
+ if (mimeType.startsWith("image/")) return "image";
2713
+ if (mimeType.startsWith("video/")) return "video";
2714
+ return "document";
2715
+ }
2716
+ async tryReuseCachedSourceUpload(filePath, sourceName, platform) {
2717
+ const hint = this.fileCache.getPathHint(filePath);
2718
+ if (!hint) {
2719
+ return void 0;
2720
+ }
2721
+ const entry = this.fileCache.getByHash(hint.hash);
2722
+ if (!entry) {
2723
+ return void 0;
2724
+ }
2725
+ const record = entry.platforms[platform];
2726
+ if (!this.isAccessiblePlatformRecord(record)) {
2727
+ return void 0;
2728
+ }
2729
+ let effectiveStatus = record.status;
2730
+ const adapter = this.sessionManager.getAdapter(platform);
2731
+ if (effectiveStatus === "processing" && adapter) {
2732
+ const remoteStatus = await adapter.getStatus(record.fileId);
2733
+ if (remoteStatus.status === "active") {
2734
+ effectiveStatus = "active";
2735
+ this.fileCache.updatePlatformStatus(hint.hash, platform, "active");
2736
+ } else if (remoteStatus.status === "error" || remoteStatus.status === "expired" || remoteStatus.status === "not_found") {
2737
+ this.fileCache.updatePlatformStatus(hint.hash, platform, remoteStatus.status);
2738
+ return void 0;
2739
+ }
2740
+ }
2741
+ this.sessionManager.trackFile(
2742
+ record.fileId,
2743
+ hint.hash,
2744
+ platform,
2745
+ effectiveStatus === "active" ? "ready" : "uploading"
2746
+ );
2747
+ return {
2748
+ success: true,
2749
+ hash: hint.hash,
2750
+ fileId: record.fileId,
2751
+ name: sourceName || entry.name,
2752
+ size: entry.size,
2753
+ type: this.getFileType(entry.mimeType),
2754
+ status: effectiveStatus === "active" ? "ready" : "processing",
2755
+ platform,
2756
+ expiresAt: record.expiresAt
2757
+ };
2758
+ }
2759
+ /**
2760
+ * Detect purpose from file path based on extension
2761
+ */
2762
+ detectPurpose(filePath) {
2763
+ const ext = path8.extname(filePath).toLowerCase();
2764
+ switch (ext) {
2765
+ case ".mp4":
2766
+ case ".mov":
2767
+ case ".avi":
2768
+ case ".webm":
2769
+ case ".mkv":
2770
+ return "video";
2771
+ case ".jpg":
2772
+ case ".jpeg":
2773
+ case ".png":
2774
+ case ".webp":
2775
+ case ".gif":
2776
+ return "image";
2777
+ default:
2778
+ return "file-extract";
2779
+ }
2780
+ }
2781
+ getEntryStatus(entry) {
2782
+ const statuses = Object.values(entry.platforms).map((p) => p.status);
2783
+ if (statuses.some((s) => s === "processing")) return "uploading";
2784
+ if (statuses.some((s) => s === "active")) return "ready";
2785
+ if (statuses.every((s) => s === "expired")) return "expired";
2786
+ return "local";
2787
+ }
2788
+ mapSessionStatusToFileInfoStatus(status) {
2789
+ switch (status) {
2790
+ case "pending":
2791
+ case "uploading":
2792
+ return "uploading";
2793
+ case "ready":
2794
+ return "ready";
2795
+ case "expired":
2796
+ case "error":
2797
+ return "expired";
2798
+ default:
2799
+ return "local";
2800
+ }
2801
+ }
2802
+ cleanupTempFiles(output) {
2803
+ try {
2804
+ if (typeof output === "string") {
2805
+ if (fs7.existsSync(output)) {
2806
+ fs7.unlinkSync(output);
2807
+ }
2808
+ } else {
2809
+ for (const file of output) {
2810
+ if (fs7.existsSync(file)) {
2811
+ fs7.unlinkSync(file);
2812
+ }
2813
+ }
2814
+ }
2815
+ } catch {
2816
+ }
2817
+ }
2818
+ /**
2819
+ * Get files from current session
2820
+ * Used by @mention system to show recently uploaded files
2821
+ */
2822
+ getSessionFiles() {
2823
+ const files = this.sessionManager.getAllFiles();
2824
+ return files.flatMap(({ fileId, entry }) => {
2825
+ const cacheEntry = this.fileCache.getByHash(entry.hash);
2826
+ if (!cacheEntry) {
2827
+ return [];
2828
+ }
2829
+ const type = this.getFileType(cacheEntry.mimeType);
2830
+ const currentPlatformRecord = cacheEntry.platforms[this.platform];
2831
+ if (this.canReusePlatformRecord(currentPlatformRecord)) {
2832
+ return [{
2833
+ fileId: currentPlatformRecord.fileId,
2834
+ name: cacheEntry.name,
2835
+ size: cacheEntry.size,
2836
+ type,
2837
+ status: currentPlatformRecord.status === "active" ? "ready" : "uploading",
2838
+ reuse: "uploaded",
2839
+ sourcePlatform: entry.platform
2840
+ }];
2841
+ }
2842
+ const localPath = this.fileCache.getLocalPath(entry.hash);
2843
+ if (localPath && fs7.existsSync(localPath)) {
2844
+ return [{
2845
+ fileId,
2846
+ name: cacheEntry.name,
2847
+ size: cacheEntry.size,
2848
+ type,
2849
+ status: "local",
2850
+ reuse: "local",
2851
+ path: localPath,
2852
+ sourcePlatform: entry.platform
2853
+ }];
2854
+ }
2855
+ return [];
2856
+ });
2857
+ }
2858
+ /**
2859
+ * Search files in current working directory
2860
+ * Used by @mention system to show local files
2861
+ */
2862
+ getCwdFiles(query) {
2863
+ const files = [];
2864
+ const cwd = process.cwd();
2865
+ const listing = this.getDirectoryListing(cwd);
2866
+ const normalizedQuery = query?.toLowerCase();
2867
+ for (const entry of listing.files) {
2868
+ if (normalizedQuery && !entry.name.toLowerCase().includes(normalizedQuery)) {
2869
+ continue;
2870
+ }
2871
+ files.push({
2872
+ ...entry,
2873
+ cacheStatus: this.getCacheStatusForPath(entry.path)
2874
+ });
2875
+ }
2876
+ files.sort((a, b) => a.name.localeCompare(b.name, "zh-Hans-CN", { numeric: true }));
2877
+ return files;
2878
+ }
2879
+ listPathEntries(dirPath, query) {
2880
+ const directories = [];
2881
+ const files = [];
2882
+ const resolvedDir = resolvePath(dirPath);
2883
+ const listing = this.getDirectoryListing(resolvedDir);
2884
+ const normalizedQuery = query?.toLowerCase();
2885
+ for (const directory of listing.directories) {
2886
+ if (normalizedQuery && !directory.name.toLowerCase().includes(normalizedQuery)) {
2887
+ continue;
2888
+ }
2889
+ directories.push(directory);
2890
+ }
2891
+ for (const entry of listing.files) {
2892
+ if (normalizedQuery && !entry.name.toLowerCase().includes(normalizedQuery)) {
2893
+ continue;
2894
+ }
2895
+ files.push({
2896
+ ...entry,
2897
+ cacheStatus: this.getCacheStatusForPath(entry.path)
2898
+ });
2899
+ }
2900
+ const sorter = (a, b) => a.name.localeCompare(b.name, "zh-Hans-CN", { numeric: true });
2901
+ directories.sort(sorter);
2902
+ files.sort(sorter);
2903
+ return {
2904
+ directories,
2905
+ files
2906
+ };
2907
+ }
2908
+ getCacheStatusForPath(filePath) {
2909
+ try {
2910
+ const hint = this.fileCache.getPathHint(filePath);
2911
+ if (!hint) {
2912
+ return void 0;
2913
+ }
2914
+ if (hint.uploadedPlatforms?.includes(this.platform)) {
2915
+ return "uploaded";
2916
+ }
2917
+ const cached = this.fileCache.getByHash(hint.hash);
2918
+ if (!cached) return void 0;
2919
+ const currentPlatformRecord = cached.platforms[this.platform];
2920
+ if (currentPlatformRecord && currentPlatformRecord.status !== "error" && currentPlatformRecord.status !== "expired") {
2921
+ return "uploaded";
2922
+ }
2923
+ return "cached";
2924
+ } catch {
2925
+ return void 0;
2926
+ }
2927
+ }
2928
+ getDirectoryListing(dirPath) {
2929
+ const resolvedDir = resolvePath(dirPath);
2930
+ const cached = this.directoryListingCache.get(resolvedDir);
2931
+ if (cached && cached.expiresAt > Date.now()) {
2932
+ return cached;
2933
+ }
2934
+ const listing = {
2935
+ expiresAt: Date.now() + DIRECTORY_LISTING_TTL_MS,
2936
+ files: [],
2937
+ directories: []
2938
+ };
2939
+ try {
2940
+ const entries = fs7.readdirSync(resolvedDir, { withFileTypes: true });
2941
+ for (const entry of entries) {
2942
+ if (!entry.name || entry.name.startsWith(".")) {
2943
+ continue;
2944
+ }
2945
+ const fullPath = path8.join(resolvedDir, entry.name);
2946
+ if (entry.isDirectory()) {
2947
+ listing.directories.push({ name: entry.name, path: fullPath });
2948
+ continue;
2949
+ }
2950
+ let isDirectory = false;
2951
+ let isFile = entry.isFile();
2952
+ if (entry.isSymbolicLink()) {
2953
+ try {
2954
+ const targetStat = fs7.statSync(fullPath);
2955
+ isDirectory = targetStat.isDirectory();
2956
+ isFile = targetStat.isFile();
2957
+ } catch {
2958
+ continue;
2959
+ }
2960
+ }
2961
+ if (isDirectory) {
2962
+ listing.directories.push({ name: entry.name, path: fullPath });
2963
+ continue;
2964
+ }
2965
+ if (!isFile) {
2966
+ continue;
2967
+ }
2968
+ const type = FileCache.getFileTypeFromName(entry.name);
2969
+ if (!type) {
2970
+ continue;
2971
+ }
2972
+ const stat2 = fs7.statSync(fullPath);
2973
+ listing.files.push({
2974
+ name: entry.name,
2975
+ path: fullPath,
2976
+ size: stat2.size,
2977
+ type
2978
+ });
2979
+ }
2980
+ } catch {
2981
+ }
2982
+ this.directoryListingCache.set(resolvedDir, listing);
2983
+ return listing;
2984
+ }
2985
+ invalidateDirectoryListingCacheForPath(filePath) {
2986
+ this.directoryListingCache.delete(path8.dirname(resolvePath(filePath)));
2987
+ }
2988
+ buildAuthFingerprint(apiKey) {
2989
+ return crypto2.createHash("sha256").update(apiKey).digest("hex").slice(0, 16);
2990
+ }
2991
+ matchesCurrentAuth(record) {
2992
+ if (!record) {
2993
+ return false;
2994
+ }
2995
+ if (!this.authFingerprint) {
2996
+ return true;
2997
+ }
2998
+ return record.authFingerprint === this.authFingerprint;
2999
+ }
3000
+ isAccessiblePlatformRecord(record) {
3001
+ if (!record) {
3002
+ return false;
3003
+ }
3004
+ if (record.status === "error" || record.status === "expired") {
3005
+ return false;
3006
+ }
3007
+ return this.matchesCurrentAuth(record);
3008
+ }
3009
+ canReusePlatformRecord(record) {
3010
+ if (!record || !this.isAccessiblePlatformRecord(record)) {
3011
+ return false;
3012
+ }
3013
+ return record.status === "active";
3014
+ }
3015
+ getStats() {
3016
+ return {
3017
+ cache: this.fileCache.getStats(),
3018
+ session: this.sessionManager.getStats()
3019
+ };
3020
+ }
3021
+ };
3022
+
3023
+ // src/capabilities/read-file-understanding.ts
3024
+ var MAX_EXTRACTED_DOCUMENT_CHARS = 12e4;
3025
+ var DEFAULT_INLINE_LIMIT_MB = {
3026
+ image: 10,
3027
+ video: 15
3028
+ };
3029
+ function createFileManagerForModel(params) {
3030
+ const platform = params.model.filePlatform || params.model.attachmentPlatform || "unknown";
3031
+ const manager = new FileManager({
3032
+ sessionId: params.sessionId,
3033
+ platform,
3034
+ apiKey: params.apiKey,
3035
+ baseDir: path9.join(params.configDir, "files"),
3036
+ sessionsDir: path9.join(params.configDir, "sessions")
3037
+ });
3038
+ switch (getFileManagerAdapterKind(platform)) {
3039
+ case "kimi":
3040
+ if (params.model.baseUrl) {
3041
+ manager.registerAdapter(new KimiFileAdapter(params.apiKey, params.model.baseUrl));
3042
+ }
3043
+ break;
3044
+ case "gemini":
3045
+ manager.registerAdapter(new GeminiFileAdapter(params.apiKey));
3046
+ break;
3047
+ case "openai-compatible-files":
3048
+ if (params.model.baseUrl) {
3049
+ manager.registerAdapter(new OpenAICompatibleFilesAdapter(params.apiKey, params.model.baseUrl, params.model.headers));
3050
+ }
3051
+ break;
3052
+ default:
3053
+ break;
3054
+ }
3055
+ return manager;
3056
+ }
3057
+ function fileManagerAdapterKindForModel(model) {
3058
+ return getFileManagerAdapterKind(model.filePlatform || model.attachmentPlatform);
3059
+ }
3060
+ function getCapabilityLimitMb(model, kind) {
3061
+ const capability = model.fileCapabilities?.[kind];
3062
+ if (capability && typeof capability === "object" && typeof capability.maxFileSizeMb === "number") {
3063
+ return capability.maxFileSizeMb;
3064
+ }
3065
+ return DEFAULT_INLINE_LIMIT_MB[kind];
3066
+ }
3067
+ function isInlineMediaRequest(request) {
3068
+ return request.kind === "image" || request.kind === "video";
3069
+ }
3070
+ async function prepareInlineMediaContent(params) {
3071
+ const stat2 = await fs8.stat(params.request.absolutePath);
3072
+ const limitMb = getCapabilityLimitMb(params.model, params.request.kind);
3073
+ const limitBytes = limitMb * 1024 * 1024;
3074
+ if (stat2.size > limitBytes) {
3075
+ throw new Error(
3076
+ `${params.request.kind} understanding for ${params.model.provider}/${params.model.id} supports inline files up to ${limitMb}MB; ${path9.basename(params.request.displayPath)} is ${(stat2.size / 1024 / 1024).toFixed(1)}MB. Configure a model with a file upload adapter, or compress/trim the file before reading it.`
3077
+ );
3078
+ }
3079
+ const data = await fs8.readFile(params.request.absolutePath, "base64");
3080
+ const content = params.request.kind === "video" ? [{ type: "video", data, mimeType: params.request.mimeType }] : [{ type: "image", data, mimeType: params.request.mimeType }];
3081
+ return {
3082
+ content,
3083
+ details: {
3084
+ inputMode: "inlineDataUrl",
3085
+ inlineFileSizeBytes: stat2.size,
3086
+ inlineLimitMb: limitMb
3087
+ }
3088
+ };
3089
+ }
3090
+ async function waitForReady(params) {
3091
+ const started = Date.now();
3092
+ while (Date.now() - started < params.timeoutMs) {
3093
+ if (params.signal?.aborted) throw new Error("Operation aborted");
3094
+ const status = await params.manager.getFileStatus(params.fileId);
3095
+ if (!status || status.status === "active" || status.status === "ready") return;
3096
+ if (status.status === "error" || status.status === "expired") {
3097
+ throw new Error(`Uploaded file is not ready: ${status.status}${status.error ? ` (${status.error})` : ""}`);
3098
+ }
3099
+ await new Promise((resolve2) => setTimeout(resolve2, 1500));
3100
+ }
3101
+ throw new Error("Timed out waiting for uploaded file to become ready");
3102
+ }
3103
+ async function prepareFileContent(configDir, params) {
3104
+ if (isInlineMediaRequest(params.request) && (fileManagerAdapterKindForModel(params.model) === "none" || fileManagerAdapterKindForModel(params.model) === "openai-compatible-files")) {
3105
+ return prepareInlineMediaContent({ ...params, request: params.request });
3106
+ }
3107
+ const manager = createFileManagerForModel({
3108
+ model: params.model,
3109
+ apiKey: params.apiKey,
3110
+ sessionId: params.sessionId,
3111
+ configDir
3112
+ });
3113
+ if (params.request.kind === "document") {
3114
+ const upload2 = await manager.upload(params.request.absolutePath, {
3115
+ sourceName: path9.basename(params.request.displayPath),
3116
+ purpose: "file-extract"
3117
+ });
3118
+ await waitForReady({ manager, fileId: upload2.fileId, timeoutMs: 12e4, signal: params.request.signal });
3119
+ const extracted = await manager.getExtractedContent(upload2.fileId);
3120
+ const truncated = extracted.length > MAX_EXTRACTED_DOCUMENT_CHARS;
3121
+ const documentText = truncated ? `${extracted.slice(0, MAX_EXTRACTED_DOCUMENT_CHARS)}
3122
+
3123
+ [Document extraction truncated after ${MAX_EXTRACTED_DOCUMENT_CHARS} characters.]` : extracted;
3124
+ return {
3125
+ content: [{
3126
+ type: "text",
3127
+ text: [
3128
+ "Extracted document content:",
3129
+ documentText || "(document extraction returned no text)"
3130
+ ].join("\n")
3131
+ }],
3132
+ details: {
3133
+ inputMode: "fileUploadExtraction",
3134
+ uploadedFileId: upload2.fileId
3135
+ }
3136
+ };
3137
+ }
3138
+ const upload = params.request.kind === "video" ? await manager.uploadVideo(params.request.absolutePath, { sourceName: path9.basename(params.request.displayPath), strategy: "compress" }) : await manager.upload(params.request.absolutePath, {
3139
+ sourceName: path9.basename(params.request.displayPath),
3140
+ purpose: params.request.kind === "image" ? "image" : "file-extract"
3141
+ });
3142
+ if (params.request.kind !== "video") {
3143
+ await waitForReady({ manager, fileId: upload.fileId, timeoutMs: 12e4, signal: params.request.signal });
3144
+ }
3145
+ const ref = {
3146
+ type: "fileRef",
3147
+ url: `ms://${upload.fileId}`,
3148
+ mimeType: params.request.mimeType,
3149
+ modality: modalityForReadFileUnderstandingKind(params.request.kind)
3150
+ };
3151
+ return { content: [ref], details: { inputMode: "fileRef" } };
3152
+ }
3153
+ async function understandReadFile(deps, request) {
3154
+ return createReadFileUnderstandingHandler({
3155
+ getAgentModel: deps.getAgentModel,
3156
+ getSessionId: deps.getSessionId,
3157
+ resolveToolModel: deps.resolveToolModel,
3158
+ resolveToolModelCandidates: deps.resolveToolModelCandidates,
3159
+ prepareFileContent: (params) => prepareFileContent(deps.configDir, params)
3160
+ })(request);
3161
+ }
3162
+
3163
+ export {
3164
+ getFileManagerAdapterKind,
3165
+ normalizeFileManagerPlatform,
3166
+ FileManagerError,
3167
+ KimiFileAdapter,
3168
+ GeminiFileAdapter,
3169
+ OpenAICompatibleFilesAdapter,
3170
+ monitorLogger,
3171
+ looksLikeFilePath,
3172
+ formatBytes,
3173
+ resolvePath,
3174
+ getFileTypeIcon,
3175
+ FileCache,
3176
+ FileManager,
3177
+ understandReadFile
3178
+ };