@agentage/cli 0.53.0 → 0.55.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 (45) hide show
  1. package/README.md +9 -11
  2. package/dist/commands/daemon/daemon.d.ts +3 -3
  3. package/dist/commands/daemon/daemon.js +21 -8
  4. package/dist/commands/daemon/installer.js +4 -7
  5. package/dist/commands/extension/build.js +5 -3
  6. package/dist/commands/extension/configure.js +2 -1
  7. package/dist/commands/extension/create-install.js +3 -2
  8. package/dist/commands/extension/install-once.d.ts +2 -0
  9. package/dist/commands/extension/install-once.js +5 -5
  10. package/dist/commands/extension/kit-tool.d.ts +1 -1
  11. package/dist/commands/extension/lifecycle.d.ts +0 -2
  12. package/dist/commands/extension/lifecycle.js +4 -4
  13. package/dist/commands/extension/package-build.d.ts +10 -0
  14. package/dist/commands/extension/package-build.js +28 -9
  15. package/dist/commands/extension/release-guard.d.ts +8 -1
  16. package/dist/commands/extension/release-guard.js +39 -16
  17. package/dist/commands/extension/release.js +35 -19
  18. package/dist/commands/extension/setup-install.js +2 -4
  19. package/dist/commands/extension/up-app.d.ts +9 -0
  20. package/dist/commands/extension/up-app.js +59 -0
  21. package/dist/commands/extension/up-build.d.ts +0 -1
  22. package/dist/commands/extension/up-build.js +3 -9
  23. package/dist/commands/extension/up-local.d.ts +3 -0
  24. package/dist/commands/extension/up-local.js +30 -11
  25. package/dist/commands/extension/up-reload.d.ts +9 -1
  26. package/dist/commands/extension/up-reload.js +58 -17
  27. package/dist/commands/extension/up-run.d.ts +2 -0
  28. package/dist/commands/extension/up-run.js +80 -38
  29. package/dist/commands/extension/up-watch.d.ts +2 -2
  30. package/dist/commands/extension/up-watch.js +21 -11
  31. package/dist/commands/extension/up.js +6 -4
  32. package/dist/commands/status/status-daemon.d.ts +12 -0
  33. package/dist/commands/status/status-daemon.js +22 -0
  34. package/dist/commands/status/status.d.ts +2 -0
  35. package/dist/commands/status/status.js +18 -4
  36. package/dist/core/loader/manifest.js +1 -2
  37. package/dist/lib/daemon/daemon-client.js +3 -6
  38. package/dist/lib/daemon/daemon-probe.d.ts +1 -0
  39. package/dist/lib/daemon/daemon-probe.js +7 -2
  40. package/dist/lib/daemon/host-client.d.ts +8 -5
  41. package/dist/lib/daemon/host-client.js +19 -16
  42. package/dist/lib/fs/file-lock.js +6 -0
  43. package/dist/lib/proc/start-time.d.ts +2 -2
  44. package/dist/lib/proc/start-time.js +12 -10
  45. package/package.json +7 -3
package/README.md CHANGED
@@ -75,16 +75,14 @@ More: [docs/profiles.md](docs/profiles.md).
75
75
 
76
76
  ### Write and run your own extension
77
77
 
78
- `create` needs git and network. `build` and `up` also need
79
- Docker; `release` needs the `gh` CLI.
78
+ `create` needs git and network. `build --container`, `up --docker` and `release` also need
79
+ Docker and a committed tree; `release` needs the `gh` CLI.
80
80
 
81
81
  ```bash
82
82
  agentage extension create example api # makes ./extension-example with the api part
83
83
  cd extension-example && npm ci # installs the pinned cli
84
- git init -q && git add -A && git commit -qm init # up needs one commit
85
- npx agentage extension up # runs it with Docker
86
- npx agentage extension token --scope example:read # prints a dev token with that scope
87
- npx agentage extension down # removes what up started
84
+ npx agentage extension up # runs it on the daemon, reloads each saved change
85
+ npx agentage extension down # removes the row up added (its data stays)
88
86
  ```
89
87
 
90
88
  In the extension folder, use `npx agentage`: the project's pinned cli and the global one can differ.
@@ -147,11 +145,11 @@ commit that touches `package.json`. It skips a version already on npm.
147
145
  - The publish worked but the tag push failed: push the tag by hand on the release commit
148
146
  (`git tag v0.52.0 <release commit> && git push origin v0.52.0`); never publish again.
149
147
  - The agentage/e2e cli tier (`e2e.yml` on a PR) is not a required check; `release.yml` runs only
150
- its `@smoke` tests before the publish. No workflow runs its lifecycle tests
151
- (`AGENTAGE_CLI_LIFECYCLE=1`).
152
- - Before the release PR merges, check: the PR checks of the release commit are green, and the
153
- lifecycle tests of agentage/e2e pass 17 of 17 against the packed tarball of that commit
154
- (`AGENTAGE_CLI_TARBALL=<tgz> AGENTAGE_CLI_LIFECYCLE=1 npm run e2e -- cli p0 local`).
148
+ its `@smoke` tests before the publish. No workflow of this repo runs its lifecycle, execution
149
+ and reload tests on a candidate; agentage/e2e runs them on its own PRs against the published cli.
150
+ - Before the release PR merges, check: the PR checks of the release commit are green, and the cli
151
+ project of agentage/e2e passes 48 of 48 against the packed tarball of that commit
152
+ (`AGENTAGE_CLI_TARBALL=<tgz> npm run test:cli -- --retries=0`).
155
153
 
156
154
  ## Documentation
157
155
 
@@ -1,5 +1,5 @@
1
1
  import { type Command } from 'commander';
2
- import { type Health } from '../../lib/daemon/daemon-probe.js';
2
+ import { type Health, type Probe } from '../../lib/daemon/daemon-probe.js';
3
3
  import { type HealthMarks } from '../../lib/daemon/daemon-health.js';
4
4
  import { type StopResult } from '../../lib/daemon/daemon-stop.js';
5
5
  import { type MoveReport } from './move.js';
@@ -20,11 +20,11 @@ export type DaemonStatus = ({
20
20
  } & Health & HealthMarks)) & {
21
21
  move?: MoveReport | null;
22
22
  };
23
- export declare const runDaemonStatus: (look?: (port: number, tries?: number, timeoutMs?: number) => Promise<import("../../lib/daemon/daemon-probe.js").Probe>) => Promise<DaemonStatus>;
23
+ export declare const runDaemonStatus: (look?: (port: number, tries?: number, timeoutMs?: number) => Promise<Probe>) => Promise<DaemonStatus>;
24
24
  export declare const runDaemonStop: (stop?: () => Promise<StopResult>) => Promise<{
25
25
  stopped: boolean;
26
26
  }>;
27
- export declare const settled: (port: number, look?: (port: number, tries?: number, timeoutMs?: number) => Promise<import("../../lib/daemon/daemon-probe.js").Probe>, timeoutMs?: number) => Promise<string[]>;
27
+ export declare const settled: (port: number, look?: (port: number, tries?: number, timeoutMs?: number) => Promise<Probe>, timeoutMs?: number) => Promise<string[]>;
28
28
  export declare const runDaemonRestart: (ensure?: () => Promise<number>, settle?: (port: number) => Promise<string[]>) => Promise<{
29
29
  port: number;
30
30
  settled: boolean;
@@ -1,7 +1,7 @@
1
1
  import {} from 'commander';
2
2
  import { ensureDaemon } from '../../lib/daemon/daemon-client.js';
3
3
  import { isAlive, readDaemonFile } from '../../lib/daemon/daemon-file.js';
4
- import { PROGRESS_MS, probeRetry, proven } from '../../lib/daemon/daemon-probe.js';
4
+ import { PROGRESS_MS, probeRetry, proven, } from '../../lib/daemon/daemon-probe.js';
5
5
  import { waitFor } from '../../lib/wait.js';
6
6
  import { degradedReasons, healthLines, withSealError, } from '../../lib/daemon/daemon-health.js';
7
7
  import { stopDaemon } from '../../lib/daemon/daemon-stop.js';
@@ -17,8 +17,7 @@ const report = (file, found) => {
17
17
  console.log(line);
18
18
  return { running: true, port: file.port, ...live, ...(reasons.length > 0 && { reasons }) };
19
19
  };
20
- // Reads only: a stale daemon.json is left for the next start or stop to remove.
21
- // The D6 move's warning or skipped entries, until the user fixes them.
20
+ // The D6 move's warning or skipped entries; reads only, a stale daemon.json stays.
22
21
  const moveLines = () => {
23
22
  const move = readMoveReport();
24
23
  if (move?.warning)
@@ -31,16 +30,31 @@ export const runDaemonStatus = async (look = probeRetry) => {
31
30
  const status = await daemonStatus(look);
32
31
  return { ...status, ...moveLines() };
33
32
  };
33
+ // The probe is bounded (3 tries, 2 s each); a wait past 3 s says so on stderr.
34
+ const asked = async (file, look) => {
35
+ const slow = setTimeout(() => console.error(`waiting for the daemon (pid ${file.pid}) on 127.0.0.1:${file.port}...`), PROGRESS_MS);
36
+ try {
37
+ return await look(file.port);
38
+ }
39
+ finally {
40
+ clearTimeout(slow);
41
+ }
42
+ };
43
+ const silentLine = ({ pid, port }) => `daemon: pid ${pid} does not answer on 127.0.0.1:${port} (3 tries, 2 s each); ` +
44
+ 'try again, or agentage daemon restart';
45
+ const notRunning = (file, found) => file && found?.kind === 'foreign'
46
+ ? `daemon: not running (pid ${file.pid} of daemon.json lives, but 127.0.0.1:${file.port} answers as another program)`
47
+ : 'daemon: not running';
34
48
  const daemonStatus = async (look) => {
35
49
  const file = readDaemonFile();
36
- const found = file && isAlive(file.pid) ? await look(file.port) : null;
50
+ const found = file && isAlive(file.pid) ? await asked(file, look) : null;
37
51
  if (file && found?.kind === 'silent') {
38
- console.log(`daemon: pid ${file.pid} does not answer on 127.0.0.1:${file.port}`);
52
+ console.log(silentLine(file));
39
53
  return { running: false, unresponsive: true, pid: file.pid, port: file.port };
40
54
  }
41
55
  const live = file && found ? proven(file, found) : null;
42
56
  if (!file || !live)
43
- return (console.log('daemon: not running'), { running: false });
57
+ return (console.log(notRunning(file, found)), { running: false });
44
58
  return report(file, live);
45
59
  };
46
60
  const STOPPED = (result) => {
@@ -56,8 +70,7 @@ export const runDaemonStop = async (stop = () => stopDaemon()) => {
56
70
  return { stopped: result !== null && 'stopped' in result };
57
71
  };
58
72
  const SETTLE_MS = 60_000;
59
- // Row 4 of S1.1.2: after a restart the extensions answer; a child still `starting` is waited for.
60
- // Gives the ids still starting when the wait ran out ([] once none is).
73
+ // Row 4 of S1.1.2: the ids still `starting` when the wait ran out ([] once none is).
61
74
  export const settled = async (port, look = probeRetry, timeoutMs = SETTLE_MS) => {
62
75
  let starting = [];
63
76
  const none = async () => {
@@ -15,8 +15,7 @@ import { siteFqdn } from '../../lib/net/origins.js';
15
15
  export const installError = (code, status, message) => Object.assign(new Error(message), { code, status });
16
16
  // The market's own reason, in the daemon's case (market_failed is MARKET_FAILED).
17
17
  const marketDown = (id, why) => installError(why.code.toUpperCase(), 502, `${id}: ${why.message}`);
18
- // With a market only the scoped name (anyone can publish the unscoped one); on a site with no
19
- // market the name id was installed under, else both names, as cli 0.51.1.
18
+ // A market: the scoped name only (anyone can publish the other); no market: as cli 0.51.1.
20
19
  const npmName = (id, down) => noSiteMarket(down) ? (installedName(id) ?? id) : `@agentage/extension-${id}`;
21
20
  // The market names the package and its newest version; without it npm alone decides.
22
21
  const inputOf = async (id, version, market) => {
@@ -60,7 +59,7 @@ const tagged = async (input, registry) => {
60
59
  }
61
60
  return null;
62
61
  };
63
- // The one exact version npm has for the input: a range, a version, a dist-tag, or the newest that fits.
62
+ // The one exact version npm has for a range, a version, a dist-tag, or the newest that fits.
64
63
  const exact = async (input, registry) => {
65
64
  if (distTagOf(input)) {
66
65
  const found = await tagged(input, registry);
@@ -94,8 +93,7 @@ const fetched = async (id, found, deps) => {
94
93
  throw installError('INSTALL_FAILED', 502, messageOf(err));
95
94
  });
96
95
  };
97
- // The daemon's installer: a version on disk (its own tree or the 0.51 one) needs no network;
98
- // otherwise the market, then npm into one folder per version (idempotent).
96
+ // A version on disk needs no network; else the market, then npm into one folder per version.
99
97
  export const cliInstaller = (deps) => async ({ id, version }) => {
100
98
  if (version !== undefined && !isVersionSpec(version))
101
99
  throw installError('VALIDATION_ERROR', 400, `${id}@${version}: not a version, range or dist-tag`);
@@ -108,7 +106,6 @@ export const cliInstaller = (deps) => async ({ id, version }) => {
108
106
  checkId(dir, id);
109
107
  return { id, version: found.version, dir };
110
108
  };
111
- // The newest version npm has that this cli can run, of the name id was installed under (update
112
- // on a site with no market); never another npm name for an installed row.
109
+ // No market: the newest runnable version of the npm name the row was installed under, no other.
113
110
  export const npmNewest = (manifest) => async (id) => (await exact(installedName(id) ?? id, registryLookup(manifest, editableProfile().registries)))
114
111
  .version;
@@ -3,7 +3,7 @@ import { promisify } from 'node:util';
3
3
  import {} from 'commander';
4
4
  import { addJson, CliError, omitJson } from '../../lib/json-output.js';
5
5
  import { loadKitTool } from './kit-tool.js';
6
- import { buildPackage } from './package-build.js';
6
+ import { buildPackage, newerKitLine } from './package-build.js';
7
7
  // With --json the written paths go to stderr, so stdout stays one JSON document.
8
8
  const writeContracts = async (dir, tool, json) => {
9
9
  for (const file of await (await tool()).writeContracts(dir))
@@ -19,8 +19,10 @@ export const runExtensionCheck = async ({ dir = '.', json, write } = {}, tool =
19
19
  const fail = report.conforms ? undefined : lines.pop();
20
20
  for (const line of json ? [JSON.stringify(report, null, 2)] : lines)
21
21
  console.log(line);
22
- if (!report.conforms)
23
- throw new CliError('not_conforming', fail ?? 'does not conform');
22
+ if (report.conforms)
23
+ return;
24
+ const newer = newerKitLine(dir);
25
+ throw new CliError('not_conforming', [fail ?? 'does not conform', newer].filter(Boolean).join('; '));
24
26
  };
25
27
  // The build record names HEAD, so the tree it builds must be HEAD.
26
28
  export const assertCommitted = async (dir) => {
@@ -2,7 +2,8 @@ import { join } from 'node:path';
2
2
  import { installationRows } from '../../core/loader/installed.js';
3
3
  import { isRecord, readJson } from '../../lib/fs/json-file.js';
4
4
  import { CliError, DaemonError, isJsonRun } from '../../lib/json-output.js';
5
- import { report, specOf } from './lifecycle.js';
5
+ import { specOf } from './install-spec.js';
6
+ import { report } from './lifecycle.js';
6
7
  const ENTER = ['\r', '\n', '\u0004'];
7
8
  const CTRL_C = '\u0003';
8
9
  const BACKSPACE = '\u007f';
@@ -7,7 +7,7 @@ import { CliError } from '../../lib/json-output.js';
7
7
  import { loadKitTool } from './kit-tool.js';
8
8
  import { confirmed, report, summaryOf, terminalIo } from './lifecycle.js';
9
9
  import { ignoreLocal } from './up-local.js';
10
- import { buildPackage, npmIn } from './package-build.js';
10
+ import { buildPackage, newerKitLine, npmIn } from './package-build.js';
11
11
  export const createInstallDeps = {
12
12
  npm: npmIn,
13
13
  build: (dir) => buildPackage(dir),
@@ -45,7 +45,8 @@ const conforms = async (dir, deps) => {
45
45
  return;
46
46
  for (const text of (await deps.tool()).checkLines(checked))
47
47
  console.error(`check ${text}`);
48
- throw new CliError('not_conforming', `${dir} does not conform: agentage extension check`);
48
+ const newer = newerKitLine(dir);
49
+ throw new CliError('not_conforming', newer ?? `${dir} does not conform: agentage extension check`);
49
50
  };
50
51
  // After the scaffold: npm ci, the package build, then the daemon runs the folder (POST {source});
51
52
  // --no-install leaves the scaffold as it is: no npm, no build.
@@ -14,4 +14,6 @@ export interface Installed {
14
14
  }
15
15
  export declare const addOnce: (host: HostClient, spec: IdBody) => Promise<Installed>;
16
16
  export declare const installId: (host: HostClient, spec: IdBody) => Promise<Installed>;
17
+ export declare const real: (path: string) => string;
18
+ export declare const folderRow: (host: HostClient, id: string, dir: string) => Promise<HostRow | undefined>;
17
19
  export declare const installFolder: (host: HostClient, source: string) => Promise<Installed>;
@@ -2,8 +2,7 @@ import { realpathSync } from 'node:fs';
2
2
  import { existingOf } from '../../lib/daemon/daemon-answer.js';
3
3
  import {} from '../../lib/daemon/host-client.js';
4
4
  import { CliError, DaemonError } from '../../lib/json-output.js';
5
- // The add itself is the check, so two cli runs cannot both add one id: the second gets CONFLICT,
6
- // whose details name the installed entry.
5
+ // The add is the check: of two cli runs, the second gets CONFLICT naming the installed entry.
7
6
  const added = (host, body) => host.add(body).catch((err) => {
8
7
  const existing = err instanceof DaemonError ? existingOf(err) : null;
9
8
  if (existing)
@@ -32,7 +31,7 @@ export const installId = async (host, spec) => {
32
31
  return { row: await host.change(id, { version: spec.version }), already: false };
33
32
  return got;
34
33
  };
35
- const real = (path) => {
34
+ export const real = (path) => {
36
35
  try {
37
36
  return realpathSync(path);
38
37
  }
@@ -40,8 +39,9 @@ const real = (path) => {
40
39
  return path;
41
40
  }
42
41
  };
43
- // A folder: the same folder again (by real path) is installed already; its id from elsewhere is
44
- // refused.
42
+ // The daemon's row of id when it runs this folder (by real path), else undefined.
43
+ export const folderRow = async (host, id, dir) => (await host.list()).find((row) => row.id === id && real(row.source) === real(dir));
44
+ // The same folder again (by real path) is installed already; its id from elsewhere is refused.
45
45
  export const installFolder = async (host, source) => {
46
46
  const got = await added(host, { source });
47
47
  if (!isExisting(got))
@@ -1,6 +1,6 @@
1
1
  import type * as Kit from '@agentage/extension/tool';
2
2
  import { type KitCheck } from '../../core/loader/load.js';
3
- export type KitTool = Pick<typeof Kit, 'check' | 'checkLines' | 'build' | 'buildLines' | 'runCommand' | 'checkCli' | 'up' | 'down' | 'token' | 'readManifest' | 'writeContracts'>;
3
+ export type KitTool = Pick<typeof Kit, 'check' | 'checkLines' | 'build' | 'buildLines' | 'runCommand' | 'checkCli' | 'up' | 'down' | 'token' | 'readManifest' | 'writeContracts' | 'appBuilder' | 'buildApp'>;
4
4
  export type LoadKitTool = () => Promise<KitTool>;
5
5
  export declare const loadKitTool: LoadKitTool;
6
6
  export declare const kitCheck: (tool?: LoadKitTool) => KitCheck;
@@ -1,5 +1,4 @@
1
1
  import { type HostClient, type HostSummary } from '../../lib/daemon/host-client.js';
2
- import { specOf } from './install-spec.js';
3
2
  export interface LifecycleDeps {
4
3
  host: () => Promise<HostClient>;
5
4
  }
@@ -37,4 +36,3 @@ export declare const runRemove: (opts: RemoveOptions, deps: LifecycleDeps & {
37
36
  id: string;
38
37
  purged: boolean;
39
38
  }>;
40
- export { specOf };
@@ -38,15 +38,16 @@ export const report = (done, note = '') => {
38
38
  console.log(`${done.id} ${done.version} ${done.state}${note}`);
39
39
  return summaryOf(done);
40
40
  };
41
+ // The install string is checked before the daemon starts: a bad one starts nothing.
41
42
  export const runInstall = async (opts, deps) => {
42
- const host = await deps.host();
43
- const folder = LOCAL.test(opts.name) || isAbsolute(opts.name);
43
+ const folder = LOCAL.test(opts.name) || isAbsolute(opts.name) ? folderOf(opts.name) : null;
44
44
  const spec = folder ? null : specOf(opts.name);
45
45
  if (spec && opts.name.startsWith(UNSCOPED) && (await deps.hasMarket?.(spec.id)))
46
46
  throw unscoped(opts.name);
47
+ const host = await deps.host();
47
48
  const { row: done, already } = spec
48
49
  ? await installId(host, spec)
49
- : await installFolder(host, folderOf(opts.name));
50
+ : await installFolder(host, folder ?? '');
50
51
  const bare = spec && !spec.version && !already;
51
52
  const line = bare && (await deps.fromNpm?.(spec.id, `${spec.id} ${done.version} came`));
52
53
  if (line)
@@ -115,4 +116,3 @@ export const runRemove = async (opts, deps) => {
115
116
  console.log(`removed ${id}${purge ? ', its data deleted' : ''}`);
116
117
  return { id, purged: purge };
117
118
  };
118
- export { specOf };
@@ -1,7 +1,17 @@
1
+ import { type ChildProcess } from 'node:child_process';
1
2
  import type { CheckReport } from '@agentage/extension/tool';
2
3
  import { type LoadKitTool } from './kit-tool.js';
4
+ export declare const STEP_MS = 600000;
3
5
  export type Npm = (dir: string, args: string[]) => Promise<void>;
6
+ export declare const how: (code: number | null, signal: NodeJS.Signals | null) => string;
7
+ export declare const deadline: (child: ChildProcess, timeoutMs: number, graceMs: number) => {
8
+ late: () => boolean;
9
+ stop: () => void;
10
+ };
4
11
  export declare const npmIn: (dir: string, args: string[], timeoutMs?: number, graceMs?: number, npmCli?: (opts?: import("../../lib/npm/npm-cli.js").ResolveNpmOptions) => string) => Promise<void>;
12
+ export declare const packageOf: (dir: string) => Record<string, unknown>;
13
+ export declare const buildScriptOf: (dir: string) => string | null;
14
+ export declare const newerKitLine: (dir: string, kit?: string) => string | null;
5
15
  export interface PackageBuild {
6
16
  dir: string;
7
17
  built: boolean;
@@ -2,13 +2,16 @@ import { spawn } from 'node:child_process';
2
2
  import { existsSync, readFileSync } from 'node:fs';
3
3
  import { join, resolve } from 'node:path';
4
4
  import { childEnv } from '../../lib/child-env.js';
5
+ import { isRecord, readJson } from '../../lib/fs/json-file.js';
5
6
  import { CliError, messageOf } from '../../lib/json-output.js';
6
7
  import { resolveNpmCli } from '../../lib/npm/npm-cli.js';
8
+ import { compareVersions } from '../../lib/update/update-check.js';
9
+ import { kitVersion } from '../../core/kit-version.js';
7
10
  import { loadKitTool } from './kit-tool.js';
8
- const STEP_MS = 600_000;
11
+ export const STEP_MS = 600_000;
9
12
  const GRACE_MS = 5_000;
10
13
  const failed = (what, why) => new CliError('build_failed', `${what} ${why}`);
11
- const how = (code, signal) => code === null ? `exited by signal ${signal ?? 'unknown'}` : `exited ${code}`;
14
+ export const how = (code, signal) => code === null ? `exited by signal ${signal ?? 'unknown'}` : `exited ${code}`;
12
15
  // npm runs as `node npm-cli.js`: no npm.cmd shim, which Windows cannot spawn with no shell.
13
16
  const spawnNpm = (dir, args, npmCli) => spawn(process.execPath, [npmCli(), ...args], {
14
17
  cwd: dir,
@@ -16,7 +19,8 @@ const spawnNpm = (dir, args, npmCli) => spawn(process.execPath, [npmCli(), ...ar
16
19
  stdio: ['ignore', 2, 2],
17
20
  windowsHide: true,
18
21
  });
19
- const deadline = (child, timeoutMs, graceMs) => {
22
+ // Past its time SIGTERM, then SIGKILL after the grace time.
23
+ export const deadline = (child, timeoutMs, graceMs) => {
20
24
  let late = false;
21
25
  let kill;
22
26
  const timer = setTimeout(() => {
@@ -26,7 +30,7 @@ const deadline = (child, timeoutMs, graceMs) => {
26
30
  }, timeoutMs);
27
31
  return { late: () => late, stop: () => (clearTimeout(timer), clearTimeout(kill)) };
28
32
  };
29
- // npm's output goes to stderr (a --json stdout stays one object); past its time SIGTERM, then SIGKILL.
33
+ // npm's output to stderr (a --json stdout stays one object); past its time SIGTERM, then SIGKILL.
30
34
  export const npmIn = (dir, args, timeoutMs = STEP_MS, graceMs = GRACE_MS, npmCli = resolveNpmCli) => new Promise((done, fail) => {
31
35
  const what = `npm ${args.join(' ')} in ${dir}`;
32
36
  const notStarted = (err) => fail(failed(what, `did not start: ${messageOf(err)}`));
@@ -47,17 +51,32 @@ export const npmIn = (dir, args, timeoutMs = STEP_MS, graceMs = GRACE_MS, npmCli
47
51
  fail(failed(what, clock.late() ? stopped : how(code, signal)));
48
52
  });
49
53
  });
50
- const hasBuildScript = (dir) => {
51
- if (!existsSync(join(dir, 'package.json')))
54
+ export const packageOf = (dir) => {
55
+ const file = join(dir, 'package.json');
56
+ if (!existsSync(file))
52
57
  throw new CliError('invalid_argument', `no package.json in ${dir}: run it in an extension package folder`);
53
- const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
54
- return typeof pkg.scripts?.['build'] === 'string';
58
+ const pkg = JSON.parse(readFileSync(file, 'utf8'));
59
+ return isRecord(pkg) ? pkg : {};
60
+ };
61
+ export const buildScriptOf = (dir) => {
62
+ const scripts = packageOf(dir)['scripts'];
63
+ const script = isRecord(scripts) ? scripts['build'] : undefined;
64
+ return typeof script === 'string' ? script : null;
65
+ };
66
+ // A package on a newer kit than this cli bundles fails the check for that cause only: say so.
67
+ export const newerKitLine = (dir, kit = kitVersion()) => {
68
+ const engines = readJson(join(dir, 'package.json'), isRecord)?.['engines'];
69
+ const range = isRecord(engines) ? engines['agentage'] : undefined;
70
+ const lowest = typeof range === 'string' ? /\d+\.\d+\.\d+/.exec(range)?.[0] : undefined;
71
+ if (!lowest || compareVersions(lowest, kit) <= 0)
72
+ return null;
73
+ return `this cli bundles kit ${kit}, the package needs kit ${String(range)}: update the cli (agentage update), then run it again`;
55
74
  };
56
75
  const defaultDeps = { npm: npmIn, tool: loadKitTool };
57
76
  // The author's build script, the kit's contract files, then the kit's check; no Docker.
58
77
  export const buildPackage = async (folder = '.', deps = defaultDeps) => {
59
78
  const dir = resolve(folder);
60
- const built = hasBuildScript(dir);
79
+ const built = buildScriptOf(dir) !== null;
61
80
  if (built)
62
81
  await deps.npm(dir, ['run', 'build']);
63
82
  const kit = await deps.tool();
@@ -1,4 +1,4 @@
1
- import type { BuiltImage } from '@agentage/extension/tool';
1
+ import type { BuiltImage, ExtensionPackage } from '@agentage/extension/tool';
2
2
  export type Ran = {
3
3
  ok: boolean;
4
4
  out: string;
@@ -7,8 +7,15 @@ export type Ran = {
7
7
  export type Exec = (cmd: string, args: string[], env?: NodeJS.ProcessEnv) => Promise<Ran>;
8
8
  export declare const execIn: (cwd: string, seconds?: number) => Exec;
9
9
  export declare const RECORD = "agentage-extension.json";
10
+ export declare const CONTAINER_RECORD = "agentage-container.json";
11
+ export declare const PART_SUFFIX: RegExp;
10
12
  export declare const IMAGE_PARTS: readonly BuiltImage['part'][];
13
+ export declare const imagesOf: (pkg: ExtensionPackage) => {
14
+ parts: ("api" | "worker" | "pages" | "ui" | "mcp")[];
15
+ oneImage: boolean;
16
+ };
11
17
  export type GuardInput = Record<'dir' | 'tag' | 'sha' | 'repo' | 'id' | 'version', string> & {
12
18
  parts: readonly BuiltImage['part'][];
19
+ oneImage: boolean;
13
20
  };
14
21
  export declare const releaseGuard: (g: GuardInput, exec: Exec) => Promise<"build" | "reuse">;
@@ -17,47 +17,70 @@ export const execIn = (cwd, seconds = 0) => (cmd, args, env) => new Promise((res
17
17
  child.stdin?.end();
18
18
  });
19
19
  export const RECORD = 'agentage-extension.json';
20
+ // The record of the one image (build --container --push), attached beside RECORD.
21
+ export const CONTAINER_RECORD = 'agentage-container.json';
22
+ // An id with a part suffix names the part image of another extension (market-api).
23
+ export const PART_SUFFIX = /-(pages|ui|api|mcp|worker)$/;
20
24
  export const IMAGE_PARTS = ['pages', 'ui', 'api', 'mcp', 'worker'];
25
+ const declared = (pkg, part) => (pkg.agentage.parts[part] ?? false) !== false;
26
+ // The part images, and the one image when the package has a server part for it to run.
27
+ export const imagesOf = (pkg) => ({
28
+ parts: IMAGE_PARTS.filter((part) => declared(pkg, part)),
29
+ oneImage: ['api', 'mcp', 'worker'].some((part) => declared(pkg, part)),
30
+ });
21
31
  // Only "not found" means "not released"; any other failure stops the release, never rebuilds it.
22
32
  const notFound = (ran, pattern, what) => {
23
33
  if (!pattern.test(ran.err))
24
34
  throw new Error(`cannot tell whether ${what} exists: ${ran.err}`);
25
35
  };
26
- const reuse = async ({ dir, tag, sha }, json) => {
36
+ const downloadOf = (g, name, exec) => exec('gh', ['release', 'download', g.tag, '-R', g.repo, '-p', name, '-O', '-']);
37
+ const reuse = async (g, json, exec) => {
38
+ const { dir, tag, sha } = g;
27
39
  const { commit } = JSON.parse(json);
28
40
  if (commit !== sha) {
29
41
  const moved = `${tag} was released from ${String(commit)}, not ${sha}`;
30
42
  throw new Error(`${moved}; a version's images never change: release a new version`);
31
43
  }
44
+ // The container record is uploaded first: a part record without it is a half-done release.
45
+ if (g.oneImage && !(await downloadOf(g, CONTAINER_RECORD, exec)).ok)
46
+ throw new Error(`${tag} has ${RECORD} but no ${CONTAINER_RECORD}; its one image has no record: release a new version`);
32
47
  await mkdir(join(dir, 'dist'), { recursive: true });
33
48
  await writeFile(join(dir, 'dist', RECORD), `${json.trimEnd()}\n`);
34
49
  return 'reuse';
35
50
  };
51
+ const refsOf = (g) => [
52
+ ...g.parts.map((part) => `ghcr.io/agentage/${g.id}-${part}:${g.version}`),
53
+ ...(g.oneImage ? [`ghcr.io/agentage/${g.id}:${g.version}`] : []),
54
+ ];
55
+ // GHCR answers denied for a new name too: the GitHub API tells a new package from another repo's.
56
+ const ownsName = async (g, exec) => {
57
+ const got = await exec('gh', ['api', `/orgs/agentage/packages/container/${g.id}`]);
58
+ if (!got.ok)
59
+ return notFound(got, /404|Not Found/, `the package ghcr.io/agentage/${g.id}`);
60
+ const { repository } = JSON.parse(got.out);
61
+ if (repository?.full_name !== g.repo)
62
+ throw new Error(`ghcr.io/agentage/${g.id} is denied: the name ${g.id} belongs to another package`);
63
+ };
36
64
  const ensureNoImages = async (g, exec) => {
37
- for (const part of g.parts) {
38
- const image = `ghcr.io/agentage/${g.id}-${part}:${g.version}`;
65
+ for (const image of refsOf(g)) {
39
66
  const ran = await exec('docker', ['manifest', 'inspect', image]);
40
67
  if (ran.ok)
41
68
  throw new Error(`${image} is already pushed but ${g.tag} has no record; release a new version`);
42
- // denied too: GHCR may answer it for a package that does not exist yet (a new part).
69
+ // A part may be new: GHCR can answer denied for it. Denied for the plain id (the one image)
70
+ // may be another package's name, which would fail the push after the part images.
71
+ const one = g.oneImage && image === `ghcr.io/agentage/${g.id}:${g.version}`;
72
+ if (one && /denied/.test(ran.err)) {
73
+ await ownsName(g, exec);
74
+ continue;
75
+ }
43
76
  notFound(ran, /manifest unknown|no such manifest|denied/, image);
44
77
  }
45
78
  };
46
79
  // A released version is never rebuilt: its images and record stay as first pushed.
47
80
  export const releaseGuard = async (g, exec) => {
48
- const record = await exec('gh', [
49
- 'release',
50
- 'download',
51
- g.tag,
52
- '-R',
53
- g.repo,
54
- '-p',
55
- RECORD,
56
- '-O',
57
- '-',
58
- ]);
81
+ const record = await downloadOf(g, RECORD, exec);
59
82
  if (record.ok)
60
- return reuse(g, record.out);
83
+ return reuse(g, record.out, exec);
61
84
  notFound(record, /release not found|no assets match|no assets to download/, `the ${g.tag} release record`);
62
85
  await ensureNoImages(g, exec);
63
86
  return 'build';
@@ -1,11 +1,12 @@
1
- import { mkdtemp, writeFile } from 'node:fs/promises';
1
+ import { mkdtemp, readFile, 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
5
  import { addJson, CliError } from '../../lib/json-output.js';
6
6
  import { runImageBuild } from './build.js';
7
7
  import { loadKitTool } from './kit-tool.js';
8
- import { execIn, IMAGE_PARTS, RECORD, releaseGuard } from './release-guard.js';
8
+ import { CONTAINER_RECORD, execIn, imagesOf, PART_SUFFIX, RECORD, releaseGuard, } from './release-guard.js';
9
+ import {} from './release-guard.js';
9
10
  const defaultDeps = { exec: execIn, tool: loadKitTool, env: process.env };
10
11
  const step = (line) => console.log(`PASS ${line}`);
11
12
  const fail = (line) => {
@@ -20,17 +21,31 @@ const takeSecrets = (env) => {
20
21
  return { gh: gh ? { GH_TOKEN: gh } : {}, npm: NPM_TOKEN ? { NPM_TOKEN } : {} };
21
22
  };
22
23
  const scoped = (exec, secrets) => (cmd, args) => exec(cmd, args, secrets[cmd]);
23
- const imageParts = (pkg) => IMAGE_PARTS.filter((part) => (pkg.agentage.parts[part] ?? false) !== false);
24
- // The record by digest on the tag's release; the release is created when the tag has none.
25
- const attach = async (run, tag, repo) => {
26
- const file = join('dist', RECORD);
27
- const exists = (await run('gh', ['release', 'view', tag, '-R', repo])).ok;
28
- const notes = ['--title', tag, '--notes', `Images by digest: ${RECORD}`];
29
- const args = exists ? ['upload', tag, file] : ['create', tag, file, ...notes];
30
- const ran = await run('gh', ['release', ...args, '-R', repo]);
31
- if (!ran.ok)
32
- fail(`record: ${ran.err}`);
33
- step(`record: ${RECORD} attached to release ${tag}`);
24
+ // Every image is pushed first. The records go up one call each, RECORD last: it is the "done" marker.
25
+ const attach = async (run, tag, repo, names) => {
26
+ const notes = ['--title', tag, '--notes', `Images by digest: ${names.join(', ')}`];
27
+ let exists = (await run('gh', ['release', 'view', tag, '-R', repo])).ok;
28
+ for (const name of names) {
29
+ const file = join('dist', name);
30
+ const args = exists ? ['upload', tag, file] : ['create', tag, file, ...notes];
31
+ const ran = await run('gh', ['release', ...args, '-R', repo]);
32
+ if (!ran.ok)
33
+ fail(`record: ${ran.err}`);
34
+ exists = true;
35
+ }
36
+ step(`record: ${names.join(', ')} attached to release ${tag}`);
37
+ };
38
+ // The part images (v13 rows, the estate) and the one image (app hosts), all pushed by digest.
39
+ const buildImages = async (dir, oneImage, tool) => {
40
+ await runImageBuild({ push: true, dir }, tool);
41
+ if (!oneImage)
42
+ return [RECORD];
43
+ // The second compile may clean dist/: the part record is kept and written back.
44
+ const record = await readFile(join(dir, 'dist', RECORD));
45
+ // The first build checked this HEAD; its own dist/ output must not read as a change.
46
+ await runImageBuild({ push: true, container: true, dir }, tool, async () => undefined);
47
+ await writeFile(join(dir, 'dist', RECORD), record);
48
+ return [CONTAINER_RECORD, RECORD];
34
49
  };
35
50
  // Single quotes on purpose: npm expands ${NPM_TOKEN} itself, the token never lands on disk.
36
51
  const tokenConfig = async (token) => {
@@ -87,6 +102,8 @@ const preflight = async (run, pkg, tag, sha, isPrivate) => {
87
102
  if (pkg.agentage.id === 'template')
88
103
  fail('id: this repo is the starting point for extensions: create one, release that');
89
104
  step(`id: ${pkg.agentage.id} is not the template`);
105
+ if (imagesOf(pkg).oneImage && PART_SUFFIX.test(pkg.agentage.id))
106
+ fail(`id: ${pkg.agentage.id} ends in a part name: it would name another extension's image`);
90
107
  const fetched = await run('git', ['fetch', '-q', 'origin', 'master']);
91
108
  if (!fetched.ok || !(await run('git', ['merge-base', '--is-ancestor', sha, 'origin/master'])).ok)
92
109
  fail(`master: ${sha} is not on master${fetched.err ? `: ${fetched.err}` : ''}`);
@@ -110,15 +127,14 @@ export const runExtensionRelease = async ({ dir = '.', timeout = 60 } = {}, deps
110
127
  const isPrivate = pkg['private'] === true;
111
128
  await preflight(run, pkg, tag, sha, isPrivate);
112
129
  const { id } = pkg.agentage;
113
- const g = { dir, tag, sha, repo, id, version: pkg.version, parts: imageParts(pkg) };
130
+ const { parts, oneImage } = imagesOf(pkg);
131
+ const g = { dir, tag, sha, repo, id, version: pkg.version, parts, oneImage };
114
132
  const decision = await releaseGuard(g, run).catch((e) => fail(`guard: ${e.message}`));
115
133
  const build = decision === 'build';
116
134
  const done = isPrivate ? 'is released' : 'is released: npm only';
117
135
  step(`guard: ${tag} ${build ? 'has no record and no image: build' : done}`);
118
- if (build) {
119
- await runImageBuild({ push: true, dir }, deps.tool);
120
- await attach(run, tag, repo);
121
- }
136
+ if (build)
137
+ await attach(run, tag, repo, await buildImages(dir, oneImage, deps.tool));
122
138
  if (isPrivate)
123
139
  step('npm: private package, not published');
124
140
  else
@@ -128,7 +144,7 @@ export const runExtensionRelease = async ({ dir = '.', timeout = 60 } = {}, deps
128
144
  export const addRelease = (group, release) => {
129
145
  addJson(group
130
146
  .command('release')
131
- .description('Release an extension from its v* tag in CI: guard, images, record, npm package')
147
+ .description('Release an extension from its v* tag in CI: guard, images, one image, records, npm package')
132
148
  .option('--dir <path>', 'the extension package folder (default: the current folder)')
133
149
  .option('--timeout <seconds>', 'bound on each git, GitHub and npm check (default: 60; npm publish: 300)', Number)).action(release);
134
150
  };
@@ -15,8 +15,7 @@ const installOne = async (host, entry) => {
15
15
  const { row, already } = await addOnce(host, { ...bodyOf(entry.id, entry.range), ...off });
16
16
  return already ? { ...row, already } : row;
17
17
  };
18
- // A package that is not an extension is said and skipped: the daemon cannot install it, ever.
19
- // A problem: the entry failed to install (no row) or to start (a failed row).
18
+ // A problem: no row (install failed) or a failed row; a non-extension package is only said.
20
19
  const tryOne = async (host, entry) => {
21
20
  if (entry.id === null)
22
21
  return void console.log(`${entry.name}: ${NOT_EXTENSION}`);
@@ -58,8 +57,7 @@ const tryAll = async (host, entries) => {
58
57
  }
59
58
  return problems;
60
59
  };
61
- // The profile's extensions go through the daemon, which runs them; the cli loads nothing itself.
62
- // Plain setup tries each entry once per machine, then only the ids that failed (in the marker).
60
+ // Plain setup tries each entry once per machine, then only the ids the marker names as failed.
63
61
  export const installThroughDaemon = async (profile, deps) => {
64
62
  const account = deps.from === 'account';
65
63
  const failed = account ? readMarker() : null;