Open History to see the last commit
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;
24}
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 ];
35}
36
37const MAX_SKILL_BYTES = 1_000_000;
38const MAX_SCAN_BYTES = 8_000_000;
39const MAX_SCAN_ENTRIES = 10_000;
40
41const SkillFrontmatter = Schema.Struct({
42 name: Schema.optional(Schema.NullOr(Schema.String)),
43 description: Schema.optional(Schema.NullOr(Schema.String)),
44});
45const decodeSkillFrontmatter = Schema.decodeUnknownSync(SkillFrontmatter);
46
47export class AntigravitySkillsProbeError extends Schema.TaggedError<AntigravitySkillsProbeError>()(
48 "AntigravitySkillsProbeError",
49 {
50 reason: Schema.Literals(["scan-budget-exhausted", "filesystem-error"]),
51 path: Schema.String,
52 cause: Schema.optional(Schema.Defect()),
53 },
54) {
55 override get message(): string {
56 return this.reason === "scan-budget-exhausted"
57 ? `Antigravity skill discovery exceeded its scan limit at '${this.path}'.`
58 : `Antigravity could not read skills at '${this.path}'.`;
59 }
60}
61
62interface ScanBudget {
63 remainingBytes: number;
64 remainingEntries: number;
65}
66
67const readIfPresent = <A, R>(
68 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
69 path: string,
70) =>
71 effect.pipe(
72 Effect.catchTags({
73 PlatformError: (cause) =>
74 cause.reason._tag === "NotFound"
75 ? Effect.undefined
76 : Effect.fail(
77 new AntigravitySkillsProbeError({ reason: "filesystem-error", path, cause }),
78 ),
79 }),
80 );
81
82function parseSkillFrontmatter(contents: string, fileName: string) {
83 const start = contents.indexOf("---");
84 if (start === -1) return undefined;
85 const end = contents.indexOf("---", start + 3);
86 if (end === -1) return undefined;
87 try {
88 const frontmatter = decodeSkillFrontmatter(
89 parseYamlDocument(contents.slice(start + 3, end).trim()) ?? {},
90 );
91 const name = frontmatter.name || fileName.slice(0, -3);
92 const description = frontmatter.description?.trim();
93 // Native names are not trimmed. Do not rename one to fit the picker contract.
94 if (!name || name !== name.trim()) return undefined;
95 return { name, ...(description ? { description } : {}) };
96 } catch {
97 return undefined;
98 }
99}
100
101/** The native loader orders child paths with Go's URL.EscapedPath encoding. */
102function skillPathSortKey(entry: string) {
103 return encodeURI(entry).replace(
104 /[!'()*?#]/g,
105 (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
106 );
107}
108
109const readSkill = Effect.fn("readAntigravitySkill")(function* (
110 skillPath: string,
111 budget: ScanBudget,
112) {
113 const fileSystem = yield* FileSystem.FileSystem;
114 const info = yield* readIfPresent(fileSystem.stat(skillPath), skillPath);
115 if (info?.type !== "File") return undefined;
116
117 const byteLimit = Math.min(MAX_SKILL_BYTES, budget.remainingBytes);
118 if (info.size > BigInt(byteLimit)) {
119 return yield* new AntigravitySkillsProbeError({
120 reason: "scan-budget-exhausted",
121 path: skillPath,
122 });
123 }
124 const chunks = yield* readIfPresent(
125 fileSystem.stream(skillPath, { bytesToRead: byteLimit + 1 }).pipe(Stream.runCollect),
126 skillPath,
127 );
128 if (chunks === undefined) return undefined;
129 const bytes = Buffer.concat(chunks);
130 if (bytes.byteLength > byteLimit) {
131 return yield* new AntigravitySkillsProbeError({
132 reason: "scan-budget-exhausted",
133 path: skillPath,
134 });
135 }
136 budget.remainingBytes -= bytes.byteLength;
137 return bytes.toString("utf8");
138});
139
140/** Keep read errors typed so workspace snapshots cannot cache partial results. */
141export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")(function* (input: {
142 readonly cwd: string;
143 readonly userHome: string;
144}): Effect.fn.Return<
145 ReadonlyArray<ServerProviderSkill>,
146 AntigravitySkillsProbeError,
147 FileSystem.FileSystem | Path.Path
148> {
149 const fileSystem = yield* FileSystem.FileSystem;
150 const path = yield* Path.Path;
151 const [configSkills, cliSkills] = antigravityUserSkillDirectories(
152 path,
153 path.join(input.userHome, ".gemini"),
154 );
155 const roots = [
156 { directory: configSkills, scope: "user" },
157 { directory: path.resolve(input.cwd, ".gemini", "skills"), scope: "project" },
158 { directory: cliSkills, scope: "user" },
159 { directory: path.resolve(input.cwd, ".agents", "skills"), scope: "project" },
160 { directory: path.resolve(input.cwd, ".agent", "skills"), scope: "project" },
161 ];
162 const budget: ScanBudget = {
163 remainingBytes: MAX_SCAN_BYTES,
164 remainingEntries: MAX_SCAN_ENTRIES,
165 };
166 const skillsByName = new Map<string, ServerProviderSkill>();
167
168 const scanDirectory = Effect.fn("scanAntigravitySkillDirectory")(function* (
169 directory: string,
170 scope: string,
171 scanChildren: boolean,
172 ): Effect.fn.Return<void, AntigravitySkillsProbeError, FileSystem.FileSystem> {
173 const info = yield* readIfPresent(fileSystem.stat(directory), directory);
174 if (info?.type !== "Directory") return;
175 const entries = yield* readIfPresent(fileSystem.readDirectory(directory), directory);
176 if (entries === undefined) return;
177 if (entries.length > budget.remainingEntries) {
178 return yield* new AntigravitySkillsProbeError({
179 reason: "scan-budget-exhausted",
180 path: directory,
181 });
182 }
183 budget.remainingEntries -= entries.length;
184
185 const sortedEntries = entries.toSorted();
186 const skillFileName = sortedEntries.find((entry) => entry.toLowerCase() === "skill.md");
187 if (skillFileName !== undefined) {
188 if (!skillFileName.endsWith(".md")) return;
189 const skillPath = path.join(directory, skillFileName);
190 const contents = yield* readSkill(skillPath, budget);
191 if (contents === undefined) return;
192 const skill = parseSkillFrontmatter(contents, skillFileName);
193 if (!skill || skillsByName.has(skill.name)) return;
194 skillsByName.set(skill.name, {
195 ...skill,
196 path: skillPath,
197 scope,
198 enabled: true,
199 });
200 return;
201 }
202 if (scanChildren) {
203 const children = sortedEntries
204 .map((entry) => ({ entry, sortKey: skillPathSortKey(entry) }))
205 .sort((left, right) =>
206 left.sortKey < right.sortKey ? -1 : left.sortKey > right.sortKey ? 1 : 0,
207 );
208 for (const { entry } of children) {
209 yield* scanDirectory(path.join(directory, entry), scope, false);
210 }
211 }
212 });
213
214 for (const root of roots) {
215 yield* scanDirectory(root.directory, root.scope, true);
216 }
217 return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
218});