@anhlp/alp-cli 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 (80) hide show
  1. package/dist/THIRD-PARTY-NOTICES.txt +52 -2
  2. package/dist/acp/main.js +1 -1
  3. package/dist/acp.js +7802 -2239
  4. package/dist/alp-dashboard/THIRD-PARTY-NOTICES.txt +3256 -0
  5. package/dist/alp-dashboard/alp-boundary.json +16 -0
  6. package/dist/alp-dashboard/apple-touch-icon.png +0 -0
  7. package/dist/alp-dashboard/assets/TerminalPanel-D8HE9XBX.js +22 -0
  8. package/dist/alp-dashboard/assets/TerminalPanel-DLuoa74B.css +1 -0
  9. package/dist/alp-dashboard/assets/highlighter-BnicKQ_d.js +18 -0
  10. package/dist/alp-dashboard/assets/index-DwqDSiIi.css +1 -0
  11. package/dist/alp-dashboard/assets/index-YdtH3NBy.js +59 -0
  12. package/dist/alp-dashboard/favicon-attention.svg +6 -0
  13. package/dist/alp-dashboard/favicon-running.svg +6 -0
  14. package/dist/alp-dashboard/favicon.svg +5 -0
  15. package/dist/alp-dashboard/index.html +20 -0
  16. package/dist/alp-dashboard.js +10165 -0
  17. package/dist/alpd.js +39374 -17503
  18. package/dist/backup.js +2 -2
  19. package/dist/build-manifest.json +139 -3
  20. package/dist/cli.js +40 -6
  21. package/dist/daemon.d.ts +3 -3
  22. package/dist/daemon.js +16 -7
  23. package/dist/dashboard-migrate.d.ts +31 -0
  24. package/dist/dashboard-migrate.js +127 -0
  25. package/dist/dashboard-service.d.ts +69 -0
  26. package/dist/dashboard-service.js +141 -0
  27. package/dist/desktop.d.ts +56 -0
  28. package/dist/desktop.js +91 -0
  29. package/dist/interfaces.d.ts +23 -3
  30. package/dist/interfaces.js +277 -41
  31. package/dist/library.d.ts +16 -2
  32. package/dist/library.js +114 -7
  33. package/dist/paths.d.ts +6 -0
  34. package/dist/paths.js +4 -1
  35. package/dist/projects.js +2 -1
  36. package/dist/roles.d.ts +15 -0
  37. package/dist/roles.js +16 -0
  38. package/dist/schedules.d.ts +2 -0
  39. package/dist/schedules.js +45 -0
  40. package/dist/self-update.d.ts +151 -0
  41. package/dist/self-update.js +422 -0
  42. package/dist/sessions.d.ts +7 -2
  43. package/dist/sessions.js +44 -12
  44. package/dist/tasks.js +22 -8
  45. package/dist/terminal-native/README.md +201 -0
  46. package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
  47. package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
  48. package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
  49. package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
  50. package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  51. package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  52. package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  53. package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  54. package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  55. package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  56. package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
  57. package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  58. package/dist/terminal-native/terminal-owner.c +389 -0
  59. package/dist/terminal.d.ts +13 -0
  60. package/dist/terminal.js +80 -0
  61. package/dist/usage.d.ts +1 -1
  62. package/dist/usage.js +31 -9
  63. package/package.json +11 -4
  64. package/src/backup.js +1 -1
  65. package/src/cli.js +51 -6
  66. package/src/daemon.js +18 -9
  67. package/src/dashboard-migrate.js +152 -0
  68. package/src/dashboard-service.js +192 -0
  69. package/src/desktop.js +122 -0
  70. package/src/interfaces.js +345 -38
  71. package/src/library.js +108 -9
  72. package/src/paths.js +9 -1
  73. package/src/projects.js +3 -1
  74. package/src/roles.js +26 -0
  75. package/src/schedules.js +38 -0
  76. package/src/self-update.js +443 -0
  77. package/src/sessions.js +44 -15
  78. package/src/tasks.js +22 -8
  79. package/src/terminal.js +78 -0
  80. package/src/usage.js +31 -9
package/src/backup.js CHANGED
@@ -123,5 +123,5 @@ export async function restoreCommand(args) {
123
123
  for (const { root, reason } of result.skipped) console.log(` skipped ${root}: ${reason}`);
124
124
  for (const warning of result.warnings) console.log(` note: ${warning}`);
125
125
  if (result.stateSchema !== null && result.stateSchema !== undefined) console.log(' sessions that were working when the backup was made wait for you; alpd continues none by itself');
126
- if (result.safety) console.log(`the data it replaced is in ${result.safety}; alp restore ${result.safety} puts it back`);
126
+ if (result.safety) console.log(`the data it replaced is in ${result.safety}; alp restore ${result.safety} restores that data with the same workspace authority checks`);
127
127
  }
package/src/cli.js CHANGED
@@ -1,21 +1,66 @@
1
1
  #!/usr/bin/env node
2
+ import { readFileSync } from 'node:fs';
2
3
  import { setup } from '@anhlp/alp-client/setup';
3
4
  import { alpHome } from '@anhlp/alp-client/index';
4
5
  import { scrubText } from '@anhlp/alp-core/log';
6
+ import { catalogModels, useLiveModels } from '@anhlp/alp-core/models';
5
7
  import { USAGE, UsageError } from './usage.js';
6
8
  import { project, permissionsCommand, trustCommand, language, verify, doctor } from './projects.js';
7
9
  import { daemon } from './daemon.js';
8
- import { run, ps, attach, send, questions, answer, top, log, board, pause, resume, recall, interrupt } from './sessions.js';
9
- import { libraryCommand, editCommand, teamsCommand } from './library.js';
10
+ import { run, ps, attach, send, questions, answer, top, log, board, models, pause, resume, recall, interrupt, compact } from './sessions.js';
11
+ import { libraryCommand, editCommand, teamsCommand, packsCommand, packCommand } from './library.js';
12
+ import { scheduleCommand } from './schedules.js';
10
13
  import { tasksCommand, formulaCommand, taskCommand } from './tasks.js';
11
- import { webCommand, acpCommand } from './interfaces.js';
14
+ import { dashboardCommand, acpCommand } from './interfaces.js';
15
+ import { desktopCommand } from './desktop.js';
12
16
  import { backupCommand, restoreCommand } from './backup.js';
17
+ import { terminalCommand } from './terminal.js';
18
+ import { bridgeCommand } from './roles.js';
19
+ import { selfUpdate } from './self-update.js';
20
+ import { bundleInfo } from '@anhlp/alp-core/packaged';
21
+ import { connect, lockAlive, readLock } from '@anhlp/alp-client/index';
13
22
 
14
- const commands = { setup: args => setup(args, alpHome()), init: args => project('init', args), upgrade: args => project('upgrade', args), update: args => project('upgrade', args), daemon, doctor, run, ps, top, attach, send, questions, answer, log, board, tasks: tasksCommand, task: taskCommand, formula: formulaCommand, permissions: permissionsCommand, agents: args => libraryCommand('agents', args), skills: args => libraryCommand('skills', args), mcp: args => ['add', 'rm', 'mv', 'cp', 'test', 'show', 'edit'].includes(args[0]) ? editCommand('mcp', args) : libraryCommand('mcp', args), hooks: args => libraryCommand('hooks', args), providers: args => libraryCommand('providers', args), provider: args => editCommand('providers', args), teams: teamsCommand, trust: trustCommand, agent: args => editCommand('agents', args), team: args => editCommand('teams', args), skill: args => editCommand('skills', args), hook: args => editCommand('hooks', args), verify, recall, pause, resume, language, interrupt, acp: acpCommand, web: webCommand, backup: backupCommand, restore: restoreCommand };
23
+ /** The version of this alp: the build's, or the package's. */
24
+ function alpVersion() {
25
+ /* global __ALP_VERSION__ */
26
+ return (typeof __ALP_VERSION__ === 'string' ? __ALP_VERSION__ : JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
27
+ }
28
+
29
+ /** The running alpd's version and live sessions, if one runs for this ALP_HOME. */
30
+ async function runningDaemon() {
31
+ const lock = await readLock(alpHome());
32
+ if (!lockAlive(lock)) return undefined;
33
+ const client = await connect(lock.socket, { name: 'alp-cli', version: '1' }).catch(() => undefined);
34
+ if (!client) return { version: lock.version };
35
+ try {
36
+ const status = await client.request('daemon.status');
37
+ return { version: status.version ?? lock.version, sessions: status.sessions };
38
+ } catch {
39
+ return { version: lock.version };
40
+ } finally {
41
+ client.close();
42
+ }
43
+ }
44
+
45
+ /** alp update: the bundle's self-update (t-1807); the template upgrade is alp update-template. */
46
+ async function updateCommand(args) {
47
+ const code = await selfUpdate(args, { bundle: bundleInfo(), version: alpVersion(), daemon: runningDaemon });
48
+ if (code) process.exitCode = code;
49
+ }
50
+
51
+ const commands = { schedule: scheduleCommand, setup: args => setup(args, alpHome()), init: args => project('init', args), 'update-template': args => project('upgrade', args), upgrade: args => project('upgrade', args), update: updateCommand, daemon, doctor, run, ps, top, attach, send, questions, answer, log, board, tasks: tasksCommand, task: taskCommand, formula: formulaCommand, permissions: permissionsCommand, agents: args => libraryCommand('agents', args), skills: args => libraryCommand('skills', args), mcp: args => ['add', 'rm', 'mv', 'cp', 'test', 'show', 'edit'].includes(args[0]) ? editCommand('mcp', args) : libraryCommand('mcp', args), hooks: args => libraryCommand('hooks', args), providers: args => libraryCommand('providers', args), provider: args => editCommand('providers', args), teams: teamsCommand, packs: packsCommand, pack: packCommand, trust: trustCommand, agent: args => editCommand('agents', args), team: args => editCommand('teams', args), skill: args => editCommand('skills', args), hook: args => editCommand('hooks', args), verify, recall, pause, resume, language, models, interrupt, compact, acp: acpCommand, dashboard: dashboardCommand, desktop: desktopCommand, backup: backupCommand, restore: restoreCommand, terminal: terminalCommand, bridge: bridgeCommand };
15
52
  const [command, ...args] = process.argv.slice(2);
16
53
  try {
17
- if (!Object.hasOwn(commands, command)) throw new UsageError();
18
- await commands[command](args);
54
+ if (command === '--version') {
55
+ // Published builds inject their package version; source execution reads the same metadata.
56
+ console.log(alpVersion());
57
+ } else {
58
+ if (!Object.hasOwn(commands, command)) throw new UsageError();
59
+ // Effort checks read the catalog alpd last cached, the rows alpd itself checks with (t-086c), so
60
+ // the CLI and alpd agree on a model only live rows list (t-b3cd #8). No provider is asked.
61
+ if (command !== 'setup') useLiveModels(catalogModels(alpHome()));
62
+ await commands[command](args);
63
+ }
19
64
  } catch (error) {
20
65
  if (error instanceof UsageError || error?.code === 'ERR_PARSE_ARGS_UNKNOWN_OPTION') console.error(USAGE);
21
66
  else console.error(`alp: ${scrubText(error?.message ?? error)}`);
package/src/daemon.js CHANGED
@@ -2,22 +2,23 @@ import { access } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { installedProgram, installService, serviceFor, uninstallService } from '@anhlp/alp-client/service';
4
4
  import { holdDaemon, startDaemon } from '@anhlp/alp-client/supervise';
5
- import { alpHome, connect, lockAlive, readLock } from '@anhlp/alp-client/index';
5
+ import { alpHome, connect, daemonStartTimeoutMs, lockAlive, readLock, withDaemonLifecycle } from '@anhlp/alp-client/index';
6
6
  import { scrubText } from '@anhlp/alp-core/log';
7
7
  import { UsageError } from './usage.js';
8
- import { DAEMON_ENTRY } from './paths.js';
8
+ import { DAEMON_ENTRY, DAEMON_SCRIPT } from './paths.js';
9
+ import { runRole } from './roles.js';
9
10
 
10
- async function built() {
11
+ async function built(entry = DAEMON_ENTRY) {
11
12
  try {
12
- await access(DAEMON_ENTRY);
13
+ await access(entry);
13
14
  } catch {
14
- throw new Error(`alpd is not built (${DAEMON_ENTRY}); run npm run build`);
15
+ throw new Error(`alpd is not built (${entry}); run npm run build`);
15
16
  }
16
17
  }
17
18
 
18
- /** Waits until an alpd for this home is ready; returns its socket. */
19
+ /** Waits until an alpd for this home is ready; returns its socket. Default wait: ALP_DAEMON_START_TIMEOUT_MS, else 60 s. */
19
20
 
20
- async function ready(timeoutMs = 15_000) {
21
+ async function ready(timeoutMs = daemonStartTimeoutMs()) {
21
22
  const deadline = Date.now() + timeoutMs;
22
23
  while (Date.now() < deadline) {
23
24
  const lock = await readLock(alpHome());
@@ -60,15 +61,23 @@ async function stop() {
60
61
  }
61
62
 
62
63
  async function daemon([action, ...rest]) {
64
+ // alpd itself in this process (alpd.js on this Node, even where the bundle ships the native alpd);
65
+ // its own options (--detach, --service, --startup-timeout=MS) follow.
66
+ if (action === 'run') { await built(DAEMON_SCRIPT); return runRole('daemon', DAEMON_SCRIPT, rest); }
63
67
  if (rest.length && !(action === 'status' && rest.length === 1 && rest[0] === '--json')) throw new UsageError();
64
68
  if (action === 'start') {
65
69
  const socket = await start();
66
70
  const lock = await readLock(alpHome());
67
71
  console.log(`alpd ${lock.version} running (pid ${lock.pid}) on ${socket}`);
68
72
  } else if (action === 'stop') {
69
- const stopped = await stop();
70
- // On purpose: the Paseo plugin leaves it stopped until something asks for it.
73
+ // Publish intent before waiting for a launch, then drain that launch before
74
+ // reading its lock. No detached child can arrive after this stop resolves.
71
75
  await holdDaemon(alpHome());
76
+ const stopped = await withDaemonLifecycle(alpHome(), 'stop', async () => {
77
+ const stopped = await stop();
78
+ await holdDaemon(alpHome());
79
+ return stopped;
80
+ });
72
81
  console.log(stopped ? `alpd stopped; it stays stopped until alp daemon start, a prompt in Paseo, or ${await installed() ? 'the next login' : 'Paseo starting again'}` : 'alpd is not running');
73
82
  } else if (action === 'restart') {
74
83
  const client = await running().catch(() => undefined);
@@ -0,0 +1,152 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { chmod, link, lstat, readFile, rename, unlink, writeFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { migrateDashboardSettings } from '@anhlp/alp-core/user-settings';
5
+ import { DASHBOARD, LEGACY_WEB, refusal, serviceOwner, stopService } from './dashboard-service.js';
6
+
7
+ /**
8
+ * The move from `alp web` (0.0.1-beta.8 and earlier) to `alp dashboard` (t-81b0.5), run by every
9
+ * `alp dashboard` command before it reads or starts anything. An install keeps its token, its port
10
+ * and its enabled/disabled setting:
11
+ *
12
+ * 1. alp web still running under `integrations/web.lock` (or the Paseo integration from before its
13
+ * own rename, which held the same lock) is stopped, with the same proofs `alp dashboard --stop`
14
+ * uses; a holder that cannot be proven is left running and nothing below is moved, since it
15
+ * may still write the old files.
16
+ * 2. `<home>/web/` (alp web's credential store) becomes `<home>/dashboard/`.
17
+ * 3. `<home>/web.json` written by alp web (`app: 'alp-web'`) becomes `<home>/dashboard.json`, keeping
18
+ * its token and credential id; one without `app` is the Paseo integration's identity and is left
19
+ * for the service to carry into paseo.json, as before.
20
+ * 4. `logs/integrations/alp-web.log` becomes `alp-dashboard.log`.
21
+ * 5. settings.json: `web.enabled`, `web.port` and `web.permissions` move to `dashboard.*`
22
+ * (`web.relay`, Paseo's, stays); see migrateDashboardSettings.
23
+ *
24
+ * Every step only moves an old name onto a missing new one, so a second run does nothing and a home
25
+ * that has both keeps the new one untouched (the old one is reported, never merged or deleted).
26
+ * Steps that race another `alp dashboard` lose cleanly: a rename or link that finds its source gone
27
+ * or its target present is skipped.
28
+ */
29
+
30
+ /** @param {string} file */
31
+ const exists = file => lstat(file).then(() => true, () => false);
32
+ /** A file's JSON, or undefined when it is missing or not JSON. @param {string} file */
33
+ const readJson = file => readFile(file, 'utf8').then(text => { try { return JSON.parse(text); } catch { return undefined; } }, () => undefined);
34
+ /** @param {unknown} error */
35
+ const code = error => /** @type {any} */ (error)?.code;
36
+
37
+ /**
38
+ * @param {string} home
39
+ * @param {{ strict?: boolean }} [options] strict: a legacy holder alp cannot stop is an error (a start
40
+ * would otherwise lose its port to it); without it, it is reported and the files are left alone.
41
+ * @returns {Promise<{ stopped?: number, held?: boolean, moved: string[], kept: string[], warnings: string[] }>}
42
+ * held: a legacy holder alp would not stop is still running (only without strict).
43
+ */
44
+ export async function migrateDashboard(home, { strict = false } = {}) {
45
+ /** @type {{ stopped?: number, held?: boolean, moved: string[], kept: string[], warnings: string[] }} */
46
+ const report = { moved: [], kept: [], warnings: [] };
47
+
48
+ // 1. The service from before the rename.
49
+ const owner = await serviceOwner(home, LEGACY_WEB);
50
+ if ('pid' in owner || (owner.alive && owner.kind === 'transient')) {
51
+ try { report.stopped = await stopService(home, 30_000, LEGACY_WEB); }
52
+ catch (error) {
53
+ if (strict) throw error;
54
+ report.warnings.push(/** @type {any} */ (error)?.message ?? String(error));
55
+ report.held = true;
56
+ return report;
57
+ }
58
+ } else if (owner.alive) {
59
+ const message = `${refusal(home, LEGACY_WEB)} (${owner.reason}); stop it, then run the command again`;
60
+ if (strict) throw new Error(message);
61
+ report.warnings.push(message);
62
+ report.held = true;
63
+ return report;
64
+ }
65
+
66
+ // 2. The credential store.
67
+ const oldStore = path.join(home, 'web');
68
+ const newStore = path.join(home, 'dashboard');
69
+ if (await exists(path.join(oldStore, 'credentials.json'))) {
70
+ if (await exists(newStore)) report.kept.push(oldStore);
71
+ else {
72
+ try { await rename(oldStore, newStore); report.moved.push(`${oldStore} -> ${newStore}`); }
73
+ catch (error) { if (!['ENOENT', 'EEXIST', 'ENOTEMPTY'].includes(code(error))) throw error; }
74
+ }
75
+ }
76
+
77
+ // 3. What the service published.
78
+ const oldInfo = path.join(home, LEGACY_WEB.info);
79
+ const newInfo = path.join(home, DASHBOARD.info);
80
+ const published = await readJson(oldInfo);
81
+ if (published?.app === LEGACY_WEB.app) {
82
+ // The same token in dashboard.json: this file was already carried (by an earlier or a concurrent
83
+ // run, or a crash after the link), so the old one is only a copy.
84
+ const carriedAlready = async () => typeof published.token === 'string' && published.token !== '' && (await readJson(newInfo))?.token === published.token;
85
+ const removeOld = () => unlink(oldInfo).catch(error => { if (code(error) !== 'ENOENT') throw error; });
86
+ if (await exists(newInfo)) {
87
+ if (await carriedAlready()) await removeOld();
88
+ else report.kept.push(oldInfo);
89
+ } else {
90
+ // Only what the next start reuses; the old pid, port and URL died with the old service.
91
+ const carried = { version: published.version, app: DASHBOARD.app, token: published.token, credentialId: published.credentialId };
92
+ const temporary = `${newInfo}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
93
+ try {
94
+ await writeFile(temporary, `${JSON.stringify(carried)}\n`, { mode: 0o600, flag: 'wx' });
95
+ await chmod(temporary, 0o600);
96
+ // A link never replaces: a dashboard.json written meanwhile wins, and the old file is
97
+ // removed only when that one carries the same token.
98
+ const linked = await link(temporary, newInfo).then(() => true, error => { if (code(error) !== 'EEXIST') throw error; return false; });
99
+ if (linked) { report.moved.push(`${oldInfo} -> ${newInfo}`); await removeOld(); }
100
+ else if (await carriedAlready()) await removeOld();
101
+ else report.kept.push(oldInfo);
102
+ } finally { await unlink(temporary).catch(() => {}); }
103
+ }
104
+ }
105
+
106
+ // 4. The service's log.
107
+ const logs = path.join(home, 'logs', 'integrations');
108
+ const oldLog = path.join(logs, 'alp-web.log');
109
+ const newLog = path.join(logs, 'alp-dashboard.log');
110
+ if (await exists(oldLog) && !(await exists(newLog))) {
111
+ await rename(oldLog, newLog).then(() => report.moved.push(`${oldLog} -> ${newLog}`), error => { if (code(error) !== 'ENOENT') throw error; });
112
+ }
113
+
114
+ // 5. Settings. A file alp cannot rewrite (invalid, read-only) is still obeyed: dashboardSettings
115
+ // reads `web.*` where `dashboard.*` is not set.
116
+ try {
117
+ const settings = await migrateDashboardSettings(home);
118
+ for (const key of settings.moved) report.moved.push(`settings.json web.${key} -> dashboard.${key}`);
119
+ for (const key of settings.conflicts) report.kept.push(`settings.json web.${key} (dashboard.${key} is set and wins)`);
120
+ } catch (error) {
121
+ report.warnings.push(`settings.json was not migrated (web.* is still read): ${/** @type {any} */ (error)?.message ?? error}`);
122
+ }
123
+ return report;
124
+ }
125
+
126
+ /**
127
+ * What a home still has under the names from before the rename, without changing anything (for
128
+ * `alp dashboard --status`): `pending` the next `alp dashboard` moves, `kept` it leaves because the
129
+ * new name exists, and the legacy service if one runs.
130
+ * @param {string} home
131
+ * @returns {Promise<{ legacy?: { pid?: number, reason?: string }, pending: string[], kept: string[] }>}
132
+ */
133
+ export async function legacyLeftovers(home) {
134
+ /** @type {{ legacy?: { pid?: number, reason?: string }, pending: string[], kept: string[] }} */
135
+ const result = { pending: [], kept: [] };
136
+ const owner = await serviceOwner(home, LEGACY_WEB);
137
+ if ('pid' in owner) result.legacy = { pid: owner.pid };
138
+ else if (owner.alive) result.legacy = { reason: owner.reason };
139
+ const place = async (/** @type {string} */ old, /** @type {string} */ current) => (await exists(current) ? result.kept : result.pending).push(old);
140
+ if (await exists(path.join(home, 'web', 'credentials.json'))) await place(path.join(home, 'web'), path.join(home, 'dashboard'));
141
+ const published = await readJson(path.join(home, LEGACY_WEB.info));
142
+ if (published?.app === LEGACY_WEB.app) await place(path.join(home, LEGACY_WEB.info), path.join(home, DASHBOARD.info));
143
+ const logs = path.join(home, 'logs', 'integrations');
144
+ if (await exists(path.join(logs, 'alp-web.log'))) await place(path.join(logs, 'alp-web.log'), path.join(logs, 'alp-dashboard.log'));
145
+ const settings = await readJson(path.join(home, 'settings.json'));
146
+ for (const key of ['enabled', 'port', 'permissions']) {
147
+ if (settings?.web?.[key] === undefined) continue;
148
+ if (settings?.dashboard?.[key] !== undefined) result.kept.push(`settings.json web.${key} (dashboard.${key} is set and wins)`);
149
+ else result.pending.push(`settings.json web.${key}`);
150
+ }
151
+ return result;
152
+ }
@@ -0,0 +1,192 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { lstat, readFile } from 'node:fs/promises';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { promisify } from 'node:util';
8
+ import { bootTime, isSameBoot, readLock } from '@anhlp/alp-client/index';
9
+ import { distributionEntry } from './paths.js';
10
+ import { selfEntry } from '@anhlp/alp-core/packaged';
11
+
12
+ /**
13
+ * The CLI's side of alp-dashboard (packages/cli/src/dashboard), the service behind `alp dashboard`:
14
+ * where it is, which process owns its lock, and how to stop that process safely. The same proofs
15
+ * apply to what ran under the names from before the rename (t-81b0.5): `integrations/web.lock` and
16
+ * `web.json`, held by alp web of 0.0.1-beta.8 or earlier, or by the Paseo integration from before
17
+ * its own rename.
18
+ *
19
+ * Only a process proven to be the one that took the service's lock is ever signalled, and only
20
+ * with SIGTERM (the CLI's own `--rotate` child aside, which it may time out): the lock and the
21
+ * service's `<name>.json` name the same pid, both files are the user's, the lock is
22
+ * from this boot, the pid answers signal 0 (so it is the user's own process), and that process
23
+ * started no later than the lock was written (so the pid was not reused). Anything else is reported
24
+ * and left alone. A stopped owner releases the lock; one that died holding it leaves it to the next
25
+ * acquire, which reclaims it only on proof of death (the integration lock protocol, t-e148).
26
+ */
27
+
28
+ const execFileAsync = promisify(execFile);
29
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
30
+
31
+ /** The alp-dashboard service script beside this CLI; a clear error when this CLI was built without it. */
32
+ export function dashboardScript() {
33
+ const entry = fileURLToPath(distributionEntry('alp-dashboard.js'));
34
+ if (!existsSync(entry)) throw new Error(`alp dashboard is not built: ${entry} is missing. Build the CLI (npm run build in the ALP checkout) or reinstall ALP.`);
35
+ return entry;
36
+ }
37
+
38
+ /** What starts alp-dashboard: its script under Node (named through app/current in the ALP bundle). */
39
+ export const dashboardEntry = () => selfEntry(dashboardScript());
40
+
41
+ /**
42
+ * @typedef {{ lock: string, info: string, app: string, what: string }} Service
43
+ * The integration lock's name, the file the service publishes, the `app` it writes there, and what
44
+ * messages call it.
45
+ */
46
+ /** @type {Service} */
47
+ export const DASHBOARD = Object.freeze({ lock: 'dashboard', info: 'dashboard.json', app: 'alp-dashboard', what: 'alp dashboard' });
48
+ /** alp web as 0.0.1-beta.8 and earlier ran it (and, before that, the Paseo integration). @type {Service} */
49
+ export const LEGACY_WEB = Object.freeze({ lock: 'web', info: 'web.json', app: 'alp-web', what: 'alp web from before its rename to alp dashboard' });
50
+
51
+ const readJson = async file => JSON.parse(await readFile(file, 'utf8'));
52
+
53
+ /** When `pid` started and elapsed seconds from ps, or undefined when ps cannot say. @param {number} pid */
54
+ async function processTimes(pid) {
55
+ try {
56
+ const { stdout } = await execFileAsync('ps', ['-o', 'etime=', '-p', String(pid)], { encoding: 'utf8', timeout: 5_000 });
57
+ // [[dd-]hh:]mm:ss
58
+ const match = /^\s*(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)\s*$/.exec(stdout);
59
+ if (!match) return undefined;
60
+ const [, days = '0', hours = '0', minutes, seconds] = match;
61
+ const elapsed = ((Number(days) * 24 + Number(hours)) * 60 + Number(minutes)) * 60 + Number(seconds);
62
+ return { started: Date.now() - elapsed * 1000, elapsed };
63
+ } catch { return undefined; }
64
+ }
65
+
66
+ /**
67
+ * The process that owns `service`'s lock, if it is proven safe to stop; else why not. `kind` says
68
+ * whether waiting can help: `transient` (an owner still starting has not published its file yet),
69
+ * `foreign` (proven not to be the integration: another user's, another boot's, or a reused pid) or
70
+ * `unknown` (it cannot be proven either way, for example without ps or on Windows).
71
+ *
72
+ * The reuse proof compares the lock's creation time with the process's start from ps: when
73
+ * `startedUptime` is recorded, monotonic uptime comparison prevents clock step vulnerabilities.
74
+ * For legacy locks, wall-clock `startedAt` is compared.
75
+ * @param {string} home @param {Service} [service]
76
+ * @returns {Promise<{ pid: number, app: unknown } | { reason: string, alive: boolean, kind?: 'transient' | 'foreign' | 'unknown' }>}
77
+ */
78
+ export async function serviceOwner(home, service = DASHBOARD) {
79
+ const lockFile = path.join(home, 'integrations', `${service.lock}.lock`);
80
+ const infoFile = path.join(home, service.info);
81
+ let lock, lockInfo;
82
+ try { lockInfo = await lstat(lockFile); lock = await readJson(lockFile); } catch { return { reason: `${lockFile} is missing or unreadable`, alive: false }; }
83
+ if (!lockInfo.isFile() || !Number.isSafeInteger(lock?.pid) || lock.pid <= 0 || typeof lock.bootTime !== 'number' || !Number.isFinite(Date.parse(lock.startedAt))) {
84
+ return { reason: `${lockFile} is not a complete integration lock`, alive: false };
85
+ }
86
+ const { pid } = lock;
87
+ try { process.kill(pid, 0); } catch (error) {
88
+ if (error?.code === 'ESRCH') return { reason: `its pid ${pid} has exited`, alive: false };
89
+ if (error?.code === 'EPERM') return { reason: `pid ${pid} belongs to another user`, alive: true, kind: 'foreign' };
90
+ return { reason: `pid ${pid} cannot be signalled (${error?.code ?? error})`, alive: true, kind: 'unknown' };
91
+ }
92
+ const refuse = (/** @type {string} */ reason, /** @type {'transient' | 'foreign' | 'unknown'} */ kind) => ({ reason, alive: true, kind });
93
+ if (process.platform === 'win32') return refuse('alp does not stop it on Windows', 'unknown');
94
+ const uid = process.getuid?.();
95
+ if (lockInfo.uid !== uid) return refuse('its lock is not yours', 'foreign');
96
+ if (!isSameBoot(lock)) return refuse('its lock is from another boot', 'foreign');
97
+ if (pid === process.pid || pid === (await readLock(home).catch(() => undefined))?.pid) return refuse(`pid ${pid} is not an integration`, 'foreign');
98
+ const times = await processTimes(pid);
99
+ if (times === undefined) return refuse(`the start time of pid ${pid} is unknown`, 'unknown');
100
+ // When startedUptime is recorded, monotonic uptime comparison prevents clock step vulnerabilities.
101
+ // Otherwise, fallback to wall-clock startedAt comparison with 2s tolerance for ps resolution.
102
+ const isReused = typeof lock.startedUptime === 'number'
103
+ ? (Math.floor(os.uptime()) - times.elapsed) > lock.startedUptime + 2
104
+ : times.started > Date.parse(lock.startedAt) + 2_000;
105
+ if (isReused) return refuse(`pid ${pid} started after the lock was written (a reused pid)`, 'foreign');
106
+ // The lock's owner; its published file must name it too (an owner still starting has not written it yet).
107
+ let info, infoStat;
108
+ try { infoStat = await lstat(infoFile); info = await readJson(infoFile); } catch { return refuse(`${infoFile} is missing or unreadable`, 'transient'); }
109
+ if (info?.pid !== pid) return refuse(`${infoFile} names another process than the lock`, 'transient');
110
+ if (!infoStat.isFile() || infoStat.uid !== uid) return refuse(`${infoFile} is not yours`, 'foreign');
111
+ return { pid, app: info.app };
112
+ }
113
+
114
+ /**
115
+ * Sends SIGTERM to a proven owner and waits for it to exit.
116
+ * @param {number} pid @param {string} what @param {number} [timeoutMs]
117
+ */
118
+ async function terminate(pid, what, timeoutMs = 20_000) {
119
+ try { process.kill(pid, 'SIGTERM'); } catch (error) { if (error?.code === 'ESRCH') return; throw error; }
120
+ const deadline = Date.now() + timeoutMs;
121
+ while (Date.now() < deadline) {
122
+ try { process.kill(pid, 0); } catch (error) { if (error?.code === 'ESRCH') return; }
123
+ await sleep(100);
124
+ }
125
+ throw new Error(`${what} (pid ${pid}) did not stop within ${timeoutMs / 1000} s of SIGTERM; stop it, then run the command again`);
126
+ }
127
+
128
+ const PASEO_BEFORE_RENAME = 'The Paseo integration from before its rename';
129
+
130
+ /** What a proven owner of `service`'s lock is, by the `app` its file names. @param {Service} service @param {unknown} app */
131
+ const ownerName = (service, app) => app === service.app || service === DASHBOARD ? service.what : PASEO_BEFORE_RENAME;
132
+
133
+ /**
134
+ * Stops whatever runs as `service` (alp dashboard; for LEGACY_WEB, alp web from before the rename or
135
+ * the Paseo integration from before its own), waiting up to `timeoutMs` for a starting owner to
136
+ * publish what proves it. Resolves with the pid it stopped, or undefined once no live process owns
137
+ * the lock; refuses at once an owner that is foreign or cannot be proven.
138
+ * @param {string} home @param {number} [timeoutMs] @param {Service} [service]
139
+ */
140
+ export async function stopService(home, timeoutMs = 30_000, service = DASHBOARD) {
141
+ const deadline = Date.now() + timeoutMs;
142
+ for (;;) {
143
+ const owner = await serviceOwner(home, service);
144
+ if ('pid' in owner) { await terminate(owner.pid, ownerName(service, owner.app)); return owner.pid; }
145
+ if (!owner.alive) return undefined;
146
+ // Only an owner still starting can become provable; waiting changes nothing else.
147
+ if (owner.kind !== 'transient' || Date.now() >= deadline) throw new Error(`${refusal(home, service)} (${owner.reason}); stop it, then run the command again`);
148
+ await sleep(200);
149
+ }
150
+ }
151
+
152
+ /** The opening of the message for a lock held by a process alp would not stop. @param {string} home @param {Service} [service] */
153
+ export function refusal(home, service = DASHBOARD) {
154
+ const lock = path.join(home, 'integrations', `${service.lock}.lock`);
155
+ return service === DASHBOARD
156
+ ? `${lock} is held by a process that alp cannot prove is alp dashboard, so it was left running`
157
+ : `${lock} is held by a process that alp cannot prove is ${service.what} or the Paseo integration from before its rename, so it was left running`;
158
+ }
159
+
160
+ /**
161
+ * Probes whether the published dashboard URL is live and answering requests.
162
+ * Accepts only loopback HTTP/HTTPS addresses.
163
+ * @param {string | undefined} url
164
+ * @param {number} [timeoutMs]
165
+ */
166
+ export async function isDashboardReady(url, timeoutMs = 1_000) {
167
+ if (typeof url !== 'string' || !url) return false;
168
+ try {
169
+ const parsed = new URL(url);
170
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false;
171
+ if (!['127.0.0.1', 'localhost', '::1', '[::1]'].includes(parsed.hostname)) return false;
172
+ const res = await fetch(parsed.href, { signal: AbortSignal.timeout(timeoutMs) });
173
+ return typeof res.status === 'number' && res.status > 0;
174
+ } catch {
175
+ return false;
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Whether the published file is genuinely claimed by a live alp-dashboard process.
181
+ * If the process is proven foreign (e.g. a reused PID or from another boot) or
182
+ * the URL does not answer HTTP requests, it is never claimed.
183
+ * @param {any} published
184
+ * @param {number | undefined} lockPid
185
+ * @param {any} held
186
+ * @param {number} [timeoutMs]
187
+ */
188
+ export async function isServiceClaimed(published, lockPid, held, timeoutMs = 1_000) {
189
+ if (published?.app !== DASHBOARD.app || published.pid !== lockPid) return false;
190
+ if (held?.kind === 'foreign') return false;
191
+ return isDashboardReady(published.url, timeoutMs);
192
+ }
package/src/desktop.js ADDED
@@ -0,0 +1,122 @@
1
+ import { execFile, spawn } from 'node:child_process';
2
+ import { readFile, stat } from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { UsageError } from './usage.js';
6
+
7
+ /**
8
+ * alp desktop (t-81b0.5): opens ALP's desktop app (apps/desktop, an Electron shell for macOS). The
9
+ * app is looked for, in order:
10
+ * 1. ALP.app in /Applications, then in ~/Applications (macOS), opened with `open`. Only a bundle
11
+ * whose CFBundleIdentifier is DESKTOP_BUNDLE_ID counts: another app of that name (an older ALP
12
+ * desktop app, say) is skipped with a one-line message and the lookup goes on;
13
+ * 2. a checkout named by ALP_DESKTOP_CHECKOUT (the repository root, or its apps/desktop), whose
14
+ * app is built (`bun install && bun run build` in apps/desktop), run with its own Electron;
15
+ * 3. neither: how to get it, and exit 1.
16
+ * Nothing secret passes here: the app asks `alp dashboard --print` for its address itself.
17
+ */
18
+
19
+ /** The bundle id of the packaged app (apps/desktop/electron-builder.yml, appId). */
20
+ export const DESKTOP_BUNDLE_ID = 'com.anhlp.alp.shell';
21
+
22
+ /**
23
+ * The CFBundleIdentifier of the app bundle at `app`, or undefined when it cannot be read. An XML
24
+ * Info.plist (what electron-builder writes) is read directly; any other form through plutil.
25
+ * @param {string} app
26
+ * @returns {Promise<string | undefined>}
27
+ */
28
+ export async function readBundleId(app) {
29
+ const plist = path.join(app, 'Contents', 'Info.plist');
30
+ const text = await readFile(plist, 'utf8').catch(() => undefined);
31
+ if (text === undefined) return undefined;
32
+ if (text.trimStart().startsWith('<')) {
33
+ const match = /<key>CFBundleIdentifier<\/key>\s*<string>([^<]*)<\/string>/.exec(text);
34
+ return match ? match[1].trim() : undefined;
35
+ }
36
+ return new Promise(resolve => {
37
+ execFile('/usr/bin/plutil', ['-extract', 'CFBundleIdentifier', 'raw', '-o', '-', plist], (error, stdout) => resolve(error ? undefined : stdout.trim() || undefined));
38
+ });
39
+ }
40
+
41
+ /** @param {string} file */
42
+ const isDirectory = file => stat(file).then(info => info.isDirectory(), () => false);
43
+ /** @param {string} file */
44
+ const isFile = file => stat(file).then(info => info.isFile(), () => false);
45
+
46
+ /**
47
+ * The desktop app's directory in a checkout: `dir` itself or `dir/apps/desktop`, whichever holds the
48
+ * package named alp-desktop.
49
+ * @param {string} dir
50
+ */
51
+ async function desktopPackage(dir) {
52
+ for (const candidate of [path.join(dir, 'apps', 'desktop'), dir]) {
53
+ const manifest = await readFile(path.join(candidate, 'package.json'), 'utf8').then(text => { try { return JSON.parse(text); } catch { return undefined; } }, () => undefined);
54
+ if (manifest?.name === 'alp-desktop') return candidate;
55
+ }
56
+ return undefined;
57
+ }
58
+
59
+ /**
60
+ * Where the app is and how to start it. Exported for tests.
61
+ * `onSkip` hears about each ALP.app passed over because its bundle id is not DESKTOP_BUNDLE_ID.
62
+ * @param {{ platform?: NodeJS.Platform, home?: string, env?: NodeJS.ProcessEnv, applications?: string[], onSkip?: (message: string) => void }} [options]
63
+ * @returns {Promise<{ kind: 'app', app: string, command: string, args: string[] }
64
+ * | { kind: 'checkout', dir: string, command: string, args: string[] }
65
+ * | { kind: 'missing', reason?: string }>}
66
+ */
67
+ export async function resolveDesktop({ platform = process.platform, home = os.homedir(), env = process.env, applications, onSkip = () => {} } = {}) {
68
+ if (platform === 'darwin') {
69
+ for (const directory of applications ?? ['/Applications', path.join(home, 'Applications')]) {
70
+ const app = path.join(directory, 'ALP.app');
71
+ if (!(await isDirectory(app))) continue;
72
+ const id = await readBundleId(app);
73
+ if (id === DESKTOP_BUNDLE_ID) return { kind: 'app', app, command: 'open', args: [app] };
74
+ onSkip(`Skipped ${app}: its bundle id is ${id ? JSON.stringify(id) : 'unreadable'}, not ${DESKTOP_BUNDLE_ID} (ALP's desktop app).`);
75
+ }
76
+ }
77
+ const checkout = env.ALP_DESKTOP_CHECKOUT;
78
+ if (!checkout) return { kind: 'missing' };
79
+ const dir = await desktopPackage(path.resolve(checkout));
80
+ if (!dir) return { kind: 'missing', reason: `ALP_DESKTOP_CHECKOUT=${checkout} is not an ALP checkout: neither it nor its apps/desktop holds the alp-desktop package.` };
81
+ const electron = path.join(dir, 'node_modules', '.bin', platform === 'win32' ? 'electron.cmd' : 'electron');
82
+ if (!(await isFile(electron)) || !(await isFile(path.join(dir, 'dist', 'main.cjs')))) {
83
+ return { kind: 'missing', reason: `The desktop app in ${dir} is not built: run \`bun install && bun run build\` there, then run alp desktop again.` };
84
+ }
85
+ return { kind: 'checkout', dir, command: electron, args: [dir] };
86
+ }
87
+
88
+ const INSTRUCTIONS = `ALP's desktop app is not installed.
89
+ - Put ALP.app in /Applications (or ~/Applications), or
90
+ - point ALP_DESKTOP_CHECKOUT at an ALP checkout whose apps/desktop is built:
91
+ cd <checkout>/apps/desktop && bun install && bun run build
92
+ ALP_DESKTOP_CHECKOUT=<checkout> alp desktop
93
+ Meanwhile, \`alp dashboard\` opens ALP in your browser.`;
94
+
95
+ /**
96
+ * @param {string[]} args
97
+ * @param {{ resolve?: typeof resolveDesktop, launch?: (command: string, args: string[], env: NodeJS.ProcessEnv) => Promise<void> }} [deps]
98
+ */
99
+ export async function desktopCommand(args, { resolve = resolveDesktop, launch = start } = {}) {
100
+ if (args.length) throw new UsageError();
101
+ const found = await resolve({ onSkip: message => console.error(message) });
102
+ if (found.kind === 'missing') {
103
+ if (found.reason) console.error(found.reason);
104
+ console.error(INSTRUCTIONS);
105
+ process.exitCode = 1;
106
+ return;
107
+ }
108
+ const env = { ...process.env };
109
+ // An agent's shell (and Electron's own tools) may set it; Electron would then run as plain Node.
110
+ delete env.ELECTRON_RUN_AS_NODE;
111
+ await launch(found.command, found.args, env);
112
+ console.log(found.kind === 'app' ? `Opened ${found.app}.` : `Started the desktop app from ${found.dir}.`);
113
+ }
114
+
115
+ /** Starts `command` detached, resolving once it spawned. @param {string} command @param {string[]} args @param {NodeJS.ProcessEnv} env */
116
+ function start(command, args, env) {
117
+ return new Promise((resolve, reject) => {
118
+ const child = spawn(command, args, { stdio: 'ignore', detached: true, env });
119
+ child.once('error', reject);
120
+ child.once('spawn', () => { child.unref(); resolve(); });
121
+ });
122
+ }