forked from sanbuphy/learn-coding-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilesApi.ts
More file actions
748 lines (657 loc) · 21 KB
/
filesApi.ts
File metadata and controls
748 lines (657 loc) · 21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
/**
* Files API client for managing files
*
* This module provides functionality to download and upload files to Anthropic Public Files API.
* Used by the Claude Code agent to download file attachments at session startup.
*
* API Reference: https://docs.anthropic.com/en/api/files-content
*/
import axios from 'axios'
import { randomUUID } from 'crypto'
import * as fs from 'fs/promises'
import * as path from 'path'
import { count } from '../../utils/array.js'
import { getCwd } from '../../utils/cwd.js'
import { logForDebugging } from '../../utils/debug.js'
import { errorMessage } from '../../utils/errors.js'
import { logError } from '../../utils/log.js'
import { sleep } from '../../utils/sleep.js'
import {
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
logEvent,
} from '../analytics/index.js'
// Files API is currently in beta. oauth-2025-04-20 enables Bearer OAuth
// on public-api routes (auth.py: "oauth_auth" not in beta_versions → 404).
const FILES_API_BETA_HEADER = 'files-api-2025-04-14,oauth-2025-04-20'
const ANTHROPIC_VERSION = '2023-06-01'
// API base URL - uses ANTHROPIC_BASE_URL set by env-manager for the appropriate environment
// Falls back to public API for standalone usage
function getDefaultApiBaseUrl(): string {
return (
process.env.ANTHROPIC_BASE_URL ||
process.env.CLAUDE_CODE_API_BASE_URL ||
'https://api.anthropic.com'
)
}
function logDebugError(message: string): void {
logForDebugging(`[files-api] ${message}`, { level: 'error' })
}
function logDebug(message: string): void {
logForDebugging(`[files-api] ${message}`)
}
/**
* File specification parsed from CLI args
* Format: --file=<file_id>:<relative_path>
*/
export type File = {
fileId: string
relativePath: string
}
/**
* Configuration for the files API client
*/
export type FilesApiConfig = {
/** OAuth token for authentication (from session JWT) */
oauthToken: string
/** Base URL for the API (default: https://api.anthropic.com) */
baseUrl?: string
/** Session ID for creating session-specific directories */
sessionId: string
}
/**
* Result of a file download operation
*/
export type DownloadResult = {
fileId: string
path: string
success: boolean
error?: string
bytesWritten?: number
}
const MAX_RETRIES = 3
const BASE_DELAY_MS = 500
const MAX_FILE_SIZE_BYTES = 500 * 1024 * 1024 // 500MB
/**
* Result type for retry operations - signals whether to continue retrying
*/
type RetryResult<T> = { done: true; value: T } | { done: false; error?: string }
/**
* Executes an operation with exponential backoff retry logic
*
* @param operation - Operation name for logging
* @param attemptFn - Function to execute on each attempt, returns RetryResult
* @returns The successful result value
* @throws Error if all retries exhausted
*/
async function retryWithBackoff<T>(
operation: string,
attemptFn: (attempt: number) => Promise<RetryResult<T>>,
): Promise<T> {
let lastError = ''
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
const result = await attemptFn(attempt)
if (result.done) {
return result.value
}
lastError = result.error || `${operation} failed`
logDebug(
`${operation} attempt ${attempt}/${MAX_RETRIES} failed: ${lastError}`,
)
if (attempt < MAX_RETRIES) {
const delayMs = BASE_DELAY_MS * Math.pow(2, attempt - 1)
logDebug(`Retrying ${operation} in ${delayMs}ms...`)
await sleep(delayMs)
}
}
throw new Error(`${lastError} after ${MAX_RETRIES} attempts`)
}
/**
* Downloads a single file from the Anthropic Public Files API
*
* @param fileId - The file ID (e.g., "file_011CNha8iCJcU1wXNR6q4V8w")
* @param config - Files API configuration
* @returns The file content as a Buffer
*/
export async function downloadFile(
fileId: string,
config: FilesApiConfig,
): Promise<Buffer> {
const baseUrl = config.baseUrl || getDefaultApiBaseUrl()
const url = `${baseUrl}/v1/files/${fileId}/content`
const headers = {
Authorization: `Bearer ${config.oauthToken}`,
'anthropic-version': ANTHROPIC_VERSION,
'anthropic-beta': FILES_API_BETA_HEADER,
}
logDebug(`Downloading file ${fileId} from ${url}`)
return retryWithBackoff(`Download file ${fileId}`, async () => {
try {
const response = await axios.get(url, {
headers,
responseType: 'arraybuffer',
timeout: 60000, // 60 second timeout for large files
validateStatus: status => status < 500,
})
if (response.status === 200) {
logDebug(`Downloaded file ${fileId} (${response.data.length} bytes)`)
return { done: true, value: Buffer.from(response.data) }
}
// Non-retriable errors - throw immediately
if (response.status === 404) {
throw new Error(`File not found: ${fileId}`)
}
if (response.status === 401) {
throw new Error('Authentication failed: invalid or missing API key')
}
if (response.status === 403) {
throw new Error(`Access denied to file: ${fileId}`)
}
return { done: false, error: `status ${response.status}` }
} catch (error) {
if (!axios.isAxiosError(error)) {
throw error
}
return { done: false, error: error.message }
}
})
}
/**
* Normalizes a relative path, strips redundant prefixes, and builds the full
* download path under {basePath}/{session_id}/uploads/.
* Returns null if the path is invalid (e.g., path traversal).
*/
export function buildDownloadPath(
basePath: string,
sessionId: string,
relativePath: string,
): string | null {
const normalized = path.normalize(relativePath)
if (normalized.startsWith('..')) {
logDebugError(
`Invalid file path: ${relativePath}. Path must not traverse above workspace`,
)
return null
}
const uploadsBase = path.join(basePath, sessionId, 'uploads')
const redundantPrefixes = [
path.join(basePath, sessionId, 'uploads') + path.sep,
path.sep + 'uploads' + path.sep,
]
const matchedPrefix = redundantPrefixes.find(p => normalized.startsWith(p))
const cleanPath = matchedPrefix
? normalized.slice(matchedPrefix.length)
: normalized
return path.join(uploadsBase, cleanPath)
}
/**
* Downloads a file and saves it to the session-specific workspace directory
*
* @param attachment - The file attachment to download
* @param config - Files API configuration
* @returns Download result with success/failure status
*/
export async function downloadAndSaveFile(
attachment: File,
config: FilesApiConfig,
): Promise<DownloadResult> {
const { fileId, relativePath } = attachment
const fullPath = buildDownloadPath(getCwd(), config.sessionId, relativePath)
if (!fullPath) {
return {
fileId,
path: '',
success: false,
error: `Invalid file path: ${relativePath}`,
}
}
try {
// Download the file content
const content = await downloadFile(fileId, config)
// Ensure the parent directory exists
const parentDir = path.dirname(fullPath)
await fs.mkdir(parentDir, { recursive: true })
// Write the file
await fs.writeFile(fullPath, content)
logDebug(`Saved file ${fileId} to ${fullPath} (${content.length} bytes)`)
return {
fileId,
path: fullPath,
success: true,
bytesWritten: content.length,
}
} catch (error) {
logDebugError(`Failed to download file ${fileId}: ${errorMessage(error)}`)
if (error instanceof Error) {
logError(error)
}
return {
fileId,
path: fullPath,
success: false,
error: errorMessage(error),
}
}
}
// Default concurrency limit for parallel downloads
const DEFAULT_CONCURRENCY = 5
/**
* Execute promises with limited concurrency
*
* @param items - Items to process
* @param fn - Async function to apply to each item
* @param concurrency - Maximum concurrent operations
* @returns Results in the same order as input items
*/
async function parallelWithLimit<T, R>(
items: T[],
fn: (item: T, index: number) => Promise<R>,
concurrency: number,
): Promise<R[]> {
const results: R[] = new Array(items.length)
let currentIndex = 0
async function worker(): Promise<void> {
while (currentIndex < items.length) {
const index = currentIndex++
const item = items[index]
if (item !== undefined) {
results[index] = await fn(item, index)
}
}
}
// Start workers up to the concurrency limit
const workers: Promise<void>[] = []
const workerCount = Math.min(concurrency, items.length)
for (let i = 0; i < workerCount; i++) {
workers.push(worker())
}
await Promise.all(workers)
return results
}
/**
* Downloads all file attachments for a session in parallel
*
* @param attachments - List of file attachments to download
* @param config - Files API configuration
* @param concurrency - Maximum concurrent downloads (default: 5)
* @returns Array of download results in the same order as input
*/
export async function downloadSessionFiles(
files: File[],
config: FilesApiConfig,
concurrency: number = DEFAULT_CONCURRENCY,
): Promise<DownloadResult[]> {
if (files.length === 0) {
return []
}
logDebug(
`Downloading ${files.length} file(s) for session ${config.sessionId}`,
)
const startTime = Date.now()
// Download files in parallel with concurrency limit
const results = await parallelWithLimit(
files,
file => downloadAndSaveFile(file, config),
concurrency,
)
const elapsedMs = Date.now() - startTime
const successCount = count(results, r => r.success)
logDebug(
`Downloaded ${successCount}/${files.length} file(s) in ${elapsedMs}ms`,
)
return results
}
// ============================================================================
// Upload Functions (BYOC mode)
// ============================================================================
/**
* Result of a file upload operation
*/
export type UploadResult =
| {
path: string
fileId: string
size: number
success: true
}
| {
path: string
error: string
success: false
}
/**
* Upload a single file to the Files API (BYOC mode)
*
* Size validation is performed after reading the file to avoid TOCTOU race
* conditions where the file size could change between initial check and upload.
*
* @param filePath - Absolute path to the file to upload
* @param relativePath - Relative path for the file (used as filename in API)
* @param config - Files API configuration
* @returns Upload result with success/failure status
*/
export async function uploadFile(
filePath: string,
relativePath: string,
config: FilesApiConfig,
opts?: { signal?: AbortSignal },
): Promise<UploadResult> {
const baseUrl = config.baseUrl || getDefaultApiBaseUrl()
const url = `${baseUrl}/v1/files`
const headers = {
Authorization: `Bearer ${config.oauthToken}`,
'anthropic-version': ANTHROPIC_VERSION,
'anthropic-beta': FILES_API_BETA_HEADER,
}
logDebug(`Uploading file ${filePath} as ${relativePath}`)
// Read file content first (outside retry loop since it's not a network operation)
let content: Buffer
try {
content = await fs.readFile(filePath)
} catch (error) {
logEvent('tengu_file_upload_failed', {
error_type:
'file_read' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
})
return {
path: relativePath,
error: errorMessage(error),
success: false,
}
}
const fileSize = content.length
if (fileSize > MAX_FILE_SIZE_BYTES) {
logEvent('tengu_file_upload_failed', {
error_type:
'file_too_large' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
})
return {
path: relativePath,
error: `File exceeds maximum size of ${MAX_FILE_SIZE_BYTES} bytes (actual: ${fileSize})`,
success: false,
}
}
// Use crypto.randomUUID for boundary to avoid collisions when uploads start same millisecond
const boundary = `----FormBoundary${randomUUID()}`
const filename = path.basename(relativePath)
// Build the multipart body
const bodyParts: Buffer[] = []
// File part
bodyParts.push(
Buffer.from(
`--${boundary}\r\n` +
`Content-Disposition: form-data; name="file"; filename="${filename}"\r\n` +
`Content-Type: application/octet-stream\r\n\r\n`,
),
)
bodyParts.push(content)
bodyParts.push(Buffer.from('\r\n'))
// Purpose part
bodyParts.push(
Buffer.from(
`--${boundary}\r\n` +
`Content-Disposition: form-data; name="purpose"\r\n\r\n` +
`user_data\r\n`,
),
)
// End boundary
bodyParts.push(Buffer.from(`--${boundary}--\r\n`))
const body = Buffer.concat(bodyParts)
try {
return await retryWithBackoff(`Upload file ${relativePath}`, async () => {
try {
const response = await axios.post(url, body, {
headers: {
...headers,
'Content-Type': `multipart/form-data; boundary=${boundary}`,
'Content-Length': body.length.toString(),
},
timeout: 120000, // 2 minute timeout for uploads
signal: opts?.signal,
validateStatus: status => status < 500,
})
if (response.status === 200 || response.status === 201) {
const fileId = response.data?.id
if (!fileId) {
return {
done: false,
error: 'Upload succeeded but no file ID returned',
}
}
logDebug(`Uploaded file ${filePath} -> ${fileId} (${fileSize} bytes)`)
return {
done: true,
value: {
path: relativePath,
fileId,
size: fileSize,
success: true as const,
},
}
}
// Non-retriable errors - throw to exit retry loop
if (response.status === 401) {
logEvent('tengu_file_upload_failed', {
error_type:
'auth' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
})
throw new UploadNonRetriableError(
'Authentication failed: invalid or missing API key',
)
}
if (response.status === 403) {
logEvent('tengu_file_upload_failed', {
error_type:
'forbidden' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
})
throw new UploadNonRetriableError('Access denied for upload')
}
if (response.status === 413) {
logEvent('tengu_file_upload_failed', {
error_type:
'size' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
})
throw new UploadNonRetriableError('File too large for upload')
}
return { done: false, error: `status ${response.status}` }
} catch (error) {
// Non-retriable errors propagate up
if (error instanceof UploadNonRetriableError) {
throw error
}
if (axios.isCancel(error)) {
throw new UploadNonRetriableError('Upload canceled')
}
// Network errors are retriable
if (axios.isAxiosError(error)) {
return { done: false, error: error.message }
}
throw error
}
})
} catch (error) {
if (error instanceof UploadNonRetriableError) {
return {
path: relativePath,
error: error.message,
success: false,
}
}
logEvent('tengu_file_upload_failed', {
error_type:
'network' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
})
return {
path: relativePath,
error: errorMessage(error),
success: false,
}
}
}
/** Error class for non-retriable upload failures */
class UploadNonRetriableError extends Error {
constructor(message: string) {
super(message)
this.name = 'UploadNonRetriableError'
}
}
/**
* Upload multiple files in parallel with concurrency limit (BYOC mode)
*
* @param files - Array of files to upload (path and relativePath)
* @param config - Files API configuration
* @param concurrency - Maximum concurrent uploads (default: 5)
* @returns Array of upload results in the same order as input
*/
export async function uploadSessionFiles(
files: Array<{ path: string; relativePath: string }>,
config: FilesApiConfig,
concurrency: number = DEFAULT_CONCURRENCY,
): Promise<UploadResult[]> {
if (files.length === 0) {
return []
}
logDebug(`Uploading ${files.length} file(s) for session ${config.sessionId}`)
const startTime = Date.now()
const results = await parallelWithLimit(
files,
file => uploadFile(file.path, file.relativePath, config),
concurrency,
)
const elapsedMs = Date.now() - startTime
const successCount = count(results, r => r.success)
logDebug(`Uploaded ${successCount}/${files.length} file(s) in ${elapsedMs}ms`)
return results
}
// ============================================================================
// List Files Functions (1P/Cloud mode)
// ============================================================================
/**
* File metadata returned from listFilesCreatedAfter
*/
export type FileMetadata = {
filename: string
fileId: string
size: number
}
/**
* List files created after a given timestamp (1P/Cloud mode).
* Uses the public GET /v1/files endpoint with after_created_at query param.
* Handles pagination via after_id cursor when has_more is true.
*
* @param afterCreatedAt - ISO 8601 timestamp to filter files created after
* @param config - Files API configuration
* @returns Array of file metadata for files created after the timestamp
*/
export async function listFilesCreatedAfter(
afterCreatedAt: string,
config: FilesApiConfig,
): Promise<FileMetadata[]> {
const baseUrl = config.baseUrl || getDefaultApiBaseUrl()
const headers = {
Authorization: `Bearer ${config.oauthToken}`,
'anthropic-version': ANTHROPIC_VERSION,
'anthropic-beta': FILES_API_BETA_HEADER,
}
logDebug(`Listing files created after ${afterCreatedAt}`)
const allFiles: FileMetadata[] = []
let afterId: string | undefined
// Paginate through results
while (true) {
const params: Record<string, string> = {
after_created_at: afterCreatedAt,
}
if (afterId) {
params.after_id = afterId
}
const page = await retryWithBackoff(
`List files after ${afterCreatedAt}`,
async () => {
try {
const response = await axios.get(`${baseUrl}/v1/files`, {
headers,
params,
timeout: 60000,
validateStatus: status => status < 500,
})
if (response.status === 200) {
return { done: true, value: response.data }
}
if (response.status === 401) {
logEvent('tengu_file_list_failed', {
error_type:
'auth' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
})
throw new Error('Authentication failed: invalid or missing API key')
}
if (response.status === 403) {
logEvent('tengu_file_list_failed', {
error_type:
'forbidden' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
})
throw new Error('Access denied to list files')
}
return { done: false, error: `status ${response.status}` }
} catch (error) {
if (!axios.isAxiosError(error)) {
throw error
}
logEvent('tengu_file_list_failed', {
error_type:
'network' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
})
return { done: false, error: error.message }
}
},
)
const files = page.data || []
for (const f of files) {
allFiles.push({
filename: f.filename,
fileId: f.id,
size: f.size_bytes,
})
}
if (!page.has_more) {
break
}
// Use the last file's ID as cursor for next page
const lastFile = files.at(-1)
if (!lastFile?.id) {
break
}
afterId = lastFile.id
}
logDebug(`Listed ${allFiles.length} files created after ${afterCreatedAt}`)
return allFiles
}
// ============================================================================
// Parse Functions
// ============================================================================
/**
* Parse file attachment specs from CLI arguments
* Format: <file_id>:<relative_path>
*
* @param fileSpecs - Array of file spec strings
* @returns Parsed file attachments
*/
export function parseFileSpecs(fileSpecs: string[]): File[] {
const files: File[] = []
// Sandbox-gateway may pass multiple specs as a single space-separated string
const expandedSpecs = fileSpecs.flatMap(s => s.split(' ').filter(Boolean))
for (const spec of expandedSpecs) {
const colonIndex = spec.indexOf(':')
if (colonIndex === -1) {
continue
}
const fileId = spec.substring(0, colonIndex)
const relativePath = spec.substring(colonIndex + 1)
if (!fileId || !relativePath) {
logDebugError(
`Invalid file spec: ${spec}. Both file_id and path are required`,
)
continue
}
files.push({ fileId, relativePath })
}
return files
}