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

providerSkills.ts

392 lines14.8 KB

1import {
2 type EnvironmentId,
3 isProviderWorkspaceSnapshotCurrent,
4 isProviderWorkspaceSnapshotPending,
5 PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS,
6 type ProviderInstanceId,
7 type ServerProvider,
8 type ServerProviderSkill,
9 type ServerProviderSlashCommand,
10} from "@t3tools/contracts";
11import { Atom } from "effect/reactivity";
12​
13import { deadlineStore } from "./clock.ts";
14import { type AtomCommand, runAtomCommand } from "./state/runtime.ts";
15​
16export type ProviderSkillSourceKind = "app" | "repo" | "project" | "personal" | "system" | "other";
17​
18function normalizePathSeparators(pathValue: string): string {
19 return pathValue.replaceAll("\\", "/");
21​
22export function dedupeProviderSkillsByName(
23 skills: ReadonlyArray<ServerProviderSkill>,
24): ServerProviderSkill[] {
25 const seenNames = new Set<string>();
26 return skills.filter((skill) => {
27 const normalizedName = skill.name.trim().toLowerCase();
28 if (seenNames.has(normalizedName)) {
29 return false;
30 }
31 seenNames.add(normalizedName);
32 return true;
33 });
35​
36/**
37 * Exclude disabled and agent-only skills (Claude Code's `user-invocable: false`).
38 * Skills the agent cannot start on its own can still be invoked by users in the provider's native form.
39 */
40export function isProviderSkillUserInvocable(
41 skill: Pick<ServerProviderSkill, "enabled" | "userInvocable">,
42): boolean {
43 return skill.enabled && skill.userInvocable !== false;
45​
46export function getProviderSkillsForSlashMenu(
47 skills: ReadonlyArray<ServerProviderSkill>,
48 showSkillsInSlashMenu: boolean,
49): ServerProviderSkill[] {
50 return showSkillsInSlashMenu
51 ? dedupeProviderSkillsByName(skills.filter(isProviderSkillUserInvocable))
52 : [];
54​
55export function getProviderSlashCommandsForSlashMenu(
56 slashCommands: ReadonlyArray<ServerProviderSlashCommand>,
57 visibleSkills: ReadonlyArray<ServerProviderSkill>,
58): ServerProviderSlashCommand[] {
59 const skillNames = new Set(visibleSkills.map((skill) => skill.name.trim().toLowerCase()));
60 return slashCommands.filter((command) => !skillNames.has(command.name.trim().toLowerCase()));
62​
63export function resolveProviderSkillSourceKind(
64 skill: Pick<ServerProviderSkill, "path" | "scope">,
65): ProviderSkillSourceKind {
66 const normalizedPath = normalizePathSeparators(skill.path);
67 if (normalizedPath.includes("/.codex/plugins/") || normalizedPath.includes("/.agents/plugins/")) {
68 return "app";
69 }
70​
71 const normalizedScope = skill.scope?.trim().toLowerCase();
72 switch (normalizedScope) {
73 case "repo":
74 case "repository":
75 return "repo";
76 case "project":
77 case "workspace":
78 case "local":
79 return "project";
80 case "user":
81 case "personal":
82 return "personal";
83 case "system":
84 return "system";
85 case undefined:
86 case "":
87 return "other";
88 default:
89 return "other";
90 }
92​
93function resolveProviderWorkspaceSnapshot(
94 provider: ServerProvider,
95 cwd: string | null | undefined,
96) {
97 if (!cwd) return undefined;
98 return provider.workspaceSnapshots?.find((snapshot) => snapshot.cwd === cwd);
100​
101export function hasCompleteProviderWorkspaceSnapshot(
102 provider: ServerProvider | null | undefined,
103 cwd: string | null | undefined,
104): boolean {
105 const snapshot = provider && resolveProviderWorkspaceSnapshot(provider, cwd);
106 return Boolean(snapshot && !isProviderWorkspaceSnapshotPending(snapshot));
108​
109function hasCurrentProviderWorkspaceSnapshot(
110 provider: ServerProvider | null | undefined,
111 cwd: string | null | undefined,
112 nowMs: number,
113): boolean {
114 const snapshot = provider && resolveProviderWorkspaceSnapshot(provider, cwd);
115 return Boolean(
116 snapshot &&
117 !isProviderWorkspaceSnapshotPending(snapshot) &&
118 isProviderWorkspaceSnapshotCurrent(snapshot, nowMs),
119 );
121​
122// The agent reloads skills on these, but the composer's per-cwd skill list is cached separately.
123const SKILL_RELOAD_COMMANDS = new Set(["/reload-skills", "/reload-plugins"]);
124​
125export function isSkillReloadCommand(prompt: string): boolean {
126 return SKILL_RELOAD_COMMANDS.has(prompt.trim().toLowerCase());
128​
129export function resolveProviderSkillsForCwd(
130 provider: ServerProvider,
131 cwd: string | null | undefined,
132): ServerProvider["skills"] {
133 return resolveProviderWorkspaceSnapshot(provider, cwd)?.skills ?? provider.skills;
135​
136export function resolveProviderSlashCommandsForCwd(
137 provider: ServerProvider,
138 cwd: string | null | undefined,
139): ServerProvider["slashCommands"] {
140 return resolveProviderWorkspaceSnapshot(provider, cwd)?.slashCommands ?? provider.slashCommands;
142​
143/** A project's own provider config can add models that only its workspace snapshot lists. */
144function resolveProviderModelsForCwd(
145 provider: ServerProvider,
146 cwd: string | null | undefined,
147): ServerProvider["models"] {
148 return resolveProviderWorkspaceSnapshot(provider, cwd)?.models ?? provider.models;
150​
151/** Providers keep their identity unless the cwd has its own catalog. */
152export function resolveProvidersForCwd<P extends ServerProvider>(
153 providers: ReadonlyArray<P>,
154 cwd: string | null | undefined,
155): ReadonlyArray<P> {
156 const resolved = providers.map((provider) => {
157 const models = resolveProviderModelsForCwd(provider, cwd);
158 return models === provider.models ? provider : { ...provider, models };
159 });
160 return resolved.every((provider, index) => provider === providers[index]) ? providers : resolved;
162​
163const WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS = 10_000;
164// A cwd that never scans, such as a deleted worktree, would otherwise retry forever.
165const WORKSPACE_SNAPSHOT_MAX_ATTEMPTS = 3;
166​
167export interface ProviderWorkspaceSnapshotRefreshState {
168 /**
169 * When the last scan was requested. A request inside the TTL is not
170 * repeated, so a client clock ahead of the server's cannot loop rescans.
171 */
172 readonly requestedAt: number | null;
173 /** A failed scan is not retried before this time. */
174 readonly retryNotBefore: number | null;
175 /** Failed scans within the current request TTL. */
176 readonly failedAttempts: number;
177 readonly hadSnapshot: boolean;
178 /** The server published a partial snapshot and is still discovering. */
179 readonly snapshotPending: boolean;
181​
182const initialProviderWorkspaceSnapshotRefreshState: ProviderWorkspaceSnapshotRefreshState = {
183 requestedAt: null,
184 retryNotBefore: null,
185 failedAttempts: 0,
186 hadSnapshot: false,
187 snapshotPending: false,
188};
189​
190/**
191 * Decides whether a composer looking at `cwd` should ask the server to rescan
192 * the provider's workspace, and when to look again if a retry is due while the
193 * server still reports the scan as pending.
194 */
195function planProviderWorkspaceSnapshotRefresh(
196 previous: ProviderWorkspaceSnapshotRefreshState,
197 provider: ServerProvider | null | undefined,
198 cwd: string,
199 now: number,
200): {
201 readonly state: ProviderWorkspaceSnapshotRefreshState;
202 readonly refresh: boolean;
203 readonly recheckAt: number | null;
204} {
205 const hasSnapshot = hasCompleteProviderWorkspaceSnapshot(provider, cwd);
206 const snapshot = provider && resolveProviderWorkspaceSnapshot(provider, cwd);
207 const pending = Boolean(snapshot && isProviderWorkspaceSnapshotPending(snapshot));
208 // Losing a snapshot (the server dropped it) lifts both the TTL and the retry
209 // cooldown so the scan happens at once.
210 const lost = previous.hadSnapshot && !hasSnapshot;
211 const requestedAt = lost ? null : previous.requestedAt;
212 const retryNotBefore =
213 lost || (previous.retryNotBefore !== null && now >= previous.retryNotBefore)
214 ? null
215 : previous.retryNotBefore;
216 const state = {
217 requestedAt,
218 retryNotBefore,
219 failedAttempts:
220 lost || (requestedAt !== null && now - requestedAt >= PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS)
221 ? 0
222 : previous.failedAttempts,
223 hadSnapshot: hasSnapshot,
224 snapshotPending: pending,
225 };
226 const refresh =
227 (requestedAt === null || now - requestedAt >= PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS) &&
228 !hasCurrentProviderWorkspaceSnapshot(provider, cwd, now) &&
229 retryNotBefore === null;
230 if (refresh) {
231 return { state: { ...state, requestedAt: now }, refresh: true, recheckAt: null };
232 }
233 return { state, refresh: false, recheckAt: pending ? retryNotBefore : null };
235​
236/**
237 * A scan that failed, or finished without a complete snapshot, cools down
238 * before retrying. After the last attempt the request marker stays, so only
239 * the TTL (or a snapshot loss) lets the next scan through.
240 */
241function failProviderWorkspaceSnapshotRefresh(
242 state: ProviderWorkspaceSnapshotRefreshState,
243 requestedAt: number,
244 now: number,
245 cooldownMs = WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS,
246): ProviderWorkspaceSnapshotRefreshState {
247 // A newer request, or a snapshot loss, already superseded this one.
248 if (state.requestedAt !== requestedAt) return state;
249 const failedAttempts = state.failedAttempts + 1;
250 if (failedAttempts >= WORKSPACE_SNAPSHOT_MAX_ATTEMPTS) return { ...state, failedAttempts };
251 return {
252 ...state,
253 requestedAt: null,
254 retryNotBefore: cooldownMs === 0 ? null : now + cooldownMs,
255 failedAttempts,
256 };
258​
259/**
260 * A scan is in flight, or the server is still discovering, for a cwd without a
261 * complete snapshot, so its skills and commands may still arrive. A failed scan
262 * clears `requestedAt`, and exhausted attempts end it, so this cannot stay true
263 * for a scan that will not finish.
264 */
265export function isProviderWorkspaceSnapshotScanning(
266 state: ProviderWorkspaceSnapshotRefreshState | undefined,
267): boolean {
268 return (
269 state !== undefined &&
270 (state.requestedAt !== null || state.snapshotPending) &&
271 !state.hadSnapshot &&
272 state.failedAttempts < WORKSPACE_SNAPSHOT_MAX_ATTEMPTS
273 );
275​
276type WorkspaceSnapshotStatus = "absent" | "pending" | "complete";
277​
278function resolveWorkspaceSnapshotStatus(
279 provider: ServerProvider | undefined,
280 cwd: string,
281): WorkspaceSnapshotStatus {
282 const snapshot = provider && resolveProviderWorkspaceSnapshot(provider, cwd);
283 if (!snapshot) return "absent";
284 return isProviderWorkspaceSnapshotPending(snapshot) ? "pending" : "complete";
286​
287interface ProviderWorkspaceSnapshotRefreshTarget {
288 readonly environmentId: EnvironmentId;
289 readonly instanceId: ProviderInstanceId;
290 readonly cwd: string;
292​
293/**
294 * Keeps one environment/provider/cwd workspace snapshot fresh while mounted:
295 * reading scans when it is missing or stale, and refreshing re-checks (the
296 * composer does as the user types). It owns the retry timer, so the timer dies
297 * with the last subscriber.
298 */
299export function createProviderWorkspaceSnapshotRefreshAtomFamily(input: {
300 readonly providers: (
301 environmentId: EnvironmentId,
302 ) => Atom.Atom<ReadonlyArray<ServerProvider> | null>;
303 readonly refreshProviders: AtomCommand<
304 {
305 readonly environmentId: EnvironmentId;
306 readonly input: { readonly instanceId: ProviderInstanceId; readonly cwd: string };
307 },
308 { readonly providers: ReadonlyArray<ServerProvider> },
309 unknown
310 >;
311}) {
312 // Plain-object keys compare structurally (Effect `Equal`/`Hash`).
313 const family = Atom.family((target: ProviderWorkspaceSnapshotRefreshTarget) => {
314 const { environmentId, instanceId, cwd } = target;
315 const key = `${environmentId}:${instanceId}:${cwd}`;
316 const findProvider = (providers: ReadonlyArray<ServerProvider> | null) =>
317 providers?.find((provider) => provider.instanceId === instanceId);
318 const statusAtom = Atom.make((get) =>
319 resolveWorkspaceSnapshotStatus(findProvider(get(input.providers(environmentId))), cwd),
320 ).pipe(Atom.withLabel(`provider-workspace-snapshot-status:${key}`));
321 type Update = (
322 state: ProviderWorkspaceSnapshotRefreshState,
323 ) => ProviderWorkspaceSnapshotRefreshState;
324 const refreshAtom: Atom.Writable<ProviderWorkspaceSnapshotRefreshState, Update> = Atom.writable(
325 (get): ProviderWorkspaceSnapshotRefreshState => {
326 get(statusAtom);
327 // `once`: unrelated provider updates must not trigger a check.
328 const provider = findProvider(get.once(input.providers(environmentId)));
329 // @effect-diagnostics-next-line globalDate:off
330 const now = Date.now();
331 const previous = get.self<ProviderWorkspaceSnapshotRefreshState>();
332 const plan = planProviderWorkspaceSnapshotRefresh(
333 previous._tag === "Some" ? previous.value : initialProviderWorkspaceSnapshotRefreshState,
334 provider,
335 cwd,
336 now,
337 );
338 if (plan.recheckAt !== null) {
339 get.addFinalizer(deadlineStore(plan.recheckAt).subscribe(() => get.refreshSelf()));
340 }
341 if (!plan.refresh) return plan.state;
342 const registry = get.registry;
343 // Outlives this build on purpose: a rebuild must not drop the retry.
344 // Once nothing subscribes, the retry state dies with the node; writing
345 // would recreate and rebuild it, which scans again with no subscriber.
346 const retry = (cooldownMs?: number) => {
347 const node = registry.getNodes().get(refreshAtom);
348 if (node === undefined || node.canBeRemoved) return;
349 registry.set(refreshAtom, (state) =>
350 // @effect-diagnostics-next-line globalDate:off
351 failProviderWorkspaceSnapshotRefresh(state, now, Date.now(), cooldownMs),
352 );
353 };
354 const retryLater = () => retry();
355 void runAtomCommand(
356 registry,
357 input.refreshProviders,
358 { environmentId, input: { instanceId, cwd } },
359 { reportFailure: false },
360 ).then((result) => {
361 const refreshedProvider =
362 result._tag === "Success" ? findProvider(result.value.providers) : undefined;
363 const snapshot =
364 refreshedProvider && resolveProviderWorkspaceSnapshot(refreshedProvider, cwd);
365 // A new server timestamp proves progress even when the client clock is ahead.
366 // @effect-diagnostics-next-line globalDate:off
367 const completedAt = Date.now();
368 const refreshed =
369 hasCompleteProviderWorkspaceSnapshot(refreshedProvider, cwd) &&
370 (hasCurrentProviderWorkspaceSnapshot(refreshedProvider, cwd, completedAt) ||
371 snapshot?.checkedAt !==
372 (provider && resolveProviderWorkspaceSnapshot(provider, cwd))?.checkedAt);
373 if (!refreshed) return retryLater();
374 // A reply is dropped when the provider changed while it was in flight, such as a
375 // SessionStart rescan; ask again at once for the snapshot that change produced.
376 const held = findProvider(registry.get(input.providers(environmentId)));
377 if (!hasCompleteProviderWorkspaceSnapshot(held, cwd)) retry(0);
378 }, retryLater);
379 return plan.state;
380 },
381 (ctx, update: Update) => {
382 ctx.setSelf(update(ctx.get(refreshAtom)));
383 ctx.refreshSelf();
384 },
385 ).pipe(Atom.withLabel(`provider-workspace-snapshot-refresh:${key}`));
386 return refreshAtom;
387 });
388 return (
389 target: ProviderWorkspaceSnapshotRefreshTarget,
390 ): Atom.Atom<ProviderWorkspaceSnapshotRefreshState> =>
391 family({ environmentId: target.environmentId, instanceId: target.instanceId, cwd: target.cwd });