@eduardo191labs/opencode-free-pi 0.3.0 → 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 +34 -1
- package/dist/catalog/catalog.d.ts +2 -0
- package/dist/catalog/catalog.js +58 -21
- package/dist/catalog/registry.d.ts +5 -0
- package/dist/catalog/registry.js +75 -25
- package/dist/constants.d.ts +6 -0
- package/dist/constants.js +6 -0
- package/dist/logging.d.ts +1 -1
- package/dist/logging.js +49 -6
- package/dist/plugin.js +4 -1
- package/dist/utils/cache.d.ts +7 -0
- package/dist/utils/cache.js +45 -0
- package/package.json +2 -2
- package/src/catalog/catalog.ts +72 -20
- package/src/catalog/registry.ts +99 -28
- package/src/constants.ts +6 -0
- package/src/logging.ts +50 -6
- package/src/plugin.ts +4 -1
- package/src/utils/cache.ts +49 -0
package/README.md
CHANGED
|
@@ -73,6 +73,9 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
73
73
|
plugin finaliza la sesión del proveedor cuando la ejecución del modelo
|
|
74
74
|
termina (éxito, fallo o interrupción) y al apagar OpenCode.
|
|
75
75
|
- Recuperación automática del límite de sesiones concurrentes.
|
|
76
|
+
- **Catálogo y metadatos resistentes**: el catálogo de free-pi y el registro de
|
|
77
|
+
models.dev se guardan en disco; si la red falla al arrancar se usan las copias
|
|
78
|
+
locales en vez de quedarse sin modelos o sin límites de contexto.
|
|
76
79
|
- Compatible con rutas, credenciales y navegador de cada sistema operativo.
|
|
77
80
|
|
|
78
81
|
No incluye herramientas personalizadas. Usa las herramientas integradas de
|
|
@@ -116,9 +119,38 @@ Si `XDG_CONFIG_HOME` o `OPENCODE_CONFIG_DIR` están definidos, se respetan.
|
|
|
116
119
|
| `FREEPI_DEVICE_LOGIN=1` | Forzar inicio de sesión por dispositivo. |
|
|
117
120
|
| `FREEPI_CONFIGURE=1` | Registrar el paquete en `opencode.json` al instalar. |
|
|
118
121
|
| `OPENCODE_CONFIG_DIR` | Directorio de configuración de OpenCode. |
|
|
122
|
+
| `FREE_PI_CACHE_DIR` | Directorio de caché del plugin. |
|
|
123
|
+
| `FREE_PI_LOG_FILE` | Ruta alternativa del archivo de log del plugin. |
|
|
119
124
|
|
|
120
125
|
No hay variables obligatorias.
|
|
121
126
|
|
|
127
|
+
## Caché y logs
|
|
128
|
+
|
|
129
|
+
El plugin guarda el catálogo de free-pi y el registro de models.dev en:
|
|
130
|
+
|
|
131
|
+
```text
|
|
132
|
+
~/.cache/opencode/free-pi/catalog.json
|
|
133
|
+
~/.cache/opencode/free-pi/models-dev.json
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
En Windows es `%USERPROFILE%\.cache\opencode\free-pi\`. El catálogo se reutiliza
|
|
137
|
+
hasta 24 h y el registro hasta 7 días si la red falla; cuando la petición
|
|
138
|
+
funciona, las copias se refrescan solas.
|
|
139
|
+
|
|
140
|
+
Los mensajes del plugin se escriben en la consola con el prefijo `[free-pi]` y
|
|
141
|
+
también en:
|
|
142
|
+
|
|
143
|
+
```text
|
|
144
|
+
~/.cache/opencode/free-pi/plugin.log
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
El archivo rota a `plugin.log.1` al llegar a 1 MB. Ejemplo:
|
|
148
|
+
|
|
149
|
+
```text
|
|
150
|
+
2026-11-21T08:20:00.000Z INFO [free-pi] Loaded 20 free-pi model(s) and 7 defense model(s)
|
|
151
|
+
2026-11-21T08:20:00.000Z WARN [free-pi] models.dev is unreachable; using cached model metadata {"reason":"request timed out"}
|
|
152
|
+
```
|
|
153
|
+
|
|
122
154
|
## Instalación rápida con script
|
|
123
155
|
|
|
124
156
|
### Windows (PowerShell)
|
|
@@ -177,10 +209,11 @@ src/
|
|
|
177
209
|
errors/ parseo, mensajes y reescritura de límites
|
|
178
210
|
integration/ integración y métodos de inicio de sesión
|
|
179
211
|
session/ hooks, eventos, seguimiento y uso
|
|
180
|
-
utils/ helpers pequeños
|
|
212
|
+
utils/ helpers pequeños (incluye cache.ts)
|
|
181
213
|
dist/ build ESM y tipos
|
|
182
214
|
scripts/postinstall.mjs registro en opencode.json
|
|
183
215
|
test/smoke.mjs prueba de humo del build
|
|
216
|
+
test/registry.mjs caché y tolerancia a fallos de models.dev
|
|
184
217
|
```
|
|
185
218
|
|
|
186
219
|
## Desinstalar
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
/** Fetches the live free-pi model catalog. */
|
|
2
2
|
import type { Deps } from "../deps.js";
|
|
3
3
|
import type { Catalog } from "../types.js";
|
|
4
|
+
/** Refreshes the catalog without blocking callers that already have data. */
|
|
5
|
+
export declare function refreshCatalog(deps: Deps): Promise<Catalog | undefined>;
|
|
4
6
|
export declare function fetchCatalog(deps: Deps): Promise<Catalog | undefined>;
|
package/dist/catalog/catalog.js
CHANGED
|
@@ -1,43 +1,80 @@
|
|
|
1
1
|
/** Fetches the live free-pi model catalog. */
|
|
2
|
-
import { CATALOG_TTL_MS } from "../constants.js";
|
|
2
|
+
import { CATALOG_DISK_TTL_MS, CATALOG_TIMEOUT_MS, CATALOG_TTL_MS, } from "../constants.js";
|
|
3
|
+
import { readCache, writeCache } from "../utils/cache.js";
|
|
3
4
|
import { resolveBaseUrl } from "../utils/urls.js";
|
|
4
|
-
|
|
5
|
+
const CACHE_FILE = "catalog.json";
|
|
6
|
+
function isCatalog(value) {
|
|
7
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
8
|
+
}
|
|
9
|
+
function reasonText(error) {
|
|
10
|
+
if (error instanceof Error) {
|
|
11
|
+
return error.name === "TimeoutError" ? "request timed out" : error.message;
|
|
12
|
+
}
|
|
13
|
+
return "request failed";
|
|
14
|
+
}
|
|
15
|
+
function applyCatalog(deps, catalog) {
|
|
5
16
|
const state = deps.state;
|
|
6
|
-
if (
|
|
7
|
-
|
|
17
|
+
if (typeof catalog.latest === "string" && catalog.latest.length > 0) {
|
|
18
|
+
state.latestClientVersion = catalog.latest;
|
|
8
19
|
}
|
|
20
|
+
const arm = catalog.cost_experiment?.arm;
|
|
21
|
+
state.costExperimentArm =
|
|
22
|
+
typeof arm === "string" && /^[A-Za-z0-9_-]{1,40}$/.test(arm)
|
|
23
|
+
? arm
|
|
24
|
+
: undefined;
|
|
25
|
+
state.cachedCatalog = catalog;
|
|
26
|
+
state.cachedCatalogAt = Date.now();
|
|
27
|
+
return catalog;
|
|
28
|
+
}
|
|
29
|
+
/** Refreshes the catalog without blocking callers that already have data. */
|
|
30
|
+
export function refreshCatalog(deps) {
|
|
31
|
+
const state = deps.state;
|
|
9
32
|
if (state.catalogPromise)
|
|
10
33
|
return state.catalogPromise;
|
|
11
34
|
const pending = (async () => {
|
|
12
35
|
try {
|
|
13
36
|
const response = await fetch(`${resolveBaseUrl()}/client-version`, {
|
|
14
|
-
|
|
37
|
+
headers: { accept: "application/json" },
|
|
38
|
+
signal: AbortSignal.timeout(CATALOG_TIMEOUT_MS),
|
|
15
39
|
});
|
|
16
40
|
if (!response.ok)
|
|
17
|
-
|
|
41
|
+
throw new Error(`HTTP ${response.status}`);
|
|
18
42
|
const catalog = (await response.json());
|
|
19
|
-
if (
|
|
20
|
-
|
|
43
|
+
if (!isCatalog(catalog)) {
|
|
44
|
+
throw new Error("free-pi returned an unexpected catalog payload");
|
|
21
45
|
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
typeof arm === "string" && /^[A-Za-z0-9_-]{1,40}$/.test(arm)
|
|
25
|
-
? arm
|
|
26
|
-
: undefined;
|
|
27
|
-
state.cachedCatalog = catalog;
|
|
28
|
-
state.cachedCatalogAt = Date.now();
|
|
46
|
+
applyCatalog(deps, catalog);
|
|
47
|
+
void writeCache(CACHE_FILE, catalog);
|
|
29
48
|
return catalog;
|
|
30
49
|
}
|
|
31
|
-
catch {
|
|
32
|
-
|
|
50
|
+
catch (error) {
|
|
51
|
+
const cached = state.cachedCatalog;
|
|
52
|
+
deps.log.warn(cached
|
|
53
|
+
? "free-pi catalog is unreachable; using the cached model list"
|
|
54
|
+
: "free-pi catalog is unreachable; no free-pi models were registered", { reason: reasonText(error) });
|
|
55
|
+
return cached;
|
|
33
56
|
}
|
|
34
57
|
})();
|
|
35
58
|
state.catalogPromise = pending;
|
|
36
|
-
|
|
37
|
-
return await pending;
|
|
38
|
-
}
|
|
39
|
-
finally {
|
|
59
|
+
void pending.finally(() => {
|
|
40
60
|
if (state.catalogPromise === pending)
|
|
41
61
|
state.catalogPromise = undefined;
|
|
62
|
+
});
|
|
63
|
+
return pending;
|
|
64
|
+
}
|
|
65
|
+
export async function fetchCatalog(deps) {
|
|
66
|
+
const state = deps.state;
|
|
67
|
+
if (state.cachedCatalog && Date.now() - state.cachedCatalogAt < CATALOG_TTL_MS) {
|
|
68
|
+
return state.cachedCatalog;
|
|
69
|
+
}
|
|
70
|
+
if (!state.cachedCatalog) {
|
|
71
|
+
const disk = await readCache(CACHE_FILE, CATALOG_DISK_TTL_MS);
|
|
72
|
+
if (isCatalog(disk)) {
|
|
73
|
+
applyCatalog(deps, disk);
|
|
74
|
+
// Serve the cached copy immediately and refresh it in the background.
|
|
75
|
+
void refreshCatalog(deps);
|
|
76
|
+
return disk;
|
|
77
|
+
}
|
|
42
78
|
}
|
|
79
|
+
return refreshCatalog(deps);
|
|
43
80
|
}
|
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
/** Fetches the models.dev capability registry. */
|
|
2
2
|
import type { Deps } from "../deps.js";
|
|
3
3
|
import type { ModelRegistry } from "../types.js";
|
|
4
|
+
/**
|
|
5
|
+
* Refreshes the registry without blocking callers that already have data.
|
|
6
|
+
* Concurrent calls share one request.
|
|
7
|
+
*/
|
|
8
|
+
export declare function refreshModelsRegistry(deps: Deps): Promise<ModelRegistry | undefined>;
|
|
4
9
|
export declare function fetchModelsRegistry(deps: Deps): Promise<ModelRegistry | undefined>;
|
package/dist/catalog/registry.js
CHANGED
|
@@ -1,46 +1,96 @@
|
|
|
1
1
|
/** Fetches the models.dev capability registry. */
|
|
2
|
-
import { REGISTRY_TTL_MS } from "../constants.js";
|
|
2
|
+
import { REGISTRY_ATTEMPTS, REGISTRY_DISK_TTL_MS, REGISTRY_RETRY_MS, REGISTRY_TIMEOUT_MS, REGISTRY_TTL_MS, } from "../constants.js";
|
|
3
|
+
import { sleep } from "../utils/async.js";
|
|
4
|
+
import { readCache, writeCache } from "../utils/cache.js";
|
|
3
5
|
import { modelsRegistryUrl } from "../utils/urls.js";
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
const CACHE_FILE = "models-dev.json";
|
|
7
|
+
function isRegistry(value) {
|
|
8
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
9
|
+
}
|
|
10
|
+
function reasonText(error) {
|
|
11
|
+
if (error instanceof Error) {
|
|
12
|
+
return error.name === "TimeoutError" ? "request timed out" : error.message;
|
|
8
13
|
}
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
14
|
+
return "request failed";
|
|
15
|
+
}
|
|
16
|
+
async function requestRegistry() {
|
|
17
|
+
const base = modelsRegistryUrl();
|
|
18
|
+
const url = base.endsWith(".json") ? base : `${base}/api.json`;
|
|
19
|
+
let lastError;
|
|
20
|
+
for (let attempt = 1; attempt <= REGISTRY_ATTEMPTS; attempt += 1) {
|
|
21
|
+
try {
|
|
22
|
+
const response = await fetch(url, {
|
|
23
|
+
headers: { accept: "application/json" },
|
|
24
|
+
signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS),
|
|
25
|
+
});
|
|
26
|
+
if (!response.ok)
|
|
27
|
+
throw new Error(`HTTP ${response.status}`);
|
|
28
|
+
return (await response.json());
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
lastError = error;
|
|
32
|
+
if (attempt < REGISTRY_ATTEMPTS)
|
|
33
|
+
await sleep(500 * attempt);
|
|
34
|
+
}
|
|
13
35
|
}
|
|
36
|
+
throw lastError instanceof Error
|
|
37
|
+
? lastError
|
|
38
|
+
: new Error("models.dev request failed");
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Refreshes the registry without blocking callers that already have data.
|
|
42
|
+
* Concurrent calls share one request.
|
|
43
|
+
*/
|
|
44
|
+
export function refreshModelsRegistry(deps) {
|
|
45
|
+
const state = deps.state;
|
|
14
46
|
if (state.registryPromise)
|
|
15
47
|
return state.registryPromise;
|
|
16
48
|
const pending = (async () => {
|
|
17
49
|
state.registryAttemptAt = Date.now();
|
|
18
50
|
try {
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
|
|
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;
|
|
51
|
+
const registry = await requestRegistry();
|
|
52
|
+
if (!isRegistry(registry)) {
|
|
53
|
+
throw new Error("models.dev returned an unexpected payload");
|
|
29
54
|
}
|
|
30
55
|
state.cachedRegistry = registry;
|
|
31
56
|
state.cachedRegistryAt = Date.now();
|
|
57
|
+
void writeCache(CACHE_FILE, registry);
|
|
32
58
|
return registry;
|
|
33
59
|
}
|
|
34
|
-
catch {
|
|
35
|
-
|
|
60
|
+
catch (error) {
|
|
61
|
+
const cached = state.cachedRegistry;
|
|
62
|
+
deps.log.warn(cached
|
|
63
|
+
? "models.dev is unreachable; using cached model metadata"
|
|
64
|
+
: "models.dev is unreachable; model limits fall back to defaults", { reason: reasonText(error) });
|
|
65
|
+
return cached;
|
|
36
66
|
}
|
|
37
67
|
})();
|
|
38
68
|
state.registryPromise = pending;
|
|
39
|
-
|
|
40
|
-
return await pending;
|
|
41
|
-
}
|
|
42
|
-
finally {
|
|
69
|
+
void pending.finally(() => {
|
|
43
70
|
if (state.registryPromise === pending)
|
|
44
71
|
state.registryPromise = undefined;
|
|
72
|
+
});
|
|
73
|
+
return pending;
|
|
74
|
+
}
|
|
75
|
+
export async function fetchModelsRegistry(deps) {
|
|
76
|
+
const state = deps.state;
|
|
77
|
+
if (state.cachedRegistry &&
|
|
78
|
+
Date.now() - state.cachedRegistryAt < REGISTRY_TTL_MS) {
|
|
79
|
+
return state.cachedRegistry;
|
|
80
|
+
}
|
|
81
|
+
if (!state.cachedRegistry) {
|
|
82
|
+
const disk = await readCache(CACHE_FILE, REGISTRY_DISK_TTL_MS);
|
|
83
|
+
if (isRegistry(disk)) {
|
|
84
|
+
state.cachedRegistry = disk;
|
|
85
|
+
state.cachedRegistryAt = Date.now();
|
|
86
|
+
// Serve the cached copy immediately and refresh it in the background.
|
|
87
|
+
void refreshModelsRegistry(deps);
|
|
88
|
+
return disk;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (state.registryAttemptAt &&
|
|
92
|
+
Date.now() - state.registryAttemptAt < REGISTRY_RETRY_MS) {
|
|
93
|
+
return state.cachedRegistry;
|
|
45
94
|
}
|
|
95
|
+
return refreshModelsRegistry(deps);
|
|
46
96
|
}
|
package/dist/constants.d.ts
CHANGED
|
@@ -25,7 +25,13 @@ export declare const AD_TURN_LIMIT = 200;
|
|
|
25
25
|
export declare const AD_IMPRESSION_LIMIT = 200;
|
|
26
26
|
export declare const CREDITS_PER_USD: number;
|
|
27
27
|
export declare const CATALOG_TTL_MS: number;
|
|
28
|
+
export declare const CATALOG_DISK_TTL_MS: number;
|
|
29
|
+
export declare const CATALOG_TIMEOUT_MS = 8000;
|
|
28
30
|
export declare const REGISTRY_TTL_MS: number;
|
|
31
|
+
export declare const REGISTRY_DISK_TTL_MS: number;
|
|
32
|
+
export declare const REGISTRY_RETRY_MS = 60000;
|
|
33
|
+
export declare const REGISTRY_TIMEOUT_MS = 3500;
|
|
34
|
+
export declare const REGISTRY_ATTEMPTS = 2;
|
|
29
35
|
export declare const DEFAULT_MODELS_REGISTRY_URL = "https://models.opencode.ai";
|
|
30
36
|
export declare const QUOTA_TTL_MS = 30000;
|
|
31
37
|
export declare const QUOTA_HTTP_TIMEOUT_MS = 5000;
|
package/dist/constants.js
CHANGED
|
@@ -25,7 +25,13 @@ export const AD_TURN_LIMIT = 200;
|
|
|
25
25
|
export const AD_IMPRESSION_LIMIT = 200;
|
|
26
26
|
export const CREDITS_PER_USD = 40_000 / 3;
|
|
27
27
|
export const CATALOG_TTL_MS = 10 * 60_000;
|
|
28
|
+
export const CATALOG_DISK_TTL_MS = 24 * 60 * 60_000;
|
|
29
|
+
export const CATALOG_TIMEOUT_MS = 8_000;
|
|
28
30
|
export const REGISTRY_TTL_MS = 5 * 60_000;
|
|
31
|
+
export const REGISTRY_DISK_TTL_MS = 7 * 24 * 60 * 60_000;
|
|
32
|
+
export const REGISTRY_RETRY_MS = 60_000;
|
|
33
|
+
export const REGISTRY_TIMEOUT_MS = 3_500;
|
|
34
|
+
export const REGISTRY_ATTEMPTS = 2;
|
|
29
35
|
export const DEFAULT_MODELS_REGISTRY_URL = "https://models.opencode.ai";
|
|
30
36
|
export const QUOTA_TTL_MS = 30_000;
|
|
31
37
|
export const QUOTA_HTTP_TIMEOUT_MS = 5_000;
|
package/dist/logging.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** Logging for the plugin. V2 has no `app.log`, so messages go to the console. */
|
|
1
|
+
/** Logging for the plugin. V2 has no `app.log`, so messages go to the console and a file. */
|
|
2
2
|
export type LogLevel = "info" | "warn" | "error" | "debug";
|
|
3
3
|
export type Logger = {
|
|
4
4
|
log: (level: LogLevel, message: string, extra?: unknown) => void;
|
package/dist/logging.js
CHANGED
|
@@ -1,14 +1,57 @@
|
|
|
1
|
-
/** Logging for the plugin. V2 has no `app.log`, so messages go to the console. */
|
|
1
|
+
/** Logging for the plugin. V2 has no `app.log`, so messages go to the console and a file. */
|
|
2
|
+
import { appendFileSync, mkdirSync, renameSync, statSync } from "node:fs";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { cacheDir } from "./utils/cache.js";
|
|
5
|
+
const MAX_LOG_BYTES = 1_000_000;
|
|
6
|
+
let fileFailureReported = false;
|
|
7
|
+
function logFile() {
|
|
8
|
+
const configured = process.env.FREE_PI_LOG_FILE?.trim();
|
|
9
|
+
return configured || join(cacheDir(), "plugin.log");
|
|
10
|
+
}
|
|
11
|
+
function rotate(file) {
|
|
12
|
+
try {
|
|
13
|
+
if (statSync(file).size < MAX_LOG_BYTES)
|
|
14
|
+
return;
|
|
15
|
+
renameSync(file, `${file}.1`);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
// Missing file: nothing to rotate.
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function formatExtra(extra) {
|
|
22
|
+
if (extra === undefined)
|
|
23
|
+
return "";
|
|
24
|
+
try {
|
|
25
|
+
return ` ${JSON.stringify(extra)}`;
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return " [unserializable]";
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function appendToFile(line) {
|
|
32
|
+
try {
|
|
33
|
+
const file = logFile();
|
|
34
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
35
|
+
rotate(file);
|
|
36
|
+
appendFileSync(file, `${line}\n`, "utf8");
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
if (fileFailureReported)
|
|
40
|
+
return;
|
|
41
|
+
fileFailureReported = true;
|
|
42
|
+
console.warn("[free-pi] could not write the plugin log file", error);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
2
45
|
export function createLogger(scope = "free-pi") {
|
|
3
46
|
const write = (level, message, extra) => {
|
|
4
|
-
const line =
|
|
5
|
-
const args = extra === undefined ? [line] : [line, extra];
|
|
47
|
+
const line = `${new Date().toISOString()} ${level.toUpperCase()} [${scope}] ${message}${formatExtra(extra)}`;
|
|
6
48
|
if (level === "error")
|
|
7
|
-
console.error(
|
|
49
|
+
console.error(line);
|
|
8
50
|
else if (level === "warn")
|
|
9
|
-
console.warn(
|
|
51
|
+
console.warn(line);
|
|
10
52
|
else
|
|
11
|
-
console.log(
|
|
53
|
+
console.log(line);
|
|
54
|
+
appendToFile(line);
|
|
12
55
|
};
|
|
13
56
|
return {
|
|
14
57
|
log: write,
|
package/dist/plugin.js
CHANGED
|
@@ -45,10 +45,13 @@ async function setup(ctx) {
|
|
|
45
45
|
}
|
|
46
46
|
},
|
|
47
47
|
};
|
|
48
|
-
const [
|
|
48
|
+
const [catalogResult, registryResult] = await Promise.all([
|
|
49
49
|
settle(fetchCatalog(deps), undefined),
|
|
50
50
|
settle(fetchModelsRegistry(deps), undefined),
|
|
51
51
|
]);
|
|
52
|
+
// The fetch may finish just after `settle` gives up; reuse whatever landed.
|
|
53
|
+
const catalog = catalogResult ?? state.cachedCatalog;
|
|
54
|
+
const registry = registryResult ?? state.cachedRegistry;
|
|
52
55
|
const { main, defense } = partitionModels(catalog);
|
|
53
56
|
const candidates = modelRegistryCandidates(registry);
|
|
54
57
|
const mainModels = buildModels(main, candidates);
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Best-effort JSON cache on disk for data fetched over the network. */
|
|
2
|
+
export declare function cacheDir(): string;
|
|
3
|
+
export declare function cachePath(name: string): string;
|
|
4
|
+
/** Reads a cached value when it is younger than `ttlMs`. Never throws. */
|
|
5
|
+
export declare function readCache<T>(name: string, ttlMs: number): Promise<T | undefined>;
|
|
6
|
+
/** Writes a value atomically. Never throws. */
|
|
7
|
+
export declare function writeCache<T>(name: string, value: T): Promise<void>;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/** Best-effort JSON cache on disk for data fetched over the network. */
|
|
2
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
export function cacheDir() {
|
|
6
|
+
const configured = process.env.FREE_PI_CACHE_DIR?.trim();
|
|
7
|
+
if (configured)
|
|
8
|
+
return configured;
|
|
9
|
+
return join(homedir(), ".cache", "opencode", "free-pi");
|
|
10
|
+
}
|
|
11
|
+
export function cachePath(name) {
|
|
12
|
+
return join(cacheDir(), name);
|
|
13
|
+
}
|
|
14
|
+
/** Reads a cached value when it is younger than `ttlMs`. Never throws. */
|
|
15
|
+
export async function readCache(name, ttlMs) {
|
|
16
|
+
try {
|
|
17
|
+
const raw = await readFile(cachePath(name), "utf8");
|
|
18
|
+
const entry = JSON.parse(raw);
|
|
19
|
+
if (!entry || typeof entry.at !== "number")
|
|
20
|
+
return undefined;
|
|
21
|
+
if (!Number.isFinite(entry.at))
|
|
22
|
+
return undefined;
|
|
23
|
+
if (Date.now() - entry.at > ttlMs)
|
|
24
|
+
return undefined;
|
|
25
|
+
return entry.value;
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** Writes a value atomically. Never throws. */
|
|
32
|
+
export async function writeCache(name, value) {
|
|
33
|
+
try {
|
|
34
|
+
const file = cachePath(name);
|
|
35
|
+
await mkdir(dirname(file), { recursive: true });
|
|
36
|
+
const temp = `${file}.${process.pid}.${Math.random()
|
|
37
|
+
.toString(36)
|
|
38
|
+
.slice(2)}.tmp`;
|
|
39
|
+
await writeFile(temp, JSON.stringify({ at: Date.now(), value }), "utf8");
|
|
40
|
+
await rename(temp, file);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
// The cache is an optimization; failures must not affect the plugin.
|
|
44
|
+
}
|
|
45
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@eduardo191labs/opencode-free-pi",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "Ad-supported free-pi provider plugin for OpenCode on Windows, Linux, macOS and Termux",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"scripts": {
|
|
25
25
|
"build": "tsc -p tsconfig.json",
|
|
26
26
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
27
|
-
"test": "npm run build && node test/smoke.mjs",
|
|
27
|
+
"test": "npm run build && node test/smoke.mjs && node test/registry.mjs",
|
|
28
28
|
"prepublishOnly": "npm run build",
|
|
29
29
|
"postinstall": "node scripts/postinstall.mjs"
|
|
30
30
|
},
|
package/src/catalog/catalog.ts
CHANGED
|
@@ -1,42 +1,94 @@
|
|
|
1
1
|
/** Fetches the live free-pi model catalog. */
|
|
2
2
|
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
CATALOG_DISK_TTL_MS,
|
|
5
|
+
CATALOG_TIMEOUT_MS,
|
|
6
|
+
CATALOG_TTL_MS,
|
|
7
|
+
} from "../constants.js";
|
|
4
8
|
import type { Deps } from "../deps.js";
|
|
5
9
|
import type { Catalog } from "../types.js";
|
|
10
|
+
import { readCache, writeCache } from "../utils/cache.js";
|
|
6
11
|
import { resolveBaseUrl } from "../utils/urls.js";
|
|
7
12
|
|
|
8
|
-
|
|
13
|
+
const CACHE_FILE = "catalog.json";
|
|
14
|
+
|
|
15
|
+
function isCatalog(value: unknown): value is Catalog {
|
|
16
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function reasonText(error: unknown): string {
|
|
20
|
+
if (error instanceof Error) {
|
|
21
|
+
return error.name === "TimeoutError" ? "request timed out" : error.message;
|
|
22
|
+
}
|
|
23
|
+
return "request failed";
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function applyCatalog(deps: Deps, catalog: Catalog): Catalog {
|
|
9
27
|
const state = deps.state;
|
|
10
|
-
if (
|
|
11
|
-
|
|
28
|
+
if (typeof catalog.latest === "string" && catalog.latest.length > 0) {
|
|
29
|
+
state.latestClientVersion = catalog.latest;
|
|
12
30
|
}
|
|
31
|
+
const arm = catalog.cost_experiment?.arm;
|
|
32
|
+
state.costExperimentArm =
|
|
33
|
+
typeof arm === "string" && /^[A-Za-z0-9_-]{1,40}$/.test(arm)
|
|
34
|
+
? arm
|
|
35
|
+
: undefined;
|
|
36
|
+
state.cachedCatalog = catalog;
|
|
37
|
+
state.cachedCatalogAt = Date.now();
|
|
38
|
+
return catalog;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Refreshes the catalog without blocking callers that already have data. */
|
|
42
|
+
export function refreshCatalog(deps: Deps): Promise<Catalog | undefined> {
|
|
43
|
+
const state = deps.state;
|
|
13
44
|
if (state.catalogPromise) return state.catalogPromise;
|
|
14
45
|
const pending = (async () => {
|
|
15
46
|
try {
|
|
16
47
|
const response = await fetch(`${resolveBaseUrl()}/client-version`, {
|
|
17
|
-
|
|
48
|
+
headers: { accept: "application/json" },
|
|
49
|
+
signal: AbortSignal.timeout(CATALOG_TIMEOUT_MS),
|
|
18
50
|
});
|
|
19
|
-
if (!response.ok)
|
|
51
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
20
52
|
const catalog = (await response.json()) as Catalog;
|
|
21
|
-
if (
|
|
22
|
-
|
|
53
|
+
if (!isCatalog(catalog)) {
|
|
54
|
+
throw new Error("free-pi returned an unexpected catalog payload");
|
|
23
55
|
}
|
|
24
|
-
|
|
25
|
-
|
|
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();
|
|
56
|
+
applyCatalog(deps, catalog);
|
|
57
|
+
void writeCache(CACHE_FILE, catalog);
|
|
31
58
|
return catalog;
|
|
32
|
-
} catch {
|
|
33
|
-
|
|
59
|
+
} catch (error) {
|
|
60
|
+
const cached = state.cachedCatalog;
|
|
61
|
+
deps.log.warn(
|
|
62
|
+
cached
|
|
63
|
+
? "free-pi catalog is unreachable; using the cached model list"
|
|
64
|
+
: "free-pi catalog is unreachable; no free-pi models were registered",
|
|
65
|
+
{ reason: reasonText(error) },
|
|
66
|
+
);
|
|
67
|
+
return cached;
|
|
34
68
|
}
|
|
35
69
|
})();
|
|
36
70
|
state.catalogPromise = pending;
|
|
37
|
-
|
|
38
|
-
return await pending;
|
|
39
|
-
} finally {
|
|
71
|
+
void pending.finally(() => {
|
|
40
72
|
if (state.catalogPromise === pending) state.catalogPromise = undefined;
|
|
73
|
+
});
|
|
74
|
+
return pending;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export async function fetchCatalog(deps: Deps): Promise<Catalog | undefined> {
|
|
78
|
+
const state = deps.state;
|
|
79
|
+
if (state.cachedCatalog && Date.now() - state.cachedCatalogAt < CATALOG_TTL_MS) {
|
|
80
|
+
return state.cachedCatalog;
|
|
41
81
|
}
|
|
82
|
+
|
|
83
|
+
if (!state.cachedCatalog) {
|
|
84
|
+
const disk = await readCache<Catalog>(CACHE_FILE, CATALOG_DISK_TTL_MS);
|
|
85
|
+
if (isCatalog(disk)) {
|
|
86
|
+
applyCatalog(deps, disk);
|
|
87
|
+
// Serve the cached copy immediately and refresh it in the background.
|
|
88
|
+
void refreshCatalog(deps);
|
|
89
|
+
return disk;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return refreshCatalog(deps);
|
|
42
94
|
}
|
package/src/catalog/registry.ts
CHANGED
|
@@ -1,51 +1,122 @@
|
|
|
1
1
|
/** Fetches the models.dev capability registry. */
|
|
2
2
|
|
|
3
|
-
import {
|
|
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";
|
|
4
10
|
import type { Deps } from "../deps.js";
|
|
5
11
|
import type { ModelRegistry } from "../types.js";
|
|
12
|
+
import { sleep } from "../utils/async.js";
|
|
13
|
+
import { readCache, writeCache } from "../utils/cache.js";
|
|
6
14
|
import { modelsRegistryUrl } from "../utils/urls.js";
|
|
7
15
|
|
|
8
|
-
|
|
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(
|
|
9
56
|
deps: Deps,
|
|
10
57
|
): Promise<ModelRegistry | undefined> {
|
|
11
58
|
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
59
|
if (state.registryPromise) return state.registryPromise;
|
|
23
60
|
const pending = (async () => {
|
|
24
61
|
state.registryAttemptAt = Date.now();
|
|
25
62
|
try {
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
|
|
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;
|
|
63
|
+
const registry = await requestRegistry();
|
|
64
|
+
if (!isRegistry(registry)) {
|
|
65
|
+
throw new Error("models.dev returned an unexpected payload");
|
|
37
66
|
}
|
|
38
67
|
state.cachedRegistry = registry;
|
|
39
68
|
state.cachedRegistryAt = Date.now();
|
|
69
|
+
void writeCache(CACHE_FILE, registry);
|
|
40
70
|
return registry;
|
|
41
|
-
} catch {
|
|
42
|
-
|
|
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;
|
|
43
80
|
}
|
|
44
81
|
})();
|
|
45
82
|
state.registryPromise = pending;
|
|
46
|
-
|
|
47
|
-
return await pending;
|
|
48
|
-
} finally {
|
|
83
|
+
void pending.finally(() => {
|
|
49
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;
|
|
50
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);
|
|
51
122
|
}
|
package/src/constants.ts
CHANGED
|
@@ -35,7 +35,13 @@ export const AD_IMPRESSION_LIMIT = 200;
|
|
|
35
35
|
export const CREDITS_PER_USD = 40_000 / 3;
|
|
36
36
|
|
|
37
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;
|
|
38
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;
|
|
39
45
|
export const DEFAULT_MODELS_REGISTRY_URL = "https://models.opencode.ai";
|
|
40
46
|
|
|
41
47
|
export const QUOTA_TTL_MS = 30_000;
|
package/src/logging.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
/** Logging for the plugin. V2 has no `app.log`, so messages go to the console. */
|
|
1
|
+
/** Logging for the plugin. V2 has no `app.log`, so messages go to the console and a file. */
|
|
2
|
+
|
|
3
|
+
import { appendFileSync, mkdirSync, renameSync, statSync } from "node:fs";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { cacheDir } from "./utils/cache.js";
|
|
2
6
|
|
|
3
7
|
export type LogLevel = "info" | "warn" | "error" | "debug";
|
|
4
8
|
|
|
@@ -9,13 +13,53 @@ export type Logger = {
|
|
|
9
13
|
error: (message: string, extra?: unknown) => void;
|
|
10
14
|
};
|
|
11
15
|
|
|
16
|
+
const MAX_LOG_BYTES = 1_000_000;
|
|
17
|
+
|
|
18
|
+
let fileFailureReported = false;
|
|
19
|
+
|
|
20
|
+
function logFile(): string {
|
|
21
|
+
const configured = process.env.FREE_PI_LOG_FILE?.trim();
|
|
22
|
+
return configured || join(cacheDir(), "plugin.log");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function rotate(file: string): void {
|
|
26
|
+
try {
|
|
27
|
+
if (statSync(file).size < MAX_LOG_BYTES) return;
|
|
28
|
+
renameSync(file, `${file}.1`);
|
|
29
|
+
} catch {
|
|
30
|
+
// Missing file: nothing to rotate.
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function formatExtra(extra: unknown): string {
|
|
35
|
+
if (extra === undefined) return "";
|
|
36
|
+
try {
|
|
37
|
+
return ` ${JSON.stringify(extra)}`;
|
|
38
|
+
} catch {
|
|
39
|
+
return " [unserializable]";
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function appendToFile(line: string): void {
|
|
44
|
+
try {
|
|
45
|
+
const file = logFile();
|
|
46
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
47
|
+
rotate(file);
|
|
48
|
+
appendFileSync(file, `${line}\n`, "utf8");
|
|
49
|
+
} catch (error) {
|
|
50
|
+
if (fileFailureReported) return;
|
|
51
|
+
fileFailureReported = true;
|
|
52
|
+
console.warn("[free-pi] could not write the plugin log file", error);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
12
56
|
export function createLogger(scope = "free-pi"): Logger {
|
|
13
57
|
const write = (level: LogLevel, message: string, extra?: unknown) => {
|
|
14
|
-
const line =
|
|
15
|
-
|
|
16
|
-
if (level === "
|
|
17
|
-
else
|
|
18
|
-
|
|
58
|
+
const line = `${new Date().toISOString()} ${level.toUpperCase()} [${scope}] ${message}${formatExtra(extra)}`;
|
|
59
|
+
if (level === "error") console.error(line);
|
|
60
|
+
else if (level === "warn") console.warn(line);
|
|
61
|
+
else console.log(line);
|
|
62
|
+
appendToFile(line);
|
|
19
63
|
};
|
|
20
64
|
return {
|
|
21
65
|
log: write,
|
package/src/plugin.ts
CHANGED
|
@@ -55,10 +55,13 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
55
55
|
},
|
|
56
56
|
};
|
|
57
57
|
|
|
58
|
-
const [
|
|
58
|
+
const [catalogResult, registryResult] = await Promise.all([
|
|
59
59
|
settle(fetchCatalog(deps), undefined),
|
|
60
60
|
settle(fetchModelsRegistry(deps), undefined),
|
|
61
61
|
]);
|
|
62
|
+
// The fetch may finish just after `settle` gives up; reuse whatever landed.
|
|
63
|
+
const catalog = catalogResult ?? state.cachedCatalog;
|
|
64
|
+
const registry = registryResult ?? state.cachedRegistry;
|
|
62
65
|
const { main, defense } = partitionModels(catalog);
|
|
63
66
|
const candidates = modelRegistryCandidates(registry);
|
|
64
67
|
const mainModels = buildModels(main, candidates);
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/** Best-effort JSON cache on disk for data fetched over the network. */
|
|
2
|
+
|
|
3
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
|
|
7
|
+
type CacheEntry<T> = { at: number; value: T };
|
|
8
|
+
|
|
9
|
+
export function cacheDir(): string {
|
|
10
|
+
const configured = process.env.FREE_PI_CACHE_DIR?.trim();
|
|
11
|
+
if (configured) return configured;
|
|
12
|
+
return join(homedir(), ".cache", "opencode", "free-pi");
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function cachePath(name: string): string {
|
|
16
|
+
return join(cacheDir(), name);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Reads a cached value when it is younger than `ttlMs`. Never throws. */
|
|
20
|
+
export async function readCache<T>(
|
|
21
|
+
name: string,
|
|
22
|
+
ttlMs: number,
|
|
23
|
+
): Promise<T | undefined> {
|
|
24
|
+
try {
|
|
25
|
+
const raw = await readFile(cachePath(name), "utf8");
|
|
26
|
+
const entry = JSON.parse(raw) as CacheEntry<T>;
|
|
27
|
+
if (!entry || typeof entry.at !== "number") return undefined;
|
|
28
|
+
if (!Number.isFinite(entry.at)) return undefined;
|
|
29
|
+
if (Date.now() - entry.at > ttlMs) return undefined;
|
|
30
|
+
return entry.value;
|
|
31
|
+
} catch {
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Writes a value atomically. Never throws. */
|
|
37
|
+
export async function writeCache<T>(name: string, value: T): Promise<void> {
|
|
38
|
+
try {
|
|
39
|
+
const file = cachePath(name);
|
|
40
|
+
await mkdir(dirname(file), { recursive: true });
|
|
41
|
+
const temp = `${file}.${process.pid}.${Math.random()
|
|
42
|
+
.toString(36)
|
|
43
|
+
.slice(2)}.tmp`;
|
|
44
|
+
await writeFile(temp, JSON.stringify({ at: Date.now(), value }), "utf8");
|
|
45
|
+
await rename(temp, file);
|
|
46
|
+
} catch {
|
|
47
|
+
// The cache is an optimization; failures must not affect the plugin.
|
|
48
|
+
}
|
|
49
|
+
}
|