@anhlp/alp-cli 0.0.1-beta.3 → 0.0.1-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/THIRD-PARTY-NOTICES.txt +51 -1
  2. package/dist/acp/main.js +1 -1
  3. package/dist/acp.js +300 -92
  4. package/dist/alp-web/THIRD-PARTY-NOTICES.txt +3256 -0
  5. package/dist/alp-web/alp-boundary.json +16 -0
  6. package/dist/alp-web/apple-touch-icon.png +0 -0
  7. package/dist/alp-web/assets/TerminalPanel-CqTsgY-W.js +22 -0
  8. package/dist/alp-web/assets/TerminalPanel-DLuoa74B.css +1 -0
  9. package/dist/alp-web/assets/highlighter-BnicKQ_d.js +18 -0
  10. package/dist/alp-web/assets/index-BMbDUCHW.css +1 -0
  11. package/dist/alp-web/assets/index-B_RFaj2C.js +59 -0
  12. package/dist/alp-web/favicon-attention.svg +6 -0
  13. package/dist/alp-web/favicon-running.svg +6 -0
  14. package/dist/alp-web/favicon.svg +5 -0
  15. package/dist/alp-web/index.html +20 -0
  16. package/dist/alp-web.js +10119 -0
  17. package/dist/alpd.js +30333 -15153
  18. package/dist/backup.js +2 -2
  19. package/dist/build-manifest.json +120 -2
  20. package/dist/cli.js +34 -3
  21. package/dist/daemon.d.ts +1 -1
  22. package/dist/daemon.js +5 -0
  23. package/dist/interfaces.d.ts +22 -2
  24. package/dist/interfaces.js +182 -37
  25. package/dist/paths.d.ts +1 -0
  26. package/dist/paths.js +2 -1
  27. package/dist/roles.d.ts +15 -0
  28. package/dist/roles.js +18 -0
  29. package/dist/schedules.d.ts +2 -0
  30. package/dist/schedules.js +45 -0
  31. package/dist/self-update.d.ts +152 -0
  32. package/dist/self-update.js +390 -0
  33. package/dist/sessions.d.ts +7 -1
  34. package/dist/sessions.js +44 -12
  35. package/dist/tasks.js +22 -8
  36. package/dist/terminal-native/README.md +201 -0
  37. package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
  38. package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
  39. package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
  40. package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
  41. package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  42. package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  43. package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  44. package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  45. package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  46. package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  47. package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
  48. package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  49. package/dist/terminal-native/terminal-owner.c +389 -0
  50. package/dist/terminal.d.ts +13 -0
  51. package/dist/terminal.js +80 -0
  52. package/dist/usage.d.ts +1 -1
  53. package/dist/usage.js +22 -7
  54. package/dist/web-service.d.ts +56 -0
  55. package/dist/web-service.js +143 -0
  56. package/package.json +11 -4
  57. package/src/backup.js +1 -1
  58. package/src/cli.js +40 -4
  59. package/src/daemon.js +3 -0
  60. package/src/interfaces.js +227 -32
  61. package/src/paths.js +3 -1
  62. package/src/roles.js +28 -0
  63. package/src/schedules.js +38 -0
  64. package/src/self-update.js +406 -0
  65. package/src/sessions.js +44 -13
  66. package/src/tasks.js +22 -8
  67. package/src/terminal.js +78 -0
  68. package/src/usage.js +22 -7
  69. package/src/web-service.js +187 -0
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.3" : "dev";
10
+ var VERSION = true ? "0.0.1-beta.6" : "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");
@@ -138,7 +138,7 @@ async function restoreCommand(args) {
138
138
  for (const { root, reason } of result.skipped) console.log(` skipped ${root}: ${reason}`);
139
139
  for (const warning of result.warnings) console.log(` note: ${warning}`);
140
140
  if (result.stateSchema !== null && result.stateSchema !== void 0) console.log(" sessions that were working when the backup was made wait for you; alpd continues none by itself");
141
- if (result.safety) console.log(`the data it replaced is in ${result.safety}; alp restore ${result.safety} puts it back`);
141
+ if (result.safety) console.log(`the data it replaced is in ${result.safety}; alp restore ${result.safety} restores that data with the same workspace authority checks`);
142
142
  }
143
143
  export {
144
144
  backupCommand,
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.0.1-beta.3",
2
+ "version": "0.0.1-beta.6",
3
3
  "entries": {
4
4
  "packages/cli/dist/alpd.js": {
5
5
  "inputs": [
@@ -11,22 +11,29 @@
11
11
  "packages/client/src/rpc/framing.js",
12
12
  "packages/client/src/rpc/handshake.js",
13
13
  "packages/client/src/rpc/reconnect.js",
14
+ "packages/client/src/rpc/registry.js",
15
+ "packages/client/src/rpc/terminal-directory.js",
14
16
  "packages/client/src/rpc/timers.js",
15
17
  "packages/client/src/websocket.js",
16
18
  "packages/core/src/adapter.js",
17
19
  "packages/core/src/atomic.js",
18
20
  "packages/core/src/backup.js",
21
+ "packages/core/src/beads.js",
22
+ "packages/core/src/bridges.js",
19
23
  "packages/core/src/delegation.js",
20
24
  "packages/core/src/errors.js",
21
25
  "packages/core/src/formulas.js",
26
+ "packages/core/src/gate-ledger.js",
22
27
  "packages/core/src/hook-run.js",
23
28
  "packages/core/src/hooks.js",
29
+ "packages/core/src/index.js",
24
30
  "packages/core/src/init.js",
25
31
  "packages/core/src/library-edit.js",
26
32
  "packages/core/src/library.js",
27
33
  "packages/core/src/log.js",
28
34
  "packages/core/src/migrations.js",
29
35
  "packages/core/src/models.js",
36
+ "packages/core/src/packaged.js",
30
37
  "packages/core/src/permissions.js",
31
38
  "packages/core/src/profiles.js",
32
39
  "packages/core/src/promptsafe.js",
@@ -40,18 +47,34 @@
40
47
  "packages/core/src/teams.js",
41
48
  "packages/core/src/template-path.js",
42
49
  "packages/core/src/trust.js",
50
+ "packages/core/src/upgrade.js",
43
51
  "packages/core/src/user-settings.js",
52
+ "packages/core/src/user-worktree.js",
44
53
  "packages/core/src/validation.js",
45
54
  "packages/core/src/verify.js",
46
55
  "packages/core/src/workflow.js",
56
+ "packages/daemon/src/attachments.ts",
57
+ "packages/daemon/src/conversation.ts",
58
+ "packages/daemon/src/disk.ts",
47
59
  "packages/daemon/src/files.ts",
60
+ "packages/daemon/src/git.ts",
48
61
  "packages/daemon/src/gitignore.ts",
62
+ "packages/daemon/src/history.ts",
63
+ "packages/daemon/src/lifecycle.ts",
49
64
  "packages/daemon/src/lock.ts",
50
65
  "packages/daemon/src/main.ts",
66
+ "packages/daemon/src/native-terminal.ts",
51
67
  "packages/daemon/src/operations.ts",
68
+ "packages/daemon/src/registry.ts",
52
69
  "packages/daemon/src/rpc-error.ts",
70
+ "packages/daemon/src/scheduler.ts",
71
+ "packages/daemon/src/schedules.ts",
53
72
  "packages/daemon/src/server.ts",
54
73
  "packages/daemon/src/store.ts",
74
+ "packages/daemon/src/terminal-screen.ts",
75
+ "packages/daemon/src/terminals.ts",
76
+ "packages/daemon/src/windows-terminal.ts",
77
+ "packages/daemon/src/worktrees.ts",
55
78
  "packages/protocol/src/contract-v1.js",
56
79
  "packages/protocol/src/contract.js",
57
80
  "packages/protocol/src/index.ts",
@@ -59,18 +82,26 @@
59
82
  "packages/protocol/src/wire.js",
60
83
  "packages/runtime/src/acp-transport.ts",
61
84
  "packages/runtime/src/antigravity-transport.ts",
85
+ "packages/runtime/src/assignment-results.ts",
86
+ "packages/runtime/src/attachments.ts",
62
87
  "packages/runtime/src/board-domain.ts",
63
88
  "packages/runtime/src/board.ts",
64
89
  "packages/runtime/src/catalog.ts",
65
90
  "packages/runtime/src/claude-transport.ts",
91
+ "packages/runtime/src/compact.ts",
92
+ "packages/runtime/src/configure.ts",
66
93
  "packages/runtime/src/contracts.ts",
94
+ "packages/runtime/src/conversation.ts",
67
95
  "packages/runtime/src/github.ts",
68
96
  "packages/runtime/src/handoff.ts",
69
97
  "packages/runtime/src/index.ts",
98
+ "packages/runtime/src/input-limits.ts",
70
99
  "packages/runtime/src/language.ts",
71
100
  "packages/runtime/src/live.ts",
72
101
  "packages/runtime/src/mailbox.ts",
73
102
  "packages/runtime/src/mcp-tools.ts",
103
+ "packages/runtime/src/model-catalog.ts",
104
+ "packages/runtime/src/model-probes.ts",
74
105
  "packages/runtime/src/permission-path.ts",
75
106
  "packages/runtime/src/process-info.ts",
76
107
  "packages/runtime/src/providers.ts",
@@ -94,6 +125,7 @@
94
125
  "node:crypto",
95
126
  "node:fs",
96
127
  "node:fs/promises",
128
+ "node:module",
97
129
  "node:net",
98
130
  "node:os",
99
131
  "node:path",
@@ -102,6 +134,7 @@
102
134
  "node:stream",
103
135
  "node:stream/promises",
104
136
  "node:string_decoder",
137
+ "node:timers/promises",
105
138
  "node:url",
106
139
  "node:zlib",
107
140
  "path"
@@ -120,22 +153,107 @@
120
153
  "packages/client/src/rpc/framing.js",
121
154
  "packages/client/src/rpc/handshake.js",
122
155
  "packages/client/src/rpc/reconnect.js",
156
+ "packages/client/src/rpc/registry.js",
157
+ "packages/client/src/rpc/terminal-directory.js",
123
158
  "packages/client/src/rpc/timers.js",
124
159
  "packages/client/src/service.js",
125
160
  "packages/client/src/supervise.js",
126
161
  "packages/client/src/websocket.js",
127
162
  "packages/core/src/log.js",
163
+ "packages/core/src/packaged.js",
128
164
  "packages/protocol/src/index.ts",
129
165
  "packages/protocol/src/wire.js"
130
166
  ],
131
167
  "external": [
132
168
  "node:child_process",
133
169
  "node:crypto",
170
+ "node:fs",
171
+ "node:fs/promises",
172
+ "node:net",
173
+ "node:os",
174
+ "node:path",
175
+ "node:stream",
176
+ "node:timers/promises"
177
+ ]
178
+ },
179
+ "packages/cli/dist/alp-web.js": {
180
+ "inputs": [
181
+ "apps/gateway/src/config.js",
182
+ "apps/gateway/src/connection.js",
183
+ "apps/gateway/src/credentials.js",
184
+ "apps/gateway/src/index.js",
185
+ "apps/gateway/src/log.js",
186
+ "apps/gateway/src/policy.js",
187
+ "apps/gateway/src/server.js",
188
+ "apps/gateway/src/tickets.js",
189
+ "apps/gateway/src/upstream.js",
190
+ "packages/cli/src/web/grant.js",
191
+ "packages/cli/src/web/main.js",
192
+ "packages/cli/src/web/serve.js",
193
+ "packages/client/src/command.js",
194
+ "packages/client/src/index.js",
195
+ "packages/client/src/integration-lock.js",
196
+ "packages/client/src/ipc.js",
197
+ "packages/client/src/portable.js",
198
+ "packages/client/src/rpc/client.js",
199
+ "packages/client/src/rpc/errors.js",
200
+ "packages/client/src/rpc/framing.js",
201
+ "packages/client/src/rpc/handshake.js",
202
+ "packages/client/src/rpc/reconnect.js",
203
+ "packages/client/src/rpc/registry.js",
204
+ "packages/client/src/rpc/terminal-directory.js",
205
+ "packages/client/src/rpc/timers.js",
206
+ "packages/client/src/service.js",
207
+ "packages/client/src/supervise.js",
208
+ "packages/client/src/websocket.js",
209
+ "packages/core/src/atomic.js",
210
+ "packages/core/src/errors.js",
211
+ "packages/core/src/library-edit.js",
212
+ "packages/core/src/library.js",
213
+ "packages/core/src/log.js",
214
+ "packages/core/src/models.js",
215
+ "packages/core/src/packaged.js",
216
+ "packages/core/src/permissions.js",
217
+ "packages/core/src/providers.js",
218
+ "packages/core/src/resolver.js",
219
+ "packages/core/src/safe-path.js",
220
+ "packages/core/src/shell.js",
221
+ "packages/core/src/teams.js",
222
+ "packages/core/src/template-path.js",
223
+ "packages/core/src/validation.js",
224
+ "packages/core/src/verify.js",
225
+ "packages/protocol/src/contract-v1.js",
226
+ "packages/protocol/src/contract.js",
227
+ "packages/protocol/src/index.ts",
228
+ "packages/protocol/src/validate.js",
229
+ "packages/protocol/src/wire.js"
230
+ ],
231
+ "external": [
232
+ "buffer",
233
+ "bufferutil",
234
+ "crypto",
235
+ "events",
236
+ "http",
237
+ "https",
238
+ "net",
239
+ "node:child_process",
240
+ "node:crypto",
241
+ "node:fs",
134
242
  "node:fs/promises",
243
+ "node:http",
244
+ "node:https",
135
245
  "node:net",
136
246
  "node:os",
137
247
  "node:path",
138
- "node:stream"
248
+ "node:timers/promises",
249
+ "node:url",
250
+ "node:util",
251
+ "stream",
252
+ "tls",
253
+ "url",
254
+ "utf-8-validate",
255
+ "util",
256
+ "zlib"
139
257
  ]
140
258
  }
141
259
  }
package/dist/cli.js CHANGED
@@ -7,16 +7,47 @@ import { scrubText } from "@anhlp/alp-core/log";
7
7
  import { USAGE, UsageError } from "./usage.js";
8
8
  import { project, permissionsCommand, trustCommand, language, verify, doctor } from "./projects.js";
9
9
  import { daemon } from "./daemon.js";
10
- import { run, ps, attach, send, questions, answer, top, log, board, pause, resume, recall, interrupt } from "./sessions.js";
10
+ import { run, ps, attach, send, questions, answer, top, log, board, models, pause, resume, recall, interrupt, compact } from "./sessions.js";
11
11
  import { libraryCommand, editCommand, teamsCommand } from "./library.js";
12
+ import { scheduleCommand } from "./schedules.js";
12
13
  import { tasksCommand, formulaCommand, taskCommand } from "./tasks.js";
13
14
  import { webCommand, acpCommand } from "./interfaces.js";
14
15
  import { backupCommand, restoreCommand } from "./backup.js";
15
- var commands = { setup: (args2) => setup(args2, alpHome()), init: (args2) => project("init", args2), upgrade: (args2) => project("upgrade", args2), update: (args2) => project("upgrade", args2), 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, 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, interrupt, acp: acpCommand, web: webCommand, backup: backupCommand, restore: restoreCommand };
16
+ import { terminalCommand } from "./terminal.js";
17
+ import { bridgeCommand } from "./roles.js";
18
+ import { cleanupOldExecutable, selfUpdate } from "./self-update.js";
19
+ import { executablePath, packagedInfo } from "@anhlp/alp-core/packaged";
20
+ import { connect, lockAlive, readLock } from "@anhlp/alp-client/index";
21
+ function alpVersion() {
22
+ return packagedInfo()?.version ?? (true ? "0.0.1-beta.6" : JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version);
23
+ }
24
+ async function runningDaemon() {
25
+ const lock = await readLock(alpHome());
26
+ if (!lockAlive(lock)) return void 0;
27
+ const client = await connect(lock.socket, { name: "alp-cli", version: "1" }).catch(() => void 0);
28
+ if (!client) return { version: lock.version };
29
+ try {
30
+ const status = await client.request("daemon.status");
31
+ return { version: status.version ?? lock.version, sessions: status.sessions };
32
+ } catch {
33
+ return { version: lock.version };
34
+ } finally {
35
+ client.close();
36
+ }
37
+ }
38
+ async function updateCommand(args2) {
39
+ const code = await selfUpdate(args2, { packaged: packagedInfo() !== void 0, version: alpVersion(), daemon: runningDaemon });
40
+ if (code) process.exitCode = code;
41
+ }
42
+ {
43
+ const executable = executablePath();
44
+ if (executable) cleanupOldExecutable(executable);
45
+ }
46
+ 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, 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 };
16
47
  var [command, ...args] = process.argv.slice(2);
17
48
  try {
18
49
  if (command === "--version") {
19
- console.log(true ? "0.0.1-beta.3" : JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version);
50
+ console.log(alpVersion());
20
51
  } else {
21
52
  if (!Object.hasOwn(commands, command)) throw new UsageError();
22
53
  await commands[command](args);
package/dist/daemon.d.ts CHANGED
@@ -32,4 +32,4 @@ export function start(): Promise<string>;
32
32
  /** Connects to a running daemon without starting one. */
33
33
  export function running(): Promise<import("@anhlp/alp-client/index").AlpClient>;
34
34
  export function stop(): Promise<boolean>;
35
- export function daemon([action, ...rest]: [any, ...any[]]): Promise<void>;
35
+ export function daemon([action, ...rest]: [any, ...any[]]): Promise<any>;
package/dist/daemon.js CHANGED
@@ -7,6 +7,7 @@ import { alpHome, connect, lockAlive, readLock, withDaemonLifecycle } from "@anh
7
7
  import { scrubText } from "@anhlp/alp-core/log";
8
8
  import { UsageError } from "./usage.js";
9
9
  import { DAEMON_ENTRY } from "./paths.js";
10
+ import { runRole } from "./roles.js";
10
11
  async function built() {
11
12
  try {
12
13
  await access(DAEMON_ENTRY);
@@ -46,6 +47,10 @@ async function stop() {
46
47
  return true;
47
48
  }
48
49
  async function daemon([action, ...rest]) {
50
+ if (action === "run") {
51
+ await built();
52
+ return runRole("daemon", DAEMON_ENTRY, rest);
53
+ }
49
54
  if (rest.length && !(action === "status" && rest.length === 1 && rest[0] === "--json")) throw new UsageError();
50
55
  if (action === "start") {
51
56
  const socket = await start();
@@ -1,6 +1,25 @@
1
+ /**
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>;
1
19
  /**
2
20
  * 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.
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 webCommand(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>;
@@ -1,55 +1,191 @@
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, packagedInfo } from "@anhlp/alp-core/packaged";
12
+ import { runRole } from "./roles.js";
13
+ import { alpWebEntry, alpWebScript, isWebClaimed, isWebReady, refusal, stopPreRenamePaseo, stopWebService, webOwner } from "./web-service.js";
14
+ var PASEO = "paseo";
15
+ var WEB = "web";
16
+ async function startPaseoIntegration(home) {
17
+ const entry = await discoverIntegration(PASEO, { home });
18
+ if (!entry) {
19
+ const legacy = path.join(home, "integrations", "web.json");
20
+ const legacyEntry = await legacyDescriptorEntry(legacy, home);
21
+ if (legacyEntry) {
22
+ console.error(`Using the Paseo integration registered before its rename (${legacy}); run \`alp-paseo-integration --register\` to register it again.`);
23
+ return startIntegration({ name: PASEO, entry: legacyEntry, home });
24
+ }
21
25
  }
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;
26
+ return startIntegration({ name: PASEO, home });
27
+ }
28
+ async function legacyDescriptorEntry(file, home) {
29
+ const raw = await readFile(file, "utf8").then((text) => JSON.parse(text)).catch(() => void 0);
30
+ const isFile = (candidate) => stat(candidate).then((info) => info.isFile(), () => false);
31
+ for (const field of ["main", "entry", "path", "command"]) {
32
+ const value = raw?.[field];
33
+ if (typeof value !== "string" || !value.trim()) continue;
34
+ const candidates = path.isAbsolute(value) ? [value] : [path.resolve(path.dirname(file), value), path.resolve(home, value)];
35
+ for (const candidate of candidates) if (await isFile(candidate)) return candidate;
36
+ }
37
+ return void 0;
38
+ }
39
+ async function currentProject() {
40
+ const cwd = process.cwd();
41
+ return await stat(path.join(cwd, ".alp")).then((info) => info.isDirectory(), () => false) ? cwd : void 0;
42
+ }
43
+ async function projectArgs() {
44
+ const project = await currentProject();
45
+ return project ? ["--project", project] : [];
46
+ }
47
+ async function registerProject(home, directory, { timeoutMs = 5e3, connectClient = connect } = {}) {
48
+ const socket = daemonPaths(home).socket;
49
+ let client;
50
+ let expired = false;
51
+ let timer;
52
+ const work = (async () => {
53
+ const connected = await connectClient(socket, { name: "alp-cli", version: "1" }, { timeoutMs });
54
+ if (expired) {
55
+ connected.close();
56
+ return;
57
+ }
58
+ client = connected;
59
+ for (let attempt = 0; attempt < 5 && !expired; attempt++) {
60
+ const list = await client.request("project.list", { limit: 1 }, { timeoutMs }).catch(() => void 0);
61
+ if (expired) return;
62
+ const revision = typeof list?.revision === "number" ? list.revision : 0;
63
+ try {
64
+ await client.request("project.register", { directory, ifRevision: revision, requestId: randomUUID() }, { timeoutMs });
65
+ break;
66
+ } catch (error) {
67
+ if (error?.data?.reason === "stale_revision" && attempt < 4) continue;
68
+ break;
33
69
  }
70
+ }
71
+ })();
72
+ try {
73
+ await Promise.race([work.catch(() => {
74
+ }), new Promise((resolve) => {
75
+ timer = setTimeout(() => {
76
+ expired = true;
77
+ try {
78
+ client?.close();
79
+ } catch {
80
+ }
81
+ resolve(void 0);
82
+ }, timeoutMs);
83
+ })]);
84
+ } finally {
85
+ expired = true;
86
+ clearTimeout(timer);
87
+ try {
88
+ client?.close();
34
89
  } catch {
35
- alive = false;
36
90
  }
37
- let integrationPid = void 0;
91
+ }
92
+ }
93
+ async function waitForGrant(home, credentialId, project, { timeoutMs = 5e3 } = {}) {
94
+ const credentialsFile = path.join(home, "web", "credentials.json");
95
+ const canonical = await realpath(project).catch(() => project);
96
+ const deadline = Date.now() + timeoutMs;
97
+ while (Date.now() < deadline) {
38
98
  try {
39
- integrationPid = JSON.parse(await readFile(path.join(home, "integrations", "web.lock"), "utf8"))?.pid;
99
+ const raw = JSON.parse(await readFile(credentialsFile, "utf8"));
100
+ const credential = raw?.credentials?.find((c) => c.id === credentialId && !c.revokedAt);
101
+ if (credential?.workspaces?.some((w) => w.canonical === canonical || w.path === project || w.path === canonical)) {
102
+ return true;
103
+ }
40
104
  } catch {
41
105
  }
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));
106
+ await new Promise((resolve) => setTimeout(resolve, 25));
107
+ }
108
+ return false;
109
+ }
110
+ async function webDisabled(home) {
111
+ const settings = await readFile(path.join(home, "settings.json"), "utf8").then((text) => JSON.parse(text), () => void 0);
112
+ return settings?.web?.enabled === false;
113
+ }
114
+ var DISABLED = 'alp web is disabled by settings ("web.enabled": false).';
115
+ async function serveWeb(home, entry) {
116
+ await stopPreRenamePaseo(home);
117
+ const held = await webOwner(home);
118
+ const published = await readFile(path.join(home, "web.json"), "utf8").then((text) => JSON.parse(text), () => void 0);
119
+ const lockPid = await readFile(path.join(home, "integrations", "web.lock"), "utf8").then((text) => JSON.parse(text)?.pid, () => void 0);
120
+ const claimed = await isWebClaimed(published, lockPid, held);
121
+ if ("reason" in held && held.alive && held.kind === "foreign" && !claimed) throw new Error(`${refusal(home)} (${held.reason}). Stop it, then run alp web again.`);
122
+ const project = await currentProject();
123
+ let lock;
124
+ try {
125
+ lock = await startIntegration({ name: WEB, entry, home, args: project ? ["--project", project] : [] });
126
+ } catch (error) {
127
+ const owner = await webOwner(home);
128
+ if ("reason" in owner && owner.alive) throw new Error(`${error?.message ?? error}
129
+ ${refusal(home)} (${owner.reason}). If it is not alp web, stop it, then run alp web again.`, { cause: error });
130
+ throw error;
45
131
  }
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}`;
132
+ const info = await readFile(path.join(home, "web.json"), "utf8").then((text) => JSON.parse(text), () => void 0);
133
+ if (info?.app !== "alp-web" || info.pid !== lock.pid) {
134
+ const owner = await webOwner(home);
135
+ throw new Error(`${refusal(home)}${"reason" in owner ? ` (${owner.reason})` : ""}. Stop pid ${lock.pid}, then run alp web again.`);
136
+ }
137
+ if (typeof info.url !== "string" || typeof info.token !== "string" || !await isWebReady(info.url)) {
138
+ throw new Error(`alp web published no address; see ${path.join(home, "logs", "integrations", "alp-web.log")}`);
139
+ }
140
+ if (project) {
141
+ await registerProject(home, project);
142
+ await waitForGrant(home, info.credentialId, project);
143
+ }
144
+ return `${info.url}#token=${info.token}`;
145
+ }
146
+ async function webCommand(args) {
147
+ if (args[0] === "pair") return pairCommand(args.slice(1));
148
+ if (args[0] === "rotate") return rotateCommand(args.slice(1));
149
+ if (args[0] === "serve") return runRole("web", alpWebScript(), args.slice(1));
150
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { print: { type: "boolean" } } });
151
+ if (positionals.length) throw new UsageError();
152
+ const entry = alpWebEntry();
153
+ const home = alpHome();
154
+ if (await webDisabled(home)) throw new Error(DISABLED);
155
+ await start();
156
+ const url = await serveWeb(home, entry);
48
157
  console.log(url);
49
158
  if (values.print) return;
50
159
  const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open";
51
160
  spawn(opener, [url], { stdio: "ignore", detached: true }).on("error", () => console.error("Open the address above in your browser")).unref();
52
161
  }
162
+ async function rotateCommand(args) {
163
+ if (args.length) throw new UsageError();
164
+ const entry = alpWebEntry();
165
+ const home = alpHome();
166
+ await start();
167
+ const project = await projectArgs();
168
+ for (let attempt = 1; ; attempt++) {
169
+ await stopWebService(home);
170
+ const rotated = await new Promise((resolve) => {
171
+ const rotate = entryCommand(entry, "web", ["--rotate", ...project]);
172
+ execFile(
173
+ rotate.command,
174
+ rotate.args,
175
+ { env: { ...process.env, ALP_HOME: home }, encoding: "utf8", timeout: 6e4, killSignal: "SIGTERM" },
176
+ (error, stdout, stderr) => resolve({ code: error ? typeof error.code === "number" ? error.code : 1 : 0, output: `${stderr}${stdout}`.trim() })
177
+ );
178
+ });
179
+ if (rotated.code === 0) break;
180
+ if (rotated.code !== 3 || attempt >= 3) throw new Error(`alp web could not rotate its token${rotated.output ? `:
181
+ ${rotated.output.slice(-2e3)}` : ""}`);
182
+ }
183
+ if (await webDisabled(home)) {
184
+ console.log(`alp web has a new token; the old one no longer works. ${DISABLED.replace(/\.$/, "")}, so it was not started.`);
185
+ return;
186
+ }
187
+ console.log(await serveWeb(home, entry));
188
+ }
53
189
  async function requestPairing(client, params, attempts = 50) {
54
190
  let last;
55
191
  for (let attempt = 0; attempt < attempts; attempt += 1) {
@@ -66,7 +202,8 @@ async function pairCommand(args) {
66
202
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { on: { type: "boolean" }, off: { type: "boolean" } } });
67
203
  if (positionals.length || values.on && values.off) throw new UsageError();
68
204
  await start();
69
- await startIntegration();
205
+ const home = alpHome();
206
+ await startPaseoIntegration(home);
70
207
  const client = await running();
71
208
  try {
72
209
  const pairing = await requestPairing(client, values.on ? { enable: true } : values.off ? { enable: false } : {});
@@ -75,9 +212,11 @@ async function pairCommand(args) {
75
212
  return;
76
213
  }
77
214
  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):
215
+ console.log(`Open this link on the device that runs Paseo's app:
79
216
  ${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.");
217
+ const password = await readFile(path.join(home, `${PASEO}.json`), "utf8").then((text) => JSON.parse(text)?.token).catch(() => void 0);
218
+ if (typeof password === "string" && password) console.log(`When Paseo's app asks for a password, give it: ${password}`);
219
+ else console.log(`When Paseo's app asks for a password, give it the token in ${path.join(home, `${PASEO}.json`)}.`);
81
220
  } finally {
82
221
  client.close();
83
222
  }
@@ -85,12 +224,18 @@ ${pairing.url}`);
85
224
  async function acpCommand(args) {
86
225
  if (args.length) throw new UsageError();
87
226
  await built();
88
- const { runAcp } = await import(distributionEntry("acp.js"));
227
+ const acp = packagedInfo()?.roles?.acp;
228
+ const { runAcp } = (
229
+ /** @type {{ runAcp: (options: { daemonEntry: string }) => Promise<void> }} */
230
+ acp ? await acp() : await import(distributionEntry("acp.js").href)
231
+ );
89
232
  await runAcp({ daemonEntry: DAEMON_ENTRY });
90
233
  }
91
234
  export {
92
235
  acpCommand,
93
236
  pairCommand,
237
+ registerProject,
94
238
  requestPairing,
239
+ startPaseoIntegration,
95
240
  webCommand
96
241
  };
package/dist/paths.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  /** Locate artifacts in either the independently shipped CLI or the legacy root build. */
2
2
  export function distributionEntry(name: any): URL;
3
+ /** What starts alpd: alpd.js under Node, or the ALP executable itself (`alp daemon run`). */
3
4
  export const DAEMON_ENTRY: string;