Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Show Installing while an ACP agent's npx package installs (PRD-9262) (#6150)

Andrew Mikofalvya91c0074f268
diff --git a/.changeset/prd-9262-agent-install-status.md b/.changeset/prd-9262-agent-install-status.md
new file mode 100644
index 000000000..c96304b1a
--- /dev/null
+++ b/.changeset/prd-9262-agent-install-status.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+An agent thread's status line now says "Installing" rather than "Starting" while the agent is downloaded and installed ahead of launch.
diff --git a/knip.config.ts b/knip.config.ts
index 0004a763a..69344114d 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -149,15 +149,11 @@ export default {
'packages/server': {
entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],
project: 'src/**',
- ignoreDependencies: [
- '@types/shell-quote',
- ],
+ ignoreDependencies: ['@types/shell-quote'],
},
'packages/cli': {
entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],
- ignoreDependencies: [
- 'yjs',
- ],
+ ignoreDependencies: ['yjs'],
},
'packages/desktop': {
entry: [
diff --git a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
index 4549c74b3..a50b00123 100644
--- a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
+++ b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
@@ -1,4 +1,3 @@
-
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
index 4fc2c11f9..6fcdc23f2 100644
--- a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
+++ b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
@@ -1,4 +1,3 @@
-
import { setTimeout as wait } from 'node:timers/promises';
import { normalizeBridge } from '@inkeep/open-knowledge-core';
import { updateYFragment } from '@tiptap/y-tiptap';
diff --git a/packages/app/tests/integration/interior-edit-freshness.test.ts b/packages/app/tests/integration/interior-edit-freshness.test.ts
index 9f2f6feb6..40b5cdfd6 100644
--- a/packages/app/tests/integration/interior-edit-freshness.test.ts
+++ b/packages/app/tests/integration/interior-edit-freshness.test.ts
@@ -1,4 +1,3 @@
-
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
index 2a085742b..93666af70 100644
--- a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
+++ b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
@@ -1,4 +1,3 @@
-
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/producer-guard-wiring.test.ts b/packages/app/tests/integration/producer-guard-wiring.test.ts
index 878d5196b..867598d34 100644
--- a/packages/app/tests/integration/producer-guard-wiring.test.ts
+++ b/packages/app/tests/integration/producer-guard-wiring.test.ts
@@ -1,4 +1,3 @@
-
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
index 4ada3cf26..0970ac12f 100644
--- a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
+++ b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
@@ -1,4 +1,3 @@
-
import { randomUUID } from 'node:crypto';
import { afterEach, describe, expect, test } from 'vitest';
import { agentWriteMd, createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
index cbe2b705f..b632185e1 100644
--- a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
+++ b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
@@ -1,4 +1,3 @@
-
import { execFileSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { join } from 'node:path';
diff --git a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
index 89bc9b4d9..c530ce4ba 100644
--- a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
+++ b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
@@ -1,4 +1,3 @@
-
import { randomUUID } from 'node:crypto';
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';
import type * as Y from 'yjs';
diff --git a/packages/app/tests/integration/undo-after-rollback.test.ts b/packages/app/tests/integration/undo-after-rollback.test.ts
index a78aeb0e4..d3767adc9 100644
--- a/packages/app/tests/integration/undo-after-rollback.test.ts
+++ b/packages/app/tests/integration/undo-after-rollback.test.ts
@@ -1,4 +1,3 @@
-
import { ROLLBACK_ORIGIN } from '@inkeep/open-knowledge-server';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
diff --git a/packages/app/tests/integration/undo-recycle-reset.test.ts b/packages/app/tests/integration/undo-recycle-reset.test.ts
index e7cc69c3f..b076f955c 100644
--- a/packages/app/tests/integration/undo-recycle-reset.test.ts
+++ b/packages/app/tests/integration/undo-recycle-reset.test.ts
@@ -1,4 +1,3 @@
-
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/tests/integration/undo-rederive-survival.test.ts b/packages/app/tests/integration/undo-rederive-survival.test.ts
index 9ddcd0730..7935e35f8 100644
--- a/packages/app/tests/integration/undo-rederive-survival.test.ts
+++ b/packages/app/tests/integration/undo-rederive-survival.test.ts
@@ -1,4 +1,3 @@
-
import { prependFrontmatter } from '@inkeep/open-knowledge-core';
import { Plugin, PluginKey } from '@tiptap/pm/state';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.ts
index 2a597ec3d..f4cc8a286 100644
--- a/packages/core/src/bridge/compose.ts
+++ b/packages/core/src/bridge/compose.ts
@@ -1,4 +1,3 @@
-
import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';
export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index ffd8fce06..e7e63f43d 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,4 +1,3 @@
-
import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';
import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index fb0ba5a7c..fc267cbea 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index fa3cfcd86..bfd7e3109 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parent, Root } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 8be632ba4..4d3250d3a 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,4 +1,3 @@
-
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/packages/server/src/acp/held-install-registry.test-helper.ts b/packages/server/src/acp/held-install-registry.test-helper.ts
new file mode 100644
index 000000000..036bcfb32
--- /dev/null
+++ b/packages/server/src/acp/held-install-registry.test-helper.ts
@@ -0,0 +1,306 @@
+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 { ZipFile } from 'yazl';
+import { withAcquisitionHome } from './package-acquisition.test-helper.ts';
+import type { RegistryBinaryTarget } from './registry.ts';
+
+type HeldArtifact = 'npm-package' | 'npm-dependency' | 'wheel' | 'binary-archive';
+
+export type HeldInstallRegistry = {
+ home: string;
+ npmPackage: string;
+ uvxPackage: string;
+ binaryTarget: RegistryBinaryTarget;
+ requested: (artifact: HeldArtifact) => number;
+ release: (artifact: HeldArtifact) => void;
+ rearm: (artifact: HeldArtifact) => void;
+ answerNotFound: (artifact: HeldArtifact) => void;
+};
+
+const AGENT_NAME = 'ok-held-install-agent';
+const DEPENDENCY_NAME = 'ok-held-install-dependency';
+const VERSION = '1.0.0';
+const PUBLISHED = '2020-01-01T00:00:00.000Z';
+const WHEEL_FILE = `ok_held_install_agent-${VERSION}-py3-none-any.whl`;
+
+const NODE_ACP_AGENT = `
+const write = (msg) => process.stdout.write(JSON.stringify(msg) + '\\n');
+let buffer = '';
+process.stdin.setEncoding('utf8');
+process.stdin.on('data', (chunk) => {
+ buffer += chunk;
+ let idx = buffer.indexOf('\\n');
+ while (idx !== -1) {
+ const line = buffer.slice(0, idx);
+ buffer = buffer.slice(idx + 1);
+ idx = buffer.indexOf('\\n');
+ if (line.trim() === '') continue;
+ const msg = JSON.parse(line);
+ if (msg.method === 'initialize') {
+ write({ jsonrpc: '2.0', id: msg.id, result: { protocolVersion: 1, agentCapabilities: {} } });
+ } else if (msg.method === 'session/new') {
+ write({ jsonrpc: '2.0', id: msg.id, result: { sessionId: 'held-install-session' } });
+ } else if (msg.id !== undefined && msg.method !== undefined) {
+ write({ jsonrpc: '2.0', id: msg.id, result: {} });
+ }
+ }
+});
+`;
+
+const PYTHON_ACP_AGENT = `import json
+import sys
+
+
+def main():
+ while True:
+ line = sys.stdin.readline()
+ if not line:
+ return
+ if line.strip() == '':
+ continue
+ msg = json.loads(line)
+ if 'id' not in msg or 'method' not in msg:
+ continue
+ if msg['method'] == 'initialize':
+ result = {'protocolVersion': 1, 'agentCapabilities': {}}
+ elif msg['method'] == 'session/new':
+ result = {'sessionId': 'held-install-session'}
+ else:
+ result = {}
+ sys.stdout.write(json.dumps({'jsonrpc': '2.0', 'id': msg['id'], 'result': result}) + '\\n')
+ sys.stdout.flush()
+`;
+
+function tarball(root: string, label: string, files: Record<string, string>, top: string): Buffer {
+ const tree = join(root, label);
+ for (const [path, body] of Object.entries(files)) {
+ const target = join(tree, top, path);
+ mkdirSync(join(target, '..'), { recursive: true });
+ writeFileSync(target, body, { mode: 0o755 });
+ }
+ const archive = join(root, `${label}.tgz`);
+ execFileSync('tar', ['-czf', archive, '-C', tree, top]);
+ return readFileSync(archive);
+}
+
+async function wheel(): Promise<Buffer> {
+ const distInfo = `ok_held_install_agent-${VERSION}.dist-info`;
+ const files: Record<string, string> = {
+ 'ok_held_install_agent/__init__.py': PYTHON_ACP_AGENT,
+ [`${distInfo}/METADATA`]: `Metadata-Version: 2.1\nName: ${AGENT_NAME}\nVersion: ${VERSION}\n`,
+ [`${distInfo}/WHEEL`]:
+ 'Wheel-Version: 1.0\nGenerator: ok-held-install\nRoot-Is-Purelib: true\nTag: py3-none-any\n',
+ [`${distInfo}/entry_points.txt`]: `[console_scripts]\n${AGENT_NAME} = ok_held_install_agent:main\n`,
+ };
+ const record = Object.entries(files).map(
+ ([path, body]) =>
+ `${path},sha256=${createHash('sha256').update(body).digest('base64url')},${Buffer.byteLength(body)}`,
+ );
+ files[`${distInfo}/RECORD`] = `${record.join('\n')}\n${distInfo}/RECORD,,\n`;
+ const zip = new ZipFile();
+ for (const [path, body] of Object.entries(files)) zip.addBuffer(Buffer.from(body), path);
+ zip.end();
+ const chunks: Buffer[] = [];
+ for await (const chunk of zip.outputStream) chunks.push(chunk as Buffer);
+ return Buffer.concat(chunks);
+}
+
+function packument(
+ host: string,
+ name: string,
+ bytes: Buffer,
+ manifest: Record<string, unknown>,
+ published: string,
+): string {
+ return JSON.stringify({
+ name,
+ 'dist-tags': { latest: VERSION },
+ versions: {
+ [VERSION]: {
+ name,
+ version: VERSION,
+ ...manifest,
+ dist: {
+ tarball: `http://${host}/${name}/-/${name}-${VERSION}.tgz`,
+ shasum: createHash('sha1').update(bytes).digest('hex'),
+ integrity: `sha512-${createHash('sha512').update(bytes).digest('base64')}`,
+ },
+ },
+ },
+ time: { [VERSION]: published },
+ });
+}
+
+export async function withHeldInstallRegistry(
+ run: (registry: HeldInstallRegistry) => Promise<void>,
+ { dependencyPublished = PUBLISHED }: { dependencyPublished?: string } = {},
+): Promise<void> {
+ await withAcquisitionHome(async (home) => {
+ const sources = join(home, 'held-install-sources');
+ const agentManifest = {
+ bin: { [AGENT_NAME]: 'agent.js' },
+ dependencies: { [DEPENDENCY_NAME]: VERSION },
+ };
+ const agentTarball = tarball(
+ sources,
+ 'npm-agent',
+ {
+ 'package.json': JSON.stringify({ name: AGENT_NAME, version: VERSION, ...agentManifest }),
+ 'agent.js': `#!/usr/bin/env node\n${NODE_ACP_AGENT}`,
+ },
+ 'package',
+ );
+ const dependencyTarball = tarball(
+ sources,
+ 'npm-dependency',
+ {
+ 'package.json': JSON.stringify({ name: DEPENDENCY_NAME, version: VERSION }),
+ 'index.js': 'module.exports = 1;\n',
+ },
+ 'package',
+ );
+ const binaryArchive = tarball(
+ sources,
+ 'binary',
+ { 'bin/agent': `#!/usr/bin/env node\n${NODE_ACP_AGENT}` },
+ 'agent',
+ );
+ const wheelBytes = await wheel();
+
+ const openers: Array<() => void> = [];
+ const gate = (): { open: () => void; opened: Promise<void> } => {
+ let open = (): void => {};
+ const opened = new Promise<void>((resolve) => {
+ open = resolve;
+ });
+ openers.push(open);
+ return { open, opened };
+ };
+ const holds = new Map<
+ HeldArtifact,
+ {
+ count: number;
+ released: boolean;
+ notFound: boolean;
+ open: () => void;
+ opened: Promise<void>;
+ }
+ >();
+ for (const artifact of ['npm-package', 'npm-dependency', 'wheel', 'binary-archive'] as const) {
+ holds.set(artifact, { count: 0, released: false, notFound: false, ...gate() });
+ }
+ const heldEntry = (artifact: HeldArtifact) => {
+ const entry = holds.get(artifact);
+ if (entry === undefined) throw new Error(`unknown held artifact ${artifact}`);
+ return entry;
+ };
+ const release = (artifact: HeldArtifact): void => {
+ const entry = heldEntry(artifact);
+ entry.released = true;
+ entry.open();
+ };
+ release('npm-package');
+
+ const server = createServer((req, res) => {
+ const path = decodeURIComponent(req.url ?? '/');
+ const host = req.headers.host ?? '127.0.0.1';
+ const send = (bytes: Buffer, contentType: string): void => {
+ res.writeHead(200, { 'content-type': contentType, 'content-length': bytes.length });
+ res.end(req.method === 'HEAD' ? undefined : bytes);
+ };
+ const sendHeld = (artifact: HeldArtifact, bytes: Buffer, contentType: string): void => {
+ const entry = heldEntry(artifact);
+ entry.count += 1;
+ if (entry.notFound) {
+ res.writeHead(404);
+ res.end();
+ return;
+ }
+ void entry.opened.then(() => send(bytes, contentType));
+ };
+ if (path === `/${AGENT_NAME}`) {
+ send(
+ Buffer.from(packument(host, AGENT_NAME, agentTarball, agentManifest, PUBLISHED)),
+ 'application/json',
+ );
+ } else if (path === `/${DEPENDENCY_NAME}`) {
+ send(
+ Buffer.from(packument(host, DEPENDENCY_NAME, dependencyTarball, {}, dependencyPublished)),
+ 'application/json',
+ );
+ } else if (path === `/${AGENT_NAME}/-/${AGENT_NAME}-${VERSION}.tgz`) {
+ sendHeld('npm-package', agentTarball, 'application/octet-stream');
+ } else if (path === `/${DEPENDENCY_NAME}/-/${DEPENDENCY_NAME}-${VERSION}.tgz`) {
+ sendHeld('npm-dependency', dependencyTarball, 'application/octet-stream');
+ } else if (path === `/simple/${AGENT_NAME}/`) {
+ send(
+ Buffer.from(
+ JSON.stringify({
+ meta: { 'api-version': '1.1' },
+ name: AGENT_NAME,
+ versions: [VERSION],
+ files: [
+ {
+ filename: WHEEL_FILE,
+ url: `/files/${WHEEL_FILE}`,
+ hashes: { sha256: createHash('sha256').update(wheelBytes).digest('hex') },
+ 'upload-time': PUBLISHED,
+ size: wheelBytes.length,
+ },
+ ],
+ }),
+ ),
+ 'application/vnd.pypi.simple.v1+json',
+ );
+ } else if (path === `/files/${WHEEL_FILE}`) {
+ sendHeld('wheel', wheelBytes, 'application/octet-stream');
+ } else if (path === '/binary/agent.tgz') {
+ sendHeld('binary-archive', binaryArchive, 'application/gzip');
+ } else {
+ res.writeHead(404);
+ res.end();
+ }
+ });
+ server.listen(0, '127.0.0.1');
+ await once(server, 'listening');
+ const address = server.address();
+ if (address === null || typeof address === 'string') throw new Error('missing port');
+ const origin = `http://127.0.0.1:${address.port}`;
+ process.env.npm_config_registry = `${origin}/`;
+ process.env.npm_config_fetch_timeout = '120000';
+ process.env.UV_OFFLINE = '0';
+ process.env.UV_DEFAULT_INDEX = `${origin}/simple`;
+ process.env.UV_HTTP_TIMEOUT = '120';
+
+ try {
+ await run({
+ home,
+ npmPackage: `${AGENT_NAME}@${VERSION}`,
+ uvxPackage: `${AGENT_NAME}==${VERSION}`,
+ binaryTarget: {
+ archive: `${origin}/binary/agent.tgz`,
+ sha256: createHash('sha256').update(binaryArchive).digest('hex'),
+ cmd: './agent/bin/agent',
+ },
+ requested: (artifact) => heldEntry(artifact).count,
+ release,
+ rearm: (artifact) => {
+ const entry = heldEntry(artifact);
+ if (!entry.released) throw new Error(`${artifact} is still held`);
+ Object.assign(entry, { released: false, ...gate() });
+ },
+ answerNotFound: (artifact) => {
+ heldEntry(artifact).notFound = true;
+ },
+ });
+ } finally {
+ for (const open of openers) open();
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ }
+ });
+}
diff --git a/packages/server/src/acp/launch-package-acquisition.test.ts b/packages/server/src/acp/launch-package-acquisition.test.ts
index 67491dc53..607197faf 100644
--- a/packages/server/src/acp/launch-package-acquisition.test.ts
+++ b/packages/server/src/acp/launch-package-acquisition.test.ts
@@ -267,6 +267,33 @@ describe('hermetic package acquisition and native dispatch', () => {
});
});
+ test('an install that fails without output names its exit code in the machine detail', async () => {
+ await withAcquisitionHome(async (home) => {
+ const bin = join(home, 'bin');
+ mkdirSync(bin);
+ installNodeFixture(bin);
+ writeExecutable(join(bin, 'npx'), 'process.exit(3);');
+ writeExecutable(
+ join(bin, 'npm'),
+ `process.stdout.write(${JSON.stringify(JSON.stringify([{ name: 'is-number', version: '7.0.0' }]))});`,
+ );
+ await expect(
+ resolveRegistryLaunch(
+ registryPackage('[email protected]', 'npx', { PATH: bin }),
+ null,
+ log,
+ undefined,
+ async (launch) => launch,
+ { install: true },
+ ),
+ ).rejects.toMatchObject({
+ code: 'install-failed',
+ message: 'Could not install [email protected].',
+ machineDetail: 'exit code 3',
+ });
+ });
+ });
+
test.each(['malformed', 'overflow', 'timeout'] as const)(
'native npm %s output fails acquisition and releases the owned process',
async (mode) => {
diff --git a/packages/server/src/acp/launch.ts b/packages/server/src/acp/launch.ts
index 9d56782e9..2775d9d19 100644
--- a/packages/server/src/acp/launch.ts
+++ b/packages/server/src/acp/launch.ts
@@ -32,10 +32,13 @@ export type ResolvedLaunch = {
pathFromOverlay: boolean;
} & ({ kind: 'npx' } | { kind: 'uvx' } | { kind: 'binary' } | { kind: 'custom' });
+export type NpxCacheEntry = string & { readonly __brand: 'NpxCacheEntry' };
+
export const MINIMUM_NPX_NODE_MAJOR = 22;
export class AgentLaunchError extends Error {
readonly machineDetail?: string;
+ readonly npxCacheEntry?: NpxCacheEntry;
readonly code:
| 'unsupported-platform'
| 'no-distribution'
@@ -44,11 +47,12 @@ export class AgentLaunchError extends Error {
constructor(
code: AgentLaunchError['code'],
message: string,
- options?: ErrorOptions & { machineDetail?: string },
+ options?: ErrorOptions & { machineDetail?: string; npxCacheEntry?: NpxCacheEntry },
) {
super(message, options);
this.name = 'AgentLaunchError';
this.code = code;
+ this.npxCacheEntry = options?.npxCacheEntry;
this.machineDetail =
options?.machineDetail === undefined
? undefined
@@ -110,9 +114,10 @@ type ResolvedNpmAcquisition =
| { outcome: ProbedNpmOutcome; acquired: string; source: 'memo'; elapsedMs: 0 }
| (NpmPackageResolution & { source: 'probe' | 'joined' });
-type NpmAcquisitionOptions = {
+type RegistryAcquisitionOptions = {
reacquire?: boolean;
- onProbeStart?: () => void;
+ install?: boolean;
+ onAcquiring?: () => void;
onResolved?: (resolution: ResolvedNpmAcquisition) => void;
};
@@ -128,7 +133,7 @@ export function resolveRegistryLaunch(
log: PinoLogger,
binaryCacheDir: string | undefined,
prepare: PrepareRegistryLaunch,
- acquisition?: NpmAcquisitionOptions,
+ acquisition?: RegistryAcquisitionOptions,
): Promise<ResolvedLaunch | null>;
export async function resolveRegistryLaunch(
agent: RegistryAgent,
@@ -136,8 +141,17 @@ export async function resolveRegistryLaunch(
log: PinoLogger,
binaryCacheDir: string = defaultBinaryCacheDir(),
prepare?: PrepareRegistryLaunch,
- acquisition?: NpmAcquisitionOptions,
+ acquisition?: RegistryAcquisitionOptions,
): Promise<ResolvedLaunch | null> {
+ let acquiringReported = false;
+ const reporting: RegistryAcquisitionOptions = {
+ ...acquisition,
+ onAcquiring: () => {
+ if (acquiringReported) return;
+ acquiringReported = true;
+ acquisition?.onAcquiring?.();
+ },
+ };
const dist = agent.distribution;
if (dist.npx !== undefined) {
const raw: ResolvedLaunch = {
@@ -154,14 +168,17 @@ export async function resolveRegistryLaunch(
dist.npx.package,
);
if (pin?.groups === undefined) return launch;
- const selected = await acquireNpmPackage(
+ const { acquired, outcome } = await acquireNpmPackage(
launch,
pin.groups.name,
pin.groups.version,
log,
- acquisition,
+ reporting,
);
- return { ...launch, args: ['-y', selected, ...(dist.npx.args ?? [])] };
+ if (acquisition?.install === true && outcome !== 'forwarded') {
+ await ensureNpmPackageInstalled(launch, acquired, log, reporting);
+ }
+ return { ...launch, args: ['-y', acquired, ...(dist.npx.args ?? [])] };
}
if (dist.uvx !== undefined) {
const pin = /^(?<name>[A-Za-z0-9][A-Za-z0-9._-]*)(?:==|@)(?<version>\d+\.\d+\.\d+)$/.exec(
@@ -195,7 +212,9 @@ export async function resolveRegistryLaunch(
);
}
const target = dist.binary[platformKey];
- const root = await ensureBinaryInstalled(agent.id, agent.version, target, binaryCacheDir, log);
+ const root = await ensureBinaryInstalled(agent.id, agent.version, target, binaryCacheDir, log, {
+ onDownloadStart: reporting.onAcquiring,
+ });
const cmd = resolve(root, target.cmd.replace(/\\/g, '/'));
if (!isWithin(root, cmd)) {
throw new AgentLaunchError(
@@ -266,12 +285,12 @@ const NPX_CACHE_PACKAGE_JSON =
const PARENT_SEGMENT = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
-export function staleNpxCacheEntry(detail: string): string | null {
+export function staleNpxCacheEntry(detail: string): NpxCacheEntry | null {
if (!/\bENOENT\b/.test(detail)) return null;
for (const pattern of NPM_ENOENT_PATH_LINES) {
const path = pattern.exec(detail)?.[1];
const entry = path === undefined ? undefined : NPX_CACHE_PACKAGE_JSON.exec(path)?.[1];
- if (entry !== undefined && !PARENT_SEGMENT.test(entry)) return entry;
+ if (entry !== undefined && !PARENT_SEGMENT.test(entry)) return entry as NpxCacheEntry;
}
return null;
}
@@ -368,15 +387,104 @@ type AcquiredNpmPackage =
const acquiredNpmPackages = new Map<string, AcquiredNpmPackage>();
+type InstalledNpmPackage = { state: 'installing'; install: Promise<void> } | { state: 'installed' };
+
+const installedNpmPackages = new Map<string, InstalledNpmPackage>();
+
export function resetAcquisitionCache(): void {
acquiredNpmPackages.clear();
+ installedNpmPackages.clear();
}
-function acquisitionKey(launch: ResolvedLaunch, name: string, ceiling: string): string {
- const env = Object.entries(launch.env).sort(([left], [right]) =>
+function sortedLaunchEnv(launch: ResolvedLaunch): [string, string][] {
+ return Object.entries(launch.env).sort(([left], [right]) =>
left < right ? -1 : left > right ? 1 : 0,
);
- return JSON.stringify([launch.cmd, env, name, ceiling]);
+}
+
+function acquisitionKey(launch: ResolvedLaunch, name: string, ceiling: string): string {
+ return JSON.stringify([launch.cmd, sortedLaunchEnv(launch), name, ceiling]);
+}
+
+function ensureNpmPackageInstalled(
+ launch: ResolvedLaunch,
+ acquired: string,
+ log: PinoLogger,
+ acquisition: RegistryAcquisitionOptions,
+): Promise<void> {
+ const key = JSON.stringify([launch.cmd, sortedLaunchEnv(launch), acquired]);
+ const cached = installedNpmPackages.get(key);
+ if (cached?.state === 'installing') {
+ acquisition.onAcquiring?.();
+ return cached.install;
+ }
+ if (cached?.state === 'installed' && acquisition.reacquire !== true) return Promise.resolve();
+ acquisition.onAcquiring?.();
+ const install = installNpmPackage(launch, acquired, log);
+ const entry: InstalledNpmPackage = { state: 'installing', install };
+ installedNpmPackages.set(key, entry);
+ const replace = (next: InstalledNpmPackage | null): void => {
+ if (installedNpmPackages.get(key) !== entry) return;
+ if (next === null) installedNpmPackages.delete(key);
+ else installedNpmPackages.set(key, next);
+ };
+ void install.then(
+ () => replace({ state: 'installed' }),
+ () => replace(null),
+ );
+ return install;
+}
+
+async function installNpmPackage(
+ launch: ResolvedLaunch,
+ acquired: string,
+ log: PinoLogger,
+): Promise<void> {
+ const startedAt = Date.now();
+ const child = spawnAcpAgent({
+ ...launch,
+ kind: 'npx',
+ args: ['--yes', `--package=${acquired}`, '--call=exit 0'],
+ });
+ let stderr = '';
+ let rawStderr = '';
+ let spawnFailure: string | undefined;
+ child.stdin?.end();
+ child.stdout?.resume();
+ child.stderr?.setEncoding('utf8');
+ const stderrCapture = createDiagnosticStderrCapture(
+ (line) => {
+ stderr = `${stderr}${line}\n`.slice(-ACQUISITION_DETAIL_MAX_CHARS);
+ },
+ (rawLine) => {
+ rawStderr = `${rawStderr}${rawLine}\n`.slice(-ACQUISITION_DETAIL_MAX_CHARS);
+ },
+ );
+ child.stderr?.on('data', stderrCapture.write);
+ child.stderr?.on('end', stderrCapture.end);
+ child.once('error', (err) => {
+ spawnFailure = err.message;
+ });
+ const [code, signal] = await new Promise<[number | null, NodeJS.Signals | null]>(
+ (resolvePromise) => child.once('close', (...exit) => resolvePromise(exit)),
+ );
+ if (spawnFailure === undefined && code === 0) {
+ log.info(
+ { package: acquired, elapsedMs: Date.now() - startedAt },
+ '[acp-launch] agent package installed',
+ );
+ return;
+ }
+ const detail = `${stderr}${spawnFailure ?? ''}`.trim() || (signal ?? `exit code ${code}`);
+ const npxCacheEntry = staleNpxCacheEntry(rawStderr) ?? undefined;
+ if (npxCacheEntry === undefined) {
+ const refusal = spawnFailure === undefined ? packageAcquisitionFailure(launch, detail) : null;
+ if (refusal !== null) throw refusal;
+ }
+ throw new AgentLaunchError('install-failed', `Could not install ${acquired}.`, {
+ machineDetail: detail,
+ npxCacheEntry,
+ });
}
function heldNpmPackage(entry: AcquiredNpmPackage | undefined): HeldNpmPackage | null {
@@ -396,8 +504,8 @@ function acquireNpmPackage(
name: string,
ceiling: string,
log: PinoLogger,
- acquisition?: NpmAcquisitionOptions,
-): Promise<string> {
+ acquisition?: RegistryAcquisitionOptions,
+): Promise<{ acquired: string; outcome: NpmPackageResolution['outcome'] }> {
const key = acquisitionKey(launch, name, ceiling);
const cached = acquiredNpmPackages.get(key);
const held = heldNpmPackage(cached);
@@ -408,14 +516,15 @@ function acquireNpmPackage(
source: 'memo',
elapsedMs: 0,
});
- return Promise.resolve(held.acquired);
+ return Promise.resolve({ acquired: held.acquired, outcome: held.outcome });
}
const joined = openNpmProbe(cached);
+ if (joined !== null) acquisition?.onAcquiring?.();
const probe = joined ?? beginNpmAcquisition(key, held, launch, name, ceiling, log, acquisition);
const source: 'probe' | 'joined' = joined === null ? 'probe' : 'joined';
return probe.then((resolved) => {
acquisition?.onResolved?.({ ...resolved, source });
- return resolved.acquired;
+ return { acquired: resolved.acquired, outcome: resolved.outcome };
});
}
@@ -426,7 +535,7 @@ function beginNpmAcquisition(
name: string,
ceiling: string,
log: PinoLogger,
- acquisition?: NpmAcquisitionOptions,
+ acquisition?: RegistryAcquisitionOptions,
): Promise<NpmPackageResolution> {
const probe = acquireNpmPackageUncached(launch, name, ceiling, log, acquisition);
const entry: AcquiredNpmPackage =
@@ -456,7 +565,7 @@ async function acquireNpmPackageUncached(
name: string,
ceiling: string,
log: PinoLogger,
- acquisition?: NpmAcquisitionOptions,
+ acquisition?: RegistryAcquisitionOptions,
): Promise<NpmPackageResolution> {
let descriptor = `${name}@${ceiling}`;
const npm = await npmCommand(launch);
@@ -467,7 +576,7 @@ async function acquireNpmPackageUncached(
);
return { outcome: 'forwarded', acquired: descriptor, elapsedMs: 0 };
}
- acquisition?.onProbeStart?.();
+ acquisition?.onAcquiring?.();
const probeStartedAt = Date.now();
let result = await probeNpmPackage(launch, descriptor, npm);
let bounded = false;
@@ -574,6 +683,7 @@ function prependPath(dir: string, existing: string | undefined): string {
export interface EnsureBinaryInstallOptions {
fetchImpl?: typeof fetch;
+ onDownloadStart?: () => void;
beforeCommit?: () => Promise<void>;
commitLockTimeoutMs?: number;
}
@@ -682,6 +792,7 @@ export async function ensureBinaryInstalled(
);
}
await tracedRm(markerPath, { force: true });
+ opts.onDownloadStart?.();
log.info({ id, version, archive: target.archive }, '[acp-launch] downloading agent binary');
const isZip = /\.zip$/i.test(new URL(target.archive).pathname);
const archivePath = join(stagingDir, isZip ? 'archive.zip' : 'archive.tar.gz');
diff --git a/packages/server/src/acp/thread-manager.integration.test.ts b/packages/server/src/acp/thread-manager.integration.test.ts
index b028e4233..0b45ca5e4 100644
--- a/packages/server/src/acp/thread-manager.integration.test.ts
+++ b/packages/server/src/acp/thread-manager.integration.test.ts
@@ -37,9 +37,14 @@ import { isValidLockPid } from '../process-alive.ts';
import { RUNTIME_VERSION } from '../version-constants.ts';
import { withLocalAcquisitionRegistry } from './acquisition-contract.test-helper.ts';
import { isWithin } from './archive.ts';
-import { agentSpawnPath } from './launch.ts';
+import {
+ type HeldInstallRegistry,
+ withHeldInstallRegistry,
+} from './held-install-registry.test-helper.ts';
+import { agentSpawnPath, resetAcquisitionCache } from './launch.ts';
import {
installNodeFixture,
+ native,
npmCli,
probedDescriptors,
registryPackage,
@@ -50,7 +55,7 @@ import {
import { AcpPermissionStore, readAutoApproveOkTools } from './permissions.ts';
import * as projectSkillStaging from './project-skill-staging.ts';
import { PROJECT_SKILL_ENTRY, projectSkillStageDir } from './project-skill-staging.ts';
-import { AcpRegistry } from './registry.ts';
+import { AcpRegistry, type RegistryAgent, registryPlatformKey } from './registry.ts';
import {
ACP_ENVIRONMENT_NOTE,
AcpThreadManager,
@@ -7725,6 +7730,401 @@ describe('registry adapter acquisition probe scope across thread opens', () => {
}, 90_000);
});
+describe.skipIf(process.platform === 'win32')(
+ 'status frames while an agent package is really being installed',
+ () => {
+ const heldInstallManager = (
+ held: HeldInstallRegistry,
+ distribution: RegistryAgent['distribution'],
+ ): { agentId: string; manager: AcpThreadManager } => {
+ const localDir = tmp();
+ const agent: RegistryAgent = {
+ id: 'held-install',
+ name: 'Held install agent',
+ version: '1.0.0',
+ distribution,
+ };
+ const registry = new AcpRegistry({
+ localDir,
+ log,
+ fetchImpl: async () => new Response(JSON.stringify({ agents: [agent] })),
+ });
+ return {
+ agentId: agent.id,
+ manager: makeManager(held.home, localDir, { registry, projectSkillSourceDir: null }),
+ };
+ };
+
+ const binaryDistribution = (held: HeldInstallRegistry): RegistryAgent['distribution'] => {
+ const platformKey = registryPlatformKey();
+ if (platformKey === null) throw new Error('this platform has no registry binary key');
+ return { binary: { [platformKey]: held.binaryTarget } };
+ };
+
+ const expectNpxLeavingStaleEntries = async (): Promise<void> => {
+ const npx = await native('npx', ['--version']);
+ expect(npx.code, npx.stderr).toBe(0);
+ expect(
+ Number.parseInt(npx.stdout, 10),
+ `npx ${npx.stdout.trim()} cannot leave the stale entry this test reinstalls; it needs npm 11 or later`,
+ ).toBeGreaterThanOrEqual(11);
+ };
+
+ const statusOnceReached = async (
+ read: () => string | undefined,
+ wanted: string,
+ ms: number,
+ ): Promise<string | undefined> => {
+ const deadline = Date.now() + ms;
+ let seen = read();
+ while (seen !== wanted && Date.now() < deadline) {
+ await new Promise((r) => setTimeout(r, 25));
+ seen = read();
+ }
+ return seen;
+ };
+
+ const leaveStaleNpxEntry = (held: HeldInstallRegistry): void => {
+ const npxCache = join(held.home, 'npm-cache', '_npx');
+ const entries = readdirSync(npxCache);
+ expect(entries).toHaveLength(1);
+ const packageJson = join(npxCache, String(entries[0]), 'package.json');
+ expect(existsSync(packageJson)).toBe(true);
+ rmSync(packageJson);
+ rmSync(join(held.home, 'npm-cache', '_cacache'), { recursive: true, force: true });
+ };
+
+ test('a cold npx launch reports installing while npx installs the package', async () => {
+ await withHeldInstallRegistry(async (held) => {
+ const { agentId, manager } = heldInstallManager(held, {
+ npx: { package: held.npmPackage },
+ });
+ try {
+ const info = await manager.createThread({ agent: { source: 'registry', id: agentId } });
+ await waitUntil(
+ () => held.requested('npm-dependency') > 0,
+ 30_000,
+ 'npx to start installing the package',
+ );
+
+ await expect
+ .poll(() => manager.getInfo(info.threadId)?.status, { timeout: 10_000 })
+ .toBe('installing');
+
+ held.release('npm-dependency');
+ await expect
+ .poll(() => manager.getInfo(info.threadId)?.status, { timeout: 30_000 })
+ .toBe('ready');
+ } finally {
+ await manager.destroy();
+ }
+ });
+ }, 90_000);
+
+ test('a second thread waiting on an in-flight npx install reports installing', async () => {
+ await withHeldInstallRegistry(async (held) => {
+ const { agentId, manager } = heldInstallManager(held, {
+ npx: { package: held.npmPackage },
+ });
+ try {
+ const first = await manager.createThread({ agent: { source: 'registry', id: agentId } });
+ await waitUntil(
+ () => held.requested('npm-dependency') > 0,
+ 30_000,
+ "the first thread's npx to start installing the package",
+ );
+ const second = await manager.createThread({
+ agent: { source: 'registry', id: agentId },
+ });
+
+ await expect
+ .poll(() => manager.getInfo(second.threadId)?.status, { timeout: 10_000 })
+ .toBe('installing');
+
+ held.release('npm-dependency');
+ await expect
+ .poll(() => manager.getInfo(first.threadId)?.status, { timeout: 30_000 })
+ .toBe('ready');
+ await expect
+ .poll(() => manager.getInfo(second.threadId)?.status, { timeout: 30_000 })
+ .toBe('ready');
+ } finally {
+ await manager.destroy();
+ }
+ });
+ }, 90_000);
+
+ test('a cold binary agent launch reports installing while its archive downloads', async () => {
+ await withHeldInstallRegistry(async (held) => {
+ const { agentId, manager } = heldInstallManager(held, binaryDistribution(held));
+ try {
+ const info = await manager.createThread({ agent: { source: 'registry', id: agentId } });
+ await waitUntil(
+ () => held.requested('binary-archive') > 0,
+ 30_000,
+ 'the agent archive download to start',
+ );
+
+ await expect
+ .poll(() => manager.getInfo(info.threadId)?.status, { timeout: 10_000 })
+ .toBe('installing');
+
+ held.release('binary-archive');
+ await expect
+ .poll(() => manager.getInfo(info.threadId)?.status, { timeout: 30_000 })
+ .toBe('ready');
+ } finally {
+ await manager.destroy();
+ }
+ });
+ }, 90_000);
+
+ test('an npx reopen after a completed install never reports installing', async () => {
+ await withHeldInstallRegistry(async (held) => {
+ const { agentId, manager } = heldInstallManager(held, {
+ npx: { package: held.npmPackage },
+ });
+ try {
+ const first = await manager.createThread({ agent: { source: 'registry', id: agentId } });
+ held.release('npm-dependency');
+ await expect
+ .poll(() => manager.getInfo(first.threadId)?.status, { timeout: 30_000 })
+ .toBe('ready');
+ expect(held.requested('npm-dependency')).toBe(1);
+
+ const second = await manager.createThread({
+ agent: { source: 'registry', id: agentId },
+ });
+ await expect
+ .poll(() => manager.getInfo(second.threadId)?.status, { timeout: 30_000 })
+ .toBe('ready');
+
+ expect(held.requested('npm-dependency')).toBe(1);
+ expect(await statusesOf(manager, second.threadId)).not.toContain('installing');
+ } finally {
+ await manager.destroy();
+ }
+ });
+ }, 90_000);
+
+ test('a reopen of an installed binary agent never reports installing', async () => {
+ await withHeldInstallRegistry(async (held) => {
+ const { agentId, manager } = heldInstallManager(held, binaryDistribution(held));
+ try {
+ const first = await manager.createThread({ agent: { source: 'registry', id: agentId } });
+ held.release('binary-archive');
+ await expect
+ .poll(() => manager.getInfo(first.threadId)?.status, { timeout: 30_000 })
+ .toBe('ready');
+ expect(held.requested('binary-archive')).toBe(1);
+
+ const second = await manager.createThread({
+ agent: { source: 'registry', id: agentId },
+ });
+ await expect
+ .poll(() => manager.getInfo(second.threadId)?.status, { timeout: 30_000 })
+ .toBe('ready');
+
+ expect(held.requested('binary-archive')).toBe(1);
+ expect(await statusesOf(manager, second.threadId)).not.toContain('installing');
+ } finally {
+ await manager.destroy();
+ }
+ });
+ }, 90_000);
+
+ test('a uvx reopen after a completed install never reports installing', async (ctx) => {
+ ctx.skip(
+ !hasUvx || !findExecutable('python3', agentSpawnPath(), executableFacts),
+ 'uvx and python3 must be available to install a real Python agent',
+ );
+ await withHeldInstallRegistry(async (held) => {
+ const { agentId, manager } = heldInstallManager(held, {
+ uvx: { package: held.uvxPackage },
+ });
+ try {
+ const first = await manager.createThread({ agent: { source: 'registry', id: agentId } });
+ held.release('wheel');
+ await expect
+ .poll(() => manager.getInfo(first.threadId)?.status, { timeout: 30_000 })
+ .toBe('ready');
+
+ const second = await manager.createThread({
+ agent: { source: 'registry', id: agentId },
+ });
+ await expect
+ .poll(() => manager.getInfo(second.threadId)?.status, { timeout: 30_000 })
+ .toBe('ready');
+
+ expect(await statusesOf(manager, second.threadId)).not.toContain('installing');
+ } finally {
+ await manager.destroy();
+ }
+ });
+ }, 90_000);
+
+ test.for(['warm', 'cold'] as const)(
+ 'a stale npx entry is reinstalled under installing with a %s acquisition memo',
+ { timeout: 90_000 },
+ async (memo) => {
+ await withHeldInstallRegistry(async (held) => {
+ await expectNpxLeavingStaleEntries();
+ const { agentId, manager } = heldInstallManager(held, {
+ npx: { package: held.npmPackage },
+ });
+ try {
+ const first = await manager.createThread({
+ agent: { source: 'registry', id: agentId },
+ });
+ held.release('npm-dependency');
+ await expect
+ .poll(() => manager.getInfo(first.threadId)?.status, { timeout: 30_000 })
+ .toBe('ready');
+ if (memo === 'cold') resetAcquisitionCache();
+ leaveStaleNpxEntry(held);
+ held.rearm('npm-dependency');
+
+ const second = await manager.createThread({
+ agent: { source: 'registry', id: agentId },
+ });
+ await waitUntil(
+ () => held.requested('npm-dependency') === 2,
+ 30_000,
+ 'npx to reinstall the package into the cleared entry',
+ );
+
+ await expect
+ .poll(() => manager.getInfo(second.threadId)?.status, { timeout: 10_000 })
+ .toBe('installing');
+
+ held.release('npm-dependency');
+ await expect
+ .poll(() => manager.getInfo(second.threadId)?.status, { timeout: 30_000 })
+ .toBe('ready');
+ } finally {
+ await manager.destroy();
+ }
+ });
+ },
+ );
+
+ test('a second thread joining an in-flight version probe reports installing', async () => {
+ await withHeldInstallRegistry(async (held) => {
+ held.rearm('npm-package');
+ const { agentId, manager } = heldInstallManager(held, {
+ npx: { package: held.npmPackage },
+ });
+ try {
+ const first = await manager.createThread({ agent: { source: 'registry', id: agentId } });
+ await waitUntil(
+ () => held.requested('npm-package') === 1,
+ 30_000,
+ "the first thread's version probe to fetch the package",
+ );
+ expect(manager.getInfo(first.threadId)?.status).toBe('installing');
+ const second = await manager.createThread({
+ agent: { source: 'registry', id: agentId },
+ });
+ const joinedStatus = await statusOnceReached(
+ () => manager.getInfo(second.threadId)?.status,
+ 'installing',
+ 10_000,
+ );
+
+ held.release('npm-package');
+ held.release('npm-dependency');
+ await expect
+ .poll(() => manager.getInfo(first.threadId)?.status, { timeout: 30_000 })
+ .toBe('ready');
+ await expect
+ .poll(() => manager.getInfo(second.threadId)?.status, { timeout: 30_000 })
+ .toBe('ready');
+ expect(joinedStatus).toBe('installing');
+ } finally {
+ await manager.destroy();
+ }
+ });
+ }, 90_000);
+
+ test('a failed npx install goes from installing straight to error', async () => {
+ await withHeldInstallRegistry(async (held) => {
+ held.answerNotFound('npm-dependency');
+ const { agentId, manager } = heldInstallManager(held, {
+ npx: { package: held.npmPackage },
+ });
+ try {
+ const info = await manager.createThread({ agent: { source: 'registry', id: agentId } });
+ await waitUntil(
+ () => ['error', 'exited'].includes(manager.getInfo(info.threadId)?.status ?? ''),
+ 30_000,
+ 'the failed npx install to settle',
+ );
+ expect(held.requested('npm-dependency')).toBeGreaterThan(0);
+
+ const events: ThreadEvent[] = [];
+ await manager.subscribe(info.threadId, 0, (frame) => {
+ if (frame.op === 'event') events.push(frame.event);
+ else if (frame.op === 'events') events.push(...frame.events);
+ });
+ const statuses = events.flatMap((event) =>
+ event.kind === 'status' ? [event.status] : [],
+ );
+ expect(statuses).toEqual(['spawning', 'installing', 'error']);
+ expect(
+ events.filter((event) => event.kind === 'status' && event.status === 'error').at(-1),
+ ).toMatchObject({
+ failure: { reason: 'connect', agentMessage: expect.stringContaining(held.npmPackage) },
+ });
+ } finally {
+ await manager.destroy();
+ }
+ });
+ }, 90_000);
+
+ test('a dependency the release-date policy refuses during the npx install reports that policy', async () => {
+ await withHeldInstallRegistry(
+ async (held) => {
+ writeFileSync(join(held.home, '.npmrc'), 'before=2025-01-01T00:00:00Z\n');
+ const { agentId, manager } = heldInstallManager(held, {
+ npx: { package: held.npmPackage },
+ });
+ try {
+ const info = await manager.createThread({
+ agent: { source: 'registry', id: agentId },
+ });
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.status === 'error',
+ 30_000,
+ 'the refused npx install to settle',
+ );
+
+ const events: ThreadEvent[] = [];
+ await manager.subscribe(info.threadId, 0, (frame) => {
+ if (frame.op === 'event') events.push(frame.event);
+ else if (frame.op === 'events') events.push(...frame.events);
+ });
+ expect(
+ events.flatMap((event) => (event.kind === 'status' ? [event.status] : [])),
+ ).toEqual(['spawning', 'installing', 'error']);
+ expect(
+ events.filter((event) => event.kind === 'status' && event.status === 'error').at(-1),
+ ).toMatchObject({
+ failure: {
+ reason: 'connect',
+ agentMessage: expect.stringContaining("package manager's release-date policy"),
+ },
+ });
+ expect(held.requested('npm-dependency')).toBe(0);
+ } finally {
+ await manager.destroy();
+ }
+ },
+ { dependencyPublished: '2030-01-01T00:00:00.000Z' },
+ );
+ }, 90_000);
+ },
+);
+
const NPX_ENTRY_HASH = '4142609e2aa780f6';
const NPX_RELAUNCH_LOG = '[acp-threads] cleared a stale npx cache entry; relaunching the agent';
const NPX_JOIN_LOG =
diff --git a/packages/server/src/acp/thread-manager.ts b/packages/server/src/acp/thread-manager.ts
index 2a998f259..e16746ea8 100644
--- a/packages/server/src/acp/thread-manager.ts
+++ b/packages/server/src/acp/thread-manager.ts
@@ -116,6 +116,7 @@ import {
incompatibleManagedRuntimeHint,
incompatibleNodeHint,
isPathQualified,
+ type NpxCacheEntry,
packageAcquisitionFailure,
preflightLaunch,
probeInterpreterHealth,
@@ -838,29 +839,42 @@ export class AcpThreadManager {
} 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,
- undefined,
- (candidate) => this.ensureLaunchable(record, candidate, consentBudgetMs),
- {
- reacquire: acquisition === 'reacquire',
- onProbeStart: () => this.emitStatus(record, 'installing'),
- onResolved: ({ acquired, outcome, source, elapsedMs }) =>
- this.opts.log.info(
- {
- threadId: record.info.threadId,
- agentId: record.info.agent.id,
- package: acquired,
- outcome,
- source,
- elapsedMs,
- },
- '[acp-threads] agent package acquired',
- ),
- },
- );
+ try {
+ launch = await resolveRegistryLaunch(
+ manifest,
+ registryPlatformKey(),
+ this.opts.log,
+ undefined,
+ (candidate) => this.ensureLaunchable(record, candidate, consentBudgetMs),
+ {
+ reacquire: acquisition === 'reacquire',
+ install: true,
+ onAcquiring: () => this.emitStatus(record, 'installing'),
+ onResolved: ({ acquired, outcome, source, elapsedMs }) =>
+ this.opts.log.info(
+ {
+ threadId: record.info.threadId,
+ agentId: record.info.agent.id,
+ package: acquired,
+ outcome,
+ source,
+ elapsedMs,
+ },
+ '[acp-threads] agent package acquired',
+ ),
+ },
+ );
+ } catch (err) {
+ if (
+ err instanceof AgentLaunchError &&
+ err.npxCacheEntry !== undefined &&
+ npxCacheRecovery === 'available' &&
+ (await this.clearStaleNpxCacheEntry(record, err.npxCacheEntry))
+ ) {
+ return this.connectAgent(record, custom, 'reacquire', consentBudgetMs, 'spent');
+ }
+ throw err;
+ }
}
if (launch === null || record.closed) return null;
@@ -1143,7 +1157,7 @@ export class AcpThreadManager {
: null;
if (staleEntry !== null && (await this.clearStaleNpxCacheEntry(record, staleEntry))) {
launchSuperseded = true;
- return this.connectAgent(record, custom, acquisition, consentBudgetMs, 'spent');
+ return this.connectAgent(record, custom, 'reacquire', consentBudgetMs, 'spent');
}
throw new ThreadOpError('spawn-failed', `initialize failed: ${agentErrorMessage(err)}`);
} finally {
@@ -1158,7 +1172,10 @@ export class AcpThreadManager {
return { conn, init, launch };
}
- private async clearStaleNpxCacheEntry(record: ThreadRecord, entryDir: string): Promise<boolean> {
+ private async clearStaleNpxCacheEntry(
+ record: ThreadRecord,
+ entryDir: NpxCacheEntry,
+ ): Promise<boolean> {
const logContext = {
threadId: record.info.threadId,
agentId: record.info.agent.id,