Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(antigravity): stage skills in the managed profile and harden reads

Krishna Dobhale80862b69895
diff --git a/server/bounded-file-read.test.ts b/server/bounded-file-read.test.ts
new file mode 100644
index 0000000000..8de48c605f
--- /dev/null
+++ b/server/bounded-file-read.test.ts
@@ -0,0 +1,36 @@
+import { appendFileSync, fstatSync, mkdirSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { DATA_DIR } from "./config.ts";
+import { readFileNoFollow } from "./imported-skills.ts";
+
+vi.mock("node:fs", async (importOriginal) => {
+ const fs = await importOriginal<typeof import("node:fs")>();
+ return { ...fs, fstatSync: vi.fn(fs.fstatSync) };
+});
+const original = (await vi.importActual<typeof import("node:fs")>("node:fs")).fstatSync;
+afterEach(() => vi.mocked(fstatSync).mockReset().mockImplementation(original));
+
+describe("bounded file reads", () => {
+ it("keeps existing callers unlimited and rejects files above the supplied limit", () => {
+ mkdirSync(DATA_DIR, { recursive: true });
+ const file = join(DATA_DIR, "bounded.txt");
+ writeFileSync(file, "1234");
+ expect(readFileNoFollow(file, 4)?.toString()).toBe("1234");
+ expect(readFileNoFollow(file, 3)).toBeNull();
+ expect(readFileNoFollow(file)?.toString()).toBe("1234");
+ });
+
+ it("rejects growth after the opened descriptor was checked", () => {
+ mkdirSync(DATA_DIR, { recursive: true });
+ const file = join(DATA_DIR, "growing.txt");
+ writeFileSync(file, "1234");
+ vi.mocked(fstatSync).mockImplementationOnce((fd) => {
+ const info = original(fd);
+ appendFileSync(file, Buffer.alloc(4096));
+ return info;
+ });
+ expect(readFileNoFollow(file, 4)).toBeNull();
+ });
+});
diff --git a/server/drivers/acp/client-path.test.ts b/server/drivers/acp/client-path.test.ts
new file mode 100644
index 0000000000..1a56176e0f
--- /dev/null
+++ b/server/drivers/acp/client-path.test.ts
@@ -0,0 +1,25 @@
+import { mkdirSync, realpathSync, symlinkSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+import { DATA_DIR } from "../../config.ts";
+import { resolveAcpClientPath } from "./client-path.ts";
+
+describe("ACP client paths", () => {
+ it("allows turn-selected profile reads without granting writes or other profile files", async () => {
+ const cwd = join(DATA_DIR, "client-task");
+ const profile = join(DATA_DIR, "profile");
+ const skill = join(profile, "omb-skills", "hash");
+ mkdirSync(cwd, { recursive: true });
+ mkdirSync(join(skill, "references"), { recursive: true });
+ const file = join(skill, "references", "guide.md");
+ writeFileSync(file, "reviewed");
+ await expect(resolveAcpClientPath(file, cwd, [skill])).resolves.toBe(realpathSync(file));
+ await expect(resolveAcpClientPath(file, cwd)).rejects.toThrow("outside");
+ await expect(resolveAcpClientPath(join(profile, "acp_token.json"), cwd, [skill])).rejects.toThrow("outside");
+ await expect(resolveAcpClientPath(join(skill + "-other", "SKILL.md"), cwd, [skill])).rejects.toThrow("outside");
+ await expect(resolveAcpClientPath("relative", cwd, [skill])).rejects.toThrow("absolute");
+ symlinkSync(cwd, join(skill, "escape"), process.platform === "win32" ? "junction" : "dir");
+ await expect(resolveAcpClientPath(join(skill, "escape", "new.md"), cwd, [skill])).rejects.toThrow("outside");
+ });
+});
diff --git a/server/drivers/acp/client-path.ts b/server/drivers/acp/client-path.ts
new file mode 100644
index 0000000000..b5da031cdd
--- /dev/null
+++ b/server/drivers/acp/client-path.ts
@@ -0,0 +1,28 @@
+import { lstat, realpath } from "node:fs/promises";
+import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
+
+const inside = (root: string, path: string) => {
+ const rel = relative(root, path);
+ return rel !== ".." && !rel.startsWith(".." + sep) && !isAbsolute(rel);
+};
+
+export async function resolveAcpClientPath(requestPath: unknown, cwd: string, readRoots: readonly string[] = []): Promise<string> {
+ if (typeof requestPath !== "string" || !isAbsolute(requestPath)) throw new Error("ACP file paths must be absolute.");
+ const requested = resolve(requestPath);
+ const root = [cwd, ...readRoots].find((allowed) => inside(resolve(allowed), requested));
+ if (!root) throw new Error("ACP file path is outside the session workspace.");
+ const workspace = await realpath(root).catch(() => resolve(root));
+ const suffix = [basename(requested)];
+ let ancestor = dirname(requested);
+ while (!(await lstat(ancestor).catch(() => null))) {
+ const parent = dirname(ancestor);
+ if (parent === ancestor) throw new Error("ACP file path has no accessible parent.");
+ suffix.unshift(basename(ancestor));
+ ancestor = parent;
+ }
+ const candidate = resolve(await realpath(ancestor), ...suffix);
+ if (!inside(workspace, candidate)) throw new Error("ACP file path is outside the session workspace.");
+ const existing = await lstat(candidate).catch(() => null);
+ if (existing?.isSymbolicLink()) throw new Error("ACP file path cannot be a symbolic link.");
+ return candidate;
+}
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.ts
index c9d70b995b..1f635443a2 100644
--- a/server/drivers/acp/core.ts
+++ b/server/drivers/acp/core.ts
@@ -6,8 +6,9 @@ import { type ServerText } from "../../../shared/server-text.ts";
// `allow`-kind option approves, and option order is never a security contract.
import { mkdtempSync, rmSync } from "node:fs";
import { homedir, tmpdir } from "node:os";
-import { lstat, mkdir, readFile, realpath, stat, writeFile } from "node:fs/promises";
-import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
+import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { resolveAcpClientPath } from "./client-path.ts";
import { createHash } from "node:crypto";
import { PROVIDER_CREDENTIAL_ENV, stripControlPlaneEnv, WORKSPACE_CREDENTIAL_ENV } from "../../config.ts";
@@ -186,6 +187,8 @@ export interface AcpSupport {
shareProcess?: boolean;
/** Route workspace file access through ACP so edits retain approval cards. */
clientFileSystem?: boolean;
+ /** Additional server-owned directories this turn may read; writes remain confined to cwd. */
+ clientReadRoots?(turn: SendTurnInput): readonly string[];
/** Sent as `clientCapabilities._meta` on initialize, where agents read vendor capabilities. */
clientCapabilitiesMeta?: Record<string, unknown>;
/** Made once per process: rewrites a session/update before the turn reads it, or drops it by returning null. */
@@ -624,35 +627,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
const acp = host.link(threadId, cwd);
const send = (obj: unknown) => acp.send(obj);
- const resolveClientPath = async (requestPath: unknown): Promise<string> => {
- if (typeof requestPath !== "string" || !isAbsolute(requestPath)) {
- throw new Error("ACP file paths must be absolute.");
- }
- const workspace = await realpath(cwd).catch(() => resolve(cwd));
- const requested = resolve(requestPath);
- const lexical = relative(resolve(cwd), requested);
- if (lexical === ".." || lexical.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute(lexical)) {
- throw new Error("ACP file path is outside the session workspace.");
- }
- const suffix = [basename(requested)];
- let ancestor = dirname(requested);
- while (!(await lstat(ancestor).catch(() => null))) {
- const parent = dirname(ancestor);
- if (parent === ancestor) throw new Error("ACP file path has no accessible parent.");
- suffix.unshift(basename(ancestor));
- ancestor = parent;
- }
- const candidate = resolve(await realpath(ancestor), ...suffix);
- const rel = relative(workspace, candidate);
- if (rel === ".." || rel.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute(rel)) {
- throw new Error("ACP file path is outside the session workspace.");
- }
- const existing = await lstat(candidate).catch(() => null);
- if (existing?.isSymbolicLink()) throw new Error("ACP file path cannot be a symbolic link.");
- return candidate;
- };
-
- const handleClientFileRequest = async (msg: any): Promise<void> => {
+ const handleClientFileRequest = async (msg: any, current: AcpTurn): Promise<void> => {
const fail = (error: unknown) => send({
jsonrpc: "2.0",
id: msg.id,
@@ -661,7 +636,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
try {
if (!support.clientFileSystem) throw new Error("Client file access is disabled.");
const params = msg.params ?? {};
- const path = await resolveClientPath(params.path);
+ const path = await resolveAcpClientPath(params.path, cwd, msg.method === "fs/read_text_file" ? support.clientReadRoots?.(current.turn) : undefined);
if (msg.method === "fs/read_text_file") {
const info = await stat(path);
if (!info.isFile() || info.size > CLIENT_FILE_MAX_BYTES) {
@@ -697,7 +672,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
const handleServerRequest = (msg: any, current: AcpTurn) => {
current.state.startupActivity = true; if (current.state.promptSent) current.acknowledge();
if (msg.method === "fs/read_text_file" || msg.method === "fs/write_text_file") {
- void handleClientFileRequest(msg);
+ void handleClientFileRequest(msg, current);
return;
}
const question = questionRequestFor(support.questionRequests, msg.method);
diff --git a/server/drivers/antigravity-skills.test.ts b/server/drivers/antigravity-skills.test.ts
index 77d1eb06d9..8faf6a256e 100644
--- a/server/drivers/antigravity-skills.test.ts
+++ b/server/drivers/antigravity-skills.test.ts
@@ -1,4 +1,4 @@
-import { mkdirSync, readFileSync, realpathSync, symlinkSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, readFileSync, realpathSync, readdirSync, symlinkSync, writeFileSync } from "node:fs";
import { join, relative } from "node:path";
import { describe, expect, it } from "vitest";
@@ -7,7 +7,7 @@ import { stageAntigravitySkills } from "./antigravity-skills.ts";
function fixture(name: string) {
const source = join(DATA_DIR, name, "skills", ".revisions", "revision");
- const cwd = join(DATA_DIR, name, "task");
+ const cwd = join(DATA_DIR, name, "profile");
mkdirSync(join(source, "references"), { recursive: true });
mkdirSync(cwd, { recursive: true });
const file = join(source, "SKILL.md");
@@ -17,7 +17,7 @@ function fixture(name: string) {
}
describe("Antigravity skill staging", () => {
- it("stages selected skills and references inside cwd, rewriting every prompt half and slash command", () => {
+ it("stages selected skills and references inside the managed profile, rewriting every prompt half and slash command", () => {
const { source, cwd, file } = fixture("stage");
const text = "Read " + JSON.stringify(file);
const turn = { threadId: "thread", text, system: text, systemStable: text, systemVolatile: text, recoveryText: text, skillFiles: [file] };
@@ -28,6 +28,7 @@ describe("Antigravity skill staging", () => {
expect(readFileSync(join(target, "..", "references", "guide.md"), "utf8")).toBe("Reviewed reference");
for (const field of ["system", "systemStable", "systemVolatile", "recoveryText"] as const) expect(staged[field]).toBe(staged.text);
expect(turn.text).toBe(text);
+ expect(staged.skillFiles).toEqual([target]);
expect(stageAntigravitySkills(turn, cwd).text).toBe(staged.text);
writeFileSync(join(source, "references", "guide.md"), "Updated reference");
@@ -60,7 +61,31 @@ describe("Antigravity skill staging", () => {
const turn = { threadId: "thread", text: "Read " + JSON.stringify(file), skillFiles: [file] };
expect(() => stageAntigravitySkills(turn, cwd)).toThrow("unsafe file");
const other = fixture("root-link");
- symlinkSync(outside, join(other.cwd, ".omb-skills"), process.platform === "win32" ? "junction" : "dir");
+ symlinkSync(outside, join(other.cwd, "omb-skills"), process.platform === "win32" ? "junction" : "dir");
expect(() => stageAntigravitySkills({ ...turn, text: "Read " + JSON.stringify(other.file), skillFiles: [other.file] }, other.cwd)).toThrow("staging path");
});
+
+ it("never stages through a task directory link", () => {
+ const { cwd, file } = fixture("task-race");
+ const task = join(DATA_DIR, "replaceable-task");
+ const outside = join(DATA_DIR, "race-outside");
+ mkdirSync(task, { recursive: true });
+ mkdirSync(outside, { recursive: true });
+ symlinkSync(outside, join(task, ".omb-skills"), process.platform === "win32" ? "junction" : "dir");
+ const staged = stageAntigravitySkills({ threadId: "thread", text: "Read " + JSON.stringify(file), skillFiles: [file], cwd: task }, cwd);
+ expect(staged.text).toContain("omb-skills");
+ expect(readdirSync(outside)).toEqual([]);
+ expect(existsSync(join(task, "omb-skills"))).toBe(false);
+ });
+
+ it.each(["file", "link", "folder"])("rejects an unexpected %s in a reused staged copy", (kind) => {
+ const { cwd, file } = fixture("unexpected-" + kind);
+ const turn = { threadId: "thread", text: "Read " + JSON.stringify(file), skillFiles: [file] };
+ const staged = stageAntigravitySkills(turn, cwd);
+ const folder = join(JSON.parse(staged.text.slice(5)) as string, "..");
+ if (kind === "file") writeFileSync(join(folder, "unexpected.py"), "malicious");
+ else if (kind === "folder") mkdirSync(join(folder, "unexpected"));
+ else symlinkSync(cwd, join(folder, "unexpected"), process.platform === "win32" ? "junction" : "dir");
+ expect(() => stageAntigravitySkills(turn, cwd)).toThrow("staged skill files changed");
+ });
});
diff --git a/server/drivers/antigravity-skills.ts b/server/drivers/antigravity-skills.ts
index 207bf65602..2e16abd2e7 100644
--- a/server/drivers/antigravity-skills.ts
+++ b/server/drivers/antigravity-skills.ts
@@ -9,9 +9,25 @@ import { directoryEntryState } from "../skill-storage.ts";
const PROMPT_FIELDS = ["text", "system", "systemStable", "systemVolatile", "recoveryText"] as const;
-/** Antigravity c57db0a9 resolves links before restricting view_file to cwd and GEMINI_HOME. */
-export function stageAntigravitySkills(turn: SendTurnInput, cwd: string): SendTurnInput {
- const result = { ...turn };
+function stagedSkillMatches(target: string, paths: string[], hash: string): boolean {
+ const expected = new Set(paths);
+ const folders = new Set(paths.flatMap((path) => path.split("/").slice(0, -1).map((_, index) => path.split("/").slice(0, index + 1).join("/"))));
+ const visit = (folder: string, prefix = ""): boolean => {
+ if (directoryEntryState(folder) !== "directory") return false;
+ return readdirSync(folder).every((name) => {
+ const path = prefix + name;
+ const full = join(folder, name);
+ const info = lstatSync(full);
+ return info.isDirectory() ? folders.has(path) && visit(full, path + "/") : info.isFile() && expected.has(path);
+ });
+ };
+ return visit(target) && skillFolderDigest(target, paths, { remember: false }) === hash;
+}
+
+/** Antigravity c57db0a9 permits GEMINI_HOME. Stage in its server-owned profile, never in a replaceable task directory. */
+export function stageAntigravitySkills(turn: SendTurnInput, profile: string): SendTurnInput {
+ const result: SendTurnInput = { ...turn, skillFiles: [] };
+ const stagedFiles: string[] = [];
for (const file of new Set(turn.skillFiles ?? [])) {
const quoted = JSON.stringify(file);
if (!PROMPT_FIELDS.some((field) => result[field]?.includes(quoted))) continue;
@@ -27,7 +43,7 @@ export function stageAntigravitySkills(turn: SendTurnInput, cwd: string): SendTu
if (skillFilePathProblem(path, info.isDirectory())) throw new Error("Antigravity skill contains an unsafe path.");
if (info.isDirectory()) { visit(full, path + "/"); continue; }
if (!info.isFile() || info.size > SKILL_FOLDER_LIMITS.fileBytes) throw new Error("Antigravity skill contains an unsafe file.");
- const content = readFileNoFollow(full);
+ const content = readFileNoFollow(full, SKILL_FOLDER_LIMITS.fileBytes);
if (!content) throw new Error("Antigravity skill file could not be read.");
bytes += content.length;
if (files.length >= SKILL_FOLDER_LIMITS.files || bytes > SKILL_FOLDER_LIMITS.bytes) throw new Error("Antigravity skill exceeds folder limits.");
@@ -42,8 +58,10 @@ export function stageAntigravitySkills(turn: SendTurnInput, cwd: string): SendTu
const digest = createHash("sha256");
for (const entry of files) digest.update(entry.path + "\0" + (entry.executable ? "x" : "-") + "\0" + createHash("sha256").update(entry.content).digest("hex") + "\n");
const hash = digest.digest("hex");
- const root = join(realpathSync(cwd), ".omb-skills");
- if (directoryEntryState(root) === "missing") mkdirSync(root, { mode: 0o700 });
+ if (directoryEntryState(profile) === "missing") mkdirSync(profile, { recursive: true, mode: 0o700 });
+ if (directoryEntryState(profile) !== "directory") throw new Error("Antigravity profile must be a real directory.");
+ const root = join(realpathSync(profile), "omb-skills");
+ if (directoryEntryState(root) === "missing") mkdirSync(root, { recursive: true, mode: 0o700 });
if (directoryEntryState(root) !== "directory") throw new Error("Antigravity staging path must be a real directory.");
const target = join(root, hash);
if (directoryEntryState(target) === "missing") {
@@ -53,18 +71,20 @@ export function stageAntigravitySkills(turn: SendTurnInput, cwd: string): SendTu
writeSkillFolder(prepared, skillMd.content, files.filter((entry) => entry !== skillMd));
try { renameSync(prepared, target); }
catch (error) {
- if (skillFolderDigest(target, files.map((entry) => entry.path), { remember: false }) !== hash) throw error;
+ if (!stagedSkillMatches(target, files.map((entry) => entry.path), hash)) throw error;
}
} finally {
rmSync(temporary, { recursive: true, force: true });
}
}
- if (skillFolderDigest(target, files.map((entry) => entry.path), { remember: false }) !== hash) {
+ if (!stagedSkillMatches(target, files.map((entry) => entry.path), hash)) {
throw new Error("Antigravity staged skill files changed.");
}
+ stagedFiles.push(join(target, "SKILL.md"));
for (const field of PROMPT_FIELDS) {
if (result[field] !== undefined) result[field] = result[field]!.replaceAll(quoted, JSON.stringify(join(target, "SKILL.md")));
}
}
+ result.skillFiles = stagedFiles;
return result;
}
diff --git a/server/drivers/antigravity.test.ts b/server/drivers/antigravity.test.ts
index 74922e5e59..8ee63d039d 100644
--- a/server/drivers/antigravity.test.ts
+++ b/server/drivers/antigravity.test.ts
@@ -1,4 +1,4 @@
-import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
+import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
@@ -853,6 +853,34 @@ describe("Antigravity driver over shared ACP", () => {
const tokenDirectory = join(antigravityProfileDirectory(instanceId), "antigravity-acp");
mkdirSync(tokenDirectory, { recursive: true });
writeFileSync(join(tokenDirectory, "acp_token.json"), "{}", { mode: 0o600 });
+ const replies = new Map<string, any>();
+ let received!: () => void;
+ const fileRequestsFinished = new Promise<void>((resolve) => { received = resolve; });
+ const spawn = procs.spawnCli;
+ vi.spyOn(procs, "spawnCli").mockImplementation((...args) => {
+ const child = spawn(...args);
+ const write = child.stdin.write.bind(child.stdin);
+ vi.spyOn(child.stdin, "write").mockImplementation((...writeArgs) => {
+ const message = JSON.parse(String(writeArgs[0]));
+ if (message.method === "session/prompt") {
+ const path = JSON.parse(message.params.prompt[0].text.slice(5)) as string;
+ const calls = [
+ { id: "skill-read", method: "fs/read_text_file", path },
+ { id: "reference-read", method: "fs/read_text_file", path: join(dirname(path), "references", "guide.md") },
+ { id: "skill-write", method: "fs/write_text_file", path, content: "unreviewed" },
+ { id: "token-read", method: "fs/read_text_file", path: join(tokenDirectory, "acp_token.json") },
+ ];
+ for (const call of calls) child.stdout.emit("data", Buffer.from(JSON.stringify({
+ jsonrpc: "2.0", id: call.id, method: call.method, params: { sessionId: message.params.sessionId, path: call.path, content: call.content },
+ }) + "\n"));
+ } else if (["skill-read", "reference-read", "skill-write", "token-read"].includes(message.id)) {
+ replies.set(message.id, message);
+ if (replies.size === 4) received();
+ }
+ return write(...writeArgs);
+ });
+ return child;
+ });
instance = await AntigravityDriver.create({
instanceId,
displayName: "Antigravity Work",
@@ -908,9 +936,14 @@ describe("Antigravity driver over shared ACP", () => {
expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: true });
const prompt = JSON.parse(readFileSync(`${dump}.prompt.json`, "utf8"));
const stagedFile = JSON.parse(prompt[0].text.slice(5)) as string;
- expect(stagedFile.startsWith(join(fake.directory, ".omb-skills"))).toBe(true);
+ expect(stagedFile.startsWith(join(realpathSync(antigravityProfileDirectory(instanceId)), "omb-skills") + (process.platform === "win32" ? "\\" : "/"))).toBe(true);
expect(readFileSync(stagedFile, "utf8")).toBe("Read references/guide.md.");
expect(readFileSync(join(dirname(stagedFile), "references", "guide.md"), "utf8")).toBe("Reviewed instructions");
+ await fileRequestsFinished;
+ expect(replies.get("skill-read").result).toEqual({ content: "Read references/guide.md." });
+ expect(replies.get("reference-read").result).toEqual({ content: "Reviewed instructions" });
+ expect(replies.get("skill-write").error.message).toContain("outside");
+ expect(replies.get("token-read").error.message).toContain("outside");
const dumpState = JSON.parse(readFileSync(dump, "utf8"));
expect(dumpState.argv).toEqual(process.platform === "linux" ? ["--uid="] : []);
expect(dumpState.env.GEMINI_HOME).toBe(antigravityProfileDirectory(instanceId));
diff --git a/server/drivers/antigravity.ts b/server/drivers/antigravity.ts
index 40863f694c..53b5491d12 100644
--- a/server/drivers/antigravity.ts
+++ b/server/drivers/antigravity.ts
@@ -1,7 +1,7 @@
// Google Antigravity through its official ACP server: managed runtime, isolated Google profile,
// model/mode configuration and OAuth.
import type { ApprovalMode } from "../../shared/approval-mode.ts";
-import { homedir } from "node:os";
+import { dirname } from "node:path";
import { stageAntigravitySkills } from "./antigravity-skills.ts";
import { antigravityAccount } from "./antigravity-account.ts";
import type {
@@ -16,6 +16,7 @@ import { createAcpDriver, type AcpConfig, type AcpSupport } from "./acp/core.ts"
import {
AntigravityAuthController,
antigravityProfileAuthenticated,
+ antigravityProfileDirectory,
prepareAntigravityProfile,
probeAntigravityModels,
removeAntigravitySignIn,
@@ -78,6 +79,7 @@ const support: AcpSupport = {
sessionScopedApproval: true,
resumeMethod: "resume",
clientFileSystem: true,
+ clientReadRoots: (turn) => (turn.skillFiles ?? []).map(dirname),
sanitizeToolPayload: true,
resolveCommand: async (env, config, instanceId) => {
@@ -173,7 +175,7 @@ export const AntigravityDriver: ProviderDriver<AcpConfig> = {
...base,
adapter: {
...base.adapter,
- sendTurn: (turn) => base.adapter.sendTurn(stageAntigravitySkills(turn, turn.cwd ?? input.config.workspace ?? homedir())),
+ sendTurn: (turn) => base.adapter.sendTurn(stageAntigravitySkills(turn, antigravityProfileDirectory(input.instanceId))),
},
get models() {
return base.models;
diff --git a/server/host/skills-library.ts b/server/host/skills-library.ts
index 831938c78f..2723608258 100644
--- a/server/host/skills-library.ts
+++ b/server/host/skills-library.ts
@@ -129,10 +129,11 @@ export function createSkillsLibraryHost(deps: SkillsLibraryHostDeps) {
const conversationSkills = (bot: BotRecord, threadId: string): string[] | undefined =>
skillsLibraryEnabled(cfg) ? conversationAssignedSkills(bot.id, liveAssigned(bot), conversationStartedAt(threadId)) : undefined;
const turnSkillFiles = (bot: BotRecord, threadId: string, instance?: TurnInstance): string[] => {
- const assigned = conversationSkills(bot, threadId);
+ const assigned = skillsLibraryEnabled(cfg) ? liveAssigned(bot) : undefined;
const names = resolveBotSkills(bot.id, assigned).filter((skill) => skill.enabled).map((skill) => skill.name);
- return [...enabledSkillFiles(bot.id, names, assigned).values(),
- ...importsFor(bot, assigned, instance).map((skill) => skill.file)];
+ return [...new Set([...enabledSkillFiles(bot.id, names, assigned).values(),
+ ...importsFor(bot, conversationSkills(bot, threadId), instance).map((skill) => skill.file),
+ ...importsFor(bot, assigned, instance).map((skill) => skill.file)])];
};
const engineOf = (instance: TurnInstance | undefined): SkillTurnEngine | undefined => {
diff --git a/server/imported-skills.ts b/server/imported-skills.ts
index 24b2194fa3..5bdbd5a2e1 100644
--- a/server/imported-skills.ts
+++ b/server/imported-skills.ts
@@ -11,7 +11,7 @@
import { createHash, randomUUID } from "node:crypto";
import {
closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync,
- statSync, symlinkSync, unlinkSync, writeFileSync,
+ readSync, statSync, symlinkSync, unlinkSync, writeFileSync,
} from "node:fs";
import { homedir } from "node:os";
import { dirname, isAbsolute, join, resolve } from "node:path";
@@ -95,12 +95,21 @@ export function listedImportedSkills<T extends { name: string; description: stri
return available.filter((skill) => picked.has(skill.name));
}
-export function readFileNoFollow(path: string): Buffer | null {
+export function readFileNoFollow(path: string, maxBytes?: number): Buffer | null {
let fd: number | null = null;
try {
fd = openSync(path, constants.O_RDONLY | (process.platform === "win32" ? 0 : constants.O_NOFOLLOW));
- if (!fstatSync(fd).isFile()) return null;
- return readFileSync(fd);
+ const info = fstatSync(fd);
+ if (!info.isFile() || (maxBytes !== undefined && info.size > maxBytes)) return null;
+ if (maxBytes === undefined) return readFileSync(fd);
+ const buffer = Buffer.alloc(maxBytes + 1);
+ let length = 0;
+ while (length < buffer.length) {
+ const count = readSync(fd, buffer, length, buffer.length - length, null);
+ if (count === 0) break;
+ length += count;
+ }
+ return length <= maxBytes ? Buffer.from(buffer.subarray(0, length)) : null;
} catch {
return null;
} finally {
diff --git a/server/skill-command.test.ts b/server/skill-command.test.ts
index ae1e71375c..c49b2a83bd 100644
--- a/server/skill-command.test.ts
+++ b/server/skill-command.test.ts
@@ -4,7 +4,9 @@ import { join } from "node:path";
import type { AppConfig } from "./config.ts";
import { createSkillsLibraryHost } from "./host/skills-library.ts";
-import { enabledSkillFile, installSkill, setSkillEnabled } from "./skills.ts";
+import { applyStagedSkillWrite, enabledSkillFile, installSkill, setSkillEnabled, stageSkillWrite } from "./skills.ts";
+import { librarySkillFilePath } from "./skill-library.ts";
+import { shareLearnedSkill } from "./skill-share.ts";
import type { BotRecord, Store } from "./store.ts";
import { noteTypedSend, typedWords } from "./typed-sends.ts";
import { workspaceDir } from "./workspace.ts";
@@ -60,6 +62,27 @@ describe("parseSkillCommand", () => {
});
describe("words a person typed", () => {
+ it("stages an explicitly called team skill shared after the conversation started", () => {
+ const name = "late-" + randomUUID().slice(0, 8);
+ const author = { id: "author-" + randomUUID().slice(0, 8), name: "Author", section: "Team" };
+ const mate = { id: "mate-" + randomUUID().slice(0, 8), name: "Mate", section: "Team", assignedSkills: [] as string[] } as BotRecord;
+ const staged = stageSkillWrite(author.id, { action: "create", files: [{ path: "SKILL.md", content: SKILL(name) }], source: "learn:conversation" });
+ if ("error" in staged) throw new Error(staged.error);
+ expect(applyStagedSkillWrite(author.id, staged.id, { expectedSha256: staged.sha256 })).not.toHaveProperty("error");
+ expect(shareLearnedSkill({ author, bots: [author, mate], name, now: 1000,
+ patchAssigned: (id, assigned) => { if (id === mate.id) mate.assignedSkills = assigned; },
+ })).not.toHaveProperty("error");
+ const libraryHost = createSkillsLibraryHost({
+ store: { bot: () => mate, messagesFor: () => [{ at: 500 }] } as unknown as Store,
+ cfg: { features: { skillsLibrary: true } } as AppConfig,
+ appendSkillRequestCard: () => ({ requestId: "", summary: "" }),
+ });
+ const engine = { instanceId: "antigravity", driverKind: "antigravityAgent" };
+ expect(libraryHost.skillsIndex(mate, "thread", engine)).not.toContain(name);
+ expect(libraryHost.expandSkillCommand(mate, "thread", "/" + name, engine, [], true)).toContain(JSON.stringify(librarySkillFilePath(name)));
+ expect(libraryHost.turnSkillFiles(mate, "thread", engine)).toContain(librarySkillFilePath(name));
+ });
+
it("offers only enabled skill files for driver staging", () => {
const bot = botWith("standup");
const record = { id: bot } as BotRecord;