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

AntigravitySkills.ts

287 lines10.2 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/** Match Python os.path.expanduser: USERPROFILE, then HOMEDRIVE+HOMEPATH on Windows; HOME elsewhere. */
11export function resolveAntigravityUserHome(
12 platform: NodeJS.Platform,
13 environment: NodeJS.ProcessEnv,
14 home: string,
15): string {
16 if (platform === "win32") {
17 if (environment.USERPROFILE) return environment.USERPROFILE;
18 if (environment.HOMEDRIVE && environment.HOMEPATH) {
19 return `${environment.HOMEDRIVE}${environment.HOMEPATH}`;
20 }
21 return home;
22 }
23 return environment.HOME || home;
25​
26/** Link private GEMINI_HOME skills to ~/.gemini; ~/.agents/skills is ignored because .agents/skills is project-only. */
27export function antigravityUserSkillDirectories(
28 path: Path.Path,
29 geminiHome: string,
30): readonly [configSkills: string, cliSkills: string] {
31 return [
32 path.join(geminiHome, "config", "skills"),
33 path.join(geminiHome, "antigravity-cli", "skills"),
34 ];
36​
37const MAX_SKILL_BYTES = 1_000_000;
38const MAX_SCAN_BYTES = 8_000_000;
39const MAX_SCAN_ENTRIES = 10_000;
40// Typical frontmatter fits in one chunk, so most skills cost about this much of the scan budget.
41const SKILL_READ_CHUNK_BYTES = 1024;
42​
43const SkillFrontmatter = Schema.Struct({
44 name: Schema.optional(Schema.NullOr(Schema.String)),
45 description: Schema.optional(Schema.NullOr(Schema.String)),
46});
47const decodeSkillFrontmatter = Schema.decodeUnknownSync(SkillFrontmatter);
48const decodePluginPreferences = Schema.decodeUnknownOption(
49 Schema.fromJsonString(
50 Schema.Struct({
51 plugins: Schema.optional(
52 Schema.Record(Schema.String, Schema.Struct({ enabled: Schema.optional(Schema.Boolean) })),
53 ),
54 }),
55 ),
56);
57​
58export class AntigravitySkillsProbeError extends Schema.TaggedError<AntigravitySkillsProbeError>()(
59 "AntigravitySkillsProbeError",
60 {
61 reason: Schema.Literals(["scan-budget-exhausted", "filesystem-error"]),
62 path: Schema.String,
63 cause: Schema.optional(Schema.Defect()),
64 },
65) {
66 override get message(): string {
67 return this.reason === "scan-budget-exhausted"
68 ? `Antigravity skill discovery exceeded its scan limit at '${this.path}'.`
69 : `Antigravity could not read skills at '${this.path}'.`;
70 }
72​
73interface ScanBudget {
74 remainingBytes: number;
75 remainingEntries: number;
77​
78const readIfPresent = <A, R>(
79 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
80 path: string,
81) =>
82 effect.pipe(
83 Effect.catchTags({
84 PlatformError: (cause) =>
85 cause.reason._tag === "NotFound"
86 ? Effect.undefined
87 : Effect.fail(
88 new AntigravitySkillsProbeError({ reason: "filesystem-error", path, cause }),
89 ),
90 }),
91 );
92​
93function parseSkillFrontmatter(contents: string, fileName: string) {
94 const start = contents.indexOf("---");
95 if (start === -1) return undefined;
96 const end = contents.indexOf("---", start + 3);
97 if (end === -1) return undefined;
98 try {
99 const frontmatter = decodeSkillFrontmatter(
100 parseYamlDocument(contents.slice(start + 3, end).trim()) ?? {},
101 );
102 const name = frontmatter.name || fileName.slice(0, -3);
103 const description = frontmatter.description?.trim();
104 // Native names are not trimmed. Do not rename one to fit the picker contract.
105 if (!name || name !== name.trim()) return undefined;
106 return { name, ...(description ? { description } : {}) };
107 } catch {
108 return undefined;
109 }
111​
112/** The native loader orders child paths with Go's URL.EscapedPath encoding. */
113function skillPathSortKey(entry: string) {
114 return encodeURI(entry).replace(
115 /[!'()*?#]/g,
116 (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
117 );
119​
120const DASH = 0x2d;
121​
122/** Finds the byte offset after the second `---`, as parseSkillFrontmatter's indexOf calls do. */
123function makeFrontmatterEndFinder() {
124 let bytesSeen = 0;
125 let dashes = 0;
126 let markers = 0;
127 return (chunk: Uint8Array) => {
128 for (const byte of chunk) {
129 bytesSeen += 1;
130 dashes = byte === DASH ? dashes + 1 : 0;
131 if (dashes === 3) {
132 dashes = 0;
133 markers += 1;
134 if (markers === 2) return bytesSeen;
135 }
136 }
137 return undefined;
138 };
140​
141/** Reads through the frontmatter only, so skill bodies do not spend the scan budget. */
142const readSkillFrontmatter = Effect.fn("readAntigravitySkill")(function* (
143 skillPath: string,
144 budget: ScanBudget,
145) {
146 const fileSystem = yield* FileSystem.FileSystem;
147 const info = yield* readIfPresent(fileSystem.stat(skillPath), skillPath);
148 if (info?.type !== "File") return undefined;
149​
150 const byteLimit = Math.min(MAX_SKILL_BYTES, budget.remainingBytes);
151 const findFrontmatterEnd = makeFrontmatterEndFinder();
152 let frontmatterEnd: number | undefined;
153 const chunks = yield* readIfPresent(
154 fileSystem
155 .stream(skillPath, { bytesToRead: byteLimit + 1, chunkSize: SKILL_READ_CHUNK_BYTES })
156 .pipe(
157 Stream.takeUntil((chunk) => (frontmatterEnd = findFrontmatterEnd(chunk)) !== undefined),
158 Stream.runCollect,
159 ),
160 skillPath,
161 );
162 if (chunks === undefined) return undefined;
163 const bytes = Buffer.concat(chunks);
164 budget.remainingBytes -= bytes.byteLength;
165 if ((frontmatterEnd ?? bytes.byteLength) > byteLimit) {
166 return yield* new AntigravitySkillsProbeError({
167 reason: "scan-budget-exhausted",
168 path: skillPath,
169 });
170 }
171 return bytes.toString("utf8", 0, frontmatterEnd);
172});
173​
174/** Keep read errors typed so workspace snapshots cannot cache partial results. */
175export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")(function* (input: {
176 readonly cwd: string;
177 readonly userHome: string;
178 /** The instance's GEMINI_HOME, where agy loads plugins from. */
179 readonly profileDirectory: string;
180}): Effect.fn.Return<
181 ReadonlyArray<ServerProviderSkill>,
182 AntigravitySkillsProbeError,
183 FileSystem.FileSystem | Path.Path
184> {
185 const fileSystem = yield* FileSystem.FileSystem;
186 const path = yield* Path.Path;
187 const [configSkills, cliSkills] = antigravityUserSkillDirectories(
188 path,
189 path.join(input.userHome, ".gemini"),
190 );
191 const roots = [
192 { directory: configSkills, scope: "user" },
193 { directory: path.resolve(input.cwd, ".gemini", "skills"), scope: "project" },
194 { directory: cliSkills, scope: "user" },
195 { directory: path.resolve(input.cwd, ".agents", "skills"), scope: "project" },
196 { directory: path.resolve(input.cwd, ".agent", "skills"), scope: "project" },
197 ];
198 const budget: ScanBudget = {
199 remainingBytes: MAX_SCAN_BYTES,
200 remainingEntries: MAX_SCAN_ENTRIES,
201 };
202 const skillsByName = new Map<string, ServerProviderSkill>();
203​
204 const scanDirectory = Effect.fn("scanAntigravitySkillDirectory")(function* (
205 directory: string,
206 scope: string,
207 scanChildren: boolean,
208 ): Effect.fn.Return<void, AntigravitySkillsProbeError, FileSystem.FileSystem> {
209 const info = yield* readIfPresent(fileSystem.stat(directory), directory);
210 if (info?.type !== "Directory") return;
211 const entries = yield* readIfPresent(fileSystem.readDirectory(directory), directory);
212 if (entries === undefined) return;
213 if (entries.length > budget.remainingEntries) {
214 return yield* new AntigravitySkillsProbeError({
215 reason: "scan-budget-exhausted",
216 path: directory,
217 });
218 }
219 budget.remainingEntries -= entries.length;
220​
221 const sortedEntries = entries.toSorted();
222 const skillFileName = sortedEntries.find((entry) => entry.toLowerCase() === "skill.md");
223 if (skillFileName !== undefined) {
224 if (!skillFileName.endsWith(".md")) return;
225 const skillPath = path.join(directory, skillFileName);
226 const contents = yield* readSkillFrontmatter(skillPath, budget);
227 if (contents === undefined) return;
228 const skill = parseSkillFrontmatter(contents, skillFileName);
229 if (!skill || skillsByName.has(skill.name)) return;
230 skillsByName.set(skill.name, {
231 ...skill,
232 path: skillPath,
233 scope,
234 enabled: true,
235 });
236 return;
237 }
238 if (scanChildren) {
239 const children = sortedEntries
240 .map((entry) => ({ entry, sortKey: skillPathSortKey(entry) }))
241 .sort((left, right) =>
242 left.sortKey < right.sortKey ? -1 : left.sortKey > right.sortKey ? 1 : 0,
243 );
244 for (const { entry } of children) {
245 yield* scanDirectory(path.join(directory, entry), scope, false);
246 }
247 }
248 });
249​
250 for (const root of roots) {
251 yield* scanDirectory(root.directory, root.scope, true);
252 }
253​
254 const pluginsDirectory = path.join(input.profileDirectory, "config", "plugins");
255 const plugins = yield* readIfPresent(
256 fileSystem.readDirectory(pluginsDirectory),
257 pluginsDirectory,
258 );
259 if (plugins !== undefined && plugins.length > 0) {
260 const configPath = path.join(input.profileDirectory, "config", "config.json");
261 const configInfo = yield* readIfPresent(fileSystem.stat(configPath), configPath);
262 if (configInfo?.type === "File" && configInfo.size > BigInt(MAX_SKILL_BYTES)) {
263 return yield* new AntigravitySkillsProbeError({
264 reason: "scan-budget-exhausted",
265 path: configPath,
266 });
267 }
268 const config =
269 configInfo?.type === "File"
270 ? yield* readIfPresent(fileSystem.readFileString(configPath), configPath)
271 : undefined;
272 const preferences = config === undefined ? undefined : decodePluginPreferences(config);
273 const disabled = new Set(
274 Object.entries(
275 (preferences?._tag === "Some" ? preferences.value.plugins : undefined) ?? {},
276 ).flatMap(([name, plugin]) => (plugin.enabled === false ? [name] : [])),
277 );
278 for (const plugin of plugins.toSorted()) {
279 if (disabled.has(plugin)) continue;
280 const pluginDirectory = path.join(pluginsDirectory, plugin);
281 const info = yield* readIfPresent(fileSystem.stat(pluginDirectory), pluginDirectory);
282 if (info?.type !== "Directory") continue;
283 yield* scanDirectory(path.join(pluginDirectory, "skills"), "user", true);
284 }
285 }
286 return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
287});