# Sage Pi Adapter Integration Skill

Use this skill when a repository uses `@earendil-works/pi-coding-agent` (formerly `@mariozechner/pi-coding-agent`) and needs Sage integrated into its session bootstrap/plugin layer.

## Preflight (Do This First)

1. Verify npm package availability:
   - `npm view @sage-protocol/pi-adapter version`
2. Ensure you are patching the harness repo (not this package repo):
   - For pi-mono target: `https://github.com/badlogic/pi-mono/tree/main/packages/coding-agent`
3. If current workspace does not contain harness sources, switch/clone first, then patch there.

## Hard-Stop Conditions

Stop and report immediately (do not keep searching random directories) if any of these are true:

- `npm view @sage-protocol/pi-adapter version` fails after retrying once
- Current workspace does not contain harness paths like `packages/coding-agent`
- You cannot find a session bootstrap path (`createAgentSession` call sites)

When stopping, report what is missing and ask for the harness repo path.

> **Pi upstream:** [earendil-works/pi](https://github.com/earendil-works/pi) — `@earendil-works/pi-coding-agent`
> **Sage upstream:** [sage-protocol/sage](https://github.com/sage-protocol/sage)

## Goal

Apply the Sage integration contract exactly:

1. For pi CLI users: `pi install npm:@sage-protocol/pi-adapter` (no harness code edits)
 2. For source-owned harness users: apply SDK patch (`createSageSessionConfig`, `customTools`, `wrapToolsWithSecurity`, `setupHooks`)
 3. Package name: `@earendil-works/pi-coding-agent` (formerly `@mariozechner/pi-coding-agent`)

## Integration Modes (Important)

- Installed pi CLI only (no harness source): run `pi install npm:@sage-protocol/pi-adapter`, restart pi, and verify Sage tools are present.
- Source-owned harness (editable repo): apply the patch pattern in this skill.

## CLI-Only Flow (No Source Edits)

```bash
pi install npm:@sage-protocol/pi-adapter
pi list
```

Then restart `pi` and verify `sage_status` is callable.

Bridge health expectation:

- Pi exposes Sage through `sage_search`, `sage_execute`, and `sage_status`.
- `sage_status` is the user-facing health surface. When the MCP bridge is
  degraded, surface a readable bridge error and recovery hint instead of silent
  retry exhaustion.
- Inside bridge startup/health code, probe low-level MCP (`tools/list` or a
  minimal Sage MCP call). Do not recursively call the adapter-level
  `sage_status` tool from inside the bridge.
- Recovery wording should point at the Sage MCP bridge (`sage mcp start`,
  restart Pi/Sage bridge) unless the failing path is specifically the daemon.

For project-local monorepo development, prefer an explicit `.pi/settings.json` that
keeps pi thin and points at the Sage Pi export surface:

```json
{
  "packages": [
    "../packages/sage-pi-adapter",
    {
      "source": "../packages/sage-pi-export",
      "skills": ["skills/*/SKILL.md"],
      "extensions": [],
      "prompts": [],
      "themes": []
    },
    {
      "source": "npm:oh-pi",
      "extensions": ["!**"]
    }
  ],
  "skills": [
    "-../.agents/skills/frontend-design/SKILL.md",
    "-~/.pi/agent/skills/prompt-builder/SKILL.md",
    "-~/.pi/agent/skills/sage/SKILL.md",
    "-~/.pi/agent/skills/sage-workflow/SKILL.md"
  ],
  "enableSkillCommands": true
}
```

This keeps the harness responsible for transport and tool exposure while Sage skills
and libraries own the routing and behavior layer.

The package-filtered `../packages/sage-pi-export` entry is intentional: it exposes a Pi-safe,
curated Sage surface without scanning broad runtime roots such as `~/.local/share/sage/skills`,
which often contain backup directories, version snapshots, and third-party installs that are valid
for Sage runtime use but noisy for Pi skill validation.

Architectural posture:

- pi/OpenClaw = transport and tool surface
- `sage` = router and tool-aware base skill
- repo-authored entrypoint definitions = authoring layer
- on-chain libraries = shared distribution and sync/pull layer
- local sync = development convenience

The entrypoint layer should stay thin. It should dispatch into stable Sage-owned dependency
libraries by key, not duplicate them. For example, a review or planning entrypoint can route into
`code-review`, `ceo-plan-review`, or `vc-office-hours` from `sage-review-foundations` without
copying those skill bodies.

Pi export surface rule:

- author real skills under `packages/sage/skills/`
- declare Pi-visible skills in `packages/sage/pi-export.manifest.json`
- materialize the Pi-safe surface with `node scripts/util/sync-sage-pi-export.mjs`
- point `.pi/settings.json` at `../packages/sage-pi-export`, not at the raw authoring tree

Hook command semantics:

- `sage suggest hook skill` reads prompt from env/stdin (for IDE/agent hooks)
- It does not accept positional query text
- Manual query testing uses `sage suggest skill "..."`

## Required Patch Pattern

```ts
import { createSageSessionConfig } from '@sage-protocol/pi-adapter';

const sage = await createSageSessionConfig({
  source: 'pi-agent-core',
  enableSecurityHooks: true,
  enableRlmFeedback: true,
  suggestLimit: 3,
});

const { session } = await createAgentSession({
  ...existingConfig,
  tools: sage.wrapToolsWithSecurity(existingTools),
  customTools: sage.customTools,
});

const disposeSageHooks = sage.setupHooks(session);
```

## Plugin Setup (If Harness Uses Plugins)

- Put this in the plugin/bootstrap setup path, not in random feature code.
- Return or register a disposer that calls:
  - `disposeSageHooks()`
  - `await sage.mcpBridge.stop()` (optional but recommended for owned lifecycle)

## Where to Search

Find patch points with:

```bash
rg "createAgentSession|createCodingTools|customTools|tools:" src
rg "dispose|shutdown|teardown|cleanup" src
rg "createAgentSession|createCodingTools|customTools|tools:" packages/coding-agent
rg "dispose|shutdown|teardown|cleanup" packages/coding-agent
```

Install in the harness repo root:

```bash
npm install @sage-protocol/pi-adapter
```

If npm lookup fails unexpectedly:

```bash
npm config get registry
npm view @sage-protocol/pi-adapter version
```

## Guardrails

- Keep existing model/provider/settings behavior unchanged.
- Do not remove existing tools; wrap them.
- Do not duplicate hook setup in multiple places.
- Ensure cleanup path is wired for long-running processes.
- Do not stop after patching this package's own examples; patch the actual harness bootstrap.

## Copy-Paste Agent Prompt

```text
If the user only has pi CLI access, run:
- pi install npm:@sage-protocol/pi-adapter
- verify with pi list
- restart pi and verify sage_status tool is available

If the user has harness source access (target repo: pi-mono/packages/coding-agent), patch Sage into bootstrap.

Preflight:
1) npm view @sage-protocol/pi-adapter version
2) npm config get registry
3) ensure current workspace contains packages/coding-agent

Then implement:
- const sage = await createSageSessionConfig(...)
- customTools: sage.customTools
- tools: sage.wrapToolsWithSecurity(existingTools)
- const disposeSageHooks = sage.setupHooks(session)
- teardown calls disposeSageHooks() (and sage.mcpBridge.stop() if lifecycle owned)

Do not change existing model/provider behavior. Run build/tests for touched package and report changed files.
```

## Verification Checklist

- `customTools` includes Sage tools
- Base tools are wrapped with `wrapToolsWithSecurity`
- `setupHooks(session)` is called once per session
- Teardown calls `disposeSageHooks()`
- `sage_status` reports bridge health; broken bridge paths return a structured,
  user-readable error quickly
- Build/tests pass for touched repo

## Source of Truth

For the latest contract and examples, see:

- `packages/sage-pi-adapter/README.md`
