meshy-dsh 0.3.7 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/tasks.js ADDED
@@ -0,0 +1,687 @@
1
+ // Task journal reading, a cache of CLI `get` reads, account library aggregation, bounded
2
+ // workspace GLB discovery, safe Meshy asset streaming, and the per-workspace asset index.
3
+ // The CLI runner and its resource catalog are passed in, so this module never spawns a process
4
+ // and keeps no list of the CLI's commands.
5
+ import { createReadStream } from 'node:fs'
6
+ import { mkdir, readdir, readFile, realpath, rename, stat, writeFile } from 'node:fs/promises'
7
+ import { randomUUID } from 'node:crypto'
8
+ import { dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'
9
+ import { Readable } from 'node:stream'
10
+
11
+ /** Where the CLI kept its operation journal before 0.4.0: one for the whole workspace. */
12
+ export const JOURNAL = ['.meshy', 'operations']
13
+ /** Since 0.4.0 each chat has its own CLI state directory (`DSH_MESHY_STATE_DIR`) under here. */
14
+ export const SESSIONS_DIR = ['.meshy', 'sessions']
15
+ /** Hidden folder where task models may also be stored. */
16
+ export const MESHY_MODELS_DIR = ['.meshy', 'models']
17
+ /** Per-workspace index of the files each task saved (task id -> asset entry). */
18
+ export const ASSET_INDEX = ['.meshy', 'dsh-assets.json']
19
+ const MAX_ASSETS = 500
20
+ /** Files remembered for one task. */
21
+ const MAX_FILES = 64
22
+ /** How well a saved file previews: a GLB, then a 3MF, then an image, then anything else. */
23
+ const FILE_RANKS = [/\.glb$/i, /\.3mf$/i, /\.(?:png|jpe?g|webp)$/i]
24
+ const fileRank = (file) => {
25
+ const i = FILE_RANKS.findIndex((re) => re.test(file))
26
+ return i < 0 ? FILE_RANKS.length : i
27
+ }
28
+
29
+ /** API assets live this long on non-Enterprise plans (public docs: Asset Retention). */
30
+ export const RETENTION_DAYS = 3
31
+ const RETENTION_MS = RETENTION_DAYS * 24 * 3600_000
32
+
33
+ /**
34
+ * What a task is expected to produce before its output says: `image` for a resource whose name
35
+ * ends in "image" (the CLI's 2D generators), `model` for any other. Only a running task needs it.
36
+ */
37
+ export function kindOfResource(resource) {
38
+ return /(?:^|-)image$/.test(String(resource ?? '')) ? 'image' : 'model'
39
+ }
40
+
41
+ /**
42
+ * What a task produced, read from its output: `model` (model files), `image` (pictures only),
43
+ * `none` (it finished with neither, such as a printability report), or null while unknown.
44
+ */
45
+ export function outputKind(view) {
46
+ if (!view) return null
47
+ if (view.glb || view.formats?.length > 0 || view.produced === 'model') return 'model'
48
+ if (view.imageUrls?.length > 0 || view.produced === 'image') return 'image'
49
+ return view.status === 'SUCCEEDED' ? 'none' : null
50
+ }
51
+
52
+ const filled = (v) => typeof v === 'string' && v.length > 0
53
+
54
+ /**
55
+ * What a task's output fields hold, whatever their URLs: `model`, `image` or null. A URL this
56
+ * plugin will not fetch still says what the task made, so it never reads as having made nothing.
57
+ */
58
+ function producedOf(task) {
59
+ const urls = task?.model_urls && typeof task.model_urls === 'object' ? Object.values(task.model_urls) : []
60
+ const result = task?.result && typeof task.result === 'object' ? task.result : {}
61
+ if (urls.some(filled) || Object.entries(result).some(([k, v]) => /_glb_url$/.test(k) && filled(v))) return 'model'
62
+ if (Array.isArray(task?.image_urls) && task.image_urls.some(filled)) return 'image'
63
+ return null
64
+ }
65
+
66
+ const ASSET_KINDS = new Set(['model', 'image', 'none'])
67
+
68
+ /**
69
+ * The account library's default lists (the left Meshy page): the generations people browse.
70
+ * Only those the CLI still lists as task resources with `list` are read.
71
+ */
72
+ export const LIBRARY_RESOURCES = ['text-to-3d', 'image-to-3d', 'multi-image-to-3d', 'retexture', 'rigging', 'animate', 'text-to-image', 'image-to-image']
73
+
74
+ /** A task id as the API issues them; never starts with "-", so it cannot read as an option. */
75
+ export const TASK_ID = /^[A-Za-z0-9][A-Za-z0-9-]{7,63}$/
76
+
77
+ /** Statuses after which a task never changes again. */
78
+ export const TERMINAL = new Set(['SUCCEEDED', 'FAILED', 'CANCELED', 'EXPIRED'])
79
+
80
+ /** Maximum GLB file size streamed for 3D previews (256 MiB). */
81
+ export const MAX_GLB = 256 << 20
82
+
83
+ /** Bounded workspace walk limits for `.glb` discovery. */
84
+ export const MAX_DEPTH = 6
85
+ export const MAX_MODELS = 200
86
+ const MAX_DIRS = 2000
87
+ const SKIP_DIRS = new Set([
88
+ 'node_modules', '.git', 'bower_components', 'vendor', 'target', 'build', 'dist', 'out', 'venv', '__pycache__',
89
+ ])
90
+ /** Model files the viewer opens: GLB, and 3MF print files (a multi-color print, say). */
91
+ const GLB_RE = /\.(?:glb|3mf)$/i
92
+
93
+ /**
94
+ * The CLI state directory of one chat: `<workspace>/.meshy/sessions/<id>`. The id is made
95
+ * path-safe, so it can never leave that folder.
96
+ */
97
+ export function sessionStateDir(workspace, sessionId) {
98
+ const safe = String(sessionId ?? '').replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^\.+/, '_').slice(0, 120) || 'unknown'
99
+ return join(workspace, ...SESSIONS_DIR, safe)
100
+ }
101
+
102
+ // Record names as the CLI writes them (a UUID, or a caller's --operation-id made path-safe).
103
+ const OPERATION_FILE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,119}\.json$/
104
+ const MAX_RECORD = 64 << 10
105
+ const MAX_PARSED = 4000
106
+ /** Parsed records by path, kept while the file's mtime and size stay the same. */
107
+ const parsed = new Map()
108
+
109
+ function normalize(r) {
110
+ if (r?.schema_version !== 1 || typeof r.operation_id !== 'string' || typeof r.resource !== 'string' || typeof r.state !== 'string') return null
111
+ const startedAt = Date.parse(r.started_at)
112
+ if (!Number.isFinite(startedAt)) return null
113
+ return {
114
+ operationId: r.operation_id,
115
+ resource: r.resource,
116
+ state: r.state,
117
+ taskId: typeof r.task_id === 'string' ? r.task_id : null,
118
+ startedAt,
119
+ error: typeof r.error === 'string' ? r.error : null,
120
+ // The API the CLI submitted to; a task from another origin cannot be read with this sign-in.
121
+ apiOrigin: typeof r.api_origin === 'string' && r.api_origin ? r.api_origin : null,
122
+ }
123
+ }
124
+
125
+ /**
126
+ * The operation records in `dir` started at or after `since` (epoch ms), newest first. A missing
127
+ * directory, an unreadable file or a malformed record is skipped, never thrown.
128
+ */
129
+ export async function readJournal(dir, { since = 0, limit = 50 } = {}) {
130
+ let names
131
+ try {
132
+ names = await readdir(dir)
133
+ } catch {
134
+ return []
135
+ }
136
+ if (parsed.size > MAX_PARSED) parsed.clear()
137
+ const records = []
138
+ await Promise.all(names.filter((name) => OPERATION_FILE.test(name)).map(async (name) => {
139
+ const file = join(dir, name)
140
+ let info
141
+ try {
142
+ info = await stat(file)
143
+ } catch {
144
+ return
145
+ }
146
+ if (!info.isFile() || info.size > MAX_RECORD || info.mtimeMs < since) return
147
+ let hit = parsed.get(file)
148
+ if (!hit || hit.mtimeMs !== info.mtimeMs || hit.size !== info.size) {
149
+ let record = null
150
+ try {
151
+ record = normalize(JSON.parse(await readFile(file, 'utf8')))
152
+ } catch {
153
+ // Half-written or malformed record: skip it this poll.
154
+ }
155
+ hit = { mtimeMs: info.mtimeMs, size: info.size, record }
156
+ parsed.set(file, hit)
157
+ }
158
+ if (hit.record && hit.record.startedAt >= since) records.push(hit.record)
159
+ }))
160
+ records.sort((a, b) => b.startedAt - a.startedAt || (a.operationId < b.operationId ? -1 : a.operationId > b.operationId ? 1 : 0))
161
+ return records.slice(0, limit)
162
+ }
163
+
164
+ const isAssetHost = (host) => ['meshy.ai', 'meshy.cn'].some((domain) => host === domain || host.endsWith(`.${domain}`))
165
+
166
+ /** An https URL on Meshy's own hosts, or null: the only URLs shown or fetched. */
167
+ export function assetUrl(value) {
168
+ if (typeof value !== 'string') return null
169
+ try {
170
+ const url = new URL(value)
171
+ return url.protocol === 'https:' && !url.username && !url.password && isAssetHost(url.hostname) ? url.href : null
172
+ } catch {
173
+ return null
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Every GLB a finished task produced, by variant: `model` (model_urls.glb), `rigged`
179
+ * (rigged_character_glb_url), `animation` (animation_glb_url), and one per basic animation
180
+ * (`walking`, `running`, ...). Armature-only GLBs carry no mesh and are left out.
181
+ */
182
+ export function glbsOf(task) {
183
+ const out = {}
184
+ const put = (variant, value) => {
185
+ const url = assetUrl(value)
186
+ if (url && !out[variant] && !Object.values(out).includes(url)) out[variant] = url
187
+ }
188
+ put('model', task?.model_urls?.glb)
189
+ const result = task?.result && typeof task.result === 'object' ? task.result : {}
190
+ put('rigged', result.rigged_character_glb_url)
191
+ put('animation', result.animation_glb_url)
192
+ const animations = result.basic_animations && typeof result.basic_animations === 'object' ? result.basic_animations : {}
193
+ for (const [key, value] of Object.entries(animations)) {
194
+ const m = /^([a-z0-9]+)_glb_url$/.exec(key)
195
+ if (m) put(m[1], value)
196
+ }
197
+ for (const [key, value] of Object.entries(result)) {
198
+ const m = /^([a-z0-9_]+?)_glb_url$/.exec(key)
199
+ if (m && !m[1].includes('armature')) put(m[1], value)
200
+ }
201
+ return out
202
+ }
203
+
204
+ /** Variants in the order a viewer should prefer: a playing animation before a bind pose. */
205
+ const GLB_PREFERENCE = ['model', 'animation', 'walking', 'running', 'rigged']
206
+
207
+ /** The GLB to show first: the model, else an animated character, else the rigged one. */
208
+ function glbOf(task, glbs = glbsOf(task)) {
209
+ for (const variant of GLB_PREFERENCE) if (glbs[variant]) return glbs[variant]
210
+ return Object.values(glbs)[0] ?? null
211
+ }
212
+
213
+ function formatsOf(task, glb) {
214
+ const formats = []
215
+ const urls = task?.model_urls && typeof task.model_urls === 'object' ? task.model_urls : {}
216
+ for (const [fmt, value] of Object.entries(urls)) {
217
+ const key = fmt.toLowerCase()
218
+ if (/^[a-z0-9]{2,8}$/.test(key) && assetUrl(value)) formats.push(key)
219
+ }
220
+ if (glb && !formats.includes('glb')) formats.unshift('glb')
221
+ return formats
222
+ }
223
+
224
+ const num = (v) => typeof v === 'number' && Number.isFinite(v) ? v : null
225
+ const text = (v) => typeof v === 'string' && v ? v : null
226
+
227
+ /** Epoch ms from a number (ms) or an ISO string, else null. */
228
+ function epochMs(value) {
229
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) return value
230
+ if (typeof value === 'string' && value) {
231
+ const parsed = Date.parse(value)
232
+ if (Number.isFinite(parsed)) return parsed
233
+ }
234
+ return null
235
+ }
236
+
237
+ /** Normalized task view extracted from a meshy-cli task object. `glb` stays host-side. */
238
+ export function viewOf(task) {
239
+ if (!task || typeof task !== 'object') return null
240
+ const glbs = glbsOf(task)
241
+ const glb = glbOf(task, glbs)
242
+ const imageUrls = Array.isArray(task.image_urls) ? task.image_urls.map(assetUrl).filter(Boolean) : []
243
+ return {
244
+ taskId: text(task.task_id) ?? text(task.id),
245
+ status: text(task.status),
246
+ progress: num(task.progress),
247
+ name: text(task.name),
248
+ prompt: text(task.prompt) ?? text(task.raw?.prompt) ?? text(task.texture_prompt) ?? text(task.text_style_prompt) ?? text(task.name),
249
+ type: text(task.type),
250
+ createdAt: num(task.created_at),
251
+ finishedAt: num(task.finished_at),
252
+ expiresAt: epochMs(task.expires_at),
253
+ credits: num(task.consumed_credits),
254
+ thumbnail: assetUrl(task.thumbnail_url) ?? imageUrls[0] ?? null,
255
+ glb,
256
+ glbs,
257
+ // A print file (`model_urls['3mf']`), shown when the task has no GLB; host-side like `glb`.
258
+ printFile: assetUrl(task?.model_urls?.['3mf']) ?? assetUrl(task?.model_urls?.['3MF']),
259
+ // Public: which GLB variants exist (the URLs stay host-side).
260
+ variants: Object.keys(glbs),
261
+ formats: formatsOf(task, glb),
262
+ imageUrls,
263
+ produced: producedOf(task),
264
+ parentTaskId: text(task.preview_task_id) ?? text(task.input_task_id) ?? text(task.raw?.preview_task_id) ?? text(task.raw?.input_task_id) ?? null,
265
+ error: text(task.task_error?.message),
266
+ }
267
+ }
268
+
269
+ /**
270
+ * Live task states read through `cli(args)` (which resolves to the CLI's JSON envelope).
271
+ * A running task is cached for `liveMs`, a terminal task for `doneMs`, and concurrent asks share
272
+ * one in-flight call (max `concurrency` simultaneous CLI invocations).
273
+ */
274
+ export function createTaskStates({ cli, catalog, now = Date.now, liveMs = 4000, doneMs = 10 * 60_000, concurrency = 2 }) {
275
+ const cache = new Map()
276
+ let active = 0
277
+ const waiting = []
278
+ const acquire = () => new Promise((resolveAcquire) => {
279
+ if (active < concurrency) { active++; resolveAcquire() } else waiting.push(resolveAcquire)
280
+ })
281
+ const release = () => {
282
+ const next = waiting.shift()
283
+ if (next) next()
284
+ else active--
285
+ }
286
+
287
+ async function read(args, signal) {
288
+ await acquire()
289
+ try {
290
+ const out = await cli(args, signal ? { signal } : undefined)
291
+ if (!out?.ok) {
292
+ const failed = text(out?.error?.message) ?? 'the Meshy CLI could not read this task'
293
+ // A 404 never turns into a task later (another account or API), so it is cached as final.
294
+ const notFound = out?.error?.code === 'not_found' || /\bmeshy api 404\b/.test(failed)
295
+ return notFound ? { failed, notFound: true } : { failed }
296
+ }
297
+ return { view: viewOf(out.result?.task) }
298
+ } finally {
299
+ release()
300
+ }
301
+ }
302
+
303
+ /**
304
+ * Read a task's state: `{ view }`, `{ failed }` (plus `notFound: true` on a 404, kept as long as
305
+ * a finished task), or undefined when the CLI lists no such task resource or the id is malformed.
306
+ */
307
+ async function get(resource, taskId, { fresh = false, signal } = {}) {
308
+ const args = await catalog.taskArgs(resource, 'get', taskId)
309
+ if (!args) return undefined
310
+ const key = `${resource} ${taskId}`
311
+ const hit = cache.get(key)
312
+ if (!fresh && hit?.state) {
313
+ const ttl = TERMINAL.has(hit.state.view?.status) || hit.state.notFound ? doneMs : liveMs
314
+ if (now() - hit.at < ttl) return hit.state
315
+ }
316
+ if (!fresh && hit?.reading) return hit.reading
317
+ const reading = read(args, signal)
318
+ .catch((err) => {
319
+ if (err?.name === 'AbortError' || signal?.aborted) throw err
320
+ return { failed: String(err?.message ?? err) }
321
+ })
322
+ .then((state) => {
323
+ const kept = state.failed && hit?.state?.view ? { ...hit.state, failed: state.failed } : state
324
+ cache.set(key, { at: now(), state: kept })
325
+ return kept
326
+ })
327
+ if (!fresh) cache.set(key, { ...hit, reading })
328
+ return reading
329
+ }
330
+
331
+ function invalidate(resource, taskId) {
332
+ cache.delete(`${resource} ${taskId}`)
333
+ }
334
+
335
+ return { get, invalidate }
336
+ }
337
+
338
+ function isAuthError(envelope) {
339
+ if (!envelope || envelope.ok) return false
340
+ const code = String(envelope.error?.code ?? '').toLowerCase()
341
+ const msg = String(envelope.error?.message ?? '').toLowerCase()
342
+ return code === 'auth' || code === 'unauthorized' || /not signed in|unauthenticated|sign in|api key|credential|401/.test(msg)
343
+ }
344
+
345
+ /**
346
+ * When a listed task's files stop being downloadable: its `expires_at`, else (text-to-3d tasks and
347
+ * older records carry none) three days after it finished or was created. Null when unknown.
348
+ */
349
+ export function expiryOf(view) {
350
+ if (!view) return null
351
+ if (typeof view.expiresAt === 'number') return view.expiresAt
352
+ const ref = view.finishedAt ?? view.createdAt
353
+ return typeof ref === 'number' && ref > 0 ? ref + RETENTION_MS : null
354
+ }
355
+
356
+ /**
357
+ * Aggregated recent account library reader across `LIBRARY_RESOURCES` (or one requested listable
358
+ * resource), cached for 60s. Tasks past the API's asset retention are
359
+ * dropped: their thumbnails and models no longer load.
360
+ */
361
+ export function createLibraryReader({ cli, catalog, now = Date.now, ttlMs = 60_000 }) {
362
+ const cache = new Map()
363
+
364
+ async function list({ resource, limit = 24, refresh = false } = {}) {
365
+ const clamped = Math.max(1, Math.min(30, Number.isInteger(limit) ? limit : Number.parseInt(String(limit ?? 24), 10) || 24))
366
+ const listable = await catalog.listable()
367
+ let resources
368
+ if (resource) {
369
+ if (!listable.has(resource)) {
370
+ throw Object.assign(new Error(`unsupported library resource: ${resource}`), { statusCode: 400 })
371
+ }
372
+ resources = [resource]
373
+ } else {
374
+ resources = LIBRARY_RESOURCES.filter((name) => listable.has(name))
375
+ }
376
+ const key = `${resources.join(',')}|${clamped}`
377
+ const hit = cache.get(key)
378
+ if (!refresh && hit && now() - hit.at < ttlMs) return hit.data
379
+
380
+ // Newest first from the API; a full page per resource leaves enough after the expiry filter.
381
+ const pageSize = 30
382
+ const results = await Promise.all(resources.map(async (resName) => {
383
+ const cmd = await catalog.taskCommand(resName)
384
+ const out = await cli([...cmd, 'list', '--page-size', String(pageSize)]).catch((err) => ({ ok: false, error: { message: String(err?.message ?? err) } }))
385
+ return { resName, out }
386
+ }))
387
+
388
+ if (results.every(({ out }) => isAuthError(out))) {
389
+ const data = { authenticated: false, items: [], retentionDays: RETENTION_DAYS }
390
+ cache.set(key, { at: now(), data })
391
+ return data
392
+ }
393
+
394
+ const at = now()
395
+ // The image-to-image list also returns text-to-image tasks (their `type` says so): an item
396
+ // belongs to the list its type names, and each task appears once.
397
+ const seen = new Set()
398
+ const items = []
399
+ for (const { resName, out } of results) {
400
+ if (!out?.ok) continue
401
+ const listItems = Array.isArray(out.result?.items) ? out.result.items : []
402
+ for (const rawItem of listItems) {
403
+ const v = viewOf(rawItem)
404
+ if (!v?.taskId || seen.has(v.taskId)) continue
405
+ if (v.type && v.type !== resName && listable.has(v.type)) continue
406
+ const expiresAt = expiryOf(v)
407
+ if (expiresAt !== null && expiresAt <= at) continue
408
+ const kind = outputKind(v) ?? kindOfResource(resName)
409
+ if (kind === 'none') continue
410
+ seen.add(v.taskId)
411
+ items.push({
412
+ resource: resName,
413
+ kind,
414
+ taskId: v.taskId,
415
+ status: v.status,
416
+ progress: v.progress,
417
+ name: v.name,
418
+ prompt: v.prompt,
419
+ type: v.type,
420
+ createdAt: v.createdAt,
421
+ finishedAt: v.finishedAt,
422
+ expiresAt,
423
+ credits: v.credits,
424
+ thumbnail: v.thumbnail,
425
+ model: Boolean(v.glb || v.printFile),
426
+ variants: v.variants,
427
+ formats: v.formats,
428
+ })
429
+ }
430
+ }
431
+
432
+ items.sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0) || (a.taskId < b.taskId ? -1 : a.taskId > b.taskId ? 1 : 0))
433
+ const data = { authenticated: true, items: items.slice(0, clamped), retentionDays: RETENTION_DAYS }
434
+ cache.set(key, { at: now(), data })
435
+ return data
436
+ }
437
+
438
+ function clear() {
439
+ cache.clear()
440
+ }
441
+
442
+ return { list, clear }
443
+ }
444
+
445
+ /**
446
+ * Bounded workspace walk of `.glb` files (max 200 files, max depth 6, skipping dependency/build
447
+ * and hidden dirs except `.meshy/models`), never following symlinks, sorted newest first.
448
+ */
449
+ export async function listModels(cwd) {
450
+ if (typeof cwd !== 'string' || !cwd) return []
451
+ let root
452
+ try {
453
+ root = await realpath(cwd)
454
+ } catch {
455
+ return []
456
+ }
457
+ const seen = new Set()
458
+ const files = []
459
+ let dirs = 0
460
+
461
+ const visit = async (dir, rel, depth) => {
462
+ if (++dirs > MAX_DIRS) return
463
+ let entries
464
+ try {
465
+ entries = await readdir(dir, { withFileTypes: true })
466
+ } catch {
467
+ return
468
+ }
469
+ for (const entry of entries) {
470
+ if (entry.isSymbolicLink()) continue
471
+ const path = rel ? `${rel}/${entry.name}` : entry.name
472
+ if (entry.isFile() && GLB_RE.test(entry.name)) {
473
+ if (!seen.has(path)) { seen.add(path); files.push(path) }
474
+ } else if (entry.isDirectory() && depth < MAX_DEPTH && !entry.name.startsWith('.') && !SKIP_DIRS.has(entry.name)) {
475
+ await visit(join(dir, entry.name), path, depth + 1)
476
+ }
477
+ }
478
+ }
479
+
480
+ await visit(root, '', 0)
481
+ // Also include .meshy/models (the one hidden folder allowed by contract).
482
+ try {
483
+ const meshyModels = join(root, ...MESHY_MODELS_DIR)
484
+ const entries = await readdir(meshyModels, { withFileTypes: true })
485
+ for (const entry of entries) {
486
+ if (!entry.isSymbolicLink() && entry.isFile() && GLB_RE.test(entry.name)) {
487
+ const path = `${MESHY_MODELS_DIR.join('/')}/${entry.name}`
488
+ if (!seen.has(path)) { seen.add(path); files.push(path) }
489
+ }
490
+ }
491
+ } catch {
492
+ // No .meshy/models directory yet.
493
+ }
494
+
495
+ const models = (await Promise.all(files.map(async (file) => {
496
+ const info = await stat(join(root, ...file.split('/'))).catch(() => null)
497
+ if (!info?.isFile()) return null
498
+ return { file, size: info.size, mtimeMs: Math.round(info.mtimeMs) }
499
+ }))).filter(Boolean)
500
+
501
+ models.sort((a, b) => b.mtimeMs - a.mtimeMs || a.file.localeCompare(b.file))
502
+ return models.slice(0, MAX_MODELS)
503
+ }
504
+
505
+ function isInsideRoot(root, candidate) {
506
+ return candidate === root || candidate.startsWith(root.endsWith(sep) ? root : root + sep)
507
+ }
508
+
509
+ /**
510
+ * Resolve an existing file inside `workspace` with `realpath` containment checking.
511
+ * Refuses path traversal, null bytes, symlinks escaping `workspace`, and disallowed extensions.
512
+ */
513
+ export async function resolveWorkspaceFile(workspace, inputPath, { allowedExts } = {}) {
514
+ if (typeof workspace !== 'string' || !workspace) throw Object.assign(new Error('workspace is unavailable'), { statusCode: 400 })
515
+ if (typeof inputPath !== 'string' || !inputPath.trim() || inputPath.includes('\0')) {
516
+ throw Object.assign(new Error('invalid file path'), { statusCode: 400 })
517
+ }
518
+ const root = await realpath(workspace)
519
+ const candidate = isAbsolute(inputPath) ? resolve(inputPath) : resolve(root, inputPath)
520
+ if (!isInsideRoot(root, candidate)) {
521
+ throw Object.assign(new Error('file path escapes the session workspace'), { statusCode: 400 })
522
+ }
523
+ let real
524
+ try {
525
+ real = await realpath(candidate)
526
+ } catch {
527
+ throw Object.assign(new Error(`file not found: ${inputPath}`), { statusCode: 404 })
528
+ }
529
+ if (!isInsideRoot(root, real) || real === root) {
530
+ throw Object.assign(new Error('file path escapes the session workspace'), { statusCode: 400 })
531
+ }
532
+ const info = await stat(real)
533
+ if (!info.isFile()) throw Object.assign(new Error('path is not a regular file'), { statusCode: 400 })
534
+ const ext = extname(real).toLowerCase()
535
+ if (allowedExts && !allowedExts.has(ext)) {
536
+ throw Object.assign(new Error(`unsupported file extension: ${ext || '(none)'}`), { statusCode: 400 })
537
+ }
538
+ const rel = relative(root, real).split(sep).join('/')
539
+ return { root, abs: real, rel, size: info.size }
540
+ }
541
+
542
+ /**
543
+ * Stream a local `.glb` file from the session workspace with strict realpath + size checking.
544
+ */
545
+ export async function serveWorkspaceModel(workspace, relFile, { max = MAX_GLB } = {}) {
546
+ const { abs, size } = await resolveWorkspaceFile(workspace, relFile, { allowedExts: new Set(['.glb', '.3mf']) })
547
+ if (size > max) {
548
+ throw Object.assign(new Error('the model is too large to preview'), { statusCode: 413, tooLarge: size })
549
+ }
550
+ const stream = Readable.toWeb(createReadStream(abs))
551
+ return new Response(stream, {
552
+ headers: { 'content-type': modelType(abs), 'cache-control': 'no-store' },
553
+ })
554
+ }
555
+
556
+ const modelType = (name) => (/\.3mf(?:$|\?)/i.test(name) ? 'model/3mf' : 'model/gltf-binary')
557
+
558
+ /**
559
+ * Fetch a GLB (or 3MF) from Meshy's asset hosts as a byte stream, refusing anything over `max` bytes.
560
+ * Resolves to a Response for the browser, or throws.
561
+ */
562
+ export async function fetchModel(url, { max = MAX_GLB, fetchImpl = fetch, timeoutMs = 120_000 } = {}) {
563
+ const target = assetUrl(url)
564
+ if (!target) throw Object.assign(new Error('not a Meshy asset URL'), { statusCode: 400 })
565
+ const res = await fetchImpl(target, { signal: AbortSignal.timeout(timeoutMs) })
566
+ if (!res.ok || !res.body) throw Object.assign(new Error(`the model download failed (HTTP ${res.status})`), { statusCode: 502 })
567
+ const declared = Number(res.headers.get('content-length'))
568
+ if (Number.isFinite(declared) && declared > max) {
569
+ throw Object.assign(new Error('the model is too large to preview'), { statusCode: 413, tooLarge: declared })
570
+ }
571
+ let seen = 0
572
+ const capped = res.body.pipeThrough(new TransformStream({
573
+ transform(chunk, controller) {
574
+ seen += chunk.byteLength
575
+ if (seen > max) controller.error(new Error('the model is too large to preview'))
576
+ else controller.enqueue(chunk)
577
+ },
578
+ }))
579
+ return new Response(capped, { headers: { 'content-type': modelType(new URL(target).pathname), 'cache-control': 'no-store' } })
580
+ }
581
+
582
+ // ---------------------------------------------------------------------------
583
+ // Asset index
584
+ // ---------------------------------------------------------------------------
585
+
586
+ /** Serialize index writes per workspace so concurrent jobs never lose each other's entries. */
587
+ const indexLocks = new Map()
588
+
589
+ function indexPath(root) {
590
+ return join(root, ...ASSET_INDEX)
591
+ }
592
+
593
+ async function rootOf(workspace) {
594
+ if (typeof workspace !== 'string' || !workspace) return null
595
+ return realpath(workspace).catch(() => null)
596
+ }
597
+
598
+ const OPTIONAL_FACTS = ['prompt', 'stage', 'callId', 'jobId']
599
+
600
+ /** The optional string facts an index entry may carry (the submitting call, its job, the prompt). */
601
+ function optionalFacts(entry) {
602
+ const out = {}
603
+ for (const key of OPTIONAL_FACTS) {
604
+ const value = text(entry?.[key])
605
+ if (value) out[key] = key === 'prompt' ? value.slice(0, 800) : value.slice(0, 200)
606
+ }
607
+ return out
608
+ }
609
+
610
+ /**
611
+ * The asset index of a workspace: `{ [taskId]: { resource, kind, title, file, files, createdAt } }`,
612
+ * plus `prompt`, `stage`, `callId` and `jobId` when the task was submitted here.
613
+ */
614
+ export async function readAssetIndex(workspace) {
615
+ const root = await rootOf(workspace)
616
+ if (!root) return {}
617
+ try {
618
+ const raw = JSON.parse(await readFile(indexPath(root), 'utf8'))
619
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}
620
+ const out = {}
621
+ for (const [id, entry] of Object.entries(raw)) {
622
+ if (!TASK_ID.test(id) || !entry || typeof entry !== 'object') continue
623
+ out[id] = {
624
+ resource: text(entry.resource),
625
+ kind: ASSET_KINDS.has(entry.kind) ? entry.kind : null,
626
+ title: text(entry.title),
627
+ file: text(entry.file),
628
+ files: Array.isArray(entry.files) ? entry.files.filter((f) => typeof f === 'string') : [],
629
+ createdAt: num(entry.createdAt),
630
+ ...optionalFacts(entry),
631
+ }
632
+ }
633
+ return out
634
+ } catch {
635
+ return {}
636
+ }
637
+ }
638
+
639
+ /**
640
+ * Record (or update) the files a task saved, atomically (temp file + rename), keeping the newest
641
+ * 500 entries. Never throws: the index is a convenience, the files are already on disk.
642
+ */
643
+ export async function recordAsset(workspace, taskId, entry, { now = Date.now } = {}) {
644
+ const root = await rootOf(workspace)
645
+ if (!root || typeof taskId !== 'string' || !TASK_ID.test(taskId)) return null
646
+ const previous = indexLocks.get(root) ?? Promise.resolve()
647
+ const next = previous.catch(() => {}).then(async () => {
648
+ const index = await readAssetIndex(root)
649
+ const prior = index[taskId] ?? {}
650
+ // Every file any call saved for the task, the newest last.
651
+ const added = Array.isArray(entry?.files) ? entry.files.filter((f) => typeof f === 'string' && f) : []
652
+ const files = [...new Set([...(prior.files ?? []), ...added])].slice(-MAX_FILES)
653
+ // A finished output is never downgraded to "nothing" by a later, emptier read.
654
+ const kind = ASSET_KINDS.has(entry?.kind) && !(entry.kind === 'none' && prior.kind && prior.kind !== 'none')
655
+ ? entry.kind
656
+ : (prior.kind ?? null)
657
+ const merged = {
658
+ resource: text(entry?.resource) ?? prior.resource ?? null,
659
+ kind,
660
+ // A task keeps the name it was submitted with; a later wait or get never renames it.
661
+ title: prior.title ?? text(entry?.title) ?? null,
662
+ // The file the Studio opens: the most previewable one saved, the newest on a tie.
663
+ file: [text(entry?.file), prior.file, ...[...files].reverse()].reduce(
664
+ (best, f) => (f && (best === null || fileRank(f) < fileRank(best)) ? f : best),
665
+ null,
666
+ ),
667
+ files,
668
+ createdAt: num(prior.createdAt) ?? num(entry?.createdAt) ?? now(),
669
+ ...optionalFacts(prior),
670
+ ...optionalFacts(entry),
671
+ }
672
+ index[taskId] = merged
673
+ const kept = Object.entries(index)
674
+ .sort((a, b) => (b[1].createdAt ?? 0) - (a[1].createdAt ?? 0))
675
+ .slice(0, MAX_ASSETS)
676
+ const path = indexPath(root)
677
+ await mkdir(dirname(path), { recursive: true })
678
+ const tmp = `${path}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`
679
+ await writeFile(tmp, `${JSON.stringify(Object.fromEntries(kept), null, 1)}\n`, { mode: 0o600 })
680
+ await rename(tmp, path)
681
+ return merged
682
+ })
683
+ const settled = next.catch(() => null)
684
+ indexLocks.set(root, settled)
685
+ settled.finally(() => { if (indexLocks.get(root) === settled) indexLocks.delete(root) })
686
+ return settled
687
+ }