forked from ericc-ch/copilot-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
190 lines (157 loc) · 4.88 KB
/
utils.ts
File metadata and controls
190 lines (157 loc) · 4.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import type { Context } from "hono"
import consola from "consola"
import type { Account } from "~/lib/account-pool"
import type { ApiContext } from "~/lib/api-config"
import type { Model } from "~/services/copilot/get-models"
import { getModels } from "~/services/copilot/get-models"
import { getVSCodeVersion } from "~/services/get-vscode-version"
import { state } from "./state"
export const sleep = (ms: number) =>
new Promise((resolve) => {
setTimeout(resolve, ms)
})
export const isNullish = (value: unknown): value is null | undefined =>
value === null || value === undefined
export function normalizeClaudeModelVersion(model: string): string {
if (!model.startsWith("claude-")) {
return model
}
// Convert numeric segments from hyphen to dot, e.g. claude-opus-4-6 -> claude-opus-4.6.
// Only replace when the next numeric token ends at '-' or end, so suffixes like '-1m' stay unchanged.
return model.replaceAll(/(\d)-(?=\d(?:-|$))/g, "$1.")
}
/**
* Resolve model ID by checking the anthropic-beta header for context window variants.
*/
export function resolveModelId(model: string, c?: Context): string {
const normalized = normalizeClaudeModelVersion(model)
if (!c) {
return normalized
}
const betaHeader = c.req.header("anthropic-beta")
if (
normalized.startsWith("claude-")
&& betaHeader
&& /\bcontext-1m\b/.test(betaHeader)
) {
if (normalized.endsWith("-1m")) {
return normalized
}
return `${normalized}-1m`
}
return normalized
}
/**
* Calculate Jaccard similarity between two strings based on character bigrams.
*/
function getBigrams(str: string): Set<string> {
const bigrams = new Set<string>()
const normalized = str.toLowerCase().replaceAll(/[^a-z0-9]/g, "")
for (let i = 0; i < normalized.length - 1; i++) {
bigrams.add(normalized.slice(i, i + 2))
}
return bigrams
}
export function jaccardSimilarity(str1: string, str2: string): number {
const bigrams1 = getBigrams(str1)
const bigrams2 = getBigrams(str2)
if (bigrams1.size === 0 && bigrams2.size === 0) {
return 1
}
let intersection = 0
for (const bigram of bigrams1) {
if (bigrams2.has(bigram)) {
intersection++
}
}
const union = bigrams1.size + bigrams2.size - intersection
return union === 0 ? 0 : intersection / union
}
function findBestModelMatch(
modelId: string,
models: Array<Model>,
minSimilarity = 0.3,
): Model | null {
if (models.length === 0) {
return null
}
let bestMatch: Model | null = null
let bestScore = 0
for (const model of models) {
const score = jaccardSimilarity(modelId, model.id)
if (score > bestScore) {
bestScore = score
bestMatch = model
}
}
if (bestScore >= minSimilarity && bestMatch) {
consola.info(
`Fuzzy matched model "${modelId}" to "${bestMatch.id}" (similarity: ${bestScore.toFixed(2)})`,
)
return bestMatch
}
return null
}
/**
* Resolve a requested model ID against available Copilot models.
* Order: exact -> fuzzy -> auto-version fallback -> first available.
*/
export function mapModelIdToAvailableModels(
requestedModelId: string,
models: Array<Model>,
): string {
if (models.length === 0) {
return requestedModelId
}
const exact = models.find((m) => m.id === requestedModelId)
if (exact) {
return exact.id
}
const fuzzy = findBestModelMatch(requestedModelId, models)
if (fuzzy) {
return fuzzy.id
}
const autoModel = models.find((m) => m.id === "auto")
const autoVersionModel = models.find((m) => m.version === autoModel?.version)
if (autoVersionModel) {
consola.info(
`Model "${requestedModelId}" not found, using ${autoVersionModel.id} model`,
)
return autoVersionModel.id
}
const fallback = models[0]
consola.info(
`Model "${requestedModelId}" not found, using first available model: ${fallback.id}`,
)
return fallback.id
}
/**
* Resolve model ID from request metadata, then map to an available server model.
*/
export function resolveAndMapModelId(
model: string,
c?: Context,
models: Array<Model> = state.models?.data ?? [],
): string {
const resolved = resolveModelId(model, c)
return mapModelIdToAvailableModels(resolved, models)
}
export function makeApiContext(account: Account): ApiContext {
return { account, vsCodeVersion: state.vsCodeVersion }
}
/** Returns an ApiContext for the first available pool account. */
export function defaultApiContext(): ApiContext {
if (!state.pool || state.pool.accounts.length === 0) {
throw new Error("Account pool is empty; cannot build ApiContext")
}
return makeApiContext(state.pool.accounts[0])
}
export async function cacheModels(): Promise<void> {
const models = await getModels(defaultApiContext())
state.models = models
}
export const cacheVSCodeVersion = async () => {
const response = await getVSCodeVersion()
state.vsCodeVersion = response
consola.info(`Using VSCode version: ${response}`)
}