@agentage/cli 0.51.0 → 0.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/README.md +95 -127
  2. package/dist/commands/auth/setup.d.ts +2 -0
  3. package/dist/commands/auth/setup.js +4 -1
  4. package/dist/commands/daemon/daemon.d.ts +38 -0
  5. package/dist/commands/daemon/daemon.js +75 -0
  6. package/dist/commands/daemon/installer.d.ts +11 -0
  7. package/dist/commands/daemon/installer.js +87 -0
  8. package/dist/commands/daemon/move-plan.d.ts +17 -0
  9. package/dist/commands/daemon/move-plan.js +67 -0
  10. package/dist/commands/daemon/move-settings.d.ts +5 -0
  11. package/dist/commands/daemon/move-settings.js +50 -0
  12. package/dist/commands/daemon/move.d.ts +17 -0
  13. package/dist/commands/daemon/move.js +106 -0
  14. package/dist/commands/daemon/run.d.ts +6 -0
  15. package/dist/commands/daemon/run.js +36 -0
  16. package/dist/commands/extension/build.d.ts +13 -4
  17. package/dist/commands/extension/build.js +67 -25
  18. package/dist/commands/extension/configure.d.ts +26 -0
  19. package/dist/commands/extension/configure.js +100 -0
  20. package/dist/commands/extension/create-install.d.ts +26 -0
  21. package/dist/commands/extension/create-install.js +81 -0
  22. package/dist/commands/extension/create.d.ts +6 -1
  23. package/dist/commands/extension/create.js +58 -16
  24. package/dist/commands/extension/delegate.js +3 -1
  25. package/dist/commands/extension/doctor.d.ts +1 -1
  26. package/dist/commands/extension/doctor.js +8 -7
  27. package/dist/commands/extension/install-once.d.ts +17 -0
  28. package/dist/commands/extension/install-once.js +57 -0
  29. package/dist/commands/extension/kit-tool.d.ts +1 -1
  30. package/dist/commands/extension/lifecycle-commands.d.ts +19 -0
  31. package/dist/commands/extension/lifecycle-commands.js +80 -0
  32. package/dist/commands/extension/lifecycle-list.d.ts +26 -0
  33. package/dist/commands/extension/lifecycle-list.js +92 -0
  34. package/dist/commands/extension/lifecycle.d.ts +41 -0
  35. package/dist/commands/extension/lifecycle.js +142 -0
  36. package/dist/commands/extension/line.d.ts +1 -0
  37. package/dist/commands/extension/line.js +2 -0
  38. package/dist/commands/extension/list.d.ts +4 -14
  39. package/dist/commands/extension/list.js +11 -95
  40. package/dist/commands/extension/package-build.d.ts +15 -0
  41. package/dist/commands/extension/package-build.js +51 -0
  42. package/dist/commands/extension/plan.d.ts +4 -2
  43. package/dist/commands/extension/plan.js +37 -37
  44. package/dist/commands/extension/profile-plan.d.ts +16 -0
  45. package/dist/commands/extension/profile-plan.js +48 -0
  46. package/dist/commands/extension/release.d.ts +2 -1
  47. package/dist/commands/extension/release.js +10 -9
  48. package/dist/commands/extension/row-lines.d.ts +1 -2
  49. package/dist/commands/extension/row-lines.js +5 -6
  50. package/dist/commands/extension/rows.js +6 -4
  51. package/dist/commands/extension/setup-cloud.d.ts +2 -2
  52. package/dist/commands/extension/setup-cloud.js +6 -5
  53. package/dist/commands/extension/setup-install.d.ts +8 -0
  54. package/dist/commands/extension/setup-install.js +56 -0
  55. package/dist/commands/extension/setup.d.ts +4 -1
  56. package/dist/commands/extension/setup.js +56 -18
  57. package/dist/commands/extension/stack-owner.d.ts +4 -0
  58. package/dist/commands/extension/stack-owner.js +45 -0
  59. package/dist/commands/extension/sync.d.ts +6 -11
  60. package/dist/commands/extension/sync.js +8 -50
  61. package/dist/commands/extension/up-commands.d.ts +9 -0
  62. package/dist/commands/extension/up-commands.js +74 -0
  63. package/dist/commands/extension/up-local.d.ts +21 -0
  64. package/dist/commands/extension/up-local.js +94 -0
  65. package/dist/commands/extension/up-run.d.ts +23 -0
  66. package/dist/commands/extension/up-run.js +75 -0
  67. package/dist/commands/extension/up.d.ts +12 -11
  68. package/dist/commands/extension/up.js +65 -71
  69. package/dist/commands/update/update.d.ts +9 -1
  70. package/dist/commands/update/update.js +20 -6
  71. package/dist/core/installer/compare-lock.d.ts +0 -2
  72. package/dist/core/installer/compare-lock.js +0 -12
  73. package/dist/core/installer/compat.js +5 -3
  74. package/dist/core/installer/npm.d.ts +1 -0
  75. package/dist/core/installer/npm.js +6 -0
  76. package/dist/core/installer/old-tree.d.ts +3 -0
  77. package/dist/core/installer/old-tree.js +45 -0
  78. package/dist/core/installer/package-dir.d.ts +11 -0
  79. package/dist/core/installer/package-dir.js +53 -0
  80. package/dist/core/installer/resolve.js +1 -2
  81. package/dist/core/installer/tree.d.ts +0 -5
  82. package/dist/core/installer/tree.js +1 -25
  83. package/dist/core/kit-id.d.ts +1 -0
  84. package/dist/core/kit-id.js +20 -0
  85. package/dist/core/loader/discover.d.ts +7 -1
  86. package/dist/core/loader/discover.js +5 -4
  87. package/dist/core/loader/installed.d.ts +9 -0
  88. package/dist/core/loader/installed.js +51 -0
  89. package/dist/core/loader/manifest.d.ts +4 -0
  90. package/dist/core/loader/manifest.js +25 -3
  91. package/dist/core/loader/scan.d.ts +2 -1
  92. package/dist/core/loader/scan.js +17 -4
  93. package/dist/core/loader/secrets.d.ts +0 -7
  94. package/dist/core/loader/secrets.js +0 -11
  95. package/dist/core/loader/verbs.d.ts +0 -1
  96. package/dist/core/loader/verbs.js +1 -13
  97. package/dist/core/profile/machine.d.ts +0 -1
  98. package/dist/core/profile/machine.js +0 -5
  99. package/dist/lib/auth/introspect.js +1 -2
  100. package/dist/lib/auth/sign-in.js +3 -0
  101. package/dist/lib/child-env.d.ts +1 -0
  102. package/dist/lib/child-env.js +6 -0
  103. package/dist/lib/daemon/daemon-answer.d.ts +8 -0
  104. package/dist/lib/daemon/daemon-answer.js +38 -0
  105. package/dist/lib/daemon/daemon-client.d.ts +17 -0
  106. package/dist/lib/daemon/daemon-client.js +112 -0
  107. package/dist/lib/daemon/daemon-file.d.ts +16 -0
  108. package/dist/lib/daemon/daemon-file.js +30 -0
  109. package/dist/lib/daemon/daemon-health.d.ts +16 -0
  110. package/dist/lib/daemon/daemon-health.js +36 -0
  111. package/dist/lib/daemon/daemon-probe.d.ts +32 -0
  112. package/dist/lib/daemon/daemon-probe.js +41 -0
  113. package/dist/lib/daemon/daemon-stop.d.ts +13 -0
  114. package/dist/lib/daemon/daemon-stop.js +42 -0
  115. package/dist/lib/daemon/host-client.d.ts +40 -0
  116. package/dist/lib/daemon/host-client.js +45 -0
  117. package/dist/lib/exit-code.d.ts +2 -0
  118. package/dist/lib/exit-code.js +8 -0
  119. package/dist/lib/fs/json-file.d.ts +1 -0
  120. package/dist/lib/fs/json-file.js +1 -1
  121. package/dist/lib/json-output.d.ts +36 -0
  122. package/dist/lib/json-output.js +163 -0
  123. package/dist/lib/net/market-error.d.ts +12 -0
  124. package/dist/lib/net/market-error.js +28 -0
  125. package/dist/lib/net/market.d.ts +17 -2
  126. package/dist/lib/net/market.js +92 -18
  127. package/dist/lib/wait.d.ts +6 -0
  128. package/dist/lib/wait.js +17 -0
  129. package/dist/lib/with-action.d.ts +12 -0
  130. package/dist/lib/with-action.js +33 -0
  131. package/dist/program-deps.d.ts +2 -0
  132. package/dist/program-deps.js +95 -0
  133. package/dist/program.d.ts +29 -21
  134. package/dist/program.js +41 -75
  135. package/package.json +8 -6
  136. package/CHANGELOG.md +0 -68
  137. package/dist/commands/extension/install-load.d.ts +0 -7
  138. package/dist/commands/extension/install-load.js +0 -42
  139. package/dist/commands/extension/install.d.ts +0 -12
  140. package/dist/commands/extension/install.js +0 -49
  141. package/dist/commands/extension/latest.d.ts +0 -2
  142. package/dist/commands/extension/latest.js +0 -71
  143. package/dist/commands/extension/remove.d.ts +0 -15
  144. package/dist/commands/extension/remove.js +0 -86
  145. package/dist/commands/extension/secrets-prompt.d.ts +0 -6
  146. package/dist/commands/extension/secrets-prompt.js +0 -47
  147. package/dist/core/installer/installer.d.ts +0 -28
  148. package/dist/core/installer/installer.js +0 -87
  149. package/dist/core/installer/latest.d.ts +0 -27
  150. package/dist/core/installer/latest.js +0 -90
  151. package/dist/core/profile/edit.d.ts +0 -4
  152. package/dist/core/profile/edit.js +0 -27
@@ -0,0 +1,142 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { createInterface } from 'node:readline/promises';
3
+ import { isAbsolute, join, resolve } from 'node:path';
4
+ import { kitIdProblem } from '../../core/kit-id.js';
5
+ import { unsafeDevPath } from '../../core/loader/dev-path.js';
6
+ import { prunePackages } from '../../core/installer/package-dir.js';
7
+ import { installationRows, versionsInUse } from '../../core/loader/installed.js';
8
+ import { getConfigDir } from '../../lib/fs/config.js';
9
+ import { isRecord, readJson } from '../../lib/fs/json-file.js';
10
+ import {} from '../../lib/daemon/host-client.js';
11
+ import { installFolder, installId } from './install-once.js';
12
+ import { CliError, isJsonRun } from '../../lib/json-output.js';
13
+ const ID = /^[a-z][a-z0-9-]*$/;
14
+ 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`);
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
+ // The real path; a folder another user can write runs code as you, so it is refused.
43
+ const folderOf = (input) => {
44
+ let path;
45
+ try {
46
+ path = realpathSync(resolve(input));
47
+ }
48
+ catch {
49
+ throw new CliError('invalid_argument', `${input}: no such folder`);
50
+ }
51
+ const unsafe = unsafeDevPath(path, process.getuid?.());
52
+ if (unsafe)
53
+ throw new CliError('invalid_argument', unsafe);
54
+ return path;
55
+ };
56
+ export const summaryOf = ({ id, version, state, error }) => ({
57
+ id,
58
+ version,
59
+ state,
60
+ ...(error && { error }),
61
+ });
62
+ // A failed start is listed (state failed) and the command exits 1 with the reason.
63
+ export const report = (done, note = '') => {
64
+ if (done.state === 'failed')
65
+ throw new CliError('extension_failed', `${done.id} failed: ${done.error ?? 'no reason given'}`);
66
+ console.log(`${done.id} ${done.version} ${done.state}${note}`);
67
+ return summaryOf(done);
68
+ };
69
+ export const runInstall = async (opts, deps) => {
70
+ const host = await deps.host();
71
+ const folder = LOCAL.test(opts.name) || isAbsolute(opts.name);
72
+ const spec = folder ? null : specOf(opts.name);
73
+ if (spec && opts.name.startsWith(UNSCOPED) && (await deps.hasMarket?.(spec.id)))
74
+ throw unscoped(opts.name);
75
+ const { row: done, already } = spec
76
+ ? await installId(host, spec)
77
+ : await installFolder(host, folderOf(opts.name));
78
+ const bare = spec && !spec.version && !already;
79
+ const line = bare && (await deps.fromNpm?.(spec.id, `${spec.id} ${done.version} came`));
80
+ if (line)
81
+ console.error(line);
82
+ if (!opts.off)
83
+ return report(done, already ? ' (already installed)' : '');
84
+ console.error('install --off is now: agentage extension disable <id>');
85
+ return report(await host.change(done.id, { enabled: false }));
86
+ };
87
+ export const runEnabled = async (id, enabled, deps) => report(await (await deps.host()).change(specOf(id).id, { enabled }));
88
+ const askLine = async (question) => {
89
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
90
+ try {
91
+ return await rl.question(question);
92
+ }
93
+ finally {
94
+ rl.close();
95
+ }
96
+ };
97
+ export const terminalIo = () => ({
98
+ isTTY: process.stdin.isTTY === true,
99
+ prompt: askLine,
100
+ });
101
+ // Only y or yes (any case) says yes.
102
+ export const confirmed = async (io, question) => /^y(es)?$/i.test((await io.prompt(question)).trim());
103
+ // Asked before anything changes; without a terminal (or with --json) only --yes deletes.
104
+ const purgeConfirmed = async (id, opts, io) => {
105
+ const data = join(getConfigDir(), 'data', id);
106
+ if (opts.yes)
107
+ return true;
108
+ if (!io.isTTY || isJsonRun())
109
+ throw new CliError('confirmation_required', `--purge without a terminal needs --yes: agentage extension remove ${id} --purge --yes ` +
110
+ `(it deletes ${data})`);
111
+ return confirmed(io, `delete ${data} and everything in it? [y/N] `);
112
+ };
113
+ const peersOf = (dir) => {
114
+ const peers = readJson(join(dir, 'package.json'), isRecord)?.['peerDependencies'];
115
+ return isRecord(peers) ? Object.keys(peers) : [];
116
+ };
117
+ // Another installed extension (a disabled one too) that peer-depends on it would break.
118
+ const checkDependents = (id, force) => {
119
+ const rows = installationRows();
120
+ const pkg = rows.find((row) => row.id === id && row.dir !== null);
121
+ const name = pkg?.dir ? readJson(join(pkg.dir, 'package.json'), isRecord)?.['name'] : null;
122
+ if (typeof name !== 'string' || force)
123
+ return;
124
+ const needing = rows.filter((row) => row.dir !== null && peersOf(row.dir).includes(name));
125
+ if (needing.length === 0)
126
+ return;
127
+ const names = needing.map((row) => row.id).join(', ');
128
+ throw new CliError('needed_by_dependents', `${id} is needed by ${names}; remove them first, or --force`);
129
+ };
130
+ // The daemon answers once the old child is stopped: the folders no row uses can go.
131
+ export const pruneUnused = (id) => prunePackages(id, versionsInUse(id));
132
+ export const runRemove = async (opts, deps) => {
133
+ const { id } = specOf(opts.name);
134
+ checkDependents(id, opts.force);
135
+ const purge = opts.purge === true && (await purgeConfirmed(id, opts, deps.io));
136
+ if (opts.purge && !purge)
137
+ throw new CliError('confirmation_required', 'nothing removed');
138
+ await (await deps.host()).remove(id, purge);
139
+ pruneUnused(id);
140
+ console.log(`removed ${id}${purge ? ', its data deleted' : ''}`);
141
+ return { id, purged: purge };
142
+ };
@@ -0,0 +1 @@
1
+ export declare const line: (label: string, value: string) => string;
@@ -0,0 +1,2 @@
1
+ // One report line: a 10-column label, then the value.
2
+ export const line = (label, value) => `${label.padEnd(10)} ${value}`;
@@ -3,22 +3,12 @@ import { type BuildActions } from './build.js';
3
3
  import { type ExtensionReleaseOptions } from './release.js';
4
4
  import { type ExtensionCreateOptions } from './create.js';
5
5
  import { type ExtensionDoctorOptions } from './doctor.js';
6
- import { type ExtensionInstallOptions } from './install.js';
7
- import { type ExtensionRemoveOptions } from './remove.js';
8
- import { type Latest } from './row-lines.js';
9
- import { type Market } from '../../lib/net/market.js';
6
+ import { type LifecycleActions } from './lifecycle-commands.js';
10
7
  import { type ExtensionsGather } from './rows.js';
11
- import { type KitActions } from './up.js';
12
- export interface ExtensionListOptions {
13
- json?: boolean;
14
- }
15
- export declare const printReport: ({ status, warnings }: ExtensionsGather, json?: boolean, latest?: Latest) => void;
16
- export declare const runExtensionList: (opts?: ExtensionListOptions, market?: Market) => Promise<void>;
8
+ import { type KitActions } from './up-commands.js';
9
+ export declare const printReport: ({ status, warnings }: ExtensionsGather, json?: boolean) => void;
17
10
  export declare const helpOrUnknown: (_opts: unknown, group: Command) => void;
18
- export interface ExtensionActions extends KitActions, BuildActions {
19
- install: (opts: ExtensionInstallOptions) => Promise<void>;
20
- remove: (opts: ExtensionRemoveOptions) => Promise<void>;
21
- list: (opts: ExtensionListOptions) => Promise<void>;
11
+ export interface ExtensionActions extends KitActions, BuildActions, LifecycleActions {
22
12
  doctor: (opts: ExtensionDoctorOptions) => Promise<void>;
23
13
  create: (opts: ExtensionCreateOptions) => Promise<void>;
24
14
  release: (opts: ExtensionReleaseOptions) => Promise<void>;
@@ -3,81 +3,20 @@ import { addBuild } from './build.js';
3
3
  import { addRelease } from './release.js';
4
4
  import { addCreate } from './create.js';
5
5
  import {} from './doctor.js';
6
- import {} from './install.js';
7
- import {} from './remove.js';
6
+ import { addLifecycle } from './lifecycle-commands.js';
8
7
  import { printWarnings, rowLines } from './row-lines.js';
9
- import {} from '../../lib/net/market.js';
10
- import { gatherExtensions, invalidProfileError } from './rows.js';
11
- import { addKitTools } from './up.js';
12
- const withLatest = (status, latest) => ({
13
- ...status,
14
- extensions: status.extensions.map((row) => ({
15
- ...row,
16
- latest: latest.get(row.id ?? '') ?? null,
17
- })),
18
- });
19
- // The rows, or the whole report as JSON, on stdout; warnings on stderr.
20
- export const printReport = ({ status, warnings }, json, latest) => {
21
- const rows = status.extensions.length > 0 ? rowLines(status.extensions, latest) : ['no extensions'];
8
+ import {} from './rows.js';
9
+ import { addKitTools } from './up-commands.js';
10
+ // The rows, or the whole report as JSON, on stdout; warnings on stderr (extension doctor).
11
+ export const printReport = ({ status, warnings }, json) => {
12
+ const rows = status.extensions.length > 0 ? rowLines(status.extensions) : ['no extensions'];
22
13
  if (json)
23
- console.log(JSON.stringify(latest ? withLatest(status, latest) : status, null, 2));
14
+ console.log(JSON.stringify(status, null, 2));
24
15
  else
25
16
  for (const text of rows)
26
17
  console.log(text);
27
18
  printWarnings(warnings);
28
19
  };
29
- // A refused answer costs only its own row: one stderr line, no version.
30
- const versionOf = async (market, id) => {
31
- try {
32
- return (await market.latest(id))?.version ?? null;
33
- }
34
- catch (err) {
35
- console.error(err.message);
36
- return null;
37
- }
38
- };
39
- // The market's newest version for each installed id it knows; unknown or refused ids are null.
40
- const newest = async ({ status }, market) => {
41
- const ids = status.extensions.flatMap((row) => (row.id === null ? [] : [row.id]));
42
- const found = await Promise.all(ids.map(async (id) => [id, await versionOf(market, id)]));
43
- return market.down() ? undefined : new Map(found);
44
- };
45
- // The rows always print; an invalid profile.json then fails the step (exit 1).
46
- export const runExtensionList = async (opts = {}, market) => {
47
- const gathered = await gatherExtensions();
48
- printReport(gathered, opts.json, market && (await newest(gathered, market)));
49
- const failure = invalidProfileError(gathered.status.profile);
50
- if (failure)
51
- throw failure;
52
- };
53
- const INSTALL_HELP = `
54
- <name> is resolved in this order: a local path (./path or /path) is a working copy, linked as a
55
- dev extension: kept in machine.json by its real path and loaded on this machine only, in place
56
- of an installed copy of the same package; http:, file:, npm: and github: are refused; an https:
57
- tarball URL and a package name are used as written (a name without @<range> is pinned to ^ its
58
- newest version whose engines.agentage fits this CLI's extension API, or the kit's version for a
59
- package built on the extension kit, naming each newer version it skipped); a short name like
60
- memory is @agentage/extension-memory, else agentage-extension-memory. A package goes into
61
- profile.json (created from the default profile when absent), from the registry the profile
62
- names for its scope; --off keeps it from loading on this machine. Then installs and loads like
63
- setup, and exits 1 when an extension failed. Never signs in. On a machine whose profile comes
64
- from your account, the change applies to the account's newest profile and is pushed (with npm's
65
- lock) once everything loaded; if another machine pushed in between, it is replayed once on that
66
- profile. The commands of a package built on the kit run as agentage <command> and always as
67
- agentage <id> <command>; one whose name is a core command, an extension id or a command an
68
- earlier install took runs only as agentage <id> <command>, and one line says so.`;
69
- const REMOVE_HELP = `
70
- <name> is a package name, a short name or an extension id. Refused while another extension
71
- peer-depends on it. Takes it out of profile.json and this machine's off list, or out of
72
- machine.json for a dev extension, deletes state/<id>.json, then installs and loads the rest like
73
- setup, and pushes the profile to your account like install. --purge also deletes data/<id>/
74
- after asking; without a terminal it needs --yes.`;
75
- const LIST_HELP = `
76
- One row per extension in the profile, a dev path or the installed tree: id, state (installed,
77
- off, blocked, invalid, missing), what setup would change (add, update, remove; blank for
78
- nothing), package, installed version, wanted range, contributed commands, the last run from
79
- state/<id>.json, and the reason when it cannot load. Extension code is never loaded; the only
80
- file written is machine.json.`;
81
20
  const DOCTOR_HELP = `
82
21
  Loads every extension this machine can run, once, the way setup does: what an extension prints
83
22
  while loading goes to stderr, state/<id>.json is rewritten for each, and the rows show ok or
@@ -92,30 +31,7 @@ export const helpOrUnknown = (_opts, group) => {
92
31
  group.help();
93
32
  group.error(`error: unknown command '${name}'`, { code: 'commander.unknownCommand' });
94
33
  };
95
- const addChanges = (group, { install, remove }) => {
96
- group
97
- .command('install')
98
- .description('Add an extension to the profile, then install and load it')
99
- .argument('<name>', 'package name[@range], short name, https: tarball URL or local path')
100
- .option('--off', 'install it, but do not load it on this machine')
101
- .addHelpText('after', INSTALL_HELP)
102
- .action((name, opts) => install({ name, ...opts }));
103
- group
104
- .command('remove')
105
- .description('Remove an extension from the profile, then install and load the rest')
106
- .argument('<name>', 'package name, short name or extension id')
107
- .option('--purge', "also delete the extension's data, data/<id>/")
108
- .option('--yes', 'do not ask before --purge deletes (needed without a terminal)')
109
- .addHelpText('after', REMOVE_HELP)
110
- .action((name, opts) => remove({ name, ...opts }));
111
- };
112
- const addReports = (group, { list, doctor }) => {
113
- group
114
- .command('list')
115
- .description('Show one row per extension: state, versions, commands, last run')
116
- .option('--json', 'machine-readable output')
117
- .addHelpText('after', LIST_HELP)
118
- .action(list);
34
+ const addDoctor = (group, doctor) => {
119
35
  group
120
36
  .command('doctor')
121
37
  .description('Load every extension once and refresh its state: ok or failed')
@@ -123,15 +39,15 @@ const addReports = (group, { list, doctor }) => {
123
39
  .addHelpText('after', DOCTOR_HELP)
124
40
  .action(doctor);
125
41
  };
126
- // Help lists the subcommands in this order: install, remove, list, doctor, create, check, build, release, up, down, token.
42
+ // Help order: C1 (install to remove), then doctor, create, check, build, release, up, down, token.
127
43
  export const registerExtension = (program, actions) => {
128
44
  const group = program
129
45
  .command('extension')
130
46
  .description('Work with the extensions on this machine')
131
47
  .allowExcessArguments()
132
48
  .action(helpOrUnknown);
133
- addChanges(group, actions);
134
- addReports(group, actions);
49
+ addLifecycle(group, actions);
50
+ addDoctor(group, actions.doctor);
135
51
  addCreate(group, actions.create);
136
52
  addBuild(group, actions);
137
53
  addRelease(group, actions.release);
@@ -0,0 +1,15 @@
1
+ import type { CheckReport } from '@agentage/extension/tool';
2
+ import { type LoadKitTool } from './kit-tool.js';
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>;
5
+ export interface PackageBuild {
6
+ dir: string;
7
+ built: boolean;
8
+ contracts: string[];
9
+ report: CheckReport;
10
+ }
11
+ export interface PackageBuildDeps {
12
+ npm: Npm;
13
+ tool: LoadKitTool;
14
+ }
15
+ export declare const buildPackage: (folder?: string, deps?: PackageBuildDeps) => Promise<PackageBuild>;
@@ -0,0 +1,51 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { join, resolve } from 'node:path';
4
+ import { childEnv } from '../../lib/child-env.js';
5
+ import { CliError } from '../../lib/json-output.js';
6
+ import { loadKitTool } from './kit-tool.js';
7
+ const STEP_MS = 600_000;
8
+ const GRACE_MS = 5_000;
9
+ const failed = (what, why) => new CliError('build_failed', `${what} ${why}`);
10
+ 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] });
16
+ let late = false;
17
+ let kill;
18
+ const timer = setTimeout(() => {
19
+ late = true;
20
+ child.kill('SIGTERM');
21
+ kill = setTimeout(() => child.kill('SIGKILL'), graceMs);
22
+ }, timeoutMs);
23
+ const stop = () => (clearTimeout(timer), clearTimeout(kill));
24
+ child.once('error', (err) => (stop(), fail(failed(what, `did not start: ${err.message}`))));
25
+ child.once('exit', (code, signal) => {
26
+ stop();
27
+ if (code === 0)
28
+ return done();
29
+ const stopped = `did not finish in ${timeoutMs / 1000} s; stopped (${how(code, signal)})`;
30
+ fail(failed(what, late ? stopped : how(code, signal)));
31
+ });
32
+ });
33
+ const hasBuildScript = (dir) => {
34
+ if (!existsSync(join(dir, 'package.json')))
35
+ throw new CliError('invalid_argument', `no package.json in ${dir}: run it in an extension package folder`);
36
+ const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
37
+ return typeof pkg.scripts?.['build'] === 'string';
38
+ };
39
+ const defaultDeps = { npm: npmIn, tool: loadKitTool };
40
+ // The author's build script, the kit's contract files, then the kit's check; no Docker.
41
+ export const buildPackage = async (folder = '.', deps = defaultDeps) => {
42
+ const dir = resolve(folder);
43
+ const built = hasBuildScript(dir);
44
+ if (built)
45
+ await deps.npm(dir, ['run', 'build']);
46
+ const kit = await deps.tool();
47
+ const contracts = await kit.writeContracts(dir);
48
+ for (const file of contracts)
49
+ console.log(`wrote ${file}`);
50
+ return { dir, built, contracts, report: await kit.check(dir) };
51
+ };
@@ -1,8 +1,10 @@
1
- import { type Plan } from '../../core/installer/plan.js';
2
1
  import { type Profile } from '../../core/profile/schema.js';
2
+ import { type ProfilePlan } from './profile-plan.js';
3
3
  export interface PlanOptions {
4
4
  json?: boolean;
5
+ file: boolean;
6
+ from: string;
5
7
  }
6
- export declare const planLines: ({ extensions, summary: s }: Plan) => string[];
8
+ export declare const planLines: ({ extensions, summary: s, skipped }: ProfilePlan) => string[];
7
9
  export declare const printDryRun: (profile: Profile, opts: PlanOptions) => void;
8
10
  export declare const runSetupCheck: (profile: Profile, opts: PlanOptions) => void;
@@ -1,32 +1,32 @@
1
1
  import { DEFAULT_REGISTRY } from '../../core/installer/npm.js';
2
- import { currentDependencies, driftLines, lockDrift, pendingChanges, planChanges, } from '../../core/installer/plan.js';
3
- import { NO_MACHINE, readMachine } from '../../core/profile/machine.js';
4
- import { effective, keepMachine } from '../../core/profile/merge.js';
2
+ import { existsSync } from 'node:fs';
3
+ import {} from '../../core/installer/plan.js';
4
+ import { machinePath } from '../../core/paths.js';
5
+ import { readMachine } from '../../core/profile/machine.js';
6
+ import { keepMachine } from '../../core/profile/merge.js';
5
7
  import { readProfile } from '../../core/profile/profile.js';
6
8
  import {} from '../../core/profile/schema.js';
7
- import { line } from './install-load.js';
8
- // Desired: the profile, with this machine's own entry from profile.json as setup keeps it.
9
- const planFor = (profile, machine) => {
9
+ import { line } from './line.js';
10
+ import { accountProfileInstalled, NOT_EXTENSION, profilePlan, } from './profile-plan.js';
11
+ // What setup would send to the daemon, with this machine's own entry from profile.json kept. A
12
+ // file (`--profile`) is never gated; the local profile is, once the account profile was installed.
13
+ const planFor = (profile, file) => {
10
14
  const local = readProfile();
11
- const id = machine?.id ?? '';
12
- const desired = keepMachine(profile, local?.ok ? local.profile : null, id);
13
- return planChanges(effective(desired, machine ?? NO_MACHINE), currentDependencies());
14
- };
15
- const entryLine = ({ verb, name, wanted, current }) => {
16
- if (verb === 'add')
17
- return `+ add ${name} ${wanted}`;
18
- if (verb === 'update')
19
- return `~ update ${name} ${wanted} (was ${current})`;
20
- return verb === 'remove' ? `- remove ${name}` : `o off ${name}`;
15
+ const desired = keepMachine(profile, local?.ok ? local.profile : null, readMachine()?.id ?? '');
16
+ return profilePlan(desired, !file && accountProfileInstalled());
21
17
  };
18
+ const entryLine = ({ verb, name, wanted }) => verb === 'add' ? `+ add ${name} ${wanted}` : `o off ${name} ${wanted} (installed disabled)`;
22
19
  // One line per extension setup would touch or leaves off, then one summary line.
23
- export const planLines = ({ extensions, summary: s }) => {
20
+ export const planLines = ({ extensions, summary: s, skipped }) => {
24
21
  const shown = extensions.filter((entry) => entry.verb !== 'unchanged');
22
+ const skips = skipped.map((name) => `- ${name}: ${NOT_EXTENSION}`);
25
23
  if (shown.length === 0)
26
- return ['plan: nothing to change'];
27
- const total = `${s.add} to add, ${s.update} to update, ${s.remove} to remove`;
28
- return [...shown.map(entryLine), `plan: ${total}, ${s.off} off, ${s.unchanged} unchanged`];
24
+ return [...skips, 'plan: nothing to change'];
25
+ const total = `${s.add} to add, ${s.off} off, ${s.unchanged} already installed`;
26
+ return [...shown.map(entryLine), ...skips, `plan: ${total}`];
29
27
  };
28
+ // --check and --dry-run read no account: the plan says which profile it is of.
29
+ const sourceLine = ({ file, from }) => line('from', file ? from : `${from} on this machine; plain setup installs your account profile`);
30
30
  // One line per scope the profile routes, then the registry for everything else.
31
31
  const registryLines = (registries) => {
32
32
  const all = [...Object.entries(registries), ['default', DEFAULT_REGISTRY]];
@@ -35,32 +35,32 @@ const registryLines = (registries) => {
35
35
  };
36
36
  // `setup --dry-run`: reads only, never creates machine.json.
37
37
  export const printDryRun = (profile, opts) => {
38
- const plan = planFor(profile, readMachine());
38
+ const plan = planFor(profile, opts.file);
39
39
  if (opts.json)
40
- return console.log(JSON.stringify(plan, null, 2));
40
+ return console.log(JSON.stringify({ ...plan, source: opts.from }, null, 2));
41
41
  const header = [line('dry run', 'nothing written'), ...registryLines(profile.registries)];
42
- for (const text of [...header, ...planLines(plan)])
42
+ for (const text of [...header, ...planLines(plan), sourceLine(opts)])
43
43
  console.log(text);
44
44
  };
45
- const LOCK_MISMATCH = 'lock mismatch: extensions/package-lock.json does not match the current tree';
46
- // What applying the plan would not fix: a lock that disagrees with its tree.
47
- const lockProblems = () => {
48
- const { integrity, matches } = lockDrift();
49
- if (integrity.length > 0)
50
- return driftLines(integrity);
51
- return matches ? [] : [LOCK_MISMATCH];
45
+ // A machine.json that does not parse is not "missing": setup would not make a new one over it.
46
+ const machineProblem = () => {
47
+ if (readMachine())
48
+ return [];
49
+ return [
50
+ existsSync(machinePath()) ? 'machine.json: invalid, fix or delete it' : 'machine.json: missing',
51
+ ];
52
52
  };
53
- // `setup --check`: the plan, then exit 1 for anything setup would change or cannot trust.
53
+ // `setup --check`: the plan, then exit 1 for anything setup would install.
54
54
  export const runSetupCheck = (profile, opts) => {
55
- const machine = readMachine();
56
- const plan = planFor(profile, machine);
57
- const problems = [...(machine ? [] : ['machine.json: missing']), ...lockProblems()];
55
+ const plan = planFor(profile, opts.file);
56
+ const problems = machineProblem();
58
57
  if (opts.json)
59
- console.log(JSON.stringify({ ...plan, problems }, null, 2));
58
+ console.log(JSON.stringify({ ...plan, problems, source: opts.from }, null, 2));
60
59
  else
61
- for (const text of planLines(plan))
60
+ for (const text of [...planLines(plan), sourceLine(opts)])
62
61
  console.log(text);
63
- const changes = pendingChanges(plan.summary);
62
+ const { add, off } = plan.summary;
63
+ const changes = [add && `${add} to add`, off && `${off} to install disabled`].filter(Boolean);
64
64
  const pending = changes.length > 0 ? [`not converged: ${changes.join(', ')}`] : [];
65
65
  if (problems.length + pending.length > 0)
66
66
  throw new Error([...problems, ...pending].join('\n'));
@@ -0,0 +1,16 @@
1
+ import { type Plan } from '../../core/installer/plan.js';
2
+ import { type Profile } from '../../core/profile/schema.js';
3
+ export declare const profileMarkerPath: () => string;
4
+ export declare const accountProfileInstalled: () => boolean;
5
+ export declare const NOT_EXTENSION = "not an extension, skipped";
6
+ export interface ProfileEntry {
7
+ name: string;
8
+ range: string;
9
+ id: string | null;
10
+ off: boolean;
11
+ }
12
+ export declare const profileEntries: (profile: Profile) => ProfileEntry[];
13
+ export type ProfilePlan = Plan & {
14
+ skipped: string[];
15
+ };
16
+ export declare const profilePlan: (profile: Profile, done: boolean) => ProfilePlan;
@@ -0,0 +1,48 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import {} from '../../core/installer/plan.js';
4
+ import { installationRows } from '../../core/loader/installed.js';
5
+ import { readMachine } from '../../core/profile/machine.js';
6
+ import {} from '../../core/profile/schema.js';
7
+ import { getConfigDir } from '../../lib/fs/config.js';
8
+ const PACKAGE_ID = /^(?:@agentage\/extension-|agentage-extension-)([a-z][a-z0-9-]*)$/;
9
+ // Written once plain setup tried every entry of the account profile: once per machine.
10
+ export const profileMarkerPath = () => join(getConfigDir(), 'setup.profile-installed');
11
+ export const accountProfileInstalled = () => existsSync(profileMarkerPath());
12
+ // A profile entry the daemon can never install: said once, never a change to make.
13
+ export const NOT_EXTENSION = 'not an extension, skipped';
14
+ export const profileEntries = (profile) => {
15
+ const off = profile.machines[readMachine()?.id ?? '']?.off ?? [];
16
+ return Object.entries(profile.extensions).map(([name, range]) => ({
17
+ name,
18
+ range,
19
+ id: PACKAGE_ID.exec(name)?.[1] ?? null,
20
+ off: off.includes(name),
21
+ }));
22
+ };
23
+ const verbOf = (entry, have, done) => {
24
+ if (done || (entry.id !== null && have.has(entry.id)))
25
+ return 'unchanged';
26
+ return entry.off ? 'off' : 'add';
27
+ };
28
+ // What setup would send to the daemon: add, add disabled (off), or nothing (unchanged). Reads
29
+ // installation.json only; `done` is a plain setup that installed the account profile already.
30
+ export const profilePlan = (profile, done) => {
31
+ const rows = new Map(installationRows().map((row) => [row.id, row]));
32
+ const entries = profileEntries(profile);
33
+ const extensions = entries.flatMap((entry) => entry.id === null
34
+ ? []
35
+ : [
36
+ {
37
+ verb: verbOf(entry, new Set(rows.keys()), done),
38
+ name: entry.name,
39
+ wanted: entry.range,
40
+ current: rows.has(entry.id) ? 'installed' : null,
41
+ },
42
+ ]);
43
+ const summary = { add: 0, update: 0, remove: 0, off: 0, unchanged: 0 };
44
+ for (const entry of extensions)
45
+ summary[entry.verb] += 1;
46
+ const skipped = entries.filter((entry) => entry.id === null).map((entry) => entry.name);
47
+ return { extensions, summary, skipped };
48
+ };
@@ -4,11 +4,12 @@ import { type Exec } from './release-guard.js';
4
4
  export type ExtensionReleaseOptions = {
5
5
  dir?: string;
6
6
  timeout?: number;
7
+ json?: boolean;
7
8
  };
8
9
  export interface ReleaseDeps {
9
10
  exec: (cwd: string, seconds?: number) => Exec;
10
11
  tool: LoadKitTool;
11
12
  env: NodeJS.ProcessEnv;
12
13
  }
13
- export declare const runExtensionRelease: ({ dir, timeout }?: ExtensionReleaseOptions, deps?: ReleaseDeps) => Promise<void>;
14
+ export declare const runExtensionRelease: ({ dir, timeout }?: ExtensionReleaseOptions, deps?: ReleaseDeps) => Promise<unknown>;
14
15
  export declare const addRelease: (group: Command, release: (opts: ExtensionReleaseOptions) => Promise<void>) => void;
@@ -2,13 +2,14 @@ import { mkdtemp, writeFile } from 'node:fs/promises';
2
2
  import { tmpdir } from 'node:os';
3
3
  import { join } from 'node:path';
4
4
  import {} from 'commander';
5
- import { runExtensionBuild } from './build.js';
5
+ import { addJson, CliError } from '../../lib/json-output.js';
6
+ import { runImageBuild } from './build.js';
6
7
  import { loadKitTool } from './kit-tool.js';
7
8
  import { execIn, IMAGE_PARTS, RECORD, releaseGuard } from './release-guard.js';
8
9
  const defaultDeps = { exec: execIn, tool: loadKitTool, env: process.env };
9
10
  const step = (line) => console.log(`PASS ${line}`);
10
11
  const fail = (line) => {
11
- throw new Error(`FAIL ${line}`);
12
+ throw new CliError('release_refused', `FAIL ${line}`);
12
13
  };
13
14
  // Tokens leave the environment, so docker build and npm lifecycle scripts never see them.
14
15
  const takeSecrets = (env) => {
@@ -115,19 +116,19 @@ export const runExtensionRelease = async ({ dir = '.', timeout = 60 } = {}, deps
115
116
  const done = isPrivate ? 'is released' : 'is released: npm only';
116
117
  step(`guard: ${tag} ${build ? 'has no record and no image: build' : done}`);
117
118
  if (build) {
118
- await runExtensionBuild({ push: true, dir }, deps.tool);
119
+ await runImageBuild({ push: true, dir }, deps.tool);
119
120
  await attach(run, tag, repo);
120
121
  }
121
122
  if (isPrivate)
122
- return step('npm: private package, not published');
123
- const push = scoped(deps.exec(dir, PUBLISH_SECONDS), secrets);
124
- await publish(run, push, pkg, secrets['npm']?.['NPM_TOKEN']);
123
+ step('npm: private package, not published');
124
+ else
125
+ await publish(run, scoped(deps.exec(dir, PUBLISH_SECONDS), secrets), pkg, secrets['npm']?.['NPM_TOKEN']);
126
+ return { id, version: pkg.version, tag, built: build, published: !isPrivate };
125
127
  };
126
128
  export const addRelease = (group, release) => {
127
- group
129
+ addJson(group
128
130
  .command('release')
129
131
  .description('Release an extension from its v* tag in CI: guard, images, record, npm package')
130
132
  .option('--dir <path>', 'the extension package folder (default: the current folder)')
131
- .option('--timeout <seconds>', 'bound on each git, GitHub and npm check (default: 60; npm publish: 300)', Number)
132
- .action(release);
133
+ .option('--timeout <seconds>', 'bound on each git, GitHub and npm check (default: 60; npm publish: 300)', Number)).action(release);
133
134
  };
@@ -1,5 +1,4 @@
1
1
  import { type ExtensionRow, type ExtensionsStatus } from './rows.js';
2
2
  export declare const summaryLines: (status: ExtensionsStatus) => string[];
3
- export type Latest = ReadonlyMap<string, string | null>;
4
- export declare const rowLines: (rows: ExtensionRow[], latest?: Latest) => string[];
3
+ export declare const rowLines: (rows: ExtensionRow[]) => string[];
5
4
  export declare const printWarnings: (warnings: string[]) => void;