mirror of
https://github.com/n8n-io/n8n.git
synced 2026-12-04 00:30:34 +00:00
chore: Upgrade agent harness and Codespaces from OpenCode V1 to V2 (#45235)
Co-authored-by: n8n-cat-bot[bot] <283985454+n8n-cat-bot[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
a26c6f4d01
commit
7e48eb914f
13 files changed
+403
-156
No files matched your search
@@ -5,7 +5,7 @@ FROM node:${NODE_VERSION}-bookworm
|
||||
|
||||
ARG PNPM_VERSION=12.4.2
|
||||
ARG PLAYWRIGHT_VERSION=1.62.1
|
||||
ARG OPENCODE_VERSION=1.18.25
|
||||
ARG OPENCODE_VERSION=2.4.1
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
tmux sudo less jq ripgrep postgresql-client \
|
||||
@@ -16,7 +16,7 @@ RUN npx -y playwright@${PLAYWRIGHT_VERSION} install-deps chromium
|
||||
|
||||
# Agent harnesses. Self-update is off: the image is the update mechanism
|
||||
ENV DISABLE_AUTOUPDATER=1
|
||||
RUN npm install -g @anthropic-ai/claude-code opencode-ai@${OPENCODE_VERSION}
|
||||
RUN npm install -g @anthropic-ai/claude-code @opencode/cli@${OPENCODE_VERSION}
|
||||
|
||||
COPY codespaces-env.sh /usr/local/lib/codespaces-env.sh
|
||||
COPY codespaces-secrets.sh /etc/profile.d/codespaces-secrets.sh
|
||||
|
||||
@@ -107,9 +107,10 @@ pnpm agent:harness
|
||||
```
|
||||
|
||||
The command verifies the release checksum. It caches the bundle under
|
||||
`~/.cache/n8n-agent-harness`. It then links the bundle plugin into
|
||||
`~/.config/opencode/plugins`. Run the command again after the lock changes.
|
||||
Restart OpenCode after the command completes.
|
||||
`~/.cache/n8n-agent-harness`. It then writes a managed plugin shim at
|
||||
`~/.config/opencode/plugins/n8n-harness/index.js` and removes any legacy
|
||||
`n8n-harness.js` symlink. Run the command again after the lock changes.
|
||||
OpenCode watches plugin files and reloads automatically.
|
||||
|
||||
## Local OpenCode clients
|
||||
|
||||
@@ -130,7 +131,7 @@ For the TUI, install the same OpenCode version as the remote server. The
|
||||
for new images:
|
||||
|
||||
```bash
|
||||
npm install -g opencode-ai@<version>
|
||||
npm install -g @opencode/cli@<version>
|
||||
```
|
||||
|
||||
Use npm, not pnpm. The package gets its binary from a `postinstall` script.
|
||||
@@ -180,7 +181,6 @@ your laptop can access the local browser proxy while it runs. Do not forward
|
||||
this proxy or the OpenCode server port to other machines.
|
||||
|
||||
The server enables only OpenRouter. It reads `OPENROUTER_API_KEY` when it starts.
|
||||
It enables OpenCode code mode by default to reduce the initial tool context.
|
||||
Browser mode opens the workspace's most recently updated conversation directly.
|
||||
The web UI stores opened projects in browser storage. If a new-session page
|
||||
shows **New project**, open `/workspaces/n8n` there once. Keep the same browser
|
||||
|
||||
@@ -22,16 +22,17 @@ const SLACK_TEXT_LIMIT = 3900;
|
||||
|
||||
export function openCodeConfig(environment) {
|
||||
const config = {
|
||||
provider: { openrouter: { options: { apiKey: '{env:OPENROUTER_API_KEY}' } } },
|
||||
providers: { openrouter: { settings: { apiKey: '{env:OPENROUTER_API_KEY}' } } },
|
||||
};
|
||||
if (environment.FLAKY_MCP_URL && environment.FLAKY_MCP_TOKEN) {
|
||||
config.mcp = {
|
||||
flaky: {
|
||||
type: 'remote',
|
||||
url: environment.FLAKY_MCP_URL,
|
||||
enabled: true,
|
||||
oauth: false,
|
||||
headers: { Authorization: 'Bearer {env:FLAKY_MCP_TOKEN}' },
|
||||
servers: {
|
||||
flaky: {
|
||||
type: 'remote',
|
||||
url: environment.FLAKY_MCP_URL,
|
||||
oauth: false,
|
||||
headers: { Authorization: 'Bearer {env:FLAKY_MCP_TOKEN}' },
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -117,7 +118,9 @@ function stopProcessTree(child, signal) {
|
||||
}
|
||||
|
||||
function eventError(event) {
|
||||
return event.error?.data?.message ?? event.error?.message ?? event.error?.name;
|
||||
return (
|
||||
event.error?.data?.message ?? event.error?.message ?? event.error?.name ?? event.error?.type
|
||||
);
|
||||
}
|
||||
|
||||
export function runOpenCode(
|
||||
@@ -318,9 +321,10 @@ export async function startSlackProgress(
|
||||
|
||||
return {
|
||||
event(event) {
|
||||
if (!event.part?.id) return;
|
||||
const partId = event.part?.partID ?? event.part?.id;
|
||||
if (!partId) return;
|
||||
if (event.type === 'tool_use') {
|
||||
tools.set(event.part.id, {
|
||||
tools.set(partId, {
|
||||
status: event.part.state?.status,
|
||||
title: event.part.state?.title || event.part.tool,
|
||||
});
|
||||
|
||||
@@ -146,7 +146,8 @@ test('streams tool progress but excludes reasoning', async () => {
|
||||
type: 'tool_use',
|
||||
sessionID: 'ses_1',
|
||||
part: {
|
||||
id: 'prt_tool',
|
||||
partID: 'prt_tool',
|
||||
id: 'call_1',
|
||||
type: 'tool',
|
||||
tool: 'read',
|
||||
state: { status: 'completed', title: 'Read worker source' },
|
||||
@@ -215,7 +216,8 @@ test('replaces progress with the final answer', async () => {
|
||||
type: 'tool_use',
|
||||
sessionID: 'ses_1',
|
||||
part: {
|
||||
id: 'prt_tool',
|
||||
partID: 'prt_tool',
|
||||
id: 'call_1',
|
||||
type: 'tool',
|
||||
tool: 'read',
|
||||
state: { status: 'completed', title: 'Read worker source' },
|
||||
@@ -331,6 +333,31 @@ test('stops the OpenCode process group at the turn limit', async () => {
|
||||
assert.deepEqual(signals, ['SIGTERM']);
|
||||
});
|
||||
|
||||
test('reports OpenCode V2 error events clearly', async () => {
|
||||
await assert.rejects(
|
||||
runOpenCode(
|
||||
{ message: 'Test message', cwd: '/workspaces/n8n', author: 'Tester' },
|
||||
() => {},
|
||||
() => {},
|
||||
{
|
||||
spawnProcess() {
|
||||
return completedChild([
|
||||
JSON.stringify({
|
||||
type: 'error',
|
||||
sessionID: 'ses_err',
|
||||
error: {
|
||||
type: 'provider.no-route',
|
||||
message: 'Model unavailable: openrouter/openai/gpt-5.6-sol',
|
||||
},
|
||||
}),
|
||||
]);
|
||||
},
|
||||
},
|
||||
),
|
||||
/Model unavailable: openrouter\/openai\/gpt-5\.6-sol/,
|
||||
);
|
||||
});
|
||||
|
||||
test('keeps broker credentials out of the OpenCode process', () => {
|
||||
const environment = openCodeEnvironment({
|
||||
AGENT_WORKER_TOKEN: 'worker',
|
||||
@@ -341,7 +368,7 @@ test('keeps broker credentials out of the OpenCode process', () => {
|
||||
GITHUB_TOKEN: 'github',
|
||||
});
|
||||
assert.deepEqual(JSON.parse(environment.OPENCODE_CONFIG_CONTENT), {
|
||||
provider: { openrouter: { options: { apiKey: '{env:OPENROUTER_API_KEY}' } } },
|
||||
providers: { openrouter: { settings: { apiKey: '{env:OPENROUTER_API_KEY}' } } },
|
||||
});
|
||||
delete environment.OPENCODE_CONFIG_CONTENT;
|
||||
assert.deepEqual(environment, {
|
||||
@@ -362,14 +389,15 @@ test('configures Flaky MCP without serializing its token', () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(JSON.parse(environment.OPENCODE_CONFIG_CONTENT), {
|
||||
provider: { openrouter: { options: { apiKey: '{env:OPENROUTER_API_KEY}' } } },
|
||||
providers: { openrouter: { settings: { apiKey: '{env:OPENROUTER_API_KEY}' } } },
|
||||
mcp: {
|
||||
flaky: {
|
||||
type: 'remote',
|
||||
url: 'https://example.com/mcp',
|
||||
enabled: true,
|
||||
oauth: false,
|
||||
headers: { Authorization: 'Bearer {env:FLAKY_MCP_TOKEN}' },
|
||||
servers: {
|
||||
flaky: {
|
||||
type: 'remote',
|
||||
url: 'https://example.com/mcp',
|
||||
oauth: false,
|
||||
headers: { Authorization: 'Bearer {env:FLAKY_MCP_TOKEN}' },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -99,7 +99,10 @@ test('starts a named OpenCode session in a worktree', () => {
|
||||
|
||||
assert.match(command, /tmux new -As fix-flaky-opencode/);
|
||||
assert.match(command, /unset AGENT_WORKER_TOKEN N8N_DEQUEUE_URL SLACK_BOT_TOKEN/);
|
||||
assert.match(command, /OPENCODE_CONFIG_CONTENT/);
|
||||
assert.match(
|
||||
command,
|
||||
/OPENCODE_CONFIG_CONTENT="\{\\"providers\\":\{\\"openrouter\\":\{\\"settings\\":\{\\"apiKey\\":\\"\{env:OPENROUTER_API_KEY\}\\"\}\}\}\}"/,
|
||||
);
|
||||
assert.match(command, /export N8N_AGENT_RUNTIME=sandbox; unset N8N_AGENT_PROFILE/);
|
||||
assert.match(
|
||||
command,
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { rmSync, readFileSync } from 'node:fs';
|
||||
import { createServer } from 'node:net';
|
||||
import { test } from 'node:test';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import { fakeBinaries } from './fake-bin.mjs';
|
||||
import { parseOpenCodeArgs } from '../../scripts/cloud-session-opencode.mjs';
|
||||
import { parseOpenCodeArgs, parseOpenCodeVersion } from '../../scripts/cloud-session-opencode.mjs';
|
||||
|
||||
const script = fileURLToPath(new URL('../../scripts/cloud-session.mjs', import.meta.url));
|
||||
const secret = 'a'.repeat(64);
|
||||
@@ -31,8 +32,9 @@ if (args[0] === 'codespace' && args[1] === 'list') {
|
||||
const server = require('node:http').createServer((req, res) => {
|
||||
const expected = 'Basic ' + Buffer.from('opencode:' + '${secret}').toString('base64');
|
||||
if (process.env.TEST_UNAUTHORIZED || req.headers.authorization !== expected) { res.writeHead(401).end(); return; }
|
||||
if (req.url !== '/api/info') { res.writeHead(404).end(); return; }
|
||||
res.setHeader('content-type', 'application/json');
|
||||
res.end(JSON.stringify({ healthy: true, version: process.env.TEST_SERVER_VERSION || '1.2.3' }));
|
||||
res.end(JSON.stringify({ version: process.env.TEST_SERVER_VERSION || '2.4.1', pid: process.pid, urls: [], paths: { tmp: '/tmp' } }));
|
||||
});
|
||||
server.listen(port, '127.0.0.1');
|
||||
if (process.env.TEST_TUNNEL_DROP) setTimeout(() => process.exit(1), 500);
|
||||
@@ -59,9 +61,15 @@ if (args[0] === 'codespace' && args[1] === 'list') {
|
||||
`
|
||||
if (args[0] === '--version') {
|
||||
if (process.env.TEST_NO_CLIENT) process.exit(1);
|
||||
console.log(process.env.TEST_CLIENT_VERSION || '1.2.3');
|
||||
console.log(process.env.TEST_CLIENT_VERSION || 'opencode v2.4.1');
|
||||
} else {
|
||||
log({ command: 'opencode', args, password: process.env.OPENCODE_SERVER_PASSWORD });
|
||||
log({
|
||||
command: 'opencode',
|
||||
args,
|
||||
password: process.env.OPENCODE_PASSWORD,
|
||||
legacyPassword: process.env.OPENCODE_SERVER_PASSWORD ?? null,
|
||||
legacyUsername: process.env.OPENCODE_SERVER_USERNAME ?? null,
|
||||
});
|
||||
if (process.env.TEST_CLIENT_WAIT) setInterval(() => {}, 1000);
|
||||
}
|
||||
`,
|
||||
@@ -113,6 +121,26 @@ function stopped(pid) {
|
||||
}
|
||||
}
|
||||
|
||||
async function freePort() {
|
||||
const server = createServer();
|
||||
await new Promise((resolve, reject) => {
|
||||
server.once('error', reject);
|
||||
server.listen(0, '127.0.0.1', resolve);
|
||||
});
|
||||
const { port } = server.address();
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
return port;
|
||||
}
|
||||
|
||||
test('parses V2 and bare semver OpenCode version output', () => {
|
||||
assert.equal(parseOpenCodeVersion('opencode v2.4.1\n'), '2.4.1');
|
||||
assert.equal(parseOpenCodeVersion('opencode v2.3.2-rc.1+build.4\n'), '2.3.2-rc.1+build.4');
|
||||
assert.equal(parseOpenCodeVersion('2.4.1\n'), '2.4.1');
|
||||
assert.equal(parseOpenCodeVersion('1.18.25'), '1.18.25');
|
||||
assert.equal(parseOpenCodeVersion(''), undefined);
|
||||
assert.equal(parseOpenCodeVersion('unexpected output'), undefined);
|
||||
});
|
||||
|
||||
test('parses options before or after the workspace and rejects unsupported flags', () => {
|
||||
assert.equal(parseOpenCodeArgs(['--web']).port, 4096);
|
||||
assert.equal(parseOpenCodeArgs([]).port, 0);
|
||||
@@ -152,13 +180,12 @@ test(
|
||||
const tunnel = calls.find((call) => call.command === 'gh' && call.args.includes('-N'));
|
||||
assert.match(tunnel.args.at(-1), /^127\.0\.0\.1:\d+:127\.0\.0\.1:4242$/);
|
||||
const client = calls.find((call) => call.command === 'opencode');
|
||||
assert.deepEqual(client.args.slice(2), [
|
||||
'--dir',
|
||||
'/workspaces/wt-fix-flaky',
|
||||
'--session',
|
||||
'ses_saved',
|
||||
]);
|
||||
assert.equal(client.args[0], '--server');
|
||||
assert.match(client.args[1], /^http:\/\/127\.0\.0\.1:\d+$/);
|
||||
assert.deepEqual(client.args.slice(2), ['--session', 'ses_saved', '/workspaces/wt-fix-flaky']);
|
||||
assert.equal(client.password, secret);
|
||||
assert.equal(client.legacyPassword, null);
|
||||
assert.equal(client.legacyUsername, null);
|
||||
assert.ok(!result.output.includes(secret));
|
||||
assert.ok(calls.some((call) => call.event === 'tunnel-stopped'));
|
||||
const pid = calls.find((call) => call.event === 'ssh-child').pid;
|
||||
@@ -167,11 +194,13 @@ test(
|
||||
);
|
||||
|
||||
test('starts a new conversation for --new instead of continuing', { timeout: 15000 }, async (t) => {
|
||||
const f = fixture(t);
|
||||
const f = fixture(t, { TEST_CLIENT_VERSION: '2.4.1' });
|
||||
const result = await f.start(['fix-flaky', '--new']).done;
|
||||
assert.equal(result.code, 0, result.output);
|
||||
const client = f.calls().find((call) => call.command === 'opencode');
|
||||
assert.deepEqual(client.args.slice(2), ['--dir', '/workspaces/wt-fix-flaky']);
|
||||
assert.equal(client.args[0], '--server');
|
||||
assert.match(client.args[1], /^http:\/\/127\.0\.0\.1:\d+$/);
|
||||
assert.deepEqual(client.args.slice(2), ['/workspaces/wt-fix-flaky']);
|
||||
});
|
||||
|
||||
for (const signal of ['SIGINT', 'SIGHUP']) {
|
||||
@@ -180,7 +209,8 @@ for (const signal of ['SIGINT', 'SIGHUP']) {
|
||||
{ timeout: 15000 },
|
||||
async (t) => {
|
||||
const f = fixture(t, { TEST_NO_CLIENT: '1' });
|
||||
const run = f.start(['--web', 'fix-flaky']);
|
||||
const port = await freePort();
|
||||
const run = f.start(['--web', '--port', String(port), 'fix-flaky']);
|
||||
const browser = await waitFor(() => f.calls().find((call) => call.command === 'browser'));
|
||||
const url = new URL(browser.args[0]);
|
||||
assert.equal(
|
||||
@@ -188,7 +218,7 @@ for (const signal of ['SIGINT', 'SIGHUP']) {
|
||||
`/${Buffer.from('/workspaces/wt-fix-flaky').toString('base64url')}/session/ses_saved`,
|
||||
);
|
||||
assert.equal(url.password, '');
|
||||
const response = await fetch(`${url.origin}/global/health`);
|
||||
const response = await fetch(`${url.origin}/api/info`);
|
||||
assert.equal(response.status, 200);
|
||||
await response.text();
|
||||
run.child.kill(signal);
|
||||
@@ -203,8 +233,8 @@ for (const signal of ['SIGINT', 'SIGHUP']) {
|
||||
for (const [label, env, message] of [
|
||||
[
|
||||
'a version mismatch',
|
||||
{ TEST_SERVER_VERSION: '1.14.22' },
|
||||
/versions differ.*npm install -g opencode-ai@1\.14\.22/,
|
||||
{ TEST_SERVER_VERSION: '2.3.2' },
|
||||
/versions differ.*npm install -g @opencode\/cli@2\.3\.2/,
|
||||
],
|
||||
['an authentication failure', { TEST_UNAUTHORIZED: '1' }, /health check failed \(401\)/],
|
||||
['a tunnel startup failure', { TEST_TUNNEL_FAIL: '1' }, /SSH tunnel closed/],
|
||||
|
||||
@@ -45,24 +45,23 @@ async function freePort() {
|
||||
return port;
|
||||
}
|
||||
|
||||
async function request(server, path, directory, options = {}, timeout = 60_000) {
|
||||
async function request(server, path, options = {}, timeout = 60_000) {
|
||||
return await fetch(`http://127.0.0.1:${server.port}${path}`, {
|
||||
...options,
|
||||
headers: {
|
||||
authorization: `Basic ${Buffer.from(`opencode:${server.password}`).toString('base64')}`,
|
||||
'x-opencode-directory': encodeURIComponent(directory),
|
||||
'content-type': 'application/json',
|
||||
},
|
||||
signal: AbortSignal.timeout(timeout),
|
||||
});
|
||||
}
|
||||
|
||||
async function health(server, directory) {
|
||||
async function health(server) {
|
||||
try {
|
||||
const response = await request(server, '/global/health', directory, {}, 3000);
|
||||
const response = await request(server, '/api/info', {}, 3000);
|
||||
if (!response.ok) return undefined;
|
||||
const result = await response.json();
|
||||
return result.healthy === true && typeof result.version === 'string' ? result : undefined;
|
||||
return typeof result?.version === 'string' && result.version.length > 0 ? result : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
@@ -70,9 +69,9 @@ async function health(server, directory) {
|
||||
|
||||
const serverFile = (stateDir) => join(stateDir, 'server.json');
|
||||
|
||||
async function runningServer({ stateDir, mainDirectory }) {
|
||||
async function runningServer({ stateDir }) {
|
||||
const previous = readJson(serverFile(stateDir));
|
||||
return previous && (await health(previous, mainDirectory)) ? previous : undefined;
|
||||
return previous && (await health(previous)) ? previous : undefined;
|
||||
}
|
||||
|
||||
async function startServer({ stateDir, mainDirectory, workspaces }) {
|
||||
@@ -94,12 +93,14 @@ async function startServer({ stateDir, mainDirectory, workspaces }) {
|
||||
'unset AGENT_WORKER_TOKEN N8N_DEQUEUE_URL SLACK_BOT_TOKEN',
|
||||
`export TURBO_CACHE_DIR=${quote(join(workspaces, '.turbo-cache'))}`,
|
||||
`[ -d "$TURBO_CACHE_DIR" ] || cp -r ${quote(join(mainDirectory, '.turbo/cache'))} "$TURBO_CACHE_DIR" 2>/dev/null || mkdir -p "$TURBO_CACHE_DIR"`,
|
||||
`export OPENCODE_SERVER_USERNAME=opencode OPENCODE_SERVER_PASSWORD=${quote(server.password)}`,
|
||||
'export OPENCODE_EXPERIMENTAL_CODE_MODE=true',
|
||||
`export OPENCODE_PASSWORD=${quote(server.password)}`,
|
||||
`export OPENCODE_CONFIG_CONTENT=${quote(
|
||||
JSON.stringify({
|
||||
enabled_providers: ['openrouter'],
|
||||
provider: { openrouter: { options: { apiKey: '{env:OPENROUTER_API_KEY}' } } },
|
||||
policies: [
|
||||
{ action: 'provider.use', resource: '*', effect: 'deny' },
|
||||
{ action: 'provider.use', resource: 'openrouter', effect: 'allow' },
|
||||
],
|
||||
providers: { openrouter: { settings: { apiKey: '{env:OPENROUTER_API_KEY}' } } },
|
||||
}),
|
||||
)}`,
|
||||
// Interactive sessions use the harness sandbox runtime without a profile.
|
||||
@@ -114,7 +115,7 @@ async function startServer({ stateDir, mainDirectory, workspaces }) {
|
||||
run('tmux', ['new-session', '-d', '-s', tmuxSession, `bash ${quote(launcher)}`]);
|
||||
console.error('Starting the OpenCode server…');
|
||||
for (let attempt = 0; attempt < 60; attempt++) {
|
||||
if (await health(server, mainDirectory)) return server;
|
||||
if (await health(server)) return server;
|
||||
await delay(500);
|
||||
}
|
||||
throw new Error(`OpenCode did not become ready. Check ${stateDir}/server.log.`);
|
||||
@@ -172,22 +173,22 @@ function prepareWorkspace({ name, directory, mainDirectory, stateDir }) {
|
||||
// each worktree resumes its own most recently updated root conversation.
|
||||
async function resolveSession({ name, fresh, directory, server }) {
|
||||
if (!fresh) {
|
||||
const query = new URLSearchParams({ directory, roots: 'true' });
|
||||
const response = await request(server, `/session?${query}`, directory);
|
||||
const query = new URLSearchParams({ directory, parentID: 'null', order: 'desc' });
|
||||
const response = await request(server, `/api/session?${query}`);
|
||||
if (!response.ok) throw new Error(`Cannot list OpenCode sessions (${response.status}).`);
|
||||
const sessions = await response.json();
|
||||
const latest = Array.isArray(sessions)
|
||||
? sessions.find((entry) => typeof entry?.id === 'string' && entry.id.length > 0)
|
||||
const result = await response.json();
|
||||
const latest = Array.isArray(result?.data)
|
||||
? result.data.find((entry) => typeof entry?.id === 'string' && entry.id.length > 0)
|
||||
: undefined;
|
||||
if (latest) return latest.id;
|
||||
}
|
||||
const response = await request(server, '/session', directory, {
|
||||
const response = await request(server, '/api/session', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ title: `n8n: ${name}` }),
|
||||
body: JSON.stringify({ title: `n8n: ${name}`, location: { directory } }),
|
||||
});
|
||||
if (!response.ok) throw new Error(`Cannot create OpenCode session (${response.status}).`);
|
||||
const session = await response.json();
|
||||
if (typeof session.id !== 'string' || session.directory !== directory)
|
||||
const session = (await response.json())?.data;
|
||||
if (typeof session?.id !== 'string' || session.location?.directory !== directory)
|
||||
throw new Error('OpenCode returned an invalid session.');
|
||||
return session.id;
|
||||
}
|
||||
@@ -203,7 +204,7 @@ export async function prepareOpenCode({
|
||||
if (!/^\w[\w-]*$/.test(name)) throw new Error('Invalid OpenCode workspace name.');
|
||||
mkdirSync(stateDir, { recursive: true, mode: 0o700 });
|
||||
const directory = name === 'agent' ? mainDirectory : join(workspaces, `wt-${name}`);
|
||||
let server = await runningServer({ stateDir, mainDirectory });
|
||||
let server = await runningServer({ stateDir });
|
||||
// On a cold start, fail before the worktree install when OpenCode is missing on the Codespace.
|
||||
if (!server) execFileSync('opencode', ['--version'], { stdio: ['ignore', 'pipe', 'inherit'] });
|
||||
prepareWorkspace({ name, directory, mainDirectory, stateDir });
|
||||
|
||||
@@ -71,49 +71,55 @@ if (args[0] === 'has-session') {
|
||||
bin(
|
||||
'opencode',
|
||||
`
|
||||
if (args[0] === '--version') { console.log('1.2.3'); process.exit(0); }
|
||||
if (args[0] === '--version') { console.log('opencode v2.4.1'); process.exit(0); }
|
||||
fs.writeFileSync(file('server-env.json'), JSON.stringify({
|
||||
worker: !!process.env.AGENT_WORKER_TOKEN, queue: !!process.env.N8N_DEQUEUE_URL, slack: !!process.env.SLACK_BOT_TOKEN,
|
||||
password: !!process.env.OPENCODE_PASSWORD,
|
||||
legacyPassword: !!process.env.OPENCODE_SERVER_PASSWORD,
|
||||
legacyUsername: !!process.env.OPENCODE_SERVER_USERNAME,
|
||||
codeMode: !!process.env.OPENCODE_EXPERIMENTAL_CODE_MODE,
|
||||
cache: process.env.TURBO_CACHE_DIR, config: JSON.parse(process.env.OPENCODE_CONFIG_CONTENT),
|
||||
runtime: process.env.N8N_AGENT_RUNTIME, profile: process.env.N8N_AGENT_PROFILE ?? null,
|
||||
}));
|
||||
let sessions = fs.existsSync(file('sessions.json')) ? JSON.parse(fs.readFileSync(file('sessions.json'), 'utf8')) : {};
|
||||
const server = require('node:http').createServer(async (req, res) => {
|
||||
res.setHeader('content-type', 'application/json');
|
||||
const expected = 'Basic ' + Buffer.from('opencode:' + process.env.OPENCODE_SERVER_PASSWORD).toString('base64');
|
||||
const expected = 'Basic ' + Buffer.from('opencode:' + process.env.OPENCODE_PASSWORD).toString('base64');
|
||||
if (req.headers.authorization !== expected) { res.writeHead(401).end('{}'); return; }
|
||||
const directory = decodeURIComponent(req.headers['x-opencode-directory']);
|
||||
if (req.url === '/global/health') { res.end(JSON.stringify({ healthy:true, version:'1.2.3' })); return; }
|
||||
if (req.method === 'POST' && req.url === '/session') {
|
||||
if (req.url === '/api/info') {
|
||||
res.end(JSON.stringify({ version: '2.4.1', pid: process.pid, urls: [], paths: { tmp: '/tmp' } }));
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/api/session') {
|
||||
if (fs.existsSync(file('reject-create'))) { res.writeHead(503).end('{}'); return; }
|
||||
let body = '';
|
||||
for await (const chunk of req) body += chunk;
|
||||
const payload = JSON.parse(body);
|
||||
const id = 'ses_' + (Object.keys(sessions).length + 1);
|
||||
sessions[id] = { id, directory, title: JSON.parse(body).title };
|
||||
sessions[id] = { id, title: payload.title, location: { directory: payload.location?.directory } };
|
||||
fs.writeFileSync(file('sessions.json'), JSON.stringify(sessions));
|
||||
res.end(JSON.stringify(sessions[id])); return;
|
||||
res.end(JSON.stringify({ data: sessions[id] })); return;
|
||||
}
|
||||
if (fs.existsSync(file('reject-session'))) { res.writeHead(503).end('{}'); return; }
|
||||
const url = new URL(req.url, 'http://localhost');
|
||||
if (url.pathname === '/session') {
|
||||
// Newest first, like the real server. Filter on the query, not the header,
|
||||
// so the test fails when the launcher omits either parameter. The
|
||||
// child-session file models a subagent conversation that the roots query
|
||||
// flag must exclude.
|
||||
if (url.pathname === '/api/session') {
|
||||
// Newest first, like the real server. Filter on the query parameters so the
|
||||
// test fails when the launcher omits directory or parentID=null. The
|
||||
// child-session file models a subagent conversation that parentID=null must
|
||||
// exclude.
|
||||
const directory = url.searchParams.get('directory');
|
||||
const roots = url.searchParams.get('roots') === 'true';
|
||||
const roots = url.searchParams.get('parentID') === 'null';
|
||||
const order = url.searchParams.get('order');
|
||||
const stored = Object.values(sessions);
|
||||
if (fs.existsSync(file('child-session')))
|
||||
stored.push({ id: 'ses_child', directory, title: 'child', parentID: 'ses_1' });
|
||||
const list = stored
|
||||
.filter(s => s.directory === directory && (!roots || !s.parentID))
|
||||
.reverse();
|
||||
if (fs.existsSync(file('extra-session'))) list.unshift({ id: 'ses_extra', directory, title: 'TUI session' });
|
||||
res.end(JSON.stringify(list)); return;
|
||||
stored.push({ id: 'ses_child', title: 'child', parentID: 'ses_1', location: { directory } });
|
||||
let list = stored.filter(s => s.location?.directory === directory && (!roots || !s.parentID));
|
||||
if (order !== 'asc') list = list.reverse();
|
||||
if (fs.existsSync(file('extra-session')))
|
||||
list.unshift({ id: 'ses_extra', title: 'TUI session', location: { directory } });
|
||||
res.end(JSON.stringify({ data: list, cursor: { previous: null, next: null } })); return;
|
||||
}
|
||||
const session = sessions[req.url.split('/').at(-1)];
|
||||
if (!session) { res.writeHead(404).end('{}'); return; }
|
||||
res.end(JSON.stringify(session));
|
||||
res.writeHead(404).end('{}');
|
||||
});
|
||||
server.listen(+args[args.indexOf('--port') + 1], '127.0.0.1');
|
||||
`,
|
||||
@@ -178,7 +184,7 @@ test(
|
||||
assert.equal(webbed.sessionID, 'ses_1');
|
||||
const created = JSON.parse(readFileSync(join(f.dir, 'sessions.json'), 'utf8'));
|
||||
assert.equal(created.ses_1.title, 'n8n: fix-flaky');
|
||||
assert.equal(created.ses_1.directory, join(f.dir, 'wt-fix-flaky'));
|
||||
assert.equal(created.ses_1.location.directory, join(f.dir, 'wt-fix-flaky'));
|
||||
assert.equal((await f.prepare({ name: 'fix-flaky', web: true })).sessionID, 'ses_1');
|
||||
assert.equal((await f.prepare({ name: 'another-task', web: true })).sessionID, 'ses_2');
|
||||
writeFileSync(join(f.dir, 'extra-session'), '');
|
||||
@@ -192,9 +198,16 @@ test(
|
||||
assert.equal((await f.prepare({ name: 'fix-flaky', web: true })).sessionID, fresh.sessionID);
|
||||
const env = JSON.parse(readFileSync(join(f.dir, 'server-env.json'), 'utf8'));
|
||||
assert.deepEqual([env.worker, env.queue, env.slack], [false, false, false]);
|
||||
assert.deepEqual(
|
||||
[env.password, env.legacyPassword, env.legacyUsername, env.codeMode],
|
||||
[true, false, false, false],
|
||||
);
|
||||
assert.equal(env.cache, join(f.dir, '.turbo-cache'));
|
||||
assert.equal(env.config.provider.openrouter.options.apiKey, '{env:OPENROUTER_API_KEY}');
|
||||
assert.deepEqual(env.config.enabled_providers, ['openrouter']);
|
||||
assert.equal(env.config.providers.openrouter.settings.apiKey, '{env:OPENROUTER_API_KEY}');
|
||||
assert.deepEqual(env.config.policies, [
|
||||
{ action: 'provider.use', resource: '*', effect: 'deny' },
|
||||
{ action: 'provider.use', resource: 'openrouter', effect: 'allow' },
|
||||
]);
|
||||
assert.deepEqual([env.runtime, env.profile], ['sandbox', null]);
|
||||
assert.equal(statSync(join(f.dir, '.n8n-opencode')).mode & 0o777, 0o700);
|
||||
for (const file of ['serve.sh', 'server.json']) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"repository": "n8n-io/cat-bot",
|
||||
"releaseTag": "harness-v0.11.0",
|
||||
"version": "0.11.0",
|
||||
"assetName": "n8n-opencode-harness-0.11.0.tgz"
|
||||
"releaseTag": "harness-v1.1.0",
|
||||
"version": "1.1.0",
|
||||
"assetName": "n8n-opencode-harness-1.1.0.tgz"
|
||||
}
|
||||
+61
-20
@@ -8,15 +8,19 @@ import {
|
||||
readFileSync,
|
||||
renameSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
|
||||
const REPOSITORY = 'n8n-io/cat-bot';
|
||||
const BUNDLE_ROOT = 'n8n-opencode-harness';
|
||||
const PLUGIN_FILE = 'n8n-harness.js';
|
||||
const PLUGIN_NAME = 'n8n-harness';
|
||||
const PLUGIN_ENTRY = 'index.js';
|
||||
const LEGACY_PLUGIN_FILE = 'n8n-harness.js';
|
||||
const PLUGIN_SUBPATH = join(PLUGIN_NAME, PLUGIN_ENTRY);
|
||||
const MANAGED_HEADER = '// Managed by n8n agent-harness. Do not edit.';
|
||||
const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
|
||||
export function validateLock(lock) {
|
||||
@@ -64,25 +68,62 @@ export function downloadReleaseAsset(lock, destination, { run = execFileSync } =
|
||||
}
|
||||
}
|
||||
|
||||
function activatePlugin(pluginPath, pluginLink) {
|
||||
if (existsSync(pluginLink) && !lstatSync(pluginLink).isSymbolicLink()) {
|
||||
throw new Error(`Refusing to overwrite the non-symlink path ${pluginLink}.`);
|
||||
}
|
||||
mkdirSync(dirname(pluginLink), { recursive: true });
|
||||
const temporaryLink = `${pluginLink}.tmp-${process.pid}`;
|
||||
function statIfPresent(targetPath) {
|
||||
try {
|
||||
rmSync(temporaryLink, { force: true });
|
||||
symlinkSync(pluginPath, temporaryLink);
|
||||
renameSync(temporaryLink, pluginLink);
|
||||
} finally {
|
||||
rmSync(temporaryLink, { force: true });
|
||||
return lstatSync(targetPath);
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') return undefined;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function buildPluginShim(pluginPath) {
|
||||
const targetUrl = pathToFileURL(resolve(pluginPath)).href;
|
||||
return `${MANAGED_HEADER}\nexport { default } from ${JSON.stringify(targetUrl)};\n`;
|
||||
}
|
||||
|
||||
function activatePlugin(pluginPath, pluginDir) {
|
||||
const pluginDirStat = statIfPresent(pluginDir);
|
||||
if (pluginDirStat && (pluginDirStat.isSymbolicLink() || !pluginDirStat.isDirectory())) {
|
||||
throw new Error(`Refusing to overwrite the unmanaged plugin path ${pluginDir}.`);
|
||||
}
|
||||
|
||||
const pluginEntry = join(pluginDir, PLUGIN_ENTRY);
|
||||
const pluginEntryStat = statIfPresent(pluginEntry);
|
||||
if (pluginEntryStat) {
|
||||
if (!pluginEntryStat.isFile()) {
|
||||
throw new Error(`Refusing to overwrite the unmanaged plugin path ${pluginEntry}.`);
|
||||
}
|
||||
const existing = readFileSync(pluginEntry, 'utf8');
|
||||
if (!existing.startsWith(`${MANAGED_HEADER}\n`)) {
|
||||
throw new Error(`Refusing to overwrite the unmanaged plugin file ${pluginEntry}.`);
|
||||
}
|
||||
}
|
||||
|
||||
mkdirSync(pluginDir, { recursive: true });
|
||||
const temporaryEntry = join(pluginDir, `.${PLUGIN_ENTRY}.tmp-${process.pid}`);
|
||||
try {
|
||||
// OpenCode V2 resolves relative imports from the symlink path, so re-export
|
||||
// from the absolute cache file URL instead of symlinking the plugin directory.
|
||||
writeFileSync(temporaryEntry, buildPluginShim(pluginPath));
|
||||
renameSync(temporaryEntry, pluginEntry);
|
||||
} finally {
|
||||
rmSync(temporaryEntry, { force: true });
|
||||
}
|
||||
|
||||
// Remove the V1 single-file symlink without touching unmanaged user files.
|
||||
const legacyPluginLink = join(dirname(pluginDir), LEGACY_PLUGIN_FILE);
|
||||
if (statIfPresent(legacyPluginLink)?.isSymbolicLink()) {
|
||||
rmSync(legacyPluginLink, { force: true });
|
||||
}
|
||||
|
||||
return pluginEntry;
|
||||
}
|
||||
|
||||
export function installAgentHarness({
|
||||
lockPath = join(REPO_ROOT, 'agent-harness.lock.json'),
|
||||
cacheRoot = join(homedir(), '.cache', 'n8n-agent-harness'),
|
||||
pluginLink = join(homedir(), '.config', 'opencode', 'plugins', PLUGIN_FILE),
|
||||
pluginDir = join(homedir(), '.config', 'opencode', 'plugins', PLUGIN_NAME),
|
||||
download = downloadReleaseAsset,
|
||||
extract = (archive, destination) =>
|
||||
execFileSync('tar', ['-xzf', archive, '-C', destination], { stdio: 'pipe' }),
|
||||
@@ -90,7 +131,7 @@ export function installAgentHarness({
|
||||
const lock = readLock(lockPath);
|
||||
const versionDir = join(cacheRoot, lock.version);
|
||||
const bundlePath = join(versionDir, BUNDLE_ROOT);
|
||||
const pluginPath = join(bundlePath, 'plugins', PLUGIN_FILE);
|
||||
const pluginPath = join(bundlePath, 'plugins', PLUGIN_SUBPATH);
|
||||
mkdirSync(cacheRoot, { recursive: true });
|
||||
|
||||
// The version cache is write-once after a successful installation.
|
||||
@@ -104,8 +145,8 @@ export function installAgentHarness({
|
||||
download(lock, stagedVersion);
|
||||
// Cat-bot validates archive contents before publishing these pinned bytes.
|
||||
extract(archivePath, stagedVersion);
|
||||
if (!existsSync(join(stagedVersion, BUNDLE_ROOT, 'plugins', PLUGIN_FILE))) {
|
||||
throw new Error(`The agent harness bundle has no ${PLUGIN_FILE} plugin.`);
|
||||
if (!existsSync(join(stagedVersion, BUNDLE_ROOT, 'plugins', PLUGIN_SUBPATH))) {
|
||||
throw new Error(`The agent harness bundle has no ${PLUGIN_SUBPATH} plugin.`);
|
||||
}
|
||||
rmSync(versionDir, { recursive: true, force: true });
|
||||
renameSync(stagedVersion, versionDir);
|
||||
@@ -114,8 +155,8 @@ export function installAgentHarness({
|
||||
}
|
||||
}
|
||||
|
||||
activatePlugin(pluginPath, pluginLink);
|
||||
return { version: lock.version, cacheHit, bundlePath, pluginLink };
|
||||
const pluginEntry = activatePlugin(pluginPath, pluginDir);
|
||||
return { version: lock.version, cacheHit, bundlePath, pluginDir, pluginEntry };
|
||||
}
|
||||
|
||||
if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) {
|
||||
|
||||
+148
-25
@@ -2,11 +2,12 @@ import assert from 'node:assert/strict';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import {
|
||||
copyFileSync,
|
||||
existsSync,
|
||||
lstatSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
readlinkSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { afterEach, test } from 'node:test';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
|
||||
import { downloadReleaseAsset, installAgentHarness, validateLock } from './agent-harness.mjs';
|
||||
|
||||
@@ -32,7 +34,25 @@ function fixtureDirectory() {
|
||||
}
|
||||
|
||||
function makeAsset(root, version = '1.2.3') {
|
||||
const source = join(root, 'source');
|
||||
const source = join(root, `source-${version}`);
|
||||
const bundle = join(source, 'n8n-opencode-harness');
|
||||
mkdirSync(join(bundle, 'plugins', 'n8n-harness'), { recursive: true });
|
||||
mkdirSync(join(bundle, 'lib'), { recursive: true });
|
||||
writeFileSync(
|
||||
join(bundle, 'lib', 'n8n-harness.js'),
|
||||
`export const plugin = { id: 'n8n.harness', version: ${JSON.stringify(version)} };\n`,
|
||||
);
|
||||
writeFileSync(
|
||||
join(bundle, 'plugins', 'n8n-harness', 'index.js'),
|
||||
"import { plugin } from '../../lib/n8n-harness.js';\nexport default plugin;\n",
|
||||
);
|
||||
const asset = join(root, `n8n-opencode-harness-${version}.tgz`);
|
||||
execFileSync('tar', ['-czf', asset, '-C', source, 'n8n-opencode-harness']);
|
||||
return asset;
|
||||
}
|
||||
|
||||
function makeLegacyOnlyAsset(root, version = '0.11.0') {
|
||||
const source = join(root, `legacy-source-${version}`);
|
||||
const bundle = join(source, 'n8n-opencode-harness');
|
||||
mkdirSync(join(bundle, 'plugins'), { recursive: true });
|
||||
writeFileSync(join(bundle, 'plugins', 'n8n-harness.js'), 'export default async () => ({});\n');
|
||||
@@ -42,7 +62,7 @@ function makeAsset(root, version = '1.2.3') {
|
||||
}
|
||||
|
||||
function writeLock(root, overrides = {}) {
|
||||
const version = '1.2.3';
|
||||
const version = overrides.version ?? '1.2.3';
|
||||
const lock = {
|
||||
repository: 'n8n-io/cat-bot',
|
||||
releaseTag: `harness-v${version}`,
|
||||
@@ -50,7 +70,7 @@ function writeLock(root, overrides = {}) {
|
||||
assetName: `n8n-opencode-harness-${version}.tgz`,
|
||||
...overrides,
|
||||
};
|
||||
const lockPath = join(root, 'agent-harness.lock.json');
|
||||
const lockPath = join(root, `agent-harness-${version}.lock.json`);
|
||||
writeFileSync(lockPath, JSON.stringify(lock));
|
||||
return lockPath;
|
||||
}
|
||||
@@ -58,7 +78,7 @@ function writeLock(root, overrides = {}) {
|
||||
function installerPaths(root) {
|
||||
return {
|
||||
cacheRoot: join(root, 'cache'),
|
||||
pluginLink: join(root, 'config', 'opencode', 'plugins', 'n8n-harness.js'),
|
||||
pluginDir: join(root, 'config', 'opencode', 'plugins', 'n8n-harness'),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -69,9 +89,9 @@ function copyAsset(asset) {
|
||||
test('validates the pinned release values', () => {
|
||||
const lock = {
|
||||
repository: 'n8n-io/cat-bot',
|
||||
releaseTag: 'harness-v1.2.3',
|
||||
version: '1.2.3',
|
||||
assetName: 'n8n-opencode-harness-1.2.3.tgz',
|
||||
releaseTag: 'harness-v1.1.0',
|
||||
version: '1.1.0',
|
||||
assetName: 'n8n-opencode-harness-1.1.0.tgz',
|
||||
};
|
||||
assert.equal(validateLock(lock), lock);
|
||||
for (const invalid of [
|
||||
@@ -84,22 +104,86 @@ test('validates the pinned release values', () => {
|
||||
}
|
||||
});
|
||||
|
||||
test('installs the pinned release and activates its plugin', () => {
|
||||
test('installs the V2 release, writes a managed shim, and resolves relative bundle imports', async () => {
|
||||
const root = fixtureDirectory();
|
||||
const asset = makeAsset(root);
|
||||
const asset = makeAsset(root, '1.1.0');
|
||||
const result = installAgentHarness({
|
||||
...installerPaths(root),
|
||||
lockPath: writeLock(root),
|
||||
lockPath: writeLock(root, { version: '1.1.0' }),
|
||||
download: copyAsset(asset),
|
||||
});
|
||||
|
||||
assert.equal(result.cacheHit, false);
|
||||
assert.equal(
|
||||
readlinkSync(result.pluginLink),
|
||||
join(result.bundlePath, 'plugins', 'n8n-harness.js'),
|
||||
assert.equal(result.pluginEntry, join(result.pluginDir, 'index.js'));
|
||||
assert.equal(lstatSync(result.pluginDir).isDirectory(), true);
|
||||
assert.equal(lstatSync(result.pluginEntry).isFile(), true);
|
||||
assert.match(
|
||||
readFileSync(result.pluginEntry, 'utf8'),
|
||||
new RegExp(pathToFileURL(join(result.bundlePath, 'plugins', 'n8n-harness', 'index.js')).href),
|
||||
);
|
||||
assert.match(readFileSync(result.pluginLink, 'utf8'), /export default/);
|
||||
assert.deepEqual(readdirSync(join(root, 'cache')), ['1.2.3']);
|
||||
assert.deepEqual(readdirSync(join(root, 'cache')), ['1.1.0']);
|
||||
|
||||
// Importing the shim must resolve relative imports inside the cached V2 bundle.
|
||||
const loaded = await import(pathToFileURL(result.pluginEntry).href);
|
||||
assert.deepEqual(loaded.default, { id: 'n8n.harness', version: '1.1.0' });
|
||||
});
|
||||
|
||||
test('updates a previously managed shim to a newer release', async () => {
|
||||
const root = fixtureDirectory();
|
||||
const paths = installerPaths(root);
|
||||
installAgentHarness({
|
||||
...paths,
|
||||
lockPath: writeLock(root, { version: '1.0.0' }),
|
||||
download: copyAsset(makeAsset(root, '1.0.0')),
|
||||
});
|
||||
const updated = installAgentHarness({
|
||||
...paths,
|
||||
lockPath: writeLock(root, { version: '1.1.0' }),
|
||||
download: copyAsset(makeAsset(root, '1.1.0')),
|
||||
});
|
||||
|
||||
const loaded = await import(`${pathToFileURL(updated.pluginEntry).href}?updated=1`);
|
||||
assert.deepEqual(loaded.default, { id: 'n8n.harness', version: '1.1.0' });
|
||||
});
|
||||
|
||||
test('removes live and dangling legacy n8n-harness.js symlinks during activation', () => {
|
||||
for (const dangling of [false, true]) {
|
||||
const root = fixtureDirectory();
|
||||
const asset = makeAsset(root);
|
||||
const paths = installerPaths(root);
|
||||
const pluginsDir = dirname(paths.pluginDir);
|
||||
mkdirSync(pluginsDir, { recursive: true });
|
||||
const legacyLink = join(pluginsDir, 'n8n-harness.js');
|
||||
const legacyTarget = join(root, 'legacy-target.js');
|
||||
if (!dangling) writeFileSync(legacyTarget, 'export default async () => ({});\n');
|
||||
symlinkSync(legacyTarget, legacyLink);
|
||||
|
||||
installAgentHarness({
|
||||
...paths,
|
||||
lockPath: writeLock(root),
|
||||
download: copyAsset(asset),
|
||||
});
|
||||
|
||||
assert.throws(() => lstatSync(legacyLink), { code: 'ENOENT' });
|
||||
}
|
||||
});
|
||||
|
||||
test('does not delete an unmanaged non-symlink legacy n8n-harness.js file', () => {
|
||||
const root = fixtureDirectory();
|
||||
const asset = makeAsset(root);
|
||||
const paths = installerPaths(root);
|
||||
const pluginsDir = dirname(paths.pluginDir);
|
||||
mkdirSync(pluginsDir, { recursive: true });
|
||||
const legacyFile = join(pluginsDir, 'n8n-harness.js');
|
||||
writeFileSync(legacyFile, 'user legacy file\n');
|
||||
|
||||
installAgentHarness({
|
||||
...paths,
|
||||
lockPath: writeLock(root),
|
||||
download: copyAsset(asset),
|
||||
});
|
||||
|
||||
assert.equal(readFileSync(legacyFile, 'utf8'), 'user legacy file\n');
|
||||
});
|
||||
|
||||
test('reuses an installed release without downloading it again', () => {
|
||||
@@ -119,14 +203,16 @@ test('reuses an installed release without downloading it again', () => {
|
||||
assert.equal(result.cacheHit, true);
|
||||
});
|
||||
|
||||
test('keeps the active plugin when installation fails', () => {
|
||||
test('keeps the active plugin and legacy symlink when installation fails', () => {
|
||||
const root = fixtureDirectory();
|
||||
const asset = makeAsset(root);
|
||||
const paths = installerPaths(root);
|
||||
mkdirSync(dirname(paths.pluginLink), { recursive: true });
|
||||
const pluginsDir = dirname(paths.pluginDir);
|
||||
mkdirSync(pluginsDir, { recursive: true });
|
||||
const legacyLink = join(pluginsDir, 'n8n-harness.js');
|
||||
const previous = join(root, 'previous-plugin.js');
|
||||
writeFileSync(previous, 'previous plugin\n');
|
||||
symlinkSync(previous, paths.pluginLink);
|
||||
symlinkSync(previous, legacyLink);
|
||||
|
||||
assert.throws(
|
||||
() =>
|
||||
@@ -140,15 +226,31 @@ test('keeps the active plugin when installation fails', () => {
|
||||
}),
|
||||
/extraction failed/,
|
||||
);
|
||||
assert.equal(readlinkSync(paths.pluginLink), previous);
|
||||
assert.equal(lstatSync(legacyLink).isSymbolicLink(), true);
|
||||
assert.equal(existsSync(paths.pluginDir), false);
|
||||
});
|
||||
|
||||
test('does not overwrite a user plugin file', () => {
|
||||
test('rejects bundles without the V2 plugin entrypoint', () => {
|
||||
const root = fixtureDirectory();
|
||||
const asset = makeLegacyOnlyAsset(root, '0.11.0');
|
||||
assert.throws(
|
||||
() =>
|
||||
installAgentHarness({
|
||||
...installerPaths(root),
|
||||
lockPath: writeLock(root, { version: '0.11.0' }),
|
||||
download: copyAsset(asset),
|
||||
}),
|
||||
/has no n8n-harness\/index\.js plugin/,
|
||||
);
|
||||
});
|
||||
|
||||
test('does not overwrite unmanaged user plugin files or symlinks', () => {
|
||||
const root = fixtureDirectory();
|
||||
const asset = makeAsset(root);
|
||||
const paths = installerPaths(root);
|
||||
mkdirSync(dirname(paths.pluginLink), { recursive: true });
|
||||
writeFileSync(paths.pluginLink, 'user plugin\n');
|
||||
mkdirSync(paths.pluginDir, { recursive: true });
|
||||
const userEntry = join(paths.pluginDir, 'index.js');
|
||||
writeFileSync(userEntry, 'export default { id: "user.custom" };\n');
|
||||
|
||||
assert.throws(
|
||||
() =>
|
||||
@@ -157,15 +259,36 @@ test('does not overwrite a user plugin file', () => {
|
||||
lockPath: writeLock(root),
|
||||
download: copyAsset(asset),
|
||||
}),
|
||||
/non-symlink path/,
|
||||
/unmanaged plugin file/,
|
||||
);
|
||||
assert.equal(readFileSync(userEntry, 'utf8'), 'export default { id: "user.custom" };\n');
|
||||
|
||||
// Also refuse when the plugin directory itself is a symlink to another directory.
|
||||
const symlinkRoot = fixtureDirectory();
|
||||
const symlinkPaths = installerPaths(symlinkRoot);
|
||||
const targetDir = join(symlinkRoot, 'user-plugin-dir');
|
||||
mkdirSync(targetDir, { recursive: true });
|
||||
writeFileSync(join(targetDir, 'index.js'), 'original target\n');
|
||||
mkdirSync(dirname(symlinkPaths.pluginDir), { recursive: true });
|
||||
symlinkSync(targetDir, symlinkPaths.pluginDir);
|
||||
|
||||
assert.throws(
|
||||
() =>
|
||||
installAgentHarness({
|
||||
...symlinkPaths,
|
||||
lockPath: writeLock(symlinkRoot),
|
||||
download: copyAsset(makeAsset(symlinkRoot)),
|
||||
}),
|
||||
/unmanaged plugin path/,
|
||||
);
|
||||
assert.equal(readFileSync(join(targetDir, 'index.js'), 'utf8'), 'original target\n');
|
||||
});
|
||||
|
||||
test('reports a clear GitHub access failure', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
downloadReleaseAsset(
|
||||
{ repository: 'n8n-io/cat-bot', releaseTag: 'harness-v1.2.3', assetName: 'asset.tgz' },
|
||||
{ repository: 'n8n-io/cat-bot', releaseTag: 'harness-v1.1.0', assetName: 'asset.tgz' },
|
||||
fixtureDirectory(),
|
||||
{
|
||||
run: () => {
|
||||
|
||||
@@ -31,13 +31,19 @@ export function parseOpenCodeArgs(args) {
|
||||
return { name: positionals[0] ?? 'agent', web: !!values.web, fresh: !!values.new, port };
|
||||
}
|
||||
|
||||
export function parseOpenCodeVersion(output) {
|
||||
const match = output
|
||||
.trim()
|
||||
.match(/^(?:opencode\s+v?)?(\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?)$/);
|
||||
return match?.[1];
|
||||
}
|
||||
|
||||
function localVersion() {
|
||||
const result = spawnSync('opencode', ['--version'], { encoding: 'utf8' });
|
||||
if (result.error || result.status !== 0)
|
||||
throw new Error('Install OpenCode locally, or use --web to connect with a browser.');
|
||||
const version = result.stdout.trim();
|
||||
if (!/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(version))
|
||||
throw new Error('Cannot read the local OpenCode version. Use --web or --legacy.');
|
||||
const version = parseOpenCodeVersion(result.stdout);
|
||||
if (!version) throw new Error('Cannot read the local OpenCode version. Use --web or --legacy.');
|
||||
return version;
|
||||
}
|
||||
|
||||
@@ -148,7 +154,7 @@ async function waitForTunnel(url, password, tunnel, signal) {
|
||||
throw new Error('The SSH tunnel closed. Check the SSH output above, then reconnect.');
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(`${url}/global/health`, {
|
||||
response = await fetch(`${url}/api/info`, {
|
||||
headers: { authorization: basicAuth(password) },
|
||||
signal: AbortSignal.any([signal, AbortSignal.timeout(1000)]),
|
||||
});
|
||||
@@ -160,10 +166,10 @@ async function waitForTunnel(url, password, tunnel, signal) {
|
||||
throw new Error(
|
||||
`OpenCode health check failed (${response.status}). Reconnect after checking the remote server.`,
|
||||
);
|
||||
const health = await response.json();
|
||||
if (health.healthy !== true || typeof health.version !== 'string')
|
||||
const info = await response.json();
|
||||
if (typeof info?.version !== 'string' || info.version.length === 0)
|
||||
throw new Error('Invalid OpenCode health response.');
|
||||
return health;
|
||||
return info;
|
||||
}
|
||||
await delay(500, undefined, { signal });
|
||||
}
|
||||
@@ -217,10 +223,10 @@ export async function connectOpenCode(options, ensureCodespace) {
|
||||
],
|
||||
{ stdio: ['ignore', 'ignore', 'inherit'], detached: true },
|
||||
);
|
||||
const health = await waitForTunnel(url, state.password, tunnel, controller.signal);
|
||||
if (version && health.version !== version) {
|
||||
const info = await waitForTunnel(url, state.password, tunnel, controller.signal);
|
||||
if (version && info.version !== version) {
|
||||
throw new Error(
|
||||
`OpenCode versions differ: local ${version}, server ${health.version}. Install the matching version with \`npm install -g opencode-ai@${health.version}\`, or use --web or --legacy. The remote server is still running.`,
|
||||
`OpenCode versions differ: local ${version}, server ${info.version}. Install the matching version with \`npm install -g @opencode/cli@${info.version}\`, or use --web or --legacy. The remote server is still running.`,
|
||||
);
|
||||
}
|
||||
const stopped = new Promise((resolve) =>
|
||||
@@ -235,25 +241,23 @@ export async function connectOpenCode(options, ensureCodespace) {
|
||||
);
|
||||
openBrowser(webUrl);
|
||||
} else {
|
||||
console.log(`Connecting to OpenCode ${health.version} in ${state.directory}…`);
|
||||
console.log(`Connecting to OpenCode ${info.version} in ${state.directory}…`);
|
||||
// OpenCode's own resume spans all worktrees of the repository. The
|
||||
// server resolved the workspace's latest conversation instead, so
|
||||
// target it directly. A fresh TUI conversation needs no target.
|
||||
client = startChild(
|
||||
'opencode',
|
||||
[
|
||||
'attach',
|
||||
'--server',
|
||||
url,
|
||||
'--dir',
|
||||
state.directory,
|
||||
...(state.sessionID ? ['--session', state.sessionID] : []),
|
||||
state.directory,
|
||||
],
|
||||
{
|
||||
stdio: 'inherit',
|
||||
env: {
|
||||
...process.env,
|
||||
OPENCODE_SERVER_PASSWORD: state.password,
|
||||
OPENCODE_SERVER_USERNAME: 'opencode',
|
||||
OPENCODE_PASSWORD: state.password,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
@@ -88,7 +88,7 @@ function ensureCodespace() {
|
||||
const SESSION_SECRETS =
|
||||
'. /usr/local/lib/codespaces-env.sh 2>/dev/null || true; unset AGENT_WORKER_TOKEN N8N_DEQUEUE_URL SLACK_BOT_TOKEN';
|
||||
const OPENCODE_CONFIG =
|
||||
'export OPENCODE_CONFIG_CONTENT="{\\"provider\\":{\\"openrouter\\":{\\"options\\":{\\"apiKey\\":\\"{env:OPENROUTER_API_KEY}\\"}}}}"; export N8N_AGENT_RUNTIME=sandbox; unset N8N_AGENT_PROFILE';
|
||||
'export OPENCODE_CONFIG_CONTENT="{\\"providers\\":{\\"openrouter\\":{\\"settings\\":{\\"apiKey\\":\\"{env:OPENROUTER_API_KEY}\\"}}}}"; export N8N_AGENT_RUNTIME=sandbox; unset N8N_AGENT_PROFILE';
|
||||
// Worktrees share the pnpm store but not the turbo cache; a shared TURBO_CACHE_DIR
|
||||
// (seeded from the main checkout) keeps new-worktree builds at cache-hit speed.
|
||||
const CACHE =
|
||||
|
||||
Reference in new issue
Block a user