@anhlp/alp-cli 0.0.1-beta.3 → 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.
Files changed (69) hide show
  1. package/dist/THIRD-PARTY-NOTICES.txt +51 -1
  2. package/dist/acp/main.js +1 -1
  3. package/dist/acp.js +300 -92
  4. package/dist/alp-web/THIRD-PARTY-NOTICES.txt +3256 -0
  5. package/dist/alp-web/alp-boundary.json +16 -0
  6. package/dist/alp-web/apple-touch-icon.png +0 -0
  7. package/dist/alp-web/assets/TerminalPanel-CqTsgY-W.js +22 -0
  8. package/dist/alp-web/assets/TerminalPanel-DLuoa74B.css +1 -0
  9. package/dist/alp-web/assets/highlighter-BnicKQ_d.js +18 -0
  10. package/dist/alp-web/assets/index-BMbDUCHW.css +1 -0
  11. package/dist/alp-web/assets/index-B_RFaj2C.js +59 -0
  12. package/dist/alp-web/favicon-attention.svg +6 -0
  13. package/dist/alp-web/favicon-running.svg +6 -0
  14. package/dist/alp-web/favicon.svg +5 -0
  15. package/dist/alp-web/index.html +20 -0
  16. package/dist/alp-web.js +10119 -0
  17. package/dist/alpd.js +30333 -15153
  18. package/dist/backup.js +2 -2
  19. package/dist/build-manifest.json +120 -2
  20. package/dist/cli.js +34 -3
  21. package/dist/daemon.d.ts +1 -1
  22. package/dist/daemon.js +5 -0
  23. package/dist/interfaces.d.ts +22 -2
  24. package/dist/interfaces.js +182 -37
  25. package/dist/paths.d.ts +1 -0
  26. package/dist/paths.js +2 -1
  27. package/dist/roles.d.ts +15 -0
  28. package/dist/roles.js +18 -0
  29. package/dist/schedules.d.ts +2 -0
  30. package/dist/schedules.js +45 -0
  31. package/dist/self-update.d.ts +152 -0
  32. package/dist/self-update.js +390 -0
  33. package/dist/sessions.d.ts +7 -1
  34. package/dist/sessions.js +44 -12
  35. package/dist/tasks.js +22 -8
  36. package/dist/terminal-native/README.md +201 -0
  37. package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
  38. package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
  39. package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
  40. package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
  41. package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  42. package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  43. package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  44. package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  45. package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  46. package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  47. package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
  48. package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  49. package/dist/terminal-native/terminal-owner.c +389 -0
  50. package/dist/terminal.d.ts +13 -0
  51. package/dist/terminal.js +80 -0
  52. package/dist/usage.d.ts +1 -1
  53. package/dist/usage.js +22 -7
  54. package/dist/web-service.d.ts +56 -0
  55. package/dist/web-service.js +143 -0
  56. package/package.json +11 -4
  57. package/src/backup.js +1 -1
  58. package/src/cli.js +40 -4
  59. package/src/daemon.js +3 -0
  60. package/src/interfaces.js +227 -32
  61. package/src/paths.js +3 -1
  62. package/src/roles.js +28 -0
  63. package/src/schedules.js +38 -0
  64. package/src/self-update.js +406 -0
  65. package/src/sessions.js +44 -13
  66. package/src/tasks.js +22 -8
  67. package/src/terminal.js +78 -0
  68. package/src/usage.js +22 -7
  69. package/src/web-service.js +187 -0
@@ -0,0 +1,143 @@
1
+ // packages/cli/src/web-service.js
2
+ import { execFile } from "node:child_process";
3
+ import { existsSync } from "node:fs";
4
+ import { lstat, readFile } from "node:fs/promises";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { promisify } from "node:util";
9
+ import { bootTime, isSameBoot, readLock } from "@anhlp/alp-client/index";
10
+ import { distributionEntry } from "./paths.js";
11
+ import { isPackaged, selfEntry } from "@anhlp/alp-core/packaged";
12
+ var execFileAsync = promisify(execFile);
13
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
14
+ function alpWebScript() {
15
+ const entry = fileURLToPath(distributionEntry("alp-web.js"));
16
+ if (!isPackaged() && !existsSync(entry)) throw new Error(`alp web is not built: ${entry} is missing. Build the CLI (npm run build in the ALP checkout) or reinstall ALP.`);
17
+ return entry;
18
+ }
19
+ var alpWebEntry = () => selfEntry(alpWebScript());
20
+ var readJson = async (file) => JSON.parse(await readFile(file, "utf8"));
21
+ async function processTimes(pid) {
22
+ try {
23
+ const { stdout } = await execFileAsync("ps", ["-o", "etime=", "-p", String(pid)], { encoding: "utf8", timeout: 5e3 });
24
+ const match = /^\s*(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)\s*$/.exec(stdout);
25
+ if (!match) return void 0;
26
+ const [, days = "0", hours = "0", minutes, seconds] = match;
27
+ const elapsed = ((Number(days) * 24 + Number(hours)) * 60 + Number(minutes)) * 60 + Number(seconds);
28
+ return { started: Date.now() - elapsed * 1e3, elapsed };
29
+ } catch {
30
+ return void 0;
31
+ }
32
+ }
33
+ async function webOwner(home) {
34
+ const lockFile = path.join(home, "integrations", "web.lock");
35
+ const infoFile = path.join(home, "web.json");
36
+ let lock, lockInfo;
37
+ try {
38
+ lockInfo = await lstat(lockFile);
39
+ lock = await readJson(lockFile);
40
+ } catch {
41
+ return { reason: `${lockFile} is missing or unreadable`, alive: false };
42
+ }
43
+ if (!lockInfo.isFile() || !Number.isSafeInteger(lock?.pid) || lock.pid <= 0 || typeof lock.bootTime !== "number" || !Number.isFinite(Date.parse(lock.startedAt))) {
44
+ return { reason: `${lockFile} is not a complete integration lock`, alive: false };
45
+ }
46
+ const { pid } = lock;
47
+ try {
48
+ process.kill(pid, 0);
49
+ } catch (error) {
50
+ if (error?.code === "ESRCH") return { reason: `its pid ${pid} has exited`, alive: false };
51
+ if (error?.code === "EPERM") return { reason: `pid ${pid} belongs to another user`, alive: true, kind: "foreign" };
52
+ return { reason: `pid ${pid} cannot be signalled (${error?.code ?? error})`, alive: true, kind: "unknown" };
53
+ }
54
+ const refuse = (reason, kind) => ({ reason, alive: true, kind });
55
+ if (process.platform === "win32") return refuse("alp does not stop it on Windows", "unknown");
56
+ const uid = process.getuid?.();
57
+ if (lockInfo.uid !== uid) return refuse("its lock is not yours", "foreign");
58
+ if (!isSameBoot(lock)) return refuse("its lock is from another boot", "foreign");
59
+ if (pid === process.pid || pid === (await readLock(home).catch(() => void 0))?.pid) return refuse(`pid ${pid} is not an integration`, "foreign");
60
+ const times = await processTimes(pid);
61
+ if (times === void 0) return refuse(`the start time of pid ${pid} is unknown`, "unknown");
62
+ const isReused = typeof lock.startedUptime === "number" ? Math.floor(os.uptime()) - times.elapsed > lock.startedUptime + 2 : times.started > Date.parse(lock.startedAt) + 2e3;
63
+ if (isReused) return refuse(`pid ${pid} started after the lock was written (a reused pid)`, "foreign");
64
+ let info, infoStat;
65
+ try {
66
+ infoStat = await lstat(infoFile);
67
+ info = await readJson(infoFile);
68
+ } catch {
69
+ return refuse(`${infoFile} is missing or unreadable`, "transient");
70
+ }
71
+ if (info?.pid !== pid) return refuse(`${infoFile} names another process than the lock`, "transient");
72
+ if (!infoStat.isFile() || infoStat.uid !== uid) return refuse(`${infoFile} is not yours`, "foreign");
73
+ return { pid, app: info.app };
74
+ }
75
+ async function terminate(pid, what, timeoutMs = 2e4) {
76
+ try {
77
+ process.kill(pid, "SIGTERM");
78
+ } catch (error) {
79
+ if (error?.code === "ESRCH") return;
80
+ throw error;
81
+ }
82
+ const deadline = Date.now() + timeoutMs;
83
+ while (Date.now() < deadline) {
84
+ try {
85
+ process.kill(pid, 0);
86
+ } catch (error) {
87
+ if (error?.code === "ESRCH") return;
88
+ }
89
+ await sleep(100);
90
+ }
91
+ throw new Error(`${what} (pid ${pid}) did not stop within ${timeoutMs / 1e3} s of SIGTERM; stop it, then run the command again`);
92
+ }
93
+ var isAlpWeb = (app) => app === "alp-web";
94
+ var PASEO_BEFORE_RENAME = "The Paseo integration from before its rename";
95
+ async function stopPreRenamePaseo(home) {
96
+ const owner = await webOwner(home);
97
+ if (!("pid" in owner) || isAlpWeb(owner.app)) return void 0;
98
+ await terminate(owner.pid, PASEO_BEFORE_RENAME);
99
+ return owner.pid;
100
+ }
101
+ async function stopWebService(home, timeoutMs = 3e4) {
102
+ const deadline = Date.now() + timeoutMs;
103
+ for (; ; ) {
104
+ const owner = await webOwner(home);
105
+ if ("pid" in owner) {
106
+ await terminate(owner.pid, isAlpWeb(owner.app) ? "alp web" : PASEO_BEFORE_RENAME);
107
+ return owner.pid;
108
+ }
109
+ if (!owner.alive) return void 0;
110
+ if (owner.kind !== "transient" || Date.now() >= deadline) throw new Error(`${refusal(home)} (${owner.reason}); stop it, then run the command again`);
111
+ await sleep(200);
112
+ }
113
+ }
114
+ function refusal(home) {
115
+ return `${path.join(home, "integrations", "web.lock")} is held by a process that alp cannot prove is alp web or the Paseo integration from before its rename, so it was left running`;
116
+ }
117
+ async function isWebReady(url, timeoutMs = 1e3) {
118
+ if (typeof url !== "string" || !url) return false;
119
+ try {
120
+ const parsed = new URL(url);
121
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
122
+ if (!["127.0.0.1", "localhost", "::1", "[::1]"].includes(parsed.hostname)) return false;
123
+ const res = await fetch(parsed.href, { signal: AbortSignal.timeout(timeoutMs) });
124
+ return typeof res.status === "number" && res.status > 0;
125
+ } catch {
126
+ return false;
127
+ }
128
+ }
129
+ async function isWebClaimed(published, lockPid, held, timeoutMs = 1e3) {
130
+ if (published?.app !== "alp-web" || published.pid !== lockPid) return false;
131
+ if (held?.kind === "foreign") return false;
132
+ return isWebReady(published.url, timeoutMs);
133
+ }
134
+ export {
135
+ alpWebEntry,
136
+ alpWebScript,
137
+ isWebClaimed,
138
+ isWebReady,
139
+ refusal,
140
+ stopPreRenamePaseo,
141
+ stopWebService,
142
+ webOwner
143
+ };
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "@anhlp/alp-cli",
3
- "version": "0.0.1-beta.3",
3
+ "version": "0.0.1-beta.6",
4
4
  "type": "module",
5
5
  "description": "ALP cli module",
6
6
  "files": [
7
7
  "src",
8
+ "!src/web",
8
9
  "dist",
9
10
  "NOTICE"
10
11
  ],
@@ -126,9 +127,9 @@
126
127
  "node": ">=22.12"
127
128
  },
128
129
  "dependencies": {
129
- "@anhlp/alp-core": "0.0.1-beta.3",
130
- "@anhlp/alp-client": "0.0.1-beta.3",
131
- "@anhlp/alp-protocol": "0.0.1-beta.3",
130
+ "@anhlp/alp-core": "0.0.1-beta.6",
131
+ "@anhlp/alp-client": "0.0.1-beta.6",
132
+ "@anhlp/alp-protocol": "0.0.1-beta.6",
132
133
  "smol-toml": "1.9.0",
133
134
  "@agentclientprotocol/sdk": "1.7.0",
134
135
  "@anthropic-ai/claude-agent-sdk": "^0.3.292"
@@ -155,5 +156,11 @@
155
156
  },
156
157
  "bin": {
157
158
  "alp": "dist/cli.js"
159
+ },
160
+ "optionalDependencies": {
161
+ "node-pty": "1.2.0-beta.15"
162
+ },
163
+ "devDependencies": {
164
+ "@anhlp/alp-gateway": "0.0.1-beta.6"
158
165
  }
159
166
  }
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
@@ -6,19 +6,55 @@ import { scrubText } from '@anhlp/alp-core/log';
6
6
  import { USAGE, UsageError } from './usage.js';
7
7
  import { project, permissionsCommand, trustCommand, language, verify, doctor } from './projects.js';
8
8
  import { daemon } from './daemon.js';
9
- import { run, ps, attach, send, questions, answer, top, log, board, pause, resume, recall, interrupt } from './sessions.js';
9
+ import { run, ps, attach, send, questions, answer, top, log, board, models, pause, resume, recall, interrupt, compact } from './sessions.js';
10
10
  import { libraryCommand, editCommand, teamsCommand } from './library.js';
11
+ import { scheduleCommand } from './schedules.js';
11
12
  import { tasksCommand, formulaCommand, taskCommand } from './tasks.js';
12
13
  import { webCommand, acpCommand } from './interfaces.js';
13
14
  import { backupCommand, restoreCommand } from './backup.js';
15
+ import { terminalCommand } from './terminal.js';
16
+ import { bridgeCommand } from './roles.js';
17
+ import { cleanupOldExecutable, selfUpdate } from './self-update.js';
18
+ import { executablePath, packagedInfo } from '@anhlp/alp-core/packaged';
19
+ import { connect, lockAlive, readLock } from '@anhlp/alp-client/index';
14
20
 
15
- 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 };
21
+ /** The version of this alp: the executable's, the build's, or the package's. */
22
+ function alpVersion() {
23
+ /* global __ALP_VERSION__ */
24
+ return packagedInfo()?.version ?? (typeof __ALP_VERSION__ === 'string' ? __ALP_VERSION__ : JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
25
+ }
26
+
27
+ /** The running alpd's version and live sessions, if one runs for this ALP_HOME. */
28
+ async function runningDaemon() {
29
+ const lock = await readLock(alpHome());
30
+ if (!lockAlive(lock)) return undefined;
31
+ const client = await connect(lock.socket, { name: 'alp-cli', version: '1' }).catch(() => undefined);
32
+ if (!client) return { version: lock.version };
33
+ try {
34
+ const status = await client.request('daemon.status');
35
+ return { version: status.version ?? lock.version, sessions: status.sessions };
36
+ } catch {
37
+ return { version: lock.version };
38
+ } finally {
39
+ client.close();
40
+ }
41
+ }
42
+
43
+ /** alp update: the executable's self-update (t-1e02 P3); the template upgrade is alp update-template. */
44
+ async function updateCommand(args) {
45
+ const code = await selfUpdate(args, { packaged: packagedInfo() !== undefined, version: alpVersion(), daemon: runningDaemon });
46
+ if (code) process.exitCode = code;
47
+ }
48
+
49
+ // A Windows update leaves the previous alp.exe as alp.old.exe: it can only go once that process ended.
50
+ { const executable = executablePath(); if (executable) cleanupOldExecutable(executable); }
51
+
52
+ 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, 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, web: webCommand, backup: backupCommand, restore: restoreCommand, terminal: terminalCommand, bridge: bridgeCommand };
16
53
  const [command, ...args] = process.argv.slice(2);
17
54
  try {
18
55
  if (command === '--version') {
19
56
  // Published builds inject their package version; source execution reads the same metadata.
20
- /* global __ALP_VERSION__ */
21
- console.log(typeof __ALP_VERSION__ === 'string' ? __ALP_VERSION__ : JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
57
+ console.log(alpVersion());
22
58
  } else {
23
59
  if (!Object.hasOwn(commands, command)) throw new UsageError();
24
60
  await commands[command](args);
package/src/daemon.js CHANGED
@@ -6,6 +6,7 @@ import { alpHome, connect, lockAlive, readLock, withDaemonLifecycle } from '@anh
6
6
  import { scrubText } from '@anhlp/alp-core/log';
7
7
  import { UsageError } from './usage.js';
8
8
  import { DAEMON_ENTRY } from './paths.js';
9
+ import { runRole } from './roles.js';
9
10
 
10
11
  async function built() {
11
12
  try {
@@ -60,6 +61,8 @@ async function stop() {
60
61
  }
61
62
 
62
63
  async function daemon([action, ...rest]) {
64
+ // alpd itself in this process; its own options (--detach, --service, --startup-timeout=MS) follow.
65
+ if (action === 'run') { await built(); return runRole('daemon', DAEMON_ENTRY, rest); }
63
66
  if (rest.length && !(action === 'status' && rest.length === 1 && rest[0] === '--json')) throw new UsageError();
64
67
  if (action === 'start') {
65
68
  const socket = await start();
package/src/interfaces.js CHANGED
@@ -1,51 +1,242 @@
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, packagedInfo } from '@anhlp/alp-core/packaged';
11
+ import { runRole } from './roles.js';
12
+ import { alpWebEntry, alpWebScript, isWebClaimed, isWebReady, refusal, stopPreRenamePaseo, stopWebService, webOwner } from './web-service.js';
9
13
 
14
+ /** The Paseo integration (its web app, bridge and relay) runs as integration `paseo`. */
15
+ const PASEO = 'paseo';
16
+ /** alp-web (packages/cli/src/web), the service behind `alp web`, runs as integration `web`. */
17
+ const WEB = 'web';
18
+
19
+ /**
20
+ * Starts the Paseo integration. For one release, a home that still has only the descriptor
21
+ * registered before the rename (`integrations/web.json`) keeps working, with a hint to re-register.
22
+ * Exported for tests.
23
+ * @param {string} home
24
+ */
25
+ export async function startPaseoIntegration(home) {
26
+ const entry = await discoverIntegration(PASEO, { home });
27
+ if (!entry) {
28
+ const legacy = path.join(home, 'integrations', 'web.json');
29
+ const legacyEntry = await legacyDescriptorEntry(legacy, home);
30
+ if (legacyEntry) {
31
+ console.error(`Using the Paseo integration registered before its rename (${legacy}); run \`alp-paseo-integration --register\` to register it again.`);
32
+ return startIntegration({ name: PASEO, entry: legacyEntry, home });
33
+ }
34
+ }
35
+ return startIntegration({ name: PASEO, home });
36
+ }
37
+
38
+ /**
39
+ * The entry named by the pre-rename descriptor `<home>/integrations/web.json`, and nothing else: no
40
+ * environment, distribution or PATH lookup, since the name `web` now belongs to alp-web. A relative
41
+ * `main` resolves against the descriptor's directory, then the home, as discovery does.
42
+ * @param {string} file
43
+ * @param {string} home
44
+ */
45
+ async function legacyDescriptorEntry(file, home) {
46
+ // A missing or corrupt descriptor is no registration: the caller then reports the missing package.
47
+ const raw = await readFile(file, 'utf8').then(text => JSON.parse(text)).catch(() => undefined);
48
+ const isFile = candidate => stat(candidate).then(info => info.isFile(), () => false);
49
+ // The fields discovery accepts in a descriptor, in its priority order.
50
+ for (const field of ['main', 'entry', 'path', 'command']) {
51
+ const value = raw?.[field];
52
+ if (typeof value !== 'string' || !value.trim()) continue;
53
+ const candidates = path.isAbsolute(value) ? [value] : [path.resolve(path.dirname(file), value), path.resolve(home, value)];
54
+ for (const candidate of candidates) if (await isFile(candidate)) return candidate;
55
+ }
56
+ return undefined;
57
+ }
58
+
59
+ /** Whether the current working directory is an ALP project: its grant then covers it. */
60
+ async function currentProject() {
61
+ const cwd = process.cwd();
62
+ return await stat(path.join(cwd, '.alp')).then(info => info.isDirectory(), () => false) ? cwd : undefined;
63
+ }
64
+
65
+ /** `--project <cwd>` when the directory `alp web` runs in is an ALP project: its grant then covers it. */
66
+ async function projectArgs() {
67
+ const project = await currentProject();
68
+ return project ? ['--project', project] : [];
69
+ }
70
+
71
+ /**
72
+ * Registers `directory` as a project in alpd via IPC (`project.register`).
73
+ * If alpd cannot be reached or the call fails, this is best-effort.
74
+ * @param {string} home
75
+ * @param {string} directory
76
+ * @param {{ timeoutMs?: number, connectClient?: typeof connect }} [options]
77
+ */
78
+ export async function registerProject(home, directory, { timeoutMs = 5_000, connectClient = connect } = {}) {
79
+ const socket = daemonPaths(home).socket;
80
+ let client;
81
+ let expired = false;
82
+ let timer;
83
+ const work = (async () => {
84
+ const connected = await connectClient(socket, { name: 'alp-cli', version: '1' }, { timeoutMs });
85
+ if (expired) { connected.close(); return; }
86
+ client = connected;
87
+ for (let attempt = 0; attempt < 5 && !expired; attempt++) {
88
+ const list = await client.request('project.list', { limit: 1 }, { timeoutMs }).catch(() => undefined);
89
+ if (expired) return;
90
+ const revision = typeof list?.revision === 'number' ? list.revision : 0;
91
+ try {
92
+ await client.request('project.register', { directory, ifRevision: revision, requestId: randomUUID() }, { timeoutMs });
93
+ break;
94
+ } catch (error) {
95
+ if (error?.data?.reason === 'stale_revision' && attempt < 4) continue;
96
+ break;
97
+ }
98
+ }
99
+ })();
100
+ try {
101
+ // One deadline covers connection/hello and every retry; a late connection is closed above.
102
+ await Promise.race([work.catch(() => {}), new Promise(resolve => {
103
+ timer = setTimeout(() => {
104
+ expired = true;
105
+ try { client?.close(); } catch {}
106
+ resolve(undefined);
107
+ }, timeoutMs);
108
+ })]);
109
+ } finally {
110
+ expired = true;
111
+ clearTimeout(timer);
112
+ try { client?.close(); } catch {}
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Waits until the credential in `<home>/web/credentials.json` contains `project`.
118
+ * Polls for up to `timeoutMs` (default 5,000 ms).
119
+ * @param {string} home
120
+ * @param {string} credentialId
121
+ * @param {string} project
122
+ * @param {{ timeoutMs?: number }} [options]
123
+ */
124
+ async function waitForGrant(home, credentialId, project, { timeoutMs = 5_000 } = {}) {
125
+ const credentialsFile = path.join(home, 'web', 'credentials.json');
126
+ const canonical = await realpath(project).catch(() => project);
127
+ const deadline = Date.now() + timeoutMs;
128
+ while (Date.now() < deadline) {
129
+ try {
130
+ const raw = JSON.parse(await readFile(credentialsFile, 'utf8'));
131
+ const credential = raw?.credentials?.find(c => c.id === credentialId && !c.revokedAt);
132
+ if (credential?.workspaces?.some(w => w.canonical === canonical || w.path === project || w.path === canonical)) {
133
+ return true;
134
+ }
135
+ } catch {}
136
+ await new Promise(resolve => setTimeout(resolve, 25));
137
+ }
138
+ return false;
139
+ }
140
+
141
+ /** Whether settings.json turns alp web off. @param {string} home */
142
+ async function webDisabled(home) {
143
+ const settings = await readFile(path.join(home, 'settings.json'), 'utf8').then(text => JSON.parse(text), () => undefined);
144
+ return settings?.web?.enabled === false;
145
+ }
146
+
147
+ const DISABLED = 'alp web is disabled by settings ("web.enabled": false).';
148
+
149
+ /**
150
+ * Starts alp-web unless it runs and returns the address to open, the token in its fragment (which
151
+ * the browser never sends to a server). The Paseo integration from before its rename, still running
152
+ * as integration `web`, is stopped first.
153
+ * @param {string} home @param {string} entry
154
+ */
155
+ async function serveWeb(home, entry) {
156
+ await stopPreRenamePaseo(home);
157
+ // A lock held by a process proven not to be alp web: say so now rather than wait for it. A
158
+ // running alp-web (its web.json names the lock's pid and is answering) is left to startIntegration.
159
+ const held = await webOwner(home);
160
+ const published = await readFile(path.join(home, 'web.json'), 'utf8').then(text => JSON.parse(text), () => undefined);
161
+ const lockPid = await readFile(path.join(home, 'integrations', 'web.lock'), 'utf8').then(text => JSON.parse(text)?.pid, () => undefined);
162
+ const claimed = await isWebClaimed(published, lockPid, held);
163
+ if ('reason' in held && held.alive && held.kind === 'foreign' && !claimed) throw new Error(`${refusal(home)} (${held.reason}). Stop it, then run alp web again.`);
164
+ const project = await currentProject();
165
+ let lock;
166
+ try { lock = await startIntegration({ name: WEB, entry, home, args: project ? ['--project', project] : [] }); }
167
+ catch (error) {
168
+ // Still held by a live process alp cannot prove: name it, as the wait may have been for it.
169
+ const owner = await webOwner(home);
170
+ if ('reason' in owner && owner.alive) throw new Error(`${error?.message ?? error}\n${refusal(home)} (${owner.reason}). If it is not alp web, stop it, then run alp web again.`, { cause: error });
171
+ throw error;
172
+ }
173
+ const info = await readFile(path.join(home, 'web.json'), 'utf8').then(text => JSON.parse(text), () => undefined);
174
+ if (info?.app !== 'alp-web' || info.pid !== lock.pid) {
175
+ const owner = await webOwner(home);
176
+ throw new Error(`${refusal(home)}${'reason' in owner ? ` (${owner.reason})` : ''}. Stop pid ${lock.pid}, then run alp web again.`);
177
+ }
178
+ if (typeof info.url !== 'string' || typeof info.token !== 'string' || !(await isWebReady(info.url))) {
179
+ throw new Error(`alp web published no address; see ${path.join(home, 'logs', 'integrations', 'alp-web.log')}`);
180
+ }
181
+ if (project) {
182
+ await registerProject(home, project);
183
+ await waitForGrant(home, info.credentialId, project);
184
+ }
185
+ return `${info.url}#token=${info.token}`;
186
+ }
10
187
 
11
188
  async function webCommand(args) {
12
189
  if (args[0] === 'pair') return pairCommand(args.slice(1));
190
+ if (args[0] === 'rotate') return rotateCommand(args.slice(1));
191
+ // alp-web itself in this process; its own options (--service, --rotate, --project DIR) follow.
192
+ if (args[0] === 'serve') return runRole('web', alpWebScript(), args.slice(1));
13
193
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { print: { type: 'boolean' } } });
14
194
  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();
195
+ const entry = alpWebEntry();
23
196
  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));
36
- }
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}`;
197
+ if (await webDisabled(home)) throw new Error(DISABLED);
198
+ await start();
199
+ const url = await serveWeb(home, entry);
40
200
  console.log(url);
41
201
  if (values.print) return;
42
202
  const opener = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'explorer' : 'xdg-open';
43
203
  spawn(opener, [url], { stdio: 'ignore', detached: true }).on('error', () => console.error('Open the address above in your browser')).unref();
44
204
  }
45
205
 
206
+ /**
207
+ * alp web rotate: alp web's token is replaced and the old one revoked, so every open page loses
208
+ * access. Only the process holding the web lock writes alp web's credentials, so the service is
209
+ * stopped first; `alp-web.js --rotate` then takes the lock, replaces the credential, records the
210
+ * new token in web.json and releases the lock, and the service starts again with it.
211
+ */
212
+ async function rotateCommand(args) {
213
+ if (args.length) throw new UsageError();
214
+ const entry = alpWebEntry();
215
+ const home = alpHome();
216
+ await start();
217
+ const project = await projectArgs();
218
+ for (let attempt = 1; ; attempt++) {
219
+ await stopWebService(home);
220
+ const rotated = await new Promise(resolve => {
221
+ const rotate = entryCommand(entry, 'web', ['--rotate', ...project]);
222
+ execFile(rotate.command, rotate.args, { env: { ...process.env, ALP_HOME: home }, encoding: 'utf8', timeout: 60_000, killSignal: 'SIGTERM' },
223
+ (error, stdout, stderr) => resolve({ code: error ? (typeof error.code === 'number' ? error.code : 1) : 0, output: `${stderr}${stdout}`.trim() }));
224
+ });
225
+ if (rotated.code === 0) break;
226
+ // Exit 3: alp web started again between the stop and the rotation; stop it once more.
227
+ if (rotated.code !== 3 || attempt >= 3) throw new Error(`alp web could not rotate its token${rotated.output ? `:\n${rotated.output.slice(-2000)}` : ''}`);
228
+ }
229
+ if (await webDisabled(home)) {
230
+ console.log(`alp web has a new token; the old one no longer works. ${DISABLED.replace(/\.$/, '')}, so it was not started.`);
231
+ return;
232
+ }
233
+ console.log(await serveWeb(home, entry));
234
+ }
235
+
46
236
  /**
47
237
  * 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.
238
+ * (ALPD §64). The device then signs in with the password this command prints (the token kept in
239
+ * ~/.alp/paseo.json).
49
240
  */
50
241
 
51
242
  /**
@@ -72,7 +263,8 @@ async function pairCommand(args) {
72
263
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { on: { type: 'boolean' }, off: { type: 'boolean' } } });
73
264
  if (positionals.length || (values.on && values.off)) throw new UsageError();
74
265
  await start();
75
- await startIntegration();
266
+ const home = alpHome();
267
+ await startPaseoIntegration(home);
76
268
  const client = await running();
77
269
  try {
78
270
  const pairing = await requestPairing(client, values.on ? { enable: true } : values.off ? { enable: false } : {});
@@ -81,8 +273,10 @@ async function pairCommand(args) {
81
273
  return;
82
274
  }
83
275
  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.");
276
+ console.log(`Open this link on the device that runs Paseo's app:\n${pairing.url}`);
277
+ const password = await readFile(path.join(home, `${PASEO}.json`), 'utf8').then(text => JSON.parse(text)?.token).catch(() => undefined);
278
+ if (typeof password === 'string' && password) console.log(`When Paseo's app asks for a password, give it: ${password}`);
279
+ else console.log(`When Paseo's app asks for a password, give it the token in ${path.join(home, `${PASEO}.json`)}.`);
86
280
  } finally {
87
281
  client.close();
88
282
  }
@@ -93,7 +287,8 @@ async function pairCommand(args) {
93
287
  async function acpCommand(args) {
94
288
  if (args.length) throw new UsageError();
95
289
  await built();
96
- const { runAcp } = await import(distributionEntry('acp.js'));
290
+ const acp = packagedInfo()?.roles?.acp;
291
+ const { runAcp } = /** @type {{ runAcp: (options: { daemonEntry: string }) => Promise<void> }} */ (acp ? await acp() : await import(distributionEntry('acp.js').href));
97
292
  await runAcp({ daemonEntry: DAEMON_ENTRY });
98
293
  }
99
294
 
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 { 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,5 @@ 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
+ /** What starts alpd: alpd.js under Node, or the ALP executable itself (`alp daemon run`). */
18
+ export const DAEMON_ENTRY = selfEntry(fileURLToPath(distributionEntry('alpd.js')));
package/src/roles.js ADDED
@@ -0,0 +1,28 @@
1
+ import { pathToFileURL } from 'node:url';
2
+ import { runBridge } from '@anhlp/alp-core/bridges';
3
+ import { packagedInfo } from '@anhlp/alp-core/packaged';
4
+ import { UsageError } from './usage.js';
5
+
6
+ /**
7
+ * The role subcommands (t-1e02): `alp daemon run`, `alp web serve` and `alp bridge acp|antigravity`
8
+ * run alpd, alp-web and the MCP bridges in this process. The ALP executable starts its own roles
9
+ * this way, since it cannot run a script path; under Node they import the same scripts that
10
+ * `node alpd.js` and `node alp-web.js` run.
11
+ *
12
+ * The role's module reads its options from process.argv as when run directly, so argv is rewritten
13
+ * to `[runtime, entry, ...args]` before the module loads.
14
+ * @param {'daemon' | 'web' | 'acp'} role
15
+ * @param {string} file the role's script beside this CLI
16
+ * @param {string[]} args
17
+ */
18
+ export async function runRole(role, file, args) {
19
+ process.argv = [process.argv[0], file, ...args];
20
+ const load = packagedInfo()?.roles?.[role];
21
+ return load ? load() : import(pathToFileURL(file).href);
22
+ }
23
+
24
+ /** alp bridge acp|antigravity: the stdio MCP bridge an agent CLI starts to reach alpd's tools. @param {string[]} args */
25
+ export function bridgeCommand(args) {
26
+ if (args.length !== 1 || !['acp', 'antigravity'].includes(args[0])) throw new UsageError();
27
+ runBridge(args[0]);
28
+ }
@@ -0,0 +1,38 @@
1
+ import path from 'node:path';
2
+ import { parseArgs } from 'node:util';
3
+ import { running } from './daemon.js';
4
+ import { UsageError } from './usage.js';
5
+
6
+ /** One-shot continuations of an existing root session; timestamps need an explicit offset. */
7
+ export async function scheduleCommand(args) {
8
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
9
+ project: { type: 'string' }, session: { type: 'string' }, at: { type: 'string' },
10
+ prompt: { type: 'string' }, status: { type: 'string' }, json: { type: 'boolean' },
11
+ } });
12
+ const [action, id, ...extra] = positionals;
13
+ if (!['create', 'list', 'show', 'cancel'].includes(action) || extra.length) throw new UsageError();
14
+ if ((action === 'show' || action === 'cancel') ? !id : !!id) throw new UsageError();
15
+ if (action !== 'create' && (values.session || values.at || values.prompt)) throw new UsageError();
16
+ if (action !== 'list' && values.status) throw new UsageError();
17
+ if (action === 'create' && (!values.session || !values.prompt?.trim() ||
18
+ !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:\d{2})$/.test(values.at ?? '') ||
19
+ !Number.isFinite(Date.parse(values.at)))) throw new Error('create needs --session, --prompt and --at ISO timestamp with Z or a UTC offset (for example 2026-10-20T16:00:00+07:00)');
20
+ const projectRoot = path.resolve(values.project ?? process.cwd());
21
+ const params = action === 'create'
22
+ ? { projectRoot, sessionId: values.session, dueAt: values.at, prompt: values.prompt }
23
+ : { projectRoot, ...(id ? { id } : {}), ...(values.status ? { status: values.status } : {}) };
24
+ const client = await running();
25
+ try {
26
+ const result = await client.request(`schedule.${action === 'show' ? 'get' : action}`, params);
27
+ if (values.json) { console.log(JSON.stringify(result)); return; }
28
+ const jobs = result.jobs ?? [result.job];
29
+ if (!jobs.length) console.log('No scheduled continuations');
30
+ for (const job of jobs) {
31
+ console.log(`${job.id} ${job.status} ${job.dueAt} session ${job.sessionId}`);
32
+ console.log(` ${job.prompt}`);
33
+ if (job.attemptedAt) console.log(` attempted ${job.attemptedAt}; attempts ${job.attempts}; late ${job.lateByMs ?? 0} ms`);
34
+ for (const field of ['deliveredAt', 'failedAt', 'cancelledAt']) if (job[field]) console.log(` ${field}: ${job[field]}`);
35
+ if (job.lastError) console.log(` ${job.lastError.code ?? 'error'}: ${job.lastError.message}`);
36
+ }
37
+ } finally { client.close(); }
38
+ }