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 }).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(effectiveConfig, processEnv);
144
145 const checkProvider = fileSystem
146 .makeDirectory(probeCwd, { recursive: true })
147 .pipe(
148 Effect.ignore,
149 Effect.andThen(checkPiProviderStatus(effectiveConfig, processEnv, probeCwd)),
150 Effect.map(stampIdentity),
151 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
152 );
153
154 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
155 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<PiSettings>>({
156 resolveMaintenance,
157 getSettings: snapshotSettings.getSettings,
158 streamSettings: snapshotSettings.streamSettings,
159 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
160 initialSnapshot: (settings) =>
161 buildInitialPiProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),
162 checkProvider,
163 enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
164 resolveMaintenance().pipe(
165 Effect.flatMap((maintenanceCapabilities) =>
166 enrichPiSnapshot({
167 snapshot: currentSnapshot,
168 maintenanceCapabilities,
169 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
170 publishSnapshot,
171 }),
172 ),
173 Effect.provideService(HttpClient.HttpClient, httpClient),
174 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
175 ),
176 }).pipe(
177 Effect.mapError(
178 (cause) =>
179 new ProviderDriverError({
180 driver: DRIVER_KIND,
181 instanceId,
182 detail: "Failed to build Pi snapshot.",
183 cause,
184 }),
185 ),
186 );
187
188 return {
189 instanceId,
190 driverKind: DRIVER_KIND,
191 continuationIdentity,
192 displayName,
193 accentColor,
194 enabled,
195 snapshot,
196 snapshotForCwd: (workspaceCwd) =>
197 !effectiveConfig.enabled
198 ? snapshot.getSnapshot
199 : Effect.all([
200 snapshot.getSnapshot,
201 discoverPiCommandsForCwd(effectiveConfig, processEnv, workspaceCwd).pipe(
202 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
203 Effect.mapError(
204 (cause) =>
205 new ProviderDriverError({
206 driver: DRIVER_KIND,
207 instanceId,
208 detail: "Failed to discover Pi workspace commands.",
209 cause,
210 }),
211 ),
212 ),
213 ]).pipe(
214 Effect.map(([machineSnapshot, commands]) => ({
215 ...machineSnapshot,
216 ...commands,
217 slashCommandsPending: false,
218 })),
219 ),
220 orchestrationAdapter,
221 textGeneration,
222 } satisfies ProviderInstance;
223 }),
224};