@pmate/cli 0.44.8 → 0.44.10
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,24 +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
|
-
const
|
|
4
|
+
const {modelCatalog}=require('./model-catalog.cjs')
|
|
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','scripts.run']
|
|
6
7
|
function createAgentRuntime({ platform = process.platform, home = homedir(), execute, fetcher = fetch, environment = process.env } = {}) {
|
|
7
8
|
let identityEpoch=0
|
|
8
|
-
let identity
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
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) => new Promise((resolve, reject) => {
|
|
11
|
+
execFile(file, args, { cwd, timeout, 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()))
|
|
12
12
|
}))
|
|
13
|
-
const
|
|
14
|
-
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}}
|
|
15
|
-
try{await run('merry-runtime',['--help']);await run('merry-plugin',['--help']);return true}catch{return false}
|
|
16
|
-
}
|
|
17
|
-
const check = async () => {
|
|
18
|
-
const checks = [{ id:'macos', name:'macOS', ready:platform==='darwin', required:true }]
|
|
19
|
-
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}) }
|
|
20
|
-
return { supported:platform==='darwin', checks, installed:await installed() }
|
|
21
|
-
}
|
|
13
|
+
const check = () => checkEnvironment({platform,home,run,fetcher})
|
|
22
14
|
const api = async (route, method='GET', body) => {
|
|
23
15
|
if (!identity) throw new Error('请先登录梅丽号')
|
|
24
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) })
|
|
@@ -26,37 +18,13 @@ function createAgentRuntime({ platform = process.platform, home = homedir(), exe
|
|
|
26
18
|
if(!response.ok||!value.success)throw new Error(value.message||`Issues API 请求失败 (${response.status})`)
|
|
27
19
|
return value.data
|
|
28
20
|
}
|
|
29
|
-
const install = async () => {
|
|
30
|
-
if (installation) return installation
|
|
31
|
-
installation=(async()=>{
|
|
32
|
-
try {
|
|
33
|
-
const environment=await check()
|
|
34
|
-
if(!environment.supported)throw new Error('Runtime 目前仅支持 macOS')
|
|
35
|
-
const missing=environment.checks.filter(c=>!c.ready).map(c=>c.name)
|
|
36
|
-
if(missing.length)throw new Error(`请先安装 ${missing.join('、')},然后重新检测`)
|
|
37
|
-
if(environment.installed&&!existsSync(root)){progress={phase:'ready',message:'已检测到现有 Runtime'};return progress}
|
|
38
|
-
if(existsSync(root)&&!existsSync(path.join(root,'packages/merry-runtime/src/runtime-cli.ts')))throw new Error('安装目录不是当前 Runtime 源码,请先保留本地改动并更新仓库后重试;不会覆盖现有文件')
|
|
39
|
-
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])}
|
|
40
|
-
progress={phase:'installing',message:'正在安装依赖'}
|
|
41
|
-
await run('pnpm',['install','--frozen-lockfile','--ignore-scripts'],root)
|
|
42
|
-
progress={phase:'verifying',message:'正在验证 Runtime'}
|
|
43
|
-
await run('bun',['packages/merry-runtime/src/runtime-cli.ts','--help'],root)
|
|
44
|
-
await run('bun',['packages/merry-runtime/src/plugin.ts','--help'],root)
|
|
45
|
-
await run('bun',['packages/merry-runtime/src/setup.ts'],root)
|
|
46
|
-
await run('bun',['packages/merry-runtime/src/plugin.ts','install'],root)
|
|
47
|
-
progress={phase:'ready',message:'Runtime 已安装'}
|
|
48
|
-
return progress
|
|
49
|
-
}catch(error){progress={phase:'error',error:error.message};throw error}finally{installation=undefined}
|
|
50
|
-
})()
|
|
51
|
-
return installation
|
|
52
|
-
}
|
|
53
21
|
const invoke = async (method,input) => {
|
|
54
22
|
if(!methods.includes(method))throw new Error('ELECTRON_METHOD_UNAVAILABLE')
|
|
55
23
|
if(method==='capabilities')return methods
|
|
56
24
|
if(method==='runtime.checkEnvironment')return check()
|
|
57
|
-
if(method==='runtime.status')return
|
|
58
|
-
if(method==='runtime.
|
|
59
|
-
if(method==='scripts.run')
|
|
25
|
+
if(method==='runtime.status')return check()
|
|
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(':')}})
|
|
27
|
+
if(method==='scripts.run')throw new Error('未知脚本操作')
|
|
60
28
|
if(method==='workspaces.list')return api('/v2/workspaces')
|
|
61
29
|
const {scope,id,config,expectedRevision}=input||{}
|
|
62
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('无效工作区')
|
|
@@ -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}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
const {spawn}=require('node:child_process')
|
|
2
|
+
const {createInterface}=require('node:readline')
|
|
3
|
+
const {tmpdir}=require('node:os')
|
|
4
|
+
const EFFORTS=['none','minimal','low','medium','high','xhigh','max','ultra']
|
|
5
|
+
function normalize(engine,rows){
|
|
6
|
+
if(!Array.isArray(rows))throw Error('invalid_catalog')
|
|
7
|
+
const seen=new Set(),models=[]
|
|
8
|
+
for(const row of rows){
|
|
9
|
+
const id=engine==='codex'?row.model:(row.resolvedModel||row.value)
|
|
10
|
+
if(typeof id!=='string'||!/^[-a-zA-Z0-9_.:/[\]]{1,160}$/.test(id)||seen.has(id))continue
|
|
11
|
+
seen.add(id)
|
|
12
|
+
const efforts=(engine==='codex'?row.supportedReasoningEfforts?.map(x=>x.reasoningEffort):row.supportedEffortLevels)??[]
|
|
13
|
+
if(!Array.isArray(efforts))continue
|
|
14
|
+
models.push({id,label:typeof row.displayName==='string'?row.displayName.slice(0,120):id,efforts:[...new Set(efforts.filter(e=>EFFORTS.includes(e)))],...(engine==='codex'&&efforts.includes(row.defaultReasoningEffort)?{defaultEffort:row.defaultReasoningEffort}:{})})
|
|
15
|
+
}
|
|
16
|
+
if(!models.length)throw Error('empty_catalog')
|
|
17
|
+
return models
|
|
18
|
+
}
|
|
19
|
+
function queryModels(engine,{environment=process.env,spawnProcess=spawn,timeoutMs=8000}={}){
|
|
20
|
+
return new Promise(resolve=>{
|
|
21
|
+
let child,reader,timer,settled=false,bytes=0,models=[],pages=0
|
|
22
|
+
const finish=(result)=>{if(settled)return;settled=true;clearTimeout(timer);reader?.close();child?.stdin?.end();child?.kill();resolve(result)}
|
|
23
|
+
const fail=()=>finish({source:'fallback',models:[],reason:'catalog_unavailable'})
|
|
24
|
+
try{
|
|
25
|
+
const env={...environment};delete env.CLAUDECODE
|
|
26
|
+
const args=engine==='codex'?['app-server','--stdio']:['--print','--input-format','stream-json','--output-format','stream-json','--verbose','--no-session-persistence','--safe-mode','--tools','','--strict-mcp-config']
|
|
27
|
+
child=spawnProcess(engine==='codex'?'codex':'claude',args,{cwd:tmpdir(),env,stdio:['pipe','pipe','pipe']})
|
|
28
|
+
const send=v=>child.stdin.write(JSON.stringify(v)+'\n')
|
|
29
|
+
timer=setTimeout(fail,timeoutMs)
|
|
30
|
+
child.on('error',fail);child.on('exit',()=>{if(!settled)fail()});child.stdin.on('error',fail)
|
|
31
|
+
child.stderr.on('data',()=>{})
|
|
32
|
+
reader=createInterface({input:child.stdout})
|
|
33
|
+
child.stdout.on('data',b=>{bytes+=b.length;if(bytes>1024*1024)fail()})
|
|
34
|
+
reader.on('line',line=>{if(settled)return;try{
|
|
35
|
+
const v=JSON.parse(line)
|
|
36
|
+
if(engine==='codex'){
|
|
37
|
+
if(v.id===1){if(v.error)return fail();send({method:'initialized',params:{}});send({id:2,method:'model/list',params:{limit:100}})}
|
|
38
|
+
if(v.id===2){if(v.error)return fail();models.push(...normalize(engine,v.result?.data));if(v.result.nextCursor){if(++pages>10)return fail();send({id:2,method:'model/list',params:{limit:100,cursor:v.result.nextCursor}})}else finish({source:'live',models,checkedAt:new Date().toISOString()})}
|
|
39
|
+
}else if(v.type==='control_response'&&v.response?.request_id==='models'){
|
|
40
|
+
if(v.response.subtype!=='success')return fail();finish({source:'live',models:normalize(engine,v.response.response?.models),checkedAt:new Date().toISOString()})
|
|
41
|
+
}
|
|
42
|
+
}catch{fail()}})
|
|
43
|
+
send(engine==='codex'?{id:1,method:'initialize',params:{clientInfo:{name:'merry_model_picker',version:'1'}}}:{type:'control_request',request_id:'models',request:{subtype:'initialize'}})
|
|
44
|
+
}catch{fail()}
|
|
45
|
+
})
|
|
46
|
+
}
|
|
47
|
+
async function modelCatalog(options){const [codex,claude]=await Promise.all([queryModels('codex',options),queryModels('claude',options)]);return{codex,claude}}
|
|
48
|
+
module.exports={modelCatalog,queryModels,normalize}
|