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