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
43 changes: 40 additions & 3 deletions docs/PI.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,43 @@ phone needs, shown with the same cards as the other agents:
The checklist, questions, sub-agents and background shells need no card of
their own beyond what they start.

A file Pi changes with `edit` or `write` shows as a diff under its call:
an edit's lines are the patch Pi applied, with the lines around it; a write
shows the content it wrote.

## Diagnostics

After an `edit` or `write` succeeds, the project's language server checks
the file, and its errors and warnings are added to the tool's result — the
model reads a type error it just made before its next step, and the phone
shows it in the result like the rest. Only servers already on the machine
are used; nothing is installed:

| Files | Server | Found in |
|---|---|---|
| TypeScript, JavaScript | `typescript-language-server` for a TypeScript up to 6.x; TypeScript 7's own `tsc --lsp` | the project's `node_modules`; `typescript-language-server` also on `PATH` |
| Python | `basedpyright-langserver`, else `pyright-langserver` | the project's `.venv`/`venv`, its `node_modules`, then `PATH` |
| Rust | `rust-analyzer` (its own check, then `cargo check`'s) | `PATH` |

The project is the nearest directory above the file with a `tsconfig.json`,
`jsconfig.json` or `package.json`; a `Cargo.toml`; or a `pyproject.toml`,
`setup.py`, `setup.cfg`, `pyrightconfig.json` or `requirements.txt`. A
server starts with the first change in its project and stays for the
session (stopped after ten idle minutes, and with Pi). The first check
waits for it to load the project — about a second for TypeScript and
Python, ten or more for rust-analyzer, at most 30 s — and later ones take
under a second; a check never waits more than 10 s, and a list that came
in late is marked unfinished. A server that is missing or fails to start
is skipped for that project until the session ends: rustup's
`rust-analyzer` without the component installed
(`rustup component add rust-analyzer`) is one.

Reported: the changed file only, errors and warnings (not hints), at most
20. A server runs the project's own build tooling (`cargo check` runs
build scripts) with the bridge's environment, without a provider profile's
token. Set `CODEDECK_PI_LSP=off` in the bridge's environment to turn the
checks off.

## Reasoning and messages

Reasoning is Pi's thinking level: Off, Minimal, Low, Medium (Pi's default),
Expand Down Expand Up @@ -165,8 +202,7 @@ 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 neither it nor CodeDeck ships,
such as LSP diagnostics.
a URL) or a path, and is how Pi gains tools neither it nor CodeDeck ships.
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 @@ -177,7 +213,8 @@ change load it.

- **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.
- **Diagnostics for three languages**: TypeScript/JavaScript, Python and
Rust (above). Another language's checks can come from a Pi package.
- **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
1 change: 1 addition & 0 deletions packages/agent-host/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"@types/node": "^22.10.0",
"esbuild": "^0.25.0",
"typescript": "^5.7.0",
"typescript-language-server": "6.1.0",
"vitest": "^3.0.0"
},
"license": "MIT"
Expand Down
40 changes: 2 additions & 38 deletions packages/agent-host/src/drivers/opencode/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ import type { FileDiffInfo } from '@opencode/client';
import { todosOf, toolLocations } from '../../sdk/tools';
import { opencodeTool } from './tools';
import {
MAX_DIFF_LINE_CHARS,
MAX_DIFF_LINES,
boundedDiff,
patchLines,
toDiffLines,
truncateToolResult,
type DiffPayload,
Expand Down Expand Up @@ -266,42 +266,6 @@ function toolResultEntries(event: Extract<OpenCodeEvent, { type: 'tool-result' }

// --- diffs ---

/** Lines of a unified diff. File headers (`diff`, `index`, `---`, `+++`) are
* only skipped before the first hunk: inside a hunk, `---x` is the deletion
* of the line `--x`, not a header. Hunk headers and "\ No newline" markers
* carry no line content. */
function patchLines(patch: string): DiffLine[] {
const out: DiffLine[] = [];
let inHunk = false;
for (const line of patch.split('\n')) {
if (line.startsWith('@@')) {
inHunk = true;
continue;
}
if (!inHunk || line.startsWith('\\')) continue;
if (line.startsWith('+')) out.push({ type: 'add', text: truncateDiffLine(line.slice(1)) });
else if (line.startsWith('-')) out.push({ type: 'del', text: truncateDiffLine(line.slice(1)) });
else if (line.startsWith(' ')) out.push({ type: 'context', text: truncateDiffLine(line.slice(1)) });
}
return out;
}

function truncateDiffLine(line: string): string {
return line.length > MAX_DIFF_LINE_CHARS ? line.slice(0, MAX_DIFF_LINE_CHARS) + '…' : line;
}

/** A diff payload inside the shared wire caps; `null` when there are no
* lines to show. */
function boundedDiff(path: string, lines: DiffLine[]): DiffPayload | null {
if (lines.length === 0) return null;
const truncated = lines.length > MAX_DIFF_LINES;
return {
path,
lines: truncated ? lines.slice(0, MAX_DIFF_LINES) : lines,
...(truncated ? { truncated: true } : {}),
};
}

/** One file OpenCode reports as changed, as a card: its unified patch turned
* into lines. `null` when the patch carries no line content at all (only
* counts) — there is nothing to render then. */
Expand Down
195 changes: 195 additions & 0 deletions packages/agent-host/src/drivers/pi/__tests__/fakeLanguageServer.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
/**
* A language server for the CodeDeck Pi extension's diagnostics tests, run
* as its own process: `node fakeLanguageServer.mjs <mode>`.
*
* Each mode does only what the real server was seen doing, run by hand
* against it (2026-11-18, the frames logged around didOpen/didChange/didSave):
*
* - `push`: typescript-language-server 6.1.0 with TypeScript 5.9 — no pull;
* a `$/progress` begin/end around its first project load; then one
* `publishDiagnostics` per change, WITHOUT a version and with the URI in VS
* Code's spelling (`file:///c%3A/…` for `file:///C:/…`).
* - `push-versioned`: Pyright / basedpyright 1.40 — no pull advertised; a
* progress (created with `window/workDoneProgress/create`) around each
* analysis, then a push WITH the version; `workspace/configuration`
* requests, numbered from 0.
* - `pull`: TypeScript 7.0's `tsc --lsp` — `diagnosticProvider`, answers
* `textDocument/diagnostic` at once, never pushes.
* - `ra`: rust-analyzer 1.99 — answers a pull, but with an empty list while
* its workspace loads under progress; after a save, `cargo check` runs
* under the `rust-analyzer/flycheck/0` progress, its results arrive as a
* versioned push (worded differently, same code), and then it sends
* `workspace/diagnostic/refresh` with no params.
* - `crash`: rustup's `rust-analyzer` proxy with the component not installed
* — prints an error and exits 1.
* - `silent`: a server that never reports, for the deadline.
*
* And faults no real server was seen making, for the client's own guards:
* `null-frame` sends a frame whose body is `null` before each answer;
* `mute` never answers `initialize`; `slow-first` is `push-versioned` with
* no progress and slow pushes: the first after 600 ms, the rest after
* 1000 ms.
*
* Diagnostics come from the document's text: a line holding `ERROR <msg>` is
* an error at that word, `WARN` a warning, `HINT` a hint, and `ENV <NAME>`
* an error saying whether NAME is in this process's environment.
*/
const mode = process.argv[2] ?? 'push';
if (mode === 'crash') {
process.stderr.write("error: Unknown binary 'rust-analyzer' in official toolchain\n");
process.exit(1);
}

let buffer = Buffer.alloc(0);
let nextId = 0;
let loaded = mode !== 'ra';
let firstLoad = true;
let pushes = 0;
// `null-frame` is `pull` with its fault.
const pulls = mode === 'pull' || mode === 'null-frame';
const docs = new Map();

function send(message) {
if (mode === 'null-frame') process.stdout.write('Content-Length: 4\r\n\r\nnull');
const body = Buffer.from(JSON.stringify({ jsonrpc: '2.0', ...message }), 'utf8');
process.stdout.write(`Content-Length: ${body.length}\r\n\r\n`);
process.stdout.write(body);
}
const progress = (token, kind, title) => send({ method: '$/progress', params: { token, value: kind === 'begin' ? { kind, title } : { kind } } });
const later = (ms, fn) => setTimeout(fn, ms);

/** VS Code's spelling of a file URI: lower-case drive, colon encoded. */
function vscodeUri(uri) {
return uri.replace(/^file:\/\/\/([A-Za-z]):/, (_, drive) => `file:///${drive.toLowerCase()}%3A`);
}

function diagnosticsOf(text, source) {
const out = [];
text.split('\n').forEach((line, index) => {
const match = /\b(ERROR|WARN|HINT|ENV)\s+(\S.*)$/.exec(line);
if (!match) return;
const severity = { ERROR: 1, WARN: 2, HINT: 4, ENV: 1 }[match[1]];
const message = match[1] === 'ENV' ? `${match[2]} is ${process.env[match[2]] === undefined ? 'unset' : 'set'}` : match[2];
out.push({
range: { start: { line: index, character: match.index }, end: { line: index, character: line.length } },
severity,
message,
source,
code: 'E1',
});
});
return out;
}

function changed(uri) {
const doc = docs.get(uri);
if (mode === 'push') {
const token = 'tls-load';
if (firstLoad) {
firstLoad = false;
progress(token, 'begin', 'Initializing JS/TS language features…');
later(80, () => progress(token, 'end'));
}
later(120, () => send({ method: 'textDocument/publishDiagnostics', params: { uri: vscodeUri(uri), diagnostics: diagnosticsOf(doc.text, 'typescript') } }));
} else if (mode === 'push-versioned' || mode === 'slow-first') {
const token = `pyright-${++nextId}`;
const reportsProgress = mode !== 'slow-first';
if (reportsProgress) {
send({ id: nextId, method: 'window/workDoneProgress/create', params: { token } });
progress(token, 'begin', '');
}
const version = doc.version;
const text = doc.text;
later(mode === 'slow-first' ? (pushes++ === 0 ? 600 : 1000) : 60, () => {
if (reportsProgress) progress(token, 'end');
send({ method: 'textDocument/publishDiagnostics', params: { uri: vscodeUri(uri), version, diagnostics: diagnosticsOf(text, 'Pyright') } });
});
}
}

function saved(uri) {
if (mode !== 'ra') return;
const doc = docs.get(uri);
const token = 'rust-analyzer/flycheck/0';
send({ id: ++nextId, method: 'window/workDoneProgress/create', params: { token } });
progress(token, 'begin', 'cargo check');
later(150, () => {
const checked = diagnosticsOf(doc.text, 'rustc').map((d) => ({ ...d, message: `${d.message} (as rustc words it)` }));
send({ method: 'textDocument/publishDiagnostics', params: { uri, version: doc.version, diagnostics: checked } });
progress(token, 'end');
send({ id: ++nextId, method: 'workspace/diagnostic/refresh' });
});
}

function handle(message) {
const { id, method, params } = message;
if (method === undefined) return; // a response to one of ours
switch (method) {
case 'initialize': {
if (mode === 'mute') return;
const pull = pulls || mode === 'ra';
send({ id, result: { capabilities: { textDocumentSync: 2, ...(pull ? { diagnosticProvider: { interFileDependencies: true, workspaceDiagnostics: false } } : {}) } } });
return;
}
case 'initialized':
if (mode === 'push-versioned') {
send({ id: 0, method: 'workspace/configuration', params: { items: [{ section: 'python' }] } });
}
return;
case 'textDocument/didOpen': {
const { uri, version, text } = params.textDocument;
docs.set(uri, { version, text });
if (mode === 'ra' && !loaded) {
// The workspace loads under progress; until it has, a pull is empty.
progress('rustAnalyzer/Fetching', 'begin', 'Fetching');
later(200, () => {
loaded = true;
progress('rustAnalyzer/Fetching', 'end');
});
}
changed(uri);
return;
}
case 'textDocument/didChange': {
const { uri, version } = params.textDocument;
docs.set(uri, { version, text: params.contentChanges.at(-1).text });
changed(uri);
return;
}
case 'textDocument/didSave':
saved(params.textDocument.uri);
return;
case 'textDocument/diagnostic': {
if (!pulls && mode !== 'ra') {
send({ id, error: { code: -32601, message: 'Unhandled method textDocument/diagnostic' } });
return;
}
const doc = docs.get(params.textDocument.uri);
const items = doc && loaded ? diagnosticsOf(doc.text, mode === 'ra' ? 'rust-analyzer' : 'ts') : [];
send({ id, result: { kind: 'full', items } });
return;
}
case 'shutdown':
send({ id, result: null });
return;
case 'exit':
process.exit(0);
return;
default:
if (id !== undefined) send({ id, error: { code: -32601, message: `Unhandled method ${method}` } });
}
}

process.stdin.on('data', (chunk) => {
buffer = Buffer.concat([buffer, chunk]);
for (;;) {
const end = buffer.indexOf('\r\n\r\n');
if (end < 0) return;
const length = Number(/Content-Length: (\d+)/i.exec(buffer.subarray(0, end).toString())[1]);
if (buffer.length < end + 4 + length) return;
const message = JSON.parse(buffer.subarray(end + 4, end + 4 + length).toString('utf8'));
buffer = buffer.subarray(end + 4 + length);
handle(message);
}
});
process.stdin.on('end', () => process.exit(0));
65 changes: 65 additions & 0 deletions packages/agent-host/src/drivers/pi/__tests__/piDriver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,71 @@ describe('PiSession background tasks', () => {
});
});

describe('PiSession file changes', () => {
const end = (toolCallId: string, toolName: string, details: unknown, isError = false) => ({
type: 'tool_execution_end',
toolCallId,
toolName,
result: { content: [{ type: 'text', text: isError ? 'Could not find the text' : 'Done' }], details },
isError,
});
const diffs = (ctx: Parameters<typeof entries>[0]) => entries(ctx).filter((entry) => entry.entryType === 'diff');

it('shows an edit as the diff of the patch Pi applied, context lines included', async () => {
const h = withDriver();
const ctx = await ready(h);
h.fake.emit({ type: 'tool_execution_start', toolCallId: 'call_e', toolName: 'edit', args: { path: 'src/a.ts', edits: [{ oldText: 'b', newText: 'c' }] } });
// The shape Pi's edit-diff.js formats: file headers, then one hunk.
const patch = '--- src/a.ts\n+++ src/a.ts\n@@ -1,3 +1,3 @@\n a\n-b\n+c\n d\n';
h.fake.emit(end('call_e', 'edit', { diff: '…', patch, firstChangedLine: 2 }));
await ctx.waitFor((event) => event.type === 'entries' && event.entries.some((entry) => entry.entryType === 'diff'));
expect(diffs(ctx)).toEqual([
expect.objectContaining({
path: 'src/a.ts',
callId: 'call_e',
lines: [
{ type: 'context', text: 'a' },
{ type: 'del', text: 'b' },
{ type: 'add', text: 'c' },
{ type: 'context', text: 'd' },
],
}),
]);
});

it('shows a write as its content added, and no card for a change that failed', async () => {
const h = withDriver();
const ctx = await ready(h);
h.fake.emit({ type: 'tool_execution_start', toolCallId: 'call_w', toolName: 'write', args: { path: 'b.py', content: 'x = 1\ny = 2' } });
h.fake.emit(end('call_w', 'write', undefined));
h.fake.emit({ type: 'tool_execution_start', toolCallId: 'call_f', toolName: 'edit', args: { path: 'c.rs', edits: [] } });
h.fake.emit(end('call_f', 'edit', undefined, true));
await ctx.waitFor((event) => event.type === 'entries' && event.entries.some((entry) => entry.entryType === 'tool_result' && entry.callId === 'call_f'));
expect(diffs(ctx)).toEqual([
expect.objectContaining({ path: 'b.py', callId: 'call_w', lines: [{ type: 'add', text: 'x = 1' }, { type: 'add', text: 'y = 2' }] }),
]);
});

it("shows a sub-agent's edit under its parent's call", async () => {
const h = withDriver();
const ctx = await ready(h);
const subagent = { label: 'general', parentCallId: 'call_task' };
const update = (seq: number, event: Record<string, unknown>) => ({
type: 'tool_execution_update',
toolCallId: 'call_task',
toolName: 'task',
partialResult: { content: [], details: { subagent, seq, event } },
});
h.fake.emit({ type: 'tool_execution_start', toolCallId: 'call_task', toolName: 'task', args: { description: 'x', prompt: 'y', agent: 'general' } });
h.fake.emit(update(1, { kind: 'tool_call', callId: 'c1', toolName: 'edit', args: { path: 'a.ts', edits: [] } }));
h.fake.emit(update(2, { kind: 'tool_result', callId: 'c1', text: 'Done', isError: false, patch: '--- a.ts\n+++ a.ts\n@@ -1 +1 @@\n-x\n+y\n' }));
await ctx.waitFor((event) => event.type === 'entries' && event.entries.some((entry) => entry.entryType === 'diff'));
expect(diffs(ctx)).toEqual([
expect.objectContaining({ path: 'a.ts', callId: 'call_task/c1', subagent, lines: [{ type: 'del', text: 'x' }, { type: 'add', text: 'y' }] }),
]);
});
});

describe('PiSession checklist', () => {
it('shows a todo call as the checklist, not as a tool row', async () => {
const h = withDriver();
Expand Down
Loading
Loading