forked from ericc-ch/copilot-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmacos.ts
More file actions
253 lines (227 loc) · 6.87 KB
/
macos.ts
File metadata and controls
253 lines (227 loc) · 6.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
/* eslint-disable */
import { spawnSync } from "node:child_process"
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import {
APP_DIR,
ERR_FILE,
LOG_FILE,
buildDirectCommand,
buildNpxCommand,
launcherPath,
} from "./shared"
import type { DaemonInstallArgs } from "./shared"
const LAUNCHD_LABEL = "com.xc-copilot-api"
function plistPath(): string {
return path.join(
os.homedir(),
"Library",
"LaunchAgents",
`${LAUNCHD_LABEL}.plist`,
)
}
export function installMacOS(args: DaemonInstallArgs): void {
const plist = plistPath()
const launcher = launcherPath()
fs.mkdirSync(APP_DIR, { recursive: true })
fs.mkdirSync(path.dirname(plist), { recursive: true })
const execCmd = args.npx
? buildNpxCommand(args)
: buildDirectCommand(args)
// Launcher script sources login shell so PATH includes nvm, homebrew, etc.
fs.writeFileSync(
launcher,
[
"#!/bin/zsh -l",
'[ -f "$HOME/.zshrc" ] && source "$HOME/.zshrc"',
`exec ${execCmd}`,
"",
].join("\n"),
)
fs.chmodSync(launcher, 0o755)
const plistContent = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>${LAUNCHD_LABEL}</string>
<key>ProgramArguments</key>
<array>
<string>${launcher}</string>
</array>
<key>WorkingDirectory</key>
<string>${os.homedir()}</string>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardOutPath</key>
<string>${LOG_FILE}</string>
<key>StandardErrorPath</key>
<string>${ERR_FILE}</string>
</dict>
</plist>
`
fs.writeFileSync(plist, plistContent)
console.log(`Installed LaunchAgent '${LAUNCHD_LABEL}'`)
console.log(` Plist: ${plist}`)
console.log(` Launcher: ${launcher}`)
console.log(` Log: ${LOG_FILE}`)
console.log(` Mode: ${args.npx ? "npx (auto-update)" : "direct"}`)
console.log(` Start: xc-copilot-api-daemon restart`)
}
export function uninstallMacOS(): void {
stopMacOS()
const plist = plistPath()
if (fs.existsSync(plist)) {
fs.unlinkSync(plist)
console.log(`Removed LaunchAgent plist: ${plist}`)
}
const launcher = launcherPath()
if (fs.existsSync(launcher)) {
fs.unlinkSync(launcher)
console.log(`Removed launcher: ${launcher}`)
}
console.log(`Uninstalled daemon '${LAUNCHD_LABEL}'`)
}
export function stopMacOS(): boolean {
const domain = `gui/${process.getuid?.() ?? 501}`
const job = `${domain}/${LAUNCHD_LABEL}`
const result = spawnSync("launchctl", ["bootout", job], {
encoding: "utf-8",
timeout: 15000,
})
if (result.status === 0) {
console.log(`Stopped LaunchAgent '${LAUNCHD_LABEL}'`)
return true
}
const detail = (result.stderr || result.stdout || "").toLowerCase()
if (detail.includes("not find") || detail.includes("no such")) {
return true // not running
}
return false
}
export function startMacOS(): boolean {
const plist = plistPath()
if (!fs.existsSync(plist)) {
console.error(`LaunchAgent plist not found: ${plist}`)
console.error("Run 'xc-copilot-api-daemon install' first.")
return false
}
const domain = `gui/${process.getuid?.() ?? 501}`
const job = `${domain}/${LAUNCHD_LABEL}`
// Bootstrap (load) the daemon
const bootstrap = spawnSync("launchctl", ["bootstrap", domain, plist], {
encoding: "utf-8",
timeout: 10000,
})
if (bootstrap.status !== 0) {
const detail = (bootstrap.stderr || bootstrap.stdout || "").toLowerCase()
if (!detail.includes("already")) {
console.error(`launchctl bootstrap failed: ${detail.trim()}`)
return false
}
}
// Kickstart -k kills existing instance and restarts
const kick = spawnSync("launchctl", ["kickstart", "-k", job], {
encoding: "utf-8",
timeout: 15000,
})
if (kick.status !== 0) {
console.error(
`launchctl kickstart failed: ${(kick.stderr || kick.stdout || "").trim()}`,
)
return false
}
console.log(`Started LaunchAgent '${LAUNCHD_LABEL}'`)
return true
}
export function statusMacOS(): void {
const plist = plistPath()
if (!fs.existsSync(plist)) {
console.log("Daemon: not installed")
return
}
console.log(`Daemon: installed`)
console.log(` Plist: ${plist}`)
const launcher = launcherPath()
if (fs.existsSync(launcher)) {
const content = fs.readFileSync(launcher, "utf-8")
const execLine = content
.split("\n")
.find((l) => l.startsWith("exec "))
if (execLine) {
console.log(` Command: ${execLine.replace("exec ", "")}`)
}
}
// Check if running via launchctl
const result = spawnSync("launchctl", ["list", LAUNCHD_LABEL], {
encoding: "utf-8",
timeout: 5000,
})
if (result.status === 0) {
const output = result.stdout.trim()
// Parse PID and status from launchctl list output
const pidLine = output
.split("\n")
.find((l) => l.includes("PID") || l.match(/^\s*"PID"/))
const lastExitLine = output
.split("\n")
.find((l) => l.includes("LastExitStatus"))
// launchctl list <label> outputs key-value pairs
const pidMatch = output.match(/"PID"\s*=\s*(\d+)/)
const exitMatch = output.match(/"LastExitStatus"\s*=\s*(\d+)/)
if (pidMatch) {
console.log(` Status: running (PID ${pidMatch[1]})`)
} else {
console.log(` Status: not running`)
}
if (exitMatch) {
console.log(` Last exit: ${exitMatch[1]}`)
}
if (pidLine) void pidLine // suppress unused
if (lastExitLine) void lastExitLine // suppress unused
} else {
console.log(" Status: not loaded")
}
// Show recent log
if (fs.existsSync(LOG_FILE)) {
const stat = fs.statSync(LOG_FILE)
console.log(
` Log: ${LOG_FILE} (${(stat.size / 1024).toFixed(1)} KB)`,
)
}
}
export interface CopilotJob {
label: string
pid: string | null
plistPath: string | null
}
export function findAllCopilotLaunchdJobs(): CopilotJob[] {
const result = spawnSync("launchctl", ["list"], {
encoding: "utf-8",
timeout: 5000,
})
if (result.status !== 0) return []
const jobs: CopilotJob[] = []
for (const line of result.stdout.split("\n")) {
if (!line.toLowerCase().includes("copilot")) continue
const parts = line.trim().split(/\s+/)
if (parts.length < 3) continue
const pid = parts[0] === "-" ? null : parts[0]
const label = parts[2]
const plist = path.join(
os.homedir(),
"Library",
"LaunchAgents",
`${label}.plist`,
)
jobs.push({
label,
pid,
plistPath: fs.existsSync(plist) ? plist : null,
})
}
return jobs
}