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 enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
171 resolveMaintenance().pipe(
172 Effect.flatMap((maintenanceCapabilities) =>
173 enrichPiSnapshot({
174 snapshot: currentSnapshot,
175 maintenanceCapabilities,
176 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
177 publishSnapshot,
178 }),
179 ),
180 Effect.provideService(HttpClient.HttpClient, httpClient),
181 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
182 ),
183 }).pipe(
184 Effect.mapError(
185 (cause) =>
186 new ProviderDriverError({
187 driver: DRIVER_KIND,
188 instanceId,
189 detail: "Failed to build Pi snapshot.",
190 cause,
191 }),
192 ),
193 );
194
195 return {
196 instanceId,
197 driverKind: DRIVER_KIND,
198 continuationIdentity,
199 displayName,
200 accentColor,
201 enabled,
202 snapshot,
203 snapshotForCwd: (workspaceCwd) =>
204 !effectiveConfig.enabled
205 ? snapshot.getSnapshot
206 : Effect.all([
207 snapshot.getSnapshot,
208 discoverPiCommandsForCwd(effectiveConfig, processEnv, workspaceCwd).pipe(
209 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
210 Effect.mapError(
211 (cause) =>
212 new ProviderDriverError({
213 driver: DRIVER_KIND,
214 instanceId,
215 detail: "Failed to discover Pi workspace commands.",
216 cause,
217 }),
218 ),
219 ),
220 ]).pipe(
221 Effect.map(([machineSnapshot, commands]) => ({
222 ...machineSnapshot,
223 ...commands,
224 slashCommandsPending: false,
225 })),
226 ),
227 orchestrationAdapter,
228 textGeneration,
229 } satisfies ProviderInstance;
230 }),
231};