Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(acp): ask the login shell for PATH before offering a managed Node (#3179)
mike-inkeepa04026727cf9
diff --git a/.changeset/acp-login-shell-path-fallback.md b/.changeset/acp-login-shell-path-fallback.mdnew file mode 100644index 000000000..bf3ade4f0--- /dev/null+++ b/.changeset/acp-login-shell-path-fallback.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Agents that run through `npx` or `uvx` now start on machines where Node or Python tooling is managed by nvm or fnm, instead of offering to download a copy of Node the user already has. A desktop app opened from the Dock or Finder inherits a minimal `PATH`, and a version manager like nvm has no fixed directory to add to it — the active Node lives under a versioned path that only a shell function puts on `PATH`. When a command can't be found, OK now asks your login shell what its `PATH` is and tries once more before offering to download a managed runtime. The same fallback also rescues custom agents installed in shell-configured locations. The probe runs at most once per session, only after a launch has already failed, and never overrides a `PATH` that an agent's own configuration set.diff --git a/knip.config.ts b/knip.config.tsindex 13582ee18..f004e6bc3 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -123,7 +123,9 @@ 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 d7a845280..dfd95ef49 100644--- a/packages/core/src/bridge/bind-frontmatter-doc.ts+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts@@ -1,3 +1,4 @@+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 005627195..8bfdb40cd 100644--- a/packages/core/src/bridge/bridge-invariant.ts+++ b/packages/core/src/bridge/bridge-invariant.ts@@ -1,3 +1,4 @@+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 f4cc8a286..2a597ec3d 100644--- a/packages/core/src/bridge/compose.ts+++ b/packages/core/src/bridge/compose.ts@@ -1,3 +1,4 @@+import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex 8fb428b90..01ef76a9f 100644--- a/packages/core/src/bridge/doc-boundary-space.ts+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -1,3 +1,4 @@+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 9d9c244b0..463e89595 100644--- a/packages/core/src/bridge/growth-detect.ts+++ b/packages/core/src/bridge/growth-detect.ts@@ -1,3 +1,4 @@+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 c43fdd7e7..0939885bb 100644--- a/packages/core/src/bridge/intraline-predicate.ts+++ b/packages/core/src/bridge/intraline-predicate.ts@@ -1,3 +1,4 @@+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 251560a35..c0dc65705 100644--- a/packages/core/src/bridge/merge-three-way.ts+++ b/packages/core/src/bridge/merge-three-way.ts@@ -65,6 +65,7 @@ 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 01ac80099..dcc5b0690 100644--- a/packages/core/src/bridge/normalize.ts+++ b/packages/core/src/bridge/normalize.ts@@ -1,3 +1,4 @@+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 754dc5cc2..0be5203e4 100644--- a/packages/core/src/bridge/pm-structural-equivalence.ts+++ b/packages/core/src/bridge/pm-structural-equivalence.ts@@ -32,6 +32,7 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };const BR_LITERAL_RE = /^<br\s*\/?>$/i;+interface DegradeEntry {readonly label: string;readonly severity: ToleranceClassSeverity;@@ -127,6 +128,7 @@ 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(@@ -248,6 +250,7 @@ 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 af20de1e2..dca644141 100644--- a/packages/core/src/bridge/subsequence.ts+++ b/packages/core/src/bridge/subsequence.ts@@ -1,3 +1,4 @@+/** 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 83d47404a..a363dfd54 100644--- a/packages/core/src/markdown/callout-transformer.ts+++ b/packages/core/src/markdown/callout-transformer.ts@@ -1,3 +1,4 @@+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 9807a7e82..4499dbc92 100644--- a/packages/core/src/markdown/code-fence.ts+++ b/packages/core/src/markdown/code-fence.ts@@ -1,3 +1,4 @@+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 7415c474a..34704165b 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -1,3 +1,4 @@+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 ece5c02a1..b6299a948 100644--- a/packages/core/src/markdown/dedent-block-jsx-close.ts+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts@@ -1,3 +1,4 @@+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 54774764a..acd398aa6 100644--- a/packages/core/src/markdown/details-accordion-promoter.ts+++ b/packages/core/src/markdown/details-accordion-promoter.ts@@ -1,3 +1,4 @@+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 43ecdc709..ba9b56384 100644--- a/packages/core/src/markdown/div-align-promoter.ts+++ b/packages/core/src/markdown/div-align-promoter.ts@@ -1,3 +1,4 @@+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 6d3f3643e..4513da9bb 100644--- a/packages/core/src/markdown/fence-regions.ts+++ b/packages/core/src/markdown/fence-regions.ts@@ -1,3 +1,4 @@+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 00f5771ee..6931623c7 100644--- a/packages/core/src/markdown/fixtures/index.ts+++ b/packages/core/src/markdown/fixtures/index.ts@@ -1,3 +1,4 @@+import { readFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -8,6 +9,7 @@ function fixturePath(...segments: string[]): string {return resolve(FIXTURES_DIR, ...segments);}+interface GfmExample {section: string;markdown: string;@@ -17,6 +19,7 @@ export function loadGfmExamples(): GfmExample[] {return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];}+interface MdxCrashEntry {id: string;input: string;@@ -68,6 +71,7 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {) as LargeEmbedFixture[];}+export function loadPrd6955Before(): string {return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');}@@ -76,6 +80,7 @@ export function loadPrd6955CorruptedTriplicated(): string {return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');}+export interface NgPinnedCase {id: string;name: string;@@ -92,6 +97,7 @@ 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 8b1eb8519..daa3ef82b 100644--- a/packages/core/src/markdown/fixtures/perf/generate.ts+++ b/packages/core/src/markdown/fixtures/perf/generate.ts@@ -1,3 +1,4 @@+import { writeFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -10,6 +11,7 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;const SEED = 0xf1de1117;+function mulberry32(seed: number): () => number {let a = seed >>> 0;return () => {@@ -36,6 +38,7 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {return items[items.length - 1][0];}+const WORDS = ['lorem','ipsum',@@ -153,6 +156,7 @@ 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][] = [@@ -191,6 +195,7 @@ 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 420dc0fe5..32c055c5b 100644--- a/packages/core/src/markdown/guard-flanking-matrix.ts+++ b/packages/core/src/markdown/guard-flanking-matrix.ts@@ -7,6 +7,7 @@ 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 2653473da..283913255 100644--- a/packages/core/src/markdown/handler-shadow-audit.ts+++ b/packages/core/src/markdown/handler-shadow-audit.ts@@ -1,3 +1,4 @@+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 da0a81d23..5d1000cc4 100644--- a/packages/core/src/markdown/highlight-promoter.ts+++ b/packages/core/src/markdown/highlight-promoter.ts@@ -1,3 +1,4 @@+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 787315157..9681c0056 100644--- a/packages/core/src/markdown/html-to-mdast.ts+++ b/packages/core/src/markdown/html-to-mdast.ts@@ -1,3 +1,4 @@+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';@@ -128,7 +129,8 @@ 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 706fa9afb..994eb6917 100644--- a/packages/core/src/markdown/image-promoter.ts+++ b/packages/core/src/markdown/image-promoter.ts@@ -1,3 +1,4 @@+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 9075aa7f1..69221627d 100644--- a/packages/core/src/markdown/index.ts+++ b/packages/core/src/markdown/index.ts@@ -1,3 +1,4 @@+import {type FromProseMirrorOptions,fromPmMark,@@ -206,6 +207,7 @@ export class MarkdownManager {}}+const registry = createRegistry();function destructureAttrs(@@ -254,6 +256,7 @@ function destructureAttrs(return result;}+function hasDirtyDescendant(node: PmNode): boolean {let found = false;node.descendants((child) => {@@ -276,6 +279,7 @@ 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 ?? [];@@ -344,6 +348,7 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {return out;}+import {AUDIO_EXTENSIONS,FILE_ATTACHMENT_EXTENSIONS,@@ -596,6 +601,7 @@ function buildMdastToPmHandlers(}));}+if (m.emphasis) {handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({sourceDelimiter: node.data?.sourceDelimiter ?? '*',@@ -676,6 +682,7 @@ function buildMdastToPmHandlers(}));}+if (m.link) {const sourceLiteralMark = m.sourceLiteral;handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {@@ -973,6 +980,7 @@ function buildMdastToPmHandlers(};}+const blockUnknownHandler = (node: {type: string;position?: { start: { offset: number }; end: { offset: number } };@@ -1098,6 +1106,7 @@ 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 fa0be9e86..b79e9aef7 100644--- a/packages/core/src/markdown/lint/applies-to.ts+++ b/packages/core/src/markdown/lint/applies-to.ts@@ -1,3 +1,4 @@+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 312c9c74b..94b34dee1 100644--- a/packages/core/src/markdown/lint/config-files.ts+++ b/packages/core/src/markdown/lint/config-files.ts@@ -1,3 +1,4 @@+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 0ba33b7d8..e413367ef 100644--- a/packages/core/src/markdown/lint/config-schemas.ts+++ b/packages/core/src/markdown/lint/config-schemas.ts@@ -38,6 +38,7 @@ 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 d48eea5e4..a51f2ffb0 100644--- a/packages/core/src/markdown/lint/default-config.ts+++ b/packages/core/src/markdown/lint/default-config.ts@@ -6,6 +6,7 @@ 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 ef478e268..9c9542661 100644--- a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts+++ b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts@@ -1,3 +1,4 @@+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 0d4c9a0df..b96d19182 100644--- a/packages/core/src/markdown/lint/frontmatter-validate.ts+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts@@ -1,3 +1,4 @@+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 00d08265a..48d260ed6 100644--- a/packages/core/src/markdown/lint/index.ts+++ b/packages/core/src/markdown/lint/index.ts@@ -1,3 +1,4 @@+import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';import type { LintDiagnostic } from './types.ts';diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.tsindex 5e832aa19..be5871ed9 100644--- a/packages/core/src/markdown/lint/plugins.ts+++ b/packages/core/src/markdown/lint/plugins.ts@@ -1,3 +1,4 @@+import { z } from 'zod';import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';import {@@ -13,6 +14,7 @@ import {type MarkdownlintSlice,} from './types.ts';+const MarkdownlintRuleSettingSchema = z.union([z.boolean(),z.enum(MARKDOWNLINT_RULE_SEVERITIES),diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.tsindex 3918e657c..833c3a727 100644--- a/packages/core/src/markdown/lint/types.ts+++ b/packages/core/src/markdown/lint/types.ts@@ -1,3 +1,4 @@+export const LINT_PLUGIN_IDS = ['markdownlint', 'frontmatter'] as const;export type LintPluginId = (typeof LINT_PLUGIN_IDS)[number];@@ -71,6 +72,7 @@ export interface FrontmatterSlice {schemas: ResolvedFrontmatterSchemaEntry[];}+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 98238656e..437cc539a 100644--- a/packages/core/src/markdown/lint/validation-counts.ts+++ b/packages/core/src/markdown/lint/validation-counts.ts@@ -1,3 +1,4 @@+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 a5b511f25..bd79424c7 100644--- a/packages/core/src/markdown/math-promoter.ts+++ b/packages/core/src/markdown/math-promoter.ts@@ -1,3 +1,4 @@+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 ed89371d0..00fbc0035 100644--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts@@ -1,3 +1,4 @@+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 8ce2b2492..df788a80d 100644--- a/packages/core/src/markdown/mdast-to-html.ts+++ b/packages/core/src/markdown/mdast-to-html.ts@@ -1,3 +1,4 @@+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 bfd7e3109..fa3cfcd86 100644--- a/packages/core/src/markdown/merged-walker.ts+++ b/packages/core/src/markdown/merged-walker.ts@@ -1,3 +1,4 @@+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 1a897fca8..17ed2b829 100644--- a/packages/core/src/markdown/mermaid-promoter.ts+++ b/packages/core/src/markdown/mermaid-promoter.ts@@ -1,3 +1,4 @@+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 d988f4b8b..4aa0490c4 100644--- a/packages/core/src/markdown/parse-with-fallback.ts+++ b/packages/core/src/markdown/parse-with-fallback.ts@@ -168,6 +168,7 @@ export function parseRecursive(}}+interface VFilePlace {offset?: number;start?: { offset?: number };@@ -186,6 +187,7 @@ function extractErrorOffset(err: unknown): number | undefined {return undefined;}+interface Region {start: number;end: number;@@ -209,6 +211,7 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {return null;}+export interface TagEvent {kind: 'open' | 'close' | 'self-close';name: string;@@ -355,6 +358,7 @@ function findFallbackRegion(src: string, errorOffset: number): Region {return { start: blockStart, end: blockEnd };}+interface SourceBlock {src: string;start: number;@@ -452,6 +456,7 @@ 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 e6ab4fd57..43d420187 100644--- a/packages/core/src/markdown/parser-drop-closure.ts+++ b/packages/core/src/markdown/parser-drop-closure.ts@@ -1,3 +1,4 @@+export type DroppedTokenAdjudication =| {kind: 'format-dof-axis';diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.tsindex 449e6f12f..5af2f05f5 100644--- a/packages/core/src/markdown/pipeline.ts+++ b/packages/core/src/markdown/pipeline.ts@@ -1,3 +1,4 @@+import {type FromProseMirrorOptions,fromProseMirror,diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.tsindex 91cdf658f..ccf06e94d 100644--- a/packages/core/src/markdown/position-aware-join.ts+++ b/packages/core/src/markdown/position-aware-join.ts@@ -1,3 +1,4 @@+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 0f399d34c..e5b4c9eba 100644--- a/packages/core/src/markdown/position-slice.ts+++ b/packages/core/src/markdown/position-slice.ts@@ -1,3 +1,4 @@+import type { Nodes, Root } from 'mdast';import { visit } from 'unist-util-visit';import type { VFile } from 'vfile';@@ -476,7 +477,8 @@ 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 db10fa54b..ca225ce9b 100644--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts@@ -1,3 +1,4 @@+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 34068d103..3a2524a9a 100644--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts@@ -1,3 +1,4 @@+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 93151d43b..2279a0189 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts@@ -1,3 +1,4 @@+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 188f02d83..a0f467c42 100644--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts@@ -1,3 +1,4 @@+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 4ba2c3418..4e8542a21 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts@@ -1,3 +1,4 @@+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 1a74b1272..a3c96b24a 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts@@ -1,3 +1,4 @@+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 de35e7b79..e95cf43d6 100644--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts@@ -1,3 +1,4 @@+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 b4be1b2ea..ffdb4d5b5 100644--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts@@ -1,3 +1,4 @@+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 3c8d88b7c..e2a96d1a7 100644--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts@@ -1,3 +1,4 @@+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 cf2c9da8e..0389575ac 100644--- a/packages/core/src/markdown/resolve-image-url.ts+++ b/packages/core/src/markdown/resolve-image-url.ts@@ -1,3 +1,4 @@+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 4d3250d3a..8be632ba4 100644--- a/packages/core/src/markdown/safe-url.ts+++ b/packages/core/src/markdown/safe-url.ts@@ -1,3 +1,4 @@+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 0dd54070e..96304e7a5 100644--- a/packages/core/src/markdown/serialize-fidelity.test-helper.ts+++ b/packages/core/src/markdown/serialize-fidelity.test-helper.ts@@ -1,3 +1,4 @@+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 7cac5b042..93798cf83 100644--- a/packages/core/src/markdown/serialize-helpers.ts+++ b/packages/core/src/markdown/serialize-helpers.ts@@ -1,3 +1,4 @@+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 b012a5aff..8c08b7a04 100644--- a/packages/core/src/markdown/single-dollar-math-promoter.ts+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts@@ -1,3 +1,4 @@+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 3e79f8cb6..959cc0bd2 100644--- a/packages/core/src/markdown/to-markdown-handlers.ts+++ b/packages/core/src/markdown/to-markdown-handlers.ts@@ -1,3 +1,4 @@+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 0f1b0f27d..6e6d73400 100644--- a/packages/core/src/markdown/underline-promoter.ts+++ b/packages/core/src/markdown/underline-promoter.ts@@ -1,3 +1,4 @@+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 1a082bda7..932d7d2a8 100644--- a/packages/core/src/markdown/unknown-mdast-guard.ts+++ b/packages/core/src/markdown/unknown-mdast-guard.ts@@ -1,3 +1,4 @@+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 d578476a7..ac9f5239b 100644--- a/packages/core/src/markdown/whitespace-char-ref.ts+++ b/packages/core/src/markdown/whitespace-char-ref.ts@@ -1,3 +1,4 @@+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 6dad26200..afd9936fe 100644--- a/packages/core/src/markdown/wiki-link-micromark.ts+++ b/packages/core/src/markdown/wiki-link-micromark.ts@@ -17,6 +17,7 @@ declare module 'micromark-util-types' {}}+const CODE_BANG = 33; // !const CODE_LBRACKET = 91; // [const CODE_RBRACKET = 93; // ]@@ -260,6 +261,7 @@ export function wikiLinkSyntax(): Extension {};}+function enterWikiLink(this: CompileContext, token: Token) {this.enter({@@ -385,6 +387,7 @@ export const wikiLinkToMarkdown: {unsafe: [{ character: '[', inConstruct: ['phrasing'] }],};+const MICROMARK_EXT = wikiLinkSyntax();export function remarkWikiLink(this: Processor) {diff --git a/packages/server/src/acp/harness-availability.test.ts b/packages/server/src/acp/harness-availability.test.tsindex 62cd9ca90..6f8e785b0 100644--- a/packages/server/src/acp/harness-availability.test.ts+++ b/packages/server/src/acp/harness-availability.test.ts@@ -1,11 +1,20 @@+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';import type { TerminalCli } from '@inkeep/open-knowledge-core';-import { describe, expect, test } from 'vitest';+import { afterEach, describe, expect, test } from 'vitest';import {ACP_AGENT_HARNESS_CLIS,createAcpHarnessAvailabilityProbe,type HarnessAvailability,} from './harness-availability.ts';+let shims: string[] = [];+afterEach(() => {+ for (const d of shims) rmSync(d, { recursive: true, force: true });+ shims = [];+});+describe('ACP harness availability', () => {test('maps the registry-backed harness agents to their real CLI ids', () => {expect(ACP_AGENT_HARNESS_CLIS).toEqual({@@ -44,6 +53,45 @@ describe('ACP harness availability', () => {expect(calls).toHaveLength(8);});+ // Availability drives defaulting, so it has to agree with what the launch+ // chain can actually start. On a machine where the harness lives only on the+ // login shell's PATH (nvm/fnm), reporting `not-found` would steer the user+ // away from an agent that works. On CI none of these CLIs are installed, so+ // every entry here exercises the fallback.+ test('a harness reachable only via the login shell reports present', async () => {+ const shimDir = mkdtempSync(join(tmpdir(), 'harness-avail-test-'));+ shims.push(shimDir);+ for (const bin of ['claude', 'codex', 'cursor-agent', 'opencode']) {+ writeFileSync(join(shimDir, bin), '#!/bin/sh\nexit 0\n', { mode: 0o755 });+ }+ const probe = createAcpHarnessAvailabilityProbe({+ resolveLoginShellPath: async () => shimDir,+ });+ expect(await probe()).toEqual({+ claude: 'present',+ codex: 'present',+ cursor: 'present',+ opencode: 'present',+ });+ });++ test('a harness missing from the login shell too stays not-found', async () => {+ const emptyDir = mkdtempSync(join(tmpdir(), 'harness-avail-test-'));+ shims.push(emptyDir);+ let consulted = 0;+ const probe = createAcpHarnessAvailabilityProbe({+ resolveLoginShellPath: async () => {+ consulted += 1;+ return emptyDir;+ },+ });+ const result = await probe();+ // Whatever this machine happens to have installed, every CLI that missed+ // the base PATH must have been given the login-shell second chance.+ const missing = Object.values(result).filter((v) => v === 'not-found').length;+ expect(consulted).toBe(missing);+ });+test('contains a rejected per-harness probe as unknown', async () => {const probe = createAcpHarnessAvailabilityProbe({probe: async (cli) => {diff --git a/packages/server/src/acp/harness-availability.ts b/packages/server/src/acp/harness-availability.tsindex 1854217ec..33836ffc8 100644--- a/packages/server/src/acp/harness-availability.ts+++ b/packages/server/src/acp/harness-availability.ts@@ -8,7 +8,9 @@*/import type { TerminalCli } from '@inkeep/open-knowledge-core';-import { AgentLaunchError, mergedEnv, preflightLaunch } from './launch.ts';+import { getLogger } from '../logger.ts';+import { AgentLaunchError, mergedEnv, preflightLaunch, withLoginShellPath } from './launch.ts';+import { getSharedLoginShellPathProvider } from './login-shell-path.ts';export type HarnessAvailability = 'present' | 'not-found' | 'unknown';@@ -35,18 +37,34 @@ export type AcpHarnessAvailability = Readonly<Partial<Record<TerminalCli, Harnesconst DEFAULT_TTL_MS = 60_000;-async function detectHarness(cli: TerminalCli): Promise<HarnessAvailability> {+async function detectHarness(+ cli: TerminalCli,+ resolveLoginShellPath: () => Promise<string | null>,+): Promise<HarnessAvailability> {+ const launch = {+ cmd: HARNESS_BINS[cli],+ args: [],+ env: mergedEnv(),+ kind: 'custom' as const,+ pathFromOverlay: false,+ };try {- await preflightLaunch({- cmd: HARNESS_BINS[cli],- args: [],- env: mergedEnv(),- kind: 'custom',- });+ await preflightLaunch(launch);return 'present';} catch (err) {- if (err instanceof AgentLaunchError && err.code === 'command-not-found') return 'not-found';- return 'unknown';+ if (!(err instanceof AgentLaunchError) || err.code !== 'command-not-found') return 'unknown';+ // Same second chance the launch chain takes, and deliberately the same+ // shared provider: reporting `not-found` for a harness that+ // `ensureLaunchable` would go on to start is worse than no signal at all,+ // because it steers defaulting away from an agent that works.+ const loginShellPath = await resolveLoginShellPath().catch(() => null);+ if (loginShellPath === null) return 'not-found';+ try {+ await preflightLaunch(withLoginShellPath(launch, loginShellPath));+ return 'present';+ } catch {+ return 'not-found';+ }}}@@ -55,9 +73,13 @@ export function createAcpHarnessAvailabilityProbe(probe?: (cli: TerminalCli) => Promise<HarnessAvailability>;now?: () => number;ttlMs?: number;+ /** Defaults to the process-shared probe the launch chain uses. */+ resolveLoginShellPath?: () => Promise<string | null>;} = {},): () => Promise<AcpHarnessAvailability> {- const probe = opts.probe ?? detectHarness;+ const resolveLoginShellPath =+ opts.resolveLoginShellPath ?? getSharedLoginShellPathProvider(getLogger('acp-harness'));+ const probe = opts.probe ?? ((cli: TerminalCli) => detectHarness(cli, resolveLoginShellPath));const now = opts.now ?? Date.now;const ttlMs = opts.ttlMs ?? DEFAULT_TTL_MS;const harnesses = [...new Set(Object.values(ACP_AGENT_HARNESS_CLIS))].filter(diff --git a/packages/server/src/acp/launch.test.ts b/packages/server/src/acp/launch.test.tsindex 915065e0f..3482ed2e7 100644--- a/packages/server/src/acp/launch.test.ts+++ b/packages/server/src/acp/launch.test.ts@@ -15,7 +15,9 @@ import { OK_HOSTED_AGENT_ENV } from '@inkeep/open-knowledge-core';import { afterEach, describe, expect, test } from 'vitest';import {AgentLaunchError,+ isPathQualified,mergedEnv,+ overlaySetsPath,preflightLaunch,type ResolvedLaunch,resolveWindowsCommand,@@ -23,6 +25,7 @@ import {terminateAgentTree,windowsCmdWrap,withHostedAgentMarker,+ withLoginShellPath,} from './launch.ts';describe('mergedEnv PATH augmentation', () => {@@ -44,6 +47,49 @@ describe('mergedEnv PATH augmentation', () => {test('preserves non-PATH process.env entries', () => {expect(mergedEnv().HOME).toBe(process.env.HOME);});++ test('overlaySetsPath sees PATH under any spelling', () => {+ expect(overlaySetsPath({ Path: '/x' })).toBe(true);+ expect(overlaySetsPath({ PATH: '/x' })).toBe(true);+ expect(overlaySetsPath({ HOME: '/x' })).toBe(false);+ expect(overlaySetsPath(undefined)).toBe(false);+ });+});++describe('withLoginShellPath', () => {+ const key = 'PATH' in process.env ? 'PATH' : 'Path';++ test('appends the login shell PATH to the launch env, key spelling preserved', () => {+ const out = withLoginShellPath(+ { cmd: 'npx', args: [], env: { [key]: '/usr/bin' }, kind: 'npx', pathFromOverlay: false },+ `/nvm/bin${delimiter}/usr/bin`,+ );+ expect(out.env[key]).toBe(`/usr/bin${delimiter}/nvm/bin`);+ expect(out.cmd).toBe('npx');+ });++ test('leaves the rest of the env untouched', () => {+ const out = withLoginShellPath(+ {+ cmd: 'npx',+ args: ['-y', 'pkg'],+ env: { [key]: '/usr/bin', TOKEN: 'keep' },+ kind: 'npx',+ pathFromOverlay: false,+ },+ '/nvm/bin',+ );+ expect(out.env.TOKEN).toBe('keep');+ expect(out.args).toEqual(['-y', 'pkg']);+ });+});++describe('isPathQualified', () => {+ test('a bare name is PATH-searched; a located command is not', () => {+ expect(isPathQualified('npx')).toBe(false);+ expect(isPathQualified('./agent')).toBe(true);+ expect(isPathQualified('/opt/agent/bin/agent')).toBe(true);+ });});const isAlive = (pid: number): boolean => {@@ -68,6 +114,7 @@ const launchFor = (script: string, overlay?: Record<string, string>): ResolvedLaargs: [script],env: plainEnv(overlay),kind: 'custom',+ pathFromOverlay: overlaySetsPath(overlay),});async function waitFor(pred: () => boolean, ms: number, what: string): Promise<void> {@@ -139,14 +186,26 @@ describe('preflightLaunch', () => {test('a path-qualified command that exists resolves', async () => {// process.execPath is an absolute, executable path → no PATH search.await expect(- preflightLaunch({ cmd: process.execPath, args: [], env: {}, kind: 'custom' }),+ preflightLaunch({+ cmd: process.execPath,+ args: [],+ env: {},+ kind: 'custom',+ pathFromOverlay: false,+ }),).resolves.toBeUndefined();});test('a missing npx surfaces an actionable Node.js hint', async () => {// Empty PATH guarantees `npx` cannot resolve on any platform.const err = await catchErr(- preflightLaunch({ cmd: 'npx', args: ['-y', 'x'], env: { PATH: '' }, kind: 'npx' }),+ preflightLaunch({+ cmd: 'npx',+ args: ['-y', 'x'],+ env: { PATH: '' },+ kind: 'npx',+ pathFromOverlay: true,+ }),);expect(err).toBeInstanceOf(AgentLaunchError);expect((err as AgentLaunchError).code).toBe('command-not-found');@@ -155,7 +214,13 @@ describe('preflightLaunch', () => {test('a missing uvx surfaces an actionable uv hint', async () => {const err = await catchErr(- preflightLaunch({ cmd: 'uvx', args: [], env: { PATH: '' }, kind: 'uvx' }),+ preflightLaunch({+ cmd: 'uvx',+ args: [],+ env: { PATH: '' },+ kind: 'uvx',+ pathFromOverlay: true,+ }),);expect(err).toBeInstanceOf(AgentLaunchError);expect((err as AgentLaunchError).message).toContain('uv');@@ -166,14 +231,26 @@ describe('preflightLaunch', () => {const name = process.platform === 'win32' ? 'fakeagent.cmd' : 'fakeagent';writeFileSync(join(dir, name), '#!/bin/sh\nexit 0\n', { mode: 0o755 });await expect(- preflightLaunch({ cmd: 'fakeagent', args: [], env: { PATH: dir }, kind: 'custom' }),+ preflightLaunch({+ cmd: 'fakeagent',+ args: [],+ env: { PATH: dir },+ kind: 'custom',+ pathFromOverlay: true,+ }),).resolves.toBeUndefined();});test('a missing binary distribution reports the offending path', async () => {const missing = join(tmp(), 'does-not-exist-agent');const err = await catchErr(- preflightLaunch({ cmd: missing, args: [], env: {}, kind: 'binary' }),+ preflightLaunch({+ cmd: missing,+ args: [],+ env: {},+ kind: 'binary',+ pathFromOverlay: false,+ }),);expect(err).toBeInstanceOf(AgentLaunchError);expect((err as AgentLaunchError).code).toBe('command-not-found');diff --git a/packages/server/src/acp/launch.ts b/packages/server/src/acp/launch.tsindex 6aef767ed..5a5903b27 100644--- a/packages/server/src/acp/launch.ts+++ b/packages/server/src/acp/launch.ts@@ -23,6 +23,7 @@ import { augmentAgentSpawnPath, OK_DIR, OK_HOSTED_AGENT_ENV } from '@inkeep/openimport { tracedMkdir, tracedRename, tracedRm } 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 type { ManagedRuntime } from './managed-runtime.ts';import type { CustomAgentEntry, RegistryAgent, RegistryBinaryTarget } from './registry.ts';@@ -31,6 +32,13 @@ export interface ResolvedLaunch {args: string[];env: Record<string, string>;kind: 'npx' | 'uvx' | 'binary' | 'custom';+ /**+ * True when this launch's PATH came from a manifest / custom-agent `env`+ * overlay rather than the repaired inherited base. Such a PATH is a spawn-env+ * contract that wins verbatim (see {@link mergedEnv}), so the login-shell+ * fallback must leave it alone — the same reason base augmentation does.+ */+ pathFromOverlay: boolean;}export class AgentLaunchError extends Error {@@ -87,6 +95,11 @@ export function mergedEnv(overlay?: Record<string, string>): Record<string, strireturn { ...base, ...overlay };}+/** True when `overlay` sets PATH under any spelling — see {@link ResolvedLaunch.pathFromOverlay}. */+export function overlaySetsPath(overlay?: Record<string, string>): boolean {+ return overlay !== undefined && Object.keys(overlay).some((k) => k.toLowerCase() === 'path');+}+/*** Stamp the hosted-agent marker onto an agent's spawn env.*@@ -124,6 +137,7 @@ export async function resolveRegistryLaunch(args: ['-y', dist.npx.package, ...(dist.npx.args ?? [])],env: mergedEnv(dist.npx.env),kind: 'npx',+ pathFromOverlay: overlaySetsPath(dist.npx.env),};}if (dist.uvx !== undefined) {@@ -132,6 +146,7 @@ export async function resolveRegistryLaunch(args: [dist.uvx.package, ...(dist.uvx.args ?? [])],env: mergedEnv(dist.uvx.env),kind: 'uvx',+ pathFromOverlay: overlaySetsPath(dist.uvx.env),};}if (dist.binary !== undefined) {@@ -151,7 +166,13 @@ export async function resolveRegistryLaunch(`${agent.name} manifest cmd escapes its archive`,);}- return { cmd, args: [...(target.args ?? [])], env: mergedEnv(target.env), kind: 'binary' };+ return {+ cmd,+ args: [...(target.args ?? [])],+ env: mergedEnv(target.env),+ kind: 'binary',+ pathFromOverlay: overlaySetsPath(target.env),+ };}throw new AgentLaunchError('no-distribution', `${agent.name} has no supported distribution`);}@@ -162,6 +183,7 @@ export function resolveCustomLaunch(entry: CustomAgentEntry): ResolvedLaunch {args: [...(entry.args ?? [])],env: mergedEnv(entry.env),kind: 'custom',+ pathFromOverlay: overlaySetsPath(entry.env),};}@@ -181,12 +203,26 @@ export function rewriteLaunchToManagedRuntime(): ResolvedLaunch {const env = { ...launch.env };env[pathKey(env)] = prependPath(runtime.binDir, envPath(env));+ const pathFromOverlay = launch.pathFromOverlay;if (runtime.kind === 'node') {env.npm_config_cache = runtime.cacheDir;- return { cmd: runtime.npxBin, args: [...launch.args], env, kind: 'npx' };+ return { cmd: runtime.npxBin, args: [...launch.args], env, kind: 'npx', pathFromOverlay };}env.UV_CACHE_DIR = runtime.cacheDir;- return { cmd: runtime.uvxBin, args: [...launch.args], env, kind: 'uvx' };+ return { cmd: runtime.uvxBin, args: [...launch.args], env, kind: 'uvx', pathFromOverlay };+}++/**+ * Rewrite a launch to also search the login shell's PATH — used when the+ * inherited-plus-augmented PATH couldn't resolve the command but the user's+ * terminal can (a version manager whose bin dir no static list can name; see+ * `login-shell-path.ts`). Appended, never prepended, so every directory that+ * already resolved keeps resolving to the same binary.+ */+export function withLoginShellPath(launch: ResolvedLaunch, loginShellPath: string): ResolvedLaunch {+ const env = { ...launch.env };+ env[pathKey(env)] = mergeLoginShellPath(envPath(env), loginShellPath, delimiter);+ return { ...launch, env };}/** The env's PATH key (Windows spells it `Path`), for case-preserving overwrite. */@@ -312,11 +348,20 @@ export function envPath(env: Record<string, string>): string | undefined {return process.env.PATH;}+/**+ * True when `cmd` names a location rather than a name to search for — binary+ * distributions and path-qualified custom agents. Such a command is checked in+ * place, so no amount of PATH repair changes its verdict.+ */+export function isPathQualified(cmd: string): boolean {+ const win = process.platform === 'win32';+ return isAbsolute(cmd) || cmd.includes('/') || (win && cmd.includes('\\'));+}+/** Resolve `cmd` to an executable the way the OS would at spawn time. */async function isLaunchable(cmd: string, pathEnv: string | undefined): Promise<boolean> {const win = process.platform === 'win32';- // A path-qualified command is checked in place — no PATH search.- if (isAbsolute(cmd) || cmd.includes('/') || (win && cmd.includes('\\'))) {+ if (isPathQualified(cmd)) {return isExecutableFile(cmd);}const exts = windiff --git a/packages/server/src/acp/login-shell-path.test.ts b/packages/server/src/acp/login-shell-path.test.tsnew file mode 100644index 000000000..2e76155bc--- /dev/null+++ b/packages/server/src/acp/login-shell-path.test.ts@@ -0,0 +1,358 @@+/**+ * The login-shell PATH probe: sentinel parsing, append-only merge semantics,+ * the skip conditions that must never spawn a shell, and the real-subprocess+ * rung — a fake `$SHELL` that proves stdout capture, the timeout kill, and+ * that the probe script itself is valid POSIX shell.+ */++import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { delimiter, join } from 'node:path';+import { afterEach, describe, expect, test } from 'vitest';+import { getLogger } from '../logger.ts';+import {+ createLoginShellPathProvider,+ loginShellProbeArgs,+ mergeLoginShellPath,+ parseLoginShellPath,+} from './login-shell-path.ts';++const log = getLogger('login-shell-path-test');++let dirs: string[] = [];+function tmp(): string {+ const d = mkdtempSync(join(tmpdir(), 'login-shell-path-test-'));+ dirs.push(d);+ return d;+}+afterEach(() => {+ for (const d of dirs) rmSync(d, { recursive: true, force: true });+ dirs = [];+});++/** A stand-in `$SHELL` that ignores its args and prints `body`. */+function fakeShell(body: string): string {+ const dir = tmp();+ const path = join(dir, 'fake-shell');+ writeFileSync(path, `#!/bin/sh\n${body}\n`, { mode: 0o755 });+ return path;+}++const wrap = (path: string): string => `__OK_PATH_BEGIN__${path}__OK_PATH_END__`;++describe('parseLoginShellPath', () => {+ test('extracts the fenced PATH', () => {+ expect(parseLoginShellPath(wrap('/a:/b'))).toBe('/a:/b');+ });++ test('survives a profile that printed a banner first', () => {+ expect(parseLoginShellPath(`Welcome!\nnvm: using v22\n${wrap('/a:/b')}`)).toBe('/a:/b');+ });++ test('trims the newline printenv leaves behind', () => {+ expect(parseLoginShellPath('__OK_PATH_BEGIN__/a:/b\n__OK_PATH_END__')).toBe('/a:/b');+ });++ test('prefers the last begin sentinel — an echoed command line must not win', () => {+ expect(parseLoginShellPath(`+ printf %s __OK_PATH_BEGIN__\n${wrap('/real')}`)).toBe('/real');+ });++ test('null when a sentinel is missing or the value is empty', () => {+ expect(parseLoginShellPath('')).toBeNull();+ expect(parseLoginShellPath('__OK_PATH_BEGIN__/a:/b')).toBeNull();+ expect(parseLoginShellPath('shell: bad flag')).toBeNull();+ expect(parseLoginShellPath(wrap(' '))).toBeNull();+ });+});++describe('mergeLoginShellPath', () => {+ test('appends only what is new, keeping existing entries first', () => {+ expect(+ mergeLoginShellPath('/usr/bin:/bin', '/bin:/home/u/.nvm/versions/node/v24/bin', ':'),+ ).toBe('/usr/bin:/bin:/home/u/.nvm/versions/node/v24/bin');+ });++ test('an existing entry keeps winning — order is never rewritten', () => {+ // /usr/bin holds a `node` too; appending must not let the shell's copy take over.+ expect(mergeLoginShellPath('/usr/bin', '/opt/other/bin:/usr/bin', ':')).toBe(+ '/usr/bin:/opt/other/bin',+ );+ });++ test('handles an absent or empty current PATH', () => {+ expect(mergeLoginShellPath(undefined, '/a:/b', ':')).toBe('/a:/b');+ expect(mergeLoginShellPath('', '/a', ':')).toBe('/a');+ });++ test('drops empty segments rather than emitting a cwd-searching entry', () => {+ expect(mergeLoginShellPath('/a:', '/b::/c', ':')).toBe('/a:/b:/c');+ });+});++describe('createLoginShellPathProvider (skip conditions)', () => {+ const neverRuns = () => {+ throw new Error('probe must not spawn');+ };++ test('windows never probes — its PATH comes from the registry, not a shell', async () => {+ const provider = createLoginShellPathProvider({+ log,+ platform: 'win32',+ shell: 'C:\\Windows\\system32\\cmd.exe',+ runProbe: neverRuns,+ });+ await expect(provider()).resolves.toBeNull();+ });++ test('no $SHELL → no probe', async () => {+ const provider = createLoginShellPathProvider({+ log,+ platform: 'darwin',+ shell: undefined,+ runProbe: neverRuns,+ });+ await expect(provider()).resolves.toBeNull();+ });++ test('a login-refusing shell is not worth the latency', async () => {+ const provider = createLoginShellPathProvider({+ log,+ platform: 'linux',+ shell: '/usr/sbin/nologin',+ runProbe: neverRuns,+ });+ await expect(provider()).resolves.toBeNull();+ });++ test('probes once and reuses the answer', async () => {+ let calls = 0;+ const provider = createLoginShellPathProvider({+ log,+ platform: 'darwin',+ shell: '/bin/zsh',+ runProbe: async () => {+ calls += 1;+ return wrap('/a:/b');+ },+ });+ expect(await provider()).toBe('/a:/b');+ expect(await provider()).toBe('/a:/b');+ expect(calls).toBe(1);+ });++ test('a probe that throws degrades to null instead of failing the launch', async () => {+ const provider = createLoginShellPathProvider({+ log,+ platform: 'darwin',+ shell: '/bin/zsh',+ runProbe: async () => {+ throw new Error('spawn EMFILE');+ },+ });+ await expect(provider()).resolves.toBeNull();+ });++ test('passes the login + interactive flags — zsh sources both startup sets from one run', () => {+ expect(loginShellProbeArgs().slice(0, 3)).toEqual(['-l', '-i', '-c']);+ });+});++describe('createLoginShellPathProvider (bash needs both startup branches)', () => {+ /** Records the argv of each capture and answers per-invocation. */+ const recordingProbe = (answers: Array<string | null>) => {+ const seen: string[][] = [];+ const runProbe = async (_shell: string, args: readonly string[]) => {+ seen.push([...args]);+ return answers[seen.length - 1] ?? null;+ };+ return { seen, runProbe };+ };++ test('zsh is captured once — its login and interactive gates are additive', async () => {+ const { seen, runProbe } = recordingProbe([wrap('/zsh/bin')]);+ const provider = createLoginShellPathProvider({+ log,+ platform: 'darwin',+ shell: '/bin/zsh',+ runProbe,+ });+ expect(await provider()).toBe('/zsh/bin');+ expect(seen).toEqual([['-l', '-i', '-c', expect.any(String)]]);+ });++ test('bash gets a second, non-login capture — `-l` locks it out of .bashrc', async () => {+ // The nvm shape under bash: `.bash_profile` holds one dir, `.bashrc` holds+ // the nvm one, and only the second capture can see the latter.+ const { seen, runProbe } = recordingProbe([wrap('/usr/bin'), wrap('/home/u/.nvm/v24/bin')]);+ const provider = createLoginShellPathProvider({+ log,+ platform: 'linux',+ shell: '/bin/bash',+ runProbe,+ });+ expect(await provider()).toBe(`/usr/bin${delimiter}/home/u/.nvm/v24/bin`);+ expect(seen[0]?.slice(0, 3)).toEqual(['-l', '-i', '-c']);+ expect(seen[1]?.slice(0, 2)).toEqual(['-i', '-c']);+ });++ test('bash still answers when only one of the two captures works', async () => {+ const loginOnly = createLoginShellPathProvider({+ log,+ platform: 'linux',+ shell: '/bin/bash',+ runProbe: recordingProbe([wrap('/only/login'), null]).runProbe,+ });+ expect(await loginOnly()).toBe('/only/login');++ const interactiveOnly = createLoginShellPathProvider({+ log,+ platform: 'linux',+ shell: '/bin/bash',+ runProbe: recordingProbe([null, wrap('/only/rc')]).runProbe,+ });+ expect(await interactiveOnly()).toBe('/only/rc');+ });++ test('sh takes the bash path — it is bash in POSIX mode on macOS', async () => {+ const { seen, runProbe } = recordingProbe([wrap('/a'), wrap('/b')]);+ const provider = createLoginShellPathProvider({+ log,+ platform: 'darwin',+ shell: '/bin/sh',+ runProbe,+ });+ await provider();+ expect(seen).toHaveLength(2);+ });+});++describe('createLoginShellPathProvider (failed probes stay retryable)', () => {+ test('a real answer is memoized for good', async () => {+ let calls = 0;+ const provider = createLoginShellPathProvider({+ log,+ platform: 'darwin',+ shell: '/bin/zsh',+ runProbe: async () => {+ calls += 1;+ return wrap('/a');+ },+ });+ expect(await provider()).toBe('/a');+ expect(await provider()).toBe('/a');+ expect(calls).toBe(1);+ });++ test('a failure does not disable the fallback for the life of the server', async () => {+ let calls = 0;+ let clock = 1_000_000;+ const provider = createLoginShellPathProvider({+ log,+ platform: 'darwin',+ shell: '/bin/zsh',+ now: () => clock,+ runProbe: async () => {+ calls += 1;+ // A transient failure (a shell that hung once), then a real answer.+ return calls === 1 ? null : wrap('/recovered');+ },+ });+ expect(await provider()).toBeNull();+ // Inside the backoff the failure is reused, so a burst of launches doesn't+ // re-pay the timeout.+ expect(await provider()).toBeNull();+ expect(calls).toBe(1);++ clock += 60_001;+ expect(await provider()).toBe('/recovered');+ expect(calls).toBe(2);+ });++ test('a structural skip never spawns, backoff or not', async () => {+ let clock = 0;+ const provider = createLoginShellPathProvider({+ log,+ platform: 'darwin',+ shell: undefined,+ now: () => clock,+ runProbe: () => {+ throw new Error('probe must not spawn');+ },+ });+ expect(await provider()).toBeNull();+ clock += 60_001;+ expect(await provider()).toBeNull();+ });+});++describe.skipIf(process.platform === 'win32')(+ 'createLoginShellPathProvider (real subprocess)',+ () => {+ test('captures the PATH a real shell prints, banner and all', async () => {+ const shell = fakeShell(+ `echo "Last login: today"\nprintf %s '${wrap('/opt/fake/bin:/usr/bin')}'`,+ );+ const provider = createLoginShellPathProvider({ log, platform: 'darwin', shell });+ await expect(provider()).resolves.toBe('/opt/fake/bin:/usr/bin');+ });++ test('the probe script is valid shell — /bin/sh answers with a real PATH', async () => {+ const provider = createLoginShellPathProvider({ log, platform: 'darwin', shell: '/bin/sh' });+ const value = await provider();+ // The exact PATH depends on the machine's profiles; that it parsed at all+ // is the contract under test (printf + printenv + the sentinels).+ expect(value).not.toBeNull();+ expect(value).toContain('/');+ });++ test('a shell that hangs is killed and yields no verdict', async () => {+ const provider = createLoginShellPathProvider({+ log,+ platform: 'darwin',+ shell: fakeShell('sleep 30'),+ timeoutMs: 250,+ });+ const started = Date.now();+ await expect(provider()).resolves.toBeNull();+ expect(Date.now() - started).toBeLessThan(5_000);+ });++ test('a shell that cannot be executed yields no verdict', async () => {+ const provider = createLoginShellPathProvider({+ log,+ platform: 'darwin',+ shell: join(tmp(), 'does-not-exist'),+ });+ await expect(provider()).resolves.toBeNull();+ });++ // The reason the bash branch exists, against real bash rather than a fake:+ // a PATH entry that only `.bashrc` adds is invisible to `-l -i` (bash takes+ // the login branch and never reads it), so collapsing back to a single+ // capture would silently stop rescuing bash's default nvm setup.+ //+ // Only the `.bashrc` half is asserted. Which login profile a given bash+ // reads — and whether it reads one at all under `-l -i -c` — varies with+ // the distro's build and its /etc/profile, so pinning that would make this+ // a test of the runner rather than of the union.+ test('real bash: a .bashrc-only directory is reached', async () => {+ const home = tmp();+ writeFileSync(join(home, '.bash_profile'), 'export PATH="/from/profile:$PATH"\n');+ writeFileSync(join(home, '.bashrc'), 'export PATH="/from/bashrc:$PATH"\n');+ const realHome = process.env.HOME;+ process.env.HOME = home;+ try {+ const captured = await createLoginShellPathProvider({+ log,+ platform: 'darwin',+ shell: '/bin/bash',+ })();+ expect(captured).not.toBeNull();+ expect((captured ?? '').split(delimiter)).toContain('/from/bashrc');+ } finally {+ if (realHome === undefined) delete process.env.HOME;+ else process.env.HOME = realHome;+ }+ });+ },+);diff --git a/packages/server/src/acp/login-shell-path.ts b/packages/server/src/acp/login-shell-path.tsnew file mode 100644index 000000000..8f060d9f5--- /dev/null+++ b/packages/server/src/acp/login-shell-path.ts@@ -0,0 +1,318 @@+/**+ * Login-shell PATH capture — the last thing tried before OK offers to download+ * a managed runtime.+ *+ * `mergedEnv` repairs a GUI-launched server's launchd-minimal PATH by+ * appending a static list of well-known tool and package-manager-global+ * directories (`augmentAgentSpawnPath`). No static list can express a version+ * manager that exports no stable directory: nvm keeps the active Node under+ * `~/.nvm/versions/node/<version>/bin` and only a shell function puts it on+ * PATH, and fnm's directory is per-shell and ephemeral+ * (`fnm_multishells/<pid>_<ts>/bin`). On those machines `npx` runs fine in a+ * terminal yet is invisible to a Dock-launched OK, so the launch would offer+ * to download a second Node the user already has.+ *+ * So before that offer, ask the login shell what PATH it has. Capturing the+ * whole PATH rather than just resolving the binary is load-bearing: npm ships+ * `npx` with a `#!/usr/bin/env node` shebang, so an absolute path to `npx`+ * still fails unless its sibling `node` is resolvable too. Appending the+ * directory that holds both fixes the launch and every nested resolution the+ * agent performs afterwards.+ *+ * This does NOT displace static augmentation, for the reasons `git-spawn-path`+ * gives (deterministic, no interaction with user shell configs, identical in+ * dev and packaged builds). It is scoped to the moment those properties stop+ * mattering — a launch that has already failed, where the alternative is a+ * download prompt. One probe per server, timeout-bounded, and never on the+ * happy path.+ *+ * Running the user's shell config is not a new posture: the docked terminal+ * already spawns `$SHELL -l -i`, so anything a profile does here it already+ * does when the user opens a terminal in OK. Note the sibling probes that+ * share this argv shape — `desktop/src/main/claude-readiness.ts` (CLI-on-PATH+ * readiness) and `desktop/src/utility/pty-host.ts` (the docked terminal) —+ * both inherit the bash caveat documented on `interactiveShellProbeArgs`+ * below: under bash, `-l -i` reaches `.bash_profile` but never `.bashrc`.+ */++import { spawn } from 'node:child_process';+import { delimiter } from 'node:path';+import type { PinoLogger } from '../logger.ts';++/** How long the login shell gets to answer before the probe is abandoned. */+const LOGIN_SHELL_PROBE_TIMEOUT_MS = 5_000;++/** Cap on captured stdout — a misbehaving profile must not grow the heap. */+const MAX_PROBE_STDOUT_BYTES = 512 * 1024;++const PATH_BEGIN = '__OK_PATH_BEGIN__';+const PATH_END = '__OK_PATH_END__';++/**+ * Probe script. `printenv PATH` (not `echo $PATH`) is deliberate: it prints+ * the colon-joined value the shell EXPORTS to children, which is what a spawn+ * inherits, and it reads correctly under fish — where `$PATH` is a list that a+ * quoted expansion would join with spaces. The sentinels let the value be+ * recovered from stdout that a login profile has already written to (banners,+ * version-manager chatter).+ */+const PROBE_SCRIPT = `printf %s ${PATH_BEGIN}; printenv PATH; printf %s ${PATH_END}`;++/**+ * `-l -i` matches the docked terminal's own `$SHELL -l -i` (pty-host). Under+ * zsh — macOS's default since Catalina — the startup gates are additive, so+ * one invocation sources `.zprofile` AND `.zshrc`, which is where a version+ * manager initializes itself.+ */+export function loginShellProbeArgs(): readonly string[] {+ return ['-l', '-i', '-c', PROBE_SCRIPT];+}++/**+ * The second capture, for {@link SPLIT_STARTUP_SHELLS}. bash's login and+ * non-login startup branches are mutually EXCLUSIVE: given `-l` it reads+ * `.bash_profile` and never `.bashrc`, no matter that `-i` is also present.+ * Since nvm's installer writes to `.bashrc` by default, the login capture+ * alone misses bash's most common nvm setup entirely — the probe would return+ * a well-formed PATH that simply omits the nvm directory. Dropping `-l` is+ * what reaches that file.+ */+function interactiveShellProbeArgs(): readonly string[] {+ return ['-i', '-c', PROBE_SCRIPT];+}++/**+ * Shells needing both captures because their login and interactive startup+ * files are mutually exclusive (see {@link interactiveShellProbeArgs}). zsh+ * and fish source both sets from one invocation, so they pay for one spawn.+ * `sh` is here because it is bash in POSIX mode on macOS.+ */+const SPLIT_STARTUP_SHELLS = new Set(['bash', 'sh']);++/**+ * Recover the PATH from probe stdout, or null when the sentinels are absent+ * (probe died early, shell refused `-c`) or fenced an empty value.+ *+ * Scans from the LAST begin sentinel so a profile that echoed the command line+ * to stdout doesn't win over the real output.+ */+export function parseLoginShellPath(stdout: string): string | null {+ const begin = stdout.lastIndexOf(PATH_BEGIN);+ if (begin === -1) return null;+ const from = begin + PATH_BEGIN.length;+ const end = stdout.indexOf(PATH_END, from);+ if (end === -1) return null;+ const value = stdout.slice(from, end).trim();+ return value === '' ? null : value;+}++/**+ * Append the login shell's PATH entries to `current`, keeping `current`'s+ * entries first and dropping duplicates. Append-only for the same reason+ * `git-spawn-path` appends: an entry already on PATH keeps winning, so this+ * can only ADD resolutions, never redirect an existing one to a different+ * binary.+ */+export function mergeLoginShellPath(+ current: string | undefined,+ loginShellPath: string,+ delim: string,+): string {+ const entries = (current ?? '').split(delim).filter((e) => e !== '');+ const seen = new Set(entries);+ for (const entry of loginShellPath.split(delim)) {+ if (entry === '' || seen.has(entry)) continue;+ seen.add(entry);+ entries.push(entry);+ }+ return entries.join(delim);+}++/** Shells that exist to refuse a session — probing them is pure latency. */+const NON_INTERACTIVE_SHELLS = new Set(['false', 'nologin', 'sync']);++/** Runs the probe and resolves its stdout, or null if it produced no verdict. */+type RunLoginShellProbe = (+ shell: string,+ args: readonly string[],+ timeoutMs: number,+) => Promise<string | null>;++export interface LoginShellPathDeps {+ log: PinoLogger;+ /** Defaults to `process.platform`. */+ platform?: NodeJS.Platform;+ /** Defaults to `process.env.SHELL`. */+ shell?: string | undefined;+ timeoutMs?: number;+ /** Test seam — defaults to a real `spawn`. */+ runProbe?: RunLoginShellProbe;+ /** Test seam for the failed-probe backoff clock — defaults to `Date.now`. */+ now?: () => number;+}++/**+ * Spawn the login shell and collect stdout. Never rejects: a spawn that throws+ * (resource exhaustion), errors (ENOENT/EACCES on `$SHELL`), or outlives the+ * timeout (a profile waiting on input) resolves null, which the caller treats+ * as "no verdict" — never as "the user has no npx".+ */+const spawnLoginShellProbe: RunLoginShellProbe = (shell, args, timeoutMs) =>+ new Promise((resolvePromise) => {+ let child: ReturnType<typeof spawn>;+ try {+ child = spawn(shell, [...args], {+ // stdin ignored: a profile that reads from stdin must hit EOF rather+ // than block until the timeout. stderr ignored: profile noise is not+ // ours to surface.+ stdio: ['ignore', 'pipe', 'ignore'],+ windowsHide: true,+ });+ } catch {+ resolvePromise(null);+ return;+ }+ let out = '';+ let settled = false;+ const finish = (value: string | null): void => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ resolvePromise(value);+ };+ const timer = setTimeout(() => {+ child.kill('SIGKILL');+ finish(null);+ }, timeoutMs);+ timer.unref?.();+ child.stdout?.setEncoding('utf8');+ child.stdout?.on('data', (chunk: string) => {+ if (out.length >= MAX_PROBE_STDOUT_BYTES) return;+ out += chunk;+ });+ child.on('error', () => finish(null));+ // Read stdout regardless of exit code: a profile that ends with a non-zero+ // status still printed a usable PATH before it got there.+ child.on('close', () => finish(out));+ });++/**+ * How long a probe that produced no verdict is allowed to suppress the next+ * one. Matches `harness-availability.ts`'s TTL for the same reason: repeated+ * shell startups on every failing launch are wasteful, but a permanent cache+ * is worse (see the provider's note on transient failures).+ */+const FAILED_PROBE_RETRY_MS = 60_000;++/** One capture. Null when the shell produced no parsable PATH. */+async function captureShellPath(+ deps: LoginShellPathDeps,+ shell: string,+ args: readonly string[],+ timeoutMs: number,+ runProbe: RunLoginShellProbe,+): Promise<string | null> {+ // `elapsed` is the only thing that separates the failure modes downstream: a+ // value near `timeoutMs` means the shell hung (and the launch it was+ // rescuing paid that latency), where a near-zero one means the shell never+ // ran at all (missing/unexecutable `$SHELL`, resource exhaustion).+ const startedAt = Date.now();+ const stdout = await runProbe(shell, args, timeoutMs).catch(() => null);+ const elapsed = Date.now() - startedAt;+ if (stdout === null) {+ deps.log.debug({ shell, args, elapsed }, '[login-shell-path] probe produced no output');+ return null;+ }+ const value = parseLoginShellPath(stdout);+ if (value === null) {+ deps.log.debug({ shell, args, elapsed }, '[login-shell-path] probe output carried no PATH');+ return null;+ }+ return value;+}++/**+ * A cached login-shell PATH provider. A real answer is memoized for the life+ * of the provider (one per thread manager, so one per server), which keeps a+ * machine with several npx-distributed agents to a single shell startup rather+ * than one per launch.+ *+ * A NON-answer is deliberately not memoized the same way. Null covers two+ * unlike things: structural ("there is no shell to ask" — Windows, no+ * `$SHELL`, a login-refusing shell), which never spawns and never changes, and+ * transient (timeout, `EMFILE`, a half-executed profile), which can succeed on+ * the next try. Caching the transient case forever would let one unlucky+ * timeout disable this fallback for the entire life of a server that is+ * detached and reaped only after 30 idle minutes. So failures expire after+ * {@link FAILED_PROBE_RETRY_MS}; structural skips cost nothing to re-evaluate.+ */+export function createLoginShellPathProvider(+ deps: LoginShellPathDeps,+): () => Promise<string | null> {+ const platform = deps.platform ?? process.platform;+ const shell = deps.shell ?? process.env.SHELL;+ const timeoutMs = deps.timeoutMs ?? LOGIN_SHELL_PROBE_TIMEOUT_MS;+ const runProbe = deps.runProbe ?? spawnLoginShellProbe;+ const now = deps.now ?? Date.now;+ let answer: Promise<string | null> | null = null;+ let retryFailedAfter = 0;++ const probe = async (): Promise<string | null> => {+ if (platform === 'win32') return null;+ if (shell === undefined || shell === '') {+ deps.log.debug({}, '[login-shell-path] no $SHELL; skipping probe');+ return null;+ }+ const base = shell.slice(shell.lastIndexOf('/') + 1);+ if (NON_INTERACTIVE_SHELLS.has(base)) {+ deps.log.debug({ shell }, '[login-shell-path] login-refusing shell; skipping probe');+ return null;+ }+ const login = await captureShellPath(deps, shell, loginShellProbeArgs(), timeoutMs, runProbe);+ if (!SPLIT_STARTUP_SHELLS.has(base)) return login;+ // Union, not fallback: bash's two startup branches hold different+ // directories, and the launch may need either. Merging keeps the login+ // capture's entries first, so precedence follows the profile the user's+ // terminal would have applied last.+ const interactive = await captureShellPath(+ deps,+ shell,+ interactiveShellProbeArgs(),+ timeoutMs,+ runProbe,+ );+ if (login === null) return interactive;+ if (interactive === null) return login;+ return mergeLoginShellPath(login, interactive, delimiter);+ };++ return () => {+ if (answer !== null) return answer;+ if (now() < retryFailedAfter) return Promise.resolve(null);+ const pending = probe().catch(() => null);+ answer = pending;+ void pending.then((value) => {+ if (value !== null) return;+ // No verdict: release the memo so a later launch can try again, but not+ // before the backoff — a shell that hangs must not charge its timeout to+ // every launch in a burst.+ answer = null;+ retryFailedAfter = now() + FAILED_PROBE_RETRY_MS;+ });+ return pending;+ };+}++let sharedProvider: (() => Promise<string | null>) | null = null;++/**+ * The process-wide provider. Both consumers — the launch chain's retry and the+ * harness-availability probe — must agree on what the user's PATH is, or the+ * UI reports an agent as missing that the launch chain can in fact start. One+ * provider also means one shell startup per process rather than one per+ * caller. Tests inject their own provider instead of touching this.+ */+export function getSharedLoginShellPathProvider(log: PinoLogger): () => Promise<string | null> {+ sharedProvider ??= createLoginShellPathProvider({ log });+ return sharedProvider;+}diff --git a/packages/server/src/acp/managed-runtime-flow.integration.test.ts b/packages/server/src/acp/managed-runtime-flow.integration.test.tsindex 80cef0567..2eb51d535 100644--- a/packages/server/src/acp/managed-runtime-flow.integration.test.ts+++ b/packages/server/src/acp/managed-runtime-flow.integration.test.ts@@ -107,6 +107,7 @@ function makeManager(opts: {runtimeRoot: string;consentHome: string;fetchImpl: typeof fetch;+ resolveLoginShellPath?: () => Promise<string | null>;}): AcpThreadManager {const manager = new AcpThreadManager({contentDir: opts.contentDir,@@ -122,6 +123,7 @@ function makeManager(opts: {consentHome: opts.consentHome,fetchImpl: opts.fetchImpl,},+ resolveLoginShellPath: opts.resolveLoginShellPath,log,});managers.push(manager);@@ -267,6 +269,35 @@ describe('managed-runtime consent + download flow', () => {expect((await readRuntimeConsent(consentHome)).node).toBeUndefined();});+ test('a manifest-supplied PATH is never widened by the login shell', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const runtimeRoot = tmp();+ const consentHome = tmp();+ let probes = 0;+ const manager = makeManager({+ contentDir,+ localDir,+ runtimeRoot,+ consentHome,+ fetchImpl: fakeNodeFetch(Buffer.from('unused'), 'x'.repeat(64)),+ resolveLoginShellPath: async () => {+ probes += 1;+ return '/should/never/be/consulted';+ },+ });++ const events: ThreadEvent[] = [];+ const info = await manager.createThread({ agent: { source: 'registry', id: 'npxagent' } });+ await collect(manager, info.threadId, events);++ // NPX_AGENT pins its own PATH, which is a spawn-env contract: the launch+ // gets exactly that PATH, so the fallback must not append to it and the+ // download offer is still the right next step.+ await waitFor(() => findConsentRequest(events) !== undefined, 5_000, 'consent request');+ expect(probes).toBe(0);+ });+test('a persisted grant skips the prompt entirely', async () => {const contentDir = tmp();const localDir = tmp();diff --git a/packages/server/src/acp/thread-manager.integration.test.ts b/packages/server/src/acp/thread-manager.integration.test.tsindex 142e9af23..aa13cbe01 100644--- a/packages/server/src/acp/thread-manager.integration.test.ts+++ b/packages/server/src/acp/thread-manager.integration.test.ts@@ -63,6 +63,7 @@ function makeManager(unwatchedTurnKillMs?: number;isIgnoredPath?: (relPosix: string) => boolean;registry?: AcpRegistry;+ resolveLoginShellPath?: () => Promise<string | null>;},): AcpThreadManager {const manager = new AcpThreadManager({@@ -1748,3 +1749,62 @@ describe('AcpThreadManager prompt queueing', () => {expect(manager2.getInfo(info.threadId)?.queue).toBeUndefined();}, 40_000);});++describe.skipIf(process.platform === 'win32')('login-shell PATH fallback', () => {+ /**+ * The nvm/fnm shape: the agent's command exists, but only in a directory+ * that the inherited PATH and its static augmentation cannot name. The shim+ * dir stands in for `~/.nvm/versions/node/<v>/bin` — reachable from a+ * terminal, invisible to a Dock-launched server.+ */+ test('launches a command only the login shell can resolve', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const shimDir = tmp();+ const command = `ok-login-shell-agent-${process.pid}`;+ writeFileSync(join(shimDir, command), `#!/bin/sh\nexec node ${EXAMPLE_AGENT} "$@"\n`, {+ mode: 0o755,+ });+ writeFileSync(+ join(localDir, 'acp-agents.json'),+ JSON.stringify([{ id: 'shell-agent', name: 'Shell Agent', command }]),+ );++ const manager = makeManager(contentDir, localDir, {+ resolveLoginShellPath: async () => shimDir,+ });+ const info = await manager.createThread({ agent: { source: 'custom', id: 'shell-agent' } });+ await manager.subscribe(info.threadId, 0, () => {});+ // Reaching 'ready' means preflight, spawn, and the ACP handshake all ran+ // against a binary that only the injected login-shell PATH could find.+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'ready');+ }, 30_000);++ test('a command missing from the login shell too still fails with the install hint', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ writeFileSync(+ join(localDir, 'acp-agents.json'),+ JSON.stringify([+ { id: 'absent-agent', name: 'Absent Agent', command: `ok-absent-${process.pid}` },+ ]),+ );++ const manager = makeManager(contentDir, localDir, {+ resolveLoginShellPath: async () => tmp(),+ });+ const seen: ThreadEvent[] = [];+ const info = await manager.createThread({ agent: { source: 'custom', id: 'absent-agent' } });+ await manager.subscribe(info.threadId, 0, (frame: ThreadServerFrame) => {+ if (frame.op === 'event') seen.push(frame.event);+ if (frame.op === 'events') seen.push(...frame.events);+ });+ const errorEvent = (): Extract<ThreadEvent, { kind: 'status' }> | undefined =>+ seen.find(+ (e): e is Extract<ThreadEvent, { kind: 'status' }> =>+ e.kind === 'status' && e.status === 'error',+ );+ await waitUntil(() => errorEvent() !== undefined, 10_000, 'error status');+ expect(errorEvent()?.detail).toContain('was not found');+ }, 20_000);+});diff --git a/packages/server/src/acp/thread-manager.ts b/packages/server/src/acp/thread-manager.tsindex 7f459d2ba..2206658e5 100644--- a/packages/server/src/acp/thread-manager.ts+++ b/packages/server/src/acp/thread-manager.ts@@ -72,6 +72,8 @@ import { MCP_HOSTED_AGENT_HEADER } from '../mcp/agent-identity.ts';import { boundSessionUpdateForLog, coalesceChunkInto } from './event-log-bounds.ts';import {AgentLaunchError,+ envPath,+ isPathQualified,preflightLaunch,type ResolvedLaunch,resolveCustomLaunch,@@ -79,7 +81,9 @@ import {rewriteLaunchToManagedRuntime,spawnAcpAgent,terminateAgentTree,+ withLoginShellPath,} from './launch.ts';+import { getSharedLoginShellPathProvider } from './login-shell-path.ts';import {cleanupManagedRuntimeStaging,describeRuntime,@@ -320,6 +324,14 @@ export interface AcpThreadManagerOptions {fetchImpl?: typeof fetch;consentHome?: string;};+ /**+ * The user's login-shell PATH, consulted only after a PATH-resolved command+ * fails preflight and before any managed-runtime download is offered (see+ * `login-shell-path.ts`). Resolves null when there is no answer. Injected by+ * tests so the fallback's effect on a launch can be driven without spawning+ * the developer's own shell; production defaults to the real one-shot probe.+ */+ resolveLoginShellPath?: () => Promise<string | null>;log: PinoLogger;maxThreads?: number;idleReapMs?: number;@@ -354,11 +366,14 @@ export class AcpThreadManager {private readonly unwatchedTurnCancelMs: number;private readonly unwatchedTurnKillMs: number;private readonly persistence: ThreadPersistenceStore;+ private readonly resolveLoginShellPath: () => Promise<string | null>;private destroyed = false;private initialized = false;constructor(opts: AcpThreadManagerOptions) {this.opts = opts;+ this.resolveLoginShellPath =+ opts.resolveLoginShellPath ?? getSharedLoginShellPathProvider(opts.log);this.maxThreads = opts.maxThreads ?? MAX_ACP_THREADS;this.idleReapMs = opts.idleReapMs ?? DEFAULT_IDLE_REAP_MS;this.unwatchedTurnCancelMs = opts.unwatchedTurnCancelMs ?? DEFAULT_UNWATCHED_TURN_CANCEL_MS;@@ -775,12 +790,12 @@ export class AcpThreadManager {}/**- * Preflight the launch; on a missing npx/uvx interpreter, resolve a managed- * runtime (already-installed → persisted-consent → interactive consent →- * download) and return the rewritten launch. Returns null only when the- * thread closed mid-flight; throws an actionable {@link AgentLaunchError} on- * decline / unsupported platform / failed install (callers map it to an- * error status).+ * Preflight the launch; on a command the inherited PATH can't resolve, try+ * the login shell's PATH, then — for npx/uvx only — a managed runtime+ * (already-installed → persisted-consent → interactive consent → download)+ * and return the rewritten launch. Returns null only when the thread closed+ * mid-flight; throws an actionable {@link AgentLaunchError} on decline /+ * unsupported platform / failed install (callers map it to an error status).*/private async ensureLaunchable(record: ThreadRecord,@@ -791,6 +806,10 @@ export class AcpThreadManager {return launch;} catch (err) {if (!(err instanceof AgentLaunchError) || err.code !== 'command-not-found') throw err;+ // A terminal would have found it: adopt the login shell's PATH rather+ // than download a runtime (or blame the user) for a tool they have.+ const viaLoginShell = await this.retryWithLoginShellPath(launch);+ if (viaLoginShell !== null) return viaLoginShell;// Only npx/uvx have a managed fallback — a binary/custom command doesn't.if (launch.kind !== 'npx' && launch.kind !== 'uvx') throw err;const runtimeKind = runtimeForInterpreter(launch.kind);@@ -805,6 +824,41 @@ export class AcpThreadManager {}}+ /**+ * Second chance for a command the inherited PATH couldn't resolve: append+ * the login shell's PATH and preflight again. Returns the rewritten launch+ * on success, or null when the fallback doesn't apply (path-qualified+ * command, caller-supplied PATH), has nothing to add, or still can't find+ * the command — in which case the caller carries on to the managed runtime.+ */+ private async retryWithLoginShellPath(launch: ResolvedLaunch): Promise<ResolvedLaunch | null> {+ if (launch.pathFromOverlay || isPathQualified(launch.cmd)) return null;+ const loginShellPath = await this.resolveLoginShellPath().catch(() => null);+ if (loginShellPath === null) return null;+ const retry = withLoginShellPath(launch, loginShellPath);+ if (envPath(retry.env) === envPath(launch.env)) return null;+ try {+ await preflightLaunch(retry);+ } catch (err) {+ // Only a launchability verdict means "keep going to the managed runtime".+ // Anything else is a bug in the preflight itself and must stay visible.+ if (!(err instanceof AgentLaunchError)) throw err;+ // The user has a shell PATH and it still doesn't hold this command — the+ // download offer that follows is the right outcome, but an operator+ // reading the log should see that the second chance was taken and spent.+ this.opts.log.debug(+ { cmd: launch.cmd, kind: launch.kind },+ '[acp] login-shell PATH did not resolve the command either',+ );+ return null;+ }+ this.opts.log.info(+ { cmd: launch.cmd, kind: launch.kind },+ '[acp] command resolved via the login-shell PATH; skipping the managed-runtime offer',+ );+ return retry;+ }+/*** Return a managed runtime for `runtimeKind`, downloading it if the user* consents. Null means the thread closed while we waited; a throw means the