@agentage/cli 0.81.2 → 0.82.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.
@@ -1,11 +1,10 @@
1
1
  import {} from '../../core/profile/cloud.js';
2
- import { authedFetch } from '../../lib/auth/api.js';
3
2
  import { resolveAuth } from '../../lib/auth/credentials.js';
4
3
  import { credentialLinks, detectEnvMismatch } from '../../lib/auth/env-match.js';
5
4
  import { introspectToken } from '../../lib/auth/introspect.js';
6
5
  import { platformFetch } from '../../lib/auth/platform-pat.js';
7
6
  import { discoverTarget } from '../../lib/net/discovery.js';
8
- import { apiOrigin, siteFqdn } from '../../lib/net/origins.js';
7
+ import { siteFqdn } from '../../lib/net/origins.js';
9
8
  const CLIENT = { 'x-client-type': 'cli' };
10
9
  // Read before any extension loads: the token is captured here, the fetch at CLI start.
11
10
  export const signedInAccount = async (opts = {}) => {
@@ -19,13 +18,11 @@ export const signedInAccount = async (opts = {}) => {
19
18
  if (derived && detectEnvMismatch(auth, fqdn, (await found()).links.auth) !== null)
20
19
  return null;
21
20
  const target = credentialLinks(auth);
22
- const to = (base) => async (path, { headers, timeoutMs, ...init } = {}) => authedFetch(auth, target, `${await base()}${path}`, { ...init, headers: { ...CLIENT, ...headers } }, { timeoutMs });
23
- const platform = async () => (await found()).platform.url;
24
- const fetch = to(() => apiOrigin(fqdn));
21
+ const platform = async () => (await found()).platform?.url ?? null;
25
22
  const machines = async (path, { headers, timeoutMs, ...init } = {}) => {
26
23
  const sent = { ...init, headers: { ...CLIENT, ...headers } };
27
24
  return platformFetch(auth, target, await found(), path, sent, { timeoutMs });
28
25
  };
29
26
  const id = () => introspectToken(auth, target).then((s) => s.userId ?? null, () => null);
30
- return { fetch, machines, platform, id };
27
+ return { machines, platform, id };
31
28
  };
@@ -0,0 +1,2 @@
1
+ export declare const BLANK = "blank";
2
+ export declare const applyBlank: (dir: string, blank: boolean | undefined) => void;
@@ -0,0 +1,36 @@
1
+ import { cpSync, existsSync, readFileSync, rmSync } from 'node:fs';
2
+ import { isAbsolute, join, relative, resolve } from 'node:path';
3
+ import { CliError } from '../../lib/json-output.js';
4
+ export const BLANK = 'blank';
5
+ const REMOVE = 'remove.json';
6
+ const inside = (dir, path) => {
7
+ const rel = relative(resolve(dir), resolve(dir, path));
8
+ return rel !== '' && !rel.startsWith('..') && !isAbsolute(path) && !isAbsolute(rel);
9
+ };
10
+ // A JSON list of template paths; an unreadable list or a path outside the folder stops the run.
11
+ const removals = (overlay) => {
12
+ const file = join(overlay, REMOVE);
13
+ if (!existsSync(file))
14
+ return [];
15
+ const list = JSON.parse(readFileSync(file, 'utf8'));
16
+ if (!Array.isArray(list) || list.some((item) => typeof item !== 'string'))
17
+ throw new Error(`${BLANK}/${REMOVE}: expected a list of paths`);
18
+ return list;
19
+ };
20
+ // Runs first: blank/ is a template overlay, never part of the extension that is made.
21
+ export const applyBlank = (dir, blank) => {
22
+ const overlay = join(dir, BLANK);
23
+ const found = existsSync(overlay);
24
+ if (blank && !found)
25
+ throw new CliError('invalid_argument', '--blank: this template has no blank variant');
26
+ if (blank) {
27
+ for (const path of removals(overlay)) {
28
+ if (!inside(dir, path))
29
+ throw new Error(`${BLANK}/${REMOVE}: ${path} is outside the template`);
30
+ rmSync(join(dir, path), { recursive: true, force: true });
31
+ }
32
+ rmSync(join(overlay, REMOVE), { force: true });
33
+ cpSync(overlay, dir, { recursive: true, force: true });
34
+ }
35
+ rmSync(overlay, { recursive: true, force: true });
36
+ };
@@ -0,0 +1,3 @@
1
+ import { type Command } from 'commander';
2
+ import { type ExtensionCreateOptions } from './create.js';
3
+ export declare const addCreate: (group: Command, create: (o: ExtensionCreateOptions) => Promise<void>) => Command;
@@ -0,0 +1,14 @@
1
+ import {} from 'commander';
2
+ import { addJson } from '../../lib/json-output.js';
3
+ import { PARTS, TEMPLATE } from './create.js';
4
+ export const addCreate = (group, create) => addJson(group
5
+ .command('create')
6
+ .description('Create ./extension-<id> from the extension template with the parts named')
7
+ .argument('<id>', 'the extension id, also its host and contract name')
8
+ .argument('[parts...]', `parts to keep (default: all eight): ${PARTS.join(', ')}`)
9
+ .option('--from <owner/repo[#branch][:folder]>', `the template repo and folder (default: ${TEMPLATE})`)
10
+ .option('--no-install', 'build the folder, but do not give it to the daemon')
11
+ .option('--blank', 'keep the parts but not the notes example (the template needs a blank/ folder)')
12
+ .option('--into <dir>', 'write <dir>/<id> for a shared repo (no repo files of its own); <dir> is its extensions folder')
13
+ .option('--yes', 'run code from another --from repo or branch without asking')
14
+ .addHelpText('after', '\nExample:\n agentage extension create my-ext app api (parts may also be app,api)')).action((id, parts, o) => create({ id, parts, ...o }));
@@ -0,0 +1 @@
1
+ export declare const lowerFloor: (dir: string, kept: string[], all: number) => string | undefined;
@@ -0,0 +1,17 @@
1
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ const CI = join('.github', 'workflows', 'ci.yml');
4
+ const FLOOR = /MIN_EXECUTED: '\d+'/;
5
+ const LOWERED = " ci MIN_EXECUTED is 1: after the first green run, set it to the gate's count";
6
+ const BY_HAND = ` ci no MIN_EXECUTED line found in ${CI}: set it by hand to the gate's count`;
7
+ // The template's floor counts the gate's tests for all eight parts; a subset's count is unknown.
8
+ export const lowerFloor = (dir, kept, all) => {
9
+ if (kept.length === all)
10
+ return undefined;
11
+ const file = join(dir, CI);
12
+ const text = existsSync(file) ? readFileSync(file, 'utf8') : '';
13
+ if (!FLOOR.test(text))
14
+ return BY_HAND;
15
+ writeFileSync(file, text.replace(FLOOR, "MIN_EXECUTED: '1'"));
16
+ return LOWERED;
17
+ };
@@ -0,0 +1,3 @@
1
+ export declare const intoRefusal: (into: string, id: string) => string;
2
+ export declare const shapeShared: (dir: string, into: string, id: string) => string | undefined;
3
+ export declare const rootEdits: (id: string) => string[];
@@ -0,0 +1,46 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ // What the template has for a repo of its own: workflows, dependabot and the repo-class files.
5
+ const OWN_REPO = ['.github', '.repo-class', '.repo-doctor.yml'];
6
+ export const intoRefusal = (into, id) => {
7
+ if (!existsSync(into) || !statSync(into).isDirectory())
8
+ return `--into ${into}: not a folder (the extensions folder of the shared repo)`;
9
+ return existsSync(join(into, id)) ? `${join(into, id)} exists: pick another id or remove it` : '';
10
+ };
11
+ const git = (dir, ...args) => {
12
+ try {
13
+ return execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8', stdio: 'pipe' }).trim();
14
+ }
15
+ catch {
16
+ return '';
17
+ }
18
+ };
19
+ // The shared repo: its GitHub owner/repo from origin, and where the folder sits in it.
20
+ const sharedRepo = (into, id) => {
21
+ const slug = /github\.com[:/]([\w.-]+\/[\w.-]+?)(?:\.git)?$/.exec(git(into, 'remote', 'get-url', 'origin'))?.[1];
22
+ return slug ? { slug, directory: `${git(into, 'rev-parse', '--show-prefix')}${id}` } : undefined;
23
+ };
24
+ // The shape of host-core, host-platform and examples: no repo files of its own, the repo points at the shared repo.
25
+ export const shapeShared = (dir, into, id) => {
26
+ for (const name of OWN_REPO)
27
+ rmSync(join(dir, name), { recursive: true, force: true });
28
+ const repo = sharedRepo(into, id);
29
+ if (!repo)
30
+ return ' package no github origin found: set repository and bugs in package.json by hand';
31
+ const file = join(dir, 'package.json');
32
+ const pkg = JSON.parse(readFileSync(file, 'utf8'));
33
+ pkg['repository'] = {
34
+ type: 'git',
35
+ url: `git+https://github.com/${repo.slug}.git`,
36
+ directory: repo.directory,
37
+ };
38
+ pkg['bugs'] = { url: `https://github.com/${repo.slug}/issues` };
39
+ writeFileSync(file, `${JSON.stringify(pkg, null, 2)}\n`);
40
+ return undefined;
41
+ };
42
+ // Root files the shared repo keeps for each extension; create never edits them.
43
+ export const rootEdits = (id) => [
44
+ ` root edit in the shared repo root: ci.yml gets "${id}" in the MIN_EXECUTED map (start at 1)`,
45
+ ` root README.md and CLAUDE.md list ${id}; agentage/e2e extensions.json needs a row for ${id}`,
46
+ ];
@@ -0,0 +1 @@
1
+ export declare const pruneLib: (dir: string) => string[];
@@ -0,0 +1,58 @@
1
+ import { existsSync, readdirSync, readFileSync, rmdirSync, rmSync } from 'node:fs';
2
+ import { dirname, join, relative, resolve } from 'node:path';
3
+ const LIB = join('src', 'lib');
4
+ const CODE = /\.(?:[cm]?[jt]sx?)$/;
5
+ const TEST = /^(.*)\.(?:test|spec)(\.[cm]?[jt]sx?)$/;
6
+ const SKIP = new Set(['node_modules', '.git', 'dist', 'coverage']);
7
+ // from '..', import '..', import('..'), require('..'), vi.mock('..')
8
+ const SPEC = /(?:\bfrom\s*|\bimport\s*\(?\s*|\brequire\s*\(\s*|\bmock\s*\(\s*)(['"])(\.{1,2}\/[^'"]*|\.{1,2})\1/g;
9
+ const walk = (dir) => readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
10
+ if (SKIP.has(entry.name))
11
+ return [];
12
+ const path = join(dir, entry.name);
13
+ return entry.isDirectory() ? walk(path) : CODE.test(entry.name) ? [path] : [];
14
+ });
15
+ // `./a.js` names a.ts, a.tsx or a/index.ts in a nodenext repo.
16
+ const target = (from, spec, files) => {
17
+ const base = resolve(dirname(from), spec);
18
+ const bare = base.replace(/\.[cm]?js$/, '');
19
+ return [base, ...['.ts', '.tsx', '.mts', '.cts'].map((ext) => bare + ext)]
20
+ .concat(['.ts', '.tsx'].map((ext) => join(base, `index${ext}`)))
21
+ .find((path) => files.has(path));
22
+ };
23
+ const importsOf = (file, files) => [...readFileSync(file, 'utf8').matchAll(SPEC)].flatMap((m) => target(file, m[2] ?? '', files) ?? []);
24
+ // Every file outside src/lib is a root; a lib test is no root, it goes with the file it tests.
25
+ const reachable = (files, lib) => {
26
+ const seen = new Set();
27
+ const todo = [...files].filter((path) => !path.startsWith(lib));
28
+ for (let path = todo.pop(); path; path = todo.pop()) {
29
+ if (seen.has(path))
30
+ continue;
31
+ seen.add(path);
32
+ todo.push(...importsOf(path, files));
33
+ }
34
+ return seen;
35
+ };
36
+ const emptyDirs = (dir) => {
37
+ for (const entry of readdirSync(dir, { withFileTypes: true }))
38
+ if (entry.isDirectory())
39
+ emptyDirs(join(dir, entry.name));
40
+ if (readdirSync(dir).length === 0)
41
+ rmdirSync(dir);
42
+ };
43
+ // Removes the src/lib files (and their tests) that no kept file imports, so no dead file lowers the coverage.
44
+ export const pruneLib = (dir) => {
45
+ const lib = `${resolve(dir, LIB)}/`;
46
+ if (!existsSync(lib))
47
+ return [];
48
+ const files = new Set(walk(resolve(dir)));
49
+ const used = reachable(files, lib);
50
+ const inLib = [...files].filter((path) => path.startsWith(lib));
51
+ const dead = inLib.filter((path) => !TEST.test(path) && !used.has(path));
52
+ const gone = new Set(dead.map((path) => path.replace(CODE, '')));
53
+ const tests = inLib.filter((path) => gone.has(TEST.exec(path)?.[1] ?? '\0'));
54
+ for (const path of [...dead, ...tests])
55
+ rmSync(path, { force: true });
56
+ emptyDirs(lib);
57
+ return [...dead, ...tests].map((path) => relative(resolve(dir), path));
58
+ };
@@ -1,6 +1,6 @@
1
1
  import { execFile } from 'node:child_process';
2
2
  import { lstatSync, mkdtempSync, readdirSync, renameSync, rmSync } from 'node:fs';
3
- import { join } from 'node:path';
3
+ import { basename, dirname, join } from 'node:path';
4
4
  import { promisify } from 'node:util';
5
5
  import { holdSignals } from '../../core/loader/dispose.js';
6
6
  const run = promisify(execFile);
@@ -55,7 +55,7 @@ const refuseLinks = (dir, from) => {
55
55
  // Removes only what this run made; also the Ctrl-C path, so it never throws.
56
56
  export const removeOwn = (path) => rmSync(path, { recursive: true, force: true });
57
57
  // A fresh name beside the new folder (a rename across disks fails), so no folder of yours is reused.
58
- const cloneFolder = (dir, folder) => folder ? mkdtempSync(`.${dir}.clone-`) : dir;
58
+ const cloneFolder = (dir, folder) => folder ? mkdtempSync(join(dirname(dir), `.${basename(dir)}.clone-`)) : dir;
59
59
  // With :folder only that folder stays; a signal during the clone removes this run's folders, then exits as it would.
60
60
  export const clone = async (url, from, dir) => {
61
61
  const { folder } = repoRef(from);
@@ -1,4 +1,3 @@
1
- import { type Command } from 'commander';
2
1
  import { installCreated } from './create-install.js';
3
2
  import { TEMPLATE } from './create-source.js';
4
3
  import { type ConfirmIo } from './lifecycle.js';
@@ -10,8 +9,9 @@ export interface ExtensionCreateOptions {
10
9
  from?: string;
11
10
  install?: boolean;
12
11
  yes?: boolean;
12
+ blank?: boolean;
13
+ into?: string;
13
14
  json?: boolean;
14
15
  }
15
16
  export declare const splitParts: (parts: string[]) => string[];
16
17
  export declare const runExtensionCreate: (opts: ExtensionCreateOptions, url?: (from: string) => string, after?: typeof installCreated, io?: ConfirmIo) => Promise<unknown>;
17
- export declare const addCreate: (group: Command, create: (o: ExtensionCreateOptions) => Promise<void>) => Command;
@@ -1,9 +1,12 @@
1
1
  import { existsSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
2
2
  import { join, resolve } from 'node:path';
3
- import {} from 'commander';
4
- import { addJson, CliError } from '../../lib/json-output.js';
3
+ import { CliError } from '../../lib/json-output.js';
5
4
  import { siteFqdn } from '../../lib/net/origins.js';
6
5
  import { installCreated, trustFrom } from './create-install.js';
6
+ import { applyBlank } from './create-blank.js';
7
+ import { pruneLib } from './create-lib.js';
8
+ import { lowerFloor } from './create-floor.js';
9
+ import { intoRefusal, rootEdits, shapeShared } from './create-into.js';
7
10
  import { markFolder } from './create-markers.js';
8
11
  import { devDropped, PRUNE, syncLockRoot } from './create-prune.js';
9
12
  import { clone, fromRefusal, repoRef, TEMPLATE } from './create-source.js';
@@ -16,7 +19,7 @@ const WORD = /(?<![A-Za-z0-9])template(?![A-Za-z0-9])/g;
16
19
  const LOCK = 'package-lock.json';
17
20
  // Parts come as separate words, comma lists or both: `app,api`, `app api`, `app, api`.
18
21
  export const splitParts = (parts) => parts.flatMap((part) => part.split(/[\s,]+/)).filter(Boolean);
19
- const refusal = ({ id, parts, from = TEMPLATE }, kept) => {
22
+ const refusal = ({ id, parts, from = TEMPLATE, into }, kept) => {
20
23
  const unknown = parts.find((part) => !PARTS.includes(part));
21
24
  if (unknown)
22
25
  return `unknown part ${unknown}: one of ${PARTS.join(', ')}`;
@@ -28,6 +31,8 @@ const refusal = ({ id, parts, from = TEMPLATE }, kept) => {
28
31
  return `an extension needs at least one of ${ROUTED.join(', ')}`;
29
32
  if (fromRefusal(from))
30
33
  return fromRefusal(from);
34
+ if (into)
35
+ return intoRefusal(into, id);
31
36
  return existsSync(`extension-${id}`)
32
37
  ? `extension-${id} exists: pick another id or remove it`
33
38
  : '';
@@ -82,32 +87,21 @@ const renameLock = (dir, id) => {
82
87
  syncLockRoot(root, json(join(dir, 'package.json'))['devDependencies'] ?? {});
83
88
  save(join(dir, LOCK), lock);
84
89
  };
85
- const CI = join('.github', 'workflows', 'ci.yml');
86
- const FLOOR = /MIN_EXECUTED: '\d+'/;
87
- const LOWERED = " ci MIN_EXECUTED is 1: after the first green run, set it to the gate's count";
88
- const BY_HAND = ` ci no MIN_EXECUTED line found in ${CI}: set it by hand to the gate's count`;
89
- // The template's floor counts the gate's tests for all eight parts; a subset's count is unknown.
90
- const lowerFloor = (dir, kept) => {
91
- if (kept.length === PARTS.length)
92
- return undefined;
93
- const file = join(dir, CI);
94
- const text = existsSync(file) ? readFileSync(file, 'utf8') : '';
95
- if (!FLOOR.test(text))
96
- return BY_HAND;
97
- writeFileSync(file, text.replace(FLOOR, "MIN_EXECUTED: '1'"));
98
- return LOWERED;
99
- };
100
90
  // A half-made folder is removed, so a re-run is not refused as "exists".
101
- const shape = (dir, from, id, kept) => {
91
+ const shape = (dir, from, id, kept, { blank, into }) => {
102
92
  try {
93
+ applyBlank(dir, blank);
103
94
  drop(dir, kept);
95
+ pruneLib(dir);
104
96
  markFolder(dir, kept, PARTS);
105
97
  rewrite(dir, id);
106
98
  renameLock(dir, id);
107
- return lowerFloor(dir, kept);
99
+ return into ? shapeShared(dir, into, id) : lowerFloor(dir, kept, PARTS.length);
108
100
  }
109
101
  catch (err) {
110
102
  rmSync(dir, { recursive: true, force: true });
103
+ if (err instanceof CliError)
104
+ throw err;
111
105
  throw new Error(`template ${from}: ${err.message}`);
112
106
  }
113
107
  };
@@ -115,7 +109,9 @@ const shape = (dir, from, id, kept) => {
115
109
  const hostLine = (id) => process.env['AGENTAGE_SITE_FQDN']?.trim()
116
110
  ? `host ${id}.${siteFqdn()}`
117
111
  : `host ${id} on your site (set AGENTAGE_SITE_FQDN to print its address)`;
118
- const printNext = (dir, from, id, kept) => {
112
+ // With no install, the folder has no node_modules: npm ci comes first, and npx runs the pinned cli.
113
+ const nextStep = (dir, install) => `cd ${dir} && ${install ? '' : 'npm ci && '}npx agentage extension up`;
114
+ const printNext = (dir, from, id, kept, install) => {
119
115
  const kit = String(json(join(dir, 'package.json'))['dependencies']?.['@agentage/extension'] ?? '?');
120
116
  const { repo, ref, folder } = repoRef(from);
121
117
  const branch = ref ? `branch ${ref}` : 'default branch';
@@ -124,7 +120,7 @@ const printNext = (dir, from, id, kept) => {
124
120
  const contract = kept.includes('mcp') ? ` · contract ${id}.mcpc.json` : '';
125
121
  console.log(` folder ${resolve(dir)}`);
126
122
  console.log(` id ${id} · ${hostLine(id)}${contract}`);
127
- console.log(` next cd ${dir} && agentage extension up`);
123
+ console.log(` next ${nextStep(dir, install)}`);
128
124
  };
129
125
  // Clones the template's default branch (or the #branch of --from; only its :folder) into ./extension-<id>, no history;
130
126
  // then installs its dependencies, builds it and (unless --no-install) gives it to the daemon.
@@ -136,20 +132,13 @@ export const runExtensionCreate = async (opts, url = (from) => `https://github.c
136
132
  if (refused)
137
133
  throw new CliError('invalid_argument', refused);
138
134
  await trustFrom(from, opts, opts.json ? { ...io, isTTY: false } : io);
139
- const dir = `extension-${id}`;
135
+ const dir = opts.into ? join(opts.into, id) : `extension-${id}`;
140
136
  await clone(url(repoRef(from).repo), from, dir);
141
- const ci = shape(dir, from, id, kept);
142
- printNext(dir, from, id, kept);
137
+ const ci = shape(dir, from, id, kept, opts);
138
+ printNext(dir, from, id, kept, opts.install !== false);
143
139
  if (ci)
144
140
  console.log(ci);
141
+ if (opts.into)
142
+ rootEdits(id).forEach((line) => console.log(line));
145
143
  return { id, dir, from, kept, ...(await after(dir, opts.install !== false)) };
146
144
  };
147
- export const addCreate = (group, create) => addJson(group
148
- .command('create')
149
- .description('Create ./extension-<id> from the extension template with the parts named')
150
- .argument('<id>', 'the extension id, also its host and contract name')
151
- .argument('[parts...]', `parts to keep (default: all eight): ${PARTS.join(', ')}`)
152
- .option('--from <owner/repo[#branch][:folder]>', `the template repo and folder (default: ${TEMPLATE})`)
153
- .option('--no-install', 'build the folder, but do not give it to the daemon')
154
- .option('--yes', 'run code from another --from repo or branch without asking')
155
- .addHelpText('after', '\nExample:\n agentage extension create my-ext app api (parts may also be app,api)')).action((id, parts, o) => create({ id, parts, ...o }));
@@ -1,7 +1,8 @@
1
1
  import {} from 'commander';
2
2
  import { addBuild } from './build.js';
3
3
  import { addRelease } from './release.js';
4
- import { addCreate } from './create.js';
4
+ import { addCreate } from './create-command.js';
5
+ import {} from './create.js';
5
6
  import {} from './doctor.js';
6
7
  import { addLifecycle } from './lifecycle-commands.js';
7
8
  import { addMarket } from './market-commands.js';
@@ -12,7 +12,6 @@ const COLOR = {
12
12
  missing: chalk.yellow,
13
13
  };
14
14
  const STATE_WIDTH = Math.max(...Object.keys(COLOR).map((state) => state.length));
15
- const cloudText = ({ version, etag }) => chalk.yellow(`; account: version ${version}, etag ${etag} - run agentage setup`);
16
15
  const profileText = (profile) => {
17
16
  if (profile.state === 'missing')
18
17
  return 'no profile';
@@ -20,8 +19,7 @@ const profileText = (profile) => {
20
19
  return chalk.red('invalid');
21
20
  const etag = profile.etag === null ? '' : `, etag ${profile.etag}`;
22
21
  const readOnly = profile.readOnly ? chalk.yellow(', read-only') : '';
23
- const cloud = profile.cloud ? cloudText(profile.cloud) : '';
24
- return `version ${profile.version} (source: ${profile.source}${etag}${readOnly})${cloud}`;
22
+ return `version ${profile.version} (source: ${profile.source}${etag}${readOnly})`;
25
23
  };
26
24
  const pendingText = (plan) => {
27
25
  const changes = pendingChanges(plan);
@@ -32,10 +32,6 @@ export type ProfileStatus = {
32
32
  source: ProfileSource;
33
33
  readOnly: boolean;
34
34
  etag: string | null;
35
- cloud?: {
36
- version: number;
37
- etag: string;
38
- };
39
35
  };
40
36
  export interface ExtensionsStatus {
41
37
  machine: {
@@ -42,7 +42,7 @@ export const accountSetup = async (deps) => {
42
42
  return fromLocalCopy(deps);
43
43
  const platform = await account.platform();
44
44
  const machine = await connect(account);
45
- const registered = registerMachine(account.machines, machine);
45
+ const registered = platform ? registerMachine(account.machines, machine) : false;
46
46
  try {
47
47
  await profileFrom(machine, deps);
48
48
  }
@@ -55,7 +55,8 @@ export const accountSetup = async (deps) => {
55
55
  export const disconnect = async (deps) => {
56
56
  const machine = readMachine();
57
57
  const account = await deps.account();
58
- if (machine !== null && account !== null)
58
+ const platform = account === null ? null : await account.platform().catch(() => null);
59
+ if (machine !== null && account !== null && platform !== null)
59
60
  await disconnectMachine(account.machines, machine.id);
60
61
  await deps.signOut();
61
62
  if (machine !== null)
@@ -1,32 +1,12 @@
1
- import { pullProfile } from '../../core/profile/cloud.js';
1
+ import {} from '../../core/profile/cloud.js';
2
2
  import { seenMachine } from '../../core/profile/register.js';
3
3
  import { gatherExtensions } from '../extension/rows.js';
4
- const STATUS_TIMEOUT_MS = 2_000;
5
- // The account's profile when it moved past the local copy; null when the same or not known.
6
- const accountProfile = async (fetch, profile) => {
7
- if (profile.state !== 'ok' || profile.etag === null)
8
- return null;
9
- const pulled = await pullProfile(fetch, profile.etag, STATUS_TIMEOUT_MS);
10
- if (pulled.kind !== 'found')
11
- return null;
12
- return { version: pulled.doc.profile.version, etag: pulled.doc.etag };
13
- };
14
- // `status`: marks this machine seen (does the account know it?) and compares the profile copies.
4
+ // `status`: marks this machine seen (does the account know it?) and names its platform.
15
5
  export const gatherWithAccount = async (account) => {
16
6
  const gathered = await gatherExtensions();
17
- const { machine, profile } = gathered.status;
18
- const [registered, cloud] = account === null
19
- ? [null, null]
20
- : await Promise.all([
21
- seenMachine(account.machines, machine.id),
22
- accountProfile(account.fetch, profile),
23
- ]);
24
- const compared = cloud !== null && profile.state === 'ok' ? { ...profile, cloud } : profile;
7
+ const { machine } = gathered.status;
25
8
  const platform = account === null ? null : await account.platform().catch(() => null);
26
- const status = {
27
- ...gathered.status,
28
- machine: { ...machine, registered, platform },
29
- profile: compared,
30
- };
9
+ const registered = account === null || platform === null ? null : await seenMachine(account.machines, machine.id);
10
+ const status = { ...gathered.status, machine: { ...machine, registered, platform } };
31
11
  return { ...gathered, status };
32
12
  };
@@ -109,8 +109,7 @@ export const runStatus = async (opts = {}, deps = statusDeps()) => {
109
109
  };
110
110
  const EXTENSIONS_HELP = `
111
111
  Extensions: adds this machine's id and name (machine.json), the local profile version
112
- (profile.json) with its source and, for a profile from your account, its etag and the
113
- account's when that moved on, and the number of extensions, with what setup would change, e.g.
112
+ (profile.json) with its source and the number of extensions, with what setup would change, e.g.
114
113
  (1 to add); agentage extension list shows one row per extension. Signed in, it also marks this
115
114
  machine seen in your account (--json: machine.registered). Extension code is never loaded; the
116
115
  only file written is machine.json.
@@ -1,6 +1,3 @@
1
- import { type Profile } from './schema.js';
2
- export declare const PROFILE_PATH = "/v1/profile";
3
- export type JsonObject = Record<string, unknown>;
4
1
  export interface CloudInit {
5
2
  method?: string;
6
3
  headers?: Record<string, string>;
@@ -9,30 +6,8 @@ export interface CloudInit {
9
6
  }
10
7
  export type CloudFetch = (path: string, init?: CloudInit) => Promise<Response>;
11
8
  export interface Account {
12
- fetch: CloudFetch;
13
9
  machines: CloudFetch;
14
- platform: () => Promise<string>;
10
+ platform: () => Promise<string | null>;
15
11
  id: () => Promise<string | null>;
16
12
  }
17
- export interface CloudProfile {
18
- profile: Profile;
19
- readOnly: boolean;
20
- lock: JsonObject | null;
21
- npmMajor: number | null;
22
- etag: string | null;
23
- }
24
- export type Pull = {
25
- kind: 'current';
26
- } | {
27
- kind: 'found';
28
- doc: CloudProfile & {
29
- etag: string;
30
- };
31
- } | {
32
- kind: 'none';
33
- } | {
34
- kind: 'unavailable';
35
- reason: string;
36
- };
37
13
  export declare const errorCode: (res: Response) => Promise<string | null>;
38
- export declare const pullProfile: (fetch: CloudFetch, etag: string | null, timeoutMs?: number) => Promise<Pull>;
@@ -1,16 +1,4 @@
1
1
  import { isRecord } from '../../lib/fs/json-file.js';
2
- import { parseProfile } from './schema.js';
3
- // One resource per account: the profile, npm's lock and the npm major that wrote it, one ETag.
4
- export const PROFILE_PATH = '/v1/profile';
5
- // What a request ended with: the Response, or why there was none.
6
- const attempt = async (request) => {
7
- try {
8
- return await request();
9
- }
10
- catch (err) {
11
- return err.name === 'TimeoutError' ? 'timed out' : err.message;
12
- }
13
- };
14
2
  const bodyOf = async (res) => {
15
3
  try {
16
4
  return (await res.json());
@@ -19,51 +7,9 @@ const bodyOf = async (res) => {
19
7
  return null;
20
8
  }
21
9
  };
22
- // The code of the house error envelope, e.g. PROFILE_NOT_FOUND; null without one. Reads the body.
10
+ // The code of the house error envelope, e.g. MACHINE_NOT_FOUND; null without one. Reads the body.
23
11
  export const errorCode = async (res) => {
24
12
  const body = await bodyOf(res);
25
13
  const error = isRecord(body) && isRecord(body['error']) ? body['error'] : {};
26
14
  return typeof error['code'] === 'string' ? error['code'] : null;
27
15
  };
28
- // e.g. "503 AUTH_UNAVAILABLE": the status, and the envelope's code when there is one.
29
- const failureOf = async (res) => {
30
- const code = await errorCode(res);
31
- return code === null ? `${res.status}` : `${res.status} ${code}`;
32
- };
33
- const isMajor = (value) => value === null || (typeof value === 'number' && Number.isInteger(value));
34
- // A served resource and its etag, parsed; a string says what is wrong with it.
35
- const resourceOf = (data, etag) => {
36
- if (!isRecord(data) || typeof etag !== 'string')
37
- return 'unexpected answer';
38
- const { lock, npmMajor } = data;
39
- if (!(lock === null || isRecord(lock)) || !isMajor(npmMajor))
40
- return 'unexpected answer';
41
- const parsed = parseProfile(data['profile']);
42
- if (!parsed.ok)
43
- return `the profile in your account is invalid: ${parsed.errors.join('; ')}`;
44
- return { profile: parsed.profile, readOnly: parsed.readOnly, lock, npmMajor, etag };
45
- };
46
- // meta.etag equals the ETag header on a 2xx; either will do.
47
- const etagOf = (body, header) => {
48
- const meta = isRecord(body) && isRecord(body['meta']) ? body['meta'] : {};
49
- return meta['etag'] ?? header;
50
- };
51
- const served = (body, header) => resourceOf(isRecord(body) ? body['data'] : null, etagOf(body, header));
52
- const unavailable = (reason) => ({ kind: 'unavailable', reason });
53
- const NO_PROFILE = '404 PROFILE_NOT_FOUND';
54
- // GET, conditional on the local copy's etag: 304 keeps it, 200 replaces it, 404 means none yet.
55
- export const pullProfile = async (fetch, etag, timeoutMs) => {
56
- const headers = etag === null ? {} : { 'if-none-match': etag };
57
- const res = await attempt(() => fetch(PROFILE_PATH, { headers, timeoutMs }));
58
- if (typeof res === 'string')
59
- return unavailable(res);
60
- if (res.status === 304)
61
- return { kind: 'current' };
62
- if (res.status !== 200) {
63
- // Any other 404 is an API without the profile route, not an account without a profile.
64
- const failure = await failureOf(res);
65
- return failure === NO_PROFILE ? { kind: 'none' } : unavailable(failure);
66
- }
67
- const doc = served(await bodyOf(res), res.headers.get('etag'));
68
- return typeof doc === 'string' ? unavailable(doc) : { kind: 'found', doc };
69
- };
@@ -72,10 +72,8 @@ const tokenFor = async (auth, links, renew, opts) => {
72
72
  void revokePat(auth, links, old.id);
73
73
  return { minted: true, token };
74
74
  };
75
- // A discovered platform takes only a JWT PAT the session mints; an env PAT goes as is.
75
+ // The platform takes only a JWT PAT the session mints; an env PAT goes as is.
76
76
  const fetchAt = async (auth, links, found, url, init, opts) => {
77
- if (!found.discovered)
78
- return authedFetch(auth, links, url, init, opts);
79
77
  if (found.links.auth !== links.auth)
80
78
  throw refuse(links.auth, `platform token: the site's issuer is ${found.links.auth}`);
81
79
  if (auth.kind === 'pat')
@@ -98,4 +96,8 @@ const fetchAt = async (auth, links, found, url, init, opts) => {
98
96
  throw refuse(links.auth, 'platform token refused (401) by the platform');
99
97
  };
100
98
  // The machines routes at `<platform>/api/platform/machines`.
101
- export const platformFetch = (auth, links, found, path, init, opts) => machinesCall(found.platform, path, (url) => fetchAt(auth, links, found, url, init, opts));
99
+ export const platformFetch = (auth, links, found, path, init, opts) => {
100
+ if (!found.platform)
101
+ throw new Error('the site names no platform');
102
+ return machinesCall(found.platform, path, (url) => fetchAt(auth, links, found, url, init, opts));
103
+ };
@@ -7,8 +7,7 @@ export interface Platform {
7
7
  export declare const issuerAllowed: (issuer: string, site: string) => boolean;
8
8
  export interface Target {
9
9
  links: Links;
10
- platform: Platform;
11
- discovered: boolean;
10
+ platform: Platform | null;
12
11
  }
13
12
  export declare const derivedTarget: (fqdn: string) => Target;
14
13
  export declare const discoverTarget: (fqdn: string, get?: Get) => Promise<Target>;
@@ -1,6 +1,6 @@
1
1
  import { isRecord } from '../fs/json-file.js';
2
2
  import { cliFetch } from './fetch.js';
3
- import { apiOrigin, links } from './origins.js';
3
+ import { links } from './origins.js';
4
4
  const debug = (text) => {
5
5
  if (process.env['AGENTAGE_DEBUG'] === '1')
6
6
  console.error(`discovery: ${text}`);
@@ -36,10 +36,10 @@ const read = async (url, get) => {
36
36
  if (res.ok)
37
37
  return await res.json();
38
38
  if (res.status !== 404)
39
- debug(`${url} answered ${res.status}, using the api origin`);
39
+ debug(`${url} answered ${res.status}, using the derived origins`);
40
40
  }
41
41
  catch (err) {
42
- debug(`${url} failed (${err.message}), using the api origin`);
42
+ debug(`${url} failed (${err.message}), using the derived origins`);
43
43
  }
44
44
  return undefined;
45
45
  };
@@ -58,12 +58,8 @@ const issuerOf = (doc, base, url) => {
58
58
  throw new Error(`FAIL discovery: ${url} names an issuer outside the site`);
59
59
  return new URL(issuer).origin;
60
60
  };
61
- // The origins derived from the fqdn alone, as before discovery.
62
- export const derivedTarget = (fqdn) => {
63
- const api = apiOrigin(fqdn);
64
- const platform = { url: api, machines: `${api}/v1/machines` };
65
- return { links: links(fqdn), platform, discovered: false };
66
- };
61
+ // The origins derived from the fqdn alone; a site with no document has no platform.
62
+ export const derivedTarget = (fqdn) => ({ links: links(fqdn), platform: null });
67
63
  const fetchTarget = async (fqdn, get) => {
68
64
  const base = links(fqdn);
69
65
  const url = `${base.site}/.well-known/agentage.json`;
@@ -71,10 +67,10 @@ const fetchTarget = async (fqdn, get) => {
71
67
  if (doc === undefined)
72
68
  return derivedTarget(fqdn);
73
69
  const platform = platformOf(doc, base.site, url);
74
- return { links: { ...base, auth: issuerOf(doc, base, url) }, platform, discovered: true };
70
+ return { links: { ...base, auth: issuerOf(doc, base, url) }, platform };
75
71
  };
76
72
  const once = new Map();
77
- // Fetched once per run; an unserved document (404, 5xx, unreachable) keeps the derived origins,
73
+ // Fetched once per run; an unserved document (404, 5xx, unreachable) keeps the derived origins (no platform),
78
74
  // a served one without a valid platform or issuer fails closed.
79
75
  export const discoverTarget = (fqdn, get = cliFetch) => {
80
76
  if (get !== cliFetch)
@@ -1,12 +1,10 @@
1
1
  export type Env = 'development' | 'production';
2
2
  export interface Links {
3
3
  site: string;
4
- api: string;
5
4
  auth: string;
6
5
  }
7
6
  export declare const DEFAULT_FQDN = "agentage.io";
8
7
  export declare const normalizeFqdn: (raw?: string) => string;
9
8
  export declare const siteFqdn: () => string;
10
9
  export declare const environment: (fqdn: string) => Env;
11
- export declare const apiOrigin: (fqdn: string) => string;
12
10
  export declare const links: (fqdn: string) => Links;
@@ -17,19 +17,11 @@ const stubOrigin = (fqdn) => {
17
17
  return m ? `http://127.0.0.1:${m[1]}` : null;
18
18
  };
19
19
  export const environment = (fqdn) => isLocal(fqdn) || fqdn.startsWith('dev.') ? 'development' : 'production';
20
- // The account routes (/v1/...) sit at the root of the API origin; `links().api` is its /api family.
21
- export const apiOrigin = (fqdn) => {
22
- const stub = stubOrigin(fqdn);
23
- if (stub)
24
- return stub;
25
- return isLocal(fqdn) ? 'http://localhost:3001' : `https://api.${fqdn}`;
26
- };
27
20
  export const links = (fqdn) => {
28
21
  const stub = stubOrigin(fqdn);
29
- const api = `${apiOrigin(fqdn)}/api`;
30
22
  if (stub)
31
- return { site: stub, api, auth: stub };
23
+ return { site: stub, auth: stub };
32
24
  return isLocal(fqdn)
33
- ? { site: 'http://localhost:3000', api, auth: 'http://localhost:3010' }
34
- : { site: `https://${fqdn}`, api, auth: `https://auth.${fqdn}` };
25
+ ? { site: 'http://localhost:3000', auth: 'http://localhost:3010' }
26
+ : { site: `https://${fqdn}`, auth: `https://auth.${fqdn}` };
35
27
  };
@@ -10,10 +10,6 @@ import { checkForUpdate } from '../update/update-check.js';
10
10
  import { VERSION } from '../../utils/version.js';
11
11
  // node:https via fetchJsonUnref, not global fetch: undici's ref'd connect timer keeps the process
12
12
  // alive ~10s after an aborted request on a packet-drop network, stalling `status` exit.
13
- const checkEndpoint = async (apiUrl, headers) => {
14
- const res = await fetchJsonUnref(`${apiUrl}/health`, 3000, headers);
15
- return res?.ok ?? false;
16
- };
17
13
  // Host reachability, not app health: the site root answers any HTTP status (200/3xx/4xx) when the
18
14
  // host is up, so any non-null response counts as reachable; only a refused/timed-out connect fails.
19
15
  const checkSite = async (siteUrl, headers) => {
@@ -38,16 +34,14 @@ export const gatherStatus = async (auth, fqdn) => {
38
34
  const derived = links(fqdn);
39
35
  const env = environment(fqdn);
40
36
  const headers = requestHeaders();
41
- const [found, apiUp, siteReachable, update] = await Promise.all([
37
+ const [found, siteReachable, update] = await Promise.all([
42
38
  discoverTarget(fqdn).catch(() => derivedTarget(fqdn)),
43
- checkEndpoint(derived.api, headers),
44
39
  checkSite(derived.site, headers),
45
40
  checkForUpdate(VERSION),
46
41
  ]);
47
- const { links: target, platform, discovered } = found;
48
- // A discovered platform has no /health: its host answering is enough.
49
- const endpoint = discovered ? platform.url : target.api;
50
- const reachable = discovered ? await checkSite(endpoint, headers) : apiUp;
42
+ const { links: target, platform } = found;
43
+ const endpoint = platform ? platform.url : derived.site;
44
+ const reachable = platform ? await checkSite(endpoint, headers) : siteReachable;
51
45
  const report = {
52
46
  version: VERSION,
53
47
  fqdn,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentage/cli",
3
- "version": "0.81.2",
3
+ "version": "0.82.0",
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
  },
56
56
  "dependencies": {
57
57
  "@agentage/apphost": "0.8.5",
58
- "@agentage/extension": "0.25.9",
58
+ "@agentage/extension": "0.25.10",
59
59
  "@electric-sql/pglite": "^0.6.0",
60
60
  "@tailwindcss/postcss": "^4.3.5",
61
61
  "chalk": "^6.0.0",