The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import { |
| 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"; |
| 11 | import { Atom } from "effect/reactivity"; |
| 12 | |
| 13 | import { deadlineStore } from "./clock.ts"; |
| 14 | import { type AtomCommand, runAtomCommand } from "./state/runtime.ts"; |
| 15 | |
| 16 | export type ProviderSkillSourceKind = "app" | "repo" | "project" | "personal" | "system" | "other"; |
| 17 | |
| 18 | function normalizePathSeparators(pathValue: string): string { |
| 19 | return pathValue.replaceAll("\\", "/"); |
| 20 | } |
| 21 | |
| 22 | export 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 | }); |
| 34 | } |
| 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 | */ |
| 40 | export function isProviderSkillUserInvocable( |
| 41 | skill: Pick<ServerProviderSkill, "enabled" | "userInvocable">, |
| 42 | ): boolean { |
| 43 | return skill.enabled && skill.userInvocable !== false; |
| 44 | } |
| 45 | |
| 46 | export function getProviderSkillsForSlashMenu( |
| 47 | skills: ReadonlyArray<ServerProviderSkill>, |
| 48 | showSkillsInSlashMenu: boolean, |
| 49 | ): ServerProviderSkill[] { |
| 50 | return showSkillsInSlashMenu |
| 51 | ? dedupeProviderSkillsByName(skills.filter(isProviderSkillUserInvocable)) |
| 52 | : []; |
| 53 | } |
| 54 | |
| 55 | export 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())); |
| 61 | } |
| 62 | |
| 63 | export 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 | } |
| 91 | } |
| 92 | |
| 93 | function resolveProviderWorkspaceSnapshot( |
| 94 | provider: ServerProvider, |
| 95 | cwd: string | null | undefined, |
| 96 | ) { |
| 97 | if (!cwd) return undefined; |
| 98 | return provider.workspaceSnapshots?.find((snapshot) => snapshot.cwd === cwd); |
| 99 | } |
| 100 | |
| 101 | export 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)); |
| 107 | } |
| 108 | |
| 109 | function 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 | ); |
| 120 | } |
| 121 | |
| 122 | export function resolveProviderSkillsForCwd( |
| 123 | provider: ServerProvider, |
| 124 | cwd: string | null | undefined, |
| 125 | ): ServerProvider["skills"] { |
| 126 | return resolveProviderWorkspaceSnapshot(provider, cwd)?.skills ?? provider.skills; |
| 127 | } |
| 128 | |
| 129 | export function resolveProviderSlashCommandsForCwd( |
| 130 | provider: ServerProvider, |
| 131 | cwd: string | null | undefined, |
| 132 | ): ServerProvider["slashCommands"] { |
| 133 | return resolveProviderWorkspaceSnapshot(provider, cwd)?.slashCommands ?? provider.slashCommands; |
| 134 | } |
| 135 | |
| 136 | /** A project's own provider config can add models that only its workspace snapshot lists. */ |
| 137 | function resolveProviderModelsForCwd( |
| 138 | provider: ServerProvider, |
| 139 | cwd: string | null | undefined, |
| 140 | ): ServerProvider["models"] { |
| 141 | return resolveProviderWorkspaceSnapshot(provider, cwd)?.models ?? provider.models; |
| 142 | } |
| 143 | |
| 144 | /** Providers keep their identity unless the cwd has its own catalog. */ |
| 145 | export function resolveProvidersForCwd<P extends ServerProvider>( |
| 146 | providers: ReadonlyArray<P>, |
| 147 | cwd: string | null | undefined, |
| 148 | ): ReadonlyArray<P> { |
| 149 | const resolved = providers.map((provider) => { |
| 150 | const models = resolveProviderModelsForCwd(provider, cwd); |
| 151 | return models === provider.models ? provider : { ...provider, models }; |
| 152 | }); |
| 153 | return resolved.every((provider, index) => provider === providers[index]) ? providers : resolved; |
| 154 | } |
| 155 | |
| 156 | const WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS = 10_000; |
| 157 | // A cwd that never scans, such as a deleted worktree, would otherwise retry forever. |
| 158 | const WORKSPACE_SNAPSHOT_MAX_ATTEMPTS = 3; |
| 159 | |
| 160 | export interface ProviderWorkspaceSnapshotRefreshState { |
| 161 | /** |
| 162 | * When the last scan was requested. A request inside the TTL is not |
| 163 | * repeated, so a client clock ahead of the server's cannot loop rescans. |
| 164 | */ |
| 165 | readonly requestedAt: number | null; |
| 166 | /** A failed scan is not retried before this time. */ |
| 167 | readonly retryNotBefore: number | null; |
| 168 | /** Failed scans within the current request TTL. */ |
| 169 | readonly failedAttempts: number; |
| 170 | readonly hadSnapshot: boolean; |
| 171 | /** The server published a partial snapshot and is still discovering. */ |
| 172 | readonly snapshotPending: boolean; |
| 173 | } |
| 174 | |
| 175 | const initialProviderWorkspaceSnapshotRefreshState: ProviderWorkspaceSnapshotRefreshState = { |
| 176 | requestedAt: null, |
| 177 | retryNotBefore: null, |
| 178 | failedAttempts: 0, |
| 179 | hadSnapshot: false, |
| 180 | snapshotPending: false, |
| 181 | }; |
| 182 | |
| 183 | /** |
| 184 | * Decides whether a composer looking at `cwd` should ask the server to rescan |
| 185 | * the provider's workspace, and when to look again if a retry is due while the |
| 186 | * server still reports the scan as pending. |
| 187 | */ |
| 188 | function planProviderWorkspaceSnapshotRefresh( |
| 189 | previous: ProviderWorkspaceSnapshotRefreshState, |
| 190 | provider: ServerProvider | null | undefined, |
| 191 | cwd: string, |
| 192 | now: number, |
| 193 | ): { |
| 194 | readonly state: ProviderWorkspaceSnapshotRefreshState; |
| 195 | readonly refresh: boolean; |
| 196 | readonly recheckAt: number | null; |
| 197 | } { |
| 198 | const hasSnapshot = hasCompleteProviderWorkspaceSnapshot(provider, cwd); |
| 199 | const snapshot = provider && resolveProviderWorkspaceSnapshot(provider, cwd); |
| 200 | const pending = Boolean(snapshot && isProviderWorkspaceSnapshotPending(snapshot)); |
| 201 | // Losing a snapshot (the server dropped it) lifts both the TTL and the retry |
| 202 | // cooldown so the scan happens at once. |
| 203 | const lost = previous.hadSnapshot && !hasSnapshot; |
| 204 | const requestedAt = lost ? null : previous.requestedAt; |
| 205 | const retryNotBefore = |
| 206 | lost || (previous.retryNotBefore !== null && now >= previous.retryNotBefore) |
| 207 | ? null |
| 208 | : previous.retryNotBefore; |
| 209 | const state = { |
| 210 | requestedAt, |
| 211 | retryNotBefore, |
| 212 | failedAttempts: |
| 213 | lost || (requestedAt !== null && now - requestedAt >= PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS) |
| 214 | ? 0 |
| 215 | : previous.failedAttempts, |
| 216 | hadSnapshot: hasSnapshot, |
| 217 | snapshotPending: pending, |
| 218 | }; |
| 219 | const refresh = |
| 220 | (requestedAt === null || now - requestedAt >= PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS) && |
| 221 | !hasCurrentProviderWorkspaceSnapshot(provider, cwd, now) && |
| 222 | retryNotBefore === null; |
| 223 | if (refresh) { |
| 224 | return { state: { ...state, requestedAt: now }, refresh: true, recheckAt: null }; |
| 225 | } |
| 226 | return { state, refresh: false, recheckAt: pending ? retryNotBefore : null }; |
| 227 | } |
| 228 | |
| 229 | /** |
| 230 | * A scan that failed, or finished without a complete snapshot, cools down |
| 231 | * before retrying. After the last attempt the request marker stays, so only |
| 232 | * the TTL (or a snapshot loss) lets the next scan through. |
| 233 | */ |
| 234 | function failProviderWorkspaceSnapshotRefresh( |
| 235 | state: ProviderWorkspaceSnapshotRefreshState, |
| 236 | requestedAt: number, |
| 237 | now: number, |
| 238 | cooldownMs = WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS, |
| 239 | ): ProviderWorkspaceSnapshotRefreshState { |
| 240 | // A newer request, or a snapshot loss, already superseded this one. |
| 241 | if (state.requestedAt !== requestedAt) return state; |
| 242 | const failedAttempts = state.failedAttempts + 1; |
| 243 | if (failedAttempts >= WORKSPACE_SNAPSHOT_MAX_ATTEMPTS) return { ...state, failedAttempts }; |
| 244 | return { |
| 245 | ...state, |
| 246 | requestedAt: null, |
| 247 | retryNotBefore: cooldownMs === 0 ? null : now + cooldownMs, |
| 248 | failedAttempts, |
| 249 | }; |
| 250 | } |
| 251 | |
| 252 | /** |
| 253 | * A scan is in flight, or the server is still discovering, for a cwd without a |
| 254 | * complete snapshot, so its skills and commands may still arrive. A failed scan |
| 255 | * clears `requestedAt`, and exhausted attempts end it, so this cannot stay true |
| 256 | * for a scan that will not finish. |
| 257 | */ |
| 258 | export function isProviderWorkspaceSnapshotScanning( |
| 259 | state: ProviderWorkspaceSnapshotRefreshState | undefined, |
| 260 | ): boolean { |
| 261 | return ( |
| 262 | state !== undefined && |
| 263 | (state.requestedAt !== null || state.snapshotPending) && |
| 264 | !state.hadSnapshot && |
| 265 | state.failedAttempts < WORKSPACE_SNAPSHOT_MAX_ATTEMPTS |
| 266 | ); |
| 267 | } |
| 268 | |
| 269 | type WorkspaceSnapshotStatus = "absent" | "pending" | "complete"; |
| 270 | |
| 271 | function resolveWorkspaceSnapshotStatus( |
| 272 | provider: ServerProvider | undefined, |
| 273 | cwd: string, |
| 274 | ): WorkspaceSnapshotStatus { |
| 275 | const snapshot = provider && resolveProviderWorkspaceSnapshot(provider, cwd); |
| 276 | if (!snapshot) return "absent"; |
| 277 | return isProviderWorkspaceSnapshotPending(snapshot) ? "pending" : "complete"; |
| 278 | } |
| 279 | |
| 280 | interface ProviderWorkspaceSnapshotRefreshTarget { |
| 281 | readonly environmentId: EnvironmentId; |
| 282 | readonly instanceId: ProviderInstanceId; |
| 283 | readonly cwd: string; |
| 284 | } |
| 285 | |
| 286 | /** |
| 287 | * Keeps one environment/provider/cwd workspace snapshot fresh while mounted: |
| 288 | * reading scans when it is missing or stale, and refreshing re-checks (the |
| 289 | * composer does as the user types). It owns the retry timer, so the timer dies |
| 290 | * with the last subscriber. |
| 291 | */ |
| 292 | export function createProviderWorkspaceSnapshotRefreshAtomFamily(input: { |
| 293 | readonly providers: ( |
| 294 | environmentId: EnvironmentId, |
| 295 | ) => Atom.Atom<ReadonlyArray<ServerProvider> | null>; |
| 296 | readonly refreshProviders: AtomCommand< |
| 297 | { |
| 298 | readonly environmentId: EnvironmentId; |
| 299 | readonly input: { readonly instanceId: ProviderInstanceId; readonly cwd: string }; |
| 300 | }, |
| 301 | { readonly providers: ReadonlyArray<ServerProvider> }, |
| 302 | unknown |
| 303 | >; |
| 304 | }) { |
| 305 | // Plain-object keys compare structurally (Effect `Equal`/`Hash`). |
| 306 | const family = Atom.family((target: ProviderWorkspaceSnapshotRefreshTarget) => { |
| 307 | const { environmentId, instanceId, cwd } = target; |
| 308 | const key = `${environmentId}:${instanceId}:${cwd}`; |
| 309 | const findProvider = (providers: ReadonlyArray<ServerProvider> | null) => |
| 310 | providers?.find((provider) => provider.instanceId === instanceId); |
| 311 | const statusAtom = Atom.make((get) => |
| 312 | resolveWorkspaceSnapshotStatus(findProvider(get(input.providers(environmentId))), cwd), |
| 313 | ).pipe(Atom.withLabel(`provider-workspace-snapshot-status:${key}`)); |
| 314 | type Update = ( |
| 315 | state: ProviderWorkspaceSnapshotRefreshState, |
| 316 | ) => ProviderWorkspaceSnapshotRefreshState; |
| 317 | const refreshAtom: Atom.Writable<ProviderWorkspaceSnapshotRefreshState, Update> = Atom.writable( |
| 318 | (get): ProviderWorkspaceSnapshotRefreshState => { |
| 319 | get(statusAtom); |
| 320 | // `once`: unrelated provider updates must not trigger a check. |
| 321 | const provider = findProvider(get.once(input.providers(environmentId))); |
| 322 | // @effect-diagnostics-next-line globalDate:off |
| 323 | const now = Date.now(); |
| 324 | const previous = get.self<ProviderWorkspaceSnapshotRefreshState>(); |
| 325 | const plan = planProviderWorkspaceSnapshotRefresh( |
| 326 | previous._tag === "Some" ? previous.value : initialProviderWorkspaceSnapshotRefreshState, |
| 327 | provider, |
| 328 | cwd, |
| 329 | now, |
| 330 | ); |
| 331 | if (plan.recheckAt !== null) { |
| 332 | get.addFinalizer(deadlineStore(plan.recheckAt).subscribe(() => get.refreshSelf())); |
| 333 | } |
| 334 | if (!plan.refresh) return plan.state; |
| 335 | const registry = get.registry; |
| 336 | // Outlives this build on purpose: a rebuild must not drop the retry. |
| 337 | // Once nothing subscribes, the retry state dies with the node; writing |
| 338 | // would recreate and rebuild it, which scans again with no subscriber. |
| 339 | const retry = (cooldownMs?: number) => { |
| 340 | const node = registry.getNodes().get(refreshAtom); |
| 341 | if (node === undefined || node.canBeRemoved) return; |
| 342 | registry.set(refreshAtom, (state) => |
| 343 | // @effect-diagnostics-next-line globalDate:off |
| 344 | failProviderWorkspaceSnapshotRefresh(state, now, Date.now(), cooldownMs), |
| 345 | ); |
| 346 | }; |
| 347 | const retryLater = () => retry(); |
| 348 | void runAtomCommand( |
| 349 | registry, |
| 350 | input.refreshProviders, |
| 351 | { environmentId, input: { instanceId, cwd } }, |
| 352 | { reportFailure: false }, |
| 353 | ).then((result) => { |
| 354 | const refreshedProvider = |
| 355 | result._tag === "Success" ? findProvider(result.value.providers) : undefined; |
| 356 | const snapshot = |
| 357 | refreshedProvider && resolveProviderWorkspaceSnapshot(refreshedProvider, cwd); |
| 358 | // A new server timestamp proves progress even when the client clock is ahead. |
| 359 | // @effect-diagnostics-next-line globalDate:off |
| 360 | const completedAt = Date.now(); |
| 361 | const refreshed = |
| 362 | hasCompleteProviderWorkspaceSnapshot(refreshedProvider, cwd) && |
| 363 | (hasCurrentProviderWorkspaceSnapshot(refreshedProvider, cwd, completedAt) || |
| 364 | snapshot?.checkedAt !== |
| 365 | (provider && resolveProviderWorkspaceSnapshot(provider, cwd))?.checkedAt); |
| 366 | if (!refreshed) return retryLater(); |
| 367 | // A reply is dropped when the provider changed while it was in flight, such as a |
| 368 | // SessionStart rescan; ask again at once for the snapshot that change produced. |
| 369 | const held = findProvider(registry.get(input.providers(environmentId))); |
| 370 | if (!hasCompleteProviderWorkspaceSnapshot(held, cwd)) retry(0); |
| 371 | }, retryLater); |
| 372 | return plan.state; |
| 373 | }, |
| 374 | (ctx, update: Update) => { |
| 375 | ctx.setSelf(update(ctx.get(refreshAtom))); |
| 376 | ctx.refreshSelf(); |
| 377 | }, |
| 378 | ).pipe(Atom.withLabel(`provider-workspace-snapshot-refresh:${key}`)); |
| 379 | return refreshAtom; |
| 380 | }); |
| 381 | return ( |
| 382 | target: ProviderWorkspaceSnapshotRefreshTarget, |
| 383 | ): Atom.Atom<ProviderWorkspaceSnapshotRefreshState> => |
| 384 | family({ environmentId: target.environmentId, instanceId: target.instanceId, cwd: target.cwd }); |
| 385 | } |