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

AntigravitySkills.ts

439 lines15.1 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;
40const MAX_INHERIT_DEPTH = 10;
41// Typical frontmatter fits in one chunk, so most skills cost about this much of the scan budget.
42const SKILL_READ_CHUNK_BYTES = 1024;
43​
44const SkillFrontmatter = Schema.Struct({
45 name: Schema.optional(Schema.NullOr(Schema.String)),
46 description: Schema.optional(Schema.NullOr(Schema.String)),
47});
48const decodeSkillFrontmatter = Schema.decodeUnknownSync(SkillFrontmatter);
49const SkillConfigEntry = Schema.Struct({
50 path: Schema.String,
51 include_only: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))),
52 exclude: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))),
53});
54const decodeSkillsConfig = Schema.decodeUnknownOption(
55 Schema.fromJsonString(
56 Schema.Struct({
57 inherits: Schema.optional(Schema.NullOr(Schema.Array(SkillConfigEntry))),
58 entries: Schema.optional(Schema.NullOr(Schema.Array(SkillConfigEntry))),
59 }),
60 ),
61);
62const decodePluginPreferences = Schema.decodeUnknownOption(
63 Schema.fromJsonString(
64 Schema.Struct({
65 plugins: Schema.optional(
66 Schema.Record(Schema.String, Schema.Struct({ enabled: Schema.optional(Schema.Boolean) })),
67 ),
68 }),
69 ),
70);
71​
72export class AntigravitySkillsProbeError extends Schema.TaggedError<AntigravitySkillsProbeError>()(
73 "AntigravitySkillsProbeError",
74 {
75 reason: Schema.Literals(["scan-budget-exhausted", "filesystem-error"]),
76 path: Schema.String,
77 cause: Schema.optional(Schema.Defect()),
78 },
79) {
80 override get message(): string {
81 return this.reason === "scan-budget-exhausted"
82 ? `Antigravity skill discovery exceeded its scan limit at '${this.path}'.`
83 : `Antigravity could not read skills at '${this.path}'.`;
84 }
86​
87interface ScanBudget {
88 remainingBytes: number;
89 remainingEntries: number;
91​
92const readIfPresent = <A, R>(
93 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
94 path: string,
95) =>
96 effect.pipe(
97 Effect.catchTags({
98 PlatformError: (cause) =>
99 cause.reason._tag === "NotFound"
100 ? Effect.undefined
101 : Effect.fail(
102 new AntigravitySkillsProbeError({ reason: "filesystem-error", path, cause }),
103 ),
104 }),
105 );
106​
107function parseSkillFrontmatter(contents: string, fileName: string) {
108 const start = contents.indexOf("---");
109 if (start === -1) return undefined;
110 const end = contents.indexOf("---", start + 3);
111 if (end === -1) return undefined;
112 try {
113 const frontmatter = decodeSkillFrontmatter(
114 parseYamlDocument(contents.slice(start + 3, end).trim()) ?? {},
115 );
116 const name = frontmatter.name || fileName.slice(0, -3);
117 const description = frontmatter.description?.trim();
118 // Native names are not trimmed. Do not rename one to fit the picker contract.
119 if (!name || name !== name.trim()) return undefined;
120 return { name, ...(description ? { description } : {}) };
121 } catch {
122 return undefined;
123 }
125​
126/** The native loader orders child paths with Go's URL.EscapedPath encoding. */
127function skillPathSortKey(entry: string) {
128 return encodeURI(entry).replace(
129 /[!'()*?#]/g,
130 (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
131 );
133​
134const DASH = 0x2d;
135​
136/** Finds the byte offset after the second `---`, as parseSkillFrontmatter's indexOf calls do. */
137function makeFrontmatterEndFinder() {
138 let bytesSeen = 0;
139 let dashes = 0;
140 let markers = 0;
141 return (chunk: Uint8Array) => {
142 for (const byte of chunk) {
143 bytesSeen += 1;
144 dashes = byte === DASH ? dashes + 1 : 0;
145 if (dashes === 3) {
146 dashes = 0;
147 markers += 1;
148 if (markers === 2) return bytesSeen;
149 }
150 }
151 return undefined;
152 };
154​
155/** Reads through the frontmatter only, so skill bodies do not spend the scan budget. */
156const readSkillFrontmatter = Effect.fn("readAntigravitySkill")(function* (
157 skillPath: string,
158 budget: ScanBudget,
159) {
160 const fileSystem = yield* FileSystem.FileSystem;
161 const info = yield* readIfPresent(fileSystem.stat(skillPath), skillPath);
162 if (info?.type !== "File") return undefined;
163​
164 const byteLimit = Math.min(MAX_SKILL_BYTES, budget.remainingBytes);
165 const findFrontmatterEnd = makeFrontmatterEndFinder();
166 let frontmatterEnd: number | undefined;
167 const chunks = yield* readIfPresent(
168 fileSystem
169 .stream(skillPath, { bytesToRead: byteLimit + 1, chunkSize: SKILL_READ_CHUNK_BYTES })
170 .pipe(
171 Stream.takeUntil((chunk) => (frontmatterEnd = findFrontmatterEnd(chunk)) !== undefined),
172 Stream.runCollect,
173 ),
174 skillPath,
175 );
176 if (chunks === undefined) return undefined;
177 const bytes = Buffer.concat(chunks);
178 budget.remainingBytes -= bytes.byteLength;
179 if ((frontmatterEnd ?? bytes.byteLength) > byteLimit) {
180 return yield* new AntigravitySkillsProbeError({
181 reason: "scan-budget-exhausted",
182 path: skillPath,
183 });
184 }
185 return bytes.toString("utf8", 0, frontmatterEnd);
186});
187​
188interface SkillEntryFilter {
189 readonly includeGroups: ReadonlyArray<ReadonlyArray<string>>;
190 readonly excludeNames: ReadonlyArray<string>;
192​
193const EMPTY_SKILL_FILTER: SkillEntryFilter = {
194 includeGroups: [],
195 excludeNames: [],
196};
197​
198function matchesSkillFilter(entry: string, filter: SkillEntryFilter): boolean {
199 for (const group of filter.includeGroups) {
200 if (!group.includes(entry)) return false;
201 }
202 return !filter.excludeNames.includes(entry);
204​
205function narrowSkillFilter(
206 parent: SkillEntryFilter,
207 entry: typeof SkillConfigEntry.Type,
208): SkillEntryFilter {
209 const includeGroups =
210 entry.include_only && entry.include_only.length > 0
211 ? [...parent.includeGroups, entry.include_only]
212 : parent.includeGroups;
213 const excludeNames =
214 entry.exclude && entry.exclude.length > 0
215 ? [...parent.excludeNames, ...entry.exclude]
216 : parent.excludeNames;
217 return { includeGroups, excludeNames };
219​
220// agy does not expand ~, so a ~/ path stays relative to the config file.
221function resolveSkillsConfigPath(path: Path.Path, rawPath: string, baseDir: string): string {
222 return path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseDir, rawPath);
224​
225/** Keep read errors typed so workspace snapshots cannot cache partial results. */
226export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")(function* (input: {
227 readonly cwd: string;
228 readonly userHome: string;
229 /** The instance's GEMINI_HOME, where agy loads plugins from. */
230 readonly profileDirectory: string;
231}): Effect.fn.Return<
232 ReadonlyArray<ServerProviderSkill>,
233 AntigravitySkillsProbeError,
234 FileSystem.FileSystem | Path.Path
235> {
236 const fileSystem = yield* FileSystem.FileSystem;
237 const path = yield* Path.Path;
238 const [configSkills, cliSkills] = antigravityUserSkillDirectories(
239 path,
240 path.join(input.userHome, ".gemini"),
241 );
242 const roots = [
243 { directory: configSkills, scope: "user" },
244 { directory: path.resolve(input.cwd, ".gemini", "skills"), scope: "project" },
245 { directory: cliSkills, scope: "user" },
246 { directory: path.resolve(input.cwd, ".agents", "skills"), scope: "project" },
247 { directory: path.resolve(input.cwd, ".agent", "skills"), scope: "project" },
248 ];
249 const budget: ScanBudget = {
250 remainingBytes: MAX_SCAN_BYTES,
251 remainingEntries: MAX_SCAN_ENTRIES,
252 };
253 const skillsByName = new Map<string, ServerProviderSkill>();
254​
255 const addSkillFile = Effect.fn("addAntigravitySkillFile")(function* (
256 skillPath: string,
257 scope: string,
258 ) {
259 const fileName = path.basename(skillPath);
260 if (fileName.toLowerCase() !== "skill.md" || !fileName.endsWith(".md")) return;
261 const contents = yield* readSkillFrontmatter(skillPath, budget);
262 if (contents === undefined) return;
263 const skill = parseSkillFrontmatter(contents, fileName);
264 if (!skill || skillsByName.has(skill.name)) return;
265 skillsByName.set(skill.name, {
266 ...skill,
267 path: skillPath,
268 scope,
269 enabled: true,
270 });
271 });
272​
273 const scanDirectory = Effect.fn("scanAntigravitySkillDirectory")(function* (
274 directory: string,
275 scope: string,
276 scanChildren: boolean,
277 filter: SkillEntryFilter = EMPTY_SKILL_FILTER,
278 acceptSkillFile = false,
279 ): Effect.fn.Return<void, AntigravitySkillsProbeError, FileSystem.FileSystem> {
280 const info = yield* readIfPresent(fileSystem.stat(directory), directory);
281 if (info?.type === "File" && acceptSkillFile) {
282 if (budget.remainingEntries === 0) {
283 return yield* new AntigravitySkillsProbeError({
284 reason: "scan-budget-exhausted",
285 path: directory,
286 });
287 }
288 budget.remainingEntries -= 1;
289 if (matchesSkillFilter(path.basename(path.dirname(directory)), filter)) {
290 yield* addSkillFile(directory, scope);
291 }
292 return;
293 }
294 if (info?.type !== "Directory") return;
295 const entries = yield* readIfPresent(fileSystem.readDirectory(directory), directory);
296 if (entries === undefined) return;
297 if (entries.length > budget.remainingEntries) {
298 return yield* new AntigravitySkillsProbeError({
299 reason: "scan-budget-exhausted",
300 path: directory,
301 });
302 }
303 budget.remainingEntries -= entries.length;
304​
305 const sortedEntries = entries.toSorted();
306 const skillFileName = sortedEntries.find((entry) => entry.toLowerCase() === "skill.md");
307 if (skillFileName !== undefined) {
308 yield* addSkillFile(path.join(directory, skillFileName), scope);
309 return;
310 }
311 if (scanChildren) {
312 const children = sortedEntries
313 .filter((entry) => matchesSkillFilter(entry, filter))
314 .map((entry) => ({ entry, sortKey: skillPathSortKey(entry) }))
315 .sort((left, right) =>
316 left.sortKey < right.sortKey ? -1 : left.sortKey > right.sortKey ? 1 : 0,
317 );
318 for (const { entry } of children) {
319 yield* scanDirectory(path.join(directory, entry), scope, false);
320 }
321 }
322 });
323​
324 const scanSkillsConfig = Effect.fn("scanAntigravitySkillsConfig")(function* (
325 configPath: string,
326 baseDir: string,
327 scope: string,
328 filter: SkillEntryFilter,
329 visitedConfigs: ReadonlySet<string>,
330 depth: number,
331 ): Effect.fn.Return<void, AntigravitySkillsProbeError, FileSystem.FileSystem> {
332 if (depth > MAX_INHERIT_DEPTH) return;
333 const resolvedConfigPath = path.resolve(configPath);
334 if (visitedConfigs.has(resolvedConfigPath)) return;
335 const configInfo = yield* readIfPresent(
336 fileSystem.stat(resolvedConfigPath),
337 resolvedConfigPath,
338 );
339 if (configInfo?.type !== "File") return;
340 const byteLimit = Math.min(MAX_SKILL_BYTES, budget.remainingBytes);
341 if (configInfo.size > BigInt(byteLimit)) {
342 return yield* new AntigravitySkillsProbeError({
343 reason: "scan-budget-exhausted",
344 path: resolvedConfigPath,
345 });
346 }
347 const raw = yield* readIfPresent(
348 fileSystem.readFileString(resolvedConfigPath),
349 resolvedConfigPath,
350 );
351 if (raw === undefined) return;
352 budget.remainingBytes -= Buffer.byteLength(raw, "utf8");
353 const parsed = decodeSkillsConfig(raw);
354 if (parsed._tag === "None") return;
355​
356 const nextVisited = new Set(visitedConfigs);
357 nextVisited.add(resolvedConfigPath);
358 for (const inherited of parsed.value.inherits ?? []) {
359 const inheritedPath = resolveSkillsConfigPath(path, inherited.path, baseDir);
360 yield* scanSkillsConfig(
361 inheritedPath,
362 path.dirname(inheritedPath),
363 scope,
364 narrowSkillFilter(filter, inherited),
365 nextVisited,
366 depth + 1,
367 );
368 }
369 for (const entry of parsed.value.entries ?? []) {
370 const entryDirectory = resolveSkillsConfigPath(path, entry.path, baseDir);
371 yield* scanDirectory(entryDirectory, scope, true, narrowSkillFilter(filter, entry), true);
372 }
373 });
374​
375 for (const root of roots) {
376 yield* scanDirectory(root.directory, root.scope, true);
377 }
378​
379 for (const config of [
380 {
381 configPath: path.resolve(input.cwd, ".agents", "skills.json"),
382 baseDir: input.cwd,
383 scope: "project",
384 },
385 {
386 configPath: path.resolve(input.cwd, ".agent", "skills.json"),
387 baseDir: input.cwd,
388 scope: "project",
389 },
390 {
391 configPath: path.join(input.userHome, ".gemini", "config", "skills.json"),
392 baseDir: path.join(input.userHome, ".gemini", "config"),
393 scope: "user",
394 },
395 ]) {
396 yield* scanSkillsConfig(
397 config.configPath,
398 config.baseDir,
399 config.scope,
400 EMPTY_SKILL_FILTER,
401 new Set(),
402 0,
403 );
404 }
405​
406 const pluginsDirectory = path.join(input.profileDirectory, "config", "plugins");
407 const plugins = yield* readIfPresent(
408 fileSystem.readDirectory(pluginsDirectory),
409 pluginsDirectory,
410 );
411 if (plugins !== undefined && plugins.length > 0) {
412 const configPath = path.join(input.profileDirectory, "config", "config.json");
413 const configInfo = yield* readIfPresent(fileSystem.stat(configPath), configPath);
414 if (configInfo?.type === "File" && configInfo.size > BigInt(MAX_SKILL_BYTES)) {
415 return yield* new AntigravitySkillsProbeError({
416 reason: "scan-budget-exhausted",
417 path: configPath,
418 });
419 }
420 const config =
421 configInfo?.type === "File"
422 ? yield* readIfPresent(fileSystem.readFileString(configPath), configPath)
423 : undefined;
424 const preferences = config === undefined ? undefined : decodePluginPreferences(config);
425 const disabled = new Set(
426 Object.entries(
427 (preferences?._tag === "Some" ? preferences.value.plugins : undefined) ?? {},
428 ).flatMap(([name, plugin]) => (plugin.enabled === false ? [name] : [])),
429 );
430 for (const plugin of plugins.toSorted()) {
431 if (disabled.has(plugin)) continue;
432 const pluginDirectory = path.join(pluginsDirectory, plugin);
433 const info = yield* readIfPresent(fileSystem.stat(pluginDirectory), pluginDirectory);
434 if (info?.type !== "Directory") continue;
435 yield* scanDirectory(path.join(pluginDirectory, "skills"), "user", true);
436 }
437 }
438 return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
439});