@eduardo191labs/opencode-free-pi 0.7.16 → 0.7.17

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 CHANGED
@@ -227,26 +227,38 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
227
227
  mientras no haya ningún modelo registrado, así que un arranque sin red (VPN
228
228
  caída, DPI bloqueando el gateway) se recupera solo cuando vuelve la conexión.
229
229
  No hace falta reiniciar OpenCode ni elegir otra carpeta.
230
- - **Proxy de VPN o red corporativa**: el CLI oficial de free-pi lee `HTTPS_PROXY`,
231
- `HTTP_PROXY` y `ALL_PROXY` (en mayúsculas o minúsculas), pero `fetch` de Node
232
- los ignora salvo que se active. Por eso, si el entorno define un proxy, el
233
- plugin lo activa al arrancar con `http.setGlobalProxyFromEnv()`: el catálogo,
234
- la cuota, los anuncios, la visión, los reintentos y las peticiones al gateway
235
- pasan por el proxy en vez de salir directos y fallar con `ETIMEDOUT`. `ALL_PROXY`
236
- se copia a `HTTPS_PROXY`/`HTTP_PROXY` porque Node solo lee esos dos. Sin
237
- variables de proxy no cambia nada. `setGlobalProxyFromEnv()` existe desde Node
238
- 24.5; en un Node anterior el plugin escribe en el log que hay que arrancar
239
- OpenCode con `NODE_USE_ENV_PROXY=1` (o actualizar Node), porque esa versión
240
- ignora el proxy en `fetch` aunque se defina el resto. Un proxy SOCKS no se
241
- puede usar con esta API y también se avisa. En Node 26 la
242
- verificación fue real: con `HTTPS_PROXY` apuntando a un proxy local, las
243
- conexiones a `api.freepi.ai`, `models.opencode.ai` y `registry.npmjs.org`
244
- aparecieron en el proxy y una sesión completa respondió correctamente.
245
- `fetch` solo admite el proxy de forma global en el proceso, así que la
246
- activación equivale a arrancar con `NODE_USE_ENV_PROXY=1`: cualquier cliente
247
- del proceso que respete el proxy global lo usará, y los demás proveedores del
248
- mismo OpenCode también dejan de fallar detrás de una red que solo permite
249
- proxy.
230
+ - **Conexión directa, sin proxy y solo IPv4**: el plugin **no usa ningún proxy**.
231
+ Si el entorno define `HTTPS_PROXY`, `HTTP_PROXY`, `ALL_PROXY` o sus variantes en
232
+ minúsculas, las borra del proceso al arrancar y lo avisa en el log. Un proxy
233
+ heredado es justo lo que rompía el plugin en Termux/Android: `fetch` lo
234
+ respetaba, todas las peticiones fallaban, el catálogo caía a cero modelos y el
235
+ selector mostraba `ModelUnavailableError`. Ir directo elimina ese fallo en vez
236
+ de intentar repararlo.
237
+ Además se aplican dos ajustes propios de Android:
238
+ - **IPv4 forzado**: `dns.setDefaultResultOrder("ipv4first")` y
239
+ `net.setDefaultAutoSelectFamily(false)`. Android suele anunciar una ruta
240
+ IPv6 que nunca completa; con el orden `verbatim` y el *happy eyeballs*
241
+ activo, Node intentaba AAAA y podía consumir el timeout entero. Ahora toda
242
+ petición usa el registro A.
243
+ - **Almacén de certificados de Termux**: Node trae las raíces de Mozilla, pero
244
+ Termux guarda el bundle que Android realmente confía en
245
+ `$PREFIX/etc/tls/cert.pem`. Se añade a las raíces compiladas (no las
246
+ reemplaza) leyendo `SSL_CERT_FILE`, `CURL_CA_BUNDLE`, `NODE_EXTRA_CA_CERTS`,
247
+ `$PREFIX/etc/tls/cert.pem` y, como último recurso, la ruta por defecto de
248
+ Termux. Esto resuelve los `UNABLE_TO_VERIFY_LEAF_SIGNATURE` y
249
+ `self-signed certificate in chain` detrás de una red que inspecciona TLS.
250
+ Verificado en Node 26 sobre Termux: con `HTTPS_PROXY` apuntando a un puerto
251
+ cerrado, la petición sale directa y llega al servidor; y con el proxy presente
252
+ las variables quedan vacías tras el arranque.
253
+ - **Dependencias del host, no propias**: el plugin declara `@opencode/plugin` y
254
+ `@opencode/schema` como *peer dependencies* opcionales y **no** los instala.
255
+ El runtime de OpenCode V2 rechaza explícitamente que un plugin cargue
256
+ `@opencode/plugin` o `effect` desde su propio `node_modules` (lanza
257
+ `is not provided by OpenCode; plugins must use the host's ... modules`), así
258
+ que el plugin usa siempre las copias del binario que lo carga. Solo
259
+ `@silvia-odwyer/photon-node` sigue siendo opcional propio y se importa de
260
+ forma perezosa: si falta, el redimensionado de imágenes cae a la ruta sin WASM
261
+ en vez de romper el arranque.
250
262
  - **Aislamiento por proveedor**: todo lo que añade el plugin —herramientas,
251
263
  cabeceras, anuncios, reglas de prompt, compactación, reintentos, topes de
252
264
  tokens y ajustes— se aplica solo a `free-pi` y `free-pi-defense`. Los demás
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Direct network policy for free-pi: IPv4-only sockets and Termux's CA bundle.
3
+ *
4
+ * There is no proxy support on purpose. A proxy exported in the environment
5
+ * (VPN client, corporate agent, a dead local port) is what breaks the plugin on
6
+ * Termux/Android: Node's `fetch` honors it, every request fails, the catalog
7
+ * falls back to zero models and the picker shows `ModelUnavailableError`.
8
+ * Going direct removes that entire failure mode instead of trying to repair it.
9
+ *
10
+ * Two Android-specific fixups are applied here:
11
+ *
12
+ * - IPv4 only. Android networks often advertise an IPv6 route that never
13
+ * completes. With the default `verbatim` order and `autoSelectFamily` on,
14
+ * Node races an AAAA dial and can burn the whole request timeout on a family
15
+ * that has no connectivity. `ipv4first` plus a disabled happy-eyeballs dial
16
+ * keeps every request on the A record.
17
+ * - Termux's trust store. Node ships Mozilla's roots, but Termux keeps the
18
+ * bundle Android actually trusts in `$PREFIX/etc/tls/cert.pem`. Certificates
19
+ * intercepted or re-issued by the local network validate against that bundle
20
+ * and fail against the compiled one, which surfaced as
21
+ * `UNABLE_TO_VERIFY_LEAF_SIGNATURE` / `self-signed certificate in chain`.
22
+ */
23
+ import type { Logger } from "../logging.js";
24
+ /** The proxy that was present, if any. Only reported, never used. */
25
+ export declare function detectProxy(env?: NodeJS.ProcessEnv): string | undefined;
26
+ /** Strips every proxy variable so nothing can route through one. */
27
+ export declare function dropProxyVariables(env?: NodeJS.ProcessEnv): string | undefined;
28
+ /**
29
+ * Pins DNS and socket selection to IPv4. Returns whether the resolver order was
30
+ * set; both calls are optional APIs and a missing one is not an error.
31
+ */
32
+ export declare function forceIpv4(): boolean;
33
+ /**
34
+ * Adds Termux's CA bundle to Node's default trust store.
35
+ *
36
+ * The bundle is appended to the compiled roots rather than replacing them, so a
37
+ * partial Termux install still validates public hosts. Returns the path loaded,
38
+ * or undefined when nothing readable was found.
39
+ */
40
+ export declare function loadTermuxCertificates(env?: NodeJS.ProcessEnv): string | undefined;
41
+ /**
42
+ * Installs the direct network policy for this process. Runs before the first
43
+ * catalog request so the provider registers models instead of disappearing.
44
+ */
45
+ export declare function applyDirectNetwork(log: Logger, env?: NodeJS.ProcessEnv): {
46
+ ipv4: boolean;
47
+ ca?: string;
48
+ };
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Direct network policy for free-pi: IPv4-only sockets and Termux's CA bundle.
3
+ *
4
+ * There is no proxy support on purpose. A proxy exported in the environment
5
+ * (VPN client, corporate agent, a dead local port) is what breaks the plugin on
6
+ * Termux/Android: Node's `fetch` honors it, every request fails, the catalog
7
+ * falls back to zero models and the picker shows `ModelUnavailableError`.
8
+ * Going direct removes that entire failure mode instead of trying to repair it.
9
+ *
10
+ * Two Android-specific fixups are applied here:
11
+ *
12
+ * - IPv4 only. Android networks often advertise an IPv6 route that never
13
+ * completes. With the default `verbatim` order and `autoSelectFamily` on,
14
+ * Node races an AAAA dial and can burn the whole request timeout on a family
15
+ * that has no connectivity. `ipv4first` plus a disabled happy-eyeballs dial
16
+ * keeps every request on the A record.
17
+ * - Termux's trust store. Node ships Mozilla's roots, but Termux keeps the
18
+ * bundle Android actually trusts in `$PREFIX/etc/tls/cert.pem`. Certificates
19
+ * intercepted or re-issued by the local network validate against that bundle
20
+ * and fail against the compiled one, which surfaced as
21
+ * `UNABLE_TO_VERIFY_LEAF_SIGNATURE` / `self-signed certificate in chain`.
22
+ */
23
+ import dns from "node:dns";
24
+ import net from "node:net";
25
+ import { existsSync, readFileSync } from "node:fs";
26
+ import { join } from "node:path";
27
+ import tls from "node:tls";
28
+ /** Variables that make a runtime dial a proxy instead of the target host. */
29
+ const PROXY_VARIABLES = [
30
+ "HTTPS_PROXY",
31
+ "https_proxy",
32
+ "HTTP_PROXY",
33
+ "http_proxy",
34
+ "ALL_PROXY",
35
+ "all_proxy",
36
+ "NO_PROXY",
37
+ "no_proxy",
38
+ ];
39
+ /** The proxy that was present, if any. Only reported, never used. */
40
+ export function detectProxy(env = process.env) {
41
+ for (const name of PROXY_VARIABLES) {
42
+ const value = env[name]?.trim();
43
+ if (value && !name.toLowerCase().startsWith("no_"))
44
+ return value;
45
+ }
46
+ return undefined;
47
+ }
48
+ /** Strips every proxy variable so nothing can route through one. */
49
+ export function dropProxyVariables(env = process.env) {
50
+ const found = detectProxy(env);
51
+ for (const name of PROXY_VARIABLES)
52
+ delete env[name];
53
+ return found;
54
+ }
55
+ /**
56
+ * Pins DNS and socket selection to IPv4. Returns whether the resolver order was
57
+ * set; both calls are optional APIs and a missing one is not an error.
58
+ */
59
+ export function forceIpv4() {
60
+ let applied = false;
61
+ try {
62
+ dns.setDefaultResultOrder("ipv4first");
63
+ applied = true;
64
+ }
65
+ catch {
66
+ // Old runtime: happy-eyeballs below still limits the damage.
67
+ }
68
+ try {
69
+ net.setDefaultAutoSelectFamily(false);
70
+ }
71
+ catch {
72
+ // Not available: the resolver order is the only lever here.
73
+ }
74
+ return applied;
75
+ }
76
+ /** Files that may carry a usable CA bundle, most explicit first. */
77
+ function certificateCandidates(env) {
78
+ const found = [];
79
+ for (const name of ["SSL_CERT_FILE", "CURL_CA_BUNDLE", "NODE_EXTRA_CA_CERTS"]) {
80
+ const value = env[name]?.trim();
81
+ if (value)
82
+ found.push(value);
83
+ }
84
+ const prefix = env.PREFIX?.trim();
85
+ if (prefix)
86
+ found.push(join(prefix, "etc/tls/cert.pem"));
87
+ found.push("/data/data/com.termux/files/usr/etc/tls/cert.pem");
88
+ return [...new Set(found)];
89
+ }
90
+ /**
91
+ * Adds Termux's CA bundle to Node's default trust store.
92
+ *
93
+ * The bundle is appended to the compiled roots rather than replacing them, so a
94
+ * partial Termux install still validates public hosts. Returns the path loaded,
95
+ * or undefined when nothing readable was found.
96
+ */
97
+ export function loadTermuxCertificates(env = process.env) {
98
+ if (typeof tls.setDefaultCACertificates !== "function")
99
+ return undefined;
100
+ let builtIn = [];
101
+ try {
102
+ builtIn = tls.getCACertificates("default");
103
+ }
104
+ catch {
105
+ builtIn = [];
106
+ }
107
+ for (const path of certificateCandidates(env)) {
108
+ if (!existsSync(path))
109
+ continue;
110
+ let text;
111
+ try {
112
+ text = readFileSync(path, "utf8");
113
+ }
114
+ catch {
115
+ continue;
116
+ }
117
+ const certificates = text.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);
118
+ if (!certificates || certificates.length === 0)
119
+ continue;
120
+ try {
121
+ tls.setDefaultCACertificates([...builtIn, ...certificates]);
122
+ }
123
+ catch {
124
+ continue;
125
+ }
126
+ return path;
127
+ }
128
+ return undefined;
129
+ }
130
+ /**
131
+ * Installs the direct network policy for this process. Runs before the first
132
+ * catalog request so the provider registers models instead of disappearing.
133
+ */
134
+ export function applyDirectNetwork(log, env = process.env) {
135
+ const dropped = dropProxyVariables(env);
136
+ const ipv4 = forceIpv4();
137
+ const ca = loadTermuxCertificates(env);
138
+ if (dropped) {
139
+ log.warn("free-pi dropped a proxy from the environment; requests go direct", {
140
+ proxy: dropped,
141
+ });
142
+ }
143
+ log.info("free-pi network policy applied", {
144
+ ipv4: ipv4 ? "forced" : "default",
145
+ ca: ca ?? "builtin",
146
+ });
147
+ return { ipv4, ...(ca ? { ca } : {}) };
148
+ }
package/dist/plugin.js CHANGED
@@ -13,7 +13,7 @@ import { applyProvider } from "./catalog/v2.js";
13
13
  import { CATALOG_RECOVERY_DELAYS_MS, CATALOG_RECOVERY_INTERVAL_MS, CATALOG_RECOVERY_LOG_EVERY, DEFENSE_PROVIDER_ID, PROVIDER_ID, } from "./constants.js";
14
14
  import { registerIntegration } from "./integration/setup.js";
15
15
  import { createLogger } from "./logging.js";
16
- import { applyEnvironmentProxy } from "./network/proxy.js";
16
+ import { applyDirectNetwork } from "./network/direct.js";
17
17
  import { subscribeEvents } from "./session/events.js";
18
18
  import { registerSessionHooks } from "./session/hooks.js";
19
19
  import { cancelAllFinalizeTimers } from "./session/track.js";
@@ -39,10 +39,10 @@ function activeCredentialResolver(ctx) {
39
39
  }
40
40
  async function setup(ctx) {
41
41
  const log = createLogger("free-pi");
42
- // A VPN or corporate setup may only allow traffic through a local proxy.
43
- // Enable it before the first catalog request so the provider registers models
44
- // instead of disappearing from the picker.
45
- applyEnvironmentProxy(log);
42
+ // Go direct before the first catalog request: no proxy, IPv4 only, and the
43
+ // Termux trust store. A proxy inherited from the environment is the failure
44
+ // mode that left the picker with zero models and `ModelUnavailableError`.
45
+ applyDirectNetwork(log);
46
46
  const state = createRuntimeState();
47
47
  const includeDefense = ctx.options?.includeDefense !== false;
48
48
  const deps = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.7.16",
3
+ "version": "0.7.17",
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",
@@ -49,17 +49,29 @@
49
49
  "engines": {
50
50
  "node": ">=20"
51
51
  },
52
+ "peerDependencies": {
53
+ "@opencode/plugin": ">=2.3.2",
54
+ "@opencode/schema": ">=2.3.2"
55
+ },
56
+ "peerDependenciesMeta": {
57
+ "@opencode/plugin": {
58
+ "optional": true
59
+ },
60
+ "@opencode/schema": {
61
+ "optional": true
62
+ }
63
+ },
52
64
  "devDependencies": {
53
65
  "@opencode/client": "^2.3.2",
66
+ "@opencode/plugin": "^2.3.2",
67
+ "@opencode/schema": "^2.3.2",
54
68
  "@types/node": "^24.0.0",
55
69
  "typescript": "^5.9.0"
56
70
  },
57
71
  "publishConfig": {
58
72
  "access": "public"
59
73
  },
60
- "dependencies": {
61
- "@opencode/plugin": "^2.3.2",
62
- "@opencode/schema": "^2.3.2",
74
+ "optionalDependencies": {
63
75
  "@silvia-odwyer/photon-node": "^0.3.4"
64
76
  }
65
77
  }
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Direct network policy for free-pi: IPv4-only sockets and Termux's CA bundle.
3
+ *
4
+ * There is no proxy support on purpose. A proxy exported in the environment
5
+ * (VPN client, corporate agent, a dead local port) is what breaks the plugin on
6
+ * Termux/Android: Node's `fetch` honors it, every request fails, the catalog
7
+ * falls back to zero models and the picker shows `ModelUnavailableError`.
8
+ * Going direct removes that entire failure mode instead of trying to repair it.
9
+ *
10
+ * Two Android-specific fixups are applied here:
11
+ *
12
+ * - IPv4 only. Android networks often advertise an IPv6 route that never
13
+ * completes. With the default `verbatim` order and `autoSelectFamily` on,
14
+ * Node races an AAAA dial and can burn the whole request timeout on a family
15
+ * that has no connectivity. `ipv4first` plus a disabled happy-eyeballs dial
16
+ * keeps every request on the A record.
17
+ * - Termux's trust store. Node ships Mozilla's roots, but Termux keeps the
18
+ * bundle Android actually trusts in `$PREFIX/etc/tls/cert.pem`. Certificates
19
+ * intercepted or re-issued by the local network validate against that bundle
20
+ * and fail against the compiled one, which surfaced as
21
+ * `UNABLE_TO_VERIFY_LEAF_SIGNATURE` / `self-signed certificate in chain`.
22
+ */
23
+
24
+ import dns from "node:dns";
25
+ import net from "node:net";
26
+ import { existsSync, readFileSync } from "node:fs";
27
+ import { join } from "node:path";
28
+ import tls from "node:tls";
29
+ import type { Logger } from "../logging.js";
30
+
31
+ /** Variables that make a runtime dial a proxy instead of the target host. */
32
+ const PROXY_VARIABLES = [
33
+ "HTTPS_PROXY",
34
+ "https_proxy",
35
+ "HTTP_PROXY",
36
+ "http_proxy",
37
+ "ALL_PROXY",
38
+ "all_proxy",
39
+ "NO_PROXY",
40
+ "no_proxy",
41
+ ] as const;
42
+
43
+ /** The proxy that was present, if any. Only reported, never used. */
44
+ export function detectProxy(env: NodeJS.ProcessEnv = process.env): string | undefined {
45
+ for (const name of PROXY_VARIABLES) {
46
+ const value = env[name]?.trim();
47
+ if (value && !name.toLowerCase().startsWith("no_")) return value;
48
+ }
49
+ return undefined;
50
+ }
51
+
52
+ /** Strips every proxy variable so nothing can route through one. */
53
+ export function dropProxyVariables(
54
+ env: NodeJS.ProcessEnv = process.env,
55
+ ): string | undefined {
56
+ const found = detectProxy(env);
57
+ for (const name of PROXY_VARIABLES) delete env[name];
58
+ return found;
59
+ }
60
+
61
+ /**
62
+ * Pins DNS and socket selection to IPv4. Returns whether the resolver order was
63
+ * set; both calls are optional APIs and a missing one is not an error.
64
+ */
65
+ export function forceIpv4(): boolean {
66
+ let applied = false;
67
+ try {
68
+ dns.setDefaultResultOrder("ipv4first");
69
+ applied = true;
70
+ } catch {
71
+ // Old runtime: happy-eyeballs below still limits the damage.
72
+ }
73
+ try {
74
+ net.setDefaultAutoSelectFamily(false);
75
+ } catch {
76
+ // Not available: the resolver order is the only lever here.
77
+ }
78
+ return applied;
79
+ }
80
+
81
+ /** Files that may carry a usable CA bundle, most explicit first. */
82
+ function certificateCandidates(env: NodeJS.ProcessEnv): string[] {
83
+ const found: string[] = [];
84
+ for (const name of ["SSL_CERT_FILE", "CURL_CA_BUNDLE", "NODE_EXTRA_CA_CERTS"]) {
85
+ const value = env[name]?.trim();
86
+ if (value) found.push(value);
87
+ }
88
+ const prefix = env.PREFIX?.trim();
89
+ if (prefix) found.push(join(prefix, "etc/tls/cert.pem"));
90
+ found.push("/data/data/com.termux/files/usr/etc/tls/cert.pem");
91
+ return [...new Set(found)];
92
+ }
93
+
94
+ /**
95
+ * Adds Termux's CA bundle to Node's default trust store.
96
+ *
97
+ * The bundle is appended to the compiled roots rather than replacing them, so a
98
+ * partial Termux install still validates public hosts. Returns the path loaded,
99
+ * or undefined when nothing readable was found.
100
+ */
101
+ export function loadTermuxCertificates(
102
+ env: NodeJS.ProcessEnv = process.env,
103
+ ): string | undefined {
104
+ if (typeof tls.setDefaultCACertificates !== "function") return undefined;
105
+ let builtIn: string[] = [];
106
+ try {
107
+ builtIn = tls.getCACertificates("default");
108
+ } catch {
109
+ builtIn = [];
110
+ }
111
+ for (const path of certificateCandidates(env)) {
112
+ if (!existsSync(path)) continue;
113
+ let text: string;
114
+ try {
115
+ text = readFileSync(path, "utf8");
116
+ } catch {
117
+ continue;
118
+ }
119
+ const certificates = text.match(
120
+ /-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g,
121
+ );
122
+ if (!certificates || certificates.length === 0) continue;
123
+ try {
124
+ tls.setDefaultCACertificates([...builtIn, ...certificates]);
125
+ } catch {
126
+ continue;
127
+ }
128
+ return path;
129
+ }
130
+ return undefined;
131
+ }
132
+
133
+ /**
134
+ * Installs the direct network policy for this process. Runs before the first
135
+ * catalog request so the provider registers models instead of disappearing.
136
+ */
137
+ export function applyDirectNetwork(
138
+ log: Logger,
139
+ env: NodeJS.ProcessEnv = process.env,
140
+ ): { ipv4: boolean; ca?: string } {
141
+ const dropped = dropProxyVariables(env);
142
+ const ipv4 = forceIpv4();
143
+ const ca = loadTermuxCertificates(env);
144
+ if (dropped) {
145
+ log.warn("free-pi dropped a proxy from the environment; requests go direct", {
146
+ proxy: dropped,
147
+ });
148
+ }
149
+ log.info("free-pi network policy applied", {
150
+ ipv4: ipv4 ? "forced" : "default",
151
+ ca: ca ?? "builtin",
152
+ });
153
+ return { ipv4, ...(ca ? { ca } : {}) };
154
+ }
package/src/plugin.ts CHANGED
@@ -43,7 +43,7 @@ import type { Deps } from "./deps.js";
43
43
  import type { ModelMap } from "./types.js";
44
44
  import { registerIntegration } from "./integration/setup.js";
45
45
  import { createLogger } from "./logging.js";
46
- import { applyEnvironmentProxy } from "./network/proxy.js";
46
+ import { applyDirectNetwork } from "./network/direct.js";
47
47
  import { subscribeEvents } from "./session/events.js";
48
48
  import { registerSessionHooks } from "./session/hooks.js";
49
49
  import { cancelAllFinalizeTimers } from "./session/track.js";
@@ -69,10 +69,10 @@ function activeCredentialResolver(ctx: Plugin.Context) {
69
69
 
70
70
  async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
71
71
  const log = createLogger("free-pi");
72
- // A VPN or corporate setup may only allow traffic through a local proxy.
73
- // Enable it before the first catalog request so the provider registers models
74
- // instead of disappearing from the picker.
75
- applyEnvironmentProxy(log);
72
+ // Go direct before the first catalog request: no proxy, IPv4 only, and the
73
+ // Termux trust store. A proxy inherited from the environment is the failure
74
+ // mode that left the picker with zero models and `ModelUnavailableError`.
75
+ applyDirectNetwork(log);
76
76
  const state = createRuntimeState();
77
77
  const includeDefense = ctx.options?.includeDefense !== false;
78
78
 
@@ -1,19 +0,0 @@
1
- /**
2
- * Honors the proxy a VPN or corporate network exports in the environment.
3
- *
4
- * The free-pi CLI reads `*_proxy`/`all_proxy` and routes its requests through
5
- * an agent, so it keeps working when the network only allows traffic through a
6
- * local proxy. Node's `fetch` ignores those variables unless the process opts
7
- * in, which left the plugin unable to fetch the catalog, quota, ads or replay a
8
- * request while the CLI worked. `http.setGlobalProxyFromEnv()` (Node 24.5+)
9
- * turns the environment proxy on for every request of this process, including
10
- * `fetch`; when the runtime is older the plugin keeps going direct and says so.
11
- */
12
- import type { Logger } from "../logging.js";
13
- /** First proxy URL exported in the environment, or undefined. */
14
- export declare function proxyFromEnvironment(env?: NodeJS.ProcessEnv): string | undefined;
15
- /**
16
- * Enables the environment proxy for this process when one is configured.
17
- * Returns whether the plugin will use it.
18
- */
19
- export declare function applyEnvironmentProxy(log: Logger, env?: NodeJS.ProcessEnv): boolean;
@@ -1,118 +0,0 @@
1
- /**
2
- * Honors the proxy a VPN or corporate network exports in the environment.
3
- *
4
- * The free-pi CLI reads `*_proxy`/`all_proxy` and routes its requests through
5
- * an agent, so it keeps working when the network only allows traffic through a
6
- * local proxy. Node's `fetch` ignores those variables unless the process opts
7
- * in, which left the plugin unable to fetch the catalog, quota, ads or replay a
8
- * request while the CLI worked. `http.setGlobalProxyFromEnv()` (Node 24.5+)
9
- * turns the environment proxy on for every request of this process, including
10
- * `fetch`; when the runtime is older the plugin keeps going direct and says so.
11
- */
12
- import http from "node:http";
13
- const DIRECT_VARIABLES = [
14
- "HTTPS_PROXY",
15
- "https_proxy",
16
- "HTTP_PROXY",
17
- "http_proxy",
18
- ];
19
- const ALL_VARIABLES = ["ALL_PROXY", "all_proxy"];
20
- const PROXY_VARIABLES = [...DIRECT_VARIABLES, ...ALL_VARIABLES];
21
- /** First proxy URL exported in the environment, or undefined. */
22
- export function proxyFromEnvironment(env = process.env) {
23
- for (const name of PROXY_VARIABLES) {
24
- const value = env[name]?.trim();
25
- if (value)
26
- return value;
27
- }
28
- return undefined;
29
- }
30
- function firstValue(env, names) {
31
- for (const name of names) {
32
- const value = env[name]?.trim();
33
- if (value)
34
- return { name, value };
35
- }
36
- return undefined;
37
- }
38
- /** Proxy URL without credentials, safe for the log. */
39
- function describeProxy(value) {
40
- try {
41
- const url = new URL(value);
42
- const port = url.port ? `:${url.port}` : "";
43
- return `${url.protocol}//${url.hostname}${port}`;
44
- }
45
- catch {
46
- return "configured";
47
- }
48
- }
49
- /** HTTP(S) proxies only: Node's env support cannot dial a SOCKS URL. */
50
- function hasSupportedScheme(value) {
51
- try {
52
- const url = new URL(value);
53
- return url.protocol === "http:" || url.protocol === "https:";
54
- }
55
- catch {
56
- return false;
57
- }
58
- }
59
- /**
60
- * Node reads `HTTPS_PROXY`/`HTTP_PROXY` and ignores `ALL_PROXY`, which is the
61
- * generic name many VPN clients export. Copy it into the protocol-specific
62
- * variables so a proxy-only network still works.
63
- */
64
- function applyAllProxyFallback(env) {
65
- const all = firstValue(env, ALL_VARIABLES);
66
- if (!all || !hasSupportedScheme(all.value))
67
- return;
68
- for (const [specific, name] of [
69
- ["HTTPS_PROXY", "https_proxy"],
70
- ["HTTP_PROXY", "http_proxy"],
71
- ]) {
72
- if (!env[specific]?.trim() && !env[name]?.trim()) {
73
- env[specific] = all.value;
74
- }
75
- }
76
- }
77
- function proxySetter() {
78
- const candidate = http
79
- .setGlobalProxyFromEnv;
80
- return typeof candidate === "function"
81
- ? candidate
82
- : undefined;
83
- }
84
- /**
85
- * Enables the environment proxy for this process when one is configured.
86
- * Returns whether the plugin will use it.
87
- */
88
- export function applyEnvironmentProxy(log, env = process.env) {
89
- const proxy = proxyFromEnvironment(env);
90
- if (!proxy)
91
- return false;
92
- if (!hasSupportedScheme(proxy)) {
93
- log.warn("free-pi found a proxy in the environment that this runtime cannot use (only http/https proxies are supported); requests go out directly", { proxy: describeProxy(proxy) });
94
- return false;
95
- }
96
- // Normalize ALL_PROXY first: it stays useful even when this runtime cannot
97
- // enable the proxy, because a restart with NODE_USE_ENV_PROXY=1 reads it.
98
- applyAllProxyFallback(env);
99
- const setter = proxySetter();
100
- if (!setter) {
101
- log.warn("free-pi found a proxy in the environment but this Node runtime cannot apply it; start OpenCode with NODE_USE_ENV_PROXY=1 or use Node 24.5+ so free-pi requests follow the proxy", { node: process.version, proxy: describeProxy(proxy) });
102
- return false;
103
- }
104
- try {
105
- setter();
106
- log.info("free-pi requests follow the proxy configured in the environment", {
107
- proxy: describeProxy(proxy),
108
- });
109
- return true;
110
- }
111
- catch (error) {
112
- log.warn("free-pi could not enable the environment proxy", {
113
- proxy: describeProxy(proxy),
114
- reason: error instanceof Error ? error.message : String(error),
115
- });
116
- return false;
117
- }
118
- }
@@ -1,137 +0,0 @@
1
- /**
2
- * Honors the proxy a VPN or corporate network exports in the environment.
3
- *
4
- * The free-pi CLI reads `*_proxy`/`all_proxy` and routes its requests through
5
- * an agent, so it keeps working when the network only allows traffic through a
6
- * local proxy. Node's `fetch` ignores those variables unless the process opts
7
- * in, which left the plugin unable to fetch the catalog, quota, ads or replay a
8
- * request while the CLI worked. `http.setGlobalProxyFromEnv()` (Node 24.5+)
9
- * turns the environment proxy on for every request of this process, including
10
- * `fetch`; when the runtime is older the plugin keeps going direct and says so.
11
- */
12
-
13
- import http from "node:http";
14
- import type { Logger } from "../logging.js";
15
-
16
- const DIRECT_VARIABLES = [
17
- "HTTPS_PROXY",
18
- "https_proxy",
19
- "HTTP_PROXY",
20
- "http_proxy",
21
- ] as const;
22
- const ALL_VARIABLES = ["ALL_PROXY", "all_proxy"] as const;
23
- const PROXY_VARIABLES = [...DIRECT_VARIABLES, ...ALL_VARIABLES] as const;
24
-
25
- /** First proxy URL exported in the environment, or undefined. */
26
- export function proxyFromEnvironment(
27
- env: NodeJS.ProcessEnv = process.env,
28
- ): string | undefined {
29
- for (const name of PROXY_VARIABLES) {
30
- const value = env[name]?.trim();
31
- if (value) return value;
32
- }
33
- return undefined;
34
- }
35
-
36
- function firstValue(
37
- env: NodeJS.ProcessEnv,
38
- names: readonly string[],
39
- ): { name: string; value: string } | undefined {
40
- for (const name of names) {
41
- const value = env[name]?.trim();
42
- if (value) return { name, value };
43
- }
44
- return undefined;
45
- }
46
-
47
- /** Proxy URL without credentials, safe for the log. */
48
- function describeProxy(value: string): string {
49
- try {
50
- const url = new URL(value);
51
- const port = url.port ? `:${url.port}` : "";
52
- return `${url.protocol}//${url.hostname}${port}`;
53
- } catch {
54
- return "configured";
55
- }
56
- }
57
-
58
- /** HTTP(S) proxies only: Node's env support cannot dial a SOCKS URL. */
59
- function hasSupportedScheme(value: string): boolean {
60
- try {
61
- const url = new URL(value);
62
- return url.protocol === "http:" || url.protocol === "https:";
63
- } catch {
64
- return false;
65
- }
66
- }
67
-
68
- /**
69
- * Node reads `HTTPS_PROXY`/`HTTP_PROXY` and ignores `ALL_PROXY`, which is the
70
- * generic name many VPN clients export. Copy it into the protocol-specific
71
- * variables so a proxy-only network still works.
72
- */
73
- function applyAllProxyFallback(env: NodeJS.ProcessEnv): void {
74
- const all = firstValue(env, ALL_VARIABLES);
75
- if (!all || !hasSupportedScheme(all.value)) return;
76
- for (const [specific, name] of [
77
- ["HTTPS_PROXY", "https_proxy"],
78
- ["HTTP_PROXY", "http_proxy"],
79
- ] as const) {
80
- if (!env[specific]?.trim() && !env[name]?.trim()) {
81
- env[specific] = all.value;
82
- }
83
- }
84
- }
85
-
86
- type ProxySetter = () => unknown;
87
-
88
- function proxySetter(): ProxySetter | undefined {
89
- const candidate = (http as { setGlobalProxyFromEnv?: unknown })
90
- .setGlobalProxyFromEnv;
91
- return typeof candidate === "function"
92
- ? (candidate as ProxySetter)
93
- : undefined;
94
- }
95
-
96
- /**
97
- * Enables the environment proxy for this process when one is configured.
98
- * Returns whether the plugin will use it.
99
- */
100
- export function applyEnvironmentProxy(
101
- log: Logger,
102
- env: NodeJS.ProcessEnv = process.env,
103
- ): boolean {
104
- const proxy = proxyFromEnvironment(env);
105
- if (!proxy) return false;
106
- if (!hasSupportedScheme(proxy)) {
107
- log.warn(
108
- "free-pi found a proxy in the environment that this runtime cannot use (only http/https proxies are supported); requests go out directly",
109
- { proxy: describeProxy(proxy) },
110
- );
111
- return false;
112
- }
113
- // Normalize ALL_PROXY first: it stays useful even when this runtime cannot
114
- // enable the proxy, because a restart with NODE_USE_ENV_PROXY=1 reads it.
115
- applyAllProxyFallback(env);
116
- const setter = proxySetter();
117
- if (!setter) {
118
- log.warn(
119
- "free-pi found a proxy in the environment but this Node runtime cannot apply it; start OpenCode with NODE_USE_ENV_PROXY=1 or use Node 24.5+ so free-pi requests follow the proxy",
120
- { node: process.version, proxy: describeProxy(proxy) },
121
- );
122
- return false;
123
- }
124
- try {
125
- setter();
126
- log.info("free-pi requests follow the proxy configured in the environment", {
127
- proxy: describeProxy(proxy),
128
- });
129
- return true;
130
- } catch (error) {
131
- log.warn("free-pi could not enable the environment proxy", {
132
- proxy: describeProxy(proxy),
133
- reason: error instanceof Error ? error.message : String(error),
134
- });
135
- return false;
136
- }
137
- }