Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
PRD-8178 Enforce ACP Node runtime compatibility (#3715)
mike-inkeepa05318297b2f
diff --git a/.changeset/acp-node-runtime-compatibility.md b/.changeset/acp-node-runtime-compatibility.mdnew file mode 100644index 000000000..e63734bf2--- /dev/null+++ b/.changeset/acp-node-runtime-compatibility.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++In-app Claude, Codex, and other `npx`-distributed agents no longer start under an obsolete Node.js inherited by the desktop app. OpenKnowledge now requires Node.js 22 or newer for these adapters, retries with the compatible runtime from the user's login shell when available, and otherwise offers its private managed Node.js runtime before the agent starts.diff --git a/knip.config.ts b/knip.config.tsindex f9179f2d4..78162ec09 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -123,9 +123,7 @@ 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'],diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.tsindex dfd95ef49..d7a845280 100644--- a/packages/core/src/bridge/bind-frontmatter-doc.ts+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts@@ -1,4 +1,3 @@-import type * as Y from 'yjs';import type { Err, Ok, Result } from '../config/result.ts';import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.tsindex 8bfdb40cd..005627195 100644--- a/packages/core/src/bridge/bridge-invariant.ts+++ b/packages/core/src/bridge/bridge-invariant.ts@@ -1,4 +1,3 @@-import { fnv1aDigest } from './hash-util.ts';export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.tsindex 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/divergence-locate.ts b/packages/core/src/bridge/divergence-locate.tsindex d979f4b39..6b505314d 100644--- a/packages/core/src/bridge/divergence-locate.ts+++ b/packages/core/src/bridge/divergence-locate.ts@@ -1,4 +1,3 @@-import { findFirstDivergenceIndex } from './tolerance-telemetry.ts';export const BRIDGE_LINE_KINDS = [diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex 01ef76a9f..8fb428b90 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/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.tsindex 463e89595..9d9c244b0 100644--- a/packages/core/src/bridge/growth-detect.ts+++ b/packages/core/src/bridge/growth-detect.ts@@ -1,4 +1,3 @@-const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;diff --git a/packages/core/src/bridge/intraline-predicate.ts b/packages/core/src/bridge/intraline-predicate.tsindex 0939885bb..c43fdd7e7 100644--- a/packages/core/src/bridge/intraline-predicate.ts+++ b/packages/core/src/bridge/intraline-predicate.ts@@ -1,4 +1,3 @@-export function rawLineCounts(doc: string): Map<string, number> {const counts = new Map<string, number>();for (const line of doc.split('\n')) {diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.tsindex c0dc65705..251560a35 100644--- a/packages/core/src/bridge/merge-three-way.ts+++ b/packages/core/src/bridge/merge-three-way.ts@@ -65,7 +65,6 @@ export function tryLineLevelCombine(return { clean: true, merged };}-export type BridgeMergeContentLossSide = 'user' | 'agent';export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.tsindex dcc5b0690..01ac80099 100644--- a/packages/core/src/bridge/normalize.ts+++ b/packages/core/src/bridge/normalize.ts@@ -1,4 +1,3 @@-import { stripFrontmatter } from '../extensions/frontmatter.ts';import { bodyEdgeEmpties } from './doc-boundary-space.ts';diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.tsindex 0be5203e4..754dc5cc2 100644--- a/packages/core/src/bridge/pm-structural-equivalence.ts+++ b/packages/core/src/bridge/pm-structural-equivalence.ts@@ -32,7 +32,6 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };const BR_LITERAL_RE = /^<br\s*\/?>$/i;-interface DegradeEntry {readonly label: string;readonly severity: ToleranceClassSeverity;@@ -128,7 +127,6 @@ export interface ComparePmStructuralOptions {ignoreAttrs?: (attrKey: string) => boolean;}-/** Rebuild a node with `fn` applied to each child; identity when childless.* Shared by the degrade canonicalizers so none re-implements the walk. */function mapChildren(@@ -250,7 +248,6 @@ function applyDegrades(tree: PmStructuralNode): {return { normalized: current, fired };}-export function comparePmStructural(expected: PmStructuralNode,actual: PmStructuralNode,diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.tsindex dca644141..af20de1e2 100644--- a/packages/core/src/bridge/subsequence.ts+++ b/packages/core/src/bridge/subsequence.ts@@ -1,4 +1,3 @@-/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):* insertions in `haystack` are free; any dropped or substituted `needle` byte* fails. */diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.tsindex a363dfd54..83d47404a 100644--- a/packages/core/src/markdown/callout-transformer.ts+++ b/packages/core/src/markdown/callout-transformer.ts@@ -1,4 +1,3 @@-import type { Blockquote, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/code-fence.ts b/packages/core/src/markdown/code-fence.tsindex 4499dbc92..9807a7e82 100644--- a/packages/core/src/markdown/code-fence.ts+++ b/packages/core/src/markdown/code-fence.ts@@ -1,4 +1,3 @@-export function selectFenceChar(info: string): '`' | '~' {return info.includes('`') ? '~' : '`';}diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.tsindex 34704165b..7415c474a 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/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.tsindex b6299a948..ece5c02a1 100644--- a/packages/core/src/markdown/dedent-block-jsx-close.ts+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts@@ -1,4 +1,3 @@-import { findFencedRegions, isInsideFence } from './fence-regions.ts';const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.tsindex acd398aa6..54774764a 100644--- a/packages/core/src/markdown/details-accordion-promoter.ts+++ b/packages/core/src/markdown/details-accordion-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/div-align-promoter.ts b/packages/core/src/markdown/div-align-promoter.tsindex ba9b56384..43ecdc709 100644--- a/packages/core/src/markdown/div-align-promoter.ts+++ b/packages/core/src/markdown/div-align-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';import type { MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.tsindex 4513da9bb..6d3f3643e 100644--- a/packages/core/src/markdown/fence-regions.ts+++ b/packages/core/src/markdown/fence-regions.ts@@ -1,4 +1,3 @@-const FENCE_RE = /^(`{3,}|~{3,})/gm;export function findFencedRegions(src: string): Array<[number, number]> {diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.tsindex 6931623c7..00f5771ee 100644--- a/packages/core/src/markdown/fixtures/index.ts+++ b/packages/core/src/markdown/fixtures/index.ts@@ -1,4 +1,3 @@-import { readFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -9,7 +8,6 @@ function fixturePath(...segments: string[]): string {return resolve(FIXTURES_DIR, ...segments);}-interface GfmExample {section: string;markdown: string;@@ -19,7 +17,6 @@ export function loadGfmExamples(): GfmExample[] {return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];}-interface MdxCrashEntry {id: string;input: string;@@ -71,7 +68,6 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {) as LargeEmbedFixture[];}-export function loadPrd6955Before(): string {return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');}@@ -80,7 +76,6 @@ export function loadPrd6955CorruptedTriplicated(): string {return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');}-export interface NgPinnedCase {id: string;name: string;@@ -97,7 +92,6 @@ export function loadNgPinnedCases(): NgPinnedCase[] {) as NgPinnedCase[];}-export function loadLargeRealistic(): string {return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');}diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.tsindex daa3ef82b..8b1eb8519 100644--- a/packages/core/src/markdown/fixtures/perf/generate.ts+++ b/packages/core/src/markdown/fixtures/perf/generate.ts@@ -1,4 +1,3 @@-import { writeFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -11,7 +10,6 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;const SEED = 0xf1de1117;-function mulberry32(seed: number): () => number {let a = seed >>> 0;return () => {@@ -38,7 +36,6 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {return items[items.length - 1][0];}-const WORDS = ['lorem','ipsum',@@ -156,7 +153,6 @@ function mdxBlock(rand: () => number): string {return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;}-type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';const MIX: readonly [BlockKind, number][] = [@@ -195,7 +191,6 @@ function generateDocument(blockCount: number, seed: number): string {return `${blocks.join('\n\n')}\n`;}-function main(): void {for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {const doc = generateDocument(count, SEED);diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.tsindex 32c055c5b..420dc0fe5 100644--- a/packages/core/src/markdown/guard-flanking-matrix.ts+++ b/packages/core/src/markdown/guard-flanking-matrix.ts@@ -7,7 +7,6 @@ import {import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';-export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;export type FlankClass = 'whitespace' | 'punctuation' | 'other';diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.tsindex 283913255..2653473da 100644--- a/packages/core/src/markdown/handler-shadow-audit.ts+++ b/packages/core/src/markdown/handler-shadow-audit.ts@@ -1,4 +1,3 @@-export interface HandlerShadowWitness {input: string;expect: 'byte' | 'byte-and-reparse-type';diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.tsindex 5d1000cc4..da0a81d23 100644--- a/packages/core/src/markdown/highlight-promoter.ts+++ b/packages/core/src/markdown/highlight-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';import type { MdxJsxTextElement } from 'mdast-util-mdx';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.tsindex 9681c0056..787315157 100644--- a/packages/core/src/markdown/html-to-mdast.ts+++ b/packages/core/src/markdown/html-to-mdast.ts@@ -1,4 +1,3 @@-import type { Element as HastElement, Root as HastRoot } from 'hast';import type { List, Nodes as MdastNodes, Root as MdastRoot } from 'mdast';import rehypeParse from 'rehype-parse';@@ -129,8 +128,7 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRothrow new HtmlPayloadTooLargeError(html.length, maxBytes);}- const processor = unified()- .use(rehypeParse, { fragment: true });+ const processor = unified().use(rehypeParse, { fragment: true });for (const plugin of cleanupPlugins) {processor.use(plugin);diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.tsindex 994eb6917..706fa9afb 100644--- a/packages/core/src/markdown/image-promoter.ts+++ b/packages/core/src/markdown/image-promoter.ts@@ -1,4 +1,3 @@-import type { Image, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.tsindex ec1ac1b7e..779e27500 100644--- a/packages/core/src/markdown/index.ts+++ b/packages/core/src/markdown/index.ts@@ -1,4 +1,3 @@-import {type FromProseMirrorOptions,fromPmMark,@@ -207,7 +206,6 @@ export class MarkdownManager {}}-const registry = createRegistry();function destructureAttrs(@@ -256,7 +254,6 @@ function destructureAttrs(return result;}-function hasDirtyDescendant(node: PmNode): boolean {let found = false;node.descendants((child) => {@@ -279,7 +276,6 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChecreturn freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;}-function isEmptyMdastParagraph(node: MdastNodes): boolean {if (node.type !== 'paragraph') return false;const children = node.children ?? [];@@ -348,7 +344,6 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {return out;}-import {AUDIO_EXTENSIONS,FILE_ATTACHMENT_EXTENSIONS,@@ -601,7 +596,6 @@ function buildMdastToPmHandlers(}));}-if (m.emphasis) {handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({sourceDelimiter: node.data?.sourceDelimiter ?? '*',@@ -682,7 +676,6 @@ function buildMdastToPmHandlers(}));}-if (m.link) {const sourceLiteralMark = m.sourceLiteral;handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {@@ -980,7 +973,6 @@ function buildMdastToPmHandlers(};}-const blockUnknownHandler = (node: {type: string;position?: { start: { offset: number }; end: { offset: number } };@@ -1106,7 +1098,6 @@ function buildMdastToPmHandlers(return handlers as RemarkProseMirrorOptions['handlers'];}-function buildPmToMdastHandlers(schema: Schema,freshness: FreshnessCheckerHolder,diff --git a/packages/core/src/markdown/lint/applies-to.ts b/packages/core/src/markdown/lint/applies-to.tsindex b79e9aef7..fa0be9e86 100644--- a/packages/core/src/markdown/lint/applies-to.ts+++ b/packages/core/src/markdown/lint/applies-to.ts@@ -1,4 +1,3 @@-import picomatch from 'picomatch';import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.tsindex 94b34dee1..312c9c74b 100644--- a/packages/core/src/markdown/lint/config-files.ts+++ b/packages/core/src/markdown/lint/config-files.ts@@ -1,4 +1,3 @@-const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set(['.markdownlint.json','.markdownlint.jsonc',diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.tsindex fbbd309df..1a81aa524 100644--- a/packages/core/src/markdown/lint/config-schemas.ts+++ b/packages/core/src/markdown/lint/config-schemas.ts@@ -52,7 +52,6 @@ const fullPluginShape = Object.fromEntries(LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),) as z.ZodRawShape;-export const LinterConfigSchema = z.object({enabled: z.boolean(),plugins: z.object(fullPluginShape),diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.tsindex a51f2ffb0..d48eea5e4 100644--- a/packages/core/src/markdown/lint/default-config.ts+++ b/packages/core/src/markdown/lint/default-config.ts@@ -6,7 +6,6 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSettingMD013: false,};-export function resolveMarkdownlintConfig(rules: Record<string, MarkdownlintRuleSetting> | undefined,): Configuration {diff --git a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts b/packages/core/src/markdown/lint/frontmatter-schema-edit.tsindex 9c9542661..ef478e268 100644--- a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts+++ b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts@@ -1,4 +1,3 @@-import { CANONICAL_SCHEMA_DIALECT_URIS, DEFAULT_SCHEMA_DIALECT } from './frontmatter-validate.ts';export interface FrontmatterFieldConstraint {diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.tsindex b0e7833fd..5f953d667 100644--- a/packages/core/src/markdown/lint/frontmatter-validate.ts+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts@@ -1,4 +1,3 @@-import Ajv, { type ValidateFunction } from 'ajv';import Ajv2019 from 'ajv/dist/2019.js';import Ajv2020 from 'ajv/dist/2020.js';diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.tsindex ffd277a90..11b5abdfd 100644--- a/packages/core/src/markdown/lint/index.ts+++ b/packages/core/src/markdown/lint/index.ts@@ -1,4 +1,3 @@-import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';import type { LintDiagnostic } from './types.ts';diff --git a/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts b/packages/core/src/markdown/lint/okf-frontmatter/materialize.tsindex f438f1b16..7a5af097e 100644--- a/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts+++ b/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts@@ -1,4 +1,3 @@-import type { OkfRuleId } from '../okf-rule-meta.ts';import { fileNameFor, OKF_SCHEMA_DIR, okfSchemaPathFor } from './paths.ts';import { OKF_FRONTMATTER_REGISTRY } from './registry.ts';diff --git a/packages/core/src/markdown/lint/okf-frontmatter/paths.ts b/packages/core/src/markdown/lint/okf-frontmatter/paths.tsindex c290b6878..1ee913527 100644--- a/packages/core/src/markdown/lint/okf-frontmatter/paths.ts+++ b/packages/core/src/markdown/lint/okf-frontmatter/paths.ts@@ -1,4 +1,3 @@-import type { OkfRuleId } from '../okf-rule-meta.ts';export const OKF_SCHEMA_DIR = '.ok/okf';diff --git a/packages/core/src/markdown/lint/okf-frontmatter/registry.ts b/packages/core/src/markdown/lint/okf-frontmatter/registry.tsindex 53ecb619d..f325fbbb4 100644--- a/packages/core/src/markdown/lint/okf-frontmatter/registry.ts+++ b/packages/core/src/markdown/lint/okf-frontmatter/registry.ts@@ -1,4 +1,3 @@-import { compileAppliesTo } from '../applies-to.ts';import { validateFrontmatterSource } from '../frontmatter-validate.ts';import {diff --git a/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts b/packages/core/src/markdown/lint/okf-frontmatter/schemas.tsindex 89845d3d5..f1c37671b 100644--- a/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts+++ b/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts@@ -1,4 +1,3 @@-// file-level form is deliberate: the sibling `biome-ignore` must sit on the line// oxlint-disable unicorn/no-thenablediff --git a/packages/core/src/markdown/lint/okf-project/rules.ts b/packages/core/src/markdown/lint/okf-project/rules.tsindex 8b476332e..6d691ae2b 100644--- a/packages/core/src/markdown/lint/okf-project/rules.ts+++ b/packages/core/src/markdown/lint/okf-project/rules.ts@@ -1,4 +1,3 @@-import { SUPPORTED_DOC_EXTENSIONS } from '../../../constants/doc-extensions.ts';import { isOkfRuleEnabled, type OkfRuleId, type OkfRuleToggles } from '../okf-rule-meta.ts';diff --git a/packages/core/src/markdown/lint/okf-rule-meta.ts b/packages/core/src/markdown/lint/okf-rule-meta.tsindex 44913a9dc..4de50d79f 100644--- a/packages/core/src/markdown/lint/okf-rule-meta.ts+++ b/packages/core/src/markdown/lint/okf-rule-meta.ts@@ -1,4 +1,3 @@-export const OKF_RULE_IDS = ['no-wiki-links','log-shape',diff --git a/packages/core/src/markdown/lint/okf-rules.ts b/packages/core/src/markdown/lint/okf-rules.tsindex d0999b62e..1d5538421 100644--- a/packages/core/src/markdown/lint/okf-rules.ts+++ b/packages/core/src/markdown/lint/okf-rules.ts@@ -1,4 +1,3 @@-import { isOkfRuleEnabled, type OkfRuleId, type OkfRuleToggles } from './okf-rule-meta.ts';import type { OkfRule } from './okf-runner.ts';import { indexShape } from './rules/index-shape.ts';diff --git a/packages/core/src/markdown/lint/okf-runner.ts b/packages/core/src/markdown/lint/okf-runner.tsindex fabb08d6e..de130e3f4 100644--- a/packages/core/src/markdown/lint/okf-runner.ts+++ b/packages/core/src/markdown/lint/okf-runner.ts@@ -1,4 +1,3 @@-import type { Root } from 'mdast';import remarkFrontmatter from 'remark-frontmatter';import remarkGfm from 'remark-gfm';diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.tsindex 0a089990e..09c8450ee 100644--- a/packages/core/src/markdown/lint/plugins.ts+++ b/packages/core/src/markdown/lint/plugins.ts@@ -1,4 +1,3 @@-import { z } from 'zod';import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';import {@@ -24,7 +23,6 @@ import {type OkfSlice,} from './types.ts';-const MarkdownlintRuleSettingSchema = z.union([z.boolean(),z.enum(MARKDOWNLINT_RULE_SEVERITIES),diff --git a/packages/core/src/markdown/lint/rules/index-shape.ts b/packages/core/src/markdown/lint/rules/index-shape.tsindex fcbb1b56c..59fe9b87d 100644--- a/packages/core/src/markdown/lint/rules/index-shape.ts+++ b/packages/core/src/markdown/lint/rules/index-shape.ts@@ -1,4 +1,3 @@-import type { List, ListItem } from 'mdast';import { EXIT, visit } from 'unist-util-visit';import { defineScopedOkfRule } from '../okf-runner.ts';diff --git a/packages/core/src/markdown/lint/rules/log-shape.ts b/packages/core/src/markdown/lint/rules/log-shape.tsindex 431e4e9c8..e0159519f 100644--- a/packages/core/src/markdown/lint/rules/log-shape.ts+++ b/packages/core/src/markdown/lint/rules/log-shape.ts@@ -1,4 +1,3 @@-import type { Heading } from 'mdast';import { toString as headingText } from 'mdast-util-to-string';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/lint/rules/no-wiki-links.ts b/packages/core/src/markdown/lint/rules/no-wiki-links.tsindex f75a04d15..2123e977f 100644--- a/packages/core/src/markdown/lint/rules/no-wiki-links.ts+++ b/packages/core/src/markdown/lint/rules/no-wiki-links.ts@@ -1,4 +1,3 @@-import type { Point } from 'unist';import { visit } from 'unist-util-visit';import { defineOkfRule } from '../okf-runner.ts';diff --git a/packages/core/src/markdown/lint/rules/reserved-casing.ts b/packages/core/src/markdown/lint/rules/reserved-casing.tsindex c8b4d8f28..89ef3e4a9 100644--- a/packages/core/src/markdown/lint/rules/reserved-casing.ts+++ b/packages/core/src/markdown/lint/rules/reserved-casing.ts@@ -1,4 +1,3 @@-import { SUPPORTED_DOC_EXTENSIONS } from '../../../constants/doc-extensions.ts';import { defineOkfRule } from '../okf-runner.ts';diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.tsindex c04fa4de0..6836b962d 100644--- a/packages/core/src/markdown/lint/types.ts+++ b/packages/core/src/markdown/lint/types.ts@@ -1,4 +1,3 @@-import type { BrokenLinkReason } from '../../schemas/api/agent-write.ts';import type { OkfRuleId } from './okf-rule-meta.ts';@@ -113,7 +112,6 @@ export interface OkfSlice {generate?: { index?: boolean };}-interface RuleOptionSpecBase {key: string;description: string;diff --git a/packages/core/src/markdown/lint/validation-counts.ts b/packages/core/src/markdown/lint/validation-counts.tsindex 437cc539a..98238656e 100644--- a/packages/core/src/markdown/lint/validation-counts.ts+++ b/packages/core/src/markdown/lint/validation-counts.ts@@ -1,4 +1,3 @@-export interface ValidationSourceCounts {errorCount: number;warningCount: number;diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.tsindex bd79424c7..a5b511f25 100644--- a/packages/core/src/markdown/math-promoter.ts+++ b/packages/core/src/markdown/math-promoter.ts@@ -1,4 +1,3 @@-import type { Code, Root } from 'mdast';import type { Math as MdastMath } from 'mdast-util-math';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.tsindex 00fbc0035..ed89371d0 100644--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts@@ -1,4 +1,3 @@-import type { Comment, Element, ElementContent, Properties } from 'hast';import type { FootnoteDefinition, FootnoteReference } from 'mdast';import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.tsindex df788a80d..8ce2b2492 100644--- a/packages/core/src/markdown/mdast-to-html.ts+++ b/packages/core/src/markdown/mdast-to-html.ts@@ -1,4 +1,3 @@-import type { Element, Root as HastRoot, Text as HastText } from 'hast';import type { Root as MdastRoot, Text as MdastText } from 'mdast';import type { Handler } from 'mdast-util-to-hast';diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.tsindex 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/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.tsindex 17ed2b829..1a897fca8 100644--- a/packages/core/src/markdown/mermaid-promoter.ts+++ b/packages/core/src/markdown/mermaid-promoter.ts@@ -1,4 +1,3 @@-import type { Code, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.tsindex 4aa0490c4..d988f4b8b 100644--- a/packages/core/src/markdown/parse-with-fallback.ts+++ b/packages/core/src/markdown/parse-with-fallback.ts@@ -168,7 +168,6 @@ export function parseRecursive(}}-interface VFilePlace {offset?: number;start?: { offset?: number };@@ -187,7 +186,6 @@ function extractErrorOffset(err: unknown): number | undefined {return undefined;}-interface Region {start: number;end: number;@@ -211,7 +209,6 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {return null;}-export interface TagEvent {kind: 'open' | 'close' | 'self-close';name: string;@@ -358,7 +355,6 @@ function findFallbackRegion(src: string, errorOffset: number): Region {return { start: blockStart, end: blockEnd };}-interface SourceBlock {src: string;start: number;@@ -456,7 +452,6 @@ function tryPerBlockFallback(};}-function wholeDocRawText(source: string): JSONContent {return {type: 'doc',diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.tsindex 43d420187..e6ab4fd57 100644--- a/packages/core/src/markdown/parser-drop-closure.ts+++ b/packages/core/src/markdown/parser-drop-closure.ts@@ -1,4 +1,3 @@-export type DroppedTokenAdjudication =| {kind: 'format-dof-axis';diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.tsindex 55736041c..0e3224206 100644--- a/packages/core/src/markdown/pipeline.ts+++ b/packages/core/src/markdown/pipeline.ts@@ -1,4 +1,3 @@-import {type FromProseMirrorOptions,fromProseMirror,diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.tsindex ccf06e94d..91cdf658f 100644--- a/packages/core/src/markdown/position-aware-join.ts+++ b/packages/core/src/markdown/position-aware-join.ts@@ -1,4 +1,3 @@-import type { Join } from 'mdast-util-to-markdown';import type { Position } from 'unist';import { isBlankLineParagraph } from './zero-emission-blocks.ts';diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.tsindex e5b4c9eba..0f399d34c 100644--- a/packages/core/src/markdown/position-slice.ts+++ b/packages/core/src/markdown/position-slice.ts@@ -1,4 +1,3 @@-import type { Nodes, Root } from 'mdast';import { visit } from 'unist-util-visit';import type { VFile } from 'vfile';@@ -477,8 +476,7 @@ export function applyPositionSliceToNode(const first = source[startOff];if (first !== '[' && first !== '<' && !node.title) {node.data.sourceStyle = 'gfm-autolink';- }- else if (first === '[') {+ } else if (first === '[') {const slice = source.slice(startOff, endOff);const closeBracketIdx = slice.lastIndexOf('](');if (closeBracketIdx !== -1) {diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.tsindex ca225ce9b..db10fa54b 100644--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts@@ -1,4 +1,3 @@-import type { Comment, Element, Root, Text } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.tsindex 3a2524a9a..34068d103 100644--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts@@ -1,4 +1,3 @@-import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.tsindex 2279a0189..93151d43b 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts@@ -1,4 +1,3 @@-import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.tsindex a0f467c42..188f02d83 100644--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts@@ -1,4 +1,3 @@-import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.tsindex 4e8542a21..4ba2c3418 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts@@ -1,4 +1,3 @@-import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.tsindex a3c96b24a..1a74b1272 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts@@ -1,4 +1,3 @@-import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.tsindex e95cf43d6..de35e7b79 100644--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts@@ -1,4 +1,3 @@-import type { Comment, Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.tsindex ffdb4d5b5..b4be1b2ea 100644--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts@@ -1,4 +1,3 @@-import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.tsindex e2a96d1a7..3c8d88b7c 100644--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts@@ -1,4 +1,3 @@-import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.tsindex 0389575ac..cf2c9da8e 100644--- a/packages/core/src/markdown/resolve-image-url.ts+++ b/packages/core/src/markdown/resolve-image-url.ts@@ -1,4 +1,3 @@-import { isRelativeUrl } from './safe-url.ts';function isDevDiagnosticContext(): boolean {diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.tsindex 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/core/src/markdown/serialize-fidelity.test-helper.ts b/packages/core/src/markdown/serialize-fidelity.test-helper.tsindex 96304e7a5..0dd54070e 100644--- a/packages/core/src/markdown/serialize-fidelity.test-helper.ts+++ b/packages/core/src/markdown/serialize-fidelity.test-helper.ts@@ -1,4 +1,3 @@-import type { JSONContent } from '@tiptap/core';import type { Nodes } from 'mdast';import { expect } from 'vitest';diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.tsindex 93798cf83..7cac5b042 100644--- a/packages/core/src/markdown/serialize-helpers.ts+++ b/packages/core/src/markdown/serialize-helpers.ts@@ -1,4 +1,3 @@-import type { Node as PmNode } from '@tiptap/pm/model';import type {MdxJsxAttribute,diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.tsindex 8c08b7a04..b012a5aff 100644--- a/packages/core/src/markdown/single-dollar-math-promoter.ts+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts@@ -1,4 +1,3 @@-import type { PhrasingContent, Root, Text } from 'mdast';import type { InlineMath } from 'mdast-util-math';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.tsindex 959cc0bd2..3e79f8cb6 100644--- a/packages/core/src/markdown/to-markdown-handlers.ts+++ b/packages/core/src/markdown/to-markdown-handlers.ts@@ -1,4 +1,3 @@-import type { Nodes, Parents } from 'mdast';import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import type { Handle, Info, State } from 'mdast-util-to-markdown';diff --git a/packages/core/src/markdown/underline-promoter.ts b/packages/core/src/markdown/underline-promoter.tsindex 6e6d73400..0f1b0f27d 100644--- a/packages/core/src/markdown/underline-promoter.ts+++ b/packages/core/src/markdown/underline-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Parent, Root } from 'mdast';import type { MdxJsxTextElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.tsindex 932d7d2a8..1a082bda7 100644--- a/packages/core/src/markdown/unknown-mdast-guard.ts+++ b/packages/core/src/markdown/unknown-mdast-guard.ts@@ -1,4 +1,3 @@-import type { Root as MdastRoot } from 'mdast';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.tsindex ac9f5239b..d578476a7 100644--- a/packages/core/src/markdown/whitespace-char-ref.ts+++ b/packages/core/src/markdown/whitespace-char-ref.ts@@ -1,4 +1,3 @@-const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([[0x20, ' '],[0x09, '\t'],diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.tsindex afd9936fe..6dad26200 100644--- a/packages/core/src/markdown/wiki-link-micromark.ts+++ b/packages/core/src/markdown/wiki-link-micromark.ts@@ -17,7 +17,6 @@ declare module 'micromark-util-types' {}}-const CODE_BANG = 33; // !const CODE_LBRACKET = 91; // [const CODE_RBRACKET = 93; // ]@@ -261,7 +260,6 @@ export function wikiLinkSyntax(): Extension {};}-function enterWikiLink(this: CompileContext, token: Token) {this.enter({@@ -387,7 +385,6 @@ export const wikiLinkToMarkdown: {unsafe: [{ character: '[', inConstruct: ['phrasing'] }],};-const MICROMARK_EXT = wikiLinkSyntax();export function remarkWikiLink(this: Processor) {diff --git a/packages/server/src/acp/launch.test.ts b/packages/server/src/acp/launch.test.tsindex 9e81aa02c..10f91ebda 100644--- a/packages/server/src/acp/launch.test.ts+++ b/packages/server/src/acp/launch.test.ts@@ -30,12 +30,16 @@ import {brokenInterpreterHint,declinedRepairHint,ensureBinaryInstalled,+ incompatibleNodeHint,isPathQualified,+ MINIMUM_NPX_NODE_MAJOR,mergedEnv,overlaySetsPath,preflightLaunch,probeInterpreterHealth,+ probeNpxNodeCompatibility,type ResolvedLaunch,+ resolveNpxNodeCommand,resolveWindowsCommand,spawnAcpAgent,terminateAgentTree,@@ -44,6 +48,7 @@ import {windowsCmdWrap,withHostedAgentMarker,withLoginShellPath,+ withPreferredLoginShellPath,} from './launch.ts';import type { RegistryBinaryTarget } from './registry.ts';@@ -157,6 +162,25 @@ describe('withLoginShellPath', () => {});});+describe('withPreferredLoginShellPath', () => {+ const key = 'PATH' in process.env ? 'PATH' : 'Path';++ test('promotes the login-shell PATH ahead of an incompatible inherited runtime', () => {+ const out = withPreferredLoginShellPath(+ {+ cmd: 'npx',+ args: ['-y', 'pkg'],+ env: { [key]: `/old-node/bin${delimiter}/usr/bin`, TOKEN: 'keep' },+ kind: 'npx',+ pathFromOverlay: false,+ },+ `/new-node/bin${delimiter}/usr/bin`,+ );+ expect(out.env[key]).toBe(`/new-node/bin${delimiter}/usr/bin${delimiter}/old-node/bin`);+ expect(out.env.TOKEN).toBe('keep');+ });+});+describe('isPathQualified', () => {test('a bare name is PATH-searched; a located command is not', () => {expect(isPathQualified('npx')).toBe(false);@@ -891,6 +915,71 @@ describe.skipIf(process.platform === 'win32')('probeInterpreterHealth', () => {}, 20_000);});+describe.skipIf(process.platform === 'win32')('probeNpxNodeCompatibility', () => {+ const launchWithNodeVersion = (body: string): ResolvedLaunch => {+ const dir = tmp();+ writeFileSync(join(dir, 'node'), `#!/bin/sh\n${body}\n`, { mode: 0o755 });+ return {+ cmd: 'npx',+ args: ['-y', '@fake/agent'],+ env: { PATH: dir },+ kind: 'npx',+ pathFromOverlay: true,+ };+ };++ test(`accepts Node ${MINIMUM_NPX_NODE_MAJOR}`, async () => {+ await expect(+ probeNpxNodeCompatibility(launchWithNodeVersion(`echo v${MINIMUM_NPX_NODE_MAJOR}.0.0`)),+ ).resolves.toBeNull();+ });++ test('rejects a runnable Node 16 with the found and required versions', async () => {+ const detail = await probeNpxNodeCompatibility(launchWithNodeVersion('echo v16.14.2'));+ expect(detail).toContain('Node.js v16.14.2 is incompatible');+ expect(detail).toContain(`Node.js ${MINIMUM_NPX_NODE_MAJOR} or newer is required`);+ });++ test('fails closed when the runtime does not report a recognizable version', async () => {+ await expect(+ probeNpxNodeCompatibility(launchWithNodeVersion('echo unknown')),+ ).resolves.toContain('unrecognized version');+ });++ test('a hung version probe times out as unknown instead of incompatible', async () => {+ await expect(+ probeNpxNodeCompatibility(launchWithNodeVersion('while :; do /bin/sleep 1; done'), 100),+ ).resolves.toBeNull();+ });++ test('fails closed when Node is missing from the selected PATH', async () => {+ const launch: ResolvedLaunch = {+ cmd: 'npx',+ args: ['-y', '@fake/agent'],+ env: { PATH: tmp() },+ kind: 'npx',+ pathFromOverlay: true,+ };+ await expect(probeNpxNodeCompatibility(launch)).resolves.toContain(+ 'Node.js version probe failed',+ );+ });++ test('fails closed when Node exits successfully without a version', async () => {+ await expect(probeNpxNodeCompatibility(launchWithNodeVersion('exit 0'))).resolves.toContain(+ 'returned no version',+ );+ });++ test('the dead-end hint explains compatibility rather than claiming Node is missing', () => {+ const launch = launchWithNodeVersion('echo v16.14.2');+ const hint = incompatibleNodeHint(launch, 'Node.js v16.14.2 is incompatible');+ expect(hint).toContain('selected Node.js runtime');+ expect(hint).toContain('private compatible copy');+ expect(hint).not.toContain('was not found');+ });+});+describe('brokenInterpreterHint', () => {test('names Node.js for npx and points at the Homebrew icu4c cause', () => {const hint = brokenInterpreterHint(@@ -1009,6 +1098,30 @@ describe('windows cmd wrapping (spawn on Windows)', () => {if (resolved !== 'npx') expect(/\.cmd$/i.test(resolved)).toBe(true);});+ test('the npx compatibility probe selects the node.exe beside the resolved shim', () => {+ const priorPathExt = process.env.PATHEXT;+ try {+ process.env.PATHEXT = '.cmd;.exe';+ const earlier = tmp();+ const npmBin = tmp();+ writeFileSync(join(earlier, 'node.exe'), 'unrelated node');+ writeFileSync(join(npmBin, 'npx.cmd'), '@echo off\n');+ writeFileSync(join(npmBin, 'node.exe'), 'npm shim node');+ const launch: ResolvedLaunch = {+ cmd: 'npx',+ args: ['-y', '@fake/agent'],+ env: { PATH: [earlier, npmBin].join(delimiter) },+ kind: 'npx',+ pathFromOverlay: true,+ };++ expect(resolveNpxNodeCommand(launch, 'win32')).toBe(join(npmBin, 'node.exe'));+ } finally {+ if (priorPathExt === undefined) delete process.env.PATHEXT;+ else process.env.PATHEXT = priorPathExt;+ }+ });+test('outer-quotes the whole command so a spaced launcher path survives /s', () => {const { cmd, args } = windowsCmdWrap('C:\\Program Files\\nodejs\\npx.cmd', ['-y', 'pkg']);expect(cmd.toLowerCase()).toContain('cmd');diff --git a/packages/server/src/acp/launch.ts b/packages/server/src/acp/launch.tsindex ad8738d2d..807e7770a 100644--- a/packages/server/src/acp/launch.ts+++ b/packages/server/src/acp/launch.ts@@ -23,7 +23,7 @@ import { augmentAgentSpawnPath, OK_DIR, OK_HOSTED_AGENT_ENV } from '@inkeep/openimport { tracedMkdir, tracedRm, tracedWriteFile } from '../fs-traced.ts';import type { PinoLogger } from '../logger.ts';import { downloadToFileWithSha, extractArchive, isWithin, sanitizeSegment } from './archive.ts';-import { mergeLoginShellPath } from './login-shell-path.ts';+import { mergeLoginShellPath, preferLoginShellPath } from './login-shell-path.ts';import type { ManagedRuntime } from './managed-runtime.ts';import type { CustomAgentEntry, RegistryAgent, RegistryBinaryTarget } from './registry.ts';import { STALE_INSTALL_ARTIFACT_AGE_MS, stagedInstall } from './staged-install.ts';@@ -42,6 +42,9 @@ export interface ResolvedLaunch {pathFromOverlay: boolean;}+/** Strictest declared Node floor among the registry-backed npx ACP adapters. */+export const MINIMUM_NPX_NODE_MAJOR = 22;+export class AgentLaunchError extends Error {readonly code:| 'unsupported-platform'@@ -240,6 +243,21 @@ export function withLoginShellPath(launch: ResolvedLaunch, loginShellPath: strinreturn { ...launch, env: withLoginShellPathEnv(launch.env, loginShellPath) };}+/**+ * Retry an incompatible interpreter under the environment the user's terminal+ * sees. Unlike the normal append-only merge, this intentionally lets the shell+ * runtime win; callers must first establish that the inherited runtime cannot+ * satisfy the launch contract.+ */+export function withPreferredLoginShellPath(+ launch: ResolvedLaunch,+ loginShellPath: string,+): ResolvedLaunch {+ const env = { ...launch.env };+ env[pathKey(env)] = preferLoginShellPath(envPath(env), loginShellPath, delimiter);+ return { ...launch, env };+}+/*** {@link withLoginShellPath} for a bare spawn env — the ACP terminal surface,* which builds its env from `mergedEnv` rather than from a `ResolvedLaunch`.@@ -521,6 +539,11 @@ export function unrepairableManagedRuntimeHint(launch: ResolvedLaunch, detail: sreturn `OK downloaded a fresh copy of ${runtime} and it still can't run (${detail}). Something on this machine is stopping it — antivirus, a security policy, or an unsupported CPU are the usual causes.`;}+/** Actionable dead end when this OK build carries an obsolete managed Node. */+export function incompatibleManagedRuntimeHint(detail: string): string {+ return `OK's private Node.js runtime is incompatible (${detail}). Update Open Knowledge and try again.`;+}+/*** The launch-error detail for a damaged copy of OK's own runtime that could* not be replaced: the rename that clears the way for a fresh download failed,@@ -545,9 +568,9 @@ export function declinedRepairHint(launch: ResolvedLaunch): string {return `OK's own copy of ${runtime} is damaged and can't run this agent. Start the agent again to let OK download a fresh copy.`;}-/** Cap on probe stderr retained while waiting for the verdict. */-const PROBE_STDERR_MAX = 2_000;-/** Cap on the stderr excerpt carried in a probe verdict (it reaches the user). */+/** Cap on probe output retained while waiting for the verdict. */+const PROBE_OUTPUT_MAX = 2_000;+/** Cap on the output excerpt carried in a probe verdict (it reaches the user). */const PROBE_DETAIL_MAX = 300;/**@@ -605,7 +628,7 @@ export function probeInterpreterHealth(let stderr = '';child.stderr?.setEncoding('utf8');child.stderr?.on('data', (chunk: string) => {- if (stderr.length < PROBE_STDERR_MAX) stderr += chunk;+ if (stderr.length < PROBE_OUTPUT_MAX) stderr += chunk;});let settled = false;const settle = (detail: string | null): void => {@@ -651,6 +674,110 @@ export function probeInterpreterHealth(});}+/**+ * Verify that an npx launch resolves a supported Node runtime from the same+ * environment the adapter will inherit. npm's POSIX launcher uses+ * `#!/usr/bin/env node`; its Windows launcher prefers the sibling `node.exe`+ * beside the resolved `npx.cmd` shim, then falls back to PATH.+ *+ * Compatibility is fail-closed for a missing runtime, failed process, empty+ * output, or unparsable version. A timeout is only an unknown/slow verdict, so+ * it proceeds with the launch after best-effort process-tree termination and+ * a debug log, matching the interpreter-health probe's latency policy.+ */+export function probeNpxNodeCompatibility(+ launch: ResolvedLaunch,+ timeoutMs = 5_000,+ log?: PinoLogger,+): Promise<string | null> {+ const win = process.platform === 'win32';+ const resolved = resolveNpxNodeCommand(launch);+ return new Promise((settleProbe) => {+ let child: ChildProcess;+ try {+ child = spawn(resolved, ['--version'], {+ env: launch.env,+ stdio: ['ignore', 'pipe', 'pipe'],+ shell: false,+ detached: !win,+ windowsHide: true,+ });+ } catch (err) {+ settleProbe(+ `Node.js version probe could not start: ${err instanceof Error ? err.message : String(err)}`,+ );+ return;+ }+ let stdout = '';+ let stderr = '';+ child.stdout?.setEncoding('utf8');+ child.stdout?.on('data', (chunk: string) => {+ if (stdout.length < PROBE_OUTPUT_MAX) stdout += chunk;+ });+ child.stderr?.setEncoding('utf8');+ child.stderr?.on('data', (chunk: string) => {+ if (stderr.length < PROBE_OUTPUT_MAX) stderr += chunk;+ });+ let settled = false;+ const settle = (detail: string | null): void => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ settleProbe(detail);+ };+ const timer = setTimeout(() => {+ terminateAgentTree(child, { graceMs: 0, forceWaitMs: 0 }).catch(() => {+ // Best-effort: the unknown verdict stands either way.+ });+ log?.debug(+ { cmd: launch.cmd, kind: launch.kind, timeoutMs },+ '[acp-launch] Node.js compatibility probe timed out — proceeding with the launch',+ );+ settle(null);+ }, timeoutMs);+ timer.unref?.();+ child.on('error', (err) => settle(`Node.js version probe failed: ${err.message}`));+ // `close`, not `exit`: stdout can remain readable briefly after the process+ // exits, and the version bytes are the compatibility verdict.+ child.on('close', (code, signal) => {+ if (signal !== null || (code !== null && code !== 0)) {+ const firstStderrLine = stderr+ .split('\n')+ .map((line) => line.trim())+ .find((line) => line !== '');+ const reason = signal ?? `exit code ${code}`;+ settle(+ firstStderrLine === undefined+ ? `Node.js version probe failed with ${reason}`+ : `Node.js version probe failed with ${reason}: ${firstStderrLine.slice(0, PROBE_DETAIL_MAX)}`,+ );+ return;+ }+ const version = stdout.trim();+ const match = /^v?(\d+)(?:\.|$)/.exec(version);+ if (match === null) {+ settle(+ version === ''+ ? 'Node.js version probe returned no version'+ : `Node.js reported an unrecognized version: ${version.slice(0, PROBE_DETAIL_MAX)}`,+ );+ return;+ }+ const major = Number.parseInt(match[1] ?? '', 10);+ settle(+ major >= MINIMUM_NPX_NODE_MAJOR+ ? null+ : `Node.js ${version} is incompatible; Node.js ${MINIMUM_NPX_NODE_MAJOR} or newer is required`,+ );+ });+ });+}++/** Actionable dead-end message when no compatible system Node can be selected. */+export function incompatibleNodeHint(launch: ResolvedLaunch, detail: string): string {+ return `\`${launch.cmd}\` cannot run this agent with the selected Node.js runtime (${detail}). Upgrade Node.js or let Open Knowledge download a private compatible copy.`;+}+/** Case-insensitive `PATH` lookup (Windows spells it `Path`), falling back to the process env. */export function envPath(env: Record<string, string>): string | undefined {for (const [k, v] of Object.entries(env)) {@@ -737,6 +864,30 @@ export function resolveWindowsCommand(cmd: string, pathEnv: string | undefined):return cmd;}+/** Resolve the Node executable that npm's npx launcher will actually use. */+export function resolveNpxNodeCommand(+ launch: ResolvedLaunch,+ platform: NodeJS.Platform = process.platform,+): string {+ if (platform !== 'win32') return 'node';+ const pathEnv = envPath(launch.env);+ const resolvedNpx = resolveWindowsCommand(launch.cmd, pathEnv);+ const npxWasResolved =+ resolvedNpx !== launch.cmd ||+ isAbsolute(resolvedNpx) ||+ resolvedNpx.includes('/') ||+ resolvedNpx.includes('\\');+ if (npxWasResolved) {+ const siblingNode = join(dirname(resolvedNpx), 'node.exe');+ try {+ if (statSync(siblingNode).isFile()) return siblingNode;+ } catch {+ // npm falls back to PATH when its sibling Node is absent.+ }+ }+ return resolveWindowsCommand('node', pathEnv);+}+/** Double-quote a token if cmd.exe would otherwise split or interpret it. */function quoteCmdArg(arg: string): string {if (arg === '') return '""';diff --git a/packages/server/src/acp/login-shell-path.test.ts b/packages/server/src/acp/login-shell-path.test.tsindex 2e76155bc..95b5e3947 100644--- a/packages/server/src/acp/login-shell-path.test.ts+++ b/packages/server/src/acp/login-shell-path.test.ts@@ -15,6 +15,7 @@ import {loginShellProbeArgs,mergeLoginShellPath,parseLoginShellPath,+ preferLoginShellPath,} from './login-shell-path.ts';const log = getLogger('login-shell-path-test');@@ -89,6 +90,18 @@ describe('mergeLoginShellPath', () => {});});+describe('preferLoginShellPath', () => {+ test('moves shell entries first and retains inherited-only entries', () => {+ expect(preferLoginShellPath('/old/bin:/usr/bin', '/new/bin:/usr/bin', ':')).toBe(+ '/new/bin:/usr/bin:/old/bin',+ );+ });++ test('drops empty and duplicate entries', () => {+ expect(preferLoginShellPath('/old/bin::/new/bin', '/new/bin:', ':')).toBe('/new/bin:/old/bin');+ });+});+describe('createLoginShellPathProvider (skip conditions)', () => {const neverRuns = () => {throw new Error('probe must not spawn');diff --git a/packages/server/src/acp/login-shell-path.ts b/packages/server/src/acp/login-shell-path.tsindex d68651722..6d9cbc940 100644--- a/packages/server/src/acp/login-shell-path.ts+++ b/packages/server/src/acp/login-shell-path.ts@@ -128,6 +128,20 @@ export function mergeLoginShellPath(return entries.join(delim);}+/**+ * Put the login shell's PATH first, retaining inherited-only entries behind it.+ * This is deliberately separate from the append-only normal merge: callers use+ * it only after proving the inherited interpreter is incompatible, when keeping+ * that interpreter first would guarantee the launch fails.+ */+export function preferLoginShellPath(+ current: string | undefined,+ loginShellPath: string,+ delim: string,+): string {+ return mergeLoginShellPath(loginShellPath, current ?? '', delim);+}+/** Shells that exist to refuse a session — probing them is pure latency. */const NON_INTERACTIVE_SHELLS = new Set(['false', 'nologin', 'sync']);diff --git a/packages/server/src/acp/managed-runtime-flow.integration.test.ts b/packages/server/src/acp/managed-runtime-flow.integration.test.tsindex b27af6adb..df35d1260 100644--- a/packages/server/src/acp/managed-runtime-flow.integration.test.ts+++ b/packages/server/src/acp/managed-runtime-flow.integration.test.ts@@ -31,12 +31,14 @@ import type {import { afterEach, describe, expect, test } from 'vitest';import type { AgentSessionManager } from '../agent-sessions.ts';import { getLogger } from '../logger.ts';-import { ensureManagedRuntime, findManagedRuntime } from './managed-runtime.ts';+import { MINIMUM_NPX_NODE_MAJOR } from './launch.ts';+import { describeRuntime, ensureManagedRuntime, findManagedRuntime } from './managed-runtime.ts';import { AcpPermissionStore } from './permissions.ts';import { AcpRegistry } from './registry.ts';import { AcpThreadManager } from './thread-manager.ts';const log = getLogger('managed-runtime-flow-test');+const MANAGED_NODE_VERSION = describeRuntime('node').version;const fakeSessionManager = {getSession: async () => {@@ -77,11 +79,12 @@ const NPX_AGENT = {function fakeNodeTarball(dir: string,npxBody = '#!/bin/sh\nexit 0\n',+ nodeVersion = MANAGED_NODE_VERSION,): { bytes: Buffer; sha: string } {const treeRoot = join(dir, 'tree');const binDir = join(treeRoot, 'node-vTEST', 'bin');mkdirSync(binDir, { recursive: true });- writeFileSync(join(binDir, 'node'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });+ writeFileSync(join(binDir, 'node'), `#!/bin/sh\necho ${nodeVersion}\n`, { mode: 0o755 });writeFileSync(join(binDir, 'npx'), npxBody, { mode: 0o755 });const tarPath = join(dir, 'node.tar.gz');execFileSync('tar', ['-czf', tarPath, '-C', treeRoot, 'node-vTEST']);@@ -97,7 +100,7 @@ function fakeNodeFetch(bytes: Buffer, sha: string, agent: unknown = NPX_AGENT):}if (u.endsWith('SHASUMS256.txt')) {const names = ['darwin-arm64', 'darwin-x64', 'linux-arm64', 'linux-x64'].map(- (n) => `${sha} node-v24.18.0-${n}.tar.gz`,+ (n) => `${sha} node-${MANAGED_NODE_VERSION}-${n}.tar.gz`,);return new Response(`${names.join('\n')}\n`, { status: 200 });}@@ -108,6 +111,10 @@ function fakeNodeFetch(bytes: Buffer, sha: string, agent: unknown = NPX_AGENT):}) as unknown as typeof fetch;}+function writeNodeVersion(binDir: string, version: string): void {+ writeFileSync(join(binDir, 'node'), `#!/bin/sh\necho ${version}\n`, { mode: 0o755 });+}+function makeManager(opts: {contentDir: string;localDir: string;@@ -180,7 +187,7 @@ describe('managed-runtime consent + download flow', () => {const fetchImpl = fakeNodeFetch(bytes, sha);await ensureManagedRuntime('node', log, { root: runtimeRoot, fetchImpl });- const staleDir = join(runtimeRoot, 'node', '.install-v24.18.0-orphaned');+ const staleDir = join(runtimeRoot, 'node', `.install-${MANAGED_NODE_VERSION}-orphaned`);mkdirSync(staleDir, { recursive: true });const staleTime = new Date(Date.now() - 25 * 60 * 60 * 1_000);utimesSync(staleDir, staleTime, staleTime);@@ -340,6 +347,100 @@ describe('managed-runtime consent + download flow', () => {expect(installed).not.toBeNull();}, 20_000);+ test('a runnable Node 16 routes to the managed runtime despite a healthy npx', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const runtimeRoot = tmp();+ const oldBin = tmp();+ writeFileSync(join(oldBin, 'npx'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });+ writeNodeVersion(oldBin, 'v16.14.2');+ const manager = makeManager({+ contentDir,+ localDir,+ runtimeRoot,+ fetchImpl: fakeNodeFetch(Buffer.from('unused'), 'x'.repeat(64), {+ ...NPX_AGENT,+ distribution: { npx: { package: '@fake/agent', env: { PATH: oldBin } } },+ }),+ });++ const events: ThreadEvent[] = [];+ const info = await manager.createThread({ agent: { source: 'registry', id: 'npxagent' } });+ await collect(manager, info.threadId, events);+ await waitFor(() => findConsentRequest(events) !== undefined, 10_000, 'consent request');++ const req = findConsentRequest(events);+ if (req === undefined) throw new Error('unreachable');+ expect(req.reason).toBe('broken');+ manager.respondRuntimeConsent(info.threadId, req.requestId, { kind: 'declined' });+ await waitFor(+ () => events.some((e) => e.kind === 'status' && e.status === 'error'),+ 10_000,+ 'incompatible runtime error',+ );+ const errEvent = events.find(+ (e): e is Extract<ThreadEvent, { kind: 'status' }> =>+ e.kind === 'status' && e.status === 'error',+ );+ expect(errEvent?.detail).toContain('Node.js v16.14.2 is incompatible');+ expect(errEvent?.detail).toContain(`Node.js ${MINIMUM_NPX_NODE_MAJOR} or newer is required`);+ }, 20_000);++ test.skipIf(process.platform === 'win32')(+ 'a compatible login-shell Node replaces a stale GUI-inherited Node',+ async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const runtimeRoot = tmp();+ const oldBin = tmp();+ const newBin = tmp();+ const calls = join(tmp(), 'calls.log');+ writeFileSync(join(oldBin, 'npx'), `#!/bin/sh\necho "old:$*" >> ${calls}\nexit 0\n`, {+ mode: 0o755,+ });+ writeNodeVersion(oldBin, 'v16.14.2');+ writeFileSync(join(newBin, 'npx'), `#!/bin/sh\necho "new:$*" >> ${calls}\nexit 0\n`, {+ mode: 0o755,+ });+ writeNodeVersion(newBin, 'v24.13.0');++ const priorPath = process.env.PATH;+ process.env.PATH = oldBin;+ try {+ const manager = makeManager({+ contentDir,+ localDir,+ runtimeRoot,+ fetchImpl: fakeNodeFetch(Buffer.from('unused'), 'x'.repeat(64), {+ ...NPX_AGENT,+ distribution: { npx: { package: '@fake/agent' } },+ }),+ resolveLoginShellPath: async () => newBin,+ });++ const events: ThreadEvent[] = [];+ const info = await manager.createThread({ agent: { source: 'registry', id: 'npxagent' } });+ await collect(manager, info.threadId, events);+ await waitFor(+ () => manager.getInfo(info.threadId)?.status === 'error',+ 10_000,+ 'the fake adapter to exit',+ );++ expect(findConsentRequest(events)).toBeUndefined();+ const invocations = readFileSync(calls, 'utf8').trim().split('\n');+ expect(invocations).toContain('old:--version');+ expect(invocations).not.toContain('old:-y @fake/agent');+ expect(invocations).toContain('new:--version');+ expect(invocations).toContain('new:-y @fake/agent');+ } finally {+ if (priorPath === undefined) delete process.env.PATH;+ else process.env.PATH = priorPath;+ }+ },+ 20_000,+ );+// Declining the download must not leave the user with the stock hint, which// says the interpreter "isn't installed" — the one thing this case disproves.test('declining after a crash reports the broken interpreter, not a missing one', async () => {@@ -432,6 +533,41 @@ describe('managed-runtime consent + download flow', () => {});describe('interpreter health probe', () => {+ test('an incompatible managed Node asks the user to update OK instead of blaming the machine', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const runtimeRoot = tmp();+ const stage = tmp();+ const { bytes, sha } = fakeNodeTarball(stage, undefined, 'v16.14.2');+ const fetchImpl = fakeNodeFetch(bytes, sha);+ const manager = makeManager({ contentDir, localDir, runtimeRoot, fetchImpl });+ const events: ThreadEvent[] = [];+ const info = await manager.createThread({ agent: { source: 'registry', id: 'npxagent' } });+ await collect(manager, info.threadId, events);++ await waitFor(() => findConsentRequest(events) !== undefined, 10_000, 'download offer');+ const req = findConsentRequest(events);+ if (req === undefined) throw new Error('unreachable');+ manager.respondRuntimeConsent(info.threadId, req.requestId, { kind: 'granted' });++ await waitFor(+ () =>+ events.some((e) => e.kind === 'status' && e.status === 'error') ||+ events.filter((e) => e.kind === 'runtime_consent_request').length > 1,+ 15_000,+ 'managed runtime incompatibility verdict',+ );+ const errEvent = events.find(+ (e): e is Extract<ThreadEvent, { kind: 'status' }> =>+ e.kind === 'status' && e.status === 'error',+ );+ expect(errEvent?.detail).toContain('Update Open Knowledge');+ expect(errEvent?.detail).not.toContain('antivirus');+ expect(errEvent?.detail).not.toContain('security policy');+ expect(errEvent?.detail).not.toContain('unsupported CPU');+ expect(events.filter((e) => e.kind === 'runtime_consent_request')).toHaveLength(1);+ }, 30_000);+// The fallback's own fallback. `findManagedRuntime`'s already-installed fast// path admits a runtime on an exists-plus-execute-bit check — the evidence// `probeInterpreterHealth` supersedes — so one damaged by an interrupted@@ -573,6 +709,7 @@ describe('interpreter health probe', () => {// Healthy for `--version`, useless afterwards: the thread fails at the// handshake, which is all this needs — the probe verdict is now cached.writeFileSync(npxPath, '#!/bin/sh\nexit 0\n', { mode: 0o755 });+ writeNodeVersion(binDir, 'v24.0.0');const manager = makeManager({contentDir,localDir,@@ -624,6 +761,7 @@ describe('interpreter health probe', () => {writeFileSync(join(binDir, 'npx'), `#!/bin/sh\necho "$@" >> ${calls}\nexit 0\n`, {mode: 0o755,});+ writeNodeVersion(binDir, 'v24.0.0');const manager = makeManager({contentDir,localDir,@@ -641,8 +779,13 @@ describe('interpreter health probe', () => {.filter((l) => l.trim() === '--version').length: 0;- await manager.createThread({ agent: { source: 'registry', id: 'npxagent' } });- await waitFor(() => versionProbes() === 1, 10_000, 'the first probe');+ const first = await manager.createThread({ agent: { source: 'registry', id: 'npxagent' } });+ await waitFor(+ () => manager.getInfo(first.threadId)?.status === 'error',+ 10_000,+ 'the first thread to finish its launch attempt',+ );+ expect(versionProbes()).toBe(1);const second = await manager.createThread({ agent: { source: 'registry', id: 'npxagent' } });// The second thread must reach its own (failed) launch — otherwise this// would pass on a thread that never got as far as needing an interpreter.diff --git a/packages/server/src/acp/managed-runtime.test.ts b/packages/server/src/acp/managed-runtime.test.tsindex 45b1a0bf2..e9dcaa5f2 100644--- a/packages/server/src/acp/managed-runtime.test.ts+++ b/packages/server/src/acp/managed-runtime.test.ts@@ -24,6 +24,7 @@ import { join } from 'node:path';import { afterEach, describe, expect, test } from 'vitest';import { getLogger } from '../logger.ts';import { shaForFile } from './archive.ts';+import { MINIMUM_NPX_NODE_MAJOR } from './launch.ts';import {describeRuntime,ensureManagedRuntime,@@ -34,6 +35,7 @@ import {} from './managed-runtime.ts';const log = getLogger('managed-runtime-test');+const MANAGED_NODE_VERSION = describeRuntime('node').version;let dirs: string[] = [];function tmp(): string {@@ -81,7 +83,7 @@ function makeFetch(bytes: Buffer, sha: string): typeof fetch {return (async (url: string | URL | Request) => {const u = String(url);if (u.endsWith('SHASUMS256.txt')) {- const body = `${NODE_NAMES.map((n) => `${sha} node-v24.18.0-${n}`).join('\n')}\n`;+ const body = `${NODE_NAMES.map((n) => `${sha} node-${MANAGED_NODE_VERSION}-${n}`).join('\n')}\n`;return new Response(body, { status: 200 });}if (u.endsWith('.sha256')) {@@ -131,6 +133,11 @@ describe('descriptors', () => {expect(node.approxSizeMB).toBeGreaterThan(0);expect(describeRuntime('uv').provides).toBe('uvx');});++ test('the pinned managed Node satisfies the npx compatibility floor', () => {+ const major = Number.parseInt(describeRuntime('node').version.replace(/^v/, ''), 10);+ expect(major).toBeGreaterThanOrEqual(MINIMUM_NPX_NODE_MAJOR);+ });});describe('findManagedRuntime', () => {@@ -182,7 +189,7 @@ describe('ensureManagedRuntime', () => {test('removes crash-orphaned staging directories on the next install', async () => {const stage = tmp();const root = tmp();- const staleDir = join(root, 'node', '.install-v24.18.0-orphaned');+ const staleDir = join(root, 'node', `.install-${MANAGED_NODE_VERSION}-orphaned`);mkdirSync(staleDir, { recursive: true });writeFileSync(join(staleDir, 'partial-archive'), 'partial');const staleTime = new Date(Date.now() - 25 * 60 * 60 * 1_000);diff --git a/packages/server/src/acp/thread-manager.ts b/packages/server/src/acp/thread-manager.tsindex 71e01037b..2dd5b8c93 100644--- a/packages/server/src/acp/thread-manager.ts+++ b/packages/server/src/acp/thread-manager.ts@@ -80,9 +80,12 @@ import {brokenInterpreterHint,declinedRepairHint,envPath,+ incompatibleManagedRuntimeHint,+ incompatibleNodeHint,isPathQualified,preflightLaunch,probeInterpreterHealth,+ probeNpxNodeCompatibility,type ResolvedLaunch,resolveCustomLaunch,resolveRegistryLaunch,@@ -92,6 +95,7 @@ import {undeletableManagedRuntimeHint,unrepairableManagedRuntimeHint,withLoginShellPath,+ withPreferredLoginShellPath,} from './launch.ts';import {getSharedLoginShellPathProvider,@@ -481,6 +485,11 @@ export function buildOkMcpStdioCommand(return { command, args: [...rest, 'mcp', '--port', String(port)] };}+interface InterpreterProbeFailure {+ kind: 'unhealthy' | 'incompatible';+ detail: string;+}+export class AcpThreadManager {private readonly opts: AcpThreadManagerOptions;private readonly threads = new Map<string, ThreadRecord>();@@ -494,8 +503,9 @@ export class AcpThreadManager {private readonly persistence: ThreadPersistenceStore;private readonly resolveLoginShellPath: () => Promise<string | null>;/**- * Interpreters that answered `--version` cleanly, keyed by command + the PATH- * they were probed under — see {@link AcpThreadManager.ensureInterpreterRuns}.+ * Interpreters that answered their liveness and compatibility probes cleanly,+ * keyed by command + PATH — see+ * {@link AcpThreadManager.ensureInterpreterRuns}.* Healthy verdicts only, so a repaired Node is picked up without a restart;* `retryThread` clears it alongside the login-shell memo so the user's retry* re-checks an interpreter that broke after it was cached.@@ -1059,33 +1069,75 @@ export class AcpThreadManager {* here — a login-shell-resolved interpreter can be just as broken as an* inherited-PATH one.*- * A broken interpreter goes STRAIGHT to the managed runtime, never back- * through the login-shell retry: that merge is append-only, so a shell PATH- * cannot shadow an interpreter that already resolves. Non-interpreter kinds- * pass through untouched — a binary/custom command has no managed fallback,- * so probing it could only add latency and a failure mode with no remedy.+ * A broken interpreter goes straight to the managed runtime. An incompatible+ * npx runtime gets one narrower retry with the login-shell PATH promoted,+ * because a terminal-visible compatible Node is preferable to a download.+ * Non-interpreter kinds pass through untouched — a binary/custom command has+ * no managed fallback, so probing it could only add latency and a failure+ * mode with no remedy.*/private async ensureInterpreterRuns(record: ThreadRecord,launch: ResolvedLaunch,): Promise<ResolvedLaunch | null> {if (launch.kind !== 'npx' && launch.kind !== 'uvx') return launch;- const brokenDetail = await this.probeInterpreterOnce(launch);+ const failure = await this.probeInterpreterOnce(launch);if (record.closed) return null;- if (brokenDetail === null) return launch;+ if (failure === null) return launch;++ // A compatible Node in the user's terminal should win over a stale Node+ // inherited by the GUI process. This is deliberately narrower than the+ // normal PATH merge: only a proven incompatibility authorizes redirecting+ // an already-resolved interpreter.+ if (failure.kind === 'incompatible') {+ const preferred = await this.withPreferredLoginShellPathIfEligible(launch);+ if (record.closed) return null;+ if (envPath(preferred.env) !== envPath(launch.env)) {+ try {+ await preflightLaunch(preferred);+ const preferredFailure = await this.probeInterpreterOnce(preferred);+ if (record.closed) return null;+ if (preferredFailure === null) {+ this.opts.log.info(+ { threadId: record.info.threadId, agentId: record.info.agent.id },+ '[acp-threads] compatible Node resolved via the preferred login-shell PATH',+ );+ return preferred;+ }+ this.opts.log.debug(+ {+ threadId: record.info.threadId,+ agentId: record.info.agent.id,+ cmd: preferred.cmd,+ kind: preferred.kind,+ failureKind: preferredFailure.kind,+ detail: preferredFailure.detail,+ },+ '[acp-threads] preferred login-shell PATH did not provide a compatible Node',+ );+ } catch (err) {+ if (!(err instanceof AgentLaunchError) || err.code !== 'command-not-found') throw err;+ // The managed runtime below is the remaining compatible candidate.+ }+ }+ }+this.opts.log.warn({threadId: record.info.threadId,agentId: record.info.agent.id,cmd: launch.cmd,kind: launch.kind,- detail: brokenDetail,+ failureKind: failure.kind,+ detail: failure.detail,},- '[acp-threads] interpreter is installed but failed to run — offering the managed runtime',+ '[acp-threads] interpreter cannot run this agent — offering the managed runtime',);const cause = new AgentLaunchError('command-not-found',- brokenInterpreterHint(launch, brokenDetail),+ failure.kind === 'incompatible'+ ? incompatibleNodeHint(launch, failure.detail)+ : brokenInterpreterHint(launch, failure.detail),);// Also the message a decline lands on: the stock decline hint says the// interpreter "isn't installed", which is the one thing we just proved@@ -1094,7 +1146,7 @@ export class AcpThreadManager {}/**- * Route an npx/uvx interpreter that is missing or broken to the managed+ * Route an npx/uvx interpreter that is missing, broken, or incompatible to the managed* runtime, returning the rewritten launch. Returns null only when the thread* closed mid-flight; rethrows `cause` when this launch kind or platform has* no managed fallback, so the actionable hint reaches the user instead of a@@ -1138,7 +1190,13 @@ export class AcpThreadManager {// opaque "connection closed" with nothing left to try.const brokenManaged = await this.probeInterpreterOnce(rewritten);if (brokenManaged === null) return rewritten;- return this.repairManagedRuntime(record, launch, runtimeKind, brokenManaged);+ if (brokenManaged.kind === 'incompatible') {+ throw new AgentLaunchError(+ 'install-failed',+ incompatibleManagedRuntimeHint(brokenManaged.detail),+ );+ }+ return this.repairManagedRuntime(record, launch, runtimeKind, brokenManaged.detail);}/**@@ -1193,29 +1251,40 @@ export class AcpThreadManager {const stillBroken = await this.probeInterpreterOnce(rewritten);if (stillBroken === null) return rewritten;this.opts.log.error(- { ...logContext, detail: stillBroken },+ { ...logContext, detail: stillBroken.detail },'[acp-threads] a freshly downloaded managed runtime failed to run',);throw new AgentLaunchError('install-failed',- unrepairableManagedRuntimeHint(rewritten, stillBroken),+ stillBroken.kind === 'incompatible'+ ? incompatibleManagedRuntimeHint(stillBroken.detail)+ : unrepairableManagedRuntimeHint(rewritten, stillBroken.detail),);}/**- * {@link probeInterpreterHealth}, memoized per command + PATH. Healthy- * verdicts only: a failing probe is the slow path anyway, and re-running it- * lets a user who repairs their Node mid-session out of the managed runtime- * without restarting the server.+ * Interpreter liveness plus npx Node compatibility, memoized per command+ * and PATH. Healthy verdicts only: a failing probe+ * is the slow path anyway, and re-running it lets a user who repairs their+ * Node mid-session out of the managed runtime without restarting the server.*/- private async probeInterpreterOnce(launch: ResolvedLaunch): Promise<string | null> {- // Both fields, JSON-encoded rather than concatenated: a command or PATH- // holding the delimiter would otherwise let two launches share a verdict.+ private async probeInterpreterOnce(+ launch: ResolvedLaunch,+ ): Promise<InterpreterProbeFailure | null> {+ // JSON-encoded rather than concatenated: a command or PATH holding the+ // delimiter would otherwise let two launches share a verdict.const healthKey = JSON.stringify([launch.cmd, envPath(launch.env) ?? '']);if (this.healthyInterpreters.has(healthKey)) return null;- const detail = await probeInterpreterHealth(launch, undefined, this.opts.log);- if (detail === null) this.healthyInterpreters.add(healthKey);- return detail;+ const unhealthyDetail = await probeInterpreterHealth(launch, undefined, this.opts.log);+ if (unhealthyDetail !== null) return { kind: 'unhealthy', detail: unhealthyDetail };+ if (launch.kind === 'npx') {+ const incompatibleDetail = await probeNpxNodeCompatibility(launch, undefined, this.opts.log);+ if (incompatibleDetail !== null) {+ return { kind: 'incompatible', detail: incompatibleDetail };+ }+ }+ this.healthyInterpreters.add(healthKey);+ return null;}/**@@ -1264,6 +1333,20 @@ export class AcpThreadManager {return withLoginShellPath(launch, loginShellPath);}+ /**+ * Promote the login-shell PATH only after the inherited Node was proven+ * incompatible. Manifest PATH overlays and path-qualified launchers remain+ * authoritative and are never reordered.+ */+ private async withPreferredLoginShellPathIfEligible(+ launch: ResolvedLaunch,+ ): Promise<ResolvedLaunch> {+ if (launch.pathFromOverlay || isPathQualified(launch.cmd)) return launch;+ const loginShellPath = await this.resolveLoginShellPath().catch(() => null);+ if (loginShellPath === null) return launch;+ return withPreferredLoginShellPath(launch, loginShellPath);+ }+/*** Return a managed runtime for `runtimeKind`, downloading it if the user* consents. Null means the thread closed while we waited; a throw means the