Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat: off-cwd OK server addressing (open files outside a project) (#2061)

tim-inkeep0b622c28b439
diff --git a/packages/cli/src/commands/single-file-open.ts b/packages/cli/src/commands/single-file-open.ts
index 7c9f49b7e..1375fdec3 100644
--- a/packages/cli/src/commands/single-file-open.ts
+++ b/packages/cli/src/commands/single-file-open.ts
@@ -14,6 +14,8 @@ import {
import { createRealDetectDeps, type DetectResult, detectDesktop } from './desktop-dispatch.ts';
import { createRealOpenDeps, runOpen } from './open.ts';
+const EPHEMERAL_IDLE_SHUTDOWN_MS = 10 * 60 * 1000;
+
/** Injectable surface so `cli.test.ts` can drive the dispatch matrix without a
* real desktop / server / browser. */
export interface SingleFileOpenDeps {
@@ -151,6 +153,7 @@ async function runSingleFileBrowserOpen(
singleFile: plan.canonicalFilePath,
serveContentAssets: true,
reactShellDistDir,
+ idleThresholdMs: EPHEMERAL_IDLE_SHUTDOWN_MS,
});
} catch (err) {
await teardown();
@@ -161,9 +164,14 @@ async function runSingleFileBrowserOpen(
}
const url = `http://${host}:${booted.port}/#/${encodeDocName(plan.docName)}`;
- process.stdout.write(`Opening ${plan.singleDocRelPath} in your browser: ${url}\n`);
- process.stdout.write('Press Ctrl-C to close the session.\n');
- openBrowser(url);
+ const headless = process.env.OK_SINGLE_FILE_NO_OPEN === '1';
+ if (headless) {
+ process.stdout.write(`Serving ${plan.singleDocRelPath} (headless) at: ${url}\n`);
+ } else {
+ process.stdout.write(`Opening ${plan.singleDocRelPath} in your browser: ${url}\n`);
+ process.stdout.write('Press Ctrl-C to close the session.\n');
+ openBrowser(url);
+ }
await new Promise<never>(() => {});
}
diff --git a/packages/cli/src/commands/start.test.ts b/packages/cli/src/commands/start.test.ts
index fa39830a5..565b3e6b0 100644
--- a/packages/cli/src/commands/start.test.ts
+++ b/packages/cli/src/commands/start.test.ts
@@ -28,6 +28,7 @@ import {
startCommand,
tryDescribeLockCollision,
type UiSpawnDecision,
+ withEphemeralTempDirReap,
} from './start.ts';
import { closeHttpServers, startUiServer, type UiServerHandle } from './ui.ts';
@@ -1685,3 +1686,49 @@ describe('tryDescribeLockCollision', () => {
expect(result).toBeNull();
});
});
+
+describe('withEphemeralTempDirReap', () => {
+ test('runs the inner handler, then removes the temp projectDir', async () => {
+ const order: string[] = [];
+ const handler = async () => {
+ order.push('handler');
+ };
+ const removed: string[] = [];
+ const wrapped = withEphemeralTempDirReap(handler, '/tmp/ok-ephemeral-x', async (dir) => {
+ order.push('rm');
+ removed.push(dir);
+ });
+ await wrapped();
+ expect(order).toEqual(['handler', 'rm']);
+ expect(removed).toEqual(['/tmp/ok-ephemeral-x']);
+ });
+
+ test('swallows a rm failure (best-effort) — the handler still completes', async () => {
+ let handled = false;
+ const wrapped = withEphemeralTempDirReap(
+ async () => {
+ handled = true;
+ },
+ '/tmp/ok-ephemeral-y',
+ async () => {
+ throw new Error('EBUSY');
+ },
+ );
+ await expect(wrapped()).resolves.toBeUndefined();
+ expect(handled).toBe(true);
+ });
+ test('reaps the temp dir even when the inner handler throws (finally)', async () => {
+ const removed: string[] = [];
+ const wrapped = withEphemeralTempDirReap(
+ async () => {
+ throw new Error('destroy failed');
+ },
+ '/tmp/ok-ephemeral-throw',
+ async (dir) => {
+ removed.push(dir);
+ },
+ );
+ await expect(wrapped()).rejects.toThrow('destroy failed');
+ expect(removed).toEqual(['/tmp/ok-ephemeral-throw']);
+ });
+});
diff --git a/packages/cli/src/commands/start.ts b/packages/cli/src/commands/start.ts
index 1804d957a..b46bd05ff 100644
--- a/packages/cli/src/commands/start.ts
+++ b/packages/cli/src/commands/start.ts
@@ -4,6 +4,7 @@ import {
spawn as nativeSpawn,
} from 'node:child_process';
import { closeSync, existsSync as fsExistsSync, mkdirSync as fsMkdirSync, openSync } from 'node:fs';
+import { rm } from 'node:fs/promises';
import type { Server as HttpServer } from 'node:http';
import { basename, join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
@@ -229,6 +230,26 @@ interface BuildIdleShutdownHandlerInput {
const DEFAULT_SIGTERM_GRACE_MS = SHARED_DEFAULT_SIGTERM_GRACE_MS;
const DEFAULT_SIGTERM_POLL_MS = SHARED_DEFAULT_SIGTERM_POLL_MS;
+export function withEphemeralTempDirReap(
+ handler: () => Promise<void>,
+ projectDir: string,
+ rmFn: (dir: string) => Promise<void> = (dir) => rm(dir, { recursive: true, force: true }),
+): () => Promise<void> {
+ return async () => {
+ try {
+ await handler();
+ } finally {
+ try {
+ await rmFn(projectDir);
+ } catch (err) {
+ process.stderr.write(
+ `[start] ephemeral temp dir reap failed for ${projectDir}: ${err instanceof Error ? err.message : String(err)}\n`,
+ );
+ }
+ }
+ };
+}
+
export function buildIdleShutdownHandler(
input: BuildIdleShutdownHandlerInput,
): () => Promise<void> {
@@ -458,8 +479,8 @@ export async function bootStartServer(opts: BootStartServerOptions): Promise<Boo
idleShutdownMs: idleThresholdMs,
skipAutoInit: true, // Guard already ran above; no scaffold fn to pass
...(attachUiSibling ? { spawnUiSiblingFn } : {}),
- idleShutdownHandler: (destroyServer) =>
- buildIdleShutdownHandler({
+ idleShutdownHandler: (destroyServer) => {
+ const handler = buildIdleShutdownHandler({
readUiLock: () => readUiLock(booted.lockDir),
isAlive: isProcessAlive,
killPid: (pid, signal) => {
@@ -467,7 +488,9 @@ export async function bootStartServer(opts: BootStartServerOptions): Promise<Boo
},
destroy: destroyServer,
log,
- }),
+ });
+ return ephemeral ? withEphemeralTempDirReap(handler, ephemeralProjectDir) : handler;
+ },
log,
...(opts.serveContentAssets ? { serveContentAssets: true } : {}),
...(opts.reactShellDistDir ? { reactShellDistDir: opts.reactShellDistDir } : {}),
diff --git a/packages/cli/src/utils/process-scan.ts b/packages/cli/src/utils/process-scan.ts
index dcc740f72..07bcdf537 100644
--- a/packages/cli/src/utils/process-scan.ts
+++ b/packages/cli/src/utils/process-scan.ts
@@ -1,314 +1,7 @@
-
-import { spawnSync } from 'node:child_process';
-import { existsSync, lstatSync, readdirSync } from 'node:fs';
-import { realpath } from 'node:fs/promises';
-import { basename, isAbsolute, join } from 'node:path';
-
-const SPAWN_TIMEOUT_MS = 2000;
-const LOCK_SCAN_MAX_DEPTH = 3;
-const LOCK_SCAN_MAX_ENTRIES = 2000;
-const OK_LOCK_DIR_ARG_PREFIX = '--ok-lock-dir-b64=';
-const OK_PROJECT_PATH_ARG_PREFIX = '--ok-project-path=';
-const OK_PROCESS_PGREP_QUERY =
- 'cli\\.mjs|open-knowledge|Open ?Knowledge(\\.app| Helper)|--ok-lock-dir-b64=|--ok-project-path=|(^|[ /])ok[ ]+(start|mcp|ui)([ ]|$)|packages/(cli|app)|hocuspocus|vite';
-
-const OK_PROCESS_PATTERNS: RegExp[] = [
- /cli\.mjs/,
- /(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,
- /Open ?Knowledge(?:\.app| Helper)/,
- /(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,
- /(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,
- /(^|\s)--ok-lock-dir-b64=/,
- /(^|\s)--ok-project-path=/,
-];
-
-function isOkProcess(command: string): boolean {
- return OK_PROCESS_PATTERNS.some((re) => re.test(command));
-}
-
-function extractMarkedLockDir(command: string): string | null {
- const token = command
- .trim()
- .split(/\s+/)
- .find((part) => part.startsWith(OK_LOCK_DIR_ARG_PREFIX));
- if (token == null) return null;
- const encoded = token.slice(OK_LOCK_DIR_ARG_PREFIX.length);
- if (!encoded) return null;
- try {
- const decoded = Buffer.from(encoded, 'base64url').toString('utf8');
- return isAbsolute(decoded) ? decoded : null;
- } catch {
- return null;
- }
-}
-
-function extractProjectPathArg(command: string): string | null {
- const markerIdx = command.indexOf(OK_PROJECT_PATH_ARG_PREFIX);
- if (markerIdx === -1) return null;
- const valueStart = markerIdx + OK_PROJECT_PATH_ARG_PREFIX.length;
- const rest = command.slice(valueStart);
- const nextArgIdx = rest.search(/\s--/);
- const raw = (nextArgIdx === -1 ? rest : rest.slice(0, nextArgIdx)).trim();
- if (!raw) return null;
- return isAbsolute(raw) ? raw : null;
-}
-
-interface OkProcessEntry {
- pid: number;
- command: string;
-}
-
-function parsePgrepOutput(output: string): OkProcessEntry[] {
- const entries: OkProcessEntry[] = [];
- for (const line of output.split('\n')) {
- const trimmed = line.trim();
- if (!trimmed) continue;
- const spaceIdx = trimmed.indexOf(' ');
- if (spaceIdx === -1) continue;
- const pidStr = trimmed.slice(0, spaceIdx);
- const command = trimmed.slice(spaceIdx + 1);
- const pid = Number.parseInt(pidStr, 10);
- if (!Number.isNaN(pid) && isOkProcess(command)) {
- entries.push({ pid, command });
- }
- }
- return entries;
-}
-
-function parsePsOutput(output: string): OkProcessEntry[] {
- const entries: OkProcessEntry[] = [];
- const lines = output.split('\n');
- for (let i = 1; i < lines.length; i++) {
- const line = lines[i]?.trim();
- if (!line) continue;
- const spaceIdx = line.indexOf(' ');
- if (spaceIdx === -1) continue;
- const pidStr = line.slice(0, spaceIdx);
- const command = line.slice(spaceIdx + 1).trim();
- const pid = Number.parseInt(pidStr, 10);
- if (!Number.isNaN(pid) && isOkProcess(command)) {
- entries.push({ pid, command });
- }
- }
- return entries;
-}
-
-async function findOkProcessEntries(): Promise<OkProcessEntry[]> {
- const pgrepResult = spawnSync('pgrep', ['-a', '-f', OK_PROCESS_PGREP_QUERY], {
- encoding: 'utf-8',
- timeout: SPAWN_TIMEOUT_MS,
- });
-
- const pgrepUnavailable =
- pgrepResult.error != null && (pgrepResult.error as NodeJS.ErrnoException).code === 'ENOENT';
-
- if (!pgrepUnavailable) {
- const output = pgrepResult.stdout ?? '';
- const entries = parsePgrepOutput(output);
- if (entries.length > 0 || output.trim() === '') return entries;
- }
-
- const psResult = spawnSync('ps', ['-axo', 'pid,command'], {
- encoding: 'utf-8',
- timeout: SPAWN_TIMEOUT_MS,
- });
-
- if (psResult.error != null || !psResult.stdout) {
- return [];
- }
-
- return parsePsOutput(psResult.stdout);
-}
-
-export async function findOkProcessPids(): Promise<number[]> {
- return (await findOkProcessEntries()).map((e) => e.pid);
-}
-
-export function extractOkBinaryPath(command: string): string | null {
- const tokens = command.trim().split(/\s+/).filter(Boolean);
- for (const token of tokens) {
- if (token.startsWith('@')) continue;
- const base = basename(token);
- if (base === 'open-knowledge' || base === 'ok') return token;
- if (
- token.endsWith('/packages/cli/src/cli.ts') ||
- token.endsWith('/packages/cli/dist/cli.mjs')
- ) {
- return token;
- }
- if (base === 'cli.mjs' || base === 'cli.ts') return token;
- }
- return null;
-}
-
-export function processCommand(pid: number): string | null {
- const result = spawnSync('ps', ['-p', String(pid), '-o', 'command='], {
- encoding: 'utf-8',
- timeout: SPAWN_TIMEOUT_MS,
- });
-
- if (result.error != null || !result.stdout) return null;
- return result.stdout.trim() || null;
-}
-
-export interface ProcessUsage {
- cpuPercent: number;
- memPercent: number;
-}
-
-export function processUsage(pid: number): ProcessUsage | null {
- const result = spawnSync('ps', ['-p', String(pid), '-o', '%cpu=,%mem='], {
- encoding: 'utf-8',
- timeout: SPAWN_TIMEOUT_MS,
- });
-
- if (result.error != null || !result.stdout) return null;
- const [cpuRaw, memRaw] = result.stdout.trim().split(/\s+/);
- const cpuPercent = Number.parseFloat(cpuRaw ?? '');
- const memPercent = Number.parseFloat(memRaw ?? '');
- if (Number.isNaN(cpuPercent) || Number.isNaN(memPercent)) return null;
- return { cpuPercent, memPercent };
-}
-
-export async function pidCwd(pid: number): Promise<string | null> {
- const result = spawnSync('lsof', ['-p', String(pid), '-a', '-d', 'cwd', '-Fn'], {
- encoding: 'utf-8',
- timeout: SPAWN_TIMEOUT_MS,
- });
-
- if (result.error != null) {
- return null;
- }
-
- const output = result.stdout ?? '';
- for (const line of output.split('\n')) {
- if (line.startsWith('n') && line.length > 1) {
- return line.slice(1);
- }
- }
-
- return null;
-}
-
-function parseListeningPids(output: string): number[] {
- const pids: number[] = [];
- const lines = output.split('\n');
- for (let i = 1; i < lines.length; i++) {
- const line = lines[i]?.trim();
- if (!line) continue;
- const parts = line.split(/\s+/);
- if (parts.length < 2) continue;
- const pid = Number.parseInt(parts[1] ?? '', 10);
- if (!Number.isNaN(pid)) {
- pids.push(pid);
- }
- }
- return [...new Set(pids)];
-}
-
-function hasLockFile(lockDir: string): boolean {
- return existsSync(join(lockDir, 'server.lock')) || existsSync(join(lockDir, 'ui.lock'));
-}
-
-function addLockDirsForCwd(candidateDirs: Set<string>, cwd: string): void {
- for (const lockDir of [join(cwd, '.ok', 'local'), join(cwd, '.ok')]) {
- if (existsSync(lockDir) && hasLockFile(lockDir)) {
- candidateDirs.add(lockDir);
- }
- }
-}
-
-function addLockDirsUnderCwd(candidateDirs: Set<string>, cwd: string): void {
- let visited = 0;
-
- const walk = (dir: string, depth: number): void => {
- if (visited >= LOCK_SCAN_MAX_ENTRIES) return;
- visited++;
-
- addLockDirsForCwd(candidateDirs, dir);
- if (depth >= LOCK_SCAN_MAX_DEPTH) return;
-
- let entries: string[];
- try {
- entries = readdirSync(dir);
- } catch {
- return;
- }
-
- for (const entry of entries) {
- if (visited >= LOCK_SCAN_MAX_ENTRIES) return;
- if (entry === 'node_modules' || entry === '.git' || entry === 'Library') continue;
- if (entry.startsWith('.') && entry !== '.ok') continue;
-
- const child = join(dir, entry);
- let isDirectory = false;
- try {
- isDirectory = lstatSync(child).isDirectory();
- } catch {
- continue;
- }
- if (isDirectory) walk(child, depth + 1);
- }
- };
-
- walk(cwd, 0);
-}
-
-export async function discoverLockDirs(): Promise<string[]> {
- const candidateDirs = new Set<string>();
-
- const okEntries = await findOkProcessEntries();
- const cwdPromises = okEntries.map((e) => pidCwd(e.pid));
- const cwds = await Promise.all(cwdPromises);
-
- for (const entry of okEntries) {
- const markedLockDir = extractMarkedLockDir(entry.command);
- if (markedLockDir != null && existsSync(markedLockDir)) {
- candidateDirs.add(markedLockDir);
- }
-
- const projectPath = extractProjectPathArg(entry.command);
- if (projectPath != null) {
- addLockDirsForCwd(candidateDirs, projectPath);
- }
- }
-
- for (const cwd of cwds) {
- if (cwd == null) continue;
- addLockDirsForCwd(candidateDirs, cwd);
- }
-
- const lsofResult = spawnSync('lsof', ['-iTCP', '-sTCP:LISTEN', '-nP'], {
- encoding: 'utf-8',
- timeout: SPAWN_TIMEOUT_MS,
- });
-
- if (lsofResult.error == null && lsofResult.stdout) {
- const listeningPids = parseListeningPids(lsofResult.stdout);
- const knownPidSet = new Set(okEntries.map((e) => e.pid));
- const newPids = listeningPids.filter((p) => !knownPidSet.has(p));
- const portCwdPromises = newPids.map((pid) => pidCwd(pid));
- const portCwds = await Promise.all(portCwdPromises);
-
- for (const cwd of portCwds) {
- if (cwd == null) continue;
- addLockDirsForCwd(candidateDirs, cwd);
- }
- }
-
- if (candidateDirs.size === 0 || cwds.some((cwd) => cwd === '/')) {
- addLockDirsUnderCwd(candidateDirs, process.cwd());
- }
-
- const canonical = new Map<string, string>();
- for (const dir of candidateDirs) {
- try {
- const real = await realpath(dir);
- canonical.set(real, real);
- } catch {
- canonical.set(dir, dir);
- }
- }
-
- return [...canonical.values()];
-}
+export {
+ discoverLockDirs,
+ extractOkBinaryPath,
+ type ProcessUsage,
+ processCommand,
+ processUsage,
+} from '@inkeep/open-knowledge-server';
diff --git a/packages/server/assets/skills/discovery/SKILL.md b/packages/server/assets/skills/discovery/SKILL.md
index 90733cfc5..6e9af5e95 100644
--- a/packages/server/assets/skills/discovery/SKILL.md
+++ b/packages/server/assets/skills/discovery/SKILL.md
@@ -14,9 +14,13 @@ directory of `.md` / `.mdx` files into a live, multi-writer knowledge base:
agents and humans edit the same documents in real time, every change is
attributed, and a browser preview renders edits as they land.
-This skill is **discovery-only**. It explains what OpenKnowledge is and how
-to set it up. It carries **no runtime rules** for reading or editing markdown
-— that guidance ships separately (see *Working inside a project* below).
+This skill covers **discovery, install, and opening OpenKnowledge files** —
+including single files that are not part of a project (see *Opening a file
+outside a project* below). It does **not** carry the in-project read/write
+runtime contract (the STOP rules for native file tools, the grounding and
+linking rules, the MCP routing table) — that ships separately as the
+project-local skill installed by `ok init` (see *Working inside a project*
+below).
## Install OpenKnowledge on a repository
@@ -71,6 +75,51 @@ bundles its own CLI, opens a project as an editor + preview window, and keeps
the project's MCP wiring and skills current on every launch. Download DMGs
from the releases page.
+## Opening a file outside a project
+
+OpenKnowledge can open a single markdown file that is **not** part of an OK
+project — a loose `.md` / `.mdx`, **or a file that lives inside a regular
+repo/folder which was never `ok init`'d**. It opens in a throwaway session (a
+temp project in the OS temp dir — your repo is never touched, no `.ok/` is
+written into it) with the same live preview you get inside a project.
+
+**Never run `ok init` just to view or open a file.** `ok init` turns a repo
+into a shared OpenKnowledge project; it is not a prerequisite for opening one
+file. Opening a file needs no project, no `.ok/`, and no server already
+running — each path below boots the session itself.
+
+When asked to open or preview such a file, **decide by the viewing surface you
+actually have** — check the tool, not the host name. Only open a browser when
+you genuinely have one; never pop a browser tab on a host that has none.
+
+- **You have an in-app / built-in browser** (Cursor, Codex, and similar) — this
+ is the default: call the **`preview_url` MCP tool** with `file` set to the
+ absolute path (it finds, or boots on demand, the session and returns a full
+ `url`), then **immediately open that `url` in your in-app browser**. "Open it"
+ means navigate your browser — don't just print the URL and stop. This is also
+ the only way to view it in a browser when the OK Desktop app is installed
+ (`ok open` prefers the Desktop app). Get the URL from `preview_url` only —
+ never hunt for it via `ok ps` / `ok status` / `ok ui` / `ok start` or a guessed
+ port.
+- **You have a Claude Code Desktop preview *pane* but no general browser** — the
+ pane is project-only: it shows in-project docs via `preview_start`, but it
+ **cannot host a file from outside the project**. For such a file run
+ `ok open /abs/path/to/file.md` (the Desktop app) instead; don't try to force
+ the file into the pane.
+- **No in-app browser and no pane** (a pure-stdio CLI) — run
+ `ok open /abs/path/to/file.md`: it opens the Desktop app when installed, else a
+ browser, and boots the session itself. Don't force a browser tab the user
+ didn't ask for; `ok open` is the right default here. If `ok` isn't on PATH,
+ `npx @inkeep/open-knowledge open /abs/path/to/file.md` does the same.
+
+If the OK MCP server isn't wired into this host there is no `preview_url` to
+call — use the `ok open` path above. Don't reconstruct what `preview_url` does
+by hand (spawning `ok mcp` yourself, scraping ports from `ok ps`).
+
+The path must be absolute (a file outside a project has no cwd to anchor a
+relative path). Re-opening the same file lands on the same session. Never
+construct or guess the URL — use the one `preview_url` returns.
+
## Working inside a project — use the project-local skill, not this one
Do **not** use this skill to perform OpenKnowledge reads or writes. The
diff --git a/packages/server/src/ensure-single-file-session.test.ts b/packages/server/src/ensure-single-file-session.test.ts
new file mode 100644
index 000000000..c0f3f0834
--- /dev/null
+++ b/packages/server/src/ensure-single-file-session.test.ts
@@ -0,0 +1,108 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import {
+ __resetEnsureSingleFileInflightForTests,
+ type EnsureSingleFileDeps,
+ ensureSingleFileSession,
+} from './ensure-single-file-session.ts';
+
+afterEach(() => __resetEnsureSingleFileInflightForTests());
+
+function makeClock() {
+ let t = 0;
+ return {
+ now: () => t,
+ sleep: async (ms: number) => {
+ t += ms;
+ },
+ };
+}
+
+function makeDeps(
+ isServing: (f: string) => Promise<boolean>,
+ spawn: { calls: string[] },
+): EnsureSingleFileDeps {
+ const clock = makeClock();
+ return {
+ spawnSession: (f) => spawn.calls.push(f),
+ isServing,
+ realpath: async (p) => p,
+ pollIntervalMs: 100,
+ timeoutMs: 1000,
+ sleep: clock.sleep,
+ now: clock.now,
+ };
+}
+
+describe('ensureSingleFileSession', () => {
+ test('already serving → returns true without spawning', async () => {
+ const spawn = { calls: [] as string[] };
+ const ok = await ensureSingleFileSession(
+ '/loose/a.md',
+ makeDeps(async () => true, spawn),
+ );
+ expect(ok).toBe(true);
+ expect(spawn.calls).toEqual([]);
+ });
+
+ test('spawns once, returns true when the session registers on a later poll', async () => {
+ const spawn = { calls: [] as string[] };
+ let checks = 0;
+ const deps = makeDeps(async () => {
+ checks += 1;
+ return checks >= 3;
+ }, spawn);
+ const ok = await ensureSingleFileSession('/loose/b.md', deps);
+ expect(ok).toBe(true);
+ expect(spawn.calls).toEqual(['/loose/b.md']);
+ });
+
+ test('returns false when the session never registers before the timeout', async () => {
+ const spawn = { calls: [] as string[] };
+ const ok = await ensureSingleFileSession(
+ '/loose/c.md',
+ makeDeps(async () => false, spawn),
+ );
+ expect(ok).toBe(false);
+ expect(spawn.calls).toEqual(['/loose/c.md']); // spawned, but never came up
+ });
+
+ test('single-flight: concurrent ensures for one file coalesce to a single spawn', async () => {
+ const spawn = { calls: [] as string[] };
+ let checks = 0;
+ const deps = makeDeps(async () => {
+ checks += 1;
+ return checks >= 3;
+ }, spawn);
+ const [a, b] = await Promise.all([
+ ensureSingleFileSession('/loose/d.md', deps),
+ ensureSingleFileSession('/loose/d.md', deps),
+ ]);
+ expect(a).toBe(true);
+ expect(b).toBe(true);
+ expect(spawn.calls).toEqual(['/loose/d.md']); // exactly one spawn for both callers
+ });
+ test('different files spawn independently (not coalesced)', async () => {
+ const clock = makeClock();
+ const spawn = { calls: [] as string[] };
+ const served = new Set<string>();
+ const deps: EnsureSingleFileDeps = {
+ spawnSession: (f) => {
+ spawn.calls.push(f);
+ served.add(f); // registers immediately so the next poll sees it
+ },
+ isServing: async (f) => served.has(f),
+ realpath: async (p) => p,
+ pollIntervalMs: 100,
+ timeoutMs: 1000,
+ sleep: clock.sleep,
+ now: clock.now,
+ };
+ const [a, b] = await Promise.all([
+ ensureSingleFileSession('/loose/p.md', deps),
+ ensureSingleFileSession('/loose/q.md', deps),
+ ]);
+ expect(a).toBe(true);
+ expect(b).toBe(true);
+ expect([...spawn.calls].sort()).toEqual(['/loose/p.md', '/loose/q.md']);
+ });
+});
diff --git a/packages/server/src/ensure-single-file-session.ts b/packages/server/src/ensure-single-file-session.ts
new file mode 100644
index 000000000..66de1be8a
--- /dev/null
+++ b/packages/server/src/ensure-single-file-session.ts
@@ -0,0 +1,91 @@
+
+import { spawn } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import { realpath as fsRealpath } from 'node:fs/promises';
+import { resolve } from 'node:path';
+import { isSupportedDocFile } from './doc-extensions.ts';
+import { createOffCwdResolverDeps, resolveOffCwdTarget } from './off-cwd-resolver.ts';
+
+export interface EnsureSingleFileDeps {
+ readonly spawnSession: (absFile: string) => void;
+ readonly isServing: (absFile: string) => Promise<boolean>;
+ readonly realpath: (p: string) => Promise<string>;
+ readonly pollIntervalMs?: number;
+ readonly timeoutMs?: number;
+ readonly sleep?: (ms: number) => Promise<void>;
+ readonly now?: () => number;
+}
+
+const DEFAULT_POLL_INTERVAL_MS = 500;
+const DEFAULT_TIMEOUT_MS = 15000;
+
+const inflight = new Map<string, Promise<boolean>>();
+
+export function ensureSingleFileSession(
+ absFile: string,
+ deps: EnsureSingleFileDeps,
+): Promise<boolean> {
+ const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
+ const now = deps.now ?? (() => Date.now());
+ const pollMs = deps.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
+ const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
+
+ const run = async (): Promise<boolean> => {
+ const key = await deps.realpath(resolve(absFile)).catch(() => resolve(absFile));
+ const existing = inflight.get(key);
+ if (existing) return existing;
+
+ const work = (async (): Promise<boolean> => {
+ const serving = () => deps.isServing(key).catch(() => false);
+ if (await serving()) return true;
+ deps.spawnSession(key);
+ const deadline = now() + timeoutMs;
+ while (now() < deadline) {
+ await sleep(pollMs);
+ if (await serving()) return true;
+ }
+ return false;
+ })().finally(() => {
+ inflight.delete(key);
+ });
+
+ inflight.set(key, work);
+ return work;
+ };
+
+ return run();
+}
+
+export function __resetEnsureSingleFileInflightForTests(): void {
+ inflight.clear();
+}
+
+export function createEnsureSingleFileSession(): (absFile: string) => Promise<boolean> {
+ const deps: EnsureSingleFileDeps = {
+ spawnSession: (absFile) => {
+ if (!isSupportedDocFile(absFile) || !existsSync(absFile)) return;
+ const entry = process.argv[1];
+ if (!entry) {
+ process.stderr.write(
+ '[ensure-single-file-session] process.argv[1] is empty — cannot spawn a single-file session\n',
+ );
+ return;
+ }
+ const env: NodeJS.ProcessEnv = {
+ ...process.env,
+ OK_SINGLE_FILE_NO_OPEN: '1',
+ ELECTRON_RUN_AS_NODE: '1',
+ };
+ const child = spawn(process.execPath, [entry, absFile], {
+ detached: true,
+ stdio: 'ignore',
+ env,
+ });
+ child.unref();
+ },
+ isServing: async (absFile) =>
+ (await resolveOffCwdTarget(absFile, createOffCwdResolverDeps())) !== null,
+ realpath: (p) => fsRealpath(p).catch(() => p),
+ };
+ return (absFile) => ensureSingleFileSession(absFile, deps);
+}
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index 8e9e4d62c..e4676c284 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -318,6 +318,13 @@ export {
releaseProcessLock,
updateProcessLockPort,
} from './process-lock.ts';
+export {
+ discoverLockDirs,
+ extractOkBinaryPath,
+ type ProcessUsage,
+ processCommand,
+ processUsage,
+} from './process-scan.ts';
export {
type EnsureProjectGitResult,
ensureProjectGit,
diff --git a/packages/server/src/mcp/tools/get-preview-url.test.ts b/packages/server/src/mcp/tools/get-preview-url.test.ts
index 287e2840b..e43999a62 100644
--- a/packages/server/src/mcp/tools/get-preview-url.test.ts
+++ b/packages/server/src/mcp/tools/get-preview-url.test.ts
@@ -6,6 +6,7 @@ import { join } from 'node:path';
import { AutoStartDisabledError } from '../../autostart.ts';
import { resolveLockDir } from '../../config/paths.ts';
import { type Config, ConfigSchema } from '../../config/schema.ts';
+import type { OffCwdResolverDeps } from '../../off-cwd-resolver.ts';
import { readArmedPaneTarget } from '../../pane-target.ts';
import { register } from './get-preview-url.ts';
import { bindTestServerLock, bindTestUiLock } from './preview-url-test-helpers.ts';
@@ -26,6 +27,7 @@ type ToolHandler = (args: {
document?: string;
folder?: string;
skill?: { name: string; scope?: 'project' | 'global' };
+ file?: string;
armPaneTarget?: boolean;
cwd?: string;
}) => Promise<ToolResult>;
@@ -33,6 +35,9 @@ type ToolHandler = (args: {
interface EnsureDeps {
serverUrl?: (cwd?: string) => Promise<string | undefined>;
uiBindWait?: { timeoutMs?: number; pollIntervalMs?: number };
+ offCwdResolverDeps?: OffCwdResolverDeps;
+ ensureSingleFileSession?: (absFile: string) => Promise<boolean>;
+ resolveUserAutoOpen?: () => boolean;
}
function captureRegistration(
@@ -396,3 +401,167 @@ describe('preview_url tool — error path', () => {
expect(result.content[0]?.text).toContain('no roots configured');
});
});
+
+function mockOffCwdDeps(
+ candidates: Array<{ contentDir: string; baseUrl: string; alive?: boolean }>,
+): OffCwdResolverDeps {
+ const cands = candidates.map((c) => ({
+ lockDir: `${c.contentDir}/.ok/local`,
+ contentDir: c.contentDir,
+ baseUrl: c.baseUrl,
+ alive: c.alive ?? true,
+ }));
+ return {
+ discover: async () => cands.map((c) => c.lockDir),
+ inspect: async (d) => cands.find((c) => c.lockDir === d) ?? null,
+ realpath: async (p) => p,
+ };
+}
+
+describe('preview_url tool — file branch (out-of-project)', () => {
+ test('resolves a loose file to the session whose contentDir contains it', async () => {
+ const handler = captureRegistration(mkdtempSync(join(tmpdir(), 'ok-pv-')), BASE_CONFIG, {
+ offCwdResolverDeps: mockOffCwdDeps([
+ { contentDir: '/loose', baseUrl: 'http://localhost:6001' },
+ ]),
+ });
+ const result = await handler({ file: '/loose/notes.md' });
+ expect(result.isError).toBeUndefined();
+ expect(result.structuredContent?.running).toBe(true);
+ expect(result.structuredContent?.baseUrl).toBe('http://localhost:6001');
+ expect(result.structuredContent?.url).toBe('http://localhost:6001/#/notes');
+ expect(result.structuredContent?.autoOpen).toBe(true);
+ });
+
+ test('no session for the file → running:false with an ok-open hint', async () => {
+ const handler = captureRegistration(mkdtempSync(join(tmpdir(), 'ok-pv-')), BASE_CONFIG, {
+ offCwdResolverDeps: mockOffCwdDeps([]),
+ });
+ const result = await handler({ file: '/loose/notes.md' });
+ expect(result.isError).toBeUndefined();
+ expect(result.structuredContent?.running).toBe(false);
+ expect(result.structuredContent?.url).toBeNull();
+ expect(result.content[0]?.text).toContain('ok open /loose/notes.md');
+ });
+
+ test('file is mutually exclusive with document', async () => {
+ const handler = captureRegistration(mkdtempSync(join(tmpdir(), 'ok-pv-')), BASE_CONFIG, {
+ offCwdResolverDeps: mockOffCwdDeps([]),
+ });
+ const result = await handler({ file: '/loose/notes.md', document: 'specs/foo' });
+ expect(result.isError).toBe(true);
+ expect(result.content[0]?.text).toContain('mutually exclusive');
+ });
+});
+
+describe('preview_url tool — file branch boot-on-demand', () => {
+ test('boots a session when none serves the file yet, then resolves its URL', async () => {
+ let candidate: { contentDir: string; baseUrl: string } | null = null;
+ const liveDeps: OffCwdResolverDeps = {
+ discover: async () => (candidate ? [`${candidate.contentDir}/.ok/local`] : []),
+ inspect: async () =>
+ candidate
+ ? {
+ lockDir: `${candidate.contentDir}/.ok/local`,
+ contentDir: candidate.contentDir,
+ baseUrl: candidate.baseUrl,
+ alive: true,
+ }
+ : null,
+ realpath: async (p) => p,
+ };
+ const handler = captureRegistration(mkdtempSync(join(tmpdir(), 'ok-pv-')), BASE_CONFIG, {
+ offCwdResolverDeps: liveDeps,
+ ensureSingleFileSession: async () => {
+ candidate = { contentDir: '/loose', baseUrl: 'http://localhost:6010' };
+ return true;
+ },
+ });
+ const result = await handler({ file: '/loose/new.md' });
+ expect(result.structuredContent?.running).toBe(true);
+ expect(result.structuredContent?.url).toBe('http://localhost:6010/#/new');
+ });
+
+ test('boot-on-demand that never registers → running:false + ok-open hint', async () => {
+ const empty: OffCwdResolverDeps = {
+ discover: async () => [],
+ inspect: async () => null,
+ realpath: async (p) => p,
+ };
+ let called = false;
+ const handler = captureRegistration(mkdtempSync(join(tmpdir(), 'ok-pv-')), BASE_CONFIG, {
+ offCwdResolverDeps: empty,
+ ensureSingleFileSession: async () => {
+ called = true;
+ return false;
+ },
+ });
+ const result = await handler({ file: '/loose/x.md' });
+ expect(called).toBe(true);
+ expect(result.structuredContent?.running).toBe(false);
+ expect(result.content[0]?.text).toContain('ok open');
+ });
+
+ test('no ensureSingleFileSession dep (no spawn authority) → hint, no boot', async () => {
+ const empty: OffCwdResolverDeps = {
+ discover: async () => [],
+ inspect: async () => null,
+ realpath: async (p) => p,
+ };
+ const handler = captureRegistration(mkdtempSync(join(tmpdir(), 'ok-pv-')), BASE_CONFIG, {
+ offCwdResolverDeps: empty,
+ });
+ const result = await handler({ file: '/loose/y.md' });
+ expect(result.structuredContent?.running).toBe(false);
+ expect(result.content[0]?.text).toContain('ok open');
+ });
+ test('ensureSingleFileSession rejection → running:false + hint (not a tool error)', async () => {
+ const empty: OffCwdResolverDeps = {
+ discover: async () => [],
+ inspect: async () => null,
+ realpath: async (p) => p,
+ };
+ const handler = captureRegistration(mkdtempSync(join(tmpdir(), 'ok-pv-')), BASE_CONFIG, {
+ offCwdResolverDeps: empty,
+ ensureSingleFileSession: async () => {
+ throw new Error('spawn boom');
+ },
+ });
+ const result = await handler({ file: '/loose/z.md' });
+ expect(result.isError).toBeUndefined();
+ expect(result.structuredContent?.running).toBe(false);
+ expect(result.content[0]?.text).toContain('ok open');
+ });
+ test('relative file path is rejected (must be absolute)', async () => {
+ const handler = captureRegistration(mkdtempSync(join(tmpdir(), 'ok-pv-')), BASE_CONFIG);
+ const result = await handler({ file: 'notes.md' });
+ expect(result.isError).toBe(true);
+ expect(result.content[0]?.text).toContain('absolute');
+ });
+ test('boot reports success but the session is not discoverable → falls back to the hint', async () => {
+ const empty: OffCwdResolverDeps = {
+ discover: async () => [],
+ inspect: async () => null,
+ realpath: async (p) => p,
+ };
+ const handler = captureRegistration(mkdtempSync(join(tmpdir(), 'ok-pv-')), BASE_CONFIG, {
+ offCwdResolverDeps: empty,
+ ensureSingleFileSession: async () => true,
+ });
+ const result = await handler({ file: '/loose/gone.md' });
+ expect(result.isError).toBeUndefined();
+ expect(result.structuredContent?.running).toBe(false);
+ expect(result.content[0]?.text).toContain('ok open');
+ });
+ test('file branch honors a user-scoped autoOpen=false preference', async () => {
+ const handler = captureRegistration(mkdtempSync(join(tmpdir(), 'ok-pv-')), BASE_CONFIG, {
+ offCwdResolverDeps: mockOffCwdDeps([
+ { contentDir: '/loose', baseUrl: 'http://127.0.0.1:6020' },
+ ]),
+ resolveUserAutoOpen: () => false,
+ });
+ const result = await handler({ file: '/loose/notes.md' });
+ expect(result.structuredContent?.running).toBe(true);
+ expect(result.structuredContent?.autoOpen).toBe(false);
+ });
+});
diff --git a/packages/server/src/mcp/tools/get-preview-url.ts b/packages/server/src/mcp/tools/get-preview-url.ts
index 69dadb582..43d792806 100644
--- a/packages/server/src/mcp/tools/get-preview-url.ts
+++ b/packages/server/src/mcp/tools/get-preview-url.ts
@@ -1,8 +1,15 @@
+import { isAbsolute } from 'node:path';
import { MANAGED_ARTIFACT_SCOPES, SKILL_NAME_REGEX } from '@inkeep/open-knowledge-core';
+import { readConfigSafely, resolveConfigPath } from '@inkeep/open-knowledge-core/server';
import { z } from 'zod';
import { AutoStartDisabledError } from '../../autostart.ts';
import { resolveLockDir } from '../../config/paths.ts';
+import {
+ createOffCwdResolverDeps,
+ type OffCwdResolverDeps,
+ resolveOffCwdTarget,
+} from '../../off-cwd-resolver.ts';
import { armPaneTarget } from '../../pane-target.ts';
import { isProcessAlive } from '../../process-alive.ts';
import { readServerLock } from '../../server-lock.ts';
@@ -28,14 +35,17 @@ const DESCRIPTION = [
'',
'Per-response `previewUrl` fields on read/write tools are ROUTE-ONLY (`/#/<doc>`, no host:port) — they identify which doc to preview, not a URL to open by itself. Call this tool to get the full, openable URL.',
'',
- 'Use this when YOUR host opens the URL itself: navigate your in-app browser to the returned `url`, or — only on a stdio host with no browser tool — `open` it in the system browser. Hosts with a preview pane (Claude Code Desktop) call `preview_start("open-knowledge-ui")` instead; the Claude Code CLI uses `ok open <doc>` to open in the OK Desktop app.',
+ 'This is THE way to open a doc OR a loose file in a browser, and the only way to force a browser when the OK Desktop app is installed (the `ok open` CLI prefers Desktop). Use it when YOUR host opens the URL itself: navigate your in-app / embedded browser to the returned `url`, or — only on a stdio host with no browser tool — `open` it in the system browser. Do not hunt for the URL via `ok ps`/`ok status` or by guessing a port — this tool returns it. Hosts with a preview pane (Claude Code Desktop) call `preview_start("open-knowledge-ui")` instead; a pure stdio CLI with no browser uses `ok open <doc>` to open in the OK Desktop app.',
'',
'Returns `{ url: null, baseUrl: null, running: false, autoOpen }` + a recovery hint only when no UI could be reached (auto-start disabled via `OK_MCP_AUTOSTART=0`, no spawn authority in this registration, or the UI did not bind in time) — the hint names the right command for the actual state.',
'',
+ 'To open a single markdown file that may live OUTSIDE any Open Knowledge project (a loose file, or a doc in a different git worktree), pass `file` with an absolute path: the tool finds the running session whose content directory contains it and returns that session’s URL, then navigate your in-app browser there. `document`/`folder` are for a doc in the current project; `file` is the out-of-project form.',
+ '',
'**Parameters:**',
- '- `document` (optional) — Extension-less doc path (e.g. `specs/foo/SPEC`). Omit for the UI root URL.',
- '- `folder` (optional) — Folder path (e.g. `specs/foo`); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.',
- '- `skill` (optional) — A skill to open in the editor: `{ name, scope? }` (scope `project` default). Returns the `…/#/__skill__/<scope>/<name>` route. Mutually exclusive with `document`/`folder`.',
+ '- `document` (optional) — Extension-less doc path in the current project (e.g. `specs/foo/SPEC`). Omit for the UI root URL.',
+ '- `folder` (optional) — Folder path in the current project (e.g. `specs/foo`); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.',
+ '- `skill` (optional) — A skill to open in the editor: `{ name, scope? }` (scope `project` default). Returns the `…/#/__skill__/<scope>/<name>` route. Mutually exclusive with `document`/`folder`/`file`.',
+ '- `file` (optional) — Absolute path to a single markdown file, including one outside any project. Resolves to the running single-file / worktree session serving it. Mutually exclusive with `document`/`folder`/`skill`; `cwd` is ignored when set.',
'- `armPaneTarget` (optional) — When true with a `document`/`folder`/`skill`, writes a small TTL-bounded (~30s) state file under `.ok/local/` so a later Claude-pane base-open lands on that target. Independent of server state; omit it and the call writes nothing.',
'- `cwd` (optional) — Project root (see `cwd` description below).',
].join('\n');
@@ -45,6 +55,9 @@ interface GetPreviewUrlDeps {
resolveCwd: (explicit?: string) => Promise<string>;
serverUrl?: ServerUrlOrResolver;
uiBindWait?: { timeoutMs?: number; pollIntervalMs?: number };
+ offCwdResolverDeps?: OffCwdResolverDeps;
+ ensureSingleFileSession?: (absFile: string) => Promise<boolean>;
+ resolveUserAutoOpen?: () => boolean;
}
const UI_BIND_WAIT_TIMEOUT_MS = 3000;
@@ -78,7 +91,13 @@ const InputSchema = {
})
.optional()
.describe(
- 'Skill to resolve an editor preview URL for; returns the `…/#/__skill__/<scope>/<name>` route. Mutually exclusive with `document`/`folder`.',
+ 'Skill to resolve an editor preview URL for; returns the `…/#/__skill__/<scope>/<name>` route. Mutually exclusive with `document`/`folder`/`file`.',
+ ),
+ file: z
+ .string()
+ .optional()
+ .describe(
+ 'Absolute path to a single markdown file to open, including one OUTSIDE any Open Knowledge project. Resolves to the running single-file (or worktree) session whose content directory contains it and returns that session’s `url`. Mutually exclusive with `document` / `folder` / `skill`. When `file` is set, `cwd` is ignored.',
),
armPaneTarget: z
.boolean()
@@ -115,6 +134,25 @@ const NO_UI_SERVER_RUNNING_MESSAGE =
const NO_SERVER_MESSAGE =
'No OpenKnowledge server is running for this project. Start it with `ok start` (also starts the preview UI), use `preview_start("open-knowledge-ui")` (Claude Code Desktop), or open the project in OK Electron.';
const AUTOSTART_DISABLED_NOTE = ' Auto-start is disabled (OK_MCP_AUTOSTART=0).';
+function readUserAutoOpen(): boolean {
+ try {
+ const cfg = readConfigSafely({
+ absPath: resolveConfigPath('user', process.cwd()),
+ sideline: false,
+ warn: () => {},
+ });
+ return cfg.value.appearance?.preview?.autoOpen ?? true;
+ } catch (err) {
+ process.stderr.write(
+ `[preview-url] readUserAutoOpen failed: ${err instanceof Error ? err.message : String(err)}\n`,
+ );
+ return true;
+ }
+}
+
+function noSingleFileSessionMessage(file: string): string {
+ return `No Open Knowledge session is serving ${file} yet. On a host with a terminal, \`ok open ${file}\` starts one; otherwise open ${file} in the OK Desktop app. Then retry.`;
+}
function isServerLive(lockDir: string): boolean {
try {
@@ -144,20 +182,63 @@ export function register(server: ServerInstance, deps: GetPreviewUrlDeps): void
document?: string;
folder?: string;
skill?: { name: string; scope?: 'project' | 'global' };
+ file?: string;
armPaneTarget?: boolean;
cwd?: string;
}) => {
- if ([args.document, args.folder, args.skill].filter((t) => t != null).length > 1) {
+ if ([args.document, args.folder, args.skill, args.file].filter((t) => t != null).length > 1) {
return {
isError: true,
content: [
{
type: 'text' as const,
- text: 'Error: document, folder, and skill are mutually exclusive — pass at most one.',
+ text: 'Error: document, folder, skill, and file are mutually exclusive — pass at most one.',
},
],
};
}
+
+ if (args.file) {
+ if (!isAbsolute(args.file)) {
+ return {
+ isError: true,
+ content: [
+ {
+ type: 'text' as const,
+ text: 'Error: file must be an absolute path (a loose file outside a project has no cwd to anchor a relative path).',
+ },
+ ],
+ };
+ }
+ const fileAutoOpen = (deps.resolveUserAutoOpen ?? readUserAutoOpen)();
+ const resolverDeps = deps.offCwdResolverDeps ?? createOffCwdResolverDeps();
+ let hit = await resolveOffCwdTarget(args.file, resolverDeps);
+ if (hit === null && deps.ensureSingleFileSession) {
+ const booted = await deps.ensureSingleFileSession(args.file).catch((err) => {
+ process.stderr.write(
+ `[preview-url] ensureSingleFileSession failed for ${args.file}: ${err instanceof Error ? err.message : String(err)}\n`,
+ );
+ return false;
+ });
+ if (booted) hit = await resolveOffCwdTarget(args.file, resolverDeps);
+ }
+ if (hit !== null) {
+ const url = `${hit.baseUrl}/#/${encodeDocName(hit.docName)}`;
+ return textPlusStructured(`Preview URL: ${url}`, {
+ url,
+ baseUrl: hit.baseUrl,
+ running: true,
+ autoOpen: fileAutoOpen,
+ });
+ }
+ return textPlusStructured(noSingleFileSessionMessage(args.file), {
+ url: null,
+ baseUrl: null,
+ running: false,
+ autoOpen: fileAutoOpen,
+ });
+ }
+
const context = await resolveProjectConfigContext(deps.resolveCwd, deps.config, args.cwd);
if (!context.ok) {
return {
diff --git a/packages/server/src/mcp/tools/index.ts b/packages/server/src/mcp/tools/index.ts
index d276d4ec0..4c26f3ea1 100644
--- a/packages/server/src/mcp/tools/index.ts
+++ b/packages/server/src/mcp/tools/index.ts
@@ -1,4 +1,5 @@
+import { createEnsureSingleFileSession } from '../../ensure-single-file-session.ts';
import type { AgentIdentity } from '../agent-identity.ts';
import { getCurrentMcpLogger, type McpLogger } from '../logger.ts';
import { createLoggedServer } from '../tool-logging.ts';
@@ -142,6 +143,7 @@ export function registerAllTools(server: ServerInstance, opts: RegisterAllToolsO
config: opts.config,
resolveCwd: named('preview_url'),
serverUrl: opts.serverUrl,
+ ...(opts.serverUrl ? { ensureSingleFileSession: createEnsureSingleFileSession() } : {}),
});
registerConflicts(registrationServer, {
serverUrl: opts.serverUrl,
diff --git a/packages/server/src/off-cwd-resolver.test.ts b/packages/server/src/off-cwd-resolver.test.ts
new file mode 100644
index 000000000..e2cb2d28a
--- /dev/null
+++ b/packages/server/src/off-cwd-resolver.test.ts
@@ -0,0 +1,109 @@
+import { describe, expect, test } from 'bun:test';
+import {
+ type OffCwdCandidate,
+ type OffCwdResolverDeps,
+ projectDirOfLockDir,
+ resolveOffCwdTarget,
+} from './off-cwd-resolver.ts';
+
+function makeDeps(
+ candidates: OffCwdCandidate[],
+ realpathMap: Record<string, string> = {},
+): OffCwdResolverDeps {
+ return {
+ discover: async () => candidates.map((c) => c.lockDir),
+ inspect: async (lockDir) => candidates.find((c) => c.lockDir === lockDir) ?? null,
+ realpath: async (p) => realpathMap[p] ?? p,
+ };
+}
+
+function candidate(contentDir: string, port: number, alive = true): OffCwdCandidate {
+ return {
+ lockDir: `${contentDir}/.ok/local`,
+ contentDir,
+ baseUrl: `http://127.0.0.1:${port}`,
+ alive,
+ };
+}
+
+describe('resolveOffCwdTarget', () => {
+ test('matches a target to the one server whose contentDir contains it', async () => {
+ const deps = makeDeps([candidate('/repo/feat-a', 5101), candidate('/repo/feat-b', 5102)]);
+ const r = await resolveOffCwdTarget('/repo/feat-b/specs/foo.md', deps);
+ expect(r).toEqual({ baseUrl: 'http://127.0.0.1:5102', docName: 'specs/foo' });
+ });
+
+ test('longest-prefix wins: nested worktree beats its parent checkout', async () => {
+ const deps = makeDeps([
+ candidate('/repo', 5100), // main checkout
+ candidate('/repo/.claude/worktrees/b', 5102), // nested worktree
+ ]);
+ const r = await resolveOffCwdTarget('/repo/.claude/worktrees/b/docs/x.md', deps);
+ expect(r?.baseUrl).toBe('http://127.0.0.1:5102');
+ expect(r?.docName).toBe('docs/x');
+ });
+
+ test('contentDir != projectDir: matches the config-derived content subdir', async () => {
+ const deps = makeDeps([candidate('/proj/docs', 5103)]);
+ const r = await resolveOffCwdTarget('/proj/docs/guide.mdx', deps);
+ expect(r).toEqual({ baseUrl: 'http://127.0.0.1:5103', docName: 'guide' });
+ });
+
+ test('dead servers are skipped (liveness gate)', async () => {
+ const deps = makeDeps([
+ candidate('/repo/feat-b', 5102, /* alive */ false),
+ candidate('/repo/feat-a', 5101, true),
+ ]);
+ const r = await resolveOffCwdTarget('/repo/feat-b/specs/foo.md', deps);
+ expect(r).toBeNull();
+ });
+
+ test('live shorter-prefix wins over a dead longer-prefix match (liveness gates before longest-prefix)', async () => {
+ const deps = makeDeps([
+ candidate('/repo', 5101, /* alive */ true), // shorter prefix, live
+ candidate('/repo/feat-b', 5102, /* alive */ false), // longer prefix, dead
+ ]);
+ const r = await resolveOffCwdTarget('/repo/feat-b/specs/foo.md', deps);
+ expect(r).toEqual({ baseUrl: 'http://127.0.0.1:5101', docName: 'feat-b/specs/foo' });
+ });
+
+ test('no server contains the target → null (caller ensures/refuses)', async () => {
+ const deps = makeDeps([candidate('/repo/feat-a', 5101)]);
+ const r = await resolveOffCwdTarget('/somewhere/else/notes.md', deps);
+ expect(r).toBeNull();
+ });
+
+ test('symlinked target is realpath-resolved before matching', async () => {
+ const deps = makeDeps([candidate('/repo/feat-b', 5102)], {
+ '/link/notes.md': '/repo/feat-b/notes.md',
+ });
+ const r = await resolveOffCwdTarget('/link/notes.md', deps);
+ expect(r).toEqual({ baseUrl: 'http://127.0.0.1:5102', docName: 'notes' });
+ });
+
+ test('a doc at the contentDir root resolves to its bare name', async () => {
+ const deps = makeDeps([candidate('/proj', 5104)]);
+ const r = await resolveOffCwdTarget('/proj/README.md', deps);
+ expect(r).toEqual({ baseUrl: 'http://127.0.0.1:5104', docName: 'README' });
+ });
+
+ test('an inspect failure on one candidate does not sink the resolution', async () => {
+ const good = candidate('/repo/feat-b', 5102);
+ const deps: OffCwdResolverDeps = {
+ discover: async () => ['/bad/.ok/local', good.lockDir],
+ inspect: async (d) => {
+ if (d === '/bad/.ok/local') throw new Error('stat failed');
+ return good;
+ },
+ realpath: async (p) => p,
+ };
+ const r = await resolveOffCwdTarget('/repo/feat-b/x.md', deps);
+ expect(r?.baseUrl).toBe('http://127.0.0.1:5102');
+ });
+});
+
+describe('projectDirOfLockDir', () => {
+ test('walks up from <projectDir>/.ok/local to <projectDir>', () => {
+ expect(projectDirOfLockDir('/repo/feat-a/.ok/local')).toBe('/repo/feat-a');
+ });
+});
diff --git a/packages/server/src/off-cwd-resolver.ts b/packages/server/src/off-cwd-resolver.ts
new file mode 100644
index 000000000..dca7655f7
--- /dev/null
+++ b/packages/server/src/off-cwd-resolver.ts
@@ -0,0 +1,88 @@
+
+import { realpath as fsRealpath } from 'node:fs/promises';
+import { dirname, relative, resolve, sep } from 'node:path';
+import { readConfigSafely, resolveConfigPath } from '@inkeep/open-knowledge-core/server';
+import { isProcessAlive } from './process-alive.ts';
+import { discoverLockDirs } from './process-scan.ts';
+import { readUiLock } from './ui-lock.ts';
+
+export interface OffCwdCandidate {
+ readonly lockDir: string;
+ readonly contentDir: string;
+ readonly baseUrl: string;
+ readonly alive: boolean;
+}
+
+export interface OffCwdResolverDeps {
+ readonly discover: () => Promise<readonly string[]>;
+ readonly inspect: (lockDir: string) => Promise<OffCwdCandidate | null>;
+ readonly realpath: (p: string) => Promise<string>;
+}
+
+export interface OffCwdResolution {
+ readonly baseUrl: string;
+ readonly docName: string;
+}
+
+function isPathInside(target: string, dir: string): boolean {
+ if (target === dir) return true;
+ const prefix = dir.endsWith(sep) ? dir : dir + sep;
+ return target.startsWith(prefix);
+}
+
+function toDocName(contentDir: string, target: string): string {
+ const rel = relative(contentDir, target).split(sep).join('/');
+ return rel.replace(/\.(md|mdx)$/i, '');
+}
+
+export async function resolveOffCwdTarget(
+ absTarget: string,
+ deps: OffCwdResolverDeps,
+): Promise<OffCwdResolution | null> {
+ const target = await deps.realpath(resolve(absTarget)).catch(() => resolve(absTarget));
+ const lockDirs = await deps.discover();
+ const candidates = await Promise.all(lockDirs.map((d) => deps.inspect(d).catch(() => null)));
+
+ let best: OffCwdCandidate | null = null;
+ for (const c of candidates) {
+ if (c === null || !c.alive) continue;
+ if (!isPathInside(target, c.contentDir)) continue;
+ if (best === null || c.contentDir.length > best.contentDir.length) best = c;
+ }
+ if (best === null) return null;
+ return { baseUrl: best.baseUrl, docName: toDocName(best.contentDir, target) };
+}
+
+export function projectDirOfLockDir(lockDir: string): string {
+ return dirname(dirname(lockDir));
+}
+
+export function createOffCwdResolverDeps(): OffCwdResolverDeps {
+ return {
+ discover: () => discoverLockDirs(),
+ realpath: (p) => fsRealpath(p).catch(() => p),
+ inspect: async (lockDir) => {
+ const projectDir = projectDirOfLockDir(lockDir);
+ let contentDir: string;
+ try {
+ const config = readConfigSafely({
+ absPath: resolveConfigPath('project', projectDir),
+ sideline: false,
+ warn: () => {},
+ });
+ const contentRel = config.value.content?.dir ?? '.';
+ const abs = resolve(projectDir, contentRel);
+ contentDir = await fsRealpath(abs).catch(() => abs);
+ } catch (err) {
+ process.stderr.write(
+ `[off-cwd-resolver] skipping ${lockDir} (config unreadable): ${err instanceof Error ? err.message : String(err)}\n`,
+ );
+ return null;
+ }
+ const lock = readUiLock(lockDir);
+ const port = lock?.port ?? 0;
+ const alive = lock != null && port > 0 && isProcessAlive(lock.pid);
+ return { lockDir, contentDir, baseUrl: `http://localhost:${port}`, alive };
+ },
+ };
+}
diff --git a/packages/cli/src/utils/process-scan.test.ts b/packages/server/src/process-scan.test.ts
similarity index 100%
rename from packages/cli/src/utils/process-scan.test.ts
rename to packages/server/src/process-scan.test.ts
diff --git a/packages/server/src/process-scan.ts b/packages/server/src/process-scan.ts
new file mode 100644
index 000000000..dcc740f72
--- /dev/null
+++ b/packages/server/src/process-scan.ts
@@ -0,0 +1,314 @@
+
+import { spawnSync } from 'node:child_process';
+import { existsSync, lstatSync, readdirSync } from 'node:fs';
+import { realpath } from 'node:fs/promises';
+import { basename, isAbsolute, join } from 'node:path';
+
+const SPAWN_TIMEOUT_MS = 2000;
+const LOCK_SCAN_MAX_DEPTH = 3;
+const LOCK_SCAN_MAX_ENTRIES = 2000;
+const OK_LOCK_DIR_ARG_PREFIX = '--ok-lock-dir-b64=';
+const OK_PROJECT_PATH_ARG_PREFIX = '--ok-project-path=';
+const OK_PROCESS_PGREP_QUERY =
+ 'cli\\.mjs|open-knowledge|Open ?Knowledge(\\.app| Helper)|--ok-lock-dir-b64=|--ok-project-path=|(^|[ /])ok[ ]+(start|mcp|ui)([ ]|$)|packages/(cli|app)|hocuspocus|vite';
+
+const OK_PROCESS_PATTERNS: RegExp[] = [
+ /cli\.mjs/,
+ /(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,
+ /Open ?Knowledge(?:\.app| Helper)/,
+ /(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,
+ /(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,
+ /(^|\s)--ok-lock-dir-b64=/,
+ /(^|\s)--ok-project-path=/,
+];
+
+function isOkProcess(command: string): boolean {
+ return OK_PROCESS_PATTERNS.some((re) => re.test(command));
+}
+
+function extractMarkedLockDir(command: string): string | null {
+ const token = command
+ .trim()
+ .split(/\s+/)
+ .find((part) => part.startsWith(OK_LOCK_DIR_ARG_PREFIX));
+ if (token == null) return null;
+ const encoded = token.slice(OK_LOCK_DIR_ARG_PREFIX.length);
+ if (!encoded) return null;
+ try {
+ const decoded = Buffer.from(encoded, 'base64url').toString('utf8');
+ return isAbsolute(decoded) ? decoded : null;
+ } catch {
+ return null;
+ }
+}
+
+function extractProjectPathArg(command: string): string | null {
+ const markerIdx = command.indexOf(OK_PROJECT_PATH_ARG_PREFIX);
+ if (markerIdx === -1) return null;
+ const valueStart = markerIdx + OK_PROJECT_PATH_ARG_PREFIX.length;
+ const rest = command.slice(valueStart);
+ const nextArgIdx = rest.search(/\s--/);
+ const raw = (nextArgIdx === -1 ? rest : rest.slice(0, nextArgIdx)).trim();
+ if (!raw) return null;
+ return isAbsolute(raw) ? raw : null;
+}
+
+interface OkProcessEntry {
+ pid: number;
+ command: string;
+}
+
+function parsePgrepOutput(output: string): OkProcessEntry[] {
+ const entries: OkProcessEntry[] = [];
+ for (const line of output.split('\n')) {
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+ const spaceIdx = trimmed.indexOf(' ');
+ if (spaceIdx === -1) continue;
+ const pidStr = trimmed.slice(0, spaceIdx);
+ const command = trimmed.slice(spaceIdx + 1);
+ const pid = Number.parseInt(pidStr, 10);
+ if (!Number.isNaN(pid) && isOkProcess(command)) {
+ entries.push({ pid, command });
+ }
+ }
+ return entries;
+}
+
+function parsePsOutput(output: string): OkProcessEntry[] {
+ const entries: OkProcessEntry[] = [];
+ const lines = output.split('\n');
+ for (let i = 1; i < lines.length; i++) {
+ const line = lines[i]?.trim();
+ if (!line) continue;
+ const spaceIdx = line.indexOf(' ');
+ if (spaceIdx === -1) continue;
+ const pidStr = line.slice(0, spaceIdx);
+ const command = line.slice(spaceIdx + 1).trim();
+ const pid = Number.parseInt(pidStr, 10);
+ if (!Number.isNaN(pid) && isOkProcess(command)) {
+ entries.push({ pid, command });
+ }
+ }
+ return entries;
+}
+
+async function findOkProcessEntries(): Promise<OkProcessEntry[]> {
+ const pgrepResult = spawnSync('pgrep', ['-a', '-f', OK_PROCESS_PGREP_QUERY], {
+ encoding: 'utf-8',
+ timeout: SPAWN_TIMEOUT_MS,
+ });
+
+ const pgrepUnavailable =
+ pgrepResult.error != null && (pgrepResult.error as NodeJS.ErrnoException).code === 'ENOENT';
+
+ if (!pgrepUnavailable) {
+ const output = pgrepResult.stdout ?? '';
+ const entries = parsePgrepOutput(output);
+ if (entries.length > 0 || output.trim() === '') return entries;
+ }
+
+ const psResult = spawnSync('ps', ['-axo', 'pid,command'], {
+ encoding: 'utf-8',
+ timeout: SPAWN_TIMEOUT_MS,
+ });
+
+ if (psResult.error != null || !psResult.stdout) {
+ return [];
+ }
+
+ return parsePsOutput(psResult.stdout);
+}
+
+export async function findOkProcessPids(): Promise<number[]> {
+ return (await findOkProcessEntries()).map((e) => e.pid);
+}
+
+export function extractOkBinaryPath(command: string): string | null {
+ const tokens = command.trim().split(/\s+/).filter(Boolean);
+ for (const token of tokens) {
+ if (token.startsWith('@')) continue;
+ const base = basename(token);
+ if (base === 'open-knowledge' || base === 'ok') return token;
+ if (
+ token.endsWith('/packages/cli/src/cli.ts') ||
+ token.endsWith('/packages/cli/dist/cli.mjs')
+ ) {
+ return token;
+ }
+ if (base === 'cli.mjs' || base === 'cli.ts') return token;
+ }
+ return null;
+}
+
+export function processCommand(pid: number): string | null {
+ const result = spawnSync('ps', ['-p', String(pid), '-o', 'command='], {
+ encoding: 'utf-8',
+ timeout: SPAWN_TIMEOUT_MS,
+ });
+
+ if (result.error != null || !result.stdout) return null;
+ return result.stdout.trim() || null;
+}
+
+export interface ProcessUsage {
+ cpuPercent: number;
+ memPercent: number;
+}
+
+export function processUsage(pid: number): ProcessUsage | null {
+ const result = spawnSync('ps', ['-p', String(pid), '-o', '%cpu=,%mem='], {
+ encoding: 'utf-8',
+ timeout: SPAWN_TIMEOUT_MS,
+ });
+
+ if (result.error != null || !result.stdout) return null;
+ const [cpuRaw, memRaw] = result.stdout.trim().split(/\s+/);
+ const cpuPercent = Number.parseFloat(cpuRaw ?? '');
+ const memPercent = Number.parseFloat(memRaw ?? '');
+ if (Number.isNaN(cpuPercent) || Number.isNaN(memPercent)) return null;
+ return { cpuPercent, memPercent };
+}
+
+export async function pidCwd(pid: number): Promise<string | null> {
+ const result = spawnSync('lsof', ['-p', String(pid), '-a', '-d', 'cwd', '-Fn'], {
+ encoding: 'utf-8',
+ timeout: SPAWN_TIMEOUT_MS,
+ });
+
+ if (result.error != null) {
+ return null;
+ }
+
+ const output = result.stdout ?? '';
+ for (const line of output.split('\n')) {
+ if (line.startsWith('n') && line.length > 1) {
+ return line.slice(1);
+ }
+ }
+
+ return null;
+}
+
+function parseListeningPids(output: string): number[] {
+ const pids: number[] = [];
+ const lines = output.split('\n');
+ for (let i = 1; i < lines.length; i++) {
+ const line = lines[i]?.trim();
+ if (!line) continue;
+ const parts = line.split(/\s+/);
+ if (parts.length < 2) continue;
+ const pid = Number.parseInt(parts[1] ?? '', 10);
+ if (!Number.isNaN(pid)) {
+ pids.push(pid);
+ }
+ }
+ return [...new Set(pids)];
+}
+
+function hasLockFile(lockDir: string): boolean {
+ return existsSync(join(lockDir, 'server.lock')) || existsSync(join(lockDir, 'ui.lock'));
+}
+
+function addLockDirsForCwd(candidateDirs: Set<string>, cwd: string): void {
+ for (const lockDir of [join(cwd, '.ok', 'local'), join(cwd, '.ok')]) {
+ if (existsSync(lockDir) && hasLockFile(lockDir)) {
+ candidateDirs.add(lockDir);
+ }
+ }
+}
+
+function addLockDirsUnderCwd(candidateDirs: Set<string>, cwd: string): void {
+ let visited = 0;
+
+ const walk = (dir: string, depth: number): void => {
+ if (visited >= LOCK_SCAN_MAX_ENTRIES) return;
+ visited++;
+
+ addLockDirsForCwd(candidateDirs, dir);
+ if (depth >= LOCK_SCAN_MAX_DEPTH) return;
+
+ let entries: string[];
+ try {
+ entries = readdirSync(dir);
+ } catch {
+ return;
+ }
+
+ for (const entry of entries) {
+ if (visited >= LOCK_SCAN_MAX_ENTRIES) return;
+ if (entry === 'node_modules' || entry === '.git' || entry === 'Library') continue;
+ if (entry.startsWith('.') && entry !== '.ok') continue;
+
+ const child = join(dir, entry);
+ let isDirectory = false;
+ try {
+ isDirectory = lstatSync(child).isDirectory();
+ } catch {
+ continue;
+ }
+ if (isDirectory) walk(child, depth + 1);
+ }
+ };
+
+ walk(cwd, 0);
+}
+
+export async function discoverLockDirs(): Promise<string[]> {
+ const candidateDirs = new Set<string>();
+
+ const okEntries = await findOkProcessEntries();
+ const cwdPromises = okEntries.map((e) => pidCwd(e.pid));
+ const cwds = await Promise.all(cwdPromises);
+
+ for (const entry of okEntries) {
+ const markedLockDir = extractMarkedLockDir(entry.command);
+ if (markedLockDir != null && existsSync(markedLockDir)) {
+ candidateDirs.add(markedLockDir);
+ }
+
+ const projectPath = extractProjectPathArg(entry.command);
+ if (projectPath != null) {
+ addLockDirsForCwd(candidateDirs, projectPath);
+ }
+ }
+
+ for (const cwd of cwds) {
+ if (cwd == null) continue;
+ addLockDirsForCwd(candidateDirs, cwd);
+ }
+
+ const lsofResult = spawnSync('lsof', ['-iTCP', '-sTCP:LISTEN', '-nP'], {
+ encoding: 'utf-8',
+ timeout: SPAWN_TIMEOUT_MS,
+ });
+
+ if (lsofResult.error == null && lsofResult.stdout) {
+ const listeningPids = parseListeningPids(lsofResult.stdout);
+ const knownPidSet = new Set(okEntries.map((e) => e.pid));
+ const newPids = listeningPids.filter((p) => !knownPidSet.has(p));
+ const portCwdPromises = newPids.map((pid) => pidCwd(pid));
+ const portCwds = await Promise.all(portCwdPromises);
+
+ for (const cwd of portCwds) {
+ if (cwd == null) continue;
+ addLockDirsForCwd(candidateDirs, cwd);
+ }
+ }
+
+ if (candidateDirs.size === 0 || cwds.some((cwd) => cwd === '/')) {
+ addLockDirsUnderCwd(candidateDirs, process.cwd());
+ }
+
+ const canonical = new Map<string, string>();
+ for (const dir of candidateDirs) {
+ try {
+ const real = await realpath(dir);
+ canonical.set(real, real);
+ } catch {
+ canonical.set(dir, dir);
+ }
+ }
+
+ return [...canonical.values()];
+}