Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

driver.ts

221 lines7.9 KB

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