Open History to see the last commit
1import { mkdir, readFile, stat, writeFile } from 'node:fs/promises'
2import { basename, join, resolve } from 'node:path'
3import { mediaPart, mimeTypeOf } from '@tanstack/ai-harness/media'
4import type { ContentPart } from '@tanstack/ai'
5import type {
6 HarnessSession,
7 MediaRecord,
8 UserInput,
9} from '@tanstack/ai-harness'
10
11/**
12 * An `@path` token: an `@` at the start of the text or after white space,
13 * then a quoted path (`@"my cat.png"`) or the text up to the next white
14 * space. The white space before the `@` is part of the match, so it goes
15 * out of the text with the token.
16 */
17const TOKEN = /(^|\s)@(?:"([^"]+)"|(\S+))/g
18
19/** The path of a token. One of the two groups always matches. */
20function pathOf(token: RegExpExecArray) {
21 return token[2] ?? token[3] ?? ''
22}
23
24/**
25 * The file that `path` names, when it is a readable regular file, else
26 * `undefined`. A file with an extension that `mimeTypeOf` does not know
27 * throws.
28 */
29async function readToken(path: string, cwd: string) {
30 const file = resolve(cwd, path)
31 const info = await stat(file).catch(() => undefined)
32 if (!info?.isFile()) return undefined
33 const name = basename(file)
34 const mimeType = mimeTypeOf(name)
35 if (mimeType === undefined) {
36 throw new Error(
37 `Cannot attach ${name}: the file type is not known. To send the path as text, remove the @.`,
38 )
39 }
40 // ponytail: reads the whole file, and the store refuses it after that when
41 // it is over `media.maxBytes`. Stream it when big local files matter.
42 const bytes = await readFile(file).catch(() => undefined)
43 return bytes === undefined ? undefined : { bytes, mimeType, name }
44}
45
46/**
47 * The message for `text`, with each `@path` token that names a file sent as
48 * a stored media part. The token goes out of the text. Any other `@` stays
49 * as typed: `me@acme.dev`, `@types/node`, or a path with no file. Returns
50 * `text` as it is when no token names a file.
51 *
52 * Throws for a file of a type it does not know, before it stores a file.
53 * `putMedia` throws a `MediaError` for a file over `media.maxBytes`, or of a
54 * kind that the harness does not take. The message does not go then.
55 */
56export async function attach(
57 session: HarnessSession,
58 text: string,
59 options: { cwd: string },
60) {
61 const tokens = [...text.matchAll(TOKEN)]
62 // Read every file first, so a bad file stops the send before a store.
63 const files = await Promise.all(
64 tokens.map((token) => readToken(pathOf(token), options.cwd)),
65 )
66 if (files.every((file) => file === undefined)) return text
67
68 const media: Array<ContentPart> = []
69 let rest = ''
70 let end = 0
71 for (const [index, token] of tokens.entries()) {
72 const file = files[index]
73 if (file === undefined) continue
74 rest += text.slice(end, token.index)
75 end = token.index + token[0].length
76 const record = await session.putMedia({
77 body: file.bytes,
78 mimeType: file.mimeType,
79 name: file.name,
80 })
81 media.push(mediaPart(record))
82 }
83 const content = `${rest}${text.slice(end)}`.trim()
84 const input: UserInput =
85 content === '' ? media : [{ type: 'text', content }, ...media]
86 return input
87}
88
89function isTaken(error: unknown) {
90 return error instanceof Error && 'code' in error && error.code === 'EEXIST'
91}
92
93/**
94 * Write the bytes of a media file into `dir`, and return the path. The file
95 * gets the name of the record, with `-1`, `-2`, ... before the extension
96 * when that name is taken. It never overwrites a file. A name with a folder
97 * in it (`/`, `\`, a drive `:`), `.`, or `..` is refused, because a name can
98 * come from an upload.
99 */
100export async function saveMedia(
101 session: HarnessSession,
102 record: Pick<MediaRecord, 'id' | 'name'>,
103 dir: string,
104) {
105 const { name } = record
106 const isPlainName =
107 name !== '' && name !== '.' && name !== '..' && !/[\\/:]/.test(name)
108 if (!isPlainName) {
109 throw new Error(
110 `Cannot save ${JSON.stringify(name)}: it is not a plain file name.`,
111 )
112 }
113 const bytes = await session.loadMedia({ id: record.id })
114 await mkdir(dir, { recursive: true })
115 const dot = name.lastIndexOf('.')
116 const stem = dot > 0 ? name.slice(0, dot) : name
117 const extension = dot > 0 ? name.slice(dot) : ''
118 for (let count = 0; ; count += 1) {
119 const path = join(dir, count === 0 ? name : `${stem}-${count}${extension}`)
120 try {
121 // `wx` fails when the file is there, so a file is never overwritten.
122 await writeFile(path, bytes, { flag: 'wx' })
123 return path
124 } catch (error) {
125 if (!isTaken(error)) throw error
126 }
127 }
128}
129
130/**
131 * Save a media file with `saveMedia`, and get the line that says where it
132 * went, or why it was not saved. It does not throw.
133 */
134export async function saveMediaLine(
135 session: HarnessSession,
136 record: Pick<MediaRecord, 'id' | 'name' | 'kind'>,
137 dir: string,
138) {
139 try {
140 const path = await saveMedia(session, record, dir)
141 return { path, text: `[${record.kind} saved: ${path}]` }
142 } catch (error) {
143 const reason = error instanceof Error ? error.message : String(error)
144 return { text: `[${record.kind} not saved: ${reason}]` }
145 }
146}
147
148/**
149 * The default media folder of a harness, relative to the working folder:
150 * the name as a safe folder name, then `-media`. `acme/coder` saves into
151 * `acme-coder-media`.
152 */
153export function defaultMediaDir(harnessName: string) {
154 const safe = harnessName.replace(/[^\w.-]+/g, '-').replace(/^[-.]+|-+$/g, '')
155 return `${safe || 'harness'}-media`
156}