@agentage/cli 0.52.0 → 0.53.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.
Files changed (48) hide show
  1. package/dist/commands/daemon/daemon.d.ts +3 -1
  2. package/dist/commands/daemon/daemon.js +27 -5
  3. package/dist/commands/daemon/installer.d.ts +4 -0
  4. package/dist/commands/daemon/installer.js +29 -2
  5. package/dist/commands/daemon/move-plan.js +1 -1
  6. package/dist/commands/daemon/run.d.ts +3 -0
  7. package/dist/commands/daemon/run.js +11 -1
  8. package/dist/commands/extension/install-spec.d.ts +7 -0
  9. package/dist/commands/extension/install-spec.js +33 -0
  10. package/dist/commands/extension/lifecycle.d.ts +3 -4
  11. package/dist/commands/extension/lifecycle.js +5 -29
  12. package/dist/commands/extension/package-build.d.ts +1 -1
  13. package/dist/commands/extension/package-build.js +27 -10
  14. package/dist/commands/extension/setup-install.js +48 -21
  15. package/dist/commands/extension/setup-marker.d.ts +6 -0
  16. package/dist/commands/extension/setup-marker.js +23 -0
  17. package/dist/commands/extension/up-build.d.ts +18 -0
  18. package/dist/commands/extension/up-build.js +77 -0
  19. package/dist/commands/extension/up-commands.js +11 -10
  20. package/dist/commands/extension/up-local.d.ts +12 -12
  21. package/dist/commands/extension/up-local.js +40 -58
  22. package/dist/commands/extension/up-reload.d.ts +24 -0
  23. package/dist/commands/extension/up-reload.js +92 -0
  24. package/dist/commands/extension/up-run.d.ts +9 -11
  25. package/dist/commands/extension/up-run.js +97 -51
  26. package/dist/commands/extension/up-watch.d.ts +23 -0
  27. package/dist/commands/extension/up-watch.js +81 -0
  28. package/dist/commands/extension/up.d.ts +5 -3
  29. package/dist/commands/extension/up.js +47 -26
  30. package/dist/core/installer/version-spec.d.ts +2 -0
  31. package/dist/core/installer/version-spec.js +5 -0
  32. package/dist/core/loader/manifest.d.ts +2 -1
  33. package/dist/core/loader/manifest.js +14 -8
  34. package/dist/lib/daemon/daemon-client.d.ts +3 -1
  35. package/dist/lib/daemon/daemon-client.js +37 -16
  36. package/dist/lib/daemon/daemon-file.d.ts +2 -0
  37. package/dist/lib/daemon/daemon-file.js +4 -0
  38. package/dist/lib/daemon/daemon-health.d.ts +5 -0
  39. package/dist/lib/daemon/daemon-health.js +27 -2
  40. package/dist/lib/daemon/daemon-probe.d.ts +11 -5
  41. package/dist/lib/daemon/daemon-probe.js +10 -0
  42. package/dist/lib/daemon/host-client.d.ts +14 -1
  43. package/dist/lib/daemon/host-client.js +36 -9
  44. package/dist/lib/json-output.js +7 -5
  45. package/dist/lib/proc/start-time.d.ts +10 -0
  46. package/dist/lib/proc/start-time.js +44 -0
  47. package/dist/program-deps.js +3 -1
  48. 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 UP_CHANGED = "extension up now runs with no Docker; the Docker stack is `extension up --docker`";
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, env?: NodeJS.ProcessEnv, tty?: boolean) => Promise<unknown>;
21
- export declare const runExtensionDown: (opts?: ExtensionDownOptions, tool?: LoadKitTool) => Promise<unknown>;
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,28 @@
1
- import { existsSync } from 'node:fs';
1
+ import { existsSync, realpathSync } 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';
4
6
  import { loadKitTool } from './kit-tool.js';
5
7
  import { execIn } from './release-guard.js';
6
8
  import { assertOwnStack } from './stack-owner.js';
7
- import { stopLocal } from './up-local.js';
9
+ import { readRecord, stopLocal } from './up-local.js';
8
10
  import { runLocalUp } from './up-run.js';
11
+ const real = (path) => (existsSync(path) ? realpathSync(path) : path);
9
12
  // Prints each line as the kit reports it and keeps them for the --json answer.
10
13
  const printed = () => {
11
14
  const lines = [];
12
15
  return { lines, onLine: (line) => void (console.log(line), lines.push(line)) };
13
16
  };
14
- export const UP_CHANGED = 'extension up now runs with no Docker; the Docker stack is `extension up --docker`';
15
- // CI=false, 0 or empty is not CI.
16
- const inCi = (env) => !['', 'false', '0', undefined].includes(env['CI']);
17
- // 0.51's up was Docker: a CI script with neither flag asked for that, so it stops instead.
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) => {
17
+ // S1.1.1 D10: an old flag is kept for one minor with a line that names the new form.
18
+ export const LOCAL_DEPRECATED = '--local is deprecated (removed in the next minor): extension up runs the working copy on the daemon';
19
+ // No Docker: the working copy on the daemon, watched (D12); in CI too. --docker: the kit's path.
20
+ export const runExtensionUp = async ({ docker, local: asked, ...opts } = {}, tool = loadKitTool, local = (dir, json) => runLocalUp(dir, undefined, json)) => {
27
21
  if (docker && asked)
28
22
  throw new CliError('invalid_argument', '--docker and --local: pick one');
29
23
  if (!docker) {
30
- noticeChange({ local: asked }, env, tty);
24
+ if (asked)
25
+ console.error(LOCAL_DEPRECATED);
31
26
  return local(opts.dir, opts.json === true);
32
27
  }
33
28
  const { up } = await tool();
@@ -43,23 +38,49 @@ const dockerDown = async (opts, tool) => {
43
38
  };
44
39
  const LOCAL_LINES = {
45
40
  stopped: 'stopped extension up in this folder',
46
- stale: 'removed a stale extension up record (its port no longer answers as it)',
41
+ stale: 'removed the record of an extension up that ended',
47
42
  none: '',
48
43
  };
49
- // A local up of the folder stops; a Docker stack up --docker started there goes too.
50
- export const runExtensionDown = async (opts = {}, tool = loadKitTool) => {
51
- const dir = opts.dir ?? '.';
52
- const local = await stopLocal(dir);
53
- const lines = local === 'none' ? [] : [LOCAL_LINES[local]];
54
- for (const line of lines)
55
- console.log(line);
44
+ // The row up added goes (no purge: its data stays); a row up found there is left as it was.
45
+ const removeAdded = async (dir, record, host) => {
46
+ if (!record?.added)
47
+ return [];
48
+ const client = await host();
49
+ const row = (await client.list()).find((r) => r.id === record.id);
50
+ if (!row || real(row.source) !== real(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
+ if (down !== 'none')
64
+ lines.push(LOCAL_LINES[down]);
65
+ }
66
+ finally {
67
+ lines.push(...(await removeAdded(dir, record, host)));
68
+ for (const line of lines)
69
+ console.log(line);
70
+ }
71
+ return { down, lines };
72
+ };
73
+ // The up of the folder stops and its row goes; a Docker stack up --docker started there goes too.
74
+ export const runExtensionDown = async (opts = {}, tool = loadKitTool, host = defaultHost, stopMs = 10_000) => {
75
+ const dir = resolve(opts.dir ?? '.');
76
+ const { down, lines } = await stopAndRemove(dir, host, stopMs);
56
77
  if (existsSync(join(dir, '.agentage', 'compose.json')))
57
78
  lines.push(...(await dockerDown(opts, tool)));
58
79
  if (lines.length === 0) {
59
- lines.push(`nothing runs for ${resolve(dir)}`);
80
+ lines.push(`nothing runs for ${dir}`);
60
81
  console.log(lines[0]);
61
82
  }
62
- return { local, lines };
83
+ return { local: down, lines };
63
84
  };
64
85
  // The token alone on stdout, so a script can take it as it is.
65
86
  export const runExtensionToken = async ({ dir = '.', json, ...opts }, tool = loadKitTool, exec = execIn('.', 10)) => {
@@ -0,0 +1,2 @@
1
+ export declare const DIST_TAG: RegExp;
2
+ export declare const isVersionSpec: (spec: string) => boolean;
@@ -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 OLDER_KIT_MINORS: string[];
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,23 @@ const engineProblem = (engine, version, against) => {
83
83
  return null;
84
84
  return `engines.agentage "${engine}" does not match ${against} ${version}`;
85
85
  };
86
- // The older kit minors this kit still hosts: 0.12 is what cli 0.51 installed, 0.13 the one before
87
- // this kit; their part modules and command contract are those of 0.14 (the update smoke proves it).
88
- export const OLDER_KIT_MINORS = ['0.12', '0.13'];
89
- const OLDER = OLDER_KIT_MINORS.map((minor) => ({
90
- minor,
91
- versions: Array.from({ length: 100 }, (_, patch) => `${minor}.${patch}`),
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
+ // Every minor from KIT_FLOOR up to the one below the bundled kit: their part modules and command
89
+ // contract are those of the bundled kit (the update smoke proves it).
90
+ export const olderKitMinors = (kit = kitVersion()) => {
91
+ const [major, minor] = kit.split('.').map(Number);
92
+ const [floorMajor, floor] = KIT_FLOOR.split('.').map(Number);
93
+ if (major !== floorMajor || minor === undefined || floor === undefined)
94
+ return [];
95
+ return Array.from({ length: Math.max(0, minor - floor) }, (_, i) => `${major}.${floor + i}`);
96
+ };
97
+ const versionsOf = (minor) => Array.from({ length: 100 }, (_, patch) => `${minor}.${patch}`);
93
98
  const olderMinorOf = (engine, kit) => {
94
99
  if (!isRange(engine) || satisfies(kit, engine))
95
100
  return null;
96
- return OLDER.find(({ versions }) => versions.some((v) => satisfies(v, engine)))?.minor ?? null;
101
+ const minors = olderKitMinors(kit);
102
+ return minors.find((minor) => versionsOf(minor).some((v) => satisfies(v, engine))) ?? null;
97
103
  };
98
104
  export const olderKitWarning = (minor) => `built on kit ${minor}, update the extension`;
99
105
  // A range this kit does not satisfy and an older hosted minor does: a warning, never a problem.
@@ -6,9 +6,11 @@ export interface EnsureDeps {
6
6
  spawn: (port: number) => Promise<SpawnOutcome>;
7
7
  stop: () => Promise<StopResult>;
8
8
  log: (line: string) => void;
9
+ lateMs?: number;
9
10
  }
10
11
  export declare const LOG_CAP: number;
11
- export declare const waitForHealth: (port: number, timeoutMs?: number) => Promise<boolean>;
12
+ export declare const LATE_FILE_MS = 2000;
13
+ export declare const waitForHealth: (port: number, pid: number, timeoutMs?: number) => Promise<boolean>;
12
14
  export declare const daemonLogPath: () => string;
13
15
  export declare const openDaemonLog: (cap?: number) => number;
14
16
  export declare const spawnDaemon: (port: number, entry?: string) => Promise<SpawnOutcome>;
@@ -1,5 +1,5 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { closeSync, mkdirSync, openSync, renameSync, statSync } from 'node:fs';
2
+ import { closeSync, existsSync, mkdirSync, openSync, renameSync, statSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { childEnv } from '../child-env.js';
@@ -8,13 +8,18 @@ import { CliError } from '../json-output.js';
8
8
  import { compareVersions } from '../update/update-check.js';
9
9
  import { VERSION } from '../../utils/version.js';
10
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';
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';
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.
16
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, {
17
+ // A busy port: how long daemon.json of this folder may take to appear (written after listen).
18
+ export const LATE_FILE_MS = 2_000;
19
+ const answersAs = (pid, found) => found.kind === 'ours' && found.health.pid === pid;
20
+ const announced = (pid) => readDaemonFile()?.pid === pid;
21
+ // Healthy only as the spawned pid, and once its daemon.json (the host token) is written after listen.
22
+ export const waitForHealth = (port, pid, timeoutMs = START_MS) => waitFor(async () => answersAs(pid, await probe(port, 500)) && announced(pid), timeoutMs, {
18
23
  afterMs: PROGRESS_MS,
19
24
  line: `waiting for the daemon to start on 127.0.0.1:${port}...`,
20
25
  });
@@ -40,7 +45,7 @@ export const spawnDaemon = async (port, entry = CLI_ENTRY) => {
40
45
  closeSync(out);
41
46
  const exited = new Promise((resolve) => child.once('exit', (code) => resolve(code === EADDRINUSE_EXIT ? 'port-in-use' : 'unreachable')));
42
47
  child.unref();
43
- const healthy = waitForHealth(port).then((ok) => (ok ? 'ok' : 'unreachable'));
48
+ const healthy = waitForHealth(port, child.pid ?? 0).then((ok) => ok ? 'ok' : 'unreachable');
44
49
  return Promise.race([healthy, exited]);
45
50
  };
46
51
  export const defaultEnsureDeps = {
@@ -55,14 +60,23 @@ const lateDaemon = async (deps) => {
55
60
  return file && proven(file, await deps.probe(file.port)) ? file.port : null;
56
61
  };
57
62
  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.
63
+ // Another cli of this folder may have started one at the same time: its daemon.json can lag.
64
+ const ownLate = async (deps, port, ms) => waitFor(async () => (await lateDaemon(deps)) === port, ms);
65
+ // A busy port is ours only through this folder's daemon.json; else it is refused, never used.
66
+ const busyPort = async (deps, port) => {
67
+ if (await ownLate(deps, port, deps.lateMs ?? LATE_FILE_MS))
68
+ return port;
69
+ const found = await deps.probe(port);
70
+ if (found.kind !== 'ours')
71
+ throw portInUse(port);
72
+ if (existsSync(daemonFilePath()))
73
+ throw unreadableFile(port, found.health.pid);
74
+ throw otherFolder(port, found.health.pid);
75
+ };
59
76
  const start = async (deps, port) => {
60
77
  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
- }
78
+ if (outcome === 'port-in-use')
79
+ return busyPort(deps, port);
66
80
  if (outcome !== 'ok') {
67
81
  const late = await lateDaemon(deps);
68
82
  if (late === null)
@@ -74,6 +88,12 @@ const start = async (deps, port) => {
74
88
  };
75
89
  // Restart only for another protocol or an older daemon: a newer one serves as it is.
76
90
  const outdated = (health) => health.protocol !== PROTOCOL || compareVersions(health.version, VERSION) < 0;
91
+ // D11: a daemon that wrote no hostToken (cli 0.52 or older) refuses every /host/* call of this cli.
92
+ const restartReason = (file, health) => {
93
+ if (outdated(health))
94
+ return `it ran ${health.version}, this cli is ${VERSION}`;
95
+ return file.hostToken ? null : `it ran ${health.version} with no host token`;
96
+ };
77
97
  // daemon.json's daemon when proven; a dead pid, or a live one whose port refuses, is a stale file.
78
98
  const fromFile = async (file, deps) => {
79
99
  if (!isAlive(file.pid))
@@ -86,13 +106,14 @@ const fromFile = async (file, deps) => {
86
106
  return (removeDaemonFile(), null);
87
107
  const health = proven(file, found);
88
108
  if (!health)
89
- throw portInUse(file.port);
90
- if (!outdated(health))
109
+ throw found.kind === 'ours' ? otherFolder(file.port, found.health.pid) : portInUse(file.port);
110
+ const why = restartReason(file, health);
111
+ if (!why)
91
112
  return file.port;
113
+ // Said before the start: a start that fails then shows why the old daemon went.
114
+ deps.log(`daemon restarted: ${why}`);
92
115
  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;
116
+ return start({ ...deps, log: () => undefined }, daemonPort());
96
117
  };
97
118
  export const ensureDaemon = async (deps = defaultEnsureDeps) => {
98
119
  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((ext) => ` ${ext.id} ${ext.version} ${ext.state}`),
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
- id: string;
14
- version: string;
15
- state: string;
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';
@@ -29,4 +33,6 @@ 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;
31
35
  export declare const unresponsive: (file: DaemonFile) => CliError;
36
+ export declare const otherFolder: (port: number, pid: number, platform?: NodeJS.Platform) => CliError;
37
+ export declare const unreadableFile: (port: number, pid: number) => CliError;
32
38
  export declare const portInUse: (port: number) => CliError;
@@ -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' };
@@ -38,4 +39,13 @@ export const probeRetry = async (port, tries = 3, timeoutMs = 2000) => {
38
39
  export const proven = (file, found) => found.kind === 'ours' && found.health.pid === file.pid ? found.health : null;
39
40
  export const unresponsive = (file) => new CliError('daemon_unresponsive', `the daemon (pid ${file.pid}) does not answer on 127.0.0.1:${file.port}; ` +
40
41
  'try again, or stop that process yourself');
42
+ const killLine = (pid, platform = process.platform) => platform === 'win32' ? `taskkill /PID ${pid} /F` : `kill ${pid}`;
43
+ const stopAdvice = (pid, platform) => `stop it (agentage daemon stop with its AGENTAGE_CONFIG_DIR, or ${killLine(pid, platform)}), ` +
44
+ 'or set AGENTAGE_DAEMON_PORT to another port';
45
+ // The daemon of another config folder (AGENTAGE_CONFIG_DIR) holds the port: never used as ours.
46
+ export const otherFolder = (port, pid, platform) => new CliError('port_in_use', `port ${port} is in use by the agentage daemon (pid ${pid}) of another config folder; ` +
47
+ stopAdvice(pid, platform));
48
+ // This folder's daemon.json exists but cannot be read: the daemon on the port is not proven ours.
49
+ export const unreadableFile = (port, pid) => new CliError('port_in_use', `port ${port} is in use by an agentage daemon (pid ${pid}), and daemon.json of this config ` +
50
+ `folder cannot be read; ${stopAdvice(pid)}`);
41
51
  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`);
@@ -33,8 +33,21 @@ 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
  }
38
+ export interface HostReload {
39
+ id: string;
40
+ version: string;
41
+ state: string;
42
+ pid?: number;
43
+ reloaded: boolean;
44
+ refused?: string;
45
+ }
46
+ type Token = () => string | undefined;
47
+ type Same = (port: number) => Promise<boolean>;
48
+ export declare const sameDaemon: Same;
37
49
  export declare const hostClient: (port: number, waits?: {
38
50
  read: number;
39
51
  change: number;
40
- }) => HostClient;
52
+ }, token?: Token, same?: Same) => HostClient;
53
+ export {};
@@ -1,7 +1,9 @@
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
- // An install runs npm (up to 10 min in the daemon), then starts the child: past that it is stuck.
4
+ import { daemonFilePath, readDaemonFile, readHostToken } from './daemon-file.js';
5
+ import { probe, proven } from './daemon-probe.js';
6
+ // An install runs npm (the daemon waits up to 660 s), then starts the child: past that it is stuck.
5
7
  const WAITS = { read: 10_000, change: 12 * 60_000 };
6
8
  // The kit's queue and installer can each take 11 min, so a change can still finish after this
7
9
  // wait; /health lists it under pending until it ends.
@@ -18,28 +20,53 @@ const unreachable = (port, err, ms, method) => {
18
20
  const look = LOOK[method] ?? LOOK['PATCH'];
19
21
  return new CliError('timeout', `${after}; ${look}`);
20
22
  };
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}`, {
23
+ const headersOf = (body, token) => ({
24
+ ...(body && { 'content-type': 'application/json' }),
25
+ ...(token && { authorization: `Bearer ${token}` }),
26
+ });
27
+ const REFUSED = [401, 403];
28
+ // A token that stays refused: daemon.json names another daemon than the one on the port.
29
+ 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);
30
+ // A retry with a new token only when daemon.json still names this port and its pid answers there.
31
+ export const sameDaemon = async (port) => {
32
+ const file = readDaemonFile();
33
+ return file?.port === port && proven(file, await probe(port)) !== null;
34
+ };
35
+ const sendOnce = async (to, method, path, body) => {
36
+ const ms = method === 'GET' ? to.waits.read : to.waits.change;
37
+ const res = await fetch(`http://127.0.0.1:${to.port}${path}`, {
24
38
  method,
25
- headers: body ? { 'content-type': 'application/json' } : {},
39
+ headers: headersOf(body, to.token()),
26
40
  body: body && JSON.stringify(body),
27
41
  signal: AbortSignal.timeout(ms),
42
+ redirect: 'error',
28
43
  }).catch((err) => {
29
- throw unreachable(port, err, ms, method);
44
+ throw unreachable(to.port, err, ms, method);
30
45
  });
31
46
  const parsed = await res.json().catch(() => null);
32
47
  if (!res.ok || !isRecord(parsed) || parsed['success'] !== true)
33
48
  throw daemonFailure(res.status, parsed);
34
49
  return parsed['data'];
35
50
  };
51
+ const refused = (err) => err instanceof DaemonError && REFUSED.includes(err.status);
52
+ // 401 or 403 is refused before any change: daemon.json is read again (a new daemon), once.
53
+ const sender = (to) => (method, path, body) => sendOnce(to, method, path, body).catch(async (err) => {
54
+ if (!refused(err))
55
+ throw err;
56
+ if (!(await to.same(to.port)))
57
+ throw tokenRefused(err);
58
+ return sendOnce(to, method, path, body).catch((again) => {
59
+ throw refused(again) ? tokenRefused(again) : again;
60
+ });
61
+ });
36
62
  const at = (id) => `/host/extensions/${encodeURIComponent(id)}`;
37
- export const hostClient = (port, waits = WAITS) => {
38
- const send = sender(port, waits);
63
+ export const hostClient = (port, waits = WAITS, token = readHostToken, same = sameDaemon) => {
64
+ const send = sender({ port, waits, token, same });
39
65
  return {
40
66
  list: () => send('GET', '/host/extensions'),
41
67
  add: (body) => send('POST', '/host/extensions', body),
42
68
  change: (id, patch) => send('PATCH', at(id), patch),
43
69
  remove: (id, purge) => send('DELETE', `${at(id)}${purge ? '?purge=true' : ''}`),
70
+ reload: (id) => send('POST', `${at(id)}/reload`, {}),
44
71
  };
45
72
  };
@@ -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), passed through as it is, with its details.
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)) => io.writeOut(`${JSON.stringify({ success: false, error: { code, message: messageOf(err) } })}\n`);
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, read?: ReadStart) => boolean;
10
+ export declare const stopProven: (mark: ProcessMark, read?: ReadStart) => boolean;
@@ -0,0 +1,44 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { readFileSync } from 'node:fs';
3
+ import { isPid } from '../daemon/daemon-file.js';
4
+ // Field 22 of /proc/<pid>/stat, counted from the state field after the `(comm)` part.
5
+ const STARTTIME = 19;
6
+ const fromProc = (pid) => {
7
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
8
+ return stat.slice(stat.lastIndexOf(')') + 2).split(' ')[STARTTIME] ?? null;
9
+ };
10
+ const fromPs = (pid) => execFileSync('ps', ['-o', 'lstart=', '-p', String(pid)], { encoding: 'utf8' }).trim() || null;
11
+ // When a pid started: a pid plus this proves one process, a reused pid has another.
12
+ // Windows has neither /proc nor ps: null there, so a process is never proven and never signalled.
13
+ export const startedAt = (pid) => {
14
+ if (!isPid(pid) || process.platform === 'win32')
15
+ return null;
16
+ try {
17
+ return process.platform === 'linux' ? fromProc(pid) : fromPs(pid);
18
+ }
19
+ catch {
20
+ return null;
21
+ }
22
+ };
23
+ export const markOf = (pid, read = startedAt) => {
24
+ const started = pid === undefined ? null : read(pid);
25
+ return pid !== undefined && started !== null ? { pid, started } : null;
26
+ };
27
+ export const isMark = (value) => typeof value === 'object' &&
28
+ value !== null &&
29
+ isPid(value.pid) &&
30
+ typeof value.started === 'string';
31
+ // The same process still runs: the pid lives and started at the recorded time.
32
+ export const proven = (mark, read = startedAt) => (mark ? read(mark.pid) === mark.started : false);
33
+ // SIGTERM only to a proven process; anything else is left alone and reported.
34
+ export const stopProven = (mark, read = startedAt) => {
35
+ if (!proven(mark, read))
36
+ return false;
37
+ try {
38
+ process.kill(mark.pid, 'SIGTERM');
39
+ return true;
40
+ }
41
+ catch {
42
+ return false;
43
+ }
44
+ };