@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
@@ -0,0 +1,78 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { chmod, lstat, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { alpHome } from '@anhlp/alp-client/index';
6
+ import { UsageError } from './usage.js';
7
+
8
+ /**
9
+ * `alp terminal allow|deny|status`: the host owner's switch for remote terminals
10
+ * (docs/protocol/alp-json-rpc-v1.md §12.10, issue #121 H). It lives in $ALP_HOME/terminal.json, a
11
+ * file only this user may read or write; no RPC changes it and no backup carries it.
12
+ */
13
+ export const TERMINAL_WARNING = (user = os.userInfo().username) => [
14
+ `A remote terminal runs a real shell on this computer as ${user}, with that account's full access:`,
15
+ 'every file it can read or write, any program, and the network.',
16
+ 'A workspace only picks the directory the shell starts in. It is NOT a sandbox.',
17
+ 'Only gateway credentials that hold the terminal.exec permission can open one (never a default);',
18
+ 'Paseo app devices paired with this host only after alp terminal allow --paseo.',
19
+ ].join('\n');
20
+
21
+ const file = home => path.join(home, 'terminal.json');
22
+
23
+ export async function read(home, platform = process.platform) {
24
+ const info = await lstat(file(home)).catch(() => undefined);
25
+ if (!info) return { exists: false, value: undefined, private: true };
26
+ const own = !process.getuid || info.uid === process.getuid();
27
+ const value = info.isFile() ? await readFile(file(home), 'utf8').then(JSON.parse).catch(() => undefined) : undefined;
28
+ // Windows has no POSIX group/other mode bits (files report 0o666/0o444).
29
+ return { exists: true, value, private: info.isFile() && own && (platform === 'win32' || !(info.mode & 0o077)) };
30
+ }
31
+
32
+ async function write(home, value) {
33
+ await mkdir(home, { recursive: true, mode: 0o700 });
34
+ const temporary = `${file(home)}.${randomUUID().slice(0, 8)}.tmp`;
35
+ await writeFile(temporary, JSON.stringify(value, null, 2) + '\n', { mode: 0o600, flag: 'wx' });
36
+ await chmod(temporary, 0o600);
37
+ await rename(temporary, file(home)).catch(async error => { await rm(temporary, { force: true }); throw error; });
38
+ }
39
+
40
+ export async function terminalCommand(args, { home = alpHome(), out = console.log } = {}) {
41
+ const [action, ...rest] = args;
42
+ const json = rest.includes('--json');
43
+ const current = await read(home);
44
+ const limits = current.value && typeof current.value.limits === 'object' && current.value.limits ? { limits: current.value.limits } : {};
45
+ const paseo = rest.includes('--paseo');
46
+ const paseoBefore = current.private && current.value?.allowPaseoTerminal === true;
47
+ if (action === 'allow') {
48
+ if (!rest.includes('--yes')) {
49
+ out(`${TERMINAL_WARNING()}\n\nRun again with --yes to allow remote terminals on this host.`);
50
+ process.exitCode = 1;
51
+ return;
52
+ }
53
+ const allowPaseoTerminal = paseo || paseoBefore;
54
+ await write(home, { version: 1, allowRemoteTerminal: true, ...(allowPaseoTerminal ? { allowPaseoTerminal: true } : {}), ...limits });
55
+ out(json ? JSON.stringify({ allowRemoteTerminal: true, allowPaseoTerminal }) : `${TERMINAL_WARNING()}\n\nRemote terminals are allowed on this host (${file(home)})${allowPaseoTerminal ? ', also for every Paseo app device paired with it' : ''}. alp terminal deny turns them off and ends every open one.`);
56
+ return;
57
+ }
58
+ if (action === 'deny') {
59
+ if (paseo) {
60
+ const allowed = current.private && current.value?.allowRemoteTerminal === true;
61
+ await write(home, { version: 1, allowRemoteTerminal: allowed, ...limits });
62
+ out(json ? JSON.stringify({ allowRemoteTerminal: allowed, allowPaseoTerminal: false }) : 'Paseo app devices can no longer open terminals on this host; the bridge ends the terminals it holds.');
63
+ return;
64
+ }
65
+ await write(home, { version: 1, allowRemoteTerminal: false, ...limits });
66
+ out(json ? JSON.stringify({ allowRemoteTerminal: false, allowPaseoTerminal: false }) : 'Remote terminals are off on this host; alpd ends every open terminal within 5 seconds.');
67
+ return;
68
+ }
69
+ if (action === 'status') {
70
+ const allowed = current.private && current.value?.version === 1 && current.value.allowRemoteTerminal === true;
71
+ const allowPaseoTerminal = allowed && current.value.allowPaseoTerminal === true;
72
+ const problem = current.exists && !current.private ? `${file(home)} is not a private file of this user, so terminals stay off` : undefined;
73
+ if (json) out(JSON.stringify({ allowRemoteTerminal: allowed, allowPaseoTerminal, ...limits, ...(problem ? { problem } : {}) }));
74
+ else out([`Remote terminals: ${allowed ? 'allowed' : 'off'}${allowPaseoTerminal ? ' (also for paired Paseo app devices)' : ''}`, ...(problem ? [problem] : []), ...(allowed ? ['', TERMINAL_WARNING()] : [])].join('\n'));
75
+ return;
76
+ }
77
+ throw new UsageError();
78
+ }
package/src/usage.js CHANGED
@@ -2,26 +2,37 @@
2
2
  import path from 'node:path';
3
3
 
4
4
  const USAGE = `Usage:
5
- alp <init|upgrade|update> [directory]
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)
7
+ alp --version
6
8
  alp setup [directory] [--runtime codex|claude|mix] [--prefer claude|codex]
7
9
  [--claude-model M] [--codex-model M] [--claude-supervisor M] [--codex-supervisor M]
8
10
  [--claude-oracle M] [--codex-oracle M] write Phở/Cafe's agent profiles to .alp/settings.json
9
11
  alp daemon <start|stop|restart>
10
12
  alp daemon status [--json] liveness and readiness; exit 0 ready, 3 not running, 4 not ready
11
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)
12
15
  alp acp serve ALP to an editor (Zed, JetBrains) over the Agent Client Protocol on stdio
13
- alp web [--print] open the local web app alpd serves; --print only prints its address
16
+ alp web [--print] open the ALP web app on this machine (alp-web, loopback); --print only prints its address
17
+ alp web serve [--service|--rotate] [--project DIR] run alp-web in this process (what alp web starts)
18
+ alp bridge <acp|antigravity> the stdio MCP bridge an agent CLI starts to reach alpd (internal)
19
+ alp web rotate give alp web a new token: open pages lose access; prints the new address
14
20
  alp web pair [--on|--off] the link that pairs Paseo's app on another device through the relay; --on or --off turns the relay on or off
21
+ alp terminal <allow [--paseo] --yes|deny [--paseo]|status> [--json] remote terminals (a shell as you on this host; a workspace is not a sandbox), off by default
15
22
  alp doctor [--project DIR] [--fix] [--json] check this machine and project; --fix repairs what is safe to
16
23
  alp backup [-o FILE] [--project DIR]... [--no-projects] [--stop] [--json] sessions, settings, library and tasks in one file
17
24
  alp backup verify <file> [--json] | alp backup list [--json]
18
25
  alp restore <file> [--home-only] [--dry-run] [--stop] [--replace-newer] [--json] checks the whole backup first; keeps what it replaces
19
26
  alpd must be stopped for both; --stop stops it and starts it again after
20
27
  alp run [--agent A] [--team pho|cafe|ID] [--model M] [--mode read-only|workspace-write|full-access] [--thinking T] [--project DIR] [--json] <prompt>
28
+ alp schedule create --session ID --at ISO_WITH_OFFSET --prompt TEXT [--project DIR] [--json]
29
+ alp schedule list [--status pending|delivered|failed|cancelled] [--project DIR] [--json]
30
+ alp schedule <show|cancel> ID [--project DIR] [--json] one-shot wake; timer gates only unblock tasks
21
31
  alp ps [--all]
22
32
  alp top [session] [--once]
23
33
  alp attach <session> [--json]
24
- alp send <session> [--json] <text>
34
+ alp send <session> [--prompt] [--json] <text>
35
+ child default: user mail; --prompt: explicit new prompt to a live root or child
25
36
  alp questions [--json]
26
37
  alp answer <question> <text> | alp answer <question> --dismiss [--reason R]
27
38
  alp log <session> [--json]
@@ -38,7 +49,7 @@ const USAGE = `Usage:
38
49
  alp mcp add <name> [--project [DIR]] (--command C [--arg A]... [--env K=V]... [--cwd D] | --url U [--header K=V]...)
39
50
  alp hook add <name> [--project [DIR]] --event E --command C [--blocking] [--timeout SEC] [--match-agent A] [--match-label L]
40
51
  alp provider add <id> --command C [--arg A]... [--env K=V]... [--label L] [-d text] [--models a,b] an ACP agent; use id antigravity for native agy
41
- alp provider edit antigravity --read-only-mode instructions|reject opt into prompt-only read-only for advisory roles
52
+ alp provider edit antigravity --read-only-mode instructions|reject legacy, no effect: agy enforces every mode itself
42
53
  alp <agent|team|skill|mcp|hook|provider> <rm|show> <name> [--project [DIR]] | <cp|mv> <from> <to> [--project [DIR]]
43
54
  alp <mcp|hook|provider> test <name> [--project [DIR]] list an MCP server's tools; run a hook once; initialize a provider
44
55
  without --project, changes go to your library in ~/.alp; built-in agents and teams are never changed
@@ -59,13 +70,17 @@ const USAGE = `Usage:
59
70
  alp verify [--project DIR] [--task ID] [--json] run the project's verify commands; --task records the result
60
71
  alp task reopen <id> [-m note]
61
72
  alp task dep <add|rm> <id> [--after ID]... [--parent ID] [--related ID]...
62
- alp task gate add <id> --human "question" | --timer +2h|ISO | --pr N|owner/repo#N | --run N|owner/repo#N
63
- alp task gate <clear|rm> <id> <gate> [-m note]
73
+ alp task gate add <id> --human "question" [--option answer]... | --timer +2h|ISO | --pr N|owner/repo#N | --run N|owner/repo#N
74
+ alp task gate clear <id> <gate> [--choice answer] [-m note] approve; main is told by mail
75
+ alp task gate reject <id> <gate> [-m reason] the gate stays open; main is told by mail
76
+ alp task gate rm <id> <gate> [-m note]
64
77
  alp pause [codex|claude] [--now] [-m reason] | alp pause status hold delegation; --now parks running assignments
65
78
  alp resume [codex|claude] lift a pause; parked assignments continue
79
+ alp models [--refresh] [--json] the models alpd offers now, from each provider (cached; refreshed every 6 h)
66
80
  alp language [name | --reset] the language agents and ALP write to you in; default Vietnamese
67
81
  alp recall <assignment|task> [--project DIR] [--json] <question> ask a finished assignment about its work
68
- alp interrupt <session>`;
82
+ alp interrupt <session>
83
+ alp compact <session>`;
69
84
 
70
85
  class UsageError extends Error {}
71
86
 
@@ -0,0 +1,187 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { lstat, readFile } from 'node:fs/promises';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { promisify } from 'node:util';
8
+ import { bootTime, isSameBoot, readLock } from '@anhlp/alp-client/index';
9
+ import { distributionEntry } from './paths.js';
10
+ import { isPackaged, selfEntry } from '@anhlp/alp-core/packaged';
11
+
12
+ /**
13
+ * The CLI's side of alp-web (packages/cli/src/web), the service behind `alp web`: where it is, which
14
+ * process owns its lock, and how to stop that process safely.
15
+ *
16
+ * Only a process proven to be the one that took `integrations/web.lock` is ever signalled, and only
17
+ * with SIGTERM (the CLI's own `--rotate` child aside, which it may time out): the lock and `web.json` name the same pid, both files are the user's, the lock is
18
+ * from this boot, the pid answers signal 0 (so it is the user's own process), and that process
19
+ * started no later than the lock was written (so the pid was not reused). Anything else is reported
20
+ * and left alone. A stopped owner releases the lock; one that died holding it leaves it to the next
21
+ * acquire, which reclaims it only on proof of death (the integration lock protocol, t-e148).
22
+ */
23
+
24
+ const execFileAsync = promisify(execFile);
25
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
26
+
27
+ /** The alp-web service script beside this CLI; a clear error when this CLI was built without it. */
28
+ export function alpWebScript() {
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.`);
32
+ return entry;
33
+ }
34
+
35
+ /** What starts alp-web: its script under Node, or the ALP executable (`alp web serve`). */
36
+ export const alpWebEntry = () => selfEntry(alpWebScript());
37
+
38
+ const readJson = async file => JSON.parse(await readFile(file, 'utf8'));
39
+
40
+ /** When `pid` started and elapsed seconds from ps, or undefined when ps cannot say. @param {number} pid */
41
+ async function processTimes(pid) {
42
+ try {
43
+ const { stdout } = await execFileAsync('ps', ['-o', 'etime=', '-p', String(pid)], { encoding: 'utf8', timeout: 5_000 });
44
+ // [[dd-]hh:]mm:ss
45
+ const match = /^\s*(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)\s*$/.exec(stdout);
46
+ if (!match) return undefined;
47
+ const [, days = '0', hours = '0', minutes, seconds] = match;
48
+ const elapsed = ((Number(days) * 24 + Number(hours)) * 60 + Number(minutes)) * 60 + Number(seconds);
49
+ return { started: Date.now() - elapsed * 1000, elapsed };
50
+ } catch { return undefined; }
51
+ }
52
+
53
+ /**
54
+ * The process that owns alp web's lock, if it is proven safe to stop; else why not. `kind` says
55
+ * whether waiting can help: `transient` (an owner still starting has not published web.json yet),
56
+ * `foreign` (proven not to be the integration: another user's, another boot's, or a reused pid) or
57
+ * `unknown` (it cannot be proven either way, for example without ps or on Windows).
58
+ *
59
+ * The reuse proof compares the lock's creation time with the process's start from ps: when
60
+ * `startedUptime` is recorded, monotonic uptime comparison prevents clock step vulnerabilities.
61
+ * For legacy locks, wall-clock `startedAt` is compared.
62
+ * @param {string} home
63
+ * @returns {Promise<{ pid: number, app: unknown } | { reason: string, alive: boolean, kind?: 'transient' | 'foreign' | 'unknown' }>}
64
+ */
65
+ export async function webOwner(home) {
66
+ const lockFile = path.join(home, 'integrations', 'web.lock');
67
+ const infoFile = path.join(home, 'web.json');
68
+ let lock, lockInfo;
69
+ try { lockInfo = await lstat(lockFile); lock = await readJson(lockFile); } catch { return { reason: `${lockFile} is missing or unreadable`, alive: false }; }
70
+ if (!lockInfo.isFile() || !Number.isSafeInteger(lock?.pid) || lock.pid <= 0 || typeof lock.bootTime !== 'number' || !Number.isFinite(Date.parse(lock.startedAt))) {
71
+ return { reason: `${lockFile} is not a complete integration lock`, alive: false };
72
+ }
73
+ const { pid } = lock;
74
+ try { process.kill(pid, 0); } catch (error) {
75
+ if (error?.code === 'ESRCH') return { reason: `its pid ${pid} has exited`, alive: false };
76
+ if (error?.code === 'EPERM') return { reason: `pid ${pid} belongs to another user`, alive: true, kind: 'foreign' };
77
+ return { reason: `pid ${pid} cannot be signalled (${error?.code ?? error})`, alive: true, kind: 'unknown' };
78
+ }
79
+ const refuse = (/** @type {string} */ reason, /** @type {'transient' | 'foreign' | 'unknown'} */ kind) => ({ reason, alive: true, kind });
80
+ if (process.platform === 'win32') return refuse('alp does not stop it on Windows', 'unknown');
81
+ const uid = process.getuid?.();
82
+ if (lockInfo.uid !== uid) return refuse('its lock is not yours', 'foreign');
83
+ if (!isSameBoot(lock)) return refuse('its lock is from another boot', 'foreign');
84
+ if (pid === process.pid || pid === (await readLock(home).catch(() => undefined))?.pid) return refuse(`pid ${pid} is not an integration`, 'foreign');
85
+ const times = await processTimes(pid);
86
+ if (times === undefined) return refuse(`the start time of pid ${pid} is unknown`, 'unknown');
87
+ // When startedUptime is recorded, monotonic uptime comparison prevents clock step vulnerabilities.
88
+ // Otherwise, fallback to wall-clock startedAt comparison with 2s tolerance for ps resolution.
89
+ const isReused = typeof lock.startedUptime === 'number'
90
+ ? (Math.floor(os.uptime()) - times.elapsed) > lock.startedUptime + 2
91
+ : times.started > Date.parse(lock.startedAt) + 2_000;
92
+ if (isReused) return refuse(`pid ${pid} started after the lock was written (a reused pid)`, 'foreign');
93
+ // The lock's owner; web.json must name it too (an owner still starting has not written it yet).
94
+ let info, infoStat;
95
+ try { infoStat = await lstat(infoFile); info = await readJson(infoFile); } catch { return refuse(`${infoFile} is missing or unreadable`, 'transient'); }
96
+ if (info?.pid !== pid) return refuse(`${infoFile} names another process than the lock`, 'transient');
97
+ if (!infoStat.isFile() || infoStat.uid !== uid) return refuse(`${infoFile} is not yours`, 'foreign');
98
+ return { pid, app: info.app };
99
+ }
100
+
101
+ /**
102
+ * Sends SIGTERM to a proven owner and waits for it to exit.
103
+ * @param {number} pid @param {string} what @param {number} [timeoutMs]
104
+ */
105
+ async function terminate(pid, what, timeoutMs = 20_000) {
106
+ try { process.kill(pid, 'SIGTERM'); } catch (error) { if (error?.code === 'ESRCH') return; throw error; }
107
+ const deadline = Date.now() + timeoutMs;
108
+ while (Date.now() < deadline) {
109
+ try { process.kill(pid, 0); } catch (error) { if (error?.code === 'ESRCH') return; }
110
+ await sleep(100);
111
+ }
112
+ throw new Error(`${what} (pid ${pid}) did not stop within ${timeoutMs / 1000} s of SIGTERM; stop it, then run the command again`);
113
+ }
114
+
115
+ /** Whether `web.json` is alp-web's own (the pre-rename Paseo integration wrote it without `app`). */
116
+ const isAlpWeb = app => app === 'alp-web';
117
+ const PASEO_BEFORE_RENAME = 'The Paseo integration from before its rename';
118
+
119
+ /**
120
+ * Stops the Paseo integration from before its rename when it still runs as integration `web` (its
121
+ * web.json has no `app: 'alp-web'`), so alp-web can take the lock and web.port. Returns the pid it
122
+ * stopped. A process that cannot be proven to be that integration is left alone.
123
+ * @param {string} home
124
+ */
125
+ export async function stopPreRenamePaseo(home) {
126
+ const owner = await webOwner(home);
127
+ if (!('pid' in owner) || isAlpWeb(owner.app)) return undefined;
128
+ await terminate(owner.pid, PASEO_BEFORE_RENAME);
129
+ return owner.pid;
130
+ }
131
+
132
+ /**
133
+ * Stops whatever runs as integration `web` (alp-web, or the Paseo integration from before its
134
+ * rename), waiting up to `timeoutMs` for a starting owner to publish what proves it. Resolves once
135
+ * no live process owns the lock; refuses at once an owner that is foreign or cannot be proven.
136
+ * @param {string} home @param {number} [timeoutMs]
137
+ */
138
+ export async function stopWebService(home, timeoutMs = 30_000) {
139
+ const deadline = Date.now() + timeoutMs;
140
+ for (;;) {
141
+ const owner = await webOwner(home);
142
+ if ('pid' in owner) { await terminate(owner.pid, isAlpWeb(owner.app) ? 'alp web' : PASEO_BEFORE_RENAME); return owner.pid; }
143
+ if (!owner.alive) return undefined;
144
+ // Only an owner still starting can become provable; waiting changes nothing else.
145
+ if (owner.kind !== 'transient' || Date.now() >= deadline) throw new Error(`${refusal(home)} (${owner.reason}); stop it, then run the command again`);
146
+ await sleep(200);
147
+ }
148
+ }
149
+
150
+ /** The opening of the message for a web lock held by a process alp would not stop. @param {string} home */
151
+ export function refusal(home) {
152
+ return `${path.join(home, 'integrations', 'web.lock')} is held by a process that alp cannot prove is alp web or the Paseo integration from before its rename, so it was left running`;
153
+ }
154
+
155
+ /**
156
+ * Probes whether the published web service URL is live and answering requests.
157
+ * Accepts only loopback HTTP/HTTPS addresses.
158
+ * @param {string | undefined} url
159
+ * @param {number} [timeoutMs]
160
+ */
161
+ export async function isWebReady(url, timeoutMs = 1_000) {
162
+ if (typeof url !== 'string' || !url) return false;
163
+ try {
164
+ const parsed = new URL(url);
165
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false;
166
+ if (!['127.0.0.1', 'localhost', '::1', '[::1]'].includes(parsed.hostname)) return false;
167
+ const res = await fetch(parsed.href, { signal: AbortSignal.timeout(timeoutMs) });
168
+ return typeof res.status === 'number' && res.status > 0;
169
+ } catch {
170
+ return false;
171
+ }
172
+ }
173
+
174
+ /**
175
+ * Whether web metadata is genuinely claimed by a live alp-web process.
176
+ * If the process is proven foreign (e.g. a reused PID or from another boot) or
177
+ * the URL does not answer HTTP requests, it is never claimed.
178
+ * @param {any} published
179
+ * @param {number | undefined} lockPid
180
+ * @param {any} held
181
+ * @param {number} [timeoutMs]
182
+ */
183
+ export async function isWebClaimed(published, lockPid, held, timeoutMs = 1_000) {
184
+ if (published?.app !== 'alp-web' || published.pid !== lockPid) return false;
185
+ if (held?.kind === 'foreign') return false;
186
+ return isWebReady(published.url, timeoutMs);
187
+ }