@agentage/cli 0.79.0 → 0.80.1

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 (65) hide show
  1. package/dist/commands/daemon/installer.d.ts +2 -0
  2. package/dist/commands/daemon/installer.js +12 -0
  3. package/dist/commands/daemon/repo-installer.d.ts +13 -0
  4. package/dist/commands/daemon/repo-installer.js +93 -0
  5. package/dist/commands/daemon/repo-pins.d.ts +6 -0
  6. package/dist/commands/daemon/repo-pins.js +22 -0
  7. package/dist/commands/extension/available.d.ts +20 -0
  8. package/dist/commands/extension/available.js +44 -0
  9. package/dist/commands/extension/install-once.js +2 -1
  10. package/dist/commands/extension/install-repo.d.ts +7 -0
  11. package/dist/commands/extension/install-repo.js +30 -0
  12. package/dist/commands/extension/install-spec.js +12 -4
  13. package/dist/commands/extension/lifecycle-list.d.ts +3 -1
  14. package/dist/commands/extension/lifecycle-list.js +37 -11
  15. package/dist/commands/extension/lifecycle-repo.d.ts +16 -0
  16. package/dist/commands/extension/lifecycle-repo.js +66 -0
  17. package/dist/commands/extension/lifecycle.d.ts +2 -0
  18. package/dist/commands/extension/lifecycle.js +2 -1
  19. package/dist/commands/extension/list.d.ts +2 -0
  20. package/dist/commands/extension/list.js +3 -1
  21. package/dist/commands/extension/market-commands.d.ts +10 -0
  22. package/dist/commands/extension/market-commands.js +24 -0
  23. package/dist/commands/extension/market.d.ts +39 -0
  24. package/dist/commands/extension/market.js +89 -0
  25. package/dist/commands/extension/table.d.ts +1 -0
  26. package/dist/commands/extension/table.js +8 -0
  27. package/dist/core/installer/npm.d.ts +1 -0
  28. package/dist/core/installer/npm.js +1 -1
  29. package/dist/core/installer/resolve.js +3 -1
  30. package/dist/core/installer/tree.d.ts +1 -0
  31. package/dist/core/installer/tree.js +5 -4
  32. package/dist/core/loader/installed.d.ts +5 -0
  33. package/dist/core/loader/installed.js +6 -0
  34. package/dist/lib/daemon/daemon-health.js +1 -1
  35. package/dist/lib/daemon/daemon-probe.d.ts +1 -0
  36. package/dist/lib/json-codes.d.ts +2 -0
  37. package/dist/lib/json-codes.js +41 -0
  38. package/dist/lib/json-output.d.ts +2 -2
  39. package/dist/lib/json-output.js +2 -38
  40. package/dist/lib/market/repo-build.d.ts +7 -0
  41. package/dist/lib/market/repo-build.js +67 -0
  42. package/dist/lib/market/repo-cache.d.ts +25 -0
  43. package/dist/lib/market/repo-cache.js +96 -0
  44. package/dist/lib/market/repo-entries.d.ts +14 -0
  45. package/dist/lib/market/repo-entries.js +46 -0
  46. package/dist/lib/market/repo-git.d.ts +13 -0
  47. package/dist/lib/market/repo-git.js +76 -0
  48. package/dist/lib/market/repo-links.d.ts +4 -0
  49. package/dist/lib/market/repo-links.js +35 -0
  50. package/dist/lib/market/repo-manifest.d.ts +14 -0
  51. package/dist/lib/market/repo-manifest.js +73 -0
  52. package/dist/lib/market/repo-markets-file.d.ts +12 -0
  53. package/dist/lib/market/repo-markets-file.js +39 -0
  54. package/dist/lib/market/repo-resolve.d.ts +15 -0
  55. package/dist/lib/market/repo-resolve.js +55 -0
  56. package/dist/lib/market/repo-text.d.ts +2 -0
  57. package/dist/lib/market/repo-text.js +7 -0
  58. package/dist/lib/market/repo-version.d.ts +13 -0
  59. package/dist/lib/market/repo-version.js +35 -0
  60. package/dist/lib/npm/npm-cli.d.ts +1 -0
  61. package/dist/lib/npm/npm-cli.js +1 -1
  62. package/dist/program-deps.js +24 -1
  63. package/dist/program.d.ts +2 -0
  64. package/dist/program.js +6 -0
  65. package/package.json +2 -2
@@ -0,0 +1,24 @@
1
+ import {} from 'commander';
2
+ import { addJson } from '../../lib/json-output.js';
3
+ import {} from './market.js';
4
+ const MARKET_HELP = `
5
+ A repo market is a GitHub repo with agentage-market.json at its root. Its extensions install by
6
+ id (the site market first) or as <market>/<id>, from the newest v* tag, else the default branch.
7
+ git's own credentials reach private repos (GH_TOKEN or GITHUB_TOKEN too); nothing is stored. An
8
+ extension with a build script is built on this machine: npm ci, then npm run build.`;
9
+ // `extension market add | list | remove`: this machine's repo markets, in markets.json.
10
+ export const addMarket = (group, actions) => {
11
+ const market = group
12
+ .command('market')
13
+ .description('Add, list or remove the GitHub repos that offer extensions')
14
+ .addHelpText('after', MARKET_HELP);
15
+ addJson(market
16
+ .command('add')
17
+ .description('Add a GitHub repo as a market (clones it, reads its manifest)')
18
+ .argument('<repo>', '<owner>/<repo>')).action((repo, opts) => actions.add({ ...opts, repo }));
19
+ addJson(market.command('list').description('Show each repo market: name, repo, extensions')).action(actions.list);
20
+ addJson(market
21
+ .command('remove')
22
+ .description('Forget a repo market; its installed extensions keep running')
23
+ .argument('<name>', 'the market name')).action((name, opts) => actions.remove({ ...opts, name }));
24
+ };
@@ -0,0 +1,39 @@
1
+ import { type Git } from '../../lib/market/repo-git.js';
2
+ export interface MarketCmdDeps {
3
+ git: Git;
4
+ now?: () => Date;
5
+ }
6
+ export interface MarketAddOptions {
7
+ repo: string;
8
+ json?: boolean;
9
+ }
10
+ export interface MarketListOptions {
11
+ json?: boolean;
12
+ }
13
+ export interface MarketRemoveOptions {
14
+ name: string;
15
+ json?: boolean;
16
+ }
17
+ export interface MarketRuns {
18
+ add: (opts: MarketAddOptions) => Promise<unknown>;
19
+ list: (opts: MarketListOptions) => Promise<unknown>;
20
+ remove: (opts: MarketRemoveOptions) => Promise<unknown>;
21
+ }
22
+ export declare const BUILD_NOTE = "installs from this market run its build scripts as you, outside the seal, with your files in reach; add only a market you trust";
23
+ export declare const runMarketAdd: (opts: MarketAddOptions, deps: MarketCmdDeps) => Promise<{
24
+ extensions: number;
25
+ already: boolean;
26
+ name: string;
27
+ repo: string;
28
+ added: string;
29
+ }>;
30
+ export declare const runMarketList: (_opts: MarketListOptions, deps: MarketCmdDeps) => Promise<{
31
+ extensions: number | null;
32
+ name: string;
33
+ repo: string;
34
+ added: string;
35
+ }[]>;
36
+ export declare const runMarketRemove: (opts: MarketRemoveOptions) => Promise<{
37
+ name: string;
38
+ repo: string;
39
+ }>;
@@ -0,0 +1,89 @@
1
+ import { rmSync } from 'node:fs';
2
+ import { CliError } from '../../lib/json-output.js';
3
+ import { cacheDir, CURRENT, manifestAt, syncLocked, withCloneLock, } from '../../lib/market/repo-cache.js';
4
+ import { offersAt } from '../../lib/market/repo-entries.js';
5
+ import {} from '../../lib/market/repo-git.js';
6
+ import { marketsToWrite, readMarkets, REPO, withMarkets, writeMarkets, } from '../../lib/market/repo-markets-file.js';
7
+ import { table } from './table.js';
8
+ export const BUILD_NOTE = 'installs from this market run its build scripts as you, outside the seal, with your files in reach; add only a market you trust';
9
+ const repoOf = (input) => {
10
+ const repo = input.replace(/\.git$/, '');
11
+ if (!REPO.test(repo))
12
+ throw new CliError('invalid_argument', `${input}: not <owner>/<repo>`);
13
+ return repo;
14
+ };
15
+ const sameRepo = (a, b) => a.toLowerCase() === b.toLowerCase();
16
+ const claimed = (markets, name, repo) => {
17
+ const other = markets.find((m) => m.name === name && !sameRepo(m.repo, repo));
18
+ if (other)
19
+ throw new CliError('invalid_argument', `the market name ${name} is taken by ${other.repo}; nothing added`);
20
+ };
21
+ // The manifest name, read at the newest ref; a failed first add leaves no clone behind.
22
+ const nameAt = async (repo, markets, deps) => {
23
+ let name = '';
24
+ const { commit } = await syncLocked(deps.git, repo, async (at) => {
25
+ name = (await manifestAt(deps.git, { repo, commit: at })).name;
26
+ claimed(markets, name, repo);
27
+ });
28
+ return { commit, name };
29
+ };
30
+ const dropClone = (repo) => rmSync(cacheDir(repo), { recursive: true, force: true });
31
+ // The row, written under the lock from the file as it is now; another add may have landed first.
32
+ const record = (repo, name, now) => withMarkets((markets) => {
33
+ const had = markets.find((m) => sameRepo(m.repo, repo));
34
+ if (had)
35
+ return { row: had, already: true };
36
+ claimed(markets, name, repo);
37
+ const row = { name, repo, added: now.toISOString() };
38
+ writeMarkets([...markets, row]);
39
+ return { row, already: false };
40
+ });
41
+ // Under the clone lock, then the markets.json lock (one order everywhere): row and clone together.
42
+ const addLocked = async (repo, deps) => {
43
+ const markets = marketsToWrite();
44
+ const fresh = !markets.some((m) => sameRepo(m.repo, repo));
45
+ const { commit, name } = await nameAt(repo, markets, deps);
46
+ const recorded = await record(repo, name, deps.now?.() ?? new Date()).catch((err) => {
47
+ if (fresh && !readMarkets().some((m) => sameRepo(m.repo, repo)))
48
+ dropClone(repo);
49
+ throw err;
50
+ });
51
+ return { ...recorded, commit };
52
+ };
53
+ // Clones the repo, reads its manifest; the same repo again changes nothing.
54
+ export const runMarketAdd = async (opts, deps) => {
55
+ const repo = repoOf(opts.repo);
56
+ marketsToWrite();
57
+ const { row, already, commit } = await withCloneLock(repo, () => addLocked(repo, deps));
58
+ const offers = await offersAt(deps.git, { name: row.name, repo, commit });
59
+ console.log(`market ${row.name} ${repo}: ${offers.length} extensions${already ? ' (already added)' : ''}`);
60
+ console.error(BUILD_NOTE);
61
+ return { ...row, extensions: offers.length, already };
62
+ };
63
+ // The count at the last fetched ref: no network.
64
+ const countOf = async (market, git) => manifestAt(git, { repo: market.repo, commit: CURRENT }).then((m) => m.extensions.length, () => null);
65
+ export const runMarketList = async (_opts, deps) => {
66
+ const rows = await Promise.all(readMarkets().map(async (m) => ({ ...m, extensions: await countOf(m, deps.git) })));
67
+ const cells = rows.map((r) => [r.name, r.repo, String(r.extensions ?? '?')]);
68
+ const lines = table([['NAME', 'REPO', 'EXTENSIONS'], ...cells]);
69
+ for (const line of rows.length > 0 ? lines : ['no repo markets'])
70
+ console.log(line);
71
+ return rows;
72
+ };
73
+ const noMarket = (name) => new CliError('not_installed', `no market ${name} on this machine`);
74
+ // Forgets the market and its clone, both under the clone lock; installed extensions keep running.
75
+ export const runMarketRemove = async (opts) => {
76
+ const named = marketsToWrite().find((m) => m.name === opts.name);
77
+ if (!named)
78
+ throw noMarket(opts.name);
79
+ const gone = await withCloneLock(named.repo, () => withMarkets((markets) => {
80
+ const found = markets.find((m) => m.name === opts.name && sameRepo(m.repo, named.repo));
81
+ if (!found)
82
+ throw noMarket(opts.name);
83
+ writeMarkets(markets.filter((m) => m !== found));
84
+ dropClone(found.repo);
85
+ return found;
86
+ }));
87
+ console.log(`removed market ${gone.name} (${gone.repo}); its installed extensions stay`);
88
+ return { name: gone.name, repo: gone.repo };
89
+ };
@@ -0,0 +1 @@
1
+ export declare const table: (rows: string[][]) => string[];
@@ -0,0 +1,8 @@
1
+ // Columns padded to the widest cell; trailing spaces trimmed.
2
+ export const table = (rows) => {
3
+ const widths = rows[0]?.map((_, i) => Math.max(...rows.map((r) => (r[i] ?? '').length))) ?? [];
4
+ return rows.map((r) => r
5
+ .map((cell, i) => cell.padEnd(widths[i] ?? 0))
6
+ .join(' ')
7
+ .trimEnd());
8
+ };
@@ -4,6 +4,7 @@ export type NpmCommand = 'ci' | 'install' | 'update';
4
4
  export type Npm = (command: NpmCommand, tree: string, packages?: string[]) => Promise<NpmResult>;
5
5
  export type LookupCommand = 'pack' | 'view';
6
6
  export type NpmManifest = (command: LookupCommand, spec: string, registries: Record<string, string>) => Promise<NpmResult>;
7
+ export declare const configFlags: (env: NodeJS.ProcessEnv) => string[];
7
8
  export declare const npmArgs: (command: NpmCommand, tree: string, env?: NodeJS.ProcessEnv, packages?: string[]) => string[];
8
9
  export declare const manifestArgs: (command: LookupCommand, spec: string, registries: Record<string, string>, prefix: string, env?: NodeJS.ProcessEnv) => string[];
9
10
  export declare const npmMajor: (env?: NodeJS.ProcessEnv) => Promise<number>;
@@ -16,7 +16,7 @@ const npmConfig = (env, key) => {
16
16
  return (found && env[found]) || null;
17
17
  };
18
18
  // Carried as flags: runNpm drops every npm_config_* variable from the child env.
19
- const configFlags = (env) => {
19
+ export const configFlags = (env) => {
20
20
  const userconfig = npmConfig(env, 'userconfig');
21
21
  const cache = npmConfig(env, 'cache');
22
22
  return [
@@ -102,9 +102,11 @@ export const resolveName = async (input, registry) => {
102
102
  throw new Error(`${input}: ${refused}`);
103
103
  return HTTPS.test(input) ? fromUrl(input, registry.find) : fromName(input, registry);
104
104
  };
105
+ // npm 10 and 11 print an array of packs; npm 12 an object keyed by package name.
106
+ const firstPack = (value) => Array.isArray(value) ? value[0] : isRecord(value) ? Object.values(value)[0] : undefined;
105
107
  const parseFound = (stdout) => {
106
108
  try {
107
- const [first] = JSON.parse(stdout);
109
+ const first = firstPack(JSON.parse(stdout));
108
110
  const { name, version } = isRecord(first) ? first : {};
109
111
  return typeof name === 'string' && typeof version === 'string' ? { name, version } : null;
110
112
  }
@@ -13,4 +13,5 @@ export declare const clearStaging: (extensionsDir: string) => void;
13
13
  export declare const stageTree: (extensionsDir: string, files: TreeFiles) => string;
14
14
  export declare const discardTree: (dir: string) => void;
15
15
  export declare const commitTree: (extensionsDir: string, staging: string, name: string) => void;
16
+ export declare const withLongLock: <T>(target: string, waiting: string, fn: () => Promise<T>) => Promise<T>;
16
17
  export declare const withInstallLock: <T>(extensionsDir: string, fn: () => Promise<T>) => Promise<T>;
@@ -68,9 +68,10 @@ const heartbeat = async (target, fn) => {
68
68
  clearInterval(beat);
69
69
  }
70
70
  };
71
- // A second run waits on `<extensionsDir>/install.lock` instead of racing the first one.
72
- export const withInstallLock = (extensionsDir, fn) => {
73
- const target = join(extensionsDir, 'install');
74
- const onWait = () => console.error(`waiting for another install to finish (${target}.lock)`);
71
+ // `<target>.lock` for a run of minutes: a second run waits, printing `waiting` once.
72
+ export const withLongLock = (target, waiting, fn) => {
73
+ const onWait = () => console.error(`waiting for ${waiting} to finish (${target}.lock)`);
75
74
  return withFileLock(target, () => heartbeat(target, fn), { ...INSTALL_LOCK, onWait });
76
75
  };
76
+ // A second run waits on `<extensionsDir>/install.lock` instead of racing the first one.
77
+ export const withInstallLock = (extensionsDir, fn) => withLongLock(join(extensionsDir, 'install'), 'another install', fn);
@@ -2,6 +2,11 @@ import { type DiscoveredExtension } from './discover.js';
2
2
  export declare const installationPath: () => string;
3
3
  export declare const settingsPath: () => string;
4
4
  export declare const versionsInUse: (id: string) => string[];
5
+ export declare const installedVersions: () => {
6
+ id: string;
7
+ version: string;
8
+ }[];
9
+ export declare const installVersion: (id: string) => string | null;
5
10
  export declare const installationRows: () => {
6
11
  id: string;
7
12
  dir: string | null;
@@ -29,6 +29,12 @@ const settings = () => {
29
29
  };
30
30
  // The versions of id that installation.json names now.
31
31
  export const versionsInUse = (id) => rows().flatMap((row) => isRecord(row) && row['id'] === id && typeof row['version'] === 'string' ? [row['version']] : []);
32
+ // Each row's id and version as installation.json names them.
33
+ export const installedVersions = () => rows().flatMap((row) => isRecord(row) && typeof row['id'] === 'string' && typeof row['version'] === 'string'
34
+ ? [{ id: row['id'], version: row['version'] }]
35
+ : []);
36
+ // The version installation.json names for id (a repo market's carries its market), or null.
37
+ export const installVersion = (id) => versionsInUse(id)[0] ?? null;
32
38
  // Each row's id and package folder, disabled ones too (null: its version is on no disk here).
33
39
  export const installationRows = () => rows().flatMap((row) => isRecord(row) && typeof row['id'] === 'string'
34
40
  ? [{ id: row['id'], dir: dirOf(row)?.dir ?? null }]
@@ -13,7 +13,7 @@ export const degradedReasons = (health) => {
13
13
  return [];
14
14
  const reasons = health.extensions
15
15
  .filter((ext) => UNSETTLED.includes(ext.state))
16
- .map((ext) => `${ext.id} is ${ext.state}`);
16
+ .map((ext) => `${ext.id} is ${ext.state}${ext.error ? `: ${ext.error}` : ''}`);
17
17
  if (health.unsynced?.length)
18
18
  reasons.push(`a change of ${health.unsynced.join(', ')} was not undone: its files disagree`);
19
19
  if (health.installation === 'unreadable')
@@ -18,6 +18,7 @@ export interface HealthEntry {
18
18
  parts?: string[];
19
19
  seal?: 'on' | 'off';
20
20
  restarts?: number;
21
+ error?: string;
21
22
  }
22
23
  export type Probe = {
23
24
  kind: 'ours';
@@ -0,0 +1,2 @@
1
+ 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", "invalid_manifest", "market_auth", "market_failed", "market_timeout", "market_unreachable", "needed_by_dependents", "network_unavailable", "no_discovery", "no_manifest", "no_market", "not_conforming", "not_installed", "not_pushed", "permission_denied", "port_in_use", "profile_invalid", "release_refused", "secret_refused", "stop_failed", "timeout", "token_request_failed", "uncommitted_changes", "usage"];
2
+ export type Code = (typeof CODES)[number];
@@ -0,0 +1,41 @@
1
+ // Every code of the cli's own: docs/reference.md lists the same, and a test keeps them equal.
2
+ export const CODES = [
3
+ 'already_installed',
4
+ 'already_running',
5
+ 'auth_required',
6
+ 'auth_unavailable',
7
+ 'build_failed',
8
+ 'cancelled',
9
+ 'confirmation_required',
10
+ 'daemon_disabled',
11
+ 'daemon_unavailable',
12
+ 'daemon_unresponsive',
13
+ 'disk_full',
14
+ 'error',
15
+ 'extension_failed',
16
+ 'integrity_drift',
17
+ 'invalid_argument',
18
+ 'invalid_manifest',
19
+ 'market_auth',
20
+ 'market_failed',
21
+ 'market_timeout',
22
+ 'market_unreachable',
23
+ 'needed_by_dependents',
24
+ 'network_unavailable',
25
+ 'no_discovery',
26
+ 'no_manifest',
27
+ 'no_market',
28
+ 'not_conforming',
29
+ 'not_installed',
30
+ 'not_pushed',
31
+ 'permission_denied',
32
+ 'port_in_use',
33
+ 'profile_invalid',
34
+ 'release_refused',
35
+ 'secret_refused',
36
+ 'stop_failed',
37
+ 'timeout',
38
+ 'token_request_failed',
39
+ 'uncommitted_changes',
40
+ 'usage',
41
+ ];
@@ -1,6 +1,6 @@
1
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", "secret_refused", "stop_failed", "timeout", "token_request_failed", "uncommitted_changes", "usage"];
3
- export type Code = (typeof CODES)[number];
2
+ import { type Code } from './json-codes.js';
3
+ export { CODES, type Code } from './json-codes.js';
4
4
  export declare class CliError extends Error {
5
5
  readonly code: Code;
6
6
  readonly details: Record<string, unknown>;
@@ -2,44 +2,8 @@ import { CommanderError } from 'commander';
2
2
  import { NotPushedError } from '../core/profile/cloud.js';
3
3
  import { AuthRequiredError, TransientAuthError } from './auth/auth-errors.js';
4
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
- 'secret_refused',
37
- 'stop_failed',
38
- 'timeout',
39
- 'token_request_failed',
40
- 'uncommitted_changes',
41
- 'usage',
42
- ];
5
+ import {} from './json-codes.js';
6
+ export { CODES } from './json-codes.js';
43
7
  // An error with a stable snake_case code for `--json`; any other error is `error`.
44
8
  export class CliError extends Error {
45
9
  code;
@@ -0,0 +1,7 @@
1
+ import { type NpmResult } from '../npm/npm-cli.js';
2
+ export type NpmStep = (args: string[], cwd: string, timeoutMs: number) => Promise<NpmResult>;
3
+ export declare const buildPlan: (pkg: Record<string, unknown>, hasLock: boolean) => string[][];
4
+ export declare const buildEnv: (env?: NodeJS.ProcessEnv) => NodeJS.ProcessEnv;
5
+ export declare const pinnedConfig: (npmCli: string, env: NodeJS.ProcessEnv) => Record<string, string>;
6
+ export declare const npmStep: (env?: NodeJS.ProcessEnv) => NpmStep;
7
+ export declare const runBuild: (dir: string, step: NpmStep, now?: () => number) => Promise<void>;
@@ -0,0 +1,67 @@
1
+ import { existsSync, rmSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { configFlags, lastLines } from '../../core/installer/npm.js';
4
+ import { childEnv } from '../child-env.js';
5
+ import { isRecord, readJson } from '../fs/json-file.js';
6
+ import { resolveNpmCli, runNpm } from '../npm/npm-cli.js';
7
+ import { redact } from './repo-git.js';
8
+ import { printable } from './repo-text.js';
9
+ const BUILD_MS = 10 * 60_000;
10
+ const hasDeps = (pkg, keys) => keys.some((key) => isRecord(pkg[key]) && Object.keys(pkg[key]).length > 0);
11
+ // A build script: install with scripts, then build. Else no script runs, and no dev dependency.
12
+ export const buildPlan = (pkg, hasLock) => {
13
+ const install = hasLock ? 'ci' : 'install';
14
+ const scripts = isRecord(pkg['scripts']) ? pkg['scripts'] : {};
15
+ if (typeof scripts['build'] === 'string') {
16
+ const deps = hasDeps(pkg, ['dependencies', 'devDependencies', 'optionalDependencies']);
17
+ return [...(deps ? [[install]] : []), ['run', 'build']];
18
+ }
19
+ if (!hasDeps(pkg, ['dependencies', 'optionalDependencies']))
20
+ return [];
21
+ return [[install, '--ignore-scripts', '--omit=dev']];
22
+ };
23
+ // Credentials a build has no use for: git's and the ssh agent's, tokens, keys, the cli's own.
24
+ const CREDENTIAL = /^(SSH_AUTH_SOCK|SSH_ASKPASS|GIT_ASKPASS|GIT_CONFIG_.*|AGENTAGE_.*)$|(^|_)(TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|ACCESS_KEY)$/i;
25
+ // The repo's scripts run as this user, outside the seal; they get none of the credentials above.
26
+ export const buildEnv = (env = process.env) => ({
27
+ ...Object.fromEntries(Object.entries(childEnv(env)).filter(([key]) => !CREDENTIAL.test(key))),
28
+ GIT_TERMINAL_PROMPT: '0',
29
+ });
30
+ // npm's defaults for the keys that name a program, and no git dependency: no config file changes them.
31
+ export const pinnedConfig = (npmCli, env) => {
32
+ const win = process.platform === 'win32';
33
+ const prefix = env['PREFIX'] ?? (win ? dirname(process.execPath) : dirname(dirname(process.execPath)));
34
+ return {
35
+ git: 'git',
36
+ 'script-shell': win ? (env['ComSpec'] ?? 'cmd.exe') : 'sh',
37
+ 'node-gyp': join(dirname(npmCli), '..', 'node_modules', 'node-gyp', 'bin', 'node-gyp.js'),
38
+ globalconfig: join(prefix, 'etc', 'npmrc'),
39
+ 'allow-git': 'none',
40
+ };
41
+ };
42
+ // As flags for this npm, and as env for the npm it starts to prepare a git dependency.
43
+ export const npmStep = (env = process.env) => (args, cwd, timeoutMs) => {
44
+ const npmCli = resolveNpmCli({ env });
45
+ const pinned = Object.entries(pinnedConfig(npmCli, env));
46
+ const flags = pinned.map(([key, value]) => `--${key}=${value}`);
47
+ const pinEnv = Object.fromEntries(pinned.map(([key, value]) => [`npm_config_${key.replace(/-/g, '_')}`, value]));
48
+ const all = [...args, '--no-update-notifier', ...configFlags(env), ...flags];
49
+ return runNpm(all, { cwd, timeoutMs, npmCli, baseEnv: buildEnv(env), env: pinEnv });
50
+ };
51
+ const GIT_REFUSED = 'a market extension cannot use git dependencies: publish them to a registry or bundle them';
52
+ const why = (res) => {
53
+ const tail = lastLines(`${res.stdout}\n${res.stderr}`);
54
+ return tail.includes('EALLOWGIT') ? `${tail}\n${GIT_REFUSED}` : tail;
55
+ };
56
+ // The plan of the folder, run in order within one bound, with no project npm config of the repo.
57
+ export const runBuild = async (dir, step, now = Date.now) => {
58
+ rmSync(join(dir, '.npmrc'), { force: true });
59
+ const pkg = readJson(join(dir, 'package.json'), isRecord) ?? {};
60
+ const deadline = now() + BUILD_MS;
61
+ for (const args of buildPlan(pkg, existsSync(join(dir, 'package-lock.json')))) {
62
+ const res = await step(args, dir, Math.max(1, deadline - now()));
63
+ if (res.code === 0)
64
+ continue;
65
+ throw new Error(`npm ${args.join(' ')} failed (exit ${res.code})\n${printable(redact(why(res)))}`);
66
+ }
67
+ };
@@ -0,0 +1,25 @@
1
+ import { type Git } from './repo-git.js';
2
+ export declare const CURRENT = "refs/agentage/current";
3
+ export interface Synced {
4
+ ref: string;
5
+ commit: string;
6
+ }
7
+ export declare const cacheDir: (repo: string) => string;
8
+ export declare const withCloneLock: <T>(repo: string, fn: () => Promise<T>) => Promise<T>;
9
+ export declare const syncLocked: (git: Git, repo: string, check?: (commit: string) => Promise<void>) => Promise<Synced>;
10
+ export declare const syncRepo: (git: Git, repo: string) => Promise<Synced>;
11
+ export declare const keepCommit: (git: Git, repo: string, used: Set<string>, pin: {
12
+ id: string;
13
+ commit: string;
14
+ }) => Promise<boolean>;
15
+ export declare const manifestAt: (git: Git, at: {
16
+ repo: string;
17
+ commit: string;
18
+ }) => Promise<import("./repo-manifest.js").MarketManifest>;
19
+ export declare const showFile: (git: Git, repo: string, rev: string, path: string) => Promise<string | null>;
20
+ export declare const objectType: (git: Git, repo: string, rev: string, path: string) => Promise<string | null>;
21
+ export declare const commitOf: (git: Git, repo: string, rev: string) => Promise<string | null>;
22
+ export declare const exportFolder: (git: Git, repo: string, at: {
23
+ commit: string;
24
+ path: string;
25
+ }, to: string) => Promise<void>;
@@ -0,0 +1,96 @@
1
+ import { existsSync, mkdirSync, rmSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { withLongLock } from '../../core/installer/tree.js';
4
+ import { getConfigDir } from '../fs/config.js';
5
+ import { CliError } from '../json-output.js';
6
+ import { cloneUrl, gitOk } from './repo-git.js';
7
+ import { MANIFEST_FILE, parseManifest } from './repo-manifest.js';
8
+ import { newestRef } from './repo-version.js';
9
+ // The ref the last sync moved: what `market list` reads with no network.
10
+ export const CURRENT = 'refs/agentage/current';
11
+ // One bare, shallow clone per repo; it holds no URL and no credential.
12
+ export const cacheDir = (repo) => join(getConfigDir(), 'markets', `${repo.toLowerCase()}.git`);
13
+ const gitDir = (repo) => ['--git-dir', cacheDir(repo)];
14
+ const fetchNewest = async (git, repo) => {
15
+ const listed = ['ls-remote', '--symref', '--', cloneUrl(repo), 'HEAD', 'refs/tags/v*'];
16
+ const newest = newestRef(await gitOk(git, repo, listed));
17
+ if (!newest)
18
+ throw new CliError('market_failed', `${repo}: the repo has no commit`);
19
+ const fetch = ['fetch', '-q', '--depth', '1', '--no-tags', '--', cloneUrl(repo), newest.ref];
20
+ await gitOk(git, repo, [...gitDir(repo), ...fetch]);
21
+ const commit = (await gitOk(git, repo, [...gitDir(repo), 'rev-parse', 'FETCH_HEAD^{commit}'])).trim();
22
+ return { ref: newest.ref, commit };
23
+ };
24
+ // `<repo>.git.lock` beside the clone, never in it: a failed add and `market remove` delete it.
25
+ export const withCloneLock = (repo, fn) => {
26
+ mkdirSync(dirname(cacheDir(repo)), { recursive: true, mode: 0o700 });
27
+ return withLongLock(cacheDir(repo), `another sync of ${repo}`, fn);
28
+ };
29
+ // The sync for a caller that holds the clone lock (`market add`); CURRENT moves only after `check`.
30
+ export const syncLocked = async (git, repo, check = async () => { }) => {
31
+ const dir = cacheDir(repo);
32
+ const fresh = !existsSync(dir);
33
+ try {
34
+ if (fresh)
35
+ await gitOk(git, repo, ['init', '-q', '--bare', '--', dir]);
36
+ const synced = await fetchNewest(git, repo);
37
+ await manifestAt(git, { repo, commit: synced.commit });
38
+ await check(synced.commit);
39
+ await gitOk(git, repo, [...gitDir(repo), 'update-ref', CURRENT, synced.commit]);
40
+ return synced;
41
+ }
42
+ catch (err) {
43
+ if (fresh)
44
+ rmSync(dir, { recursive: true, force: true });
45
+ throw err;
46
+ }
47
+ };
48
+ export const syncRepo = (git, repo) => withCloneLock(repo, () => syncLocked(git, repo));
49
+ const PINS = 'refs/agentage/installed/';
50
+ // One ref per installed `<id>/<commit>` keeps it from a gc; pins no row names go first.
51
+ export const keepCommit = async (git, repo, used, pin) => {
52
+ const kept = `${pin.id}/${pin.commit}`;
53
+ const listed = await git([...gitDir(repo), 'for-each-ref', '--format=%(refname)', PINS]);
54
+ for (const ref of listed.stdout.split('\n').filter((r) => r.startsWith(PINS)))
55
+ if (!used.has(ref.slice(PINS.length)) && ref !== `${PINS}${kept}`)
56
+ await git([...gitDir(repo), 'update-ref', '-d', ref]);
57
+ return (await git([...gitDir(repo), 'update-ref', `${PINS}${kept}`, pin.commit])).code === 0;
58
+ };
59
+ // The manifest at a commit; none is no_manifest, a bad one invalid_manifest.
60
+ export const manifestAt = async (git, at) => {
61
+ const text = await showFile(git, at.repo, at.commit, MANIFEST_FILE);
62
+ if (text === null)
63
+ throw new CliError('no_manifest', `${at.repo}: no ${MANIFEST_FILE} at the repo root`);
64
+ return parseManifest(text);
65
+ };
66
+ // A file at a commit in the cache, or null when the commit or the file is not there.
67
+ export const showFile = async (git, repo, rev, path) => {
68
+ const res = await git([...gitDir(repo), 'show', `${rev}:${path}`]);
69
+ return res.code === 0 ? res.stdout : null;
70
+ };
71
+ // `tree` for a folder; a symlink, a file or nothing is not one.
72
+ export const objectType = async (git, repo, rev, path) => {
73
+ const res = await git([...gitDir(repo), 'cat-file', '-t', `${rev}:${path}`]);
74
+ return res.code === 0 ? res.stdout.trim() : null;
75
+ };
76
+ // The full commit of a rev in the cache, or null.
77
+ export const commitOf = async (git, repo, rev) => {
78
+ if (!existsSync(cacheDir(repo)))
79
+ return null;
80
+ const res = await git([...gitDir(repo), 'rev-parse', '--verify', '-q', `${rev}^{commit}`]);
81
+ return res.code === 0 ? res.stdout.trim() : null;
82
+ };
83
+ // The folder of a commit, written under `to` by git itself (no shell, no tar), via its own index.
84
+ export const exportFolder = async (git, repo, at, to) => {
85
+ const index = { GIT_INDEX_FILE: join(dirname(to), `.index-${process.pid}`) };
86
+ const tree = `${at.commit}:${at.path === '.' ? '' : at.path}`;
87
+ mkdirSync(to, { recursive: true });
88
+ try {
89
+ await gitOk(git, repo, [...gitDir(repo), 'read-tree', tree], index);
90
+ const work = [...gitDir(repo), '--work-tree', to, 'checkout-index', '-a', '-f'];
91
+ await gitOk(git, repo, work, index);
92
+ }
93
+ finally {
94
+ rmSync(index.GIT_INDEX_FILE, { force: true });
95
+ }
96
+ };
@@ -0,0 +1,14 @@
1
+ import { type Git } from './repo-git.js';
2
+ import { type MarketEntry } from './repo-manifest.js';
3
+ export interface MarketAt {
4
+ name: string;
5
+ repo: string;
6
+ commit: string;
7
+ }
8
+ export interface RepoOffer extends MarketEntry {
9
+ market: string;
10
+ name: string | null;
11
+ version: string | null;
12
+ problem?: string;
13
+ }
14
+ export declare const offersAt: (git: Git, at: MarketAt) => Promise<RepoOffer[]>;
@@ -0,0 +1,46 @@
1
+ import { isRecord } from '../fs/json-file.js';
2
+ import { manifestAt, objectType, showFile } from './repo-cache.js';
3
+ import {} from './repo-git.js';
4
+ import {} from './repo-manifest.js';
5
+ import { oneLine } from './repo-text.js';
6
+ import { PLAIN_VERSION, repoVersion } from './repo-version.js';
7
+ const NPM_NAME = /^(@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/;
8
+ const fileIn = (path, file) => (path === '.' ? file : `${path}/${file}`);
9
+ const parsed = (text) => {
10
+ try {
11
+ const value = text === null ? null : JSON.parse(text);
12
+ return isRecord(value) ? value : null;
13
+ }
14
+ catch {
15
+ return null;
16
+ }
17
+ };
18
+ // Why the folder's package.json cannot be this entry, or null.
19
+ const packageProblem = (pkg, id) => {
20
+ if (!pkg)
21
+ return 'its folder has no package.json';
22
+ const agentage = isRecord(pkg['agentage']) ? pkg['agentage'] : {};
23
+ if (agentage['id'] !== id)
24
+ return `agentage.id is ${oneLine(String(agentage['id']), 64)}, not ${id}`;
25
+ if (typeof pkg['name'] !== 'string' || !NPM_NAME.test(pkg['name']))
26
+ return 'package.json has no valid name';
27
+ if (typeof pkg['version'] !== 'string' || !PLAIN_VERSION.test(pkg['version']))
28
+ return 'package.json version is not a plain version (x.y.z, no build part)';
29
+ return null;
30
+ };
31
+ const offerOf = async (git, at, entry) => {
32
+ const base = { ...entry, market: at.name, name: null, version: null };
33
+ if ((await objectType(git, at.repo, at.commit, entry.path === '.' ? '' : entry.path)) !== 'tree')
34
+ return { ...base, problem: `${entry.path} is not a folder of the repo` };
35
+ const pkg = parsed(await showFile(git, at.repo, at.commit, fileIn(entry.path, 'package.json')));
36
+ const problem = packageProblem(pkg, entry.id);
37
+ if (problem || !pkg)
38
+ return { ...base, problem: problem ?? 'no package.json' };
39
+ const version = repoVersion(String(pkg['version']), at.name, at.commit);
40
+ return { ...base, name: String(pkg['name']), version };
41
+ };
42
+ // Every entry of the market at a commit, the invalid ones with their problem.
43
+ export const offersAt = async (git, at) => {
44
+ const manifest = await manifestAt(git, at);
45
+ return Promise.all(manifest.extensions.map((entry) => offerOf(git, at, entry)));
46
+ };