Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(grid): Pi, through a config directory the daemon owns

Dev jacob8993e0c7ae6d
diff --git a/cli/README.md b/cli/README.md
index 6d171d275..ff5091494 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -130,8 +130,9 @@ claude under a terminal backend ──writes──▶ ~/.claude/projects/**.json
session that environment with `new-session -e`, so the credential never appears in the engine's
argv. Six engines have a documented way to be pointed somewhere else and are supported through it:
**claude** (`ANTHROPIC_BASE_URL`), **codex** (`-c model_providers.grid.*`, key via `env_key`),
- **opencode** and **hermes** (`OPENAI_BASE_URL`), **grok** (`GROK_MODELS_BASE_URL`) and **copilot**
- (`COPILOT_PROVIDER_BASE_URL`). Every other engine is **refused** with `GRID_ENGINE_UNSUPPORTED`
+ **opencode** and **hermes** (`OPENAI_BASE_URL`), **grok** (`GROK_MODELS_BASE_URL`), **copilot**
+ (`COPILOT_PROVIDER_BASE_URL`) and **pi** (a private config directory via `PI_CODING_AGENT_DIR`,
+ so the user's own `~/.pi` is never touched). Every other engine is **refused** with `GRID_ENGINE_UNSUPPORTED`
and a reason specific to it — some talk only to their own service, some need a provider block
written into a dotfile this daemon will not edit — rather than quietly started on its own login.
Needs tmux ≥ 3.2; an older one is refused as `TMUX_TOO_OLD_FOR_GRID`. See `src/lib/gridLaunch.ts`.
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index f3d4cc285..13fab5293 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -44,6 +44,7 @@ import { AuthSessionError, AuthSessionManager, clearAuthSession, readAuthSession
import { ENGINE_CLI_COMMANDS, ENGINES } from './lib/engineBin.js'
import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell, interactiveEngineShell } from './lib/engineLaunch.js'
import { buildGridEngineLaunch, describeGridLaunch } from './lib/gridLaunch.js'
+import { writeGridConfigDir } from './lib/gridConfigDir.js'
import { tmuxSupportsSessionEnv, TMUX_SESSION_ENV_MIN } from './lib/tmuxVersion.js'
import { clearDeleted, isRecentlyDeleted, markDeleted } from './lib/deletedSessions.js'
import { terminateDeletedAgent } from './lib/deleteAgentFallback.js'
@@ -2706,6 +2707,10 @@ async function runForeground(session: AuthSession): Promise<void> {
} catch {
return { ok: false, error: 'CWD_NOT_FOUND' }
}
+ // Harness-created sessions are easy to distinguish from a user's organic tmux sessions while
+ // retaining the engine and a collision-resistant creation suffix for diagnostics. Computed
+ // before the grid block because a file-configured engine keys its config directory on it.
+ const label = `harness-${engine}-${Date.now()}`.replace(/[^A-Za-z0-9_-]/g, '-')
// A grid is the user's answer to "where should this run", so every way of not honouring it is a
// refusal rather than a fallback — an agent silently started on the engine's own login spends the
// wrong account and looks identical to one that worked.
@@ -2724,14 +2729,23 @@ async function runForeground(session: AuthSession): Promise<void> {
console.warn(`[agent] create ${engine} refused · ${detail}`)
return { ok: false, error: 'TMUX_TOO_OLD_FOR_GRID', detail }
}
- gridLaunch = built.launch
+ gridLaunch = { env: { ...built.launch.env }, args: built.launch.args }
+ // An engine whose provider lives in a file gets a directory this daemon owns, never the
+ // user's own dotfiles. The label is unique per creation, so two agents never share one.
+ if (built.launch.configDir) {
+ const { envVar, files } = built.launch.configDir
+ try {
+ gridLaunch.env[envVar] = await writeGridConfigDir(label, files)
+ } catch (error) {
+ const detail = `could not write ${engine}'s grid configuration · ${error instanceof Error ? error.message : error}`
+ console.warn(`[agent] create ${engine} refused · ${detail}`)
+ return { ok: false, error: 'GRID_CONFIG_FAILED', detail }
+ }
+ }
// Named in the log because the pane itself gives nothing away: the engine looks exactly like a
// normally launched one. The key is never printed.
console.log(describeGridLaunch(engine, grid))
}
- // Harness-created sessions are easy to distinguish from a user's organic tmux sessions while
- // retaining the engine and a collision-resistant creation suffix for diagnostics.
- const label = `harness-${engine}-${Date.now()}`.replace(/[^A-Za-z0-9_-]/g, '-')
const launchOptions = { bypassPermission, extraArgs: gridLaunch?.args }
const command = buildEngineCommandArgv(engine, launchOptions)
const argv = buildEngineLaunchArgv(engine, launchOptions)
@@ -2902,12 +2916,24 @@ async function runForeground(session: AuthSession): Promise<void> {
// Nothing may type into the pane while it is being replaced.
const release = acquireTerminalControl(session.agentId)
if (!release) return { ok: false, error: 'AGENT_BUSY' }
+ const gridEnv: Record<string, string> = { ...built.launch.env }
+ if (built.launch.configDir) {
+ // Keyed on the agent, so moving the same agent between grids rewrites one directory rather
+ // than leaving a trail of them.
+ const { envVar, files } = built.launch.configDir
+ try {
+ gridEnv[envVar] = await writeGridConfigDir(session.agentId, files)
+ } catch (error) {
+ const detail = `could not write ${session.engine}'s grid configuration · ${error instanceof Error ? error.message : error}`
+ return { ok: false, error: 'GRID_CONFIG_FAILED', detail }
+ }
+ }
try {
const launchOptions = { resumeSessionId: session.sessionId || null, extraArgs: built.launch.args }
const respawned = await tmuxBackend.respawn(pane, {
...(session.cwd ? { cwd: session.cwd } : {}),
command: buildEngineLaunchArgv(session.engine, launchOptions),
- env: built.launch.env,
+ env: gridEnv,
})
if (respawned.state !== 'succeeded') {
console.warn(`[grid] retarget ${sid(session.agentId)} failed · ${respawned.reason}`)
diff --git a/cli/src/lib/gridAssignment.spec.ts b/cli/src/lib/gridAssignment.spec.ts
index 1c895e7a2..709026a68 100644
--- a/cli/src/lib/gridAssignment.spec.ts
+++ b/cli/src/lib/gridAssignment.spec.ts
@@ -1,7 +1,10 @@
-import { describe, expect, it } from 'vitest'
-import { assignmentMatches, classifyGridAssignment } from './gridAssignment.js'
+import { afterEach, describe, expect, it } from 'vitest'
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { assignmentMatches, classifyGridAssignment, readPiGridAssignment } from './gridAssignment.js'
import { buildGridEngineLaunch, gridCapableEngines, type GridLaunchOverride } from './gridLaunch.js'
-import { parsePsEnviron } from './processEnv.js'
+import { clearProcessEnvCache, parsePsEnviron } from './processEnv.js'
const NETWORK_ID = 'grid-3378218621364f16'
const RELAY = `https://grid.autonomous.ai/${NETWORK_ID}/relay`
@@ -20,6 +23,9 @@ describe('classifyGridAssignment', () => {
// The point of the round trip: the probe and the launcher must use the SAME knob per engine, or
// an agent that IS on a grid reports as being on none and gets pointlessly restarted.
for (const engine of gridCapableEngines()) {
+ // Pi's endpoint is in a file rather than the process, so it round-trips through the probe
+ // below instead — this one only covers what a process carries.
+ if (engine === 'pi') continue
const built = buildGridEngineLaunch(engine, OVERRIDE)
expect(built.ok).toBe(true)
if (!built.ok) continue
@@ -33,6 +39,7 @@ describe('classifyGridAssignment', () => {
it('never carries the credential out of the process', () => {
for (const engine of gridCapableEngines()) {
+ if (engine === 'pi') continue
const built = buildGridEngineLaunch(engine, OVERRIDE)
if (!built.ok) continue
const assignment = classifyGridAssignment(engine, built.launch.env, built.launch.args.join(' '))
@@ -76,6 +83,60 @@ describe('classifyGridAssignment', () => {
})
})
+describe('Pi, whose endpoint lives in a file', () => {
+ const dirs: string[] = []
+ afterEach(() => {
+ clearProcessEnvCache()
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
+ })
+
+ /** Writes the launch's own config files where the probe will look for them. */
+ function materialize(): { dir: string; args: string } {
+ const built = buildGridEngineLaunch('pi', OVERRIDE)
+ if (!built.ok) throw new Error(built.detail)
+ const dir = mkdtempSync(join(tmpdir(), 'pi-grid-'))
+ dirs.push(dir)
+ for (const file of built.launch.configDir!.files) writeFileSync(join(dir, file.name), file.content)
+ return { dir, args: `pi ${built.launch.args.join(' ')}` }
+ }
+
+ it('round-trips: what the launcher wrote is what the probe reads back', async () => {
+ const { dir, args } = materialize()
+ // Parsed from a real macOS `ps eww` line — argv first, then the environment — so the shape the
+ // probe is handed at runtime is the shape under test.
+ const env = parsePsEnviron(`${args} PI_CODING_AGENT_DIR=${dir} GRID_API_KEY=gridkey-secret`)
+ await expect(readPiGridAssignment(env, args)).resolves.toEqual({
+ baseUrl: RELAY_V1,
+ model: 'GLM-4.7-Flash',
+ })
+ await expect(readPiGridAssignment(env, args)).resolves.toSatisfy(
+ (a: { baseUrl: string; model: string | null }) => assignmentMatches(a, NETWORK_ID, 'GLM-4.7-Flash'),
+ )
+ })
+
+ it('a config directory that is gone reads as unknown, not as fine', async () => {
+ const { dir, args } = materialize()
+ const env = parsePsEnviron(`${args} PI_CODING_AGENT_DIR=${dir}`)
+ rmSync(dir, { recursive: true, force: true })
+ // Nothing to read → null → the app offers a move rather than claiming the agent is in place.
+ await expect(readPiGridAssignment(env, args)).resolves.toBeNull()
+ })
+
+ it('reads nothing when the pane was never given a config directory', async () => {
+ const { args } = materialize()
+ await expect(readPiGridAssignment({}, args)).resolves.toBeNull()
+ })
+
+ it('will not call a provider pointed somewhere else a grid', async () => {
+ const { dir, args } = materialize()
+ writeFileSync(join(dir, 'models.json'), JSON.stringify({
+ providers: { grid: { baseUrl: 'https://api.openai.com/v1' } },
+ }))
+ const env = parsePsEnviron(`${args} PI_CODING_AGENT_DIR=${dir}`)
+ await expect(readPiGridAssignment(env, args)).resolves.toBeNull()
+ })
+})
+
describe('assignmentMatches', () => {
const assignment = { baseUrl: RELAY, model: 'GLM-4.7-Flash' }
diff --git a/cli/src/lib/gridAssignment.ts b/cli/src/lib/gridAssignment.ts
index f1a50e230..1827d16a7 100644
--- a/cli/src/lib/gridAssignment.ts
+++ b/cli/src/lib/gridAssignment.ts
@@ -18,6 +18,8 @@
* endpoint and the model, both of which the app already knows because it chose them.
*/
+import { readFile } from 'node:fs/promises'
+import { join } from 'node:path'
import type { AgentEngine } from '../engines/types.js'
import { readProcessEnv } from './processEnv.js'
import type { ProcessIdentity } from './registry.js'
@@ -49,6 +51,15 @@ const MODEL_VAR: Partial<Record<AgentEngine, string>> = {
/** Engines whose model was written into argv as `-m <model>` rather than an environment variable. */
const MODEL_IN_ARGV = new Set<AgentEngine>(['codex', 'grok'])
+/**
+ * Pi's endpoint is in neither its environment nor its argv — it is in the `models.json` inside the
+ * config directory `PI_CODING_AGENT_DIR` points at. So that is where it is read from, because the
+ * alternative is to trust a note we wrote ourselves about what we did.
+ */
+const PI_CONFIG_DIR_VAR = 'PI_CODING_AGENT_DIR'
+/** `--model grid/<model>` — how Pi is told which provider and model to use. */
+const PI_ARGV_MODEL = /(?:^|\s)--model\s+([A-Za-z0-9_-]+)\/(\S+)/
+
/** `-c model_providers.<name>.base_url="…"` — how Codex's endpoint is written, so how it is read. */
const CODEX_BASE_URL = /model_providers\.[A-Za-z0-9_-]+\.base_url=(?:"([^"]+)"|(\S+))/
const ARGV_MODEL = /(?:^|\s)-m\s+(\S+)/
@@ -90,6 +101,36 @@ export function classifyGridAssignment(
return { baseUrl, model: model || null }
}
+/**
+ * Pi's provider block, read out of the config directory its process was pointed at.
+ *
+ * Exported so a spec can drive the real read against real files: the process half of the probe
+ * cannot be faked (an environment is fixed at exec), and a round trip that re-implemented this
+ * would prove nothing about the code that runs.
+ *
+ * Every failure lands on null — an unreadable or rewritten directory is "we cannot tell", which the
+ * caller already treats as "not on the grid you picked".
+ */
+export async function readPiGridAssignment(
+ processEnv: Record<string, string>,
+ args: string,
+): Promise<GridAssignment | null> {
+ const dir = processEnv[PI_CONFIG_DIR_VAR]?.trim()
+ if (!dir) return null
+ const model = PI_ARGV_MODEL.exec(args)
+ if (!model) return null
+ try {
+ const raw = JSON.parse(await readFile(join(dir, 'models.json'), 'utf8')) as {
+ providers?: Record<string, { baseUrl?: unknown }>
+ }
+ const baseUrl = raw.providers?.[model[1]]?.baseUrl
+ if (typeof baseUrl !== 'string' || !isGridUrl(baseUrl)) return null
+ return { baseUrl, model: model[2] }
+ } catch {
+ return null
+ }
+}
+
/**
* Read one live engine process's grid.
*
@@ -104,7 +145,9 @@ export async function probeGridAssignment(
args = '',
): Promise<GridAssignment | null> {
const processEnv = await readProcessEnv(identity)
- return processEnv ? classifyGridAssignment(engine, processEnv, args) : null
+ if (!processEnv) return null
+ if (engine === 'pi') return await readPiGridAssignment(processEnv, args)
+ return classifyGridAssignment(engine, processEnv, args)
}
/** Is this agent already where `networkId` is served, on `model`? */
diff --git a/cli/src/lib/gridConfigDir.ts b/cli/src/lib/gridConfigDir.ts
new file mode 100644
index 000000000..dc9646ef8
--- /dev/null
+++ b/cli/src/lib/gridConfigDir.ts
@@ -0,0 +1,64 @@
+/**
+ * The private config directory an engine is given when its provider lives in a file.
+ *
+ * Pi is the case this exists for: it reads providers out of a directory, and `PI_CODING_AGENT_DIR`
+ * moves that directory. Rather than edit `~/.pi/agent/models.json` — someone else's file, which
+ * would outlive the agent and survive every uninstall — the daemon writes a directory it owns and
+ * points the engine at that. The user's own configuration is never opened, and deleting the
+ * directory undoes the whole thing.
+ *
+ * Nothing written here is secret. A provider block references the key through an environment
+ * variable; the key itself only ever lives in the process environment.
+ */
+
+import { mkdir, readdir, rm, stat, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { env } from '../config/env.js'
+import type { GridConfigFile } from './gridLaunch.js'
+
+/** Everything this module owns lives under one root, so pruning can be confident about what it is. */
+export function gridConfigRoot(): string {
+ return join(env.ADAPTER_DATA_DIR, 'grid-engine-config')
+}
+
+/**
+ * A directory that has not been touched in this long belongs to an agent that is long gone.
+ *
+ * These are a few hundred bytes each, so this is tidiness rather than reclamation — but a directory
+ * per agent ever created, kept forever, is the kind of thing that is only ever noticed years later.
+ */
+const PRUNE_AFTER_MS = 30 * 24 * 60 * 60 * 1000
+
+/** Only `[A-Za-z0-9_-]` survives, so a key can never climb out of the root. */
+function safeKey(key: string): string {
+ return key.replace(/[^A-Za-z0-9_-]/g, '-').slice(0, 96) || 'agent'
+}
+
+async function prune(root: string): Promise<void> {
+ const cutoff = Date.now() - PRUNE_AFTER_MS
+ const entries = await readdir(root, { withFileTypes: true }).catch(() => [])
+ await Promise.all(entries.map(async (entry) => {
+ if (!entry.isDirectory()) return
+ const path = join(root, entry.name)
+ const info = await stat(path).catch(() => null)
+ if (info && info.mtimeMs < cutoff) await rm(path, { recursive: true, force: true }).catch(() => {})
+ }))
+}
+
+/**
+ * Write `files` into this agent's own directory and return its path.
+ *
+ * Rewriting is the normal case, not an error: moving an agent to a different grid writes the same
+ * directory again with the new provider, which is exactly what a respawn should read.
+ */
+export async function writeGridConfigDir(key: string, files: readonly GridConfigFile[]): Promise<string> {
+ const root = gridConfigRoot()
+ const dir = join(root, safeKey(key))
+ await mkdir(dir, { recursive: true, mode: 0o700 })
+ // Best-effort and never in the way: a failed prune must not cost a launch.
+ await prune(root).catch(() => {})
+ for (const file of files) {
+ await writeFile(join(dir, file.name), file.content, { mode: 0o600 })
+ }
+ return dir
+}
diff --git a/cli/src/lib/gridLaunch.spec.ts b/cli/src/lib/gridLaunch.spec.ts
index 2fa350b4e..face5c80d 100644
--- a/cli/src/lib/gridLaunch.spec.ts
+++ b/cli/src/lib/gridLaunch.spec.ts
@@ -136,11 +136,48 @@ describe('the launch each engine gets', () => {
})
})
- it('never puts the key in argv, for any engine', () => {
+ it('gives Pi a config directory of ours, never the user\'s own', () => {
+ const launch = launchOf('pi')
+ expect(launch.env).toEqual({ GRID_API_KEY: WIRE.apiKey })
+ expect(launch.args).toEqual(['--model', 'grid/GLM-4.7-Flash'])
+ const configDir = launch.configDir
+ expect(configDir?.envVar).toBe('PI_CODING_AGENT_DIR')
+ const models = configDir?.files.find((file) => file.name === 'models.json')
+ expect(models).toBeDefined()
+ const parsed = JSON.parse(models!.content) as {
+ providers: Record<string, { baseUrl: string; api: string; apiKey: string }>
+ }
+ expect(parsed.providers.grid.baseUrl).toBe(RELAY_V1)
+ // `openai-completions` makes Pi post to <base>/chat/completions, which the relay serves.
+ expect(parsed.providers.grid.api).toBe('openai-completions')
+ // An env REFERENCE. Writing the key itself would put a live credential on disk, outliving the
+ // agent and every reason it existed.
+ expect(parsed.providers.grid.apiKey).toBe('$GRID_API_KEY')
+ expect(models!.content).not.toContain(WIRE.apiKey)
+ })
+
+ it('hands Pi back the skills the redirection would otherwise hide', () => {
+ const settings = launchOf('pi').configDir?.files.find((file) => file.name === 'settings.json')
+ const parsed = JSON.parse(settings!.content) as Record<string, unknown>
+ expect((parsed.skills as string[])[0]).toContain('.pi')
+ // The Grid app set `defaultProjectTrust: always` because it drove Pi headless with nobody there
+ // to answer. Here a person is sitting in front of the pane, so the trust prompt stays theirs.
+ expect(parsed).not.toHaveProperty('defaultProjectTrust')
+ })
+
+ it('refuses Pi without a model — its provider block has to name one', () => {
+ expect(buildGridEngineLaunch('pi', OVERRIDE)).toMatchObject({ ok: false, error: 'GRID_MODEL_REQUIRED' })
+ })
+
+ it('never puts the key in argv, or on disk, for any engine', () => {
// `ps` is world-readable for the life of the process; the environment is not.
for (const engine of gridCapableEngines()) {
- expect(launchOf(engine).args.join(' ')).not.toContain(WIRE.apiKey)
- expect(Object.values(launchOf(engine).env)).toContain(WIRE.apiKey)
+ const launch = launchOf(engine)
+ expect(launch.args.join(' '), engine).not.toContain(WIRE.apiKey)
+ expect(Object.values(launch.env), engine).toContain(WIRE.apiKey)
+ for (const file of launch.configDir?.files ?? []) {
+ expect(file.content, `${engine}/${file.name}`).not.toContain(WIRE.apiKey)
+ }
}
})
@@ -176,7 +213,7 @@ describe('the engines that cannot', () => {
it('lists exactly the engines with a verified vendor contract', () => {
expect([...gridCapableEngines()].sort())
- .toEqual(['claude', 'codex', 'copilot', 'grok', 'hermes', 'opencode'])
+ .toEqual(['claude', 'codex', 'copilot', 'grok', 'hermes', 'opencode', 'pi'])
})
})
diff --git a/cli/src/lib/gridLaunch.ts b/cli/src/lib/gridLaunch.ts
index 1b30308a4..78272912f 100644
--- a/cli/src/lib/gridLaunch.ts
+++ b/cli/src/lib/gridLaunch.ts
@@ -37,8 +37,15 @@
* somewhere other than where the user said, spend the wrong account, and look like it worked.
*/
+import { homedir } from 'node:os'
+import { join } from 'node:path'
import type { AgentEngine } from '../engines/types.js'
+/** Where Pi keeps the skills the user manages, handed back through our own settings.json. */
+function userPiSkillsDir(): string {
+ return join(homedir(), '.pi', 'agent', 'skills')
+}
+
/** What the desktop sends, once validated. Mirrors `GridAgentOverride` in the desktop app. */
export interface GridLaunchOverride {
networkId: string
@@ -142,12 +149,30 @@ export function anthropicBaseUrl(baseUrl: string): string {
return trimmed.endsWith('/v1') ? trimmed.slice(0, -'/v1'.length) : trimmed
}
+/** One file to write into the per-agent config directory a launch is given. */
+export interface GridConfigFile {
+ /** File name inside the directory. Never a path — this writes one flat directory. */
+ name: string
+ content: string
+}
+
/** How one engine is launched against a grid. */
export interface GridEngineLaunch {
/** Layered over the engine's inherited environment. This is where the key goes, always. */
env: Record<string, string>
/** Appended to the engine's argv. Never carries the key — `ps` is world-readable. */
args: string[]
+ /**
+ * For an engine that reads its provider out of a config directory rather than an environment
+ * variable: files the daemon writes into a directory IT owns, and the variable that points the
+ * engine at that directory.
+ *
+ * This is not "editing the user's dotfiles" — the point of the indirection is that it never
+ * touches them. The engine gets a private configuration for this agent, the user's own stays
+ * exactly as they left it, and deleting the directory undoes everything. No file written here may
+ * contain the key; Pi's provider block references an environment variable instead.
+ */
+ configDir?: { envVar: string; files: GridConfigFile[] }
}
interface GridEngineContract {
@@ -156,8 +181,62 @@ interface GridEngineContract {
requiresModel?: boolean
}
-/** The variable Codex is told to read the key from — its own `env_key` indirection. */
-const CODEX_KEY_VAR = 'GRID_API_KEY'
+/**
+ * The variable an engine is told to read the key from, where the engine supports that indirection.
+ *
+ * Codex names it in `env_key`; Pi's `models.json` writes it as a `$VAR` reference. Both exist so the
+ * credential can stay in the environment while the configuration that points at it is not secret.
+ */
+const GRID_KEY_VAR = 'GRID_API_KEY'
+
+/** The provider id our generated config declares. Pi selects it as `--model <id>/<model>`. */
+const GRID_PROVIDER_ID = 'grid'
+
+/**
+ * Pi's provider block, as the Grid app shipped and unit-tested it
+ * (`autonomous-grid-app`, `pi_grid_config.dart` at 36d00c95, before Pi was dropped from that app for
+ * reasons about ITS chat UI — a fourth agent nobody reached for, and a 180 MB private Node
+ * toolchain — none of which apply here, where the user installs Pi themselves).
+ *
+ * `api: openai-completions` makes Pi post to `<base>/chat/completions`, which is what the relay
+ * serves. The context/cost numbers are Pi's own bookkeeping for its display; the grid decides what
+ * the model really takes.
+ */
+function piModelsJson(baseUrl: string, model: string): string {
+ return JSON.stringify({
+ providers: {
+ [GRID_PROVIDER_ID]: {
+ name: 'Autonomous Grid',
+ baseUrl,
+ api: 'openai-completions',
+ // An env reference, not the key — nothing secret is written to disk.
+ apiKey: `$${GRID_KEY_VAR}`,
+ models: [{
+ id: model,
+ name: model,
+ reasoning: false,
+ input: ['text'],
+ contextWindow: 200000,
+ maxTokens: 8192,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ }],
+ },
+ },
+ }, null, 2)
+}
+
+/**
+ * Pi's settings for the directory we own, which exists to hand back the one thing the redirection
+ * takes away: the skills the user keeps in their real `~/.pi/agent/skills`.
+ *
+ * Deliberately NOT `defaultProjectTrust: always`. The Grid app set it because it drove Pi headless,
+ * one process per turn, with nobody there to answer a prompt. Here the user is sitting in front of
+ * an interactive pane, and silently pre-trusting every folder they open an agent in would be this
+ * daemon deciding something it was not asked to decide.
+ */
+function piSettingsJson(userSkillsDir: string): string {
+ return JSON.stringify({ skills: [userSkillsDir] }, null, 2)
+}
/**
* Every engine that can be pointed at a grid, and how.
@@ -194,12 +273,12 @@ const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> =
// The key travels in the environment under `env_key`, never in argv.
codex: {
build: (override) => ({
- env: { [CODEX_KEY_VAR]: override.apiKey },
+ env: { [GRID_KEY_VAR]: override.apiKey },
args: [
'-c', 'model_provider="grid"',
'-c', 'model_providers.grid.name="Autonomous Grid"',
'-c', `model_providers.grid.base_url="${relayBaseUrl(override.baseUrl)}"`,
- '-c', `model_providers.grid.env_key="${CODEX_KEY_VAR}"`,
+ '-c', `model_providers.grid.env_key="${GRID_KEY_VAR}"`,
// Mandatory: Codex speaks the Responses dialect and rejects `wire_api = "chat"`.
'-c', 'model_providers.grid.wire_api="responses"',
// The relay streams HTTP SSE, not WebSocket.
@@ -250,6 +329,27 @@ const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> =
}),
},
+ // Pi reads its providers out of a config DIRECTORY, and `PI_CODING_AGENT_DIR` moves that
+ // directory. So it gets a private one per agent: the provider block lands there, the user's
+ // ~/.pi/agent/models.json is never opened, and their skills are handed back through settings.json.
+ //
+ // The model is not optional — the provider block has to name the model it serves, and Pi selects
+ // it as `grid/<model>`.
+ pi: {
+ requiresModel: true,
+ build: (override) => ({
+ env: { [GRID_KEY_VAR]: override.apiKey },
+ args: ['--model', `${GRID_PROVIDER_ID}/${override.model as string}`],
+ configDir: {
+ envVar: 'PI_CODING_AGENT_DIR',
+ files: [
+ { name: 'models.json', content: piModelsJson(relayBaseUrl(override.baseUrl), override.model as string) },
+ { name: 'settings.json', content: piSettingsJson(userPiSkillsDir()) },
+ ],
+ },
+ }),
+ },
+
// GitHub's documented BYOK path for Copilot CLI (docs.github.com … /use-byok-models). Copilot
// will not start against a custom provider without being told the model, so that is enforced
// here rather than left to fail inside the app.
@@ -273,10 +373,11 @@ const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> =
* whether to wait for a release, change a setting, or pick another engine.
*/
const GRID_ENGINE_REFUSALS: Partial<Record<AgentEngine, string>> = {
+ // NOTE: pi is NOT here — it is supported through a private config directory. Kilo is, because its
+ // CLI has no OpenAI-compatible provider to configure at all, in any directory.
cursor: 'Cursor Agent can only be re-pointed at another Cursor API (CURSOR_API_ENDPOINT), '
+ 'not at an OpenAI-compatible relay',
agy: 'Antigravity speaks the Gemini API, which this relay does not serve',
- pi: 'Pi needs a provider block written into ~/.pi/agent/models.json, which this will not edit for you',
kilo: 'the Kilo CLI has no OpenAI-compatible provider option yet (its own issues #5840, #6315)',
amp: 'Amp documents no way to change where it sends inference',
devin: 'Devin runs on its own hosted service and documents no endpoint override',