@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
@@ -0,0 +1,141 @@
1
+ // packages/cli/src/dashboard-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 { selfEntry } from "@anhlp/alp-core/packaged";
12
+ var execFileAsync = promisify(execFile);
13
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
14
+ function dashboardScript() {
15
+ const entry = fileURLToPath(distributionEntry("alp-dashboard.js"));
16
+ if (!existsSync(entry)) throw new Error(`alp dashboard is not built: ${entry} is missing. Build the CLI (npm run build in the ALP checkout) or reinstall ALP.`);
17
+ return entry;
18
+ }
19
+ var dashboardEntry = () => selfEntry(dashboardScript());
20
+ var DASHBOARD = Object.freeze({ lock: "dashboard", info: "dashboard.json", app: "alp-dashboard", what: "alp dashboard" });
21
+ var LEGACY_WEB = Object.freeze({ lock: "web", info: "web.json", app: "alp-web", what: "alp web from before its rename to alp dashboard" });
22
+ var readJson = async (file) => JSON.parse(await readFile(file, "utf8"));
23
+ async function processTimes(pid) {
24
+ try {
25
+ const { stdout } = await execFileAsync("ps", ["-o", "etime=", "-p", String(pid)], { encoding: "utf8", timeout: 5e3 });
26
+ const match = /^\s*(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)\s*$/.exec(stdout);
27
+ if (!match) return void 0;
28
+ const [, days = "0", hours = "0", minutes, seconds] = match;
29
+ const elapsed = ((Number(days) * 24 + Number(hours)) * 60 + Number(minutes)) * 60 + Number(seconds);
30
+ return { started: Date.now() - elapsed * 1e3, elapsed };
31
+ } catch {
32
+ return void 0;
33
+ }
34
+ }
35
+ async function serviceOwner(home, service = DASHBOARD) {
36
+ const lockFile = path.join(home, "integrations", `${service.lock}.lock`);
37
+ const infoFile = path.join(home, service.info);
38
+ let lock, lockInfo;
39
+ try {
40
+ lockInfo = await lstat(lockFile);
41
+ lock = await readJson(lockFile);
42
+ } catch {
43
+ return { reason: `${lockFile} is missing or unreadable`, alive: false };
44
+ }
45
+ if (!lockInfo.isFile() || !Number.isSafeInteger(lock?.pid) || lock.pid <= 0 || typeof lock.bootTime !== "number" || !Number.isFinite(Date.parse(lock.startedAt))) {
46
+ return { reason: `${lockFile} is not a complete integration lock`, alive: false };
47
+ }
48
+ const { pid } = lock;
49
+ try {
50
+ process.kill(pid, 0);
51
+ } catch (error) {
52
+ if (error?.code === "ESRCH") return { reason: `its pid ${pid} has exited`, alive: false };
53
+ if (error?.code === "EPERM") return { reason: `pid ${pid} belongs to another user`, alive: true, kind: "foreign" };
54
+ return { reason: `pid ${pid} cannot be signalled (${error?.code ?? error})`, alive: true, kind: "unknown" };
55
+ }
56
+ const refuse = (reason, kind) => ({ reason, alive: true, kind });
57
+ if (process.platform === "win32") return refuse("alp does not stop it on Windows", "unknown");
58
+ const uid = process.getuid?.();
59
+ if (lockInfo.uid !== uid) return refuse("its lock is not yours", "foreign");
60
+ if (!isSameBoot(lock)) return refuse("its lock is from another boot", "foreign");
61
+ if (pid === process.pid || pid === (await readLock(home).catch(() => void 0))?.pid) return refuse(`pid ${pid} is not an integration`, "foreign");
62
+ const times = await processTimes(pid);
63
+ if (times === void 0) return refuse(`the start time of pid ${pid} is unknown`, "unknown");
64
+ const isReused = typeof lock.startedUptime === "number" ? Math.floor(os.uptime()) - times.elapsed > lock.startedUptime + 2 : times.started > Date.parse(lock.startedAt) + 2e3;
65
+ if (isReused) return refuse(`pid ${pid} started after the lock was written (a reused pid)`, "foreign");
66
+ let info, infoStat;
67
+ try {
68
+ infoStat = await lstat(infoFile);
69
+ info = await readJson(infoFile);
70
+ } catch {
71
+ return refuse(`${infoFile} is missing or unreadable`, "transient");
72
+ }
73
+ if (info?.pid !== pid) return refuse(`${infoFile} names another process than the lock`, "transient");
74
+ if (!infoStat.isFile() || infoStat.uid !== uid) return refuse(`${infoFile} is not yours`, "foreign");
75
+ return { pid, app: info.app };
76
+ }
77
+ async function terminate(pid, what, timeoutMs = 2e4) {
78
+ try {
79
+ process.kill(pid, "SIGTERM");
80
+ } catch (error) {
81
+ if (error?.code === "ESRCH") return;
82
+ throw error;
83
+ }
84
+ const deadline = Date.now() + timeoutMs;
85
+ while (Date.now() < deadline) {
86
+ try {
87
+ process.kill(pid, 0);
88
+ } catch (error) {
89
+ if (error?.code === "ESRCH") return;
90
+ }
91
+ await sleep(100);
92
+ }
93
+ throw new Error(`${what} (pid ${pid}) did not stop within ${timeoutMs / 1e3} s of SIGTERM; stop it, then run the command again`);
94
+ }
95
+ var PASEO_BEFORE_RENAME = "The Paseo integration from before its rename";
96
+ var ownerName = (service, app) => app === service.app || service === DASHBOARD ? service.what : PASEO_BEFORE_RENAME;
97
+ async function stopService(home, timeoutMs = 3e4, service = DASHBOARD) {
98
+ const deadline = Date.now() + timeoutMs;
99
+ for (; ; ) {
100
+ const owner = await serviceOwner(home, service);
101
+ if ("pid" in owner) {
102
+ await terminate(owner.pid, ownerName(service, owner.app));
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, service)} (${owner.reason}); stop it, then run the command again`);
107
+ await sleep(200);
108
+ }
109
+ }
110
+ function refusal(home, service = DASHBOARD) {
111
+ const lock = path.join(home, "integrations", `${service.lock}.lock`);
112
+ return service === DASHBOARD ? `${lock} is held by a process that alp cannot prove is alp dashboard, so it was left running` : `${lock} is held by a process that alp cannot prove is ${service.what} or the Paseo integration from before its rename, so it was left running`;
113
+ }
114
+ async function isDashboardReady(url, timeoutMs = 1e3) {
115
+ if (typeof url !== "string" || !url) return false;
116
+ try {
117
+ const parsed = new URL(url);
118
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
119
+ if (!["127.0.0.1", "localhost", "::1", "[::1]"].includes(parsed.hostname)) return false;
120
+ const res = await fetch(parsed.href, { signal: AbortSignal.timeout(timeoutMs) });
121
+ return typeof res.status === "number" && res.status > 0;
122
+ } catch {
123
+ return false;
124
+ }
125
+ }
126
+ async function isServiceClaimed(published, lockPid, held, timeoutMs = 1e3) {
127
+ if (published?.app !== DASHBOARD.app || published.pid !== lockPid) return false;
128
+ if (held?.kind === "foreign") return false;
129
+ return isDashboardReady(published.url, timeoutMs);
130
+ }
131
+ export {
132
+ DASHBOARD,
133
+ LEGACY_WEB,
134
+ dashboardEntry,
135
+ dashboardScript,
136
+ isDashboardReady,
137
+ isServiceClaimed,
138
+ refusal,
139
+ serviceOwner,
140
+ stopService
141
+ };
@@ -0,0 +1,56 @@
1
+ /**
2
+ * The CFBundleIdentifier of the app bundle at `app`, or undefined when it cannot be read. An XML
3
+ * Info.plist (what electron-builder writes) is read directly; any other form through plutil.
4
+ * @param {string} app
5
+ * @returns {Promise<string | undefined>}
6
+ */
7
+ export function readBundleId(app: string): Promise<string | undefined>;
8
+ /**
9
+ * Where the app is and how to start it. Exported for tests.
10
+ * `onSkip` hears about each ALP.app passed over because its bundle id is not DESKTOP_BUNDLE_ID.
11
+ * @param {{ platform?: NodeJS.Platform, home?: string, env?: NodeJS.ProcessEnv, applications?: string[], onSkip?: (message: string) => void }} [options]
12
+ * @returns {Promise<{ kind: 'app', app: string, command: string, args: string[] }
13
+ * | { kind: 'checkout', dir: string, command: string, args: string[] }
14
+ * | { kind: 'missing', reason?: string }>}
15
+ */
16
+ export function resolveDesktop({ platform, home, env, applications, onSkip }?: {
17
+ platform?: NodeJS.Platform;
18
+ home?: string;
19
+ env?: NodeJS.ProcessEnv;
20
+ applications?: string[];
21
+ onSkip?: (message: string) => void;
22
+ }): Promise<{
23
+ kind: "app";
24
+ app: string;
25
+ command: string;
26
+ args: string[];
27
+ } | {
28
+ kind: "checkout";
29
+ dir: string;
30
+ command: string;
31
+ args: string[];
32
+ } | {
33
+ kind: "missing";
34
+ reason?: string;
35
+ }>;
36
+ /**
37
+ * @param {string[]} args
38
+ * @param {{ resolve?: typeof resolveDesktop, launch?: (command: string, args: string[], env: NodeJS.ProcessEnv) => Promise<void> }} [deps]
39
+ */
40
+ export function desktopCommand(args: string[], { resolve, launch }?: {
41
+ resolve?: typeof resolveDesktop;
42
+ launch?: (command: string, args: string[], env: NodeJS.ProcessEnv) => Promise<void>;
43
+ }): Promise<void>;
44
+ /**
45
+ * alp desktop (t-81b0.5): opens ALP's desktop app (apps/desktop, an Electron shell for macOS). The
46
+ * app is looked for, in order:
47
+ * 1. ALP.app in /Applications, then in ~/Applications (macOS), opened with `open`. Only a bundle
48
+ * whose CFBundleIdentifier is DESKTOP_BUNDLE_ID counts: another app of that name (an older ALP
49
+ * desktop app, say) is skipped with a one-line message and the lookup goes on;
50
+ * 2. a checkout named by ALP_DESKTOP_CHECKOUT (the repository root, or its apps/desktop), whose
51
+ * app is built (`bun install && bun run build` in apps/desktop), run with its own Electron;
52
+ * 3. neither: how to get it, and exit 1.
53
+ * Nothing secret passes here: the app asks `alp dashboard --print` for its address itself.
54
+ */
55
+ /** The bundle id of the packaged app (apps/desktop/electron-builder.yml, appId). */
56
+ export const DESKTOP_BUNDLE_ID: "com.anhlp.alp.shell";
@@ -0,0 +1,91 @@
1
+ // packages/cli/src/desktop.js
2
+ import { execFile, spawn } from "node:child_process";
3
+ import { readFile, stat } from "node:fs/promises";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { UsageError } from "./usage.js";
7
+ var DESKTOP_BUNDLE_ID = "com.anhlp.alp.shell";
8
+ async function readBundleId(app) {
9
+ const plist = path.join(app, "Contents", "Info.plist");
10
+ const text = await readFile(plist, "utf8").catch(() => void 0);
11
+ if (text === void 0) return void 0;
12
+ if (text.trimStart().startsWith("<")) {
13
+ const match = /<key>CFBundleIdentifier<\/key>\s*<string>([^<]*)<\/string>/.exec(text);
14
+ return match ? match[1].trim() : void 0;
15
+ }
16
+ return new Promise((resolve) => {
17
+ execFile("/usr/bin/plutil", ["-extract", "CFBundleIdentifier", "raw", "-o", "-", plist], (error, stdout) => resolve(error ? void 0 : stdout.trim() || void 0));
18
+ });
19
+ }
20
+ var isDirectory = (file) => stat(file).then((info) => info.isDirectory(), () => false);
21
+ var isFile = (file) => stat(file).then((info) => info.isFile(), () => false);
22
+ async function desktopPackage(dir) {
23
+ for (const candidate of [path.join(dir, "apps", "desktop"), dir]) {
24
+ const manifest = await readFile(path.join(candidate, "package.json"), "utf8").then((text) => {
25
+ try {
26
+ return JSON.parse(text);
27
+ } catch {
28
+ return void 0;
29
+ }
30
+ }, () => void 0);
31
+ if (manifest?.name === "alp-desktop") return candidate;
32
+ }
33
+ return void 0;
34
+ }
35
+ async function resolveDesktop({ platform = process.platform, home = os.homedir(), env = process.env, applications, onSkip = () => {
36
+ } } = {}) {
37
+ if (platform === "darwin") {
38
+ for (const directory of applications ?? ["/Applications", path.join(home, "Applications")]) {
39
+ const app = path.join(directory, "ALP.app");
40
+ if (!await isDirectory(app)) continue;
41
+ const id = await readBundleId(app);
42
+ if (id === DESKTOP_BUNDLE_ID) return { kind: "app", app, command: "open", args: [app] };
43
+ onSkip(`Skipped ${app}: its bundle id is ${id ? JSON.stringify(id) : "unreadable"}, not ${DESKTOP_BUNDLE_ID} (ALP's desktop app).`);
44
+ }
45
+ }
46
+ const checkout = env.ALP_DESKTOP_CHECKOUT;
47
+ if (!checkout) return { kind: "missing" };
48
+ const dir = await desktopPackage(path.resolve(checkout));
49
+ if (!dir) return { kind: "missing", reason: `ALP_DESKTOP_CHECKOUT=${checkout} is not an ALP checkout: neither it nor its apps/desktop holds the alp-desktop package.` };
50
+ const electron = path.join(dir, "node_modules", ".bin", platform === "win32" ? "electron.cmd" : "electron");
51
+ if (!await isFile(electron) || !await isFile(path.join(dir, "dist", "main.cjs"))) {
52
+ return { kind: "missing", reason: `The desktop app in ${dir} is not built: run \`bun install && bun run build\` there, then run alp desktop again.` };
53
+ }
54
+ return { kind: "checkout", dir, command: electron, args: [dir] };
55
+ }
56
+ var INSTRUCTIONS = `ALP's desktop app is not installed.
57
+ - Put ALP.app in /Applications (or ~/Applications), or
58
+ - point ALP_DESKTOP_CHECKOUT at an ALP checkout whose apps/desktop is built:
59
+ cd <checkout>/apps/desktop && bun install && bun run build
60
+ ALP_DESKTOP_CHECKOUT=<checkout> alp desktop
61
+ Meanwhile, \`alp dashboard\` opens ALP in your browser.`;
62
+ async function desktopCommand(args, { resolve = resolveDesktop, launch = start } = {}) {
63
+ if (args.length) throw new UsageError();
64
+ const found = await resolve({ onSkip: (message) => console.error(message) });
65
+ if (found.kind === "missing") {
66
+ if (found.reason) console.error(found.reason);
67
+ console.error(INSTRUCTIONS);
68
+ process.exitCode = 1;
69
+ return;
70
+ }
71
+ const env = { ...process.env };
72
+ delete env.ELECTRON_RUN_AS_NODE;
73
+ await launch(found.command, found.args, env);
74
+ console.log(found.kind === "app" ? `Opened ${found.app}.` : `Started the desktop app from ${found.dir}.`);
75
+ }
76
+ function start(command, args, env) {
77
+ return new Promise((resolve, reject) => {
78
+ const child = spawn(command, args, { stdio: "ignore", detached: true, env });
79
+ child.once("error", reject);
80
+ child.once("spawn", () => {
81
+ child.unref();
82
+ resolve();
83
+ });
84
+ });
85
+ }
86
+ export {
87
+ DESKTOP_BUNDLE_ID,
88
+ desktopCommand,
89
+ readBundleId,
90
+ resolveDesktop
91
+ };
@@ -1,6 +1,25 @@
1
1
  /**
2
- * alp web pair: the link that pairs Paseo's app on another device with alpd through Paseo's relay
3
- * (ALPD §64). The device then signs in with the token that `alp web --print` shows.
2
+ * Starts the Paseo integration. For one release, a home that still has only the descriptor
3
+ * registered before the rename (`integrations/web.json`) keeps working, with a hint to re-register.
4
+ * Exported for tests.
5
+ * @param {string} home
6
+ */
7
+ export function startPaseoIntegration(home: string): Promise<any>;
8
+ /**
9
+ * Registers `directory` as a project in alpd via IPC (`project.register`).
10
+ * If alpd cannot be reached or the call fails, this is best-effort.
11
+ * @param {string} home
12
+ * @param {string} directory
13
+ * @param {{ timeoutMs?: number, connectClient?: typeof connect }} [options]
14
+ */
15
+ export function registerProject(home: string, directory: string, { timeoutMs, connectClient }?: {
16
+ timeoutMs?: number;
17
+ connectClient?: typeof connect;
18
+ }): Promise<void>;
19
+ /**
20
+ * alp dashboard pair: the link that pairs Paseo's app on another device with alpd through Paseo's relay
21
+ * (ALPD §64). The device then signs in with the password this command prints (the token kept in
22
+ * ~/.alp/paseo.json).
4
23
  */
5
24
  /**
6
25
  * `web.pairing` is an extension the integration registers on its alpd connection. Right after an
@@ -10,7 +29,8 @@
10
29
  * Exported so the wait can be pinned by a regression test without a live daemon restart.
11
30
  */
12
31
  export function requestPairing(client: any, params: any, attempts?: number): Promise<any>;
13
- export function webCommand(args: any): Promise<void>;
32
+ import { connect } from '@anhlp/alp-client/index';
33
+ export function dashboardCommand(args: any): Promise<any>;
14
34
  export function pairCommand(args: any): Promise<void>;
15
35
  /** alp acp: ALP as an ACP agent for editors; stdout carries only the protocol (ALPD §60). */
16
36
  export function acpCommand(args: any): Promise<void>;