The best way to control Claude Code, Codex and more from any computer or phone

main
ts 230 lines 8.22 KB
Raw
1 // User-wide ~/.pi/agent state makes continuation identity use default instance grouping.
2 import { ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
3 import { PiSettings } from "../settings.ts";
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 * as HttpClient from "effect/http/HttpClient";
9 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
10
11 import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
12 import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
13 import { piUsageReader } from "./usage.ts";
14 import { makePiTextGeneration } from "./textGeneration.ts";
15 import { PiAdapterV2Driver, type PiAdapterV2DriverEnv } from "./adapter.ts";
16 import { ProviderDriverError } from "@t3tools/provider-core/server/errors";
17 import {
18 buildInitialPiProviderSnapshot,
19 checkPiProviderStatus,
20 discoverPiCommandsForCwd,
21 enrichPiSnapshot,
22 } from "./status.ts";
23 import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
24 import {
25 defaultProviderContinuationIdentity,
26 type ProviderDriver,
27 type ProviderInstance,
28 } from "@t3tools/provider-core/server/driver";
29 import type { ServerProviderDraft } from "@t3tools/provider-core/server/snapshotProbe";
30 import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
31 import {
32 makeCachedProviderMaintenanceResolution,
33 makePackageManagedProviderMaintenanceResolver,
34 resolveProviderMaintenanceCapabilitiesEffect,
35 } from "@t3tools/provider-core/server/maintenanceResolver";
36 import {
37 haveProviderSnapshotSettingsChanged,
38 makeProviderSnapshotSettingsSource,
39 type ProviderSnapshotSettings,
40 } from "@t3tools/provider-core/server/snapshotSettings";
41
42 const decodePiSettings = Schema.decodeSync(PiSettings);
43
44 const DRIVER_KIND = ProviderDriverKind.make("pi");
45 const UPDATE = makePackageManagedProviderMaintenanceResolver({
46 provider: DRIVER_KIND,
47 npmPackageName: "@earendil-works/pi-coding-agent",
48 mise: { tool: "pi" },
49 nativeUpdate: { args: ["update", "--self"] },
50 });
51
52 export type PiDriverEnv =
53 | PiAdapterV2DriverEnv
54 | ProviderHost.ProviderHost
55 | ChildProcessSpawner.ChildProcessSpawner
56 | FileSystem.FileSystem
57 | HttpClient.HttpClient
58 | ProviderLatestVersions.ProviderLatestVersions
59 | Path.Path;
60
61 const withInstanceIdentity =
62 (input: {
63 readonly instanceId: ProviderInstance["instanceId"];
64 readonly displayName: string | undefined;
65 readonly accentColor: string | undefined;
66 readonly continuationGroupKey: string;
67 }) =>
68 (snapshot: ServerProviderDraft): ServerProvider => ({
69 ...snapshot,
70 instanceId: input.instanceId,
71 driver: DRIVER_KIND,
72 ...(input.displayName ? { displayName: input.displayName } : {}),
73 ...(input.accentColor ? { accentColor: input.accentColor } : {}),
74 continuation: { groupKey: input.continuationGroupKey },
75 });
76
77 export const PiDriver: ProviderDriver<PiSettings, PiDriverEnv, Path.Path> = {
78 driverKind: DRIVER_KIND,
79 metadata: {
80 displayName: "Pi",
81 supportsMultipleInstances: true,
82 },
83 usage: piUsageReader,
84 configSchema: PiSettings,
85 defaultConfig: (): PiSettings => decodePiSettings({}),
86 create: Effect.fn("PiDriver.create")(function* ({
87 instanceId,
88 displayName,
89 accentColor,
90 environment,
91 enabled,
92 config,
93 }) {
94 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
95 const fileSystem = yield* FileSystem.FileSystem;
96 const pathService = yield* Path.Path;
97 const httpClient = yield* HttpClient.HttpClient;
98 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
99 const host = yield* ProviderHost.ProviderHost;
100 // Pi runs extensions' session_start in its cwd; the server's cwd is $HOME on packaged desktop.
101 const probeCwd = pathService.join(host.paths.providerStatusCacheDir, "pi-status-probe");
102 const processEnv = yield* mergeProviderInstanceEnvironment(environment);
103 const continuationIdentity = defaultProviderContinuationIdentity({
104 driverKind: DRIVER_KIND,
105 instanceId,
106 });
107 const stampIdentity = withInstanceIdentity({
108 instanceId,
109 displayName,
110 accentColor,
111 continuationGroupKey: continuationIdentity.continuationKey,
112 });
113 const effectiveConfig = { ...config, enabled } satisfies PiSettings;
114 const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
115 resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
116 binaryPath: effectiveConfig.binaryPath,
117 env: processEnv,
118 }).pipe(
119 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
120 Effect.provideService(FileSystem.FileSystem, fileSystem),
121 Effect.provideService(Path.Path, pathService),
122 ),
123 );
124
125 const orchestrationAdapter = yield* PiAdapterV2Driver.create({
126 instanceId,
127 displayName,
128 accentColor,
129 environment,
130 enabled,
131 config,
132 }).pipe(
133 Effect.mapError(
134 (cause) =>
135 new ProviderDriverError({
136 driver: DRIVER_KIND,
137 instanceId,
138 detail: "Failed to build Pi orchestration adapter.",
139 cause,
140 }),
141 ),
142 );
143 const textGeneration = yield* makePiTextGeneration(
144 effectiveConfig,
145 processEnv,
146 host.compatibility,
147 );
148
149 const checkProvider = fileSystem
150 .makeDirectory(probeCwd, { recursive: true })
151 .pipe(
152 Effect.ignore,
153 Effect.andThen(
154 checkPiProviderStatus(effectiveConfig, processEnv, probeCwd, host.compatibility),
155 ),
156 Effect.map(stampIdentity),
157 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
158 );
159
160 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
161 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<PiSettings>>({
162 resolveMaintenance,
163 getSettings: snapshotSettings.getSettings,
164 streamSettings: snapshotSettings.streamSettings,
165 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
166 initialSnapshot: (settings) =>
167 buildInitialPiProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),
168 checkProvider,
169 enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
170 resolveMaintenance().pipe(
171 Effect.flatMap((maintenanceCapabilities) =>
172 enrichPiSnapshot({
173 snapshot: currentSnapshot,
174 maintenanceCapabilities,
175 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
176 publishSnapshot,
177 }),
178 ),
179 Effect.provideService(HttpClient.HttpClient, httpClient),
180 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
181 ),
182 }).pipe(
183 Effect.mapError(
184 (cause) =>
185 new ProviderDriverError({
186 driver: DRIVER_KIND,
187 instanceId,
188 detail: "Failed to build Pi snapshot.",
189 cause,
190 }),
191 ),
192 );
193
194 return {
195 instanceId,
196 driverKind: DRIVER_KIND,
197 continuationIdentity,
198 displayName,
199 accentColor,
200 enabled,
201 snapshot,
202 snapshotForCwd: (workspaceCwd) =>
203 !effectiveConfig.enabled
204 ? snapshot.getSnapshot
205 : Effect.all([
206 snapshot.getSnapshot,
207 discoverPiCommandsForCwd(effectiveConfig, processEnv, workspaceCwd).pipe(
208 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
209 Effect.mapError(
210 (cause) =>
211 new ProviderDriverError({
212 driver: DRIVER_KIND,
213 instanceId,
214 detail: "Failed to discover Pi workspace commands.",
215 cause,
216 }),
217 ),
218 ),
219 ]).pipe(
220 Effect.map(([machineSnapshot, commands]) => ({
221 ...machineSnapshot,
222 ...commands,
223 slashCommandsPending: false,
224 })),
225 ),
226 orchestrationAdapter,
227 textGeneration,
228 } satisfies ProviderInstance;
229 }),
230 };