@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,428 @@
1
+ import * as acp from '@agentclientprotocol/sdk';
2
+ import { randomUUID } from 'node:crypto';
3
+ import path from 'node:path';
4
+ import type { DaemonConnection } from '@anhlp/alp-protocol/connection';
5
+ import type { Envelope, HostMcpServer, SessionPreview, TimelineItem, UserQuestion } from '@anhlp/alp-protocol';
6
+
7
+ /**
8
+ * ALP as an ACP agent (ALPD §60): an editor such as Zed starts `alp acp` and speaks
9
+ * the Agent Client Protocol on stdio. Each ACP session is a root in alpd; this process
10
+ * only translates, as the Paseo plugin does. A session opens in alpd on its first
11
+ * prompt, so the user can choose its team first; its tree keeps working in alpd after
12
+ * the editor goes away, and session/load picks it up again.
13
+ */
14
+
15
+ export type AcpAgentOptions = {
16
+ /** Opens a connection to alpd, starting it when needed. */
17
+ connect(): Promise<DaemonConnection>;
18
+ version: string;
19
+ /** Where diagnostics go; stdout belongs to the protocol. */
20
+ log?: (message: string, fields?: { code?: string; error?: unknown }) => void;
21
+ };
22
+
23
+ type Team = SessionPreview['teams'][number];
24
+
25
+ type Session = {
26
+ id: string;
27
+ cwd: string;
28
+ mcpServers: Record<string, HostMcpServer>;
29
+ preview: SessionPreview;
30
+ /** Open in alpd: the team is fixed from then on. */
31
+ opened: boolean;
32
+ /** Prompts this connection sent, which the editor already shows. */
33
+ ours: Set<string>;
34
+ /** Assistant text sent so far, per item, so only what is new goes out. */
35
+ texts: Map<string, string>;
36
+ /** Tool calls announced, so later states go out as updates. */
37
+ tools: Set<string>;
38
+ /** Questions to the user that wait in this tree. */
39
+ questions: Map<string, UserQuestion>;
40
+ /** Updates go out in order; a prompt answers after its updates. */
41
+ queue: Promise<void>;
42
+ /** The prompt waiting for its turn to end. */
43
+ waiting?: { clientMessageId: string; turnId?: string; done(result: { state: 'completed' | 'failed' | 'canceled'; error?: string }): void };
44
+ };
45
+
46
+ const MODES = [
47
+ { id: 'read-only', name: 'Read only', description: 'Agents read and search; nothing is changed' },
48
+ { id: 'workspace-write', name: 'Workspace write', description: 'Agents change files and run commands inside the project' },
49
+ { id: 'full-access', name: 'Full access', description: 'Agents may do anything, without a sandbox' },
50
+ ];
51
+
52
+ /** How much of a command's output a tool call shows. */
53
+ const OUTPUT_CHARS = 20_000;
54
+
55
+ const COMMANDS: acp.AvailableCommand[] = [
56
+ { name: 'answer', description: 'Answer the question an agent asked you', input: { hint: 'your answer' } },
57
+ { name: 'dismiss', description: 'Dismiss the question an agent asked you', input: { hint: 'why (optional)' } },
58
+ ];
59
+
60
+ /** ACP's MCP servers, as ALP hosts them beside the agents' own. */
61
+ export function hostServers(servers: acp.McpServer[] = []): Record<string, HostMcpServer> {
62
+ const host: Record<string, HostMcpServer> = {};
63
+ for (const server of servers) {
64
+ if ('command' in server) host[server.name] = { type: 'stdio', command: server.command, args: server.args, env: Object.fromEntries(server.env.map(variable => [variable.name, variable.value])) };
65
+ else if (server.type === 'http' || server.type === 'sse') host[server.name] = { type: server.type, url: server.url, headers: Object.fromEntries(server.headers.map(header => [header.name, header.value])) };
66
+ }
67
+ return host;
68
+ }
69
+
70
+ /** A prompt's content as the text ALP gives the agent: files the editor attaches are named or inlined. */
71
+ export function promptText(blocks: acp.ContentBlock[]) {
72
+ let text = '';
73
+ for (const block of blocks) {
74
+ if (block.type === 'text') { text += block.text; continue; }
75
+ let part = '';
76
+ if (block.type === 'resource_link') part = `@${block.uri.replace(/^file:\/\//, '')}`;
77
+ else if (block.type === 'resource') {
78
+ const { resource } = block;
79
+ const where = resource.uri.replace(/^file:\/\//, '');
80
+ part = 'text' in resource ? `\n<file path="${where}">\n${resource.text}\n</file>\n` : `@${where}`;
81
+ }
82
+ // A mention stands apart from the words around it.
83
+ if (part && text && !/\s$/.test(text) && !part.startsWith('\n')) text += ' ';
84
+ text += part;
85
+ }
86
+ return text.trim();
87
+ }
88
+
89
+ /** What kind of work a tool call is, from its name or its command's first word (Claude reports tools as `Read {…}`). */
90
+ export function toolKind(item: Extract<TimelineItem, { kind: 'tool_call' }>): acp.ToolKind {
91
+ const word = item.detail.type === 'shell' ? String(item.detail.command ?? '').trim().split(/[\s{(]/)[0] : item.name;
92
+ if (/^(Read|NotebookRead|LS)$/.test(word)) return 'read';
93
+ if (/^(Edit|MultiEdit|Write|NotebookEdit)$/.test(word)) return 'edit';
94
+ if (/^(Grep|Glob)$/.test(word)) return 'search';
95
+ if (/^(WebFetch|WebSearch)$/.test(word)) return 'fetch';
96
+ if (/^(Skill|Task|TodoWrite)$/.test(word) || item.name.startsWith('alp_')) return 'other';
97
+ return item.detail.type === 'shell' ? 'execute' : 'other';
98
+ }
99
+
100
+ function toolTitle(item: Extract<TimelineItem, { kind: 'tool_call' }>) {
101
+ if (item.detail.type === 'shell') return clip(String(item.detail.command ?? '').split('\n')[0], 160);
102
+ const input = (item.detail.input ?? {}) as Record<string, unknown>;
103
+ if (item.name === 'alp_delegate') return clip(`Delegate to ${input.agent ?? 'an agent'}: ${String(input.task ?? '').split('\n')[0]}`, 160);
104
+ return clip(`${item.name} ${JSON.stringify(input)}`, 160);
105
+ }
106
+
107
+ function toolOutput(item: Extract<TimelineItem, { kind: 'tool_call' }>): acp.ToolCallContent[] {
108
+ let text = '';
109
+ if (item.detail.type === 'shell') text = item.detail.output ?? '';
110
+ else {
111
+ const output = item.detail.output as unknown;
112
+ text = Array.isArray(output) ? output.map(part => typeof part?.text === 'string' ? part.text : JSON.stringify(part)).join('\n') : output == null ? '' : typeof output === 'string' ? output : JSON.stringify(output, null, 2);
113
+ }
114
+ if (item.error) text = text ? `${text}\n${item.error}` : item.error;
115
+ if (!text) return [];
116
+ if (text.length > OUTPUT_CHARS) text = `${text.slice(0, OUTPUT_CHARS)}\n… (${text.length - OUTPUT_CHARS} more characters)`;
117
+ return [{ type: 'content', content: { type: 'text', text } }];
118
+ }
119
+
120
+ const clip = (text: string, chars: number) => text.length > chars ? `${text.slice(0, chars - 1)}…` : text;
121
+
122
+ const status = (state: 'running' | 'completed' | 'failed'): acp.ToolCallStatus => state === 'running' ? 'in_progress' : state;
123
+
124
+ export function createAcpAgent(options: AcpAgentOptions) {
125
+ const log = options.log ?? (() => {});
126
+ const sessions = new Map<string, Session>();
127
+ let alpd: Promise<DaemonConnection> | undefined;
128
+ let editor: acp.AgentContext | undefined;
129
+ /** The editor went away and this process lets go of alpd. */
130
+ let leaving = false;
131
+
132
+ async function daemon() {
133
+ alpd ??= options.connect().then(connection => {
134
+ connection.onEvent(project);
135
+ connection.onClose(error => {
136
+ if (leaving) return;
137
+ log('lost the connection to alpd', { code: 'ALP_IPC_LOST', error });
138
+ alpd = undefined;
139
+ for (const session of sessions.values()) {
140
+ session.opened = false;
141
+ session.waiting?.done({ state: 'failed', error: `ALP lost its connection to alpd: ${error.message}` });
142
+ }
143
+ });
144
+ return connection;
145
+ }, error => { alpd = undefined; log('could not reach alpd', { code: 'ALP_IPC_CONNECT_FAILED', error }); throw error; });
146
+ return alpd;
147
+ }
148
+
149
+ const request = async (method: string, params: unknown) => (await daemon()).request(method, params);
150
+
151
+ function send(session: Session, update: acp.SessionUpdate) {
152
+ const client = editor;
153
+ if (!client) return;
154
+ session.queue = session.queue.then(() => client.notify('session/update', { sessionId: session.id, update })).catch(error => log('could not send an update to the editor', { code: 'ALP_ACP_UPDATE_FAILED', error }));
155
+ }
156
+
157
+ const say = (session: Session, text: string) => send(session, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } });
158
+
159
+ function configOptions(session: Session): acp.SessionConfigOption[] {
160
+ const teams: Team[] = session.opened ? session.preview.teams.filter(team => team.id === session.preview.team) : session.preview.teams;
161
+ return [
162
+ {
163
+ id: 'team', name: 'Team', category: 'model', type: 'select', currentValue: session.preview.team,
164
+ description: session.opened ? 'A session keeps its team; start a new one for another team' : 'The team that works on this session',
165
+ options: (teams.length ? teams : [{ id: session.preview.team, label: session.preview.teamLabel ?? session.preview.team }]).map(team => ({ value: team.id, name: team.label, ...(team.description ? { description: team.description } : {}) })),
166
+ },
167
+ { id: 'mode', name: 'Permissions', category: 'mode', type: 'select', currentValue: session.preview.mode, options: MODES.map(mode => ({ value: mode.id, name: mode.name, description: mode.description })) },
168
+ ];
169
+ }
170
+
171
+ const modeState = (session: Session): acp.SessionModeState => ({ currentModeId: session.preview.mode, availableModes: MODES });
172
+
173
+ function track(id: string, cwd: string, mcpServers: Record<string, HostMcpServer>, preview: SessionPreview, opened: boolean) {
174
+ const session: Session = { id, cwd, mcpServers, preview, opened, ours: new Set(), texts: new Map(), tools: new Set(), questions: new Map(), queue: Promise.resolve() };
175
+ sessions.set(id, session);
176
+ return session;
177
+ }
178
+
179
+ function known(sessionId: string) {
180
+ const session = sessions.get(sessionId);
181
+ if (!session) throw acp.RequestError.resourceNotFound(sessionId);
182
+ return session;
183
+ }
184
+
185
+ /** alpd events of this connection's trees, as ACP updates on their roots. */
186
+ function project(envelope: Envelope) {
187
+ const session = sessions.get(envelope.sessionId);
188
+ const { event } = envelope;
189
+ // Questions belong to the root, whichever agent of its tree asks.
190
+ if (event.type === 'question') {
191
+ const root = sessions.get(event.question.rootId);
192
+ if (!root || root.questions.has(event.question.id)) return;
193
+ root.questions.set(event.question.id, event.question);
194
+ const options = event.question.options?.length ? `\nOptions: ${event.question.options.join(' · ')}` : '';
195
+ say(root, `\n\n**${event.question.agent} asks you:** ${event.question.body}${options}\n\nReply with /answer <your answer>, or /dismiss.\n\n`);
196
+ return;
197
+ }
198
+ if (event.type === 'question.resolved') {
199
+ for (const root of sessions.values()) root.questions.delete(event.questionId);
200
+ return;
201
+ }
202
+ // Children show through their requester's alp_delegate call.
203
+ if (!session) return;
204
+ switch (event.type) {
205
+ case 'session.updated':
206
+ if (event.session.mode !== session.preview.mode) {
207
+ session.preview = { ...session.preview, mode: event.session.mode };
208
+ send(session, { sessionUpdate: 'current_mode_update', currentModeId: event.session.mode });
209
+ send(session, { sessionUpdate: 'config_option_update', configOptions: configOptions(session) });
210
+ }
211
+ return;
212
+ case 'prompt.accepted':
213
+ if (session.waiting?.clientMessageId === event.clientMessageId) session.waiting.turnId = event.turnId;
214
+ return;
215
+ case 'prompt.failed':
216
+ if (session.waiting?.clientMessageId === event.clientMessageId) session.waiting.done({ state: 'failed', error: event.error.message });
217
+ return;
218
+ case 'turn.ended':
219
+ if (session.waiting?.turnId === event.turnId) session.waiting.done({ state: event.state, ...(event.error ? { error: event.error.message } : {}) });
220
+ return;
221
+ case 'session.failed':
222
+ session.opened = false;
223
+ session.waiting?.done({ state: 'failed', error: event.error.message });
224
+ return;
225
+ case 'session.closed':
226
+ session.opened = false;
227
+ return;
228
+ case 'item':
229
+ item(session, event.item);
230
+ return;
231
+ }
232
+ }
233
+
234
+ function item(session: Session, item: TimelineItem) {
235
+ switch (item.kind) {
236
+ case 'user_message': {
237
+ if (item.clientMessageId && session.ours.has(item.clientMessageId)) return;
238
+ // Mail and ALP's own prompts to main are not the user's words: they show as a step.
239
+ if (item.clientMessageId?.startsWith('alp-') || item.id.startsWith('user:alp-')) {
240
+ send(session, { sessionUpdate: 'tool_call', toolCallId: item.id, title: clip(`ALP: ${item.text.split('\n').find(line => line.trim()) ?? 'note'}`, 160), kind: 'other', status: 'completed', content: [{ type: 'content', content: { type: 'text', text: item.text } }] });
241
+ return;
242
+ }
243
+ send(session, { sessionUpdate: 'user_message_chunk', content: { type: 'text', text: item.text } });
244
+ return;
245
+ }
246
+ case 'assistant_message': {
247
+ const before = session.texts.get(item.id) ?? '';
248
+ session.texts.set(item.id, item.text);
249
+ const fresh = item.text.startsWith(before) ? item.text.slice(before.length) : `\n${item.text}`;
250
+ if (fresh) say(session, fresh);
251
+ return;
252
+ }
253
+ case 'notice':
254
+ say(session, `\n\n> ALP: ${item.text}\n\n`);
255
+ return;
256
+ case 'compaction':
257
+ if (item.status !== 'running') say(session, `\n\n> ALP: ${item.status === 'completed' ? `the context was compacted${item.preTokens ? ` from ${Math.round(item.preTokens / 1000)}k tokens` : ''}` : 'compacting the context failed'}\n\n`);
258
+ return;
259
+ case 'todo':
260
+ send(session, { sessionUpdate: 'plan', entries: item.items.map(entry => ({ content: entry.text, priority: 'medium', status: entry.status })) });
261
+ return;
262
+ case 'tool_call': {
263
+ const fields = { title: toolTitle(item), kind: toolKind(item), status: status(item.status), content: toolOutput(item), rawInput: item.detail.type === 'shell' ? { command: item.detail.command, cwd: item.detail.cwd } : item.detail.input };
264
+ if (session.tools.has(item.id)) send(session, { sessionUpdate: 'tool_call_update', toolCallId: item.id, ...fields });
265
+ else {
266
+ session.tools.add(item.id);
267
+ send(session, { sessionUpdate: 'tool_call', toolCallId: item.id, ...fields });
268
+ }
269
+ return;
270
+ }
271
+ }
272
+ }
273
+
274
+ /** Opens the session's root in alpd with what the user chose; a reopened one resumes. */
275
+ async function open(session: Session, resume: boolean) {
276
+ await request('session.create', {
277
+ sessionId: session.id,
278
+ spec: { cwd: session.cwd, persist: true, workflow: session.preview.team, mode: session.preview.mode, mcpServers: session.mcpServers },
279
+ history: 'skip',
280
+ ...(resume ? { resume: true } : {}),
281
+ });
282
+ session.opened = true;
283
+ }
284
+
285
+ async function prompt(session: Session, blocks: acp.ContentBlock[]): Promise<acp.PromptResponse> {
286
+ const text = promptText(blocks);
287
+ const command = /^\/(answer|dismiss)\b\s*([\s\S]*)$/.exec(text);
288
+ if (command) {
289
+ const [question] = session.questions.values();
290
+ if (!question) say(session, 'No agent is waiting for an answer from you.');
291
+ else {
292
+ await request('question.answer', command[1] === 'answer' ? { questionId: question.id, text: command[2].trim() || 'yes' } : { questionId: question.id, dismiss: true, ...(command[2].trim() ? { reason: command[2].trim() } : {}) });
293
+ session.questions.delete(question.id);
294
+ say(session, command[1] === 'answer' ? `Sent your answer to ${question.agent}.` : `Dismissed ${question.agent}'s question.`);
295
+ }
296
+ await session.queue;
297
+ return { stopReason: 'end_turn' };
298
+ }
299
+ if (!text) throw acp.RequestError.invalidParams(undefined, 'The prompt is empty');
300
+ if (!session.opened) {
301
+ const { session: snapshot } = await request('session.get', { sessionId: session.id }).catch(() => ({ session: undefined }));
302
+ await open(session, !!snapshot);
303
+ send(session, { sessionUpdate: 'config_option_update', configOptions: configOptions(session) });
304
+ }
305
+ if (session.waiting) throw acp.RequestError.invalidRequest(undefined, 'A prompt is already running in this session');
306
+ const clientMessageId = randomUUID();
307
+ session.ours.add(clientMessageId);
308
+ let done!: NonNullable<Session['waiting']>['done'];
309
+ const ended = new Promise<{ state: 'completed' | 'failed' | 'canceled'; error?: string }>(resolve => {
310
+ done = result => { if (session.waiting?.clientMessageId === clientMessageId) session.waiting = undefined; resolve(result); };
311
+ });
312
+ session.waiting = { clientMessageId, done };
313
+ try {
314
+ // A turn main started by itself (mail from its team) takes the user's words as a steer.
315
+ await request('session.prompt', { sessionId: session.id, clientMessageId, delivery: 'auto', content: [{ type: 'text', text }] });
316
+ } catch (error) {
317
+ done({ state: 'failed', error: error instanceof Error ? error.message : String(error) });
318
+ }
319
+ const result = await ended;
320
+ await session.queue;
321
+ if (result.state === 'canceled') return { stopReason: 'cancelled' };
322
+ if (result.state === 'failed') throw acp.RequestError.internalError(undefined, result.error ?? 'The turn failed');
323
+ return { stopReason: 'end_turn' };
324
+ }
325
+
326
+ async function preview(cwd: string, mcpServers: Record<string, HostMcpServer>, team?: string, mode?: string): Promise<SessionPreview> {
327
+ const { preview } = await request('session.preview', { spec: { cwd, mcpServers, ...(team ? { workflow: team } : {}), ...(mode ? { mode } : {}) } });
328
+ return preview;
329
+ }
330
+
331
+ const absolute = (cwd: string) => {
332
+ if (!path.isAbsolute(cwd)) throw acp.RequestError.invalidParams(undefined, 'cwd must be an absolute path');
333
+ return path.resolve(cwd);
334
+ };
335
+
336
+ return acp.agent({ name: 'alp' })
337
+ .onConnect(connection => { editor = connection.client; void connection.closed.then(() => release()); })
338
+ .onRequest('initialize', () => ({
339
+ protocolVersion: acp.PROTOCOL_VERSION,
340
+ agentCapabilities: {
341
+ loadSession: true,
342
+ promptCapabilities: { embeddedContext: true },
343
+ mcpCapabilities: { http: true, sse: true },
344
+ sessionCapabilities: { list: {}, close: {} },
345
+ },
346
+ agentInfo: { name: 'alp', title: 'ALP', version: options.version },
347
+ authMethods: [],
348
+ }))
349
+ .onRequest('authenticate', () => ({}))
350
+ .onRequest('session/new', async ({ params }) => {
351
+ const cwd = absolute(params.cwd);
352
+ const mcpServers = hostServers(params.mcpServers);
353
+ const session = track(`acp-${randomUUID()}`, cwd, mcpServers, await preview(cwd, mcpServers), false);
354
+ queueMicrotask(() => send(session, { sessionUpdate: 'available_commands_update', availableCommands: COMMANDS }));
355
+ return { sessionId: session.id, configOptions: configOptions(session), modes: modeState(session) };
356
+ })
357
+ .onRequest('session/load', async ({ params }) => {
358
+ const cwd = absolute(params.cwd);
359
+ const { session: record } = await request('session.get', { sessionId: params.sessionId }).catch(() => { throw acp.RequestError.resourceNotFound(params.sessionId); });
360
+ if (record.parentId || path.resolve(record.projectRoot) !== cwd) throw acp.RequestError.invalidParams(undefined, 'That ALP session belongs to another project');
361
+ const session = track(params.sessionId, cwd, hostServers(params.mcpServers), {
362
+ teams: [{ id: record.workflow?.mode ?? 'pho', label: record.teamLabel ?? record.workflow?.mode ?? 'pho' }],
363
+ team: record.workflow?.mode ?? 'pho', ...(record.teamLabel ? { teamLabel: record.teamLabel } : {}),
364
+ agent: record.agent, runtime: record.runtime, model: record.model, mode: record.mode, thinking: record.thinking,
365
+ }, true);
366
+ // The history comes as updates before the answer, as ACP asks; a live root is followed, a closed one reopens on its next prompt.
367
+ const live = record.status === 'idle' || record.status === 'running';
368
+ await request('session.attach', { sessionId: session.id, replay: true });
369
+ session.opened = live;
370
+ await session.queue;
371
+ send(session, { sessionUpdate: 'available_commands_update', availableCommands: COMMANDS });
372
+ return { configOptions: configOptions(session), modes: modeState(session) };
373
+ })
374
+ .onRequest('session/list', async ({ params }) => {
375
+ const { sessions: rows } = await request('session.list', { ...(params.cwd ? { projectRoot: path.resolve(params.cwd) } : {}), rootsOnly: true, includeClosed: true });
376
+ return {
377
+ sessions: rows.filter((row: any) => row.persistent).slice(0, 100).map((row: any) => ({
378
+ sessionId: row.id,
379
+ cwd: row.projectRoot,
380
+ title: row.title ?? `ALP ${row.agent}`,
381
+ ...(row.updatedAt ? { updatedAt: row.updatedAt } : {}),
382
+ })),
383
+ };
384
+ })
385
+ .onRequest('session/prompt', ({ params }) => prompt(known(params.sessionId), params.prompt))
386
+ .onNotification('session/cancel', async ({ params }) => {
387
+ const session = sessions.get(params.sessionId);
388
+ if (!session?.opened) return;
389
+ await request('session.interrupt', { sessionId: session.id }).catch(error => log('session.interrupt failed', { code: 'ALP_ACP_INTERRUPT_FAILED', error }));
390
+ })
391
+ .onRequest('session/set_mode', async ({ params }) => {
392
+ await setMode(known(params.sessionId), params.modeId);
393
+ return {};
394
+ })
395
+ .onRequest('session/set_config_option', async ({ params }) => {
396
+ const session = known(params.sessionId);
397
+ const value = String(params.value);
398
+ if (params.configId === 'mode') await setMode(session, value);
399
+ else if (params.configId === 'team') {
400
+ if (session.opened && value !== session.preview.team) throw acp.RequestError.invalidParams(undefined, 'A session keeps its team; start a new one for another team');
401
+ if (!session.preview.teams.some(team => team.id === value)) throw acp.RequestError.invalidParams(undefined, `Unknown team ${value}`);
402
+ session.preview = { ...await preview(session.cwd, session.mcpServers, value), mode: session.preview.mode };
403
+ } else throw acp.RequestError.invalidParams(undefined, `Unknown option ${params.configId}`);
404
+ return { configOptions: configOptions(session) };
405
+ })
406
+ .onRequest('session/close', async ({ params }) => {
407
+ const session = known(params.sessionId);
408
+ sessions.delete(session.id);
409
+ if (session.opened) await request('session.release', { sessionId: session.id }).catch(() => {});
410
+ return {};
411
+ });
412
+
413
+ async function setMode(session: Session, mode: string) {
414
+ if (!MODES.some(entry => entry.id === mode)) throw acp.RequestError.invalidParams(undefined, `Unknown mode ${mode}`);
415
+ if (session.opened) await request('session.configure', { sessionId: session.id, mode });
416
+ session.preview = { ...session.preview, mode };
417
+ }
418
+
419
+ /** The editor went away: alpd closes each root once idle, and lets running work finish. */
420
+ async function release() {
421
+ leaving = true;
422
+ const connection = await alpd?.catch(() => undefined);
423
+ if (!connection) return;
424
+ await Promise.all([...sessions.values()].filter(session => session.opened).map(session => connection.request('session.release', { sessionId: session.id }).catch(() => {})));
425
+ sessions.clear();
426
+ connection.close();
427
+ }
428
+ }
@@ -0,0 +1,24 @@
1
+ import * as acp from '@agentclientprotocol/sdk';
2
+ import { Readable, Writable } from 'node:stream';
3
+ import { alpHome, connect } from '@anhlp/alp-client/index';
4
+ import { startDaemon } from '@anhlp/alp-client/supervise';
5
+ import { createLogger } from '@anhlp/alp-core/log';
6
+ import { createAcpAgent } from './agent.js';
7
+
8
+ declare const __ALP_VERSION__: string;
9
+
10
+ /** `alp acp`: serves the Agent Client Protocol on stdio until the editor closes it (ALPD §60). */
11
+ export async function runAcp({ daemonEntry }: { daemonEntry: string }) {
12
+ const version = typeof __ALP_VERSION__ === 'string' ? __ALP_VERSION__ : '0.0.0';
13
+ // Stdout is the protocol stream; diagnostics are structured lines on stderr only.
14
+ const logger = createLogger({ component: 'acp' });
15
+ const log = (message: string, fields?: { code?: string; error?: unknown }) => logger.warn(message, fields);
16
+ const app = createAcpAgent({
17
+ version,
18
+ log,
19
+ connect: async () => connect(await startDaemon({ home: alpHome(), entry: daemonEntry }), { name: 'alp-acp', version }),
20
+ });
21
+ const stream = acp.ndJsonStream(Writable.toWeb(process.stdout), Readable.toWeb(process.stdin) as ReadableStream<Uint8Array>);
22
+ const connection = app.connect(stream);
23
+ await connection.closed;
24
+ }
package/src/backup.js ADDED
@@ -0,0 +1,127 @@
1
+ import { access, readdir, stat } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { BACKUP_EXTENSION, backupsDir, createBackup, knownProjects, restoreBackup, verifyBackup } from '@anhlp/alp-core/backup';
5
+ import { acquireDaemonLock, alpHome, assertPrivateDirectory, daemonPaths, lockAlive, readLock, releaseDaemonLock, PROTOCOL_VERSION } from '@anhlp/alp-client/index';
6
+ import { daemonHeld, holdDaemon, releaseHold } from '@anhlp/alp-client/supervise';
7
+ import { start, stop } from './daemon.js';
8
+ import { UsageError } from './usage.js';
9
+
10
+ /* global __ALP_VERSION__ */
11
+ const VERSION = typeof __ALP_VERSION__ === 'string' ? __ALP_VERSION__ : 'dev';
12
+ const BY = `alp ${VERSION}`;
13
+
14
+ const size = bytes => bytes >= 1024 * 1024 ? `${(bytes / 1024 / 1024).toFixed(1)} MB` : bytes >= 1024 ? `${(bytes / 1024).toFixed(1)} KB` : `${bytes} B`;
15
+ const stamp = () => new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z');
16
+
17
+ /**
18
+ * Runs `work` with alpd away (ALPD §68): its lock is taken for the maintenance, so no alpd
19
+ * starts on data being read or replaced, and Paseo is held from starting one meanwhile. A
20
+ * running alpd is stopped only with --stop, and started again after; what it was working on
21
+ * is continued then, as after any stop (ALPD §31).
22
+ */
23
+ async function withMaintenance(kind, { stopFirst }, work) {
24
+ const home = alpHome();
25
+ await assertPrivateDirectory(home, { create: true });
26
+ const current = await readLock(home);
27
+ const running = lockAlive(current);
28
+ if (running && current.maintenance) throw new Error(`alp ${current.maintenance} already runs (pid ${current.pid})`);
29
+ if (running && !stopFirst) throw new Error(`alpd is running (pid ${current.pid}); stop it first with alp daemon stop, or pass --stop: ALP then stops alpd for the ${kind} and starts it again after`);
30
+ const wasHeld = await daemonHeld(home);
31
+ await holdDaemon(home, `alp ${kind}`);
32
+ let restart = false;
33
+ try {
34
+ if (running) restart = await stop();
35
+ await acquireDaemonLock(home, { version: VERSION, protocolVersion: PROTOCOL_VERSION, socket: daemonPaths(home).socket, maintenance: kind });
36
+ try { return await work(home); }
37
+ finally { await releaseDaemonLock(home); }
38
+ } finally {
39
+ if (!wasHeld) await releaseHold(home);
40
+ if (restart) {
41
+ await start().then(() => console.log('alpd started again'), error => console.error(`alp: alpd did not start again (${error.message}); run alp daemon start`));
42
+ }
43
+ }
44
+ }
45
+
46
+ async function isProject(directory) {
47
+ return access(path.join(directory, '.alp')).then(() => true, () => false);
48
+ }
49
+
50
+ /** alp backup [create] | verify <file> | list */
51
+ export async function backupCommand(args) {
52
+ const [first, ...rest] = args;
53
+ if (first === 'verify') return verifyCommand(rest);
54
+ if (first === 'list') return listCommand(rest);
55
+ const { values, positionals } = parseArgs({ args: first === 'create' ? rest : args, allowPositionals: true, options: {
56
+ output: { type: 'string', short: 'o' }, project: { type: 'string', multiple: true }, 'no-projects': { type: 'boolean' }, stop: { type: 'boolean' }, json: { type: 'boolean' },
57
+ } });
58
+ if (positionals.length) throw new UsageError();
59
+ const out = path.resolve(values.output ?? path.join(backupsDir(alpHome()), `backup-${stamp()}${BACKUP_EXTENSION}`));
60
+ if (await stat(out).then(() => true, () => false)) throw new Error(`${out} exists; choose another file with -o`);
61
+ const summary = await withMaintenance('backup', { stopFirst: values.stop }, async home => {
62
+ let projects = [];
63
+ if (!values['no-projects']) {
64
+ // The projects the sessions worked in, those named, and this directory when it is one.
65
+ const named = (values.project ?? []).map(directory => path.resolve(directory));
66
+ for (const directory of named) if (!await isProject(directory)) throw new Error(`${directory} is not an ALP project (no .alp directory)`);
67
+ const here = await isProject(process.cwd()) ? [path.resolve(process.cwd())] : [];
68
+ projects = [...new Set([...await knownProjects(home), ...named, ...here])].sort();
69
+ }
70
+ return createBackup({ home, out, projects, by: BY });
71
+ });
72
+ if (values.json) { console.log(JSON.stringify(summary)); return; }
73
+ console.log(`backup written to ${out} (${size((await stat(out)).size)})`);
74
+ console.log(` ${summary.sessions} session record${summary.sessions === 1 ? '' : 's'}, state schema ${summary.stateSchema ?? 'unknown'}; ${summary.tasks} task${summary.tasks === 1 ? '' : 's'} in ${summary.projects.length} project${summary.projects.length === 1 ? '' : 's'}${summary.projects.length ? `: ${summary.projects.join(', ')}` : ''}`);
75
+ console.log(' it holds your settings and library too, and may hold credentials from them: keep it private. Codex and Claude keep their own threads; see docs/alp/data-recovery.md');
76
+ }
77
+
78
+ async function verifyCommand(args) {
79
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { json: { type: 'boolean' } } });
80
+ if (positionals.length !== 1) throw new UsageError();
81
+ const contents = await verifyBackup(path.resolve(positionals[0]));
82
+ if (values.json) { console.log(JSON.stringify(contents)); return; }
83
+ console.log(`${contents.file}: complete and intact`);
84
+ console.log(` made ${contents.createdAt}${contents.by ? ` by ${contents.by}` : ''} (${contents.kind}) from ${contents.home}; state schema ${contents.stateSchema ?? 'unknown'}`);
85
+ console.log(` ${contents.sessions} session records, ${contents.tasks} tasks, ${contents.files} files, ${size(contents.bytes)}`);
86
+ if (contents.projects.length) console.log(` projects: ${contents.projects.join(', ')}`);
87
+ }
88
+
89
+ async function listCommand(args) {
90
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { json: { type: 'boolean' } } });
91
+ if (positionals.length) throw new UsageError();
92
+ const directory = backupsDir(alpHome());
93
+ const names = (await readdir(directory).catch(() => [])).filter(name => name.endsWith(BACKUP_EXTENSION)).sort();
94
+ const files = await Promise.all(names.map(async name => { const info = await stat(path.join(directory, name)); return { file: path.join(directory, name), bytes: info.size, at: info.mtime.toISOString() }; }));
95
+ if (values.json) { console.log(JSON.stringify(files)); return; }
96
+ if (!files.length) { console.log(`no backups in ${directory}`); return; }
97
+ for (const file of files) console.log(`${file.at} ${size(file.bytes).padStart(9)} ${file.file}`);
98
+ }
99
+
100
+ /** alp restore <file> [--home-only] [--stop] [--dry-run] [--replace-newer] [--json] */
101
+ export async function restoreCommand(args) {
102
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
103
+ 'home-only': { type: 'boolean' }, stop: { type: 'boolean' }, 'dry-run': { type: 'boolean' }, 'replace-newer': { type: 'boolean' }, json: { type: 'boolean' },
104
+ } });
105
+ if (positionals.length !== 1) throw new UsageError();
106
+ const file = path.resolve(positionals[0]);
107
+ if (values['dry-run']) {
108
+ const contents = await verifyBackup(file);
109
+ const missing = [];
110
+ for (const root of contents.projects) if (!await stat(root).then(info => info.isDirectory(), () => false)) missing.push(root);
111
+ if (values.json) { console.log(JSON.stringify({ ...contents, missing })); return; }
112
+ console.log(`${file} is intact; a restore would replace, in ${alpHome()}: ${contents.units.join(', ') || 'nothing'}`);
113
+ if (!values['home-only']) for (const root of contents.projects) console.log(` and in ${root}: its ALP files and tasks${missing.includes(root) ? ' (skipped: the directory does not exist)' : ''}`);
114
+ console.log('nothing was changed');
115
+ return;
116
+ }
117
+ const result = await withMaintenance('restore', { stopFirst: values.stop }, home => restoreBackup({ home, file, projects: !values['home-only'], replaceNewer: values['replace-newer'], by: BY }));
118
+ if (values.json) { console.log(JSON.stringify(result)); return; }
119
+ if (result.interrupted) console.log(`an earlier restore was cut short and has been ${result.interrupted.outcome}`);
120
+ console.log(`restored ${file}`);
121
+ console.log(` ${alpHome()}: ${result.units.filter(unit => unit.area === 'home' && unit.present).map(unit => unit.unit).join(', ') || 'nothing'}`);
122
+ for (const root of result.projects) console.log(` ${root}: ${result.units.filter(unit => unit.area === root && unit.present).map(unit => unit.unit).join(', ') || 'nothing'}`);
123
+ for (const { root, reason } of result.skipped) console.log(` skipped ${root}: ${reason}`);
124
+ for (const warning of result.warnings) console.log(` note: ${warning}`);
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} puts it back`);
127
+ }
package/src/cli.js ADDED
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env node
2
+ import { setup } from '@anhlp/alp-client/setup';
3
+ import { alpHome } from '@anhlp/alp-client/index';
4
+ import { scrubText } from '@anhlp/alp-core/log';
5
+ import { USAGE, UsageError } from './usage.js';
6
+ import { project, permissionsCommand, trustCommand, language, verify, doctor } from './projects.js';
7
+ import { daemon } from './daemon.js';
8
+ import { run, ps, attach, send, questions, answer, top, log, board, pause, resume, recall, interrupt } from './sessions.js';
9
+ import { libraryCommand, editCommand, teamsCommand } from './library.js';
10
+ import { tasksCommand, formulaCommand, taskCommand } from './tasks.js';
11
+ import { webCommand, acpCommand } from './interfaces.js';
12
+ import { backupCommand, restoreCommand } from './backup.js';
13
+
14
+ 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 };
15
+ const [command, ...args] = process.argv.slice(2);
16
+ try {
17
+ if (!Object.hasOwn(commands, command)) throw new UsageError();
18
+ await commands[command](args);
19
+ } catch (error) {
20
+ if (error instanceof UsageError || error?.code === 'ERR_PARSE_ARGS_UNKNOWN_OPTION') console.error(USAGE);
21
+ else console.error(`alp: ${scrubText(error?.message ?? error)}`);
22
+ process.exitCode = 1;
23
+ }