@lincyaw/cli 1.0.0-rc.116 → 1.0.0-rc.118

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/cli",
3
- "version": "1.0.0-rc.116",
3
+ "version": "1.0.0-rc.118",
4
4
  "description": "The presmium command: build, dev, ir, check and serve for Presmium documents",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -37,10 +37,10 @@
37
37
  "dependencies": {
38
38
  "jiti": "^2.7.0",
39
39
  "yaml": "^2.9.1",
40
- "@lincyaw/compiler": "1.0.0-rc.116",
41
- "@lincyaw/server": "1.0.0-rc.116",
42
- "@lincyaw/kernel": "1.0.0-rc.116",
43
- "@lincyaw/skills": "1.0.0-rc.116",
44
- "@lincyaw/workspace": "1.0.0-rc.116"
40
+ "@lincyaw/compiler": "1.0.0-rc.118",
41
+ "@lincyaw/workspace": "1.0.0-rc.118",
42
+ "@lincyaw/server": "1.0.0-rc.118",
43
+ "@lincyaw/skills": "1.0.0-rc.118",
44
+ "@lincyaw/kernel": "1.0.0-rc.118"
45
45
  }
46
46
  }
package/src/cli.ts CHANGED
@@ -6,7 +6,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url'
6
6
  import { parseArgs } from 'node:util'
7
7
  import { createJiti } from 'jiti'
8
8
  import { APPROVAL_KINDS, deckLocale, errorMessage } from '@lincyaw/kernel'
9
- import { bracketIPv6, irRevision, lanAddresses } from '@lincyaw/kernel/node'
9
+ import { bracketIPv6, irRevision, lanAddresses, ServiceUpgradeError } from '@lincyaw/kernel/node'
10
10
  import type { ApprovalKind, Finding, Severity, SpeechVoice } from '@lincyaw/kernel'
11
11
  import { build, Compiler, dev, resolveEntry } from '@lincyaw/compiler'
12
12
  import type { BuildReport, Compilation, RunStats } from '@lincyaw/compiler'
@@ -97,7 +97,7 @@ export async function main(argv: string[], options: MainOptions = {}): Promise<n
97
97
  case 'serve': return await runServeCommand(command, bundled)
98
98
  }
99
99
  } catch (error) {
100
- process.stderr.write(`presmium: ${typeof error === 'object' && error !== null && 'code' in error && error.code === 'workspace-service-already-running' ? t.workspaceServiceBusy('url' in error && typeof error.url === 'string' ? error.url : undefined) : errorMessage(error)}\n`)
100
+ process.stderr.write(`presmium: ${error instanceof ServiceUpgradeError ? t.workspaceServiceUpgrade(error.reason, error.version) : typeof error === 'object' && error !== null && 'code' in error && error.code === 'workspace-service-already-running' ? t.workspaceServiceBusy('url' in error && typeof error.url === 'string' ? error.url : undefined) : errorMessage(error)}\n`)
101
101
  return 2
102
102
  }
103
103
  }
@@ -291,27 +291,40 @@ async function runDevCommand(command: Command, bundled: string): Promise<number>
291
291
  }
292
292
 
293
293
  async function runServeCommand(command: Command, bundled: string): Promise<number> {
294
- const started = await serveWorkspace({
295
- dir: command.entry,
296
- listenAddress: command.listenAddress,
297
- port: command.port,
298
- ...command.operatorDir ? { operatorDir: resolve(command.operatorDir) } : {},
299
- bundled,
300
- check: compilation => compilation.check(),
301
- previewOrigins: command.previewOrigins,
302
- ...command.publicUrl ? { publicUrl: command.publicUrl } : {},
303
- allow: command.allow,
304
- })
305
- process.stdout.write(`serve ${started.url}\n${networkLines(command.listenAddress, started.url)}workspace ${started.root}\nmcp ${started.mcp.url}${t.token(started.mcp.stateFile)}\n`)
306
- if (command.listenAddress && !isLoopback(command.listenAddress)) {
307
- process.stderr.write(`${t.serveOpen(command.listenAddress, new URL(started.url).port)}\n`)
294
+ const stop = new AbortController(), quit = () => stop.abort()
295
+ const parentPipe = process.env.PRESMIUM_SERVICE_PARENT_PIPE === '1'
296
+ delete process.env.PRESMIUM_SERVICE_PARENT_PIPE
297
+ process.once('SIGINT', quit)
298
+ process.once('SIGTERM', quit)
299
+ if (parentPipe) { process.stdin.once('end', quit); process.stdin.resume() }
300
+ try {
301
+ const started = await serveWorkspace({
302
+ dir: command.entry,
303
+ listenAddress: command.listenAddress,
304
+ port: command.port,
305
+ ...command.operatorDir ? { operatorDir: resolve(command.operatorDir) } : {},
306
+ bundled,
307
+ check: compilation => compilation.check(),
308
+ previewOrigins: command.previewOrigins,
309
+ ...command.publicUrl ? { publicUrl: command.publicUrl } : {},
310
+ allow: command.allow,
311
+ signal: stop.signal,
312
+ onUpgrade: version => { process.stdout.write(`service-upgrade ${version}\n`); quit() },
313
+ })
314
+ try {
315
+ process.stdout.write(`serve ${started.url}\n${networkLines(command.listenAddress, started.url)}workspace ${started.root}\nmcp ${started.mcp.url}${t.token(started.mcp.stateFile)}\n`)
316
+ if (command.listenAddress && !isLoopback(command.listenAddress)) process.stderr.write(`${t.serveOpen(command.listenAddress, new URL(started.url).port)}\n`)
317
+ if (!stop.signal.aborted) await new Promise<void>(done => stop.signal.addEventListener('abort', () => done(), { once: true }))
318
+ } finally { await started.close() }
319
+ return 0
320
+ } catch (error) {
321
+ if (stop.signal.aborted) return 0
322
+ throw error
323
+ } finally {
324
+ process.removeListener('SIGINT', quit)
325
+ process.removeListener('SIGTERM', quit)
326
+ if (parentPipe) { process.stdin.removeListener('end', quit); process.stdin.pause() }
308
327
  }
309
- await new Promise<void>((done) => {
310
- process.once('SIGINT', done)
311
- process.once('SIGTERM', done)
312
- })
313
- await started.close()
314
- return 0
315
328
  }
316
329
 
317
330
  function resolveInstalled(name: string, bundled: string): string | undefined {
@@ -533,8 +546,8 @@ async function runMcpCommand(argv: string[], bundled: string): Promise<number> {
533
546
  }
534
547
  console.log = console.info = console.debug = console.error
535
548
  const workspace = mcpWorkspaceSession(bundled)
536
- const { main: mcpMain } = await createJiti(import.meta.url).import<{ main(argv: string[], options: { bundled: string, startWorkspace: typeof workspace.startWorkspace }): Promise<number | undefined> }>(entry)
537
- try { return await mcpMain(argv, { bundled, startWorkspace: workspace.startWorkspace }) ?? 0 }
549
+ const { main: mcpMain } = await createJiti(import.meta.url).import<{ main(argv: string[], options: { bundled: string, startWorkspace: typeof workspace.startWorkspace, locateWorkspace: typeof workspace.locateWorkspace }): Promise<number | undefined> }>(entry)
550
+ try { return await mcpMain(argv, { bundled, startWorkspace: workspace.startWorkspace, locateWorkspace: workspace.locateWorkspace }) ?? 0 }
538
551
  catch (error) { return fail(errorMessage(error), 2) }
539
552
  finally { await workspace.close() }
540
553
  }
@@ -1,75 +1,101 @@
1
- import { existsSync, realpathSync } from 'node:fs'
1
+ import { existsSync, readFileSync, realpathSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
+ import { createInterface } from 'node:readline'
3
4
  import { setTimeout as delay } from 'node:timers/promises'
5
+ import type { ChildProcess } from 'node:child_process'
4
6
  import { findWorkspaceRoot, WORKSPACE_CONFIG } from '@lincyaw/compiler'
5
- import { findWorkspaceServiceState, readServiceState, serveStateDir, tryAcquireServiceHostLease } from '@lincyaw/kernel/node'
7
+ import { compareServiceVersion, findWorkspaceServiceState, readServiceState, serveStateDir, SERVICE_VERSION, ServiceUpgradeError, spawnInteractiveNode, upgradeWorkspaceService } from '@lincyaw/kernel/node'
6
8
  import type { ApprovalKind } from '@lincyaw/kernel'
7
- import type { ServiceHostLease, ServiceState } from '@lincyaw/kernel/node'
8
- import { serveWorkspace } from '@lincyaw/workspace'
9
- import type { WorkspaceServer } from '@lincyaw/workspace'
9
+ import type { ServiceState } from '@lincyaw/kernel/node'
10
+ import { CLI_MESSAGES, systemLocale } from './messages.ts'
10
11
 
11
12
  interface WorkspaceTarget { mcp: string, token: string, pid: number }
12
13
  export interface McpWorkspaceConnection { target: WorkspaceTarget, close(): Promise<void> }
14
+ interface OwnedHost { child: ChildProcess, exited: Promise<void> }
13
15
 
14
- /** One stdio session may own the shared host; every other session borrows its published endpoint. */
16
+ /** Stdio relays survive host upgrades. Each elected host loads its installation in a fresh Node process. */
15
17
  export function mcpWorkspaceSession(bundled: string) {
16
- let root: Promise<string> | undefined, owned: { server: WorkspaceServer, lease: ServiceHostLease } | undefined
18
+ let root: Promise<string> | undefined, owned: OwnedHost | undefined
19
+ let minimumVersion = SERVICE_VERSION
17
20
  let closed = false, pending: Promise<McpWorkspaceConnection> | undefined, closing: Promise<void> | undefined
21
+ const stopped = new AbortController()
18
22
  const closeOwned = async () => {
19
23
  const current = owned
20
24
  owned = undefined
21
- await current?.server.close()
25
+ if (!current) return
26
+ current.child.stdin?.end()
27
+ await Promise.race([current.exited, delay(8000, undefined, { ref: false })])
28
+ if (current.child.exitCode === null && current.child.signalCode === null) current.child.kill()
29
+ await current.exited
22
30
  }
23
31
  const close = (): Promise<void> => closing ??= Promise.resolve().then(async () => {
24
32
  closed = true
33
+ stopped.abort()
25
34
  await pending?.catch(() => undefined)
26
35
  await closeOwned()
27
36
  })
28
- const target = (state: ServiceState): WorkspaceTarget => ({ mcp: state.mcp, token: state.token, pid: state.pid })
37
+ const target = (state: ServiceState): WorkspaceTarget => {
38
+ if (state.version && compareServiceVersion(state, minimumVersion) > 0) minimumVersion = state.version
39
+ return { mcp: state.mcp, token: state.token, pid: state.pid }
40
+ }
41
+ const installation = () => {
42
+ let installed: { version: string, bin: { presmium: string } } | undefined
43
+ try { installed = JSON.parse(readFileSync(join(bundled, 'package.json'), 'utf8')) } catch {}
44
+ const version = installed && compareServiceVersion({ version: installed.version }, minimumVersion) > 0 ? installed.version : minimumVersion
45
+ return { installed, version }
46
+ }
29
47
  return {
48
+ locateWorkspace(dir: string): WorkspaceTarget | undefined {
49
+ const found = findWorkspaceServiceState(dir)
50
+ return found && compareServiceVersion(found.state, installation().version) >= 0 ? target(found.state) : undefined
51
+ },
30
52
  startWorkspace(dir: string, allow: readonly ApprovalKind[], signal: AbortSignal): Promise<McpWorkspaceConnection> {
31
53
  if (pending) return pending
32
54
  const work = async () => {
33
- signal.throwIfAborted()
55
+ const startup = AbortSignal.any([signal, stopped.signal, AbortSignal.timeout(30_000)])
56
+ startup.throwIfAborted()
34
57
  if (closed) throw new Error('mcp-workspace-session-closed')
35
58
  if (!root) {
36
59
  const existing = findWorkspaceServiceState(dir)
37
60
  root = existing ? Promise.resolve(existing.root) : findWorkspaceRoot(dir).then(found => realpathSync(existsSync(join(found, WORKSPACE_CONFIG)) ? found : dir))
38
61
  }
39
62
  const directory = await root, file = join(serveStateDir(directory), 'server.json')
40
- const deadline = Date.now() + 30_000
63
+ let launchError: Error | undefined
41
64
  for (;;) {
42
- signal.throwIfAborted()
65
+ startup.throwIfAborted()
43
66
  if (closed) throw new Error('mcp-workspace-session-closed')
44
- if (owned?.lease.signal.aborted) await closeOwned()
67
+ // Read the installed command again: a long-lived relay must not restart its cached, older modules.
68
+ const { installed, version } = installation()
45
69
  const state = readServiceState(file)
46
- if (state) return { target: target(state), close }
47
- if (Date.now() >= deadline) throw new Error('mcp-workspace-start-timeout')
48
- const lease = await tryAcquireServiceHostLease(directory)
49
- if (!lease) { await delay(100, undefined, { signal }); continue }
50
- // A previous host may have published while this process was waiting for its lease.
51
- const appeared = readServiceState(file)
52
- if (appeared) { await lease.release(); return { target: target(appeared), close } }
53
- let server: WorkspaceServer | undefined
54
- const startup = AbortSignal.any([signal, AbortSignal.timeout(Math.max(1, deadline - Date.now()))])
55
- try {
56
- signal.throwIfAborted()
57
- server = await serveWorkspace({ dir: directory, bundled, port: 0, listenAddress: '127.0.0.1', allow: [...allow], hostLease: lease, signal: startup })
58
- startup.throwIfAborted()
59
- if (closed) throw new Error('mcp-workspace-session-closed')
60
- const ready = readServiceState(file)
61
- if (!ready || ready.pid !== process.pid || ready.mcp !== server.mcp.url) throw new Error('mcp-workspace-state-unavailable')
62
- owned = { server, lease }
63
- return { target: target(ready), close }
64
- } catch (error) {
65
- if (server) await server.close()
66
- else await lease.release()
67
- if (!signal.aborted && startup.aborted) throw new Error('mcp-workspace-start-timeout')
68
- throw error
70
+ if (state && compareServiceVersion(state, version) >= 0) return { target: target(state), close }
71
+ if (state) { await upgradeWorkspaceService(directory, state, version, process.env, startup); continue }
72
+ if (!installed) throw new ServiceUpgradeError('unavailable')
73
+ if (launchError) throw launchError
74
+ if (!owned && compareServiceVersion({ version: installed.version }, version) === 0) {
75
+ const env: NodeJS.ProcessEnv = { ...process.env, PRESMIUM_SERVICE_PARENT_PIPE: '1' }
76
+ delete env.PRESMIUM_STUDIO_PARENT_PIPE
77
+ const child = spawnInteractiveNode(join(bundled, installed.bin.presmium), ['serve', directory, '--port', '0', ...allow.length ? ['--allow', allow.join(',')] : []], { cwd: directory, env, stdio: ['pipe', 'pipe', 'pipe'] })
78
+ const lines = createInterface({ input: child.stdout! })
79
+ lines.on('line', line => {
80
+ if (line.startsWith('service-upgrade ')) {
81
+ const next = line.slice('service-upgrade '.length)
82
+ try { if (compareServiceVersion({ version: next }, minimumVersion) > 0) minimumVersion = next } catch {}
83
+ }
84
+ })
85
+ child.stderr?.on('data', bytes => process.stderr.write(bytes))
86
+ const current: OwnedHost = { child, exited: new Promise<void>(done => {
87
+ child.once('error', error => { launchError = error; done() })
88
+ child.once('exit', () => { if (owned === current) owned = undefined; lines.close(); done() })
89
+ }) }
90
+ owned = current
69
91
  }
92
+ await delay(100, undefined, { signal: startup })
70
93
  }
71
94
  }
72
- pending = work().finally(() => { pending = undefined })
95
+ pending = work().catch(error => {
96
+ if (error instanceof ServiceUpgradeError) throw new Error(CLI_MESSAGES[systemLocale()].workspaceServiceUpgrade(error.reason, error.version))
97
+ throw error
98
+ }).finally(() => { pending = undefined })
73
99
  return pending
74
100
  },
75
101
  close,
package/src/messages.ts CHANGED
@@ -30,6 +30,7 @@ export interface CliMessages {
30
30
  studioMissing: string
31
31
  mcpMissing: string
32
32
  workspaceServiceBusy(url?: string): string
33
+ workspaceServiceUpgrade(reason: 'busy' | 'newer' | 'unavailable', version?: string): string
33
34
  noProblems: string
34
35
  counts(errors: number, warnings: number, infos: number): string
35
36
  severity: Record<'error' | 'warning' | 'info', string>
@@ -223,6 +224,7 @@ export const CLI_MESSAGES: Record<Locale, CliMessages> = {
223
224
  studioMissing: 'presmium studio: 没有安装 Presmium Studio。它随 Presmium 一起安装,请运行 pnpm add -g @lincyaw/presmium。',
224
225
  mcpMissing: 'presmium mcp: 没有安装 @lincyaw/mcp。它随 Presmium 一起安装,请运行 pnpm add -g @lincyaw/presmium。',
225
226
  workspaceServiceBusy: url => `这个工作区已有作者服务${url ? `:${url}` : '正在启动'}。请使用已运行的服务。`,
227
+ workspaceServiceUpgrade: (reason, version) => reason === 'busy' ? '工作区正在编辑或导出,请等待当前操作结束后重试升级。' : reason === 'newer' ? `工作区服务已运行更新版本 ${version},请升级当前 Presmium。` : '无法自动切换旧版工作区服务,请关闭使用该工作区的旧版 Presmium 后重试。',
226
228
  noProblems: '没有问题',
227
229
  counts: (errors, warnings, infos) => `${errors} 个错误,${warnings} 个警告,${infos} 条信息`,
228
230
  severity: { error: '错误', warning: '警告', info: '信息' },
@@ -457,6 +459,7 @@ Exit Codes: 0 no errors, 1 error findings, 2 usage or internal error.`,
457
459
  studioMissing: 'presmium studio: Presmium Studio is not installed. It comes with Presmium: run pnpm add -g @lincyaw/presmium.',
458
460
  mcpMissing: 'presmium mcp: @lincyaw/mcp is not installed. It comes with Presmium: run pnpm add -g @lincyaw/presmium.',
459
461
  workspaceServiceBusy: url => `This workspace already has an authoring service${url ? `: ${url}` : ' starting'}. Use the existing service.`,
462
+ workspaceServiceUpgrade: (reason, version) => reason === 'busy' ? 'The workspace is being edited or exported. Wait for the current operation to finish, then retry the upgrade.' : reason === 'newer' ? `The workspace service runs the newer version ${version}. Update this Presmium.` : 'The older workspace service could not be replaced automatically. Close the older Presmium using this workspace, then retry.',
460
463
  noProblems: 'no problems',
461
464
  counts: (errors, warnings, infos) => `${errors} errors, ${warnings} warnings, ${infos} infos`,
462
465
  severity: { error: 'error', warning: 'warning', info: 'info' },