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

AntigravitySkills.ts

230 lines7.8 KB

1import type { ServerProviderSkill } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Path from "effect/Path";
5import type * as PlatformError from "effect/PlatformError";
6import * as Schema from "effect/Schema";
7import * as Stream from "effect/Stream";
8import { parse as parseYamlDocument } from "yaml";
9​
10/**
11 * The home directory the agent expands `~` against, matching Python's
12 * `os.path.expanduser` in the launch environment T3 hands the process:
13 * `USERPROFILE`, then `HOMEDRIVE` + `HOMEPATH`, on Windows and `HOME`
14 * elsewhere.
15 */
16export function resolveAntigravityUserHome(
17 platform: NodeJS.Platform,
18 environment: NodeJS.ProcessEnv,
19 home: string,
20): string {
21 if (platform === "win32") {
22 if (environment.USERPROFILE) return environment.USERPROFILE;
23 if (environment.HOMEDRIVE && environment.HOMEPATH) {
24 return `${environment.HOMEDRIVE}${environment.HOMEPATH}`;
25 }
26 return home;
27 }
28 return environment.HOME || home;
30​
31/**
32 * The agent resolves both under `GEMINI_HOME`, which T3 points at a private
33 * profile, so the profile links these back to the user's `~/.gemini`.
34 * `~/.agents/skills` is not read: the agent only treats `.agents/skills` as a
35 * project directory.
36 */
37export function antigravityUserSkillDirectories(
38 path: Path.Path,
39 geminiHome: string,
40): readonly [configSkills: string, cliSkills: string] {
41 return [
42 path.join(geminiHome, "config", "skills"),
43 path.join(geminiHome, "antigravity-cli", "skills"),
44 ];
46​
47const MAX_SKILL_BYTES = 1_000_000;
48const MAX_SCAN_BYTES = 8_000_000;
49const MAX_SCAN_ENTRIES = 10_000;
50​
51const SkillFrontmatter = Schema.Struct({
52 name: Schema.optional(Schema.NullOr(Schema.String)),
53 description: Schema.optional(Schema.NullOr(Schema.String)),
54});
55const decodeSkillFrontmatter = Schema.decodeUnknownSync(SkillFrontmatter);
56​
57export class AntigravitySkillsProbeError extends Schema.TaggedError<AntigravitySkillsProbeError>()(
58 "AntigravitySkillsProbeError",
59 {
60 reason: Schema.Literals(["scan-budget-exhausted", "filesystem-error"]),
61 path: Schema.String,
62 cause: Schema.optional(Schema.Defect()),
63 },
64) {
65 override get message(): string {
66 return this.reason === "scan-budget-exhausted"
67 ? `Antigravity skill discovery exceeded its scan limit at '${this.path}'.`
68 : `Antigravity could not read skills at '${this.path}'.`;
69 }
71​
72interface ScanBudget {
73 remainingBytes: number;
74 remainingEntries: number;
76​
77const readIfPresent = <A, R>(
78 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
79 path: string,
80) =>
81 effect.pipe(
82 Effect.catchTags({
83 PlatformError: (cause) =>
84 cause.reason._tag === "NotFound"
85 ? Effect.undefined
86 : Effect.fail(
87 new AntigravitySkillsProbeError({ reason: "filesystem-error", path, cause }),
88 ),
89 }),
90 );
91​
92function parseSkillFrontmatter(contents: string, fileName: string) {
93 const start = contents.indexOf("---");
94 if (start === -1) return undefined;
95 const end = contents.indexOf("---", start + 3);
96 if (end === -1) return undefined;
97 try {
98 const frontmatter = decodeSkillFrontmatter(
99 parseYamlDocument(contents.slice(start + 3, end).trim()) ?? {},
100 );
101 const name = frontmatter.name || fileName.slice(0, -3);
102 const description = frontmatter.description?.trim();
103 // Native names are not trimmed. Do not rename one to fit the picker contract.
104 if (!name || name !== name.trim()) return undefined;
105 return { name, ...(description ? { description } : {}) };
106 } catch {
107 return undefined;
108 }
110​
111/** The native loader orders child paths with Go's URL.EscapedPath encoding. */
112function skillPathSortKey(entry: string) {
113 return encodeURI(entry).replace(
114 /[!'()*?#]/g,
115 (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
116 );
118​
119const readSkill = Effect.fn("readAntigravitySkill")(function* (
120 skillPath: string,
121 budget: ScanBudget,
122) {
123 const fileSystem = yield* FileSystem.FileSystem;
124 const info = yield* readIfPresent(fileSystem.stat(skillPath), skillPath);
125 if (info?.type !== "File") return undefined;
126​
127 const byteLimit = Math.min(MAX_SKILL_BYTES, budget.remainingBytes);
128 if (info.size > BigInt(byteLimit)) {
129 return yield* new AntigravitySkillsProbeError({
130 reason: "scan-budget-exhausted",
131 path: skillPath,
132 });
133 }
134 const chunks = yield* readIfPresent(
135 fileSystem.stream(skillPath, { bytesToRead: byteLimit + 1 }).pipe(Stream.runCollect),
136 skillPath,
137 );
138 if (chunks === undefined) return undefined;
139 const bytes = Buffer.concat(chunks);
140 if (bytes.byteLength > byteLimit) {
141 return yield* new AntigravitySkillsProbeError({
142 reason: "scan-budget-exhausted",
143 path: skillPath,
144 });
145 }
146 budget.remainingBytes -= bytes.byteLength;
147 return bytes.toString("utf8");
148});
149​
150/**
151 * Read failures remain typed so workspace snapshots do not cache partial results.
152 */
153export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")(function* (input: {
154 readonly cwd: string;
155 readonly userHome: string;
156}): Effect.fn.Return<
157 ReadonlyArray<ServerProviderSkill>,
158 AntigravitySkillsProbeError,
159 FileSystem.FileSystem | Path.Path
160> {
161 const fileSystem = yield* FileSystem.FileSystem;
162 const path = yield* Path.Path;
163 const [configSkills, cliSkills] = antigravityUserSkillDirectories(
164 path,
165 path.join(input.userHome, ".gemini"),
166 );
167 const roots = [
168 { directory: configSkills, scope: "user" },
169 { directory: path.resolve(input.cwd, ".gemini", "skills"), scope: "project" },
170 { directory: cliSkills, scope: "user" },
171 { directory: path.resolve(input.cwd, ".agents", "skills"), scope: "project" },
172 { directory: path.resolve(input.cwd, ".agent", "skills"), scope: "project" },
173 ];
174 const budget: ScanBudget = {
175 remainingBytes: MAX_SCAN_BYTES,
176 remainingEntries: MAX_SCAN_ENTRIES,
177 };
178 const skillsByName = new Map<string, ServerProviderSkill>();
179​
180 const scanDirectory = Effect.fn("scanAntigravitySkillDirectory")(function* (
181 directory: string,
182 scope: string,
183 scanChildren: boolean,
184 ): Effect.fn.Return<void, AntigravitySkillsProbeError, FileSystem.FileSystem> {
185 const info = yield* readIfPresent(fileSystem.stat(directory), directory);
186 if (info?.type !== "Directory") return;
187 const entries = yield* readIfPresent(fileSystem.readDirectory(directory), directory);
188 if (entries === undefined) return;
189 if (entries.length > budget.remainingEntries) {
190 return yield* new AntigravitySkillsProbeError({
191 reason: "scan-budget-exhausted",
192 path: directory,
193 });
194 }
195 budget.remainingEntries -= entries.length;
196​
197 const sortedEntries = entries.toSorted();
198 const skillFileName = sortedEntries.find((entry) => entry.toLowerCase() === "skill.md");
199 if (skillFileName !== undefined) {
200 if (!skillFileName.endsWith(".md")) return;
201 const skillPath = path.join(directory, skillFileName);
202 const contents = yield* readSkill(skillPath, budget);
203 if (contents === undefined) return;
204 const skill = parseSkillFrontmatter(contents, skillFileName);
205 if (!skill || skillsByName.has(skill.name)) return;
206 skillsByName.set(skill.name, {
207 ...skill,
208 path: skillPath,
209 scope,
210 enabled: true,
211 });
212 return;
213 }
214 if (scanChildren) {
215 const children = sortedEntries
216 .map((entry) => ({ entry, sortKey: skillPathSortKey(entry) }))
217 .sort((left, right) =>
218 left.sortKey < right.sortKey ? -1 : left.sortKey > right.sortKey ? 1 : 0,
219 );
220 for (const { entry } of children) {
221 yield* scanDirectory(path.join(directory, entry), scope, false);
222 }
223 }
224 });
225​
226 for (const root of roots) {
227 yield* scanDirectory(root.directory, root.scope, true);
228 }
229 return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
230});