@anhlp/alp-cli 0.0.0-beta.1 → 0.0.1-beta.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/THIRD-PARTY-NOTICES.txt +52 -2
- package/dist/acp/agent.d.ts +11 -3
- package/dist/acp/agent.js +118 -19
- package/dist/acp/main.js +1 -1
- package/dist/acp.js +7898 -2238
- package/dist/alp-dashboard/THIRD-PARTY-NOTICES.txt +3256 -0
- package/dist/alp-dashboard/alp-boundary.json +16 -0
- package/dist/alp-dashboard/apple-touch-icon.png +0 -0
- package/dist/alp-dashboard/assets/TerminalPanel-D8HE9XBX.js +22 -0
- package/dist/alp-dashboard/assets/TerminalPanel-DLuoa74B.css +1 -0
- package/dist/alp-dashboard/assets/highlighter-BnicKQ_d.js +18 -0
- package/dist/alp-dashboard/assets/index-DwqDSiIi.css +1 -0
- package/dist/alp-dashboard/assets/index-YdtH3NBy.js +59 -0
- package/dist/alp-dashboard/favicon-attention.svg +6 -0
- package/dist/alp-dashboard/favicon-running.svg +6 -0
- package/dist/alp-dashboard/favicon.svg +5 -0
- package/dist/alp-dashboard/index.html +20 -0
- package/dist/alp-dashboard.js +10165 -0
- package/dist/alpd.js +39994 -16997
- package/dist/backup.js +2 -2
- package/dist/build-manifest.json +142 -3
- package/dist/cli.js +40 -6
- package/dist/daemon.d.ts +3 -3
- package/dist/daemon.js +16 -7
- package/dist/dashboard-migrate.d.ts +31 -0
- package/dist/dashboard-migrate.js +127 -0
- package/dist/dashboard-service.d.ts +69 -0
- package/dist/dashboard-service.js +141 -0
- package/dist/desktop.d.ts +56 -0
- package/dist/desktop.js +91 -0
- package/dist/interfaces.d.ts +23 -3
- package/dist/interfaces.js +277 -41
- package/dist/library.d.ts +16 -2
- package/dist/library.js +114 -7
- package/dist/paths.d.ts +6 -0
- package/dist/paths.js +4 -1
- package/dist/projects.js +2 -1
- package/dist/roles.d.ts +15 -0
- package/dist/roles.js +16 -0
- package/dist/schedules.d.ts +2 -0
- package/dist/schedules.js +45 -0
- package/dist/self-update.d.ts +151 -0
- package/dist/self-update.js +422 -0
- package/dist/sessions.d.ts +9 -2
- package/dist/sessions.js +67 -13
- package/dist/tasks.js +22 -8
- package/dist/terminal-native/README.md +201 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
- package/dist/terminal-native/terminal-owner.c +389 -0
- package/dist/terminal.d.ts +13 -0
- package/dist/terminal.js +80 -0
- package/dist/usage.d.ts +1 -1
- package/dist/usage.js +31 -9
- package/package.json +11 -4
- package/src/acp/agent.ts +111 -20
- package/src/backup.js +1 -1
- package/src/cli.js +51 -6
- package/src/daemon.js +18 -9
- package/src/dashboard-migrate.js +152 -0
- package/src/dashboard-service.js +192 -0
- package/src/desktop.js +122 -0
- package/src/interfaces.js +345 -38
- package/src/library.js +108 -9
- package/src/paths.js +9 -1
- package/src/projects.js +3 -1
- package/src/roles.js +26 -0
- package/src/schedules.js +38 -0
- package/src/self-update.js +443 -0
- package/src/sessions.js +60 -16
- package/src/tasks.js +22 -8
- package/src/terminal.js +78 -0
- package/src/usage.js +31 -9
package/src/acp/agent.ts
CHANGED
|
@@ -27,6 +27,11 @@ type Session = {
|
|
|
27
27
|
cwd: string;
|
|
28
28
|
mcpServers: Record<string, HostMcpServer>;
|
|
29
29
|
preview: SessionPreview;
|
|
30
|
+
/**
|
|
31
|
+
* The team the first preview named when the project's team list lacks it (`custom`, for settings
|
|
32
|
+
* without workflow.mode), kept so the editor can choose it again after trying another team.
|
|
33
|
+
*/
|
|
34
|
+
unlisted?: Team;
|
|
30
35
|
/** Open in alpd: the team is fixed from then on. */
|
|
31
36
|
opened: boolean;
|
|
32
37
|
/** Prompts this connection sent, which the editor already shows. */
|
|
@@ -43,6 +48,10 @@ type Session = {
|
|
|
43
48
|
waiting?: { clientMessageId: string; turnId?: string; done(result: { state: 'completed' | 'failed' | 'canceled'; error?: string }): void };
|
|
44
49
|
};
|
|
45
50
|
|
|
51
|
+
/** The team a preview named when its list lacks it (`custom` runs settings' delegation graph, ALPD §42). */
|
|
52
|
+
const unlistedOf = ({ teams, team, teamLabel }: SessionPreview): Team | undefined =>
|
|
53
|
+
teams.some(entry => entry.id === team) ? undefined : { id: team, label: teamLabel ?? (team === 'custom' ? 'Custom' : team) };
|
|
54
|
+
|
|
46
55
|
const MODES = [
|
|
47
56
|
{ id: 'read-only', name: 'Read only', description: 'Agents read and search; nothing is changed' },
|
|
48
57
|
{ id: 'workspace-write', name: 'Workspace write', description: 'Agents change files and run commands inside the project' },
|
|
@@ -86,35 +95,104 @@ export function promptText(blocks: acp.ContentBlock[]) {
|
|
|
86
95
|
return text.trim();
|
|
87
96
|
}
|
|
88
97
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
98
|
+
type ToolItem = Extract<TimelineItem, { kind: 'tool_call' }>;
|
|
99
|
+
/** A detail as received; a type later than this version's falls to the unknown branches. */
|
|
100
|
+
type AnyDetail = ToolItem['detail'];
|
|
101
|
+
|
|
102
|
+
/** A path as the editor's user knows it: relative to the session's folder when inside it. */
|
|
103
|
+
function shown(file: string, cwd?: string) {
|
|
104
|
+
if (!cwd || !path.isAbsolute(file)) return file;
|
|
105
|
+
const relative = path.relative(cwd, file);
|
|
106
|
+
return relative && !relative.startsWith('..') && !path.isAbsolute(relative) ? relative : file;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** What kind of work a tool call is: from its typed detail, else its name or its command's first word (older Claude items are `Read {…}` commands). */
|
|
110
|
+
export function toolKind(item: ToolItem): acp.ToolKind {
|
|
111
|
+
const detail = item.detail as AnyDetail;
|
|
112
|
+
switch (detail.type) {
|
|
113
|
+
case 'read': return 'read';
|
|
114
|
+
case 'edit': case 'write': return 'edit';
|
|
115
|
+
case 'search': return detail.toolName === 'web_search' ? 'fetch' : 'search';
|
|
116
|
+
case 'fetch': return 'fetch';
|
|
117
|
+
case 'plan': return 'think';
|
|
118
|
+
case 'sub_agent': case 'plain_text': return 'other';
|
|
119
|
+
}
|
|
120
|
+
const word = detail.type === 'shell' ? String(detail.command ?? '').trim().split(/[\s{(]/)[0] : item.name;
|
|
92
121
|
if (/^(Read|NotebookRead|LS)$/.test(word)) return 'read';
|
|
93
122
|
if (/^(Edit|MultiEdit|Write|NotebookEdit)$/.test(word)) return 'edit';
|
|
94
123
|
if (/^(Grep|Glob)$/.test(word)) return 'search';
|
|
95
124
|
if (/^(WebFetch|WebSearch)$/.test(word)) return 'fetch';
|
|
96
125
|
if (/^(Skill|Task|TodoWrite)$/.test(word) || item.name.startsWith('alp_')) return 'other';
|
|
97
|
-
return
|
|
126
|
+
return detail.type === 'shell' ? 'execute' : 'other';
|
|
98
127
|
}
|
|
99
128
|
|
|
100
|
-
function toolTitle(item:
|
|
101
|
-
|
|
102
|
-
|
|
129
|
+
export function toolTitle(item: ToolItem, cwd?: string) {
|
|
130
|
+
const detail = item.detail as AnyDetail;
|
|
131
|
+
switch (detail.type) {
|
|
132
|
+
case 'shell': return clip(String(detail.command ?? '').split('\n')[0], 160);
|
|
133
|
+
case 'read': return clip(`Read ${shown(detail.filePath, cwd)}`, 160);
|
|
134
|
+
case 'edit': return clip(`Edit ${shown(detail.filePath, cwd)}`, 160);
|
|
135
|
+
case 'write': return clip(`Write ${shown(detail.filePath, cwd)}`, 160);
|
|
136
|
+
case 'search': return clip(`${detail.toolName === 'web_search' ? 'Search the web' : 'Search'} ${detail.query}`, 160);
|
|
137
|
+
case 'fetch': return clip(`Fetch ${detail.url}`, 160);
|
|
138
|
+
case 'sub_agent': return clip(`${detail.subAgentType ?? 'Sub-agent'}${detail.description ? `: ${detail.description.split('\n')[0]}` : ''}`, 160);
|
|
139
|
+
case 'plan': return 'Plan';
|
|
140
|
+
case 'plain_text': return clip(`${item.name}${detail.label ? `: ${detail.label}` : ''}`, 160);
|
|
141
|
+
}
|
|
142
|
+
const input = ((detail as { input?: unknown }).input ?? {}) as Record<string, unknown>;
|
|
103
143
|
if (item.name === 'alp_delegate') return clip(`Delegate to ${input.agent ?? 'an agent'}: ${String(input.task ?? '').split('\n')[0]}`, 160);
|
|
104
144
|
return clip(`${item.name} ${JSON.stringify(input)}`, 160);
|
|
105
145
|
}
|
|
106
146
|
|
|
107
|
-
|
|
147
|
+
const bounded = (text: string) => text.length > OUTPUT_CHARS ? `${text.slice(0, OUTPUT_CHARS)}\n… (${text.length - OUTPUT_CHARS} more characters)` : text;
|
|
148
|
+
|
|
149
|
+
export function toolOutput(item: ToolItem): acp.ToolCallContent[] {
|
|
150
|
+
const detail = item.detail as AnyDetail;
|
|
151
|
+
const parts: acp.ToolCallContent[] = [];
|
|
108
152
|
let text = '';
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
153
|
+
switch (detail.type) {
|
|
154
|
+
case 'shell': text = detail.output ?? ''; break;
|
|
155
|
+
case 'read': text = detail.content ?? ''; break;
|
|
156
|
+
case 'edit':
|
|
157
|
+
// The editor shows a change as a diff when both sides are known.
|
|
158
|
+
if (detail.newString !== undefined || detail.oldString !== undefined) parts.push({ type: 'diff', path: detail.filePath, oldText: detail.oldString ?? null, newText: detail.newString ?? '' });
|
|
159
|
+
else if (detail.unifiedDiff) text = '```diff\n' + detail.unifiedDiff + (detail.unifiedDiff.endsWith('\n') ? '' : '\n') + '```';
|
|
160
|
+
break;
|
|
161
|
+
case 'write':
|
|
162
|
+
if (detail.content !== undefined) parts.push({ type: 'diff', path: detail.filePath, oldText: null, newText: detail.content });
|
|
163
|
+
break;
|
|
164
|
+
case 'search':
|
|
165
|
+
text = detail.content ?? [...(detail.filePaths ?? []), ...(detail.webResults ?? []).map(hit => `${hit.title} — ${hit.url}`)].join('\n');
|
|
166
|
+
break;
|
|
167
|
+
case 'fetch': text = detail.result ?? ''; break;
|
|
168
|
+
case 'sub_agent': text = detail.log || detail.description || ''; break;
|
|
169
|
+
case 'plan': text = detail.text; break;
|
|
170
|
+
case 'plain_text': text = detail.text ?? ''; break;
|
|
171
|
+
default: {
|
|
172
|
+
const output = (detail as { output?: unknown }).output;
|
|
173
|
+
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);
|
|
174
|
+
}
|
|
113
175
|
}
|
|
114
176
|
if (item.error) text = text ? `${text}\n${item.error}` : item.error;
|
|
115
|
-
if (
|
|
116
|
-
|
|
117
|
-
|
|
177
|
+
if (text) parts.push({ type: 'content', content: { type: 'text', text: bounded(text) } });
|
|
178
|
+
return parts.map(part => part.type === 'diff' ? { ...part, newText: bounded(part.newText), ...(part.oldText ? { oldText: bounded(part.oldText) } : {}) } : part);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** The call's input as the editor shows it raw: a command, a typed call's own fields without its long texts, or the tool's input. */
|
|
182
|
+
export function toolInput(item: ToolItem): unknown {
|
|
183
|
+
const detail = item.detail as AnyDetail;
|
|
184
|
+
if (detail.type === 'shell') return { command: detail.command, cwd: detail.cwd };
|
|
185
|
+
if (detail.type === 'unknown' || !['read', 'edit', 'write', 'search', 'fetch', 'sub_agent', 'plan', 'plain_text'].includes(detail.type as string)) return (detail as { input?: unknown }).input;
|
|
186
|
+
const { type: _type, content: _content, oldString: _old, newString: _new, unifiedDiff: _diff, result: _result, log: _log, text: _text, filePaths: _paths, webResults: _hits, ...rest } = detail as Record<string, unknown>;
|
|
187
|
+
return rest;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** The file a typed call read or changed, for the editor to follow. */
|
|
191
|
+
export function toolLocations(item: ToolItem): acp.ToolCallLocation[] | undefined {
|
|
192
|
+
const detail = item.detail as AnyDetail;
|
|
193
|
+
if (detail.type !== 'read' && detail.type !== 'edit' && detail.type !== 'write') return undefined;
|
|
194
|
+
const filePath = String(detail.filePath);
|
|
195
|
+
return [{ path: filePath, ...(detail.type === 'read' && typeof detail.offset === 'number' ? { line: detail.offset } : {}) }];
|
|
118
196
|
}
|
|
119
197
|
|
|
120
198
|
const clip = (text: string, chars: number) => text.length > chars ? `${text.slice(0, chars - 1)}…` : text;
|
|
@@ -157,21 +235,33 @@ export function createAcpAgent(options: AcpAgentOptions) {
|
|
|
157
235
|
const say = (session: Session, text: string) => send(session, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } });
|
|
158
236
|
|
|
159
237
|
function configOptions(session: Session): acp.SessionConfigOption[] {
|
|
160
|
-
const teams: Team[] = session.opened ? session.
|
|
238
|
+
const teams: Team[] = session.opened ? choices(session).filter(team => team.id === session.preview.team) : choices(session);
|
|
161
239
|
return [
|
|
162
240
|
{
|
|
163
241
|
id: 'team', name: 'Team', category: 'model', type: 'select', currentValue: session.preview.team,
|
|
164
242
|
description: session.opened ? 'A session keeps its team; start a new one for another team' : 'The team that works on this session',
|
|
165
|
-
options:
|
|
243
|
+
options: teams.map(team => ({ value: team.id, name: team.label, ...(team.description ? { description: team.description } : {}) })),
|
|
166
244
|
},
|
|
167
245
|
{ 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
246
|
];
|
|
169
247
|
}
|
|
170
248
|
|
|
249
|
+
/**
|
|
250
|
+
* The teams the editor may choose: the project's, led by the team the preview named when the
|
|
251
|
+
* list lacks it (`custom`, for settings without workflow.mode), so it can be chosen back.
|
|
252
|
+
*/
|
|
253
|
+
function choices(session: Session): Team[] {
|
|
254
|
+
const { teams, team } = session.preview;
|
|
255
|
+
const own = unlistedOf(session.preview);
|
|
256
|
+
const first = session.unlisted && session.unlisted.id !== team && !teams.some(entry => entry.id === session.unlisted!.id) ? [session.unlisted] : [];
|
|
257
|
+
return [...first, ...(own ? [own] : []), ...teams];
|
|
258
|
+
}
|
|
259
|
+
|
|
171
260
|
const modeState = (session: Session): acp.SessionModeState => ({ currentModeId: session.preview.mode, availableModes: MODES });
|
|
172
261
|
|
|
173
262
|
function track(id: string, cwd: string, mcpServers: Record<string, HostMcpServer>, preview: SessionPreview, opened: boolean) {
|
|
174
|
-
const
|
|
263
|
+
const unlisted = unlistedOf(preview);
|
|
264
|
+
const session: Session = { id, cwd, mcpServers, preview, opened, ...(unlisted ? { unlisted } : {}), ours: new Set(), texts: new Map(), tools: new Set(), questions: new Map(), queue: Promise.resolve() };
|
|
175
265
|
sessions.set(id, session);
|
|
176
266
|
return session;
|
|
177
267
|
}
|
|
@@ -260,7 +350,8 @@ export function createAcpAgent(options: AcpAgentOptions) {
|
|
|
260
350
|
send(session, { sessionUpdate: 'plan', entries: item.items.map(entry => ({ content: entry.text, priority: 'medium', status: entry.status })) });
|
|
261
351
|
return;
|
|
262
352
|
case 'tool_call': {
|
|
263
|
-
const
|
|
353
|
+
const locations = toolLocations(item);
|
|
354
|
+
const fields = { title: toolTitle(item, session.cwd), kind: toolKind(item), status: status(item.status), content: toolOutput(item), rawInput: toolInput(item), ...(locations ? { locations } : {}) };
|
|
264
355
|
if (session.tools.has(item.id)) send(session, { sessionUpdate: 'tool_call_update', toolCallId: item.id, ...fields });
|
|
265
356
|
else {
|
|
266
357
|
session.tools.add(item.id);
|
|
@@ -398,7 +489,7 @@ export function createAcpAgent(options: AcpAgentOptions) {
|
|
|
398
489
|
if (params.configId === 'mode') await setMode(session, value);
|
|
399
490
|
else if (params.configId === 'team') {
|
|
400
491
|
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.
|
|
492
|
+
if (!choices(session).some(team => team.id === value)) throw acp.RequestError.invalidParams(undefined, `Unknown team ${value}`);
|
|
402
493
|
session.preview = { ...await preview(session.cwd, session.mcpServers, value), mode: session.preview.mode };
|
|
403
494
|
} else throw acp.RequestError.invalidParams(undefined, `Unknown option ${params.configId}`);
|
|
404
495
|
return { configOptions: configOptions(session) };
|
package/src/backup.js
CHANGED
|
@@ -123,5 +123,5 @@ export async function restoreCommand(args) {
|
|
|
123
123
|
for (const { root, reason } of result.skipped) console.log(` skipped ${root}: ${reason}`);
|
|
124
124
|
for (const warning of result.warnings) console.log(` note: ${warning}`);
|
|
125
125
|
if (result.stateSchema !== null && result.stateSchema !== undefined) console.log(' sessions that were working when the backup was made wait for you; alpd continues none by itself');
|
|
126
|
-
if (result.safety) console.log(`the data it replaced is in ${result.safety}; alp restore ${result.safety}
|
|
126
|
+
if (result.safety) console.log(`the data it replaced is in ${result.safety}; alp restore ${result.safety} restores that data with the same workspace authority checks`);
|
|
127
127
|
}
|
package/src/cli.js
CHANGED
|
@@ -1,21 +1,66 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
2
3
|
import { setup } from '@anhlp/alp-client/setup';
|
|
3
4
|
import { alpHome } from '@anhlp/alp-client/index';
|
|
4
5
|
import { scrubText } from '@anhlp/alp-core/log';
|
|
6
|
+
import { catalogModels, useLiveModels } from '@anhlp/alp-core/models';
|
|
5
7
|
import { USAGE, UsageError } from './usage.js';
|
|
6
8
|
import { project, permissionsCommand, trustCommand, language, verify, doctor } from './projects.js';
|
|
7
9
|
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 { run, ps, attach, send, questions, answer, top, log, board, models, pause, resume, recall, interrupt, compact } from './sessions.js';
|
|
11
|
+
import { libraryCommand, editCommand, teamsCommand, packsCommand, packCommand } from './library.js';
|
|
12
|
+
import { scheduleCommand } from './schedules.js';
|
|
10
13
|
import { tasksCommand, formulaCommand, taskCommand } from './tasks.js';
|
|
11
|
-
import {
|
|
14
|
+
import { dashboardCommand, acpCommand } from './interfaces.js';
|
|
15
|
+
import { desktopCommand } from './desktop.js';
|
|
12
16
|
import { backupCommand, restoreCommand } from './backup.js';
|
|
17
|
+
import { terminalCommand } from './terminal.js';
|
|
18
|
+
import { bridgeCommand } from './roles.js';
|
|
19
|
+
import { selfUpdate } from './self-update.js';
|
|
20
|
+
import { bundleInfo } from '@anhlp/alp-core/packaged';
|
|
21
|
+
import { connect, lockAlive, readLock } from '@anhlp/alp-client/index';
|
|
13
22
|
|
|
14
|
-
|
|
23
|
+
/** The version of this alp: the build's, or the package's. */
|
|
24
|
+
function alpVersion() {
|
|
25
|
+
/* global __ALP_VERSION__ */
|
|
26
|
+
return (typeof __ALP_VERSION__ === 'string' ? __ALP_VERSION__ : JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The running alpd's version and live sessions, if one runs for this ALP_HOME. */
|
|
30
|
+
async function runningDaemon() {
|
|
31
|
+
const lock = await readLock(alpHome());
|
|
32
|
+
if (!lockAlive(lock)) return undefined;
|
|
33
|
+
const client = await connect(lock.socket, { name: 'alp-cli', version: '1' }).catch(() => undefined);
|
|
34
|
+
if (!client) return { version: lock.version };
|
|
35
|
+
try {
|
|
36
|
+
const status = await client.request('daemon.status');
|
|
37
|
+
return { version: status.version ?? lock.version, sessions: status.sessions };
|
|
38
|
+
} catch {
|
|
39
|
+
return { version: lock.version };
|
|
40
|
+
} finally {
|
|
41
|
+
client.close();
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** alp update: the bundle's self-update (t-1807); the template upgrade is alp update-template. */
|
|
46
|
+
async function updateCommand(args) {
|
|
47
|
+
const code = await selfUpdate(args, { bundle: bundleInfo(), version: alpVersion(), daemon: runningDaemon });
|
|
48
|
+
if (code) process.exitCode = code;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const commands = { schedule: scheduleCommand, setup: args => setup(args, alpHome()), init: args => project('init', args), 'update-template': args => project('upgrade', args), upgrade: args => project('upgrade', args), update: updateCommand, 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, packs: packsCommand, pack: packCommand, 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, models, interrupt, compact, acp: acpCommand, dashboard: dashboardCommand, desktop: desktopCommand, backup: backupCommand, restore: restoreCommand, terminal: terminalCommand, bridge: bridgeCommand };
|
|
15
52
|
const [command, ...args] = process.argv.slice(2);
|
|
16
53
|
try {
|
|
17
|
-
if (
|
|
18
|
-
|
|
54
|
+
if (command === '--version') {
|
|
55
|
+
// Published builds inject their package version; source execution reads the same metadata.
|
|
56
|
+
console.log(alpVersion());
|
|
57
|
+
} else {
|
|
58
|
+
if (!Object.hasOwn(commands, command)) throw new UsageError();
|
|
59
|
+
// Effort checks read the catalog alpd last cached, the rows alpd itself checks with (t-086c), so
|
|
60
|
+
// the CLI and alpd agree on a model only live rows list (t-b3cd #8). No provider is asked.
|
|
61
|
+
if (command !== 'setup') useLiveModels(catalogModels(alpHome()));
|
|
62
|
+
await commands[command](args);
|
|
63
|
+
}
|
|
19
64
|
} catch (error) {
|
|
20
65
|
if (error instanceof UsageError || error?.code === 'ERR_PARSE_ARGS_UNKNOWN_OPTION') console.error(USAGE);
|
|
21
66
|
else console.error(`alp: ${scrubText(error?.message ?? error)}`);
|
package/src/daemon.js
CHANGED
|
@@ -2,22 +2,23 @@ import { access } from 'node:fs/promises';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { installedProgram, installService, serviceFor, uninstallService } from '@anhlp/alp-client/service';
|
|
4
4
|
import { holdDaemon, startDaemon } from '@anhlp/alp-client/supervise';
|
|
5
|
-
import { alpHome, connect, lockAlive, readLock } from '@anhlp/alp-client/index';
|
|
5
|
+
import { alpHome, connect, daemonStartTimeoutMs, lockAlive, readLock, withDaemonLifecycle } from '@anhlp/alp-client/index';
|
|
6
6
|
import { scrubText } from '@anhlp/alp-core/log';
|
|
7
7
|
import { UsageError } from './usage.js';
|
|
8
|
-
import { DAEMON_ENTRY } from './paths.js';
|
|
8
|
+
import { DAEMON_ENTRY, DAEMON_SCRIPT } from './paths.js';
|
|
9
|
+
import { runRole } from './roles.js';
|
|
9
10
|
|
|
10
|
-
async function built() {
|
|
11
|
+
async function built(entry = DAEMON_ENTRY) {
|
|
11
12
|
try {
|
|
12
|
-
await access(
|
|
13
|
+
await access(entry);
|
|
13
14
|
} catch {
|
|
14
|
-
throw new Error(`alpd is not built (${
|
|
15
|
+
throw new Error(`alpd is not built (${entry}); run npm run build`);
|
|
15
16
|
}
|
|
16
17
|
}
|
|
17
18
|
|
|
18
|
-
/** Waits until an alpd for this home is ready; returns its socket. */
|
|
19
|
+
/** Waits until an alpd for this home is ready; returns its socket. Default wait: ALP_DAEMON_START_TIMEOUT_MS, else 60 s. */
|
|
19
20
|
|
|
20
|
-
async function ready(timeoutMs =
|
|
21
|
+
async function ready(timeoutMs = daemonStartTimeoutMs()) {
|
|
21
22
|
const deadline = Date.now() + timeoutMs;
|
|
22
23
|
while (Date.now() < deadline) {
|
|
23
24
|
const lock = await readLock(alpHome());
|
|
@@ -60,15 +61,23 @@ async function stop() {
|
|
|
60
61
|
}
|
|
61
62
|
|
|
62
63
|
async function daemon([action, ...rest]) {
|
|
64
|
+
// alpd itself in this process (alpd.js on this Node, even where the bundle ships the native alpd);
|
|
65
|
+
// its own options (--detach, --service, --startup-timeout=MS) follow.
|
|
66
|
+
if (action === 'run') { await built(DAEMON_SCRIPT); return runRole('daemon', DAEMON_SCRIPT, rest); }
|
|
63
67
|
if (rest.length && !(action === 'status' && rest.length === 1 && rest[0] === '--json')) throw new UsageError();
|
|
64
68
|
if (action === 'start') {
|
|
65
69
|
const socket = await start();
|
|
66
70
|
const lock = await readLock(alpHome());
|
|
67
71
|
console.log(`alpd ${lock.version} running (pid ${lock.pid}) on ${socket}`);
|
|
68
72
|
} else if (action === 'stop') {
|
|
69
|
-
|
|
70
|
-
//
|
|
73
|
+
// Publish intent before waiting for a launch, then drain that launch before
|
|
74
|
+
// reading its lock. No detached child can arrive after this stop resolves.
|
|
71
75
|
await holdDaemon(alpHome());
|
|
76
|
+
const stopped = await withDaemonLifecycle(alpHome(), 'stop', async () => {
|
|
77
|
+
const stopped = await stop();
|
|
78
|
+
await holdDaemon(alpHome());
|
|
79
|
+
return stopped;
|
|
80
|
+
});
|
|
72
81
|
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
82
|
} else if (action === 'restart') {
|
|
74
83
|
const client = await running().catch(() => undefined);
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { chmod, link, lstat, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { migrateDashboardSettings } from '@anhlp/alp-core/user-settings';
|
|
5
|
+
import { DASHBOARD, LEGACY_WEB, refusal, serviceOwner, stopService } from './dashboard-service.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The move from `alp web` (0.0.1-beta.8 and earlier) to `alp dashboard` (t-81b0.5), run by every
|
|
9
|
+
* `alp dashboard` command before it reads or starts anything. An install keeps its token, its port
|
|
10
|
+
* and its enabled/disabled setting:
|
|
11
|
+
*
|
|
12
|
+
* 1. alp web still running under `integrations/web.lock` (or the Paseo integration from before its
|
|
13
|
+
* own rename, which held the same lock) is stopped, with the same proofs `alp dashboard --stop`
|
|
14
|
+
* uses; a holder that cannot be proven is left running and nothing below is moved, since it
|
|
15
|
+
* may still write the old files.
|
|
16
|
+
* 2. `<home>/web/` (alp web's credential store) becomes `<home>/dashboard/`.
|
|
17
|
+
* 3. `<home>/web.json` written by alp web (`app: 'alp-web'`) becomes `<home>/dashboard.json`, keeping
|
|
18
|
+
* its token and credential id; one without `app` is the Paseo integration's identity and is left
|
|
19
|
+
* for the service to carry into paseo.json, as before.
|
|
20
|
+
* 4. `logs/integrations/alp-web.log` becomes `alp-dashboard.log`.
|
|
21
|
+
* 5. settings.json: `web.enabled`, `web.port` and `web.permissions` move to `dashboard.*`
|
|
22
|
+
* (`web.relay`, Paseo's, stays); see migrateDashboardSettings.
|
|
23
|
+
*
|
|
24
|
+
* Every step only moves an old name onto a missing new one, so a second run does nothing and a home
|
|
25
|
+
* that has both keeps the new one untouched (the old one is reported, never merged or deleted).
|
|
26
|
+
* Steps that race another `alp dashboard` lose cleanly: a rename or link that finds its source gone
|
|
27
|
+
* or its target present is skipped.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/** @param {string} file */
|
|
31
|
+
const exists = file => lstat(file).then(() => true, () => false);
|
|
32
|
+
/** A file's JSON, or undefined when it is missing or not JSON. @param {string} file */
|
|
33
|
+
const readJson = file => readFile(file, 'utf8').then(text => { try { return JSON.parse(text); } catch { return undefined; } }, () => undefined);
|
|
34
|
+
/** @param {unknown} error */
|
|
35
|
+
const code = error => /** @type {any} */ (error)?.code;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* @param {string} home
|
|
39
|
+
* @param {{ strict?: boolean }} [options] strict: a legacy holder alp cannot stop is an error (a start
|
|
40
|
+
* would otherwise lose its port to it); without it, it is reported and the files are left alone.
|
|
41
|
+
* @returns {Promise<{ stopped?: number, held?: boolean, moved: string[], kept: string[], warnings: string[] }>}
|
|
42
|
+
* held: a legacy holder alp would not stop is still running (only without strict).
|
|
43
|
+
*/
|
|
44
|
+
export async function migrateDashboard(home, { strict = false } = {}) {
|
|
45
|
+
/** @type {{ stopped?: number, held?: boolean, moved: string[], kept: string[], warnings: string[] }} */
|
|
46
|
+
const report = { moved: [], kept: [], warnings: [] };
|
|
47
|
+
|
|
48
|
+
// 1. The service from before the rename.
|
|
49
|
+
const owner = await serviceOwner(home, LEGACY_WEB);
|
|
50
|
+
if ('pid' in owner || (owner.alive && owner.kind === 'transient')) {
|
|
51
|
+
try { report.stopped = await stopService(home, 30_000, LEGACY_WEB); }
|
|
52
|
+
catch (error) {
|
|
53
|
+
if (strict) throw error;
|
|
54
|
+
report.warnings.push(/** @type {any} */ (error)?.message ?? String(error));
|
|
55
|
+
report.held = true;
|
|
56
|
+
return report;
|
|
57
|
+
}
|
|
58
|
+
} else if (owner.alive) {
|
|
59
|
+
const message = `${refusal(home, LEGACY_WEB)} (${owner.reason}); stop it, then run the command again`;
|
|
60
|
+
if (strict) throw new Error(message);
|
|
61
|
+
report.warnings.push(message);
|
|
62
|
+
report.held = true;
|
|
63
|
+
return report;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// 2. The credential store.
|
|
67
|
+
const oldStore = path.join(home, 'web');
|
|
68
|
+
const newStore = path.join(home, 'dashboard');
|
|
69
|
+
if (await exists(path.join(oldStore, 'credentials.json'))) {
|
|
70
|
+
if (await exists(newStore)) report.kept.push(oldStore);
|
|
71
|
+
else {
|
|
72
|
+
try { await rename(oldStore, newStore); report.moved.push(`${oldStore} -> ${newStore}`); }
|
|
73
|
+
catch (error) { if (!['ENOENT', 'EEXIST', 'ENOTEMPTY'].includes(code(error))) throw error; }
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// 3. What the service published.
|
|
78
|
+
const oldInfo = path.join(home, LEGACY_WEB.info);
|
|
79
|
+
const newInfo = path.join(home, DASHBOARD.info);
|
|
80
|
+
const published = await readJson(oldInfo);
|
|
81
|
+
if (published?.app === LEGACY_WEB.app) {
|
|
82
|
+
// The same token in dashboard.json: this file was already carried (by an earlier or a concurrent
|
|
83
|
+
// run, or a crash after the link), so the old one is only a copy.
|
|
84
|
+
const carriedAlready = async () => typeof published.token === 'string' && published.token !== '' && (await readJson(newInfo))?.token === published.token;
|
|
85
|
+
const removeOld = () => unlink(oldInfo).catch(error => { if (code(error) !== 'ENOENT') throw error; });
|
|
86
|
+
if (await exists(newInfo)) {
|
|
87
|
+
if (await carriedAlready()) await removeOld();
|
|
88
|
+
else report.kept.push(oldInfo);
|
|
89
|
+
} else {
|
|
90
|
+
// Only what the next start reuses; the old pid, port and URL died with the old service.
|
|
91
|
+
const carried = { version: published.version, app: DASHBOARD.app, token: published.token, credentialId: published.credentialId };
|
|
92
|
+
const temporary = `${newInfo}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
93
|
+
try {
|
|
94
|
+
await writeFile(temporary, `${JSON.stringify(carried)}\n`, { mode: 0o600, flag: 'wx' });
|
|
95
|
+
await chmod(temporary, 0o600);
|
|
96
|
+
// A link never replaces: a dashboard.json written meanwhile wins, and the old file is
|
|
97
|
+
// removed only when that one carries the same token.
|
|
98
|
+
const linked = await link(temporary, newInfo).then(() => true, error => { if (code(error) !== 'EEXIST') throw error; return false; });
|
|
99
|
+
if (linked) { report.moved.push(`${oldInfo} -> ${newInfo}`); await removeOld(); }
|
|
100
|
+
else if (await carriedAlready()) await removeOld();
|
|
101
|
+
else report.kept.push(oldInfo);
|
|
102
|
+
} finally { await unlink(temporary).catch(() => {}); }
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// 4. The service's log.
|
|
107
|
+
const logs = path.join(home, 'logs', 'integrations');
|
|
108
|
+
const oldLog = path.join(logs, 'alp-web.log');
|
|
109
|
+
const newLog = path.join(logs, 'alp-dashboard.log');
|
|
110
|
+
if (await exists(oldLog) && !(await exists(newLog))) {
|
|
111
|
+
await rename(oldLog, newLog).then(() => report.moved.push(`${oldLog} -> ${newLog}`), error => { if (code(error) !== 'ENOENT') throw error; });
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// 5. Settings. A file alp cannot rewrite (invalid, read-only) is still obeyed: dashboardSettings
|
|
115
|
+
// reads `web.*` where `dashboard.*` is not set.
|
|
116
|
+
try {
|
|
117
|
+
const settings = await migrateDashboardSettings(home);
|
|
118
|
+
for (const key of settings.moved) report.moved.push(`settings.json web.${key} -> dashboard.${key}`);
|
|
119
|
+
for (const key of settings.conflicts) report.kept.push(`settings.json web.${key} (dashboard.${key} is set and wins)`);
|
|
120
|
+
} catch (error) {
|
|
121
|
+
report.warnings.push(`settings.json was not migrated (web.* is still read): ${/** @type {any} */ (error)?.message ?? error}`);
|
|
122
|
+
}
|
|
123
|
+
return report;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* What a home still has under the names from before the rename, without changing anything (for
|
|
128
|
+
* `alp dashboard --status`): `pending` the next `alp dashboard` moves, `kept` it leaves because the
|
|
129
|
+
* new name exists, and the legacy service if one runs.
|
|
130
|
+
* @param {string} home
|
|
131
|
+
* @returns {Promise<{ legacy?: { pid?: number, reason?: string }, pending: string[], kept: string[] }>}
|
|
132
|
+
*/
|
|
133
|
+
export async function legacyLeftovers(home) {
|
|
134
|
+
/** @type {{ legacy?: { pid?: number, reason?: string }, pending: string[], kept: string[] }} */
|
|
135
|
+
const result = { pending: [], kept: [] };
|
|
136
|
+
const owner = await serviceOwner(home, LEGACY_WEB);
|
|
137
|
+
if ('pid' in owner) result.legacy = { pid: owner.pid };
|
|
138
|
+
else if (owner.alive) result.legacy = { reason: owner.reason };
|
|
139
|
+
const place = async (/** @type {string} */ old, /** @type {string} */ current) => (await exists(current) ? result.kept : result.pending).push(old);
|
|
140
|
+
if (await exists(path.join(home, 'web', 'credentials.json'))) await place(path.join(home, 'web'), path.join(home, 'dashboard'));
|
|
141
|
+
const published = await readJson(path.join(home, LEGACY_WEB.info));
|
|
142
|
+
if (published?.app === LEGACY_WEB.app) await place(path.join(home, LEGACY_WEB.info), path.join(home, DASHBOARD.info));
|
|
143
|
+
const logs = path.join(home, 'logs', 'integrations');
|
|
144
|
+
if (await exists(path.join(logs, 'alp-web.log'))) await place(path.join(logs, 'alp-web.log'), path.join(logs, 'alp-dashboard.log'));
|
|
145
|
+
const settings = await readJson(path.join(home, 'settings.json'));
|
|
146
|
+
for (const key of ['enabled', 'port', 'permissions']) {
|
|
147
|
+
if (settings?.web?.[key] === undefined) continue;
|
|
148
|
+
if (settings?.dashboard?.[key] !== undefined) result.kept.push(`settings.json web.${key} (dashboard.${key} is set and wins)`);
|
|
149
|
+
else result.pending.push(`settings.json web.${key}`);
|
|
150
|
+
}
|
|
151
|
+
return result;
|
|
152
|
+
}
|