@agentage/cli 0.51.1 → 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 (150) hide show
  1. package/README.md +26 -15
  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 +33 -12
  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 -96
  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/sync.d.ts +6 -11
  58. package/dist/commands/extension/sync.js +8 -50
  59. package/dist/commands/extension/up-commands.d.ts +9 -0
  60. package/dist/commands/extension/up-commands.js +74 -0
  61. package/dist/commands/extension/up-local.d.ts +21 -0
  62. package/dist/commands/extension/up-local.js +94 -0
  63. package/dist/commands/extension/up-run.d.ts +23 -0
  64. package/dist/commands/extension/up-run.js +75 -0
  65. package/dist/commands/extension/up.d.ts +10 -10
  66. package/dist/commands/extension/up.js +62 -74
  67. package/dist/commands/update/update.d.ts +9 -1
  68. package/dist/commands/update/update.js +20 -6
  69. package/dist/core/installer/compare-lock.d.ts +0 -2
  70. package/dist/core/installer/compare-lock.js +0 -12
  71. package/dist/core/installer/compat.js +5 -3
  72. package/dist/core/installer/npm.d.ts +1 -0
  73. package/dist/core/installer/npm.js +6 -0
  74. package/dist/core/installer/old-tree.d.ts +3 -0
  75. package/dist/core/installer/old-tree.js +45 -0
  76. package/dist/core/installer/package-dir.d.ts +11 -0
  77. package/dist/core/installer/package-dir.js +53 -0
  78. package/dist/core/installer/resolve.js +1 -2
  79. package/dist/core/installer/tree.d.ts +0 -5
  80. package/dist/core/installer/tree.js +1 -25
  81. package/dist/core/kit-id.d.ts +1 -0
  82. package/dist/core/kit-id.js +20 -0
  83. package/dist/core/loader/discover.d.ts +7 -1
  84. package/dist/core/loader/discover.js +5 -4
  85. package/dist/core/loader/installed.d.ts +9 -0
  86. package/dist/core/loader/installed.js +51 -0
  87. package/dist/core/loader/manifest.d.ts +4 -0
  88. package/dist/core/loader/manifest.js +25 -3
  89. package/dist/core/loader/scan.d.ts +2 -1
  90. package/dist/core/loader/scan.js +17 -4
  91. package/dist/core/loader/secrets.d.ts +0 -7
  92. package/dist/core/loader/secrets.js +0 -11
  93. package/dist/core/loader/verbs.d.ts +0 -1
  94. package/dist/core/loader/verbs.js +1 -13
  95. package/dist/core/profile/machine.d.ts +0 -1
  96. package/dist/core/profile/machine.js +0 -5
  97. package/dist/lib/auth/introspect.js +1 -2
  98. package/dist/lib/auth/sign-in.js +3 -0
  99. package/dist/lib/child-env.d.ts +1 -0
  100. package/dist/lib/child-env.js +6 -0
  101. package/dist/lib/daemon/daemon-answer.d.ts +8 -0
  102. package/dist/lib/daemon/daemon-answer.js +38 -0
  103. package/dist/lib/daemon/daemon-client.d.ts +17 -0
  104. package/dist/lib/daemon/daemon-client.js +112 -0
  105. package/dist/lib/daemon/daemon-file.d.ts +16 -0
  106. package/dist/lib/daemon/daemon-file.js +30 -0
  107. package/dist/lib/daemon/daemon-health.d.ts +16 -0
  108. package/dist/lib/daemon/daemon-health.js +36 -0
  109. package/dist/lib/daemon/daemon-probe.d.ts +32 -0
  110. package/dist/lib/daemon/daemon-probe.js +41 -0
  111. package/dist/lib/daemon/daemon-stop.d.ts +13 -0
  112. package/dist/lib/daemon/daemon-stop.js +42 -0
  113. package/dist/lib/daemon/host-client.d.ts +40 -0
  114. package/dist/lib/daemon/host-client.js +45 -0
  115. package/dist/lib/exit-code.d.ts +2 -0
  116. package/dist/lib/exit-code.js +8 -0
  117. package/dist/lib/fs/json-file.d.ts +1 -0
  118. package/dist/lib/fs/json-file.js +1 -1
  119. package/dist/lib/json-output.d.ts +36 -0
  120. package/dist/lib/json-output.js +163 -0
  121. package/dist/lib/net/market-error.d.ts +12 -0
  122. package/dist/lib/net/market-error.js +28 -0
  123. package/dist/lib/net/market.d.ts +17 -2
  124. package/dist/lib/net/market.js +92 -18
  125. package/dist/lib/wait.d.ts +6 -0
  126. package/dist/lib/wait.js +17 -0
  127. package/dist/lib/with-action.d.ts +12 -0
  128. package/dist/lib/with-action.js +33 -0
  129. package/dist/program-deps.d.ts +2 -0
  130. package/dist/program-deps.js +95 -0
  131. package/dist/program.d.ts +29 -21
  132. package/dist/program.js +41 -75
  133. package/package.json +8 -6
  134. package/CHANGELOG.md +0 -68
  135. package/dist/commands/extension/install-load.d.ts +0 -7
  136. package/dist/commands/extension/install-load.js +0 -42
  137. package/dist/commands/extension/install.d.ts +0 -12
  138. package/dist/commands/extension/install.js +0 -49
  139. package/dist/commands/extension/latest.d.ts +0 -2
  140. package/dist/commands/extension/latest.js +0 -71
  141. package/dist/commands/extension/remove.d.ts +0 -15
  142. package/dist/commands/extension/remove.js +0 -86
  143. package/dist/commands/extension/secrets-prompt.d.ts +0 -6
  144. package/dist/commands/extension/secrets-prompt.js +0 -47
  145. package/dist/core/installer/installer.d.ts +0 -28
  146. package/dist/core/installer/installer.js +0 -87
  147. package/dist/core/installer/latest.d.ts +0 -27
  148. package/dist/core/installer/latest.js +0 -90
  149. package/dist/core/profile/edit.d.ts +0 -4
  150. package/dist/core/profile/edit.js +0 -27
@@ -0,0 +1,57 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { existingOf } from '../../lib/daemon/daemon-answer.js';
3
+ import {} from '../../lib/daemon/host-client.js';
4
+ import { CliError, DaemonError } from '../../lib/json-output.js';
5
+ // The add itself is the check, so two cli runs cannot both add one id: the second gets CONFLICT,
6
+ // whose details name the installed entry.
7
+ const added = (host, body) => host.add(body).catch((err) => {
8
+ const existing = err instanceof DaemonError ? existingOf(err) : null;
9
+ if (existing)
10
+ return existing;
11
+ throw err;
12
+ });
13
+ const isExisting = (got) => !('state' in got);
14
+ const elsewhere = (what, id) => new CliError('already_installed', `${what}; agentage extension remove ${id} first`);
15
+ // The row of an id: added now, or the one the daemon has (removed in between: added again).
16
+ export const addOnce = async (host, spec) => {
17
+ const got = await added(host, spec);
18
+ if (!isExisting(got))
19
+ return { row: got, already: false };
20
+ const row = (await host.list()).find((r) => r.id === spec.id);
21
+ return row ? { row, already: true } : { row: await host.add(spec), already: false };
22
+ };
23
+ // An id installed already: another version is a change of version (go back, data kept).
24
+ export const installId = async (host, spec) => {
25
+ const got = await addOnce(host, spec);
26
+ if (!got.already)
27
+ return got;
28
+ const { id, source } = got.row;
29
+ if (source !== 'market')
30
+ throw elsewhere(`${id} runs from the folder ${source}`, id);
31
+ if (spec.version && spec.version !== got.row.version)
32
+ return { row: await host.change(id, { version: spec.version }), already: false };
33
+ return got;
34
+ };
35
+ const real = (path) => {
36
+ try {
37
+ return realpathSync(path);
38
+ }
39
+ catch {
40
+ return path;
41
+ }
42
+ };
43
+ // A folder: the same folder again (by real path) is installed already; its id from elsewhere is
44
+ // refused.
45
+ export const installFolder = async (host, source) => {
46
+ const got = await added(host, { source });
47
+ if (!isExisting(got))
48
+ return { row: got, already: false };
49
+ const { id } = got;
50
+ const where = got.source ? `the folder ${got.source}` : 'the market';
51
+ if (!got.source || real(got.source) !== real(source))
52
+ throw elsewhere(`${id} is installed from ${where}`, id);
53
+ const row = (await host.list()).find((r) => r.id === id);
54
+ if (row)
55
+ return { row, already: true };
56
+ return { row: await host.add({ source }), already: false };
57
+ };
@@ -1,6 +1,6 @@
1
1
  import type * as Kit from '@agentage/extension/tool';
2
2
  import { type KitCheck } from '../../core/loader/load.js';
3
- export type KitTool = Pick<typeof Kit, 'check' | 'checkLines' | 'build' | 'buildLines' | 'runCommand' | 'checkCli' | 'up' | 'down' | 'token' | 'readManifest'>;
3
+ export type KitTool = Pick<typeof Kit, 'check' | 'checkLines' | 'build' | 'buildLines' | 'runCommand' | 'checkCli' | 'up' | 'down' | 'token' | 'readManifest' | 'writeContracts'>;
4
4
  export type LoadKitTool = () => Promise<KitTool>;
5
5
  export declare const loadKitTool: LoadKitTool;
6
6
  export declare const kitCheck: (tool?: LoadKitTool) => KitCheck;
@@ -0,0 +1,19 @@
1
+ import { type Command } from 'commander';
2
+ import { type ConfigureOptions } from './configure.js';
3
+ import { type InstallOptions, type RemoveOptions } from './lifecycle.js';
4
+ import { type ListOptions, type ExtensionUpdateOptions } from './lifecycle-list.js';
5
+ type Action<T> = (opts: T) => Promise<void>;
6
+ export interface LifecycleActions {
7
+ install: Action<InstallOptions>;
8
+ list: Action<ListOptions>;
9
+ update: Action<ExtensionUpdateOptions>;
10
+ enabled: Action<{
11
+ id: string;
12
+ enabled: boolean;
13
+ json?: boolean;
14
+ }>;
15
+ configure: Action<ConfigureOptions>;
16
+ remove: Action<RemoveOptions>;
17
+ }
18
+ export declare const addLifecycle: (group: Command, actions: LifecycleActions) => void;
19
+ export {};
@@ -0,0 +1,80 @@
1
+ import {} from 'commander';
2
+ import { addJson } from '../../lib/json-output.js';
3
+ import {} from './configure.js';
4
+ import {} from './lifecycle.js';
5
+ import {} from './lifecycle-list.js';
6
+ const INSTALL_HELP = `
7
+ Every lifecycle command is a client of the daemon (agentage daemon status) and starts it when
8
+ none runs. <id> asks the market for its newest version; <id>@<version> installs that version,
9
+ and over an installed one changes to it, data kept (go back). A local path (./path, ../path,
10
+ /path) runs that folder itself, no copy; a folder another user can write is refused. The
11
+ extension then runs: its api at 127.0.0.1:4243/api/<id>/ and its commands in agentage --help.`;
12
+ const LIST_HELP = `
13
+ One row per installed extension: id, version, source (market or folder) and state (starting,
14
+ running, failed with the reason, disabled). --json gives the daemon's rows. --available reads
15
+ the market instead: each listed id with its newest version.`;
16
+ const REMOVE_HELP = `
17
+ Stops the extension and forgets its settings and secrets; its data folder (data/<id>/ in the
18
+ config folder) stays. --purge also deletes it, after asking; without a terminal it needs --yes.`;
19
+ const CONFIGURE_HELP = `
20
+ The daemon starts the extension again with the new values, then moves its route: the daemon does
21
+ not restart and no request is lost. --secret stores the values as secrets (never printed); a
22
+ single <key> with no =value reads the value from stdin, or asks for it on a terminal.`;
23
+ const addInstall = (group, { install, list }) => {
24
+ addJson(group
25
+ .command('install')
26
+ .description('Install an extension in the daemon and run it')
27
+ .argument('<name>', '<id>, <id>@<version> or a local folder')
28
+ .option('--off', 'old name of: install, then extension disable'))
29
+ .addHelpText('after', INSTALL_HELP)
30
+ .action((name, opts) => install({ name, ...opts }));
31
+ addJson(group
32
+ .command('list')
33
+ .description('Show each installed extension: id, version, source, state')
34
+ .option('--available', 'what the market offers, with the newest versions'))
35
+ .addHelpText('after', LIST_HELP)
36
+ .action(list);
37
+ };
38
+ const addChanges = (group, { update, enabled }) => {
39
+ addJson(group
40
+ .command('update')
41
+ .description('Move each market extension, or one, to its newest version')
42
+ .argument('[id]', 'only this extension')
43
+ .option('--check', 'only report what would change')).action((id, opts) => update({ ...opts, id }));
44
+ for (const [name, on] of [
45
+ ['disable', false],
46
+ ['enable', true],
47
+ ])
48
+ addJson(group
49
+ .command(name)
50
+ .description(on ? 'Run a disabled extension again' : 'Stop an extension, keep its data')
51
+ .argument('<id>', 'the extension id')).action((id, opts) => enabled({ ...opts, id, enabled: on }));
52
+ };
53
+ const addConfigure = (group, configure) => {
54
+ addJson(group
55
+ .command('configure')
56
+ .description('Set settings (or --secret secrets) of an extension, no restart')
57
+ .argument('<id>', 'the extension id')
58
+ .argument('<pairs...>', '<key>=<value>, one or more')
59
+ .option('--secret', 'store them as secrets'))
60
+ .addHelpText('after', CONFIGURE_HELP)
61
+ .action((id, pairs, opts) => configure({ ...opts, id, pairs }));
62
+ };
63
+ const addRemove = (group, remove) => {
64
+ addJson(group
65
+ .command('remove')
66
+ .description('Stop and remove an extension; its data stays unless --purge')
67
+ .argument('<id>', 'the extension id')
68
+ .option('--purge', "also delete the extension's data, data/<id>/")
69
+ .option('--yes', 'do not ask before --purge deletes (needed without a terminal)')
70
+ .option('--force', 'remove it although another installed extension depends on it'))
71
+ .addHelpText('after', REMOVE_HELP)
72
+ .action((name, opts) => remove({ name, ...opts }));
73
+ };
74
+ // C1: install, list, update, disable, enable, configure, remove.
75
+ export const addLifecycle = (group, actions) => {
76
+ addInstall(group, actions);
77
+ addChanges(group, actions);
78
+ addConfigure(group, actions.configure);
79
+ addRemove(group, actions.remove);
80
+ };
@@ -0,0 +1,26 @@
1
+ import { type HostRow } from '../../lib/daemon/host-client.js';
2
+ import { WithMeta } from '../../lib/json-output.js';
3
+ import { type Listing, type Market } from '../../lib/net/market.js';
4
+ import { type LifecycleDeps } from './lifecycle.js';
5
+ export interface ListOptions {
6
+ available?: boolean;
7
+ json?: boolean;
8
+ }
9
+ export interface ExtensionUpdateOptions {
10
+ id?: string;
11
+ check?: boolean;
12
+ json?: boolean;
13
+ }
14
+ export interface ListDeps extends LifecycleDeps {
15
+ available: () => Promise<Listing>;
16
+ market: () => Market;
17
+ npmNewest: (id: string) => Promise<string>;
18
+ }
19
+ export declare const table: (rows: string[][]) => string[];
20
+ export declare const runList: (opts: ListOptions, deps: ListDeps) => Promise<WithMeta | HostRow[]>;
21
+ export declare const runUpdate: (opts: ExtensionUpdateOptions, deps: ListDeps) => Promise<{
22
+ updated: boolean;
23
+ id: string;
24
+ from: string;
25
+ to: string;
26
+ }[]>;
@@ -0,0 +1,92 @@
1
+ import {} from '../../lib/daemon/host-client.js';
2
+ import { CliError, messageOf, WithMeta } from '../../lib/json-output.js';
3
+ import {} from '../../lib/net/market.js';
4
+ import { fromNpmLine, noSiteMarket } from '../../lib/net/market-error.js';
5
+ import { siteFqdn } from '../../lib/net/origins.js';
6
+ import { pruneUnused } from './lifecycle.js';
7
+ // The daemon's rows as they are; a folder entry says `folder` and keeps its path.
8
+ const shown = (row) => row.source === 'market' ? row : { ...row, source: 'folder', path: row.source };
9
+ export const table = (rows) => {
10
+ const widths = rows[0]?.map((_, i) => Math.max(...rows.map((r) => (r[i] ?? '').length))) ?? [];
11
+ return rows.map((r) => r
12
+ .map((cell, i) => cell.padEnd(widths[i] ?? 0))
13
+ .join(' ')
14
+ .trimEnd());
15
+ };
16
+ const printRows = (rows) => {
17
+ const cells = rows.map((r) => [r.id, r.version, r.source, r.state, r.error ?? '']);
18
+ const lines = table([['ID', 'VERSION', 'SOURCE', 'STATE', ''], ...cells]);
19
+ for (const line of rows.length > 0 ? lines : ['no extensions'])
20
+ console.log(line);
21
+ };
22
+ // A row the market cannot answer for is left out and named on stderr; the others are listed.
23
+ const available = async (deps) => {
24
+ const { offered, skipped } = await deps.available();
25
+ const lines = table([['ID', 'VERSION'], ...offered.map((o) => [o.id, o.version])]);
26
+ for (const line of offered.length > 0 ? lines : ['the market lists nothing'])
27
+ console.log(line);
28
+ if (skipped.length > 0)
29
+ console.error(`skipped ${skipped.map((s) => `${s.id} (${s.reason})`).join(', ')}`);
30
+ return new WithMeta(offered, { skipped });
31
+ };
32
+ export const runList = async (opts, deps) => {
33
+ if (opts.available)
34
+ return available(deps);
35
+ const rows = (await (await deps.host()).list()).map(shown);
36
+ printRows(rows);
37
+ return rows;
38
+ };
39
+ // The market's newest. A market that answers without the id keeps the installed version (one
40
+ // line); only a site with no market asks npm, by the name the row was installed under.
41
+ const newestOf = async (row, market, deps) => {
42
+ const to = (await market.latest(row.id))?.version;
43
+ const down = market.down();
44
+ if (to || (down && !noSiteMarket(down)))
45
+ return to ?? null;
46
+ if (down)
47
+ return deps.npmNewest(row.id);
48
+ console.error(`${row.id}: not in the market any more; ${row.version} stays`);
49
+ return null;
50
+ };
51
+ // An id npm cannot resolve is named and skipped: the other ids still update.
52
+ const movesOf = async (rows, deps) => {
53
+ const market = deps.market();
54
+ const moves = [];
55
+ const failed = [];
56
+ for (const row of rows) {
57
+ const to = await newestOf(row, market, deps).catch((err) => {
58
+ failed.push(`${row.id}: ${messageOf(err)}`);
59
+ return null;
60
+ });
61
+ if (to && to !== row.version)
62
+ moves.push({ id: row.id, from: row.version, to });
63
+ }
64
+ const down = market.down();
65
+ if (down && !noSiteMarket(down))
66
+ throw down;
67
+ if (down && rows.length > 0)
68
+ console.error(fromNpmLine(siteFqdn(), 'newest versions'));
69
+ return { moves, failed };
70
+ };
71
+ const marketRows = async (opts, rows) => {
72
+ const chosen = rows.filter((r) => r.source === 'market' && (!opts.id || r.id === opts.id));
73
+ if (opts.id && chosen.length === 0)
74
+ throw new CliError('not_installed', `${opts.id} is not installed from the market`);
75
+ return chosen;
76
+ };
77
+ // The market's newest version for each extension it installed (or one); --check changes nothing.
78
+ // On a site with no market, an id npm cannot resolve fails the run at the end (exit 1).
79
+ export const runUpdate = async (opts, deps) => {
80
+ const host = await deps.host();
81
+ const { moves, failed } = await movesOf(await marketRows(opts, await host.list()), deps);
82
+ for (const { id, from, to } of moves) {
83
+ if (!opts.check)
84
+ await host.change(id, { version: to }).then(() => pruneUnused(id));
85
+ console.log(`${id} ${from} to ${to}${opts.check ? ' (available)' : ''}`);
86
+ }
87
+ if (moves.length === 0 && failed.length === 0)
88
+ console.log('every extension is at its newest version');
89
+ if (failed.length > 0)
90
+ throw new CliError('extension_failed', `no newest version found:\n ${failed.join('\n ')}`);
91
+ return moves.map((move) => ({ ...move, updated: !opts.check }));
92
+ };
@@ -0,0 +1,41 @@
1
+ import { type HostClient, type HostSummary } from '../../lib/daemon/host-client.js';
2
+ export interface LifecycleDeps {
3
+ host: () => Promise<HostClient>;
4
+ }
5
+ export interface ConfirmIo {
6
+ isTTY: boolean;
7
+ prompt: (question: string) => Promise<string>;
8
+ }
9
+ export interface InstallOptions {
10
+ name: string;
11
+ off?: boolean;
12
+ json?: boolean;
13
+ }
14
+ export interface RemoveOptions {
15
+ name: string;
16
+ purge?: boolean;
17
+ yes?: boolean;
18
+ force?: boolean;
19
+ json?: boolean;
20
+ }
21
+ export declare const specOf: (name: string) => {
22
+ id: string;
23
+ version?: string;
24
+ };
25
+ export declare const summaryOf: ({ id, version, state, error }: HostSummary) => HostSummary;
26
+ export declare const report: (done: HostSummary, note?: string) => HostSummary;
27
+ export interface InstallDeps extends LifecycleDeps {
28
+ fromNpm?: (id: string, what: string) => Promise<string | null>;
29
+ hasMarket?: (id: string) => Promise<boolean>;
30
+ }
31
+ export declare const runInstall: (opts: InstallOptions, deps: InstallDeps) => Promise<HostSummary>;
32
+ export declare const runEnabled: (id: string, enabled: boolean, deps: LifecycleDeps) => Promise<HostSummary>;
33
+ export declare const terminalIo: () => ConfirmIo;
34
+ export declare const confirmed: (io: ConfirmIo, question: string) => Promise<boolean>;
35
+ export declare const pruneUnused: (id: string) => string[];
36
+ export declare const runRemove: (opts: RemoveOptions, deps: LifecycleDeps & {
37
+ io: ConfirmIo;
38
+ }) => Promise<{
39
+ id: string;
40
+ purged: boolean;
41
+ }>;
@@ -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,82 +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 bare id like memory
60
- asks the market first and takes its latest version (a private entry has no npm package and is
61
- refused), else it is @agentage/extension-memory, then agentage-extension-memory. A package goes into
62
- profile.json (created from the default profile when absent), from the registry the profile
63
- names for its scope; --off keeps it from loading on this machine. Then installs and loads like
64
- setup, and exits 1 when an extension failed. Never signs in. On a machine whose profile comes
65
- from your account, the change applies to the account's newest profile and is pushed (with npm's
66
- lock) once everything loaded; if another machine pushed in between, it is replayed once on that
67
- profile. The commands of a package built on the kit run as agentage <command> and always as
68
- agentage <id> <command>; one whose name is a core command, an extension id or a command an
69
- earlier install took runs only as agentage <id> <command>, and one line says so.`;
70
- const REMOVE_HELP = `
71
- <name> is a package name, a short name or an extension id. Refused while another extension
72
- peer-depends on it. Takes it out of profile.json and this machine's off list, or out of
73
- machine.json for a dev extension, deletes state/<id>.json, then installs and loads the rest like
74
- setup, and pushes the profile to your account like install. --purge also deletes data/<id>/
75
- after asking; without a terminal it needs --yes.`;
76
- const LIST_HELP = `
77
- One row per extension in the profile, a dev path or the installed tree: id, state (installed,
78
- off, blocked, invalid, missing), what setup would change (add, update, remove; blank for
79
- nothing), package, installed version, wanted range, contributed commands, the last run from
80
- state/<id>.json, and the reason when it cannot load. Extension code is never loaded; the only
81
- file written is machine.json.`;
82
20
  const DOCTOR_HELP = `
83
21
  Loads every extension this machine can run, once, the way setup does: what an extension prints
84
22
  while loading goes to stderr, state/<id>.json is rewritten for each, and the rows show ok or
@@ -93,30 +31,7 @@ export const helpOrUnknown = (_opts, group) => {
93
31
  group.help();
94
32
  group.error(`error: unknown command '${name}'`, { code: 'commander.unknownCommand' });
95
33
  };
96
- const addChanges = (group, { install, remove }) => {
97
- group
98
- .command('install')
99
- .description('Add an extension to the profile, then install and load it')
100
- .argument('<name>', 'package name[@range], short name, https: tarball URL or local path')
101
- .option('--off', 'install it, but do not load it on this machine')
102
- .addHelpText('after', INSTALL_HELP)
103
- .action((name, opts) => install({ name, ...opts }));
104
- group
105
- .command('remove')
106
- .description('Remove an extension from the profile, then install and load the rest')
107
- .argument('<name>', 'package name, short name or extension id')
108
- .option('--purge', "also delete the extension's data, data/<id>/")
109
- .option('--yes', 'do not ask before --purge deletes (needed without a terminal)')
110
- .addHelpText('after', REMOVE_HELP)
111
- .action((name, opts) => remove({ name, ...opts }));
112
- };
113
- const addReports = (group, { list, doctor }) => {
114
- group
115
- .command('list')
116
- .description('Show one row per extension: state, versions, commands, last run')
117
- .option('--json', 'machine-readable output')
118
- .addHelpText('after', LIST_HELP)
119
- .action(list);
34
+ const addDoctor = (group, doctor) => {
120
35
  group
121
36
  .command('doctor')
122
37
  .description('Load every extension once and refresh its state: ok or failed')
@@ -124,15 +39,15 @@ const addReports = (group, { list, doctor }) => {
124
39
  .addHelpText('after', DOCTOR_HELP)
125
40
  .action(doctor);
126
41
  };
127
- // 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.
128
43
  export const registerExtension = (program, actions) => {
129
44
  const group = program
130
45
  .command('extension')
131
46
  .description('Work with the extensions on this machine')
132
47
  .allowExcessArguments()
133
48
  .action(helpOrUnknown);
134
- addChanges(group, actions);
135
- addReports(group, actions);
49
+ addLifecycle(group, actions);
50
+ addDoctor(group, actions.doctor);
136
51
  addCreate(group, actions.create);
137
52
  addBuild(group, actions);
138
53
  addRelease(group, actions.release);