@agentage/cli 0.52.1 → 0.54.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 +9 -11
- package/dist/commands/daemon/daemon.d.ts +5 -3
- package/dist/commands/daemon/daemon.js +45 -10
- package/dist/commands/daemon/installer.d.ts +4 -0
- package/dist/commands/daemon/installer.js +32 -8
- package/dist/commands/daemon/run.d.ts +3 -0
- package/dist/commands/daemon/run.js +11 -1
- package/dist/commands/extension/build.js +5 -3
- package/dist/commands/extension/configure.js +2 -1
- package/dist/commands/extension/create-install.js +3 -2
- package/dist/commands/extension/install-once.d.ts +2 -0
- package/dist/commands/extension/install-once.js +5 -5
- package/dist/commands/extension/install-spec.d.ts +7 -0
- package/dist/commands/extension/install-spec.js +33 -0
- package/dist/commands/extension/lifecycle.d.ts +1 -4
- package/dist/commands/extension/lifecycle.js +8 -32
- package/dist/commands/extension/package-build.d.ts +11 -1
- package/dist/commands/extension/package-build.js +53 -17
- package/dist/commands/extension/release-guard.d.ts +8 -1
- package/dist/commands/extension/release-guard.js +39 -16
- package/dist/commands/extension/release.js +35 -19
- package/dist/commands/extension/setup-install.js +48 -23
- package/dist/commands/extension/setup-marker.d.ts +6 -0
- package/dist/commands/extension/setup-marker.js +23 -0
- package/dist/commands/extension/up-build.d.ts +17 -0
- package/dist/commands/extension/up-build.js +71 -0
- package/dist/commands/extension/up-commands.js +11 -10
- package/dist/commands/extension/up-local.d.ts +15 -12
- package/dist/commands/extension/up-local.js +61 -60
- package/dist/commands/extension/up-reload.d.ts +30 -0
- package/dist/commands/extension/up-reload.js +115 -0
- package/dist/commands/extension/up-run.d.ts +9 -11
- package/dist/commands/extension/up-run.js +132 -50
- package/dist/commands/extension/up-watch.d.ts +23 -0
- package/dist/commands/extension/up-watch.js +81 -0
- package/dist/commands/extension/up.d.ts +5 -3
- package/dist/commands/extension/up.js +48 -25
- package/dist/core/installer/version-spec.d.ts +2 -0
- package/dist/core/installer/version-spec.js +5 -0
- package/dist/core/loader/manifest.d.ts +2 -1
- package/dist/core/loader/manifest.js +13 -8
- package/dist/lib/daemon/daemon-client.js +16 -11
- package/dist/lib/daemon/daemon-file.d.ts +2 -0
- package/dist/lib/daemon/daemon-file.js +4 -0
- package/dist/lib/daemon/daemon-health.d.ts +5 -0
- package/dist/lib/daemon/daemon-health.js +27 -2
- package/dist/lib/daemon/daemon-probe.d.ts +10 -5
- package/dist/lib/daemon/daemon-probe.js +8 -2
- package/dist/lib/daemon/host-client.d.ts +17 -2
- package/dist/lib/daemon/host-client.js +42 -12
- package/dist/lib/fs/file-lock.js +6 -0
- package/dist/lib/json-output.js +7 -5
- package/dist/lib/proc/start-time.d.ts +10 -0
- package/dist/lib/proc/start-time.js +46 -0
- package/dist/program-deps.js +3 -1
- package/package.json +2 -2
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type HostClient } from '../../lib/daemon/host-client.js';
|
|
1
2
|
import { type LoadKitTool } from './kit-tool.js';
|
|
2
3
|
import { type Exec } from './release-guard.js';
|
|
3
4
|
export interface ExtensionUpOptions {
|
|
@@ -15,9 +16,10 @@ export interface ExtensionUpFlags extends ExtensionUpOptions {
|
|
|
15
16
|
docker?: boolean;
|
|
16
17
|
local?: boolean;
|
|
17
18
|
}
|
|
18
|
-
export declare const
|
|
19
|
+
export declare const LOCAL_DEPRECATED = "--local is deprecated (removed in the next minor): extension up runs the working copy on the daemon";
|
|
19
20
|
type LocalRun = (dir: string | undefined, json: boolean) => Promise<unknown>;
|
|
20
|
-
export declare const runExtensionUp: ({ docker, local: asked, ...opts }?: ExtensionUpFlags, tool?: LoadKitTool, local?: LocalRun
|
|
21
|
-
|
|
21
|
+
export declare const runExtensionUp: ({ docker, local: asked, ...opts }?: ExtensionUpFlags, tool?: LoadKitTool, local?: LocalRun) => Promise<unknown>;
|
|
22
|
+
type Host = () => Promise<HostClient>;
|
|
23
|
+
export declare const runExtensionDown: (opts?: ExtensionDownOptions, tool?: LoadKitTool, host?: Host, stopMs?: number) => Promise<unknown>;
|
|
22
24
|
export declare const runExtensionToken: ({ dir, json, ...opts }: ExtensionTokenOptions, tool?: LoadKitTool, exec?: Exec) => Promise<unknown>;
|
|
23
25
|
export {};
|
|
@@ -1,33 +1,29 @@
|
|
|
1
1
|
import { existsSync } from 'node:fs';
|
|
2
2
|
import { join, resolve } from 'node:path';
|
|
3
|
+
import { ensureDaemon } from '../../lib/daemon/daemon-client.js';
|
|
4
|
+
import { hostClient } from '../../lib/daemon/host-client.js';
|
|
3
5
|
import { CliError, omitJson } from '../../lib/json-output.js';
|
|
6
|
+
import { folderRow } from './install-once.js';
|
|
4
7
|
import { loadKitTool } from './kit-tool.js';
|
|
5
8
|
import { execIn } from './release-guard.js';
|
|
6
9
|
import { assertOwnStack } from './stack-owner.js';
|
|
7
|
-
import {
|
|
10
|
+
import { removeStage } from './up-build.js';
|
|
11
|
+
import { readRecord, stopLocal } from './up-local.js';
|
|
8
12
|
import { runLocalUp } from './up-run.js';
|
|
9
13
|
// Prints each line as the kit reports it and keeps them for the --json answer.
|
|
10
14
|
const printed = () => {
|
|
11
15
|
const lines = [];
|
|
12
16
|
return { lines, onLine: (line) => void (console.log(line), lines.push(line)) };
|
|
13
17
|
};
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
const noticeChange = ({ local }, env, tty) => {
|
|
19
|
-
if (local)
|
|
20
|
-
return;
|
|
21
|
-
if (inCi(env) && !tty)
|
|
22
|
-
throw new CliError('invalid_argument', `${UP_CHANGED}; or --local`);
|
|
23
|
-
console.error(UP_CHANGED);
|
|
24
|
-
};
|
|
25
|
-
// No Docker: the working copy in this terminal (D7). --docker: the kit's path, a line per step.
|
|
26
|
-
export const runExtensionUp = async ({ docker, local: asked, ...opts } = {}, tool = loadKitTool, local = (dir, json) => runLocalUp(dir, undefined, json), env = process.env, tty = process.stdin.isTTY === true) => {
|
|
18
|
+
// S1.1.1 D10: an old flag is kept for one minor with a line that names the new form.
|
|
19
|
+
export const LOCAL_DEPRECATED = '--local is deprecated (removed in the next minor): extension up runs the working copy on the daemon';
|
|
20
|
+
// No Docker: the working copy on the daemon, watched (D12); in CI too. --docker: the kit's path.
|
|
21
|
+
export const runExtensionUp = async ({ docker, local: asked, ...opts } = {}, tool = loadKitTool, local = (dir, json) => runLocalUp(dir, undefined, json)) => {
|
|
27
22
|
if (docker && asked)
|
|
28
23
|
throw new CliError('invalid_argument', '--docker and --local: pick one');
|
|
29
24
|
if (!docker) {
|
|
30
|
-
|
|
25
|
+
if (asked)
|
|
26
|
+
console.error(LOCAL_DEPRECATED);
|
|
31
27
|
return local(opts.dir, opts.json === true);
|
|
32
28
|
}
|
|
33
29
|
const { up } = await tool();
|
|
@@ -43,23 +39,50 @@ const dockerDown = async (opts, tool) => {
|
|
|
43
39
|
};
|
|
44
40
|
const LOCAL_LINES = {
|
|
45
41
|
stopped: 'stopped extension up in this folder',
|
|
46
|
-
stale: 'removed
|
|
42
|
+
stale: 'removed the record of an extension up that ended',
|
|
47
43
|
none: '',
|
|
48
44
|
};
|
|
49
|
-
//
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
const
|
|
54
|
-
|
|
55
|
-
|
|
45
|
+
// The row up added goes (no purge: its data stays); a row up found there is left as it was.
|
|
46
|
+
const removeAdded = async (dir, record, host) => {
|
|
47
|
+
if (!record?.added)
|
|
48
|
+
return [];
|
|
49
|
+
const client = await host();
|
|
50
|
+
if (!(await folderRow(client, record.id, dir)))
|
|
51
|
+
return [];
|
|
52
|
+
await client.remove(record.id, false);
|
|
53
|
+
return [`removed ${record.id} from the daemon (its data stays)`];
|
|
54
|
+
};
|
|
55
|
+
const defaultHost = async () => hostClient(await ensureDaemon());
|
|
56
|
+
// The row up added goes even when that up does not stop or is gone (a stop_failed still throws).
|
|
57
|
+
const stopAndRemove = async (dir, host, stopMs) => {
|
|
58
|
+
const record = readRecord(dir);
|
|
59
|
+
const lines = [];
|
|
60
|
+
let down = 'none';
|
|
61
|
+
try {
|
|
62
|
+
down = (await stopLocal(dir, stopMs)).down;
|
|
63
|
+
// Only once no up runs: a killed up leaves its stage in the config cache.
|
|
64
|
+
removeStage(dir);
|
|
65
|
+
if (down !== 'none')
|
|
66
|
+
lines.push(LOCAL_LINES[down]);
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
lines.push(...(await removeAdded(dir, record, host)));
|
|
70
|
+
for (const line of lines)
|
|
71
|
+
console.log(line);
|
|
72
|
+
}
|
|
73
|
+
return { down, lines };
|
|
74
|
+
};
|
|
75
|
+
// The up of the folder stops and its row goes; a Docker stack up --docker started there goes too.
|
|
76
|
+
export const runExtensionDown = async (opts = {}, tool = loadKitTool, host = defaultHost, stopMs = 10_000) => {
|
|
77
|
+
const dir = resolve(opts.dir ?? '.');
|
|
78
|
+
const { down, lines } = await stopAndRemove(dir, host, stopMs);
|
|
56
79
|
if (existsSync(join(dir, '.agentage', 'compose.json')))
|
|
57
80
|
lines.push(...(await dockerDown(opts, tool)));
|
|
58
81
|
if (lines.length === 0) {
|
|
59
|
-
lines.push(`nothing runs for ${
|
|
82
|
+
lines.push(`nothing runs for ${dir}`);
|
|
60
83
|
console.log(lines[0]);
|
|
61
84
|
}
|
|
62
|
-
return { local, lines };
|
|
85
|
+
return { local: down, lines };
|
|
63
86
|
};
|
|
64
87
|
// The token alone on stdout, so a script can take it as it is.
|
|
65
88
|
export const runExtensionToken = async ({ dir = '.', json, ...opts }, tool = loadKitTool, exec = execIn('.', 10)) => {
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { isRange } from '../semver-range.js';
|
|
2
|
+
// A dist-tag is a word: a letter first, then letters, digits, `.`, `_` or `-` (never a flag).
|
|
3
|
+
export const DIST_TAG = /^[A-Za-z][\w.-]*$/;
|
|
4
|
+
// What may follow `<id>@`: a version, a range or a dist-tag; never a path, URL, git or file spec.
|
|
5
|
+
export const isVersionSpec = (spec) => !/\s/.test(spec) && (isRange(spec) || DIST_TAG.test(spec));
|
|
@@ -17,7 +17,8 @@ export interface ManifestInfo {
|
|
|
17
17
|
shape: string | null;
|
|
18
18
|
}
|
|
19
19
|
export declare const manifestInfo: (pkg: Record<string, unknown>) => ManifestInfo;
|
|
20
|
-
export declare const
|
|
20
|
+
export declare const KIT_FLOOR = "0.12";
|
|
21
|
+
export declare const olderKitMinors: (kit?: string) => string[];
|
|
21
22
|
export declare const olderKitWarning: (minor: string) => string;
|
|
22
23
|
export declare const onPreviousKit: (engine: string, kit?: string) => boolean;
|
|
23
24
|
export declare const kitWarning: (info: ManifestInfo, kit?: string) => string | null;
|
|
@@ -83,17 +83,22 @@ const engineProblem = (engine, version, against) => {
|
|
|
83
83
|
return null;
|
|
84
84
|
return `engines.agentage "${engine}" does not match ${against} ${version}`;
|
|
85
85
|
};
|
|
86
|
-
//
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
const
|
|
90
|
-
minor
|
|
91
|
-
|
|
92
|
-
|
|
86
|
+
// C10 (D8): the oldest kit minor this cli runs; it moves only with a breaking ctx change.
|
|
87
|
+
export const KIT_FLOOR = '0.12';
|
|
88
|
+
// KIT_FLOOR up to the bundled minor: they share its parts and command contract (the update smoke).
|
|
89
|
+
export const olderKitMinors = (kit = kitVersion()) => {
|
|
90
|
+
const [major, minor] = kit.split('.').map(Number);
|
|
91
|
+
const [floorMajor, floor] = KIT_FLOOR.split('.').map(Number);
|
|
92
|
+
if (major !== floorMajor || minor === undefined || floor === undefined)
|
|
93
|
+
return [];
|
|
94
|
+
return Array.from({ length: Math.max(0, minor - floor) }, (_, i) => `${major}.${floor + i}`);
|
|
95
|
+
};
|
|
96
|
+
const versionsOf = (minor) => Array.from({ length: 100 }, (_, patch) => `${minor}.${patch}`);
|
|
93
97
|
const olderMinorOf = (engine, kit) => {
|
|
94
98
|
if (!isRange(engine) || satisfies(kit, engine))
|
|
95
99
|
return null;
|
|
96
|
-
|
|
100
|
+
const minors = olderKitMinors(kit);
|
|
101
|
+
return minors.find((minor) => versionsOf(minor).some((v) => satisfies(v, engine))) ?? null;
|
|
97
102
|
};
|
|
98
103
|
export const olderKitWarning = (minor) => `built on kit ${minor}, update the extension`;
|
|
99
104
|
// A range this kit does not satisfy and an older hosted minor does: a warning, never a problem.
|
|
@@ -9,7 +9,7 @@ import { compareVersions } from '../update/update-check.js';
|
|
|
9
9
|
import { VERSION } from '../../utils/version.js';
|
|
10
10
|
import { waitFor } from '../wait.js';
|
|
11
11
|
import { daemonFilePath, daemonOff, daemonPort, EADDRINUSE_EXIT, isAlive, readDaemonFile, removeDaemonFile, } from './daemon-file.js';
|
|
12
|
-
import { otherFolder, unreadableFile, portInUse, probe, probeRetry, PROGRESS_MS, PROTOCOL, proven, unresponsive, } from './daemon-probe.js';
|
|
12
|
+
import { otherFolder, unreadableFile, portInUse, probe, probeRetry, PROGRESS_MS, PROTOCOL, proven, provenPort, unresponsive, } from './daemon-probe.js';
|
|
13
13
|
import { stopDaemon } from './daemon-stop.js';
|
|
14
14
|
const START_MS = 30_000;
|
|
15
15
|
// Over this the log moves to daemon.log.1 at the next start; one old file is kept.
|
|
@@ -17,8 +17,9 @@ export const LOG_CAP = 5 * 1024 * 1024;
|
|
|
17
17
|
// A busy port: how long daemon.json of this folder may take to appear (written after listen).
|
|
18
18
|
export const LATE_FILE_MS = 2_000;
|
|
19
19
|
const answersAs = (pid, found) => found.kind === 'ours' && found.health.pid === pid;
|
|
20
|
-
|
|
21
|
-
|
|
20
|
+
const announced = (pid) => readDaemonFile()?.pid === pid;
|
|
21
|
+
// Healthy only as the spawned pid, once its daemon.json (the host token) is written.
|
|
22
|
+
export const waitForHealth = (port, pid, timeoutMs = START_MS) => waitFor(async () => answersAs(pid, await probe(port, 500)) && announced(pid), timeoutMs, {
|
|
22
23
|
afterMs: PROGRESS_MS,
|
|
23
24
|
line: `waiting for the daemon to start on 127.0.0.1:${port}...`,
|
|
24
25
|
});
|
|
@@ -54,10 +55,7 @@ export const defaultEnsureDeps = {
|
|
|
54
55
|
log: (line) => console.error(line),
|
|
55
56
|
};
|
|
56
57
|
// A start that timed out may still have come up late: a proven daemon in daemon.json serves.
|
|
57
|
-
const lateDaemon =
|
|
58
|
-
const file = readDaemonFile();
|
|
59
|
-
return file && proven(file, await deps.probe(file.port)) ? file.port : null;
|
|
60
|
-
};
|
|
58
|
+
const lateDaemon = (deps) => provenPort(deps.probe);
|
|
61
59
|
const notStarted = () => new CliError('daemon_unavailable', `the daemon did not start: it did not answer; see agentage daemon status and ${daemonLogPath()}`);
|
|
62
60
|
// Another cli of this folder may have started one at the same time: its daemon.json can lag.
|
|
63
61
|
const ownLate = async (deps, port, ms) => waitFor(async () => (await lateDaemon(deps)) === port, ms);
|
|
@@ -87,6 +85,12 @@ const start = async (deps, port) => {
|
|
|
87
85
|
};
|
|
88
86
|
// Restart only for another protocol or an older daemon: a newer one serves as it is.
|
|
89
87
|
const outdated = (health) => health.protocol !== PROTOCOL || compareVersions(health.version, VERSION) < 0;
|
|
88
|
+
// D11: a daemon that wrote no hostToken (cli 0.52 or older) refuses every /host/* call of this cli.
|
|
89
|
+
const restartReason = (file, health) => {
|
|
90
|
+
if (outdated(health))
|
|
91
|
+
return `it ran ${health.version}, this cli is ${VERSION}`;
|
|
92
|
+
return file.hostToken ? null : `it ran ${health.version} with no host token`;
|
|
93
|
+
};
|
|
90
94
|
// daemon.json's daemon when proven; a dead pid, or a live one whose port refuses, is a stale file.
|
|
91
95
|
const fromFile = async (file, deps) => {
|
|
92
96
|
if (!isAlive(file.pid))
|
|
@@ -100,12 +104,13 @@ const fromFile = async (file, deps) => {
|
|
|
100
104
|
const health = proven(file, found);
|
|
101
105
|
if (!health)
|
|
102
106
|
throw found.kind === 'ours' ? otherFolder(file.port, found.health.pid) : portInUse(file.port);
|
|
103
|
-
|
|
107
|
+
const why = restartReason(file, health);
|
|
108
|
+
if (!why)
|
|
104
109
|
return file.port;
|
|
110
|
+
// Said before the start: a start that fails then shows why the old daemon went.
|
|
111
|
+
deps.log(`daemon restarted: ${why}`);
|
|
105
112
|
await deps.stop();
|
|
106
|
-
|
|
107
|
-
deps.log(`daemon restarted: it ran ${health.version}, this cli is ${VERSION}`);
|
|
108
|
-
return port;
|
|
113
|
+
return start({ ...deps, log: () => undefined }, daemonPort());
|
|
109
114
|
};
|
|
110
115
|
export const ensureDaemon = async (deps = defaultEnsureDeps) => {
|
|
111
116
|
if (daemonOff())
|
|
@@ -6,11 +6,13 @@ export interface DaemonFile {
|
|
|
6
6
|
version: string;
|
|
7
7
|
protocol: number;
|
|
8
8
|
startedBy: string;
|
|
9
|
+
hostToken?: string;
|
|
9
10
|
}
|
|
10
11
|
export declare const daemonPort: (env?: NodeJS.ProcessEnv) => number;
|
|
11
12
|
export declare const daemonOff: (env?: NodeJS.ProcessEnv) => boolean;
|
|
12
13
|
export declare const daemonFilePath: () => string;
|
|
13
14
|
export declare const isPid: (pid: unknown) => pid is number;
|
|
14
15
|
export declare const readDaemonFile: () => DaemonFile | null;
|
|
16
|
+
export declare const readHostToken: () => string | undefined;
|
|
15
17
|
export declare const removeDaemonFile: () => void;
|
|
16
18
|
export declare const isAlive: (pid: number) => boolean;
|
|
@@ -15,6 +15,10 @@ export const daemonFilePath = () => join(getConfigDir(), 'daemon.json');
|
|
|
15
15
|
export const isPid = (pid) => Number.isInteger(pid) && pid > 1;
|
|
16
16
|
const isDaemonFile = (value) => isRecord(value) && isPid(value['pid']) && Number.isInteger(value['port']);
|
|
17
17
|
export const readDaemonFile = () => readJson(daemonFilePath(), isDaemonFile);
|
|
18
|
+
export const readHostToken = () => {
|
|
19
|
+
const token = readDaemonFile()?.hostToken;
|
|
20
|
+
return typeof token === 'string' && token !== '' ? token : undefined;
|
|
21
|
+
};
|
|
18
22
|
export const removeDaemonFile = () => unlinkQuiet(daemonFilePath());
|
|
19
23
|
// EPERM: the pid lives, under another user.
|
|
20
24
|
export const isAlive = (pid) => {
|
|
@@ -11,6 +11,11 @@ export interface HealthMarks {
|
|
|
11
11
|
unsynced?: string[];
|
|
12
12
|
installation?: 'invalid' | 'unreadable';
|
|
13
13
|
installationError?: string;
|
|
14
|
+
seal?: 'on' | 'off';
|
|
15
|
+
sealError?: string;
|
|
16
|
+
clockRate?: number;
|
|
14
17
|
}
|
|
15
18
|
export declare const degradedReasons: (health: Health & HealthMarks) => string[];
|
|
19
|
+
export declare const withSealError: (health: Health & HealthMarks) => Health & HealthMarks;
|
|
20
|
+
export declare const sealOffLine: (port: number, look?: (port: number, timeoutMs?: number) => Promise<import("./daemon-probe.js").Probe>) => Promise<string | null>;
|
|
16
21
|
export declare const healthLines: (health: Health & HealthMarks, reasons: string[]) => string[];
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { existsSync } from 'node:fs';
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
import { getConfigDir } from '../fs/config.js';
|
|
4
|
-
import {} from './daemon-probe.js';
|
|
4
|
+
import { probe } from './daemon-probe.js';
|
|
5
5
|
const UNSETTLED = ['starting', 'failed'];
|
|
6
6
|
// The kit keeps a copy only of a file whose rows it refused at boot, not of one that later broke.
|
|
7
7
|
const invalidReason = () => existsSync(join(getConfigDir(), 'installation.json.bad'))
|
|
@@ -20,6 +20,8 @@ export const degradedReasons = (health) => {
|
|
|
20
20
|
reasons.push(`installation.json cannot be read (${health.installationError ?? 'no reason'})`);
|
|
21
21
|
if (health.installation === 'invalid')
|
|
22
22
|
reasons.push(invalidReason());
|
|
23
|
+
if (health.seal === 'off')
|
|
24
|
+
reasons.push(health.sealError ?? 'seal off');
|
|
23
25
|
if (reasons.length === 0)
|
|
24
26
|
reasons.push('the daemon gave no reason');
|
|
25
27
|
return reasons;
|
|
@@ -28,9 +30,32 @@ const pendingLine = ({ op, id, source, since, timedOut }) => {
|
|
|
28
30
|
const late = timedOut ? ', the daemon stopped waiting; it still runs' : '';
|
|
29
31
|
return ` pending ${op} ${id ?? source ?? ''} since ${since}${late}`;
|
|
30
32
|
};
|
|
33
|
+
// parts, seal and restarts when the daemon reports them (kit 0.15).
|
|
34
|
+
const entryLine = ({ id, version, state, parts, seal, restarts }) => {
|
|
35
|
+
const more = [
|
|
36
|
+
// A starting market entry has no parts yet (kit: `parts: []` until its folder is known).
|
|
37
|
+
parts?.length && `parts ${parts.join(', ')}`,
|
|
38
|
+
seal && `seal ${seal}`,
|
|
39
|
+
restarts !== undefined && `restarts ${restarts}`,
|
|
40
|
+
].filter(Boolean);
|
|
41
|
+
return ` ${id} ${version} ${state}${more.length ? `; ${more.join('; ')}` : ''}`;
|
|
42
|
+
};
|
|
43
|
+
// An entry with seal off carries the daemon's reason in --json too.
|
|
44
|
+
export const withSealError = (health) => ({
|
|
45
|
+
...health,
|
|
46
|
+
extensions: health.extensions.map((ext) => ext.seal === 'off' && health.sealError ? { ...ext, sealError: health.sealError } : ext),
|
|
47
|
+
});
|
|
48
|
+
// C2: the one line install prints when the daemon runs its children with no seal.
|
|
49
|
+
export const sealOffLine = async (port, look = probe) => {
|
|
50
|
+
const found = await look(port);
|
|
51
|
+
if (found.kind !== 'ours')
|
|
52
|
+
return null;
|
|
53
|
+
const { seal, sealError } = found.health;
|
|
54
|
+
return seal === 'off' ? (sealError ?? 'seal off') : null;
|
|
55
|
+
};
|
|
31
56
|
// The lines under the first one of `daemon status`.
|
|
32
57
|
export const healthLines = (health, reasons) => [
|
|
33
|
-
...health.extensions.map(
|
|
58
|
+
...health.extensions.map(entryLine),
|
|
34
59
|
...(health.pending ?? []).map(pendingLine),
|
|
35
60
|
...reasons.map((reason) => ` degraded: ${reason}`),
|
|
36
61
|
];
|
|
@@ -9,11 +9,15 @@ export interface Health {
|
|
|
9
9
|
pid: number;
|
|
10
10
|
version: string;
|
|
11
11
|
protocol: number;
|
|
12
|
-
extensions:
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
12
|
+
extensions: HealthEntry[];
|
|
13
|
+
}
|
|
14
|
+
export interface HealthEntry {
|
|
15
|
+
id: string;
|
|
16
|
+
version: string;
|
|
17
|
+
state: string;
|
|
18
|
+
parts?: string[];
|
|
19
|
+
seal?: 'on' | 'off';
|
|
20
|
+
restarts?: number;
|
|
17
21
|
}
|
|
18
22
|
export type Probe = {
|
|
19
23
|
kind: 'ours';
|
|
@@ -28,6 +32,7 @@ export type Probe = {
|
|
|
28
32
|
export declare const probe: (port: number, timeoutMs?: number) => Promise<Probe>;
|
|
29
33
|
export declare const probeRetry: (port: number, tries?: number, timeoutMs?: number) => Promise<Probe>;
|
|
30
34
|
export declare const proven: (file: DaemonFile, found: Probe) => Health | null;
|
|
35
|
+
export declare const provenPort: (look?: (port: number) => Promise<Probe>) => Promise<number | null>;
|
|
31
36
|
export declare const unresponsive: (file: DaemonFile) => CliError;
|
|
32
37
|
export declare const otherFolder: (port: number, pid: number, platform?: NodeJS.Platform) => CliError;
|
|
33
38
|
export declare const unreadableFile: (port: number, pid: number) => CliError;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { isRecord } from '../fs/json-file.js';
|
|
2
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.
|
|
3
|
+
import { readDaemonFile } from './daemon-file.js';
|
|
5
4
|
// A wait longer than this prints one line on stderr, so a slow start or stop does not look hung.
|
|
6
5
|
export const PROGRESS_MS = 3_000;
|
|
6
|
+
// C4/C5: the protocol this cli speaks; a daemon with another one is restarted.
|
|
7
7
|
export const PROTOCOL = 1;
|
|
8
8
|
export const DAEMON_SERVICE = 'agentage-daemon';
|
|
9
9
|
const isHealth = (body) => isRecord(body) &&
|
|
@@ -15,6 +15,7 @@ export const probe = async (port, timeoutMs = 2000) => {
|
|
|
15
15
|
try {
|
|
16
16
|
const res = await fetch(`http://127.0.0.1:${port}/health`, {
|
|
17
17
|
signal: AbortSignal.timeout(timeoutMs),
|
|
18
|
+
redirect: 'manual',
|
|
18
19
|
});
|
|
19
20
|
const body = await res.json().catch(() => null);
|
|
20
21
|
return isHealth(body) ? { kind: 'ours', health: body } : { kind: 'foreign' };
|
|
@@ -36,6 +37,11 @@ export const probeRetry = async (port, tries = 3, timeoutMs = 2000) => {
|
|
|
36
37
|
};
|
|
37
38
|
// The proof that daemon.json names a daemon of ours: its port answers with the same pid.
|
|
38
39
|
export const proven = (file, found) => found.kind === 'ours' && found.health.pid === file.pid ? found.health : null;
|
|
40
|
+
// The port of daemon.json when its daemon is proven there, else null.
|
|
41
|
+
export const provenPort = async (look = probe) => {
|
|
42
|
+
const file = readDaemonFile();
|
|
43
|
+
return file && proven(file, await look(file.port)) ? file.port : null;
|
|
44
|
+
};
|
|
39
45
|
export const unresponsive = (file) => new CliError('daemon_unresponsive', `the daemon (pid ${file.pid}) does not answer on 127.0.0.1:${file.port}; ` +
|
|
40
46
|
'try again, or stop that process yourself');
|
|
41
47
|
const killLine = (pid, platform = process.platform) => platform === 'win32' ? `taskkill /PID ${pid} /F` : `kill ${pid}`;
|
|
@@ -33,8 +33,23 @@ export interface HostClient {
|
|
|
33
33
|
remove: (id: string, purge: boolean) => Promise<{
|
|
34
34
|
id: string;
|
|
35
35
|
}>;
|
|
36
|
+
reload: (id: string) => Promise<HostReload>;
|
|
36
37
|
}
|
|
37
|
-
export
|
|
38
|
+
export interface HostReload {
|
|
39
|
+
id: string;
|
|
40
|
+
version: string;
|
|
41
|
+
state: string;
|
|
42
|
+
pid?: number;
|
|
43
|
+
reloaded: boolean;
|
|
44
|
+
refused?: string;
|
|
45
|
+
}
|
|
46
|
+
export interface Waits {
|
|
38
47
|
read: number;
|
|
39
48
|
change: number;
|
|
40
|
-
|
|
49
|
+
reload?: number;
|
|
50
|
+
}
|
|
51
|
+
type Token = () => string | undefined;
|
|
52
|
+
type Same = (port: number) => Promise<boolean>;
|
|
53
|
+
export declare const sameDaemon: Same;
|
|
54
|
+
export declare const hostClient: (port: number, waits?: Waits, token?: Token, same?: Same) => HostClient;
|
|
55
|
+
export {};
|
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
import { isRecord } from '../fs/json-file.js';
|
|
2
|
-
import { CliError, messageOf } from '../json-output.js';
|
|
2
|
+
import { CliError, DaemonError, messageOf } from '../json-output.js';
|
|
3
3
|
import { daemonFailure } from './daemon-answer.js';
|
|
4
|
+
import { daemonFilePath, readHostToken } from './daemon-file.js';
|
|
5
|
+
import { provenPort } from './daemon-probe.js';
|
|
4
6
|
// An install runs npm (the daemon waits up to 660 s), then starts the child: past that it is stuck.
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
// wait; /health lists it
|
|
7
|
+
// A reload: drain 10 s, start and health 60 s each, and the same again to restore: past 5 min stuck.
|
|
8
|
+
const WAITS = { read: 10_000, change: 12 * 60_000, reload: 5 * 60_000 };
|
|
9
|
+
// A change can finish after this wait (queue and installer 11 min each); /health lists it pending.
|
|
8
10
|
const LOOK = {
|
|
9
11
|
GET: 'agentage daemon status',
|
|
10
12
|
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
13
|
PATCH: 'the daemon may still finish the change: agentage daemon status shows it under pending, then agentage extension list shows the version',
|
|
14
|
+
RELOAD: 'agentage extension list shows its state; agentage daemon restart if it stays so',
|
|
12
15
|
};
|
|
13
16
|
// A timed-out change may still finish in the daemon: say how to look, never that it failed.
|
|
14
17
|
const unreachable = (port, err, ms, method) => {
|
|
@@ -18,28 +21,55 @@ const unreachable = (port, err, ms, method) => {
|
|
|
18
21
|
const look = LOOK[method] ?? LOOK['PATCH'];
|
|
19
22
|
return new CliError('timeout', `${after}; ${look}`);
|
|
20
23
|
};
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
+
// A body that is no envelope is not the daemon's answer (a proxy, a crash page, another program).
|
|
25
|
+
const foreign = (port, status) => new CliError('daemon_unavailable', `127.0.0.1:${port} answered HTTP ${status} with no agentage answer; agentage daemon status shows what runs there, agentage daemon restart starts it again`);
|
|
26
|
+
const headersOf = (body, token) => ({
|
|
27
|
+
...(body && { 'content-type': 'application/json' }),
|
|
28
|
+
...(token && { authorization: `Bearer ${token}` }),
|
|
29
|
+
});
|
|
30
|
+
const REFUSED = [401, 403];
|
|
31
|
+
// A token that stays refused: daemon.json names another daemon than the one on the port.
|
|
32
|
+
const tokenRefused = (err) => new DaemonError(err.code, `the daemon refused the host token of ${daemonFilePath()} (${err.message}); run agentage daemon restart`, err.status, err.details);
|
|
33
|
+
// A retry with a new token only when daemon.json still names this port and its pid answers there.
|
|
34
|
+
export const sameDaemon = async (port) => (await provenPort()) === port;
|
|
35
|
+
const waitOf = ({ waits }, kind) => kind === 'GET' ? waits.read : kind === 'RELOAD' ? (waits.reload ?? waits.read) : waits.change;
|
|
36
|
+
const sendOnce = async (to, method, path, body, kind = method) => {
|
|
37
|
+
const ms = waitOf(to, kind);
|
|
38
|
+
const res = await fetch(`http://127.0.0.1:${to.port}${path}`, {
|
|
24
39
|
method,
|
|
25
|
-
headers: body
|
|
40
|
+
headers: headersOf(body, to.token()),
|
|
26
41
|
body: body && JSON.stringify(body),
|
|
27
42
|
signal: AbortSignal.timeout(ms),
|
|
43
|
+
redirect: 'error',
|
|
28
44
|
}).catch((err) => {
|
|
29
|
-
throw unreachable(port, err, ms,
|
|
45
|
+
throw unreachable(to.port, err, ms, kind);
|
|
30
46
|
});
|
|
31
47
|
const parsed = await res.json().catch(() => null);
|
|
32
|
-
if (!
|
|
48
|
+
if (!isRecord(parsed) || typeof parsed['success'] !== 'boolean')
|
|
49
|
+
throw foreign(to.port, res.status);
|
|
50
|
+
if (!res.ok || parsed['success'] !== true)
|
|
33
51
|
throw daemonFailure(res.status, parsed);
|
|
34
52
|
return parsed['data'];
|
|
35
53
|
};
|
|
54
|
+
const refused = (err) => err instanceof DaemonError && REFUSED.includes(err.status);
|
|
55
|
+
// 401 or 403 is refused before any change: daemon.json is read again (a new daemon), once.
|
|
56
|
+
const sender = (to) => (method, path, body, kind = method) => sendOnce(to, method, path, body, kind).catch(async (err) => {
|
|
57
|
+
if (!refused(err))
|
|
58
|
+
throw err;
|
|
59
|
+
if (!(await to.same(to.port)))
|
|
60
|
+
throw tokenRefused(err);
|
|
61
|
+
return sendOnce(to, method, path, body, kind).catch((again) => {
|
|
62
|
+
throw refused(again) ? tokenRefused(again) : again;
|
|
63
|
+
});
|
|
64
|
+
});
|
|
36
65
|
const at = (id) => `/host/extensions/${encodeURIComponent(id)}`;
|
|
37
|
-
export const hostClient = (port, waits = WAITS) => {
|
|
38
|
-
const send = sender(port, waits);
|
|
66
|
+
export const hostClient = (port, waits = WAITS, token = readHostToken, same = sameDaemon) => {
|
|
67
|
+
const send = sender({ port, waits, token, same });
|
|
39
68
|
return {
|
|
40
69
|
list: () => send('GET', '/host/extensions'),
|
|
41
70
|
add: (body) => send('POST', '/host/extensions', body),
|
|
42
71
|
change: (id, patch) => send('PATCH', at(id), patch),
|
|
43
72
|
remove: (id, purge) => send('DELETE', `${at(id)}${purge ? '?purge=true' : ''}`),
|
|
73
|
+
reload: (id) => send('POST', `${at(id)}/reload`, {}, 'RELOAD'),
|
|
44
74
|
};
|
|
45
75
|
};
|
package/dist/lib/fs/file-lock.js
CHANGED
|
@@ -60,6 +60,12 @@ const createLockExclusive = (path, content) => {
|
|
|
60
60
|
try {
|
|
61
61
|
linkSync(tmp, path);
|
|
62
62
|
}
|
|
63
|
+
catch (err) {
|
|
64
|
+
// No hard links on the volume (exFAT, some SMB or Docker mounts): an exclusive create instead.
|
|
65
|
+
if (err.code === 'EEXIST')
|
|
66
|
+
throw err;
|
|
67
|
+
writeFileSync(path, content, { flag: 'wx' });
|
|
68
|
+
}
|
|
63
69
|
finally {
|
|
64
70
|
unlinkQuiet(tmp);
|
|
65
71
|
}
|
package/dist/lib/json-output.js
CHANGED
|
@@ -47,7 +47,7 @@ export class CliError extends Error {
|
|
|
47
47
|
this.code = code;
|
|
48
48
|
}
|
|
49
49
|
}
|
|
50
|
-
// The daemon's own code (NOT_FOUND, INVALID_SETTING)
|
|
50
|
+
// The daemon's own code (NOT_FOUND, INVALID_SETTING) and details (START_FAILED), as it gives them.
|
|
51
51
|
export class DaemonError extends Error {
|
|
52
52
|
code;
|
|
53
53
|
status;
|
|
@@ -96,9 +96,7 @@ export class WithMeta {
|
|
|
96
96
|
this.meta = meta;
|
|
97
97
|
}
|
|
98
98
|
}
|
|
99
|
-
const envelope = (data) => JSON.stringify(data instanceof WithMeta
|
|
100
|
-
? { success: true, data: data.data, meta: data.meta }
|
|
101
|
-
: { success: true, data });
|
|
99
|
+
const envelope = (data) => JSON.stringify({ success: true, ...(data instanceof WithMeta ? data : { data }) });
|
|
102
100
|
let active = false;
|
|
103
101
|
// True inside a --json run: nothing may prompt.
|
|
104
102
|
export const isJsonRun = () => active;
|
|
@@ -112,7 +110,11 @@ export const messageOf = (err) => {
|
|
|
112
110
|
const why = err.message === 'fetch failed' && cause instanceof Error ? `: ${cause.message}` : '';
|
|
113
111
|
return `${err.message}${why}`;
|
|
114
112
|
};
|
|
115
|
-
export const writeError = (io, err, code = codeOf(err)) =>
|
|
113
|
+
export const writeError = (io, err, code = codeOf(err)) => {
|
|
114
|
+
const details = err instanceof DaemonError && Object.keys(err.details).length && err.details;
|
|
115
|
+
const error = { code, message: messageOf(err), ...(details && { details }) };
|
|
116
|
+
io.writeOut(`${JSON.stringify({ success: false, error })}\n`);
|
|
117
|
+
};
|
|
116
118
|
// Progress goes to stderr; a pinned command keeps stdout and we note that it printed.
|
|
117
119
|
const redirectLog = (legacy) => {
|
|
118
120
|
const log = console.log;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export type ReadStart = (pid: number) => string | null;
|
|
2
|
+
export declare const startedAt: ReadStart;
|
|
3
|
+
export interface ProcessMark {
|
|
4
|
+
pid: number;
|
|
5
|
+
started: string;
|
|
6
|
+
}
|
|
7
|
+
export declare const markOf: (pid: number | undefined, read?: ReadStart) => ProcessMark | null;
|
|
8
|
+
export declare const isMark: (value: unknown) => value is ProcessMark;
|
|
9
|
+
export declare const proven: (mark: ProcessMark | undefined | null) => boolean;
|
|
10
|
+
export declare const stopProven: (mark: ProcessMark) => boolean;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { isPid } from '../daemon/daemon-file.js';
|
|
4
|
+
import { isRecord } from '../fs/json-file.js';
|
|
5
|
+
// Field 22 of /proc/<pid>/stat, counted from the state field after the `(comm)` part.
|
|
6
|
+
const STARTTIME = 19;
|
|
7
|
+
const fromProc = (pid) => {
|
|
8
|
+
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
|
|
9
|
+
return stat.slice(stat.lastIndexOf(')') + 2).split(' ')[STARTTIME] ?? null;
|
|
10
|
+
};
|
|
11
|
+
// A ps that hangs reads as "cannot tell", so nothing is signalled.
|
|
12
|
+
const PS_MS = 5_000;
|
|
13
|
+
const fromPs = (pid) => execFileSync('ps', ['-o', 'lstart=', '-p', String(pid)], {
|
|
14
|
+
encoding: 'utf8',
|
|
15
|
+
timeout: PS_MS,
|
|
16
|
+
}).trim() || null;
|
|
17
|
+
// Pid plus start time proves one process; null on Windows (no /proc, no ps): never signalled.
|
|
18
|
+
export const startedAt = (pid) => {
|
|
19
|
+
if (!isPid(pid) || process.platform === 'win32')
|
|
20
|
+
return null;
|
|
21
|
+
try {
|
|
22
|
+
return process.platform === 'linux' ? fromProc(pid) : fromPs(pid);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
export const markOf = (pid, read = startedAt) => {
|
|
29
|
+
const started = pid === undefined ? null : read(pid);
|
|
30
|
+
return pid !== undefined && started !== null ? { pid, started } : null;
|
|
31
|
+
};
|
|
32
|
+
export const isMark = (value) => isRecord(value) && isPid(value['pid']) && typeof value['started'] === 'string';
|
|
33
|
+
// The same process still runs: the pid lives and started at the recorded time.
|
|
34
|
+
export const proven = (mark) => mark ? startedAt(mark.pid) === mark.started : false;
|
|
35
|
+
// SIGTERM only to a proven process; anything else is left alone and reported.
|
|
36
|
+
export const stopProven = (mark) => {
|
|
37
|
+
if (!proven(mark))
|
|
38
|
+
return false;
|
|
39
|
+
try {
|
|
40
|
+
process.kill(mark.pid, 'SIGTERM');
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
};
|