Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(skills): keep the skills that fit when a large import runs out of budget
AdityaUmale2c78b86e6448
diff --git a/server/skill-fetch.test.ts b/server/skill-fetch.test.tsindex 816ae5e3de..36a4754fd6 100644--- a/server/skill-fetch.test.ts+++ b/server/skill-fetch.test.ts@@ -377,6 +377,26 @@ describe("skill import budget", () => {expect(skills).toHaveLength(MAX_SKILLS_PER_IMPORT);});+ it("keeps the skills that came in whole when a large collection runs out of downloads", async () => {+ const entries: Record<string, FakeRepoEntry> = {};+ for (let i = 0; i < 40; i++) {+ entries[`skills/skill-${i}/SKILL.md`] = SKILL(`skill-${i}`);+ for (let j = 1; j < 30; j++) entries[`skills/skill-${i}/ref-${j}.md`] = `# ${j}`;+ }+ const skills = ok(await fetchSkillFromSource("a/b", fakeGitHub({ "a/b": entries }).fetch));+ expect(skills).toHaveLength(33);+ expect(skills.every((skill) => skill.files.length === 30)).toBe(true);+ });++ it("stops looking for more skills while the request budget still covers the ones found", async () => {+ const entries: Record<string, FakeRepoEntry> = {};+ for (let i = 0; i < 30; i++) entries[`skills/skill-${i}/SKILL.md`] = SKILL(`skill-${i}`);+ for (let i = 0; i < 70; i++) entries[`skills/notes-${i}/README.md`] = "# Notes";+ for (const folder of ["docs", "guides", "pages"]) for (let i = 0; i < 100; i++) entries[`${folder}/page-${i}/README.md`] = "# Page";+ const skills = ok(await fetchSkillFromSource("a/b", fakeGitHub({ "a/b": entries }).fetch));+ expect(skills).toHaveLength(30);+ });+it("stops a larger collection at the per-import cap", async () => {const entries: Record<string, FakeRepoEntry> = {};for (let i = 0; i < MAX_SKILLS_PER_IMPORT + 5; i++) entries[`skills/skill-${i}/SKILL.md`] = SKILL(`skill-${i}`);diff --git a/server/skill-fetch.ts b/server/skill-fetch.tsindex d43069645f..ab151f0b7c 100644--- a/server/skill-fetch.ts+++ b/server/skill-fetch.ts@@ -15,6 +15,10 @@ const LISTING_MAX_BYTES = 1_048_576;const IMPORT_LIMITS = { apiRequests: 320, downloads: 1_000, bytes: 64 * 1_048_576, ms: 120_000 };const PARALLEL_DOWNLOADS = 4;class ImportLimitError extends Error {}+/** The whole import ran out of requests, downloads or bytes, rather than one file or folder being too big. */+class ImportBudgetError extends ImportLimitError {}++type ImportFetch = typeof fetch & { apiRequestsLeft: () => number };class GitHubApiError extends Error {}export interface SkillImportSignIn {@@ -61,7 +65,7 @@ function boundedImportFetch(fetcher: typeof fetch,cancel?: AbortSignal,authorization: () => Promise<SkillImportSignIn> = () => skillImportToken(),-): typeof fetch {+): ImportFetch {let apiRequests = 0;let downloads = 0;let bytes = 0;@@ -88,7 +92,7 @@ function boundedImportFetch(const bounded: typeof fetch = async (input, init) => {const api = isGitHubApiRequest(input);if (api ? ++apiRequests > IMPORT_LIMITS.apiRequests : ++downloads > IMPORT_LIMITS.downloads) {- throw new ImportLimitError("Import request limit reached — paste a specific skill folder instead.");+ throw new ImportBudgetError("Import request limit reached — paste a specific skill folder instead.");}signal.throwIfAborted();const sent: RequestInit = { ...init, signal };@@ -132,9 +136,10 @@ function boundedImportFetch(if (chunk.done) break;size += chunk.value.byteLength;bytes += chunk.value.byteLength;- if (size > (api ? LISTING_MAX_BYTES : SKILL_FOLDER_LIMITS.fileBytes) || bytes > IMPORT_LIMITS.bytes) {+ if (size > (api ? LISTING_MAX_BYTES : SKILL_FOLDER_LIMITS.fileBytes)) {throw new ImportLimitError("Import size limit reached — paste a smaller skill folder instead.");}+ if (bytes > IMPORT_LIMITS.bytes) throw new ImportBudgetError("Import size limit reached — paste a smaller skill folder instead.");chunks.push(chunk.value);}} finally {@@ -142,7 +147,7 @@ function boundedImportFetch(}return new Response(Buffer.concat(chunks), { status: response.status, headers: response.headers });};- return bounded;+ return Object.assign(bounded, { apiRequestsLeft: () => IMPORT_LIMITS.apiRequests - apiRequests });}export interface FetchedSkill {@@ -326,7 +331,7 @@ async function skillNameFrom(snapshot: Snapshot, entries: ContentEntry[], fetche}/** The skills.sh registry's discovery order: the path, skills/, .claude/skills/, .agents/skills/, then direct children. */-async function discoverSkillDirs(target: Target, snapshot: Snapshot, fetcher: typeof fetch): Promise<string[]> {+async function discoverSkillDirs(target: Target, snapshot: Snapshot, fetcher: ImportFetch): Promise<string[]> {const root = await listDir(snapshot, target.path, fetcher);const wanted = target.skill ? toSkillSlug(target.skill) || undefined : undefined;const dirMatches = (dir: string) => !!wanted && toSkillSlug(dir.split("/").at(-1)!) === wanted;@@ -344,7 +349,8 @@ async function discoverSkillDirs(target: Target, snapshot: Snapshot, fetcher: tyconst preferred = ["skills", ".claude", ".agents"];const rank = (name: string) => (wanted && toSkillSlug(name) === wanted ? 0 : preferred.includes(name) ? 1 : 2);const ordered = [...dirs].sort((a, b) => rank(a.name) - rank(b.name));- const enough = () => found.length >= (wanted ? 1 : MAX_SKILLS_PER_IMPORT);+ // Each skill found takes one more request to fetch its folder, so the walk stops while those still fit.+ const enough = () => found.length >= (wanted ? 1 : MAX_SKILLS_PER_IMPORT) || (found.length > 0 && fetcher.apiRequestsLeft() < found.length + 2);for (const dir of ordered.slice(0, MAX_FOLDERS_WALKED)) {if (enough()) break;const base = dir.name === ".claude" || dir.name === ".agents" ? `${dir.path}/skills` : dir.path;@@ -431,7 +437,7 @@ async function fetchSkillFolder(target: Target, snapshot: Snapshot, dir: string,};}-async function fetchSkills(target: Target, fetcher: typeof fetch): Promise<FetchedSkill[]> {+async function fetchSkills(target: Target, fetcher: ImportFetch): Promise<FetchedSkill[]> {const commit = await resolveCommit(target.owner, target.repo, target.ref ?? "HEAD", fetcher);const snapshot: Snapshot = { owner: target.owner, repo: target.repo, commit, trees: new Map() };const dirs = await discoverSkillDirs(target, snapshot, fetcher);@@ -441,7 +447,14 @@ async function fetchSkills(target: Target, fetcher: typeof fetch): Promise<Fetch: "no SKILL.md found there — paste a skill folder or a repo with a skills/ directory");}const skills: FetchedSkill[] = [];- for (const dir of dirs) skills.push(await fetchSkillFolder(target, snapshot, dir, fetcher));+ for (const dir of dirs) {+ try {+ skills.push(await fetchSkillFolder(target, snapshot, dir, fetcher));+ } catch (error) {+ if (error instanceof ImportBudgetError && skills.length) break;+ throw error;+ }+ }return skills;}@@ -453,13 +466,13 @@ export async function fetchSkillFromSource(): Promise<{ skills: FetchedSkill[] } | { error: string }> {const parsed = parseSkillSource(input);if ("error" in parsed) return parsed;- fetcher = boundedImportFetch(fetcher, cancel, authorization);+ const bounded = boundedImportFetch(fetcher, cancel, authorization);try {- return { skills: await fetchSkills(parsed, fetcher) };+ return { skills: await fetchSkills(parsed, bounded) };} catch (error) {if (parsed.rawUrl && error instanceof GitHubApiError) {try {- const content = await fetchBytes(parsed.rawUrl, fetcher);+ const content = await fetchBytes(parsed.rawUrl, bounded);return { skills: [{ source: parsed.rawUrl, files: [{ path: "SKILL.md", content, executable: false }], skipped: [{ path: "", reason: "unlisted" }] }] };} catch {}}