@agentage/cli 0.52.1 → 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 (46) 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/run.d.ts +3 -0
  6. package/dist/commands/daemon/run.js +11 -1
  7. package/dist/commands/extension/install-spec.d.ts +7 -0
  8. package/dist/commands/extension/install-spec.js +33 -0
  9. package/dist/commands/extension/lifecycle.d.ts +3 -4
  10. package/dist/commands/extension/lifecycle.js +5 -29
  11. package/dist/commands/extension/package-build.d.ts +1 -1
  12. package/dist/commands/extension/package-build.js +27 -10
  13. package/dist/commands/extension/setup-install.js +48 -21
  14. package/dist/commands/extension/setup-marker.d.ts +6 -0
  15. package/dist/commands/extension/setup-marker.js +23 -0
  16. package/dist/commands/extension/up-build.d.ts +18 -0
  17. package/dist/commands/extension/up-build.js +77 -0
  18. package/dist/commands/extension/up-commands.js +11 -10
  19. package/dist/commands/extension/up-local.d.ts +12 -12
  20. package/dist/commands/extension/up-local.js +40 -58
  21. package/dist/commands/extension/up-reload.d.ts +24 -0
  22. package/dist/commands/extension/up-reload.js +92 -0
  23. package/dist/commands/extension/up-run.d.ts +9 -11
  24. package/dist/commands/extension/up-run.js +97 -51
  25. package/dist/commands/extension/up-watch.d.ts +23 -0
  26. package/dist/commands/extension/up-watch.js +81 -0
  27. package/dist/commands/extension/up.d.ts +5 -3
  28. package/dist/commands/extension/up.js +47 -26
  29. package/dist/core/installer/version-spec.d.ts +2 -0
  30. package/dist/core/installer/version-spec.js +5 -0
  31. package/dist/core/loader/manifest.d.ts +2 -1
  32. package/dist/core/loader/manifest.js +14 -8
  33. package/dist/lib/daemon/daemon-client.js +14 -6
  34. package/dist/lib/daemon/daemon-file.d.ts +2 -0
  35. package/dist/lib/daemon/daemon-file.js +4 -0
  36. package/dist/lib/daemon/daemon-health.d.ts +5 -0
  37. package/dist/lib/daemon/daemon-health.js +27 -2
  38. package/dist/lib/daemon/daemon-probe.d.ts +9 -5
  39. package/dist/lib/daemon/daemon-probe.js +1 -0
  40. package/dist/lib/daemon/host-client.d.ts +14 -1
  41. package/dist/lib/daemon/host-client.js +35 -8
  42. package/dist/lib/json-output.js +7 -5
  43. package/dist/lib/proc/start-time.d.ts +10 -0
  44. package/dist/lib/proc/start-time.js +44 -0
  45. package/dist/program-deps.js +3 -1
  46. 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.
@@ -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
- // Healthy only as the spawned pid: a daemon of another config folder on the port is not ours.
21
- export const waitForHealth = (port, pid, timeoutMs = START_MS) => waitFor(async () => answersAs(pid, await probe(port, 500)), timeoutMs, {
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, {
22
23
  afterMs: PROGRESS_MS,
23
24
  line: `waiting for the daemon to start on 127.0.0.1:${port}...`,
24
25
  });
@@ -87,6 +88,12 @@ const start = async (deps, port) => {
87
88
  };
88
89
  // Restart only for another protocol or an older daemon: a newer one serves as it is.
89
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
+ };
90
97
  // daemon.json's daemon when proven; a dead pid, or a live one whose port refuses, is a stale file.
91
98
  const fromFile = async (file, deps) => {
92
99
  if (!isAlive(file.pid))
@@ -100,12 +107,13 @@ const fromFile = async (file, deps) => {
100
107
  const health = proven(file, found);
101
108
  if (!health)
102
109
  throw found.kind === 'ours' ? otherFolder(file.port, found.health.pid) : portInUse(file.port);
103
- if (!outdated(health))
110
+ const why = restartReason(file, health);
111
+ if (!why)
104
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}`);
105
115
  await deps.stop();
106
- const port = await start({ ...deps, log: () => undefined }, daemonPort());
107
- deps.log(`daemon restarted: it ran ${health.version}, this cli is ${VERSION}`);
108
- return port;
116
+ return start({ ...deps, log: () => undefined }, daemonPort());
109
117
  };
110
118
  export const ensureDaemon = async (deps = defaultEnsureDeps) => {
111
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';
@@ -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' };
@@ -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,6 +1,8 @@
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, readDaemonFile, readHostToken } from './daemon-file.js';
5
+ import { probe, proven } 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
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
@@ -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
+ };
@@ -19,6 +19,7 @@ import { runUpdate } from './commands/update/update.js';
19
19
  import { npmMajor, prepareManifest, prepareNpm } from './core/installer/npm.js';
20
20
  import { ensureSignedIn, signOut } from './lib/auth/sign-in.js';
21
21
  import { ensureDaemon } from './lib/daemon/daemon-client.js';
22
+ import { sealOffLine } from './lib/daemon/daemon-health.js';
22
23
  import { hostClient } from './lib/daemon/host-client.js';
23
24
  import { listMarket, openMarket } from './lib/net/market.js';
24
25
  import { noSiteMarket, npmFallbackLine } from './lib/net/market-error.js';
@@ -53,6 +54,7 @@ const fromNpm = async (id, what) => {
53
54
  return null;
54
55
  return npmFallbackLine(siteFqdn(), id, what, market.down());
55
56
  };
57
+ const sealOff = async () => sealOffLine(await ensureDaemon());
56
58
  const hasMarket = async (id) => {
57
59
  const market = openMarket();
58
60
  await market.latest(id);
@@ -67,7 +69,7 @@ export const defaultDeps = {
67
69
  }),
68
70
  status: (opts) => runStatus(opts),
69
71
  update: (opts) => runUpdate(opts),
70
- extensionInstall: (opts) => runInstall(opts, { ...lifecycle, fromNpm, hasMarket }),
72
+ extensionInstall: (opts) => runInstall(opts, { ...lifecycle, fromNpm, hasMarket, sealOff }),
71
73
  extensionRemove: (opts) => runRemove(opts, { ...lifecycle, io: terminalIo() }),
72
74
  extensionList: (opts) => runList(opts, listDeps),
73
75
  extensionUpdate: (opts) => runExtensionUpdate(opts, listDeps),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentage/cli",
3
- "version": "0.52.1",
3
+ "version": "0.53.0",
4
4
  "description": "The agentage CLI - connect this machine to agentage from the terminal",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -54,7 +54,7 @@
54
54
  "prepublishOnly": "npm run verify"
55
55
  },
56
56
  "dependencies": {
57
- "@agentage/extension": "^0.14.0",
57
+ "@agentage/extension": "^0.15.0",
58
58
  "@electric-sql/pglite": "^0.5.16",
59
59
  "chalk": "^6.0.0",
60
60
  "commander": "^15.0.0",