meshy-dsh 0.3.6 → 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/index.js CHANGED
@@ -1,14 +1,36 @@
1
- // Host half of the plugin. It owns the Meshy sign-in: dsh runs model shell calls in a sandbox
2
- // that cannot write the CLI's credential store, and a refresh that cannot be saved spends the
3
- // login, so the host signs in, keeps the session fresh and hands every shell call a current
4
- // credential (DSH_MESHY_*), together with the CLI this package ships, so no session installs
5
- // one. It also registers `meshy_sign_in` for chats where no settings page is at hand, and, in
6
- // Web and Desktop, five authenticated routes under /api for the settings page. Every CLI call
7
- // uses fixed arguments.
1
+ // Host half of the plugin. It owns the Meshy sign-in, shell environment injection
2
+ // (DSH_MESHY_*), three native Cordis tools (`meshy`, which passes the agent's CLI arguments
3
+ // through, `meshy_sign_in` and `meshy_preview_model`), live SSE events, `/api/meshy.*` routes for
4
+ // Web and Desktop, the adaptive `meshy:compose` prompt section, and the public `meshy` Cordis
5
+ // service. The host's own CLI calls run with fixed, validated arguments.
8
6
  import { spawn } from 'node:child_process'
9
- import { readFileSync, watch } from 'node:fs'
7
+ import { createReadStream, readFileSync, watch } from 'node:fs'
8
+ import { readdir, realpath } from 'node:fs/promises'
10
9
  import { createRequire } from 'node:module'
11
10
  import { basename, dirname, join } from 'node:path'
11
+ import { Readable } from 'node:stream'
12
+ import { fileURLToPath } from 'node:url'
13
+ import { createCatalog } from './catalog.js'
14
+ import { registerCompose } from './compose.js'
15
+ import { createEventBus } from './events.js'
16
+ import { createMeshyService } from './service.js'
17
+ import {
18
+ createLibraryReader,
19
+ createTaskStates,
20
+ fetchModel,
21
+ JOURNAL,
22
+ kindOfResource,
23
+ outputKind,
24
+ listModels,
25
+ readAssetIndex,
26
+ readJournal,
27
+ serveWorkspaceModel,
28
+ sessionStateDir,
29
+ SESSIONS_DIR,
30
+ TERMINAL,
31
+ } from './tasks.js'
32
+ import { createTools } from './tools.js'
33
+ import { createInputRoute } from './uploads.js'
12
34
 
13
35
  export const name = 'meshy-dsh'
14
36
 
@@ -26,34 +48,74 @@ const SESSION_REFRESH_MS = 5 * 60_000
26
48
  const MAX_OUTPUT = 1 << 20
27
49
  const FLOW_ID = /^[A-Za-z0-9_-]{16,64}$/
28
50
  const REGIONS = new Set(['global', 'cn'])
51
+ const SSE_PING_MS = 25_000
29
52
 
30
- // dsh never updates a plugin it installed from npm, so the settings page says when reinstalling
31
- // would bring a newer release. The registries are the two dsh installs plugins from; the first
32
- // to answer wins, and the host's fetch goes through dsh's proxy settings.
33
53
  const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version
54
+ const ENV_HDR_PATH = fileURLToPath(new URL('../assets/viewer-env.hdr', import.meta.url))
34
55
  const REGISTRIES = ['https://registry.npmjs.org/meshy-dsh', 'https://registry.npmmirror.com/meshy-dsh']
35
- // dsh installs with pnpm, which holds a release back for its first day (`minimumReleaseAge`), so
36
- // a release is offered only once a reinstall would actually get it.
37
56
  const RELEASE_AGE_MS = 24 * 3600_000
38
57
  const UPDATE_CHECK_MS = 6 * 3600_000
39
58
  const RELEASE = /^(\d+)\.(\d+)\.(\d+)$/
40
59
 
41
60
  /**
42
- * Run one command with fixed argv (no shell; every argument is a constant or validated), capped
43
- * output and a deadline.
61
+ * Run one command with fixed argv (no shell), capped output, a deadline, and optional
62
+ * AbortSignal cancellation. `onStdoutLine` / `onStderrLine` receive each output line as it comes.
44
63
  * @returns {Promise<{ code: number | null, stdout: string, timedOut: boolean }>}
45
64
  */
46
- export function run(cmd, args, timeoutMs, env = process.env) {
65
+ export function run(cmd, args, timeoutMs, env = process.env, signal, { cwd, onStdoutLine, onStderrLine } = {}) {
47
66
  return new Promise((resolve, reject) => {
48
- const child = spawn(cmd, args, { env, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true })
67
+ if (signal?.aborted) {
68
+ const err = new Error('Operation aborted')
69
+ err.name = 'AbortError'
70
+ return reject(err)
71
+ }
72
+ const child = spawn(cmd, args, {
73
+ env,
74
+ ...(cwd ? { cwd } : {}),
75
+ stdio: ['ignore', 'pipe', onStderrLine ? 'pipe' : 'ignore'],
76
+ windowsHide: true,
77
+ })
49
78
  let stdout = ''
50
79
  let timedOut = false
80
+ let aborted = false
51
81
  const timer = setTimeout(() => { timedOut = true; child.kill() }, timeoutMs)
52
- child.stdout.setEncoding('utf8').on('data', (chunk) => {
53
- if (stdout.length < MAX_OUTPUT) stdout += chunk
82
+ const onAbort = () => { aborted = true; child.kill() }
83
+ signal?.addEventListener('abort', onAbort, { once: true })
84
+ const cleanup = () => {
85
+ clearTimeout(timer)
86
+ signal?.removeEventListener('abort', onAbort)
87
+ }
88
+ const lines = (stream, each) => {
89
+ let rest = ''
90
+ stream.setEncoding('utf8').on('data', (chunk) => {
91
+ if (stream === child.stdout && stdout.length < MAX_OUTPUT) stdout += chunk
92
+ if (!each) return
93
+ rest += chunk
94
+ let nl
95
+ while ((nl = rest.indexOf('\n')) >= 0) {
96
+ const line = rest.slice(0, nl).replace(/\r$/, '')
97
+ rest = rest.slice(nl + 1)
98
+ try { each(line) } catch { /* a line handler never stops the run */ }
99
+ }
100
+ if (rest.length > MAX_OUTPUT) rest = ''
101
+ }).on('end', () => {
102
+ if (each && rest) {
103
+ try { each(rest) } catch { /* as above */ }
104
+ }
105
+ })
106
+ }
107
+ lines(child.stdout, onStdoutLine)
108
+ if (child.stderr) lines(child.stderr, onStderrLine)
109
+ child.once('error', (err) => { cleanup(); reject(err) })
110
+ child.once('close', (code) => {
111
+ cleanup()
112
+ if (aborted) {
113
+ const err = new Error('Operation aborted')
114
+ err.name = 'AbortError'
115
+ return reject(err)
116
+ }
117
+ resolve({ code, stdout, timedOut })
54
118
  })
55
- child.once('error', (err) => { clearTimeout(timer); reject(err) })
56
- child.once('close', (code) => { clearTimeout(timer); resolve({ code, stdout, timedOut }) })
57
119
  })
58
120
  }
59
121
 
@@ -62,39 +124,91 @@ export function run(cmd, args, timeoutMs, env = process.env) {
62
124
  * exported MESHY_API_KEY out of shell calls on purpose, so the host does not pass one on either,
63
125
  * and a dsh started from a dsh shell must not read back the credential it was handed.
64
126
  */
65
- function hostEnv() {
127
+ function hostEnv(extraEnv) {
66
128
  const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => {
67
129
  const key = k.toUpperCase()
68
130
  return key !== 'MESHY_API_KEY' && !key.startsWith('DSH_MESHY_')
69
131
  }))
132
+ if (extraEnv && typeof extraEnv === 'object') {
133
+ for (const [k, v] of Object.entries(extraEnv)) {
134
+ if (typeof v === 'string') env[k] = v
135
+ }
136
+ }
70
137
  if (ELECTRON) env.ELECTRON_RUN_AS_NODE = '1'
71
138
  return env
72
139
  }
73
140
 
74
- async function meshy(args, timeoutMs = 60_000) {
75
- const out = await run(process.execPath, [cli(), ...args, ...JSON_FLAGS], timeoutMs, hostEnv())
141
+ /**
142
+ * Run the bundled CLI and resolve to its v1 envelope. The plugin owns the output format (`json`,
143
+ * or `ndjson` with `stream`, whose `task` events go to `onEvent` as they arrive) and, with
144
+ * `workspace`, the CLI's write limit; both go before a `--` so they never read as arguments.
145
+ */
146
+ async function meshy(args, optsOrTimeout = 60_000) {
147
+ const opts = typeof optsOrTimeout === 'number' ? { timeoutMs: optsOrTimeout } : (optsOrTimeout ?? {})
148
+ const timeoutMs = opts.timeoutMs ?? 60_000
149
+ const owned = [
150
+ ...(opts.stream ? ['--format', 'ndjson', '--no-update-check'] : JSON_FLAGS),
151
+ ...(opts.workspace ? ['--workspace', opts.workspace] : []),
152
+ ]
153
+ const cut = args.indexOf('--')
154
+ const argv = cut >= 0 ? [...args.slice(0, cut), ...owned, ...args.slice(cut)] : [...args, ...owned]
155
+ let last = null
156
+ const onStdoutLine = opts.stream
157
+ ? (line) => {
158
+ if (!line.trim()) return
159
+ let event
160
+ try {
161
+ event = JSON.parse(line)
162
+ } catch {
163
+ return
164
+ }
165
+ last = event
166
+ if (event?.event === 'task') opts.onEvent?.(event)
167
+ }
168
+ : undefined
169
+ const out = await run(process.execPath, [cli(), ...argv], timeoutMs, hostEnv(opts.extraEnv), opts.signal, {
170
+ cwd: opts.cwd,
171
+ onStdoutLine,
172
+ onStderrLine: opts.onStderrLine,
173
+ })
174
+ const failed = (message) => ({ ok: false, error: { message } })
76
175
  let envelope
77
- try {
78
- envelope = JSON.parse(out.stdout)
79
- } catch {
80
- envelope = { ok: false, error: { message: out.timedOut ? 'timed out' : 'the Meshy CLI printed no result' } }
176
+ if (opts.stream) {
177
+ if (last && last.event !== 'task') {
178
+ const { event: _e, sequence: _s, ...body } = last
179
+ envelope = body
180
+ } else {
181
+ envelope = failed(out.timedOut ? 'timed out' : `the Meshy CLI ended without a result (exit ${out.code})`)
182
+ if (last?.result) envelope.result = last.result
183
+ }
184
+ } else {
185
+ try {
186
+ envelope = JSON.parse(out.stdout)
187
+ } catch {
188
+ envelope = failed(out.timedOut ? 'timed out' : 'the Meshy CLI printed no result')
189
+ }
81
190
  }
82
191
  return { ...envelope, timedOut: out.timedOut }
83
192
  }
84
193
 
85
194
  const regionOf = (baseUrl) => typeof baseUrl === 'string' && baseUrl.includes('meshy.cn') ? 'cn' : 'global'
86
195
 
196
+ function originOf(baseUrl) {
197
+ try {
198
+ return typeof baseUrl === 'string' && baseUrl ? new URL(baseUrl).origin : null
199
+ } catch {
200
+ return null
201
+ }
202
+ }
203
+
87
204
  /** The signed-in session handed to shells, or null while signed out. Never sent to a page. */
88
205
  let session = null
206
+ /** The API origin the CLI uses now (signed in or not), from the last session read. */
207
+ let apiOrigin = null
89
208
  let reading = null
90
209
  let watcher = null
91
210
  let watchedFile = null
92
211
 
93
- /**
94
- * Re-read the session as soon as the credentials file changes. A refresh by any other process (a
95
- * terminal, another agent) ends the access token this host holds, so waiting for the next timer
96
- * tick would hand shells a rejected token in the meantime.
97
- */
98
212
  function watchStore(file) {
99
213
  if (typeof file !== 'string' || !file || file === watchedFile) return
100
214
  stopWatching()
@@ -124,6 +238,7 @@ export function refreshSession() {
124
238
  .then((out) => {
125
239
  const r = out.result ?? {}
126
240
  watchStore(r.credentials_file)
241
+ apiOrigin = originOf(r.base_url_v1) ?? apiOrigin
127
242
  session = out.ok && r.authenticated === true && typeof r.token === 'string' && r.token
128
243
  ? {
129
244
  token: r.token,
@@ -144,17 +259,33 @@ const SHELL_VARIABLES = {
144
259
  DSH_MESHY_CREDENTIAL: { description: 'The Meshy sign-in, kept fresh by the plugin; the CLI reads it. Never print it.' },
145
260
  DSH_MESHY_REGION: { description: 'The Meshy site of that sign-in: global or cn.' },
146
261
  DSH_MESHY_SUBJECT: { description: 'The Meshy account the CLI binds its operation journal to.' },
147
- DSH_MESHY_STATE_DIR: { description: "Where the Meshy CLI keeps its operation journal: .meshy in the session's workspace." },
262
+ DSH_MESHY_STATE_DIR: { description: "Where the Meshy CLI keeps this chat's operation journal: .meshy/sessions/<chat> in the workspace." },
263
+ }
264
+
265
+ /** Observed session headers captured from shell/tool executions as a lookup fallback. */
266
+ const seenSessions = new Map()
267
+ /** A task still not finished this long after it started is shown as stale, not as running. */
268
+ const STALE_MS = 24 * 3600_000
269
+
270
+ function parseTimestamp(value) {
271
+ if (typeof value === 'number' && Number.isFinite(value)) return value
272
+ if (typeof value === 'string' && value) {
273
+ const parsed = Date.parse(value)
274
+ if (Number.isFinite(parsed)) return parsed
275
+ }
276
+ return 0
148
277
  }
149
278
 
150
279
  /** What one shell call gets: the CLI, the session while signed in, and a writable journal. */
151
280
  export function shellFacts(execution) {
152
281
  const facts = { DSH_MESHY_NODE: NODE, DSH_MESHY_CLI: cli() }
153
- const cwd = execution?.agent?.session?.header?.cwd
154
- if (typeof cwd === 'string' && cwd) facts.DSH_MESHY_STATE_DIR = join(cwd, '.meshy')
282
+ const header = execution?.agent?.session?.header
283
+ const cwd = header?.cwd
284
+ if (typeof header?.id === 'string' && header.id && typeof cwd === 'string' && cwd) {
285
+ seenSessions.set(header.id, { cwd, createdAt: parseTimestamp(header.createdAt) })
286
+ }
287
+ if (typeof cwd === 'string' && cwd) facts.DSH_MESHY_STATE_DIR = sessionStateDir(cwd, header?.id)
155
288
  if (session) {
156
- // After a sleep the timer may not have run yet: refresh now, and leave out a token that
157
- // would be rejected (the CLI then explains, and the next call has the fresh one).
158
289
  const left = session.expiresAt === null ? Infinity : session.expiresAt - Date.now()
159
290
  if (left < 60_000) void refreshSession()
160
291
  if (left > 0) {
@@ -170,8 +301,7 @@ let signingIn = null
170
301
 
171
302
  /**
172
303
  * Start a browser sign-in on the host and finish it in the background: the CLI polls until the
173
- * user approves or the code expires, and the session is re-read when it lands. A second call
174
- * while one is waiting returns the same link and code.
304
+ * user approves or the code expires, and the session is re-read when it lands.
175
305
  */
176
306
  export async function signIn(region) {
177
307
  if (signingIn?.region === region) return signingIn.view
@@ -181,7 +311,6 @@ export async function signIn(region) {
181
311
  throw new Error(started.error?.message ?? 'the Meshy CLI could not start a sign-in')
182
312
  }
183
313
  const expiresIn = typeof r.expires_in === 'number' ? r.expires_in : 600
184
- // Only what the user needs: an older CLI also prints the device code, a bearer secret.
185
314
  const view = { status: 'waiting_for_approval', verification_url: r.verification_url, user_code: String(r.user_code ?? ''), expires_in: expiresIn }
186
315
  const attempt = { region, view }
187
316
  signingIn = attempt
@@ -192,43 +321,6 @@ export async function signIn(region) {
192
321
  return view
193
322
  }
194
323
 
195
- const SIGN_IN_TOOL = {
196
- name: 'meshy_sign_in',
197
- description:
198
- 'Sign the user in to Meshy, and how to run Meshy here. In DeepSeek Harness the Meshy plugin ships ' +
199
- 'the Meshy CLI and keeps the sign-in: run every Meshy command as "$DSH_MESHY_NODE" "$DSH_MESHY_CLI" ' +
200
- '<command> (PowerShell: & $env:DSH_MESHY_NODE $env:DSH_MESHY_CLI <command>), never a `meshy` found ' +
201
- 'on PATH, which cannot see this sign-in, and install nothing. Call this tool only when such a ' +
202
- 'command reports that nobody is signed in or the session was rejected; never run `auth login` in ' +
203
- 'the shell, which cannot store a login. It returns a link and a code: show both to the user, wait ' +
204
- 'until they say they approved it, then retry the command. Use region "cn" only when the user signs ' +
205
- 'in on the China site (meshy.cn).',
206
- parameters: {
207
- type: 'object',
208
- properties: { region: { type: 'string', enum: ['global', 'cn'], description: 'Meshy site; default global.' } },
209
- additionalProperties: false,
210
- },
211
- output: {
212
- schema: {
213
- type: 'object',
214
- properties: {
215
- status: { type: 'string' },
216
- verification_url: { type: 'string' },
217
- user_code: { type: 'string' },
218
- expires_in: { type: 'integer' },
219
- },
220
- required: ['status', 'verification_url', 'user_code', 'expires_in'],
221
- additionalProperties: false,
222
- },
223
- render: (_args, v) => [{ type: 'text', text: `Open ${v.verification_url} and confirm code ${v.user_code} (valid ${Math.round(v.expires_in / 60)} minutes).` }],
224
- },
225
- async execute(args) {
226
- const region = args?.region ?? 'global'
227
- if (!REGIONS.has(region)) throw new Error('meshy_sign_in: region must be global or cn')
228
- return signIn(region)
229
- },
230
- }
231
-
232
324
  const json = (body, status = 200) => Response.json(body, { status, headers: { 'cache-control': 'no-store' } })
233
325
  const failure = (envelope, status = 502) => json({ error: envelope.error?.message ?? 'the Meshy CLI failed' }, status)
234
326
 
@@ -241,30 +333,30 @@ async function body(request) {
241
333
  }
242
334
  }
243
335
 
244
- export async function status() {
245
- const version = await run(process.execPath, [cli(), '--version'], 30_000, hostEnv()).catch(() => undefined)
246
- if (!version || version.code !== 0) return json({ cli: null, error: 'Meshy CLI not found: reinstall the Meshy plugin' })
336
+ export async function readAuthStatus() {
247
337
  const auth = await meshy(['auth', 'status'])
248
338
  const r = auth.result ?? {}
249
339
  const text = (v) => typeof v === 'string' && v ? v : null
340
+ return {
341
+ authenticated: r.authenticated === true,
342
+ verified: r.verified === true,
343
+ method: r.authenticated !== true ? null : String(r.credential ?? '').startsWith('msy_at_') ? 'browser' : 'apiKey',
344
+ account: r.account && (text(r.account.name) || text(r.account.email)) ? { name: text(r.account.name), email: text(r.account.email) } : null,
345
+ region: regionOf(r.base_url_v1),
346
+ balance: typeof r.balance?.balance === 'number' ? r.balance.balance : null,
347
+ hint: r.hint ?? null,
348
+ }
349
+ }
350
+
351
+ export async function status() {
352
+ const version = await run(process.execPath, [cli(), '--version'], 30_000, hostEnv()).catch(() => undefined)
353
+ if (!version || version.code !== 0) return json({ cli: null, error: 'Meshy CLI not found: reinstall the Meshy plugin' })
250
354
  return json({
251
355
  cli: { version: version.stdout.trim() },
252
- auth: {
253
- authenticated: r.authenticated === true,
254
- verified: r.verified === true,
255
- // How it signed in, never the credential: an OAuth access token starts msy_at_.
256
- method: r.authenticated !== true ? null : String(r.credential ?? '').startsWith('msy_at_') ? 'browser' : 'apiKey',
257
- // Who signed in, when the site reports it (not for an API key, a login before CLI 0.8, or
258
- // the China site yet).
259
- account: r.account && (text(r.account.name) || text(r.account.email)) ? { name: text(r.account.name), email: text(r.account.email) } : null,
260
- region: regionOf(r.base_url_v1),
261
- balance: typeof r.balance?.balance === 'number' ? r.balance.balance : null,
262
- hint: r.hint ?? null,
263
- },
356
+ auth: await readAuthStatus(),
264
357
  })
265
358
  }
266
359
 
267
- /** Compare two plain x.y.z versions; NaN when either is not one, so every comparison fails. */
268
360
  function compare(a, b) {
269
361
  const x = RELEASE.exec(String(a)), y = RELEASE.exec(String(b))
270
362
  if (!x || !y) return NaN
@@ -272,10 +364,6 @@ function compare(a, b) {
272
364
  return 0
273
365
  }
274
366
 
275
- /**
276
- * The release a reinstall would bring, when it is newer than `current`: the highest version up to
277
- * `latest` that has been out for a day. Prereleases and malformed entries are never offered.
278
- */
279
367
  export function pickUpdate(packument, current, now = Date.now()) {
280
368
  const latest = packument?.['dist-tags']?.latest
281
369
  let best = null
@@ -290,7 +378,6 @@ let packument = null
290
378
  let checkedAt = 0
291
379
  let checking = null
292
380
 
293
- /** Read the published releases again once the last read is six hours old; a failed read retries next time. */
294
381
  function checkForUpdate() {
295
382
  if (Date.now() - checkedAt < UPDATE_CHECK_MS) return Promise.resolve()
296
383
  checking ??= (async () => {
@@ -324,14 +411,12 @@ export async function loginStart(request) {
324
411
  const started = await meshy(['auth', 'login', '--device', '--no-wait', '--region', region])
325
412
  const r = started.result ?? {}
326
413
  if (!started.ok || typeof r.verification_url !== 'string' || !r.verification_url.startsWith('https://')) return failure(started)
327
- // Only what the page shows: an older CLI also prints the device code, a bearer secret.
328
414
  return json({ verification_url: r.verification_url, user_code: r.user_code, flow_id: r.flow_id, expires_in: r.expires_in })
329
415
  }
330
416
 
331
417
  export async function loginFinish(request) {
332
418
  const input = await body(request)
333
419
  if (typeof input?.flow_id !== 'string' || !FLOW_ID.test(input.flow_id)) return json({ error: 'invalid flow_id' }, 400)
334
- // `=` keeps an id that starts with "-" from reading as an option.
335
420
  const done = await meshy(['auth', 'login', `--device-flow=${input.flow_id}`], 60_000)
336
421
  if (done.timedOut) return json({ status: 'pending' }, 202)
337
422
  if (!done.ok) return failure(done)
@@ -345,15 +430,332 @@ export async function logout() {
345
430
  return out.ok ? json({ status: 'logged_out' }) : failure(out)
346
431
  }
347
432
 
348
- const ROUTES = [
349
- ['/api/meshy.status', 'GET', status],
350
- ['/api/meshy.update', 'GET', update],
351
- ['/api/meshy.login', 'POST', loginStart],
352
- ['/api/meshy.login.finish', 'POST', loginFinish],
353
- ['/api/meshy.logout', 'POST', logout],
354
- ]
433
+ function headerFacts(header) {
434
+ if (!header || typeof header !== 'object') return null
435
+ const cwd = typeof header.cwd === 'string' && header.cwd ? header.cwd : null
436
+ if (!cwd) return null
437
+ return { cwd, createdAt: parseTimestamp(header.createdAt) }
438
+ }
439
+
440
+ function getService(ctx, name) {
441
+ if (!ctx || typeof ctx !== 'object') return undefined
442
+ if (typeof ctx.get === 'function') return ctx.get(name)
443
+ return ctx[name]
444
+ }
445
+
446
+ /**
447
+ * Resolve a session's `{ cwd, createdAt }`: the live session's header (`ctx.sessions.get(id)`),
448
+ * else the stored one (`ctx.sessionPersistence.stat(id)`), else a header seen in a shell call.
449
+ */
450
+ export async function resolveSession(ctx, sessionId) {
451
+ if (typeof sessionId !== 'string' || !sessionId) return null
452
+ try {
453
+ const live = getService(ctx, 'sessions')?.get?.(sessionId)
454
+ const facts = headerFacts(live?.header)
455
+ if (facts) return facts
456
+ } catch {
457
+ // Fall through to the stored header.
458
+ }
459
+ try {
460
+ const stored = await getService(ctx, 'sessionPersistence')?.stat?.(sessionId)
461
+ const facts = headerFacts(stored?.header)
462
+ if (facts) return facts
463
+ } catch {
464
+ // Fall through to headers seen in shell calls.
465
+ }
466
+ return seenSessions.get(sessionId) ?? null
467
+ }
468
+
469
+ function createHostRuntime(ctx, { cliImpl = meshy, eventsBus = createEventBus(), now = Date.now, currentOrigin = () => apiOrigin } = {}) {
470
+ const catalog = createCatalog({ cli: cliImpl })
471
+ const taskStates = createTaskStates({ cli: cliImpl, catalog })
472
+ const library = createLibraryReader({ cli: cliImpl, catalog })
473
+
474
+ /** The chat state directories under a workspace (for the whole-workspace view). */
475
+ async function chatStateDirs(cwd) {
476
+ const root = join(cwd, ...SESSIONS_DIR)
477
+ try {
478
+ const names = await readdir(root, { withFileTypes: true })
479
+ return names.filter((d) => d.isDirectory()).slice(0, 200).map((d) => join(root, d.name))
480
+ } catch {
481
+ return []
482
+ }
483
+ }
484
+
485
+ /**
486
+ * A chat's operation records, newest first: its own CLI state directory, plus the shared journal
487
+ * of plugin versions before 0.4.0, attributed by time (records started since the chat began).
488
+ */
489
+ async function chatJournal(meta, sessionId, scope) {
490
+ const dirs = scope === 'workspace' ? await chatStateDirs(meta.cwd) : [sessionStateDir(meta.cwd, sessionId)]
491
+ const legacySince = scope === 'workspace' ? 0 : Math.max(0, (meta.createdAt || 0) - 5000)
492
+ const lists = await Promise.all([
493
+ readJournal(join(meta.cwd, ...JOURNAL), { since: legacySince }),
494
+ ...dirs.map((dir) => readJournal(join(dir, 'operations'))),
495
+ ])
496
+ const byId = new Map()
497
+ for (const r of lists.flat()) if (!byId.has(r.operationId)) byId.set(r.operationId, r)
498
+ return [...byId.values()].sort((a, b) => b.startedAt - a.startedAt).slice(0, 50)
499
+ }
500
+
501
+ async function sessionTasks(sessionId, { light = false, scope = 'session', fallback } = {}) {
502
+ const meta = (await resolveSession(ctx, sessionId)) ?? (fallback?.cwd ? { cwd: fallback.cwd, createdAt: parseTimestamp(fallback.createdAt) } : null)
503
+ if (!meta?.cwd) return light ? { workspace: null, tasks: [] } : { workspace: null, tasks: [], models: [] }
504
+ const records = await chatJournal(meta, sessionId, scope)
505
+ if (light) {
506
+ return {
507
+ workspace: meta.cwd,
508
+ tasks: records.map((r) => ({ id: r.operationId, startedAt: r.startedAt })),
509
+ }
510
+ }
511
+
512
+ // A record another CLI submitted to a different API origin cannot be read with this sign-in.
513
+ const here = currentOrigin()
514
+ const foreign = (r) => Boolean(here && r.apiOrigin && r.apiOrigin !== here)
515
+ const [models, assets, states] = await Promise.all([
516
+ listModels(meta.cwd),
517
+ readAssetIndex(meta.cwd),
518
+ Promise.all(records.map((r) => r.state === 'accepted' && r.taskId && !foreign(r) ? taskStates.get(r.resource, r.taskId) : undefined)),
519
+ ])
520
+ const tasks = records.map((r, i) => {
521
+ const state = states[i]
522
+ const v = state?.view ?? null
523
+ const saved = r.taskId ? assets[r.taskId] ?? null : null
524
+ // A row is stale when its task cannot be read (another API origin, a 404, a failed read),
525
+ // or it has not finished a day after it started: no live status is shown, and nothing
526
+ // should keep polling it.
527
+ const unread = r.state === 'accepted' && Boolean(r.taskId) && !v
528
+ const unfinished = !r.error && !TERMINAL.has(v?.status) && now() - r.startedAt > STALE_MS
529
+ const stale = unread || unfinished
530
+ return {
531
+ id: r.operationId,
532
+ resource: r.resource,
533
+ kind: outputKind(v) ?? saved?.kind ?? kindOfResource(r.resource),
534
+ taskId: r.taskId,
535
+ callId: saved?.callId ?? null,
536
+ jobId: saved?.jobId ?? null,
537
+ stage: saved?.stage ?? null,
538
+ startedAt: r.startedAt,
539
+ journal: r.state,
540
+ submitError: r.error,
541
+ status: stale ? null : (v?.status ?? null),
542
+ ...(stale ? { stale: true } : {}),
543
+ progress: stale ? null : (v?.progress ?? null),
544
+ title: saved?.title ?? v?.name ?? v?.prompt ?? null,
545
+ name: v?.name ?? null,
546
+ prompt: v?.prompt ?? saved?.prompt ?? null,
547
+ type: v?.type ?? null,
548
+ createdAt: v?.createdAt ?? null,
549
+ finishedAt: v?.finishedAt ?? null,
550
+ expiresAt: v?.expiresAt ?? null,
551
+ credits: v?.credits ?? null,
552
+ thumbnail: v?.thumbnail ?? null,
553
+ model: Boolean(v?.glb || v?.printFile),
554
+ variants: v?.variants ?? [],
555
+ formats: v?.formats ?? [],
556
+ localFile: saved?.file ?? null,
557
+ files: saved?.files ?? [],
558
+ parentTaskId: v?.parentTaskId ?? null,
559
+ error: v?.error ?? null,
560
+ readError: foreign(r) ? 'submitted through another Meshy API; not readable with this sign-in' : (state?.failed ?? null),
561
+ }
562
+ })
563
+
564
+ // Fill localFile from workspace models if a file name contains the task id and wasn't cached yet.
565
+ for (const t of tasks) {
566
+ if (!t.localFile && t.taskId) {
567
+ const match = models.find((m) => m.file.includes(t.taskId))
568
+ if (match) t.localFile = match.file
569
+ }
570
+ }
571
+
572
+ return { workspace: meta.cwd, tasks, models }
573
+ }
574
+
575
+ async function handleTasks(request) {
576
+ const url = new URL(request.url)
577
+ const sessionId = url.searchParams.get('session') ?? ''
578
+ if (!sessionId) return json({ workspace: null, tasks: [], models: [] })
579
+ const light = url.searchParams.get('light') === '1'
580
+ const scope = url.searchParams.get('scope') === 'workspace' ? 'workspace' : 'session'
581
+ return json(await sessionTasks(sessionId, { light, scope }))
582
+ }
583
+
584
+ async function handleLibrary(request) {
585
+ const url = new URL(request.url)
586
+ const limitParam = url.searchParams.get('limit')
587
+ const limit = limitParam ? Number.parseInt(limitParam, 10) : 24
588
+ const resource = url.searchParams.get('resource') || undefined
589
+ const refresh = url.searchParams.get('refresh') === '1'
590
+ try {
591
+ return json(await library.list({ resource, limit, refresh }))
592
+ } catch (err) {
593
+ return json({ error: String(err?.message ?? err) }, err?.statusCode ?? 500)
594
+ }
595
+ }
596
+
597
+ async function handleModel(request) {
598
+ const url = new URL(request.url)
599
+ const sessionId = url.searchParams.get('session')
600
+ const file = url.searchParams.get('file')
601
+ if (sessionId && file) {
602
+ const meta = await resolveSession(ctx, sessionId)
603
+ if (!meta?.cwd) return json({ error: 'session workspace not found' }, 404)
604
+ try {
605
+ return await serveWorkspaceModel(meta.cwd, file)
606
+ } catch (err) {
607
+ return json({ error: String(err?.message ?? err) }, err?.statusCode ?? 400)
608
+ }
609
+ }
610
+
611
+ const resource = url.searchParams.get('resource')
612
+ const taskId = url.searchParams.get('task')
613
+ if (!resource || !taskId || !(await catalog.taskArgs(resource, 'get', taskId))) {
614
+ return json({ error: 'provide either (resource, task) or (session, file)' }, 400)
615
+ }
616
+ const state = await taskStates.get(resource, taskId)
617
+ // `variant` picks one GLB of a task that has several (a rigging task's walking/running).
618
+ const variant = url.searchParams.get('variant')
619
+ // A task with no GLB shows its print file (a multi-color 3MF).
620
+ const glb = variant ? state?.view?.glbs?.[variant] : state?.view?.glb ?? state?.view?.printFile
621
+ if (!glb) {
622
+ return json({ error: state?.failed ?? (variant ? `no ${variant} model for this task` : 'model not available for this task') }, 404)
623
+ }
624
+ try {
625
+ return await fetchModel(glb)
626
+ } catch (err) {
627
+ return json({ error: String(err?.message ?? err) }, err?.statusCode ?? 502)
628
+ }
629
+ }
630
+
631
+ async function handleEvents(request) {
632
+ const url = new URL(request.url)
633
+ const sessionId = url.searchParams.get('session') ?? ''
634
+ if (!sessionId) return json({ error: 'session is required' }, 400)
635
+ const meta = await resolveSession(ctx, sessionId)
636
+ let workspaceRoot = null
637
+ if (meta?.cwd) {
638
+ workspaceRoot = await realpath(meta.cwd).catch(() => meta.cwd)
639
+ }
640
+
641
+ const encoder = new TextEncoder()
642
+ let unsubscribe = () => {}
643
+ let pingTimer = null
644
+
645
+ const stream = new ReadableStream({
646
+ start(controller) {
647
+ const push = (chunk) => {
648
+ try {
649
+ controller.enqueue(encoder.encode(chunk))
650
+ } catch {
651
+ cleanup()
652
+ }
653
+ }
654
+ const cleanup = () => {
655
+ unsubscribe()
656
+ unsubscribe = () => {}
657
+ if (pingTimer) { clearInterval(pingTimer); pingTimer = null }
658
+ }
659
+
660
+ push('retry: 3000\n\n')
661
+
662
+ unsubscribe = eventsBus.subscribe((event) => {
663
+ const matchesSession = Boolean(event.sessionId && event.sessionId === sessionId)
664
+ const matchesWorkspace = Boolean(
665
+ event.workspace && (
666
+ (workspaceRoot && event.workspace === workspaceRoot)
667
+ || (meta?.cwd && event.workspace === meta.cwd)
668
+ ),
669
+ )
670
+ if (!matchesSession && !matchesWorkspace) return
671
+ // Strip internal routing fields so the host workspace path never leaks to the browser.
672
+ const { sessionId: _s, workspace: _w, ...publicPayload } = event
673
+ push(`data: ${JSON.stringify(publicPayload)}\n\n`)
674
+ })
675
+
676
+ pingTimer = setInterval(() => push(': ping\n\n'), SSE_PING_MS)
677
+ pingTimer.unref?.()
678
+
679
+ request.signal?.addEventListener('abort', () => {
680
+ cleanup()
681
+ try { controller.close() } catch { /* already closed */ }
682
+ }, { once: true })
683
+ },
684
+ cancel() {
685
+ unsubscribe()
686
+ unsubscribe = () => {}
687
+ if (pingTimer) { clearInterval(pingTimer); pingTimer = null }
688
+ },
689
+ })
690
+
691
+ return new Response(stream, {
692
+ status: 200,
693
+ headers: {
694
+ 'content-type': 'text/event-stream; charset=utf-8',
695
+ 'cache-control': 'no-store',
696
+ connection: 'keep-alive',
697
+ 'x-accel-buffering': 'no',
698
+ },
699
+ })
700
+ }
701
+
702
+ async function handleEnvHdr() {
703
+ const stream = Readable.toWeb(createReadStream(ENV_HDR_PATH))
704
+ return new Response(stream, {
705
+ status: 200,
706
+ headers: {
707
+ 'content-type': 'application/octet-stream',
708
+ 'cache-control': 'public, max-age=86400',
709
+ },
710
+ })
711
+ }
712
+
713
+ const { tools, meshyTool } = createTools({ ctx, cli: cliImpl, catalog, signIn, events: eventsBus })
714
+
715
+ const service = createMeshyService({
716
+ getStatus: async () => {
717
+ const auth = await readAuthStatus()
718
+ return {
719
+ authenticated: auth.authenticated,
720
+ verified: auth.verified,
721
+ region: auth.region,
722
+ account: auth.account,
723
+ balance: auth.balance,
724
+ }
725
+ },
726
+ sessionTasks,
727
+ library,
728
+ taskStates,
729
+ events: eventsBus,
730
+ meshyTool,
731
+ })
732
+
733
+ const handleInput = createInputRoute({
734
+ workspaceOf: async (sessionId) => (await resolveSession(ctx, sessionId))?.cwd ?? null,
735
+ })
736
+
737
+ const routes = [
738
+ ['/api/meshy.status', 'GET', status],
739
+ ['/api/meshy.update', 'GET', update],
740
+ ['/api/meshy.login', 'POST', loginStart],
741
+ ['/api/meshy.login.finish', 'POST', loginFinish],
742
+ ['/api/meshy.logout', 'POST', logout],
743
+ ['/api/meshy.tasks', 'GET', handleTasks],
744
+ ['/api/meshy.library', 'GET', handleLibrary],
745
+ ['/api/meshy.model', 'GET', handleModel],
746
+ ['/api/meshy.input', 'POST', handleInput],
747
+ ['/api/meshy.events', 'GET', handleEvents],
748
+ ['/api/meshy.env.hdr', 'GET', handleEnvHdr],
749
+ ]
750
+
751
+ return { routes, tools, service, events: eventsBus, taskStates, library, catalog }
752
+ }
753
+
754
+ export { createHostRuntime }
355
755
 
356
756
  export function apply(ctx) {
757
+ const runtime = createHostRuntime(ctx)
758
+
357
759
  ctx.effect(() => {
358
760
  void refreshSession()
359
761
  const timer = setInterval(refreshSession, SESSION_REFRESH_MS)
@@ -363,15 +765,26 @@ export function apply(ctx) {
363
765
  stopWatching()
364
766
  }
365
767
  }, 'meshy-dsh: session refresh')
366
- ctx.inject(['shellEnv'], (ctx) => {
367
- ctx.shellEnv.register({ name: 'meshy', variables: SHELL_VARIABLES, resolve: shellFacts })
768
+
769
+ if (typeof ctx.provide === 'function') {
770
+ ctx.provide('meshy', runtime.service)
771
+ }
772
+
773
+ ctx.inject(['shellEnv'], (inner) => {
774
+ inner.shellEnv.register({ name: 'meshy', variables: SHELL_VARIABLES, resolve: shellFacts })
368
775
  })
369
- ctx.inject(['tools'], (ctx) => {
370
- ctx.tools.register(SIGN_IN_TOOL)
776
+
777
+ ctx.inject(['tools'], (inner) => {
778
+ for (const tool of runtime.tools) inner.tools.register(tool)
371
779
  })
372
- ctx.inject(['connection'], (ctx) => {
373
- for (const [path, method, handle] of ROUTES) {
374
- ctx.effect(() => ctx.connection.fetch.register({
780
+
781
+ ctx.inject(['systemPrompt'], (inner) => {
782
+ registerCompose(inner, ctx)
783
+ })
784
+
785
+ ctx.inject(['connection'], (inner) => {
786
+ for (const [path, method, handle] of runtime.routes) {
787
+ inner.effect(() => inner.connection.fetch.register({
375
788
  path,
376
789
  methods: [method],
377
790
  requestBody: 'buffered',