fix(providers): discover workspace skills everywhere (#9180)

Co-authored-by: maria-rcks <[email protected]>
This commit is contained in:
mariaandmaria-rcks authored and GitHub committed 2026-09-02 20:07:31 -04:00
1 parent 443b4ebfe8
commit 15fea6c5f4
15 files changed
+698 -61

No files matched your search

@@ -1053,7 +1053,7 @@ export function NewTaskDraftScreen(props: {
multiline
scrollEnabled
value={flow.prompt}
skills={flow.selectedProviderStatus?.skills ?? []}
skills={composerMenu.skills}
selection={composerMenu.selection}
onChangeText={flow.setPrompt}
onSelectionChange={composerMenu.onSelectionChange}
@@ -652,7 +652,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
multiline
value={props.draftMessage}
readOnly={voiceInput.freezesEditor}
skills={selectedProviderStatus?.skills ?? []}
skills={composerMenu.skills}
selection={composerMenu.selection}
onChangeText={props.onChangeDraftMessage}
onSelectionChange={composerMenu.onSelectionChange}
@@ -5,6 +5,7 @@ import {
} from "@t3tools/client-runtime/codex-artifact-templates";
import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkills";
import type { LegendListRef } from "@legendapp/list/react-native";
import { HeaderHeightContext } from "@react-navigation/elements";
import type {
@@ -510,12 +511,14 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
const contentMaxWidth = isSplitLayout ? CHAT_CONTENT_MAX_WIDTH : undefined;
const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
const selectedProviderSkills = useMemo(
() =>
props.serverConfig?.providers.find((provider) => provider.instanceId === selectedInstanceId)
?.skills ?? [],
[props.serverConfig, selectedInstanceId],
);
const selectedProviderSkills = useMemo(() => {
const provider = props.serverConfig?.providers.find(
(candidate) => candidate.instanceId === selectedInstanceId,
);
return provider
? resolveProviderSkillsForCwd(provider, props.threadCwd ?? props.projectWorkspaceRoot)
: [];
}, [props.projectWorkspaceRoot, props.serverConfig, props.threadCwd, selectedInstanceId]);
useLayoutEffect(() => {
selectedThreadKeyRef.current = selectedThreadKey;
@@ -809,7 +812,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
serverConfig={props.serverConfig}
queueCount={props.selectedThreadQueueCount}
environmentId={props.environmentId}
projectCwd={props.projectWorkspaceRoot}
projectCwd={props.threadCwd ?? props.projectWorkspaceRoot}
bottomInset={composerBottomInset}
onChangeDraftMessage={props.onChangeDraftMessage}
onPickDraftMedia={props.onPickDraftMedia}
@@ -3,6 +3,12 @@ import { describe, expect, it, vi } from "vite-plus/test";
vi.mock("../../state/queries", () => ({
useComposerPathSearch: () => ({ entries: [], isPending: false }),
}));
vi.mock("../../state/server", () => ({
serverEnvironment: { refreshProviders: Symbol("refreshProviders") },
}));
vi.mock("../../state/use-atom-command", () => ({
useAtomCommand: () => vi.fn(),
}));
import { composerSelectionAtEnd } from "./use-composer-command-menu";
@@ -13,14 +13,19 @@ import {
dedupeProviderSkillsByName,
getProviderSkillsForSlashMenu,
isProviderSkillUserInvocable,
resolveProviderSkillsForCwd,
} from "@t3tools/client-runtime/providerSkills";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { ComposerEditorSelection } from "../../components/ComposerEditor";
import { serverEnvironment } from "../../state/server";
import { useAtomCommand } from "../../state/use-atom-command";
import { useComposerPathSearch } from "../../state/queries";
import type { ComposerCommandItem } from "./ComposerCommandPopover";
import { matchesSlashSkillQuery } from "./composerSlashSkillSearch";
const WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS = 10_000;
export function composerSelectionAtEnd(draftMessage: string): ComposerEditorSelection {
return { start: draftMessage.length, end: draftMessage.length };
}
@@ -69,6 +74,72 @@ export function useComposerCommandMenu({
setSelection(composerSelectionAtEnd(draftMessage));
}, [draftMessage, ownerKey]);
const skills = useMemo(
() =>
selectedProviderStatus ? resolveProviderSkillsForCwd(selectedProviderStatus, projectCwd) : [],
[projectCwd, selectedProviderStatus],
);
const slashCommands = selectedProviderStatus?.slashCommands ?? [];
const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
reportFailure: false,
});
const selectedProviderInstanceId = selectedProviderStatus?.instanceId;
const hasWorkspaceSnapshot = Boolean(
projectCwd &&
selectedProviderStatus?.workspaceSnapshots?.some((snapshot) => snapshot.cwd === projectCwd),
);
const workspaceRefreshKeyRef = useRef<string | null>(null);
const workspaceRefreshRetryRef = useRef<{ key: string; notBefore: number } | null>(null);
const hadWorkspaceSnapshotRef = useRef(false);
useEffect(() => {
if (hadWorkspaceSnapshotRef.current && !hasWorkspaceSnapshot) {
workspaceRefreshKeyRef.current = null;
workspaceRefreshRetryRef.current = null;
}
hadWorkspaceSnapshotRef.current = hasWorkspaceSnapshot;
}, [hasWorkspaceSnapshot]);
useEffect(() => {
if (!environmentId || !projectCwd || !selectedProviderInstanceId) return;
const key = `${environmentId}:${selectedProviderInstanceId}:${projectCwd}`;
if (workspaceRefreshKeyRef.current === key) return;
if (hasWorkspaceSnapshot) {
workspaceRefreshKeyRef.current = key;
workspaceRefreshRetryRef.current = null;
return;
}
const retry = workspaceRefreshRetryRef.current;
if (retry?.key === key && Date.now() < retry.notBefore) return;
workspaceRefreshKeyRef.current = key;
const retryLater = () => {
if (workspaceRefreshKeyRef.current !== key) return;
workspaceRefreshKeyRef.current = null;
workspaceRefreshRetryRef.current = {
key,
notBefore: Date.now() + WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS,
};
};
void refreshProviders({
environmentId,
input: { instanceId: selectedProviderInstanceId, cwd: projectCwd },
}).then((result) => {
const refreshed =
result._tag === "Success" &&
result.value.providers
.find((provider) => provider.instanceId === selectedProviderInstanceId)
?.workspaceSnapshots?.some((snapshot) => snapshot.cwd === projectCwd);
if (!refreshed && workspaceRefreshKeyRef.current === key) {
retryLater();
}
}, retryLater);
}, [
draftMessage,
environmentId,
hasWorkspaceSnapshot,
projectCwd,
refreshProviders,
selectedProviderInstanceId,
]);
const trigger = useMemo(() => {
if (!enabled || selection.start !== selection.end) {
return null;
@@ -120,8 +191,7 @@ export function useComposerCommandMenu({
// locally and skills insert a `$` mention the server dispatches from
// any position, so only provider commands are position-gated.
const providerCommands: ComposerCommandItem[] = [];
const expandableCommands =
trigger.rangeStart === 0 ? (selectedProviderStatus?.slashCommands ?? []) : [];
const expandableCommands = trigger.rangeStart === 0 ? slashCommands : [];
for (const command of expandableCommands) {
if (!command.name.toLowerCase().includes(q)) continue;
// Codex feedback uploads an existing thread's session and logs.
@@ -141,7 +211,7 @@ export function useComposerCommandMenu({
});
}
const skillItems = getProviderSkillsForSlashMenu(selectedProviderStatus?.skills ?? [], true)
const skillItems = getProviderSkillsForSlashMenu(skills, true)
.filter((skill) => matchesSlashSkillQuery(skill, q))
.map((skill) => ({
id: `skill:${skill.name}`,
@@ -155,9 +225,7 @@ export function useComposerCommandMenu({
}
if (trigger.kind === "skill") {
const enabledSkills = dedupeProviderSkillsByName(
(selectedProviderStatus?.skills ?? []).filter(isProviderSkillUserInvocable),
);
const enabledSkills = dedupeProviderSkillsByName(skills.filter(isProviderSkillUserInvocable));
const normalizedQuery = normalizeSearchQuery(trigger.query, {
trimLeadingPattern: /^\$+/,
});
@@ -254,7 +322,15 @@ export function useComposerCommandMenu({
}
return [];
}, [hasThread, onUpdateInteractionMode, pathSearch.entries, selectedProviderStatus, trigger]);
}, [
hasThread,
onUpdateInteractionMode,
pathSearch.entries,
selectedProviderStatus,
skills,
slashCommands,
trigger,
]);
const onSelect = useCallback(
(item: ComposerCommandItem) => {
@@ -299,6 +375,7 @@ export function useComposerCommandMenu({
onSelectionChange,
trigger,
items,
skills,
isLoading: pathSearch.isPending,
onSelect,
};
@@ -50,6 +50,7 @@ import {
makeProviderSnapshotSettingsSource,
type ProviderSnapshotSettings,
} from "../providerUpdateSettings.ts";
import { probeCursorSkills } from "./CursorSkills.ts";
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
const DRIVER_KIND = ProviderDriverKind.make("cursor");
@@ -166,6 +167,25 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
accentColor,
enabled,
snapshot,
snapshotForCwd: (cwd) =>
!effectiveConfig.enabled
? snapshot.getSnapshot
: Effect.all([
snapshot.getSnapshot,
probeCursorSkills(cwd, processEnv).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
Effect.mapError(
(cause) =>
new ProviderDriverError({
driver: DRIVER_KIND,
instanceId,
detail: `Failed to discover Cursor skills for '${cwd}'`,
cause,
}),
),
),
]).pipe(Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills }))),
adapter,
textGeneration,
} satisfies ProviderInstance;
@@ -0,0 +1,283 @@
/**
* CursorSkills — workspace-aware discovery and native invocation for Cursor.
*
* Cursor discovers Agent Skills recursively from user and project roots but
* its ACP command catalog only appears after opening a real session. Scanning
* the same roots avoids starting an agent and its MCP servers just to populate
* a composer menu.
*
* @module provider/Drivers/CursorSkills
*/
import * as NodeOS from "node:os";
import type { ServerProviderSkill } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import { parse as parseYamlDocument } from "yaml";
const FRONTMATTER_PATTERN = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
const SKILL_MENTION_PATTERN = /(^|\s)\$([a-zA-Z][a-zA-Z0-9:_-]*)(?=\s|$)/g;
const HAS_SKILL_MENTION_PATTERN = /(^|\s)\$[a-zA-Z][a-zA-Z0-9:_-]*(?=\s|$)/;
const MAX_SKILL_DEPTH = 10;
const MAX_SKILL_BYTES = FileSystem.Size(1_000_000);
const MAX_SKILL_SCAN_ENTRIES = 10_000;
const MAX_SKILL_SCAN_BYTES = FileSystem.Size(8_000_000);
interface CursorSkillFrontmatter {
readonly description?: string;
readonly displayName?: string;
readonly userInvocationOnly?: boolean;
readonly userInvocable?: boolean;
readonly cliVisible: boolean;
}
interface CursorSkillScanBudget {
remainingEntries: number;
remainingBytes: bigint;
exhausted: boolean;
incomplete: boolean;
}
class CursorSkillsProbeError extends Schema.TaggedErrorClass<CursorSkillsProbeError>()(
"CursorSkillsProbeError",
{
reason: Schema.Literals(["scan-budget-exhausted", "filesystem-error"]),
cwd: Schema.optional(Schema.String),
},
) {
override get message(): string {
const location = this.cwd === undefined ? "" : ` for '${this.cwd}'`;
return `Cursor skill discovery${location} was incomplete (${this.reason}).`;
}
}
const orUndefined = <A, R>(
effect: Effect.Effect<A, PlatformError.PlatformError, R>,
budget?: CursorSkillScanBudget,
): Effect.Effect<A | undefined, never, R> =>
effect.pipe(
Effect.map((value): A | undefined => value),
Effect.catchTags({
PlatformError: (error) => {
if (error.reason._tag !== "NotFound" && budget) budget.incomplete = true;
return Effect.void.pipe(Effect.as(undefined));
},
}),
);
function parseFrontmatterBoolean(value: unknown): boolean | undefined {
if (typeof value === "boolean") return value;
if (typeof value === "number") return value === 1 ? true : value === 0 ? false : undefined;
if (typeof value !== "string") return undefined;
switch (value.trim().toLowerCase()) {
case "true":
case "yes":
case "on":
return true;
case "false":
case "no":
case "off":
return false;
default:
return undefined;
}
}
function parseSkillFrontmatter(contents: string): CursorSkillFrontmatter | undefined {
const match = FRONTMATTER_PATTERN.exec(contents);
if (!match) return { cliVisible: true };
let parsed: unknown;
try {
parsed = parseYamlDocument(match[1] ?? "");
} catch {
return undefined;
}
if (typeof parsed !== "object" || parsed === null) return undefined;
const record = parsed as Record<string, unknown>;
const metadata =
typeof record.metadata === "object" && record.metadata !== null
? (record.metadata as Record<string, unknown>)
: undefined;
const rawSurfaces = metadata?.surfaces;
const surfaces = Array.isArray(rawSurfaces)
? rawSurfaces.filter((surface): surface is string => typeof surface === "string")
: typeof rawSurfaces === "string"
? rawSurfaces.split(",")
: [];
const description = typeof record.description === "string" ? record.description.trim() : "";
const displayName = typeof record.name === "string" ? record.name.trim() : "";
return {
cliVisible:
surfaces.length === 0 || surfaces.some((surface) => surface.trim().toLowerCase() === "cli"),
...(description ? { description } : {}),
...(displayName ? { displayName } : {}),
...(parseFrontmatterBoolean(record["disable-model-invocation"]) === true
? { userInvocationOnly: true }
: {}),
...(parseFrontmatterBoolean(record["user-invocable"]) === false
? { userInvocable: false }
: {}),
};
}
const discoverSkillsInRoot = Effect.fn("discoverCursorSkillsInRoot")(function* (input: {
readonly directory: string;
readonly scope: "user" | "project";
readonly budget: CursorSkillScanBudget;
}): Effect.fn.Return<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const skills: ServerProviderSkill[] = [];
if (input.budget.exhausted) return skills;
const rootDirectory = yield* orUndefined(fileSystem.realPath(input.directory), input.budget);
if (!rootDirectory) return skills;
const visitedDirectories = new Set<string>();
const visit = Effect.fn("visitCursorSkillDirectory")(function* (
directory: string,
depth: number,
): Effect.fn.Return<void, never> {
if (input.budget.exhausted) return;
const resolvedDirectory = yield* orUndefined(fileSystem.realPath(directory), input.budget);
if (!resolvedDirectory) {
return;
}
if (
visitedDirectories.has(resolvedDirectory) ||
(resolvedDirectory !== rootDirectory &&
!resolvedDirectory.startsWith(`${rootDirectory}${path.sep}`))
) {
return;
}
visitedDirectories.add(resolvedDirectory);
const skillPath = path.join(resolvedDirectory, "SKILL.md");
const skillInfo = yield* orUndefined(fileSystem.stat(skillPath), input.budget);
if (skillInfo?.type === "File") {
let frontmatter: CursorSkillFrontmatter | undefined = { cliVisible: true };
if (skillInfo.size <= MAX_SKILL_BYTES && skillInfo.size <= input.budget.remainingBytes) {
const contents = yield* orUndefined(fileSystem.readFileString(skillPath));
if (contents !== undefined) {
input.budget.remainingBytes -= skillInfo.size;
frontmatter = parseSkillFrontmatter(contents);
}
}
const name = path.basename(resolvedDirectory).trim();
if (frontmatter?.cliVisible && name) {
skills.push({
name,
path: skillPath,
scope: input.scope,
enabled: true,
...(frontmatter.displayName && frontmatter.displayName !== name
? { displayName: frontmatter.displayName }
: {}),
...(frontmatter.description ? { description: frontmatter.description } : {}),
...(frontmatter.userInvocationOnly ? { userInvocationOnly: true } : {}),
...(frontmatter.userInvocable === false ? { userInvocable: false } : {}),
});
}
}
const entries = yield* orUndefined(fileSystem.readDirectory(resolvedDirectory), input.budget);
if (!entries) {
return;
}
for (const entry of [...entries].sort()) {
if (input.budget.remainingEntries === 0) {
input.budget.exhausted = true;
return;
}
input.budget.remainingEntries -= 1;
const child = path.join(resolvedDirectory, entry);
const info = yield* orUndefined(fileSystem.stat(child), input.budget);
if (info?.type !== "Directory") continue;
if (depth >= MAX_SKILL_DEPTH) {
input.budget.exhausted = true;
return;
}
yield* visit(child, depth + 1);
}
});
yield* visit(rootDirectory, 0);
return skills;
});
const inspectCursorSkills = Effect.fn("inspectCursorSkills")(function* (
cwd?: string,
environment: NodeJS.ProcessEnv = process.env,
) {
const path = yield* Path.Path;
const userHome = environment.HOME?.trim() || environment.USERPROFILE?.trim() || NodeOS.homedir();
const rootsBelow = (base: string, scope: "user" | "project") => [
{ directory: path.join(base, ".cursor", "skills"), scope },
{ directory: path.join(base, ".agents", "skills"), scope },
{ directory: path.join(base, ".codex", "skills"), scope },
{ directory: path.join(base, ".claude", "skills"), scope },
];
const roots = [...(cwd ? rootsBelow(cwd, "project") : []), ...rootsBelow(userHome, "user")];
const skillsByName = new Map<string, ServerProviderSkill>();
const budget: CursorSkillScanBudget = {
remainingEntries: MAX_SKILL_SCAN_ENTRIES,
remainingBytes: MAX_SKILL_SCAN_BYTES,
exhausted: false,
incomplete: false,
};
for (const root of roots) {
if (budget.exhausted) break;
const skills = yield* discoverSkillsInRoot({ ...root, budget });
for (const skill of skills) {
if (!skillsByName.has(skill.name)) skillsByName.set(skill.name, skill);
}
}
return {
skills: [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name)),
failureReason: budget.exhausted
? ("scan-budget-exhausted" as const)
: budget.incomplete
? ("filesystem-error" as const)
: undefined,
};
});
export const discoverCursorSkills = Effect.fn("discoverCursorSkills")(function* (
cwd?: string,
environment: NodeJS.ProcessEnv = process.env,
) {
return (yield* inspectCursorSkills(cwd, environment)).skills;
});
export const probeCursorSkills = Effect.fn("probeCursorSkills")(function* (
cwd?: string,
environment: NodeJS.ProcessEnv = process.env,
) {
const inspection = yield* inspectCursorSkills(cwd, environment);
if (inspection.failureReason) {
return yield* new CursorSkillsProbeError({
reason: inspection.failureReason,
...(cwd ? { cwd } : {}),
});
}
return inspection.skills;
});
/** Cursor invokes Agent Skills with `/name`; T3 composers insert `$name`. */
export function hasCursorSkillMention(prompt: string): boolean {
return HAS_SKILL_MENTION_PATTERN.test(prompt);
}
export function rewriteCursorSkillMentions(
prompt: string,
skillNames: ReadonlySet<string>,
): string {
return prompt.replace(SKILL_MENTION_PATTERN, (match, prefix: string, name: string) =>
skillNames.has(name) ? `${prefix}/${name}` : match,
);
}
@@ -27,6 +27,7 @@ import {
} from "../ProviderDriver.ts";
import { withInstanceIdentity } from "./instanceIdentity.ts";
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
import { discoverGrokSkills } from "./GrokSkills.ts";
import {
makeManualOnlyProviderMaintenanceCapabilities,
makeStaticProviderMaintenanceResolver,
@@ -133,6 +134,24 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
}),
),
);
const snapshotForCwd = (workspaceCwd: string) =>
!effectiveConfig.enabled
? snapshot.getSnapshot
: Effect.all([
snapshot.getSnapshot,
discoverGrokSkills(effectiveConfig, processEnv, workspaceCwd).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.mapError(
(cause) =>
new ProviderDriverError({
driver: DRIVER_KIND,
instanceId,
detail: `Failed to discover Grok skills for '${workspaceCwd}'`,
cause,
}),
),
),
]).pipe(Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })));
return {
instanceId,
@@ -142,6 +161,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
accentColor,
enabled,
snapshot,
snapshotForCwd,
adapter,
textGeneration,
} satisfies ProviderInstance;
@@ -93,14 +93,15 @@ describe("parseGrokInspectSkills", () => {
});
describe("discoverGrokSkills", () => {
it.effect("spawns the inspect probe in the configured cwd", () => {
it.effect("spawns in the configured cwd and rejects a failed probe", () => {
const spawnCwds: Array<string | undefined> = [];
let exitCode = 0;
const spawner = ChildProcessSpawner.make((command) => {
spawnCwds.push(command._tag === "StandardCommand" ? command.options.cwd : undefined);
return Effect.succeed(
ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
@@ -130,6 +131,13 @@ describe("discoverGrokSkills", () => {
expect(spawnCwds).toEqual(["/workspaces/demo"]);
expect(skills.map((skill) => skill.name)).toEqual(["kept"]);
exitCode = 1;
const failed = yield* discoverGrokSkills({ binaryPath: "grok" }).pipe(
Effect.result,
Effect.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
);
expect(failed._tag).toBe("Failure");
});
});
});
+60 -24
View File
@@ -9,41 +9,57 @@
* (ignore lists, disabled skills) and includes plugin skills, which live
* three levels deep under `~/.grok/installed-plugins/` where a flat scan
* cannot see them. This mirrors how the Codex app-server reports skills over
* `skills/list`. Discovery is best-effort: an older CLI without `inspect`,
* a timeout, or malformed output yields an empty list, never a degraded
* provider snapshot.
* `skills/list`. Probe failures stay typed so workspace snapshots do not
* cache an empty catalog; machine-level discovery recovers them to an empty
* list without degrading the provider.
*
* @module provider/Drivers/GrokSkills
*/
import type { GrokSettings, ServerProviderSkill } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Result from "effect/Result";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as Schema from "effect/Schema";
import { ChildProcess } from "effect/unstable/process";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
import { spawnAndCollect } from "../providerSnapshot.ts";
const GROK_SKILLS_PROBE_TIMEOUT_MS = 4_000;
class GrokSkillsProbeError extends Schema.TaggedErrorClass<GrokSkillsProbeError>()(
"GrokSkillsProbeError",
{
stage: Schema.Literals(["spawn", "timeout", "exit", "decode"]),
cwd: Schema.optional(Schema.String),
exitCode: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
const location = this.cwd === undefined ? "" : ` for '${this.cwd}'`;
const exitCode = this.exitCode === undefined ? "" : ` with exit code ${this.exitCode}`;
return `\`grok inspect --json\` failed during ${this.stage}${location}${exitCode}.`;
}
}
/**
* Map `grok inspect --json` output onto provider skills. Entries without a
* name or a filesystem path are skipped; `userInvocable: false` skills are
* kept but disabled so pickers that filter on `enabled` hide them.
*/
export function parseGrokInspectSkills(stdout: string): ReadonlyArray<ServerProviderSkill> {
function decodeGrokInspectSkills(stdout: string): ReadonlyArray<ServerProviderSkill> | undefined {
let parsed: unknown;
try {
parsed = JSON.parse(stdout);
} catch {
return [];
return undefined;
}
if (typeof parsed !== "object" || parsed === null) {
return [];
return undefined;
}
const entries = (parsed as Record<string, unknown>).skills;
if (!Array.isArray(entries)) {
return [];
return undefined;
}
const skillsByName = new Map<string, ServerProviderSkill>();
@@ -75,20 +91,20 @@ export function parseGrokInspectSkills(stdout: string): ReadonlyArray<ServerProv
return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
}
export function parseGrokInspectSkills(stdout: string): ReadonlyArray<ServerProviderSkill> {
return decodeGrokInspectSkills(stdout) ?? [];
}
/**
* Run `grok inspect --json` and map the reported catalog onto provider
* skills. Never fails: any spawn error, non-zero exit, or timeout resolves
* to an empty list.
* skills. Callers that need best-effort discovery can recover this effect to
* an empty list; workspace callers leave failures typed so they are not cached.
*/
export const discoverGrokSkills = Effect.fn("discoverGrokSkills")(function* (
grokSettings: Pick<GrokSettings, "binaryPath">,
environment: NodeJS.ProcessEnv = process.env,
cwd?: string,
): Effect.fn.Return<
ReadonlyArray<ServerProviderSkill>,
never,
ChildProcessSpawner.ChildProcessSpawner
> {
) {
const command = grokSettings.binaryPath || "grok";
const inspectResult = yield* Effect.gen(function* () {
const spawnCommand = yield* resolveSpawnCommand(command, ["inspect", "--json"], {
@@ -102,18 +118,38 @@ export const discoverGrokSkills = Effect.fn("discoverGrokSkills")(function* (
shell: spawnCommand.shell,
}),
);
}).pipe(Effect.timeoutOption(GROK_SKILLS_PROBE_TIMEOUT_MS), Effect.result);
}).pipe(
Effect.mapError(
(cause) =>
new GrokSkillsProbeError({
stage: "spawn",
...(cwd ? { cwd } : {}),
cause,
}),
),
Effect.timeoutOption(GROK_SKILLS_PROBE_TIMEOUT_MS),
);
if (Result.isFailure(inspectResult) || Option.isNone(inspectResult.success)) {
yield* Effect.logDebug("Grok skill discovery failed; continuing without skills.");
return [];
if (Option.isNone(inspectResult)) {
return yield* new GrokSkillsProbeError({
stage: "timeout",
...(cwd ? { cwd } : {}),
});
}
const output = inspectResult.success.value;
const output = inspectResult.value;
if (output.code !== 0) {
yield* Effect.logDebug("Grok skill discovery exited non-zero; continuing without skills.", {
return yield* new GrokSkillsProbeError({
stage: "exit",
...(cwd ? { cwd } : {}),
exitCode: output.code,
});
return [];
}
return parseGrokInspectSkills(output.stdout);
const skills = decodeGrokInspectSkills(output.stdout);
if (!skills) {
return yield* new GrokSkillsProbeError({
stage: "decode",
...(cwd ? { cwd } : {}),
});
}
return skills;
});
@@ -250,6 +250,52 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
}),
);
it.effect("sends selected project skills in Cursor's native slash form", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const settings = yield* ServerSettingsService;
const threadId = ThreadId.make("cursor-skill-dispatch");
const workspace = yield* Effect.promise(() =>
NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "cursor-skill-dispatch-")),
);
const requestLogPath = NodePath.join(workspace, "requests.ndjson");
const argvLogPath = NodePath.join(workspace, "argv.txt");
const skillDirectory = NodePath.join(workspace, ".cursor", "skills", "review");
yield* Effect.promise(() => NodeFSP.mkdir(skillDirectory, { recursive: true }));
yield* Effect.promise(() =>
NodeFSP.writeFile(NodePath.join(skillDirectory, "SKILL.md"), "# Review\n", "utf8"),
);
yield* Effect.promise(() => NodeFSP.writeFile(requestLogPath, "", "utf8"));
const wrapperPath = yield* Effect.promise(() =>
makeProbeWrapper(requestLogPath, argvLogPath),
);
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
cwd: workspace,
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
});
yield* adapter.sendTurn({
threadId,
input: "please $review this",
attachments: [],
});
yield* adapter.stopSession(threadId);
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
const promptRequests = requests.filter((entry) => entry.method === "session/prompt");
assert.deepStrictEqual(
promptRequests.map(
(request) => (request.params as Record<string, unknown> | undefined)?.prompt,
),
[[{ type: "text", text: "please /review this" }]],
);
}),
);
it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
@@ -77,6 +77,11 @@ import {
import { type CursorAdapterShape } from "../Services/CursorAdapter.ts";
import { resolveCursorAcpBaseModelId } from "./CursorProvider.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
import {
discoverCursorSkills,
hasCursorSkillMention,
rewriteCursorSkillMentions,
} from "../Drivers/CursorSkills.ts";
const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown));
const PROVIDER = ProviderDriverKind.make("cursor");
@@ -133,6 +138,7 @@ interface CursorSessionContext {
readonly turns: Array<{ id: TurnId; items: Array<unknown> }>;
lastPlanFingerprint: string | undefined;
activeTurnId: TurnId | undefined;
cursorSkillNames: ReadonlySet<string> | undefined;
/** Number of sendTurn prompts currently in flight or being prepared.
* >0 means a turn is actively running, so a new sendTurn is a steer that
* continues it, and only the last remaining prompt settles the turn. */
@@ -779,6 +785,7 @@ export function makeCursorAdapter(
turns: [],
lastPlanFingerprint: undefined,
activeTurnId: undefined,
cursorSkillNames: undefined,
promptsInFlight: 0,
stopped: false,
};
@@ -968,8 +975,28 @@ export function makeCursorAdapter(
}
const promptParts: Array<EffectAcpSchema.ContentBlock> = [];
if (input.input?.trim()) {
promptParts.push({ type: "text", text: input.input.trim() });
const rawPrompt = input.input?.trim() ?? "";
if (rawPrompt) {
let cursorSkillNames = ctx.cursorSkillNames;
if (hasCursorSkillMention(rawPrompt) && cursorSkillNames === undefined) {
const skills = yield* discoverCursorSkills(
ctx.session.cwd,
options?.environment,
).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
);
cursorSkillNames = new Set(
skills
.filter((skill) => skill.enabled && skill.userInvocable !== false)
.map((skill) => skill.name),
);
ctx.cursorSkillNames = cursorSkillNames;
}
const prompt = cursorSkillNames
? rewriteCursorSkillMentions(rawPrompt, cursorSkillNames)
: rawPrompt;
promptParts.push({ type: "text", text: prompt });
}
if (input.attachments && input.attachments.length > 0) {
for (const attachment of input.attachments) {
@@ -24,6 +24,12 @@ import {
resolveCursorAcpBaseModelId,
resolveCursorAcpConfigUpdates,
} from "./CursorProvider.ts";
import {
discoverCursorSkills,
hasCursorSkillMention,
probeCursorSkills,
rewriteCursorSkillMentions,
} from "../Drivers/CursorSkills.ts";
const runNode = <A, E>(
effect: Effect.Effect<
@@ -312,6 +318,98 @@ const cursorCliCommandMissingMessage = [
"See https://cursor.com/docs/cli/installation.",
].join(" ");
describe("Cursor skills", () => {
it("discovers recursive project skills with project precedence", async () =>
await runNode(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const userHome = yield* fileSystem.makeTempDirectory({
directory: NodeOS.tmpdir(),
prefix: "cursor-skills-home-",
});
const workspace = yield* fileSystem.makeTempDirectory({
directory: NodeOS.tmpdir(),
prefix: "cursor-skills-workspace-",
});
const writeSkill = Effect.fn("writeCursorSkill")(function* (
root: string,
name: string,
contents: string,
) {
const skillDirectory = path.join(root, name);
yield* fileSystem.makeDirectory(skillDirectory, { recursive: true });
yield* fileSystem.writeFileString(path.join(skillDirectory, "SKILL.md"), contents);
});
yield* writeSkill(
path.join(userHome, ".cursor", "skills"),
"review",
"---\ndescription: user review\n---\n",
);
yield* writeSkill(
path.join(workspace, ".agents", "skills", "nested"),
"review",
"---\nname: Review changes\ndescription: project review\n---\n",
);
yield* writeSkill(
path.join(workspace, ".cursor", "skills"),
"internal",
"---\nuser-invocable: false\n---\n",
);
yield* writeSkill(
path.join(workspace, ".cursor", "skills"),
"oversized",
"x".repeat(1_000_001),
);
yield* fileSystem.makeDirectory(path.join(userHome, ".codex"), { recursive: true });
yield* fileSystem.writeFileString(
path.join(userHome, ".codex", "skills"),
"not a directory",
);
const skills = yield* discoverCursorSkills(workspace, { HOME: userHome });
expect(skills).toEqual([
{
name: "internal",
path: path.join(workspace, ".cursor", "skills", "internal", "SKILL.md"),
scope: "project",
enabled: true,
userInvocable: false,
},
{
name: "oversized",
path: path.join(workspace, ".cursor", "skills", "oversized", "SKILL.md"),
scope: "project",
enabled: true,
},
{
name: "review",
displayName: "Review changes",
description: "project review",
path: path.join(workspace, ".agents", "skills", "nested", "review", "SKILL.md"),
scope: "project",
enabled: true,
},
]);
expect(
(yield* probeCursorSkills(workspace, { HOME: userHome }).pipe(Effect.result))._tag,
).toBe("Failure");
}),
));
it("rewrites only discovered skill mentions into Cursor slash invocations", () => {
expect(hasCursorSkillMention("use $Review_Pr:V2 here")).toBe(true);
expect(hasCursorSkillMention("please $review this")).toBe(true);
expect(
rewriteCursorSkillMentions("use $review, keep $HOME and 5$review", new Set(["review"])),
).toBe("use $review, keep $HOME and 5$review");
expect(rewriteCursorSkillMentions("please $review this", new Set(["review"]))).toBe(
"please /review this",
);
});
});
describe("getCursorFallbackModels", () => {
it("does not publish any built-in cursor models before ACP discovery", () => {
expect(
@@ -453,7 +453,10 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func
? { status: "unauthenticated" }
: { status: "unknown" };
const skills = yield* discoverGrokSkills(grokSettings, environment, cwd);
const skills = yield* discoverGrokSkills(grokSettings, environment, cwd).pipe(
Effect.tapError((cause) => Effect.logDebug("Grok skill discovery failed.", { cause })),
Effect.orElseSucceed(() => []),
);
const acpExit = yield* discoverGrokModelsViaAcpInitialize(grokSettings, environment).pipe(
Effect.timeoutOption(GROK_ACP_INITIALIZE_TIMEOUT_MS),
+26 -16
View File
@@ -346,6 +346,8 @@ import { useAtomCommand } from "../../state/use-atom-command";
import { serverEnvironment } from "../../state/server";
import type { ReviewCommentContext } from "../../reviewCommentContext";
const WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS = 10_000;
const runtimeModeConfig: Record<
RuntimeMode,
{ label: string; description: string; icon: LucideIcon }
@@ -1130,6 +1132,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
reportFailure: false,
});
const workspaceRefreshKeyRef = useRef<string | null>(null);
const workspaceRefreshRetryRef = useRef<{ key: string; notBefore: number } | null>(null);
const hadWorkspaceSnapshotRef = useRef(false);
useEffect(() => {
const hasWorkspaceSnapshot = Boolean(
@@ -1138,6 +1141,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
);
if (hadWorkspaceSnapshotRef.current && !hasWorkspaceSnapshot) {
workspaceRefreshKeyRef.current = null;
workspaceRefreshRetryRef.current = null;
}
hadWorkspaceSnapshotRef.current = hasWorkspaceSnapshot;
}, [gitCwd, selectedProviderStatus]);
@@ -1150,28 +1154,34 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
if (workspaceRefreshKeyRef.current === key) return;
if (hasWorkspaceSnapshot) {
workspaceRefreshKeyRef.current = key;
workspaceRefreshRetryRef.current = null;
return;
}
const retry = workspaceRefreshRetryRef.current;
if (retry?.key === key && Date.now() < retry.notBefore) return;
workspaceRefreshKeyRef.current = key;
const retryLater = () => {
if (workspaceRefreshKeyRef.current !== key) return;
workspaceRefreshKeyRef.current = null;
workspaceRefreshRetryRef.current = {
key,
notBefore: Date.now() + WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS,
};
};
void refreshProviders({
environmentId,
input: { instanceId: selectedProviderEntry.instanceId, cwd: gitCwd },
}).then(
(result) => {
const hasWorkspaceSnapshot =
result._tag === "Success" &&
result.value.providers
.find((provider) => provider.instanceId === selectedProviderEntry.instanceId)
?.workspaceSnapshots?.some((snapshot) => snapshot.cwd === gitCwd);
if (!hasWorkspaceSnapshot && workspaceRefreshKeyRef.current === key) {
workspaceRefreshKeyRef.current = null;
}
},
() => {
if (workspaceRefreshKeyRef.current === key) workspaceRefreshKeyRef.current = null;
},
);
}, [environmentId, gitCwd, refreshProviders, selectedProviderEntry]);
}).then((result) => {
const hasWorkspaceSnapshot =
result._tag === "Success" &&
result.value.providers
.find((provider) => provider.instanceId === selectedProviderEntry.instanceId)
?.workspaceSnapshots?.some((snapshot) => snapshot.cwd === gitCwd);
if (!hasWorkspaceSnapshot && workspaceRefreshKeyRef.current === key) {
retryLater();
}
}, retryLater);
}, [environmentId, gitCwd, prompt, refreshProviders, selectedProviderEntry]);
const selectedProviderModels = useMemo<ReadonlyArray<ServerProvider["models"][number]>>(
() => selectedProviderEntry?.models ?? [],
[selectedProviderEntry],