@agentage/cli 0.51.1 → 0.52.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 (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 +19 -0
  104. package/dist/lib/daemon/daemon-client.js +125 -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 +34 -0
  110. package/dist/lib/daemon/daemon-probe.js +50 -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,15 @@
1
+ import type { CheckReport } from '@agentage/extension/tool';
2
+ import { type LoadKitTool } from './kit-tool.js';
3
+ export type Npm = (dir: string, args: string[]) => Promise<void>;
4
+ export declare const npmIn: (dir: string, args: string[], timeoutMs?: number, graceMs?: number) => Promise<void>;
5
+ export interface PackageBuild {
6
+ dir: string;
7
+ built: boolean;
8
+ contracts: string[];
9
+ report: CheckReport;
10
+ }
11
+ export interface PackageBuildDeps {
12
+ npm: Npm;
13
+ tool: LoadKitTool;
14
+ }
15
+ export declare const buildPackage: (folder?: string, deps?: PackageBuildDeps) => Promise<PackageBuild>;
@@ -0,0 +1,51 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { join, resolve } from 'node:path';
4
+ import { childEnv } from '../../lib/child-env.js';
5
+ import { CliError } from '../../lib/json-output.js';
6
+ import { loadKitTool } from './kit-tool.js';
7
+ const STEP_MS = 600_000;
8
+ const GRACE_MS = 5_000;
9
+ const failed = (what, why) => new CliError('build_failed', `${what} ${why}`);
10
+ const how = (code, signal) => code === null ? `exited by signal ${signal ?? 'unknown'}` : `exited ${code}`;
11
+ // npm's own output goes to stderr, so a --json stdout stays one object. Past its time it gets
12
+ // SIGTERM, then SIGKILL after `graceMs`.
13
+ export const npmIn = (dir, args, timeoutMs = STEP_MS, graceMs = GRACE_MS) => new Promise((done, fail) => {
14
+ const what = `npm ${args.join(' ')} in ${dir}`;
15
+ const child = spawn('npm', args, { cwd: dir, env: childEnv(), stdio: ['ignore', 2, 2] });
16
+ let late = false;
17
+ let kill;
18
+ const timer = setTimeout(() => {
19
+ late = true;
20
+ child.kill('SIGTERM');
21
+ kill = setTimeout(() => child.kill('SIGKILL'), graceMs);
22
+ }, timeoutMs);
23
+ const stop = () => (clearTimeout(timer), clearTimeout(kill));
24
+ child.once('error', (err) => (stop(), fail(failed(what, `did not start: ${err.message}`))));
25
+ child.once('exit', (code, signal) => {
26
+ stop();
27
+ if (code === 0)
28
+ return done();
29
+ const stopped = `did not finish in ${timeoutMs / 1000} s; stopped (${how(code, signal)})`;
30
+ fail(failed(what, late ? stopped : how(code, signal)));
31
+ });
32
+ });
33
+ const hasBuildScript = (dir) => {
34
+ if (!existsSync(join(dir, 'package.json')))
35
+ throw new CliError('invalid_argument', `no package.json in ${dir}: run it in an extension package folder`);
36
+ const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
37
+ return typeof pkg.scripts?.['build'] === 'string';
38
+ };
39
+ const defaultDeps = { npm: npmIn, tool: loadKitTool };
40
+ // The author's build script, the kit's contract files, then the kit's check; no Docker.
41
+ export const buildPackage = async (folder = '.', deps = defaultDeps) => {
42
+ const dir = resolve(folder);
43
+ const built = hasBuildScript(dir);
44
+ if (built)
45
+ await deps.npm(dir, ['run', 'build']);
46
+ const kit = await deps.tool();
47
+ const contracts = await kit.writeContracts(dir);
48
+ for (const file of contracts)
49
+ console.log(`wrote ${file}`);
50
+ return { dir, built, contracts, report: await kit.check(dir) };
51
+ };
@@ -1,8 +1,10 @@
1
- import { type Plan } from '../../core/installer/plan.js';
2
1
  import { type Profile } from '../../core/profile/schema.js';
2
+ import { type ProfilePlan } from './profile-plan.js';
3
3
  export interface PlanOptions {
4
4
  json?: boolean;
5
+ file: boolean;
6
+ from: string;
5
7
  }
6
- export declare const planLines: ({ extensions, summary: s }: Plan) => string[];
8
+ export declare const planLines: ({ extensions, summary: s, skipped }: ProfilePlan) => string[];
7
9
  export declare const printDryRun: (profile: Profile, opts: PlanOptions) => void;
8
10
  export declare const runSetupCheck: (profile: Profile, opts: PlanOptions) => void;
@@ -1,32 +1,32 @@
1
1
  import { DEFAULT_REGISTRY } from '../../core/installer/npm.js';
2
- import { currentDependencies, driftLines, lockDrift, pendingChanges, planChanges, } from '../../core/installer/plan.js';
3
- import { NO_MACHINE, readMachine } from '../../core/profile/machine.js';
4
- import { effective, keepMachine } from '../../core/profile/merge.js';
2
+ import { existsSync } from 'node:fs';
3
+ import {} from '../../core/installer/plan.js';
4
+ import { machinePath } from '../../core/paths.js';
5
+ import { readMachine } from '../../core/profile/machine.js';
6
+ import { keepMachine } from '../../core/profile/merge.js';
5
7
  import { readProfile } from '../../core/profile/profile.js';
6
8
  import {} from '../../core/profile/schema.js';
7
- import { line } from './install-load.js';
8
- // Desired: the profile, with this machine's own entry from profile.json as setup keeps it.
9
- const planFor = (profile, machine) => {
9
+ import { line } from './line.js';
10
+ import { accountProfileInstalled, NOT_EXTENSION, profilePlan, } from './profile-plan.js';
11
+ // What setup would send to the daemon, with this machine's own entry from profile.json kept. A
12
+ // file (`--profile`) is never gated; the local profile is, once the account profile was installed.
13
+ const planFor = (profile, file) => {
10
14
  const local = readProfile();
11
- const id = machine?.id ?? '';
12
- const desired = keepMachine(profile, local?.ok ? local.profile : null, id);
13
- return planChanges(effective(desired, machine ?? NO_MACHINE), currentDependencies());
14
- };
15
- const entryLine = ({ verb, name, wanted, current }) => {
16
- if (verb === 'add')
17
- return `+ add ${name} ${wanted}`;
18
- if (verb === 'update')
19
- return `~ update ${name} ${wanted} (was ${current})`;
20
- return verb === 'remove' ? `- remove ${name}` : `o off ${name}`;
15
+ const desired = keepMachine(profile, local?.ok ? local.profile : null, readMachine()?.id ?? '');
16
+ return profilePlan(desired, !file && accountProfileInstalled());
21
17
  };
18
+ const entryLine = ({ verb, name, wanted }) => verb === 'add' ? `+ add ${name} ${wanted}` : `o off ${name} ${wanted} (installed disabled)`;
22
19
  // One line per extension setup would touch or leaves off, then one summary line.
23
- export const planLines = ({ extensions, summary: s }) => {
20
+ export const planLines = ({ extensions, summary: s, skipped }) => {
24
21
  const shown = extensions.filter((entry) => entry.verb !== 'unchanged');
22
+ const skips = skipped.map((name) => `- ${name}: ${NOT_EXTENSION}`);
25
23
  if (shown.length === 0)
26
- return ['plan: nothing to change'];
27
- const total = `${s.add} to add, ${s.update} to update, ${s.remove} to remove`;
28
- return [...shown.map(entryLine), `plan: ${total}, ${s.off} off, ${s.unchanged} unchanged`];
24
+ return [...skips, 'plan: nothing to change'];
25
+ const total = `${s.add} to add, ${s.off} off, ${s.unchanged} already installed`;
26
+ return [...shown.map(entryLine), ...skips, `plan: ${total}`];
29
27
  };
28
+ // --check and --dry-run read no account: the plan says which profile it is of.
29
+ const sourceLine = ({ file, from }) => line('from', file ? from : `${from} on this machine; plain setup installs your account profile`);
30
30
  // One line per scope the profile routes, then the registry for everything else.
31
31
  const registryLines = (registries) => {
32
32
  const all = [...Object.entries(registries), ['default', DEFAULT_REGISTRY]];
@@ -35,32 +35,32 @@ const registryLines = (registries) => {
35
35
  };
36
36
  // `setup --dry-run`: reads only, never creates machine.json.
37
37
  export const printDryRun = (profile, opts) => {
38
- const plan = planFor(profile, readMachine());
38
+ const plan = planFor(profile, opts.file);
39
39
  if (opts.json)
40
- return console.log(JSON.stringify(plan, null, 2));
40
+ return console.log(JSON.stringify({ ...plan, source: opts.from }, null, 2));
41
41
  const header = [line('dry run', 'nothing written'), ...registryLines(profile.registries)];
42
- for (const text of [...header, ...planLines(plan)])
42
+ for (const text of [...header, ...planLines(plan), sourceLine(opts)])
43
43
  console.log(text);
44
44
  };
45
- const LOCK_MISMATCH = 'lock mismatch: extensions/package-lock.json does not match the current tree';
46
- // What applying the plan would not fix: a lock that disagrees with its tree.
47
- const lockProblems = () => {
48
- const { integrity, matches } = lockDrift();
49
- if (integrity.length > 0)
50
- return driftLines(integrity);
51
- return matches ? [] : [LOCK_MISMATCH];
45
+ // A machine.json that does not parse is not "missing": setup would not make a new one over it.
46
+ const machineProblem = () => {
47
+ if (readMachine())
48
+ return [];
49
+ return [
50
+ existsSync(machinePath()) ? 'machine.json: invalid, fix or delete it' : 'machine.json: missing',
51
+ ];
52
52
  };
53
- // `setup --check`: the plan, then exit 1 for anything setup would change or cannot trust.
53
+ // `setup --check`: the plan, then exit 1 for anything setup would install.
54
54
  export const runSetupCheck = (profile, opts) => {
55
- const machine = readMachine();
56
- const plan = planFor(profile, machine);
57
- const problems = [...(machine ? [] : ['machine.json: missing']), ...lockProblems()];
55
+ const plan = planFor(profile, opts.file);
56
+ const problems = machineProblem();
58
57
  if (opts.json)
59
- console.log(JSON.stringify({ ...plan, problems }, null, 2));
58
+ console.log(JSON.stringify({ ...plan, problems, source: opts.from }, null, 2));
60
59
  else
61
- for (const text of planLines(plan))
60
+ for (const text of [...planLines(plan), sourceLine(opts)])
62
61
  console.log(text);
63
- const changes = pendingChanges(plan.summary);
62
+ const { add, off } = plan.summary;
63
+ const changes = [add && `${add} to add`, off && `${off} to install disabled`].filter(Boolean);
64
64
  const pending = changes.length > 0 ? [`not converged: ${changes.join(', ')}`] : [];
65
65
  if (problems.length + pending.length > 0)
66
66
  throw new Error([...problems, ...pending].join('\n'));
@@ -0,0 +1,16 @@
1
+ import { type Plan } from '../../core/installer/plan.js';
2
+ import { type Profile } from '../../core/profile/schema.js';
3
+ export declare const profileMarkerPath: () => string;
4
+ export declare const accountProfileInstalled: () => boolean;
5
+ export declare const NOT_EXTENSION = "not an extension, skipped";
6
+ export interface ProfileEntry {
7
+ name: string;
8
+ range: string;
9
+ id: string | null;
10
+ off: boolean;
11
+ }
12
+ export declare const profileEntries: (profile: Profile) => ProfileEntry[];
13
+ export type ProfilePlan = Plan & {
14
+ skipped: string[];
15
+ };
16
+ export declare const profilePlan: (profile: Profile, done: boolean) => ProfilePlan;
@@ -0,0 +1,48 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import {} from '../../core/installer/plan.js';
4
+ import { installationRows } from '../../core/loader/installed.js';
5
+ import { readMachine } from '../../core/profile/machine.js';
6
+ import {} from '../../core/profile/schema.js';
7
+ import { getConfigDir } from '../../lib/fs/config.js';
8
+ const PACKAGE_ID = /^(?:@agentage\/extension-|agentage-extension-)([a-z][a-z0-9-]*)$/;
9
+ // Written once plain setup tried every entry of the account profile: once per machine.
10
+ export const profileMarkerPath = () => join(getConfigDir(), 'setup.profile-installed');
11
+ export const accountProfileInstalled = () => existsSync(profileMarkerPath());
12
+ // A profile entry the daemon can never install: said once, never a change to make.
13
+ export const NOT_EXTENSION = 'not an extension, skipped';
14
+ export const profileEntries = (profile) => {
15
+ const off = profile.machines[readMachine()?.id ?? '']?.off ?? [];
16
+ return Object.entries(profile.extensions).map(([name, range]) => ({
17
+ name,
18
+ range,
19
+ id: PACKAGE_ID.exec(name)?.[1] ?? null,
20
+ off: off.includes(name),
21
+ }));
22
+ };
23
+ const verbOf = (entry, have, done) => {
24
+ if (done || (entry.id !== null && have.has(entry.id)))
25
+ return 'unchanged';
26
+ return entry.off ? 'off' : 'add';
27
+ };
28
+ // What setup would send to the daemon: add, add disabled (off), or nothing (unchanged). Reads
29
+ // installation.json only; `done` is a plain setup that installed the account profile already.
30
+ export const profilePlan = (profile, done) => {
31
+ const rows = new Map(installationRows().map((row) => [row.id, row]));
32
+ const entries = profileEntries(profile);
33
+ const extensions = entries.flatMap((entry) => entry.id === null
34
+ ? []
35
+ : [
36
+ {
37
+ verb: verbOf(entry, new Set(rows.keys()), done),
38
+ name: entry.name,
39
+ wanted: entry.range,
40
+ current: rows.has(entry.id) ? 'installed' : null,
41
+ },
42
+ ]);
43
+ const summary = { add: 0, update: 0, remove: 0, off: 0, unchanged: 0 };
44
+ for (const entry of extensions)
45
+ summary[entry.verb] += 1;
46
+ const skipped = entries.filter((entry) => entry.id === null).map((entry) => entry.name);
47
+ return { extensions, summary, skipped };
48
+ };
@@ -4,11 +4,12 @@ import { type Exec } from './release-guard.js';
4
4
  export type ExtensionReleaseOptions = {
5
5
  dir?: string;
6
6
  timeout?: number;
7
+ json?: boolean;
7
8
  };
8
9
  export interface ReleaseDeps {
9
10
  exec: (cwd: string, seconds?: number) => Exec;
10
11
  tool: LoadKitTool;
11
12
  env: NodeJS.ProcessEnv;
12
13
  }
13
- export declare const runExtensionRelease: ({ dir, timeout }?: ExtensionReleaseOptions, deps?: ReleaseDeps) => Promise<void>;
14
+ export declare const runExtensionRelease: ({ dir, timeout }?: ExtensionReleaseOptions, deps?: ReleaseDeps) => Promise<unknown>;
14
15
  export declare const addRelease: (group: Command, release: (opts: ExtensionReleaseOptions) => Promise<void>) => void;
@@ -2,13 +2,14 @@ import { mkdtemp, writeFile } from 'node:fs/promises';
2
2
  import { tmpdir } from 'node:os';
3
3
  import { join } from 'node:path';
4
4
  import {} from 'commander';
5
- import { runExtensionBuild } from './build.js';
5
+ import { addJson, CliError } from '../../lib/json-output.js';
6
+ import { runImageBuild } from './build.js';
6
7
  import { loadKitTool } from './kit-tool.js';
7
8
  import { execIn, IMAGE_PARTS, RECORD, releaseGuard } from './release-guard.js';
8
9
  const defaultDeps = { exec: execIn, tool: loadKitTool, env: process.env };
9
10
  const step = (line) => console.log(`PASS ${line}`);
10
11
  const fail = (line) => {
11
- throw new Error(`FAIL ${line}`);
12
+ throw new CliError('release_refused', `FAIL ${line}`);
12
13
  };
13
14
  // Tokens leave the environment, so docker build and npm lifecycle scripts never see them.
14
15
  const takeSecrets = (env) => {
@@ -115,19 +116,19 @@ export const runExtensionRelease = async ({ dir = '.', timeout = 60 } = {}, deps
115
116
  const done = isPrivate ? 'is released' : 'is released: npm only';
116
117
  step(`guard: ${tag} ${build ? 'has no record and no image: build' : done}`);
117
118
  if (build) {
118
- await runExtensionBuild({ push: true, dir }, deps.tool);
119
+ await runImageBuild({ push: true, dir }, deps.tool);
119
120
  await attach(run, tag, repo);
120
121
  }
121
122
  if (isPrivate)
122
- return step('npm: private package, not published');
123
- const push = scoped(deps.exec(dir, PUBLISH_SECONDS), secrets);
124
- await publish(run, push, pkg, secrets['npm']?.['NPM_TOKEN']);
123
+ step('npm: private package, not published');
124
+ else
125
+ await publish(run, scoped(deps.exec(dir, PUBLISH_SECONDS), secrets), pkg, secrets['npm']?.['NPM_TOKEN']);
126
+ return { id, version: pkg.version, tag, built: build, published: !isPrivate };
125
127
  };
126
128
  export const addRelease = (group, release) => {
127
- group
129
+ addJson(group
128
130
  .command('release')
129
131
  .description('Release an extension from its v* tag in CI: guard, images, record, npm package')
130
132
  .option('--dir <path>', 'the extension package folder (default: the current folder)')
131
- .option('--timeout <seconds>', 'bound on each git, GitHub and npm check (default: 60; npm publish: 300)', Number)
132
- .action(release);
133
+ .option('--timeout <seconds>', 'bound on each git, GitHub and npm check (default: 60; npm publish: 300)', Number)).action(release);
133
134
  };
@@ -1,5 +1,4 @@
1
1
  import { type ExtensionRow, type ExtensionsStatus } from './rows.js';
2
2
  export declare const summaryLines: (status: ExtensionsStatus) => string[];
3
- export type Latest = ReadonlyMap<string, string | null>;
4
- export declare const rowLines: (rows: ExtensionRow[], latest?: Latest) => string[];
3
+ export declare const rowLines: (rows: ExtensionRow[]) => string[];
5
4
  export declare const printWarnings: (warnings: string[]) => void;
@@ -1,5 +1,6 @@
1
1
  import chalk from 'chalk';
2
2
  import { pendingChanges } from '../../core/installer/plan.js';
3
+ import { line } from './line.js';
3
4
  import {} from './rows.js';
4
5
  const COLOR = {
5
6
  installed: chalk.green,
@@ -11,7 +12,6 @@ const COLOR = {
11
12
  missing: chalk.yellow,
12
13
  };
13
14
  const STATE_WIDTH = Math.max(...Object.keys(COLOR).map((state) => state.length));
14
- const line = (label, value) => `${label.padEnd(10)} ${value}`;
15
15
  const cloudText = ({ version, etag }) => chalk.yellow(`; account: version ${version}, etag ${etag} - run agentage setup`);
16
16
  const profileText = (profile) => {
17
17
  if (profile.state === 'missing')
@@ -46,22 +46,21 @@ const wantedText = (row) => {
46
46
  return 'dev';
47
47
  return row.wanted === null ? 'not in profile' : `wants ${row.wanted}`;
48
48
  };
49
- const rowLine = (row, widths, latest) => {
49
+ const rowLine = (row, widths) => {
50
50
  const id = (row.id ?? '?').padEnd(widths.id);
51
51
  const state = COLOR[row.state](row.state.padEnd(STATE_WIDTH));
52
52
  const drift = widths.drift === 0 ? '' : `${driftOf(row).padEnd(widths.drift)} `;
53
53
  const pkg = `${row.package} ${row.installed ?? '-'} (${wantedText(row)})`;
54
- const newest = latest ? ` latest ${latest.get(row.id ?? '') ?? '-'}` : '';
55
54
  const commands = row.commands.length > 0 ? ` commands: ${row.commands.join(', ')}` : '';
56
55
  // A failed load quotes the extension's own message; the core's reasons print as they are.
57
56
  const reason = row.state === 'failed' ? `"${row.error}"` : row.error;
58
57
  const error = row.error === null ? '' : chalk.dim(` ${reason}`);
59
- return `${id} ${state} ${drift}${pkg}${newest}${commands}${lastRunText(row.lastRun)}${error}`;
58
+ return `${id} ${state} ${drift}${pkg}${commands}${lastRunText(row.lastRun)}${error}`;
60
59
  };
61
- export const rowLines = (rows, latest) => {
60
+ export const rowLines = (rows) => {
62
61
  const id = Math.max(0, ...rows.map((row) => (row.id ?? '?').length));
63
62
  const drift = Math.max(0, ...rows.map((row) => driftOf(row).length));
64
- return rows.map((row) => rowLine(row, { id, drift }, latest));
63
+ return rows.map((row) => rowLine(row, { id, drift }));
65
64
  };
66
65
  export const printWarnings = (warnings) => {
67
66
  for (const warning of warnings)
@@ -1,7 +1,8 @@
1
+ import { CliError } from '../../lib/json-output.js';
1
2
  import {} from '../../core/installer/plan.js';
2
3
  import {} from '../../core/loader/discover.js';
3
4
  import {} from '../../core/loader/load.js';
4
- import { loadSet, scan } from '../../core/loader/scan.js';
5
+ import { loadSet, scanNow } from '../../core/loader/scan.js';
5
6
  import { readRunState } from '../../core/loader/state.js';
6
7
  import {} from '../../core/loader/states.js';
7
8
  import { claimVerbs, commandNames, readHeld } from '../../core/loader/verbs.js';
@@ -56,12 +57,13 @@ export const gatherFrom = (found, runs = new Map()) => {
56
57
  plan: found.plan.summary,
57
58
  extensions,
58
59
  };
59
- const warnings = [...(parsed?.ok ? parsed.warnings : []), ...found.found.warnings];
60
+ const old = found.found.extensions.flatMap((p) => (p.warning ? [`${p.id}: ${p.warning}`] : []));
61
+ const warnings = [...(parsed?.ok ? parsed.warnings : []), ...found.found.warnings, ...old];
60
62
  return { status, warnings, drift: found.drift, verbs: seen.verbs };
61
63
  };
62
64
  // Reads manifests, profile and state files; writes only a missing machine.json.
63
- export const gatherExtensions = async () => gatherFrom(scan(await loadMachine()));
65
+ export const gatherExtensions = async () => gatherFrom(scanNow(await loadMachine()));
64
66
  // The report still prints first; an invalid profile.json then fails the step.
65
67
  export const invalidProfileError = (profile) => profile.state === 'invalid'
66
- ? new Error(`profile.json is invalid:\n${profile.errors.map((e) => ` ${e}`).join('\n')}`)
68
+ ? new CliError('profile_invalid', `profile.json is invalid:\n${profile.errors.map((e) => ` ${e}`).join('\n')}`)
67
69
  : null;
@@ -1,6 +1,6 @@
1
- import { type EditDeps } from './sync.js';
1
+ import { type EditDeps, type ProfileDeps } from './sync.js';
2
2
  export interface AccountSetupDeps extends EditDeps {
3
3
  signOut: () => Promise<void>;
4
4
  }
5
- export declare const accountSetup: (deps: EditDeps) => Promise<void>;
5
+ export declare const accountSetup: (deps: ProfileDeps) => Promise<void>;
6
6
  export declare const disconnect: (deps: AccountSetupDeps) => Promise<void>;
@@ -5,7 +5,7 @@ import { defaultProfile, mutateProfile, readProfile } from '../../core/profile/p
5
5
  import { pushWithReplay } from '../../core/profile/push.js';
6
6
  import { disconnectMachine, registerMachine } from '../../core/profile/register.js';
7
7
  import {} from '../../core/profile/schema.js';
8
- import { installAndLoad, line } from './install-load.js';
8
+ import { line } from './line.js';
9
9
  import { applying, checkAccount } from './sync.js';
10
10
  const FILE_NOTE = 'from a file (setup --profile), not synced with your account';
11
11
  // profile.json: null when absent; an invalid one stops setup naming each problem.
@@ -26,12 +26,13 @@ const fromLocalCopy = async (reason, deps) => {
26
26
  if (local === null)
27
27
  return console.error(chalk.dim(`${unavailable} and no local profile.json, nothing installed (${reason})`));
28
28
  console.error(chalk.dim(`${unavailable}, using local profile.json (${reason})`));
29
- await installAndLoad(local, deps.npm);
29
+ await deps.installProfile(local);
30
30
  };
31
31
  const installPulled = async (doc, deps) => {
32
32
  await mutateProfile(() => doc.profile);
33
33
  console.log(line('profile', `pulled from your account (etag ${doc.etag})`));
34
- await installAndLoad({ ...doc.profile, lock: doc.lock }, deps.npm, () => setCloud(doc.etag));
34
+ await setCloud(doc.etag);
35
+ await deps.installProfile(doc.profile);
35
36
  };
36
37
  // A create the account did not take fails nothing: the next setup creates it.
37
38
  const notCreated = (err) => {
@@ -55,7 +56,7 @@ const createIn = async (account, deps) => {
55
56
  const profileFrom = async (account, machine, deps) => {
56
57
  if (machine.profileSource === 'file') {
57
58
  console.log(line('profile', FILE_NOTE));
58
- return installAndLoad(localCopy() ?? defaultProfile(), deps.npm);
59
+ return deps.installProfile(localCopy() ?? defaultProfile());
59
60
  }
60
61
  const pulled = await pullProfile(account.fetch, mirroredEtag(machine));
61
62
  if (pulled.kind === 'found')
@@ -63,7 +64,7 @@ const profileFrom = async (account, machine, deps) => {
63
64
  if (pulled.kind === 'none')
64
65
  return createIn(account, deps);
65
66
  if (pulled.kind === 'current')
66
- return installAndLoad(localCopy() ?? defaultProfile(), deps.npm);
67
+ return deps.installProfile(localCopy() ?? defaultProfile());
67
68
  return fromLocalCopy(pulled.reason, deps);
68
69
  };
69
70
  // The first signed-in setup records the account; another account is refused until --disconnect.
@@ -0,0 +1,8 @@
1
+ import { type Profile } from '../../core/profile/schema.js';
2
+ import { type HostClient } from '../../lib/daemon/host-client.js';
3
+ export interface ProfileInstallDeps {
4
+ host: () => Promise<HostClient>;
5
+ daemonOff: boolean;
6
+ from: 'account' | 'file';
7
+ }
8
+ export declare const installThroughDaemon: (profile: Profile, deps: ProfileInstallDeps) => Promise<void>;
@@ -0,0 +1,56 @@
1
+ import { writeFileSync } from 'node:fs';
2
+ import {} from '../../core/profile/schema.js';
3
+ import {} from '../../lib/daemon/host-client.js';
4
+ import { CliError, messageOf } from '../../lib/json-output.js';
5
+ import { line } from './line.js';
6
+ import { addOnce } from './install-once.js';
7
+ import { accountProfileInstalled, NOT_EXTENSION, profileEntries, profileMarkerPath, } from './profile-plan.js';
8
+ const EXACT = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
9
+ const KEPT = 'your account profile was installed here already; setup installs nothing (agentage extension install)';
10
+ // An exact version is sent as it is; a range installs the market's newest version.
11
+ const bodyOf = (id, range) => EXACT.test(range) ? { id, version: range } : { id };
12
+ // One entry through POST /host/extensions; an off entry is added disabled (it never starts).
13
+ const installOne = async (host, entry) => {
14
+ const off = entry.off ? { enabled: false } : {};
15
+ const { row, already } = await addOnce(host, { ...bodyOf(entry.id, entry.range), ...off });
16
+ return already ? { ...row, already } : row;
17
+ };
18
+ // A package that is not an extension is said and skipped: the daemon cannot install it, ever.
19
+ // A problem is the line under "not installed": the entry failed to install or to start.
20
+ const tryOne = async (host, entry) => {
21
+ if (entry.id === null)
22
+ return void console.log(`${entry.name}: ${NOT_EXTENSION}`);
23
+ const id = entry.id;
24
+ const row = await installOne(host, { ...entry, id }).catch((err) => ({
25
+ id,
26
+ error: messageOf(err),
27
+ }));
28
+ if ('error' in row && !('state' in row))
29
+ return `${id}: ${row.error}`;
30
+ if ('already' in row)
31
+ return void console.log(`${id} already installed`);
32
+ console.log(`${row.id} ${row.version} ${row.state}`);
33
+ return row.state === 'failed' ? `${id}: ${row.error ?? 'failed'}` : undefined;
34
+ };
35
+ // The profile's extensions go through the daemon, which runs them; the cli loads nothing itself.
36
+ // An entry already in the installation is left as it is.
37
+ export const installThroughDaemon = async (profile, deps) => {
38
+ const account = deps.from === 'account';
39
+ if (account && accountProfileInstalled())
40
+ return console.log(line('extensions', KEPT));
41
+ const entries = profileEntries(profile);
42
+ if (entries.length > 0 && deps.daemonOff)
43
+ return console.log(line('extensions', 'the daemon is off, nothing installed'));
44
+ const host = entries.length > 0 ? await deps.host() : null;
45
+ const problems = [];
46
+ for (const entry of host ? entries : []) {
47
+ const problem = await tryOne(host, entry);
48
+ if (problem)
49
+ problems.push(problem);
50
+ }
51
+ // An empty profile tried nothing: a later setup still installs one with entries.
52
+ if (account && host)
53
+ writeFileSync(profileMarkerPath(), `${new Date().toISOString()}\n`, { mode: 0o600 });
54
+ if (problems.length > 0)
55
+ throw new CliError('extension_failed', ['not installed:', ...problems.map((p) => ` ${p}`)].join('\n'));
56
+ };
@@ -1,5 +1,8 @@
1
1
  import { type SetupDeps, type SetupOptions } from '../auth/setup.js';
2
+ import { type HostClient } from '../../lib/daemon/host-client.js';
2
3
  import { type EditDeps } from './sync.js';
3
4
  export interface ExtensionSetupDeps extends SetupDeps, EditDeps {
5
+ host: () => Promise<HostClient>;
6
+ updateExtensions: () => Promise<unknown>;
4
7
  }
5
- export declare const runExtensionSetup: (opts: SetupOptions, deps: ExtensionSetupDeps) => Promise<void>;
8
+ export declare const runExtensionSetup: (opts: SetupOptions, deps: ExtensionSetupDeps) => Promise<unknown>;
@@ -1,19 +1,22 @@
1
1
  import { readFileSync } from 'node:fs';
2
+ import { rawPatToken } from '../../lib/auth/credentials.js';
2
3
  import { loadMachine, setProfileSource } from '../../core/profile/machine.js';
3
4
  import { keepMachine } from '../../core/profile/merge.js';
4
5
  import { defaultProfile, mutateProfile, parseProfileText, readProfile, } from '../../core/profile/profile.js';
5
6
  import {} from '../../core/profile/schema.js';
6
7
  import {} from '../auth/setup.js';
7
- import { installAndLoad } from './install-load.js';
8
- import { runSetupLatest } from './latest.js';
9
8
  import { printDryRun, runSetupCheck } from './plan.js';
10
9
  import { printWarnings } from './row-lines.js';
11
10
  import { accountSetup, disconnect } from './setup-cloud.js';
11
+ import { installThroughDaemon } from './setup-install.js';
12
+ import {} from '../../lib/daemon/host-client.js';
13
+ import { daemonOff } from '../../lib/daemon/daemon-file.js';
12
14
  import {} from './sync.js';
15
+ import { CliError } from '../../lib/json-output.js';
13
16
  const sourceOf = (label, parsed) => {
14
17
  if (!parsed.ok)
15
- throw new Error(`${label} is invalid:\n${parsed.errors.map((e) => ` ${e}`).join('\n')}`);
16
- return { profile: parsed.profile, warnings: parsed.warnings };
18
+ throw new CliError('profile_invalid', `${label} is invalid: ${parsed.errors.join('; ')}`);
19
+ return { profile: parsed.profile, warnings: parsed.warnings, from: label };
17
20
  };
18
21
  const fileSource = (file) => {
19
22
  if (/^[a-z][a-z0-9+.-]*:\/\//i.test(file))
@@ -32,37 +35,72 @@ const localSource = () => {
32
35
  const parsed = readProfile();
33
36
  if (parsed !== null)
34
37
  return sourceOf('profile.json', parsed);
35
- return { profile: defaultProfile(), warnings: [] };
38
+ return { profile: defaultProfile(), warnings: [], from: 'the built-in default profile' };
36
39
  };
37
40
  // --check and --dry-run read only and never sign in.
38
- const readOnly = (source, opts) => {
41
+ const readOnly = (source, opts, file) => {
39
42
  printWarnings(source.warnings);
43
+ const plan = { ...opts, file, from: source.from };
40
44
  if (opts.check)
41
- runSetupCheck(source.profile, opts);
45
+ runSetupCheck(source.profile, plan);
42
46
  else
43
- printDryRun(source.profile, opts);
47
+ printDryRun(source.profile, plan);
44
48
  };
45
- // `--profile` never signs in nor calls the account; this machine's own entry is kept.
46
- const fromFile = async (source, deps) => {
49
+ const noDaemon = (opts) => opts.daemon === false || daemonOff();
50
+ // `--profile` never signs in nor calls the account; it installs through the daemon as plain setup.
51
+ const fromFile = async (source, opts, deps) => {
47
52
  const machine = await loadMachine();
48
53
  await mutateProfile((current) => keepMachine(source.profile, current, machine.id));
49
54
  await setProfileSource('file');
50
- await installAndLoad(source.profile, deps.npm);
55
+ await installThroughDaemon(source.profile, {
56
+ host: deps.host,
57
+ daemonOff: noDaemon(opts),
58
+ from: 'file',
59
+ });
51
60
  };
52
- export const runExtensionSetup = async (opts, deps) => {
61
+ // The daemon needs no account; --no-daemon or AGENTAGE_NO_DAEMON=1 leave it off.
62
+ const startDaemon = async (opts, deps) => {
63
+ if (noDaemon(opts))
64
+ return;
65
+ console.log(`daemon running on 127.0.0.1:${await deps.startDaemon()}`);
66
+ };
67
+ // Plain setup installs the profile only through the daemon (one install path).
68
+ const profileDeps = (opts, deps) => ({
69
+ ...deps,
70
+ installProfile: (profile) => installThroughDaemon(profile, {
71
+ host: deps.host,
72
+ daemonOff: noDaemon(opts),
73
+ from: 'account',
74
+ }),
75
+ });
76
+ // A token is the headless credential: no browser and no callback, so --reauth has nothing to do.
77
+ const signIn = async (opts, deps) => {
78
+ if (!rawPatToken())
79
+ return void (await deps.ensureSignedIn({ reauth: opts.reauth, browser: opts.browser }));
80
+ if (opts.reauth)
81
+ console.error('--reauth does nothing: AGENTAGE_TOKEN is set and is the credential');
82
+ };
83
+ const setupFlow = async (opts, deps) => {
53
84
  if (opts.disconnect)
54
85
  return disconnect(deps);
55
86
  const file = opts.profile === undefined ? null : fileSource(opts.profile);
56
87
  if (opts.check || opts.dryRun)
57
- return readOnly(file ?? localSource(), opts);
88
+ return readOnly(file ?? localSource(), opts, file !== null);
58
89
  if (file)
59
- return fromFile(file, deps);
60
- if (opts.latest)
61
- return runSetupLatest(deps);
62
- await deps.ensureSignedIn({ reauth: opts.reauth, browser: opts.browser });
90
+ return fromFile(file, opts, deps);
91
+ if (opts.latest) {
92
+ console.error('setup --latest is now: agentage extension update');
93
+ return void (await deps.updateExtensions());
94
+ }
63
95
  const token = process.env['AGENTAGE_TOKEN'];
64
- const failure = await accountSetup(deps).then(() => null, (error) => error);
96
+ await signIn(opts, deps);
97
+ const failure = await accountSetup(profileDeps(opts, deps)).then(() => null, (error) => error);
65
98
  await deps.printStatus({ token });
99
+ await startDaemon(opts, deps);
66
100
  if (failure)
67
101
  throw failure;
68
102
  };
103
+ export const runExtensionSetup = async (opts, deps) => {
104
+ await setupFlow(opts, deps);
105
+ return undefined;
106
+ };