@agentage/cli 0.50.4 → 0.51.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.
package/README.md CHANGED
@@ -2,46 +2,37 @@
2
2
 
3
3
  ![Connect this machine to agentage from the terminal](https://github.com/agentage/cli/raw/master/docs/banner.svg)
4
4
 
5
- Connect this machine to your [agentage](https://agentage.io) account from the terminal, and
6
- install the extensions your account's profile names. One command signs you in through your
7
- browser; the same profile then gives you the same extensions on every machine you set up.
5
+ The agentage CLI connects each machine you use to your agentage account, a shared place for your
6
+ AI tools. Use it from a terminal, a server or CI. It also installs extensions: npm packages that
7
+ add commands to `agentage`. You need Node.js 22 or newer.
8
8
 
9
- ## What is this?
9
+ ```bash
10
+ npm install -g @agentage/cli && agentage setup
11
+ ```
10
12
 
11
- agentage gives your AI tools a shared, account-backed home. Every machine you use is connected
12
- to that account once, by this package. It keeps your sign-in on the machine (OAuth 2.1 with
13
- PKCE, nothing typed into the terminal), tells you whether the machine is connected, and keeps
14
- itself up to date.
13
+ ## What is this?
15
14
 
16
- The CLI itself stays **small**: sign-in, status, update, and an extension manager. Everything
17
- else, memory included, arrives as an extension the CLI installs for you.
15
+ The CLI stays **small**: sign-in, status, update and an extension manager. Sign-in uses OAuth 2.1
16
+ with PKCE: you type nothing into the terminal. Everything else, memory included, arrives as an
17
+ extension.
18
18
 
19
19
  ## Get started
20
20
 
21
- Needs Node.js 22 or newer.
22
-
23
- ```bash
24
- npm install -g @agentage/cli
25
- agentage setup
26
- ```
27
-
28
- `setup` opens your browser, you sign in, and the session is stored in `~/.agentage`. Then:
29
-
30
- ```bash
31
- agentage status
32
- ```
21
+ `agentage setup` opens your browser for sign-in. Check the session with `agentage status`.
22
+ Installing and running extensions needs no sign-in. Sign-in adds your account's profile, so every
23
+ machine gets the same extensions.
33
24
 
34
25
  ### On a server or in CI (no browser)
35
26
 
27
+ `agentage setup --no-browser` prints the sign-in URL. Open it in a browser on this same machine,
28
+ because sign-in returns to `localhost`. On a server, use a personal access token from the
29
+ dashboard (**Settings -> API tokens**):
30
+
36
31
  ```bash
37
- agentage setup --no-browser # prints the sign-in URL to open elsewhere
38
- AGENTAGE_TOKEN=aga_... agentage status # or use a personal access token
32
+ AGENTAGE_TOKEN=aga_... agentage status
39
33
  ```
40
34
 
41
- ### Then
42
-
43
- - `agentage status --json` in scripts to check the machine is connected.
44
- - `agentage update` whenever a newer version is published; `status` tells you when.
35
+ More: [docs/reference.md](docs/reference.md#token-auth-ci-and-headless).
45
36
 
46
37
  ## Commands
47
38
 
@@ -53,114 +44,77 @@ AGENTAGE_TOKEN=aga_... agentage status # or use a personal access token
53
44
  | `agentage setup --disconnect` | Sign out and remove local credentials |
54
45
  | `agentage status` | Version, update, target, sign-in, endpoint, then machine, profile, extensions |
55
46
  | `agentage update` | Install the latest published version (`--check` only reports) |
47
+ | `agentage extension ...` | Manage extensions, see [Extensions](#extensions) |
56
48
 
57
- For extensions (see below):
58
-
59
- | Command | What it does |
60
- | -------------------------------------------- | ---------------------------------------------------------------- |
61
- | `agentage setup --profile <file>` | Install and load the extensions a profile file names, no sign-in |
62
- | `agentage setup --profile <file> --dry-run` | Show what would be installed, write nothing |
63
- | `agentage setup --latest` | Update each extension to the newest version its range allows |
64
- | `agentage extension install <name> [--off]` | Add an extension to the profile, install and load it |
65
- | `agentage extension remove <name> [--purge]` | Take it out of the profile and reinstall the rest |
66
- | `agentage extension list` | One row per extension: state, version, commands, last run |
67
- | `agentage extension doctor` | Load every extension once and refresh the states |
68
- | `agentage extension create <id> [part...]` | New `./extension-<id>` from the template, only the parts named |
69
- | `agentage extension check [dir] [--write]` | Check that an extension package conforms (the six kit rules) |
70
- | `agentage extension build [--push]` | Build the part images of a committed tree; push with digests |
71
- | `agentage extension release` | Release from a tag in CI: guard, images, record, npm package |
72
- | `agentage extension up` / `down` | Run an extension package on this machine with Docker, then stop |
73
- | `agentage extension token --scope <scope>` | Print a token from the dev issuer `extension up` started |
74
- | `agentage <command>` | Run a command an installed extension contributes |
75
- | `agentage <id> <command>` | The same for an extension built on the kit; always works |
76
-
77
- Flags, exit codes and token auth are in [`docs/reference.md`](docs/reference.md).
49
+ More: [author commands](docs/extensions.md#author-commands).
78
50
 
79
51
  ## Extensions
80
52
 
81
- An extension is an npm package that adds to the CLI: commands today, more later. Extensions are
82
- on by default. A machine whose profile names no extensions has none, and `setup`, `status` and
83
- `update` work as described above, with three more `status` lines: `machine`, `profile` and
84
- `extensions`.
53
+ - A **profile** lists what your account wants: extensions, version ranges, and which are off
54
+ per machine.
55
+ - `setup` installs the profile, loads each extension once and prints `ok` or why not.
56
+ - `extension install` and `remove` edit the profile, then do the same.
57
+ - Nothing installs on a timer: the machine changes only when you run a command.
58
+
59
+ ```bash
60
+ agentage extension install probe # short name for @agentage/extension-probe
61
+ agentage extension list # one row per extension
62
+ agentage probe ping # run a command by its extension id
63
+ agentage extension remove probe # take it out again
64
+ agentage extension doctor # load each once, refresh states
65
+ agentage setup --latest # newest versions the ranges allow
66
+ agentage setup --profile profile.json # install a profile file, no sign-in
67
+ ```
68
+
69
+ Extensions run in the CLI process with your privileges, so install only ones you trust. npm runs with
70
+ `--ignore-scripts`. The account token leaves the environment before extension code loads.
71
+
72
+ More: [docs/profiles.md](docs/profiles.md).
85
73
 
86
- The model is simple. A **profile** says what this account wants: which extensions, at which
87
- version ranges, and which ones are switched off on which machine. The CLI brings the machine
88
- to that state: `setup` installs what the profile names, loads each extension once and prints
89
- whether it loaded (`ok`) or why not. `extension install` and `extension remove` edit the
90
- profile and then do the same. Nothing installs itself on a timer; the state only changes when
91
- you run a command.
74
+ ### Write and run your own extension
92
75
 
93
- Once you are signed in, `setup` reads the profile your account holds, when it has one, so every
94
- machine you set up gets the same extensions, and `extension install` and `extension remove` save
95
- the change there. When your account has no profile to give, `setup` says so on one line and
96
- carries on. Each machine you run `setup` on appears in your account as one of its machines.
76
+ `create` needs git and network. `build` and `up` also need
77
+ Docker; `release` needs the `gh` CLI.
97
78
 
98
79
  ```bash
99
- agentage setup --profile ./profile.json # install and load the extensions a profile names
100
- agentage setup --profile ./profile.json --dry-run # show the plan, write nothing
101
- agentage setup --check # exit 1 when this machine differs from its profile
102
- agentage setup --latest # newest versions the ranges allow, diff printed
103
- agentage extension install @agentage/example # add one extension, install and load it
104
- agentage extension install ./my-extension # a local folder, for development
105
- agentage extension install . # link the working copy you are in
106
- agentage extension remove @agentage/example # take it out again
107
- agentage extension list # state per extension, with what setup would change
108
- agentage hello # a command the hello extension contributes
109
- agentage ping # a command of an extension built on the kit
110
- agentage probe ping # the same, by its extension id
80
+ agentage extension create example api # makes ./extension-example with the api part
81
+ cd extension-example && npm ci # installs the pinned cli
82
+ git init -q && git add -A && git commit -qm init # up needs one commit
83
+ npx agentage extension up # runs it with Docker
84
+ npx agentage extension token --scope example:read
85
+ npx agentage extension down # removes what up started
111
86
  ```
112
87
 
113
- An extension built on the extension kit lists its commands in its manifest; each runs as
114
- `agentage <command>` and always as `agentage <id> <command>`. When the name is a core command,
115
- an extension id or a command an earlier install took, only `agentage <id> <command>` runs it, and
116
- the install says so.
117
-
118
- The plan is what `setup` would change, one line per extension (`+ add`, `~ update`, `- remove`,
119
- `o off`) and a summary such as `plan: 1 to add, 0 to update, 0 to remove, 0 off, 2 unchanged`.
120
- `setup --dry-run` prints it, `setup --check` exits 1 when anything would change, `extension list`
121
- shows it per extension and `status` sums it up, for example `extensions 2 (1 to add)`.
122
-
123
- `setup --latest` moves each extension to the newest version its range allows and prints one line
124
- per change, such as `~ update @agentage/example 1.0.0 -> 1.0.1`. The new versions take over only
125
- after every extension loaded from them cleanly; until then the installed ones stay. A version
126
- that needs a newer extension API than this CLI has is skipped, here and by `extension install`.
127
-
128
- A profile is a JSON file that maps package names to version ranges. `registries` is optional
129
- and routes a scope to another npm-compatible registry; everything else comes from npm's public
130
- registry.
131
-
132
- ```json
133
- {
134
- "version": 1,
135
- "extensions": { "@agentage/example": "^1.0.0" },
136
- "registries": { "@acme": "https://npm.acme.example" }
137
- }
138
- ```
88
+ In the extension folder, use `npx agentage`: the project's pinned cli and the global one can differ.
89
+
90
+ More: [docs/extensions.md](docs/extensions.md#run-it-locally).
91
+
92
+ ## Where things live
139
93
 
140
- Extensions run in the CLI process with your privileges, so install only extensions you trust.
141
- npm runs with `--ignore-scripts`, and the account token is removed from the environment before
142
- any extension code loads. Everything lives in the config directory:
94
+ Everything lives in the config directory, `~/.agentage` by default:
143
95
 
144
- | Path | What |
145
- | --------------------------- | -------------------------------------------------------------- |
146
- | `~/.agentage/profile.json` | the profile: what this account wants |
147
- | `~/.agentage/machine.json` | this machine's id, name, development extensions and account |
148
- | `~/.agentage/extensions/` | installed extensions; `extensions/current` names the live tree |
149
- | `~/.agentage/state/` | the last run of each extension |
150
- | `~/.agentage/commands.json` | which extension holds each top-level command |
151
- | `~/.agentage/data/<id>/` | what each extension keeps |
96
+ | Path | What |
97
+ | --------------------------- | --------------------------------------------------- |
98
+ | `~/.agentage/auth.json` | your sign-in, owner-only |
99
+ | `~/.agentage/profile.json` | the profile: what this account wants |
100
+ | `~/.agentage/machine.json` | this machine's id, name, dev extensions and account |
101
+ | `~/.agentage/extensions/` | installed extensions; `current` names the live tree |
102
+ | `~/.agentage/state/` | the last run of each extension |
103
+ | `~/.agentage/commands.json` | which extension holds each top-level command |
104
+ | `~/.agentage/secrets.json` | extension secrets, owner-only |
105
+ | `~/.agentage/data/<id>/` | what each extension keeps |
152
106
 
153
- Every state an extension can be in, and every flag, is in [`docs/reference.md`](docs/reference.md).
154
- To write an extension, start with [`docs/extensions.md`](docs/extensions.md).
107
+ `status` writes `machine.json` even before you sign in.
108
+
109
+ To uninstall, run `agentage setup --disconnect`, then `npm uninstall -g @agentage/cli`, then
110
+ delete `~/.agentage`.
155
111
 
156
112
  ## How it works
157
113
 
158
- This is the **terminal client for an agentage account**. `setup` registers a one-off OAuth
159
- client, opens the authorization page in your browser and waits on a localhost callback; the
160
- tokens land in `~/.agentage/auth.json` with owner-only permissions and are refreshed
161
- automatically. `status` validates the session against the account's introspection endpoint
162
- and reports version, update, target host and connectivity. Nothing runs in the background, and
163
- nothing is installed beyond this package unless your profile names extensions.
114
+ - `setup` registers a one-off OAuth client and waits for the browser on a localhost callback.
115
+ - Tokens land in `~/.agentage/auth.json` (owner-only) and refresh automatically.
116
+ - `status` checks the session against the account's introspection endpoint.
117
+ - Nothing runs in the background.
164
118
 
165
119
  ## Configuration
166
120
 
@@ -180,16 +134,19 @@ npm run verify
180
134
  npm run build && npm run test:e2e -- --grep @offline
181
135
  ```
182
136
 
183
- The e2e specs under `e2e/core/` read as scenarios: each title names the command and what must
184
- hold. They run against a loopback registry that serves the extensions under `fixtures/`.
137
+ Each e2e title under `e2e/core/` names a command and what must hold. The tests use a loopback
138
+ npm registry that serves `fixtures/`.
185
139
 
186
140
  ## Release
187
141
 
188
- Releases publish to npm via GitHub Actions when a `chore(release): X.Y.Z` commit that touches
189
- `package.json` lands on `master` (the squash-merge subject of a release PR). The workflow skips
190
- any version already on npm.
142
+ GitHub Actions publishes to npm when a release PR merges to `master` as a `chore(release): X.Y.Z`
143
+ commit that touches `package.json`. It skips a version already on npm.
144
+
145
+ ## Documentation
191
146
 
192
- An extension release (`agentage extension release`) skips npm for a package with `"private": true`: it pushes the images, attaches the record and prints `PASS npm: private package, not published`.
147
+ - [docs/reference.md](docs/reference.md): every flag, exit code and environment variable.
148
+ - [docs/profiles.md](docs/profiles.md): profiles, extension states, the plan and updates.
149
+ - [docs/extensions.md](docs/extensions.md): write, check and run your own extension.
193
150
 
194
151
  ## License
195
152
 
@@ -86,18 +86,41 @@ const clone = async (url, from, dir) => {
86
86
  });
87
87
  rmSync(join(dir, '.git'), { recursive: true, force: true });
88
88
  };
89
+ const CI = join('.github', 'workflows', 'ci.yml');
90
+ const FLOOR = /MIN_EXECUTED: '\d+'/;
91
+ const LOWERED = " ci MIN_EXECUTED is 1: after the first green run, set it to the gate's count";
92
+ const BY_HAND = ` ci no MIN_EXECUTED line found in ${CI}: set it by hand to the gate's count`;
93
+ // The template's floor counts the gate's tests for all seven parts; a subset's count is unknown.
94
+ const lowerFloor = (dir, kept) => {
95
+ if (kept.length === PARTS.length)
96
+ return undefined;
97
+ const file = join(dir, CI);
98
+ const text = existsSync(file) ? readFileSync(file, 'utf8') : '';
99
+ if (!FLOOR.test(text))
100
+ return BY_HAND;
101
+ writeFileSync(file, text.replace(FLOOR, "MIN_EXECUTED: '1'"));
102
+ return LOWERED;
103
+ };
89
104
  // A half-made folder is removed, so a re-run is not refused as "exists".
90
105
  const shape = (dir, from, id, kept) => {
91
106
  try {
92
107
  drop(dir, kept);
93
108
  rewrite(dir, id);
94
109
  renameLock(dir, id);
110
+ return lowerFloor(dir, kept);
95
111
  }
96
112
  catch (err) {
97
113
  rmSync(dir, { recursive: true, force: true });
98
114
  throw new Error(`template ${from}: ${err.message}`);
99
115
  }
100
116
  };
117
+ const printNext = (dir, from, id, kept) => {
118
+ const kit = String(json(join(dir, 'package.json'))['dependencies']?.['@agentage/extension'] ?? '?');
119
+ console.log(` template ${from} (default branch, kit ${kit.replace(/^[\^~]/, '')})`);
120
+ console.log(` kept ${kept.join(', ')}`);
121
+ console.log(` id ${id} · host ${id}.next.agentage.io · contract ${id}.mcpc.json`);
122
+ console.log(` next cd ${dir} && npm ci && npm run build && agentage extension check`);
123
+ };
101
124
  // Clones the template's default branch into ./extension-<id> as a new working copy, no history.
102
125
  export const runExtensionCreate = async (opts, url = (from) => `https://github.com/${from}`) => {
103
126
  const { id, from = TEMPLATE } = opts;
@@ -107,12 +130,10 @@ export const runExtensionCreate = async (opts, url = (from) => `https://github.c
107
130
  throw new Error(refused);
108
131
  const dir = `extension-${id}`;
109
132
  await clone(url(from), from, dir);
110
- shape(dir, from, id, kept);
111
- const kit = String(json(join(dir, 'package.json'))['dependencies']?.['@agentage/extension'] ?? '?');
112
- console.log(` template ${from} (default branch, kit ${kit.replace(/^[\^~]/, '')})`);
113
- console.log(` kept ${kept.join(', ')}`);
114
- console.log(` id ${id} · host ${id}.next.agentage.io · contract ${id}.mcpc.json`);
115
- console.log(` next cd ${dir} && npm ci && npm run build && agentage extension check`);
133
+ const ci = shape(dir, from, id, kept);
134
+ printNext(dir, from, id, kept);
135
+ if (ci)
136
+ console.log(ci);
116
137
  };
117
138
  export const addCreate = (group, create) => group
118
139
  .command('create')
@@ -1,4 +1,5 @@
1
1
  import { type NpmManifest } from '../../core/installer/npm.js';
2
+ import { type Market } from '../../lib/net/market.js';
2
3
  import { type EditDeps } from './sync.js';
3
4
  export interface ExtensionInstallOptions {
4
5
  name: string;
@@ -6,5 +7,6 @@ export interface ExtensionInstallOptions {
6
7
  }
7
8
  export interface ExtensionInstallDeps extends EditDeps {
8
9
  manifest: () => Promise<NpmManifest>;
10
+ market?: Market;
9
11
  }
10
12
  export declare const runExtensionInstall: (opts: ExtensionInstallOptions, deps: ExtensionInstallDeps) => Promise<void>;
@@ -4,6 +4,7 @@ import { registryLookup, resolveName } from '../../core/installer/resolve.js';
4
4
  import { addExtension } from '../../core/profile/edit.js';
5
5
  import { loadMachine, setDev } from '../../core/profile/machine.js';
6
6
  import { editableProfile } from '../../core/profile/profile.js';
7
+ import {} from '../../lib/net/market.js';
7
8
  import {} from '../../core/profile/schema.js';
8
9
  import { installAndLoad, line } from './install-load.js';
9
10
  import { finishEdit, pullForEdit } from './sync.js';
@@ -27,10 +28,20 @@ const addDev = async (target, off, deps) => {
27
28
  console.log(line('dev', `${target.name} ${target.path}`));
28
29
  await installAndLoad(editableProfile(), deps.npm);
29
30
  };
31
+ const ID = /^[a-z][a-z0-9-]*$/;
32
+ // A bare id takes the version the market's /latest names; a private entry has no npm package.
33
+ const marketName = async (name, market) => {
34
+ const latest = ID.test(name) ? await market?.latest(name) : null;
35
+ if (!latest)
36
+ return name;
37
+ if (latest.package === null)
38
+ throw new Error(`${name}: private entry, no npm package; it cannot be installed from npm`);
39
+ return `${latest.package}@${latest.version}`;
40
+ };
30
41
  // Never signs in: the name is looked up in the registries the local profile routes.
31
42
  export const runExtensionInstall = async (opts, deps) => {
32
43
  const { registries } = editableProfile();
33
- const target = await resolveName(opts.name, registryLookup(deps.manifest, registries));
44
+ const target = await resolveName(await marketName(opts.name, deps.market), registryLookup(deps.manifest, registries));
34
45
  if (target.kind === 'dev')
35
46
  await addDev(target, opts.off === true, deps);
36
47
  else
@@ -5,13 +5,15 @@ import { type ExtensionCreateOptions } from './create.js';
5
5
  import { type ExtensionDoctorOptions } from './doctor.js';
6
6
  import { type ExtensionInstallOptions } from './install.js';
7
7
  import { type ExtensionRemoveOptions } from './remove.js';
8
+ import { type Latest } from './row-lines.js';
9
+ import { type Market } from '../../lib/net/market.js';
8
10
  import { type ExtensionsGather } from './rows.js';
9
11
  import { type KitActions } from './up.js';
10
12
  export interface ExtensionListOptions {
11
13
  json?: boolean;
12
14
  }
13
- export declare const printReport: ({ status, warnings }: ExtensionsGather, json?: boolean) => void;
14
- export declare const runExtensionList: (opts?: ExtensionListOptions) => Promise<void>;
15
+ export declare const printReport: ({ status, warnings }: ExtensionsGather, json?: boolean, latest?: Latest) => void;
16
+ export declare const runExtensionList: (opts?: ExtensionListOptions, market?: Market) => Promise<void>;
15
17
  export declare const helpOrUnknown: (_opts: unknown, group: Command) => void;
16
18
  export interface ExtensionActions extends KitActions, BuildActions {
17
19
  install: (opts: ExtensionInstallOptions) => Promise<void>;
@@ -6,22 +6,46 @@ import {} from './doctor.js';
6
6
  import {} from './install.js';
7
7
  import {} from './remove.js';
8
8
  import { printWarnings, rowLines } from './row-lines.js';
9
+ import {} from '../../lib/net/market.js';
9
10
  import { gatherExtensions, invalidProfileError } from './rows.js';
10
11
  import { addKitTools } from './up.js';
12
+ const withLatest = (status, latest) => ({
13
+ ...status,
14
+ extensions: status.extensions.map((row) => ({
15
+ ...row,
16
+ latest: latest.get(row.id ?? '') ?? null,
17
+ })),
18
+ });
11
19
  // The rows, or the whole report as JSON, on stdout; warnings on stderr.
12
- export const printReport = ({ status, warnings }, json) => {
13
- const rows = status.extensions.length > 0 ? rowLines(status.extensions) : ['no extensions'];
20
+ export const printReport = ({ status, warnings }, json, latest) => {
21
+ const rows = status.extensions.length > 0 ? rowLines(status.extensions, latest) : ['no extensions'];
14
22
  if (json)
15
- console.log(JSON.stringify(status, null, 2));
23
+ console.log(JSON.stringify(latest ? withLatest(status, latest) : status, null, 2));
16
24
  else
17
25
  for (const text of rows)
18
26
  console.log(text);
19
27
  printWarnings(warnings);
20
28
  };
29
+ // A refused answer costs only its own row: one stderr line, no version.
30
+ const versionOf = async (market, id) => {
31
+ try {
32
+ return (await market.latest(id))?.version ?? null;
33
+ }
34
+ catch (err) {
35
+ console.error(err.message);
36
+ return null;
37
+ }
38
+ };
39
+ // The market's newest version for each installed id it knows; unknown or refused ids are null.
40
+ const newest = async ({ status }, market) => {
41
+ const ids = status.extensions.flatMap((row) => (row.id === null ? [] : [row.id]));
42
+ const found = await Promise.all(ids.map(async (id) => [id, await versionOf(market, id)]));
43
+ return market.down() ? undefined : new Map(found);
44
+ };
21
45
  // The rows always print; an invalid profile.json then fails the step (exit 1).
22
- export const runExtensionList = async (opts = {}) => {
46
+ export const runExtensionList = async (opts = {}, market) => {
23
47
  const gathered = await gatherExtensions();
24
- printReport(gathered, opts.json);
48
+ printReport(gathered, opts.json, market && (await newest(gathered, market)));
25
49
  const failure = invalidProfileError(gathered.status.profile);
26
50
  if (failure)
27
51
  throw failure;
@@ -32,8 +56,9 @@ dev extension: kept in machine.json by its real path and loaded on this machine
32
56
  of an installed copy of the same package; http:, file:, npm: and github: are refused; an https:
33
57
  tarball URL and a package name are used as written (a name without @<range> is pinned to ^ its
34
58
  newest version whose engines.agentage fits this CLI's extension API, or the kit's version for a
35
- package built on the extension kit, naming each newer version it skipped); a short name like
36
- memory is @agentage/extension-memory, else agentage-extension-memory. A package goes into
59
+ package built on the extension kit, naming each newer version it skipped); a bare id like memory
60
+ asks the market first and takes its latest version (a private entry has no npm package and is
61
+ refused), else it is @agentage/extension-memory, then agentage-extension-memory. A package goes into
37
62
  profile.json (created from the default profile when absent), from the registry the profile
38
63
  names for its scope; --off keeps it from loading on this machine. Then installs and loads like
39
64
  setup, and exits 1 when an extension failed. Never signs in. On a machine whose profile comes
@@ -1,4 +1,5 @@
1
1
  import { type ExtensionRow, type ExtensionsStatus } from './rows.js';
2
2
  export declare const summaryLines: (status: ExtensionsStatus) => string[];
3
- export declare const rowLines: (rows: ExtensionRow[]) => string[];
3
+ export type Latest = ReadonlyMap<string, string | null>;
4
+ export declare const rowLines: (rows: ExtensionRow[], latest?: Latest) => string[];
4
5
  export declare const printWarnings: (warnings: string[]) => void;
@@ -46,21 +46,22 @@ 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) => {
49
+ const rowLine = (row, widths, latest) => {
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 ?? '') ?? '-'}` : '';
54
55
  const commands = row.commands.length > 0 ? ` commands: ${row.commands.join(', ')}` : '';
55
56
  // A failed load quotes the extension's own message; the core's reasons print as they are.
56
57
  const reason = row.state === 'failed' ? `"${row.error}"` : row.error;
57
58
  const error = row.error === null ? '' : chalk.dim(` ${reason}`);
58
- return `${id} ${state} ${drift}${pkg}${commands}${lastRunText(row.lastRun)}${error}`;
59
+ return `${id} ${state} ${drift}${pkg}${newest}${commands}${lastRunText(row.lastRun)}${error}`;
59
60
  };
60
- export const rowLines = (rows) => {
61
+ export const rowLines = (rows, latest) => {
61
62
  const id = Math.max(0, ...rows.map((row) => (row.id ?? '?').length));
62
63
  const drift = Math.max(0, ...rows.map((row) => driftOf(row).length));
63
- return rows.map((row) => rowLine(row, { id, drift }));
64
+ return rows.map((row) => rowLine(row, { id, drift }, latest));
64
65
  };
65
66
  export const printWarnings = (warnings) => {
66
67
  for (const warning of warnings)
@@ -0,0 +1,4 @@
1
+ import { type LoadKitTool } from './kit-tool.js';
2
+ import { type Exec } from './release-guard.js';
3
+ export declare const ownProject: (id: string, dir: string) => Promise<string>;
4
+ export declare const assertOwnStack: (dir: string, exec: Exec, tool: LoadKitTool) => Promise<void>;
@@ -0,0 +1,45 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile, realpath } from 'node:fs/promises';
3
+ import { join, resolve } from 'node:path';
4
+ import {} from './kit-tool.js';
5
+ import {} from './release-guard.js';
6
+ const FORMAT = '{{.Label "com.docker.compose.project"}}\t{{.Ports}}';
7
+ const HERE = 'run agentage extension up here';
8
+ // The kit's projectName over its workingCopy (not exported from /tool): one project per real path.
9
+ export const ownProject = async (id, dir) => {
10
+ const absolute = resolve(dir);
11
+ const real = await realpath(absolute).catch(() => absolute);
12
+ return `agentage-${id}-${createHash('sha256').update(real).digest('hex').slice(0, 8)}`;
13
+ };
14
+ const rendered = async (dir) => readFile(join(dir, '.agentage', 'compose.json'), 'utf8')
15
+ .then((text) => JSON.parse(text).name)
16
+ .catch(() => undefined);
17
+ // As the kit's down decides: this path's project, or the legacy one only when compose.json names it.
18
+ const accepts = async (dir, id, holder) => {
19
+ if (holder === (await ownProject(id, dir)))
20
+ return true;
21
+ return holder === `agentage-${id}` && (await rendered(dir)) === holder;
22
+ };
23
+ // The live signal: the row of the container that publishes the dev issuer's port, if any.
24
+ const issuerRow = async (exec) => {
25
+ const ran = await exec('docker', ['ps', '--format', FORMAT]);
26
+ if (!ran.ok)
27
+ throw new Error(`cannot ask docker which stack is up: ${ran.err}`);
28
+ return ran.out.split('\n').find((line) => line.includes(':4281->'));
29
+ };
30
+ const named = (project) => {
31
+ const id = /^agentage-([a-z][a-z0-9-]*)-[0-9a-f]{8}$/.exec(project)?.[1];
32
+ return id ? `extension ${id} (${project})` : `compose project ${project}`;
33
+ };
34
+ // A dev token only from the stack `up` started in this folder, never from another one.
35
+ export const assertOwnStack = async (dir, exec, tool) => {
36
+ const row = await issuerRow(exec);
37
+ if (row === undefined)
38
+ throw new Error(`no stack is up on localhost:4281: ${HERE}`);
39
+ const holder = row.split('\t')[0] ?? '';
40
+ if (!holder)
41
+ throw new Error(`localhost:4281 is held by a container that is not from compose: stop it, then ${HERE}`);
42
+ const { id } = (await (await tool()).readManifest(dir)).agentage;
43
+ if (!(await accepts(dir, id, holder)))
44
+ throw new Error(`the stack up is ${named(holder)}, not this folder: ${HERE}`);
45
+ };
@@ -1,18 +1,19 @@
1
1
  import { type Command } from 'commander';
2
2
  import { type LoadKitTool } from './kit-tool.js';
3
+ import { type Exec } from './release-guard.js';
3
4
  export interface ExtensionUpOptions {
4
5
  dir?: string;
5
6
  }
6
7
  export interface ExtensionDownOptions extends ExtensionUpOptions {
7
8
  keepData?: boolean;
8
9
  }
9
- export interface ExtensionTokenOptions {
10
+ export interface ExtensionTokenOptions extends ExtensionUpOptions {
10
11
  scope: string;
11
12
  issuer?: string;
12
13
  }
13
14
  export declare const runExtensionUp: (opts?: ExtensionUpOptions, tool?: LoadKitTool) => Promise<void>;
14
15
  export declare const runExtensionDown: (opts?: ExtensionDownOptions, tool?: LoadKitTool) => Promise<void>;
15
- export declare const runExtensionToken: (opts: ExtensionTokenOptions, tool?: LoadKitTool) => Promise<void>;
16
+ export declare const runExtensionToken: ({ dir, ...opts }: ExtensionTokenOptions, tool?: LoadKitTool, exec?: Exec) => Promise<void>;
16
17
  export declare const issuerUrl: (value: string) => string;
17
18
  export interface KitActions {
18
19
  up: (opts: ExtensionUpOptions) => Promise<void>;
@@ -1,5 +1,7 @@
1
1
  import { InvalidArgumentError } from 'commander';
2
2
  import { loadKitTool } from './kit-tool.js';
3
+ import { execIn } from './release-guard.js';
4
+ import { assertOwnStack } from './stack-owner.js';
3
5
  const print = (line) => console.log(line);
4
6
  // Each step's line as the kit reports it, the ready line last.
5
7
  export const runExtensionUp = async (opts = {}, tool = loadKitTool) => {
@@ -11,7 +13,9 @@ export const runExtensionDown = async (opts = {}, tool = loadKitTool) => {
11
13
  await down({ ...opts, onLine: print });
12
14
  };
13
15
  // The token alone on stdout, so a script can take it as it is.
14
- export const runExtensionToken = async (opts, tool = loadKitTool) => {
16
+ export const runExtensionToken = async ({ dir = '.', ...opts }, tool = loadKitTool, exec = execIn('.', 10)) => {
17
+ if (!opts.issuer)
18
+ await assertOwnStack(dir, exec, tool);
15
19
  const { token } = await tool();
16
20
  console.log(await token(opts));
17
21
  };
@@ -41,9 +45,10 @@ Removes what agentage extension up started for the package in --dir, and nothing
41
45
  containers, network and the store's volume; --keep-data keeps the volume. The line it prints
42
46
  names the compose project it removed. Exits 1 when that fails.`;
43
47
  const TOKEN_HELP = `
44
- Prints a token from the dev issuer agentage extension up started, alone on stdout, for calling
45
- /api/v1/ and /mcp by hand or from tests. Only up trusts it. Exits 1 when the issuer refuses or
46
- does not answer within 5 s.`;
48
+ Prints a token from the dev issuer agentage extension up started for the package in --dir,
49
+ alone on stdout, for calling /api/v1/ and /mcp by hand or from tests. Only up trusts it. Exits 1
50
+ when the stack on localhost:4281 is not this package's (it names the one that is), or when the
51
+ issuer refuses or does not answer within 5 s. --issuer asks that issuer and skips the check.`;
47
52
  const DIR = '--dir <path>';
48
53
  const DIR_TEXT = 'the extension package folder (default: the current folder)';
49
54
  const addUp = (group, up) => {
@@ -68,6 +73,7 @@ const addToken = (group, token) => {
68
73
  .command('token')
69
74
  .description('Print a token from the dev issuer extension up started')
70
75
  .requiredOption('--scope <scope>', 'the scope the token carries, e.g. probe:write')
76
+ .option(DIR, DIR_TEXT)
71
77
  .option('--issuer <url>', 'the dev issuer (default: http://localhost:4281)', issuerUrl)
72
78
  .addHelpText('after', TOKEN_HELP)
73
79
  .action(token);
@@ -1,7 +1,7 @@
1
1
  import chalk from 'chalk';
2
2
  import {} from 'commander';
3
3
  import { resolveAuth } from '../../lib/auth/credentials.js';
4
- import { siteFqdn } from '../../lib/net/origins.js';
4
+ import { DEFAULT_FQDN, siteFqdn } from '../../lib/net/origins.js';
5
5
  import { gatherStatus } from '../../lib/status/status-info.js';
6
6
  import { INSTALL_HINT } from '../../lib/update/update-check.js';
7
7
  import { signedInAccount } from '../extension/account.js';
@@ -44,7 +44,9 @@ export const printStatus = (report) => {
44
44
  row('update', updateLine(report.update));
45
45
  const t = report.target;
46
46
  const targetSuffix = t.reachable ? '' : ' - unreachable';
47
- row('target', `${mark(t.reachable)} ${t.fqdn} (${t.env})${targetSuffix}`);
47
+ // "production" is the default site only: any other production-shaped fqdn came from the override.
48
+ const source = t.env === 'production' && t.fqdn !== DEFAULT_FQDN ? 'from AGENTAGE_SITE_FQDN' : t.env;
49
+ row('target', `${mark(t.reachable)} ${t.fqdn} (${source})${targetSuffix}`);
48
50
  row('auth', authLine(report.auth));
49
51
  row('endpoint', `${mark(report.endpoint.reachable)} ${report.endpoint.url} ` +
50
52
  (report.endpoint.reachable ? 'reachable' : 'unreachable'));
@@ -74,10 +74,12 @@ const tokenFor = async (auth, links, renew, opts) => {
74
74
  // A discovered platform takes only a JWT PAT the session mints; an env PAT goes as is.
75
75
  export const platformFetch = async (auth, links, found, path, init, opts) => {
76
76
  const url = `${found.platform.machines}${path}`;
77
- if (!found.discovered || auth.kind === 'pat')
77
+ if (!found.discovered)
78
78
  return authedFetch(auth, links, url, init, opts);
79
79
  if (found.links.auth !== links.auth)
80
80
  throw refuse(links.auth, `platform token: the site's issuer is ${found.links.auth}`);
81
+ if (auth.kind === 'pat')
82
+ return authedFetch(auth, links, url, init, opts);
81
83
  const prior = refused.get(links.auth);
82
84
  if (prior)
83
85
  throw prior;
@@ -0,0 +1,11 @@
1
+ type Get = (url: string) => Promise<Response>;
2
+ export interface Latest {
3
+ version: string;
4
+ package: string | null;
5
+ }
6
+ export interface Market {
7
+ latest: (id: string) => Promise<Latest | null>;
8
+ down: () => boolean;
9
+ }
10
+ export declare const openMarket: (fqdn?: string, get?: Get) => Market;
11
+ export {};
@@ -0,0 +1,56 @@
1
+ import { isRecord } from '../fs/json-file.js';
2
+ import { cliFetch } from './fetch.js';
3
+ import { links, siteFqdn } from './origins.js';
4
+ const TIMEOUT_MS = 5_000;
5
+ const UNAVAILABLE = 'market unavailable, versions not checked';
6
+ const EXACT = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/;
7
+ const timed = (url) => cliFetch(url, {}, { timeoutMs: TIMEOUT_MS });
8
+ const json = async (get, url) => {
9
+ const res = await get(url);
10
+ if (res.status === 404)
11
+ return null;
12
+ if (!res.ok)
13
+ throw new Error(`${url} answered ${res.status}`);
14
+ const body = await res.json();
15
+ return isRecord(body) ? body : null;
16
+ };
17
+ // The first market the site's discovery document names: https, or http when the site is local.
18
+ const marketUrl = async (fqdn, get) => {
19
+ const { site } = links(fqdn);
20
+ const doc = await json(get, `${site}/.well-known/agentage.json`);
21
+ const first = Array.isArray(doc?.['markets']) ? doc['markets'][0] : undefined;
22
+ const url = new URL(String(first));
23
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && site.startsWith('http:')))
24
+ throw new Error('no market');
25
+ return url.origin;
26
+ };
27
+ // An answer is trusted only when it names this id's own package and one exact version.
28
+ const accept = (id, { version, package: pkg }) => {
29
+ const refuse = (why) => new Error(`market answer refused for ${id}: ${why}`);
30
+ if (typeof version !== 'string' || !EXACT.test(version))
31
+ throw refuse(`version ${JSON.stringify(version)} is not an exact version`);
32
+ if (pkg !== null && pkg !== `@agentage/extension-${id}` && pkg !== `agentage-extension-${id}`)
33
+ throw refuse(`package ${JSON.stringify(pkg)} is not an extension of that id`);
34
+ return { version, package: pkg };
35
+ };
36
+ // Never throws: a missing or silent market prints one line on stderr and answers null.
37
+ export const openMarket = (fqdn = siteFqdn(), get = timed) => {
38
+ let base;
39
+ let told = false;
40
+ const latest = async (id) => {
41
+ let data;
42
+ try {
43
+ base ??= marketUrl(fqdn, get);
44
+ const path = `/api/v1/extensions/${encodeURIComponent(id)}/latest`;
45
+ data = (await json(get, `${await base}${path}`))?.['data'];
46
+ }
47
+ catch {
48
+ if (!told)
49
+ console.error(UNAVAILABLE);
50
+ told = true;
51
+ return null;
52
+ }
53
+ return isRecord(data) ? accept(id, data) : null;
54
+ };
55
+ return { latest, down: () => told };
56
+ };
@@ -4,6 +4,7 @@ export interface Links {
4
4
  api: string;
5
5
  auth: string;
6
6
  }
7
+ export declare const DEFAULT_FQDN = "agentage.io";
7
8
  export declare const normalizeFqdn: (raw?: string) => string;
8
9
  export declare const siteFqdn: () => string;
9
10
  export declare const environment: (fqdn: string) => Env;
@@ -1,4 +1,4 @@
1
- const DEFAULT_FQDN = 'agentage.io';
1
+ export const DEFAULT_FQDN = 'agentage.io';
2
2
  export const normalizeFqdn = (raw) => {
3
3
  const value = (raw ?? '')
4
4
  .trim()
package/dist/program.js CHANGED
@@ -5,6 +5,7 @@ import { runExtensionBuild, runExtensionCheck, } from './commands/extension/buil
5
5
  import { runExtensionCreate } from './commands/extension/create.js';
6
6
  import { registerDelegates } from './commands/extension/delegate.js';
7
7
  import { runExtensionDoctor } from './commands/extension/doctor.js';
8
+ import { openMarket } from './lib/net/market.js';
8
9
  import { runExtensionInstall } from './commands/extension/install.js';
9
10
  import { registerExtension, runExtensionList, } from './commands/extension/list.js';
10
11
  import { runExtensionRemove, terminalIo, } from './commands/extension/remove.js';
@@ -31,9 +32,13 @@ const defaultDeps = {
31
32
  setup: (opts) => runExtensionSetup(opts, { ...setupDeps, ...editDeps }),
32
33
  status: (opts) => runStatus(opts),
33
34
  update: (opts) => runUpdate(opts),
34
- extensionInstall: (opts) => runExtensionInstall(opts, { ...editDeps, manifest: () => prepareManifest() }),
35
+ extensionInstall: (opts) => runExtensionInstall(opts, {
36
+ ...editDeps,
37
+ manifest: () => prepareManifest(),
38
+ market: openMarket(),
39
+ }),
35
40
  extensionRemove: (opts) => runExtensionRemove(opts, { ...editDeps, io: terminalIo() }),
36
- extensionList: (opts) => runExtensionList(opts),
41
+ extensionList: (opts) => runExtensionList(opts, openMarket()),
37
42
  extensionDoctor: (opts) => runExtensionDoctor(opts),
38
43
  extensionCreate: (opts) => runExtensionCreate(opts),
39
44
  extensionCheck: (opts) => runExtensionCheck(opts),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentage/cli",
3
- "version": "0.50.4",
3
+ "version": "0.51.1",
4
4
  "description": "The agentage CLI - connect this machine to agentage from the terminal",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -55,7 +55,7 @@
55
55
  "prepublishOnly": "npm run verify"
56
56
  },
57
57
  "dependencies": {
58
- "@agentage/extension": "^0.12.1",
58
+ "@agentage/extension": "^0.12.3",
59
59
  "chalk": "^6.0.0",
60
60
  "commander": "^15.0.0",
61
61
  "open": "^11.0.0"