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

AntigravitySkills.ts

237 lines8.4 KB

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