@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
@@ -24,8 +24,10 @@ export declare const runDaemonStatus: (look?: (port: number, tries?: number, tim
24
24
  export declare const runDaemonStop: (stop?: () => Promise<StopResult>) => Promise<{
25
25
  stopped: boolean;
26
26
  }>;
27
- export declare const runDaemonRestart: (ensure?: () => Promise<number>) => Promise<{
27
+ export declare const settled: (port: number, look?: (port: number, tries?: number, timeoutMs?: number) => Promise<import("../../lib/daemon/daemon-probe.js").Probe>, timeoutMs?: number) => Promise<string[]>;
28
+ export declare const runDaemonRestart: (ensure?: () => Promise<number>, settle?: (port: number) => Promise<string[]>) => Promise<{
28
29
  port: number;
30
+ settled: boolean;
29
31
  }>;
30
32
  type Action = (opts: DaemonOptions) => Promise<void>;
31
33
  export interface DaemonActions {
@@ -1,14 +1,16 @@
1
1
  import {} from 'commander';
2
2
  import { ensureDaemon } from '../../lib/daemon/daemon-client.js';
3
3
  import { isAlive, readDaemonFile } from '../../lib/daemon/daemon-file.js';
4
- import { probeRetry, proven } from '../../lib/daemon/daemon-probe.js';
5
- import { degradedReasons, healthLines } from '../../lib/daemon/daemon-health.js';
4
+ import { PROGRESS_MS, probeRetry, proven } from '../../lib/daemon/daemon-probe.js';
5
+ import { waitFor } from '../../lib/wait.js';
6
+ import { degradedReasons, healthLines, withSealError, } from '../../lib/daemon/daemon-health.js';
6
7
  import { stopDaemon } from '../../lib/daemon/daemon-stop.js';
7
8
  import { addJson } from '../../lib/json-output.js';
8
9
  import { readMoveReport } from './move.js';
9
10
  import { helpOrUnknown } from '../extension/list.js';
10
11
  // Degraded always comes with its reasons, in the lines and in --json.
11
- const report = (file, live) => {
12
+ const report = (file, found) => {
13
+ const live = withSealError(found);
12
14
  console.log(`daemon: ${live.status} on 127.0.0.1:${file.port}, pid ${live.pid}, ${live.version}`);
13
15
  const reasons = degradedReasons(live);
14
16
  for (const line of healthLines(live, reasons))
@@ -53,9 +55,29 @@ export const runDaemonStop = async (stop = () => stopDaemon()) => {
53
55
  console.log(STOPPED(result));
54
56
  return { stopped: result !== null && 'stopped' in result };
55
57
  };
56
- export const runDaemonRestart = async (ensure = () => ensureDaemon()) => {
58
+ const SETTLE_MS = 60_000;
59
+ // Row 4 of S1.1.2: after a restart the extensions answer; a child still `starting` is waited for.
60
+ // Gives the ids still starting when the wait ran out ([] once none is).
61
+ export const settled = async (port, look = probeRetry, timeoutMs = SETTLE_MS) => {
62
+ let starting = [];
63
+ const none = async () => {
64
+ const found = await look(port);
65
+ if (found.kind !== 'ours')
66
+ return ((starting = []), true);
67
+ starting = found.health.extensions.filter((e) => e.state === 'starting').map((e) => e.id);
68
+ return starting.length === 0;
69
+ };
70
+ const line = 'waiting for the extensions to start...';
71
+ return (await waitFor(none, timeoutMs, { afterMs: PROGRESS_MS, line })) ? [] : starting;
72
+ };
73
+ // A wait that ran out is one warning, never a failure: the daemon runs and they may still start.
74
+ export const runDaemonRestart = async (ensure = () => ensureDaemon(), settle = settled) => {
57
75
  await stopDaemon();
58
- return { port: await ensure() };
76
+ const port = await ensure();
77
+ const starting = await settle(port);
78
+ if (starting.length > 0)
79
+ console.error(`warning: still starting after ${SETTLE_MS / 1000} s: ${starting.join(', ')}`);
80
+ return { port, settled: starting.length === 0 };
59
81
  };
60
82
  const HELP = `
61
83
  The daemon runs the installed extensions on 127.0.0.1 (port 4243, AGENTAGE_DAEMON_PORT for
@@ -7,5 +7,9 @@ export interface InstallerDeps {
7
7
  market: () => Market;
8
8
  }
9
9
  export declare const installError: (code: string, status: 400 | 404 | 502, message: string) => Error;
10
+ export declare const distTagOf: (input: string) => {
11
+ name: string;
12
+ tag: string;
13
+ } | null;
10
14
  export declare const cliInstaller: (deps: InstallerDeps) => Installer;
11
15
  export declare const npmNewest: (manifest: () => Promise<NpmManifest>) => (id: string) => Promise<string>;
@@ -2,7 +2,9 @@ import { join } from 'node:path';
2
2
  import { installedDir, installedName } from '../../core/installer/old-tree.js';
3
3
  import { installPackage, packageDir } from '../../core/installer/package-dir.js';
4
4
  import {} from '../../core/installer/npm.js';
5
- import { registryLookup, resolveName } from '../../core/installer/resolve.js';
5
+ import { candidatesFor, registryLookup, resolveName, } from '../../core/installer/resolve.js';
6
+ import { isRange } from '../../core/semver-range.js';
7
+ import { DIST_TAG, isVersionSpec } from '../../core/installer/version-spec.js';
6
8
  import { editableProfile } from '../../core/profile/profile.js';
7
9
  import { isRecord, readJson } from '../../lib/fs/json-file.js';
8
10
  import { messageOf } from '../../lib/json-output.js';
@@ -41,8 +43,31 @@ const resolveError = (err) => {
41
43
  return installError('INSTALL_FAILED', 502, message);
42
44
  return installError('VALIDATION_ERROR', 400, message);
43
45
  };
44
- // The one exact version npm has for the input: a range, a version, or the newest that fits.
46
+ // `fixture@broken`: a word that is not a range is a dist-tag, resolved by npm as npm does.
47
+ export const distTagOf = (input) => {
48
+ const at = input.lastIndexOf('@');
49
+ const tag = at > 0 ? input.slice(at + 1) : '';
50
+ return DIST_TAG.test(tag) && !isRange(tag) ? { name: input.slice(0, at), tag } : null;
51
+ };
52
+ const tagged = async (input, registry) => {
53
+ const { name, tag } = distTagOf(input) ?? { name: '', tag: '' };
54
+ for (const candidate of candidatesFor(name)) {
55
+ const found = await registry.find(`${candidate}@${tag}`).catch((err) => {
56
+ throw resolveError(err);
57
+ });
58
+ if (found)
59
+ return found;
60
+ }
61
+ return null;
62
+ };
63
+ // The one exact version npm has for the input: a range, a version, a dist-tag, or the newest that fits.
45
64
  const exact = async (input, registry) => {
65
+ if (distTagOf(input)) {
66
+ const found = await tagged(input, registry);
67
+ if (found)
68
+ return found;
69
+ throw installError('NOT_FOUND', 404, `${input}: npm has no such dist-tag`);
70
+ }
46
71
  const target = await resolveName(input, registry).catch((err) => {
47
72
  throw resolveError(err);
48
73
  });
@@ -72,6 +97,8 @@ const fetched = async (id, found, deps) => {
72
97
  // The daemon's installer: a version on disk (its own tree or the 0.51 one) needs no network;
73
98
  // otherwise the market, then npm into one folder per version (idempotent).
74
99
  export const cliInstaller = (deps) => async ({ id, version }) => {
100
+ if (version !== undefined && !isVersionSpec(version))
101
+ throw installError('VALIDATION_ERROR', 400, `${id}@${version}: not a version, range or dist-tag`);
75
102
  const have = version ? installedDir(id, version) : null;
76
103
  if (version && have)
77
104
  return { id, version, dir: have };
@@ -3,4 +3,7 @@ export interface DaemonRunDeps {
3
3
  installer: () => Installer;
4
4
  before?: () => Promise<void>;
5
5
  }
6
+ export declare const clockRateOf: (env?: NodeJS.ProcessEnv) => {
7
+ clockRate?: number;
8
+ };
6
9
  export declare const runDaemon: (deps: DaemonRunDeps) => Promise<void>;
@@ -4,6 +4,11 @@ import { getConfigDir } from '../../lib/fs/config.js';
4
4
  import { CliError } from '../../lib/json-output.js';
5
5
  import { VERSION } from '../../utils/version.js';
6
6
  import { KIT_EXIT } from '../extension/kit-commands.js';
7
+ // C5: the test clock comes only from this env (the e2e lab); unset or empty is the real clock.
8
+ export const clockRateOf = (env = process.env) => {
9
+ const raw = env['AGENTAGE_DAEMON_CLOCK_RATE'];
10
+ return raw ? { clockRate: Number(raw) } : {};
11
+ };
7
12
  const signalled = () => new Promise((resolve) => {
8
13
  process.once('SIGTERM', resolve);
9
14
  process.once('SIGINT', resolve);
@@ -29,7 +34,12 @@ export const runDaemon = async (deps) => {
29
34
  const stopping = signalled();
30
35
  await deps.before?.().catch(running);
31
36
  const { createDaemon } = await import('@agentage/extension/host');
32
- const opts = { configDir: getConfigDir(), port: daemonPort(), version: VERSION };
37
+ const opts = {
38
+ configDir: getConfigDir(),
39
+ port: daemonPort(),
40
+ version: VERSION,
41
+ ...clockRateOf(),
42
+ };
33
43
  const daemon = await createDaemon({ ...opts, install: deps.installer(), startedBy: 'cli' }).catch(busy);
34
44
  await stopping;
35
45
  await daemon.stop();
@@ -0,0 +1,7 @@
1
+ import { CliError } from '../../lib/json-output.js';
2
+ export declare const UNSCOPED = "agentage-extension-";
3
+ export declare const unscoped: (name: string) => CliError;
4
+ export declare const specOf: (name: string) => {
5
+ id: string;
6
+ version?: string;
7
+ };
@@ -0,0 +1,33 @@
1
+ import { isVersionSpec } from '../../core/installer/version-spec.js';
2
+ import { kitIdProblem } from '../../core/kit-id.js';
3
+ import { CliError } from '../../lib/json-output.js';
4
+ const ID = /^[a-z][a-z0-9-]*$/;
5
+ const PACKAGE_PREFIX = /^(@agentage\/extension-|agentage-extension-)/;
6
+ export const UNSCOPED = 'agentage-extension-';
7
+ // The daemon takes an id, not a package name: with a market it resolves only the scoped name.
8
+ export const unscoped = (name) => new CliError('invalid_argument', `${name}: an unscoped npm name installs only on a site with no market; nothing installed; install its folder instead: agentage extension install ./<folder>`);
9
+ // What 0.51 installed and the daemon does not: say what to type instead.
10
+ const refusedName = (name) => {
11
+ if (/^https?:\/\//i.test(name))
12
+ return `${name}: a tarball URL no longer installs; unpack it, then agentage extension install ./<folder>`;
13
+ if (name.startsWith('@') && !PACKAGE_PREFIX.test(name))
14
+ return `${name}: only @agentage/extension-<id> packages install, by id; for another package, install its folder (./path)`;
15
+ return null;
16
+ };
17
+ // `probe`, `probe@0.6.2`, or a package name of the id.
18
+ export const specOf = (name) => {
19
+ const refused = refusedName(name);
20
+ if (refused)
21
+ throw new CliError('invalid_argument', refused);
22
+ const at = name.indexOf('@', 1);
23
+ const id = (at < 0 ? name : name.slice(0, at)).replace(PACKAGE_PREFIX, '');
24
+ const version = at < 0 ? undefined : name.slice(at + 1);
25
+ if (!ID.test(id) || version === '')
26
+ throw new CliError('invalid_argument', `${name}: not an id, id@version or a folder (./path)`);
27
+ if (version !== undefined && !isVersionSpec(version))
28
+ throw new CliError('invalid_argument', `${name}: after @ only a version, a range or a dist-tag`);
29
+ const owned = kitIdProblem(id);
30
+ if (owned)
31
+ throw new CliError('invalid_argument', `${name}: ${owned}`);
32
+ return { id, ...(version && { version }) };
33
+ };
@@ -1,4 +1,5 @@
1
1
  import { type HostClient, type HostSummary } from '../../lib/daemon/host-client.js';
2
+ import { specOf } from './install-spec.js';
2
3
  export interface LifecycleDeps {
3
4
  host: () => Promise<HostClient>;
4
5
  }
@@ -18,15 +19,12 @@ export interface RemoveOptions {
18
19
  force?: boolean;
19
20
  json?: boolean;
20
21
  }
21
- export declare const specOf: (name: string) => {
22
- id: string;
23
- version?: string;
24
- };
25
22
  export declare const summaryOf: ({ id, version, state, error }: HostSummary) => HostSummary;
26
23
  export declare const report: (done: HostSummary, note?: string) => HostSummary;
27
24
  export interface InstallDeps extends LifecycleDeps {
28
25
  fromNpm?: (id: string, what: string) => Promise<string | null>;
29
26
  hasMarket?: (id: string) => Promise<boolean>;
27
+ sealOff?: () => Promise<string | null>;
30
28
  }
31
29
  export declare const runInstall: (opts: InstallOptions, deps: InstallDeps) => Promise<HostSummary>;
32
30
  export declare const runEnabled: (id: string, enabled: boolean, deps: LifecycleDeps) => Promise<HostSummary>;
@@ -39,3 +37,4 @@ export declare const runRemove: (opts: RemoveOptions, deps: LifecycleDeps & {
39
37
  id: string;
40
38
  purged: boolean;
41
39
  }>;
40
+ export { specOf };
@@ -1,7 +1,6 @@
1
1
  import { realpathSync } from 'node:fs';
2
2
  import { createInterface } from 'node:readline/promises';
3
3
  import { isAbsolute, join, resolve } from 'node:path';
4
- import { kitIdProblem } from '../../core/kit-id.js';
5
4
  import { unsafeDevPath } from '../../core/loader/dev-path.js';
6
5
  import { prunePackages } from '../../core/installer/package-dir.js';
7
6
  import { installationRows, versionsInUse } from '../../core/loader/installed.js';
@@ -10,35 +9,8 @@ import { isRecord, readJson } from '../../lib/fs/json-file.js';
10
9
  import {} from '../../lib/daemon/host-client.js';
11
10
  import { installFolder, installId } from './install-once.js';
12
11
  import { CliError, isJsonRun } from '../../lib/json-output.js';
13
- const ID = /^[a-z][a-z0-9-]*$/;
12
+ import { specOf, unscoped, UNSCOPED } from './install-spec.js';
14
13
  const LOCAL = /^\.{1,2}(?:[/\\]|$)/;
15
- const PACKAGE_PREFIX = /^(@agentage\/extension-|agentage-extension-)/;
16
- const UNSCOPED = 'agentage-extension-';
17
- // The daemon takes an id, not a package name: with a market it resolves only the scoped name.
18
- const unscoped = (name) => new CliError('invalid_argument', `${name}: an unscoped npm name installs only on a site with no market; nothing installed; install its folder instead: agentage extension install ./<folder>`);
19
- // What 0.51 installed and the daemon does not: say what to type instead.
20
- const refusedName = (name) => {
21
- if (/^https?:\/\//i.test(name))
22
- return `${name}: a tarball URL no longer installs; unpack it, then agentage extension install ./<folder>`;
23
- if (name.startsWith('@') && !PACKAGE_PREFIX.test(name))
24
- return `${name}: only @agentage/extension-<id> packages install, by id; for another package, install its folder (./path)`;
25
- return null;
26
- };
27
- // `probe`, `probe@0.6.2`, or a package name of the id.
28
- export const specOf = (name) => {
29
- const refused = refusedName(name);
30
- if (refused)
31
- throw new CliError('invalid_argument', refused);
32
- const at = name.indexOf('@', 1);
33
- const id = (at < 0 ? name : name.slice(0, at)).replace(PACKAGE_PREFIX, '');
34
- const version = at < 0 ? undefined : name.slice(at + 1);
35
- if (!ID.test(id) || version === '')
36
- throw new CliError('invalid_argument', `${name}: not an id, id@version or a folder (./path)`);
37
- const owned = kitIdProblem(id);
38
- if (owned)
39
- throw new CliError('invalid_argument', `${name}: ${owned}`);
40
- return { id, ...(version && { version }) };
41
- };
42
14
  // The real path; a folder another user can write runs code as you, so it is refused.
43
15
  const folderOf = (input) => {
44
16
  let path;
@@ -79,6 +51,9 @@ export const runInstall = async (opts, deps) => {
79
51
  const line = bare && (await deps.fromNpm?.(spec.id, `${spec.id} ${done.version} came`));
80
52
  if (line)
81
53
  console.error(line);
54
+ const seal = await deps.sealOff?.().catch(() => null);
55
+ if (seal)
56
+ console.error(seal);
82
57
  if (!opts.off)
83
58
  return report(done, already ? ' (already installed)' : '');
84
59
  console.error('install --off is now: agentage extension disable <id>');
@@ -140,3 +115,4 @@ export const runRemove = async (opts, deps) => {
140
115
  console.log(`removed ${id}${purge ? ', its data deleted' : ''}`);
141
116
  return { id, purged: purge };
142
117
  };
118
+ export { specOf };
@@ -1,7 +1,7 @@
1
1
  import type { CheckReport } from '@agentage/extension/tool';
2
2
  import { type LoadKitTool } from './kit-tool.js';
3
3
  export type Npm = (dir: string, args: string[]) => Promise<void>;
4
- export declare const npmIn: (dir: string, args: string[], timeoutMs?: number, graceMs?: number) => Promise<void>;
4
+ export declare const npmIn: (dir: string, args: string[], timeoutMs?: number, graceMs?: number, npmCli?: (opts?: import("../../lib/npm/npm-cli.js").ResolveNpmOptions) => string) => Promise<void>;
5
5
  export interface PackageBuild {
6
6
  dir: string;
7
7
  built: boolean;
@@ -2,17 +2,21 @@ import { spawn } from 'node:child_process';
2
2
  import { existsSync, readFileSync } from 'node:fs';
3
3
  import { join, resolve } from 'node:path';
4
4
  import { childEnv } from '../../lib/child-env.js';
5
- import { CliError } from '../../lib/json-output.js';
5
+ import { CliError, messageOf } from '../../lib/json-output.js';
6
+ import { resolveNpmCli } from '../../lib/npm/npm-cli.js';
6
7
  import { loadKitTool } from './kit-tool.js';
7
8
  const STEP_MS = 600_000;
8
9
  const GRACE_MS = 5_000;
9
10
  const failed = (what, why) => new CliError('build_failed', `${what} ${why}`);
10
11
  const how = (code, signal) => code === null ? `exited by signal ${signal ?? 'unknown'}` : `exited ${code}`;
11
- // npm's own output goes to stderr, so a --json stdout stays one object. Past its time it gets
12
- // SIGTERM, then SIGKILL after `graceMs`.
13
- export const npmIn = (dir, args, timeoutMs = STEP_MS, graceMs = GRACE_MS) => new Promise((done, fail) => {
14
- const what = `npm ${args.join(' ')} in ${dir}`;
15
- const child = spawn('npm', args, { cwd: dir, env: childEnv(), stdio: ['ignore', 2, 2] });
12
+ // npm runs as `node npm-cli.js`: no npm.cmd shim, which Windows cannot spawn with no shell.
13
+ const spawnNpm = (dir, args, npmCli) => spawn(process.execPath, [npmCli(), ...args], {
14
+ cwd: dir,
15
+ env: childEnv(),
16
+ stdio: ['ignore', 2, 2],
17
+ windowsHide: true,
18
+ });
19
+ const deadline = (child, timeoutMs, graceMs) => {
16
20
  let late = false;
17
21
  let kill;
18
22
  const timer = setTimeout(() => {
@@ -20,14 +24,27 @@ export const npmIn = (dir, args, timeoutMs = STEP_MS, graceMs = GRACE_MS) => new
20
24
  child.kill('SIGTERM');
21
25
  kill = setTimeout(() => child.kill('SIGKILL'), graceMs);
22
26
  }, timeoutMs);
23
- const stop = () => (clearTimeout(timer), clearTimeout(kill));
24
- child.once('error', (err) => (stop(), fail(failed(what, `did not start: ${err.message}`))));
27
+ return { late: () => late, stop: () => (clearTimeout(timer), clearTimeout(kill)) };
28
+ };
29
+ // npm's output goes to stderr (a --json stdout stays one object); past its time SIGTERM, then SIGKILL.
30
+ export const npmIn = (dir, args, timeoutMs = STEP_MS, graceMs = GRACE_MS, npmCli = resolveNpmCli) => new Promise((done, fail) => {
31
+ const what = `npm ${args.join(' ')} in ${dir}`;
32
+ const notStarted = (err) => fail(failed(what, `did not start: ${messageOf(err)}`));
33
+ let child;
34
+ try {
35
+ child = spawnNpm(dir, args, () => npmCli());
36
+ }
37
+ catch (err) {
38
+ return notStarted(err);
39
+ }
40
+ const clock = deadline(child, timeoutMs, graceMs);
41
+ child.once('error', (err) => (clock.stop(), notStarted(err)));
25
42
  child.once('exit', (code, signal) => {
26
- stop();
43
+ clock.stop();
27
44
  if (code === 0)
28
45
  return done();
29
46
  const stopped = `did not finish in ${timeoutMs / 1000} s; stopped (${how(code, signal)})`;
30
- fail(failed(what, late ? stopped : how(code, signal)));
47
+ fail(failed(what, clock.late() ? stopped : how(code, signal)));
31
48
  });
32
49
  });
33
50
  const hasBuildScript = (dir) => {
@@ -1,10 +1,10 @@
1
- import { writeFileSync } from 'node:fs';
2
1
  import {} from '../../core/profile/schema.js';
3
2
  import {} from '../../lib/daemon/host-client.js';
4
3
  import { CliError, messageOf } from '../../lib/json-output.js';
5
4
  import { line } from './line.js';
6
5
  import { addOnce } from './install-once.js';
7
- import { accountProfileInstalled, NOT_EXTENSION, profileEntries, profileMarkerPath, } from './profile-plan.js';
6
+ import { NOT_EXTENSION, profileEntries } from './profile-plan.js';
7
+ import { readMarker, writeMarker } from './setup-marker.js';
8
8
  const EXACT = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
9
9
  const KEPT = 'your account profile was installed here already; setup installs nothing (agentage extension install)';
10
10
  // An exact version is sent as it is; a range installs the market's newest version.
@@ -16,7 +16,7 @@ const installOne = async (host, entry) => {
16
16
  return already ? { ...row, already } : row;
17
17
  };
18
18
  // A package that is not an extension is said and skipped: the daemon cannot install it, ever.
19
- // A problem is the line under "not installed": the entry failed to install or to start.
19
+ // A problem: the entry failed to install (no row) or to start (a failed row).
20
20
  const tryOne = async (host, entry) => {
21
21
  if (entry.id === null)
22
22
  return void console.log(`${entry.name}: ${NOT_EXTENSION}`);
@@ -26,31 +26,58 @@ const tryOne = async (host, entry) => {
26
26
  error: messageOf(err),
27
27
  }));
28
28
  if ('error' in row && !('state' in row))
29
- return `${id}: ${row.error}`;
30
- if ('already' in row)
29
+ return { id, row: false, text: `${id}: ${row.error}` };
30
+ if ('already' in row && row.state !== 'failed')
31
31
  return void console.log(`${id} already installed`);
32
- console.log(`${row.id} ${row.version} ${row.state}`);
33
- return row.state === 'failed' ? `${id}: ${row.error ?? 'failed'}` : undefined;
32
+ if (!('already' in row))
33
+ console.log(`${row.id} ${row.version} ${row.state}`);
34
+ const failed = row.state === 'failed';
35
+ return failed ? { id, row: true, text: `${id}: ${row.error ?? 'failed'}` } : undefined;
36
+ };
37
+ const AGAIN = 'the next setup tries those entries again';
38
+ const notInstalled = (problems, account) => new CliError('extension_failed', ['not installed:', ...problems.map((p) => ` ${p.text}`), ...(account ? [AGAIN] : [])].join('\n'));
39
+ // A retry is only the ids that failed; one whose failed row the user removed is not added again.
40
+ const retryEntries = async (host, entries, failed) => {
41
+ const ids = new Set((await host.list()).map((row) => row.id));
42
+ return entries.filter((entry) => {
43
+ const was = failed.find((f) => f.id === entry.id);
44
+ if (!was)
45
+ return false;
46
+ if (!was.row || ids.has(was.id))
47
+ return true;
48
+ console.log(`${was.id} was removed here; setup does not add it again`);
49
+ return false;
50
+ });
51
+ };
52
+ const tryAll = async (host, entries) => {
53
+ const problems = [];
54
+ for (const entry of entries) {
55
+ const problem = await tryOne(host, entry);
56
+ if (problem)
57
+ problems.push(problem);
58
+ }
59
+ return problems;
34
60
  };
35
61
  // The profile's extensions go through the daemon, which runs them; the cli loads nothing itself.
36
- // An entry already in the installation is left as it is.
62
+ // Plain setup tries each entry once per machine, then only the ids that failed (in the marker).
37
63
  export const installThroughDaemon = async (profile, deps) => {
38
64
  const account = deps.from === 'account';
39
- if (account && accountProfileInstalled())
65
+ const failed = account ? readMarker() : null;
66
+ if (failed?.length === 0)
40
67
  return console.log(line('extensions', KEPT));
41
68
  const entries = profileEntries(profile);
42
69
  if (entries.length > 0 && deps.daemonOff)
43
70
  return console.log(line('extensions', 'the daemon is off, nothing installed'));
44
- const host = entries.length > 0 ? await deps.host() : null;
45
- const problems = [];
46
- for (const entry of host ? entries : []) {
47
- const problem = await tryOne(host, entry);
48
- if (problem)
49
- problems.push(problem);
50
- }
51
- // An empty profile tried nothing: a later setup still installs one with entries.
52
- if (account && host)
53
- writeFileSync(profileMarkerPath(), `${new Date().toISOString()}\n`, { mode: 0o600 });
54
- if (problems.length > 0)
55
- throw new CliError('extension_failed', ['not installed:', ...problems.map((p) => ` ${p}`)].join('\n'));
71
+ if (entries.length === 0)
72
+ return;
73
+ const host = await deps.host();
74
+ const problems = await tryAll(host, failed ? await retryEntries(host, entries, failed) : entries);
75
+ if (account)
76
+ writeMarker(problems.map(({ id, row }) => ({ id, row })));
77
+ if (problems.length === 0)
78
+ return;
79
+ if (!failed)
80
+ throw notInstalled(problems, account);
81
+ for (const p of problems)
82
+ console.log(`${p.text} (still fails; the next setup tries it again)`);
56
83
  };
@@ -0,0 +1,6 @@
1
+ export interface FailedEntry {
2
+ id: string;
3
+ row: boolean;
4
+ }
5
+ export declare const readMarker: () => FailedEntry[] | null;
6
+ export declare const writeMarker: (failed: FailedEntry[]) => void;
@@ -0,0 +1,23 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+ import { isRecord } from '../../lib/fs/json-file.js';
4
+ import { profileMarkerPath } from './profile-plan.js';
5
+ const isFailed = (value) => isRecord(value) && typeof value['id'] === 'string' && typeof value['row'] === 'boolean';
6
+ // null: no marker. A marker of cli 0.52 (a time line) or one that is not JSON has nothing to retry.
7
+ export const readMarker = () => {
8
+ if (!existsSync(profileMarkerPath()))
9
+ return null;
10
+ try {
11
+ const doc = JSON.parse(readFileSync(profileMarkerPath(), 'utf8'));
12
+ const failed = isRecord(doc) && Array.isArray(doc['failed']) ? doc['failed'] : [];
13
+ return failed.filter(isFailed);
14
+ }
15
+ catch {
16
+ return [];
17
+ }
18
+ };
19
+ export const writeMarker = (failed) => {
20
+ mkdirSync(dirname(profileMarkerPath()), { recursive: true });
21
+ const doc = { installedAt: new Date().toISOString(), failed };
22
+ writeFileSync(profileMarkerPath(), `${JSON.stringify(doc)}\n`, { mode: 0o600 });
23
+ };
@@ -0,0 +1,18 @@
1
+ import { type Npm } from './package-build.js';
2
+ export type UpMode = {
3
+ kind: 'tsc';
4
+ tsc: string;
5
+ config: string;
6
+ rest: string | null;
7
+ } | {
8
+ kind: 'stage';
9
+ script: string | null;
10
+ };
11
+ export declare const NEXT = "dist.next";
12
+ export declare const buildScriptOf: (dir: string) => string | null;
13
+ export declare const upModeOf: (dir: string) => UpMode;
14
+ export declare const seedNext: (dir: string) => void;
15
+ export declare const stageOf: (dir: string) => string;
16
+ export declare const removeStage: (dir: string) => void;
17
+ export declare const prepareStage: (dir: string) => string;
18
+ export declare const stagedBuild: (dir: string, npm: Npm) => Promise<void>;
@@ -0,0 +1,77 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, symlinkSync, unlinkSync, } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { basename, join, resolve } from 'node:path';
5
+ import { getConfigDir } from '../../lib/fs/config.js';
6
+ import {} from './package-build.js';
7
+ // The live tree the daemon runs is dist; the watcher writes only dist.next (the daemon copies it).
8
+ export const NEXT = 'dist.next';
9
+ const TSC = /^tsc(?:\s+-p\s+(\S+))?$/;
10
+ export const buildScriptOf = (dir) => {
11
+ const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
12
+ const script = pkg.scripts?.['build'];
13
+ return typeof script === 'string' ? script : null;
14
+ };
15
+ // The folder's own typescript, run as `node typescript/bin/tsc` (no .bin shim, none on Windows).
16
+ const tscOf = (dir) => {
17
+ try {
18
+ return createRequire(join(dir, 'package.json')).resolve('typescript/bin/tsc');
19
+ }
20
+ catch {
21
+ return null;
22
+ }
23
+ };
24
+ export const upModeOf = (dir) => {
25
+ const script = buildScriptOf(dir);
26
+ const [head = '', ...tail] = (script ?? '').split('&&');
27
+ const match = TSC.exec(head.trim());
28
+ const tsc = match ? tscOf(dir) : null;
29
+ if (!match || !tsc)
30
+ return { kind: 'stage', script };
31
+ const rest = tail.join('&&').trim();
32
+ return { kind: 'tsc', tsc, config: match[1] ?? 'tsconfig.json', rest: rest || null };
33
+ };
34
+ // dist.next starts as dist, so what tsc does not write (the manifest, dist/ui) stays in it.
35
+ export const seedNext = (dir) => {
36
+ mkdirSync(join(dir, NEXT), { recursive: true });
37
+ if (existsSync(join(dir, 'dist')))
38
+ cpSync(join(dir, 'dist'), join(dir, NEXT), { recursive: true, force: true });
39
+ };
40
+ // The stage is the config folder's cache, one per working copy: never inside the folder.
41
+ export const stageOf = (dir) => {
42
+ const hash = createHash('sha256').update(resolve(dir)).digest('hex').slice(0, 12);
43
+ return join(getConfigDir(), 'cache', 'up-stage', `${basename(resolve(dir))}-${hash}`);
44
+ };
45
+ const NOT_STAGED = new Set(['node_modules', '.agentage', '.git', 'coverage']);
46
+ const staged = (name) => !NOT_STAGED.has(name) && !name.startsWith('dist') && !name.startsWith('.env');
47
+ // The link goes first, so the remove never walks into the folder's own node_modules.
48
+ export const removeStage = (dir) => {
49
+ const modules = join(stageOf(dir), 'node_modules');
50
+ if (lstatSync(modules, { throwIfNoEntry: false })?.isSymbolicLink())
51
+ unlinkSync(modules);
52
+ rmSync(stageOf(dir), { recursive: true, force: true });
53
+ };
54
+ // A copy of the folder with its node_modules linked: the build there never touches the live dist.
55
+ // No .env*, coverage, .git or dist*; a `../` path in the build script resolves from the cache.
56
+ export const prepareStage = (dir) => {
57
+ const stage = stageOf(dir);
58
+ removeStage(dir);
59
+ mkdirSync(stage, { recursive: true });
60
+ for (const name of readdirSync(dir).filter(staged))
61
+ cpSync(join(dir, name), join(stage, name), { recursive: true });
62
+ const modules = join(dir, 'node_modules');
63
+ if (existsSync(modules))
64
+ symlinkSync(modules, join(stage, 'node_modules'), 'junction');
65
+ return stage;
66
+ };
67
+ // One build of the current src/ in the stage; its dist goes over dist.next (never the live dist).
68
+ export const stagedBuild = async (dir, npm) => {
69
+ const stage = existsSync(stageOf(dir)) ? stageOf(dir) : prepareStage(dir);
70
+ rmSync(join(stage, 'src'), { recursive: true, force: true });
71
+ if (existsSync(join(dir, 'src')))
72
+ cpSync(join(dir, 'src'), join(stage, 'src'), { recursive: true });
73
+ rmSync(join(stage, 'dist'), { recursive: true, force: true });
74
+ await npm(stage, ['run', 'build']);
75
+ if (existsSync(join(stage, 'dist')))
76
+ cpSync(join(stage, 'dist'), join(dir, NEXT), { recursive: true, force: true });
77
+ };