@agentage/cli 0.51.0 → 0.52.0
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/README.md +95 -127
- package/dist/commands/auth/setup.d.ts +2 -0
- package/dist/commands/auth/setup.js +4 -1
- package/dist/commands/daemon/daemon.d.ts +38 -0
- package/dist/commands/daemon/daemon.js +75 -0
- package/dist/commands/daemon/installer.d.ts +11 -0
- package/dist/commands/daemon/installer.js +87 -0
- package/dist/commands/daemon/move-plan.d.ts +17 -0
- package/dist/commands/daemon/move-plan.js +67 -0
- package/dist/commands/daemon/move-settings.d.ts +5 -0
- package/dist/commands/daemon/move-settings.js +50 -0
- package/dist/commands/daemon/move.d.ts +17 -0
- package/dist/commands/daemon/move.js +106 -0
- package/dist/commands/daemon/run.d.ts +6 -0
- package/dist/commands/daemon/run.js +36 -0
- package/dist/commands/extension/build.d.ts +13 -4
- package/dist/commands/extension/build.js +67 -25
- package/dist/commands/extension/configure.d.ts +26 -0
- package/dist/commands/extension/configure.js +100 -0
- package/dist/commands/extension/create-install.d.ts +26 -0
- package/dist/commands/extension/create-install.js +81 -0
- package/dist/commands/extension/create.d.ts +6 -1
- package/dist/commands/extension/create.js +58 -16
- package/dist/commands/extension/delegate.js +3 -1
- package/dist/commands/extension/doctor.d.ts +1 -1
- package/dist/commands/extension/doctor.js +8 -7
- package/dist/commands/extension/install-once.d.ts +17 -0
- package/dist/commands/extension/install-once.js +57 -0
- package/dist/commands/extension/kit-tool.d.ts +1 -1
- package/dist/commands/extension/lifecycle-commands.d.ts +19 -0
- package/dist/commands/extension/lifecycle-commands.js +80 -0
- package/dist/commands/extension/lifecycle-list.d.ts +26 -0
- package/dist/commands/extension/lifecycle-list.js +92 -0
- package/dist/commands/extension/lifecycle.d.ts +41 -0
- package/dist/commands/extension/lifecycle.js +142 -0
- package/dist/commands/extension/line.d.ts +1 -0
- package/dist/commands/extension/line.js +2 -0
- package/dist/commands/extension/list.d.ts +4 -14
- package/dist/commands/extension/list.js +11 -95
- package/dist/commands/extension/package-build.d.ts +15 -0
- package/dist/commands/extension/package-build.js +51 -0
- package/dist/commands/extension/plan.d.ts +4 -2
- package/dist/commands/extension/plan.js +37 -37
- package/dist/commands/extension/profile-plan.d.ts +16 -0
- package/dist/commands/extension/profile-plan.js +48 -0
- package/dist/commands/extension/release.d.ts +2 -1
- package/dist/commands/extension/release.js +10 -9
- package/dist/commands/extension/row-lines.d.ts +1 -2
- package/dist/commands/extension/row-lines.js +5 -6
- package/dist/commands/extension/rows.js +6 -4
- package/dist/commands/extension/setup-cloud.d.ts +2 -2
- package/dist/commands/extension/setup-cloud.js +6 -5
- package/dist/commands/extension/setup-install.d.ts +8 -0
- package/dist/commands/extension/setup-install.js +56 -0
- package/dist/commands/extension/setup.d.ts +4 -1
- package/dist/commands/extension/setup.js +56 -18
- package/dist/commands/extension/stack-owner.d.ts +4 -0
- package/dist/commands/extension/stack-owner.js +45 -0
- package/dist/commands/extension/sync.d.ts +6 -11
- package/dist/commands/extension/sync.js +8 -50
- package/dist/commands/extension/up-commands.d.ts +9 -0
- package/dist/commands/extension/up-commands.js +74 -0
- package/dist/commands/extension/up-local.d.ts +21 -0
- package/dist/commands/extension/up-local.js +94 -0
- package/dist/commands/extension/up-run.d.ts +23 -0
- package/dist/commands/extension/up-run.js +75 -0
- package/dist/commands/extension/up.d.ts +12 -11
- package/dist/commands/extension/up.js +65 -71
- package/dist/commands/update/update.d.ts +9 -1
- package/dist/commands/update/update.js +20 -6
- package/dist/core/installer/compare-lock.d.ts +0 -2
- package/dist/core/installer/compare-lock.js +0 -12
- package/dist/core/installer/compat.js +5 -3
- package/dist/core/installer/npm.d.ts +1 -0
- package/dist/core/installer/npm.js +6 -0
- package/dist/core/installer/old-tree.d.ts +3 -0
- package/dist/core/installer/old-tree.js +45 -0
- package/dist/core/installer/package-dir.d.ts +11 -0
- package/dist/core/installer/package-dir.js +53 -0
- package/dist/core/installer/resolve.js +1 -2
- package/dist/core/installer/tree.d.ts +0 -5
- package/dist/core/installer/tree.js +1 -25
- package/dist/core/kit-id.d.ts +1 -0
- package/dist/core/kit-id.js +20 -0
- package/dist/core/loader/discover.d.ts +7 -1
- package/dist/core/loader/discover.js +5 -4
- package/dist/core/loader/installed.d.ts +9 -0
- package/dist/core/loader/installed.js +51 -0
- package/dist/core/loader/manifest.d.ts +4 -0
- package/dist/core/loader/manifest.js +25 -3
- package/dist/core/loader/scan.d.ts +2 -1
- package/dist/core/loader/scan.js +17 -4
- package/dist/core/loader/secrets.d.ts +0 -7
- package/dist/core/loader/secrets.js +0 -11
- package/dist/core/loader/verbs.d.ts +0 -1
- package/dist/core/loader/verbs.js +1 -13
- package/dist/core/profile/machine.d.ts +0 -1
- package/dist/core/profile/machine.js +0 -5
- package/dist/lib/auth/introspect.js +1 -2
- package/dist/lib/auth/sign-in.js +3 -0
- package/dist/lib/child-env.d.ts +1 -0
- package/dist/lib/child-env.js +6 -0
- package/dist/lib/daemon/daemon-answer.d.ts +8 -0
- package/dist/lib/daemon/daemon-answer.js +38 -0
- package/dist/lib/daemon/daemon-client.d.ts +17 -0
- package/dist/lib/daemon/daemon-client.js +112 -0
- package/dist/lib/daemon/daemon-file.d.ts +16 -0
- package/dist/lib/daemon/daemon-file.js +30 -0
- package/dist/lib/daemon/daemon-health.d.ts +16 -0
- package/dist/lib/daemon/daemon-health.js +36 -0
- package/dist/lib/daemon/daemon-probe.d.ts +32 -0
- package/dist/lib/daemon/daemon-probe.js +41 -0
- package/dist/lib/daemon/daemon-stop.d.ts +13 -0
- package/dist/lib/daemon/daemon-stop.js +42 -0
- package/dist/lib/daemon/host-client.d.ts +40 -0
- package/dist/lib/daemon/host-client.js +45 -0
- package/dist/lib/exit-code.d.ts +2 -0
- package/dist/lib/exit-code.js +8 -0
- package/dist/lib/fs/json-file.d.ts +1 -0
- package/dist/lib/fs/json-file.js +1 -1
- package/dist/lib/json-output.d.ts +36 -0
- package/dist/lib/json-output.js +163 -0
- package/dist/lib/net/market-error.d.ts +12 -0
- package/dist/lib/net/market-error.js +28 -0
- package/dist/lib/net/market.d.ts +17 -2
- package/dist/lib/net/market.js +92 -18
- package/dist/lib/wait.d.ts +6 -0
- package/dist/lib/wait.js +17 -0
- package/dist/lib/with-action.d.ts +12 -0
- package/dist/lib/with-action.js +33 -0
- package/dist/program-deps.d.ts +2 -0
- package/dist/program-deps.js +95 -0
- package/dist/program.d.ts +29 -21
- package/dist/program.js +41 -75
- package/package.json +8 -6
- package/CHANGELOG.md +0 -68
- package/dist/commands/extension/install-load.d.ts +0 -7
- package/dist/commands/extension/install-load.js +0 -42
- package/dist/commands/extension/install.d.ts +0 -12
- package/dist/commands/extension/install.js +0 -49
- package/dist/commands/extension/latest.d.ts +0 -2
- package/dist/commands/extension/latest.js +0 -71
- package/dist/commands/extension/remove.d.ts +0 -15
- package/dist/commands/extension/remove.js +0 -86
- package/dist/commands/extension/secrets-prompt.d.ts +0 -6
- package/dist/commands/extension/secrets-prompt.js +0 -47
- package/dist/core/installer/installer.d.ts +0 -28
- package/dist/core/installer/installer.js +0 -87
- package/dist/core/installer/latest.d.ts +0 -27
- package/dist/core/installer/latest.js +0 -90
- package/dist/core/profile/edit.d.ts +0 -4
- package/dist/core/profile/edit.js +0 -27
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { closeSync, mkdirSync, openSync, renameSync, statSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { childEnv } from '../child-env.js';
|
|
6
|
+
import { getConfigDir } from '../fs/config.js';
|
|
7
|
+
import { CliError } from '../json-output.js';
|
|
8
|
+
import { compareVersions } from '../update/update-check.js';
|
|
9
|
+
import { VERSION } from '../../utils/version.js';
|
|
10
|
+
import { waitFor } from '../wait.js';
|
|
11
|
+
import { daemonOff, daemonPort, EADDRINUSE_EXIT, isAlive, readDaemonFile, removeDaemonFile, } from './daemon-file.js';
|
|
12
|
+
import { portInUse, probe, probeRetry, PROGRESS_MS, PROTOCOL, proven, unresponsive, } from './daemon-probe.js';
|
|
13
|
+
import { stopDaemon } from './daemon-stop.js';
|
|
14
|
+
const START_MS = 30_000;
|
|
15
|
+
// Over this the log moves to daemon.log.1 at the next start; one old file is kept.
|
|
16
|
+
export const LOG_CAP = 5 * 1024 * 1024;
|
|
17
|
+
export const waitForHealth = (port, timeoutMs = START_MS) => waitFor(async () => (await probe(port, 500)).kind === 'ours', timeoutMs, {
|
|
18
|
+
afterMs: PROGRESS_MS,
|
|
19
|
+
line: `waiting for the daemon to start on 127.0.0.1:${port}...`,
|
|
20
|
+
});
|
|
21
|
+
const CLI_ENTRY = fileURLToPath(new URL('../../cli.js', import.meta.url));
|
|
22
|
+
export const daemonLogPath = () => join(getConfigDir(), 'logs', 'daemon.log');
|
|
23
|
+
// The daemon's own output (each child's too), so a start that fails can be read later.
|
|
24
|
+
export const openDaemonLog = (cap = LOG_CAP) => {
|
|
25
|
+
const path = daemonLogPath();
|
|
26
|
+
mkdirSync(join(getConfigDir(), 'logs'), { recursive: true, mode: 0o700 });
|
|
27
|
+
const size = statSync(path, { throwIfNoEntry: false })?.size ?? 0;
|
|
28
|
+
if (size > cap)
|
|
29
|
+
renameSync(path, `${path}.1`);
|
|
30
|
+
return openSync(path, 'a', 0o600);
|
|
31
|
+
};
|
|
32
|
+
// Detached in its own process group, so it outlives this cli; the first to exit or answer wins.
|
|
33
|
+
export const spawnDaemon = async (port, entry = CLI_ENTRY) => {
|
|
34
|
+
const out = openDaemonLog();
|
|
35
|
+
const child = spawn(process.execPath, [entry, 'daemon', 'run'], {
|
|
36
|
+
detached: true,
|
|
37
|
+
stdio: ['ignore', out, out],
|
|
38
|
+
env: { ...childEnv(), AGENTAGE_DAEMON_PORT: String(port) },
|
|
39
|
+
});
|
|
40
|
+
closeSync(out);
|
|
41
|
+
const exited = new Promise((resolve) => child.once('exit', (code) => resolve(code === EADDRINUSE_EXIT ? 'port-in-use' : 'unreachable')));
|
|
42
|
+
child.unref();
|
|
43
|
+
const healthy = waitForHealth(port).then((ok) => (ok ? 'ok' : 'unreachable'));
|
|
44
|
+
return Promise.race([healthy, exited]);
|
|
45
|
+
};
|
|
46
|
+
export const defaultEnsureDeps = {
|
|
47
|
+
probe: (port) => probeRetry(port),
|
|
48
|
+
spawn: (port) => spawnDaemon(port),
|
|
49
|
+
stop: () => stopDaemon(),
|
|
50
|
+
log: (line) => console.error(line),
|
|
51
|
+
};
|
|
52
|
+
// A start that timed out may still have come up late: a proven daemon in daemon.json serves.
|
|
53
|
+
const lateDaemon = async (deps) => {
|
|
54
|
+
const file = readDaemonFile();
|
|
55
|
+
return file && proven(file, await deps.probe(file.port)) ? file.port : null;
|
|
56
|
+
};
|
|
57
|
+
const notStarted = () => new CliError('daemon_unavailable', `the daemon did not start: it did not answer; see agentage daemon status and ${daemonLogPath()}`);
|
|
58
|
+
// Another cli may have started one on the same port at the same time: that one serves.
|
|
59
|
+
const start = async (deps, port) => {
|
|
60
|
+
const outcome = await deps.spawn(port);
|
|
61
|
+
if (outcome === 'port-in-use') {
|
|
62
|
+
if ((await deps.probe(port)).kind === 'ours')
|
|
63
|
+
return port;
|
|
64
|
+
throw portInUse(port);
|
|
65
|
+
}
|
|
66
|
+
if (outcome !== 'ok') {
|
|
67
|
+
const late = await lateDaemon(deps);
|
|
68
|
+
if (late === null)
|
|
69
|
+
throw notStarted();
|
|
70
|
+
return late;
|
|
71
|
+
}
|
|
72
|
+
deps.log(`daemon started on 127.0.0.1:${port}`);
|
|
73
|
+
return port;
|
|
74
|
+
};
|
|
75
|
+
// Restart only for another protocol or an older daemon: a newer one serves as it is.
|
|
76
|
+
const outdated = (health) => health.protocol !== PROTOCOL || compareVersions(health.version, VERSION) < 0;
|
|
77
|
+
// daemon.json's daemon when proven; a dead pid, or a live one whose port refuses, is a stale file.
|
|
78
|
+
const fromFile = async (file, deps) => {
|
|
79
|
+
if (!isAlive(file.pid))
|
|
80
|
+
return (removeDaemonFile(), null);
|
|
81
|
+
const found = await deps.probe(file.port);
|
|
82
|
+
if (found.kind === 'silent')
|
|
83
|
+
throw unresponsive(file);
|
|
84
|
+
// daemon.json is written after the daemon listens: a refused port means a reused pid.
|
|
85
|
+
if (found.kind === 'none')
|
|
86
|
+
return (removeDaemonFile(), null);
|
|
87
|
+
const health = proven(file, found);
|
|
88
|
+
if (!health)
|
|
89
|
+
throw portInUse(file.port);
|
|
90
|
+
if (!outdated(health))
|
|
91
|
+
return file.port;
|
|
92
|
+
await deps.stop();
|
|
93
|
+
const port = await start({ ...deps, log: () => undefined }, daemonPort());
|
|
94
|
+
deps.log(`daemon restarted: it ran ${health.version}, this cli is ${VERSION}`);
|
|
95
|
+
return port;
|
|
96
|
+
};
|
|
97
|
+
export const ensureDaemon = async (deps = defaultEnsureDeps) => {
|
|
98
|
+
if (daemonOff())
|
|
99
|
+
throw new CliError('daemon_disabled', 'AGENTAGE_NO_DAEMON=1 is set: no daemon is used');
|
|
100
|
+
const file = readDaemonFile();
|
|
101
|
+
const live = file ? await fromFile(file, deps) : null;
|
|
102
|
+
return live ?? start(deps, daemonPort());
|
|
103
|
+
};
|
|
104
|
+
// After `agentage update`: a daemon that ran stops and starts again from the new files.
|
|
105
|
+
export const restartIfRunning = async (deps = defaultEnsureDeps) => {
|
|
106
|
+
const result = await deps.stop();
|
|
107
|
+
if (result === null || !('stopped' in result))
|
|
108
|
+
return false;
|
|
109
|
+
await start({ ...deps, log: () => undefined }, daemonPort());
|
|
110
|
+
deps.log(`daemon restarted on 127.0.0.1:${daemonPort()}`);
|
|
111
|
+
return true;
|
|
112
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export declare const DEFAULT_DAEMON_PORT = 4243;
|
|
2
|
+
export declare const EADDRINUSE_EXIT = 3;
|
|
3
|
+
export interface DaemonFile {
|
|
4
|
+
pid: number;
|
|
5
|
+
port: number;
|
|
6
|
+
version: string;
|
|
7
|
+
protocol: number;
|
|
8
|
+
startedBy: string;
|
|
9
|
+
}
|
|
10
|
+
export declare const daemonPort: (env?: NodeJS.ProcessEnv) => number;
|
|
11
|
+
export declare const daemonOff: (env?: NodeJS.ProcessEnv) => boolean;
|
|
12
|
+
export declare const daemonFilePath: () => string;
|
|
13
|
+
export declare const isPid: (pid: unknown) => pid is number;
|
|
14
|
+
export declare const readDaemonFile: () => DaemonFile | null;
|
|
15
|
+
export declare const removeDaemonFile: () => void;
|
|
16
|
+
export declare const isAlive: (pid: number) => boolean;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { getConfigDir } from '../fs/config.js';
|
|
3
|
+
import { isRecord, readJson, unlinkQuiet } from '../fs/json-file.js';
|
|
4
|
+
export const DEFAULT_DAEMON_PORT = 4243;
|
|
5
|
+
// `daemon run` exits with this on a busy port, so the cli that spawned it stops waiting at once.
|
|
6
|
+
export const EADDRINUSE_EXIT = 3;
|
|
7
|
+
export const daemonPort = (env = process.env) => {
|
|
8
|
+
const port = Number(env['AGENTAGE_DAEMON_PORT']);
|
|
9
|
+
return Number.isInteger(port) && port > 0 && port < 65536 ? port : DEFAULT_DAEMON_PORT;
|
|
10
|
+
};
|
|
11
|
+
// AGENTAGE_NO_DAEMON=1: no command starts or uses the daemon.
|
|
12
|
+
export const daemonOff = (env = process.env) => env['AGENTAGE_NO_DAEMON'] === '1';
|
|
13
|
+
export const daemonFilePath = () => join(getConfigDir(), 'daemon.json');
|
|
14
|
+
// A pid the cli may signal: 0 and -1 name process groups, 1 is init.
|
|
15
|
+
export const isPid = (pid) => Number.isInteger(pid) && pid > 1;
|
|
16
|
+
const isDaemonFile = (value) => isRecord(value) && isPid(value['pid']) && Number.isInteger(value['port']);
|
|
17
|
+
export const readDaemonFile = () => readJson(daemonFilePath(), isDaemonFile);
|
|
18
|
+
export const removeDaemonFile = () => unlinkQuiet(daemonFilePath());
|
|
19
|
+
// EPERM: the pid lives, under another user.
|
|
20
|
+
export const isAlive = (pid) => {
|
|
21
|
+
if (!isPid(pid))
|
|
22
|
+
return false;
|
|
23
|
+
try {
|
|
24
|
+
process.kill(pid, 0);
|
|
25
|
+
return true;
|
|
26
|
+
}
|
|
27
|
+
catch (err) {
|
|
28
|
+
return err.code === 'EPERM';
|
|
29
|
+
}
|
|
30
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type Health } from './daemon-probe.js';
|
|
2
|
+
export interface PendingChange {
|
|
3
|
+
op: string;
|
|
4
|
+
id?: string;
|
|
5
|
+
source?: string;
|
|
6
|
+
since: string;
|
|
7
|
+
timedOut?: true;
|
|
8
|
+
}
|
|
9
|
+
export interface HealthMarks {
|
|
10
|
+
pending?: PendingChange[];
|
|
11
|
+
unsynced?: string[];
|
|
12
|
+
installation?: 'invalid' | 'unreadable';
|
|
13
|
+
installationError?: string;
|
|
14
|
+
}
|
|
15
|
+
export declare const degradedReasons: (health: Health & HealthMarks) => string[];
|
|
16
|
+
export declare const healthLines: (health: Health & HealthMarks, reasons: string[]) => string[];
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { getConfigDir } from '../fs/config.js';
|
|
4
|
+
import {} from './daemon-probe.js';
|
|
5
|
+
const UNSETTLED = ['starting', 'failed'];
|
|
6
|
+
// The kit keeps a copy only of a file whose rows it refused at boot, not of one that later broke.
|
|
7
|
+
const invalidReason = () => existsSync(join(getConfigDir(), 'installation.json.bad'))
|
|
8
|
+
? 'installation.json is invalid: the daemon kept the bad file as installation.json.bad'
|
|
9
|
+
: 'installation.json is invalid';
|
|
10
|
+
// Why the daemon says degraded: every cause the kit counts, in words; empty when ok.
|
|
11
|
+
export const degradedReasons = (health) => {
|
|
12
|
+
if (health.status === 'ok')
|
|
13
|
+
return [];
|
|
14
|
+
const reasons = health.extensions
|
|
15
|
+
.filter((ext) => UNSETTLED.includes(ext.state))
|
|
16
|
+
.map((ext) => `${ext.id} is ${ext.state}`);
|
|
17
|
+
if (health.unsynced?.length)
|
|
18
|
+
reasons.push(`a change of ${health.unsynced.join(', ')} was not undone: its files disagree`);
|
|
19
|
+
if (health.installation === 'unreadable')
|
|
20
|
+
reasons.push(`installation.json cannot be read (${health.installationError ?? 'no reason'})`);
|
|
21
|
+
if (health.installation === 'invalid')
|
|
22
|
+
reasons.push(invalidReason());
|
|
23
|
+
if (reasons.length === 0)
|
|
24
|
+
reasons.push('the daemon gave no reason');
|
|
25
|
+
return reasons;
|
|
26
|
+
};
|
|
27
|
+
const pendingLine = ({ op, id, source, since, timedOut }) => {
|
|
28
|
+
const late = timedOut ? ', the daemon stopped waiting; it still runs' : '';
|
|
29
|
+
return ` pending ${op} ${id ?? source ?? ''} since ${since}${late}`;
|
|
30
|
+
};
|
|
31
|
+
// The lines under the first one of `daemon status`.
|
|
32
|
+
export const healthLines = (health, reasons) => [
|
|
33
|
+
...health.extensions.map((ext) => ` ${ext.id} ${ext.version} ${ext.state}`),
|
|
34
|
+
...(health.pending ?? []).map(pendingLine),
|
|
35
|
+
...reasons.map((reason) => ` degraded: ${reason}`),
|
|
36
|
+
];
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { CliError } from '../json-output.js';
|
|
2
|
+
import { type DaemonFile } from './daemon-file.js';
|
|
3
|
+
export declare const PROGRESS_MS = 3000;
|
|
4
|
+
export declare const PROTOCOL = 1;
|
|
5
|
+
export declare const DAEMON_SERVICE = "agentage-daemon";
|
|
6
|
+
export interface Health {
|
|
7
|
+
status: string;
|
|
8
|
+
service: string;
|
|
9
|
+
pid: number;
|
|
10
|
+
version: string;
|
|
11
|
+
protocol: number;
|
|
12
|
+
extensions: {
|
|
13
|
+
id: string;
|
|
14
|
+
version: string;
|
|
15
|
+
state: string;
|
|
16
|
+
}[];
|
|
17
|
+
}
|
|
18
|
+
export type Probe = {
|
|
19
|
+
kind: 'ours';
|
|
20
|
+
health: Health;
|
|
21
|
+
} | {
|
|
22
|
+
kind: 'foreign';
|
|
23
|
+
} | {
|
|
24
|
+
kind: 'none';
|
|
25
|
+
} | {
|
|
26
|
+
kind: 'silent';
|
|
27
|
+
};
|
|
28
|
+
export declare const probe: (port: number, timeoutMs?: number) => Promise<Probe>;
|
|
29
|
+
export declare const probeRetry: (port: number, tries?: number, timeoutMs?: number) => Promise<Probe>;
|
|
30
|
+
export declare const proven: (file: DaemonFile, found: Probe) => Health | null;
|
|
31
|
+
export declare const unresponsive: (file: DaemonFile) => CliError;
|
|
32
|
+
export declare const portInUse: (port: number) => CliError;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { isRecord } from '../fs/json-file.js';
|
|
2
|
+
import { CliError } from '../json-output.js';
|
|
3
|
+
import {} from './daemon-file.js';
|
|
4
|
+
// C4/C5: the protocol this cli speaks; a daemon with another one is restarted.
|
|
5
|
+
// A wait longer than this prints one line on stderr, so a slow start or stop does not look hung.
|
|
6
|
+
export const PROGRESS_MS = 3_000;
|
|
7
|
+
export const PROTOCOL = 1;
|
|
8
|
+
export const DAEMON_SERVICE = 'agentage-daemon';
|
|
9
|
+
const isHealth = (body) => isRecord(body) &&
|
|
10
|
+
body['service'] === DAEMON_SERVICE &&
|
|
11
|
+
Number.isInteger(body['pid']) &&
|
|
12
|
+
typeof body['version'] === 'string' &&
|
|
13
|
+
Array.isArray(body['extensions']);
|
|
14
|
+
export const probe = async (port, timeoutMs = 2000) => {
|
|
15
|
+
try {
|
|
16
|
+
const res = await fetch(`http://127.0.0.1:${port}/health`, {
|
|
17
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
18
|
+
});
|
|
19
|
+
const body = await res.json().catch(() => null);
|
|
20
|
+
return isHealth(body) ? { kind: 'ours', health: body } : { kind: 'foreign' };
|
|
21
|
+
}
|
|
22
|
+
catch (err) {
|
|
23
|
+
const refused = err.cause?.code === 'ECONNREFUSED';
|
|
24
|
+
return refused ? { kind: 'none' } : { kind: 'silent' };
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
// A slow daemon is asked again before it counts as silent.
|
|
28
|
+
export const probeRetry = async (port, tries = 3, timeoutMs = 2000) => {
|
|
29
|
+
let last = { kind: 'silent' };
|
|
30
|
+
for (let i = 0; i < tries; i += 1) {
|
|
31
|
+
last = await probe(port, timeoutMs);
|
|
32
|
+
if (last.kind !== 'silent')
|
|
33
|
+
return last;
|
|
34
|
+
}
|
|
35
|
+
return last;
|
|
36
|
+
};
|
|
37
|
+
// The proof that daemon.json names a daemon of ours: its port answers with the same pid.
|
|
38
|
+
export const proven = (file, found) => found.kind === 'ours' && found.health.pid === file.pid ? found.health : null;
|
|
39
|
+
export const unresponsive = (file) => new CliError('daemon_unresponsive', `the daemon (pid ${file.pid}) does not answer on 127.0.0.1:${file.port}; ` +
|
|
40
|
+
'try again, or stop that process yourself');
|
|
41
|
+
export const portInUse = (port) => new CliError('port_in_use', `port ${port} is in use by another program; free it, or set AGENTAGE_DAEMON_PORT to another port`);
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type Probe } from './daemon-probe.js';
|
|
2
|
+
export type StopResult = {
|
|
3
|
+
stopped: number;
|
|
4
|
+
} | {
|
|
5
|
+
stale: number;
|
|
6
|
+
} | null;
|
|
7
|
+
export interface StopDeps {
|
|
8
|
+
probe: (port: number) => Promise<Probe>;
|
|
9
|
+
timeoutMs: number;
|
|
10
|
+
progressMs?: number;
|
|
11
|
+
killMs?: number;
|
|
12
|
+
}
|
|
13
|
+
export declare const stopDaemon: (deps?: StopDeps) => Promise<StopResult>;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { CliError } from '../json-output.js';
|
|
2
|
+
import { isAlive, readDaemonFile, removeDaemonFile } from './daemon-file.js';
|
|
3
|
+
import { waitFor } from '../wait.js';
|
|
4
|
+
import { PROGRESS_MS, probeRetry, proven, unresponsive } from './daemon-probe.js';
|
|
5
|
+
// The daemon drains each child for up to 10 s; past this it is killed.
|
|
6
|
+
const STOP_MS = 30_000;
|
|
7
|
+
const gone = (pid, timeoutMs, afterMs = PROGRESS_MS) => waitFor(() => !isAlive(pid), timeoutMs, {
|
|
8
|
+
afterMs,
|
|
9
|
+
line: `waiting for the daemon (pid ${pid}) to stop...`,
|
|
10
|
+
});
|
|
11
|
+
const signal = (pid, name) => {
|
|
12
|
+
try {
|
|
13
|
+
process.kill(pid, name);
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
// exited in between
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
const DEPS = { probe: (port) => probeRetry(port), timeoutMs: STOP_MS };
|
|
20
|
+
// Said only once the pid is gone; a pid that outlives SIGKILL keeps daemon.json, so it stays known.
|
|
21
|
+
const stillThere = (pid) => new CliError('stop_failed', `the daemon (pid ${pid}) did not stop, not even on SIGKILL`);
|
|
22
|
+
// A pid is signalled only when its own port answers as our daemon with that pid.
|
|
23
|
+
export const stopDaemon = async (deps = DEPS) => {
|
|
24
|
+
const file = readDaemonFile();
|
|
25
|
+
if (!file)
|
|
26
|
+
return null;
|
|
27
|
+
if (!isAlive(file.pid))
|
|
28
|
+
return (removeDaemonFile(), { stale: file.pid });
|
|
29
|
+
const found = await deps.probe(file.port);
|
|
30
|
+
if (found.kind === 'silent')
|
|
31
|
+
throw unresponsive(file);
|
|
32
|
+
if (!proven(file, found))
|
|
33
|
+
return (removeDaemonFile(), { stale: file.pid });
|
|
34
|
+
signal(file.pid, 'SIGTERM');
|
|
35
|
+
if (!(await gone(file.pid, deps.timeoutMs, deps.progressMs))) {
|
|
36
|
+
signal(file.pid, 'SIGKILL');
|
|
37
|
+
if (!(await gone(file.pid, deps.killMs ?? 5_000)))
|
|
38
|
+
throw stillThere(file.pid);
|
|
39
|
+
}
|
|
40
|
+
removeDaemonFile();
|
|
41
|
+
return { stopped: file.pid };
|
|
42
|
+
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export interface HostRow {
|
|
2
|
+
id: string;
|
|
3
|
+
version: string;
|
|
4
|
+
source: string;
|
|
5
|
+
state: string;
|
|
6
|
+
enabled: boolean;
|
|
7
|
+
error?: string;
|
|
8
|
+
[key: string]: unknown;
|
|
9
|
+
}
|
|
10
|
+
export interface HostSummary {
|
|
11
|
+
id: string;
|
|
12
|
+
version: string;
|
|
13
|
+
state: string;
|
|
14
|
+
error?: string;
|
|
15
|
+
}
|
|
16
|
+
export interface HostPatch {
|
|
17
|
+
version?: string;
|
|
18
|
+
enabled?: boolean;
|
|
19
|
+
settings?: Record<string, string>;
|
|
20
|
+
secrets?: Record<string, string>;
|
|
21
|
+
}
|
|
22
|
+
export interface HostClient {
|
|
23
|
+
list: () => Promise<HostRow[]>;
|
|
24
|
+
add: (body: ({
|
|
25
|
+
id: string;
|
|
26
|
+
version?: string;
|
|
27
|
+
} | {
|
|
28
|
+
source: string;
|
|
29
|
+
}) & {
|
|
30
|
+
enabled?: false;
|
|
31
|
+
}) => Promise<HostSummary>;
|
|
32
|
+
change: (id: string, patch: HostPatch) => Promise<HostSummary>;
|
|
33
|
+
remove: (id: string, purge: boolean) => Promise<{
|
|
34
|
+
id: string;
|
|
35
|
+
}>;
|
|
36
|
+
}
|
|
37
|
+
export declare const hostClient: (port: number, waits?: {
|
|
38
|
+
read: number;
|
|
39
|
+
change: number;
|
|
40
|
+
}) => HostClient;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { isRecord } from '../fs/json-file.js';
|
|
2
|
+
import { CliError, messageOf } from '../json-output.js';
|
|
3
|
+
import { daemonFailure } from './daemon-answer.js';
|
|
4
|
+
// An install runs npm (up to 10 min in the daemon), then starts the child: past that it is stuck.
|
|
5
|
+
const WAITS = { read: 10_000, change: 12 * 60_000 };
|
|
6
|
+
// The kit's queue and installer can each take 11 min, so a change can still finish after this
|
|
7
|
+
// wait; /health lists it under pending until it ends.
|
|
8
|
+
const LOOK = {
|
|
9
|
+
GET: 'agentage daemon status',
|
|
10
|
+
POST: 'the daemon may still finish the install: agentage daemon status shows it under pending, then agentage extension list shows if it was installed',
|
|
11
|
+
PATCH: 'the daemon may still finish the change: agentage daemon status shows it under pending, then agentage extension list shows the version',
|
|
12
|
+
};
|
|
13
|
+
// A timed-out change may still finish in the daemon: say how to look, never that it failed.
|
|
14
|
+
const unreachable = (port, err, ms, method) => {
|
|
15
|
+
if (err.name !== 'TimeoutError')
|
|
16
|
+
return new CliError('daemon_unavailable', `the daemon on 127.0.0.1:${port}: ${messageOf(err)}`);
|
|
17
|
+
const after = `the daemon on 127.0.0.1:${port} did not answer in ${ms / 1000} s`;
|
|
18
|
+
const look = LOOK[method] ?? LOOK['PATCH'];
|
|
19
|
+
return new CliError('timeout', `${after}; ${look}`);
|
|
20
|
+
};
|
|
21
|
+
const sender = (port, waits) => async (method, path, body) => {
|
|
22
|
+
const ms = method === 'GET' ? waits.read : waits.change;
|
|
23
|
+
const res = await fetch(`http://127.0.0.1:${port}${path}`, {
|
|
24
|
+
method,
|
|
25
|
+
headers: body ? { 'content-type': 'application/json' } : {},
|
|
26
|
+
body: body && JSON.stringify(body),
|
|
27
|
+
signal: AbortSignal.timeout(ms),
|
|
28
|
+
}).catch((err) => {
|
|
29
|
+
throw unreachable(port, err, ms, method);
|
|
30
|
+
});
|
|
31
|
+
const parsed = await res.json().catch(() => null);
|
|
32
|
+
if (!res.ok || !isRecord(parsed) || parsed['success'] !== true)
|
|
33
|
+
throw daemonFailure(res.status, parsed);
|
|
34
|
+
return parsed['data'];
|
|
35
|
+
};
|
|
36
|
+
const at = (id) => `/host/extensions/${encodeURIComponent(id)}`;
|
|
37
|
+
export const hostClient = (port, waits = WAITS) => {
|
|
38
|
+
const send = sender(port, waits);
|
|
39
|
+
return {
|
|
40
|
+
list: () => send('GET', '/host/extensions'),
|
|
41
|
+
add: (body) => send('POST', '/host/extensions', body),
|
|
42
|
+
change: (id, patch) => send('PATCH', at(id), patch),
|
|
43
|
+
remove: (id, purge) => send('DELETE', `${at(id)}${purge ? '?purge=true' : ''}`),
|
|
44
|
+
};
|
|
45
|
+
};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export declare const isRecord: (value: unknown) => value is Record<string, unknown>;
|
|
2
2
|
export declare const readJson: <T>(path: string, guard: (value: unknown) => value is T) => T | null;
|
|
3
|
+
export declare const unlinkQuiet: (path: string) => void;
|
|
3
4
|
export declare const writeTextAtomic: (path: string, text: string, mode?: number) => void;
|
|
4
5
|
export declare const writeJsonAtomic: (path: string, value: unknown, mode?: number) => void;
|
package/dist/lib/fs/json-file.js
CHANGED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { type Command } from 'commander';
|
|
2
|
+
export declare const CODES: readonly ["already_installed", "already_running", "auth_required", "auth_unavailable", "build_failed", "cancelled", "confirmation_required", "daemon_disabled", "daemon_unavailable", "daemon_unresponsive", "disk_full", "error", "extension_failed", "integrity_drift", "invalid_argument", "market_failed", "market_timeout", "market_unreachable", "needed_by_dependents", "network_unavailable", "no_discovery", "no_market", "not_conforming", "not_installed", "not_pushed", "permission_denied", "port_in_use", "profile_invalid", "release_refused", "stop_failed", "timeout", "token_request_failed", "uncommitted_changes", "usage"];
|
|
3
|
+
export type Code = (typeof CODES)[number];
|
|
4
|
+
export declare class CliError extends Error {
|
|
5
|
+
readonly code: Code;
|
|
6
|
+
constructor(code: Code, message: string);
|
|
7
|
+
}
|
|
8
|
+
export declare class DaemonError extends Error {
|
|
9
|
+
readonly code: string;
|
|
10
|
+
readonly status: number;
|
|
11
|
+
readonly details: Record<string, unknown>;
|
|
12
|
+
constructor(code: string, message: string, status?: number, details?: Record<string, unknown>);
|
|
13
|
+
}
|
|
14
|
+
export declare const codeOf: (err: unknown) => string;
|
|
15
|
+
export interface JsonIo {
|
|
16
|
+
writeOut: (text: string) => void;
|
|
17
|
+
}
|
|
18
|
+
export interface Failure {
|
|
19
|
+
err: unknown;
|
|
20
|
+
shown: boolean;
|
|
21
|
+
}
|
|
22
|
+
export declare class WithMeta {
|
|
23
|
+
readonly data: unknown;
|
|
24
|
+
readonly meta: Record<string, unknown>;
|
|
25
|
+
constructor(data: unknown, meta: Record<string, unknown>);
|
|
26
|
+
}
|
|
27
|
+
export declare const isJsonRun: () => boolean;
|
|
28
|
+
export declare const isJson: (opts: unknown) => boolean;
|
|
29
|
+
export declare const attempt: (run: () => Promise<unknown>) => Promise<Failure | null>;
|
|
30
|
+
export declare const messageOf: (err: unknown) => string;
|
|
31
|
+
export declare const writeError: (io: JsonIo, err: unknown, code?: string) => void;
|
|
32
|
+
export declare const runJson: (io: JsonIo, run: () => Promise<unknown>, legacy?: boolean) => Promise<Failure | null>;
|
|
33
|
+
export declare const omitJson: <T extends {
|
|
34
|
+
json?: boolean;
|
|
35
|
+
}>(opts: T) => Omit<T, "json">;
|
|
36
|
+
export declare const addJson: (command: Command) => Command;
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { CommanderError } from 'commander';
|
|
2
|
+
import { NotPushedError } from '../core/profile/cloud.js';
|
|
3
|
+
import { AuthRequiredError, TransientAuthError } from './auth/auth-errors.js';
|
|
4
|
+
import { TokenRequestError } from './auth/oauth.js';
|
|
5
|
+
// Every code of the cli's own: docs/reference.md lists the same, and a test keeps them equal.
|
|
6
|
+
export const CODES = [
|
|
7
|
+
'already_installed',
|
|
8
|
+
'already_running',
|
|
9
|
+
'auth_required',
|
|
10
|
+
'auth_unavailable',
|
|
11
|
+
'build_failed',
|
|
12
|
+
'cancelled',
|
|
13
|
+
'confirmation_required',
|
|
14
|
+
'daemon_disabled',
|
|
15
|
+
'daemon_unavailable',
|
|
16
|
+
'daemon_unresponsive',
|
|
17
|
+
'disk_full',
|
|
18
|
+
'error',
|
|
19
|
+
'extension_failed',
|
|
20
|
+
'integrity_drift',
|
|
21
|
+
'invalid_argument',
|
|
22
|
+
'market_failed',
|
|
23
|
+
'market_timeout',
|
|
24
|
+
'market_unreachable',
|
|
25
|
+
'needed_by_dependents',
|
|
26
|
+
'network_unavailable',
|
|
27
|
+
'no_discovery',
|
|
28
|
+
'no_market',
|
|
29
|
+
'not_conforming',
|
|
30
|
+
'not_installed',
|
|
31
|
+
'not_pushed',
|
|
32
|
+
'permission_denied',
|
|
33
|
+
'port_in_use',
|
|
34
|
+
'profile_invalid',
|
|
35
|
+
'release_refused',
|
|
36
|
+
'stop_failed',
|
|
37
|
+
'timeout',
|
|
38
|
+
'token_request_failed',
|
|
39
|
+
'uncommitted_changes',
|
|
40
|
+
'usage',
|
|
41
|
+
];
|
|
42
|
+
// An error with a stable snake_case code for `--json`; any other error is `error`.
|
|
43
|
+
export class CliError extends Error {
|
|
44
|
+
code;
|
|
45
|
+
constructor(code, message) {
|
|
46
|
+
super(message);
|
|
47
|
+
this.code = code;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
// The daemon's own code (NOT_FOUND, INVALID_SETTING), passed through as it is, with its details.
|
|
51
|
+
export class DaemonError extends Error {
|
|
52
|
+
code;
|
|
53
|
+
status;
|
|
54
|
+
details;
|
|
55
|
+
constructor(code, message, status = 0, details = {}) {
|
|
56
|
+
super(message);
|
|
57
|
+
this.code = code;
|
|
58
|
+
this.status = status;
|
|
59
|
+
this.details = details;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const KNOWN = [
|
|
63
|
+
[AuthRequiredError, 'auth_required'],
|
|
64
|
+
[TransientAuthError, 'auth_unavailable'],
|
|
65
|
+
[NotPushedError, 'not_pushed'],
|
|
66
|
+
[TokenRequestError, 'token_request_failed'],
|
|
67
|
+
];
|
|
68
|
+
// What the system says of an expected failure: a folder or file we may not use, a full disk.
|
|
69
|
+
const ERRNO = {
|
|
70
|
+
EACCES: 'permission_denied',
|
|
71
|
+
EPERM: 'permission_denied',
|
|
72
|
+
EROFS: 'permission_denied',
|
|
73
|
+
ENOSPC: 'disk_full',
|
|
74
|
+
EDQUOT: 'disk_full',
|
|
75
|
+
};
|
|
76
|
+
const systemCode = (err) => {
|
|
77
|
+
if (!(err instanceof Error))
|
|
78
|
+
return undefined;
|
|
79
|
+
if (err.name === 'TimeoutError')
|
|
80
|
+
return 'timeout';
|
|
81
|
+
if (err instanceof TypeError && err.message === 'fetch failed')
|
|
82
|
+
return 'network_unavailable';
|
|
83
|
+
return ERRNO[err.code ?? ''];
|
|
84
|
+
};
|
|
85
|
+
export const codeOf = (err) => {
|
|
86
|
+
if (err instanceof CliError || err instanceof DaemonError)
|
|
87
|
+
return err.code;
|
|
88
|
+
return KNOWN.find(([type]) => err instanceof type)?.[1] ?? systemCode(err) ?? 'error';
|
|
89
|
+
};
|
|
90
|
+
// A command's answer with `meta` beside `data` in the --json envelope.
|
|
91
|
+
export class WithMeta {
|
|
92
|
+
data;
|
|
93
|
+
meta;
|
|
94
|
+
constructor(data, meta) {
|
|
95
|
+
this.data = data;
|
|
96
|
+
this.meta = meta;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const envelope = (data) => JSON.stringify(data instanceof WithMeta
|
|
100
|
+
? { success: true, data: data.data, meta: data.meta }
|
|
101
|
+
: { success: true, data });
|
|
102
|
+
let active = false;
|
|
103
|
+
// True inside a --json run: nothing may prompt.
|
|
104
|
+
export const isJsonRun = () => active;
|
|
105
|
+
export const isJson = (opts) => typeof opts === 'object' && opts !== null && opts.json === true;
|
|
106
|
+
export const attempt = async (run) => run().then(() => null, (err) => ({ err, shown: false }));
|
|
107
|
+
// fetch says only "fetch failed"; its cause names the host and why (ECONNREFUSED, ENOTFOUND).
|
|
108
|
+
export const messageOf = (err) => {
|
|
109
|
+
if (!(err instanceof Error))
|
|
110
|
+
return String(err);
|
|
111
|
+
const cause = err.cause;
|
|
112
|
+
const why = err.message === 'fetch failed' && cause instanceof Error ? `: ${cause.message}` : '';
|
|
113
|
+
return `${err.message}${why}`;
|
|
114
|
+
};
|
|
115
|
+
export const writeError = (io, err, code = codeOf(err)) => io.writeOut(`${JSON.stringify({ success: false, error: { code, message: messageOf(err) } })}\n`);
|
|
116
|
+
// Progress goes to stderr; a pinned command keeps stdout and we note that it printed.
|
|
117
|
+
const redirectLog = (legacy) => {
|
|
118
|
+
const log = console.log;
|
|
119
|
+
let wrote = false;
|
|
120
|
+
console.log = (...args) => {
|
|
121
|
+
if (!legacy)
|
|
122
|
+
return console.error(...args);
|
|
123
|
+
wrote = true;
|
|
124
|
+
log(...args);
|
|
125
|
+
};
|
|
126
|
+
return { wrote: () => wrote, restore: () => void (console.log = log) };
|
|
127
|
+
};
|
|
128
|
+
const failureOf = (io, { err }, wrote) => {
|
|
129
|
+
if (err instanceof CommanderError)
|
|
130
|
+
return { err, shown: true };
|
|
131
|
+
if (wrote)
|
|
132
|
+
return { err, shown: false };
|
|
133
|
+
writeError(io, err);
|
|
134
|
+
return { err, shown: true };
|
|
135
|
+
};
|
|
136
|
+
// Stdout is reserved for the envelope; `legacy` keeps a command's own pinned JSON instead.
|
|
137
|
+
export const runJson = async (io, run, legacy = false) => {
|
|
138
|
+
const log = redirectLog(legacy);
|
|
139
|
+
active = true;
|
|
140
|
+
try {
|
|
141
|
+
let data = null;
|
|
142
|
+
const failure = await attempt(async () => {
|
|
143
|
+
data = (await run()) ?? null;
|
|
144
|
+
});
|
|
145
|
+
if (failure)
|
|
146
|
+
return failureOf(io, failure, log.wrote());
|
|
147
|
+
if (!legacy)
|
|
148
|
+
io.writeOut(`${envelope(data)}\n`);
|
|
149
|
+
return null;
|
|
150
|
+
}
|
|
151
|
+
finally {
|
|
152
|
+
log.restore();
|
|
153
|
+
active = false;
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
// A copy of the options without the flag, for a call that hands them on.
|
|
157
|
+
export const omitJson = (opts) => {
|
|
158
|
+
const copy = { ...opts };
|
|
159
|
+
delete copy.json;
|
|
160
|
+
return copy;
|
|
161
|
+
};
|
|
162
|
+
// The one --json option every command carries.
|
|
163
|
+
export const addJson = (command) => command.option('--json', 'one JSON object on stdout: { success, data } or { success: false, error }');
|