@anhlp/alp-cli 0.0.0-beta.2 → 0.0.1-beta.4

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 (45) hide show
  1. package/dist/THIRD-PARTY-NOTICES.txt +25 -0
  2. package/dist/acp/main.js +1 -1
  3. package/dist/acp.js +139 -23
  4. package/dist/alp-web/THIRD-PARTY-NOTICES.txt +2590 -0
  5. package/dist/alp-web/alp-boundary.json +15 -0
  6. package/dist/alp-web/apple-touch-icon.png +0 -0
  7. package/dist/alp-web/assets/TerminalPanel-DLuoa74B.css +1 -0
  8. package/dist/alp-web/assets/TerminalPanel-PrU2l3u5.js +16 -0
  9. package/dist/alp-web/assets/index-BJdBTDFX.css +1 -0
  10. package/dist/alp-web/assets/index-DpfiPv5s.js +52 -0
  11. package/dist/alp-web/favicon-attention.svg +6 -0
  12. package/dist/alp-web/favicon-running.svg +6 -0
  13. package/dist/alp-web/favicon.svg +5 -0
  14. package/dist/alp-web/index.html +20 -0
  15. package/dist/alp-web.js +9640 -0
  16. package/dist/alpd.js +10897 -3514
  17. package/dist/backup.js +2 -2
  18. package/dist/build-manifest.json +99 -1
  19. package/dist/cli.js +9 -3
  20. package/dist/daemon.js +6 -2
  21. package/dist/interfaces.d.ts +9 -1
  22. package/dist/interfaces.js +99 -39
  23. package/dist/schedules.d.ts +2 -0
  24. package/dist/schedules.js +45 -0
  25. package/dist/sessions.d.ts +3 -1
  26. package/dist/sessions.js +22 -11
  27. package/dist/terminal.d.ts +8 -0
  28. package/dist/terminal.js +79 -0
  29. package/dist/usage.d.ts +1 -1
  30. package/dist/usage.js +8 -2
  31. package/dist/web-service.d.ts +38 -0
  32. package/dist/web-service.js +119 -0
  33. package/package.json +10 -4
  34. package/src/backup.js +1 -1
  35. package/src/cli.js +12 -3
  36. package/src/daemon.js +8 -3
  37. package/src/interfaces.js +136 -31
  38. package/src/schedules.js +38 -0
  39. package/src/sessions.js +21 -11
  40. package/src/terminal.js +77 -0
  41. package/src/usage.js +8 -2
  42. package/src/web/grant.js +204 -0
  43. package/src/web/main.js +285 -0
  44. package/src/web/serve.js +144 -0
  45. package/src/web-service.js +143 -0
@@ -0,0 +1,79 @@
1
+ // packages/cli/src/terminal.js
2
+ import { randomUUID } from "node:crypto";
3
+ import { chmod, lstat, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { alpHome } from "@anhlp/alp-client/index";
7
+ import { UsageError } from "./usage.js";
8
+ var TERMINAL_WARNING = (user = os.userInfo().username) => [
9
+ `A remote terminal runs a real shell on this computer as ${user}, with that account's full access:`,
10
+ "every file it can read or write, any program, and the network.",
11
+ "A workspace only picks the directory the shell starts in. It is NOT a sandbox.",
12
+ "Only gateway credentials that hold the terminal.exec permission can open one (never a default);",
13
+ "Paseo app devices paired with this host only after alp terminal allow --paseo."
14
+ ].join("\n");
15
+ var file = (home) => path.join(home, "terminal.json");
16
+ async function read(home) {
17
+ const info = await lstat(file(home)).catch(() => void 0);
18
+ if (!info) return { exists: false, value: void 0, private: true };
19
+ const own = !process.getuid || info.uid === process.getuid();
20
+ const value = info.isFile() ? await readFile(file(home), "utf8").then(JSON.parse, () => void 0) : void 0;
21
+ return { exists: true, value, private: info.isFile() && own && !(info.mode & 63) };
22
+ }
23
+ async function write(home, value) {
24
+ await mkdir(home, { recursive: true, mode: 448 });
25
+ const temporary = `${file(home)}.${randomUUID().slice(0, 8)}.tmp`;
26
+ await writeFile(temporary, JSON.stringify(value, null, 2) + "\n", { mode: 384, flag: "wx" });
27
+ await chmod(temporary, 384);
28
+ await rename(temporary, file(home)).catch(async (error) => {
29
+ await rm(temporary, { force: true });
30
+ throw error;
31
+ });
32
+ }
33
+ async function terminalCommand(args, { home = alpHome(), out = console.log } = {}) {
34
+ const [action, ...rest] = args;
35
+ const json = rest.includes("--json");
36
+ const current = await read(home);
37
+ const limits = current.value && typeof current.value.limits === "object" && current.value.limits ? { limits: current.value.limits } : {};
38
+ const paseo = rest.includes("--paseo");
39
+ const paseoBefore = current.private && current.value?.allowPaseoTerminal === true;
40
+ if (action === "allow") {
41
+ if (!rest.includes("--yes")) {
42
+ out(`${TERMINAL_WARNING()}
43
+
44
+ Run again with --yes to allow remote terminals on this host.`);
45
+ process.exitCode = 1;
46
+ return;
47
+ }
48
+ const allowPaseoTerminal = paseo || paseoBefore;
49
+ await write(home, { version: 1, allowRemoteTerminal: true, ...allowPaseoTerminal ? { allowPaseoTerminal: true } : {}, ...limits });
50
+ out(json ? JSON.stringify({ allowRemoteTerminal: true, allowPaseoTerminal }) : `${TERMINAL_WARNING()}
51
+
52
+ Remote terminals are allowed on this host (${file(home)})${allowPaseoTerminal ? ", also for every Paseo app device paired with it" : ""}. alp terminal deny turns them off and ends every open one.`);
53
+ return;
54
+ }
55
+ if (action === "deny") {
56
+ if (paseo) {
57
+ const allowed = current.private && current.value?.allowRemoteTerminal === true;
58
+ await write(home, { version: 1, allowRemoteTerminal: allowed, ...limits });
59
+ out(json ? JSON.stringify({ allowRemoteTerminal: allowed, allowPaseoTerminal: false }) : "Paseo app devices can no longer open terminals on this host; the bridge ends the terminals it holds.");
60
+ return;
61
+ }
62
+ await write(home, { version: 1, allowRemoteTerminal: false, ...limits });
63
+ out(json ? JSON.stringify({ allowRemoteTerminal: false, allowPaseoTerminal: false }) : "Remote terminals are off on this host; alpd ends every open terminal within 5 seconds.");
64
+ return;
65
+ }
66
+ if (action === "status") {
67
+ const allowed = current.private && current.value?.version === 1 && current.value.allowRemoteTerminal === true;
68
+ const allowPaseoTerminal = allowed && current.value.allowPaseoTerminal === true;
69
+ const problem = current.exists && !current.private ? `${file(home)} is not a private file of this user, so terminals stay off` : void 0;
70
+ if (json) out(JSON.stringify({ allowRemoteTerminal: allowed, allowPaseoTerminal, ...limits, ...problem ? { problem } : {} }));
71
+ else out([`Remote terminals: ${allowed ? "allowed" : "off"}${allowPaseoTerminal ? " (also for paired Paseo app devices)" : ""}`, ...problem ? [problem] : [], ...allowed ? ["", TERMINAL_WARNING()] : []].join("\n"));
72
+ return;
73
+ }
74
+ throw new UsageError();
75
+ }
76
+ export {
77
+ TERMINAL_WARNING,
78
+ terminalCommand
79
+ };
package/dist/usage.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export const USAGE: "Usage:\n alp <init|upgrade|update> [directory]\n alp setup [directory] [--runtime codex|claude|mix] [--prefer claude|codex]\n [--claude-model M] [--codex-model M] [--claude-supervisor M] [--codex-supervisor M]\n [--claude-oracle M] [--codex-oracle M] write Ph\u1EDF/Cafe's agent profiles to .alp/settings.json\n alp daemon <start|stop|restart>\n alp daemon status [--json] liveness and readiness; exit 0 ready, 3 not running, 4 not ready\n alp daemon <install|uninstall> run alpd as a login service that restarts after a crash\n alp acp serve ALP to an editor (Zed, JetBrains) over the Agent Client Protocol on stdio\n alp web [--print] open the local web app alpd serves; --print only prints its address\n alp web pair [--on|--off] the link that pairs Paseo's app on another device through the relay; --on or --off turns the relay on or off\n alp doctor [--project DIR] [--fix] [--json] check this machine and project; --fix repairs what is safe to\n alp backup [-o FILE] [--project DIR]... [--no-projects] [--stop] [--json] sessions, settings, library and tasks in one file\n alp backup verify <file> [--json] | alp backup list [--json]\n alp restore <file> [--home-only] [--dry-run] [--stop] [--replace-newer] [--json] checks the whole backup first; keeps what it replaces\n alpd must be stopped for both; --stop stops it and starts it again after\n alp run [--agent A] [--team pho|cafe|ID] [--model M] [--mode read-only|workspace-write|full-access] [--thinking T] [--project DIR] [--json] <prompt>\n alp ps [--all]\n alp top [session] [--once]\n alp attach <session> [--json]\n alp send <session> [--json] <text>\n alp questions [--json]\n alp answer <question> <text> | alp answer <question> --dismiss [--reason R]\n alp log <session> [--json]\n alp board [--project DIR] [--json]\n alp <agents|skills|mcp|hooks> [--project DIR] [--json] the library: built-in, ~/.alp and project entries\n alp providers [--json] ACP and Antigravity providers in your library\n alp teams [--project DIR] [--json] teams sessions run in: members, delegation, house rules\n alp agent <new|edit> <name> [--project [DIR]] [--from A] [-d text] [--provider P] [--model M] [--thinking T] [--mode M]\n [--skills a,b] [--mcp a,b] [--hooks a,b] [--instructions FILE]\n alp team <new|edit> <id> [--project [DIR]] [--from ID] [--label L] [-d text] [--main A] [--member name=role]...\n [--member-model name=M]... [--member-thinking name=T]... [--delegate owner=a,b]... [--max-peers N]\n [--supervisor A] [--supervisor-model M] [--supervisor-thinking T] [--no-supervisor] [--rules FILE]\n alp skill new <name> [--project [DIR]] [--from S] [--file FILE]\n alp mcp add <name> [--project [DIR]] (--command C [--arg A]... [--env K=V]... [--cwd D] | --url U [--header K=V]...)\n alp hook add <name> [--project [DIR]] --event E --command C [--blocking] [--timeout SEC] [--match-agent A] [--match-label L]\n alp provider add <id> --command C [--arg A]... [--env K=V]... [--label L] [-d text] [--models a,b] an ACP agent; use id antigravity for native agy\n alp provider edit antigravity --read-only-mode instructions|reject opt into prompt-only read-only for advisory roles\n alp <agent|team|skill|mcp|hook|provider> <rm|show> <name> [--project [DIR]] | <cp|mv> <from> <to> [--project [DIR]]\n alp <mcp|hook|provider> test <name> [--project [DIR]] list an MCP server's tools; run a hook once; initialize a provider\n without --project, changes go to your library in ~/.alp; built-in agents and teams are never changed\n alp trust [--project DIR] | --revoke [--project DIR] | --list [--json] whether the project's hooks may run\n alp permissions [--project DIR] [--json] each agent's permission profile\n alp permissions check <agent> \"<command>\" what that agent's profile says about a command\n alp tasks [ready] [--all] [--status S] [--label L] [--project DIR] [--json]\n alp tasks gates [--json] open gates; checks GitHub ones\n alp tasks compact [--days 30] [--dry-run]\n alp tasks export [-o file.jsonl] as beads JSONL\n alp tasks import [file.jsonl] [--dry-run] beads JSONL; default .beads/issues.jsonl\n alp formula list | show <name> | pour <name> [--var k=v]... [--parent ID] [--dry-run]\n alp task add <title> [-d text] [-p 0-4] [-t task|bug|feature|chore|epic] [--parent ID] [--after ID]... [-l label]... [--path P]... [--from ID]\n alp task show <id> [--json]\n alp task report <epic> [--json] what an epic came to: tasks, time, rework, verification\n alp task edit <id> [--title T] [-d text] [-p N] [-t type] [-l label]... [--path P]... [-m note]\n alp task close <id> [--reason done|wontfix|duplicate|superseded] [-m summary] [--unverified \"why\"]\n alp verify [--project DIR] [--task ID] [--json] run the project's verify commands; --task records the result\n alp task reopen <id> [-m note]\n alp task dep <add|rm> <id> [--after ID]... [--parent ID] [--related ID]...\n alp task gate add <id> --human \"question\" | --timer +2h|ISO | --pr N|owner/repo#N | --run N|owner/repo#N\n alp task gate <clear|rm> <id> <gate> [-m note]\n alp pause [codex|claude] [--now] [-m reason] | alp pause status hold delegation; --now parks running assignments\n alp resume [codex|claude] lift a pause; parked assignments continue\n alp language [name | --reset] the language agents and ALP write to you in; default Vietnamese\n alp recall <assignment|task> [--project DIR] [--json] <question> ask a finished assignment about its work\n alp interrupt <session>";
1
+ export const USAGE: "Usage:\n alp <init|upgrade|update> [directory]\n alp setup [directory] [--runtime codex|claude|mix] [--prefer claude|codex]\n [--claude-model M] [--codex-model M] [--claude-supervisor M] [--codex-supervisor M]\n [--claude-oracle M] [--codex-oracle M] write Ph\u1EDF/Cafe's agent profiles to .alp/settings.json\n alp daemon <start|stop|restart>\n alp daemon status [--json] liveness and readiness; exit 0 ready, 3 not running, 4 not ready\n alp daemon <install|uninstall> run alpd as a login service that restarts after a crash\n alp acp serve ALP to an editor (Zed, JetBrains) over the Agent Client Protocol on stdio\n alp web [--print] open the ALP web app on this machine (alp-web, loopback); --print only prints its address\n alp web rotate give alp web a new token: open pages lose access; prints the new address\n alp web pair [--on|--off] the link that pairs Paseo's app on another device through the relay; --on or --off turns the relay on or off\n alp terminal <allow [--paseo] --yes|deny [--paseo]|status> [--json] remote terminals (a shell as you on this host; a workspace is not a sandbox), off by default\n alp doctor [--project DIR] [--fix] [--json] check this machine and project; --fix repairs what is safe to\n alp backup [-o FILE] [--project DIR]... [--no-projects] [--stop] [--json] sessions, settings, library and tasks in one file\n alp backup verify <file> [--json] | alp backup list [--json]\n alp restore <file> [--home-only] [--dry-run] [--stop] [--replace-newer] [--json] checks the whole backup first; keeps what it replaces\n alpd must be stopped for both; --stop stops it and starts it again after\n alp run [--agent A] [--team pho|cafe|ID] [--model M] [--mode read-only|workspace-write|full-access] [--thinking T] [--project DIR] [--json] <prompt>\n alp schedule create --session ID --at ISO_WITH_OFFSET --prompt TEXT [--project DIR] [--json]\n alp schedule list [--status pending|delivered|failed|cancelled] [--project DIR] [--json]\n alp schedule <show|cancel> ID [--project DIR] [--json] one-shot wake; timer gates only unblock tasks\n alp ps [--all]\n alp top [session] [--once]\n alp attach <session> [--json]\n alp send <session> [--prompt] [--json] <text>\n child default: user mail; --prompt: explicit new prompt to a live root or child\n alp questions [--json]\n alp answer <question> <text> | alp answer <question> --dismiss [--reason R]\n alp log <session> [--json]\n alp board [--project DIR] [--json]\n alp <agents|skills|mcp|hooks> [--project DIR] [--json] the library: built-in, ~/.alp and project entries\n alp providers [--json] ACP and Antigravity providers in your library\n alp teams [--project DIR] [--json] teams sessions run in: members, delegation, house rules\n alp agent <new|edit> <name> [--project [DIR]] [--from A] [-d text] [--provider P] [--model M] [--thinking T] [--mode M]\n [--skills a,b] [--mcp a,b] [--hooks a,b] [--instructions FILE]\n alp team <new|edit> <id> [--project [DIR]] [--from ID] [--label L] [-d text] [--main A] [--member name=role]...\n [--member-model name=M]... [--member-thinking name=T]... [--delegate owner=a,b]... [--max-peers N]\n [--supervisor A] [--supervisor-model M] [--supervisor-thinking T] [--no-supervisor] [--rules FILE]\n alp skill new <name> [--project [DIR]] [--from S] [--file FILE]\n alp mcp add <name> [--project [DIR]] (--command C [--arg A]... [--env K=V]... [--cwd D] | --url U [--header K=V]...)\n alp hook add <name> [--project [DIR]] --event E --command C [--blocking] [--timeout SEC] [--match-agent A] [--match-label L]\n alp provider add <id> --command C [--arg A]... [--env K=V]... [--label L] [-d text] [--models a,b] an ACP agent; use id antigravity for native agy\n alp provider edit antigravity --read-only-mode instructions|reject opt into prompt-only read-only for advisory roles\n alp <agent|team|skill|mcp|hook|provider> <rm|show> <name> [--project [DIR]] | <cp|mv> <from> <to> [--project [DIR]]\n alp <mcp|hook|provider> test <name> [--project [DIR]] list an MCP server's tools; run a hook once; initialize a provider\n without --project, changes go to your library in ~/.alp; built-in agents and teams are never changed\n alp trust [--project DIR] | --revoke [--project DIR] | --list [--json] whether the project's hooks may run\n alp permissions [--project DIR] [--json] each agent's permission profile\n alp permissions check <agent> \"<command>\" what that agent's profile says about a command\n alp tasks [ready] [--all] [--status S] [--label L] [--project DIR] [--json]\n alp tasks gates [--json] open gates; checks GitHub ones\n alp tasks compact [--days 30] [--dry-run]\n alp tasks export [-o file.jsonl] as beads JSONL\n alp tasks import [file.jsonl] [--dry-run] beads JSONL; default .beads/issues.jsonl\n alp formula list | show <name> | pour <name> [--var k=v]... [--parent ID] [--dry-run]\n alp task add <title> [-d text] [-p 0-4] [-t task|bug|feature|chore|epic] [--parent ID] [--after ID]... [-l label]... [--path P]... [--from ID]\n alp task show <id> [--json]\n alp task report <epic> [--json] what an epic came to: tasks, time, rework, verification\n alp task edit <id> [--title T] [-d text] [-p N] [-t type] [-l label]... [--path P]... [-m note]\n alp task close <id> [--reason done|wontfix|duplicate|superseded] [-m summary] [--unverified \"why\"]\n alp verify [--project DIR] [--task ID] [--json] run the project's verify commands; --task records the result\n alp task reopen <id> [-m note]\n alp task dep <add|rm> <id> [--after ID]... [--parent ID] [--related ID]...\n alp task gate add <id> --human \"question\" | --timer +2h|ISO | --pr N|owner/repo#N | --run N|owner/repo#N\n alp task gate <clear|rm> <id> <gate> [-m note]\n alp pause [codex|claude] [--now] [-m reason] | alp pause status hold delegation; --now parks running assignments\n alp resume [codex|claude] lift a pause; parked assignments continue\n alp language [name | --reset] the language agents and ALP write to you in; default Vietnamese\n alp recall <assignment|task> [--project DIR] [--json] <question> ask a finished assignment about its work\n alp interrupt <session>";
2
2
  export class UsageError extends Error {
3
3
  }
package/dist/usage.js CHANGED
@@ -8,18 +8,24 @@ var USAGE = `Usage:
8
8
  alp daemon status [--json] liveness and readiness; exit 0 ready, 3 not running, 4 not ready
9
9
  alp daemon <install|uninstall> run alpd as a login service that restarts after a crash
10
10
  alp acp serve ALP to an editor (Zed, JetBrains) over the Agent Client Protocol on stdio
11
- alp web [--print] open the local web app alpd serves; --print only prints its address
11
+ alp web [--print] open the ALP web app on this machine (alp-web, loopback); --print only prints its address
12
+ alp web rotate give alp web a new token: open pages lose access; prints the new address
12
13
  alp web pair [--on|--off] the link that pairs Paseo's app on another device through the relay; --on or --off turns the relay on or off
14
+ alp terminal <allow [--paseo] --yes|deny [--paseo]|status> [--json] remote terminals (a shell as you on this host; a workspace is not a sandbox), off by default
13
15
  alp doctor [--project DIR] [--fix] [--json] check this machine and project; --fix repairs what is safe to
14
16
  alp backup [-o FILE] [--project DIR]... [--no-projects] [--stop] [--json] sessions, settings, library and tasks in one file
15
17
  alp backup verify <file> [--json] | alp backup list [--json]
16
18
  alp restore <file> [--home-only] [--dry-run] [--stop] [--replace-newer] [--json] checks the whole backup first; keeps what it replaces
17
19
  alpd must be stopped for both; --stop stops it and starts it again after
18
20
  alp run [--agent A] [--team pho|cafe|ID] [--model M] [--mode read-only|workspace-write|full-access] [--thinking T] [--project DIR] [--json] <prompt>
21
+ alp schedule create --session ID --at ISO_WITH_OFFSET --prompt TEXT [--project DIR] [--json]
22
+ alp schedule list [--status pending|delivered|failed|cancelled] [--project DIR] [--json]
23
+ alp schedule <show|cancel> ID [--project DIR] [--json] one-shot wake; timer gates only unblock tasks
19
24
  alp ps [--all]
20
25
  alp top [session] [--once]
21
26
  alp attach <session> [--json]
22
- alp send <session> [--json] <text>
27
+ alp send <session> [--prompt] [--json] <text>
28
+ child default: user mail; --prompt: explicit new prompt to a live root or child
23
29
  alp questions [--json]
24
30
  alp answer <question> <text> | alp answer <question> --dismiss [--reason R]
25
31
  alp log <session> [--json]
@@ -0,0 +1,38 @@
1
+ /** The alp-web service script beside this CLI; a clear error when this CLI was built without it. */
2
+ export function alpWebEntry(): string;
3
+ /**
4
+ * The process that owns alp web's lock, if it is proven safe to stop; else why not. `kind` says
5
+ * whether waiting can help: `transient` (an owner still starting has not published web.json yet),
6
+ * `foreign` (proven not to be the integration: another user's, another boot's, or a reused pid) or
7
+ * `unknown` (it cannot be proven either way, for example without ps or on Windows).
8
+ *
9
+ * The reuse proof compares the lock's wall-clock `startedAt` with the process's start from ps: a
10
+ * wall clock stepped back by more than two seconds after the lock was written could make a reused
11
+ * pid look older than the lock. A step forward only refuses.
12
+ * @param {string} home
13
+ * @returns {Promise<{ pid: number, app: unknown } | { reason: string, alive: boolean, kind?: 'transient' | 'foreign' | 'unknown' }>}
14
+ */
15
+ export function webOwner(home: string): Promise<{
16
+ pid: number;
17
+ app: unknown;
18
+ } | {
19
+ reason: string;
20
+ alive: boolean;
21
+ kind?: "transient" | "foreign" | "unknown";
22
+ }>;
23
+ /**
24
+ * Stops the Paseo integration from before its rename when it still runs as integration `web` (its
25
+ * web.json has no `app: 'alp-web'`), so alp-web can take the lock and web.port. Returns the pid it
26
+ * stopped. A process that cannot be proven to be that integration is left alone.
27
+ * @param {string} home
28
+ */
29
+ export function stopPreRenamePaseo(home: string): Promise<number | undefined>;
30
+ /**
31
+ * Stops whatever runs as integration `web` (alp-web, or the Paseo integration from before its
32
+ * rename), waiting up to `timeoutMs` for a starting owner to publish what proves it. Resolves once
33
+ * no live process owns the lock; refuses at once an owner that is foreign or cannot be proven.
34
+ * @param {string} home @param {number} [timeoutMs]
35
+ */
36
+ export function stopWebService(home: string, timeoutMs?: number): Promise<number | undefined>;
37
+ /** The opening of the message for a web lock held by a process alp would not stop. @param {string} home */
38
+ export function refusal(home: string): string;
@@ -0,0 +1,119 @@
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 path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { promisify } from "node:util";
8
+ import { bootTime, readLock } from "@anhlp/alp-client/index";
9
+ import { distributionEntry } from "./paths.js";
10
+ var execFileAsync = promisify(execFile);
11
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
12
+ function alpWebEntry() {
13
+ const entry = fileURLToPath(distributionEntry("alp-web.js"));
14
+ if (!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.`);
15
+ return entry;
16
+ }
17
+ var readJson = async (file) => JSON.parse(await readFile(file, "utf8"));
18
+ async function processStart(pid) {
19
+ try {
20
+ const { stdout } = await execFileAsync("ps", ["-o", "etime=", "-p", String(pid)], { encoding: "utf8", timeout: 5e3 });
21
+ const match = /^\s*(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)\s*$/.exec(stdout);
22
+ if (!match) return void 0;
23
+ const [, days = "0", hours = "0", minutes, seconds] = match;
24
+ const elapsed = ((Number(days) * 24 + Number(hours)) * 60 + Number(minutes)) * 60 + Number(seconds);
25
+ return Date.now() - elapsed * 1e3;
26
+ } catch {
27
+ return void 0;
28
+ }
29
+ }
30
+ async function webOwner(home) {
31
+ const lockFile = path.join(home, "integrations", "web.lock");
32
+ const infoFile = path.join(home, "web.json");
33
+ let lock, lockInfo;
34
+ try {
35
+ lockInfo = await lstat(lockFile);
36
+ lock = await readJson(lockFile);
37
+ } catch {
38
+ return { reason: `${lockFile} is missing or unreadable`, alive: false };
39
+ }
40
+ if (!lockInfo.isFile() || !Number.isSafeInteger(lock?.pid) || lock.pid <= 0 || typeof lock.bootTime !== "number" || !Number.isFinite(Date.parse(lock.startedAt))) {
41
+ return { reason: `${lockFile} is not a complete integration lock`, alive: false };
42
+ }
43
+ const { pid } = lock;
44
+ try {
45
+ process.kill(pid, 0);
46
+ } catch (error) {
47
+ if (error?.code === "ESRCH") return { reason: `its pid ${pid} has exited`, alive: false };
48
+ if (error?.code === "EPERM") return { reason: `pid ${pid} belongs to another user`, alive: true, kind: "foreign" };
49
+ return { reason: `pid ${pid} cannot be signalled (${error?.code ?? error})`, alive: true, kind: "unknown" };
50
+ }
51
+ const refuse = (reason, kind) => ({ reason, alive: true, kind });
52
+ if (process.platform === "win32") return refuse("alp does not stop it on Windows", "unknown");
53
+ const uid = process.getuid?.();
54
+ if (lockInfo.uid !== uid) return refuse("its lock is not yours", "foreign");
55
+ if (Math.abs(lock.bootTime - bootTime()) > 30) return refuse("its lock is from another boot", "foreign");
56
+ if (pid === process.pid || pid === (await readLock(home).catch(() => void 0))?.pid) return refuse(`pid ${pid} is not an integration`, "foreign");
57
+ const started = await processStart(pid);
58
+ if (started === void 0) return refuse(`the start time of pid ${pid} is unknown`, "unknown");
59
+ if (started > Date.parse(lock.startedAt) + 2e3) return refuse(`pid ${pid} started after the lock was written (a reused pid)`, "foreign");
60
+ let info, infoStat;
61
+ try {
62
+ infoStat = await lstat(infoFile);
63
+ info = await readJson(infoFile);
64
+ } catch {
65
+ return refuse(`${infoFile} is missing or unreadable`, "transient");
66
+ }
67
+ if (info?.pid !== pid) return refuse(`${infoFile} names another process than the lock`, "transient");
68
+ if (!infoStat.isFile() || infoStat.uid !== uid) return refuse(`${infoFile} is not yours`, "foreign");
69
+ return { pid, app: info.app };
70
+ }
71
+ async function terminate(pid, what, timeoutMs = 2e4) {
72
+ try {
73
+ process.kill(pid, "SIGTERM");
74
+ } catch (error) {
75
+ if (error?.code === "ESRCH") return;
76
+ throw error;
77
+ }
78
+ const deadline = Date.now() + timeoutMs;
79
+ while (Date.now() < deadline) {
80
+ try {
81
+ process.kill(pid, 0);
82
+ } catch (error) {
83
+ if (error?.code === "ESRCH") return;
84
+ }
85
+ await sleep(100);
86
+ }
87
+ throw new Error(`${what} (pid ${pid}) did not stop within ${timeoutMs / 1e3} s of SIGTERM; stop it, then run the command again`);
88
+ }
89
+ var isAlpWeb = (app) => app === "alp-web";
90
+ var PASEO_BEFORE_RENAME = "The Paseo integration from before its rename";
91
+ async function stopPreRenamePaseo(home) {
92
+ const owner = await webOwner(home);
93
+ if (!("pid" in owner) || isAlpWeb(owner.app)) return void 0;
94
+ await terminate(owner.pid, PASEO_BEFORE_RENAME);
95
+ return owner.pid;
96
+ }
97
+ async function stopWebService(home, timeoutMs = 3e4) {
98
+ const deadline = Date.now() + timeoutMs;
99
+ for (; ; ) {
100
+ const owner = await webOwner(home);
101
+ if ("pid" in owner) {
102
+ await terminate(owner.pid, isAlpWeb(owner.app) ? "alp web" : PASEO_BEFORE_RENAME);
103
+ return owner.pid;
104
+ }
105
+ if (!owner.alive) return void 0;
106
+ if (owner.kind !== "transient" || Date.now() >= deadline) throw new Error(`${refusal(home)} (${owner.reason}); stop it, then run the command again`);
107
+ await sleep(200);
108
+ }
109
+ }
110
+ function refusal(home) {
111
+ 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`;
112
+ }
113
+ export {
114
+ alpWebEntry,
115
+ refusal,
116
+ stopPreRenamePaseo,
117
+ stopWebService,
118
+ webOwner
119
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anhlp/alp-cli",
3
- "version": "0.0.0-beta.2",
3
+ "version": "0.0.1-beta.4",
4
4
  "type": "module",
5
5
  "description": "ALP cli module",
6
6
  "files": [
@@ -126,9 +126,9 @@
126
126
  "node": ">=22.12"
127
127
  },
128
128
  "dependencies": {
129
- "@anhlp/alp-core": "0.0.0-beta.2",
130
- "@anhlp/alp-client": "0.0.0-beta.2",
131
- "@anhlp/alp-protocol": "0.0.0-beta.2",
129
+ "@anhlp/alp-core": "0.0.1-beta.4",
130
+ "@anhlp/alp-client": "0.0.1-beta.4",
131
+ "@anhlp/alp-protocol": "0.0.1-beta.4",
132
132
  "smol-toml": "1.9.0",
133
133
  "@agentclientprotocol/sdk": "1.7.0",
134
134
  "@anthropic-ai/claude-agent-sdk": "^0.3.292"
@@ -155,5 +155,11 @@
155
155
  },
156
156
  "bin": {
157
157
  "alp": "dist/cli.js"
158
+ },
159
+ "optionalDependencies": {
160
+ "node-pty": "1.2.0-beta.15"
161
+ },
162
+ "devDependencies": {
163
+ "@anhlp/alp-gateway": "0.0.1-beta.4"
158
164
  }
159
165
  }
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,4 +1,5 @@
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';
@@ -7,15 +8,23 @@ import { project, permissionsCommand, trustCommand, language, verify, doctor } f
7
8
  import { daemon } from './daemon.js';
8
9
  import { run, ps, attach, send, questions, answer, top, log, board, pause, resume, recall, interrupt } from './sessions.js';
9
10
  import { libraryCommand, editCommand, teamsCommand } from './library.js';
11
+ import { scheduleCommand } from './schedules.js';
10
12
  import { tasksCommand, formulaCommand, taskCommand } from './tasks.js';
11
13
  import { webCommand, acpCommand } from './interfaces.js';
12
14
  import { backupCommand, restoreCommand } from './backup.js';
15
+ import { terminalCommand } from './terminal.js';
13
16
 
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 };
17
+ const commands = { schedule: scheduleCommand, 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, terminal: terminalCommand };
15
18
  const [command, ...args] = process.argv.slice(2);
16
19
  try {
17
- if (!Object.hasOwn(commands, command)) throw new UsageError();
18
- await commands[command](args);
20
+ if (command === '--version') {
21
+ // Published builds inject their package version; source execution reads the same metadata.
22
+ /* global __ALP_VERSION__ */
23
+ console.log(typeof __ALP_VERSION__ === 'string' ? __ALP_VERSION__ : JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
24
+ } else {
25
+ if (!Object.hasOwn(commands, command)) throw new UsageError();
26
+ await commands[command](args);
27
+ }
19
28
  } catch (error) {
20
29
  if (error instanceof UsageError || error?.code === 'ERR_PARSE_ARGS_UNKNOWN_OPTION') console.error(USAGE);
21
30
  else console.error(`alp: ${scrubText(error?.message ?? error)}`);
package/src/daemon.js CHANGED
@@ -2,7 +2,7 @@ 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, 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
8
  import { DAEMON_ENTRY } from './paths.js';
@@ -66,9 +66,14 @@ async function daemon([action, ...rest]) {
66
66
  const lock = await readLock(alpHome());
67
67
  console.log(`alpd ${lock.version} running (pid ${lock.pid}) on ${socket}`);
68
68
  } else if (action === 'stop') {
69
- const stopped = await stop();
70
- // On purpose: the Paseo plugin leaves it stopped until something asks for it.
69
+ // Publish intent before waiting for a launch, then drain that launch before
70
+ // reading its lock. No detached child can arrive after this stop resolves.
71
71
  await holdDaemon(alpHome());
72
+ const stopped = await withDaemonLifecycle(alpHome(), 'stop', async () => {
73
+ const stopped = await stop();
74
+ await holdDaemon(alpHome());
75
+ return stopped;
76
+ });
72
77
  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
78
  } else if (action === 'restart') {
74
79
  const client = await running().catch(() => undefined);
package/src/interfaces.js CHANGED
@@ -1,51 +1,153 @@
1
- import { spawn } from 'node:child_process';
2
- import { readFile } from 'node:fs/promises';
1
+ import { execFile, spawn } from 'node:child_process';
2
+ import { readFile, stat } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { parseArgs } from 'node:util';
5
- import { alpHome, lockAlive, readLock, startIntegration } from '@anhlp/alp-client/index';
5
+ import { alpHome, discoverIntegration, startIntegration } from '@anhlp/alp-client/index';
6
6
  import { UsageError } from './usage.js';
7
7
  import { built, start, running } from './daemon.js';
8
8
  import { DAEMON_ENTRY, distributionEntry } from './paths.js';
9
+ import { alpWebEntry, refusal, stopPreRenamePaseo, stopWebService, webOwner } from './web-service.js';
9
10
 
11
+ /** The Paseo integration (its web app, bridge and relay) runs as integration `paseo`. */
12
+ const PASEO = 'paseo';
13
+ /** alp-web (packages/cli/src/web), the service behind `alp web`, runs as integration `web`. */
14
+ const WEB = 'web';
15
+
16
+ /**
17
+ * Starts the Paseo integration. For one release, a home that still has only the descriptor
18
+ * registered before the rename (`integrations/web.json`) keeps working, with a hint to re-register.
19
+ * Exported for tests.
20
+ * @param {string} home
21
+ */
22
+ export async function startPaseoIntegration(home) {
23
+ const entry = await discoverIntegration(PASEO, { home });
24
+ if (!entry) {
25
+ const legacy = path.join(home, 'integrations', 'web.json');
26
+ const legacyEntry = await legacyDescriptorEntry(legacy, home);
27
+ if (legacyEntry) {
28
+ console.error(`Using the Paseo integration registered before its rename (${legacy}); run \`alp-paseo-integration --register\` to register it again.`);
29
+ return startIntegration({ name: PASEO, entry: legacyEntry, home });
30
+ }
31
+ }
32
+ return startIntegration({ name: PASEO, home });
33
+ }
34
+
35
+ /**
36
+ * The entry named by the pre-rename descriptor `<home>/integrations/web.json`, and nothing else: no
37
+ * environment, distribution or PATH lookup, since the name `web` now belongs to alp-web. A relative
38
+ * `main` resolves against the descriptor's directory, then the home, as discovery does.
39
+ * @param {string} file
40
+ * @param {string} home
41
+ */
42
+ async function legacyDescriptorEntry(file, home) {
43
+ // A missing or corrupt descriptor is no registration: the caller then reports the missing package.
44
+ const raw = await readFile(file, 'utf8').then(text => JSON.parse(text)).catch(() => undefined);
45
+ const isFile = candidate => stat(candidate).then(info => info.isFile(), () => false);
46
+ // The fields discovery accepts in a descriptor, in its priority order.
47
+ for (const field of ['main', 'entry', 'path', 'command']) {
48
+ const value = raw?.[field];
49
+ if (typeof value !== 'string' || !value.trim()) continue;
50
+ const candidates = path.isAbsolute(value) ? [value] : [path.resolve(path.dirname(file), value), path.resolve(home, value)];
51
+ for (const candidate of candidates) if (await isFile(candidate)) return candidate;
52
+ }
53
+ return undefined;
54
+ }
55
+
56
+ /** `--project <cwd>` when the directory `alp web` runs in is an ALP project: its grant then covers it. */
57
+ async function projectArgs() {
58
+ const cwd = process.cwd();
59
+ return await stat(path.join(cwd, '.alp')).then(info => info.isDirectory(), () => false) ? ['--project', cwd] : [];
60
+ }
61
+
62
+ /** Whether settings.json turns alp web off. @param {string} home */
63
+ async function webDisabled(home) {
64
+ const settings = await readFile(path.join(home, 'settings.json'), 'utf8').then(text => JSON.parse(text), () => undefined);
65
+ return settings?.web?.enabled === false;
66
+ }
67
+
68
+ const DISABLED = 'alp web is disabled by settings ("web.enabled": false).';
69
+
70
+ /**
71
+ * Starts alp-web unless it runs and returns the address to open, the token in its fragment (which
72
+ * the browser never sends to a server). The Paseo integration from before its rename, still running
73
+ * as integration `web`, is stopped first.
74
+ * @param {string} home @param {string} entry
75
+ */
76
+ async function serveWeb(home, entry) {
77
+ await stopPreRenamePaseo(home);
78
+ // A lock held by a process proven not to be alp web: say so now rather than wait for it. A
79
+ // running alp-web (its web.json names the lock's pid) is left to startIntegration, whatever the
80
+ // proof says, so a clock step can never keep alp web from reusing it.
81
+ const held = await webOwner(home);
82
+ const published = await readFile(path.join(home, 'web.json'), 'utf8').then(text => JSON.parse(text), () => undefined);
83
+ const claimed = published?.app === 'alp-web' && published.pid === (await readFile(path.join(home, 'integrations', 'web.lock'), 'utf8').then(text => JSON.parse(text)?.pid, () => undefined));
84
+ if ('reason' in held && held.alive && held.kind === 'foreign' && !claimed) throw new Error(`${refusal(home)} (${held.reason}). Stop it, then run alp web again.`);
85
+ let lock;
86
+ try { lock = await startIntegration({ name: WEB, entry, home, args: await projectArgs() }); }
87
+ catch (error) {
88
+ // Still held by a live process alp cannot prove: name it, as the wait may have been for it.
89
+ const owner = await webOwner(home);
90
+ 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 });
91
+ throw error;
92
+ }
93
+ const info = await readFile(path.join(home, 'web.json'), 'utf8').then(text => JSON.parse(text), () => undefined);
94
+ if (info?.app !== 'alp-web' || info.pid !== lock.pid) {
95
+ const owner = await webOwner(home);
96
+ throw new Error(`${refusal(home)}${'reason' in owner ? ` (${owner.reason})` : ''}. Stop pid ${lock.pid}, then run alp web again.`);
97
+ }
98
+ if (typeof info.url !== 'string' || typeof info.token !== 'string') throw new Error(`alp web published no address; see ${path.join(home, 'logs', 'integrations', 'alp-web.log')}`);
99
+ return `${info.url}#token=${info.token}`;
100
+ }
10
101
 
11
102
  async function webCommand(args) {
12
103
  if (args[0] === 'pair') return pairCommand(args.slice(1));
104
+ if (args[0] === 'rotate') return rotateCommand(args.slice(1));
13
105
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { print: { type: 'boolean' } } });
14
106
  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();
107
+ const entry = alpWebEntry();
23
108
  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}`;
109
+ if (await webDisabled(home)) throw new Error(DISABLED);
110
+ await start();
111
+ const url = await serveWeb(home, entry);
40
112
  console.log(url);
41
113
  if (values.print) return;
42
114
  const opener = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'explorer' : 'xdg-open';
43
115
  spawn(opener, [url], { stdio: 'ignore', detached: true }).on('error', () => console.error('Open the address above in your browser')).unref();
44
116
  }
45
117
 
118
+ /**
119
+ * alp web rotate: alp web's token is replaced and the old one revoked, so every open page loses
120
+ * access. Only the process holding the web lock writes alp web's credentials, so the service is
121
+ * stopped first; `alp-web.js --rotate` then takes the lock, replaces the credential, records the
122
+ * new token in web.json and releases the lock, and the service starts again with it.
123
+ */
124
+ async function rotateCommand(args) {
125
+ if (args.length) throw new UsageError();
126
+ const entry = alpWebEntry();
127
+ const home = alpHome();
128
+ await start();
129
+ const project = await projectArgs();
130
+ for (let attempt = 1; ; attempt++) {
131
+ await stopWebService(home);
132
+ const rotated = await new Promise(resolve => {
133
+ execFile(process.execPath, [entry, '--rotate', ...project], { env: { ...process.env, ALP_HOME: home }, encoding: 'utf8', timeout: 60_000, killSignal: 'SIGTERM' },
134
+ (error, stdout, stderr) => resolve({ code: error ? (typeof error.code === 'number' ? error.code : 1) : 0, output: `${stderr}${stdout}`.trim() }));
135
+ });
136
+ if (rotated.code === 0) break;
137
+ // Exit 3: alp web started again between the stop and the rotation; stop it once more.
138
+ if (rotated.code !== 3 || attempt >= 3) throw new Error(`alp web could not rotate its token${rotated.output ? `:\n${rotated.output.slice(-2000)}` : ''}`);
139
+ }
140
+ if (await webDisabled(home)) {
141
+ console.log(`alp web has a new token; the old one no longer works. ${DISABLED.replace(/\.$/, '')}, so it was not started.`);
142
+ return;
143
+ }
144
+ console.log(await serveWeb(home, entry));
145
+ }
146
+
46
147
  /**
47
148
  * 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.
149
+ * (ALPD §64). The device then signs in with the password this command prints (the token kept in
150
+ * ~/.alp/paseo.json).
49
151
  */
50
152
 
51
153
  /**
@@ -72,7 +174,8 @@ async function pairCommand(args) {
72
174
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { on: { type: 'boolean' }, off: { type: 'boolean' } } });
73
175
  if (positionals.length || (values.on && values.off)) throw new UsageError();
74
176
  await start();
75
- await startIntegration();
177
+ const home = alpHome();
178
+ await startPaseoIntegration(home);
76
179
  const client = await running();
77
180
  try {
78
181
  const pairing = await requestPairing(client, values.on ? { enable: true } : values.off ? { enable: false } : {});
@@ -81,8 +184,10 @@ async function pairCommand(args) {
81
184
  return;
82
185
  }
83
186
  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.");
187
+ console.log(`Open this link on the device that runs Paseo's app:\n${pairing.url}`);
188
+ const password = await readFile(path.join(home, `${PASEO}.json`), 'utf8').then(text => JSON.parse(text)?.token).catch(() => undefined);
189
+ if (typeof password === 'string' && password) console.log(`When Paseo's app asks for a password, give it: ${password}`);
190
+ else console.log(`When Paseo's app asks for a password, give it the token in ${path.join(home, `${PASEO}.json`)}.`);
86
191
  } finally {
87
192
  client.close();
88
193
  }