@agentage/cli 0.51.1 → 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 +26 -15
- 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 +33 -12
- 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 -96
- 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/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 +10 -10
- package/dist/commands/extension/up.js +62 -74
- 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
|
@@ -1,22 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { dirname } from 'node:path';
|
|
3
|
-
import { isDeepStrictEqual } from 'node:util';
|
|
4
|
-
import { isRecord, readJson, writeJsonAtomic } from '../../lib/fs/json-file.js';
|
|
1
|
+
import { isRecord, readJson } from '../../lib/fs/json-file.js';
|
|
5
2
|
import { commandsPath } from '../paths.js';
|
|
6
3
|
import {} from './discover.js';
|
|
7
4
|
import { CORE_COMMANDS } from './manifest.js';
|
|
8
5
|
const isHeld = (value) => isRecord(value) && Object.values(value).every((pkg) => typeof pkg === 'string');
|
|
9
6
|
// Who held each top-level verb after the last install; absent or unreadable: nobody.
|
|
10
7
|
export const readHeld = () => new Map(Object.entries(readJson(commandsPath(), isHeld) ?? {}));
|
|
11
|
-
// Written only when it changed, so a machine without kit commands never gets the file.
|
|
12
|
-
export const writeHeld = (top) => {
|
|
13
|
-
const next = Object.fromEntries(top);
|
|
14
|
-
const current = Object.fromEntries(readHeld());
|
|
15
|
-
if (isDeepStrictEqual(next, current))
|
|
16
|
-
return;
|
|
17
|
-
mkdirSync(dirname(commandsPath()), { recursive: true, mode: 0o700 });
|
|
18
|
-
writeJsonAtomic(commandsPath(), next);
|
|
19
|
-
};
|
|
20
8
|
// Core commands and every extension id are namespaces; 1.0 commands are named after their id.
|
|
21
9
|
const takenNames = (extensions) => {
|
|
22
10
|
const taken = new Map(CORE_COMMANDS.map((name) => [name, 'is a core command']));
|
|
@@ -11,7 +11,6 @@ export declare const NO_MACHINE: MachineFile;
|
|
|
11
11
|
export declare const readMachine: () => MachineFile | null;
|
|
12
12
|
export declare const loadMachine: () => Promise<MachineFile>;
|
|
13
13
|
export declare const setProfileSource: (source: ProfileSource) => Promise<MachineFile>;
|
|
14
|
-
export declare const setDev: (name: string, path: string | null) => Promise<MachineFile>;
|
|
15
14
|
export declare const setCloud: (etag: string) => Promise<MachineFile>;
|
|
16
15
|
export declare const setAccount: (accountId: string) => Promise<MachineFile>;
|
|
17
16
|
export declare const forgetAccount: () => Promise<MachineFile>;
|
|
@@ -61,11 +61,6 @@ const update = async (change) => withFileLock(machinePath(), () => {
|
|
|
61
61
|
return isDeepStrictEqual(next, machine) ? machine : save(next);
|
|
62
62
|
});
|
|
63
63
|
export const setProfileSource = async (source) => update((machine) => ({ ...machine, profileSource: source }));
|
|
64
|
-
// One dev entry by package name: a real path adds or replaces it, null removes it.
|
|
65
|
-
export const setDev = async (name, path) => update((machine) => {
|
|
66
|
-
const dev = Object.fromEntries(Object.entries(machine.dev).filter(([pkg]) => pkg !== name));
|
|
67
|
-
return { ...machine, dev: path === null ? dev : { ...dev, [name]: path } };
|
|
68
|
-
});
|
|
69
64
|
// After a pull or a push: profile.json mirrors the account's profile at `etag`.
|
|
70
65
|
export const setCloud = async (etag) => update((machine) => ({ ...machine, profileSource: 'cloud', profileEtag: etag }));
|
|
71
66
|
export const setAccount = async (accountId) => update((machine) => ({ ...machine, accountId }));
|
|
@@ -2,6 +2,7 @@ import {} from '../fs/config.js';
|
|
|
2
2
|
import {} from '../net/origins.js';
|
|
3
3
|
import { authedJson, refreshOrThrow } from './api.js';
|
|
4
4
|
import { AuthRequiredError, TransientAuthError } from './auth-errors.js';
|
|
5
|
+
import { sleep } from '../wait.js';
|
|
5
6
|
const isPast = (iso) => {
|
|
6
7
|
if (!iso)
|
|
7
8
|
return false;
|
|
@@ -9,8 +10,6 @@ const isPast = (iso) => {
|
|
|
9
10
|
return !Number.isNaN(t) && t <= Date.now();
|
|
10
11
|
};
|
|
11
12
|
const RETRY_BACKOFF_MS = 300;
|
|
12
|
-
// Ref'd on purpose: an unref'd backoff let Node exit 13 mid-retry once nothing else held the loop.
|
|
13
|
-
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
14
13
|
// Any failure but a 401 is a transient: a network blip must never read as a dead session.
|
|
15
14
|
const getSession = async (auth, links) => {
|
|
16
15
|
const url = `${links.auth}/api/auth/mcp/get-session`;
|
package/dist/lib/auth/sign-in.js
CHANGED
|
@@ -2,6 +2,7 @@ import chalk from 'chalk';
|
|
|
2
2
|
import { deleteAuth, ensureConfigDir, mutateAuth, readAuth } from '../fs/config.js';
|
|
3
3
|
import { discoverTarget } from '../net/discovery.js';
|
|
4
4
|
import { siteFqdn } from '../net/origins.js';
|
|
5
|
+
import { CliError, isJsonRun } from '../json-output.js';
|
|
5
6
|
import { AuthRequiredError } from './auth-errors.js';
|
|
6
7
|
import { startCallbackServer } from './callback-server.js';
|
|
7
8
|
import { credentialLinks, detectEnvMismatch } from './env-match.js';
|
|
@@ -41,6 +42,8 @@ const authorize = async (server, state, opts, deps, authUrl) => {
|
|
|
41
42
|
};
|
|
42
43
|
// A fresh DCR client per run: the redirect URI binds this run's ephemeral callback port.
|
|
43
44
|
export const signIn = async (opts, deps = defaultDeps) => {
|
|
45
|
+
if (isJsonRun() && opts.browser !== false)
|
|
46
|
+
throw new CliError('confirmation_required', 'sign-in opens a browser: pass --no-browser');
|
|
44
47
|
const fqdn = siteFqdn();
|
|
45
48
|
const to = await deps.discover(fqdn);
|
|
46
49
|
const authUrl = to.auth;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const childEnv: (env?: NodeJS.ProcessEnv) => NodeJS.ProcessEnv;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { DaemonError } from '../json-output.js';
|
|
2
|
+
export declare const daemonFailure: (status: number, body: unknown) => DaemonError;
|
|
3
|
+
export interface Existing {
|
|
4
|
+
id: string;
|
|
5
|
+
version?: string;
|
|
6
|
+
source?: string;
|
|
7
|
+
}
|
|
8
|
+
export declare const existingOf: (err: DaemonError) => Existing | null;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { isRecord } from '../fs/json-file.js';
|
|
2
|
+
import { DaemonError } from '../json-output.js';
|
|
3
|
+
const STATUS = 'agentage daemon status';
|
|
4
|
+
// After a 504 the kit records nothing; the npm tree an installer finishes later is reused.
|
|
5
|
+
const RECORDED_NOT = `the daemon recorded nothing: when ${STATUS} no longer shows it under pending, run the command again (a download that finished is reused)`;
|
|
6
|
+
// A 409 CONFLICT of a timed-out install that still runs names op and since, not an installed entry.
|
|
7
|
+
const stillRuns = (details) => details['timedOut'] === true || typeof details['op'] === 'string';
|
|
8
|
+
// One honest tail per answer the kit 0.14 daemon gives; the daemon's code stays the cli's code.
|
|
9
|
+
const tailOf = (status, code, details) => {
|
|
10
|
+
if (code === 'CONFLICT' && stillRuns(details))
|
|
11
|
+
return `; ${STATUS} shows it under pending; try again when it ends`;
|
|
12
|
+
if (code === 'INSTALLATION_UNREADABLE')
|
|
13
|
+
return `; ${STATUS} shows the reason`;
|
|
14
|
+
if (code === 'TIMEOUT')
|
|
15
|
+
return `; ${RECORDED_NOT}`;
|
|
16
|
+
if (status === 503)
|
|
17
|
+
return '; try again';
|
|
18
|
+
return '';
|
|
19
|
+
};
|
|
20
|
+
// The daemon's envelope as a DaemonError: its code, its message with the tail, status and details.
|
|
21
|
+
export const daemonFailure = (status, body) => {
|
|
22
|
+
const error = isRecord(body) && isRecord(body['error']) ? body['error'] : {};
|
|
23
|
+
const message = typeof error['message'] === 'string' ? error['message'] : `HTTP ${status}`;
|
|
24
|
+
const code = typeof error['code'] === 'string' && error['code'] ? error['code'] : 'error';
|
|
25
|
+
const details = isRecord(error['details']) ? error['details'] : {};
|
|
26
|
+
const tail = message.endsWith('try again') ? '' : tailOf(status, code, details);
|
|
27
|
+
return new DaemonError(code, `${message}${tail}`, status, details);
|
|
28
|
+
};
|
|
29
|
+
export const existingOf = (err) => {
|
|
30
|
+
const { id, version, source } = err.details;
|
|
31
|
+
if (err.code !== 'CONFLICT' || typeof id !== 'string' || stillRuns(err.details))
|
|
32
|
+
return null;
|
|
33
|
+
return {
|
|
34
|
+
id,
|
|
35
|
+
...(typeof version === 'string' && { version }),
|
|
36
|
+
...(typeof source === 'string' && { source }),
|
|
37
|
+
};
|
|
38
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type Probe } from './daemon-probe.js';
|
|
2
|
+
import { type StopResult } from './daemon-stop.js';
|
|
3
|
+
export type SpawnOutcome = 'ok' | 'port-in-use' | 'unreachable';
|
|
4
|
+
export interface EnsureDeps {
|
|
5
|
+
probe: (port: number) => Promise<Probe>;
|
|
6
|
+
spawn: (port: number) => Promise<SpawnOutcome>;
|
|
7
|
+
stop: () => Promise<StopResult>;
|
|
8
|
+
log: (line: string) => void;
|
|
9
|
+
}
|
|
10
|
+
export declare const LOG_CAP: number;
|
|
11
|
+
export declare const waitForHealth: (port: number, timeoutMs?: number) => Promise<boolean>;
|
|
12
|
+
export declare const daemonLogPath: () => string;
|
|
13
|
+
export declare const openDaemonLog: (cap?: number) => number;
|
|
14
|
+
export declare const spawnDaemon: (port: number, entry?: string) => Promise<SpawnOutcome>;
|
|
15
|
+
export declare const defaultEnsureDeps: EnsureDeps;
|
|
16
|
+
export declare const ensureDaemon: (deps?: EnsureDeps) => Promise<number>;
|
|
17
|
+
export declare const restartIfRunning: (deps?: EnsureDeps) => Promise<boolean>;
|
|
@@ -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;
|