@anhlp/alp-client 0.0.0-beta.2 → 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.
Files changed (46) hide show
  1. package/README.md +23 -1
  2. package/dist/acp-probe.d.ts +3 -2
  3. package/dist/acp-probe.js +11 -2
  4. package/dist/antigravity-probe.d.ts +1 -2
  5. package/dist/antigravity-probe.js +11 -5
  6. package/dist/command.js +3 -1
  7. package/dist/doctor.d.ts +8 -0
  8. package/dist/doctor.js +276 -13
  9. package/dist/index.d.ts +123 -8
  10. package/dist/index.js +332 -52
  11. package/dist/integration-lock.d.ts +37 -0
  12. package/dist/integration-lock.js +199 -0
  13. package/dist/mcp-probe.js +1 -1
  14. package/dist/portable.d.ts +3 -1
  15. package/dist/portable.js +11 -2
  16. package/dist/render.js +3 -0
  17. package/dist/rpc/handshake.d.ts +6 -1
  18. package/dist/rpc/handshake.js +4 -2
  19. package/dist/rpc/registry.d.ts +227 -0
  20. package/dist/rpc/registry.js +223 -0
  21. package/dist/rpc/terminal-directory.d.ts +24 -0
  22. package/dist/rpc/terminal-directory.js +70 -0
  23. package/dist/service.d.ts +2 -2
  24. package/dist/service.js +3 -1
  25. package/dist/setup.d.ts +7 -1
  26. package/dist/setup.js +159 -32
  27. package/dist/supervise.d.ts +3 -1
  28. package/dist/supervise.js +26 -16
  29. package/package.json +11 -3
  30. package/src/acp-probe.js +10 -3
  31. package/src/antigravity-probe.js +12 -5
  32. package/src/command.js +3 -1
  33. package/src/doctor.d.ts +8 -0
  34. package/src/doctor.js +345 -3
  35. package/src/index.js +411 -55
  36. package/src/integration-lock.js +203 -0
  37. package/src/mcp-probe.js +1 -1
  38. package/src/portable.js +4 -1
  39. package/src/render.js +3 -0
  40. package/src/rpc/handshake.js +7 -2
  41. package/src/rpc/registry.js +229 -0
  42. package/src/rpc/terminal-directory.js +61 -0
  43. package/src/service.js +7 -3
  44. package/src/setup.js +201 -35
  45. package/src/supervise.d.ts +3 -1
  46. package/src/supervise.js +31 -19
package/src/setup.js CHANGED
@@ -1,10 +1,10 @@
1
- import { copyFile, readFile, writeFile } from 'node:fs/promises';
1
+ import { copyFile, mkdir, readFile, writeFile } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { parseArgs } from 'node:util';
4
4
  import { initProject } from '@anhlp/alp-core/init';
5
- import { MODELS } from '@anhlp/alp-core/models';
6
- import { fitEffort, modelEfforts } from '@anhlp/alp-core/profiles';
7
- import { resolveTeam } from '@anhlp/alp-core/teams';
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
8
  import { validateSettings } from '@anhlp/alp-core/validation';
9
9
  import { Cancelled, select, text } from './prompt.js';
10
10
 
@@ -21,8 +21,16 @@ const FLAGS = { main: 'model', worker: 'model', supervisor: 'supervisor', oracle
21
21
  const SEAT_LABEL = { main: 'main', worker: 'lead, reviewer', supervisor: 'supervisor', oracle: 'oracle' };
22
22
  const ANY_EFFORT = ['low', 'medium', 'high', 'xhigh', 'max'];
23
23
 
24
- /** Write Phở and Cafe's agent profiles into a project's .alp/settings.json, without installing software or calling models. */
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
+ */
25
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));
26
34
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: Object.fromEntries(
27
35
  ['runtime', 'prefer', ...PROVIDERS.flatMap(provider => Object.values(FLAGS).map(flag => `${provider}-${flag}`))].map(name => [name, { type: 'string' }]),
28
36
  ) });
@@ -49,17 +57,8 @@ export async function setup(args, home) {
49
57
  if (!enabled.includes(provider) && values[`${provider}-${flag}`]) throw new Error(`--${provider}-${flag} is unavailable in ${runtime}-only mode`);
50
58
  }
51
59
  }
52
- /** @type {Record<string, Array<{ provider: string, model: string, effort?: string }>>} */
53
- const seats = {};
54
- for (const [seat, flag] of Object.entries(FLAGS)) {
55
- seats[seat] = (seat === 'main' ? [prefer] : enabled).map(provider => {
56
- const option = `${provider}-${flag}`;
57
- const [fallback, effort] = DEFAULTS[seat][provider];
58
- const model = nativeModel(values[option] ?? fallback, provider, `--${option}`);
59
- return { provider, model, effort: fitEffort(`${provider}:${model}`, effort) };
60
- });
61
- }
62
- const peers = enabled.map(provider => `${provider}:*`);
60
+ const seats = seatsFor(enabled, prefer, values);
61
+ const peers = peersFor(enabled);
63
62
 
64
63
  const file = path.join(root, '.alp/settings.json');
65
64
  const settings = await readFile(file, 'utf8').then(content => {
@@ -72,10 +71,16 @@ export async function setup(args, home) {
72
71
  for (const [seat, choices] of Object.entries(seats)) console.log(` ${SEAT_LABEL[seat]}: ${choices.map(describe).join(', ')}`);
73
72
  console.log(` peer: ${peers.join(', ')} (any model: whoever assigns a peer picks its model and effort for the task)`);
74
73
  };
74
+ // Checked as it is first: reading its entries' owners assumes well-formed settings.
75
+ if (settings) validateSettings(settings, file);
75
76
  console.log(`Profiles for Phở and Cafe in ${file}:`);
76
77
  show();
77
- const replaced = ['pho', 'cafe'].filter(id => (settings?.team ?? settings?.profile)?.[id]);
78
- if (replaced.length) console.log(`These replace the ${replaced.join(' and ')} profiles already in the file; a backup is kept in ${file}.bak.`);
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);
79
84
  if (interactive) {
80
85
  for (;;) {
81
86
  const next = await select({ message: 'Save these profiles?', initial: 'save', choices: [
@@ -85,18 +90,19 @@ export async function setup(args, home) {
85
90
  ] });
86
91
  if (next === 'cancel') throw new Cancelled();
87
92
  if (next === 'save') break;
88
- await change(seats);
93
+ await change(seats, home);
89
94
  show();
90
95
  }
91
96
  }
92
- const profile = await profiles(root, home, seats, peers, settings);
93
- validateSettings({ ...(settings ?? {}), team: { ...(settings?.profile ?? {}), ...(settings?.team ?? {}), ...profile } }, file);
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);
94
99
  if (!settings) await initProject(root, { library: home });
95
100
  else if (replaced.length) await copyFile(file, `${file}.bak`);
96
101
  const written = settings ?? JSON.parse(await readFile(file, 'utf8'));
97
- const next = { ...written, team: { ...(written.profile ?? {}), ...(written.team ?? {}), ...profile } };
98
- delete next.profile;
102
+ const { next, record } = merge(written, await profiles(root, home, seats, peers, written), owners);
103
+ validateSettings(next, file);
99
104
  await writeFile(file, JSON.stringify(next, null, 2) + '\n');
105
+ await writeRecord(root, record, owners.newer);
100
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.');
101
107
  } catch (error) {
102
108
  if (!(error instanceof Cancelled)) throw error;
@@ -107,41 +113,201 @@ export async function setup(args, home) {
107
113
  const describe = choice => `${choice.provider}:${choice.model}${choice.effort ? `:${choice.effort}` : ''}`;
108
114
 
109
115
  /** Pick one seat and provider, then its model and effort. */
110
- async function change(seats) {
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);
111
119
  const [seat, at] = await select({ message: 'Which model?', choices: Object.entries(seats).flatMap(([seat, choices]) =>
112
120
  choices.map((choice, at) => ({ label: `${SEAT_LABEL[seat]} · ${PROVIDER_LABEL[choice.provider]}`, value: [seat, at], hint: describe(choice) }))) });
113
121
  const current = seats[seat][at];
114
- const offered = MODELS.filter(model => model.runtime === current.provider);
122
+ const offered = catalog.filter(model => model.runtime === current.provider);
115
123
  const picked = await select({ message: `${SEAT_LABEL[seat]} on ${PROVIDER_LABEL[current.provider]}`, initial: current.model, choices: [
116
124
  ...offered.map(model => ({ label: model.label, value: model.id, hint: `${model.id} · ${model.description}` })),
117
125
  { label: 'Other…', value: undefined, hint: 'type a model ID' },
118
126
  ] });
119
127
  const model = picked ?? nativeModel(await text(`${PROVIDER_LABEL[current.provider]} model ID:`), current.provider, 'The model ID');
120
- const efforts = modelEfforts(`${current.provider}:${model}`) ?? ANY_EFFORT;
128
+ const efforts = catalog.find(entry => entry.runtime === current.provider && entry.id === model)?.efforts ?? modelEfforts(`${current.provider}:${model}`) ?? ANY_EFFORT;
121
129
  const effort = efforts.length > 1 ? await select({ message: 'Effort', initial: efforts.includes(current.effort) ? current.effort : DEFAULTS[seat][current.provider][1],
122
130
  choices: efforts.map(effort => ({ label: effort, value: effort })) }) : efforts[0];
123
131
  seats[seat][at] = { provider: current.provider, model, ...(effort ? { effort } : {}) };
124
132
  }
125
133
 
126
- /** Every Phở and Cafe agent's profiles, keeping each agent's own compaction setting. */
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). */
127
168
  async function profiles(root, home, seats, peers, settings) {
128
169
  const profile = {};
129
- for (const id of ['pho', 'cafe']) {
170
+ for (const id of BUILTIN_TEAMS) {
130
171
  const team = await resolveTeam(root, id, { library: home });
131
172
  const agents = {};
132
- const seat = (name, choices) => {
133
- agents[name] = { profiles: choices.map(choice => typeof choice === 'string' ? choice : describe(choice)), autocompact: (settings?.team ?? settings?.profile)?.[id]?.[name]?.autocompact ?? 'auto' };
134
- };
135
- for (const [name, member] of Object.entries(team.members)) {
136
- if (name !== 'oracle') seat(name, name === team.main ? seats.main : member.role === 'peer' ? peers : seats.worker);
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 } : {}) };
137
176
  }
138
- if (team.supervisor) seat(team.supervisor.agent, seats.supervisor);
139
- if (team.members.oracle) seat('oracle', seats.oracle);
140
177
  profile[id] = agents;
141
178
  }
142
179
  return profile;
143
180
  }
144
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
+
145
311
  /** A model for one provider: a native ID, or one prefixed with that provider. */
146
312
  function nativeModel(id, provider, where) {
147
313
  const model = id.startsWith(`${provider}:`) ? id.slice(provider.length + 1) : id;
@@ -1,7 +1,7 @@
1
1
  export function holdDaemon(home: string, by?: string): Promise<void>;
2
2
  export function releaseHold(home: string): Promise<void>;
3
3
  export function daemonHeld(home: string): Promise<boolean>;
4
- export function startDaemon(options: { home: string; entry?: string; env?: NodeJS.ProcessEnv; timeoutMs?: number }): Promise<string>;
4
+ export function startDaemon(options: { home: string; entry?: string; env?: NodeJS.ProcessEnv; timeoutMs?: number; signal?: AbortSignal }): Promise<string>;
5
5
  export function superviseDaemon(options: {
6
6
  home: string;
7
7
  entry?: string | (() => string | undefined);
@@ -9,4 +9,6 @@ export function superviseDaemon(options: {
9
9
  intervalMs?: number;
10
10
  misses?: number;
11
11
  log?: (message: string) => void;
12
+ /** Who keeps alpd up, for the log: "alpd started with <by>". */
13
+ by?: string;
12
14
  }): (() => Promise<void>) & { started: Promise<void> };
package/src/supervise.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { mkdir, unlink, writeFile, stat } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
- import { ensureDaemon, lockAlive, readLock } from './index.js';
3
+ import { daemonStartTimeoutMs, ensureDaemon, lockAlive, readLock, withDaemonLifecycle } from './index.js';
4
4
  import { installedProgram, serviceFor, startService } from './service.js';
5
5
 
6
6
  /**
@@ -27,9 +27,10 @@ export async function daemonHeld(home) {
27
27
  }
28
28
 
29
29
  /** Polls until an alpd for `home` is ready; returns its socket. */
30
- async function whenReady(home, timeoutMs) {
30
+ async function whenReady(home, timeoutMs, signal) {
31
31
  const deadline = Date.now() + timeoutMs;
32
32
  while (Date.now() < deadline) {
33
+ signal?.throwIfAborted();
33
34
  const lock = await readLock(home);
34
35
  if (lockAlive(lock) && lock.ready) return lock.socket;
35
36
  await new Promise(resolve => setTimeout(resolve, 100));
@@ -39,33 +40,43 @@ async function whenReady(home, timeoutMs) {
39
40
 
40
41
  /**
41
42
  * Starts alpd for `home` unless it runs, and lifts a hold: someone asked for it.
42
- * Returns its socket.
43
+ * Returns its socket. Waits up to `timeoutMs`, by default daemonStartTimeoutMs(env)
44
+ * (ALP_DAEMON_START_TIMEOUT_MS, else 60 s).
43
45
  */
44
- export async function startDaemon({ home, entry, env = process.env, timeoutMs = 15_000 }) {
45
- await releaseHold(home);
46
- const lock = await readLock(home);
47
- if (lockAlive(lock)) return lock.ready ? lock.socket : whenReady(home, timeoutMs);
48
- const service = serviceFor({ home, env });
49
- if (service && await installedProgram(service)) {
50
- await startService(service);
51
- return whenReady(home, timeoutMs);
52
- }
53
- return ensureDaemon({ home, entry, env, timeoutMs });
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 });
54
63
  }
55
64
 
56
65
  /**
57
66
  * Starts alpd now and starts it again whenever it is found down on `misses` checks in a
58
67
  * row, `intervalMs` apart, unless the user holds it. Two misses let `alp daemon restart`
59
68
  * and `install` finish their own stop and start first. Returns a function that stops
60
- * watching, and resolves once a start it began has settled; alpd keeps running.
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>").
61
71
  */
62
- export function superviseDaemon({ home, entry, env = process.env, intervalMs = 5_000, misses = 2, log = () => {} }) {
72
+ export function superviseDaemon({ home, entry, env = process.env, intervalMs = 5_000, misses = 2, log = () => {}, by }) {
63
73
  let stopped = false;
64
74
  let missed = 0;
65
75
  let starting;
66
- const start = reason => {
67
- starting ??= startDaemon({ home, entry: typeof entry === 'function' ? entry() : entry, env })
68
- .then(() => log(`alpd ${reason}`), error => log(`could not start alpd: ${error?.message ?? error}`))
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}`))
69
80
  .finally(() => { starting = undefined; missed = 0; });
70
81
  return starting;
71
82
  };
@@ -76,7 +87,8 @@ export function superviseDaemon({ home, entry, env = process.env, intervalMs = 5
76
87
  // Stopped while this check looked: start nothing.
77
88
  if (++missed >= misses && !stopped) await start('was down; started it again');
78
89
  };
79
- const initial = start('started with Paseo');
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);
80
92
  const timer = setInterval(() => { void check(); }, intervalMs);
81
93
  timer.unref?.();
82
94
  const stop = () => { stopped = true; clearInterval(timer); return starting ?? Promise.resolve(); };