@pmate/cli 0.44.9 → 0.44.11

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.
@@ -1,25 +1,16 @@
1
1
  const { execFile } = require('node:child_process')
2
- const { existsSync, mkdirSync } = require('node:fs')
3
2
  const { homedir } = require('node:os')
4
3
  const path = require('node:path')
5
4
  const {modelCatalog}=require('./model-catalog.cjs')
6
- const methods = ['capabilities','workspaces.list','agents.list','agents.create','agents.update','plugins.list','plugins.configure','runtime.checkEnvironment','runtime.install','runtime.status','scripts.run']
5
+ const {checkEnvironment}=require('./environment-check.cjs')
6
+ const methods = ['capabilities','workspaces.list','agents.list','agents.create','agents.update','plugins.list','plugins.configure','runtime.checkEnvironment','runtime.status','runtime.inspect','scripts.run']
7
7
  function createAgentRuntime({ platform = process.platform, home = homedir(), execute, fetcher = fetch, environment = process.env } = {}) {
8
8
  let identityEpoch=0
9
- let identity, installation, progress = { phase: 'idle' }
10
- const root = path.join(home, '.pmate', 'merry-runtime')
11
- const run = execute || ((file, args, cwd) => new Promise((resolve, reject) => {
12
- execFile(file, args, { cwd, timeout: 600000, maxBuffer: 1024 * 1024, env: { ...environment, PATH: [path.join(home,'.local/bin'),path.join(home,'.bun/bin'),environment.PNPM_HOME,path.join(home,'Library/pnpm'),path.join(home,'.local/share/pnpm'),'/opt/homebrew/bin','/usr/local/bin',environment.PATH].filter(Boolean).join(':'), GIT_TERMINAL_PROMPT: '0' } }, (error, stdout) => error ? reject(new Error(`${path.basename(file)} 执行失败,请检查本地安装和仓库访问权限`)) : resolve(stdout.trim()))
9
+ let identity
10
+ const run = execute || ((file, args, cwd, timeout = 600000, credentials = {}) => new Promise((resolve, reject) => {
11
+ execFile(file, args, { cwd, timeout, maxBuffer: 4 * 1024 * 1024, env: { ...environment, ...credentials, PATH: [path.join(home,'.local/bin'),path.join(home,'.bun/bin'),environment.PNPM_HOME,path.join(home,'Library/pnpm'),path.join(home,'.local/share/pnpm'),'/opt/homebrew/bin','/usr/local/bin',environment.PATH].filter(Boolean).join(':'), GIT_TERMINAL_PROMPT: '0' } }, (error, stdout) => error ? reject(new Error(`${path.basename(file)} 执行失败,请检查本地安装和仓库访问权限`)) : resolve(stdout.trim()))
13
12
  }))
14
- const installed = async () => {
15
- if(existsSync(path.join(root,'packages/merry-runtime/src/runtime-cli.ts'))){try{await run('bun',['packages/merry-runtime/src/runtime-cli.ts','--help'],root);await run('bun',['packages/merry-runtime/src/plugin.ts','--help'],root);return true}catch{return false}}
16
- try{await run('merry-runtime',['--help']);await run('merry-plugin',['--help']);return true}catch{return false}
17
- }
18
- const check = async () => {
19
- const checks = [{ id:'macos', name:'macOS', ready:platform==='darwin', required:true }]
20
- for (const name of ['git','node','bun','pnpm']) { let version; try { version=await run(name,['--version']) } catch {} checks.push({id:name,name,ready:!!version&&(name!=='node'||Number(version.replace(/^v/,'').split('.')[0])>=24),version,required:true}) }
21
- return { supported:platform==='darwin', checks, installed:await installed() }
22
- }
13
+ const check = () => checkEnvironment({platform,home,run,fetcher})
23
14
  const api = async (route, method='GET', body) => {
24
15
  if (!identity) throw new Error('请先登录梅丽号')
25
16
  const response = await fetcher(`https://issue-api.pmate.chat${route}`, { method, headers: { authorization:`Bearer ${identity.token}`, 'x-pmate-app':identity.appId, 'content-type':'application/json' }, ...(body===undefined?{}:{body:JSON.stringify(body)}), signal:AbortSignal.timeout(30000) })
@@ -27,42 +18,25 @@ function createAgentRuntime({ platform = process.platform, home = homedir(), exe
27
18
  if(!response.ok||!value.success)throw new Error(value.message||`Issues API 请求失败 (${response.status})`)
28
19
  return value.data
29
20
  }
30
- const install = async () => {
31
- if (installation) return installation
32
- installation=(async()=>{
33
- try {
34
- const environment=await check()
35
- if(!environment.supported)throw new Error('Runtime 目前仅支持 macOS')
36
- const missing=environment.checks.filter(c=>!c.ready).map(c=>c.name)
37
- if(missing.length)throw new Error(`请先安装 ${missing.join('、')},然后重新检测`)
38
- if(environment.installed&&!existsSync(root)){progress={phase:'ready',message:'已检测到现有 Runtime'};return progress}
39
- if(existsSync(root)&&!existsSync(path.join(root,'packages/merry-runtime/src/runtime-cli.ts')))throw new Error('安装目录不是当前 Runtime 源码,请先保留本地改动并更新仓库后重试;不会覆盖现有文件')
40
- if(!existsSync(root)){mkdirSync(path.dirname(root),{recursive:true,mode:0o700});progress={phase:'downloading',message:'正在获取 Runtime 源码'};await run('git',['clone','https://github.com/parrot-mate/pmate-agents.git',root])}
41
- progress={phase:'installing',message:'正在安装依赖'}
42
- await run('pnpm',['install','--frozen-lockfile','--ignore-scripts'],root)
43
- progress={phase:'verifying',message:'正在验证 Runtime'}
44
- await run('bun',['packages/merry-runtime/src/runtime-cli.ts','--help'],root)
45
- await run('bun',['packages/merry-runtime/src/plugin.ts','--help'],root)
46
- await run('bun',['packages/merry-runtime/src/setup.ts'],root)
47
- await run('bun',['packages/merry-runtime/src/plugin.ts','install'],root)
48
- progress={phase:'ready',message:'Runtime 已安装'}
49
- return progress
50
- }catch(error){progress={phase:'error',error:error.message};throw error}finally{installation=undefined}
51
- })()
52
- return installation
53
- }
54
21
  const invoke = async (method,input) => {
55
22
  if(!methods.includes(method))throw new Error('ELECTRON_METHOD_UNAVAILABLE')
56
23
  if(method==='capabilities')return methods
57
24
  if(method==='runtime.checkEnvironment')return check()
58
- if(method==='runtime.status')return {...progress,installed:await installed()}
59
- if(method==='runtime.install')return install()
25
+ if(method==='runtime.status')return check()
60
26
  if(method==='scripts.run'&&input?.id==='runtime.models'&&input.args&&Object.keys(input.args).length===0)return modelCatalog({environment:{...environment,PATH:[path.join(home,'.local/bin'),path.join(home,'.bun/bin'),'/opt/homebrew/bin','/usr/local/bin',environment.PATH].filter(Boolean).join(':')}})
61
- if(method==='scripts.run') {if(input?.id!=='runtime.repair'||!input.args||Object.keys(input.args).length)throw new Error('未知安装操作');return install()}
27
+ if(method==='scripts.run')throw new Error('未知脚本操作')
62
28
  if(method==='workspaces.list')return api('/v2/workspaces')
63
29
  const {scope,id,config,expectedRevision}=input||{}
64
30
  if(!scope||!['namespace','topic'].every(k=>typeof scope[k]==='string'&&/^[a-z0-9][a-z0-9_-]{0,127}$/.test(scope[k])))throw new Error('无效工作区')
65
31
  const base=`/v2/topics/${encodeURIComponent(scope.namespace)}/${encodeURIComponent(scope.topic)}`
32
+ if(method==='runtime.inspect'){
33
+ if(!identity)throw new Error('请先登录梅丽号')
34
+ if(!['runs','run','run-logs'].includes(input.kind)||Object.keys(input).some(k=>!['scope','kind','agentId','runId','status'].includes(k)))throw new Error('无效的 Run 查询')
35
+ const epoch=identityEpoch
36
+ const output=await run('merry-runtime',['inspect','--request',JSON.stringify(input)],undefined,600000,{PCS_AGENT_API_TOKEN:identity.token,PCS_ISSUES_API_URL:'https://issue-api.pmate.chat',PCS_AGENT_ID:undefined,PCS_AGENT_RUN_ID:undefined,VEGA_RUN_TOKEN:undefined,VEGA_INPUT_ID:undefined})
37
+ if(epoch!==identityEpoch||!identity)throw new Error('登录身份已改变,请重新打开页面')
38
+ return JSON.parse(output)
39
+ }
66
40
  if(method==='agents.list')return api(base+'/vega-agents')
67
41
  if(method==='plugins.list')return api(base+'/runtime-plugins')
68
42
  if(typeof id!=='string'||!(method==='plugins.configure'?/^(?:[a-z][a-z0-9-]*:)?[a-z][a-z0-9-]*$/:/^0x[a-f0-9]{64}$/).test(id)||!config||typeof config!=='object'||Array.isArray(config))throw new Error('无效配置')
@@ -0,0 +1,61 @@
1
+ const {existsSync,readFileSync,realpathSync}=require('node:fs')
2
+ const path=require('node:path')
3
+ const SHA=/^[a-f0-9]{40}$/
4
+ const SEMVER=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/
5
+ const versionAtLeast=(local,latest)=>{const a=local.split('.').map(Number),b=latest.split('.').map(Number);for(let i=0;i<3;i++)if(a[i]!==b[i])return a[i]>b[i];return true}
6
+ const row=(id,value)=>({id,name:id,required:true,ready:false,...value})
7
+
8
+ /** Read-only dependency gate. Each recheck observes remote versions again; never installs. */
9
+ async function checkEnvironment({platform,home,run,fetcher}){
10
+ const command=(file,args,cwd)=>run(file,args,cwd,10000)
11
+ const tools=await Promise.all(['git','node','bun','pnpm'].map(async id=>{
12
+ try{const version=await command(id,['--version']);const ready=id!=='node'||/^v?(\d+)\./.test(version)&&Number(version.replace(/^v/,'').split('.')[0])>=24;return row(id,{version,ready,status:ready?'ready':'outdated',...(ready?{}:{detail:'需要 Node.js 24 或更新版本'})})}
13
+ catch{return row(id,{status:'missing'})}
14
+ }))
15
+ async function sourceCheck(id,packageName,repository,load){
16
+ let info
17
+ try{info=await load()}
18
+ catch(error){return row(id,{...(error.installedVersion?{version:error.installedVersion,status:'broken',detail:'本地安装缺少可用的版本检查信息,请按 Skill 更新并重新构建'}:{status:'missing',detail:'未找到可用的本地安装;请按安装 Skill 安装或更新'})})}
19
+ if(!info||typeof info!=='object'||info.package!==packageName||!SEMVER.test(info.version)||!SHA.test(info.revision)||typeof info.root!=='string'||!path.isAbsolute(info.root))return row(id,{status:'broken',detail:'安装信息不完整,请按 Skill 更新并重新构建'})
20
+ const local={version:info.version,revision:info.revision}
21
+ try{
22
+ const root=await command('git',['rev-parse','--show-toplevel'],info.root)
23
+ const remote=await command('git',['remote','get-url','origin'],root)
24
+ // Do not compare a copied build or an unrelated repository to an apparent version.
25
+ if(!new RegExp(`(?:/|:)parrot-mate/${repository}(?:\\.git)?$`).test(remote))return row(id,{...local,status:'broken',detail:'安装来源不是预期的源码仓库'})
26
+ if(id==='merry-runtime'&&realpathSync(root)!==realpathSync(path.join(home,'.pmate/merry-runtime')))return row(id,{...local,status:'broken',detail:'Runtime 必须安装到 ~/.pmate/merry-runtime'})
27
+ const latest=(await command('git',['ls-remote','origin','refs/heads/main'],root)).split(/\s+/)[0]
28
+ if(!SHA.test(latest))throw Error('Invalid remote revision')
29
+ const target={...local,latestVersion:`main@${latest.slice(0,12)}`,latestRevision:latest}
30
+ if(await command('git',['status','--porcelain','--untracked-files=no'],root))return row(id,{...target,status:'modified',detail:'本地源码有未提交改动,请保留并检查后再更新'})
31
+ if(info.revision!==latest)return row(id,{...target,status:'outdated',detail:'本地执行版本与远端 main 不一致,请按 Skill 更新;CLI 更新源码后还需重新构建'})
32
+ return row(id,{...target,ready:true,status:'ready'})
33
+ }catch{return row(id,{...local,status:'unknown',detail:'无法确认远端 main;请检查 GitHub 访问权限和网络后重新检查'})}
34
+ }
35
+ const runtime=sourceCheck('merry-runtime','@pmate/merry-runtime','pmate-agents',async()=>{
36
+ const root=path.join(home,'.pmate/merry-runtime')
37
+ if(!existsSync(path.join(root,'packages/merry-runtime/package.json')))throw Error('missing')
38
+ const pkg=JSON.parse(readFileSync(path.join(root,'packages/merry-runtime/package.json'),'utf8'))
39
+ try{const info=JSON.parse(await command('bun',['packages/merry-runtime/src/runtime-cli.ts','--build-info'],root));await command('bun',['packages/merry-runtime/src/plugin.ts','--help'],root);return info}
40
+ catch{throw Object.assign(Error('Runtime verification failed'),{installedVersion:pkg.version})}
41
+ })
42
+ const merry=sourceCheck('merry-cli','@pmate/merry-cli','pmate-merry',async()=>{const version=await command('merry',['--version']);try{return JSON.parse(await command('merry',['--build-info']))}catch{throw Object.assign(Error('CLI verification failed'),{installedVersion:version})}})
43
+ const pmate=(async()=>{
44
+ let version,latestVersion
45
+ try{const output=await command('pmate',['--version']);version=output.trim();if(!SEMVER.test(version))return row('pmate-cli',{status:'broken',detail:'无法识别 pmate --version 的输出'})}
46
+ catch{return row('pmate-cli',{status:'missing'})}
47
+ try{
48
+ const response=await fetcher('https://registry.npmjs.org/@pmate%2fcli/latest',{signal:AbortSignal.timeout(10000),headers:{'cache-control':'no-cache'}})
49
+ if(!response.ok)throw Error('registry unavailable')
50
+ const pkg=await response.json();latestVersion=pkg.version
51
+ if(pkg.name!=='@pmate/cli'||!SEMVER.test(latestVersion))throw Error('invalid registry version')
52
+ const ready=versionAtLeast(version,latestVersion)
53
+ return row('pmate-cli',{version,latestVersion,ready,status:ready?'ready':'outdated'})
54
+ }catch{return row('pmate-cli',{version,status:'unknown',detail:'无法确认 npm 最新版本;请检查网络后重新检查'})}
55
+ })()
56
+ const libraries=await Promise.all([runtime,merry,pmate])
57
+ const checks=[row('macos',{name:'macOS',ready:platform==='darwin',status:platform==='darwin'?'ready':'unsupported'}),...tools,...libraries]
58
+ const ready=checks.every(c=>c.ready)
59
+ return {schemaVersion:2,supported:platform==='darwin',installed:ready,ready,checks}
60
+ }
61
+ module.exports={checkEnvironment}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pmate/cli",
3
- "version": "0.44.9",
3
+ "version": "0.44.11",
4
4
  "description": "CLI utilities for the pMate project",
5
5
  "license": "MIT",
6
6
  "bin": {