Skip to content

Commit f8389d5

Browse files
committed
feat: add Pi provider integration via RPC
1 parent 1c9a6de commit f8389d5

32 files changed

Lines changed: 5250 additions & 41 deletions

‎README.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,18 @@
11
# T3 Code
22

3-
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, Cursor, and OpenCode, more coming soon).
3+
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, Cursor, OpenCode, and Pi, more coming soon).
44

55
## Installation
66

77
> [!WARNING]
8-
> T3 Code currently supports Codex, Claude, Cursor, and OpenCode.
8+
> T3 Code currently supports Codex, Claude, Cursor, OpenCode, and Pi.
99
> Install and authenticate at least one provider before use:
1010
>
1111
> - Codex: install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`
1212
> - Claude: install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login`
1313
> - Cursor: install [Cursor CLI](https://cursor.com/cli) and run `cursor-agent login`
1414
> - OpenCode: install [OpenCode](https://opencode.ai) and run `opencode auth login`
15+
> - Pi: install the Pi CLI and configure a provider API key (Pi is Early Access and disabled by default — see [docs/providers/pi.md](./docs/providers/pi.md))
1516
1617
### Run without installing
1718

‎apps/server/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
"node-pty": "^1.1.0"
3535
},
3636
"devDependencies": {
37+
"@earendil-works/pi-coding-agent": "^0.80.2",
3738
"@effect/vitest": "catalog:",
3839
"@t3tools/contracts": "workspace:*",
3940
"@t3tools/shared": "workspace:*",

‎apps/server/scripts/cli.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,17 @@ const buildCmd = Command.make(
180180
const webDist = path.join(repoRoot, "apps/web/dist");
181181
const clientTarget = path.join(serverDir, "dist/client");
182182

183+
// Pi loads the approval-gate extension at runtime; vp pack won't emit it, so copy it next to the bundle.
184+
const piExtensionSource = path.join(serverDir, "src/provider/assets/pi/t3-approvals.ts");
185+
const piAssetTargetDir = path.join(serverDir, "dist/assets/pi");
186+
if (yield* fs.exists(piExtensionSource)) {
187+
yield* fs.makeDirectory(piAssetTargetDir, { recursive: true });
188+
yield* fs.copyFile(piExtensionSource, path.join(piAssetTargetDir, "t3-approvals.ts"));
189+
yield* Effect.log("[cli] Bundled Pi approval extension into dist/assets/pi");
190+
} else {
191+
yield* Effect.logWarning("[cli] Pi approval extension not found — skipping asset copy.");
192+
}
193+
183194
if (yield* fs.exists(webDist)) {
184195
yield* fs.copy(webDist, clientTarget);
185196
yield* applyDevelopmentIconOverrides(repoRoot, serverDir);

‎apps/server/scripts/pi-mock-rpc.ts‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
#!/usr/bin/env node
2+
// @effect-diagnostics nodeBuiltinImport:off
3+
// Fake `pi --mode rpc` for tests; driven by `PI_MOCK_*` env vars.
4+
import * as NodeReadline from "node:readline";
5+
6+
const assistantText = process.env["PI_MOCK_ASSISTANT_TEXT"] ?? '{"title":"Mock title"}';
7+
const emitInvalidJson = process.env["PI_MOCK_EMIT_INVALID_JSON"] === "1";
8+
const lastTextFails = process.env["PI_MOCK_LAST_TEXT_FAILS"] === "1";
9+
10+
const replyText = emitInvalidJson
11+
? "Sure — here is the answer, with no JSON at all."
12+
: assistantText;
13+
let lastAssistantText: string | null = null;
14+
15+
function write(obj: unknown): void {
16+
process.stdout.write(`${JSON.stringify(obj)}\n`);
17+
}
18+
19+
const rl = NodeReadline.createInterface({ input: process.stdin });
20+
21+
rl.on("line", (line: string) => {
22+
const trimmed = line.trim();
23+
if (!trimmed) return;
24+
let command: { type?: string; id?: string };
25+
try {
26+
command = JSON.parse(trimmed) as { type?: string; id?: string };
27+
} catch {
28+
return;
29+
}
30+
31+
switch (command.type) {
32+
case "prompt":
33+
case "steer":
34+
case "follow_up": {
35+
write({ type: "agent_start" });
36+
write({ type: "turn_start" });
37+
write({
38+
type: "message_update",
39+
assistantMessageEvent: { type: "text_delta", delta: replyText },
40+
});
41+
lastAssistantText = replyText;
42+
write({ type: "message_end" });
43+
write({ type: "turn_end" });
44+
write({ type: "agent_end" });
45+
return;
46+
}
47+
case "get_last_assistant_text": {
48+
write(
49+
lastTextFails
50+
? {
51+
type: "response",
52+
id: command.id,
53+
command: "get_last_assistant_text",
54+
success: false,
55+
error: "no assistant text",
56+
}
57+
: {
58+
type: "response",
59+
id: command.id,
60+
command: "get_last_assistant_text",
61+
success: true,
62+
data: { text: lastAssistantText },
63+
},
64+
);
65+
return;
66+
}
67+
case "get_state": {
68+
write({
69+
type: "response",
70+
id: command.id,
71+
command: "get_state",
72+
success: true,
73+
data: {
74+
sessionId: "mock-session",
75+
sessionFile: "/tmp/pi-mock-session.json",
76+
thinkingLevel: "off",
77+
isStreaming: false,
78+
isCompacting: false,
79+
steeringMode: "all",
80+
followUpMode: "all",
81+
autoCompactionEnabled: false,
82+
messageCount: 0,
83+
pendingMessageCount: 0,
84+
},
85+
});
86+
return;
87+
}
88+
case "get_commands": {
89+
write({
90+
type: "response",
91+
id: command.id,
92+
command: "get_commands",
93+
success: true,
94+
data: { commands: [] },
95+
});
96+
return;
97+
}
98+
default: {
99+
if (command.id !== undefined) {
100+
write({
101+
type: "response",
102+
id: command.id,
103+
command: command.type ?? "unknown",
104+
success: true,
105+
});
106+
}
107+
return;
108+
}
109+
}
110+
});
111+
112+
rl.on("close", () => {
113+
process.exit(0);
114+
});
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
import { PiSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
2+
import * as Crypto from "effect/Crypto";
3+
import * as Duration from "effect/Duration";
4+
import * as Effect from "effect/Effect";
5+
import * as FileSystem from "effect/FileSystem";
6+
import * as Path from "effect/Path";
7+
import * as Schema from "effect/Schema";
8+
import { HttpClient } from "effect/unstable/http";
9+
import { ChildProcessSpawner } from "effect/unstable/process";
10+
11+
import { ServerConfig } from "../../config.ts";
12+
import { ServerSettingsService } from "../../serverSettings.ts";
13+
import { makePiTextGeneration } from "../../textGeneration/PiTextGeneration.ts";
14+
import { ProviderDriverError } from "../Errors.ts";
15+
import { makePiAdapter } from "../Layers/PiAdapter.ts";
16+
import { buildInitialPiProviderSnapshot, checkPiProviderStatus } from "../Layers/PiProvider.ts";
17+
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
18+
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
19+
import {
20+
defaultProviderContinuationIdentity,
21+
type ProviderDriver,
22+
type ProviderInstance,
23+
} from "../ProviderDriver.ts";
24+
import type { ServerProviderDraft } from "../providerSnapshot.ts";
25+
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
26+
import {
27+
enrichProviderSnapshotWithVersionAdvisory,
28+
makePackageManagedProviderMaintenanceResolver,
29+
resolveProviderMaintenanceCapabilitiesEffect,
30+
} from "../providerMaintenance.ts";
31+
import {
32+
haveProviderSnapshotSettingsChanged,
33+
makeProviderSnapshotSettingsSource,
34+
type ProviderSnapshotSettings,
35+
} from "../providerUpdateSettings.ts";
36+
37+
const decodePiSettings = Schema.decodeSync(PiSettings);
38+
39+
const DRIVER_KIND = ProviderDriverKind.make("pi");
40+
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
41+
42+
const UPDATE = makePackageManagedProviderMaintenanceResolver({
43+
provider: DRIVER_KIND,
44+
npmPackageName: "@earendil-works/pi-coding-agent",
45+
homebrewFormula: null,
46+
nativeUpdate: null,
47+
});
48+
49+
export type PiDriverEnv =
50+
| ChildProcessSpawner.ChildProcessSpawner
51+
| Crypto.Crypto
52+
| FileSystem.FileSystem
53+
| HttpClient.HttpClient
54+
| Path.Path
55+
| ProviderEventLoggers
56+
| ServerConfig
57+
| ServerSettingsService;
58+
59+
const withInstanceIdentity =
60+
(input: {
61+
readonly instanceId: ProviderInstance["instanceId"];
62+
readonly displayName: string | undefined;
63+
readonly accentColor: string | undefined;
64+
readonly continuationGroupKey: string;
65+
}) =>
66+
(snapshot: ServerProviderDraft): ServerProvider => ({
67+
...snapshot,
68+
instanceId: input.instanceId,
69+
driver: DRIVER_KIND,
70+
...(input.displayName ? { displayName: input.displayName } : {}),
71+
...(input.accentColor ? { accentColor: input.accentColor } : {}),
72+
continuation: { groupKey: input.continuationGroupKey },
73+
});
74+
75+
export const PiDriver: ProviderDriver<PiSettings, PiDriverEnv> = {
76+
driverKind: DRIVER_KIND,
77+
metadata: {
78+
displayName: "Pi",
79+
supportsMultipleInstances: true,
80+
},
81+
configSchema: PiSettings,
82+
defaultConfig: (): PiSettings => decodePiSettings({}),
83+
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
84+
Effect.gen(function* () {
85+
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
86+
const httpClient = yield* HttpClient.HttpClient;
87+
const serverSettings = yield* ServerSettingsService;
88+
const serverConfig = yield* ServerConfig;
89+
const processEnv = mergeProviderInstanceEnvironment(environment);
90+
const continuationIdentity = defaultProviderContinuationIdentity({
91+
driverKind: DRIVER_KIND,
92+
instanceId,
93+
});
94+
const stampIdentity = withInstanceIdentity({
95+
instanceId,
96+
displayName,
97+
accentColor,
98+
continuationGroupKey: continuationIdentity.continuationKey,
99+
});
100+
const effectiveConfig = { ...config, enabled } satisfies PiSettings;
101+
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
102+
binaryPath: effectiveConfig.binaryPath,
103+
env: processEnv,
104+
});
105+
106+
const adapter = yield* makePiAdapter(effectiveConfig, {
107+
instanceId,
108+
environment: processEnv,
109+
});
110+
const textGeneration = yield* makePiTextGeneration(effectiveConfig, processEnv);
111+
112+
const checkProvider = checkPiProviderStatus(
113+
effectiveConfig,
114+
serverConfig.cwd,
115+
processEnv,
116+
).pipe(
117+
Effect.map(stampIdentity),
118+
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
119+
);
120+
121+
const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
122+
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<PiSettings>>({
123+
maintenanceCapabilities,
124+
getSettings: snapshotSettings.getSettings,
125+
streamSettings: snapshotSettings.streamSettings,
126+
haveSettingsChanged: haveProviderSnapshotSettingsChanged,
127+
initialSnapshot: (settings) =>
128+
buildInitialPiProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),
129+
checkProvider,
130+
enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
131+
enrichProviderSnapshotWithVersionAdvisory(currentSnapshot, maintenanceCapabilities, {
132+
enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
133+
}).pipe(
134+
Effect.provideService(HttpClient.HttpClient, httpClient),
135+
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
136+
Effect.catchCause((cause) =>
137+
Effect.logWarning("Pi version advisory enrichment failed", { cause }).pipe(
138+
Effect.asVoid,
139+
),
140+
),
141+
),
142+
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
143+
}).pipe(
144+
Effect.mapError(
145+
(cause) =>
146+
new ProviderDriverError({
147+
driver: DRIVER_KIND,
148+
instanceId,
149+
detail: `Failed to build Pi snapshot: ${cause.message ?? String(cause)}`,
150+
cause,
151+
}),
152+
),
153+
);
154+
155+
return {
156+
instanceId,
157+
driverKind: DRIVER_KIND,
158+
continuationIdentity,
159+
displayName,
160+
accentColor,
161+
enabled,
162+
snapshot,
163+
adapter,
164+
textGeneration,
165+
} satisfies ProviderInstance;
166+
}),
167+
};

0 commit comments

Comments
 (0)