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

driver.ts

211 lines8.0 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: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
89 Effect.gen(function* () {
90 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
91 const fileSystem = yield* FileSystem.FileSystem;
92 const pathService = yield* Path.Path;
93 const httpClient = yield* HttpClient.HttpClient;
94 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
95 const host = yield* ProviderHost.ProviderHost;
96 const { cwd } = host.paths;
97 const processEnv = yield* mergeProviderInstanceEnvironment(environment);
98 const continuationIdentity = defaultProviderContinuationIdentity({
99 driverKind: DRIVER_KIND,
100 instanceId,
101 });
102 const stampIdentity = withInstanceIdentity({
103 instanceId,
104 displayName,
105 accentColor,
106 continuationGroupKey: continuationIdentity.continuationKey,
107 });
108 const effectiveConfig = { ...config, enabled } satisfies PiSettings;
109 const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
110 resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
111 binaryPath: effectiveConfig.binaryPath,
112 env: processEnv,
113 }).pipe(
114 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
115 Effect.provideService(FileSystem.FileSystem, fileSystem),
116 Effect.provideService(Path.Path, pathService),
117 ),
118 );
119​
120 const orchestrationAdapter = yield* PiAdapterV2Driver.create({
121 instanceId,
122 displayName,
123 accentColor,
124 environment,
125 enabled,
126 config,
127 }).pipe(
128 Effect.mapError(
129 (cause) =>
130 new ProviderDriverError({
131 driver: DRIVER_KIND,
132 instanceId,
133 detail: "Failed to build Pi orchestration adapter.",
134 cause,
135 }),
136 ),
137 );
138 const textGeneration = yield* makePiTextGeneration(effectiveConfig, processEnv);
139​
140 const checkProvider = checkPiProviderStatus(effectiveConfig, processEnv, cwd).pipe(
141 Effect.map(stampIdentity),
142 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
143 );
144​
145 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
146 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<PiSettings>>({
147 resolveMaintenance,
148 getSettings: snapshotSettings.getSettings,
149 streamSettings: snapshotSettings.streamSettings,
150 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
151 initialSnapshot: (settings) =>
152 buildInitialPiProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),
153 checkProvider,
154 enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
155 resolveMaintenance().pipe(
156 Effect.flatMap((maintenanceCapabilities) =>
157 enrichPiSnapshot({
158 snapshot: currentSnapshot,
159 maintenanceCapabilities,
160 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
161 publishSnapshot,
162 }),
163 ),
164 Effect.provideService(HttpClient.HttpClient, httpClient),
165 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
166 ),
167 }).pipe(
168 Effect.mapError(
169 (cause) =>
170 new ProviderDriverError({
171 driver: DRIVER_KIND,
172 instanceId,
173 detail: "Failed to build Pi snapshot.",
174 cause,
175 }),
176 ),
177 );
178​
179 return {
180 instanceId,
181 driverKind: DRIVER_KIND,
182 continuationIdentity,
183 displayName,
184 accentColor,
185 enabled,
186 snapshot,
187 snapshotForCwd: (workspaceCwd) =>
188 !effectiveConfig.enabled
189 ? snapshot.getSnapshot
190 : Effect.all([
191 snapshot.getSnapshot,
192 discoverPiCommandsForCwd(effectiveConfig, processEnv, workspaceCwd).pipe(
193 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
194 Effect.mapError(
195 (cause) =>
196 new ProviderDriverError({
197 driver: DRIVER_KIND,
198 instanceId,
199 detail: "Failed to discover Pi workspace commands.",
200 cause,
201 }),
202 ),
203 ),
204 ]).pipe(
205 Effect.map(([machineSnapshot, commands]) => ({ ...machineSnapshot, ...commands })),
206 ),
207 orchestrationAdapter,
208 textGeneration,
209 } satisfies ProviderInstance;
210 }),
211};