Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ Each row names the doc first, then the code that proves it. Read the doc before
- Profiles, states, the plan, short names, the profile file: `docs/profiles.md`;
`src/core/installer/`, `src/core/loader/states.ts`.
- Writing an extension, `ctx`, peers, author commands, `extension create`, run it locally:
`docs/extensions.md`; `src/extension.ts`, `src/core/loader/`, `src/commands/extension/create.ts`,
`docs/extensions.md`; `src/extension.ts`, `src/core/loader/`, `src/commands/extension/create.ts`
(the template source: `create-source.ts`),
`up.ts`.
- e2e scenarios: `e2e/core/README.md`. Test fixtures: `fixtures/README.md`.
- CI jobs and coverage floors (no doc): `.github/workflows/ci.yml`, `vitest.config.ts`.
Expand Down
9 changes: 6 additions & 3 deletions docs/extensions.md
Original file line number Diff line number Diff line change
Expand Up @@ -306,8 +306,11 @@ parts, `create` sets `MIN_EXECUTED` to 1. `MIN_EXECUTED` is the least number of
must run. After the first green run, set it to the real count. When `create` cannot find that
line, it says so and you set it by hand.

`--from <owner/repo>` takes another template repo, and `--from <owner/repo#branch>` one of its
branches. For any source other than `agentage/extension-template` itself, `create` first prints
The template is the folder `template/` of the kit repo (`agentage/platform:template`); only that
folder is copied, with no history. `--from <owner/repo>` takes another template repo at its root
(`agentage/extension-template` is the old template), `--from <owner/repo#branch>` one of its
branches, and `:folder` after either one folder of it. For any source other than the kit's
`template` folder or `agentage/extension-template`, `create` first prints
that code from that repo will be built and run on this machine, and asks `run it? (y/N)`; with
`--yes` it does not ask, and with no terminal (or `--json`) it needs `--yes`. After the clone,
`create` runs `npm ci --ignore-scripts`, builds the package (as `extension build` does) and gives
Expand All @@ -316,7 +319,7 @@ the clone, the rename and the parts dropped, no npm and no build. `create` adds
folder's `.gitignore` when it is missing, and says so. It ends
with `url <the first public route of the api that answers>`.

1. Install git and npm for `create`, which clones the template from GitHub. `build --container`,
1. Install git and npm for `create`, which clones the kit repo from GitHub. `build --container`,
`build --push`, `up --docker` and `release` also need Docker and a committed tree.
2. Inside the extension folder, run `npx agentage extension up`. Use `npx agentage`, not the
global `agentage`, which can be older than the version the project pins. It builds the
Expand Down
19 changes: 19 additions & 0 deletions docs/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,25 @@ removes, settings in `installation.json` and `settings.json`) 0.51 does not see.
first with `agentage daemon stop`, then install 0.51; 0.51 has no daemon and would leave this one
running on its port.

## extension create

```bash
agentage extension create <id> [part...] [--from <owner/repo[#branch][:folder]>] [--no-install] [--yes]
```

Makes `./extension-<id>` from a template, with no git history (the author guide, `docs/extensions.md`
"Run it locally", has the parts and the steps after the clone). `--from` names the template:

| `--from` | Takes |
| ----------------------------------------------- | ------------------------------------------------------------------------------------------ |
| not given | `agentage/platform:template`, the folder `template/` of the kit repo |
| `owner/repo` | the root of that repo's default branch (`agentage/extension-template` is the old template) |
| `owner/repo#branch` | the root of that branch |
| `owner/repo:folder`, `owner/repo#branch:folder` | only that folder (dot files included); a missing folder or a link is refused |

The clone is shallow; only the folder is kept. A source other than the kit's `template` folder or
`agentage/extension-template` asks `run it? (y/N)` first (`--yes` does not ask).

## extension doctor

```bash
Expand Down
13 changes: 8 additions & 5 deletions src/commands/extension/create-install.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,12 +136,15 @@ describe('extension create --from another repo or a branch', () => {
const NOTICE = (from: string) =>
`template ${from}: code from that repo will be built and run on this machine`;

test('the template itself asks nothing', async () => {
const quiet = await output(() => trustFrom('agentage/extension-template', {}, io(false).io));
expect(quiet).toMatchObject({ error: null, stderr: '' });
});
test.for(['agentage/platform:template', 'agentage/extension-template'])(
'the template itself asks nothing: %s',
async (from) => {
const quiet = await output(() => trustFrom(from, {}, io(false).io));
expect(quiet).toMatchObject({ error: null, stderr: '' });
}
);

test.for(['acme/ext', 'agentage/extension-template#feature/x'])(
test.for(['acme/ext', 'agentage/extension-template#feature/x', 'agentage/platform:packages'])(
'%s with no terminal needs --yes, --no-install or not',
async (from) => {
const refused = await output(() => trustFrom(from, {}, io(false).io));
Expand Down
5 changes: 2 additions & 3 deletions src/commands/extension/create-install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { hostClient, type HostClient } from '../../lib/daemon/host-client.js';
import { CliError } from '../../lib/json-output.js';
import { loadKitTool, type LoadKitTool } from './kit-tool.js';
import { confirmed, report, summaryOf, terminalIo, type ConfirmIo } from './lifecycle.js';
import { OWN_TEMPLATES } from './create-source.js';
import { ignoreLocal } from './up-local.js';
import { buildPackage, newerKitLine, npmIn, type Npm, type PackageBuild } from './package-build.js';

Expand Down Expand Up @@ -92,15 +93,13 @@ export const installCreated = async (
return { installed, url };
};

const OWN_TEMPLATE = 'agentage/extension-template';

// Another repo, or a branch of ours, is code nobody reviewed for you: its build script runs here.
export const trustFrom = async (
from: string,
opts: { yes?: boolean },
io: ConfirmIo = terminalIo()
): Promise<void> => {
if (from === OWN_TEMPLATE) return;
if (OWN_TEMPLATES.includes(from)) return;
console.error(`template ${from}: code from that repo will be built and run on this machine`);
if (opts.yes) return;
if (!io.isTTY)
Expand Down
123 changes: 123 additions & 0 deletions src/commands/extension/create-kit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import {
existsSync,
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
statSync,
symlinkSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect } from 'vitest';
import { output, test } from '../../test/config-dir.js';
import {
CI,
EXECUTABLE,
git,
KIT_MANIFEST,
kitRepo,
pushKit,
put,
RELEASE,
TEMPLATE_FILES,
} from '../../test/kit-repo.js';
import { runExtensionCreate, TEMPLATE } from './create.js';

let root = '';
let url = '';
const home = process.cwd();
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), 'agentage-create-kit-'));
url = kitRepo(root);
process.chdir(root);
});
afterEach(() => {
process.chdir(home);
rmSync(root, { recursive: true, force: true });
});

const YES = { isTTY: true, prompt: async () => 'y' };
const scaffoldOnly = async () => ({ installed: null, url: null });
const asked: string[] = [];
const create = (from?: string, to = () => url) =>
output(() =>
runExtensionCreate(
{ id: 'market', parts: [], ...(from && { from }) },
(repo) => (asked.push(repo), to()),
scaffoldOnly,
YES
)
);
const made = 'extension-market';
const read = (path: string) => readFileSync(join(root, made, path), 'utf8');
const listed = (dir: string): string[] =>
readdirSync(join(root, dir), { withFileTypes: true }).flatMap((e) =>
e.isDirectory() ? listed(join(dir, e.name)).map((f) => `${e.name}/${f}`) : [e.name]
);

describe('extension create from the kit repo', () => {
test('the default is the folder template/ of agentage/platform', async () => {
expect(TEMPLATE).toBe('agentage/platform:template');
const printed = await create();
expect(printed).toMatchObject({ error: null, stderr: '' });
expect(asked.at(-1)).toBe('agentage/platform');
expect(printed.lines[0]).toBe(
' template agentage/platform:template (default branch, kit 0.21.0)'
);
});

test('only template/ is copied, dot files and modes kept, no kit history', async () => {
await create();
expect(listed(made).sort()).toEqual(Object.keys(TEMPLATE_FILES).sort());
expect(read('.repo-doctor.yml')).toBe('class: extension\n');
expect(read('.gitignore')).toBe('node_modules/\n');
expect(read('CLAUDE.md')).toBe('# extension-market\n');
expect(statSync(join(root, made, EXECUTABLE)).mode & 0o111).toBe(0o111);
expect(readdirSync(root).filter((f) => f.includes('clone'))).toEqual([]);
});

test('repository and bugs name the new repo without the monorepo directory, private stays', async () => {
expect(KIT_MANIFEST.repository.directory).toBe('template');
await create();
const pkg = JSON.parse(read('package.json')) as typeof KIT_MANIFEST;
expect(pkg.repository).toEqual({
type: 'git',
url: 'git+https://github.com/agentage/extension-market.git',
});
expect(pkg.bugs.url).toBe('https://github.com/agentage/extension-market/issues');
expect(pkg.homepage).toBe('https://agentage.io');
expect(pkg.private).toBe(true);
expect(read('.github/workflows/release.yml')).toBe(RELEASE);
expect(read('.github/workflows/ci.yml')).toBe(CI);
});

test('--from owner/repo#branch:folder takes that folder of that branch', async () => {
git(join(root, 'kit-work'), 'checkout', '-q', '-b', 'feature/t');
put(join(root, 'kit-work', 'other'), { ...TEMPLATE_FILES, 'branch.txt': 'b\n' });
pushKit(root, 'feature/t');
const printed = await create('agentage/platform#feature/t:other');
expect(printed.lines[0]).toMatch(/^ template {2}agentage\/platform:other \(branch feature\/t,/);
expect(read('branch.txt')).toBe('b\n');
});

test.for([
['a missing folder', 'agentage/platform:nope'],
['a link', 'agentage/platform:link'],
])('refuses %s with one line, no folder and no clone left', async ([, from]) => {
symlinkSync('template', join(root, 'kit-work', 'link'));
pushKit(root);
const folder = from?.split(':')[1];
expect((await create(from)).error).toBe(
`cannot clone template ${from}: no folder ${folder} in the repo`
);
expect(readdirSync(root).sort()).toEqual(['kit-work', 'kit.git']);
});

test('a clone that fails leaves no clone folder', async () => {
const printed = await create(undefined, () => `file://${root}/none`);
expect(printed.error).toMatch(/^cannot clone template agentage\/platform:template: fatal/);
expect(existsSync(join(root, made))).toBe(false);
expect(readdirSync(root).sort()).toEqual(['kit-work', 'kit.git']);
});
});
92 changes: 92 additions & 0 deletions src/commands/extension/create-safety.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import {
existsSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
symlinkSync,
writeFileSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, vi } from 'vitest';
import { output, test } from '../../test/config-dir.js';
import { kitRepo, pushKit } from '../../test/kit-repo.js';
import { runExtensionCreate } from './create.js';
import { removeOwn } from './create-source.js';

let root = '';
let url = '';
const home = process.cwd();
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), 'agentage-create-safe-'));
url = kitRepo(root);
process.chdir(root);
});
afterEach(() => {
process.chdir(home);
vi.restoreAllMocks();
rmSync(root, { recursive: true, force: true });
});

const YES = { isTTY: true, prompt: async () => 'y' };
const create = (from?: string) =>
output(() =>
runExtensionCreate(
{ id: 'market', parts: [], ...(from && { from }) },
() => url,
async () => ({ installed: null, url: null }),
YES
)
);
const outside = () => readdirSync(root).filter((f) => !['kit-work', 'kit.git'].includes(f));

describe('extension create keeps to its own folders', () => {
test('a folder of yours named like the clone folder stays as it was', async () => {
mkdirSync(join(root, '.extension-market.clone'));
writeFileSync(join(root, '.extension-market.clone', 'mine.txt'), 'mine');
expect((await create()).error).toBeNull();
expect(readFileSync(join(root, '.extension-market.clone', 'mine.txt'), 'utf8')).toBe('mine');
expect(outside().sort()).toEqual(['.extension-market.clone', 'extension-market']);
});

test.for([
['in the folder', 'template/src', 'agentage/platform:template'],
['at the root', 'src', 'agentage/extension-template'],
])('refuses a template with a symbolic link %s, nothing left', async ([, at = '', from]) => {
mkdirSync(join(root, 'kit-work', at), { recursive: true });
symlinkSync(root, join(root, 'kit-work', at, 'out'));
pushKit(root);
const { error } = await create(from);
expect(error).toBe(`template ${from}: a symbolic link extension-market/src/out`);
expect(outside()).toEqual([]);
expect(existsSync(join(root, 'kit-work'))).toBe(true);
});

test('Ctrl-C during the clone removes this run only, then the signal ends the process', async () => {
const kill = vi.spyOn(process, 'kill').mockImplementation(() => true);
const before = process.listeners('SIGINT');
const bin = join(root, 'bin');
mkdirSync(bin);
writeFileSync(join(bin, 'git'), '#!/bin/sh\nsleep 0.5\nexit 1\n', { mode: 0o755 });
const path = process.env['PATH'];
process.env['PATH'] = `${bin}:${path ?? ''}`;
try {
const running = create();
await vi.waitFor(() => expect(process.listeners('SIGINT').length).toBe(before.length + 1));
const [onSigint] = process.listeners('SIGINT').filter((l) => !before.includes(l));
onSigint?.('SIGINT');
await vi.waitFor(() => expect(kill).toHaveBeenCalledWith(process.pid, 'SIGINT'));
expect(outside()).toEqual(['bin']);
await running;
} finally {
process.env['PATH'] = path;
}
expect(process.listeners('SIGINT')).toEqual(before);
});

test('removeOwn never throws, also for a folder already gone', () => {
expect(() => removeOwn(join(root, 'none'))).not.toThrow();
});
});
Loading