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