@anhlp/alp-client 0.0.1-beta.4 → 0.0.1-beta.6

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.
@@ -0,0 +1,61 @@
1
+ /**
2
+ * A terminal directory for one connection. Subscribe before requesting the atomic snapshot.
3
+ * Invalidations are coalesced; a reconnect installs a new watcher and replaces state with its
4
+ * full snapshot (reset), rather than replaying obsolete list mutations. No output is replayed.
5
+ * @param {{request<T = any>(method:string, params?:any):Promise<T>, onNotification?(listener:(method:string,params:any)=>void):()=>void, onClose(listener:(error:Error)=>void):()=>void}} connection
6
+ * @param {{capabilities:readonly string[], workspaceId?:string, pollMs?:number, onSnapshot:(terminals:import('@anhlp/alp-protocol').TerminalInfo[])=>void, onError?:(error:unknown)=>void, onMode?:(mode:'events'|'polling')=>void}} options
7
+ */
8
+ export function watchTerminals(connection, options) {
9
+ const events = options.capabilities.includes('terminal.watch') && !!connection.onNotification;
10
+ let closed = false;
11
+ let watchId = '';
12
+ let cursor = '';
13
+ let again = false;
14
+ /** @type {Promise<void> | undefined} */ let refreshing;
15
+ // One newest token per watchId; bounded even when the host sends malformed/stale traffic.
16
+ /** @type {Map<string,string>} */ const pending = new Map();
17
+ const off = connection.onNotification?.((method, params) => {
18
+ if (closed || !events || method !== 'terminal.changed' || !/^[0-9a-f]{32}$/.test(params?.watchId) || !/^[0-9a-f]{32}$/.test(params?.cursor)) return;
19
+ if (pending.size >= 4 && !pending.has(params.watchId)) pending.delete(pending.keys().next().value ?? '');
20
+ pending.set(params.watchId, params.cursor);
21
+ if (params.watchId === watchId && params.cursor !== cursor) { again = true; void refresh(); }
22
+ });
23
+ function refresh() {
24
+ if (closed) return Promise.resolve();
25
+ if (refreshing) return refreshing;
26
+ refreshing = (async () => {
27
+ do {
28
+ again = false;
29
+ try {
30
+ const result = await connection.request(events ? 'terminal.watch' : 'terminal.list', { ...(options.workspaceId ? { workspaceId: options.workspaceId } : {}), ...(events && cursor ? { after: cursor } : {}) });
31
+ if (closed) return;
32
+ if (!Array.isArray(result?.terminals)) throw new Error('Invalid terminal directory snapshot');
33
+ if (events) {
34
+ if (!/^[0-9a-f]{32}$/.test(result.watchId) || !/^[0-9a-f]{32}$/.test(result.cursor) || typeof result.reset !== 'boolean') throw new Error('Invalid terminal directory cursor');
35
+ watchId = result.watchId;
36
+ cursor = result.cursor;
37
+ again = pending.has(watchId) && pending.get(watchId) !== cursor;
38
+ pending.clear();
39
+ }
40
+ options.onSnapshot(result.terminals);
41
+ } catch (error) { options.onError?.(error); return; }
42
+ } while (again && !closed);
43
+ })().finally(() => { refreshing = undefined; });
44
+ return refreshing;
45
+ }
46
+ const timer = events ? undefined : setInterval(() => { void refresh(); }, options.pollMs ?? 5000);
47
+ let offClose = () => {};
48
+ /** @param {boolean} [unwatch] */
49
+ function close(unwatch = true) {
50
+ if (closed) return;
51
+ closed = true;
52
+ if (timer !== undefined) clearInterval(timer);
53
+ off?.(); offClose(); pending.clear();
54
+ if (events && unwatch) void connection.request('terminal.unwatch', {}).catch(() => {});
55
+ }
56
+ offClose = connection.onClose(() => close(false));
57
+ if (closed) offClose();
58
+ options.onMode?.(events ? 'events' : 'polling');
59
+ const ready = refresh();
60
+ return { ready, refresh, close, mode: events ? 'events' : 'polling' };
61
+ }
package/src/service.js CHANGED
@@ -3,6 +3,7 @@ import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { runCommand } from './command.js';
6
+ import { entryCommand } from '@anhlp/alp-core/packaged';
6
7
 
7
8
  /**
8
9
  * alpd as a user service (ALPD §37): a LaunchAgent on macOS, a systemd user unit on
@@ -53,11 +54,13 @@ export function serviceFor({ home, env = process.env, platform = process.platfor
53
54
  return undefined;
54
55
  }
55
56
 
56
- /** The service definition that runs `entry` with `execPath` for `home`. */
57
+ /** The service definition that runs `entry` (alpd.js with `execPath`, or the ALP executable) for `home`. */
57
58
  export function serviceDefinition(service, { home, entry, execPath = process.execPath, env = process.env }) {
58
59
  const variables = { ALP_HOME: path.resolve(home), PATH: env.PATH ?? '' };
59
60
  for (const name of CARRIED) if (env[name]) variables[name] = env[name];
60
- const program = [execPath, entry, '--service'];
61
+ // A script entry runs under execPath; the ALP executable runs `alp daemon run --service`.
62
+ const launch = entryCommand(entry, 'daemon', ['--service'], execPath);
63
+ const program = [launch.command, ...launch.args];
61
64
  const fatal = path.join(path.resolve(home), 'logs', 'alpd.service.log');
62
65
  if (service.kind === 'launchd') {
63
66
  return `<?xml version="1.0" encoding="UTF-8"?>
package/src/setup.js CHANGED
@@ -2,7 +2,7 @@ import { copyFile, 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';
5
+ import { catalogModels } from '@anhlp/alp-core/models';
6
6
  import { fitEffort, modelEfforts } from '@anhlp/alp-core/profiles';
7
7
  import { resolveTeam } from '@anhlp/alp-core/teams';
8
8
  import { validateSettings } from '@anhlp/alp-core/validation';
@@ -85,7 +85,7 @@ export async function setup(args, home) {
85
85
  ] });
86
86
  if (next === 'cancel') throw new Cancelled();
87
87
  if (next === 'save') break;
88
- await change(seats);
88
+ await change(seats, home);
89
89
  show();
90
90
  }
91
91
  }
@@ -107,17 +107,19 @@ export async function setup(args, home) {
107
107
  const describe = choice => `${choice.provider}:${choice.model}${choice.effort ? `:${choice.effort}` : ''}`;
108
108
 
109
109
  /** Pick one seat and provider, then its model and effort. */
110
- async function change(seats) {
110
+ async function change(seats, home) {
111
+ // alpd's live catalog (t-e5ee) when it has one, else the static rows.
112
+ const catalog = catalogModels(home);
111
113
  const [seat, at] = await select({ message: 'Which model?', choices: Object.entries(seats).flatMap(([seat, choices]) =>
112
114
  choices.map((choice, at) => ({ label: `${SEAT_LABEL[seat]} · ${PROVIDER_LABEL[choice.provider]}`, value: [seat, at], hint: describe(choice) }))) });
113
115
  const current = seats[seat][at];
114
- const offered = MODELS.filter(model => model.runtime === current.provider);
116
+ const offered = catalog.filter(model => model.runtime === current.provider);
115
117
  const picked = await select({ message: `${SEAT_LABEL[seat]} on ${PROVIDER_LABEL[current.provider]}`, initial: current.model, choices: [
116
118
  ...offered.map(model => ({ label: model.label, value: model.id, hint: `${model.id} · ${model.description}` })),
117
119
  { label: 'Other…', value: undefined, hint: 'type a model ID' },
118
120
  ] });
119
121
  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;
122
+ const efforts = catalog.find(entry => entry.runtime === current.provider && entry.id === model)?.efforts ?? modelEfforts(`${current.provider}:${model}`) ?? ANY_EFFORT;
121
123
  const effort = efforts.length > 1 ? await select({ message: 'Effort', initial: efforts.includes(current.effort) ? current.effort : DEFAULTS[seat][current.provider][1],
122
124
  choices: efforts.map(effort => ({ label: effort, value: effort })) }) : efforts[0];
123
125
  seats[seat][at] = { provider: current.provider, model, ...(effort ? { effort } : {}) };
@@ -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);
package/src/supervise.js CHANGED
@@ -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));
@@ -41,20 +42,23 @@ async function whenReady(home, timeoutMs) {
41
42
  * Starts alpd for `home` unless it runs, and lifts a hold: someone asked for it.
42
43
  * Returns its socket.
43
44
  */
44
- export async function startDaemon({ home, entry, env = process.env, timeoutMs = 15_000, automatic = false }) {
45
+ export async function startDaemon({ home, entry, env = process.env, timeoutMs = 15_000, automatic = false, signal }) {
45
46
  return withDaemonLifecycle(home, 'start', async () => {
47
+ signal?.throwIfAborted();
46
48
  if (automatic) {
47
49
  if (await daemonHeld(home)) return;
48
50
  } else await releaseHold(home);
49
51
  const lock = await readLock(home);
50
- if (lockAlive(lock)) return lock.ready ? lock.socket : whenReady(home, timeoutMs);
52
+ signal?.throwIfAborted();
53
+ if (lockAlive(lock)) return lock.ready ? lock.socket : whenReady(home, timeoutMs, signal);
51
54
  const service = serviceFor({ home, env });
52
55
  if (service && await installedProgram(service)) {
56
+ signal?.throwIfAborted();
53
57
  await startService(service);
54
- return whenReady(home, timeoutMs);
58
+ return whenReady(home, timeoutMs, signal);
55
59
  }
56
- return ensureDaemon({ home, entry, env, timeoutMs, lifecycleLocked: true });
57
- });
60
+ return ensureDaemon({ home, entry, env, timeoutMs, lifecycleLocked: true, signal });
61
+ }, { signal });
58
62
  }
59
63
 
60
64
  /**