Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): stop in-app agents pasting localhost preview URLs (PRD-7767) (#3165)
Andrew Mikofalvy555e10235575
diff --git a/.changeset/hosted-agent-preview-steer.md b/.changeset/hosted-agent-preview-steer.mdnew file mode 100644index 000000000..7bca245c1--- /dev/null+++ b/.changeset/hosted-agent-preview-steer.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Agents in the in-app agent panel no longer answer with a `localhost` preview link to the app you are already looking at. After creating or editing a doc, an agent would sometimes end its reply with a bare `http://localhost:<port>/#/...` URL instead of just bringing the doc up on screen. The steer that prevents this already existed, but it only recognized agents running in the desktop app's built-in terminal, so the agent panel never received it and fell back to handing over a raw URL. Every way a panel agent reaches OpenKnowledge now carries the same signal, and the guidance is explicit that the URL should not be pasted into a reply when you are already in the app. Agents outside the app are unaffected and still get a URL they can open.diff --git a/packages/cli/src/mcp/server.ts b/packages/cli/src/mcp/server.tsindex e691e343f..71076993d 100644--- a/packages/cli/src/mcp/server.ts+++ b/packages/cli/src/mcp/server.ts@@ -31,7 +31,7 @@ import { realpathSync, statSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import { promisify } from 'node:util';-import { OK_PROJECT_MARKER } from '@inkeep/open-knowledge-core';+import { OK_PROJECT_MARKER, resolveIsHostedAgent } from '@inkeep/open-knowledge-core';import { type KeepaliveHandle, startKeepalive } from '@inkeep/open-knowledge-core/keepalive';import {type AgentIdentity,@@ -433,11 +433,13 @@ export async function startGlobalMcpServer(resolveCwd,config: resolveConfigForCwd,identityRef,- // This `ok mcp` process inherits `OK_DESKTOP_TERMINAL=1` from OK Desktop's- // built-in terminal pty when the agent runs there (and only there — nothing- // else sets it). `preview_url` uses it to steer the agent to `ok open`- // instead of returning a URL it shouldn't navigate.- isDesktopTerminal: process.env.OK_DESKTOP_TERMINAL === '1',+ // Two disjoint markers, one meaning: the agent driving this `ok mcp` is+ // running inside an OpenKnowledge surface, so the user is already looking+ // at the app. `OK_DESKTOP_TERMINAL` comes from the desktop terminal's pty;+ // `OK_HOSTED_AGENT` from the agents OK launches itself. Either way+ // `preview_url` steers to `ok open` instead of handing back a URL the+ // agent shouldn't navigate.+ isHostedAgent: resolveIsHostedAgent(process.env),});const transport = new StdioServerTransport();diff --git a/packages/core/src/constants/mcp.test.ts b/packages/core/src/constants/mcp.test.tsnew file mode 100644index 000000000..9daf62149--- /dev/null+++ b/packages/core/src/constants/mcp.test.ts@@ -0,0 +1,50 @@+/**+ * `resolveIsHostedAgent` — the shared read of the two hosted-agent markers.+ *+ * Both markers are set on different paths (the desktop pty host; the ACP agent+ * spawn) but mean the same thing to `preview_url`, so the OR lives in one+ * place. These tests pin the exact-'1' comparison: a truthy-coercing read+ * would treat `OK_HOSTED_AGENT=0` — the shape an operator reaches for to turn+ * the marker off — as hosted, which silently suppresses the preview URL for+ * an agent that legitimately needs one.+ */++import { describe, expect, test } from 'vitest';+import { OK_DESKTOP_TERMINAL_ENV, OK_HOSTED_AGENT_ENV, resolveIsHostedAgent } from './mcp.ts';++describe('resolveIsHostedAgent', () => {+ test('either marker alone is enough — the two surfaces are disjoint by construction', () => {+ expect(resolveIsHostedAgent({ [OK_DESKTOP_TERMINAL_ENV]: '1' })).toBe(true);+ expect(resolveIsHostedAgent({ [OK_HOSTED_AGENT_ENV]: '1' })).toBe(true);+ });++ test('both set (belt-and-braces paths overlapping) still resolves hosted', () => {+ expect(+ resolveIsHostedAgent({+ [OK_DESKTOP_TERMINAL_ENV]: '1',+ [OK_HOSTED_AGENT_ENV]: '1',+ }),+ ).toBe(true);+ });++ test('an env with neither marker is not hosted — external agents keep their URL', () => {+ expect(resolveIsHostedAgent({})).toBe(false);+ expect(resolveIsHostedAgent({ PATH: '/usr/bin', HOME: '/home/x' })).toBe(false);+ });++ test('only the exact value "1" counts', () => {+ for (const value of ['0', '', 'true', 'yes', 'false']) {+ expect(resolveIsHostedAgent({ [OK_HOSTED_AGENT_ENV]: value })).toBe(false);+ expect(resolveIsHostedAgent({ [OK_DESKTOP_TERMINAL_ENV]: value })).toBe(false);+ }+ });++ test('undefined values (the shape process.env hands us) are not hosted', () => {+ expect(+ resolveIsHostedAgent({+ [OK_HOSTED_AGENT_ENV]: undefined,+ [OK_DESKTOP_TERMINAL_ENV]: undefined,+ }),+ ).toBe(false);+ });+});diff --git a/packages/core/src/constants/mcp.ts b/packages/core/src/constants/mcp.tsindex 6563c2846..bd967fe41 100644--- a/packages/core/src/constants/mcp.ts+++ b/packages/core/src/constants/mcp.ts@@ -19,3 +19,41 @@ export const GREP_MAX_RESULTS = 50;* re-exports it) stay in lockstep with the value editor wiring writes.*/export const MCP_SERVER_NAME = 'open-knowledge';++/**+ * Env marker stamped on every agent OpenKnowledge launches itself — today the+ * in-app agent panel. An `ok mcp` process spawned by such an agent inherits+ * it, which is how `preview_url` distinguishes "this agent is hosted by an+ * OpenKnowledge surface, so the user is already looking at the app" from+ * "this agent is elsewhere and genuinely needs a URL".+ *+ * Sibling of `OK_DESKTOP_TERMINAL` (set by the desktop pty host for the+ * built-in terminal). The two are disjoint by construction: pty-host strips+ * the Electron host markers and sets its own, so a shell agent carries+ * exactly one of them and a panel agent the other. Both mean the same thing+ * to `preview_url` — steer to `ok open`, do not hand back a URL.+ *+ * Deliberately NOT keyed on "is the desktop app running": an external editor+ * with its own browser pane still wants a navigable URL even while Desktop is+ * open. Only agents OK spawns carry this.+ */+export const OK_HOSTED_AGENT_ENV = 'OK_HOSTED_AGENT';++/**+ * The pty host's marker for the desktop app's built-in terminal. Named here+ * so both the set site and the read site reference one symbol and a typo is a+ * compile error rather than a silently unmarked agent.+ */+export const OK_DESKTOP_TERMINAL_ENV = 'OK_DESKTOP_TERMINAL';++/**+ * Whether the agent driving a process with this environment is hosted by an+ * OpenKnowledge surface — the desktop terminal or the in-app agent panel.+ *+ * The two markers are set by different code on different paths but mean the+ * same thing to every consumer, so the OR lives here rather than being+ * re-spelled at each read site.+ */+export function resolveIsHostedAgent(env: Record<string, string | undefined>): boolean {+ return env[OK_DESKTOP_TERMINAL_ENV] === '1' || env[OK_HOSTED_AGENT_ENV] === '1';+}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 1c18b39b0..e4ac295d0 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -326,7 +326,14 @@ export {KNOWN_NON_GITHUB_GIT_HOSTS,} from './constants/github.ts';export { isOrphanMode, ORPHAN_MODES, type OrphanMode } from './constants/graph.ts';-export { GREP_MAX_RESULTS, MCP_SERVER_NAME, READ_DOCUMENT_HISTORY_DEPTH } from './constants/mcp.ts';+export {+ GREP_MAX_RESULTS,+ MCP_SERVER_NAME,+ OK_DESKTOP_TERMINAL_ENV,+ OK_HOSTED_AGENT_ENV,+ READ_DOCUMENT_HISTORY_DEPTH,+ resolveIsHostedAgent,+} from './constants/mcp.ts';export {MENU_LABELS,type MenuLabelKey,diff --git a/packages/desktop/src/utility/pty-host.ts b/packages/desktop/src/utility/pty-host.tsindex 914e90e38..43ece3879 100644--- a/packages/desktop/src/utility/pty-host.ts+++ b/packages/desktop/src/utility/pty-host.ts@@ -12,6 +12,7 @@*/import { delimiter, join } from 'node:path';+import { OK_DESKTOP_TERMINAL_ENV } from '@inkeep/open-knowledge-core';const DARWIN_FALLBACK_SHELL = '/bin/zsh';@@ -245,7 +246,7 @@ export function buildShellEnv(// keys off this to pick `ok open <doc>` (focuses a tab in THIS window) over// resolving a preview URL — otherwise the agent can't tell where it's running// and guesses the browser path. Set last so it can't be shadowed by parentEnv.- out.OK_DESKTOP_TERMINAL = '1';+ out[OK_DESKTOP_TERMINAL_ENV] = '1';return out;}diff --git a/packages/desktop/tests/utility/pty-host.test.ts b/packages/desktop/tests/utility/pty-host.test.tsindex 44ddb346c..3d4f71574 100644--- a/packages/desktop/tests/utility/pty-host.test.ts+++ b/packages/desktop/tests/utility/pty-host.test.ts@@ -1,3 +1,4 @@+import { OK_DESKTOP_TERMINAL_ENV } from '@inkeep/open-knowledge-core';import { describe, expect, test } from 'vitest';import {buildShellArgs,@@ -187,10 +188,10 @@ describe('setupPtyHost — create', () => {test('marks the shell as the OK Desktop terminal (OK_DESKTOP_TERMINAL=1)', () => {// Positive identity the project skill keys off to pick `ok open` over a// preview URL. Set even when the parent tries to clear it.- const h = makeHarness({ env: { SHELL: '/bin/zsh', OK_DESKTOP_TERMINAL: '' } });+ const h = makeHarness({ env: { SHELL: '/bin/zsh', [OK_DESKTOP_TERMINAL_ENV]: '' } });h.fire(CREATE());const env = h.spawnCalls[0]?.options.env ?? {};- expect(env.OK_DESKTOP_TERMINAL).toBe('1');+ expect(env[OK_DESKTOP_TERMINAL_ENV]).toBe('1');});test('prepends ~/.ok/bin to the child PATH so `ok` resolves regardless of rc consent', () => {@@ -636,7 +637,7 @@ describe('buildShellEnv', () => {expect(env).toEqual({PATH: '/Users/x/.ok/bin:/usr/bin',HOME: '/Users/x',- OK_DESKTOP_TERMINAL: '1',+ [OK_DESKTOP_TERMINAL_ENV]: '1',});});});diff --git a/packages/server/assets/skills/project/SKILL.md b/packages/server/assets/skills/project/SKILL.mdindex 167876d45..ab3f82fe8 100644--- a/packages/server/assets/skills/project/SKILL.md+++ b/packages/server/assets/skills/project/SKILL.md@@ -18,7 +18,7 @@ OpenKnowledge (OK) is a markdown-CRDT collaboration platform exposed via MCP. Th1. **Reads:** `exec("cat …")` for one doc, `exec("ls -A …")` for a directory (folder defaults + template menu), `exec("grep …")` for literal, `search` for ranked retrieval. Native `Read` / `Grep` only on source code (`.ts` / `.py` / …), never on in-scope `.md` / `.mdx`.2. **Writes:** `write({ document: { path, content } })` for a new or full-replace doc; `edit({ document: { path, find, replace } })` for a body find/replace; `edit({ document: { path, frontmatter } })` for a frontmatter merge-patch (`null` deletes a key). `delete({ document })` removes, `move({ from, to })` moves/renames. Body find/replace is body-only. Pass a one-line `summary` (≤80 chars, user-facing outcome) on every content write.-3. **Preview / open a doc — determine your ONE surface FIRST (once per session).** Stop at first match: **`OK_DESKTOP_TERMINAL` set** → OK Desktop's terminal → `ok open <name>` (switches this window) · in-app browser (Claude Code Desktop's Browser pane, Cursor, Codex) → `preview_url`, then open/navigate it to the doc · else plain CLI → `ok open <name>`. `ok open <name>` opens a doc or folder (auto-detected); `--skill <name>` for a skill. The `previewUrl` field is a route id, **not** your open mechanism. Don't `preview_screenshot` to confirm edits. Full Step-0 procedure + per-surface how-to: `references/preview.md`.+3. **Preview / open a doc — determine your ONE surface FIRST (once per session).** Stop at first match: **`OK_DESKTOP_TERMINAL` or `OK_HOSTED_AGENT` set** → you're inside OpenKnowledge (desktop terminal / in-app agent panel) → `ok open <name>` (switches the window the user is already looking at); never paste a `localhost` URL into your reply here · in-app browser (Claude Code Desktop's Browser pane, Cursor, Codex) → `preview_url`, then open/navigate it to the doc · else plain CLI → `ok open <name>`. `ok open <name>` opens a doc or folder (auto-detected); `--skill <name>` for a skill. The `previewUrl` field is a route id, **not** your open mechanism. Don't `preview_screenshot` to confirm edits. Full Step-0 procedure + per-surface how-to: `references/preview.md`.4. **Knowledge layers:** capturing a source (ingest), synthesizing findings (research), promoting a decision (consolidate) — procedures, **not tool calls**; there is no `ingest` tool. Ingest ships here (`references/ingest-and-sources.md`); research + consolidate come with the `knowledge-base` pack. Layer model + packs: `references/starter-packs.md`.5. **Direct questions:** a plain business question ("which customers…", "what did we decide about…") routes to `search` / `exec` + a cited chat answer — no "research" keyword needed. Persist only when durable + multi-doc + not already covered, and *offer* first. See `references/corpus-qa.md`.6. **Authoring or improving a skill** ("write/make a skill", "improve this skill", "turn this into a skill"): STOP and invoke the **`open-knowledge-write-skill`** skill — it owns scope choice (project vs global), the SKILL.md contract, evaluation, and install; don't improvise here. Author through the `skill` target (`write({ skill })`), never a raw path document. Skills are REAL folders under the editor dirs' `skills/` (`.claude` · `.cursor` · `.codex` · `.opencode` · `.pi` · `.agents`): ONE is the source, the rest are managed copies/symlinks. **Read and edit via the tools (`skills`, `edit({ skill })`) — they route to the source.** Never hand-edit a non-source copy: unedited copies refresh from the source, and editing one forks it into its own skill that stops refreshing.diff --git a/packages/server/assets/skills/project/references/preview.md b/packages/server/assets/skills/project/references/preview.mdindex 5e602c2d1..fb386288b 100644--- a/packages/server/assets/skills/project/references/preview.md+++ b/packages/server/assets/skills/project/references/preview.md@@ -21,7 +21,7 @@ The user watches your edits land in a live browser preview. Open it once at sessYour host doesn't change mid-session, so determine this **once**, the first time you're asked to open/show/preview a doc, and use that one surface for the rest of the session. Run the checks **top-to-bottom and stop at the first match** — earlier rungs win:-1. **Is `OK_DESKTOP_TERMINAL` set in your environment?** You're a shell agent — actually check it (`echo "$OK_DESKTOP_TERMINAL"`, or read your env), don't assume. **Set → you're inside the OK Desktop app's own terminal.** Open a doc or folder with `ok open <name>` (auto-detected; `--skill <name>` for a skill) — it switches THIS window to the target. **Never resolve a preview URL here.** (This rung is the one agents miss most — check the env first, before anything else.)+1. **Is `OK_DESKTOP_TERMINAL` or `OK_HOSTED_AGENT` set in your environment?** Actually check (`echo "$OK_DESKTOP_TERMINAL$OK_HOSTED_AGENT"`, or read your env), don't assume. **Either one set → you are running inside OpenKnowledge itself** — `OK_DESKTOP_TERMINAL` in the desktop app's built-in terminal, `OK_HOSTED_AGENT` in its in-app agent panel. Open a doc or folder with `ok open <name>` (auto-detected; `--skill <name>` for a skill) — it switches the window the user is already looking at to the target. **Never resolve a preview URL here, and never paste one into your reply**: the user is looking at the app that URL points to, so a `localhost` link is noise at best. (This rung is the one agents miss most — check the env first, before anything else.)2. **Do you have any URL-navigation / in-app browser tool** (Claude Code Desktop's **Browser pane**, Cursor's `Navigate`, Codex's `@Browser`, or `browser` / `open_url` / `view_url` / …)? → **Claude Code Desktop / Cursor / Codex desktop** → `preview_url` once, then open/navigate that browser to the `url` (per-surface how-to below — Claude Desktop opens the pane with `preview_start({ url })` then `navigate({ url })` to move; Cursor/Codex navigate directly).3. **None of the above** → you're a **plain CLI** (Claude Code CLI, Codex CLI, Cursor CLI, OpenCode, Pi, any shell agent) → `ok open <name>` for a doc or folder (auto-detected; `--skill <name>` for a skill); deep-links a separate OK Desktop window, system browser only if no desktop.@@ -42,7 +42,7 @@ Decide once; then every "open / show / preview this doc" this session uses that- **`ok open <skill-name> --skill [--scope project|global]`** — opens a **skill** in the skill editor (skills are addressed by name + scope, not a content path, so they need the flag).- All three deep-link into OK Desktop when a bundle is installed, and fall back to the browser UI (`ok ui`) otherwise. No `ok` on PATH or no shell → `preview_url`, then `open <url>` in the system browser as a last resort, and say so plainly. The system browser is the fallback, never the default.-(The same vendors' *desktop apps* with a built-in browser — Cursor, Codex desktop — are NOT here; they navigate their own browser per the in-app branch above. Codex **IDE extension** / **Cloud** are web-search-only → they're on this CLI track too.) **Running inside the OK Desktop built-in terminal (the `OK_DESKTOP_TERMINAL` env var is set)? Same track — `ok open <name>` re-targets the window you're already in** (switches that window to the doc/folder; no second window, no need to raise it since it's already frontmost). Don't resolve preview URLs in that case; `ok open` is the whole answer.+(The same vendors' *desktop apps* with a built-in browser — Cursor, Codex desktop — are NOT here; they navigate their own browser per the in-app branch above. Codex **IDE extension** / **Cloud** are web-search-only → they're on this CLI track too.) **Running inside OpenKnowledge itself — the desktop built-in terminal (`OK_DESKTOP_TERMINAL`) or the in-app agent panel (`OK_HOSTED_AGENT`)? Same track — `ok open <name>` re-targets the surface you're already in** (switches it to the doc/folder; when that surface is a desktop window there's no second window, and no need to raise it since it's already frontmost). Don't resolve preview URLs in that case; `ok open` is the whole answer.**Opening or reading a file IS a preview navigation.** On any "open `<file>`" / "read `<file>`" request, navigate the browser to that doc's `previewUrl` route from the tool response — not a separate fetch, not a fresh system-browser launch.diff --git a/packages/server/src/acp/launch.test.ts b/packages/server/src/acp/launch.test.tsindex 4a37fd989..915065e0f 100644--- a/packages/server/src/acp/launch.test.ts+++ b/packages/server/src/acp/launch.test.ts@@ -11,6 +11,7 @@import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { delimiter, join } from 'node:path';+import { OK_HOSTED_AGENT_ENV } from '@inkeep/open-knowledge-core';import { afterEach, describe, expect, test } from 'vitest';import {AgentLaunchError,@@ -21,6 +22,7 @@ import {spawnAcpAgent,terminateAgentTree,windowsCmdWrap,+ withHostedAgentMarker,} from './launch.ts';describe('mergedEnv PATH augmentation', () => {@@ -96,6 +98,41 @@ afterEach(() => {dirs = [];});+describe('hosted-agent marker', () => {+ test('sets the marker and leaves the rest of the env alone', () => {+ const out = withHostedAgentMarker({ FOO: 'bar' });+ expect(out[OK_HOSTED_AGENT_ENV]).toBe('1');+ expect(out.FOO).toBe('bar');+ });++ test('wins over a launch env that already set the key — hosting is our fact, not the agent config’s', () => {+ expect(withHostedAgentMarker({ [OK_HOSTED_AGENT_ENV]: '0' })[OK_HOSTED_AGENT_ENV]).toBe('1');+ });++ // The marker only earns its keep if it survives into the spawned process —+ // that is the hop `ok mcp` reads it across. Assert on a real spawn rather+ // than on the helper's return value.+ test('a really-spawned agent receives it in its environment', async () => {+ const dir = tmp();+ const script = join(dir, 'echo-marker.js');+ // Write-then-rename: a plain writeFileSync makes the path observable the+ // instant it is created, so a waiter polling on existence can read it back+ // empty before the bytes land. The rename publishes it already complete.+ writeFileSync(+ script,+ [+ "const fs = require('node:fs');",+ `fs.writeFileSync(process.argv[1] + '.tmp', String(process.env.${OK_HOSTED_AGENT_ENV} ?? 'ABSENT'));`,+ "fs.renameSync(process.argv[1] + '.tmp', process.argv[1] + '.out');",+ ].join('\n'),+ );+ const child = spawnAcpAgent(launchFor(script), dir);+ if (child.pid !== undefined) strayPids.push(child.pid);+ await waitFor(() => existsSync(`${script}.out`), 10_000, 'spawned agent to report its env');+ expect(readFileSync(`${script}.out`, 'utf8')).toBe('1');+ });+});+describe('preflightLaunch', () => {const catchErr = (p: Promise<unknown>): Promise<unknown> => p.then(() => null).catch((e) => e);diff --git a/packages/server/src/acp/launch.ts b/packages/server/src/acp/launch.tsindex f538dc5e6..6aef767ed 100644--- a/packages/server/src/acp/launch.ts+++ b/packages/server/src/acp/launch.ts@@ -19,7 +19,7 @@ import { constants, statSync } from 'node:fs';import { access, chmod, stat } from 'node:fs/promises';import { homedir, tmpdir } from 'node:os';import { delimiter, isAbsolute, join, resolve } from 'node:path';-import { augmentAgentSpawnPath, OK_DIR } from '@inkeep/open-knowledge-core';+import { augmentAgentSpawnPath, OK_DIR, OK_HOSTED_AGENT_ENV } from '@inkeep/open-knowledge-core';import { tracedMkdir, tracedRename, tracedRm } from '../fs-traced.ts';import type { PinoLogger } from '../logger.ts';import { downloadToFileWithSha, extractArchive, isWithin, sanitizeSegment } from './archive.ts';@@ -87,6 +87,24 @@ export function mergedEnv(overlay?: Record<string, string>): Record<string, strireturn { ...base, ...overlay };}+/**+ * Stamp the hosted-agent marker onto an agent's spawn env.+ *+ * Applied at the spawn site rather than inside `mergedEnv` so it lands on+ * real agent launches only — the harness-availability probe builds its env+ * from `mergedEnv` too, and a throwaway `--version` check is not a hosted+ * agent. Applied AFTER the caller's overlay: whether OK is hosting this agent+ * is our fact about the launch, not a per-agent registry setting to override.+ *+ * The marker's reason for existing is the hop it survives: the agent we spawn+ * goes on to spawn its own `ok mcp` (from the harness's MCP config, which OK+ * does not control), and that process reads the marker to decide whether to+ * hand the agent a preview URL or steer it to `ok open`.+ */+export function withHostedAgentMarker(env: Record<string, string>): Record<string, string> {+ return { ...env, [OK_HOSTED_AGENT_ENV]: '1' };+}+/*** Resolve a registry agent to a spawnable command, downloading + extracting* a binary distribution when that's the only option. Preference order@@ -415,7 +433,7 @@ export function spawnAcpAgent(launch: ResolvedLaunch, cwd: string): ChildProcess: { cmd: resolved, args: launch.args };return spawn(cmd, args, {cwd,- env: launch.env,+ env: withHostedAgentMarker(launch.env),stdio: ['pipe', 'pipe', 'pipe'],shell: false,detached: !win,diff --git a/packages/server/src/acp/mcp-injection-skip.test.ts b/packages/server/src/acp/mcp-injection-skip.test.tsindex 7ef4f96cc..dd70111d7 100644--- a/packages/server/src/acp/mcp-injection-skip.test.ts+++ b/packages/server/src/acp/mcp-injection-skip.test.ts@@ -9,9 +9,11 @@import { mkdtempSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';+import { OK_HOSTED_AGENT_ENV } from '@inkeep/open-knowledge-core';import { afterEach, describe, expect, test } from 'vitest';import type { AgentSessionManager } from '../agent-sessions.ts';import { getLogger } from '../logger.ts';+import { MCP_HOSTED_AGENT_HEADER } from '../mcp/agent-identity.ts';import { AcpPermissionStore } from './permissions.ts';import { AcpRegistry } from './registry.ts';import {@@ -51,7 +53,14 @@ type BuildMcpServersSeam = {info: { threadId: string };},init: { agentCapabilities?: { mcpCapabilities?: { http?: boolean } } },- ) => Promise<Array<{ name: string; type?: string }>>;+ ) => Promise<+ Array<{+ name: string;+ type?: string;+ env?: Array<{ name: string; value: string }>;+ headers?: Array<{ name: string; value: string }>;+ }>+ >;};function makeManager(@@ -110,6 +119,31 @@ describe('buildMcpServers × probeHarnessManagedMcpEntry', () => {expect(servers[0]).toMatchObject({ name: 'open-knowledge', type: 'http' });});+ // The env marker cannot travel over HTTP, so the hosted-agent fact rides a+ // header. Without it an HTTP-capable panel agent reaches `preview_url` on+ // the shared server, where the steer can't be computed, and gets the bare+ // URL this whole change exists to suppress.+ test('the injected HTTP server carries the hosted-agent header', async () => {+ const m = makeManager(() => null);+ const servers = await m.buildMcpServers(record('registry', 'codex-acp'), HTTP_INIT);+ expect(servers[0]).toMatchObject({+ type: 'http',+ headers: [{ name: MCP_HOSTED_AGENT_HEADER, value: '1' }],+ });+ });++ // On this branch we name the command, so the marker can be guaranteed+ // rather than left to inheritance through the agent process.+ test('the injected stdio server carries the hosted-agent marker', async () => {+ const m = makeManager(() => null);+ const servers = await m.buildMcpServers(record('registry', 'claude-acp'), {});+ expect(servers).toHaveLength(1);+ expect(servers[0]).toMatchObject({+ name: 'open-knowledge',+ env: [{ name: OK_HOSTED_AGENT_ENV, value: '1' }],+ });+ });+test('never probes for custom agents or registry agents without an OK config surface', async () => {let calls = 0;const m = makeManager(() => {diff --git a/packages/server/src/acp/terminals.test.ts b/packages/server/src/acp/terminals.test.tsindex bf4d79bbe..419bad22e 100644--- a/packages/server/src/acp/terminals.test.ts+++ b/packages/server/src/acp/terminals.test.ts@@ -1,3 +1,4 @@+import { OK_HOSTED_AGENT_ENV } from '@inkeep/open-knowledge-core';import type { ThreadEvent } from '@inkeep/open-knowledge-core/acp/thread-protocol';import { afterEach, describe, expect, test } from 'vitest';import { getLogger } from '../logger.ts';@@ -47,6 +48,32 @@ describe('AcpTerminalSet', () => {expect(created.command).toBe(process.execPath);});+ // A terminal is a peer of the agent's own child processes: an agent that+ // routes its shell through `terminal/create` rather than spawning in-process+ // must still look hosted, or an `ok mcp` started there hands the user a URL.+ test('a created terminal carries the hosted-agent marker', async () => {+ const events: ThreadEvent[] = [];+ const set = makeSet(events);+ const { terminalId } = set.create(+ node(`process.stdout.write(String(process.env.${OK_HOSTED_AGENT_ENV} ?? 'ABSENT'))`),+ );+ await set.waitForExit(terminalId);+ expect(set.output(terminalId).output).toBe('1');+ });++ test('an explicit env overlay does not displace the hosted-agent marker', async () => {+ const events: ThreadEvent[] = [];+ const set = makeSet(events);+ const { terminalId } = set.create({+ ...node(+ `process.stdout.write(String(process.env.${OK_HOSTED_AGENT_ENV} ?? 'ABSENT') + ':' + String(process.env.MY_VAR))`,+ ),+ env: [{ name: 'MY_VAR', value: 'kept' }],+ });+ await set.waitForExit(terminalId);+ expect(set.output(terminalId).output).toBe('1:kept');+ });+test('captures stderr interleaved and a non-zero exit code', async () => {const events: ThreadEvent[] = [];const set = makeSet(events);diff --git a/packages/server/src/acp/terminals.ts b/packages/server/src/acp/terminals.tsindex 691c3ad33..4b1e88ab1 100644--- a/packages/server/src/acp/terminals.ts+++ b/packages/server/src/acp/terminals.ts@@ -30,6 +30,7 @@ import {resolveWindowsCommand,terminateAgentTree,windowsCmdWrap,+ withHostedAgentMarker,} from './launch.ts';/** Retained-output default when the agent sends no `outputByteLimit`. */@@ -156,7 +157,14 @@ export class AcpTerminalSet {const terminalId = crypto.randomUUID();const overlay: Record<string, string> = {};for (const entry of params.env ?? []) overlay[entry.name] = entry.value;- const env = mergedEnv(overlay);+ // A terminal only ever exists because an agent OK is hosting asked for+ // one, so the hosted-agent fact is true by construction here. Stamping it+ // matters because this spawn is a peer of the agent's own child processes:+ // an agent that routes its shell through `terminal/create` (OK advertises+ // `terminal: true`) would otherwise run `ok mcp`, or an env check, in a+ // process that never saw the marker — and fall back to handing the user a+ // URL, which is the failure this marker exists to prevent.+ const env = withHostedAgentMarker(mergedEnv(overlay));const cwd =params.cwd != null? isAbsolute(params.cwd)diff --git a/packages/server/src/acp/thread-manager.ts b/packages/server/src/acp/thread-manager.tsindex 89caf26bd..146d2d526 100644--- a/packages/server/src/acp/thread-manager.ts+++ b/packages/server/src/acp/thread-manager.ts@@ -48,6 +48,7 @@ import {colorFromSeed,type EditorId,iconFromClientName,+ OK_HOSTED_AGENT_ENV,} from '@inkeep/open-knowledge-core';import type {QueuedMessage,@@ -67,6 +68,7 @@ import {} from '../agent-sessions.ts';import { isConfigDoc, isSystemDoc } from '../cc1-broadcast.ts';import type { PinoLogger } from '../logger.ts';+import { MCP_HOSTED_AGENT_HEADER } from '../mcp/agent-identity.ts';import { boundSessionUpdateForLog, coalesceChunkInto } from './event-log-bounds.ts';import {AgentLaunchError,@@ -944,11 +946,15 @@ export class AcpThreadManager {const serverUrl = this.opts.getServerUrl?.();if (serverUrl !== undefined && init.agentCapabilities?.mcpCapabilities?.http === true) {// Preferred: a direct HTTP MCP connection to this running server.+ // The env marker the stdio branch uses cannot travel over HTTP, so the+ // hosted-agent fact rides a header instead. It has to be per-connection:+ // this same server also answers external clients that legitimately want+ // a navigable URL, so the signal cannot live on the server process.mcpServers.push({type: 'http',name: 'open-knowledge',url: `${serverUrl}/mcp`,- headers: [],+ headers: [{ name: MCP_HOSTED_AGENT_HEADER, value: '1' }],});} else {// Fallback for agents that don't advertise HTTP-MCP support (e.g. Claude@@ -963,7 +969,13 @@ export class AcpThreadManager {name: 'open-knowledge',command: stdio.command,args: [...stdio.args],- env: [],+ // Carry the hosted-agent marker explicitly rather than relying on+ // the agent to pass its own env through to the MCP servers it+ // spawns. On this branch we name the command, so we can make it+ // deterministic; on the skip branch above the harness spawns its+ // own entry and the marker has to arrive by inheritance from+ // `withHostedAgentMarker` at the agent spawn.+ env: [{ name: OK_HOSTED_AGENT_ENV, value: '1' }],});}}diff --git a/packages/server/src/mcp-http.test.ts b/packages/server/src/mcp-http.test.tsindex 6e4512c62..2e6da582c 100644--- a/packages/server/src/mcp-http.test.ts+++ b/packages/server/src/mcp-http.test.ts@@ -21,7 +21,7 @@ import { setTimeout as wait } from 'node:timers/promises';import { afterEach, beforeEach, expect, test } from 'vitest';import { type Config, ConfigSchema } from './config/schema.ts';import { getFreeLoopbackPort } from './loopback-rig-test-helpers.ts';-import { MCP_CONNECTION_ID_HEADER } from './mcp/agent-identity.ts';+import { MCP_CONNECTION_ID_HEADER, MCP_HOSTED_AGENT_HEADER } from './mcp/agent-identity.ts';import {createMcpHttpHandler,type McpHttpHandler,@@ -97,12 +97,16 @@ interface InitializedSession {protocolVersion: string;}-async function openMcpSession(port: number): Promise<InitializedSession> {+async function openMcpSession(+ port: number,+ extraHeaders: Record<string, string> = {},+): Promise<InitializedSession> {const init = await fetch(`http://127.0.0.1:${port}/mcp`, {method: 'POST',headers: {accept: 'application/json, text/event-stream','content-type': 'application/json',+ ...extraHeaders,},body: JSON.stringify({jsonrpc: '2.0',@@ -610,3 +614,58 @@ test('inactive MCP sessions expire and return 404 on later use', async () => {expect(expired.status).toBe(404);expect(await expired.text()).toContain('MCP session not found');});++/**+ * The hosted-agent header is the HTTP transport's stand-in for the env marker+ * stdio agents inherit. Each hop either side of it is unit-tested (the ACP+ * injection sends the header; `preview_url` steers given `isHostedAgent`), but+ * the hop between them is this handler reading the header into+ * `registerAllTools` — a rename or a changed comparison there would silently+ * un-steer every HTTP-transport panel agent with nothing failing.+ *+ * Asserted through `okOpenCommand`, which is null in every non-hosted context+ * and carries the `ok open` steer when hosted. No UI needs to be running: the+ * steer fires on the no-UI payload too.+ */+async function previewUrlOkOpenCommand(+ port: number,+ extraHeaders: Record<string, string> = {},+): Promise<unknown> {+ const { sessionId, protocolVersion } = await openMcpSession(port, extraHeaders);+ const call = await fetch(`http://127.0.0.1:${port}/mcp`, {+ method: 'POST',+ headers: {+ accept: 'application/json, text/event-stream',+ 'content-type': 'application/json',+ 'mcp-session-id': sessionId,+ 'mcp-protocol-version': protocolVersion,+ },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 2,+ method: 'tools/call',+ params: { name: 'preview_url', arguments: { document: 'specs/foo/SPEC' } },+ }),+ });+ expect(call.status).toBe(200);+ const body = (await call.json()) as {+ result?: { structuredContent?: { okOpenCommand?: unknown } };+ };+ return body.result?.structuredContent?.okOpenCommand ?? null;+}++test('hosted-agent header reaches preview_url as the ok open steer', async () => {+ const harness = await bootHandler(ConfigSchema.parse({}));+ openHarnesses.push(harness);+ expect(await previewUrlOkOpenCommand(harness.port, { [MCP_HOSTED_AGENT_HEADER]: '1' })).toBe(+ 'ok open specs/foo/SPEC',+ );+});++test('without the header the same server keeps the plain-URL behavior', async () => {+ // The load-bearing half: one server answers both the in-app panel and+ // external clients, and an external client must still get a navigable URL.+ const harness = await bootHandler(ConfigSchema.parse({}));+ openHarnesses.push(harness);+ expect(await previewUrlOkOpenCommand(harness.port)).toBeNull();+});diff --git a/packages/server/src/mcp-http.ts b/packages/server/src/mcp-http.tsindex b4681ad61..7cd083c0a 100644--- a/packages/server/src/mcp-http.ts+++ b/packages/server/src/mcp-http.ts@@ -9,6 +9,7 @@ import { MCP_SERVER_NAME } from './constants.ts';import {type AgentIdentity,MCP_CONNECTION_ID_HEADER,+ MCP_HOSTED_AGENT_HEADER,sanitizeClientName,} from './mcp/agent-identity.ts';import { installPrettyZodErrors } from './mcp/pretty-zod-errors.ts';@@ -63,6 +64,7 @@ function createSessionServer(opts: McpHttpHandlerOptions,transport: StreamableHTTPServerTransport,forwardedConnectionId: string | undefined,+ isHostedAgent: boolean,): McpHttpSession {const config = opts.config;// No `instructions` handshake — see startGlobalMcpServer. The@@ -129,6 +131,7 @@ function createSessionServer(},config,identityRef,+ isHostedAgent,});return { server, transport };@@ -218,12 +221,23 @@ export function createMcpHttpHandler(opts: McpHttpHandlerOptions): McpHttpHandle);}+ // Only the HTTP MCP entry OK injects for an agent it hosts sets this;+ // an external client (Cursor/Codex outside the app, an `ok start`+ // consumer) never does and keeps the plain-URL behavior. Read per+ // session rather than per process because one server answers both.+ const isHostedAgent = firstHeader(req.headers[MCP_HOSTED_AGENT_HEADER]) === '1';+const transport = new StreamableHTTPServerTransport({sessionIdGenerator: () => randomUUID(),enableJsonResponse: true,onsessioninitialized: async (newSessionId) => {try {- const session = createSessionServer(opts, transport, forwardedConnectionId);+ const session = createSessionServer(+ opts,+ transport,+ forwardedConnectionId,+ isHostedAgent,+ );await session.server.connect(transport);sessions.set(newSessionId, session);touchSession(newSessionId, session);diff --git a/packages/server/src/mcp/agent-identity.ts b/packages/server/src/mcp/agent-identity.tsindex efdfd3f7c..2e9620684 100644--- a/packages/server/src/mcp/agent-identity.ts+++ b/packages/server/src/mcp/agent-identity.ts@@ -47,6 +47,19 @@ export interface AgentIdentity {*/export const MCP_CONNECTION_ID_HEADER = 'x-ok-connection-id';+/**+ * Per-connection carrier for the hosted-agent fact on the HTTP MCP transport.+ *+ * The env marker that carries this on stdio (`OK_HOSTED_AGENT`) cannot travel+ * over HTTP, and the signal has to stay per-connection rather than+ * per-process: one shared server answers both the in-app agent panel and+ * external clients (an outside Cursor/Codex, an `ok start` consumer), and+ * those external clients legitimately want a navigable URL. Only the entry OK+ * injects for an agent it hosts sets this header, so absent means "not+ * hosted" and the plain-URL behavior is preserved by default.+ */+export const MCP_HOSTED_AGENT_HEADER = 'x-ok-hosted-agent';+/*** Coerce an MCP client's self-reported `clientInfo.name` into a safe display* string: strip ASCII control characters, collapse internal whitespace,diff --git a/packages/server/src/mcp/tools/get-preview-url.test.ts b/packages/server/src/mcp/tools/get-preview-url.test.tsindex 13dcdefb6..e374156a8 100644--- a/packages/server/src/mcp/tools/get-preview-url.test.ts+++ b/packages/server/src/mcp/tools/get-preview-url.test.ts@@ -46,7 +46,7 @@ interface EnsureDeps {offCwdResolverDeps?: OffCwdResolverDeps;ensureSingleFileSession?: (absFile: string) => Promise<boolean>;resolveUserAutoOpen?: () => boolean;- isDesktopTerminal?: boolean;+ isHostedAgent?: boolean;}function captureRegistration(@@ -102,11 +102,11 @@ describe('preview_url tool — UI running', () => {expect(result.structuredContent?.url).toBe(`${uiBase}/#/My%20Notes/sub/`);});- describe('isDesktopTerminal steer (OK Desktop built-in terminal)', () => {+ describe('isHostedAgent steer (desktop terminal or in-app agent panel)', () => {test('document: response leads with `ok open <doc>` and tells the agent not to navigate the URL', async () => {const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));bindTestUiLock(cwd);- const handler = captureRegistration(cwd, BASE_CONFIG, { isDesktopTerminal: true });+ const handler = captureRegistration(cwd, BASE_CONFIG, { isHostedAgent: true });const result = await handler({ document: 'specs/foo/SPEC' });const text = result.content[0]?.text ?? '';expect(text).toContain('ok open specs/foo/SPEC');@@ -116,10 +116,22 @@ describe('preview_url tool — UI running', () => {expect(result.structuredContent?.okOpenCommand).toBe('ok open specs/foo/SPEC');});+ // The reported failure was not a bad URL — it was a correct URL pasted+ // into the reply of an agent sitting inside the app the URL points at.+ // "don't navigate" alone left that reading open, so the steer has to+ // close it explicitly.+ test('document: steer tells the agent not to paste the URL into its reply', async () => {+ const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));+ bindTestUiLock(cwd);+ const handler = captureRegistration(cwd, BASE_CONFIG, { isHostedAgent: true });+ const result = await handler({ document: 'specs/foo/SPEC' });+ expect(result.content[0]?.text ?? '').toContain('paste the URL into your reply');+ });+test('folder: steers to `ok open <folder>`', async () => {const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));bindTestUiLock(cwd);- const handler = captureRegistration(cwd, BASE_CONFIG, { isDesktopTerminal: true });+ const handler = captureRegistration(cwd, BASE_CONFIG, { isHostedAgent: true });const result = await handler({ folder: 'specs/foo' });expect(result.content[0]?.text ?? '').toContain('ok open specs/foo');expect(result.structuredContent?.okOpenCommand).toBe('ok open specs/foo');@@ -128,7 +140,7 @@ describe('preview_url tool — UI running', () => {test('skill default scope (project): steers to `ok open <name> --skill` (no --scope)', async () => {const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));bindTestUiLock(cwd);- const handler = captureRegistration(cwd, BASE_CONFIG, { isDesktopTerminal: true });+ const handler = captureRegistration(cwd, BASE_CONFIG, { isHostedAgent: true });const result = await handler({ skill: { name: 'trip-log' } });expect(result.content[0]?.text ?? '').toContain('ok open trip-log --skill');expect(result.content[0]?.text ?? '').not.toContain('--scope');@@ -138,7 +150,7 @@ describe('preview_url tool — UI running', () => {test('skill --scope global: steers to `ok open <name> --skill --scope global`', async () => {const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));bindTestUiLock(cwd);- const handler = captureRegistration(cwd, BASE_CONFIG, { isDesktopTerminal: true });+ const handler = captureRegistration(cwd, BASE_CONFIG, { isHostedAgent: true });const result = await handler({ skill: { name: 'trip-log', scope: 'global' } });expect(result.content[0]?.text ?? '').toContain('ok open trip-log --skill --scope global');expect(result.structuredContent?.okOpenCommand).toBe(@@ -149,12 +161,12 @@ describe('preview_url tool — UI running', () => {test('no target (root): no steer — nothing to `ok open`', async () => {const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));bindTestUiLock(cwd);- const handler = captureRegistration(cwd, BASE_CONFIG, { isDesktopTerminal: true });+ const handler = captureRegistration(cwd, BASE_CONFIG, { isHostedAgent: true });const result = await handler({});expect(result.content[0]?.text ?? '').not.toContain('ok open');});- test('NOT a desktop terminal (default): no steer — plain Preview URL', async () => {+ test('NOT a hosted agent (default): no steer — plain Preview URL', async () => {const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));bindTestUiLock(cwd);const handler = captureRegistration(cwd);@@ -164,20 +176,23 @@ describe('preview_url tool — UI running', () => {expect(result.structuredContent?.okOpenCommand ?? null).toBeNull();});- test('desktop terminal + no UI running: steer + okOpenCommand still fire (ok open does not need the UI)', async () => {+ test('hosted agent + no UI running: steer + okOpenCommand still fire (ok open does not need the UI)', async () => {const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));// No bindTestUiLock / bindTestServerLock — nothing is running.- const handler = captureRegistration(cwd, BASE_CONFIG, { isDesktopTerminal: true });+ const handler = captureRegistration(cwd, BASE_CONFIG, { isHostedAgent: true });const result = await handler({ document: 'specs/foo/SPEC' });expect(result.structuredContent?.running).toBe(false);expect(result.structuredContent?.okOpenCommand).toBe('ok open specs/foo/SPEC');expect(result.content[0]?.text ?? '').toContain('ok open specs/foo/SPEC');+ // The steer rides the no-UI payload too — without this assertion,+ // dropping it from that branch would pass every other test here.+ expect(result.content[0]?.text ?? '').toContain('paste the URL into your reply');});test('document with a space: okOpenCommand shell-quotes the path', async () => {const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));bindTestUiLock(cwd);- const handler = captureRegistration(cwd, BASE_CONFIG, { isDesktopTerminal: true });+ const handler = captureRegistration(cwd, BASE_CONFIG, { isHostedAgent: true });const result = await handler({ document: 'notes/My Doc' });expect(result.structuredContent?.okOpenCommand).toBe("ok open 'notes/My Doc'");});@@ -185,16 +200,16 @@ describe('preview_url tool — UI running', () => {test('document with an embedded single quote: okOpenCommand POSIX-escapes it', async () => {const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));bindTestUiLock(cwd);- const handler = captureRegistration(cwd, BASE_CONFIG, { isDesktopTerminal: true });+ const handler = captureRegistration(cwd, BASE_CONFIG, { isHostedAgent: true });const result = await handler({ document: "Q&A/what's new" });// POSIX single-quote escape: close-quote, escaped-quote, reopen → '\''expect(result.structuredContent?.okOpenCommand).toBe("ok open 'Q&A/what'\\''s new'");});- test('desktop terminal + no UI + folder: okOpenCommand still fires', async () => {+ test('hosted agent + no UI + folder: okOpenCommand still fires', async () => {const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));// No bindTestUiLock — nothing running.- const handler = captureRegistration(cwd, BASE_CONFIG, { isDesktopTerminal: true });+ const handler = captureRegistration(cwd, BASE_CONFIG, { isHostedAgent: true });const result = await handler({ folder: 'specs/foo' });expect(result.structuredContent?.running).toBe(false);expect(result.structuredContent?.okOpenCommand).toBe('ok open specs/foo');diff --git a/packages/server/src/mcp/tools/get-preview-url.ts b/packages/server/src/mcp/tools/get-preview-url.tsindex 813105491..0a654d5ad 100644--- a/packages/server/src/mcp/tools/get-preview-url.ts+++ b/packages/server/src/mcp/tools/get-preview-url.ts@@ -69,6 +69,8 @@ const DESCRIPTION = ['','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. Claude Code Desktop opens its in-app Browser pane with `preview_start({url})` then `navigate({url})` to move; a pure stdio CLI with no browser uses `ok open <doc>` to open in the OK Desktop app.','',+ 'If you are running INSIDE an OpenKnowledge surface — the desktop app’s built-in terminal or its in-app agent panel — the response leads with an `ok open …` steer and returns it as `okOpenCommand`. Run that instead: the user is already looking at the app, so a localhost URL in your reply is noise at best and a dead link at worst. Never paste `url` into your answer in that case.',+ '','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.',@@ -85,14 +87,17 @@ interface GetPreviewUrlDeps {config: ConfigOrResolver;resolveCwd: (explicit?: string) => Promise<string>;/**- * True when this MCP server runs inside OK Desktop's own built-in terminal- * (`OK_DESKTOP_TERMINAL=1`). When set, the doc/folder/skill responses lead- * with a steer to run `ok open <target>` (which focuses the OK Desktop- * window) rather than navigating the returned URL — the terminal agent has- * no business opening a browser. Absent/false everywhere else (the shared- * collab server, Cursor/Codex, plain CLI), so those paths are unchanged.+ * True when the calling agent is hosted by an OpenKnowledge surface — the+ * desktop app's built-in terminal (`OK_DESKTOP_TERMINAL=1`) or its in-app+ * agent panel (`OK_HOSTED_AGENT=1`). When set, the doc/folder/skill+ * responses lead with a steer to run `ok open <target>` (which focuses the+ * target up for the user) rather than navigating the+ * returned URL — an agent living inside the app has no business handing its+ * user a localhost link to the app they are looking at. Absent/false+ * everywhere else (the shared collab server, an external Cursor/Codex with+ * its own browser pane, plain CLI), so those paths are unchanged.*/- isDesktopTerminal?: boolean;+ isHostedAgent?: boolean;/*** Hocuspocus URL (or per-call resolver). When present, a preview request* is treated as demand for a backend: the resolver's auto-spawn path@@ -193,7 +198,7 @@ const OutputSchema = outputSchemaWithText({.nullable().optional().describe(- 'Machine-readable form of the desktop-terminal steer: when this MCP server runs inside OK Desktop’s built-in terminal AND a doc/folder/skill target was given, the exact `ok open …` command to run to focus it in the OK Desktop window. Prefer running it over navigating `url`. `null`/absent in every other context (navigate `url` per your host instead).',+ 'Machine-readable form of the hosted-agent steer: when the calling agent runs inside an OpenKnowledge surface (the desktop app’s built-in terminal, or its in-app agent panel) AND a doc/folder/skill target was given, the exact `ok open …` command to run to bring it up for the user. Run it INSTEAD of navigating `url`, and do not paste `url` into your reply — the user is already in the app it points at. `null`/absent in every other context (navigate `url` per your host instead).',),});@@ -379,12 +384,13 @@ export function register(server: ServerInstance, deps: GetPreviewUrlDeps): void? `#/${encodeSkillRoute(args.skill.scope ?? 'project', args.skill.name)}`: null;- // Desktop-terminal steer: this MCP process inherited `OK_DESKTOP_TERMINAL`- // from OK Desktop's built-in terminal, so the agent is sitting in the app —- // it should focus the page with `ok open` (which navigates the OK Desktop- // window), NOT navigate this URL or open a browser. Lead the response with- // the exact command. Only for an in-project doc/folder/skill target (the- // `file` branch returns earlier; the root has nothing to `ok open`).+ // Hosted-agent steer: this MCP process inherited a marker from an+ // OpenKnowledge surface (the desktop terminal's pty, or the agent spawn+ // for the in-app panel), so the agent is sitting in the app — it should+ // focus the page with `ok open`, NOT navigate this URL or open a+ // browser. Lead the response with the exact command. Only for an+ // in-project doc/folder/skill target (the `file` branch returns earlier;+ // the root has nothing to `ok open`).const okOpenCommand = args.document? `ok open ${shellQuoteArg(args.document)}`: args.folder@@ -392,9 +398,9 @@ export function register(server: ServerInstance, deps: GetPreviewUrlDeps): void: args.skill? `ok open ${args.skill.name} --skill${args.skill.scope === 'global' ? ' --scope global' : ''}`: null;- const desktopTerminalSteer =- deps.isDesktopTerminal && okOpenCommand- ? `You're in the OK Desktop terminal — run \`${okOpenCommand}\` to focus this in the OK Desktop window. Don't navigate the URL below or open a browser; it's for reference only.\n\n`+ const hostedAgentSteer =+ deps.isHostedAgent && okOpenCommand+ ? `You're running inside OpenKnowledge — run \`${okOpenCommand}\` to bring this up for the user. Don't navigate the URL below, open a browser, or paste the URL into your reply; it's for reference only.\n\n`: '';// Demand-ensure: when this registration has server authority, run the@@ -448,24 +454,24 @@ export function register(server: ServerInstance, deps: GetPreviewUrlDeps): voidconst hint = isServerLive(lockDir)? NO_UI_SERVER_RUNNING_MESSAGE: `${NO_SERVER_MESSAGE}${autoStartDisabled ? AUTOSTART_DISABLED_NOTE : ''}`;- return textPlusStructured(`${desktopTerminalSteer}${hint}`, {+ return textPlusStructured(`${hostedAgentSteer}${hint}`, {url: null,baseUrl: null,running: false,autoOpen,- okOpenCommand: deps.isDesktopTerminal ? okOpenCommand : null,+ okOpenCommand: deps.isHostedAgent ? okOpenCommand : null,});}// baseUrl is non-null here (the lock is bound) — compose base + route.const url = routeFragment ? `${baseUrl}/${routeFragment}` : baseUrl;- return textPlusStructured(`${desktopTerminalSteer}Preview URL: ${url}`, {+ return textPlusStructured(`${hostedAgentSteer}Preview URL: ${url}`, {url,baseUrl,running: true,autoOpen,- okOpenCommand: deps.isDesktopTerminal ? okOpenCommand : null,+ okOpenCommand: deps.isHostedAgent ? okOpenCommand : null,});},);diff --git a/packages/server/src/mcp/tools/index.ts b/packages/server/src/mcp/tools/index.tsindex fc9c07d28..291d54220 100644--- a/packages/server/src/mcp/tools/index.ts+++ b/packages/server/src/mcp/tools/index.ts@@ -80,14 +80,16 @@ interface RegisterAllToolsOptions {identityRef?: { current: AgentIdentity };logger?: McpLogger;/**- * True when this MCP server process is running inside OK Desktop's own- * built-in terminal (`OK_DESKTOP_TERMINAL=1` inherited from the pty). The- * global `ok mcp` server sets it from its env; the shared collab server- * (`ok start`) never has the marker, so it stays false there. `preview_url`- * uses it to steer the agent to `ok open` (which focuses the OK Desktop- * window) instead of returning a URL the agent shouldn't navigate.+ * True when the agent driving this MCP server process is running inside an+ * OpenKnowledge surface — the desktop app's built-in terminal+ * (`OK_DESKTOP_TERMINAL=1` from the pty) or its in-app agent panel+ * (`OK_HOSTED_AGENT=1` from the agent spawn). The global `ok mcp` server+ * sets it from its env; the shared collab server (`ok start`) never has+ * either marker, so it stays false there. `preview_url` uses it to steer+ * the agent to `ok open` (which focuses the doc where the user is already+ * looking) instead of returning a URL the agent shouldn't navigate.*/- isDesktopTerminal?: boolean;+ isHostedAgent?: boolean;}export function registerAllTools(server: ServerInstance, opts: RegisterAllToolsOptions): void {@@ -258,7 +260,7 @@ export function registerAllTools(server: ServerInstance, opts: RegisterAllToolsOconfig: opts.config,resolveCwd: named('preview_url'),serverUrl: opts.serverUrl,- isDesktopTerminal: opts.isDesktopTerminal,+ isHostedAgent: opts.isHostedAgent,// Boot-on-demand for the `file` branch is wired only when this registration// has backend/spawn authority (the same gate as `serverUrl`): it spawns a// detached `ok <file>` via this process's own CLI entry.