@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.
@@ -0,0 +1,160 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { initProject } from '@anhlp/alp-core/init';
3
+ import { upgradeProject } from '@anhlp/alp-core/upgrade';
4
+ import { seedLibrary } from '@anhlp/alp-core/library';
5
+ import { commandDecision, profileFor } from '@anhlp/alp-core/permissions';
6
+ import { describeVerification, runVerify, verifyConfig } from '@anhlp/alp-core/verify';
7
+ import { diagnose, repair } from '@anhlp/alp-client/doctor';
8
+ import { discoverAgents } from '@anhlp/alp-core/resolver';
9
+ import { probeAntigravity } from '@anhlp/alp-client/antigravity-probe';
10
+ import { isTrusted, revokeProject, trustProject, trustedProjects } from '@anhlp/alp-core/trust';
11
+ import { getTask, recordVerification } from '@anhlp/alp-core/tasks';
12
+ import { alpHome } from '@anhlp/alp-client/index';
13
+ import { languageSetting, setLanguage } from '@anhlp/alp-core/user-settings';
14
+ import { UsageError } from './usage.js';
15
+ import { taskProject } from './tasks.js';
16
+ import { DAEMON_ENTRY } from './paths.js';
17
+
18
+ const DOCTOR_MARK = { ok: '✓', info: '·', warn: '!', fail: '✗' };
19
+
20
+ async function project(command, args) {
21
+ if (args.length > 1) throw new UsageError();
22
+ try {
23
+ const result = await (command === 'upgrade' ? upgradeProject : initProject)(args[0] ?? process.cwd(), { library: alpHome() });
24
+ console.log(`ALP initialized: ${result.created.length} files created, ${result.preserved.length} existing files preserved.`);
25
+ const library = await seedLibrary(alpHome());
26
+ if (library.created.length || library.updated.length) console.log(`Skill library ${alpHome()}: ${library.created.length} files added, ${library.updated.length} unchanged files updated.`);
27
+ if (command === 'init' && result.updated?.length) console.log(`Template model profiles refreshed: ${result.updated.join(', ')}`);
28
+ if (command === 'upgrade') {
29
+ console.log(`ALP upgraded: ${result.updated.length} files updated.${result.backup ? ` Backup: ${result.backup}` : ''}`);
30
+ if (result.customInstructions.length) console.log(`Custom instructions preserved; reconcile with templates if needed: ${result.customInstructions.join(', ')}`);
31
+ const copies = result.removed.filter(name => /^\.alp\/agents\/[^/]+$/.test(name));
32
+ const skills = result.removed.filter(name => !copies.includes(name));
33
+ if (skills.length) console.log(`Retired skills archived: ${skills.join(', ')}`);
34
+ if (copies.length) console.log(`Unedited agent copies put away; the project now uses ALP's built-ins: ${copies.join(', ')}`);
35
+ if (result.customSkills.length) console.log(`Customized retired skills preserved for review: ${result.customSkills.join(', ')}`);
36
+ }
37
+ } catch (error) {
38
+ console.error(`ALP initialization failed: ${error.message}`);
39
+ process.exitCode = 1;
40
+ }
41
+ }
42
+
43
+ async function permissionsCommand(args) {
44
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { project: { type: 'string' }, json: { type: 'boolean' } } });
45
+ const root = await taskProject(values.project);
46
+ if (positionals[0] === 'check') {
47
+ if (positionals.length !== 3) throw new UsageError();
48
+ const profile = await profileFor(root, alpHome(), positionals[1]);
49
+ const decision = profile ? commandDecision(profile, positionals[2]) : undefined;
50
+ const result = { agent: positionals[1], profile: profile?.name ?? null, base: profile?.base ?? null, decision: decision ?? 'mode' };
51
+ if (values.json) { console.log(JSON.stringify(result)); return; }
52
+ console.log(decision === 'deny' ? `deny: a deny rule of profile ${profile.name} covers it`
53
+ : decision === 'ask' ? `ask: profile ${profile.name} asks the user each time`
54
+ : decision === 'allow' ? `allow: profile ${profile.name} lets ${result.agent} run it, even beyond its ${profile.base} mode`
55
+ : `no rule covers it: ${result.agent}'s mode decides${profile ? ` (at most ${profile.base})` : ''}`);
56
+ return;
57
+ }
58
+ if (positionals.length) throw new UsageError();
59
+ const rows = [];
60
+ for (const agent of await discoverAgents(root, { library: alpHome() })) rows.push({ agent, profile: await profileFor(root, alpHome(), agent) });
61
+ if (values.json) { console.log(JSON.stringify(rows)); return; }
62
+ for (const { agent, profile } of rows) {
63
+ console.log(profile ? `${agent} profile ${profile.name}, at most ${profile.base}${profile.beyondMode === 'ask' ? '; asks the user beyond it' : ''}` : `${agent} no profile: the mode its requester or the user chooses`);
64
+ if (profile?.allow.length) console.log(` allow: ${profile.allow.join(', ')}`);
65
+ if (profile?.ask.length) console.log(` ask: ${profile.ask.join(', ')}`);
66
+ if (profile?.deny.length) console.log(` deny: ${profile.deny.join(', ')}`);
67
+ }
68
+ }
69
+
70
+ /** Lists one library kind: where each entry comes from, what it overrides, and who uses it. */
71
+
72
+ async function trustCommand(args) {
73
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { project: { type: 'string' }, revoke: { type: 'boolean' }, list: { type: 'boolean' }, json: { type: 'boolean' } } });
74
+ if (positionals.length || (values.revoke && values.list)) throw new UsageError();
75
+ if (values.list) {
76
+ const rows = await trustedProjects(alpHome());
77
+ if (values.json) console.log(JSON.stringify(rows));
78
+ else console.log(rows.length ? rows.map(row => `${row.root} since ${row.trustedAt.slice(0, 10)} (${row.by})`).join('\n') : 'No workspace is trusted yet; ALP asks before a project\'s hooks first run.');
79
+ return;
80
+ }
81
+ const root = await taskProject(values.project);
82
+ if (values.revoke) {
83
+ const was = await revokeProject(alpHome(), root);
84
+ console.log(was ? `ALP asks again before the hooks of ${root} run.` : `${root} was not trusted.`);
85
+ return;
86
+ }
87
+ if (await isTrusted(alpHome(), root)) { console.log(`${root} is already trusted.`); return; }
88
+ await trustProject(alpHome(), root, 'alp trust');
89
+ console.log(`The hooks of ${root} now run without asking, including hooks added or changed later.`);
90
+ }
91
+
92
+ /** alp teams: each team with where it comes from, its main, members and delegation. */
93
+
94
+ async function language(args) {
95
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { reset: { type: 'boolean' }, json: { type: 'boolean' } } });
96
+ if (positionals.length > 1 || (values.reset && positionals.length)) throw new UsageError();
97
+ const state = values.reset ? await setLanguage(alpHome(), null) : positionals.length ? await setLanguage(alpHome(), positionals[0]) : await languageSetting(alpHome());
98
+ if (values.json) console.log(JSON.stringify(state));
99
+ else console.log(state.language ? `Language: ${state.language}` : `Language: ${state.applies} (the default; not set)`);
100
+ }
101
+
102
+ /** alp verify: run the project's verify commands here, in the project root. */
103
+
104
+ async function verify(args) {
105
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { project: { type: 'string' }, task: { type: 'string' }, json: { type: 'boolean' } } });
106
+ if (positionals[0] === 'antigravity') {
107
+ const result = await probeAntigravity({}, { cwd: process.cwd() });
108
+ if (values.json) console.log(JSON.stringify(result));
109
+ else console.log(`Antigravity ${result.version || 'installed'}: ok (${result.models.length} models)`);
110
+ return;
111
+ }
112
+ if (positionals.length) throw new UsageError();
113
+ const root = await taskProject(values.project);
114
+ const config = await verifyConfig(root);
115
+ if (!config) throw new Error(`${root} has no verify commands; add "verify": { "test": "npm test" } to .alp/settings.json`);
116
+ if (values.task) await getTask(root, values.task);
117
+ const verification = await runVerify(root, config);
118
+ if (values.task) await recordVerification(root, values.task, { ...verification, where: 'checkout' }, 'user');
119
+ if (values.json) console.log(JSON.stringify(verification));
120
+ else {
121
+ for (const command of verification.commands) {
122
+ console.log(`${command.exitCode === 0 ? '✓' : '✗'} ${command.step}: ${command.command} (${(command.ms / 1000).toFixed(1)} s${command.timedOut ? ', timed out' : command.exitCode ? `, exit ${command.exitCode}` : ''})`);
123
+ if (command.exitCode !== 0 && command.output) console.log(` ${command.output.trimEnd().split('\n').slice(-30).join('\n ')}`);
124
+ }
125
+ console.log(`${describeVerification(verification)}${values.task ? `; recorded on ${values.task}` : ''}`);
126
+ }
127
+ if (!verification.passed) process.exitCode = 1;
128
+ }
129
+
130
+ async function doctor(args) {
131
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { project: { type: 'string' }, fix: { type: 'boolean' }, json: { type: 'boolean' } } });
132
+ if (positionals.length) throw new UsageError();
133
+ const project = values.project ? await taskProject(values.project) : await taskProject(undefined).catch(() => undefined);
134
+ const sandbox = await import('../dist/runtime/index.js').then(runtime => runtime.claudeSandboxAvailable(), () => undefined);
135
+ const options = { home: alpHome(), project, sandbox, daemonEntry: DAEMON_ENTRY };
136
+ let checks = await diagnose(options);
137
+ const fixed = values.fix ? await repair(checks) : [];
138
+ if (fixed.length) checks = await diagnose(options);
139
+ if (values.json) {
140
+ console.log(JSON.stringify({ project: project ?? null, checks: checks.map(({ fix, ...check }) => ({ ...check, ...(fix ? { fix: fix.describe } : {}) })), fixed }));
141
+ } else {
142
+ for (const { id, result } of fixed) console.log(`fixed ${id}: ${result}`);
143
+ if (fixed.length) console.log('');
144
+ for (const check of checks) {
145
+ console.log(`${DOCTOR_MARK[check.status]} ${check.id.padEnd(13)} ${check.summary}`);
146
+ for (const detail of check.details ?? []) console.log(` ${detail}`);
147
+ if (check.fix) console.log(` --fix: ${check.fix.describe}`);
148
+ if (check.hint) console.log(` ${check.hint}`);
149
+ }
150
+ const failed = checks.filter(check => check.status === 'fail').length;
151
+ const warned = checks.filter(check => check.status === 'warn').length;
152
+ const fixable = checks.filter(check => check.fix).length;
153
+ console.log(`\n${failed || warned ? `${failed} failed, ${warned} to look at` : 'All good'}${project ? '' : ' (no ALP project here; pass --project to check one)'}${fixable ? `; alp doctor --fix repairs ${fixable}` : ''}`);
154
+ }
155
+ if (checks.some(check => check.status === 'fail')) process.exitCode = 1;
156
+ }
157
+
158
+ /** alp recall: ask a finished assignment, or the last one on a task, what it did and why. */
159
+
160
+ export { project, permissionsCommand, trustCommand, language, verify, doctor };
@@ -0,0 +1,384 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import path from 'node:path';
3
+ import { createInterface } from 'node:readline';
4
+ import { parseArgs } from 'node:util';
5
+ import { ago, duration, renderLog, renderPs } from '@anhlp/alp-client/render';
6
+ import { isTaskId } from '@anhlp/alp-core/tasks';
7
+ import { connect } from '@anhlp/alp-client/index';
8
+ import { UsageError } from './usage.js';
9
+ import { start, running, stop } from './daemon.js';
10
+ import { taskProject } from './tasks.js';
11
+
12
+ function printer(json) {
13
+ const depth = new Map();
14
+ const agents = new Map();
15
+ const printed = new Set();
16
+ const latest = new Map();
17
+ const line = (sessionId, text) => console.log(`${' '.repeat(depth.get(sessionId) ?? 0)}${text}`);
18
+ return envelope => {
19
+ if (json) { console.log(JSON.stringify(envelope)); return; }
20
+ const { sessionId, event } = envelope;
21
+ if (event.type === 'session.opened') {
22
+ const { session } = event;
23
+ depth.set(sessionId, session.parentId ? (depth.get(session.parentId) ?? 0) + 1 : 0);
24
+ agents.set(sessionId, session.agent);
25
+ line(sessionId, `▸ ${session.agent} (${session.runtime}:${session.model}, ${session.mode}) ${sessionId}`);
26
+ } else if (event.type === 'item') {
27
+ const { item } = event;
28
+ latest.set(item.id, { sessionId, item });
29
+ if (item.kind === 'tool_call' && item.status !== 'running' && !printed.has(item.id)) {
30
+ printed.add(item.id);
31
+ const detail = item.detail.type === 'shell' ? item.detail.command : item.name === 'alp_delegate' ? `delegate → ${item.detail.input?.agent}` : item.name;
32
+ line(sessionId, ` ${item.status === 'failed' ? '✗' : '✓'} ${detail}`);
33
+ }
34
+ if (item.kind === 'notice') line(sessionId, ` ${item.level === 'error' ? '‼' : item.level === 'warning' ? '!' : 'ℹ'} ${item.text}`);
35
+ if (item.kind === 'todo') {
36
+ line(sessionId, ' tasks:');
37
+ for (const entry of item.items) line(sessionId, ` ${entry.status === 'completed' ? '☑' : entry.status === 'in_progress' ? '◐' : '☐'} ${entry.text}`);
38
+ }
39
+ } else if (event.type === 'mail') {
40
+ line(sessionId, ` ✉ ${event.mail.kind} from ${event.mail.from}`);
41
+ } else if (event.type === 'question') {
42
+ const { question } = event;
43
+ line(sessionId, ` ? ${question.agent} asks you [${question.id}]: ${question.body}${question.options?.length ? ` (${question.options.join(' | ')})` : ''}`);
44
+ line(sessionId, ` answer here, or with: alp answer ${question.id} <text>`);
45
+ } else if (event.type === 'question.resolved') {
46
+ line(sessionId, ` ↳ ${event.questionId} ${event.outcome}${event.answer !== undefined ? `: ${event.answer}` : ''}`);
47
+ } else if (event.type === 'turn.ended') {
48
+ for (const [id, entry] of latest) {
49
+ if (entry.sessionId !== sessionId || printed.has(id) || entry.item.kind !== 'assistant_message') continue;
50
+ printed.add(id);
51
+ line(sessionId, ` ${agents.get(sessionId) ?? 'agent'}: ${entry.item.text.replace(/\n/g, `\n${' '.repeat((depth.get(sessionId) ?? 0) + 2)}`)}`);
52
+ }
53
+ if (event.state !== 'completed') line(sessionId, ` turn ${event.state}${event.error ? `: ${event.error.message}` : ''}`);
54
+ } else if (event.type === 'prompt.failed') {
55
+ line(sessionId, ` prompt failed: ${event.error.message}`);
56
+ } else if (event.type === 'session.failed') {
57
+ line(sessionId, ` runtime failed: ${event.error.message}`);
58
+ }
59
+ };
60
+ }
61
+
62
+ /** Reads answers to questions for the user from the terminal, one question at a time. */
63
+
64
+ function answerer(client) {
65
+ const waiting = [];
66
+ let rl;
67
+ const ask = () => {
68
+ if (rl || !waiting.length) return;
69
+ const question = waiting[0];
70
+ rl = createInterface({ input: process.stdin, output: process.stderr });
71
+ rl.question(`answer ${question.id}> `, text => {
72
+ rl.close();
73
+ rl = undefined;
74
+ waiting.shift();
75
+ // An empty line leaves the question for another client, such as Paseo or alp answer.
76
+ if (text.trim()) client.request('question.answer', { questionId: question.id, text }).catch(error => console.error(`alp: ${error.message}`));
77
+ ask();
78
+ });
79
+ };
80
+ return {
81
+ accept(event) {
82
+ if (event.type === 'question') { waiting.push(event.question); ask(); }
83
+ if (event.type === 'question.resolved') {
84
+ const index = waiting.findIndex(question => question.id === event.questionId);
85
+ if (index === 0 && rl) { rl.close(); rl = undefined; console.error(''); }
86
+ if (index >= 0) waiting.splice(index, 1);
87
+ ask();
88
+ }
89
+ },
90
+ close() { rl?.close(); rl = undefined; },
91
+ };
92
+ }
93
+
94
+ /** Streams a tree until its root is idle; the first Ctrl-C interrupts it, the second detaches. */
95
+
96
+ function follow(client, rootId, print, { untilIdle, interactive = false }) {
97
+ const answering = interactive ? answerer(client) : undefined;
98
+ const done = new Promise((resolve, reject) => {
99
+ let failed = false;
100
+ let interrupted = false;
101
+ const finish = () => { process.off('SIGINT', onSignal); answering?.close(); resolve(!failed); };
102
+ const onSignal = () => {
103
+ if (interrupted) { finish(); return; }
104
+ interrupted = true;
105
+ console.error('Interrupting… press Ctrl-C again to detach.');
106
+ client.request('session.interrupt', { sessionId: rootId }).catch(() => {});
107
+ };
108
+ process.on('SIGINT', onSignal);
109
+ client.onClose(error => { process.off('SIGINT', onSignal); reject(error); });
110
+ let rootEnded = false;
111
+ client.onEvent(envelope => {
112
+ print(envelope);
113
+ answering?.accept(envelope.event);
114
+ const { sessionId, event } = envelope;
115
+ if (event.type === 'turn.ended') {
116
+ if (sessionId === rootId) {
117
+ failed = event.state !== 'completed';
118
+ rootEnded = true;
119
+ }
120
+ if (!untilIdle || !rootEnded) return;
121
+ // The root may still have assignments, mail, or a supervisor review; it is done
122
+ // only when idle, so any turn that ends in the tree checks again.
123
+ setTimeout(() => {
124
+ client.request('session.get', { sessionId: rootId }).then(({ session }) => { if (!session.busy) finish(); }, finish);
125
+ }, 50);
126
+ return;
127
+ }
128
+ if (sessionId !== rootId) return;
129
+ if (event.type === 'turn.started') {
130
+ rootEnded = false;
131
+ } else if (event.type === 'session.closed' || event.type === 'session.failed' || event.type === 'prompt.failed') {
132
+ failed ||= event.type !== 'session.closed';
133
+ finish();
134
+ }
135
+ });
136
+ });
137
+ // A request can fail before the caller awaits this; closing the client must not crash the CLI then.
138
+ done.catch(() => {});
139
+ return done;
140
+ }
141
+
142
+ async function run(args) {
143
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
144
+ agent: { type: 'string' }, team: { type: 'string' }, profile: { type: 'string' }, workflow: { type: 'string' }, model: { type: 'string' }, mode: { type: 'string' },
145
+ thinking: { type: 'string' }, project: { type: 'string' }, json: { type: 'boolean' },
146
+ } });
147
+ const text = positionals.join(' ').trim();
148
+ if (!text) throw new UsageError();
149
+ // --profile and --workflow are the option's names before teams.
150
+ const teams = [values.team, values.profile, values.workflow].filter(Boolean);
151
+ if (new Set(teams).size > 1) throw new UsageError();
152
+ const client = await connect(await start(), { name: 'alp-cli', version: '1' });
153
+ try {
154
+ const spec = { cwd: path.resolve(values.project ?? process.cwd()), persist: true, agent: values.agent, workflow: teams[0], model: values.model, mode: values.mode, thinking: values.thinking };
155
+ const sessionId = `cli-${randomUUID()}`;
156
+ const done = follow(client, sessionId, printer(values.json), { untilIdle: true, interactive: !values.json && process.stdin.isTTY });
157
+ await client.request('session.create', { sessionId, spec });
158
+ await client.request('session.prompt', { sessionId, clientMessageId: randomUUID(), content: [{ type: 'text', text }] });
159
+ if (!await done) process.exitCode = 1;
160
+ await client.request('session.release', { sessionId }).catch(() => {});
161
+ } finally {
162
+ client.close();
163
+ }
164
+ }
165
+
166
+ async function ps(args) {
167
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { all: { type: 'boolean' } } });
168
+ if (positionals.length) throw new UsageError();
169
+ const client = await running();
170
+ const [{ sessions }, pauses] = await Promise.all([client.request('session.list', { includeClosed: values.all }), client.request('daemon.pauses')]).finally(() => client.close());
171
+ printPauses(pauses, false);
172
+ if (!sessions.length) { console.log(values.all ? 'No sessions' : 'No live sessions'); return; }
173
+ for (const line of renderPs(sessions)) console.log(line);
174
+ }
175
+
176
+ async function attach(args) {
177
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { json: { type: 'boolean' } } });
178
+ if (positionals.length !== 1) throw new UsageError();
179
+ const client = await running();
180
+ try {
181
+ const done = follow(client, positionals[0], printer(values.json), { untilIdle: false, interactive: !values.json && process.stdin.isTTY });
182
+ const { session } = await client.request('session.attach', { sessionId: positionals[0] });
183
+ if (session.id !== positionals[0]) console.error(`Following root ${session.id}`);
184
+ // A closed session has only history; resume it with alp send.
185
+ if (session.status === 'idle' || session.status === 'running') await done;
186
+ else console.error(`Session is ${session.lastError?.code ?? session.status}; resume it with: alp send ${session.id} <text>`);
187
+ } finally {
188
+ client.close();
189
+ }
190
+ }
191
+
192
+ /** Steers a running root, prompts an idle one, or resumes a closed one; then follows it until idle. */
193
+
194
+ async function send(args) {
195
+ const { values, positionals: [sessionId, ...words] } = parseArgs({ args, allowPositionals: true, options: { json: { type: 'boolean' } } });
196
+ const text = words.join(' ').trim();
197
+ if (!sessionId || !text) throw new UsageError();
198
+ const client = await connect(await start(), { name: 'alp-cli', version: '1' });
199
+ try {
200
+ const { session } = await client.request('session.get', { sessionId });
201
+ if (session.parentId) {
202
+ // An assignment gets the text as mail from the user, in its running turn.
203
+ await client.request('session.message', { sessionId, text });
204
+ if (!values.json) console.error(`Sent to ${session.agent} as mail from the user`);
205
+ return;
206
+ }
207
+ const done = follow(client, sessionId, printer(values.json), { untilIdle: true, interactive: !values.json && process.stdin.isTTY });
208
+ const live = session.status === 'idle' || session.status === 'running';
209
+ if (live) await client.request('session.attach', { sessionId, replay: false });
210
+ else await client.request('session.create', { sessionId, spec: { cwd: session.projectRoot } });
211
+ const steer = live && !!session.activeTurnId;
212
+ await client.request('session.prompt', { sessionId, clientMessageId: randomUUID(), delivery: steer ? 'steer' : 'auto', content: [{ type: 'text', text }] });
213
+ if (!values.json) console.error(steer ? 'Steered the running turn' : live ? 'Started a turn' : 'Resumed the session');
214
+ if (!await done) process.exitCode = 1;
215
+ await client.request('session.release', { sessionId }).catch(() => {});
216
+ } finally {
217
+ client.close();
218
+ }
219
+ }
220
+
221
+ async function questions(args) {
222
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { json: { type: 'boolean' } } });
223
+ if (positionals.length) throw new UsageError();
224
+ const client = await running();
225
+ const { questions: pending } = await client.request('question.list').finally(() => client.close());
226
+ if (values.json) { console.log(JSON.stringify(pending)); return; }
227
+ if (!pending.length) { console.log('No questions wait for you'); return; }
228
+ for (const question of pending) {
229
+ console.log(`${question.id} ${question.agent} ${ago(question.askedAt)} ago root ${question.rootId}`);
230
+ console.log(` ${question.body.replace(/\n/g, '\n ')}`);
231
+ if (question.options?.length) console.log(` options: ${question.options.join(' | ')}`);
232
+ }
233
+ }
234
+
235
+ async function answer(args) {
236
+ const { values, positionals: [questionId, ...words] } = parseArgs({ args, allowPositionals: true, options: { dismiss: { type: 'boolean' }, reason: { type: 'string' } } });
237
+ const text = words.join(' ').trim();
238
+ if (!questionId || (values.dismiss ? text : !text)) throw new UsageError();
239
+ const client = await running();
240
+ const result = await client.request('question.answer', values.dismiss ? { questionId, dismiss: true, reason: values.reason } : { questionId, text }).finally(() => client.close());
241
+ console.log(`${values.dismiss ? 'Dismissed' : 'Answered'} ${result.questionId}`);
242
+ }
243
+
244
+ /** One tree as text: sessions by depth, then questions, unmerged worktrees and leases. */
245
+
246
+ function renderStatus(status, root) {
247
+ const lines = [`${root?.title ? `"${root.title}" ` : ''}${status.rootId} ${status.sessions[0]?.projectRoot ?? ''}`];
248
+ const depth = new Map();
249
+ const assignments = new Map(status.assignments.map(assignment => [assignment.id, assignment]));
250
+ for (const session of status.sessions) {
251
+ depth.set(session.id, session.parentId ? (depth.get(session.parentId) ?? 0) + 1 : 0);
252
+ const assignment = assignments.get(session.id);
253
+ const where = assignment?.worktree ? ` worktree ${assignment.worktree.branch}` : '';
254
+ const mail = session.unreadMail ? ` ✉${session.unreadMail}` : '';
255
+ lines.push(`${' '.repeat(depth.get(session.id) + 1)}${session.agent.padEnd(9)} ${session.state.padEnd(14)} idle ${duration(session.idleMs).padEnd(7)} ${session.runtime}:${session.model} ${session.mode}${where}${mail}`);
256
+ }
257
+ for (const question of status.questions) lines.push(` ? ${question.id} ${question.agent} asks (${ago(question.askedAt)}): ${question.body.split('\n')[0]}`);
258
+ for (const worktree of status.worktrees) lines.push(` ⎇ unmerged ${worktree.branch} from ${worktree.agent}: ${worktree.files.length} files${worktree.stat ? ` (${worktree.stat.trim()})` : ''}`);
259
+ for (const lease of status.leases) lines.push(` ⚿ ${lease.agent} holds the write lease on ${lease.checkout}`);
260
+ for (const claim of status.claims ?? []) lines.push(` ⚑ ${claim.agent} claims ${claim.paths.join(', ')}${claim.task ? ` for ${claim.task}` : ''}: ${claim.body.split('\n')[0].slice(0, 100)}`);
261
+ return lines.join('\n');
262
+ }
263
+
264
+ /** A live dashboard of every tree, or of one, refreshed every second. */
265
+
266
+ async function top(args) {
267
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { once: { type: 'boolean' } } });
268
+ if (positionals.length > 1) throw new UsageError();
269
+ const client = await running();
270
+ const frame = async () => {
271
+ const { sessions } = await client.request('session.list', { rootsOnly: true });
272
+ const roots = positionals.length ? sessions.filter(session => session.id === positionals[0]) : sessions;
273
+ if (positionals.length && !roots.length) throw new Error(`Session ${positionals[0]} is not a live root`);
274
+ const blocks = [];
275
+ for (const root of roots) {
276
+ const { status } = await client.request('session.status', { sessionId: root.id }).catch(() => ({}));
277
+ if (status) blocks.push(renderStatus(status, root));
278
+ }
279
+ return `alp top ${new Date().toLocaleTimeString()} ${roots.length} live ${roots.length === 1 ? 'tree' : 'trees'}\n\n${blocks.join('\n\n') || 'No live sessions'}`;
280
+ };
281
+ try {
282
+ if (values.once || !process.stdout.isTTY) { console.log(await frame()); return; }
283
+ let stop = false;
284
+ process.once('SIGINT', () => { stop = true; });
285
+ while (!stop) {
286
+ const text = await frame();
287
+ process.stdout.write(`\x1b[2J\x1b[H${text}\n\n(Ctrl-C to exit)\n`);
288
+ await new Promise(resolve => setTimeout(resolve, 1000));
289
+ }
290
+ } finally {
291
+ client.close();
292
+ }
293
+ }
294
+
295
+ /** The tree's assignment log: delegations, mail, handoffs, worktrees and questions to the user. */
296
+
297
+ async function log(args) {
298
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { json: { type: 'boolean' } } });
299
+ if (positionals.length !== 1) throw new UsageError();
300
+ const client = await running();
301
+ const { rootId, entries } = await client.request('session.log', { sessionId: positionals[0] }).finally(() => client.close());
302
+ if (values.json) { for (const entry of entries) console.log(JSON.stringify(entry)); return; }
303
+ if (!entries.length) { console.log(`No assignment log for ${rootId}`); return; }
304
+ for (const line of renderLog(rootId, entries)) console.log(line);
305
+ }
306
+
307
+ /** The project board every agent on the project shares: live claims, then decisions and findings. */
308
+
309
+ async function board(args) {
310
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { project: { type: 'string' }, json: { type: 'boolean' } } });
311
+ if (positionals.length) throw new UsageError();
312
+ const projectRoot = path.resolve(values.project ?? process.cwd());
313
+ const client = await running();
314
+ const { pins } = await client.request('board.list', { projectRoot }).finally(() => client.close());
315
+ if (values.json) { console.log(JSON.stringify(pins)); return; }
316
+ if (!pins.length) { console.log(`The board for ${projectRoot} is empty`); return; }
317
+ console.log(`Project board ${projectRoot}`);
318
+ for (const pin of pins) {
319
+ const mark = pin.kind === 'claim' ? '⚑' : pin.kind === 'decision' ? '◆' : '•';
320
+ console.log(`${mark} ${pin.kind.padEnd(8)} ${pin.id} ${pin.agent} ${ago(pin.at)} ago${pin.paths ? ` [${pin.paths.join(', ')}]` : ''}`);
321
+ console.log(` ${pin.body.replace(/\n/g, '\n ')}`);
322
+ }
323
+ }
324
+
325
+ function printPauses({ all, runtimes, parked }, always = true) {
326
+ const line = (name, pause) => console.log(`⏸ ${name} paused since ${pause.since.slice(0, 16).replace('T', ' ')} by ${pause.by}: ${pause.reason}${pause.resetsAt ? `; the limit resets ${pause.resetsAt}` : ''}${pause.checkedAt ? `; ${name} last asked ${ago(pause.checkedAt)} ago` : ''}`);
327
+ if (all) line('ALP', all);
328
+ for (const [kind, pause] of Object.entries(runtimes)) line(kind, pause);
329
+ for (const entry of parked) console.log(` parked ${entry.agent} ${entry.assignmentId} (${entry.runtime}): ${entry.reason}`);
330
+ if (always && !all && !Object.keys(runtimes).length) console.log('Nothing is paused');
331
+ }
332
+
333
+ /** alp pause: hold delegation and wakes on one runtime, or all; --now also parks running assignments. */
334
+
335
+ async function pause(args) {
336
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { now: { type: 'boolean' }, message: { type: 'string', short: 'm' }, json: { type: 'boolean' } } });
337
+ if (positionals.length > 1 || (positionals[0] && !['codex', 'claude', 'status'].includes(positionals[0]))) throw new UsageError();
338
+ const client = await running();
339
+ const state = await (positionals[0] === 'status'
340
+ ? client.request('daemon.pauses')
341
+ : client.request('daemon.pause', { ...(positionals[0] ? { runtime: positionals[0] } : {}), now: !!values.now, ...(values.message ? { reason: values.message } : {}) })).finally(() => client.close());
342
+ if (values.json) console.log(JSON.stringify(state));
343
+ else printPauses(state);
344
+ }
345
+
346
+ /** alp resume: lift a pause; parked assignments continue where they stopped. */
347
+
348
+ async function resume(args) {
349
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { json: { type: 'boolean' } } });
350
+ if (positionals.length > 1 || (positionals[0] && !['codex', 'claude'].includes(positionals[0]))) throw new UsageError();
351
+ const client = await running();
352
+ const state = await client.request('daemon.resume', positionals[0] ? { runtime: positionals[0] } : {}).finally(() => client.close());
353
+ if (values.json) console.log(JSON.stringify(state));
354
+ else printPauses(state);
355
+ }
356
+
357
+ /** alp language: the language the user reads (ALPD §54); new sessions use it. */
358
+
359
+ async function recall(args) {
360
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { project: { type: 'string' }, json: { type: 'boolean' } } });
361
+ const [target, ...words] = positionals;
362
+ const question = words.join(' ').trim();
363
+ if (!target || !question) throw new UsageError();
364
+ const byTask = isTaskId(target);
365
+ const client = await running();
366
+ const answer = await client.request('assignment.recall', {
367
+ ...(byTask ? { taskId: target, projectRoot: await taskProject(values.project) } : { assignmentId: target }),
368
+ question,
369
+ }).finally(() => client.close());
370
+ if (values.json) { console.log(JSON.stringify(answer)); return; }
371
+ console.log(`${answer.agent} (assignment ${answer.assignmentId}${answer.taskId ? `, task ${answer.taskId}` : ''}, finished ${ago(answer.finishedAt)} ago):`);
372
+ console.log(answer.answer);
373
+ }
374
+
375
+ /** alp web: opens the web app alpd serves on 127.0.0.1, with the token in the address (ALPD §61). */
376
+
377
+ async function interrupt(args) {
378
+ if (args.length !== 1) throw new UsageError();
379
+ const client = await running();
380
+ await client.request('session.interrupt', { sessionId: args[0] }).finally(() => client.close());
381
+ console.log('Interrupted');
382
+ }
383
+
384
+ export { printer, answerer, follow, run, ps, attach, send, questions, answer, renderStatus, top, log, board, printPauses, pause, resume, recall, interrupt };