toc-ocra 0.2.34 → 0.2.36
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/LICENSE +21 -21
- package/README.md +129 -121
- package/assets/icon.svg +1 -1
- package/dist/cli/cli.mjs +747 -395
- package/dist/plugin/renderer.css.map +1 -1
- package/dist/plugin/renderer.js.map +1 -1
- package/dist/service/agent.mjs +734 -383
- package/dist/src/exec/script-runner.js +9 -5
- package/dist/src/exec/script-runner.js.map +1 -1
- package/dist/src/health/server.js +8 -8
- package/dist/src/index.js +6 -2
- package/dist/src/index.js.map +1 -1
- package/dist/src/platform/common.d.ts +20 -0
- package/dist/src/platform/common.js +40 -0
- package/dist/src/platform/common.js.map +1 -0
- package/dist/src/platform/index.d.ts +10 -0
- package/dist/src/platform/index.js +20 -0
- package/dist/src/platform/index.js.map +1 -0
- package/dist/src/platform/posix.d.ts +2 -0
- package/dist/src/platform/posix.js +210 -0
- package/dist/src/platform/posix.js.map +1 -0
- package/dist/src/platform/types.d.ts +61 -0
- package/dist/src/platform/types.js +2 -0
- package/dist/src/platform/types.js.map +1 -0
- package/dist/src/platform/win32.d.ts +4 -0
- package/dist/src/platform/win32.js +162 -0
- package/dist/src/platform/win32.js.map +1 -0
- package/dist/src/providers/cli/claude.js +3 -2
- package/dist/src/providers/cli/claude.js.map +1 -1
- package/dist/src/providers/cli/codex.js +3 -2
- package/dist/src/providers/cli/codex.js.map +1 -1
- package/dist/src/providers/cli/gemini.js +2 -2
- package/dist/src/providers/cli/gemini.js.map +1 -1
- package/dist/src/providers/cli/grok.js +2 -2
- package/dist/src/providers/cli/grok.js.map +1 -1
- package/dist/src/providers/cli/kiro-session-log.d.ts +53 -0
- package/dist/src/providers/cli/kiro-session-log.js +155 -0
- package/dist/src/providers/cli/kiro-session-log.js.map +1 -0
- package/dist/src/providers/cli/kiro.d.ts +8 -2
- package/dist/src/providers/cli/kiro.js +100 -13
- package/dist/src/providers/cli/kiro.js.map +1 -1
- package/dist/src/providers/cli/opencode.js +2 -2
- package/dist/src/providers/cli/opencode.js.map +1 -1
- package/dist/src/providers/codex-quota.js +3 -2
- package/dist/src/providers/codex-quota.js.map +1 -1
- package/dist/src/providers/detection.js +3 -1
- package/dist/src/providers/detection.js.map +1 -1
- package/dist/src/providers/kiro-models.js +3 -2
- package/dist/src/providers/kiro-models.js.map +1 -1
- package/dist/src/providers/model-catalog.js +3 -1
- package/dist/src/providers/model-catalog.js.map +1 -1
- package/dist/src/providers/provider.d.ts +55 -4
- package/dist/src/providers/provider.js +51 -15
- package/dist/src/providers/provider.js.map +1 -1
- package/dist/src/runs/orphan-registry.js +2 -8
- package/dist/src/runs/orphan-registry.js.map +1 -1
- package/dist/src/runs/process-tree.d.ts +5 -14
- package/dist/src/runs/process-tree.js +7 -83
- package/dist/src/runs/process-tree.js.map +1 -1
- package/dist/src/runs/run-supervisor.d.ts +2 -0
- package/dist/src/runs/run-supervisor.js +56 -10
- package/dist/src/runs/run-supervisor.js.map +1 -1
- package/dist/src/runtime/cli/hydrate-shell-path.d.ts +9 -22
- package/dist/src/runtime/cli/hydrate-shell-path.js +17 -148
- package/dist/src/runtime/cli/hydrate-shell-path.js.map +1 -1
- package/dist/src/shared/node-cli-command-resolution.d.ts +5 -0
- package/dist/src/shared/node-cli-command-resolution.js +28 -81
- package/dist/src/shared/node-cli-command-resolution.js.map +1 -1
- package/locales/en.json +202 -202
- package/locales/zh-CN.json +202 -202
- package/package.json +100 -100
- package/scripts/installation.cjs +239 -239
- package/scripts/postinstall.cjs +22 -22
- package/scripts/service.mjs +253 -253
package/scripts/installation.cjs
CHANGED
|
@@ -1,239 +1,239 @@
|
|
|
1
|
-
'use strict'
|
|
2
|
-
|
|
3
|
-
// The npm global package directory is the sole toc-ocra installation. Echo
|
|
4
|
-
// records its location here and reads it in place; it never keeps a copy.
|
|
5
|
-
const fs = require('node:fs')
|
|
6
|
-
const path = require('node:path')
|
|
7
|
-
const os = require('node:os')
|
|
8
|
-
const net = require('node:net')
|
|
9
|
-
const { spawn } = require('node:child_process')
|
|
10
|
-
const { setTimeout: delay } = require('node:timers/promises')
|
|
11
|
-
|
|
12
|
-
const PLUGIN_ID = 'echo.device-agent'
|
|
13
|
-
const PACKAGE_NAME = 'toc-ocra'
|
|
14
|
-
const VERSION = /^\d+\.\d+\.\d+$/
|
|
15
|
-
const UPDATE_LOCK_PORT = 17337
|
|
16
|
-
|
|
17
|
-
function dataDir() {
|
|
18
|
-
if (process.platform === 'darwin') return path.join(os.homedir(), 'Library', 'Application Support', PACKAGE_NAME)
|
|
19
|
-
if (process.platform === 'win32') return path.join(process.env.APPDATA || os.homedir(), PACKAGE_NAME)
|
|
20
|
-
return path.join(process.env.XDG_STATE_HOME || path.join(os.homedir(), '.local', 'state'), PACKAGE_NAME)
|
|
21
|
-
}
|
|
22
|
-
function installationDir() { return path.join(dataDir(), 'installation') }
|
|
23
|
-
function readJson(file) { return JSON.parse(fs.readFileSync(file, 'utf8')) }
|
|
24
|
-
function atomicText(file, text, mode = 0o600) {
|
|
25
|
-
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
|
|
26
|
-
const temporary = `${file}.${process.pid}.tmp`
|
|
27
|
-
fs.writeFileSync(temporary, text, { mode })
|
|
28
|
-
fs.chmodSync(temporary, mode)
|
|
29
|
-
fs.renameSync(temporary, file)
|
|
30
|
-
}
|
|
31
|
-
function atomicJson(file, value) { atomicText(file, JSON.stringify(value, null, 2)) }
|
|
32
|
-
|
|
33
|
-
function packageInfo(root) {
|
|
34
|
-
const pkg = readJson(path.join(root, 'package.json'))
|
|
35
|
-
if (pkg.name !== PACKAGE_NAME || pkg.tocPlugin?.id !== PLUGIN_ID || !VERSION.test(pkg.version)) throw new Error('设备代理安装包身份或版本无效')
|
|
36
|
-
return pkg
|
|
37
|
-
}
|
|
38
|
-
function isGlobalPackage(root) {
|
|
39
|
-
return path.basename(path.dirname(root)) === 'node_modules' &&
|
|
40
|
-
(process.platform === 'win32' || path.basename(path.dirname(path.dirname(root))) === 'lib')
|
|
41
|
-
}
|
|
42
|
-
function runtimeFor(root) {
|
|
43
|
-
const prefix = path.dirname(path.dirname(path.dirname(root)))
|
|
44
|
-
const candidates = process.platform === 'win32'
|
|
45
|
-
? [path.join(prefix, 'node.exe'), path.join(prefix, 'bin', 'node.exe')]
|
|
46
|
-
: [path.join(prefix, 'bin', 'node')]
|
|
47
|
-
return candidates.find(file => fs.existsSync(file)) || process.execPath
|
|
48
|
-
}
|
|
49
|
-
function packageRootFromBin(directory) {
|
|
50
|
-
try {
|
|
51
|
-
let root = path.dirname(fs.realpathSync(path.join(directory, 'toc-ocra')))
|
|
52
|
-
while (path.dirname(root) !== root) {
|
|
53
|
-
if (fs.existsSync(path.join(root, 'package.json'))) {
|
|
54
|
-
const pkg = packageInfo(root)
|
|
55
|
-
return isGlobalPackage(root) ? { root, version: pkg.version, runtime: runtimeFor(root) } : null
|
|
56
|
-
}
|
|
57
|
-
root = path.dirname(root)
|
|
58
|
-
}
|
|
59
|
-
} catch { /* not a toc-ocra executable */ }
|
|
60
|
-
return null
|
|
61
|
-
}
|
|
62
|
-
function candidates(sourceRoot) {
|
|
63
|
-
const found = new Map()
|
|
64
|
-
const add = value => {
|
|
65
|
-
try {
|
|
66
|
-
const root = path.resolve(value)
|
|
67
|
-
const pkg = packageInfo(root)
|
|
68
|
-
if (isGlobalPackage(root)) found.set(root, { root, version: pkg.version, runtime: runtimeFor(root) })
|
|
69
|
-
} catch { /* stale alias or unrelated package */ }
|
|
70
|
-
}
|
|
71
|
-
try {
|
|
72
|
-
const old = readJson(path.join(installationDir(), 'aliases.json'))
|
|
73
|
-
if (Array.isArray(old)) old.forEach(add)
|
|
74
|
-
} catch { /* first install */ }
|
|
75
|
-
for (const directory of (process.env.PATH || '').split(path.delimiter)) {
|
|
76
|
-
const item = packageRootFromBin(directory)
|
|
77
|
-
if (item) found.set(item.root, item)
|
|
78
|
-
}
|
|
79
|
-
add(sourceRoot)
|
|
80
|
-
return [...found.values()].sort((a, b) => {
|
|
81
|
-
const anvm = a.root.includes(`${path.sep}.nvm${path.sep}`) ? 0 : 1
|
|
82
|
-
const bnvm = b.root.includes(`${path.sep}.nvm${path.sep}`) ? 0 : 1
|
|
83
|
-
return anvm - bnvm || a.root.localeCompare(b.root)
|
|
84
|
-
})
|
|
85
|
-
}
|
|
86
|
-
function currentInstallation() {
|
|
87
|
-
const file = path.join(installationDir(), 'current.json')
|
|
88
|
-
if (fs.existsSync(file)) {
|
|
89
|
-
const record = readJson(file)
|
|
90
|
-
if (record.schema === 2 && typeof record.root === 'string' && path.isAbsolute(record.root)) {
|
|
91
|
-
const root = path.resolve(record.root)
|
|
92
|
-
const pkg = packageInfo(root)
|
|
93
|
-
if (!isGlobalPackage(root) || !fs.existsSync(path.join(root, 'dist', 'cli', 'cli.mjs')))
|
|
94
|
-
throw new Error('设备代理唯一安装位置无效,请重新安装 toc-ocra')
|
|
95
|
-
const current = { ...record, version: pkg.version, runtime: record.runtime && fs.existsSync(record.runtime) ? record.runtime : runtimeFor(root), root, pkg }
|
|
96
|
-
if (record.version !== pkg.version || record.runtime !== current.runtime) {
|
|
97
|
-
atomicJson(file, { schema: 2, root, runtime: current.runtime, version: pkg.version, updatedAt: new Date().toISOString() })
|
|
98
|
-
}
|
|
99
|
-
return current
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
const root = candidates()[0]
|
|
103
|
-
if (!root) return null
|
|
104
|
-
const pkg = packageInfo(root.root)
|
|
105
|
-
return { schema: 2, root: root.root, runtime: root.runtime, version: pkg.version, updatedAt: new Date().toISOString(), pkg }
|
|
106
|
-
}
|
|
107
|
-
function compareVersions(a, b) {
|
|
108
|
-
const left = a.split('.').map(Number), right = b.split('.').map(Number)
|
|
109
|
-
for (let i = 0; i < 3; i++) if (left[i] !== right[i]) return left[i] - right[i]
|
|
110
|
-
return 0
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
async function endpoint() {
|
|
114
|
-
const configPath = process.env.TOC_OCRA_CONFIG || path.join(process.env.TOC_OCRA_DATA_DIR || dataDir(), 'config.json')
|
|
115
|
-
let config = {}
|
|
116
|
-
try { config = readJson(configPath) } catch (error) { if (error.code !== 'ENOENT') throw error }
|
|
117
|
-
let host = process.env.TOC_OCRA_HEALTH_HOST || config.healthHost || '127.0.0.1'
|
|
118
|
-
if (host === '0.0.0.0' || host === '::') host = '127.0.0.1'
|
|
119
|
-
if (host.includes(':')) host = `[${host}]`
|
|
120
|
-
return `http://${host}:${process.env.TOC_OCRA_HEALTH_PORT || config.healthPort || 17339}`
|
|
121
|
-
}
|
|
122
|
-
async function runningAgent() {
|
|
123
|
-
const base = await endpoint()
|
|
124
|
-
const info = await fetch(`${base}/control/info`, { signal: AbortSignal.timeout(2_000) }).then(r => r.ok ? r.json() : null).catch(() => null)
|
|
125
|
-
if (info?.name !== PACKAGE_NAME) return null
|
|
126
|
-
const state = await fetch(`${base}/health`, { signal: AbortSignal.timeout(2_000) }).then(r => { if (!r.ok) throw new Error('无法读取设备代理状态'); return r.json() })
|
|
127
|
-
if (!Number.isInteger(state.activeSessions)) throw new Error('无法确认设备代理的活动任务,请稍后重试')
|
|
128
|
-
return { base, info, state }
|
|
129
|
-
}
|
|
130
|
-
async function ensureIdle() {
|
|
131
|
-
const running = await runningAgent()
|
|
132
|
-
if (running?.state.activeSessions > 0) throw new Error(`本机还有 ${running.state.activeSessions} 个任务运行,请在任务结束后升级`)
|
|
133
|
-
return running
|
|
134
|
-
}
|
|
135
|
-
function execute(runtime, args) {
|
|
136
|
-
return new Promise((resolve, reject) => {
|
|
137
|
-
const child = spawn(runtime, args, { env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' }, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
|
|
138
|
-
let output = ''
|
|
139
|
-
child.stdout.on('data', x => { output = (output + x).slice(-4_000) })
|
|
140
|
-
child.stderr.on('data', x => { output = (output + x).slice(-4_000) })
|
|
141
|
-
child.once('error', reject)
|
|
142
|
-
child.once('exit', code => code === 0 ? resolve() : reject(new Error(output.trim() || `更新设备代理服务失败(${code})`)))
|
|
143
|
-
})
|
|
144
|
-
}
|
|
145
|
-
function instanceRunning() {
|
|
146
|
-
return new Promise((resolve, reject) => {
|
|
147
|
-
const socket = net.createConnection({ host: '127.0.0.1', port: 17338 })
|
|
148
|
-
socket.setTimeout(1_000, () => { socket.destroy(); reject(new Error('无法确认旧设备代理是否退出')) })
|
|
149
|
-
socket.once('connect', () => { socket.destroy(); resolve(true) })
|
|
150
|
-
socket.once('error', error => { socket.destroy(); if (error.code === 'ECONNREFUSED') resolve(false); else reject(error) })
|
|
151
|
-
})
|
|
152
|
-
}
|
|
153
|
-
async function restart(current, running) {
|
|
154
|
-
if (running) {
|
|
155
|
-
const tokenFile = path.join(process.env.TOC_OCRA_DATA_DIR || dataDir(), 'control-token')
|
|
156
|
-
if (fs.existsSync(tokenFile)) {
|
|
157
|
-
const token = fs.readFileSync(tokenFile, 'utf8').trim()
|
|
158
|
-
const response = await fetch(`${running.base}/control/shutdown`, { method: 'POST', headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(3_000) }).catch(() => null)
|
|
159
|
-
if (response && !response.ok && response.status !== 404) throw new Error('设备代理拒绝升级重启,请确认本机控制凭据有效')
|
|
160
|
-
if (response?.ok) {
|
|
161
|
-
await response.arrayBuffer()
|
|
162
|
-
for (let attempt = 0; attempt < 120 && await instanceRunning(); attempt++) await delay(500)
|
|
163
|
-
if (await instanceRunning()) throw new Error('旧设备代理尚未完整退出,已停止升级重启')
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
await execute(current.runtime, [path.join(current.root, 'scripts', 'service.mjs'), 'install'])
|
|
168
|
-
for (let attempt = 0; attempt < 60; attempt++) {
|
|
169
|
-
const next = await runningAgent()
|
|
170
|
-
if (next?.info.version === current.version) return
|
|
171
|
-
await delay(500)
|
|
172
|
-
}
|
|
173
|
-
throw new Error('设备代理已更新,但未确认新版服务启动')
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
function copyPackage(source, target) {
|
|
177
|
-
fs.mkdirSync(target, { recursive: true, mode: 0o700 })
|
|
178
|
-
for (const name of ['package.json', 'dist/cli', 'dist/service', 'dist/plugin', 'dist/src', 'assets', 'locales', 'scripts', 'README.md', 'LICENSE']) {
|
|
179
|
-
const from = path.join(source, name)
|
|
180
|
-
if (fs.existsSync(from)) fs.cpSync(from, path.join(target, name), { recursive: true, filter: file => !fs.lstatSync(file).isSymbolicLink() })
|
|
181
|
-
}
|
|
182
|
-
packageInfo(target)
|
|
183
|
-
if (!fs.existsSync(path.join(target, 'dist', 'cli', 'cli.mjs'))) throw new Error('toc-ocra 命令入口缺失')
|
|
184
|
-
}
|
|
185
|
-
async function installShared(sourceRoot, options = {}) {
|
|
186
|
-
const source = fs.realpathSync(sourceRoot)
|
|
187
|
-
const pkg = packageInfo(source)
|
|
188
|
-
if (!fs.existsSync(path.join(source, 'dist', 'cli', 'cli.mjs'))) throw new Error('此版本尚不支持单目录安装,请先构建 toc-ocra')
|
|
189
|
-
const lock = net.createServer(socket => socket.end())
|
|
190
|
-
await new Promise((resolve, reject) => {
|
|
191
|
-
lock.once('error', () => reject(new Error('设备代理正在进行另一项升级,请稍后重试')))
|
|
192
|
-
lock.listen({ host: '127.0.0.1', port: UPDATE_LOCK_PORT, exclusive: true }, resolve)
|
|
193
|
-
})
|
|
194
|
-
let current, wasRunning, swapped = false
|
|
195
|
-
let staging, backup
|
|
196
|
-
try {
|
|
197
|
-
current = currentInstallation() || candidates(source)[0]
|
|
198
|
-
if (!current) throw new Error('找不到现有 npm 全局安装。请先通过 nvm 安装 toc-ocra,再从 Echo 或终端升级')
|
|
199
|
-
if (compareVersions(pkg.version, current.version) < 0) throw new Error(`本机已有较新版本 ${current.version},已阻止降级到 ${pkg.version}`)
|
|
200
|
-
// npm releases are immutable by version. In particular, do not replace a
|
|
201
|
-
// locally repaired install with stale contents from the same registry tag.
|
|
202
|
-
if (pkg.version === current.version) return current
|
|
203
|
-
wasRunning = await ensureIdle()
|
|
204
|
-
if (options.beforeInstall) await options.beforeInstall()
|
|
205
|
-
const root = current.root
|
|
206
|
-
const parent = path.dirname(root)
|
|
207
|
-
staging = fs.mkdtempSync(path.join(parent, '.toc-ocra-install-'))
|
|
208
|
-
fs.rmSync(staging, { recursive: true, force: true })
|
|
209
|
-
copyPackage(source, staging)
|
|
210
|
-
const oldVersion = packageInfo(root).version
|
|
211
|
-
backup = path.join(parent, `.toc-ocra-backup-${process.pid}`)
|
|
212
|
-
if (fs.existsSync(backup)) fs.rmSync(backup, { recursive: true, force: true })
|
|
213
|
-
fs.renameSync(root, backup)
|
|
214
|
-
try { fs.renameSync(staging, root); swapped = true }
|
|
215
|
-
catch (error) { fs.renameSync(backup, root); throw error }
|
|
216
|
-
const nextPkg = packageInfo(root)
|
|
217
|
-
const next = { schema: 2, root, runtime: current.runtime || runtimeFor(root), version: nextPkg.version, updatedAt: new Date().toISOString() }
|
|
218
|
-
atomicJson(path.join(installationDir(), 'current.json'), next)
|
|
219
|
-
if (wasRunning || options.startService) await restart({ ...next, pkg: nextPkg }, wasRunning)
|
|
220
|
-
fs.rmSync(backup, { recursive: true, force: true })
|
|
221
|
-
return { ...next, pkg: nextPkg }
|
|
222
|
-
} catch (error) {
|
|
223
|
-
if (swapped && backup && fs.existsSync(backup)) {
|
|
224
|
-
const root = current.root
|
|
225
|
-
fs.rmSync(root, { recursive: true, force: true })
|
|
226
|
-
fs.renameSync(backup, root)
|
|
227
|
-
const pkg = packageInfo(root)
|
|
228
|
-
const restored = { schema: 2, root, runtime: current.runtime || runtimeFor(root), version: pkg.version, updatedAt: new Date().toISOString() }
|
|
229
|
-
atomicJson(path.join(installationDir(), 'current.json'), restored)
|
|
230
|
-
if (wasRunning) await restart({ ...restored, pkg }, await runningAgent()).catch(() => undefined)
|
|
231
|
-
}
|
|
232
|
-
throw error
|
|
233
|
-
} finally {
|
|
234
|
-
if (staging) fs.rmSync(staging, { recursive: true, force: true })
|
|
235
|
-
await new Promise(resolve => lock.close(resolve))
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
module.exports = { PLUGIN_ID, PACKAGE_NAME, installationDir, currentInstallation, compareVersions, isGlobalPackage, installShared, ensureIdle }
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
// The npm global package directory is the sole toc-ocra installation. Echo
|
|
4
|
+
// records its location here and reads it in place; it never keeps a copy.
|
|
5
|
+
const fs = require('node:fs')
|
|
6
|
+
const path = require('node:path')
|
|
7
|
+
const os = require('node:os')
|
|
8
|
+
const net = require('node:net')
|
|
9
|
+
const { spawn } = require('node:child_process')
|
|
10
|
+
const { setTimeout: delay } = require('node:timers/promises')
|
|
11
|
+
|
|
12
|
+
const PLUGIN_ID = 'echo.device-agent'
|
|
13
|
+
const PACKAGE_NAME = 'toc-ocra'
|
|
14
|
+
const VERSION = /^\d+\.\d+\.\d+$/
|
|
15
|
+
const UPDATE_LOCK_PORT = 17337
|
|
16
|
+
|
|
17
|
+
function dataDir() {
|
|
18
|
+
if (process.platform === 'darwin') return path.join(os.homedir(), 'Library', 'Application Support', PACKAGE_NAME)
|
|
19
|
+
if (process.platform === 'win32') return path.join(process.env.APPDATA || os.homedir(), PACKAGE_NAME)
|
|
20
|
+
return path.join(process.env.XDG_STATE_HOME || path.join(os.homedir(), '.local', 'state'), PACKAGE_NAME)
|
|
21
|
+
}
|
|
22
|
+
function installationDir() { return path.join(dataDir(), 'installation') }
|
|
23
|
+
function readJson(file) { return JSON.parse(fs.readFileSync(file, 'utf8')) }
|
|
24
|
+
function atomicText(file, text, mode = 0o600) {
|
|
25
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
|
|
26
|
+
const temporary = `${file}.${process.pid}.tmp`
|
|
27
|
+
fs.writeFileSync(temporary, text, { mode })
|
|
28
|
+
fs.chmodSync(temporary, mode)
|
|
29
|
+
fs.renameSync(temporary, file)
|
|
30
|
+
}
|
|
31
|
+
function atomicJson(file, value) { atomicText(file, JSON.stringify(value, null, 2)) }
|
|
32
|
+
|
|
33
|
+
function packageInfo(root) {
|
|
34
|
+
const pkg = readJson(path.join(root, 'package.json'))
|
|
35
|
+
if (pkg.name !== PACKAGE_NAME || pkg.tocPlugin?.id !== PLUGIN_ID || !VERSION.test(pkg.version)) throw new Error('设备代理安装包身份或版本无效')
|
|
36
|
+
return pkg
|
|
37
|
+
}
|
|
38
|
+
function isGlobalPackage(root) {
|
|
39
|
+
return path.basename(path.dirname(root)) === 'node_modules' &&
|
|
40
|
+
(process.platform === 'win32' || path.basename(path.dirname(path.dirname(root))) === 'lib')
|
|
41
|
+
}
|
|
42
|
+
function runtimeFor(root) {
|
|
43
|
+
const prefix = path.dirname(path.dirname(path.dirname(root)))
|
|
44
|
+
const candidates = process.platform === 'win32'
|
|
45
|
+
? [path.join(prefix, 'node.exe'), path.join(prefix, 'bin', 'node.exe')]
|
|
46
|
+
: [path.join(prefix, 'bin', 'node')]
|
|
47
|
+
return candidates.find(file => fs.existsSync(file)) || process.execPath
|
|
48
|
+
}
|
|
49
|
+
function packageRootFromBin(directory) {
|
|
50
|
+
try {
|
|
51
|
+
let root = path.dirname(fs.realpathSync(path.join(directory, 'toc-ocra')))
|
|
52
|
+
while (path.dirname(root) !== root) {
|
|
53
|
+
if (fs.existsSync(path.join(root, 'package.json'))) {
|
|
54
|
+
const pkg = packageInfo(root)
|
|
55
|
+
return isGlobalPackage(root) ? { root, version: pkg.version, runtime: runtimeFor(root) } : null
|
|
56
|
+
}
|
|
57
|
+
root = path.dirname(root)
|
|
58
|
+
}
|
|
59
|
+
} catch { /* not a toc-ocra executable */ }
|
|
60
|
+
return null
|
|
61
|
+
}
|
|
62
|
+
function candidates(sourceRoot) {
|
|
63
|
+
const found = new Map()
|
|
64
|
+
const add = value => {
|
|
65
|
+
try {
|
|
66
|
+
const root = path.resolve(value)
|
|
67
|
+
const pkg = packageInfo(root)
|
|
68
|
+
if (isGlobalPackage(root)) found.set(root, { root, version: pkg.version, runtime: runtimeFor(root) })
|
|
69
|
+
} catch { /* stale alias or unrelated package */ }
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
const old = readJson(path.join(installationDir(), 'aliases.json'))
|
|
73
|
+
if (Array.isArray(old)) old.forEach(add)
|
|
74
|
+
} catch { /* first install */ }
|
|
75
|
+
for (const directory of (process.env.PATH || '').split(path.delimiter)) {
|
|
76
|
+
const item = packageRootFromBin(directory)
|
|
77
|
+
if (item) found.set(item.root, item)
|
|
78
|
+
}
|
|
79
|
+
add(sourceRoot)
|
|
80
|
+
return [...found.values()].sort((a, b) => {
|
|
81
|
+
const anvm = a.root.includes(`${path.sep}.nvm${path.sep}`) ? 0 : 1
|
|
82
|
+
const bnvm = b.root.includes(`${path.sep}.nvm${path.sep}`) ? 0 : 1
|
|
83
|
+
return anvm - bnvm || a.root.localeCompare(b.root)
|
|
84
|
+
})
|
|
85
|
+
}
|
|
86
|
+
function currentInstallation() {
|
|
87
|
+
const file = path.join(installationDir(), 'current.json')
|
|
88
|
+
if (fs.existsSync(file)) {
|
|
89
|
+
const record = readJson(file)
|
|
90
|
+
if (record.schema === 2 && typeof record.root === 'string' && path.isAbsolute(record.root)) {
|
|
91
|
+
const root = path.resolve(record.root)
|
|
92
|
+
const pkg = packageInfo(root)
|
|
93
|
+
if (!isGlobalPackage(root) || !fs.existsSync(path.join(root, 'dist', 'cli', 'cli.mjs')))
|
|
94
|
+
throw new Error('设备代理唯一安装位置无效,请重新安装 toc-ocra')
|
|
95
|
+
const current = { ...record, version: pkg.version, runtime: record.runtime && fs.existsSync(record.runtime) ? record.runtime : runtimeFor(root), root, pkg }
|
|
96
|
+
if (record.version !== pkg.version || record.runtime !== current.runtime) {
|
|
97
|
+
atomicJson(file, { schema: 2, root, runtime: current.runtime, version: pkg.version, updatedAt: new Date().toISOString() })
|
|
98
|
+
}
|
|
99
|
+
return current
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const root = candidates()[0]
|
|
103
|
+
if (!root) return null
|
|
104
|
+
const pkg = packageInfo(root.root)
|
|
105
|
+
return { schema: 2, root: root.root, runtime: root.runtime, version: pkg.version, updatedAt: new Date().toISOString(), pkg }
|
|
106
|
+
}
|
|
107
|
+
function compareVersions(a, b) {
|
|
108
|
+
const left = a.split('.').map(Number), right = b.split('.').map(Number)
|
|
109
|
+
for (let i = 0; i < 3; i++) if (left[i] !== right[i]) return left[i] - right[i]
|
|
110
|
+
return 0
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async function endpoint() {
|
|
114
|
+
const configPath = process.env.TOC_OCRA_CONFIG || path.join(process.env.TOC_OCRA_DATA_DIR || dataDir(), 'config.json')
|
|
115
|
+
let config = {}
|
|
116
|
+
try { config = readJson(configPath) } catch (error) { if (error.code !== 'ENOENT') throw error }
|
|
117
|
+
let host = process.env.TOC_OCRA_HEALTH_HOST || config.healthHost || '127.0.0.1'
|
|
118
|
+
if (host === '0.0.0.0' || host === '::') host = '127.0.0.1'
|
|
119
|
+
if (host.includes(':')) host = `[${host}]`
|
|
120
|
+
return `http://${host}:${process.env.TOC_OCRA_HEALTH_PORT || config.healthPort || 17339}`
|
|
121
|
+
}
|
|
122
|
+
async function runningAgent() {
|
|
123
|
+
const base = await endpoint()
|
|
124
|
+
const info = await fetch(`${base}/control/info`, { signal: AbortSignal.timeout(2_000) }).then(r => r.ok ? r.json() : null).catch(() => null)
|
|
125
|
+
if (info?.name !== PACKAGE_NAME) return null
|
|
126
|
+
const state = await fetch(`${base}/health`, { signal: AbortSignal.timeout(2_000) }).then(r => { if (!r.ok) throw new Error('无法读取设备代理状态'); return r.json() })
|
|
127
|
+
if (!Number.isInteger(state.activeSessions)) throw new Error('无法确认设备代理的活动任务,请稍后重试')
|
|
128
|
+
return { base, info, state }
|
|
129
|
+
}
|
|
130
|
+
async function ensureIdle() {
|
|
131
|
+
const running = await runningAgent()
|
|
132
|
+
if (running?.state.activeSessions > 0) throw new Error(`本机还有 ${running.state.activeSessions} 个任务运行,请在任务结束后升级`)
|
|
133
|
+
return running
|
|
134
|
+
}
|
|
135
|
+
function execute(runtime, args) {
|
|
136
|
+
return new Promise((resolve, reject) => {
|
|
137
|
+
const child = spawn(runtime, args, { env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' }, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
|
|
138
|
+
let output = ''
|
|
139
|
+
child.stdout.on('data', x => { output = (output + x).slice(-4_000) })
|
|
140
|
+
child.stderr.on('data', x => { output = (output + x).slice(-4_000) })
|
|
141
|
+
child.once('error', reject)
|
|
142
|
+
child.once('exit', code => code === 0 ? resolve() : reject(new Error(output.trim() || `更新设备代理服务失败(${code})`)))
|
|
143
|
+
})
|
|
144
|
+
}
|
|
145
|
+
function instanceRunning() {
|
|
146
|
+
return new Promise((resolve, reject) => {
|
|
147
|
+
const socket = net.createConnection({ host: '127.0.0.1', port: 17338 })
|
|
148
|
+
socket.setTimeout(1_000, () => { socket.destroy(); reject(new Error('无法确认旧设备代理是否退出')) })
|
|
149
|
+
socket.once('connect', () => { socket.destroy(); resolve(true) })
|
|
150
|
+
socket.once('error', error => { socket.destroy(); if (error.code === 'ECONNREFUSED') resolve(false); else reject(error) })
|
|
151
|
+
})
|
|
152
|
+
}
|
|
153
|
+
async function restart(current, running) {
|
|
154
|
+
if (running) {
|
|
155
|
+
const tokenFile = path.join(process.env.TOC_OCRA_DATA_DIR || dataDir(), 'control-token')
|
|
156
|
+
if (fs.existsSync(tokenFile)) {
|
|
157
|
+
const token = fs.readFileSync(tokenFile, 'utf8').trim()
|
|
158
|
+
const response = await fetch(`${running.base}/control/shutdown`, { method: 'POST', headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(3_000) }).catch(() => null)
|
|
159
|
+
if (response && !response.ok && response.status !== 404) throw new Error('设备代理拒绝升级重启,请确认本机控制凭据有效')
|
|
160
|
+
if (response?.ok) {
|
|
161
|
+
await response.arrayBuffer()
|
|
162
|
+
for (let attempt = 0; attempt < 120 && await instanceRunning(); attempt++) await delay(500)
|
|
163
|
+
if (await instanceRunning()) throw new Error('旧设备代理尚未完整退出,已停止升级重启')
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
await execute(current.runtime, [path.join(current.root, 'scripts', 'service.mjs'), 'install'])
|
|
168
|
+
for (let attempt = 0; attempt < 60; attempt++) {
|
|
169
|
+
const next = await runningAgent()
|
|
170
|
+
if (next?.info.version === current.version) return
|
|
171
|
+
await delay(500)
|
|
172
|
+
}
|
|
173
|
+
throw new Error('设备代理已更新,但未确认新版服务启动')
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function copyPackage(source, target) {
|
|
177
|
+
fs.mkdirSync(target, { recursive: true, mode: 0o700 })
|
|
178
|
+
for (const name of ['package.json', 'dist/cli', 'dist/service', 'dist/plugin', 'dist/src', 'assets', 'locales', 'scripts', 'README.md', 'LICENSE']) {
|
|
179
|
+
const from = path.join(source, name)
|
|
180
|
+
if (fs.existsSync(from)) fs.cpSync(from, path.join(target, name), { recursive: true, filter: file => !fs.lstatSync(file).isSymbolicLink() })
|
|
181
|
+
}
|
|
182
|
+
packageInfo(target)
|
|
183
|
+
if (!fs.existsSync(path.join(target, 'dist', 'cli', 'cli.mjs'))) throw new Error('toc-ocra 命令入口缺失')
|
|
184
|
+
}
|
|
185
|
+
async function installShared(sourceRoot, options = {}) {
|
|
186
|
+
const source = fs.realpathSync(sourceRoot)
|
|
187
|
+
const pkg = packageInfo(source)
|
|
188
|
+
if (!fs.existsSync(path.join(source, 'dist', 'cli', 'cli.mjs'))) throw new Error('此版本尚不支持单目录安装,请先构建 toc-ocra')
|
|
189
|
+
const lock = net.createServer(socket => socket.end())
|
|
190
|
+
await new Promise((resolve, reject) => {
|
|
191
|
+
lock.once('error', () => reject(new Error('设备代理正在进行另一项升级,请稍后重试')))
|
|
192
|
+
lock.listen({ host: '127.0.0.1', port: UPDATE_LOCK_PORT, exclusive: true }, resolve)
|
|
193
|
+
})
|
|
194
|
+
let current, wasRunning, swapped = false
|
|
195
|
+
let staging, backup
|
|
196
|
+
try {
|
|
197
|
+
current = currentInstallation() || candidates(source)[0]
|
|
198
|
+
if (!current) throw new Error('找不到现有 npm 全局安装。请先通过 nvm 安装 toc-ocra,再从 Echo 或终端升级')
|
|
199
|
+
if (compareVersions(pkg.version, current.version) < 0) throw new Error(`本机已有较新版本 ${current.version},已阻止降级到 ${pkg.version}`)
|
|
200
|
+
// npm releases are immutable by version. In particular, do not replace a
|
|
201
|
+
// locally repaired install with stale contents from the same registry tag.
|
|
202
|
+
if (pkg.version === current.version) return current
|
|
203
|
+
wasRunning = await ensureIdle()
|
|
204
|
+
if (options.beforeInstall) await options.beforeInstall()
|
|
205
|
+
const root = current.root
|
|
206
|
+
const parent = path.dirname(root)
|
|
207
|
+
staging = fs.mkdtempSync(path.join(parent, '.toc-ocra-install-'))
|
|
208
|
+
fs.rmSync(staging, { recursive: true, force: true })
|
|
209
|
+
copyPackage(source, staging)
|
|
210
|
+
const oldVersion = packageInfo(root).version
|
|
211
|
+
backup = path.join(parent, `.toc-ocra-backup-${process.pid}`)
|
|
212
|
+
if (fs.existsSync(backup)) fs.rmSync(backup, { recursive: true, force: true })
|
|
213
|
+
fs.renameSync(root, backup)
|
|
214
|
+
try { fs.renameSync(staging, root); swapped = true }
|
|
215
|
+
catch (error) { fs.renameSync(backup, root); throw error }
|
|
216
|
+
const nextPkg = packageInfo(root)
|
|
217
|
+
const next = { schema: 2, root, runtime: current.runtime || runtimeFor(root), version: nextPkg.version, updatedAt: new Date().toISOString() }
|
|
218
|
+
atomicJson(path.join(installationDir(), 'current.json'), next)
|
|
219
|
+
if (wasRunning || options.startService) await restart({ ...next, pkg: nextPkg }, wasRunning)
|
|
220
|
+
fs.rmSync(backup, { recursive: true, force: true })
|
|
221
|
+
return { ...next, pkg: nextPkg }
|
|
222
|
+
} catch (error) {
|
|
223
|
+
if (swapped && backup && fs.existsSync(backup)) {
|
|
224
|
+
const root = current.root
|
|
225
|
+
fs.rmSync(root, { recursive: true, force: true })
|
|
226
|
+
fs.renameSync(backup, root)
|
|
227
|
+
const pkg = packageInfo(root)
|
|
228
|
+
const restored = { schema: 2, root, runtime: current.runtime || runtimeFor(root), version: pkg.version, updatedAt: new Date().toISOString() }
|
|
229
|
+
atomicJson(path.join(installationDir(), 'current.json'), restored)
|
|
230
|
+
if (wasRunning) await restart({ ...restored, pkg }, await runningAgent()).catch(() => undefined)
|
|
231
|
+
}
|
|
232
|
+
throw error
|
|
233
|
+
} finally {
|
|
234
|
+
if (staging) fs.rmSync(staging, { recursive: true, force: true })
|
|
235
|
+
await new Promise(resolve => lock.close(resolve))
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
module.exports = { PLUGIN_ID, PACKAGE_NAME, installationDir, currentInstallation, compareVersions, isGlobalPackage, installShared, ensureIdle }
|
package/scripts/postinstall.cjs
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
'use strict'
|
|
2
|
-
const path = require('node:path')
|
|
3
|
-
const fs = require('node:fs')
|
|
4
|
-
const { installShared } = require('./installation.cjs')
|
|
5
|
-
|
|
6
|
-
if (process.env.npm_config_global === 'true') {
|
|
7
|
-
const source = path.resolve(__dirname, '..')
|
|
8
|
-
installShared(source).then(current => {
|
|
9
|
-
// npm may have staged this package under a different global prefix. Fold
|
|
10
|
-
// it into the one registered installation, then remove only this package
|
|
11
|
-
// copy and its npm-owned command symlink.
|
|
12
|
-
if (path.resolve(source) !== path.resolve(current.root)) {
|
|
13
|
-
const prefix = path.dirname(path.dirname(path.dirname(source)))
|
|
14
|
-
const bin = path.join(prefix, 'bin', process.platform === 'win32' ? 'toc-ocra.cmd' : 'toc-ocra')
|
|
15
|
-
try {
|
|
16
|
-
if (fs.lstatSync(bin).isSymbolicLink() && path.resolve(path.dirname(bin), fs.readlinkSync(bin)) === path.resolve(source, 'dist', 'cli', 'cli.mjs')) fs.unlinkSync(bin)
|
|
17
|
-
} catch { /* absent or not owned by this package */ }
|
|
18
|
-
fs.rmSync(source, { recursive: true, force: true })
|
|
19
|
-
}
|
|
20
|
-
console.log(`toc-ocra ${current.version} 已更新到唯一安装位置 ${current.root}`)
|
|
21
|
-
}).catch(error => { console.error(error.message); process.exitCode = 1 })
|
|
22
|
-
}
|
|
1
|
+
'use strict'
|
|
2
|
+
const path = require('node:path')
|
|
3
|
+
const fs = require('node:fs')
|
|
4
|
+
const { installShared } = require('./installation.cjs')
|
|
5
|
+
|
|
6
|
+
if (process.env.npm_config_global === 'true') {
|
|
7
|
+
const source = path.resolve(__dirname, '..')
|
|
8
|
+
installShared(source).then(current => {
|
|
9
|
+
// npm may have staged this package under a different global prefix. Fold
|
|
10
|
+
// it into the one registered installation, then remove only this package
|
|
11
|
+
// copy and its npm-owned command symlink.
|
|
12
|
+
if (path.resolve(source) !== path.resolve(current.root)) {
|
|
13
|
+
const prefix = path.dirname(path.dirname(path.dirname(source)))
|
|
14
|
+
const bin = path.join(prefix, 'bin', process.platform === 'win32' ? 'toc-ocra.cmd' : 'toc-ocra')
|
|
15
|
+
try {
|
|
16
|
+
if (fs.lstatSync(bin).isSymbolicLink() && path.resolve(path.dirname(bin), fs.readlinkSync(bin)) === path.resolve(source, 'dist', 'cli', 'cli.mjs')) fs.unlinkSync(bin)
|
|
17
|
+
} catch { /* absent or not owned by this package */ }
|
|
18
|
+
fs.rmSync(source, { recursive: true, force: true })
|
|
19
|
+
}
|
|
20
|
+
console.log(`toc-ocra ${current.version} 已更新到唯一安装位置 ${current.root}`)
|
|
21
|
+
}).catch(error => { console.error(error.message); process.exitCode = 1 })
|
|
22
|
+
}
|