Open History to see the last commit
1import {
2 repositoryGroupingKeyOf,
3 type EnvironmentId,
4 type ModelSelection,
5 type PullRequestLinkedThreadsResult,
6 type RepositoryIdentity,
7 type ServerProvider,
8 type ThreadLinkedPullRequest,
9 type ThreadId,
10 type ThreadPullRequestLink,
11} from "@t3tools/contracts";
12import { resolveSelectableModel, type SelectableModelOption } from "@t3tools/shared/model";
13import type { AsyncResult } from "effect/reactivity";
14import type { PromptLinkPullRequest, PromptLinkRepository } from "@t3tools/shared/promptLinks";
15import {
16 threadPullRequestKeyOf,
17 threadPullRequestsOf,
18 visibleThreadPullRequests,
19} from "./threadPullRequests.ts";
20
21// A link's `owner/name` is GitHub's. GitCafe syncs a repository two-way with GitHub under the
22// same path, so a checkout cloned from git.cafe counts as the linked repository.
23const PROMPT_LINK_REPOSITORY_HOSTS = ["github.com", "git.cafe", "staging.git.cafe"];
24
25/**
26 * The repository's projects in the order given. Callers pass projects most recently active
27 * first and open the first, so the user lands where they last worked.
28 */
29export function findPromptLinkProjects<
30 P extends { readonly repositoryIdentity?: RepositoryIdentity | null | undefined },
31>(projects: ReadonlyArray<P>, repository: PromptLinkRepository): P[] {
32 const path = `${repository.owner}/${repository.name}`.toLowerCase();
33 const keys = new Set(PROMPT_LINK_REPOSITORY_HOSTS.map((host) => `${host}/${path}`));
34 return projects.filter(
35 (project) =>
36 project.repositoryIdentity != null &&
37 keys.has(repositoryGroupingKeyOf(project.repositoryIdentity).toLowerCase()),
38 );
39}
40
41export function findPromptLinkPullRequestThread<
42 T extends {
43 readonly updatedAt: string;
44 readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
45 readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
46 },
47>(threads: ReadonlyArray<T>, pullRequest: PromptLinkPullRequest): T | undefined {
48 const key = threadPullRequestKeyOf({
49 host: "github.com",
50 repository: `${pullRequest.owner}/${pullRequest.name}`,
51 number: pullRequest.number,
52 });
53 let latest: T | undefined;
54 for (const thread of threads) {
55 if (latest !== undefined && thread.updatedAt <= latest.updatedAt) continue;
56 const linked = visibleThreadPullRequests(threadPullRequestsOf(thread)).some(
57 (link) => threadPullRequestKeyOf(link) === key,
58 );
59 if (linked) latest = thread;
60 }
61 return latest;
62}
63
64/**
65 * The first open thread from per-environment pull request lookups, in the order given, once
66 * every lookup before it has answered. `null` when none has one; `undefined` until then.
67 */
68export function pickPromptLinkPullRequestThread(
69 lookups: ReadonlyArray<{
70 readonly environmentId: EnvironmentId;
71 readonly result: AsyncResult.AsyncResult<PullRequestLinkedThreadsResult, unknown>;
72 }>,
73): { readonly environmentId: EnvironmentId; readonly id: ThreadId } | null | undefined {
74 for (const { environmentId, result } of lookups) {
75 if (result._tag === "Initial" || result.waiting) return undefined;
76 const thread =
77 result._tag === "Success"
78 ? result.value.threads.find((candidate) => candidate.archivedAt === null)
79 : undefined;
80 if (thread !== undefined) return { environmentId, id: thread.id };
81 }
82 return null;
83}
84
85const PROVIDER_ALIASES: Record<string, string> = { claude: "claudeagent" };
86
87/**
88 * `exact` is false when the instance exists but the model does not, so its default model
89 * stands in. Null when no usable instance of that provider exists; the user's default
90 * applies then.
91 */
92export function resolvePromptLinkModelSelection(
93 providers: ReadonlyArray<
94 Pick<ServerProvider, "instanceId" | "driver" | "enabled" | "availability" | "status"> & {
95 readonly models: ReadonlyArray<
96 SelectableModelOption & { readonly isDefault?: boolean | undefined }
97 >;
98 }
99 >,
100 request: { readonly provider: string; readonly model: string | null },
101): { readonly selection: ModelSelection; readonly exact: boolean } | null {
102 const driver = PROVIDER_ALIASES[request.provider] ?? request.provider;
103 const usable = providers.filter(
104 (provider) =>
105 provider.driver.toLowerCase() === driver &&
106 provider.enabled &&
107 provider.availability !== "unavailable",
108 );
109 const instance =
110 usable.find((provider) => provider.status === "ready") ??
111 usable.find((provider) => provider.status === "warning");
112 if (instance === undefined) return null;
113 const requested =
114 request.model === null
115 ? null
116 : resolveSelectableModel(instance.driver, request.model, instance.models);
117 const model =
118 requested ??
119 (instance.models.find((candidate) => candidate.isDefault) ?? instance.models[0])?.slug;
120 if (model === undefined) return null;
121 return {
122 selection: { instanceId: instance.instanceId, model },
123 exact: request.model === null || requested !== null,
124 };
125}