@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
@@ -1,55 +1,283 @@
1
1
  // packages/cli/src/interfaces.js
2
- import { spawn } from "node:child_process";
3
- import { readFile } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ import { execFile, spawn } from "node:child_process";
4
+ import { readFile, realpath, stat } from "node:fs/promises";
4
5
  import path from "node:path";
5
6
  import { parseArgs } from "node:util";
6
- import { alpHome, lockAlive, readLock, startIntegration } from "@anhlp/alp-client/index";
7
+ import { alpHome, connect, daemonPaths, discoverIntegration, startIntegration } from "@anhlp/alp-client/index";
7
8
  import { UsageError } from "./usage.js";
8
9
  import { built, start, running } from "./daemon.js";
9
10
  import { DAEMON_ENTRY, distributionEntry } from "./paths.js";
10
- async function webCommand(args) {
11
- if (args[0] === "pair") return pairCommand(args.slice(1));
12
- const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { print: { type: "boolean" } } });
13
- if (positionals.length) throw new UsageError();
14
- const lock = await readLock(alpHome()).catch(() => void 0);
15
- await start();
16
- try {
17
- const settings = JSON.parse(await readFile(path.join(alpHome(), "settings.json"), "utf8"));
18
- if (settings?.web?.enabled === false) throw new Error('ALP web app is disabled by settings ("web.enabled": false).');
19
- } catch (error) {
20
- if (/disabled by settings/.test(error?.message ?? "")) throw error;
11
+ import { entryCommand } from "@anhlp/alp-core/packaged";
12
+ import { isAgentProcess } from "@anhlp/alp-core/tasks";
13
+ import { runRole } from "./roles.js";
14
+ import { DASHBOARD, LEGACY_WEB, dashboardEntry, dashboardScript, isDashboardReady, isServiceClaimed, refusal, serviceOwner, stopService } from "./dashboard-service.js";
15
+ import { legacyLeftovers, migrateDashboard } from "./dashboard-migrate.js";
16
+ import { dashboardSettings } from "@anhlp/alp-core/user-settings";
17
+ var PASEO = "paseo";
18
+ async function startPaseoIntegration(home) {
19
+ const entry = await discoverIntegration(PASEO, { home });
20
+ if (!entry) {
21
+ const legacy = path.join(home, "integrations", "web.json");
22
+ const legacyEntry = await legacyDescriptorEntry(legacy, home);
23
+ if (legacyEntry) {
24
+ console.error(`Using the Paseo integration registered before its rename (${legacy}); run \`alp-paseo-integration --register\` to register it again.`);
25
+ return startIntegration({ name: PASEO, entry: legacyEntry, home });
26
+ }
21
27
  }
22
- await startIntegration();
23
- const home = alpHome();
24
- const file = path.join(home, "web.json");
25
- let info;
26
- for (let i = 0; i < 100; i++) {
27
- info = await readFile(file, "utf8").then(JSON.parse, () => void 0);
28
- let alive = false;
29
- try {
30
- if (info?.pid) {
31
- process.kill(info.pid, 0);
32
- alive = true;
28
+ return startIntegration({ name: PASEO, home });
29
+ }
30
+ async function legacyDescriptorEntry(file, home) {
31
+ const raw = await readFile(file, "utf8").then((text) => JSON.parse(text)).catch(() => void 0);
32
+ const isFile = (candidate) => stat(candidate).then((info) => info.isFile(), () => false);
33
+ for (const field of ["main", "entry", "path", "command"]) {
34
+ const value = raw?.[field];
35
+ if (typeof value !== "string" || !value.trim()) continue;
36
+ const candidates = path.isAbsolute(value) ? [value] : [path.resolve(path.dirname(file), value), path.resolve(home, value)];
37
+ for (const candidate of candidates) if (await isFile(candidate)) return candidate;
38
+ }
39
+ return void 0;
40
+ }
41
+ async function currentProject() {
42
+ const cwd = process.cwd();
43
+ return await stat(path.join(cwd, ".alp")).then((info) => info.isDirectory(), () => false) ? cwd : void 0;
44
+ }
45
+ async function projectArgs() {
46
+ const project = await currentProject();
47
+ return project ? ["--project", project] : [];
48
+ }
49
+ async function registerProject(home, directory, { timeoutMs = 5e3, connectClient = connect } = {}) {
50
+ const socket = daemonPaths(home).socket;
51
+ let client;
52
+ let expired = false;
53
+ let timer;
54
+ const work = (async () => {
55
+ const connected = await connectClient(socket, { name: "alp-cli", version: "1" }, { timeoutMs });
56
+ if (expired) {
57
+ connected.close();
58
+ return;
59
+ }
60
+ client = connected;
61
+ for (let attempt = 0; attempt < 5 && !expired; attempt++) {
62
+ const list = await client.request("project.list", { limit: 1 }, { timeoutMs }).catch(() => void 0);
63
+ if (expired) return;
64
+ const revision = typeof list?.revision === "number" ? list.revision : 0;
65
+ try {
66
+ await client.request("project.register", { directory, ifRevision: revision, requestId: randomUUID() }, { timeoutMs });
67
+ break;
68
+ } catch (error) {
69
+ if (error?.data?.reason === "stale_revision" && attempt < 4) continue;
70
+ break;
33
71
  }
72
+ }
73
+ })();
74
+ try {
75
+ await Promise.race([work.catch(() => {
76
+ }), new Promise((resolve) => {
77
+ timer = setTimeout(() => {
78
+ expired = true;
79
+ try {
80
+ client?.close();
81
+ } catch {
82
+ }
83
+ resolve(void 0);
84
+ }, timeoutMs);
85
+ })]);
86
+ } finally {
87
+ expired = true;
88
+ clearTimeout(timer);
89
+ try {
90
+ client?.close();
34
91
  } catch {
35
- alive = false;
36
92
  }
37
- let integrationPid = void 0;
93
+ }
94
+ }
95
+ async function waitForGrant(home, credentialId, project, { timeoutMs = 5e3 } = {}) {
96
+ const credentialsFile = path.join(home, "dashboard", "credentials.json");
97
+ const canonical = await realpath(project).catch(() => project);
98
+ const deadline = Date.now() + timeoutMs;
99
+ while (Date.now() < deadline) {
38
100
  try {
39
- integrationPid = JSON.parse(await readFile(path.join(home, "integrations", "web.lock"), "utf8"))?.pid;
101
+ const raw = JSON.parse(await readFile(credentialsFile, "utf8"));
102
+ const credential = raw?.credentials?.find((c) => c.id === credentialId && !c.revokedAt);
103
+ if (credential?.workspaces?.some((w) => w.canonical === canonical || w.path === project || w.path === canonical)) {
104
+ return true;
105
+ }
40
106
  } catch {
41
107
  }
42
- if (info?.token && info?.url && alive && info.pid !== lock?.pid && (!integrationPid || info.pid === integrationPid)) break;
43
- info = void 0;
44
- await new Promise((resolve) => setTimeout(resolve, 100));
108
+ await new Promise((resolve) => setTimeout(resolve, 25));
109
+ }
110
+ return false;
111
+ }
112
+ async function dashboardDisabled(home) {
113
+ const settings = await readJsonFile(path.join(home, "settings.json"));
114
+ return dashboardSettings(settings).enabled === false;
115
+ }
116
+ var DISABLED = 'alp dashboard is disabled by settings ("dashboard.enabled": false).';
117
+ var readJsonFile = (file) => readFile(file, "utf8").then((text) => {
118
+ try {
119
+ return JSON.parse(text);
120
+ } catch {
121
+ return void 0;
122
+ }
123
+ }, () => void 0);
124
+ var readPublished = (home) => readJsonFile(path.join(home, DASHBOARD.info));
125
+ var readServiceLock = (home) => readJsonFile(path.join(home, "integrations", `${DASHBOARD.lock}.lock`));
126
+ async function runningDashboard(home) {
127
+ const lock = await readServiceLock(home);
128
+ if (!Number.isSafeInteger(lock?.pid) || lock.pid <= 0) return void 0;
129
+ try {
130
+ process.kill(lock.pid, 0);
131
+ } catch (error) {
132
+ if (
133
+ /** @type {any} */
134
+ error?.code !== "EPERM"
135
+ ) return void 0;
45
136
  }
46
- 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");
47
- const url = `${info.url}#token=${info.token}`;
137
+ const info = await readPublished(home);
138
+ if (info?.app === DASHBOARD.app && info.pid === lock.pid && typeof info.url === "string" && await isDashboardReady(info.url)) return { pid: info.pid, port: info.port, url: info.url };
139
+ return { held: lock.pid };
140
+ }
141
+ var LOOPBACK_HOSTS = ["127.0.0.1", "localhost"];
142
+ async function serveDashboard(home, entry, { port } = {}) {
143
+ const held = await serviceOwner(home);
144
+ const published = await readPublished(home);
145
+ const lockPid = (await readServiceLock(home))?.pid;
146
+ const claimed = await isServiceClaimed(published, lockPid, held);
147
+ if ("reason" in held && held.alive && held.kind === "foreign" && !claimed) throw new Error(`${refusal(home)} (${held.reason}). Stop it, then run alp dashboard again.`);
148
+ if (port !== void 0 && claimed && published.port !== port) {
149
+ throw new Error(`alp dashboard already runs on port ${published.port} (pid ${published.pid}); you asked for port ${port}. Stop it with \`alp dashboard --stop\`, or drop --port to use the running one.`);
150
+ }
151
+ const project = await currentProject();
152
+ let lock;
153
+ try {
154
+ lock = await startIntegration({ name: DASHBOARD.lock, entry, home, args: [...project ? ["--project", project] : [], ...port !== void 0 ? ["--port", String(port)] : []] });
155
+ } catch (error) {
156
+ const owner = await serviceOwner(home);
157
+ if ("reason" in owner && owner.alive) throw new Error(`${error?.message ?? error}
158
+ ${refusal(home)} (${owner.reason}). If it is not alp dashboard, stop it, then run alp dashboard again.`, { cause: error });
159
+ throw error;
160
+ }
161
+ const info = await readPublished(home);
162
+ if (info?.app !== DASHBOARD.app || info.pid !== lock.pid) {
163
+ const owner = await serviceOwner(home);
164
+ throw new Error(`${refusal(home)}${"reason" in owner ? ` (${owner.reason})` : ""}. Stop pid ${lock.pid}, then run alp dashboard again.`);
165
+ }
166
+ if (typeof info.url !== "string" || typeof info.token !== "string" || !await isDashboardReady(info.url)) {
167
+ throw new Error(`alp dashboard published no address; see ${path.join(home, "logs", "integrations", "alp-dashboard.log")}`);
168
+ }
169
+ if (port !== void 0 && info.port !== port) {
170
+ throw new Error(`alp dashboard is running on port ${info.port}, not ${port} (port ${port} was busy or alp dashboard was starting already); it was left running there. Stop it with \`alp dashboard --stop\` and free port ${port}, or drop --port`);
171
+ }
172
+ if (project) {
173
+ await registerProject(home, project);
174
+ await waitForGrant(home, info.credentialId, project);
175
+ }
176
+ return `${info.url}#token=${info.token}`;
177
+ }
178
+ function reportMigration(report) {
179
+ if (report.stopped) console.error(`Stopped ${LEGACY_WEB.what} (pid ${report.stopped}).`);
180
+ if (report.moved.length) console.error(`Moved alp web's files to alp dashboard's names: ${report.moved.join("; ")}`);
181
+ for (const warning of report.warnings) console.error(warning);
182
+ }
183
+ async function statusCommand(home) {
184
+ try {
185
+ const running2 = await runningDashboard(home);
186
+ if (running2 && "url" in running2) {
187
+ console.log("1 alp dashboard process running:");
188
+ console.log(` PID ${running2.pid} [dashboard]: ${running2.url} (port ${running2.port})`);
189
+ } else if (running2) {
190
+ const owner = await serviceOwner(home);
191
+ console.log(`No alp dashboard running. pid ${running2.held} holds ${path.join(home, "integrations", `${DASHBOARD.lock}.lock`)}${"reason" in owner ? ` (${owner.reason})` : ""}.`);
192
+ } else console.log("No alp dashboard running.");
193
+ if (await dashboardDisabled(home)) console.log(DISABLED);
194
+ const left = await legacyLeftovers(home);
195
+ if (left.legacy?.pid) console.log(`${LEGACY_WEB.what} still runs (pid ${left.legacy.pid}); \`alp dashboard\` or \`alp dashboard --stop\` stops it.`);
196
+ else if (left.legacy) console.log(`${refusal(home, LEGACY_WEB)} (${left.legacy.reason}).`);
197
+ for (const item of left.pending) console.log(`From before the rename to alp dashboard, moved by the next \`alp dashboard\`: ${item}`);
198
+ for (const item of left.kept) console.log(`Left from before the rename to alp dashboard, not used: ${item}`);
199
+ } catch (error) {
200
+ console.log(`alp dashboard could not tell everything: ${error?.message ?? error}`);
201
+ }
202
+ }
203
+ async function stopCommand(home) {
204
+ const report = await migrateDashboard(home);
205
+ reportMigration(report);
206
+ if (report.held) process.exitCode = 1;
207
+ const owner = await serviceOwner(home);
208
+ if (!owner.alive && !("pid" in owner)) {
209
+ if (!report.stopped) console.log("No alp dashboard running for this ALP home.");
210
+ return;
211
+ }
212
+ const pid = await stopService(home);
213
+ if (pid) console.log(`Stopped alp dashboard (pid ${pid}).`);
214
+ else console.log("No alp dashboard running for this ALP home.");
215
+ }
216
+ async function dashboardCommand(args) {
217
+ if (isAgentProcess()) throw new Error("alp dashboard is the user's: it prints and rotates the user's credential; this process was started by an ALP agent (ALP_AGENT_SESSION is set)");
218
+ if (args[0] === "pair") return pairCommand(args.slice(1));
219
+ if (args[0] === "rotate") return rotateCommand(args.slice(1));
220
+ if (args[0] === "serve") return runRole("dashboard", dashboardScript(), args.slice(1));
221
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
222
+ print: { type: "boolean" },
223
+ "no-open": { type: "boolean" },
224
+ status: { type: "boolean" },
225
+ stop: { type: "boolean" },
226
+ port: { type: "string" },
227
+ host: { type: "string" }
228
+ } });
229
+ if (positionals.length) throw new UsageError();
230
+ const home = alpHome();
231
+ if (values.status && values.stop) throw new UsageError();
232
+ if (values.status) return statusCommand(home);
233
+ if (values.stop) return stopCommand(home);
234
+ let port;
235
+ if (values.port !== void 0) {
236
+ port = Number(values.port);
237
+ if (!/^\d+$/.test(values.port) || port < 1024 || port > 65535) throw new Error(`--port must be a port from 1024 to 65535, not ${values.port}`);
238
+ }
239
+ if (values.host !== void 0 && !LOOPBACK_HOSTS.includes(values.host)) {
240
+ throw new Error(`alp dashboard listens on this machine only (127.0.0.1): --host ${values.host} is refused. Reach it from another machine through an SSH tunnel to 127.0.0.1.`);
241
+ }
242
+ const entry = dashboardEntry();
243
+ reportMigration(await migrateDashboard(home, { strict: true }));
244
+ if (await dashboardDisabled(home)) throw new Error(DISABLED);
245
+ await start();
246
+ let url = await serveDashboard(home, entry, { port });
247
+ if (values.host === "localhost") url = url.replace("://127.0.0.1:", "://localhost:");
48
248
  console.log(url);
49
- if (values.print) return;
249
+ if (values.print || values["no-open"]) return;
50
250
  const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open";
51
251
  spawn(opener, [url], { stdio: "ignore", detached: true }).on("error", () => console.error("Open the address above in your browser")).unref();
52
252
  }
253
+ async function rotateCommand(args) {
254
+ if (args.length) throw new UsageError();
255
+ const entry = dashboardEntry();
256
+ const home = alpHome();
257
+ reportMigration(await migrateDashboard(home, { strict: true }));
258
+ await start();
259
+ const project = await projectArgs();
260
+ for (let attempt = 1; ; attempt++) {
261
+ await stopService(home);
262
+ const rotated = await new Promise((resolve) => {
263
+ const rotate = entryCommand(entry, "dashboard", ["--rotate", ...project]);
264
+ execFile(
265
+ rotate.command,
266
+ rotate.args,
267
+ { env: { ...process.env, ALP_HOME: home }, encoding: "utf8", timeout: 6e4, killSignal: "SIGTERM" },
268
+ (error, stdout, stderr) => resolve({ code: error ? typeof error.code === "number" ? error.code : 1 : 0, output: `${stderr}${stdout}`.trim() })
269
+ );
270
+ });
271
+ if (rotated.code === 0) break;
272
+ if (rotated.code !== 3 || attempt >= 3) throw new Error(`alp dashboard could not rotate its token${rotated.output ? `:
273
+ ${rotated.output.slice(-2e3)}` : ""}`);
274
+ }
275
+ if (await dashboardDisabled(home)) {
276
+ console.log(`alp dashboard has a new token; the old one no longer works. ${DISABLED.replace(/\.$/, "")}, so it was not started.`);
277
+ return;
278
+ }
279
+ console.log(await serveDashboard(home, entry));
280
+ }
53
281
  async function requestPairing(client, params, attempts = 50) {
54
282
  let last;
55
283
  for (let attempt = 0; attempt < attempts; attempt += 1) {
@@ -60,24 +288,27 @@ async function requestPairing(client, params, attempts = 50) {
60
288
  if (!unknown) throw outcome.error;
61
289
  await new Promise((resolve) => setTimeout(resolve, 100));
62
290
  }
63
- throw last ?? new Error("alpd did not register web.pairing; run `alp web` to let the integration start, then retry");
291
+ throw last ?? new Error("alpd did not register web.pairing; run `alp dashboard pair` again to let the integration start");
64
292
  }
65
293
  async function pairCommand(args) {
66
294
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { on: { type: "boolean" }, off: { type: "boolean" } } });
67
295
  if (positionals.length || values.on && values.off) throw new UsageError();
68
296
  await start();
69
- await startIntegration();
297
+ const home = alpHome();
298
+ await startPaseoIntegration(home);
70
299
  const client = await running();
71
300
  try {
72
301
  const pairing = await requestPairing(client, values.on ? { enable: true } : values.off ? { enable: false } : {});
73
302
  if (!pairing.relayEnabled) {
74
- console.log(`The relay is off${values.off ? " now" : ""}. Turn it on with: alp web pair --on`);
303
+ console.log(`The relay is off${values.off ? " now" : ""}. Turn it on with: alp dashboard pair --on`);
75
304
  return;
76
305
  }
77
306
  console.log(`Relay ${pairing.endpoint}: ${pairing.connected ? "connected" : "connecting"}`);
78
- console.log(`Open this link on the device, or scan the QR code in the web app (Settings \u2192 host \u2192 Pair device):
307
+ console.log(`Open this link on the device that runs Paseo's app:
79
308
  ${pairing.url}`);
80
- console.log("When Paseo's app asks for a password, give it alpd's token: the part after #token= in alp web --print.");
309
+ const password = await readFile(path.join(home, `${PASEO}.json`), "utf8").then((text) => JSON.parse(text)?.token).catch(() => void 0);
310
+ if (typeof password === "string" && password) console.log(`When Paseo's app asks for a password, give it: ${password}`);
311
+ else console.log(`When Paseo's app asks for a password, give it the token in ${path.join(home, `${PASEO}.json`)}.`);
81
312
  } finally {
82
313
  client.close();
83
314
  }
@@ -85,12 +316,17 @@ ${pairing.url}`);
85
316
  async function acpCommand(args) {
86
317
  if (args.length) throw new UsageError();
87
318
  await built();
88
- const { runAcp } = await import(distributionEntry("acp.js"));
319
+ const { runAcp } = (
320
+ /** @type {{ runAcp: (options: { daemonEntry: string }) => Promise<void> }} */
321
+ await import(distributionEntry("acp.js").href)
322
+ );
89
323
  await runAcp({ daemonEntry: DAEMON_ENTRY });
90
324
  }
91
325
  export {
92
326
  acpCommand,
327
+ dashboardCommand,
93
328
  pairCommand,
329
+ registerProject,
94
330
  requestPairing,
95
- webCommand
331
+ startPaseoIntegration
96
332
  };
package/dist/library.d.ts CHANGED
@@ -86,6 +86,12 @@ export const EDIT_OPTIONS: {
86
86
  file: {
87
87
  type: string;
88
88
  };
89
+ roles: {
90
+ type: string;
91
+ };
92
+ 'no-roles': {
93
+ type: string;
94
+ };
89
95
  command: {
90
96
  type: string;
91
97
  };
@@ -122,10 +128,10 @@ export const EDIT_OPTIONS: {
122
128
  'match-label': {
123
129
  type: string;
124
130
  };
125
- kind: {
131
+ strict: {
126
132
  type: string;
127
133
  };
128
- 'read-only-mode': {
134
+ kind: {
129
135
  type: string;
130
136
  };
131
137
  models: {
@@ -138,3 +144,11 @@ export function edited(kind: any, name: any, current: any, values: any): Promise
138
144
  export function editCommand(kind: any, args: any): Promise<void>;
139
145
  /** alp trust: the workspaces whose hooks run without asking (ALPD §45). */
140
146
  export function teamsCommand(args: any): Promise<void>;
147
+ /**
148
+ * alp packs [--project DIR] [--json]: the optional packs ALP ships, and whether the library or the
149
+ * project has them. alp pack install <id> [--project [DIR]] [--assign] [--json]: copies a pack's
150
+ * skills, agents and teams into the library (or the project's .alp/), keeping any entry already
151
+ * there; --assign (library) gives its suggested skills to roles in role-skills.json.
152
+ */
153
+ export function packsCommand(args: any): Promise<void>;
154
+ export function packCommand(args: any): Promise<void>;
package/dist/library.js CHANGED
@@ -5,14 +5,31 @@ import { parseArgs } from "node:util";
5
5
  import { seedLibrary } from "@anhlp/alp-core/library";
6
6
  import { libraryEntries } from "@anhlp/alp-core/resolver";
7
7
  import { listTeams, resolveTeam } from "@anhlp/alp-core/teams";
8
- import { deleteEntry, duplicateEntry, getEntry, renameEntry, saveEntry } from "@anhlp/alp-core/library-edit";
8
+ import { deleteEntry, duplicateEntry, getEntry, listRetiredSkills, renameEntry, restoreSkill, saveEntry, withSkillName } from "@anhlp/alp-core/library-edit";
9
9
  import { testEntry } from "@anhlp/alp-client/library-test";
10
+ import { formatValidation, validateSkill } from "@anhlp/alp-core/skill-validate";
11
+ import { installPack, listPacks, packStatus } from "@anhlp/alp-core/packs";
10
12
  import { alpHome } from "@anhlp/alp-client/index";
11
13
  import { UsageError } from "./usage.js";
12
14
  import { taskProject } from "./tasks.js";
13
15
  async function libraryCommand(kind, args) {
14
- const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { project: { type: "string" }, json: { type: "boolean" } } });
16
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { project: { type: "string" }, json: { type: "boolean" }, ...kind === "skills" ? { retired: { type: "boolean" } } : {} } });
15
17
  if (positionals.length) throw new UsageError();
18
+ if (values.retired) {
19
+ if (values.project !== void 0) throw new UsageError();
20
+ const rows2 = await listRetiredSkills({ library: alpHome() });
21
+ if (values.json) {
22
+ console.log(JSON.stringify(rows2));
23
+ return;
24
+ }
25
+ if (!rows2.length) {
26
+ console.log(`No retired skills in ${path.join(alpHome(), "retired-skills")}`);
27
+ return;
28
+ }
29
+ const width2 = Math.max(...rows2.map((row) => row.name.length));
30
+ for (const row of rows2) console.log(`${row.name.padEnd(width2)} ${row.retiredAt} ${row.roles === null ? "roles not recorded" : `roles: ${row.roles.join(", ") || "none"}`}${row.agent ? `; by ${row.agent}` : ""}${row.invalid ? `; warning: invalid retired metadata: ${row.invalid}` : ""} ${row.directory}`);
31
+ return;
32
+ }
16
33
  if (kind === "providers") await seedLibrary(alpHome());
17
34
  const root = path.resolve(values.project ?? process.cwd());
18
35
  const rows = await libraryEntries(kind, root, { library: alpHome() });
@@ -75,6 +92,8 @@ var EDIT_OPTIONS = {
75
92
  rules: { type: "string" },
76
93
  // skill, mcp, hook
77
94
  file: { type: "string" },
95
+ roles: { type: "string" },
96
+ "no-roles": { type: "boolean" },
78
97
  command: { type: "string" },
79
98
  arg: { type: "string", multiple: true },
80
99
  env: { type: "string", multiple: true },
@@ -86,9 +105,9 @@ var EDIT_OPTIONS = {
86
105
  timeout: { type: "string" },
87
106
  "match-agent": { type: "string" },
88
107
  "match-label": { type: "string" },
108
+ strict: { type: "boolean" },
89
109
  // provider
90
110
  kind: { type: "string" },
91
- "read-only-mode": { type: "string" },
92
111
  models: { type: "string" }
93
112
  };
94
113
  async function edited(kind, name, current, values) {
@@ -156,12 +175,16 @@ Describe what this agent does, and how.
156
175
  if (values.file !== void 0) content.body = await readFile(values.file, "utf8");
157
176
  content.body ??= `---
158
177
  name: ${name}
159
- description: When to use this skill.
178
+ description: ${JSON.stringify(values.description ?? `What ${name} does. Use when the work it is for comes up.`)}
160
179
  ---
161
180
 
162
181
  # ${name}
163
182
 
164
- Steps and checks.
183
+ ## When to use
184
+
185
+ ## Workflow
186
+
187
+ ## Verification
165
188
  `;
166
189
  } else if (kind === "mcp") {
167
190
  if (values.command !== void 0 || values.url !== void 0) content.server = {};
@@ -199,7 +222,7 @@ Steps and checks.
199
222
  set(provider, "label", values.label);
200
223
  set(provider, "description", values.description);
201
224
  set(provider, "command", values.command);
202
- set(provider, "readOnlyMode", values["read-only-mode"]);
225
+ delete provider.readOnlyMode;
203
226
  if (values.arg?.length) provider.args = values.arg;
204
227
  if (values.env?.length) provider.env = pairs(values.env, "--env");
205
228
  const models = names(values.models);
@@ -211,9 +234,44 @@ Steps and checks.
211
234
  }
212
235
  return content;
213
236
  }
237
+ async function checkSkills(name, positionals, values) {
238
+ if (positionals.length > 2) throw new UsageError();
239
+ const root = path.resolve(values.project ?? process.cwd());
240
+ const mode = values.strict ? "strict" : "legacy";
241
+ let targets;
242
+ if (name !== void 0 && (name.includes("/") || name.includes(path.sep) || name.startsWith("."))) targets = [path.resolve(name)];
243
+ else {
244
+ const rows = await libraryEntries("skills", root, { library: alpHome() });
245
+ const chosen = name === void 0 ? rows : rows.filter((row) => row.name === name);
246
+ if (name !== void 0 && !chosen.length) throw new Error(`No skill '${name}' in ${path.join(root, ".alp", "skills")} or ${path.join(alpHome(), "skills")}`);
247
+ targets = chosen.map((row) => path.dirname(row.path));
248
+ }
249
+ const reports = [];
250
+ for (const target of targets) reports.push(await validateSkill(target, { mode }));
251
+ if (values.json) console.log(JSON.stringify(reports));
252
+ else {
253
+ for (const report of reports) console.log(formatValidation(report));
254
+ const failed = reports.filter((report) => !report.ok).length;
255
+ const warned = reports.filter((report) => report.warnings.length).length;
256
+ console.log(`${reports.length} skill${reports.length === 1 ? "" : "s"} checked (${mode}): ${failed} with errors, ${warned} with warnings.${mode === "legacy" && warned ? " Warnings do not stop a skill from loading; fix them when you next edit it." : ""}`);
257
+ }
258
+ if (reports.some((report) => !report.ok)) process.exitCode = 1;
259
+ }
214
260
  async function editCommand(kind, args) {
261
+ if (kind === "providers" && args.some((arg) => arg === "--read-only-mode" || arg.startsWith("--read-only-mode="))) throw new Error("--read-only-mode was removed; delete readOnlyMode from provider JSON and choose the session --mode read-only, workspace-write or full-access. Existing native sessions keep their mode.");
215
262
  const { values, positionals } = parseArgs({ args: projectFlag(args), allowPositionals: true, options: EDIT_OPTIONS });
216
263
  const [action, name, target] = positionals;
264
+ if (kind === "skills" && action === "restore") {
265
+ if (!name || positionals.length > 2 || values.project !== void 0 || values.roles !== void 0 && values["no-roles"]) throw new UsageError();
266
+ const roles = values["no-roles"] ? [] : names(values.roles);
267
+ const result2 = await restoreSkill(name, { library: alpHome(), from: values.from, roles });
268
+ console.log(values.json ? JSON.stringify(result2) : `Restored ${name} to ${result2.restored} from ${result2.from}; ${result2.roles.length ? `given to ${result2.roles.join(", ")}` : "given to no role"}.`);
269
+ return;
270
+ }
271
+ if (kind === "skills" && action === "check") {
272
+ await checkSkills(name, positionals, values);
273
+ return;
274
+ }
217
275
  if (kind === "providers" && action !== "add") await seedLibrary(alpHome());
218
276
  const creates = { agents: "new", teams: "new", skills: "new", mcp: "add", hooks: "add", providers: "add" }[kind];
219
277
  if (!name || positionals.length > (["cp", "mv"].includes(action) ? 3 : 2) || ["cp", "mv"].includes(action) && !target) throw new UsageError();
@@ -271,6 +329,7 @@ stderr: ${result2.stderr.trim()}` : ""}`);
271
329
  let revision = null;
272
330
  if (action === creates) {
273
331
  if (values.from !== void 0) current = (await getEntry(kind, values.from, { root, library: alpHome() })).content;
332
+ if (kind === "skills" && current?.body !== void 0) current = { ...current, body: withSkillName(current.body, name) };
274
333
  } else {
275
334
  const entry = await getEntry(kind, name, { root, library: alpHome() }).catch((error) => {
276
335
  if (error.code === "NOT_FOUND") throw new Error(`No ${kind} entry '${name}'; create it with alp ${kind.replace(/s$/, "")} ${creates}`);
@@ -280,8 +339,14 @@ stderr: ${result2.stderr.trim()}` : ""}`);
280
339
  current = (own ?? entry).content;
281
340
  revision = own ? own.revision : null;
282
341
  }
283
- const result = await saveEntry(kind, name, await edited(kind, name, current, values), { ...options, revision });
342
+ const result = await saveEntry(kind, name, await edited(kind, name, current, values), { ...options, revision, strict: kind === "skills" && action === creates });
284
343
  done(result, `${action === "edit" ? "Saved" : "Created"} ${name} in ${where}.`);
344
+ if (kind === "skills" && !values.json) {
345
+ const directory = path.join(scope === "project" ? path.join(root, ".alp") : alpHome(), "skills", name);
346
+ const report = await validateSkill(directory);
347
+ const notes = [...result.warnings ?? [], ...report.errors.map((finding) => finding.message), ...report.warnings.map((finding) => finding.message)];
348
+ for (const note of [...new Set(notes)]) console.log(`note: ${note}`);
349
+ }
285
350
  }
286
351
  async function teamsCommand(args) {
287
352
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { project: { type: "string" }, json: { type: "boolean" } } });
@@ -307,12 +372,54 @@ async function teamsCommand(args) {
307
372
  console.log(` supervisor: ${team.supervisor ? member(team.supervisor.agent, { role: "watches main", model: team.supervisor.model, thinking: team.supervisor.thinking }) : "none"}${team.maxPeers ? `; at most ${team.maxPeers} peers` : ""}`);
308
373
  }
309
374
  }
375
+ async function packsCommand(args) {
376
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { project: { type: "string" }, json: { type: "boolean" } } });
377
+ if (positionals.length) throw new UsageError();
378
+ const root = path.resolve(values.project ?? process.cwd());
379
+ const rows = [];
380
+ for (const pack of await listPacks()) rows.push({ ...pack, installed: await packStatus(pack, { root, library: alpHome() }) });
381
+ if (values.json) {
382
+ console.log(JSON.stringify(rows));
383
+ return;
384
+ }
385
+ const width = Math.max(...rows.map((row) => row.id.length));
386
+ for (const row of rows) {
387
+ const contents = [row.skills.length ? `skills: ${row.skills.join(", ")}` : "", row.agents.length ? `agents: ${row.agents.join(", ")}` : "", row.teams.length ? `teams: ${row.teams.join(", ")}` : ""].filter(Boolean).join("; ");
388
+ const where = [row.installed.library ? "library" : "", row.installed.project ? "project" : ""].filter(Boolean).join(", ");
389
+ console.log(`${row.id.padEnd(width)} ${row.description}
390
+ ${" ".repeat(width)} ${contents}${where ? ` [installed: ${where}]` : ""}`);
391
+ }
392
+ console.log("Install one with: alp pack install <id> [--project] [--assign]");
393
+ }
394
+ async function packCommand(args) {
395
+ const { values, positionals } = parseArgs({ args: projectFlag(args), allowPositionals: true, options: { project: { type: "string" }, json: { type: "boolean" }, assign: { type: "boolean" } } });
396
+ const [action, id] = positionals;
397
+ if (action !== "install" || !id || positionals.length > 2) throw new UsageError();
398
+ const scope = values.project !== void 0 ? "project" : "library";
399
+ const root = values.project !== void 0 ? path.resolve(values.project) : void 0;
400
+ if (scope === "project") await taskProject(root);
401
+ const result = await installPack(id, { scope, root, library: alpHome(), assign: values.assign });
402
+ if (values.json) {
403
+ console.log(JSON.stringify(result));
404
+ return;
405
+ }
406
+ const where = scope === "project" ? `the project ${root}` : `your library ${alpHome()}`;
407
+ for (const entry of result.installed) console.log(`installed ${entry.kind.replace(/s$/, "")} ${entry.name} ${entry.path}`);
408
+ for (const entry of result.kept) console.log(`kept ${entry.kind.replace(/s$/, "")} ${entry.name}: one already exists, and stays as it is (${entry.path})`);
409
+ for (const line of result.permissions.set) console.log(`permission ${line} (agent capped by its permission profile)`);
410
+ for (const line of result.permissions.conflicts) console.log(`warning: ${line}`);
411
+ if (result.assigned.length) console.log(`assigned ${result.assigned.join(", ")} in role-skills.json`);
412
+ else if (!values.assign && scope === "library" && result.installed.some((entry) => entry.kind === "skills")) console.log("No role has these skills yet: rerun with --assign for the pack's suggestion, or alp agent edit <agent> --skills a,b.");
413
+ console.log(`Pack ${id} in ${where}. Start a new session (or close and resume) for agents to see it.`);
414
+ }
310
415
  export {
311
416
  EDIT_OPTIONS,
312
417
  editCommand,
313
418
  edited,
314
419
  libraryCommand,
315
420
  names,
421
+ packCommand,
422
+ packsCommand,
316
423
  pairs,
317
424
  projectFlag,
318
425
  teamsCommand
package/dist/paths.d.ts CHANGED
@@ -1,3 +1,9 @@
1
1
  /** Locate artifacts in either the independently shipped CLI or the legacy root build. */
2
2
  export function distributionEntry(name: any): URL;
3
+ /** alpd.js, which `alp daemon run` runs in this process (named through app/current in the ALP bundle). */
4
+ export const DAEMON_SCRIPT: string;
5
+ /**
6
+ * What starts alpd: the bundle's native alpd when it ships one (t-81b0.9), else alpd.js under Node;
7
+ * ALP_NATIVE_DAEMON=0 keeps the Node alpd. Named through app/current in the ALP bundle.
8
+ */
3
9
  export const DAEMON_ENTRY: string;
package/dist/paths.js CHANGED
@@ -2,6 +2,7 @@
2
2
  import { existsSync } from "node:fs";
3
3
  import { fileURLToPath, pathToFileURL } from "node:url";
4
4
  import path from "node:path";
5
+ import { daemonEntry, selfEntry } from "@anhlp/alp-core/packaged";
5
6
  function distributionEntry(name) {
6
7
  const entry = process.argv[1] && path.basename(process.argv[1]) === "cli.js" ? pathToFileURL(path.resolve(process.argv[1])) : void 0;
7
8
  const candidates = [
@@ -11,8 +12,10 @@ function distributionEntry(name) {
11
12
  ];
12
13
  return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0];
13
14
  }
14
- var DAEMON_ENTRY = fileURLToPath(distributionEntry("alpd.js"));
15
+ var DAEMON_SCRIPT = selfEntry(fileURLToPath(distributionEntry("alpd.js")));
16
+ var DAEMON_ENTRY = daemonEntry(fileURLToPath(distributionEntry("alpd.js")));
15
17
  export {
16
18
  DAEMON_ENTRY,
19
+ DAEMON_SCRIPT,
17
20
  distributionEntry
18
21
  };