@agentage/cli 0.78.2 → 0.80.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 (87) hide show
  1. package/README.md +2 -0
  2. package/dist/commands/config/config-get.d.ts +11 -0
  3. package/dist/commands/config/config-get.js +17 -0
  4. package/dist/commands/config/config-keys.d.ts +13 -0
  5. package/dist/commands/config/config-keys.js +18 -0
  6. package/dist/commands/config/config-list.d.ts +8 -0
  7. package/dist/commands/config/config-list.js +45 -0
  8. package/dist/commands/config/config-set.d.ts +12 -0
  9. package/dist/commands/config/config-set.js +71 -0
  10. package/dist/commands/config/config.d.ts +13 -0
  11. package/dist/commands/config/config.js +46 -0
  12. package/dist/commands/daemon/installer.d.ts +2 -0
  13. package/dist/commands/daemon/installer.js +12 -0
  14. package/dist/commands/daemon/repo-installer.d.ts +13 -0
  15. package/dist/commands/daemon/repo-installer.js +93 -0
  16. package/dist/commands/daemon/repo-pins.d.ts +6 -0
  17. package/dist/commands/daemon/repo-pins.js +22 -0
  18. package/dist/commands/extension/available.d.ts +20 -0
  19. package/dist/commands/extension/available.js +44 -0
  20. package/dist/commands/extension/configure.d.ts +1 -0
  21. package/dist/commands/extension/configure.js +1 -1
  22. package/dist/commands/extension/install-once.js +2 -1
  23. package/dist/commands/extension/install-repo.d.ts +7 -0
  24. package/dist/commands/extension/install-repo.js +30 -0
  25. package/dist/commands/extension/install-spec.js +12 -4
  26. package/dist/commands/extension/kit-commands.js +12 -3
  27. package/dist/commands/extension/kit-tool.d.ts +1 -1
  28. package/dist/commands/extension/kit-values.d.ts +7 -0
  29. package/dist/commands/extension/kit-values.js +60 -0
  30. package/dist/commands/extension/lifecycle-list.d.ts +3 -1
  31. package/dist/commands/extension/lifecycle-list.js +37 -11
  32. package/dist/commands/extension/lifecycle-repo.d.ts +16 -0
  33. package/dist/commands/extension/lifecycle-repo.js +66 -0
  34. package/dist/commands/extension/lifecycle.d.ts +2 -0
  35. package/dist/commands/extension/lifecycle.js +2 -1
  36. package/dist/commands/extension/list.d.ts +4 -0
  37. package/dist/commands/extension/list.js +5 -1
  38. package/dist/commands/extension/market-commands.d.ts +10 -0
  39. package/dist/commands/extension/market-commands.js +24 -0
  40. package/dist/commands/extension/market.d.ts +39 -0
  41. package/dist/commands/extension/market.js +89 -0
  42. package/dist/commands/extension/table.d.ts +1 -0
  43. package/dist/commands/extension/table.js +8 -0
  44. package/dist/commands/extension/types.d.ts +14 -0
  45. package/dist/commands/extension/types.js +51 -0
  46. package/dist/core/installer/npm.d.ts +1 -0
  47. package/dist/core/installer/npm.js +1 -1
  48. package/dist/core/installer/resolve.js +3 -1
  49. package/dist/core/installer/tree.d.ts +1 -0
  50. package/dist/core/installer/tree.js +5 -4
  51. package/dist/core/loader/installed.d.ts +5 -0
  52. package/dist/core/loader/installed.js +6 -0
  53. package/dist/core/loader/manifest.js +12 -2
  54. package/dist/lib/daemon/host-client.d.ts +3 -0
  55. package/dist/lib/daemon/host-client.js +3 -0
  56. package/dist/lib/daemon/values.types.d.ts +30 -0
  57. package/dist/lib/daemon/values.types.js +1 -0
  58. package/dist/lib/json-codes.d.ts +2 -0
  59. package/dist/lib/json-codes.js +41 -0
  60. package/dist/lib/json-output.d.ts +4 -3
  61. package/dist/lib/json-output.js +8 -39
  62. package/dist/lib/market/repo-build.d.ts +7 -0
  63. package/dist/lib/market/repo-build.js +67 -0
  64. package/dist/lib/market/repo-cache.d.ts +25 -0
  65. package/dist/lib/market/repo-cache.js +96 -0
  66. package/dist/lib/market/repo-entries.d.ts +14 -0
  67. package/dist/lib/market/repo-entries.js +46 -0
  68. package/dist/lib/market/repo-git.d.ts +13 -0
  69. package/dist/lib/market/repo-git.js +76 -0
  70. package/dist/lib/market/repo-links.d.ts +4 -0
  71. package/dist/lib/market/repo-links.js +35 -0
  72. package/dist/lib/market/repo-manifest.d.ts +14 -0
  73. package/dist/lib/market/repo-manifest.js +73 -0
  74. package/dist/lib/market/repo-markets-file.d.ts +12 -0
  75. package/dist/lib/market/repo-markets-file.js +39 -0
  76. package/dist/lib/market/repo-resolve.d.ts +15 -0
  77. package/dist/lib/market/repo-resolve.js +55 -0
  78. package/dist/lib/market/repo-text.d.ts +2 -0
  79. package/dist/lib/market/repo-text.js +7 -0
  80. package/dist/lib/market/repo-version.d.ts +13 -0
  81. package/dist/lib/market/repo-version.js +35 -0
  82. package/dist/lib/npm/npm-cli.d.ts +1 -0
  83. package/dist/lib/npm/npm-cli.js +1 -1
  84. package/dist/program-deps.js +36 -1
  85. package/dist/program.d.ts +13 -0
  86. package/dist/program.js +18 -0
  87. package/package.json +3 -3
@@ -0,0 +1,51 @@
1
+ import {} from 'commander';
2
+ import { installationRows } from '../../core/loader/installed.js';
3
+ import { addJson, CliError } from '../../lib/json-output.js';
4
+ import { loadKitTool } from './kit-tool.js';
5
+ // `<owner>.<key>` and `<owner>.<name>:write` name their owner before the first dot.
6
+ const ownerIds = (uses = {}) => new Set(Object.values(uses)
7
+ .flat()
8
+ .flatMap((entry) => (entry?.includes('.') ? [entry.slice(0, entry.indexOf('.'))] : [])));
9
+ // The folders of the used owners this machine has installed; the kit looks in node_modules after.
10
+ const installedOwners = async (tool, dir) => {
11
+ const wanted = ownerIds((await (await tool()).readManifest(dir)).agentage.uses);
12
+ return installationRows().flatMap((row) => (row.dir && wanted.has(row.id) ? [row.dir] : []));
13
+ };
14
+ const OUT_OF_DATE = /out of date/;
15
+ // The kit names why a use fails (KEY_NOT_FOUND, NOT_SHARED); an owner not installed is not_installed.
16
+ const named = (err) => {
17
+ const { name, message = '', code } = err;
18
+ if (OUT_OF_DATE.test(message))
19
+ return new CliError('not_conforming', message);
20
+ if (name !== 'UsesError' || typeof code !== 'string')
21
+ return err;
22
+ const cli = code === 'OWNER_NOT_FOUND' ? 'not_installed' : 'not_conforming';
23
+ return new CliError(cli, `${message} (${code})`);
24
+ };
25
+ // Writes src/agentage-env.d.ts from the manifest and its owners; --check only compares.
26
+ export const runExtensionTypes = async ({ dir = '.', check, owner } = {}, tool = loadKitTool) => {
27
+ const owners = owner?.length ? owner : await installedOwners(tool, dir);
28
+ const result = await (await tool())
29
+ .types({ dir, check: check === true, owners })
30
+ .catch((err) => {
31
+ throw named(err);
32
+ });
33
+ console.log(result.changed ? `wrote ${result.file}` : `${result.file} is up to date`);
34
+ return { ...result, owners };
35
+ };
36
+ const TYPES_HELP = `
37
+ Writes src/agentage-env.d.ts from the manifest: the own settings, secrets and databases, and those
38
+ of each owner named in agentage.uses, so ctx.setting(), ctx.secret() and ctx.db() are typed. No
39
+ code of another extension runs. The owners come from each --owner folder, else from the
40
+ extensions installed on this machine, then from node_modules. --check writes nothing and exits 1
41
+ (not_conforming) when the file differs, or when a used key is gone or no longer shared (its kit
42
+ code in brackets); a used owner found nowhere is not_installed.`;
43
+ const collect = (value, all = []) => [...all, value];
44
+ export const addTypes = (group, types) => addJson(group
45
+ .command('types')
46
+ .description('Write src/agentage-env.d.ts, the typed keys; --check only compares')
47
+ .option('--dir <path>', 'the extension package folder (default: the current folder)')
48
+ .option('--check', 'write nothing; exit 1 when the file differs')
49
+ .option('--owner <dir>', 'the package folder of a used owner (repeatable)', collect))
50
+ .addHelpText('after', TYPES_HELP)
51
+ .action(types);
@@ -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 }]
@@ -5,9 +5,19 @@ import { isRange, satisfies } from '../semver-range.js';
5
5
  import { cliEntryOf, isKitShaped, kitCommandsOf, kitShapeProblem, } from './kit-manifest.js';
6
6
  export const ID_PATTERN = /^[a-z][a-z0-9-]*$/;
7
7
  const DEFAULT_ENGINE = '^1';
8
- export const CORE_COMMANDS = ['setup', 'status', 'update', 'extension', 'add', 'remove', 'help'];
8
+ export const CORE_COMMANDS = [
9
+ 'setup',
10
+ 'status',
11
+ 'update',
12
+ 'extension',
13
+ 'config',
14
+ 'add',
15
+ 'remove',
16
+ 'help',
17
+ ];
9
18
  const DEVICE_NAMES = ['con', 'prn', 'aux', 'nul'].concat(...Array.from({ length: 10 }, (_, n) => [`com${n}`, `lpt${n}`]));
10
- const RESERVED_IDS = new Set([...CORE_COMMANDS, ...DEVICE_NAMES]);
19
+ // `shared` owns the shared.<key> values (D125.2): no verb, but never an id.
20
+ const RESERVED_IDS = new Set([...CORE_COMMANDS, 'shared', ...DEVICE_NAMES]);
11
21
  const SUBCOMMAND = /^[a-z0-9][a-z0-9-]*$/;
12
22
  const str = (value) => (typeof value === 'string' ? value : null);
13
23
  const record = (value) => (isRecord(value) ? value : {});
@@ -1,3 +1,4 @@
1
+ import { type ValueRow, type ValuesDone, type ValuesPatch } from './values.types.js';
1
2
  export interface HostRow {
2
3
  id: string;
3
4
  version: string;
@@ -34,6 +35,8 @@ export interface HostClient {
34
35
  id: string;
35
36
  }>;
36
37
  reload: (id: string, part?: 'app') => Promise<HostReload>;
38
+ values: (owner?: string) => Promise<ValueRow[]>;
39
+ patchValues: (patch: ValuesPatch) => Promise<ValuesDone>;
37
40
  }
38
41
  export interface HostReload {
39
42
  id: string;
@@ -3,6 +3,7 @@ import { CliError, DaemonError, messageOf } from '../json-output.js';
3
3
  import { daemonFailure } from './daemon-answer.js';
4
4
  import { daemonFilePath, readHostToken } from './daemon-file.js';
5
5
  import { provenPort } from './daemon-probe.js';
6
+ import {} from './values.types.js';
6
7
  // An install runs npm (the daemon waits up to 660 s), then starts the child: past that it is stuck.
7
8
  // A reload: drain 10 s, start and health 60 s each, and the same again to restore: past 5 min stuck.
8
9
  const WAITS = { read: 10_000, change: 12 * 60_000, reload: 5 * 60_000 };
@@ -71,5 +72,7 @@ export const hostClient = (port, waits = WAITS, token = readHostToken, same = sa
71
72
  change: (id, patch) => send('PATCH', at(id), patch),
72
73
  remove: (id, purge) => send('DELETE', `${at(id)}${purge ? '?purge=true' : ''}`),
73
74
  reload: (id, part) => send('POST', `${at(id)}/reload`, part ? { part } : {}, 'RELOAD'),
75
+ values: (owner) => send('GET', `/host/values${owner ? `?owner=${encodeURIComponent(owner)}` : ''}`),
76
+ patchValues: (patch) => send('PATCH', '/host/values', patch),
74
77
  };
75
78
  };
@@ -0,0 +1,30 @@
1
+ import { type HostSummary } from './host-client.js';
2
+ export interface SettingRow {
3
+ key: string;
4
+ type: string;
5
+ enum?: unknown[];
6
+ value: unknown;
7
+ source: 'default' | 'set';
8
+ share?: string;
9
+ declaredBy?: string[];
10
+ conflict?: string;
11
+ }
12
+ export interface SecretRow {
13
+ key: string;
14
+ set: boolean;
15
+ share?: string;
16
+ declaredBy?: string[];
17
+ }
18
+ export interface ValueRow {
19
+ owner: string;
20
+ settings: SettingRow[];
21
+ secrets: SecretRow[];
22
+ }
23
+ export interface ValuesPatch {
24
+ settings?: Record<string, unknown>;
25
+ secrets?: Record<string, string | null>;
26
+ }
27
+ export interface ValuesDone {
28
+ changed: string[];
29
+ restarted: HostSummary[];
30
+ }
@@ -0,0 +1 @@
1
+ import {} from './host-client.js';
@@ -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,9 +1,10 @@
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", "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
- constructor(code: Code, message: string);
6
+ readonly details: Record<string, unknown>;
7
+ constructor(code: Code, message: string, details?: Record<string, unknown>);
7
8
  }
8
9
  export declare class DaemonError extends Error {
9
10
  readonly code: string;
@@ -2,49 +2,16 @@ 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
- 'stop_failed',
37
- 'timeout',
38
- 'token_request_failed',
39
- 'uncommitted_changes',
40
- 'usage',
41
- ];
5
+ import {} from './json-codes.js';
6
+ export { CODES } from './json-codes.js';
42
7
  // An error with a stable snake_case code for `--json`; any other error is `error`.
43
8
  export class CliError extends Error {
44
9
  code;
45
- constructor(code, message) {
10
+ details;
11
+ constructor(code, message, details = {}) {
46
12
  super(message);
47
13
  this.code = code;
14
+ this.details = details;
48
15
  }
49
16
  }
50
17
  // The daemon's own code (NOT_FOUND, INVALID_SETTING) and details (START_FAILED), as it gives them.
@@ -111,7 +78,9 @@ export const messageOf = (err) => {
111
78
  return `${err.message}${why}`;
112
79
  };
113
80
  export const writeError = (io, err, code = codeOf(err)) => {
114
- const details = err instanceof DaemonError && Object.keys(err.details).length && err.details;
81
+ const details = (err instanceof DaemonError || err instanceof CliError) &&
82
+ Object.keys(err.details).length &&
83
+ err.details;
115
84
  const error = { code, message: messageOf(err), ...(details && { details }) };
116
85
  io.writeOut(`${JSON.stringify({ success: false, error })}\n`);
117
86
  };
@@ -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
+ };
@@ -0,0 +1,13 @@
1
+ import { CliError } from '../json-output.js';
2
+ export interface GitResult {
3
+ code: number;
4
+ stdout: string;
5
+ stderr: string;
6
+ }
7
+ export type Git = (args: string[], extra?: NodeJS.ProcessEnv) => Promise<GitResult>;
8
+ export declare const cloneUrl: (repo: string) => string;
9
+ export declare const gitEnv: (env?: NodeJS.ProcessEnv) => NodeJS.ProcessEnv;
10
+ export declare const redact: (text: string, env?: NodeJS.ProcessEnv) => string;
11
+ export declare const runGit: (env?: NodeJS.ProcessEnv) => Git;
12
+ export declare const gitError: (repo: string, res: GitResult) => CliError;
13
+ export declare const gitOk: (git: Git, repo: string, args: string[], extra?: NodeJS.ProcessEnv) => Promise<string>;