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/service.mjs
CHANGED
|
@@ -1,253 +1,253 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { existsSync } from 'node:fs'
|
|
3
|
-
import { chmod, mkdir, readFile, unlink, writeFile } from 'node:fs/promises'
|
|
4
|
-
import { createConnection } from 'node:net'
|
|
5
|
-
import { homedir } from 'node:os'
|
|
6
|
-
import { dirname, join, resolve } from 'node:path'
|
|
7
|
-
import { fileURLToPath } from 'node:url'
|
|
8
|
-
import { spawnSync } from 'node:child_process'
|
|
9
|
-
import { setTimeout as delay } from 'node:timers/promises'
|
|
10
|
-
|
|
11
|
-
const SERVICE_NAME = 'toc-ocra'
|
|
12
|
-
const LAUNCHD_LABEL = 'top.stormapex.toc-ocra'
|
|
13
|
-
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
|
|
14
|
-
const bundledEntry = join(root, 'dist', 'cli', 'cli.mjs')
|
|
15
|
-
const agentEntry = existsSync(bundledEntry) ? bundledEntry : join(root, 'dist', 'src', 'index.js')
|
|
16
|
-
const action = process.argv[2]
|
|
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
|
|
20
|
-
|
|
21
|
-
if (action !== 'install' && action !== 'uninstall') usage()
|
|
22
|
-
if (action === 'install' && !existsSync(agentEntry)) fail('Build output is missing. Run npm run build first.')
|
|
23
|
-
// The service may start unenrolled: it then waits to be paired from the plugin.
|
|
24
|
-
if (action === 'install') await ensureIdle()
|
|
25
|
-
|
|
26
|
-
if (process.platform === 'darwin') await manageLaunchd(action)
|
|
27
|
-
else if (process.platform === 'linux') await manageSystemd(action)
|
|
28
|
-
else if (process.platform === 'win32') await manageWindowsTask(action)
|
|
29
|
-
else fail(`Unsupported platform: ${process.platform}`)
|
|
30
|
-
|
|
31
|
-
function readOption(name) {
|
|
32
|
-
const index = process.argv.indexOf(name)
|
|
33
|
-
return index >= 0 ? process.argv[index + 1] : undefined
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
function defaultDataDir() {
|
|
37
|
-
if (process.platform === 'darwin') return join(homedir(), 'Library', 'Application Support', SERVICE_NAME)
|
|
38
|
-
if (process.platform === 'win32') return join(process.env.APPDATA ?? homedir(), SERVICE_NAME)
|
|
39
|
-
return join(process.env.XDG_STATE_HOME ?? join(homedir(), '.local', 'state'), SERVICE_NAME)
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function defaultConfigPath() {
|
|
43
|
-
return join(defaultDataDir(), 'config.json')
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
async function manageLaunchd(mode) {
|
|
47
|
-
const target = join(homedir(), 'Library', 'LaunchAgents', `${LAUNCHD_LABEL}.plist`)
|
|
48
|
-
const domain = `gui/${process.getuid()}`
|
|
49
|
-
if (mode === 'uninstall') {
|
|
50
|
-
await retireLegacyChat(domain)
|
|
51
|
-
command('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], true)
|
|
52
|
-
await unlink(target).catch(ignoreMissing)
|
|
53
|
-
process.stdout.write(`Removed ${target}\n`)
|
|
54
|
-
return
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
await retireLegacyChat(domain)
|
|
58
|
-
command('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], true)
|
|
59
|
-
await waitForInstanceExit()
|
|
60
|
-
const logDir = join(defaultDataDir(), 'logs')
|
|
61
|
-
const path = servicePath()
|
|
62
|
-
await mkdir(dirname(target), { recursive: true })
|
|
63
|
-
await mkdir(logDir, { recursive: true, mode: 0o700 })
|
|
64
|
-
const plist = `<?xml version="1.0" encoding="UTF-8"?>
|
|
65
|
-
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
66
|
-
<plist version="1.0"><dict>
|
|
67
|
-
<key>Label</key><string>${LAUNCHD_LABEL}</string>
|
|
68
|
-
<key>ProgramArguments</key><array>
|
|
69
|
-
<string>${xml(process.execPath)}</string><string>${xml(agentEntry)}</string><string>run</string>
|
|
70
|
-
</array>
|
|
71
|
-
<key>EnvironmentVariables</key><dict>
|
|
72
|
-
<key>TOC_OCRA_CONFIG</key><string>${xml(configPath)}</string>
|
|
73
|
-
<key>ELECTRON_RUN_AS_NODE</key><string>1</string>
|
|
74
|
-
<key>HOME</key><string>${xml(homedir())}</string>
|
|
75
|
-
<key>SHELL</key><string>${xml(process.env.SHELL ?? '/bin/zsh')}</string>
|
|
76
|
-
<key>PATH</key><string>${xml(path)}</string>
|
|
77
|
-
</dict>
|
|
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>
|
|
82
|
-
<key>StandardOutPath</key><string>${xml(join(logDir, 'service.stdout.log'))}</string>
|
|
83
|
-
<key>StandardErrorPath</key><string>${xml(join(logDir, 'service.stderr.log'))}</string>
|
|
84
|
-
</dict></plist>
|
|
85
|
-
`
|
|
86
|
-
await writeFile(target, plist, { mode: 0o600 })
|
|
87
|
-
command('launchctl', ['enable', `${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])
|
|
91
|
-
process.stdout.write(`Installed ${target}\n`)
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
async function manageSystemd(mode) {
|
|
95
|
-
const target = join(homedir(), '.config', 'systemd', 'user', `${SERVICE_NAME}.service`)
|
|
96
|
-
if (mode === 'uninstall') {
|
|
97
|
-
command('systemctl', ['--user', 'disable', '--now', SERVICE_NAME], true)
|
|
98
|
-
await unlink(target).catch(ignoreMissing)
|
|
99
|
-
command('systemctl', ['--user', 'daemon-reload'])
|
|
100
|
-
process.stdout.write(`Removed ${target}\n`)
|
|
101
|
-
return
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
command('systemctl', ['--user', 'stop', SERVICE_NAME], true)
|
|
105
|
-
await waitForInstanceExit()
|
|
106
|
-
await mkdir(dirname(target), { recursive: true })
|
|
107
|
-
const unit = `[Unit]
|
|
108
|
-
Description=echo_cli_agent TaskMCP device agent
|
|
109
|
-
After=network-online.target
|
|
110
|
-
Wants=network-online.target
|
|
111
|
-
|
|
112
|
-
[Service]
|
|
113
|
-
Type=simple
|
|
114
|
-
Environment=TOC_OCRA_CONFIG=${systemdQuote(configPath)}
|
|
115
|
-
Environment=ELECTRON_RUN_AS_NODE=1
|
|
116
|
-
Environment=PATH=${systemdQuote(servicePath())}
|
|
117
|
-
ExecStart=${systemdQuote(process.execPath)} ${systemdQuote(agentEntry)} run
|
|
118
|
-
Restart=on-failure
|
|
119
|
-
RestartSec=3
|
|
120
|
-
TimeoutStopSec=60
|
|
121
|
-
KillMode=mixed
|
|
122
|
-
NoNewPrivileges=true
|
|
123
|
-
|
|
124
|
-
[Install]
|
|
125
|
-
WantedBy=default.target
|
|
126
|
-
`
|
|
127
|
-
await writeFile(target, unit, { mode: 0o600 })
|
|
128
|
-
command('systemctl', ['--user', 'daemon-reload'])
|
|
129
|
-
command('systemctl', ['--user', 'enable', '--now', SERVICE_NAME])
|
|
130
|
-
process.stdout.write(`Installed ${target}\n`)
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
async function manageWindowsTask(mode) {
|
|
134
|
-
const launcher = join(defaultDataDir(), 'run-agent.cmd')
|
|
135
|
-
if (mode === 'uninstall') {
|
|
136
|
-
command('schtasks.exe', ['/Delete', '/F', '/TN', SERVICE_NAME], true)
|
|
137
|
-
await unlink(launcher).catch(ignoreMissing)
|
|
138
|
-
process.stdout.write(`Removed scheduled task ${SERVICE_NAME}\n`)
|
|
139
|
-
return
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
command('schtasks.exe', ['/End', '/TN', SERVICE_NAME], true)
|
|
143
|
-
await waitForInstanceExit()
|
|
144
|
-
rejectCmdMetacharacters(configPath)
|
|
145
|
-
rejectCmdMetacharacters(process.execPath)
|
|
146
|
-
rejectCmdMetacharacters(agentEntry)
|
|
147
|
-
await mkdir(dirname(launcher), { recursive: true })
|
|
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 })
|
|
149
|
-
await chmod(launcher, 0o700).catch(() => undefined)
|
|
150
|
-
command('schtasks.exe', ['/Create', '/F', '/TN', SERVICE_NAME, '/SC', 'ONLOGON', '/RL', 'LIMITED', '/TR', `"${launcher}"`])
|
|
151
|
-
command('schtasks.exe', ['/Run', '/TN', SERVICE_NAME])
|
|
152
|
-
process.stdout.write(`Installed scheduled task ${SERVICE_NAME}\n`)
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
function command(executable, args, allowFailure = false) {
|
|
156
|
-
const result = spawnSync(executable, args, { stdio: allowFailure ? 'ignore' : 'inherit', shell: false })
|
|
157
|
-
if (!allowFailure && result.status !== 0) fail(`${executable} failed with exit code ${result.status ?? 'unknown'}`)
|
|
158
|
-
}
|
|
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
|
-
|
|
218
|
-
function xml(value) {
|
|
219
|
-
return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"')
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
function servicePath() {
|
|
223
|
-
const entries = [
|
|
224
|
-
dirname(process.execPath),
|
|
225
|
-
join(homedir(), '.local', 'bin'),
|
|
226
|
-
'/opt/homebrew/bin',
|
|
227
|
-
'/usr/local/bin',
|
|
228
|
-
process.env.PATH ?? ''
|
|
229
|
-
]
|
|
230
|
-
return [...new Set(entries.flatMap((entry) => entry.split(':')).filter(Boolean))].join(':')
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
function systemdQuote(value) {
|
|
234
|
-
return `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('%', '%%')}"`
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
function rejectCmdMetacharacters(value) {
|
|
238
|
-
if (/[\r\n&|<>^]/.test(value)) fail('Windows service paths contain unsupported command characters')
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
function ignoreMissing(error) {
|
|
242
|
-
if (error?.code !== 'ENOENT') throw error
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
function usage() {
|
|
246
|
-
process.stderr.write('Usage: node scripts/service.mjs <install|uninstall> [--config /path/config.json]\n')
|
|
247
|
-
process.exit(2)
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
function fail(message) {
|
|
251
|
-
process.stderr.write(`${message}\n`)
|
|
252
|
-
process.exit(1)
|
|
253
|
-
}
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { existsSync } from 'node:fs'
|
|
3
|
+
import { chmod, mkdir, readFile, unlink, writeFile } from 'node:fs/promises'
|
|
4
|
+
import { createConnection } from 'node:net'
|
|
5
|
+
import { homedir } from 'node:os'
|
|
6
|
+
import { dirname, join, resolve } from 'node:path'
|
|
7
|
+
import { fileURLToPath } from 'node:url'
|
|
8
|
+
import { spawnSync } from 'node:child_process'
|
|
9
|
+
import { setTimeout as delay } from 'node:timers/promises'
|
|
10
|
+
|
|
11
|
+
const SERVICE_NAME = 'toc-ocra'
|
|
12
|
+
const LAUNCHD_LABEL = 'top.stormapex.toc-ocra'
|
|
13
|
+
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
|
|
14
|
+
const bundledEntry = join(root, 'dist', 'cli', 'cli.mjs')
|
|
15
|
+
const agentEntry = existsSync(bundledEntry) ? bundledEntry : join(root, 'dist', 'src', 'index.js')
|
|
16
|
+
const action = process.argv[2]
|
|
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
|
|
20
|
+
|
|
21
|
+
if (action !== 'install' && action !== 'uninstall') usage()
|
|
22
|
+
if (action === 'install' && !existsSync(agentEntry)) fail('Build output is missing. Run npm run build first.')
|
|
23
|
+
// The service may start unenrolled: it then waits to be paired from the plugin.
|
|
24
|
+
if (action === 'install') await ensureIdle()
|
|
25
|
+
|
|
26
|
+
if (process.platform === 'darwin') await manageLaunchd(action)
|
|
27
|
+
else if (process.platform === 'linux') await manageSystemd(action)
|
|
28
|
+
else if (process.platform === 'win32') await manageWindowsTask(action)
|
|
29
|
+
else fail(`Unsupported platform: ${process.platform}`)
|
|
30
|
+
|
|
31
|
+
function readOption(name) {
|
|
32
|
+
const index = process.argv.indexOf(name)
|
|
33
|
+
return index >= 0 ? process.argv[index + 1] : undefined
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function defaultDataDir() {
|
|
37
|
+
if (process.platform === 'darwin') return join(homedir(), 'Library', 'Application Support', SERVICE_NAME)
|
|
38
|
+
if (process.platform === 'win32') return join(process.env.APPDATA ?? homedir(), SERVICE_NAME)
|
|
39
|
+
return join(process.env.XDG_STATE_HOME ?? join(homedir(), '.local', 'state'), SERVICE_NAME)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function defaultConfigPath() {
|
|
43
|
+
return join(defaultDataDir(), 'config.json')
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function manageLaunchd(mode) {
|
|
47
|
+
const target = join(homedir(), 'Library', 'LaunchAgents', `${LAUNCHD_LABEL}.plist`)
|
|
48
|
+
const domain = `gui/${process.getuid()}`
|
|
49
|
+
if (mode === 'uninstall') {
|
|
50
|
+
await retireLegacyChat(domain)
|
|
51
|
+
command('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], true)
|
|
52
|
+
await unlink(target).catch(ignoreMissing)
|
|
53
|
+
process.stdout.write(`Removed ${target}\n`)
|
|
54
|
+
return
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
await retireLegacyChat(domain)
|
|
58
|
+
command('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], true)
|
|
59
|
+
await waitForInstanceExit()
|
|
60
|
+
const logDir = join(defaultDataDir(), 'logs')
|
|
61
|
+
const path = servicePath()
|
|
62
|
+
await mkdir(dirname(target), { recursive: true })
|
|
63
|
+
await mkdir(logDir, { recursive: true, mode: 0o700 })
|
|
64
|
+
const plist = `<?xml version="1.0" encoding="UTF-8"?>
|
|
65
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
66
|
+
<plist version="1.0"><dict>
|
|
67
|
+
<key>Label</key><string>${LAUNCHD_LABEL}</string>
|
|
68
|
+
<key>ProgramArguments</key><array>
|
|
69
|
+
<string>${xml(process.execPath)}</string><string>${xml(agentEntry)}</string><string>run</string>
|
|
70
|
+
</array>
|
|
71
|
+
<key>EnvironmentVariables</key><dict>
|
|
72
|
+
<key>TOC_OCRA_CONFIG</key><string>${xml(configPath)}</string>
|
|
73
|
+
<key>ELECTRON_RUN_AS_NODE</key><string>1</string>
|
|
74
|
+
<key>HOME</key><string>${xml(homedir())}</string>
|
|
75
|
+
<key>SHELL</key><string>${xml(process.env.SHELL ?? '/bin/zsh')}</string>
|
|
76
|
+
<key>PATH</key><string>${xml(path)}</string>
|
|
77
|
+
</dict>
|
|
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>
|
|
82
|
+
<key>StandardOutPath</key><string>${xml(join(logDir, 'service.stdout.log'))}</string>
|
|
83
|
+
<key>StandardErrorPath</key><string>${xml(join(logDir, 'service.stderr.log'))}</string>
|
|
84
|
+
</dict></plist>
|
|
85
|
+
`
|
|
86
|
+
await writeFile(target, plist, { mode: 0o600 })
|
|
87
|
+
command('launchctl', ['enable', `${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])
|
|
91
|
+
process.stdout.write(`Installed ${target}\n`)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function manageSystemd(mode) {
|
|
95
|
+
const target = join(homedir(), '.config', 'systemd', 'user', `${SERVICE_NAME}.service`)
|
|
96
|
+
if (mode === 'uninstall') {
|
|
97
|
+
command('systemctl', ['--user', 'disable', '--now', SERVICE_NAME], true)
|
|
98
|
+
await unlink(target).catch(ignoreMissing)
|
|
99
|
+
command('systemctl', ['--user', 'daemon-reload'])
|
|
100
|
+
process.stdout.write(`Removed ${target}\n`)
|
|
101
|
+
return
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
command('systemctl', ['--user', 'stop', SERVICE_NAME], true)
|
|
105
|
+
await waitForInstanceExit()
|
|
106
|
+
await mkdir(dirname(target), { recursive: true })
|
|
107
|
+
const unit = `[Unit]
|
|
108
|
+
Description=echo_cli_agent TaskMCP device agent
|
|
109
|
+
After=network-online.target
|
|
110
|
+
Wants=network-online.target
|
|
111
|
+
|
|
112
|
+
[Service]
|
|
113
|
+
Type=simple
|
|
114
|
+
Environment=TOC_OCRA_CONFIG=${systemdQuote(configPath)}
|
|
115
|
+
Environment=ELECTRON_RUN_AS_NODE=1
|
|
116
|
+
Environment=PATH=${systemdQuote(servicePath())}
|
|
117
|
+
ExecStart=${systemdQuote(process.execPath)} ${systemdQuote(agentEntry)} run
|
|
118
|
+
Restart=on-failure
|
|
119
|
+
RestartSec=3
|
|
120
|
+
TimeoutStopSec=60
|
|
121
|
+
KillMode=mixed
|
|
122
|
+
NoNewPrivileges=true
|
|
123
|
+
|
|
124
|
+
[Install]
|
|
125
|
+
WantedBy=default.target
|
|
126
|
+
`
|
|
127
|
+
await writeFile(target, unit, { mode: 0o600 })
|
|
128
|
+
command('systemctl', ['--user', 'daemon-reload'])
|
|
129
|
+
command('systemctl', ['--user', 'enable', '--now', SERVICE_NAME])
|
|
130
|
+
process.stdout.write(`Installed ${target}\n`)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async function manageWindowsTask(mode) {
|
|
134
|
+
const launcher = join(defaultDataDir(), 'run-agent.cmd')
|
|
135
|
+
if (mode === 'uninstall') {
|
|
136
|
+
command('schtasks.exe', ['/Delete', '/F', '/TN', SERVICE_NAME], true)
|
|
137
|
+
await unlink(launcher).catch(ignoreMissing)
|
|
138
|
+
process.stdout.write(`Removed scheduled task ${SERVICE_NAME}\n`)
|
|
139
|
+
return
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
command('schtasks.exe', ['/End', '/TN', SERVICE_NAME], true)
|
|
143
|
+
await waitForInstanceExit()
|
|
144
|
+
rejectCmdMetacharacters(configPath)
|
|
145
|
+
rejectCmdMetacharacters(process.execPath)
|
|
146
|
+
rejectCmdMetacharacters(agentEntry)
|
|
147
|
+
await mkdir(dirname(launcher), { recursive: true })
|
|
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 })
|
|
149
|
+
await chmod(launcher, 0o700).catch(() => undefined)
|
|
150
|
+
command('schtasks.exe', ['/Create', '/F', '/TN', SERVICE_NAME, '/SC', 'ONLOGON', '/RL', 'LIMITED', '/TR', `"${launcher}"`])
|
|
151
|
+
command('schtasks.exe', ['/Run', '/TN', SERVICE_NAME])
|
|
152
|
+
process.stdout.write(`Installed scheduled task ${SERVICE_NAME}\n`)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function command(executable, args, allowFailure = false) {
|
|
156
|
+
const result = spawnSync(executable, args, { stdio: allowFailure ? 'ignore' : 'inherit', shell: false })
|
|
157
|
+
if (!allowFailure && result.status !== 0) fail(`${executable} failed with exit code ${result.status ?? 'unknown'}`)
|
|
158
|
+
}
|
|
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
|
+
|
|
218
|
+
function xml(value) {
|
|
219
|
+
return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"')
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function servicePath() {
|
|
223
|
+
const entries = [
|
|
224
|
+
dirname(process.execPath),
|
|
225
|
+
join(homedir(), '.local', 'bin'),
|
|
226
|
+
'/opt/homebrew/bin',
|
|
227
|
+
'/usr/local/bin',
|
|
228
|
+
process.env.PATH ?? ''
|
|
229
|
+
]
|
|
230
|
+
return [...new Set(entries.flatMap((entry) => entry.split(':')).filter(Boolean))].join(':')
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function systemdQuote(value) {
|
|
234
|
+
return `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('%', '%%')}"`
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function rejectCmdMetacharacters(value) {
|
|
238
|
+
if (/[\r\n&|<>^]/.test(value)) fail('Windows service paths contain unsupported command characters')
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function ignoreMissing(error) {
|
|
242
|
+
if (error?.code !== 'ENOENT') throw error
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function usage() {
|
|
246
|
+
process.stderr.write('Usage: node scripts/service.mjs <install|uninstall> [--config /path/config.json]\n')
|
|
247
|
+
process.exit(2)
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function fail(message) {
|
|
251
|
+
process.stderr.write(`${message}\n`)
|
|
252
|
+
process.exit(1)
|
|
253
|
+
}
|