Open History to see the last commit
1import {
2 type PiSettings,
3 type ModelCapabilities,
4 type ServerProviderModel,
5 type ServerProviderSkill,
6 ProviderDriverKind,
7} from "@t3tools/contracts";
8import * as DateTime from "effect/DateTime";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
13import * as Result from "effect/Result";
14import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
15import { createModelCapabilities } from "@t3tools/shared/model";
16
17import {
18 buildSelectOptionDescriptor,
19 buildServerProvider,
20 DEFAULT_TIMEOUT_MS,
21 detailFromResult,
22 isCommandMissingCause,
23 parseGenericCliVersion,
24 providerModelsFromSettings,
25 spawnAndCollect,
26 type ServerProviderDraft,
27} from "../providerSnapshot.ts";
28import { makePiEnvironment, resolvePiHomePath } from "../Drivers/PiHome.ts";
29
30const DEFAULT_PI_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
31 optionDescriptors: [],
32});
33
34const PROVIDER = ProviderDriverKind.make("piAgent");
35const PI_PRESENTATION = {
36 displayName: "Pi Agent",
37 showInteractionModeToggle: true,
38} as const;
39
40const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
41 {
42 slug: "claude-sonnet-4-6",
43 name: "Claude Sonnet 4.6",
44 isCustom: false,
45 capabilities: createModelCapabilities({
46 optionDescriptors: [
47 buildSelectOptionDescriptor({
48 id: "thinking",
49 label: "Thinking",
50 options: [
51 { value: "off", label: "Off" },
52 { value: "low", label: "Low" },
53 { value: "medium", label: "Medium", isDefault: true },
54 { value: "high", label: "High" },
55 { value: "xhigh", label: "Extra High" },
56 ],
57 }),
58 ],
59 }),
60 },
61 {
62 slug: "claude-opus-4-7",
63 name: "Claude Opus 4.7",
64 isCustom: false,
65 capabilities: createModelCapabilities({
66 optionDescriptors: [
67 buildSelectOptionDescriptor({
68 id: "thinking",
69 label: "Thinking",
70 options: [
71 { value: "off", label: "Off" },
72 { value: "low", label: "Low" },
73 { value: "medium", label: "Medium" },
74 { value: "high", label: "High", isDefault: true },
75 { value: "xhigh", label: "Extra High" },
76 ],
77 }),
78 ],
79 }),
80 },
81 {
82 slug: "claude-haiku-4-5",
83 name: "Claude Haiku 4.5",
84 isCustom: false,
85 capabilities: createModelCapabilities({
86 optionDescriptors: [
87 buildSelectOptionDescriptor({
88 id: "thinking",
89 label: "Thinking",
90 options: [
91 { value: "off", label: "Off" },
92 { value: "low", label: "Low", isDefault: true },
93 { value: "medium", label: "Medium" },
94 { value: "high", label: "High" },
95 ],
96 }),
97 ],
98 }),
99 },
100];
101
102export function getPiModelCapabilities(model: string | null | undefined): ModelCapabilities {
103 const slug = model?.trim();
104 return (
105 BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ??
106 DEFAULT_PI_MODEL_CAPABILITIES
107 );
108}
109
110const runPiCommand = Effect.fn("runPiCommand")(function* (
111 piSettings: PiSettings,
112 args: ReadonlyArray<string>,
113 environment: NodeJS.ProcessEnv = process.env,
114) {
115 const piEnvironment = yield* makePiEnvironment(piSettings, environment);
116 const command = ChildProcess.make(piSettings.binaryPath || "pi", [...args], {
117 env: piEnvironment,
118 shell: false,
119 });
120 return yield* spawnAndCollect(piSettings.binaryPath || "pi", command);
121});
122
123const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
124
125function parseSkillFrontmatter(content: string): {
126 name?: string;
127 description?: string;
128} {
129 const match = /^---\s*\n([\s\S]*?)\n---/.exec(content);
130 if (!match?.[1]) return {};
131 const yaml = match[1];
132 const result: { name?: string; description?: string } = {};
133 for (const line of yaml.split("\n")) {
134 const kvMatch = /^(\w[\w-]*):\s*(.+)$/.exec(line.trim());
135 if (!kvMatch) continue;
136 const key = kvMatch[1];
137 const rawValue = kvMatch[2] ?? "";
138 const value = rawValue.replace(/^["']|["']$/g, "").trim();
139 if (key === "name" && value.length > 0) result.name = value;
140 if (key === "description" && value.length > 0) result.description = value;
141 }
142 return result;
143}
144
145function skillNameFromPath(filePath: string, pathSep: string): string {
146 const base = filePath.split(pathSep).pop() ?? filePath;
147 return base.replace(/\.md$/i, "");
148}
149
150const scanSkillDir = Effect.fn("scanSkillDir")(function* (
151 dir: string,
152 scope: string,
153): Effect.fn.Return<
154 ServerProviderSkill[],
155 never,
156 FileSystem.FileSystem | Path.Path
157> {
158 const fs = yield* FileSystem.FileSystem;
159 const path = yield* Path.Path;
160 const skills: ServerProviderSkill[] = [];
161
162 const exists = yield* fs.exists(dir).pipe(Effect.orElseSucceed(() => false));
163 if (!exists) return skills;
164
165 const entries = yield* fs.readDirectory(dir).pipe(Effect.orElseSucceed(() => [] as string[]));
166
167 for (const entry of entries) {
168 const entryPath = path.join(dir, entry);
169 const stat = yield* fs.stat(entryPath).pipe(Effect.orElseSucceed(() => undefined));
170 if (!stat) continue;
171
172 if (stat.type === "Directory") {
173 const skillMdPath = path.join(entryPath, "SKILL.md");
174 const hasSkillMd = yield* fs.exists(skillMdPath).pipe(Effect.orElseSucceed(() => false));
175 if (hasSkillMd) {
176 const content = yield* fs.readFileString(skillMdPath).pipe(
177 Effect.orElseSucceed(() => ""),
178 );
179 const frontmatter = parseSkillFrontmatter(content);
180 const name = frontmatter.name ?? entry;
181 skills.push({
182 name,
183 path: skillMdPath,
184 enabled: true,
185 scope,
186 ...(frontmatter.description ? { description: frontmatter.description } : {}),
187 ...(frontmatter.name ? { displayName: frontmatter.name } : {}),
188 });
189 }
190 continue;
191 }
192
193 if (entry.endsWith(".md")) {
194 const content = yield* fs.readFileString(entryPath).pipe(
195 Effect.orElseSucceed(() => ""),
196 );
197 const frontmatter = parseSkillFrontmatter(content);
198 const name = frontmatter.name ?? skillNameFromPath(entry, path.sep);
199 skills.push({
200 name,
201 path: entryPath,
202 enabled: true,
203 ...(scope ? { scope } : {}),
204 ...(frontmatter.description ? { description: frontmatter.description } : {}),
205 ...(frontmatter.name ? { displayName: frontmatter.name } : {}),
206 });
207 }
208 }
209
210 return skills;
211});
212
213const discoverPiSkills = Effect.fn("discoverPiSkills")(function* (
214 cwd: string,
215 piSettings: PiSettings,
216): Effect.fn.Return<
217 ReadonlyArray<ServerProviderSkill>,
218 never,
219 FileSystem.FileSystem | Path.Path
220> {
221 const path = yield* Path.Path;
222 const piHomePath = yield* resolvePiHomePath(piSettings);
223
224 const dirs: Array<{ dir: string; scope: string }> = [
225 { dir: path.join(cwd, ".pi", "skills"), scope: "project" },
226 { dir: path.join(cwd, ".claude", "skills"), scope: "project" },
227 { dir: path.join(piHomePath, ".pi", "agent", "skills"), scope: "user" },
228 ];
229
230 const results = yield* Effect.all(
231 dirs.map(({ dir, scope }) => scanSkillDir(dir, scope)),
232 { concurrency: "unbounded" },
233 );
234
235 const seen = new Set<string>();
236 const deduped: ServerProviderSkill[] = [];
237 for (const batch of results) {
238 for (const skill of batch) {
239 if (!seen.has(skill.name)) {
240 seen.add(skill.name);
241 deduped.push(skill);
242 }
243 }
244 }
245 return deduped;
246});
247
248export const checkPiProviderStatus = Effect.fn("checkPiProviderStatus")(function* (
249 piSettings: PiSettings,
250 cwd: string,
251 environment: NodeJS.ProcessEnv = process.env,
252): Effect.fn.Return<
253 ServerProviderDraft,
254 never,
255 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
256> {
257 const checkedAt = DateTime.formatIso(yield* DateTime.now);
258 const allModels = providerModelsFromSettings(
259 BUILT_IN_MODELS,
260 PROVIDER,
261 piSettings.customModels,
262 DEFAULT_PI_MODEL_CAPABILITIES,
263 );
264
265 if (!piSettings.enabled) {
266 return buildServerProvider({
267 presentation: PI_PRESENTATION,
268 enabled: false,
269 checkedAt,
270 models: allModels,
271 probe: {
272 installed: false,
273 version: null,
274 status: "warning",
275 auth: { status: "unknown" },
276 message: "Pi Agent is disabled in T3 Code settings.",
277 },
278 });
279 }
280
281 const versionProbe = yield* runPiCommand(piSettings, ["--version"], environment).pipe(
282 Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
283 Effect.result,
284 );
285
286 if (Result.isFailure(versionProbe)) {
287 const error = versionProbe.failure;
288 return buildServerProvider({
289 presentation: PI_PRESENTATION,
290 enabled: piSettings.enabled,
291 checkedAt,
292 models: allModels,
293 probe: {
294 installed: !isCommandMissingCause(error),
295 version: null,
296 status: "error",
297 auth: { status: "unknown" },
298 message: isCommandMissingCause(error)
299 ? "Pi Agent CLI (`pi`) is not installed or not on PATH."
300 : `Failed to execute Pi Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
301 },
302 });
303 }
304
305 if (Option.isNone(versionProbe.success)) {
306 return buildServerProvider({
307 presentation: PI_PRESENTATION,
308 enabled: piSettings.enabled,
309 checkedAt,
310 models: allModels,
311 probe: {
312 installed: true,
313 version: null,
314 status: "error",
315 auth: { status: "unknown" },
316 message: "Pi Agent CLI is installed but failed to run. Timed out while running command.",
317 },
318 });
319 }
320
321 const version = versionProbe.success.value;
322 const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
323
324 if (version.code !== 0) {
325 const detail = detailFromResult(version);
326 return buildServerProvider({
327 presentation: PI_PRESENTATION,
328 enabled: piSettings.enabled,
329 checkedAt,
330 models: allModels,
331 probe: {
332 installed: true,
333 version: parsedVersion,
334 status: "error",
335 auth: { status: "unknown" },
336 message: detail ?? "Pi Agent CLI returned an error during health check.",
337 },
338 });
339 }
340
341 const skills = yield* discoverPiSkills(cwd, piSettings).pipe(
342 Effect.orElseSucceed(() => [] as ServerProviderSkill[]),
343 );
344
345 return buildServerProvider({
346 presentation: PI_PRESENTATION,
347 enabled: piSettings.enabled,
348 checkedAt,
349 models: allModels,
350 skills,
351 probe: {
352 installed: true,
353 version: parsedVersion,
354 status: "ready",
355 auth: { status: "authenticated" },
356 },
357 });
358});
359
360export const makePendingPiProvider = (piSettings: PiSettings): Effect.Effect<ServerProviderDraft> =>
361 Effect.gen(function* () {
362 const checkedAt = yield* nowIso;
363 const models = providerModelsFromSettings(
364 BUILT_IN_MODELS,
365 PROVIDER,
366 piSettings.customModels,
367 DEFAULT_PI_MODEL_CAPABILITIES,
368 );
369
370 if (!piSettings.enabled) {
371 return buildServerProvider({
372 presentation: PI_PRESENTATION,
373 enabled: false,
374 checkedAt,
375 models,
376 probe: {
377 installed: false,
378 version: null,
379 status: "warning",
380 auth: { status: "unknown" },
381 message: "Pi Agent is disabled in T3 Code settings.",
382 },
383 });
384 }
385
386 return buildServerProvider({
387 presentation: PI_PRESENTATION,
388 enabled: true,
389 checkedAt,
390 models,
391 probe: {
392 installed: false,
393 version: null,
394 status: "warning",
395 auth: { status: "unknown" },
396 message: "Pi Agent provider status has not been checked in this session yet.",
397 },
398 });
399 });