@anhlp/alp-cli 0.0.1-beta.8 → 0.0.1-beta.9

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 (50) hide show
  1. package/dist/acp/main.js +1 -1
  2. package/dist/acp.js +180 -82
  3. package/dist/{alp-web → alp-dashboard}/THIRD-PARTY-NOTICES.txt +1 -1
  4. package/dist/{alp-web/assets/TerminalPanel-BbYa_Xkd.js → alp-dashboard/assets/TerminalPanel-BSjqIfNr.js} +1 -1
  5. package/dist/{alp-web/assets/index-DOJh89Ik.js → alp-dashboard/assets/index-CZFfSOIE.js} +5 -5
  6. package/dist/{alp-web → alp-dashboard}/index.html +1 -1
  7. package/dist/{alp-web.js → alp-dashboard.js} +349 -306
  8. package/dist/alpd.js +1308 -1271
  9. package/dist/backup.js +1 -1
  10. package/dist/build-manifest.json +14 -5
  11. package/dist/cli.js +4 -3
  12. package/dist/daemon.d.ts +1 -1
  13. package/dist/daemon.js +6 -6
  14. package/dist/dashboard-migrate.d.ts +31 -0
  15. package/dist/dashboard-migrate.js +127 -0
  16. package/dist/dashboard-service.d.ts +69 -0
  17. package/dist/{web-service.js → dashboard-service.js} +30 -32
  18. package/dist/desktop.d.ts +56 -0
  19. package/dist/desktop.js +91 -0
  20. package/dist/interfaces.d.ts +2 -2
  21. package/dist/interfaces.js +133 -43
  22. package/dist/paths.d.ts +6 -1
  23. package/dist/paths.js +4 -2
  24. package/dist/roles.d.ts +5 -5
  25. package/dist/self-update.d.ts +2 -1
  26. package/dist/self-update.js +7 -1
  27. package/dist/sessions.d.ts +0 -1
  28. package/dist/usage.d.ts +1 -1
  29. package/dist/usage.js +6 -4
  30. package/package.json +6 -6
  31. package/src/cli.js +3 -2
  32. package/src/daemon.js +7 -6
  33. package/src/dashboard-migrate.js +152 -0
  34. package/src/{web-service.js → dashboard-service.js} +54 -48
  35. package/src/desktop.js +122 -0
  36. package/src/interfaces.js +170 -61
  37. package/src/paths.js +9 -3
  38. package/src/roles.js +4 -4
  39. package/src/self-update.js +10 -2
  40. package/src/sessions.js +0 -2
  41. package/src/usage.js +6 -4
  42. package/dist/web-service.d.ts +0 -56
  43. /package/dist/{alp-web → alp-dashboard}/alp-boundary.json +0 -0
  44. /package/dist/{alp-web → alp-dashboard}/apple-touch-icon.png +0 -0
  45. /package/dist/{alp-web → alp-dashboard}/assets/TerminalPanel-DLuoa74B.css +0 -0
  46. /package/dist/{alp-web → alp-dashboard}/assets/highlighter-BnicKQ_d.js +0 -0
  47. /package/dist/{alp-web → alp-dashboard}/assets/index-DwqDSiIi.css +0 -0
  48. /package/dist/{alp-web → alp-dashboard}/favicon-attention.svg +0 -0
  49. /package/dist/{alp-web → alp-dashboard}/favicon-running.svg +0 -0
  50. /package/dist/{alp-web → alp-dashboard}/favicon.svg +0 -0
package/dist/backup.js CHANGED
@@ -7,7 +7,7 @@ import { acquireDaemonLock, alpHome, assertPrivateDirectory, daemonPaths, lockAl
7
7
  import { daemonHeld, holdDaemon, releaseHold } from "@anhlp/alp-client/supervise";
8
8
  import { start, stop } from "./daemon.js";
9
9
  import { UsageError } from "./usage.js";
10
- var VERSION = true ? "0.0.1-beta.8" : "dev";
10
+ var VERSION = true ? "0.0.1-beta.9" : "dev";
11
11
  var BY = `alp ${VERSION}`;
12
12
  var size = (bytes) => bytes >= 1024 * 1024 ? `${(bytes / 1024 / 1024).toFixed(1)} MB` : bytes >= 1024 ? `${(bytes / 1024).toFixed(1)} KB` : `${bytes} B`;
13
13
  var stamp = () => (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.0.1-beta.8",
2
+ "version": "0.0.1-beta.9",
3
3
  "entries": {
4
4
  "packages/cli/dist/alpd.js": {
5
5
  "inputs": [
@@ -165,8 +165,16 @@
165
165
  "packages/client/src/service.js",
166
166
  "packages/client/src/supervise.js",
167
167
  "packages/client/src/websocket.js",
168
+ "packages/core/src/atomic.js",
169
+ "packages/core/src/errors.js",
168
170
  "packages/core/src/log.js",
171
+ "packages/core/src/models.js",
169
172
  "packages/core/src/packaged.js",
173
+ "packages/core/src/permissions.js",
174
+ "packages/core/src/shell.js",
175
+ "packages/core/src/user-settings.js",
176
+ "packages/core/src/validation.js",
177
+ "packages/core/src/verify.js",
170
178
  "packages/protocol/src/index.ts",
171
179
  "packages/protocol/src/wire.js"
172
180
  ],
@@ -182,7 +190,7 @@
182
190
  "node:timers/promises"
183
191
  ]
184
192
  },
185
- "packages/cli/dist/alp-web.js": {
193
+ "packages/cli/dist/alp-dashboard.js": {
186
194
  "inputs": [
187
195
  "apps/gateway/src/config.js",
188
196
  "apps/gateway/src/connection.js",
@@ -193,9 +201,9 @@
193
201
  "apps/gateway/src/server.js",
194
202
  "apps/gateway/src/tickets.js",
195
203
  "apps/gateway/src/upstream.js",
196
- "packages/cli/src/web/grant.js",
197
- "packages/cli/src/web/main.js",
198
- "packages/cli/src/web/serve.js",
204
+ "packages/cli/src/dashboard/grant.js",
205
+ "packages/cli/src/dashboard/main.js",
206
+ "packages/cli/src/dashboard/serve.js",
199
207
  "packages/client/src/command.js",
200
208
  "packages/client/src/index.js",
201
209
  "packages/client/src/integration-lock.js",
@@ -229,6 +237,7 @@
229
237
  "packages/core/src/tasks.js",
230
238
  "packages/core/src/teams.js",
231
239
  "packages/core/src/template-path.js",
240
+ "packages/core/src/user-settings.js",
232
241
  "packages/core/src/validation.js",
233
242
  "packages/core/src/verify.js",
234
243
  "packages/protocol/src/contract-v1.js",
package/dist/cli.js CHANGED
@@ -12,7 +12,8 @@ import { run, ps, attach, send, questions, answer, top, log, board, models, paus
12
12
  import { libraryCommand, editCommand, teamsCommand, packsCommand, packCommand } from "./library.js";
13
13
  import { scheduleCommand } from "./schedules.js";
14
14
  import { tasksCommand, formulaCommand, taskCommand } from "./tasks.js";
15
- import { webCommand, acpCommand } from "./interfaces.js";
15
+ import { dashboardCommand, acpCommand } from "./interfaces.js";
16
+ import { desktopCommand } from "./desktop.js";
16
17
  import { backupCommand, restoreCommand } from "./backup.js";
17
18
  import { terminalCommand } from "./terminal.js";
18
19
  import { bridgeCommand } from "./roles.js";
@@ -20,7 +21,7 @@ import { selfUpdate } from "./self-update.js";
20
21
  import { bundleInfo } from "@anhlp/alp-core/packaged";
21
22
  import { connect, lockAlive, readLock } from "@anhlp/alp-client/index";
22
23
  function alpVersion() {
23
- return true ? "0.0.1-beta.8" : JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
24
+ return true ? "0.0.1-beta.9" : JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
24
25
  }
25
26
  async function runningDaemon() {
26
27
  const lock = await readLock(alpHome());
@@ -40,7 +41,7 @@ async function updateCommand(args2) {
40
41
  const code = await selfUpdate(args2, { bundle: bundleInfo(), version: alpVersion(), daemon: runningDaemon });
41
42
  if (code) process.exitCode = code;
42
43
  }
43
- var commands = { schedule: scheduleCommand, setup: (args2) => setup(args2, alpHome()), init: (args2) => project("init", args2), "update-template": (args2) => project("upgrade", args2), upgrade: (args2) => project("upgrade", args2), update: updateCommand, daemon, doctor, run, ps, top, attach, send, questions, answer, log, board, tasks: tasksCommand, task: taskCommand, formula: formulaCommand, permissions: permissionsCommand, agents: (args2) => libraryCommand("agents", args2), skills: (args2) => libraryCommand("skills", args2), mcp: (args2) => ["add", "rm", "mv", "cp", "test", "show", "edit"].includes(args2[0]) ? editCommand("mcp", args2) : libraryCommand("mcp", args2), hooks: (args2) => libraryCommand("hooks", args2), providers: (args2) => libraryCommand("providers", args2), provider: (args2) => editCommand("providers", args2), teams: teamsCommand, packs: packsCommand, pack: packCommand, trust: trustCommand, agent: (args2) => editCommand("agents", args2), team: (args2) => editCommand("teams", args2), skill: (args2) => editCommand("skills", args2), hook: (args2) => editCommand("hooks", args2), verify, recall, pause, resume, language, models, interrupt, compact, acp: acpCommand, web: webCommand, backup: backupCommand, restore: restoreCommand, terminal: terminalCommand, bridge: bridgeCommand };
44
+ var commands = { schedule: scheduleCommand, setup: (args2) => setup(args2, alpHome()), init: (args2) => project("init", args2), "update-template": (args2) => project("upgrade", args2), upgrade: (args2) => project("upgrade", args2), update: updateCommand, daemon, doctor, run, ps, top, attach, send, questions, answer, log, board, tasks: tasksCommand, task: taskCommand, formula: formulaCommand, permissions: permissionsCommand, agents: (args2) => libraryCommand("agents", args2), skills: (args2) => libraryCommand("skills", args2), mcp: (args2) => ["add", "rm", "mv", "cp", "test", "show", "edit"].includes(args2[0]) ? editCommand("mcp", args2) : libraryCommand("mcp", args2), hooks: (args2) => libraryCommand("hooks", args2), providers: (args2) => libraryCommand("providers", args2), provider: (args2) => editCommand("providers", args2), teams: teamsCommand, packs: packsCommand, pack: packCommand, trust: trustCommand, agent: (args2) => editCommand("agents", args2), team: (args2) => editCommand("teams", args2), skill: (args2) => editCommand("skills", args2), hook: (args2) => editCommand("hooks", args2), verify, recall, pause, resume, language, models, interrupt, compact, acp: acpCommand, dashboard: dashboardCommand, desktop: desktopCommand, backup: backupCommand, restore: restoreCommand, terminal: terminalCommand, bridge: bridgeCommand };
44
45
  var [command, ...args] = process.argv.slice(2);
45
46
  try {
46
47
  if (command === "--version") {
package/dist/daemon.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export function built(): Promise<void>;
1
+ export function built(entry?: string): Promise<void>;
2
2
  /** Waits until an alpd for this home is ready; returns its socket. Default wait: ALP_DAEMON_START_TIMEOUT_MS, else 60 s. */
3
3
  export function ready(timeoutMs?: number): Promise<any>;
4
4
  /** The installed service for this ALP_HOME, if any. */
package/dist/daemon.js CHANGED
@@ -6,13 +6,13 @@ import { holdDaemon, startDaemon } from "@anhlp/alp-client/supervise";
6
6
  import { alpHome, connect, daemonStartTimeoutMs, lockAlive, readLock, withDaemonLifecycle } from "@anhlp/alp-client/index";
7
7
  import { scrubText } from "@anhlp/alp-core/log";
8
8
  import { UsageError } from "./usage.js";
9
- import { DAEMON_ENTRY } from "./paths.js";
9
+ import { DAEMON_ENTRY, DAEMON_SCRIPT } from "./paths.js";
10
10
  import { runRole } from "./roles.js";
11
- async function built() {
11
+ async function built(entry = DAEMON_ENTRY) {
12
12
  try {
13
- await access(DAEMON_ENTRY);
13
+ await access(entry);
14
14
  } catch {
15
- throw new Error(`alpd is not built (${DAEMON_ENTRY}); run npm run build`);
15
+ throw new Error(`alpd is not built (${entry}); run npm run build`);
16
16
  }
17
17
  }
18
18
  async function ready(timeoutMs = daemonStartTimeoutMs()) {
@@ -48,8 +48,8 @@ async function stop() {
48
48
  }
49
49
  async function daemon([action, ...rest]) {
50
50
  if (action === "run") {
51
- await built();
52
- return runRole("daemon", DAEMON_ENTRY, rest);
51
+ await built(DAEMON_SCRIPT);
52
+ return runRole("daemon", DAEMON_SCRIPT, rest);
53
53
  }
54
54
  if (rest.length && !(action === "status" && rest.length === 1 && rest[0] === "--json")) throw new UsageError();
55
55
  if (action === "start") {
@@ -0,0 +1,31 @@
1
+ /**
2
+ * @param {string} home
3
+ * @param {{ strict?: boolean }} [options] strict: a legacy holder alp cannot stop is an error (a start
4
+ * would otherwise lose its port to it); without it, it is reported and the files are left alone.
5
+ * @returns {Promise<{ stopped?: number, held?: boolean, moved: string[], kept: string[], warnings: string[] }>}
6
+ * held: a legacy holder alp would not stop is still running (only without strict).
7
+ */
8
+ export function migrateDashboard(home: string, { strict }?: {
9
+ strict?: boolean;
10
+ }): Promise<{
11
+ stopped?: number;
12
+ held?: boolean;
13
+ moved: string[];
14
+ kept: string[];
15
+ warnings: string[];
16
+ }>;
17
+ /**
18
+ * What a home still has under the names from before the rename, without changing anything (for
19
+ * `alp dashboard --status`): `pending` the next `alp dashboard` moves, `kept` it leaves because the
20
+ * new name exists, and the legacy service if one runs.
21
+ * @param {string} home
22
+ * @returns {Promise<{ legacy?: { pid?: number, reason?: string }, pending: string[], kept: string[] }>}
23
+ */
24
+ export function legacyLeftovers(home: string): Promise<{
25
+ legacy?: {
26
+ pid?: number;
27
+ reason?: string;
28
+ };
29
+ pending: string[];
30
+ kept: string[];
31
+ }>;
@@ -0,0 +1,127 @@
1
+ // packages/cli/src/dashboard-migrate.js
2
+ import { randomBytes } from "node:crypto";
3
+ import { chmod, link, lstat, readFile, rename, unlink, writeFile } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { migrateDashboardSettings } from "@anhlp/alp-core/user-settings";
6
+ import { DASHBOARD, LEGACY_WEB, refusal, serviceOwner, stopService } from "./dashboard-service.js";
7
+ var exists = (file) => lstat(file).then(() => true, () => false);
8
+ var readJson = (file) => readFile(file, "utf8").then((text) => {
9
+ try {
10
+ return JSON.parse(text);
11
+ } catch {
12
+ return void 0;
13
+ }
14
+ }, () => void 0);
15
+ var code = (error) => (
16
+ /** @type {any} */
17
+ error?.code
18
+ );
19
+ async function migrateDashboard(home, { strict = false } = {}) {
20
+ const report = { moved: [], kept: [], warnings: [] };
21
+ const owner = await serviceOwner(home, LEGACY_WEB);
22
+ if ("pid" in owner || owner.alive && owner.kind === "transient") {
23
+ try {
24
+ report.stopped = await stopService(home, 3e4, LEGACY_WEB);
25
+ } catch (error) {
26
+ if (strict) throw error;
27
+ report.warnings.push(
28
+ /** @type {any} */
29
+ error?.message ?? String(error)
30
+ );
31
+ report.held = true;
32
+ return report;
33
+ }
34
+ } else if (owner.alive) {
35
+ const message = `${refusal(home, LEGACY_WEB)} (${owner.reason}); stop it, then run the command again`;
36
+ if (strict) throw new Error(message);
37
+ report.warnings.push(message);
38
+ report.held = true;
39
+ return report;
40
+ }
41
+ const oldStore = path.join(home, "web");
42
+ const newStore = path.join(home, "dashboard");
43
+ if (await exists(path.join(oldStore, "credentials.json"))) {
44
+ if (await exists(newStore)) report.kept.push(oldStore);
45
+ else {
46
+ try {
47
+ await rename(oldStore, newStore);
48
+ report.moved.push(`${oldStore} -> ${newStore}`);
49
+ } catch (error) {
50
+ if (!["ENOENT", "EEXIST", "ENOTEMPTY"].includes(code(error))) throw error;
51
+ }
52
+ }
53
+ }
54
+ const oldInfo = path.join(home, LEGACY_WEB.info);
55
+ const newInfo = path.join(home, DASHBOARD.info);
56
+ const published = await readJson(oldInfo);
57
+ if (published?.app === LEGACY_WEB.app) {
58
+ const carriedAlready = async () => typeof published.token === "string" && published.token !== "" && (await readJson(newInfo))?.token === published.token;
59
+ const removeOld = () => unlink(oldInfo).catch((error) => {
60
+ if (code(error) !== "ENOENT") throw error;
61
+ });
62
+ if (await exists(newInfo)) {
63
+ if (await carriedAlready()) await removeOld();
64
+ else report.kept.push(oldInfo);
65
+ } else {
66
+ const carried = { version: published.version, app: DASHBOARD.app, token: published.token, credentialId: published.credentialId };
67
+ const temporary = `${newInfo}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
68
+ try {
69
+ await writeFile(temporary, `${JSON.stringify(carried)}
70
+ `, { mode: 384, flag: "wx" });
71
+ await chmod(temporary, 384);
72
+ const linked = await link(temporary, newInfo).then(() => true, (error) => {
73
+ if (code(error) !== "EEXIST") throw error;
74
+ return false;
75
+ });
76
+ if (linked) {
77
+ report.moved.push(`${oldInfo} -> ${newInfo}`);
78
+ await removeOld();
79
+ } else if (await carriedAlready()) await removeOld();
80
+ else report.kept.push(oldInfo);
81
+ } finally {
82
+ await unlink(temporary).catch(() => {
83
+ });
84
+ }
85
+ }
86
+ }
87
+ const logs = path.join(home, "logs", "integrations");
88
+ const oldLog = path.join(logs, "alp-web.log");
89
+ const newLog = path.join(logs, "alp-dashboard.log");
90
+ if (await exists(oldLog) && !await exists(newLog)) {
91
+ await rename(oldLog, newLog).then(() => report.moved.push(`${oldLog} -> ${newLog}`), (error) => {
92
+ if (code(error) !== "ENOENT") throw error;
93
+ });
94
+ }
95
+ try {
96
+ const settings = await migrateDashboardSettings(home);
97
+ for (const key of settings.moved) report.moved.push(`settings.json web.${key} -> dashboard.${key}`);
98
+ for (const key of settings.conflicts) report.kept.push(`settings.json web.${key} (dashboard.${key} is set and wins)`);
99
+ } catch (error) {
100
+ report.warnings.push(`settings.json was not migrated (web.* is still read): ${/** @type {any} */
101
+ error?.message ?? error}`);
102
+ }
103
+ return report;
104
+ }
105
+ async function legacyLeftovers(home) {
106
+ const result = { pending: [], kept: [] };
107
+ const owner = await serviceOwner(home, LEGACY_WEB);
108
+ if ("pid" in owner) result.legacy = { pid: owner.pid };
109
+ else if (owner.alive) result.legacy = { reason: owner.reason };
110
+ const place = async (old, current) => (await exists(current) ? result.kept : result.pending).push(old);
111
+ if (await exists(path.join(home, "web", "credentials.json"))) await place(path.join(home, "web"), path.join(home, "dashboard"));
112
+ const published = await readJson(path.join(home, LEGACY_WEB.info));
113
+ if (published?.app === LEGACY_WEB.app) await place(path.join(home, LEGACY_WEB.info), path.join(home, DASHBOARD.info));
114
+ const logs = path.join(home, "logs", "integrations");
115
+ if (await exists(path.join(logs, "alp-web.log"))) await place(path.join(logs, "alp-web.log"), path.join(logs, "alp-dashboard.log"));
116
+ const settings = await readJson(path.join(home, "settings.json"));
117
+ for (const key of ["enabled", "port", "permissions"]) {
118
+ if (settings?.web?.[key] === void 0) continue;
119
+ if (settings?.dashboard?.[key] !== void 0) result.kept.push(`settings.json web.${key} (dashboard.${key} is set and wins)`);
120
+ else result.pending.push(`settings.json web.${key}`);
121
+ }
122
+ return result;
123
+ }
124
+ export {
125
+ legacyLeftovers,
126
+ migrateDashboard
127
+ };
@@ -0,0 +1,69 @@
1
+ /** The alp-dashboard service script beside this CLI; a clear error when this CLI was built without it. */
2
+ export function dashboardScript(): string;
3
+ /**
4
+ * The process that owns `service`'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 its file 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 creation time with the process's start from ps: when
10
+ * `startedUptime` is recorded, monotonic uptime comparison prevents clock step vulnerabilities.
11
+ * For legacy locks, wall-clock `startedAt` is compared.
12
+ * @param {string} home @param {Service} [service]
13
+ * @returns {Promise<{ pid: number, app: unknown } | { reason: string, alive: boolean, kind?: 'transient' | 'foreign' | 'unknown' }>}
14
+ */
15
+ export function serviceOwner(home: string, service?: Service): Promise<{
16
+ pid: number;
17
+ app: unknown;
18
+ } | {
19
+ reason: string;
20
+ alive: boolean;
21
+ kind?: "transient" | "foreign" | "unknown";
22
+ }>;
23
+ /**
24
+ * Stops whatever runs as `service` (alp dashboard; for LEGACY_WEB, alp web from before the rename or
25
+ * the Paseo integration from before its own), waiting up to `timeoutMs` for a starting owner to
26
+ * publish what proves it. Resolves with the pid it stopped, or undefined once no live process owns
27
+ * the lock; refuses at once an owner that is foreign or cannot be proven.
28
+ * @param {string} home @param {number} [timeoutMs] @param {Service} [service]
29
+ */
30
+ export function stopService(home: string, timeoutMs?: number, service?: Service): Promise<number | undefined>;
31
+ /** The opening of the message for a lock held by a process alp would not stop. @param {string} home @param {Service} [service] */
32
+ export function refusal(home: string, service?: Service): string;
33
+ /**
34
+ * Probes whether the published dashboard URL is live and answering requests.
35
+ * Accepts only loopback HTTP/HTTPS addresses.
36
+ * @param {string | undefined} url
37
+ * @param {number} [timeoutMs]
38
+ */
39
+ export function isDashboardReady(url: string | undefined, timeoutMs?: number): Promise<boolean>;
40
+ /**
41
+ * Whether the published file is genuinely claimed by a live alp-dashboard process.
42
+ * If the process is proven foreign (e.g. a reused PID or from another boot) or
43
+ * the URL does not answer HTTP requests, it is never claimed.
44
+ * @param {any} published
45
+ * @param {number | undefined} lockPid
46
+ * @param {any} held
47
+ * @param {number} [timeoutMs]
48
+ */
49
+ export function isServiceClaimed(published: any, lockPid: number | undefined, held: any, timeoutMs?: number): Promise<boolean>;
50
+ export function dashboardEntry(): string;
51
+ /**
52
+ * @typedef {{ lock: string, info: string, app: string, what: string }} Service
53
+ * The integration lock's name, the file the service publishes, the `app` it writes there, and what
54
+ * messages call it.
55
+ */
56
+ /** @type {Service} */
57
+ export const DASHBOARD: Service;
58
+ /** alp web as 0.0.1-beta.8 and earlier ran it (and, before that, the Paseo integration). @type {Service} */
59
+ export const LEGACY_WEB: Service;
60
+ /**
61
+ * The integration lock's name, the file the service publishes, the `app` it writes there, and what
62
+ * messages call it.
63
+ */
64
+ export type Service = {
65
+ lock: string;
66
+ info: string;
67
+ app: string;
68
+ what: string;
69
+ };
@@ -1,4 +1,4 @@
1
- // packages/cli/src/web-service.js
1
+ // packages/cli/src/dashboard-service.js
2
2
  import { execFile } from "node:child_process";
3
3
  import { existsSync } from "node:fs";
4
4
  import { lstat, readFile } from "node:fs/promises";
@@ -11,12 +11,14 @@ import { distributionEntry } from "./paths.js";
11
11
  import { selfEntry } from "@anhlp/alp-core/packaged";
12
12
  var execFileAsync = promisify(execFile);
13
13
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
14
- function alpWebScript() {
15
- const entry = fileURLToPath(distributionEntry("alp-web.js"));
16
- 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.`);
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
17
  return entry;
18
18
  }
19
- var alpWebEntry = () => selfEntry(alpWebScript());
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" });
20
22
  var readJson = async (file) => JSON.parse(await readFile(file, "utf8"));
21
23
  async function processTimes(pid) {
22
24
  try {
@@ -30,9 +32,9 @@ async function processTimes(pid) {
30
32
  return void 0;
31
33
  }
32
34
  }
33
- async function webOwner(home) {
34
- const lockFile = path.join(home, "integrations", "web.lock");
35
- const infoFile = path.join(home, "web.json");
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);
36
38
  let lock, lockInfo;
37
39
  try {
38
40
  lockInfo = await lstat(lockFile);
@@ -90,31 +92,26 @@ async function terminate(pid, what, timeoutMs = 2e4) {
90
92
  }
91
93
  throw new Error(`${what} (pid ${pid}) did not stop within ${timeoutMs / 1e3} s of SIGTERM; stop it, then run the command again`);
92
94
  }
93
- var isAlpWeb = (app) => app === "alp-web";
94
95
  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) {
96
+ var ownerName = (service, app) => app === service.app || service === DASHBOARD ? service.what : PASEO_BEFORE_RENAME;
97
+ async function stopService(home, timeoutMs = 3e4, service = DASHBOARD) {
102
98
  const deadline = Date.now() + timeoutMs;
103
99
  for (; ; ) {
104
- const owner = await webOwner(home);
100
+ const owner = await serviceOwner(home, service);
105
101
  if ("pid" in owner) {
106
- await terminate(owner.pid, isAlpWeb(owner.app) ? "alp web" : PASEO_BEFORE_RENAME);
102
+ await terminate(owner.pid, ownerName(service, owner.app));
107
103
  return owner.pid;
108
104
  }
109
105
  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`);
106
+ if (owner.kind !== "transient" || Date.now() >= deadline) throw new Error(`${refusal(home, service)} (${owner.reason}); stop it, then run the command again`);
111
107
  await sleep(200);
112
108
  }
113
109
  }
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`;
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`;
116
113
  }
117
- async function isWebReady(url, timeoutMs = 1e3) {
114
+ async function isDashboardReady(url, timeoutMs = 1e3) {
118
115
  if (typeof url !== "string" || !url) return false;
119
116
  try {
120
117
  const parsed = new URL(url);
@@ -126,18 +123,19 @@ async function isWebReady(url, timeoutMs = 1e3) {
126
123
  return false;
127
124
  }
128
125
  }
129
- async function isWebClaimed(published, lockPid, held, timeoutMs = 1e3) {
130
- if (published?.app !== "alp-web" || published.pid !== lockPid) return false;
126
+ async function isServiceClaimed(published, lockPid, held, timeoutMs = 1e3) {
127
+ if (published?.app !== DASHBOARD.app || published.pid !== lockPid) return false;
131
128
  if (held?.kind === "foreign") return false;
132
- return isWebReady(published.url, timeoutMs);
129
+ return isDashboardReady(published.url, timeoutMs);
133
130
  }
134
131
  export {
135
- alpWebEntry,
136
- alpWebScript,
137
- isWebClaimed,
138
- isWebReady,
132
+ DASHBOARD,
133
+ LEGACY_WEB,
134
+ dashboardEntry,
135
+ dashboardScript,
136
+ isDashboardReady,
137
+ isServiceClaimed,
139
138
  refusal,
140
- stopPreRenamePaseo,
141
- stopWebService,
142
- webOwner
139
+ serviceOwner,
140
+ stopService
143
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
+ };
@@ -17,7 +17,7 @@ export function registerProject(home: string, directory: string, { timeoutMs, co
17
17
  connectClient?: typeof connect;
18
18
  }): Promise<void>;
19
19
  /**
20
- * alp web pair: the link that pairs Paseo's app on another device with alpd through Paseo's relay
20
+ * alp dashboard pair: the link that pairs Paseo's app on another device with alpd through Paseo's relay
21
21
  * (ALPD §64). The device then signs in with the password this command prints (the token kept in
22
22
  * ~/.alp/paseo.json).
23
23
  */
@@ -30,7 +30,7 @@ export function registerProject(home: string, directory: string, { timeoutMs, co
30
30
  */
31
31
  export function requestPairing(client: any, params: any, attempts?: number): Promise<any>;
32
32
  import { connect } from '@anhlp/alp-client/index';
33
- export function webCommand(args: any): Promise<any>;
33
+ export function dashboardCommand(args: any): Promise<any>;
34
34
  export function pairCommand(args: any): Promise<void>;
35
35
  /** alp acp: ALP as an ACP agent for editors; stdout carries only the protocol (ALPD §60). */
36
36
  export function acpCommand(args: any): Promise<void>;