Open History to see the last commit
1// User-wide ~/.pi/agent state makes continuation identity use default instance grouping.
2import { ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
3import { PiSettings } from "../settings.ts";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Path from "effect/Path";
7import * as Schema from "effect/Schema";
8import * as HttpClient from "effect/http/HttpClient";
9import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
10
11import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
12import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
13import { piUsageReader } from "./usage.ts";
14import { makePiTextGeneration } from "./textGeneration.ts";
15import { PiAdapterV2Driver, type PiAdapterV2DriverEnv } from "./adapter.ts";
16import { ProviderDriverError } from "@t3tools/provider-core/server/errors";
17import {
18 buildInitialPiProviderSnapshot,
19 checkPiProviderStatus,
20 discoverPiCommandsForCwd,
21 enrichPiSnapshot,
22} from "./status.ts";
23import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
24import {
25 defaultProviderContinuationIdentity,
26 type ProviderDriver,
27 type ProviderInstance,
28} from "@t3tools/provider-core/server/driver";
29import type { ServerProviderDraft } from "@t3tools/provider-core/server/snapshotProbe";
30import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
31import {
32 makeCachedProviderMaintenanceResolution,
33 makePackageManagedProviderMaintenanceResolver,
34 resolveProviderMaintenanceCapabilitiesEffect,
35} from "@t3tools/provider-core/server/maintenanceResolver";
36import {
37 haveProviderSnapshotSettingsChanged,
38 makeProviderSnapshotSettingsSource,
39 type ProviderSnapshotSettings,
40} from "@t3tools/provider-core/server/snapshotSettings";
41
42const decodePiSettings = Schema.decodeSync(PiSettings);
43
44const DRIVER_KIND = ProviderDriverKind.make("pi");
45const UPDATE = makePackageManagedProviderMaintenanceResolver({
46 provider: DRIVER_KIND,
47 npmPackageName: "@earendil-works/pi-coding-agent",
48 mise: { tool: "pi" },
49 nativeUpdate: { args: ["update", "--self"] },
50});
51
52export type PiDriverEnv =
53 | PiAdapterV2DriverEnv
54 | ProviderHost.ProviderHost
55 | ChildProcessSpawner.ChildProcessSpawner
56 | FileSystem.FileSystem
57 | HttpClient.HttpClient
58 | ProviderLatestVersions.ProviderLatestVersions
59 | Path.Path;
60
61const 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
77export 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 npmCacheDir: pathService.join(host.paths.providerStatusCacheDir, "npm"),
119 }).pipe(
120 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
121 Effect.provideService(FileSystem.FileSystem, fileSystem),
122 Effect.provideService(Path.Path, pathService),
123 ),
124 );
125
126 const orchestrationAdapter = yield* PiAdapterV2Driver.create({
127 instanceId,
128 displayName,
129 accentColor,
130 environment,
131 enabled,
132 config,
133 }).pipe(
134 Effect.mapError(
135 (cause) =>
136 new ProviderDriverError({
137 driver: DRIVER_KIND,
138 instanceId,
139 detail: "Failed to build Pi orchestration adapter.",
140 cause,
141 }),
142 ),
143 );
144 const textGeneration = yield* makePiTextGeneration(
145 effectiveConfig,
146 processEnv,
147 host.compatibility,
148 );
149
150 const checkProvider = fileSystem
151 .makeDirectory(probeCwd, { recursive: true })
152 .pipe(
153 Effect.ignore,
154 Effect.andThen(
155 checkPiProviderStatus(effectiveConfig, processEnv, probeCwd, host.compatibility),
156 ),
157 Effect.map(stampIdentity),
158 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
159 );
160
161 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
162 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<PiSettings>>({
163 resolveMaintenance,
164 getSettings: snapshotSettings.getSettings,
165 streamSettings: snapshotSettings.streamSettings,
166 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
167 initialSnapshot: (settings) =>
168 buildInitialPiProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),
169 checkProvider,
170 awaitEnrichmentOnRefresh: true,
171 enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
172 resolveMaintenance().pipe(
173 Effect.flatMap((maintenanceCapabilities) =>
174 enrichPiSnapshot({
175 snapshot: currentSnapshot,
176 maintenanceCapabilities,
177 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
178 publishSnapshot,
179 }),
180 ),
181 Effect.provideService(HttpClient.HttpClient, httpClient),
182 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
183 ),
184 }).pipe(
185 Effect.mapError(
186 (cause) =>
187 new ProviderDriverError({
188 driver: DRIVER_KIND,
189 instanceId,
190 detail: "Failed to build Pi snapshot.",
191 cause,
192 }),
193 ),
194 );
195
196 return {
197 instanceId,
198 driverKind: DRIVER_KIND,
199 continuationIdentity,
200 displayName,
201 accentColor,
202 enabled,
203 snapshot,
204 snapshotForCwd: (workspaceCwd) =>
205 !effectiveConfig.enabled
206 ? snapshot.getSnapshot
207 : Effect.all([
208 snapshot.getSnapshot,
209 discoverPiCommandsForCwd(effectiveConfig, processEnv, workspaceCwd).pipe(
210 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
211 Effect.mapError(
212 (cause) =>
213 new ProviderDriverError({
214 driver: DRIVER_KIND,
215 instanceId,
216 detail: "Failed to discover Pi workspace commands.",
217 cause,
218 }),
219 ),
220 ),
221 ]).pipe(
222 Effect.map(([machineSnapshot, commands]) => ({
223 ...machineSnapshot,
224 ...commands,
225 slashCommandsPending: false,
226 })),
227 ),
228 orchestrationAdapter,
229 textGeneration,
230 } satisfies ProviderInstance;
231 }),
232};