@eduardo191labs/opencode-free-pi 0.3.21 → 0.4.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 +64 -0
- package/dist/plugin.js +36 -5
- package/dist/session/hooks.d.ts +3 -1
- package/dist/session/hooks.js +28 -1
- package/dist/state.d.ts +1 -0
- package/dist/state.js +1 -0
- package/dist/tools/account.d.ts +10 -0
- package/dist/tools/account.js +103 -0
- package/dist/tools/api.d.ts +54 -0
- package/dist/tools/api.js +120 -0
- package/dist/tools/fusion.d.ts +45 -0
- package/dist/tools/fusion.js +162 -0
- package/dist/tools/image-generate.d.ts +13 -0
- package/dist/tools/image-generate.js +143 -0
- package/dist/tools/usage.d.ts +12 -0
- package/dist/tools/usage.js +125 -0
- package/dist/tools/vision-queue.d.ts +19 -0
- package/dist/tools/vision-queue.js +149 -0
- package/dist/tools/vision.js +150 -53
- package/dist/tools/web.d.ts +12 -0
- package/dist/tools/web.js +165 -0
- package/dist/types.d.ts +4 -0
- package/package.json +2 -2
- package/src/plugin.ts +50 -5
- package/src/session/hooks.ts +39 -0
- package/src/state.ts +2 -0
- package/src/tools/account.ts +135 -0
- package/src/tools/api.ts +178 -0
- package/src/tools/fusion.ts +221 -0
- package/src/tools/image-generate.ts +195 -0
- package/src/tools/usage.ts +163 -0
- package/src/tools/vision-queue.ts +161 -0
- package/src/tools/vision.ts +180 -56
- package/src/tools/web.ts +212 -0
- package/src/types.ts +1 -0
package/README.md
CHANGED
|
@@ -135,6 +135,10 @@ herramienta `look_at_image` con una ruta y una pregunta concreta. El plugin:
|
|
|
135
135
|
mejor calidad JPEG que quepan en el límite.
|
|
136
136
|
- Envía la imagen a `/tools/vision` y devuelve la respuesta del modelo de
|
|
137
137
|
visión como texto.
|
|
138
|
+
- Serializa las preguntas entre sesiones y procesos de OpenCode mediante un
|
|
139
|
+
bloqueo en la caché del plugin. Si el servidor responde `rate_limited` porque
|
|
140
|
+
otra sesión o el CLI está consultando una imagen, reintenta automáticamente
|
|
141
|
+
respetando `Retry-After` en vez de hacer fallar el turno.
|
|
138
142
|
|
|
139
143
|
Cada llamada consume parte del allowance diario del usuario, como en el CLI.
|
|
140
144
|
La herramienta solo se ejecuta en sesiones de free-pi; en otros proveedores
|
|
@@ -142,6 +146,66 @@ responde que no está disponible. Si el modelo intenta leer una imagen con
|
|
|
142
146
|
`read`, el plugin sustituye el base64 por un aviso que le indica usar
|
|
143
147
|
`look_at_image` con la misma ruta.
|
|
144
148
|
|
|
149
|
+
## Herramientas free-pi
|
|
150
|
+
|
|
151
|
+
El plugin registra las mismas herramientas de servidor que el CLI. Todas
|
|
152
|
+
comprueban que la sesión sea de free-pi antes de gastar cuota; en cualquier otro
|
|
153
|
+
proveedor responden que no están disponibles.
|
|
154
|
+
|
|
155
|
+
| Herramienta | Qué hace |
|
|
156
|
+
| ----------------------- | ------------------------------------------------------------------------ |
|
|
157
|
+
| `look_at_image` | Pregunta a un modelo de visión por una imagen del proyecto. |
|
|
158
|
+
| `generate_image` | Genera una imagen desde un prompt y la guarda en `images/`. |
|
|
159
|
+
| `web_search` | Busca en la web y devuelve título, URL, fecha y texto de cada resultado. |
|
|
160
|
+
| `docs_lookup` | Consulta documentación actual de una librería o framework. |
|
|
161
|
+
| `free_pi_usage` | Muestra cuota restante, créditos, tokens y tier de la cuenta. |
|
|
162
|
+
| `free_pi_buy_credits` | Abre la página de compra de créditos y muestra la URL. |
|
|
163
|
+
| `free_pi_docs` | Devuelve la guía integrada de free-pi sin hacer red. |
|
|
164
|
+
| `fusion_plan` | Fusion: pide al modelo planificador un plan antes de editar archivos. |
|
|
165
|
+
|
|
166
|
+
`generate_image` acepta `prompt`, `aspect_ratio` (`1:1`, `16:9`, `9:16`, `4:3`,
|
|
167
|
+
`3:2`) y un `name` opcional para el archivo. Rechaza tipos que no sean PNG,
|
|
168
|
+
JPEG o WebP y limita el archivo a 8 MB, igual que el CLI. Los nombres se
|
|
169
|
+
normalizan a `images/<slug>-<6 hex>.<ext>` para que una respuesta del servidor
|
|
170
|
+
no pueda escribir fuera de `images/`.
|
|
171
|
+
|
|
172
|
+
`web_search` y `docs_lookup` usan `/tools/web-search` y `/tools/docs`. Los
|
|
173
|
+
códigos `daily_cap`, `rolling_cap`, `rate_limited`, `not_found`,
|
|
174
|
+
`not_configured`, `upstream_error` y los de invitado se traducen al mismo texto
|
|
175
|
+
que el CLI, para que el agente sepa cuándo no debe reintentar. Igual que
|
|
176
|
+
`look_at_image`, cada llamada consume allowance.
|
|
177
|
+
|
|
178
|
+
`free_pi_usage` consulta `/me/stats` y resume el tier, los créditos restantes
|
|
179
|
+
con su hora de recarga en ET, los créditos premium o de referidos y los tokens
|
|
180
|
+
de hoy y de por vida. Si el servidor asigna el carril lento, incluye el aviso
|
|
181
|
+
del CLI.
|
|
182
|
+
|
|
183
|
+
`free_pi_buy_credits` consulta `/me` y abre `buy_url` en el navegador cuando
|
|
184
|
+
hay uno; en SSH o sesiones headless solo imprime la URL.
|
|
185
|
+
|
|
186
|
+
### Fusion
|
|
187
|
+
|
|
188
|
+
Cuando el catálogo incluye `deepseek-v4-flash`, el plugin añade el modelo
|
|
189
|
+
virtual **🧬 Fusion** al selector. Fusion usa Flash para construir y pide el
|
|
190
|
+
plan a `deepseek-v4-pro` cuando la cuenta tiene créditos premium (o a Flash como
|
|
191
|
+
respaldo), igual que el CLI:
|
|
192
|
+
|
|
193
|
+
1. El ejecutor explora el proyecto con herramientas de solo lectura.
|
|
194
|
+
2. Llama a `fusion_plan` con lo que encontró y lo que hace falta.
|
|
195
|
+
3. El plugin pide el plan al planificador mediante la generación sin estado
|
|
196
|
+
del SDK V2 y devuelve el texto al ejecutor.
|
|
197
|
+
4. El ejecutor registra el plan con el gestor de todos nativo y lo implementa.
|
|
198
|
+
|
|
199
|
+
La guía de Fusion se inyecta en el system prompt solo para las sesiones que
|
|
200
|
+
eligieron ese modelo, y el modelo virtual se resuelve al ejecutor antes de
|
|
201
|
+
enviar la petición. Si la generación sin estado no está disponible, la
|
|
202
|
+
herramienta responde con instrucciones para que el propio ejecutor escriba el
|
|
203
|
+
plan, sin bloquear el turno.
|
|
204
|
+
|
|
205
|
+
Las herramientas `todo` y `ask_user` del CLI no se duplican: OpenCode ya tiene
|
|
206
|
+
un gestor de todos nativo y su propia herramienta de preguntas al usuario, con
|
|
207
|
+
mejor integración en la TUI.
|
|
208
|
+
|
|
145
209
|
## Cabeceras enviadas
|
|
146
210
|
|
|
147
211
|
El plugin replica las cabeceras del plugin V1 de free-pi:
|
package/dist/plugin.js
CHANGED
|
@@ -14,7 +14,12 @@ import { subscribeEvents } from "./session/events.js";
|
|
|
14
14
|
import { registerSessionHooks } from "./session/hooks.js";
|
|
15
15
|
import { cancelAllFinalizeTimers } from "./session/track.js";
|
|
16
16
|
import { createRuntimeState } from "./state.js";
|
|
17
|
+
import { registerAccountTools } from "./tools/account.js";
|
|
18
|
+
import { addFusionModel, FUSION_PLANNER_ID, premiumPlannerAvailable, registerFusionTool, resolveFusionIds, } from "./tools/fusion.js";
|
|
19
|
+
import { registerGenerateImageTool } from "./tools/image-generate.js";
|
|
20
|
+
import { registerUsageTool } from "./tools/usage.js";
|
|
17
21
|
import { registerVisionTool } from "./tools/vision.js";
|
|
22
|
+
import { registerWebTools } from "./tools/web.js";
|
|
18
23
|
import { settle } from "./utils/async.js";
|
|
19
24
|
function activeCredentialResolver(ctx) {
|
|
20
25
|
return async () => {
|
|
@@ -58,6 +63,15 @@ async function setup(ctx) {
|
|
|
58
63
|
const buildOptions = { compact100: state.costExperimentArm === "compact100" };
|
|
59
64
|
const mainModels = buildModels(main, candidates, buildOptions);
|
|
60
65
|
const defenseModels = buildModels(defense, candidates, buildOptions);
|
|
66
|
+
const fusionIds = resolveFusionIds(Object.keys(mainModels), catalog?.default_model, {
|
|
67
|
+
server: catalog?.fusion,
|
|
68
|
+
hasPremium: !catalog?.fusion && mainModels[FUSION_PLANNER_ID]
|
|
69
|
+
? await premiumPlannerAvailable(deps)
|
|
70
|
+
: undefined,
|
|
71
|
+
});
|
|
72
|
+
if (fusionIds && addFusionModel(mainModels, fusionIds)) {
|
|
73
|
+
log.info("Registered the Fusion model", fusionIds);
|
|
74
|
+
}
|
|
61
75
|
for (const [id, model] of Object.entries(mainModels)) {
|
|
62
76
|
state.outputLimits.set(`${PROVIDER_ID}/${id}`, model.limit.output);
|
|
63
77
|
}
|
|
@@ -84,12 +98,29 @@ async function setup(ctx) {
|
|
|
84
98
|
if (preferred)
|
|
85
99
|
editor.default.set(PROVIDER_ID, preferred);
|
|
86
100
|
});
|
|
87
|
-
const registrations = await registerSessionHooks(ctx, deps
|
|
88
|
-
|
|
89
|
-
|
|
101
|
+
const registrations = await registerSessionHooks(ctx, deps, {
|
|
102
|
+
fusionExecutorID: fusionIds?.executor,
|
|
103
|
+
});
|
|
104
|
+
const tools = [
|
|
105
|
+
{ name: "look_at_image", register: () => registerVisionTool(ctx, deps) },
|
|
106
|
+
{ name: "free_pi_usage", register: () => registerUsageTool(ctx, deps) },
|
|
107
|
+
{ name: "account", register: () => registerAccountTools(ctx, deps) },
|
|
108
|
+
{ name: "web", register: () => registerWebTools(ctx, deps) },
|
|
109
|
+
{ name: "generate_image", register: () => registerGenerateImageTool(ctx, deps) },
|
|
110
|
+
];
|
|
111
|
+
if (fusionIds) {
|
|
112
|
+
tools.push({
|
|
113
|
+
name: "fusion",
|
|
114
|
+
register: () => registerFusionTool(ctx, deps, fusionIds),
|
|
115
|
+
});
|
|
90
116
|
}
|
|
91
|
-
|
|
92
|
-
|
|
117
|
+
for (const tool of tools) {
|
|
118
|
+
try {
|
|
119
|
+
registrations.push(await tool.register());
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
log.warn(`Could not register the ${tool.name} tools`, error);
|
|
123
|
+
}
|
|
93
124
|
}
|
|
94
125
|
const abort = new AbortController();
|
|
95
126
|
const eventTask = subscribeEvents(ctx, deps, abort.signal);
|
package/dist/session/hooks.d.ts
CHANGED
|
@@ -4,5 +4,7 @@ import type { Deps } from "../deps.js";
|
|
|
4
4
|
type Registration = {
|
|
5
5
|
dispose: () => Promise<void>;
|
|
6
6
|
};
|
|
7
|
-
export declare function registerSessionHooks(ctx: Plugin.Context, deps: Deps
|
|
7
|
+
export declare function registerSessionHooks(ctx: Plugin.Context, deps: Deps, options?: {
|
|
8
|
+
readonly fusionExecutorID?: string;
|
|
9
|
+
}): Promise<Registration[]>;
|
|
8
10
|
export {};
|
package/dist/session/hooks.js
CHANGED
|
@@ -14,6 +14,7 @@ import { rememberFreePiSession } from "./track.js";
|
|
|
14
14
|
import { markWireSessionDirty, rotateWireSessionID, takeWireSessionDirty, wireSessionID, } from "./wire.js";
|
|
15
15
|
import { isFreePiSession, recordCompaction, recordToolEnd, recordToolStart, toolHeaders, } from "./tools.js";
|
|
16
16
|
import { rememberTrackedModel } from "./usage.js";
|
|
17
|
+
import { FUSION_GUIDELINE, FUSION_ID } from "../tools/fusion.js";
|
|
17
18
|
const PENDING_LIMIT = 400;
|
|
18
19
|
/** Each agent gets its own ad turn, so a subagent never reuses the parent's. */
|
|
19
20
|
function pendingKeyOf(sessionID, agent, kind) {
|
|
@@ -58,6 +59,16 @@ async function applyGeneration(deps, event, kind) {
|
|
|
58
59
|
event.system = system;
|
|
59
60
|
}
|
|
60
61
|
}
|
|
62
|
+
// The virtual Fusion model routes its turns to the executor; the guideline
|
|
63
|
+
// lives here so it is sent with the resolved provider request, not with the
|
|
64
|
+
// model picker's name.
|
|
65
|
+
if (kind === "primary" && deps.state.fusionSessions.has(event.sessionID)) {
|
|
66
|
+
const system = Array.isArray(event.system) ? event.system : [];
|
|
67
|
+
if (!system.some((part) => part?.type === "text" && part.text === FUSION_GUIDELINE)) {
|
|
68
|
+
system.push({ type: "text", text: FUSION_GUIDELINE });
|
|
69
|
+
event.system = system;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
61
72
|
const agent = event.agent;
|
|
62
73
|
const turn = await resolveAdTurn(deps, {
|
|
63
74
|
sessionID: event.sessionID,
|
|
@@ -286,9 +297,25 @@ async function hookForProviders(ctx, name, callback, registrations) {
|
|
|
286
297
|
}));
|
|
287
298
|
}
|
|
288
299
|
}
|
|
289
|
-
export async function registerSessionHooks(ctx, deps) {
|
|
300
|
+
export async function registerSessionHooks(ctx, deps, options = {}) {
|
|
290
301
|
const registrations = [];
|
|
291
302
|
const generation = (kind) => (event) => applyGeneration(deps, event, kind);
|
|
303
|
+
if (options.fusionExecutorID) {
|
|
304
|
+
await hookForProviders(ctx, "experimental.model.resolve", (event) => {
|
|
305
|
+
if (event.model?.providerID !== PROVIDER_ID)
|
|
306
|
+
return;
|
|
307
|
+
if (event.model?.id !== FUSION_ID) {
|
|
308
|
+
deps.state.fusionSessions.delete(event.sessionID);
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
deps.state.fusionSessions.add(event.sessionID);
|
|
312
|
+
// The picker says Fusion; the wire request uses the executor model.
|
|
313
|
+
event.model = {
|
|
314
|
+
...event.model,
|
|
315
|
+
id: options.fusionExecutorID,
|
|
316
|
+
};
|
|
317
|
+
}, registrations);
|
|
318
|
+
}
|
|
292
319
|
await hookForProviders(ctx, "context", generation("primary"), registrations);
|
|
293
320
|
await hookForProviders(ctx, "compaction", generation("compaction"), registrations);
|
|
294
321
|
await hookForProviders(ctx, "generate", generation("generate"), registrations);
|
package/dist/state.d.ts
CHANGED
|
@@ -33,6 +33,7 @@ export type RuntimeState = {
|
|
|
33
33
|
sessionResetPromise?: Promise<SessionResetOutcome>;
|
|
34
34
|
lastSessionResetAt: number;
|
|
35
35
|
freePiSessions: Set<string>;
|
|
36
|
+
fusionSessions: Set<string>;
|
|
36
37
|
wireSessions: Map<string, string>;
|
|
37
38
|
replayBodies: Map<string, string>;
|
|
38
39
|
dirtySessions: Set<string>;
|
package/dist/state.js
CHANGED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Account helpers that mirror the provider CLI: `free_pi_buy_credits` and the
|
|
3
|
+
* built-in `free_pi_docs` guide.
|
|
4
|
+
*/
|
|
5
|
+
import type { Plugin } from "@opencode/plugin";
|
|
6
|
+
import type { Deps } from "../deps.js";
|
|
7
|
+
export declare const FREE_PI_DOCS = "# free-pi in OpenCode\n\nfree-pi is a free, ad-supported way to run coding models. You sign in with\nGitHub, and ads shown in the session pay for the inference. You never handle a\nmodel API key. The free daily allowance can change with supply and demand.\n\n## Checking usage and credits\n- `free_pi_usage` shows today's remaining allowance, purchased credits, token\n counts and your account tier.\n- `free_pi_buy_credits` opens the buy page. Purchased credits cover use beyond\n the free allowance.\n- The dashboard at https://freepi.ai/dashboard shows usage, credits and privacy.\n\n## Tools that spend the daily allowance\n- `look_at_image` asks a vision model about a PNG, JPEG or WebP inside the\n project. free-pi models are text-only, so they cannot see images otherwise.\n- `generate_image` draws one image from a prompt and saves it under `images/`.\n- `web_search` searches the web for current information.\n- `docs_lookup` looks up current library and framework documentation.\n- `free_pi_usage`, `free_pi_buy_credits` and `free_pi_docs` are read-only.\n\n## Agents and sessions\n- The Fusion agent gathers context, asks a planning model for a step-by-step\n plan, and then implements it. Fusion needs the planner model in the catalog;\n otherwise it falls back to the default free-pi model.\n- Subagents inherit the parent's free-pi allowance and count against the same\n daily budget.\n- A session's server slot is closed shortly after its last step. If another\n terminal is stuck, close that session before starting a new one.\n\n## Limits\n- One image question can run at a time; `look_at_image` queues and waits.\n- Usage limits (`daily_cap`, `rolling_cap`, concurrency) are terminal: the\n agent is told to stop and continue without the tool rather than retrying.\n";
|
|
8
|
+
export declare function registerAccountTools(ctx: Plugin.Context, deps: Deps): Promise<{
|
|
9
|
+
dispose: () => Promise<void>;
|
|
10
|
+
}>;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Account helpers that mirror the provider CLI: `free_pi_buy_credits` and the
|
|
3
|
+
* built-in `free_pi_docs` guide.
|
|
4
|
+
*/
|
|
5
|
+
import { browserAvailable, openBrowser } from "../utils/browser.js";
|
|
6
|
+
import { safeUrl } from "../utils/urls.js";
|
|
7
|
+
import { done, fail, freePiRequest, GATED_TEXT, isGatedSession, } from "./api.js";
|
|
8
|
+
const NO_INPUT = {
|
|
9
|
+
type: "object",
|
|
10
|
+
additionalProperties: false,
|
|
11
|
+
properties: {},
|
|
12
|
+
};
|
|
13
|
+
const BUY_NOT_AVAILABLE = "Buying credits is not available on this server yet.";
|
|
14
|
+
function buyPageText(url) {
|
|
15
|
+
return `Opening the buy page in your browser. If it did not open (for example over SSH), visit:
|
|
16
|
+
${url}
|
|
17
|
+
|
|
18
|
+
Packs: $5 = 50,000 credits, $10 = 100,000 credits. Card or USDC.`;
|
|
19
|
+
}
|
|
20
|
+
async function executeBuy(deps, context) {
|
|
21
|
+
if (!isGatedSession(deps, context.sessionID))
|
|
22
|
+
return fail(GATED_TEXT);
|
|
23
|
+
const result = await freePiRequest(deps, {
|
|
24
|
+
path: "/me",
|
|
25
|
+
timeoutMs: 5_000,
|
|
26
|
+
signal: context.signal,
|
|
27
|
+
audience: "model",
|
|
28
|
+
});
|
|
29
|
+
if (!result.ok)
|
|
30
|
+
return fail(result.text);
|
|
31
|
+
const url = safeUrl(result.data?.buy_url);
|
|
32
|
+
if (!url) {
|
|
33
|
+
return done(BUY_NOT_AVAILABLE, { available: false });
|
|
34
|
+
}
|
|
35
|
+
const opened = browserAvailable() ? await openBrowser(url) : false;
|
|
36
|
+
deps.log.info("free_pi_buy_credits opened the buy page", {
|
|
37
|
+
opened,
|
|
38
|
+
url,
|
|
39
|
+
});
|
|
40
|
+
return done(buyPageText(url), { buy_url: url, opened });
|
|
41
|
+
}
|
|
42
|
+
export const FREE_PI_DOCS = `# free-pi in OpenCode
|
|
43
|
+
|
|
44
|
+
free-pi is a free, ad-supported way to run coding models. You sign in with
|
|
45
|
+
GitHub, and ads shown in the session pay for the inference. You never handle a
|
|
46
|
+
model API key. The free daily allowance can change with supply and demand.
|
|
47
|
+
|
|
48
|
+
## Checking usage and credits
|
|
49
|
+
- \`free_pi_usage\` shows today's remaining allowance, purchased credits, token
|
|
50
|
+
counts and your account tier.
|
|
51
|
+
- \`free_pi_buy_credits\` opens the buy page. Purchased credits cover use beyond
|
|
52
|
+
the free allowance.
|
|
53
|
+
- The dashboard at https://freepi.ai/dashboard shows usage, credits and privacy.
|
|
54
|
+
|
|
55
|
+
## Tools that spend the daily allowance
|
|
56
|
+
- \`look_at_image\` asks a vision model about a PNG, JPEG or WebP inside the
|
|
57
|
+
project. free-pi models are text-only, so they cannot see images otherwise.
|
|
58
|
+
- \`generate_image\` draws one image from a prompt and saves it under \`images/\`.
|
|
59
|
+
- \`web_search\` searches the web for current information.
|
|
60
|
+
- \`docs_lookup\` looks up current library and framework documentation.
|
|
61
|
+
- \`free_pi_usage\`, \`free_pi_buy_credits\` and \`free_pi_docs\` are read-only.
|
|
62
|
+
|
|
63
|
+
## Agents and sessions
|
|
64
|
+
- The Fusion agent gathers context, asks a planning model for a step-by-step
|
|
65
|
+
plan, and then implements it. Fusion needs the planner model in the catalog;
|
|
66
|
+
otherwise it falls back to the default free-pi model.
|
|
67
|
+
- Subagents inherit the parent's free-pi allowance and count against the same
|
|
68
|
+
daily budget.
|
|
69
|
+
- A session's server slot is closed shortly after its last step. If another
|
|
70
|
+
terminal is stuck, close that session before starting a new one.
|
|
71
|
+
|
|
72
|
+
## Limits
|
|
73
|
+
- One image question can run at a time; \`look_at_image\` queues and waits.
|
|
74
|
+
- Usage limits (\`daily_cap\`, \`rolling_cap\`, concurrency) are terminal: the
|
|
75
|
+
agent is told to stop and continue without the tool rather than retrying.
|
|
76
|
+
`;
|
|
77
|
+
async function executeDocs(deps, context, raw) {
|
|
78
|
+
if (raw && typeof raw === "object" && Object.keys(raw).length > 0) {
|
|
79
|
+
return fail("free_pi_docs takes no arguments.");
|
|
80
|
+
}
|
|
81
|
+
if (!isGatedSession(deps, context.sessionID)) {
|
|
82
|
+
return fail(GATED_TEXT);
|
|
83
|
+
}
|
|
84
|
+
return done(FREE_PI_DOCS, { ok: true });
|
|
85
|
+
}
|
|
86
|
+
export async function registerAccountTools(ctx, deps) {
|
|
87
|
+
return ctx.tool.transform((editor) => {
|
|
88
|
+
editor.add({
|
|
89
|
+
name: "free_pi_buy_credits",
|
|
90
|
+
description: "Open the free-pi buy-credits page in the browser (and print the URL, for SSH sessions with no browser). Read-only against the server, takes no arguments.",
|
|
91
|
+
input: NO_INPUT,
|
|
92
|
+
options: { codemode: false },
|
|
93
|
+
execute: (_input, context) => executeBuy(deps, context),
|
|
94
|
+
});
|
|
95
|
+
editor.add({
|
|
96
|
+
name: "free_pi_docs",
|
|
97
|
+
description: "Return the built-in free-pi guide: what it is, how the free allowance, credits, ads and tools work. Read-only, takes no arguments, makes no network calls.",
|
|
98
|
+
input: NO_INPUT,
|
|
99
|
+
options: { codemode: false },
|
|
100
|
+
execute: (input, context) => executeDocs(deps, context, input),
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared plumbing for the free-pi server tools.
|
|
3
|
+
*
|
|
4
|
+
* The provider CLI spends the user's daily allowance through a small set of
|
|
5
|
+
* `/tools/*` and `/me*` endpoints. This module keeps the token handling,
|
|
6
|
+
* timeouts and error wording identical across those tools.
|
|
7
|
+
*/
|
|
8
|
+
import type { Deps } from "../deps.js";
|
|
9
|
+
export type ToolOutput = {
|
|
10
|
+
readonly content: ReadonlyArray<{
|
|
11
|
+
readonly type: "text";
|
|
12
|
+
readonly text: string;
|
|
13
|
+
}>;
|
|
14
|
+
readonly metadata: Record<string, unknown>;
|
|
15
|
+
};
|
|
16
|
+
export declare function done(text: string, metadata?: Record<string, unknown>): ToolOutput;
|
|
17
|
+
export declare function fail(text: string): ToolOutput;
|
|
18
|
+
export declare const GATED_TEXT = "This tool is only available in free-pi sessions.";
|
|
19
|
+
/** Same wording as the provider CLI when the integration is not connected. */
|
|
20
|
+
export declare const NO_TOKEN_TEXT = "This tool needs a free-pi sign-in. Do not retry; tell the user to connect the free-pi integration, and continue without this tool.";
|
|
21
|
+
export declare function isGatedSession(deps: Deps, sessionID: string | undefined): boolean;
|
|
22
|
+
export declare function friendlyThrown(error: unknown): string;
|
|
23
|
+
export declare function friendlyStatus(status: number, message?: unknown, audience?: "model" | "user"): string;
|
|
24
|
+
export type ApiResult = {
|
|
25
|
+
readonly ok: true;
|
|
26
|
+
readonly data: any;
|
|
27
|
+
} | {
|
|
28
|
+
readonly ok: false;
|
|
29
|
+
readonly status: number;
|
|
30
|
+
readonly code: string;
|
|
31
|
+
readonly text: string;
|
|
32
|
+
};
|
|
33
|
+
type RequestOptions = {
|
|
34
|
+
readonly path: string;
|
|
35
|
+
readonly method?: "GET" | "POST";
|
|
36
|
+
readonly body?: unknown;
|
|
37
|
+
readonly timeoutMs?: number;
|
|
38
|
+
readonly signal?: AbortSignal;
|
|
39
|
+
/** Passed to `friendlyStatus` for non-mapped HTTP failures. */
|
|
40
|
+
readonly audience?: "model" | "user";
|
|
41
|
+
/** Prefix for timeout and transport errors, e.g. "The vision request". */
|
|
42
|
+
readonly label?: string;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Calls a free-pi endpoint with the current credential and never throws.
|
|
46
|
+
* Business error codes are returned intact so each tool can map them to the
|
|
47
|
+
* exact wording the provider CLI uses.
|
|
48
|
+
*/
|
|
49
|
+
export declare function freePiRequest(deps: Deps, options: RequestOptions): Promise<ApiResult>;
|
|
50
|
+
/** Maps a business error code to the CLI's wording, or keeps the HTTP text. */
|
|
51
|
+
export declare function mappedText(table: Record<string, string>, result: Extract<ApiResult, {
|
|
52
|
+
ok: false;
|
|
53
|
+
}>, library?: string): string;
|
|
54
|
+
export {};
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared plumbing for the free-pi server tools.
|
|
3
|
+
*
|
|
4
|
+
* The provider CLI spends the user's daily allowance through a small set of
|
|
5
|
+
* `/tools/*` and `/me*` endpoints. This module keeps the token handling,
|
|
6
|
+
* timeouts and error wording identical across those tools.
|
|
7
|
+
*/
|
|
8
|
+
import { resolveToken } from "../auth/token.js";
|
|
9
|
+
import { isFreePiSession } from "../session/tools.js";
|
|
10
|
+
import { resolveBaseUrl } from "../utils/urls.js";
|
|
11
|
+
export function done(text, metadata = {}) {
|
|
12
|
+
return { content: [{ type: "text", text }], metadata };
|
|
13
|
+
}
|
|
14
|
+
export function fail(text) {
|
|
15
|
+
return done(text, { ok: false });
|
|
16
|
+
}
|
|
17
|
+
export const GATED_TEXT = "This tool is only available in free-pi sessions.";
|
|
18
|
+
/** Same wording as the provider CLI when the integration is not connected. */
|
|
19
|
+
export const NO_TOKEN_TEXT = "This tool needs a free-pi sign-in. Do not retry; tell the user to connect the free-pi integration, and continue without this tool.";
|
|
20
|
+
export function isGatedSession(deps, sessionID) {
|
|
21
|
+
return typeof sessionID === "string" && isFreePiSession(deps, sessionID);
|
|
22
|
+
}
|
|
23
|
+
export function friendlyThrown(error) {
|
|
24
|
+
const name = error instanceof Error ? error.name : "";
|
|
25
|
+
if (name === "TimeoutError")
|
|
26
|
+
return "free-pi took too long to answer. Try again.";
|
|
27
|
+
if (name === "AbortError")
|
|
28
|
+
return "Cancelled.";
|
|
29
|
+
if (name === "SyntaxError")
|
|
30
|
+
return "free-pi sent an unexpected reply. Try again.";
|
|
31
|
+
return "Couldn't reach free-pi - check your connection.";
|
|
32
|
+
}
|
|
33
|
+
export function friendlyStatus(status, message, audience = "model") {
|
|
34
|
+
if (status === 401) {
|
|
35
|
+
return audience === "model"
|
|
36
|
+
? "The user's free-pi sign-in has expired; tell them to reconnect the free-pi integration."
|
|
37
|
+
: "Your free-pi sign-in has expired. Reconnect the free-pi integration.";
|
|
38
|
+
}
|
|
39
|
+
if (typeof message === "string" && message.trim())
|
|
40
|
+
return message.trim();
|
|
41
|
+
if (status >= 500) {
|
|
42
|
+
return `free-pi is having trouble right now (HTTP ${status}). Try again in a minute.`;
|
|
43
|
+
}
|
|
44
|
+
return `free-pi could not complete the request (HTTP ${status}).`;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Calls a free-pi endpoint with the current credential and never throws.
|
|
48
|
+
* Business error codes are returned intact so each tool can map them to the
|
|
49
|
+
* exact wording the provider CLI uses.
|
|
50
|
+
*/
|
|
51
|
+
export async function freePiRequest(deps, options) {
|
|
52
|
+
const token = await resolveToken(deps);
|
|
53
|
+
if (!token) {
|
|
54
|
+
return { ok: false, status: 401, code: "no_token", text: NO_TOKEN_TEXT };
|
|
55
|
+
}
|
|
56
|
+
const timeout = AbortSignal.timeout(options.timeoutMs ?? 20_000);
|
|
57
|
+
const signal = options.signal
|
|
58
|
+
? AbortSignal.any([options.signal, timeout])
|
|
59
|
+
: timeout;
|
|
60
|
+
let response;
|
|
61
|
+
try {
|
|
62
|
+
response = await fetch(`${resolveBaseUrl()}${options.path}`, {
|
|
63
|
+
method: options.method ?? "GET",
|
|
64
|
+
headers: {
|
|
65
|
+
authorization: `Bearer ${token}`,
|
|
66
|
+
...(options.body !== undefined
|
|
67
|
+
? { "content-type": "application/json" }
|
|
68
|
+
: {}),
|
|
69
|
+
},
|
|
70
|
+
...(options.body !== undefined
|
|
71
|
+
? { body: JSON.stringify(options.body) }
|
|
72
|
+
: {}),
|
|
73
|
+
signal,
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
if (options.signal?.aborted) {
|
|
78
|
+
return { ok: false, status: 0, code: "cancelled", text: "Cancelled." };
|
|
79
|
+
}
|
|
80
|
+
const timedOut = error instanceof Error && error.name === "TimeoutError";
|
|
81
|
+
const prefix = options.label ? `${options.label} ` : "";
|
|
82
|
+
return {
|
|
83
|
+
ok: false,
|
|
84
|
+
status: 0,
|
|
85
|
+
code: timedOut ? "timeout" : "network",
|
|
86
|
+
text: timedOut
|
|
87
|
+
? `${prefix}timed out. Try again.`
|
|
88
|
+
: friendlyThrown(error),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
if (response.ok) {
|
|
92
|
+
const data = await response.json().catch(() => undefined);
|
|
93
|
+
if (data === undefined) {
|
|
94
|
+
return {
|
|
95
|
+
ok: false,
|
|
96
|
+
status: response.status,
|
|
97
|
+
code: "invalid_response",
|
|
98
|
+
text: "free-pi sent an unexpected reply. Try again.",
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
return { ok: true, data };
|
|
102
|
+
}
|
|
103
|
+
const body = (await response.json().catch(() => ({})));
|
|
104
|
+
const code = String(body?.error?.code ?? body?.code ?? "");
|
|
105
|
+
return {
|
|
106
|
+
ok: false,
|
|
107
|
+
status: response.status,
|
|
108
|
+
code,
|
|
109
|
+
text: friendlyStatus(response.status, body?.error?.message ?? body?.message, options.audience),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/** Maps a business error code to the CLI's wording, or keeps the HTTP text. */
|
|
113
|
+
export function mappedText(table, result, library) {
|
|
114
|
+
if (result.code === "no_token")
|
|
115
|
+
return NO_TOKEN_TEXT;
|
|
116
|
+
const mapped = table[result.code];
|
|
117
|
+
if (mapped)
|
|
118
|
+
return mapped;
|
|
119
|
+
return result.text;
|
|
120
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fusion: DeepSeek Pro plans, Flash builds.
|
|
3
|
+
*
|
|
4
|
+
* The provider CLI registers a virtual "fusion" model. OpenCode gets the same
|
|
5
|
+
* shape: a `fusion` model that routes its turns to the executor model, plus a
|
|
6
|
+
* `fusion_plan` tool that asks the planner model for a plan through the
|
|
7
|
+
* stateless generate API before any edit. The executor then carries the plan
|
|
8
|
+
* out, exactly like the CLI.
|
|
9
|
+
*/
|
|
10
|
+
import type { Plugin } from "@opencode/plugin";
|
|
11
|
+
import type { Deps } from "../deps.js";
|
|
12
|
+
import type { ModelDefinition } from "../types.js";
|
|
13
|
+
export declare const FUSION_ID = "fusion";
|
|
14
|
+
export declare const FUSION_PLANNER_ID = "deepseek-v4-pro";
|
|
15
|
+
export declare const FUSION_EXECUTOR_ID = "deepseek-v4-flash";
|
|
16
|
+
export declare const FUSION_FALLBACK_PLANNER_ID = "deepseek-v4-flash";
|
|
17
|
+
export declare const FUSION_GUIDELINE = "Fusion: if the task needs any file changes, first gather the context with read-only tools (read, grep, glob) and make no edits. Then call fusion_plan with a summary of what you found and what the task needs, BEFORE any edit or write; the planning model writes the plan and you carry it out. Once the plan exists, record it with the todo tool, then carry out the unfinished items yourself (edit, write tests, run them) and finish the user's task. Only a task that needs no file changes (a plain question) is answered directly without fusion_plan.";
|
|
18
|
+
export type FusionIds = {
|
|
19
|
+
readonly planner: string;
|
|
20
|
+
readonly executor: string;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Picks the planner and executor from the live catalog, like the CLI: prefer
|
|
24
|
+
* the server-provided pair, then Pro when the account has premium credits, then
|
|
25
|
+
* Flash for both roles.
|
|
26
|
+
*/
|
|
27
|
+
export declare function resolveFusionIds(modelIDs: readonly string[], defaultModelID?: string, options?: {
|
|
28
|
+
readonly server?: {
|
|
29
|
+
planner?: string;
|
|
30
|
+
executor?: string;
|
|
31
|
+
};
|
|
32
|
+
readonly hasPremium?: boolean;
|
|
33
|
+
}): FusionIds | undefined;
|
|
34
|
+
/**
|
|
35
|
+
* The CLI asks `/me` before offering the Pro planner: without premium credits
|
|
36
|
+
* the Pro model refuses the request, so Fusion plans with Flash instead. A
|
|
37
|
+
* failed check keeps Pro, matching the CLI.
|
|
38
|
+
*/
|
|
39
|
+
export declare function premiumPlannerAvailable(deps: Deps): Promise<boolean>;
|
|
40
|
+
export declare function fusionName(ids: FusionIds): string;
|
|
41
|
+
/** Adds the virtual model next to the catalog models. */
|
|
42
|
+
export declare function addFusionModel(models: Record<string, ModelDefinition>, ids: FusionIds): string | undefined;
|
|
43
|
+
export declare function registerFusionTool(ctx: Plugin.Context, deps: Deps, ids: FusionIds): Promise<{
|
|
44
|
+
dispose: () => Promise<void>;
|
|
45
|
+
}>;
|