/ utils / tempfile.ts
tempfile.ts
 1  import { createHash, randomUUID } from 'crypto'
 2  import { tmpdir } from 'os'
 3  import { join } from 'path'
 4  
 5  /**
 6   * Generate a temporary file path.
 7   *
 8   * @param prefix Optional prefix for the temp file name
 9   * @param extension Optional file extension (defaults to '.md')
10   * @param options.contentHash When provided, the identifier is derived from a
11   *   SHA-256 hash of this string (first 16 hex chars). This produces a path
12   *   that is stable across process boundaries — any process with the same
13   *   content will get the same path. Use this when the path ends up in content
14   *   sent to the Anthropic API (e.g., sandbox deny lists in tool descriptions),
15   *   because a random UUID would change on every subprocess spawn and
16   *   invalidate the prompt cache prefix.
17   * @returns Temp file path
18   */
19  export function generateTempFilePath(
20    prefix: string = 'claude-prompt',
21    extension: string = '.md',
22    options?: { contentHash?: string },
23  ): string {
24    const id = options?.contentHash
25      ? createHash('sha256')
26          .update(options.contentHash)
27          .digest('hex')
28          .slice(0, 16)
29      : randomUUID()
30    return join(tmpdir(), `${prefix}-${id}${extension}`)
31  }