toc-ocra 0.2.24 → 0.2.27

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,251 @@
1
+ 'use strict'
2
+
3
+ // Shared installation protocol v1. Keep this file identical to
4
+ // echo_web/electron/plugins/ocra-installation.cjs (the desktop never executes
5
+ // lifecycle scripts from downloaded packages).
6
+ const fs = require('node:fs')
7
+ const path = require('node:path')
8
+ const os = require('node:os')
9
+ const net = require('node:net')
10
+ const { spawn } = require('node:child_process')
11
+ const { setTimeout: delay } = require('node:timers/promises')
12
+
13
+ const PLUGIN_ID = 'echo.device-agent'
14
+ const PACKAGE_NAME = 'toc-ocra'
15
+ const VERSION = /^\d+\.\d+\.\d+$/
16
+ const UPDATE_LOCK_PORT = 17337
17
+
18
+ function dataDir() {
19
+ if (process.platform === 'darwin') return path.join(os.homedir(), 'Library', 'Application Support', PACKAGE_NAME)
20
+ if (process.platform === 'win32') return path.join(process.env.APPDATA || os.homedir(), PACKAGE_NAME)
21
+ return path.join(process.env.XDG_STATE_HOME || path.join(os.homedir(), '.local', 'state'), PACKAGE_NAME)
22
+ }
23
+
24
+ function installationDir() { return path.join(dataDir(), 'installation') }
25
+ function readJson(file) { return JSON.parse(fs.readFileSync(file, 'utf8')) }
26
+ function atomicText(file, text, mode) {
27
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
28
+ const temporary = `${file}.${process.pid}.tmp`
29
+ fs.writeFileSync(temporary, text, { mode })
30
+ fs.chmodSync(temporary, mode)
31
+ fs.renameSync(temporary, file)
32
+ }
33
+ function atomicJson(file, value) {
34
+ atomicText(file, JSON.stringify(value, null, 2), 0o600)
35
+ }
36
+
37
+ function packageInfo(root) {
38
+ const pkg = readJson(path.join(root, 'package.json'))
39
+ if (pkg.name !== PACKAGE_NAME || pkg.tocPlugin?.id !== PLUGIN_ID || !VERSION.test(pkg.version)) throw new Error('设备代理安装包身份或版本无效')
40
+ return pkg
41
+ }
42
+
43
+ function currentInstallation() {
44
+ const file = path.join(installationDir(), 'current.json')
45
+ if (!fs.existsSync(file)) return null
46
+ const record = readJson(file)
47
+ if (record.schema !== 1 || !VERSION.test(record.version)) throw new Error('设备代理共享安装记录无效')
48
+ const root = path.join(installationDir(), 'versions', record.version)
49
+ const pkg = packageInfo(root)
50
+ if (pkg.version !== record.version || !fs.existsSync(path.join(root, 'dist', 'cli', 'cli.mjs'))) throw new Error('设备代理共享安装不完整,请重新安装')
51
+ return { ...record, root, pkg }
52
+ }
53
+
54
+ function compareVersions(a, b) {
55
+ const left = a.split('.').map(Number), right = b.split('.').map(Number)
56
+ for (let i = 0; i < 3; i++) if (left[i] !== right[i]) return left[i] - right[i]
57
+ return 0
58
+ }
59
+
60
+ function isGlobalPackage(root) {
61
+ return path.basename(path.dirname(root)) === 'node_modules' &&
62
+ (process.platform === 'win32' || path.basename(path.dirname(path.dirname(root))) === 'lib')
63
+ }
64
+
65
+ function globalAliases(sourceRoot) {
66
+ const aliases = new Set()
67
+ try { for (const root of readJson(path.join(installationDir(), 'aliases.json'))) aliases.add(root) } catch { /* first install */ }
68
+ if (isGlobalPackage(sourceRoot)) aliases.add(sourceRoot)
69
+ for (const directory of (process.env.PATH || '').split(path.delimiter)) {
70
+ try {
71
+ let root = path.dirname(fs.realpathSync(path.join(directory, 'toc-ocra')))
72
+ while (path.dirname(root) !== root) {
73
+ if (fs.existsSync(path.join(root, 'package.json'))) {
74
+ if (packageInfo(root).name === PACKAGE_NAME && isGlobalPackage(root)) aliases.add(root)
75
+ break
76
+ }
77
+ root = path.dirname(root)
78
+ }
79
+ } catch { /* not an npm toc-ocra command */ }
80
+ }
81
+ return [...aliases].filter(root => {
82
+ try { return typeof root === 'string' && path.isAbsolute(root) && isGlobalPackage(root) && packageInfo(root).name === PACKAGE_NAME }
83
+ catch { return false }
84
+ })
85
+ }
86
+
87
+ function syncLaunchers(current, sourceRoot) {
88
+ const launcherDir = path.join(installationDir(), 'bin')
89
+ fs.mkdirSync(launcherDir, { recursive: true, mode: 0o700 })
90
+ const launcher = path.join(launcherDir, 'launch.cjs')
91
+ // This stable launcher resolves the current package on every invocation.
92
+ const body = `const fs=require('node:fs'),path=require('node:path'),{pathToFileURL}=require('node:url');\nconst base=${JSON.stringify(installationDir())};const r=JSON.parse(fs.readFileSync(path.join(base,'current.json'),'utf8'));if(!/^\\d+\\.\\d+\\.\\d+$/.test(r.version))throw Error('共享安装版本无效');import(pathToFileURL(path.join(base,'versions',r.version,'dist','cli','cli.mjs')).href).catch(e=>{console.error(e.message);process.exitCode=1});\n`
93
+ atomicText(launcher, body, 0o600)
94
+ const aliases = globalAliases(sourceRoot)
95
+ for (const root of aliases) {
96
+ const pkg = packageInfo(root)
97
+ const relative = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.[PACKAGE_NAME]
98
+ if (typeof relative !== 'string') continue
99
+ const entry = path.resolve(root, relative)
100
+ if (!entry.startsWith(root + path.sep)) throw new Error('npm 命令入口超出了设备代理安装目录')
101
+ // Preserve npm's bin symlink. Repoint its owned JS entry to the shared
102
+ // launcher, so later npm installs can replace it without EEXIST errors.
103
+ const entries = new Set([entry, path.join(root, 'dist', 'src', 'index.js')])
104
+ for (const file of entries) {
105
+ fs.mkdirSync(path.dirname(file), { recursive: true })
106
+ atomicText(file, `#!/usr/bin/env node\nimport ${JSON.stringify(require('node:url').pathToFileURL(launcher).href)};\n`, 0o755)
107
+ }
108
+ for (const relative of ['dist/service/agent.mjs', 'scripts/service.mjs']) {
109
+ const file = path.join(root, relative)
110
+ if (!fs.existsSync(file)) continue
111
+ const wrapper = `#!/usr/bin/env node\nimport fs from 'node:fs';import path from 'node:path';import{pathToFileURL}from'node:url';const base=${JSON.stringify(installationDir())};const r=JSON.parse(fs.readFileSync(path.join(base,'current.json'),'utf8'));if(!/^\\d+\\.\\d+\\.\\d+$/.test(r.version))throw Error('共享安装版本无效');await import(pathToFileURL(path.join(base,'versions',r.version,${JSON.stringify(relative)})).href);\n`
112
+ atomicText(file, wrapper, 0o755)
113
+ }
114
+ atomicJson(path.join(root, 'package.json'), { ...pkg, version: current.version })
115
+ }
116
+ atomicJson(path.join(installationDir(), 'aliases.json'), aliases)
117
+ // A desktop-only installation also has a terminal command, using the same
118
+ // Node/Electron runtime; existing npm commands are synchronized above.
119
+ if (process.platform !== 'win32') {
120
+ const bin = path.join(os.homedir(), '.local', 'bin', PACKAGE_NAME)
121
+ fs.mkdirSync(path.dirname(bin), { recursive: true })
122
+ const quote = value => `'${value.replaceAll("'", "'\\''")}'`
123
+ atomicText(bin, `#!/bin/sh\n# TOC_OCRA_SHARED_LAUNCHER\nELECTRON_RUN_AS_NODE=1 exec ${quote(current.runtime)} ${quote(launcher)} "$@"\n`, 0o755)
124
+ } else {
125
+ atomicText(path.join(launcherDir, 'toc-ocra.cmd'), `@echo off\r\nset "ELECTRON_RUN_AS_NODE=1"\r\n"${current.runtime}" "${launcher}" %*\r\n`, 0o700)
126
+ }
127
+ }
128
+
129
+ async function endpoint() {
130
+ const configPath = process.env.TOC_OCRA_CONFIG || path.join(process.env.TOC_OCRA_DATA_DIR || dataDir(), 'config.json')
131
+ let config = {}
132
+ try { config = readJson(configPath) } catch (error) { if (error.code !== 'ENOENT') throw error }
133
+ let host = process.env.TOC_OCRA_HEALTH_HOST || config.healthHost || '127.0.0.1'
134
+ if (host === '0.0.0.0' || host === '::') host = '127.0.0.1'
135
+ if (host.includes(':')) host = `[${host}]`
136
+ return `http://${host}:${process.env.TOC_OCRA_HEALTH_PORT || config.healthPort || 17339}`
137
+ }
138
+
139
+ async function runningAgent() {
140
+ const base = await endpoint()
141
+ const info = await fetch(`${base}/control/info`, { signal: AbortSignal.timeout(2_000) }).then(r => r.ok ? r.json() : null).catch(() => null)
142
+ if (info?.name !== PACKAGE_NAME) return null
143
+ const state = await fetch(`${base}/health`, { signal: AbortSignal.timeout(2_000) }).then(r => { if (!r.ok) throw new Error('无法读取设备代理状态'); return r.json() })
144
+ if (!Number.isInteger(state.activeSessions)) throw new Error('无法确认设备代理的活动任务,请稍后重试')
145
+ return { base, info, state }
146
+ }
147
+
148
+ async function ensureIdle() {
149
+ const running = await runningAgent()
150
+ if (running?.state.activeSessions > 0) throw new Error(`本机还有 ${running.state.activeSessions} 个任务运行,请在任务结束后升级`)
151
+ return running
152
+ }
153
+
154
+ function execute(runtime, args) {
155
+ return new Promise((resolve, reject) => {
156
+ const child = spawn(runtime, args, { env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' }, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
157
+ let output = ''
158
+ child.stdout.on('data', x => { output = (output + x).slice(-4_000) })
159
+ child.stderr.on('data', x => { output = (output + x).slice(-4_000) })
160
+ child.once('error', reject)
161
+ child.once('exit', code => code === 0 ? resolve() : reject(new Error(output.trim() || `更新设备代理服务失败(${code})`)))
162
+ })
163
+ }
164
+
165
+ function instanceRunning() {
166
+ return new Promise((resolve, reject) => {
167
+ const socket = net.createConnection({ host: '127.0.0.1', port: 17338 })
168
+ socket.setTimeout(1_000, () => { socket.destroy(); reject(new Error('无法确认旧设备代理是否退出')) })
169
+ socket.once('connect', () => { socket.destroy(); resolve(true) })
170
+ socket.once('error', error => { socket.destroy(); if (error.code === 'ECONNREFUSED') resolve(false); else reject(error) })
171
+ })
172
+ }
173
+
174
+ async function restart(current, running) {
175
+ if (running) {
176
+ const tokenFile = path.join(process.env.TOC_OCRA_DATA_DIR || dataDir(), 'control-token')
177
+ if (fs.existsSync(tokenFile)) {
178
+ const token = fs.readFileSync(tokenFile, 'utf8').trim()
179
+ const response = await fetch(`${running.base}/control/shutdown`, { method: 'POST', headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(3_000) }).catch(() => null)
180
+ // Older agents are stopped by the existing OS service installer below.
181
+ if (response && !response.ok && response.status !== 404) throw new Error('设备代理拒绝升级重启,请确认本机控制凭据有效')
182
+ if (response?.ok) {
183
+ await response.arrayBuffer()
184
+ // Do not bootout a job while its first SIGTERM is still draining.
185
+ // Legacy once-only signal handlers would terminate on the second
186
+ // signal and leave a live server lease behind for 90 seconds.
187
+ for (let attempt = 0; attempt < 120 && await instanceRunning(); attempt++) await delay(500)
188
+ if (await instanceRunning()) throw new Error('旧设备代理尚未完整退出,已停止升级重启')
189
+ }
190
+ }
191
+ }
192
+ await execute(current.runtime, [path.join(current.root, 'scripts', 'service.mjs'), 'install'])
193
+ for (let attempt = 0; attempt < 60; attempt++) {
194
+ const next = await runningAgent()
195
+ if (next?.info.version === current.version) return
196
+ await delay(500)
197
+ }
198
+ throw new Error('共享安装已更新,但未确认新版设备代理启动,升级未完成')
199
+ }
200
+
201
+ async function installShared(sourceRoot, options = {}) {
202
+ const source = fs.realpathSync(sourceRoot)
203
+ const pkg = packageInfo(source)
204
+ if (!fs.existsSync(path.join(source, 'dist', 'cli', 'cli.mjs'))) throw new Error('此版本尚不支持统一安装,请发布新版 toc-ocra 后再升级')
205
+ const lock = net.createServer(socket => socket.end())
206
+ await new Promise((resolve, reject) => {
207
+ lock.once('error', () => reject(new Error('设备代理正在进行另一项升级,请稍后重试')))
208
+ lock.listen({ host: '127.0.0.1', port: UPDATE_LOCK_PORT, exclusive: true }, resolve)
209
+ })
210
+ let previous
211
+ let changed = false
212
+ let wasRunning
213
+ try {
214
+ previous = currentInstallation()
215
+ if (previous && compareVersions(pkg.version, previous.version) < 0) throw new Error(`本机已有较新版本 ${previous.version},已阻止降级到 ${pkg.version}`)
216
+ wasRunning = await ensureIdle()
217
+ if (options.beforeInstall) await options.beforeInstall()
218
+ const versions = path.join(installationDir(), 'versions')
219
+ const target = path.join(versions, pkg.version)
220
+ fs.mkdirSync(versions, { recursive: true, mode: 0o700 })
221
+ if (!fs.existsSync(target)) {
222
+ const staging = fs.mkdtempSync(path.join(versions, '.install-'))
223
+ try {
224
+ for (const name of ['package.json', 'dist/cli', 'dist/service', 'dist/plugin', 'dist/src', 'assets', 'locales', 'scripts', 'README.md', 'LICENSE']) {
225
+ const from = path.join(source, name)
226
+ if (fs.existsSync(from)) fs.cpSync(from, path.join(staging, name), { recursive: true, filter: file => !fs.lstatSync(file).isSymbolicLink() })
227
+ }
228
+ packageInfo(staging)
229
+ fs.renameSync(staging, target)
230
+ } finally { fs.rmSync(staging, { recursive: true, force: true }) }
231
+ }
232
+ const record = { schema: 1, version: pkg.version, runtime: previous?.runtime && fs.existsSync(previous.runtime) ? previous.runtime : options.runtime || process.execPath, updatedAt: new Date().toISOString() }
233
+ atomicJson(path.join(installationDir(), 'current.json'), record)
234
+ changed = true
235
+ const current = currentInstallation()
236
+ syncLaunchers(current, source)
237
+ if (wasRunning || options.startService) await restart(current, wasRunning)
238
+ return current
239
+ } catch (error) {
240
+ if (changed) {
241
+ if (previous) {
242
+ atomicJson(path.join(installationDir(), 'current.json'), previous)
243
+ syncLaunchers(previous, source)
244
+ if (wasRunning) await restart(previous, await runningAgent()).catch(() => undefined)
245
+ } else fs.rmSync(path.join(installationDir(), 'current.json'), { force: true })
246
+ }
247
+ throw error
248
+ } finally { await new Promise(resolve => lock.close(resolve)) }
249
+ }
250
+
251
+ module.exports = { PLUGIN_ID, PACKAGE_NAME, installationDir, currentInstallation, compareVersions, isGlobalPackage, installShared, ensureIdle }
@@ -0,0 +1,9 @@
1
+ 'use strict'
2
+ const path = require('node:path')
3
+ const { installShared } = require('./installation.cjs')
4
+
5
+ if (process.env.npm_config_global === 'true') {
6
+ installShared(path.resolve(__dirname, '..')).then(current => {
7
+ console.log(`toc-ocra ${current.version} 已安装到本机共享位置,终端与 Echo 插件共用此版本`)
8
+ }).catch(error => { console.error(error.message); process.exitCode = 1 })
9
+ }
@@ -1,21 +1,27 @@
1
1
  #!/usr/bin/env node
2
2
  import { existsSync } from 'node:fs'
3
- import { chmod, mkdir, unlink, writeFile } from 'node:fs/promises'
3
+ import { chmod, mkdir, readFile, unlink, writeFile } from 'node:fs/promises'
4
+ import { createConnection } from 'node:net'
4
5
  import { homedir } from 'node:os'
5
6
  import { dirname, join, resolve } from 'node:path'
6
7
  import { fileURLToPath } from 'node:url'
7
8
  import { spawnSync } from 'node:child_process'
9
+ import { setTimeout as delay } from 'node:timers/promises'
8
10
 
9
11
  const SERVICE_NAME = 'toc-ocra'
10
12
  const LAUNCHD_LABEL = 'top.stormapex.toc-ocra'
11
13
  const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
12
- const agentEntry = join(root, 'dist', 'src', 'index.js')
14
+ const bundledEntry = join(root, 'dist', 'cli', 'cli.mjs')
15
+ const agentEntry = existsSync(bundledEntry) ? bundledEntry : join(root, 'dist', 'src', 'index.js')
13
16
  const action = process.argv[2]
14
17
  const configPath = resolve(readOption('--config') ?? defaultConfigPath())
18
+ // Must match src/runtime/instance-lock.ts; never configurable per profile.
19
+ const INSTANCE_LOCK_PORT = 17338
15
20
 
16
21
  if (action !== 'install' && action !== 'uninstall') usage()
17
22
  if (action === 'install' && !existsSync(agentEntry)) fail('Build output is missing. Run npm run build first.')
18
23
  // The service may start unenrolled: it then waits to be paired from the plugin.
24
+ if (action === 'install') await ensureIdle()
19
25
 
20
26
  if (process.platform === 'darwin') await manageLaunchd(action)
21
27
  else if (process.platform === 'linux') await manageSystemd(action)
@@ -41,12 +47,16 @@ async function manageLaunchd(mode) {
41
47
  const target = join(homedir(), 'Library', 'LaunchAgents', `${LAUNCHD_LABEL}.plist`)
42
48
  const domain = `gui/${process.getuid()}`
43
49
  if (mode === 'uninstall') {
44
- command('launchctl', ['bootout', domain, target], true)
50
+ await retireLegacyChat(domain)
51
+ command('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], true)
45
52
  await unlink(target).catch(ignoreMissing)
46
53
  process.stdout.write(`Removed ${target}\n`)
47
54
  return
48
55
  }
49
56
 
57
+ await retireLegacyChat(domain)
58
+ command('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], true)
59
+ await waitForInstanceExit()
50
60
  const logDir = join(defaultDataDir(), 'logs')
51
61
  const path = servicePath()
52
62
  await mkdir(dirname(target), { recursive: true })
@@ -60,20 +70,24 @@ async function manageLaunchd(mode) {
60
70
  </array>
61
71
  <key>EnvironmentVariables</key><dict>
62
72
  <key>TOC_OCRA_CONFIG</key><string>${xml(configPath)}</string>
73
+ <key>ELECTRON_RUN_AS_NODE</key><string>1</string>
63
74
  <key>HOME</key><string>${xml(homedir())}</string>
64
75
  <key>SHELL</key><string>${xml(process.env.SHELL ?? '/bin/zsh')}</string>
65
76
  <key>PATH</key><string>${xml(path)}</string>
66
77
  </dict>
67
- <key>RunAtLoad</key><true/><key>KeepAlive</key><true/>
78
+ <key>RunAtLoad</key><true/>
79
+ <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
80
+ <key>ExitTimeOut</key><integer>60</integer>
81
+ <key>ThrottleInterval</key><integer>10</integer>
68
82
  <key>StandardOutPath</key><string>${xml(join(logDir, 'service.stdout.log'))}</string>
69
83
  <key>StandardErrorPath</key><string>${xml(join(logDir, 'service.stderr.log'))}</string>
70
84
  </dict></plist>
71
85
  `
72
86
  await writeFile(target, plist, { mode: 0o600 })
73
- command('launchctl', ['bootout', domain, target], true)
74
- command('launchctl', ['bootstrap', domain, target])
75
87
  command('launchctl', ['enable', `${domain}/${LAUNCHD_LABEL}`])
76
- command('launchctl', ['kickstart', '-k', `${domain}/${LAUNCHD_LABEL}`])
88
+ // RunAtLoad starts it exactly once. kickstart -k here would kill that new
89
+ // process during startup and leave an outstanding server lease behind.
90
+ command('launchctl', ['bootstrap', domain, target])
77
91
  process.stdout.write(`Installed ${target}\n`)
78
92
  }
79
93
 
@@ -87,6 +101,8 @@ async function manageSystemd(mode) {
87
101
  return
88
102
  }
89
103
 
104
+ command('systemctl', ['--user', 'stop', SERVICE_NAME], true)
105
+ await waitForInstanceExit()
90
106
  await mkdir(dirname(target), { recursive: true })
91
107
  const unit = `[Unit]
92
108
  Description=echo_cli_agent TaskMCP device agent
@@ -96,10 +112,13 @@ Wants=network-online.target
96
112
  [Service]
97
113
  Type=simple
98
114
  Environment=TOC_OCRA_CONFIG=${systemdQuote(configPath)}
115
+ Environment=ELECTRON_RUN_AS_NODE=1
99
116
  Environment=PATH=${systemdQuote(servicePath())}
100
117
  ExecStart=${systemdQuote(process.execPath)} ${systemdQuote(agentEntry)} run
101
- Restart=always
118
+ Restart=on-failure
102
119
  RestartSec=3
120
+ TimeoutStopSec=60
121
+ KillMode=mixed
103
122
  NoNewPrivileges=true
104
123
 
105
124
  [Install]
@@ -120,11 +139,13 @@ async function manageWindowsTask(mode) {
120
139
  return
121
140
  }
122
141
 
142
+ command('schtasks.exe', ['/End', '/TN', SERVICE_NAME], true)
143
+ await waitForInstanceExit()
123
144
  rejectCmdMetacharacters(configPath)
124
145
  rejectCmdMetacharacters(process.execPath)
125
146
  rejectCmdMetacharacters(agentEntry)
126
147
  await mkdir(dirname(launcher), { recursive: true })
127
- await writeFile(launcher, `@echo off\r\nset "TOC_OCRA_CONFIG=${configPath}"\r\n"${process.execPath}" "${agentEntry}" run\r\n`, { mode: 0o600 })
148
+ await writeFile(launcher, `@echo off\r\nset "TOC_OCRA_CONFIG=${configPath}"\r\nset "ELECTRON_RUN_AS_NODE=1"\r\n"${process.execPath}" "${agentEntry}" run\r\n`, { mode: 0o600 })
128
149
  await chmod(launcher, 0o700).catch(() => undefined)
129
150
  command('schtasks.exe', ['/Create', '/F', '/TN', SERVICE_NAME, '/SC', 'ONLOGON', '/RL', 'LIMITED', '/TR', `"${launcher}"`])
130
151
  command('schtasks.exe', ['/Run', '/TN', SERVICE_NAME])
@@ -132,10 +153,68 @@ async function manageWindowsTask(mode) {
132
153
  }
133
154
 
134
155
  function command(executable, args, allowFailure = false) {
135
- const result = spawnSync(executable, args, { stdio: 'inherit', shell: false })
156
+ const result = spawnSync(executable, args, { stdio: allowFailure ? 'ignore' : 'inherit', shell: false })
136
157
  if (!allowFailure && result.status !== 0) fail(`${executable} failed with exit code ${result.status ?? 'unknown'}`)
137
158
  }
138
159
 
160
+ async function retireLegacyChat(domain) {
161
+ const label = `${LAUNCHD_LABEL}.cli-chat`
162
+ command('launchctl', ['bootout', `${domain}/${label}`], true)
163
+ await unlink(join(homedir(), 'Library', 'LaunchAgents', `${label}.plist`)).catch(ignoreMissing)
164
+ }
165
+
166
+ async function localEndpoint() {
167
+ const config = JSON.parse(await readFile(configPath, 'utf8').catch(error => {
168
+ if (error.code === 'ENOENT') return '{}'
169
+ throw error
170
+ }))
171
+ const host = process.env.TOC_OCRA_HEALTH_HOST ?? config.healthHost ?? '127.0.0.1'
172
+ return { host: host === '0.0.0.0' || host === '::' ? '127.0.0.1' : host, port: Number(process.env.TOC_OCRA_HEALTH_PORT ?? config.healthPort ?? 17339) }
173
+ }
174
+
175
+ async function ensureIdle() {
176
+ const endpoint = await localEndpoint()
177
+ const host = endpoint.host.includes(':') ? `[${endpoint.host}]` : endpoint.host
178
+ const state = await fetch(`http://${host}:${endpoint.port}/health`, { signal: AbortSignal.timeout(2_000) })
179
+ .then(response => response.ok ? response.json() : undefined).catch(() => undefined)
180
+ if (state?.activeSessions > 0) fail(`本机还有 ${state.activeSessions} 个任务运行,请在任务结束后重新安装或升级服务`)
181
+ // The retired worker had no health endpoint. Preserve its active children
182
+ // instead of silently cancelling a chat while merging into the main service.
183
+ const records = JSON.parse(await readFile(join(process.env.TOC_OCRA_DATA_DIR ?? defaultDataDir(), 'chat-active-runs.json'), 'utf8').catch(error => {
184
+ if (error.code === 'ENOENT') return '[]'
185
+ throw error
186
+ }))
187
+ for (const record of records) {
188
+ if (!Number.isInteger(record?.pid) || record.pid <= 1) continue
189
+ try { process.kill(record.pid, 0) }
190
+ catch (error) { if (error.code === 'ESRCH') continue; throw error }
191
+ fail('独立聊天 worker 仍有任务运行,请在聊天结束后重新安装或升级服务')
192
+ }
193
+ }
194
+
195
+ function portOpen(host, port) {
196
+ if (!port) return Promise.resolve(false)
197
+ return new Promise((resolvePort, rejectPort) => {
198
+ const socket = createConnection({ host, port })
199
+ socket.setTimeout(1_000, () => { socket.destroy(); rejectPort(new Error('等待本机服务退出超时')) })
200
+ socket.once('connect', () => { socket.destroy(); resolvePort(true) })
201
+ socket.once('error', error => {
202
+ socket.destroy()
203
+ if (error.code === 'ECONNREFUSED') resolvePort(false)
204
+ else rejectPort(error)
205
+ })
206
+ })
207
+ }
208
+
209
+ async function waitForInstanceExit() {
210
+ const endpoint = await localEndpoint()
211
+ for (let attempt = 0; attempt < 120; attempt++) {
212
+ if (!await portOpen('127.0.0.1', INSTANCE_LOCK_PORT) && !await portOpen(endpoint.host, endpoint.port)) return
213
+ await delay(500)
214
+ }
215
+ fail('现有设备代理尚未退出;若由终端或桌面启动,请先关闭该实例,再安装后台服务')
216
+ }
217
+
139
218
  function xml(value) {
140
219
  return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;')
141
220
  }