@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,60 @@
|
|
|
1
|
+
/** The free-pi credential file written by the free-pi CLI. */
|
|
2
|
+
|
|
3
|
+
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { dirname, join, resolve } from "node:path";
|
|
6
|
+
import type { Credentials } from "../types.js";
|
|
7
|
+
import { normalizeIssuer, resolveBaseUrl } from "../utils/urls.js";
|
|
8
|
+
|
|
9
|
+
export function credentialsPath(): string {
|
|
10
|
+
const override = process.env.FREEPI_CREDENTIALS_PATH?.trim();
|
|
11
|
+
if (override) return resolve(override);
|
|
12
|
+
return join(homedir(), ".free-pi", "agent", "credentials.json");
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function credentialsDisplayPath(): string {
|
|
16
|
+
const override = process.env.FREEPI_CREDENTIALS_PATH?.trim();
|
|
17
|
+
if (override) return override;
|
|
18
|
+
return process.platform === "win32"
|
|
19
|
+
? join("%USERPROFILE%", ".free-pi", "agent", "credentials.json")
|
|
20
|
+
: "~/.free-pi/agent/credentials.json";
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function readCredentials(): Promise<Credentials | undefined> {
|
|
24
|
+
const envToken = process.env.FREEPI_JWT?.trim();
|
|
25
|
+
if (envToken) return { token: envToken, issuer: resolveBaseUrl() };
|
|
26
|
+
try {
|
|
27
|
+
const raw = await readFile(credentialsPath(), "utf8");
|
|
28
|
+
const parsed = JSON.parse(raw) as { token?: unknown; issuer?: unknown };
|
|
29
|
+
if (typeof parsed.token !== "string" || parsed.token.length === 0)
|
|
30
|
+
return undefined;
|
|
31
|
+
const issuer = normalizeIssuer(parsed.issuer);
|
|
32
|
+
return issuer ? { token: parsed.token, issuer } : { token: parsed.token };
|
|
33
|
+
} catch {
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function readCredentialsToken(): Promise<string | undefined> {
|
|
39
|
+
return (await readCredentials())?.token;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function writeCredentials(
|
|
43
|
+
token: string,
|
|
44
|
+
issuer?: string,
|
|
45
|
+
): Promise<void> {
|
|
46
|
+
const path = credentialsPath();
|
|
47
|
+
const temporary = `${path}.${process.pid}.${Date.now()}.tmp`;
|
|
48
|
+
const record = issuer
|
|
49
|
+
? { token, issuer: normalizeIssuer(issuer) ?? issuer }
|
|
50
|
+
: { token };
|
|
51
|
+
await mkdir(dirname(path), { recursive: true });
|
|
52
|
+
await writeFile(temporary, JSON.stringify(record), { mode: 0o600 });
|
|
53
|
+
try {
|
|
54
|
+
await rename(temporary, path);
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (process.platform !== "win32") throw error;
|
|
57
|
+
await rm(path, { force: true });
|
|
58
|
+
await rename(temporary, path);
|
|
59
|
+
}
|
|
60
|
+
}
|
package/src/auth/jwt.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/** JWT and refresh-token encoding helpers. */
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
AUTH_SKEW_MS,
|
|
5
|
+
REFRESH_PREFIX,
|
|
6
|
+
} from "../constants.js";
|
|
7
|
+
import type { Credentials, JwtClaims } from "../types.js";
|
|
8
|
+
import { normalizeIssuer } from "../utils/urls.js";
|
|
9
|
+
|
|
10
|
+
export function parseJwtClaims(token: string): JwtClaims | undefined {
|
|
11
|
+
const payload = token.split(".")[1];
|
|
12
|
+
if (!payload) return undefined;
|
|
13
|
+
try {
|
|
14
|
+
const parsed = JSON.parse(
|
|
15
|
+
Buffer.from(payload, "base64url").toString("utf8"),
|
|
16
|
+
);
|
|
17
|
+
return parsed && typeof parsed === "object"
|
|
18
|
+
? (parsed as JwtClaims)
|
|
19
|
+
: undefined;
|
|
20
|
+
} catch {
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function tokenExpiry(token: string): number | undefined {
|
|
26
|
+
const exp = parseJwtClaims(token)?.exp;
|
|
27
|
+
return typeof exp === "number" && Number.isFinite(exp) && exp > 0
|
|
28
|
+
? exp * 1000
|
|
29
|
+
: undefined;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function tokenNeedsRefresh(token: string, expires?: number): boolean {
|
|
33
|
+
const now = Date.now();
|
|
34
|
+
const jwtExpiry = tokenExpiry(token);
|
|
35
|
+
return (
|
|
36
|
+
(jwtExpiry !== undefined && jwtExpiry - now <= AUTH_SKEW_MS) ||
|
|
37
|
+
(typeof expires === "number" &&
|
|
38
|
+
expires > 0 &&
|
|
39
|
+
expires - now <= AUTH_SKEW_MS)
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function encodeRefreshToken(token: string, issuer?: string): string {
|
|
44
|
+
const payload = JSON.stringify(issuer ? { token, issuer } : { token });
|
|
45
|
+
return `${REFRESH_PREFIX}${Buffer.from(payload).toString("base64url")}`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function decodeRefreshToken(
|
|
49
|
+
value: string | undefined,
|
|
50
|
+
): Credentials | undefined {
|
|
51
|
+
if (!value) return undefined;
|
|
52
|
+
if (value.startsWith(REFRESH_PREFIX)) {
|
|
53
|
+
try {
|
|
54
|
+
const parsed = JSON.parse(
|
|
55
|
+
Buffer.from(value.slice(REFRESH_PREFIX.length), "base64url").toString(
|
|
56
|
+
"utf8",
|
|
57
|
+
),
|
|
58
|
+
) as { token?: unknown; issuer?: unknown };
|
|
59
|
+
if (typeof parsed.token === "string" && parsed.token.length > 0) {
|
|
60
|
+
const issuer = normalizeIssuer(parsed.issuer);
|
|
61
|
+
return issuer
|
|
62
|
+
? { token: parsed.token, issuer }
|
|
63
|
+
: { token: parsed.token };
|
|
64
|
+
}
|
|
65
|
+
} catch {}
|
|
66
|
+
}
|
|
67
|
+
try {
|
|
68
|
+
const parsed = JSON.parse(value) as { token?: unknown; issuer?: unknown };
|
|
69
|
+
if (typeof parsed.token === "string" && parsed.token.length > 0) {
|
|
70
|
+
const issuer = normalizeIssuer(parsed.issuer);
|
|
71
|
+
return issuer ? { token: parsed.token, issuer } : { token: parsed.token };
|
|
72
|
+
}
|
|
73
|
+
} catch {}
|
|
74
|
+
return { token: value };
|
|
75
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/** Resolves the token used for free-pi HTTP requests. */
|
|
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 { readCredentials } from "./credentials.js";
|
|
7
|
+
import {
|
|
8
|
+
expiryFromCredential,
|
|
9
|
+
tokenFromCredential,
|
|
10
|
+
} from "./credential.js";
|
|
11
|
+
import { tokenNeedsRefresh } from "./jwt.js";
|
|
12
|
+
|
|
13
|
+
export type TokenSource = {
|
|
14
|
+
readonly state: RuntimeState;
|
|
15
|
+
readonly log: Logger;
|
|
16
|
+
activeCredential: () => Promise<Credential.Value | undefined>;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Prefers the active OpenCode credential. The free-pi CLI credential file is a
|
|
21
|
+
* fallback for users who have not connected the integration yet.
|
|
22
|
+
*/
|
|
23
|
+
export async function resolveToken(
|
|
24
|
+
source: TokenSource,
|
|
25
|
+
): Promise<string | undefined> {
|
|
26
|
+
const credential = await source.activeCredential();
|
|
27
|
+
const current = tokenFromCredential(credential);
|
|
28
|
+
const stored = await readCredentials();
|
|
29
|
+
|
|
30
|
+
if (current && !tokenNeedsRefresh(current, expiryFromCredential(credential)))
|
|
31
|
+
return current;
|
|
32
|
+
|
|
33
|
+
if (
|
|
34
|
+
stored?.token &&
|
|
35
|
+
stored.token !== current &&
|
|
36
|
+
!tokenNeedsRefresh(stored.token)
|
|
37
|
+
) {
|
|
38
|
+
return stored.token;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (current) {
|
|
42
|
+
if (source.state.lastExpiredToken !== current) {
|
|
43
|
+
source.state.lastExpiredToken = current;
|
|
44
|
+
source.log.warn(
|
|
45
|
+
"free-pi token is expired. free-pi does not expose a refresh endpoint; sign in again from the free-pi integration.",
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
return current;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return stored?.token;
|
|
52
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** Fetches the live free-pi model catalog. */
|
|
2
|
+
|
|
3
|
+
import { CATALOG_TTL_MS } from "../constants.js";
|
|
4
|
+
import type { Deps } from "../deps.js";
|
|
5
|
+
import type { Catalog } from "../types.js";
|
|
6
|
+
import { resolveBaseUrl } from "../utils/urls.js";
|
|
7
|
+
|
|
8
|
+
export async function fetchCatalog(deps: Deps): Promise<Catalog | undefined> {
|
|
9
|
+
const state = deps.state;
|
|
10
|
+
if (state.cachedCatalog && Date.now() - state.cachedCatalogAt < CATALOG_TTL_MS) {
|
|
11
|
+
return state.cachedCatalog;
|
|
12
|
+
}
|
|
13
|
+
if (state.catalogPromise) return state.catalogPromise;
|
|
14
|
+
const pending = (async () => {
|
|
15
|
+
try {
|
|
16
|
+
const response = await fetch(`${resolveBaseUrl()}/client-version`, {
|
|
17
|
+
signal: AbortSignal.timeout(8000),
|
|
18
|
+
});
|
|
19
|
+
if (!response.ok) return state.cachedCatalog;
|
|
20
|
+
const catalog = (await response.json()) as Catalog;
|
|
21
|
+
if (typeof catalog.latest === "string" && catalog.latest.length > 0) {
|
|
22
|
+
state.latestClientVersion = catalog.latest;
|
|
23
|
+
}
|
|
24
|
+
const arm = catalog.cost_experiment?.arm;
|
|
25
|
+
state.costExperimentArm =
|
|
26
|
+
typeof arm === "string" && /^[A-Za-z0-9_-]{1,40}$/.test(arm)
|
|
27
|
+
? arm
|
|
28
|
+
: undefined;
|
|
29
|
+
state.cachedCatalog = catalog;
|
|
30
|
+
state.cachedCatalogAt = Date.now();
|
|
31
|
+
return catalog;
|
|
32
|
+
} catch {
|
|
33
|
+
return state.cachedCatalog;
|
|
34
|
+
}
|
|
35
|
+
})();
|
|
36
|
+
state.catalogPromise = pending;
|
|
37
|
+
try {
|
|
38
|
+
return await pending;
|
|
39
|
+
} finally {
|
|
40
|
+
if (state.catalogPromise === pending) state.catalogPromise = undefined;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -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,51 @@
|
|
|
1
|
+
/** Fetches the models.dev capability registry. */
|
|
2
|
+
|
|
3
|
+
import { REGISTRY_TTL_MS } from "../constants.js";
|
|
4
|
+
import type { Deps } from "../deps.js";
|
|
5
|
+
import type { ModelRegistry } from "../types.js";
|
|
6
|
+
import { modelsRegistryUrl } from "../utils/urls.js";
|
|
7
|
+
|
|
8
|
+
export async function fetchModelsRegistry(
|
|
9
|
+
deps: Deps,
|
|
10
|
+
): Promise<ModelRegistry | undefined> {
|
|
11
|
+
const state = deps.state;
|
|
12
|
+
if (state.cachedRegistry && Date.now() - state.cachedRegistryAt < REGISTRY_TTL_MS) {
|
|
13
|
+
return state.cachedRegistry;
|
|
14
|
+
}
|
|
15
|
+
if (
|
|
16
|
+
!state.cachedRegistry &&
|
|
17
|
+
state.registryAttemptAt &&
|
|
18
|
+
Date.now() - state.registryAttemptAt < REGISTRY_TTL_MS
|
|
19
|
+
) {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
if (state.registryPromise) return state.registryPromise;
|
|
23
|
+
const pending = (async () => {
|
|
24
|
+
state.registryAttemptAt = Date.now();
|
|
25
|
+
try {
|
|
26
|
+
const base = modelsRegistryUrl();
|
|
27
|
+
const url = base.endsWith(".json") ? base : `${base}/api.json`;
|
|
28
|
+
const response = await fetch(url, { signal: AbortSignal.timeout(8000) });
|
|
29
|
+
if (!response.ok) return state.cachedRegistry;
|
|
30
|
+
const registry = (await response.json()) as ModelRegistry;
|
|
31
|
+
if (
|
|
32
|
+
!registry ||
|
|
33
|
+
typeof registry !== "object" ||
|
|
34
|
+
Array.isArray(registry)
|
|
35
|
+
) {
|
|
36
|
+
return state.cachedRegistry;
|
|
37
|
+
}
|
|
38
|
+
state.cachedRegistry = registry;
|
|
39
|
+
state.cachedRegistryAt = Date.now();
|
|
40
|
+
return registry;
|
|
41
|
+
} catch {
|
|
42
|
+
return state.cachedRegistry;
|
|
43
|
+
}
|
|
44
|
+
})();
|
|
45
|
+
state.registryPromise = pending;
|
|
46
|
+
try {
|
|
47
|
+
return await pending;
|
|
48
|
+
} finally {
|
|
49
|
+
if (state.registryPromise === pending) state.registryPromise = undefined;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -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
|
+
}
|