Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .claude/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,9 @@ credentials (`--env` is for the agent's own paths, not its keys).
(`packages/agent-host/tools/fake-model.mjs`). The session is real, the
model is not: each prompt is a scenario — `/tool` (a tool call; OpenCode
and Pi ask permission for it), `/question` (a question form), `/plan-approval`
(a plan card), `/error` (an API failure), `/long` (a long answer and a
large context) — and anything else is echoed. Nothing reaches an account,
(a plan card), `/task <brief>` (a Pi sub-agent running the brief),
`/background` (a background shell), `/error` (an API failure), `/long` (a
long answer and a large context) — and anything else is echoed. Nothing reaches an account,
and CI runs the same thing for claude-code and pi
(`src/drivers/claude/__tests__/claudeFakeModel.test.ts`,
`src/drivers/pi/__tests__/piFakeModel.test.ts`).
Expand Down
2 changes: 2 additions & 0 deletions .claude/skills/verify-changes/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,8 @@ agent uses:
| `/tool [command]` | call its own shell tool (a permission card on OpenCode) |
| `/question` | ask one multiple-choice question (a question form/card) |
| `/plan-approval` | propose a plan for approval (a plan card; needs plan mode) |
| `/task [brief]` | start a sub-agent whose prompt is the brief (Pi; `/task /tool` makes it run a command) |
| `/background [command]` | run a shell command in the background (Qwen Code, Pi) |
| `/error` | answer with a 400, exercising the failure path |
| `/long` | answer with a long text and a large context figure |
| anything else | echoed back as the agent's text |
Expand Down
6 changes: 4 additions & 2 deletions docker/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,14 @@ FROM ${NODE_IMAGE}
ARG USER_ID=1000
ARG GROUP_ID=1000

# git/gh/python3/curl are for the agent's own tool use inside sessions. The
# git/gh/python3/curl are for the agent's own tool use inside sessions, and
# ripgrep/fd are Pi's `grep` and `find` (Debian names fd `fdfind`, which Pi
# looks for too; Pi runs offline, so it never downloads them itself). The
# GitHub CLI keyring is served already dearmored, so no gnupg is needed.
# yarn and corepack ship with the node image and nothing here uses them (npm
# stays, for the agents' own use in sessions).
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates curl git python3 \
&& apt-get install -y --no-install-recommends ca-certificates curl git python3 ripgrep fd-find \
&& install -d -m 0755 /etc/apt/keyrings \
&& curl -fsSL -o /etc/apt/keyrings/githubcli-archive-keyring.gpg https://cli.github.com/packages/githubcli-archive-keyring.gpg \
&& chmod go+r /etc/apt/keyrings/githubcli-archive-keyring.gpg \
Expand Down
85 changes: 67 additions & 18 deletions docs/PI.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,17 @@ A session needs a model Pi can reach, any of:
others). Pi's own code stores it, in its home (below), exactly where its
`/login` would. The model picker then lists that provider's models.
- **A provider profile** added on the phone (the agent's page → AI
providers): any OpenAI-compatible endpoint. A session bound to one runs on
it, and its models are the ones the picker offers.
providers): any OpenAI-compatible endpoint — a provider's own API or a
gateway in front of several (claude-code-router, LiteLLM). A session bound
to one runs on it, and its models are the ones the picker offers. A
profile's model list rarely says how large a model's context is or
whether it reasons, so each model borrows those facts from Pi's own
catalog: matched on the part of its id after the last `/` (a gateway's
`OpenCode Go/deepseek-v4.1-flash` is Pi's `deepseek-v4.1-flash`), from the
provider the route names when Pi has it, else the entry with the smallest
context. That sets the context meter, when Pi compacts, the reasoning
levels and the longest answer. A size the endpoint states wins; a model Pi
does not know runs at 128k context without reasoning.
- **The bridge's environment**: the keys Pi reads itself, such as
`ANTHROPIC_API_KEY` or `OPENROUTER_API_KEY`. Accounts shows them as the
machine's, which only the machine can change.
Expand Down Expand Up @@ -62,24 +71,65 @@ the one its release shipped with, plus your own `models.json`.
## Permissions

Pi has no permission system of its own: it runs every tool call it decides
on. CodeDeck installs an extension into every session —
`<home>/codedeck/codedeck-pi.js`, rewritten when the bridge's version of it
changes and loaded with `-e` — that holds each tool call until the phone
answers:
on. CodeDeck installs an extension into every session — the CodeDeck Pi
extension, `<home>/codedeck/codedeck-pi.js`, rewritten when the bridge's
version of it changes and loaded with `-e` — that holds each tool call until
the phone answers:

- **Ask** (the default): a card for every tool call, except Pi's read-only
tools (`read`, `grep`, `find`, `ls`), which run without one. The card
offers Allow, Allow `<tool>` for this session, and Deny; a denied call
never runs, and Pi tells the model it was denied. A tool that another
extension or an MCP server adds asks like any other.
tools (`read`, `grep`, `find`, `ls`) and the extension's own tools that
change nothing (below), which run without one. The card offers Allow,
Allow `<tool>` for this session, and Deny; a denied call never runs, and
Pi tells the model it was denied. A tool that another extension or an MCP
server adds asks like any other.
- **Auto edit**: Pi's own file tools (`edit`, `write`) also run without a
card; a command, and any tool an extension or an MCP server adds, still
asks.
card; a command, a web fetch, and any tool an extension or an MCP server
adds, still asks.
- **Plan**: the session explores and changes nothing. Read-only tools and
read-only shell commands (`git status`, `git diff`, `cat`, `grep`… without
their writing options, no redirection) run; anything else is refused, and
the model is told to present its plan instead. The plan arrives as a plan
card: approve it to switch the session to Ask or Auto edit, or send it
back with what to change.
- **YOLO**: every tool call runs without a card.

What "for this session" allows is kept by the session only: Pi saves no
rules, so the next session asks again.

## Tools

Pi ships `read`, `bash`, `edit` and `write` on by default. A session also
turns on its `ls`, and its `grep` and `find` where ripgrep and fd are on the
machine (the container image has both; Pi runs offline, so it never
downloads them). The CodeDeck Pi extension adds what a session driven from a
phone needs, shown with the same cards as the other agents:

- **`todo`**: the model's checklist, shown as the session's checklist.
- **`ask`**: up to four questions with options, shown as a question card.
- **`exit_plan`**: the plan card of Plan mode.
- **`task`**: a sub-agent — a second Pi with a fresh context — for one job,
answering with its conclusion; several run in parallel. `explore` has the
read-only tools only, so it changes nothing and never asks; `general` has
the session's tools, and each of its tool calls asks exactly as the
session's own would, on a card that names the sub-agent. Its work shows
under its call.
- **`bash_background`**, **`task_output`**, **`task_stop`**: a command that
keeps running after its call (a dev server, a watcher), whose output the
model reads later. Each is a background task the phone can stop; whatever
still runs when the session's Pi exits is stopped with it.
- **`web_fetch`**: one web page read as text, asking first every time. It
sends no cookies or credentials, follows at most five redirects and
never into a local or private address the first URL did not name, reads
text only, and tells the model the page is data, not instructions.
- **`memory`**: notes about the project that later sessions start with —
one file per note and an index the system prompt carries, in Pi's home
under `codedeck/memory/<project>/`, never in the working tree. Each save
shows on the phone as a `memory` call; a note that looks like it holds a
secret is refused.

The checklist, questions, sub-agents and background shells need no card of
their own beyond what they start.

## Reasoning and messages

Reasoning is Pi's thinking level: Off, Minimal, Low, Medium (Pi's default),
Expand Down Expand Up @@ -115,8 +165,8 @@ and macOS.
The Plugins screen manages Pi's packages, through Pi's own `pi install`,
`pi update` and `pi remove`. A package bundles extensions, skills, prompt
templates and themes from npm (`npm:<package>`), git (`git:github.com/…` or
a URL) or a path, and is how Pi gains tools it does not ship — subagents,
LSP diagnostics and the like come from packages rather than from CodeDeck.
a URL) or a path, and is how Pi gains tools neither it nor CodeDeck ships,
such as LSP diagnostics.
A package runs code with the bridge's permissions: install only ones you
trust. An npm package needs `npm` on the machine (the container image has
it, a release archive does not); `CODEDECK_NPM_REGISTRY` is passed on to it.
Expand All @@ -125,10 +175,9 @@ change load it.

## What this does not have

- **No question or plan tool**: Pi has neither, so the session shows no
question forms or plan cards of its own.
- **No subscription usage** to ask for (the context meter still works), no
background tasks and no saved permission rules.
- **No subscription usage** to ask for (the context meter still works) and
no saved permission rules.
- **No LSP diagnostics** of CodeDeck's own: a Pi package can add them.
- **Accounts need Pi's package**: with `CODEDECK_PI_PATH` naming an
executable rather than a `cli.js`, they cannot be listed or changed.

Expand Down
5 changes: 3 additions & 2 deletions docs/PROTOCOL.md
Original file line number Diff line number Diff line change
Expand Up @@ -1013,8 +1013,9 @@ restart.
The host ships five: `drivers/opencode/`, `drivers/claude/`,
`drivers/deepseek/`, `drivers/qwen/` (those two over the shared `acp/`
machinery, which is what an ACP agent's driver reuses) and `drivers/pi/`
(Pi's own RPC mode, with an extension the driver writes for the
permission gate).
(Pi's own RPC mode, with the CodeDeck Pi extension the driver writes
for the permission gate and the tools Pi lacks — bundled from
`drivers/pi/extension/`).
4. Test it beside the driver, in `src/drivers/<agent>/__tests__/`, like
`drivers/claude/__tests__/claudeDriver.test.ts` and
`drivers/opencode/__tests__/opencodeDriver.test.ts` do, with the
Expand Down
8 changes: 8 additions & 0 deletions packages/agent-host/build.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,15 @@
*
* The Claude Agent SDK stays external: it ships its own CLI binary and must
* resolve its files from node_modules, not from inside a bundle.
*
* The CodeDeck Pi extension is bundled first, on its own, and carried inside
* the host as text (`__CODEDECK_PI_EXTENSION__`): it runs inside Pi's
* process, not the host's, and the driver writes it into Pi's home.
*/
import { build } from 'esbuild';
import { bundlePiExtension } from './src/drivers/pi/extension/bundle.mjs';

const piExtension = await bundlePiExtension();

await build({
entryPoints: ['src/host/main.ts'],
Expand All @@ -17,6 +24,7 @@ await build({
format: 'esm',
outfile: 'dist/main.js',
external: ['@anthropic-ai/claude-agent-sdk'],
define: { __CODEDECK_PI_EXTENSION__: JSON.stringify(piExtension) },
banner: {
js: [
'import { createRequire as __cdxCreateRequire } from "node:module";',
Expand Down
74 changes: 74 additions & 0 deletions packages/agent-host/src/drivers/pi/__tests__/piBackground.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/**
* Background shells: the session's own shell is the default, a real command
* runs to its end in it with its output kept, and a shell the machine does
* not have says which one to use instead. The command runs for real, in
* PowerShell on Windows and in sh elsewhere — the two syntaxes a session's
* shell tool speaks.
*/
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import * as path from 'node:path';
import { describe, expect, it } from 'vitest';
import { backgroundShell, registerBackground, type ShellConfig, type TaskEvent } from '../extension/background';

type Execute = (
toolCallId: string,
params: Record<string, unknown>,
signal: AbortSignal | undefined,
onUpdate: undefined,
ctx: { cwd: string },
) => Promise<{ content: Array<{ text: string }>; details: Record<string, unknown> }>;

function harness(shells: Record<'bash' | 'powershell', () => ShellConfig>, active: string[]) {
const tools = new Map<string, Execute>();
const events: TaskEvent[] = [];
registerBackground(
{ registerTool: ((tool: { name: string; execute: Execute }) => tools.set(tool.name, tool.execute)) as never },
{ shells, active: () => active, report: (event) => events.push(event) },
);
const cwd = mkdtempSync(path.join(tmpdir(), 'codedeck-pi-bg-'));
const run = (name: string, params: Record<string, unknown>) => tools.get(name)!('call_1', params, undefined, undefined, { cwd });
return { run, events };
}

const missing = (): ShellConfig => {
throw new Error('not on this machine');
};

describe('backgroundShell', () => {
it("defaults to the session's own shell, and takes the one asked for", () => {
expect(backgroundShell(undefined, ['read', 'bash', 'powershell'])).toBe('bash');
expect(backgroundShell(undefined, ['read', 'powershell'])).toBe('powershell');
expect(backgroundShell(undefined, ['read'])).toBe('bash');
expect(backgroundShell('powershell', ['bash'])).toBe('powershell');
expect(backgroundShell('zsh', ['powershell'])).toBe('powershell');
});
});

describe('a background shell', () => {
const windows = process.platform === 'win32';
// The shell this machine runs a session's commands in, as Pi resolves it.
const real: ShellConfig = windows
? { shell: 'powershell.exe', args: ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command'] }
: { shell: '/bin/sh', args: ['-c'] };
const command = windows ? 'Write-Output codedeck-bg; Write-Output done' : 'echo codedeck-bg; echo done';

it(`runs to its end in ${windows ? 'PowerShell' : 'sh'}, reporting its start and end and keeping its output`, async () => {
const shells = windows ? { bash: missing, powershell: () => real } : { bash: () => real, powershell: missing };
const { run, events } = harness(shells, windows ? ['read', 'powershell'] : ['read', 'bash']);
const started = await run('bash_background', { command, description: 'Print twice' });
const taskId = String(started.details.taskId);
expect(events[0]).toMatchObject({ kind: 'task', taskId, status: 'running', title: 'Print twice', callId: 'call_1' });

const output = await run('task_output', { id: taskId, wait: 60 });
expect(output.content[0]!.text).toContain('codedeck-bg');
expect(output.content[0]!.text).toContain('exited with code 0');
expect(events.at(-1)).toMatchObject({ taskId, status: 'completed', summary: 'Exited with code 0' });
}, 60_000);

it('says which shell to use when the one it would use is not there', async () => {
const { run, events } = harness({ bash: missing, powershell: () => real }, ['read', 'bash']);
await expect(run('bash_background', { command })).rejects.toThrow(/bash is not available here.*shell: "powershell"/);
expect(events).toHaveLength(0);
});
});
Loading
Loading