Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Log failed agent launches, clear stale npx cache (PRD-8025, PRD-8554) (#4906)
Abraham3f33b623a5c5
diff --git a/.changeset/prd-8025-8554-launch-failure-diagnostics.md b/.changeset/prd-8025-8554-launch-failure-diagnostics.mdnew file mode 100644index 000000000..692fce030--- /dev/null+++ b/.changeset/prd-8025-8554-launch-failure-diagnostics.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Bug reports now carry the output of in-app agent launches that failed, and a launch that fails on a stale npx cache entry clears the entry and retries once on its own.diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdxindex 35b5be601..2a73a5e03 100644--- a/docs/content/features/editor.mdx+++ b/docs/content/features/editor.mdx@@ -140,6 +140,8 @@ To apply it sooner, stop that server yourself. [`ok stop`](/docs/reference/cli#mRetrying a conversation that failed to start re-resolves that conversation's own agent right away and leaves every other conversation on the adapter it already has. Custom agent commands keep their existing behavior.+When a catalog-managed agent that OpenKnowledge launches through npx fails because npm reports that the entry in its npx cache is missing its `package.json`, OpenKnowledge deletes that one `_npx/<hash>` directory from npm's cache and relaunches the adapter once before reporting a failure. Custom agent commands and uv-managed adapters are never retried this way. Every launch that does fail, whatever its kind, is recorded with the last lines the adapter printed in [`.ok/local/acp-launch-failures.log`](../reference/what-open-knowledge-writes.mdx#while-a-project-is-open), which bug reports include.+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 selectiondiff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdxindex 505de2591..72f71833c 100644--- a/docs/content/reference/what-open-knowledge-writes.mdx+++ b/docs/content/reference/what-open-knowledge-writes.mdx@@ -121,6 +121,7 @@ The app runs a collaboration server for the open project. It writes runtime stat| `.ok/local/conflicts.json` | Every conflict the app is holding a document for, including conflicts that involve no remote. A row for OpenKnowledge's own merge of the editor against disk embeds up to three full copies of the document body, so **keep this file while any conflict is open**. Deleting it loses those copies. If the app cannot read the file, it renames it to `conflicts.json.corrupt-<timestamp>` and leaves it in place | In-project, gitignored || `.ok/local/stale-external-writes.json` | Recovery snapshot for a rejected stale external save. It can hold the acknowledged, rejected, and retained document text. Protection expires after 30 minutes, but an unresolved snapshot stays until you resolve the conflict | In-project, gitignored || `.ok/local/state.json`, `.ok/local/last-spawn-error.log` | State-schema manifest and the last detached-spawn error log | In-project, gitignored |+| `.ok/local/acp-launch-failures.log` | In-app agent launches that failed: when, which agent, why, and the last lines the agent printed before it exited, so a bug report shows the cause without a re-run. Starts over once it passes 256 KB | In-project, gitignored || `.ok/local/last-server-exit.json` | Why the collaboration server the app started last exited — a timestamp, its process id, the exit code, the signal that ended it, and which part of the app was watching. One record, overwritten on each exit; a server the app only attached to, or one you started yourself with `ok start`, leaves none. No document content or paths | In-project, gitignored || `.ok/local/last-server-crash.json` | The collaboration server's own account of a crash it did not survive — a timestamp, the error message and stack, its process id, and how long it had been running. Written by the server itself, so it covers `ok start` too. Holds the most recent crash only | In-project, gitignored || `.ok/local/telemetry/spans-*.jsonl` | Local diagnostic spans, rotated at ~50 MB | In-project, gitignored |@@ -151,6 +152,7 @@ On each launch and project open, the app also runs **repair sweeps**: it rewrite| `~/.agents/skills/<name>/`, `~/.claude/skills/<name>/`, … | Your global-scope skills, versioned in place in your home editor dirs (kept by `ok uninstall` unless `--purge-content`) | No || `~/.ok/local/installed-skills.json`, `~/.ok/local/skill-move-retained.json` | The same skill-install markers and unfinished-scope-move bookkeeping the tables above list under a project's `.ok/local/`, written under your home directory for Global-scope skills instead | No || `~/.ok/stats.jsonl` | Local "open with AI" handoff stats — local-only, no phone-home | No |+| `_npx/<hash>/` under npm's cache (`~/.npm` unless your `npm_config_cache` says otherwise) | Deleted, not written: when a catalog-managed in-app agent that OpenKnowledge launched through npx fails because npm reports that entry is missing its `package.json`, OpenKnowledge removes that one directory so npx rebuilds it on the single relaunch that follows. Never for custom agent commands or uv-managed adapters | No || `~/.ok/themes/` | Your saved color themes from the [Themes plugin](../plugins/themes.mdx), one Tinted Theming base16 YAML file per theme, written when you create or edit a theme | No || `~/.ok/mcp-status.json` | First-launch MCP consent record | No || `~/.ok/logs/`, `~/.ok/bug-reports/` | Desktop and CLI logs, and bug-report bundles from `ok bug-report` and the app's **Help → Report a bug…** dialog (`ok diagnose bundle` writes into the project, under `.ok/local/diagnostics/`). Each report from the dialog also gets a small YAML record holding its send state and a secret-redacted copy of the note you wrote, so report history can still show what a report was about. The zip is deleted once the report is sent; the record is kept, and both go when you delete the report from report history. If that record ever can't be read back, OpenKnowledge leaves it exactly as it is rather than overwriting your note, and writes a second tiny `.sent.yaml` file beside it when a report does send, so history still shows it as sent instead of offering to send it again | No |@@ -247,6 +249,7 @@ On Windows, Claude Desktop and OpenCode configs live under `%APPDATA%\Claude\` a| `.ok/local/conflicts.json` | Every conflict the app is holding a document for, including conflicts that involve no remote. A row for OpenKnowledge's own merge of the editor against disk embeds up to three full copies of the document body, so **keep this file while any conflict is open**. Deleting it loses those copies. If the app cannot read the file, it renames it to `conflicts.json.corrupt-<timestamp>` and leaves it in place | In-project, gitignored || `.ok/local/stale-external-writes.json` | Recovery snapshot for a rejected stale external save. It can hold the acknowledged, rejected, and retained document text. Protection expires after 30 minutes, but an unresolved snapshot stays until you resolve the conflict | In-project, gitignored || `.ok/local/state.json`, `.ok/local/last-spawn-error.log` | State-schema manifest and the last detached-spawn error log | In-project, gitignored |+| `.ok/local/acp-launch-failures.log` | In-app agent launches that failed: when, which agent, why, and the last lines the agent printed before it exited, so a bug report shows the cause without a re-run. Starts over once it passes 256 KB | In-project, gitignored || `.ok/local/last-server-crash.json` | The server's own account of a crash it did not survive — a timestamp, the error message and stack, its process id, and how long it had been running. Holds the most recent crash only | In-project, gitignored || `.ok/local/telemetry/spans-*.jsonl` | Local diagnostic spans, rotated at ~50 MB | In-project, gitignored || `.ok/local/logs/server-*.jsonl` | Local server logs, rotated at ~25 MB | In-project, gitignored |@@ -285,6 +288,7 @@ Projects initialized by an older CLI may lack the `local/` rule in `.ok/.gitigno| `~/.agents/skills/<name>/`, `~/.claude/skills/<name>/`, … | Your global-scope skills, versioned in place in your home editor dirs (kept by `ok uninstall` unless `--purge-content`) | No || `~/.ok/local/installed-skills.json`, `~/.ok/local/skill-move-retained.json` | The same skill-install markers and unfinished-scope-move bookkeeping the tables above list under a project's `.ok/local/`, written under your home directory for Global-scope skills instead | No || `~/.ok/stats.jsonl` | Local "open with AI" handoff stats — local-only, no phone-home | No |+| `_npx/<hash>/` under npm's cache (`~/.npm` unless your `npm_config_cache` says otherwise) | Deleted, not written: when a catalog-managed in-app agent that OpenKnowledge launched through npx fails because npm reports that entry is missing its `package.json`, OpenKnowledge removes that one directory so npx rebuilds it on the single relaunch that follows. Never for custom agent commands or uv-managed adapters | No || `~/.ok/themes/` | Your saved color themes from the [Themes plugin](../plugins/themes.mdx), one Tinted Theming base16 YAML file per theme, written when you create or edit a theme | No || `~/.ok/logs/` | CLI logs (`cli.<date>.log`), size- and age-capped | No || `~/.ok/bug-reports/` | Bug-report bundles from `ok bug-report` — the desktop app's **Help → Report a bug…** dialog writes here too (`ok diagnose bundle` writes into the project, under `.ok/local/diagnostics/`). A report filed from the dialog also leaves a small YAML record beside its bundle, holding the report's send state and a secret-redacted copy of the note you wrote so report history can name it. That record outlives the bundle: the zip is deleted once the report is sent, and the record is kept until you delete the report from report history. If the record ever can't be read back, OpenKnowledge leaves it exactly as it is rather than overwriting your note, and writes a second tiny `.sent.yaml` file beside it when a report does send. That marker holds only the send time and the report's reference, never your note, and it is removed with the rest of the report | No |diff --git a/packages/cli/src/commands/bug-report-bundle.test.ts b/packages/cli/src/commands/bug-report-bundle.test.tsindex af318f5df..f7adc3bb6 100644--- a/packages/cli/src/commands/bug-report-bundle.test.ts+++ b/packages/cli/src/commands/bug-report-bundle.test.ts@@ -92,6 +92,11 @@ describe('collectStandardBundle — project bundle', () => {const projectDir = makeProjectDir();writeAt(projectDir, '.ok/local/server.lock', '{"pid":1234}\n');writeAt(projectDir, '.ok/local/last-spawn-error.log', 'spawn failed\n');+ writeAt(+ projectDir,+ '.ok/local/acp-launch-failures.log',+ '=== acp launch failure 2026-09-23T12:00:00.000Z thread=t agent=codex-acp source=registry reason=connect ===\n',+ );writeAt(projectDir, '.ok/local/logs/server-current.jsonl', '{"level":30}\n');const outputPath = join(makeTmpDir(), 'report.zip');@@ -108,6 +113,7 @@ describe('collectStandardBundle — project bundle', () => {const entries = listZipEntries(zipPath);expect(entries).toContain('lockdir/server.lock');expect(entries).toContain('lockdir/last-spawn-error.log');+ expect(entries).toContain('lockdir/acp-launch-failures.log');expect(entries).toContain('local-logs/server-current.jsonl');expect(entries).toContain('sysinfo.json');expect(entries).toContain('MANIFEST.json');diff --git a/packages/cli/src/commands/bug-report-bundle.ts b/packages/cli/src/commands/bug-report-bundle.tsindex 4339fd9f3..711e0364f 100644--- a/packages/cli/src/commands/bug-report-bundle.ts+++ b/packages/cli/src/commands/bug-report-bundle.ts@@ -4,6 +4,7 @@ import { createWriteStream, existsSync, mkdirSync, readdirSync, readFileSync } fimport { freemem, homedir, type as osType, platform, release, totalmem, uptime } from 'node:os';import { basename, dirname, join, resolve } from 'node:path';import {+ ACP_LAUNCH_FAILURE_LOG,type BundleManifest,type BundleRedaction,REPORT_SENT_MARKER_SUFFIX,@@ -244,7 +245,12 @@ function collectLockDir(cwd: string): { files: string[] } {const lockDir = join(cwd, '.ok', 'local');if (!existsSync(lockDir)) return { files: [] };- const candidates = ['server.lock', 'last-spawn-error.log', SERVER_CRASH_LOG];+ const candidates = [+ 'server.lock',+ 'last-spawn-error.log',+ SERVER_CRASH_LOG,+ ACP_LAUNCH_FAILURE_LOG,+ ];const found = candidates.map((f) => join(lockDir, f)).filter((f) => existsSync(f));return { files: found };diff --git a/packages/cli/src/diagnose/bundle.test.ts b/packages/cli/src/diagnose/bundle.test.tsindex da077b534..569df4d23 100644--- a/packages/cli/src/diagnose/bundle.test.ts+++ b/packages/cli/src/diagnose/bundle.test.ts@@ -155,6 +155,11 @@ describe('collectBundle — file inventory', () => {writeAt(projectDir, '.ok/local/telemetry/spans-current.jsonl', realSpans);writeAt(projectDir, '.ok/local/logs/server-current.jsonl', '{"level":30,"msg":"x"}\n');writeAt(projectDir, '.ok/local/server.lock', JSON.stringify({ port: 6111 }));+ writeAt(+ projectDir,+ '.ok/local/acp-launch-failures.log',+ '=== acp launch failure 2026-09-23T12:00:00.000Z thread=t agent=codex-acp source=registry reason=connect ===\n',+ );writeAt(contentDir, '.ok/local/telemetry/spans-current.jsonl', '{"resourceSpans":["DECOY"]}\n');const collected = await collectBundle({@@ -167,6 +172,7 @@ describe('collectBundle — file inventory', () => {expect(paths).toContain('telemetry/spans-current.jsonl');expect(paths).toContain('logs/server-current.jsonl');expect(paths).toContain('state/server.lock');+ expect(paths).toContain('state/acp-launch-failures.log');const staged = readFileSync(join(collected.stagingDir, 'telemetry', 'spans-current.jsonl'),'utf-8',diff --git a/packages/cli/src/diagnose/bundle.ts b/packages/cli/src/diagnose/bundle.tsindex 99bed8635..58c388e5c 100644--- a/packages/cli/src/diagnose/bundle.ts+++ b/packages/cli/src/diagnose/bundle.ts@@ -16,6 +16,7 @@ import { arch as osArch, platform as osPlatform, tmpdir } from 'node:os';import { basename, dirname, join, relative, resolve, sep } from 'node:path';import type { BundleRedaction as SecretScrubEntry } from '@inkeep/open-knowledge-core';import {+ ACP_LAUNCH_FAILURE_LOG,REPORT_SIDECAR_BUNDLE_DIR,SERVER_CRASH_LOG,SERVER_EXIT_LOG,@@ -586,6 +587,11 @@ export async function collectBundle(opts: CollectBundleOpts): Promise<CollectedBjoin(stagingDir, 'state', SERVER_CRASH_LOG),);+ stageFileIfPresent(+ join(lockDir, ACP_LAUNCH_FAILURE_LOG),+ join(stagingDir, 'state', ACP_LAUNCH_FAILURE_LOG),+ );+const runtime = readRuntime();const desktop = readDesktopEnv();const language = readLanguage();diff --git a/packages/core/src/constants/lifecycle.ts b/packages/core/src/constants/lifecycle.tsindex 05bb3568a..1060ff7a8 100644--- a/packages/core/src/constants/lifecycle.ts+++ b/packages/core/src/constants/lifecycle.ts@@ -8,6 +8,8 @@ export const SPAWN_ERROR_LOG_MAX_BYTES = 256 * 1024;export const SPAWN_ATTEMPT_MARKER = '=== spawn attempt ';+export const ACP_LAUNCH_FAILURE_LOG = 'acp-launch-failures.log';+export function spawnErrorLogOpenMode(currentSizeBytes: number | undefined): 'a' | 'w' {if (currentSizeBytes === undefined) return 'a';return currentSizeBytes >= SPAWN_ERROR_LOG_MAX_BYTES ? 'w' : 'a';diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 7e01e3221..71cc7ed73 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -445,6 +445,7 @@ export {} from './constants/github.ts';export { isOrphanMode, ORPHAN_MODES, type OrphanMode } from './constants/graph.ts';export {+ ACP_LAUNCH_FAILURE_LOG,DEFAULT_SIGTERM_GRACE_MS,DEFAULT_SIGTERM_POLL_MS,formatSpawnAttemptHeader,diff --git a/packages/server/src/acp/diagnostics.ts b/packages/server/src/acp/diagnostics.tsindex 1952af2de..0d4ba5777 100644--- a/packages/server/src/acp/diagnostics.ts+++ b/packages/server/src/acp/diagnostics.ts@@ -6,7 +6,10 @@ export function redactDiagnostic(text: string): string {return scrubSecrets(text.replace(/(https?:\/\/)[^\s/]+@/gi, '$1***@'));}-export function createDiagnosticStderrCapture(consume: (line: string) => void): {+export function createDiagnosticStderrCapture(+ consume: (line: string) => void,+ inspectRaw?: (line: string) => void,+): {write: (chunk: string) => void;end: () => void;} {@@ -14,7 +17,10 @@ export function createDiagnosticStderrCapture(consume: (line: string) => void):let dropping = false;const flush = (): void => {if (dropping) consume('[oversized diagnostic line omitted]');- else if (pending !== '') consume(redactDiagnostic(pending));+ else if (pending !== '') {+ inspectRaw?.(pending);+ consume(redactDiagnostic(pending));+ }pending = '';dropping = false;};diff --git a/packages/server/src/acp/launch-failure-log.test.ts b/packages/server/src/acp/launch-failure-log.test.tsnew file mode 100644index 000000000..ae1a9f976--- /dev/null+++ b/packages/server/src/acp/launch-failure-log.test.ts@@ -0,0 +1,90 @@+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { SPAWN_ERROR_LOG_MAX_BYTES } from '@inkeep/open-knowledge-core';+import { afterEach, expect, test } from 'vitest';+import {+ type AcpLaunchFailureEntry,+ acpLaunchFailureLogPath,+ recordAcpLaunchFailure,+} from './launch-failure-log.ts';++const dirs: string[] = [];+function tmp(): string {+ const dir = mkdtempSync(join(tmpdir(), 'acp-launch-failure-log-'));+ dirs.push(dir);+ return dir;+}+afterEach(() => {+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++function entry(overrides: Partial<AcpLaunchFailureEntry> = {}): AcpLaunchFailureEntry {+ return {+ at: new Date('2026-09-23T12:00:00.000Z'),+ threadId: 'thread-1',+ agentId: 'codex-acp',+ agentSource: 'registry',+ reason: 'connect',+ detail: 'initialize failed: ACP connection closed',+ machineDetail:+ 'npm error code ENOENT\nnpm error path /Users/andrew/.npm/_npx/4142609e2aa780f6/package.json',+ ...overrides,+ };+}++test('appends one redacted entry per failure', async () => {+ const localDir = tmp();+ await recordAcpLaunchFailure(localDir, entry());+ await recordAcpLaunchFailure(+ localDir,+ entry({+ threadId: 'thread-2',+ agentId: 'house-agent',+ agentSource: 'custom',+ reason: 'session-setup',+ detail: 'session setup failed: boom',+ machineDetail: 'Authorization: Bearer fixture-token',+ }),+ );+ const text = readFileSync(acpLaunchFailureLogPath(localDir), 'utf8');+ expect(text).toContain(+ '=== acp launch failure 2026-09-23T12:00:00.000Z thread=thread-1 agent=codex-acp source=registry reason=connect ===\ninitialize failed: ACP connection closed\n--- stderr tail ---\nnpm error code ENOENT\nnpm error path ~/.npm/_npx/4142609e2aa780f6/package.json\n\n',+ );+ expect(text).not.toContain('/Users/andrew');+ expect(text).toContain(+ '=== acp launch failure 2026-09-23T12:00:00.000Z thread=thread-2 agent=house-agent source=custom reason=session-setup ===\nsession setup failed: boom\n--- stderr tail ---\n',+ );+ expect(text).not.toContain('fixture-token');+});++test('omits the stderr section when the failure carried no output', async () => {+ const localDir = tmp();+ await recordAcpLaunchFailure(localDir, entry({ machineDetail: undefined }));+ const text = readFileSync(acpLaunchFailureLogPath(localDir), 'utf8');+ expect(text).toBe(+ '=== acp launch failure 2026-09-23T12:00:00.000Z thread=thread-1 agent=codex-acp source=registry reason=connect ===\ninitialize failed: ACP connection closed\n\n',+ );+});++test('starts over once the log reaches its size bound', async () => {+ const localDir = tmp();+ writeFileSync(acpLaunchFailureLogPath(localDir), 'x'.repeat(SPAWN_ERROR_LOG_MAX_BYTES));+ await recordAcpLaunchFailure(localDir, entry());+ const text = readFileSync(acpLaunchFailureLogPath(localDir), 'utf8');+ expect(text.startsWith('=== acp launch failure')).toBe(true);+ expect(text).not.toContain('xxxx');+});++test('concurrent writes at the bound keep every entry', async () => {+ const localDir = tmp();+ writeFileSync(acpLaunchFailureLogPath(localDir), 'x'.repeat(SPAWN_ERROR_LOG_MAX_BYTES));+ await Promise.all([+ recordAcpLaunchFailure(localDir, entry()),+ recordAcpLaunchFailure(localDir, entry({ threadId: 'thread-2' })),+ ]);+ const text = readFileSync(acpLaunchFailureLogPath(localDir), 'utf8');+ expect(text).not.toContain('xxxx');+ expect(text).toContain('thread=thread-1');+ expect(text).toContain('thread=thread-2');+});diff --git a/packages/server/src/acp/launch-failure-log.ts b/packages/server/src/acp/launch-failure-log.tsnew file mode 100644index 000000000..e2e3e6dc4--- /dev/null+++ b/packages/server/src/acp/launch-failure-log.ts@@ -0,0 +1,68 @@+import { stat } from 'node:fs/promises';+import { join } from 'node:path';+import { ACP_LAUNCH_FAILURE_LOG, spawnErrorLogOpenMode } from '@inkeep/open-knowledge-core';+import type { ThreadFailureDetail } from '@inkeep/open-knowledge-core/acp/thread-protocol';+import { tracedAppendFile, tracedWriteFile } from '../fs-traced.ts';+import { redactDiagnostic } from './diagnostics.ts';++export type AcpLaunchFailureReason = Extract<+ ThreadFailureDetail['reason'],+ 'connect' | 'session-setup'+>;++export function isAcpLaunchFailureReason(+ reason: ThreadFailureDetail['reason'],+): reason is AcpLaunchFailureReason {+ return reason === 'connect' || reason === 'session-setup';+}++export interface AcpLaunchFailureEntry {+ at: Date;+ threadId: string;+ agentId: string;+ agentSource: 'registry' | 'custom';+ reason: AcpLaunchFailureReason;+ detail: string | undefined;+ machineDetail: string | undefined;+}++export function acpLaunchFailureLogPath(localDir: string): string {+ return join(localDir, ACP_LAUNCH_FAILURE_LOG);+}++function formatAcpLaunchFailureEntry(entry: AcpLaunchFailureEntry): string {+ const lines = [+ `=== acp launch failure ${entry.at.toISOString()} thread=${entry.threadId} agent=${entry.agentId} source=${entry.agentSource} reason=${entry.reason} ===`,+ ];+ if (entry.detail !== undefined && entry.detail !== '') lines.push(entry.detail);+ if (entry.machineDetail !== undefined && entry.machineDetail !== '') {+ lines.push('--- stderr tail ---', entry.machineDetail);+ }+ return redactDiagnostic(`${lines.join('\n')}\n\n`);+}++const pendingWrites = new Map<string, Promise<void>>();++export function recordAcpLaunchFailure(+ localDir: string,+ entry: AcpLaunchFailureEntry,+): Promise<void> {+ const path = acpLaunchFailureLogPath(localDir);+ const text = formatAcpLaunchFailureEntry(entry);+ const previous = pendingWrites.get(path) ?? Promise.resolve();+ const write = previous+ .catch(() => undefined)+ .then(async () => {+ const currentSize = await stat(path).then(+ (stats) => stats.size,+ () => undefined,+ );+ if (spawnErrorLogOpenMode(currentSize) === 'w') await tracedWriteFile(path, text);+ else await tracedAppendFile(path, text);+ });+ pendingWrites.set(path, write);+ void write.finally(() => {+ if (pendingWrites.get(path) === write) pendingWrites.delete(path);+ });+ return write;+}diff --git a/packages/server/src/acp/launch.test.ts b/packages/server/src/acp/launch.test.tsindex e78df2bd7..7d0252a59 100644--- a/packages/server/src/acp/launch.test.ts+++ b/packages/server/src/acp/launch.test.ts@@ -38,6 +38,7 @@ import {resolveRegistryLaunch,resolveWindowsCommand,spawnAcpAgent,+ staleNpxCacheEntry,terminateAgentTree,undeletableManagedRuntimeHint,unrepairableManagedRuntimeHint,@@ -1389,6 +1390,81 @@ describe('startup package policy classification', () => {});});+describe('staleNpxCacheEntry', () => {+ const npm11 = [+ 'npm error code ENOENT',+ 'npm error syscall open',+ 'npm error path /Users/andrew/.npm/_npx/4142609e2aa780f6/package.json',+ 'npm error errno -2',+ "npm error enoent Could not read package.json: Error: ENOENT: no such file or directory, open '/Users/andrew/.npm/_npx/4142609e2aa780f6/package.json'",+ 'npm error enoent This is related to npm not being able to find a file.',+ ].join('\n');++ test('names the npx cache entry npm could not read', () => {+ expect(staleNpxCacheEntry(npm11)).toBe('/Users/andrew/.npm/_npx/4142609e2aa780f6');+ });++ test('reads the older npm ERR! spelling and a Windows cache path', () => {+ const detail =+ 'npm ERR! code ENOENT\r\nnpm ERR! path C:\\Users\\Ann Smith\\AppData\\Local\\npm-cache\\_npx\\1a2b3c4d5e6f7a8b\\package.json\r\nnpm ERR! errno -4058\r\n';+ expect(staleNpxCacheEntry(detail)).toBe(+ 'C:\\Users\\Ann Smith\\AppData\\Local\\npm-cache\\_npx\\1a2b3c4d5e6f7a8b',+ );+ });++ test('falls back to the quoted path of the failed open', () => {+ const detail =+ "npm error code ENOENT\nnpm error enoent Could not read package.json: Error: ENOENT: no such file or directory, open '/home/ann/.cache/npm/_npx/deadbeef00/package.json'";+ expect(staleNpxCacheEntry(detail)).toBe('/home/ann/.cache/npm/_npx/deadbeef00');+ });++ test.each([+ [+ 'a failure other than ENOENT',+ 'npm error code E401\nnpm error path /Users/andrew/.npm/_npx/4142609e2aa780f6/package.json',+ ],+ [+ 'a path outside the npx cache',+ 'npm error code ENOENT\nnpm error path /Users/andrew/project/package.json',+ ],+ [+ 'a cache entry that is not a hash',+ 'npm error code ENOENT\nnpm error path /Users/andrew/.npm/_npx/not-a-hash/package.json',+ ],+ [+ 'a file other than package.json',+ 'npm error code ENOENT\nnpm error path /Users/andrew/.npm/_npx/4142609e2aa780f6/package-lock.json',+ ],+ [+ 'a relative path',+ 'npm error code ENOENT\nnpm error path .npm/_npx/4142609e2aa780f6/package.json',+ ],+ [+ 'a parent segment',+ 'npm error code ENOENT\nnpm error path /tmp/../_npx/4142609e2aa780f6/package.json',+ ],+ ])('ignores %s', (_label, detail) => {+ expect(staleNpxCacheEntry(detail)).toBeNull();+ });+});++test('diagnostic stderr hands each kept line to the raw inspector before redaction', () => {+ const raw: string[] = [];+ const lines: string[] = [];+ const capture = createDiagnosticStderrCapture(+ (line) => lines.push(line),+ (line) => raw.push(line),+ );+ capture.write('npm error path /Users/andrew/.npm/_npx/4142609e2aa780f6/package.json\n');+ capture.write(`https://alice:${'x'.repeat(16_000)}\n`);+ capture.end();+ expect(raw).toEqual(['npm error path /Users/andrew/.npm/_npx/4142609e2aa780f6/package.json']);+ expect(lines).toEqual([+ 'npm error path ~/.npm/_npx/4142609e2aa780f6/package.json',+ '[oversized diagnostic line omitted]',+ ]);+});+test.each(['npx', 'uvx'] as const)('%s startup policy diagnostics redact credentials', (kind) => {const signature =kind === 'npx'diff --git a/packages/server/src/acp/launch.ts b/packages/server/src/acp/launch.tsindex 3777d0e79..82e830c26 100644--- a/packages/server/src/acp/launch.ts+++ b/packages/server/src/acp/launch.ts@@ -255,6 +255,26 @@ export function packageAcquisitionFailure();}+const NPM_ENOENT_PATH_LINES: readonly RegExp[] = [+ /^npm (?:error|ERR!) path (.+?)\s*$/m,+ /ENOENT: no such file or directory, open '([^'\n]+)'/,+];++const NPX_CACHE_PACKAGE_JSON =+ /^((?:[A-Za-z]:)?[\\/](?:.*[\\/])?_npx[\\/][0-9a-f]{8,64})[\\/]package\.json$/i;++const PARENT_SEGMENT = /(?:^|[\\/])\.\.(?:[\\/]|$)/;++export function staleNpxCacheEntry(detail: string): string | 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;+ }+ return null;+}+async function npmCommand(launch: ResolvedLaunch): Promise<string | null> {let npx = launch.cmd;if (!isPathQualified(npx)) {diff --git a/packages/server/src/acp/thread-manager.integration.test.ts b/packages/server/src/acp/thread-manager.integration.test.tsindex d65be615f..332632af9 100644--- a/packages/server/src/acp/thread-manager.integration.test.ts+++ b/packages/server/src/acp/thread-manager.integration.test.ts@@ -11,6 +11,7 @@ import {import { tmpdir } from 'node:os';import { delimiter, dirname, join } from 'node:path';import { pathToFileURL } from 'node:url';+import { ACP_LAUNCH_FAILURE_LOG } from '@inkeep/open-knowledge-core';import type {ThreadEvent,ThreadInfo,@@ -6911,3 +6912,287 @@ describe('registry adapter acquisition probe scope across thread opens', () => {});}, 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 =+ '[acp-threads] npx cache entry was cleared by another launch moments ago; relaunching without clearing it again';++type NpxEnoentMode = 'while-entry-exists' | 'always' | 'stderr-after-stdout-eof';++function npmEnoentSource(entryDir: string, mode: NpxEnoentMode): string {+ const fail =+ mode === 'stderr-after-stdout-eof'+ ? `process.stdout.end(() => setTimeout(() => process.stderr.write(lines.join('\\n'), () => process.exit(254)), 150));`+ : `process.stderr.write(lines.join('\\n'), () => process.exit(254));`;+ return `+const entry = ${JSON.stringify(entryDir)};+if (${mode === 'always' ? 'true' : 'existsSync(entry)'}) {+ const lines = [+ 'npm error code ENOENT',+ 'npm error syscall open',+ 'npm error path ' + entry + '/package.json',+ 'npm error errno -2',+ "npm error enoent Could not read package.json: Error: ENOENT: no such file or directory, open '" + entry + "/package.json'",+ 'npm error enoent This is related to npm not being able to find a file.',+ '',+ ];+ ${fail}+} else {+ import(${JSON.stringify(pathToFileURL(EXAMPLE_AGENT).href)});+}+`;+}++function writeNpxCacheFailingAgentEntry(+ localDir: string,+ id: string,+ entryDir: string,+ mode: NpxEnoentMode,+): void {+ const agentPath = join(localDir, `${id}.mjs`);+ writeFileSync(+ agentPath,+ `import { existsSync } from 'node:fs';\n${npmEnoentSource(entryDir, mode)}`,+ );+ writeFileSync(+ join(localDir, 'acp-agents.json'),+ JSON.stringify([{ id, name: 'npx cache fixture', command: 'node', args: [agentPath] }]),+ );+}++function logCount(warn: ReturnType<typeof vi.spyOn>, message: string): number {+ return warn.mock.calls.filter((call) => call[1] === message).length;+}++async function withNpxLaunchFixture(+ mode: NpxEnoentMode,+ run: (fixture: {+ manager: AcpThreadManager;+ agentId: string;+ entryDir: string;+ localDir: string;+ warn: ReturnType<typeof vi.spyOn>;+ }) => Promise<void>,+): Promise<void> {+ await withAcquisitionHome(async (home) => {+ const localDir = tmp();+ const bin = join(home, 'bin');+ mkdirSync(bin);+ installNodeFixture(bin);+ writeRecordingNpm(bin, join(home, 'npm-probes.log'));+ const entryDir = join(home, 'npm-cache', '_npx', NPX_ENTRY_HASH);+ writeExecutable(+ join(bin, 'npx'),+ `const { existsSync } = require('node:fs');+if (process.argv.includes('--version')) {+ process.stdout.write('11.17.0\\n');+ process.exit(0);+}+${npmEnoentSource(entryDir, mode)}`,+ );+ const env = { PATH: [bin, process.env.PATH ?? ''].join(delimiter) };+ const 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 warn = vi.spyOn(log, 'warn');+ const manager = makeManager(home, localDir, { registry });+ await manager.init();+ try {+ await run({ manager, agentId: agent.id, entryDir, localDir, warn });+ } finally {+ await manager.destroy();+ }+ });+}++describe('launch failure diagnostics and npx cache recovery', () => {+ test('a stale npx cache entry is cleared and the launch retried once', async () => {+ await withNpxLaunchFixture(+ 'while-entry-exists',+ async ({ manager, agentId, entryDir, localDir, warn }) => {+ mkdirSync(entryDir, { recursive: true });+ const info = await manager.createThread({ agent: { source: 'registry', id: agentId } });+ await waitUntil(+ () => manager.getInfo(info.threadId)?.status === 'ready',+ 20_000,+ 'agent ready after relaunch',+ );+ expect(existsSync(entryDir)).toBe(false);+ expect(logCount(warn, NPX_RELAUNCH_LOG)).toBe(1);+ const statuses = await statusesOf(manager, info.threadId);+ expect(statuses).not.toContain('error');+ expect(statuses).not.toContain('exited');+ expect(existsSync(join(localDir, ACP_LAUNCH_FAILURE_LOG))).toBe(false);+ },+ );+ }, 40_000);++ test('the relaunch stays silent when the npm error lands after stdout closes', async () => {+ await withNpxLaunchFixture(+ 'stderr-after-stdout-eof',+ async ({ manager, agentId, entryDir, warn }) => {+ mkdirSync(entryDir, { recursive: true });+ const info = await manager.createThread({ agent: { source: 'registry', id: agentId } });+ await waitUntil(+ () => manager.getInfo(info.threadId)?.status === 'ready',+ 20_000,+ 'agent ready after relaunch',+ );+ expect(existsSync(entryDir)).toBe(false);+ expect(logCount(warn, NPX_RELAUNCH_LOG)).toBe(1);+ const statuses = await statusesOf(manager, info.threadId);+ expect(statuses).not.toContain('exited');+ expect(statuses).not.toContain('error');+ },+ );+ }, 40_000);++ test('a launch that keeps failing on the npx cache is reported after one retry', async () => {+ await withNpxLaunchFixture('always', async ({ manager, agentId, entryDir, localDir, warn }) => {+ mkdirSync(entryDir, { recursive: true });+ const info = await manager.createThread({ agent: { source: 'registry', id: agentId } });+ await waitUntil(+ () => manager.getInfo(info.threadId)?.status === 'error',+ 20_000,+ 'launch failure',+ );+ expect(existsSync(entryDir)).toBe(false);+ expect(logCount(warn, NPX_RELAUNCH_LOG)).toBe(1);+ const statuses = await statusesOf(manager, info.threadId);+ expect(statuses.filter((status) => status === 'error')).toHaveLength(1);+ const logPath = join(localDir, ACP_LAUNCH_FAILURE_LOG);+ await waitUntil(() => existsSync(logPath), 5_000, 'launch failure log');+ const logText = readFileSync(logPath, 'utf8');+ expect(logText.match(/=== acp launch failure /g)).toHaveLength(1);+ expect(logText).toContain(+ `thread=${info.threadId} agent=${agentId} source=registry reason=connect ===\ninitialize failed:`,+ );+ expect(logText).toContain('--- stderr tail ---');+ expect(logText).toContain('npm error code ENOENT');+ });+ }, 40_000);++ test.each(['package.json', 'concurrency.lock'])(+ 'an npx cache entry that still holds %s is left alone',+ async (file) => {+ await withNpxLaunchFixture(+ 'while-entry-exists',+ async ({ manager, agentId, entryDir, warn }) => {+ mkdirSync(entryDir, { recursive: true });+ writeFileSync(join(entryDir, file), '');+ const info = await manager.createThread({ agent: { source: 'registry', id: agentId } });+ await waitUntil(+ () => manager.getInfo(info.threadId)?.status === 'error',+ 20_000,+ 'launch failure',+ );+ expect(existsSync(join(entryDir, file))).toBe(true);+ expect(logCount(warn, NPX_RELAUNCH_LOG)).toBe(0);+ },+ );+ },+ 40_000,+ );++ test('a second launch does not delete an entry another launch just cleared', async () => {+ await withNpxLaunchFixture(+ 'while-entry-exists',+ async ({ manager, agentId, entryDir, warn }) => {+ mkdirSync(entryDir, { recursive: true });+ const first = await manager.createThread({ agent: { source: 'registry', id: agentId } });+ await waitUntil(+ () => manager.getInfo(first.threadId)?.status === 'ready',+ 20_000,+ 'first launch ready',+ );+ expect(existsSync(entryDir)).toBe(false);+ mkdirSync(entryDir, { recursive: true });+ const second = await manager.createThread({ agent: { source: 'registry', id: agentId } });+ await waitUntil(+ () => manager.getInfo(second.threadId)?.status === 'error',+ 20_000,+ 'second launch failure',+ );+ expect(existsSync(entryDir)).toBe(true);+ expect(logCount(warn, NPX_RELAUNCH_LOG)).toBe(1);+ expect(logCount(warn, NPX_JOIN_LOG)).toBe(1);+ },+ );+ }, 60_000);++ test('a custom agent that prints the npx cache signature is not retried', async () => {+ const localDir = tmp();+ const entryDir = join(tmp(), '_npx', NPX_ENTRY_HASH);+ mkdirSync(entryDir, { recursive: true });+ writeNpxCacheFailingAgentEntry(localDir, 'npx-cache', entryDir, 'while-entry-exists');+ const warn = vi.spyOn(log, 'warn');+ const manager = makeManager(tmp(), localDir);+ const info = await manager.createThread({ agent: { source: 'custom', id: 'npx-cache' } });+ await waitUntil(+ () => manager.getInfo(info.threadId)?.status === 'error',+ 20_000,+ 'launch failure',+ );+ expect(existsSync(entryDir)).toBe(true);+ expect(logCount(warn, NPX_RELAUNCH_LOG)).toBe(0);+ const logPath = join(localDir, ACP_LAUNCH_FAILURE_LOG);+ await waitUntil(() => existsSync(logPath), 5_000, 'launch failure log');+ const logText = readFileSync(logPath, 'utf8');+ expect(logText).toContain(+ `thread=${info.threadId} agent=npx-cache source=custom reason=connect ===`,+ );+ expect(logText).toContain('npm error code ENOENT');+ }, 30_000);++ test('a session setup failure is recorded with its reason', async () => {+ const localDir = tmp();+ writeSessionFailingAgentEntry(+ localDir,+ 'broken-agent',+ { code: -32603, message: 'Failed to initialize session services' },+ 'boot: loading services',+ );+ const manager = makeManager(tmp(), localDir);+ const info = await manager.createThread({ agent: { source: 'custom', id: 'broken-agent' } });+ await waitUntil(+ () => manager.getInfo(info.threadId)?.status === 'error',+ 15_000,+ 'session setup failure',+ );+ const logPath = join(localDir, ACP_LAUNCH_FAILURE_LOG);+ await waitUntil(() => existsSync(logPath), 5_000, 'launch failure log');+ const logText = readFileSync(logPath, 'utf8');+ expect(logText).toContain(+ `thread=${info.threadId} agent=broken-agent source=custom reason=session-setup ===\nsession setup failed: Failed to initialize session services`,+ );+ expect(logText).toContain('boot: loading services');+ }, 30_000);++ test('a prompt failure is not a launch failure and stays out of the log', async () => {+ const localDir = tmp();+ writeRequestingAgentEntry(+ localDir,+ 'prompt-failure',+ "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: 'prompt-failure' } });+ const statuses: StatusEvent[] = [];+ await manager.subscribe(info.threadId, 0, collectStatuses(statuses));+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'ready');+ manager.sendPrompt(info.threadId, 'edit');+ await waitUntil(+ () => statuses.some((event) => event.failure?.reason === 'prompt'),+ 5_000,+ 'prompt failure',+ );+ await new Promise((resolve) => setTimeout(resolve, 200));+ expect(existsSync(join(localDir, ACP_LAUNCH_FAILURE_LOG))).toBe(false);+ }, 30_000);+});diff --git a/packages/server/src/acp/thread-manager.ts b/packages/server/src/acp/thread-manager.tsindex 5c3e0bbfa..31275e94c 100644--- a/packages/server/src/acp/thread-manager.ts+++ b/packages/server/src/acp/thread-manager.ts@@ -5,7 +5,7 @@*/import type { ChildProcess } from 'node:child_process';-import { readFile, realpath } from 'node:fs/promises';+import { readFile, realpath, stat } from 'node:fs/promises';import { dirname, isAbsolute, join, normalize, relative, resolve, sep } from 'node:path';import { Readable, Writable } from 'node:stream';import { pathToFileURL } from 'node:url';@@ -75,6 +75,7 @@ import {ConcurrentOverwriteRefusedError,logConcurrentOverwriteRefusal,} from '../concurrent-overwrite-refused-error.ts';+import { tracedRm } from '../fs-traced.ts';import { resolveOnPath } from '../git-preflight.ts';import type { PinoLogger } from '../logger.ts';import { MCP_HOSTED_AGENT_HEADER } from '../mcp/agent-identity.ts';@@ -108,12 +109,14 @@ import {resolveRegistryLaunch,rewriteLaunchToManagedRuntime,spawnAcpAgent,+ staleNpxCacheEntry,terminateAgentTree,undeletableManagedRuntimeHint,unrepairableManagedRuntimeHint,withLoginShellPath,withPreferredLoginShellPath,} from './launch.ts';+import { isAcpLaunchFailureReason, recordAcpLaunchFailure } from './launch-failure-log.ts';import {getSharedLoginShellPathProvider,resetSharedLoginShellPathProvider,@@ -176,6 +179,10 @@ const CONCURRENT_OVERWRITE_REFUSED_CODE = -32009;type AcquisitionPolicy = 'reuse' | 'reacquire';+type NpxCacheRecovery = 'available' | 'spent';++const NPX_CACHE_CLEAR_COOLDOWN_MS = 5 * 60 * 1000;+export const ACP_ENVIRONMENT_NOTE ='Note on your environment: you are running inside the OpenKnowledge app, ' +'connected over ACP (Agent Client Protocol) — not inside your own terminal app. ' +@@ -462,6 +469,7 @@ export class AcpThreadManager {private readonly unwatchedTurnKillMs: number;private readonly turnStallMs: number;private readonly persistence: ThreadPersistenceStore;+ private readonly npxCacheClears = new Map<string, number>();private readonly resolveLoginShellPath: () => Promise<string | null>;private readonly healthyInterpreters = new Set<string>();private projectSkillStaging: Promise<string> | null = null;@@ -771,6 +779,7 @@ export class AcpThreadManager {custom: CustomAgentEntry | null,acquisition: AcquisitionPolicy = 'reuse',consentBudgetMs: number,+ npxCacheRecovery: NpxCacheRecovery = 'available',): Promise<{ conn: ClientConnection; init: InitializeResponse; launch: ResolvedLaunch } | null> {let launch: ResolvedLaunch | null;if (custom !== null) {@@ -852,14 +861,29 @@ export class AcpThreadManager {};record.drainStderr = drainStderr;let startupStderr = '';+ let rawStartupStderr = '';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();- });+ 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();+ },+ (rawLine) => {+ if (capturingStartup)+ rawStartupStderr = `${rawStartupStderr}${rawLine}\n`.slice(-ACQUISITION_DETAIL_MAX_CHARS);+ },+ );+ const launchKind = launch.kind;+ let launchSuperseded = false;+ const staleNpxCacheRecoveryPending = (): boolean =>+ launchKind === 'npx' &&+ capturingStartup &&+ npxCacheRecovery === 'available' &&+ staleNpxCacheEntry(rawStartupStderr) !== null;+ const launchStatusMuted = (): boolean => launchSuperseded || staleNpxCacheRecoveryPending();child.stderr?.setEncoding('utf8');child.stderr?.on('data', diagnosticCapture.write);@@ -876,6 +900,7 @@ export class AcpThreadManager {}});child.on('error', (err) => {+ if (launchStatusMuted()) return;this.emitStatus(record, 'error', `agent failed to start: ${err.message}`, {reason: 'connect',agentMessage: err.message,@@ -896,6 +921,7 @@ export class AcpThreadManager {.then((tail) => {if (record.terminals !== terminals) return;if (isThreadClosed(record)) return;+ if (launchStatusMuted()) return;if (record.info.status === 'error') {this.failPendingPermissions(record);return;@@ -1000,12 +1026,16 @@ export class AcpThreadManager {.connect(stream);record.conn = conn;conn.closed.then(- () => {+ async () => {+ await drainStderr();+ if (launchStatusMuted()) return;if (record.info.status !== 'exited' && record.info.status !== 'error') {this.emitStatus(record, 'exited', 'agent connection closed');}},- (err: unknown) => {+ async (err: unknown) => {+ await drainStderr();+ if (launchStatusMuted()) return;this.opts.log.warn({ err, threadId: record.info.threadId },'[acp-threads] agent connection closed with error',@@ -1041,10 +1071,19 @@ export class AcpThreadManager {const acquisitionFailure = packageAcquisitionFailure(launch, startupStderr, err);if (acquisitionFailure !== null) throw acquisitionFailure;}+ const staleEntry =+ launchKind === 'npx' && npxCacheRecovery === 'available'+ ? staleNpxCacheEntry(rawStartupStderr)+ : null;+ if (staleEntry !== null && (await this.clearStaleNpxCacheEntry(record, staleEntry))) {+ launchSuperseded = true;+ return this.connectAgent(record, custom, acquisition, consentBudgetMs, 'spent');+ }throw new ThreadOpError('spawn-failed', `initialize failed: ${agentErrorMessage(err)}`);} finally {capturingStartup = false;startupStderr = '';+ rawStartupStderr = '';}if (record.closed) return null;record.lastInit = init;@@ -1053,6 +1092,76 @@ export class AcpThreadManager {return { conn, init, launch };}+ private async clearStaleNpxCacheEntry(record: ThreadRecord, entryDir: string): Promise<boolean> {+ const logContext = {+ threadId: record.info.threadId,+ agentId: record.info.agent.id,+ npxCacheEntry: redactDiagnostic(entryDir),+ };+ const clearedAt = this.npxCacheClears.get(entryDir);+ if (clearedAt !== undefined && Date.now() - clearedAt < NPX_CACHE_CLEAR_COOLDOWN_MS) {+ this.opts.log.warn(+ logContext,+ '[acp-threads] npx cache entry was cleared by another launch moments ago; relaunching without clearing it again',+ );+ await this.discardFailedLaunch(record);+ return !isThreadClosed(record);+ }+ this.npxCacheClears.set(entryDir, Date.now());+ for (const file of ['package.json', 'concurrency.lock']) {+ const code = await stat(join(entryDir, file)).then(+ () => 'present',+ (err: NodeJS.ErrnoException) => err.code ?? 'unknown',+ );+ if (code !== 'ENOENT') {+ this.opts.log.warn(+ { ...logContext, file, code },+ '[acp-threads] leaving an npx cache entry alone',+ );+ return false;+ }+ }+ try {+ await tracedRm(entryDir, { recursive: true, force: true });+ } catch (err) {+ this.opts.log.warn(+ { err, ...logContext },+ '[acp-threads] stale npx cache entry could not be cleared',+ );+ return false;+ }+ this.opts.log.warn(+ logContext,+ '[acp-threads] cleared a stale npx cache entry; relaunching the agent',+ );+ await this.discardFailedLaunch(record);+ return !isThreadClosed(record);+ }++ private async discardFailedLaunch(t: ThreadRecord): Promise<void> {+ t.drainStderr = null;+ t.stderrTail = [];+ await this.stopAgentProcess(t, '[acp-threads] terminal cleanup before relaunch failed');+ }++ private async stopAgentProcess(t: ThreadRecord, terminalCleanupWarning: string): Promise<void> {+ const child = t.child;+ const conn = t.conn;+ const terminals = t.terminals;+ t.child = null;+ t.conn = null;+ t.terminals = null;+ try {+ conn?.close();+ } catch {}+ await terminals?.disposeAll().catch((err: unknown) => {+ this.opts.log.warn({ err, threadId: t.info.threadId }, terminalCleanupWarning);+ });+ if (child !== null) {+ await terminateAgentTree(child, { graceMs: KILL_GRACE_MS });+ }+ }+private async ensureLaunchable(record: ThreadRecord,launch: ResolvedLaunch,@@ -3314,6 +3423,22 @@ export class AcpThreadManager {'[acp-threads] thread failure status',);}+ if (status === 'error' && failure !== undefined && isAcpLaunchFailureReason(failure.reason)) {+ void recordAcpLaunchFailure(this.opts.localDir, {+ at: new Date(),+ threadId: t.info.threadId,+ agentId: t.info.agent.id,+ agentSource: t.info.agent.source,+ reason: failure.reason,+ detail,+ machineDetail: failure.machineDetail,+ }).catch((err: unknown) => {+ this.opts.log.warn(+ { err, threadId: t.info.threadId },+ '[acp-threads] launch failure log write failed',+ );+ });+ }this.appendEvent(t, {kind: 'status',status,@@ -3327,27 +3452,13 @@ 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;- t.child = null;- t.conn = null;t.lastInit = null;- t.terminals = null;t.sessionId = null;t.info.contextWindow = null;- try {- conn?.close();- } catch {}- await terminals?.disposeAll().catch((err: unknown) => {- this.opts.log.warn(- { err, threadId: t.info.threadId },- '[acp-threads] terminal cleanup on failed-agent teardown failed',- );- });- if (child !== null) {- await terminateAgentTree(child, { graceMs: KILL_GRACE_MS });- }+ await this.stopAgentProcess(+ t,+ '[acp-threads] terminal cleanup on failed-agent teardown failed',+ );}private emitInfo(t: ThreadRecord): void {