@anhlp/alp-cli 0.0.1-beta.3 → 0.0.1-beta.4
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/THIRD-PARTY-NOTICES.txt +25 -0
- package/dist/acp/main.js +1 -1
- package/dist/acp.js +37 -4
- package/dist/alp-web/THIRD-PARTY-NOTICES.txt +2590 -0
- package/dist/alp-web/alp-boundary.json +15 -0
- package/dist/alp-web/apple-touch-icon.png +0 -0
- package/dist/alp-web/assets/TerminalPanel-DLuoa74B.css +1 -0
- package/dist/alp-web/assets/TerminalPanel-PrU2l3u5.js +16 -0
- package/dist/alp-web/assets/index-BJdBTDFX.css +1 -0
- package/dist/alp-web/assets/index-DpfiPv5s.js +52 -0
- package/dist/alp-web/favicon-attention.svg +6 -0
- package/dist/alp-web/favicon-running.svg +6 -0
- package/dist/alp-web/favicon.svg +5 -0
- package/dist/alp-web/index.html +20 -0
- package/dist/alp-web.js +9640 -0
- package/dist/alpd.js +10350 -3346
- package/dist/backup.js +2 -2
- package/dist/build-manifest.json +99 -1
- package/dist/cli.js +4 -2
- package/dist/interfaces.d.ts +9 -1
- package/dist/interfaces.js +99 -39
- package/dist/schedules.d.ts +2 -0
- package/dist/schedules.js +45 -0
- package/dist/sessions.d.ts +3 -1
- package/dist/sessions.js +22 -11
- package/dist/terminal.d.ts +8 -0
- package/dist/terminal.js +79 -0
- package/dist/usage.d.ts +1 -1
- package/dist/usage.js +8 -2
- package/dist/web-service.d.ts +38 -0
- package/dist/web-service.js +119 -0
- package/package.json +10 -4
- package/src/backup.js +1 -1
- package/src/cli.js +3 -1
- package/src/interfaces.js +136 -31
- package/src/schedules.js +38 -0
- package/src/sessions.js +21 -11
- package/src/terminal.js +77 -0
- package/src/usage.js +8 -2
- package/src/web/grant.js +204 -0
- package/src/web/main.js +285 -0
- package/src/web/serve.js +144 -0
- package/src/web-service.js +143 -0
package/dist/usage.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export const USAGE: "Usage:\n alp <init|upgrade|update> [directory]\n alp setup [directory] [--runtime codex|claude|mix] [--prefer claude|codex]\n [--claude-model M] [--codex-model M] [--claude-supervisor M] [--codex-supervisor M]\n [--claude-oracle M] [--codex-oracle M] write Ph\u1EDF/Cafe's agent profiles to .alp/settings.json\n alp daemon <start|stop|restart>\n alp daemon status [--json] liveness and readiness; exit 0 ready, 3 not running, 4 not ready\n alp daemon <install|uninstall> run alpd as a login service that restarts after a crash\n alp acp serve ALP to an editor (Zed, JetBrains) over the Agent Client Protocol on stdio\n alp web [--print] open the
|
|
1
|
+
export const USAGE: "Usage:\n alp <init|upgrade|update> [directory]\n alp setup [directory] [--runtime codex|claude|mix] [--prefer claude|codex]\n [--claude-model M] [--codex-model M] [--claude-supervisor M] [--codex-supervisor M]\n [--claude-oracle M] [--codex-oracle M] write Ph\u1EDF/Cafe's agent profiles to .alp/settings.json\n alp daemon <start|stop|restart>\n alp daemon status [--json] liveness and readiness; exit 0 ready, 3 not running, 4 not ready\n alp daemon <install|uninstall> run alpd as a login service that restarts after a crash\n alp acp serve ALP to an editor (Zed, JetBrains) over the Agent Client Protocol on stdio\n alp web [--print] open the ALP web app on this machine (alp-web, loopback); --print only prints its address\n alp web rotate give alp web a new token: open pages lose access; prints the new address\n 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\n 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\n alp doctor [--project DIR] [--fix] [--json] check this machine and project; --fix repairs what is safe to\n alp backup [-o FILE] [--project DIR]... [--no-projects] [--stop] [--json] sessions, settings, library and tasks in one file\n alp backup verify <file> [--json] | alp backup list [--json]\n alp restore <file> [--home-only] [--dry-run] [--stop] [--replace-newer] [--json] checks the whole backup first; keeps what it replaces\n alpd must be stopped for both; --stop stops it and starts it again after\n alp run [--agent A] [--team pho|cafe|ID] [--model M] [--mode read-only|workspace-write|full-access] [--thinking T] [--project DIR] [--json] <prompt>\n alp schedule create --session ID --at ISO_WITH_OFFSET --prompt TEXT [--project DIR] [--json]\n alp schedule list [--status pending|delivered|failed|cancelled] [--project DIR] [--json]\n alp schedule <show|cancel> ID [--project DIR] [--json] one-shot wake; timer gates only unblock tasks\n alp ps [--all]\n alp top [session] [--once]\n alp attach <session> [--json]\n alp send <session> [--prompt] [--json] <text>\n child default: user mail; --prompt: explicit new prompt to a live root or child\n alp questions [--json]\n alp answer <question> <text> | alp answer <question> --dismiss [--reason R]\n alp log <session> [--json]\n alp board [--project DIR] [--json]\n alp <agents|skills|mcp|hooks> [--project DIR] [--json] the library: built-in, ~/.alp and project entries\n alp providers [--json] ACP and Antigravity providers in your library\n alp teams [--project DIR] [--json] teams sessions run in: members, delegation, house rules\n alp agent <new|edit> <name> [--project [DIR]] [--from A] [-d text] [--provider P] [--model M] [--thinking T] [--mode M]\n [--skills a,b] [--mcp a,b] [--hooks a,b] [--instructions FILE]\n alp team <new|edit> <id> [--project [DIR]] [--from ID] [--label L] [-d text] [--main A] [--member name=role]...\n [--member-model name=M]... [--member-thinking name=T]... [--delegate owner=a,b]... [--max-peers N]\n [--supervisor A] [--supervisor-model M] [--supervisor-thinking T] [--no-supervisor] [--rules FILE]\n alp skill new <name> [--project [DIR]] [--from S] [--file FILE]\n alp mcp add <name> [--project [DIR]] (--command C [--arg A]... [--env K=V]... [--cwd D] | --url U [--header K=V]...)\n alp hook add <name> [--project [DIR]] --event E --command C [--blocking] [--timeout SEC] [--match-agent A] [--match-label L]\n 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\n alp provider edit antigravity --read-only-mode instructions|reject opt into prompt-only read-only for advisory roles\n alp <agent|team|skill|mcp|hook|provider> <rm|show> <name> [--project [DIR]] | <cp|mv> <from> <to> [--project [DIR]]\n alp <mcp|hook|provider> test <name> [--project [DIR]] list an MCP server's tools; run a hook once; initialize a provider\n without --project, changes go to your library in ~/.alp; built-in agents and teams are never changed\n alp trust [--project DIR] | --revoke [--project DIR] | --list [--json] whether the project's hooks may run\n alp permissions [--project DIR] [--json] each agent's permission profile\n alp permissions check <agent> \"<command>\" what that agent's profile says about a command\n alp tasks [ready] [--all] [--status S] [--label L] [--project DIR] [--json]\n alp tasks gates [--json] open gates; checks GitHub ones\n alp tasks compact [--days 30] [--dry-run]\n alp tasks export [-o file.jsonl] as beads JSONL\n alp tasks import [file.jsonl] [--dry-run] beads JSONL; default .beads/issues.jsonl\n alp formula list | show <name> | pour <name> [--var k=v]... [--parent ID] [--dry-run]\n alp task add <title> [-d text] [-p 0-4] [-t task|bug|feature|chore|epic] [--parent ID] [--after ID]... [-l label]... [--path P]... [--from ID]\n alp task show <id> [--json]\n alp task report <epic> [--json] what an epic came to: tasks, time, rework, verification\n alp task edit <id> [--title T] [-d text] [-p N] [-t type] [-l label]... [--path P]... [-m note]\n alp task close <id> [--reason done|wontfix|duplicate|superseded] [-m summary] [--unverified \"why\"]\n alp verify [--project DIR] [--task ID] [--json] run the project's verify commands; --task records the result\n alp task reopen <id> [-m note]\n alp task dep <add|rm> <id> [--after ID]... [--parent ID] [--related ID]...\n alp task gate add <id> --human \"question\" | --timer +2h|ISO | --pr N|owner/repo#N | --run N|owner/repo#N\n alp task gate <clear|rm> <id> <gate> [-m note]\n alp pause [codex|claude] [--now] [-m reason] | alp pause status hold delegation; --now parks running assignments\n alp resume [codex|claude] lift a pause; parked assignments continue\n alp language [name | --reset] the language agents and ALP write to you in; default Vietnamese\n alp recall <assignment|task> [--project DIR] [--json] <question> ask a finished assignment about its work\n alp interrupt <session>";
|
|
2
2
|
export class UsageError extends Error {
|
|
3
3
|
}
|
package/dist/usage.js
CHANGED
|
@@ -8,18 +8,24 @@ var USAGE = `Usage:
|
|
|
8
8
|
alp daemon status [--json] liveness and readiness; exit 0 ready, 3 not running, 4 not ready
|
|
9
9
|
alp daemon <install|uninstall> run alpd as a login service that restarts after a crash
|
|
10
10
|
alp acp serve ALP to an editor (Zed, JetBrains) over the Agent Client Protocol on stdio
|
|
11
|
-
alp web [--print] open the
|
|
11
|
+
alp web [--print] open the ALP web app on this machine (alp-web, loopback); --print only prints its address
|
|
12
|
+
alp web rotate give alp web a new token: open pages lose access; prints the new address
|
|
12
13
|
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
|
|
14
|
+
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
|
|
13
15
|
alp doctor [--project DIR] [--fix] [--json] check this machine and project; --fix repairs what is safe to
|
|
14
16
|
alp backup [-o FILE] [--project DIR]... [--no-projects] [--stop] [--json] sessions, settings, library and tasks in one file
|
|
15
17
|
alp backup verify <file> [--json] | alp backup list [--json]
|
|
16
18
|
alp restore <file> [--home-only] [--dry-run] [--stop] [--replace-newer] [--json] checks the whole backup first; keeps what it replaces
|
|
17
19
|
alpd must be stopped for both; --stop stops it and starts it again after
|
|
18
20
|
alp run [--agent A] [--team pho|cafe|ID] [--model M] [--mode read-only|workspace-write|full-access] [--thinking T] [--project DIR] [--json] <prompt>
|
|
21
|
+
alp schedule create --session ID --at ISO_WITH_OFFSET --prompt TEXT [--project DIR] [--json]
|
|
22
|
+
alp schedule list [--status pending|delivered|failed|cancelled] [--project DIR] [--json]
|
|
23
|
+
alp schedule <show|cancel> ID [--project DIR] [--json] one-shot wake; timer gates only unblock tasks
|
|
19
24
|
alp ps [--all]
|
|
20
25
|
alp top [session] [--once]
|
|
21
26
|
alp attach <session> [--json]
|
|
22
|
-
alp send <session> [--json] <text>
|
|
27
|
+
alp send <session> [--prompt] [--json] <text>
|
|
28
|
+
child default: user mail; --prompt: explicit new prompt to a live root or child
|
|
23
29
|
alp questions [--json]
|
|
24
30
|
alp answer <question> <text> | alp answer <question> --dismiss [--reason R]
|
|
25
31
|
alp log <session> [--json]
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** The alp-web service script beside this CLI; a clear error when this CLI was built without it. */
|
|
2
|
+
export function alpWebEntry(): string;
|
|
3
|
+
/**
|
|
4
|
+
* The process that owns alp web's lock, if it is proven safe to stop; else why not. `kind` says
|
|
5
|
+
* whether waiting can help: `transient` (an owner still starting has not published web.json yet),
|
|
6
|
+
* `foreign` (proven not to be the integration: another user's, another boot's, or a reused pid) or
|
|
7
|
+
* `unknown` (it cannot be proven either way, for example without ps or on Windows).
|
|
8
|
+
*
|
|
9
|
+
* The reuse proof compares the lock's wall-clock `startedAt` with the process's start from ps: a
|
|
10
|
+
* wall clock stepped back by more than two seconds after the lock was written could make a reused
|
|
11
|
+
* pid look older than the lock. A step forward only refuses.
|
|
12
|
+
* @param {string} home
|
|
13
|
+
* @returns {Promise<{ pid: number, app: unknown } | { reason: string, alive: boolean, kind?: 'transient' | 'foreign' | 'unknown' }>}
|
|
14
|
+
*/
|
|
15
|
+
export function webOwner(home: string): Promise<{
|
|
16
|
+
pid: number;
|
|
17
|
+
app: unknown;
|
|
18
|
+
} | {
|
|
19
|
+
reason: string;
|
|
20
|
+
alive: boolean;
|
|
21
|
+
kind?: "transient" | "foreign" | "unknown";
|
|
22
|
+
}>;
|
|
23
|
+
/**
|
|
24
|
+
* Stops the Paseo integration from before its rename when it still runs as integration `web` (its
|
|
25
|
+
* web.json has no `app: 'alp-web'`), so alp-web can take the lock and web.port. Returns the pid it
|
|
26
|
+
* stopped. A process that cannot be proven to be that integration is left alone.
|
|
27
|
+
* @param {string} home
|
|
28
|
+
*/
|
|
29
|
+
export function stopPreRenamePaseo(home: string): Promise<number | undefined>;
|
|
30
|
+
/**
|
|
31
|
+
* Stops whatever runs as integration `web` (alp-web, or the Paseo integration from before its
|
|
32
|
+
* rename), waiting up to `timeoutMs` for a starting owner to publish what proves it. Resolves once
|
|
33
|
+
* no live process owns the lock; refuses at once an owner that is foreign or cannot be proven.
|
|
34
|
+
* @param {string} home @param {number} [timeoutMs]
|
|
35
|
+
*/
|
|
36
|
+
export function stopWebService(home: string, timeoutMs?: number): Promise<number | undefined>;
|
|
37
|
+
/** The opening of the message for a web lock held by a process alp would not stop. @param {string} home */
|
|
38
|
+
export function refusal(home: string): string;
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// packages/cli/src/web-service.js
|
|
2
|
+
import { execFile } from "node:child_process";
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { lstat, readFile } from "node:fs/promises";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { promisify } from "node:util";
|
|
8
|
+
import { bootTime, readLock } from "@anhlp/alp-client/index";
|
|
9
|
+
import { distributionEntry } from "./paths.js";
|
|
10
|
+
var execFileAsync = promisify(execFile);
|
|
11
|
+
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
12
|
+
function alpWebEntry() {
|
|
13
|
+
const entry = fileURLToPath(distributionEntry("alp-web.js"));
|
|
14
|
+
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.`);
|
|
15
|
+
return entry;
|
|
16
|
+
}
|
|
17
|
+
var readJson = async (file) => JSON.parse(await readFile(file, "utf8"));
|
|
18
|
+
async function processStart(pid) {
|
|
19
|
+
try {
|
|
20
|
+
const { stdout } = await execFileAsync("ps", ["-o", "etime=", "-p", String(pid)], { encoding: "utf8", timeout: 5e3 });
|
|
21
|
+
const match = /^\s*(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)\s*$/.exec(stdout);
|
|
22
|
+
if (!match) return void 0;
|
|
23
|
+
const [, days = "0", hours = "0", minutes, seconds] = match;
|
|
24
|
+
const elapsed = ((Number(days) * 24 + Number(hours)) * 60 + Number(minutes)) * 60 + Number(seconds);
|
|
25
|
+
return Date.now() - elapsed * 1e3;
|
|
26
|
+
} catch {
|
|
27
|
+
return void 0;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
async function webOwner(home) {
|
|
31
|
+
const lockFile = path.join(home, "integrations", "web.lock");
|
|
32
|
+
const infoFile = path.join(home, "web.json");
|
|
33
|
+
let lock, lockInfo;
|
|
34
|
+
try {
|
|
35
|
+
lockInfo = await lstat(lockFile);
|
|
36
|
+
lock = await readJson(lockFile);
|
|
37
|
+
} catch {
|
|
38
|
+
return { reason: `${lockFile} is missing or unreadable`, alive: false };
|
|
39
|
+
}
|
|
40
|
+
if (!lockInfo.isFile() || !Number.isSafeInteger(lock?.pid) || lock.pid <= 0 || typeof lock.bootTime !== "number" || !Number.isFinite(Date.parse(lock.startedAt))) {
|
|
41
|
+
return { reason: `${lockFile} is not a complete integration lock`, alive: false };
|
|
42
|
+
}
|
|
43
|
+
const { pid } = lock;
|
|
44
|
+
try {
|
|
45
|
+
process.kill(pid, 0);
|
|
46
|
+
} catch (error) {
|
|
47
|
+
if (error?.code === "ESRCH") return { reason: `its pid ${pid} has exited`, alive: false };
|
|
48
|
+
if (error?.code === "EPERM") return { reason: `pid ${pid} belongs to another user`, alive: true, kind: "foreign" };
|
|
49
|
+
return { reason: `pid ${pid} cannot be signalled (${error?.code ?? error})`, alive: true, kind: "unknown" };
|
|
50
|
+
}
|
|
51
|
+
const refuse = (reason, kind) => ({ reason, alive: true, kind });
|
|
52
|
+
if (process.platform === "win32") return refuse("alp does not stop it on Windows", "unknown");
|
|
53
|
+
const uid = process.getuid?.();
|
|
54
|
+
if (lockInfo.uid !== uid) return refuse("its lock is not yours", "foreign");
|
|
55
|
+
if (Math.abs(lock.bootTime - bootTime()) > 30) return refuse("its lock is from another boot", "foreign");
|
|
56
|
+
if (pid === process.pid || pid === (await readLock(home).catch(() => void 0))?.pid) return refuse(`pid ${pid} is not an integration`, "foreign");
|
|
57
|
+
const started = await processStart(pid);
|
|
58
|
+
if (started === void 0) return refuse(`the start time of pid ${pid} is unknown`, "unknown");
|
|
59
|
+
if (started > Date.parse(lock.startedAt) + 2e3) return refuse(`pid ${pid} started after the lock was written (a reused pid)`, "foreign");
|
|
60
|
+
let info, infoStat;
|
|
61
|
+
try {
|
|
62
|
+
infoStat = await lstat(infoFile);
|
|
63
|
+
info = await readJson(infoFile);
|
|
64
|
+
} catch {
|
|
65
|
+
return refuse(`${infoFile} is missing or unreadable`, "transient");
|
|
66
|
+
}
|
|
67
|
+
if (info?.pid !== pid) return refuse(`${infoFile} names another process than the lock`, "transient");
|
|
68
|
+
if (!infoStat.isFile() || infoStat.uid !== uid) return refuse(`${infoFile} is not yours`, "foreign");
|
|
69
|
+
return { pid, app: info.app };
|
|
70
|
+
}
|
|
71
|
+
async function terminate(pid, what, timeoutMs = 2e4) {
|
|
72
|
+
try {
|
|
73
|
+
process.kill(pid, "SIGTERM");
|
|
74
|
+
} catch (error) {
|
|
75
|
+
if (error?.code === "ESRCH") return;
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
const deadline = Date.now() + timeoutMs;
|
|
79
|
+
while (Date.now() < deadline) {
|
|
80
|
+
try {
|
|
81
|
+
process.kill(pid, 0);
|
|
82
|
+
} catch (error) {
|
|
83
|
+
if (error?.code === "ESRCH") return;
|
|
84
|
+
}
|
|
85
|
+
await sleep(100);
|
|
86
|
+
}
|
|
87
|
+
throw new Error(`${what} (pid ${pid}) did not stop within ${timeoutMs / 1e3} s of SIGTERM; stop it, then run the command again`);
|
|
88
|
+
}
|
|
89
|
+
var isAlpWeb = (app) => app === "alp-web";
|
|
90
|
+
var PASEO_BEFORE_RENAME = "The Paseo integration from before its rename";
|
|
91
|
+
async function stopPreRenamePaseo(home) {
|
|
92
|
+
const owner = await webOwner(home);
|
|
93
|
+
if (!("pid" in owner) || isAlpWeb(owner.app)) return void 0;
|
|
94
|
+
await terminate(owner.pid, PASEO_BEFORE_RENAME);
|
|
95
|
+
return owner.pid;
|
|
96
|
+
}
|
|
97
|
+
async function stopWebService(home, timeoutMs = 3e4) {
|
|
98
|
+
const deadline = Date.now() + timeoutMs;
|
|
99
|
+
for (; ; ) {
|
|
100
|
+
const owner = await webOwner(home);
|
|
101
|
+
if ("pid" in owner) {
|
|
102
|
+
await terminate(owner.pid, isAlpWeb(owner.app) ? "alp web" : PASEO_BEFORE_RENAME);
|
|
103
|
+
return owner.pid;
|
|
104
|
+
}
|
|
105
|
+
if (!owner.alive) return void 0;
|
|
106
|
+
if (owner.kind !== "transient" || Date.now() >= deadline) throw new Error(`${refusal(home)} (${owner.reason}); stop it, then run the command again`);
|
|
107
|
+
await sleep(200);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function refusal(home) {
|
|
111
|
+
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`;
|
|
112
|
+
}
|
|
113
|
+
export {
|
|
114
|
+
alpWebEntry,
|
|
115
|
+
refusal,
|
|
116
|
+
stopPreRenamePaseo,
|
|
117
|
+
stopWebService,
|
|
118
|
+
webOwner
|
|
119
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anhlp/alp-cli",
|
|
3
|
-
"version": "0.0.1-beta.
|
|
3
|
+
"version": "0.0.1-beta.4",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "ALP cli module",
|
|
6
6
|
"files": [
|
|
@@ -126,9 +126,9 @@
|
|
|
126
126
|
"node": ">=22.12"
|
|
127
127
|
},
|
|
128
128
|
"dependencies": {
|
|
129
|
-
"@anhlp/alp-core": "0.0.1-beta.
|
|
130
|
-
"@anhlp/alp-client": "0.0.1-beta.
|
|
131
|
-
"@anhlp/alp-protocol": "0.0.1-beta.
|
|
129
|
+
"@anhlp/alp-core": "0.0.1-beta.4",
|
|
130
|
+
"@anhlp/alp-client": "0.0.1-beta.4",
|
|
131
|
+
"@anhlp/alp-protocol": "0.0.1-beta.4",
|
|
132
132
|
"smol-toml": "1.9.0",
|
|
133
133
|
"@agentclientprotocol/sdk": "1.7.0",
|
|
134
134
|
"@anthropic-ai/claude-agent-sdk": "^0.3.292"
|
|
@@ -155,5 +155,11 @@
|
|
|
155
155
|
},
|
|
156
156
|
"bin": {
|
|
157
157
|
"alp": "dist/cli.js"
|
|
158
|
+
},
|
|
159
|
+
"optionalDependencies": {
|
|
160
|
+
"node-pty": "1.2.0-beta.15"
|
|
161
|
+
},
|
|
162
|
+
"devDependencies": {
|
|
163
|
+
"@anhlp/alp-gateway": "0.0.1-beta.4"
|
|
158
164
|
}
|
|
159
165
|
}
|
package/src/backup.js
CHANGED
|
@@ -123,5 +123,5 @@ export async function restoreCommand(args) {
|
|
|
123
123
|
for (const { root, reason } of result.skipped) console.log(` skipped ${root}: ${reason}`);
|
|
124
124
|
for (const warning of result.warnings) console.log(` note: ${warning}`);
|
|
125
125
|
if (result.stateSchema !== null && result.stateSchema !== undefined) console.log(' sessions that were working when the backup was made wait for you; alpd continues none by itself');
|
|
126
|
-
if (result.safety) console.log(`the data it replaced is in ${result.safety}; alp restore ${result.safety}
|
|
126
|
+
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`);
|
|
127
127
|
}
|
package/src/cli.js
CHANGED
|
@@ -8,11 +8,13 @@ import { project, permissionsCommand, trustCommand, language, verify, doctor } f
|
|
|
8
8
|
import { daemon } from './daemon.js';
|
|
9
9
|
import { run, ps, attach, send, questions, answer, top, log, board, pause, resume, recall, interrupt } from './sessions.js';
|
|
10
10
|
import { libraryCommand, editCommand, teamsCommand } from './library.js';
|
|
11
|
+
import { scheduleCommand } from './schedules.js';
|
|
11
12
|
import { tasksCommand, formulaCommand, taskCommand } from './tasks.js';
|
|
12
13
|
import { webCommand, acpCommand } from './interfaces.js';
|
|
13
14
|
import { backupCommand, restoreCommand } from './backup.js';
|
|
15
|
+
import { terminalCommand } from './terminal.js';
|
|
14
16
|
|
|
15
|
-
const commands = { setup: args => setup(args, alpHome()), init: args => project('init', args), upgrade: args => project('upgrade', args), update: args => project('upgrade', args), 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, interrupt, acp: acpCommand, web: webCommand, backup: backupCommand, restore: restoreCommand };
|
|
17
|
+
const commands = { schedule: scheduleCommand, setup: args => setup(args, alpHome()), init: args => project('init', args), upgrade: args => project('upgrade', args), update: args => project('upgrade', args), 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, interrupt, acp: acpCommand, web: webCommand, backup: backupCommand, restore: restoreCommand, terminal: terminalCommand };
|
|
16
18
|
const [command, ...args] = process.argv.slice(2);
|
|
17
19
|
try {
|
|
18
20
|
if (command === '--version') {
|
package/src/interfaces.js
CHANGED
|
@@ -1,51 +1,153 @@
|
|
|
1
|
-
import { spawn } from 'node:child_process';
|
|
2
|
-
import { readFile } from 'node:fs/promises';
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { parseArgs } from 'node:util';
|
|
5
|
-
import { alpHome,
|
|
5
|
+
import { alpHome, discoverIntegration, startIntegration } from '@anhlp/alp-client/index';
|
|
6
6
|
import { UsageError } from './usage.js';
|
|
7
7
|
import { built, start, running } from './daemon.js';
|
|
8
8
|
import { DAEMON_ENTRY, distributionEntry } from './paths.js';
|
|
9
|
+
import { alpWebEntry, refusal, stopPreRenamePaseo, stopWebService, webOwner } from './web-service.js';
|
|
9
10
|
|
|
11
|
+
/** The Paseo integration (its web app, bridge and relay) runs as integration `paseo`. */
|
|
12
|
+
const PASEO = 'paseo';
|
|
13
|
+
/** alp-web (packages/cli/src/web), the service behind `alp web`, runs as integration `web`. */
|
|
14
|
+
const WEB = 'web';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Starts the Paseo integration. For one release, a home that still has only the descriptor
|
|
18
|
+
* registered before the rename (`integrations/web.json`) keeps working, with a hint to re-register.
|
|
19
|
+
* Exported for tests.
|
|
20
|
+
* @param {string} home
|
|
21
|
+
*/
|
|
22
|
+
export async function startPaseoIntegration(home) {
|
|
23
|
+
const entry = await discoverIntegration(PASEO, { home });
|
|
24
|
+
if (!entry) {
|
|
25
|
+
const legacy = path.join(home, 'integrations', 'web.json');
|
|
26
|
+
const legacyEntry = await legacyDescriptorEntry(legacy, home);
|
|
27
|
+
if (legacyEntry) {
|
|
28
|
+
console.error(`Using the Paseo integration registered before its rename (${legacy}); run \`alp-paseo-integration --register\` to register it again.`);
|
|
29
|
+
return startIntegration({ name: PASEO, entry: legacyEntry, home });
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return startIntegration({ name: PASEO, home });
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The entry named by the pre-rename descriptor `<home>/integrations/web.json`, and nothing else: no
|
|
37
|
+
* environment, distribution or PATH lookup, since the name `web` now belongs to alp-web. A relative
|
|
38
|
+
* `main` resolves against the descriptor's directory, then the home, as discovery does.
|
|
39
|
+
* @param {string} file
|
|
40
|
+
* @param {string} home
|
|
41
|
+
*/
|
|
42
|
+
async function legacyDescriptorEntry(file, home) {
|
|
43
|
+
// A missing or corrupt descriptor is no registration: the caller then reports the missing package.
|
|
44
|
+
const raw = await readFile(file, 'utf8').then(text => JSON.parse(text)).catch(() => undefined);
|
|
45
|
+
const isFile = candidate => stat(candidate).then(info => info.isFile(), () => false);
|
|
46
|
+
// The fields discovery accepts in a descriptor, in its priority order.
|
|
47
|
+
for (const field of ['main', 'entry', 'path', 'command']) {
|
|
48
|
+
const value = raw?.[field];
|
|
49
|
+
if (typeof value !== 'string' || !value.trim()) continue;
|
|
50
|
+
const candidates = path.isAbsolute(value) ? [value] : [path.resolve(path.dirname(file), value), path.resolve(home, value)];
|
|
51
|
+
for (const candidate of candidates) if (await isFile(candidate)) return candidate;
|
|
52
|
+
}
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** `--project <cwd>` when the directory `alp web` runs in is an ALP project: its grant then covers it. */
|
|
57
|
+
async function projectArgs() {
|
|
58
|
+
const cwd = process.cwd();
|
|
59
|
+
return await stat(path.join(cwd, '.alp')).then(info => info.isDirectory(), () => false) ? ['--project', cwd] : [];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Whether settings.json turns alp web off. @param {string} home */
|
|
63
|
+
async function webDisabled(home) {
|
|
64
|
+
const settings = await readFile(path.join(home, 'settings.json'), 'utf8').then(text => JSON.parse(text), () => undefined);
|
|
65
|
+
return settings?.web?.enabled === false;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const DISABLED = 'alp web is disabled by settings ("web.enabled": false).';
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Starts alp-web unless it runs and returns the address to open, the token in its fragment (which
|
|
72
|
+
* the browser never sends to a server). The Paseo integration from before its rename, still running
|
|
73
|
+
* as integration `web`, is stopped first.
|
|
74
|
+
* @param {string} home @param {string} entry
|
|
75
|
+
*/
|
|
76
|
+
async function serveWeb(home, entry) {
|
|
77
|
+
await stopPreRenamePaseo(home);
|
|
78
|
+
// A lock held by a process proven not to be alp web: say so now rather than wait for it. A
|
|
79
|
+
// running alp-web (its web.json names the lock's pid) is left to startIntegration, whatever the
|
|
80
|
+
// proof says, so a clock step can never keep alp web from reusing it.
|
|
81
|
+
const held = await webOwner(home);
|
|
82
|
+
const published = await readFile(path.join(home, 'web.json'), 'utf8').then(text => JSON.parse(text), () => undefined);
|
|
83
|
+
const claimed = published?.app === 'alp-web' && published.pid === (await readFile(path.join(home, 'integrations', 'web.lock'), 'utf8').then(text => JSON.parse(text)?.pid, () => undefined));
|
|
84
|
+
if ('reason' in held && held.alive && held.kind === 'foreign' && !claimed) throw new Error(`${refusal(home)} (${held.reason}). Stop it, then run alp web again.`);
|
|
85
|
+
let lock;
|
|
86
|
+
try { lock = await startIntegration({ name: WEB, entry, home, args: await projectArgs() }); }
|
|
87
|
+
catch (error) {
|
|
88
|
+
// Still held by a live process alp cannot prove: name it, as the wait may have been for it.
|
|
89
|
+
const owner = await webOwner(home);
|
|
90
|
+
if ('reason' in owner && owner.alive) throw new Error(`${error?.message ?? error}\n${refusal(home)} (${owner.reason}). If it is not alp web, stop it, then run alp web again.`, { cause: error });
|
|
91
|
+
throw error;
|
|
92
|
+
}
|
|
93
|
+
const info = await readFile(path.join(home, 'web.json'), 'utf8').then(text => JSON.parse(text), () => undefined);
|
|
94
|
+
if (info?.app !== 'alp-web' || info.pid !== lock.pid) {
|
|
95
|
+
const owner = await webOwner(home);
|
|
96
|
+
throw new Error(`${refusal(home)}${'reason' in owner ? ` (${owner.reason})` : ''}. Stop pid ${lock.pid}, then run alp web again.`);
|
|
97
|
+
}
|
|
98
|
+
if (typeof info.url !== 'string' || typeof info.token !== 'string') throw new Error(`alp web published no address; see ${path.join(home, 'logs', 'integrations', 'alp-web.log')}`);
|
|
99
|
+
return `${info.url}#token=${info.token}`;
|
|
100
|
+
}
|
|
10
101
|
|
|
11
102
|
async function webCommand(args) {
|
|
12
103
|
if (args[0] === 'pair') return pairCommand(args.slice(1));
|
|
104
|
+
if (args[0] === 'rotate') return rotateCommand(args.slice(1));
|
|
13
105
|
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { print: { type: 'boolean' } } });
|
|
14
106
|
if (positionals.length) throw new UsageError();
|
|
15
|
-
const
|
|
16
|
-
await start();
|
|
17
|
-
try {
|
|
18
|
-
const settings = JSON.parse(await readFile(path.join(alpHome(),'settings.json'),'utf8'));
|
|
19
|
-
if (settings?.web?.enabled === false) throw new Error('ALP web app is disabled by settings ("web.enabled": false).');
|
|
20
|
-
} catch (error) { if (/disabled by settings/.test(error?.message ?? '')) throw error; }
|
|
21
|
-
// The web app is owned by the optional Paseo integration.
|
|
22
|
-
await startIntegration();
|
|
107
|
+
const entry = alpWebEntry();
|
|
23
108
|
const home = alpHome();
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
for (let i = 0; i < 100; i++) {
|
|
28
|
-
info = await readFile(file, 'utf8').then(JSON.parse, () => undefined);
|
|
29
|
-
let alive = false;
|
|
30
|
-
try { if (info?.pid) { process.kill(info.pid, 0); alive = true; } } catch { alive = false; }
|
|
31
|
-
let integrationPid = undefined;
|
|
32
|
-
try { integrationPid = JSON.parse(await readFile(path.join(home, 'integrations', 'web.lock'), 'utf8'))?.pid; } catch {}
|
|
33
|
-
if (info?.token && info?.url && alive && info.pid !== lock?.pid && (!integrationPid || info.pid === integrationPid)) break;
|
|
34
|
-
info = undefined;
|
|
35
|
-
await new Promise(resolve => setTimeout(resolve, 100));
|
|
36
|
-
}
|
|
37
|
-
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');
|
|
38
|
-
// The token rides in the fragment, which the browser never sends to a server.
|
|
39
|
-
const url = `${info.url}#token=${info.token}`;
|
|
109
|
+
if (await webDisabled(home)) throw new Error(DISABLED);
|
|
110
|
+
await start();
|
|
111
|
+
const url = await serveWeb(home, entry);
|
|
40
112
|
console.log(url);
|
|
41
113
|
if (values.print) return;
|
|
42
114
|
const opener = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'explorer' : 'xdg-open';
|
|
43
115
|
spawn(opener, [url], { stdio: 'ignore', detached: true }).on('error', () => console.error('Open the address above in your browser')).unref();
|
|
44
116
|
}
|
|
45
117
|
|
|
118
|
+
/**
|
|
119
|
+
* alp web rotate: alp web's token is replaced and the old one revoked, so every open page loses
|
|
120
|
+
* access. Only the process holding the web lock writes alp web's credentials, so the service is
|
|
121
|
+
* stopped first; `alp-web.js --rotate` then takes the lock, replaces the credential, records the
|
|
122
|
+
* new token in web.json and releases the lock, and the service starts again with it.
|
|
123
|
+
*/
|
|
124
|
+
async function rotateCommand(args) {
|
|
125
|
+
if (args.length) throw new UsageError();
|
|
126
|
+
const entry = alpWebEntry();
|
|
127
|
+
const home = alpHome();
|
|
128
|
+
await start();
|
|
129
|
+
const project = await projectArgs();
|
|
130
|
+
for (let attempt = 1; ; attempt++) {
|
|
131
|
+
await stopWebService(home);
|
|
132
|
+
const rotated = await new Promise(resolve => {
|
|
133
|
+
execFile(process.execPath, [entry, '--rotate', ...project], { env: { ...process.env, ALP_HOME: home }, encoding: 'utf8', timeout: 60_000, killSignal: 'SIGTERM' },
|
|
134
|
+
(error, stdout, stderr) => resolve({ code: error ? (typeof error.code === 'number' ? error.code : 1) : 0, output: `${stderr}${stdout}`.trim() }));
|
|
135
|
+
});
|
|
136
|
+
if (rotated.code === 0) break;
|
|
137
|
+
// Exit 3: alp web started again between the stop and the rotation; stop it once more.
|
|
138
|
+
if (rotated.code !== 3 || attempt >= 3) throw new Error(`alp web could not rotate its token${rotated.output ? `:\n${rotated.output.slice(-2000)}` : ''}`);
|
|
139
|
+
}
|
|
140
|
+
if (await webDisabled(home)) {
|
|
141
|
+
console.log(`alp web has a new token; the old one no longer works. ${DISABLED.replace(/\.$/, '')}, so it was not started.`);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
console.log(await serveWeb(home, entry));
|
|
145
|
+
}
|
|
146
|
+
|
|
46
147
|
/**
|
|
47
148
|
* alp web pair: the link that pairs Paseo's app on another device with alpd through Paseo's relay
|
|
48
|
-
* (ALPD §64). The device then signs in with the
|
|
149
|
+
* (ALPD §64). The device then signs in with the password this command prints (the token kept in
|
|
150
|
+
* ~/.alp/paseo.json).
|
|
49
151
|
*/
|
|
50
152
|
|
|
51
153
|
/**
|
|
@@ -72,7 +174,8 @@ async function pairCommand(args) {
|
|
|
72
174
|
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { on: { type: 'boolean' }, off: { type: 'boolean' } } });
|
|
73
175
|
if (positionals.length || (values.on && values.off)) throw new UsageError();
|
|
74
176
|
await start();
|
|
75
|
-
|
|
177
|
+
const home = alpHome();
|
|
178
|
+
await startPaseoIntegration(home);
|
|
76
179
|
const client = await running();
|
|
77
180
|
try {
|
|
78
181
|
const pairing = await requestPairing(client, values.on ? { enable: true } : values.off ? { enable: false } : {});
|
|
@@ -81,8 +184,10 @@ async function pairCommand(args) {
|
|
|
81
184
|
return;
|
|
82
185
|
}
|
|
83
186
|
console.log(`Relay ${pairing.endpoint}: ${pairing.connected ? 'connected' : 'connecting'}`);
|
|
84
|
-
console.log(`Open this link on the device
|
|
85
|
-
|
|
187
|
+
console.log(`Open this link on the device that runs Paseo's app:\n${pairing.url}`);
|
|
188
|
+
const password = await readFile(path.join(home, `${PASEO}.json`), 'utf8').then(text => JSON.parse(text)?.token).catch(() => undefined);
|
|
189
|
+
if (typeof password === 'string' && password) console.log(`When Paseo's app asks for a password, give it: ${password}`);
|
|
190
|
+
else console.log(`When Paseo's app asks for a password, give it the token in ${path.join(home, `${PASEO}.json`)}.`);
|
|
86
191
|
} finally {
|
|
87
192
|
client.close();
|
|
88
193
|
}
|
package/src/schedules.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { parseArgs } from 'node:util';
|
|
3
|
+
import { running } from './daemon.js';
|
|
4
|
+
import { UsageError } from './usage.js';
|
|
5
|
+
|
|
6
|
+
/** One-shot continuations of an existing root session; timestamps need an explicit offset. */
|
|
7
|
+
export async function scheduleCommand(args) {
|
|
8
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
|
|
9
|
+
project: { type: 'string' }, session: { type: 'string' }, at: { type: 'string' },
|
|
10
|
+
prompt: { type: 'string' }, status: { type: 'string' }, json: { type: 'boolean' },
|
|
11
|
+
} });
|
|
12
|
+
const [action, id, ...extra] = positionals;
|
|
13
|
+
if (!['create', 'list', 'show', 'cancel'].includes(action) || extra.length) throw new UsageError();
|
|
14
|
+
if ((action === 'show' || action === 'cancel') ? !id : !!id) throw new UsageError();
|
|
15
|
+
if (action !== 'create' && (values.session || values.at || values.prompt)) throw new UsageError();
|
|
16
|
+
if (action !== 'list' && values.status) throw new UsageError();
|
|
17
|
+
if (action === 'create' && (!values.session || !values.prompt?.trim() ||
|
|
18
|
+
!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:\d{2})$/.test(values.at ?? '') ||
|
|
19
|
+
!Number.isFinite(Date.parse(values.at)))) throw new Error('create needs --session, --prompt and --at ISO timestamp with Z or a UTC offset (for example 2026-10-20T16:00:00+07:00)');
|
|
20
|
+
const projectRoot = path.resolve(values.project ?? process.cwd());
|
|
21
|
+
const params = action === 'create'
|
|
22
|
+
? { projectRoot, sessionId: values.session, dueAt: values.at, prompt: values.prompt }
|
|
23
|
+
: { projectRoot, ...(id ? { id } : {}), ...(values.status ? { status: values.status } : {}) };
|
|
24
|
+
const client = await running();
|
|
25
|
+
try {
|
|
26
|
+
const result = await client.request(`schedule.${action === 'show' ? 'get' : action}`, params);
|
|
27
|
+
if (values.json) { console.log(JSON.stringify(result)); return; }
|
|
28
|
+
const jobs = result.jobs ?? [result.job];
|
|
29
|
+
if (!jobs.length) console.log('No scheduled continuations');
|
|
30
|
+
for (const job of jobs) {
|
|
31
|
+
console.log(`${job.id} ${job.status} ${job.dueAt} session ${job.sessionId}`);
|
|
32
|
+
console.log(` ${job.prompt}`);
|
|
33
|
+
if (job.attemptedAt) console.log(` attempted ${job.attemptedAt}; attempts ${job.attempts}; late ${job.lateByMs ?? 0} ms`);
|
|
34
|
+
for (const field of ['deliveredAt', 'failedAt', 'cancelledAt']) if (job[field]) console.log(` ${field}: ${job[field]}`);
|
|
35
|
+
if (job.lastError) console.log(` ${job.lastError.code ?? 'error'}: ${job.lastError.message}`);
|
|
36
|
+
}
|
|
37
|
+
} finally { client.close(); }
|
|
38
|
+
}
|
package/src/sessions.js
CHANGED
|
@@ -108,7 +108,7 @@ function answerer(client) {
|
|
|
108
108
|
|
|
109
109
|
/** Streams a tree until its root is idle; the first Ctrl-C interrupts it, the second detaches. */
|
|
110
110
|
|
|
111
|
-
function follow(client, rootId, print, { untilIdle, interactive = false }) {
|
|
111
|
+
function follow(client, rootId, print, { untilIdle, interactive = false, targetOnly = false, promptId }) {
|
|
112
112
|
const answering = interactive ? answerer(client) : undefined;
|
|
113
113
|
const done = new Promise((resolve, reject) => {
|
|
114
114
|
let failed = false;
|
|
@@ -121,9 +121,11 @@ function follow(client, rootId, print, { untilIdle, interactive = false }) {
|
|
|
121
121
|
client.request('session.interrupt', { sessionId: rootId }).catch(() => {});
|
|
122
122
|
};
|
|
123
123
|
process.on('SIGINT', onSignal);
|
|
124
|
-
client.onClose(error => { process.off('SIGINT', onSignal); reject(error); });
|
|
124
|
+
client.onClose(error => { process.off('SIGINT', onSignal); answering?.close(); reject(error); });
|
|
125
125
|
let rootEnded = false;
|
|
126
126
|
client.onEvent(envelope => {
|
|
127
|
+
if (targetOnly && envelope.sessionId !== rootId) return;
|
|
128
|
+
if (promptId && envelope.event.type === 'prompt.failed' && envelope.event.clientMessageId !== promptId) return;
|
|
127
129
|
print(envelope);
|
|
128
130
|
answering?.accept(envelope.event);
|
|
129
131
|
const { sessionId, event } = envelope;
|
|
@@ -207,28 +209,36 @@ async function attach(args) {
|
|
|
207
209
|
/** Steers a running root, prompts an idle one, or resumes a closed one; then follows it until idle. */
|
|
208
210
|
|
|
209
211
|
async function send(args) {
|
|
210
|
-
const { values, positionals: [sessionId, ...words] } = parseArgs({ args, allowPositionals: true, options: { json: { type: 'boolean' } } });
|
|
212
|
+
const { values, positionals: [sessionId, ...words] } = parseArgs({ args, allowPositionals: true, options: { json: { type: 'boolean' }, prompt: { type: 'boolean' } } });
|
|
211
213
|
const text = words.join(' ').trim();
|
|
212
214
|
if (!sessionId || !text) throw new UsageError();
|
|
213
215
|
const client = await connect(await start(), { name: 'alp-cli', version: '1' });
|
|
216
|
+
let subscriptionId;
|
|
214
217
|
try {
|
|
215
218
|
const { session } = await client.request('session.get', { sessionId });
|
|
216
|
-
if (session.parentId) {
|
|
219
|
+
if (session.parentId && !values.prompt) {
|
|
217
220
|
// An assignment gets the text as mail from the user, in its running turn.
|
|
218
221
|
await client.request('session.message', { sessionId, text });
|
|
219
222
|
if (!values.json) console.error(`Sent to ${session.agent} as mail from the user`);
|
|
220
223
|
return;
|
|
221
224
|
}
|
|
222
|
-
const done = follow(client, sessionId, printer(values.json), { untilIdle: true, interactive: !values.json && process.stdin.isTTY });
|
|
223
225
|
const live = session.status === 'idle' || session.status === 'running';
|
|
224
|
-
if (live)
|
|
225
|
-
|
|
226
|
-
const
|
|
227
|
-
|
|
228
|
-
|
|
226
|
+
if (values.prompt && !live) throw new Error('Explicit prompts require a live session; use default alp send to reopen a root');
|
|
227
|
+
const clientMessageId = randomUUID();
|
|
228
|
+
const done = follow(client, sessionId, printer(values.json), { untilIdle: true, interactive: !values.json && process.stdin.isTTY, targetOnly: !!session.parentId, promptId: clientMessageId });
|
|
229
|
+
if (live) {
|
|
230
|
+
const attached = await client.request('session.attach', { sessionId, replay: false });
|
|
231
|
+
subscriptionId = attached.session.id; // A child attaches its root for observation only.
|
|
232
|
+
} else {
|
|
233
|
+
await client.request('session.create', { sessionId, spec: { cwd: session.projectRoot } });
|
|
234
|
+
subscriptionId = sessionId;
|
|
235
|
+
}
|
|
236
|
+
const steer = !values.prompt && live && !!session.activeTurnId;
|
|
237
|
+
await client.request('session.prompt', { sessionId, clientMessageId, delivery: steer ? 'steer' : 'auto', content: [{ type: 'text', text }] });
|
|
238
|
+
if (!values.json) console.error(values.prompt ? 'Submitted an explicit prompt' : steer ? 'Steered the running turn' : live ? 'Started a turn' : 'Resumed the session');
|
|
229
239
|
if (!await done) process.exitCode = 1;
|
|
230
|
-
await client.request('session.release', { sessionId }).catch(() => {});
|
|
231
240
|
} finally {
|
|
241
|
+
if (subscriptionId) await client.request('session.release', { sessionId: subscriptionId }).catch(() => {});
|
|
232
242
|
client.close();
|
|
233
243
|
}
|
|
234
244
|
}
|