@anhlp/alp-client 0.0.0-stage → 0.0.1-beta.10
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 +202 -0
- package/NOTICE +7 -0
- package/README.md +45 -2
- package/dist/acp-probe.d.ts +45 -0
- package/dist/acp-probe.js +46 -0
- package/dist/antigravity-probe.d.ts +33 -0
- package/dist/antigravity-probe.js +101 -0
- package/dist/command.d.ts +5 -0
- package/dist/command.js +35 -0
- package/dist/doctor.d.ts +21 -0
- package/dist/doctor.js +850 -0
- package/dist/index.d.ts +216 -0
- package/dist/index.js +702 -0
- package/dist/integration-lock.d.ts +37 -0
- package/dist/integration-lock.js +199 -0
- package/dist/ipc.d.ts +42 -0
- package/dist/ipc.js +69 -0
- package/dist/library-test.d.ts +94 -0
- package/dist/library-test.js +37 -0
- package/dist/mcp-probe.d.ts +24 -0
- package/dist/mcp-probe.js +147 -0
- package/dist/portable.d.ts +20 -0
- package/dist/portable.js +36 -0
- package/dist/prompt.d.ts +32 -0
- package/dist/prompt.js +59 -0
- package/dist/render.d.ts +6 -0
- package/dist/render.js +123 -0
- package/dist/rpc/client.d.ts +82 -0
- package/dist/rpc/client.js +292 -0
- package/dist/rpc/errors.d.ts +42 -0
- package/dist/rpc/errors.js +34 -0
- package/dist/rpc/framing.d.ts +21 -0
- package/dist/rpc/framing.js +57 -0
- package/dist/rpc/handshake.d.ts +24 -0
- package/dist/rpc/handshake.js +10 -0
- package/dist/rpc/reconnect.d.ts +97 -0
- package/dist/rpc/reconnect.js +227 -0
- package/dist/rpc/registry.d.ts +227 -0
- package/dist/rpc/registry.js +223 -0
- package/dist/rpc/terminal-directory.d.ts +24 -0
- package/dist/rpc/terminal-directory.js +70 -0
- package/dist/rpc/timers.d.ts +11 -0
- package/dist/rpc/timers.js +11 -0
- package/dist/service.d.ts +50 -0
- package/dist/service.js +145 -0
- package/dist/setup.d.ts +8 -0
- package/dist/setup.js +273 -0
- package/dist/supervise.d.ts +14 -0
- package/dist/supervise.js +91 -0
- package/dist/websocket.d.ts +51 -0
- package/dist/websocket.js +190 -0
- package/package.json +174 -4
- package/src/acp-probe.js +53 -0
- package/src/antigravity-probe.js +113 -0
- package/src/command.js +20 -0
- package/src/doctor.d.ts +21 -0
- package/src/doctor.js +912 -0
- package/src/index.js +813 -0
- package/src/integration-lock.js +203 -0
- package/src/ipc.js +92 -0
- package/src/library-test.js +41 -0
- package/src/mcp-probe.js +118 -0
- package/src/portable.js +30 -0
- package/src/prompt.js +64 -0
- package/src/render.js +139 -0
- package/src/rpc/client.js +296 -0
- package/src/rpc/errors.js +54 -0
- package/src/rpc/framing.js +61 -0
- package/src/rpc/handshake.js +21 -0
- package/src/rpc/reconnect.js +226 -0
- package/src/rpc/registry.js +229 -0
- package/src/rpc/terminal-directory.js +61 -0
- package/src/rpc/timers.js +16 -0
- package/src/service.js +158 -0
- package/src/setup.js +316 -0
- package/src/supervise.d.ts +14 -0
- package/src/supervise.js +97 -0
- package/src/websocket.js +259 -0
package/src/service.js
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { runCommand } from './command.js';
|
|
6
|
+
import { entryCommand, stablePath } from '@anhlp/alp-core/packaged';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* alpd as a user service (ALPD §37): a LaunchAgent on macOS, a systemd user unit on
|
|
10
|
+
* Linux. The service manager starts alpd at login and starts it again after a crash;
|
|
11
|
+
* a clean stop (`alp daemon stop`, exit 0) stays stopped until `alp daemon start`.
|
|
12
|
+
* Paths can be redirected for tests: ALP_SERVICE_DIR for the definition's directory,
|
|
13
|
+
* ALP_LAUNCHCTL and ALP_SYSTEMCTL for the managers.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** Variables alpd reads, carried into the service when the installing shell sets them. */
|
|
17
|
+
const CARRIED = ['ALP_RUN_LOG_DIR', 'ALP_CODEX_BIN', 'ALP_CLAUDE_BIN', 'ALP_ANTIGRAVITY_BIN', 'ALP_GH_BIN'];
|
|
18
|
+
|
|
19
|
+
const escapeXml = value => value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
20
|
+
const quoteUnit = value => `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Where and how alpd for `home` is defined as a service on `platform`, or undefined
|
|
24
|
+
* where ALP has no service support. Each ALP_HOME gets its own service.
|
|
25
|
+
*/
|
|
26
|
+
export function serviceFor({ home, env = process.env, platform = process.platform, uid = process.getuid?.() ?? 0 }) {
|
|
27
|
+
const custom = path.resolve(home) !== path.join(os.homedir(), '.alp');
|
|
28
|
+
const suffix = custom ? createHash('sha256').update(path.resolve(home)).digest('hex').slice(0, 8) : '';
|
|
29
|
+
if (platform === 'darwin') {
|
|
30
|
+
const label = `com.alp.alpd${suffix ? `.${suffix}` : ''}`;
|
|
31
|
+
const directory = env.ALP_SERVICE_DIR || path.join(os.homedir(), 'Library', 'LaunchAgents');
|
|
32
|
+
const launchctl = env.ALP_LAUNCHCTL || 'launchctl';
|
|
33
|
+
const target = `gui/${uid}/${label}`;
|
|
34
|
+
const file = path.join(directory, `${label}.plist`);
|
|
35
|
+
return {
|
|
36
|
+
kind: 'launchd', name: label, file,
|
|
37
|
+
install: [[launchctl, ['bootout', target], { ignore: true }], [launchctl, ['bootstrap', `gui/${uid}`, file]]],
|
|
38
|
+
start: [[launchctl, ['kickstart', target]]],
|
|
39
|
+
uninstall: [[launchctl, ['bootout', target], { ignore: true }]],
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
if (platform === 'linux') {
|
|
43
|
+
const name = `alpd${suffix ? `-${suffix}` : ''}`;
|
|
44
|
+
const directory = env.ALP_SERVICE_DIR || path.join(env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'systemd', 'user');
|
|
45
|
+
const systemctl = env.ALP_SYSTEMCTL || 'systemctl';
|
|
46
|
+
return {
|
|
47
|
+
kind: 'systemd', name, file: path.join(directory, `${name}.service`),
|
|
48
|
+
install: [[systemctl, ['--user', 'daemon-reload']], [systemctl, ['--user', 'enable', '--now', `${name}.service`]]],
|
|
49
|
+
start: [[systemctl, ['--user', 'start', `${name}.service`]]],
|
|
50
|
+
uninstall: [[systemctl, ['--user', 'disable', '--now', `${name}.service`], { ignore: true }]],
|
|
51
|
+
afterUninstall: [[systemctl, ['--user', 'daemon-reload'], { ignore: true }]],
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The service definition that runs `entry` (alpd.js with `execPath`, the native alpd, or an `alp` command) for `home`. */
|
|
58
|
+
export function serviceDefinition(service, { home, entry, execPath = process.execPath, env = process.env }) {
|
|
59
|
+
const variables = { ALP_HOME: path.resolve(home), PATH: env.PATH ?? '' };
|
|
60
|
+
for (const name of CARRIED) if (env[name]) variables[name] = env[name];
|
|
61
|
+
// A script entry runs under execPath; an `alp` command runs `alp daemon run --service`. Inside the
|
|
62
|
+
// ALP bundle both name it through app/current, so `alp update` never leaves the service on a removed version.
|
|
63
|
+
const launch = entryCommand(stablePath(entry), 'daemon', ['--service'], stablePath(execPath));
|
|
64
|
+
const program = [launch.command, ...launch.args];
|
|
65
|
+
const fatal = path.join(path.resolve(home), 'logs', 'alpd.service.log');
|
|
66
|
+
if (service.kind === 'launchd') {
|
|
67
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
68
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
69
|
+
<plist version="1.0">
|
|
70
|
+
<dict>
|
|
71
|
+
<key>Label</key>
|
|
72
|
+
<string>${escapeXml(service.name)}</string>
|
|
73
|
+
<key>ProgramArguments</key>
|
|
74
|
+
<array>
|
|
75
|
+
${program.map(arg => ` <string>${escapeXml(arg)}</string>`).join('\n')}
|
|
76
|
+
</array>
|
|
77
|
+
<key>EnvironmentVariables</key>
|
|
78
|
+
<dict>
|
|
79
|
+
${Object.entries(variables).map(([key, value]) => ` <key>${escapeXml(key)}</key>\n <string>${escapeXml(value)}</string>`).join('\n')}
|
|
80
|
+
</dict>
|
|
81
|
+
<key>RunAtLoad</key>
|
|
82
|
+
<true/>
|
|
83
|
+
<key>KeepAlive</key>
|
|
84
|
+
<dict>
|
|
85
|
+
<key>Crashed</key>
|
|
86
|
+
<true/>
|
|
87
|
+
<key>SuccessfulExit</key>
|
|
88
|
+
<false/>
|
|
89
|
+
</dict>
|
|
90
|
+
<key>ThrottleInterval</key>
|
|
91
|
+
<integer>10</integer>
|
|
92
|
+
<key>ProcessType</key>
|
|
93
|
+
<string>Background</string>
|
|
94
|
+
<key>StandardOutPath</key>
|
|
95
|
+
<string>${escapeXml(fatal)}</string>
|
|
96
|
+
<key>StandardErrorPath</key>
|
|
97
|
+
<string>${escapeXml(fatal)}</string>
|
|
98
|
+
</dict>
|
|
99
|
+
</plist>
|
|
100
|
+
`;
|
|
101
|
+
}
|
|
102
|
+
return `[Unit]
|
|
103
|
+
Description=ALP daemon (alpd) for ${path.resolve(home)}
|
|
104
|
+
|
|
105
|
+
[Service]
|
|
106
|
+
ExecStart=${program.map(quoteUnit).join(' ')}
|
|
107
|
+
${Object.entries(variables).map(([key, value]) => `Environment=${quoteUnit(`${key}=${value}`)}`).join('\n')}
|
|
108
|
+
Restart=on-failure
|
|
109
|
+
RestartSec=10
|
|
110
|
+
StandardOutput=append:${fatal}
|
|
111
|
+
StandardError=append:${fatal}
|
|
112
|
+
|
|
113
|
+
[Install]
|
|
114
|
+
WantedBy=default.target
|
|
115
|
+
`;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** The program an installed definition runs: [node, alpd.js] or [alpd, --service] (native, t-81b0.9), or undefined when it is not installed. */
|
|
119
|
+
export async function installedProgram(service) {
|
|
120
|
+
const text = await readFile(service.file, 'utf8').catch(() => undefined);
|
|
121
|
+
if (text === undefined) return undefined;
|
|
122
|
+
if (service.kind === 'launchd') {
|
|
123
|
+
const array = text.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/)?.[1] ?? '';
|
|
124
|
+
const unescape = value => value.replace(/"/g, '"').replace(/>/g, '>').replace(/</g, '<').replace(/&/g, '&');
|
|
125
|
+
return [...array.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(match => unescape(match[1])).slice(0, 2);
|
|
126
|
+
}
|
|
127
|
+
const line = text.match(/^ExecStart=(.*)$/m)?.[1] ?? '';
|
|
128
|
+
return [...line.matchAll(/"((?:[^"\\]|\\.)*)"/g)].map(match => match[1].replace(/\\(.)/g, '$1')).slice(0, 2);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function runAll(steps, run) {
|
|
132
|
+
for (const [command, args, { ignore = false } = {}] of steps) {
|
|
133
|
+
const result = await run(command, args);
|
|
134
|
+
if (result.code !== 0 && !ignore) throw new Error(`${command} ${args.join(' ')} failed: ${(result.stderr || result.stdout).trim() || `exit ${result.code}`}`);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Writes the definition and loads it, which starts alpd. */
|
|
139
|
+
export async function installService(service, options, run = runCommand) {
|
|
140
|
+
await mkdir(path.dirname(service.file), { recursive: true });
|
|
141
|
+
await mkdir(path.join(path.resolve(options.home), 'logs'), { recursive: true, mode: 0o700 });
|
|
142
|
+
await writeFile(service.file, serviceDefinition(service, options), { mode: 0o644 });
|
|
143
|
+
await runAll(service.install, run);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Starts an installed service's alpd. */
|
|
147
|
+
export async function startService(service, run = runCommand) {
|
|
148
|
+
await runAll(service.start, run);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Unloads the service, which stops its alpd, and removes the definition; false when none was installed. */
|
|
152
|
+
export async function uninstallService(service, run = runCommand) {
|
|
153
|
+
if (await installedProgram(service) === undefined) return false;
|
|
154
|
+
await runAll(service.uninstall, run);
|
|
155
|
+
await unlink(service.file).catch(error => { if (error.code !== 'ENOENT') throw error; });
|
|
156
|
+
await runAll(service.afterUninstall ?? [], run);
|
|
157
|
+
return true;
|
|
158
|
+
}
|
package/src/setup.js
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import { copyFile, mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { parseArgs } from 'node:util';
|
|
4
|
+
import { initProject } from '@anhlp/alp-core/init';
|
|
5
|
+
import { catalogModels, useLiveModels } from '@anhlp/alp-core/models';
|
|
6
|
+
import { fitEffort, modelEfforts, profileDefaults, profileFingerprint, projectProfiles } from '@anhlp/alp-core/profiles';
|
|
7
|
+
import { BUILTIN_TEAMS, resolveTeam, teamSources } from '@anhlp/alp-core/teams';
|
|
8
|
+
import { validateSettings } from '@anhlp/alp-core/validation';
|
|
9
|
+
import { Cancelled, select, text } from './prompt.js';
|
|
10
|
+
|
|
11
|
+
const PROVIDERS = ['claude', 'codex'];
|
|
12
|
+
const PROVIDER_LABEL = { claude: 'Claude', codex: 'Codex' };
|
|
13
|
+
/** Each seat's model and effort per provider. Main runs on the preferred provider's only; peers may run on any model of an enabled provider. */
|
|
14
|
+
const DEFAULTS = {
|
|
15
|
+
main: { claude: ['claude-opus-5-5', 'high'], codex: ['gpt-6.1-sol', 'high'] },
|
|
16
|
+
worker: { claude: ['claude-opus-5-5', 'high'], codex: ['gpt-6.1-sol', 'high'] },
|
|
17
|
+
supervisor: { claude: ['claude-sonnet-5', 'medium'], codex: ['gpt-6-luna', 'medium'] },
|
|
18
|
+
oracle: { claude: ['claude-fable-5-1', 'high'], codex: ['gpt-6-astra', 'high'] },
|
|
19
|
+
};
|
|
20
|
+
const FLAGS = { main: 'model', worker: 'model', supervisor: 'supervisor', oracle: 'oracle' };
|
|
21
|
+
const SEAT_LABEL = { main: 'main', worker: 'lead, reviewer', supervisor: 'supervisor', oracle: 'oracle' };
|
|
22
|
+
const ANY_EFFORT = ['low', 'medium', 'high', 'xhigh', 'max'];
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Write Phở and Cafe's agent profiles into a project's .alp/settings.json, without installing software or calling models.
|
|
26
|
+
* Only entries ALP wrote are rewritten: the template's defaults (templateDefaults) and setup's own earlier output
|
|
27
|
+
* (its record in .alp/state/setup-profiles.json, or for a project without one, what setup writes with its default models). A profile
|
|
28
|
+
* list the user wrote, or one a team override of Phở or Cafe pins in its team.json, is kept and named. Other teams are
|
|
29
|
+
* left alone and named with the settings keys to edit: their team.json carries their author's model choices.
|
|
30
|
+
*/
|
|
31
|
+
export async function setup(args, home) {
|
|
32
|
+
// Effort fitting reads alpd's cached live catalog when there is one (t-086c); no provider is asked.
|
|
33
|
+
useLiveModels(catalogModels(home));
|
|
34
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: Object.fromEntries(
|
|
35
|
+
['runtime', 'prefer', ...PROVIDERS.flatMap(provider => Object.values(FLAGS).map(flag => `${provider}-${flag}`))].map(name => [name, { type: 'string' }]),
|
|
36
|
+
) });
|
|
37
|
+
if (positionals.length > 1) throw new Error('setup takes at most one directory');
|
|
38
|
+
const root = path.resolve(positionals[0] ?? process.cwd());
|
|
39
|
+
const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
40
|
+
try {
|
|
41
|
+
const runtime = values.runtime ?? (interactive ? await select({ message: 'Runtime', initial: 'mix', choices: [
|
|
42
|
+
{ label: 'Mix', value: 'mix', hint: 'Claude and Codex: main runs on one, the others can run on either' },
|
|
43
|
+
{ label: 'Codex only', value: 'codex' },
|
|
44
|
+
{ label: 'Claude only', value: 'claude' },
|
|
45
|
+
] }) : undefined);
|
|
46
|
+
if (runtime === undefined) throw new Error('Pass --runtime codex, claude or mix when setup is not running in a terminal');
|
|
47
|
+
if (!['codex', 'claude', 'mix'].includes(runtime)) throw new Error('--runtime must be codex, claude or mix');
|
|
48
|
+
const prefer = values.prefer ?? (runtime !== 'mix' ? runtime : interactive ? await select({ message: 'Main runs on', initial: 'claude', choices: [
|
|
49
|
+
{ label: 'Claude', value: 'claude', hint: 'Claude first for the others too' },
|
|
50
|
+
{ label: 'Codex', value: 'codex', hint: 'Codex first for the others too' },
|
|
51
|
+
] }) : 'claude');
|
|
52
|
+
if (!PROVIDERS.includes(prefer) || (runtime !== 'mix' && prefer !== runtime)) throw new Error('--prefer must be an enabled runtime');
|
|
53
|
+
// The preferred provider comes first: it is each agent's default, the other one a choice.
|
|
54
|
+
const enabled = runtime === 'mix' ? [prefer, ...PROVIDERS.filter(provider => provider !== prefer)] : [runtime];
|
|
55
|
+
for (const provider of PROVIDERS) {
|
|
56
|
+
for (const flag of Object.values(FLAGS)) {
|
|
57
|
+
if (!enabled.includes(provider) && values[`${provider}-${flag}`]) throw new Error(`--${provider}-${flag} is unavailable in ${runtime}-only mode`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const seats = seatsFor(enabled, prefer, values);
|
|
61
|
+
const peers = peersFor(enabled);
|
|
62
|
+
|
|
63
|
+
const file = path.join(root, '.alp/settings.json');
|
|
64
|
+
const settings = await readFile(file, 'utf8').then(content => {
|
|
65
|
+
try { return JSON.parse(content); } catch (error) { throw new Error(`${file} is not valid JSON: ${error.message}`); }
|
|
66
|
+
}, error => {
|
|
67
|
+
if (error.code === 'ENOENT') return undefined;
|
|
68
|
+
throw new Error(`${file}: ${error.message}`);
|
|
69
|
+
});
|
|
70
|
+
const show = () => {
|
|
71
|
+
for (const [seat, choices] of Object.entries(seats)) console.log(` ${SEAT_LABEL[seat]}: ${choices.map(describe).join(', ')}`);
|
|
72
|
+
console.log(` peer: ${peers.join(', ')} (any model: whoever assigns a peer picks its model and effort for the task)`);
|
|
73
|
+
};
|
|
74
|
+
// Checked as it is first: reading its entries' owners assumes well-formed settings.
|
|
75
|
+
if (settings) validateSettings(settings, file);
|
|
76
|
+
console.log(`Profiles for Phở and Cafe in ${file}:`);
|
|
77
|
+
show();
|
|
78
|
+
// Which existing entries are ALP's to rewrite, and which are the user's (p-47ce54f6): decided before any prompt.
|
|
79
|
+
const owners = await ownership(root, home, settings);
|
|
80
|
+
const replaced = BUILTIN_TEAMS.filter(id => Object.keys(currentTeams(settings)?.[id] ?? {}).some(name => owners.rewrites(id, name)));
|
|
81
|
+
if (replaced.length) console.log(`These replace the ${replaced.join(' and ')} profiles ALP or an earlier alp setup wrote; saving backs the file up to ${file}.bak first.`);
|
|
82
|
+
for (const line of owners.kept) console.log(line);
|
|
83
|
+
for (const line of owners.others) console.log(line);
|
|
84
|
+
if (interactive) {
|
|
85
|
+
for (;;) {
|
|
86
|
+
const next = await select({ message: 'Save these profiles?', initial: 'save', choices: [
|
|
87
|
+
{ label: 'Save', value: 'save' },
|
|
88
|
+
{ label: 'Change a model', value: 'change' },
|
|
89
|
+
{ label: 'Cancel', value: 'cancel' },
|
|
90
|
+
] });
|
|
91
|
+
if (next === 'cancel') throw new Cancelled();
|
|
92
|
+
if (next === 'save') break;
|
|
93
|
+
await change(seats, home);
|
|
94
|
+
show();
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
// Checked before anything is written: no scaffold, backup or partial file for settings that would not load.
|
|
98
|
+
validateSettings(merge(settings ?? {}, await profiles(root, home, seats, peers, settings), owners).next, file);
|
|
99
|
+
if (!settings) await initProject(root, { library: home });
|
|
100
|
+
else if (replaced.length) await copyFile(file, `${file}.bak`);
|
|
101
|
+
const written = settings ?? JSON.parse(await readFile(file, 'utf8'));
|
|
102
|
+
const { next, record } = merge(written, await profiles(root, home, seats, peers, written), owners);
|
|
103
|
+
validateSettings(next, file);
|
|
104
|
+
await writeFile(file, JSON.stringify(next, null, 2) + '\n');
|
|
105
|
+
await writeRecord(root, record, owners.newer);
|
|
106
|
+
console.log('Setup saved. New sessions in this project use these profiles; edit the file to change one agent. Run alp doctor to check that each CLI is installed and logged in.');
|
|
107
|
+
} catch (error) {
|
|
108
|
+
if (!(error instanceof Cancelled)) throw error;
|
|
109
|
+
console.log(error.message);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const describe = choice => `${choice.provider}:${choice.model}${choice.effort ? `:${choice.effort}` : ''}`;
|
|
114
|
+
|
|
115
|
+
/** Pick one seat and provider, then its model and effort. */
|
|
116
|
+
async function change(seats, home) {
|
|
117
|
+
// alpd's live catalog (t-e5ee) when it has one, else the static rows.
|
|
118
|
+
const catalog = catalogModels(home);
|
|
119
|
+
const [seat, at] = await select({ message: 'Which model?', choices: Object.entries(seats).flatMap(([seat, choices]) =>
|
|
120
|
+
choices.map((choice, at) => ({ label: `${SEAT_LABEL[seat]} · ${PROVIDER_LABEL[choice.provider]}`, value: [seat, at], hint: describe(choice) }))) });
|
|
121
|
+
const current = seats[seat][at];
|
|
122
|
+
const offered = catalog.filter(model => model.runtime === current.provider);
|
|
123
|
+
const picked = await select({ message: `${SEAT_LABEL[seat]} on ${PROVIDER_LABEL[current.provider]}`, initial: current.model, choices: [
|
|
124
|
+
...offered.map(model => ({ label: model.label, value: model.id, hint: `${model.id} · ${model.description}` })),
|
|
125
|
+
{ label: 'Other…', value: undefined, hint: 'type a model ID' },
|
|
126
|
+
] });
|
|
127
|
+
const model = picked ?? nativeModel(await text(`${PROVIDER_LABEL[current.provider]} model ID:`), current.provider, 'The model ID');
|
|
128
|
+
const efforts = catalog.find(entry => entry.runtime === current.provider && entry.id === model)?.efforts ?? modelEfforts(`${current.provider}:${model}`) ?? ANY_EFFORT;
|
|
129
|
+
const effort = efforts.length > 1 ? await select({ message: 'Effort', initial: efforts.includes(current.effort) ? current.effort : DEFAULTS[seat][current.provider][1],
|
|
130
|
+
choices: efforts.map(effort => ({ label: effort, value: effort })) }) : efforts[0];
|
|
131
|
+
seats[seat][at] = { provider: current.provider, model, ...(effort ? { effort } : {}) };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Each seat's choices for the enabled providers: main on the preferred one, the others on each. */
|
|
135
|
+
function seatsFor(enabled, prefer, values = {}) {
|
|
136
|
+
/** @type {Record<string, Array<{ provider: string, model: string, effort?: string }>>} */
|
|
137
|
+
const seats = {};
|
|
138
|
+
for (const [seat, flag] of Object.entries(FLAGS)) {
|
|
139
|
+
seats[seat] = (seat === 'main' ? [prefer] : enabled).map(provider => {
|
|
140
|
+
const option = `${provider}-${flag}`;
|
|
141
|
+
const [fallback, effort] = DEFAULTS[seat][provider];
|
|
142
|
+
const model = nativeModel(values[option] ?? fallback, provider, `--${option}`);
|
|
143
|
+
return { provider, model, effort: fitEffort(`${provider}:${model}`, effort) };
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
return seats;
|
|
147
|
+
}
|
|
148
|
+
/** Whether two { key: value } maps hold the same pairs, in any order. */
|
|
149
|
+
const sameEntries = (a, b) => JSON.stringify(Object.entries(a ?? {}).sort()) === JSON.stringify(Object.entries(b ?? {}).sort());
|
|
150
|
+
/** A peer takes any model of an enabled provider: whoever assigns it picks the model and effort. */
|
|
151
|
+
const peersFor = enabled => enabled.map(provider => `${provider}:*`);
|
|
152
|
+
const currentTeams = settings => settings && ({ ...(settings.profile ?? {}), ...(settings.team ?? {}) });
|
|
153
|
+
|
|
154
|
+
/** Each agent's profile list for one team, by its role: main, supervisor and oracle by seat, a peer on any model, the others as workers. */
|
|
155
|
+
function teamProfiles(team, seats, peers) {
|
|
156
|
+
const strings = choices => choices.map(choice => typeof choice === 'string' ? choice : describe(choice));
|
|
157
|
+
/** @type {Record<string, string[]>} */
|
|
158
|
+
const agents = {};
|
|
159
|
+
for (const [name, member] of Object.entries(team.members)) {
|
|
160
|
+
if (name !== 'oracle') agents[name] = strings(name === team.main ? seats.main : member.role === 'peer' ? peers : seats.worker);
|
|
161
|
+
}
|
|
162
|
+
if (team.supervisor) agents[team.supervisor.agent] = strings(seats.supervisor);
|
|
163
|
+
if (team.members.oracle) agents.oracle = strings(seats.oracle);
|
|
164
|
+
return agents;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Every Phở and Cafe agent's profiles, keeping each agent's own compaction setting and "/" commands (t-efa3). */
|
|
168
|
+
async function profiles(root, home, seats, peers, settings) {
|
|
169
|
+
const profile = {};
|
|
170
|
+
for (const id of BUILTIN_TEAMS) {
|
|
171
|
+
const team = await resolveTeam(root, id, { library: home });
|
|
172
|
+
const agents = {};
|
|
173
|
+
for (const [name, list] of Object.entries(teamProfiles(team, seats, peers))) {
|
|
174
|
+
const old = currentTeams(settings)?.[id]?.[name];
|
|
175
|
+
agents[name] = { profiles: list, autocompact: old?.autocompact ?? 'auto', ...(old?.commands ? { commands: old.commands } : {}) };
|
|
176
|
+
}
|
|
177
|
+
profile[id] = agents;
|
|
178
|
+
}
|
|
179
|
+
return profile;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Who owns each existing Phở and Cafe entry. setup rewrites an entry ALP wrote: one matching the template's
|
|
184
|
+
* defaults (unless a team override pins that agent's model itself), setup's record of what it wrote, or (a
|
|
185
|
+
* project set up before that record existed) what setup writes for some runtime with its default models.
|
|
186
|
+
* Anything else is the user's, and the user's own configuration is authoritative (p-47ce54f6).
|
|
187
|
+
*/
|
|
188
|
+
/**
|
|
189
|
+
* Fingerprints of the profiles alp setup last wrote, by team and agent. They live in project state, not in
|
|
190
|
+
* settings.json: validateSettings refuses an unknown top-level key, so a settings key would make an older ALP
|
|
191
|
+
* reject the file. The directory ignores itself in Git (this checkout's bookkeeping, not configuration). A record
|
|
192
|
+
* that is missing, unreadable, malformed or of another version counts as empty: setup falls back to its known
|
|
193
|
+
* defaults, and never refuses to run over it.
|
|
194
|
+
*/
|
|
195
|
+
const RECORD_VERSION = 1;
|
|
196
|
+
const recordFile = root => path.join(root, '.alp', 'state', 'setup-profiles.json');
|
|
197
|
+
async function readRecord(root) {
|
|
198
|
+
let value;
|
|
199
|
+
try { value = JSON.parse(await readFile(recordFile(root), 'utf8')); } catch { return { teams: {}, newer: false }; }
|
|
200
|
+
// A newer ALP's record is left for it, unread and unwritten.
|
|
201
|
+
if (Number.isSafeInteger(value?.version) && value.version > RECORD_VERSION) return { teams: {}, newer: true };
|
|
202
|
+
const teams = value?.version === RECORD_VERSION && value.teams && typeof value.teams === 'object' && !Array.isArray(value.teams) ? value.teams : {};
|
|
203
|
+
return { newer: false, teams: Object.fromEntries(Object.entries(teams).filter(([, agents]) => agents && typeof agents === 'object' && !Array.isArray(agents))
|
|
204
|
+
.map(([id, agents]) => [id, Object.fromEntries(Object.entries(agents).filter(([, hash]) => typeof hash === 'string' && /^[a-f0-9]{64}$/.test(hash)))])) };
|
|
205
|
+
}
|
|
206
|
+
/** Saves the record; settings are already saved, so a failure here is reported, not thrown. */
|
|
207
|
+
async function writeRecord(root, teams, newer) {
|
|
208
|
+
if (newer) return;
|
|
209
|
+
const directory = path.dirname(recordFile(root));
|
|
210
|
+
try {
|
|
211
|
+
await mkdir(directory, { recursive: true });
|
|
212
|
+
await writeFile(path.join(directory, '.gitignore'), '*\n', { flag: 'wx' }).catch(error => { if (error.code !== 'EEXIST') throw error; });
|
|
213
|
+
await writeFile(recordFile(root), JSON.stringify({ version: RECORD_VERSION, teams }, null, 2) + '\n');
|
|
214
|
+
} catch (error) {
|
|
215
|
+
console.log(`Could not save ${recordFile(root)} (${error.message}); the next alp setup recognizes these profiles by setup's defaults instead.`);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async function ownership(root, home, existing) {
|
|
220
|
+
const { teams: record, newer } = await readRecord(root);
|
|
221
|
+
// A project without settings is judged as alp init is about to write it, so a team override's pinned model counts there too.
|
|
222
|
+
const initial = existing ? undefined : await projectProfiles({ root, library: home });
|
|
223
|
+
const settings = existing ?? { team: initial, templateDefaults: profileDefaults(initial) };
|
|
224
|
+
const teams = currentTeams(settings) ?? {};
|
|
225
|
+
const file = path.join(root, '.alp/settings.json');
|
|
226
|
+
/** @type {Record<string, Record<string, string[]>>} */
|
|
227
|
+
const legacy = {};
|
|
228
|
+
/** @type {Record<string, Record<string, string>>} */
|
|
229
|
+
const pinned = {};
|
|
230
|
+
for (const id of BUILTIN_TEAMS) {
|
|
231
|
+
const team = await resolveTeam(root, id, { library: home });
|
|
232
|
+
const builtin = await resolveTeam(undefined, id, { library: '' });
|
|
233
|
+
legacy[id] = {};
|
|
234
|
+
for (const runtime of [...PROVIDERS, 'mix']) {
|
|
235
|
+
for (const prefer of runtime === 'mix' ? PROVIDERS : [runtime]) {
|
|
236
|
+
const enabled = runtime === 'mix' ? [prefer, ...PROVIDERS.filter(provider => provider !== prefer)] : [runtime];
|
|
237
|
+
for (const [name, list] of Object.entries(teamProfiles(team, seatsFor(enabled, prefer), peersFor(enabled)))) {
|
|
238
|
+
(legacy[id][name] ??= []).push(profileFingerprint({ profiles: list }, name));
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
// A library or project override of Phở or Cafe that names a member's model itself made that choice on purpose.
|
|
243
|
+
pinned[id] = {};
|
|
244
|
+
if (team.source !== 'builtin') {
|
|
245
|
+
/** What an override sets for one agent beyond the built-in's, as "model" and/or "effort X"; undefined when nothing. */
|
|
246
|
+
const choice = (own, base) => {
|
|
247
|
+
const parts = [own?.model && own.model !== base?.model ? own.model : undefined, own?.thinking && own.thinking !== base?.thinking ? `effort ${own.thinking}` : undefined].filter(Boolean);
|
|
248
|
+
return parts.length ? parts.join(', ') : undefined;
|
|
249
|
+
};
|
|
250
|
+
for (const [name, member] of Object.entries(team.members)) {
|
|
251
|
+
const set = name === 'oracle' ? undefined : choice(member, builtin.members[name]);
|
|
252
|
+
if (set) pinned[id][name] = set;
|
|
253
|
+
}
|
|
254
|
+
if (team.supervisor) {
|
|
255
|
+
const set = choice(team.supervisor, builtin.supervisor && builtin.supervisor.agent === team.supervisor.agent ? builtin.supervisor : undefined);
|
|
256
|
+
if (set) pinned[id][team.supervisor.agent] = set;
|
|
257
|
+
}
|
|
258
|
+
if (team.members.oracle && ((team.oracleModels && JSON.stringify(team.oracleModels) !== JSON.stringify(builtin.oracleModels)) || (team.oracleThinking && sameEntries(team.oracleThinking, builtin.oracleThinking) === false))) {
|
|
259
|
+
pinned[id].oracle = [team.oracleModels?.join(', '), team.oracleThinking ? `efforts ${Object.entries(team.oracleThinking).map(([lens, effort]) => `${lens} ${effort}`).join(', ')}` : undefined].filter(Boolean).join('; ');
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
const rewrites = (id, name) => {
|
|
264
|
+
const config = teams[id]?.[name];
|
|
265
|
+
if (!config) return true;
|
|
266
|
+
const fingerprint = profileFingerprint(config, name);
|
|
267
|
+
if (record[id]?.[name] === fingerprint || legacy[id]?.[name]?.includes(fingerprint)) return true;
|
|
268
|
+
return settings?.templateDefaults?.[id]?.[name] === fingerprint && !pinned[id]?.[name];
|
|
269
|
+
};
|
|
270
|
+
const kept = [];
|
|
271
|
+
for (const id of BUILTIN_TEAMS) {
|
|
272
|
+
for (const [name, config] of Object.entries(teams[id] ?? {})) {
|
|
273
|
+
if (rewrites(id, name)) continue;
|
|
274
|
+
const list = (config.profiles ?? []).map(profile => typeof profile === 'string' ? profile : describe(profile)).join(', ');
|
|
275
|
+
kept.push(pinned[id]?.[name] && settings?.templateDefaults?.[id]?.[name] === profileFingerprint(config, name)
|
|
276
|
+
? `Kept team.${id}.${name}.profiles (${list}): the ${id} team's team.json sets it (${pinned[id][name]}). Delete the entry from the file and run alp setup again to replace it.`
|
|
277
|
+
// Only an entry the record names, and which has changed since, is known to be someone else's edit.
|
|
278
|
+
: record[id]?.[name]
|
|
279
|
+
? `Kept team.${id}.${name}.profiles (${list}): changed since alp setup wrote it, so it is kept as yours. Delete the entry from the file and run alp setup again to replace it.`
|
|
280
|
+
: `Kept team.${id}.${name}.profiles (${list}): ALP cannot tell whether an earlier alp setup or you wrote it (it is none of setup's defaults, and no setup record names it), so it is kept as yours. Delete the entry from the file and run alp setup again to replace it.`);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
const others = [];
|
|
284
|
+
for (const [id, found] of await teamSources(root, { library: home })) {
|
|
285
|
+
if (BUILTIN_TEAMS.includes(id)) continue;
|
|
286
|
+
const team = await resolveTeam(root, id, { library: home }).catch(() => undefined);
|
|
287
|
+
const agents = team ? [...Object.keys(team.members).filter(name => name !== 'oracle'), ...(team.supervisor ? [team.supervisor.agent] : []), ...(team.members.oracle ? ['oracle'] : [])] : [];
|
|
288
|
+
others.push(`Team ${id} (${found.source}) is not Phở or Cafe, so alp setup leaves its profiles as they are: its team.json chooses its models. To change them, edit team.${id}.<agent>.profiles in ${file}${agents.length ? ` (agents: ${agents.join(', ')})` : ''}.`);
|
|
289
|
+
}
|
|
290
|
+
return { rewrites, kept, others, record, newer };
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** The settings with setup's profiles where setup may write them and every other entry kept, and the record of what setup wrote. */
|
|
294
|
+
function merge(written, profile, owners) {
|
|
295
|
+
const next = { ...written, team: currentTeams(written) };
|
|
296
|
+
delete next.profile;
|
|
297
|
+
const record = structuredClone(owners.record);
|
|
298
|
+
for (const [id, agents] of Object.entries(profile)) {
|
|
299
|
+
const team = { ...(next.team[id] ?? {}) };
|
|
300
|
+
for (const [name, config] of Object.entries(agents)) {
|
|
301
|
+
if (!owners.rewrites(id, name)) { if (record[id]) delete record[id][name]; continue; }
|
|
302
|
+
team[name] = config;
|
|
303
|
+
(record[id] ??= {})[name] = profileFingerprint(config, name);
|
|
304
|
+
}
|
|
305
|
+
next.team[id] = team;
|
|
306
|
+
if (record[id] && !Object.keys(record[id]).length) delete record[id];
|
|
307
|
+
}
|
|
308
|
+
return { next, record };
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** A model for one provider: a native ID, or one prefixed with that provider. */
|
|
312
|
+
function nativeModel(id, provider, where) {
|
|
313
|
+
const model = id.startsWith(`${provider}:`) ? id.slice(provider.length + 1) : id;
|
|
314
|
+
if (!model || /\s/.test(model) || /^(codex|claude):/.test(model) || (model.includes(':') && !id.startsWith(`${provider}:`))) throw new Error(`${where} expects a ${provider} model, got '${id}'`);
|
|
315
|
+
return model;
|
|
316
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export function holdDaemon(home: string, by?: string): Promise<void>;
|
|
2
|
+
export function releaseHold(home: string): Promise<void>;
|
|
3
|
+
export function daemonHeld(home: string): Promise<boolean>;
|
|
4
|
+
export function startDaemon(options: { home: string; entry?: string; env?: NodeJS.ProcessEnv; timeoutMs?: number; signal?: AbortSignal }): Promise<string>;
|
|
5
|
+
export function superviseDaemon(options: {
|
|
6
|
+
home: string;
|
|
7
|
+
entry?: string | (() => string | undefined);
|
|
8
|
+
env?: NodeJS.ProcessEnv;
|
|
9
|
+
intervalMs?: number;
|
|
10
|
+
misses?: number;
|
|
11
|
+
log?: (message: string) => void;
|
|
12
|
+
/** Who keeps alpd up, for the log: "alpd started with <by>". */
|
|
13
|
+
by?: string;
|
|
14
|
+
}): (() => Promise<void>) & { started: Promise<void> };
|
package/src/supervise.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { mkdir, unlink, writeFile, stat } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { daemonStartTimeoutMs, ensureDaemon, lockAlive, readLock, withDaemonLifecycle } from './index.js';
|
|
4
|
+
import { installedProgram, serviceFor, startService } from './service.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Keeping alpd up (ALPD §40). Whoever starts alpd goes through its login service when
|
|
8
|
+
* one is installed, so the service keeps managing it; otherwise alpd starts detached.
|
|
9
|
+
* A deliberate `alp daemon stop` leaves a hold, which watchers respect: they start
|
|
10
|
+
* alpd again only when someone asks for it.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const holdFile = home => path.join(home, 'state', 'alpd.held');
|
|
14
|
+
|
|
15
|
+
/** Records that the user stopped alpd on purpose. */
|
|
16
|
+
export async function holdDaemon(home, by = 'alp daemon stop') {
|
|
17
|
+
await mkdir(path.dirname(holdFile(home)), { recursive: true, mode: 0o700 });
|
|
18
|
+
await writeFile(holdFile(home), JSON.stringify({ by, at: new Date().toISOString() }) + '\n', { mode: 0o600 });
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function releaseHold(home) {
|
|
22
|
+
await unlink(holdFile(home)).catch(() => {});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function daemonHeld(home) {
|
|
26
|
+
return stat(holdFile(home)).then(() => true, () => false);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Polls until an alpd for `home` is ready; returns its socket. */
|
|
30
|
+
async function whenReady(home, timeoutMs, signal) {
|
|
31
|
+
const deadline = Date.now() + timeoutMs;
|
|
32
|
+
while (Date.now() < deadline) {
|
|
33
|
+
signal?.throwIfAborted();
|
|
34
|
+
const lock = await readLock(home);
|
|
35
|
+
if (lockAlive(lock) && lock.ready) return lock.socket;
|
|
36
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
37
|
+
}
|
|
38
|
+
throw new Error(`alpd did not become ready within ${timeoutMs / 1000} s; see ${path.join(home, 'logs')}`);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Starts alpd for `home` unless it runs, and lifts a hold: someone asked for it.
|
|
43
|
+
* Returns its socket. Waits up to `timeoutMs`, by default daemonStartTimeoutMs(env)
|
|
44
|
+
* (ALP_DAEMON_START_TIMEOUT_MS, else 60 s).
|
|
45
|
+
*/
|
|
46
|
+
export async function startDaemon({ home, entry, env = process.env, timeoutMs = daemonStartTimeoutMs(env), automatic = false, signal }) {
|
|
47
|
+
return withDaemonLifecycle(home, 'start', async () => {
|
|
48
|
+
signal?.throwIfAborted();
|
|
49
|
+
if (automatic) {
|
|
50
|
+
if (await daemonHeld(home)) return;
|
|
51
|
+
} else await releaseHold(home);
|
|
52
|
+
const lock = await readLock(home);
|
|
53
|
+
signal?.throwIfAborted();
|
|
54
|
+
if (lockAlive(lock)) return lock.ready ? lock.socket : whenReady(home, timeoutMs, signal);
|
|
55
|
+
const service = serviceFor({ home, env });
|
|
56
|
+
if (service && await installedProgram(service)) {
|
|
57
|
+
signal?.throwIfAborted();
|
|
58
|
+
await startService(service);
|
|
59
|
+
return whenReady(home, timeoutMs, signal);
|
|
60
|
+
}
|
|
61
|
+
return ensureDaemon({ home, entry, env, timeoutMs, lifecycleLocked: true, signal });
|
|
62
|
+
}, { signal });
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Starts alpd now and starts it again whenever it is found down on `misses` checks in a
|
|
67
|
+
* row, `intervalMs` apart, unless the user holds it. Two misses let `alp daemon restart`
|
|
68
|
+
* and `install` finish their own stop and start first. Returns a function that stops
|
|
69
|
+
* watching, and resolves once a start it began has settled; alpd keeps running. `by` names the
|
|
70
|
+
* caller in the log line of the first start ("alpd started with <by>").
|
|
71
|
+
*/
|
|
72
|
+
export function superviseDaemon({ home, entry, env = process.env, intervalMs = 5_000, misses = 2, log = () => {}, by }) {
|
|
73
|
+
let stopped = false;
|
|
74
|
+
let missed = 0;
|
|
75
|
+
let starting;
|
|
76
|
+
// The first start is the caller's own request (it lifts a hold); later ones are automatic.
|
|
77
|
+
const start = (reason, automatic = true) => {
|
|
78
|
+
starting ??= startDaemon({ home, entry: typeof entry === 'function' ? entry() : entry, env, automatic })
|
|
79
|
+
.then(socket => { if (socket) log(`alpd ${reason}`); }, error => log(`could not start alpd: ${error?.message ?? error}`))
|
|
80
|
+
.finally(() => { starting = undefined; missed = 0; });
|
|
81
|
+
return starting;
|
|
82
|
+
};
|
|
83
|
+
const check = async () => {
|
|
84
|
+
if (stopped || starting) return;
|
|
85
|
+
if (lockAlive(await readLock(home))) { missed = 0; return; }
|
|
86
|
+
if (await daemonHeld(home)) { missed = 0; return; }
|
|
87
|
+
// Stopped while this check looked: start nothing.
|
|
88
|
+
if (++missed >= misses && !stopped) await start('was down; started it again');
|
|
89
|
+
};
|
|
90
|
+
// `by` names the supervising service in the log, for example `Paseo` or `alp dashboard`.
|
|
91
|
+
const initial = start(by ? `started with ${by}` : 'started', false);
|
|
92
|
+
const timer = setInterval(() => { void check(); }, intervalMs);
|
|
93
|
+
timer.unref?.();
|
|
94
|
+
const stop = () => { stopped = true; clearInterval(timer); return starting ?? Promise.resolve(); };
|
|
95
|
+
stop.started = initial;
|
|
96
|
+
return stop;
|
|
97
|
+
}
|