@pmate/cli 0.45.3 → 0.46.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.
@@ -3,14 +3,16 @@ const { homedir } = require('node:os')
3
3
  const path = require('node:path')
4
4
  const {modelCatalog}=require('./model-catalog.cjs')
5
5
  const {createLocalExecutor}=require('./local-exec.cjs')
6
+ const {createShellPathResolver}=require('./shell-path.cjs')
6
7
  const methods = ['capabilities','workspaces.list','agents.list','agents.create','agents.update','plugins.list','plugins.configure','local.info','local.exec','runtime.inspect','scripts.run']
7
8
  function createAgentRuntime({ platform = process.platform, home = homedir(), execute, fetcher = fetch, environment = process.env } = {}) {
9
+ const resolvePath=createShellPathResolver({home,environment,platform})
8
10
  let identityEpoch=0
9
11
  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()))
12
- }))
13
- const localExec=createLocalExecutor({home,environment})
12
+ const run = execute || (async(file, args, cwd, timeout = 600000, credentials = {}) => {const resolved=await resolvePath();return new Promise((resolve, reject) => {
13
+ execFile(file, args, { cwd, timeout, maxBuffer: 4 * 1024 * 1024, env: { ...environment, ...credentials, PATH: resolved.path, GIT_TERMINAL_PROMPT: '0' } }, (error, stdout) => error ? reject(new Error(`${path.basename(file)} 执行失败,请检查本地安装和仓库访问权限`)) : resolve(stdout.trim()))
14
+ })})
15
+ const localExec=createLocalExecutor({home,environment,resolvePath})
14
16
  const api = async (route, method='GET', body) => {
15
17
  if (!identity) throw new Error('请先登录梅丽号')
16
18
  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) })
@@ -28,7 +30,7 @@ function createAgentRuntime({ platform = process.platform, home = homedir(), exe
28
30
  if(epoch!==identityEpoch||!identity)throw new Error('登录身份已改变,请重新执行')
29
31
  return result
30
32
  }
31
- 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(':')}})
33
+ if(method==='scripts.run'&&input?.id==='runtime.models'&&input.args&&Object.keys(input.args).length===0)return modelCatalog({environment:{...environment,PATH:(await resolvePath()).path}})
32
34
  if(method==='scripts.run')throw new Error('未知脚本操作')
33
35
  if(method==='workspaces.list')return api('/v2/workspaces')
34
36
  const {scope,id,config,expectedRevision}=input||{}
@@ -1,15 +1,16 @@
1
1
  const {execFile}=require('node:child_process')
2
2
  const path=require('node:path')
3
+ const {createShellPathResolver}=require('./shell-path.cjs')
3
4
  /** Stable local process capability. Command selection and business rules belong to Web/bridge. */
4
- function createLocalExecutor({home,environment,execute=execFile}){
5
- const 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(':')}
5
+ function createLocalExecutor({home,environment,execute=execFile,resolvePath=createShellPathResolver({home,environment})}){
6
+
6
7
  return input=>{
7
8
  if(!input||typeof input.command!=='string'||!input.command||input.command.includes('\0')||!Array.isArray(input.args)||input.args.some(v=>typeof v!=='string'||v.includes('\0'))||input.args.length>256||input.args.some(v=>v.length>131072))throw Error('Invalid local command')
8
9
  if(input.cwd!==undefined&&(typeof input.cwd!=='string'||!path.isAbsolute(input.cwd)||input.cwd.includes('\0')))throw Error('Invalid working directory')
9
10
  if(input.env!==undefined&&(!input.env||typeof input.env!=='object'||Array.isArray(input.env)||Object.entries(input.env).some(([k,v])=>!k||k.includes('=')||k.includes('\0')||typeof v!=='string'||v.includes('\0'))))throw Error('Invalid process environment')
10
11
  const timeout=input.timeoutMs??10000
11
12
  if(!Number.isSafeInteger(timeout)||timeout<100||timeout>120000)throw Error('Invalid command timeout')
12
- return new Promise(resolve=>execute(input.command,input.args,{cwd:input.cwd,env:{...env,...input.env},shell:false,timeout,maxBuffer:1024*1024,windowsHide:true},(error,stdout,stderr)=>resolve({stdout:String(stdout??''),stderr:String(stderr??''),exitCode:error?(typeof error.code==='number'?error.code:null):0,error:error?(error.code==='ENOENT'?'NOT_FOUND':error.code==='ERR_CHILD_PROCESS_STDIO_MAXBUFFER'?'OUTPUT_LIMIT':error.killed?'TIMEOUT':'PROCESS_FAILED'):undefined})))
13
+ return resolvePath().then(({path:resolvedPath,warning})=>new Promise(resolve=>execute(input.command,input.args,{cwd:input.cwd,env:{...environment,PATH:resolvedPath,...input.env},shell:false,timeout,maxBuffer:1024*1024,windowsHide:true},(error,stdout,stderr)=>resolve({stdout:String(stdout??''),stderr:(error&&warning?warning+'\n':'')+String(stderr??''),exitCode:error?(typeof error.code==='number'?error.code:null):0,error:error?(error.code==='ENOENT'?'NOT_FOUND':error.code==='ERR_CHILD_PROCESS_STDIO_MAXBUFFER'?'OUTPUT_LIMIT':error.killed?'TIMEOUT':'PROCESS_FAILED'):undefined}))))
13
14
  }
14
15
  }
15
16
  module.exports={createLocalExecutor}
@@ -0,0 +1,37 @@
1
+ const {execFile}=require('node:child_process')
2
+ const {userInfo}=require('node:os')
3
+ const path=require('node:path')
4
+ const {randomBytes}=require('node:crypto')
5
+ function fallbackPath(home,environment,platform){
6
+ if(platform==='win32')return environment.PATH||''
7
+ return [...new Set([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','/usr/bin','/bin'].filter(Boolean)].filter(Boolean).flatMap(value=>value.split(':')).filter(value=>path.isAbsolute(value)))].join(':')
8
+ }
9
+ /** Read only PATH from the user's shell. Never import shell credentials or execute caller arguments through it. */
10
+ function createShellPathResolver({home,environment,platform=process.platform,shell,execute=execFile,timeoutMs=5000}={}){
11
+ let cached
12
+ return()=>cached??(cached=(async()=>{
13
+ const fallback=fallbackPath(home,environment,platform)
14
+ if(platform==='win32')return{path:fallback}
15
+ let selected=shell
16
+ if(!selected)try{selected=userInfo().shell}catch{}
17
+ selected=selected||environment.SHELL||(platform==='darwin'?'/bin/zsh':'/bin/sh')
18
+ if(!path.isAbsolute(selected)||selected.includes('\0'))return{path:fallback,warning:'无法读取用户 shell,已使用桌面默认 PATH'}
19
+ const marker='MERRY_PATH_'+randomBytes(16).toString('hex'),begin=marker+'_BEGIN',end=marker+'_END'
20
+ const command=`printf '\\n${begin}\\n'; /usr/bin/printenv PATH; printf '\\n${end}\\n'`
21
+ return new Promise(resolve=>{
22
+ let done=false,timer,child
23
+ const finish=value=>{if(done)return;done=true;clearTimeout(timer);resolve(value)}
24
+ timer=setTimeout(()=>{child?.kill('SIGKILL');finish({path:fallback,warning:'读取用户 shell PATH 超时,已使用桌面默认 PATH'})},timeoutMs)
25
+ try{child=execute(selected,['-ilc',command],{env:{...environment,HOME:home},cwd:home,shell:false,timeout:timeoutMs,killSignal:'SIGKILL',maxBuffer:1024*1024,windowsHide:true},(error,stdout)=>{
26
+ if(error)return finish({path:fallback,warning:'读取用户 shell PATH 失败,已使用桌面默认 PATH'})
27
+ const output=String(stdout??''),start=output.indexOf('\n'+begin+'\n'),stop=output.indexOf('\n'+end+'\n',start+begin.length+2)
28
+ const value=start<0||stop<0?'':output.slice(start+begin.length+2,stop).trim()
29
+ if(!value||/[\r\n\0]/.test(value))return finish({path:fallback,warning:'用户 shell 未返回有效 PATH,已使用桌面默认 PATH'})
30
+ const entries=value.split(':').filter(entry=>path.isAbsolute(entry))
31
+ if(!entries.length)return finish({path:fallback,warning:'用户 shell PATH 无效,已使用桌面默认 PATH'})
32
+ finish({path:[...new Set([...entries,...fallback.split(':')])].join(':')})
33
+ })}catch{finish({path:fallback,warning:'无法启动用户 shell,已使用桌面默认 PATH'})}
34
+ })
35
+ })())
36
+ }
37
+ module.exports={createShellPathResolver}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pmate/cli",
3
- "version": "0.45.3",
3
+ "version": "0.46.0",
4
4
  "description": "CLI utilities for the pMate project",
5
5
  "license": "MIT",
6
6
  "bin": {