@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/interfaces.js CHANGED
@@ -1,51 +1,355 @@
1
- import { spawn } from 'node:child_process';
2
- import { readFile } from 'node:fs/promises';
1
+ import { randomUUID } from 'node:crypto';
2
+ import { execFile, spawn } from 'node:child_process';
3
+ import { readFile, realpath, stat } from 'node:fs/promises';
3
4
  import path from 'node:path';
4
5
  import { parseArgs } from 'node:util';
5
- import { alpHome, lockAlive, readLock, startIntegration } from '@anhlp/alp-client/index';
6
+ import { alpHome, connect, daemonPaths, discoverIntegration, startIntegration } from '@anhlp/alp-client/index';
6
7
  import { UsageError } from './usage.js';
7
8
  import { built, start, running } from './daemon.js';
8
9
  import { DAEMON_ENTRY, distributionEntry } from './paths.js';
10
+ import { entryCommand } from '@anhlp/alp-core/packaged';
11
+ import { isAgentProcess } from '@anhlp/alp-core/tasks';
12
+ import { runRole } from './roles.js';
13
+ import { DASHBOARD, LEGACY_WEB, dashboardEntry, dashboardScript, isDashboardReady, isServiceClaimed, refusal, serviceOwner, stopService } from './dashboard-service.js';
14
+ import { legacyLeftovers, migrateDashboard } from './dashboard-migrate.js';
15
+ import { dashboardSettings } from '@anhlp/alp-core/user-settings';
9
16
 
17
+ /** The Paseo integration (its web app, bridge and relay) runs as integration `paseo`. */
18
+ const PASEO = 'paseo';
10
19
 
11
- async function webCommand(args) {
20
+ /**
21
+ * Starts the Paseo integration. For one release, a home that still has only the descriptor
22
+ * registered before the rename (`integrations/web.json`) keeps working, with a hint to re-register.
23
+ * Exported for tests.
24
+ * @param {string} home
25
+ */
26
+ export async function startPaseoIntegration(home) {
27
+ const entry = await discoverIntegration(PASEO, { home });
28
+ if (!entry) {
29
+ const legacy = path.join(home, 'integrations', 'web.json');
30
+ const legacyEntry = await legacyDescriptorEntry(legacy, home);
31
+ if (legacyEntry) {
32
+ console.error(`Using the Paseo integration registered before its rename (${legacy}); run \`alp-paseo-integration --register\` to register it again.`);
33
+ return startIntegration({ name: PASEO, entry: legacyEntry, home });
34
+ }
35
+ }
36
+ return startIntegration({ name: PASEO, home });
37
+ }
38
+
39
+ /**
40
+ * The entry named by the pre-rename descriptor `<home>/integrations/web.json`, and nothing else: no
41
+ * environment, distribution or PATH lookup, since the name `web` belonged to alp web after that. A relative
42
+ * `main` resolves against the descriptor's directory, then the home, as discovery does.
43
+ * @param {string} file
44
+ * @param {string} home
45
+ */
46
+ async function legacyDescriptorEntry(file, home) {
47
+ // A missing or corrupt descriptor is no registration: the caller then reports the missing package.
48
+ const raw = await readFile(file, 'utf8').then(text => JSON.parse(text)).catch(() => undefined);
49
+ const isFile = candidate => stat(candidate).then(info => info.isFile(), () => false);
50
+ // The fields discovery accepts in a descriptor, in its priority order.
51
+ for (const field of ['main', 'entry', 'path', 'command']) {
52
+ const value = raw?.[field];
53
+ if (typeof value !== 'string' || !value.trim()) continue;
54
+ const candidates = path.isAbsolute(value) ? [value] : [path.resolve(path.dirname(file), value), path.resolve(home, value)];
55
+ for (const candidate of candidates) if (await isFile(candidate)) return candidate;
56
+ }
57
+ return undefined;
58
+ }
59
+
60
+ /** Whether the current working directory is an ALP project: its grant then covers it. */
61
+ async function currentProject() {
62
+ const cwd = process.cwd();
63
+ return await stat(path.join(cwd, '.alp')).then(info => info.isDirectory(), () => false) ? cwd : undefined;
64
+ }
65
+
66
+ /** `--project <cwd>` when the directory `alp dashboard` runs in is an ALP project: its grant then covers it. */
67
+ async function projectArgs() {
68
+ const project = await currentProject();
69
+ return project ? ['--project', project] : [];
70
+ }
71
+
72
+ /**
73
+ * Registers `directory` as a project in alpd via IPC (`project.register`).
74
+ * If alpd cannot be reached or the call fails, this is best-effort.
75
+ * @param {string} home
76
+ * @param {string} directory
77
+ * @param {{ timeoutMs?: number, connectClient?: typeof connect }} [options]
78
+ */
79
+ export async function registerProject(home, directory, { timeoutMs = 5_000, connectClient = connect } = {}) {
80
+ const socket = daemonPaths(home).socket;
81
+ let client;
82
+ let expired = false;
83
+ let timer;
84
+ const work = (async () => {
85
+ const connected = await connectClient(socket, { name: 'alp-cli', version: '1' }, { timeoutMs });
86
+ if (expired) { connected.close(); return; }
87
+ client = connected;
88
+ for (let attempt = 0; attempt < 5 && !expired; attempt++) {
89
+ const list = await client.request('project.list', { limit: 1 }, { timeoutMs }).catch(() => undefined);
90
+ if (expired) return;
91
+ const revision = typeof list?.revision === 'number' ? list.revision : 0;
92
+ try {
93
+ await client.request('project.register', { directory, ifRevision: revision, requestId: randomUUID() }, { timeoutMs });
94
+ break;
95
+ } catch (error) {
96
+ if (error?.data?.reason === 'stale_revision' && attempt < 4) continue;
97
+ break;
98
+ }
99
+ }
100
+ })();
101
+ try {
102
+ // One deadline covers connection/hello and every retry; a late connection is closed above.
103
+ await Promise.race([work.catch(() => {}), new Promise(resolve => {
104
+ timer = setTimeout(() => {
105
+ expired = true;
106
+ try { client?.close(); } catch {}
107
+ resolve(undefined);
108
+ }, timeoutMs);
109
+ })]);
110
+ } finally {
111
+ expired = true;
112
+ clearTimeout(timer);
113
+ try { client?.close(); } catch {}
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Waits until the credential in `<home>/dashboard/credentials.json` contains `project`.
119
+ * Polls for up to `timeoutMs` (default 5,000 ms).
120
+ * @param {string} home
121
+ * @param {string} credentialId
122
+ * @param {string} project
123
+ * @param {{ timeoutMs?: number }} [options]
124
+ */
125
+ async function waitForGrant(home, credentialId, project, { timeoutMs = 5_000 } = {}) {
126
+ const credentialsFile = path.join(home, 'dashboard', 'credentials.json');
127
+ const canonical = await realpath(project).catch(() => project);
128
+ const deadline = Date.now() + timeoutMs;
129
+ while (Date.now() < deadline) {
130
+ try {
131
+ const raw = JSON.parse(await readFile(credentialsFile, 'utf8'));
132
+ const credential = raw?.credentials?.find(c => c.id === credentialId && !c.revokedAt);
133
+ if (credential?.workspaces?.some(w => w.canonical === canonical || w.path === project || w.path === canonical)) {
134
+ return true;
135
+ }
136
+ } catch {}
137
+ await new Promise(resolve => setTimeout(resolve, 25));
138
+ }
139
+ return false;
140
+ }
141
+
142
+ /** Whether settings.json turns alp dashboard off (`dashboard.enabled`, else `web.enabled` from before the rename). @param {string} home */
143
+ async function dashboardDisabled(home) {
144
+ const settings = await readJsonFile(path.join(home, 'settings.json'));
145
+ return dashboardSettings(settings).enabled === false;
146
+ }
147
+
148
+ const DISABLED = 'alp dashboard is disabled by settings ("dashboard.enabled": false).';
149
+
150
+ /** A file's JSON, or undefined when it is missing or not JSON (as before: a broken file counts as none). @param {string} file */
151
+ const readJsonFile = file => readFile(file, 'utf8').then(text => { try { return JSON.parse(text); } catch { return undefined; } }, () => undefined);
152
+ /** @param {string} home */
153
+ const readPublished = home => readJsonFile(path.join(home, DASHBOARD.info));
154
+ /** @param {string} home */
155
+ const readServiceLock = home => readJsonFile(path.join(home, 'integrations', `${DASHBOARD.lock}.lock`));
156
+
157
+ /**
158
+ * The running service as its files and its listener show it, without ps (so also on Windows): the
159
+ * lock names a live pid, dashboard.json names the same pid and is alp-dashboard's, and its address
160
+ * answers. `held` is a live lock owner that is not (yet) that.
161
+ * @param {string} home
162
+ * @returns {Promise<{ pid: number, port: number, url: string } | { held: number } | undefined>}
163
+ */
164
+ async function runningDashboard(home) {
165
+ const lock = await readServiceLock(home);
166
+ if (!Number.isSafeInteger(lock?.pid) || lock.pid <= 0) return undefined;
167
+ try { process.kill(lock.pid, 0); } catch (error) { if (/** @type {any} */ (error)?.code !== 'EPERM') return undefined; }
168
+ const info = await readPublished(home);
169
+ if (info?.app === DASHBOARD.app && info.pid === lock.pid && typeof info.url === 'string' && await isDashboardReady(info.url)) return { pid: info.pid, port: info.port, url: info.url };
170
+ return { held: lock.pid };
171
+ }
172
+
173
+ /** Loopback names `--host` accepts; the service listens on 127.0.0.1 only, which serves both. */
174
+ const LOOPBACK_HOSTS = ['127.0.0.1', 'localhost'];
175
+
176
+ /**
177
+ * Starts alp-dashboard unless it runs and returns the address to open, the token in its fragment
178
+ * (which the browser never sends to a server).
179
+ * @param {string} home @param {string} entry @param {{ port?: number }} [options]
180
+ */
181
+ async function serveDashboard(home, entry, { port } = {}) {
182
+ // A lock held by a process proven not to be alp dashboard: say so now rather than wait for it. A
183
+ // running alp-dashboard (its dashboard.json names the lock's pid and is answering) is left to startIntegration.
184
+ const held = await serviceOwner(home);
185
+ const published = await readPublished(home);
186
+ const lockPid = (await readServiceLock(home))?.pid;
187
+ const claimed = await isServiceClaimed(published, lockPid, held);
188
+ if ('reason' in held && held.alive && held.kind === 'foreign' && !claimed) throw new Error(`${refusal(home)} (${held.reason}). Stop it, then run alp dashboard again.`);
189
+ // `--port` asks for a port; a service already running elsewhere is not silently reused.
190
+ if (port !== undefined && claimed && published.port !== port) {
191
+ throw new Error(`alp dashboard already runs on port ${published.port} (pid ${published.pid}); you asked for port ${port}. Stop it with \`alp dashboard --stop\`, or drop --port to use the running one.`);
192
+ }
193
+ const project = await currentProject();
194
+ let lock;
195
+ try { lock = await startIntegration({ name: DASHBOARD.lock, entry, home, args: [...(project ? ['--project', project] : []), ...(port !== undefined ? ['--port', String(port)] : [])] }); }
196
+ catch (error) {
197
+ // Still held by a live process alp cannot prove: name it, as the wait may have been for it.
198
+ const owner = await serviceOwner(home);
199
+ if ('reason' in owner && owner.alive) throw new Error(`${error?.message ?? error}\n${refusal(home)} (${owner.reason}). If it is not alp dashboard, stop it, then run alp dashboard again.`, { cause: error });
200
+ throw error;
201
+ }
202
+ const info = await readPublished(home);
203
+ if (info?.app !== DASHBOARD.app || info.pid !== lock.pid) {
204
+ const owner = await serviceOwner(home);
205
+ throw new Error(`${refusal(home)}${'reason' in owner ? ` (${owner.reason})` : ''}. Stop pid ${lock.pid}, then run alp dashboard again.`);
206
+ }
207
+ if (typeof info.url !== 'string' || typeof info.token !== 'string' || !(await isDashboardReady(info.url))) {
208
+ throw new Error(`alp dashboard published no address; see ${path.join(home, 'logs', 'integrations', 'alp-dashboard.log')}`);
209
+ }
210
+ if (port !== undefined && info.port !== port) {
211
+ throw new Error(`alp dashboard is running on port ${info.port}, not ${port} (port ${port} was busy or alp dashboard was starting already); it was left running there. Stop it with \`alp dashboard --stop\` and free port ${port}, or drop --port`);
212
+ }
213
+ if (project) {
214
+ await registerProject(home, project);
215
+ await waitForGrant(home, info.credentialId, project);
216
+ }
217
+ return `${info.url}#token=${info.token}`;
218
+ }
219
+
220
+ /** Reports what the migration from `alp web` did, on stderr (stdout carries only the address). @param {Awaited<ReturnType<typeof migrateDashboard>>} report */
221
+ function reportMigration(report) {
222
+ if (report.stopped) console.error(`Stopped ${LEGACY_WEB.what} (pid ${report.stopped}).`);
223
+ if (report.moved.length) console.error(`Moved alp web's files to alp dashboard's names: ${report.moved.join('; ')}`);
224
+ for (const warning of report.warnings) console.error(warning);
225
+ }
226
+
227
+ /**
228
+ * alp dashboard --status, after Hermes' `hermes dashboard --status` (hermes_cli/main_dashboard.py
229
+ * _report_dashboard_status): what runs, or that nothing does; always exit 0, and nothing is changed
230
+ * (the move from `alp web` waits for a command that starts or stops). The address is printed
231
+ * without its token.
232
+ * @param {string} home
233
+ */
234
+ async function statusCommand(home) {
235
+ try {
236
+ const running = await runningDashboard(home);
237
+ if (running && 'url' in running) {
238
+ console.log('1 alp dashboard process running:');
239
+ console.log(` PID ${running.pid} [dashboard]: ${running.url} (port ${running.port})`);
240
+ } else if (running) {
241
+ const owner = await serviceOwner(home);
242
+ console.log(`No alp dashboard running. pid ${running.held} holds ${path.join(home, 'integrations', `${DASHBOARD.lock}.lock`)}${'reason' in owner ? ` (${owner.reason})` : ''}.`);
243
+ } else console.log('No alp dashboard running.');
244
+ if (await dashboardDisabled(home)) console.log(DISABLED);
245
+ const left = await legacyLeftovers(home);
246
+ if (left.legacy?.pid) console.log(`${LEGACY_WEB.what} still runs (pid ${left.legacy.pid}); \`alp dashboard\` or \`alp dashboard --stop\` stops it.`);
247
+ else if (left.legacy) console.log(`${refusal(home, LEGACY_WEB)} (${left.legacy.reason}).`);
248
+ for (const item of left.pending) console.log(`From before the rename to alp dashboard, moved by the next \`alp dashboard\`: ${item}`);
249
+ for (const item of left.kept) console.log(`Left from before the rename to alp dashboard, not used: ${item}`);
250
+ } catch (error) {
251
+ console.log(`alp dashboard could not tell everything: ${error?.message ?? error}`);
252
+ }
253
+ }
254
+
255
+ /**
256
+ * alp dashboard --stop, after Hermes' `hermes dashboard --stop` (hermes_cli/main.py
257
+ * _dashboard_lifecycle_flags): only this ALP home's service (and alp web from before the rename,
258
+ * which the move stops); nothing running is not an error; a process alp cannot prove is the service
259
+ * is left running and the command fails.
260
+ * @param {string} home
261
+ */
262
+ async function stopCommand(home) {
263
+ const report = await migrateDashboard(home);
264
+ reportMigration(report);
265
+ // alp web from before the rename still holds its lock: not stopped, so not a success.
266
+ if (report.held) process.exitCode = 1;
267
+ const owner = await serviceOwner(home);
268
+ if (!owner.alive && !('pid' in owner)) {
269
+ if (!report.stopped) console.log('No alp dashboard running for this ALP home.');
270
+ return;
271
+ }
272
+ const pid = await stopService(home);
273
+ if (pid) console.log(`Stopped alp dashboard (pid ${pid}).`);
274
+ else console.log('No alp dashboard running for this ALP home.');
275
+ }
276
+
277
+ async function dashboardCommand(args) {
278
+ // alp dashboard prints, rotates and pairs with the user's own secrets (t-1c59), and stops the
279
+ // user's service: a process an ALP agent started is refused before anything is read, stopped or printed.
280
+ if (isAgentProcess()) throw new Error('alp dashboard is the user\'s: it prints and rotates the user\'s credential; this process was started by an ALP agent (ALP_AGENT_SESSION is set)');
12
281
  if (args[0] === 'pair') return pairCommand(args.slice(1));
13
- const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { print: { type: 'boolean' } } });
282
+ if (args[0] === 'rotate') return rotateCommand(args.slice(1));
283
+ // alp-dashboard itself in this process; its own options (--service, --rotate, --project DIR, --port N) follow.
284
+ if (args[0] === 'serve') return runRole('dashboard', dashboardScript(), args.slice(1));
285
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
286
+ print: { type: 'boolean' }, 'no-open': { type: 'boolean' }, status: { type: 'boolean' }, stop: { type: 'boolean' },
287
+ port: { type: 'string' }, host: { type: 'string' },
288
+ } });
14
289
  if (positionals.length) throw new UsageError();
15
- const lock = await readLock(alpHome()).catch(() => undefined);
16
- await start();
17
- try {
18
- const settings = JSON.parse(await readFile(path.join(alpHome(),'settings.json'),'utf8'));
19
- if (settings?.web?.enabled === false) throw new Error('ALP web app is disabled by settings ("web.enabled": false).');
20
- } catch (error) { if (/disabled by settings/.test(error?.message ?? '')) throw error; }
21
- // The web app is owned by the optional Paseo integration.
22
- await startIntegration();
23
290
  const home = alpHome();
24
- const file = path.join(home, 'web.json');
25
- let info;
26
- // A fresh integration writes web.json just before it is ready; stale files from daemon or an older pid are rejected.
27
- for (let i = 0; i < 100; i++) {
28
- info = await readFile(file, 'utf8').then(JSON.parse, () => undefined);
29
- let alive = false;
30
- try { if (info?.pid) { process.kill(info.pid, 0); alive = true; } } catch { alive = false; }
31
- let integrationPid = undefined;
32
- try { integrationPid = JSON.parse(await readFile(path.join(home, 'integrations', 'web.lock'), 'utf8'))?.pid; } catch {}
33
- if (info?.token && info?.url && alive && info.pid !== lock?.pid && (!integrationPid || info.pid === integrationPid)) break;
34
- info = undefined;
35
- await new Promise(resolve => setTimeout(resolve, 100));
291
+ // As in Hermes, the lifecycle flags win over the start flags: they report or stop, and exit.
292
+ if (values.status && values.stop) throw new UsageError();
293
+ if (values.status) return statusCommand(home);
294
+ if (values.stop) return stopCommand(home);
295
+ let port;
296
+ if (values.port !== undefined) {
297
+ port = Number(values.port);
298
+ if (!/^\d+$/.test(values.port) || port < 1024 || port > 65535) throw new Error(`--port must be a port from 1024 to 65535, not ${values.port}`);
299
+ }
300
+ // ALP's token is the dashboard's only lock and its gateway accepts only loopback Host and Origin
301
+ // names, so it is never bound beyond this machine (Hermes too refuses a non-loopback bind without
302
+ // an auth provider, which ALP does not have).
303
+ if (values.host !== undefined && !LOOPBACK_HOSTS.includes(values.host)) {
304
+ throw new Error(`alp dashboard listens on this machine only (127.0.0.1): --host ${values.host} is refused. Reach it from another machine through an SSH tunnel to 127.0.0.1.`);
36
305
  }
37
- if (!info) throw new Error(lockAlive(lock) ? 'alpd serves no web app: it is older than this alp (alp daemon restart), or "web": { "enabled": false } is set in ~/.alp/settings.json' : 'alpd started without its web app; see ~/.alp/logs/alpd.log');
38
- // The token rides in the fragment, which the browser never sends to a server.
39
- const url = `${info.url}#token=${info.token}`;
306
+ const entry = dashboardEntry();
307
+ reportMigration(await migrateDashboard(home, { strict: true }));
308
+ if (await dashboardDisabled(home)) throw new Error(DISABLED);
309
+ await start();
310
+ let url = await serveDashboard(home, entry, { port });
311
+ if (values.host === 'localhost') url = url.replace('://127.0.0.1:', '://localhost:');
40
312
  console.log(url);
41
- if (values.print) return;
313
+ if (values.print || values['no-open']) return;
42
314
  const opener = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'explorer' : 'xdg-open';
43
315
  spawn(opener, [url], { stdio: 'ignore', detached: true }).on('error', () => console.error('Open the address above in your browser')).unref();
44
316
  }
45
317
 
46
318
  /**
47
- * alp web pair: the link that pairs Paseo's app on another device with alpd through Paseo's relay
48
- * (ALPD §64). The device then signs in with the token that `alp web --print` shows.
319
+ * alp dashboard rotate: alp dashboard's token is replaced and the old one revoked, so every open
320
+ * page loses access. Only the process holding the dashboard lock writes its credentials, so the
321
+ * service is stopped first; `alp-dashboard.js --rotate` then takes the lock, replaces the credential,
322
+ * records the new token in dashboard.json and releases the lock, and the service starts again with it.
323
+ */
324
+ async function rotateCommand(args) {
325
+ if (args.length) throw new UsageError();
326
+ const entry = dashboardEntry();
327
+ const home = alpHome();
328
+ reportMigration(await migrateDashboard(home, { strict: true }));
329
+ await start();
330
+ const project = await projectArgs();
331
+ for (let attempt = 1; ; attempt++) {
332
+ await stopService(home);
333
+ const rotated = await new Promise(resolve => {
334
+ const rotate = entryCommand(entry, 'dashboard', ['--rotate', ...project]);
335
+ execFile(rotate.command, rotate.args, { env: { ...process.env, ALP_HOME: home }, encoding: 'utf8', timeout: 60_000, killSignal: 'SIGTERM' },
336
+ (error, stdout, stderr) => resolve({ code: error ? (typeof error.code === 'number' ? error.code : 1) : 0, output: `${stderr}${stdout}`.trim() }));
337
+ });
338
+ if (rotated.code === 0) break;
339
+ // Exit 3: alp dashboard started again between the stop and the rotation; stop it once more.
340
+ if (rotated.code !== 3 || attempt >= 3) throw new Error(`alp dashboard could not rotate its token${rotated.output ? `:\n${rotated.output.slice(-2000)}` : ''}`);
341
+ }
342
+ if (await dashboardDisabled(home)) {
343
+ console.log(`alp dashboard has a new token; the old one no longer works. ${DISABLED.replace(/\.$/, '')}, so it was not started.`);
344
+ return;
345
+ }
346
+ console.log(await serveDashboard(home, entry));
347
+ }
348
+
349
+ /**
350
+ * alp dashboard pair: the link that pairs Paseo's app on another device with alpd through Paseo's relay
351
+ * (ALPD §64). The device then signs in with the password this command prints (the token kept in
352
+ * ~/.alp/paseo.json).
49
353
  */
50
354
 
51
355
  /**
@@ -65,24 +369,27 @@ export async function requestPairing(client, params, attempts = 50) {
65
369
  if (!unknown) throw outcome.error;
66
370
  await new Promise(resolve => setTimeout(resolve, 100));
67
371
  }
68
- throw last ?? new Error('alpd did not register web.pairing; run `alp web` to let the integration start, then retry');
372
+ throw last ?? new Error('alpd did not register web.pairing; run `alp dashboard pair` again to let the integration start');
69
373
  }
70
374
 
71
375
  async function pairCommand(args) {
72
376
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { on: { type: 'boolean' }, off: { type: 'boolean' } } });
73
377
  if (positionals.length || (values.on && values.off)) throw new UsageError();
74
378
  await start();
75
- await startIntegration();
379
+ const home = alpHome();
380
+ await startPaseoIntegration(home);
76
381
  const client = await running();
77
382
  try {
78
383
  const pairing = await requestPairing(client, values.on ? { enable: true } : values.off ? { enable: false } : {});
79
384
  if (!pairing.relayEnabled) {
80
- console.log(`The relay is off${values.off ? ' now' : ''}. Turn it on with: alp web pair --on`);
385
+ console.log(`The relay is off${values.off ? ' now' : ''}. Turn it on with: alp dashboard pair --on`);
81
386
  return;
82
387
  }
83
388
  console.log(`Relay ${pairing.endpoint}: ${pairing.connected ? 'connected' : 'connecting'}`);
84
- console.log(`Open this link on the device, or scan the QR code in the web app (Settings → host → Pair device):\n${pairing.url}`);
85
- console.log("When Paseo's app asks for a password, give it alpd's token: the part after #token= in alp web --print.");
389
+ console.log(`Open this link on the device that runs Paseo's app:\n${pairing.url}`);
390
+ const password = await readFile(path.join(home, `${PASEO}.json`), 'utf8').then(text => JSON.parse(text)?.token).catch(() => undefined);
391
+ if (typeof password === 'string' && password) console.log(`When Paseo's app asks for a password, give it: ${password}`);
392
+ else console.log(`When Paseo's app asks for a password, give it the token in ${path.join(home, `${PASEO}.json`)}.`);
86
393
  } finally {
87
394
  client.close();
88
395
  }
@@ -93,8 +400,8 @@ async function pairCommand(args) {
93
400
  async function acpCommand(args) {
94
401
  if (args.length) throw new UsageError();
95
402
  await built();
96
- const { runAcp } = await import(distributionEntry('acp.js'));
403
+ const { runAcp } = /** @type {{ runAcp: (options: { daemonEntry: string }) => Promise<void> }} */ (await import(distributionEntry('acp.js').href));
97
404
  await runAcp({ daemonEntry: DAEMON_ENTRY });
98
405
  }
99
406
 
100
- export { webCommand, pairCommand, acpCommand };
407
+ export { dashboardCommand, pairCommand, acpCommand };
package/src/library.js CHANGED
@@ -4,15 +4,26 @@ import { parseArgs } from 'node:util';
4
4
  import { seedLibrary } from '@anhlp/alp-core/library';
5
5
  import { libraryEntries } from '@anhlp/alp-core/resolver';
6
6
  import { listTeams, resolveTeam } from '@anhlp/alp-core/teams';
7
- import { deleteEntry, duplicateEntry, getEntry, renameEntry, saveEntry } from '@anhlp/alp-core/library-edit';
7
+ import { deleteEntry, duplicateEntry, getEntry, listRetiredSkills, renameEntry, restoreSkill, saveEntry, withSkillName } from '@anhlp/alp-core/library-edit';
8
8
  import { testEntry } from '@anhlp/alp-client/library-test';
9
+ import { formatValidation, validateSkill } from '@anhlp/alp-core/skill-validate';
10
+ import { installPack, listPacks, packStatus } from '@anhlp/alp-core/packs';
9
11
  import { alpHome } from '@anhlp/alp-client/index';
10
12
  import { UsageError } from './usage.js';
11
13
  import { taskProject } from './tasks.js';
12
14
 
13
15
  async function libraryCommand(kind, args) {
14
- const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { project: { type: 'string' }, json: { type: 'boolean' } } });
16
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { project: { type: 'string' }, json: { type: 'boolean' }, ...(kind === 'skills' ? { retired: { type: 'boolean' } } : {}) } });
15
17
  if (positionals.length) throw new UsageError();
18
+ if (values.retired) {
19
+ if (values.project !== undefined) throw new UsageError();
20
+ const rows = await listRetiredSkills({ library: alpHome() });
21
+ if (values.json) { console.log(JSON.stringify(rows)); return; }
22
+ if (!rows.length) { console.log(`No retired skills in ${path.join(alpHome(), 'retired-skills')}`); return; }
23
+ const width = Math.max(...rows.map(row => row.name.length));
24
+ for (const row of rows) console.log(`${row.name.padEnd(width)} ${row.retiredAt} ${row.roles === null ? 'roles not recorded' : `roles: ${row.roles.join(', ') || 'none'}`}${row.agent ? `; by ${row.agent}` : ''}${row.invalid ? `; warning: invalid retired metadata: ${row.invalid}` : ''} ${row.directory}`);
25
+ return;
26
+ }
16
27
  if (kind === 'providers') await seedLibrary(alpHome());
17
28
  // Outside a project only the built-ins and the library apply.
18
29
  const root = path.resolve(values.project ?? process.cwd());
@@ -57,12 +68,11 @@ const EDIT_OPTIONS = {
57
68
  'member-thinking': { type: 'string', multiple: true }, delegate: { type: 'string', multiple: true }, 'max-peers': { type: 'string' },
58
69
  supervisor: { type: 'string' }, 'supervisor-model': { type: 'string' }, 'supervisor-thinking': { type: 'string' }, 'no-supervisor': { type: 'boolean' }, rules: { type: 'string' },
59
70
  // skill, mcp, hook
60
- file: { type: 'string' }, command: { type: 'string' }, arg: { type: 'string', multiple: true }, env: { type: 'string', multiple: true }, cwd: { type: 'string' },
71
+ file: { type: 'string' }, roles: { type: 'string' }, 'no-roles': { type: 'boolean' }, command: { type: 'string' }, arg: { type: 'string', multiple: true }, env: { type: 'string', multiple: true }, cwd: { type: 'string' },
61
72
  url: { type: 'string' }, header: { type: 'string', multiple: true }, event: { type: 'string' }, blocking: { type: 'boolean' }, timeout: { type: 'string' },
62
- 'match-agent': { type: 'string' }, 'match-label': { type: 'string' },
73
+ 'match-agent': { type: 'string' }, 'match-label': { type: 'string' }, strict: { type: 'boolean' },
63
74
  // provider
64
75
  kind: { type: 'string' },
65
- 'read-only-mode': { type: 'string' },
66
76
  models: { type: 'string' },
67
77
  };
68
78
 
@@ -115,7 +125,7 @@ async function edited(kind, name, current, values) {
115
125
  if (values.rules !== undefined) content.houseRules = await readFile(values.rules, 'utf8');
116
126
  } else if (kind === 'skills') {
117
127
  if (values.file !== undefined) content.body = await readFile(values.file, 'utf8');
118
- content.body ??= `---\nname: ${name}\ndescription: When to use this skill.\n---\n\n# ${name}\n\nSteps and checks.\n`;
128
+ content.body ??= `---\nname: ${name}\ndescription: ${JSON.stringify(values.description ?? `What ${name} does. Use when the work it is for comes up.`)}\n---\n\n# ${name}\n\n## When to use\n\n## Workflow\n\n## Verification\n`;
119
129
  } else if (kind === 'mcp') {
120
130
  if (values.command !== undefined || values.url !== undefined) content.server = {};
121
131
  const server = content.server ?? {};
@@ -151,7 +161,7 @@ async function edited(kind, name, current, values) {
151
161
  set(provider, 'label', values.label);
152
162
  set(provider, 'description', values.description);
153
163
  set(provider, 'command', values.command);
154
- set(provider, 'readOnlyMode', values['read-only-mode']);
164
+ delete provider.readOnlyMode; // Drop the retired no-op setting when saving an existing definition.
155
165
  if (values.arg?.length) provider.args = values.arg;
156
166
  if (values.env?.length) provider.env = pairs(values.env, '--env');
157
167
  const models = names(values.models);
@@ -161,11 +171,50 @@ async function edited(kind, name, current, values) {
161
171
  return content;
162
172
  }
163
173
 
174
+ /**
175
+ * alp skill check [name|DIR] [--project [DIR]] [--strict] [--json]: validates skills (Agent Skills
176
+ * format, packages/core/src/skill-validate.js). Without a name, every skill the project and the
177
+ * library hold; a name, the one that applies; a path, that directory. Existing skills are checked in
178
+ * legacy mode (format problems are warnings) unless --strict. Reads only; exit 1 on an error.
179
+ */
180
+ async function checkSkills(name, positionals, values) {
181
+ if (positionals.length > 2) throw new UsageError();
182
+ const root = path.resolve(values.project ?? process.cwd());
183
+ const mode = values.strict ? 'strict' : 'legacy';
184
+ let targets;
185
+ if (name !== undefined && (name.includes('/') || name.includes(path.sep) || name.startsWith('.'))) targets = [path.resolve(name)];
186
+ else {
187
+ const rows = await libraryEntries('skills', root, { library: alpHome() });
188
+ const chosen = name === undefined ? rows : rows.filter(row => row.name === name);
189
+ if (name !== undefined && !chosen.length) throw new Error(`No skill '${name}' in ${path.join(root, '.alp', 'skills')} or ${path.join(alpHome(), 'skills')}`);
190
+ targets = chosen.map(row => path.dirname(row.path));
191
+ }
192
+ const reports = [];
193
+ for (const target of targets) reports.push(await validateSkill(target, { mode }));
194
+ if (values.json) console.log(JSON.stringify(reports));
195
+ else {
196
+ for (const report of reports) console.log(formatValidation(report));
197
+ const failed = reports.filter(report => !report.ok).length;
198
+ const warned = reports.filter(report => report.warnings.length).length;
199
+ console.log(`${reports.length} skill${reports.length === 1 ? '' : 's'} checked (${mode}): ${failed} with errors, ${warned} with warnings.${mode === 'legacy' && warned ? ' Warnings do not stop a skill from loading; fix them when you next edit it.' : ''}`);
200
+ }
201
+ if (reports.some(report => !report.ok)) process.exitCode = 1;
202
+ }
203
+
164
204
  /** alp agent|team|skill|mcp|hook: create, change, copy, rename, remove and test library entries. */
165
205
 
166
206
  async function editCommand(kind, args) {
207
+ if (kind === 'providers' && args.some(arg => arg === '--read-only-mode' || arg.startsWith('--read-only-mode='))) throw new Error('--read-only-mode was removed; delete readOnlyMode from provider JSON and choose the session --mode read-only, workspace-write or full-access. Existing native sessions keep their mode.');
167
208
  const { values, positionals } = parseArgs({ args: projectFlag(args), allowPositionals: true, options: EDIT_OPTIONS });
168
209
  const [action, name, target] = positionals;
210
+ if (kind === 'skills' && action === 'restore') {
211
+ if (!name || positionals.length > 2 || values.project !== undefined || (values.roles !== undefined && values['no-roles'])) throw new UsageError();
212
+ const roles = values['no-roles'] ? [] : names(values.roles);
213
+ const result = await restoreSkill(name, { library: alpHome(), from: values.from, roles });
214
+ console.log(values.json ? JSON.stringify(result) : `Restored ${name} to ${result.restored} from ${result.from}; ${result.roles.length ? `given to ${result.roles.join(', ')}` : 'given to no role'}.`);
215
+ return;
216
+ }
217
+ if (kind === 'skills' && action === 'check') { await checkSkills(name, positionals, values); return; }
169
218
  if (kind === 'providers' && action !== 'add') await seedLibrary(alpHome());
170
219
  const creates = { agents: 'new', teams: 'new', skills: 'new', mcp: 'add', hooks: 'add', providers: 'add' }[kind];
171
220
  if (!name || positionals.length > (['cp', 'mv'].includes(action) ? 3 : 2) || (['cp', 'mv'].includes(action) && !target)) throw new UsageError();
@@ -208,6 +257,8 @@ async function editCommand(kind, args) {
208
257
  let revision = null;
209
258
  if (action === creates) {
210
259
  if (values.from !== undefined) current = (await getEntry(kind, values.from, { root, library: alpHome() })).content;
260
+ // A skill made from another names itself, as its directory does.
261
+ if (kind === 'skills' && current?.body !== undefined) current = { ...current, body: withSkillName(current.body, name) };
211
262
  } else {
212
263
  // Editing an entry that only a lower layer has makes this scope's copy of it.
213
264
  const entry = await getEntry(kind, name, { root, library: alpHome() }).catch(error => { if (error.code === 'NOT_FOUND') throw new Error(`No ${kind} entry '${name}'; create it with alp ${kind.replace(/s$/, '')} ${creates}`); throw error; });
@@ -215,8 +266,15 @@ async function editCommand(kind, args) {
215
266
  current = (own ?? entry).content;
216
267
  revision = own ? own.revision : null;
217
268
  }
218
- const result = await saveEntry(kind, name, await edited(kind, name, current, values), { ...options, revision });
269
+ // A new skill meets the skill format strictly; an edit of an existing one is saved as before, and told what to fix.
270
+ const result = await saveEntry(kind, name, await edited(kind, name, current, values), { ...options, revision, strict: kind === 'skills' && action === creates });
219
271
  done(result, `${action === 'edit' ? 'Saved' : 'Created'} ${name} in ${where}.`);
272
+ if (kind === 'skills' && !values.json) {
273
+ const directory = path.join(scope === 'project' ? path.join(root, '.alp') : alpHome(), 'skills', name);
274
+ const report = await validateSkill(directory);
275
+ const notes = [...(result.warnings ?? []), ...report.errors.map(finding => finding.message), ...report.warnings.map(finding => finding.message)];
276
+ for (const note of [...new Set(notes)]) console.log(`note: ${note}`);
277
+ }
220
278
  }
221
279
 
222
280
  /** alp trust: the workspaces whose hooks run without asking (ALPD §45). */
@@ -240,4 +298,45 @@ async function teamsCommand(args) {
240
298
  }
241
299
  }
242
300
 
243
- export { libraryCommand, projectFlag, pairs, names, EDIT_OPTIONS, edited, editCommand, teamsCommand };
301
+ /**
302
+ * alp packs [--project DIR] [--json]: the optional packs ALP ships, and whether the library or the
303
+ * project has them. alp pack install <id> [--project [DIR]] [--assign] [--json]: copies a pack's
304
+ * skills, agents and teams into the library (or the project's .alp/), keeping any entry already
305
+ * there; --assign (library) gives its suggested skills to roles in role-skills.json.
306
+ */
307
+ async function packsCommand(args) {
308
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { project: { type: 'string' }, json: { type: 'boolean' } } });
309
+ if (positionals.length) throw new UsageError();
310
+ const root = path.resolve(values.project ?? process.cwd());
311
+ const rows = [];
312
+ for (const pack of await listPacks()) rows.push({ ...pack, installed: await packStatus(pack, { root, library: alpHome() }) });
313
+ if (values.json) { console.log(JSON.stringify(rows)); return; }
314
+ const width = Math.max(...rows.map(row => row.id.length));
315
+ for (const row of rows) {
316
+ const contents = [row.skills.length ? `skills: ${row.skills.join(', ')}` : '', row.agents.length ? `agents: ${row.agents.join(', ')}` : '', row.teams.length ? `teams: ${row.teams.join(', ')}` : ''].filter(Boolean).join('; ');
317
+ const where = [row.installed.library ? 'library' : '', row.installed.project ? 'project' : ''].filter(Boolean).join(', ');
318
+ console.log(`${row.id.padEnd(width)} ${row.description}\n${' '.repeat(width)} ${contents}${where ? ` [installed: ${where}]` : ''}`);
319
+ }
320
+ console.log('Install one with: alp pack install <id> [--project] [--assign]');
321
+ }
322
+
323
+ async function packCommand(args) {
324
+ const { values, positionals } = parseArgs({ args: projectFlag(args), allowPositionals: true, options: { project: { type: 'string' }, json: { type: 'boolean' }, assign: { type: 'boolean' } } });
325
+ const [action, id] = positionals;
326
+ if (action !== 'install' || !id || positionals.length > 2) throw new UsageError();
327
+ const scope = values.project !== undefined ? 'project' : 'library';
328
+ const root = values.project !== undefined ? path.resolve(values.project) : undefined;
329
+ if (scope === 'project') await taskProject(root);
330
+ const result = await installPack(id, { scope, root, library: alpHome(), assign: values.assign });
331
+ if (values.json) { console.log(JSON.stringify(result)); return; }
332
+ const where = scope === 'project' ? `the project ${root}` : `your library ${alpHome()}`;
333
+ for (const entry of result.installed) console.log(`installed ${entry.kind.replace(/s$/, '')} ${entry.name} ${entry.path}`);
334
+ for (const entry of result.kept) console.log(`kept ${entry.kind.replace(/s$/, '')} ${entry.name}: one already exists, and stays as it is (${entry.path})`);
335
+ for (const line of result.permissions.set) console.log(`permission ${line} (agent capped by its permission profile)`);
336
+ for (const line of result.permissions.conflicts) console.log(`warning: ${line}`);
337
+ if (result.assigned.length) console.log(`assigned ${result.assigned.join(', ')} in role-skills.json`);
338
+ else if (!values.assign && scope === 'library' && result.installed.some(entry => entry.kind === 'skills')) console.log('No role has these skills yet: rerun with --assign for the pack\'s suggestion, or alp agent edit <agent> --skills a,b.');
339
+ console.log(`Pack ${id} in ${where}. Start a new session (or close and resume) for agents to see it.`);
340
+ }
341
+
342
+ export { libraryCommand, projectFlag, pairs, names, EDIT_OPTIONS, edited, editCommand, teamsCommand, packsCommand, packCommand };
package/src/paths.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { existsSync } from 'node:fs';
2
2
  import { fileURLToPath, pathToFileURL } from 'node:url';
3
3
  import path from 'node:path';
4
+ import { daemonEntry, selfEntry } from '@anhlp/alp-core/packaged';
4
5
 
5
6
  /** Locate artifacts in either the independently shipped CLI or the legacy root build. */
6
7
  export function distributionEntry(name) {
@@ -13,4 +14,11 @@ export function distributionEntry(name) {
13
14
  return candidates.find(candidate => existsSync(candidate)) ?? candidates[0];
14
15
  }
15
16
 
16
- export const DAEMON_ENTRY = fileURLToPath(distributionEntry('alpd.js'));
17
+ /** alpd.js, which `alp daemon run` runs in this process (named through app/current in the ALP bundle). */
18
+ export const DAEMON_SCRIPT = selfEntry(fileURLToPath(distributionEntry('alpd.js')));
19
+
20
+ /**
21
+ * What starts alpd: the bundle's native alpd when it ships one (t-81b0.9), else alpd.js under Node;
22
+ * ALP_NATIVE_DAEMON=0 keeps the Node alpd. Named through app/current in the ALP bundle.
23
+ */
24
+ export const DAEMON_ENTRY = daemonEntry(fileURLToPath(distributionEntry('alpd.js')));