|
41 | 41 |
|
42 | 42 | import { createHash, randomUUID } from 'node:crypto'; |
43 | 43 | import { copyFileSync, mkdirSync, readdirSync, statSync, unlinkSync, writeFileSync } from 'node:fs'; |
44 | | -import { tmpdir } from 'node:os'; |
45 | 44 | import { join } from 'node:path'; |
46 | 45 |
|
47 | 46 | import type { PromptPart, Session } from '@pymodel/pythinker-code-sdk'; |
@@ -664,15 +663,19 @@ export function persistOriginalImageSync( |
664 | 663 | const hash = createHash('sha256').update(bytes).digest('hex').slice(0, 32); |
665 | 664 | const target = join(targetDir, `${hash}.${imageExtensionForMime(mime)}`); |
666 | 665 | mkdirSync(targetDir, { recursive: true }); |
667 | | - const existing = statSync(target, { throwIfNoEntry: false }); |
668 | | - // Content-addressed: an existing entry with the right size IS this image. |
669 | | - if (existing === undefined || existing.size !== bytes.length) { |
670 | | - writeFileSync(target, bytes); |
| 666 | + try { |
| 667 | + writeFileSync(target, bytes, { flag: 'wx' }); |
| 668 | + } catch (error) { |
| 669 | + const code = error instanceof Error && 'code' in error ? (error as NodeJS.ErrnoException).code : undefined; |
| 670 | + if (code !== 'EEXIST') throw error; |
671 | 671 | } |
672 | 672 | sweepCacheSync(targetDir, maxTotalBytes); |
673 | | - // The just-written file may itself have been evicted by the sweep when a |
674 | | - // single original exceeds the cap; report persistence honestly. |
675 | | - return statSync(target, { throwIfNoEntry: false }) === undefined ? null : target; |
| 673 | + try { |
| 674 | + const existing = statSync(target); |
| 675 | + return existing.isFile() && existing.size === bytes.length ? target : null; |
| 676 | + } catch { |
| 677 | + return null; |
| 678 | + } |
676 | 679 | } catch { |
677 | 680 | return null; |
678 | 681 | } |
@@ -706,7 +709,7 @@ function sweepCacheSync(dir: string, maxTotalBytes: number): void { |
706 | 709 |
|
707 | 710 | /** Mirrors agent-core-v2's `originalImageCacheDir` (not re-exported through the SDK). */ |
708 | 711 | function originalImageTempDir(): string { |
709 | | - return join(tmpdir(), 'pythinker-code-original-images'); |
| 712 | + return join(getCacheDir(), 'original-images'); |
710 | 713 | } |
711 | 714 |
|
712 | 715 | /** |
|
0 commit comments