@pmate/cli 0.44.1 → 0.44.2

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.
@@ -0,0 +1,73 @@
1
+ const { execFile } = require('node:child_process')
2
+ const { existsSync, mkdirSync } = require('node:fs')
3
+ const { homedir } = require('node:os')
4
+ const path = require('node:path')
5
+ const methods = ['capabilities','workspaces.list','agents.list','agents.create','agents.update','plugins.list','plugins.configure','runtime.checkEnvironment','runtime.install','runtime.status','scripts.run']
6
+ function createAgentRuntime({ platform = process.platform, home = homedir(), execute, fetcher = fetch } = {}) {
7
+ let identity, installation, progress = { phase: 'idle' }
8
+ const root = path.join(home, '.pmate', 'merry-runtime')
9
+ const run = execute || ((file, args, cwd) => new Promise((resolve, reject) => {
10
+ execFile(file, args, { cwd, timeout: 600000, maxBuffer: 1024 * 1024, env: { ...process.env, PATH: [path.join(home,'.bun/bin'),'/opt/homebrew/bin','/usr/local/bin',process.env.PATH].filter(Boolean).join(':'), GIT_TERMINAL_PROMPT: '0' } }, (error, stdout) => error ? reject(new Error(`${path.basename(file)} 执行失败,请检查本地安装和仓库访问权限`)) : resolve(stdout.trim()))
11
+ }))
12
+ const installed = async () => {
13
+ if(existsSync(path.join(root,'packages/pmate-agent-tools/src/cli.ts')))return true
14
+ try{await run('pmate-agent-tools',['plugin','--help']);return true}catch{return false}
15
+ }
16
+ const check = async () => {
17
+ const checks = [{ id:'macos', name:'macOS', ready:platform==='darwin', required:true }]
18
+ 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}) }
19
+ return { supported:platform==='darwin', checks, installed:await installed() }
20
+ }
21
+ const api = async (route, method='GET', body) => {
22
+ if (!identity) throw new Error('请先登录梅丽号')
23
+ 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) })
24
+ const value=await response.json()
25
+ if(!response.ok||!value.success)throw new Error(value.message||`Issues API 请求失败 (${response.status})`)
26
+ return value.data
27
+ }
28
+ const install = async () => {
29
+ if (installation) return installation
30
+ installation=(async()=>{
31
+ try {
32
+ const environment=await check()
33
+ if(!environment.supported)throw new Error('Runtime 目前仅支持 macOS')
34
+ const missing=environment.checks.filter(c=>!c.ready).map(c=>c.name)
35
+ if(missing.length)throw new Error(`请先安装 ${missing.join('、')},然后重新检测`)
36
+ if(environment.installed&&!existsSync(root)){progress={phase:'ready',message:'已检测到现有 Runtime'};return progress}
37
+ if(existsSync(root)&&!environment.installed)throw new Error('安装目录已存在但不完整,请检查后重试;不会覆盖现有文件')
38
+ if(!environment.installed){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])}
39
+ progress={phase:'installing',message:'正在安装依赖'}
40
+ await run('pnpm',['install','--frozen-lockfile','--ignore-scripts'],root)
41
+ progress={phase:'verifying',message:'正在验证 Runtime'}
42
+ await run('bun',['packages/pmate-agent-tools/src/cli.ts','plugin','--help'],root)
43
+ progress={phase:'ready',message:'Runtime 已安装'}
44
+ return progress
45
+ }catch(error){progress={phase:'error',error:error.message};throw error}finally{installation=undefined}
46
+ })()
47
+ return installation
48
+ }
49
+ const invoke = async (method,input) => {
50
+ if(!methods.includes(method))throw new Error('ELECTRON_METHOD_UNAVAILABLE')
51
+ if(method==='capabilities')return methods
52
+ if(method==='runtime.checkEnvironment')return check()
53
+ if(method==='runtime.status')return {...progress,installed:await installed()}
54
+ if(method==='runtime.install')return install()
55
+ if(method==='scripts.run') {if(input?.id!=='runtime.repair'||!input.args||Object.keys(input.args).length)throw new Error('未知安装操作');return install()}
56
+ if(method==='workspaces.list')return api('/v2/workspaces')
57
+ const {scope,id,config,expectedRevision}=input||{}
58
+ if(!scope||!['namespace','topic'].every(k=>typeof scope[k]==='string'&&/^[a-z0-9][a-z0-9_-]{0,127}$/.test(scope[k])))throw new Error('无效工作区')
59
+ const base=`/v2/topics/${encodeURIComponent(scope.namespace)}/${encodeURIComponent(scope.topic)}`
60
+ if(method==='agents.list')return api(base+'/vega-agents')
61
+ if(method==='plugins.list')return api(base+'/runtime-plugins')
62
+ if(typeof id!=='string'||!/^(?:[a-z][a-z0-9-]*:)?[a-z][a-z0-9-]*$/.test(id)||!config||typeof config!=='object'||Array.isArray(config))throw new Error('无效配置')
63
+ if(Object.hasOwn(config,'expectedRevision'))throw new Error('revision 必须单独指定')
64
+ if(method!=='agents.create'&&(!Number.isSafeInteger(expectedRevision)||expectedRevision<1))throw new Error('更新需要 revision')
65
+ if(method==='agents.create'&&expectedRevision!==undefined)throw new Error('创建不能指定 revision')
66
+ return api(base+(method==='plugins.configure'?'/runtime-plugins/':'/vega-agents/')+encodeURIComponent(id),'PUT',{...config,...(expectedRevision===undefined?{}:{expectedRevision})})
67
+ }
68
+ return { invoke, setIdentity(value) { identity=value ? {appId:value.appId,token:value.token} : undefined } }
69
+ }
70
+ function installAgentRuntime({ ipcMain, trusted, runtime }) {
71
+ ipcMain.handle('pmate:electron:invoke',(event,method,input)=>{if(!trusted(event))throw new Error('Untrusted Electron sender');return runtime.invoke(method,input)})
72
+ }
73
+ module.exports={createAgentRuntime,installAgentRuntime}
@@ -10,6 +10,8 @@ const { createDesktopCalls, supportsDesktopCalls } = require('./calls.cjs')
10
10
  const { installNavigationRestrictions } = require('./navigation.cjs')
11
11
  const { installDesktopApps } = require('./apps.cjs')
12
12
  const { createDesktopTray } = require('./tray.cjs')
13
+ const { createAgentRuntime, installAgentRuntime } = require('./agent-runtime.cjs')
14
+ const agentRuntime = createAgentRuntime()
13
15
  const config = require('./desktop-config.json')
14
16
  app.setName(config.productName)
15
17
  if (process.platform === 'win32') app.setAppUserModelId(config.bundleId)
@@ -91,12 +93,15 @@ else {
91
93
  if (!desktopNotifications.trusted(event) || !desktopCalls) throw new Error('Untrusted call sender')
92
94
  desktopCalls.setPeople(people)
93
95
  })
94
- ipcMain.handle('pmate:reach:configure', (event, identity) => {
96
+ ipcMain.handle('pmate:reach:configure', async (event, identity) => {
95
97
  if (!desktopNotifications.trusted(event)) throw new Error('Untrusted reach sender')
96
- return desktopReach.configure(identity)
98
+ const result = await desktopReach.configure(identity)
99
+ agentRuntime.setIdentity(identity)
100
+ return result
97
101
  })
98
102
  ipcMain.handle('pmate:reach:stop', event => {
99
103
  if (!desktopNotifications.trusted(event)) throw new Error('Untrusted reach sender')
104
+ agentRuntime.setIdentity(null)
100
105
  desktopReach.stop(); desktopNotifications.reset()
101
106
  })
102
107
  app.on('before-quit', () => { desktopTray?.beginQuit(); desktopApps.close(); desktopReach.stop(); desktopNotifications.reset() })
@@ -2,6 +2,7 @@ const { contextBridge, ipcRenderer } = require('electron')
2
2
  const origin = process.argv.find(value => value.startsWith('--pmate-origin='))?.slice('--pmate-origin='.length)
3
3
  if (process.isMainFrame && location.origin === origin) contextBridge.exposeInMainWorld('pmateDesktop', Object.freeze({
4
4
  runtime: Object.freeze({ platform: process.platform, appVersion: process.argv.find(value => value.startsWith('--pmate-app-version='))?.slice('--pmate-app-version='.length), electronVersion: process.versions.electron, bridgeVersion: '1.3.0', contentSource: 'remote' }),
5
+ electron: Object.freeze({ invoke: (method, input) => ipcRenderer.invoke('pmate:electron:invoke', method, input) }),
5
6
  updates: Object.freeze({
6
7
  check: () => ipcRenderer.invoke('pmate:update:check'),
7
8
  download: () => ipcRenderer.invoke('pmate:update:download'),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pmate/cli",
3
- "version": "0.44.1",
3
+ "version": "0.44.2",
4
4
  "description": "CLI utilities for the pMate project",
5
5
  "license": "MIT",
6
6
  "bin": {