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

providerSkills.ts

358 lines13.1 KB

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