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

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.
package/dist/usage.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // packages/cli/src/usage.js
2
2
  var USAGE = `Usage:
3
3
  alp <init|update-template> [directory] create a project, or upgrade an older project's ALP template (upgrade is an alias)
4
- alp update [--check] [--yes] [--version X] update the ALP executable from GitHub Releases (checksum and provenance checked)
4
+ alp update [--check] [--yes] [--version X] update ALP from GitHub Releases (checksum and provenance checked)
5
5
  alp --version
6
6
  alp setup [directory] [--runtime codex|claude|mix] [--prefer claude|codex]
7
7
  [--claude-model M] [--codex-model M] [--claude-supervisor M] [--codex-supervisor M]
@@ -9,7 +9,7 @@ var USAGE = `Usage:
9
9
  alp daemon <start|stop|restart>
10
10
  alp daemon status [--json] liveness and readiness; exit 0 ready, 3 not running, 4 not ready
11
11
  alp daemon <install|uninstall> run alpd as a login service that restarts after a crash
12
- alp daemon run [--detach] [--service] run alpd in this process (what services and the ALP executable start)
12
+ alp daemon run [--detach] [--service] run alpd in this process (what services written by 0.0.1-beta.5/6 start)
13
13
  alp acp serve ALP to an editor (Zed, JetBrains) over the Agent Client Protocol on stdio
14
14
  alp web [--print] open the ALP web app on this machine (alp-web, loopback); --print only prints its address
15
15
  alp web serve [--service|--rotate] [--project DIR] run alp-web in this process (what alp web starts)
@@ -8,12 +8,12 @@ import { fileURLToPath } from "node:url";
8
8
  import { promisify } from "node:util";
9
9
  import { bootTime, isSameBoot, readLock } from "@anhlp/alp-client/index";
10
10
  import { distributionEntry } from "./paths.js";
11
- import { isPackaged, selfEntry } from "@anhlp/alp-core/packaged";
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
14
  function alpWebScript() {
15
15
  const entry = fileURLToPath(distributionEntry("alp-web.js"));
16
- if (!isPackaged() && !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.`);
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.`);
17
17
  return entry;
18
18
  }
19
19
  var alpWebEntry = () => selfEntry(alpWebScript());
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anhlp/alp-cli",
3
- "version": "0.0.1-beta.6",
3
+ "version": "0.0.1-beta.7",
4
4
  "type": "module",
5
5
  "description": "ALP cli module",
6
6
  "files": [
@@ -127,9 +127,9 @@
127
127
  "node": ">=22.12"
128
128
  },
129
129
  "dependencies": {
130
- "@anhlp/alp-core": "0.0.1-beta.6",
131
- "@anhlp/alp-client": "0.0.1-beta.6",
132
- "@anhlp/alp-protocol": "0.0.1-beta.6",
130
+ "@anhlp/alp-core": "0.0.1-beta.7",
131
+ "@anhlp/alp-client": "0.0.1-beta.7",
132
+ "@anhlp/alp-protocol": "0.0.1-beta.7",
133
133
  "smol-toml": "1.9.0",
134
134
  "@agentclientprotocol/sdk": "1.7.0",
135
135
  "@anthropic-ai/claude-agent-sdk": "^0.3.292"
@@ -161,6 +161,6 @@
161
161
  "node-pty": "1.2.0-beta.15"
162
162
  },
163
163
  "devDependencies": {
164
- "@anhlp/alp-gateway": "0.0.1-beta.6"
164
+ "@anhlp/alp-gateway": "0.0.1-beta.7"
165
165
  }
166
166
  }
package/src/cli.js CHANGED
@@ -14,14 +14,14 @@ import { webCommand, acpCommand } from './interfaces.js';
14
14
  import { backupCommand, restoreCommand } from './backup.js';
15
15
  import { terminalCommand } from './terminal.js';
16
16
  import { bridgeCommand } from './roles.js';
17
- import { cleanupOldExecutable, selfUpdate } from './self-update.js';
18
- import { executablePath, packagedInfo } from '@anhlp/alp-core/packaged';
17
+ import { selfUpdate } from './self-update.js';
18
+ import { bundleInfo } from '@anhlp/alp-core/packaged';
19
19
  import { connect, lockAlive, readLock } from '@anhlp/alp-client/index';
20
20
 
21
- /** The version of this alp: the executable's, the build's, or the package's. */
21
+ /** The version of this alp: the build's, or the package's. */
22
22
  function alpVersion() {
23
23
  /* global __ALP_VERSION__ */
24
- return packagedInfo()?.version ?? (typeof __ALP_VERSION__ === 'string' ? __ALP_VERSION__ : JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
24
+ return (typeof __ALP_VERSION__ === 'string' ? __ALP_VERSION__ : JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
25
25
  }
26
26
 
27
27
  /** The running alpd's version and live sessions, if one runs for this ALP_HOME. */
@@ -40,15 +40,12 @@ async function runningDaemon() {
40
40
  }
41
41
  }
42
42
 
43
- /** alp update: the executable's self-update (t-1e02 P3); the template upgrade is alp update-template. */
43
+ /** alp update: the bundle's self-update (t-1807); the template upgrade is alp update-template. */
44
44
  async function updateCommand(args) {
45
- const code = await selfUpdate(args, { packaged: packagedInfo() !== undefined, version: alpVersion(), daemon: runningDaemon });
45
+ const code = await selfUpdate(args, { bundle: bundleInfo(), version: alpVersion(), daemon: runningDaemon });
46
46
  if (code) process.exitCode = code;
47
47
  }
48
48
 
49
- // A Windows update leaves the previous alp.exe as alp.old.exe: it can only go once that process ended.
50
- { const executable = executablePath(); if (executable) cleanupOldExecutable(executable); }
51
-
52
49
  const commands = { schedule: scheduleCommand, setup: args => setup(args, alpHome()), init: args => project('init', args), 'update-template': args => project('upgrade', args), upgrade: args => project('upgrade', args), update: updateCommand, daemon, doctor, run, ps, top, attach, send, questions, answer, log, board, tasks: tasksCommand, task: taskCommand, formula: formulaCommand, permissions: permissionsCommand, agents: args => libraryCommand('agents', args), skills: args => libraryCommand('skills', args), mcp: args => ['add', 'rm', 'mv', 'cp', 'test', 'show', 'edit'].includes(args[0]) ? editCommand('mcp', args) : libraryCommand('mcp', args), hooks: args => libraryCommand('hooks', args), providers: args => libraryCommand('providers', args), provider: args => editCommand('providers', args), teams: teamsCommand, trust: trustCommand, agent: args => editCommand('agents', args), team: args => editCommand('teams', args), skill: args => editCommand('skills', args), hook: args => editCommand('hooks', args), verify, recall, pause, resume, language, models, interrupt, compact, acp: acpCommand, web: webCommand, backup: backupCommand, restore: restoreCommand, terminal: terminalCommand, bridge: bridgeCommand };
53
50
  const [command, ...args] = process.argv.slice(2);
54
51
  try {
package/src/interfaces.js CHANGED
@@ -7,7 +7,7 @@ import { alpHome, connect, daemonPaths, discoverIntegration, startIntegration }
7
7
  import { UsageError } from './usage.js';
8
8
  import { built, start, running } from './daemon.js';
9
9
  import { DAEMON_ENTRY, distributionEntry } from './paths.js';
10
- import { entryCommand, packagedInfo } from '@anhlp/alp-core/packaged';
10
+ import { entryCommand } from '@anhlp/alp-core/packaged';
11
11
  import { runRole } from './roles.js';
12
12
  import { alpWebEntry, alpWebScript, isWebClaimed, isWebReady, refusal, stopPreRenamePaseo, stopWebService, webOwner } from './web-service.js';
13
13
 
@@ -287,8 +287,7 @@ async function pairCommand(args) {
287
287
  async function acpCommand(args) {
288
288
  if (args.length) throw new UsageError();
289
289
  await built();
290
- const acp = packagedInfo()?.roles?.acp;
291
- const { runAcp } = /** @type {{ runAcp: (options: { daemonEntry: string }) => Promise<void> }} */ (acp ? await acp() : await import(distributionEntry('acp.js').href));
290
+ const { runAcp } = /** @type {{ runAcp: (options: { daemonEntry: string }) => Promise<void> }} */ (await import(distributionEntry('acp.js').href));
292
291
  await runAcp({ daemonEntry: DAEMON_ENTRY });
293
292
  }
294
293
 
package/src/paths.js CHANGED
@@ -14,5 +14,5 @@ export function distributionEntry(name) {
14
14
  return candidates.find(candidate => existsSync(candidate)) ?? candidates[0];
15
15
  }
16
16
 
17
- /** What starts alpd: alpd.js under Node, or the ALP executable itself (`alp daemon run`). */
17
+ /** What starts alpd: alpd.js under Node (named through app/current in the ALP bundle). */
18
18
  export const DAEMON_ENTRY = selfEntry(fileURLToPath(distributionEntry('alpd.js')));
package/src/roles.js CHANGED
@@ -1,13 +1,12 @@
1
1
  import { pathToFileURL } from 'node:url';
2
2
  import { runBridge } from '@anhlp/alp-core/bridges';
3
- import { packagedInfo } from '@anhlp/alp-core/packaged';
4
3
  import { UsageError } from './usage.js';
5
4
 
6
5
  /**
7
6
  * The role subcommands (t-1e02): `alp daemon run`, `alp web serve` and `alp bridge acp|antigravity`
8
- * run alpd, alp-web and the MCP bridges in this process. The ALP executable starts its own roles
9
- * this way, since it cannot run a script path; under Node they import the same scripts that
10
- * `node alpd.js` and `node alp-web.js` run.
7
+ * run alpd, alp-web and the MCP bridges in this process: they import the same scripts that
8
+ * `node alpd.js` and `node alp-web.js` run. Services and MCP entries written by the single-file
9
+ * executable of 0.0.1-beta.5/6 still name them.
11
10
  *
12
11
  * The role's module reads its options from process.argv as when run directly, so argv is rewritten
13
12
  * to `[runtime, entry, ...args]` before the module loads.
@@ -17,8 +16,7 @@ import { UsageError } from './usage.js';
17
16
  */
18
17
  export async function runRole(role, file, args) {
19
18
  process.argv = [process.argv[0], file, ...args];
20
- const load = packagedInfo()?.roles?.[role];
21
- return load ? load() : import(pathToFileURL(file).href);
19
+ return import(pathToFileURL(file).href);
22
20
  }
23
21
 
24
22
  /** alp bridge acp|antigravity: the stdio MCP bridge an agent CLI starts to reach alpd's tools. @param {string[]} args */
@@ -6,12 +6,13 @@ import path from 'node:path';
6
6
  import { createInterface } from 'node:readline/promises';
7
7
  import { fileURLToPath, pathToFileURL } from 'node:url';
8
8
  import { parseArgs } from 'node:util';
9
- import { executablePath } from '@anhlp/alp-core/packaged';
9
+ import { bundleInfo, samePath } from '@anhlp/alp-core/packaged';
10
10
 
11
11
  /**
12
- * `alp update` (t-1e02 P3): replaces the ALP executable with a release from GitHub Releases, after
13
- * checking the archive against the release's SHA256SUMS and, when `gh` is installed, its build
14
- * provenance. The project template upgrade that `alp update` used to run is `alp update-template`.
12
+ * `alp update` (t-1807): installs a release of the ALP bundle from GitHub Releases beside the running
13
+ * one (<app>/<version>, see @anhlp/alp-core/packaged) and points <app>/current at it, after checking
14
+ * the archive against the release's SHA256SUMS and, when `gh` is installed, its build provenance.
15
+ * The project template upgrade that `alp update` used to run is `alp update-template`.
15
16
  *
16
17
  * Everything that touches the network, the filesystem or child processes comes in through `deps`
17
18
  * so the tests can drive each step.
@@ -20,12 +21,12 @@ import { executablePath } from '@anhlp/alp-core/packaged';
20
21
  export const DEFAULT_REPO = 'phucanh08/alp';
21
22
  export const SIGNER_WORKFLOW = '.github/workflows/release-binaries.yml';
22
23
  export const NPM_PACKAGE = '@anhlp/alp';
23
- const TEMPLATE_HINT = 'did you mean `alp update-template`? (`alp update` now updates the ALP executable; the project template upgrade is `alp update-template [directory]`)';
24
+ const TEMPLATE_HINT = 'did you mean `alp update-template`? (`alp update` now updates ALP itself; the project template upgrade is `alp update-template [directory]`)';
24
25
 
25
26
  const OPTIONS = { check: { type: 'boolean' }, yes: { type: 'boolean', short: 'y' }, version: { type: 'string' }, 'base-url': { type: 'string' }, help: { type: 'boolean', short: 'h' } };
26
27
 
27
28
  export const UPDATE_USAGE = `Usage: alp update [--check] [--yes] [--version X] [--base-url URL]
28
- Replaces this ALP executable with the latest release (or release X) from GitHub Releases, after checking
29
+ Installs the latest ALP release (or release X) from GitHub Releases beside this one and switches to it, after checking
29
30
  it against SHA256SUMS and, when gh is installed, its build provenance. --check only reports.
30
31
  ALP_UPDATE_BASE_URL (as --base-url, an https:// or file:// mirror) and ALP_INSTALL_REPO (owner/name) override the source.
31
32
  The project template upgrade is \`alp update-template [directory]\`.`;
@@ -34,7 +35,7 @@ The project template upgrade is \`alp update-template [directory]\`.`;
34
35
  export function releasePlatform(platform = process.platform, arch = process.arch) {
35
36
  const osName = { darwin: 'darwin', linux: 'linux', win32: 'windows' }[platform];
36
37
  const archName = { x64: 'x64', arm64: 'arm64' }[arch];
37
- if (!osName || !archName || (osName === 'windows' && archName !== 'x64')) throw new Error(`ALP publishes no executable for ${platform}-${arch}`);
38
+ if (!osName || !archName || (osName === 'windows' && archName !== 'x64')) throw new Error(`ALP publishes no build for ${platform}-${arch}`);
38
39
  return `${osName}-${archName}`;
39
40
  }
40
41
 
@@ -62,7 +63,7 @@ export function parseSums(text) {
62
63
  export function selectAsset(sumsText, platform, version) {
63
64
  const suffix = `-${platform}${archiveExtension(platform)}`;
64
65
  const matches = parseSums(sumsText).filter(({ name }) => name.endsWith(suffix) && /^alp-[0-9]/.test(name) && (!version || name === `alp-${version}${suffix}`));
65
- if (matches.length === 0) throw new Error(`This release has no ALP executable for ${platform}${version ? ` at version ${version}` : ''}`);
66
+ if (matches.length === 0) throw new Error(`This release has no ALP build for ${platform}${version ? ` at version ${version}` : ''}`);
66
67
  if (matches.length > 1) throw new Error(`SHA256SUMS lists more than one ${platform} archive: ${matches.map(m => m.name).join(', ')}`);
67
68
  const [match] = matches;
68
69
  if (/[^0-9A-Za-z.+_-]/.test(match.name)) throw new Error(`Unexpected archive name in SHA256SUMS: ${match.name}`);
@@ -109,7 +110,7 @@ export function releaseBaseUrl({ repo, version, baseUrl }) {
109
110
  return base;
110
111
  }
111
112
 
112
- /** The largest file alp update downloads: the executable is about 100 MB. */
113
+ /** The largest file alp update downloads: an archive of the bundle is about 70 MB. */
113
114
  export const MAX_DOWNLOAD = 512 * 1024 * 1024;
114
115
 
115
116
  const LOOPBACK = ['127.0.0.1', 'localhost', '[::1]'];
@@ -188,18 +189,12 @@ export function verifyProvenance(file, { repo, env = process.env, run = spawnSyn
188
189
  return 'verified';
189
190
  }
190
191
 
191
- /** The previous executable Windows keeps beside the new one until the next start. @param {string} target @param {string} [platform] */
192
- export const oldPath = (target, platform = process.platform) => {
193
- const p = platform === 'win32' ? path.win32 : path;
194
- return p.join(p.dirname(target), `${p.basename(target, p.extname(target))}.old${p.extname(target) || '.exe'}`);
195
- };
196
-
197
- const TRANSIENT = new Set(['EBUSY', 'EPERM', 'EACCES']);
192
+ const TRANSIENT = new Set(['EBUSY', 'EPERM', 'EACCES', 'ENOTEMPTY']);
198
193
  const pause = (/** @type {number} */ ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
199
194
 
200
195
  /**
201
196
  * Runs `action`, again after a pause while Windows reports the file busy: a virus scanner holds an
202
- * executable it just saw run (the staged file's --version) for a moment. About 6 s in all.
197
+ * executable it just saw run (the staged bundle's --version) for a moment. About 6 s in all.
203
198
  * @template T @param {() => T} action @param {(ms: number) => void} [sleep]
204
199
  */
205
200
  export function retryBusy(action, sleep = pause, attempts = 25) {
@@ -211,64 +206,7 @@ export function retryBusy(action, sleep = pause, attempts = 25) {
211
206
  }
212
207
  }
213
208
 
214
- /**
215
- * Puts `staged` in place of `target`. Unix: rename over the running file. Windows: the running
216
- * alp.exe cannot be overwritten but can be renamed, so it becomes alp.old.exe (deleted on the next
217
- * start) and the new file takes its name; a failure puts the old one back.
218
- * @param {string} staged @param {string} target @param {{ platform?: string, fs?: Pick<typeof nodeFs, 'renameSync' | 'rmSync' | 'existsSync'>, unique?: () => string, sleep?: (ms: number) => void }} [options]
219
- */
220
- export function replaceExecutable(staged, target, { platform = process.platform, fs = nodeFs, unique = () => randomBytes(4).toString('hex'), sleep = pause } = {}) {
221
- if (platform !== 'win32') { fs.renameSync(staged, target); return { old: undefined }; }
222
- const old = oldPath(target, platform);
223
- if (fs.existsSync(old)) {
224
- // A process started from the previous update's file (an alpd not restarted yet) keeps it locked:
225
- // it cannot be deleted, but it can be moved aside for a later start to delete.
226
- try { fs.rmSync(old, { force: true }); } catch {
227
- const aside = old.replace(/\.exe$/i, `.${unique()}.exe`);
228
- try { fs.renameSync(old, aside); } catch (error) {
229
- throw new Error(`${old} is in use and could not be moved (${error.code ?? error.message}); stop the ALP processes started from it (alp daemon stop) and run alp update again`);
230
- }
231
- }
232
- }
233
- retryBusy(() => fs.renameSync(target, old), sleep);
234
- try {
235
- retryBusy(() => fs.renameSync(staged, target), sleep);
236
- } catch (error) {
237
- try { retryBusy(() => fs.renameSync(old, target), sleep); } catch (restore) {
238
- throw new Error(`Could not put the new executable at ${target} (${error.code ?? error.message}), and could not move the previous one back (${restore.code ?? restore.message}): rename ${old} to ${target} yourself`);
239
- }
240
- throw error;
241
- }
242
- return { old };
243
- }
244
-
245
- /** Deletes the alp.old.exe (and alp.old.<hex>.exe) a Windows update left behind; called on every packaged start. @param {string} target @param {{ platform?: string, fs?: Pick<typeof nodeFs, 'rmSync' | 'readdirSync'> }} [options] */
246
- export function cleanupOldExecutable(target, { platform = process.platform, fs = nodeFs } = {}) {
247
- if (platform !== 'win32') return false;
248
- const old = path.win32.basename(oldPath(target, platform));
249
- const stem = old.slice(0, -'.exe'.length).toLowerCase();
250
- let names;
251
- try { names = fs.readdirSync(path.win32.dirname(target)); } catch { return false; }
252
- let removed = false;
253
- // alp.old.exe, and the alp.old.<hex>.exe a locked one was moved aside to.
254
- for (const name of names) {
255
- const lower = name.toLowerCase();
256
- if (lower !== `${stem}.exe` && !(lower.startsWith(`${stem}.`) && /^[0-9a-f]+\.exe$/.test(lower.slice(stem.length + 1)))) continue;
257
- try { fs.rmSync(path.win32.join(path.win32.dirname(target), name), { force: true }); removed = true; } catch {}
258
- }
259
- return removed;
260
- }
261
-
262
- /**
263
- * Whether the executable is the one npm installed for @anhlp/alp (t-cd7f): it lives in a platform
264
- * package, node_modules/@anhlp/alp-<os>-<arch>/bin/. npm owns that file; updating it in place would
265
- * leave npm's records behind, so npm updates it. @param {string} execPath
266
- */
267
- export function isNpmExecutable(execPath) {
268
- return /[\\/]node_modules[\\/]@anhlp[\\/]alp-(?:darwin|linux|win32)-(?:arm64|x64)[\\/]bin[\\/]alp(?:\.exe)?$/i.test(execPath ?? '');
269
- }
270
-
271
- /** What to say outside the executable (an npm install). @param {string[]} positionals */
209
+ /** What to say outside the ALP bundle (an npm install). @param {string[]} positionals */
272
210
  export function npmMessage(positionals = []) {
273
211
  const lines = [];
274
212
  if (positionals.length) lines.push(`alp: ${TEMPLATE_HINT}`);
@@ -276,18 +214,68 @@ export function npmMessage(positionals = []) {
276
214
  return lines.join('\n');
277
215
  }
278
216
 
279
- /** Extracts the archive and returns the executable inside it. @param {string} archive @param {string} directory @param {{ name: string }} asset @param {string} platform */
217
+ /** Why this bundle cannot update itself: it was not installed by install.sh / install.ps1. @param {string} root */
218
+ export const notInstalledMessage = root => `alp: ${root} is not an installed ALP (no app/current points at it); install the release with install.sh (Windows: install.ps1), which alp update can then keep up to date:\n curl -fsSL https://github.com/${DEFAULT_REPO}/releases/latest/download/install.sh | sh`;
219
+
220
+ const systemTar = () => process.platform === 'win32' ? path.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'tar.exe') : 'tar';
221
+
222
+ /** Extracts the archive into `directory` and returns the bundle inside it. @param {string} archive @param {string} directory @param {{ name: string }} asset @param {string} platform */
280
223
  function extract(archive, directory, asset, platform, run = spawnSync) {
281
224
  const windows = platform.startsWith('windows-');
282
225
  // tar reads both: GNU/bsd tar for .tar.gz, Windows' bsdtar (tar.exe) for .zip.
283
226
  // On Windows, Git's GNU tar (which reads no zip) may come first on PATH: use the system's bsdtar.
284
- const tar = process.platform === 'win32' ? path.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'tar.exe') : 'tar';
285
- const result = run(tar, [windows ? '-xf' : '-xzf', archive, '-C', directory], { encoding: 'utf8', windowsHide: true });
227
+ const result = run(systemTar(), [windows ? '-xf' : '-xzf', archive, '-C', directory], { encoding: 'utf8', windowsHide: true });
286
228
  if (result.status !== 0) throw new Error(`Could not extract ${asset.name}: ${(result.stderr || result.error?.message || '').trim()}`);
287
- const name = asset.name.slice(0, -archiveExtension(platform).length);
288
- const binary = path.join(directory, name, windows ? 'alp.exe' : 'alp');
289
- if (!nodeFs.existsSync(binary)) throw new Error(`${asset.name} does not contain ${name}/${windows ? 'alp.exe' : 'alp'}`);
290
- return binary;
229
+ const root = path.join(directory, asset.name.slice(0, -archiveExtension(platform).length));
230
+ if (!nodeFs.existsSync(path.join(root, 'alp-bundle.json'))) throw new Error(`${asset.name} does not contain an ALP bundle (${path.basename(root)}/alp-bundle.json)`);
231
+ return root;
232
+ }
233
+
234
+ /** The bundle's own Node and CLI: run without its launcher, so Windows needs no shell for alp.cmd. @param {string} root @param {string} platform */
235
+ export function bundleCommand(root, platform = process.platform) {
236
+ const node = platform === 'win32' ? path.join(root, 'node', 'node.exe') : path.join(root, 'node', 'bin', 'node');
237
+ return { command: node, args: [path.join(root, 'lib', 'node_modules', '@anhlp', 'alp-cli', 'dist', 'cli.js')] };
238
+ }
239
+
240
+ /**
241
+ * Points `<app>/current` at `<app>/<version>`. Unix: a relative symlink renamed over the old one, in
242
+ * one step. Windows: the junction is replaced (removed, then made again; put back on failure).
243
+ * @param {string} app @param {string} version @param {{ platform?: string, fs?: typeof nodeFs, unique?: () => string }} [options]
244
+ */
245
+ export function switchCurrent(app, version, { platform = process.platform, fs = nodeFs, unique = () => randomBytes(6).toString('hex') } = {}) {
246
+ const p = platform === 'win32' ? path.win32 : path;
247
+ const current = p.join(app, 'current');
248
+ if (platform !== 'win32') {
249
+ const link = p.join(app, `.current-${unique()}`);
250
+ fs.symlinkSync(version, link);
251
+ try { fs.renameSync(link, current); } catch (error) { try { fs.unlinkSync(link); } catch {} throw error; }
252
+ return;
253
+ }
254
+ let previous;
255
+ try { previous = fs.readlinkSync(current); } catch {}
256
+ if (previous !== undefined) retryBusy(() => fs.unlinkSync(current));
257
+ try { fs.symlinkSync(p.join(app, version), current, 'junction'); } catch (error) {
258
+ if (previous !== undefined) try { fs.symlinkSync(previous, current, 'junction'); } catch {}
259
+ throw error;
260
+ }
261
+ }
262
+
263
+ /**
264
+ * Removes what earlier updates left in `<app>`: versions other than `keep`, and staging directories.
265
+ * A failure (a file still in use on Windows) leaves that entry for the next update. keepAside keeps
266
+ * the copies earlier reinstalls moved aside, which a running alpd may still run from.
267
+ * @param {string} app @param {string[]} keep
268
+ */
269
+ export function pruneVersions(app, keep, fs = nodeFs, { keepAside = false } = {}) {
270
+ let names;
271
+ try { names = fs.readdirSync(app); } catch { return []; }
272
+ const removed = [];
273
+ for (const name of names) {
274
+ if (name === 'current' || keep.includes(name) || (keepAside && name.startsWith('.alp-old-'))) continue;
275
+ if (!/^[0-9][0-9A-Za-z.+-]*$/.test(name) && !/^\.alp-(update|old)-[0-9A-Za-z]+$/.test(name) && !/^\.current-[0-9a-f]+$/.test(name)) continue;
276
+ try { fs.rmSync(path.join(app, name), { recursive: true, force: true }); removed.push(name); } catch {}
277
+ }
278
+ return removed;
291
279
  }
292
280
 
293
281
  /** Asks a yes/no question on the terminal. @param {string} question */
@@ -298,12 +286,12 @@ async function confirm(question) {
298
286
 
299
287
  /**
300
288
  * @typedef {{
301
- * packaged: boolean, version: string, execPath: string, env: NodeJS.ProcessEnv, platform: string, arch: string,
289
+ * bundle: import('@anhlp/alp-core/packaged').BundleInfo | undefined, version: string, env: NodeJS.ProcessEnv, platform: string, arch: string,
302
290
  * log: (line: string) => void, warn: (line: string) => void, interactive: boolean,
303
291
  * fetchBytes: (url: string) => Promise<Uint8Array>, confirm: (question: string) => Promise<boolean>,
304
292
  * provenance: (file: string, repo: string) => string, extract: typeof extract,
305
- * daemon: () => Promise<{ version: string, sessions?: number } | undefined>, restartDaemon: (binary: string) => number,
306
- * runVersion: (binary: string) => string,
293
+ * daemon: () => Promise<{ version: string, sessions?: number } | undefined>, restartDaemon: (root: string) => number,
294
+ * runVersion: (root: string) => string,
307
295
  * }} UpdateDeps
308
296
  */
309
297
 
@@ -311,26 +299,29 @@ async function confirm(question) {
311
299
  export async function selfUpdate(args, overrides = {}) {
312
300
  /** @type {UpdateDeps} */
313
301
  const deps = {
314
- packaged: false, version: '0.0.0', execPath: executablePath() ?? '', env: process.env, platform: process.platform, arch: process.arch,
302
+ bundle: bundleInfo(), version: '0.0.0', env: process.env, platform: process.platform, arch: process.arch,
315
303
  log: line => console.log(line), warn: line => console.error(line), interactive: !!(process.stdin.isTTY && process.stdout.isTTY),
316
304
  fetchBytes, confirm, extract,
317
305
  provenance: (file, repo) => verifyProvenance(file, { repo }),
318
- daemon: async () => undefined, restartDaemon: binary => spawnSync(binary, ['daemon', 'restart'], { stdio: 'inherit', windowsHide: true }).status ?? 1,
319
- runVersion: binary => spawnSync(binary, ['--version'], { encoding: 'utf8', windowsHide: true, timeout: 60_000 }).stdout?.trim() ?? '',
306
+ daemon: async () => undefined,
307
+ restartDaemon: root => { const run = bundleCommand(root); return spawnSync(run.command, [...run.args, 'daemon', 'restart'], { stdio: 'inherit', windowsHide: true }).status ?? 1; },
308
+ runVersion: root => { const run = bundleCommand(root); return spawnSync(run.command, [...run.args, '--version'], { encoding: 'utf8', windowsHide: true, timeout: 60_000 }).stdout?.trim() ?? ''; },
320
309
  ...overrides,
321
310
  };
311
+ const { bundle } = deps;
322
312
  let parsed;
323
313
  try {
324
314
  parsed = parseArgs({ args, allowPositionals: true, options: OPTIONS, strict: true });
325
315
  } catch (error) {
326
316
  deps.warn(`alp: ${error.message}`);
327
317
  deps.warn(`alp: ${TEMPLATE_HINT}`);
328
- return deps.packaged ? 1 : 0;
318
+ return bundle ? 1 : 0;
329
319
  }
330
320
  const { values, positionals } = parsed;
331
321
  if (values.help) { deps.log(UPDATE_USAGE); return 0; }
332
- if (!deps.packaged || isNpmExecutable(deps.execPath)) { deps.log(npmMessage(positionals)); return 0; }
322
+ if (!bundle) { deps.log(npmMessage(positionals)); return 0; }
333
323
  if (positionals.length) { deps.warn(`alp: ${TEMPLATE_HINT}`); return 1; }
324
+ if (!bundle.current) { deps.warn(notInstalledMessage(bundle.root)); return 1; }
334
325
 
335
326
  const wanted = values.version?.replace(/^v/, '');
336
327
  if (wanted !== undefined && !/^[0-9][0-9A-Za-z.+-]*$/.test(wanted)) throw new Error(`Invalid version: ${values.version}`);
@@ -352,18 +343,24 @@ export async function selfUpdate(args, overrides = {}) {
352
343
  if (order === 0 && !wanted) { deps.log(`alp ${deps.version} is up to date (${platform})`); return 0; }
353
344
  if (order < 0 && !wanted) { deps.log(`alp ${deps.version} is newer than the latest release ${asset.version}; nothing to do (pass --version ${asset.version} to go back)`); return 0; }
354
345
 
355
- let target;
356
- try { target = nodeFs.realpathSync(deps.execPath); } catch { target = deps.execPath; }
357
- const dir = path.dirname(target);
358
- try { nodeFs.accessSync(dir, nodeFs.constants.W_OK); } catch { throw new Error(`${dir} is not writable; run alp update with the permissions that installed ${target}`); }
346
+ const { app, current } = bundle;
347
+ // Windows cannot rename or delete a directory that a running node.exe (this one) comes from.
348
+ if (deps.platform === 'win32' && asset.version === path.basename(bundle.root)) throw new Error(`ALP ${asset.version} is the version running now; Windows cannot replace it in place. Close ALP (alp daemon stop) and rerun install.ps1 to repair it`);
349
+ // The version a running alpd uses keeps its files, like the one this process runs.
350
+ const running = await deps.daemon().catch(() => undefined);
351
+ try { nodeFs.accessSync(app, nodeFs.constants.W_OK); } catch { throw new Error(`${app} is not writable; run alp update with the permissions that installed ALP there`); }
352
+ const target = path.join(app, asset.version);
359
353
 
360
354
  if (!values.yes) {
361
- if (!deps.interactive) throw new Error(`alp update would replace ${target} (${deps.version} → ${asset.version}); pass --yes to do it without a terminal`);
362
- if (!await deps.confirm(`Replace ${target} (${deps.version} → ${asset.version})?`)) { deps.log('Not updated.'); return 1; }
355
+ if (!deps.interactive) throw new Error(`alp update would install ${target} and switch ${current} to it (${deps.version} → ${asset.version}); pass --yes to do it without a terminal`);
356
+ if (!await deps.confirm(`Install ALP ${asset.version} in ${target} and switch to it (from ${deps.version})?`)) { deps.log('Not updated.'); return 1; }
363
357
  }
364
358
 
365
359
  const work = nodeFs.mkdtempSync(path.join(os.tmpdir(), 'alp-update-'));
366
- let staged;
360
+ // Unpacked beside the versions, so moving it into place stays on one filesystem.
361
+ const staging = path.join(app, `.alp-update-${randomBytes(6).toString('hex')}`);
362
+ /** @type {string | undefined} the running version, moved aside by a reinstall */
363
+ let aside;
367
364
  try {
368
365
  deps.log(`Downloading ${asset.name} from ${base}`);
369
366
  const bytes = await deps.fetchBytes(`${base}/${asset.name}`);
@@ -374,25 +371,28 @@ export async function selfUpdate(args, overrides = {}) {
374
371
  const provenance = deps.provenance(archive, repo);
375
372
  if (provenance === 'verified') deps.log(`Provenance verified by gh attestation (${repo}, refs/heads/main, release-binaries.yml)`);
376
373
  else deps.warn('alp: warning: gh is not available, so only the SHA256SUMS checksum was verified, not the build provenance (install gh to verify it)');
377
- const unpacked = path.join(work, 'x');
378
- nodeFs.mkdirSync(unpacked);
379
- const binary = deps.extract(archive, unpacked, asset, platform);
380
- // Stage beside the target so the rename stays on one filesystem; no half-written file is ever alp.
381
- staged = path.join(dir, `.alp.update.${randomBytes(6).toString('hex')}${deps.platform === 'win32' ? '.exe' : ''}`);
382
- nodeFs.copyFileSync(binary, staged);
383
- if (deps.platform !== 'win32') nodeFs.chmodSync(staged, 0o755);
384
- const reported = deps.runVersion(staged);
385
- if (reported !== asset.version) throw new Error(`The downloaded executable reports version ${JSON.stringify(reported)}, not ${asset.version}; nothing was replaced`);
386
- replaceExecutable(staged, target, { platform: deps.platform });
387
- staged = undefined;
374
+ nodeFs.mkdirSync(staging);
375
+ const unpacked = deps.extract(archive, staging, asset, platform);
376
+ const manifest = JSON.parse(nodeFs.readFileSync(path.join(unpacked, 'alp-bundle.json'), 'utf8'));
377
+ if (manifest.version !== asset.version || (manifest.platform && manifest.platform !== platform)) throw new Error(`${asset.name} holds ALP ${manifest.version} for ${manifest.platform}, not ${asset.version} for ${platform}; nothing was changed`);
378
+ const reported = deps.runVersion(unpacked);
379
+ if (reported !== asset.version) throw new Error(`The downloaded ALP reports version ${JSON.stringify(reported)}, not ${asset.version}; nothing was changed`);
380
+ if (nodeFs.existsSync(target)) {
381
+ // A reinstall of the running version moves it aside (its processes keep their files); any other copy is stale.
382
+ if (samePath(target, bundle.root) || running?.version === asset.version) { aside = `.alp-old-${randomBytes(6).toString('hex')}`; retryBusy(() => nodeFs.renameSync(target, path.join(app, aside))); }
383
+ else nodeFs.rmSync(target, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
384
+ }
385
+ retryBusy(() => nodeFs.renameSync(unpacked, target));
386
+ switchCurrent(app, asset.version, { platform: deps.platform });
388
387
  } finally {
389
- // A cleanup failure must not hide why the update failed; a leftover .alp.update.* is harmless.
390
- if (staged) try { nodeFs.rmSync(staged, { force: true, maxRetries: 10, retryDelay: 100 }); } catch {}
388
+ // A cleanup failure must not hide why the update failed; a leftover staging directory goes with the next update.
389
+ try { nodeFs.rmSync(staging, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } catch {}
391
390
  try { nodeFs.rmSync(work, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } catch {}
392
391
  }
393
- deps.log(`Updated ${target}: ${deps.version} → ${asset.version}`);
392
+ // The version this process (and maybe alpd) runs stays until the next update.
393
+ pruneVersions(app, [asset.version, path.basename(bundle.root), ...(running?.version ? [running.version] : []), ...(aside ? [aside] : [])], nodeFs, { keepAside: Boolean(running) });
394
+ deps.log(`Updated ALP ${deps.version} → ${asset.version} (${current} → ${target})`);
394
395
 
395
- const running = await deps.daemon().catch(() => undefined);
396
396
  if (running && running.version !== asset.version) {
397
397
  const sessions = running.sessions;
398
398
  const known = Number.isSafeInteger(sessions);
package/src/usage.js CHANGED
@@ -3,7 +3,7 @@ import path from 'node:path';
3
3
 
4
4
  const USAGE = `Usage:
5
5
  alp <init|update-template> [directory] create a project, or upgrade an older project's ALP template (upgrade is an alias)
6
- alp update [--check] [--yes] [--version X] update the ALP executable from GitHub Releases (checksum and provenance checked)
6
+ alp update [--check] [--yes] [--version X] update ALP from GitHub Releases (checksum and provenance checked)
7
7
  alp --version
8
8
  alp setup [directory] [--runtime codex|claude|mix] [--prefer claude|codex]
9
9
  [--claude-model M] [--codex-model M] [--claude-supervisor M] [--codex-supervisor M]
@@ -11,7 +11,7 @@ const USAGE = `Usage:
11
11
  alp daemon <start|stop|restart>
12
12
  alp daemon status [--json] liveness and readiness; exit 0 ready, 3 not running, 4 not ready
13
13
  alp daemon <install|uninstall> run alpd as a login service that restarts after a crash
14
- alp daemon run [--detach] [--service] run alpd in this process (what services and the ALP executable start)
14
+ alp daemon run [--detach] [--service] run alpd in this process (what services written by 0.0.1-beta.5/6 start)
15
15
  alp acp serve ALP to an editor (Zed, JetBrains) over the Agent Client Protocol on stdio
16
16
  alp web [--print] open the ALP web app on this machine (alp-web, loopback); --print only prints its address
17
17
  alp web serve [--service|--rotate] [--project DIR] run alp-web in this process (what alp web starts)
@@ -7,7 +7,7 @@ import { fileURLToPath } from 'node:url';
7
7
  import { promisify } from 'node:util';
8
8
  import { bootTime, isSameBoot, readLock } from '@anhlp/alp-client/index';
9
9
  import { distributionEntry } from './paths.js';
10
- import { isPackaged, selfEntry } from '@anhlp/alp-core/packaged';
10
+ import { selfEntry } from '@anhlp/alp-core/packaged';
11
11
 
12
12
  /**
13
13
  * The CLI's side of alp-web (packages/cli/src/web), the service behind `alp web`: where it is, which
@@ -27,12 +27,11 @@ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
27
27
  /** The alp-web service script beside this CLI; a clear error when this CLI was built without it. */
28
28
  export function alpWebScript() {
29
29
  const entry = fileURLToPath(distributionEntry('alp-web.js'));
30
- // The ALP executable carries alp-web inside itself.
31
- if (!isPackaged() && !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.`);
30
+ 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.`);
32
31
  return entry;
33
32
  }
34
33
 
35
- /** What starts alp-web: its script under Node, or the ALP executable (`alp web serve`). */
34
+ /** What starts alp-web: its script under Node (named through app/current in the ALP bundle). */
36
35
  export const alpWebEntry = () => selfEntry(alpWebScript());
37
36
 
38
37
  const readJson = async file => JSON.parse(await readFile(file, 'utf8'));