@eduardo191labs/opencode-free-pi 0.2.7 → 0.3.0
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 +118 -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 +4 -0
- package/dist/catalog/catalog.js +43 -0
- package/dist/catalog/models.d.ts +15 -0
- package/dist/catalog/models.js +206 -0
- package/dist/catalog/registry.d.ts +4 -0
- package/dist/catalog/registry.js +46 -0
- package/dist/catalog/v2.d.ts +18 -0
- package/dist/catalog/v2.js +93 -0
- package/dist/constants.d.ts +40 -0
- package/dist/constants.js +40 -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 +19 -0
- package/dist/plugin.d.ts +4 -0
- package/dist/plugin.js +106 -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/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 +4 -3
- 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 +42 -0
- package/src/catalog/models.ts +291 -0
- package/src/catalog/registry.ts +51 -0
- package/src/catalog/v2.ts +124 -0
- package/src/constants.ts +55 -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 +26 -0
- package/src/plugin.ts +140 -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/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,15 @@
|
|
|
1
|
+
/** Turns the free-pi catalog and models.dev registry into model definitions. */
|
|
2
|
+
import type { Catalog, CatalogModel, ModelDefinition, ModelRegistry, ModelsDevModel, ReasoningOption, RegistryCandidate } from "../types.js";
|
|
3
|
+
export type VariantMap = Record<string, Record<string, unknown>>;
|
|
4
|
+
export type ModelMap = Record<string, ModelDefinition>;
|
|
5
|
+
export declare function usableModels(catalog: Catalog | undefined): CatalogModel[];
|
|
6
|
+
export declare function partitionModels(catalog: Catalog | undefined): {
|
|
7
|
+
main: CatalogModel[];
|
|
8
|
+
defense: CatalogModel[];
|
|
9
|
+
};
|
|
10
|
+
export declare function displayName(model: CatalogModel): string;
|
|
11
|
+
export declare function modelCost(model: CatalogModel, capability?: ModelsDevModel): ModelDefinition["cost"];
|
|
12
|
+
export declare function modelRegistryCandidates(registry: ModelRegistry | undefined): RegistryCandidate[];
|
|
13
|
+
export declare function modelCapability(model: CatalogModel, candidates: RegistryCandidate[]): ModelsDevModel | undefined;
|
|
14
|
+
export declare function modelVariants(options: ReasoningOption[] | undefined, outputLimit: number): VariantMap;
|
|
15
|
+
export declare function buildModels(models: CatalogModel[], candidates?: RegistryCandidate[]): ModelMap;
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/** Turns the free-pi catalog and models.dev registry into model definitions. */
|
|
2
|
+
import { CONTEXT_WINDOW, MAX_OUTPUT_TOKENS, } from "../constants.js";
|
|
3
|
+
import { creditsToUsd, positiveNumber } from "../utils/numbers.js";
|
|
4
|
+
import { cleanText } from "../utils/text.js";
|
|
5
|
+
export function usableModels(catalog) {
|
|
6
|
+
return (catalog?.models ?? []).filter((model) => typeof model.id === "string" && model.id.length > 0);
|
|
7
|
+
}
|
|
8
|
+
export function partitionModels(catalog) {
|
|
9
|
+
const models = usableModels(catalog);
|
|
10
|
+
const main = models.filter((model) => model.section !== "defense");
|
|
11
|
+
const defense = models.filter((model) => model.section === "defense");
|
|
12
|
+
if (main.length > 0)
|
|
13
|
+
return { main, defense };
|
|
14
|
+
if (typeof catalog?.default_model === "string" &&
|
|
15
|
+
catalog.default_model.length > 0) {
|
|
16
|
+
return { main: [{ id: catalog.default_model }], defense };
|
|
17
|
+
}
|
|
18
|
+
return { main: [], defense };
|
|
19
|
+
}
|
|
20
|
+
export function displayName(model) {
|
|
21
|
+
const base = model.display_name || model.name || model.id || "model";
|
|
22
|
+
const tags = [];
|
|
23
|
+
const lower = base.toLowerCase();
|
|
24
|
+
if (model.free === true && !lower.includes("free"))
|
|
25
|
+
tags.push("free");
|
|
26
|
+
if (model.tier === "premium" &&
|
|
27
|
+
!lower.includes("premium") &&
|
|
28
|
+
!(model.note ?? "").toLowerCase().includes("premium")) {
|
|
29
|
+
tags.push("premium");
|
|
30
|
+
}
|
|
31
|
+
if (model.note && !lower.includes(model.note.toLowerCase()))
|
|
32
|
+
tags.push(model.note);
|
|
33
|
+
if (model.usage_x && !lower.includes(`${model.usage_x}x`)) {
|
|
34
|
+
tags.push(`~${model.usage_x}x usage`);
|
|
35
|
+
}
|
|
36
|
+
return tags.length > 0 ? `${base} (${tags.join(" · ")})` : base;
|
|
37
|
+
}
|
|
38
|
+
export function modelCost(model, capability) {
|
|
39
|
+
const zero = { input: 0, output: 0, cache_read: 0, cache_write: 0 };
|
|
40
|
+
if (model.free === true)
|
|
41
|
+
return zero;
|
|
42
|
+
const input = creditsToUsd(model.input_credits_per_mtok) ||
|
|
43
|
+
positiveNumber(capability?.cost?.input) ||
|
|
44
|
+
0;
|
|
45
|
+
const output = creditsToUsd(model.output_credits_per_mtok) ||
|
|
46
|
+
positiveNumber(capability?.cost?.output) ||
|
|
47
|
+
0;
|
|
48
|
+
if (input > 0 || output > 0) {
|
|
49
|
+
return {
|
|
50
|
+
input,
|
|
51
|
+
output,
|
|
52
|
+
cache_read: creditsToUsd(model.cache_read_credits_per_mtok) ||
|
|
53
|
+
positiveNumber(capability?.cost?.cache_read) ||
|
|
54
|
+
input,
|
|
55
|
+
cache_write: creditsToUsd(model.cache_write_credits_per_mtok) ||
|
|
56
|
+
positiveNumber(capability?.cost?.cache_write) ||
|
|
57
|
+
input,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
return zero;
|
|
61
|
+
}
|
|
62
|
+
export function modelRegistryCandidates(registry) {
|
|
63
|
+
const candidates = [];
|
|
64
|
+
for (const [providerID, provider] of Object.entries(registry ?? {})) {
|
|
65
|
+
for (const [modelID, model] of Object.entries(provider?.models ?? {})) {
|
|
66
|
+
if (model && typeof model === "object")
|
|
67
|
+
candidates.push({ providerID, modelID, model });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return candidates;
|
|
71
|
+
}
|
|
72
|
+
function normalizeModelKey(value) {
|
|
73
|
+
return value.toLowerCase().replace(/[^a-z0-9]+/g, "");
|
|
74
|
+
}
|
|
75
|
+
function capabilityScore(model, candidate) {
|
|
76
|
+
const id = model.id?.toLowerCase();
|
|
77
|
+
const stats = model.stats_id?.toLowerCase();
|
|
78
|
+
const candidateID = candidate.modelID.toLowerCase();
|
|
79
|
+
const candidateName = cleanText(candidate.model.name).toLowerCase();
|
|
80
|
+
const name = cleanText(model.display_name || model.name).toLowerCase();
|
|
81
|
+
let score = 0;
|
|
82
|
+
if (stats) {
|
|
83
|
+
const slash = stats.indexOf("/");
|
|
84
|
+
const providerHint = slash > 0 ? stats.slice(0, slash) : "";
|
|
85
|
+
const modelHint = slash > 0 ? stats.slice(slash + 1) : stats;
|
|
86
|
+
if (providerHint && candidate.providerID.toLowerCase() === providerHint)
|
|
87
|
+
score += 100;
|
|
88
|
+
if (candidateID === modelHint)
|
|
89
|
+
score += 80;
|
|
90
|
+
else if (candidateID === stats)
|
|
91
|
+
score += 60;
|
|
92
|
+
else if (candidateID.endsWith(`/${modelHint}`))
|
|
93
|
+
score += 50;
|
|
94
|
+
}
|
|
95
|
+
if (id) {
|
|
96
|
+
if (candidateID === id)
|
|
97
|
+
score += 50;
|
|
98
|
+
else if (candidateID.endsWith(`/${id}`))
|
|
99
|
+
score += 40;
|
|
100
|
+
else if (normalizeModelKey(candidateID) === normalizeModelKey(id))
|
|
101
|
+
score += 20;
|
|
102
|
+
}
|
|
103
|
+
if (name && candidateName === name)
|
|
104
|
+
score += 30;
|
|
105
|
+
else if (name && normalizeModelKey(candidateName) === normalizeModelKey(name))
|
|
106
|
+
score += 15;
|
|
107
|
+
if (model.release_date && candidate.model.release_date === model.release_date)
|
|
108
|
+
score += 10;
|
|
109
|
+
if (model.family && candidate.model.family === model.family)
|
|
110
|
+
score += 5;
|
|
111
|
+
return score;
|
|
112
|
+
}
|
|
113
|
+
export function modelCapability(model, candidates) {
|
|
114
|
+
let best;
|
|
115
|
+
let bestScore = 0;
|
|
116
|
+
let bestProvider = "";
|
|
117
|
+
let bestID = "";
|
|
118
|
+
for (const candidate of candidates) {
|
|
119
|
+
const score = capabilityScore(model, candidate);
|
|
120
|
+
if (score < 30)
|
|
121
|
+
continue;
|
|
122
|
+
const provider = candidate.providerID.toLowerCase();
|
|
123
|
+
const id = candidate.modelID.toLowerCase();
|
|
124
|
+
if (score > bestScore ||
|
|
125
|
+
(score === bestScore &&
|
|
126
|
+
(provider < bestProvider || (provider === bestProvider && id < bestID)))) {
|
|
127
|
+
best = candidate.model;
|
|
128
|
+
bestScore = score;
|
|
129
|
+
bestProvider = provider;
|
|
130
|
+
bestID = id;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return best;
|
|
134
|
+
}
|
|
135
|
+
function budgetVariants(option, outputLimit, variants) {
|
|
136
|
+
const ceiling = Math.max(1, Math.min(positiveNumber(option.max) ?? outputLimit - 1024, outputLimit - 1024, MAX_OUTPUT_TOKENS - 1024));
|
|
137
|
+
const floor = Math.min(positiveNumber(option.min) ?? 0, ceiling);
|
|
138
|
+
const high = Math.min(Math.max(floor, Math.floor((ceiling + 1) / 2)), ceiling);
|
|
139
|
+
for (const [level, budget] of [
|
|
140
|
+
["high", high],
|
|
141
|
+
["max", ceiling],
|
|
142
|
+
]) {
|
|
143
|
+
variants[level] = {
|
|
144
|
+
reasoningEffort: level,
|
|
145
|
+
thinking_budget: budget,
|
|
146
|
+
thinking: { type: "enabled", budget_tokens: budget },
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
export function modelVariants(options, outputLimit) {
|
|
151
|
+
const variants = {};
|
|
152
|
+
if (!options || options.length === 0)
|
|
153
|
+
return variants;
|
|
154
|
+
const effort = options.find((option) => option.type === "effort");
|
|
155
|
+
if (effort) {
|
|
156
|
+
for (const value of effort.values) {
|
|
157
|
+
variants[value] = { reasoningEffort: value };
|
|
158
|
+
}
|
|
159
|
+
return variants;
|
|
160
|
+
}
|
|
161
|
+
if (options.some((option) => option.type === "toggle")) {
|
|
162
|
+
variants.none = { reasoningEffort: "none" };
|
|
163
|
+
variants.high = { reasoningEffort: "high" };
|
|
164
|
+
}
|
|
165
|
+
const budget = options.find((option) => option.type === "budget_tokens");
|
|
166
|
+
if (budget)
|
|
167
|
+
budgetVariants(budget, outputLimit, variants);
|
|
168
|
+
return variants;
|
|
169
|
+
}
|
|
170
|
+
export function buildModels(models, candidates = []) {
|
|
171
|
+
const result = {};
|
|
172
|
+
for (const model of models) {
|
|
173
|
+
if (!model.id)
|
|
174
|
+
continue;
|
|
175
|
+
const capability = modelCapability(model, candidates);
|
|
176
|
+
const reasoning = model.reasoning ?? capability?.reasoning ?? true;
|
|
177
|
+
const reasoningOptions = model.reasoning_options ?? capability?.reasoning_options;
|
|
178
|
+
const limitContext = positiveNumber(model.context_window, model.contextWindow, model.limit?.context, capability?.limit?.context) ?? CONTEXT_WINDOW;
|
|
179
|
+
const limitOutput = positiveNumber(model.max_tokens, model.maxTokens, model.max_output_tokens, model.limit?.output, capability?.limit?.output) ?? MAX_OUTPUT_TOKENS;
|
|
180
|
+
result[model.id] = {
|
|
181
|
+
id: model.id,
|
|
182
|
+
name: displayName(model),
|
|
183
|
+
family: model.family ??
|
|
184
|
+
capability?.family ??
|
|
185
|
+
(model.section === "defense" ? "defense" : ""),
|
|
186
|
+
release_date: model.release_date ?? capability?.release_date,
|
|
187
|
+
reasoning,
|
|
188
|
+
reasoning_options: reasoningOptions,
|
|
189
|
+
variants: reasoning ? modelVariants(reasoningOptions, limitOutput) : {},
|
|
190
|
+
temperature: model.temperature ?? capability?.temperature ?? true,
|
|
191
|
+
tool_call: model.tool_call ?? capability?.tool_call ?? true,
|
|
192
|
+
attachment: model.attachment ?? capability?.attachment ?? false,
|
|
193
|
+
interleaved: model.interleaved ?? capability?.interleaved,
|
|
194
|
+
cost: modelCost(model, capability),
|
|
195
|
+
limit: { context: limitContext, output: limitOutput },
|
|
196
|
+
modalities: {
|
|
197
|
+
input: model.modalities?.input ??
|
|
198
|
+
capability?.modalities?.input ?? ["text"],
|
|
199
|
+
output: model.modalities?.output ??
|
|
200
|
+
capability?.modalities?.output ?? ["text"],
|
|
201
|
+
},
|
|
202
|
+
status: model.unavailable ? "deprecated" : "active",
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
return result;
|
|
206
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** Fetches the models.dev capability registry. */
|
|
2
|
+
import { REGISTRY_TTL_MS } from "../constants.js";
|
|
3
|
+
import { modelsRegistryUrl } from "../utils/urls.js";
|
|
4
|
+
export async function fetchModelsRegistry(deps) {
|
|
5
|
+
const state = deps.state;
|
|
6
|
+
if (state.cachedRegistry && Date.now() - state.cachedRegistryAt < REGISTRY_TTL_MS) {
|
|
7
|
+
return state.cachedRegistry;
|
|
8
|
+
}
|
|
9
|
+
if (!state.cachedRegistry &&
|
|
10
|
+
state.registryAttemptAt &&
|
|
11
|
+
Date.now() - state.registryAttemptAt < REGISTRY_TTL_MS) {
|
|
12
|
+
return undefined;
|
|
13
|
+
}
|
|
14
|
+
if (state.registryPromise)
|
|
15
|
+
return state.registryPromise;
|
|
16
|
+
const pending = (async () => {
|
|
17
|
+
state.registryAttemptAt = Date.now();
|
|
18
|
+
try {
|
|
19
|
+
const base = modelsRegistryUrl();
|
|
20
|
+
const url = base.endsWith(".json") ? base : `${base}/api.json`;
|
|
21
|
+
const response = await fetch(url, { signal: AbortSignal.timeout(8000) });
|
|
22
|
+
if (!response.ok)
|
|
23
|
+
return state.cachedRegistry;
|
|
24
|
+
const registry = (await response.json());
|
|
25
|
+
if (!registry ||
|
|
26
|
+
typeof registry !== "object" ||
|
|
27
|
+
Array.isArray(registry)) {
|
|
28
|
+
return state.cachedRegistry;
|
|
29
|
+
}
|
|
30
|
+
state.cachedRegistry = registry;
|
|
31
|
+
state.cachedRegistryAt = Date.now();
|
|
32
|
+
return registry;
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return state.cachedRegistry;
|
|
36
|
+
}
|
|
37
|
+
})();
|
|
38
|
+
state.registryPromise = pending;
|
|
39
|
+
try {
|
|
40
|
+
return await pending;
|
|
41
|
+
}
|
|
42
|
+
finally {
|
|
43
|
+
if (state.registryPromise === pending)
|
|
44
|
+
state.registryPromise = undefined;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Converts internal model definitions into OpenCode V2 provider records. */
|
|
2
|
+
import type { ModelMap } from "./models.js";
|
|
3
|
+
type ProviderEditorLike = {
|
|
4
|
+
get(providerID: string): any;
|
|
5
|
+
add(input: {
|
|
6
|
+
info: any;
|
|
7
|
+
models: readonly any[];
|
|
8
|
+
sourceConnection?: any;
|
|
9
|
+
}): void;
|
|
10
|
+
};
|
|
11
|
+
export declare function toV2Models(providerID: string, models: ModelMap): any[];
|
|
12
|
+
export declare function baseProviderInfo(providerID: string, name: string, token: string | undefined): any;
|
|
13
|
+
/**
|
|
14
|
+
* Adds a provider, merging an existing record so user or config overrides win.
|
|
15
|
+
* `editor.add` replaces the whole record, so the merge happens here.
|
|
16
|
+
*/
|
|
17
|
+
export declare function applyProvider(editor: ProviderEditorLike, providerID: string, name: string, models: ModelMap, token: string | undefined): void;
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/** Converts internal model definitions into OpenCode V2 provider records. */
|
|
2
|
+
import { CONTEXT_WINDOW, MAX_OUTPUT_TOKENS, OPENAI_COMPATIBLE_PACKAGE, PROVIDER_ID, } from "../constants.js";
|
|
3
|
+
import { completionsBaseUrl } from "../utils/urls.js";
|
|
4
|
+
export function toV2Models(providerID, models) {
|
|
5
|
+
return Object.values(models).map((model) => {
|
|
6
|
+
const cost = model.cost ?? {};
|
|
7
|
+
const released = Date.parse(model.release_date ?? "");
|
|
8
|
+
return {
|
|
9
|
+
id: model.id,
|
|
10
|
+
modelID: model.id,
|
|
11
|
+
providerID,
|
|
12
|
+
name: model.name ?? model.id,
|
|
13
|
+
...(model.family ? { family: model.family } : {}),
|
|
14
|
+
capabilities: {
|
|
15
|
+
tools: model.tool_call !== false,
|
|
16
|
+
input: model.modalities?.input ?? ["text"],
|
|
17
|
+
output: model.modalities?.output ?? ["text"],
|
|
18
|
+
...(model.temperature === undefined
|
|
19
|
+
? {}
|
|
20
|
+
: { temperature: model.temperature }),
|
|
21
|
+
},
|
|
22
|
+
variants: Object.entries(model.variants ?? {}).map(([id, settings]) => ({
|
|
23
|
+
id,
|
|
24
|
+
settings,
|
|
25
|
+
})),
|
|
26
|
+
time: { released: Number.isFinite(released) ? released : 0 },
|
|
27
|
+
cost: [
|
|
28
|
+
{
|
|
29
|
+
input: cost.input ?? 0,
|
|
30
|
+
output: cost.output ?? 0,
|
|
31
|
+
cache: {
|
|
32
|
+
read: cost.cache_read ?? cost.input ?? 0,
|
|
33
|
+
write: cost.cache_write ?? cost.input ?? 0,
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
],
|
|
37
|
+
status: model.status === "deprecated" ? "deprecated" : "active",
|
|
38
|
+
enabled: true,
|
|
39
|
+
limit: {
|
|
40
|
+
context: model.limit?.context ?? CONTEXT_WINDOW,
|
|
41
|
+
output: model.limit?.output ?? MAX_OUTPUT_TOKENS,
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
export function baseProviderInfo(providerID, name, token) {
|
|
47
|
+
return {
|
|
48
|
+
id: providerID,
|
|
49
|
+
name,
|
|
50
|
+
activation: "enabled",
|
|
51
|
+
integrationID: PROVIDER_ID,
|
|
52
|
+
package: OPENAI_COMPATIBLE_PACKAGE,
|
|
53
|
+
settings: {
|
|
54
|
+
baseURL: completionsBaseUrl(),
|
|
55
|
+
apiKey: token ?? "free-pi",
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Adds a provider, merging an existing record so user or config overrides win.
|
|
61
|
+
* `editor.add` replaces the whole record, so the merge happens here.
|
|
62
|
+
*/
|
|
63
|
+
export function applyProvider(editor, providerID, name, models, token) {
|
|
64
|
+
const generated = toV2Models(providerID, models);
|
|
65
|
+
const existing = editor.get(providerID);
|
|
66
|
+
if (!existing) {
|
|
67
|
+
editor.add({ info: baseProviderInfo(providerID, name, token), models: generated });
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
const base = baseProviderInfo(providerID, name, token);
|
|
71
|
+
const info = {
|
|
72
|
+
...base,
|
|
73
|
+
...existing.provider,
|
|
74
|
+
id: providerID,
|
|
75
|
+
settings: {
|
|
76
|
+
...base.settings,
|
|
77
|
+
...(existing.provider?.settings ?? {}),
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
const merged = new Map();
|
|
81
|
+
for (const model of generated)
|
|
82
|
+
merged.set(model.id, model);
|
|
83
|
+
for (const [id, model] of existing.models) {
|
|
84
|
+
merged.set(id, { ...(merged.get(id) ?? {}), ...model });
|
|
85
|
+
}
|
|
86
|
+
editor.add({
|
|
87
|
+
info,
|
|
88
|
+
models: [...merged.values()],
|
|
89
|
+
...(existing.sourceConnection
|
|
90
|
+
? { sourceConnection: existing.sourceConnection }
|
|
91
|
+
: {}),
|
|
92
|
+
});
|
|
93
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** Identifiers and defaults shared by every part of the plugin. */
|
|
2
|
+
export declare const PROVIDER_ID = "free-pi";
|
|
3
|
+
export declare const DEFENSE_PROVIDER_ID = "free-pi-defense";
|
|
4
|
+
export declare const INTEGRATION_ID = "free-pi";
|
|
5
|
+
export declare const PROVIDER_NAME = "Free Pi";
|
|
6
|
+
export declare const DEFENSE_PROVIDER_NAME = "Free Pi Defense";
|
|
7
|
+
export declare const DEFAULT_BASE_URL = "https://api.freepi.ai";
|
|
8
|
+
export declare const DEFAULT_CLIENT_VERSION = "0.6.25";
|
|
9
|
+
export declare const CONSENT_VERSION = "4";
|
|
10
|
+
export declare const CONTEXT_WINDOW = 200000;
|
|
11
|
+
export declare const MAX_OUTPUT_TOKENS = 32768;
|
|
12
|
+
export declare const AD_CONTEXT_HEADER = "x-ad-context";
|
|
13
|
+
export declare const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
|
|
14
|
+
export declare const EFFICIENCY_RULE = "- When several independent reads or searches are needed, issue them in the same turn.";
|
|
15
|
+
export declare const SESSION_TRACK_LIMIT = 200;
|
|
16
|
+
export declare const AUTH_SKEW_MS = 60000;
|
|
17
|
+
export declare const AUTH_TIMEOUT_MS: number;
|
|
18
|
+
export declare const AUTH_NETWORK_FAILURES = 6;
|
|
19
|
+
export declare const DEFAULT_TOKEN_LIFETIME_MS: number;
|
|
20
|
+
export declare const REFRESH_PREFIX = "free-pi:v1:";
|
|
21
|
+
export declare const AD_CONTEXT_MAX_CHARS = 1000;
|
|
22
|
+
export declare const AD_REQUEST_TIMEOUT_MS = 5000;
|
|
23
|
+
export declare const AD_IMPRESSION_TIMEOUT_MS = 3000;
|
|
24
|
+
export declare const AD_TURN_LIMIT = 200;
|
|
25
|
+
export declare const AD_IMPRESSION_LIMIT = 200;
|
|
26
|
+
export declare const CREDITS_PER_USD: number;
|
|
27
|
+
export declare const CATALOG_TTL_MS: number;
|
|
28
|
+
export declare const REGISTRY_TTL_MS: number;
|
|
29
|
+
export declare const DEFAULT_MODELS_REGISTRY_URL = "https://models.opencode.ai";
|
|
30
|
+
export declare const QUOTA_TTL_MS = 30000;
|
|
31
|
+
export declare const QUOTA_HTTP_TIMEOUT_MS = 5000;
|
|
32
|
+
export declare const QUOTA_REFRESH_DEBOUNCE_MS = 1000;
|
|
33
|
+
export declare const SESSION_RESET_COOLDOWN_MS = 15000;
|
|
34
|
+
/**
|
|
35
|
+
* How long a free-pi session must stay quiet before its server slot is closed.
|
|
36
|
+
* Background compaction can start right after the last step, so closing on the
|
|
37
|
+
* execution event alone would race with it.
|
|
38
|
+
*/
|
|
39
|
+
export declare const SESSION_FINALIZE_DELAY_MS = 2000;
|
|
40
|
+
export declare const OPENAI_COMPATIBLE_PACKAGE = "@opencode/ai/providers/openai-compatible";
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** Identifiers and defaults shared by every part of the plugin. */
|
|
2
|
+
export const PROVIDER_ID = "free-pi";
|
|
3
|
+
export const DEFENSE_PROVIDER_ID = "free-pi-defense";
|
|
4
|
+
export const INTEGRATION_ID = PROVIDER_ID;
|
|
5
|
+
export const PROVIDER_NAME = "Free Pi";
|
|
6
|
+
export const DEFENSE_PROVIDER_NAME = "Free Pi Defense";
|
|
7
|
+
export const DEFAULT_BASE_URL = "https://api.freepi.ai";
|
|
8
|
+
export const DEFAULT_CLIENT_VERSION = "0.6.25";
|
|
9
|
+
export const CONSENT_VERSION = "4";
|
|
10
|
+
export const CONTEXT_WINDOW = 200_000;
|
|
11
|
+
export const MAX_OUTPUT_TOKENS = 32_768;
|
|
12
|
+
export const AD_CONTEXT_HEADER = "x-ad-context";
|
|
13
|
+
export const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
|
|
14
|
+
export const EFFICIENCY_RULE = "- When several independent reads or searches are needed, issue them in the same turn.";
|
|
15
|
+
export const SESSION_TRACK_LIMIT = 200;
|
|
16
|
+
export const AUTH_SKEW_MS = 60_000;
|
|
17
|
+
export const AUTH_TIMEOUT_MS = 15 * 60_000;
|
|
18
|
+
export const AUTH_NETWORK_FAILURES = 6;
|
|
19
|
+
export const DEFAULT_TOKEN_LIFETIME_MS = 30 * 24 * 60 * 60_000;
|
|
20
|
+
export const REFRESH_PREFIX = "free-pi:v1:";
|
|
21
|
+
export const AD_CONTEXT_MAX_CHARS = 1_000;
|
|
22
|
+
export const AD_REQUEST_TIMEOUT_MS = 5_000;
|
|
23
|
+
export const AD_IMPRESSION_TIMEOUT_MS = 3_000;
|
|
24
|
+
export const AD_TURN_LIMIT = 200;
|
|
25
|
+
export const AD_IMPRESSION_LIMIT = 200;
|
|
26
|
+
export const CREDITS_PER_USD = 40_000 / 3;
|
|
27
|
+
export const CATALOG_TTL_MS = 10 * 60_000;
|
|
28
|
+
export const REGISTRY_TTL_MS = 5 * 60_000;
|
|
29
|
+
export const DEFAULT_MODELS_REGISTRY_URL = "https://models.opencode.ai";
|
|
30
|
+
export const QUOTA_TTL_MS = 30_000;
|
|
31
|
+
export const QUOTA_HTTP_TIMEOUT_MS = 5_000;
|
|
32
|
+
export const QUOTA_REFRESH_DEBOUNCE_MS = 1_000;
|
|
33
|
+
export const SESSION_RESET_COOLDOWN_MS = 15_000;
|
|
34
|
+
/**
|
|
35
|
+
* How long a free-pi session must stay quiet before its server slot is closed.
|
|
36
|
+
* Background compaction can start right after the last step, so closing on the
|
|
37
|
+
* execution event alone would race with it.
|
|
38
|
+
*/
|
|
39
|
+
export const SESSION_FINALIZE_DELAY_MS = 2_000;
|
|
40
|
+
export const OPENAI_COMPATIBLE_PACKAGE = "@opencode/ai/providers/openai-compatible";
|
package/dist/deps.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Dependencies shared by the free-pi modules. */
|
|
2
|
+
import type { Credential } from "@opencode/schema/credential";
|
|
3
|
+
import type { Logger } from "./logging.js";
|
|
4
|
+
import type { RuntimeState } from "./state.js";
|
|
5
|
+
import type { ReadContext } from "./types.js";
|
|
6
|
+
export type Deps = {
|
|
7
|
+
readonly state: RuntimeState;
|
|
8
|
+
readonly log: Logger;
|
|
9
|
+
readonly activeCredential: () => Promise<Credential.Value | undefined>;
|
|
10
|
+
readonly readContext: ReadContext;
|
|
11
|
+
};
|
package/dist/deps.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/** Central handling for free-pi failures reported by the provider or session. */
|
|
2
|
+
import { fetchQuota, rememberTokenCheck } from "../api/quota.js";
|
|
3
|
+
import { resetFreePiSessions } from "../api/session.js";
|
|
4
|
+
import { logInvalidToken } from "./invalid.js";
|
|
5
|
+
import { freePiErrorSeverity, freePiErrorTitle, friendlyFreePiError, } from "./messages.js";
|
|
6
|
+
import { parseFreePiError } from "./parse.js";
|
|
7
|
+
export async function handleFreePiError(deps, error, opts = {}) {
|
|
8
|
+
const parsed = parseFreePiError(error, opts.allowRaw === true);
|
|
9
|
+
if (!parsed)
|
|
10
|
+
return;
|
|
11
|
+
deps.state.lastFreePiError = parsed;
|
|
12
|
+
if (parsed.status === 401 ||
|
|
13
|
+
parsed.code === "unauthorized" ||
|
|
14
|
+
parsed.code === "expired_token") {
|
|
15
|
+
const token = deps.state.quotaCache?.token;
|
|
16
|
+
if (token)
|
|
17
|
+
rememberTokenCheck(deps, token, "invalid");
|
|
18
|
+
await logInvalidToken(deps, token);
|
|
19
|
+
void fetchQuota(deps, { force: true }).catch(() => undefined);
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
let message = friendlyFreePiError(parsed);
|
|
23
|
+
let resetOutcome;
|
|
24
|
+
if (parsed.code === "concurrent_session") {
|
|
25
|
+
resetOutcome = await resetFreePiSessions(deps);
|
|
26
|
+
if (resetOutcome === "released") {
|
|
27
|
+
message =
|
|
28
|
+
"free-pi was at its session limit; freed a stale slot automatically. Retry your request now.";
|
|
29
|
+
}
|
|
30
|
+
else if (resetOutcome === "none") {
|
|
31
|
+
message =
|
|
32
|
+
"free-pi is at its session limit and no other session was running. Wait for a slot to free up and retry.";
|
|
33
|
+
}
|
|
34
|
+
else if (resetOutcome === "failed" || resetOutcome === "unavailable") {
|
|
35
|
+
message =
|
|
36
|
+
"free-pi is at its session limit and the slot could not be freed automatically. Wait a moment and retry.";
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
message =
|
|
40
|
+
"free-pi session reset was just attempted; retry in a moment.";
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const key = `${parsed.code}\u0000${parsed.message ?? ""}`;
|
|
44
|
+
const now = Date.now();
|
|
45
|
+
if (key !== deps.state.lastErrorLogKey || now - deps.state.lastErrorLogAt > 15_000) {
|
|
46
|
+
deps.state.lastErrorLogKey = key;
|
|
47
|
+
deps.state.lastErrorLogAt = now;
|
|
48
|
+
const level = freePiErrorSeverity(parsed);
|
|
49
|
+
deps.log.log(level, `${freePiErrorTitle(parsed)}: ${message}`, {
|
|
50
|
+
code: parsed.code,
|
|
51
|
+
status: parsed.status,
|
|
52
|
+
limit: parsed.limit,
|
|
53
|
+
retry_after_seconds: parsed.retry_after_seconds,
|
|
54
|
+
clears_at: parsed.clears_at,
|
|
55
|
+
reset: resetOutcome,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
if (parsed.status === 402 ||
|
|
59
|
+
parsed.status === 403 ||
|
|
60
|
+
parsed.status === 429 ||
|
|
61
|
+
parsed.limit !== undefined) {
|
|
62
|
+
void fetchQuota(deps, { force: true }).catch(() => undefined);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Warns once when the stored free-pi credential is rejected. */
|
|
2
|
+
export async function logInvalidToken(deps, token) {
|
|
3
|
+
const key = token ?? "(none)";
|
|
4
|
+
if (deps.state.lastInvalidToken === key)
|
|
5
|
+
return;
|
|
6
|
+
deps.state.lastInvalidToken = key;
|
|
7
|
+
deps.log.warn("free-pi sign-in is invalid or expired. Run `opencode auth login -p free-pi` to sign in again.");
|
|
8
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rewrites long-lived free-pi limit responses so the client shows the friendly
|
|
3
|
+
* message instead of a raw 429. Mirrors the fetch wrapper used by the V1 plugin.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* Returns a replacement response when `response` is a 429 that represents a
|
|
7
|
+
* long-lived limit. The replacement is a 400 with the same body but a friendly
|
|
8
|
+
* message, so the model error surface reads it like any other failure.
|
|
9
|
+
*/
|
|
10
|
+
export declare function rewriteLimitResponse(response: Response): Promise<Response | undefined>;
|