@anhlp/alp-cli 0.0.0-beta.1

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/src/daemon.js ADDED
@@ -0,0 +1,137 @@
1
+ import { access } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { installedProgram, installService, serviceFor, uninstallService } from '@anhlp/alp-client/service';
4
+ import { holdDaemon, startDaemon } from '@anhlp/alp-client/supervise';
5
+ import { alpHome, connect, lockAlive, readLock } from '@anhlp/alp-client/index';
6
+ import { scrubText } from '@anhlp/alp-core/log';
7
+ import { UsageError } from './usage.js';
8
+ import { DAEMON_ENTRY } from './paths.js';
9
+
10
+ async function built() {
11
+ try {
12
+ await access(DAEMON_ENTRY);
13
+ } catch {
14
+ throw new Error(`alpd is not built (${DAEMON_ENTRY}); run npm run build`);
15
+ }
16
+ }
17
+
18
+ /** Waits until an alpd for this home is ready; returns its socket. */
19
+
20
+ async function ready(timeoutMs = 15_000) {
21
+ const deadline = Date.now() + timeoutMs;
22
+ while (Date.now() < deadline) {
23
+ const lock = await readLock(alpHome());
24
+ if (lockAlive(lock) && lock.ready) return lock.socket;
25
+ await new Promise(resolve => setTimeout(resolve, 100));
26
+ }
27
+ throw new Error(`alpd did not become ready within ${timeoutMs / 1000} s; see ${path.join(alpHome(), 'logs')}`);
28
+ }
29
+
30
+ /** The installed service for this ALP_HOME, if any. */
31
+
32
+ async function installed() {
33
+ const service = serviceFor({ home: alpHome() });
34
+ return service && await installedProgram(service) ? service : undefined;
35
+ }
36
+
37
+ /** Starts alpd: through its service when installed, so the service keeps it running; else detached. */
38
+
39
+ async function start() {
40
+ await built();
41
+ return startDaemon({ home: alpHome(), entry: DAEMON_ENTRY });
42
+ }
43
+
44
+ /** Connects to a running daemon without starting one. */
45
+
46
+ async function running() {
47
+ const lock = await readLock(alpHome());
48
+ if (!lockAlive(lock) || !lock.ready) throw new Error('alpd is not running; start it with: alp daemon start');
49
+ return connect(lock.socket, { name: 'alp-cli', version: '1' });
50
+ }
51
+
52
+ async function stop() {
53
+ const home = alpHome();
54
+ const lock = await readLock(home);
55
+ if (!lockAlive(lock)) return false;
56
+ const client = await connect(lock.socket, { name: 'alp-cli', version: '1' });
57
+ await client.request('daemon.shutdown').finally(() => client.close());
58
+ for (let i = 0; i < 150 && lockAlive(await readLock(home)); i++) await new Promise(resolve => setTimeout(resolve, 100));
59
+ return true;
60
+ }
61
+
62
+ async function daemon([action, ...rest]) {
63
+ if (rest.length && !(action === 'status' && rest.length === 1 && rest[0] === '--json')) throw new UsageError();
64
+ if (action === 'start') {
65
+ const socket = await start();
66
+ const lock = await readLock(alpHome());
67
+ console.log(`alpd ${lock.version} running (pid ${lock.pid}) on ${socket}`);
68
+ } else if (action === 'stop') {
69
+ const stopped = await stop();
70
+ // On purpose: the Paseo plugin leaves it stopped until something asks for it.
71
+ await holdDaemon(alpHome());
72
+ console.log(stopped ? `alpd stopped; it stays stopped until alp daemon start, a prompt in Paseo, or ${await installed() ? 'the next login' : 'Paseo starting again'}` : 'alpd is not running');
73
+ } else if (action === 'restart') {
74
+ const client = await running().catch(() => undefined);
75
+ const status = client && await client.request('daemon.status').finally(() => client.close());
76
+ await stop();
77
+ await daemon(['start']);
78
+ // Running work is kept on stop and continued at start (ALPD §31).
79
+ if (status?.sessions) console.log(`${status.sessions} live sessions were open; alpd reopens what was still working`);
80
+ } else if (action === 'install') {
81
+ await built();
82
+ const service = serviceFor({ home: alpHome() });
83
+ if (!service) throw new Error(`alp daemon install supports macOS (launchd) and Linux (systemd), not ${process.platform}`);
84
+ // The service's alpd takes over; running work continues in it (ALPD §31).
85
+ const replaced = await stop();
86
+ await installService(service, { home: alpHome(), entry: DAEMON_ENTRY });
87
+ await ready();
88
+ const lock = await readLock(alpHome());
89
+ console.log(`alpd installed as ${service.kind === 'launchd' ? 'a LaunchAgent' : 'a systemd user service'} (${service.name}, ${service.file})`);
90
+ console.log(`alpd ${lock.version} running (pid ${lock.pid}); it starts at login and again after a crash${replaced ? '; the alpd that ran before handed its work over' : ''}`);
91
+ } else if (action === 'uninstall') {
92
+ const service = serviceFor({ home: alpHome() });
93
+ if (!service || !await uninstallService(service)) {
94
+ console.log('alpd is not installed as a service');
95
+ return;
96
+ }
97
+ // Unloading stops alpd cleanly; wait for it to let go of its lock.
98
+ for (let i = 0; i < 150 && lockAlive(await readLock(alpHome())); i++) await new Promise(resolve => setTimeout(resolve, 100));
99
+ console.log(`alpd service ${service.name} removed and alpd stopped; alp daemon start runs it without a service`);
100
+ } else if (action === 'status') {
101
+ // Exit codes: 0 ready, 3 not running, 4 alive but not ready (or not answering).
102
+ const json = rest[0] === '--json';
103
+ const lock = await readLock(alpHome());
104
+ if (!lockAlive(lock) || lock.maintenance) {
105
+ // A backup or a restore holds alpd's lock while alpd is stopped (ALPD §68).
106
+ const busy = lockAlive(lock) ? { maintenance: lock.maintenance, pid: lock.pid } : {};
107
+ if (json) console.log(JSON.stringify({ running: false, live: false, ready: false, ...busy }));
108
+ else console.log(busy.maintenance ? `alpd is not running: alp ${busy.maintenance} runs (pid ${busy.pid})` : 'alpd is not running');
109
+ process.exitCode = 3;
110
+ return;
111
+ }
112
+ const client = await connect(lock.socket, { name: 'alp-cli', version: '1' }).catch(error => {
113
+ if (json) console.log(JSON.stringify({ running: true, live: true, ready: false, pid: lock.pid, checks: [{ id: 'ipc', ok: false, code: 'ALP_IPC_FAILED', message: scrubText(error.message) }] }));
114
+ else console.log(`alpd (pid ${lock.pid}) is running but not answering on ${lock.socket}: ${scrubText(error.message)}; alp doctor says more`);
115
+ process.exitCode = 4;
116
+ });
117
+ if (!client) return;
118
+ const status = await client.request('daemon.status').finally(() => client.close());
119
+ const health = status.health ?? { live: true, ready: lock.ready === true, checks: [] };
120
+ if (json) {
121
+ console.log(JSON.stringify({ running: true, ...status, health }));
122
+ } else {
123
+ console.log(`alpd ${status.version} running (pid ${status.pid}) since ${status.startedAt}; ${status.sessions} live sessions; socket ${lock.socket}`);
124
+ console.log(health.ready ? 'ready' : `not ready: ${health.checks.filter(check => !check.ok).map(check => `${check.code ?? check.id} (${scrubText(check.message ?? 'failed')})`).join(', ') || 'starting'}`);
125
+ if (status.previousExit?.kind === 'crash') console.log(`the alpd before it stopped unexpectedly${status.previousExit.at ? ` around ${status.previousExit.at}` : ''}`);
126
+ const service = await installed();
127
+ if (service) console.log(`managed by ${service.kind} as ${service.name}`);
128
+ }
129
+ if (!health.ready) process.exitCode = 4;
130
+ } else {
131
+ throw new UsageError();
132
+ }
133
+ }
134
+
135
+ /** Human-readable event stream; one line per finished item, indented by tree depth. */
136
+
137
+ export { built, ready, installed, start, running, stop, daemon };
package/src/index.js ADDED
@@ -0,0 +1,2 @@
1
+ // CLI is exposed through the alp executable.
2
+ export const CLI_PACKAGE = '@anhlp/alp-cli';
@@ -0,0 +1,100 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { readFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { parseArgs } from 'node:util';
5
+ import { alpHome, lockAlive, readLock, startIntegration } from '@anhlp/alp-client/index';
6
+ import { UsageError } from './usage.js';
7
+ import { built, start, running } from './daemon.js';
8
+ import { DAEMON_ENTRY, distributionEntry } from './paths.js';
9
+
10
+
11
+ async function webCommand(args) {
12
+ if (args[0] === 'pair') return pairCommand(args.slice(1));
13
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { print: { type: 'boolean' } } });
14
+ if (positionals.length) throw new UsageError();
15
+ const lock = await readLock(alpHome()).catch(() => undefined);
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();
23
+ const home = alpHome();
24
+ const file = path.join(home, 'web.json');
25
+ let info;
26
+ // A fresh integration writes web.json just before it is ready; stale files from daemon or an older pid are rejected.
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}`;
40
+ console.log(url);
41
+ if (values.print) return;
42
+ const opener = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'explorer' : 'xdg-open';
43
+ spawn(opener, [url], { stdio: 'ignore', detached: true }).on('error', () => console.error('Open the address above in your browser')).unref();
44
+ }
45
+
46
+ /**
47
+ * 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 token that `alp web --print` shows.
49
+ */
50
+
51
+ /**
52
+ * `web.pairing` is an extension the integration registers on its alpd connection. Right after an
53
+ * alpd restart the old registration is gone and the new one may still be in flight, so an
54
+ * unknown-method reply means "not yet", not "never": wait for the fresh registration.
55
+ *
56
+ * Exported so the wait can be pinned by a regression test without a live daemon restart.
57
+ */
58
+ export async function requestPairing(client, params, attempts = 50) {
59
+ let last;
60
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
61
+ const outcome = await client.request('web.pairing', params).then(value => ({ value }), error => ({ error }));
62
+ if (!outcome.error) return outcome.value;
63
+ last = outcome.error;
64
+ const unknown = outcome.error?.code === -32601 || /unknown method|not available|not registered/i.test(outcome.error?.message ?? '');
65
+ if (!unknown) throw outcome.error;
66
+ await new Promise(resolve => setTimeout(resolve, 100));
67
+ }
68
+ throw last ?? new Error('alpd did not register web.pairing; run `alp web` to let the integration start, then retry');
69
+ }
70
+
71
+ async function pairCommand(args) {
72
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { on: { type: 'boolean' }, off: { type: 'boolean' } } });
73
+ if (positionals.length || (values.on && values.off)) throw new UsageError();
74
+ await start();
75
+ await startIntegration();
76
+ const client = await running();
77
+ try {
78
+ const pairing = await requestPairing(client, values.on ? { enable: true } : values.off ? { enable: false } : {});
79
+ if (!pairing.relayEnabled) {
80
+ console.log(`The relay is off${values.off ? ' now' : ''}. Turn it on with: alp web pair --on`);
81
+ return;
82
+ }
83
+ console.log(`Relay ${pairing.endpoint}: ${pairing.connected ? 'connected' : 'connecting'}`);
84
+ console.log(`Open this link on the device, or scan the QR code in the web app (Settings → host → Pair device):\n${pairing.url}`);
85
+ console.log("When Paseo's app asks for a password, give it alpd's token: the part after #token= in alp web --print.");
86
+ } finally {
87
+ client.close();
88
+ }
89
+ }
90
+
91
+ /** alp acp: ALP as an ACP agent for editors; stdout carries only the protocol (ALPD §60). */
92
+
93
+ async function acpCommand(args) {
94
+ if (args.length) throw new UsageError();
95
+ await built();
96
+ const { runAcp } = await import(distributionEntry('acp.js'));
97
+ await runAcp({ daemonEntry: DAEMON_ENTRY });
98
+ }
99
+
100
+ export { webCommand, pairCommand, acpCommand };
package/src/library.js ADDED
@@ -0,0 +1,243 @@
1
+ import { access, readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { seedLibrary } from '@anhlp/alp-core/library';
5
+ import { libraryEntries } from '@anhlp/alp-core/resolver';
6
+ import { listTeams, resolveTeam } from '@anhlp/alp-core/teams';
7
+ import { deleteEntry, duplicateEntry, getEntry, renameEntry, saveEntry } from '@anhlp/alp-core/library-edit';
8
+ import { testEntry } from '@anhlp/alp-client/library-test';
9
+ import { alpHome } from '@anhlp/alp-client/index';
10
+ import { UsageError } from './usage.js';
11
+ import { taskProject } from './tasks.js';
12
+
13
+ async function libraryCommand(kind, args) {
14
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { project: { type: 'string' }, json: { type: 'boolean' } } });
15
+ if (positionals.length) throw new UsageError();
16
+ if (kind === 'providers') await seedLibrary(alpHome());
17
+ // Outside a project only the built-ins and the library apply.
18
+ const root = path.resolve(values.project ?? process.cwd());
19
+ const rows = await libraryEntries(kind, root, { library: alpHome() });
20
+ if (values.json) { console.log(JSON.stringify(rows)); return; }
21
+ if (!rows.length) { console.log(kind === 'providers' ? `No providers in ${path.join(alpHome(), kind)}; add an ACP agent with alp provider add` : `No ${kind} in ${path.join(alpHome(), kind)} or ${path.join(root, '.alp', kind)}`); return; }
22
+ const width = Math.max(...rows.map(row => row.name.length));
23
+ for (const row of rows) {
24
+ const where = row.source === 'builtin' ? 'built-in' : row.source;
25
+ const notes = [
26
+ row.overrides ? `overrides the ${row.overrides === 'builtin' ? 'built-in' : row.overrides} one` : '',
27
+ row.usedBy ? `used by ${row.usedBy.join(', ')}` : '',
28
+ row.description ?? '',
29
+ ].filter(Boolean);
30
+ console.log(`${row.name.padEnd(width)} ${where.padEnd(8)}${notes.length ? ` ${notes.join('; ')}` : ''}`);
31
+ }
32
+ }
33
+
34
+ /** `--project` may stand alone, meaning the current directory. */
35
+
36
+ function projectFlag(args) {
37
+ const result = [...args];
38
+ for (let i = 0; i < result.length; i++) if (result[i] === '--project' && (i + 1 === result.length || result[i + 1].startsWith('-'))) result.splice(i + 1, 0, '.');
39
+ return result;
40
+ }
41
+
42
+ const pairs = (list, what) => Object.fromEntries((list ?? []).map(item => {
43
+ const at = item.indexOf('=');
44
+ if (at <= 0) throw new Error(`${what} takes name=value, not '${item}'`);
45
+ return [item.slice(0, at), item.slice(at + 1)];
46
+ }));
47
+
48
+ const names = text => text === undefined ? undefined : text.split(',').map(name => name.trim()).filter(Boolean);
49
+
50
+ const EDIT_OPTIONS = {
51
+ project: { type: 'string' }, json: { type: 'boolean' }, from: { type: 'string' }, description: { type: 'string', short: 'd' },
52
+ // agent
53
+ provider: { type: 'string' }, model: { type: 'string' }, thinking: { type: 'string' }, mode: { type: 'string' },
54
+ skills: { type: 'string' }, mcp: { type: 'string' }, hooks: { type: 'string' }, instructions: { type: 'string' },
55
+ // team
56
+ label: { type: 'string' }, main: { type: 'string' }, member: { type: 'string', multiple: true }, 'member-model': { type: 'string', multiple: true },
57
+ 'member-thinking': { type: 'string', multiple: true }, delegate: { type: 'string', multiple: true }, 'max-peers': { type: 'string' },
58
+ supervisor: { type: 'string' }, 'supervisor-model': { type: 'string' }, 'supervisor-thinking': { type: 'string' }, 'no-supervisor': { type: 'boolean' }, rules: { type: 'string' },
59
+ // skill, mcp, hook
60
+ file: { type: 'string' }, command: { type: 'string' }, arg: { type: 'string', multiple: true }, env: { type: 'string', multiple: true }, cwd: { type: 'string' },
61
+ url: { type: 'string' }, header: { type: 'string', multiple: true }, event: { type: 'string' }, blocking: { type: 'boolean' }, timeout: { type: 'string' },
62
+ 'match-agent': { type: 'string' }, 'match-label': { type: 'string' },
63
+ // provider
64
+ kind: { type: 'string' },
65
+ 'read-only-mode': { type: 'string' },
66
+ models: { type: 'string' },
67
+ };
68
+
69
+ /** The content of an entry after a CLI new or edit: the current content with the options applied. */
70
+
71
+ async function edited(kind, name, current, values) {
72
+ const content = structuredClone(current ?? {});
73
+ const set = (target, key, value) => { if (value !== undefined) { if (value === '') delete target[key]; else target[key] = value; } };
74
+ if (kind === 'agents') {
75
+ if (values.instructions !== undefined) content.instructions = await readFile(values.instructions, 'utf8');
76
+ content.instructions ??= `# ${name}\n\nDescribe what this agent does, and how.\n`;
77
+ const config = content.config ?? {};
78
+ set(config, 'description', values.description);
79
+ for (const key of ['provider', 'model', 'thinking', 'mode']) set(config, key, values[key]);
80
+ for (const key of ['skills', 'mcp', 'hooks']) { const list = names(values[key]); if (list) { if (list.length) config[key] = list; else delete config[key]; } }
81
+ content.config = config;
82
+ } else if (kind === 'teams') {
83
+ const team = content.team ?? { label: name, main: 'main', members: { main: {} }, delegation: {} };
84
+ set(team, 'label', values.label);
85
+ set(team, 'description', values.description);
86
+ if (values.main !== undefined && values.main !== team.main) {
87
+ // The old main leaves the team with its place in the graph.
88
+ delete team.members[team.main];
89
+ delete team.delegation[team.main];
90
+ team.main = values.main;
91
+ team.members[values.main] = { ...(team.members[values.main] ?? {}) };
92
+ delete team.members[values.main].role;
93
+ }
94
+ if (values.member?.length) {
95
+ const roles = pairs(values.member, '--member');
96
+ team.members = { [team.main]: team.members[team.main] ?? {}, ...Object.fromEntries(Object.entries(roles).filter(([member]) => member !== team.main).map(([member, role]) => [member, { ...(team.members[member] ?? {}), role }])) };
97
+ }
98
+ for (const [option, key] of [['member-model', 'model'], ['member-thinking', 'thinking']]) {
99
+ for (const [member, value] of Object.entries(pairs(values[option], `--${option}`))) {
100
+ if (!team.members[member]) throw new Error(`--${option}: ${member} is not a member of ${name}`);
101
+ set(team.members[member], key, value);
102
+ }
103
+ }
104
+ if (values.delegate?.length) team.delegation = Object.fromEntries(Object.entries(pairs(values.delegate, '--delegate')).map(([owner, targets]) => [owner, names(targets)]));
105
+ if (values['max-peers'] !== undefined) { if (values['max-peers'] === '') delete team.maxPeers; else team.maxPeers = Number(values['max-peers']); }
106
+ if (values['no-supervisor']) team.supervisor = false;
107
+ else if (values.supervisor !== undefined || values['supervisor-model'] !== undefined || values['supervisor-thinking'] !== undefined) {
108
+ const watcher = team.supervisor || { agent: 'supervisor' };
109
+ set(watcher, 'agent', values.supervisor);
110
+ set(watcher, 'model', values['supervisor-model']);
111
+ set(watcher, 'thinking', values['supervisor-thinking']);
112
+ team.supervisor = watcher;
113
+ }
114
+ content.team = team;
115
+ if (values.rules !== undefined) content.houseRules = await readFile(values.rules, 'utf8');
116
+ } else if (kind === 'skills') {
117
+ if (values.file !== undefined) content.body = await readFile(values.file, 'utf8');
118
+ content.body ??= `---\nname: ${name}\ndescription: When to use this skill.\n---\n\n# ${name}\n\nSteps and checks.\n`;
119
+ } else if (kind === 'mcp') {
120
+ if (values.command !== undefined || values.url !== undefined) content.server = {};
121
+ const server = content.server ?? {};
122
+ set(server, 'command', values.command);
123
+ if (values.arg?.length) server.args = values.arg;
124
+ if (values.env?.length) server.env = pairs(values.env, '--env');
125
+ set(server, 'cwd', values.cwd);
126
+ set(server, 'url', values.url);
127
+ if (values.header?.length) server.headers = pairs(values.header, '--header');
128
+ content.server = server;
129
+ } else if (kind === 'hooks') {
130
+ const hook = content.hook ?? {};
131
+ set(hook, 'description', values.description);
132
+ set(hook, 'event', values.event);
133
+ set(hook, 'command', values.command);
134
+ if (values.blocking !== undefined) hook.blocking = values.blocking;
135
+ if (values.timeout !== undefined) hook.timeoutSec = Number(values.timeout);
136
+ if (values['match-agent'] !== undefined || values['match-label'] !== undefined) {
137
+ const match = hook.match ?? {};
138
+ set(match, 'agent', values['match-agent']);
139
+ set(match, 'label', values['match-label']);
140
+ if (Object.keys(match).length) hook.match = match; else delete hook.match;
141
+ }
142
+ content.hook = hook;
143
+ } else if (kind === 'providers') {
144
+ const isAntigravity = name === 'antigravity' || values.kind === 'antigravity';
145
+ const provider = content.provider ?? { kind: isAntigravity ? 'antigravity' : 'acp' };
146
+ if (values.kind !== undefined) provider.kind = values.kind;
147
+ if (isAntigravity) {
148
+ if (provider.command === undefined && values.command === undefined) provider.command = 'agy';
149
+ if (provider.label === undefined && values.label === undefined) provider.label = 'Antigravity';
150
+ }
151
+ set(provider, 'label', values.label);
152
+ set(provider, 'description', values.description);
153
+ set(provider, 'command', values.command);
154
+ set(provider, 'readOnlyMode', values['read-only-mode']);
155
+ if (values.arg?.length) provider.args = values.arg;
156
+ if (values.env?.length) provider.env = pairs(values.env, '--env');
157
+ const models = names(values.models);
158
+ if (models) { if (models.length) provider.models = models.map(id => provider.models?.find(model => model.id === id) ?? { id }); else delete provider.models; }
159
+ content.provider = provider;
160
+ }
161
+ return content;
162
+ }
163
+
164
+ /** alp agent|team|skill|mcp|hook: create, change, copy, rename, remove and test library entries. */
165
+
166
+ async function editCommand(kind, args) {
167
+ const { values, positionals } = parseArgs({ args: projectFlag(args), allowPositionals: true, options: EDIT_OPTIONS });
168
+ const [action, name, target] = positionals;
169
+ if (kind === 'providers' && action !== 'add') await seedLibrary(alpHome());
170
+ const creates = { agents: 'new', teams: 'new', skills: 'new', mcp: 'add', hooks: 'add', providers: 'add' }[kind];
171
+ if (!name || positionals.length > (['cp', 'mv'].includes(action) ? 3 : 2) || (['cp', 'mv'].includes(action) && !target)) throw new UsageError();
172
+ const scope = values.project !== undefined ? 'project' : 'library';
173
+ let root = values.project !== undefined ? path.resolve(values.project) : undefined;
174
+ if (scope === 'project') await taskProject(root);
175
+ // A library edit still sees the current project, for what it uses.
176
+ root ??= await access(path.join(process.cwd(), '.alp')).then(() => process.cwd(), () => undefined);
177
+ const options = { scope, root, library: alpHome() };
178
+ const done = (result, line) => console.log(values.json ? JSON.stringify(result) : line);
179
+ const where = scope === 'project' ? `the project ${root}` : `your library ${alpHome()}`;
180
+ if (action === 'show') {
181
+ const entry = await getEntry(kind, name, { root, library: alpHome(), ...(values.project !== undefined ? { scope } : {}) });
182
+ if (values.json) { console.log(JSON.stringify(entry)); return; }
183
+ console.log(`${name} ${entry.source === 'builtin' ? 'built-in' : entry.source}${entry.overrides ? `, overrides the ${entry.overrides === 'builtin' ? 'built-in' : entry.overrides} one` : ''}${entry.usedBy.length ? `; used by ${entry.usedBy.join(', ')}` : ''}`);
184
+ for (const [key, value] of Object.entries(entry.content)) console.log(`--- ${key}\n${typeof value === 'string' ? value.trimEnd() : JSON.stringify(value, null, 2)}`);
185
+ return;
186
+ }
187
+ if (action === 'rm') { const result = await deleteEntry(kind, name, options); done(result, `Removed ${name} from ${where}${result.now ? `; the ${result.now === 'builtin' ? 'built-in' : result.now} one applies again` : ''}.`); return; }
188
+ if (action === 'mv') { done(await renameEntry(kind, name, target, options), `Renamed ${name} to ${target} in ${where}.`); return; }
189
+ if (action === 'cp') { done(await duplicateEntry(kind, name, target, options), `Copied ${name} to ${target} in ${where}.`); return; }
190
+ if (action === 'test') {
191
+ if (!['mcp', 'hooks', 'providers'].includes(kind)) throw new UsageError();
192
+ const result = await testEntry(kind, name, { root, library: alpHome(), ...(values.project !== undefined ? { scope } : {}) });
193
+ if (values.json) console.log(JSON.stringify(result));
194
+ else if (kind === 'providers') {
195
+ if (result.agent?.name === 'antigravity') {
196
+ console.log(`${name}: ${result.agent?.title ?? 'Antigravity'} ${result.agent?.version ?? ''} (models: ${result.models?.length ?? 0}, mode: ${result.currentMode ?? 'full-access'})`);
197
+ } else {
198
+ console.log(`${name}: ${result.agent?.title ?? result.agent?.name ?? 'agent'} ${result.agent?.version ?? ''} speaks ACP ${result.protocolVersion}; ${result.loadSession ? 'resumes sessions' : 'cannot resume sessions'}${result.mcpHttp ? '; takes HTTP MCP servers' : ''}${result.authMethods?.length ? `; signs in with ${result.authMethods.join(', ')}` : ''}`);
199
+ }
200
+ }
201
+ else if (kind === 'mcp') console.log(`${name}: ${result.server?.name ?? 'server'} ${result.server?.version ?? ''} offers ${result.tools.length} tools${result.tools.length ? `:\n${result.tools.map(tool => ` ${tool.name}${tool.description ? ` ${tool.description.split('\n')[0]}` : ''}`).join('\n')}` : ''}`);
202
+ else console.log(`${name}: ${result.timedOut ? 'timed out' : `exit ${result.exitCode ?? result.signal}`} in ${result.durationMs} ms${result.wouldBlock ? '; as a blocking hook it would refuse the action' : ''}${result.stdout.trim() ? `\nstdout: ${result.stdout.trim()}` : ''}${result.stderr.trim() ? `\nstderr: ${result.stderr.trim()}` : ''}`);
203
+ if (!result.ok) process.exitCode = 1;
204
+ return;
205
+ }
206
+ if (action !== creates && action !== 'edit') throw new UsageError();
207
+ let current;
208
+ let revision = null;
209
+ if (action === creates) {
210
+ if (values.from !== undefined) current = (await getEntry(kind, values.from, { root, library: alpHome() })).content;
211
+ } else {
212
+ // Editing an entry that only a lower layer has makes this scope's copy of it.
213
+ const entry = await getEntry(kind, name, { root, library: alpHome() }).catch(error => { if (error.code === 'NOT_FOUND') throw new Error(`No ${kind} entry '${name}'; create it with alp ${kind.replace(/s$/, '')} ${creates}`); throw error; });
214
+ const own = await getEntry(kind, name, { root, library: alpHome(), scope }).catch(() => undefined);
215
+ current = (own ?? entry).content;
216
+ revision = own ? own.revision : null;
217
+ }
218
+ const result = await saveEntry(kind, name, await edited(kind, name, current, values), { ...options, revision });
219
+ done(result, `${action === 'edit' ? 'Saved' : 'Created'} ${name} in ${where}.`);
220
+ }
221
+
222
+ /** alp trust: the workspaces whose hooks run without asking (ALPD §45). */
223
+
224
+ async function teamsCommand(args) {
225
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { project: { type: 'string' }, json: { type: 'boolean' } } });
226
+ if (positionals.length) throw new UsageError();
227
+ const root = path.resolve(values.project ?? process.cwd());
228
+ const options = { library: alpHome() };
229
+ const rows = [];
230
+ for (const row of await listTeams(root, options)) rows.push(row.error ? row : { ...row, team: await resolveTeam(root, row.id, options) });
231
+ if (values.json) { console.log(JSON.stringify(rows.map(({ team, ...row }) => ({ ...row, ...(team ? { main: team.main, members: team.members, delegation: team.delegation, maxPeers: team.maxPeers, supervisor: team.supervisor } : {}) })))); return; }
232
+ for (const { team, ...row } of rows) {
233
+ const where = row.source === 'builtin' ? 'built-in' : row.source;
234
+ console.log(`${row.id} ${row.label ?? ''} ${where}${row.overrides ? `, overrides the ${row.overrides === 'builtin' ? 'built-in' : row.overrides} one` : ''}`);
235
+ if (row.error) { console.log(` error: ${row.error}`); continue; }
236
+ const member = (name, { role, model, thinking }) => `${name}${role ? ` (${role})` : ' (main)'}${model ? ` on ${model}${thinking ? `, ${thinking}` : ''}` : ''}`;
237
+ console.log(` members: ${Object.entries(team.members).map(([name, value]) => member(name, value)).join(', ')}`);
238
+ console.log(` delegation: ${Object.entries(team.delegation).map(([owner, targets]) => `${owner} → ${targets.join(', ')}`).join('; ') || 'none'}`);
239
+ console.log(` supervisor: ${team.supervisor ? member(team.supervisor.agent, { role: 'watches main', model: team.supervisor.model, thinking: team.supervisor.thinking }) : 'none'}${team.maxPeers ? `; at most ${team.maxPeers} peers` : ''}`);
240
+ }
241
+ }
242
+
243
+ export { libraryCommand, projectFlag, pairs, names, EDIT_OPTIONS, edited, editCommand, teamsCommand };
package/src/paths.js ADDED
@@ -0,0 +1,16 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { fileURLToPath, pathToFileURL } from 'node:url';
3
+ import path from 'node:path';
4
+
5
+ /** Locate artifacts in either the independently shipped CLI or the legacy root build. */
6
+ export function distributionEntry(name) {
7
+ const entry = process.argv[1] && path.basename(process.argv[1]) === 'cli.js' ? pathToFileURL(path.resolve(process.argv[1])) : undefined;
8
+ const candidates = [
9
+ ...(entry ? [new URL(`../dist/${name}`, entry)] : []),
10
+ new URL(`../dist/${name}`, import.meta.url),
11
+ new URL(`../../../dist/${name}`, import.meta.url),
12
+ ];
13
+ return candidates.find(candidate => existsSync(candidate)) ?? candidates[0];
14
+ }
15
+
16
+ export const DAEMON_ENTRY = fileURLToPath(distributionEntry('alpd.js'));