@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,36 @@
1
+ import { type Command } from 'commander';
2
+ export declare const CODES: readonly ["already_installed", "already_running", "auth_required", "auth_unavailable", "build_failed", "cancelled", "confirmation_required", "daemon_disabled", "daemon_unavailable", "daemon_unresponsive", "disk_full", "error", "extension_failed", "integrity_drift", "invalid_argument", "market_failed", "market_timeout", "market_unreachable", "needed_by_dependents", "network_unavailable", "no_discovery", "no_market", "not_conforming", "not_installed", "not_pushed", "permission_denied", "port_in_use", "profile_invalid", "release_refused", "stop_failed", "timeout", "token_request_failed", "uncommitted_changes", "usage"];
3
+ export type Code = (typeof CODES)[number];
4
+ export declare class CliError extends Error {
5
+ readonly code: Code;
6
+ constructor(code: Code, message: string);
7
+ }
8
+ export declare class DaemonError extends Error {
9
+ readonly code: string;
10
+ readonly status: number;
11
+ readonly details: Record<string, unknown>;
12
+ constructor(code: string, message: string, status?: number, details?: Record<string, unknown>);
13
+ }
14
+ export declare const codeOf: (err: unknown) => string;
15
+ export interface JsonIo {
16
+ writeOut: (text: string) => void;
17
+ }
18
+ export interface Failure {
19
+ err: unknown;
20
+ shown: boolean;
21
+ }
22
+ export declare class WithMeta {
23
+ readonly data: unknown;
24
+ readonly meta: Record<string, unknown>;
25
+ constructor(data: unknown, meta: Record<string, unknown>);
26
+ }
27
+ export declare const isJsonRun: () => boolean;
28
+ export declare const isJson: (opts: unknown) => boolean;
29
+ export declare const attempt: (run: () => Promise<unknown>) => Promise<Failure | null>;
30
+ export declare const messageOf: (err: unknown) => string;
31
+ export declare const writeError: (io: JsonIo, err: unknown, code?: string) => void;
32
+ export declare const runJson: (io: JsonIo, run: () => Promise<unknown>, legacy?: boolean) => Promise<Failure | null>;
33
+ export declare const omitJson: <T extends {
34
+ json?: boolean;
35
+ }>(opts: T) => Omit<T, "json">;
36
+ export declare const addJson: (command: Command) => Command;
@@ -0,0 +1,163 @@
1
+ import { CommanderError } from 'commander';
2
+ import { NotPushedError } from '../core/profile/cloud.js';
3
+ import { AuthRequiredError, TransientAuthError } from './auth/auth-errors.js';
4
+ import { TokenRequestError } from './auth/oauth.js';
5
+ // Every code of the cli's own: docs/reference.md lists the same, and a test keeps them equal.
6
+ export const CODES = [
7
+ 'already_installed',
8
+ 'already_running',
9
+ 'auth_required',
10
+ 'auth_unavailable',
11
+ 'build_failed',
12
+ 'cancelled',
13
+ 'confirmation_required',
14
+ 'daemon_disabled',
15
+ 'daemon_unavailable',
16
+ 'daemon_unresponsive',
17
+ 'disk_full',
18
+ 'error',
19
+ 'extension_failed',
20
+ 'integrity_drift',
21
+ 'invalid_argument',
22
+ 'market_failed',
23
+ 'market_timeout',
24
+ 'market_unreachable',
25
+ 'needed_by_dependents',
26
+ 'network_unavailable',
27
+ 'no_discovery',
28
+ 'no_market',
29
+ 'not_conforming',
30
+ 'not_installed',
31
+ 'not_pushed',
32
+ 'permission_denied',
33
+ 'port_in_use',
34
+ 'profile_invalid',
35
+ 'release_refused',
36
+ 'stop_failed',
37
+ 'timeout',
38
+ 'token_request_failed',
39
+ 'uncommitted_changes',
40
+ 'usage',
41
+ ];
42
+ // An error with a stable snake_case code for `--json`; any other error is `error`.
43
+ export class CliError extends Error {
44
+ code;
45
+ constructor(code, message) {
46
+ super(message);
47
+ this.code = code;
48
+ }
49
+ }
50
+ // The daemon's own code (NOT_FOUND, INVALID_SETTING), passed through as it is, with its details.
51
+ export class DaemonError extends Error {
52
+ code;
53
+ status;
54
+ details;
55
+ constructor(code, message, status = 0, details = {}) {
56
+ super(message);
57
+ this.code = code;
58
+ this.status = status;
59
+ this.details = details;
60
+ }
61
+ }
62
+ const KNOWN = [
63
+ [AuthRequiredError, 'auth_required'],
64
+ [TransientAuthError, 'auth_unavailable'],
65
+ [NotPushedError, 'not_pushed'],
66
+ [TokenRequestError, 'token_request_failed'],
67
+ ];
68
+ // What the system says of an expected failure: a folder or file we may not use, a full disk.
69
+ const ERRNO = {
70
+ EACCES: 'permission_denied',
71
+ EPERM: 'permission_denied',
72
+ EROFS: 'permission_denied',
73
+ ENOSPC: 'disk_full',
74
+ EDQUOT: 'disk_full',
75
+ };
76
+ const systemCode = (err) => {
77
+ if (!(err instanceof Error))
78
+ return undefined;
79
+ if (err.name === 'TimeoutError')
80
+ return 'timeout';
81
+ if (err instanceof TypeError && err.message === 'fetch failed')
82
+ return 'network_unavailable';
83
+ return ERRNO[err.code ?? ''];
84
+ };
85
+ export const codeOf = (err) => {
86
+ if (err instanceof CliError || err instanceof DaemonError)
87
+ return err.code;
88
+ return KNOWN.find(([type]) => err instanceof type)?.[1] ?? systemCode(err) ?? 'error';
89
+ };
90
+ // A command's answer with `meta` beside `data` in the --json envelope.
91
+ export class WithMeta {
92
+ data;
93
+ meta;
94
+ constructor(data, meta) {
95
+ this.data = data;
96
+ this.meta = meta;
97
+ }
98
+ }
99
+ const envelope = (data) => JSON.stringify(data instanceof WithMeta
100
+ ? { success: true, data: data.data, meta: data.meta }
101
+ : { success: true, data });
102
+ let active = false;
103
+ // True inside a --json run: nothing may prompt.
104
+ export const isJsonRun = () => active;
105
+ export const isJson = (opts) => typeof opts === 'object' && opts !== null && opts.json === true;
106
+ export const attempt = async (run) => run().then(() => null, (err) => ({ err, shown: false }));
107
+ // fetch says only "fetch failed"; its cause names the host and why (ECONNREFUSED, ENOTFOUND).
108
+ export const messageOf = (err) => {
109
+ if (!(err instanceof Error))
110
+ return String(err);
111
+ const cause = err.cause;
112
+ const why = err.message === 'fetch failed' && cause instanceof Error ? `: ${cause.message}` : '';
113
+ return `${err.message}${why}`;
114
+ };
115
+ export const writeError = (io, err, code = codeOf(err)) => io.writeOut(`${JSON.stringify({ success: false, error: { code, message: messageOf(err) } })}\n`);
116
+ // Progress goes to stderr; a pinned command keeps stdout and we note that it printed.
117
+ const redirectLog = (legacy) => {
118
+ const log = console.log;
119
+ let wrote = false;
120
+ console.log = (...args) => {
121
+ if (!legacy)
122
+ return console.error(...args);
123
+ wrote = true;
124
+ log(...args);
125
+ };
126
+ return { wrote: () => wrote, restore: () => void (console.log = log) };
127
+ };
128
+ const failureOf = (io, { err }, wrote) => {
129
+ if (err instanceof CommanderError)
130
+ return { err, shown: true };
131
+ if (wrote)
132
+ return { err, shown: false };
133
+ writeError(io, err);
134
+ return { err, shown: true };
135
+ };
136
+ // Stdout is reserved for the envelope; `legacy` keeps a command's own pinned JSON instead.
137
+ export const runJson = async (io, run, legacy = false) => {
138
+ const log = redirectLog(legacy);
139
+ active = true;
140
+ try {
141
+ let data = null;
142
+ const failure = await attempt(async () => {
143
+ data = (await run()) ?? null;
144
+ });
145
+ if (failure)
146
+ return failureOf(io, failure, log.wrote());
147
+ if (!legacy)
148
+ io.writeOut(`${envelope(data)}\n`);
149
+ return null;
150
+ }
151
+ finally {
152
+ log.restore();
153
+ active = false;
154
+ }
155
+ };
156
+ // A copy of the options without the flag, for a call that hands them on.
157
+ export const omitJson = (opts) => {
158
+ const copy = { ...opts };
159
+ delete copy.json;
160
+ return copy;
161
+ };
162
+ // The one --json option every command carries.
163
+ export const addJson = (command) => command.option('--json', 'one JSON object on stdout: { success, data } or { success: false, error }');
@@ -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
+ };