meshy-dsh 0.3.7 → 0.4.1

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/tools.js ADDED
@@ -0,0 +1,756 @@
1
+ // Native Cordis tools for Meshy. `meshy` runs the bundled Meshy CLI with the agent's own
2
+ // arguments, unchanged: a command that spends credits asks the user first (with the agent's
3
+ // estimate and the current balance) and runs as a dsh background job, and every command's chat
4
+ // card and Studio row come from the CLI's own JSON envelope. `meshy_sign_in` signs the user in;
5
+ // `meshy_preview_model` opens a file or task in the right-sidebar Meshy Studio. Nothing here knows
6
+ // a CLI flag, model or price: which commands spend credits comes from `meshy resources`.
7
+ import { realpath } from 'node:fs/promises'
8
+ import { extname, isAbsolute, relative, resolve, sep } from 'node:path'
9
+ import {
10
+ assetUrl,
11
+ kindOfResource,
12
+ outputKind,
13
+ readAssetIndex,
14
+ recordAsset,
15
+ resolveWorkspaceFile,
16
+ sessionStateDir,
17
+ TASK_ID,
18
+ viewOf,
19
+ } from './tasks.js'
20
+
21
+ const REGIONS = new Set(['global', 'cn'])
22
+ const IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.webp'])
23
+ const MODEL_EXTS = new Set(['.glb', '.3mf'])
24
+ const PREVIEW_EXTS = new Set([...MODEL_EXTS, ...IMAGE_EXTS])
25
+
26
+ const MAX_ARGS = 200
27
+ const MAX_ARG = 8192
28
+ /** A paid or watching command: the CLI's own wait gives up first (600s a step by default). */
29
+ const LONG_TIMEOUT_MS = 3 * 3600_000
30
+ const SHORT_TIMEOUT_MS = 10 * 60_000
31
+ const JOB_OUTPUT_LIMIT = 16384
32
+ const JOB_LABEL_MAX = 120
33
+ /** What the agent reads back: the CLI's envelope, compact, cut here. */
34
+ const RESULT_TEXT_MAX = 16_000
35
+ /** Abort reason used when a job started but the tool falls back to running inside the call. */
36
+ const FALLBACK = 'meshy-dsh: fall back to running in the tool call'
37
+
38
+ /** Options that would replace the user's Meshy sign-in, send it elsewhere, or print it. */
39
+ const REFUSED = /^--(?:api-key|api-key-file|base-url[a-z0-9-]*|show-token)$/
40
+ /** Options the plugin sets itself on every run. */
41
+ const OWNED_WITH_VALUE = new Set(['--format', '--workspace'])
42
+ const OWNED_FLAGS = new Set(['--json', '--no-update-check'])
43
+
44
+ const short = (value, max = 64) => {
45
+ if (typeof value !== 'string') return null
46
+ const clean = value.replace(/\s+/g, ' ').trim()
47
+ if (!clean) return null
48
+ return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean
49
+ }
50
+
51
+ /**
52
+ * The chat card's data (`result.meta`): Meshy-hosted thumbnails only, short text, and no null or
53
+ * undefined fields. Never part of what the model reads.
54
+ */
55
+ function cardMeta(card) {
56
+ const clean = {}
57
+ for (const [k, v] of Object.entries(card)) {
58
+ if (v === undefined || v === null) continue
59
+ if (k === 'thumbnail') {
60
+ const safe = assetUrl(v)
61
+ if (safe) clean.thumbnail = safe
62
+ } else if (k === 'title' || k === 'prompt') {
63
+ const s = short(v, 72)
64
+ if (s) clean[k] = s
65
+ } else {
66
+ clean[k] = v
67
+ }
68
+ }
69
+ return clean
70
+ }
71
+
72
+ function abortError(message) {
73
+ const err = new Error(message)
74
+ err.name = 'AbortError'
75
+ return err
76
+ }
77
+
78
+ const isAbort = (err, signal) => err?.name === 'AbortError' || Boolean(signal?.aborted)
79
+
80
+ function getService(ctx, name) {
81
+ if (!ctx || typeof ctx !== 'object') return undefined
82
+ if (typeof ctx.get === 'function') return ctx.get(name)
83
+ return ctx[name]
84
+ }
85
+
86
+ function sessionInfo(exec) {
87
+ const header = exec?.agent?.session?.header
88
+ const sessionId = typeof header?.id === 'string' && header.id ? header.id : null
89
+ const workspace = typeof header?.cwd === 'string' && header.cwd ? header.cwd : null
90
+ return { sessionId, workspace }
91
+ }
92
+
93
+ function interpretApproval(outcome) {
94
+ if (typeof outcome === 'string') {
95
+ return { approved: outcome === 'allowed-once' || outcome === 'allowed', code: outcome }
96
+ }
97
+ if (outcome && typeof outcome === 'object') {
98
+ if (outcome.allowed === true) return { approved: true, code: 'allowed-once' }
99
+ const tag = outcome.outcome ?? outcome.decision ?? outcome.kind ?? outcome.status
100
+ if (tag === 'allowed-once' || tag === 'allowed') return { approved: true, code: tag }
101
+ return { approved: false, code: typeof tag === 'string' ? tag : 'rejected' }
102
+ }
103
+ return { approved: false, code: 'unavailable' }
104
+ }
105
+
106
+ /**
107
+ * The agent's argv, checked and without the options the plugin owns: it starts with the command
108
+ * (a leading `meshy` is dropped), never replaces or prints the sign-in, and its output format and
109
+ * workspace are set by the plugin. Everything else passes through as given.
110
+ */
111
+ export function prepareArgs(args) {
112
+ if (!Array.isArray(args) || args.length === 0) {
113
+ throw new Error('args must be the Meshy CLI arguments as a list of strings, starting with the command (e.g. ["balance"]).')
114
+ }
115
+ if (args.length > MAX_ARGS) throw new Error(`args takes at most ${MAX_ARGS} items.`)
116
+ const argv = args.map((a, i) => {
117
+ if (typeof a !== 'string' || a.length > MAX_ARG || a.includes('\0')) throw new Error(`args[${i}] must be a string (at most ${MAX_ARG} characters).`)
118
+ return a
119
+ })
120
+ if (argv[0] === 'meshy' || argv[0] === 'meshy-cli') argv.shift()
121
+ if (!argv[0] || argv[0].startsWith('-')) {
122
+ throw new Error('args must start with the command (e.g. ["image-to-3d", "create", ...]); put options after it.')
123
+ }
124
+ if (argv[0] === 'auth' && argv[1] !== 'status') {
125
+ throw new Error('The plugin keeps the Meshy sign-in: call meshy_sign_in instead of `meshy auth`. Only `auth status` runs here.')
126
+ }
127
+ if (argv[0] === 'view') {
128
+ throw new Error('The Meshy Studio is the 3D viewer here: call meshy_preview_model to open a workspace model in it. `meshy view` does not run here.')
129
+ }
130
+ const kept = []
131
+ let literal = false
132
+ for (let i = 0; i < argv.length; i++) {
133
+ const a = argv[i]
134
+ if (literal) { kept.push(a); continue }
135
+ if (a === '--') { literal = true; kept.push(a); continue }
136
+ const flag = a.startsWith('--') ? a.split('=', 1)[0] : a
137
+ if (REFUSED.test(flag)) throw new Error(`${flag} is not allowed here: the plugin runs the Meshy CLI with the user's own sign-in.`)
138
+ if (OWNED_WITH_VALUE.has(flag)) {
139
+ if (!a.includes('=')) i++
140
+ continue
141
+ }
142
+ if (OWNED_FLAGS.has(a)) continue
143
+ kept.push(a)
144
+ }
145
+ return kept
146
+ }
147
+
148
+ /** `meshy make 'a red fox'`: how the command reads in the approval and card. */
149
+ export function displayOf(argv) {
150
+ const quote = (a) => (/^[\w@%+=:,./-]+$/.test(a) ? a : `'${a.replace(/'/g, `'\\''`)}'`)
151
+ return ['meshy', ...argv.map(quote)].join(' ')
152
+ }
153
+
154
+ /**
155
+ * The tasks a command ran, by id, from the places the CLI's envelope reports them: `make`'s
156
+ * `executed` steps and `submitted` step, a create's `submission` (or a `--async` create's
157
+ * `task_id`), and the `task` it followed. A `list` names other tasks in `items` and is left out.
158
+ * `resource` is the command's own task resource, for the records that do not carry one.
159
+ */
160
+ export function collectTasks(result, resource = null) {
161
+ const found = new Map()
162
+ const add = (v, fallback = null) => {
163
+ if (!v || typeof v !== 'object' || Array.isArray(v) || typeof v.task_id !== 'string' || !TASK_ID.test(v.task_id)) return
164
+ const prior = found.get(v.task_id)
165
+ found.set(v.task_id, { ...(fallback ? { resource: fallback } : {}), ...prior, ...v })
166
+ }
167
+ if (!result || typeof result !== 'object') return []
168
+ for (const step of Array.isArray(result.executed) ? result.executed.slice(0, 20) : []) add(step)
169
+ add(result.submitted)
170
+ add(result.submission, resource)
171
+ if (typeof result.task_id === 'string') add({ task_id: result.task_id }, resource)
172
+ add(result.task, resource)
173
+ return [...found.values()]
174
+ }
175
+
176
+ /** The files the CLI wrote (`downloads.files` with status written), wherever its result puts them. */
177
+ export function collectFiles(result) {
178
+ const paths = []
179
+ const walk = (v, depth) => {
180
+ if (!v || typeof v !== 'object' || depth > 6) return
181
+ if (Array.isArray(v)) {
182
+ for (const x of v.slice(0, 50)) walk(x, depth + 1)
183
+ return
184
+ }
185
+ if (Array.isArray(v.files) && ('metadata_path' in v || 'state' in v)) {
186
+ for (const f of v.files) {
187
+ if (f?.status === 'written' && typeof f.path === 'string' && !paths.includes(f.path)) paths.push(f.path)
188
+ }
189
+ }
190
+ for (const [k, x] of Object.entries(v)) {
191
+ if (k !== 'raw' && k !== 'response' && k !== 'files') walk(x, depth + 1)
192
+ }
193
+ }
194
+ walk(result, 0)
195
+ return paths
196
+ }
197
+
198
+ /** Workspace-relative POSIX paths of the files inside the workspace; others are left out. */
199
+ async function inWorkspace(workspace, paths) {
200
+ const roots = [workspace]
201
+ try {
202
+ const real = await realpath(workspace)
203
+ if (real !== workspace) roots.unshift(real)
204
+ } catch {
205
+ // The workspace path as given.
206
+ }
207
+ const out = []
208
+ for (const p of paths) {
209
+ for (const root of roots) {
210
+ const rel = relative(root, resolve(root, p))
211
+ if (rel && !rel.startsWith('..') && !isAbsolute(rel)) {
212
+ const posix = rel.split(sep).join('/')
213
+ if (!out.includes(posix)) out.push(posix)
214
+ break
215
+ }
216
+ }
217
+ }
218
+ return out
219
+ }
220
+
221
+ const kindOfFile = (file) => {
222
+ const ext = extname(file).toLowerCase()
223
+ return MODEL_EXTS.has(ext) ? 'model' : IMAGE_EXTS.has(ext) ? 'image' : 'file'
224
+ }
225
+
226
+ /** The compact envelope the agent reads, cut at RESULT_TEXT_MAX. */
227
+ function envelopeText(env) {
228
+ let text
229
+ try {
230
+ const { timedOut: _t, ...body } = env ?? {}
231
+ text = JSON.stringify(body)
232
+ } catch {
233
+ text = String(env?.error?.message ?? 'the Meshy CLI printed no result')
234
+ }
235
+ return text.length > RESULT_TEXT_MAX ? `${text.slice(0, RESULT_TEXT_MAX)}… (cut; ${text.length} characters)` : text
236
+ }
237
+
238
+ /** The name the asset index has for the first task id among `argv` (a `wait`/`get` on it). */
239
+ async function knownTitle(workspace, argv) {
240
+ const ids = argv
241
+ .map((a) => (a.startsWith('--') && a.includes('=') ? a.slice(a.indexOf('=') + 1) : a))
242
+ .filter((a) => TASK_ID.test(a) && /\d/.test(a) && a.includes('-'))
243
+ if (ids.length === 0) return null
244
+ try {
245
+ const index = await readAssetIndex(workspace)
246
+ for (const id of ids) if (index[id]?.title) return index[id].title
247
+ } catch {
248
+ // No name: the call shows the agent's label.
249
+ }
250
+ return null
251
+ }
252
+
253
+ /**
254
+ * Build the native Cordis tools for `meshy-dsh`.
255
+ * `cli(argv, opts)` runs the bundled CLI and resolves to its envelope; `catalog` is the CLI's
256
+ * resource listing (`createCatalog`).
257
+ */
258
+ export function createTools({ ctx, cli, catalog, signIn, events }) {
259
+ /** One `task` SSE event for a task a `meshy` call is running. */
260
+ function emitTask(run, view, extra = {}) {
261
+ const title = short(run.taskTitle ?? view?.name ?? view?.prompt, 72)
262
+ events.emit({
263
+ type: 'task',
264
+ sessionId: run.sessionId,
265
+ workspace: run.workspace,
266
+ callId: run.callId,
267
+ jobId: run.jobId ?? null,
268
+ resource: view.resource ?? null,
269
+ stage: null,
270
+ taskId: view.taskId,
271
+ parentTaskId: view.parentTaskId ?? null,
272
+ kind: view.kind,
273
+ title,
274
+ name: title,
275
+ status: view.status ?? 'PENDING',
276
+ progress: view.progress ?? 0,
277
+ thumbnail: view.thumbnail ?? null,
278
+ localFile: extra.localFile ?? null,
279
+ ...(Array.isArray(extra.files) ? { files: extra.files } : {}),
280
+ credits: view.credits ?? null,
281
+ error: view.error ?? null,
282
+ })
283
+ }
284
+
285
+ /** The CLI's tasks as the Studio shows them: status, progress, thumbnail, credits. */
286
+ function viewsOf(run, result) {
287
+ return collectTasks(result, run.resource).map((t) => {
288
+ const v = viewOf(t) ?? {}
289
+ const resource = typeof t.resource === 'string' ? t.resource : null
290
+ return { ...v, taskId: t.task_id, resource, kind: outputKind(v) }
291
+ })
292
+ }
293
+
294
+ /**
295
+ * A task seen for the first time: index it so its Studio row knows the call that ran it. Only
296
+ * the call that submitted a task names it; a `wait` or `get` keeps the name it has.
297
+ */
298
+ async function remember(run, view) {
299
+ const before = run.seen.get(view.taskId)
300
+ run.seen.set(view.taskId, view)
301
+ // Seen before: only what it produced is new, once it has finished.
302
+ if (before && ((before.kind && before.kind !== 'none') || !view.kind || view.kind === before.kind)) return
303
+ try {
304
+ await recordAsset(run.workspace, view.taskId, before ? { kind: view.kind } : {
305
+ resource: view.resource,
306
+ kind: view.kind,
307
+ title: run.creates ? run.taskTitle ?? short(view.name ?? view.prompt, 72) : null,
308
+ // The Studio row links to the call that submitted the task, never a later wait on it.
309
+ ...(run.creates ? { callId: run.callId, ...(run.jobId ? { jobId: run.jobId } : {}) } : {}),
310
+ })
311
+ } catch {
312
+ // The index is a convenience; the journal still lists the task.
313
+ }
314
+ }
315
+
316
+ /** One streamed CLI event: update the card and Studio rows of the tasks it names. */
317
+ function observe(run, envelope, job) {
318
+ for (const view of viewsOf(run, envelope?.result)) {
319
+ const sig = `${view.status}|${view.progress}|${view.thumbnail ?? ''}`
320
+ if (run.lastSig.get(view.taskId) === sig) continue
321
+ run.lastSig.set(view.taskId, sig)
322
+ void remember(run, view)
323
+ emitTask(run, view)
324
+ if (job) {
325
+ const pct = Number.isFinite(view.progress) ? Math.round(view.progress) : 0
326
+ try {
327
+ job.updateProgress?.(`${view.status ?? 'PENDING'} ${pct}%`)
328
+ } catch {
329
+ // Progress is best-effort.
330
+ }
331
+ }
332
+ }
333
+ }
334
+
335
+ /** Run the CLI for one call. Resolves to its envelope; rejects only on abort or a spawn failure. */
336
+ function execute(run, signal, job) {
337
+ return cli(run.argv, {
338
+ cwd: run.workspace,
339
+ workspace: run.workspace,
340
+ extraEnv: { DSH_MESHY_STATE_DIR: sessionStateDir(run.workspace, run.sessionId) },
341
+ timeoutMs: run.long ? LONG_TIMEOUT_MS : SHORT_TIMEOUT_MS,
342
+ signal,
343
+ stream: run.long,
344
+ onEvent: (e) => observe(run, e, job),
345
+ onStderrLine: job ? (line) => {
346
+ try {
347
+ job.append?.(`${line}\n`)
348
+ } catch {
349
+ // job_output is best-effort.
350
+ }
351
+ } : undefined,
352
+ })
353
+ }
354
+
355
+ /** After the CLI exits: final rows, index and open the saved files, and the call's result. */
356
+ async function settle(run, env) {
357
+ const views = viewsOf(run, env?.result)
358
+ const files = await inWorkspace(run.workspace, collectFiles(env?.result))
359
+ const primary = files.find((f) => kindOfFile(f) === 'model') ?? files.find((f) => kindOfFile(f) === 'image') ?? files[0] ?? null
360
+ // Saved files belong to the last task the command reports (make: the final stage).
361
+ const owner = [...views].reverse().find((v) => v.status === 'SUCCEEDED') ?? views.at(-1) ?? null
362
+ for (const view of views) {
363
+ await remember(run, view)
364
+ emitTask(run, view, view === owner ? { localFile: primary, files } : {})
365
+ }
366
+ const route = { sessionId: run.sessionId, workspace: run.workspace }
367
+ let savedTitle = null
368
+ if (files.length > 0) {
369
+ const kind = primary ? kindOfFile(primary) : 'file'
370
+ let title = run.taskTitle ?? short(owner?.name ?? owner?.prompt, 72) ?? null
371
+ if (owner) {
372
+ try {
373
+ const saved = await recordAsset(run.workspace, owner.taskId, {
374
+ resource: owner.resource,
375
+ kind: owner.kind ?? (kind === 'model' || kind === 'image' ? kind : null),
376
+ title: run.creates ? title : null,
377
+ file: primary,
378
+ files,
379
+ })
380
+ title = saved?.title ?? title
381
+ } catch {
382
+ // The files are on disk either way.
383
+ }
384
+ }
385
+ savedTitle = title
386
+ events.emit({ type: 'asset', ...route, taskId: owner?.taskId ?? null, resource: owner?.resource ?? null, kind, file: primary, files, title })
387
+ if (primary && kind === 'model') {
388
+ events.emit({ type: 'model', ...route, file: primary, resource: owner?.resource ?? null, taskId: owner?.taskId ?? null })
389
+ events.emit({ type: 'open', ...route, kind: 'model', target: { file: primary } })
390
+ } else if (primary && kind === 'image') {
391
+ events.emit({ type: 'open', ...route, kind: 'image', target: { file: primary } })
392
+ }
393
+ }
394
+ const byId = new Map(views.map((v) => [v.taskId, v.credits]))
395
+ const spent = [...byId.values()].filter((c) => typeof c === 'number')
396
+ return {
397
+ status: env?.ok ? 'ok' : 'failed',
398
+ command: run.display,
399
+ ok: env?.ok === true,
400
+ tasks: views.slice(0, 8).map((v) => ({
401
+ taskId: v.taskId,
402
+ resource: v.resource,
403
+ kind: v.kind,
404
+ status: v.status ?? null,
405
+ progress: v.progress ?? null,
406
+ thumbnail: v.thumbnail ?? null,
407
+ credits: v.credits ?? null,
408
+ })),
409
+ files,
410
+ file: primary,
411
+ credits: spent.length > 0 ? spent.reduce((a, b) => a + b, 0) : null,
412
+ title: savedTitle ?? null,
413
+ ...(run.paid ? { paid: true, estimate: run.estimate } : {}),
414
+ error: env?.ok ? null : (short(env?.error?.message, 240) ?? 'the Meshy CLI failed'),
415
+ envelope: env,
416
+ }
417
+ }
418
+
419
+ /** The background job body: run the CLI, then settle. `done` never rejects. */
420
+ function runAsJob(run, job) {
421
+ const controller = new AbortController()
422
+ if (!run.jobId && typeof job?.id === 'string') run.jobId = job.id
423
+ const done = (async () => {
424
+ let env
425
+ try {
426
+ env = await execute(run, controller.signal, job)
427
+ } catch (err) {
428
+ if (controller.signal.aborted) {
429
+ for (const view of run.seen.values()) emitTask(run, { ...view, error: 'no longer watched here; the task keeps running on Meshy' })
430
+ const ids = [...run.seen.keys()]
431
+ return {
432
+ status: 'killed',
433
+ detail: ids.length > 0
434
+ ? `Stopped the Meshy CLI. Task ${ids.join(', ')} keeps running on Meshy; follow it with the resource's \`wait\` command (no new task, no credits).`
435
+ : 'Stopped the Meshy CLI before it reported a task.',
436
+ }
437
+ }
438
+ return { status: 'failed', detail: String(err?.message ?? err) }
439
+ }
440
+ const value = await settle(run, env).catch((err) => ({ ok: false, envelope: env, error: String(err?.message ?? err) }))
441
+ const text = envelopeText(value.envelope ?? env)
442
+ return value.ok ? { status: 'completed', result: text } : { status: 'failed', detail: text }
443
+ })()
444
+ return { cancel: (reason) => controller.abort(reason ?? 'killed'), done }
445
+ }
446
+
447
+ /** Start the background job; null when dsh cannot run one (the call then runs inline). */
448
+ async function startJob(jobs, run, exec) {
449
+ let hooks = null
450
+ try {
451
+ const id = await jobs.start({
452
+ kind: 'meshy',
453
+ label: short(run.taskTitle ? `${run.taskTitle} · ${run.display}` : run.display, JOB_LABEL_MAX) ?? 'meshy',
454
+ owner: run.sessionId,
455
+ ...(run.callId
456
+ ? { toolCall: { callId: run.callId, rootCallId: typeof exec?.rootCallId === 'string' && exec.rootCallId ? exec.rootCallId : run.callId } }
457
+ : {}),
458
+ outputLimitBytes: JOB_OUTPUT_LIMIT,
459
+ run(job) {
460
+ hooks = runAsJob(run, job)
461
+ return hooks
462
+ },
463
+ })
464
+ const jobId = typeof id === 'string' && id ? id : typeof id === 'number' ? String(id) : run.jobId
465
+ if (!jobId) throw new Error('the job registry returned no id')
466
+ run.jobId = jobId
467
+ return jobId
468
+ } catch {
469
+ hooks?.cancel(FALLBACK)
470
+ run.jobId = null
471
+ return null
472
+ }
473
+ }
474
+
475
+ async function readBalance(signal) {
476
+ try {
477
+ const env = await cli(['balance'], { timeoutMs: 20_000, signal })
478
+ const value = env?.ok ? env.result?.balance : null
479
+ return typeof value === 'number' && Number.isFinite(value) ? value : null
480
+ } catch (err) {
481
+ if (isAbort(err, signal)) throw err
482
+ return null
483
+ }
484
+ }
485
+
486
+ /** The approval text, in both languages: the command, the agent's estimate, the balance. */
487
+ function approvalText({ display, estimate, source, balance, requester }) {
488
+ const en = [`Run ${display}${requester ? ` (requested by ${requester})` : ''}.`]
489
+ const zh = [`运行 ${display}${requester ? `(由 ${requester} 发起)` : ''}。`]
490
+ if (typeof estimate === 'number') {
491
+ en.push(`Estimated ~${estimate} credits${source ? ` (${source})` : ''}.`)
492
+ zh.push(`预计约 ${estimate} 积分${source ? `(${source})` : ''}。`)
493
+ } else {
494
+ en.push('Price unknown; the actual charge applies.')
495
+ zh.push('价格未知,以实际扣费为准。')
496
+ }
497
+ if (typeof balance === 'number') {
498
+ en.push(`Balance: ${balance} credits.`)
499
+ zh.push(`当前余额 ${balance} 积分。`)
500
+ }
501
+ return { reason: en.join(' '), displayReason: { en: en.join(' '), zh: zh.join('') } }
502
+ }
503
+
504
+ /** Fail-closed approval for a command that spends credits. */
505
+ async function approve(exec, { display, estimate, source }) {
506
+ const approval = getService(ctx, 'approval')
507
+ const refused = (what) => `${what}; ${display} did not run (0 credits spent).`
508
+ if (!approval || typeof approval.request !== 'function') throw new Error(refused('Approval is unavailable in this session'))
509
+ const balance = await readBalance(exec?.signal)
510
+ const { reason, displayReason } = approvalText({ display, estimate, source, balance, requester: exec?.requester })
511
+ let res
512
+ try {
513
+ res = await approval.request({ agent: exec?.agent, toolName: 'meshy', callId: exec?.callId, reason, displayReason, signal: exec?.signal })
514
+ } catch (err) {
515
+ if (isAbort(err, exec?.signal)) throw err
516
+ throw new Error(refused(`Approval failed (${err?.message ?? err})`))
517
+ }
518
+ const decision = interpretApproval(res)
519
+ if (decision.approved) return
520
+ if (decision.code === 'cancelled') throw abortError(refused('Approval cancelled'))
521
+ if (decision.code === 'unavailable') throw new Error(refused('Approval is unavailable in this session'))
522
+ throw new Error(refused('The user declined'))
523
+ }
524
+
525
+ // 1. meshy: the bundled CLI, arguments passed through
526
+ const meshyTool = {
527
+ name: 'meshy',
528
+ description:
529
+ 'Run the Meshy CLI that this plugin ships, signed in as the user: pass its arguments exactly as ' +
530
+ 'the Meshy skills document them, one item per argument and without the leading `meshy` (e.g. ' +
531
+ '["make", "a red fox"]). Use this tool instead of running meshy in the shell. The plugin adds the ' +
532
+ 'JSON output and the workspace limit itself, runs in the session workspace (relative paths ' +
533
+ 'resolve there), and returns the CLI\'s JSON envelope. A command that spends credits (`make`, ' +
534
+ '`create` on a task resource, a non-GET `api`) asks the user first: pass `estimated_credits` ' +
535
+ 'and `estimate_source` from `make --dry-run` or the published price list when you have one, ' +
536
+ 'never a guess. Such a command, and `wait`/`stream`, runs as a background job: a notice with ' +
537
+ 'the envelope arrives when it ends; do not poll it or run it again. A command that submits a ' +
538
+ 'task follows it to its result in that job, so one call carries it from submission to its ' +
539
+ 'files: do not submit it and then wait on it in a second call. If the CLI\'s wait times ' +
540
+ 'out the task keeps running on Meshy: resume with the `wait` command the envelope names (no new ' +
541
+ 'task). Saved .glb and .3mf models and images open in the Meshy Studio on their own.',
542
+ parameters: {
543
+ type: 'object',
544
+ properties: {
545
+ args: {
546
+ type: 'array',
547
+ items: { type: 'string' },
548
+ description: 'The Meshy CLI arguments after `meshy`, starting with the command, one item per argument.',
549
+ },
550
+ estimated_credits: {
551
+ type: 'number',
552
+ description: 'For a command that spends credits: the estimate shown to the user, from `make --dry-run` or the published price list. Omit when unknown.',
553
+ },
554
+ estimate_source: {
555
+ type: 'string',
556
+ description: 'Where estimated_credits comes from (e.g. "make --dry-run" or "Meshy pricing page").',
557
+ },
558
+ title: {
559
+ type: 'string',
560
+ description: 'For a command that submits a task: the name of what it makes, a few words in the user\'s language (e.g. "oak chest"), shown in the job list and the Meshy Studio. Name the thing, not the step ("oak chest", not "generating the chest"). A command on an existing task keeps that task\'s name, so omit it there.',
561
+ },
562
+ },
563
+ required: ['args'],
564
+ additionalProperties: false,
565
+ },
566
+ output: {
567
+ schema: { type: 'object', additionalProperties: true },
568
+ render: (_args, v) => [{
569
+ type: 'text',
570
+ text: v.status === 'started'
571
+ ? `${v.command} is running as background job ${v.jobId}. A notice with the CLI's result arrives when it ends; do not poll it or run it again.`
572
+ : envelopeText(v.envelope),
573
+ }],
574
+ presentationMeta: (_args, v) => cardMeta({
575
+ tool: 'meshy',
576
+ status: v.status,
577
+ command: short(v.command, 240),
578
+ title: v.title,
579
+ jobId: v.jobId,
580
+ paid: v.paid,
581
+ estimate: v.estimate,
582
+ credits: v.credits,
583
+ tasks: Array.isArray(v.tasks) ? v.tasks.map((t) => cardMeta(t)) : undefined,
584
+ file: v.file,
585
+ files: Array.isArray(v.files) ? v.files.slice(0, 12) : undefined,
586
+ error: v.error,
587
+ }),
588
+ },
589
+ async execute(args, exec) {
590
+ const argv = prepareArgs(args?.args)
591
+ const { sessionId, workspace } = sessionInfo(exec)
592
+ if (!workspace) throw new Error('The Meshy CLI runs in the session workspace, and this session has none.')
593
+ const estimate = typeof args?.estimated_credits === 'number' && Number.isFinite(args.estimated_credits) && args.estimated_credits >= 0
594
+ ? Math.round(args.estimated_credits * 100) / 100
595
+ : null
596
+ const source = short(args?.estimate_source, 120)
597
+ const kind = await catalog.classify(argv, { signal: exec?.signal })
598
+ const display = displayOf(argv)
599
+ if (kind.paid) await approve(exec, { display, estimate, source })
600
+ if (exec?.signal?.aborted) throw abortError(`Aborted before ${display} ran (0 credits spent).`)
601
+
602
+ // A call that submits tasks names them; any other call shows the name its task already has.
603
+ const creates = argv[0] === 'make' || kind.verb === 'create'
604
+ const label = short(args?.title, 72)
605
+ const run = {
606
+ sessionId,
607
+ workspace,
608
+ callId: typeof exec?.callId === 'string' ? exec.callId : null,
609
+ jobId: null,
610
+ argv,
611
+ display,
612
+ creates,
613
+ // The agent's title names what a create makes; a call on an existing task shows its name.
614
+ taskTitle: creates ? label : await knownTitle(workspace, argv),
615
+ resource: kind.resource ?? null,
616
+ long: kind.long,
617
+ paid: kind.paid,
618
+ estimate,
619
+ seen: new Map(),
620
+ lastSig: new Map(),
621
+ }
622
+
623
+ const jobs = exec?.meshyWait === true ? null : getService(ctx, 'jobs')
624
+ if (run.long && sessionId && typeof jobs?.start === 'function') {
625
+ const jobId = await startJob(jobs, run, exec)
626
+ if (jobId) {
627
+ return {
628
+ status: 'started',
629
+ command: display,
630
+ jobId,
631
+ title: run.taskTitle,
632
+ ...(run.paid ? { paid: true, estimate } : {}),
633
+ }
634
+ }
635
+ }
636
+
637
+ let env
638
+ try {
639
+ env = await execute(run, exec?.signal, null)
640
+ } catch (err) {
641
+ if (isAbort(err, exec?.signal)) {
642
+ const ids = [...run.seen.keys()]
643
+ throw abortError(ids.length > 0
644
+ ? `Aborted ${display}. Task ${ids.join(', ')} keeps running on Meshy; follow it with the resource's \`wait\` command (do not resubmit).`
645
+ : `Aborted ${display}.`)
646
+ }
647
+ throw err
648
+ }
649
+ const value = await settle(run, env)
650
+ return { ...value, title: value.title ?? run.taskTitle }
651
+ },
652
+ }
653
+
654
+ // 2. meshy_sign_in
655
+ const meshySignIn = {
656
+ name: 'meshy_sign_in',
657
+ description:
658
+ 'Sign the user in to Meshy. The Meshy plugin keeps the sign-in for both the `meshy` tool and ' +
659
+ 'shell calls. Call this when Meshy reports that nobody is signed in or the session was rejected; ' +
660
+ 'never run `auth login` in the shell. Show the link and code to the user and wait for approval. ' +
661
+ 'Use region "cn" only for the China site (meshy.cn).',
662
+ parameters: {
663
+ type: 'object',
664
+ properties: {
665
+ region: { type: 'string', enum: ['global', 'cn'], description: 'Meshy site; default global.' },
666
+ },
667
+ additionalProperties: false,
668
+ },
669
+ output: {
670
+ schema: {
671
+ type: 'object',
672
+ properties: {
673
+ status: { type: 'string' },
674
+ verification_url: { type: 'string' },
675
+ user_code: { type: 'string' },
676
+ expires_in: { type: 'integer' },
677
+ region: { type: 'string' },
678
+ },
679
+ required: ['status', 'verification_url', 'user_code', 'expires_in'],
680
+ additionalProperties: false,
681
+ },
682
+ render: (_args, v) => [{
683
+ type: 'text',
684
+ text: `Open ${v.verification_url} and confirm code ${v.user_code} (valid ${Math.round(v.expires_in / 60)} minutes).`,
685
+ }],
686
+ presentationMeta: (args, v) => cardMeta({
687
+ tool: 'meshy_sign_in',
688
+ status: v.status,
689
+ verificationUrl: v.verification_url,
690
+ userCode: v.user_code,
691
+ expiresIn: v.expires_in,
692
+ region: v.region ?? args?.region ?? 'global',
693
+ }),
694
+ },
695
+ async execute(args) {
696
+ const region = args?.region ?? 'global'
697
+ if (!REGIONS.has(region)) throw new Error('meshy_sign_in: region must be global or cn')
698
+ const view = await signIn(region)
699
+ return { ...view, region }
700
+ },
701
+ }
702
+
703
+ // 3. meshy_preview_model
704
+ const meshyPreviewModel = {
705
+ name: 'meshy_preview_model',
706
+ description: 'Open a workspace .glb or .3mf model or image, or a finished Meshy task, in the right-sidebar Meshy Studio (no credits spent).',
707
+ isConcurrencySafe: () => true,
708
+ parameters: {
709
+ type: 'object',
710
+ properties: {
711
+ file: { type: 'string', description: 'Workspace-relative .glb, .3mf, .png, .jpg or .webp file path.' },
712
+ resource: { type: 'string', description: 'Meshy task resource as `meshy resources` names it (paired with task_id).' },
713
+ task_id: { type: 'string', description: 'Meshy task id (paired with resource).' },
714
+ },
715
+ additionalProperties: false,
716
+ },
717
+ output: {
718
+ schema: { type: 'object', additionalProperties: true },
719
+ render: (_args, v) => [{
720
+ type: 'text',
721
+ text: v.file
722
+ ? `Opened ${v.file} in Meshy Studio.`
723
+ : `Opened Meshy ${v.resource} task ${v.taskId} in Meshy Studio.`,
724
+ }],
725
+ presentationMeta: (_args, v) => cardMeta({
726
+ tool: 'meshy_preview_model',
727
+ status: 'ok',
728
+ kind: v.kind,
729
+ file: v.file,
730
+ resource: v.resource,
731
+ taskId: v.taskId,
732
+ }),
733
+ },
734
+ async execute(args, exec) {
735
+ const { sessionId, workspace } = sessionInfo(exec)
736
+ if (typeof args?.file === 'string' && args.file.trim()) {
737
+ if (!workspace) throw new Error('previewing a workspace file requires an active session workspace')
738
+ const resolved = await resolveWorkspaceFile(workspace, args.file.trim(), { allowedExts: PREVIEW_EXTS })
739
+ const kind = kindOfFile(resolved.rel)
740
+ events.emit({ type: 'open', sessionId, workspace, kind, target: { file: resolved.rel } })
741
+ return { status: 'ok', kind, file: resolved.rel, resource: null, taskId: null }
742
+ }
743
+ if (args?.resource && args?.task_id) {
744
+ if (!(await catalog.taskArgs(args.resource, 'get', args.task_id, { signal: exec?.signal }))) {
745
+ throw new Error(`not a Meshy task: ${args.resource} ${args.task_id} (see \`meshy resources\`)`)
746
+ }
747
+ const kind = kindOfResource(args.resource)
748
+ events.emit({ type: 'open', sessionId, workspace, kind, target: { resource: args.resource, taskId: args.task_id } })
749
+ return { status: 'ok', kind, file: null, resource: args.resource, taskId: args.task_id }
750
+ }
751
+ throw new Error('provide either file (a workspace .glb, .3mf or image) or resource + task_id')
752
+ },
753
+ }
754
+
755
+ return { tools: [meshyTool, meshySignIn, meshyPreviewModel], meshyTool }
756
+ }