Open History to see the last commit
1import { makeLazyAdapter } from "@t3tools/provider-core/server/lazyAdapter";
2/**
3 * Pi state (sessions, settings, extensions, auth) lives in the user's own
4 * `~/.pi/agent`, so continuation identity uses the default instance grouping.
5 */
6import { ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
7import { PiSettings } from "../settings.ts";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Path from "effect/Path";
11import * as Schema from "effect/Schema";
12import * as HttpClient from "effect/http/HttpClient";
13import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
14
15import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
16import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
17import { piUsageReader } from "./usage.ts";
18import { makePiTextGeneration } from "./textGeneration.ts";
19import type { PiAdapterV2DriverEnv } from "./adapter.ts";
20import { ProviderDriverError } from "@t3tools/provider-core/server/errors";
21import {
22 buildInitialPiProviderSnapshot,
23 checkPiProviderStatus,
24 discoverPiCommandsForCwd,
25 enrichPiSnapshot,
26} from "./status.ts";
27import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
28import {
29 defaultProviderContinuationIdentity,
30 type ProviderDriver,
31 type ProviderInstance,
32} from "@t3tools/provider-core/server/driver";
33import type { ServerProviderDraft } from "@t3tools/provider-core/server/snapshotProbe";
34import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
35import {
36 makeCachedProviderMaintenanceResolution,
37 makePackageManagedProviderMaintenanceResolver,
38 resolveProviderMaintenanceCapabilitiesEffect,
39} from "@t3tools/provider-core/server/maintenanceResolver";
40import {
41 haveProviderSnapshotSettingsChanged,
42 makeProviderSnapshotSettingsSource,
43 type ProviderSnapshotSettings,
44} from "@t3tools/provider-core/server/snapshotSettings";
45
46const decodePiSettings = Schema.decodeSync(PiSettings);
47
48const DRIVER_KIND = ProviderDriverKind.make("pi");
49const UPDATE = makePackageManagedProviderMaintenanceResolver({
50 provider: DRIVER_KIND,
51 npmPackageName: "@earendil-works/pi-coding-agent",
52 nativeUpdate: { args: ["update", "--self"] },
53});
54
55export type PiDriverEnv =
56 | PiAdapterV2DriverEnv
57 | ProviderHost.ProviderHost
58 | ChildProcessSpawner.ChildProcessSpawner
59 | FileSystem.FileSystem
60 | HttpClient.HttpClient
61 | ProviderLatestVersions.ProviderLatestVersions
62 | Path.Path;
63
64const withInstanceIdentity =
65 (input: {
66 readonly instanceId: ProviderInstance["instanceId"];
67 readonly displayName: string | undefined;
68 readonly accentColor: string | undefined;
69 readonly continuationGroupKey: string;
70 }) =>
71 (snapshot: ServerProviderDraft): ServerProvider => ({
72 ...snapshot,
73 instanceId: input.instanceId,
74 driver: DRIVER_KIND,
75 ...(input.displayName ? { displayName: input.displayName } : {}),
76 ...(input.accentColor ? { accentColor: input.accentColor } : {}),
77 continuation: { groupKey: input.continuationGroupKey },
78 });
79
80export const PiDriver: ProviderDriver<PiSettings, PiDriverEnv, Path.Path> = {
81 driverKind: DRIVER_KIND,
82 metadata: {
83 displayName: "Pi",
84 supportsMultipleInstances: true,
85 },
86 usage: piUsageReader,
87 configSchema: PiSettings,
88 defaultConfig: (): PiSettings => decodePiSettings({}),
89 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
90 Effect.gen(function* () {
91 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
92 const fileSystem = yield* FileSystem.FileSystem;
93 const pathService = yield* Path.Path;
94 const httpClient = yield* HttpClient.HttpClient;
95 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
96 const host = yield* ProviderHost.ProviderHost;
97 const { cwd } = host.paths;
98 const processEnv = yield* mergeProviderInstanceEnvironment(environment);
99 const continuationIdentity = defaultProviderContinuationIdentity({
100 driverKind: DRIVER_KIND,
101 instanceId,
102 });
103 const stampIdentity = withInstanceIdentity({
104 instanceId,
105 displayName,
106 accentColor,
107 continuationGroupKey: continuationIdentity.continuationKey,
108 });
109 const effectiveConfig = { ...config, enabled } satisfies PiSettings;
110 const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
111 resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
112 binaryPath: effectiveConfig.binaryPath,
113 env: processEnv,
114 }).pipe(
115 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
116 Effect.provideService(FileSystem.FileSystem, fileSystem),
117 Effect.provideService(Path.Path, pathService),
118 ),
119 );
120
121 const orchestrationAdapter = yield* makeLazyAdapter(
122 instanceId,
123 DRIVER_KIND,
124 Effect.promise(() => import("./adapter.ts")).pipe(
125 Effect.flatMap(({ PiAdapterV2Driver }) =>
126 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 ),
145 ),
146 );
147 const textGeneration = yield* makePiTextGeneration(effectiveConfig, processEnv);
148
149 const checkProvider = checkPiProviderStatus(effectiveConfig, processEnv, cwd).pipe(
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};