@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,12 @@
1
+ import { CliError } from '../json-output.js';
2
+ export type MarketCode = 'no_discovery' | 'no_market' | 'market_unreachable' | 'market_failed' | 'market_timeout';
3
+ export declare const marketError: (code: MarketCode, text: string) => CliError;
4
+ export declare const noSiteMarket: (err: CliError | null) => boolean;
5
+ export declare const fromNpmLine: (fqdn: string, what: string) => string;
6
+ export declare const npmFallbackLine: (fqdn: string, id: string, what: string, down: CliError | null) => string | null;
7
+ export declare const noDiscovery: (fqdn: string, url: string, why: string) => CliError;
8
+ export declare const noMarket: (fqdn: string, url: string) => CliError;
9
+ export declare const notTheDocument: (url: string, why: string) => CliError;
10
+ export declare const isTimeout: (err: unknown) => boolean;
11
+ export declare const unreached: (url: string, err: unknown, timeoutMs: number) => CliError;
12
+ export declare const answered: (url: string, status: number, why?: string) => CliError;
@@ -0,0 +1,28 @@
1
+ import { CliError } from '../json-output.js';
2
+ const CHOOSE = 'choose another site with AGENTAGE_SITE_FQDN=<site>';
3
+ export const marketError = (code, text) => new CliError(code, text);
4
+ // 0.51: a site with no market resolves an id on npm. An unreachable or failing market stays an error.
5
+ export const noSiteMarket = (err) => err?.code === 'no_discovery' || err?.code === 'no_market';
6
+ export const fromNpmLine = (fqdn, what) => `${fqdn} has no extension market; ${what} from npm, as cli 0.51 did`;
7
+ // After a market lookup found no entry for id: why npm resolves it, or null when it does not
8
+ // (a market that is down stays an error). A market that answers without the id says so too.
9
+ export const npmFallbackLine = (fqdn, id, what, down) => {
10
+ if (noSiteMarket(down))
11
+ return fromNpmLine(fqdn, what);
12
+ return down
13
+ ? null
14
+ : `the market of ${fqdn} has no ${id}; ${what} from npm as @agentage/extension-${id}`;
15
+ };
16
+ export const noDiscovery = (fqdn, url, why) => marketError('no_discovery', `${fqdn} has no extension market: ${url} ${why}; ${CHOOSE}`);
17
+ export const noMarket = (fqdn, url) => marketError('no_market', `${fqdn} has no extension market: ${url} names none; ${CHOOSE}`);
18
+ // An answer, but not the discovery document: the network, not the site, may be the cause.
19
+ export const notTheDocument = (url, why) => marketError('market_unreachable', `${url} ${why}: not the discovery document; check the network`);
20
+ export const isTimeout = (err) => err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError');
21
+ // A fetch that threw: no answer in time, or no connection (the cause names why).
22
+ export const unreached = (url, err, timeoutMs) => {
23
+ if (isTimeout(err))
24
+ return marketError('market_timeout', `${url} did not answer in ${timeoutMs / 1000} s`);
25
+ const cause = err.cause?.message;
26
+ return marketError('market_unreachable', `cannot reach ${url}: ${cause ?? err.message}`);
27
+ };
28
+ export const answered = (url, status, why = '') => marketError('market_failed', `${url} answered ${status}${why && `, ${why}`}`);
@@ -1,3 +1,4 @@
1
+ import { CliError } from '../json-output.js';
1
2
  type Get = (url: string) => Promise<Response>;
2
3
  export interface Latest {
3
4
  version: string;
@@ -5,7 +6,21 @@ export interface Latest {
5
6
  }
6
7
  export interface Market {
7
8
  latest: (id: string) => Promise<Latest | null>;
8
- down: () => boolean;
9
+ down: () => CliError | null;
9
10
  }
10
- export declare const openMarket: (fqdn?: string, get?: Get) => Market;
11
+ export declare const openMarket: (fqdn?: string, get?: Get, known?: string) => Market;
12
+ export interface Offered {
13
+ id: string;
14
+ version: string;
15
+ }
16
+ export declare const MAX_PAGES = 20;
17
+ export interface Skipped {
18
+ id: string;
19
+ reason: string;
20
+ }
21
+ export interface Listing {
22
+ offered: Offered[];
23
+ skipped: Skipped[];
24
+ }
25
+ export declare const listMarket: (fqdn?: string, get?: Get) => Promise<Listing>;
11
26
  export {};
@@ -1,27 +1,53 @@
1
1
  import { isRecord } from '../fs/json-file.js';
2
+ import { CliError, messageOf } from '../json-output.js';
2
3
  import { cliFetch } from './fetch.js';
4
+ import { answered, isTimeout, marketError, noDiscovery, noMarket, notTheDocument, unreached, } from './market-error.js';
3
5
  import { links, siteFqdn } from './origins.js';
4
6
  const TIMEOUT_MS = 5_000;
5
- const UNAVAILABLE = 'market unavailable, versions not checked';
6
7
  const EXACT = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/;
7
8
  const timed = (url) => cliFetch(url, {}, { timeoutMs: TIMEOUT_MS });
9
+ const fetched = (get, url) => get(url).catch((err) => {
10
+ throw unreached(url, err, TIMEOUT_MS);
11
+ });
12
+ const bodyOf = (res, url) => res.json().catch((err) => {
13
+ throw isTimeout(err) ? unreached(url, err, TIMEOUT_MS) : answered(url, res.status, 'no JSON');
14
+ });
8
15
  const json = async (get, url) => {
9
- const res = await get(url);
16
+ const res = await fetched(get, url);
10
17
  if (res.status === 404)
11
18
  return null;
12
19
  if (!res.ok)
13
- throw new Error(`${url} answered ${res.status}`);
14
- const body = await res.json();
20
+ throw answered(url, res.status);
21
+ const body = await bodyOf(res, url);
15
22
  return isRecord(body) ? body : null;
16
23
  };
24
+ // Only the site's own 404 means it has none. A redirect or a page that is no JSON object (a
25
+ // network's sign-in page) is not the site's answer; another status is a failure.
26
+ const discovery = async (fqdn, get) => {
27
+ const url = `${links(fqdn).site}/.well-known/agentage.json`;
28
+ const res = await fetched(get, url);
29
+ if (res.status === 404)
30
+ throw noDiscovery(fqdn, url, 'answered 404');
31
+ if (res.status >= 300 && res.status < 400) {
32
+ const to = res.headers.get('location') ?? 'no Location';
33
+ throw notTheDocument(url, `answered ${res.status} to ${to}`);
34
+ }
35
+ if (!res.ok)
36
+ throw answered(url, res.status);
37
+ const doc = await res.json().catch(() => null);
38
+ if (!isRecord(doc))
39
+ throw notTheDocument(url, `answered ${res.status} with no JSON object`);
40
+ return doc;
41
+ };
17
42
  // The first market the site's discovery document names: https, or http when the site is local.
18
43
  const marketUrl = async (fqdn, get) => {
44
+ const doc = await discovery(fqdn, get);
19
45
  const { site } = links(fqdn);
20
- const doc = await json(get, `${site}/.well-known/agentage.json`);
21
- const first = Array.isArray(doc?.['markets']) ? doc['markets'][0] : undefined;
22
- const url = new URL(String(first));
23
- if (url.protocol !== 'https:' && !(url.protocol === 'http:' && site.startsWith('http:')))
24
- throw new Error('no market');
46
+ const first = Array.isArray(doc['markets']) ? doc['markets'][0] : undefined;
47
+ const url = typeof first === 'string' && URL.canParse(first) ? new URL(first) : null;
48
+ const local = url?.protocol === 'http:' && site.startsWith('http:');
49
+ if (!url || (url.protocol !== 'https:' && !local))
50
+ throw noMarket(fqdn, `${site}/.well-known/agentage.json`);
25
51
  return url.origin;
26
52
  };
27
53
  // An answer is trusted only when it names this id's own package and one exact version.
@@ -33,10 +59,10 @@ const accept = (id, { version, package: pkg }) => {
33
59
  throw refuse(`package ${JSON.stringify(pkg)} is not an extension of that id`);
34
60
  return { version, package: pkg };
35
61
  };
36
- // Never throws: a missing or silent market prints one line on stderr and answers null.
37
- export const openMarket = (fqdn = siteFqdn(), get = timed) => {
38
- let base;
39
- let told = false;
62
+ // Never throws for a missing or silent market: it answers null and `down` keeps the first reason.
63
+ export const openMarket = (fqdn = siteFqdn(), get = timed, known) => {
64
+ let base = known === undefined ? undefined : Promise.resolve(known);
65
+ let failure = null;
40
66
  const latest = async (id) => {
41
67
  let data;
42
68
  try {
@@ -44,13 +70,61 @@ export const openMarket = (fqdn = siteFqdn(), get = timed) => {
44
70
  const path = `/api/v1/extensions/${encodeURIComponent(id)}/latest`;
45
71
  data = (await json(get, `${await base}${path}`))?.['data'];
46
72
  }
47
- catch {
48
- if (!told)
49
- console.error(UNAVAILABLE);
50
- told = true;
73
+ catch (err) {
74
+ failure ??= err instanceof CliError ? err : marketError('market_failed', messageOf(err));
51
75
  return null;
52
76
  }
53
77
  return isRecord(data) ? accept(id, data) : null;
54
78
  };
55
- return { latest, down: () => told };
79
+ return { latest, down: () => failure };
80
+ };
81
+ const PAGE = 200;
82
+ // /latest calls in flight at once while listing.
83
+ const AT_ONCE = 8;
84
+ // A market that repeats its cursor would page for ever; past this the listing stops.
85
+ export const MAX_PAGES = 20;
86
+ // Every row of the market list, page after page while `meta.nextCursor` names one.
87
+ const pages = async (get, url, cursor, page = 1) => {
88
+ if (page > MAX_PAGES)
89
+ throw marketError('market_failed', `the market list has more than ${MAX_PAGES} pages of ${PAGE}; stopped there`);
90
+ const query = `?limit=${PAGE}${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`;
91
+ const body = await json(get, `${url}${query}`);
92
+ const data = Array.isArray(body?.['data']) ? body['data'] : [];
93
+ const meta = body?.['meta'];
94
+ const next = isRecord(meta) && typeof meta['nextCursor'] === 'string' ? meta['nextCursor'] : '';
95
+ return next && data.length > 0 ? [...data, ...(await pages(get, url, next, page + 1))] : data;
96
+ };
97
+ // A row without an exact version (the market of today lists none) asks /latest for it.
98
+ const offered = async (row, market) => {
99
+ if (!isRecord(row) || typeof row['id'] !== 'string')
100
+ return null;
101
+ const id = row['id'];
102
+ if (typeof row['version'] === 'string' && EXACT.test(row['version']))
103
+ return { id, version: row['version'] };
104
+ try {
105
+ const version = (await market.latest(id))?.version;
106
+ const down = market.down();
107
+ if (down)
108
+ return { id, reason: down.message };
109
+ return version ? { id, version } : { id, reason: 'the market has no version of it' };
110
+ }
111
+ catch (err) {
112
+ return { id, reason: messageOf(err) };
113
+ }
114
+ };
115
+ // `extension list --available`: each listed id with its newest version. Only a failed list call
116
+ // fails it; a row that cannot be read is skipped with its reason.
117
+ export const listMarket = async (fqdn = siteFqdn(), get = timed) => {
118
+ const base = await marketUrl(fqdn, get);
119
+ const rows = await pages(get, `${base}/api/v1/extensions`);
120
+ const found = [];
121
+ for (let i = 0; i < rows.length; i += AT_ONCE) {
122
+ const batch = rows.slice(i, i + AT_ONCE);
123
+ found.push(...(await Promise.all(batch.map((r) => offered(r, openMarket(fqdn, get, base))))));
124
+ }
125
+ const listing = { offered: [], skipped: [] };
126
+ for (const row of found)
127
+ if (row)
128
+ 'version' in row ? listing.offered.push(row) : listing.skipped.push(row);
129
+ return listing;
56
130
  };
@@ -0,0 +1,6 @@
1
+ export declare const sleep: (ms: number) => Promise<void>;
2
+ export interface Slow {
3
+ afterMs: number;
4
+ line: string;
5
+ }
6
+ export declare const waitFor: (done: () => boolean | Promise<boolean>, timeoutMs: number, slow?: Slow) => Promise<boolean>;
@@ -0,0 +1,17 @@
1
+ const POLL_MS = 100;
2
+ export const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
3
+ // Polls `done` until it holds (true) or the time is up (false).
4
+ export const waitFor = async (done, timeoutMs, slow) => {
5
+ const deadline = Date.now() + timeoutMs;
6
+ const note = slow ? Date.now() + slow.afterMs : Infinity;
7
+ let noted = false;
8
+ for (;;) {
9
+ if (await done())
10
+ return true;
11
+ if (Date.now() >= deadline)
12
+ return false;
13
+ if (!noted && Date.now() >= note)
14
+ noted = (console.error(slow?.line), true);
15
+ await sleep(POLL_MS);
16
+ }
17
+ };
@@ -0,0 +1,12 @@
1
+ import { type JsonIo } from './json-output.js';
2
+ export declare const EXIT_OK = 0;
3
+ export declare const EXIT_FAILED = 1;
4
+ export declare const EXIT_USAGE = 2;
5
+ export declare const ACTION_FAILED = "agentage.actionFailed";
6
+ type Legacy = (opts: never) => boolean;
7
+ export declare const notPinned: Legacy;
8
+ export declare const pinned: Legacy;
9
+ export declare const withAction: <T>(io: JsonIo & {
10
+ writeErr: (text: string) => void;
11
+ }, fn: (opts: T) => Promise<unknown>, prefix?: string, legacy?: Legacy) => (opts: T) => Promise<void>;
12
+ export {};
@@ -0,0 +1,33 @@
1
+ import chalk from 'chalk';
2
+ import { CommanderError } from 'commander';
3
+ import { attempt, isJson, messageOf, runJson } from './json-output.js';
4
+ export const EXIT_OK = 0;
5
+ export const EXIT_FAILED = 1;
6
+ export const EXIT_USAGE = 2;
7
+ export const ACTION_FAILED = 'agentage.actionFailed';
8
+ export const notPinned = () => false;
9
+ export const pinned = () => true;
10
+ // AGENTAGE_DEBUG=1: the original error and its cause, with stacks, on stderr; never on stdout.
11
+ const debugStack = (io, err) => {
12
+ if (process.env['AGENTAGE_DEBUG'] !== '1')
13
+ return;
14
+ for (let e = err; e instanceof Error; e = e.cause)
15
+ io.writeErr(`${e.stack ?? String(e)}\n`);
16
+ };
17
+ // One failure path: a red stderr line, exit 1, or with --json the error envelope on stdout.
18
+ // `legacy` marks a run whose own JSON is pinned; an extension's --help or usage error keeps its code.
19
+ export const withAction = (io, fn, prefix = '', legacy = notPinned) => async (opts) => {
20
+ const run = () => fn(opts);
21
+ const failure = isJson(opts)
22
+ ? await runJson(io, run, legacy(opts))
23
+ : await attempt(run);
24
+ if (!failure)
25
+ return;
26
+ const { err, shown } = failure;
27
+ if (err instanceof CommanderError)
28
+ throw err;
29
+ debugStack(io, err);
30
+ if (!shown)
31
+ io.writeErr(`${chalk.red(`${prefix}${messageOf(err)}`)}\n`);
32
+ throw new CommanderError(EXIT_FAILED, ACTION_FAILED, messageOf(err));
33
+ };
@@ -0,0 +1,2 @@
1
+ import { type ProgramDeps } from './program.js';
2
+ export declare const defaultDeps: ProgramDeps;
@@ -0,0 +1,95 @@
1
+ import {} from './commands/auth/setup.js';
2
+ import { runDaemonRestart, runDaemonStatus, runDaemonStop } from './commands/daemon/daemon.js';
3
+ import { cliInstaller, npmNewest } from './commands/daemon/installer.js';
4
+ import { moveBeforeStart } from './commands/daemon/move.js';
5
+ import { runDaemon } from './commands/daemon/run.js';
6
+ import { signedInAccount } from './commands/extension/account.js';
7
+ import { runExtensionBuild, runExtensionCheck } from './commands/extension/build.js';
8
+ import { runExtensionCreate } from './commands/extension/create.js';
9
+ import { runExtensionDoctor } from './commands/extension/doctor.js';
10
+ import { readHidden, runConfigure, stdinInput } from './commands/extension/configure.js';
11
+ import { runEnabled, runInstall, runRemove, terminalIo } from './commands/extension/lifecycle.js';
12
+ import { runList, runUpdate as runExtensionUpdate } from './commands/extension/lifecycle-list.js';
13
+ import { loadKitTool } from './commands/extension/kit-tool.js';
14
+ import { runExtensionRelease } from './commands/extension/release.js';
15
+ import { runExtensionSetup } from './commands/extension/setup.js';
16
+ import { runExtensionDown, runExtensionToken, runExtensionUp } from './commands/extension/up.js';
17
+ import { runStatus, statusDeps } from './commands/status/status.js';
18
+ import { runUpdate } from './commands/update/update.js';
19
+ import { npmMajor, prepareManifest, prepareNpm } from './core/installer/npm.js';
20
+ import { ensureSignedIn, signOut } from './lib/auth/sign-in.js';
21
+ import { ensureDaemon } from './lib/daemon/daemon-client.js';
22
+ import { hostClient } from './lib/daemon/host-client.js';
23
+ import { listMarket, openMarket } from './lib/net/market.js';
24
+ import { noSiteMarket, npmFallbackLine } from './lib/net/market-error.js';
25
+ import { siteFqdn } from './lib/net/origins.js';
26
+ import { refreshUpdateCache, updateHint } from './lib/update/update-cache.js';
27
+ import {} from './program.js';
28
+ const setupDeps = {
29
+ ensureSignedIn: (signInOpts) => ensureSignedIn(signInOpts),
30
+ signOut: () => signOut(),
31
+ printStatus: (opts) => runStatus(opts, statusDeps(false)),
32
+ startDaemon: () => ensureDaemon(),
33
+ };
34
+ // What a profile edit reaches: npm, and the account it syncs with when signed in.
35
+ const editDeps = { npm: () => prepareNpm(), npmMajor: () => npmMajor(), account: signedInAccount };
36
+ const installer = () => cliInstaller({
37
+ npm: () => prepareNpm(),
38
+ manifest: () => prepareManifest(),
39
+ market: () => openMarket(),
40
+ });
41
+ // The daemon is started on request by every lifecycle command.
42
+ const lifecycle = { host: async () => hostClient(await ensureDaemon()) };
43
+ const listDeps = {
44
+ ...lifecycle,
45
+ available: () => listMarket(),
46
+ market: () => openMarket(),
47
+ npmNewest: npmNewest(() => prepareManifest()),
48
+ };
49
+ // After a bare-id install: the line when npm resolved it (no market, or one without the id).
50
+ const fromNpm = async (id, what) => {
51
+ const market = openMarket();
52
+ if (await market.latest(id))
53
+ return null;
54
+ return npmFallbackLine(siteFqdn(), id, what, market.down());
55
+ };
56
+ const hasMarket = async (id) => {
57
+ const market = openMarket();
58
+ await market.latest(id);
59
+ return !noSiteMarket(market.down());
60
+ };
61
+ export const defaultDeps = {
62
+ setup: (opts) => runExtensionSetup(opts, {
63
+ ...setupDeps,
64
+ ...editDeps,
65
+ updateExtensions: () => runExtensionUpdate({}, listDeps),
66
+ host: lifecycle.host,
67
+ }),
68
+ status: (opts) => runStatus(opts),
69
+ update: (opts) => runUpdate(opts),
70
+ extensionInstall: (opts) => runInstall(opts, { ...lifecycle, fromNpm, hasMarket }),
71
+ extensionRemove: (opts) => runRemove(opts, { ...lifecycle, io: terminalIo() }),
72
+ extensionList: (opts) => runList(opts, listDeps),
73
+ extensionUpdate: (opts) => runExtensionUpdate(opts, listDeps),
74
+ extensionEnabled: ({ id, enabled }) => runEnabled(id, enabled, lifecycle),
75
+ extensionConfigure: (opts) => runConfigure(opts, { ...lifecycle, input: stdinInput(readHidden) }),
76
+ extensionDoctor: (opts) => runExtensionDoctor(opts),
77
+ extensionCreate: (opts) => runExtensionCreate(opts),
78
+ extensionCheck: (opts) => runExtensionCheck(opts),
79
+ extensionBuild: (opts) => runExtensionBuild(opts),
80
+ extensionRelease: (opts) => runExtensionRelease(opts),
81
+ extensionUp: (opts) => runExtensionUp(opts),
82
+ extensionDown: (opts) => runExtensionDown(opts),
83
+ extensionToken: (opts) => runExtensionToken(opts),
84
+ daemon: {
85
+ status: () => runDaemonStatus(),
86
+ stop: () => runDaemonStop(),
87
+ restart: () => runDaemonRestart(),
88
+ run: () => runDaemon({ installer, before: () => moveBeforeStart() }),
89
+ },
90
+ kitTool: loadKitTool,
91
+ updateHint,
92
+ refreshUpdateCache: () => refreshUpdateCache(),
93
+ writeOut: (text) => void process.stdout.write(text),
94
+ writeErr: (text) => void process.stderr.write(text),
95
+ };
package/dist/program.d.ts CHANGED
@@ -1,39 +1,47 @@
1
1
  import { Command } from 'commander';
2
2
  import { type SetupOptions } from './commands/auth/setup.js';
3
+ import { type DaemonOptions } from './commands/daemon/daemon.js';
3
4
  import { type ExtensionBuildOptions, type ExtensionCheckOptions } from './commands/extension/build.js';
4
5
  import { type ExtensionCreateOptions } from './commands/extension/create.js';
5
6
  import { type ExtensionDoctorOptions } from './commands/extension/doctor.js';
6
- import { type ExtensionInstallOptions } from './commands/extension/install.js';
7
- import { type ExtensionListOptions } from './commands/extension/list.js';
8
- import { type ExtensionRemoveOptions } from './commands/extension/remove.js';
7
+ import { type ConfigureOptions } from './commands/extension/configure.js';
8
+ import { type InstallOptions, type RemoveOptions } from './commands/extension/lifecycle.js';
9
+ import { type ExtensionUpdateOptions, type ListOptions } from './commands/extension/lifecycle-list.js';
9
10
  import { type LoadKitTool } from './commands/extension/kit-tool.js';
10
11
  import { type ExtensionReleaseOptions } from './commands/extension/release.js';
11
- import { type ExtensionDownOptions, type ExtensionTokenOptions, type ExtensionUpOptions } from './commands/extension/up.js';
12
+ import { type ExtensionDownOptions, type ExtensionTokenOptions, type ExtensionUpFlags } from './commands/extension/up.js';
12
13
  import { type StatusOptions } from './commands/status/status.js';
13
14
  import { type UpdateOptions } from './commands/update/update.js';
15
+ type Run<T> = (opts: T) => Promise<unknown>;
14
16
  export interface ProgramDeps {
15
- setup: (opts: SetupOptions) => Promise<void>;
16
- status: (opts: StatusOptions) => Promise<void>;
17
- update: (opts: UpdateOptions) => Promise<void>;
18
- extensionInstall: (opts: ExtensionInstallOptions) => Promise<void>;
19
- extensionRemove: (opts: ExtensionRemoveOptions) => Promise<void>;
20
- extensionList: (opts: ExtensionListOptions) => Promise<void>;
21
- extensionDoctor: (opts: ExtensionDoctorOptions) => Promise<void>;
22
- extensionCreate: (opts: ExtensionCreateOptions) => Promise<void>;
23
- extensionCheck: (opts: ExtensionCheckOptions) => Promise<void>;
24
- extensionBuild: (opts: ExtensionBuildOptions) => Promise<void>;
25
- extensionRelease: (opts: ExtensionReleaseOptions) => Promise<void>;
26
- extensionUp: (opts: ExtensionUpOptions) => Promise<void>;
27
- extensionDown: (opts: ExtensionDownOptions) => Promise<void>;
28
- extensionToken: (opts: ExtensionTokenOptions) => Promise<void>;
17
+ setup: Run<SetupOptions>;
18
+ status: Run<StatusOptions>;
19
+ update: Run<UpdateOptions>;
20
+ extensionInstall: Run<InstallOptions>;
21
+ extensionRemove: Run<RemoveOptions>;
22
+ extensionList: Run<ListOptions>;
23
+ extensionUpdate: Run<ExtensionUpdateOptions>;
24
+ extensionEnabled: Run<{
25
+ id: string;
26
+ enabled: boolean;
27
+ json?: boolean;
28
+ }>;
29
+ extensionConfigure: Run<ConfigureOptions>;
30
+ extensionDoctor: Run<ExtensionDoctorOptions>;
31
+ extensionCreate: Run<ExtensionCreateOptions>;
32
+ extensionCheck: Run<ExtensionCheckOptions>;
33
+ extensionBuild: Run<ExtensionBuildOptions>;
34
+ extensionRelease: Run<ExtensionReleaseOptions>;
35
+ extensionUp: Run<ExtensionUpFlags>;
36
+ extensionDown: Run<ExtensionDownOptions>;
37
+ extensionToken: Run<ExtensionTokenOptions>;
38
+ daemon: Record<'status' | 'stop' | 'restart' | 'run', Run<DaemonOptions>>;
29
39
  kitTool: LoadKitTool;
30
40
  updateHint: () => string | null;
31
41
  refreshUpdateCache: () => Promise<void>;
32
42
  writeOut: (text: string) => void;
33
43
  writeErr: (text: string) => void;
34
44
  }
35
- export declare const EXIT_OK = 0;
36
- export declare const EXIT_FAILED = 1;
37
- export declare const EXIT_USAGE = 2;
38
45
  export declare const createProgram: (deps?: ProgramDeps, argv?: string[]) => Command;
39
46
  export declare const run: (argv?: string[], deps?: ProgramDeps) => Promise<number>;
47
+ export {};
package/dist/program.js CHANGED
@@ -1,75 +1,26 @@
1
1
  import chalk from 'chalk';
2
2
  import { Command, CommanderError } from 'commander';
3
3
  import { registerSetup } from './commands/auth/setup.js';
4
- import { runExtensionBuild, runExtensionCheck, } from './commands/extension/build.js';
5
- import { runExtensionCreate } from './commands/extension/create.js';
4
+ import { registerDaemon } from './commands/daemon/daemon.js';
5
+ import {} from './commands/extension/build.js';
6
+ import {} from './commands/extension/create.js';
6
7
  import { registerDelegates } from './commands/extension/delegate.js';
7
- import { runExtensionDoctor } from './commands/extension/doctor.js';
8
- import { openMarket } from './lib/net/market.js';
9
- import { runExtensionInstall } from './commands/extension/install.js';
10
- import { registerExtension, runExtensionList, } from './commands/extension/list.js';
11
- import { runExtensionRemove, terminalIo, } from './commands/extension/remove.js';
12
- import { signedInAccount } from './commands/extension/account.js';
8
+ import {} from './commands/extension/doctor.js';
9
+ import {} from './commands/extension/configure.js';
10
+ import {} from './commands/extension/lifecycle.js';
11
+ import {} from './commands/extension/lifecycle-list.js';
12
+ import { registerExtension } from './commands/extension/list.js';
13
13
  import { KIT_EXIT } from './commands/extension/kit-commands.js';
14
- import { loadKitTool } from './commands/extension/kit-tool.js';
15
- import { runExtensionRelease } from './commands/extension/release.js';
16
- import { runExtensionSetup } from './commands/extension/setup.js';
17
- import { runExtensionDown, runExtensionToken, runExtensionUp, } from './commands/extension/up.js';
18
- import { registerStatus, runStatus, statusDeps, } from './commands/status/status.js';
19
- import { registerUpdate, runUpdate } from './commands/update/update.js';
20
- import { npmMajor, prepareManifest, prepareNpm } from './core/installer/npm.js';
21
- import { ensureSignedIn, signOut } from './lib/auth/sign-in.js';
22
- import { refreshUpdateCache, updateHint } from './lib/update/update-cache.js';
14
+ import {} from './commands/extension/kit-tool.js';
15
+ import {} from './commands/extension/release.js';
16
+ import {} from './commands/extension/up.js';
17
+ import { registerStatus } from './commands/status/status.js';
18
+ import { registerUpdate } from './commands/update/update.js';
19
+ import { takeExit } from './lib/exit-code.js';
20
+ import { messageOf, writeError } from './lib/json-output.js';
21
+ import { ACTION_FAILED, EXIT_FAILED, EXIT_OK, EXIT_USAGE, pinned, withAction, } from './lib/with-action.js';
22
+ import { defaultDeps } from './program-deps.js';
23
23
  import { VERSION } from './utils/version.js';
24
- const setupDeps = {
25
- ensureSignedIn: (signInOpts) => ensureSignedIn(signInOpts),
26
- signOut: () => signOut(),
27
- printStatus: (opts) => runStatus(opts, statusDeps(false)),
28
- };
29
- // What a profile edit reaches: npm, and the account it syncs with when signed in.
30
- const editDeps = { npm: () => prepareNpm(), npmMajor: () => npmMajor(), account: signedInAccount };
31
- const defaultDeps = {
32
- setup: (opts) => runExtensionSetup(opts, { ...setupDeps, ...editDeps }),
33
- status: (opts) => runStatus(opts),
34
- update: (opts) => runUpdate(opts),
35
- extensionInstall: (opts) => runExtensionInstall(opts, {
36
- ...editDeps,
37
- manifest: () => prepareManifest(),
38
- market: openMarket(),
39
- }),
40
- extensionRemove: (opts) => runExtensionRemove(opts, { ...editDeps, io: terminalIo() }),
41
- extensionList: (opts) => runExtensionList(opts, openMarket()),
42
- extensionDoctor: (opts) => runExtensionDoctor(opts),
43
- extensionCreate: (opts) => runExtensionCreate(opts),
44
- extensionCheck: (opts) => runExtensionCheck(opts),
45
- extensionBuild: (opts) => runExtensionBuild(opts),
46
- extensionRelease: (opts) => runExtensionRelease(opts),
47
- extensionUp: (opts) => runExtensionUp(opts),
48
- extensionDown: (opts) => runExtensionDown(opts),
49
- extensionToken: (opts) => runExtensionToken(opts),
50
- kitTool: loadKitTool,
51
- updateHint,
52
- refreshUpdateCache: () => refreshUpdateCache(),
53
- writeOut: (text) => void process.stdout.write(text),
54
- writeErr: (text) => void process.stderr.write(text),
55
- };
56
- export const EXIT_OK = 0;
57
- export const EXIT_FAILED = 1;
58
- export const EXIT_USAGE = 2;
59
- const ACTION_FAILED = 'agentage.actionFailed';
60
- const messageOf = (err) => (err instanceof Error ? err.message : String(err));
61
- // One failure path: a red stderr line, exit 1; an extension's --help or usage error keeps its code.
62
- const withAction = (deps, fn, prefix = '') => async (opts) => {
63
- try {
64
- await fn(opts);
65
- }
66
- catch (err) {
67
- if (err instanceof CommanderError)
68
- throw err;
69
- deps.writeErr(`${chalk.red(`${prefix}${messageOf(err)}`)}\n`);
70
- throw new CommanderError(EXIT_FAILED, ACTION_FAILED, messageOf(err));
71
- }
72
- };
73
24
  // status and update report update state themselves; the hint never touches --json stdout.
74
25
  const hintAfter = (deps) => (_program, action) => {
75
26
  if (action.name() === 'status' || action.name() === 'update')
@@ -85,9 +36,12 @@ const addExtensions = (program, deps, argv) => {
85
36
  install: withAction(deps, deps.extensionInstall),
86
37
  remove: withAction(deps, deps.extensionRemove),
87
38
  list: withAction(deps, deps.extensionList),
88
- doctor: withAction(deps, deps.extensionDoctor),
39
+ update: withAction(deps, deps.extensionUpdate),
40
+ enabled: withAction(deps, deps.extensionEnabled),
41
+ configure: withAction(deps, deps.extensionConfigure),
42
+ doctor: withAction(deps, deps.extensionDoctor, '', pinned),
89
43
  create: withAction(deps, deps.extensionCreate),
90
- check: withAction(deps, deps.extensionCheck),
44
+ check: withAction(deps, deps.extensionCheck, '', pinned),
91
45
  build: withAction(deps, deps.extensionBuild),
92
46
  release: withAction(deps, deps.extensionRelease),
93
47
  up: withAction(deps, deps.extensionUp),
@@ -111,14 +65,21 @@ export const createProgram = (deps = defaultDeps, argv = process.argv) => {
111
65
  .configureOutput({ writeOut: deps.writeOut, writeErr: deps.writeErr })
112
66
  .addHelpText('after', '\nNew here? Run: agentage setup to connect this machine.')
113
67
  .hook('postAction', hintAfter(deps));
114
- registerSetup(program, withAction(deps, deps.setup, 'Setup failed: '));
115
- registerStatus(program, withAction(deps, deps.status));
68
+ registerSetup(program, withAction(deps, deps.setup, 'Setup failed: ', (o) => !!(o.dryRun || o.check)));
69
+ registerStatus(program, withAction(deps, deps.status, '', pinned));
116
70
  registerUpdate(program, withAction(deps, deps.update));
71
+ const daemon = (fn) => withAction(deps, fn);
72
+ registerDaemon(program, {
73
+ status: daemon(deps.daemon.status),
74
+ stop: daemon(deps.daemon.stop),
75
+ restart: daemon(deps.daemon.restart),
76
+ run: daemon(deps.daemon.run),
77
+ });
117
78
  addExtensions(program, deps, argv);
118
79
  return program;
119
80
  };
120
- // --help and --version stay 0; a kit command keeps its code; any other commander error is usage.
121
- const exitCodeOf = (err, deps) => {
81
+ // --help and --version stay 0; a kit command keeps its code; other commander errors are usage.
82
+ const exitCodeOf = (err, deps, argv) => {
122
83
  if (!(err instanceof CommanderError)) {
123
84
  deps.writeErr(`${chalk.red(messageOf(err))}\n`);
124
85
  return EXIT_FAILED;
@@ -127,7 +88,12 @@ const exitCodeOf = (err, deps) => {
127
88
  return EXIT_FAILED;
128
89
  if (err.code === KIT_EXIT)
129
90
  return err.exitCode;
130
- return err.exitCode === 0 ? EXIT_OK : EXIT_USAGE;
91
+ if (err.exitCode === 0)
92
+ return EXIT_OK;
93
+ if (!argv.includes('--json'))
94
+ return EXIT_USAGE;
95
+ writeError(deps, err, 'usage'); // a usage error under --json is still one envelope
96
+ return EXIT_FAILED;
131
97
  };
132
98
  // Returns the exit code instead of exiting, so piped stdout is never cut short.
133
99
  export const run = async (argv = process.argv, deps = defaultDeps) => {
@@ -135,9 +101,9 @@ export const run = async (argv = process.argv, deps = defaultDeps) => {
135
101
  chalk.level = 0; // chalk ignores NO_COLOR on its own
136
102
  try {
137
103
  await createProgram(deps, argv).parseAsync(argv);
138
- return EXIT_OK;
104
+ return takeExit() ?? EXIT_OK;
139
105
  }
140
106
  catch (err) {
141
- return exitCodeOf(err, deps);
107
+ return exitCodeOf(err, deps, argv);
142
108
  }
143
109
  };