From 33e77977e6ad3a967d7fe6dfe1133628fa27803c Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:10:28 -0500 Subject: [PATCH] feat(settings): show all enabled providers and skill toggles on Plugins & Skills Settings > Plugins & Skills previously only listed Codex and Claude, hiding skills and MCP configs for every other enabled provider and leaving non-toggleable rows with a plain On badge and no escape hatch. Add per-provider extension discovery and capability metadata across all built-in drivers (Antigravity, Grok, Cursor, OpenCode, Pi, Muse, fx, and community ACP agents), keeping external OpenCode instances metadata-only and confining project reads and deletes to the canonical repository root. Wire hybrid per-skill toggles for Grok ([skills] ignore in config.toml), local OpenCode (policies skill.use in user opencode.json), and Antigravity personal skills (per-skill profile symlinks inside Threadlines' isolated GEMINI_HOME). Replace On/Off pills on locked skill rows with dimmed disabled switches and tooltips, and add Open plugin, Disable plugin, Open config, Reveal in folder, and symlink target notices to the skill detail modal. --- apps/server/src/guide/topics.ts | 2 +- .../provider/antigravity/AntigravitySkills.ts | 50 +- .../antigravity/AntigravityUserConfig.test.ts | 74 + .../antigravity/AntigravityUserConfig.ts | 497 ++++- .../src/provider/otherProviderExtensions.ts | 1672 +++++++++++++++++ .../src/provider/otherProviderSkillToggles.ts | 884 +++++++++ .../src/provider/providerExtensions.test.ts | 550 ++++++ .../server/src/provider/providerExtensions.ts | 306 ++- apps/server/src/ws.ts | 25 +- .../settings/ExtensionsSettings.logic.test.ts | 45 + .../settings/ExtensionsSettings.logic.ts | 56 +- .../settings/ExtensionsSettings.tsx | 574 ++++-- .../settings/SettingsPanels.browser.tsx | 274 +++ packages/contracts/src/providerExtensions.ts | 35 + 14 files changed, 4769 insertions(+), 275 deletions(-) create mode 100644 apps/server/src/provider/otherProviderExtensions.ts create mode 100644 apps/server/src/provider/otherProviderSkillToggles.ts diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index fa9730789..8a731a808 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -348,7 +348,7 @@ When a Claude, Codex or Antigravity usage limit stops a thread, the notice above "instructions", "rules", ], - body: `{place:settings.plugins} manages what agents can use beyond their own tools, per provider, on this computer or one project: {place:plugins.installed}, {place:plugins.apps}, {place:plugins.connections} (MCP servers) and {place:plugins.hooks}. Its Skills tab is {place:plugins.skills}. + body: `{place:settings.plugins} manages what agents can use beyond their own tools, per provider, on this computer or one project: {place:plugins.installed}, {place:plugins.apps}, {place:plugins.connections} (MCP servers) and {place:plugins.hooks}. Its Skills tab ({place:plugins.skills}) lists skills across every enabled provider (Codex, Claude, Antigravity, Grok, Cursor, OpenCode, Pi, Muse, fx and community agents), lets you toggle skills for Codex, Claude personal skills, Grok, local OpenCode and Antigravity personal skills (inside Threadlines profiles), and lets you inspect, reveal in folder, open provider config, create or delete skills where supported. {place:settings.instructions} shows the instruction files each provider reads in a project (like AGENTS.md or CLAUDE.md), to open or edit.`, }, diff --git a/apps/server/src/provider/antigravity/AntigravitySkills.ts b/apps/server/src/provider/antigravity/AntigravitySkills.ts index 53188ac80..171e09444 100644 --- a/apps/server/src/provider/antigravity/AntigravitySkills.ts +++ b/apps/server/src/provider/antigravity/AntigravitySkills.ts @@ -421,6 +421,8 @@ export interface ListAntigravitySkillsInput { readonly cwd: string; /** The instance's profile (`GEMINI_HOME`), already prepared (`prepareAntigravityProfile`). */ readonly profileDir: string; + /** False on machine-wide views, so home-dir `.agents` / `.gemini` folders are not treated as project roots. */ + readonly includeProject?: boolean; } export interface AntigravitySkillListing { @@ -436,41 +438,49 @@ export async function listAntigravitySkillsNow( ): Promise { const cwd = resolve(input.cwd); const profile = resolve(input.profileDir); + const includeProject = input.includeProject !== false; const scan = new SkillScan( Date.now() + (options.timeLimitMs ?? Duration.toMillis(LIST_TIME_LIMIT)), ); // Nothing outside the project or its repository root is opened for it. - const root = await repositoryRoot(scan, cwd); - const realRoot = (await scan.realpath(root)) ?? root; + const root = includeProject ? await repositoryRoot(scan, cwd) : cwd; + const realRoot = includeProject ? ((await scan.realpath(root)) ?? root) : cwd; const insideProject: Confine = async (path) => { const real = await scan.realpath(path); return real !== undefined && isInside(realRoot, real); }; - const roots: ReadonlyArray = [ - [join(profile, "config", "skills"), "user"], - [join(cwd, ".gemini", "skills"), "project"], - [join(profile, "antigravity-cli", "skills"), "user"], - [join(cwd, ".agents", "skills"), "project"], - [join(cwd, ".agent", "skills"), "project"], - ]; + const roots: ReadonlyArray = includeProject + ? [ + [join(profile, "config", "skills"), "user"], + [join(cwd, ".gemini", "skills"), "project"], + [join(profile, "antigravity-cli", "skills"), "user"], + [join(cwd, ".agents", "skills"), "project"], + [join(cwd, ".agent", "skills"), "project"], + ] + : [ + [join(profile, "config", "skills"), "user"], + [join(profile, "antigravity-cli", "skills"), "user"], + ]; for (const [dir, scope] of roots) { await scan.scanFolder(dir, scope, NO_FILTER, scope === "project" ? insideProject : undefined); } // The CLI skips project manifest entries leaving the project or its repository root. - for (let dir = cwd; ; dir = dirname(dir)) { - for (const folder of [".agents", ".agent"]) { - await scan.scanManifest({ - path: join(dir, folder, "skills.json"), - baseDir: dir, - scope: "project", - filter: NO_FILTER, - confine: insideProject, - }); + if (includeProject) { + for (let dir = cwd; ; dir = dirname(dir)) { + for (const folder of [".agents", ".agent"]) { + await scan.scanManifest({ + path: join(dir, folder, "skills.json"), + baseDir: dir, + scope: "project", + filter: NO_FILTER, + confine: insideProject, + }); + } + if (dir === root || dirname(dir) === dir || scan.exhausted) break; } - if (dir === root || dirname(dir) === dir || scan.exhausted) break; } await scan.scanManifest({ path: join(profile, "config", "skills.json"), @@ -495,7 +505,7 @@ export async function listAntigravitySkillsNow( export function makeAntigravitySkillsLister() { const lastComplete = new Map>(); return (input: ListAntigravitySkillsInput) => { - const key = `${resolve(input.cwd)}\0${resolve(input.profileDir)}`; + const key = `${resolve(input.cwd)}\0${resolve(input.profileDir)}\0${input.includeProject !== false ? "1" : "0"}`; return Effect.promise(() => listAntigravitySkillsNow(input).catch((): AntigravitySkillListing => ({ skills: [], diff --git a/apps/server/src/provider/antigravity/AntigravityUserConfig.test.ts b/apps/server/src/provider/antigravity/AntigravityUserConfig.test.ts index 94bb63b9f..ed90f6df9 100644 --- a/apps/server/src/provider/antigravity/AntigravityUserConfig.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityUserConfig.test.ts @@ -22,6 +22,8 @@ import { ANTIGRAVITY_SHARED_DIRS, ANTIGRAVITY_SHARED_FILES, antigravityUserHome, + readAntigravityDisabledSkills, + setAntigravitySkillDisabled, shareAntigravityUserConfigNow, } from "./AntigravityUserConfig.ts"; @@ -432,4 +434,76 @@ describe("an Antigravity instance and the user's own setup", () => { { name: "review", description: "Review changes.", path: skill, scope: "user", enabled: true }, ]); }); + + it("splits config/skills into per-skill links when a skill is disabled and collapses safely on re-enable", async () => { + const setup = await makeSetup(); + await setup.write("config/skills/alpha/SKILL.md", "---\nname: alpha\n---\n"); + await setup.write("config/skills/beta/SKILL.md", "---\nname: beta\n---\n"); + + await shareAntigravityUserConfigNow({ ...setup, platform: "linux" }); + expect(await linkOf(inProfile(setup.profileDir, "config/skills"))).toBe( + path.join(setup.gemini, "config/skills"), + ); + + const disableProblems = await setAntigravitySkillDisabled({ + ...setup, + platform: "linux", + sharedDir: "config/skills", + entryName: "beta", + disabled: true, + }); + expect(disableProblems).toEqual([]); + expect(await linkOf(inProfile(setup.profileDir, "config/skills"))).toBeUndefined(); + expect(await linkOf(inProfile(setup.profileDir, "config/skills/alpha"))).toBe( + path.join(setup.gemini, "config/skills/alpha"), + ); + expect(await exists(inProfile(setup.profileDir, "config/skills/beta"))).toBe(false); + expect(await readAntigravityDisabledSkills(setup.profileDir)).toEqual({ + "config/skills": ["beta"], + "antigravity-cli/skills": [], + }); + + // Re-enabling restores the whole-directory symlink when no agent-owned folder is inside. + const enableProblems = await setAntigravitySkillDisabled({ + ...setup, + platform: "linux", + sharedDir: "config/skills", + entryName: "beta", + disabled: false, + }); + expect(enableProblems).toEqual([]); + expect(await linkOf(inProfile(setup.profileDir, "config/skills"))).toBe( + path.join(setup.gemini, "config/skills"), + ); + + // If the agent created its own skill while split, re-enabling must keep enabled links intact. + await setAntigravitySkillDisabled({ + ...setup, + platform: "linux", + sharedDir: "config/skills", + entryName: "beta", + disabled: true, + }); + await NodeFS.mkdir(inProfile(setup.profileDir, "config/skills/agent-own"), { recursive: true }); + await NodeFS.writeFile( + inProfile(setup.profileDir, "config/skills/agent-own/SKILL.md"), + "agent", + ); + await setAntigravitySkillDisabled({ + ...setup, + platform: "linux", + sharedDir: "config/skills", + entryName: "beta", + disabled: false, + }); + expect(await exists(inProfile(setup.profileDir, "config/skills/agent-own/SKILL.md"))).toBe( + true, + ); + expect(await linkOf(inProfile(setup.profileDir, "config/skills/alpha"))).toBe( + path.join(setup.gemini, "config/skills/alpha"), + ); + expect(await linkOf(inProfile(setup.profileDir, "config/skills/beta"))).toBe( + path.join(setup.gemini, "config/skills/beta"), + ); + }); }); diff --git a/apps/server/src/provider/antigravity/AntigravityUserConfig.ts b/apps/server/src/provider/antigravity/AntigravityUserConfig.ts index 5c4653a3b..056601881 100644 --- a/apps/server/src/provider/antigravity/AntigravityUserConfig.ts +++ b/apps/server/src/provider/antigravity/AntigravityUserConfig.ts @@ -51,11 +51,10 @@ import { readRegularFile } from "./AntigravityFileReads.ts"; * always-on rule files (CLI changelog: global customization in * `~/.gemini/config` includes the `rules/` folder). */ -export const ANTIGRAVITY_SHARED_DIRS = [ - "config/skills", - "antigravity-cli/skills", - "config/rules", -] as const; +export const ANTIGRAVITY_SKILL_DIRS = ["config/skills", "antigravity-cli/skills"] as const; +export type AntigravitySkillDir = (typeof ANTIGRAVITY_SKILL_DIRS)[number]; + +export const ANTIGRAVITY_SHARED_DIRS = [...ANTIGRAVITY_SKILL_DIRS, "config/rules"] as const; /** Global rule files and the skill and rule manifests, relative to `GEMINI_HOME`. */ export const ANTIGRAVITY_SHARED_FILES = [ @@ -88,10 +87,12 @@ const KEEP_OUT_NAMES = new Set([ /** Copies above this size are skipped: the CLI cuts a rule file off far below it. */ const MAX_COPY_BYTES = 1_000_000; -const MAX_RECORD_BYTES = 64 * 1024; +const MAX_RECORD_BYTES = 1024 * 1024; /** No chat waits longer than this for the user's rules and skills. */ const SHARE_TIME_LIMIT = Duration.seconds(10); +const SKILL_DIR_SET = new Set(ANTIGRAVITY_SKILL_DIRS); + /** What Threadlines put in the profile, so it never touches what it didn't. */ interface SharedConfigRecord { /** Link path (relative to the profile) to the target it was made for. */ @@ -102,16 +103,42 @@ interface SharedConfigRecord { * the copy landing and the record catching up leaves it still ours. */ copies: Record>; + /** + * Per-skill-dir folder names disabled inside this Threadlines profile. + * Empty/absent keeps the whole skills folder linked as one symlink. + */ + disabledSkills?: Record>; + /** + * Shared skill directories currently materialized as real folders holding + * per-skill links so disabled entries can be omitted cleanly. + */ + splitDirs?: Array; } /** Beside the profile, so the record is outside the folder the agent keeps as its home. */ export const antigravitySharedConfigRecordPath = (profileDir: string) => `${profileDir}.shared-config.json`; +function isSafeEntryName(name: string): boolean { + return ( + name.length > 0 && + name !== "." && + name !== ".." && + !name.includes("/") && + !name.includes("\\") && + !name.includes("\0") + ); +} + function parseRecord(raw: unknown): SharedConfigRecord { const record: SharedConfigRecord = { links: {}, copies: {} }; if (typeof raw !== "object" || raw === null) return record; - const { links, copies } = raw as { links?: unknown; copies?: unknown }; + const { links, copies, disabledSkills, splitDirs } = raw as { + links?: unknown; + copies?: unknown; + disabledSkills?: unknown; + splitDirs?: unknown; + }; if (typeof links === "object" && links !== null) { for (const [rel, target] of Object.entries(links)) { if (typeof target === "string") record.links[rel] = target; @@ -124,6 +151,29 @@ function parseRecord(raw: unknown): SharedConfigRecord { } } } + if (typeof disabledSkills === "object" && disabledSkills !== null) { + const parsedDisabled: Record> = {}; + for (const [rel, entries] of Object.entries(disabledSkills)) { + if (!SKILL_DIR_SET.has(rel) || !Array.isArray(entries)) continue; + const valid = [ + ...new Set( + entries.filter( + (entry): entry is string => typeof entry === "string" && isSafeEntryName(entry), + ), + ), + ].toSorted(); + if (valid.length > 0) parsedDisabled[rel] = valid; + } + if (Object.keys(parsedDisabled).length > 0) record.disabledSkills = parsedDisabled; + } + if (Array.isArray(splitDirs)) { + const validSplit = [ + ...new Set( + splitDirs.filter((rel): rel is string => typeof rel === "string" && SKILL_DIR_SET.has(rel)), + ), + ].toSorted(); + if (validSplit.length > 0) record.splitDirs = validSplit; + } return record; } @@ -140,12 +190,36 @@ async function readRecord(profileDir: string): Promise { } async function writeRecord(profileDir: string, record: SharedConfigRecord): Promise { + const payload = JSON.stringify(record); + if (Buffer.byteLength(payload, "utf8") > MAX_RECORD_BYTES) { + throw new Error("Antigravity shared-config record exceeded the maximum safe size."); + } const target = antigravitySharedConfigRecordPath(profileDir); const temp = `${target}.${randomBytes(4).toString("hex")}.tmp`; - await fs.writeFile(temp, JSON.stringify(record), { mode: 0o600, flag: "wx" }); + await fs.writeFile(temp, payload, { mode: 0o600, flag: "wx" }); await fs.rename(temp, target); } +/** Reads per-shared-dir disabled skill folder names stored beside an Antigravity profile. */ +export async function readAntigravityDisabledSkills( + profileDir: string, +): Promise>>> { + const record = await readRecord(profileDir); + return { + "config/skills": record.disabledSkills?.["config/skills"] ?? [], + "antigravity-cli/skills": record.disabledSkills?.["antigravity-cli/skills"] ?? [], + }; +} + +/** Whether Threadlines currently manages `rel` in `profileDir` as a split per-skill folder. */ +export async function isAntigravitySplitSkillDir( + profileDir: string, + rel: AntigravitySkillDir, +): Promise { + const record = await readRecord(profileDir); + return record.splitDirs?.includes(rel) === true; +} + /** * The home folder the agent will treat as `~`, which is where its global * config lives: Python's `os.path.expanduser`, so `USERPROFILE` (then @@ -430,9 +504,340 @@ export interface ShareAntigravityUserConfigInput { readonly threadlinesDir?: string; } +export interface SetAntigravitySkillDisabledInput extends ShareAntigravityUserConfigInput { + readonly sharedDir: AntigravitySkillDir; + readonly entryName: string; + readonly disabled: boolean; +} + +async function hasDirectSkillFile(dir: string): Promise { + const entries = await fs.readdir(dir).catch(() => undefined); + if (!entries) return false; + for (const name of entries) { + if (name.toLowerCase() !== "skill.md") continue; + const stat = await fs.stat(join(dir, name)).catch(() => undefined); + if (stat?.isFile()) return true; + } + return false; +} + +function addSplitDir(record: SharedConfigRecord, rel: AntigravitySkillDir): void { + const next = new Set(record.splitDirs ?? []); + next.add(rel); + record.splitDirs = [...next].toSorted(); +} + +function removeSplitDir(record: SharedConfigRecord, rel: AntigravitySkillDir): void { + const next = (record.splitDirs ?? []).filter((item) => item !== rel); + if (next.length > 0) record.splitDirs = next; + else delete record.splitDirs; +} + +function childLinkPrefix(rel: AntigravitySkillDir): string { + return `${rel}/`; +} + +/** + * Reconciles per-skill links inside `/` for a split skill folder. + * Enabled child directories from `source` are linked into the profile; disabled or removed + * children have only Threadlines-owned links removed, leaving any agent-created folders intact. + */ +async function reconcileSplitSkillChildren(input: { + readonly rel: AntigravitySkillDir; + readonly path: string; + readonly source: string; + readonly allowed: boolean; + readonly disabledEntries: ReadonlySet; + readonly profileDir: string; + readonly realProfile: string; + readonly platform: NodeJS.Platform; + readonly rules: SourceRules; + readonly record: SharedConfigRecord; + readonly claim: () => Promise; + readonly problems: Array<{ path: string; error: string }>; +}): Promise { + const prefix = childLinkPrefix(input.rel); + const seenChildRels = new Set(); + + if (input.allowed) { + const names = await fs.readdir(input.source).catch(() => undefined); + if (!names) { + input.problems.push({ + path: input.source, + error: "Could not read the shared Antigravity skills folder; keeping existing links.", + }); + return; + } + for (const name of names.toSorted()) { + if (!isSafeEntryName(name)) continue; + const childSource = join(input.source, name); + const childAllowed = await sourceAllowed(childSource, "dir", input.rules); + if (!childAllowed) continue; + const childRel = `${prefix}${name}`; + seenChildRels.add(childRel); + const childPath = join(input.path, name); + const childParent = { + profileDir: input.profileDir, + realProfile: input.realProfile, + rel: childRel, + }; + try { + if (!(await realParentInProfile({ ...childParent, create: false }))) { + input.problems.push({ + path: childPath, + error: "A folder on the way is a link; left alone.", + }); + continue; + } + await shareByLink({ + rel: childRel, + path: childPath, + source: childSource, + kind: "dir", + allowed: !input.disabledEntries.has(name), + platform: input.platform, + record: input.record, + claim: input.claim, + makeParent: () => realParentInProfile({ ...childParent, create: true }), + }); + } catch (error) { + input.problems.push({ path: childPath, error: String(error) }); + } + } + } + + // Clean up Threadlines-owned links for skills that disappeared from the source folder. + const staleRels = Object.keys(input.record.links).filter( + (key) => key.startsWith(prefix) && !seenChildRels.has(key), + ); + for (const staleRel of staleRels) { + const childPath = join(input.profileDir, ...staleRel.split("/")); + const childParent = { + profileDir: input.profileDir, + realProfile: input.realProfile, + rel: staleRel, + }; + try { + if (!(await realParentInProfile({ ...childParent, create: false }))) continue; + await shareByLink({ + rel: staleRel, + path: childPath, + source: input.record.links[staleRel] ?? "", + kind: "dir", + allowed: false, + platform: input.platform, + record: input.record, + claim: input.claim, + makeParent: () => Promise.resolve(false), + }); + } catch (error) { + input.problems.push({ path: childPath, error: String(error) }); + } + } +} + +/** + * Attempts to collapse a split skill directory back to a single whole-folder symlink once no + * skills are disabled. Refuses to delete anything Threadlines did not create; if an agent-owned + * folder exists inside, keeps split mode so enabled skills stay linked. + */ +async function tryCollapseSplitSkillDir(input: { + readonly rel: AntigravitySkillDir; + readonly path: string; + readonly record: SharedConfigRecord; +}): Promise { + const prefix = childLinkPrefix(input.rel); + const stat = await fs.lstat(input.path).catch(() => undefined); + if (!stat) { + for (const key of Object.keys(input.record.links)) { + if (key.startsWith(prefix)) delete input.record.links[key]; + } + removeSplitDir(input.record, input.rel); + return true; + } + if (!stat.isDirectory()) { + removeSplitDir(input.record, input.rel); + return false; + } + const names = await fs.readdir(input.path).catch(() => undefined); + if (!names) return false; + + // Verify every child is a Threadlines-owned link BEFORE removing anything, so a foreign or + // agent-created folder never causes enabled links to be stripped out. + const ownedChildren: Array<{ + readonly rel: string; + readonly path: string; + readonly target: string; + }> = []; + for (const name of names) { + const childRel = `${prefix}${name}`; + const recorded = input.record.links[childRel]; + if (recorded === undefined) return false; + const childPath = join(input.path, name); + const childStat = await fs.lstat(childPath).catch(() => undefined); + if (!childStat?.isSymbolicLink()) return false; + const current = await linkTarget(childPath).catch(() => undefined); + if (current !== recorded) return false; + ownedChildren.push({ rel: childRel, path: childPath, target: recorded }); + } + + for (const child of ownedChildren) { + const removed = await removeIfOurs(child.path, async (aside) => { + const asideStat = await fs.lstat(aside).catch(() => undefined); + return asideStat?.isSymbolicLink() === true && (await linkTarget(aside)) === child.target; + }); + if (!removed) return false; + delete input.record.links[child.rel]; + } + + const removedDir = await fs.rmdir(input.path).then( + () => true, + () => false, + ); + if (!removedDir) return false; + + for (const key of Object.keys(input.record.links)) { + if (key.startsWith(prefix)) delete input.record.links[key]; + } + removeSplitDir(input.record, input.rel); + return true; +} + +/** Shares one of Antigravity's skill directories, switching to per-skill links only when needed. */ +async function shareSkillDir(input: { + readonly rel: AntigravitySkillDir; + readonly entry: EntryContext; + readonly profileDir: string; + readonly realProfile: string; + readonly rules: SourceRules; + readonly problems: Array<{ path: string; error: string }>; +}): Promise { + const { rel, entry } = input; + const disabledList = entry.record.disabledSkills?.[rel] ?? []; + const disabledSet = new Set(disabledList); + const isSplit = entry.record.splitDirs?.includes(rel) === true; + + if (disabledSet.size === 0) { + if (isSplit) { + const collapsed = await tryCollapseSplitSkillDir({ + rel, + path: entry.path, + record: entry.record, + }); + if (!collapsed) { + // An agent-owned entry lives inside the split folder: keep split mode and ensure every + // enabled child stays linked. + await reconcileSplitSkillChildren({ + rel, + path: entry.path, + source: entry.source, + allowed: entry.allowed, + disabledEntries: disabledSet, + profileDir: input.profileDir, + realProfile: input.realProfile, + platform: entry.platform, + rules: input.rules, + record: entry.record, + claim: entry.claim, + problems: input.problems, + }); + return; + } + } + await shareByLink(entry); + return; + } + + if (!entry.allowed) { + await reconcileSplitSkillChildren({ + rel, + path: entry.path, + source: entry.source, + allowed: false, + disabledEntries: disabledSet, + profileDir: input.profileDir, + realProfile: input.realProfile, + platform: entry.platform, + rules: input.rules, + record: entry.record, + claim: entry.claim, + problems: input.problems, + }); + if (isSplit) { + await tryCollapseSplitSkillDir({ rel, path: entry.path, record: entry.record }); + } else { + await shareByLink(entry); + } + return; + } + + if (await hasDirectSkillFile(entry.source)) { + input.problems.push({ + path: entry.path, + error: "Cannot disable individual skills when the skills folder itself is a single skill.", + }); + await shareByLink(entry); + return; + } + + const stat = await fs.lstat(entry.path).catch(() => undefined); + if (stat?.isSymbolicLink()) { + const recorded = entry.record.links[rel]; + const current = await linkTarget(entry.path).catch(() => undefined); + if (recorded === undefined || current !== recorded) { + input.problems.push({ + path: entry.path, + error: "A foreign symlink occupies this skills folder; left alone.", + }); + return; + } + const removed = await removeIfOurs(entry.path, async (aside) => { + const asideStat = await fs.lstat(aside).catch(() => undefined); + return asideStat?.isSymbolicLink() === true && (await linkTarget(aside)) === recorded; + }); + if (!removed) { + input.problems.push({ + path: entry.path, + error: "Could not replace the existing skills link; left alone.", + }); + return; + } + delete entry.record.links[rel]; + if (!(await entry.makeParent())) return; + await fs.mkdir(entry.path, { mode: 0o700 }); + } else if (!stat) { + if (!(await entry.makeParent())) return; + await fs.mkdir(entry.path, { mode: 0o700 }); + } else if (!stat.isDirectory()) { + input.problems.push({ + path: entry.path, + error: "A file occupies this skills folder; left alone.", + }); + return; + } + + addSplitDir(entry.record, rel); + await entry.claim(); + await reconcileSplitSkillChildren({ + rel, + path: entry.path, + source: entry.source, + allowed: true, + disabledEntries: disabledSet, + profileDir: input.profileDir, + realProfile: input.realProfile, + platform: entry.platform, + rules: input.rules, + record: entry.record, + claim: entry.claim, + problems: input.problems, + }); +} + /** Brings the user's shared rules and skills into the profile; returns what failed. */ async function shareOnce( input: ShareAntigravityUserConfigInput, + mutateDisabled?: (disabled: Record>) => void, ): Promise> { await fs.mkdir(input.profileDir, { recursive: true, mode: 0o700 }); const realProfile = await fs.realpath(input.profileDir); @@ -443,11 +848,27 @@ async function shareOnce( forbidden: [realProfile, ...(threadlinesDir ? [threadlinesDir] : [])], }; const before = await readRecord(input.profileDir); + const disabledSkills: Record> = {}; + for (const [rel, entries] of Object.entries(before.disabledSkills ?? {})) { + disabledSkills[rel] = [...entries]; + } + if (mutateDisabled) { + mutateDisabled(disabledSkills); + for (const [rel, entries] of Object.entries(disabledSkills)) { + const cleaned = [...new Set(entries.filter((entry) => isSafeEntryName(entry)))].toSorted(); + if (cleaned.length > 0) disabledSkills[rel] = cleaned; + else delete disabledSkills[rel]; + } + } const record: SharedConfigRecord = { links: { ...before.links }, copies: { ...before.copies }, + ...(Object.keys(disabledSkills).length > 0 ? { disabledSkills } : {}), + ...(before.splitDirs && before.splitDirs.length > 0 + ? { splitDirs: [...before.splitDirs] } + : {}), }; - let saved = JSON.stringify(record); + let saved = JSON.stringify(before); const save = async () => { const next = JSON.stringify(record); if (next === saved) return; @@ -479,8 +900,20 @@ async function shareOnce( claim: save, makeParent: () => realParentInProfile({ ...parent, create: true }), }; - if (kind === "file" && input.platform === "win32") await shareByCopy(entry); - else await shareByLink(entry); + if (kind === "dir" && SKILL_DIR_SET.has(rel)) { + await shareSkillDir({ + rel: rel as AntigravitySkillDir, + entry, + profileDir: input.profileDir, + realProfile, + rules, + problems, + }); + } else if (kind === "file" && input.platform === "win32") { + await shareByCopy(entry); + } else { + await shareByLink(entry); + } } catch (error) { problems.push({ path, error: String(error) }); } @@ -497,17 +930,17 @@ async function shareOnce( /** The run in progress for each profile: two starts never share at once. */ const running = new Map>(); -/** `shareOnce`, one at a time per profile; a run stuck past the time bound no longer holds the next. */ -export function shareAntigravityUserConfigNow( - input: ShareAntigravityUserConfigInput, +function enqueueProfileShare( + profileDir: string, + task: () => Promise>, ): Promise> { - const key = resolve(input.profileDir); + const key = resolve(profileDir); const previous = running.get(key) ?? Promise.resolve(); const waited = Promise.race([ previous.catch(() => undefined), new Promise((done) => setTimeout(done, Duration.toMillis(SHARE_TIME_LIMIT)).unref()), ]); - const run = waited.then(() => shareOnce(input)); + const run = waited.then(task); const settled = run.catch(() => undefined); running.set(key, settled); void settled.then(() => { @@ -516,6 +949,38 @@ export function shareAntigravityUserConfigNow( return run; } +/** `shareOnce`, one at a time per profile; a run stuck past the time bound no longer holds the next. */ +export function shareAntigravityUserConfigNow( + input: ShareAntigravityUserConfigInput, +): Promise> { + return enqueueProfileShare(input.profileDir, () => shareOnce(input)); +} + +/** + * Enables or disables one personal skill folder inside an Antigravity profile and reconciles the + * profile links immediately. Serialized with normal profile sharing so launches never race toggles. + */ +export function setAntigravitySkillDisabled( + input: SetAntigravitySkillDisabledInput, +): Promise> { + if (!isSafeEntryName(input.entryName)) { + return Promise.resolve([ + { + path: input.profileDir, + error: `Invalid Antigravity skill folder name: ${input.entryName}`, + }, + ]); + } + return enqueueProfileShare(input.profileDir, () => + shareOnce(input, (disabled) => { + const current = new Set(disabled[input.sharedDir] ?? []); + if (input.disabled) current.add(input.entryName); + else current.delete(input.entryName); + disabled[input.sharedDir] = [...current]; + }), + ); +} + /** * `shareAntigravityUserConfigNow` as an effect that never fails and never * waits past its time bound: a rule or skill that can't be brought in is diff --git a/apps/server/src/provider/otherProviderExtensions.ts b/apps/server/src/provider/otherProviderExtensions.ts new file mode 100644 index 000000000..d16fca5ff --- /dev/null +++ b/apps/server/src/provider/otherProviderExtensions.ts @@ -0,0 +1,1672 @@ +/** + * Multi-provider extension discovery and skill root resolution for providers + * other than Codex and Claude (Antigravity, Grok, Cursor, OpenCode, Pi, Muse, + * fx, and community ACP agents). + * + * Each built-in driver declares only the roots and read-only config formats it + * is known to read. Project roots are scanned only when a project scope (`cwd`) + * is selected and are strictly confined to the canonical repository root so a + * symlinked project folder cannot read or delete files outside the checkout. + * Untested community agents (`acpRegistry`) never scan disk; they surface only + * snapshot-reported skills. + * + * @module provider/otherProviderExtensions + */ +import { homedir } from "node:os"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import { + AcpRegistrySettings, + AntigravitySettings, + CursorSettings, + FxSettings, + GrokSettings, + MuseSettings, + OpenCodeSettings, + PiSettings, + ProviderDriverKind, + type ProviderExtensionMcpServer, + type ProviderExtensionProviderCapabilities, + type ProviderExtensionProviderInventory, + type ProviderExtensionSkill, + type ProviderInstanceConfig, + type ProviderInstanceId, + type ServerProvider, + type ServerProviderSkill, +} from "@threadlines/contracts"; + +import { expandHomePath } from "../pathExpansion.ts"; +import { antigravityInstancePaths } from "./antigravity/AntigravityProfile.ts"; +import { makeAntigravitySkillsLister } from "./antigravity/AntigravitySkills.ts"; +import { + type AntigravitySkillDir, + antigravityUserGeminiDir, + antigravityUserHome, + readAntigravityDisabledSkills, +} from "./antigravity/AntigravityUserConfig.ts"; +import { grokMainHome } from "./grok/GrokAccountFolder.ts"; +import { + antigravityProfileManagesSkillDir, + evaluateOpenCodeSkillPolicy, + hasOpenCodePolicyWildcard, + listAntigravityDirectUserSkills, + readGrokIgnoreState, + syncAntigravityProfileAfterSkillMutation, + writeAntigravitySkillToggle, + writeGrokSkillToggle, + writeOpenCodeSkillToggle, +} from "./otherProviderSkillToggles.ts"; +import { piAgentDir } from "./pi/PiBinary.ts"; + +export const ANTIGRAVITY_DRIVER = ProviderDriverKind.make("antigravity"); +export const GROK_DRIVER = ProviderDriverKind.make("grok"); +export const CURSOR_DRIVER = ProviderDriverKind.make("cursor"); +export const OPENCODE_DRIVER = ProviderDriverKind.make("opencode"); +export const PI_DRIVER = ProviderDriverKind.make("pi"); +export const MUSE_DRIVER = ProviderDriverKind.make("muse"); +export const FX_DRIVER = ProviderDriverKind.make("fx"); +export const ACP_REGISTRY_DRIVER = ProviderDriverKind.make("acpRegistry"); + +const MAX_SKILL_FILE_BYTES = 32_000; +const MAX_SKILL_ROOT_SCAN_DIRECTORIES = 250; +const MAX_SKILL_ROOT_SCAN_DEPTH = 6; + +const decodeAntigravitySettings = Schema.decodeUnknownSync(AntigravitySettings); +const decodeGrokSettings = Schema.decodeUnknownSync(GrokSettings); +const decodeCursorSettings = Schema.decodeUnknownSync(CursorSettings); +const decodeOpenCodeSettings = Schema.decodeUnknownSync(OpenCodeSettings); +const decodePiSettings = Schema.decodeUnknownSync(PiSettings); +const decodeMuseSettings = Schema.decodeUnknownSync(MuseSettings); +const decodeFxSettings = Schema.decodeUnknownSync(FxSettings); +const decodeAcpRegistrySettings = Schema.decodeUnknownSync(AcpRegistrySettings); + +const antigravitySkillsLister = makeAntigravitySkillsLister(); + +export interface OtherProviderSkillRoots { + readonly driver: string; + /** Where newly created skills are written (user scope). */ + readonly userSkillsRoot: string; + /** User-configured writable roots (may intentionally be symlinked, e.g. dotfiles). */ + readonly userWritableRoots: ReadonlyArray; + /** Project-scoped writable roots (must stay confined inside `projectBoundary`). */ + readonly projectWritableRoots: ReadonlyArray; + /** Canonical repository boundary confining `projectWritableRoots`. */ + readonly projectBoundary?: string | undefined; +} + +interface ScannedSkillRoot { + readonly root: string; + readonly scope: "project" | "user" | "system"; + readonly source: string; + readonly priority: number; + readonly confineToProject?: boolean; +} + +function optionalText(value: string | null | undefined): string | undefined { + const trimmed = value?.trim(); + return trimmed && trimmed.length > 0 ? trimmed : undefined; +} + +function normalizedPathKey(filePath: string): string { + const normalized = filePath.replaceAll("\\", "/").replace(/\/+$/, ""); + return process.platform === "win32" ? normalized.toLowerCase() : normalized; +} + +export function isPathWithinBoundary( + path: Path.Path, + boundary: string, + candidate: string, +): boolean { + const rel = path.relative(boundary, candidate); + return ( + rel === "" || + (!path.isAbsolute(rel) && + rel !== ".." && + !rel.startsWith(`..${path.sep}`) && + !rel.startsWith("../")) + ); +} + +function environmentHome(environment: NodeJS.ProcessEnv): string { + const home = + process.platform === "win32" + ? environment.USERPROFILE?.trim() || environment.HOME?.trim() + : environment.HOME?.trim() || environment.USERPROFILE?.trim(); + return home || homedir(); +} + +function openCodeConfigDir(environment: NodeJS.ProcessEnv): string { + const xdgConfigHome = environment.XDG_CONFIG_HOME?.trim(); + return xdgConfigHome + ? `${xdgConfigHome}/opencode` + : `${environmentHome(environment)}/.config/opencode`; +} + +function resolveGrokHome( + config: GrokSettings, + environment: NodeJS.ProcessEnv, + path: Path.Path, +): string { + const accountFolder = optionalText(config.accountFolder); + if (accountFolder) { + return path.resolve(expandHomePath(accountFolder)); + } + return grokMainHome(environment); +} + +/** + * Resolves effective enabled state for non-Codex/Claude drivers, checking both the outer instance + * record and legacy synthesized settings inside `config.config`. + */ +export function resolveOtherProviderEnabled( + config: ProviderInstanceConfig, + snapshot: ServerProvider | undefined, +): boolean { + if (typeof config.enabled === "boolean") return config.enabled; + const raw = config.config ?? {}; + try { + switch (config.driver) { + case ANTIGRAVITY_DRIVER: + return decodeAntigravitySettings(raw).enabled; + case GROK_DRIVER: + return decodeGrokSettings(raw).enabled; + case CURSOR_DRIVER: + return decodeCursorSettings(raw).enabled; + case OPENCODE_DRIVER: + return decodeOpenCodeSettings(raw).enabled; + case PI_DRIVER: + return decodePiSettings(raw).enabled; + case MUSE_DRIVER: + return decodeMuseSettings(raw).enabled; + case FX_DRIVER: + return decodeFxSettings(raw).enabled; + case ACP_REGISTRY_DRIVER: + return decodeAcpRegistrySettings(raw).enabled; + default: + return snapshot?.enabled ?? false; + } + } catch { + return snapshot?.enabled ?? false; + } +} + +function decodeOpenCodeSettingsSafe(config: ProviderInstanceConfig): OpenCodeSettings | null { + try { + return decodeOpenCodeSettings(config.config ?? {}); + } catch { + return null; + } +} + +/** + * True when an OpenCode instance points at an external `serverUrl` (or its config is malformed so + * we cannot prove it is local). External instances must never scan, read, or write local files. + */ +export function isExternalOpenCodeConfig(config: ProviderInstanceConfig): boolean { + if (config.driver !== OPENCODE_DRIVER) return false; + const rawUrl = (config.config as { readonly serverUrl?: unknown } | undefined)?.serverUrl; + if (typeof rawUrl === "string" && rawUrl.trim().length > 0) return true; + const decoded = decodeOpenCodeSettingsSafe(config); + if (!decoded) return true; + return decoded.serverUrl.trim().length > 0; +} + +function decodeGrokSettingsSafe(config: ProviderInstanceConfig): GrokSettings | null { + try { + return decodeGrokSettings(config.config ?? {}); + } catch { + return null; + } +} + +export const findRepositoryRoot = Effect.fn("otherProviderExtensions.findRepositoryRoot")( + function* (cwd: string) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + let current = path.resolve(cwd); + for (;;) { + const gitExists = yield* fileSystem.stat(path.join(current, ".git")).pipe( + Effect.map(() => true), + Effect.catch(() => Effect.succeed(false)), + ); + if (gitExists) return current; + const parent = path.dirname(current); + if (parent === current) return path.resolve(cwd); + current = parent; + } + }, +); + +function parseFrontMatterFields(contents: string): { + readonly name?: string; + readonly description?: string; +} { + const normalized = contents.replace(/\r\n/g, "\n"); + const match = normalized.match(/^---\n([\s\S]*?)\n---(?:\n|$)/); + if (!match?.[1]) return {}; + const fields = new Map(); + for (const line of match[1].split("\n")) { + const pair = line.match(/^([A-Za-z0-9_-]+):\s*(.*)$/); + if (!pair?.[1]) continue; + const key = pair[1].trim().toLowerCase(); + const rawValue = (pair[2] ?? "").trim(); + const unquoted = + (rawValue.startsWith('"') && rawValue.endsWith('"')) || + (rawValue.startsWith("'") && rawValue.endsWith("'")) + ? rawValue.slice(1, -1).trim() + : rawValue; + if (unquoted.length > 0) fields.set(key, unquoted); + } + const name = fields.get("name"); + const description = fields.get("description"); + return { + ...(name ? { name } : {}), + ...(description ? { description } : {}), + }; +} + +function firstMarkdownParagraph(contents: string): string | undefined { + const withoutFrontMatter = contents + .replace(/\r\n/g, "\n") + .replace(/^---\n[\s\S]*?\n---(?:\n|$)/, ""); + for (const line of withoutFrontMatter.split("\n")) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith("#")) continue; + return trimmed; + } + return undefined; +} + +const listChildDirectories = Effect.fn("otherProviderExtensions.listChildDirectories")(function* ( + directory: string, +): Effect.fn.Return { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const entries = yield* fileSystem + .readDirectory(directory) + .pipe(Effect.catch(() => Effect.succeed([]))); + const children = entries + .filter((entry) => !entry.startsWith(".")) + .map((entry) => path.join(directory, entry)); + const stats = yield* Effect.forEach( + children, + (child) => fileSystem.stat(child).pipe(Effect.catch(() => Effect.succeed(null))), + { concurrency: 16 }, + ); + return children.filter((_, index) => stats[index]?.type === "Directory"); +}); + +const scanSkillRoot = Effect.fn("otherProviderExtensions.scanSkillRoot")(function* ( + rootInput: ScannedSkillRoot, + projectBoundary: string | undefined, +): Effect.fn.Return< + ReadonlyArray<{ readonly skill: ProviderExtensionSkill; readonly priority: number }>, + never, + FileSystem.FileSystem | Path.Path +> { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const resolvedRoot = path.resolve(rootInput.root); + const rootStat = yield* fileSystem + .stat(resolvedRoot) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!rootStat || rootStat.type !== "Directory") return []; + + const realRoot = yield* fileSystem + .realPath(resolvedRoot) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!realRoot) return []; + if (rootInput.confineToProject) { + if (!projectBoundary || !isPathWithinBoundary(path, projectBoundary, realRoot)) { + return []; + } + } + // Canonicalize the parent directory so macOS `/var` -> `/private/var` temp paths do not look like + // user symlinks, while preserving an intentional symlink on the skills root itself (e.g. dotfiles). + const canonicalParent = yield* fileSystem + .realPath(path.dirname(resolvedRoot)) + .pipe(Effect.catch(() => Effect.succeed(null))); + const discoveredRoot = canonicalParent + ? path.join(canonicalParent, path.basename(resolvedRoot)) + : resolvedRoot; + + let scannedDirectories = 0; + const found: Array<{ + readonly directory: string; + readonly skillPath: string; + readonly size: number; + }> = []; + + const walk = ( + directory: string, + depth: number, + ): Effect.Effect => + Effect.gen(function* () { + if (depth > MAX_SKILL_ROOT_SCAN_DEPTH) return; + if (scannedDirectories >= MAX_SKILL_ROOT_SCAN_DIRECTORIES) return; + scannedDirectories += 1; + + if (rootInput.confineToProject && projectBoundary) { + const realDir = yield* fileSystem + .realPath(directory) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!realDir || !isPathWithinBoundary(path, projectBoundary, realDir)) { + return; + } + } + + const skillPath = path.join(directory, "SKILL.md"); + const skillStat = yield* fileSystem + .stat(skillPath) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (directory !== discoveredRoot && skillStat?.type === "File") { + found.push({ directory, skillPath, size: Number(skillStat.size) }); + return; + } + + for (const child of yield* listChildDirectories(directory)) { + yield* walk(child, depth + 1); + } + }); + + yield* walk(discoveredRoot, 0); + + const mapped = yield* Effect.forEach( + found, + ({ directory, skillPath, size }) => + Effect.gen(function* () { + // Keep the discovered path under `discoveredRoot` (so a per-skill symlink stays visible to + // delete checks and never deletes a sibling's target). Expose `resolvedPath` when the + // canonical target differs (for example, a shared dotfiles folder). + const realSkillPath = yield* fileSystem + .realPath(skillPath) + .pipe(Effect.catch(() => Effect.succeed(null))); + if ( + rootInput.confineToProject && + projectBoundary && + (!realSkillPath || !isPathWithinBoundary(path, projectBoundary, realSkillPath)) + ) { + return null; + } + const fallbackName = path.basename(directory); + let name = fallbackName; + let description: string | undefined; + if (size <= MAX_SKILL_FILE_BYTES) { + const contents = yield* fileSystem + .readFileString(skillPath) + .pipe(Effect.catch(() => Effect.succeed(""))); + const fm = parseFrontMatterFields(contents); + if (fm.name) name = fm.name; + description = fm.description ?? firstMarkdownParagraph(contents); + } + const hasDifferentTarget = + realSkillPath !== null && + normalizedPathKey(realSkillPath) !== normalizedPathKey(skillPath); + const skill: ProviderExtensionSkill = { + name, + path: skillPath, + enabled: true, + scope: rootInput.scope, + source: rootInput.source, + ...(description ? { description } : {}), + ...(hasDifferentTarget ? { resolvedPath: realSkillPath } : {}), + }; + return { skill, priority: rootInput.priority }; + }), + { concurrency: 8 }, + ); + + return mapped.filter((entry): entry is NonNullable => entry !== null); +}); + +function dedupeSkillsByPriority( + entries: ReadonlyArray<{ readonly skill: ProviderExtensionSkill; readonly priority: number }>, +): ProviderExtensionSkill[] { + const sorted = [...entries].toSorted((left, right) => right.priority - left.priority); + const byName = new Map(); + for (const entry of sorted) { + const key = entry.skill.name.trim().toLowerCase(); + if (!byName.has(key)) { + byName.set(key, entry.skill); + } + } + return [...byName.values()].toSorted((left, right) => left.name.localeCompare(right.name)); +} + +const isDirectChildUnderWritableRoots = Effect.fn( + "otherProviderExtensions.isDirectChildUnderWritableRoots", +)(function* (input: { + readonly skillPath: string; + readonly userWritableRoots: ReadonlyArray; + readonly projectWritableRoots: ReadonlyArray; + readonly projectBoundary?: string | undefined; +}) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const resolvedSkillPath = path.resolve(input.skillPath); + const skillDir = path.dirname(resolvedSkillPath); + // Never mark a symlinked skill file or symlinked skill directory as deletable. + const [skillLink, dirLink] = yield* Effect.all([ + fileSystem.readLink(resolvedSkillPath).pipe(Effect.catch(() => Effect.succeed(null))), + fileSystem.readLink(skillDir).pipe(Effect.catch(() => Effect.succeed(null))), + ]); + if (skillLink !== null || dirLink !== null) return false; + const realDir = yield* fileSystem + .realPath(skillDir) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!realDir) return false; + const parentKey = normalizedPathKey(path.dirname(realDir)); + + for (const userRoot of input.userWritableRoots) { + const realRoot = yield* fileSystem + .realPath(userRoot) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (realRoot && normalizedPathKey(realRoot) === parentKey) return true; + } + + if (input.projectBoundary) { + for (const projectRoot of input.projectWritableRoots) { + const realRoot = yield* fileSystem + .realPath(projectRoot) + .pipe(Effect.catch(() => Effect.succeed(null))); + if ( + realRoot && + isPathWithinBoundary(path, input.projectBoundary, realRoot) && + isPathWithinBoundary(path, input.projectBoundary, realDir) && + normalizedPathKey(realRoot) === parentKey + ) { + return true; + } + } + } + + return false; +}); + +const annotateDeletableSkills = Effect.fn("otherProviderExtensions.annotateDeletableSkills")( + function* (skills: ReadonlyArray, roots: OtherProviderSkillRoots | null) { + if (!roots) return [...skills]; + return yield* Effect.forEach( + skills, + (skill) => + Effect.gen(function* () { + if (skill.bundleId !== undefined || skill.scope === "system" || skill.canRead === false) { + return skill; + } + const canDelete = yield* isDirectChildUnderWritableRoots({ + skillPath: skill.path, + userWritableRoots: roots.userWritableRoots, + projectWritableRoots: roots.projectWritableRoots, + projectBoundary: roots.projectBoundary, + }); + return canDelete ? { ...skill, canDelete: true } : skill; + }), + { concurrency: 8 }, + ); + }, +); + +/** + * Checks whether an Antigravity profile's `config/skills` slot actually sees the user's shared + * `~/.gemini/config/skills` directory. Returns false when the profile has a foreign symlink or + * non-empty local directory that shadows the user's folder, so Create never writes into a folder + * the selected profile ignores. + */ +const antigravityProfileSeesUserSkillsRoot = Effect.fn( + "otherProviderExtensions.antigravityProfileSeesUserSkillsRoot", +)(function* (profileDir: string | undefined, userSkillsRoot: string) { + if (!profileDir) return true; + return yield* antigravityProfileManagesSkillDir(profileDir, "config/skills", userSkillsRoot); +}); + +/** + * Resolves writable skill roots for non-Codex/Claude drivers that support creating/deleting skills. + * Returns `null` for providers that are read-only (Muse, fx, community ACP agents, external OpenCode, + * or Antigravity profiles whose `config/skills` does not point to the user's shared skills folder). + */ +export const resolveOtherProviderSkillRoots = Effect.fn( + "otherProviderExtensions.resolveOtherProviderSkillRoots", +)(function* (input: { + readonly instanceId: ProviderInstanceId; + readonly config: ProviderInstanceConfig; + readonly processEnv: NodeJS.ProcessEnv; + readonly projectCwd?: string | undefined; + readonly stateDir?: string | undefined; +}): Effect.fn.Return { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + if (input.config.driver === OPENCODE_DRIVER && isExternalOpenCodeConfig(input.config)) { + return null; + } + + const projectCwd = optionalText(input.projectCwd); + const repoRoot = projectCwd ? yield* findRepositoryRoot(projectCwd) : undefined; + const projectBoundary = repoRoot + ? yield* fileSystem.realPath(repoRoot).pipe(Effect.catch(() => Effect.succeed(repoRoot))) + : undefined; + + if (input.config.driver === ANTIGRAVITY_DRIVER) { + const userHome = antigravityUserHome(process.platform, input.processEnv, homedir()); + const userSkillsRoot = path.join(antigravityUserGeminiDir(userHome), "config", "skills"); + const profileDir = input.stateDir + ? antigravityInstancePaths(input.stateDir, String(input.instanceId)).profileDir + : undefined; + const canWriteUserRoot = yield* antigravityProfileSeesUserSkillsRoot( + profileDir, + userSkillsRoot, + ); + if (!canWriteUserRoot) return null; + const projectWritableRoots = projectCwd + ? [ + path.join(projectCwd, ".gemini", "skills"), + path.join(projectCwd, ".agents", "skills"), + path.join(projectCwd, ".agent", "skills"), + ] + : []; + return { + driver: input.config.driver, + userSkillsRoot, + userWritableRoots: [userSkillsRoot], + projectWritableRoots, + ...(projectBoundary ? { projectBoundary } : {}), + }; + } + + if (input.config.driver === GROK_DRIVER) { + const decoded = decodeGrokSettingsSafe(input.config); + if (!decoded) return null; + const grokHome = resolveGrokHome(decoded, input.processEnv, path); + const userSkillsRoot = path.join(grokHome, "skills"); + const projectWritableRoots = projectCwd + ? [ + path.join(projectCwd, ".grok", "skills"), + ...(repoRoot && normalizedPathKey(repoRoot) !== normalizedPathKey(projectCwd) + ? [path.join(repoRoot, ".grok", "skills")] + : []), + ] + : []; + return { + driver: input.config.driver, + userSkillsRoot, + userWritableRoots: [userSkillsRoot], + projectWritableRoots, + ...(projectBoundary ? { projectBoundary } : {}), + }; + } + + if (input.config.driver === CURSOR_DRIVER) { + const userSkillsRoot = path.join(environmentHome(input.processEnv), ".cursor", "skills"); + const projectWritableRoots = projectCwd + ? [path.join(projectCwd, ".cursor", "skills"), path.join(projectCwd, ".agents", "skills")] + : []; + return { + driver: input.config.driver, + userSkillsRoot, + userWritableRoots: [userSkillsRoot], + projectWritableRoots, + ...(projectBoundary ? { projectBoundary } : {}), + }; + } + + if (input.config.driver === OPENCODE_DRIVER) { + if (isExternalOpenCodeConfig(input.config)) return null; + const userSkillsRoot = path.join(openCodeConfigDir(input.processEnv), "skills"); + const projectWritableRoots = projectCwd + ? [path.join(projectCwd, ".opencode", "skills"), path.join(projectCwd, ".agents", "skills")] + : []; + return { + driver: input.config.driver, + userSkillsRoot, + userWritableRoots: [userSkillsRoot], + projectWritableRoots, + ...(projectBoundary ? { projectBoundary } : {}), + }; + } + + if (input.config.driver === PI_DRIVER) { + const userSkillsRoot = path.join(piAgentDir(input.processEnv), "skills"); + const projectWritableRoots = projectCwd + ? [path.join(projectCwd, ".pi", "skills"), path.join(projectCwd, ".agents", "skills")] + : []; + return { + driver: input.config.driver, + userSkillsRoot, + userWritableRoots: [userSkillsRoot], + projectWritableRoots, + ...(projectBoundary ? { projectBoundary } : {}), + }; + } + + return null; +}); + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +type JsonReadOutcome = + | { readonly kind: "missing" } + | { readonly kind: "unsafe"; readonly message: string } + | { readonly kind: "ok"; readonly doc: Record } + | { readonly kind: "error"; readonly message: string }; + +const readJsonFileSafe = Effect.fn("otherProviderExtensions.readJsonFileSafe")(function* ( + filePath: string, + confineBoundary?: string | undefined, +): Effect.fn.Return { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const exists = yield* fileSystem.exists(filePath).pipe(Effect.catch(() => Effect.succeed(false))); + if (!exists) return { kind: "missing" }; + if (confineBoundary) { + const real = yield* fileSystem + .realPath(filePath) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!real || !isPathWithinBoundary(path, confineBoundary, real)) { + return { + kind: "unsafe", + message: `${filePath} points outside the repository boundary.`, + }; + } + } + const contents = yield* fileSystem + .readFileString(filePath) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (contents === null) { + return { kind: "error", message: `Could not read ${filePath}.` }; + } + try { + const parsed: unknown = JSON.parse(contents); + return isRecord(parsed) + ? { kind: "ok", doc: parsed } + : { kind: "error", message: `${filePath} is not a JSON object.` }; + } catch { + return { kind: "error", message: `${filePath} contains invalid JSON.` }; + } +}); + +function parseCursorMcpConfig( + doc: Record, + originKind: "project" | "user", +): ProviderExtensionMcpServer[] { + const servers = doc.mcpServers; + if (!isRecord(servers)) return []; + const results: ProviderExtensionMcpServer[] = []; + for (const [rawName, rawEntry] of Object.entries(servers)) { + const name = optionalText(rawName); + if (!name || !isRecord(rawEntry)) continue; + const url = typeof rawEntry.url === "string" ? optionalText(rawEntry.url) : undefined; + const command = + typeof rawEntry.command === "string" ? optionalText(rawEntry.command) : undefined; + const args = Array.isArray(rawEntry.args) + ? rawEntry.args.filter((value): value is string => typeof value === "string") + : []; + const transport = url ? "http" : command ? "stdio" : undefined; + const detail = url ?? (command ? [command, ...args].join(" ") : undefined); + const disabled = rawEntry.disabled === true; + results.push({ + name, + origin: { kind: originKind }, + status: disabled ? "Disabled" : "Configured", + ...(transport ? { transport } : {}), + ...(detail ? { detail } : {}), + }); + } + return results; +} + +function parseOpenCodeMcpConfig( + doc: Record, + originKind: "project" | "user", +): ProviderExtensionMcpServer[] { + const servers = doc.mcp; + if (!isRecord(servers)) return []; + const results: ProviderExtensionMcpServer[] = []; + for (const [rawName, rawEntry] of Object.entries(servers)) { + const name = optionalText(rawName); + if (!name || !isRecord(rawEntry)) continue; + const url = typeof rawEntry.url === "string" ? optionalText(rawEntry.url) : undefined; + const commandParts = Array.isArray(rawEntry.command) + ? rawEntry.command.filter((value): value is string => typeof value === "string") + : typeof rawEntry.command === "string" + ? [rawEntry.command] + : []; + const type = typeof rawEntry.type === "string" ? rawEntry.type.trim().toLowerCase() : undefined; + const transport = + type === "remote" || url + ? "http" + : type === "local" || commandParts.length > 0 + ? "stdio" + : undefined; + const detail = url ?? (commandParts.length > 0 ? commandParts.join(" ") : undefined); + const disabled = rawEntry.enabled === false; + results.push({ + name, + origin: { kind: originKind }, + status: disabled ? "Disabled" : "Configured", + ...(transport ? { transport } : {}), + ...(detail ? { detail } : {}), + }); + } + return results; +} + +function dedupeMcpServers( + projectServers: ReadonlyArray, + userServers: ReadonlyArray, +): ProviderExtensionMcpServer[] { + const byName = new Map(); + for (const server of [...projectServers, ...userServers]) { + const key = server.name.toLowerCase(); + if (!byName.has(key)) byName.set(key, server); + } + return [...byName.values()].toSorted((left, right) => left.name.localeCompare(right.name)); +} + +const mapSnapshotSkillsForScope = Effect.fn("otherProviderExtensions.mapSnapshotSkillsForScope")( + function* (input: { + readonly snapshot: ServerProvider | undefined; + readonly projectCwd?: string | undefined; + readonly projectBoundary?: string | undefined; + readonly remote?: boolean; + }): Effect.fn.Return { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const rawSkills: ReadonlyArray = input.snapshot?.skills ?? []; + const results = yield* Effect.forEach( + rawSkills, + (skill) => + Effect.gen(function* () { + // Snapshot skills were probed against the server's startup cwd, so verify canonical + // containment before admitting project-scoped entries. + if (skill.scope?.trim().toLowerCase() === "project") { + if (!input.projectCwd || !input.projectBoundary) return null; + if (input.remote) return null; + const real = yield* fileSystem + .realPath(path.resolve(skill.path)) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!real || !isPathWithinBoundary(path, input.projectBoundary, real)) { + return null; + } + } + return { + name: skill.name, + path: skill.path, + ...(skill.displayName ? { displayName: skill.displayName } : {}), + ...(skill.description ? { description: skill.description } : {}), + ...(skill.shortDescription ? { shortDescription: skill.shortDescription } : {}), + ...(skill.enabled !== undefined ? { enabled: skill.enabled } : {}), + ...(skill.scope ? { scope: skill.scope } : {}), + source: input.remote ? "Remote server" : "Provider status", + ...(input.remote ? { canRead: false } : {}), + } satisfies ProviderExtensionSkill; + }), + { concurrency: 8 }, + ); + return results.filter((entry): entry is NonNullable => entry !== null); + }, +); + +function readOnlyCapabilities(overrides?: { + readonly mcpServers?: boolean; + readonly skillCreate?: boolean; +}): ProviderExtensionProviderCapabilities { + return { + plugins: false, + mcpServers: overrides?.mcpServers ?? false, + apps: false, + hooks: false, + skillCreate: overrides?.skillCreate ?? false, + }; +} + +export const readOtherProviderInventory = Effect.fn( + "otherProviderExtensions.readOtherProviderInventory", +)(function* (input: { + readonly instanceId: ProviderInstanceId; + readonly config: ProviderInstanceConfig; + readonly snapshot: ServerProvider | undefined; + readonly processEnv: NodeJS.ProcessEnv; + readonly projectCwd?: string | undefined; + readonly stateDir?: string | undefined; +}): Effect.fn.Return { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const base = { + instanceId: input.instanceId, + driver: input.config.driver, + displayName: input.config.displayName ?? input.snapshot?.displayName, + }; + + if (!resolveOtherProviderEnabled(input.config, input.snapshot)) { + return { + ...base, + status: "disabled", + message: "Provider is disabled.", + capabilities: readOnlyCapabilities(), + plugins: [], + marketplaces: [], + skills: [], + mcpServers: [], + apps: [], + }; + } + + // External OpenCode instances must stay strictly metadata-only without touching local disk or `.git`. + if (input.config.driver === OPENCODE_DRIVER && isExternalOpenCodeConfig(input.config)) { + const skills = yield* mapSnapshotSkillsForScope({ + snapshot: input.snapshot, + remote: true, + }); + return { + ...base, + status: "ready", + capabilities: readOnlyCapabilities({ mcpServers: false, skillCreate: false }), + plugins: [], + marketplaces: [], + skills, + mcpServers: [], + apps: [], + }; + } + + const projectCwd = optionalText(input.projectCwd); + const repoRoot = projectCwd ? yield* findRepositoryRoot(projectCwd) : undefined; + const projectBoundary = repoRoot + ? yield* fileSystem.realPath(repoRoot).pipe(Effect.catch(() => Effect.succeed(repoRoot))) + : undefined; + const writableRoots = yield* resolveOtherProviderSkillRoots({ + instanceId: input.instanceId, + config: input.config, + processEnv: input.processEnv, + projectCwd, + stateDir: input.stateDir, + }); + + if (input.config.driver === ANTIGRAVITY_DRIVER) { + const userHome = antigravityUserHome(process.platform, input.processEnv, homedir()); + const geminiDir = antigravityUserGeminiDir(userHome); + const profileDir = input.stateDir + ? antigravityInstancePaths(input.stateDir, String(input.instanceId)).profileDir + : undefined; + const profileExists = profileDir + ? yield* fileSystem.stat(profileDir).pipe( + Effect.map((stat) => stat.type === "Directory"), + Effect.catch(() => Effect.succeed(false)), + ) + : false; + + const [directUserSkills, managesConfigSkills, managesCliSkills, disabledByDir] = + yield* Effect.all([ + listAntigravityDirectUserSkills(userHome), + antigravityProfileManagesSkillDir( + profileDir, + "config/skills", + path.join(geminiDir, "config", "skills"), + ), + antigravityProfileManagesSkillDir( + profileDir, + "antigravity-cli/skills", + path.join(geminiDir, "antigravity-cli", "skills"), + ), + profileDir + ? Effect.promise(() => readAntigravityDisabledSkills(profileDir)) + : Effect.succeed>>>({ + "config/skills": [], + "antigravity-cli/skills": [], + }), + ]); + + const manageableSharedDirs = new Set(); + if (profileDir && managesConfigSkills) manageableSharedDirs.add("config/skills"); + if (profileDir && managesCliSkills) manageableSharedDirs.add("antigravity-cli/skills"); + + const disabledKeys = new Set(); + for (const sharedDir of ["config/skills", "antigravity-cli/skills"] as const) { + for (const entryName of disabledByDir[sharedDir]) { + disabledKeys.add(`${sharedDir}\0${entryName}`); + } + } + + const directByDiscovered = new Map( + directUserSkills.map((entry) => [normalizedPathKey(entry.discoveredSkillPath), entry]), + ); + const directByReal = new Map>(); + for (const entry of directUserSkills) { + const key = normalizedPathKey(entry.realSkillPath); + const list = directByReal.get(key); + if (list) list.push(entry); + else directByReal.set(key, [entry]); + } + + const antigravityToggleNotice = + "Applies inside Threadlines only. Terminal agy sessions still load ~/.gemini/config/skills."; + + const enrichAntigravitySkill = (skill: ProviderExtensionSkill): ProviderExtensionSkill => { + let direct = directByDiscovered.get(normalizedPathKey(skill.path)); + if (!direct && skill.scope === "user") { + const candidates = directByReal.get(normalizedPathKey(skill.path)) ?? []; + // Prefer an enabled non-symlink entry matching the skill's name/folder when `AntigravitySkills` + // normalized `skill.path` to `realpath` (e.g. symlinked `~/.gemini/config/skills -> dotfiles`). + direct = + candidates.find( + (candidate) => + !disabledKeys.has(`${candidate.sharedDir}\0${candidate.entryName}`) && + candidate.entryName.toLowerCase() === skill.name.trim().toLowerCase(), + ) ?? + candidates.find( + (candidate) => !disabledKeys.has(`${candidate.sharedDir}\0${candidate.entryName}`), + ) ?? + candidates[0]; + } + if (!direct) return skill; + const canToggle = manageableSharedDirs.has(direct.sharedDir); + const hasDifferentTarget = + normalizedPathKey(direct.realSkillPath) !== normalizedPathKey(direct.discoveredSkillPath); + return { + ...skill, + path: direct.discoveredSkillPath, + ...(hasDifferentTarget ? { resolvedPath: direct.realSkillPath } : {}), + ...(canToggle ? { canToggle: true, toggleNotice: antigravityToggleNotice } : {}), + }; + }; + + let skills: ProviderExtensionSkill[]; + if (profileDir && profileExists) { + const listed = yield* antigravitySkillsLister({ + cwd: projectCwd ?? homedir(), + profileDir, + includeProject: projectCwd !== undefined, + }); + skills = listed.map((skill) => + enrichAntigravitySkill({ + name: skill.name, + path: skill.path, + ...(skill.displayName ? { displayName: skill.displayName } : {}), + ...(skill.description ? { description: skill.description } : {}), + ...(skill.shortDescription ? { shortDescription: skill.shortDescription } : {}), + enabled: skill.enabled ?? true, + ...(skill.scope ? { scope: skill.scope } : {}), + source: skill.scope === "project" ? "Project" : "Antigravity profile", + }), + ); + } else { + const roots: ScannedSkillRoot[] = [ + ...(projectCwd + ? [ + { + root: path.join(projectCwd, ".gemini", "skills"), + scope: "project" as const, + source: "Project (.gemini/skills)", + priority: 30, + confineToProject: true, + }, + { + root: path.join(projectCwd, ".agents", "skills"), + scope: "project" as const, + source: "Project (.agents/skills)", + priority: 20, + confineToProject: true, + }, + { + root: path.join(projectCwd, ".agent", "skills"), + scope: "project" as const, + source: "Project (.agent/skills)", + priority: 15, + confineToProject: true, + }, + ] + : []), + { + root: path.join(geminiDir, "config", "skills"), + scope: "user", + source: "Antigravity user", + priority: 10, + }, + { + root: path.join(geminiDir, "antigravity-cli", "skills"), + scope: "user", + source: "Antigravity CLI", + priority: 5, + }, + ]; + const scanned = yield* Effect.forEach(roots, (root) => scanSkillRoot(root, projectBoundary), { + concurrency: 4, + }); + skills = dedupeSkillsByPriority(scanned.flat()).map((skill) => enrichAntigravitySkill(skill)); + } + + // Surface profile-disabled personal skills so the user can see them and re-enable them. + const existingPaths = new Set(skills.map((skill) => normalizedPathKey(skill.path))); + const disabledEntries = directUserSkills.filter( + (entry) => + disabledKeys.has(`${entry.sharedDir}\0${entry.entryName}`) && + !existingPaths.has(normalizedPathKey(entry.discoveredSkillPath)), + ); + if (disabledEntries.length > 0) { + const disabledSkills = yield* Effect.forEach( + disabledEntries, + (entry) => + Effect.gen(function* () { + const stat = yield* fileSystem + .stat(entry.discoveredSkillPath) + .pipe(Effect.catch(() => Effect.succeed(null))); + let name = entry.entryName; + let description: string | undefined; + if (stat?.type === "File" && Number(stat.size) <= MAX_SKILL_FILE_BYTES) { + const contents = yield* fileSystem + .readFileString(entry.discoveredSkillPath) + .pipe(Effect.catch(() => Effect.succeed(""))); + const fm = parseFrontMatterFields(contents); + if (fm.name) name = fm.name; + description = fm.description ?? firstMarkdownParagraph(contents); + } + const hasDifferentTarget = + normalizedPathKey(entry.realSkillPath) !== + normalizedPathKey(entry.discoveredSkillPath); + const canToggle = manageableSharedDirs.has(entry.sharedDir); + return { + name, + path: entry.discoveredSkillPath, + enabled: false, + scope: "user", + source: + entry.sharedDir === "config/skills" ? "Antigravity profile" : "Antigravity CLI", + ...(description ? { description } : {}), + ...(hasDifferentTarget ? { resolvedPath: entry.realSkillPath } : {}), + ...(canToggle ? { canToggle: true, toggleNotice: antigravityToggleNotice } : {}), + } satisfies ProviderExtensionSkill; + }), + { concurrency: 8 }, + ); + skills = [...skills, ...disabledSkills].toSorted((left, right) => + left.name.localeCompare(right.name), + ); + } + + // When a sibling skill's `SKILL.md` is symlinked to another skill's regular file, never allow + // Delete on any entry sharing that realpath so deleting cannot remove a sibling folder. + const symlinkedRealTargets = new Set( + directUserSkills + .filter((entry) => entry.isEntryOrFileSymlink) + .map((entry) => normalizedPathKey(entry.realSkillPath)), + ); + const annotatedSkills = (yield* annotateDeletableSkills(skills, writableRoots)).map((skill) => { + const direct = directByDiscovered.get(normalizedPathKey(skill.path)); + if ( + direct?.isEntryOrFileSymlink || + symlinkedRealTargets.has(normalizedPathKey(skill.resolvedPath ?? skill.path)) + ) { + const { canDelete: _ignored, ...rest } = skill; + return rest; + } + return skill; + }); + return { + ...base, + status: "ready", + capabilities: readOnlyCapabilities({ skillCreate: writableRoots !== null }), + plugins: [], + marketplaces: [], + skills: annotatedSkills, + mcpServers: [], + apps: [], + }; + } + + if (input.config.driver === GROK_DRIVER) { + const decoded = decodeGrokSettingsSafe(input.config); + const mainGrokHome = grokMainHome(input.processEnv); + const grokHome = decoded ? resolveGrokHome(decoded, input.processEnv, path) : mainGrokHome; + const grokConfigPath = path.join(grokHome, "config.toml"); + const home = environmentHome(input.processEnv); + const roots: ScannedSkillRoot[] = [ + ...(projectCwd + ? [ + { + root: path.join(projectCwd, ".grok", "skills"), + scope: "project" as const, + source: "Project (.grok/skills)", + priority: 30, + confineToProject: true, + }, + ...(repoRoot && normalizedPathKey(repoRoot) !== normalizedPathKey(projectCwd) + ? [ + { + root: path.join(repoRoot, ".grok", "skills"), + scope: "project" as const, + source: "Repository (.grok/skills)", + priority: 20, + confineToProject: true, + }, + ] + : []), + ] + : []), + { + root: path.join(grokHome, "skills"), + scope: "user", + source: "Grok user", + priority: 10, + }, + { + root: path.join(home, ".claude", "skills"), + scope: "user", + source: "Claude user (shared with Grok)", + priority: 5, + }, + ]; + const [scanned, ignoreState] = yield* Effect.all([ + Effect.forEach(roots, (root) => scanSkillRoot(root, projectBoundary), { concurrency: 4 }), + readGrokIgnoreState({ + grokHome, + mainGrokHome, + environment: input.processEnv, + }), + ]); + + const sortedEntries = scanned.flat().toSorted((left, right) => right.priority - left.priority); + const seenActiveNames = new Set(); + const seenPaths = new Set(); + const mergedGrokSkills: Array = []; + for (const entry of sortedEntries) { + const pathKey = normalizedPathKey(entry.skill.path); + if (seenPaths.has(pathKey)) continue; + const dirKey = normalizedPathKey(path.dirname(entry.skill.path)); + const resolvedDirKey = entry.skill.resolvedPath + ? normalizedPathKey(path.dirname(entry.skill.resolvedPath)) + : dirKey; + const ignored = + ignoreState.resolvedKeys.has(dirKey) || ignoreState.resolvedKeys.has(resolvedDirKey); + const nameKey = entry.skill.name.trim().toLowerCase(); + if (!ignored) { + if (seenActiveNames.has(nameKey)) continue; + seenActiveNames.add(nameKey); + } + seenPaths.add(pathKey); + mergedGrokSkills.push({ + ...entry.skill, + enabled: !ignored, + canToggle: true, + configPath: grokConfigPath, + ...(ignoreState.sharesMainConfig + ? { toggleNotice: "Shared with your main Grok config.toml." } + : {}), + }); + } + mergedGrokSkills.sort((left, right) => left.name.localeCompare(right.name)); + + const skills = yield* annotateDeletableSkills(mergedGrokSkills, writableRoots); + return { + ...base, + status: "ready", + capabilities: readOnlyCapabilities({ skillCreate: writableRoots !== null }), + plugins: [], + marketplaces: [], + skills, + mcpServers: [], + apps: [], + }; + } + + if (input.config.driver === CURSOR_DRIVER) { + const home = environmentHome(input.processEnv); + const cursorHome = path.join(home, ".cursor"); + const roots: ScannedSkillRoot[] = [ + ...(projectCwd + ? [ + { + root: path.join(projectCwd, ".cursor", "skills"), + scope: "project" as const, + source: "Project (.cursor/skills)", + priority: 30, + confineToProject: true, + }, + { + root: path.join(projectCwd, ".agents", "skills"), + scope: "project" as const, + source: "Project (.agents/skills)", + priority: 20, + confineToProject: true, + }, + ] + : []), + { + root: path.join(cursorHome, "skills"), + scope: "user", + source: "Cursor user", + priority: 10, + }, + { + root: path.join(cursorHome, "skills-cursor"), + scope: "system", + source: "Cursor built-in", + priority: 5, + }, + ]; + const [scanned, projectMcpResult, userMcpResult] = yield* Effect.all( + [ + Effect.forEach(roots, (root) => scanSkillRoot(root, projectBoundary), { concurrency: 4 }), + projectCwd && normalizedPathKey(projectCwd) !== normalizedPathKey(home) + ? readJsonFileSafe(path.join(projectCwd, ".cursor", "mcp.json"), projectBoundary) + : Effect.succeed({ kind: "missing" }), + readJsonFileSafe(path.join(cursorHome, "mcp.json")), + ], + { concurrency: "unbounded" }, + ); + const skills = yield* annotateDeletableSkills( + dedupeSkillsByPriority(scanned.flat()), + writableRoots, + ); + const mcpServers = dedupeMcpServers( + projectMcpResult.kind === "ok" ? parseCursorMcpConfig(projectMcpResult.doc, "project") : [], + userMcpResult.kind === "ok" ? parseCursorMcpConfig(userMcpResult.doc, "user") : [], + ); + const mcpErrors = [projectMcpResult, userMcpResult].flatMap((entry) => + entry.kind === "error" ? [entry.message] : [], + ); + return { + ...base, + status: "ready", + capabilities: readOnlyCapabilities({ mcpServers: true, skillCreate: writableRoots !== null }), + plugins: [], + marketplaces: [], + skills, + mcpServers, + mcpServersStatus: mcpErrors.length > 0 && mcpServers.length === 0 ? "error" : "ready", + ...(mcpErrors.length > 0 ? { mcpServersMessage: mcpErrors.join(" ") } : {}), + apps: [], + }; + } + + if (input.config.driver === OPENCODE_DRIVER) { + if (isExternalOpenCodeConfig(input.config)) { + const skills = yield* mapSnapshotSkillsForScope({ + snapshot: input.snapshot, + projectCwd, + projectBoundary, + remote: true, + }); + return { + ...base, + status: "ready", + capabilities: readOnlyCapabilities({ mcpServers: false, skillCreate: false }), + plugins: [], + marketplaces: [], + skills, + mcpServers: [], + apps: [], + }; + } + + const home = environmentHome(input.processEnv); + const configDir = openCodeConfigDir(input.processEnv); + const roots: ScannedSkillRoot[] = [ + ...(projectCwd + ? [ + { + root: path.join(projectCwd, ".opencode", "skills"), + scope: "project" as const, + source: "Project (.opencode/skills)", + priority: 30, + confineToProject: true, + }, + { + root: path.join(projectCwd, ".agents", "skills"), + scope: "project" as const, + source: "Project (.agents/skills)", + priority: 20, + confineToProject: true, + }, + ] + : []), + { + root: path.join(configDir, "skills"), + scope: "user", + source: "OpenCode user", + priority: 10, + }, + { + root: path.join(home, ".agents", "skills"), + scope: "user", + source: "Shared user (.agents/skills)", + priority: 5, + }, + ]; + const userConfigPath = path.join(configDir, "opencode.json"); + const projectConfigPath = projectCwd ? path.join(projectCwd, "opencode.json") : undefined; + const [scanned, projectConfigResult, userConfigResult, realUserConfigPath] = yield* Effect.all( + [ + Effect.forEach(roots, (root) => scanSkillRoot(root, projectBoundary), { concurrency: 4 }), + projectConfigPath + ? readJsonFileSafe(projectConfigPath, projectBoundary) + : Effect.succeed({ kind: "missing" }), + readJsonFileSafe(userConfigPath), + fileSystem.realPath(userConfigPath).pipe(Effect.catch(() => Effect.succeed(null))), + ], + { concurrency: "unbounded" }, + ); + const userConfigPointsIntoProject = + projectBoundary !== undefined && + realUserConfigPath !== null && + isPathWithinBoundary(path, projectBoundary, realUserConfigPath); + const policyAnnotatedSkills = dedupeSkillsByPriority(scanned.flat()).map((skill) => { + const projectEffect = + projectConfigResult.kind === "ok" + ? evaluateOpenCodeSkillPolicy(projectConfigResult.doc, skill.name) + : undefined; + const userEffect = + userConfigResult.kind === "ok" + ? evaluateOpenCodeSkillPolicy(userConfigResult.doc, skill.name) + : undefined; + + if (projectEffect === "deny" && projectConfigPath) { + return { + ...skill, + enabled: false, + configPath: projectConfigPath, + toggleNotice: "Disabled by this project's opencode.json. Open config to change it.", + }; + } + if (projectEffect === "allow" && projectConfigPath) { + return { + ...skill, + enabled: true, + configPath: projectConfigPath, + toggleNotice: "Enabled by this project's opencode.json. Open config to change it.", + }; + } + if (userConfigResult.kind === "error") { + return { + ...skill, + enabled: true, + configPath: userConfigPath, + toggleNotice: "Fix invalid JSON in opencode.json before toggling skills.", + }; + } + if (userConfigPointsIntoProject) { + return { + ...skill, + enabled: userEffect !== "deny", + configPath: userConfigPath, + toggleNotice: + "User opencode.json links into this repository. Open config to edit it directly.", + }; + } + if (hasOpenCodePolicyWildcard(skill.name)) { + return { + ...skill, + enabled: userEffect !== "deny", + configPath: userConfigPath, + toggleNotice: + "Skills with wildcard characters in their name cannot be toggled safely via opencode.json.", + }; + } + return { + ...skill, + enabled: userEffect !== "deny", + canToggle: true, + configPath: userConfigPath, + }; + }); + const skills = yield* annotateDeletableSkills(policyAnnotatedSkills, writableRoots); + const mcpServers = dedupeMcpServers( + projectConfigResult.kind === "ok" + ? parseOpenCodeMcpConfig(projectConfigResult.doc, "project") + : [], + userConfigResult.kind === "ok" ? parseOpenCodeMcpConfig(userConfigResult.doc, "user") : [], + ); + const mcpErrors = [projectConfigResult, userConfigResult].flatMap((entry) => + entry.kind === "error" || entry.kind === "unsafe" ? [entry.message] : [], + ); + return { + ...base, + status: "ready", + capabilities: readOnlyCapabilities({ mcpServers: true, skillCreate: writableRoots !== null }), + plugins: [], + marketplaces: [], + skills, + mcpServers, + mcpServersStatus: mcpErrors.length > 0 && mcpServers.length === 0 ? "error" : "ready", + ...(mcpErrors.length > 0 ? { mcpServersMessage: mcpErrors.join(" ") } : {}), + apps: [], + }; + } + + if (input.config.driver === PI_DRIVER) { + const home = environmentHome(input.processEnv); + const agentDir = piAgentDir(input.processEnv); + const roots: ScannedSkillRoot[] = [ + ...(projectCwd + ? [ + { + root: path.join(projectCwd, ".pi", "skills"), + scope: "project" as const, + source: "Project (.pi/skills)", + priority: 30, + confineToProject: true, + }, + { + root: path.join(projectCwd, ".agents", "skills"), + scope: "project" as const, + source: "Project (.agents/skills)", + priority: 20, + confineToProject: true, + }, + ] + : []), + { + root: path.join(agentDir, "skills"), + scope: "user", + source: "Pi user", + priority: 10, + }, + { + root: path.join(home, ".agents", "skills"), + scope: "user", + source: "Shared user (.agents/skills)", + priority: 5, + }, + ]; + const [scanned, snapshotSkills] = yield* Effect.all( + [ + Effect.forEach(roots, (root) => scanSkillRoot(root, projectBoundary), { concurrency: 4 }), + mapSnapshotSkillsForScope({ + snapshot: input.snapshot, + projectCwd, + projectBoundary, + }), + ], + { concurrency: "unbounded" }, + ); + // Include Pi `--skill` launch-arg skills from the live snapshot at lower priority than direct + // disk discovery so custom paths still appear in Settings without leaking out-of-scope project skills. + const merged = dedupeSkillsByPriority([ + ...scanned.flat(), + ...snapshotSkills.map((skill) => ({ skill, priority: 1 })), + ]); + const skills = yield* annotateDeletableSkills(merged, writableRoots); + return { + ...base, + status: "ready", + capabilities: readOnlyCapabilities({ skillCreate: writableRoots !== null }), + plugins: [], + marketplaces: [], + skills, + mcpServers: [], + apps: [], + }; + } + + // Muse, fx, and community ACP agents: never guess disk paths; surface only safe snapshot skills. + const skills = yield* mapSnapshotSkillsForScope({ + snapshot: input.snapshot, + projectCwd, + projectBoundary, + }); + return { + ...base, + status: "ready", + capabilities: readOnlyCapabilities(), + plugins: [], + marketplaces: [], + skills, + mcpServers: [], + apps: [], + }; +}); + +/** + * Revalidates a skill toggle request against the live inventory for `(instanceId, projectCwd)` + * and applies the provider-appropriate native or profile-level toggle. + */ +export const setOtherProviderSkillEnabled = Effect.fn( + "otherProviderExtensions.setOtherProviderSkillEnabled", +)(function* (input: { + readonly instanceId: ProviderInstanceId; + readonly config: ProviderInstanceConfig; + readonly snapshot: ServerProvider | undefined; + readonly processEnv: NodeJS.ProcessEnv; + readonly projectCwd?: string | undefined; + readonly stateDir?: string | undefined; + readonly skillPath: string; + readonly enabled: boolean; +}): Effect.fn.Return { + const path = yield* Path.Path; + const inventory = yield* readOtherProviderInventory({ + instanceId: input.instanceId, + config: input.config, + snapshot: input.snapshot, + processEnv: input.processEnv, + projectCwd: input.projectCwd, + stateDir: input.stateDir, + }); + if (inventory.status !== "ready") { + return yield* Effect.fail(inventory.message ?? "Provider is not ready."); + } + + const requestedKey = normalizedPathKey(path.resolve(input.skillPath)); + const matched = + inventory.skills.find( + (skill) => normalizedPathKey(path.resolve(skill.path)) === requestedKey, + ) ?? + (() => { + const byResolved = inventory.skills.filter( + (skill) => + skill.resolvedPath !== undefined && + normalizedPathKey(path.resolve(skill.resolvedPath)) === requestedKey, + ); + return byResolved.length === 1 ? byResolved[0] : undefined; + })(); + + if (!matched) { + return yield* Effect.fail("That skill is not in this provider's current scope."); + } + if (matched.canToggle !== true) { + return yield* Effect.fail( + matched.toggleNotice ?? + `${inventory.displayName ?? input.config.driver} does not support toggling this skill here.`, + ); + } + + if (input.config.driver === GROK_DRIVER) { + const decoded = decodeGrokSettingsSafe(input.config); + const mainGrokHome = grokMainHome(input.processEnv); + const grokHome = decoded ? resolveGrokHome(decoded, input.processEnv, path) : mainGrokHome; + yield* writeGrokSkillToggle({ + grokHome, + mainGrokHome, + skillPath: matched.path, + enabled: input.enabled, + environment: input.processEnv, + }); + return input.enabled; + } + + if (input.config.driver === OPENCODE_DRIVER) { + if (isExternalOpenCodeConfig(input.config)) { + return yield* Effect.fail("Remote OpenCode skills cannot be toggled from this machine."); + } + const fileSystem = yield* FileSystem.FileSystem; + const projectCwd = optionalText(input.projectCwd); + const repoRoot = projectCwd ? yield* findRepositoryRoot(projectCwd) : undefined; + const projectBoundary = repoRoot + ? yield* fileSystem.realPath(repoRoot).pipe(Effect.catch(() => Effect.succeed(repoRoot))) + : undefined; + const userConfigPath = path.join(openCodeConfigDir(input.processEnv), "opencode.json"); + yield* writeOpenCodeSkillToggle({ + userConfigPath, + skillName: matched.name, + enabled: input.enabled, + forbiddenBoundary: projectBoundary, + }); + // Re-read inventory to verify effective state (e.g. a project config cannot be overridden). + const after = yield* readOtherProviderInventory({ + instanceId: input.instanceId, + config: input.config, + snapshot: input.snapshot, + processEnv: input.processEnv, + projectCwd: input.projectCwd, + stateDir: input.stateDir, + }); + const refreshed = after.skills.find( + (skill) => + normalizedPathKey(path.resolve(skill.path)) === + normalizedPathKey(path.resolve(matched.path)), + ); + return refreshed?.enabled ?? input.enabled; + } + + if (input.config.driver === ANTIGRAVITY_DRIVER) { + if (!input.stateDir) { + return yield* Effect.fail("Antigravity profile state directory is unavailable."); + } + const userHome = antigravityUserHome(process.platform, input.processEnv, homedir()); + const profileDir = antigravityInstancePaths( + input.stateDir, + String(input.instanceId), + ).profileDir; + const directEntries = yield* listAntigravityDirectUserSkills(userHome); + const matchedKey = normalizedPathKey(path.resolve(matched.path)); + const entry = directEntries.find( + (candidate) => normalizedPathKey(path.resolve(candidate.discoveredSkillPath)) === matchedKey, + ); + if (!entry) { + return yield* Effect.fail("Only personal Antigravity skills can be toggled here."); + } + yield* writeAntigravitySkillToggle({ + profileDir, + userHome, + stateDir: input.stateDir, + sharedDir: entry.sharedDir, + entryName: entry.entryName, + enabled: input.enabled, + }); + return input.enabled; + } + + return yield* Effect.fail( + `${inventory.displayName ?? input.config.driver} does not support toggling individual skills here.`, + ); +}); + +/** Re-syncs profile links after creating or deleting a user skill on profile-managed providers. */ +export const syncOtherProviderAfterSkillMutation = Effect.fn( + "otherProviderExtensions.syncOtherProviderAfterSkillMutation", +)(function* (input: { + readonly instanceId: ProviderInstanceId; + readonly config: ProviderInstanceConfig; + readonly processEnv: NodeJS.ProcessEnv; + readonly stateDir?: string | undefined; +}): Effect.fn.Return { + if (input.config.driver !== ANTIGRAVITY_DRIVER || !input.stateDir) return; + const userHome = antigravityUserHome(process.platform, input.processEnv, homedir()); + const profileDir = antigravityInstancePaths(input.stateDir, String(input.instanceId)).profileDir; + yield* syncAntigravityProfileAfterSkillMutation({ + profileDir, + userHome, + stateDir: input.stateDir, + }); +}); diff --git a/apps/server/src/provider/otherProviderSkillToggles.ts b/apps/server/src/provider/otherProviderSkillToggles.ts new file mode 100644 index 000000000..1c8455769 --- /dev/null +++ b/apps/server/src/provider/otherProviderSkillToggles.ts @@ -0,0 +1,884 @@ +/** + * Native and profile-level skill toggle helpers for non-Codex/Claude providers: + * - Grok: format-preserving `[skills] ignore` edits in `/config.toml` + * - Local OpenCode: `policies` (`action: "skill.use"`) evaluation and edits in `opencode.json` + * - Antigravity: profile-level per-skill disable sync via `AntigravityUserConfig` + * + * @module provider/otherProviderSkillToggles + */ +import { randomBytes } from "node:crypto"; +import * as fs from "node:fs/promises"; +import { homedir } from "node:os"; +import * as Effect from "effect/Effect"; +import * as Path from "effect/Path"; + +import { expandHomePath } from "../pathExpansion.ts"; +import { + ANTIGRAVITY_SKILL_DIRS, + type AntigravitySkillDir, + isAntigravitySplitSkillDir, + setAntigravitySkillDisabled, + shareAntigravityUserConfigNow, +} from "./antigravity/AntigravityUserConfig.ts"; +import { antigravityUserGeminiDir } from "./antigravity/AntigravityUserConfig.ts"; + +function normalizedPathKey(filePath: string): string { + const normalized = filePath.replaceAll("\\", "/").replace(/\/+$/, ""); + return process.platform === "win32" ? normalized.toLowerCase() : normalized; +} + +function environmentHome(environment: NodeJS.ProcessEnv): string { + const home = + process.platform === "win32" + ? environment.USERPROFILE?.trim() || environment.HOME?.trim() + : environment.HOME?.trim() || environment.USERPROFILE?.trim(); + return home || homedir(); +} + +function expandPathWithEnv(raw: string, environment: NodeJS.ProcessEnv): string { + const trimmed = raw.trim(); + if (trimmed === "~") return environmentHome(environment); + if (trimmed.startsWith("~/") || trimmed.startsWith("~\\")) { + return `${environmentHome(environment)}${trimmed.slice(1)}`; + } + return expandHomePath(trimmed); +} + +/** + * Strips a `#` comment outside single/double-quoted TOML strings on a single line. + */ +function stripTomlComment(line: string): string { + let inSingle = false; + let inDouble = false; + let escaped = false; + for (let i = 0; i < line.length; i += 1) { + const ch = line[i]!; + if (inDouble) { + if (escaped) { + escaped = false; + } else if (ch === "\\") { + escaped = true; + } else if (ch === '"') { + inDouble = false; + } + continue; + } + if (inSingle) { + if (ch === "'") inSingle = false; + continue; + } + if (ch === '"') inDouble = true; + else if (ch === "'") inSingle = true; + else if (ch === "#") return line.slice(0, i); + } + return line; +} + +/** + * Parses a TOML table header line (after comment stripping), returning the normalized table name + * or `null` when the line is not a `[table]` / `[[array]]` header. + */ +function parseTomlTableHeader(strippedLine: string): string | null { + const trimmed = strippedLine.trim(); + if (!trimmed.startsWith("[")) return null; + if (trimmed.startsWith("[[")) { + if (!trimmed.endsWith("]]")) return null; + return trimmed.slice(2, -2).trim(); + } + if (!trimmed.endsWith("]")) return null; + return trimmed.slice(1, -1).trim(); +} + +function decodeTomlBasicString(inner: string): string { + let out = ""; + for (let i = 0; i < inner.length; i += 1) { + const ch = inner[i]!; + if (ch !== "\\" || i + 1 >= inner.length) { + out += ch; + continue; + } + const next = inner[i + 1]!; + i += 1; + switch (next) { + case "b": + out += "\b"; + break; + case "t": + out += "\t"; + break; + case "n": + out += "\n"; + break; + case "f": + out += "\f"; + break; + case "r": + out += "\r"; + break; + case '"': + out += '"'; + break; + case "\\": + out += "\\"; + break; + case "u": { + const hex = inner.slice(i + 1, i + 5); + if (/^[0-9a-fA-F]{4}$/.test(hex)) { + out += String.fromCodePoint(Number.parseInt(hex, 16)); + i += 4; + } else { + out += `\\u${hex}`; + i += hex.length; + } + break; + } + case "U": { + const hex = inner.slice(i + 1, i + 9); + if (/^[0-9a-fA-F]{8}$/.test(hex)) { + out += String.fromCodePoint(Number.parseInt(hex, 16)); + i += 8; + } else { + out += `\\U${hex}`; + i += hex.length; + } + break; + } + default: + out += next; + break; + } + } + return out; +} + +/** + * Parses a TOML string array literal (everything between `[` and the matching `]`). + * Returns `null` when the slice does not close with `]` or contains unparseable tokens. + */ +function parseTomlStringArray(raw: string): { + readonly values: Array; + readonly endIndex: number; +} | null { + let i = 0; + while (i < raw.length && /\s/.test(raw[i]!)) i += 1; + if (raw[i] !== "[") return null; + i += 1; + const values: Array = []; + while (i < raw.length) { + // Skip whitespace, commas, and inline comments. + while (i < raw.length) { + const ch = raw[i]!; + if (/\s/.test(ch) || ch === ",") { + i += 1; + continue; + } + if (ch === "#") { + while (i < raw.length && raw[i] !== "\n") i += 1; + continue; + } + break; + } + if (i >= raw.length) return null; + if (raw[i] === "]") { + return { values, endIndex: i + 1 }; + } + if (raw[i] === "'") { + i += 1; + const start = i; + while (i < raw.length && raw[i] !== "'" && raw[i] !== "\n") i += 1; + if (raw[i] !== "'") return null; + values.push(raw.slice(start, i)); + i += 1; + continue; + } + if (raw[i] === '"') { + i += 1; + const start = i; + let escaped = false; + while (i < raw.length) { + const ch = raw[i]!; + if (escaped) { + escaped = false; + } else if (ch === "\\") { + escaped = true; + } else if (ch === '"') { + break; + } else if (ch === "\n") { + return null; + } + i += 1; + } + if (raw[i] !== '"') return null; + values.push(decodeTomlBasicString(raw.slice(start, i))); + i += 1; + continue; + } + return null; + } + return null; +} + +interface GrokSkillsSectionMatch { + readonly sectionStart: number; + readonly sectionEnd: number; + readonly ignoreValueStart?: number; + readonly ignoreValueEnd?: number; + readonly ignoreValues: Array; +} + +function findGrokSkillsSection(tomlText: string): GrokSkillsSectionMatch | null { + const lineStarts: Array = [0]; + for (let i = 0; i < tomlText.length; i += 1) { + if (tomlText[i] === "\n") lineStarts.push(i + 1); + } + const lines = tomlText.split("\n"); + + let skillsHeaderLine = -1; + let nextHeaderLine = lines.length; + for (let idx = 0; idx < lines.length; idx += 1) { + const header = parseTomlTableHeader(stripTomlComment(lines[idx]!)); + if (header === null) continue; + if (skillsHeaderLine === -1) { + if (header === "skills" || header === '"skills"' || header === "'skills'") { + skillsHeaderLine = idx; + } + } else { + nextHeaderLine = idx; + break; + } + } + if (skillsHeaderLine === -1) return null; + + const sectionStart = lineStarts[skillsHeaderLine]!; + const sectionEnd = + nextHeaderLine < lineStarts.length ? lineStarts[nextHeaderLine]! : tomlText.length; + + for (let idx = skillsHeaderLine + 1; idx < nextHeaderLine; idx += 1) { + const stripped = stripTomlComment(lines[idx]!); + const keyMatch = stripped.match(/^\s*(?:ignore|"ignore"|'ignore')\s*=\s*/); + if (!keyMatch) continue; + const valueStart = lineStarts[idx]! + keyMatch[0].length; + const parsed = parseTomlStringArray(tomlText.slice(valueStart, sectionEnd)); + if (!parsed) { + // Unparseable ignore value — report match without bounds so caller refuses to clobber it. + return { + sectionStart, + sectionEnd, + ignoreValues: [], + }; + } + return { + sectionStart, + sectionEnd, + ignoreValueStart: valueStart, + ignoreValueEnd: valueStart + parsed.endIndex, + ignoreValues: parsed.values, + }; + } + + return { + sectionStart, + sectionEnd, + ignoreValues: [], + }; +} + +/** Reads `[skills] ignore = [...]` entries from a Grok `config.toml` document. */ +export function parseGrokSkillsIgnore(tomlText: string): Array { + return findGrokSkillsSection(tomlText)?.ignoreValues ?? []; +} + +function encodeTomlString(value: string): string { + // Use TOML literal strings for Windows-style paths containing backslashes (recommended in Grok's + // own docs) whenever safe; otherwise fall back to standard double-quoted TOML escaping. + if (value.includes("\\") && !value.includes("'") && !/[\r\n\t\x00-\x1f\x7f]/.test(value)) { + return `'${value}'`; + } + return JSON.stringify(value); +} + +function formatTomlStringArray(values: ReadonlyArray): string { + return `[${values.map((entry) => encodeTomlString(entry)).join(", ")}]`; +} + +/** + * Updates `[skills] ignore = [...]` in a Grok `config.toml` string while preserving comments, + * formatting, and all other sections. + */ +export function updateGrokSkillsIgnore( + tomlText: string, + nextIgnore: ReadonlyArray, +): string { + const eol = tomlText.includes("\r\n") ? "\r\n" : "\n"; + const formattedArray = formatTomlStringArray(nextIgnore); + const section = findGrokSkillsSection(tomlText); + + if (!section) { + const prefix = + tomlText.length === 0 + ? "" + : tomlText.endsWith("\n") + ? `${tomlText}${eol}` + : `${tomlText}${eol}${eol}`; + return `${prefix}[skills]${eol}ignore = ${formattedArray}${eol}`; + } + + if (section.ignoreValueStart !== undefined && section.ignoreValueEnd !== undefined) { + return `${tomlText.slice(0, section.ignoreValueStart)}${formattedArray}${tomlText.slice(section.ignoreValueEnd)}`; + } + + // Insert `ignore = [...]` right before the next table header (preserving trailing blank lines). + const beforeNext = tomlText.slice(0, section.sectionEnd); + const afterNext = tomlText.slice(section.sectionEnd); + const trailingNewlinesMatch = beforeNext.match(/(\r?\n)+$/); + const trimmedSection = trailingNewlinesMatch + ? beforeNext.slice(0, beforeNext.length - trailingNewlinesMatch[0].length) + : beforeNext; + const trailing = trailingNewlinesMatch ? trailingNewlinesMatch[0] : eol; + return `${trimmedSection}${eol}ignore = ${formattedArray}${trailing}${afterNext}`; +} + +export interface GrokIgnoreState { + readonly rawEntries: ReadonlyArray; + readonly resolvedKeys: ReadonlySet; + readonly sharesMainConfig: boolean; +} + +async function resolveFileLinkAndHardLinkTarget( + filePath: string, + mainFilePath: string, +): Promise<{ + readonly targetPath: string; + readonly isHardLinkedToMain: boolean; + readonly sharesMainConfig: boolean; +}> { + const lstat = await fs.lstat(filePath).catch(() => null); + if (lstat?.isSymbolicLink()) { + const real = await fs.realpath(filePath).catch(() => filePath); + const mainReal = await fs.realpath(mainFilePath).catch(() => mainFilePath); + return { + targetPath: real, + isHardLinkedToMain: false, + sharesMainConfig: + normalizedPathKey(filePath) !== normalizedPathKey(mainFilePath) && + normalizedPathKey(real) === normalizedPathKey(mainReal), + }; + } + if (lstat?.isFile() && normalizedPathKey(filePath) !== normalizedPathKey(mainFilePath)) { + const mainStat = await fs.stat(mainFilePath).catch(() => null); + if (mainStat?.isFile() && mainStat.dev === lstat.dev && mainStat.ino === lstat.ino) { + return { + targetPath: mainFilePath, + isHardLinkedToMain: true, + sharesMainConfig: true, + }; + } + } + return { + targetPath: filePath, + isHardLinkedToMain: false, + sharesMainConfig: false, + }; +} + +/** + * Reads Grok's `[skills] ignore` entries and resolves both raw and canonical paths so symlinked + * skills and `~/` entries match reliably. + */ +export const readGrokIgnoreState = Effect.fn("otherProviderSkillToggles.readGrokIgnoreState")( + function* (input: { + readonly grokHome: string; + readonly mainGrokHome: string; + readonly environment: NodeJS.ProcessEnv; + }): Effect.fn.Return { + const path = yield* Path.Path; + const configPath = path.join(input.grokHome, "config.toml"); + const mainConfigPath = path.join(input.mainGrokHome, "config.toml"); + + return yield* Effect.promise(async () => { + const linkInfo = await resolveFileLinkAndHardLinkTarget(configPath, mainConfigPath); + const raw = await fs.readFile(linkInfo.targetPath, "utf8").catch(() => null); + if (raw === null) { + return { + rawEntries: [], + resolvedKeys: new Set(), + sharesMainConfig: linkInfo.sharesMainConfig, + }; + } + const rawEntries = parseGrokSkillsIgnore(raw); + const resolvedKeys = new Set(); + for (const entry of rawEntries) { + const expanded = path.resolve(expandPathWithEnv(entry, input.environment)); + resolvedKeys.add(normalizedPathKey(expanded)); + const real = await fs.realpath(expanded).catch(() => null); + if (real) resolvedKeys.add(normalizedPathKey(real)); + } + return { + rawEntries, + resolvedKeys, + sharesMainConfig: linkInfo.sharesMainConfig, + }; + }); + }, +); + +/** Per-file serialization queue so concurrent skill toggles never overwrite each other. */ +const configWriteQueue = new Map>(); + +function enqueueConfigWrite(filePath: string, task: () => Promise): Promise { + const key = normalizedPathKey(filePath); + const previous = configWriteQueue.get(key) ?? Promise.resolve(); + const run = previous.catch(() => undefined).then(task); + const settled = run.catch(() => undefined); + configWriteQueue.set(key, settled); + void settled.then(() => { + if (configWriteQueue.get(key) === settled) configWriteQueue.delete(key); + }); + return run; +} + +async function writeFilePreservingModeAndLinks(input: { + readonly targetPath: string; + readonly contents: string; + readonly path: Path.Path; +}): Promise { + const target = input.targetPath; + await fs.mkdir(input.path.dirname(target), { recursive: true }); + const existingStat = await fs.stat(target).catch(() => null); + const mode = existingStat ? existingStat.mode & 0o777 : 0o600; + + // When hard links point at this config (e.g. Grok account overlays on Windows/POSIX), renaming + // over `target` would split the inode and detach every hard-linked account. Write in place + // instead so every linked account stays in sync with the updated file. + if (existingStat && existingStat.nlink > 1) { + await fs.writeFile(target, input.contents, "utf8"); + return; + } + + const temp = `${target}.threadlines-${randomBytes(4).toString("hex")}.tmp`; + await fs.writeFile(temp, input.contents, { encoding: "utf8", mode }); + await fs.chmod(temp, mode).catch(() => undefined); + try { + await fs.rename(temp, target); + } catch (error) { + await fs.rm(temp, { force: true }).catch(() => undefined); + throw error; + } +} + +/** Updates Grok's `[skills] ignore` list for one validated skill directory. */ +export const writeGrokSkillToggle = Effect.fn("otherProviderSkillToggles.writeGrokSkillToggle")( + function* (input: { + readonly grokHome: string; + readonly mainGrokHome: string; + readonly skillPath: string; + readonly enabled: boolean; + readonly environment: NodeJS.ProcessEnv; + }): Effect.fn.Return { + const path = yield* Path.Path; + const configPath = path.join(input.grokHome, "config.toml"); + const mainConfigPath = path.join(input.mainGrokHome, "config.toml"); + const skillDir = path.dirname(path.resolve(input.skillPath)); + + return yield* Effect.tryPromise({ + try: async () => { + const linkInfo = await resolveFileLinkAndHardLinkTarget(configPath, mainConfigPath); + await enqueueConfigWrite(linkInfo.targetPath, async () => { + const existingText = await fs + .readFile(linkInfo.targetPath, "utf8") + .catch((error: unknown) => { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return ""; + throw error; + }); + + // Refuse to clobber an unparseable `ignore = ...` line in `[skills]`. + const section = findGrokSkillsSection(existingText); + if (section && section.ignoreValueStart === undefined) { + const sectionSlice = existingText.slice(section.sectionStart, section.sectionEnd); + if (/^\s*(?:ignore|"ignore"|'ignore')\s*=/m.test(sectionSlice)) { + throw new Error( + `Could not parse [skills].ignore in ${linkInfo.targetPath}. Edit the file directly to change ignored skills.`, + ); + } + } + + const existingEntries = parseGrokSkillsIgnore(existingText); + const targetKeys = new Set([normalizedPathKey(skillDir)]); + const realSkillDir = await fs.realpath(skillDir).catch(() => null); + if (realSkillDir) targetKeys.add(normalizedPathKey(realSkillDir)); + + const matchesTarget = async (entry: string): Promise => { + const expanded = path.resolve(expandPathWithEnv(entry, input.environment)); + if (targetKeys.has(normalizedPathKey(expanded))) return true; + const realEntry = await fs.realpath(expanded).catch(() => null); + return realEntry !== null && targetKeys.has(normalizedPathKey(realEntry)); + }; + + const filtered: Array = []; + for (const entry of existingEntries) { + if (!(await matchesTarget(entry))) { + filtered.push(entry); + } + } + + const nextEntries = input.enabled ? filtered : [...filtered, skillDir]; + const nextText = updateGrokSkillsIgnore(existingText, nextEntries); + await writeFilePreservingModeAndLinks({ + targetPath: linkInfo.targetPath, + contents: nextText, + path, + }); + }); + }, + catch: (error) => + error instanceof Error ? error.message : `Failed to update ${configPath}.`, + }); + }, +); + +/** OpenCode's wildcard rule matcher: `*` matches any run, `?` matches one character. */ +function openCodeWildcardMatch(input: string, pattern: string): boolean { + const escaped = pattern + .replace(/[.+^${}()|[\]\\]/g, "\\$&") + .replace(/\*/g, ".*") + .replace(/\?/g, "."); + return new RegExp(`^${escaped}$`, "s").test(input); +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** + * Evaluates whether an OpenCode config document explicitly allows or denies a skill name. + * Supports OpenCode 2 `policies` (`action: "skill.use"` and legacy `action: "integration.use"` + * with `"skill:"` resource prefix) and OpenCode 1 `permission.skill` maps. Last match wins. + */ +export function evaluateOpenCodeSkillPolicy( + doc: Record, + skillName: string, +): "allow" | "deny" | undefined { + let effect: "allow" | "deny" | undefined; + + // Fallback OpenCode 1 `permission.skill` object map (evaluated first so v2 `policies` wins). + if (isRecord(doc.permission)) { + const skillPerm = doc.permission.skill; + if (typeof skillPerm === "string") { + if (skillPerm === "deny") effect = "deny"; + else if (skillPerm === "allow" || skillPerm === "ask") effect = "allow"; + } else if (isRecord(skillPerm)) { + for (const [pattern, rawEffect] of Object.entries(skillPerm)) { + if (!openCodeWildcardMatch(skillName, pattern)) continue; + if (rawEffect === "deny") effect = "deny"; + else if (rawEffect === "allow" || rawEffect === "ask") effect = "allow"; + } + } + } + + if (Array.isArray(doc.policies)) { + for (const rawRule of doc.policies) { + if (!isRecord(rawRule)) continue; + const action = typeof rawRule.action === "string" ? rawRule.action : undefined; + const resource = typeof rawRule.resource === "string" ? rawRule.resource : undefined; + const ruleEffect = + rawRule.effect === "allow" || rawRule.effect === "deny" ? rawRule.effect : undefined; + if (!action || !resource || !ruleEffect) continue; + + if (action === "skill.use") { + if (openCodeWildcardMatch(skillName, resource)) { + effect = ruleEffect; + } + } else if (action === "integration.use" && resource.startsWith("skill:")) { + if (openCodeWildcardMatch(skillName, resource.slice("skill:".length))) { + effect = ruleEffect; + } + } + } + } + + return effect; +} + +/** True when an OpenCode skill name contains wildcard characters that would affect other skills. */ +export function hasOpenCodePolicyWildcard(skillName: string): boolean { + return /[*?]/.test(skillName); +} + +/** + * Updates OpenCode's user `opencode.json` `policies` list to enable or disable `skillName`. + * Never modifies project config files; refuses wildcard skill names and malformed JSON. + */ +export const writeOpenCodeSkillToggle = Effect.fn( + "otherProviderSkillToggles.writeOpenCodeSkillToggle", +)(function* (input: { + readonly userConfigPath: string; + readonly skillName: string; + readonly enabled: boolean; + readonly forbiddenBoundary?: string | undefined; +}): Effect.fn.Return { + const path = yield* Path.Path; + if (hasOpenCodePolicyWildcard(input.skillName)) { + return yield* Effect.fail( + "Skills with wildcard characters in their name cannot be toggled safely via opencode.json.", + ); + } + return yield* Effect.tryPromise({ + try: async () => { + const target = (await fs.lstat(input.userConfigPath).catch(() => null))?.isSymbolicLink() + ? await fs.realpath(input.userConfigPath).catch(() => input.userConfigPath) + : input.userConfigPath; + + if (input.forbiddenBoundary) { + const realTarget = (await fs.realpath(target).catch(() => null)) ?? path.resolve(target); + const rel = path.relative(input.forbiddenBoundary, realTarget); + const insideRepo = + rel === "" || + (!path.isAbsolute(rel) && + rel !== ".." && + !rel.startsWith(`..${path.sep}`) && + !rel.startsWith("../")); + if (insideRepo) { + throw new Error( + "User opencode.json links into this repository. Open config to edit it directly.", + ); + } + } + + await enqueueConfigWrite(target, async () => { + const raw = await fs.readFile(target, "utf8").catch((error: unknown) => { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; + throw error; + }); + let doc: Record = {}; + if (raw !== null) { + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + throw new Error(`${target} contains invalid JSON. Fix it before toggling skills.`); + } + if (!isRecord(parsed)) { + throw new Error(`${target} is not a JSON object.`); + } + doc = { ...parsed }; + } + + const existingPolicies = Array.isArray(doc.policies) ? [...doc.policies] : []; + const filteredPolicies = existingPolicies.filter((rule) => { + if (!isRecord(rule)) return true; + if (rule.action === "skill.use" && rule.resource === input.skillName) return false; + if (rule.action === "integration.use" && rule.resource === `skill:${input.skillName}`) { + return false; + } + return true; + }); + + // Clear any exact OpenCode 1 `permission.skill[skillName] = "deny"` when enabling. + if (input.enabled && isRecord(doc.permission) && isRecord(doc.permission.skill)) { + const nextSkillPerm = { ...doc.permission.skill }; + if (nextSkillPerm[input.skillName] === "deny") { + delete nextSkillPerm[input.skillName]; + doc.permission = { ...doc.permission, skill: nextSkillPerm }; + } + } + + if (!input.enabled) { + filteredPolicies.push({ + action: "skill.use", + resource: input.skillName, + effect: "deny", + }); + } else { + // If remaining rules (e.g. a wildcard `*` deny) still deny this skill, append an explicit allow. + const probeDoc: Record = { ...doc, policies: filteredPolicies }; + if (evaluateOpenCodeSkillPolicy(probeDoc, input.skillName) === "deny") { + filteredPolicies.push({ + action: "skill.use", + resource: input.skillName, + effect: "allow", + }); + } + } + + if (filteredPolicies.length > 0) { + doc.policies = filteredPolicies; + } else { + delete doc.policies; + } + + await writeFilePreservingModeAndLinks({ + targetPath: target, + contents: `${JSON.stringify(doc, null, 2)}\n`, + path, + }); + }); + }, + catch: (error) => + error instanceof Error ? error.message : `Failed to update ${input.userConfigPath}.`, + }); +}); + +/** + * Checks whether an Antigravity profile's slot (`config/skills` or `antigravity-cli/skills`) is + * controlled by Threadlines (either a symlink to `sourceDir`, an empty directory, missing, or a + * Threadlines-managed split directory). + */ +export const antigravityProfileManagesSkillDir = Effect.fn( + "otherProviderSkillToggles.antigravityProfileManagesSkillDir", +)(function* ( + profileDir: string | undefined, + rel: AntigravitySkillDir, + sourceDir: string, +): Effect.fn.Return { + if (!profileDir) return false; + const path = yield* Path.Path; + const slot = path.join(profileDir, ...rel.split("/")); + return yield* Effect.promise(async () => { + const lstat = await fs.lstat(slot).catch(() => null); + if (!lstat) return true; + if (lstat.isSymbolicLink()) { + const [slotReal, sourceReal] = await Promise.all([ + fs.realpath(slot).catch(() => null), + fs.realpath(sourceDir).catch(() => null), + ]); + if (slotReal && sourceReal) { + return normalizedPathKey(slotReal) === normalizedPathKey(sourceReal); + } + const rawTarget = await fs.readlink(slot).catch(() => null); + if (!rawTarget) return false; + const resolvedTarget = path.resolve(path.dirname(slot), rawTarget); + return normalizedPathKey(resolvedTarget) === normalizedPathKey(path.resolve(sourceDir)); + } + if (lstat.isDirectory()) { + if (await isAntigravitySplitSkillDir(profileDir, rel)) return true; + const entries = await fs.readdir(slot).catch(() => null); + return entries !== null && entries.length === 0; + } + return false; + }); +}); + +export interface AntigravityDirectUserSkillEntry { + readonly sharedDir: AntigravitySkillDir; + readonly entryName: string; + readonly discoveredSkillPath: string; + readonly realSkillPath: string; + readonly isEntryOrFileSymlink: boolean; +} + +/** + * Enumerates direct child skills inside `~/.gemini/config/skills` and `~/.gemini/antigravity-cli/skills`, + * preserving both their discovered path under `~/.gemini` and their canonical `realpath`. + */ +export const listAntigravityDirectUserSkills = Effect.fn( + "otherProviderSkillToggles.listAntigravityDirectUserSkills", +)(function* ( + userHome: string, +): Effect.fn.Return, never, Path.Path> { + const path = yield* Path.Path; + const geminiDir = antigravityUserGeminiDir(userHome); + return yield* Effect.promise(async () => { + const results: Array = []; + for (const sharedDir of ANTIGRAVITY_SKILL_DIRS) { + const rootDir = path.join(geminiDir, ...sharedDir.split("/")); + const entries = await fs.readdir(rootDir).catch(() => null); + if (!entries) continue; + // Skip roots that themselves hold a direct SKILL.md (single-skill roots cannot be split). + const hasDirectSkill = entries.some((entry) => entry.toLowerCase() === "skill.md"); + if (hasDirectSkill) continue; + for (const entryName of entries.toSorted()) { + if (entryName.startsWith(".")) continue; + const entryDir = path.join(rootDir, entryName); + const dirLstat = await fs.lstat(entryDir).catch(() => null); + if (!dirLstat) continue; + const dirStat = dirLstat.isSymbolicLink() + ? await fs.stat(entryDir).catch(() => null) + : dirLstat; + if (!dirStat?.isDirectory()) continue; + const childFiles = await fs.readdir(entryDir).catch(() => null); + const skillFileName = childFiles + ?.toSorted() + .find((name) => name.toLowerCase() === "skill.md"); + if (!skillFileName) continue; + const discoveredSkillPath = path.join(entryDir, skillFileName); + const fileLstat = await fs.lstat(discoveredSkillPath).catch(() => null); + if (!fileLstat) continue; + const fileStat = fileLstat.isSymbolicLink() + ? await fs.stat(discoveredSkillPath).catch(() => null) + : fileLstat; + if (!fileStat?.isFile()) continue; + const realSkillPath = + (await fs.realpath(discoveredSkillPath).catch(() => null)) ?? discoveredSkillPath; + results.push({ + sharedDir, + entryName, + discoveredSkillPath, + realSkillPath, + isEntryOrFileSymlink: dirLstat.isSymbolicLink() || fileLstat.isSymbolicLink(), + }); + } + } + return results; + }); +}); + +/** Re-syncs an Antigravity profile after creating or deleting a user skill so split dirs stay current. */ +export const syncAntigravityProfileAfterSkillMutation = Effect.fn( + "otherProviderSkillToggles.syncAntigravityProfileAfterSkillMutation", +)(function* (input: { + readonly profileDir: string; + readonly userHome: string; + readonly stateDir: string; +}): Effect.fn.Return { + yield* Effect.promise(async () => { + const stat = await fs.stat(input.profileDir).catch(() => null); + if (!stat?.isDirectory()) return; + await shareAntigravityUserConfigNow({ + profileDir: input.profileDir, + userHome: input.userHome, + platform: process.platform, + threadlinesDir: input.stateDir, + }).catch(() => undefined); + }); +}); + +/** Toggles one Antigravity personal skill inside its Threadlines profile and fails on any sync error. */ +export const writeAntigravitySkillToggle = Effect.fn( + "otherProviderSkillToggles.writeAntigravitySkillToggle", +)(function* (input: { + readonly profileDir: string; + readonly userHome: string; + readonly stateDir: string; + readonly sharedDir: AntigravitySkillDir; + readonly entryName: string; + readonly enabled: boolean; +}): Effect.fn.Return { + const path = yield* Path.Path; + const targetPrefix = path.resolve(path.join(input.profileDir, ...input.sharedDir.split("/"))); + return yield* Effect.tryPromise({ + try: async () => { + const problems = await setAntigravitySkillDisabled({ + profileDir: input.profileDir, + userHome: input.userHome, + platform: process.platform, + threadlinesDir: input.stateDir, + sharedDir: input.sharedDir, + entryName: input.entryName, + disabled: !input.enabled, + }); + const relevant = problems.filter((problem) => { + const resolved = path.resolve(problem.path); + return ( + normalizedPathKey(resolved) === normalizedPathKey(targetPrefix) || + normalizedPathKey(resolved).startsWith(`${normalizedPathKey(targetPrefix)}/`) || + problem.path.endsWith(".shared-config.json") + ); + }); + if (relevant.length > 0) { + throw new Error(relevant.map((problem) => problem.error).join(" ")); + } + }, + catch: (error) => + error instanceof Error ? error.message : "Failed to update Antigravity skill toggle.", + }); +}); diff --git a/apps/server/src/provider/providerExtensions.test.ts b/apps/server/src/provider/providerExtensions.test.ts index 172ebb612..ae8421998 100644 --- a/apps/server/src/provider/providerExtensions.test.ts +++ b/apps/server/src/provider/providerExtensions.test.ts @@ -19,6 +19,7 @@ import type * as CodexSchema from "effect-codex-app-server/schema"; import { ProviderDriverKind, ProviderInstanceId, + type ServerProvider, ServerSettings, type ServerSettings as ServerSettingsContract, } from "@threadlines/contracts"; @@ -3097,4 +3098,553 @@ Per-component (rounded) assert.equal(yield* fileSystem.exists(path.join(cwd, symlinkTarget)), false); }).pipe(Effect.provide(NodeServices.layer)), ); + + it.effect( + "discovers skills and read-only MCP servers for Grok, Cursor, Antigravity, local OpenCode, and Pi while confining external OpenCode and project symlinks", + () => { + const spawner = ChildProcessSpawner.make(() => + Effect.succeed(makeProcessResult("", "unexpected spawn", 1)), + ); + const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner); + + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "threadlines-other-providers-", + }); + const home = path.join(root, "home"); + const project = path.join(root, "repo"); + const outside = path.join(root, "outside"); + const stateDir = path.join(root, "state"); + + // Create a git marker so repo confinement resolves cleanly to `project`. + yield* fileSystem.makeDirectory(path.join(project, ".git"), { recursive: true }); + yield* fileSystem.makeDirectory(path.join(outside, "escape-skill"), { recursive: true }); + yield* fileSystem.writeFileString( + path.join(outside, "escape-skill", "SKILL.md"), + "---\nname: escape-skill\ndescription: Outside repo\n---\n", + ); + + // Grok user + project skills + const grokHome = path.join(home, ".grok"); + yield* fileSystem.makeDirectory(path.join(grokHome, "skills", "grok-user"), { + recursive: true, + }); + yield* fileSystem.writeFileString( + path.join(grokHome, "skills", "grok-user", "SKILL.md"), + "---\nname: grok-user\ndescription: User Grok skill\n---\nBody\n", + ); + yield* fileSystem.makeDirectory(path.join(project, ".grok", "skills", "grok-proj"), { + recursive: true, + }); + yield* fileSystem.writeFileString( + path.join(project, ".grok", "skills", "grok-proj", "SKILL.md"), + "---\nname: grok-proj\ndescription: Project Grok skill\n---\nBody\n", + ); + + // Cursor user skill + MCP config + yield* fileSystem.makeDirectory(path.join(home, ".cursor", "skills", "cursor-user"), { + recursive: true, + }); + yield* fileSystem.writeFileString( + path.join(home, ".cursor", "skills", "cursor-user", "SKILL.md"), + "---\nname: cursor-user\ndescription: Cursor skill\n---\n", + ); + yield* fileSystem.writeFileString( + path.join(home, ".cursor", "mcp.json"), + JSON.stringify({ + mcpServers: { + supabase: { url: "https://mcp.supabase.com/mcp" }, + localTools: { command: "npx", args: ["-y", "demo-mcp"] }, + }, + }), + ); + + // Antigravity user skill + yield* fileSystem.makeDirectory( + path.join(home, ".gemini", "config", "skills", "gemini-design"), + { recursive: true }, + ); + yield* fileSystem.writeFileString( + path.join(home, ".gemini", "config", "skills", "gemini-design", "SKILL.md"), + "---\nname: gemini-design\ndescription: Gemini frontend design\n---\n", + ); + + // Pi user skill via PI_CODING_AGENT_DIR + const piAgent = path.join(root, "custom-pi"); + yield* fileSystem.makeDirectory(path.join(piAgent, "skills", "pi-skill"), { + recursive: true, + }); + yield* fileSystem.writeFileString( + path.join(piAgent, "skills", "pi-skill", "SKILL.md"), + "---\nname: pi-skill\ndescription: Pi custom dir skill\n---\n", + ); + + // Project symlink escaping the repo boundary under `.cursor/skills` + yield* fileSystem.makeDirectory(path.join(project, ".cursor", "skills"), { + recursive: true, + }); + yield* fileSystem + .symlink( + path.join(outside, "escape-skill"), + path.join(project, ".cursor", "skills", "escape-skill"), + ) + .pipe(Effect.catch(() => Effect.void)); + + const envEntries = [ + { name: "HOME", value: home }, + { name: "USERPROFILE", value: home }, + ]; + const settings = makeSettings({ + providers: { + codex: { enabled: false }, + claudeAgent: { enabled: false }, + cursor: { enabled: true }, + opencode: { enabled: false }, + }, + providerInstances: { + grok: { + driver: "grok", + displayName: "Grok", + enabled: true, + config: { enabled: true }, + environment: [...envEntries, { name: "GROK_HOME", value: grokHome }], + }, + cursor: { + driver: "cursor", + displayName: "Cursor", + enabled: true, + config: { enabled: true }, + environment: envEntries, + }, + antigravity: { + driver: "antigravity", + displayName: "Antigravity", + enabled: true, + config: { enabled: true }, + environment: envEntries, + }, + pi: { + driver: "pi", + displayName: "Pi", + enabled: true, + config: { enabled: true }, + environment: [...envEntries, { name: "PI_CODING_AGENT_DIR", value: piAgent }], + }, + "opencode-remote": { + driver: "opencode", + displayName: "Remote OpenCode", + enabled: true, + config: { enabled: true, serverUrl: "http://remote.example:4096" }, + environment: envEntries, + }, + }, + }); + + const remoteSnapshot = { + instanceId: ProviderInstanceId.make("opencode-remote"), + provider: "opencode", + driverKind: "opencode", + displayName: "Remote OpenCode", + enabled: true, + installed: true, + version: "2.0.0", + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-11-24T00:00:00.000Z", + models: [], + slashCommands: [], + skills: [ + { + name: "remote-only", + path: path.join(grokHome, "skills", "grok-user", "SKILL.md"), + scope: "user", + enabled: true, + description: "Lives on remote host", + }, + ], + } as unknown as ServerProvider; + + const inventory = yield* readProviderExtensionsInventory({ + request: { cwd: project }, + settings, + providers: [remoteSnapshot], + stateDir, + }); + + const grok = inventory.providers.find((p) => String(p.instanceId) === "grok"); + const cursor = inventory.providers.find((p) => String(p.instanceId) === "cursor"); + const antigravity = inventory.providers.find((p) => String(p.instanceId) === "antigravity"); + const pi = inventory.providers.find((p) => String(p.instanceId) === "pi"); + const remoteOpenCode = inventory.providers.find( + (p) => String(p.instanceId) === "opencode-remote", + ); + + assert.deepEqual( + grok?.skills.map((s) => s.name), + ["grok-proj", "grok-user"], + ); + assert.equal(grok?.capabilities?.plugins, false); + assert.equal(grok?.capabilities?.skillCreate, true); + + // Escaping symlink skill must NOT be admitted for Cursor. + assert.deepEqual( + cursor?.skills.map((s) => s.name), + ["cursor-user"], + ); + assert.deepEqual( + cursor?.mcpServers.map((m) => [m.name, m.transport, m.status]), + [ + ["localTools", "stdio", "Configured"], + ["supabase", "http", "Configured"], + ], + ); + assert.equal(cursor?.capabilities?.mcpServers, true); + + assert.deepEqual( + antigravity?.skills.map((s) => s.name), + ["gemini-design"], + ); + assert.equal(antigravity?.capabilities?.skillCreate, true); + + assert.deepEqual( + pi?.skills.map((s) => s.name), + ["pi-skill"], + ); + + // External OpenCode skill must be metadata-only and refused by local read. + assert.equal(remoteOpenCode?.skills[0]?.canRead, false); + assert.equal(remoteOpenCode?.capabilities?.skillCreate, false); + const remoteReadError = yield* readProviderExtensionSkill({ + request: { + providerInstanceId: ProviderInstanceId.make("opencode-remote"), + path: path.join(grokHome, "skills", "grok-user", "SKILL.md"), + }, + settings, + }).pipe(Effect.flip); + assert.match(remoteReadError.message, /Remote OpenCode skills cannot be read/i); + + // Grok can read, create, and delete skills in its managed folder. + const created = yield* createProviderExtensionSkill({ + request: { + cwd: project, + providerInstanceId: ProviderInstanceId.make("grok"), + name: "new-grok-skill", + description: "Test creation", + }, + settings, + stateDir, + }); + assert.equal(yield* fileSystem.exists(created.path), true); + + // Re-scan and delete the created Grok skill cleanly. + yield* readProviderExtensionsInventory({ + request: { cwd: project, providerInstanceId: ProviderInstanceId.make("grok") }, + settings, + providers: [], + stateDir, + }); + const deleted = yield* deleteProviderExtensionSkill({ + request: { + cwd: project, + providerInstanceId: ProviderInstanceId.make("grok"), + path: created.path, + }, + settings, + stateDir, + }); + assert.equal(deleted.deleted, true); + assert.equal(yield* fileSystem.exists(created.path), false); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, spawnerLayer))); + }, + ); + + it.effect( + "toggles Grok, local OpenCode, and Antigravity skills natively while preserving boundaries", + () => { + const spawner = ChildProcessSpawner.make(() => + Effect.die("Non-Codex/Claude toggles must not spawn subprocesses"), + ); + const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner); + + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "threadlines-hybrid-toggles-", + }); + const home = path.join(root, "home"); + const grokHome = path.join(home, ".grok"); + const xdgConfig = path.join(root, "xdg"); + const project = path.join(root, "repo"); + const stateDir = path.join(root, "state"); + + yield* fileSystem.makeDirectory(path.join(project, ".git"), { recursive: true }); + yield* fileSystem.makeDirectory(path.join(project, ".grok", "skills", "review"), { + recursive: true, + }); + yield* fileSystem.makeDirectory(path.join(grokHome, "skills", "review"), { + recursive: true, + }); + yield* fileSystem.makeDirectory(path.join(xdgConfig, "opencode", "skills", "oc-user"), { + recursive: true, + }); + yield* fileSystem.makeDirectory(path.join(xdgConfig, "opencode", "skills", "oc-locked"), { + recursive: true, + }); + yield* fileSystem.makeDirectory(path.join(home, ".gemini", "config", "skills", "alpha"), { + recursive: true, + }); + yield* fileSystem.makeDirectory(path.join(home, ".gemini", "config", "skills", "beta"), { + recursive: true, + }); + yield* fileSystem.makeDirectory(path.join(project, ".gemini", "skills", "proj-only"), { + recursive: true, + }); + + yield* fileSystem.writeFileString( + path.join(grokHome, "config.toml"), + "# Keep my comment\n[ui]\nyolo = false\n", + ); + yield* fileSystem.writeFileString( + path.join(project, ".grok", "skills", "review", "SKILL.md"), + "---\nname: review\ndescription: Project review\n---\nBody\n", + ); + yield* fileSystem.writeFileString( + path.join(grokHome, "skills", "review", "SKILL.md"), + "---\nname: review\ndescription: Personal review\n---\nBody\n", + ); + yield* fileSystem.writeFileString( + path.join(xdgConfig, "opencode", "skills", "oc-user", "SKILL.md"), + "---\nname: oc-user\ndescription: OpenCode user skill\n---\nBody\n", + ); + yield* fileSystem.writeFileString( + path.join(xdgConfig, "opencode", "skills", "oc-locked", "SKILL.md"), + "---\nname: oc-locked\ndescription: Denied by project\n---\nBody\n", + ); + yield* fileSystem.writeFileString( + path.join(project, "opencode.json"), + JSON.stringify({ + policies: [{ action: "skill.use", resource: "oc-locked", effect: "deny" }], + }), + ); + yield* fileSystem.writeFileString( + path.join(home, ".gemini", "config", "skills", "alpha", "SKILL.md"), + "---\nname: alpha\ndescription: Alpha skill\n---\nBody\n", + ); + yield* fileSystem.writeFileString( + path.join(home, ".gemini", "config", "skills", "beta", "SKILL.md"), + "---\nname: beta\ndescription: Beta skill\n---\nBody\n", + ); + yield* fileSystem.writeFileString( + path.join(project, ".gemini", "skills", "proj-only", "SKILL.md"), + "---\nname: proj-only\ndescription: Project skill\n---\nBody\n", + ); + + const envEntries = [ + { name: "HOME", value: home }, + { name: "USERPROFILE", value: home }, + { name: "GROK_HOME", value: grokHome }, + { name: "XDG_CONFIG_HOME", value: xdgConfig }, + ]; + const settings = makeSettings({ + providers: { + codex: { enabled: false }, + claudeAgent: { enabled: false }, + cursor: { enabled: false }, + opencode: { enabled: false }, + }, + providerInstances: { + grok: { + driver: "grok", + displayName: "Grok", + enabled: true, + config: { enabled: true }, + environment: envEntries, + }, + opencode: { + driver: "opencode", + displayName: "OpenCode", + enabled: true, + config: { enabled: true, serverUrl: "" }, + environment: envEntries, + }, + "opencode-remote": { + driver: "opencode", + displayName: "Remote OpenCode", + enabled: true, + config: { enabled: true, serverUrl: "http://remote.example:4096" }, + environment: envEntries, + }, + antigravity: { + driver: "antigravity", + displayName: "Antigravity", + enabled: true, + config: { enabled: true }, + environment: envEntries, + }, + }, + }); + + const before = yield* readProviderExtensionsInventory({ + request: { cwd: project }, + settings, + providers: [], + stateDir, + }); + + // 1. Grok: disabling project `review` preserves comments in config.toml and exposes fallback personal `review`. + const grokBefore = before.providers.find((p) => String(p.instanceId) === "grok"); + const projectReview = grokBefore?.skills.find((s) => s.scope === "project"); + assert.equal(projectReview?.canToggle, true); + assert.equal(projectReview?.enabled, true); + + const grokDisabled = yield* setProviderExtensionSkillEnabled({ + request: { + cwd: project, + providerInstanceId: ProviderInstanceId.make("grok"), + path: projectReview!.path, + enabled: false, + }, + settings, + stateDir, + }); + assert.equal(grokDisabled.effectiveEnabled, false); + const tomlAfter = yield* fileSystem.readFileString(path.join(grokHome, "config.toml")); + assert.match(tomlAfter, /# Keep my comment/); + assert.match(tomlAfter, /\[skills\]/); + + const grokAfterDisable = yield* readProviderExtensionsInventory({ + request: { cwd: project, providerInstanceId: ProviderInstanceId.make("grok") }, + settings, + providers: [], + stateDir, + }); + const grokSkills = grokAfterDisable.providers[0]?.skills ?? []; + assert.equal(grokSkills.length, 2); + assert.equal(grokSkills.find((s) => s.scope === "project")?.enabled, false); + assert.equal(grokSkills.find((s) => s.scope === "user")?.enabled, true); + + yield* setProviderExtensionSkillEnabled({ + request: { + cwd: project, + providerInstanceId: ProviderInstanceId.make("grok"), + path: projectReview!.path, + enabled: true, + }, + settings, + stateDir, + }); + const grokReenabled = yield* readProviderExtensionsInventory({ + request: { cwd: project, providerInstanceId: ProviderInstanceId.make("grok") }, + settings, + providers: [], + stateDir, + }); + assert.equal(grokReenabled.providers[0]?.skills.length, 1); + assert.equal(grokReenabled.providers[0]?.skills[0]?.enabled, true); + + // 2. Local OpenCode: user policy toggles `oc-user`, while project-denied `oc-locked` is locked and never mutated. + const ocBefore = before.providers.find((p) => String(p.instanceId) === "opencode"); + const ocUser = ocBefore?.skills.find((s) => s.name === "oc-user"); + const ocLocked = ocBefore?.skills.find((s) => s.name === "oc-locked"); + assert.equal(ocUser?.canToggle, true); + assert.equal(ocUser?.enabled, true); + assert.equal(ocLocked?.enabled, false); + assert.equal(ocLocked?.canToggle, undefined); + assert.match(ocLocked?.toggleNotice ?? "", /project's opencode\.json/i); + + yield* setProviderExtensionSkillEnabled({ + request: { + cwd: project, + providerInstanceId: ProviderInstanceId.make("opencode"), + path: ocUser!.path, + enabled: false, + }, + settings, + stateDir, + }); + const ocAfterDisable = yield* readProviderExtensionsInventory({ + request: { cwd: project, providerInstanceId: ProviderInstanceId.make("opencode") }, + settings, + providers: [], + stateDir, + }); + assert.equal( + ocAfterDisable.providers[0]?.skills.find((s) => s.name === "oc-user")?.enabled, + false, + ); + + const ocLockedError = yield* setProviderExtensionSkillEnabled({ + request: { + cwd: project, + providerInstanceId: ProviderInstanceId.make("opencode"), + path: ocLocked!.path, + enabled: true, + }, + settings, + stateDir, + }).pipe(Effect.flip); + assert.match(ocLockedError.message, /project's opencode\.json/i); + + // External OpenCode refuses toggles. + const remoteToggleError = yield* setProviderExtensionSkillEnabled({ + request: { + cwd: project, + providerInstanceId: ProviderInstanceId.make("opencode-remote"), + path: ocUser!.path, + enabled: false, + }, + settings, + stateDir, + }).pipe(Effect.flip); + assert.match(remoteToggleError.message, /not in this provider's current scope/i); + + // 3. Antigravity: personal skill toggles via profile split links; project skill stays locked. + const agyBefore = before.providers.find((p) => String(p.instanceId) === "antigravity"); + const agyBeta = agyBefore?.skills.find((s) => s.name === "beta"); + const agyProj = agyBefore?.skills.find((s) => s.name === "proj-only"); + assert.equal(agyBeta?.canToggle, true); + assert.equal(agyProj?.canToggle, undefined); + + yield* setProviderExtensionSkillEnabled({ + request: { + cwd: project, + providerInstanceId: ProviderInstanceId.make("antigravity"), + path: agyBeta!.path, + enabled: false, + }, + settings, + stateDir, + }); + const agyAfterDisable = yield* readProviderExtensionsInventory({ + request: { cwd: project, providerInstanceId: ProviderInstanceId.make("antigravity") }, + settings, + providers: [], + stateDir, + }); + assert.equal( + agyAfterDisable.providers[0]?.skills.find((s) => s.name === "beta")?.enabled, + false, + ); + assert.equal( + agyAfterDisable.providers[0]?.skills.find((s) => s.name === "alpha")?.enabled, + true, + ); + + const agyProjError = yield* setProviderExtensionSkillEnabled({ + request: { + cwd: project, + providerInstanceId: ProviderInstanceId.make("antigravity"), + path: agyProj!.path, + enabled: false, + }, + settings, + stateDir, + }).pipe(Effect.flip); + assert.match(agyProjError.message, /does not support toggling/i); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, spawnerLayer))); + }, + ); }); diff --git a/apps/server/src/provider/providerExtensions.ts b/apps/server/src/provider/providerExtensions.ts index c68400d3b..95785f5f2 100644 --- a/apps/server/src/provider/providerExtensions.ts +++ b/apps/server/src/provider/providerExtensions.ts @@ -99,6 +99,16 @@ import { } from "./Drivers/CodexHomeLayout.ts"; import { buildCodexInitializeParams } from "./Layers/CodexProvider.ts"; import { deriveProviderInstanceConfigMap } from "./Layers/ProviderInstanceRegistryHydration.ts"; +import { + findRepositoryRoot, + isExternalOpenCodeConfig, + isPathWithinBoundary, + readOtherProviderInventory, + resolveOtherProviderEnabled, + resolveOtherProviderSkillRoots, + setOtherProviderSkillEnabled, + syncOtherProviderAfterSkillMutation, +} from "./otherProviderExtensions.ts"; import { mergeProviderInstanceEnvironment } from "./ProviderInstanceEnvironment.ts"; import { spawnAndCollect } from "./providerSnapshot.ts"; import { planCliSpawn } from "../cliSpawn.ts"; @@ -1341,21 +1351,41 @@ const isProviderExtensionsError = Schema.is(ProviderExtensionsError); * whether the store was included), so a filtered load, another client, or the composer's skill * lookup cannot revoke paths that a view loaded earlier is still showing. */ -const MAX_REPORTED_EXTENSION_PATH_SCOPES = 32; +const MAX_REPORTED_EXTENSION_PATH_SCOPES = 64; const reportedExtensionPaths = new Map< string, - { readonly skillPaths: Set; readonly pluginIconPaths: Set } + { + readonly instanceId: string; + readonly skillPaths: Map; + readonly pluginIconPaths: Set; + } >(); function recordReportedExtensionPaths( scope: string, providers: ReadonlyArray, + projectBoundary?: string | undefined, ): void { for (const provider of providers) { - const key = JSON.stringify([String(provider.instanceId), scope]); + const instanceId = String(provider.instanceId); + const key = JSON.stringify([instanceId, scope]); reportedExtensionPaths.delete(key); + const skillPaths = new Map(); + for (const skill of provider.skills) { + if (!skill.path || skill.canRead === false) continue; + // Confine non-Codex/Claude project skills to the canonical project boundary on read. + const enforceBoundary = + projectBoundary !== undefined && + skill.scope?.trim().toLowerCase() === "project" && + provider.driver !== CODEX_DRIVER && + provider.driver !== CLAUDE_DRIVER + ? projectBoundary + : undefined; + skillPaths.set(skill.path, enforceBoundary ? { boundary: enforceBoundary } : {}); + } reportedExtensionPaths.set(key, { - skillPaths: new Set(provider.skills.flatMap((skill) => (skill.path ? [skill.path] : []))), + instanceId, + skillPaths, pluginIconPaths: new Set( provider.plugins.flatMap((plugin) => (plugin.iconPath ? [plugin.iconPath] : [])), ), @@ -1378,11 +1408,25 @@ export function isCurrentProviderExtensionPluginIconPath(filePath: string): bool return false; } -export function isCurrentProviderExtensionSkillPath(filePath: string): boolean { +function findReportedExtensionSkillEntry( + filePath: string, + providerInstanceId?: ProviderInstanceId | string, +): { readonly boundary?: string | undefined } | null { + const expectedInstance = + providerInstanceId !== undefined ? String(providerInstanceId) : undefined; for (const entry of reportedExtensionPaths.values()) { - if (entry.skillPaths.has(filePath)) return true; + if (expectedInstance !== undefined && entry.instanceId !== expectedInstance) continue; + const found = entry.skillPaths.get(filePath); + if (found !== undefined) return found; } - return false; + return null; +} + +export function isCurrentProviderExtensionSkillPath( + filePath: string, + providerInstanceId?: ProviderInstanceId | string, +): boolean { + return findReportedExtensionSkillEntry(filePath, providerInstanceId) !== null; } function recordProviderExtensionOperation( @@ -4026,12 +4070,30 @@ function fallbackSkillsFromSnapshot( })); } +const CODEX_CAPABILITIES = { + plugins: true, + mcpServers: true, + apps: true, + hooks: true, + skillCreate: true, +} as const; + +const CLAUDE_CAPABILITIES = { + plugins: true, + mcpServers: true, + apps: false, + hooks: true, + skillCreate: true, +} as const; + const readProviderInventory = Effect.fn("providerExtensions.readProviderInventory")( function* (input: { readonly instanceId: ProviderInstanceId; readonly config: ProviderInstanceConfig; readonly snapshot: ServerProvider | undefined; readonly cwd: string; + readonly projectCwd?: string | undefined; + readonly stateDir?: string | undefined; readonly providerThreadId?: string | undefined; readonly includeMcpServers?: boolean | undefined; readonly includeApps?: boolean | undefined; @@ -4059,6 +4121,7 @@ const readProviderInventory = Effect.fn("providerExtensions.readProviderInventor ...base, status: "disabled", message: "Provider is disabled.", + capabilities: CODEX_CAPABILITIES, plugins: [], marketplaces: [], skills: fallbackSkillsFromSnapshot(input.snapshot), @@ -4085,6 +4148,7 @@ const readProviderInventory = Effect.fn("providerExtensions.readProviderInventor return { ...base, ...inventory, + capabilities: CODEX_CAPABILITIES, skills: inventory.skills.length > 0 ? inventory.skills @@ -4107,6 +4171,7 @@ const readProviderInventory = Effect.fn("providerExtensions.readProviderInventor ...base, status: "disabled", message: "Provider is disabled.", + capabilities: CLAUDE_CAPABILITIES, plugins: [], marketplaces: [], skills: [], @@ -4125,19 +4190,21 @@ const readProviderInventory = Effect.fn("providerExtensions.readProviderInventor ? { includePluginCatalog: input.includePluginCatalog } : {}), }); - return { ...base, ...inventory } satisfies ProviderExtensionProviderInventory; + return { + ...base, + ...inventory, + capabilities: CLAUDE_CAPABILITIES, + } satisfies ProviderExtensionProviderInventory; } - return { - ...base, - status: "unsupported", - message: "Extension inventory is only implemented for Codex and Claude.", - plugins: [], - marketplaces: [], - skills: [], - mcpServers: [], - apps: [], - } satisfies ProviderExtensionProviderInventory; + return yield* readOtherProviderInventory({ + instanceId: input.instanceId, + config: input.config, + snapshot: input.snapshot, + processEnv, + ...(input.projectCwd !== undefined ? { projectCwd: input.projectCwd } : {}), + ...(input.stateDir !== undefined ? { stateDir: input.stateDir } : {}), + }); }, ); @@ -4419,13 +4486,18 @@ interface ProviderSkillRoots { readonly driver: string; /** Where `createProviderExtensionSkill` scaffolds. User scope only in v1. */ readonly userSkillsRoot: string; - /** Every root a skill may be deleted from, user and project. */ - readonly writableRoots: ReadonlyArray; + /** User-configured roots a skill may be deleted from (may intentionally be symlinked). */ + readonly userWritableRoots: ReadonlyArray; + /** Project-scoped roots a skill may be deleted from (confined to `projectBoundary` when set). */ + readonly projectWritableRoots: ReadonlyArray; + /** Canonical boundary confining `projectWritableRoots`. */ + readonly projectBoundary?: string | undefined; } const resolveProviderSkillRoots = Effect.fn("providerExtensions.resolveProviderSkillRoots")( function* (input: { readonly cwd?: string | undefined; + readonly stateDir?: string | undefined; readonly providerInstanceId: ProviderInstanceId; readonly settings: ServerSettings; }): Effect.fn.Return< @@ -4434,7 +4506,8 @@ const resolveProviderSkillRoots = Effect.fn("providerExtensions.resolveProviderS FileSystem.FileSystem | Path.Path > { const path = yield* Path.Path; - const cwd = input.cwd ?? machineScopeCwd(); + const projectCwd = optionalText(input.cwd); + const cwd = projectCwd ?? machineScopeCwd(); const providerConfig = yield* resolveProviderActionConfig(input); if (providerConfig.driver === CLAUDE_DRIVER) { @@ -4457,7 +4530,10 @@ const resolveProviderSkillRoots = Effect.fn("providerExtensions.resolveProviderS return { driver: providerConfig.driver, userSkillsRoot: claudeUserSkillsRoot(path, claudeConfigDir), - writableRoots: roots.map((root) => root.root), + userWritableRoots: roots.filter((root) => root.scope === "user").map((root) => root.root), + projectWritableRoots: roots + .filter((root) => root.scope === "project") + .map((root) => root.root), }; } @@ -4478,12 +4554,26 @@ const resolveProviderSkillRoots = Effect.fn("providerExtensions.resolveProviderS return { driver: providerConfig.driver, userSkillsRoot: roots[0]!, - writableRoots: roots, + userWritableRoots: roots, + projectWritableRoots: [], }; } + if (!resolveOtherProviderEnabled(providerConfig, undefined)) { + return yield* new ProviderExtensionsError({ message: "Provider is disabled." }); + } + const processEnv = mergeProviderInstanceEnvironment(providerConfig.environment ?? []); + const otherRoots = yield* resolveOtherProviderSkillRoots({ + instanceId: input.providerInstanceId, + config: providerConfig, + processEnv, + projectCwd, + stateDir: input.stateDir, + }); + if (otherRoots) return otherRoots; + return yield* new ProviderExtensionsError({ - message: "Managing skills is only available for Codex and Claude providers.", + message: `Managing skills is not supported for ${providerConfig.displayName ?? String(providerConfig.driver)}.`, }); }, ); @@ -4512,6 +4602,7 @@ export const createProviderExtensionSkill = Effect.fn( )(function* (input: { readonly request: ProviderExtensionSkillCreateInput; readonly settings: ServerSettings; + readonly stateDir?: string | undefined; }): Effect.fn.Return< ProviderExtensionSkillCreateResult, ProviderExtensionsError, @@ -4531,6 +4622,7 @@ export const createProviderExtensionSkill = Effect.fn( const roots = yield* resolveProviderSkillRoots({ cwd: input.request.cwd, + stateDir: input.stateDir, providerInstanceId: input.request.providerInstanceId, settings: input.settings, }); @@ -4559,6 +4651,18 @@ export const createProviderExtensionSkill = Effect.fn( }), ), ); + const createdProvider = yield* resolveProviderActionConfig({ + providerInstanceId: input.request.providerInstanceId, + settings: input.settings, + }).pipe(Effect.catch(() => Effect.succeed(null))); + if (createdProvider) { + yield* syncOtherProviderAfterSkillMutation({ + instanceId: input.request.providerInstanceId, + config: createdProvider, + processEnv: mergeProviderInstanceEnvironment(createdProvider.environment, process.env), + stateDir: input.stateDir, + }); + } return { path: skillPath }; }); @@ -4567,6 +4671,7 @@ export const deleteProviderExtensionSkill = Effect.fn( )(function* (input: { readonly request: ProviderExtensionSkillDeleteInput; readonly settings: ServerSettings; + readonly stateDir?: string | undefined; }): Effect.fn.Return< ProviderExtensionSkillDeleteResult, ProviderExtensionsError, @@ -4575,7 +4680,7 @@ export const deleteProviderExtensionSkill = Effect.fn( const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const skillPath = input.request.path; - if (!isCurrentProviderExtensionSkillPath(skillPath)) { + if (!isCurrentProviderExtensionSkillPath(skillPath, input.request.providerInstanceId)) { return yield* new ProviderExtensionsError({ message: "Skill is not in the current provider extensions inventory.", }); @@ -4588,6 +4693,7 @@ export const deleteProviderExtensionSkill = Effect.fn( const roots = yield* resolveProviderSkillRoots({ cwd: input.request.cwd, + stateDir: input.stateDir, providerInstanceId: input.request.providerInstanceId, settings: input.settings, }); @@ -4595,7 +4701,10 @@ export const deleteProviderExtensionSkill = Effect.fn( const linkTarget = yield* fileSystem .readLink(skillPath) .pipe(Effect.catch(() => Effect.succeed(null))); - if (linkTarget !== null) { + const dirLinkTarget = yield* fileSystem + .readLink(path.dirname(path.resolve(skillPath))) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (linkTarget !== null || dirLinkTarget !== null) { return yield* new ProviderExtensionsError({ message: "Skill could not be deleted because the inventory entry is not a regular file.", }); @@ -4611,8 +4720,9 @@ export const deleteProviderExtensionSkill = Effect.fn( }); } - // Compare real paths so a symlinked skills root (the Codex shadow home) resolves to the same - // place as the shared one, and so no `..` segment can walk out of a root. + // Compare real paths so a symlinked user skills root (dotfiles or Codex shadow home) resolves + // to the same place as the shared one. Project roots are additionally confined to the repository + // boundary so a symlinked project directory cannot authorize deleting outside the checkout. const realDirectory = yield* fileSystem .realPath(path.dirname(path.resolve(skillPath))) .pipe( @@ -4620,12 +4730,25 @@ export const deleteProviderExtensionSkill = Effect.fn( () => new ProviderExtensionsError({ message: "Skill directory could not be resolved." }), ), ); - const realRoots = yield* Effect.forEach(roots.writableRoots, (root) => + const realUserRoots = yield* Effect.forEach(roots.userWritableRoots, (root) => + fileSystem.realPath(root).pipe(Effect.catch(() => Effect.succeed(null))), + ); + const realProjectRoots = yield* Effect.forEach(roots.projectWritableRoots, (root) => fileSystem.realPath(root).pipe(Effect.catch(() => Effect.succeed(null))), ); const parent = normalizedPathKey(path.dirname(realDirectory)); - const insideRoot = realRoots.some((root) => root !== null && normalizedPathKey(root) === parent); - if (!insideRoot) { + const insideUserRoot = realUserRoots.some( + (root) => root !== null && normalizedPathKey(root) === parent, + ); + const insideProjectRoot = realProjectRoots.some((root) => { + if (root === null || normalizedPathKey(root) !== parent) return false; + if (!roots.projectBoundary) return true; + return ( + isPathWithinBoundary(path, roots.projectBoundary, root) && + isPathWithinBoundary(path, roots.projectBoundary, realDirectory) + ); + }); + if (!insideUserRoot && !insideProjectRoot) { return yield* new ProviderExtensionsError({ message: "Skill is not in a skills folder Threadlines manages.", }); @@ -4641,19 +4764,35 @@ export const deleteProviderExtensionSkill = Effect.fn( ), ); forgetReportedSkillPath(skillPath); + const deletedProvider = yield* resolveProviderActionConfig({ + providerInstanceId: input.request.providerInstanceId, + settings: input.settings, + }).pipe(Effect.catch(() => Effect.succeed(null))); + if (deletedProvider) { + yield* syncOtherProviderAfterSkillMutation({ + instanceId: input.request.providerInstanceId, + config: deletedProvider, + processEnv: mergeProviderInstanceEnvironment(deletedProvider.environment, process.env), + stateDir: input.stateDir, + }); + } return { deleted: true }; }); /** - * Codex has a first-class per-skill toggle. Claude has no skill toggle, but it auto-loads each - * folder in the user skills dir as a `@skills-dir` plugin, so the normal plugin - * enable/disable path reaches it. + * Toggles a skill's enabled state using each provider's native or profile mechanism: + * - Codex: first-class `skills/config/write` + * - Claude: `@skills-dir` plugin enable/disable for personal skills + * - Grok: `[skills] ignore` in `/config.toml` + * - Local OpenCode: `policies` (`action: "skill.use"`) in `/opencode.json` + * - Antigravity: per-skill profile symlinks in Threadlines' isolated `GEMINI_HOME` */ export const setProviderExtensionSkillEnabled = Effect.fn( "providerExtensions.setProviderExtensionSkillEnabled", )(function* (input: { readonly request: ProviderExtensionSkillToggleInput; readonly settings: ServerSettings; + readonly stateDir?: string | undefined; }): Effect.fn.Return< ProviderExtensionSkillToggleResult, ProviderExtensionsError, @@ -4689,6 +4828,26 @@ export const setProviderExtensionSkillEnabled = Effect.fn( return { effectiveEnabled: input.request.enabled }; } + if (providerConfig.driver !== CODEX_DRIVER) { + const skillPath = optionalText(input.request.path); + if (!skillPath) { + return yield* new ProviderExtensionsError({ + message: "Skill path is required.", + }); + } + const effectiveEnabled = yield* setOtherProviderSkillEnabled({ + instanceId: input.request.providerInstanceId, + config: providerConfig, + snapshot: undefined, + processEnv: mergeProviderInstanceEnvironment(providerConfig.environment, process.env), + projectCwd: optionalText(input.request.cwd), + stateDir: input.stateDir, + skillPath, + enabled: input.request.enabled, + }).pipe(Effect.mapError((message) => new ProviderExtensionsError({ message }))); + return { effectiveEnabled }; + } + const params = codexSkillConfigWriteParams(input.request); if (!params) { return yield* new ProviderExtensionsError({ @@ -4751,19 +4910,29 @@ export const readProviderExtensionSkill = Effect.fn( }): Effect.fn.Return< ProviderExtensionSkillReadResult, ProviderExtensionsError, - FileSystem.FileSystem + FileSystem.FileSystem | Path.Path > { - yield* resolveProviderActionConfig({ + const providerConfig = yield* resolveProviderActionConfig({ providerInstanceId: input.request.providerInstanceId, settings: input.settings, }); - if (!isCurrentProviderExtensionSkillPath(input.request.path)) { + if (isExternalOpenCodeConfig(providerConfig)) { + return yield* new ProviderExtensionsError({ + message: "Remote OpenCode skills cannot be read from this machine.", + }); + } + const reportedEntry = findReportedExtensionSkillEntry( + input.request.path, + input.request.providerInstanceId, + ); + if (!reportedEntry) { return yield* new ProviderExtensionsError({ message: "Skill is not in the current provider extensions inventory.", }); } const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const linkTarget = yield* fileSystem .readLink(input.request.path) .pipe(Effect.catch(() => Effect.succeed(null))); @@ -4773,6 +4942,16 @@ export const readProviderExtensionSkill = Effect.fn( "Skill contents could not be read because the inventory entry is not a regular file.", }); } + if (reportedEntry.boundary) { + const realTarget = yield* fileSystem + .realPath(input.request.path) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!realTarget || !isPathWithinBoundary(path, reportedEntry.boundary, realTarget)) { + return yield* new ProviderExtensionsError({ + message: "Skill contents could not be read outside the project boundary.", + }); + } + } const stat = yield* fileSystem .stat(input.request.path) @@ -5364,30 +5543,46 @@ export const readProviderExtensionsInventory = Effect.fn( readonly request: ProviderExtensionsInventoryInput; readonly settings: ServerSettings; readonly providers: ReadonlyArray; + readonly stateDir?: string | undefined; }): Effect.fn.Return< ProviderExtensionsInventoryResult, ProviderExtensionsError, FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner > { const generatedAt = yield* Effect.map(DateTime.now, DateTime.formatIso); - const cwd = input.request.cwd ?? machineScopeCwd(); + const projectCwd = optionalText(input.request.cwd); + const cwd = projectCwd ?? machineScopeCwd(); const configMap = deriveProviderInstanceConfigMap(input.settings); const snapshotsByInstanceId = new Map( input.providers.map((provider) => [provider.instanceId, provider]), ); + const requestedInstanceId = + input.request.providerInstanceId !== undefined + ? String(input.request.providerInstanceId) + : undefined; const providerEntries = Object.entries(configMap) .map(([id, config]) => ({ instanceId: ProviderInstanceId.make(id), config, })) - .filter( - (entry) => entry.config.driver === CODEX_DRIVER || entry.config.driver === CLAUDE_DRIVER, - ) - .filter( - (entry) => - input.request.providerInstanceId === undefined || - String(entry.instanceId) === String(input.request.providerInstanceId), - ); + .filter((entry) => { + if (requestedInstanceId !== undefined) { + return String(entry.instanceId) === requestedInstanceId; + } + if (entry.config.driver === CODEX_DRIVER || entry.config.driver === CLAUDE_DRIVER) { + return true; + } + const snapshot = snapshotsByInstanceId.get(entry.instanceId); + if (!resolveOtherProviderEnabled(entry.config, snapshot)) { + return false; + } + // On unfiltered machine views, omit non-Codex/Claude providers that are not installed/ready + // so uninstalled drivers do not clutter the provider picker with empty rows. + if (snapshot && snapshot.status === "error" && !snapshot.installed) { + return false; + } + return true; + }); const [providers, instructionFiles] = yield* Effect.all( [ @@ -5396,8 +5591,7 @@ export const readProviderExtensionsInventory = Effect.fn( (entry) => { const scopedProviderThreadId = input.request.providerThreadId !== undefined && - (input.request.providerInstanceId === undefined || - String(input.request.providerInstanceId) === String(entry.instanceId)) + (requestedInstanceId === undefined || String(entry.instanceId) === requestedInstanceId) ? input.request.providerThreadId : undefined; return readProviderInventory({ @@ -5405,6 +5599,8 @@ export const readProviderExtensionsInventory = Effect.fn( config: entry.config, snapshot: snapshotsByInstanceId.get(entry.instanceId), cwd, + projectCwd, + stateDir: input.stateDir, providerThreadId: scopedProviderThreadId, includeMcpServers: input.request.includeMcpServers, includeApps: input.request.includeApps, @@ -5419,24 +5615,34 @@ export const readProviderExtensionsInventory = Effect.fn( message: error.message, plugins: [], marketplaces: [], - skills: fallbackSkillsFromSnapshot(snapshotsByInstanceId.get(entry.instanceId)), + skills: + entry.config.driver === CODEX_DRIVER || entry.config.driver === CLAUDE_DRIVER + ? fallbackSkillsFromSnapshot(snapshotsByInstanceId.get(entry.instanceId)) + : [], mcpServers: [], apps: [], }), ), ); }, - { concurrency: 3 }, + { concurrency: 6 }, ), readInstructionFiles(cwd), ], { concurrency: "unbounded" }, ); + const fileSystem = yield* FileSystem.FileSystem; + const repoRoot = projectCwd ? yield* findRepositoryRoot(projectCwd) : undefined; + const projectBoundary = repoRoot + ? yield* fileSystem.realPath(repoRoot).pipe(Effect.catch(() => Effect.succeed(repoRoot))) + : undefined; + recordReportedExtensionPaths( // A store load reports icons an installed-only load does not, so they keep separate entries. `${cwd}\u0000${input.request.includePluginCatalog === false ? "installed" : "catalog"}`, providers, + projectBoundary, ); return { diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 6cc230c5b..0d5246938 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2335,6 +2335,7 @@ const makeCoreRpcLayer = ( request: input, settings, providers, + stateDir: config.stateDir, }); }), { "rpc.aggregate": "server" }, @@ -2368,9 +2369,11 @@ const makeCoreRpcLayer = ( WS_METHODS.serverSetProviderExtensionSkillEnabled, Effect.gen(function* () { const settings = yield* loadProviderExtensionSettings; - return yield* setProviderExtensionSkillEnabled({ request: input, settings }).pipe( - Effect.tap(() => noteExtensionsChanged(input)), - ); + return yield* setProviderExtensionSkillEnabled({ + request: input, + settings, + stateDir: config.stateDir, + }).pipe(Effect.tap(() => noteExtensionsChanged(input))); }), { "rpc.aggregate": "server" }, ), @@ -2388,9 +2391,11 @@ const makeCoreRpcLayer = ( WS_METHODS.serverCreateProviderExtensionSkill, Effect.gen(function* () { const settings = yield* loadProviderExtensionSettings; - return yield* createProviderExtensionSkill({ request: input, settings }).pipe( - Effect.tap(() => noteExtensionsChanged(input)), - ); + return yield* createProviderExtensionSkill({ + request: input, + settings, + stateDir: config.stateDir, + }).pipe(Effect.tap(() => noteExtensionsChanged(input))); }), { "rpc.aggregate": "server" }, ), @@ -2399,9 +2404,11 @@ const makeCoreRpcLayer = ( WS_METHODS.serverDeleteProviderExtensionSkill, Effect.gen(function* () { const settings = yield* loadProviderExtensionSettings; - return yield* deleteProviderExtensionSkill({ request: input, settings }).pipe( - Effect.tap(() => noteExtensionsChanged(input)), - ); + return yield* deleteProviderExtensionSkill({ + request: input, + settings, + stateDir: config.stateDir, + }).pipe(Effect.tap(() => noteExtensionsChanged(input))); }), { "rpc.aggregate": "server" }, ), diff --git a/apps/web/src/components/settings/ExtensionsSettings.logic.test.ts b/apps/web/src/components/settings/ExtensionsSettings.logic.test.ts index a254324ce..7c72b9bd0 100644 --- a/apps/web/src/components/settings/ExtensionsSettings.logic.test.ts +++ b/apps/web/src/components/settings/ExtensionsSettings.logic.test.ts @@ -24,10 +24,16 @@ import { extensionTextMatchesFilter, extensionProviderDriverSortRank, formatExtensionGroupLabel, + isExtensionInventoryProviderActive, isLikelyLocalPath, isProviderCoverageMissing, makeExtensionInventoryCacheKey, mergeRefreshedProviders, + providerSupportsApps, + providerSupportsHooks, + providerSupportsMcpServers, + providerSupportsPlugins, + providerSupportsSkillCreate, formatSkillDisplayName, groupExtensionSkills, bucketSkillsByPlugin, @@ -883,4 +889,43 @@ describe("ExtensionsSettings scope", () => { ); expect(resolveExtensionScope(deriveExtensionScopeGroups([], [], []), null)).toBeNull(); }); + + it("derives provider extension capabilities with safe defaults for older servers", () => { + const legacyCodex = { driver: ProviderDriverKind.make("codex") }; + const legacyClaude = { driver: ProviderDriverKind.make("claudeAgent") }; + const legacyAntigravity = { driver: ProviderDriverKind.make("antigravity") }; + const cursor = { + driver: ProviderDriverKind.make("cursor"), + capabilities: { + plugins: false, + mcpServers: true, + apps: false, + hooks: false, + skillCreate: true, + }, + }; + + expect(providerSupportsPlugins(legacyCodex)).toBe(true); + expect(providerSupportsApps(legacyCodex)).toBe(true); + expect(providerSupportsPlugins(legacyClaude)).toBe(true); + expect(providerSupportsApps(legacyClaude)).toBe(false); + expect(providerSupportsHooks(legacyClaude)).toBe(true); + expect(providerSupportsPlugins(legacyAntigravity)).toBe(false); + expect(providerSupportsMcpServers(legacyAntigravity)).toBe(false); + expect(providerSupportsSkillCreate(legacyAntigravity)).toBe(false); + + expect(providerSupportsPlugins(cursor)).toBe(false); + expect(providerSupportsMcpServers(cursor)).toBe(true); + expect(providerSupportsSkillCreate(cursor)).toBe(true); + + expect(isExtensionInventoryProviderActive({ status: "ready" })).toBe(true); + expect(isExtensionInventoryProviderActive({ status: "disabled" })).toBe(false); + expect(isExtensionInventoryProviderActive({ status: "unsupported" })).toBe(false); + expect(extensionProviderDriverSortRank("codex")).toBeLessThan( + extensionProviderDriverSortRank("antigravity"), + ); + expect(extensionProviderDriverSortRank("antigravity")).toBeLessThan( + extensionProviderDriverSortRank("cursor"), + ); + }); }); diff --git a/apps/web/src/components/settings/ExtensionsSettings.logic.ts b/apps/web/src/components/settings/ExtensionsSettings.logic.ts index e91910581..1fe2d07da 100644 --- a/apps/web/src/components/settings/ExtensionsSettings.logic.ts +++ b/apps/web/src/components/settings/ExtensionsSettings.logic.ts @@ -268,10 +268,60 @@ export function extensionBrowserStatusLine(input: { }; } +const EXTENSION_PROVIDER_DRIVER_ORDER: Readonly> = { + codex: 0, + claudeAgent: 1, + antigravity: 2, + grok: 3, + cursor: 4, + opencode: 5, + pi: 6, + muse: 7, + fx: 8, +}; + export function extensionProviderDriverSortRank(driverKind: string): number { - if (driverKind === "codex") return 0; - if (driverKind === "claudeAgent") return 1; - return 2; + return EXTENSION_PROVIDER_DRIVER_ORDER[driverKind] ?? 9; +} + +function isLegacyManagedDriver(driver: string): boolean { + return driver === "codex" || driver === "claudeAgent"; +} + +export function isExtensionInventoryProviderActive( + provider: Pick, +): boolean { + return provider.status !== "disabled" && provider.status !== "unsupported"; +} + +export function providerSupportsPlugins( + provider: Pick, +): boolean { + return provider.capabilities?.plugins ?? isLegacyManagedDriver(String(provider.driver)); +} + +export function providerSupportsMcpServers( + provider: Pick, +): boolean { + return provider.capabilities?.mcpServers ?? isLegacyManagedDriver(String(provider.driver)); +} + +export function providerSupportsApps( + provider: Pick, +): boolean { + return provider.capabilities?.apps ?? String(provider.driver) === "codex"; +} + +export function providerSupportsHooks( + provider: Pick, +): boolean { + return provider.capabilities?.hooks ?? isLegacyManagedDriver(String(provider.driver)); +} + +export function providerSupportsSkillCreate( + provider: Pick, +): boolean { + return provider.capabilities?.skillCreate ?? isLegacyManagedDriver(String(provider.driver)); } const EXTENSION_BROWSER_MAX_SINGLETON_GROUP_RATIO = 0.6; diff --git a/apps/web/src/components/settings/ExtensionsSettings.tsx b/apps/web/src/components/settings/ExtensionsSettings.tsx index 170e45275..2a227648b 100644 --- a/apps/web/src/components/settings/ExtensionsSettings.tsx +++ b/apps/web/src/components/settings/ExtensionsSettings.tsx @@ -89,10 +89,15 @@ import { selectCuratedPlugins, shouldCuratePluginBrowse, groupPluginComponents, + isExtensionInventoryProviderActive, isLikelyLocalPath, isProviderCoverageMissing, mergeRefreshedProviders, makeExtensionInventoryCacheKey, + providerSupportsApps, + providerSupportsMcpServers, + providerSupportsPlugins, + providerSupportsSkillCreate, type ExtensionScopeGroup, type ExtensionScopeSelection, type PluginComponentTarget, @@ -901,7 +906,9 @@ function ExtensionItemBadges({ } function extensionOpenPath(item: ExtensionItem): string | null { - if (item.kind === "skill") return item.skill.path; + if (item.kind === "skill") { + return item.skill.canRead === false ? null : item.skill.path; + } if (item.kind === "plugin" && isLikelyLocalPath(item.plugin.installPath)) { return item.plugin.installPath ?? null; } @@ -1093,6 +1100,30 @@ function openPathInEditor(targetPath: string, workspaceRoot: string) { }); } +function revealPathInFileManager(targetPath: string) { + let api: ReturnType; + try { + api = ensureLocalApi(); + } catch (error) { + toastManager.add( + failureNotice({ + title: "Couldn't open the folder", + error, + }), + ); + return; + } + + void api.shell.openInEditor(targetPath, "file-manager").catch((error) => { + toastManager.add( + failureNotice({ + title: "Couldn't open the folder", + error, + }), + ); + }); +} + function DetailRow({ label, value, @@ -1471,7 +1502,8 @@ function PluginComponents({ /** What an action changed, so the page reloads just that provider (see refreshAfterMutation). */ interface ExtensionInventoryChange { - readonly providerInstanceId: string; + /** Omit to refresh every provider in scope (e.g. shared skill folders across providers). */ + readonly providerInstanceId?: string | undefined; /** Plugins can bring MCP servers with them; skills cannot. */ readonly affectsConnections: boolean; } @@ -1508,7 +1540,13 @@ function ExtensionDetailDialog({ onActionHistoryChange: (itemKey: string, entry: ExtensionActionHistoryEntry) => void; }) { const providersApi = useScopedProvidersApi(); + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const isLocalMachine = environmentId === null || environmentId === primaryEnvironmentId; const openPath = item ? extensionOpenPath(item) : null; + const skillConfigPath = + item?.kind === "skill" && item.skill.configPath && isLikelyLocalPath(item.skill.configPath) + ? item.skill.configPath + : null; const [busyAction, setBusyAction] = useState(null); const [actionOutput, setActionOutput] = useState(null); const [selectedTool, setSelectedTool] = useState(null); @@ -1520,6 +1558,10 @@ function ExtensionDetailDialog({ const [skillContents, setSkillContents] = useState({ status: "idle" }); const pollRef = useRef(0); const managedClaudePlugin = useMemo(() => findManagedClaudePluginForMcp(item), [item]); + const skillOwningPlugin = useMemo(() => { + if (!item || item.kind !== "skill" || !item.skill.bundleId) return null; + return item.provider.plugins.find((plugin) => plugin.id === item.skill.bundleId) ?? null; + }, [item]); useEffect(() => { setBusyAction(null); @@ -1532,7 +1574,7 @@ function ExtensionDetailDialog({ setPluginDetailAttempt(0); setSkillContents({ status: "idle" }); pollRef.current += 1; - }, [item?.kind, item?.id]); + }, [item?.kind, item?.id, item?.provider.instanceId]); // A plugin's component inventory needs a provider round trip, so it loads with the dialog rather // than behind a button: "what does this add" is the question the dialog exists to answer. @@ -1563,7 +1605,7 @@ function ExtensionDetailDialog({ }, [cwd, item, pluginDetailAttempt, providersApi]); useEffect(() => { - if (!item || item.kind !== "skill") return; + if (!item || item.kind !== "skill" || item.skill.canRead === false) return; let cancelled = false; setSkillContents({ status: "loading" }); @@ -1766,7 +1808,7 @@ function ExtensionDetailDialog({ ...actionBaseInput(item, cwd), path: item.skill.path, }); - await onInventoryMutated(inventoryChangeFor(item, false)); + await onInventoryMutated({ affectsConnections: false }); // The item this dialog is bound to no longer exists, so there is nothing left to show. onClose(); return "Skill deleted."; @@ -1830,6 +1872,21 @@ function ExtensionDetailDialog({ }); }, [cwd, item, onInventoryMutated, providersApi, runDialogAction]); + const toggleSkillOwningPlugin = useCallback(() => { + if (!item || !skillOwningPlugin) return; + const nextEnabled = !(skillOwningPlugin.enabled ?? true); + void runDialogAction(nextEnabled ? "Enable plugin" : "Disable plugin", async () => { + const result = await providersApi().setExtensionPluginEnabled({ + ...actionBaseInput(item, cwd), + pluginId: skillOwningPlugin.id, + ...(skillOwningPlugin.scope ? { scope: skillOwningPlugin.scope } : {}), + enabled: nextEnabled, + }); + await onInventoryMutated(inventoryChangeFor(item, true)); + return `Plugin ${result.effectiveEnabled ? "enabled" : "disabled"}.`; + }); + }, [cwd, item, onInventoryMutated, providersApi, runDialogAction, skillOwningPlugin]); + const readManagedClaudePlugin = useCallback(() => { if (!item || !managedClaudePlugin) return; void runDialogAction("Plugin details", async () => { @@ -2105,6 +2162,16 @@ function ExtensionDetailDialog({ + + ) : null} {item.kind === "mcp" ? ( @@ -2135,6 +2202,17 @@ function ExtensionDetailDialog({ ) : null} ) : null} + {item.kind === "skill" && (item.skill.toggleNotice || item.skill.resolvedPath) ? ( +
+ {item.skill.toggleNotice ?

{item.skill.toggleNotice}

: null} + {item.skill.resolvedPath ? ( +

+ Shared through a symlink. Editing or deleting this skill affects other tools + using that folder. +

+ ) : null} +
+ ) : null} {item.kind === "skill" ? (
@@ -2157,6 +2235,11 @@ function ExtensionDetailDialog({
) : null} + {item.skill.canRead === false ? ( +
+ This skill lives on a remote server and cannot be read from this machine. +
+ ) : null} {skillContents.status === "loading" ? (
@@ -2393,6 +2476,36 @@ function ExtensionDetailDialog({ {item.skill.enabled === false ? "Enable" : "Disable"} ) : null} + {item.kind === "skill" && skillOwningPlugin ? ( + <> + + {skillOwningPlugin.installed === true ? ( + + ) : null} + + ) : null} {item.kind === "skill" && item.skill.canDelete === true ? ( ) : null} + {isLocalMachine && openPath ? ( + <> + + + + ) : null} ) : null} @@ -2940,19 +3073,21 @@ function InstalledPluginsList({ items, environmentId, busyPluginId, + emptyLabel = "No plugins installed.", onSelect, onToggle, }: { items: ReadonlyArray>; environmentId: EnvironmentId | null; busyPluginId: string | null; + emptyLabel?: string; onSelect: (item: ExtensionItem) => void; onToggle: (item: Extract, nextEnabled: boolean) => void; }) { if (items.length === 0) { return ( - + ); } @@ -3193,11 +3328,13 @@ function ConnectionsTable({ items, environmentId, isLoading, + emptyLabel = "No connections configured.", onSelect, }: { items: ReadonlyArray; environmentId: EnvironmentId | null; isLoading: boolean; + emptyLabel?: string; onSelect: (item: ExtensionItem) => void; }) { if (items.length === 0) { @@ -3208,7 +3345,7 @@ function ConnectionsTable({ Reading connections
) : ( -
No connections configured.
+
{emptyLabel}
); } @@ -3890,10 +4027,33 @@ function ExtensionBrowserDialog({ ); } +function skillToggleUnavailableReason( + item: Extract, + followsPlugin: boolean, +): string { + if (item.skill.toggleNotice) { + return item.skill.toggleNotice; + } + if (item.skill.canRead === false) { + return "Managed on the remote server."; + } + if (followsPlugin || item.skill.bundleId !== undefined) { + const bundleLabel = item.skill.bundleDisplayName ?? item.skill.bundleName; + return bundleLabel + ? `Controlled by the ${bundleLabel} plugin. Click to manage.` + : "Controlled by its plugin. Click to manage."; + } + if (String(item.provider.driver) === "claudeAgent") { + return "Claude only toggles personal skills. Click to reveal folder."; + } + return `${providerTitle(item.provider)} loads this skill from disk. Click to reveal or remove.`; +} + /** - * One skill, as a row. The control on the right is whatever the server says this skill supports: - * a switch when it can be toggled, otherwise a status badge. Bundled skills follow their plugin, - * so they read as status rather than offering a control that would not apply. + * One skill, as a row. The control on the right matches the switch column across the list: + * an interactive switch when the skill can be toggled, or a disabled switch with a tooltip + * explaining why it is locked (bundled with a plugin, project-scoped, or unsupported by the + * provider). */ function SkillListRow({ item, @@ -3949,9 +4109,23 @@ function SkillListRow({ onCheckedChange={(checked) => onToggle(item, Boolean(checked))} /> ) : ( - - {enabled ? "On" : "Off"} - + + + + + } + /> + + {skillToggleUnavailableReason(item, onToggle === undefined)} + + )} ); @@ -4042,16 +4216,30 @@ function SkillPluginGroup({ onCheckedChange={(checked) => onTogglePlugin(Boolean(checked))} /> ) : ( - - {enabled ? "On" : "Off"} - + + + + + } + /> + + Plugin state cannot be changed here. + + )} {expanded ? (
{bucket.matching.map((item) => ( next !== null && choose(next)}> - {selectedOption?.label ?? "All providers"} + + {selectedOption ? ( + + + {selectedOption.label} + + ) : ( + "All providers" + )} + All providers @@ -4465,13 +4667,7 @@ export function ExtensionsSettingsPanel() { const localProviderEntries = useMemo( () => sortProviderInstanceEntries(deriveProviderInstanceEntries(serverProviders)) - .filter( - (provider) => - provider.enabled && - provider.isAvailable && - (provider.driverKind === EXTENSIONS_CODEX_DRIVER || - provider.driverKind === EXTENSIONS_CLAUDE_DRIVER), - ) + .filter((provider) => provider.enabled && provider.isAvailable) .toSorted( (left, right) => extensionProviderDriverSortRank(String(left.driverKind)) - @@ -4845,11 +5041,18 @@ export function ExtensionsSettingsPanel() { if (!requestProviderInstanceId && requestEnvironmentId) { setRemoteProviders({ environmentId: requestEnvironmentId, - options: result.providers.map((provider) => ({ - value: String(provider.instanceId), - label: provider.displayName ?? String(provider.driver), - driver: String(provider.driver), - })), + options: result.providers + .filter(isExtensionInventoryProviderActive) + .toSorted( + (left, right) => + extensionProviderDriverSortRank(String(left.driver)) - + extensionProviderDriverSortRank(String(right.driver)), + ) + .map((provider) => ({ + value: String(provider.instanceId), + label: provider.displayName ?? String(provider.driver), + driver: String(provider.driver), + })), }); } setInventory(result); @@ -4941,7 +5144,9 @@ export function ExtensionsSettingsPanel() { async (change?: ExtensionInventoryChange) => { await refresh({ invalidateCache: true, - ...(change ? { onlyProviderInstanceId: change.providerInstanceId } : {}), + ...(change?.providerInstanceId + ? { onlyProviderInstanceId: change.providerInstanceId } + : {}), ...(change && !change.affectsConnections ? { includeMcpServers: false } : {}), }); }, @@ -4992,8 +5197,10 @@ export function ExtensionsSettingsPanel() { const providerScopedInventory = useMemo( () => - (inventory?.providers ?? []).filter( - (provider) => !providerInstanceId || String(provider.instanceId) === providerInstanceId, + (inventory?.providers ?? []).filter((provider) => + providerInstanceId + ? String(provider.instanceId) === providerInstanceId + : isExtensionInventoryProviderActive(provider), ), [inventory, providerInstanceId], ); @@ -5092,17 +5299,23 @@ export function ExtensionsSettingsPanel() { [cwd, refresh, scopeEnvironmentId], ); const skillCreateProviders = useMemo( - () => - providerScopedInventory.filter( - (provider) => isCodexProvider(provider) || isClaudeProvider(provider), - ), + () => providerScopedInventory.filter(providerSupportsSkillCreate), + [providerScopedInventory], + ); + const pluginCapableProviders = useMemo( + () => providerScopedInventory.filter(providerSupportsPlugins), + [providerScopedInventory], + ); + const mcpCapableProviders = useMemo( + () => providerScopedInventory.filter(providerSupportsMcpServers), [providerScopedInventory], ); const toggleSkillRow = useCallback( async (item: Extract, nextEnabled: boolean) => { const providersApi = readScopedProvidersApi(scopeEnvironmentId); if (!providersApi) return; - setBusySkillPath(item.skill.path); + const busyKey = `${item.provider.instanceId}:${item.skill.path}`; + setBusySkillPath(busyKey); try { await providersApi.setExtensionSkillEnabled({ ...actionBaseInput(item, cwd), @@ -5118,15 +5331,15 @@ export function ExtensionsSettingsPanel() { }), ); } finally { - setBusySkillPath((current) => (current === item.skill.path ? null : current)); + setBusySkillPath((current) => (current === busyKey ? null : current)); } }, [cwd, refresh, scopeEnvironmentId], ); - // Apps are a Codex concept; the Claude driver always reports an empty list. + // Apps are a Codex concept; other drivers report an empty list. const codexProviders = useMemo( - () => providerScopedInventory.filter(isCodexProvider), + () => providerScopedInventory.filter(providerSupportsApps), [providerScopedInventory], ); const allAppItems = useMemo( @@ -5466,19 +5679,14 @@ export function ExtensionsSettingsPanel() { - - Browse catalog - + pluginCapableProviders.length > 0 ? ( + + ) : undefined } >
@@ -5489,6 +5697,11 @@ export function ExtensionsSettingsPanel() { items={searchedInstalledPlugins} environmentId={selectedEnvironmentId} busyPluginId={busyPluginId} + emptyLabel={ + pluginCapableProviders.length === 0 && providerScopedInventory.length > 0 + ? `${selectedProviderOption?.label ?? "Selected providers"} does not manage plugins here.` + : "No plugins installed." + } onSelect={setSelectedItem} onToggle={(target, nextEnabled) => void togglePluginRow(target, nextEnabled)} /> @@ -5538,15 +5751,12 @@ export function ExtensionsSettingsPanel() { Refreshing ) : null} - + {skillCreateProviders.length > 0 ? ( + + ) : null}
} > @@ -5560,18 +5770,21 @@ export function ExtensionsSettingsPanel() {
{group.label}
- {group.items.map((item) => ( - - void toggleSkillRow(target, nextEnabled) - } - /> - ))} + {group.items.map((item) => { + const rowKey = `${item.provider.instanceId}:${item.skill.path}`; + return ( + + void toggleSkillRow(target, nextEnabled) + } + /> + ); + })}
))} {skillPluginBuckets.length > 0 ? ( @@ -5637,14 +5850,14 @@ export function ExtensionsSettingsPanel() { ? "Add a computer or a project to inspect skills." : "Reconnect this machine to inspect its skills." : isLoading - ? "Reading skills from Codex and Claude." + ? "Reading skills from configured providers." : error ? "The inventory could not be loaded. Details are shown above." : allSkillItems.length > 0 ? "No skill matches the search above." : scopeCwd === null - ? "Neither provider reported skills on this machine." - : "Neither provider reported skills for this project." + ? "No skills were reported on this machine." + : "No skills were reported for this project." } /> )} @@ -5687,6 +5900,11 @@ export function ExtensionsSettingsPanel() { mcpLoadingProviderId !== null || mcpDeferredProvider !== undefined } + emptyLabel={ + mcpCapableProviders.length === 0 && providerScopedInventory.length > 0 + ? `${selectedProviderOption?.label ?? "Selected providers"} does not report MCP connections here.` + : "No connections configured." + } onSelect={setSelectedItem} /> )} @@ -5703,7 +5921,7 @@ export function ExtensionsSettingsPanel() { {allHookRows.length > 0 || hookMessages.length > 0 ? (
@@ -5716,103 +5934,107 @@ export function ExtensionsSettingsPanel() { ) : null} - - {marketplaceSummary ? ( - - {marketplaceSummary} - - } - control={ - - } - > - {showMarketplaces ? ( -
- {providerScopedInventory.map((provider) => ( - 0 ? ( + + {marketplaceSummary ? ( + + {marketplaceSummary} + + } + control={ +
- ) : null} -
- ) : null} - - - {providerThreadContextSource === "manual" - ? "Manual" - : providerThreadContextSource === "auto" - ? "Auto" - : "No context"} - - -
- } - > - {showAdvancedContext ? ( -
-
-
- Detected context + Manage + + } + > + {showMarketplaces ? ( +
+ {pluginCapableProviders.map((provider) => ( + + ))}
-
- {detectedProviderThreadId || "No active Codex thread detected"} + ) : null} + + ) : null} + {codexProviders.length > 0 ? ( + + + {providerThreadContextSource === "manual" + ? "Manual" + : providerThreadContextSource === "auto" + ? "Auto" + : "No context"} + +
-

- Leave the override empty to use the detected active session. -

-
- { - setManualThreadOverride({ scopeKey, value: event.currentTarget.value }); - invalidateInventoryRefresh(); - }} - placeholder="override provider thread id" - className="w-full" - aria-label="Override provider thread id" - /> -
+ } + > + {showAdvancedContext ? ( +
+
+
+ Detected context +
+
+ {detectedProviderThreadId || "No active Codex thread detected"} +
+

+ Leave the override empty to use the detected active session. +

+
+ { + setManualThreadOverride({ scopeKey, value: event.currentTarget.value }); + invalidateInventoryRefresh(); + }} + placeholder="override provider thread id" + className="w-full" + aria-label="Override provider thread id" + /> +
+ ) : null} + ) : null} - - + + ) : null} ) : null} diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx index 2fa46d9f6..38466cb99 100644 --- a/apps/web/src/components/settings/SettingsPanels.browser.tsx +++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx @@ -113,6 +113,7 @@ import { openConnectComputerDialog, } from "./connections/JoinComputerDialog"; import { DiagnosticsSettingsPanel } from "./DiagnosticsSettings"; +import { ExtensionsSettingsPanel } from "./ExtensionsSettings"; import { ThreadCpuUsageSection } from "./ThreadCpuUsageSection"; import { AppearanceSettingsPanel } from "./AppearanceSettings"; import { GeneralSettingsPanel, ProviderSettingsPanel } from "./SettingsPanels"; @@ -8017,3 +8018,276 @@ describe("ProviderSettingsPanel suggestions", () => { ); }); }); + +describe("ExtensionsSettingsPanel multi-provider support", () => { + const envId = EnvironmentId.make("env-ext-local"); + + beforeEach(async () => { + resetAppAtomRegistryForTests(); + resetServerStateForTests(); + __resetEnvironmentApiOverridesForTests(); + await __resetLocalApiForTests(); + await resetTestPage(); + writePrimaryEnvironmentDescriptor({ + environmentId: envId, + label: "This device", + platform: { os: "darwin", arch: "arm64" }, + serverVersion: "0.11.0", + capabilities: { repositoryIdentity: true }, + }); + }); + + afterEach(async () => { + __resetEnvironmentApiOverridesForTests(); + resetPrimaryEnvironmentDescriptorForTests(); + resetServerStateForTests(); + await __resetLocalApiForTests(); + await resetTestPage(); + }); + + it("lists all enabled providers, hides unsupported plugin controls, and renders shared-path skills across providers", async () => { + const sharedSkillPath = "/Users/will/claude-dotfiles/skills/gemini-frontend-design/SKILL.md"; + const providers: ReadonlyArray = [ + { ...createOutdatedProvider("codex"), displayName: "Codex" }, + { ...createOutdatedProvider("claudeAgent"), displayName: "Claude" }, + { ...createOutdatedProvider("antigravity"), displayName: "Antigravity" }, + { ...createOutdatedProvider("grok"), displayName: "Grok" }, + { ...createOutdatedProvider("cursor"), displayName: "Cursor" }, + ]; + setServerConfigSnapshot({ + ...createBaseServerConfig(), + providers, + }); + + const fullInventory = { + generatedAt: "2026-11-24T12:00:00.000Z", + instructionFiles: [], + providers: [ + { + instanceId: ProviderInstanceId.make("codex"), + driver: ProviderDriverKind.make("codex"), + displayName: "Codex", + status: "ready" as const, + capabilities: { + plugins: true, + mcpServers: true, + apps: true, + hooks: true, + skillCreate: true, + }, + plugins: [], + marketplaces: [], + skills: [], + mcpServers: [], + mcpServersStatus: "ready" as const, + apps: [], + appsStatus: "ready" as const, + appsCatalogStatus: "ready" as const, + }, + { + instanceId: ProviderInstanceId.make("claudeAgent"), + driver: ProviderDriverKind.make("claudeAgent"), + displayName: "Claude", + status: "ready" as const, + capabilities: { + plugins: true, + mcpServers: true, + apps: false, + hooks: true, + skillCreate: true, + }, + plugins: [], + marketplaces: [], + skills: [ + { + name: "gemini-frontend-design", + path: sharedSkillPath, + scope: "user", + enabled: true, + canToggle: true, + canDelete: true, + }, + ], + mcpServers: [], + mcpServersStatus: "ready" as const, + apps: [], + }, + { + instanceId: ProviderInstanceId.make("antigravity"), + driver: ProviderDriverKind.make("antigravity"), + displayName: "Antigravity", + status: "ready" as const, + capabilities: { + plugins: false, + mcpServers: false, + apps: false, + hooks: false, + skillCreate: true, + }, + plugins: [], + marketplaces: [], + skills: [ + { + name: "gemini-frontend-design", + path: "/Users/will/.gemini/config/skills/gemini-frontend-design/SKILL.md", + resolvedPath: sharedSkillPath, + scope: "user", + enabled: true, + canToggle: true, + canDelete: true, + toggleNotice: + "Applies inside Threadlines only. Terminal agy sessions still load ~/.gemini/config/skills.", + }, + ], + mcpServers: [], + apps: [], + }, + { + instanceId: ProviderInstanceId.make("grok"), + driver: ProviderDriverKind.make("grok"), + displayName: "Grok", + status: "ready" as const, + capabilities: { + plugins: false, + mcpServers: false, + apps: false, + hooks: false, + skillCreate: true, + }, + plugins: [], + marketplaces: [], + skills: [ + { + name: "gemini-frontend-design", + path: "/Users/will/.grok/skills/gemini-frontend-design/SKILL.md", + resolvedPath: sharedSkillPath, + configPath: "/Users/will/.grok/config.toml", + scope: "user", + enabled: true, + canToggle: true, + canDelete: true, + }, + ], + mcpServers: [], + apps: [], + }, + { + instanceId: ProviderInstanceId.make("cursor"), + driver: ProviderDriverKind.make("cursor"), + displayName: "Cursor", + status: "ready" as const, + capabilities: { + plugins: false, + mcpServers: true, + apps: false, + hooks: false, + skillCreate: true, + }, + plugins: [], + marketplaces: [], + skills: [ + { + name: "cursor-only-skill", + path: "/Users/will/.cursor/skills/cursor-only-skill/SKILL.md", + scope: "user", + enabled: true, + canDelete: true, + }, + ], + mcpServers: [ + { + name: "supabase", + origin: { kind: "user" as const }, + transport: "http", + status: "Configured", + detail: "https://mcp.supabase.com/mcp", + }, + ], + mcpServersStatus: "ready" as const, + apps: [], + }, + ], + }; + + __setEnvironmentApiOverrideForTests(envId, { + providers: { + getExtensions: vi.fn(async (input: { readonly providerInstanceId?: string }) => ({ + ...fullInventory, + providers: input.providerInstanceId + ? fullInventory.providers.filter( + (entry) => String(entry.instanceId) === input.providerInstanceId, + ) + : fullInventory.providers, + })), + readExtensionSkill: vi.fn(async () => ({ + contents: "# Skill body", + truncated: false, + })), + }, + } as unknown as EnvironmentApi); + + await renderWithTestRouter( + + + , + ); + + // Five enabled providers render as a dropdown (`> 3`) and surface Cursor's MCP connection. + const providerSelect = page.getByRole("combobox", { name: "Provider" }); + await expect.element(providerSelect).toBeInTheDocument(); + await expect.element(page.getByText("supabase")).toBeInTheDocument(); + await expect.element(page.getByRole("button", { name: "Browse catalog" })).toBeInTheDocument(); + + // Filtering to Antigravity hides Browse catalog and explains plugin/MCP capability cleanly. + await providerSelect.click(); + await page.getByRole("option", { name: "Antigravity" }).click(); + await expect + .element(page.getByText("Antigravity does not manage plugins here.")) + .toBeInTheDocument(); + await expect + .element(page.getByText("Antigravity does not report MCP connections here.")) + .toBeInTheDocument(); + await expect + .element(page.getByRole("button", { name: "Browse catalog" })) + .not.toBeInTheDocument(); + + // Switching back to All providers on the Skills tab shows interactive switches for Claude, + // Antigravity, and Grok, plus a disabled switch with tooltip for Cursor's disk-loaded skill. + await providerSelect.click(); + await page.getByRole("option", { name: "All providers" }).click(); + await page.getByRole("tab", { name: /Skills/i }).click(); + await vi.waitFor(() => { + const matches = [...document.querySelectorAll("button")].filter((el) => + el.textContent?.includes("gemini-frontend-design"), + ); + expect(matches.length).toBe(3); + const switches = [...document.querySelectorAll('[role="switch"]')]; + expect(switches.length).toBe(4); + const disabledSwitches = switches.filter( + (el) => el.getAttribute("aria-disabled") === "true" || el.hasAttribute("data-disabled"), + ); + expect(disabledSwitches.length).toBe(1); + }); + + // Hovering Cursor's disabled switch explains how to manage it. + const lockedSwitch = page.getByRole("switch", { + name: /cursor-only-skill \(enabled, cannot be toggled\)/i, + }); + await lockedSwitch.hover(); + await expect + .element(page.getByText("Cursor loads this skill from disk. Click to reveal or remove.")) + .toBeInTheDocument(); + + // Clicking Grok's skill opens the detail modal with Links to, Open config, and Reveal in folder. + const grokSkillButton = [...document.querySelectorAll("button")].find((el) => + el.textContent?.includes("/Users/will/.grok/skills/gemini-frontend-design/SKILL.md"), + ); + expect(grokSkillButton).toBeTruthy(); + grokSkillButton!.click(); + await expect.element(page.getByRole("button", { name: "Open config" })).toBeInTheDocument(); + await expect + .element(page.getByRole("button", { name: "Reveal in folder" })) + .toBeInTheDocument(); + await expect.element(page.getByText(/Shared through a symlink\./i)).toBeInTheDocument(); + }); +}); diff --git a/packages/contracts/src/providerExtensions.ts b/packages/contracts/src/providerExtensions.ts index 260f4b601..13d1c2f5f 100644 --- a/packages/contracts/src/providerExtensions.ts +++ b/packages/contracts/src/providerExtensions.ts @@ -164,6 +164,26 @@ export const ProviderExtensionSkill = Schema.Struct({ * to delete from. Never set for plugin-bundled or provider-shipped skills. */ canDelete: Schema.optional(Schema.Boolean), + /** + * False when the skill's file lives on a remote provider host rather than this machine, so the + * server will not read it from the local filesystem. Absent means readable when reported. + */ + canRead: Schema.optional(Schema.Boolean), + /** + * Canonical filesystem target when `path` or its skill folder is a symlink pointing elsewhere + * (for example, a shared dotfiles folder). Display-only so the user knows edits affect other tools. + */ + resolvedPath: Schema.optional(TrimmedNonEmptyString), + /** + * Provider configuration file that controls this skill's enabled state (for example, + * `~/.grok/config.toml` or `opencode.json`), when opening that file helps the user manage it. + */ + configPath: Schema.optional(TrimmedNonEmptyString), + /** + * Short note shown in the detail modal explaining toggle scope or why a toggle is locked + * (for example, Threadlines-only profile toggles or a project config overriding a user toggle). + */ + toggleNotice: Schema.optional(TrimmedString), }); export type ProviderExtensionSkill = typeof ProviderExtensionSkill.Type; @@ -294,12 +314,27 @@ export const ProviderExtensionHook = Schema.Struct({ }); export type ProviderExtensionHook = typeof ProviderExtensionHook.Type; +/** + * Which surfaces this provider instance actually manages on the Plugins & Skills page. + * Absent on older servers; clients fall back to Codex/Claude defaults when omitted. + */ +export const ProviderExtensionProviderCapabilities = Schema.Struct({ + plugins: Schema.optional(Schema.Boolean), + mcpServers: Schema.optional(Schema.Boolean), + apps: Schema.optional(Schema.Boolean), + hooks: Schema.optional(Schema.Boolean), + skillCreate: Schema.optional(Schema.Boolean), +}); +export type ProviderExtensionProviderCapabilities = + typeof ProviderExtensionProviderCapabilities.Type; + export const ProviderExtensionProviderInventory = Schema.Struct({ instanceId: ProviderInstanceId, driver: ProviderDriverKind, displayName: Schema.optional(TrimmedNonEmptyString), status: ProviderExtensionProviderStatus, message: Schema.optional(TrimmedString), + capabilities: Schema.optional(ProviderExtensionProviderCapabilities), plugins: Schema.Array(ProviderExtensionPlugin), marketplaces: Schema.Array(ProviderExtensionMarketplace), /** `deferred` means `plugins` holds only installed plugins; the store was not requested. */