(
overrides: Partial<LaunchdManagerDeps> = {},
)
| 55 | |
| 56 | |
| 57 | export function createLaunchdManager( |
| 58 | overrides: Partial<LaunchdManagerDeps> = {}, |
| 59 | ): ServiceManager { |
| 60 | const deps: LaunchdManagerDeps = { ...DEFAULT_DEPS, ...overrides }; |
| 61 | |
| 62 | async function install(args: InstallArgs): Promise<InstallResult> { |
| 63 | const plistPath = deps.plistPath(); |
| 64 | const logPath = deps.logPath(); |
| 65 | const program = deps.resolveProgram(); |
| 66 | const plan = buildInstallPlan({ ...args, program, logPath }); |
| 67 | |
| 68 | const alreadyInstalled = existsSync(plistPath); |
| 69 | if (alreadyInstalled && args.force !== true) { |
| 70 | return { |
| 71 | status: 'already-installed', |
| 72 | message: `LaunchAgent already installed at ${plistPath}. Rerun with --force to replace it.`, |
| 73 | plistPath, |
| 74 | }; |
| 75 | } |
| 76 | |
| 77 | if (alreadyInstalled) { |
| 78 | |
| 79 | await bestEffortBootout(deps); |
| 80 | } |
| 81 | |
| 82 | writePlist(plistPath, plan, logPath); |
| 83 | writeInstallPlan(plan); |
| 84 | |
| 85 | const bootstrap = await deps.execLaunchctl(['bootstrap', deps.guiDomain(), plistPath]); |
| 86 | if (bootstrap.code !== 0 && !isAlreadyLoaded(bootstrap)) { |
| 87 | throw new Error( |
| 88 | `launchctl bootstrap failed (code ${bootstrap.code}): ${detail(bootstrap) ?? 'unknown error'}`, |
| 89 | ); |
| 90 | } |
| 91 | |
| 92 | return { |
| 93 | status: alreadyInstalled ? 'replaced' : 'installed', |
| 94 | message: `Kimi server LaunchAgent ${alreadyInstalled ? 'replaced' : 'installed'} at ${plistPath} (port ${plan.port}).`, |
| 95 | plistPath, |
| 96 | }; |
| 97 | } |
| 98 | |
| 99 | async function uninstall(): Promise<LifecycleResult> { |
| 100 | const plistPath = deps.plistPath(); |
| 101 | const installed = existsSync(plistPath); |
| 102 | if (!installed) { |
| 103 | deleteInstallPlan(); |
| 104 | return { ok: true, message: 'LaunchAgent was not installed; nothing to remove.' }; |
| 105 | } |
| 106 | const bootout = await deps.execLaunchctl([ |
| 107 | 'bootout', |
| 108 | `${deps.guiDomain()}/${KIMI_SERVER_LABEL}`, |
| 109 | ]); |
| 110 | |
| 111 | void bootout; |
| 112 | try { |
| 113 | rmSync(plistPath, { force: true }); |
| 114 | } catch (error) { |
no outgoing calls
no test coverage detected