Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/managed-plugin-artifact.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'agent-device': minor
---

Install local plugin tarballs with `plugins add-artifact` or the plugin manager API. Artifact selections record their version and SHA-512 integrity. To replace one, run `plugins remove <package>` and then `plugins add-artifact <path.tgz>`. Close active sessions and restart the daemon to apply the changed selection.
8 changes: 4 additions & 4 deletions packages/command-surface/src/schema/command-overrides.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ const SCHEMA_ONLY_CLI_COMMAND_SCHEMAS = {
text: {
summary: 'Manage installed provider plugins',
description:
'Install, list, update, or remove npm provider plugins in AGENT_DEVICE_HOME (default ~/.agent-device). Changes take effect after restarting the local daemon. list works offline and, when a daemon is running for --state-dir, also reports the providers it registered. Use --json for structured results.',
'Install, list, update, or remove provider plugins in AGENT_DEVICE_HOME (default ~/.agent-device). Changes take effect after restarting the local daemon. list works offline and, when a daemon is running for --state-dir, also reports the providers it registered. Use --json for structured results.',
},
usageOverride:
'plugins list [--state-dir <path>]|add <package[@version]>|update <package>|remove <package>',
'plugins list [--state-dir <path>]|add <package[@version]>|add-artifact <path.tgz>|update <package>|remove <package>',
listUsageOverride: 'plugins',
positionalArgs: ['list|add|update|remove', 'package?'],
flagsByAction: { list: ['stateDir'], add: [], update: [], remove: [] },
positionalArgs: ['list|add|add-artifact|update|remove', 'package-or-path?'],
flagsByAction: { list: ['stateDir'], add: [], 'add-artifact': [], update: [], remove: [] },
supportedFlags: ['stateDir'],
},
cdp: {
Expand Down
263 changes: 263 additions & 0 deletions packages/plugins/src/store-artifact.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,263 @@
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { test, vi } from 'vitest';
import * as command from '@agent-device/host-kit/command';
import { mkdtempForTestSync, pluginHome, v2RegistrationSource } from '@agent-device/test-kit';
import {
addPluginArtifact,
changePlugin,
createPluginSelectionGuard,
listPlugins,
storePluginCandidates,
} from './store.ts';

function packFixture(
root: string,
name: string,
exportsField: unknown = { './agent-device': './plugin.mjs' },
factoryGate?: string,
) {
const source = path.join(root, name);
fs.mkdirSync(source, { recursive: true });
const sentinel = path.join(root, `${name}-executed`);
fs.writeFileSync(
path.join(source, 'package.json'),
JSON.stringify({
name,
version: '1.2.3',
type: 'module',
exports: exportsField,
scripts: {
preinstall: `node sentinel.cjs`,
install: `node sentinel.cjs`,
postinstall: `node sentinel.cjs`,
},
}),
);
fs.writeFileSync(
path.join(source, 'sentinel.cjs'),
`require('node:fs').writeFileSync(${JSON.stringify(sentinel)}, 'script')`,
);
let pluginSource = v2RegistrationSource(name).replace(
'export default (options = {}) => (',
`export default (options = {}) => (fs.writeFileSync(${JSON.stringify(sentinel)}, 'factory'), `,
);
if (factoryGate) {
pluginSource = pluginSource.replace('export default ', 'const createPlugin = ');
pluginSource += `\nexport default async (options) => {
const gate = globalThis[Symbol.for(${JSON.stringify(factoryGate)})];
gate.enter();
await gate.resume;
return createPlugin(options);
};`;
}
fs.writeFileSync(path.join(source, 'plugin.mjs'), pluginSource);
const packed = command.runCmdSync(
'npm',
['pack', '--ignore-scripts', '--json', '--pack-destination', root],
{ cwd: source },
);
assert.equal(packed.exitCode, 0, packed.stderr);
return { archive: path.join(root, JSON.parse(packed.stdout)[0].filename), sentinel };
}

test('artifact installation preserves immutable identity, isolation, collision and stale guard', async () => {
const root = mkdtempForTestSync('plugin-artifact-');
const fixture = packFixture(root, 'fixture-provider');
const { home, env: isolated } = pluginHome();
const env = { ...process.env, ...isolated };
const other = pluginHome();
const expected = `sha512-${crypto.createHash('sha512').update(fs.readFileSync(fixture.archive)).digest('base64')}`;
const result = await addPluginArtifact(path.basename(fixture.archive), { cwd: root, env });
assert.equal(result.integrity, expected);
assert.equal(result.name, 'fixture-provider');
assert.equal(result.version, '1.2.3');
assert.equal(fs.existsSync(fixture.sentinel), false);
assert.ok(fs.existsSync(fixture.archive));
assert.deepEqual(await listPlugins(other.env, []), []);
const guard = createPluginSelectionGuard(await storePluginCandidates(env), env);
const configPath = path.join(home, 'config.json');
const before = fs.readFileSync(configPath, 'utf8');
await assert.rejects(addPluginArtifact(fixture.archive, { cwd: root, env }), {
code: 'INVALID_ARGS',
});
await assert.rejects(changePlugin('update', result.name, env), { code: 'INVALID_ARGS' });
await assert.rejects(changePlugin('add', result.name, env), { code: 'INVALID_ARGS' });
assert.equal(fs.readFileSync(configPath, 'utf8'), before);
assert.equal(fs.readdirSync(path.join(home, 'plugins')).length, 1);
const [listed] = await listPlugins(env, []);
assert.equal(listed?.version, '1.2.3');
assert.equal(listed?.integrity, expected);
assert.equal(listed?.installation, result.installation);
assert.equal(fs.readFileSync(fixture.sentinel, 'utf8'), 'factory');
const config = JSON.parse(before);
config.plugins[result.name].artifact.integrity =
`sha512-${Buffer.alloc(64, 1).toString('base64')}`;
fs.writeFileSync(configPath, JSON.stringify(config));
assert.throws(
() => guard(result.name),
(error: unknown) =>
(error as { details?: { reason?: string } }).details?.reason === 'daemon-plugin-set-stale',
);
});

test('invalid artifact and missing export roll back without disturbing selections', async () => {
const root = mkdtempForTestSync('plugin-artifact-invalid-');
const { home, env: isolated } = pluginHome();
const env = { ...process.env, ...isolated };
const valid = packFixture(root, 'fixture-valid');
await addPluginArtifact(valid.archive, { cwd: root, env });
const before = fs.readFileSync(path.join(home, 'config.json'), 'utf8');
const missing = packFixture(root, 'fixture-missing', { '.': './plugin.mjs' });
await assert.rejects(addPluginArtifact(missing.archive, { cwd: root, env }));
const bad = path.join(root, 'bad.tgz');
fs.writeFileSync(bad, 'not an archive');
await assert.rejects(addPluginArtifact(bad, { cwd: root, env }));
assert.equal(fs.readFileSync(path.join(home, 'config.json'), 'utf8'), before);
assert.equal(fs.readdirSync(path.join(home, 'plugins')).length, 1);
assert.equal(fs.existsSync(missing.sentinel), false);
});

test('concurrent artifact additions preserve both selections', async () => {
const root = mkdtempForTestSync('plugin-artifact-concurrent-');
const one = packFixture(root, 'fixture-one');
const two = packFixture(root, 'fixture-two');
const { env: isolated } = pluginHome();
const env = { ...process.env, ...isolated };
await Promise.all(
[one, two].map(({ archive }) => addPluginArtifact(archive, { cwd: root, env })),
);
assert.deepEqual(
(await listPlugins(env, [])).map((plugin) => plugin.name),
['fixture-one', 'fixture-two'],
);
assert.equal(fs.existsSync(one.sentinel), true);
});

test('npm staging rejects an escaping symlink entry and leaves external files untouched', async () => {
const { default: tar } = await import('tar-stream');
const { gzipSync } = await import('node:zlib');
const root = mkdtempForTestSync('plugin-artifact-symlink-');
const outside = path.join(root, 'outside.mjs');
fs.writeFileSync(outside, 'outside');
const archive = path.join(root, 'malicious.tgz');
const stream = tar.pack();
const chunks: Buffer[] = [];
stream.on('data', (chunk: Buffer) => chunks.push(chunk));
stream.entry(
{ name: 'package/package.json' },
JSON.stringify({
name: 'fixture-escape',
version: '1.0.0',
exports: { './agent-device': './plugin.mjs' },
}),
);
stream.entry({ name: 'package/plugin.mjs', type: 'symlink', linkname: outside });
stream.entry({ name: 'package/../../escape' }, 'escaped');
const finished = new Promise<void>((resolve, reject) => {
stream.on('end', resolve);
stream.on('error', reject);
});
stream.finalize();
await finished;
fs.writeFileSync(archive, gzipSync(Buffer.concat(chunks)));
const { home, env: isolated } = pluginHome();
await assert.rejects(
addPluginArtifact(archive, { cwd: root, env: { ...process.env, ...isolated } }),
);
assert.equal(fs.readFileSync(outside, 'utf8'), 'outside');
assert.equal(fs.existsSync(path.join(home, 'escape')), false);
assert.equal(fs.existsSync(path.join(home, 'config.json')), false);
});

test('artifact installation rejects replacement bytes consumed by npm', async () => {
const root = mkdtempForTestSync('plugin-artifact-replaced-');
const originalRoot = path.join(root, 'original');
const replacementRoot = path.join(root, 'replacement');
const original = packFixture(originalRoot, 'fixture-replaced');
const replacement = packFixture(replacementRoot, 'fixture-replaced');
assert.notDeepEqual(fs.readFileSync(original.archive), fs.readFileSync(replacement.archive));
const { home, env: isolated } = pluginHome();
const env = { ...process.env, ...isolated };
const runCmd = command.runCmd;
let replaced = false;
const spy = vi.spyOn(command, 'runCmd').mockImplementation(async (program, args, options) => {
if (program === 'npm' && args[0] === 'install' && args.at(-2) === '--') {
fs.copyFileSync(replacement.archive, args.at(-1)!);
replaced = true;
}
return runCmd(program, args, options);
});
try {
await assert.rejects(addPluginArtifact(original.archive, { cwd: root, env }), {
code: 'INVALID_ARGS',
details: { reason: 'artifact_integrity_mismatch' },
});
assert.equal(replaced, true);
assert.equal(fs.existsSync(path.join(home, 'config.json')), false);
assert.deepEqual(fs.readdirSync(path.join(home, 'plugins')), []);
assert.equal(fs.existsSync(replacement.sentinel), false);
} finally {
spy.mockRestore();
}
});

test('inventory retains one selection snapshot while a factory awaits', async () => {
const root = mkdtempForTestSync('plugin-artifact-inventory-');
const key = `agent-device.artifact-inventory.${crypto.randomUUID()}`;
const first = packFixture(path.join(root, 'first'), 'fixture-inventory', undefined, key);
const second = packFixture(path.join(root, 'second'), 'fixture-inventory');
const { env: isolated } = pluginHome();
const env = { ...process.env, ...isolated };
const original = await addPluginArtifact(first.archive, { cwd: root, env });
let enter!: () => void;
let continueListing!: () => void;
const entered = new Promise<void>((resolve) => {
enter = resolve;
});
const resume = new Promise<void>((resolve) => {
continueListing = resolve;
});
const gates = globalThis as typeof globalThis & Record<symbol, unknown>;
gates[Symbol.for(key)] = { enter, resume };
const listing = listPlugins(env, []);
try {
await entered;
await changePlugin('remove', original.name, env);
const replacement = await addPluginArtifact(second.archive, { cwd: root, env });
assert.notEqual(replacement.integrity, original.integrity);
continueListing();
const [entry] = await listing;
assert.deepEqual(entry, {
name: original.name,
installation: original.installation,
integrity: original.integrity,
version: original.version,
provider: 'fixture-inventory',
compatible: true,
});
const [current] = await listPlugins(env, []);
assert.equal(current?.installation, replacement.installation);
assert.equal(current?.integrity, replacement.integrity);
} finally {
continueListing();
await listing;
delete gates[Symbol.for(key)];
}
});

test.each([undefined, '~/plugin-store'])(
'missing HOME does not preempt archive validation (%s)',
async (override) => {
const root = mkdtempForTestSync('plugin-artifact-home-');
await assert.rejects(
addPluginArtifact(path.join(root, 'missing.tgz'), {
cwd: root,
env: { HOME: undefined, AGENT_DEVICE_HOME: override },
}),
{ code: 'ENOENT' },
);
},
);
23 changes: 23 additions & 0 deletions packages/plugins/src/store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -317,3 +317,26 @@ test('equivalent nested option key order keeps the daemon selection current', as
},
);
});

test.each([
['1.2.3-01', false],
['1.2.3-rc.01', false],
['1.2.3-00', false],
['1.2.3-0', true],
['1.2.3-01a', true],
['1.2.3-1a.0+001', true],
['1.2.3+01', true],
] as const)('artifact selection validates exact SemVer %s', async (version, valid) => {
const { home, env } = pluginHome();
selectV2Plugin(home, 'example', v2RegistrationSource('example'), { manifest: { version } });
const config = readPluginConfig(env);
config.plugins.example.artifact = {
version,
integrity: `sha512-${Buffer.alloc(64).toString('base64')}`,
};
fs.writeFileSync(path.join(home, 'config.json'), JSON.stringify(config));
const [entry] = await listPlugins(env, []);
assert.equal(entry?.compatible, valid);
if (valid) assert.equal(entry?.version, version);
assert.equal(vi.mocked(runCmd).mock.calls.length, 0);
});
Loading
Loading