@eduardo191labs/opencode-free-pi 0.2.7 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +151 -157
- package/dist/ads/context.d.ts +18 -0
- package/dist/ads/context.js +125 -0
- package/dist/ads/impression.d.ts +7 -0
- package/dist/ads/impression.js +85 -0
- package/dist/ads/resolve.d.ts +11 -0
- package/dist/ads/resolve.js +35 -0
- package/dist/ads/turns.d.ts +6 -0
- package/dist/ads/turns.js +14 -0
- package/dist/api/quota.d.ts +8 -0
- package/dist/api/quota.js +90 -0
- package/dist/api/session.d.ts +9 -0
- package/dist/api/session.js +69 -0
- package/dist/auth/authorize.d.ts +14 -0
- package/dist/auth/authorize.js +60 -0
- package/dist/auth/connect.d.ts +7 -0
- package/dist/auth/connect.js +117 -0
- package/dist/auth/credential.d.ts +5 -0
- package/dist/auth/credential.js +34 -0
- package/dist/auth/credentials.d.ts +7 -0
- package/dist/auth/credentials.js +56 -0
- package/dist/auth/jwt.d.ts +7 -0
- package/dist/auth/jwt.js +60 -0
- package/dist/auth/token.d.ts +14 -0
- package/dist/auth/token.js +28 -0
- package/dist/catalog/catalog.d.ts +6 -0
- package/dist/catalog/catalog.js +80 -0
- package/dist/catalog/models.d.ts +15 -0
- package/dist/catalog/models.js +206 -0
- package/dist/catalog/registry.d.ts +9 -0
- package/dist/catalog/registry.js +96 -0
- package/dist/catalog/v2.d.ts +18 -0
- package/dist/catalog/v2.js +93 -0
- package/dist/constants.d.ts +46 -0
- package/dist/constants.js +46 -0
- package/dist/deps.d.ts +11 -0
- package/dist/deps.js +2 -0
- package/dist/errors/handle.d.ts +5 -0
- package/dist/errors/handle.js +64 -0
- package/dist/errors/invalid.d.ts +3 -0
- package/dist/errors/invalid.js +8 -0
- package/dist/errors/limit.d.ts +10 -0
- package/dist/errors/limit.js +110 -0
- package/dist/errors/messages.d.ts +6 -0
- package/dist/errors/messages.js +119 -0
- package/dist/errors/parse.d.ts +4 -0
- package/dist/errors/parse.js +153 -0
- package/dist/index.d.ts +9 -9
- package/dist/index.js +7 -3376
- package/dist/integration/setup.d.ts +4 -0
- package/dist/integration/setup.js +49 -0
- package/dist/logging.d.ts +9 -0
- package/dist/logging.js +62 -0
- package/dist/plugin.d.ts +4 -0
- package/dist/plugin.js +109 -0
- package/dist/session/events.d.ts +4 -0
- package/dist/session/events.js +96 -0
- package/dist/session/hooks.d.ts +8 -0
- package/dist/session/hooks.js +114 -0
- package/dist/session/track.d.ts +21 -0
- package/dist/session/track.js +107 -0
- package/dist/session/usage.d.ts +5 -0
- package/dist/session/usage.js +32 -0
- package/dist/state.d.ts +43 -0
- package/dist/state.js +26 -0
- package/dist/types.d.ts +272 -0
- package/dist/types.js +2 -0
- package/dist/utils/async.d.ts +8 -0
- package/dist/utils/async.js +29 -0
- package/dist/utils/browser.d.ts +3 -0
- package/dist/utils/browser.js +55 -0
- package/dist/utils/cache.d.ts +7 -0
- package/dist/utils/cache.js +45 -0
- package/dist/utils/device.d.ts +6 -0
- package/dist/utils/device.js +29 -0
- package/dist/utils/http.d.ts +4 -0
- package/dist/utils/http.js +42 -0
- package/dist/utils/json.d.ts +2 -0
- package/dist/utils/json.js +9 -0
- package/dist/utils/numbers.d.ts +6 -0
- package/dist/utils/numbers.js +49 -0
- package/dist/utils/text.d.ts +2 -0
- package/dist/utils/text.js +6 -0
- package/dist/utils/urls.d.ts +6 -0
- package/dist/utils/urls.js +41 -0
- package/install.ps1 +82 -46
- package/install.sh +98 -40
- package/package.json +5 -4
- package/scripts/postinstall.mjs +68 -34
- package/src/ads/context.ts +156 -0
- package/src/ads/impression.ts +111 -0
- package/src/ads/resolve.ts +62 -0
- package/src/ads/turns.ts +24 -0
- package/src/api/quota.ts +110 -0
- package/src/api/session.ts +76 -0
- package/src/auth/authorize.ts +104 -0
- package/src/auth/connect.ts +144 -0
- package/src/auth/credential.ts +39 -0
- package/src/auth/credentials.ts +60 -0
- package/src/auth/jwt.ts +75 -0
- package/src/auth/token.ts +52 -0
- package/src/catalog/catalog.ts +94 -0
- package/src/catalog/models.ts +291 -0
- package/src/catalog/registry.ts +122 -0
- package/src/catalog/v2.ts +124 -0
- package/src/constants.ts +61 -0
- package/src/deps.ts +13 -0
- package/src/errors/handle.ts +79 -0
- package/src/errors/invalid.ts +15 -0
- package/src/errors/limit.ts +114 -0
- package/src/errors/messages.ts +151 -0
- package/src/errors/parse.ts +156 -0
- package/src/index.ts +23 -4042
- package/src/integration/setup.ts +59 -0
- package/src/logging.ts +70 -0
- package/src/plugin.ts +143 -0
- package/src/session/events.ts +117 -0
- package/src/session/hooks.ts +192 -0
- package/src/session/track.ts +124 -0
- package/src/session/usage.ts +46 -0
- package/src/state.ts +82 -0
- package/src/types.ts +259 -0
- package/src/utils/async.ts +35 -0
- package/src/utils/browser.ts +61 -0
- package/src/utils/cache.ts +49 -0
- package/src/utils/device.ts +25 -0
- package/src/utils/http.ts +56 -0
- package/src/utils/json.ts +9 -0
- package/src/utils/numbers.ts +52 -0
- package/src/utils/text.ts +7 -0
- package/src/utils/urls.ts +47 -0
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
/** Turns the free-pi catalog and models.dev registry into model definitions. */
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
CONTEXT_WINDOW,
|
|
5
|
+
MAX_OUTPUT_TOKENS,
|
|
6
|
+
} from "../constants.js";
|
|
7
|
+
import type {
|
|
8
|
+
Catalog,
|
|
9
|
+
CatalogModel,
|
|
10
|
+
ModelDefinition,
|
|
11
|
+
ModelRegistry,
|
|
12
|
+
ModelsDevModel,
|
|
13
|
+
ReasoningOption,
|
|
14
|
+
RegistryCandidate,
|
|
15
|
+
} from "../types.js";
|
|
16
|
+
import { creditsToUsd, positiveNumber } from "../utils/numbers.js";
|
|
17
|
+
import { cleanText } from "../utils/text.js";
|
|
18
|
+
|
|
19
|
+
export type VariantMap = Record<string, Record<string, unknown>>;
|
|
20
|
+
export type ModelMap = Record<string, ModelDefinition>;
|
|
21
|
+
|
|
22
|
+
export function usableModels(catalog: Catalog | undefined): CatalogModel[] {
|
|
23
|
+
return (catalog?.models ?? []).filter(
|
|
24
|
+
(model) => typeof model.id === "string" && model.id.length > 0,
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function partitionModels(catalog: Catalog | undefined): {
|
|
29
|
+
main: CatalogModel[];
|
|
30
|
+
defense: CatalogModel[];
|
|
31
|
+
} {
|
|
32
|
+
const models = usableModels(catalog);
|
|
33
|
+
const main = models.filter((model) => model.section !== "defense");
|
|
34
|
+
const defense = models.filter((model) => model.section === "defense");
|
|
35
|
+
if (main.length > 0) return { main, defense };
|
|
36
|
+
if (
|
|
37
|
+
typeof catalog?.default_model === "string" &&
|
|
38
|
+
catalog.default_model.length > 0
|
|
39
|
+
) {
|
|
40
|
+
return { main: [{ id: catalog.default_model }], defense };
|
|
41
|
+
}
|
|
42
|
+
return { main: [], defense };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function displayName(model: CatalogModel): string {
|
|
46
|
+
const base = model.display_name || model.name || model.id || "model";
|
|
47
|
+
const tags: string[] = [];
|
|
48
|
+
const lower = base.toLowerCase();
|
|
49
|
+
if (model.free === true && !lower.includes("free")) tags.push("free");
|
|
50
|
+
if (
|
|
51
|
+
model.tier === "premium" &&
|
|
52
|
+
!lower.includes("premium") &&
|
|
53
|
+
!(model.note ?? "").toLowerCase().includes("premium")
|
|
54
|
+
) {
|
|
55
|
+
tags.push("premium");
|
|
56
|
+
}
|
|
57
|
+
if (model.note && !lower.includes(model.note.toLowerCase()))
|
|
58
|
+
tags.push(model.note);
|
|
59
|
+
if (model.usage_x && !lower.includes(`${model.usage_x}x`)) {
|
|
60
|
+
tags.push(`~${model.usage_x}x usage`);
|
|
61
|
+
}
|
|
62
|
+
return tags.length > 0 ? `${base} (${tags.join(" · ")})` : base;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function modelCost(
|
|
66
|
+
model: CatalogModel,
|
|
67
|
+
capability?: ModelsDevModel,
|
|
68
|
+
): ModelDefinition["cost"] {
|
|
69
|
+
const zero = { input: 0, output: 0, cache_read: 0, cache_write: 0 };
|
|
70
|
+
if (model.free === true) return zero;
|
|
71
|
+
const input =
|
|
72
|
+
creditsToUsd(model.input_credits_per_mtok) ||
|
|
73
|
+
positiveNumber(capability?.cost?.input) ||
|
|
74
|
+
0;
|
|
75
|
+
const output =
|
|
76
|
+
creditsToUsd(model.output_credits_per_mtok) ||
|
|
77
|
+
positiveNumber(capability?.cost?.output) ||
|
|
78
|
+
0;
|
|
79
|
+
if (input > 0 || output > 0) {
|
|
80
|
+
return {
|
|
81
|
+
input,
|
|
82
|
+
output,
|
|
83
|
+
cache_read:
|
|
84
|
+
creditsToUsd(model.cache_read_credits_per_mtok) ||
|
|
85
|
+
positiveNumber(capability?.cost?.cache_read) ||
|
|
86
|
+
input,
|
|
87
|
+
cache_write:
|
|
88
|
+
creditsToUsd(model.cache_write_credits_per_mtok) ||
|
|
89
|
+
positiveNumber(capability?.cost?.cache_write) ||
|
|
90
|
+
input,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
return zero;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function modelRegistryCandidates(
|
|
97
|
+
registry: ModelRegistry | undefined,
|
|
98
|
+
): RegistryCandidate[] {
|
|
99
|
+
const candidates: RegistryCandidate[] = [];
|
|
100
|
+
for (const [providerID, provider] of Object.entries(registry ?? {})) {
|
|
101
|
+
for (const [modelID, model] of Object.entries(provider?.models ?? {})) {
|
|
102
|
+
if (model && typeof model === "object")
|
|
103
|
+
candidates.push({ providerID, modelID, model });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return candidates;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function normalizeModelKey(value: string): string {
|
|
110
|
+
return value.toLowerCase().replace(/[^a-z0-9]+/g, "");
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function capabilityScore(
|
|
114
|
+
model: CatalogModel,
|
|
115
|
+
candidate: RegistryCandidate,
|
|
116
|
+
): number {
|
|
117
|
+
const id = model.id?.toLowerCase();
|
|
118
|
+
const stats = model.stats_id?.toLowerCase();
|
|
119
|
+
const candidateID = candidate.modelID.toLowerCase();
|
|
120
|
+
const candidateName = cleanText(candidate.model.name).toLowerCase();
|
|
121
|
+
const name = cleanText(model.display_name || model.name).toLowerCase();
|
|
122
|
+
let score = 0;
|
|
123
|
+
|
|
124
|
+
if (stats) {
|
|
125
|
+
const slash = stats.indexOf("/");
|
|
126
|
+
const providerHint = slash > 0 ? stats.slice(0, slash) : "";
|
|
127
|
+
const modelHint = slash > 0 ? stats.slice(slash + 1) : stats;
|
|
128
|
+
if (providerHint && candidate.providerID.toLowerCase() === providerHint)
|
|
129
|
+
score += 100;
|
|
130
|
+
if (candidateID === modelHint) score += 80;
|
|
131
|
+
else if (candidateID === stats) score += 60;
|
|
132
|
+
else if (candidateID.endsWith(`/${modelHint}`)) score += 50;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (id) {
|
|
136
|
+
if (candidateID === id) score += 50;
|
|
137
|
+
else if (candidateID.endsWith(`/${id}`)) score += 40;
|
|
138
|
+
else if (normalizeModelKey(candidateID) === normalizeModelKey(id))
|
|
139
|
+
score += 20;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
if (name && candidateName === name) score += 30;
|
|
143
|
+
else if (name && normalizeModelKey(candidateName) === normalizeModelKey(name))
|
|
144
|
+
score += 15;
|
|
145
|
+
if (model.release_date && candidate.model.release_date === model.release_date)
|
|
146
|
+
score += 10;
|
|
147
|
+
if (model.family && candidate.model.family === model.family) score += 5;
|
|
148
|
+
return score;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function modelCapability(
|
|
152
|
+
model: CatalogModel,
|
|
153
|
+
candidates: RegistryCandidate[],
|
|
154
|
+
): ModelsDevModel | undefined {
|
|
155
|
+
let best: ModelsDevModel | undefined;
|
|
156
|
+
let bestScore = 0;
|
|
157
|
+
let bestProvider = "";
|
|
158
|
+
let bestID = "";
|
|
159
|
+
for (const candidate of candidates) {
|
|
160
|
+
const score = capabilityScore(model, candidate);
|
|
161
|
+
if (score < 30) continue;
|
|
162
|
+
const provider = candidate.providerID.toLowerCase();
|
|
163
|
+
const id = candidate.modelID.toLowerCase();
|
|
164
|
+
if (
|
|
165
|
+
score > bestScore ||
|
|
166
|
+
(score === bestScore &&
|
|
167
|
+
(provider < bestProvider || (provider === bestProvider && id < bestID)))
|
|
168
|
+
) {
|
|
169
|
+
best = candidate.model;
|
|
170
|
+
bestScore = score;
|
|
171
|
+
bestProvider = provider;
|
|
172
|
+
bestID = id;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return best;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function budgetVariants(
|
|
179
|
+
option: Extract<ReasoningOption, { type: "budget_tokens" }>,
|
|
180
|
+
outputLimit: number,
|
|
181
|
+
variants: VariantMap,
|
|
182
|
+
): void {
|
|
183
|
+
const ceiling = Math.max(
|
|
184
|
+
1,
|
|
185
|
+
Math.min(
|
|
186
|
+
positiveNumber(option.max) ?? outputLimit - 1024,
|
|
187
|
+
outputLimit - 1024,
|
|
188
|
+
MAX_OUTPUT_TOKENS - 1024,
|
|
189
|
+
),
|
|
190
|
+
);
|
|
191
|
+
const floor = Math.min(positiveNumber(option.min) ?? 0, ceiling);
|
|
192
|
+
const high = Math.min(
|
|
193
|
+
Math.max(floor, Math.floor((ceiling + 1) / 2)),
|
|
194
|
+
ceiling,
|
|
195
|
+
);
|
|
196
|
+
for (const [level, budget] of [
|
|
197
|
+
["high", high],
|
|
198
|
+
["max", ceiling],
|
|
199
|
+
] as const) {
|
|
200
|
+
variants[level] = {
|
|
201
|
+
reasoningEffort: level,
|
|
202
|
+
thinking_budget: budget,
|
|
203
|
+
thinking: { type: "enabled", budget_tokens: budget },
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export function modelVariants(
|
|
209
|
+
options: ReasoningOption[] | undefined,
|
|
210
|
+
outputLimit: number,
|
|
211
|
+
): VariantMap {
|
|
212
|
+
const variants: VariantMap = {};
|
|
213
|
+
if (!options || options.length === 0) return variants;
|
|
214
|
+
const effort = options.find(
|
|
215
|
+
(option): option is Extract<ReasoningOption, { type: "effort" }> =>
|
|
216
|
+
option.type === "effort",
|
|
217
|
+
);
|
|
218
|
+
if (effort) {
|
|
219
|
+
for (const value of effort.values) {
|
|
220
|
+
variants[value] = { reasoningEffort: value };
|
|
221
|
+
}
|
|
222
|
+
return variants;
|
|
223
|
+
}
|
|
224
|
+
if (options.some((option) => option.type === "toggle")) {
|
|
225
|
+
variants.none = { reasoningEffort: "none" };
|
|
226
|
+
variants.high = { reasoningEffort: "high" };
|
|
227
|
+
}
|
|
228
|
+
const budget = options.find(
|
|
229
|
+
(option): option is Extract<ReasoningOption, { type: "budget_tokens" }> =>
|
|
230
|
+
option.type === "budget_tokens",
|
|
231
|
+
);
|
|
232
|
+
if (budget) budgetVariants(budget, outputLimit, variants);
|
|
233
|
+
return variants;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export function buildModels(
|
|
237
|
+
models: CatalogModel[],
|
|
238
|
+
candidates: RegistryCandidate[] = [],
|
|
239
|
+
): ModelMap {
|
|
240
|
+
const result: ModelMap = {};
|
|
241
|
+
for (const model of models) {
|
|
242
|
+
if (!model.id) continue;
|
|
243
|
+
const capability = modelCapability(model, candidates);
|
|
244
|
+
const reasoning = model.reasoning ?? capability?.reasoning ?? true;
|
|
245
|
+
const reasoningOptions =
|
|
246
|
+
model.reasoning_options ?? capability?.reasoning_options;
|
|
247
|
+
const limitContext =
|
|
248
|
+
positiveNumber(
|
|
249
|
+
model.context_window,
|
|
250
|
+
model.contextWindow,
|
|
251
|
+
model.limit?.context,
|
|
252
|
+
capability?.limit?.context,
|
|
253
|
+
) ?? CONTEXT_WINDOW;
|
|
254
|
+
const limitOutput =
|
|
255
|
+
positiveNumber(
|
|
256
|
+
model.max_tokens,
|
|
257
|
+
model.maxTokens,
|
|
258
|
+
model.max_output_tokens,
|
|
259
|
+
model.limit?.output,
|
|
260
|
+
capability?.limit?.output,
|
|
261
|
+
) ?? MAX_OUTPUT_TOKENS;
|
|
262
|
+
result[model.id] = {
|
|
263
|
+
id: model.id,
|
|
264
|
+
name: displayName(model),
|
|
265
|
+
family:
|
|
266
|
+
model.family ??
|
|
267
|
+
capability?.family ??
|
|
268
|
+
(model.section === "defense" ? "defense" : ""),
|
|
269
|
+
release_date: model.release_date ?? capability?.release_date,
|
|
270
|
+
reasoning,
|
|
271
|
+
reasoning_options: reasoningOptions,
|
|
272
|
+
variants: reasoning ? modelVariants(reasoningOptions, limitOutput) : {},
|
|
273
|
+
temperature: model.temperature ?? capability?.temperature ?? true,
|
|
274
|
+
tool_call: model.tool_call ?? capability?.tool_call ?? true,
|
|
275
|
+
attachment: model.attachment ?? capability?.attachment ?? false,
|
|
276
|
+
interleaved: model.interleaved ?? capability?.interleaved,
|
|
277
|
+
cost: modelCost(model, capability),
|
|
278
|
+
limit: { context: limitContext, output: limitOutput },
|
|
279
|
+
modalities: {
|
|
280
|
+
input: model.modalities?.input ??
|
|
281
|
+
capability?.modalities?.input ?? ["text"],
|
|
282
|
+
output: model.modalities?.output ??
|
|
283
|
+
capability?.modalities?.output ?? ["text"],
|
|
284
|
+
},
|
|
285
|
+
status: model.unavailable ? "deprecated" : "active",
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
return result;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/** Fetches the models.dev capability registry. */
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
REGISTRY_ATTEMPTS,
|
|
5
|
+
REGISTRY_DISK_TTL_MS,
|
|
6
|
+
REGISTRY_RETRY_MS,
|
|
7
|
+
REGISTRY_TIMEOUT_MS,
|
|
8
|
+
REGISTRY_TTL_MS,
|
|
9
|
+
} from "../constants.js";
|
|
10
|
+
import type { Deps } from "../deps.js";
|
|
11
|
+
import type { ModelRegistry } from "../types.js";
|
|
12
|
+
import { sleep } from "../utils/async.js";
|
|
13
|
+
import { readCache, writeCache } from "../utils/cache.js";
|
|
14
|
+
import { modelsRegistryUrl } from "../utils/urls.js";
|
|
15
|
+
|
|
16
|
+
const CACHE_FILE = "models-dev.json";
|
|
17
|
+
|
|
18
|
+
function isRegistry(value: unknown): value is ModelRegistry {
|
|
19
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function reasonText(error: unknown): string {
|
|
23
|
+
if (error instanceof Error) {
|
|
24
|
+
return error.name === "TimeoutError" ? "request timed out" : error.message;
|
|
25
|
+
}
|
|
26
|
+
return "request failed";
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function requestRegistry(): Promise<ModelRegistry> {
|
|
30
|
+
const base = modelsRegistryUrl();
|
|
31
|
+
const url = base.endsWith(".json") ? base : `${base}/api.json`;
|
|
32
|
+
let lastError: unknown;
|
|
33
|
+
for (let attempt = 1; attempt <= REGISTRY_ATTEMPTS; attempt += 1) {
|
|
34
|
+
try {
|
|
35
|
+
const response = await fetch(url, {
|
|
36
|
+
headers: { accept: "application/json" },
|
|
37
|
+
signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS),
|
|
38
|
+
});
|
|
39
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
40
|
+
return (await response.json()) as ModelRegistry;
|
|
41
|
+
} catch (error) {
|
|
42
|
+
lastError = error;
|
|
43
|
+
if (attempt < REGISTRY_ATTEMPTS) await sleep(500 * attempt);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
throw lastError instanceof Error
|
|
47
|
+
? lastError
|
|
48
|
+
: new Error("models.dev request failed");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Refreshes the registry without blocking callers that already have data.
|
|
53
|
+
* Concurrent calls share one request.
|
|
54
|
+
*/
|
|
55
|
+
export function refreshModelsRegistry(
|
|
56
|
+
deps: Deps,
|
|
57
|
+
): Promise<ModelRegistry | undefined> {
|
|
58
|
+
const state = deps.state;
|
|
59
|
+
if (state.registryPromise) return state.registryPromise;
|
|
60
|
+
const pending = (async () => {
|
|
61
|
+
state.registryAttemptAt = Date.now();
|
|
62
|
+
try {
|
|
63
|
+
const registry = await requestRegistry();
|
|
64
|
+
if (!isRegistry(registry)) {
|
|
65
|
+
throw new Error("models.dev returned an unexpected payload");
|
|
66
|
+
}
|
|
67
|
+
state.cachedRegistry = registry;
|
|
68
|
+
state.cachedRegistryAt = Date.now();
|
|
69
|
+
void writeCache(CACHE_FILE, registry);
|
|
70
|
+
return registry;
|
|
71
|
+
} catch (error) {
|
|
72
|
+
const cached = state.cachedRegistry;
|
|
73
|
+
deps.log.warn(
|
|
74
|
+
cached
|
|
75
|
+
? "models.dev is unreachable; using cached model metadata"
|
|
76
|
+
: "models.dev is unreachable; model limits fall back to defaults",
|
|
77
|
+
{ reason: reasonText(error) },
|
|
78
|
+
);
|
|
79
|
+
return cached;
|
|
80
|
+
}
|
|
81
|
+
})();
|
|
82
|
+
state.registryPromise = pending;
|
|
83
|
+
void pending.finally(() => {
|
|
84
|
+
if (state.registryPromise === pending) state.registryPromise = undefined;
|
|
85
|
+
});
|
|
86
|
+
return pending;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export async function fetchModelsRegistry(
|
|
90
|
+
deps: Deps,
|
|
91
|
+
): Promise<ModelRegistry | undefined> {
|
|
92
|
+
const state = deps.state;
|
|
93
|
+
if (
|
|
94
|
+
state.cachedRegistry &&
|
|
95
|
+
Date.now() - state.cachedRegistryAt < REGISTRY_TTL_MS
|
|
96
|
+
) {
|
|
97
|
+
return state.cachedRegistry;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
if (!state.cachedRegistry) {
|
|
101
|
+
const disk = await readCache<ModelRegistry>(
|
|
102
|
+
CACHE_FILE,
|
|
103
|
+
REGISTRY_DISK_TTL_MS,
|
|
104
|
+
);
|
|
105
|
+
if (isRegistry(disk)) {
|
|
106
|
+
state.cachedRegistry = disk;
|
|
107
|
+
state.cachedRegistryAt = Date.now();
|
|
108
|
+
// Serve the cached copy immediately and refresh it in the background.
|
|
109
|
+
void refreshModelsRegistry(deps);
|
|
110
|
+
return disk;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (
|
|
115
|
+
state.registryAttemptAt &&
|
|
116
|
+
Date.now() - state.registryAttemptAt < REGISTRY_RETRY_MS
|
|
117
|
+
) {
|
|
118
|
+
return state.cachedRegistry;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
return refreshModelsRegistry(deps);
|
|
122
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/** Converts internal model definitions into OpenCode V2 provider records. */
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
CONTEXT_WINDOW,
|
|
5
|
+
MAX_OUTPUT_TOKENS,
|
|
6
|
+
OPENAI_COMPATIBLE_PACKAGE,
|
|
7
|
+
PROVIDER_ID,
|
|
8
|
+
} from "../constants.js";
|
|
9
|
+
import { completionsBaseUrl } from "../utils/urls.js";
|
|
10
|
+
import type { ModelMap } from "./models.js";
|
|
11
|
+
|
|
12
|
+
type ProviderEditorLike = {
|
|
13
|
+
get(providerID: string): any;
|
|
14
|
+
add(input: {
|
|
15
|
+
info: any;
|
|
16
|
+
models: readonly any[];
|
|
17
|
+
sourceConnection?: any;
|
|
18
|
+
}): void;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export function toV2Models(providerID: string, models: ModelMap): any[] {
|
|
22
|
+
return Object.values(models).map((model) => {
|
|
23
|
+
const cost = model.cost ?? ({} as ModelMap[string]["cost"]);
|
|
24
|
+
const released = Date.parse(model.release_date ?? "");
|
|
25
|
+
return {
|
|
26
|
+
id: model.id,
|
|
27
|
+
modelID: model.id,
|
|
28
|
+
providerID,
|
|
29
|
+
name: model.name ?? model.id,
|
|
30
|
+
...(model.family ? { family: model.family } : {}),
|
|
31
|
+
capabilities: {
|
|
32
|
+
tools: model.tool_call !== false,
|
|
33
|
+
input: model.modalities?.input ?? ["text"],
|
|
34
|
+
output: model.modalities?.output ?? ["text"],
|
|
35
|
+
...(model.temperature === undefined
|
|
36
|
+
? {}
|
|
37
|
+
: { temperature: model.temperature }),
|
|
38
|
+
},
|
|
39
|
+
variants: Object.entries(model.variants ?? {}).map(([id, settings]) => ({
|
|
40
|
+
id,
|
|
41
|
+
settings,
|
|
42
|
+
})),
|
|
43
|
+
time: { released: Number.isFinite(released) ? released : 0 },
|
|
44
|
+
cost: [
|
|
45
|
+
{
|
|
46
|
+
input: cost.input ?? 0,
|
|
47
|
+
output: cost.output ?? 0,
|
|
48
|
+
cache: {
|
|
49
|
+
read: cost.cache_read ?? cost.input ?? 0,
|
|
50
|
+
write: cost.cache_write ?? cost.input ?? 0,
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
],
|
|
54
|
+
status: model.status === "deprecated" ? "deprecated" : "active",
|
|
55
|
+
enabled: true,
|
|
56
|
+
limit: {
|
|
57
|
+
context: model.limit?.context ?? CONTEXT_WINDOW,
|
|
58
|
+
output: model.limit?.output ?? MAX_OUTPUT_TOKENS,
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function baseProviderInfo(
|
|
65
|
+
providerID: string,
|
|
66
|
+
name: string,
|
|
67
|
+
token: string | undefined,
|
|
68
|
+
): any {
|
|
69
|
+
return {
|
|
70
|
+
id: providerID,
|
|
71
|
+
name,
|
|
72
|
+
activation: "enabled",
|
|
73
|
+
integrationID: PROVIDER_ID,
|
|
74
|
+
package: OPENAI_COMPATIBLE_PACKAGE,
|
|
75
|
+
settings: {
|
|
76
|
+
baseURL: completionsBaseUrl(),
|
|
77
|
+
apiKey: token ?? "free-pi",
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Adds a provider, merging an existing record so user or config overrides win.
|
|
84
|
+
* `editor.add` replaces the whole record, so the merge happens here.
|
|
85
|
+
*/
|
|
86
|
+
export function applyProvider(
|
|
87
|
+
editor: ProviderEditorLike,
|
|
88
|
+
providerID: string,
|
|
89
|
+
name: string,
|
|
90
|
+
models: ModelMap,
|
|
91
|
+
token: string | undefined,
|
|
92
|
+
): void {
|
|
93
|
+
const generated = toV2Models(providerID, models);
|
|
94
|
+
const existing = editor.get(providerID);
|
|
95
|
+
if (!existing) {
|
|
96
|
+
editor.add({ info: baseProviderInfo(providerID, name, token), models: generated });
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const base = baseProviderInfo(providerID, name, token);
|
|
101
|
+
const info = {
|
|
102
|
+
...base,
|
|
103
|
+
...existing.provider,
|
|
104
|
+
id: providerID,
|
|
105
|
+
settings: {
|
|
106
|
+
...base.settings,
|
|
107
|
+
...(existing.provider?.settings ?? {}),
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
const merged = new Map<string, any>();
|
|
112
|
+
for (const model of generated) merged.set(model.id, model);
|
|
113
|
+
for (const [id, model] of existing.models as ReadonlyMap<string, any>) {
|
|
114
|
+
merged.set(id, { ...(merged.get(id) ?? {}), ...model });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
editor.add({
|
|
118
|
+
info,
|
|
119
|
+
models: [...merged.values()],
|
|
120
|
+
...(existing.sourceConnection
|
|
121
|
+
? { sourceConnection: existing.sourceConnection }
|
|
122
|
+
: {}),
|
|
123
|
+
});
|
|
124
|
+
}
|
package/src/constants.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/** Identifiers and defaults shared by every part of the plugin. */
|
|
2
|
+
|
|
3
|
+
export const PROVIDER_ID = "free-pi";
|
|
4
|
+
export const DEFENSE_PROVIDER_ID = "free-pi-defense";
|
|
5
|
+
export const INTEGRATION_ID = PROVIDER_ID;
|
|
6
|
+
|
|
7
|
+
export const PROVIDER_NAME = "Free Pi";
|
|
8
|
+
export const DEFENSE_PROVIDER_NAME = "Free Pi Defense";
|
|
9
|
+
|
|
10
|
+
export const DEFAULT_BASE_URL = "https://api.freepi.ai";
|
|
11
|
+
export const DEFAULT_CLIENT_VERSION = "0.6.25";
|
|
12
|
+
export const CONSENT_VERSION = "4";
|
|
13
|
+
|
|
14
|
+
export const CONTEXT_WINDOW = 200_000;
|
|
15
|
+
export const MAX_OUTPUT_TOKENS = 32_768;
|
|
16
|
+
|
|
17
|
+
export const AD_CONTEXT_HEADER = "x-ad-context";
|
|
18
|
+
export const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
|
|
19
|
+
export const EFFICIENCY_RULE =
|
|
20
|
+
"- When several independent reads or searches are needed, issue them in the same turn.";
|
|
21
|
+
|
|
22
|
+
export const SESSION_TRACK_LIMIT = 200;
|
|
23
|
+
export const AUTH_SKEW_MS = 60_000;
|
|
24
|
+
export const AUTH_TIMEOUT_MS = 15 * 60_000;
|
|
25
|
+
export const AUTH_NETWORK_FAILURES = 6;
|
|
26
|
+
export const DEFAULT_TOKEN_LIFETIME_MS = 30 * 24 * 60 * 60_000;
|
|
27
|
+
export const REFRESH_PREFIX = "free-pi:v1:";
|
|
28
|
+
|
|
29
|
+
export const AD_CONTEXT_MAX_CHARS = 1_000;
|
|
30
|
+
export const AD_REQUEST_TIMEOUT_MS = 5_000;
|
|
31
|
+
export const AD_IMPRESSION_TIMEOUT_MS = 3_000;
|
|
32
|
+
export const AD_TURN_LIMIT = 200;
|
|
33
|
+
export const AD_IMPRESSION_LIMIT = 200;
|
|
34
|
+
|
|
35
|
+
export const CREDITS_PER_USD = 40_000 / 3;
|
|
36
|
+
|
|
37
|
+
export const CATALOG_TTL_MS = 10 * 60_000;
|
|
38
|
+
export const CATALOG_DISK_TTL_MS = 24 * 60 * 60_000;
|
|
39
|
+
export const CATALOG_TIMEOUT_MS = 8_000;
|
|
40
|
+
export const REGISTRY_TTL_MS = 5 * 60_000;
|
|
41
|
+
export const REGISTRY_DISK_TTL_MS = 7 * 24 * 60 * 60_000;
|
|
42
|
+
export const REGISTRY_RETRY_MS = 60_000;
|
|
43
|
+
export const REGISTRY_TIMEOUT_MS = 3_500;
|
|
44
|
+
export const REGISTRY_ATTEMPTS = 2;
|
|
45
|
+
export const DEFAULT_MODELS_REGISTRY_URL = "https://models.opencode.ai";
|
|
46
|
+
|
|
47
|
+
export const QUOTA_TTL_MS = 30_000;
|
|
48
|
+
export const QUOTA_HTTP_TIMEOUT_MS = 5_000;
|
|
49
|
+
export const QUOTA_REFRESH_DEBOUNCE_MS = 1_000;
|
|
50
|
+
|
|
51
|
+
export const SESSION_RESET_COOLDOWN_MS = 15_000;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* How long a free-pi session must stay quiet before its server slot is closed.
|
|
55
|
+
* Background compaction can start right after the last step, so closing on the
|
|
56
|
+
* execution event alone would race with it.
|
|
57
|
+
*/
|
|
58
|
+
export const SESSION_FINALIZE_DELAY_MS = 2_000;
|
|
59
|
+
|
|
60
|
+
export const OPENAI_COMPATIBLE_PACKAGE =
|
|
61
|
+
"@opencode/ai/providers/openai-compatible";
|
package/src/deps.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** Dependencies shared by the free-pi modules. */
|
|
2
|
+
|
|
3
|
+
import type { Credential } from "@opencode/schema/credential";
|
|
4
|
+
import type { Logger } from "./logging.js";
|
|
5
|
+
import type { RuntimeState } from "./state.js";
|
|
6
|
+
import type { ReadContext } from "./types.js";
|
|
7
|
+
|
|
8
|
+
export type Deps = {
|
|
9
|
+
readonly state: RuntimeState;
|
|
10
|
+
readonly log: Logger;
|
|
11
|
+
readonly activeCredential: () => Promise<Credential.Value | undefined>;
|
|
12
|
+
readonly readContext: ReadContext;
|
|
13
|
+
};
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/** Central handling for free-pi failures reported by the provider or session. */
|
|
2
|
+
|
|
3
|
+
import { fetchQuota, rememberTokenCheck } from "../api/quota.js";
|
|
4
|
+
import { resetFreePiSessions } from "../api/session.js";
|
|
5
|
+
import type { Deps } from "../deps.js";
|
|
6
|
+
import type { SessionResetOutcome } from "../types.js";
|
|
7
|
+
import { logInvalidToken } from "./invalid.js";
|
|
8
|
+
import {
|
|
9
|
+
freePiErrorSeverity,
|
|
10
|
+
freePiErrorTitle,
|
|
11
|
+
friendlyFreePiError,
|
|
12
|
+
} from "./messages.js";
|
|
13
|
+
import { parseFreePiError } from "./parse.js";
|
|
14
|
+
|
|
15
|
+
export async function handleFreePiError(
|
|
16
|
+
deps: Deps,
|
|
17
|
+
error: any,
|
|
18
|
+
opts: { allowRaw?: boolean } = {},
|
|
19
|
+
): Promise<void> {
|
|
20
|
+
const parsed = parseFreePiError(error, opts.allowRaw === true);
|
|
21
|
+
if (!parsed) return;
|
|
22
|
+
deps.state.lastFreePiError = parsed;
|
|
23
|
+
|
|
24
|
+
if (
|
|
25
|
+
parsed.status === 401 ||
|
|
26
|
+
parsed.code === "unauthorized" ||
|
|
27
|
+
parsed.code === "expired_token"
|
|
28
|
+
) {
|
|
29
|
+
const token = deps.state.quotaCache?.token;
|
|
30
|
+
if (token) rememberTokenCheck(deps, token, "invalid");
|
|
31
|
+
await logInvalidToken(deps, token);
|
|
32
|
+
void fetchQuota(deps, { force: true }).catch(() => undefined);
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
let message = friendlyFreePiError(parsed);
|
|
37
|
+
let resetOutcome: SessionResetOutcome | undefined;
|
|
38
|
+
if (parsed.code === "concurrent_session") {
|
|
39
|
+
resetOutcome = await resetFreePiSessions(deps);
|
|
40
|
+
if (resetOutcome === "released") {
|
|
41
|
+
message =
|
|
42
|
+
"free-pi was at its session limit; freed a stale slot automatically. Retry your request now.";
|
|
43
|
+
} else if (resetOutcome === "none") {
|
|
44
|
+
message =
|
|
45
|
+
"free-pi is at its session limit and no other session was running. Wait for a slot to free up and retry.";
|
|
46
|
+
} else if (resetOutcome === "failed" || resetOutcome === "unavailable") {
|
|
47
|
+
message =
|
|
48
|
+
"free-pi is at its session limit and the slot could not be freed automatically. Wait a moment and retry.";
|
|
49
|
+
} else {
|
|
50
|
+
message =
|
|
51
|
+
"free-pi session reset was just attempted; retry in a moment.";
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const key = `${parsed.code}\u0000${parsed.message ?? ""}`;
|
|
56
|
+
const now = Date.now();
|
|
57
|
+
if (key !== deps.state.lastErrorLogKey || now - deps.state.lastErrorLogAt > 15_000) {
|
|
58
|
+
deps.state.lastErrorLogKey = key;
|
|
59
|
+
deps.state.lastErrorLogAt = now;
|
|
60
|
+
const level = freePiErrorSeverity(parsed);
|
|
61
|
+
deps.log.log(level, `${freePiErrorTitle(parsed)}: ${message}`, {
|
|
62
|
+
code: parsed.code,
|
|
63
|
+
status: parsed.status,
|
|
64
|
+
limit: parsed.limit,
|
|
65
|
+
retry_after_seconds: parsed.retry_after_seconds,
|
|
66
|
+
clears_at: parsed.clears_at,
|
|
67
|
+
reset: resetOutcome,
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (
|
|
72
|
+
parsed.status === 402 ||
|
|
73
|
+
parsed.status === 403 ||
|
|
74
|
+
parsed.status === 429 ||
|
|
75
|
+
parsed.limit !== undefined
|
|
76
|
+
) {
|
|
77
|
+
void fetchQuota(deps, { force: true }).catch(() => undefined);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Warns once when the stored free-pi credential is rejected. */
|
|
2
|
+
|
|
3
|
+
import type { Deps } from "../deps.js";
|
|
4
|
+
|
|
5
|
+
export async function logInvalidToken(
|
|
6
|
+
deps: Deps,
|
|
7
|
+
token?: string,
|
|
8
|
+
): Promise<void> {
|
|
9
|
+
const key = token ?? "(none)";
|
|
10
|
+
if (deps.state.lastInvalidToken === key) return;
|
|
11
|
+
deps.state.lastInvalidToken = key;
|
|
12
|
+
deps.log.warn(
|
|
13
|
+
"free-pi sign-in is invalid or expired. Run `opencode auth login -p free-pi` to sign in again.",
|
|
14
|
+
);
|
|
15
|
+
}
|