Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(acp): honor npm release-age policy for registry adapter pins (PRD-7828) (#4558)
Nick Gomez4ff5fb440404
diff --git a/.changeset/acp-package-release-age.md b/.changeset/acp-package-release-age.mdnew file mode 100644index 000000000..dd0723464--- /dev/null+++ b/.changeset/acp-package-release-age.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Agent startup now respects package release-date policies, using an older allowed release when needed, and explains when no allowed release can be installed.diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdxindex 5b7078fd0..0d1ec3d2a 100644--- a/docs/content/features/editor.mdx+++ b/docs/content/features/editor.mdx@@ -130,6 +130,12 @@ The field also takes attachments when an **In app** agent is selected: drop a fiThe composer stays out of the way where it doesn't belong: it's hidden inside an AI editor's embedded view, while the [docked terminal](#terminal) is open (the terminal is its own AI entry point), and when no doc or folder is open (the empty state's create composer offers the same handoff, attachments included). It's also dismissible — an **Ask AI** badge in the status bar brings it back.+### In-app agent release-date policies++Catalog-managed in-app agents use npm or uv to acquire their adapter. OpenKnowledge preserves your package manager's release-date policy, such as npm's `min-release-age` in your user `.npmrc` or uv's `UV_EXCLUDE_NEWER`: an older eligible release at or below the catalog version may run when the pinned release is too new. npm tries the exact stable pin first and considers older releases only after a dated refusal; uv resolves an isolated tool request bounded by the catalog version. Custom agent commands keep their existing behavior.++A startup error ending with "Try again after an allowed release becomes available." means the requested adapter has no eligible release under that policy. Retry after one becomes eligible; OpenKnowledge does not disable your cooldown. Acquisition contacts your configured package registry or Python index; see [network requests](../reference/what-open-knowledge-writes.mdx#what-leaves-your-machine).+### From a text selectionSelect text in the WYSIWYG editor and the selection bubble menu shows a **Comment** button (Sparkles icon) alongside the formatting controls. Clicking it — or pressing `Cmd+Shift+M` — opens a composer on the selection. What you write there is a [comment](/docs/features/comments): it goes into the project's comment queue rather than to an agent, and you hand a batch of comments over as a separate, deliberate step from the **Comments** tab.diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdxindex 154dce89a..f2f56014f 100644--- a/docs/content/reference/what-open-knowledge-writes.mdx+++ b/docs/content/reference/what-open-knowledge-writes.mdx@@ -351,7 +351,8 @@ None of your content, by default. Everything above is written to your own disk.| Update check | Automatically — on launch and periodically while the desktop app runs | OpenKnowledge update service (`openknowledge.ai/updates`), which redirects to GitHub; sends the app version and channel || First-launch share check | Once, automatically, on the desktop app's first launch | `openknowledge.ai/continue` — redeems a share link if you installed from one || Skill-install report | Automatically, the first time a published skill is actually installed — OpenKnowledge's own built-in and starter-pack skills, and skills you install from a skills.sh listing. Counted once per skill for machine-wide installs (the built-in bundles), and once per skill **per project** for skills installed into a project, since each project gets its own copy in its own editor dirs. Never re-sent on a re-run, a reinstall, an app launch, or reopening a project — an app launch that installs nothing sends nothing. A skill you install by typing a **third-party** repository yourself is **not** reported, and neither is a private, local, or internal-hostname source. A skill bundle you switched off is never installed and so is never reported | `add-skill.vercel.sh` — the skill's name, its source repository, and which agent tools it was installed for. No file contents. This is what gives a published skill an accurate install count. Turn it off in **Settings → Preferences**, by setting `telemetry.skillInstallReports.enabled: false`, or with `DO_NOT_TRACK=1` / `DISABLE_TELEMETRY=1` |-| npm/`npx` fetch | During install (CLI) | The npm registry |+| npm/`npx` fetch | During CLI installation and catalog-managed in-app agent startup, including package admission probes, package downloads, and cache revalidation | Your configured npm registry (the public npm registry by default); package names, version constraints, and configured registry credentials, without document content |+| uv/`uvx` fetch | When starting a catalog-managed Python in-app agent, including resolution and tool installation | Your configured Python package index (PyPI by default); package names, version constraints, and configured index credentials, without document content |Local diagnostic logs and telemetry are scrubbed of credential-bearing attributes and never sent anywhere on their own.diff --git a/knip.config.ts b/knip.config.tsindex dd620604a..5b8951125 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -26,6 +26,7 @@ export default {'@typescript/native',],ignoreBinaries: [+ 'uv','printf','ps', // process listing — diagnose.ts, process-scan.ts'lsof', // open-file listing — diagnose.ts, process-scan.tsdiff --git a/packages/app/src/components/acp/ThreadView.dom.test.tsx b/packages/app/src/components/acp/ThreadView.dom.test.tsxindex 186378c80..e9dae504c 100644--- a/packages/app/src/components/acp/ThreadView.dom.test.tsx+++ b/packages/app/src/components/acp/ThreadView.dom.test.tsx@@ -2862,6 +2862,31 @@ describe('ThreadView failure notices', () => {expect(rootCause.textContent).toContain('code EUSAGE');expect(rootCause.textContent).not.toContain('complete log of this run');});++ test('compatibility control: acquisition explanation and native refusal details coexist', async () => {+ const explanation =+ "No release of the adapter is available under your package manager's release-date policy. Try again after an allowed release becomes available.";+ const detail =+ 'npm error code ETARGET\nnpm error notarget No matching version found with a date before 2026-09-07.\n';+ model = makeModel({+ turnActive: false,+ items: [+ notice({+ failure: {+ reason: 'connect',+ agentMessage: explanation,+ machineDetail: detail,+ },+ }),+ ],+ });+ render(<ThreadView info={makeInfo({ status: 'error' })} />);+ expect(screen.getByTestId('agent-thread-notice').textContent).toContain(explanation);+ expect(screen.getByTestId('agent-thread-notice-root-cause').textContent).toContain('ETARGET');+ await userEvent.click(screen.getByTestId('agent-thread-notice-details-toggle'));+ expect(screen.getByTestId('agent-thread-notice-details').textContent).toContain(detail.trim());+ expect(screen.getByTestId('agent-thread-notice').textContent).toContain(explanation);+ });});describe('ThreadView agent notices', () => {diff --git a/packages/server/package.json b/packages/server/package.jsonindex 0fd7dd301..7677e74ac 100644--- a/packages/server/package.json+++ b/packages/server/package.json@@ -75,6 +75,7 @@"build:skill-bundles": "tsx scripts/build-skill-bundles.ts","typecheck": "pnpm run typecheck:bash && tsc","test": "vitest run",+ "test:network": "vitest run --config vitest.network.config.ts","measure:generated-index-sweep": "node --import tsx --conditions=development measure-generated-index-sweep.ts","measure:observer-a-drain": "node --import tsx --conditions=development measure-observer-a-drain.ts","typecheck:bash": "tsc -p tsconfig.bash.json"diff --git a/packages/server/src/acp/acquisition-contract.test-helper.ts b/packages/server/src/acp/acquisition-contract.test-helper.tsnew file mode 100644index 000000000..94ba0eba2--- /dev/null+++ b/packages/server/src/acp/acquisition-contract.test-helper.ts@@ -0,0 +1,191 @@+import { execFileSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import { once } from 'node:events';+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { createServer } from 'node:http';+import { join } from 'node:path';+import { describe, expect, test } from 'vitest';+import { getLogger } from '../logger.ts';+import { AgentLaunchError, resolveRegistryLaunch, spawnAcpAgent } from './launch.ts';+import {+ captureChild,+ compareVersions,+ npmNative,+ registryPackage,+ withAcquisitionHome,+} from './package-acquisition.test-helper.ts';++type AcquisitionFactory = (run: (home: string) => Promise<void>) => Promise<void>;++export function acquisitionFailureContract(factory: AcquisitionFactory): void {+ const log = getLogger('acquisition-contract');+ describe('native acquisition contract', () => {+ test('an admitted exact package keeps its pin', async () => {+ await factory(async () => {+ const launch = await resolveRegistryLaunch(registryPackage('[email protected]'), null, log);+ expect(launch.args).toEqual(['-y', '[email protected]', '--version']);+ });+ });+ test('a cutoff substitutes the newest admitted version below the catalog pin', async () => {+ await factory(async (home) => {+ writeFileSync(join(home, '.npmrc'), 'before=2018-04-01T00:00:00Z\n');+ const launch = await resolveRegistryLaunch(registryPackage('[email protected]'), null, log);+ expect(launch.args).toEqual(['-y', '[email protected]', '--version']);+ });+ });+ test('uvx retains the native cutoff refusal', async () => {+ await factory(async (home) => {+ process.env.UV_EXCLUDE_NEWER = '1970-01-01';+ const launch = await resolveRegistryLaunch(+ registryPackage('[email protected]', 'uvx'),+ null,+ log,+ );+ const result = await captureChild(+ launch.kind === 'npx' ? spawnAcpAgent(launch) : spawnAcpAgent(launch, home),+ );+ expect(result.code, result.stderr).not.toBe(0);+ expect(result.stderr).toContain('No solution found when resolving tool dependencies');+ expect(result.stderr).toContain('filtered by `exclude-newer`');+ });+ });+ test('plain ETARGET does not downgrade a nonexistent pin', async () => {+ await factory(async () => {+ const spec = '[email protected]';+ const control = await npmNative(['pack', spec, '--dry-run', '--ignore-scripts', '--json']);+ expect(control.code, control.stderr).not.toBe(0);+ expect(control.stderr).toContain('ETARGET');+ expect(control.stderr).not.toContain('with a date before');+ const result = await resolveRegistryLaunch(registryPackage(spec), null, log).catch(+ (error: unknown) => error,+ );+ expect(result).toBeInstanceOf(AgentLaunchError);+ expect(result).toMatchObject({+ code: 'install-failed',+ message: `Could not acquire ${spec}.`,+ machineDetail: expect.stringContaining('ETARGET'),+ });+ });+ });+ test('no admitted version reports a release-policy refusal', async () => {+ await factory(async (home) => {+ writeFileSync(join(home, '.npmrc'), 'before=1970-01-01\n');+ await expect(+ resolveRegistryLaunch(registryPackage('[email protected]'), null, log),+ ).rejects.toMatchObject({+ code: 'install-failed',+ message: expect.stringContaining("package manager's release-date policy"),+ });+ });+ });+ });+}++export async function withLocalAcquisitionRegistry(+ run: (home: string) => Promise<void>,+): Promise<void> {+ await withAcquisitionHome(async (home) => {+ const packages = new Map<string, Map<string, { bytes: Buffer; published: string }>>();+ for (const { name, version, published } of [+ { name: 'is-number', version: '7.0.0', published: '2018-07-04T15:08:58.238Z' },+ { name: 'is-number', version: '6.0.0', published: '2018-03-31T17:02:39.953Z' },+ {+ name: '@agentclientprotocol/claude-agent-acp',+ version: '0.75.1',+ published: '2018-07-04T15:08:58.238Z',+ },+ ] satisfies { name: string; version: string; published: string }[]) {+ const directory = join(home, `${name.replaceAll('/', '-')}-${version}`);+ mkdirSync(join(directory, 'package'), { recursive: true });+ writeFileSync(join(directory, 'package/package.json'), JSON.stringify({ name, version }));+ const archive = join(directory, 'fixture.tgz');+ execFileSync('tar', ['-czf', archive, '-C', directory, 'package']);+ let releases = packages.get(name);+ if (!releases) {+ releases = new Map();+ packages.set(name, releases);+ }+ releases.set(version, { bytes: readFileSync(archive), published });+ }+ const endpoint = createServer((req, res) => {+ const pathname = decodeURIComponent(req.url ?? '/');+ if (pathname === '/simple/ruff/') {+ res.setHeader('content-type', 'application/vnd.pypi.simple.v1+json');+ res.end(+ JSON.stringify({+ meta: { 'api-version': '1.1' },+ name: 'ruff',+ versions: ['0.16.7'],+ files: [+ {+ filename: 'ruff-0.16.7-py3-none-any.whl',+ url: '/refusal-only/ruff.whl',+ hashes: {},+ 'upload-time': '2025-01-01T00:00:00Z',+ size: 1,+ },+ ],+ }),+ );+ return;+ }+ if (pathname === '/refusal-only/ruff.whl') {+ res.writeHead(409, { 'content-type': 'text/plain' });+ res.end(+ 'This fixture covers cutoff refusal only; Python package installation is unsupported.',+ );+ return;+ }+ const archive = pathname.match(/^(.*)\/([^/]+)\.tgz$/);+ const name = (archive?.[1] ?? pathname).slice(1);+ const releases = packages.get(name);+ if (!releases) {+ res.writeHead(404);+ res.end();+ return;+ }+ if (archive) {+ const release = releases.get(archive[2]);+ res.writeHead(release ? 200 : 404);+ res.end(release?.bytes);+ return;+ }+ res.setHeader('content-type', 'application/json');+ res.end(+ JSON.stringify({+ name,+ 'dist-tags': { latest: [...releases.keys()].sort(compareVersions).at(-1) },+ versions: Object.fromEntries(+ [...releases].map(([version, { bytes }]) => [+ version,+ {+ name,+ version,+ dist: {+ tarball: `http://${req.headers.host}/${name}/${version}.tgz`,+ shasum: createHash('sha1').update(bytes).digest('hex'),+ },+ },+ ]),+ ),+ time: Object.fromEntries(+ [...releases].map(([version, { published }]) => [version, published]),+ ),+ }),+ );+ });+ endpoint.listen(0, '127.0.0.1');+ await once(endpoint, 'listening');+ const address = endpoint.address();+ if (address === null || typeof address === 'string') throw new Error('missing port');+ process.env.npm_config_registry = `http://127.0.0.1:${address.port}/`;+ process.env.UV_OFFLINE = '0';+ process.env.UV_DEFAULT_INDEX = `http://127.0.0.1:${address.port}/simple`;+ try {+ await run(home);+ } finally {+ endpoint.closeAllConnections();+ await new Promise<void>((resolve) => endpoint.close(() => resolve()));+ }+ });+}diff --git a/packages/server/src/acp/diagnostics.ts b/packages/server/src/acp/diagnostics.tsnew file mode 100644index 000000000..1952af2de--- /dev/null+++ b/packages/server/src/acp/diagnostics.ts@@ -0,0 +1,36 @@+import { scrubSecrets } from '@inkeep/open-knowledge-core';++export const ACQUISITION_DETAIL_MAX_CHARS = 16_000;++export function redactDiagnostic(text: string): string {+ return scrubSecrets(text.replace(/(https?:\/\/)[^\s/]+@/gi, '$1***@'));+}++export function createDiagnosticStderrCapture(consume: (line: string) => void): {+ write: (chunk: string) => void;+ end: () => void;+} {+ let pending = '';+ let dropping = false;+ const flush = (): void => {+ if (dropping) consume('[oversized diagnostic line omitted]');+ else if (pending !== '') consume(redactDiagnostic(pending));+ pending = '';+ dropping = false;+ };+ return {+ write(chunk) {+ for (const [index, part] of chunk.split('\n').entries()) {+ if (index > 0) flush();+ if (dropping) continue;+ if (pending.length + part.length > ACQUISITION_DETAIL_MAX_CHARS) {+ pending = '';+ dropping = true;+ } else {+ pending += part;+ }+ }+ },+ end: flush,+ };+}diff --git a/packages/server/src/acp/launch-package-acquisition.network.test.ts b/packages/server/src/acp/launch-package-acquisition.network.test.tsnew file mode 100644index 000000000..ccd45f365--- /dev/null+++ b/packages/server/src/acp/launch-package-acquisition.network.test.ts@@ -0,0 +1,151 @@+import { writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { describe, expect, test } from 'vitest';+import { getLogger } from '../logger.ts';+import { acquisitionFailureContract } from './acquisition-contract.test-helper.ts';+import { resolveRegistryLaunch, spawnAcpAgent } from './launch.ts';+import {+ captureChild,+ freezeNpmClock,+ native,+ newestAdmissible,+ npmNative,+ npmPackedVersion,+ npmPublicationTimes,+ registryPackage,+ withLiveAcquisitionHome,+} from './package-acquisition.test-helper.ts';++const log = getLogger('package-acquisition-network-test');+const packageName = '@agentclientprotocol/claude-agent-acp';+const ceiling = '0.77.0';++async function npmTimes() {+ const result = await npmNative(['view', packageName, 'time', '--json']);+ expect(result.code, result.stderr).toBe(0);+ return npmPublicationTimes(result.stdout);+}++acquisitionFailureContract(withLiveAcquisitionHome);++describe('live package acquisition policy and native dispatch', () => {+ test.each([+ { policy: 'before', role: 'compatibility control' },+ { policy: 'excluded', role: 'known npm pack exclusion limitation' },+ ] as const)(+ '$role: the launch respects native $policy selection',+ async ({ policy }) => {+ await withLiveAcquisitionHome(async (home) => {+ const times = await npmTimes();+ const now = Date.parse(times[ceiling]) + 1000;+ freezeNpmClock(home, now);+ writeFileSync(join(home, '.npmrc'), 'min-release-age=7\n');+ if (policy === 'before') process.env.npm_config_before = new Date(now).toISOString();+ else+ writeFileSync(+ join(home, '.npmrc'),+ `min-release-age=7\nmin-release-age-exclude[]=${packageName}\n`,+ );+ const result = await npmNative([+ 'pack',+ `${packageName}@${ceiling}`,+ '--dry-run',+ '--ignore-scripts',+ '--json',+ ]);+ const expected =+ policy === 'before' ? ceiling : newestAdmissible(times, ceiling, now - 7 * 86_400_000);+ expect(expected).toBeDefined();+ if (policy === 'before') {+ expect(result.code, result.stderr).toBe(0);+ expect(npmPackedVersion(result.stdout)).toBe(ceiling);+ } else {+ expect(result.code, result.stderr).toBe(1);+ expect(result.stderr).toMatch(/ETARGET[\s\S]*with a date before/);+ expect(expected).not.toBe(ceiling);+ }+ const launch = await resolveRegistryLaunch(+ registryPackage(`${packageName}@${ceiling}`),+ null,+ log,+ );+ expect(launch.args).toContain(`${packageName}@${expected}`);+ });+ },+ 120_000,+ );++ test('a dated refusal selects an exact admissible descriptor below the package ceiling', async () => {+ await withLiveAcquisitionHome(async (home) => {+ const times = await npmTimes();+ freezeNpmClock(home, Date.parse(times[ceiling]) + 1000);+ writeFileSync(join(home, '.npmrc'), 'min-release-age=7\n');+ const control = await npmNative([+ 'pack',+ `${packageName}@0.0.0 - ${ceiling}`,+ '--dry-run',+ '--ignore-scripts',+ '--json',+ ]);+ expect(control.code, control.stderr).toBe(0);+ const expected = npmPackedVersion(control.stdout);+ expect(expected).not.toBe(ceiling);+ const launch = await resolveRegistryLaunch(+ registryPackage(`${packageName}@${ceiling}`),+ null,+ log,+ );+ expect(launch.args).toEqual(['-y', `${packageName}@${expected}`, '--version']);+ });+ }, 120_000);++ test.each(['@', '=='] as const)(+ 'actual uvx resolves %s exact pins below the cutoff despite an installed newer tool',+ async (separator) => {+ await withLiveAcquisitionHome(async () => {+ const response = await native('curl', [+ '-fsS',+ '--max-time',+ '20',+ 'https://pypi.org/pypi/ruff/json',+ ]);+ expect(response.code, response.stderr).toBe(0);+ const metadata = JSON.parse(response.stdout);+ const version: string = metadata.info.version;+ const published: string = metadata.releases[version][0].upload_time_iso_8601;+ const installed = await native('uv', [+ 'tool',+ 'install',+ `ruff==${version}`,+ '--no-config',+ ]);+ expect(installed.code, installed.stderr).toBe(0);+ process.env.UV_EXCLUDE_NEWER = new Date(Date.parse(published) - 1000).toISOString();+ const control = await native('uvx', [+ '--from',+ `ruff<=${version}`,+ '--isolated',+ '--upgrade-package',+ 'ruff',+ 'ruff',+ '--version',+ ]);+ expect(control.code, control.stderr).toBe(0);+ expect(control.stdout.trim()).not.toBe(`ruff ${version}`);+ const launch = await resolveRegistryLaunch(+ registryPackage(`ruff${separator}${version}`, 'uvx'),+ null,+ log,+ );+ const result = await captureChild(+ launch.kind === 'npx'+ ? spawnAcpAgent(launch)+ : spawnAcpAgent(launch, process.env.HOME ?? ''),+ );+ expect(result.code, result.stderr).toBe(0);+ expect(result.stdout.trim()).toBe(control.stdout.trim());+ });+ },+ 180_000,+ );+});diff --git a/packages/server/src/acp/launch-package-acquisition.test.ts b/packages/server/src/acp/launch-package-acquisition.test.tsnew file mode 100644index 000000000..c3e8c8343--- /dev/null+++ b/packages/server/src/acp/launch-package-acquisition.test.ts@@ -0,0 +1,312 @@+import { once } from 'node:events';+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { createServer } from 'node:http';+import { join } from 'node:path';+import { describe, expect, test } from 'vitest';+import { getLogger } from '../logger.ts';+import {+ acquisitionFailureContract,+ withLocalAcquisitionRegistry,+} from './acquisition-contract.test-helper.ts';+import { AgentLaunchError, resolveRegistryLaunch } from './launch.ts';+import {+ installNodeFixture,+ npmNative,+ npmOutputs,+ npmPackedVersion,+ registryPackage,+ withAcquisitionHome,+ writeExecutable,+} from './package-acquisition.test-helper.ts';++const log = getLogger('package-acquisition-test');++acquisitionFailureContract(withLocalAcquisitionRegistry);++describe('hermetic package acquisition and native dispatch', () => {+ test('the fixture latest tag is independent of release insertion order', async () => {+ await withLocalAcquisitionRegistry(async () => {+ const result = await npmNative([+ 'pack',+ 'is-number',+ '--dry-run',+ '--ignore-scripts',+ '--json',+ ]);+ expect(result.code, result.stderr).toBe(0);+ expect(npmPackedVersion(result.stdout)).toBe('7.0.0');+ });+ });++ test('closed custom registry preserves transport failure without a cooldown diagnosis', async () => {+ await withAcquisitionHome(async () => {+ const endpoint = createServer();+ endpoint.listen(0, '127.0.0.1');+ await once(endpoint, 'listening');+ const address = endpoint.address();+ if (address === null || typeof address === 'string') throw new Error('missing port');+ await new Promise<void>((resolve) => endpoint.close(() => resolve()));+ process.env.npm_config_registry = `http://127.0.0.1:${address.port}/`;+ const result = await resolveRegistryLaunch(+ registryPackage('[email protected]'),+ null,+ log,+ ).catch((error: unknown) => error);+ expect(result).toBeInstanceOf(AgentLaunchError);+ expect(result).toMatchObject({+ code: 'install-failed',+ message: 'Could not acquire [email protected].',+ machineDetail: expect.stringContaining('ECONNREFUSED'),+ });+ expect(String(result)).not.toMatch(/release-date policy|cooldown/);+ });+ });++ test.each(['auth', 'integrity'] as const)(+ 'real npm preserves a custom registry %s refusal',+ async (mode) => {+ await withAcquisitionHome(async (home) => {+ const seen: string[] = [];+ const endpoint = createServer((req, res) => {+ seen.push(req.headers.authorization ?? '');+ if (mode === 'auth') {+ res.writeHead(401);+ res.end('{"error":"fixture authentication rejected"}');+ return;+ }+ if (req.url?.endsWith('.tgz')) {+ res.end('corrupted tarball');+ return;+ }+ res.setHeader('content-type', 'application/json');+ res.end(+ JSON.stringify({+ name: 'acquisition-fixture',+ 'dist-tags': { latest: '1.0.0' },+ versions: {+ '1.0.0': {+ name: 'acquisition-fixture',+ version: '1.0.0',+ dist: {+ tarball: `http://${req.headers.host}/fixture.tgz`,+ shasum: '0'.repeat(40),+ },+ },+ },+ time: { '1.0.0': '2020-01-01T00:00:00.000Z' },+ }),+ );+ });+ endpoint.listen(0, '127.0.0.1');+ await once(endpoint, 'listening');+ const address = endpoint.address();+ if (address === null || typeof address === 'string') throw new Error('missing port');+ process.env.npm_config_registry = `http://127.0.0.1:${address.port}/`;+ writeFileSync(+ join(home, '.npmrc'),+ `//127.0.0.1:${address.port}/:_authToken=fixture-only-token\n`,+ );+ try {+ const control = await npmNative([+ 'pack',+ '[email protected]',+ '--dry-run',+ '--ignore-scripts',+ '--json',+ ]);+ const code = mode === 'auth' ? 'E401' : 'EINTEGRITY';+ expect(control.stderr).toContain(code);+ expect(seen).toContain('Bearer fixture-only-token');+ const result = await resolveRegistryLaunch(+ registryPackage('[email protected]'),+ null,+ log,+ ).catch((error: unknown) => error);+ expect(result).toBeInstanceOf(AgentLaunchError);+ expect(result).toMatchObject({+ code: 'install-failed',+ message: 'Could not acquire [email protected].',+ machineDetail: expect.stringContaining(code),+ });+ expect(String(result)).not.toMatch(/release-date policy|cooldown/);+ } finally {+ endpoint.closeAllConnections();+ await new Promise<void>((resolve) => endpoint.close(() => resolve()));+ }+ });+ },+ 90_000,+ );++ test.each(npmOutputs)('accepts captured npm $npmVersion package metadata', async ({ pack }) => {+ await withAcquisitionHome(async (home) => {+ const bin = join(home, 'bin');+ mkdirSync(bin);+ installNodeFixture(bin);+ writeExecutable(join(bin, 'npx'), 'process.exit(0);');+ writeExecutable(+ join(bin, 'npm'),+ `process.stdout.write(${JSON.stringify(JSON.stringify(pack))});`,+ );+ const launch = await resolveRegistryLaunch(+ registryPackage('[email protected]', 'npx', { PATH: bin }),+ null,+ log,+ );+ expect(launch.args).toEqual(['-y', '[email protected]', '--version']);+ });+ });++ test.each([+ { label: 'empty', output: {} },+ {+ label: 'multiple packages',+ output: {+ a: { name: 'is-number', version: '7.0.0' },+ b: { name: 'other', version: '1.0.0' },+ },+ },+ { label: 'wrong name', output: { other: { name: 'other', version: '7.0.0' } } },+ { label: 'above ceiling', output: { 'is-number': { name: 'is-number', version: '8.0.0' } } },+ { label: 'below exact pin', output: { 'is-number': { name: 'is-number', version: '6.0.0' } } },+ {+ label: 'prerelease',+ output: { 'is-number': { name: 'is-number', version: '7.0.0-beta.1' } },+ },+ ])('rejects $label package metadata', async ({ output }) => {+ await withAcquisitionHome(async (home) => {+ const bin = join(home, 'bin');+ mkdirSync(bin);+ installNodeFixture(bin);+ writeExecutable(join(bin, 'npx'), 'process.exit(0);');+ writeExecutable(+ join(bin, 'npm'),+ `process.stdout.write(${JSON.stringify(JSON.stringify(output))});`,+ );+ await expect(+ resolveRegistryLaunch(registryPackage('[email protected]', 'npx', { PATH: bin }), null, log),+ ).rejects.toMatchObject({ code: 'install-failed' });+ });+ });++ test.each(['missing', 'non-executable'] as const)(+ 'npx without a usable npm sibling retains the catalog pin: %s',+ async (mode) => {+ await withAcquisitionHome(async (home) => {+ const bin = join(home, 'bin');+ mkdirSync(bin);+ installNodeFixture(bin);+ writeExecutable(join(bin, 'npx'), 'process.exit(0);');+ if (mode === 'non-executable') writeFileSync(join(bin, 'npm'), 'not executable');+ const launch = await resolveRegistryLaunch(+ registryPackage('[email protected]', 'npx', { PATH: bin }),+ null,+ log,+ );+ expect(launch.args).toEqual(['-y', '[email protected]', '--version']);+ });+ },+ );++ test.each([+ { name: 'other', version: '7.0.0' },+ { name: 'is-number', version: '8.0.0' },+ { name: 'is-number', version: '6.0.0' },+ ])('names the rejected package $name@$version separately from parsing', async (selected) => {+ await withAcquisitionHome(async (home) => {+ const bin = join(home, 'bin');+ mkdirSync(bin);+ installNodeFixture(bin);+ writeExecutable(join(bin, 'npx'), 'process.exit(0);');+ writeExecutable(+ join(bin, 'npm'),+ `process.stdout.write(${JSON.stringify(JSON.stringify([selected]))});`,+ );+ await expect(+ resolveRegistryLaunch(registryPackage('[email protected]', 'npx', { PATH: bin }), null, log),+ ).rejects.toMatchObject({+ message: `npm returned ${selected.name}@${selected.version} outside the requested constraint [email protected].`,+ });+ });+ });++ test('a failed range probe names its constraint and keeps redacted output out of the headline', async () => {+ await withAcquisitionHome(async (home) => {+ const bin = join(home, 'bin');+ mkdirSync(bin);+ installNodeFixture(bin);+ writeExecutable(join(bin, 'npx'), 'process.exit(0);');+ const detail =+ 'E401 https://alice:[email protected]/private-package Authorization: Bearer fixture-token /Users/fixture-user/.npm/_logs/example.log';+ writeExecutable(+ join(bin, 'npm'),+ `+ process.stderr.write(process.argv[3].includes(' - ') ? ${JSON.stringify(detail)} : 'ETARGET No matching version found with a date before 2000-01-01');+ process.exit(1);+ `,+ );+ const result = await resolveRegistryLaunch(+ registryPackage('[email protected]', 'npx', { PATH: bin }),+ null,+ log,+ ).catch((error: unknown) => error);+ expect(result).toMatchObject({+ message: 'Could not acquire [email protected] - 7.0.0.',+ machineDetail: expect.stringContaining('E401'),+ });+ expect(result).toBeInstanceOf(AgentLaunchError);+ if (!(result instanceof AgentLaunchError)) throw new Error('expected acquisition failure');+ expect(result.machineDetail).not.toMatch(/fixture-secret|fixture-token|fixture-user/);+ expect(result.message).not.toContain('E401');+ });+ });++ test.each(['malformed', 'overflow', 'timeout'] as const)(+ 'native npm %s output fails acquisition and releases the owned process',+ async (mode) => {+ await withAcquisitionHome(async (home) => {+ const bin = join(home, 'bin');+ mkdirSync(bin);+ installNodeFixture(bin);+ const pidPath = join(home, 'probe.pid');+ const observed = join(home, 'probe.json');+ writeExecutable(join(bin, 'npx'), 'process.exit(0);');+ const response =+ mode === 'malformed'+ ? "process.stdout.write('{not-json');"+ : mode === 'overflow'+ ? "process.stdout.write('x'.repeat(32 * 1024 * 1024));"+ : 'setInterval(() => {}, 1000);';+ writeExecutable(+ join(bin, 'npm'),+ `require('node:fs').writeFileSync(${JSON.stringify(pidPath)}, String(process.pid));+ require('node:fs').writeFileSync(${JSON.stringify(observed)}, JSON.stringify({cwd:process.cwd(),args:process.argv.slice(2)}));+ ${response}`,+ );+ let pid: number | undefined;+ try {+ const result = await resolveRegistryLaunch(+ registryPackage('[email protected]', 'npx', { PATH: bin }),+ null,+ log,+ ).catch((error: unknown) => error);+ if (existsSync(pidPath)) pid = Number(readFileSync(pidPath, 'utf8'));+ expect(result).toBeInstanceOf(AgentLaunchError);+ expect(result).toMatchObject({ code: 'install-failed' });+ const probe = JSON.parse(readFileSync(observed, 'utf8'));+ expect(probe.cwd).toBe(join(home, '.ok', 'acp-npx-cwd'));+ expect(probe.args).toContain('--ignore-scripts');+ expect(() => process.kill(pid ?? 0, 0)).toThrow();+ expect(String(result).length).toBeLessThan(20_000);+ } finally {+ if (pid !== undefined) {+ try {+ process.kill(pid, 'SIGKILL');+ } catch {}+ }+ }+ });+ },+ 120_000,+ );+});diff --git a/packages/server/src/acp/launch-release-age.network.test.ts b/packages/server/src/acp/launch-release-age.network.test.tsnew file mode 100644index 000000000..40a5c14f4--- /dev/null+++ b/packages/server/src/acp/launch-release-age.network.test.ts@@ -0,0 +1,221 @@+import { spawnSync } from 'node:child_process';+import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { aroundEach, describe, expect, test, vi } from 'vitest';+import { getLogger } from '../logger.ts';+import { resolveRegistryLaunch, spawnAcpAgent } from './launch.ts';+import {+ captureChild,+ acquisitionDescriptors as descriptors,+ freezeNpmClock,+ native,+ newestAdmissible,+ npmNative,+ npmPackedVersion,+ npmPublicationTimes,+ registryPackage,+ withLiveAcquisitionHome,+} from './package-acquisition.test-helper.ts';+import type { RegistryAgent } from './registry.ts';++const day = 86_400_000;+const log = getLogger('acp-release-age-test');+const registrySites: RegistryAgent[] = JSON.parse(+ readFileSync(new URL('./registry-release-age.test-fixture.json', import.meta.url), 'utf8'),+);++aroundEach(async (runTest) => {+ await withLiveAcquisitionHome(async () => {+ try {+ await runTest();+ } finally {+ vi.useRealTimers();+ }+ });+});++test('the acquisition catalog snapshot matches current package descriptors', async () => {+ const result = await native('curl', [+ '-fsS',+ '--max-time',+ '20',+ 'https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json',+ ]);+ expect(result.code, result.stderr).toBe(0);+ const live: { agents: RegistryAgent[] } = JSON.parse(result.stdout);+ expect(descriptors(live.agents)).toEqual(descriptors(registrySites));+});++describe('registry package acquisition respects publication cutoffs at every catalog site', () => {+ test.each(registrySites.filter((agent) => agent.distribution.npx))(+ '$id produces an admissible npm plan or an acquisition error during the cooldown',+ async (agent) => {+ const descriptor = agent.distribution.npx?.package ?? '';+ const separator = descriptor.lastIndexOf('@');+ const packageName = descriptor.slice(0, separator);+ const ceiling = descriptor.slice(separator + 1);+ const times = await publicationTimes(packageName);+ const cutoff = Date.parse(times[ceiling]) - 1000;+ const expected = newestAdmissible(times, ceiling, cutoff);+ setPolicy(cutoff + 7 * day, 'npmrc');+ if (expected === undefined) {+ const rejected = await npmNative([+ 'pack',+ `${packageName}@<=${ceiling}`,+ '--dry-run',+ '--json',+ ]);+ expect(rejected.code).toBe(1);+ expect(rejected.stderr).toMatch(/ETARGET|ENOVERSIONS/);+ await expect(resolveRegistryLaunch(agent, null, log)).rejects.toMatchObject({+ name: 'AgentLaunchError',+ });+ return;+ }+ const launch = await resolveRegistryLaunch(agent, null, log);+ const constraint = launch.args.find((arg) => arg.startsWith(`${packageName}@`));+ expect(constraint).toBeDefined();+ const result = await npmNative(['pack', constraint ?? '', '--dry-run', '--json'], launch.env);+ expect(result.code, `${agent.id}: ${result.stderr}`).toBe(0);+ expect(result.stderr).not.toContain('ETARGET');+ const selected = npmPackedVersion(result.stdout);+ expect(selected).toBe(expected);+ expect(Date.parse(times[selected])).toBeLessThan(cutoff);+ },+ 150_000,+ );++ test.each(registrySites.filter((agent) => agent.distribution.uvx))(+ '$id admits an older Python release under UV_EXCLUDE_NEWER',+ async (agent) => {+ const descriptor = agent.distribution.uvx?.package ?? '';+ const [packageName, ceiling] = descriptor.split(/==|@/);+ const metadata = spawnSync(+ 'curl',+ [+ '--fail',+ '--silent',+ '--show-error',+ '--max-time',+ '20',+ `https://pypi.org/pypi/${packageName}/json`,+ ],+ { encoding: 'utf8', timeout: 25_000, maxBuffer: 8 * 1024 * 1024 },+ );+ expect(metadata.status, metadata.error?.message ?? metadata.stderr).toBe(0);+ const releases: Record<string, { upload_time_iso_8601: string; yanked: boolean }[]> =+ JSON.parse(metadata.stdout).releases;+ const times = Object.fromEntries(+ Object.entries(releases).flatMap(([version, files]) => {+ const dates = files+ .filter((file) => !file.yanked)+ .map((file) => file.upload_time_iso_8601)+ .sort();+ return dates.length ? [[version, dates[0]]] : [];+ }),+ );+ const cutoff = Date.parse(times[ceiling]) - 1000;+ const expected = newestAdmissible(times, ceiling, cutoff);+ expect(expected).toBeDefined();+ process.env.UV_EXCLUDE_NEWER = new Date(cutoff).toISOString();+ const launch = await resolveRegistryLaunch(agent, null, log);+ const constraint = launch.args.find((arg) => arg.startsWith(packageName));+ expect(constraint).toBeDefined();+ const args = [+ 'pip',+ 'install',+ '--dry-run',+ '--no-deps',+ '--no-config',+ '--index-url',+ 'https://pypi.org/simple',+ '--python-version',+ '3.13',+ '--target',+ join(process.env.HOME ?? '', 'python-target'),+ ];+ const control = spawnSync('uv', [...args, `${packageName}==${expected}`], {+ env: process.env,+ cwd: process.env.HOME,+ encoding: 'utf8',+ timeout: 60_000,+ });+ expect(control.status, control.error?.message ?? control.stderr).toBe(0);+ const result = spawnSync(+ 'uv',+ [...args, (constraint ?? '').replace(`${packageName}@`, `${packageName}==`)],+ { env: launch.env, cwd: process.env.HOME, encoding: 'utf8', timeout: 60_000 },+ );+ expect(result.status, result.error?.message ?? result.stderr).toBe(0);+ const selected = result.stderr.match(new RegExp(`${packageName}==([0-9.]+)`))?.[1];+ expect(selected).toBe(expected);+ expect(Date.parse(times[selected ?? ''])).toBeLessThan(cutoff);+ },+ 120_000,+ );+});++async function publicationTimes(packageName: string): Promise<Record<string, string>> {+ const result = await npmNative(['view', packageName, 'time', '--json']);+ expect(result.code, result.stderr).toBe(0);+ return npmPublicationTimes(result.stdout);+}++function setPolicy(now: number, source: 'npmrc' | 'env') {+ const home = process.env.HOME;+ expect(home).toBeDefined();+ freezeNpmClock(home ?? '', now);+ if (source === 'npmrc') writeFileSync(join(home ?? '', '.npmrc'), 'min-release-age=7\n');+ else process.env.npm_config_min_release_age = '7';+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(now);+}++describe('registry npm launch under a seven-day release cooldown', () => {+ test.each([+ { source: 'npmrc', pin: 'fresh' },+ { source: 'env', pin: 'fresh' },+ { source: 'npmrc', pin: 'admissible' },+ ] as const)(+ 'launches the newest admissible adapter with $source policy and a $pin catalog pin',+ async ({ source, pin }) => {+ const packageName = '@agentclientprotocol/claude-agent-acp';+ const times = await publicationTimes(packageName);+ const ceiling = '0.77.0';+ const now = Date.parse(times[ceiling]) + 1000;+ const cutoff = now - 7 * day;+ const expected = newestAdmissible(times, ceiling, cutoff);+ expect(expected).toBeDefined();+ setPolicy(now, source);+ const control = await npmNative([+ 'pack',+ `${packageName}@${expected}`,+ '--dry-run',+ '--json',+ ]);+ expect(control.code, control.stderr).toBe(0);++ const agent = registryPackage(`${packageName}@${pin === 'fresh' ? ceiling : expected}`);+ const launch = await resolveRegistryLaunch(agent, null, log);+ const result = await captureChild(+ launch.kind === 'npx'+ ? spawnAcpAgent(launch)+ : spawnAcpAgent(launch, process.env.HOME ?? ''),+ {+ timeoutMs: 90_000,+ graceMs: 1000,+ },+ );+ expect(result.code, result.stderr).toBe(0);+ expect(result.stderr).not.toContain('ETARGET');+ const cache = join(process.env.HOME ?? '', 'npm-cache', '_npx');+ const installed = readdirSync(cache)+ .map((entry) => join(cache, entry, 'node_modules', packageName, 'package.json'))+ .filter(existsSync)+ .map((path) => JSON.parse(readFileSync(path, 'utf8')).version);+ expect(installed).toEqual([expected]);+ expect(Date.parse(times[installed[0]])).toBeLessThan(cutoff);+ },+ 180_000,+ );+});diff --git a/packages/server/src/acp/launch.test.ts b/packages/server/src/acp/launch.test.tsindex 101ba5ee5..e78df2bd7 100644--- a/packages/server/src/acp/launch.test.ts+++ b/packages/server/src/acp/launch.test.ts@@ -16,6 +16,8 @@ import { OK_HOSTED_AGENT_ENV } from '@inkeep/open-knowledge-core';import { afterEach, describe, expect, test, vi } from 'vitest';import { getLogger, type PinoLogger } from '../logger.ts';import { isValidLockPid } from '../process-alive.ts';+import { withLocalAcquisitionRegistry } from './acquisition-contract.test-helper.ts';+import { createDiagnosticStderrCapture } from './diagnostics.ts';import {AgentLaunchError,brokenInterpreterHint,@@ -26,11 +28,14 @@ import {MINIMUM_NPX_NODE_MAJOR,mergedEnv,overlaySetsPath,+ packageAcquisitionFailure,preflightLaunch,probeInterpreterHealth,probeNpxNodeCompatibility,type ResolvedLaunch,+ resolveCustomLaunch,resolveNpxNodeCommand,+ resolveRegistryLaunch,resolveWindowsCommand,spawnAcpAgent,terminateAgentTree,@@ -41,8 +46,140 @@ import {withLoginShellPath,withPreferredLoginShellPath,} from './launch.ts';+import {+ registryPackage,+ spawnNpxWithProjectCwd,+ withAcquisitionHome,+} from './package-acquisition.test-helper.ts';import type { RegistryBinaryTarget } from './registry.ts';+describe('package acquisition descriptor boundaries', () => {+ test.each([+ 'is-number',+ 'is-number@latest',+ 'is-number@^7.0.0',+ '[email protected] - 7.0.0',+ '@scope/[email protected]',+ 'alias@npm:[email protected]',+ 'git+https://github.com/example/agent.git',+ 'https://example.com/agent-1.2.3.tgz',+ 'file:./agent',+ ])('compatibility control: npm descriptor %s retains its caller contract', async (descriptor) => {+ await withAcquisitionHome(async () => {+ const env = {+ npm_config_registry: 'https://registry.example.test/',+ npm_config_before: '2020-01-01',+ 'npm_config_//registry.example.test/:_authToken': 'fixture-token',+ ACP_FIXTURE: 'preserved',+ };+ const launch = await resolveRegistryLaunch(+ registryPackage(descriptor, 'npx', env),+ null,+ getLogger('descriptor-test'),+ );+ expect(launch.args).toEqual(['-y', descriptor, '--version']);+ expect(launch.env).toMatchObject(env);+ });+ });++ test.each(['@agentclientprotocol/[email protected]'])(+ 'compatibility control: admissible stable %s uses its package version instead of the catalog version',+ async (descriptor) => {+ await withLocalAcquisitionRegistry(async () => {+ const launch = await resolveRegistryLaunch(+ registryPackage(descriptor),+ null,+ getLogger('descriptor-test'),+ );+ expect(launch.args).toEqual(['-y', descriptor, '--version']);+ });+ },+ 90_000,+ );++ test.each(['[email protected]', 'ruff==0.12.0'])(+ 'stable Python descriptor %s emits an isolated bounded native tool request',+ async (descriptor) => {+ await withAcquisitionHome(async () => {+ const env = {+ UV_EXCLUDE_NEWER: '2025-01-01',+ UV_INDEX_URL: 'https://python.example.test/simple',+ };+ const launch = await resolveRegistryLaunch(+ registryPackage(descriptor, 'uvx', env),+ null,+ getLogger('descriptor-test'),+ );+ expect(launch.args).toEqual([+ '--from',+ 'ruff<=0.12.0',+ '--isolated',+ '--upgrade-package',+ 'ruff',+ 'ruff',+ '--version',+ ]);+ expect(launch.env).toMatchObject(env);+ });+ },+ );++ test.each([+ 'ruff',+ 'ruff>=0.12.0',+ 'ruff==0.12.0rc1',+ 'ruff@latest',+ 'git+https://example.com/ruff.git',+ ])(+ 'compatibility control: non-stable Python descriptor %s passes through',+ async (descriptor) => {+ const launch = await resolveRegistryLaunch(+ registryPackage(descriptor, 'uvx'),+ null,+ getLogger('descriptor-test'),+ );+ expect(launch.args).toEqual([descriptor, '--version']);+ },+ );++ test('compatibility control: binary and custom launch contracts are outside package admission', async () => {+ expect(+ resolveCustomLaunch({+ id: 'custom',+ name: 'Custom',+ command: 'node',+ args: ['script.js'],+ env: { ACP_FIXTURE: 'custom' },+ }),+ ).toMatchObject({+ kind: 'custom',+ cmd: 'node',+ args: ['script.js'],+ env: { ACP_FIXTURE: 'custom' },+ });+ await expect(+ resolveRegistryLaunch(+ { id: 'binary', name: 'Binary', version: '1.2.3', distribution: { binary: {} } },+ null,+ getLogger('descriptor-test'),+ ),+ ).rejects.toMatchObject({ code: 'unsupported-platform' });+ });++ test.each(['[email protected] - 1.2.3', '@scope/[email protected] - 1.2.3', 'agent<=1.2.3'])(+ 'compatibility control: Windows transports %s as one quoted operand',+ (operand) => {+ const wrapped = windowsCmdWrap('C:\\Program Files\\nodejs\\npm.cmd', [+ 'pack',+ operand,+ '--json',+ ]);+ expect(wrapped.args[3]).toContain(`"${operand}"`);+ expect(wrapped.args.slice(0, 3)).toEqual(['/d', '/s', '/c']);+ },+ );+});+describe('mergedEnv PATH augmentation', () => {test('an explicit overlay PATH is used verbatim — augmentation repairs only the inherited base', () => {const key = 'PATH' in process.env ? 'PATH' : 'Path';@@ -183,7 +320,10 @@ const plainEnv = (overlay: Record<string, string> = {}): Record<string, string>return { ...env, ...overlay };};-const launchFor = (script: string, overlay?: Record<string, string>): ResolvedLaunch => ({+const launchFor = (+ script: string,+ overlay?: Record<string, string>,+): ResolvedLaunch & { kind: 'custom' } => ({cmd: 'node',args: [script],env: plainEnv(overlay),@@ -718,7 +858,7 @@ describe('spawnAcpAgent — cwd isolation for npx launches', () => {return script;}- test('npx-kind spawns run from an OK-owned isolated cwd, not the record cwd', async () => {+ test('npx-kind spawns use an isolated cwd without accepting a project cwd', async () => {const dir = tmp();const script = makeEchoCwdScript(dir);const launch: ResolvedLaunch = {@@ -728,7 +868,10 @@ describe('spawnAcpAgent — cwd isolation for npx launches', () => {kind: 'npx',pathFromOverlay: false,};- const child = spawnAcpAgent(launch, dir);+ expect(() => {+ spawnNpxWithProjectCwd(launch, dir);+ }).toThrow('spawnAcpAgent does not accept a project cwd for npx launches.');+ const child = spawnAcpAgent(launch);if (child.pid !== undefined) strayPids.push(child.pid);await waitFor(() => existsSync(`${script}.out`), 10_000, 'spawned agent to report its cwd');const observed = readFileSync(`${script}.out`, 'utf8');@@ -738,10 +881,13 @@ describe('spawnAcpAgent — cwd isolation for npx launches', () => {test('the isolated cwd carries a private marker package.json so arborist walk terminates there', () => {const dir =- spawnAcpAgent(- { cmd: 'node', args: ['-e', ''], env: plainEnv(), kind: 'npx', pathFromOverlay: false },- tmp(),- ).spawnargs === undefined+ spawnAcpAgent({+ cmd: 'node',+ args: ['-e', ''],+ env: plainEnv(),+ kind: 'npx',+ pathFromOverlay: false,+ }).spawnargs === undefined? '': '';const markerPath = join(process.env.HOME ?? homedir(), '.ok', 'acp-npx-cwd', 'package.json');@@ -756,7 +902,7 @@ describe('spawnAcpAgent — cwd isolation for npx launches', () => {async (kind) => {const dir = tmp();const script = makeEchoCwdScript(dir);- const launch: ResolvedLaunch = {+ const launch: Exclude<ResolvedLaunch, { kind: 'npx' }> = {cmd: 'node',args: [script],env: plainEnv(),@@ -1060,13 +1206,13 @@ describe('brokenInterpreterHint', () => {});test('the managed-runtime hints name uv for a uvx runtime', () => {- const uvx = {+ const uvx: ResolvedLaunch = {cmd: '/home/u/.ok/runtimes/uv/uvx',args: [],env: {},kind: 'uvx',pathFromOverlay: false,- } as const;+ };for (const hint of [unrepairableManagedRuntimeHint(uvx, 'SIGABRT'),undeletableManagedRuntimeHint(uvx, 'SIGABRT'),@@ -1205,3 +1351,89 @@ describe('terminateAgentTree', () => {await waitFor(() => !isAlive(kidPid), 2_000, 'grandchild death');});});++describe('startup package policy classification', () => {+ const launch: ResolvedLaunch = {+ cmd: 'npx',+ args: [],+ env: {},+ kind: 'npx',+ pathFromOverlay: false,+ };+ test.each([+ 'npm error code E401',+ 'npm error code EINTEGRITY',+ 'npm error code ECONNREFUSED',+ 'npm error code ETARGET\nnpm error notarget No matching version found',+ ])('preserves the initialization failure for %s', (stderr) => {+ expect(packageAcquisitionFailure(launch, stderr)).toBeNull();+ });+ test('recognizes only a dated npm target refusal', () => {+ const detail =+ 'npm error code ETARGET\nnpm error notarget No matching version found with a date before 1970-01-01';+ const cause = new Error('initialize transport closed');+ expect(packageAcquisitionFailure(launch, detail, cause)).toMatchObject({+ code: 'install-failed',+ cause,+ machineDetail: detail,+ message: expect.stringContaining('release-date policy'),+ });+ });+ test('distinguishes uv cutoff refusal from another dependency failure', () => {+ const uv: ResolvedLaunch = { ...launch, kind: 'uvx' };+ const generic = 'No solution found when resolving tool dependencies';+ expect(packageAcquisitionFailure(uv, generic)).toBeNull();+ expect(+ packageAcquisitionFailure(uv, `${generic}\nversions were filtered by ` + '`exclude-newer`'),+ ).toMatchObject({ code: 'install-failed' });+ });+});++test.each(['npx', 'uvx'] as const)('%s startup policy diagnostics redact credentials', (kind) => {+ const signature =+ kind === 'npx'+ ? 'ETARGET No matching version found with a date before 1970-01-01'+ : 'No solution found when resolving tool dependencies; filtered by `exclude-newer`';+ const detail = `https://alice:fixture-long-secret${'z'.repeat(16_000)}@registry.example.test/pkg\n${signature} https://[email protected]:[email protected]/pkg https://alice:[email protected]/pkg https://[email protected]/simple https://github_pat_${'a'.repeat(30)}@registry.example.test/pkg Authorization: Bearer fixture-token`;+ const failure = packageAcquisitionFailure(+ { cmd: kind, args: [], env: {}, kind, pathFromOverlay: false },+ detail,+ );+ expect(failure?.machineDetail).toContain(signature);+ expect(failure?.machineDetail).not.toMatch(+ /fixture-secret|fixture-multi-secret|fixture-long-secret|fixture-token|github_pat_|0123456789abcdef|z{20}/,+ );+});++test.each([+ 'https://[email protected]/simple Authorization: Bearer fixture-token\n',+ 'https://[email protected]:[email protected]/simple Authorization: Bearer fixture-token\n',+])('diagnostic stderr redaction is independent of chunk boundaries: %s', (input) => {+ for (let split = 0; split <= input.length; split += 1) {+ const lines: string[] = [];+ const capture = createDiagnosticStderrCapture((line) => lines.push(line));+ capture.write(input.slice(0, split));+ capture.write(input.slice(split));+ capture.end();+ expect(lines.join('\n')).toContain('pypi.company.com/simple');+ expect(lines.join('\n')).not.toMatch(/0123456789abcdef|fixture-token|fixture-multi-secret/);+ }+});++test('diagnostic stderr omits oversized lines through their end and resumes safely', () => {+ const lines: string[] = [];+ const capture = createDiagnosticStderrCapture((line) => lines.push(line));+ capture.write(`https://alice:${'x'.repeat(16_000)}`);+ capture.write('[email protected]');+ capture.write('\nnext diagnostic\n');+ capture.end();+ expect(lines).toEqual(['[oversized diagnostic line omitted]', 'next diagnostic']);+});++test('diagnostic stderr flushes a final line without a newline', () => {+ const lines: string[] = [];+ const capture = createDiagnosticStderrCapture((line) => lines.push(line));+ capture.write('https://[email protected]/simple');+ capture.end();+ expect(lines).toEqual(['https://***@pypi.company.com/simple']);+});diff --git a/packages/server/src/acp/launch.ts b/packages/server/src/acp/launch.tsindex c1dd4cffb..b0303987d 100644--- a/packages/server/src/acp/launch.ts+++ b/packages/server/src/acp/launch.ts@@ -2,8 +2,9 @@ import { type ChildProcess, spawn } from 'node:child_process';import { constants, existsSync, statSync } from 'node:fs';import { access, chmod, readFile, stat } from 'node:fs/promises';import { homedir } from 'node:os';-import { delimiter, dirname, isAbsolute, join, resolve } from 'node:path';+import { basename, delimiter, dirname, isAbsolute, join, resolve } from 'node:path';import { augmentAgentSpawnPath, OK_DIR, OK_HOSTED_AGENT_ENV } from '@inkeep/open-knowledge-core';+import { z } from 'zod';import {tracedMkdir,tracedMkdirSync,@@ -13,31 +14,44 @@ import {} from '../fs-traced.ts';import type { PinoLogger } from '../logger.ts';import { downloadToFileWithSha, extractArchive, isWithin, sanitizeSegment } from './archive.ts';+import {+ ACQUISITION_DETAIL_MAX_CHARS,+ createDiagnosticStderrCapture,+ redactDiagnostic,+} from './diagnostics.ts';import { mergeLoginShellPath, preferLoginShellPath } from './login-shell-path.ts';import type { ManagedRuntime } from './managed-runtime.ts';import type { CustomAgentEntry, RegistryAgent, RegistryBinaryTarget } from './registry.ts';import { STALE_INSTALL_ARTIFACT_AGE_MS, stagedInstall } from './staged-install.ts';-export interface ResolvedLaunch {+export type ResolvedLaunch = {cmd: string;args: string[];env: Record<string, string>;- kind: 'npx' | 'uvx' | 'binary' | 'custom';pathFromOverlay: boolean;-}+} & ({ kind: 'npx' } | { kind: 'uvx' } | { kind: 'binary' } | { kind: 'custom' });export const MINIMUM_NPX_NODE_MAJOR = 22;export class AgentLaunchError extends Error {+ readonly machineDetail?: string;readonly code:| 'unsupported-platform'| 'no-distribution'| 'install-failed'| 'command-not-found';- constructor(code: AgentLaunchError['code'], message: string, options?: ErrorOptions) {+ constructor(+ code: AgentLaunchError['code'],+ message: string,+ options?: ErrorOptions & { machineDetail?: string },+ ) {super(message, options);this.name = 'AgentLaunchError';this.code = code;+ this.machineDetail =+ options?.machineDetail === undefined+ ? undefined+ : redactDiagnostic(options.machineDetail).slice(-ACQUISITION_DETAIL_MAX_CHARS);}}@@ -81,30 +95,70 @@ export function withHostedAgentMarker(env: Record<string, string>): Record<strinreturn { ...env, [OK_HOSTED_AGENT_ENV]: '1' };}+type PrepareRegistryLaunch = (launch: ResolvedLaunch) => Promise<ResolvedLaunch | null>;++export function resolveRegistryLaunch(+ agent: RegistryAgent,+ platformKey: string | null,+ log: PinoLogger,+ binaryCacheDir?: string,+): Promise<ResolvedLaunch>;+export function resolveRegistryLaunch(+ agent: RegistryAgent,+ platformKey: string | null,+ log: PinoLogger,+ binaryCacheDir: string | undefined,+ prepare: PrepareRegistryLaunch,+): Promise<ResolvedLaunch | null>;export async function resolveRegistryLaunch(agent: RegistryAgent,platformKey: string | null,log: PinoLogger,binaryCacheDir: string = defaultBinaryCacheDir(),-): Promise<ResolvedLaunch> {+ prepare?: PrepareRegistryLaunch,+): Promise<ResolvedLaunch | null> {const dist = agent.distribution;if (dist.npx !== undefined) {- return {+ const raw: ResolvedLaunch = {cmd: 'npx',args: ['-y', dist.npx.package, ...(dist.npx.args ?? [])],env: mergedEnv(dist.npx.env),kind: 'npx',pathFromOverlay: overlaySetsPath(dist.npx.env),};+ const launch = prepare === undefined ? raw : await prepare(raw);+ if (launch === null) return null;+ const pin =+ /^(?<name>(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+)@(?<version>(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*))$/.exec(+ dist.npx.package,+ );+ if (pin?.groups === undefined) return launch;+ const selected = await acquireNpmPackage(launch, pin.groups.name, pin.groups.version, log);+ return { ...launch, args: ['-y', selected, ...(dist.npx.args ?? [])] };}if (dist.uvx !== undefined) {- return {+ const pin = /^(?<name>[A-Za-z0-9][A-Za-z0-9._-]*)(?:==|@)(?<version>\d+\.\d+\.\d+)$/.exec(+ dist.uvx.package,+ );+ const args =+ pin?.groups === undefined+ ? [dist.uvx.package]+ : [+ '--from',+ `${pin.groups.name}<=${pin.groups.version}`,+ '--isolated',+ '--upgrade-package',+ pin.groups.name,+ pin.groups.name,+ ];+ const launch: ResolvedLaunch = {cmd: 'uvx',- args: [dist.uvx.package, ...(dist.uvx.args ?? [])],+ args: [...args, ...(dist.uvx.args ?? [])],env: mergedEnv(dist.uvx.env),kind: 'uvx',pathFromOverlay: overlaySetsPath(dist.uvx.env),};+ return prepare === undefined ? launch : prepare(launch);}if (dist.binary !== undefined) {if (platformKey === null || dist.binary[platformKey] === undefined) {@@ -122,17 +176,192 @@ export async function resolveRegistryLaunch(`${agent.name} manifest cmd escapes its archive`,);}- return {+ const launch: ResolvedLaunch = {cmd,args: [...(target.args ?? [])],env: mergedEnv(target.env),kind: 'binary',pathFromOverlay: overlaySetsPath(target.env),};+ return prepare === undefined ? launch : prepare(launch);}throw new AgentLaunchError('no-distribution', `${agent.name} has no supported distribution`);}+const npmPackedPackage = z.object({+ name: z.string(),+ version: z.string().regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/),+});+export const npmPackResult = z+ .union([+ z.array(npmPackedPackage),+ z.record(z.string(), npmPackedPackage).transform((packages) => Object.values(packages)),+ ])+ .pipe(z.tuple([npmPackedPackage]));++function stableVersionAtMost(version: string, ceiling: string): boolean {+ const upper = ceiling.split('.').map(BigInt);+ for (const [i, part] of version.split('.').map(BigInt).entries()) {+ if (part !== upper[i]) return part < upper[i];+ }+ return true;+}++function datedNpmRefusal(detail: string): boolean {+ return /\bETARGET\b/.test(detail) && /with a date before/.test(detail);+}++export function packageAcquisitionFailure(+ launch: ResolvedLaunch,+ detail: string,+ cause?: unknown,+): AgentLaunchError | null {+ const npmRefusal = launch.kind === 'npx' && datedNpmRefusal(detail);+ const uvRefusal =+ launch.kind === 'uvx' &&+ /No solution found when resolving tool dependencies/.test(detail) &&+ /filtered by `exclude-newer`/.test(detail);+ if (!npmRefusal && !uvRefusal) return null;+ return new AgentLaunchError(+ 'install-failed',+ "No allowed release is available under your package manager's release-date policy. Try again after an allowed release becomes available.",+ { cause, machineDetail: detail },+ );+}++async function npmCommand(launch: ResolvedLaunch): Promise<string | null> {+ let npx = launch.cmd;+ if (!isPathQualified(npx)) {+ if (process.platform === 'win32') npx = resolveWindowsCommand(npx, envPath(launch.env));+ else {+ for (const dir of (envPath(launch.env) ?? '').split(delimiter)) {+ if (dir !== '' && (await isExecutableFile(join(dir, npx)))) {+ npx = join(dir, npx);+ break;+ }+ }+ }+ }+ if (!isPathQualified(npx))+ throw new AgentLaunchError(+ 'install-failed',+ 'Could not locate npm for the selected agent runtime.',+ );+ const npm = join(dirname(npx), basename(npx).replace(/^npx/i, 'npm'));+ return (await isExecutableFile(npm)) ? npm : null;+}++async function probeNpmPackage(+ launch: ResolvedLaunch,+ descriptor: string,+ cmd: string,+): Promise<{ code: number | null; stdout: string; detail: string }> {+ const child = spawnAcpAgent({+ ...launch,+ kind: 'npx',+ cmd,+ args: ['pack', descriptor, '--dry-run', '--ignore-scripts', '--json'],+ });+ let stdout = '';+ let stderr = '';+ let size = 0;+ let failure: string | undefined;+ const stop = (message: string): void => {+ if (failure !== undefined) return;+ failure = message;+ void terminateAgentTree(child, { graceMs: 100 });+ };+ const timer = setTimeout(() => stop('npm package acquisition timed out.'), 30_000);+ timer.unref();+ child.stdout?.setEncoding('utf8');+ child.stderr?.setEncoding('utf8');+ child.stdout?.on('data', (chunk: string) => {+ size += Buffer.byteLength(chunk);+ if (size > 16 * 1024 * 1024) stop('npm package acquisition output exceeded its limit.');+ else stdout += chunk;+ });+ const stderrCapture = createDiagnosticStderrCapture((line) => {+ stderr = `${stderr}${line}\n`.slice(-ACQUISITION_DETAIL_MAX_CHARS);+ });+ child.stderr?.on('end', stderrCapture.end);+ child.stderr?.on('data', (chunk: string) => {+ size += Buffer.byteLength(chunk);+ stderrCapture.write(chunk);+ if (size > 16 * 1024 * 1024) stop('npm package acquisition output exceeded its limit.');+ });+ child.once('error', (err) => {+ failure = err.message;+ });+ try {+ const code = await new Promise<number | null>((resolvePromise) =>+ child.once('close', resolvePromise),+ );+ const detail = `${stdout}\n${stderr}`.trim();+ if (failure !== undefined)+ throw new AgentLaunchError('install-failed', failure, { machineDetail: detail });+ return { code, stdout, detail };+ } finally {+ clearTimeout(timer);+ await terminateAgentTree(child, { graceMs: 100 });+ }+}++async function acquireNpmPackage(+ launch: ResolvedLaunch,+ name: string,+ ceiling: string,+ log: PinoLogger,+): Promise<string> {+ let descriptor = `${name}@${ceiling}`;+ const npm = await npmCommand(launch);+ if (npm === null) {+ log.warn(+ { package: descriptor },+ '[acp-launch] package acquisition probe skipped: no executable npm sibling; forwarding the catalog pin to npx',+ );+ return descriptor;+ }+ let result = await probeNpmPackage(launch, descriptor, npm);+ let bounded = false;+ if (result.code !== 0 && datedNpmRefusal(result.detail)) {+ bounded = true;+ descriptor = `${name}@0.0.0 - ${ceiling}`;+ result = await probeNpmPackage(launch, descriptor, npm);+ }+ if (result.code !== 0) {+ const policy = bounded && /\b(?:ETARGET|ENOVERSIONS)\b/.test(result.detail);+ throw new AgentLaunchError(+ 'install-failed',+ policy+ ? `No release of ${name} at or below ${ceiling} is available under your package manager's release-date policy. Try again after an allowed release becomes available.`+ : `Could not acquire ${descriptor}.`,+ { machineDetail: result.detail },+ );+ }+ let selected: z.infer<typeof npmPackedPackage>;+ try {+ [selected] = npmPackResult.parse(JSON.parse(result.stdout));+ } catch (cause) {+ throw new AgentLaunchError(+ 'install-failed',+ 'npm returned invalid package acquisition metadata.',+ { cause, machineDetail: result.detail },+ );+ }+ if (+ selected.name !== name ||+ !stableVersionAtMost(selected.version, ceiling) ||+ (!bounded && selected.version !== ceiling)+ ) {+ throw new AgentLaunchError(+ 'install-failed',+ `npm returned ${selected.name}@${selected.version} outside the requested constraint ${descriptor}.`,+ { machineDetail: result.detail },+ );+ }+ return `${name}@${selected.version}`;+}+export function resolveCustomLaunch(entry: CustomAgentEntry): ResolvedLaunch {return {cmd: entry.command,@@ -666,19 +895,27 @@ function acpNpxIsolatedCwd(): string {return dir;}-export function spawnAcpAgent(launch: ResolvedLaunch, cwd: string): ChildProcess {- if (!isAbsolute(cwd)) {- throw new Error(`spawnAcpAgent requires an absolute cwd, got: ${cwd}`);+export function spawnAcpAgent(launch: ResolvedLaunch & { kind: 'npx' }): ChildProcess;+export function spawnAcpAgent(+ launch: Exclude<ResolvedLaunch, { kind: 'npx' }>,+ projectCwd: string,+): ChildProcess;+export function spawnAcpAgent(launch: ResolvedLaunch, projectCwd?: string): ChildProcess {+ if (launch.kind === 'npx' && projectCwd !== undefined) {+ throw new Error('spawnAcpAgent does not accept a project cwd for npx launches.');+ }+ if (projectCwd === undefined ? launch.kind !== 'npx' : !isAbsolute(projectCwd)) {+ throw new Error(`spawnAcpAgent requires an absolute cwd, got: ${projectCwd}`);}+ const cwd = launch.kind === 'npx' ? acpNpxIsolatedCwd() : projectCwd;const win = process.platform === 'win32';const resolved = win ? resolveWindowsCommand(launch.cmd, envPath(launch.env)) : launch.cmd;const wrap = win && /\.(cmd|bat)$/i.test(resolved);const { cmd, args } = wrap? windowsCmdWrap(resolved, launch.args): { cmd: resolved, args: launch.args };- const spawnCwd = launch.kind === 'npx' ? acpNpxIsolatedCwd() : cwd;return spawn(cmd, args, {- cwd: spawnCwd,+ cwd,env: withHostedAgentMarker(launch.env),stdio: ['pipe', 'pipe', 'pipe'],shell: false,diff --git a/packages/server/src/acp/managed-runtime-flow.integration.test.ts b/packages/server/src/acp/managed-runtime-flow.integration.test.tsindex 1cb260712..420b93caf 100644--- a/packages/server/src/acp/managed-runtime-flow.integration.test.ts+++ b/packages/server/src/acp/managed-runtime-flow.integration.test.ts@@ -4,22 +4,31 @@ import {existsSync,mkdirSync,mkdtempSync,+ readdirSync,readFileSync,rmSync,utimesSync,writeFileSync,} from 'node:fs';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { join, relative } from 'node:path';import type {ThreadEvent,ThreadServerFrame,} from '@inkeep/open-knowledge-core/acp/thread-protocol';import { afterEach, describe, expect, test } from 'vitest';+import { ZipFile } from 'yazl';import type { AgentSessionManager } from '../agent-sessions.ts';import { getLogger } from '../logger.ts';+import { withLocalAcquisitionRegistry } from './acquisition-contract.test-helper.ts';import { MINIMUM_NPX_NODE_MAJOR } from './launch.ts';import { describeRuntime, ensureManagedRuntime, findManagedRuntime } from './managed-runtime.ts';+import {+ installNodeFixture,+ npmCli,+ registryPackage,+ writeExecutable,+} from './package-acquisition.test-helper.ts';import { AcpPermissionStore } from './permissions.ts';import { AcpRegistry } from './registry.ts';import { AcpThreadManager } from './thread-manager.ts';@@ -81,6 +90,9 @@ function fakeNodeFetch(bytes: Buffer, sha: string, agent: unknown = NPX_AGENT):const names = ['darwin-arm64', 'darwin-x64', 'linux-arm64', 'linux-x64'].map((n) => `${sha} node-${MANAGED_NODE_VERSION}-${n}.tar.gz`,);+ names.push(+ ...['win-arm64', 'win-x64'].map((n) => `${sha} node-${MANAGED_NODE_VERSION}-${n}.zip`),+ );return new Response(`${names.join('\n')}\n`, { status: 200 });}return new Response(new Uint8Array(bytes), {@@ -153,6 +165,161 @@ function findConsentRequest();}+describe('package admission after runtime preparation', () => {+ test.each(['system', 'login-shell', 'managed'] as const)(+ '%s runtime performs real npm admission in its isolated cwd',+ async (source) => {+ await withLocalAcquisitionRegistry(async (home) => {+ const realNpx = npmCli('npx');+ const realNpm = npmCli('npm');+ expect(existsSync(realNpm)).toBe(true);+ const admissionLog = join(home, 'admission.jsonl');+ const selectedBin = join(home, 'selected', 'node-vTEST', 'bin');+ mkdirSync(selectedBin, { recursive: true });+ installNodeFixture(selectedBin);+ writeExecutable(+ join(selectedBin, 'npx'),+ `const r=require('node:child_process').spawnSync(${JSON.stringify(process.execPath)},[${JSON.stringify(realNpx)},...process.argv.slice(2)],{stdio:'inherit',env:process.env});process.exit(r.status ?? 1);`,+ );+ const npmScript = writeExecutable(+ join(selectedBin, 'npm'),+ `require('node:fs').appendFileSync(${JSON.stringify(admissionLog)},JSON.stringify({args:process.argv.slice(2),cwd:process.cwd(),before:process.env.npm_config_before,executable:process.argv[1]})+'\\n');const r=require('node:child_process').spawnSync(${JSON.stringify(process.execPath)},[${JSON.stringify(realNpm)},...process.argv.slice(2)],{stdio:'inherit',env:process.env});process.exit(r.status ?? 1);`,+ );+ const empty = join(home, 'empty');+ mkdirSync(empty);+ let bytes: Buffer;+ if (process.platform === 'win32') {+ const zip = new ZipFile();+ for (const entry of readdirSync(selectedBin)) {+ const path = join(selectedBin, entry);+ zip.addFile(path, relative(join(home, 'selected'), path).replaceAll('\\', '/'));+ }+ zip.end();+ const chunks: Buffer[] = [];+ for await (const chunk of zip.outputStream) chunks.push(chunk);+ bytes = Buffer.concat(chunks);+ } else {+ const tarPath = join(home, 'runtime.tar.gz');+ execFileSync('tar', ['-czf', tarPath, '-C', join(home, 'selected'), 'node-vTEST']);+ bytes = readFileSync(tarPath);+ }+ const sha = createHash('sha256').update(bytes).digest('hex');+ const agent = {+ ...registryPackage(+ '[email protected]',+ 'npx',+ source === 'login-shell'+ ? undefined+ : { PATH: source === 'system' ? selectedBin : empty },+ ),+ id: 'npxagent',+ };+ process.env.npm_config_before = '1970-01-01';+ if (source === 'login-shell') process.env.PATH = empty;+ const manager = makeManager({+ contentDir: home,+ localDir: tmp(),+ runtimeRoot: tmp(),+ fetchImpl: fakeNodeFetch(bytes, sha, agent),+ resolveLoginShellPath: async () => (source === 'login-shell' ? selectedBin : null),+ });+ const events: ThreadEvent[] = [];+ try {+ const info = await manager.createThread({+ agent: { source: 'registry', id: 'npxagent' },+ });+ await collect(manager, info.threadId, events);+ if (source === 'managed') {+ await expect.poll(() => findConsentRequest(events), { timeout: 10_000 }).toBeDefined();+ expect(existsSync(admissionLog)).toBe(false);+ const consent = findConsentRequest(events);+ if (!consent) throw new Error('missing runtime consent');+ manager.respondRuntimeConsent(info.threadId, consent.requestId, { kind: 'granted' });+ }+ await expect+ .poll(() => manager.getInfo(info.threadId)?.status, { timeout: 25_000 })+ .toBe('error');+ expect(+ existsSync(admissionLog),+ 'selected npm must perform admission before ACP starts',+ ).toBe(true);+ const probes = readFileSync(admissionLog, 'utf8')+ .trim()+ .split('\n')+ .map((line) => JSON.parse(line));+ expect(probes[0]).toMatchObject({+ args: expect.arrayContaining(['pack', '--dry-run', '--ignore-scripts', '--json']),+ cwd: join(home, '.ok', 'acp-npx-cwd'),+ before: '1970-01-01',+ });+ if (source !== 'managed') expect(probes[0].executable).toBe(npmScript);+ else expect(probes[0].executable).not.toBe(npmScript);+ await expect+ .poll(+ () => events.some((event) => event.kind === 'status' && event.status === 'error'),+ { timeout: 5000 },+ )+ .toBe(true);+ const failure = events+ .filter((event) => event.kind === 'status' && event.status === 'error')+ .at(-1);+ expect(failure).toMatchObject({+ failure: {+ reason: 'connect',+ machineDetail: expect.stringMatching(/ETARGET|ENOVERSIONS/),+ },+ });+ } finally {+ await manager.destroy();+ }+ });+ },+ 90_000,+ );++ test.each(['declined', 'closed'] as const)(+ 'compatibility control: %s runtime consent does not acquire a package',+ async (decision) => {+ await withLocalAcquisitionRegistry(async (home) => {+ const empty = join(home, 'empty');+ mkdirSync(empty);+ const agent = {+ ...registryPackage('[email protected]', 'npx', { PATH: empty }),+ id: 'npxagent',+ };+ const manager = makeManager({+ contentDir: home,+ localDir: tmp(),+ runtimeRoot: tmp(),+ fetchImpl: fakeNodeFetch(Buffer.from('unused'), 'f'.repeat(64), agent),+ });+ const events: ThreadEvent[] = [];+ try {+ const info = await manager.createThread({ agent: { source: 'registry', id: agent.id } });+ await collect(manager, info.threadId, events);+ await expect.poll(() => findConsentRequest(events), { timeout: 10_000 }).toBeDefined();+ const request = findConsentRequest(events);+ if (!request) throw new Error('missing runtime consent');+ if (decision === 'closed') await manager.closeThread(info.threadId);+ else {+ manager.respondRuntimeConsent(info.threadId, request.requestId, { kind: 'declined' });+ await expect+ .poll(() => manager.getInfo(info.threadId)?.status, { timeout: 5000 })+ .toBe('error');+ }+ expect(existsSync(join(home, 'npm-cache', '_cacache'))).toBe(false);+ expect(+ events.some((event) => event.kind === 'status' && event.status === 'spawning'),+ ).toBe(false);+ } finally {+ await manager.destroy();+ }+ });+ },+ 30_000,+ );+});+describe('managed-runtime consent + download flow', () => {test('normal launch cleans stale staging after a runtime is installed', async () => {const contentDir = tmp();diff --git a/packages/server/src/acp/npm-json.test-fixture.json b/packages/server/src/acp/npm-json.test-fixture.jsonnew file mode 100644index 000000000..f491b40b3--- /dev/null+++ b/packages/server/src/acp/npm-json.test-fixture.json@@ -0,0 +1,120 @@+[+ {+ "npmVersion": "11.17.0",+ "pack": [+ {+ "id": "[email protected]",+ "name": "is-number",+ "version": "7.0.0",+ "size": 3730,+ "unpackedSize": 9615,+ "shasum": "7535345b896734d5f80c4d06c50955527a14f12b",+ "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",+ "filename": "is-number-7.0.0.tgz",+ "files": [+ {+ "path": "LICENSE",+ "size": 1091,+ "mode": 420+ },+ {+ "path": "README.md",+ "size": 6514,+ "mode": 420+ },+ {+ "path": "index.js",+ "size": 411,+ "mode": 420+ },+ {+ "path": "package.json",+ "size": 1599,+ "mode": 420+ }+ ],+ "entryCount": 4,+ "bundled": []+ }+ ],+ "publicationTimes": {+ "modified": "2023-05-26T16:12:33.057Z",+ "created": "2014-09-22T01:58:51.592Z",+ "0.1.0": "2014-09-22T01:58:51.592Z",+ "0.1.1": "2014-09-22T03:37:27.931Z",+ "1.0.0": "2015-01-24T10:16:54.470Z",+ "1.1.0": "2015-01-24T10:33:21.598Z",+ "1.1.1": "2015-03-05T18:37:07.633Z",+ "1.1.2": "2015-03-05T18:57:33.841Z",+ "2.0.0": "2015-05-02T08:11:57.926Z",+ "2.0.1": "2015-05-03T04:27:13.630Z",+ "2.0.2": "2015-05-03T05:59:55.976Z",+ "2.1.0": "2015-11-22T13:56:56.624Z",+ "3.0.0": "2016-09-11T00:51:30.912Z",+ "4.0.0": "2017-10-17T05:43:56.559Z",+ "5.0.0": "2018-01-29T03:06:41.225Z",+ "6.0.0": "2018-03-31T17:02:39.953Z",+ "7.0.0": "2018-07-04T15:08:58.238Z"+ }+ },+ {+ "npmVersion": "12.0.1",+ "pack": {+ "is-number": {+ "id": "[email protected]",+ "name": "is-number",+ "version": "7.0.0",+ "size": 3730,+ "unpackedSize": 9615,+ "shasum": "7535345b896734d5f80c4d06c50955527a14f12b",+ "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",+ "filename": "is-number-7.0.0.tgz",+ "files": [+ {+ "path": "LICENSE",+ "size": 1091,+ "mode": 420+ },+ {+ "path": "README.md",+ "size": 6514,+ "mode": 420+ },+ {+ "path": "index.js",+ "size": 411,+ "mode": 420+ },+ {+ "path": "package.json",+ "size": 1599,+ "mode": 420+ }+ ],+ "entryCount": 4,+ "bundled": []+ }+ },+ "publicationTimes": [+ {+ "modified": "2023-05-26T16:12:33.057Z",+ "created": "2014-09-22T01:58:51.592Z",+ "0.1.0": "2014-09-22T01:58:51.592Z",+ "0.1.1": "2014-09-22T03:37:27.931Z",+ "1.0.0": "2015-01-24T10:16:54.470Z",+ "1.1.0": "2015-01-24T10:33:21.598Z",+ "1.1.1": "2015-03-05T18:37:07.633Z",+ "1.1.2": "2015-03-05T18:57:33.841Z",+ "2.0.0": "2015-05-02T08:11:57.926Z",+ "2.0.1": "2015-05-03T04:27:13.630Z",+ "2.0.2": "2015-05-03T05:59:55.976Z",+ "2.1.0": "2015-11-22T13:56:56.624Z",+ "3.0.0": "2016-09-11T00:51:30.912Z",+ "4.0.0": "2017-10-17T05:43:56.559Z",+ "5.0.0": "2018-01-29T03:06:41.225Z",+ "6.0.0": "2018-03-31T17:02:39.953Z",+ "7.0.0": "2018-07-04T15:08:58.238Z"+ }+ ]+ }+]diff --git a/packages/server/src/acp/package-acquisition.test-helper.test.ts b/packages/server/src/acp/package-acquisition.test-helper.test.tsnew file mode 100644index 000000000..7263e0ebd--- /dev/null+++ b/packages/server/src/acp/package-acquisition.test-helper.test.ts@@ -0,0 +1,96 @@+import { describe, expect, test } from 'vitest';+import {+ acquisitionDescriptors,+ native,+ npmOutputs,+ npmPackedVersion,+ npmPublicationTimes,+ registryPackage,+} from './package-acquisition.test-helper.ts';++describe('package acquisition command outcomes', () => {+ test('a signal-terminated command cannot report success', async () => {+ const result = await native(process.execPath, ['-e', "process.kill(process.pid, 'SIGTERM')"]);+ expect(result.code).toBe('SIGTERM');+ expect(result.stderr).toBe('');+ });++ test('preserves successful stdout and nonzero exit diagnostics', async () => {+ expect(await native(process.execPath, ['-e', "process.stdout.write('ready')"])).toEqual({+ code: 0,+ stdout: 'ready',+ stderr: '',+ });+ const failed = await native(process.execPath, [+ '-e',+ "process.stderr.write('refused'); process.exit(9)",+ ]);+ expect(failed.code).toBe(9);+ expect(failed.stderr).toBe('refused');+ });++ test('names a missing executable as a prerequisite failure', async () => {+ const failed = await native('ok-nonexistent-acquisition-executable', []);+ expect(failed.code).toBe('ENOENT');+ expect(failed.stderr).toBe('Missing test prerequisite: ok-nonexistent-acquisition-executable');+ });+});++describe('npm JSON output contracts', () => {+ test.each(npmOutputs)('reads captured npm $npmVersion output', ({ pack, publicationTimes }) => {+ expect(npmPackedVersion(JSON.stringify(pack))).toBe('7.0.0');+ expect(npmPublicationTimes(JSON.stringify(publicationTimes))['7.0.0']).toBe(+ '2018-07-04T15:08:58.238Z',+ );+ });++ test.each([+ { label: 'missing name', pack: [{ version: '7.0.0' }] },+ { label: 'prerelease', pack: { 'is-number': { name: 'is-number', version: '7.0.0-beta.1' } } },+ ])('rejects $label pack metadata outside the launch contract', ({ pack }) => {+ expect(() => npmPackedVersion(JSON.stringify(pack))).toThrow('Could not parse npm JSON output');+ });++ test.each([npmPackedVersion, npmPublicationTimes])(+ '%s preserves invalid output and its parse error',+ (parse) => {+ const invalid = '{broken-npm-output';+ expect(() => parse(invalid)).toThrow(invalid);+ expect(() => parse(invalid)).toThrow(expect.objectContaining({ cause: expect.any(Error) }));+ },+ );+});++test('catalog comparison retains every npm and uv descriptor and ignores binary-only agents', () => {+ const npx = { package: '[email protected]', args: ['--stdio'], env: { SETTING: 'enabled' } };+ const uvx = { package: 'python-one==2.0.0', args: ['--acp'], env: { PYTHON_SETTING: '1' } };+ const agents = [+ { ...registryPackage('ignored'), id: 'z', distribution: { npx, uvx } },+ { ...registryPackage('ignored'), id: 'binary', distribution: { binary: {} } },+ { ...registryPackage('ignored'), id: 'a', distribution: { uvx } },+ { ...registryPackage('ignored'), id: 'b', distribution: { npx } },+ ];+ expect(acquisitionDescriptors(agents)).toEqual([+ { id: 'a', npx: undefined, uvx },+ { id: 'b', npx, uvx: undefined },+ { id: 'z', npx, uvx },+ ]);+});++test.each(['syntax', 'schema-object', 'schema-array'] as const)(+ 'late %s failures retain the offending npm output',+ (mode) => {+ const history = Object.fromEntries(+ Array.from({ length: 200 }, (_, i) => [`1.0.${i}`, '2020-01-01T00:00:00Z']),+ );+ const record = { ...history, 'broken-release': 42, 'later-release': '2020-01-01T00:00:00Z' };+ const output =+ mode === 'syntax'+ ? JSON.stringify(record).replace(':42', ':INVALID_NPM_JSON')+ : JSON.stringify(mode === 'schema-array' ? [record] : record);+ expect(() => npmPublicationTimes(output)).toThrow('broken-release');+ expect(() => npmPublicationTimes(output)).toThrow(+ expect.objectContaining({ cause: expect.any(Error) }),+ );+ },+);diff --git a/packages/server/src/acp/package-acquisition.test-helper.ts b/packages/server/src/acp/package-acquisition.test-helper.tsnew file mode 100644index 000000000..24832242e--- /dev/null+++ b/packages/server/src/acp/package-acquisition.test-helper.ts@@ -0,0 +1,296 @@+import { type ChildProcess, execFile } from 'node:child_process';+import {+ copyFileSync,+ existsSync,+ mkdtempDisposableSync,+ readFileSync,+ realpathSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { basename, delimiter, dirname, join } from 'node:path';+import { findNodeAtLocation, type ParseError, parseTree } from 'jsonc-parser';+import { z } from 'zod';+import {+ npmPackResult,+ type ResolvedLaunch,+ resolveWindowsCommand,+ spawnAcpAgent,+ terminateAgentTree,+ windowsCmdWrap,+} from './launch.ts';+import type { RegistryAgent } from './registry.ts';++function executable(name: string): string {+ if (process.platform === 'win32') {+ const path = resolveWindowsCommand(name, process.env.PATH);+ if (!existsSync(path)) throw new Error(`Missing test prerequisite: ${name}`);+ return realpathSync(path);+ }+ const path = (process.env.PATH ?? '')+ .split(delimiter)+ .map((dir) => join(dir, name))+ .find(existsSync);+ if (!path) throw new Error(`Missing test prerequisite: ${name}`);+ return realpathSync(path);+}++export function npmCli(name: 'npm' | 'npx'): string {+ const command = executable('npx');+ const path =+ process.platform === 'win32'+ ? join(dirname(command), 'node_modules', 'npm', 'bin', `${name}-cli.js`)+ : join(dirname(command), `${name}-cli.js`);+ if (!existsSync(path)) throw new Error(`Missing test prerequisite: ${path}`);+ return path;+}++export function installNodeFixture(bin: string): void {+ if (process.platform === 'win32') copyFileSync(process.execPath, join(bin, 'node.exe'));+ else symlinkSync(process.execPath, join(bin, 'node'));+}++export function withAcquisitionHome<T>(run: (home: string) => Promise<T>): Promise<T> {+ return acquisitionHome(run, false);+}++export function withLiveAcquisitionHome<T>(run: (home: string) => Promise<T>): Promise<T> {+ return acquisitionHome(run, true);+}++async function acquisitionHome<T>(run: (home: string) => Promise<T>, network: boolean): Promise<T> {+ const prior = { ...process.env };+ const inherited = (key: string) =>+ Object.entries(prior).find(([name]) => name.toLowerCase() === key.toLowerCase())?.[1];+ using home = mkdtempDisposableSync(join(realpathSync(tmpdir()), 'ok-acquisition-'));+ const env = {+ PATH: inherited('PATH'),+ PATHEXT: inherited('PATHEXT'),+ SystemRoot: inherited('SystemRoot'),+ ComSpec: inherited('ComSpec'),+ HOME: home.path,+ USERPROFILE: home.path,+ TMPDIR: home.path,+ TMP: home.path,+ TEMP: home.path,+ XDG_CONFIG_HOME: join(home.path, 'config'),+ XDG_CACHE_HOME: join(home.path, 'cache'),+ npm_config_cache: join(home.path, 'npm-cache'),+ npm_config_userconfig: join(home.path, '.npmrc'),+ npm_config_globalconfig: join(home.path, 'global.npmrc'),+ npm_config_registry: network ? 'https://registry.npmjs.org/' : 'http://127.0.0.1:1/',+ UV_OFFLINE: network ? '0' : '1',+ npm_config_ignore_scripts: 'true',+ npm_config_audit: 'false',+ npm_config_fund: 'false',+ npm_config_update_notifier: 'false',+ npm_config_fetch_timeout: '3000',+ npm_config_fetch_retries: '0',+ DO_NOT_TRACK: '1',+ UV_CACHE_DIR: join(home.path, 'uv-cache'),+ UV_TOOL_DIR: join(home.path, 'uv-tools'),+ UV_TOOL_BIN_DIR: join(home.path, 'uv-bin'),+ UV_PYTHON_INSTALL_DIR: join(home.path, 'python'),+ UV_HTTP_TIMEOUT: '20',+ UV_HTTP_RETRIES: '0',+ UV_PYTHON_DOWNLOADS: 'never',+ };+ for (const key of Object.keys(process.env)) delete process.env[key];+ for (const [key, value] of Object.entries(env)) if (value !== undefined) process.env[key] = value;+ writeFileSync(join(home.path, '.npmrc'), '');+ writeFileSync(join(home.path, 'global.npmrc'), '');+ try {+ return await run(home.path);+ } finally {+ for (const key of Object.keys(process.env)) delete process.env[key];+ Object.assign(process.env, prior);+ }+}++export function registryPackage(+ packageSpec: string,+ runtime: 'npx' | 'uvx' = 'npx',+ env?: Record<string, string>,+): RegistryAgent {+ return {+ id: 'acquisition-fixture',+ name: 'Acquisition fixture',+ version: '99.99.99',+ distribution: { [runtime]: { package: packageSpec, args: ['--version'], env } },+ };+}++export function native(cmd: string, args: string[], env: NodeJS.ProcessEnv = process.env) {+ const path = Object.entries(env).find(([key]) => key.toLowerCase() === 'path')?.[1];+ const resolved = process.platform === 'win32' ? resolveWindowsCommand(cmd, path) : cmd;+ const wrap = process.platform === 'win32' && /\.(cmd|bat)$/i.test(resolved);+ const command = wrap ? windowsCmdWrap(resolved, args) : { cmd: resolved, args };+ return new Promise<{ code: number | string; stdout: string; stderr: string }>((resolve) => {+ execFile(+ command.cmd,+ command.args,+ {+ cwd: process.env.HOME,+ env,+ shell: false,+ windowsHide: true,+ windowsVerbatimArguments: wrap,+ timeout: 60_000,+ maxBuffer: 16 * 1024 * 1024,+ },+ (error, stdout, stderr) =>+ resolve({+ code: error === null ? 0 : (error.code ?? error.signal ?? error.message),+ stdout,+ stderr: error?.code === 'ENOENT' ? `Missing test prerequisite: ${cmd}` : stderr,+ }),+ );+ });+}++export async function npmNative(args: string[], env: NodeJS.ProcessEnv = process.env) {+ return native('npm', args, env);+}++export function freezeNpmClock(home: string, now: number): void {+ const path = join(home, 'clock.cjs');+ writeFileSync(path, `Date.now = () => ${now};\n`);+ process.env.NODE_OPTIONS = `--require=${JSON.stringify(path)}`;+}++export async function captureChild(+ child: ChildProcess,+ { timeoutMs = 60_000, graceMs = 100 }: { timeoutMs?: number; graceMs?: number } = {},+) {+ let stdout = '';+ let stderr = '';+ child.stdout?.setEncoding('utf8');+ child.stderr?.setEncoding('utf8');+ child.stdout?.on('data', (chunk: string) => {+ stdout += chunk;+ });+ child.stderr?.on('data', (chunk: string) => {+ stderr += chunk;+ });+ const timer = setTimeout(() => void terminateAgentTree(child, { graceMs }), timeoutMs);+ try {+ const code = await new Promise<number | null>((resolve, reject) => {+ child.once('close', resolve);+ child.once('error', reject);+ });+ return { code, stdout, stderr };+ } finally {+ clearTimeout(timer);+ await terminateAgentTree(child, { graceMs });+ }+}++export function writeExecutable(path: string, body: string): string {+ if (process.platform === 'win32') {+ const script = `${path}.cjs`;+ writeFileSync(script, `${body}\n`);+ writeFileSync(+ `${path}.cmd`,+ `@echo off\r\n"${process.execPath}" "%~dp0${basename(script)}" %*\r\n`,+ );+ return script;+ }+ writeFileSync(path, `#!${process.execPath}\n${body}\n`, { mode: 0o755 });+ return path;+}++export function npmPackedVersion(stdout: string): string {+ const [selected] = parseNpmOutput(npmPackResult, stdout);+ return selected.version;+}++export function npmPublicationTimes(stdout: string): Record<string, string> {+ const times = z.record(z.string(), z.string());+ return parseNpmOutput(z.union([times, z.tuple([times]).transform(([entry]) => entry)]), stdout);+}++const MAX_NPM_PARSE_OUTPUT_CHARS = 2_048;++function npmIssuePaths(issues: z.core.$ZodIssue[]): Array<Array<string | number>> {+ return issues.flatMap((issue) =>+ issue.code === 'invalid_union'+ ? issue.errors.flatMap(npmIssuePaths)+ : [issue.path.filter((part): part is string | number => typeof part !== 'symbol')],+ );+}++function npmFailureExcerpt(stdout: string, cause: unknown): string {+ const errors: ParseError[] = [];+ const root = parseTree(stdout, errors, { disallowComments: true, allowTrailingComma: false });+ let offset = errors[0]?.offset ?? 0;+ if (cause instanceof z.ZodError && root !== undefined) {+ const paths = npmIssuePaths(cause.issues).sort((a, b) => b.length - a.length);+ for (const path of paths) {+ const node = findNodeAtLocation(root, path);+ if (node === undefined) continue;+ offset = node.offset;+ break;+ }+ }+ const start = Math.max(0, offset - MAX_NPM_PARSE_OUTPUT_CHARS / 2);+ const end = Math.min(stdout.length, start + MAX_NPM_PARSE_OUTPUT_CHARS);+ return `[characters ${start}-${end} of ${stdout.length}] ${stdout.slice(start, end)}`;+}++function parseNpmOutput<T>(schema: z.ZodType<T>, stdout: string): T {+ try {+ return schema.parse(JSON.parse(stdout));+ } catch (cause) {+ throw new Error(`Could not parse npm JSON output: ${npmFailureExcerpt(stdout, cause)}`, {+ cause,+ });+ }+}++export const npmOutputs = z+ .array(+ z.object({+ npmVersion: z.string().regex(/^\d+\.\d+\.\d+$/),+ pack: z.unknown(),+ publicationTimes: z.unknown(),+ }),+ )+ .parse(+ JSON.parse(readFileSync(new URL('./npm-json.test-fixture.json', import.meta.url), 'utf8')),+ );++export function compareVersions(left: string, right: string): number {+ return left.localeCompare(right, 'en', { numeric: true });+}++export function newestAdmissible(times: Record<string, string>, ceiling: string, cutoff: number) {+ const versions = Object.keys(times)+ .filter(+ (version) =>+ /^\d+\.\d+\.\d+$/.test(version) &&+ compareVersions(version, ceiling) <= 0 &&+ Date.parse(times[version]) < cutoff,+ )+ .sort(compareVersions);+ return versions.at(-1);+}++export function acquisitionDescriptors(agents: RegistryAgent[]): {+ id: string;+ npx: RegistryAgent['distribution']['npx'];+ uvx: RegistryAgent['distribution']['uvx'];+}[] {+ return agents+ .filter((agent) => agent.distribution.npx || agent.distribution.uvx)+ .map((agent) => ({ id: agent.id, npx: agent.distribution.npx, uvx: agent.distribution.uvx }))+ .sort((a, b) => a.id.localeCompare(b.id));+}++export function spawnNpxWithProjectCwd(+ launch: ResolvedLaunch & { kind: 'npx' },+ projectCwd: string,+): ChildProcess {+ // @ts-expect-error npx launches own their cwd and cannot accept a project cwd+ return spawnAcpAgent(launch, projectCwd);+}diff --git a/packages/server/src/acp/registry-release-age.test-fixture.json b/packages/server/src/acp/registry-release-age.test-fixture.jsonnew file mode 100644index 000000000..e1f5594b4--- /dev/null+++ b/packages/server/src/acp/registry-release-age.test-fixture.json@@ -0,0 +1,334 @@+[+ {+ "id": "agoragentic-acp",+ "version": "1.3.0",+ "distribution": {+ "npx": {+ "package": "[email protected]",+ "args": ["--acp"]+ }+ },+ "name": "agoragentic-acp"+ },+ {+ "id": "auggie",+ "version": "0.36.0",+ "distribution": {+ "npx": {+ "package": "@augmentcode/[email protected]",+ "args": ["--acp"],+ "env": {+ "AUGMENT_DISABLE_AUTO_UPDATE": "1"+ }+ }+ },+ "name": "auggie"+ },+ {+ "id": "autohand",+ "version": "0.2.1",+ "distribution": {+ "npx": {+ "package": "@autohandai/[email protected]"+ }+ },+ "name": "autohand"+ },+ {+ "id": "claude-acp",+ "version": "0.77.0",+ "distribution": {+ "npx": {+ "package": "@agentclientprotocol/[email protected]"+ }+ },+ "name": "claude-acp"+ },+ {+ "id": "cline",+ "version": "3.0.61",+ "distribution": {+ "npx": {+ "package": "[email protected]",+ "args": ["--acp"]+ }+ },+ "name": "cline"+ },+ {+ "id": "codebuddy-code",+ "version": "2.150.0",+ "distribution": {+ "npx": {+ "package": "@tencent-ai/[email protected]",+ "args": ["--acp"]+ }+ },+ "name": "codebuddy-code"+ },+ {+ "id": "codex-acp",+ "version": "1.11.0",+ "distribution": {+ "npx": {+ "package": "@agentclientprotocol/[email protected]"+ }+ },+ "name": "codex-acp"+ },+ {+ "id": "deepagents",+ "version": "0.1.7",+ "distribution": {+ "npx": {+ "package": "[email protected]",+ "args": []+ }+ },+ "name": "deepagents"+ },+ {+ "id": "dimcode",+ "version": "0.5.2",+ "distribution": {+ "npx": {+ "package": "[email protected]",+ "args": ["acp"]+ }+ },+ "name": "dimcode"+ },+ {+ "id": "dirac",+ "version": "0.5.12",+ "distribution": {+ "npx": {+ "package": "[email protected]",+ "args": ["--acp"]+ }+ },+ "name": "dirac"+ },+ {+ "id": "factory-droid",+ "version": "0.218.1",+ "distribution": {+ "npx": {+ "package": "[email protected]",+ "args": ["exec", "--output-format", "acp-daemon"],+ "env": {+ "DROID_DISABLE_AUTO_UPDATE": "true",+ "FACTORY_DROID_AUTO_UPDATE_ENABLED": "false"+ }+ }+ },+ "name": "factory-droid"+ },+ {+ "id": "fast-agent",+ "version": "0.10.1",+ "distribution": {+ "uvx": {+ "package": "fast-agent-acp==0.10.1",+ "args": ["-x"],+ "env": {+ "FAST_AGENT_MODEL": "codexplan"+ }+ }+ },+ "name": "fast-agent"+ },+ {+ "id": "gemini",+ "version": "0.59.0",+ "distribution": {+ "npx": {+ "package": "@google/[email protected]",+ "args": ["--acp"]+ }+ },+ "name": "gemini"+ },+ {+ "id": "github-copilot-cli",+ "version": "1.0.83",+ "distribution": {+ "npx": {+ "package": "@github/[email protected]",+ "args": ["--acp"]+ }+ },+ "name": "github-copilot-cli"+ },+ {+ "id": "glm-acp-agent",+ "version": "1.8.0",+ "distribution": {+ "npx": {+ "package": "[email protected]"+ }+ },+ "name": "glm-acp-agent"+ },+ {+ "id": "grok-build",+ "version": "1.0.30",+ "distribution": {+ "npx": {+ "package": "@xai-official/[email protected]",+ "args": ["agent", "stdio"]+ }+ },+ "name": "grok-build"+ },+ {+ "id": "kilo",+ "version": "7.6.2",+ "distribution": {+ "binary": {+ "darwin-aarch64": {+ "archive": "https://github.com/Kilo-Org/kilocode/releases/download/v7.6.2/kilo-darwin-arm64.zip",+ "cmd": "./kilo",+ "args": ["acp"],+ "sha256": "516b8b975beec61ac6c2a3dcf9ea1377bc0959d6f4fd695564de7dcb3a350a9a"+ },+ "darwin-x86_64": {+ "archive": "https://github.com/Kilo-Org/kilocode/releases/download/v7.6.2/kilo-darwin-x64.zip",+ "cmd": "./kilo",+ "args": ["acp"],+ "sha256": "001c6d21a38984ec3a8ea4d2b217efb4870f48c527349871bc553a78bcba989f"+ },+ "linux-aarch64": {+ "archive": "https://github.com/Kilo-Org/kilocode/releases/download/v7.6.2/kilo-linux-arm64.tar.gz",+ "cmd": "./kilo",+ "args": ["acp"],+ "sha256": "b7e532d3b17693cc69883dc030ae2aa5787ec86510b75ffd09892d5b25998f5e"+ },+ "linux-x86_64": {+ "archive": "https://github.com/Kilo-Org/kilocode/releases/download/v7.6.2/kilo-linux-x64.tar.gz",+ "cmd": "./kilo",+ "args": ["acp"],+ "sha256": "74cba87e7b4b0ae53cd40c76e464432e6ae75f810a753ff88436f666a08d3858"+ },+ "windows-x86_64": {+ "archive": "https://github.com/Kilo-Org/kilocode/releases/download/v7.6.2/kilo-windows-x64.zip",+ "cmd": "./kilo.exe",+ "args": ["acp"],+ "sha256": "bfc2daae05ef7e44584928aab87b53d5cedd9e19d32af4a01903e08d36900dcf"+ }+ },+ "npx": {+ "package": "@kilocode/[email protected]",+ "args": ["acp"]+ }+ },+ "name": "kilo"+ },+ {+ "id": "minimax-code",+ "version": "0.2.7",+ "distribution": {+ "npx": {+ "package": "@minimax-ai/[email protected]",+ "args": ["acp"]+ }+ },+ "name": "minimax-code"+ },+ {+ "id": "minion-code",+ "version": "0.1.44",+ "distribution": {+ "uvx": {+ "package": "[email protected]",+ "args": ["acp"]+ }+ },+ "name": "minion-code"+ },+ {+ "id": "nova",+ "version": "1.1.38",+ "distribution": {+ "npx": {+ "package": "@compass-ai/[email protected]",+ "args": ["acp"]+ }+ },+ "name": "nova"+ },+ {+ "id": "pi-acp",+ "version": "0.0.33",+ "distribution": {+ "npx": {+ "package": "[email protected]"+ }+ },+ "name": "pi-acp"+ },+ {+ "id": "qoder",+ "version": "0.2.14",+ "distribution": {+ "npx": {+ "package": "@qoder-ai/[email protected]",+ "args": ["--acp"]+ }+ },+ "name": "qoder"+ },+ {+ "id": "qwen-code",+ "version": "0.23.3",+ "distribution": {+ "npx": {+ "package": "@qwen-code/[email protected]",+ "args": ["--acp", "--experimental-skills"]+ }+ },+ "name": "qwen-code"+ },+ {+ "id": "sigit",+ "version": "1.5.8",+ "distribution": {+ "binary": {+ "darwin-aarch64": {+ "archive": "https://github.com/getsigit/sigit/releases/download/v1.5.8/sigit-macos-arm64.tar.gz",+ "cmd": "./sigit",+ "sha256": "a5c07e6588eb9c24cb92fe9dbbb5abe661056a5e0addc17f030b8b4f057a465a"+ },+ "darwin-x86_64": {+ "archive": "https://github.com/getsigit/sigit/releases/download/v1.5.8/sigit-macos-amd64.tar.gz",+ "cmd": "./sigit",+ "sha256": "863deaff2f02e823ec18581e326d50b643f9e8b26d4b87e75e934be877824590"+ },+ "linux-aarch64": {+ "archive": "https://github.com/getsigit/sigit/releases/download/v1.5.8/sigit-linux-arm64",+ "cmd": "./sigit-linux-arm64",+ "sha256": "4ed2f21664a2aafe693649fd2bfb45951b9e1ecd6de3121facc3c6ff9b7f62a8"+ },+ "linux-x86_64": {+ "archive": "https://github.com/getsigit/sigit/releases/download/v1.5.8/sigit-linux-amd64",+ "cmd": "./sigit-linux-amd64",+ "sha256": "fa8cc4bc960a7814f5d2fdec55674a2c8719b3f48d1464d8266edf00a8c6e19b"+ },+ "windows-aarch64": {+ "archive": "https://github.com/getsigit/sigit/releases/download/v1.5.8/sigit-win-arm64.exe",+ "cmd": "./sigit-win-arm64.exe",+ "sha256": "835aa6beebfb304f66d1ac0cc8406fa74dee34484824a161bd394de6f34855bf"+ },+ "windows-x86_64": {+ "archive": "https://github.com/getsigit/sigit/releases/download/v1.5.8/sigit-win-amd64.exe",+ "cmd": "./sigit-win-amd64.exe",+ "sha256": "9db1d50d2234f6c57778e69acb8dcd94cf39e8b28aa179ed2cdad55e4361d307"+ }+ },+ "npx": {+ "package": "@smbcloud/[email protected]"+ }+ },+ "name": "sigit"+ }+]diff --git a/packages/server/src/acp/thread-manager.integration.test.ts b/packages/server/src/acp/thread-manager.integration.test.tsindex 99260ce42..669f2d26c 100644--- a/packages/server/src/acp/thread-manager.integration.test.ts+++ b/packages/server/src/acp/thread-manager.integration.test.ts@@ -1,7 +1,8 @@import type { ChildProcess } from 'node:child_process';-import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';-import { dirname, join } from 'node:path';+import { delimiter, dirname, join } from 'node:path';+import { pathToFileURL } from 'node:url';import type {ThreadEvent,ThreadInfo,@@ -16,9 +17,21 @@ import type { AgentPresenceBroadcaster } from '../agent-presence.ts';import type { AgentSessionManager } from '../agent-sessions.ts';import { getLogger, type PinoLogger } from '../logger.ts';import { RUNTIME_VERSION } from '../version-constants.ts';+import { withLocalAcquisitionRegistry } from './acquisition-contract.test-helper.ts';+import {+ installNodeFixture,+ npmCli,+ registryPackage,+ writeExecutable,+} from './package-acquisition.test-helper.ts';import { AcpPermissionStore } from './permissions.ts';import { AcpRegistry } from './registry.ts';-import { ACP_ENVIRONMENT_NOTE, AcpThreadManager, MAX_QUEUED_PROMPTS } from './thread-manager.ts';+import {+ ACP_ENVIRONMENT_NOTE,+ AcpThreadManager,+ type AcpThreadManagerOptions,+ MAX_QUEUED_PROMPTS,+} from './thread-manager.ts';const log = getLogger('acp-thread-test');@@ -52,6 +65,8 @@ function makeManager(contentDir: string,localDir: string,extra?: {+ probePiAcpBridge?: AcpThreadManagerOptions['probePiAcpBridge'];+ ensurePiAcpBridge?: AcpThreadManagerOptions['ensurePiAcpBridge'];steerStallMs?: number;authenticateTimeoutMs?: number;unwatchedTurnCancelMs?: number;@@ -115,6 +130,264 @@ function internals(manager: AcpThreadManager): {};}+describe('package acquisition failure projection', () => {+ test.each(['npx', 'uvx'] as const)(+ '%s start and retry retain actionable native refusal and clean up',+ async (runtime) => {+ await withLocalAcquisitionRegistry(async (home) => {+ process.env.npm_config_before = '1970-01-01';+ process.env.UV_EXCLUDE_NEWER = '1970-01-01';+ const localDir = tmp();+ const agent = registryPackage(+ runtime === 'npx' ? '[email protected]' : '[email protected]',+ runtime,+ );+ const registry = new AcpRegistry({+ localDir,+ log,+ fetchImpl: async () => new Response(JSON.stringify({ agents: [agent] })),+ });+ const manager = makeManager(home, localDir, { registry });+ const events: ThreadEvent[] = [];+ const info = await manager.createThread({ agent: { source: 'registry', id: agent.id } });+ await manager.subscribe(info.threadId, 0, (frame) => {+ if (frame.op === 'event') events.push(frame.event);+ else if (frame.op === 'events') events.push(...frame.events);+ });+ try {+ for (const attempt of ['start', 'retry']) {+ if (attempt === 'retry') {+ const previous = events.filter(+ (event) => event.kind === 'status' && event.status === 'error',+ ).length;+ await manager.retryThread(info.threadId).catch(() => {});+ await expect+ .poll(+ () =>+ events.filter((event) => event.kind === 'status' && event.status === 'error')+ .length,+ { timeout: 5000 },+ )+ .toBeGreaterThan(previous);+ }+ await expect+ .poll(() => manager.getInfo(info.threadId)?.status, { timeout: 20_000 })+ .toBe('error');+ await expect+ .poll(() => internals(manager).child(info.threadId), { timeout: 5000 })+ .toBeNull();+ await expect+ .poll(+ () => events.some((event) => event.kind === 'status' && event.status === 'error'),+ { timeout: 5000 },+ )+ .toBe(true);+ const failure = events+ .filter((event) => event.kind === 'status' && event.status === 'error')+ .at(-1);+ expect.soft(failure, attempt).toMatchObject({+ failure: {+ reason: 'connect',+ agentMessage: expect.stringMatching(/release|policy|allowed|available/i),+ machineDetail: expect.stringMatching(+ runtime === 'npx' ? /ETARGET|ENOVERSIONS/ : /exclude-newer|No solution found/,+ ),+ },+ });+ expect.soft(internals(manager).pendingPermissionCount(info.threadId)).toBe(0);+ if (failure?.kind === 'status')+ expect.soft(failure.failure?.machineDetail?.length ?? 0).toBeLessThan(20_000);+ if (failure?.kind === 'status')+ expect+ .soft(failure.failure?.machineDetail)+ .toContain(+ runtime === 'npx' ? 'A complete log of this run' : 'to override the cutoff',+ );+ }+ } finally {+ await manager.destroy();+ }+ });+ },+ 90_000,+ );++ test.each(['npx', 'uvx'] as const)(+ '%s resume exposes typed install-failed after real native acquisition refusal',+ async (runtime) => {+ await withLocalAcquisitionRegistry(async (home) => {+ const realNpx = npmCli('npx');+ const realNpm = npmCli('npm');+ const localDir = tmp();+ writeResumableAgentEntry(localDir, 'resume-bootstrap', { FAKE_CAPS: 'resume,load' });+ const bin = join(home, 'bin');+ mkdirSync(bin);+ installNodeFixture(bin);+ const npx = join(bin, 'npx');+ writeExecutable(+ npx,+ `if(process.argv.includes('--version')) process.stdout.write('11.17.0\\n');+ else import(${JSON.stringify(pathToFileURL(join(localDir, 'resume-bootstrap.mjs')).href)});`,+ );+ writeExecutable(+ join(bin, 'npm'),+ `const r=require('node:child_process').spawnSync(${JSON.stringify(process.execPath)}, [${JSON.stringify(realNpm)}, ...process.argv.slice(2)], {stdio:'inherit',env:process.env}); process.exit(r.status ?? 1);`,+ );+ const env = {+ PATH: [bin, process.env.PATH ?? ''].join(delimiter),+ FAKE_CAPS: 'resume,load',+ };+ let agent = registryPackage('fixture-bootstrap', 'npx', env);+ agent.distribution.npx = { package: 'fixture-bootstrap', env };+ const registry = new AcpRegistry({+ localDir,+ log,+ ttlMs: 0,+ fetchImpl: async () => new Response(JSON.stringify({ agents: [agent] })),+ });+ const manager = makeManager(home, localDir, { registry });+ await manager.init();+ try {+ const info = await manager.createThread({ agent: { source: 'registry', id: agent.id } });+ await expect+ .poll(() => manager.getInfo(info.threadId)?.status, { timeout: 15_000 })+ .toBe('ready');+ manager.sendPrompt(info.threadId, 'retain this fixture session');+ await expect+ .poll(() => manager.getInfo(info.threadId)?.status, { timeout: 15_000 })+ .toBe('ready');+ await manager.closeThread(info.threadId);+ agent = registryPackage(+ runtime === 'npx' ? '[email protected]' : '[email protected]',+ runtime,+ env,+ );+ process.env.npm_config_before = '1970-01-01';+ process.env.UV_EXCLUDE_NEWER = '1970-01-01';+ writeExecutable(+ npx,+ `const r=require('node:child_process').spawnSync(${JSON.stringify(process.execPath)}, [${JSON.stringify(realNpx)}, ...process.argv.slice(2)], {stdio:'inherit',env:process.env}); process.exit(r.status ?? 1);`,+ );+ await expect(manager.resumeThread(info.threadId)).rejects.toMatchObject({+ code: 'install-failed',+ message: expect.stringMatching(/release-date policy/),+ });+ expect(manager.getInfo(info.threadId)?.archived).toBe(true);+ expect(internals(manager).child(info.threadId)).toBeNull();+ const replay: ThreadEvent[] = [];+ await manager.subscribe(info.threadId, 0, (frame) => {+ if (frame.op === 'event') replay.push(frame.event);+ else if (frame.op === 'events') replay.push(...frame.events);+ });+ expect(replay.filter((event) => event.kind === 'status').at(-1)).toMatchObject({+ status: 'exited',+ failure: {+ reason: 'connect',+ agentMessage: expect.stringMatching(/release-date policy/),+ machineDetail: expect.stringMatching(+ runtime === 'npx' ? /ETARGET|ENOVERSIONS/ : /exclude-newer|No solution found/,+ ),+ },+ });+ } finally {+ await manager.destroy();+ }+ });+ },+ 90_000,+ );++ test('a ceiling-sized acquisition primary preserves its headline and a distinct stderr tail', async () => {+ await withLocalAcquisitionRegistry(async (home) => {+ const localDir = tmp();+ const bin = join(home, 'bin');+ mkdirSync(bin);+ installNodeFixture(bin);+ const originalPath = process.env.PATH;+ writeExecutable(+ join(bin, 'uvx'),+ `+ const args = process.argv.slice(2);+ const result = require('node:child_process').spawnSync('uvx', args, {+ encoding: 'utf8', env: { ...process.env, PATH: ${JSON.stringify(originalPath)} },+ });+ if (args.length === 1 && args[0] === '--version') {+ process.stdout.write(result.stdout);+ } else {+ const headline = 'PRIMARY-HEAD ' + result.stderr.replace(/\\n/g, ' ');+ process.stderr.write('TAIL-ONLY: registry endpoint\\n' + headline.padEnd(15999, 'x') + '\\n');+ }+ process.exit(result.status ?? 1);+ `,+ );+ const env = {+ PATH: [bin, originalPath ?? ''].join(delimiter),+ UV_EXCLUDE_NEWER: '1970-01-01',+ };+ const agent = registryPackage('[email protected]', 'uvx', env);+ const registry = new AcpRegistry({+ localDir,+ log,+ fetchImpl: async () => new Response(JSON.stringify({ agents: [agent] })),+ });+ const manager = makeManager(home, localDir, { registry });+ const info = await manager.createThread({ agent: { source: 'registry', id: agent.id } });+ const statuses: StatusEvent[] = [];+ await manager.subscribe(info.threadId, 0, collectStatuses(statuses));+ await waitUntil(+ () => statuses.some((event) => event.failure?.reason === 'connect'),+ 15_000,+ 'acquisition failure',+ );+ const detail = statuses.find((event) => event.failure?.reason === 'connect')?.failure+ ?.machineDetail;+ expect(detail).toMatch(/^PRIMARY-HEAD /);+ expect(detail).toContain('No solution found');+ expect(detail).toContain('TAIL-ONLY: registry endpoint');+ expect(detail?.length).toBeLessThanOrEqual(16_000);+ });+ }, 30_000);++ test('compatibility control: ordinary ACP closure is not described as a package policy refusal', async () => {+ const localDir = tmp();+ const command = join(localDir, 'ordinary-close.cjs');+ writeFileSync(+ command,+ "process.stderr.write('ordinary ACP fixture closure https://alice:[email protected]/pkg Authorization: Bearer fixture-token');process.exit(1);",+ );+ writeFileSync(+ join(localDir, 'acp-agents.json'),+ JSON.stringify([+ { id: 'ordinary', name: 'Ordinary', command: process.execPath, args: [command] },+ ]),+ );+ const manager = makeManager(tmp(), localDir);+ const events: ThreadEvent[] = [];+ const info = await manager.createThread({ agent: { source: 'custom', id: 'ordinary' } });+ await manager.subscribe(info.threadId, 0, (frame) => {+ if (frame.op === 'event') events.push(frame.event);+ else if (frame.op === 'events') events.push(...frame.events);+ });+ await expect+ .poll(() => manager.getInfo(info.threadId)?.status, { timeout: 10_000 })+ .toBe('error');+ await expect+ .poll(() => events.some((event) => event.kind === 'status' && event.status === 'error'), {+ timeout: 5000,+ })+ .toBe(true);+ const failure = events+ .filter((event) => event.kind === 'status' && event.status === 'error')+ .at(-1);+ expect(failure).toMatchObject({+ failure: { reason: 'connect', agentMessage: expect.stringContaining('initialize failed') },+ });+ expect(JSON.stringify(failure)).not.toMatch(+ /release-date policy|cooldown|fixture-secret|fixture-token/,+ );+ });+});+function writeExampleAgentEntry(localDir: string): void {writeFileSync(join(localDir, 'acp-agents.json'),@@ -2704,6 +2977,52 @@ process.stdin.on('data', (chunk) => {}describe('AcpThreadManager retry', () => {+ test('retry settles an outstanding permission from a failed prompt in replayed history', async () => {+ const localDir = tmp();+ writeRequestingAgentEntry(+ localDir,+ 'permission-failure',+ `+ void request('session/request_permission', {+ toolCall: { toolCallId: 'pending-edit', title: 'Edit a file', kind: 'edit' },+ options: [{ optionId: 'allow', name: 'Allow', kind: 'allow_once' }],+ });+ write({ jsonrpc: '2.0', id: msg.id, error: { code: -32603, message: 'prompt failed' } });+ `,+ );+ const manager = makeManager(tmp(), localDir);+ const info = await manager.createThread({+ agent: { source: 'custom', id: 'permission-failure' },+ });+ const events: ThreadEvent[] = [];+ await manager.subscribe(info.threadId, 0, (frame) => {+ if (frame.op === 'event') events.push(frame.event);+ if (frame.op === 'events') events.push(...frame.events);+ });+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'ready');+ manager.sendPrompt(info.threadId, 'edit');+ await waitUntil(+ () => manager.getInfo(info.threadId)?.status === 'error',+ 5000,+ 'prompt failure',+ );+ await waitUntil(+ () => events.some((event) => event.kind === 'permission_request'),+ 5000,+ 'permission event delivery',+ );+ expect(events.some((event) => event.kind === 'permission_request')).toBe(true);+ writeRequestingAgentEntry(localDir, 'permission-failure', 'finish();');+ expect((await manager.retryThread(info.threadId)).status).toBe('ready');+ const replay: ThreadEvent[] = [];+ await manager.subscribe(info.threadId, 0, (frame) => {+ if (frame.op === 'event') replay.push(frame.event);+ if (frame.op === 'events') replay.push(...frame.events);+ });+ expect(replay.some((event) => event.kind === 'permission_resolved')).toBe(true);+ expect(internals(manager).pendingPermissionCount(info.threadId)).toBe(0);+ }, 30_000);+test('a failed start retries in place and succeeds once the cause is fixed', async () => {const contentDir = tmp();const localDir = tmp();@@ -3203,17 +3522,17 @@ process.stdin.on('data', (chunk) => {);}-describe('AcpThreadManager auth classification', () => {- type StatusEvent = Extract<ThreadEvent, { kind: 'status' }>;+type StatusEvent = Extract<ThreadEvent, { kind: 'status' }>;- const collectStatuses = (into: StatusEvent[]) => (frame: ThreadServerFrame) => {- const push = (event: ThreadEvent): void => {- if (event.kind === 'status') into.push(event);- };- if (frame.op === 'event') push(frame.event);- if (frame.op === 'events') for (const event of frame.events) push(event);+const collectStatuses = (into: StatusEvent[]) => (frame: ThreadServerFrame) => {+ const push = (event: ThreadEvent): void => {+ if (event.kind === 'status') into.push(event);};+ if (frame.op === 'event') push(frame.event);+ if (frame.op === 'events') for (const event of frame.events) push(event);+};+describe('AcpThreadManager auth classification', () => {const withStatus = (statuses: StatusEvent[], status: string): StatusEvent | undefined =>statuses.find((e) => e.status === status);@@ -3316,6 +3635,67 @@ describe('AcpThreadManager auth classification', () => {await manager.closeThread(info.threadId);}, 30_000);+ test.each([+ 'short',+ 'cut-through-credentials',+ 'colon-free',+ 'long-stderr',+ 'large-tail',+ ] as const)(+ 'a %s session/new error payload is redacted before it reaches the failure detail',+ async (shape) => {+ const contentDir = tmp();+ const localDir = tmp();+ writeSessionFailingAgentEntry(+ localDir,+ 'leaky-data-agent',+ {+ code: -32603,+ message: 'Failed to initialize session services',+ data: {+ cause: 'services',+ padding: shape === 'short' ? '' : 'x'.repeat(220),+ registry:+ shape === 'colon-free'+ ? 'https://[email protected]/simple'+ : `https://alice:fixture-secret${'z'.repeat(80)}@registry.example.test/pkg`,+ header: 'Authorization: Bearer fixture-token',+ },+ },+ shape === 'large-tail'+ ? [...Array.from({ length: 39 }, () => 'x'.repeat(480)), 'boot: loading services'].join(+ '\n',+ )+ : shape === 'colon-free'+ ? 'boot: loading services https://[email protected]/simple'+ : `boot: loading services https://bob:fixture-tail-secret${shape === 'long-stderr' ? 'z'.repeat(600) : ''}@registry.example.test/pkg`,+ );+ const manager = makeManager(contentDir, localDir);+ const statuses: StatusEvent[] = [];+ const info = await manager.createThread({+ agent: { source: 'custom', id: 'leaky-data-agent' },+ });+ await manager.subscribe(info.threadId, 0, collectStatuses(statuses));+ await waitUntil(+ () => withStatus(statuses, 'error') !== undefined,+ 15_000,+ `error; got ${JSON.stringify(statuses.map((e) => e.status))}`,+ );+ const event = withStatus(statuses, 'error');+ expect(event?.failure?.reason).toBe('session-setup');+ const detail = event?.failure?.machineDetail ?? '';+ expect(detail).toContain('"cause":"services"');+ expect(detail).toContain('boot: loading services');+ expect(detail).not.toMatch(+ /fixture-secret|fixture-token|fixture-tail-secret|0123456789abcdef|fedcba9876543210/,+ );+ expect(detail.length).toBeLessThanOrEqual(16_000);++ await manager.closeThread(info.threadId);+ },+ 30_000,+ );+test('closing a failed thread archives it instead of erasing its evidence', async () => {const contentDir = tmp();const localDir = tmp();@@ -3952,23 +4332,27 @@ function writeCrashingAgentEntry(localDir: string, id: string, stderrLine: strinfunction writeExitAfterReadyAgentEntry(localDir: string,id: string,- stderrLine: string,+ stderr: { text: string; terminated: boolean },dieFile: string,-): void {+): { preExitStderr: string } {+ const payload = stderr.terminated ? `${stderr.text}\n` : stderr.text;+ const preExitStderr = payload.slice(0, -1);+ const finalStderr = payload.slice(-1);const agentPath = join(localDir, `${id}.mjs`);writeFileSync(agentPath,`import { existsSync } from 'node:fs';const write = (msg) => process.stdout.write(JSON.stringify(msg) + '\\n');-// Dies only when the test says so, and with no request in flight. A timed-// exit raced session setup: landing first, it failed the pending session/new,-// which puts the thread in 'error' — a status whose exit is a known echo and-// is deliberately not logged again.+let stderrWritten = false;setInterval(() => {- if (!existsSync(${JSON.stringify(dieFile)})) return;- process.stderr.write(${JSON.stringify(stderrLine)} + '\\n');- process.exit(7);+ if (!stderrWritten && existsSync(${JSON.stringify(`${dieFile}.stderr`)})) {+ stderrWritten = true;+ process.stderr.write(${JSON.stringify(preExitStderr)});+ }+ if (existsSync(${JSON.stringify(dieFile)})) {+ process.stderr.write(${JSON.stringify(finalStderr)}, () => process.exit(7));+ }}, 20);let buffer = '';process.stdin.setEncoding('utf8');@@ -3996,6 +4380,7 @@ process.stdin.on('data', (chunk) => {join(localDir, 'acp-agents.json'),JSON.stringify([{ id, name: `Fake ${id}`, command: 'node', args: [agentPath] }]),);+ return { preExitStderr };}function capturingLog(sink: { obj: Record<string, unknown>; msg: string }[]): PinoLogger {@@ -4015,6 +4400,644 @@ function capturingLog(sink: { obj: Record<string, unknown>; msg: string }[]): Pireturn self as unknown as PinoLogger;}+function writeHeldStdioAgentEntry(+ localDir: string,+ id: string,+ mode: 'ready' | 'auth' | 'session-setup' | 'prompt' | 'resume',+ dieFile: string,+ releaseFile: string,+): { diagnostic: string } {+ const diagnostic = 'Fatal: held final diagnostic';+ const stderr = `${diagnostic} https://alice:[email protected]/pkg`;+ const keeper = `+ const { existsSync } = require('node:fs');+ const deadline = Date.now() + 15_000;+ setInterval(() => {+ if (existsSync(${JSON.stringify(releaseFile)}) || Date.now() > deadline) process.exit(0);+ }, 10);+ `;+ const entry = join(localDir, `${id}.mjs`);+ writeFileSync(+ entry,+ `+ import { existsSync, writeFileSync } from 'node:fs';+ import { spawn } from 'node:child_process';+ const write = (msg) => process.stdout.write(JSON.stringify(msg) + '\\n');+ setInterval(() => {+ if (!existsSync(${JSON.stringify(dieFile)})) return;+ spawn(process.execPath, ['-e', ${JSON.stringify(keeper)}], {+ detached: true, stdio: ['ignore', 'inherit', 'inherit'],+ }).unref();+ process.stderr.write(${JSON.stringify(stderr)}, () => process.exit(7));+ }, 10);+ let buffer = '';+ process.stdin.setEncoding('utf8');+ process.stdin.on('data', (chunk) => {+ buffer += chunk;+ let end;+ while ((end = buffer.indexOf('\\n')) !== -1) {+ const msg = JSON.parse(buffer.slice(0, end));+ buffer = buffer.slice(end + 1);+ if (msg.method === 'initialize') {+ write({ jsonrpc: '2.0', id: msg.id, result: {+ protocolVersion: 1, agentCapabilities: { sessionCapabilities: { resume: {} } },+ authMethods: [{ id: 'login', name: 'Login' }],+ } });+ } else if (msg.method === 'session/new') {+ if (${JSON.stringify(mode)} === 'session-setup') {+ writeFileSync(${JSON.stringify(`${dieFile}.request`)}, 'session');+ } else if (${JSON.stringify(mode)} === 'auth') {+ write({ jsonrpc: '2.0', id: msg.id, error: { code: -32000, message: 'sign in' } });+ } else {+ write({ jsonrpc: '2.0', id: msg.id, result: { sessionId: 'held-session' } });+ }+ } else if (msg.method === 'session/resume' && ${JSON.stringify(mode)} !== 'resume') {+ write({ jsonrpc: '2.0', id: msg.id, result: {} });+ } else if (msg.method === 'session/prompt' || msg.method === 'session/resume') {+ writeFileSync(${JSON.stringify(`${dieFile}.request`)}, 'prompt');+ }+ }+ });+ `,+ );+ writeFileSync(+ join(localDir, 'acp-agents.json'),+ JSON.stringify([{ id, name: `Fake ${id}`, command: 'node', args: [entry] }]),+ );+ return { diagnostic };+}++describe('diagnostic stream lifetime', () => {+ test.each([+ ['npx', 'live'],+ ['npx', 'eof'],+ ['uvx', 'live'],+ ['uvx', 'eof'],+ ] as const)(+ '%s initialize handles %s before process exit',+ async (runtime, mode) => {+ const localDir = tmp();+ const binDir = tmp();+ const rejectFile = join(localDir, 'reject');+ const releaseFile = join(localDir, 'release');+ const requestFile = join(localDir, 'request');+ const diagnostic =+ runtime === 'npx'+ ? 'npm ERR! code ETARGET No matching version with a date before 1970-01-01'+ : 'No solution found when resolving tool dependencies: filtered by `exclude-newer`';+ installNodeFixture(binDir);+ writeExecutable(+ join(binDir, runtime),+ `+ const { existsSync, writeFileSync } = require('node:fs');+ if (process.argv.includes('--version')) { process.stdout.write('1.0.0\\n'); process.exit(0); }+ let request;+ let buffer = '';+ process.stdin.setEncoding('utf8');+ process.stdin.on('data', (chunk) => {+ buffer += chunk;+ const end = buffer.indexOf('\\n');+ if (end === -1) return;+ request = JSON.parse(buffer.slice(0, end));+ writeFileSync(${JSON.stringify(requestFile)}, 'initialize');+ });+ let rejected = false;+ setInterval(() => {+ if (!request || rejected || !existsSync(${JSON.stringify(rejectFile)})) return;+ rejected = true;+ if (${JSON.stringify(mode)} === 'live') {+ process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id,+ error: { code: -32603, message: 'initialize rejected while alive' } }) + '\\n');+ } else {+ process.stdout.end();+ }+ }, 10);+ setInterval(() => {+ if (existsSync(${JSON.stringify(releaseFile)})) {+ process.stderr.write(${JSON.stringify(diagnostic)}, () => process.exit(7));+ }+ }, 10);+ `,+ );+ const lines: { obj: Record<string, unknown>; msg: string }[] = [];+ const manager = makeManager(tmp(), localDir, {+ log: capturingLog(lines),+ registry: new AcpRegistry({+ localDir,+ log,+ fetchImpl: async () =>+ new Response(+ JSON.stringify({+ agents: [+ {+ id: 'initialize-order',+ name: 'Initialize order',+ version: '1.0.0',+ distribution: {+ [runtime]: { package: 'initialize-order', env: { PATH: binDir } },+ },+ },+ ],+ }),+ ),+ }),+ });+ const info = await manager.createThread({+ agent: { source: 'registry', id: 'initialize-order' },+ });+ await waitUntil(() => existsSync(requestFile), 5000, 'initialize received');+ const child = internals(manager).child(info.threadId);+ if (child?.stdout == null) throw new Error('child stdout missing');+ const closed = new Promise<void>((resolve) => child.once('close', () => resolve()));+ let rejectedAt = 0;+ let exitObserved = false;+ let eofBeforeExit = false;+ child.once('exit', () => {+ exitObserved = true;+ });+ child.stdout.once('end', () => {+ eofBeforeExit = !exitObserved;+ });+ child.stdout.on('data', (chunk: Buffer) => {+ if (chunk.toString().includes('initialize rejected while alive')) {+ rejectedAt = performance.now();+ aliveAtRejection = child.exitCode === null && child.signalCode === null;+ }+ });+ let reportedAt = 0;+ let aliveAtRejection = false;+ const statuses: StatusEvent[] = [];+ await manager.subscribe(info.threadId, 0, (frame) => {+ collectStatuses(statuses)(frame);+ if (statuses.some((event) => event.failure?.reason === 'connect') && reportedAt === 0) {+ reportedAt = performance.now();+ }+ });+ try {+ writeFileSync(rejectFile, 'reject');+ await waitUntil(+ () => lines.some((line) => line.msg === '[acp-threads] initialize failed'),+ 5000,+ 'initialize failure',+ );+ if (mode === 'eof') writeFileSync(releaseFile, 'release');+ await waitUntil(+ () => statuses.some((event) => event.failure?.reason === 'connect'),+ 5000,+ 'connect failure',+ );+ const failure = statuses.find((event) => event.failure?.reason === 'connect')?.failure;+ if (mode === 'live') {+ expect(rejectedAt).toBeGreaterThan(0);+ expect(reportedAt - rejectedAt).toBeLessThan(700);+ expect(aliveAtRejection).toBe(true);+ expect(failure?.agentMessage).toContain('initialize rejected while alive');+ } else {+ expect(eofBeforeExit).toBe(true);+ expect(failure?.agentMessage).toContain('release-date policy');+ expect(failure?.machineDetail).toContain(diagnostic);+ }+ } finally {+ writeFileSync(releaseFile, 'release');+ await closed;+ }+ },+ 30_000,+ );++ test.each(['exit', 'retry'] as const)(+ '%s retires an outstanding sign-in consent',+ async (action) => {+ const localDir = tmp();+ const binDir = tmp();+ writeAuthenticatingAgentEntry(localDir, 'consent-agent');+ const agentPath = join(localDir, 'consent-agent.mjs');+ installNodeFixture(binDir);+ writeExecutable(+ join(binDir, 'npx'),+ `+ if (process.argv.includes('--version')) process.stdout.write('1.0.0\\n');+ else void import(${JSON.stringify(pathToFileURL(agentPath).href)});+ `,+ );+ let bridgeLoadable = true;+ const manager = makeManager(tmp(), localDir, {+ registry: new AcpRegistry({+ localDir,+ log,+ fetchImpl: async () =>+ new Response(+ JSON.stringify({+ agents: [+ {+ id: 'pi-acp',+ name: 'Pi',+ version: '1.0.0',+ distribution: { npx: { package: '@fake/pi', env: { PATH: binDir } } },+ },+ ],+ }),+ ),+ }),+ probePiAcpBridge: (cwd) => ({+ project: 'ready',+ cwd,+ canonicalCwd: cwd,+ bridgePath: join(cwd, 'bridge.ts'),+ trustPath: join(cwd, 'trust.json'),+ bridge: 'absent',+ trust: 'untrusted',+ bridgeLoadable,+ otherExtensions: [],+ }),+ ensurePiAcpBridge: () => {+ throw new Error('retired consent must not provision');+ },+ });+ const info = await manager.createThread({ agent: { source: 'registry', id: 'pi-acp' } });+ const events: ThreadEvent[] = [];+ const collect = (frame: ThreadServerFrame) => {+ if (frame.op === 'event') events.push(frame.event);+ if (frame.op === 'events') events.push(...frame.events);+ };+ await manager.subscribe(info.threadId, 0, collect);+ await waitUntil(+ () => manager.getInfo(info.threadId)?.status === 'auth_required',+ 15_000,+ 'sign-in',+ );+ bridgeLoadable = false;+ let settled = false;+ const authentication = manager+ .authenticateThread(info.threadId, 'test_login')+ .finally(() => {+ settled = true;+ })+ .catch(() => undefined);+ await waitUntil(+ () => events.some((event) => event.kind === 'pi_bridge_consent_request'),+ 5000,+ 'consent',+ );+ const request = events.find((event) => event.kind === 'pi_bridge_consent_request');+ if (request?.kind !== 'pi_bridge_consent_request') throw new Error('consent missing');+ bridgeLoadable = true;+ if (action === 'exit') {+ const child = internals(manager).child(info.threadId);+ if (child == null) throw new Error('child missing');+ const exited = new Promise<void>((resolve) => child.once('exit', () => resolve()));+ child.kill('SIGKILL');+ await exited;+ } else {+ writeRequestingAgentEntry(localDir, 'consent-agent', 'finish();');+ await manager.retryThread(info.threadId);+ }+ await waitUntil(() => settled, 1000, 'authentication settlement');+ await authentication;+ manager.respondPiBridgeConsent(info.threadId, request.requestId, { kind: 'granted' });+ const replay: ThreadEvent[] = [];+ await manager.subscribe(info.threadId, 0, (frame) => {+ if (frame.op === 'event') replay.push(frame.event);+ if (frame.op === 'events') replay.push(...frame.events);+ });+ expect(+ replay.some(+ (event) =>+ event.kind === 'pi_bridge_consent_resolved' &&+ event.requestId === request.requestId &&+ event.decision === 'granted',+ ),+ ).toBe(false);+ },+ 30_000,+ );++ test('a live agent prompt rejection reports without waiting for process closure', async () => {+ const localDir = tmp();+ writeRequestingAgentEntry(+ localDir,+ 'live-rejection',+ `+ write({ jsonrpc: '2.0', id: msg.id, error: { code: -32603, message: 'invalid prompt' } });+ `,+ );+ const manager = makeManager(tmp(), localDir);+ const info = await manager.createThread({ agent: { source: 'custom', id: 'live-rejection' } });+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'ready');+ const child = internals(manager).child(info.threadId);+ if (child == null) throw new Error('child missing');+ const statuses: StatusEvent[] = [];+ await manager.subscribe(info.threadId, 0, collectStatuses(statuses));+ let rejectedAt = 0;+ child.stdout?.on('data', (chunk: Buffer) => {+ if (chunk.toString().includes('invalid prompt')) rejectedAt = performance.now();+ });+ let reportedAt = 0;+ await manager.subscribe(info.threadId, 0, (frame) => {+ const batch =+ frame.op === 'events' ? frame.events : frame.op === 'event' ? [frame.event] : [];+ if (batch.some((event) => event.kind === 'status' && event.failure?.reason === 'prompt'))+ reportedAt = performance.now();+ });+ manager.sendPrompt(info.threadId, 'reject');+ await waitUntil(+ () => statuses.some((event) => event.failure?.reason === 'prompt'),+ 5000,+ 'prompt rejection',+ );+ expect(rejectedAt).toBeGreaterThan(0);+ expect(reportedAt - rejectedAt).toBeLessThan(700);+ expect(child.exitCode).toBeNull();+ expect(child.signalCode).toBeNull();+ expect(+ statuses.find((event) => event.failure?.reason === 'prompt')?.failure?.agentMessage,+ ).toBe('invalid prompt');+ }, 30_000);++ test.each(['session-setup', 'prompt'] as const)(+ '%s failure waits for held unterminated stderr',+ async (mode) => {+ const localDir = tmp();+ const id = 'held-agent';+ const dieFile = join(localDir, 'die');+ const releaseFile = join(localDir, 'release-stdio');+ const fixture = writeHeldStdioAgentEntry(localDir, id, mode, dieFile, releaseFile);+ const manager = makeManager(tmp(), localDir);+ const info = await manager.createThread({ agent: { source: 'custom', id } });+ const statuses: StatusEvent[] = [];+ await manager.subscribe(info.threadId, 0, collectStatuses(statuses));+ if (mode === 'prompt') {+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 5000, 'ready');+ manager.sendPrompt(info.threadId, 'crash');+ }+ await waitUntil(() => existsSync(`${dieFile}.request`), 5000, 'request received');+ const child = internals(manager).child(info.threadId);+ if (child?.stderr == null || child.stdout == null) throw new Error('stdio missing');+ const closed = new Promise<void>((resolve) => child.once('close', () => resolve()));+ try {+ child.stderr.pause();+ const exited = new Promise<void>((resolve) => child.once('exit', () => resolve()));+ writeFileSync(dieFile, 'exit');+ await exited;+ child.stdout.destroy();+ await new Promise<void>((resolve) => setImmediate(resolve));+ child.stderr.resume();+ writeFileSync(releaseFile, 'release');+ await closed;+ await waitUntil(+ () => statuses.some((event) => event.failure?.reason === mode),+ 5000,+ 'typed failure',+ );+ const detail = statuses.find((event) => event.failure?.reason === mode)?.failure+ ?.machineDetail;+ expect(detail).toContain(fixture.diagnostic);+ expect(detail).not.toContain('held-secret');+ } finally {+ child.stderr.resume();+ writeFileSync(releaseFile, 'release');+ await closed;+ }+ },+ 20_000,+ );++ test('a resume that spawns after close terminates its rejected agent', async () => {+ const localDir = tmp();+ const id = 'resume-after-close';+ const pidFile = join(localDir, 'resumed-pid');+ writeResumableAgentEntry(localDir, id, { FAKE_CAPS: 'resume' });+ const release = Promise.withResolvers<string | null>();+ const entered = Promise.withResolvers<void>();+ let hold = false;+ const manager = makeManager(tmp(), localDir, {+ resolveLoginShellPath: async () => {+ if (!hold) return null;+ entered.resolve();+ return release.promise;+ },+ });+ await manager.init();+ const info = await manager.createThread({ agent: { source: 'custom', id } });+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 5000, 'ready');+ manager.sendPrompt(info.threadId, 'retain history');+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 5000, 'prompt');+ await manager.closeThread(info.threadId);+ writeFileSync(+ join(localDir, `${id}.mjs`),+ `+ import { writeFileSync } from 'node:fs';+ writeFileSync(${JSON.stringify(pidFile)}, String(process.pid));+ setInterval(() => {}, 1000);+ process.stdin.once('data', (chunk) => {+ const msg = JSON.parse(chunk.toString());+ process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: msg.id,+ error: { code: -32603, message: 'resume initialization refused' } }) + '\\n');+ });+ `,+ );+ hold = true;+ const resumed = manager.resumeThread(info.threadId).catch((error: unknown) => error);+ await entered.promise;+ await manager.closeThread(info.threadId);+ expect(manager.getInfo(info.threadId)?.archived).toBe(true);+ release.resolve(null);+ try {+ expect(await resumed).toMatchObject({ code: 'spawn-failed' });+ const pid = Number(readFileSync(pidFile, 'utf8'));+ await expect+ .poll(+ () => {+ try {+ process.kill(pid, 0);+ return true;+ } catch {+ return false;+ }+ },+ { timeout: 3000 },+ )+ .toBe(false);+ const replay: ThreadEvent[] = [];+ await manager.subscribe(info.threadId, 0, (frame) => {+ if (frame.op === 'event') replay.push(frame.event);+ if (frame.op === 'events') replay.push(...frame.events);+ });+ expect(replay.at(-1)).toMatchObject({ kind: 'status', detail: 'thread closed' });+ } finally {+ if (existsSync(pidFile)) {+ try {+ process.kill(Number(readFileSync(pidFile, 'utf8')), 'SIGKILL');+ } catch {}+ }+ }+ }, 15_000);++ test.each(['prompt', 'resume'] as const)(+ 'closing during %s diagnostics keeps thread closed last in replayed history',+ async (mode) => {+ const localDir = tmp();+ const id = 'close-during-drain';+ const dieFile = join(localDir, 'die');+ const releaseFile = join(localDir, 'release-stdio');+ writeResumableAgentEntry(localDir, id, { FAKE_CAPS: 'resume' });+ const lines: { obj: Record<string, unknown>; msg: string }[] = [];+ const manager = makeManager(tmp(), localDir, { log: capturingLog(lines) });+ await manager.init();+ const info = await manager.createThread({ agent: { source: 'custom', id } });+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 5000, 'ready');+ manager.sendPrompt(info.threadId, 'retain history');+ await waitUntil(+ () => manager.getInfo(info.threadId)?.status === 'ready',+ 5000,+ 'prompt complete',+ );+ await manager.closeThread(info.threadId);+ const fixture = writeHeldStdioAgentEntry(localDir, id, mode, dieFile, releaseFile);+ const resumed = manager.resumeThread(info.threadId).catch((error: unknown) => error);+ if (mode === 'prompt') {+ await resumed;+ manager.sendPrompt(info.threadId, 'crash');+ }+ await waitUntil(() => existsSync(`${dieFile}.request`), 5000, 'prompt received');+ const child = internals(manager).child(info.threadId);+ if (child?.stdout == null) throw new Error('child stdout missing');+ const closed = new Promise<void>((resolve) => child.once('close', () => resolve()));+ const events: ThreadEvent[] = [];+ await manager.subscribe(+ info.threadId,+ manager.getInfo(info.threadId)?.lastSeq ?? 0,+ (frame) => {+ if (frame.op === 'event') events.push(frame.event);+ if (frame.op === 'events') events.push(...frame.events);+ },+ );+ try {+ const exited = new Promise<void>((resolve) => child.once('exit', () => resolve()));+ writeFileSync(dieFile, 'exit');+ await exited;+ child.stdout.destroy();+ if (mode === 'prompt') {+ await waitUntil(+ () => events.some((event) => event.kind === 'turn_ended'),+ 5000,+ 'prompt rejected',+ );+ } else {+ await new Promise<void>((resolve) => setImmediate(resolve));+ }+ await manager.closeThread(info.threadId);+ expect(manager.getInfo(info.threadId)?.archived).toBe(true);+ writeFileSync(releaseFile, 'release');+ await closed;+ await resumed;+ await new Promise<void>((resolve) => setImmediate(resolve));+ const replay: StatusEvent[] = [];+ await manager.subscribe(info.threadId, 0, collectStatuses(replay));+ expect(replay.some((event) => event.detail === 'thread closed')).toBe(true);+ expect(replay.at(-1)?.detail).toBe('thread closed');+ expect(manager.getInfo(info.threadId)?.status).toBe('exited');+ const suppressed = lines.find(+ (line) =>+ line.obj.suppressed === true &&+ line.obj.reason === (mode === 'prompt' ? 'prompt' : 'connect'),+ );+ expect(suppressed?.obj.threadId).toBe(info.threadId);+ expect(suppressed?.obj.machineDetail).toContain(fixture.diagnostic);+ expect(JSON.stringify(suppressed)).not.toContain('held-secret');+ } finally {+ writeFileSync(releaseFile, 'release');+ await closed;+ }+ },+ 20_000,+ );++ test('an exited agent reports within the drain bound while a descendant holds stdio', async () => {+ const localDir = tmp();+ const id = 'held-agent';+ const dieFile = join(localDir, 'die');+ const releaseFile = join(localDir, 'release-stdio');+ writeHeldStdioAgentEntry(localDir, id, 'ready', dieFile, releaseFile);+ const manager = makeManager(tmp(), localDir);+ const info = await manager.createThread({ agent: { source: 'custom', id } });+ const statuses: StatusEvent[] = [];+ await manager.subscribe(info.threadId, 0, collectStatuses(statuses));+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 5000, 'ready');+ const child = internals(manager).child(info.threadId);+ if (child == null) throw new Error('child missing');+ let didClose = false;+ const closed = new Promise<void>((resolve) =>+ child.once('close', () => {+ didClose = true;+ resolve();+ }),+ );+ try {+ writeFileSync(dieFile, 'exit');+ await waitUntil(+ () => statuses.some((event) => event.detail === 'agent exited (7)'),+ 3000,+ 'bounded exit',+ );+ expect(didClose).toBe(false);+ expect(internals(manager).child(info.threadId)).toBeNull();+ } finally {+ writeFileSync(releaseFile, 'release');+ await closed;+ }+ }, 20_000);++ test('a drained old exit cannot replace the ready status or handle of a retried agent', async () => {+ const localDir = tmp();+ const id = 'held-agent';+ const dieFile = join(localDir, 'die');+ const releaseFile = join(localDir, 'release-stdio');+ writeHeldStdioAgentEntry(localDir, id, 'auth', dieFile, releaseFile);+ const manager = makeManager(tmp(), localDir);+ const info = await manager.createThread({ agent: { source: 'custom', id } });+ const statuses: StatusEvent[] = [];+ await manager.subscribe(info.threadId, 0, collectStatuses(statuses));+ await waitUntil(+ () => manager.getInfo(info.threadId)?.status === 'auth_required',+ 5000,+ 'sign in',+ );+ const original = internals(manager).child(info.threadId);+ if (original == null) throw new Error('child missing');+ const closed = new Promise<void>((resolve) => original.once('close', () => resolve()));+ try {+ const exited = new Promise<void>((resolve) => original.once('exit', () => resolve()));+ writeFileSync(dieFile, 'exit');+ await exited;+ await expect(manager.authenticateThread(info.threadId, 'login')).rejects.toThrow(+ 'is no longer running',+ );+ writeRequestingAgentEntry(localDir, id, 'finish();');+ expect((await manager.retryThread(info.threadId)).status).toBe('ready');+ const replacement = internals(manager).child(info.threadId);+ expect(replacement).toBeTruthy();+ expect(replacement).not.toBe(original);+ const retryHistory: StatusEvent[] = [];+ await manager.subscribe(info.threadId, 0, collectStatuses(retryHistory));+ const afterRetry = retryHistory.length;+ writeFileSync(releaseFile, 'release');+ await closed;+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(manager.getInfo(info.threadId)?.status).toBe('ready');+ expect(internals(manager).child(info.threadId)).toBe(replacement);+ const drainedHistory: StatusEvent[] = [];+ await manager.subscribe(info.threadId, 0, collectStatuses(drainedHistory));+ expect(drainedHistory.slice(afterRetry).some((event) => event.status === 'exited')).toBe(+ false,+ );+ } finally {+ writeFileSync(releaseFile, 'release');+ await closed;+ }+ }, 20_000);+});+describe('agent failures reach the server log', () => {test('an agent that dies before the handshake logs its last words', async () => {const contentDir = tmp();@@ -4040,32 +5063,79 @@ describe('agent failures reach the server log', () => {expect(String(failureLine?.obj.machineDetail)).toContain('libicui18n.74.dylib');}, 30_000);- test('an agent that dies after going ready logs the unexpected exit', async () => {- const contentDir = tmp();- const localDir = tmp();- const lines: { obj: Record<string, unknown>; msg: string }[] = [];- const dieFile = join(localDir, 'die-now');- writeExitAfterReadyAgentEntry(localDir, 'quitter', 'agent ran out of memory', dieFile);+ test.each(['terminated', 'unterminated'] as const)(+ 'an agent that dies after going ready emits bounded redacted exit detail from %s stderr and logs it',+ async (shape) => {+ const contentDir = tmp();+ const localDir = tmp();+ const lines: { obj: Record<string, unknown>; msg: string }[] = [];+ const dieFile = join(localDir, 'die-now');+ const stderr = [+ ...Array.from({ length: 39 }, () => 'x'.repeat(480)),+ 'agent ran out of memory https://alice:[email protected]/pkg',+ ].join('\n');+ const { preExitStderr } = writeExitAfterReadyAgentEntry(+ localDir,+ 'quitter',+ { text: stderr, terminated: shape === 'terminated' },+ dieFile,+ );- const manager = makeManager(contentDir, localDir, { log: capturingLog(lines) });- const info = await manager.createThread({ agent: { source: 'custom', id: 'quitter' } });- await waitUntil(- () => manager.getInfo(info.threadId)?.status === 'ready',- 15_000,- 'the agent to go ready',- );- writeFileSync(dieFile, 'now');- await waitUntil(- () => lines.some((line) => line.msg.includes('agent exited unexpectedly')),- 15_000,- 'the agent process exit to be logged',- );+ const manager = makeManager(contentDir, localDir, { log: capturingLog(lines) });+ const info = await manager.createThread({ agent: { source: 'custom', id: 'quitter' } });+ const statuses: StatusEvent[] = [];+ await manager.subscribe(info.threadId, 0, collectStatuses(statuses));+ await waitUntil(+ () => manager.getInfo(info.threadId)?.status === 'ready',+ 15_000,+ 'the agent to go ready',+ );+ const child = internals(manager).child(info.threadId);+ if (child?.stderr == null) throw new Error('agent stderr is unavailable');+ let observedStderr = '';+ child.stderr.on('data', (chunk: string) => {+ observedStderr += chunk;+ });+ writeFileSync(`${dieFile}.stderr`, 'write');+ await waitUntil(+ () => observedStderr.includes(preExitStderr),+ 5000,+ 'parent receives crash stderr',+ );+ child.stderr.pause();+ const exited = new Promise<void>((resolve) => child.once('exit', () => resolve()));+ writeFileSync(dieFile, 'now');+ await exited;+ expect(internals(manager).child(info.threadId)).toBeNull();+ child.stderr.resume();+ await waitUntil(+ () => lines.some((line) => line.msg.includes('agent exited unexpectedly')),+ 15_000,+ 'the agent process exit to be logged',+ );- const exitLine = lines.find((l) => l.msg.includes('agent exited unexpectedly'));- expect(exitLine).toBeDefined();- expect(exitLine?.obj.code).toBe(7);- expect(String(exitLine?.obj.machineDetail)).toContain('ran out of memory');- }, 30_000);+ await waitUntil(+ () =>+ statuses.some(+ (event) => event.status === 'exited' && event.detail?.startsWith('agent exited (7)'),+ ),+ 5000,+ 'the process exit status detail',+ );+ const detail = statuses.find(+ (event) => event.status === 'exited' && event.detail?.startsWith('agent exited (7)'),+ )?.detail;+ expect(detail).toContain('ran out of memory');+ expect(detail).not.toContain('fixture-exit-secret');+ expect(detail?.length).toBeLessThanOrEqual(16_000);+ const exitLine = lines.find((l) => l.msg.includes('agent exited unexpectedly'));+ expect(exitLine).toBeDefined();+ expect(exitLine?.obj.code).toBe(7);+ expect(String(exitLine?.obj.machineDetail)).toContain('ran out of memory');+ expect(String(exitLine?.obj.machineDetail)).not.toContain('fixture-exit-secret');+ },+ 30_000,+ );});const CODEX_WARNING_TEXT = codexFixture.candidates.find((c) => c.name === 'warning-skills-budget')diff --git a/packages/server/src/acp/thread-manager.ts b/packages/server/src/acp/thread-manager.tsindex 764481fe6..18bcbf385 100644--- a/packages/server/src/acp/thread-manager.ts+++ b/packages/server/src/acp/thread-manager.ts@@ -66,6 +66,11 @@ import type { PinoLogger } from '../logger.ts';import { MCP_HOSTED_AGENT_HEADER } from '../mcp/agent-identity.ts';import { RUNTIME_VERSION } from '../version-constants.ts';import { buildPromptBlocks } from './attachment-blocks.ts';+import {+ ACQUISITION_DETAIL_MAX_CHARS,+ createDiagnosticStderrCapture,+ redactDiagnostic,+} from './diagnostics.ts';import { boundSessionUpdateForLog, coalesceChunkInto } from './event-log-bounds.ts';import {AgentLaunchError,@@ -76,6 +81,7 @@ import {incompatibleManagedRuntimeHint,incompatibleNodeHint,isPathQualified,+ packageAcquisitionFailure,preflightLaunch,probeInterpreterHealth,probeNpxNodeCompatibility,@@ -220,6 +226,7 @@ interface ThreadRecord {piBridgeDeclined: boolean;lastPiBridgeStatus: PiBridgeThreadState | null;stderrTail: string[];+ drainStderr: (() => Promise<void>) | null;authStderr: string[] | null;terminals: AcpTerminalSet | null;turnActive: boolean;@@ -544,6 +551,7 @@ export class AcpThreadManager {piBridgeDeclined: false,lastPiBridgeStatus: null,stderrTail: [],+ drainStderr: null,authStderr: null,terminals: null,turnActive: false,@@ -611,20 +619,21 @@ export class AcpThreadManager {record: ThreadRecord,custom: CustomAgentEntry | null,): Promise<{ conn: ClientConnection; init: InitializeResponse; launch: ResolvedLaunch } | null> {- let launch: ResolvedLaunch;+ let launch: ResolvedLaunch | null;if (custom !== null) {- launch = resolveCustomLaunch(custom);+ launch = await this.ensureLaunchable(record, resolveCustomLaunch(custom));} else {const manifest = await this.opts.registry.getAgent(record.agentRef.id);if (manifest === undefined) throw new ThreadOpError('unknown-agent', 'agent vanished');- launch = await resolveRegistryLaunch(manifest, registryPlatformKey(), this.opts.log);+ launch = await resolveRegistryLaunch(+ manifest,+ registryPlatformKey(),+ this.opts.log,+ undefined,+ (candidate) => this.ensureLaunchable(record, candidate),+ );}- if (record.closed) return null;-- const launchable = await this.ensureLaunchable(record, launch);- if (launchable === null) return null;- launch = launchable;- if (record.closed) return null;+ if (launch === null || record.closed) return null;const loginShellPath = await this.resolveLoginShellPath().catch(() => null);if (record.closed) return null;@@ -637,16 +646,49 @@ export class AcpThreadManager {});this.emitStatus(record, 'spawning');- const child = spawnAcpAgent(launch, record.cwd);+ const child = launch.kind === 'npx' ? spawnAcpAgent(launch) : spawnAcpAgent(launch, record.cwd);record.child = child;record.terminals = terminals;+ const processClosed = new Promise<void>((resolveClosed) =>+ child.once('close', () => resolveClosed()),+ );+ let stderrDrained: Promise<void> | undefined;+ const drainStderr = (): Promise<void> => {+ if (+ child.exitCode === null &&+ child.signalCode === null &&+ child.stdout?.readableEnded !== true &&+ child.stdout?.destroyed !== true+ ) {+ return Promise.resolve();+ }+ stderrDrained ??= new Promise<void>((resolveDrain) => {+ const timer = setTimeout(resolveDrain, 1_000);+ timer.unref();+ void processClosed.then(() => {+ clearTimeout(timer);+ resolveDrain();+ });+ });+ return stderrDrained;+ };+ record.drainStderr = drainStderr;+ let startupStderr = '';+ let capturingStartup = true;+ const diagnosticCapture = createDiagnosticStderrCapture((line) => {+ if (capturingStartup)+ startupStderr = `${startupStderr}${line}\n`.slice(-ACQUISITION_DETAIL_MAX_CHARS);+ if (line.trim() === '') return;+ record.stderrTail.push(line.slice(0, 500));+ if (record.stderrTail.length > STDERR_TAIL_LINES) record.stderrTail.shift();+ });child.stderr?.setEncoding('utf8');+ child.stderr?.on('data', diagnosticCapture.write);+ child.stderr?.on('end', diagnosticCapture.end);child.stderr?.on('data', (chunk: string) => {for (const line of chunk.split('\n')) {if (line.trim() === '') continue;- record.stderrTail.push(line.slice(0, 500));- if (record.stderrTail.length > STDERR_TAIL_LINES) record.stderrTail.shift();if (record.authStderr !== null) {record.authStderr.push(line.slice(0, 500));if (record.authStderr.length > SIGN_IN_OUTPUT_LINES) record.authStderr.shift();@@ -662,35 +704,44 @@ export class AcpThreadManager {});});child.on('exit', (code, signal) => {+ if (record.child !== child) return;record.child = null;+ this.failPendingPermissions(record);+ this.failPendingConsents(record);terminals.disposeAll().catch((err: unknown) => {this.opts.log.warn({ err, threadId: record.info.threadId },'[acp-threads] terminal cleanup on agent exit failed',);});- if (record.closed || record.info.archived === true) return;- if (record.info.status === 'error') {- this.failPendingPermissions(record);- return;- }- const tail = record.stderrTail.slice(-10).join('\n');- this.opts.log.warn(- {- threadId: record.info.threadId,- agentId: record.info.agent.id,- code,- signal,- machineDetail: stderrTailDetail(record),- },- '[acp-threads] agent exited unexpectedly',- );- this.emitStatus(- record,- 'exited',- `agent exited (${signal ?? code ?? 'unknown'})${tail ? `\n${tail}` : ''}`,- );- this.failPendingPermissions(record);+ void stderrTailDetail(record)+ .then((tail) => {+ if (record.terminals !== terminals) return;+ if (isThreadClosed(record)) return;+ if (record.info.status === 'error') {+ this.failPendingPermissions(record);+ return;+ }+ const headline = `agent exited (${signal ?? code ?? 'unknown'})`;+ this.opts.log.warn(+ {+ threadId: record.info.threadId,+ agentId: record.info.agent.id,+ code,+ signal,+ machineDetail: tail,+ },+ '[acp-threads] agent exited unexpectedly',+ );+ this.emitStatus(record, 'exited', joinMachineDetail({ primary: headline, tail }));+ this.failPendingPermissions(record);+ })+ .catch((err: unknown) => {+ this.opts.log.error(+ { err, threadId: record.info.threadId },+ '[acp-threads] exit diagnostics failed',+ );+ });});if (child.stdin === null || child.stdout === null) {@@ -737,12 +788,7 @@ export class AcpThreadManager {record.conn = conn;conn.closed.then(() => {- if (- !record.closed &&- record.info.archived !== true &&- record.info.status !== 'exited' &&- record.info.status !== 'error'- ) {+ if (record.info.status !== 'exited' && record.info.status !== 'error') {this.emitStatus(record, 'exited', 'agent connection closed');}},@@ -751,12 +797,7 @@ export class AcpThreadManager {{ err, threadId: record.info.threadId },'[acp-threads] agent connection closed with error',);- if (- !record.closed &&- record.info.archived !== true &&- record.info.status !== 'exited' &&- record.info.status !== 'error'- ) {+ if (record.info.status !== 'exited' && record.info.status !== 'error') {this.emitStatus(record,'error',@@ -782,7 +823,15 @@ export class AcpThreadManager {{ err, threadId: record.info.threadId },'[acp-threads] initialize failed',);+ if (launch.kind === 'npx' || launch.kind === 'uvx') {+ await drainStderr();+ const acquisitionFailure = packageAcquisitionFailure(launch, startupStderr, err);+ if (acquisitionFailure !== null) throw acquisitionFailure;+ }throw new ThreadOpError('spawn-failed', `initialize failed: ${agentErrorMessage(err)}`);+ } finally {+ capturingStartup = false;+ startupStderr = '';}if (record.closed) return null;record.lastInit = init;@@ -1437,14 +1486,9 @@ export class AcpThreadManager {try {handshake = await this.connectAgent(record, custom);} catch (err) {- const detail =- err instanceof AgentLaunchError || err instanceof ThreadOpError ? err.message : String(err);- this.emitStatus(record, 'error', detail, {- reason: 'connect',- agentMessage: detail,- machineDetail: stderrTailDetail(record),- });- await this.teardownFailedAgent(record);+ const failure = await connectionFailureDetail(err, record);+ this.emitStatus(record, 'error', failure.agentMessage, failure);+ if (!isThreadClosed(record)) await this.teardownFailedAgent(record);return;}if (handshake === null) return;@@ -1511,24 +1555,28 @@ export class AcpThreadManager {authMethods: threadAuthMethods(init.authMethods),});} else {+ const tail = await stderrTailDetail(record);this.emitStatus(record, 'error', `session setup failed: ${agentErrorMessage(err)}`, {reason: 'session-setup',agentMessage: agentErrorMessage(err),- machineDetail: joinMachineDetail(agentErrorData(err), stderrTailDetail(record)),+ machineDetail: joinMachineDetail({+ primary: agentErrorData(err),+ tail,+ }),});- await this.teardownFailedAgent(record);+ if (!isThreadClosed(record)) await this.teardownFailedAgent(record);}return false;}- if (record.closed) return false;+ if (isThreadClosed(record)) return false;if (settings?.config !== undefined) {await this.applyInitialConfig(record, conn, settings.config);- if (record.closed) return false;+ if (isThreadClosed(record)) return false;}if (settings?.modeId !== undefined) {await this.applyInitialMode(record, conn, settings.modeId);- if (record.closed) return false;+ if (isThreadClosed(record)) return false;}this.emitStatus(record, 'ready');@@ -1666,7 +1714,7 @@ export class AcpThreadManager {}return { ...t.info };} catch (err) {- await this.abortResume(t);+ await this.abortResume(t, await connectionFailureDetail(err, t));if (err instanceof ThreadOpError) throw err;if (err instanceof AgentLaunchError) {throw new ThreadOpError(@@ -1839,7 +1887,12 @@ export class AcpThreadManager {}}- private async abortResume(t: ThreadRecord): Promise<void> {+ private async abortResume(t: ThreadRecord, failure: ThreadFailureDetail): Promise<void> {+ if (isThreadClosed(t)) {+ await this.teardownFailedAgent(t);+ this.emitStatus(t, 'exited', 'resume failed', failure);+ return;+ }t.closed = true;t.suppressUpdates = false;this.failPendingPermissions(t);@@ -1858,7 +1911,7 @@ export class AcpThreadManager {t.turnActive = false;this.opts.agentPresenceBroadcaster?.clearPresence(toBroadcasterKey(t.agentSessionId));t.info.archived = true;- this.emitStatus(t, 'exited', 'resume failed');+ this.recordTerminalStatus(t, 'exited', 'resume failed', failure);this.flushBroadcast(t);this.persistence.queueMetaWrite(t.info.threadId, this.buildMeta(t));await this.persistence.whenIdle(t.info.threadId);@@ -2115,7 +2168,7 @@ export class AcpThreadManager {requestPromise.then((response) => {t.turnActive = false;- if (t.closed) return;+ if (isThreadClosed(t)) return;this.appendEvent(t, {kind: 'turn_ended',stopReason: response.stopReason,@@ -2135,9 +2188,9 @@ export class AcpThreadManager {}this.emitStatus(t, 'ready');})- .catch((err) => {+ .catch(async (err) => {t.turnActive = false;- if (t.closed) return;+ if (isThreadClosed(t)) return;this.appendEvent(t, { kind: 'turn_ended', stopReason: 'cancelled', ts: Date.now() });if (t.sessionId !== null && t.conn !== null) {const steer = this.takeSteer(t);@@ -2160,11 +2213,21 @@ export class AcpThreadManager {});return;}+ const tail = await stderrTailDetail(t);this.emitStatus(t, 'error', `prompt failed: ${agentErrorMessage(err)}`, {reason: 'prompt',agentMessage: agentErrorMessage(err),- machineDetail: joinMachineDetail(agentErrorData(err), stderrTailDetail(t)),+ machineDetail: joinMachineDetail({+ primary: agentErrorData(err),+ tail,+ }),});+ })+ .catch((err: unknown) => {+ this.opts.log.error(+ { err, threadId: t.info.threadId },+ '[acp-threads] prompt diagnostics failed',+ );});}@@ -2444,7 +2507,7 @@ export class AcpThreadManager {this.appendEvent(t, { kind: 'turn_ended', stopReason: 'cancelled', ts: Date.now() });}t.info.archived = true;- this.emitStatus(t, 'exited', 'thread closed');+ this.recordTerminalStatus(t, 'exited', 'thread closed');this.flushBroadcast(t);this.persistence.queueMetaWrite(threadId, this.buildMeta(t));await this.persistence.whenIdle(threadId);@@ -2706,6 +2769,36 @@ export class AcpThreadManager {status: ThreadStatus,detail?: string,failure?: ThreadFailureDetail,+ ): void {+ if (isThreadClosed(t)) {+ const log =+ status === 'error' || status === 'auth_required' ? this.opts.log.warn : this.opts.log.info;+ log.call(+ this.opts.log,+ {+ threadId: t.info.threadId,+ agentId: t.info.agent.id,+ status,+ suppressed: true,+ detail: detail === undefined ? undefined : redactDiagnostic(detail),+ reason: failure?.reason,+ machineDetail:+ failure?.machineDetail === undefined+ ? undefined+ : redactDiagnostic(failure.machineDetail),+ },+ '[acp-threads] status suppressed after thread close',+ );+ return;+ }+ this.recordTerminalStatus(t, status, detail, failure);+ }++ private recordTerminalStatus(+ t: ThreadRecord,+ status: ThreadStatus,+ detail?: string,+ failure?: ThreadFailureDetail,): void {if (status === 'exited' || status === 'error') {t.info.queue = undefined;@@ -2737,6 +2830,8 @@ export class AcpThreadManager {}private async teardownFailedAgent(t: ThreadRecord): Promise<void> {+ this.failPendingPermissions(t);+ this.failPendingConsents(t);const child = t.child;const conn = t.conn;const terminals = t.terminals;@@ -2952,6 +3047,7 @@ function rehydratedRecord(meta: PersistedThreadMeta): ThreadRecord {piBridgeDeclined: false,lastPiBridgeStatus: null,stderrTail: [],+ drainStderr: null,authStderr: null,terminals: null,turnActive: false,@@ -3010,7 +3106,7 @@ function agentErrorData(err: unknown): string | undefined {const data = (err as { data?: unknown }).data;if (data === undefined || data === null) return undefined;try {- return JSON.stringify(data).slice(0, 300);+ return redactDiagnostic(JSON.stringify(data)).slice(0, 300);} catch {return undefined;}@@ -3026,19 +3122,53 @@ function lastFailureMessage(t: ThreadRecord): string | undefined {return undefined;}-function stderrTailDetail(t: ThreadRecord): string | undefined {- const tail = t.stderrTail.join('\n');+async function connectionFailureDetail(+ err: unknown,+ record: ThreadRecord,+): Promise<ThreadFailureDetail> {+ const detail =+ err instanceof AgentLaunchError || err instanceof ThreadOpError ? err.message : String(err);+ return {+ reason: 'connect',+ agentMessage: detail,+ machineDetail: joinMachineDetail({+ primary: err instanceof AgentLaunchError ? err.machineDetail : undefined,+ tail: await stderrTailDetail(record),+ }),+ };+}++function isThreadClosed(t: ThreadRecord): boolean {+ return t.closed || t.info.archived === true;+}++async function stderrTailDetail(t: ThreadRecord): Promise<string | undefined> {+ const lines = t.stderrTail;+ await t.drainStderr?.();+ const tail = redactDiagnostic(lines.join('\n')).slice(-ACQUISITION_DETAIL_MAX_CHARS);return tail === '' ? undefined : tail;}-function joinMachineDetail(...parts: Array<string | undefined>): string | undefined {- const joined = parts.filter((p): p is string => p !== undefined && p !== '').join('\n');- return joined === '' ? undefined : joined;+function joinMachineDetail({+ primary,+ tail,+}: {+ primary: string | undefined;+ tail: string | undefined;+}): string | undefined {+ if (!primary) return tail?.slice(-ACQUISITION_DETAIL_MAX_CHARS) || undefined;+ if (!tail) return primary.slice(0, ACQUISITION_DETAIL_MAX_CHARS);+ const tailFloor = Math.min(tail.length, 1024);+ const primaryBudget = ACQUISITION_DETAIL_MAX_CHARS - tailFloor - 1;+ const headline =+ primary.length > primaryBudget ? `${primary.slice(0, primaryBudget - 1)}…` : primary;+ const remaining = ACQUISITION_DETAIL_MAX_CHARS - headline.length - 1;+ return `${headline}\n${tail.slice(-remaining)}`;}function authMachineDetail(err: unknown, t: ThreadRecord): string | undefined {const duringSignIn = t.authStderr === null ? undefined : t.authStderr.join('\n');- return joinMachineDetail(agentErrorData(err), duringSignIn);+ return joinMachineDetail({ primary: agentErrorData(err), tail: duringSignIn });}function resumableFromCapabilities(init: InitializeResponse): boolean {diff --git a/packages/server/vitest.config.ts b/packages/server/vitest.config.tsindex 81512476f..1a0ecd810 100644--- a/packages/server/vitest.config.ts+++ b/packages/server/vitest.config.ts@@ -1,11 +1,10 @@import { defineConfig } from 'vitest/config';import { okVitestBase } from '../../test-support/vitest.base';-/**- * Vitest config for packages/server.- *- * Spreads the shared workspace base (`development` export-condition pin,- * `bun:test` alias shim, `Bun` global facade, `import.meta.dir` transform, 30s- * timeout). The base `include` matches every `*.test.ts` under the package.- */-export default defineConfig({ ...okVitestBase });+export default defineConfig({+ ...okVitestBase,+ test: {+ ...okVitestBase.test,+ exclude: [...okVitestBase.test.exclude, '**/*.network.test.ts'],+ },+});diff --git a/packages/server/vitest.network.config.ts b/packages/server/vitest.network.config.tsnew file mode 100644index 000000000..6821fc031--- /dev/null+++ b/packages/server/vitest.network.config.ts@@ -0,0 +1,11 @@+import { defineConfig } from 'vitest/config';+import { okVitestBase } from '../../test-support/vitest.base';++export default defineConfig({+ ...okVitestBase,+ test: {+ ...okVitestBase.test,+ include: ['src/acp/*.network.test.ts'],+ fileParallelism: false,+ },+});diff --git a/test-support/setup-files-contract.test.ts b/test-support/setup-files-contract.test.tsindex 00ce476ea..6e6c1af4f 100644--- a/test-support/setup-files-contract.test.ts+++ b/test-support/setup-files-contract.test.ts@@ -25,6 +25,7 @@ const KNOWN_TEST_PROJECTS = ['packages/md-conformance/md-audit/vitest.config.ts','packages/md-conformance/vitest.config.ts','packages/server/vitest.config.ts',+ 'packages/server/vitest.network.config.ts','test-support/fixtures/no-net-connect/vitest.no-net-connect-fixture.config.ts','vitest.config.ts','vitest.scripts.config.ts',