forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathartifactStorage.ts
More file actions
313 lines (282 loc) · 9.34 KB
/
Copy pathartifactStorage.ts
File metadata and controls
313 lines (282 loc) · 9.34 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
// Managed artifact storage — Windows port of the macOS agent runtime's
// artifact-storage.ts (desktop/macos/agent/src/runtime/artifact-storage.ts).
//
// Normalizes adapter-emitted file artifacts into an Omi-owned per-run directory
// (copying external files in, leaving already-managed / user-specified paths
// where they are) and discovers files an adapter wrote into the managed run cwd
// without emitting an explicit reference. Pure fs/path logic — no kernel deps —
// so it unit-tests standalone.
//
// Deviation from macOS: `defaultArtifactRoot`'s final fallback uses a Windows
// path (%APPDATA%\Omi\Artifacts) instead of ~/Library/Application Support. The
// kernel passes an explicit rootDir from the app's userData dir in practice; the
// env overrides (OMI_AGENT_ARTIFACTS_DIR / OMI_AGENT_STATE_DIR) are unchanged.
import { createHash } from 'node:crypto'
import {
copyFileSync,
cpSync,
existsSync,
mkdirSync,
readdirSync,
readFileSync,
statSync,
writeFileSync
} from 'node:fs'
import { homedir } from 'node:os'
import { basename, dirname, join, relative, resolve } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import type { AdapterArtifactReference } from '../codingAgent/interface'
import { isDeniedManagedRunArtifactBasename } from './artifactFilters'
export interface ArtifactStorageScope {
ownerId: string
sessionId: string
runId: string
attemptId: string
}
export interface ArtifactStorageOptions {
rootDir?: string
}
export class OmiArtifactStorage {
readonly rootDir: string
constructor(options: ArtifactStorageOptions = {}) {
this.rootDir = resolve(options.rootDir ?? defaultArtifactRoot())
}
normalizeArtifact(
artifact: AdapterArtifactReference,
scope: ArtifactStorageScope
): AdapterArtifactReference {
if (shouldKeepExternalLocation(artifact)) {
return artifact
}
if (!artifact.uri.startsWith('file://')) {
return artifact
}
const sourcePath = fileURLToPath(artifact.uri)
if (!existsSync(sourcePath)) {
return artifact
}
const sourceStat = statSync(sourcePath)
const destinationDir = this.directoryFor(scope)
mkdirSync(destinationDir, { recursive: true })
const destinationPath = uniqueDestinationPath(
destinationDir,
sanitizeFileName(artifact.displayName || basename(sourcePath) || 'artifact')
)
if (isInside(sourcePath, this.rootDir)) {
const normalizedMetadata = {
...(artifact.metadata ?? {}),
omiManaged: true,
managedPath: sourcePath
}
return {
...artifact,
uri: pathToFileURL(sourcePath).toString(),
displayName: artifact.displayName ?? basename(sourcePath),
sizeBytes: artifact.sizeBytes ?? (sourceStat.isFile() ? sourceStat.size : null),
contentHash: artifact.contentHash ?? (sourceStat.isFile() ? fileHash(sourcePath) : null),
metadata: normalizedMetadata
}
}
if (sourceStat.isDirectory()) {
cpSync(sourcePath, destinationPath, { recursive: true, force: false, errorOnExist: true })
} else {
copyFileSync(sourcePath, destinationPath)
}
const copiedStat = statSync(destinationPath)
const metadata = {
...(artifact.metadata ?? {}),
omiManaged: true,
originalUri: artifact.uri,
managedPath: destinationPath
}
this.writeManifest(destinationDir, {
artifact,
managedUri: pathToFileURL(destinationPath).toString(),
managedPath: destinationPath,
originalUri: artifact.uri,
scope,
copiedAtMs: Date.now()
})
return {
...artifact,
uri: pathToFileURL(destinationPath).toString(),
displayName: artifact.displayName ?? basename(destinationPath),
sizeBytes: artifact.sizeBytes ?? (copiedStat.isFile() ? copiedStat.size : null),
contentHash: artifact.contentHash ?? (copiedStat.isFile() ? fileHash(destinationPath) : null),
metadata
}
}
prepareRunDirectory(scope: ArtifactStorageScope): string {
const directory = this.directoryFor(scope)
mkdirSync(directory, { recursive: true })
return directory
}
isRootDirectory(path: string | undefined | null): boolean {
return path ? resolve(path) === this.rootDir : false
}
discoverRunArtifacts(
scope: ArtifactStorageScope,
existingArtifacts: readonly Pick<AdapterArtifactReference, 'uri'>[] = []
): AdapterArtifactReference[] {
const directory = this.directoryFor(scope)
if (!existsSync(directory)) {
return []
}
const existingUris = new Set(existingArtifacts.map((artifact) => artifact.uri))
const discovered: AdapterArtifactReference[] = []
for (const entry of readdirSync(directory, { withFileTypes: true })) {
if (
entry.name === 'manifest.json' ||
isDeniedManagedRunArtifactBasename(entry.name) ||
(!entry.isFile() && !entry.isDirectory())
) {
continue
}
const path = join(directory, entry.name)
const uri = pathToFileURL(path).toString()
if (existingUris.has(uri)) {
continue
}
const stat = statSync(path)
discovered.push({
kind: entry.isDirectory() ? 'directory' : kindForFileName(entry.name),
role: 'result',
uri,
displayName: entry.name,
mimeType: entry.isDirectory() ? 'inode/directory' : mimeTypeForFileName(entry.name),
contentHash: entry.isDirectory() ? null : fileHash(path),
sizeBytes: entry.isDirectory() ? null : stat.size,
metadata: {
omiManaged: true,
managedPath: path,
discoveredFromRunDirectory: true
}
})
}
return discovered
}
directoryFor(scope: ArtifactStorageScope): string {
return join(
this.rootDir,
sanitizePathComponent(scope.ownerId || 'local'),
sanitizePathComponent(scope.sessionId),
sanitizePathComponent(scope.runId),
sanitizePathComponent(scope.attemptId)
)
}
private writeManifest(directory: string, entry: Record<string, unknown>): void {
const manifestPath = join(directory, 'manifest.json')
let entries: unknown[] = []
if (existsSync(manifestPath)) {
try {
const raw = String(readFileSync(manifestPath))
const parsed = JSON.parse(raw)
entries = Array.isArray(parsed?.artifacts) ? parsed.artifacts : []
} catch {
entries = []
}
}
writeFileSync(manifestPath, `${JSON.stringify({ artifacts: [...entries, entry] }, null, 2)}\n`)
}
}
export function defaultArtifactRoot(env: NodeJS.ProcessEnv = process.env): string {
if (env.OMI_AGENT_ARTIFACTS_DIR) {
return env.OMI_AGENT_ARTIFACTS_DIR
}
if (env.OMI_AGENT_STATE_DIR) {
const runtimeRoot = dirname(env.OMI_AGENT_STATE_DIR)
const bundleComponent = basename(env.OMI_AGENT_STATE_DIR)
return join(dirname(runtimeRoot), 'Artifacts', bundleComponent)
}
const base = env.APPDATA || join(homedir(), 'AppData', 'Roaming')
return join(base, 'Omi', 'Artifacts')
}
function shouldKeepExternalLocation(artifact: AdapterArtifactReference): boolean {
const metadata = artifact.metadata ?? {}
return (
metadata.userSpecifiedPath === true ||
metadata.keepExternalLocation === true ||
metadata.omiManaged === false
)
}
function sanitizePathComponent(value: string): string {
return sanitizeFileName(value).replace(/^\.+$/, 'artifact')
}
function sanitizeFileName(value: string): string {
const clean = value.replace(/[/:\\\0]/g, '-').trim()
return clean.length > 0 ? clean : 'artifact'
}
function uniqueDestinationPath(directory: string, fileName: string): string {
const extIndex = fileName.lastIndexOf('.')
const stem = extIndex > 0 ? fileName.slice(0, extIndex) : fileName
const ext = extIndex > 0 ? fileName.slice(extIndex) : ''
let candidate = join(directory, fileName)
let index = 2
while (existsSync(candidate)) {
candidate = join(directory, `${stem}-${index}${ext}`)
index += 1
}
return candidate
}
function isInside(path: string, root: string): boolean {
const rel = relative(resolve(root), resolve(path))
return rel === '' || (!rel.startsWith('..') && !rel.startsWith('/'))
}
function fileHash(path: string): string {
const hash = createHash('sha256')
hash.update(readFileSync(path))
return `sha256:${hash.digest('hex')}`
}
function kindForFileName(fileName: string): string {
const ext = extension(fileName)
switch (ext) {
case '.md':
return 'markdown'
case '.txt':
return 'text'
case '.json':
return 'json'
case '.csv':
return 'csv'
case '.html':
return 'html'
case '.png':
case '.jpg':
case '.jpeg':
case '.webp':
case '.gif':
return 'image'
default:
return 'file'
}
}
function mimeTypeForFileName(fileName: string): string {
const ext = extension(fileName)
switch (ext) {
case '.md':
return 'text/markdown'
case '.txt':
return 'text/plain'
case '.json':
return 'application/json'
case '.csv':
return 'text/csv'
case '.html':
return 'text/html'
case '.png':
return 'image/png'
case '.jpg':
case '.jpeg':
return 'image/jpeg'
case '.webp':
return 'image/webp'
case '.gif':
return 'image/gif'
default:
return 'application/octet-stream'
}
}
function extension(fileName: string): string {
const index = fileName.lastIndexOf('.')
return index > 0 ? fileName.slice(index).toLowerCase() : ''
}