npm package: @sage-protocol/pi-adapter
Description: Sage Protocol MCP integration for pi coding agent
Author: Sage Protocol
Latest version: 0.2.2

# @sage-protocol/pi-adapter

Sage integration for the pi coding agent runtime.

Additional docs:
- Setup: `docs/setup.md`
- Developer guide: `docs/developer.md`

It gives you:
- Sage MCP tools in pi (`sage_search`, `sage_execute`, `sage_status`)
- **Dynamic identity context** — wallet, active libraries, and skill counts injected into every turn's system prompt
- Session hook integration (`sage skill context`, `sage suggest hook skill`)
- RLM capture hooks (`sage capture hook prompt/response`)
- Optional pre/post tool security scanning (`sage security scan-hook`)

Sage internal domains are available immediately through those tools. External MCP server lifecycle still goes through pi's hub-compat flow when needed.

## Agent Profile (Dynamic Identity Context)

Every pi session automatically gets Sage Protocol identity context injected into the system prompt. The agent knows who it's working for without any configuration.

What gets injected (example):

```
## Sage Protocol Context
Sage Protocol is a decentralized network for collaborative prompt, skill, and knowledge
curation on Base (L2). Skills and prompts live in libraries governed by DAOs. Creators
and curators earn when their work is used. SXXX is the governance token: hold it to
vote, create DAOs, and shape the protocol. Burns from activity create deflationary
pressure — early participants gain governance influence and economic upside as the
network grows. The more skills published, the more valuable discovery becomes for every
user and agent.

### Active Identity
- Wallet: 0x9794...507ca (privy, Base Sepolia)
- Active libraries (6): sage-entrypoints, impeccable-ui-review, sage-review-foundations, ...
- Libraries: 10 installed (48 skills, 12 prompts)
```

This makes every pi session "sage-aware" — the agent knows the active wallet, network, installed libraries, and available skill count. The context is fetched from the sage CLI (`wallet current`, `library active`, `library list`) and cached for 60 seconds to avoid redundant calls.

**Extension mode**: Identity context is appended to the system prompt on every turn via the `before_agent_start` hook.

**SDK mode**: Identity context is injected as a hook message at session start via `setupHooks`.

The feature is always-on when the sage CLI is available. If the CLI is missing or any query fails, the identity block is silently omitted — it never blocks the agent turn.

For model-driven patching, see `packages/sage-pi-adapter/SKILL.md`.

## Requirements

- Node project using `@mariozechner/pi-coding-agent`
- Sage CLI installed and on `PATH` (`sage`)

## Choose the Right Integration Mode

There are two different scenarios:

1. You own harness source code (SDK embedding with `createAgentSession`) -> use this package directly.
2. You only run installed `pi` CLI (`npm i -g @mariozechner/pi-coding-agent`) -> install this package with `pi install`.

This package now ships a pi extension entrypoint, so CLI users do not need to patch harness internals.

## Install

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

For pi CLI extension mode:

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

For local development from this monorepo:

```bash
npm link /path/to/sage-protocol/packages/sage-pi-adapter
```

Verify extension mode:

```bash
pi list
# should include npm:@sage-protocol/pi-adapter
```

CI validates the packed tarball against the latest published `pi` CLI by running
`npx @mariozechner/pi-coding-agent@latest install` in an isolated HOME and local
project workspace.

## pi CLI Mode (No Harness Source Changes)

After `pi install npm:@sage-protocol/pi-adapter`, restart `pi` and use it normally.

What loads automatically in extension mode:

- custom tools: `sage_search`, `sage_execute`, `sage_status`
- prompt hooks: `sage suggest hook skill`
- capture hooks: `sage capture hook prompt/response`
- security hooks: `sage security scan-hook` on tool pre/post

Optional environment overrides:

```bash
export SAGE_BIN=sage
export SAGE_PROFILE=testnet
export SAGE_SUGGEST_LIMIT=3
export SAGE_SUGGEST_DEBOUNCE_MS=800
export SAGE_SECURITY_HOOKS=1
export SAGE_RLM_FEEDBACK=1
export SAGE_SHOW_HOOK_MESSAGES=1
export SAGE_ALLOW_BASH_CLI=0   # optional: force MCP-only routing; direct `sage ...` calls are allowed by default, and `env SAGE_ALLOW_BASH_CLI=1 sage ...` re-enables per command
```

Manual hook command check (hook reads prompt from env/stdin, not positional args):

```bash
PROMPT="cpp libraries" SAGE_SOURCE=pi-extension sage suggest hook skill --limit 3
```

`sage suggest hook skill "cpp libraries"` is expected to fail because hook mode does not accept positional query text.

Use plain query mode when testing manually without hook env:

```bash
sage suggest skill "cpp libraries"
```

## Recommended Project Config For Entrypoint Development

For a project-local pi setup where Sage owns routing and entrypoint behavior, keep pi
thin and explicitly point it at the Sage Pi export surface, not the raw Sage authoring root.

Recommended `.pi/settings.json` shape for local monorepo development:

```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-codebase/SKILL.md"
  ],
  "enableSkillCommands": true
}
```

Notes:

- Paths are relative to `.pi/settings.json`, so the `../packages/...` layout matches this monorepo shape.
- Prefer the curated `packages/sage-pi-export` surface over broad runtime roots such as `~/.local/share/sage/skills`, `~/.claude/skills`, or `~/.codex/skills`. Those runtime roots often contain backups, version snapshots, and third-party skills that create noisy Pi validation errors and collisions.
- Keep pi/OpenClaw as the transport and tool layer. Put routing policy and recurring entrypoint behavior in Sage skills and libraries instead of hard-coding them into the harness.
- Treat repo-authored Sage skills and entrypoint definitions as the authoring source, on-chain libraries as the shared distribution surface, and local sync as development convenience.
- A good pattern is one thin entrypoint library concept such as `sage-entrypoints` that dispatches into stable Sage-owned dependency libraries by key instead of duplicating their bodies.
- For example, an entrypoint layer can route into `code-review`, `ceo-plan-review`, or `vc-office-hours` from a stable dependency surface such as `sage-review-foundations` without embedding those skill bodies in the adapter or local config.
- `packages/sage/pi-export.manifest.json` is the source of truth for what Pi sees by default. `node scripts/util/sync-sage-pi-export.mjs` materializes that manifest into `packages/sage-pi-export/skills/` as symlinks to the real Sage-authored skills.
- If another plugin or harness layer also injects context automatically, avoid double-injection. Pick one place to do prompt/context steering.

## Harness Integration (Recommended)

```typescript
import { createAgentSession, createCodingTools } from '@mariozechner/pi-coding-agent';
import { createSageSessionConfig } from '@sage-protocol/pi-adapter';

export async function createSessionWithSage(model: any, cwd = process.cwd()) {
  const sage = await createSageSessionConfig({
    sageBin: 'sage',
    source: 'pi-agent-core',
    suggestLimit: 3,
    enableRlmFeedback: true,
    enableSecurityHooks: true,
  });

  const { session } = await createAgentSession({
    model,
    tools: sage.wrapToolsWithSecurity(createCodingTools(cwd)),
    customTools: sage.customTools,
  });

  const disposeSageHooks = sage.setupHooks(session);

  return {
    session,
    dispose: async () => {
      disposeSageHooks();
      await sage.mcpBridge.stop();
    },
  };
}
```

## Integrate Into an Existing Harness (Model-Directed)

If this package is on npm, you can ask a coding model to patch your harness directly.

Important: make sure the model is operating in the harness repository (for example `pi-mono`), not in `sage-protocol/packages/sage-pi-adapter`.

Preflight checks to include in your instruction:

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

Use this instruction block as-is:

```text
Install @sage-protocol/pi-adapter and patch the session bootstrap to:
1) create const sage = await createSageSessionConfig(...)
2) set customTools: sage.customTools
3) wrap base tools with tools: sage.wrapToolsWithSecurity(existingTools)
4) call const disposeSageHooks = sage.setupHooks(session) after createAgentSession
5) call disposeSageHooks() during teardown
6) keep existing model/provider/settings behavior unchanged
7) if current workspace is not the harness repo, switch to it first and patch there
```

Helpful search targets for the model:

```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
```

Typical patch shape:

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

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

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

const disposeSageHooks = sage.setupHooks(session);
// on shutdown: disposeSageHooks()
```

## Plugin Pattern

If your harness has a plugin/bootstrap layer, wire Sage there:

1. Construct config with `createSageSessionConfig(...)`
2. Add `customTools: sage.customTools`
3. Wrap existing tools with `sage.wrapToolsWithSecurity(...)`
4. Call `const dispose = sage.setupHooks(session)` after session creation
5. Call `dispose()` during teardown (and optionally `sage.mcpBridge.stop()`)

If your harness uses a plugin registry, expose Sage as one plugin:

```typescript
export async function setupSagePlugin(runtime: {
  makeSession: (config: any) => Promise<{ session: any }>;
  tools: any[];
  model: any;
}) {
  const sage = await createSageSessionConfig({ source: 'pi-agent-core' });

  const { session } = await runtime.makeSession({
    model: runtime.model,
    tools: sage.wrapToolsWithSecurity(runtime.tools),
    customTools: sage.customTools,
  });

  const disposeSageHooks = sage.setupHooks(session);

  return {
    session,
    dispose: async () => {
      disposeSageHooks();
      await sage.mcpBridge.stop();
    },
  };
}
```

## API Summary

`createSageSessionConfig(config)` returns:

```typescript
{
  customTools: ToolDefinition[];
  mcpBridge: SageMcpBridge;
  setupHooks: (session: AgentSession) => () => void;
  wrapToolsWithSecurity: (tools: ToolDefinition[]) => ToolDefinition[];
}
```

Config shape:

```typescript
interface SageP2Config {
  sageBin?: string;
  sageProfile?: string;
  suggestLimit?: number;
  suggestDebounceMs?: number;
  timeoutMs?: number;
  enableProvision?: boolean;
  enableRlmFeedback?: boolean;
  enableSecurityHooks?: boolean;
  source?: string;
  env?: Record<string, string>;
}
```

## Validate

```bash
npm run build
npm test
```

## License

MIT