Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(open-knowledge): first-class Pi coding agent support via a managed bridge extension (#2479)

mike-inkeepa3b19f4508c1
diff --git a/.changeset/pi-coding-agent-support.md b/.changeset/pi-coding-agent-support.md
new file mode 100644
index 000000000..040b48dce
--- /dev/null
+++ b/.changeset/pi-coding-agent-support.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+First-class support for the Pi coding agent (pi.dev), at parity with OpenCode. Pi has no MCP support, so `ok init` now drops a managed, dependency-free bridge extension at `.pi/extensions/open-knowledge.ts` — it launches OpenKnowledge's MCP server through the same resilient launcher every other editor gets and registers each OpenKnowledge tool as a native Pi tool under an `ok_` prefix (so OK's `edit`/`write` never shadow Pi's built-ins). The OpenKnowledge project skill lands in `.pi/skills/open-knowledge/`, which Pi scans natively; both are trust-gated by Pi's folder-trust prompt, refreshed idempotently on re-init, healed by the repair/reclaim sweeps, and removed by `ok deinit`/`ok uninstall`. Pi also joins the docked-terminal launch registry (`pi '<prompt>'`) and skill install targets, and gets an integrations docs page.
diff --git a/docs/content/features/skills.mdx b/docs/content/features/skills.mdx
index 7121888a1..23ed0db99 100644
--- a/docs/content/features/skills.mdx
+++ b/docs/content/features/skills.mdx
@@ -43,7 +43,7 @@ A skill in OpenKnowledge is content, not a config file: authored in the WYSIWYG
.cap code{font-size:11.5px}
</style>
<script>
-var eds=["Claude Code","Cursor","Codex","OpenCode"],box=document.getElementById("eds"),inst=document.getElementById("inst"),chips=[];
+var eds=["Claude Code","Cursor","Codex","OpenCode","Pi"],box=document.getElementById("eds"),inst=document.getElementById("inst"),chips=[];
eds.forEach(function(e){var c=document.createElement("div");c.className="chip";c.textContent=e;box.appendChild(c);chips.push(c);});
var reduce=matchMedia("(prefers-reduced-motion:reduce)").matches;
function run(){
@@ -62,7 +62,7 @@ A project skill is not a raw text file you hand-edit in a dotfile. It is a docum
## Write once, install everywhere
-`install` **symlinks** the skill into each editor's skills directory (Claude Code, Cursor, Codex, OpenCode). Every editor points at the one `.ok/skills/<name>` source, so nothing is copied and nothing drifts: edit the skill once and every agent has the change, with no re-install.
+`install` **symlinks** the skill into each editor's skills directory (Claude Code, Cursor, Codex, OpenCode, Pi). Every editor points at the one `.ok/skills/<name>` source, so nothing is copied and nothing drifts: edit the skill once and every agent has the change, with no re-install.
## Create and install a skill
diff --git a/docs/content/get-started/quickstart.mdx b/docs/content/get-started/quickstart.mdx
index 06c8a291f..4962de4f8 100644
--- a/docs/content/get-started/quickstart.mdx
+++ b/docs/content/get-started/quickstart.mdx
@@ -122,7 +122,7 @@ Install the CLI from npm, initialize a project, and start the editor in your bro
npm install -g @inkeep/open-knowledge
# Create (or enter) a project folder, then initialize a knowledge base.
-# `ok init` scaffolds .ok/ and wires up Claude Code, Claude Desktop, Cursor, Codex, OpenCode, and OpenClaw.
+# `ok init` scaffolds .ok/ and wires up Claude Code, Claude Desktop, Cursor, Codex, OpenCode, OpenClaw, and Pi.
mkdir my-knowledge-base && cd my-knowledge-base
ok init
diff --git a/docs/content/integrations/meta.json b/docs/content/integrations/meta.json
index 7509c42d9..7448ec959 100644
--- a/docs/content/integrations/meta.json
+++ b/docs/content/integrations/meta.json
@@ -1,5 +1,5 @@
{
"title": "Integrations",
"icon": "LuPlug",
- "pages": ["claude-code", "cursor", "codex", "opencode", "openclaw"]
+ "pages": ["claude-code", "cursor", "codex", "opencode", "pi", "openclaw"]
}
diff --git a/docs/content/integrations/pi.mdx b/docs/content/integrations/pi.mdx
new file mode 100644
index 000000000..cc1fa93f7
--- /dev/null
+++ b/docs/content/integrations/pi.mdx
@@ -0,0 +1,30 @@
+---
+title: Pi
+description: Use OpenKnowledge with Pi — a minimal, extensible terminal coding agent — via OpenKnowledge's managed bridge extension.
+icon: custom/Pi
+---
+
+OpenKnowledge plugs into [Pi](https://pi.dev) through a managed **bridge extension**. Pi is a minimal terminal coding agent that deliberately ships without MCP support — its extension point is TypeScript extensions — so instead of an MCP config entry, OpenKnowledge drops a small extension into your project that connects Pi to your knowledge base.
+
+## Install
+
+Run `ok init` in your project (or open the project in the OpenKnowledge desktop app — project setup writes the same files). Two things land in the project's `.pi/` directory:
+
+- **`.pi/extensions/open-knowledge.ts`** — the bridge extension. On session start it launches OpenKnowledge's MCP server with the same resilient launcher every other editor uses, then registers each OpenKnowledge tool as a native Pi tool under an `ok_` prefix (`ok_exec`, `ok_search`, `ok_write`, …). The prefix keeps OpenKnowledge's `edit` / `write` from shadowing Pi's built-in file tools.
+- **`.pi/skills/open-knowledge/`** — the OpenKnowledge skill, in the [Agent Skills](https://pi.dev/docs/latest) format Pi reads natively from `.pi/skills/`.
+
+Both files are OpenKnowledge-managed: `ok init` re-runs refresh them in place, and `ok deinit` removes them. Don't hand-edit the bridge — your changes are overwritten on the next sync.
+
+## Trust the project
+
+Pi loads project-local extensions and skills **only after you trust the folder**. The first time you run `pi` in the project (and on fresh clones), Pi shows a trust prompt — accept it, or OpenKnowledge's tools and skill won't load. Your decision is remembered in `~/.pi/agent/trust.json`. Context files like `AGENTS.md` load regardless of trust.
+
+## Verify
+
+Run `pi` in the project, trust it if prompted, and ask:
+
+<CopyPrompt>List the first 5 documents you come across in this project.</CopyPrompt>
+
+Pi should call the OpenKnowledge `ok_exec` tool and respond with some of your documents.
+
+If the `ok_` tools are missing: make sure you trusted the folder, then `/reload` (or restart `pi`). The first tool call can take a moment on a fresh machine — the launcher may be installing the OpenKnowledge CLI via `npx`. If Pi shows an "Open Knowledge tools unavailable" notice, install [Node.js 24+](https://nodejs.org) or the OpenKnowledge desktop app and reload.
diff --git a/docs/content/reference/cli.mdx b/docs/content/reference/cli.mdx
index 93a44fd29..99a9a4d96 100644
--- a/docs/content/reference/cli.mdx
+++ b/docs/content/reference/cli.mdx
@@ -21,7 +21,7 @@ npm install -g @inkeep/open-knowledge
## Set up a project
-Run `ok init` in any folder to turn it into an OpenKnowledge project. It scaffolds a `.ok/` directory and registers the OpenKnowledge MCP server with the AI editors it detects on your machine (Claude Code, Claude Desktop, Cursor, Codex, OpenCode, OpenClaw). It only ever adds its own entry — your other settings, comments, and formatting are left untouched.
+Run `ok init` in any folder to turn it into an OpenKnowledge project. It scaffolds a `.ok/` directory and registers the OpenKnowledge MCP server with the AI editors it detects on your machine (Claude Code, Claude Desktop, Cursor, Codex, OpenCode, OpenClaw, Pi). It only ever adds its own entry — your other settings, comments, and formatting are left untouched.
```bash
cd my-project
diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdx
index c46c36f32..176142f76 100644
--- a/docs/content/reference/what-open-knowledge-writes.mdx
+++ b/docs/content/reference/what-open-knowledge-writes.mdx
@@ -83,8 +83,9 @@ When you initialize or open a project, the app scaffolds the same project files
| `.ok/`, `.ok/config.yml` | Project directory and its [config](/docs/reference/configuration) | In-project, committed |
| `.ok/.gitignore` | Keeps machine-local runtime state (`local/`, `principal.json`, `server.lock`, …) out of git | In-project, committed |
| `.okignore` | Paths excluded from the editor, search, and agents — see [Ignore patterns](/docs/features/ignore-patterns) | In-project, committed |
-| `.mcp.json`, `.cursor/mcp.json`, `.codex/config.toml`, `opencode.json` | Project-scoped MCP registration for all four project-capable editors (Claude, Cursor, Codex, OpenCode), written regardless of what's installed so the repo is ready for teammates | In-project, committed |
-| `.claude/skills/`, `.cursor/skills/`, `.codex/skills/`, `.opencode/skills/` | Project-local "rich" OpenKnowledge skill (`SKILL.md`) for the same four editors | In-project, committed |
+| `.mcp.json`, `.cursor/mcp.json`, `.codex/config.toml`, `opencode.json` | Project-scoped MCP registration for the four MCP-capable project editors (Claude, Cursor, Codex, OpenCode), written regardless of what's installed so the repo is ready for teammates | In-project, committed |
+| `.pi/extensions/open-knowledge.ts` | Managed bridge extension connecting [Pi](/docs/integrations/pi) (which has no MCP support) to the project | In-project, committed |
+| `.claude/skills/`, `.cursor/skills/`, `.codex/skills/`, `.opencode/skills/`, `.pi/skills/` | Project-local "rich" OpenKnowledge skill (`SKILL.md`) for the same five editors | In-project, committed |
| `.ok/skill-targets.json` | Committed list of which editors receive skills, written when you customize the targets | In-project, committed |
| `.claude/launch.json` | Configures Claude Code's preview pane to open the editor (on a local UI port, `39848`) | In-project, committed |
| `~/.claude.json`, `~/Library/Application Support/Claude/claude_desktop_config.json`, `~/.cursor/mcp.json`, `~/.codex/config.toml`, `~/.config/opencode/opencode.json`, `~/.openclaw/openclaw.json` | User-level `open-knowledge` MCP registration, one per detected editor, so it's available in every project (`~/.openclaw/openclaw.json` only when `~/.openclaw/` exists) | Outside-project (editor config) |
@@ -160,8 +161,9 @@ The `postinstall` step is **non-fatal** (install always succeeds even if it fail
| `.ok/.gitignore` | Keeps machine-local runtime state (`local/`, `principal.json`, `server.lock`, …) out of git | In-project, committed |
| `.okignore` | Paths excluded from the editor, search, and agents — see [Ignore patterns](/docs/features/ignore-patterns) | In-project, committed |
| `.gitignore` (project root) | Seeded (with `.DS_Store`) **only** when `ok init` creates a new git repo | In-project, committed |
-| `.mcp.json`, `.cursor/mcp.json`, `.codex/config.toml`, `opencode.json` | Project-scoped MCP registration for all four project-capable editors (Claude, Cursor, Codex, OpenCode) regardless of what's installed — prepares the repo for teammates (with `--scope project` or `both`) | In-project, committed |
-| `.claude/skills/`, `.cursor/skills/`, `.codex/skills/`, `.opencode/skills/` | Project-local "rich" OpenKnowledge skill (`SKILL.md`) for the same four editors | In-project, committed |
+| `.mcp.json`, `.cursor/mcp.json`, `.codex/config.toml`, `opencode.json` | Project-scoped MCP registration for the four MCP-capable project editors (Claude, Cursor, Codex, OpenCode) regardless of what's installed — prepares the repo for teammates (with `--scope project` or `both`) | In-project, committed |
+| `.pi/extensions/open-knowledge.ts` | Managed bridge extension connecting [Pi](/docs/integrations/pi) (which has no MCP support) to the project | In-project, committed |
+| `.claude/skills/`, `.cursor/skills/`, `.codex/skills/`, `.opencode/skills/`, `.pi/skills/` | Project-local "rich" OpenKnowledge skill (`SKILL.md`) for the same five editors | In-project, committed |
| `.ok/skill-targets.json` | Committed list of which editors receive skills, written when you customize the targets | In-project, committed |
| `.claude/launch.json` | Configures Claude Code's preview pane to open the editor (on a local UI port, `39848`) | In-project, committed |
@@ -176,6 +178,8 @@ With `--scope user` or `both` (the default), `ok init` also registers the `open-
| `~/.config/opencode/opencode.json` | OpenCode | Outside-project (editor config) |
| `~/.openclaw/openclaw.json` | OpenClaw (only when `~/.openclaw/` exists) | Outside-project (editor config) |
+Pi is the exception: it has no user-level MCP config (it has no MCP support at all), so its integration is only ever the project-scoped bridge extension above.
+
On Windows, Claude Desktop and OpenCode configs live under `%APPDATA%\Claude\` and `%APPDATA%\opencode\`, and the MCP entry is a PowerShell launcher.
`ok init` also installs the two user-global skills (`open-knowledge-discovery` and `open-knowledge-write-skill`), honoring any prior consent choice, and, if you choose **local-only** sharing, adds the OpenKnowledge paths to `.git/info/exclude` so `.ok/` stays off your remote. Switch modes later with `ok config-sharing share` / `unshare` (`unshare` refuses if an OK config file is already tracked); `ok config-sharing status` prints the current mode and the excluded paths.
diff --git a/docs/src/components/agent-icons.tsx b/docs/src/components/agent-icons.tsx
index 9bfb24d64..6dbdae505 100644
--- a/docs/src/components/agent-icons.tsx
+++ b/docs/src/components/agent-icons.tsx
@@ -3,6 +3,7 @@ import { CodexIcon } from '@/components/icons/codex';
import { CursorIcon } from '@/components/icons/cursor';
import { OpenClawIcon } from '@/components/icons/openclaw';
import { OpenCodeIcon } from '@/components/icons/opencode';
+import { PiIcon } from '@/components/icons/pi';
const AGENTS = [
{ name: 'Claude', Icon: ClaudeIcon },
@@ -10,6 +11,7 @@ const AGENTS = [
{ name: 'Codex', Icon: CodexIcon },
{ name: 'OpenCode', Icon: OpenCodeIcon },
{ name: 'OpenClaw', Icon: OpenClawIcon },
+ { name: 'Pi', Icon: PiIcon },
] as const;
export function AgentIcons() {
diff --git a/docs/src/components/icons/brand.ts b/docs/src/components/icons/brand.ts
index a11bf8397..563d8a5f3 100644
--- a/docs/src/components/icons/brand.ts
+++ b/docs/src/components/icons/brand.ts
@@ -7,6 +7,7 @@ import { McpIcon } from './mcp';
import { ObsidianIcon } from './obsidian';
import { OpenClawIcon } from './openclaw';
import { OpenCodeIcon } from './opencode';
+import { PiIcon } from './pi';
// Brand logos addressable from `meta.json` / page frontmatter via the
// `custom/<Name>` icon string (resolved in `src/lib/source.ts`). Each entry is a
@@ -18,6 +19,7 @@ export const brandIcons = {
Codex: CodexIcon,
OpenCode: OpenCodeIcon,
OpenClaw: OpenClawIcon,
+ Pi: PiIcon,
GitHub: GitHubIcon,
Obsidian: ObsidianIcon,
MCP: McpIcon,
diff --git a/docs/src/components/icons/pi.tsx b/docs/src/components/icons/pi.tsx
new file mode 100644
index 000000000..781372714
--- /dev/null
+++ b/docs/src/components/icons/pi.tsx
@@ -0,0 +1,29 @@
+import type { SVGProps } from 'react';
+
+// Pi brand mark (the blocky "P" + square "i" dot from pi.dev/logo-auto.svg),
+// rendered monochrome via `currentColor` so it tracks the surrounding text
+// color in both themes — the upstream SVG ships its own light/dark media
+// query, which can't participate in the site's theme toggle.
+export function PiIcon(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ role="img"
+ aria-label="Pi icon"
+ xmlns="http://www.w3.org/2000/svg"
+ width={24}
+ height={24}
+ fill="none"
+ viewBox="0 0 800 800"
+ {...props}
+ >
+ <title>Pi icon</title>
+ <path
+ fill="currentColor"
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"
+ />
+ <path fill="currentColor" d="M517.36 400H634.72V634.72H517.36Z" />
+ </svg>
+ );
+}
diff --git a/docs/src/components/overview-blocks.tsx b/docs/src/components/overview-blocks.tsx
index 9f870503f..2849ea311 100644
--- a/docs/src/components/overview-blocks.tsx
+++ b/docs/src/components/overview-blocks.tsx
@@ -98,7 +98,7 @@ const PATHS: Path[] = [
{
href: '/docs/integrations/claude-code',
title: 'Setting up an editor?',
- desc: 'Use with Claude, Cursor, Codex, OpenCode, or OpenClaw.',
+ desc: 'Use with Claude, Cursor, Codex, OpenCode, OpenClaw, or Pi.',
},
{
href: '/docs/workflows/karpathy-llm-wiki',
diff --git a/packages/app/src/components/ConsentDialogBody.tsx b/packages/app/src/components/ConsentDialogBody.tsx
index 0e846cbe4..d9eb88a80 100644
--- a/packages/app/src/components/ConsentDialogBody.tsx
+++ b/packages/app/src/components/ConsentDialogBody.tsx
@@ -416,10 +416,18 @@ function ConsentDialogForm({ payload, store, toast }: ConsentDialogFormProps) {
className="text-xs text-muted-foreground"
data-testid={`consent-editor-${editor.id}-scope`}
>
+ {/* Absent hasUserConfig (older main process) reads as
+ user-writable — every pre-Pi editor was. */}
{editor.hasProjectConfig ? (
- <Trans comment="Scope tag next to an AI tool — config is written at both project and user level">
- (project + user)
- </Trans>
+ (editor.hasUserConfig ?? true) ? (
+ <Trans comment="Scope tag next to an AI tool — config is written at both project and user level">
+ (project + user)
+ </Trans>
+ ) : (
+ <Trans comment="Scope tag next to an AI tool — config is written at project level only">
+ (project-level only)
+ </Trans>
+ )
) : (
<Trans comment="Scope tag next to an AI tool — config is written at user level only">
(user-level only)
diff --git a/packages/app/src/components/handoff/OpenInAgentMenuItem.tsx b/packages/app/src/components/handoff/OpenInAgentMenuItem.tsx
index 9f338c74e..0f394890d 100644
--- a/packages/app/src/components/handoff/OpenInAgentMenuItem.tsx
+++ b/packages/app/src/components/handoff/OpenInAgentMenuItem.tsx
@@ -38,6 +38,7 @@ import { ClaudeIcon } from '@/components/icons/claude';
import { CodexBrandIcon } from '@/components/icons/codex';
import { CursorIcon } from '@/components/icons/cursor';
import { OpenCodeIcon } from '@/components/icons/opencode';
+import { PiIcon } from '@/components/icons/pi';
import {
DropdownMenuItem,
DropdownMenuLabel,
@@ -68,8 +69,9 @@ const TARGET_ICON_KEY: Record<TargetData['id'], string> = {
codex: 'openai',
cursor: 'cursor',
// No `AGENT_ICON_COLORS` entry → renders monochrome (inherits the row's text
- // color), which suits OpenCode's monochrome brand mark.
+ // color), which suits OpenCode's and Pi's monochrome brand marks.
opencode: 'opencode',
+ pi: 'pi',
};
export function TargetIcon({
@@ -102,6 +104,7 @@ export function TargetIcon({
if (id === 'cursor') return <CursorIcon style={mergedStyle} className={mergedClass} {...props} />;
if (id === 'opencode')
return <OpenCodeIcon style={mergedStyle} className={mergedClass} {...props} />;
+ if (id === 'pi') return <PiIcon style={mergedStyle} className={mergedClass} {...props} />;
return null;
}
diff --git a/packages/app/src/components/icons/pi.tsx b/packages/app/src/components/icons/pi.tsx
new file mode 100644
index 000000000..b84537ec9
--- /dev/null
+++ b/packages/app/src/components/icons/pi.tsx
@@ -0,0 +1,30 @@
+import type { SVGProps } from 'react';
+
+// Pi brand mark (the blocky "P" + square "i" dot from pi.dev/logo-auto.svg),
+// rendered monochrome via `currentColor` so the dropdown row's color cascade
+// (and the optional `--ok-brand-color` override in `TargetIcon`) tints it per
+// theme — the upstream SVG ships its own light/dark media query, which can't
+// participate in the app's theme toggle.
+export function PiIcon(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ role="img"
+ aria-label="Pi icon"
+ xmlns="http://www.w3.org/2000/svg"
+ width={24}
+ height={24}
+ fill="none"
+ viewBox="0 0 800 800"
+ {...props}
+ >
+ <title>Pi icon</title>
+ <path
+ fill="currentColor"
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"
+ />
+ <path fill="currentColor" d="M517.36 400H634.72V634.72H517.36Z" />
+ </svg>
+ );
+}
diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.ts
index c14399037..dd014ac56 100644
--- a/packages/app/src/lib/desktop-bridge-types.ts
+++ b/packages/app/src/lib/desktop-bridge-types.ts
@@ -485,6 +485,9 @@ export interface OkOnboardingShowPayload {
* when only the user-level config is writable. Drives the per-row
* scope badge in the consent dialog. */
readonly hasProjectConfig: boolean;
+ /** Optional for back-compat; absent reads as `true`. `false` = the editor
+ * has no user-global config surface (Pi — project-scope only). */
+ readonly hasUserConfig?: boolean;
}[];
}
diff --git a/packages/app/src/lib/handoff/dispatch.test.ts b/packages/app/src/lib/handoff/dispatch.test.ts
index 8258cd63f..c73c00a1b 100644
--- a/packages/app/src/lib/handoff/dispatch.test.ts
+++ b/packages/app/src/lib/handoff/dispatch.test.ts
@@ -174,4 +174,18 @@ describe('dispatchHandoff — runtime exhaustiveness guard', () => {
expect(result.reason).toBe('invalid-payload');
expect(result.detail ?? '').toContain('zed');
});
+
+ test.each([
+ 'opencode',
+ 'pi',
+ ] as const)('terminal-only target %s is refused by the deep-link dispatcher (defensive)', async (target) => {
+ // No production caller routes terminal-only targets here (excluded from
+ // VISIBLE_TARGETS); the case exists so a programmatic dispatch fails
+ // loudly instead of hitting the exhaustiveness fallback.
+ const result = await dispatchHandoff({ ...BASE_PAYLOAD, target });
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.reason).toBe('invalid-payload');
+ expect(result.detail ?? '').toContain('terminal-only');
+ });
});
diff --git a/packages/app/src/lib/handoff/dispatch.ts b/packages/app/src/lib/handoff/dispatch.ts
index 088e20853..8e830f75f 100644
--- a/packages/app/src/lib/handoff/dispatch.ts
+++ b/packages/app/src/lib/handoff/dispatch.ts
@@ -126,6 +126,13 @@ export async function dispatchHandoff(
reason: 'invalid-payload',
detail: 'opencode is terminal-only; launch via requestTerminalLaunch',
};
+ case 'pi':
+ // Terminal-only target, same carve-out as opencode above.
+ return {
+ ok: false,
+ reason: 'invalid-payload',
+ detail: 'pi is terminal-only; launch via requestTerminalLaunch',
+ };
default: {
const _exhaustive: never = payload.target;
return {
diff --git a/packages/app/src/lib/handoff/targets.test.ts b/packages/app/src/lib/handoff/targets.test.ts
index 8cfff7012..b50194f0b 100644
--- a/packages/app/src/lib/handoff/targets.test.ts
+++ b/packages/app/src/lib/handoff/targets.test.ts
@@ -2,18 +2,22 @@ import { describe, expect, test } from 'bun:test';
import { KNOWN_TARGETS, VISIBLE_TARGETS } from './targets.ts';
describe('KNOWN_TARGETS', () => {
- test('has exactly five targets (four GUI + terminal-only OpenCode)', () => {
- expect(KNOWN_TARGETS.length).toBe(5);
+ test('has exactly six targets (four GUI + terminal-only OpenCode and Pi)', () => {
+ expect(KNOWN_TARGETS.length).toBe(6);
});
test('ids cover the full HandoffTarget union', () => {
const ids = new Set(KNOWN_TARGETS.map((t) => t.id));
- expect(ids).toEqual(new Set(['claude-cowork', 'claude-code', 'codex', 'cursor', 'opencode']));
+ expect(ids).toEqual(
+ new Set(['claude-cowork', 'claude-code', 'codex', 'cursor', 'opencode', 'pi']),
+ );
});
- test('opencode is terminal-only — no URL scheme', () => {
+ test('opencode and pi are terminal-only — no URL scheme', () => {
const opencode = KNOWN_TARGETS.find((t) => t.id === 'opencode');
expect(opencode?.schemes).toEqual([]);
+ const pi = KNOWN_TARGETS.find((t) => t.id === 'pi');
+ expect(pi?.schemes).toEqual([]);
});
test('claude-cowork + claude-code share the claude: scheme (single install state)', () => {
@@ -43,6 +47,7 @@ describe('KNOWN_TARGETS', () => {
expect(byId.get('codex')).toBe('Codex');
expect(byId.get('cursor')).toBe('Cursor');
expect(byId.get('opencode')).toBe('OpenCode');
+ expect(byId.get('pi')).toBe('Pi');
});
});
@@ -57,11 +62,12 @@ describe('VISIBLE_TARGETS (UI render allow-list)', () => {
expect(ids.has('claude-cowork')).toBe(false);
});
- test('hides the terminal-only opencode target from the GUI deep-link list', () => {
- // OpenCode surfaces as a terminal-CLI launch row (TERMINAL_CLI_IDS), not a
- // GUI deep-link target, so it must not appear in VISIBLE_TARGETS.
+ test('hides the terminal-only opencode + pi targets from the GUI deep-link list', () => {
+ // OpenCode and Pi surface as terminal-CLI launch rows (TERMINAL_CLI_IDS),
+ // not GUI deep-link targets, so they must not appear in VISIBLE_TARGETS.
const ids = new Set(VISIBLE_TARGETS.map((t) => t.id));
expect(ids.has('opencode')).toBe(false);
+ expect(ids.has('pi')).toBe(false);
});
test('keeps the remaining three targets visible', () => {
diff --git a/packages/app/src/lib/handoff/targets.ts b/packages/app/src/lib/handoff/targets.ts
index 3490e434e..3bf083b6f 100644
--- a/packages/app/src/lib/handoff/targets.ts
+++ b/packages/app/src/lib/handoff/targets.ts
@@ -64,6 +64,14 @@ export const KNOWN_TARGETS = [
installUrl: 'https://opencode.ai',
tagline: 'Open-source terminal coding agent; bring any local model.',
},
+ {
+ // Terminal-only target, same carve-out as `opencode` above.
+ id: 'pi',
+ displayName: 'Pi',
+ schemes: [],
+ installUrl: 'https://pi.dev',
+ tagline: 'Minimal open-source terminal coding agent, extensible in TypeScript.',
+ },
] as const satisfies ReadonlyArray<TargetData>;
// UI-visibility allow-list. `claude-cowork` is intentionally absent: dispatch
@@ -73,7 +81,7 @@ export const KNOWN_TARGETS = [
// group, and the empty-state "Create with <agent>" composer.
export const VISIBLE_TARGETS: ReadonlyArray<TargetData> = KNOWN_TARGETS.filter(
// `claude-cowork`: dispatch-by-ID only, no render surface.
- // `opencode`: terminal-only — surfaced via the terminal-CLI rows, not the
- // GUI deep-link target list, so it must not appear as a dispatchable row.
- (target) => target.id !== 'claude-cowork' && target.id !== 'opencode',
+ // `opencode` / `pi`: terminal-only — surfaced via the terminal-CLI rows, not
+ // the GUI deep-link target list, so they must not appear as dispatchable rows.
+ (target) => target.id !== 'claude-cowork' && target.id !== 'opencode' && target.id !== 'pi',
);
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 17f5aef7e..655aab7d1 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -1625,6 +1625,7 @@
"fIgqfQ": ["Reinstalling"],
"fJgQHX": ["Failed to create file"],
"fNr-MX": ["Disable semantic search"],
+ "fR-Kdc": ["(project-level only)"],
"fVcm9t": [["0", "plural", { "one": ["#", " doc"], "other": ["#", " docs"] }]],
"fWi7pn": ["Initialize starter pack"],
"fWsBTs": ["Something went wrong. Please try again."],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index b62717cb8..9ee2b363f 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -83,6 +83,11 @@ msgstr "(opens in new tab)"
msgid "(project + user)"
msgstr "(project + user)"
+#. Scope tag next to an AI tool — config is written at project level only
+#: src/components/ConsentDialogBody.tsx
+msgid "(project-level only)"
+msgstr "(project-level only)"
+
#: src/components/PropertyWidgets.tsx
msgid "(read-only — edit in source mode for now)"
msgstr "(read-only — edit in source mode for now)"
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 9c2fbf976..51130360b 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -1625,6 +1625,7 @@
"fIgqfQ": ["Ŕēĩńśţàĺĺĩńĝ"],
"fJgQHX": ["Ƒàĩĺēď ţō ćŕēàţē ƒĩĺē"],
"fNr-MX": ["Ďĩśàƀĺē śēḿàńţĩć śēàŕćĥ"],
+ "fR-Kdc": ["(ƥŕōĴēćţ-ĺēvēĺ ōńĺŷ)"],
"fVcm9t": [["0", "plural", { "one": ["#", " ďōć"], "other": ["#", " ďōćś"] }]],
"fWi7pn": ["Ĩńĩţĩàĺĩźē śţàŕţēŕ ƥàćķ"],
"fWsBTs": ["Śōḿēţĥĩńĝ ŵēńţ ŵŕōńĝ. Ƥĺēàśē ţŕŷ àĝàĩń."],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 6462425c4..293629d9b 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -83,6 +83,11 @@ msgstr ""
msgid "(project + user)"
msgstr ""
+#. Scope tag next to an AI tool — config is written at project level only
+#: src/components/ConsentDialogBody.tsx
+msgid "(project-level only)"
+msgstr ""
+
#: src/components/PropertyWidgets.tsx
msgid "(read-only — edit in source mode for now)"
msgstr ""
diff --git a/packages/app/tests/integration/_fixtures/init-load-byte-stable-snapshot.ts b/packages/app/tests/integration/_fixtures/init-load-byte-stable-snapshot.ts
index c66fa50c6..fac76235b 100644
--- a/packages/app/tests/integration/_fixtures/init-load-byte-stable-snapshot.ts
+++ b/packages/app/tests/integration/_fixtures/init-load-byte-stable-snapshot.ts
@@ -32,7 +32,8 @@ export function sha256(buf: Buffer): string {
* `.ok/` (init artifact), `.git/` (git metadata), `node_modules/`, and the
* editor / agent tool dirs: `ok init` installs the project-local skill into
* every configured editor's skills root (`.claude/skills/`, `.cursor/skills/`,
- * `.codex/skills/`, `.opencode/skills/`, plus the generic `.agents/skills/`).
+ * `.codex/skills/`, `.opencode/skills/`, `.pi/skills/`, plus the generic
+ * `.agents/skills/`).
* Those SKILL.md files are tool-config artifacts, not user knowledge-base
* content — the load-without-mutate property is about user `.md` / `.mdx`
* content only. This set must cover every `EDITOR_PROJECT_SKILL_ROOT` top-level
@@ -47,6 +48,7 @@ const SNAPSHOT_EXCLUDED_DIRS = new Set([
'.cursor',
'.codex',
'.opencode',
+ '.pi',
'.agents',
]);
diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.ts
index 00cfc81a8..3f9271d20 100644
--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts
+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts
@@ -549,6 +549,7 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
codex: true,
opencode: true,
cursor: true,
+ pi: true,
}),
rewireClaudeMcp: async () => ({ claude: 'present' as const, mcp: 'wired' as const }),
},
diff --git a/packages/cli/src/commands/editors.test.ts b/packages/cli/src/commands/editors.test.ts
index ec28a7b10..7996350bb 100644
--- a/packages/cli/src/commands/editors.test.ts
+++ b/packages/cli/src/commands/editors.test.ts
@@ -17,6 +17,7 @@ import {
resolveEditorTargets,
resolveOpenClawConfigPath,
resolveOpenCodeConfigPath,
+ resolvePiAgentDirPath,
} from './editors.ts';
describe('resolveAppSupportPath', () => {
@@ -198,6 +199,43 @@ describe('resolveOpenClawConfigPath', () => {
});
});
+describe('resolvePiAgentDirPath', () => {
+ it('builds the default Pi agent dir under home', () => {
+ expect(resolvePiAgentDirPath({ home: '/Users/alice', platformName: 'darwin', env: {} })).toBe(
+ '/Users/alice/.pi/agent',
+ );
+ });
+
+ it('honors PI_CODING_AGENT_DIR when present', () => {
+ expect(
+ resolvePiAgentDirPath({
+ home: '/Users/alice',
+ platformName: 'darwin',
+ env: { PI_CODING_AGENT_DIR: '/tmp/custom-pi-home' },
+ }),
+ ).toBe('/tmp/custom-pi-home');
+ });
+});
+
+describe('EDITOR_TARGETS.pi', () => {
+ const t = EDITOR_TARGETS.pi;
+
+ it('is a project-scope-only file-drop target', () => {
+ expect(t.format).toBe('file');
+ expect(t.scope).toBe('project');
+ // No user-global MCP config surface — mirrors Claude Desktop on Linux.
+ expect(() => t.configPath('', '/Users/alice')).toThrow(/no user-global MCP config/);
+ // No entry shape either: the managed file is built by buildPiExtensionSource.
+ expect(() => t.buildEntry('', { mode: 'published' })).toThrow(/buildPiExtensionSource/);
+ });
+
+ it('project paths target OK-owned artifacts under .pi/', () => {
+ expect(t.projectConfigPath?.('/proj')).toBe('/proj/.pi/extensions/open-knowledge.ts');
+ expect(t.projectSkillPath?.('/proj')).toBe('/proj/.pi/skills/open-knowledge/SKILL.md');
+ expect(t.detectPath?.('', '/Users/alice')).toBe('/Users/alice/.pi/agent');
+ });
+});
+
describe('EDITOR_TARGETS.openclaw', () => {
it('nests the managed launcher under mcp.servers', () => {
const t = EDITOR_TARGETS.openclaw;
diff --git a/packages/cli/src/commands/editors.ts b/packages/cli/src/commands/editors.ts
index ade0b1a2e..87663b2a2 100644
--- a/packages/cli/src/commands/editors.ts
+++ b/packages/cli/src/commands/editors.ts
@@ -197,6 +197,34 @@ foreach ($d in $dirs) {
[Console]::Error.WriteLine('OpenKnowledge: install Node.js 24+ (npm i -g @inkeep/open-knowledge), then restart your editor')
exit 127`;
+/**
+ * Version + ownership markers for Pi's managed bridge-extension file
+ * (`.pi/extensions/open-knowledge.ts`) — the `format: 'file'` sibling of the
+ * chain-entry sentinels above. The version sentinel is the whole first line of
+ * a published drop; the ownership marker is its version-agnostic prefix, so
+ * removal recognizes stale AND dev drops while the up-to-date check only
+ * passes the current version. Bump the suffix (`v2`, …) on any
+ * structurally-different generated bridge so reclaim rewrites stale files.
+ * Builders + recognizers live in `integrations/pi-extension.ts`; the constants
+ * live here so that module can depend on this one without a cycle.
+ */
+/** @internal */
+export const PI_EXTENSION_OWNERSHIP_MARKER = '// ok-pi-bridge';
+
+/** @internal */
+export const PI_EXTENSION_VERSION_SENTINEL = `${PI_EXTENSION_OWNERSHIP_MARKER}-v1`;
+
+/**
+ * `command` value of the SYNTHETIC entry `classifyExistingMcpEntry`
+ * fabricates for `format: 'file'` targets (the raw file text rides in
+ * `args[0]`). Lets the shared classify → `isEntryUpToDate` → rewrite/remove
+ * machinery treat the managed file like any config entry, with no per-host
+ * branches in the repair/reclaim consumers.
+ *
+ * @internal
+ */
+export const PI_MANAGED_FILE_ENTRY_COMMAND = 'ok-pi-managed-extension';
+
/**
* MCP install modes for `ok init`-written editor configs.
*
@@ -303,6 +331,19 @@ export function isEntryUpToDate(entry: unknown): boolean {
return false;
}
+ // Pi managed-file shape (synthesized by `classifyExistingMcpEntry` for
+ // `format: 'file'` targets): `args[0]` carries the raw text of
+ // `.pi/extensions/open-knowledge.ts`. Up-to-date iff the file's FIRST LINE
+ // is the current version sentinel — first-line strict so a foreign file that
+ // merely mentions the marker in its body is never classified current, while
+ // body drift below line one keeps the same leave-alone tolerance as the
+ // chain shapes.
+ if (e.command === PI_MANAGED_FILE_ENTRY_COMMAND) {
+ if (!Array.isArray(e.args)) return false;
+ const text = e.args[0];
+ return typeof text === 'string' && text.startsWith(PI_EXTENSION_VERSION_SENTINEL);
+ }
+
return false;
}
@@ -568,14 +609,42 @@ export function resolveOpenClawConfigPath(options: AppSupportOptions = {}): stri
return pathApiForPlatform(platformName).join(home, '.openclaw', 'openclaw.json');
}
+/**
+ * Pi's coding-agent home dir — `~/.pi/agent/` (settings, global extensions,
+ * skills, sessions), overridable via `PI_CODING_AGENT_DIR` like Codex's
+ * `CODEX_HOME`. Detection-only for OK: Pi has no user-global MCP config
+ * surface at all (its `EDITOR_TARGETS` entry is project-scoped — see the
+ * registry comment), so this path is never written, only probed to answer
+ * "is Pi installed on this machine".
+ */
+export function resolvePiAgentDirPath(options: AppSupportOptions = {}): string {
+ const platformName = options.platformName ?? process.platform;
+ const home = options.home ?? homedir();
+ const env = options.env ?? process.env;
+ return env.PI_CODING_AGENT_DIR ?? pathApiForPlatform(platformName).join(home, '.pi', 'agent');
+}
+
export interface EditorMcpTarget {
id: EditorId;
/** Human-friendly name for CLI output. */
label: string;
- /** Resolve the absolute path to the MCP config file. */
+ /**
+ * Resolve the absolute path to the MCP config file. Throws for an editor
+ * with NO user-global config surface on this platform (Claude Desktop on
+ * Linux; Pi everywhere — its integration is the project-scoped managed
+ * file). Every generic consumer already tolerates the throw (repair sweep,
+ * uninstall plan, classify) — it means "nothing to sweep at user scope".
+ */
configPath: (cwd: string, home?: string) => string;
- /** On-disk config format for this editor. */
- format: 'json' | 'toml';
+ /**
+ * On-disk config format for this editor. `'json'` / `'toml'` entries go
+ * through the surgical entry upsert; `'file'` means OK owns the WHOLE file
+ * (Pi's bridge extension) — the write path drops
+ * `buildPiExtensionSource(...)` verbatim and classify/removal treat the raw
+ * text (via the synthetic `PI_MANAGED_FILE_ENTRY_COMMAND` entry) instead of
+ * parsing a server map. `topLevelKey` is inert for `'file'` targets.
+ */
+ format: 'json' | 'toml' | 'file';
/** Top-level key that holds the server map. */
topLevelKey: 'mcpServers' | 'servers' | 'mcp_servers' | 'mcp';
/**
@@ -707,6 +776,44 @@ export const EDITOR_TARGETS: Record<EditorId, EditorMcpTarget> = {
// installed — gated on detection even under consent-flow skipAvailabilityCheck.
offerOnlyWhenDetected: true,
},
+ pi: {
+ id: 'pi',
+ label: EDITOR_LABELS.pi,
+ // Pi has no MCP support and no MCP config file — not user-global, not
+ // project-local. The ONLY route is a Pi extension, so OK's integration is
+ // the managed bridge file at `projectConfigPath` (project-scoped;
+ // `scope: 'project'` below is the structural marker consumers gate
+ // user-scope surfaces on). Throwing here mirrors Claude Desktop on Linux:
+ // every generic consumer treats it as "no user-global surface to sweep".
+ configPath: () => {
+ throw new Error(
+ "Pi has no user-global MCP config; OK's integration is the project-scoped bridge extension at .pi/extensions/open-knowledge.ts (run `ok init` in the project).",
+ );
+ },
+ format: 'file',
+ // Inert for `format: 'file'` targets (no server map to key into); the
+ // interface requires a value, and `mcpServers` is the least surprising.
+ topLevelKey: 'mcpServers',
+ serverName: () => MCP_SERVER_NAME,
+ buildEntry: () => {
+ throw new Error(
+ 'Pi has no MCP entry shape; the managed bridge file is built by buildPiExtensionSource (integrations/pi-extension.ts).',
+ );
+ },
+ scope: 'project',
+ detectPath: (_cwd, home) => resolvePiAgentDirPath({ home }),
+ // The dropped bridge extension IS the project config: its presence is the
+ // "project-configured" signal, and pointing `projectConfigPath` at it
+ // routes every generic project-scope consumer (repair sweep, desktop
+ // reclaim, sharing-mode exclude, deinit) at OK's own artifact. Second
+ // source for core's `EDITOR_PROJECT_CONFIG_PATH.pi` and must match it.
+ // OK never reads or writes `.pi/settings.json` — that file is the user's.
+ projectConfigPath: (cwd) => join(cwd, '.pi', 'extensions', 'open-knowledge.ts'),
+ // Pi scans `.pi/skills` natively (alongside `.agents/skills`), trust-gated
+ // like its extensions. Second source for core's
+ // `EDITOR_PROJECT_SKILL_ROOT.pi` and must match it.
+ projectSkillPath: (cwd) => join(cwd, '.pi', 'skills', 'open-knowledge', 'SKILL.md'),
+ },
};
/**
diff --git a/packages/cli/src/commands/init.test.ts b/packages/cli/src/commands/init.test.ts
index 096bd9de1..b1e79d187 100644
--- a/packages/cli/src/commands/init.test.ts
+++ b/packages/cli/src/commands/init.test.ts
@@ -17,6 +17,7 @@ import { readBundleDecision } from '@inkeep/open-knowledge-server';
import { loadConfig } from '../config/loader.ts';
import { OK_DIR } from '../constants.ts';
import { previewContent } from '../content/preview.ts';
+import { buildPiExtensionSource } from '../integrations/pi-extension.ts';
import {
ALL_EDITOR_IDS,
CHAIN_V1,
@@ -50,6 +51,7 @@ import {
initCommand,
LAUNCH_UI_CHAIN_SENTINEL,
LAUNCH_UI_CHAIN_V1,
+ MANAGED_FILE_BUILDERS,
readExistingMcpEntry,
resolveInitSkillEnablement,
resolveMcpScope,
@@ -616,6 +618,70 @@ describe('runInit', () => {
});
});
+ describe('Pi (project-scope file drop)', () => {
+ const piBridgePath = () => join(testDir, '.pi', 'extensions', 'open-knowledge.ts');
+
+ it('drops the managed bridge extension at .pi/extensions/open-knowledge.ts', async () => {
+ const result = await runInitForTest({ editors: ['pi'], scope: 'project' });
+
+ const projResult = result.editors.find(
+ (e) => e.editorId === 'pi' && e.configScope === 'project',
+ );
+ expect(projResult?.action).toBe('written');
+ expect(projResult?.configPath).toBe(piBridgePath());
+
+ const bytes = readFileSync(piBridgePath(), 'utf-8');
+ expect(bytes).toBe(buildPiExtensionSource({ mode: 'published' }));
+ });
+
+ it('re-run is idempotent — byte-identical bridge, action overwritten', async () => {
+ await runInitForTest({ editors: ['pi'], scope: 'project' });
+ const first = readFileSync(piBridgePath(), 'utf-8');
+
+ const again = await runInitForTest({ editors: ['pi'], scope: 'project' });
+ const projResult = again.editors.find(
+ (e) => e.editorId === 'pi' && e.configScope === 'project',
+ );
+ expect(projResult?.action).toBe('overwritten');
+ expect(readFileSync(piBridgePath(), 'utf-8')).toBe(first);
+ });
+
+ it('writes the Pi project skill into .pi/skills/', async () => {
+ const result = await runInitForTest({ editors: ['pi'], scope: 'project' });
+ const piSkill = join(testDir, '.pi', 'skills', 'open-knowledge', 'SKILL.md');
+ expect(result.projectSkills.some((s) => s.path === piSkill)).toBe(true);
+ expect(existsSync(piSkill)).toBe(true);
+ });
+
+ it('user scope produces NO pi result and never touches ~/.pi (project-scope-only editor)', async () => {
+ mkdirSync(join(fakeHome, '.pi', 'agent'), { recursive: true });
+ const result = await runInitForTest({ editors: ['pi'], scope: 'user' });
+ expect(result.editors.filter((e) => e.editorId === 'pi')).toHaveLength(0);
+ expect(existsSync(join(fakeHome, '.pi', 'extensions'))).toBe(false);
+ });
+
+ it('every format:file target has a registered managed-file builder', () => {
+ // Lockstep pin for MANAGED_FILE_BUILDERS (see its doc comment for why it
+ // is a lookup table rather than a function field on EditorMcpTarget): a
+ // future format:'file' editor must register its builder or the write
+ // path fails loud on every init.
+ for (const target of Object.values(EDITOR_TARGETS)) {
+ if (target.format === 'file') {
+ expect(MANAGED_FILE_BUILDERS[target.id]).toBeDefined();
+ }
+ }
+ expect(MANAGED_FILE_BUILDERS.pi).toBe(buildPiExtensionSource);
+ });
+
+ it('dev mode drops the dev-launcher bridge', async () => {
+ enableDevMcp();
+ await runInitForTest({ editors: ['pi'], scope: 'project', devMcp: true });
+ const bytes = readFileSync(piBridgePath(), 'utf-8');
+ expect(bytes).toBe(buildPiExtensionSource({ mode: 'dev' }));
+ expect(bytes).toContain(join(devRepoRoot(), 'packages', 'cli', 'dist', 'cli.mjs'));
+ });
+ });
+
describe('Claude Desktop', () => {
it('writes the same simple global open-knowledge entry as the local editors', async () => {
const fakeHome = join(testDir, 'fakehome');
@@ -733,10 +799,15 @@ describe('runInit', () => {
mkdirSync(dirname(codexConfigPath()), { recursive: true });
mkdirSync(dirname(opencodeConfigPath()), { recursive: true });
mkdirSync(join(fakeHome, '.openclaw'), { recursive: true });
+ mkdirSync(join(fakeHome, '.pi', 'agent'), { recursive: true });
const result = await runInitForTest({ editors: [...ALL_EDITOR_IDS] });
- expect(result.editors).toHaveLength(ALL_EDITOR_IDS.length);
+ // Every editor with a user-global config surface gets a user-scope
+ // write; Pi is project-scope only (its bridge file is written by the
+ // project-scope flow), so it is skipped here rather than failed.
+ expect(result.editors).toHaveLength(ALL_EDITOR_IDS.length - 1);
+ expect(result.editors.map((e) => e.editorId)).not.toContain('pi');
for (const editor of result.editors) {
expect(editor.action).toBe('written');
}
@@ -2297,11 +2368,21 @@ describe('detectInstalledEditors', () => {
mkdirSync(dirname(codexConfigPath()), { recursive: true });
mkdirSync(dirname(opencodeConfigPath()), { recursive: true });
mkdirSync(join(fakeHome, '.openclaw'), { recursive: true });
+ mkdirSync(join(fakeHome, '.pi', 'agent'), { recursive: true });
const detected = detectInstalledEditors(testDir, fakeHome);
expect(detected).toEqual(expect.arrayContaining([...ALL_EDITOR_IDS]));
expect(detected).toHaveLength(ALL_EDITOR_IDS.length);
});
+ it('detects Pi via ~/.pi/agent (not the bare ~/.pi dotdir)', async () => {
+ // `~/.pi` alone could belong to another tool; the coding agent's home is
+ // the nested `agent/` dir.
+ mkdirSync(join(fakeHome, '.pi'), { recursive: true });
+ expect(detectInstalledEditors(testDir, fakeHome)).not.toContain('pi');
+ mkdirSync(join(fakeHome, '.pi', 'agent'), { recursive: true });
+ expect(detectInstalledEditors(testDir, fakeHome)).toContain('pi');
+ });
+
it('preserves EDITOR_TARGETS ordering in return value', async () => {
mkdirSync(join(fakeHome, '.claude'), { recursive: true });
mkdirSync(dirname(resolveClaudeDesktopConfigPath({ home: fakeHome })), { recursive: true });
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
index 6be649a64..e500fb8bc 100644
--- a/packages/cli/src/commands/init.ts
+++ b/packages/cli/src/commands/init.ts
@@ -56,6 +56,7 @@ import {
import { stringify as stringifyToml } from 'smol-toml';
import { CONFIG_FILENAME, OK_DIR } from '../constants.ts';
import { formatPreviewBlock, type PreviewResult } from '../content/preview.ts';
+import { buildPiExtensionSource, makePiManagedFileEntry } from '../integrations/pi-extension.ts';
import { resolveProjectRoot } from '../integrations/resolve-project-root.ts';
import { removeUserGlobalSkillBundle } from '../integrations/skill-teardown.ts';
import {
@@ -1090,6 +1091,17 @@ export function writeEditorMcpConfig(
}
}
+ // `format: 'file'` targets (Pi): OK owns the WHOLE managed file, so the
+ // write is a verbatim drop of the generated source rather than an entry
+ // upsert into a shared config. Only reachable at project scope — a
+ // file-format target's user-global `configPath` throws, returning `failed`
+ // above before this point.
+ if (target.format === 'file') {
+ return writeManagedEditorFile(target, configPath, serverName, installOptions, {
+ isProjectScope: configPathOverride !== undefined,
+ });
+ }
+
let targetEntry: Record<string, unknown>;
try {
targetEntry = target.buildEntry(cwd, installOptions);
@@ -1229,6 +1241,113 @@ export function writeEditorMcpConfig(
};
}
+/**
+ * Whole-file content builders for `format: 'file'` targets, keyed by editor
+ * id. Deliberately a lookup table here rather than a `buildFileContent`
+ * function field on `EditorMcpTarget`: `integrations/pi-extension.ts` imports
+ * the registry module for the launcher chains, so a registry entry referencing
+ * the builder back would create an `editors.ts` ⇄ `pi-extension.ts` module
+ * cycle (TDZ-fragile at evaluation time). A future `format: 'file'` editor
+ * adds one entry; `writeManagedEditorFile` fails loud when it is missing, and
+ * the lockstep test in `init.test.ts` pins the two in sync.
+ *
+ * @internal exported for that lockstep test only.
+ */
+export const MANAGED_FILE_BUILDERS: Partial<
+ Record<EditorId, (options?: McpInstallOptions) => string>
+> = {
+ pi: buildPiExtensionSource,
+};
+
+/**
+ * Write path for `format: 'file'` targets — the whole-file sibling of the
+ * JSON/TOML entry upserts. Drops the generated managed source verbatim,
+ * skipping the write on byte equality so idempotent `ok init` re-runs never
+ * churn the file. A foreign file squatting OK's managed path is overwritten —
+ * the same namespace-ownership rule the entry upserts apply to a foreign
+ * server under OK's `open-knowledge` key. Serialized under the same advisory
+ * lock the entry writers use so concurrent OK writers can't interleave.
+ */
+function writeManagedEditorFile(
+ target: EditorMcpTarget,
+ configPath: string,
+ serverName: string,
+ installOptions: McpInstallOptions,
+ opts: { isProjectScope: boolean },
+): EditorMcpResult {
+ const scopeField = opts.isProjectScope ? { configScope: 'project' as const } : {};
+ const fail = (err: unknown): EditorMcpResult => ({
+ editorId: target.id,
+ label: target.label,
+ action: 'failed',
+ configPath,
+ serverName,
+ error: err instanceof Error ? err.message : String(err),
+ ...scopeField,
+ });
+
+ const buildFileContent = MANAGED_FILE_BUILDERS[target.id];
+ if (!buildFileContent) {
+ return fail(
+ new Error(
+ `No managed-file builder registered for editor "${target.id}" (format: 'file' targets need a MANAGED_FILE_BUILDERS entry).`,
+ ),
+ );
+ }
+ let desired: string;
+ try {
+ desired = buildFileContent(installOptions);
+ } catch (err) {
+ return fail(err);
+ }
+
+ try {
+ mkdirSync(dirname(configPath), { recursive: true });
+ } catch (err) {
+ return fail(err);
+ }
+
+ const captured: { action: 'written' | 'overwritten' } = { action: 'written' };
+ try {
+ withFileLockSync(
+ `${configPath}.lock`,
+ () => {
+ let existing: string | null = null;
+ try {
+ existing = readFileSync(configPath, 'utf-8');
+ } catch {
+ existing = null;
+ }
+ if (existing === desired) {
+ captured.action = 'overwritten';
+ return;
+ }
+ atomicWriteFileSync(
+ configPath,
+ desired,
+ existing !== null ? { mode: existingFileMode(configPath) } : undefined,
+ );
+ captured.action = existing === null ? 'written' : 'overwritten';
+ },
+ {
+ onWarn: (message, context) =>
+ process.stderr.write(`[ok] ${message} ${JSON.stringify(context)}\n`),
+ },
+ );
+ } catch (err) {
+ return fail(err);
+ }
+
+ return {
+ editorId: target.id,
+ label: target.label,
+ action: captured.action,
+ configPath,
+ serverName,
+ ...scopeField,
+ };
+}
+
function collectProjectConfig(
target: EditorMcpTarget,
cwd: string,
@@ -1280,7 +1399,12 @@ export interface UserMcpConfigsOptions {
* so skip-on-missing would silently drop their selection.
*/
export async function writeUserMcpConfigs(opts: UserMcpConfigsOptions): Promise<EditorMcpResult[]> {
- const targets = resolveEditorTargets(opts.editors);
+ // Filter out `scope: 'project'` targets (Pi) defensively: they have no
+ // user-global config to write (`configPath` throws), so a caller that
+ // enumerated every editor id would otherwise get a guaranteed-failed result
+ // — which the desktop consent flow treats as retry-forever. The consent UI
+ // filters its checkbox list the same way; this is the write-side backstop.
+ const targets = resolveEditorTargets(opts.editors).filter((t) => t.scope === 'global');
const installOptions: McpInstallOptions = {
mode: 'published',
skipAvailabilityCheck: true,
@@ -1437,6 +1561,16 @@ export function classifyExistingMcpEntry(
return { kind: 'absent' };
}
+ // `format: 'file'` targets (Pi): the raw text IS the classify unit — no
+ // server map to parse. Any non-blank file at the managed path classifies
+ // `present` (namespace ownership: the path is OK's, like the
+ // `open-knowledge` key in a shared config); `isEntryUpToDate` /
+ // `isOwnPiManagedFileEntry` then decide rewrite vs remove vs leave-foreign
+ // from the synthesized entry.
+ if (target.format === 'file') {
+ return { kind: 'present', entry: makePiManagedFileEntry(raw) };
+ }
+
const serverName = target.serverName(cwd);
// TOML reads through the capable engine (the native `toml_edit` addon when
@@ -1626,7 +1760,10 @@ export async function runInit(options: InitCommandOptions = {}): Promise<InitCom
continue;
}
- if (writesUser(scope) && userTargets.includes(target)) {
+ // `scope: 'project'` targets (Pi) have no user-global config surface —
+ // their `configPath` throws — so the user-scope write is skipped rather
+ // than surfaced as a spurious per-editor failure.
+ if (writesUser(scope) && userTargets.includes(target) && target.scope === 'global') {
editorResults.push(writeEditorMcpConfig(target, projectRoot, installOptions, options.home));
}
if (writesProject(scope) && projectTargets.includes(target) && target.projectConfigPath) {
diff --git a/packages/cli/src/commands/mcp-config-removal.test.ts b/packages/cli/src/commands/mcp-config-removal.test.ts
index 408eec2ae..90c537b7d 100644
--- a/packages/cli/src/commands/mcp-config-removal.test.ts
+++ b/packages/cli/src/commands/mcp-config-removal.test.ts
@@ -1,13 +1,18 @@
import { describe, expect, test } from 'bun:test';
-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { MCP_SERVER_NAME } from '@inkeep/open-knowledge-server';
+import { buildPiExtensionSource } from '../integrations/pi-extension.ts';
import {
createTomlConfigEngine,
setTomlConfigEngineForTesting,
} from '../native/toml-config-engine.ts';
-import { buildManagedServerEntry, EDITOR_TARGETS } from './editors.ts';
+import {
+ buildManagedServerEntry,
+ EDITOR_TARGETS,
+ PI_EXTENSION_OWNERSHIP_MARKER,
+} from './editors.ts';
import { removeOwnMcpEntry } from './mcp-config-removal.ts';
function tmp(): string {
@@ -279,3 +284,75 @@ describe('removeOwnMcpEntry — TOML (Codex)', () => {
}
});
});
+
+describe('removeOwnMcpEntry — Pi managed extension file', () => {
+ const piConfigPath = (dir: string) => {
+ const p = EDITOR_TARGETS.pi.projectConfigPath?.(dir);
+ if (!p) throw new Error('pi projectConfigPath missing');
+ return p;
+ };
+
+ test('removes OK’s own bridge file (current version)', () => {
+ const dir = tmp();
+ try {
+ const configPath = piConfigPath(dir);
+ mkdirSync(join(dir, '.pi', 'extensions'), { recursive: true });
+ writeFileSync(configPath, buildPiExtensionSource());
+ const outcome = removeOwnMcpEntry(EDITOR_TARGETS.pi, dir, undefined, configPath);
+ expect(outcome.kind).toBe('removed');
+ expect(existsSync(configPath)).toBe(false);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('removes a STALE-version drop (ownership marker is version-agnostic)', () => {
+ // Unlike chain entries (dev/stale → left-foreign), the managed file's
+ // first-line marker is an unambiguous OK signature, so stale drops are
+ // removable — a deinit must not strand `-v0` files forever.
+ const dir = tmp();
+ try {
+ const configPath = piConfigPath(dir);
+ mkdirSync(join(dir, '.pi', 'extensions'), { recursive: true });
+ writeFileSync(configPath, `${PI_EXTENSION_OWNERSHIP_MARKER}-v0\n// legacy body\n`);
+ const outcome = removeOwnMcpEntry(EDITOR_TARGETS.pi, dir, undefined, configPath);
+ expect(outcome.kind).toBe('removed');
+ expect(existsSync(configPath)).toBe(false);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('leaves a FOREIGN file at the managed path untouched', () => {
+ const dir = tmp();
+ try {
+ const configPath = piConfigPath(dir);
+ mkdirSync(join(dir, '.pi', 'extensions'), { recursive: true });
+ const raw = "// the user's own extension, not OK's\nexport default function () {}\n";
+ writeFileSync(configPath, raw);
+ const outcome = removeOwnMcpEntry(EDITOR_TARGETS.pi, dir, undefined, configPath);
+ expect(outcome.kind).toBe('left-foreign');
+ expect(readFileSync(configPath, 'utf-8')).toBe(raw);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('not-present when the bridge file is absent, idempotent on re-run', () => {
+ const dir = tmp();
+ try {
+ const configPath = piConfigPath(dir);
+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, dir, undefined, configPath).kind).toBe(
+ 'not-present',
+ );
+ mkdirSync(join(dir, '.pi', 'extensions'), { recursive: true });
+ writeFileSync(configPath, buildPiExtensionSource());
+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, dir, undefined, configPath).kind).toBe('removed');
+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, dir, undefined, configPath).kind).toBe(
+ 'not-present',
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/cli/src/commands/mcp-config-removal.ts b/packages/cli/src/commands/mcp-config-removal.ts
index 07da4f203..e8761bfb5 100644
--- a/packages/cli/src/commands/mcp-config-removal.ts
+++ b/packages/cli/src/commands/mcp-config-removal.ts
@@ -23,8 +23,9 @@
* config it doesn't own.
*/
-import { readFileSync } from 'node:fs';
+import { readFileSync, rmSync } from 'node:fs';
import { atomicWriteFileSync } from '@inkeep/open-knowledge-core/server';
+import { isOwnPiManagedFileEntry } from '../integrations/pi-extension.ts';
import { getTomlConfigEngine } from '../native/toml-config-engine.ts';
import { type EditorMcpTarget, isEntryUpToDate, isOwnManagedEntry } from './editors.ts';
import { classifyExistingMcpEntry, type McpDeclineReason, serverMapPath } from './init.ts';
@@ -74,9 +75,15 @@ export type McpRemoveOutcome =
* signature that can't also match a foreign server, so they surface as
* `left-foreign` (reported for manual removal) rather than risk deleting
* someone else's config.
+ *
+ * `isOwnPiManagedFileEntry` covers `format: 'file'` targets (Pi's managed
+ * bridge extension, classified as a synthetic entry carrying the raw file
+ * text). Unlike the chain shapes, stale AND dev drops ARE removable there:
+ * the first-line ownership marker is an unambiguous OK signature a foreign
+ * file wouldn't carry, so version-agnostic removal is safe.
*/
function isRemovableOwnEntry(entry: unknown): boolean {
- return isEntryUpToDate(entry) || isOwnManagedEntry(entry);
+ return isEntryUpToDate(entry) || isOwnManagedEntry(entry) || isOwnPiManagedFileEntry(entry);
}
/**
@@ -127,6 +134,15 @@ export function removeOwnMcpEntry(
}
const serverName = target.serverName(cwd);
+ // `format: 'file'` targets (Pi): OK owns the whole managed file, so removal
+ // is whole-file — already gated above on the first-line ownership marker via
+ // `isOwnPiManagedFileEntry`, so a foreign file at the managed path is never
+ // deleted (`left-foreign`).
+ if (target.format === 'file') {
+ rmSync(configPath, { force: true });
+ return { kind: 'removed' };
+ }
+
return target.format === 'toml'
? removeTomlEntry(configPath, serverName)
: removeJsonEntry(configPath, target.topLevelKey, target.serverMapSubKey, serverName);
diff --git a/packages/cli/src/commands/mcp-cross-harness-acceptance.test.ts b/packages/cli/src/commands/mcp-cross-harness-acceptance.test.ts
index 841b1ee09..f9f95c23f 100644
--- a/packages/cli/src/commands/mcp-cross-harness-acceptance.test.ts
+++ b/packages/cli/src/commands/mcp-cross-harness-acceptance.test.ts
@@ -1,8 +1,17 @@
import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
-import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import {
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
import { tmpdir } from 'node:os';
-import { join } from 'node:path';
+import { dirname, join } from 'node:path';
import { parse as parseJsonc } from 'jsonc-parser';
+import { buildPiExtensionSource } from '../integrations/pi-extension.ts';
import {
createTomlConfigEngine,
setTomlConfigEngineForTesting,
@@ -339,3 +348,71 @@ describe('decline carries no config contents', () => {
expect(JSON.stringify(result)).not.toContain(secret);
});
});
+
+describe('pi file-drop write path (whole-file sibling of the entry upserts)', () => {
+ let dir: string;
+
+ afterEach(() => {
+ if (dir) rmSync(dir, { recursive: true, force: true });
+ });
+
+ function projectDir(): string {
+ dir = mkdtempSync(join(tmpdir(), 'ok-acceptance-pi-'));
+ return dir;
+ }
+
+ function writePi(cwd: string) {
+ const target = EDITOR_TARGETS.pi;
+ const projPath = target.projectConfigPath?.(cwd);
+ if (!projPath) throw new Error('pi projectConfigPath missing');
+ return {
+ projPath,
+ result: writeEditorMcpConfig(
+ target,
+ cwd,
+ { mode: 'published', skipAvailabilityCheck: true },
+ undefined,
+ projPath,
+ ),
+ };
+ }
+
+ it('drops the managed bridge byte-equal to buildPiExtensionSource, idempotent on re-run', () => {
+ const cwd = projectDir();
+ const first = writePi(cwd);
+ expect(first.result.action).toBe('written');
+ const bytes = readFileSync(first.projPath, 'utf-8');
+ expect(bytes).toBe(buildPiExtensionSource({ mode: 'published' }));
+
+ const second = writePi(cwd);
+ expect(second.result.action).toBe('overwritten');
+ expect(readFileSync(second.projPath, 'utf-8')).toBe(bytes);
+ // No destructive sidecar on the write path.
+ expect(readdirSync(dirname(first.projPath)).some((n) => n.includes('.broken-'))).toBe(false);
+ });
+
+ it('rewrites a stale or foreign file at the managed path (namespace ownership)', () => {
+ const cwd = projectDir();
+ const target = EDITOR_TARGETS.pi;
+ const projPath = target.projectConfigPath?.(cwd) as string;
+ mkdirSync(dirname(projPath), { recursive: true });
+ writeFileSync(projPath, '// ok-pi-bridge-v0\n// stale drop\n');
+ const stale = writePi(cwd);
+ expect(stale.result.action).toBe('overwritten');
+ expect(readFileSync(projPath, 'utf-8')).toBe(buildPiExtensionSource({ mode: 'published' }));
+ });
+
+ it('refuses to write through a symlinked .pi ancestor (project path safety)', () => {
+ const cwd = projectDir();
+ const outside = mkdtempSync(join(tmpdir(), 'ok-acceptance-pi-outside-'));
+ try {
+ symlinkSync(outside, join(cwd, '.pi'));
+ const outcome = writePi(cwd);
+ expect(outcome.result.action).toBe('failed');
+ expect(outcome.result.error).toMatch(/outside the project directory|symbolic link/);
+ expect(readdirSync(outside)).toEqual([]);
+ } finally {
+ rmSync(outside, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/cli/src/commands/repair-skills.test.ts b/packages/cli/src/commands/repair-skills.test.ts
index 58a3b72a2..1f311c781 100644
--- a/packages/cli/src/commands/repair-skills.test.ts
+++ b/packages/cli/src/commands/repair-skills.test.ts
@@ -979,8 +979,12 @@ describe('repairSkills — OK_RECLAIM_DISABLE env gate (AC-C1)', () => {
describe('coverage meta-test (AC-D2): HOSTS_WITH_USER_SKILL_DIR ↔ EDITOR_TARGETS.projectSkillPath', () => {
it('CLI host list matches the set of editor ids that declare a projectSkillPath', () => {
+ // Pi is the documented carve-out: it declares a projectSkillPath
+ // (`.pi/skills`) but has NO `~/.pi/skills` user dir — its user-global
+ // skills live at `~/.pi/agent/skills` and it reads the central
+ // `~/.agents/skills` hub natively, so the user host-dir sweep skips it.
const hostsWithProjectSkillPath = Object.entries(EDITOR_TARGETS)
- .filter(([, target]) => target.projectSkillPath !== undefined)
+ .filter(([id, target]) => target.projectSkillPath !== undefined && id !== 'pi')
.map(([id]) => id)
.sort();
diff --git a/packages/cli/src/integrations/pi-extension.test.ts b/packages/cli/src/integrations/pi-extension.test.ts
new file mode 100644
index 000000000..353a4a3fb
--- /dev/null
+++ b/packages/cli/src/integrations/pi-extension.test.ts
@@ -0,0 +1,230 @@
+import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ CHAIN_V1,
+ CHAIN_WIN_V1,
+ isEntryUpToDate,
+ PI_EXTENSION_OWNERSHIP_MARKER,
+ PI_EXTENSION_VERSION_SENTINEL,
+} from '../commands/editors.ts';
+import {
+ buildPiExtensionSource,
+ isOwnPiExtensionSource,
+ isOwnPiManagedFileEntry,
+ isPiExtensionSourceUpToDate,
+ makePiManagedFileEntry,
+} from './pi-extension.ts';
+
+describe('buildPiExtensionSource', () => {
+ it('published source starts with the version sentinel as its whole first line', () => {
+ const source = buildPiExtensionSource();
+ expect(source.split('\n')[0]).toBe(PI_EXTENSION_VERSION_SENTINEL);
+ });
+
+ it('is byte-deterministic (idempotent ok init re-runs skip the write on equality)', () => {
+ expect(buildPiExtensionSource()).toBe(buildPiExtensionSource());
+ expect(buildPiExtensionSource({ mode: 'published' })).toBe(buildPiExtensionSource());
+ });
+
+ it('embeds BOTH platform launcher chains so one committed file serves every teammate', () => {
+ const source = buildPiExtensionSource();
+ // The chains ride inside JSON.stringify'd launcher entries, so their
+ // newlines appear as the two-character escape.
+ expect(source).toContain(JSON.stringify(CHAIN_V1));
+ expect(source).toContain(JSON.stringify(CHAIN_WIN_V1));
+ expect(source).toContain('process.platform === "win32"');
+ });
+
+ it('dev mode embeds the local dist launcher and an owned-but-stale header', () => {
+ const originalArgv1 = process.argv[1];
+ process.argv[1] = '/repo/packages/cli/src/cli.ts';
+ try {
+ const source = buildPiExtensionSource({ mode: 'dev' });
+ expect(source).toContain('/repo/packages/cli/dist/cli.mjs');
+ expect(isOwnPiExtensionSource(source)).toBe(true);
+ // Dev drops must NOT classify current, mirroring dev chain entries:
+ // the repair/reclaim sweeps migrate them forward to published.
+ expect(isPiExtensionSourceUpToDate(source)).toBe(false);
+ } finally {
+ process.argv[1] = originalArgv1;
+ }
+ });
+
+ it('generates syntactically valid TypeScript (the file Pi loads via jiti)', () => {
+ const transpiler = new Bun.Transpiler({ loader: 'ts' });
+ // Throws on a syntax error — an interpolation regression (unescaped
+ // backtick / ${ in the template) fails here rather than inside Pi.
+ expect(() => transpiler.transformSync(buildPiExtensionSource())).not.toThrow();
+ expect(() => transpiler.transformSync(buildPiExtensionSource({ mode: 'dev' }))).not.toThrow();
+ });
+
+ it('registers under the ok_ prefix so OK tools never shadow Pi built-ins', () => {
+ // Pi has no MCP namespacing; an unprefixed `edit` / `write` registration
+ // would OVERRIDE Pi's built-in file tools.
+ expect(buildPiExtensionSource()).toContain('const TOOL_PREFIX = "ok_"');
+ });
+});
+
+describe('pi extension recognizers', () => {
+ const published = buildPiExtensionSource();
+
+ it('isOwnPiExtensionSource: first-line strict ownership', () => {
+ expect(isOwnPiExtensionSource(published)).toBe(true);
+ expect(isOwnPiExtensionSource(`${PI_EXTENSION_OWNERSHIP_MARKER}-v0\nlegacy body`)).toBe(true);
+ // Marker in the body only — a foreign file mentioning it is not claimed.
+ expect(isOwnPiExtensionSource(`// my extension\n${PI_EXTENSION_OWNERSHIP_MARKER}\n`)).toBe(
+ false,
+ );
+ expect(isOwnPiExtensionSource('export default function () {}')).toBe(false);
+ });
+
+ it('isPiExtensionSourceUpToDate: current version only', () => {
+ expect(isPiExtensionSourceUpToDate(published)).toBe(true);
+ expect(isPiExtensionSourceUpToDate(`${PI_EXTENSION_OWNERSHIP_MARKER}-v0\nstale`)).toBe(false);
+ expect(isPiExtensionSourceUpToDate('// something else')).toBe(false);
+ });
+
+ it('isEntryUpToDate recognizes the synthetic managed-file entry', () => {
+ expect(isEntryUpToDate(makePiManagedFileEntry(published))).toBe(true);
+ expect(isEntryUpToDate(makePiManagedFileEntry(`${PI_EXTENSION_OWNERSHIP_MARKER}-v0\nx`))).toBe(
+ false,
+ );
+ expect(isEntryUpToDate(makePiManagedFileEntry('foreign'))).toBe(false);
+ });
+
+ it('isOwnPiManagedFileEntry gates removal on the ownership marker', () => {
+ expect(isOwnPiManagedFileEntry(makePiManagedFileEntry(published))).toBe(true);
+ expect(
+ isOwnPiManagedFileEntry(makePiManagedFileEntry(`${PI_EXTENSION_OWNERSHIP_MARKER}-v0\nx`)),
+ ).toBe(true);
+ expect(isOwnPiManagedFileEntry(makePiManagedFileEntry('// foreign file'))).toBe(false);
+ expect(isOwnPiManagedFileEntry({ command: '/bin/sh', args: ['-l', '-c', CHAIN_V1] })).toBe(
+ false,
+ );
+ expect(isOwnPiManagedFileEntry(null)).toBe(false);
+ });
+});
+
+// Functional round-trip: run the GENERATED extension against a fake `pi` API
+// and a stub MCP server speaking real newline-delimited JSON-RPC over stdio.
+// This exercises the whole bridge — spawn, handshake, tools/list → registerTool,
+// execute → tools/call, error mapping — through a real child process, without
+// needing Pi or a built OK CLI.
+describe('generated bridge extension (functional, stub MCP server)', () => {
+ let dir: string;
+ const originalArgv1 = process.argv[1];
+
+ const STUB_SERVER = `
+import readline from "node:readline";
+const rl = readline.createInterface({ input: process.stdin });
+function send(msg) { process.stdout.write(JSON.stringify(msg) + "\\n"); }
+rl.on("line", (line) => {
+ if (!line.trim()) return;
+ const msg = JSON.parse(line);
+ if (msg.method === "initialize") {
+ send({ jsonrpc: "2.0", id: msg.id, result: {
+ protocolVersion: "2025-06-18",
+ capabilities: { tools: {} },
+ serverInfo: { name: "stub-ok", version: "0.0.0" },
+ }});
+ } else if (msg.method === "tools/list") {
+ send({ jsonrpc: "2.0", id: msg.id, result: { tools: [
+ { name: "exec", description: "Run a command.", inputSchema: {
+ type: "object", properties: { command: { type: "string" } }, required: ["command"],
+ }},
+ { name: "boom", description: "Always fails.", inputSchema: { type: "object" } },
+ ]}});
+ } else if (msg.method === "tools/call") {
+ const { name, arguments: args } = msg.params;
+ if (name === "boom") {
+ send({ jsonrpc: "2.0", id: msg.id, result: {
+ content: [{ type: "text", text: "it broke" }], isError: true,
+ }});
+ } else {
+ send({ jsonrpc: "2.0", id: msg.id, result: {
+ content: [{ type: "text", text: "ran: " + args.command }],
+ structuredContent: { echoed: args.command },
+ }});
+ }
+ } else if (msg.id !== undefined) {
+ send({ jsonrpc: "2.0", id: msg.id, error: { code: -32601, message: "nope" } });
+ }
+});
+`;
+
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'ok-pi-bridge-'));
+ // Dev-mode launcher resolves `<root>/packages/cli/dist/cli.mjs` from
+ // argv[1]; point it at the stub server so the generated file spawns it.
+ mkdirSync(join(dir, 'packages', 'cli', 'dist'), { recursive: true });
+ writeFileSync(join(dir, 'packages', 'cli', 'dist', 'cli.mjs'), STUB_SERVER, 'utf-8');
+ process.argv[1] = join(dir, 'packages', 'cli', 'src', 'cli.ts');
+ });
+
+ afterEach(() => {
+ process.argv[1] = originalArgv1;
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ interface RegisteredTool {
+ name: string;
+ label: string;
+ description: string;
+ parameters: Record<string, unknown>;
+ execute: (
+ toolCallId: string,
+ params: Record<string, unknown>,
+ signal: AbortSignal | undefined,
+ ) => Promise<{ content: Array<{ type: string; text: string }>; details?: unknown }>;
+ }
+
+ it('handshakes, registers prefixed tools, forwards calls, maps isError to a throw', async () => {
+ const extensionPath = join(dir, 'open-knowledge.ts');
+ writeFileSync(extensionPath, buildPiExtensionSource({ mode: 'dev' }), 'utf-8');
+
+ const handlers = new Map<string, (event: unknown, ctx: unknown) => unknown>();
+ const tools = new Map<string, RegisteredTool>();
+ const fakePi = {
+ on: (event: string, handler: (event: unknown, ctx: unknown) => unknown) => {
+ handlers.set(event, handler);
+ },
+ registerTool: (definition: Record<string, unknown>) => {
+ const tool = definition as unknown as RegisteredTool;
+ tools.set(tool.name, tool);
+ },
+ };
+
+ const mod = (await import(extensionPath)) as {
+ default: (pi: typeof fakePi) => void;
+ };
+ mod.default(fakePi);
+ expect(handlers.has('session_start')).toBe(true);
+ expect(handlers.has('session_shutdown')).toBe(true);
+ expect(tools.size).toBe(0);
+
+ try {
+ await handlers.get('session_start')?.({}, { cwd: dir });
+
+ expect([...tools.keys()].sort()).toEqual(['ok_boom', 'ok_exec']);
+ const exec = tools.get('ok_exec');
+ expect(exec?.description).toBe('Run a command.');
+ // The MCP inputSchema passes through as plain JSON Schema parameters.
+ expect(exec?.parameters).toEqual({
+ type: 'object',
+ properties: { command: { type: 'string' } },
+ required: ['command'],
+ });
+
+ const result = await exec?.execute('t1', { command: 'ls' }, undefined);
+ expect(result?.content).toEqual([{ type: 'text', text: 'ran: ls' }]);
+ expect(result?.details).toEqual({ echoed: 'ls' });
+
+ // MCP isError results surface as a throw — Pi's error signal.
+ expect(tools.get('ok_boom')?.execute('t2', {}, undefined)).rejects.toThrow('it broke');
+ } finally {
+ await handlers.get('session_shutdown')?.({}, {});
+ }
+ }, 20000);
+});
diff --git a/packages/cli/src/integrations/pi-extension.ts b/packages/cli/src/integrations/pi-extension.ts
new file mode 100644
index 000000000..b3531793e
--- /dev/null
+++ b/packages/cli/src/integrations/pi-extension.ts
@@ -0,0 +1,447 @@
+/**
+ * Pi bridge-extension builder + recognizers.
+ *
+ * Pi (badlogic's `pi` coding agent) has no MCP support and no MCP config
+ * surface at all — its only extension point is a TypeScript extension module
+ * auto-discovered from the project's `.pi/extensions/` dir (loaded after the
+ * user trusts the folder). OK's integration is therefore a whole managed FILE,
+ * not a config entry: `ok init` drops `.pi/extensions/open-knowledge.ts`,
+ * whose runtime spawns OK's MCP stdio server through the same resilient
+ * launcher every other editor's config embeds (`buildManagedServerEntry`),
+ * hand-rolls the newline-delimited JSON-RPC MCP handshake, and registers each
+ * MCP tool as a native Pi tool.
+ *
+ * The generated file must be DEPENDENCY-FREE: Pi loads extensions with jiti
+ * and only guarantees Node builtins plus Pi's own bundled modules — a single
+ * dropped file cannot rely on npm packages (`@modelcontextprotocol/sdk` is not
+ * available). Tool parameter schemas pass through as plain JSON Schema, which
+ * Pi's validator accepts alongside TypeBox schemas.
+ *
+ * Versioning mirrors the chain-entry contract in `commands/editors.ts`:
+ * `PI_EXTENSION_VERSION_SENTINEL` on the FIRST LINE is the up-to-date check
+ * (reclaim's leave-alone gate) and `PI_EXTENSION_OWNERSHIP_MARKER` — its
+ * version-agnostic prefix — is the removal gate. Dev-mode (`--dev-mcp`) files
+ * carry the marker but a `-dev` suffix instead of the version sentinel, so
+ * sweeps migrate them forward to published exactly like dev chain entries,
+ * while removal still recognizes them as OK's own.
+ */
+
+import {
+ buildManagedServerEntry,
+ type McpInstallOptions,
+ PI_EXTENSION_OWNERSHIP_MARKER,
+ PI_EXTENSION_VERSION_SENTINEL,
+ PI_MANAGED_FILE_ENTRY_COMMAND,
+} from '../commands/editors.ts';
+
+/** First line of a dev-mode (`--dev-mcp`) drop: owned, never version-current. */
+const PI_EXTENSION_DEV_HEADER = `${PI_EXTENSION_OWNERSHIP_MARKER}-dev`;
+
+/**
+ * True when raw file text is recognizably OK's own managed Pi extension (any
+ * version, including dev drops) — the gate for whole-file removal. First-line
+ * strict: a user's own file at the same path that merely mentions the marker
+ * somewhere in its body is NOT claimed.
+ */
+export function isOwnPiExtensionSource(text: string): boolean {
+ return text.startsWith(PI_EXTENSION_OWNERSHIP_MARKER);
+}
+
+/**
+ * True when raw file text carries the CURRENT version sentinel on its first
+ * line — the `isEntryUpToDate` equivalent for the managed file. Body drift
+ * below line one is tolerated (same leave-alone posture as the chain-entry
+ * sentinel check); a stale or dev header fails and triggers a rewrite by the
+ * repair/reclaim sweeps.
+ */
+export function isPiExtensionSourceUpToDate(text: string): boolean {
+ return text.startsWith(PI_EXTENSION_VERSION_SENTINEL);
+}
+
+/**
+ * `isOwnPiExtensionSource` lifted to the synthetic-entry shape — the removal
+ * gate consumed by `isRemovableOwnEntry` in `mcp-config-removal.ts`.
+ */
+export function isOwnPiManagedFileEntry(entry: unknown): boolean {
+ if (typeof entry !== 'object' || entry === null) return false;
+ const e = entry as Record<string, unknown>;
+ if (e.command !== PI_MANAGED_FILE_ENTRY_COMMAND || !Array.isArray(e.args)) return false;
+ const text = e.args[0];
+ return typeof text === 'string' && isOwnPiExtensionSource(text);
+}
+
+/**
+ * Wrap raw managed-file text in the synthetic entry shape the shared
+ * classify → `isEntryUpToDate` → rewrite/remove machinery consumes.
+ * `classifyExistingMcpEntry` synthesizes this for `format: 'file'` targets so
+ * every generic consumer (CLI repair sweep, desktop boot + project-open
+ * reclaim, surgical removal) flows without per-host branches. `args[0]` is the
+ * raw text; telemetry consumers already bound it via `truncatePriorEntry`.
+ */
+export function makePiManagedFileEntry(text: string): Record<string, unknown> {
+ return { command: PI_MANAGED_FILE_ENTRY_COMMAND, args: [text] };
+}
+
+/**
+ * Build the full contents of `.pi/extensions/open-knowledge.ts`.
+ *
+ * Byte-deterministic for a given `options` value, so idempotent `ok init`
+ * re-runs skip the write on content equality. Published mode embeds BOTH
+ * platforms' launcher shapes and picks by `process.platform` at runtime —
+ * unlike a static JSON config entry, the dropped file is a program, so one
+ * committed artifact serves macOS/Linux and Windows teammates alike. Dev mode
+ * (`--dev-mcp`) embeds the machine-local `node dist/cli.mjs mcp` launcher on
+ * both slots.
+ *
+ * The generated source avoids template literals and backticks entirely so the
+ * template below never needs escaping gymnastics; launcher shapes are injected
+ * as JSON (valid JS expressions by construction).
+ */
+export function buildPiExtensionSource(options: McpInstallOptions = {}): string {
+ const dev = options.mode === 'dev';
+ const header = dev ? PI_EXTENSION_DEV_HEADER : PI_EXTENSION_VERSION_SENTINEL;
+ const launchers = {
+ unix: buildManagedServerEntry({ ...options, platformName: 'darwin' }),
+ win32: buildManagedServerEntry({ ...options, platformName: 'win32' }),
+ };
+ return `${header}
+/**
+ * Open Knowledge bridge for Pi — MANAGED FILE, written by \`ok init\`.
+ * Hand edits are overwritten whenever OK re-syncs this project; remove it
+ * with \`ok deinit\` (or delete the file) to disconnect Pi from OK.
+ *
+ * On session start it spawns Open Knowledge's MCP stdio server via OK's
+ * resilient launcher (bundle, then npx, then version-manager probes), performs
+ * the MCP handshake, and registers each MCP tool as a Pi tool under an
+ * \`ok_\` prefix (Pi has no MCP namespacing; the prefix keeps OK's \`edit\` /
+ * \`write\` from shadowing Pi's built-in tools).
+ */
+import { spawn } from "node:child_process";
+import type { ChildProcessWithoutNullStreams } from "node:child_process";
+
+const LAUNCHERS = ${JSON.stringify(launchers, null, 2)} as const;
+
+const TOOL_PREFIX = "ok_";
+// First contact may cold-install the CLI through npx — allow a generous window.
+const INIT_TIMEOUT_MS = 120000;
+const STDERR_TAIL_LIMIT = 2000;
+
+interface McpContentItem {
+ type: string;
+ text?: string;
+}
+
+interface McpToolInfo {
+ name: string;
+ description?: string;
+ inputSchema?: Record<string, unknown>;
+}
+
+interface PendingRequest {
+ resolve: (value: Record<string, unknown>) => void;
+ reject: (err: Error) => void;
+}
+
+class OkMcpClient {
+ private child: ChildProcessWithoutNullStreams;
+ private pending = new Map<number, PendingRequest>();
+ private nextId = 1;
+ private buffer = "";
+ private stderrTail = "";
+ alive = true;
+
+ constructor(cwd: string, onExit: () => void) {
+ const launcher = process.platform === "win32" ? LAUNCHERS.win32 : LAUNCHERS.unix;
+ const env: Record<string, string | undefined> = { ...process.env };
+ const launcherEnv = (launcher as { env?: Record<string, string> }).env;
+ if (launcherEnv) Object.assign(env, launcherEnv);
+ this.child = spawn(launcher.command, [...launcher.args], {
+ cwd,
+ env,
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ this.child.stdout.setEncoding("utf8");
+ this.child.stdout.on("data", (chunk: string) => this.onStdout(chunk));
+ this.child.stderr.setEncoding("utf8");
+ this.child.stderr.on("data", (chunk: string) => {
+ this.stderrTail = (this.stderrTail + chunk).slice(-STDERR_TAIL_LIMIT);
+ });
+ // A write buffered before the pipe breaks surfaces as an 'error' on stdin
+ // (not on the child); unhandled it would crash Pi's extension host.
+ // Swallow it — the exit handler owns teardown.
+ this.child.stdin.on("error", () => {});
+ const fail = () => {
+ if (!this.alive) return;
+ this.alive = false;
+ const err = new Error(
+ "Open Knowledge MCP server exited" +
+ (this.stderrTail ? ": " + this.stderrTail.trim() : ""),
+ );
+ for (const p of this.pending.values()) p.reject(err);
+ this.pending.clear();
+ onExit();
+ };
+ this.child.on("exit", fail);
+ this.child.on("error", fail);
+ }
+
+ private onStdout(chunk: string): void {
+ this.buffer += chunk;
+ let newline = this.buffer.indexOf("\\n");
+ while (newline !== -1) {
+ const line = this.buffer.slice(0, newline).trim();
+ this.buffer = this.buffer.slice(newline + 1);
+ if (line.startsWith("{")) {
+ try {
+ this.onMessage(JSON.parse(line) as Record<string, unknown>);
+ } catch {
+ // Non-JSON noise on stdout is ignored; framing recovers on the next line.
+ }
+ }
+ newline = this.buffer.indexOf("\\n");
+ }
+ }
+
+ private onMessage(msg: Record<string, unknown>): void {
+ const id = msg.id;
+ if (typeof msg.method === "string") {
+ // Server-initiated request (e.g. roots/list). This bridge declares no
+ // client capabilities, so decline rather than leave the server hanging.
+ if (id !== undefined && id !== null) {
+ this.send({
+ jsonrpc: "2.0",
+ id,
+ error: { code: -32601, message: "Method not supported by the OK Pi bridge" },
+ });
+ }
+ return;
+ }
+ if (typeof id !== "number") return;
+ const pending = this.pending.get(id);
+ if (!pending) return;
+ this.pending.delete(id);
+ const error = msg.error as { message?: string } | undefined;
+ if (error) {
+ pending.reject(new Error(error.message || "Open Knowledge MCP error"));
+ return;
+ }
+ pending.resolve((msg.result ?? {}) as Record<string, unknown>);
+ }
+
+ private send(msg: Record<string, unknown>): void {
+ // Buffered stdout can still dispatch onMessage replies after close() ends
+ // stdin; writing then would raise ERR_STREAM_WRITE_AFTER_END unhandled.
+ if (!this.alive) return;
+ this.child.stdin.write(JSON.stringify(msg) + "\\n");
+ }
+
+ request(
+ method: string,
+ params: Record<string, unknown>,
+ opts: { timeoutMs?: number; signal?: AbortSignal } = {},
+ ): Promise<Record<string, unknown>> {
+ if (!this.alive) return Promise.reject(new Error("Open Knowledge MCP server is not running"));
+ const id = this.nextId++;
+ return new Promise<Record<string, unknown>>((resolve, reject) => {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let onAbort: (() => void) | undefined;
+ const cleanup = () => {
+ if (timer !== undefined) clearTimeout(timer);
+ if (onAbort && opts.signal) opts.signal.removeEventListener("abort", onAbort);
+ this.pending.delete(id);
+ };
+ const done: PendingRequest = {
+ resolve: (value) => {
+ cleanup();
+ resolve(value);
+ },
+ reject: (err) => {
+ cleanup();
+ reject(err);
+ },
+ };
+ this.pending.set(id, done);
+ if (opts.timeoutMs) {
+ timer = setTimeout(() => {
+ done.reject(new Error(method + " timed out after " + opts.timeoutMs + "ms"));
+ }, opts.timeoutMs);
+ }
+ if (opts.signal) {
+ onAbort = () => {
+ this.notify("notifications/cancelled", { requestId: id, reason: "aborted" });
+ done.reject(new Error("Cancelled"));
+ };
+ if (opts.signal.aborted) {
+ onAbort();
+ return;
+ }
+ opts.signal.addEventListener("abort", onAbort, { once: true });
+ }
+ this.send({ jsonrpc: "2.0", id, method, params });
+ });
+ }
+
+ notify(method: string, params: Record<string, unknown>): void {
+ if (!this.alive) return;
+ this.send({ jsonrpc: "2.0", method, params });
+ }
+
+ close(): void {
+ this.alive = false;
+ for (const p of this.pending.values()) {
+ p.reject(new Error("Open Knowledge MCP client closed"));
+ }
+ this.pending.clear();
+ // ok mcp exits on stdin EOF; the delayed kill is a backstop.
+ try {
+ this.child.stdin.end();
+ } catch {
+ // Already gone.
+ }
+ const child = this.child;
+ setTimeout(() => {
+ try {
+ child.kill();
+ } catch {
+ // Already gone.
+ }
+ }, 2000).unref();
+ }
+}
+
+/** JSON Schema pass-through: Pi validates plain JSON Schema parameters. */
+function toParameters(inputSchema: Record<string, unknown> | undefined): Record<string, unknown> {
+ if (!inputSchema || typeof inputSchema !== "object") {
+ return { type: "object", properties: {} };
+ }
+ const schema = { ...inputSchema };
+ delete schema.$schema;
+ return schema;
+}
+
+function contentText(content: unknown): string {
+ if (!Array.isArray(content)) return "";
+ return (content as McpContentItem[])
+ .filter((item) => item && item.type === "text" && typeof item.text === "string")
+ .map((item) => item.text as string)
+ .join("\\n");
+}
+
+export default function okBridge(pi: {
+ on(event: string, handler: (event: unknown, ctx: unknown) => unknown): void;
+ registerTool(definition: Record<string, unknown>): void;
+}) {
+ let client: OkMcpClient | null = null;
+ let starting: Promise<OkMcpClient> | null = null;
+ let sessionCwd = process.cwd();
+ const registeredTools = new Set<string>();
+
+ async function ensureClient(): Promise<OkMcpClient> {
+ if (client && client.alive) return client;
+ if (starting) return starting;
+ starting = (async () => {
+ const next = new OkMcpClient(sessionCwd, () => {
+ if (client === next) client = null;
+ });
+ try {
+ await next.request(
+ "initialize",
+ {
+ protocolVersion: "2025-06-18",
+ capabilities: {},
+ clientInfo: { name: "pi", version: "1.0.0" },
+ },
+ { timeoutMs: INIT_TIMEOUT_MS },
+ );
+ } catch (err) {
+ // A timed-out initialize rejects the request while the child may
+ // still be running; tear it down so retries don't stack orphans.
+ next.close();
+ throw err;
+ }
+ next.notify("notifications/initialized", {});
+ client = next;
+ return next;
+ })();
+ try {
+ return await starting;
+ } finally {
+ starting = null;
+ }
+ }
+
+ async function registerOkTools(): Promise<number> {
+ const mcp = await ensureClient();
+ const listed = await mcp.request("tools/list", {}, { timeoutMs: INIT_TIMEOUT_MS });
+ const tools = Array.isArray(listed.tools) ? (listed.tools as McpToolInfo[]) : [];
+ for (const tool of tools) {
+ const name = TOOL_PREFIX + tool.name;
+ if (registeredTools.has(name)) continue;
+ registeredTools.add(name);
+ pi.registerTool({
+ name,
+ label: "OK " + tool.name,
+ description: tool.description || "Open Knowledge " + tool.name + " tool.",
+ parameters: toParameters(tool.inputSchema),
+ execute: async (
+ _toolCallId: string,
+ params: Record<string, unknown>,
+ signal: AbortSignal | undefined,
+ ) => {
+ const live = await ensureClient();
+ const result = await live.request(
+ "tools/call",
+ { name: tool.name, arguments: params ?? {} },
+ { signal },
+ );
+ const text = contentText(result.content);
+ if (result.isError) {
+ throw new Error(text || "Open Knowledge tool " + tool.name + " failed");
+ }
+ return {
+ content: [{ type: "text", text }],
+ details: result.structuredContent,
+ };
+ },
+ });
+ }
+ return tools.length;
+ }
+
+ pi.on("session_start", async (_event, ctx) => {
+ const cwd = (ctx as { cwd?: string } | undefined)?.cwd;
+ if (typeof cwd === "string" && cwd.length > 0) sessionCwd = cwd;
+ try {
+ await registerOkTools();
+ } catch (err) {
+ const ui = (ctx as { ui?: { notify?: (m: string, level: string) => void } } | undefined)?.ui;
+ try {
+ ui?.notify?.(
+ "Open Knowledge tools unavailable: " + (err instanceof Error ? err.message : String(err)),
+ "warning",
+ );
+ } catch {
+ // Non-interactive mode; the failure will resurface on first tool use.
+ }
+ }
+ });
+
+ pi.on("session_shutdown", async () => {
+ const pending = starting;
+ starting = null;
+ const current = client;
+ client = null;
+ current?.close();
+ // An in-flight ensureClient would otherwise assign a live client after
+ // shutdown; await it and tear that one down too.
+ if (pending) {
+ try {
+ (await pending).close();
+ } catch {
+ // Initialization failed — its catch path already closed the client.
+ }
+ }
+ });
+}
+`;
+}
diff --git a/packages/cli/src/sharing/git-exclude.test.ts b/packages/cli/src/sharing/git-exclude.test.ts
index fedd9cfc2..70d12b605 100644
--- a/packages/cli/src/sharing/git-exclude.test.ts
+++ b/packages/cli/src/sharing/git-exclude.test.ts
@@ -48,7 +48,7 @@ describe('getOkArtifactPaths', () => {
rmSync(dir, { recursive: true, force: true });
});
- it('returns the canonical eleven-path artifact set when no config.yml exists', () => {
+ it('returns the canonical thirteen-path artifact set when no config.yml exists', () => {
const paths = getOkArtifactPaths(dir);
expect(paths).toContain(`${OK_DIR}/`);
expect(paths).toContain('.okignore');
@@ -63,8 +63,12 @@ describe('getOkArtifactPaths', () => {
// not a shared `.agents/skills/` write), so it adds a distinct skill path on
// top of its `opencode.json` config.
expect(paths).toContain('.opencode/skills/open-knowledge/');
+ // Pi has no MCP config — its project artifact is the managed bridge
+ // extension, plus its own `.pi/skills/` primary dir.
+ expect(paths).toContain('.pi/extensions/open-knowledge.ts');
+ expect(paths).toContain('.pi/skills/open-knowledge/');
expect(paths).toContain('.claude/launch.json');
- expect(paths).toHaveLength(11);
+ expect(paths).toHaveLength(13);
});
it('preserves a stable order so `ok config-sharing status` and unit-test snapshots are deterministic', () => {
@@ -87,9 +91,9 @@ describe('getOkArtifactPaths', () => {
expect(paths).not.toContain('docs/.ok/');
expect(paths).not.toContain('docs/.okignore');
expect(paths.some((p) => p.includes('**'))).toBe(false);
- // content.dir must not inflate the set — same eleven paths as the no-config
- // case, just never `<contentDir>`-prefixed.
- expect(paths).toHaveLength(11);
+ // content.dir must not inflate the set — same thirteen paths as the
+ // no-config case, just never `<contentDir>`-prefixed.
+ expect(paths).toHaveLength(13);
});
it('excludes each installed skill projection per the OF3 marker (PRD-6934 C9 fix)', () => {
@@ -133,7 +137,7 @@ describe('getOkArtifactPaths', () => {
mkdirSync(join(dir, OK_DIR, 'local'), { recursive: true });
writeFileSync(join(dir, OK_DIR, 'local', 'installed-skills.json'), '{ corrupt', 'utf-8');
const paths = getOkArtifactPaths(dir);
- expect(paths).toHaveLength(11); // corrupt marker → fail-soft, no per-skill paths
+ expect(paths).toHaveLength(13); // corrupt marker → fail-soft, no per-skill paths
});
});
diff --git a/packages/core/src/constants/editors.ts b/packages/core/src/constants/editors.ts
index 72ba11d85..ced14e976 100644
--- a/packages/core/src/constants/editors.ts
+++ b/packages/core/src/constants/editors.ts
@@ -6,7 +6,14 @@
* resolution lives in `packages/cli/src/commands/editors.ts:EDITOR_TARGETS`,
* which now reads labels from this module to avoid drift.
*/
-export type EditorId = 'claude' | 'claude-desktop' | 'cursor' | 'codex' | 'opencode' | 'openclaw';
+export type EditorId =
+ | 'claude'
+ | 'claude-desktop'
+ | 'cursor'
+ | 'codex'
+ | 'opencode'
+ | 'openclaw'
+ | 'pi';
export const ALL_EDITOR_IDS = [
'claude',
@@ -15,6 +22,7 @@ export const ALL_EDITOR_IDS = [
'codex',
'opencode',
'openclaw',
+ 'pi',
] as const satisfies readonly EditorId[];
/**
@@ -30,6 +38,7 @@ export const EDITOR_LABELS = {
codex: 'Codex',
opencode: 'OpenCode',
openclaw: 'OpenClaw',
+ pi: 'Pi',
} as const satisfies Record<EditorId, string>;
/**
@@ -80,6 +89,12 @@ export const EDITOR_PROJECT_SKILL_ROOT = {
// OpenClaw is a global agent gateway (config + skills live under the user's
// home, e.g. `~/.agents/skills`); it has no project-scoped skill dir OK writes.
openclaw: null,
+ // Pi implements the Agent Skills standard and scans `.pi/skills` natively
+ // (alongside `.agents/skills`); OK writes its own primary dir so
+ // install-on-Pi is honest and never shares another host's write. Project
+ // skill dirs are trust-gated in Pi: they load only after the user trusts
+ // the folder.
+ pi: '.pi/skills',
} as const satisfies Record<EditorId, string | null>;
/** Editor ids that have a project skill surface (valid install-projection targets). */
@@ -96,11 +111,18 @@ export const PROJECT_SKILL_EDITOR_IDS = ALL_EDITOR_IDS.filter(
* `.claude` from `.claude/skills`) and the id set can never drift from the
* canonical editor constants. Adding a project-skill editor to
* `EDITOR_PROJECT_SKILL_ROOT` flows here automatically.
+ *
+ * Pi is the one carve-out: its user-global skills dir is `~/.pi/agent/skills`
+ * (the agent home is nested one level below the `.pi` dotdir), NOT the
+ * `~/<hostDir>/skills` layout this derivation assumes — and Pi natively reads
+ * the central `~/.agents/skills` hub, which the user-bundle installer already
+ * writes. Including it here would create a dead `~/.pi/skills/` dir nothing
+ * reads.
*/
export const HOSTS_WITH_USER_SKILL_DIR: ReadonlyArray<{
readonly hostDir: string;
readonly editorId: EditorId;
-}> = PROJECT_SKILL_EDITOR_IDS.map((editorId) => ({
+}> = PROJECT_SKILL_EDITOR_IDS.filter((editorId) => editorId !== 'pi').map((editorId) => ({
// `editorId` came from the non-null filter, so the root is a string.
hostDir: (EDITOR_PROJECT_SKILL_ROOT[editorId] ?? '').split('/')[0],
editorId,
@@ -119,6 +141,7 @@ export const EDITOR_SETUP_DOC_SLUG = {
codex: 'codex',
opencode: 'opencode',
openclaw: 'openclaw',
+ pi: 'pi',
} as const satisfies Record<EditorId, string>;
/**
@@ -138,4 +161,11 @@ export const EDITOR_PROJECT_CONFIG_PATH = {
// OpenClaw's MCP config is user-global (`~/.openclaw/openclaw.json`); no
// project-local variant, so it is never detected as "project-configured".
openclaw: null,
+ // Pi has no MCP config at all — OK's integration is a managed bridge
+ // EXTENSION file dropped at `.pi/extensions/open-knowledge.ts` (Pi loads
+ // project extensions after the user trusts the folder). That file is the
+ // project-configured signal AND the artifact every generic consumer
+ // (sharing-mode exclude, deinit, reclaim) must target, so it is the
+ // project-config path. OK never reads or writes `.pi/settings.json`.
+ pi: '.pi/extensions/open-knowledge.ts',
} as const satisfies Record<EditorId, string | null>;
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index a9b7ea6fa..2fa7bac00 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -448,6 +448,9 @@ interface OkOnboardingShowPayload {
readonly id: OkMcpWiringEditorId;
readonly label: string;
readonly hasProjectConfig: boolean;
+ /** Optional for back-compat; absent reads as `true`. `false` = the editor
+ * has no user-global config surface (Pi — project-scope only). */
+ readonly hasUserConfig?: boolean;
}[];
}
diff --git a/packages/core/src/handoff/terminal-launch.test.ts b/packages/core/src/handoff/terminal-launch.test.ts
index 34a64250e..1099f5533 100644
--- a/packages/core/src/handoff/terminal-launch.test.ts
+++ b/packages/core/src/handoff/terminal-launch.test.ts
@@ -15,10 +15,10 @@ import {
const CLAUDE_PREAPPROVE = `--settings '{"enabledMcpjsonServers":["${MCP_SERVER_NAME}"]}'`;
describe('TERMINAL_CLI_IDS', () => {
- it('lists the CLIs in auto-pick priority order (claude > codex > opencode > cursor)', () => {
+ it('lists the CLIs in auto-pick priority order (claude > codex > opencode > cursor > pi)', () => {
// The single constant drives both the visible launch-row order and the
// default-CLI auto-pick, so display and defaulting can never disagree.
- expect([...TERMINAL_CLI_IDS]).toEqual(['claude', 'codex', 'opencode', 'cursor']);
+ expect([...TERMINAL_CLI_IDS]).toEqual(['claude', 'codex', 'opencode', 'cursor', 'pi']);
});
});
@@ -114,6 +114,8 @@ describe('buildCliLaunchCommand', () => {
expect(buildCliLaunchCommand('cursor', 'hi')).toBe("cursor-agent 'hi'\r");
// OpenCode's positional is the project dir, so the prompt rides on --prompt.
expect(buildCliLaunchCommand('opencode', 'hi')).toBe("opencode --prompt 'hi'\r");
+ // Pi's positional IS the prompt — same shape as claude/codex/cursor.
+ expect(buildCliLaunchCommand('pi', 'hi')).toBe("pi 'hi'\r");
});
it('escapes the prompt identically for every CLI regardless of fixed args', () => {
diff --git a/packages/core/src/handoff/terminal-launch.ts b/packages/core/src/handoff/terminal-launch.ts
index de830f496..0f8e5b7ac 100644
--- a/packages/core/src/handoff/terminal-launch.ts
+++ b/packages/core/src/handoff/terminal-launch.ts
@@ -44,7 +44,7 @@ export function shellSingleQuote(s: string): string {
* one-shot variants: `codex exec` and `cursor-agent -p` both run-and-exit, so
* the session wouldn't stay open for the user to continue in).
*/
-export type TerminalCli = 'claude' | 'codex' | 'cursor' | 'opencode';
+export type TerminalCli = 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi';
export interface TerminalCliInfo {
/** PATH binary launched in the PTY. Interpolated (alongside any opted-in
@@ -135,6 +135,16 @@ export const TERMINAL_CLIS = {
handoffTarget: 'opencode',
promptFlag: '--prompt',
},
+ pi: {
+ // Pi's positional argument IS the starting prompt (`pi '<prompt>'` opens
+ // the interactive session with it), the same shape as claude/codex/cursor
+ // — no promptFlag. (`pi -p` is the non-interactive one-shot; the default
+ // interactive command keeps the session open, matching the other CLIs.)
+ bin: 'pi',
+ displayName: 'Pi',
+ docsUrl: 'https://pi.dev',
+ handoffTarget: 'pi',
+ },
} as const satisfies Record<TerminalCli, TerminalCliInfo>;
/**
@@ -147,6 +157,7 @@ export const TERMINAL_CLI_IDS = [
'codex',
'opencode',
'cursor',
+ 'pi',
] as const satisfies readonly TerminalCli[];
export interface BuildCliLaunchOptions {
diff --git a/packages/core/src/handoff/types.ts b/packages/core/src/handoff/types.ts
index 4955fe827..7ca747175 100644
--- a/packages/core/src/handoff/types.ts
+++ b/packages/core/src/handoff/types.ts
@@ -3,13 +3,20 @@
* pure type surface consumable from Electron main, renderer, and server.
*/
-// `opencode` is a TERMINAL-ONLY target: it has no URL scheme / GUI app, so it
-// is carved out of the deep-link dispatch path (no `RECIPES` recipe, no
-// `dispatch.ts` URL case, excluded from `VISIBLE_TARGETS`). It is a member of
-// the union only so it can reuse the shared brand-icon + display-name metadata
-// that the terminal-CLI launch rows render. Reached exclusively via
-// `requestTerminalLaunch` / `TERMINAL_CLIS`, never `dispatchHandoff`.
-export type HandoffTarget = 'claude-cowork' | 'claude-code' | 'codex' | 'cursor' | 'opencode';
+// `opencode` and `pi` are TERMINAL-ONLY targets: they have no URL scheme /
+// GUI app, so they are carved out of the deep-link dispatch path (no `RECIPES`
+// recipe, no `dispatch.ts` URL case, excluded from `VISIBLE_TARGETS`). They
+// are members of the union only so they can reuse the shared brand-icon +
+// display-name metadata that the terminal-CLI launch rows render. Reached
+// exclusively via `requestTerminalLaunch` / `TERMINAL_CLIS`, never
+// `dispatchHandoff`.
+export type HandoffTarget =
+ | 'claude-cowork'
+ | 'claude-code'
+ | 'codex'
+ | 'cursor'
+ | 'opencode'
+ | 'pi';
/**
* Data carried from the UI to the URL builder. Minimal by construction: only
diff --git a/packages/core/src/skill-targets/editor-single-source.test.ts b/packages/core/src/skill-targets/editor-single-source.test.ts
index e402df42d..66f6e4147 100644
--- a/packages/core/src/skill-targets/editor-single-source.test.ts
+++ b/packages/core/src/skill-targets/editor-single-source.test.ts
@@ -39,10 +39,13 @@ describe('project-skill editor-id single source', () => {
});
test('HOSTS_WITH_USER_SKILL_DIR derives from the same editors (CLI repair-skills ↔ desktop skill-reclaim share it)', () => {
- // Single source for the host-dir sweep both the CLI and desktop run. editorId
- // set === PROJECT_SKILL_EDITOR_IDS; hostDir === the root's top-level dotdir.
+ // Single source for the host-dir sweep both the CLI and desktop run.
+ // editorId set === PROJECT_SKILL_EDITOR_IDS minus the documented Pi
+ // carve-out (Pi's user-global skills dir is `~/.pi/agent/skills`, not the
+ // `~/<hostDir>/skills` layout this sweep assumes, and Pi reads the central
+ // `~/.agents/skills` hub natively); hostDir === the root's top-level dotdir.
expect(asStrings(HOSTS_WITH_USER_SKILL_DIR.map((h) => h.editorId))).toEqual(
- asStrings(PROJECT_SKILL_EDITOR_IDS),
+ asStrings(PROJECT_SKILL_EDITOR_IDS.filter((id) => id !== 'pi')),
);
for (const { hostDir, editorId } of HOSTS_WITH_USER_SKILL_DIR) {
expect(hostDir).toBe((EDITOR_PROJECT_SKILL_ROOT[editorId] ?? '').split('/')[0]);
@@ -50,6 +53,16 @@ describe('project-skill editor-id single source', () => {
}
});
+ test('Pi IS a project-skill install target but NOT a user-global host-dir sweep member', () => {
+ // Pi scans project `.pi/skills` natively (trust-gated), so it belongs in
+ // the install-projection enum; its user-global layout (`~/.pi/agent/skills`
+ // + the central `~/.agents/skills` hub) has no `~/.pi/skills`, so the
+ // user-bundle sweep must not fabricate one.
+ expect(SkillTargetEditorSchema.options).toContain('pi');
+ expect(HOSTS_WITH_USER_SKILL_DIR.map((h) => h.editorId)).not.toContain('pi');
+ expect(HOSTS_WITH_USER_SKILL_DIR.map((h) => h.hostDir)).not.toContain('.pi');
+ });
+
test('Claude Desktop is NOT a project-skill install target (user-global only, null root)', () => {
// Regression: the install menu / picker must not offer claude-desktop —
// it has no project skill surface (reads user-global skills only).
diff --git a/packages/core/src/skill-targets/schema.ts b/packages/core/src/skill-targets/schema.ts
index 3cb732670..bd612fdc0 100644
--- a/packages/core/src/skill-targets/schema.ts
+++ b/packages/core/src/skill-targets/schema.ts
@@ -14,8 +14,8 @@
* absent, OK falls back to the editors the project is already configured for.
*
* Only editors with a project skill surface are valid targets
- * (`claude` / `cursor` / `codex` / `opencode`; Claude Desktop and OpenClaw
- * read user-global skills only).
+ * (`claude` / `cursor` / `codex` / `opencode` / `pi`; Claude Desktop and
+ * OpenClaw read user-global skills only).
*/
import { z } from 'zod';
@@ -35,13 +35,13 @@ export const SKILL_TARGETS_SCHEMA_VERSION = 1;
* Editor ids valid as install-projection targets. Runtime values come from the
* single source `PROJECT_SKILL_EDITOR_IDS` (derived from `EDITOR_PROJECT_SKILL_ROOT`)
* so the two can't drift. z.enum needs a literal tuple, which the derived array's
- * `.filter` widens to `EditorId`, so the cast restates a narrower literal shape:
- * `Exclude<EditorId, 'claude-desktop'>` still admits `openclaw` (also without a
- * project skill surface), so the type over-approximates the runtime set
- * (`claude` / `cursor` / `codex` / `opencode`); schema.test.ts asserts the cast
- * stays value-equal to the derived list as a backstop.
+ * `.filter` widens to `EditorId`, so the cast restates the narrow literal shape:
+ * `Exclude<EditorId, 'claude-desktop' | 'openclaw'>` is exactly the set of
+ * editors WITH a project skill surface (`claude` / `cursor` / `codex` /
+ * `opencode` / `pi`). schema.test.ts asserts the cast stays value-equal to the
+ * derived list as a backstop.
*/
-type ProjectSkillEditorId = Exclude<EditorId, 'claude-desktop'>;
+type ProjectSkillEditorId = Exclude<EditorId, 'claude-desktop' | 'openclaw'>;
export const SkillTargetEditorSchema = z.enum(
// Double cast (through `unknown`): the derived array is typed `EditorId[]`,
// which TS won't directly narrow to the literal tuple z.enum needs. Runtime
diff --git a/packages/desktop/src/main/create-new-project.test.ts b/packages/desktop/src/main/create-new-project.test.ts
index da210dda8..128ff05b8 100644
--- a/packages/desktop/src/main/create-new-project.test.ts
+++ b/packages/desktop/src/main/create-new-project.test.ts
@@ -570,6 +570,9 @@ describe('runCreateNew — installs the project-local skill (PRD-6733)', () => {
expect(
existsSync(join(result.projectDir, '.opencode', 'skills', 'open-knowledge', 'SKILL.md')),
).toBe(true);
+ expect(existsSync(join(result.projectDir, '.pi', 'skills', 'open-knowledge', 'SKILL.md'))).toBe(
+ true,
+ );
// The result's `aiIntegrations` carries the per-(editor × integration)
// outcomes — the project-skill writer ran and reported success for every
@@ -582,6 +585,7 @@ describe('runCreateNew — installs the project-local skill (PRD-6733)', () => {
'codex',
'cursor',
'opencode',
+ 'pi',
]);
});
});
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 7d73b5b89..25fc204fa 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -1556,6 +1556,9 @@ async function openProject(
id: id as McpWiringEditorId,
label: EDITOR_TARGETS[id].label,
hasProjectConfig: EDITOR_TARGETS[id].projectConfigPath !== undefined,
+ // Pi is the first project-scope-only editor; without the user-side
+ // signal the badge would misread as "(project + user)".
+ hasUserConfig: EDITOR_TARGETS[id].scope === 'global',
})),
};
const decision = await requestUserConsent(
diff --git a/packages/desktop/src/main/mcp-wiring.ts b/packages/desktop/src/main/mcp-wiring.ts
index 4f44e58aa..2d45ab03f 100644
--- a/packages/desktop/src/main/mcp-wiring.ts
+++ b/packages/desktop/src/main/mcp-wiring.ts
@@ -473,7 +473,12 @@ export function checkAndRepairMcpWiringOnStartup(
if (!/\.app\/Contents\/MacOS\/[^/]+$/.test(executablePath)) {
return Promise.resolve({ status: 'skipped', reason: 'bad-executable-path' });
}
- const selectedEditors = [...cli.allEditorIds];
+ // User-scope sweep: only editors with a user-global config surface.
+ // `scope: 'project'` targets (Pi) have nothing at user scope — their
+ // `configPath` throws by contract.
+ const selectedEditors = cli.allEditorIds.filter(
+ (id) => cli.editorTargets[id]?.scope === 'global',
+ );
logger.event({ event: 'mcp-wiring-repair-check-started', editors: selectedEditors });
if (selectedEditors.length === 0) return Promise.resolve({ status: 'ok', checkedEditors: [] });
@@ -694,7 +699,15 @@ export function runMcpWiringOnFirstLaunch(opts: RunMcpWiringFirstLaunchOpts): Ru
let detections: McpWiringEditorDetection[];
try {
const detectedIds = new Set<McpWiringEditorId>(cli.detectInstalledEditors('', home));
- detections = cli.allEditorIds.map((id) => {
+ // This dialog consents USER-GLOBAL config writes; `scope: 'project'`
+ // targets (Pi) have no user-global surface (`configPath` throws), so a
+ // row for them could only ever produce a guaranteed-failed write — which
+ // defers the status marker and re-fires the dialog every launch. Their
+ // integration is written by the project-scope flows instead.
+ const globalScopeIds = cli.allEditorIds.filter(
+ (id) => cli.editorTargets[id]?.scope === 'global',
+ );
+ detections = globalScopeIds.map((id) => {
const target = cli.editorTargets[id];
if (!target) {
throw new Error(`editorTargets missing entry for id=${id}`);
diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.ts
index a4c29f1ba..10b975aa9 100644
--- a/packages/desktop/src/shared/ipc-channels.ts
+++ b/packages/desktop/src/shared/ipc-channels.ts
@@ -301,6 +301,11 @@ export interface OnboardingShowPayload {
* in the consent dialog so the user can distinguish project-scoped vs
* user-only editors before clicking Start. */
readonly hasProjectConfig: boolean;
+ /** True when this editor also has a user-global config surface. Optional
+ * for back-compat with older payload producers; absent reads as `true`
+ * (every pre-Pi editor was user-writable). Pi is the first
+ * project-scope-only editor — `false` renders "(project-level only)". */
+ readonly hasUserConfig?: boolean;
}[];
}
diff --git a/packages/desktop/tests/integration/m1-smoke.test.ts b/packages/desktop/tests/integration/m1-smoke.test.ts
index a194664d2..72753b075 100644
--- a/packages/desktop/tests/integration/m1-smoke.test.ts
+++ b/packages/desktop/tests/integration/m1-smoke.test.ts
@@ -400,7 +400,7 @@ describe('M1 smoke', () => {
typeName: 'EditorId',
canonicalPath: editorsConstantPath,
canonicalRe: /type\s+EditorId\s*=([^;]+);/,
- expectedLiteralCount: 6,
+ expectedLiteralCount: 7,
inlineRe:
/'claude'\s*\|\s*'claude-desktop'\s*\|\s*'cursor'\s*\|\s*'codex'\s*\|\s*'opencode'\s*\|\s*'openclaw'/,
mirrors: [
diff --git a/packages/desktop/tests/main/claude-readiness.test.ts b/packages/desktop/tests/main/claude-readiness.test.ts
index 24e571099..6c6a874ce 100644
--- a/packages/desktop/tests/main/claude-readiness.test.ts
+++ b/packages/desktop/tests/main/claude-readiness.test.ts
@@ -289,12 +289,14 @@ describe('resolveCliInstalledMap', () => {
codex: 127,
opencode: null,
cursor: 0,
+ pi: 127,
};
expect(await resolveCliInstalledMap({ probe: (cli) => Promise.resolve(codes[cli]) })).toEqual({
claude: true,
codex: false,
opencode: false,
cursor: true,
+ pi: false,
});
});
@@ -302,7 +304,7 @@ describe('resolveCliInstalledMap', () => {
const map = await resolveCliInstalledMap({
probe: (cli) => (cli === 'codex' ? Promise.reject(new Error('boom')) : Promise.resolve(0)),
});
- expect(map).toEqual({ claude: true, codex: false, opencode: true, cursor: true });
+ expect(map).toEqual({ claude: true, codex: false, opencode: true, cursor: true, pi: true });
});
test('returns exactly one entry per CLI in TERMINAL_CLI_IDS', async () => {
diff --git a/packages/desktop/tests/smoke/_helpers/navigator-actions.ts b/packages/desktop/tests/smoke/_helpers/navigator-actions.ts
new file mode 100644
index 000000000..54d0be416
--- /dev/null
+++ b/packages/desktop/tests/smoke/_helpers/navigator-actions.ts
@@ -0,0 +1,25 @@
+import type { Page } from '@playwright/test';
+
+/**
+ * Navigator entry-point clicks that work in both launcher states: a fresh
+ * profile (no recent projects) renders the packs-forward first-run launcher,
+ * whose secondary-row buttons wire to the same handlers as the returning-user
+ * three-card grid (nav-first-run-blank → onCreate, nav-first-run-open →
+ * onOpenFolder; see NavigatorApp.tsx). Smoke tests launch with a fresh tmp
+ * home, so they land on the first-run view; specs that reopen the Navigator
+ * after a project exists get the three-card grid. The two views are mutually
+ * exclusive, so the .or() locator resolves to exactly one element.
+ */
+export async function clickNavCreateNew(navigator: Page): Promise<void> {
+ await navigator
+ .locator('[data-testid="nav-create-new"]')
+ .or(navigator.locator('[data-testid="nav-first-run-blank"]'))
+ .click();
+}
+
+export async function clickNavOpen(navigator: Page): Promise<void> {
+ await navigator
+ .locator('[data-testid="nav-open"]')
+ .or(navigator.locator('[data-testid="nav-first-run-open"]'))
+ .click();
+}
diff --git a/packages/desktop/tests/smoke/consent-dialog.e2e.ts b/packages/desktop/tests/smoke/consent-dialog.e2e.ts
index 53221a9f2..f37d848c3 100644
--- a/packages/desktop/tests/smoke/consent-dialog.e2e.ts
+++ b/packages/desktop/tests/smoke/consent-dialog.e2e.ts
@@ -36,6 +36,7 @@ import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import type { ElectronApplication, Page } from '@playwright/test';
import { _electron as electron } from '@playwright/test';
+import { clickNavOpen } from './_helpers/navigator-actions';
import { expect, test } from './_helpers/smoke-test';
const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -198,7 +199,7 @@ test.describe('Consent-dialog smoke', () => {
captureStderrFor(app);
const navigator = await findWindowByMode(app, 'navigator');
- await navigator.locator('[data-testid="nav-open"]').click();
+ await clickNavOpen(navigator);
// content.dir now lives inside the collapsed "Advanced settings" section.
await expandAdvancedSettings(navigator);
const contentDir = navigator.locator('[data-testid="consent-content-dir"]');
@@ -238,7 +239,7 @@ test.describe('Consent-dialog smoke', () => {
captureStderrFor(app);
const navigator = await findWindowByMode(app, 'navigator');
- await navigator.locator('[data-testid="nav-open"]').click();
+ await clickNavOpen(navigator);
await expandAdvancedSettings(navigator);
const contentDirInput = navigator.locator('[data-testid="consent-content-dir"]');
@@ -269,7 +270,7 @@ test.describe('Consent-dialog smoke', () => {
captureStderrFor(app);
const navigator = await findWindowByMode(app, 'navigator');
- await navigator.locator('[data-testid="nav-open"]').click();
+ await clickNavOpen(navigator);
await expandAdvancedSettings(navigator);
// Dialog should render with git-root-promotion notice referencing the
diff --git a/packages/desktop/tests/smoke/create-new-project.e2e.ts b/packages/desktop/tests/smoke/create-new-project.e2e.ts
index c676a8052..852aeb71f 100644
--- a/packages/desktop/tests/smoke/create-new-project.e2e.ts
+++ b/packages/desktop/tests/smoke/create-new-project.e2e.ts
@@ -47,6 +47,7 @@ import { fileURLToPath } from 'node:url';
import type { ElectronApplication, Page } from '@playwright/test';
import { _electron as electron } from '@playwright/test';
import { typeProjectName } from './_helpers/create-new-dialog';
+import { clickNavCreateNew } from './_helpers/navigator-actions';
import { expect, test } from './_helpers/smoke-test';
const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -188,7 +189,7 @@ test.describe('Create-new-project smoke', () => {
captureStderrFor(app);
const navigator = await findWindowByMode(app, 'navigator');
- await navigator.locator('[data-testid="nav-create-new"]').click();
+ await clickNavCreateNew(navigator);
const dialog = navigator.locator('[data-testid="create-project-dialog"]');
await expect(dialog).toBeVisible({ timeout: 15_000 });
@@ -246,7 +247,7 @@ test.describe('Create-new-project smoke', () => {
captureStderrFor(app);
const navigator = await findWindowByMode(app, 'navigator');
- await navigator.locator('[data-testid="nav-create-new"]').click();
+ await clickNavCreateNew(navigator);
await expect(navigator.locator('[data-testid="create-project-dialog"]')).toBeVisible({
timeout: 15_000,
});
@@ -291,7 +292,7 @@ test.describe('Create-new-project smoke', () => {
captureStderrFor(app);
const navigator = await findWindowByMode(app, 'navigator');
- await navigator.locator('[data-testid="nav-create-new"]').click();
+ await clickNavCreateNew(navigator);
await expect(navigator.locator('[data-testid="create-project-dialog"]')).toBeVisible({
timeout: 15_000,
});
@@ -386,7 +387,7 @@ test.describe('Create-new-project smoke', () => {
captureStderrFor(app);
const navigator = await findWindowByMode(app, 'navigator');
- await navigator.locator('[data-testid="nav-create-new"]').click();
+ await clickNavCreateNew(navigator);
await expect(navigator.locator('[data-testid="create-project-dialog"]')).toBeVisible({
timeout: 15_000,
});
@@ -517,7 +518,7 @@ test.describe('Create-new-project smoke', () => {
captureStderrFor(app);
const navigator = await findWindowByMode(app, 'navigator');
- await navigator.locator('[data-testid="nav-create-new"]').click();
+ await clickNavCreateNew(navigator);
await expect(navigator.locator('[data-testid="create-project-dialog"]')).toBeVisible({
timeout: 15_000,
});
diff --git a/packages/desktop/tests/smoke/qa-create-new-extended.e2e.ts b/packages/desktop/tests/smoke/qa-create-new-extended.e2e.ts
index 44e7c793a..5b03a8661 100644
--- a/packages/desktop/tests/smoke/qa-create-new-extended.e2e.ts
+++ b/packages/desktop/tests/smoke/qa-create-new-extended.e2e.ts
@@ -35,6 +35,7 @@ import type { ElectronApplication, Page } from '@playwright/test';
import { _electron as electron } from '@playwright/test';
import { typeProjectName } from './_helpers/create-new-dialog';
import { captureAppProcess, closeAppBounded } from './_helpers/electron-cleanup';
+import { clickNavCreateNew } from './_helpers/navigator-actions';
import { expect, test } from './_helpers/smoke-test';
const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -168,7 +169,7 @@ test.describe('QA extended create-new-project', () => {
const app = await launchApp(tmpHome, { pickedParent: parent });
captureStderrFor(app);
const navigator = await findWindowByMode(app, 'navigator');
- await navigator.locator('[data-testid="nav-create-new"]').click();
+ await clickNavCreateNew(navigator);
await expect(navigator.locator('[data-testid="create-project-dialog"]')).toBeVisible({
timeout: 15_000,
});
@@ -229,7 +230,7 @@ test.describe('QA extended create-new-project', () => {
const app = await launchApp(tmpHome, { pickedParent: parent });
captureStderrFor(app);
const navigator = await findWindowByMode(app, 'navigator');
- await navigator.locator('[data-testid="nav-create-new"]').click();
+ await clickNavCreateNew(navigator);
const dialog = navigator.locator('[data-testid="create-project-dialog"]');
await expect(dialog).toBeVisible({ timeout: 15_000 });
@@ -297,7 +298,7 @@ test.describe('QA extended create-new-project', () => {
// close.
const app1Proc = captureAppProcess(app1);
const navigator = await findWindowByMode(app1, 'navigator');
- await navigator.locator('[data-testid="nav-create-new"]').click();
+ await clickNavCreateNew(navigator);
await expect(navigator.locator('[data-testid="create-project-dialog"]')).toBeVisible({
timeout: 15_000,
});
@@ -349,7 +350,7 @@ test.describe('QA extended create-new-project', () => {
const app2 = await launchApp(tmpHome);
captureStderrFor(app2);
const navigator2 = await findWindowByMode(app2, 'navigator', 30_000);
- await navigator2.locator('[data-testid="nav-create-new"]').click();
+ await clickNavCreateNew(navigator2);
await expect(navigator2.locator('[data-testid="create-project-dialog"]')).toBeVisible({
timeout: 15_000,
});
@@ -386,7 +387,7 @@ test.describe('QA extended create-new-project', () => {
const app = await launchApp(tmpHome, { pickedParent: parent });
captureStderrFor(app);
const navigator = await findWindowByMode(app, 'navigator');
- await navigator.locator('[data-testid="nav-create-new"]').click();
+ await clickNavCreateNew(navigator);
await expect(navigator.locator('[data-testid="create-project-dialog"]')).toBeVisible({
timeout: 15_000,
});
@@ -430,7 +431,7 @@ test.describe('QA extended create-new-project', () => {
const app = await launchApp(tmpHome, { pickedParent: parent });
captureStderrFor(app);
const navigator = await findWindowByMode(app, 'navigator');
- await navigator.locator('[data-testid="nav-create-new"]').click();
+ await clickNavCreateNew(navigator);
await expect(navigator.locator('[data-testid="create-project-dialog"]')).toBeVisible({
timeout: 15_000,
});
@@ -483,7 +484,7 @@ test.describe('QA extended create-new-project', () => {
const app = await launchApp(tmpHome, { pickedParent: subFolder });
captureStderrFor(app);
const navigator = await findWindowByMode(app, 'navigator');
- await navigator.locator('[data-testid="nav-create-new"]').click();
+ await clickNavCreateNew(navigator);
await expect(navigator.locator('[data-testid="create-project-dialog"]')).toBeVisible({
timeout: 15_000,
});
@@ -518,7 +519,7 @@ test.describe('QA extended create-new-project', () => {
const app = await launchApp(tmpHome, { pickedParent });
captureStderrFor(app);
const navigator = await findWindowByMode(app, 'navigator');
- await navigator.locator('[data-testid="nav-create-new"]').click();
+ await clickNavCreateNew(navigator);
await expect(navigator.locator('[data-testid="create-project-dialog"]')).toBeVisible({
timeout: 15_000,
});
@@ -551,7 +552,7 @@ test.describe('QA extended create-new-project', () => {
const app = await launchApp(tmpHome, { pickedParent: parent });
captureStderrFor(app);
const navigator = await findWindowByMode(app, 'navigator');
- await navigator.locator('[data-testid="nav-create-new"]').click();
+ await clickNavCreateNew(navigator);
await expect(navigator.locator('[data-testid="create-project-dialog"]')).toBeVisible({
timeout: 15_000,
});
@@ -593,7 +594,7 @@ test.describe('QA extended create-new-project', () => {
const app = await launchApp(tmpHome, { pickedParent: subFolder });
captureStderrFor(app);
const navigator = await findWindowByMode(app, 'navigator');
- await navigator.locator('[data-testid="nav-create-new"]').click();
+ await clickNavCreateNew(navigator);
await expect(navigator.locator('[data-testid="create-project-dialog"]')).toBeVisible({
timeout: 15_000,
});
@@ -645,7 +646,7 @@ test.describe('QA extended create-new-project', () => {
const app = await launchApp(tmpHome, { pickedParent: parent });
captureStderrFor(app);
const navigator = await findWindowByMode(app, 'navigator');
- await navigator.locator('[data-testid="nav-create-new"]').click();
+ await clickNavCreateNew(navigator);
await expect(navigator.locator('[data-testid="create-project-dialog"]')).toBeVisible({
timeout: 15_000,
});
diff --git a/packages/server/assets/skills/project/SKILL.md b/packages/server/assets/skills/project/SKILL.md
index 27280c697..e2d5e09d1 100644
--- a/packages/server/assets/skills/project/SKILL.md
+++ b/packages/server/assets/skills/project/SKILL.md
@@ -22,7 +22,7 @@ OpenKnowledge (OK) is a markdown-CRDT collaboration platform exposed via MCP. Th
3. **Preview / open a doc — determine your ONE surface FIRST (once per session).** Before opening anything, pick where to focus, stop at first match: **`OK_DESKTOP_TERMINAL` set** (check your env — `echo "$OK_DESKTOP_TERMINAL"`) → OK Desktop's own terminal → `ok open <name>` (switches this window) · have `preview_*` → Claude Code Desktop pane · have a URL-navigation/browser tool → Cursor/Codex → `preview_url` then navigate it · else plain CLI → `ok open <name>`. `ok open <name>` opens a **doc or folder** (auto-detected — no `--folder`); add `--skill <name>` for a skill. The `previewUrl` field is a route id, **not** your open mechanism — don't hand it to a browser just because you saw it. Don't `preview_screenshot` to confirm edits. Full Step-0 procedure + per-surface how-to: `references/preview.md`.
4. **Workflow guides:** `workflow({ kind: 'ingest' | 'research' | 'consolidate' | 'discover' })` returns a procedural guide, not data. Use it when the work fits the layer.
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 from this skill. Author through the `skill` target (`write({ skill })`), never a raw `.ok/skills/…` document. **Never read, diff, or edit the installed projections under `.claude/skills/` · `.cursor/skills/` · `.codex/skills/` · `.opencode/skills/` · `.agents/skills/`** — `install` generates them and overwrites them on the next sync; they are NOT source of truth.
+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 from this skill. Author through the `skill` target (`write({ skill })`), never a raw `.ok/skills/…` document. **Never read, diff, or edit the installed projections under `.claude/skills/` · `.cursor/skills/` · `.codex/skills/` · `.opencode/skills/` · `.pi/skills/` · `.agents/skills/`** — `install` generates them and overwrites them on the next sync; they are NOT source of truth.
## Tool index — 19 tools (router; the MCP tool descriptions carry each tool's full contract)
diff --git a/packages/server/assets/skills/project/references/preview.md b/packages/server/assets/skills/project/references/preview.md
index 920e33250..ea242fea5 100644
--- a/packages/server/assets/skills/project/references/preview.md
+++ b/packages/server/assets/skills/project/references/preview.md
@@ -5,7 +5,7 @@
- Re-navigation and end-of-turn discipline
- `previewUrl` is a route, not a URL
- The three first-class apps (Claude Code Desktop, Cursor, Codex desktop)
-- Any-CLI track — Claude Code / Codex / Cursor CLI / OpenCode, no browser → `ok open`
+- Any-CLI track — Claude Code / Codex / Cursor CLI / OpenCode / Pi, no browser → `ok open`
- Four attach signals
- `previewUrl: null` semantics, server lifecycle, read-only mirror, no-screenshots
@@ -24,11 +24,11 @@ Your host doesn't change mid-session, so determine this **once**, the first time
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.)
2. **Do you have `preview_*` tools** (`preview_start` / `preview_eval`)? → **Claude Code Desktop** → drive its pane (rung details below).
3. **Do you have any URL-navigation / in-app browser tool** (Cursor `Navigate`, Codex `@Browser`, or `browser` / `open_url` / `view_url` / …)? → **Cursor / Codex desktop** → `preview_url` once, then navigate that browser to the `url`.
-4. **None of the above** → you're a **plain CLI** (Claude Code CLI, Codex CLI, Cursor CLI, OpenCode, 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.
+4. **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.
Decide once; then every "open / show / preview this doc" this session uses that surface's mechanism. **The `previewUrl` field in tool responses is a route id, not your open mechanism** — seeing it is not a reason to hand it to a browser. The rest of this section is the per-surface "how" for whichever rung you landed on.
-**OK ships first-class preview support for three apps — Claude Code Desktop, Cursor, and the Codex desktop app — plus any CLI (Claude Code CLI, Codex CLI, Cursor CLI, OpenCode, …) on a separate `ok open` track (below). Make the preview seamless in each.** Match on the tool you actually have (capability, not host name): if a tool can navigate to a URL, it counts as an in-app browser; if nothing can, you're a CLI → `ok open`. The three apps map to:
+**OK ships first-class preview support for three apps — Claude Code Desktop, Cursor, and the Codex desktop app — plus any CLI (Claude Code CLI, Codex CLI, Cursor CLI, OpenCode, Pi, …) on a separate `ok open` track (below). Make the preview seamless in each.** Match on the tool you actually have (capability, not host name): if a tool can navigate to a URL, it counts as an in-app browser; if nothing can, you're a CLI → `ok open`. The three apps map to:
- **Claude Code Desktop — you have `preview_*` tools** (e.g. `preview_start` + `preview_eval`) → **First open of the session:** to land directly on a doc, arm it first with `preview_url({ armPaneTarget: true, document })` (or `folder`), then `preview_start("open-knowledge-ui")` — `ok ui` redirects the base-open straight to the armed route, so the pane opens on the doc, not root. Plain `preview_start` (no arm) opens at root. **Moving between docs once the pane is open: do it in one `preview_eval` step — set `window.location.hash` to the target's route fragment from the response `previewUrl`, the part from `#` on (e.g. `window.location.hash = '#/specs/foo/SPEC'`).** That drives the SPA router directly. Arm + `preview_start` only redirects a *fresh* open; it can't move an already-open pane (`preview_start` reuses the live process without reloading), so use `preview_eval` there. Don't read or edit `.claude/launch.json` — host-managed; the OK lock-collision proxy handles the UI-already-running case. If `preview_start` fails, report it; don't "fix" `launch.json`.
- **Cursor / Codex desktop — no `preview_*` tool, but you have an in-app / built-in browser tool** → call `preview_url` once for the **exact** target (`document` for a doc, `folder` for a folder) and navigate your **in-app browser** straight to the returned `url`. Open that deep URL directly — never the root then navigate; omit both args only for the root. Drive the tool your host gives you:
@@ -37,7 +37,7 @@ Decide once; then every "open / show / preview this doc" this session uses that
- **Any other host** with a URL-navigation tool (`browser`, `view_url`, `open_url`, `web.browse`, …) → navigate it to the `url`. **This is also the fallback when a named tool above isn't present under that exact name** (hosts rename tools): match on the capability, not the name. If no URL-navigation tool exists at all, drop to the Claude Code CLI track below.
- **Honor `autoOpen`** (on `preview_url`, or on `warning` for write tools). If `false`, do not open or refresh any preview UI; surface the URL only if asked.
-**Any CLI — a separate track (no browser).** **Claude Code CLI, Codex CLI, Cursor CLI, OpenCode — any pure-stdio / shell agent with no in-app browser tool — uses `ok open`, never a preview URL.** The rule is capability, not vendor: no tool that navigates a URL → you're on this track.
+**Any CLI — a separate track (no browser).** **Claude Code CLI, Codex CLI, Cursor CLI, OpenCode, Pi — any pure-stdio / shell agent with no in-app browser tool — uses `ok open`, never a preview URL.** The rule is capability, not vendor: no tool that navigates a URL → you're on this track.
- **`ok open <name>`** — opens a **doc or folder** in the OK Desktop app. The type is auto-detected (a directory on disk → folder, otherwise a doc), so **`--folder` is not needed** (it stays only as an explicit override for a folder that doesn't exist on disk yet). An action you run, not a URL to print.
- **`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).
diff --git a/packages/server/assets/skills/write-skill/SKILL.md b/packages/server/assets/skills/write-skill/SKILL.md
index 07f89525d..ff636821a 100644
--- a/packages/server/assets/skills/write-skill/SKILL.md
+++ b/packages/server/assets/skills/write-skill/SKILL.md
@@ -158,7 +158,7 @@ install({ name: "<name>" })
```
This fans the validated skill into the project's configured editors
-(`.claude/skills/`, `.cursor/skills/`, `.codex/skills/`, `.opencode/skills/`). For a project skill,
+(`.claude/skills/`, `.cursor/skills/`, `.codex/skills/`, `.opencode/skills/`, `.pi/skills/`). For a project skill,
commit `.ok/skills/<name>/` and the projections so teammates get it on pull. Edit
later with `edit({ skill })` then `install` again; `delete({ skill })` removes it
and uninstalls. Roll back a **project** skill with `history({ skill })` →
diff --git a/packages/server/src/content-filter.ts b/packages/server/src/content-filter.ts
index 7baed285d..551583f08 100644
--- a/packages/server/src/content-filter.ts
+++ b/packages/server/src/content-filter.ts
@@ -103,6 +103,7 @@ const BUILTIN_SKIP_DIRS = new Set([
'.codex',
'.agents',
'.opencode',
+ '.pi',
// OS-managed (macOS)
'Library',
'Applications',
@@ -134,6 +135,7 @@ const ALWAYS_SKIP_DIRS = new Set<string>([
'.codex',
'.agents',
'.opencode',
+ '.pi',
]);
/**
diff --git a/packages/server/src/handoff-dispatch-api.ts b/packages/server/src/handoff-dispatch-api.ts
index af484e75c..ce3bc8e2b 100644
--- a/packages/server/src/handoff-dispatch-api.ts
+++ b/packages/server/src/handoff-dispatch-api.ts
@@ -140,19 +140,19 @@ const RECIPES = {
binaryName: 'cursor',
urlScheme: 'cursor:',
},
- // `opencode` is intentionally absent: it is a terminal-only target with no
- // URL scheme, dispatched via the terminal-CLI path (`requestTerminalLaunch`),
- // never this deep-link endpoint. It is excluded from the exhaustiveness gate
- // via `Exclude<…, 'opencode'>` so the build does not demand a (nonexistent)
- // URL recipe for it.
-} as const satisfies Record<Exclude<HandoffTarget, 'opencode'>, Recipe>;
+ // `opencode` and `pi` are intentionally absent: they are terminal-only
+ // targets with no URL scheme, dispatched via the terminal-CLI path
+ // (`requestTerminalLaunch`), never this deep-link endpoint. They are
+ // excluded from the exhaustiveness gate via `Exclude<…>` so the build does
+ // not demand (nonexistent) URL recipes for them.
+} as const satisfies Record<Exclude<HandoffTarget, 'opencode' | 'pi'>, Recipe>;
// Narrowed to the URL-dispatchable subset: `RECIPES` omits the terminal-only
-// `opencode` target, so its keys (and the parsed `target`) exclude it, keeping
-// the `RECIPES[target]` lookup below exhaustive at the type level.
+// `opencode` / `pi` targets, so its keys (and the parsed `target`) exclude
+// them, keeping the `RECIPES[target]` lookup below exhaustive at the type level.
const TARGET_VALUES = Object.keys(RECIPES) as [
- Exclude<HandoffTarget, 'opencode'>,
- ...Exclude<HandoffTarget, 'opencode'>[],
+ Exclude<HandoffTarget, 'opencode' | 'pi'>,
+ ...Exclude<HandoffTarget, 'opencode' | 'pi'>[],
];
const HandoffRequestSchema = z.object({
target: z.enum(TARGET_VALUES),
diff --git a/packages/server/src/mcp/tools/install.ts b/packages/server/src/mcp/tools/install.ts
index 0297c0da4..ab9112485 100644
--- a/packages/server/src/mcp/tools/install.ts
+++ b/packages/server/src/mcp/tools/install.ts
@@ -34,11 +34,11 @@ import { resolveSkillName, SKILL_NAME_DESCRIBE, SkillScopeArg } from './verb-sch
const DESCRIPTION = [
'[Requires: Hocuspocus server] Install an authored SKILL into your editors — the deliberate Draft → Installed step.',
'',
- 'Projects the skill source at `.ok/skills/<name>/` verbatim into the editor host dirs your project is configured for (`.claude/skills/<name>/`, `.cursor/skills/<name>/`, `.codex/skills/<name>/`, `.opencode/skills/<name>/`). The source is validated FIRST — a SKILL.md with git conflict markers, missing/invalid frontmatter, XML tags in name/description, or a reserved `open-knowledge*` name is refused (never projected into your agent context). Records the install so it survives a relaunch.',
+ 'Projects the skill source at `.ok/skills/<name>/` verbatim into the editor host dirs your project is configured for (`.claude/skills/<name>/`, `.cursor/skills/<name>/`, `.codex/skills/<name>/`, `.opencode/skills/<name>/`, `.pi/skills/<name>/`). The source is validated FIRST — a SKILL.md with git conflict markers, missing/invalid frontmatter, XML tags in name/description, or a reserved `open-knowledge*` name is refused (never projected into your agent context). Records the install so it survives a relaunch.',
'',
'**Parameters:**',
`- \`name\` — ${SKILL_NAME_DESCRIBE}`,
- '- `targets` — Optional explicit editor ids (`claude` | `cursor` | `codex` | `opencode`). Omit to install into the editors this project is already configured for.',
+ '- `targets` — Optional explicit editor ids (`claude` | `cursor` | `codex` | `opencode` | `pi`). Omit to install into the editors this project is already configured for.',
'- `scope` — `project` (default, shared via git) or `global` (user-global, installed into every editor on this machine).',
'',
'After editing a skill, run `install` again to push the new version. After `delete({skill})`, the projection is removed automatically (uninstall).',
diff --git a/packages/server/src/skill-projection.test.ts b/packages/server/src/skill-projection.test.ts
index d2a567d5b..16b18fa07 100644
--- a/packages/server/src/skill-projection.test.ts
+++ b/packages/server/src/skill-projection.test.ts
@@ -107,11 +107,12 @@ describe('projectSkill / reverseProjectSkill', () => {
'claude',
'cursor',
'codex',
+ 'pi',
'claude-desktop',
]);
// claude-desktop has no skill surface → skipped.
- expect(written.sort()).toEqual(['claude', 'codex', 'cursor']);
- for (const host of ['.claude', '.cursor', '.codex']) {
+ expect(written.sort()).toEqual(['claude', 'codex', 'cursor', 'pi']);
+ for (const host of ['.claude', '.cursor', '.codex', '.pi']) {
const link = join(root, host, 'skills', 'trip-log');
// It's a symlink, not a copied dir, and it resolves to the source.
expect(lstatSync(link).isSymbolicLink()).toBe(true);
@@ -120,9 +121,10 @@ describe('projectSkill / reverseProjectSkill', () => {
expect(readlinkSync(link).startsWith('..')).toBe(true);
}
- const removed = reverseProjectSkill('trip-log', root, ['claude', 'cursor', 'codex']);
- expect(removed.sort()).toEqual(['claude', 'codex', 'cursor']);
+ const removed = reverseProjectSkill('trip-log', root, ['claude', 'cursor', 'codex', 'pi']);
+ expect(removed.sort()).toEqual(['claude', 'codex', 'cursor', 'pi']);
expect(existsSync(join(root, '.claude', 'skills', 'trip-log'))).toBe(false);
+ expect(existsSync(join(root, '.pi', 'skills', 'trip-log'))).toBe(false);
// Uninstall removes only the link — the source is untouched.
expect(existsSync(join(dir, 'SKILL.md'))).toBe(true);
});
@@ -165,6 +167,7 @@ describe('projectSkill / reverseProjectSkill', () => {
test('skillHostDir returns null for claude-desktop', () => {
expect(skillHostDir(root, 'claude-desktop', 'x')).toBeNull();
expect(skillHostDir(root, 'claude', 'x')).toContain('/.claude/skills/x');
+ expect(skillHostDir(root, 'pi', 'x')).toContain('/.pi/skills/x');
});
});